hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
e770921b9fe4c70049212ece9cfdbd42d8745619
203
hpp
C++
NWNXLib/API/Mac/API/ZSTD_optimal_t.hpp
Qowyn/unified
149d0b7670a9d156e64555fe0bd7715423db4c2a
[ "MIT" ]
null
null
null
NWNXLib/API/Mac/API/ZSTD_optimal_t.hpp
Qowyn/unified
149d0b7670a9d156e64555fe0bd7715423db4c2a
[ "MIT" ]
null
null
null
NWNXLib/API/Mac/API/ZSTD_optimal_t.hpp
Qowyn/unified
149d0b7670a9d156e64555fe0bd7715423db4c2a
[ "MIT" ]
null
null
null
#pragma once #include <cstdint> namespace NWNXLib { namespace API { struct ZSTD_optimal_t { int32_t price; uint32_t off; uint32_t mlen; uint32_t litlen; uint32_t rep[3]; }; } }
9.666667
21
0.655172
Qowyn
e7718931c7603c0a13a9f82cce8c46501ba41d49
2,006
hpp
C++
modules/wechat_qrcode/src/zxing/qrcode/decoder/qrcode_decoder_metadata.hpp
ptelang/opencv_contrib
dd68e396c76f1db4d82e5aa7a6545580939f9b9d
[ "Apache-2.0" ]
7,158
2016-07-04T22:19:27.000Z
2022-03-31T07:54:32.000Z
modules/wechat_qrcode/src/zxing/qrcode/decoder/qrcode_decoder_metadata.hpp
ptelang/opencv_contrib
dd68e396c76f1db4d82e5aa7a6545580939f9b9d
[ "Apache-2.0" ]
2,184
2016-07-05T12:04:14.000Z
2022-03-30T19:10:12.000Z
modules/wechat_qrcode/src/zxing/qrcode/decoder/qrcode_decoder_metadata.hpp
ptelang/opencv_contrib
dd68e396c76f1db4d82e5aa7a6545580939f9b9d
[ "Apache-2.0" ]
5,535
2016-07-06T12:01:10.000Z
2022-03-31T03:13:24.000Z
// 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. // // Tencent is pleased to support the open source community by making WeChat QRCode available. // Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. // // Modified from ZXing. Copyright ZXing authors. // Licensed under the Apache License, Version 2.0 (the "License"). #ifndef __ZXING_QRCODE_DECODER_QRCODEDECODERMETADATA_HPP__ #define __ZXING_QRCODE_DECODER_QRCODEDECODERMETADATA_HPP__ #include "../../common/array.hpp" #include "../../common/counted.hpp" #include "../../resultpoint.hpp" // VC++ // The main class which implements QR Code decoding -- as opposed to locating // and extracting the QR Code from an image. namespace zxing { namespace qrcode { /** * Meta-data container for QR Code decoding. Instances of this class may be used * to convey information back to the decoding caller. Callers are expected to * process this. * * @see com.google.zxing.common.DecoderResult#getOther() */ class QRCodeDecoderMetaData : public Counted { private: bool mirrored_; public: explicit QRCodeDecoderMetaData(bool mirrored) : mirrored_(mirrored) {} public: /** * @return true if the QR Code was mirrored. */ bool isMirrored() { return mirrored_; }; /** * Apply the result points' order correction due to mirroring. * * @param points Array of points to apply mirror correction to. */ void applyMirroredCorrection(ArrayRef<Ref<ResultPoint> >& points) { if (!mirrored_ || points->size() < 3) { return; } Ref<ResultPoint> bottomLeft = points[0]; points[0] = points[2]; points[2] = bottomLeft; // No need to 'fix' top-left and alignment pattern. }; }; } // namespace qrcode } // namespace zxing #endif // __ZXING_QRCODE_DECODER_QRCODEDECODERMETADATA_HPP__
30.861538
93
0.699402
ptelang
e7734fb36b4dc0a8e8a6182b63aceab7658aa031
210
cpp
C++
src/Gui.cpp
gw2-addon-loader/example_addon
fe363ac31f174ca87ff1f93c74107c95d95f2acf
[ "MIT" ]
2
2020-08-17T17:33:23.000Z
2021-02-23T01:35:28.000Z
src/Gui.cpp
gw2-addon-loader/example_addon
fe363ac31f174ca87ff1f93c74107c95d95f2acf
[ "MIT" ]
null
null
null
src/Gui.cpp
gw2-addon-loader/example_addon
fe363ac31f174ca87ff1f93c74107c95d95f2acf
[ "MIT" ]
1
2021-02-07T06:59:45.000Z
2021-02-07T06:59:45.000Z
#include "stdafx.h" void Gui::init() { //CHANGE ME } void Gui::draw() { //CHANGE ME ImGui::Begin("Hello world window"); ImGui::Text("Hello world!"); ImGui::End(); } void Gui::deinit() { //CHANGE ME }
10
36
0.6
gw2-addon-loader
e7775fc9db1eb0678b2ef081eae1001f916bcfd7
2,712
cpp
C++
web/user-guide/misc/empty.cpp
Alexis-ROYER/CLI
dc4d77aa0ad41c2de989b708d6aea931d1194070
[ "BSD-3-Clause" ]
null
null
null
web/user-guide/misc/empty.cpp
Alexis-ROYER/CLI
dc4d77aa0ad41c2de989b708d6aea931d1194070
[ "BSD-3-Clause" ]
null
null
null
web/user-guide/misc/empty.cpp
Alexis-ROYER/CLI
dc4d77aa0ad41c2de989b708d6aea931d1194070
[ "BSD-3-Clause" ]
null
null
null
//! @file //! @author cli2cpp.py - CLI library 2.9 (Alexis Royer, http://alexis.royer.free.fr/CLI/) //! @date 2018-03-14T19:03:42.485341 //! @warning File auto-generated by 'cli2cpp.py' - Do not edit! // ----- Pre-compiled headers ----- #include "cli/pch.h" // ----- Extra cpp (option='head') ----- // ----- Includes ----- #include "cli/common.h" // ----- Extra cpp (option='include') ----- // ----- Extra cpp (option='types') ----- // ----- Extra cpp (option='vars') ----- // ----- Cli class definition ----- class myCLI : public cli::Cli { // ----- Sub-menus ----- // ----- Owner CLI ----- private: myCLI* m_pcliOwnerCli; // ----- Menus ----- private: myCLI* m_pcli_cli_a; // ----- Node members ----- // ----- Extra cpp (option='members') ----- // ----- Constructor ----- public: explicit myCLI(void) : cli::Cli("myCLI", cli::Help()) { Populate(); // ----- Extra cpp (option='constructor') ----- } // ----- Destructor ----- public: virtual ~myCLI(void) { } // ----- Populate ----- public: void Populate(void) { // CLI reference m_pcliOwnerCli = dynamic_cast<myCLI*>(const_cast<cli::Cli*>(& GetCli())); // Comment line patterns // Create menus and populate m_pcliOwnerCli->m_pcli_cli_a = this; // Local nodes // tag[@ref] -> tag[@id] connections } // ----- Menu execution ----- public: virtual const bool Execute(const cli::CommandLine& CLI_CmdLine) const { { static const cli::TraceClass CLI_EXECUTION("CLI_EXECUTION", cli::Help().AddHelp(cli::Help::LANG_EN, "CLI Execution traces").AddHelp(cli::Help::LANG_FR, "Traces d'exécution du CLI")); cli::CommandLineIterator cli_Elements(CLI_CmdLine); // myCLI> m_pcli_cli_a_top_lbl: ; { if (! cli_Elements.StepIt()) return false; cli::GetTraces().Trace(CLI_EXECUTION) << "context = \"myCLI>\", " << "word = " << (dynamic_cast<const cli::Endl*>(*cli_Elements) ? "<CR>" : (const char*) (*cli_Elements)->GetKeyword()) << cli::endl; return false; } m_pcli_cli_a_end_lbl: ; } return false; } public: virtual const bool OnError(const cli::ResourceString& location, const cli::ResourceString& message) const { return Cli::OnError(location, message); } public: virtual void OnExit(void) const { } public: virtual const cli::tk::String OnPrompt(void) const { return Menu::OnPrompt(); } }; // ----- Node creation ----- // ----- Extra cpp (option='body') ----- // ----- Extra cpp (option='tail') -----
30.133333
214
0.54351
Alexis-ROYER
e777a9a9d46289b7b4de9f733218cf8a52f545bb
3,355
cc
C++
xpp_vis/src/cartesian_joint_converter.cc
innorobotics/xpp
5527b2820247c712dba622872a15f0242c2c60ed
[ "BSD-3-Clause" ]
243
2017-11-08T17:10:59.000Z
2022-03-29T12:56:51.000Z
xpp_vis/src/cartesian_joint_converter.cc
innorobotics/xpp
5527b2820247c712dba622872a15f0242c2c60ed
[ "BSD-3-Clause" ]
13
2017-12-22T13:13:53.000Z
2021-06-05T12:24:50.000Z
xpp_vis/src/cartesian_joint_converter.cc
innorobotics/xpp
5527b2820247c712dba622872a15f0242c2c60ed
[ "BSD-3-Clause" ]
91
2017-10-27T23:27:24.000Z
2022-02-02T07:38:09.000Z
/****************************************************************************** Copyright (c) 2017, Alexander W. Winkler. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ #include <xpp_vis/cartesian_joint_converter.h> #include <ros/node_handle.h> #include <xpp_msgs/RobotStateJoint.h> #include <xpp_states/convert.h> namespace xpp { CartesianJointConverter::CartesianJointConverter (const InverseKinematics::Ptr& ik, const std::string& cart_topic, const std::string& joint_topic) { inverse_kinematics_ = ik; ::ros::NodeHandle n; cart_state_sub_ = n.subscribe(cart_topic, 1, &CartesianJointConverter::StateCallback, this); ROS_DEBUG("Subscribed to: %s", cart_state_sub_.getTopic().c_str()); joint_state_pub_ = n.advertise<xpp_msgs::RobotStateJoint>(joint_topic, 1); ROS_DEBUG("Publishing to: %s", joint_state_pub_.getTopic().c_str()); } void CartesianJointConverter::StateCallback (const xpp_msgs::RobotStateCartesian& cart_msg) { auto cart = Convert::ToXpp(cart_msg); // transform feet from world -> base frame Eigen::Matrix3d B_R_W = cart.base_.ang.q.normalized().toRotationMatrix().inverse(); EndeffectorsPos ee_B(cart.ee_motion_.GetEECount()); for (auto ee : ee_B.GetEEsOrdered()) ee_B.at(ee) = B_R_W * (cart.ee_motion_.at(ee).p_ - cart.base_.lin.p_); Eigen::VectorXd q = inverse_kinematics_->GetAllJointAngles(ee_B).ToVec(); xpp_msgs::RobotStateJoint joint_msg; joint_msg.base = cart_msg.base; joint_msg.ee_contact = cart_msg.ee_contact; joint_msg.time_from_start = cart_msg.time_from_start; joint_msg.joint_state.position = std::vector<double>(q.data(), q.data()+q.size()); // Attention: Not filling joint velocities or torques joint_state_pub_.publish(joint_msg); } } /* namespace xpp */
43.571429
94
0.716542
innorobotics
e77a18b8dec6bc29bf8852e6ccd3dc02905ad0eb
2,977
cpp
C++
OfficeAutomation/OfficeDoc.cpp
anboto/Anboto
fc40730e87b85bba4d9387724fcece7e98069843
[ "Apache-2.0" ]
8
2021-02-28T12:07:43.000Z
2021-11-14T19:40:45.000Z
OfficeAutomation/OfficeDoc.cpp
anboto/Anboto
fc40730e87b85bba4d9387724fcece7e98069843
[ "Apache-2.0" ]
8
2021-03-20T10:46:58.000Z
2022-01-27T19:50:32.000Z
OfficeAutomation/OfficeDoc.cpp
anboto/Anboto
fc40730e87b85bba4d9387724fcece7e98069843
[ "Apache-2.0" ]
1
2021-08-20T09:15:18.000Z
2021-08-20T09:15:18.000Z
// SPDX-License-Identifier: Apache-2.0 // Copyright 2021 - 2021, the Anboto author and contributors #ifdef _WIN32 #include <Core/Core.h> using namespace Upp; #include <Functions4U/Functions4U.h> #include "OfficeAutomation.h" #include "OfficeAutomationBase.h" OfficeDoc::OfficeDoc() { Ole::Init(); } OfficeDoc::~OfficeDoc() { Ole::Close(); } bool OfficeDoc::Init(const char *name) { return PluginInit(*this, name); } bool DocPlugin::IsAvailable() {return false;} bool OfficeDoc::IsAvailable(const char *_name) { for (int i = 0; i < Plugins().GetCount(); ++i) { if (Plugins()[i].name == _name && Plugins()[i].type == typeid(OfficeDoc).name()) { void *dat = Plugins()[i].New(); if (!dat) return false; bool ret = (static_cast<DocPlugin *>(dat))->IsAvailable(); Plugins()[i].Delete(dat); return ret; } } return false; } bool DocPlugin::AddDoc(bool visible) {return false;} bool OfficeDoc::AddDoc(bool visible) {return (static_cast<DocPlugin *>(GetData()))->AddDoc(visible);} bool DocPlugin::OpenDoc(String fileName, bool visible) {return false;} bool OfficeDoc::OpenDoc(String fileName, bool visible) {return (static_cast<DocPlugin *>(GetData()))->OpenDoc(fileName, visible);} bool DocPlugin::SetFont(String font, int size) {return false;} bool OfficeDoc::SetFont(String font, int size) {return (static_cast<DocPlugin *>(GetData()))->SetFont(font, size);} bool DocPlugin::SetBold(bool bold) {return false;} bool OfficeDoc::SetBold(bool bold) {return (static_cast<DocPlugin *>(GetData()))->SetBold(bold);} bool DocPlugin::SetItalic(bool italic) {return false;} bool OfficeDoc::SetItalic(bool italic) {return (static_cast<DocPlugin *>(GetData()))->SetItalic(italic);} bool DocPlugin::WriteText(String value) {return false;} bool OfficeDoc::WriteText(String value) {return (static_cast<DocPlugin *>(GetData()))->WriteText(value);} bool DocPlugin::Select() {return false;} bool OfficeDoc::Select() {return (static_cast<DocPlugin *>(GetData()))->Select();} bool DocPlugin::EnableCommandVars(bool) {return false;} bool OfficeDoc::EnableCommandVars(bool enable) {return (static_cast<DocPlugin *>(GetData()))->EnableCommandVars(enable);} bool DocPlugin::Replace(String search, String replace) {return false;} bool OfficeDoc::Replace(String search, String replace) {return (static_cast<DocPlugin *>(GetData()))->Replace(search, replace);} bool DocPlugin::Print() {return false;} bool OfficeDoc::Print() {return (static_cast<DocPlugin *>(GetData()))->Print();} bool DocPlugin::SaveAs(String fileName, String _type) {return false;} bool OfficeDoc::SaveAs(String fileName, String _type) {return (static_cast<DocPlugin *>(GetData()))->SaveAs(fileName, _type);} bool DocPlugin::Quit() {return false;} bool OfficeDoc::Quit() {return (static_cast<DocPlugin *>(GetData()))->Quit();} bool DocPlugin::SetSaved(bool saved) {return false;} bool OfficeDoc::SetSaved(bool saved) {return (static_cast<DocPlugin *>(GetData()))->SetSaved(saved);} #endif
36.753086
130
0.723547
anboto
e77b6c641e1196c6e5cd28895c4ca892374e57b5
4,641
cc
C++
device/bluetooth/test/fake_radio_winrt.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
device/bluetooth/test/fake_radio_winrt.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
device/bluetooth/test/fake_radio_winrt.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "device/bluetooth/test/fake_radio_winrt.h" #include <utility> #include "base/bind.h" #include "base/test/bind_test_util.h" #include "base/threading/thread_task_runner_handle.h" #include "base/win/async_operation.h" namespace device { namespace { using ABI::Windows::Devices::Radios::Radio; using ABI::Windows::Devices::Radios::RadioAccessStatus; using ABI::Windows::Devices::Radios::RadioAccessStatus_Allowed; using ABI::Windows::Devices::Radios::RadioAccessStatus_DeniedBySystem; using ABI::Windows::Devices::Radios::RadioKind; using ABI::Windows::Devices::Radios::RadioState; using ABI::Windows::Devices::Radios::RadioState_Off; using ABI::Windows::Devices::Radios::RadioState_On; using ABI::Windows::Foundation::Collections::IVectorView; using ABI::Windows::Foundation::IAsyncOperation; using ABI::Windows::Foundation::ITypedEventHandler; using Microsoft::WRL::Make; } // namespace FakeRadioWinrt::FakeRadioWinrt() = default; FakeRadioWinrt::~FakeRadioWinrt() = default; HRESULT FakeRadioWinrt::SetStateAsync( RadioState value, IAsyncOperation<RadioAccessStatus>** operation) { auto async_op = Make<base::win::AsyncOperation<RadioAccessStatus>>(); set_state_callback_ = async_op->callback(); // Schedule a callback that will run |set_state_callback_| with Status_Allowed // and invokes |state_changed_handler_| if |value| is different from |state_|. // Capturing |this| as safe here, as the callback won't be run if // |cancelable_closure_| gets destroyed first. cancelable_closure_.Reset(base::BindLambdaForTesting([this, value] { std::move(set_state_callback_).Run(RadioAccessStatus_Allowed); if (std::exchange(state_, value) != value) state_changed_handler_->Invoke(this, nullptr); })); base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, cancelable_closure_.callback()); *operation = async_op.Detach(); return S_OK; } HRESULT FakeRadioWinrt::add_StateChanged( ITypedEventHandler<Radio*, IInspectable*>* handler, EventRegistrationToken* event_cookie) { state_changed_handler_ = handler; return S_OK; } HRESULT FakeRadioWinrt::remove_StateChanged( EventRegistrationToken event_cookie) { state_changed_handler_.Reset(); return S_OK; } HRESULT FakeRadioWinrt::get_State(RadioState* value) { *value = state_; return S_OK; } HRESULT FakeRadioWinrt::get_Name(HSTRING* value) { return E_NOTIMPL; } HRESULT FakeRadioWinrt::get_Kind(RadioKind* value) { return E_NOTIMPL; } void FakeRadioWinrt::SimulateAdapterPowerFailure() { DCHECK(set_state_callback_); // Cancel the task scheduled in SetStateAsync() and run the stored callback // with an error code. cancelable_closure_.Reset(base::BindOnce(std::move(set_state_callback_), RadioAccessStatus_DeniedBySystem)); base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, cancelable_closure_.callback()); } void FakeRadioWinrt::SimulateAdapterPoweredOn() { state_ = RadioState_On; DCHECK(state_changed_handler_); state_changed_handler_->Invoke(this, nullptr); } void FakeRadioWinrt::SimulateAdapterPoweredOff() { state_ = RadioState_Off; DCHECK(state_changed_handler_); state_changed_handler_->Invoke(this, nullptr); } void FakeRadioWinrt::SimulateSpuriousStateChangedEvent() { state_changed_handler_->Invoke(this, nullptr); } FakeRadioStaticsWinrt::FakeRadioStaticsWinrt() = default; FakeRadioStaticsWinrt::~FakeRadioStaticsWinrt() = default; HRESULT FakeRadioStaticsWinrt::GetRadiosAsync( IAsyncOperation<IVectorView<Radio*>*>** value) { return E_NOTIMPL; } HRESULT FakeRadioStaticsWinrt::GetDeviceSelector(HSTRING* device_selector) { return E_NOTIMPL; } HRESULT FakeRadioStaticsWinrt::FromIdAsync(HSTRING device_id, IAsyncOperation<Radio*>** value) { return E_NOTIMPL; } void FakeRadioStaticsWinrt::SimulateRequestAccessAsyncError( ABI::Windows::Devices::Radios::RadioAccessStatus status) { access_status_ = status; } HRESULT FakeRadioStaticsWinrt::RequestAccessAsync( IAsyncOperation<RadioAccessStatus>** operation) { auto async_op = Make<base::win::AsyncOperation<RadioAccessStatus>>(); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(async_op->callback(), access_status_)); *operation = async_op.Detach(); return S_OK; } } // namespace device
32.229167
80
0.743374
sarang-apps
e77c084654c918417dd4ed9fcde9b95cc2e98347
1,203
hpp
C++
framework/Shape.hpp
Snoopyxxel/programmiersprachen-raytracer
243765de0e5814cb20930046f6fc14a9faf87e49
[ "MIT" ]
null
null
null
framework/Shape.hpp
Snoopyxxel/programmiersprachen-raytracer
243765de0e5814cb20930046f6fc14a9faf87e49
[ "MIT" ]
null
null
null
framework/Shape.hpp
Snoopyxxel/programmiersprachen-raytracer
243765de0e5814cb20930046f6fc14a9faf87e49
[ "MIT" ]
null
null
null
#ifndef RAYTRACER_SHAPE_HPP #define RAYTRACER_SHAPE_HPP #include <string> #include <ostream> #include "color.hpp" #include "ray.hpp" #include "hitpoint.hpp" #include <glm/vec3.hpp> #include <glm/glm.hpp> #include <memory> class Shape { public: Shape(); Shape(std::string const &name, std::shared_ptr<Material> const& material); virtual float area() const = 0; virtual float volume() const = 0; friend std::ostream &operator<<(std::ostream &os, const Shape &shape); virtual HitPoint intersect(Ray const& ray) const = 0; virtual std::ostream& print(std::ostream &os = std::cout) const; virtual glm::vec3 normal(glm::vec3 const& p) const = 0; //point has to be on the object! void scale(float x,float y,float z); void translate(float x,float y,float z); void rotate(float angle,float x,float y,float z); const glm::mat4 &getWorldTransformation() const; const glm::mat4 &getWorldTransformationInv() const; std::string get_name() const; protected: std::string name_; std::shared_ptr<Material> material_; glm::mat4 world_transformation_; glm::mat4 world_transformation_inv_; }; #endif //RAYTRACER_SHAPE_HPP
22.277778
94
0.689111
Snoopyxxel
e7810d645c6cbc876b3f012a557bf0e88dd801a4
570
cpp
C++
src/Hardware.cpp
pigatron-industries/xen_algorhythm
3b4cd0fcbffeb36c52e9f1b7530bb1be52811101
[ "Unlicense" ]
2
2021-04-06T21:23:06.000Z
2021-11-07T09:52:00.000Z
src/Hardware.cpp
pigatron-industries/xen_algorhythm
3b4cd0fcbffeb36c52e9f1b7530bb1be52811101
[ "Unlicense" ]
null
null
null
src/Hardware.cpp
pigatron-industries/xen_algorhythm
3b4cd0fcbffeb36c52e9f1b7530bb1be52811101
[ "Unlicense" ]
null
null
null
#include "Hardware.h" Hardware Hardware::hw = Hardware(); void Hardware::init() { for(int i = 0; i < GATE_OUTPUTS; i++) { gateOutputs[i]->init(); } for(int i = 0; i < GATE_OUTPUTS; i++) { gateOutputs[i]->digitalWrite(false); } mcp23s17Device.gpioPortUpdate(); // TODO move to send() function } void Hardware::updateOutputs() { #if defined(ALGORHYTHM_MKII) mcp23s17Device.gpioPortUpdate(); // TODO move to send() function #endif #if defined(ALGORHYTHM_MKI) Hardware::hw.hc595Device.send(); #endif }
23.75
72
0.621053
pigatron-industries
e782f9f1e521157b6ee1fde87099d877ac318ba0
2,433
cpp
C++
src/fileinfo/file_information/file_information_types/relocation_table/relocation.cpp
lukasdurfina/retdec
7d6b8882690ff73c2bd7f209db10c5c091fa0359
[ "MIT", "Zlib", "BSD-3-Clause" ]
1
2020-03-28T02:38:53.000Z
2020-03-28T02:38:53.000Z
src/fileinfo/file_information/file_information_types/relocation_table/relocation.cpp
lukasdurfina/retdec
7d6b8882690ff73c2bd7f209db10c5c091fa0359
[ "MIT", "Zlib", "BSD-3-Clause" ]
null
null
null
src/fileinfo/file_information/file_information_types/relocation_table/relocation.cpp
lukasdurfina/retdec
7d6b8882690ff73c2bd7f209db10c5c091fa0359
[ "MIT", "Zlib", "BSD-3-Clause" ]
null
null
null
/** * @file src/fileinfo/file_information/file_information_types/relocation_table/relocation.cpp * @brief Class for one relocation. * @copyright (c) 2017 Avast Software, licensed under the MIT license */ #include "fileinfo/file_information/file_information_types/relocation_table/relocation.h" #include "fileinfo/file_information/file_information_types/type_conversions.h" namespace fileinfo { /** * Get name of associated symbol * @return Name of associated symbol */ std::string Relocation::getSymbolName() const { return symbolName; } /** * Get relocation offset * @param format Format of result (e.g. std::dec, std::hex) * @return Relocation offset */ std::string Relocation::getOffsetStr(std::ios_base &(* format)(std::ios_base &)) const { return getNumberAsString(offset, format); } /** * Get value of associated symbol * @return Value of associated symbol */ std::string Relocation::getSymbolValueStr() const { return getNumberAsString(symbolValue); } /** * Get relocation type * @return Type of relocation */ std::string Relocation::getRelocationTypeStr() const { return getNumberAsString(relocationType); } /** * Get relocation addend * @return Relocation addend */ std::string Relocation::getAddendStr() const { return getNumberAsString(addend); } /** * Get calculated value * @return Calculated value */ std::string Relocation::getCalculatedValueStr() const { return getNumberAsString(calculatedValue); } /** * Set name of associated symbol * @param name Name of symbol associated with relocation */ void Relocation::setSymbolName(std::string name) { symbolName = name; } /** * Set relocation offset * @param value Relocation offset */ void Relocation::setOffset(unsigned long long value) { offset = value; } /** * Set value of symbol associated with relocation * @param value Value of symbol associated with relocation */ void Relocation::setSymbolValue(unsigned long long value) { symbolValue = value; } /** * Set type of relocation * @param type Type of relocation */ void Relocation::setRelocationType(unsigned long long type) { relocationType = type; } /** * Set relocation addend * @param value Relocation addend */ void Relocation::setAddend(long long value) { addend = value; } /** * Set calculated value * @param value Calculated value */ void Relocation::setCalculatedValue(long long value) { calculatedValue = value; } } // namespace fileinfo
19.942623
93
0.738594
lukasdurfina
e787c3be6020b2f1bf44daf0bdeec433ebfce663
497
cpp
C++
Answer/ans_code_and_note/chapter3/test.cpp
seanleecn/EssentialCPP
a2cfbd054888a3d07cb0ac22230c34f6ce90bef5
[ "MIT" ]
null
null
null
Answer/ans_code_and_note/chapter3/test.cpp
seanleecn/EssentialCPP
a2cfbd054888a3d07cb0ac22230c34f6ce90bef5
[ "MIT" ]
null
null
null
Answer/ans_code_and_note/chapter3/test.cpp
seanleecn/EssentialCPP
a2cfbd054888a3d07cb0ac22230c34f6ce90bef5
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <vector> #include <string> using namespace std; bool myfunction(string i, string j) { return (i.length() < j.length()); } int main(void) { string myints[] = {"hello", "world", "i", "love"}; vector<string> myvec(myints, myints + 4); sort(myvec.begin(), myvec.end(), myfunction); for (vector<string>::iterator it = myvec.begin(); it != myvec.end(); ++it) { cout << ' ' << *it; } cout << endl; return 0; }
19.88
80
0.583501
seanleecn
e7886ae5992f5605081d2afb9617876cb583ffcf
50,956
cpp
C++
OgreMain/src/OgreHlmsTextureManager.cpp
osrf/ogre-2.1
936179ce97c755d357222a5642f38c70bd0a142b
[ "MIT" ]
4
2018-11-12T02:18:44.000Z
2020-09-03T12:16:14.000Z
OgreMain/src/OgreHlmsTextureManager.cpp
osrf/ogre-2.1
936179ce97c755d357222a5642f38c70bd0a142b
[ "MIT" ]
2
2020-12-01T18:20:39.000Z
2021-02-09T21:04:25.000Z
OgreMain/src/OgreHlmsTextureManager.cpp
osrf/ogre-2.1
936179ce97c755d357222a5642f38c70bd0a142b
[ "MIT" ]
3
2020-10-15T15:11:41.000Z
2021-04-04T03:38:54.000Z
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreStableHeaders.h" #include "OgreHlmsTextureManager.h" #include "OgreHlmsTexturePack.h" #include "OgreTextureManager.h" #include "OgreHardwarePixelBuffer.h" #include "OgreRenderSystem.h" #include "OgreBitwise.h" #include "OgreLogManager.h" namespace Ogre { HlmsTextureManager::HlmsTextureManager() : mRenderSystem( 0 ), mTextureId( 0 ) { mDefaultTextureParameters[TEXTURE_TYPE_DIFFUSE].hwGammaCorrection = true; mDefaultTextureParameters[TEXTURE_TYPE_MONOCHROME].pixelFormat = PF_L8; mDefaultTextureParameters[TEXTURE_TYPE_NORMALS].pixelFormat = PF_BC5_SNORM; mDefaultTextureParameters[TEXTURE_TYPE_NORMALS].isNormalMap = true; mDefaultTextureParameters[TEXTURE_TYPE_DETAIL].hwGammaCorrection = true; mDefaultTextureParameters[TEXTURE_TYPE_DETAIL_NORMAL_MAP].pixelFormat=PF_BC5_SNORM; mDefaultTextureParameters[TEXTURE_TYPE_DETAIL_NORMAL_MAP].isNormalMap = true; mDefaultTextureParameters[TEXTURE_TYPE_ENV_MAP].hwGammaCorrection = true; mDefaultTextureParameters[TEXTURE_TYPE_NON_COLOR_DATA].hwGammaCorrection = false; } //----------------------------------------------------------------------------------- HlmsTextureManager::~HlmsTextureManager() { } //----------------------------------------------------------------------------------- void HlmsTextureManager::_changeRenderSystem( RenderSystem *newRs ) { mRenderSystem = newRs; if( mRenderSystem ) { const RenderSystemCapabilities *caps = mRenderSystem->getCapabilities(); if( caps ) { TextureType textureType = TEX_TYPE_2D; if( caps->hasCapability(RSC_TEXTURE_2D_ARRAY) ) //TODO { textureType = TEX_TYPE_2D_ARRAY; for( size_t i=0; i<NUM_TEXTURE_TYPES; ++i ) { mDefaultTextureParameters[i].packingMethod = TextureArrays; mDefaultTextureParameters[i].maxTexturesPerArray = 40; } mDefaultTextureParameters[TEXTURE_TYPE_ENV_MAP].maxTexturesPerArray = 20; if( !caps->hasCapability(RSC_TEXTURE_CUBE_MAP_ARRAY) ) mDefaultTextureParameters[TEXTURE_TYPE_ENV_MAP].maxTexturesPerArray = 1; } else { for( size_t i=0; i<NUM_TEXTURE_TYPES; ++i ) { mDefaultTextureParameters[i].packingMethod = Atlas; mDefaultTextureParameters[i].maxTexturesPerArray = 1; } mDefaultTextureParameters[TEXTURE_TYPE_ENV_MAP].maxTexturesPerArray = 1; mDefaultTextureParameters[TEXTURE_TYPE_DETAIL].maxTexturesPerArray = 1; mDefaultTextureParameters[TEXTURE_TYPE_DETAIL_NORMAL_MAP].maxTexturesPerArray = 1; } bool hwGammaCorrection = caps->hasCapability( RSC_HW_GAMMA ); mDefaultTextureParameters[TEXTURE_TYPE_DIFFUSE].hwGammaCorrection = hwGammaCorrection; mDefaultTextureParameters[TEXTURE_TYPE_DETAIL].hwGammaCorrection = hwGammaCorrection; // BC5 is the best, native (lossy) compressor for normal maps. // DXT5 is like BC5, using the "store only in green and alpha channels" method. // The last one is lossless, using UV8 to store uncompressed, // and retrieve z = sqrt(x²+y²) if( caps->hasCapability(RSC_TEXTURE_COMPRESSION_BC4_BC5) ) { mDefaultTextureParameters[TEXTURE_TYPE_NORMALS].pixelFormat = PF_BC5_SNORM; mDefaultTextureParameters[TEXTURE_TYPE_DETAIL_NORMAL_MAP].pixelFormat = PF_BC5_SNORM; } /*else if( caps->hasCapability(RSC_TEXTURE_COMPRESSION_DXT) ) { mDefaultTextureParameters[TEXTURE_TYPE_NORMALS].pixelFormat = PF_DXT5; mDefaultTextureParameters[TEXTURE_TYPE_DETAIL_NORMAL_MAP].pixelFormat = PF_DXT5; }*/ else { PixelFormat pf = caps->hasCapability( RSC_TEXTURE_SIGNED_INT ) ? PF_R8G8_SNORM : PF_BYTE_LA; mDefaultTextureParameters[TEXTURE_TYPE_NORMALS].pixelFormat = pf; mDefaultTextureParameters[TEXTURE_TYPE_DETAIL_NORMAL_MAP].pixelFormat = pf; } mBlankTexture = TextureManager::getSingleton().createManual( "Hlms_Blanktexture", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, textureType, 4, 4, 1, 0, PF_R8G8B8A8, TU_DEFAULT, 0, false, 0, BLANKSTRING, false ); v1::HardwarePixelBufferSharedPtr pixelBufferBuf = mBlankTexture->getBuffer(0); const PixelBox &currImage = pixelBufferBuf->lock( Box( 0, 0, 0, 4, 4, 1 ), v1::HardwareBuffer::HBL_DISCARD ); uint8 *data = reinterpret_cast<uint8*>( currImage.data ); for( size_t y=0; y<currImage.getHeight(); ++y ) { for( size_t x=0; x<currImage.getWidth(); ++x ) { *data++ = 255; *data++ = 255; *data++ = 255; *data++ = 255; } data += ( currImage.rowPitch - currImage.getWidth() ) * 4; } pixelBufferBuf->unlock(); } } } //----------------------------------------------------------------------------------- void HlmsTextureManager::copyTextureToArray( const Image &srcImage, TexturePtr dst, uint16 entryIdx, uint8 srcBaseMip, bool isNormalMap ) { //TODO: Deal with mipmaps (& cubemaps & 3D? does it work?). We could have: // * Original image has mipmaps, we use them all // * Original image has mipmaps, we discard them // * Original image has mipmaps, we use them, but we need to create more // * Original image doesn't have mipmaps, but we need to create them // The last problem is a subset of the 3rd problem // // See Texture::_loadImages uint8 minMipmaps = std::min<uint8>( srcImage.getNumMipmaps() - srcBaseMip, dst->getNumMipmaps() ) + 1; for( uint8 j=0; j<minMipmaps; ++j ) { v1::HardwarePixelBufferSharedPtr pixelBufferBuf = dst->getBuffer(0, j); const PixelBox &currImage = pixelBufferBuf->lock( Box( 0, 0, entryIdx, pixelBufferBuf->getWidth(), pixelBufferBuf->getHeight(), entryIdx + 1 ), v1::HardwareBuffer::HBL_DISCARD ); if( isNormalMap && srcImage.getFormat() != dst->getFormat() ) PixelUtil::convertForNormalMapping( srcImage.getPixelBox(0, j + srcBaseMip), currImage ); else PixelUtil::bulkPixelConversion( srcImage.getPixelBox(0, j + srcBaseMip), currImage ); pixelBufferBuf->unlock(); } } //----------------------------------------------------------------------------------- void HlmsTextureManager::copyTextureToAtlas( const Image &srcImage, TexturePtr dst, uint16 entryIdx, uint16 sqrtMaxTextures, uint8 srcBaseMip, bool isNormalMap ) { //TODO: Deal with mipmaps (& cubemaps & 3D? does it work?). size_t xBlock = entryIdx % sqrtMaxTextures; size_t yBlock = entryIdx / sqrtMaxTextures; size_t nextX = ( entryIdx % sqrtMaxTextures ) + 1; size_t nextY = ( entryIdx / sqrtMaxTextures ) + 1; /*if( sqrtMaxTextures > 1 && PixelUtil::isCompressed( dst->getFormat() ) ) { HardwarePixelBufferSharedPtr pixelBufferBuf = dst->getBuffer(0); const PixelBox &currImage = pixelBufferBuf->lock( Box( 0, 0, 0, dst->getWidth(), dst->getHeight(), dst->getDepth() ), HardwareBuffer::HBL_DISCARD ); //HardwareBuffer::HBL_NORMAL ); PixelUtil::bulkCompressedSubregion( srcImage.getPixelBox(0, srcBaseMip), currImage, Box( xBlock * srcImage.getWidth(), yBlock * srcImage.getHeight(), 0, nextX * srcImage.getWidth(), nextY * srcImage.getHeight(), dst->getDepth() ) ); pixelBufferBuf->unlock(); } else*/ uint8 minMipmaps = std::min<uint8>( srcImage.getNumMipmaps() - srcBaseMip, dst->getNumMipmaps() ) + 1; for( uint8 j=0; j<minMipmaps; ++j ) { v1::HardwarePixelBufferSharedPtr pixelBufferBuf = dst->getBuffer(0, j); const PixelBox &currImage = pixelBufferBuf->lock( Box( xBlock * pixelBufferBuf->getWidth(), yBlock * pixelBufferBuf->getHeight(), 0, nextX * pixelBufferBuf->getWidth(), nextY * pixelBufferBuf->getHeight(), dst->getDepth() ), v1::HardwareBuffer::HBL_DISCARD ); if( isNormalMap && srcImage.getFormat() != dst->getFormat() ) PixelUtil::convertForNormalMapping( srcImage.getPixelBox(0, j + srcBaseMip), currImage ); else PixelUtil::bulkPixelConversion( srcImage.getPixelBox(0, j + srcBaseMip), currImage ); pixelBufferBuf->unlock(); } } //----------------------------------------------------------------------------------- void HlmsTextureManager::copy3DTexture( const Image &srcImage, TexturePtr dst, uint16 sliceStart, uint16 sliceEnd, uint8 srcBaseMip ) { for( uint16 i=sliceStart; i<sliceEnd; ++i ) { uint8 minMipmaps = std::min<uint8>( srcImage.getNumMipmaps() - srcBaseMip, dst->getNumMipmaps() ) + 1; for( uint8 j=0; j<minMipmaps; ++j ) { v1::HardwarePixelBufferSharedPtr pixelBufferBuf = dst->getBuffer( i, j ); const PixelBox &currImage = pixelBufferBuf->lock( Box( 0, 0, 0, pixelBufferBuf->getWidth(), pixelBufferBuf->getHeight(), 1 ), v1::HardwareBuffer::HBL_DISCARD ); PixelUtil::bulkPixelConversion( srcImage.getPixelBox( i - sliceStart, srcBaseMip + j ), currImage ); pixelBufferBuf->unlock(); } } } //----------------------------------------------------------------------------------- HlmsTextureManager::TextureArrayVec::iterator HlmsTextureManager::findSuitableArray( TextureMapType mapType, uint32 width, uint32 height, uint32 depth, uint32 faces, PixelFormat format, uint8 numMipmaps ) { TextureArrayVec::iterator retVal = mTextureArrays[mapType].end(); //Find an array where we can put it. If there is none, we'll have have to create a new one TextureArrayVec::iterator itor = mTextureArrays[mapType].begin(); TextureArrayVec::iterator end = mTextureArrays[mapType].end(); while( itor != end && retVal == end ) { TextureArray &textureArray = *itor; uint32 arrayTexWidth = textureArray.texture->getWidth() / textureArray.sqrtMaxTextures; uint32 arrayTexHeight= textureArray.texture->getHeight() / textureArray.sqrtMaxTextures; if( textureArray.automatic && textureArray.activeEntries < textureArray.maxTextures && arrayTexWidth == width && arrayTexHeight == height && (textureArray.texture->getTextureType() != TEX_TYPE_3D || textureArray.texture->getDepth()== depth) && textureArray.texture->getNumFaces() == faces && textureArray.texture->getFormat() == format && textureArray.texture->getNumMipmaps() == numMipmaps ) { retVal = itor; } ++itor; } return retVal; } //----------------------------------------------------------------------------------- HlmsTextureManager::TextureLocation HlmsTextureManager::createOrRetrieveTexture( const String &texName, TextureMapType mapType ) { return createOrRetrieveTexture( texName, texName, mapType ); } //----------------------------------------------------------------------------------- HlmsTextureManager::TextureLocation HlmsTextureManager::createOrRetrieveTexture( const String &aliasName, const String &texName, TextureMapType mapType, Image *imgSource ) { TextureEntry searchName( aliasName ); TextureEntryVec::iterator it = std::lower_bound( mEntries.begin(), mEntries.end(), searchName ); TextureLocation retVal; assert( !aliasName.empty() && "Alias name can't be left empty!" ); try { if( it == mEntries.end() || it->name != searchName.name ) { LogManager::getSingleton().logMessage( "Texture: loading " + texName + " as " + aliasName ); Image localImageVar; Image *image = imgSource; if( !imgSource ) { image = &localImageVar; image->load( texName, ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME ); } PixelFormat imageFormat = image->getFormat(); const RenderSystemCapabilities *caps = mRenderSystem->getCapabilities(); if( mDefaultTextureParameters[mapType].pixelFormat != PF_UNKNOWN ) { //Don't force non-compressed sources to be compressed when we can't do it //automatically, but force them to a format we actually understand. if( mDefaultTextureParameters[mapType].isNormalMap && mDefaultTextureParameters[mapType].pixelFormat == PF_BC5_SNORM && imageFormat != PF_BC5_SNORM ) { LogManager::getSingleton().logMessage( "WARNING: normal map texture " + texName + " is not BC5S compressed. " "This is encouraged for lower memory usage. If you don't want to see " "this message without compressing to BC5, set " "getDefaultTextureParameters()[TEXTURE_TYPE_NORMALS].pixelFormat to " "PF_R8G8_SNORM (or PF_BYTE_LA if RSC_TEXTURE_SIGNED_INT is not " "supported)", LML_NORMAL); imageFormat = caps->hasCapability( RSC_TEXTURE_SIGNED_INT ) ? PF_R8G8_SNORM : PF_BYTE_LA; } else if (mDefaultTextureParameters[mapType].pixelFormat != imageFormat && (PixelUtil::isCompressed(imageFormat) || PixelUtil::isCompressed(mDefaultTextureParameters[mapType].pixelFormat))) { //Image formats do not match, and one or both of the formats is compressed //and therefore we can not convert it to the desired format. //So we use the src image format instead of the requested image format LogManager::getSingleton().logMessage( "WARNING: The input texture " + texName + " is a " + PixelUtil::getFormatName(imageFormat) + " " + "texture and can not be converted to the requested pixel format of " + PixelUtil::getFormatName(mDefaultTextureParameters[mapType].pixelFormat) + ". " + "This will potentially cause both an increase in memory usage and a decrease in performance. " + "It is highly recommended you convert this texture to the requested format.", LML_NORMAL); } else { imageFormat = mDefaultTextureParameters[mapType].pixelFormat; } } if( imageFormat == PF_X8R8G8B8 || imageFormat == PF_R8G8B8 || imageFormat == PF_X8B8G8R8 || imageFormat == PF_B8G8R8 || imageFormat == PF_A8R8G8B8 ) { #if OGRE_PLATFORM >= OGRE_PLATFORM_ANDROID imageFormat = PF_A8B8G8R8; #else imageFormat = PF_A8R8G8B8; #endif } uint8 numMipmaps = 0; if( mDefaultTextureParameters[mapType].mipmaps ) { uint32 heighestRes = std::max( std::max( image->getWidth(), image->getHeight() ), std::max<uint32>( image->getDepth(), image->getNumFaces() ) ); #if (ANDROID || (OGRE_COMPILER == OGRE_COMPILER_MSVC && OGRE_COMP_VER < 1800)) numMipmaps = static_cast<uint8>( floorf( logf( static_cast<float>(heighestRes) ) / logf( 2.0f ) ) ); #else numMipmaps = static_cast<uint8>( floorf( log2f( static_cast<float>(heighestRes) ) ) ); #endif } TextureType texType = TEX_TYPE_2D; uint width, height, depth, faces; uint8 baseMipLevel = 0; width = image->getWidth(); height = image->getHeight(); depth = image->getDepth(); faces = image->getNumFaces(); ushort maxResolution = caps->getMaximumResolution2D(); if( image->hasFlag( IF_3D_TEXTURE ) ) { maxResolution = caps->getMaximumResolution3D(); texType = TEX_TYPE_3D; } else { if( image->hasFlag( IF_CUBEMAP ) ) { maxResolution = caps->getMaximumResolutionCubemap(); //TODO: Cubemap arrays supported since D3D10.1 texType = TEX_TYPE_CUBE_MAP; } else if( mDefaultTextureParameters[mapType].packingMethod == TextureArrays ) { //2D Texture Arrays texType = TEX_TYPE_2D_ARRAY; } } if( !maxResolution ) { OGRE_EXCEPT( Exception::ERR_RENDERINGAPI_ERROR, "Maximum resolution for this type of texture is 0.\n" "Either a driver bug, or this GPU cannot support 2D/" "Cubemap/3D texture: " + texName, "HlmsTextureManager::createOrRetrieveTexture" ); } //The texture is too big. Take a smaller mip. //If the texture doesn't have mipmaps, resize it. if( width > maxResolution || height > maxResolution ) { bool resize = true; if( image->getNumMipmaps() ) { resize = false; while( (width > maxResolution || height > maxResolution) && (baseMipLevel <= image->getNumMipmaps()) ) { width >>= 1; height >>= 1; ++baseMipLevel; } if( (width > maxResolution || height > maxResolution) ) resize = true; } if( resize ) { baseMipLevel = 0; Real aspectRatio = (Real)image->getWidth() / (Real)image->getHeight(); if( image->getWidth() >= image->getHeight() ) { width = maxResolution; height = static_cast<uint>( floorf( maxResolution / aspectRatio ) ); } else { width = static_cast<uint>( floorf( maxResolution * aspectRatio ) ); height = maxResolution; } image->resize( width, height ); } } if (image->getNumMipmaps() - baseMipLevel != (numMipmaps - baseMipLevel)) { if (image->generateMipmaps(mDefaultTextureParameters[mapType].hwGammaCorrection) == false) { //unable to generate preferred number of mipmaps, so use mipmaps of the input tex numMipmaps = image->getNumMipmaps(); LogManager::getSingleton().logMessage( "WARNING: Could not generate mipmaps for " + texName + ". " "This can negatively impact performance as the HlmsTextureManager " "will create more texture arrays than necessary, and the lower mips " "won't be available. Lack of mipmaps also contribute to aliasing. " "If this is a compressed DDS/PVR file, bake the mipmaps offline.", LML_NORMAL ); } } //Find an array where we can put it. If there is none, we'll have have to create a new one TextureArrayVec::iterator dstArrayIt = findSuitableArray( mapType, width, height, depth, faces, imageFormat, numMipmaps - baseMipLevel ); if( dstArrayIt == mTextureArrays[mapType].end() ) { //Create a new array uint limit = mDefaultTextureParameters[mapType].maxTexturesPerArray; uint limitSquared = mDefaultTextureParameters[mapType].maxTexturesPerArray; bool packNonPow2 = mDefaultTextureParameters[mapType].packNonPow2; float packMaxRatio = mDefaultTextureParameters[mapType].packMaxRatio; if( !packNonPow2 ) { if( !Bitwise::isPO2( width ) || !Bitwise::isPO2( height ) ) limit = limitSquared = 1; } if( width / (float)height >= packMaxRatio || height / (float)width >= packMaxRatio ) limit = limitSquared = 1; if( mDefaultTextureParameters[mapType].packingMethod == TextureArrays ) { limit = 1; //Texture Arrays if( texType == TEX_TYPE_3D || texType == TEX_TYPE_CUBE_MAP ) { //APIs don't support arrays + 3D textures //TODO: Cubemap arrays supported since D3D10.1 limitSquared = 1; } else if( texType == TEX_TYPE_2D_ARRAY ) { size_t textureSizeNoMips = PixelUtil::getMemorySize( width, height, 1, imageFormat ); ThresholdVec::const_iterator itThres = mDefaultTextureParameters[mapType]. textureArraysTresholds.begin(); ThresholdVec::const_iterator enThres = mDefaultTextureParameters[mapType]. textureArraysTresholds.end(); while( itThres != enThres && textureSizeNoMips > itThres->minTextureSize ) ++itThres; if( itThres == enThres ) { itThres = mDefaultTextureParameters[mapType]. textureArraysTresholds.end() - 1; } limitSquared = std::min<uint16>( limitSquared, itThres->maxTexturesPerArray ); depth = limitSquared; } } else { //UV Atlas limit = static_cast<uint>( ceilf( sqrtf( (Real)limitSquared ) ) ); limitSquared = limit * limit; if( texType == TEX_TYPE_3D || texType == TEX_TYPE_CUBE_MAP ) limit = 1; //No UV atlas for 3D and Cubemaps uint texWidth = width * limit; uint texHeight = height * limit; if( texWidth > maxResolution || texHeight > maxResolution ) { limit = maxResolution / width; limit = std::min<uint>( limit, maxResolution / height ); width = width * limit; height = height * limit; } limitSquared = limit * limit; } TextureArray textureArray( limit, limitSquared, true, mDefaultTextureParameters[mapType].isNormalMap ); textureArray.texture = TextureManager::getSingleton().createManual( "HlmsTextureManager/" + StringConverter::toString( mTextureId++ ), ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, texType, width, height, depth, numMipmaps - baseMipLevel, imageFormat, TU_DEFAULT & ~TU_AUTOMIPMAP, 0, mDefaultTextureParameters[mapType].hwGammaCorrection, 0, BLANKSTRING, false ); mTextureArrays[mapType].push_back( textureArray ); dstArrayIt = mTextureArrays[mapType].end() - 1; } uint16 entryIdx = dstArrayIt->createEntry(); uint16 arrayIdx = dstArrayIt - mTextureArrays[mapType].begin(); dstArrayIt->entries[entryIdx] = TextureArray::NamePair( aliasName, texName ); it = mEntries.insert( it, TextureEntry( searchName.name, mapType, arrayIdx, entryIdx ) ); try { if( texType != TEX_TYPE_3D && texType != TEX_TYPE_CUBE_MAP ) { if( mDefaultTextureParameters[mapType].packingMethod == TextureArrays ) { copyTextureToArray( *image, dstArrayIt->texture, entryIdx, baseMipLevel, dstArrayIt->isNormalMap ); } else { copyTextureToAtlas( *image, dstArrayIt->texture, entryIdx, dstArrayIt->sqrtMaxTextures, baseMipLevel, dstArrayIt->isNormalMap ); } } else { copy3DTexture( *image, dstArrayIt->texture, 0, std::max<uint32>( image->getNumFaces(), image->getDepth() ), baseMipLevel ); } } catch( Exception &e ) { destroyTexture(aliasName); throw; } } const TextureArray &texArray = mTextureArrays[it->mapType][it->arrayIdx]; retVal.texture = texArray.texture; if( !texArray.texture->isTextureTypeArray() ) { retVal.xIdx = it->entryIdx % texArray.sqrtMaxTextures; retVal.yIdx = it->entryIdx / texArray.sqrtMaxTextures; retVal.divisor= texArray.sqrtMaxTextures; } else { retVal.xIdx = it->entryIdx; retVal.yIdx = 0; retVal.divisor= 1; } } catch( Exception &e ) { LogManager::getSingleton().logMessage( LML_CRITICAL, e.getFullDescription() ); if( e.getNumber() != Exception::ERR_FILE_NOT_FOUND ) throw e; else { retVal.texture = mBlankTexture; retVal.xIdx = 0; retVal.yIdx = 0; retVal.divisor = 1; } } return retVal; } //----------------------------------------------------------------------------------- void HlmsTextureManager::destroyTexture( IdString aliasName ) { TextureEntry searchName( aliasName ); TextureEntryVec::iterator it = std::lower_bound( mEntries.begin(), mEntries.end(), searchName ); if( it != mEntries.end() && it->name == searchName.name ) { TextureArrayVec::iterator texArrayIt = mTextureArrays[it->mapType].begin() + it->arrayIdx; texArrayIt->destroyEntry( it->entryIdx ); if( texArrayIt->activeEntries == 0 ) { //The whole array has no actual content. Destroy the texture. ResourcePtr texResource = texArrayIt->texture; TextureManager::getSingleton().remove( texResource ); texArrayIt = efficientVectorRemove( mTextureArrays[it->mapType], texArrayIt ); if( texArrayIt != mTextureArrays[it->mapType].end() ) { //The last element has now a new index. Update the references in mEntries const size_t newArrayIdx = texArrayIt - mTextureArrays[it->mapType].begin(); TextureArray::NamePairVec::const_iterator itor = texArrayIt->entries.begin(); TextureArray::NamePairVec::const_iterator end = texArrayIt->entries.end(); while( itor != end ) { if( !itor->aliasName.empty() ) { searchName.name = itor->aliasName; TextureEntryVec::iterator itEntry = std::lower_bound( mEntries.begin(), mEntries.end(), searchName ); assert( itEntry != mEntries.end() && itEntry->name == searchName.name ); itEntry->arrayIdx = newArrayIdx; } ++itor; } } } mEntries.erase( it ); } } //----------------------------------------------------------------------------------- const String* HlmsTextureManager::findAliasName( const TextureLocation &textureLocation ) const { const String *retVal = 0; for( size_t i=0; i<NUM_TEXTURE_TYPES && !retVal; ++i ) { TextureArrayVec::const_iterator itor = mTextureArrays[i].begin(); TextureArrayVec::const_iterator end = mTextureArrays[i].end(); while( itor != end && !retVal ) { if( itor->texture == textureLocation.texture ) { size_t idx = textureLocation.yIdx * itor->sqrtMaxTextures + textureLocation.xIdx; if( idx < itor->entries.size() ) retVal = &itor->entries[idx].aliasName; } ++itor; } } return retVal; } //----------------------------------------------------------------------------------- const String* HlmsTextureManager::findResourceNameFromAlias( IdString aliasName ) const { const String *retVal = 0; TextureEntry searchName( aliasName ); TextureEntryVec::const_iterator it = std::lower_bound( mEntries.begin(), mEntries.end(), searchName ); if( it != mEntries.end() && it->name == searchName.name ) { const TextureArray &texArray = mTextureArrays[it->mapType][it->arrayIdx]; retVal = &texArray.entries[it->entryIdx].resourceName; } return retVal; } //----------------------------------------------------------------------------------- bool HlmsTextureManager::getTexturePackParameters( const HlmsTexturePack &pack, uint32 &outWidth, uint32 &outHeight, uint32 &outDepth, PixelFormat &outPixelFormat ) const { HlmsTexturePack::TextureEntryVec::const_iterator itor = pack.textureEntry.begin(); HlmsTexturePack::TextureEntryVec::const_iterator end = pack.textureEntry.end(); while( itor != end ) { const HlmsTexturePack::TextureEntry &texInfo = *itor; StringVector::const_iterator itPath = texInfo.paths.begin(); StringVector::const_iterator enPath = texInfo.paths.end(); while( itPath != enPath ) { try { Image image; image.load( *itPath, ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME ); outWidth = image.getWidth(); outHeight = image.getHeight(); outDepth = std::max<uint32>( image.getDepth(), image.getNumFaces() ); outPixelFormat = image.getFormat(); return true; } catch( ... ) { } ++itPath; } ++itor; } return false; } //----------------------------------------------------------------------------------- void HlmsTextureManager::createFromTexturePack( const HlmsTexturePack &pack ) { uint32 width = 0, height = 0, depth = 0; PixelFormat pixelFormat; uint8 numMipmaps = 0; if( !getTexturePackParameters( pack, width, height, depth, pixelFormat ) ) { OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "Could not derive the texture properties " "for texture pack '" + pack.name + "'", "HlmsTextureManager::createFromTexturePack" ); } if( pack.pixelFormat != PF_UNKNOWN ) { pixelFormat = pack.pixelFormat; } else { if( pixelFormat == PF_X8R8G8B8 || pixelFormat == PF_R8G8B8 || pixelFormat == PF_X8B8G8R8 || pixelFormat == PF_B8G8R8 || pixelFormat == PF_A8R8G8B8 ) { pixelFormat = PF_A8B8G8R8; } } if( pack.hasMipmaps ) { uint32 heighestRes = std::max( std::max( width, height ), depth ); #if (ANDROID || (OGRE_COMPILER == OGRE_COMPILER_MSVC && OGRE_COMP_VER < 1800)) numMipmaps = static_cast<uint8>( floorf( logf( static_cast<float>(heighestRes) ) / logf( 2.0f ) ) ); #else numMipmaps = static_cast<uint8>( floorf( log2f( static_cast<float>(heighestRes) ) ) ); #endif } if( pack.textureType == TEX_TYPE_CUBE_MAP ) { HlmsTexturePack::TextureEntryVec::const_iterator itor = pack.textureEntry.begin(); HlmsTexturePack::TextureEntryVec::const_iterator end = pack.textureEntry.end(); while( itor != end ) { const HlmsTexturePack::TextureEntry &texInfo = *itor; TextureEntry searchName( texInfo.name ); TextureEntryVec::iterator it = std::lower_bound( mEntries.begin(), mEntries.end(), searchName ); if( it != mEntries.end() && it->name == searchName.name ) { LogManager::getSingleton().logMessage( "ERROR: A texture by the name '" + texInfo.name + "' already exists!" ); ++itor; continue; } assert( !texInfo.paths.empty() ) ; if( texInfo.paths.size() != 1 ) { //Multiple files assert( !(texInfo.paths.size() % 6) && "For cubemaps, the number of files must be multiple of 6!" ); Image cubeMap; size_t cubeMapSize = PixelUtil::getMemorySize( width, height, 6, pixelFormat ); cubeMap.loadDynamicImage( OGRE_ALLOC_T( uchar, cubeMapSize, MEMCATEGORY_GENERAL ), width, height, 1, pixelFormat, true, 6 ); for( size_t i=0; i<6; ++i ) { Image image; image.load( texInfo.paths[i], ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME ); if( image.getWidth() != width && image.getHeight() != height ) { OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, texInfo.paths[i] + ": All textures in the same pack must have the " "same resolution!", "HlmsTextureManager::createFromTexturePack" ); } PixelUtil::bulkPixelConversion( image.getPixelBox( 0 ), cubeMap.getPixelBox( i ) ); } TextureArray textureArray( 1, 1, false, false ); textureArray.texture = TextureManager::getSingleton().createManual( "HlmsTextureManager/" + StringConverter::toString( mTextureId++ ), ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, pack.textureType, width, height, depth, numMipmaps, pixelFormat, TU_DEFAULT & ~TU_AUTOMIPMAP, 0, pack.hwGammaCorrection, 0, BLANKSTRING, false ); if( pack.hasMipmaps ) { if( !cubeMap.generateMipmaps( pack.hwGammaCorrection, Image::FILTER_GAUSSIAN ) ) { LogManager::getSingleton().logMessage( "Couldn't generate mipmaps for '" + texInfo.name + "'", LML_CRITICAL ); } if( !pack.exportLocation.empty() ) cubeMap.save( pack.exportLocation + "/" + texInfo.name + ".dds" ); } copy3DTexture( cubeMap, textureArray.texture, 0, 6, 0 ); it = mEntries.insert( it, TextureEntry( searchName.name, TEXTURE_TYPE_ENV_MAP, mTextureArrays[TEXTURE_TYPE_ENV_MAP].size(), 0 ) ); textureArray.entries.push_back( TextureArray::NamePair( texInfo.name, texInfo.name ) ); mTextureArrays[TEXTURE_TYPE_ENV_MAP].push_back( textureArray ); } else { OGRE_EXCEPT( Exception::ERR_NOT_IMPLEMENTED, "Oops! Work in Progress, sorry!", "HlmsTextureManager::createFromTexturePack" ); //TODO /*if( image.getNumMipmaps() != numMipmaps ) { image.generateMipmaps(); }*/ } ++itor; } } else { OGRE_EXCEPT( Exception::ERR_NOT_IMPLEMENTED, "Oops! Work in Progress, sorry!", "HlmsTextureManager::createFromTexturePack" ); } } //----------------------------------------------------------------------------------- HlmsTextureManager::TextureLocation HlmsTextureManager::getBlankTexture(void) const { TextureLocation retVal; retVal.texture = mBlankTexture; retVal.xIdx = 0; retVal.yIdx = 0; retVal.divisor = 1; return retVal; } //----------------------------------------------------------------------------------- void HlmsTextureManager::dumpMemoryUsage( Log* log ) const { const char *typeNames[NUM_TEXTURE_TYPES] = { "DIFFUSE", "MONOCHROME", "NORMALS", "ENV_MAP", "DETAIL", "DETAIL_NORMAL_MAP", "NON_COLOR_DATA" }; size_t bytesPerCategory[NUM_TEXTURE_TYPES]; memset( bytesPerCategory, 0, sizeof( bytesPerCategory ) ); Log* logActual = log == NULL ? LogManager::getSingleton().getDefaultLog() : log; logActual->logMessage( "================================" "Start dump of HlmsTextureManager" "================================", LML_CRITICAL ); logActual->logMessage( "|#|Type|Width|Height|Depth|Format|HW Gamma|Mipmaps|Size in bytes|" "Num. active textures|Total texture capacity|Texture Names", LML_CRITICAL ); for( size_t i=0; i<NUM_TEXTURE_TYPES; ++i ) { TextureArrayVec::const_iterator itor = mTextureArrays[i].begin(); TextureArrayVec::const_iterator end = mTextureArrays[i].end(); String row; while( itor != end ) { size_t textureSize = 0; uint32 width = itor->texture->getWidth(); uint32 height = itor->texture->getHeight(); uint32 depth = itor->texture->getDepth(); for( size_t j=0; j<(size_t)(itor->texture->getNumMipmaps() + 1); ++j ) { textureSize += PixelUtil::getMemorySize( width, height, depth, itor->texture->getFormat() ) * itor->texture->getNumFaces(); width = std::max<uint32>( width >> 1, 1 ); height = std::max<uint32>( height >> 1, 1 ); if( !itor->texture->isTextureTypeArray() ) depth = std::max<uint32>( depth >> 1, 1 ); } row += "|"; row += StringConverter::toString( (size_t)(itor - mTextureArrays[i].begin()) ) + "|"; row += String( typeNames[i] ) + "|"; row += StringConverter::toString( itor->texture->getWidth() ) + "|"; row += StringConverter::toString( itor->texture->getHeight() ) + "|"; row += StringConverter::toString( itor->texture->getDepth() ) + "|"; row += PixelUtil::getFormatName( itor->texture->getFormat() ) + "|"; row += itor->texture->isHardwareGammaEnabled() ? "Yes|" : "No|"; row += StringConverter::toString( itor->texture->getNumMipmaps() ) + "|"; row += StringConverter::toString( textureSize ) + "|"; row += StringConverter::toString( itor->activeEntries ) + "|"; row += StringConverter::toString( itor->entries.size() ); TextureArray::NamePairVec::const_iterator itEntry = itor->entries.begin(); TextureArray::NamePairVec::const_iterator enEntry = itor->entries.end(); while( itEntry != enEntry ) { row += "|" + itEntry->aliasName; ++itEntry; } logActual->logMessage( row, LML_CRITICAL ); row.clear(); bytesPerCategory[i] += textureSize; ++itor; } } logActual->logMessage( "|Size in MBs per category:", LML_CRITICAL ); size_t totalBytes = 0; for( size_t i=0; i<NUM_TEXTURE_TYPES; ++i ) { logActual->logMessage( "|" + String( typeNames[i] ) + "|" + StringConverter::toString( bytesPerCategory[i] / (1024.0f * 1024.0f) ), LML_CRITICAL ); totalBytes += bytesPerCategory[i]; } logActual->logMessage( "|Total MBs used:|" + StringConverter::toString( totalBytes / (1024.0f * 1024.0f) ), LML_CRITICAL ); logActual->logMessage( "================================" "End dump of HlmsTextureManager" "================================", LML_CRITICAL ); } //----------------------------------------------------------------------------------- //----------------------------------------------------------------------------------- //----------------------------------------------------------------------------------- uint16 HlmsTextureManager::TextureArray::createEntry(void) { assert( activeEntries < maxTextures ); ++activeEntries; TextureArray::NamePairVec::const_iterator itor = entries.begin(); TextureArray::NamePairVec::const_iterator end = entries.end(); while( itor != end && !itor->aliasName.empty() ) ++itor; return static_cast<uint16>( itor - entries.begin() ); } //----------------------------------------------------------------------------------- void HlmsTextureManager::TextureArray::destroyEntry( uint16 entry ) { assert( activeEntries != 0 ); --activeEntries; entries[entry].aliasName.clear(); entries[entry].resourceName.clear(); } //----------------------------------------------------------------------------------- }
47.666978
122
0.466932
osrf
e788b039eddcd475e3c855784a2810e79f4ca023
1,088
cpp
C++
LeetCode Problem-Set/42. Trapping Rain Water (Hard)/Solution1.cpp
ankuralld5999/LeetCode-Problems
2f9a767a0effbb2a50672e102925fbbb65034083
[ "FSFAP" ]
2
2021-01-06T20:43:59.000Z
2021-01-11T15:42:59.000Z
LeetCode Problem-Set/42. Trapping Rain Water (Hard)/Solution1.cpp
ankuralld5999/LeetCode-Problems
2f9a767a0effbb2a50672e102925fbbb65034083
[ "FSFAP" ]
null
null
null
LeetCode Problem-Set/42. Trapping Rain Water (Hard)/Solution1.cpp
ankuralld5999/LeetCode-Problems
2f9a767a0effbb2a50672e102925fbbb65034083
[ "FSFAP" ]
null
null
null
// OJ: https://leetcode.com/problems/trapping-rain-water/ // Author: github.com/lzl124631x // Time: O(N) // Space: O(N) class Solution { public: int trap(vector<int>& A) { int N = A.size(), ans = 0; vector<int> left(N, 0), right(N, 0); for (int i = 1; i < N; ++i) left[i] = max(left[i - 1], A[i - 1]); for (int i = N - 2; i >= 0; --i) right[i] = max(right[i + 1], A[i + 1]); for (int i = 1; i < N - 1; ++i) ans += max(0, min(left[i], right[i]) - A[i]); return ans; } }; //Or // Problem: https://leetcode.com/problems/trapping-rain-water/ // Author: github.com/ankuralld5999 // Time: O(N) // Space: O(N) class Solution { public: int trap(vector<int>& A) { int N = A.size(), ans = 0, mx = 0, left = 0; vector<int> right(N); for (int i = N - 2; i >= 0; --i) right[i] = max(right[i + 1], A[i + 1]); for (int i = 0; i < N; ++i) { ans += max(0, min(left, right[i]) - A[i]); left = max(left, A[i]); } return ans; } };
27.897436
80
0.463235
ankuralld5999
e788ea11cc54794e66f0671dad22a3a6197f3711
29,399
cpp
C++
src/VkRenderer/SceneObject.cpp
WubiCookie/VkRenderer
87cc5d858591fc976c197ab2834e1ac9a418becd
[ "MIT" ]
2
2020-05-31T19:54:19.000Z
2021-09-14T12:00:12.000Z
src/VkRenderer/SceneObject.cpp
WubiCookie/VkRenderer
87cc5d858591fc976c197ab2834e1ac9a418becd
[ "MIT" ]
null
null
null
src/VkRenderer/SceneObject.cpp
WubiCookie/VkRenderer
87cc5d858591fc976c197ab2834e1ac9a418becd
[ "MIT" ]
null
null
null
#include "SceneObject.hpp" #include "CommandBuffer.hpp" #include "Material.hpp" #include "RenderWindow.hpp" #include "Scene.hpp" #include "StandardMesh.hpp" #include <iostream> namespace cdm { SceneObject::Pipeline::Pipeline(Scene& s, StandardMesh& mesh, MaterialInterface& material, VkRenderPass renderPass) : scene(&s), mesh(&mesh), material(&material), renderPass(renderPass) { auto& rw = material.material().renderWindow(); auto& vk = rw.device(); #pragma region vertexShader { using namespace sdw; VertexWriter writer; Scene::SceneUbo sceneUbo(writer); Scene::ModelUbo modelUbo(writer); Scene::ModelPcb modelPcb(writer); auto shaderVertexInput = mesh.shaderVertexInput(writer); auto fragPosition = writer.declOutput<Vec3>("fragPosition", 0); auto fragUV = writer.declOutput<Vec2>("fragUV", 1); auto fragNormal = writer.declOutput<Vec3>("fragNormal", 2); auto fragTangent = writer.declOutput<Vec3>("fragTangent", 3); auto fragDistance = writer.declOutput<sdw::Float>("fragDistance", 4); auto out = writer.getOut(); auto materialVertexShaderBuildData = material.material().instantiateVertexShaderBuildData(); auto materialVertexFunction = material.material().vertexFunction( writer, materialVertexShaderBuildData.get()); writer.implementMain([&]() { auto model = modelUbo.getModel()[modelPcb.getModelId()]; auto view = sceneUbo.getView(); auto proj = sceneUbo.getProj(); fragPosition = (model * vec4(shaderVertexInput.inPosition, 1.0_f)).xyz(); fragUV = shaderVertexInput.inUV; Locale(model3, mat3(vec3(model[0][0], model[0][1], model[0][2]), vec3(model[1][0], model[1][1], model[1][2]), vec3(model[2][0], model[2][1], model[2][2]))); Locale(normalMatrix, transpose(inverse(model3))); // Locale(normalMatrix, transpose((model3))); fragNormal = shaderVertexInput.inNormal; materialVertexFunction(fragPosition, fragNormal); fragNormal = normalize(normalMatrix * fragNormal); fragTangent = normalize(normalMatrix * shaderVertexInput.inTangent); // fragNormal = normalize((model * vec4(fragNormal, 0.0_f)).xyz()); // fragTangent = normalize( // (model * vec4(shaderVertexInput.inTangent, 0.0_f)).xyz()); fragTangent = normalize(fragTangent - dot(fragTangent, fragNormal) * fragNormal); // Locale(B, cross(fragNormal, fragTangent)); // Locale(TBN, transpose(mat3(fragTangent, B, fragNormal))); // fragTanLightPos = TBN * sceneUbo.getLightPos(); // fragTanViewPos = TBN * sceneUbo.getViewPos(); // fragTanFragPos = TBN * fragPosition; fragDistance = (view * model * vec4(shaderVertexInput.inPosition, 1.0_f)).z(); out.vtx.position = proj * view * model * vec4(shaderVertexInput.inPosition, 1.0_f); }); std::vector<uint32_t> bytecode = spirv::serialiseSpirv(writer.getShader()); vk::ShaderModuleCreateInfo createInfo; createInfo.codeSize = bytecode.size() * sizeof(*bytecode.data()); createInfo.pCode = bytecode.data(); vertexModule = vk.create(createInfo); if (!vertexModule) { std::cerr << "error: failed to create vertex shader module" << std::endl; abort(); } } #pragma endregion #pragma region fragmentShader { using namespace sdw; FragmentWriter writer; Scene::SceneUbo sceneUbo(writer); Scene::ModelPcb modelPcb(writer); auto fragPosition = writer.declInput<sdw::Vec3>("fragPosition", 0); auto fragUV = writer.declInput<sdw::Vec2>("fragUV", 1); auto fragNormal = writer.declInput<sdw::Vec3>("fragNormal", 2); auto fragTangent = writer.declInput<sdw::Vec3>("fragTangent", 3); auto fragDistance = writer.declInput<sdw::Float>("fragDistance", 4); auto fragColor = writer.declOutput<Vec4>("fragColor", 0); auto fragID = writer.declOutput<UInt>("fragID", 1); auto fragNormalDepth = writer.declOutput<Vec4>("fragNormalDepth", 2); auto fragPos = writer.declOutput<Vec3>("fragPos", 3); auto fragmentShaderBuildData = material.material().instantiateFragmentShaderBuildData(); auto materialFragmentFunction = material.material().fragmentFunction( writer, fragmentShaderBuildData.get()); auto shadingModelFragmentShaderBuildData = material.material() .shadingModel() .instantiateFragmentShaderBuildData(); auto combinedMaterialFragmentFunction = material.material() .shadingModel() .combinedMaterialFragmentFunction( writer, materialFragmentFunction, shadingModelFragmentShaderBuildData.get(), sceneUbo); writer.implementMain([&]() { Locale(materialInstanceId, modelPcb.getMaterialInstanceId() + 1_u); materialInstanceId -= 1_u; Locale(normal, normalize(fragNormal)); Locale(tangent, normalize(fragTangent)); fragColor = combinedMaterialFragmentFunction( materialInstanceId, fragPosition, fragUV, normal, tangent); fragID = modelPcb.getModelId(); fragNormalDepth.xyz() = fragNormal; fragNormalDepth.w() = fragDistance; fragPos = fragPosition; }); std::vector<uint32_t> bytecode = spirv::serialiseSpirv(writer.getShader()); vk::ShaderModuleCreateInfo createInfo; createInfo.codeSize = bytecode.size() * sizeof(*bytecode.data()); createInfo.pCode = bytecode.data(); fragmentModule = vk.create(createInfo); if (!fragmentModule) { std::cerr << "error: failed to create fragment shader module" << std::endl; abort(); } } #pragma endregion #pragma region pipeline layout VkPushConstantRange pcRange{}; pcRange.size = sizeof(PcbStruct); pcRange.stageFlags = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT; std::array descriptorSetLayouts{ scene.get()->descriptorSetLayout(), material.material().shadingModel().m_descriptorSetLayout.get(), material.material().descriptorSetLayout(), }; vk::PipelineLayoutCreateInfo pipelineLayoutInfo; pipelineLayoutInfo.setLayoutCount = uint32_t(descriptorSetLayouts.size()); pipelineLayoutInfo.pSetLayouts = descriptorSetLayouts.data(); // pipelineLayoutInfo.setLayoutCount = 0; // pipelineLayoutInfo.pSetLayouts = nullptr; pipelineLayoutInfo.pushConstantRangeCount = 1; pipelineLayoutInfo.pPushConstantRanges = &pcRange; // pipelineLayoutInfo.pushConstantRangeCount = 0; // pipelineLayoutInfo.pPushConstantRanges = nullptr; pipelineLayout = vk.create(pipelineLayoutInfo); if (!pipelineLayout) { std::cerr << "error: failed to create pipeline layout" << std::endl; abort(); } #pragma endregion #pragma region pipeline vk::PipelineShaderStageCreateInfo vertShaderStageInfo; vertShaderStageInfo.stage = VK_SHADER_STAGE_VERTEX_BIT; vertShaderStageInfo.module = vertexModule; vertShaderStageInfo.pName = "main"; vk::PipelineShaderStageCreateInfo fragShaderStageInfo; fragShaderStageInfo.stage = VK_SHADER_STAGE_FRAGMENT_BIT; fragShaderStageInfo.module = fragmentModule; fragShaderStageInfo.pName = "main"; std::array shaderStages = { vertShaderStageInfo, fragShaderStageInfo }; auto vertexInputState = mesh.vertexInputState(); vk::PipelineInputAssemblyStateCreateInfo inputAssembly; inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; // inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST; inputAssembly.primitiveRestartEnable = false; VkViewport viewport = {}; viewport.x = 0.0f; viewport.y = 0.0f; /// TODO get from render pass viewport.width = float(1280); viewport.height = float(720); viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; VkRect2D scissor = {}; scissor.offset = { 0, 0 }; /// TODO get from render pass scissor.extent.width = 1280; scissor.extent.height = 720; vk::PipelineViewportStateCreateInfo viewportState; viewportState.viewportCount = 1; viewportState.pViewports = &viewport; viewportState.scissorCount = 1; viewportState.pScissors = &scissor; vk::PipelineRasterizationStateCreateInfo rasterizer; rasterizer.depthClampEnable = false; rasterizer.rasterizerDiscardEnable = false; rasterizer.polygonMode = VK_POLYGON_MODE_FILL; // rasterizer.polygonMode = VK_POLYGON_MODE_LINE; rasterizer.lineWidth = 1.0f; rasterizer.cullMode = VK_CULL_MODE_BACK_BIT; rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; rasterizer.depthBiasEnable = false; rasterizer.depthBiasConstantFactor = 0.0f; rasterizer.depthBiasClamp = 0.0f; rasterizer.depthBiasSlopeFactor = 0.0f; /// TODO get from render pass vk::PipelineMultisampleStateCreateInfo multisampling; multisampling.sampleShadingEnable = false; multisampling.rasterizationSamples = VK_SAMPLE_COUNT_4_BIT; multisampling.minSampleShading = 1.0f; multisampling.pSampleMask = nullptr; multisampling.alphaToCoverageEnable = false; multisampling.alphaToOneEnable = false; /// TODO get from render pass and material VkPipelineColorBlendAttachmentState colorBlendAttachment = {}; colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; colorBlendAttachment.blendEnable = false; colorBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_ONE; colorBlendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ZERO; colorBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD; colorBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; colorBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; colorBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD; // colorBlendAttachment.blendEnable = true; // colorBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA; // colorBlendAttachment.dstColorBlendFactor = // VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; // colorBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD; // colorBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; // colorBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; // colorBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD; /// TODO get from render pass and material VkPipelineColorBlendAttachmentState objectIDBlendAttachment = {}; objectIDBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; objectIDBlendAttachment.blendEnable = false; objectIDBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_ONE; objectIDBlendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ZERO; objectIDBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD; objectIDBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; objectIDBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; objectIDBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD; VkPipelineColorBlendAttachmentState normalDepthBlendAttachment = {}; normalDepthBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; normalDepthBlendAttachment.blendEnable = false; normalDepthBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_ONE; normalDepthBlendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ZERO; normalDepthBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD; normalDepthBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; normalDepthBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; normalDepthBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD; VkPipelineColorBlendAttachmentState positionhBlendAttachment = {}; positionhBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; positionhBlendAttachment.blendEnable = false; positionhBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_ONE; positionhBlendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ZERO; positionhBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD; positionhBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; positionhBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; positionhBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD; // colorHDRBlendAttachment.blendEnable = true; // colorHDRBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA; // colorHDRBlendAttachment.dstColorBlendFactor = // VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; // colorHDRBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD; // colorHDRBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; // colorHDRBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; // colorHDRBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD; std::array colorBlendAttachments{ colorBlendAttachment, objectIDBlendAttachment, normalDepthBlendAttachment, positionhBlendAttachment }; /// TODO get from render pass vk::PipelineColorBlendStateCreateInfo colorBlending; colorBlending.logicOpEnable = false; colorBlending.logicOp = VK_LOGIC_OP_COPY; colorBlending.attachmentCount = uint32_t(colorBlendAttachments.size()); colorBlending.pAttachments = colorBlendAttachments.data(); colorBlending.blendConstants[0] = 0.0f; colorBlending.blendConstants[1] = 0.0f; colorBlending.blendConstants[2] = 0.0f; colorBlending.blendConstants[3] = 0.0f; vk::PipelineDepthStencilStateCreateInfo depthStencil; depthStencil.depthTestEnable = true; depthStencil.depthWriteEnable = true; depthStencil.depthCompareOp = VK_COMPARE_OP_LESS; depthStencil.depthBoundsTestEnable = false; depthStencil.minDepthBounds = 0.0f; // Optional depthStencil.maxDepthBounds = 1.0f; // Optional depthStencil.stencilTestEnable = false; // depthStencil.front; // Optional // depthStencil.back; // Optional std::array dynamicStates = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, }; vk::PipelineDynamicStateCreateInfo dynamicState; dynamicState.dynamicStateCount = uint32_t(dynamicStates.size()); dynamicState.pDynamicStates = dynamicStates.data(); vk::GraphicsPipelineCreateInfo pipelineInfo; pipelineInfo.stageCount = uint32_t(shaderStages.size()); pipelineInfo.pStages = shaderStages.data(); pipelineInfo.pVertexInputState = &vertexInputState.vertexInputInfo; pipelineInfo.pInputAssemblyState = &inputAssembly; pipelineInfo.pViewportState = &viewportState; pipelineInfo.pRasterizationState = &rasterizer; pipelineInfo.pMultisampleState = &multisampling; pipelineInfo.pDepthStencilState = &depthStencil; pipelineInfo.pColorBlendState = &colorBlending; pipelineInfo.pDynamicState = &dynamicState; pipelineInfo.layout = pipelineLayout; pipelineInfo.renderPass = renderPass; pipelineInfo.subpass = 0; pipelineInfo.basePipelineHandle = nullptr; pipelineInfo.basePipelineIndex = -1; pipeline = vk.create(pipelineInfo); if (!pipeline) { std::cerr << "error: failed to create graphics pipeline" << std::endl; abort(); } #pragma endregion } void SceneObject::Pipeline::bindPipeline(CommandBuffer& cb) { cb.bindPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); } void SceneObject::Pipeline::bindDescriptorSet(CommandBuffer& cb) { std::array<VkDescriptorSet, 3> descriptorSets{ scene.get()->descriptorSet(), material.get()->material().shadingModel().m_descriptorSet, material.get()->material().descriptorSet(), }; cb.bindDescriptorSets(VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, uint32_t(descriptorSets.size()), descriptorSets.data()); } void SceneObject::Pipeline::draw(CommandBuffer& cb) { mesh.get()->draw(cb); } SceneObject::ShadowmapPipeline::ShadowmapPipeline(Scene& s, StandardMesh& mesh, MaterialInterface& material, VkRenderPass renderPass) : scene(&s), mesh(&mesh), material(&material), renderPass(renderPass) { auto& rw = material.material().renderWindow(); auto& vk = rw.device(); #pragma region vertexShader { using namespace sdw; VertexWriter writer; Scene::SceneUbo sceneUbo(writer); Scene::ModelUbo modelUbo(writer); Scene::ModelPcb modelPcb(writer); auto inPosition = writer.declInput<Vec4>("fragPosition", 0); auto out = writer.getOut(); auto materialVertexShaderBuildData = material.material().instantiateVertexShaderBuildData(); auto materialVertexFunction = material.material().vertexFunction( writer, materialVertexShaderBuildData.get()); writer.implementMain([&]() { auto model = modelUbo.getModel()[modelPcb.getModelId()]; auto view = sceneUbo.getShadowView(); auto proj = sceneUbo.getShadowProj(); out.vtx.position = proj * view * model * inPosition; }); std::vector<uint32_t> bytecode = spirv::serialiseSpirv(writer.getShader()); vk::ShaderModuleCreateInfo createInfo; createInfo.codeSize = bytecode.size() * sizeof(*bytecode.data()); createInfo.pCode = bytecode.data(); vertexModule = vk.create(createInfo); if (!vertexModule) { std::cerr << "error: failed to create vertex shader module" << std::endl; abort(); } } #pragma endregion #pragma region fragmentShader { using namespace sdw; FragmentWriter writer; writer.implementMain([&]() { }); std::vector<uint32_t> bytecode = spirv::serialiseSpirv(writer.getShader()); vk::ShaderModuleCreateInfo createInfo; createInfo.codeSize = bytecode.size() * sizeof(*bytecode.data()); createInfo.pCode = bytecode.data(); fragmentModule = vk.create(createInfo); if (!fragmentModule) { std::cerr << "error: failed to create fragment shader module" << std::endl; abort(); } } #pragma endregion #pragma region pipeline layout VkPushConstantRange pcRange{}; pcRange.size = sizeof(PcbStruct); pcRange.stageFlags = VK_SHADER_STAGE_VERTEX_BIT; std::array descriptorSetLayouts{ scene.get()->descriptorSetLayout(), material.material().shadingModel().m_descriptorSetLayout.get(), material.material().descriptorSetLayout(), }; vk::PipelineLayoutCreateInfo pipelineLayoutInfo; pipelineLayoutInfo.setLayoutCount = uint32_t(descriptorSetLayouts.size()); pipelineLayoutInfo.pSetLayouts = descriptorSetLayouts.data(); // pipelineLayoutInfo.setLayoutCount = 0; // pipelineLayoutInfo.pSetLayouts = nullptr; pipelineLayoutInfo.pushConstantRangeCount = 1; pipelineLayoutInfo.pPushConstantRanges = &pcRange; // pipelineLayoutInfo.pushConstantRangeCount = 0; // pipelineLayoutInfo.pPushConstantRanges = nullptr; pipelineLayout = vk.create(pipelineLayoutInfo); if (!pipelineLayout) { std::cerr << "error: failed to create pipeline layout" << std::endl; abort(); } #pragma endregion #pragma region pipeline vk::PipelineShaderStageCreateInfo vertShaderStageInfo; vertShaderStageInfo.stage = VK_SHADER_STAGE_VERTEX_BIT; vertShaderStageInfo.module = vertexModule; vertShaderStageInfo.pName = "main"; vk::PipelineShaderStageCreateInfo fragShaderStageInfo; fragShaderStageInfo.stage = VK_SHADER_STAGE_FRAGMENT_BIT; fragShaderStageInfo.module = fragmentModule; fragShaderStageInfo.pName = "main"; std::array shaderStages = { vertShaderStageInfo, fragShaderStageInfo }; VertexInputState vertexInputState = mesh.positionOnlyVertexInputState(); vk::PipelineInputAssemblyStateCreateInfo inputAssembly; inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; // inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST; inputAssembly.primitiveRestartEnable = false; VkViewport viewport = {}; viewport.x = 0.0f; viewport.y = 0.0f; /// TODO get from render pass viewport.width = float(1280); viewport.height = float(720); viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; VkRect2D scissor = {}; scissor.offset = { 0, 0 }; /// TODO get from render pass scissor.extent.width = 1280; scissor.extent.height = 720; vk::PipelineViewportStateCreateInfo viewportState; viewportState.viewportCount = 1; viewportState.pViewports = &viewport; viewportState.scissorCount = 1; viewportState.pScissors = &scissor; vk::PipelineRasterizationStateCreateInfo rasterizer; rasterizer.depthClampEnable = false; rasterizer.rasterizerDiscardEnable = false; rasterizer.polygonMode = VK_POLYGON_MODE_FILL; // rasterizer.polygonMode = VK_POLYGON_MODE_LINE; rasterizer.lineWidth = 1.0f; rasterizer.cullMode = VK_CULL_MODE_BACK_BIT; rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; rasterizer.depthBiasEnable = false; rasterizer.depthBiasConstantFactor = 0.0f; rasterizer.depthBiasClamp = 0.0f; rasterizer.depthBiasSlopeFactor = 0.0f; /// TODO get from render pass vk::PipelineMultisampleStateCreateInfo multisampling; multisampling.sampleShadingEnable = false; multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; multisampling.minSampleShading = 1.0f; multisampling.pSampleMask = nullptr; multisampling.alphaToCoverageEnable = false; multisampling.alphaToOneEnable = false; /// TODO get from render pass and material /* VkPipelineColorBlendAttachmentState colorBlendAttachment = {}; colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; colorBlendAttachment.blendEnable = false; colorBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_ONE; colorBlendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ZERO; colorBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD; colorBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; colorBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; colorBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD; // colorBlendAttachment.blendEnable = true; // colorBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA; // colorBlendAttachment.dstColorBlendFactor = // VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; // colorBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD; // colorBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; // colorBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; // colorBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD; /// TODO get from render pass and material VkPipelineColorBlendAttachmentState objectIDBlendAttachment = {}; objectIDBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; objectIDBlendAttachment.blendEnable = false; objectIDBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_ONE; objectIDBlendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ZERO; objectIDBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD; objectIDBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; objectIDBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; objectIDBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD; // colorHDRBlendAttachment.blendEnable = true; // colorHDRBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA; // colorHDRBlendAttachment.dstColorBlendFactor = // VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; // colorHDRBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD; // colorHDRBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; // colorHDRBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; // colorHDRBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD; std::array colorBlendAttachments{ colorBlendAttachment, objectIDBlendAttachment }; //*/ /// TODO get from render pass vk::PipelineColorBlendStateCreateInfo colorBlending; colorBlending.logicOpEnable = false; colorBlending.logicOp = VK_LOGIC_OP_COPY; // colorBlending.attachmentCount = uint32_t(colorBlendAttachments.size()); // colorBlending.pAttachments = colorBlendAttachments.data(); colorBlending.attachmentCount = 0; colorBlending.pAttachments = nullptr; colorBlending.blendConstants[0] = 0.0f; colorBlending.blendConstants[1] = 0.0f; colorBlending.blendConstants[2] = 0.0f; colorBlending.blendConstants[3] = 0.0f; vk::PipelineDepthStencilStateCreateInfo depthStencil; depthStencil.depthTestEnable = true; depthStencil.depthWriteEnable = true; depthStencil.depthCompareOp = VK_COMPARE_OP_LESS; depthStencil.depthBoundsTestEnable = false; depthStencil.minDepthBounds = 0.0f; // Optional depthStencil.maxDepthBounds = 1.0f; // Optional depthStencil.stencilTestEnable = false; // depthStencil.front; // Optional // depthStencil.back; // Optional std::array dynamicStates = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, }; vk::PipelineDynamicStateCreateInfo dynamicState; dynamicState.dynamicStateCount = uint32_t(dynamicStates.size()); dynamicState.pDynamicStates = dynamicStates.data(); vk::GraphicsPipelineCreateInfo pipelineInfo; pipelineInfo.stageCount = uint32_t(shaderStages.size()); pipelineInfo.pStages = shaderStages.data(); pipelineInfo.pVertexInputState = &vertexInputState.vertexInputInfo; pipelineInfo.pInputAssemblyState = &inputAssembly; pipelineInfo.pViewportState = &viewportState; pipelineInfo.pRasterizationState = &rasterizer; pipelineInfo.pMultisampleState = &multisampling; pipelineInfo.pDepthStencilState = &depthStencil; pipelineInfo.pColorBlendState = &colorBlending; pipelineInfo.pDynamicState = &dynamicState; pipelineInfo.layout = pipelineLayout; pipelineInfo.renderPass = renderPass; pipelineInfo.subpass = 0; pipelineInfo.basePipelineHandle = nullptr; pipelineInfo.basePipelineIndex = -1; pipeline = vk.create(pipelineInfo); if (!pipeline) { std::cerr << "error: failed to create graphics pipeline" << std::endl; abort(); } #pragma endregion } void SceneObject::ShadowmapPipeline::bindPipeline(CommandBuffer& cb) { cb.bindPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); } void SceneObject::ShadowmapPipeline::bindDescriptorSet(CommandBuffer& cb) { std::array<VkDescriptorSet, 3> descriptorSets{ scene.get()->descriptorSet(), material.get()->material().shadingModel().m_descriptorSet, material.get()->material().descriptorSet(), }; cb.bindDescriptorSets(VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, uint32_t(descriptorSets.size()), descriptorSets.data()); } void SceneObject::ShadowmapPipeline::draw(CommandBuffer& cb) { mesh.get()->drawPositions(cb); } SceneObject::SceneObject(Scene& s) : m_scene(&s) {} void SceneObject::draw(CommandBuffer& cb, VkRenderPass renderPass, std::optional<VkViewport> viewport, std::optional<VkRect2D> scissor) { if (m_scene && m_mesh && m_material) { Pipeline* pipeline; auto foundPipeline = m_pipelines.find(renderPass); if (foundPipeline == m_pipelines.end()) { auto it = m_pipelines .insert(std::make_pair( renderPass, Pipeline(*m_scene, *m_mesh, *m_material, renderPass))) .first; pipeline = &it->second; } else { pipeline = &foundPipeline->second; } pipeline->bindPipeline(cb); if (viewport.has_value()) cb.setViewport(viewport.value()); if (scissor.has_value()) cb.setScissor(scissor.value()); pipeline->bindDescriptorSet(cb); PcbStruct pcbStruct; pcbStruct.modelIndex = id; pcbStruct.materialInstanceIndex = m_material.get()->index(); cb.pushConstants( pipeline->pipelineLayout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, &pcbStruct); pipeline->draw(cb); } } void SceneObject::drawShadowmapPass(CommandBuffer& cb, VkRenderPass renderPass, std::optional<VkViewport> viewport, std::optional<VkRect2D> scissor) { if (m_scene && m_mesh && m_material) { ShadowmapPipeline* pipeline; auto foundPipeline = m_shadowmapPipelines.find(renderPass); if (foundPipeline == m_shadowmapPipelines.end()) { auto it = m_shadowmapPipelines .insert(std::make_pair( renderPass, ShadowmapPipeline(*m_scene, *m_mesh, *m_material, renderPass))) .first; pipeline = &it->second; } else { pipeline = &foundPipeline->second; } pipeline->bindPipeline(cb); if (viewport.has_value()) cb.setViewport(viewport.value()); if (scissor.has_value()) cb.setScissor(scissor.value()); pipeline->bindDescriptorSet(cb); PcbStruct pcbStruct; pcbStruct.modelIndex = id; pcbStruct.materialInstanceIndex = m_material.get()->index(); cb.pushConstants(pipeline->pipelineLayout, VK_SHADER_STAGE_VERTEX_BIT, 0, &pcbStruct); pipeline->draw(cb); } } } // namespace cdm
36.250308
80
0.734379
WubiCookie
e789f101a30695ea8fd618c0a1081aede2dce299
8,283
cpp
C++
pxr/usd/usd/testenv/testUsdInstancingCpp.cpp
DougRogers-DigitalFish/USD
d8a405a1344480f859f025c4f97085143efacb53
[ "BSD-2-Clause" ]
3,680
2016-07-26T18:28:11.000Z
2022-03-31T09:55:05.000Z
pxr/usd/usd/testenv/testUsdInstancingCpp.cpp
DougRogers-DigitalFish/USD
d8a405a1344480f859f025c4f97085143efacb53
[ "BSD-2-Clause" ]
1,759
2016-07-26T19:19:59.000Z
2022-03-31T21:24:00.000Z
pxr/usd/usd/testenv/testUsdInstancingCpp.cpp
DougRogers-DigitalFish/USD
d8a405a1344480f859f025c4f97085143efacb53
[ "BSD-2-Clause" ]
904
2016-07-26T18:33:40.000Z
2022-03-31T09:55:16.000Z
// // Copyright 2020 Pixar // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // #include "pxr/usd/pcp/primIndex.h" #include "pxr/usd/sdf/changeBlock.h" #include "pxr/usd/sdf/primSpec.h" #include "pxr/usd/sdf/layer.h" #include "pxr/usd/usd/prim.h" #include "pxr/usd/usd/stage.h" #include <iostream> #include <string> PXR_NAMESPACE_USING_DIRECTIVE // Apply changes such that an instance not represening the sourcePrimIndex for a // prototype is changed, and significant change is pseudoRoot (by adding a dummy // sublayer to it) PXR_NAMESPACE_OPEN_SCOPE const PcpPrimIndex & Usd_PrimGetSourcePrimIndex(const UsdPrim& prim) { return prim._GetSourcePrimIndex(); } PXR_NAMESPACE_CLOSE_SCOPE /// Test to verify prototypes are appropriately changed when "/" is changed void TestInstancing_1() { std::string rootLayer = "./rootLayer.usda"; // determine what instance to unset UsdStageRefPtr stage = UsdStage::Open(rootLayer); const UsdPrim& prototypePrim = stage->GetPrimAtPath(SdfPath("/instancer1/Instance0")).GetPrototype(); const SdfPath sourcePrimIndexPath = Usd_PrimGetSourcePrimIndex(prototypePrim).GetRootNode().GetPath(); const SdfPath& instancePathToUnset = (sourcePrimIndexPath.GetName() == "Instance0") ? SdfPath("/instancer1/Instance1") : SdfPath("/instancer1/Instance0"); SdfLayerRefPtr rootLayerPtr = stage->GetRootLayer(); SdfLayerRefPtr subLayerPtr = SdfLayer::FindOrOpen(rootLayerPtr->GetSubLayerPaths()[0]); SdfPrimSpecHandle instancePrimToUnset = subLayerPtr->GetPrimAtPath(instancePathToUnset); const PcpPrimIndex* origPrimIndexForSource = &(stage->GetPrimAtPath(sourcePrimIndexPath).GetPrimIndex()); SdfLayerRefPtr anonymousLayer = SdfLayer::CreateAnonymous(".usda"); SdfPrimSpecHandle dummpPrim = SdfCreatePrimInLayer(anonymousLayer, SdfPath("/dummy")); { SdfChangeBlock block; // unset instance instancePrimToUnset->SetInstanceable(false); // make a dummy change to sublayers - to trigger a significant change of // "/" - makes sure prototype are rebuild, since all prim indexes are // invalid and new ones are generated as part of this "/" change. rootLayerPtr->SetSubLayerPaths({subLayerPtr->GetIdentifier(), anonymousLayer->GetIdentifier()}); } const UsdPrim& newPrototypePrim = stage->GetPrimAtPath(sourcePrimIndexPath).GetPrototype(); const PcpPrimIndex* newPrimIndexForSource = &(stage->GetPrimAtPath(sourcePrimIndexPath).GetPrimIndex()); // Prototype's sourcePrimIndexPath is unchanged, and primIndex for this // prototype's source index should have been recomputed, since "/" change // would have triggered a pcpIndexRecompute for everything TF_VERIFY((prototypePrim.GetPath() == newPrototypePrim.GetPath()) && origPrimIndexForSource != newPrimIndexForSource); } /// Test to verify prototype for an instance is updated if its correspoding /// sourcePrim is updated because of parent being recomposed. void TestInstancing_2() { std::string rootLayer = "./secondRoot.usda"; // determine which instance to update UsdStageRefPtr stage = UsdStage::Open(rootLayer); const UsdPrim& prototypePrim = stage->GetPrimAtPath(SdfPath("/Ref1/instance1")).GetPrototype(); const SdfPath sourcePrimIndexPath = Usd_PrimGetSourcePrimIndex(prototypePrim).GetRootNode().GetPath(); const SdfPath& instancePathToUnset = (sourcePrimIndexPath.GetName() == "instance1") ? SdfPath("/Ref1/instance2") : SdfPath("/Ref1/instance1"); const PcpPrimIndex* origPrimIndexForSource = &(stage->GetPrimAtPath(sourcePrimIndexPath).GetPrimIndex()); SdfPrimSpecHandle ref1PrimSpec = stage->GetRootLayer()->GetPrimAtPath(SdfPath("/Ref1")); SdfPrimSpecHandle instancePrimToUnset = stage->GetRootLayer()->GetPrimAtPath(instancePathToUnset); SdfPrimSpecHandle dummyPrim = SdfCreatePrimInLayer(stage->GetRootLayer(), SdfPath("/dummy")); SdfReference dummyReference("", dummyPrim->GetPath()); // Test if a significant change in "/Ref1" triggers a rebuild of the // prototype since prior prim indexes for the source instance would have // been changed { SdfChangeBlock block; // unset instance instancePrimToUnset->SetInstanceable(false); // Add a reference to /ref1 to trigger a /ref1 change at pcp level ref1PrimSpec->GetReferenceList().Add(dummyReference); } const UsdPrim& newPrototypePrim = stage->GetPrimAtPath(sourcePrimIndexPath).GetPrototype(); const PcpPrimIndex* newPrimIndexForSource = &(stage->GetPrimAtPath(sourcePrimIndexPath).GetPrimIndex()); // Prototype's sourcePrimIndexPath is unchanged, and primIndex for this // prototype's source index should have been recomputed, since "/Ref1" // change would have triggered a pcpIndexRecompute because of the added // reference TF_VERIFY((prototypePrim.GetPath() == newPrototypePrim.GetPath()) && origPrimIndexForSource != newPrimIndexForSource); } /// Test to verify prototype is not updated when sourcePrim is corresponding to /// this is not updated, but parent of other instances is changed. void TestInstancing_3() { std::string rootLayer = "./thirdRoot.usda"; // determine which instance to update UsdStageRefPtr stage = UsdStage::Open(rootLayer); const UsdPrim& prototypePrim = stage->GetPrimAtPath(SdfPath("/Ref1/instance1")).GetPrototype(); const SdfPath& sourcePrimIndexPath = Usd_PrimGetSourcePrimIndex(prototypePrim).GetRootNode().GetPath(); SdfPath parentPathToRecompose = SdfPath("/Ref2"); if (sourcePrimIndexPath.HasPrefix(parentPathToRecompose)) { parentPathToRecompose = SdfPath("/Ref1"); } const PcpPrimIndex* origPrimIndexForSource = &(stage->GetPrimAtPath(sourcePrimIndexPath).GetPrimIndex()); SdfPrimSpecHandle refPrimSpec = stage->GetRootLayer()->GetPrimAtPath(parentPathToRecompose); SdfPrimSpecHandle dummyPrim = SdfCreatePrimInLayer(stage->GetRootLayer(), SdfPath("/dummy")); SdfReference dummyReference("", dummyPrim->GetPath()); { SdfChangeBlock block; // Add a reference to the parentPathToRecompose prim so as to trigger a // change in that prim, which does not hold sourceIndex for our // prototype refPrimSpec->GetReferenceList().Add(dummyReference); } const UsdPrim& newPrototypePrim = stage->GetPrimAtPath(sourcePrimIndexPath).GetPrototype(); const PcpPrimIndex* newPrimIndexForSource = &(stage->GetPrimAtPath(sourcePrimIndexPath).GetPrimIndex()); // Prototype's sourcePrimIndexPath is unchanged, and primIndex for this // prototype's source index should be same since we triggered a change // to the prim not containing our prototype's sourcePrim TF_VERIFY((prototypePrim.GetPath() == newPrototypePrim.GetPath()) && origPrimIndexForSource == newPrimIndexForSource); } int main() { TestInstancing_1(); TestInstancing_2(); TestInstancing_3(); }
37.143498
80
0.716045
DougRogers-DigitalFish
e78a81ecc6bce9fb6fd3c3a29b1da0dd0dec9615
33,645
cpp
C++
src/utilities/QuadratureUtil.cpp
chennachaos/stabfem
b3d1f44c45e354dc930203bda22efc800c377c6f
[ "MIT" ]
null
null
null
src/utilities/QuadratureUtil.cpp
chennachaos/stabfem
b3d1f44c45e354dc930203bda22efc800c377c6f
[ "MIT" ]
null
null
null
src/utilities/QuadratureUtil.cpp
chennachaos/stabfem
b3d1f44c45e354dc930203bda22efc800c377c6f
[ "MIT" ]
null
null
null
#include "QuadratureUtil.h" #include <iostream> #include <math.h> #include <assert.h> using namespace std; void getGaussPoints1D(int ngp, vector<double>& gausspoints, vector<double>& gaussweights) { //cout << " ngp = " << ngp << endl; gausspoints.resize(ngp); gaussweights.resize(ngp); switch(ngp) { case 1: // 1 Point quadrature rule gausspoints[0] = 0.0; gaussweights[0] = 2.0; break; case 2: //2 Point quadrature rule gausspoints[0] = -0.577350269189626; gaussweights[0] = 1.0; gausspoints[1] = 0.577350269189626; gaussweights[1] = 1.0; break; case 3: //3 Point quadrature rule gausspoints[0] = -0.774596669241483; gaussweights[0] = 5.0/9.0; gausspoints[1] = 0.0; gaussweights[1] = 8.0/9.0; gausspoints[2] = 0.774596669241483; gaussweights[2] = 5.0/9.0; break; case 4: //4 Point quadrature rule gausspoints[0] = -0.861136311594953; gaussweights[0] = 0.347854845137454; gausspoints[1] = -0.339981043584856; gaussweights[1] = 0.652145154862546; gausspoints[2] = 0.339981043584856; gaussweights[2] = 0.652145154862546; gausspoints[3] = 0.861136311594953; gaussweights[3] = 0.347854845137454; break; case 5: //5 Point quadrature rule gausspoints[0] = -0.906179845938664; gaussweights[0] = 0.236926885056189; gausspoints[1] = -0.538469310105683; gaussweights[1] = 0.478628670499366; gausspoints[2] = 0.0; gaussweights[2] = 0.568888888888889; gausspoints[3] = 0.538469310105683; gaussweights[3] = 0.478628670499366; gausspoints[4] = 0.906179845938664; gaussweights[4] = 0.236926885056189; break; case 6: //6 Point quadrature rule gausspoints[0] = -0.932469514203152; gaussweights[0] = 0.171324492379170; gausspoints[1] = -0.661209386466265; gaussweights[1] = 0.360761573048139; gausspoints[2] = -0.238619186083197; gaussweights[2] = 0.467913934572691; gausspoints[3] = 0.238619186083197; gaussweights[3] = 0.467913934572691; gausspoints[4] = 0.661209386466265; gaussweights[4] = 0.360761573048139; gausspoints[5] = 0.932469514203152; gaussweights[5] = 0.171324492379170; break; case 7: //7 Point quadrature rule gausspoints[0] = -0.9491079123427585245261897; gaussweights[0] = 0.1294849661688696932706114 ; gausspoints[1] = -0.7415311855993944398638648; gaussweights[1] = 0.2797053914892766679014678 ; gausspoints[2] = -0.4058451513773971669066064; gaussweights[2] = 0.3818300505051189449503698 ; gausspoints[3] = 0.0 ; gaussweights[3] = 0.4179591836734693877551020 ; gausspoints[4] = 0.4058451513773971669066064; gaussweights[4] = 0.3818300505051189449503698 ; gausspoints[5] = 0.7415311855993944398638648; gaussweights[5] = 0.2797053914892766679014678 ; gausspoints[6] = 0.9491079123427585245261897; gaussweights[6] = 0.1294849661688696932706114 ; break; case 8: //8 Point quadrature rule gausspoints[0] = -0.96028986; gaussweights[0] = 0.10122854 ; gausspoints[1] = -0.79666648; gaussweights[1] = 0.22238103 ; gausspoints[2] = -0.52553241; gaussweights[2] = 0.31370665 ; gausspoints[3] = -0.18343464; gaussweights[3] = 0.36268378 ; gausspoints[4] = 0.18343464; gaussweights[4] = 0.36268378 ; gausspoints[5] = 0.52553241; gaussweights[5] = 0.31370665 ; gausspoints[6] = 0.79666648; gaussweights[6] = 0.22238103 ; gausspoints[7] = 0.96028986; gaussweights[7] = 0.10122854 ; break; case 9: //9 Point quadrature rule gaussweights[0] = 0.0812743883615744; gausspoints[0] = -0.9681602395076261; gaussweights[1] = 0.1806481606948574; gausspoints[1] = -0.8360311073266358; gaussweights[2] = 0.2606106964029354; gausspoints[2] = -0.6133714327005904; gaussweights[3] = 0.3123470770400029; gausspoints[3] = -0.3242534234038089; gaussweights[4] = 0.3302393550012598; gausspoints[4] = 0.0000000000000000; gaussweights[5] = 0.3123470770400029; gausspoints[5] = 0.3242534234038089; gaussweights[6] = 0.2606106964029354; gausspoints[6] = 0.6133714327005904; gaussweights[7] = 0.1806481606948574; gausspoints[7] = 0.8360311073266358; gaussweights[8] = 0.0812743883615744; gausspoints[8] = 0.9681602395076261; case 10: //10 Point quadrature rule gaussweights[0] = 0.0666713443086881; gausspoints[0] = -0.9739065285171717; gaussweights[1] = 0.1494513491505806; gausspoints[1] = -0.8650633666889845; gaussweights[2] = 0.2190863625159820; gausspoints[2] = -0.6794095682990244; gaussweights[3] = 0.2692667193099963; gausspoints[3] = -0.4333953941292472; gaussweights[4] = 0.2955242247147529; gausspoints[4] = -0.1488743389816312; gaussweights[5] = 0.2955242247147529; gausspoints[5] = 0.1488743389816312; gaussweights[6] = 0.2692667193099963; gausspoints[6] = 0.4333953941292472; gaussweights[7] = 0.2190863625159820; gausspoints[7] = 0.6794095682990244; gaussweights[8] = 0.1494513491505806; gausspoints[8] = 0.8650633666889845; gaussweights[9] = 0.0666713443086881; gausspoints[9] = 0.9739065285171717; break; case 11: //11 Point quadrature rule gaussweights[0] = 0.0556685671161737; gausspoints[0] = -0.9782286581460570; gaussweights[1] = 0.1255803694649046; gausspoints[1] = -0.8870625997680953; gaussweights[2] = 0.1862902109277343; gausspoints[2] = -0.7301520055740494; gaussweights[3] = 0.2331937645919905; gausspoints[3] = -0.5190961292068118; gaussweights[4] = 0.2628045445102467; gausspoints[4] = -0.2695431559523450; gaussweights[5] = 0.2729250867779006; gausspoints[5] = 0.0000000000000000; gaussweights[6] = 0.2628045445102467; gausspoints[6] = 0.2695431559523450; gaussweights[7] = 0.2331937645919905; gausspoints[7] = 0.5190961292068118; gaussweights[8] = 0.1862902109277343; gausspoints[8] = 0.7301520055740494; gaussweights[9] = 0.1255803694649046; gausspoints[9] = 0.8870625997680953; gaussweights[10] = 0.0556685671161737; gausspoints[10] = 0.9782286581460570; break; case 12: //12 Point quadrature rule gaussweights[0] = 0.0471753363865118; gausspoints[0] = -0.9815606342467192; gaussweights[1] = 0.1069393259953184; gausspoints[1] = -0.9041172563704749; gaussweights[2] = 0.1600783285433462; gausspoints[2] = -0.7699026741943047; gaussweights[3] = 0.2031674267230659; gausspoints[3] = -0.5873179542866175; gaussweights[4] = 0.2334925365383548; gausspoints[4] = -0.3678314989981802; gaussweights[5] = 0.2491470458134028; gausspoints[5] = -0.1252334085114689; gaussweights[6] = 0.2491470458134028; gausspoints[6] = 0.1252334085114689; gaussweights[7] = 0.2334925365383548; gausspoints[7] = 0.3678314989981802; gaussweights[8] = 0.2031674267230659; gausspoints[8] = 0.5873179542866175; gaussweights[9] = 0.1600783285433462; gausspoints[9] = 0.7699026741943047; gaussweights[10] = 0.1069393259953184; gausspoints[10] = 0.9041172563704749; gaussweights[11] = 0.0471753363865118; gausspoints[11] = 0.9815606342467192; break; case 13: //13 Point quadrature rule gaussweights[0] = 0.0404840047653159; gausspoints[7] = -0.9841830547185881; gaussweights[1] = 0.0921214998377285; gausspoints[7] = -0.9175983992229779; gaussweights[2] = 0.1388735102197872; gausspoints[7] = -0.8015780907333099; gaussweights[3] = 0.1781459807619457; gausspoints[7] = -0.6423493394403402; gaussweights[4] = 0.2078160475368885; gausspoints[7] = -0.4484927510364469; gaussweights[5] = 0.2262831802628972; gausspoints[7] = -0.2304583159551348; gaussweights[6] = 0.2325515532308739; gausspoints[7] = 0.0000000000000000; gaussweights[7] = 0.2262831802628972; gausspoints[7] = 0.2304583159551348; gaussweights[8] = 0.2078160475368885; gausspoints[7] = 0.4484927510364469; gaussweights[9] = 0.1781459807619457; gausspoints[7] = 0.6423493394403402; gaussweights[10] = 0.1388735102197872; gausspoints[10] = 0.8015780907333099; gaussweights[11] = 0.0921214998377285; gausspoints[11] = 0.9175983992229779; gaussweights[12] = 0.0404840047653159; gausspoints[12] = 0.9841830547185881; break; case 14: //14 Point quadrature rule gaussweights[0] = 0.0351194603317519; gausspoints[0] = -0.9862838086968123; gaussweights[1] = 0.0801580871597602; gausspoints[1] = -0.9284348836635735; gaussweights[2] = 0.1215185706879032; gausspoints[2] = -0.8272013150697650; gaussweights[3] = 0.1572031671581935; gausspoints[3] = -0.6872929048116855; gaussweights[4] = 0.1855383974779378; gausspoints[4] = -0.5152486363581541; gaussweights[5] = 0.2051984637212956; gausspoints[5] = -0.3191123689278897; gaussweights[6] = 0.2152638534631578; gausspoints[6] = -0.1080549487073437; gaussweights[7] = 0.2152638534631578; gausspoints[7] = 0.1080549487073437; gaussweights[8] = 0.2051984637212956; gausspoints[8] = 0.3191123689278897; gaussweights[9] = 0.1855383974779378; gausspoints[9] = 0.5152486363581541; gaussweights[10] = 0.1572031671581935; gausspoints[10] = 0.6872929048116855; gaussweights[11] = 0.1215185706879032; gausspoints[11] = 0.8272013150697650; gaussweights[12] = 0.0801580871597602; gausspoints[12] = 0.9284348836635735; gaussweights[13] = 0.0351194603317519; gausspoints[13] = 0.9862838086968123; break; case 15: //15 Point quadrature rule gaussweights[0] = 0.0307532419961173; gausspoints[0] = -0.9879925180204854; gaussweights[1] = 0.0703660474881081; gausspoints[1] = -0.9372733924007060; gaussweights[2] = 0.1071592204671719; gausspoints[2] = -0.8482065834104272; gaussweights[3] = 0.1395706779261543; gausspoints[3] = -0.7244177313601701; gaussweights[4] = 0.1662692058169939; gausspoints[4] = -0.5709721726085388; gaussweights[5] = 0.1861610000155622; gausspoints[5] = -0.3941513470775634; gaussweights[6] = 0.1984314853271116; gausspoints[6] = -0.2011940939974345; gaussweights[7] = 0.2025782419255613; gausspoints[7] = 0.0000000000000000; gaussweights[8] = 0.1984314853271116; gausspoints[8] = 0.2011940939974345; gaussweights[9] = 0.1861610000155622; gausspoints[9] = 0.3941513470775634; gaussweights[10] = 0.1662692058169939; gausspoints[10] = 0.5709721726085388; gaussweights[11] = 0.1395706779261543; gausspoints[11] = 0.7244177313601701; gaussweights[12] = 0.1071592204671719; gausspoints[12] = 0.8482065834104272; gaussweights[13] = 0.0703660474881081; gausspoints[13] = 0.9372733924007060; gaussweights[14] = 0.0307532419961173; gausspoints[14] = 0.9879925180204854; break; default: cerr << " invalid value of 'ngp' ! " << endl; break; } return; } void getGaussPointsQuad(int ngp, vector<double>& gps1, vector<double>& gps2, vector<double>& gws) { gps1.resize(ngp); gps2.resize(ngp); gws.resize(ngp); int nn=0; if(ngp == 1) nn = 1; else if(ngp == 4) nn = 2; else if(ngp == 9) nn = 3; else if(ngp == 16) nn = 4; else { cerr << " Error in getGaussPointsQuad() ... ngp = " << ngp << endl; } vector<double> gpoints1, gweights1; getGaussPoints1D(nn, gpoints1, gweights1); int ind=0, ii, jj; for(jj=0; jj<nn; jj++) { for(ii=0; ii<nn; ii++) { gps1[ind] = gpoints1[ii]; gps2[ind] = gpoints1[jj]; gws[ind] = gweights1[jj]*gweights1[ii]; ind++; } } return; } void getGaussPointsHexa(int ngp, vector<double>& gp1, vector<double>& gp2, vector<double>& gp3, vector<double>& gws) { int nn=0; if(ngp == 1) nn = 1; else if(ngp == 8) nn = 2; else if(ngp == 27) nn = 3; else if(ngp == 64) nn = 4; else { cerr << " Error in getGaussPointsHex ... ngp = " << ngp << endl; } gp1.resize(ngp); gp2.resize(ngp); gp3.resize(ngp); gws.resize(ngp); vector<double> gpoints1, gweights1; getGaussPoints1D(nn, gpoints1, gweights1); int ind=0, ii, jj, kk; for(kk=0; kk<nn; kk++) { for(jj=0; jj<nn; jj++) { for(ii=0; ii<nn; ii++) { gp1[ind] = gpoints1[ii]; gp2[ind] = gpoints1[jj]; gp3[ind] = gpoints1[kk]; gws[ind] = gweights1[kk]*gweights1[jj]*gweights1[ii]; ind++; } } } return; } void getGaussPointsTriangle(int ngp, vector<double>& gps1, vector<double>& gps2, vector<double>& gws) { // weights are normalized to calculate the exact area of the triangle // i.e. each weight is divided by 2.0 double r1d3 = 1.0/3.0, a1, fact=0.5; gps1.resize(ngp); gps2.resize(ngp); gws.resize(ngp); switch(ngp) { case 1: // 1 Point quadrature rule gps1[0] = r1d3; gps2[0] = r1d3; gws[0] = fact*1.0; break; case 3: //3 Point quadrature rule a1 = 1.0/3.0; gps1[0] = 1.0/6.0; gps2[0] = 1.0/6.0; gws[0] = fact*a1; gps1[1] = 4.0/6.0; gps2[1] = 1.0/6.0; gws[1] = fact*a1; gps1[2] = 1.0/6.0; gps2[2] = 4.0/6.0; gws[2] = fact*a1; break; case 4: //4 Point quadrature rule a1 = 25.0/48.0; gps1[0] = r1d3; gps2[0] = r1d3; gws[0] = fact*(-27.0/48.0); gps1[1] = 0.6; gps2[1] = 0.2; gws[1] = fact*a1; gps1[2] = 0.2; gps2[2] = 0.6; gws[2] = fact*a1; gps1[3] = 0.2; gps2[3] = 0.2; gws[3] = fact*a1; break; case 6: //6 Point quadrature rule gps1[0] = 0.10810301816807022736; gps2[0] = 0.44594849091596488632; gws[0] = fact*0.22338158967801146570; gps1[1] = 0.44594849091596488632; gps2[1] = 0.10810301816807022736; gws[1] = fact*0.22338158967801146570; gps1[2] = 0.44594849091596488632; gps2[2] = 0.44594849091596488632; gws[2] = fact*0.22338158967801146570; gps1[3] = 0.81684757298045851308; gps2[3] = 0.09157621350977074346; gws[3] = fact*0.10995174365532186764; gps1[4] = 0.09157621350977074346; gps2[4] = 0.81684757298045851308; gws[4] = fact*0.10995174365532186764; gps1[5] = 0.09157621350977074346; gps2[5] = 0.09157621350977074346; gws[5] = fact*0.10995174365532186764; break; case 7: //7 Point quadrature rule gps1[0] = r1d3; gps2[0] = r1d3; gws[0] = fact*0.225; gps1[1] = 0.79742698535308732240; gps2[1] = 0.10128650732345633880; gws[1] = fact*0.12593918054482715260; gps1[2] = 0.10128650732345633880; gps2[2] = 0.79742698535308732240; gws[2] = fact*0.12593918054482715260; gps1[3] = 0.10128650732345633880; gps2[3] = 0.10128650732345633880; gws[3] = fact*0.12593918054482715260; gps1[4] = 0.05971587178976982045; gps2[4] = 0.47014206410511508977; gws[4] = fact*0.13239415278850618074; gps1[5] = 0.47014206410511508977; gps2[5] = 0.05971587178976982045; gws[5] = fact*0.13239415278850618074; gps1[6] = 0.47014206410511508977; gps2[6] = 0.47014206410511508977; gws[6] = fact*0.13239415278850618074; break; case 12: //12 Point quadrature rule gps1[0] = 0.87382197101699554332; gps2[0] = 0.06308901449150222834; gws[0] = fact*0.050844906370206816921; gps1[1] = 0.06308901449150222834; gps2[1] = 0.87382197101699554332; gws[1] = fact*0.050844906370206816921; gps1[2] = 0.06308901449150222834; gps2[2] = 0.06308901449150222834; gws[2] = fact*0.050844906370206816921; gps1[3] = 0.50142650965817915742; gps2[3] = 0.24928674517091042129; gws[3] = fact*0.116786275726379366030; gps1[4] = 0.24928674517091042129; gps2[4] = 0.50142650965817915742; gws[4] = fact*0.116786275726379366030; gps1[5] = 0.24928674517091042129; gps2[5] = 0.24928674517091042129; gws[5] = fact*0.116786275726379366030; gps1[6] = 0.05314504984481694735; gps2[6] = 0.31035245103378440542; gws[6] = fact*0.082851075618373575194; gps1[7] = 0.31035245103378440542; gps2[7] = 0.05314504984481694735; gws[7] = fact*0.082851075618373575194; gps1[8] = 0.05314504984481694735; gps2[8] = 0.63650249912139864723; gws[8] = fact*0.082851075618373575194; gps1[9] = 0.31035245103378440542; gps2[9] = 0.63650249912139864723; gws[9] = fact*0.082851075618373575194; gps1[10] = 0.63650249912139864723; gps2[10] = 0.05314504984481694735; gws[10] = fact*0.082851075618373575194; gps1[11] = 0.63650249912139864723; gps2[11] = 0.31035245103378440542; gws[11] = fact*0.082851075618373575194; break; case 13: // 13 point quadrature rule gps1[0] = 0.33333333333333; gps2[0] = 0.33333333333333; gws[0] = fact*-0.14957004446768; gps1[1] = 0.26034596607904; gps2[1] = 0.26034596607904; gws[1] = fact* 0.17561525743321; gps1[2] = 0.26034596607904; gps2[2] = 0.47930806784192; gws[2] = fact* 0.17561525743321; gps1[3] = 0.47930806784192; gps2[3] = 0.26034596607904; gws[3] = fact* 0.17561525743321; gps1[4] = 0.06513010290222; gps2[4] = 0.06513010290222; gws[4] = fact* 0.05334723560884; gps1[5] = 0.06513010290222; gps2[5] = 0.86973979419557; gws[5] = fact* 0.05334723560884; gps1[6] = 0.86973979419557; gps2[6] = 0.06513010290222; gws[6] = fact* 0.05334723560884; gps1[7] = 0.31286549600487; gps2[7] = 0.63844418856981; gws[7] = fact* 0.07711376089026; gps1[8] = 0.63844418856981; gps2[8] = 0.04869031542532; gws[8] = fact* 0.07711376089026; gps1[9] = 0.04869031542532; gps2[9] = 0.31286549600487; gws[9] = fact* 0.07711376089026; gps1[10] = 0.63844418856981; gps2[10] = 0.31286549600487; gws[10] = fact* 0.07711376089026; gps1[11] = 0.31286549600487; gps2[11] = 0.04869031542532; gws[11] = fact* 0.07711376089026; gps1[12] = 0.04869031542532; gps2[12] = 0.63844418856981; gws[12] = fact* 0.07711376089026; break; case 16: // 16 point quadrature rule gps1[0] = 0.33333333333333; gps2[0] = 0.33333333333333; gws[0] = fact* 0.14431560767779; gps1[1] = 0.45929258829272; gps2[1] = 0.45929258829272; gws[1] = fact* 0.09509163426728; gps1[2] = 0.45929258829272; gps2[2] = 0.08141482341455; gws[2] = fact* 0.09509163426728; gps1[3] = 0.08141482341455; gps2[3] = 0.45929258829272; gws[3] = fact* 0.09509163426728; gps1[4] = 0.17056930775176; gps2[4] = 0.17056930775176; gws[4] = fact* 0.10321737053472; gps1[5] = 0.17056930775176; gps2[5] = 0.65886138449648; gws[5] = fact* 0.10321737053472; gps1[6] = 0.65886138449648; gps2[6] = 0.17056930775176; gws[6] = fact* 0.10321737053472; gps1[7] = 0.05054722831703; gps2[7] = 0.05054722831703; gws[7] = fact* 0.03245849762320; gps1[8] = 0.05054722831703; gps2[8] = 0.89890554336594; gws[8] = fact* 0.03245849762320; gps1[9] = 0.89890554336594; gps2[9] = 0.05054722831703; gws[9] = fact* 0.03245849762320; gps1[10] = 0.26311282963464; gps2[10] = 0.72849239295540; gws[10] = fact* 0.02723031417443; gps1[11] = 0.72849239295540; gps2[11] = 0.00839477740996; gws[11] = fact* 0.02723031417443; gps1[12] = 0.00839477740996; gps2[12] = 0.26311282963464; gws[12] = fact* 0.02723031417443; gps1[13] = 0.72849239295540; gps2[13] = 0.26311282963464; gws[13] = fact* 0.02723031417443; gps1[14] = 0.26311282963464; gps2[14] = 0.00839477740996; gws[14] = fact* 0.02723031417443; gps1[15] = 0.00839477740996; gps2[15] = 0.72849239295540; gws[15] = fact* 0.02723031417443; break; default: cerr << " invalid value of 'ngp' in getGaussPointsTriangle ! " << endl; break; } return; } void getGaussPointsTetra(int ngp, vector<double>& gps1, vector<double>& gps2, vector<double>& gps3, vector<double>& gws) { double fact=1.0/6.0; gps1.resize(ngp); gps2.resize(ngp); gps3.resize(ngp); gws.resize(ngp); switch(ngp) { case 1: // 1 Point quadrature rule gps1[0] = 0.25; gps2[0] = 0.25; gps3[0] = 0.25; gws[0] = fact; break; case 4: // N=4 gps1[0] = 0.1381966011250105; gps1[1] = 0.5854101966249685; gps1[2] = 0.1381966011250105; gps1[3] = 0.1381966011250105; gps2[0] = 0.1381966011250105; gps2[1] = 0.1381966011250105; gps2[2] = 0.5854101966249685; gps2[3] = 0.1381966011250105; gps3[0] = 0.1381966011250105; gps3[1] = 0.1381966011250105; gps3[2] = 0.1381966011250105; gps3[3] = 0.5854101966249685; gws[0] = 0.2500000000000000*fact; gws[1] = 0.2500000000000000*fact; gws[2] = 0.2500000000000000*fact; gws[3] = 0.2500000000000000*fact; break; case 5: // N=5 gps1[0] = 0.2500000000000000; gps1[1] = 0.5000000000000000; gps1[2] = 0.1666666666666667; gps1[3] = 0.1666666666666667; gps1[4] = 0.1666666666666667; gps2[0] = 0.2500000000000000; gps2[1] = 0.1666666666666667; gps2[2] = 0.1666666666666667; gps2[3] = 0.1666666666666667; gps2[4] = 0.5000000000000000; gps3[0] = 0.2500000000000000; gps3[1] = 0.1666666666666667; gps3[2] = 0.1666666666666667; gps3[3] = 0.5000000000000000; gps3[4] = 0.1666666666666667; gws[0] = -0.8000000000000000*fact; gws[1] = 0.4500000000000000*fact; gws[2] = 0.4500000000000000*fact; gws[3] = 0.4500000000000000*fact; gws[4] = 0.4500000000000000*fact; break; case 8: // N=8 gps1[0] = 0.01583591; gps1[1] = 0.328054697; gps1[2] = 0.328054697; gps1[3] = 0.328054697; gps1[4] = 0.679143178; gps1[5] = 0.106952274; gps1[6] = 0.106952274; gps1[7] = 0.106952274; gps2[0] = 0.328054697; gps2[1] = 0.01583591; gps2[2] = 0.328054697; gps2[3] = 0.328054697; gps2[4] = 0.106952274; gps2[5] = 0.679143178; gps2[6] = 0.106952274; gps2[7] = 0.106952274; gps3[0] = 0.328054697; gps3[1] = 0.328054697; gps3[2] = 0.01583591; gps3[3] = 0.328054697; gps3[4] = 0.106952274; gps3[5] = 0.106952274; gps3[6] = 0.679143178; gps3[7] = 0.106952274; gws[0] = 0.023087995; gws[1] = 0.023087995; gws[2] = 0.023087995; gws[3] = 0.023087995; gws[4] = 0.018578672; gws[5] = 0.018578672; gws[6] = 0.018578672; gws[7] = 0.018578672; break; case 11: // N=11 gps1[0] = 0.2500000000000000; gps1[1] = 0.7857142857142857; gps1[2] = 0.0714285714285714; gps1[3] = 0.0714285714285714; gps1[4] = 0.0714285714285714; gps1[5] = 0.1005964238332008; gps1[6] = 0.3994035761667992; gps1[7] = 0.3994035761667992; gps1[8] = 0.3994035761667992; gps1[9] = 0.1005964238332008; gps1[10] = 0.1005964238332008; gps2[0] = 0.2500000000000000; gps2[1] = 0.0714285714285714; gps2[2] = 0.0714285714285714; gps2[3] = 0.0714285714285714; gps2[4] = 0.7857142857142857; gps2[5] = 0.3994035761667992; gps2[6] = 0.1005964238332008; gps2[7] = 0.3994035761667992; gps2[8] = 0.1005964238332008; gps2[9] = 0.3994035761667992; gps2[10] = 0.1005964238332008; gps3[0] = 0.2500000000000000; gps3[1] = 0.0714285714285714; gps3[2] = 0.0714285714285714; gps3[3] = 0.7857142857142857; gps3[4] = 0.0714285714285714; gps3[5] = 0.3994035761667992; gps3[6] = 0.3994035761667992; gps3[7] = 0.1005964238332008; gps3[8] = 0.1005964238332008; gps3[9] = 0.1005964238332008; gps3[10] = 0.3994035761667992; gws[0] = -0.0789333333333333*fact; gws[1] = 0.0457333333333333*fact; gws[2] = 0.0457333333333333*fact; gws[3] = 0.0457333333333333*fact; gws[4] = 0.0457333333333333*fact; gws[5] = 0.1493333333333333*fact; gws[6] = 0.1493333333333333*fact; gws[7] = 0.1493333333333333*fact; gws[8] = 0.1493333333333333*fact; gws[9] = 0.1493333333333333*fact; gws[10] = 0.1493333333333333*fact; break; case 15: // N=15 gps1[0] = 0.2500000000000000; gps1[1] = 0.0000000000000000; gps1[2] = 0.3333333333333333; gps1[3] = 0.3333333333333333; gps1[4] = 0.3333333333333333; gps1[5] = 0.7272727272727273; gps1[6] = 0.0909090909090909; gps1[7] = 0.0909090909090909; gps1[8] = 0.0909090909090909; gps1[9] = 0.4334498464263357; gps1[10] = 0.0665501535736643; gps1[11] = 0.0665501535736643; gps1[12] = 0.0665501535736643; gps1[13] = 0.4334498464263357; gps1[14] = 0.4334498464263357; gps2[0] = 0.2500000000000000; gps2[1] = 0.3333333333333333; gps2[2] = 0.3333333333333333; gps2[3] = 0.3333333333333333; gps2[4] = 0.0000000000000000; gps2[5] = 0.0909090909090909; gps2[6] = 0.0909090909090909; gps2[7] = 0.0909090909090909; gps2[8] = 0.7272727272727273; gps2[9] = 0.0665501535736643; gps2[10] = 0.4334498464263357; gps2[11] = 0.0665501535736643; gps2[12] = 0.4334498464263357; gps2[13] = 0.0665501535736643; gps2[14] = 0.4334498464263357; gps3[0] = 0.2500000000000000; gps3[1] = 0.3333333333333333; gps3[2] = 0.3333333333333333; gps3[3] = 0.0000000000000000; gps3[4] = 0.3333333333333333; gps3[5] = 0.0909090909090909; gps3[6] = 0.0909090909090909; gps3[7] = 0.7272727272727273; gps3[8] = 0.0909090909090909; gps3[9] = 0.0665501535736643; gps3[10] = 0.0665501535736643; gps3[11] = 0.4334498464263357; gps3[12] = 0.4334498464263357; gps3[13] = 0.4334498464263357; gps3[14] = 0.0665501535736643; gws[0] = 0.1817020685825351*fact; gws[1] = 0.0361607142857143*fact; gws[2] = 0.0361607142857143*fact; gws[3] = 0.0361607142857143*fact; gws[4] = 0.0361607142857143*fact; gws[5] = 0.0698714945161738*fact; gws[6] = 0.0698714945161738*fact; gws[7] = 0.0698714945161738*fact; gws[8] = 0.0698714945161738*fact; gws[9] = 0.0656948493683187*fact; gws[10] = 0.0656948493683187*fact; gws[11] = 0.0656948493683187*fact; gws[12] = 0.0656948493683187*fact; gws[13] = 0.0656948493683187*fact; gws[14] = 0.0656948493683187*fact; break; default: cerr << " invalid value of 'ngp' in getGaussPointsTet() ! " << '\t' << ngp << endl; break; } return; } void getLobattoPoints(int ngp, vector<double>& gausspoints, vector<double>& gaussweights) { char fct[] = "getGaussPoints"; switch(ngp) { case 2: //2 Point quadrature rule gausspoints.resize(2); gaussweights.resize(2); gausspoints[0] = -1.0; gaussweights[0] = 1.0; gausspoints[1] = 1.0; gaussweights[1] = 1.0; break; case 3: //3 Point quadrature rule gausspoints.resize(3); gaussweights.resize(3); gausspoints[0] = -1.0; gaussweights[0] = 0.333333333333; gausspoints[1] = 0.0; gaussweights[1] = 1.333333333333; gausspoints[2] = 1.0; gaussweights[2] = 0.333333333333; break; case 4: //4 Point quadrature rule gausspoints.resize(4); gaussweights.resize(4); gausspoints[0] = -1.0; gaussweights[0] = 1.0/6.0; gausspoints[1] = -0.447213595500; gaussweights[1] = 5.0/6.0; gausspoints[2] = 0.447213595500; gaussweights[2] = 5.0/6.0; gausspoints[3] = 1.0; gaussweights[3] = 1.0/6.0; break; case 5: //5 Point quadrature rule gausspoints.resize(5); gaussweights.resize(5); gausspoints[0] = -1.0; gaussweights[0] = 0.1; gausspoints[1] = -0.654653670708; gaussweights[1] = 0.54444444444; gausspoints[2] = 0.0; gaussweights[2] = 0.71111111111; gausspoints[3] = 0.654653670708; gaussweights[3] = 0.54444444444; gausspoints[4] = 1.0; gaussweights[4] = 0.1; break; default: cerr << " getGaussPoints1D()... invalid value of 'ngp' ! " << endl; break; } return; } void getGaussPointsPrism(int ngp, vector<double>& gps1, vector<double>& gps2, vector<double>& gps3, vector<double>& gws) { // weights are normalized to calculate the exact area of the triangle // i.e. each weight is divided by 2.0 double r1d3 = 1.0/3.0, a1, r1d2=0.5, fact; gps1.resize(ngp); gps2.resize(ngp); gps3.resize(ngp); gws.resize(ngp); switch(ngp) { // 1 Point quadrature rule - 1 for triangle, 1 for the quad case 1: gps1[0] = r1d3; gps2[0] = r1d3; gps3[0] = 0.0; gws[0] = r1d2*2.0; // 2.0 for the weight in the normal direction break; // 2 Point quadrature rule - 1 for triangle, 2 for the quad case 2: //2 Point quadrature rule gps1[0] = r1d3; gps2[0] = r1d3; gps3[0] = -0.577350269189626; gws[0] = r1d2*1.0; gps1[1] = r1d3; gps2[1] = r1d3; gps3[1] = 0.577350269189626; gws[1] = r1d2*1.0; break; // 3 Point quadrature rule - 3 for triangle, 1 for the quad case 3: //3 Point quadrature rule fact = r1d2*r1d3*2.0; gps1[0] = 1.0/6.0; gps2[0] = 1.0/6.0; gps3[0] = 0.0; gws[0] = fact; gps1[1] = 1.0/6.0; gps2[1] = 4.0/6.0; gps3[1] = 0.0; gws[1] = fact; gps1[2] = 4.0/6.0; gps2[2] = 1.0/6.0; gps3[2] = 0.0; gws[2] = fact; break; // 6 Point quadrature rule - 3 for triangle, 2 for the quad case 6: //6 Point quadrature rule fact = r1d2*r1d3*1.0; gps1[0] = 1.0/6.0; gps2[0] = 1.0/6.0; gps3[0] = -0.577350269189626; gws[0] = fact; gps1[1] = 1.0/6.0; gps2[1] = 4.0/6.0; gps3[1] = -0.577350269189626; gws[1] = fact; gps1[2] = 4.0/6.0; gps2[2] = 1.0/6.0; gps3[2] = -0.577350269189626; gws[2] = fact; gps1[3] = 1.0/6.0; gps2[3] = 1.0/6.0; gps3[3] = 0.577350269189626; gws[3] = fact; gps1[4] = 1.0/6.0; gps2[4] = 4.0/6.0; gps3[4] = 0.577350269189626; gws[4] = fact; gps1[5] = 4.0/6.0; gps2[5] = 1.0/6.0; gps3[5] = 0.577350269189626; gws[5] = fact; break; default: cerr << " invalid value of 'ngp' in getGaussPointsPrism ! " << endl; break; } return; } void getGaussPointsPyramid(int ngp, vector<double>& gps1, vector<double>& gps2, vector<double>& gps3, vector<double>& gws) { gps1.resize(ngp); gps2.resize(ngp); gps3.resize(ngp); gws.resize(ngp); switch(ngp) { // 1 Point quadrature rule case 1: gps1[0] = 0.0; gps2[0] = 0.0; gps3[0] = -0.5; gws[0] = 128.0/27.0; break; default: cerr << " invalid value of 'ngp' in getGaussPointsPyramid ! " << endl; break; } return; }
38.407534
123
0.580205
chennachaos
e78a973ae6efaf290a7a8194e5fc183ed541bc7f
7,155
cpp
C++
src/IntaRNA/InteractionEnergyVrna.cpp
fabio-gut/IntaRNA
034bb1427673eda5b611dffdba37f464e1bb2835
[ "MIT" ]
null
null
null
src/IntaRNA/InteractionEnergyVrna.cpp
fabio-gut/IntaRNA
034bb1427673eda5b611dffdba37f464e1bb2835
[ "MIT" ]
1
2019-06-27T07:39:05.000Z
2019-06-27T11:10:52.000Z
src/IntaRNA/InteractionEnergyVrna.cpp
fabio-gut/IntaRNA
034bb1427673eda5b611dffdba37f464e1bb2835
[ "MIT" ]
null
null
null
#include "IntaRNA/InteractionEnergyVrna.h" #include <cassert> #include <set> // ES computation extern "C" { #include <ViennaRNA/fold_vars.h> #include <ViennaRNA/fold.h> #include <ViennaRNA/part_func.h> #include <ViennaRNA/structure_utils.h> #include <ViennaRNA/utils.h> } namespace IntaRNA { //////////////////////////////////////////////////////////////////////////// InteractionEnergyVrna::InteractionEnergyVrna( const Accessibility & accS1 , const ReverseAccessibility & accS2 , VrnaHandler &vrnaHandler , const size_t maxInternalLoopSize1 , const size_t maxInternalLoopSize2 , const bool initES ) : InteractionEnergy(accS1, accS2, maxInternalLoopSize1, maxInternalLoopSize2) // get final VRNA folding parameters , foldModel( vrnaHandler.getModel() ) , foldParams( vrna_params( &foldModel ) ) , RT(vrnaHandler.getRT()) , bpCG( BP_pair[RnaSequence::getCodeForChar('C')][RnaSequence::getCodeForChar('G')] ) , bpGC( BP_pair[RnaSequence::getCodeForChar('G')][RnaSequence::getCodeForChar('C')] ) , esValues1(NULL) , esValues2(NULL) { vrna_md_defaults_reset( &foldModel ); // init ES values if needed if (initES) { // 23.11.2017 : should not be relevant anymore //#if INTARNA_MULITHREADING // #pragma omp critical(intarna_omp_callingVRNA) //#endif // { // create ES container to be filled esValues1 = new EsMatrix(); esValues2 = new EsMatrix(); // fill ES container computeES( accS1, *esValues1 ); computeES( accS2, *esValues2 ); // } // omp critical(intarna_omp_callingVRNA) } } //////////////////////////////////////////////////////////////////////////// InteractionEnergyVrna::~InteractionEnergyVrna() { // garbage collection if (foldParams != NULL) { free(foldParams); foldParams = NULL; } INTARNA_CLEANUP(esValues1); INTARNA_CLEANUP(esValues2); } //////////////////////////////////////////////////////////////////////////// E_type InteractionEnergyVrna:: getBestE_interLoop() const { // TODO maybe setup member variable (init=E_INF) with lazy initialization // get all possible base pair codes handled std::set<int> basePairCodes; for (int i=0; i<NBASES; i++) { for (int j=0; j<NBASES; j++) { if (BP_pair[i][j] != 0) { basePairCodes.insert( BP_pair[i][j] ); } } } // get minimal energy for any base pair code combination E_type minStackingE = E_INF; for (std::set<int>::const_iterator p1=basePairCodes.begin(); p1!=basePairCodes.end(); p1++) { for (std::set<int>::const_iterator p2=basePairCodes.begin(); p2!=basePairCodes.end(); p2++) { minStackingE = std::min( minStackingE , (E_type)E_IntLoop( 0 // unpaired region 1 , 0 // unpaired region 2 , *p1 // type BP (i1,i2) , *p2 // type BP (j2,j1) , 0 , 0 , 0 , 0 , foldParams) // correct from dcal/mol to kcal/mol / (E_type)100.0 ); } } return minStackingE; } //////////////////////////////////////////////////////////////////////////// E_type InteractionEnergyVrna:: getBestE_dangling() const { // TODO maybe setup member variable (init=E_INF) with lazy initialization // get all possible base pair codes handled std::set<int> basePairCodes; for (int i=0; i<NBASES; i++) { for (int j=0; j<NBASES; j++) { basePairCodes.insert( BP_pair[i][j] ); } } // get minimal energy for any base pair code combination E_type minDangleE = std::numeric_limits<E_type>::infinity(); // get codes for the sequence alphabet const RnaSequence::CodeSeq_type alphabet = RnaSequence::getCodeForString(RnaSequence::SequenceAlphabet); // get minimal for (std::set<int>::const_iterator p1=basePairCodes.begin(); p1!=basePairCodes.end(); p1++) { for (size_t i=0; i<alphabet.size(); i++) { for (size_t j=0; j<alphabet.size(); j++) { minDangleE = std::min( minDangleE , (E_type)E_Stem( *p1 , alphabet.at(i) , alphabet.at(j) , 1 // is an external loop , foldParams ) // correct from dcal/mol to kcal/mol / (E_type)100.0 ); } } } return minDangleE; } //////////////////////////////////////////////////////////////////////////// void InteractionEnergyVrna:: computeES( const Accessibility & acc, InteractionEnergyVrna::EsMatrix & esToFill ) { // prepare container esToFill.resize( acc.getSequence().size(), acc.getSequence().size() ); // sequence length const int seqLength = (int)acc.getSequence().size(); const E_type RT = getRT(); // VRNA compatible data structures char * sequence = (char *) vrna_alloc(sizeof(char) * (seqLength + 1)); char * structureConstraint = (char *) vrna_alloc(sizeof(char) * (seqLength + 1)); for (int i=0; i<seqLength; i++) { // copy sequence sequence[i] = acc.getSequence().asString().at(i); // copy accessibility constraint if present structureConstraint[i] = acc.getAccConstraint().getVrnaDotBracket(i); } sequence[seqLength] = structureConstraint[seqLength] = '\0'; // prepare folding data vrna_md_t curModel; vrna_md_copy( &curModel, &foldModel ); // set maximal base pair span curModel.max_bp_span = acc.getAccConstraint().getMaxBpSpan(); if (curModel.max_bp_span >= (int)acc.getSequence().size()) { curModel.max_bp_span = -1; } // TODO check if VRNA_OPTION_WINDOW reasonable to speedup vrna_fold_compound_t * foldData = vrna_fold_compound( sequence, &foldModel, VRNA_OPTION_PF); // Adding hard constraints from pseudo dot-bracket unsigned int constraint_options = VRNA_CONSTRAINT_DB_DEFAULT; // enforce constraints constraint_options |= VRNA_CONSTRAINT_DB_ENFORCE_BP; vrna_constraints_add( foldData, (const char *)structureConstraint, constraint_options); // compute correct partition function scaling via mfe FLT_OR_DBL min_free_energy = vrna_mfe( foldData, NULL ); vrna_exp_params_rescale( foldData, &min_free_energy); // compute partition functions const float ensembleE = vrna_pf( foldData, NULL ); if (foldData->exp_matrices == NULL) { throw std::runtime_error("AccessibilityVrna::computeES() : partition functions after computation not available"); } if (foldData->exp_matrices->qm == NULL) { throw std::runtime_error("AccessibilityVrna::computeES() : partition functions Qm after computation not available"); } // copy ensemble energies of multi loop parts = ES values FLT_OR_DBL qm_val = 0.0; const int minLoopSubseqLength = foldModel.min_loop_size + 2; for (int i=0; i<seqLength; i++) { for (int j=i; j<seqLength; j++) { // check if too short to enable a base pair if (j-i+1 < minLoopSubseqLength) { // make unfavorable esToFill(i,j) = E_INF; } else { // get Qm value // indexing via iindx starts with 1 instead of 0 qm_val = foldData->exp_matrices->qm[foldData->iindx[i+1]-j+1]; if ( E_equal(qm_val, 0.) ) { esToFill(i,j) = E_INF; } else { // ES energy = -RT*log( Qm ) esToFill(i,j) = (E_type)( - RT*( std::log(qm_val) +((FLT_OR_DBL)(j-i+1))*std::log(foldData->exp_params->pf_scale))); } } } } // garbage collection vrna_fold_compound_free(foldData); free(structureConstraint); free(sequence); } //////////////////////////////////////////////////////////////////////////// } // namespace
29.085366
118
0.647939
fabio-gut
e78c5b5141258512a2b1569e23b3c19418c75d1f
497
cpp
C++
AcWing/LeetCode究极班/565.cpp
LauZyHou/-
66c047fe68409c73a077eae561cf82b081cf8e45
[ "MIT" ]
7
2019-02-25T13:15:00.000Z
2021-12-21T22:08:39.000Z
AcWing/LeetCode究极班/565.cpp
LauZyHou/-
66c047fe68409c73a077eae561cf82b081cf8e45
[ "MIT" ]
null
null
null
AcWing/LeetCode究极班/565.cpp
LauZyHou/-
66c047fe68409c73a077eae561cf82b081cf8e45
[ "MIT" ]
1
2019-04-03T06:12:46.000Z
2019-04-03T06:12:46.000Z
class Solution { public: int arrayNesting(vector<int>& nums) { int res = 0; for (int i = 0; i < nums.size(); i ++ ) { if (nums[i] != -1) { int j = i, s = 0; // 对没遍历过的点遍历一下环 while (nums[j] != -1) { s ++ ; int next = nums[j]; nums[j] = -1; j = next; } res = max(res, s); } } return res; } };
26.157895
49
0.307847
LauZyHou
e78da99d3ff6a31a9e2a9cb5a3caf8571c98626c
1,050
cpp
C++
core/connection.cpp
shakthi-prashanth-m/DroneCore
63f204beab14d3305068db17b8f7968bfddf39aa
[ "BSD-3-Clause" ]
1
2019-06-16T23:50:37.000Z
2019-06-16T23:50:37.000Z
core/connection.cpp
peterbarker/DroneCore
d0c47bb3c749738feb9d04db807e9fba93c7688e
[ "BSD-3-Clause" ]
null
null
null
core/connection.cpp
peterbarker/DroneCore
d0c47bb3c749738feb9d04db807e9fba93c7688e
[ "BSD-3-Clause" ]
null
null
null
#include "connection.h" #include "dronecore_impl.h" #include "mavlink_channels.h" #include "global_include.h" namespace dronecore { Connection::Connection(DroneCoreImpl &parent) : _parent(parent), _mavlink_receiver() {} Connection::~Connection() { // Just in case a specific connection didn't call it already. stop_mavlink_receiver(); } bool Connection::start_mavlink_receiver() { uint8_t channel; if (!MAVLinkChannels::Instance().checkout_free_channel(channel)) { return false; } _mavlink_receiver.reset(new MAVLinkReceiver(channel)); return true; } void Connection::stop_mavlink_receiver() { if (_mavlink_receiver) { uint8_t used_channel = _mavlink_receiver->get_channel(); // Destroy receiver before giving the channel back. _mavlink_receiver.reset(); MAVLinkChannels::Instance().checkin_used_channel(used_channel); } } void Connection::receive_message(const mavlink_message_t &message) { _parent.receive_message(message); } } // namespace dronecore
22.826087
71
0.72
shakthi-prashanth-m
e78efc5ed99af925d673839374d396cd1434169f
3,255
hpp
C++
tools/Vitis-AI-Library/rcan/include/vitis/ai/rcan.hpp
bluetiger9/Vitis-AI
a7728733bbcfc292ff3afa46b9c8b03e94b740b3
[ "Apache-2.0" ]
848
2019-12-03T00:16:17.000Z
2022-03-31T22:53:17.000Z
tools/Vitis-AI-Library/rcan/include/vitis/ai/rcan.hpp
wangyifan778/Vitis-AI
f61061eef7550d98bf02a171604c9a9f283a7c47
[ "Apache-2.0" ]
656
2019-12-03T00:48:46.000Z
2022-03-31T18:41:54.000Z
tools/Vitis-AI-Library/rcan/include/vitis/ai/rcan.hpp
wangyifan778/Vitis-AI
f61061eef7550d98bf02a171604c9a9f283a7c47
[ "Apache-2.0" ]
506
2019-12-03T00:46:26.000Z
2022-03-30T10:34:56.000Z
/* * Copyright 2019 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. */ /* * Filename: rcan.hpp * * Description: * This network is used to detecting featuare from a input image. * * Please refer to document "Xilinx_AI_SDK_User_Guide.pdf" for more details. * details of these APIs. */ #pragma once #include <vitis/ai/nnpp/rcan.hpp> #include "vitis/ai/configurable_dpu_task.hpp" namespace vitis { namespace ai { /** * @brief Base class for detecting rcan from an image (cv::Mat). * * Input is an image (cv::Mat). * * Output is the enlarged image. * * @note The input image size is 640x360 * * Sample code: * @code if (argc < 2) { cerr << "usage: " << argv[0] << " modelname image_file_url " << endl; abort(); } Mat input_img = imread(argv[2]); if (input_img.empty()) { cerr << "can't load image! " << argv[2] << endl; return -1; } auto det = vitis::ai::Rcan::create(argv[1]); Mat ret_img = det->run(input_img).feat; imwrite("sample_rcan_result.png", ret_img); @endcode * * Display of the model results: * @image latex images/sample_rcan_result.png "result image" width=300px * */ class Rcan : public ConfigurableDpuTaskBase { public: /** * @brief Factory function to get an instance of derived classes of class * Rcan. * *@param model_name Model name * @param need_preprocess Normalize with mean/scale or not, default * value is true. * @return An instance of Rcan class. * */ static std::unique_ptr<Rcan> create(const std::string& model_name, bool need_preprocess = true); /** * @cond NOCOMMENTS */ public: explicit Rcan(const std::string& model_name, bool need_preprocess); Rcan(const Rcan&) = delete; virtual ~Rcan(); /** * @endcond */ public: /** * @brief Function to get running result of the RCAN neuron network. * * @param image Input data of input image (cv::Mat). * * @return RcanResult. * */ virtual RcanResult run(const cv::Mat& image) = 0; /** * @brief Function to get running result of the RCAN neuron network in batch * mode. * * @param images Input data of input images (vector<cv::Mat>). * * @return vector of RcanResult. * */ virtual std::vector<RcanResult> run(const std::vector<cv::Mat>& images) = 0; /** * @brief Function to get running results of the rcan neuron network in * batch mode , used to receive user's xrt_bo to support zero copy. * * @param input_bos The vector of vart::xrt_bo_t. * * @return The vector of RcanResult. * */ virtual std::vector<RcanResult> run( const std::vector<vart::xrt_bo_t>& input_bos) = 0; }; } // namespace ai } // namespace vitis
26.900826
78
0.656528
bluetiger9
e790c329036965309267d731546bf41618e035ee
1,115
cc
C++
example/user_profile_request_handler.cc
chao-he/tictac
13b4b0289e8ac8e1d1764f99152ad0327ffa93d4
[ "Apache-2.0" ]
null
null
null
example/user_profile_request_handler.cc
chao-he/tictac
13b4b0289e8ac8e1d1764f99152ad0327ffa93d4
[ "Apache-2.0" ]
null
null
null
example/user_profile_request_handler.cc
chao-he/tictac
13b4b0289e8ac8e1d1764f99152ad0327ffa93d4
[ "Apache-2.0" ]
null
null
null
#include "core/connection.h" #include "user_profile_request_handler.h" #include "index_service.h" #include "query_service.h" #include "userprofile.pb.h" void UserProfileRequestHandler::DoGet(RedisRequest* request, Connection* conn) { auto& uid = request->arguments(0); auto& qs = QueryService::Instance(); RecoUserList candidates; auto pos = uid.find(':'); if (pos != std::string::npos) { qs.NearUserRecommend(uid.substr(pos+1), &candidates); } else { qs.NearUserRecommend(uid, &candidates); } char* b = (char*)malloc(candidates.ByteSize() + 16); char* p = b + snprintf(b, candidates.ByteSize() + 16, "$%d\r\n", candidates.ByteSize()); candidates.SerializeToArray(p, candidates.ByteSize()); p += candidates.ByteSize(); *p ++ = '\r'; *p ++ = '\n'; conn->AsyncWrite(b, p - b); } void UserProfileRequestHandler::DoSet(RedisRequest* request, Connection* conn) { auto& is = IndexService::Instance(); is.IndexRawString(request->arguments(1)); conn->AsyncWrite("$2\r\nOK\r\n", 8); } RequestHandler* RequestHandler::NewRequestHandler() { return new RedisRequestHandler(); }
30.972222
90
0.687892
chao-he
e7914c3227dd7fed38768da5ce971a1fe43ec8dd
1,187
cc
C++
net/tools/transport_security_state_generator/spki_hash.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
net/tools/transport_security_state_generator/spki_hash.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
net/tools/transport_security_state_generator/spki_hash.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/tools/transport_security_state_generator/spki_hash.h" #include <string> #include "base/base64.h" #include "base/logging.h" #include "base/strings/string_util.h" #include "third_party/boringssl/src/include/openssl/sha.h" namespace net { namespace transport_security_state { SPKIHash::SPKIHash() {} SPKIHash::~SPKIHash() {} bool SPKIHash::FromString(base::StringPiece hash_string) { base::StringPiece base64_string; if (!base::StartsWith(hash_string, "sha256/", base::CompareCase::INSENSITIVE_ASCII)) { return false; } base64_string = hash_string.substr(7); std::string decoded; if (!base::Base64Decode(base64_string, &decoded)) { return false; } if (decoded.size() != size()) { return false; } memcpy(data_, decoded.data(), decoded.size()); return true; } void SPKIHash::CalculateFromBytes(const uint8_t* input, size_t input_length) { SHA256(input, input_length, data_); } } // namespace transport_security_state } // namespace net
23.27451
78
0.712721
metux
e796b0390eee58d6c4eb9c4b6343d1740e85f708
606
hpp
C++
src/dynamics/object.hpp
brysonjones/dynamics_sim
201bdf0a93d00addc585ffa47f280cffacebb9b3
[ "MIT" ]
null
null
null
src/dynamics/object.hpp
brysonjones/dynamics_sim
201bdf0a93d00addc585ffa47f280cffacebb9b3
[ "MIT" ]
null
null
null
src/dynamics/object.hpp
brysonjones/dynamics_sim
201bdf0a93d00addc585ffa47f280cffacebb9b3
[ "MIT" ]
null
null
null
#include <iostream> #include <autodiff/forward/real.hpp> #include <autodiff/forward/real/eigen.hpp> #include <Eigen/Dense> #include <Eigen/Core> #include "rotation.hpp" // using namespace autodiff; using namespace Eigen; class Object { public: Object(); virtual autodiff::real U(const autodiff::ArrayXreal& pos); VectorXd DLT1(const autodiff::ArrayXreal& q1, const autodiff::ArrayXreal& q2, double h); private: protected: double m = 1; // mass (kg) double g = 1; // gravity accel (m/s^2) MatrixXd J; // (3x3) Inertia Tensor (kg*m^2) };
22.444444
96
0.643564
brysonjones
e79a0ac49e4b01e4d92fd1ac5a33564b41985387
3,027
cpp
C++
src/qt/tokentransactionrecord.cpp
rlinxy/fcore
652288940bd27ecbad69c0366bba20ad0f7515b6
[ "MIT" ]
1
2021-04-29T16:38:46.000Z
2021-04-29T16:38:46.000Z
src/qt/tokentransactionrecord.cpp
rlinxy/fcore
652288940bd27ecbad69c0366bba20ad0f7515b6
[ "MIT" ]
null
null
null
src/qt/tokentransactionrecord.cpp
rlinxy/fcore
652288940bd27ecbad69c0366bba20ad0f7515b6
[ "MIT" ]
1
2019-10-22T08:16:36.000Z
2019-10-22T08:16:36.000Z
#include <tokentransactionrecord.h> #include <base58.h> #include <consensus/consensus.h> #include <validation.h> #include <timedata.h> #include <wallet/wallet.h> #include <stdint.h> /* * Decompose CWallet transaction to model transaction records. */ QList<TokenTransactionRecord> TokenTransactionRecord::decomposeTransaction(const CWallet *wallet, const CTokenTx &wtx) { // Initialize variables QList<TokenTransactionRecord> parts; uint256 credit; uint256 debit; std::string tokenSymbol; uint8_t decimals = 18; if(wallet && !wtx.nValue.IsNull() && wallet->GetTokenTxDetails(wtx, credit, debit, tokenSymbol, decimals)) { // Get token transaction data TokenTransactionRecord rec; rec.time = wtx.nCreateTime; rec.credit = dev::u2s(uintTou256(credit)); rec.debit = -dev::u2s(uintTou256(debit)); rec.hash = wtx.GetHash(); rec.txid = wtx.transactionHash; rec.tokenSymbol = tokenSymbol; rec.decimals = decimals; rec.label = wtx.strLabel; dev::s256 net = rec.credit + rec.debit; // Determine type if(net == 0) { rec.type = SendToSelf; } else if(net > 0) { rec.type = RecvWithAddress; } else { rec.type = SendToAddress; } if(net) { rec.status.countsForBalance = true; } // Set address switch (rec.type) { case SendToSelf: case SendToAddress: case SendToOther: case RecvWithAddress: case RecvFromOther: rec.address = wtx.strReceiverAddress; default: break; } // Append record if(rec.type != Other) parts.append(rec); } return parts; } void TokenTransactionRecord::updateStatus(const CWallet *wallet, const CTokenTx &wtx) { AssertLockHeld(cs_main); // Determine transaction status status.cur_num_blocks = chainActive.Height(); if(wtx.blockNumber == -1) { status.depth = 0; } else { status.depth = status.cur_num_blocks - wtx.blockNumber + 1; } auto mi = wallet->mapWallet.find(wtx.transactionHash); if (mi != wallet->mapWallet.end() && (GetAdjustedTime() - mi->second.nTimeReceived > 2 * 60) && mi->second.GetRequestCount() == 0) { status.status = TokenTransactionStatus::Offline; } else if (status.depth == 0) { status.status = TokenTransactionStatus::Unconfirmed; } else if (status.depth < RecommendedNumConfirmations) { status.status = TokenTransactionStatus::Confirming; } else { status.status = TokenTransactionStatus::Confirmed; } } bool TokenTransactionRecord::statusUpdateNeeded() { AssertLockHeld(cs_main); return status.cur_num_blocks != chainActive.Height(); } QString TokenTransactionRecord::getTxID() const { return QString::fromStdString(txid.ToString()); }
25.436975
134
0.61447
rlinxy
e79a8850483827fe6ef96d843e5a14b076bbd40b
2,124
hpp
C++
src/mlpack/core/tree/rectangle_tree/r_tree_descent_heuristic.hpp
RMaron/mlpack
a179a2708d9555ab7ee4b1e90e0c290092edad2e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
675
2019-02-07T01:23:19.000Z
2022-03-28T05:45:10.000Z
src/mlpack/core/tree/rectangle_tree/r_tree_descent_heuristic.hpp
RMaron/mlpack
a179a2708d9555ab7ee4b1e90e0c290092edad2e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
843
2019-01-25T01:06:46.000Z
2022-03-16T11:15:53.000Z
src/mlpack/core/tree/rectangle_tree/r_tree_descent_heuristic.hpp
RMaron/mlpack
a179a2708d9555ab7ee4b1e90e0c290092edad2e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
83
2019-02-20T06:18:46.000Z
2022-03-20T09:36:09.000Z
/** * @file r_tree_descent_heuristic.hpp * @author Andrew Wells * * Definition of RTreeDescentHeuristic, a class that chooses the best child of a * node in an R tree when inserting a new point. * * mlpack is free software; you may redistribute it and/or modify it under the * terms of the 3-clause BSD license. You should have received a copy of the * 3-clause BSD license along with mlpack. If not, see * http://www.opensource.org/licenses/BSD-3-Clause for more information. */ #ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_R_TREE_DESCENT_HEURISTIC_HPP #define MLPACK_CORE_TREE_RECTANGLE_TREE_R_TREE_DESCENT_HEURISTIC_HPP #include <mlpack/prereqs.hpp> namespace mlpack { namespace tree { /** * When descending a RectangleTree to insert a point, we need to have a way to * choose a child node when the point isn't enclosed by any of them. This * heuristic is used to do so. */ class RTreeDescentHeuristic { public: /** * Evaluate the node using a heuristic. The heuristic guarantees two things: * * 1. If point is contained in (or on) the bound, the value returned is zero. * 2. If the point is not contained in (or on) the bound, the value returned * is greater than zero. * * @param node The node that is being evaluated. * @param point The index of the point that is being inserted. */ template<typename TreeType> static size_t ChooseDescentNode(const TreeType* node, const size_t point); /** * Evaluate the node using a heuristic. The heuristic guarantees two things: * * 1. If point is contained in (or on) the bound, the value returned is zero. * 2. If the point is not contained in (or on) the bound, the value returned * is greater than zero. * * @param node The node that is being evaluated. * @param insertedNode The node that is being inserted. */ template<typename TreeType> static size_t ChooseDescentNode(const TreeType* node, const TreeType* insertedNode); }; } // namespace tree } // namespace mlpack // Include implementation. #include "r_tree_descent_heuristic_impl.hpp" #endif
33.1875
80
0.718456
RMaron
e79bb907214e7600470605f83640d05da78da46f
27,585
cpp
C++
core/run/jobs/SimulationJobs.cpp
pavelsevecek/OpenSPH
d547c0af6270a739d772a4dcba8a70dc01775367
[ "MIT" ]
20
2021-04-02T04:30:08.000Z
2022-03-01T09:52:01.000Z
core/run/jobs/SimulationJobs.cpp
pavelsevecek/OpenSPH
d547c0af6270a739d772a4dcba8a70dc01775367
[ "MIT" ]
null
null
null
core/run/jobs/SimulationJobs.cpp
pavelsevecek/OpenSPH
d547c0af6270a739d772a4dcba8a70dc01775367
[ "MIT" ]
1
2022-01-22T11:44:52.000Z
2022-01-22T11:44:52.000Z
#include "run/jobs/SimulationJobs.h" #include "gravity/AggregateSolver.h" #include "io/LogWriter.h" #include "io/Logger.h" #include "io/Output.h" #include "run/IRun.h" #include "run/SpecialEntries.h" #include "sph/solvers/StabilizationSolver.h" NAMESPACE_SPH_BEGIN /// \todo generailize, add generic triggers to UI class EnergyLogWriter : public ILogWriter { public: using ILogWriter::ILogWriter; private: virtual void write(const Storage& storage, const Statistics& stats) override { const Float t = stats.get<Float>(StatisticsId::RUN_TIME); const Float e = TotalEnergy().evaluate(storage); logger->write(t, " ", e); } }; static std::string getIdentifier(const std::string& name) { std::string escaped = replaceAll(name, " ", "-"); return lowercase(escaped); } // ---------------------------------------------------------------------------------------------------------- // SphJob // ---------------------------------------------------------------------------------------------------------- static RunSettings overrideSettings(const RunSettings& settings, const RunSettings& overrides, const bool isResumed) { RunSettings actual = settings; actual.addEntries(overrides); if (!isResumed) { // reset the (potentially) overriden values back to original actual.set(RunSettingsId::RUN_START_TIME, settings.get<Float>(RunSettingsId::RUN_START_TIME)); actual.set(RunSettingsId::TIMESTEPPING_INITIAL_TIMESTEP, settings.get<Float>(RunSettingsId::TIMESTEPPING_INITIAL_TIMESTEP)); actual.set( RunSettingsId::RUN_OUTPUT_FIRST_INDEX, settings.get<int>(RunSettingsId::RUN_OUTPUT_FIRST_INDEX)); } return actual; } static void addTimeSteppingCategory(VirtualSettings& connector, RunSettings& settings, bool& resumeRun) { auto courantEnabler = [&settings] { Flags<TimeStepCriterionEnum> criteria = settings.getFlags<TimeStepCriterionEnum>(RunSettingsId::TIMESTEPPING_CRITERION); return criteria.has(TimeStepCriterionEnum::COURANT); }; auto derivativeEnabler = [&settings] { Flags<TimeStepCriterionEnum> criteria = settings.getFlags<TimeStepCriterionEnum>(RunSettingsId::TIMESTEPPING_CRITERION); return criteria.hasAny(TimeStepCriterionEnum::DERIVATIVES, TimeStepCriterionEnum::ACCELERATION); }; auto divergenceEnabler = [&settings] { Flags<TimeStepCriterionEnum> criteria = settings.getFlags<TimeStepCriterionEnum>(RunSettingsId::TIMESTEPPING_CRITERION); return criteria.has(TimeStepCriterionEnum::DIVERGENCE); }; VirtualSettings::Category& rangeCat = connector.addCategory("Integration"); rangeCat.connect<Float>("Duration [s]", settings, RunSettingsId::RUN_END_TIME); rangeCat.connect("Use start time of input", "is_resumed", resumeRun); rangeCat.connect<Float>("Maximal timestep [s]", settings, RunSettingsId::TIMESTEPPING_MAX_TIMESTEP); rangeCat.connect<Float>("Initial timestep [s]", settings, RunSettingsId::TIMESTEPPING_INITIAL_TIMESTEP); rangeCat.connect<EnumWrapper>("Integrator", settings, RunSettingsId::TIMESTEPPING_INTEGRATOR); rangeCat.connect<Flags<TimeStepCriterionEnum>>( "Time step criteria", settings, RunSettingsId::TIMESTEPPING_CRITERION); rangeCat.connect<Float>("Courant number", settings, RunSettingsId::TIMESTEPPING_COURANT_NUMBER) .setEnabler(courantEnabler); rangeCat.connect<Float>("Derivative factor", settings, RunSettingsId::TIMESTEPPING_DERIVATIVE_FACTOR) .setEnabler(derivativeEnabler); rangeCat.connect<Float>("Divergence factor", settings, RunSettingsId::TIMESTEPPING_DIVERGENCE_FACTOR) .setEnabler(divergenceEnabler); rangeCat.connect<Float>("Max step change", settings, RunSettingsId::TIMESTEPPING_MAX_INCREASE); } static void addGravityCategory(VirtualSettings& connector, RunSettings& settings) { VirtualSettings::Category& gravityCat = connector.addCategory("Gravity"); gravityCat.connect<EnumWrapper>("Gravity solver", settings, RunSettingsId::GRAVITY_SOLVER); gravityCat.connect<Float>("Opening angle", settings, RunSettingsId::GRAVITY_OPENING_ANGLE) .setEnabler([&settings] { return settings.get<GravityEnum>(RunSettingsId::GRAVITY_SOLVER) == GravityEnum::BARNES_HUT; }); gravityCat.connect<int>("Multipole order", settings, RunSettingsId::GRAVITY_MULTIPOLE_ORDER); gravityCat.connect<EnumWrapper>("Softening kernel", settings, RunSettingsId::GRAVITY_KERNEL); gravityCat.connect<Float>( "Recomputation period [s]", settings, RunSettingsId::GRAVITY_RECOMPUTATION_PERIOD); } static void addOutputCategory(VirtualSettings& connector, RunSettings& settings, const SharedToken& owner) { auto enabler = [&settings] { const IoEnum type = settings.get<IoEnum>(RunSettingsId::RUN_OUTPUT_TYPE); return type != IoEnum::NONE; }; VirtualSettings::Category& outputCat = connector.addCategory("Output"); outputCat.connect<EnumWrapper>("Format", settings, RunSettingsId::RUN_OUTPUT_TYPE) .setValidator([](const IVirtualEntry::Value& value) { const IoEnum type = IoEnum(value.get<EnumWrapper>()); return type == IoEnum::NONE || getIoCapabilities(type).has(IoCapability::OUTPUT); }) .addAccessor(owner, [&settings](const IVirtualEntry::Value& value) { const IoEnum type = IoEnum(value.get<EnumWrapper>()); Path name = Path(settings.get<std::string>(RunSettingsId::RUN_OUTPUT_NAME)); if (Optional<std::string> extension = getIoExtension(type)) { name.replaceExtension(extension.value()); } settings.set(RunSettingsId::RUN_OUTPUT_NAME, name.native()); }) .setSideEffect(); // needs to update the 'File mask' entry outputCat.connect<Path>("Directory", settings, RunSettingsId::RUN_OUTPUT_PATH) .setEnabler(enabler) .setPathType(IVirtualEntry::PathType::DIRECTORY); outputCat.connect<std::string>("File mask", settings, RunSettingsId::RUN_OUTPUT_NAME).setEnabler(enabler); outputCat.connect<Flags<OutputQuantityFlag>>("Quantities", settings, RunSettingsId::RUN_OUTPUT_QUANTITIES) .setEnabler([&settings] { const IoEnum type = settings.get<IoEnum>(RunSettingsId::RUN_OUTPUT_TYPE); return type == IoEnum::TEXT_FILE || type == IoEnum::VTK_FILE; }); outputCat.connect<EnumWrapper>("Output spacing", settings, RunSettingsId::RUN_OUTPUT_SPACING) .setEnabler(enabler); outputCat.connect<Float>("Output interval [s]", settings, RunSettingsId::RUN_OUTPUT_INTERVAL) .setEnabler([&] { const IoEnum type = settings.get<IoEnum>(RunSettingsId::RUN_OUTPUT_TYPE); const OutputSpacing spacing = settings.get<OutputSpacing>(RunSettingsId::RUN_OUTPUT_SPACING); return type != IoEnum::NONE && spacing != OutputSpacing::CUSTOM; }); outputCat.connect<std::string>("Custom times [s]", settings, RunSettingsId::RUN_OUTPUT_CUSTOM_TIMES) .setEnabler([&] { const IoEnum type = settings.get<IoEnum>(RunSettingsId::RUN_OUTPUT_TYPE); const OutputSpacing spacing = settings.get<OutputSpacing>(RunSettingsId::RUN_OUTPUT_SPACING); return type != IoEnum::NONE && spacing == OutputSpacing::CUSTOM; }); } static void addLoggerCategory(VirtualSettings& connector, RunSettings& settings) { VirtualSettings::Category& loggerCat = connector.addCategory("Logging"); loggerCat.connect<EnumWrapper>("Logger", settings, RunSettingsId::RUN_LOGGER); loggerCat.connect<Path>("Log file", settings, RunSettingsId::RUN_LOGGER_FILE) .setPathType(IVirtualEntry::PathType::OUTPUT_FILE) .setEnabler( [&settings] { return settings.get<LoggerEnum>(RunSettingsId::RUN_LOGGER) == LoggerEnum::FILE; }); loggerCat.connect<int>("Log verbosity", settings, RunSettingsId::RUN_LOGGER_VERBOSITY); } class SphRun : public IRun { protected: SharedPtr<IDomain> domain; public: explicit SphRun(const RunSettings& run, SharedPtr<IDomain> domain) : domain(domain) { settings = run; scheduler = Factory::getScheduler(settings); } virtual void setUp(SharedPtr<Storage> storage) override { AutoPtr<IBoundaryCondition> bc = Factory::getBoundaryConditions(settings, domain); solver = Factory::getSolver(*scheduler, settings, std::move(bc)); for (Size matId = 0; matId < storage->getMaterialCnt(); ++matId) { solver->create(*storage, storage->getMaterial(matId)); } } virtual void tearDown(const Storage& storage, const Statistics& stats) override { // last dump after simulation ends output->dump(storage, stats); } }; SphJob::SphJob(const std::string& name, const RunSettings& overrides) : IRunJob(name) { settings = getDefaultSettings(name); settings.addEntries(overrides); } RunSettings SphJob::getDefaultSettings(const std::string& name) { const Size dumpCnt = 10; const Interval timeRange(0, 10); RunSettings settings; settings.set(RunSettingsId::TIMESTEPPING_INTEGRATOR, TimesteppingEnum::PREDICTOR_CORRECTOR) .set(RunSettingsId::TIMESTEPPING_INITIAL_TIMESTEP, 0.01_f) .set(RunSettingsId::TIMESTEPPING_MAX_TIMESTEP, 10._f) .set(RunSettingsId::TIMESTEPPING_COURANT_NUMBER, 0.2_f) .set(RunSettingsId::RUN_START_TIME, timeRange.lower()) .set(RunSettingsId::RUN_END_TIME, timeRange.upper()) .set(RunSettingsId::RUN_NAME, name) .set(RunSettingsId::RUN_OUTPUT_INTERVAL, timeRange.size() / dumpCnt) .set(RunSettingsId::RUN_OUTPUT_TYPE, IoEnum::NONE) .set(RunSettingsId::RUN_OUTPUT_NAME, getIdentifier(name) + "_%d.ssf") .set(RunSettingsId::RUN_VERBOSE_NAME, getIdentifier(name) + ".log") .set(RunSettingsId::SPH_SOLVER_TYPE, SolverEnum::ASYMMETRIC_SOLVER) .set(RunSettingsId::SPH_SOLVER_FORCES, ForceEnum::PRESSURE | ForceEnum::SOLID_STRESS | ForceEnum::SELF_GRAVITY) .set(RunSettingsId::SPH_DISCRETIZATION, DiscretizationEnum::STANDARD) .set(RunSettingsId::SPH_FINDER, FinderEnum::KD_TREE) .set(RunSettingsId::SPH_AV_TYPE, ArtificialViscosityEnum::STANDARD) .set(RunSettingsId::SPH_AV_ALPHA, 1.5_f) .set(RunSettingsId::SPH_AV_BETA, 3._f) .set(RunSettingsId::SPH_KERNEL, KernelEnum::CUBIC_SPLINE) .set(RunSettingsId::GRAVITY_SOLVER, GravityEnum::BARNES_HUT) .set(RunSettingsId::GRAVITY_KERNEL, GravityKernelEnum::SPH_KERNEL) .set(RunSettingsId::GRAVITY_OPENING_ANGLE, 0.8_f) .set(RunSettingsId::GRAVITY_RECOMPUTATION_PERIOD, 5._f) .set(RunSettingsId::FINDER_LEAF_SIZE, 20) .set(RunSettingsId::SPH_STABILIZATION_DAMPING, 0.1_f) .set(RunSettingsId::RUN_THREAD_GRANULARITY, 1000) .set(RunSettingsId::SPH_ADAPTIVE_SMOOTHING_LENGTH, EMPTY_FLAGS) .set(RunSettingsId::SPH_ASYMMETRIC_COMPUTE_RADII_HASH_MAP, false) .set(RunSettingsId::SPH_STRAIN_RATE_CORRECTION_TENSOR, true) .set(RunSettingsId::RUN_DIAGNOSTICS_INTERVAL, 1._f); return settings; } VirtualSettings SphJob::getSettings() { VirtualSettings connector; addGenericCategory(connector, instName); addTimeSteppingCategory(connector, settings, isResumed); auto stressEnabler = [this] { return settings.getFlags<ForceEnum>(RunSettingsId::SPH_SOLVER_FORCES).has(ForceEnum::SOLID_STRESS); }; auto avEnabler = [this] { return settings.get<ArtificialViscosityEnum>(RunSettingsId::SPH_AV_TYPE) != ArtificialViscosityEnum::NONE; }; auto asEnabler = [this] { return settings.get<bool>(RunSettingsId::SPH_AV_USE_STRESS); }; // auto acEnabler = [this] { return settings.get<bool>(RunSettingsId::SPH_USE_AC); }; auto deltaSphEnabler = [this] { return settings.get<bool>(RunSettingsId::SPH_USE_DELTASPH); }; auto enforceEnabler = [this] { return settings.getFlags<SmoothingLengthEnum>(RunSettingsId::SPH_ADAPTIVE_SMOOTHING_LENGTH) .has(SmoothingLengthEnum::SOUND_SPEED_ENFORCING); }; VirtualSettings::Category& solverCat = connector.addCategory("SPH solver"); solverCat.connect<Flags<ForceEnum>>("Forces", settings, RunSettingsId::SPH_SOLVER_FORCES); solverCat.connect<Vector>("Constant acceleration", settings, RunSettingsId::FRAME_CONSTANT_ACCELERATION); solverCat.connect<Float>("Tides mass [M_earth]", settings, RunSettingsId::FRAME_TIDES_MASS) .setUnits(Constants::M_earth); solverCat.connect<Vector>("Tides position [R_earth]", settings, RunSettingsId::FRAME_TIDES_POSITION) .setUnits(Constants::R_earth); solverCat.connect<EnumWrapper>("Solver type", settings, RunSettingsId::SPH_SOLVER_TYPE); solverCat.connect<EnumWrapper>("SPH discretization", settings, RunSettingsId::SPH_DISCRETIZATION); solverCat.connect<Flags<SmoothingLengthEnum>>( "Adaptive smoothing length", settings, RunSettingsId::SPH_ADAPTIVE_SMOOTHING_LENGTH); solverCat.connect<Float>("Minimal smoothing length", settings, RunSettingsId::SPH_SMOOTHING_LENGTH_MIN) .setEnabler([this] { return settings.getFlags<SmoothingLengthEnum>(RunSettingsId::SPH_ADAPTIVE_SMOOTHING_LENGTH) != EMPTY_FLAGS; }); solverCat .connect<Float>("Neighbor count enforcing strength", settings, RunSettingsId::SPH_NEIGHBOR_ENFORCING) .setEnabler(enforceEnabler); solverCat.connect<Interval>("Neighbor range", settings, RunSettingsId::SPH_NEIGHBOR_RANGE) .setEnabler(enforceEnabler); solverCat .connect<bool>("Use radii hash map", settings, RunSettingsId::SPH_ASYMMETRIC_COMPUTE_RADII_HASH_MAP) .setEnabler([this] { return settings.get<SolverEnum>(RunSettingsId::SPH_SOLVER_TYPE) == SolverEnum::ASYMMETRIC_SOLVER; }); solverCat .connect<bool>("Apply correction tensor", settings, RunSettingsId::SPH_STRAIN_RATE_CORRECTION_TENSOR) .setEnabler(stressEnabler); solverCat.connect<bool>("Sum only undamaged particles", settings, RunSettingsId::SPH_SUM_ONLY_UNDAMAGED); solverCat.connect<EnumWrapper>("Continuity mode", settings, RunSettingsId::SPH_CONTINUITY_MODE); solverCat.connect<EnumWrapper>("Neighbor finder", settings, RunSettingsId::SPH_FINDER); solverCat.connect<EnumWrapper>("Boundary condition", settings, RunSettingsId::DOMAIN_BOUNDARY); VirtualSettings::Category& avCat = connector.addCategory("Artificial viscosity"); avCat.connect<EnumWrapper>("Artificial viscosity type", settings, RunSettingsId::SPH_AV_TYPE); avCat.connect<bool>("Apply Balsara switch", settings, RunSettingsId::SPH_AV_USE_BALSARA) .setEnabler(avEnabler); avCat.connect<Float>("Artificial viscosity alpha", settings, RunSettingsId::SPH_AV_ALPHA) .setEnabler(avEnabler); avCat.connect<Float>("Artificial viscosity beta", settings, RunSettingsId::SPH_AV_BETA) .setEnabler(avEnabler); avCat.connect<bool>("Apply artificial stress", settings, RunSettingsId::SPH_AV_USE_STRESS); avCat.connect<Float>("Artificial stress factor", settings, RunSettingsId::SPH_AV_STRESS_FACTOR) .setEnabler(asEnabler); avCat.connect<Float>("Artificial stress exponent", settings, RunSettingsId::SPH_AV_STRESS_EXPONENT) .setEnabler(asEnabler); avCat.connect<bool>("Apply artificial conductivity", settings, RunSettingsId::SPH_USE_AC); avCat.connect<EnumWrapper>("Signal speed", settings, RunSettingsId::SPH_AC_SIGNAL_SPEED) .setEnabler([this] { return settings.get<bool>(RunSettingsId::SPH_USE_AC); }); VirtualSettings::Category& modCat = connector.addCategory("SPH modifications"); modCat.connect<bool>("Enable XPSH", settings, RunSettingsId::SPH_USE_XSPH); modCat.connect<Float>("XSPH epsilon", settings, RunSettingsId::SPH_XSPH_EPSILON).setEnabler([this] { return settings.get<bool>(RunSettingsId::SPH_USE_XSPH); }); modCat.connect<bool>("Enable delta-SPH", settings, RunSettingsId::SPH_USE_DELTASPH); modCat.connect<Float>("delta-SPH alpha", settings, RunSettingsId::SPH_VELOCITY_DIFFUSION_ALPHA) .setEnabler(deltaSphEnabler); modCat.connect<Float>("delta-SPH delta", settings, RunSettingsId::SPH_DENSITY_DIFFUSION_DELTA) .setEnabler(deltaSphEnabler); auto scriptEnabler = [this] { return settings.get<bool>(RunSettingsId::SPH_SCRIPT_ENABLE); }; VirtualSettings::Category& scriptCat = connector.addCategory("Scripts"); scriptCat.connect<bool>("Enable script", settings, RunSettingsId::SPH_SCRIPT_ENABLE); scriptCat.connect<Path>("Script file", settings, RunSettingsId::SPH_SCRIPT_FILE) .setEnabler(scriptEnabler) .setPathType(IVirtualEntry::PathType::INPUT_FILE) .setFileFormats({ { "Chaiscript script", "chai" } }); scriptCat.connect<Float>("Script period [s]", settings, RunSettingsId::SPH_SCRIPT_PERIOD) .setEnabler(scriptEnabler); scriptCat.connect<bool>("Run only once", settings, RunSettingsId::SPH_SCRIPT_ONESHOT) .setEnabler(scriptEnabler); addGravityCategory(connector, settings); addOutputCategory(connector, settings, *this); addLoggerCategory(connector, settings); return connector; } AutoPtr<IRun> SphJob::getRun(const RunSettings& overrides) const { SPH_ASSERT(overrides.size() < 15); // not really required, just checking that we don't override everything const BoundaryEnum boundary = settings.get<BoundaryEnum>(RunSettingsId::DOMAIN_BOUNDARY); SharedPtr<IDomain> domain; if (boundary != BoundaryEnum::NONE) { domain = this->getInput<IDomain>("boundary"); } RunSettings run = overrideSettings(settings, overrides, isResumed); if (!run.getFlags<ForceEnum>(RunSettingsId::SPH_SOLVER_FORCES).has(ForceEnum::SOLID_STRESS)) { run.set(RunSettingsId::SPH_STRAIN_RATE_CORRECTION_TENSOR, false); } return makeAuto<SphRun>(run, domain); } static JobRegistrar sRegisterSph( "SPH run", "simulations", [](const std::string& name) { return makeAuto<SphJob>(name, EMPTY_SETTINGS); }, "Runs a SPH simulation, using provided initial conditions."); // ---------------------------------------------------------------------------------------------------------- // SphStabilizationJob // ---------------------------------------------------------------------------------------------------------- class SphStabilizationRun : public SphRun { public: using SphRun::SphRun; virtual void setUp(SharedPtr<Storage> storage) override { AutoPtr<IBoundaryCondition> bc = Factory::getBoundaryConditions(settings, domain); solver = makeAuto<StabilizationSolver>(*scheduler, settings, std::move(bc)); for (Size matId = 0; matId < storage->getMaterialCnt(); ++matId) { solver->create(*storage, storage->getMaterial(matId)); } } }; VirtualSettings SphStabilizationJob::getSettings() { VirtualSettings connector = SphJob::getSettings(); VirtualSettings::Category& stabCat = connector.addCategory("Stabilization"); stabCat.connect<Float>("Damping coefficient", settings, RunSettingsId::SPH_STABILIZATION_DAMPING); return connector; } AutoPtr<IRun> SphStabilizationJob::getRun(const RunSettings& overrides) const { RunSettings run = overrideSettings(settings, overrides, isResumed); const BoundaryEnum boundary = settings.get<BoundaryEnum>(RunSettingsId::DOMAIN_BOUNDARY); SharedPtr<IDomain> domain; if (boundary != BoundaryEnum::NONE) { domain = this->getInput<IDomain>("boundary"); } return makeAuto<SphStabilizationRun>(run, domain); } static JobRegistrar sRegisterSphStab( "SPH stabilization", "stabilization", "simulations", [](const std::string& name) { return makeAuto<SphStabilizationJob>(name, EMPTY_SETTINGS); }, "Runs a SPH simulation with a damping term, suitable for stabilization of non-equilibrium initial " "conditions."); // ---------------------------------------------------------------------------------------------------------- // NBodyJob // ---------------------------------------------------------------------------------------------------------- class NBodyRun : public IRun { private: bool useSoft; public: NBodyRun(const RunSettings& run, const bool useSoft) : useSoft(useSoft) { settings = run; scheduler = Factory::getScheduler(settings); } virtual void setUp(SharedPtr<Storage> storage) override { logger = Factory::getLogger(settings); const bool aggregateEnable = settings.get<bool>(RunSettingsId::NBODY_AGGREGATES_ENABLE); const AggregateEnum aggregateSource = settings.get<AggregateEnum>(RunSettingsId::NBODY_AGGREGATES_SOURCE); if (aggregateEnable) { AutoPtr<AggregateSolver> aggregates = makeAuto<AggregateSolver>(*scheduler, settings); aggregates->createAggregateData(*storage, aggregateSource); solver = std::move(aggregates); } else if (useSoft) { solver = makeAuto<SoftSphereSolver>(*scheduler, settings); } else { solver = makeAuto<HardSphereSolver>(*scheduler, settings); } NullMaterial mtl(BodySettings::getDefaults()); solver->create(*storage, mtl); setPersistentIndices(*storage); } virtual void tearDown(const Storage& storage, const Statistics& stats) override { output->dump(storage, stats); } }; NBodyJob::NBodyJob(const std::string& name, const RunSettings& overrides) : IRunJob(name) { settings = getDefaultSettings(name); settings.addEntries(overrides); } RunSettings NBodyJob::getDefaultSettings(const std::string& name) { const Interval timeRange(0, 1.e6_f); RunSettings settings; settings.set(RunSettingsId::RUN_NAME, name) .set(RunSettingsId::RUN_TYPE, RunTypeEnum::NBODY) .set(RunSettingsId::TIMESTEPPING_INTEGRATOR, TimesteppingEnum::LEAP_FROG) .set(RunSettingsId::TIMESTEPPING_INITIAL_TIMESTEP, 0.01_f) .set(RunSettingsId::TIMESTEPPING_MAX_TIMESTEP, 10._f) .set(RunSettingsId::TIMESTEPPING_CRITERION, TimeStepCriterionEnum::ACCELERATION) .set(RunSettingsId::TIMESTEPPING_DERIVATIVE_FACTOR, 0.2_f) .set(RunSettingsId::RUN_START_TIME, timeRange.lower()) .set(RunSettingsId::RUN_END_TIME, timeRange.upper()) .set(RunSettingsId::RUN_OUTPUT_INTERVAL, timeRange.size() / 10) .set(RunSettingsId::RUN_OUTPUT_TYPE, IoEnum::NONE) .set(RunSettingsId::RUN_OUTPUT_NAME, getIdentifier(name) + "_%d.ssf") .set(RunSettingsId::RUN_VERBOSE_NAME, getIdentifier(name) + ".log") .set(RunSettingsId::SPH_FINDER, FinderEnum::KD_TREE) .set(RunSettingsId::GRAVITY_SOLVER, GravityEnum::BARNES_HUT) .set(RunSettingsId::GRAVITY_KERNEL, GravityKernelEnum::SOLID_SPHERES) .set(RunSettingsId::GRAVITY_OPENING_ANGLE, 0.8_f) .set(RunSettingsId::FINDER_LEAF_SIZE, 20) .set(RunSettingsId::COLLISION_HANDLER, CollisionHandlerEnum::MERGE_OR_BOUNCE) .set(RunSettingsId::COLLISION_OVERLAP, OverlapEnum::PASS_OR_MERGE) .set(RunSettingsId::COLLISION_RESTITUTION_NORMAL, 0.5_f) .set(RunSettingsId::COLLISION_RESTITUTION_TANGENT, 1._f) .set(RunSettingsId::COLLISION_ALLOWED_OVERLAP, 0.01_f) .set(RunSettingsId::COLLISION_BOUNCE_MERGE_LIMIT, 4._f) .set(RunSettingsId::COLLISION_ROTATION_MERGE_LIMIT, 1._f) .set(RunSettingsId::NBODY_INERTIA_TENSOR, false) .set(RunSettingsId::NBODY_MAX_ROTATION_ANGLE, 0.01_f) .set(RunSettingsId::RUN_THREAD_GRANULARITY, 100); return settings; } VirtualSettings NBodyJob::getSettings() { VirtualSettings connector; addGenericCategory(connector, instName); addTimeSteppingCategory(connector, settings, isResumed); addGravityCategory(connector, settings); VirtualSettings::Category& aggregateCat = connector.addCategory("Aggregates (experimental)"); aggregateCat.connect<bool>("Enable aggregates", settings, RunSettingsId::NBODY_AGGREGATES_ENABLE); aggregateCat.connect<EnumWrapper>("Initial aggregates", settings, RunSettingsId::NBODY_AGGREGATES_SOURCE) .setEnabler([this] { return settings.get<bool>(RunSettingsId::NBODY_AGGREGATES_ENABLE); }); VirtualSettings::Category& softCat = connector.addCategory("Soft-body physics (experimental)"); softCat.connect("Enable soft-body", "soft.enable", useSoft); softCat.connect<Float>("Repel force strength", settings, RunSettingsId::SOFT_REPEL_STRENGTH) .setEnabler([this] { return useSoft; }); softCat.connect<Float>("Friction force strength", settings, RunSettingsId::SOFT_FRICTION_STRENGTH) .setEnabler([this] { return useSoft; }); auto collisionEnabler = [this] { return !useSoft && !settings.get<bool>(RunSettingsId::NBODY_AGGREGATES_ENABLE) && settings.get<CollisionHandlerEnum>(RunSettingsId::COLLISION_HANDLER) != CollisionHandlerEnum::NONE; }; auto mergeLimitEnabler = [this] { if (useSoft) { return false; } const CollisionHandlerEnum handler = settings.get<CollisionHandlerEnum>(RunSettingsId::COLLISION_HANDLER); if (handler == CollisionHandlerEnum::NONE) { return false; } const bool aggregates = settings.get<bool>(RunSettingsId::NBODY_AGGREGATES_ENABLE); const OverlapEnum overlap = settings.get<OverlapEnum>(RunSettingsId::COLLISION_OVERLAP); return aggregates || handler == CollisionHandlerEnum::MERGE_OR_BOUNCE || overlap == OverlapEnum::PASS_OR_MERGE || overlap == OverlapEnum::REPEL_OR_MERGE; }; VirtualSettings::Category& collisionCat = connector.addCategory("Collisions"); collisionCat.connect<EnumWrapper>("Collision handler", settings, RunSettingsId::COLLISION_HANDLER) .setEnabler([this] { // return !useSoft && !settings.get<bool>(RunSettingsId::NBODY_AGGREGATES_ENABLE); }); collisionCat.connect<EnumWrapper>("Overlap handler", settings, RunSettingsId::COLLISION_OVERLAP) .setEnabler(collisionEnabler); collisionCat.connect<Float>("Normal restitution", settings, RunSettingsId::COLLISION_RESTITUTION_NORMAL) .setEnabler(collisionEnabler); collisionCat .connect<Float>("Tangential restitution", settings, RunSettingsId::COLLISION_RESTITUTION_TANGENT) .setEnabler(collisionEnabler); collisionCat.connect<Float>("Merge velocity limit", settings, RunSettingsId::COLLISION_BOUNCE_MERGE_LIMIT) .setEnabler(mergeLimitEnabler); collisionCat .connect<Float>("Merge rotation limit", settings, RunSettingsId::COLLISION_ROTATION_MERGE_LIMIT) .setEnabler(mergeLimitEnabler); addLoggerCategory(connector, settings); addOutputCategory(connector, settings, *this); return connector; } AutoPtr<IRun> NBodyJob::getRun(const RunSettings& overrides) const { RunSettings run = overrideSettings(settings, overrides, isResumed); return makeAuto<NBodyRun>(run, useSoft); } static JobRegistrar sRegisterNBody( "N-body run", "simulations", [](const std::string& name) { return makeAuto<NBodyJob>(name, EMPTY_SETTINGS); }, "Runs N-body simulation using given initial conditions."); NAMESPACE_SPH_END
49.702703
110
0.701939
pavelsevecek
e7a3a909df2aa0d7fcaa7df76d31371537250bc0
2,535
cpp
C++
src/manager/initial-values/xml-utils.cpp
Samsung/ckm
a61e9ce01fa45323b381e6456d07117516d2e55d
[ "Apache-2.0" ]
10
2015-06-02T09:16:16.000Z
2022-03-18T11:30:21.000Z
src/manager/initial-values/xml-utils.cpp
Samsung/ckm
a61e9ce01fa45323b381e6456d07117516d2e55d
[ "Apache-2.0" ]
null
null
null
src/manager/initial-values/xml-utils.cpp
Samsung/ckm
a61e9ce01fa45323b381e6456d07117516d2e55d
[ "Apache-2.0" ]
6
2017-01-28T04:21:33.000Z
2022-02-07T03:25:43.000Z
/* * Copyright (c) 2000 - 2015 Samsung Electronics Co., Ltd All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License * * * @file parser.cpp * @author Maciej Karpiuk (m.karpiuk2@samsung.com) * @version 1.0 * @brief XML parser class implementation. */ #include <string> #include <sstream> #include <algorithm> #include <xml-utils.h> namespace { const char * const WHITESPACE = " \n\r\t\v"; const char * const LINE_WHITESPACE = " \r\t\v"; std::string trim_left(const std::string& s, const char *whitespaces) { size_t startpos = s.find_first_not_of(whitespaces); return (startpos == std::string::npos) ? "" : s.substr(startpos); } std::string trim_right(const std::string& s, const char *whitespaces) { size_t endpos = s.find_last_not_of(whitespaces); return (endpos == std::string::npos) ? "" : s.substr(0, endpos+1); } std::string trim(const std::string& s, const char *whitespaces) { return trim_right(trim_left(s, whitespaces), whitespaces); } } namespace CKM { namespace XML { template <typename T> T removeChars(const T& input, const char *what) { T out(input); auto endit = std::remove_if(out.begin(), out.end(), [what](char c) { for (const char *ptr = what; *ptr; ++ptr) if (*ptr == c) return true; return false; }); out.erase(endit, out.end()); return out; } RawBuffer removeWhiteChars(const RawBuffer &buffer) { return removeChars(buffer, WHITESPACE); } std::string trimEachLine(const std::string& input) { std::stringstream ss(input); std::stringstream output; std::string line; while (std::getline(ss, line, '\n')) { auto afterTrim = ::trim(line, LINE_WHITESPACE); if (!afterTrim.empty()) output << afterTrim << std::endl; } return output.str(); } std::string trim(const std::string &s) { return removeChars(s, WHITESPACE); } } // namespace XML } // namespace CKM
25.606061
78
0.646154
Samsung
e7a5d630bb54dff331aabbf8fa33f0f3ac2f5094
1,453
cpp
C++
test/ci_app_tests/ci_test_macros.cpp
daboehme/Caliper
38e2fc9a703601801ea8223a0bbd53795b6a0a3a
[ "BSD-3-Clause" ]
null
null
null
test/ci_app_tests/ci_test_macros.cpp
daboehme/Caliper
38e2fc9a703601801ea8223a0bbd53795b6a0a3a
[ "BSD-3-Clause" ]
null
null
null
test/ci_app_tests/ci_test_macros.cpp
daboehme/Caliper
38e2fc9a703601801ea8223a0bbd53795b6a0a3a
[ "BSD-3-Clause" ]
null
null
null
// --- Caliper continuous integration test app for basic trace test #define _XOPEN_SOURCE #include <unistd.h> /* usleep */ #include "caliper/cali.h" #include "caliper/cali-manager.h" #include <string> // test C and C++ macros void foo(int count, int sleep_usec) { CALI_CXX_MARK_FUNCTION; CALI_MARK_BEGIN("pre-loop"); CALI_WRAP_STATEMENT("foo.init", count = std::max(1, count)); CALI_MARK_END("pre-loop"); CALI_MARK_LOOP_BEGIN(fooloop, "fooloop"); for (int i = 0; i < count; ++i) { CALI_MARK_ITERATION_BEGIN(fooloop, i); if (sleep_usec > 0) usleep(sleep_usec); CALI_MARK_ITERATION_END(fooloop); } CALI_MARK_LOOP_END(fooloop); } int main(int argc, char* argv[]) { int sleep_usec = 0; if (argc > 1) sleep_usec = std::stoi(argv[1]); cali::ConfigManager mgr; if (argc > 2) if (std::string(argv[2]) != "none") mgr.add(argv[2]); if (mgr.error()) { std::cerr << mgr.error_msg() << std::endl; return -1; } mgr.start(); CALI_MARK_FUNCTION_BEGIN; int count = 4; if (argc > 3) count = std::max(1, std::stoi(argv[3])); CALI_CXX_MARK_LOOP_BEGIN(mainloop, "mainloop"); for (int i = 0; i < count; ++i) { CALI_CXX_MARK_LOOP_ITERATION(mainloop, i); foo(count, sleep_usec); } CALI_CXX_MARK_LOOP_END(mainloop); CALI_MARK_FUNCTION_END; mgr.flush(); }
19.90411
67
0.600826
daboehme
e7a94c5246962d4e68054e4b3d933b461ecbfd0f
242
cpp
C++
busplan/time_line.cpp
gonmator/busplan
5845b63b16741dd0472cbba1ba028bdfdcfe0e3f
[ "MIT" ]
null
null
null
busplan/time_line.cpp
gonmator/busplan
5845b63b16741dd0472cbba1ba028bdfdcfe0e3f
[ "MIT" ]
null
null
null
busplan/time_line.cpp
gonmator/busplan
5845b63b16741dd0472cbba1ba028bdfdcfe0e3f
[ "MIT" ]
null
null
null
#include "time_line.hpp" TimeLine applyDurations(const DifTimeLine& dtline, Time start) { TimeLine rv{start}; for (auto duration: dtline.durations) { start += duration; rv.push_back(start); } return rv; }
20.166667
64
0.636364
gonmator
e7ac4f836e9d104a170b2a09124fd497d5fc4d26
1,224
cpp
C++
2017-08-04 Formatting-Exercise-Cout-Iomanip/formatting-ex-cout.cpp
gnanakeethan/cpp
51f779d9981eb4644f6a5e6e923ba68585be7988
[ "CC0-1.0" ]
null
null
null
2017-08-04 Formatting-Exercise-Cout-Iomanip/formatting-ex-cout.cpp
gnanakeethan/cpp
51f779d9981eb4644f6a5e6e923ba68585be7988
[ "CC0-1.0" ]
null
null
null
2017-08-04 Formatting-Exercise-Cout-Iomanip/formatting-ex-cout.cpp
gnanakeethan/cpp
51f779d9981eb4644f6a5e6e923ba68585be7988
[ "CC0-1.0" ]
null
null
null
#include <iostream> using namespace std; int main (void){ double up,qty,discr,total,disct,payable; int width =20; cout.width(width); cout.setf(ios::left); return 0; cout << "Enter Unit Price" << ": "; cin >> up; cout.width(width); cout.setf(ios::left); cout << "Enter Quantity" << ": "; cin >> qty; cout.width(width); cout.setf(ios::left); cout << "Enter Discount Rate" << ": "; cin >>discr; cout << "\n\n\n"; total = up*qty; disct = total*discr/100; payable = total - disct; cout.width(width); cout.fill('.'); cout.setf(ios::fixed); cout << "Total Price is" <<": " << "Rs "; cout.precision(2); cout.fill(' '); cout.width(10); cout.setf(ios::right); cout << total <<endl; cout.width(width); cout.fill('.'); cout.unsetf(ios::right); cout << "Discount is" <<": "<< "Rs "; cout.fill(' '); cout.width(10); cout.precision(2); cout.setf(ios::right); cout << disct<<endl; cout.unsetf(ios::right);cout.width(width);cout.fill('.');cout.precision(2);cout.setf(ios::fixed); cout << "Payable is" << ": "<<"Rs "; cout.width(10); cout.fill(' '); cout.setf(ios::right); cout <<payable<<endl; }
20.065574
100
0.553922
gnanakeethan
e7ad08c7d20b2dbec56a4e6238792f478bcb2d24
6,051
cpp
C++
third_party/skia_m84/third_party/externals/angle2/src/libANGLE/renderer/vulkan/win32/DisplayVkWin32.cpp
kniefliu/WindowsSamples
c841268ef4a0f1c6f89b8e95bf68058ea2548394
[ "MIT" ]
null
null
null
third_party/skia_m84/third_party/externals/angle2/src/libANGLE/renderer/vulkan/win32/DisplayVkWin32.cpp
kniefliu/WindowsSamples
c841268ef4a0f1c6f89b8e95bf68058ea2548394
[ "MIT" ]
null
null
null
third_party/skia_m84/third_party/externals/angle2/src/libANGLE/renderer/vulkan/win32/DisplayVkWin32.cpp
kniefliu/WindowsSamples
c841268ef4a0f1c6f89b8e95bf68058ea2548394
[ "MIT" ]
null
null
null
// // Copyright 2016 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // DisplayVkWin32.cpp: // Implements the class methods for DisplayVkWin32. // #include "libANGLE/renderer/vulkan/win32/DisplayVkWin32.h" #include "libANGLE/renderer/vulkan/DisplayVk.h" #include "libANGLE/renderer/vulkan/RendererVk.h" #include <windows.h> #include "libANGLE/renderer/vulkan/vk_caps_utils.h" #include "libANGLE/renderer/vulkan/vk_headers.h" #include "libANGLE/renderer/vulkan/win32/WindowSurfaceVkWin32.h" namespace rx { DisplayVkWin32::DisplayVkWin32(const egl::DisplayState &state) : DisplayVk(state), mWindowClass(NULL), mDummyWindow(nullptr) {} DisplayVkWin32::~DisplayVkWin32() {} void DisplayVkWin32::terminate() { if (mDummyWindow) { DestroyWindow(mDummyWindow); mDummyWindow = nullptr; } if (mWindowClass) { if (!UnregisterClassA(reinterpret_cast<const char *>(mWindowClass), GetModuleHandle(nullptr))) { WARN() << "Failed to unregister ANGLE window class: " << gl::FmtHex(mWindowClass); } mWindowClass = NULL; } DisplayVk::terminate(); } bool DisplayVkWin32::isValidNativeWindow(EGLNativeWindowType window) const { return (IsWindow(window) == TRUE); } SurfaceImpl *DisplayVkWin32::createWindowSurfaceVk(const egl::SurfaceState &state, EGLNativeWindowType window) { return new WindowSurfaceVkWin32(state, window); } egl::Error DisplayVkWin32::initialize(egl::Display *display) { ANGLE_TRY(DisplayVk::initialize(display)); HINSTANCE hinstance = GetModuleHandle(nullptr); std::ostringstream stream; stream << "ANGLE DisplayVkWin32 " << gl::FmtHex(display) << " Intermediate Window Class"; const LPSTR idcArrow = MAKEINTRESOURCEA(32512); std::string className = stream.str(); WNDCLASSA wndClass; if (!GetClassInfoA(hinstance, className.c_str(), &wndClass)) { WNDCLASSA intermediateClassDesc = {}; intermediateClassDesc.style = CS_OWNDC; intermediateClassDesc.lpfnWndProc = DefWindowProcA; intermediateClassDesc.cbClsExtra = 0; intermediateClassDesc.cbWndExtra = 0; intermediateClassDesc.hInstance = GetModuleHandle(nullptr); intermediateClassDesc.hIcon = nullptr; intermediateClassDesc.hCursor = LoadCursorA(nullptr, idcArrow); intermediateClassDesc.hbrBackground = 0; intermediateClassDesc.lpszMenuName = nullptr; intermediateClassDesc.lpszClassName = className.c_str(); mWindowClass = RegisterClassA(&intermediateClassDesc); if (!mWindowClass) { return egl::EglNotInitialized() << "Failed to register intermediate OpenGL window class \"" << className.c_str() << "\":" << gl::FmtErr(HRESULT_CODE(GetLastError())); } } mDummyWindow = CreateWindowExA(0, reinterpret_cast<const char *>(mWindowClass), "ANGLE Dummy Window", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, nullptr, nullptr, nullptr, nullptr); if (!mDummyWindow) { return egl::EglNotInitialized() << "Failed to create dummy OpenGL window."; } VkSurfaceKHR surfaceVk; VkWin32SurfaceCreateInfoKHR info = {VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR, nullptr, 0, GetModuleHandle(nullptr), mDummyWindow}; VkInstance instance = mRenderer->getInstance(); VkPhysicalDevice physDevice = mRenderer->getPhysicalDevice(); if (vkCreateWin32SurfaceKHR(instance, &info, nullptr, &surfaceVk) != VK_SUCCESS) { return egl::EglNotInitialized() << "vkCreateWin32SurfaceKHR failed"; } uint32_t surfaceFormatCount; if (vkGetPhysicalDeviceSurfaceFormatsKHR(physDevice, surfaceVk, &surfaceFormatCount, nullptr) != VK_SUCCESS) { return egl::EglNotInitialized() << "vkGetPhysicalDeviceSurfaceFormatsKHR failed"; } mSurfaceFormats.resize(surfaceFormatCount); if (vkGetPhysicalDeviceSurfaceFormatsKHR(physDevice, surfaceVk, &surfaceFormatCount, mSurfaceFormats.data()) != VK_SUCCESS) { return egl::EglNotInitialized() << "vkGetPhysicalDeviceSurfaceFormatsKHR (2nd) failed"; } vkDestroySurfaceKHR(instance, surfaceVk, nullptr); DestroyWindow(mDummyWindow); mDummyWindow = nullptr; return egl::NoError(); } egl::ConfigSet DisplayVkWin32::generateConfigs() { constexpr GLenum kColorFormats[] = {GL_RGB565, GL_BGRA8_EXT, GL_BGRX8_ANGLEX, GL_RGB10_A2_EXT, GL_RGBA16F_EXT}; return egl_vk::GenerateConfigs(kColorFormats, egl_vk::kConfigDepthStencilFormats, this); } bool DisplayVkWin32::checkConfigSupport(egl::Config *config) { const vk::Format &formatVk = this->getRenderer()->getFormat(config->renderTargetFormat); VkFormat nativeFormat = formatVk.vkImageFormat; // If the format list includes just one entry of VK_FORMAT_UNDEFINED, // the surface has no preferred format. Otherwise, at least one // supported format will be returned. if (mSurfaceFormats.size() == 1u && mSurfaceFormats[0].format == VK_FORMAT_UNDEFINED) { return true; } for (const VkSurfaceFormatKHR &surfaceFormat : mSurfaceFormats) { if (surfaceFormat.format == nativeFormat) { return true; } } return false; } const char *DisplayVkWin32::getWSIExtension() const { return VK_KHR_WIN32_SURFACE_EXTENSION_NAME; } bool IsVulkanWin32DisplayAvailable() { return true; } DisplayImpl *CreateVulkanWin32Display(const egl::DisplayState &state) { return new DisplayVkWin32(state); } } // namespace rx
33.430939
100
0.673112
kniefliu
e7afb45ed02cf6f452b208525637e261e33fb82c
232
cpp
C++
swig-jni/cpplib/src/main/cpp/cpplib.cpp
dickensas/kotlin-gradle-templates
dc738b9fac053ef62381ecbe88add6f6fe949fe3
[ "MIT" ]
54
2019-11-12T03:55:12.000Z
2022-03-20T14:28:02.000Z
swig-jni/cpplib/src/main/cpp/cpplib.cpp
dickensas/kotlin-gradle-templates
dc738b9fac053ef62381ecbe88add6f6fe949fe3
[ "MIT" ]
2
2020-07-31T10:50:54.000Z
2021-01-08T06:16:28.000Z
swig-jni/cpplib/src/main/cpp/cpplib.cpp
dickensas/kotlin-gradle-templates
dc738b9fac053ef62381ecbe88add6f6fe949fe3
[ "MIT" ]
14
2019-12-05T12:55:43.000Z
2022-03-10T00:47:15.000Z
/* * This C++ source file was generated by the Gradle 'init' task. */ #include <iostream> #include <stdlib.h> #include "cpplib.h" std::string jniexample::Greeter::greeting() { return std::string("Hello, World! From C++"); }
19.333333
64
0.659483
dickensas
e7afbd5ed6f7ffe5bbdcaee1b8696d62c798252c
31,985
cpp
C++
src/expr/internal_functions.cpp
raptium/BaikalDB
cbc306bf3a1c709a93f191fdd389fb14eac0952f
[ "Apache-2.0" ]
null
null
null
src/expr/internal_functions.cpp
raptium/BaikalDB
cbc306bf3a1c709a93f191fdd389fb14eac0952f
[ "Apache-2.0" ]
null
null
null
src/expr/internal_functions.cpp
raptium/BaikalDB
cbc306bf3a1c709a93f191fdd389fb14eac0952f
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2018-present Baidu, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "internal_functions.h" #include <openssl/md5.h> #include "hll_common.h" #include "datetime.h" #include <boost/date_time/gregorian/gregorian.hpp> #include <cctype> #include <cmath> #include <algorithm> namespace baikaldb { static const int32_t DATE_FORMAT_LENGTH = 128; static const std::vector<std::string> day_names = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; static const std::vector<std::string> month_names = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; ExprValue round(const std::vector<ExprValue>& input) { if (input.size() == 0 || input[0].is_null()) { return ExprValue::Null(); } int bits = input.size() == 2 ? input[1].get_numberic<int>() : 0; double base = std::pow(10, bits); double orgin = input[0].get_numberic<double>(); ExprValue tmp(pb::DOUBLE); if (base > 0) { if (orgin < 0) { tmp._u.double_val = -::round(-orgin * base) / base; } else { tmp._u.double_val = ::round(orgin * base) / base; } } return tmp; } ExprValue floor(const std::vector<ExprValue>& input) { if (input.size() == 0 || input[0].is_null()) { return ExprValue::Null(); } ExprValue tmp(pb::INT64); tmp._u.int64_val = ::floor(input[0].get_numberic<double>()); return tmp; } ExprValue ceil(const std::vector<ExprValue>& input) { if (input.size() == 0 || input[0].is_null()) { return ExprValue::Null(); } ExprValue tmp(pb::INT64); tmp._u.int64_val = ::ceil(input[0].get_numberic<double>()); return tmp; } ExprValue abs(const std::vector<ExprValue>& input) { if (input.size() == 0 || input[0].is_null()) { return ExprValue::Null(); } ExprValue tmp(pb::DOUBLE); tmp._u.double_val = ::abs(input[0].get_numberic<double>()); return tmp; } ExprValue sqrt(const std::vector<ExprValue>& input) { if (input.size() == 0 || input[0].is_null()) { return ExprValue::Null(); } double val = input[0].get_numberic<double>(); if (val < 0) { return ExprValue::Null(); } ExprValue tmp(pb::DOUBLE); tmp._u.double_val = std::sqrt(val); return tmp; } ExprValue mod(const std::vector<ExprValue>& input) { if (input.size() < 2 || input[0].is_null() || input[1].is_null()) { return ExprValue::Null(); } double rhs = input[1].get_numberic<double>(); if (float_equal(rhs, 0)) { return ExprValue::Null(); } double lhs = input[0].get_numberic<double>(); ExprValue tmp(pb::DOUBLE); tmp._u.double_val = std::fmod(lhs, rhs); return tmp; } ExprValue rand(const std::vector<ExprValue>& input) { ExprValue tmp(pb::DOUBLE); tmp._u.double_val = butil::fast_rand_double(); return tmp; } ExprValue sign(const std::vector<ExprValue>& input) { if (input.size() < 1 || input[0].is_null()) { return ExprValue::Null(); } ExprValue tmp(pb::INT64); double val = input[0].get_numberic<double>(); tmp._u.int64_val = val > 0 ? 1 : (val < 0 ? -1 : 0); return tmp; } ExprValue sin(const std::vector<ExprValue>& input) { if (input.size() < 1 || input[0].is_null()) { return ExprValue::Null(); } ExprValue tmp(pb::DOUBLE); tmp._u.double_val = std::sin(input[0].get_numberic<double>()); return tmp; } ExprValue asin(const std::vector<ExprValue>& input) { if (input.size() < 1 || input[0].is_null()) { return ExprValue::Null(); } ExprValue tmp(pb::DOUBLE); double val = input[0].get_numberic<double>(); if (val < -1 || val > 1) { return ExprValue::Null(); } tmp._u.double_val = std::asin(val); return tmp; } ExprValue cos(const std::vector<ExprValue>& input) { if (input.size() < 1 || input[0].is_null()) { return ExprValue::Null(); } ExprValue tmp(pb::DOUBLE); tmp._u.double_val = std::cos(input[0].get_numberic<double>()); return tmp; } ExprValue acos(const std::vector<ExprValue>& input) { if (input.size() < 1 || input[0].is_null()) { return ExprValue::Null(); } double val = input[0].get_numberic<double>(); if (val < -1 || val > 1) { return ExprValue::Null(); } ExprValue tmp(pb::DOUBLE); tmp._u.double_val = std::acos(val); return tmp; } ExprValue tan(const std::vector<ExprValue>& input) { if (input.size() < 1 || input[0].is_null()) { return ExprValue::Null(); } ExprValue tmp(pb::DOUBLE); tmp._u.double_val = std::tan(input[0].get_numberic<double>()); return tmp; } ExprValue cot(const std::vector<ExprValue>& input) { if (input.size() < 1 || input[0].is_null()) { return ExprValue::Null(); } ExprValue tmp(pb::DOUBLE); double val = input[0].get_numberic<double>(); double sin_val = std::sin(val); double cos_val = std::cos(val); if (float_equal(sin_val, 0)) { return ExprValue::Null(); } tmp._u.double_val = cos_val/sin_val; return tmp; } ExprValue atan(const std::vector<ExprValue>& input) { if (input.size() < 1 || input[0].is_null()) { return ExprValue::Null(); } ExprValue tmp(pb::DOUBLE); tmp._u.double_val = std::atan(input[0].get_numberic<double>()); return tmp; } ExprValue ln(const std::vector<ExprValue>& input) { if (input.size() < 1 || input[0].is_null()) { return ExprValue::Null(); } double val = input[0].get_numberic<double>(); if (val <= 0) { return ExprValue::Null(); } ExprValue tmp(pb::DOUBLE); tmp._u.double_val = std::log(input[0].get_numberic<double>()); return tmp; } ExprValue log(const std::vector<ExprValue>& input) { if (input.size() < 2 || input[0].is_null() || input[1].is_null()) { return ExprValue::Null(); } double base = input[0].get_numberic<double>(); double val = input[1].get_numberic<double>(); if (base <= 0 || val <= 0 || base == 1) { return ExprValue::Null(); } ExprValue tmp(pb::DOUBLE); tmp._u.double_val = std::log(val) / std::log(base); return tmp; } ExprValue pow(const std::vector<ExprValue>& input) { if (input.size() < 2 || input[0].is_null() || input[1].is_null()) { return ExprValue::Null(); } double base = input[0].get_numberic<double>(); double exp = input[1].get_numberic<double>(); ExprValue tmp(pb::DOUBLE); tmp._u.double_val = std::pow(base, exp); return tmp; } ExprValue pi(const std::vector<ExprValue>& input) { ExprValue tmp(pb::DOUBLE); tmp._u.double_val = M_PI; return tmp; } ExprValue greatest(const std::vector<ExprValue>& input) { bool find_flag = false; double ret = std::numeric_limits<double>::lowest(); for (const auto& item : input) { if (item.is_null()) { return ExprValue::Null(); } else { double val = item.get_numberic<double>(); if (!find_flag) { find_flag = true; ret = val; } else { if (val > ret) { ret = val; } } } } if (find_flag) { ExprValue tmp(pb::DOUBLE); tmp._u.double_val = ret; return tmp; } else { return ExprValue::Null(); } } ExprValue least(const std::vector<ExprValue>& input) { bool find_flag = false; double ret = std::numeric_limits<double>::max(); for (const auto& item : input) { if (item.is_null()) { return ExprValue::Null(); } else { double val = item.get_numberic<double>(); if (!find_flag) { find_flag = true; ret = val; } else { if (val < ret) { ret = val; } } } } if (find_flag) { ExprValue tmp(pb::DOUBLE); tmp._u.double_val = ret; return tmp; } else { return ExprValue::Null(); } } ExprValue length(const std::vector<ExprValue>& input) { if (input.size() == 0 || input[0].is_null()) { return ExprValue::Null(); } ExprValue tmp(pb::UINT32); tmp._u.uint32_val = input[0].get_string().size(); return tmp; } ExprValue bit_length(const std::vector<ExprValue>& input) { if (input.size() == 0 || input[0].is_null()) { return ExprValue::Null(); } ExprValue tmp(pb::UINT32); tmp._u.uint32_val = input[0].get_string().size() * 8; return tmp; } ExprValue lower(const std::vector<ExprValue>& input) { if (input.size() == 0 || input[0].is_null()) { return ExprValue::Null(); } ExprValue tmp(pb::STRING); tmp.str_val = input[0].get_string(); std::transform(tmp.str_val.begin(), tmp.str_val.end(), tmp.str_val.begin(), ::tolower); return tmp; } ExprValue lower_gbk(const std::vector<ExprValue>& input) { if (input.size() == 0 || input[0].is_null()) { return ExprValue::Null(); } ExprValue tmp(pb::STRING); tmp.str_val = input[0].get_string(); std::string& literal = tmp.str_val; size_t idx = 0; while (idx < literal.size()) { if ((literal[idx] & 0x80) != 0) { idx += 2; } else { literal[idx] = tolower(literal[idx]); idx++; } } return tmp; } ExprValue upper(const std::vector<ExprValue>& input) { if (input.size() == 0 || input[0].is_null()) { return ExprValue::Null(); } ExprValue tmp(pb::STRING); tmp.str_val = input[0].get_string(); std::transform(tmp.str_val.begin(), tmp.str_val.end(), tmp.str_val.begin(), ::toupper); return tmp; } ExprValue concat(const std::vector<ExprValue>& input) { ExprValue tmp(pb::STRING); for (auto& s : input) { if (s.is_null()) { return ExprValue::Null(); } tmp.str_val += s.get_string(); } return tmp; } ExprValue substr(const std::vector<ExprValue>& input) { if (input.size() < 2) { return ExprValue::Null(); } for (auto& s : input) { if (s.is_null()) { return ExprValue::Null(); } } std::string str = input[0].get_string(); ExprValue tmp(pb::STRING); int pos = input[1].get_numberic<int>(); if (pos < 0) { pos = str.size() + pos; } else { --pos; } if (pos < 0 || pos >= (int)str.size()) { return tmp; } int len = -1; if (input.size() == 3) { len = input[2].get_numberic<int>(); if (len <= 0) { return tmp; } } tmp.str_val = str; if (len == -1) { tmp.str_val = tmp.str_val.substr(pos); } else { tmp.str_val = tmp.str_val.substr(pos, len); } return tmp; } ExprValue left(const std::vector<ExprValue>& input) { if (input.size() < 2) { return ExprValue::Null(); } for (auto& s : input) { if (s.is_null()) { return ExprValue::Null(); } } ExprValue tmp(pb::STRING); int len = input[1].get_numberic<int>(); if (len <= 0) { return tmp; } tmp.str_val = input[0].str_val; tmp.str_val = tmp.str_val.substr(0, len); return tmp; } ExprValue right(const std::vector<ExprValue>& input) { if (input.size() < 2) { return ExprValue::Null(); } for (auto& s : input) { if (s.is_null()) { return ExprValue::Null(); } } ExprValue tmp(pb::STRING); int len = input[1].get_numberic<int>(); if (len <= 0) { return tmp; } int pos = input[0].str_val.size() - len; if (pos < 0) { pos = 0; } tmp.str_val = input[0].str_val; tmp.str_val = tmp.str_val.substr(pos); return tmp; } ExprValue trim(const std::vector<ExprValue>& input) { if (input.size() != 1) { return ExprValue::Null(); } ExprValue tmp(pb::STRING); tmp.str_val = input[0].str_val; tmp.str_val.erase(0, tmp.str_val.find_first_not_of(" ")); tmp.str_val.erase(tmp.str_val.find_last_not_of(" ") + 1); return tmp; } ExprValue ltrim(const std::vector<ExprValue>& input) { if (input.size() != 1) { return ExprValue::Null(); } ExprValue tmp(pb::STRING); tmp.str_val = input[0].str_val; tmp.str_val.erase(0, tmp.str_val.find_first_not_of(" ")); return tmp; } ExprValue rtrim(const std::vector<ExprValue>& input) { if (input.size() != 1) { return ExprValue::Null(); } ExprValue tmp(pb::STRING); tmp.str_val = input[0].str_val; tmp.str_val.erase(tmp.str_val.find_last_not_of(" ") + 1); return tmp; } ExprValue concat_ws(const std::vector<ExprValue>& input) { if (input.size() < 2) { return ExprValue::Null(); } if (input[0].is_null()) { return ExprValue::Null(); } ExprValue tmp(pb::STRING); bool first_push = false; for (int i = 1; i < input.size(); i++) { if (!input[i].is_null()) { if (!first_push) { first_push = true; tmp.str_val = input[i].get_string(); } else { tmp.str_val += input[0].get_string() + input[i].get_string(); } } } if (!first_push) { return ExprValue::Null(); } return tmp; } ExprValue ascii(const std::vector<ExprValue>& input) { if (input.size() < 1) { return ExprValue::Null(); } if (input[0].is_null()) { return ExprValue::Null(); } ExprValue tmp(pb::INT32); if (input[0].str_val.empty()) { tmp._u.int32_val = 0; } else { tmp._u.int32_val = static_cast<int32_t>(input[0].str_val[0]); } return tmp; } ExprValue strcmp(const std::vector<ExprValue>& input) { if (input.size() != 2) { return ExprValue::Null(); } ExprValue tmp(pb::INT32); int64_t ret = input[0].compare(input[1]); if (ret < 0) { tmp._u.int32_val = -1; } else if (ret > 0) { tmp._u.int32_val = 1; } else { tmp._u.int32_val = 0; } return tmp; } ExprValue insert(const std::vector<ExprValue>& input) { if (input.size() != 4) { return ExprValue::Null(); } for (auto s : input) { if (s.is_null()) { return ExprValue::Null(); } } int pos = input[1].get_numberic<int>(); if (pos < 0) { return input[0]; } int len = input[2].get_numberic<int>(); if (len <= 0) { return input[0]; } ExprValue tmp(pb::STRING); tmp.str_val = input[0].str_val; tmp.str_val.replace(pos, len, input[2].str_val); return tmp; } ExprValue replace(const std::vector<ExprValue>& input) { if (input.size() != 3) { return ExprValue::Null(); } if (input[0].is_null()) { return ExprValue::Null(); } if (input[1].str_val.empty()) { return input[0]; } ExprValue tmp(pb::STRING); tmp.str_val = input[0].str_val; for (auto pos = 0; pos != std::string::npos; pos += input[2].str_val.length()) { pos = tmp.str_val.find(input[1].str_val, pos); if (pos != std::string::npos) { tmp.str_val.replace(pos, input[1].str_val.length(), input[2].str_val); } else { break; } } return tmp; } ExprValue repeat(const std::vector<ExprValue>& input) { if (input.size() != 2) { return ExprValue::Null(); } if (input[0].is_null()) { return ExprValue::Null(); } int len = input[1].get_numberic<int>(); if (len <= 0) { return ExprValue::Null(); } std::string val = input[0].get_string(); ExprValue tmp(pb::STRING); tmp.str_val.reserve(val.size() * len); for (int i = 0; i < len; i++) { tmp.str_val += val; } return tmp; } ExprValue reverse(const std::vector<ExprValue>& input) { if (input.size() != 1) { return ExprValue::Null(); } if (input[0].is_null()) { return ExprValue::Null(); } ExprValue tmp(pb::STRING); tmp.str_val = input[0].get_string(); std::reverse(tmp.str_val.begin(), tmp.str_val.end()); return tmp; } ExprValue locate(const std::vector<ExprValue>& input) { if (input.size() < 2 || input.size() > 3) { return ExprValue::Null(); } for (auto s : input) { if (s.is_null()) { return ExprValue::Null(); } } int begin_pos = 0; if (input.size() == 3) { begin_pos = input[2].get_numberic<int>(); } ExprValue tmp(pb::INT32); auto pos = input[1].str_val.find(input[0].str_val, begin_pos); if (pos != std::string::npos) { tmp._u.int32_val = pos; } else { tmp._u.int32_val = 0; } return tmp; } ExprValue unix_timestamp(const std::vector<ExprValue>& input) { ExprValue tmp(pb::UINT32); if (input.size() == 0) { tmp._u.uint32_val = time(NULL); } else { if (input[0].is_null()) { return ExprValue::Null(); } ExprValue in = input[0]; if (in.type == pb::INT64) { in.cast_to(pb::STRING); } tmp._u.uint32_val = in.cast_to(pb::TIMESTAMP)._u.uint32_val; } return tmp; } ExprValue from_unixtime(const std::vector<ExprValue>& input) { if (input.size() == 0 || input[0].is_null()) { return ExprValue::Null(); } ExprValue tmp(pb::TIMESTAMP); tmp._u.uint32_val = input[0].get_numberic<uint32_t>(); return tmp; } ExprValue now(const std::vector<ExprValue>& input) { return ExprValue::Now(); } ExprValue date_format(const std::vector<ExprValue>& input) { if (input.size() != 2) { return ExprValue::Null(); } for (auto& s : input) { if (s.is_null()) { return ExprValue::Null(); } } ExprValue tmp = input[0]; time_t t = tmp.cast_to(pb::TIMESTAMP)._u.uint32_val; struct tm t_result; localtime_r(&t, &t_result); char s[DATE_FORMAT_LENGTH]; strftime(s, sizeof(s), input[1].str_val.c_str(), &t_result); ExprValue format_result(pb::STRING); format_result.str_val = s; return format_result; } ExprValue timediff(const std::vector<ExprValue>& input) { if (input.size() < 2) { return ExprValue::Null(); } for (auto& s : input) { if (s.is_null()) { return ExprValue::Null(); } } ExprValue arg1 = input[0]; ExprValue arg2 = input[1]; int32_t seconds = arg1.cast_to(pb::TIMESTAMP)._u.uint32_val - arg2.cast_to(pb::TIMESTAMP)._u.uint32_val; ExprValue ret(pb::TIME); ret._u.int32_val = seconds_to_time(seconds); return ret; } ExprValue timestampdiff(const std::vector<ExprValue>& input) { if (input.size() < 3) { return ExprValue::Null(); } for (auto& s : input) { if (s.is_null()) { return ExprValue::Null(); } } ExprValue arg2 = input[1]; ExprValue arg3 = input[2]; int32_t seconds = arg3.cast_to(pb::TIMESTAMP)._u.uint32_val - arg2.cast_to(pb::TIMESTAMP)._u.uint32_val; ExprValue ret(pb::INT64); if (input[0].str_val == "second") { ret._u.int64_val = seconds; } else if (input[0].str_val == "minute") { ret._u.int64_val = seconds / 60; } else if (input[0].str_val == "hour") { ret._u.int64_val = seconds / 3600; } else if (input[0].str_val == "day") { ret._u.int64_val = seconds / (24 * 3600); } else { // un-support return ExprValue::Null(); } return ret; } ExprValue curdate(const std::vector<ExprValue>& input) { ExprValue tmp(pb::DATE); uint64_t datetime = timestamp_to_datetime(time(NULL)); tmp._u.uint32_val = (datetime >> 41) & 0x3FFFFF; return tmp; } ExprValue current_date(const std::vector<ExprValue>& input) { return curdate(input); } ExprValue curtime(const std::vector<ExprValue>& input) { ExprValue tmp(pb::TIME); uint64_t datetime = timestamp_to_datetime(time(NULL)); tmp._u.int32_val = datetime_to_time(datetime); return tmp; } ExprValue current_time(const std::vector<ExprValue>& input) { return curtime(input); } ExprValue day(const std::vector<ExprValue>& input) { if (input.size() == 0 || input[0].is_null()) { return ExprValue::Null(); } ExprValue in = input[0]; if (in.type == pb::INT64) { in.cast_to(pb::STRING); } ExprValue tmp(pb::UINT32); time_t t = in.cast_to(pb::TIMESTAMP)._u.uint32_val; struct tm tm; localtime_r(&t, &tm); tmp._u.uint32_val = tm.tm_mday; return tmp; } ExprValue dayname(const std::vector<ExprValue>& input) { if (input.size() == 0 || input[0].is_null()) { return ExprValue::Null(); } ExprValue tmp(pb::STRING); uint32_t week_num = dayofweek(input)._u.uint32_val; if (week_num <= day_names.size()) { tmp.str_val = day_names[week_num - 1]; } return tmp; } ExprValue monthname(const std::vector<ExprValue>& input) { if (input.size() == 0 || input[0].is_null()) { return ExprValue::Null(); } uint32_t month_num = month(input)._u.uint32_val; ExprValue tmp(pb::STRING); if (month_num <= month_names.size()) { tmp.str_val = month_names[month_num - 1]; } return tmp; } ExprValue dayofweek(const std::vector<ExprValue>& input) { if (input.size() == 0 || input[0].is_null()) { return ExprValue::Null(); } ExprValue in = input[0]; if (in.type == pb::INT64) { in.cast_to(pb::STRING); } ExprValue tmp(pb::UINT32); time_t t = in.cast_to(pb::TIMESTAMP)._u.uint32_val; struct tm tm; localtime_r(&t, &tm); boost::gregorian::date today(tm.tm_year + 1900, ++tm.tm_mon, tm.tm_mday); /* DAYOFWEEK(d) 函数返回 d 对应的一周中的索引(位置)。1 表示周日,2 表示周一,……,7 表示周六 */ tmp._u.uint32_val = today.day_of_week() + 1; return tmp; } ExprValue dayofmonth(const std::vector<ExprValue>& input) { return day(input); } ExprValue month(const std::vector<ExprValue>& input) { if (input.size() == 0 || input[0].is_null()) { return ExprValue::Null(); } ExprValue in = input[0]; if (in.type == pb::INT64) { in.cast_to(pb::STRING); } ExprValue tmp(pb::UINT32); time_t t = in.cast_to(pb::TIMESTAMP)._u.uint32_val; struct tm tm; localtime_r(&t, &tm); tmp._u.uint32_val = ++tm.tm_mon; return tmp; } ExprValue year(const std::vector<ExprValue>& input) { if (input.size() == 0 || input[0].is_null()) { return ExprValue::Null(); } ExprValue in = input[0]; if (in.type == pb::INT64) { in.cast_to(pb::STRING); } ExprValue tmp(pb::UINT32); time_t t = in.cast_to(pb::TIMESTAMP)._u.uint32_val; struct tm tm; localtime_r(&t, &tm); tmp._u.uint32_val = tm.tm_year + 1900; return tmp; } ExprValue time_to_sec(const std::vector<ExprValue>& input) { if (input.size() == 0 || input[0].is_null()) { return ExprValue::Null(); } ExprValue tmp(pb::INT32); ExprValue in = input[0]; time_t time = in.cast_to(pb::TIME)._u.int32_val; bool minus = false; if (time < 0) { minus = true; time = -time; } uint32_t hour = (time >> 12) & 0x3FF; uint32_t min = (time >> 6) & 0x3F; uint32_t sec = time & 0x3F; uint32_t sec_sum = hour * 3600 + min * 60 + sec; if (!minus) { tmp._u.int32_val = sec_sum; } else { tmp._u.int32_val = -sec_sum; } return tmp; } ExprValue sec_to_time(const std::vector<ExprValue>& input) { if (input.size() == 0 || input[0].is_null()) { return ExprValue::Null(); } ExprValue in = input[0]; if (in.type == pb::STRING) { in.cast_to(pb::INT32); } int32_t secs = in._u.int32_val; bool minus = false; if (secs < 0) { minus = true; secs = - secs; } ExprValue tmp(pb::TIME); uint32_t hour = secs / 3600; uint32_t min = (secs - hour * 3600) / 60; uint32_t sec = secs % 60; int32_t time = 0; time |= sec; time |= (min << 6); time |= (hour << 12); if (minus) { time = -time; } tmp._u.int32_val = time; return tmp; } ExprValue dayofyear(const std::vector<ExprValue>& input) { if (input.size() == 0 || input[0].is_null()) { return ExprValue::Null(); } ExprValue in = input[0]; if (in.type == pb::INT64) { in.cast_to(pb::STRING); } ExprValue tmp(pb::UINT32); time_t t = in.cast_to(pb::TIMESTAMP)._u.uint32_val; struct tm tm; localtime_r(&t, &tm); boost::gregorian::date today(tm.tm_year += 1900, ++tm.tm_mon, tm.tm_mday); tmp._u.uint32_val = today.day_of_year(); return tmp; } ExprValue weekday(const std::vector<ExprValue>& input) { if (input.size() == 0 || input[0].is_null()) { return ExprValue::Null(); } ExprValue in = input[0]; if (in.type == pb::INT64) { in.cast_to(pb::STRING); } ExprValue one = input[0]; time_t t = one.cast_to(pb::TIMESTAMP)._u.uint32_val; struct tm tm; localtime_r(&t, &tm); boost::gregorian::date today(tm.tm_year + 1900, ++tm.tm_mon, tm.tm_mday); ExprValue tmp(pb::UINT32); uint32_t day_of_week = today.day_of_week(); if (day_of_week >= 1) { tmp._u.uint32_val = day_of_week - 1; } else { tmp._u.uint32_val = 6; } return tmp; } ExprValue week(const std::vector<ExprValue>& input) { if (input.size() == 0 || input[0].is_null()) { return ExprValue::Null(); } ExprValue one = input[0]; time_t t = one.cast_to(pb::TIMESTAMP)._u.uint32_val; struct tm tm; localtime_r(&t, &tm); boost::gregorian::date today(tm.tm_year += 1900, ++tm.tm_mon, tm.tm_mday); uint32_t week_number = today.week_number(); ExprValue tmp(pb::UINT32); if (input.size() > 1) { ExprValue two = input[1]; uint32_t mode = two.cast_to(pb::UINT32)._u.uint32_val; if (!mode) { week_number -= 1; } } tmp._u.uint32_val = week_number; return tmp; } ExprValue datediff(const std::vector<ExprValue>& input) { if (input.size() == 0 || input[0].is_null() || input[1].is_null()) { return ExprValue::Null(); } ExprValue left = input[0]; if (left.type == pb::INT64) { left.cast_to(pb::STRING); } ExprValue right = input[1]; if (right.type == pb::INT64) { right.cast_to(pb::STRING); } time_t t1 = left.cast_to(pb::TIMESTAMP)._u.uint32_val; time_t t2 = right.cast_to(pb::TIMESTAMP)._u.uint32_val; ExprValue tmp(pb::INT32); tmp._u.int32_val = (t1 - t2) / (3600 * 24); return tmp; } ExprValue hll_add(const std::vector<ExprValue>& input) { if (input.size() == 0) { return ExprValue::Null(); } if (!input[0].is_hll()) { (ExprValue&)input[0] = hll::hll_init(); } for (size_t i = 1; i < input.size(); i++) { if (!input[i].is_null()) { hll::hll_add((ExprValue&)input[0], input[i].hash()); } } return input[0]; } ExprValue hll_init(const std::vector<ExprValue>& input) { if (input.size() == 0) { return ExprValue::Null(); } ExprValue hll_init = hll::hll_init(); for (size_t i = 0; i < input.size(); i++) { if (!input[i].is_null()) { hll::hll_add(hll_init, input[i].hash()); } } return hll_init; } ExprValue hll_merge(const std::vector<ExprValue>& input) { if (input.size() == 0) { return ExprValue::Null(); } if (!input[0].is_hll()) { (ExprValue&)input[0] = hll::hll_init(); } for (size_t i = 1; i < input.size(); i++) { if (input[i].is_hll()) { hll::hll_merge((ExprValue&)input[0], (ExprValue&)input[i]); } } return input[0]; } ExprValue hll_estimate(const std::vector<ExprValue>& input) { if (input.size() == 0) { return ExprValue::Null(); } ExprValue tmp(pb::INT64); if (input[0].is_null()) { tmp._u.int64_val = 0; return tmp; } tmp._u.int64_val = hll::hll_estimate(input[0]); return tmp; } ExprValue case_when(const std::vector<ExprValue>& input) { for (size_t i = 0; i < input.size() / 2; ++i) { auto if_index = i * 2; auto then_index = i * 2 + 1; if (input[if_index].get_numberic<bool>()) { return input[then_index]; } } //没有else分支, 返回null if (input.size() % 2 == 0) { return ExprValue(); } else { return input[input.size() - 1]; } } ExprValue case_expr_when(const std::vector<ExprValue>& input) { for (size_t i = 0; i < (input.size() - 1) / 2; ++i) { auto if_index = i * 2 + 1; auto then_index = i * 2 + 2; if (input[0].compare(input[if_index]) == 0) { return input[then_index]; } } //没有else分支, 返回null if ((input.size() - 1) % 2 == 0) { return ExprValue(); } else { return input[input.size() - 1]; } } ExprValue if_(const std::vector<ExprValue>& input) { if (input.size() != 3) { return ExprValue::Null(); } return input[0].get_numberic<bool>() ? input[1] : input[2]; } ExprValue ifnull(const std::vector<ExprValue>& input) { if (input.size() != 2) { return ExprValue::Null(); } return input[0].is_null() ? input[1] : input[0]; } ExprValue nullif(const std::vector<ExprValue>& input) { if (input.size() != 2) { return ExprValue::Null(); } ExprValue arg1 = input[0]; ExprValue arg2 = input[1]; if (arg1.compare_diff_type(arg2) == 0) { return ExprValue::Null(); } else { return input[0]; } } ExprValue murmur_hash(const std::vector<ExprValue>& input) { if (input.size() == 0) { return ExprValue::Null(); } ExprValue tmp(pb::UINT64); if (input.size() == 0) { tmp._u.uint64_val = 0; } else { tmp._u.uint64_val = make_sign(input[0].str_val); } return tmp; } ExprValue md5(const std::vector<ExprValue>& input) { if (input.size() == 0) { return ExprValue::Null(); } ExprValue orig = input[0]; if (orig.type != pb::STRING) { orig.cast_to(pb::STRING); } ExprValue tmp(pb::STRING); unsigned char md5_str[16] = {0}; MD5_CTX ctx; MD5_Init(&ctx); MD5_Update(&ctx, orig.str_val.c_str(), orig.str_val.size()); MD5_Final(md5_str, &ctx); tmp.str_val.resize(32); int j = 0; static char const zEncode[] = "0123456789abcdef"; for (int i = 0; i < 16; i ++) { int a = md5_str[i]; tmp.str_val[j++] = zEncode[(a >> 4) & 0xf]; tmp.str_val[j++] = zEncode[a & 0xf]; } return tmp; } ExprValue sha1(const std::vector<ExprValue>& input) { if (input.size() == 0) { return ExprValue::Null(); } ExprValue orig = input[0]; if (orig.type != pb::STRING) { orig.cast_to(pb::STRING); } ExprValue tmp(pb::STRING); tmp.str_val = butil::SHA1HashString(orig.str_val); return tmp; } ExprValue sha(const std::vector<ExprValue>& input) { return sha1(input); } } /* vim: set ts=4 sw=4 sts=4 tw=100 */
27.175021
92
0.565421
raptium
e7b01a167b81d2411ed0648ce0f5c2af04c597a5
44,745
cpp
C++
sqldata/sqlmysqlapi.cpp
strk/sqlines
82676a3b672bc218a024712abeb85279ae75495c
[ "Apache-2.0" ]
null
null
null
sqldata/sqlmysqlapi.cpp
strk/sqlines
82676a3b672bc218a024712abeb85279ae75495c
[ "Apache-2.0" ]
null
null
null
sqldata/sqlmysqlapi.cpp
strk/sqlines
82676a3b672bc218a024712abeb85279ae75495c
[ "Apache-2.0" ]
null
null
null
/** * Copyright (c) 2016 SQLines * * 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. */ // SqlMysqlApi MySQL C API #if defined(WIN32) || defined(_WIN64) #include <process.h> #endif #include <stdio.h> #include "sqlmysqlapi.h" #include "../sqlcommon/str.h" #include "../sqlcommon/os.h" // Required to access ODBC and CT-Lib constants #include <sql.h> #include <sqlext.h> #include <ctpublic.h> #if defined(WIN32) || defined(WIN64) HMODULE SqlMysqlApi::_dll = NULL; #else void* SqlMysqlApi::_dll = NULL; #endif mysql_initFunc SqlMysqlApi::_mysql_init = NULL; mysql_closeFunc SqlMysqlApi::_mysql_close = NULL; mysql_errnoFunc SqlMysqlApi::_mysql_errno = NULL; mysql_errorFunc SqlMysqlApi::_mysql_error = NULL; mysql_fetch_fieldsFunc SqlMysqlApi::_mysql_fetch_fields = NULL; mysql_fetch_rowFunc SqlMysqlApi::_mysql_fetch_row = NULL; mysql_fetch_lengthsFunc SqlMysqlApi::_mysql_fetch_lengths = NULL; mysql_free_resultFunc SqlMysqlApi::_mysql_free_result = NULL; mysql_num_fieldsFunc SqlMysqlApi::_mysql_num_fields = NULL; mysql_optionsFunc SqlMysqlApi::_mysql_options = NULL; mysql_real_connectFunc SqlMysqlApi::_mysql_real_connect = NULL; mysql_queryFunc SqlMysqlApi::_mysql_query = NULL; mysql_set_character_setFunc SqlMysqlApi::_mysql_set_character_set = NULL; mysql_set_local_infile_handlerFunc SqlMysqlApi::_mysql_set_local_infile_handler = NULL; mysql_thread_initFunc SqlMysqlApi::_mysql_thread_init = NULL; mysql_use_resultFunc SqlMysqlApi::_mysql_use_result = NULL; // Constructor SqlMysqlApi::SqlMysqlApi() { _cursor_result = NULL; _ldi_rc = 0; _ldi_terminated = 0; _ldi_cols_count = 0; _ldi_rows_count = 0; _ldi_cols = NULL; _ldi_current_row = 0; _ldi_current_col = 0; _ldi_current_col_len = 0; _ldi_write_newline = false; _ldi_lob_data = NULL; _ldi_lob_size = 0; _ldi_bytes = 0; _ldi_bytes_all = 0; _port = 0; #if defined(WIN32) || defined(WIN64) _wait_event = NULL; _completed_event = NULL; #endif } SqlMysqlApi::~SqlMysqlApi() { Deallocate(); } // Initialize API for process (MySQL C library can be compiled as non thread-safe) int SqlMysqlApi::InitStatic() { if(_static_init == true) return 0; TRACE("MySQL/C InitStatic() Entered"); const char *mysql_default_lib = MYSQL_C_DLL; const char *mysql_load_error = MYSQL_DLL_LOAD_ERROR; const char *mysql_64bit_load_error = MYSQL_64BIT_DLL_LOAD_ERROR; const char *mysql_c_func_load_error = MYSQL_C_FUNC_LOAD_ERROR; const char *mysql_lib = NULL; if(_subtype == SQLDATA_SUBTYPE_MARIADB) { TRACE("MySQL/C InitStatic() for MariaDB"); mysql_default_lib = MARIADB_C_DLL; mysql_load_error = MARIADB_DLL_LOAD_ERROR; mysql_64bit_load_error = MARIADB_64BIT_DLL_LOAD_ERROR; mysql_c_func_load_error = MARIADB_C_FUNC_LOAD_ERROR; if(_parameters != NULL) mysql_lib = _parameters->Get("-mariadb_lib"); } if(mysql_lib != NULL) { TRACE_P("MySQL/C InitStatic() library: %s", mysql_lib); _dll = Os::LoadLibrary(mysql_lib); } else { // Try to load the library by default path TRACE_P("MySQL/C InitStatic() default library: %s", mysql_default_lib); _dll = Os::LoadLibrary(mysql_default_lib); } if(_dll == NULL) { Os::GetLastErrorText(mysql_load_error, _native_error_text, 1024); TRACE_P("MySQL/C InitStatic() error: %s", _native_error_text); } // DLL load failed (do not search if library path is set) if(_dll == NULL && mysql_lib == NULL) { #if defined(WIN32) || defined(_WIN64) // No error set if DLL is 64-bit and current sqldata build is 32-bit bool sf = Os::Is64Bit(mysql_default_lib); if(sf == true) strcpy(_native_error_text, mysql_64bit_load_error); // Try to find MySQL installation paths // Note that search is performed for MySQL C Connector even for MariaDB FindMysqlPaths(); for(std::list<std::string>::iterator i = _driver_paths.begin(); i != _driver_paths.end() ; i++) { std::string loc = (*i); loc += MYSQL_C_DLL; // Try to open DLL _dll = LoadLibrary(loc.c_str()); if(_dll != NULL) break; // Set error for the current search item Os::GetLastErrorText(MYSQL_DLL_LOAD_ERROR, _native_error_text, 1024); // No error set if DLL is 64-bit sf = Os::Is64Bit(MYSQL_C_DLL); if(sf == true) strcpy(_native_error_text, MYSQL_64BIT_DLL_LOAD_ERROR); } #else char *error = Os::LoadLibraryError(); if(error != NULL) strcpy(_native_error_text, error); #endif } // Get functions if(_dll != NULL) { // Save the full path of the loaded driver Os::GetModuleFileName(_dll, _loaded_driver, 1024); _mysql_init = (mysql_initFunc)Os::GetProcAddress(_dll, "mysql_init"); _mysql_close = (mysql_closeFunc)Os::GetProcAddress(_dll, "mysql_close"); _mysql_errno = (mysql_errnoFunc)Os::GetProcAddress(_dll, "mysql_errno"); _mysql_error = (mysql_errorFunc)Os::GetProcAddress(_dll, "mysql_error"); _mysql_fetch_fields = (mysql_fetch_fieldsFunc)Os::GetProcAddress(_dll, "mysql_fetch_fields"); _mysql_fetch_row = (mysql_fetch_rowFunc)Os::GetProcAddress(_dll, "mysql_fetch_row"); _mysql_fetch_lengths = (mysql_fetch_lengthsFunc)Os::GetProcAddress(_dll, "mysql_fetch_lengths"); _mysql_free_result = (mysql_free_resultFunc)Os::GetProcAddress(_dll, "mysql_free_result"); _mysql_num_fields = (mysql_num_fieldsFunc)Os::GetProcAddress(_dll, "mysql_num_fields"); _mysql_options = (mysql_optionsFunc)Os::GetProcAddress(_dll, "mysql_options"); _mysql_real_connect = (mysql_real_connectFunc)Os::GetProcAddress(_dll, "mysql_real_connect"); _mysql_query = (mysql_queryFunc)Os::GetProcAddress(_dll, "mysql_query"); _mysql_set_character_set = (mysql_set_character_setFunc)Os::GetProcAddress(_dll, "mysql_set_character_set"); _mysql_set_local_infile_handler = (mysql_set_local_infile_handlerFunc)Os::GetProcAddress(_dll, "mysql_set_local_infile_handler"); _mysql_thread_init = (mysql_thread_initFunc)Os::GetProcAddress(_dll, "mysql_thread_init"); _mysql_use_result = (mysql_use_resultFunc)Os::GetProcAddress(_dll, "mysql_use_result"); // mysql_set_character_set is available since 5.0.7, check for NULL when use if(_mysql_init == NULL || _mysql_close == NULL || _mysql_errno == NULL || _mysql_error == NULL || _mysql_fetch_fields == NULL || _mysql_fetch_row == NULL || _mysql_fetch_lengths == NULL || _mysql_free_result == NULL || _mysql_num_fields == NULL || _mysql_options == NULL || _mysql_real_connect == NULL || _mysql_query == NULL || _mysql_set_local_infile_handler == NULL || _mysql_thread_init == NULL || _mysql_use_result == NULL) { strcpy(_native_error_text, MYSQL_C_FUNC_LOAD_ERROR); return -1; } } else // Error message already set return -1; // Initialize the MySQL library // mysql_library_init is not exported DLL function it is define for mysql_server_init // but by calling mysql_init we force mysql_library_init() call to initialize the library for the process // Must be called before threads are launched, otherwise the application crashes on some systems if(_mysql_init != NULL) { MYSQL *mysql = _mysql_init(&_mysql); if(mysql == NULL) return -1; // Initialize global options that take effect only for new connections InitGlobalOptions(); // Did not work for MariaDB //_mysql_options(&_mysql, MYSQL_OPT_LOCAL_INFILE, 0); } _static_init = true; TRACE("MySQL/C InitStatic() Left"); return 0; } // Initialize API for thread int SqlMysqlApi::Init() { if(_static_init == false) return -1; #if defined(WIN32) || defined(WIN64) // Create synchronization objects for LOAD DATA INFILE command _wait_event = CreateEvent(NULL, FALSE, FALSE, NULL); _completed_event = CreateEvent(NULL, FALSE, FALSE, NULL); #else Os::CreateEvent(&_wait_event); Os::CreateEvent(&_completed_event); #endif return 0; } // Set the connection string in the API object void SqlMysqlApi::SetConnectionString(const char *conn) { if(conn == NULL) return; std::string db; SplitConnectionString(conn, _user, _pwd, db); const char *start = db.c_str(); // Find : and , that denote the server port and the database name const char *semi = strchr(start, ':'); const char *comma = strchr(start, ','); const char *end = (semi != NULL) ? semi :comma; // Define server name if(end != NULL) _server.assign(start, (size_t)(end - start)); else _server = start; // Define port if(semi != NULL) { std::string port; if(comma != NULL && comma > semi) port.assign(semi + 1, (size_t)(comma - semi - 1)); else port = semi + 1; sscanf(port.c_str(), "%d", &_port); } if(comma != NULL) _db = Str::SkipSpaces(comma + 1); } // Connect to the database int SqlMysqlApi::Connect(size_t *time_spent) { // Check if already connected if(_connected == true) return 0; size_t start = (time_spent != NULL) ? Os::GetTickCount() : 0; // Connect is called in a new thread so we must call mysql_init again but now for the thread (calls mysql_thread_init) // If not mysqk_init not called in each thread working with MySQL, the application crashes MYSQL *mysql = _mysql_init(&_mysql); if(mysql == NULL) return -1; mysql = _mysql_real_connect(&_mysql, _server.c_str(), _user.c_str(), _pwd.c_str(), _db.c_str(), (unsigned int)_port, NULL, CLIENT_LOCAL_FILES); if(mysql == NULL) { SetError(); if(time_spent != NULL) *time_spent = Os::GetTickCount() - start; return -1; } // Set callbacks for LOAD DATA INFILE command _mysql_set_local_infile_handler(&_mysql, local_infile_initS, local_infile_readS, local_infile_endS, local_infile_errorS, this); // Set version of the connected database SetVersion(); // Call after version numbers are set InitSession(); _connected = true; if(time_spent != NULL) *time_spent = Os::GetTickCount() - start; return 0; } // Initialize global options that take effect only for new connections int SqlMysqlApi::InitGlobalOptions() { if(_parameters == NULL) return -1; int rc = 0; const char *max_allowed_packet = NULL; // MariaDB options if(_subtype == SQLDATA_SUBTYPE_MARIADB) max_allowed_packet = _parameters->Get("-mariadb_max_allowed_packet"); // Set options in dedicated connection before all other connections if(max_allowed_packet != NULL) { rc = Connect(NULL); if(rc != -1) { rc = ExecuteNonQuery(std::string("SET GLOBAL max_allowed_packet=").append(max_allowed_packet).c_str(), NULL); Disconnect(); } } return rc; } // Initialize session by setting options int SqlMysqlApi::InitSession() { if(_parameters == NULL) return -1; int rc = 0; const char *value = _parameters->Get("-mysql_set_character_set"); // mysql_set_character_set is available since 5.0.7 if(Str::IsSet(value) == true && _mysql_set_character_set != NULL) rc = _mysql_set_character_set(&_mysql, value); value = _parameters->Get("-mysql_set_foreign_key_checks"); if(Str::IsSet(value) == true) { std::string stmt = "SET FOREIGN_KEY_CHECKS="; stmt += value; rc = ExecuteNonQuery(stmt.c_str(), NULL); } // Set INNODB_STATS_ON_METADATA=0 to significantly speed up access to INFORMATION_SCHEMA views // (about 5-10 times faster from 5-10 sec to 0.5-1 sec). But this requires SUPER privilege // Available since 5.1.17 if(IsVersionEqualOrHigher(5, 1, 17) == true) rc = ExecuteNonQuery("SET GLOBAL INNODB_STATS_ON_METADATA=0", NULL); // Binary logging for replication. This requires SUPER privilege! if(_subtype == SQLDATA_SUBTYPE_MARIADB) { value = _parameters->Get("-mariadb_set_sql_log_bin"); if(Str::IsSet(value)) rc = ExecuteNonQuery(std::string("SET sql_log_bin=").append(value).c_str(), NULL); } else rc = ExecuteNonQuery("SET sql_log_bin=0", NULL); // If AUTOCOMMIT is set to 0 in the database or client side, LOAD DATA INFILE requires a COMMIT statement // to put data to the table, so we force AUTOCOMMIT to 1 for connection rc = ExecuteNonQuery("SET autocommit=1", NULL); // Reset initialization error text so it will not be later associated with the data transfer *_native_error_text = '\x0'; return rc; } // Disconnect from the database void SqlMysqlApi::Disconnect() { if(_connected == false) return; _mysql_close(&_mysql); _connected = false; } // Deallocate the driver void SqlMysqlApi::Deallocate() { Disconnect(); } // Get row count for the specified object int SqlMysqlApi::GetRowCount(const char *object, long *count, size_t *time_spent) { if(object == NULL) return -1; std::string query = "SELECT COUNT(*) FROM "; query += object; // Execute the query int rc = ExecuteScalar(query.c_str(), count, time_spent); return rc; } // Execute the statement and get scalar result int SqlMysqlApi::ExecuteScalar(const char *query, long *result, size_t *time_spent) { if(query == NULL || result == NULL) return -1; size_t start = Os::GetTickCount(); // Execute the query int rc = _mysql_query(&_mysql, query); // Error raised if(rc != 0) { SetError(); return -1; } MYSQL_RES *res = _mysql_use_result(&_mysql); if(result == NULL) return -1; bool exists = false; // Fetch the first row MYSQL_ROW row = _mysql_fetch_row(res); if(row != NULL && row[0] != NULL) { sscanf(row[0], "%ld", result); exists = true; } _mysql_free_result(res); if(time_spent != NULL) *time_spent = Os::GetTickCount() - start; return (exists == true) ? 0 : -1; } // Execute the statement int SqlMysqlApi::ExecuteNonQuery(const char *query, size_t *time_spent) { size_t start = Os::GetTickCount(); // Execute the query int rc = _mysql_query(&_mysql, query); // Error raised if(rc != 0) SetError(); if(time_spent != NULL) *time_spent = Os::GetTickCount() - start; // mysql_query returns 1 on failure return (rc == 0) ? 0 : -1; } // Open cursor and allocate buffers int SqlMysqlApi::OpenCursor(const char *query, long buffer_rows, long buffer_memory, long *col_count, long *allocated_array_rows, long *rows_fetched, SqlCol **cols, size_t *time_spent, bool /*catalog_query*/, std::list<SqlDataTypeMap> * /*dtmap*/) { if(query == NULL) return -1; size_t start = Os::GetTickCount(); // Execute the query int rc = _mysql_query(&_mysql, query); // Error raised if(rc != 0) { SetError(); return -1; } _cursor_result = _mysql_use_result(&_mysql); if(_cursor_result == NULL) return -1; // Define the number of columns _cursor_cols_count = _mysql_num_fields(_cursor_result); if(_cursor_cols_count > 0) _cursor_cols = new SqlCol[_cursor_cols_count]; size_t row_size = 0; MYSQL_FIELD *fields = _mysql_fetch_fields(_cursor_result); _cursor_lob_exists = false; // Get column information for(long i = 0; i < _cursor_cols_count; i++) { // Copy column name strcpy(_cursor_cols[i]._name, fields[i].name); // Native data type _cursor_cols[i]._native_dt = fields[i].type; // Column length in characters (max_length is 0), 11 returned for INT // len 0 returned for BINARY(0) (MYSQL_TYPE_STRING = 254) // len -1 returned for LONGTEXT (MYSQL_TYPE_BLOB = 252) _cursor_cols[i]._len = fields[i].length; _cursor_cols[i]._binary = (fields[i].flags & BINARY_FLAG) ? true : false; // DECIMAL or NUMERIC if(_cursor_cols[i]._native_dt == MYSQL_TYPE_NEWDECIMAL || _cursor_cols[i]._native_dt == MYSQL_TYPE_DECIMAL) { _cursor_cols[i]._scale = (int)fields[i].decimals; // If decimals is 0 length contain precision + 1, if <> 0, length contains precision + scale if(fields[i].decimals == 0) _cursor_cols[i]._precision = (int)_cursor_cols[i]._len - 1; else _cursor_cols[i]._precision = (int)(_cursor_cols[i]._len - _cursor_cols[i]._scale); } else // MYSQL_TYPE_BLOB returned for BLOB, TEXT, LONGTEXT (MySQL 5.5); BINARY_FLAG is set for BLOBs if(_cursor_cols[i]._native_dt == MYSQL_TYPE_BLOB) { _cursor_cols[i]._lob = true; _cursor_lob_exists = true; } // len is -1 for LONGTEXT, do not allocate space in the buffer // Note 4294967295 returned on 64-bit system, and it is not equal -1 if(_cursor_cols[i]._len != -1 && _cursor_cols[i]._len < 1000000000) row_size += _cursor_cols[i]._len; // NOT NULL attribute _cursor_cols[i]._nullable = (fields[i].flags & NOT_NULL_FLAG) ? false : true; } _cursor_allocated_rows = 1; // Define how many rows fetch at once if(buffer_rows > 0) _cursor_allocated_rows = buffer_rows; else if(buffer_memory > 0) { // Avoid 0 rows size when only CHAR(0), BINARY(0) or LONGTEXT columns in table if(row_size == 0) row_size++; long rows = buffer_memory/row_size; _cursor_allocated_rows = rows > 0 ? rows : 1; } if(_cursor_lob_exists == true) _cursor_allocated_rows = 1; // Allocate buffers to each column for(int i = 0; i < _cursor_cols_count; i++) { _cursor_cols[i]._native_fetch_dt = _cursor_cols[i]._native_dt; // Do not allocate space for LONGTEXT, LONGBLOB columns, but allocate for BLOB and TEXT (65,535 bytes) if(_cursor_cols[i]._len != -1 && _cursor_cols[i]._len < 1000000000) { _cursor_cols[i]._fetch_len = _cursor_cols[i]._len + 1; _cursor_cols[i]._data = new char[_cursor_cols[i]._fetch_len * _cursor_allocated_rows]; } _cursor_cols[i].ind = new long[_cursor_allocated_rows]; } long fetched = 0; // Fetch initial set of data rc = Fetch(&fetched, NULL); if(col_count != NULL) *col_count = _cursor_cols_count; if(allocated_array_rows != NULL) *allocated_array_rows = _cursor_allocated_rows; if(rows_fetched != NULL) *rows_fetched = fetched; if(cols != NULL) *cols = _cursor_cols; if(time_spent != NULL) *time_spent = Os::GetTickCount() - start; return 0; } // Fetch next portion of data to allocate buffers int SqlMysqlApi::Fetch(long *rows_fetched, size_t *time_spent) { MYSQL_ROW row = NULL; int fetched = 0; size_t start = Os::GetTickCount(); // Fill the buffer for(long i = 0; i < _cursor_allocated_rows; i++) { // Fetch the next row row = _mysql_fetch_row(_cursor_result); if(row == NULL) break; unsigned long *lengths = (unsigned long*)_mysql_fetch_lengths(_cursor_result); // Copy column values and set indicators for(long k = 0; k < _cursor_cols_count; k++) { // Check for NULL value if(row[k] == NULL) { _cursor_cols[k].ind[i] = (size_t)-1; continue; } else _cursor_cols[k].ind[i] = (size_t)lengths[k]; char *data = NULL; // Column data if(_cursor_cols[k]._data != NULL) data = _cursor_cols[k]._data + _cursor_cols[k]._fetch_len * i; bool copy = true; // Check for zero date 0000-00-00 if(row[k] != NULL && _cursor_cols[k]._native_dt == MYSQL_TYPE_DATE) { // Change to NULL if(strcmp(row[k], "0000-00-00") == 0) { _cursor_cols[k].ind[i] = (size_t)-1; copy = false; } } else // Check for zero datetime 0000-00-00 00:00:00 if(row[k] != NULL && _cursor_cols[k]._native_dt == MYSQL_TYPE_DATETIME) { // Change to NULL if(strcmp(row[k], "0000-00-00 00:00:00") == 0) { _cursor_cols[k].ind[i] = (size_t)-1; copy = false; } } // Copy data (LONGBLOB and LONGTEXT are not copied if they transferred as LOBs to the target) if(data != NULL && copy == true) memcpy(data, row[k], lengths[k]); } fetched++; } if(rows_fetched != NULL) *rows_fetched = fetched; if(time_spent != NULL) *time_spent = GetTickCount() - start; return 0; } // Close the cursor and deallocate buffers int SqlMysqlApi::CloseCursor() { if(_cursor_result != NULL) _mysql_free_result(_cursor_result); _cursor_result = NULL; if(_cursor_cols == NULL) return 0; // Delete allocated buffers for(int i = 0; i < _cursor_cols_count; i++) { delete [] _cursor_cols[i]._data; delete [] _cursor_cols[i].ind; } delete [] _cursor_cols; _cursor_cols = NULL; _cursor_cols_count = 0; _cursor_allocated_rows = 0; return 0; } // Initialize the bulk copy from one database into another int SqlMysqlApi::InitBulkTransfer(const char *table, long col_count, long /*allocated_array_rows*/, SqlCol * /*s_cols*/, SqlCol ** /*t_cols*/) { TRACE("MySQL/C InitBulkTransfer() Entered"); // Column metadata and data passed directly to TransferRows _ldi_cols = NULL; _ldi_cols_count = col_count; _load_command = "LOAD DATA LOCAL INFILE 'sqldata.in_memory' IGNORE INTO TABLE "; _load_command += table; TRACE(_load_command.c_str()); TRACE_DMP_INIT(table); // Counters must be reset to clear data for the previous table _ldi_rc = 0; _ldi_terminated = 0; _ldi_current_row = 0; _ldi_current_col = 0; _ldi_current_col_len = 0; _ldi_write_newline = false; _ldi_lob_data = NULL; _ldi_lob_size = 0; _ldi_bytes = 0; _ldi_bytes_all = 0; #if defined(WIN32) || defined(WIN64) ResetEvent(_wait_event); ResetEvent(_completed_event); // Run blocking LOAD DATA INFILE command in a separate thread _beginthreadex(NULL, 0, StartLoadDataInfileS, this, 0, NULL); // Wait until the thread started WaitForSingleObject(_completed_event, INFINITE); #else Os::ResetEvent(&_wait_event); Os::ResetEvent(&_completed_event); pthread_t thread; pthread_create(&thread, NULL, StartLoadDataInfileS, this); Os::WaitForEvent(&_completed_event); #endif TRACE("MySQL/C InitBulkTransfer() Left"); // Return code typically 0 as init function waits for LDI thread to start only, but in case cases init can catch LDI errors return _ldi_rc; } // Transfer rows between databases int SqlMysqlApi::TransferRows(SqlCol *s_cols, long rows_fetched, long *rows_written, size_t *bytes_written, size_t *time_spent) { if(rows_fetched == 0) return 0; TRACE("MySQL/C TransferRows() Entered"); size_t start = Os::GetTickCount(); _ldi_rows_count = rows_fetched; _ldi_cols = s_cols; _ldi_current_row = 0; _ldi_current_col = 0; _ldi_current_col_len = 0; _ldi_write_newline = false; _ldi_bytes = 0; // Notify that the new portion of data is available #if defined(WIN32) || defined(_WIN64) SetEvent(_wait_event); // Wait until it processed WaitForSingleObject(_completed_event, INFINITE); #else Os::SetEvent(&_wait_event); Os::WaitForEvent(&_completed_event); #endif if(time_spent) *time_spent = GetTickCount() - start; if(rows_written != NULL) *rows_written = rows_fetched; if(bytes_written != NULL) *bytes_written = (size_t)_ldi_bytes; if(time_spent) *time_spent = GetTickCount() - start; TRACE("MySQL/C TransferRows() Left"); // Return code should remain 0 until bloking LDI call terminates return _ldi_rc; } // Write LOB data int SqlMysqlApi::WriteLob(SqlCol * /*s_cols*/, int /*row*/, int * /*lob_bytes*/) { return -1; } // LOAD DATA INFILE callbacks int SqlMysqlApi::local_infile_read(char *buf, unsigned int buf_len) { TRACE_P("MySQL/C LOAD DATA INFILE Read callback() Entered, buffer size is %d bytes", buf_len); // Wait until a new portion of data is available (_ldi_cols is NULL when first callback is called before TransferRows called) if(_ldi_cols == NULL || (_ldi_current_row == 0 && _ldi_current_col == 0 && _ldi_current_col_len == 0)) { TRACE("MySQL/C LOAD DATA INFILE Read callback() Waiting for data"); #if defined(WIN32) || defined(_WIN64) WaitForSingleObject(_wait_event, INFINITE); #else Os::WaitForEvent(&_wait_event); #endif TRACE("MySQL/C LOAD DATA INFILE Read callback() Data arrived"); } // EOF condition if(_ldi_current_row == -1) { TRACE("MySQL/C LOAD DATA INFILE Read callback() Left with EOF condition"); // Completion event will be set in the thread executing LOAD DATA INFILE return 0; } char *cur = buf; unsigned int remain_len = buf_len; // Check whether newline was not written for the previous row if(_ldi_write_newline == true) { *cur = '\n'; cur++; remain_len--; _ldi_bytes++; _ldi_bytes_all++; _ldi_write_newline = false; } // Copy rows for(long i = _ldi_current_row; i < _ldi_rows_count; i++, _ldi_current_row++) { // Copy column data for(long k = _ldi_current_col; k < _ldi_cols_count; k++, _ldi_current_col++) { // Add column delimiter if we are not in the middle of column if(k > 0 && _ldi_current_col_len == 0) { if(remain_len >= 1) { *cur = '\t'; cur++; remain_len--; _ldi_bytes++; _ldi_bytes_all++; } else { TRACE_P("MySQL/C LOAD DATA INFILE Read callback() Left - middle of batch, %d bytes chunk, %d bytes all", (int)(cur - buf), _ldi_bytes_all); TRACE_DMP(buf, (unsigned int)(cur - buf)); return (int)(cur - buf); } } long len = -1; // Check whether column is null if(_source_api_type == SQLDATA_ORACLE && _ldi_cols[k]._ind2 != NULL) { if(_ldi_cols[k]._ind2[i] != -1) { // LOB column if(_ldi_cols[k]._native_fetch_dt == SQLT_BLOB || _ldi_cols[k]._native_fetch_dt == SQLT_CLOB) { // Get the size and read LOB value when just switched to new column if(_ldi_current_col_len == 0) { // Get the LOB size in bytes for BLOB, in characters for CLOB int lob_rc = _source_api_provider->GetLobLength(i, k, &_ldi_lob_size); // Probably empty LOB if(lob_rc != -1) len = (int)_ldi_lob_size; if(lob_rc != -1 && _ldi_lob_size > 0) { long alloc_size = 0; long read_size = 0; _ldi_lob_data = _source_api_provider->GetLobBuffer(i, k, _ldi_lob_size, &alloc_size); // Get LOB content lob_rc = _source_api_provider->GetLobContent(i, k, _ldi_lob_data, alloc_size, &read_size); if(lob_rc == 0) { // Now set the size in bytes for both CLOB and BLOB _ldi_lob_size = read_size; len = read_size; } // Error reading LOB else { _source_api_provider->FreeLobBuffer(_ldi_lob_data); _ldi_lob_data = NULL; _ldi_lob_size = 0; } } } else len = (int)_ldi_lob_size; } // Not a LOB column else len = _ldi_cols[k]._len_ind2[i]; } } else // Sybase ASE if(_source_api_type == SQLDATA_SYBASE && _ldi_cols[k]._ind2 != NULL) { if(_ldi_cols[k]._ind2[i] != -1) len = _ldi_cols[k]._len_ind4[i]; } else // ODBC indicator contains either NULL or length if((_source_api_type == SQLDATA_INFORMIX || _source_api_type == SQLDATA_DB2 || _source_api_type == SQLDATA_SQL_SERVER || _source_api_type == SQLDATA_ODBC) && _ldi_cols[k].ind != NULL) { len = (int)_ldi_cols[k].ind[i]; #if defined(_WIN64) // DB2 11 64-bit CLI driver still writes indicators to 4-byte array if(_source_api_type == SQLDATA_DB2 && _ldi_cols[k].ind[0] & 0xFFFFFFFF00000000) len = ((int*)(_ldi_cols[k].ind))[i]; #endif } bool no_space = false; // Write NULL value if(len == -1) { if(remain_len >= 2) { cur[0] = '\\'; cur[1] = 'N'; cur += 2; remain_len -= 2; _ldi_bytes += 2; _ldi_bytes_all += 2; } else no_space = true; } else // Oracle CHAR, VARCHAR2, CLOB and BLOB if((_source_api_type == SQLDATA_ORACLE && (_ldi_cols[k]._native_fetch_dt == SQLT_STR || _ldi_cols[k]._native_fetch_dt == SQLT_BLOB || _ldi_cols[k]._native_fetch_dt == SQLT_CLOB || _ldi_cols[k]._native_fetch_dt == SQLT_BIN || _ldi_cols[k]._native_fetch_dt == SQLT_LNG)) || // Sybase CHAR (_source_api_type == SQLDATA_SYBASE && _ldi_cols[k]._native_fetch_dt == CS_CHAR_TYPE) || // ODBC CHAR ((_source_api_type == SQLDATA_ODBC || _source_api_type == SQLDATA_INFORMIX || _source_api_type == SQLDATA_DB2 || _source_api_type == SQLDATA_SQL_SERVER) && _ldi_cols[k]._native_fetch_dt == SQL_C_CHAR)) { // Copy data for(long m = _ldi_current_col_len; m < len; m++) { char c = 0; // Not LOB data if(_ldi_lob_data == 0) c = (_ldi_cols[k]._data + _ldi_cols[k]._fetch_len * i)[m]; else c = _ldi_lob_data[m]; // Duplicate escape \ character if(c == '\\') { if(remain_len >= 2) { cur[0] = c; cur[1] = c; cur += 2; remain_len -= 2; _ldi_bytes += 2; _ldi_bytes_all += 2; // Only one char of source data read _ldi_current_col_len++; } else { no_space = true; break; } } // Newline and tab must be escaped else if(c == '\n' || c == '\t') { if(remain_len >= 2) { cur[0] = '\\'; cur[1] = (c == '\n') ? 'n' : 't'; cur += 2; remain_len -= 2; _ldi_bytes += 2; _ldi_bytes_all += 2; // Only one char of source data read _ldi_current_col_len++; } else { no_space = true; break; } } else if(remain_len >= 1) { *cur = c; cur++; remain_len--; _ldi_bytes++; _ldi_bytes_all++; _ldi_current_col_len++; } else { no_space = true; break; } } // All column data were written if(no_space == false) { _ldi_current_col_len = 0; if(_ldi_lob_data != NULL) { _source_api_provider->FreeLobBuffer(_ldi_lob_data); _ldi_lob_data = NULL; _ldi_lob_size = 0; } } } else // Oracle DATE fetched as 7 byte binary sequence if(_source_api_type == SQLDATA_ORACLE && _ldi_cols[k]._native_fetch_dt == SQLT_DAT) { if(remain_len >= 19) { // Unsigned required for proper conversion to int unsigned char *data = (unsigned char*)(_ldi_cols[k]._data + _ldi_cols[k]._fetch_len * i); int c = ((int)data[0]) - 100; int y = ((int)data[1]) - 100; int m = (int)data[2]; int d = (int)data[3]; int h = ((int)data[4]) - 1; int mi = ((int)data[5]) - 1; int s = ((int)data[6]) - 1; // Get string representation Str::Dt2Ch(c, cur); Str::Dt2Ch(y, cur + 2); cur[4] = '-'; Str::Dt2Ch(m, cur + 5); cur[7] = '-'; Str::Dt2Ch(d, cur + 8); cur[10] = ' '; Str::Dt2Ch(h, cur + 11); cur[13] = ':'; Str::Dt2Ch(mi, cur + 14); cur[16] = ':'; Str::Dt2Ch(s, cur + 17); cur += 19; remain_len -= 19; _ldi_bytes += 19; _ldi_bytes_all += 19; } else no_space = true; } else // ODBC TIMESTAMP fetched as SQL_TIMESTAMP_STRUCT if((_source_api_type == SQLDATA_SQL_SERVER || _source_api_type == SQLDATA_DB2 || _source_api_type == SQLDATA_INFORMIX || _source_api_type == SQLDATA_ASA || _source_api_type == SQLDATA_ODBC) && _ldi_cols[k]._native_fetch_dt == SQL_C_TYPE_TIMESTAMP) { if(remain_len >= 26) { size_t offset = sizeof(SQL_TIMESTAMP_STRUCT) * i; // Informix returns '1200-01-01 11:11:00.0' for 11:11 (HOUR TO MINUTE) SQL_TIMESTAMP_STRUCT *ts = (SQL_TIMESTAMP_STRUCT*)(_ldi_cols[k]._data + offset); long fraction = (long)ts->fraction; // In ODBC, fraction is stored in nanoseconds, but now we support only microseconds fraction = fraction/1000; // Convert SQL_TIMESTAMP_STRUCT to string Str::SqlTs2Str((short)ts->year, (short)ts->month, (short)ts->day, (short)ts->hour, (short)ts->minute, (short)ts->second, fraction, cur); cur += 26; remain_len -= 26; _ldi_bytes += 26; _ldi_bytes_all += 26; } else no_space = true; } // There is no space to write the column value if(no_space) { // If it is non-first column and 0 bytes were written, remove column delimiter if(k > 0 && _ldi_current_col_len == 0) { cur--; remain_len++; _ldi_bytes--; _ldi_bytes_all--; } TRACE_P("MySQL/C LOAD DATA INFILE Read callback() Left - middle of batch, %d bytes chunk, %d bytes all", (int)(cur - buf), _ldi_bytes_all); TRACE_DMP(buf, (unsigned int)(cur - buf)); return (int)(cur - buf); } } _ldi_current_col = 0; // Add row delimiter (no need to write \r for Windows) if(remain_len >= 1) { *cur = '\n'; cur++; remain_len--; _ldi_bytes++; _ldi_bytes_all++; } else { _ldi_write_newline = true; _ldi_current_row++; _ldi_current_col = 0; _ldi_current_col_len = 0; TRACE_P("MySQL/C LOAD DATA INFILE Read callback() Left - middle of batch, %d bytes chunk, %d bytes all", (int)(cur - buf), _ldi_bytes_all); TRACE_DMP(buf, (unsigned int)(cur - buf)); return (int)(cur - buf); } } _ldi_current_row = 0; _ldi_current_col = 0; _ldi_current_col_len = 0; // Notify that the new portion of data processed #if defined(WIN32) || defined(_WIN64) SetEvent(_completed_event); #else Os::SetEvent(&_completed_event); #endif TRACE_P("MySQL/C LOAD DATA INFILE Read callback() Left - Batch fully loaded, %d bytes last chunk, %d bytes batch, %d bytes all", (int)(cur - buf), _ldi_bytes, _ldi_bytes_all); TRACE_DMP(buf, (unsigned int)(cur - buf)); return (int)(cur - buf); } void SqlMysqlApi::local_infile_end(void * /*ptr*/) { TRACE("MySQL/C LOAD DATA INFILE - End callback()"); return; } int SqlMysqlApi::local_infile_error(void * /*ptr*/, char * /*error_msg*/, unsigned int /*error_msg_len*/) { TRACE("MySQL/C LOAD DATA INFILE - Error callback()"); return 0; } int SqlMysqlApi::local_infile_initS(void **ptr, const char * /*filename*/, void *userdata) { TRACE_S(((SqlMysqlApi*)userdata), "MySQL/C LOAD DATA INFILE Init callback()"); // Pass pointer to the API object *ptr = userdata; return 0; } int SqlMysqlApi::local_infile_readS(void *ptr, char *buf, unsigned int buf_len) { if(ptr == NULL) return -1; SqlMysqlApi *mysqlApi = (SqlMysqlApi*)ptr; return mysqlApi->local_infile_read(buf, buf_len); } void SqlMysqlApi::local_infile_endS(void *ptr) { SqlMysqlApi *mysqlApi = (SqlMysqlApi*)ptr; if(mysqlApi != NULL) mysqlApi->local_infile_end(ptr); } int SqlMysqlApi::local_infile_errorS(void *ptr, char *error_msg, unsigned int error_msg_len) { SqlMysqlApi *mysqlApi = (SqlMysqlApi*)ptr; if(mysqlApi != NULL) mysqlApi->local_infile_error(ptr, error_msg, error_msg_len); return 0; } #if defined(WIN32) || defined(WIN64) unsigned int __stdcall SqlMysqlApi::StartLoadDataInfileS(void *object) { if(object == NULL) return (unsigned int)-1; #else void* SqlMysqlApi::StartLoadDataInfileS(void *object) { if(object == NULL) return NULL; #endif SqlMysqlApi *mysqlApi = (SqlMysqlApi*)object; TRACE_S(mysqlApi, "MySQL/C StartLoadDataInfileS() Entered"); // Notify InitBulkCopy that the thread started #if defined(WIN32) || defined(WIN64) SetEvent(mysqlApi->_completed_event); #else Os::SetEvent(&mysqlApi->_completed_event); #endif mysqlApi->_ldi_terminated = 0; // Execute LOAD DATA INFILE command mysqlApi->_ldi_rc = mysqlApi->ExecuteNonQuery(mysqlApi->_load_command.c_str(), NULL); mysqlApi->_ldi_terminated = 1; // Release thread called CloseBulkTransfer, so this connection can be used by other functions // If the table does not exist ExecuteNonQuery returns immediately, so notify TransferRows #if defined(WIN32) || defined(WIN64) SetEvent(mysqlApi->_completed_event); #else Os::SetEvent(&mysqlApi->_completed_event); #endif TRACE_S(mysqlApi, "MySQL/C StartLoadDataInfileS() Left"); #if defined(WIN32) || defined(WIN64) return (unsigned int)mysqlApi->_ldi_rc; #else return NULL; #endif } // Complete bulk transfer int SqlMysqlApi::CloseBulkTransfer() { TRACE("MySQL/C CloseBulkTransfer() Entered"); _ldi_current_row = -1; // Do not wait for complete event if LOAD DATA INFILE command already ended if(_ldi_terminated == 0) { // Notify that there are no more rows #if defined(WIN32) || defined(WIN64) SetEvent(_wait_event); // Wait until it processed WaitForSingleObject(_completed_event, INFINITE); #else Os::SetEvent(&_wait_event); Os::WaitForEvent(&_completed_event); #endif } // Check warnings and errors ShowWarnings(_load_command.c_str()); TRACE("MySQL/C CloseBulkTransfer() Left"); return 0; } // Execute SHOW WARNINGS and log results void SqlMysqlApi::ShowWarnings(const char *prefix) { long col_count = 0; long allocated_rows = 0; long rows_fetched = 0; SqlCol *cols = NULL; int rc = OpenCursor("SHOW WARNINGS", 100, 0, &col_count, &allocated_rows, &rows_fetched, &cols, NULL, true); if(rc >= 0 && rows_fetched > 0) { LOG_P("\n SHOW WARNINGS: %s", prefix); for(int i = 0; i < rows_fetched; i++) { std::string warn = "\n "; SQLLEN len = (SQLLEN)cols[0].ind[i]; // Level if(len != -1) { warn += cols[0]._name; warn += ": "; warn.append(cols[0]._data + cols[0]._fetch_len * i, (size_t)len); warn += "; "; } len = (SQLLEN)cols[1].ind[i]; // Code if(len != -1) { warn += cols[1]._name; warn += ": "; warn.append(cols[1]._data + cols[1]._fetch_len * i, (size_t)len); warn += "; "; } len = (SQLLEN)cols[2].ind[i]; // Code if(len != -1) { warn += cols[2]._name; warn += ": "; warn.append(cols[2]._data + cols[2]._fetch_len * i, (size_t)len); } LOG(warn.c_str()); } } CloseCursor(); } // Drop the table int SqlMysqlApi::DropTable(const char* table, size_t *time_spent, std::string &drop_stmt) { size_t start = Os::GetTickCount(); // Table may be referenced by other tables, so remove foreign keys int rc = DropReferences(table, NULL); drop_stmt = "DROP TABLE IF EXISTS "; drop_stmt += table; rc = ExecuteNonQuery(drop_stmt.c_str(), NULL); if(time_spent) *time_spent = Os::GetTickCount() - start; return rc; } // Remove foreign key constraints referencing to the parent table int SqlMysqlApi::DropReferences(const char* table, size_t *time_spent) { if(table == NULL) return -1; size_t start = Os::GetTickCount(); std::string db; std::string object; // Table can contain the database name SplitQualifiedName(table, db, object); std::list<std::string> drop_fk; // Query to find foreign keys on the table (this query takes 5-8 sec on first call even if there are 3 rows in the whole table) // INNODB_STATS_ON_METADATA=0 is set to significantly speed up access to INFORMATION_SCHEMA views // (about 5-10 times faster from 5-10 sec to 0.5-1 sec). But this requires SUPER privilege and may be OFF std::string query = "SELECT constraint_name, table_name FROM information_schema.referential_constraints "; query += "WHERE referenced_table_name = '"; query += object; query += "'"; // Execute the query int rc = _mysql_query(&_mysql, query.c_str()); // Error raised if(rc != 0) { SetError(); return -1; } MYSQL_RES *res = _mysql_use_result(&_mysql); if(res == NULL) return -1; MYSQL_ROW row = NULL; bool more = true; while(more) { // Fetch the next row row = _mysql_fetch_row(res); if(row == NULL) { more = false; break; } std::string drop = "ALTER TABLE "; drop += row[1]; drop += " DROP FOREIGN KEY "; drop += row[0]; // Add drop foreign key statement drop_fk.push_back(drop); } _mysql_free_result(res); // Drop foreign key constraints for(std::list<std::string>::iterator i = drop_fk.begin(); i != drop_fk.end(); i++) { // If at least one FK drop fails the table cannot be dropped rc = ExecuteNonQuery((*i).c_str(), NULL); if(rc == -1) break; } if(time_spent != NULL) *time_spent = Os::GetTickCount() - start; // mysql_query returns 1 on failure return (rc == 0) ? 0 : -1; } // Get the length of LOB column in the open cursor int SqlMysqlApi::GetLobLength(long /*row*/, long /*column*/, long * /*length*/) { return -1; } // Get LOB content int SqlMysqlApi::GetLobContent(long /*row*/, long /*column*/, void * /*data*/, long /*length*/, long * /*len_ind*/) { return -1; } // Get the list of available tables int SqlMysqlApi::GetAvailableTables(std::string &table_template, std::string & /*exclude*/, std::list<std::string> &tables) { std::string condition; // Get a condition to select objects from the catalog // MySQL contains the database name in "table_schema" column GetSelectionCriteria(table_template.c_str(), "table_schema", "table_name", condition, _db.c_str(), false); // Build the query std::string query = "SELECT table_schema, table_name FROM information_schema.tables"; query += " WHERE table_type='BASE TABLE'"; query += " AND table_schema NOT IN ('information_schema', 'mysql', 'performance_schema')"; // Add filter if(condition.empty() == false) { query += " AND "; query += condition; } // Execute the query int rc = _mysql_query(&_mysql, query.c_str()); // Error raised if(rc != 0) { SetError(); return -1; } MYSQL_RES *res = _mysql_use_result(&_mysql); if(res == NULL) return -1; bool more = true; while(more) { // Fetch the row MYSQL_ROW row = _mysql_fetch_row(res); // We must fetch all rows to avoid "out of sync" errors if(row == NULL) { more = false; break; } std::string tab; // Schema name if(row[0] != NULL) { tab += row[0]; tab += "."; } // Table name if(row[1] != NULL) tab += row[1]; tables.push_back(tab); } _mysql_free_result(res); return 0; } // Read schema information int SqlMysqlApi::ReadSchema(const char * /*select*/, const char * /*exclude*/, bool /*read_cns*/, bool /*read_idx*/) { return -1; } // Get table name by constraint name int SqlMysqlApi::ReadConstraintTable(const char * /*schema*/, const char * /*constraint*/, std::string & /*table*/) { return -1; } // Read information about constraint columns int SqlMysqlApi::ReadConstraintColumns(const char * /*schema*/, const char * /*table*/, const char * /*constraint*/, std::string & /*cols*/) { return -1; } // Set version of the connected database void SqlMysqlApi::SetVersion() { // Note: INFORMATION_SCHEMA.GLOBAL_VARIABLES is available since 5.1 only // Returns 4 rows and 2 columns: Variable_name and Value // 5.5.15 MySQL Community Server (GPL) x86 Win32 const char *query = "SHOW VARIABLES LIKE 'VERSION%'"; // Execute the query int rc = _mysql_query(&_mysql, query); // Error raised if(rc != 0) { SetError(); return; } MYSQL_RES *res = _mysql_use_result(&_mysql); if(res == NULL) return; _version.clear(); int i = 0; bool more = true; while(more) { // Fetch the row MYSQL_ROW row = _mysql_fetch_row(res); if(row == NULL || row[1] == NULL) { more = false; break; } if(i > 0) _version += " "; // row[1] contains 2nd column as a null-terminated string _version += row[1]; // Set version numbers if(row[0] != NULL && strcmp(row[0], "version") == 0) { sscanf(row[1], "%d.%d.%d", &_version_major, &_version_minor, &_version_release); } i++; } _mysql_free_result(res); } // Find MySQL installation paths void SqlMysqlApi::FindMysqlPaths() { #if defined(WIN32) || defined(_WIN64) HKEY hKey, hSubkey; // Main key is "Software\\MySQL AB" for MySQL 5.5 and 5.6 // MySQL Installer for MySQL 5.7 puts keys even for 64-bit version to "Software\\WOW6432Node\\MySQL AB" char *keys[] = { "Software\\MySQL AB", "Software\\WOW6432Node\\MySQL AB" }; char key[1024]; char location[1024]; for(int k = 0; k < 2; k++) { int rc = RegOpenKeyEx(HKEY_LOCAL_MACHINE, keys[k], 0, KEY_READ | KEY_ENUMERATE_SUB_KEYS, &hKey); if(rc != ERROR_SUCCESS) return; DWORD i = 0; bool more = true; // Enumerate through all keys while(more) { // Size modified with each call to RegEnumKeyEx int size = 1024; // Get next key rc = RegEnumKeyEx(hKey, i, key, (LPDWORD)&size, NULL, NULL, NULL, NULL); if(rc != ERROR_SUCCESS) { more = false; break; } i++; // Key is "MySQL Server 5.5" for version 5.5, 5.6 and 5.7 if(strncmp(key, "MySQL Server", 12) != 0) continue; rc = RegOpenKeyEx(hKey, key, 0, KEY_READ, &hSubkey); if(rc != ERROR_SUCCESS) break; int value_size = 1024; rc = RegQueryValueEx(hSubkey, "Location", NULL, NULL, (LPBYTE)location, (LPDWORD)&value_size); if(rc == ERROR_SUCCESS) { // For MySQL 5.5, 5.6 and 5.7 location includes terminating '\' std::string loc = location; loc += "lib\\"; _driver_paths.push_back(loc); } RegCloseKey(hSubkey); } RegCloseKey(hKey); } #endif } // Set error code and message for the last API call void SqlMysqlApi::SetError() { // Get native error code _native_error = (int)_mysql_errno(&_mysql); // Get native error text strcpy(_native_error_text, _mysql_error(&_mysql)); _error = SQL_DBAPI_UNKNOWN_ERROR; *_error_text = '\x0'; }
25.109428
144
0.674086
strk
e7b17965c6952e8f46fb8925e54fe64ff7be608e
202
cpp
C++
Problems_Beginner1/Problem_1002.cpp
gustavocabralsouza/Programacao_Competitiva
9b568cf968e6543ddeb12d626303cd53845a9ded
[ "MIT" ]
null
null
null
Problems_Beginner1/Problem_1002.cpp
gustavocabralsouza/Programacao_Competitiva
9b568cf968e6543ddeb12d626303cd53845a9ded
[ "MIT" ]
null
null
null
Problems_Beginner1/Problem_1002.cpp
gustavocabralsouza/Programacao_Competitiva
9b568cf968e6543ddeb12d626303cd53845a9ded
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main(){ double raio, pi, area; pi = 3.14159; scanf("%lf",&raio); area = pi * raio * raio; printf("A=%.4lf\n", area); return 0; }
12.625
28
0.549505
gustavocabralsouza
e7b2954bdd06225b432c5a29b00ab21a48dbba81
8,739
cc
C++
cpp/src/gandiva/projector.cc
jblondin/arrow
319effd98e6d1d4282751471ebefaf325b0df09f
[ "Apache-2.0" ]
1
2021-07-07T07:13:51.000Z
2021-07-07T07:13:51.000Z
cpp/src/gandiva/projector.cc
jblondin/arrow
319effd98e6d1d4282751471ebefaf325b0df09f
[ "Apache-2.0" ]
3
2018-06-27T14:56:40.000Z
2018-07-16T03:04:20.000Z
cpp/src/gandiva/projector.cc
jblondin/arrow
319effd98e6d1d4282751471ebefaf325b0df09f
[ "Apache-2.0" ]
3
2021-03-23T19:45:48.000Z
2021-03-23T21:36:16.000Z
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "gandiva/projector.h" #include <memory> #include <utility> #include <vector> #include "gandiva/cache.h" #include "gandiva/expr_validator.h" #include "gandiva/llvm_generator.h" #include "gandiva/projector_cache_key.h" namespace gandiva { Projector::Projector(std::unique_ptr<LLVMGenerator> llvm_generator, SchemaPtr schema, const FieldVector& output_fields, std::shared_ptr<Configuration> configuration) : llvm_generator_(std::move(llvm_generator)), schema_(schema), output_fields_(output_fields), configuration_(configuration) {} Projector::~Projector() {} Status Projector::Make(SchemaPtr schema, const ExpressionVector& exprs, std::shared_ptr<Projector>* projector) { return Projector::Make(schema, exprs, ConfigurationBuilder::DefaultConfiguration(), projector); } Status Projector::Make(SchemaPtr schema, const ExpressionVector& exprs, std::shared_ptr<Configuration> configuration, std::shared_ptr<Projector>* projector) { ARROW_RETURN_IF(schema == nullptr, Status::Invalid("Schema cannot be null")); ARROW_RETURN_IF(exprs.empty(), Status::Invalid("Expressions cannot be empty")); ARROW_RETURN_IF(configuration == nullptr, Status::Invalid("Configuration cannot be null")); // see if equivalent projector was already built static Cache<ProjectorCacheKey, std::shared_ptr<Projector>> cache; ProjectorCacheKey cache_key(schema, configuration, exprs); std::shared_ptr<Projector> cached_projector = cache.GetModule(cache_key); if (cached_projector != nullptr) { *projector = cached_projector; return Status::OK(); } // Build LLVM generator, and generate code for the specified expressions std::unique_ptr<LLVMGenerator> llvm_gen; ARROW_RETURN_NOT_OK(LLVMGenerator::Make(configuration, &llvm_gen)); // Run the validation on the expressions. // Return if any of the expression is invalid since // we will not be able to process further. ExprValidator expr_validator(llvm_gen->types(), schema); for (auto& expr : exprs) { ARROW_RETURN_NOT_OK(expr_validator.Validate(expr)); } ARROW_RETURN_NOT_OK(llvm_gen->Build(exprs)); // save the output field types. Used for validation at Evaluate() time. std::vector<FieldPtr> output_fields; output_fields.reserve(exprs.size()); for (auto& expr : exprs) { output_fields.push_back(expr->result()); } // Instantiate the projector with the completely built llvm generator *projector = std::shared_ptr<Projector>( new Projector(std::move(llvm_gen), schema, output_fields, configuration)); cache.PutModule(cache_key, *projector); return Status::OK(); } Status Projector::Evaluate(const arrow::RecordBatch& batch, const ArrayDataVector& output_data_vecs) { return Evaluate(batch, nullptr, output_data_vecs); } Status Projector::Evaluate(const arrow::RecordBatch& batch, const SelectionVector* selection_vector, const ArrayDataVector& output_data_vecs) { ARROW_RETURN_NOT_OK(ValidateEvaluateArgsCommon(batch)); if (output_data_vecs.size() != output_fields_.size()) { std::stringstream ss; ss << "number of buffers for output_data_vecs is " << output_data_vecs.size() << ", expected " << output_fields_.size(); return Status::Invalid(ss.str()); } int idx = 0; for (auto& array_data : output_data_vecs) { if (array_data == nullptr) { std::stringstream ss; ss << "array for output field " << output_fields_[idx]->name() << "is null."; return Status::Invalid(ss.str()); } auto num_rows = selection_vector == nullptr ? batch.num_rows() : selection_vector->GetNumSlots(); ARROW_RETURN_NOT_OK( ValidateArrayDataCapacity(*array_data, *(output_fields_[idx]), num_rows)); ++idx; } return llvm_generator_->Execute(batch, selection_vector, output_data_vecs); } Status Projector::Evaluate(const arrow::RecordBatch& batch, arrow::MemoryPool* pool, arrow::ArrayVector* output) { return Evaluate(batch, nullptr, pool, output); } Status Projector::Evaluate(const arrow::RecordBatch& batch, const SelectionVector* selection_vector, arrow::MemoryPool* pool, arrow::ArrayVector* output) { ARROW_RETURN_NOT_OK(ValidateEvaluateArgsCommon(batch)); ARROW_RETURN_IF(output == nullptr, Status::Invalid("Output must be non-null.")); ARROW_RETURN_IF(pool == nullptr, Status::Invalid("Memory pool must be non-null.")); auto num_rows = selection_vector == nullptr ? batch.num_rows() : selection_vector->GetNumSlots(); // Allocate the output data vecs. ArrayDataVector output_data_vecs; for (auto& field : output_fields_) { ArrayDataPtr output_data; ARROW_RETURN_NOT_OK(AllocArrayData(field->type(), num_rows, pool, &output_data)); output_data_vecs.push_back(output_data); } // Execute the expression(s). ARROW_RETURN_NOT_OK( llvm_generator_->Execute(batch, selection_vector, output_data_vecs)); // Create and return array arrays. output->clear(); for (auto& array_data : output_data_vecs) { output->push_back(arrow::MakeArray(array_data)); } return Status::OK(); } // TODO : handle variable-len vectors Status Projector::AllocArrayData(const DataTypePtr& type, int64_t num_records, arrow::MemoryPool* pool, ArrayDataPtr* array_data) { const auto* fw_type = dynamic_cast<const arrow::FixedWidthType*>(type.get()); ARROW_RETURN_IF(fw_type == nullptr, Status::Invalid("Unsupported output data type ", type)); std::shared_ptr<arrow::Buffer> null_bitmap; int64_t bitmap_bytes = arrow::BitUtil::BytesForBits(num_records); ARROW_RETURN_NOT_OK(arrow::AllocateBuffer(pool, bitmap_bytes, &null_bitmap)); std::shared_ptr<arrow::Buffer> data; int64_t data_len = arrow::BitUtil::BytesForBits(num_records * fw_type->bit_width()); ARROW_RETURN_NOT_OK(arrow::AllocateBuffer(pool, data_len, &data)); // This is not strictly required but valgrind gets confused and detects this // as uninitialized memory access. See arrow::util::SetBitTo(). if (type->id() == arrow::Type::BOOL) { memset(data->mutable_data(), 0, data_len); } *array_data = arrow::ArrayData::Make(type, num_records, {null_bitmap, data}); return Status::OK(); } Status Projector::ValidateEvaluateArgsCommon(const arrow::RecordBatch& batch) { ARROW_RETURN_IF(!batch.schema()->Equals(*schema_), Status::Invalid("Schema in RecordBatch must match schema in Make()")); ARROW_RETURN_IF(batch.num_rows() == 0, Status::Invalid("RecordBatch must be non-empty.")); return Status::OK(); } Status Projector::ValidateArrayDataCapacity(const arrow::ArrayData& array_data, const arrow::Field& field, int64_t num_records) { ARROW_RETURN_IF(array_data.buffers.size() < 2, Status::Invalid("ArrayData must have at least 2 buffers")); int64_t min_bitmap_len = arrow::BitUtil::BytesForBits(num_records); int64_t bitmap_len = array_data.buffers[0]->capacity(); ARROW_RETURN_IF(bitmap_len < min_bitmap_len, Status::Invalid("Bitmap buffer too small for ", field.name())); // verify size of data buffer. // TODO : handle variable-len vectors const auto& fw_type = dynamic_cast<const arrow::FixedWidthType&>(*field.type()); int64_t min_data_len = arrow::BitUtil::BytesForBits(num_records * fw_type.bit_width()); int64_t data_len = array_data.buffers[1]->capacity(); ARROW_RETURN_IF(data_len < min_data_len, Status::Invalid("Data buffer too small for ", field.name())); return Status::OK(); } } // namespace gandiva
39.722727
89
0.695617
jblondin
e7b2b7a86807ffa7b4c969eca45f7ee1f3217271
15,520
hpp
C++
osmi/ConnectionLinePreprocessor.hpp
johsin18/osmi-addresses
374f9a1d435ee7fe0ea6abb235fe4a8237e149d1
[ "BSL-1.0" ]
null
null
null
osmi/ConnectionLinePreprocessor.hpp
johsin18/osmi-addresses
374f9a1d435ee7fe0ea6abb235fe4a8237e149d1
[ "BSL-1.0" ]
null
null
null
osmi/ConnectionLinePreprocessor.hpp
johsin18/osmi-addresses
374f9a1d435ee7fe0ea6abb235fe4a8237e149d1
[ "BSL-1.0" ]
null
null
null
#ifndef CONNECTIONLINEPREPROCESSOR_HPP_ #define CONNECTIONLINEPREPROCESSOR_HPP_ #include <math.h> constexpr osmium::object_id_type DUMMY_ID = 0; // maximum length of a connection line (given in degrees) // the given value is not a strict limit: some connection lines may be longer (up to a factor of maybe 1.5) // approximate length in meters = MAXDIST*40'000'000/360 constexpr double MAXDIST = 0.01; constexpr bool IS_ADDRSTREET = true; constexpr bool IS_ADDRPLACE = false; #include "NearestPointsWriter.hpp" #include "NearestRoadsWriter.hpp" #include "NearestAreasWriter.hpp" #include "ConnectionLineWriter.hpp" #include "GeometryHelper.hpp" class ConnectionLinePreprocessor { public: ConnectionLinePreprocessor( const std::string& dir_name, name2highways_type& name2highways_area, name2highways_type& name2highways_nonarea, name2place_type& name2place_nody, name2place_type& name2place_wayy) : mp_name2highways_area(name2highways_area), mp_name2highways_nonarea(name2highways_nonarea), m_name2place_nody(name2place_nody), m_name2place_wayy(name2place_wayy), addrstreet(nullptr) { mp_nearest_points_writer = new NearestPointsWriter (dir_name); mp_nearest_roads_writer = new NearestRoadsWriter (dir_name); mp_nearest_areas_writer = new NearestAreasWriter (dir_name); mp_connection_line_writer = new ConnectionLineWriter(dir_name); } ~ConnectionLinePreprocessor() { // those need to be explicitly to be deleted to perform the commit operations in their deconstructor delete mp_nearest_points_writer; delete mp_nearest_roads_writer; delete mp_nearest_areas_writer; delete mp_connection_line_writer; } void process_interpolated_node( OGRPoint& ogr_point, std::string& road_id, // out std::string& nody_place_id, // out std::string& wayy_place_id, // out const std::string& street) { addrstreet = street.c_str(); if (addrstreet && has_entry_in_name2highways(street)) { handle_connection_line(ogr_point, DUMMY_ID, object_type::interpolated_node_object, addrstreet, road_id, nody_place_id, wayy_place_id, IS_ADDRSTREET); } } void process_node( const osmium::Node& node, std::string& road_id, // out std::string& nody_place_id, // out std::string& wayy_place_id) // out { addrstreet = node.tags().get_value_by_key("addr:street"); if (addrstreet && has_entry_in_name2highways(node)) { std::unique_ptr<OGRPoint> ogr_point = m_factory.create_point(node); handle_connection_line(*ogr_point.get(), node.id(), object_type::node_object, addrstreet, road_id, nody_place_id, wayy_place_id, IS_ADDRSTREET); } else { // road_id shall not be written by handle_connection_line } addrplace = node.tags().get_value_by_key("addr:place"); if (addrplace && has_entry_in_name2place(node)) { std::unique_ptr<OGRPoint> ogr_point = m_factory.create_point(node); handle_connection_line(*ogr_point.get(), node.id(), object_type::node_object, addrplace, road_id, nody_place_id, wayy_place_id, IS_ADDRPLACE); } else { // nody_place_id, wayy_place_id shall not be written by handle_connection_line } } void process_way( const osmium::Way& way, std::string& road_id, // out std::string& nody_place_id, // out std::string& wayy_place_id) // out { if (way.is_closed()) { addrstreet = way.tags().get_value_by_key("addr:street"); if (addrstreet && has_entry_in_name2highways(way)) { std::unique_ptr<OGRPoint> ogr_point = m_geometry_helper.centroid(way); handle_connection_line(*ogr_point.get(), way.id(), object_type::way_object, addrstreet, road_id, nody_place_id, wayy_place_id, IS_ADDRSTREET); } else { // road_id shall not be written by handle_connection_line } addrplace = way.tags().get_value_by_key("addr:place"); if (addrplace && has_entry_in_name2place(way)) { std::unique_ptr<OGRPoint> ogr_point = m_geometry_helper.centroid(way); handle_connection_line(*ogr_point.get(), way.id(), object_type::way_object, addrplace, road_id, nody_place_id, wayy_place_id, IS_ADDRPLACE); } else { // nody_place_id, wayy_place_id shall not be written by handle_connection_line } } } private: void handle_connection_line( OGRPoint& ogr_point, // TODO: can we make this const ? const osmium::object_id_type& objectid, const object_type& the_object_type, const char* addrstreet, std::string& road_id, // out std::string& nody_place_id, // out std::string& wayy_place_id, // out const bool& is_addrstreet) { std::unique_ptr<OGRPoint> closest_node(new OGRPoint); std::unique_ptr<OGRPoint> closest_point(new OGRPoint); // TODO: check if new is necessary std::unique_ptr<OGRLineString> closest_way(new OGRLineString); // TODO: check if new is necessary osmium::unsigned_object_id_type closest_obj_id = 0; // gets written later; wouldn't need an initialization, but gcc warns otherwise osmium::unsigned_object_id_type closest_way_id = 0; // gets written later; wouldn't need an initialization, but gcc warns otherwise int ind_closest_node; std::string lastchange; bool is_area; bool is_nody; // handle addr:place here if (is_addrstreet == IS_ADDRPLACE && get_closest_place(ogr_point, closest_point, is_nody, closest_obj_id, lastchange)) { if (is_nody) { nody_place_id = "1"; } else { wayy_place_id = "1"; } mp_connection_line_writer->write_line(ogr_point, closest_point, closest_obj_id, the_object_type); } // handle addr:street here if (is_addrstreet == IS_ADDRSTREET && get_closest_way(ogr_point, closest_way, is_area, closest_way_id, lastchange)) { m_geometry_helper.wgs2mercator({&ogr_point, closest_way.get(), closest_point.get()}); get_closest_node(ogr_point, closest_way, closest_node, ind_closest_node); get_closest_point_from_node_neighbourhood(ogr_point, closest_way, ind_closest_node, closest_point); m_geometry_helper.mercator2wgs({&ogr_point, closest_way.get(), closest_point.get()}); // TODO: could this be parallelized? mp_nearest_points_writer->write_point(closest_point, closest_way_id); if (is_area) { mp_nearest_areas_writer->write_area(closest_way, closest_way_id, addrstreet, lastchange); } else { mp_nearest_roads_writer->write_road(closest_way, closest_way_id, addrstreet, lastchange); } mp_connection_line_writer->write_line(ogr_point, closest_point, objectid, the_object_type); road_id = "1"; // TODO: need to write the actual road_id } } // return value: was a closest place found/written bool get_closest_place( const OGRPoint& ogr_point, std::unique_ptr<OGRPoint>& closest_point, // out bool& is_nody, // out osmium::unsigned_object_id_type& closest_obj_id, std::string& lastchange) { double best_dist = MAXDIST; double cur_dist = std::numeric_limits<double>::max(); bool is_assigned = false; std::pair<name2place_type::iterator, name2place_type::iterator> name2place_it_pair_nody; std::pair<name2place_type::iterator, name2place_type::iterator> name2place_it_pair_wayy; name2place_it_pair_nody = m_name2place_nody.equal_range(std::string(addrplace)); name2place_it_pair_wayy = m_name2place_wayy.equal_range(std::string(addrplace)); for (name2place_type::iterator it = name2place_it_pair_nody.first; it!=name2place_it_pair_nody.second; ++it) { cur_dist = it->second.ogrpoint->Distance(&ogr_point); if (cur_dist < best_dist) { closest_point.reset(static_cast<OGRPoint*>(it->second.ogrpoint.get()->clone())); is_nody = true; is_assigned = true; // TODO: extract more info from struct } } for (name2place_type::iterator it = name2place_it_pair_wayy.first; it!=name2place_it_pair_wayy.second; ++it) { cur_dist = it->second.ogrpoint->Distance(&ogr_point); if (cur_dist < best_dist) { // TODO: add check for minimum distance to prevent long connection lines closest_point.reset(static_cast<OGRPoint*>(it->second.ogrpoint.get()->clone())); is_nody = false; is_assigned = true; // TODO: extract more info from struct } } return is_assigned; } /* look up the closest way with the given name in the name2highway structs for ways and areas */ /* return: was a way found/assigned to closest_way */ bool get_closest_way( const OGRPoint& ogr_point, // in std::unique_ptr<OGRLineString>& closest_way, // out bool& is_area, // out osmium::unsigned_object_id_type& closest_way_id, // out std::string& lastchange) // out { double best_dist = std::numeric_limits<double>::max(); bool is_assigned = false; std::pair<name2highways_type::iterator, name2highways_type::iterator> name2highw_it_pair; name2highw_it_pair = mp_name2highways_area.equal_range(std::string(addrstreet)); if (get_closest_way_from_argument(ogr_point, best_dist, closest_way, closest_way_id, lastchange, name2highw_it_pair)) { is_area = true; is_assigned = true; } name2highw_it_pair = mp_name2highways_nonarea.equal_range(std::string(addrstreet)); if (get_closest_way_from_argument(ogr_point, best_dist, closest_way, closest_way_id, lastchange, name2highw_it_pair)) { is_area = false; is_assigned = true; } return is_assigned; } /* look up the closest way in the given name2highway struct that is closer than best_dist using bbox * return true if found */ bool get_closest_way_from_argument( const OGRPoint& ogr_point, // in double& best_dist, // in,out std::unique_ptr<OGRLineString>& closest_way, // out osmium::unsigned_object_id_type& closest_way_id, // out std::string& lastchange, // out const std::pair<name2highways_type::iterator, name2highways_type::iterator> name2highw_it_pair) { // in double cur_dist; bool assigned = false; for (name2highways_type::iterator it = name2highw_it_pair.first; it!=name2highw_it_pair.second; ++it) { if (m_geometry_helper.is_point_near_bbox( it->second.bbox_n, it->second.bbox_e, it->second.bbox_s, it->second.bbox_w, ogr_point, MAXDIST)) { std::unique_ptr<OGRLineString> linestring = it->second.compr_way.get()->uncompress(); cur_dist = linestring->Distance(&ogr_point); // note: distance calculation involves nodes, but not the points between the nodes on the line segments if (cur_dist < best_dist) { closest_way.reset(linestring.release()); closest_way_id = it->second.way_id; lastchange = it->second.lastchange; best_dist = cur_dist; assigned = true; } } } return assigned; } /* get the node of closest_way that is most close ogr_point */ void get_closest_node( const OGRPoint& ogr_point, const std::unique_ptr<OGRLineString>& closest_way, std::unique_ptr<OGRPoint>& closest_node, int& ind_closest_node) { double min_dist = std::numeric_limits<double>::max(); double dist; OGRPoint closest_node_candidate; // iterate over all points of the closest way for (int i=0; i<closest_way->getNumPoints(); i++){ closest_way->getPoint(i, &closest_node_candidate); dist = ogr_point.Distance(&closest_node_candidate); if (dist < min_dist) { min_dist = dist; ind_closest_node = i; } } closest_way->getPoint(ind_closest_node, closest_node.get()); } /* given the linestring closest_way, return the point on it that is closest to ogr_point */ void get_closest_point_from_node_neighbourhood( const OGRPoint& ogr_point, const std::unique_ptr<OGRLineString>& closest_way, const int& ind_closest_node, std::unique_ptr<OGRPoint>& closest_point) // out { OGRPoint neighbour_node; OGRPoint closest_point_candidate; OGRPoint closest_node; closest_way.get()->getPoint(ind_closest_node, &closest_node); closest_point.reset(static_cast<OGRPoint*>(closest_node.clone())); if (ind_closest_node > 0) { closest_way->getPoint(ind_closest_node-1, &neighbour_node); get_closest_point_from_segment(closest_node, neighbour_node, ogr_point, *closest_point.get()); // no if condition necessary here, because get_closest_point_from_segment() // will return a point, that is at least as close as closest_node } if (ind_closest_node < closest_way->getNumPoints()-1) { closest_way->getPoint(ind_closest_node+1, &neighbour_node); get_closest_point_from_segment(closest_node, neighbour_node, ogr_point, closest_point_candidate); if (ogr_point.Distance(&closest_point_candidate) < ogr_point.Distance(closest_point.get())) { closest_point.reset(static_cast<OGRPoint*>(closest_point_candidate.clone())); } } } // based on: http://postgis.refractions.net/documentation/postgis-doxygen/da/de7/liblwgeom_8h_84b0e41df157ca1201ccae4da3e3ef7d.html#84b0e41df157ca1201ccae4da3e3ef7d // see also: http://femto.cs.illinois.edu/faqs/cga-faq.html#S1.02 /* given a single line segment from a to b, return the point on it that is closest to p */ void get_closest_point_from_segment( const OGRPoint& a, const OGRPoint& b, const OGRPoint& p, OGRPoint& ret) { double r; r = ((p.getX()-a.getX()) * (b.getX()-a.getX()) + (p.getY()-a.getY()) * (b.getY()-a.getY())) / (pow(b.getX()-a.getX(),2)+pow(b.getY()-a.getY(),2)); if (r<0) { ret = a; } else if (r>1) { ret = b; } else { OGRLineString linestring; linestring.addPoint(a.getX(), a.getY()); linestring.addPoint(b.getX(), b.getY()); linestring.Value(r*linestring.get_Length(), &ret); } } bool has_entry_in_name2highways(const osmium::OSMObject& object) { return has_entry_in_name2highways(std::string(object.tags().get_value_by_key("addr:street"))); } bool has_entry_in_name2highways(const std::string& addrstreet) { if (mp_name2highways_nonarea.find(std::string(addrstreet)) != mp_name2highways_nonarea.end() || // TODO: use result directly (mp_name2highways_area.find(std::string(addrstreet)) != mp_name2highways_area.end())) { return true; } else { return false; } } bool has_entry_in_name2place(const osmium::OSMObject& object) { return has_entry_in_name2place(std::string(object.tags().get_value_by_key("addr:place"))); } bool has_entry_in_name2place(const std::string& addrplace) { if (m_name2place_nody.find(std::string(addrplace)) != m_name2place_nody.end() || // TODO: use result directly (m_name2place_wayy.find(std::string(addrplace)) != m_name2place_wayy.end())) { return true; } else { return false; } } name2highways_type& mp_name2highways_area; name2highways_type& mp_name2highways_nonarea; name2place_type& m_name2place_nody; name2place_type& m_name2place_wayy; const char* addrstreet; const char* addrplace; osmium::geom::OGRFactory<> m_factory {}; NearestPointsWriter* mp_nearest_points_writer; NearestRoadsWriter* mp_nearest_roads_writer; NearestAreasWriter* mp_nearest_areas_writer; ConnectionLineWriter* mp_connection_line_writer; GeometryHelper m_geometry_helper; }; #endif /* CONNECTIONLINEPREPROCESSOR_HPP_ */
36.690307
165
0.712436
johsin18
e7b2e2548c6985e692f8a1b79c9b4abda424f4a5
3,129
hpp
C++
util/third_party/ot-br-posix/src/backbone_router/dua_routing_manager.hpp
PascalGuenther/gecko_sdk
2e82050dc8823c9fe0e8908c1b2666fb83056230
[ "Zlib" ]
null
null
null
util/third_party/ot-br-posix/src/backbone_router/dua_routing_manager.hpp
PascalGuenther/gecko_sdk
2e82050dc8823c9fe0e8908c1b2666fb83056230
[ "Zlib" ]
null
null
null
util/third_party/ot-br-posix/src/backbone_router/dua_routing_manager.hpp
PascalGuenther/gecko_sdk
2e82050dc8823c9fe0e8908c1b2666fb83056230
[ "Zlib" ]
null
null
null
/* * Copyright (c) 2020, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * This file includes definition for DUA routing functionalities. */ #ifndef BACKBONE_ROUTER_DUA_ROUTING_MANAGER #define BACKBONE_ROUTER_DUA_ROUTING_MANAGER #if OTBR_ENABLE_DUA_ROUTING #include <set> #include <openthread/backbone_router_ftd.h> #include "agent/instance_params.hpp" #include "common/code_utils.hpp" #include "ncp/ncp_openthread.hpp" #include "utils/system_utils.hpp" namespace otbr { namespace BackboneRouter { /** * @addtogroup border-router-backbone * * @brief * This module includes definition for DUA routing functionalities. * * @{ */ /** * This class implements the DUA routing manager. * */ class DuaRoutingManager : private NonCopyable { public: /** * This constructor initializes a DUA routing manager instance. * */ explicit DuaRoutingManager() : mEnabled(false) { } /** * This method enables the DUA routing manager. * */ void Enable(const Ip6Prefix &aDomainPrefix); /** * This method disables the DUA routing manager. * */ void Disable(void); private: void AddDefaultRouteToThread(void); void DelDefaultRouteToThread(void); void AddPolicyRouteToBackbone(void); void DelPolicyRouteToBackbone(void); Ip6Prefix mDomainPrefix; bool mEnabled : 1; }; /** * @} */ } // namespace BackboneRouter } // namespace otbr #endif // OTBR_ENABLE_DUA_ROUTING #endif // BACKBONE_ROUTER_DUA_ROUTING_MANAGER
29.242991
81
0.717162
PascalGuenther
e7b3c87f107652f570bf0e8cced87e2e713d55c6
3,357
cpp
C++
test/gl/test_context.cpp
galaxysoftware/galaxy
b05af4aa071e32a0b0b067bfb80a236a90c87dde
[ "MIT" ]
null
null
null
test/gl/test_context.cpp
galaxysoftware/galaxy
b05af4aa071e32a0b0b067bfb80a236a90c87dde
[ "MIT" ]
null
null
null
test/gl/test_context.cpp
galaxysoftware/galaxy
b05af4aa071e32a0b0b067bfb80a236a90c87dde
[ "MIT" ]
null
null
null
#include "gl/context.h" #include "gl/environment.h" #include "gl/mockglfw.h" #include "gl/mockglxw.h" #include <gmock/gmock.h> using namespace gxy; using testing::_; using testing::InSequence; using testing::NiceMock; using testing::Return; struct Fixture : public testing::Test { const int width{42}; const int height{89}; const std::string title{"badger"}; NiceMock<gl::mockglfw> mockglfw{}; NiceMock<gl::mockglxw> mockglxw{}; ::GLFWwindow window{}; Fixture() { ON_CALL(mockglfw, Init()) .WillByDefault(Return(GL_TRUE)); ON_CALL(mockglxw, Init()) .WillByDefault(Return(0)); ON_CALL(mockglfw, CreateWindow(_, _, _, _, _)) .WillByDefault(Return(&window)); } }; struct EnvironmentFixture : public Fixture { gl::environment env{}; }; TEST_F(EnvironmentFixture, CreateContext_CreatesWindow) { EXPECT_CALL(mockglfw, CreateWindow(width, height, title.c_str(), nullptr, nullptr)) .Times(1); gl::context ctx{env, width, height, title.c_str()}; } TEST_F(EnvironmentFixture, CreateContext_SetsWindowHintsBefore) { InSequence s; EXPECT_CALL(mockglfw, WindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4)) .Times(1); EXPECT_CALL(mockglfw, WindowHint(GLFW_CONTEXT_VERSION_MINOR, 1)) .Times(1); EXPECT_CALL(mockglfw, WindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE)) .Times(1); EXPECT_CALL(mockglfw, WindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE)) .Times(1); EXPECT_CALL(mockglfw, CreateWindow(_, _, _, _, _)) .Times(1); gl::context ctx{env, width, height, title.c_str()}; } TEST_F(EnvironmentFixture, CreateContext_ResetWindowHintsAfter) { InSequence s; EXPECT_CALL(mockglfw, CreateWindow(_, _, _, _, _)) .Times(1); EXPECT_CALL(mockglfw, DefaultWindowHints()) .Times(1); gl::context ctx{env, width, height, title.c_str()}; } TEST_F(EnvironmentFixture, CreateContext_MakesContextCurrent) { EXPECT_CALL(mockglfw, MakeContextCurrent(&window)) .Times(1); gl::context ctx{env, width, height, title.c_str()}; } TEST_F(EnvironmentFixture, DestructContext_CallsDestroyWindow) { gl::context ctx{env, width, height, title.c_str()}; EXPECT_CALL(mockglfw, DestroyWindow(&window)) .Times(1); } using EnvironmentFixtureDeathTest = EnvironmentFixture; TEST_F(EnvironmentFixtureDeathTest, CreateWindowReturnsNullptr_Death) { ASSERT_DEATH({ ON_CALL(mockglfw, CreateWindow(_, _, _, _, _)) .WillByDefault(Return(nullptr)); gl::context ctx(env, width, height, title.c_str()); }, ""); } struct ContextFixture : public EnvironmentFixture { gl::context uut{env, width, height, title.c_str()}; }; TEST_F(ContextFixture, RunOneWindowShouldCloseTrue_ReturnsFalse) { EXPECT_CALL(mockglfw, WindowShouldClose(&window)) .WillOnce(Return(true)); ASSERT_FALSE(uut.run_one()); } struct ContextFixtureWindowShouldntClose : public ContextFixture { ContextFixtureWindowShouldntClose() { ON_CALL(mockglfw, WindowShouldClose(&window)) .WillByDefault(Return(false)); } }; TEST_F(ContextFixtureWindowShouldntClose, RunOne_ReturnsTrue) { ASSERT_TRUE(uut.run_one()); } TEST_F(ContextFixtureWindowShouldntClose, RunOne_CallsSwapBuffersThenPollEvents) { InSequence s; EXPECT_CALL(mockglfw, SwapBuffers(&window)) .Times(1); EXPECT_CALL(mockglfw, PollEvents()) .Times(1); uut.run_one(); }
21.519231
85
0.725052
galaxysoftware
e7b4b2d5aab6e9ec84745e940accc37779f2f3d5
5,904
cpp
C++
examples/machine_learning/logistic_regression.cpp
JuliaComputing/arrayfire
93427f09ff928f97df29c0e358c3fcf6b478bec6
[ "BSD-3-Clause" ]
1
2018-06-14T23:49:18.000Z
2018-06-14T23:49:18.000Z
examples/machine_learning/logistic_regression.cpp
JuliaComputing/arrayfire
93427f09ff928f97df29c0e358c3fcf6b478bec6
[ "BSD-3-Clause" ]
1
2015-07-02T15:53:02.000Z
2015-07-02T15:53:02.000Z
examples/machine_learning/logistic_regression.cpp
JuliaComputing/arrayfire
93427f09ff928f97df29c0e358c3fcf6b478bec6
[ "BSD-3-Clause" ]
1
2018-02-26T17:11:03.000Z
2018-02-26T17:11:03.000Z
/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <arrayfire.h> #include <stdio.h> #include <vector> #include <string> #include <af/util.h> #include <math.h> #include "mnist_common.h" using namespace af; float accuracy(const array& predicted, const array& target) { array val, plabels, tlabels; max(val, tlabels, target, 1); max(val, plabels, predicted, 1); return 100 * count<float>(plabels == tlabels) / tlabels.elements(); } float abserr(const array& predicted, const array& target) { return 100 * sum<float>(abs(predicted - target)) / predicted.elements(); } // Activation function array sigmoid(const array &val) { return 1 / (1 + exp(-val)); } // Predict based on given parameters array predict(const array &X, const array &Weights) { array Z = matmul(X, Weights); return sigmoid(Z); } void cost(array &J, array &dJ, const array &Weights, const array &X, const array &Y, double lambda = 1.0) { // Number of samples int m = Y.dims(0); // Make the lambda corresponding to Weights(0) == 0 array lambdat = constant(lambda, Weights.dims()); // No regularization for bias weights lambdat(0, span) = 0; // Get the prediction array H = predict(X, Weights); // Cost of misprediction array Jerr = -sum(Y * log(H) + (1 - Y) * log(1 - H)); // Regularization cost array Jreg = 0.5 * sum(lambdat * Weights * Weights); // Total cost J = (Jerr + Jreg) / m; // Find the gradient of cost array D = (H - Y); dJ = (matmulTN(X, D) + lambdat * Weights) / m; } array train(const array &X, const array &Y, double alpha = 0.1, double lambda = 1.0, double maxerr = 0.01, int maxiter = 1000, bool verbose = false) { // Initialize parameters to 0 array Weights = constant(0, X.dims(1), Y.dims(1)); array J, dJ; float err = 0; for (int i = 0; i < maxiter; i++) { // Get the cost and gradient cost(J, dJ, Weights, X, Y, lambda); err = max<float>(abs(J)); if (err < maxerr) { printf("Iteration %4d Err: %.4f\n", i + 1, err); printf("Training converged\n"); return Weights; } if (verbose && ((i + 1) % 10 == 0)) { printf("Iteration %4d Err: %.4f\n", i + 1, err); } // Update the parameters via gradient descent Weights = Weights - alpha * dJ; } printf("Training stopped after %d iterations\n", maxiter); return Weights; } void benchmark_logistic_regression(const array &train_feats, const array &train_targets, const array test_feats) { timer::start(); array Weights = train(train_feats, train_targets, 0.1, 1.0, 0.01, 1000); af::sync(); printf("Training time: %4.4lf s\n", timer::stop()); timer::start(); const int iter = 100; for (int i = 0; i < iter; i++) { array test_outputs = predict(test_feats , Weights); test_outputs.eval(); } af::sync(); printf("Prediction time: %4.4lf s\n", timer::stop() / iter); } // Demo of one vs all logistic regression int logit_demo(bool console, int perc) { array train_images, train_targets; array test_images, test_targets; int num_train, num_test, num_classes; // Load mnist data float frac = (float)(perc) / 100.0; setup_mnist<true>(&num_classes, &num_train, &num_test, train_images, test_images, train_targets, test_targets, frac); // Reshape images into feature vectors int feature_length = train_images.elements() / num_train; array train_feats = moddims(train_images, feature_length, num_train).T(); array test_feats = moddims(test_images , feature_length, num_test ).T(); train_targets = train_targets.T(); test_targets = test_targets.T(); // Add a bias that is always 1 train_feats = join(1, constant(1, num_train, 1), train_feats); test_feats = join(1, constant(1, num_test , 1), test_feats ); // Train logistic regression parameters array Weights = train(train_feats, train_targets, 0.1, // learning rate (aka alpha) 1.0, // regularization constant (aka weight decay, aka lamdba) 0.01, // maximum error 1000, // maximum iterations true);// verbose // Predict the results array train_outputs = predict(train_feats, Weights); array test_outputs = predict(test_feats , Weights); printf("Accuracy on training data: %2.2f\n", accuracy(train_outputs, train_targets )); printf("Accuracy on testing data: %2.2f\n", accuracy(test_outputs , test_targets )); printf("Maximum error on testing data: %2.2f\n", abserr(test_outputs , test_targets )); benchmark_logistic_regression(train_feats, train_targets, test_feats); if (!console) { test_outputs = test_outputs.T(); // Get 20 random test images. display_results<true>(test_images, test_outputs, test_targets.T(), 20); } return 0; } int main(int argc, char** argv) { int device = argc > 1 ? atoi(argv[1]) : 0; bool console = argc > 2 ? argv[2][0] == '-' : false; int perc = argc > 3 ? atoi(argv[3]) : 60; try { af::setDevice(device); af::info(); return logit_demo(console, perc); } catch (af::exception &ae) { std::cerr << ae.what() << std::endl; } }
28.521739
89
0.581809
JuliaComputing
e7b6bace6b9662be476cf3b3c48f18776742bf57
325
cpp
C++
Arrays/staticdynamic.cpp
sans712/SDE-Interview-Questions
44f5bda60b9ed301b93a944e1c333d833c9b054b
[ "MIT" ]
null
null
null
Arrays/staticdynamic.cpp
sans712/SDE-Interview-Questions
44f5bda60b9ed301b93a944e1c333d833c9b054b
[ "MIT" ]
null
null
null
Arrays/staticdynamic.cpp
sans712/SDE-Interview-Questions
44f5bda60b9ed301b93a944e1c333d833c9b054b
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; int main(){ int n; cin>>n; int b[100]; //static cout<<sizeof(b)<<endl; cout<<b<<endl; //symbol table int * a=new int[n]; //dynamic cout<<sizeof(a)<<endl; cout<<a<<endl; for(int i=0;i<n;i++){ cin>>a[i]; cout<<a[i]<<" "; } cout<<endl; delete [] a; }
18.055556
41
0.535385
sans712
e7b7ddf12ac03a01ce7a57b655968d326ddc4310
7,355
cpp
C++
lib/src/AMRTools/CoarseAverageFace.cpp
rmrsk/Chombo-3.3
f2119e396460c1bb19638effd55eb71c2b35119e
[ "BSD-3-Clause-LBNL" ]
10
2018-02-01T20:57:36.000Z
2022-03-17T02:57:49.000Z
lib/src/AMRTools/CoarseAverageFace.cpp
rmrsk/Chombo-3.3
f2119e396460c1bb19638effd55eb71c2b35119e
[ "BSD-3-Clause-LBNL" ]
19
2018-10-04T21:37:18.000Z
2022-02-25T16:20:11.000Z
lib/src/AMRTools/CoarseAverageFace.cpp
rmrsk/Chombo-3.3
f2119e396460c1bb19638effd55eb71c2b35119e
[ "BSD-3-Clause-LBNL" ]
11
2019-01-12T23:33:32.000Z
2021-08-09T15:19:50.000Z
#ifdef CH_LANG_CC /* * _______ __ * / ___/ / ___ __ _ / / ___ * / /__/ _ \/ _ \/ V \/ _ \/ _ \ * \___/_//_/\___/_/_/_/_.__/\___/ * Please refer to Copyright.txt, in Chombo's root directory. */ #endif #include "CoarseAverageFace.H" #include "AverageFaceF_F.H" #include "NamespaceHeader.H" // ---------------------------------------------------------- CoarseAverageFace::CoarseAverageFace() : m_isDefined(false), m_isAveraged(false) { } // ---------------------------------------------------------- CoarseAverageFace::~CoarseAverageFace() { } // ---------------------------------------------------------- CoarseAverageFace::CoarseAverageFace(const DisjointBoxLayout& a_fineGrids, int a_nComp, int a_nRef) : m_isDefined(false), m_isAveraged(false) { define(a_fineGrids, a_nComp, a_nRef); } // ---------------------------------------------------------- void CoarseAverageFace::define(const DisjointBoxLayout& a_fineGrids, int a_nComp, int a_nRef) { m_nRef = a_nRef; DisjointBoxLayout coarsened_fine_domain; coarsen(coarsened_fine_domain, a_fineGrids, m_nRef); m_coarsenedFineData.define(coarsened_fine_domain, a_nComp); m_isDefined = true; m_isAveraged = false; } // ---------------------------------------------------------- bool CoarseAverageFace::isDefined() const { return m_isDefined; } // ---------------------------------------------------------- void CoarseAverageFace::average(const LevelData<FluxBox>& a_fineData) { average(a_fineData, arithmetic, m_nRef); } // ---------------------------------------------------------- void CoarseAverageFace::averageHarmonic(const LevelData<FluxBox>& a_fineData) { average(a_fineData, harmonic, m_nRef); } // ---------------------------------------------------------- /** \param[in] a_refFactor * Sum of fine values is divided by * a_refFactor^(CH_SPACEDIM-1). For * sums this should be set to one * (default). */ void CoarseAverageFace::sum(const LevelData<FluxBox>& a_fineData, const int a_refFactor) { average(a_fineData, arithmetic, a_refFactor); } // ---------------------------------------------------------- void CoarseAverageFace::copyTo(LevelData<FluxBox>& a_coarseData) { CH_assert(m_isAveraged); // if coarseData's DisjointBoxLayout is not a simple coarsenening of // the fine one, then it needs to have at least one ghost cell in // order to ensure that this copyTo is done correctly. In // particular, this is required in order to ensure that we handle // the case where the coarse-fine interface is coincident with a // coarse-coarse boundary. The other solution to this would be to // build a specialized Copier for LevelData<FluxBox>, but we're // hoping to avoid that for now... if ((a_coarseData.ghostVect() == IntVect::Zero) && !(a_coarseData.getBoxes().compatible(m_coarsenedFineData.getBoxes()))) { MayDay::Error("CoarseAverageFace requires that coarse data which is not a coarsenening of the fine grids have at least one ghost cell"); } m_coarsenedFineData.copyTo(m_coarsenedFineData.interval(), a_coarseData, a_coarseData.interval()); } // ---------------------------------------------------------- // this function is shamelessly based on the ANAG CoarseAverage // (cell-centered) version void CoarseAverageFace::averageToCoarse(LevelData<FluxBox>& a_coarseData, const LevelData<FluxBox>& a_fineData) { computeAverages(a_coarseData, a_fineData, arithmetic); } // ---------------------------------------------------------- // this function is shamelessly based on the ANAG CoarseAverage // (cell-centered) version void CoarseAverageFace::averageToCoarseHarmonic(LevelData<FluxBox>& a_coarseData, const LevelData<FluxBox>& a_fineData) { computeAverages(a_coarseData, a_fineData, harmonic); } // ---------------------------------------------------------- void CoarseAverageFace::computeAverages(LevelData<FluxBox>& a_coarseData, const LevelData<FluxBox>& a_fineData, int a_averageType) { average(a_fineData, a_averageType, m_nRef); copyTo(a_coarseData); } // ---------------------------------------------------------- /** \param[in] a_refFactor * Sum of fine values is divided by * a_refFactor^(CH_SPACEDIM-1). * Normally this is the refinement ratio */ void CoarseAverageFace::average(const LevelData<FluxBox>& a_fineData, const int a_averageType, const int a_refFactor) { CH_assert(isDefined()); DataIterator dit = a_fineData.dataIterator(); for (dit.reset(); dit.ok(); ++dit) { FluxBox& coarsenedFine = m_coarsenedFineData[dit()]; const FluxBox& fine = a_fineData[dit()]; // coarsen from the entire fine grid onto the entire coarse grid averageGridData(coarsenedFine, fine, a_averageType, a_refFactor); } m_isAveraged = true; } // ---------------------------------------------------------- /** \param[in] a_refFactor * Sum of fine values is divided by * a_refFactor^(CH_SPACEDIM-1). * Normally this is the refinement ratio */ void CoarseAverageFace::averageGridData(FluxBox& a_coarsenedFine, const FluxBox& a_fine, int a_averageType, const int a_refFactor) const { for (int dir=0; dir<SpaceDim; dir++) { FArrayBox& coarseFab = a_coarsenedFine[dir]; const FArrayBox& fineFab = a_fine[dir]; const Box& coarseBox = coarseFab.box(); // set up refinement box int boxHi = m_nRef-1; IntVect hiVect(D_DECL6(boxHi,boxHi,boxHi, boxHi,boxHi,boxHi)); // don't want to index at all in dir direction -- // instead, want to just march along face. hiVect.setVal(dir,0); IntVect loVect(D_DECL6(0,0,0,0,0,0)); Box refBox(loVect, hiVect); if (a_averageType == arithmetic) { FORT_AVERAGEFACE( CHF_FRA(coarseFab), CHF_CONST_FRA(fineFab), CHF_BOX(coarseBox), CHF_CONST_INT(dir), CHF_CONST_INT(m_nRef), CHF_CONST_INT(a_refFactor), CHF_BOX(refBox)); } else if (a_averageType == harmonic) { FORT_AVERAGEFACEHARMONIC( CHF_FRA(coarseFab), CHF_CONST_FRA(fineFab), CHF_BOX(coarseBox), CHF_CONST_INT(dir), CHF_CONST_INT(m_nRef), CHF_CONST_INT(a_refFactor), CHF_BOX(refBox)); } else { MayDay::Error("CoarseAverageFace::averageGridData -- bad averageType"); } } } #include "NamespaceFooter.H"
31.978261
142
0.531883
rmrsk
e7ba73c31342d0787160f6b39652973be4e8a5f8
4,721
inl
C++
Phoenix3D/PX2Effect/PX2BeamEmitter.inl
PheonixFoundation/Phoenix3D
bfb2e3757bf61ac461aeeda9216bf8c8fdf76d99
[ "BSL-1.0" ]
36
2016-04-24T01:40:38.000Z
2022-01-18T07:32:26.000Z
Phoenix3D/PX2Effect/PX2BeamEmitter.inl
PheonixFoundation/Phoenix3D
bfb2e3757bf61ac461aeeda9216bf8c8fdf76d99
[ "BSL-1.0" ]
null
null
null
Phoenix3D/PX2Effect/PX2BeamEmitter.inl
PheonixFoundation/Phoenix3D
bfb2e3757bf61ac461aeeda9216bf8c8fdf76d99
[ "BSL-1.0" ]
16
2016-06-13T08:43:51.000Z
2020-09-15T13:25:58.000Z
// PX2BeamEmitter.inl //---------------------------------------------------------------------------- inline void BeamEmitter::SetEmitRate (float rate) { mEmitRate = rate; } //---------------------------------------------------------------------------- inline float BeamEmitter::GetEmitRate () const { return mEmitRate; } //---------------------------------------------------------------------------- inline void BeamEmitter::SetEmitStartPos (const APoint &startPos) { mEmitStartPos = startPos; } //---------------------------------------------------------------------------- inline const APoint &BeamEmitter::GetEmitStartPos () const { return mEmitStartPos; } //---------------------------------------------------------------------------- inline void BeamEmitter::SetEmitEndPos (const APoint &endPos) { mEmitEndPos = endPos; } //---------------------------------------------------------------------------- inline const APoint &BeamEmitter::GetEmitEndPos () const { return mEmitEndPos; } //---------------------------------------------------------------------------- inline void BeamEmitter::SetStartPosUseLocal (bool startUseLocal) { mIsStartUseLocal = startUseLocal; } //---------------------------------------------------------------------------- inline bool BeamEmitter::IsStartPosUseLocal () const { return mIsStartUseLocal; } //---------------------------------------------------------------------------- inline void BeamEmitter::SetSimpleLineWave (bool simpleLineWave) { mIsSimpleLineWave = simpleLineWave; } //---------------------------------------------------------------------------- inline bool BeamEmitter::IsSimpleLineWave () const { return mIsSimpleLineWave; } //---------------------------------------------------------------------------- inline void BeamEmitter::SetSimpleLineDoAlphaDisAfterStopSpeed (float speed) { mDoAlphaDisAfterStopSpeed = speed; } //---------------------------------------------------------------------------- inline float BeamEmitter::GetSimpleLineDoAlphaDisAfterStopSpeed () const { return mDoAlphaDisAfterStopSpeed; } //---------------------------------------------------------------------------- inline void BeamEmitter::SetWaveTypeUp (WaveType type) { mWaveTypeUp = type; } //---------------------------------------------------------------------------- inline BeamEmitter::WaveType BeamEmitter::GetWaveTypeUp () const { return mWaveTypeUp; } //---------------------------------------------------------------------------- inline void BeamEmitter::SetWaveTypeExtend (WaveType type) { mWaveTypeExtend = type; } //---------------------------------------------------------------------------- inline BeamEmitter::WaveType BeamEmitter::GetWaveTypeExtend () const { return mWaveTypeExtend; } //---------------------------------------------------------------------------- inline int BeamEmitter::GetNumMaxBeams () const { return mNumMaxBeams; } //---------------------------------------------------------------------------- inline int BeamEmitter::GetNumLowFrequency () const { return mNumLowFrequency; } //---------------------------------------------------------------------------- inline int BeamEmitter::GetNumHighFrequency () const { return mNumHighFrequency; } //---------------------------------------------------------------------------- inline void BeamEmitter::SetLowFrequencyRangeUp (const Float2 &range) { mLowRangeUp = range; } //---------------------------------------------------------------------------- inline void BeamEmitter::SetLowFrequencyRangeExtend (const Float2 &range) { mLowRangeExtend = range; } //---------------------------------------------------------------------------- inline const Float2 &BeamEmitter::GetLowFrequencyRangeUp () const { return mLowRangeUp; } //---------------------------------------------------------------------------- inline const Float2 &BeamEmitter::GetLowFrequencyRangeExtend () const { return mLowRangeExtend; } //---------------------------------------------------------------------------- inline void BeamEmitter::SetHighFrequencyRangeUp (const Float2 &range) { mHighRangeUp = range; } //---------------------------------------------------------------------------- inline void BeamEmitter::SetHighFrequencyRangeExtend (const Float2 &range) { mHighRangeExtend = range; } //---------------------------------------------------------------------------- inline const Float2 &BeamEmitter::GetHighFrequencyRangeUp () const { return mHighRangeUp; } //---------------------------------------------------------------------------- inline const Float2 &BeamEmitter::GetHighFrequencyRangeExtend () const { return mHighRangeExtend; } //----------------------------------------------------------------------------
34.210145
78
0.421945
PheonixFoundation
e7bb392669b2859123df05d58f95d1cdbd470862
3,420
cpp
C++
test/TestSpecializationConstant.cpp
dSandley20/KomputeParticles
099073c6db4b5345e80eaaebe97d97e0f8256849
[ "Apache-2.0" ]
389
2021-07-23T23:24:18.000Z
2022-03-31T12:16:47.000Z
test/TestSpecializationConstant.cpp
dSandley20/KomputeParticles
099073c6db4b5345e80eaaebe97d97e0f8256849
[ "Apache-2.0" ]
54
2020-08-28T14:33:52.000Z
2020-09-13T10:59:42.000Z
test/TestSpecializationConstant.cpp
dSandley20/KomputeParticles
099073c6db4b5345e80eaaebe97d97e0f8256849
[ "Apache-2.0" ]
31
2021-07-27T14:32:24.000Z
2022-03-19T07:57:01.000Z
// SPDX-License-Identifier: Apache-2.0 #include "gtest/gtest.h" #include "kompute/Kompute.hpp" #include "kompute_test/Shader.hpp" TEST(TestSpecializationConstants, TestTwoConstants) { { std::string shader(R"( #version 450 layout (constant_id = 0) const float cOne = 1; layout (constant_id = 1) const float cTwo = 1; layout (local_size_x = 1) in; layout(set = 0, binding = 0) buffer a { float pa[]; }; layout(set = 0, binding = 1) buffer b { float pb[]; }; void main() { uint index = gl_GlobalInvocationID.x; pa[index] = cOne; pb[index] = cTwo; })"); std::vector<uint32_t> spirv = compileSource(shader); std::shared_ptr<kp::Sequence> sq = nullptr; { kp::Manager mgr; std::shared_ptr<kp::TensorT<float>> tensorA = mgr.tensor({ 0, 0, 0 }); std::shared_ptr<kp::TensorT<float>> tensorB = mgr.tensor({ 0, 0, 0 }); std::vector<std::shared_ptr<kp::Tensor>> params = { tensorA, tensorB }; std::vector<float> spec = std::vector<float>({ 5.0, 0.3 }); std::shared_ptr<kp::Algorithm> algo = mgr.algorithm(params, spirv, {}, spec); sq = mgr.sequence() ->record<kp::OpTensorSyncDevice>(params) ->record<kp::OpAlgoDispatch>(algo) ->record<kp::OpTensorSyncLocal>(params) ->eval(); EXPECT_EQ(tensorA->vector(), std::vector<float>({ 5, 5, 5 })); EXPECT_EQ(tensorB->vector(), std::vector<float>({ 0.3, 0.3, 0.3 })); } } } TEST(TestSpecializationConstants, TestConstantsInt) { { std::string shader(R"( #version 450 layout (constant_id = 0) const int cOne = 1; layout (constant_id = 1) const int cTwo = 1; layout (local_size_x = 1) in; layout(set = 0, binding = 0) buffer a { int pa[]; }; layout(set = 0, binding = 1) buffer b { int pb[]; }; void main() { uint index = gl_GlobalInvocationID.x; pa[index] = cOne; pb[index] = cTwo; })"); std::vector<uint32_t> spirv = compileSource(shader); std::shared_ptr<kp::Sequence> sq = nullptr; { kp::Manager mgr; std::shared_ptr<kp::TensorT<int32_t>> tensorA = mgr.tensorT<int32_t>({ 0, 0, 0 }); std::shared_ptr<kp::TensorT<int32_t>> tensorB = mgr.tensorT<int32_t>({ 0, 0, 0 }); std::vector<std::shared_ptr<kp::Tensor>> params = { tensorA, tensorB }; std::vector<int32_t> spec({ -1, -2 }); std::shared_ptr<kp::Algorithm> algo = mgr.algorithm(params, spirv, {}, spec, {}); sq = mgr.sequence() ->record<kp::OpTensorSyncDevice>(params) ->record<kp::OpAlgoDispatch>(algo) ->record<kp::OpTensorSyncLocal>(params) ->eval(); EXPECT_EQ(tensorA->vector(), std::vector<int32_t>({ -1, -1, -1 })); EXPECT_EQ(tensorB->vector(), std::vector<int32_t>({ -2, -2, -2 })); } } }
32.884615
80
0.490643
dSandley20
e7bc27d00fa4fafc791cc685ff02c186e5c0c86a
4,859
hpp
C++
Source/KEngine/include/KEngine/Common/JSONReader.hpp
yxbh/KEngine
04d2aced738984f53bf1b2b84b49fbbabfbe6587
[ "Zlib" ]
1
2020-05-29T03:30:08.000Z
2020-05-29T03:30:08.000Z
Source/KEngine/include/KEngine/Common/JSONReader.hpp
yxbh/KEngine
04d2aced738984f53bf1b2b84b49fbbabfbe6587
[ "Zlib" ]
null
null
null
Source/KEngine/include/KEngine/Common/JSONReader.hpp
yxbh/KEngine
04d2aced738984f53bf1b2b84b49fbbabfbe6587
[ "Zlib" ]
null
null
null
#pragma once // libJSON lib #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4100) // unreferenced formal parameter. #pragma warning(disable : 4127) // conditional expression is constant. #endif #include "libjson_7.6.1/libjson.h" #ifdef _MSC_VER #pragma warning(pop) #endif #include <string> #include <stack> #include "IJSONReader.hpp" namespace ke { /** \class JSONReader A IJSONReader implementation which itself wraps around libjson. */ class JSONReader : public IJSONReader { public: using JSONResourceType = JSONNode; using ArrayType = JSONResourceType; using NodeType = JSONResourceType; /** \class tree_record A record of a parent JSON member & child JSON member relationship. */ struct tree_record { const JSONResourceType & parent_member; JSONNode::const_iterator iterator; tree_record(const JSONResourceType & p_rParentNode, JSONNode::const_iterator p_It) : parent_member(p_rParentNode), iterator(p_It) {}; tree_record(const tree_record & p_rRecord) : tree_record(p_rRecord.parent_member, p_rRecord.iterator) {}; JSONReader & operator = (const tree_record & p_rRecord) = delete; }; // tree_record struct private: bool m_Loaded = false; // loaded json code. JSONResourceType m_Node; bool m_AtRoot = true; std::stack<tree_record> m_TreeITStack; public: // omit ctor & dtor declaration because default versions will work. /** load & parse json file at path. @return false if failure. */ virtual bool load(const std::string & p_rPath) final; /** load string with json code int it. @return false if failure. */ virtual bool parse(const std::string & p_rJSONDoc) final; /** @return a string dump of all the contents from the json doc.*/ virtual std::string dumpToString(void) final; /** @return true if current pointered to member value is a string. */ virtual bool isTypeString(void) final; /** @return true if current pointered to member value is a number. */ virtual bool isTypeNumber(void) final; /** @return true if current pointered to member value is a boolean. */ virtual bool isTypeBoolean(void) final; /** @return true if current pointered to member value is an array. */ virtual bool isTypeArray(void) final; /** @return true if current pointered to member value is a JSON node. */ virtual bool isTypeNode(void) final; /** @return true if current pointered to member value is null/blank. */ virtual bool isTypeNull(void) final; /** @return the number of child elements the current element has. */ virtual SizeType getChildrenCount(void) const final; /** @return true if the current pointed to element has any children elements. */ virtual bool hasChildren(void) const final; /** @return current pointed to json node as a string. */ virtual StringType getValueAsString(void) const final; /** @return current pointed to json node as a number. */ virtual NumberType getValueAsNumber(void) const final; /** @return current pointed to json node as an integer. */ virtual IntegerType getValueAsInt(void) const final; /** @return current pointed to json node as a double. */ virtual FloatType getValueAsDouble(void) const final; /** @return current pointed to json node as a boolean. */ virtual BooleanType getValueAsBoolean(void) const final; /** @return true if cursor is point to the root object. */ virtual bool atRoot(void) const final; /** point cursor to the first Member/child of this member. @return true if this member contains multiple members or the value is an non-empty array. */ virtual bool traverseThisMember(void) final; /** point cursor to the parent member's next child member from this member if the parent is an array or member. @return false if there's no more. */ virtual bool pointToNextMember(void) final; /** point cursor to the parent member's previous child member from this member if the parent is an array or member. @return false if there's no more. */ virtual bool pointToPreviousMember(void) final; /** point cursor to the parent node of the currently pointed to json member. @return false if current pointed to node is the parent. */ virtual bool pointToParentMember(void) final; /** find the child element with the specified key name, and point the cursor to it. @return true if found.*/ virtual bool pointToChildElement(const std::string p_NameKey) final; /** @return name of the current element. */ virtual StringType getElementName(void) const final; }; // JSONReader class } // KE ns
42.622807
119
0.685326
yxbh
e7bffcd83db49941b0963aaf988354586bba3f38
1,005
cpp
C++
src/grbl/parsers/response_message/ResponseMessageParser.test.cpp
jgert/grblController
e5026b1e5d972f3e67b07c3fb80dad276bae2c17
[ "MIT" ]
2
2021-12-19T19:15:28.000Z
2022-01-03T10:29:32.000Z
src/grbl/parsers/response_message/ResponseMessageParser.test.cpp
jgert/grblController
e5026b1e5d972f3e67b07c3fb80dad276bae2c17
[ "MIT" ]
12
2020-06-09T21:10:10.000Z
2022-02-25T14:11:17.000Z
src/grbl/parsers/response_message/ResponseMessageParser.test.cpp
jgert/grblController
e5026b1e5d972f3e67b07c3fb80dad276bae2c17
[ "MIT" ]
1
2020-08-13T04:00:55.000Z
2020-08-13T04:00:55.000Z
// // Created by Jakub Gert on 20/06/2020. // #include <QObject> #include <QTest> #include "tests/TestSuite.h" #include "ResponseMessageParser.h" class ResponseMessageParserTests : public TestSuite { Q_OBJECT private slots: void testInvalid() { ResponseMessageParser parser; auto result = parser.parse("o"); QCOMPARE(result, false); result = parser.parse("error"); QCOMPARE(result, false); result = parser.parse("error:"); QCOMPARE(result, false); result = parser.parse("error:a"); QCOMPARE(result, false); } void testValid() { ResponseMessageParser parser; auto result = parser.parse("ok"); QCOMPARE(result, true); QCOMPARE(parser.getError(), 0); result = parser.parse("error:0"); QCOMPARE(result, true); QCOMPARE(parser.getError(), 0); } }; static ResponseMessageParserTests T_ResponseMessageParserTests; #include "ResponseMessageParser.test.moc"
21.847826
63
0.637811
jgert
e7c1f1f9191098c0b0f356bbe11abb8af4409b7a
619
hpp
C++
source/native/encoder.hpp
giovannicalo/node-webp
d841ccd4316bb73d58c2d5e3a5f844d7435fb088
[ "MIT" ]
null
null
null
source/native/encoder.hpp
giovannicalo/node-webp
d841ccd4316bb73d58c2d5e3a5f844d7435fb088
[ "MIT" ]
null
null
null
source/native/encoder.hpp
giovannicalo/node-webp
d841ccd4316bb73d58c2d5e3a5f844d7435fb088
[ "MIT" ]
null
null
null
#pragma once #include <math.h> #include <napi.h> #include <webp/encode.h> #include "format.hpp" #include "image.hpp" namespace nodeWebp { class Encoder : public Napi::AsyncWorker { private: uint8_t* buffer = nullptr; Napi::Promise::Deferred promise; float_t quality = 0; uint64_t size = 0; Image* image = nullptr; public: Encoder( Napi::Env environment, Napi::Object source, float_t quality ); ~Encoder() override; void Execute() override; void OnError(const Napi::Error& error) override; void OnOK() override; Napi::Promise getPromise(); }; }
12.632653
51
0.647819
giovannicalo
e7c2d5559e6f32948945052a81a844dfab5a8a67
10,245
cc
C++
src/vendor/mariadb-10.6.7/storage/perfschema/table_file_summary_by_event_name.cc
zettadb/zettalib
3d5f96dc9e3e4aa255f4e6105489758944d37cc4
[ "Apache-2.0" ]
null
null
null
src/vendor/mariadb-10.6.7/storage/perfschema/table_file_summary_by_event_name.cc
zettadb/zettalib
3d5f96dc9e3e4aa255f4e6105489758944d37cc4
[ "Apache-2.0" ]
null
null
null
src/vendor/mariadb-10.6.7/storage/perfschema/table_file_summary_by_event_name.cc
zettadb/zettalib
3d5f96dc9e3e4aa255f4e6105489758944d37cc4
[ "Apache-2.0" ]
2
2022-02-27T14:00:01.000Z
2022-03-31T06:24:22.000Z
/* Copyright (c) 2008, 2021, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file storage/perfschema/table_file_summary_by_event_name.cc Table FILE_SUMMARY_BY_EVENT_NAME(implementation). */ #include "my_global.h" #include "my_thread.h" #include "pfs_instr_class.h" #include "pfs_column_types.h" #include "pfs_column_values.h" #include "table_file_summary_by_event_name.h" #include "pfs_global.h" #include "pfs_visitor.h" #include "field.h" THR_LOCK table_file_summary_by_event_name::m_table_lock; PFS_engine_table_share table_file_summary_by_event_name::m_share= { { C_STRING_WITH_LEN("file_summary_by_event_name") }, &pfs_truncatable_acl, table_file_summary_by_event_name::create, NULL, /* write_row */ table_file_summary_by_event_name::delete_all_rows, table_file_summary_by_event_name::get_row_count, sizeof(PFS_simple_index), &m_table_lock, { C_STRING_WITH_LEN("CREATE TABLE file_summary_by_event_name(" "EVENT_NAME VARCHAR(128) not null comment 'Event name.'," "COUNT_STAR BIGINT unsigned not null comment 'Number of summarized events'," "SUM_TIMER_WAIT BIGINT unsigned not null comment 'Total wait time of the summarized events that are timed.'," "MIN_TIMER_WAIT BIGINT unsigned not null comment 'Minimum wait time of the summarized events that are timed.'," "AVG_TIMER_WAIT BIGINT unsigned not null comment 'Average wait time of the summarized events that are timed.'," "MAX_TIMER_WAIT BIGINT unsigned not null comment 'Maximum wait time of the summarized events that are timed.'," "COUNT_READ BIGINT unsigned not null comment 'Number of all read operations, including FGETS, FGETC, FREAD, and READ.'," "SUM_TIMER_READ BIGINT unsigned not null comment 'Total wait time of all read operations that are timed.'," "MIN_TIMER_READ BIGINT unsigned not null comment 'Minimum wait time of all read operations that are timed.'," "AVG_TIMER_READ BIGINT unsigned not null comment 'Average wait time of all read operations that are timed.'," "MAX_TIMER_READ BIGINT unsigned not null comment 'Maximum wait time of all read operations that are timed.'," "SUM_NUMBER_OF_BYTES_READ BIGINT not null comment 'Bytes read by read operations.'," "COUNT_WRITE BIGINT unsigned not null comment 'Number of all write operations, including FPUTS, FPUTC, FPRINTF, VFPRINTF, FWRITE, and PWRITE.'," "SUM_TIMER_WRITE BIGINT unsigned not null comment 'Total wait time of all write operations that are timed.'," "MIN_TIMER_WRITE BIGINT unsigned not null comment 'Minimum wait time of all write operations that are timed.'," "AVG_TIMER_WRITE BIGINT unsigned not null comment 'Average wait time of all write operations that are timed.'," "MAX_TIMER_WRITE BIGINT unsigned not null comment 'Maximum wait time of all write operations that are timed.'," "SUM_NUMBER_OF_BYTES_WRITE BIGINT not null comment 'Bytes written by write operations.'," "COUNT_MISC BIGINT unsigned not null comment 'Number of all miscellaneous operations not counted above, including CREATE, DELETE, OPEN, CLOSE, STREAM_OPEN, STREAM_CLOSE, SEEK, TELL, FLUSH, STAT, FSTAT, CHSIZE, RENAME, and SYNC.'," "SUM_TIMER_MISC BIGINT unsigned not null comment 'Total wait time of all miscellaneous operations that are timed.'," "MIN_TIMER_MISC BIGINT unsigned not null comment 'Minimum wait time of all miscellaneous operations that are timed.'," "AVG_TIMER_MISC BIGINT unsigned not null comment 'Average wait time of all miscellaneous operations that are timed.'," "MAX_TIMER_MISC BIGINT unsigned not null comment 'Maximum wait time of all miscellaneous operations that are timed.')") }, false /* perpetual */ }; PFS_engine_table* table_file_summary_by_event_name::create(void) { return new table_file_summary_by_event_name(); } int table_file_summary_by_event_name::delete_all_rows(void) { reset_file_instance_io(); reset_file_class_io(); return 0; } ha_rows table_file_summary_by_event_name::get_row_count(void) { return file_class_max; } table_file_summary_by_event_name::table_file_summary_by_event_name() : PFS_engine_table(&m_share, &m_pos), m_pos(1), m_next_pos(1) {} void table_file_summary_by_event_name::reset_position(void) { m_pos.m_index= 1; m_next_pos.m_index= 1; } int table_file_summary_by_event_name::rnd_next(void) { PFS_file_class *file_class; m_pos.set_at(&m_next_pos); file_class= find_file_class(m_pos.m_index); if (file_class) { make_row(file_class); m_next_pos.set_after(&m_pos); return 0; } return HA_ERR_END_OF_FILE; } int table_file_summary_by_event_name::rnd_pos(const void *pos) { PFS_file_class *file_class; set_position(pos); file_class= find_file_class(m_pos.m_index); if (file_class) { make_row(file_class); return 0; } return HA_ERR_RECORD_DELETED; } /** Build a row. @param file_class the file class the cursor is reading */ void table_file_summary_by_event_name::make_row(PFS_file_class *file_class) { m_row.m_event_name.make_row(file_class); PFS_instance_file_io_stat_visitor visitor; PFS_instance_iterator::visit_file_instances(file_class, &visitor); time_normalizer *normalizer= time_normalizer::get(wait_timer); /* Collect timer and byte count stats */ m_row.m_io_stat.set(normalizer, &visitor.m_file_io_stat); m_row_exists= true; } int table_file_summary_by_event_name::read_row_values(TABLE *table, unsigned char *, Field **fields, bool read_all) { Field *f; if (unlikely(!m_row_exists)) return HA_ERR_RECORD_DELETED; /* Set the null bits */ assert(table->s->null_bytes == 0); for (; (f= *fields) ; fields++) { if (read_all || bitmap_is_set(table->read_set, f->field_index)) { switch(f->field_index) { case 0: /* EVENT_NAME */ m_row.m_event_name.set_field(f); break; case 1: /* COUNT_STAR */ set_field_ulonglong(f, m_row.m_io_stat.m_all.m_waits.m_count); break; case 2: /* SUM_TIMER_WAIT */ set_field_ulonglong(f, m_row.m_io_stat.m_all.m_waits.m_sum); break; case 3: /* MIN_TIMER_WAIT */ set_field_ulonglong(f, m_row.m_io_stat.m_all.m_waits.m_min); break; case 4: /* AVG_TIMER_WAIT */ set_field_ulonglong(f, m_row.m_io_stat.m_all.m_waits.m_avg); break; case 5: /* MAX_TIMER_WAIT */ set_field_ulonglong(f, m_row.m_io_stat.m_all.m_waits.m_max); break; case 6: /* COUNT_READ */ set_field_ulonglong(f, m_row.m_io_stat.m_read.m_waits.m_count); break; case 7: /* SUM_TIMER_READ */ set_field_ulonglong(f, m_row.m_io_stat.m_read.m_waits.m_sum); break; case 8: /* MIN_TIMER_READ */ set_field_ulonglong(f, m_row.m_io_stat.m_read.m_waits.m_min); break; case 9: /* AVG_TIMER_READ */ set_field_ulonglong(f, m_row.m_io_stat.m_read.m_waits.m_avg); break; case 10: /* MAX_TIMER_READ */ set_field_ulonglong(f, m_row.m_io_stat.m_read.m_waits.m_max); break; case 11: /* SUM_NUMBER_OF_BYTES_READ */ set_field_ulonglong(f, m_row.m_io_stat.m_read.m_bytes); break; case 12: /* COUNT_WRITE */ set_field_ulonglong(f, m_row.m_io_stat.m_write.m_waits.m_count); break; case 13: /* SUM_TIMER_WRITE */ set_field_ulonglong(f, m_row.m_io_stat.m_write.m_waits.m_sum); break; case 14: /* MIN_TIMER_WRITE */ set_field_ulonglong(f, m_row.m_io_stat.m_write.m_waits.m_min); break; case 15: /* AVG_TIMER_WRITE */ set_field_ulonglong(f, m_row.m_io_stat.m_write.m_waits.m_avg); break; case 16: /* MAX_TIMER_WRITE */ set_field_ulonglong(f, m_row.m_io_stat.m_write.m_waits.m_max); break; case 17: /* SUM_NUMBER_OF_BYTES_WRITE */ set_field_ulonglong(f, m_row.m_io_stat.m_write.m_bytes); break; case 18: /* COUNT_MISC */ set_field_ulonglong(f, m_row.m_io_stat.m_misc.m_waits.m_count); break; case 19: /* SUM_TIMER_MISC */ set_field_ulonglong(f, m_row.m_io_stat.m_misc.m_waits.m_sum); break; case 20: /* MIN_TIMER_MISC */ set_field_ulonglong(f, m_row.m_io_stat.m_misc.m_waits.m_min); break; case 21: /* AVG_TIMER_MISC */ set_field_ulonglong(f, m_row.m_io_stat.m_misc.m_waits.m_avg); break; case 22: /* MAX_TIMER_MISC */ set_field_ulonglong(f, m_row.m_io_stat.m_misc.m_waits.m_max); break; default: assert(false); break; } } // if } // for return 0; }
39.403846
252
0.684236
zettadb
b10f837bda4759c001e18beff0616cb05865e361
3,252
hpp
C++
plugins/EstimationPlugin/src/base/measurement/TDRSSTwoWayRange.hpp
Randl/GMAT
d6a5b1fed68c33b0c4b1cfbd1e25a71cdfb8f8f5
[ "Apache-2.0" ]
2
2020-01-01T13:14:57.000Z
2020-12-09T07:05:07.000Z
plugins/EstimationPlugin/src/base/measurement/TDRSSTwoWayRange.hpp
rdadan/GMAT-R2016a
d6a5b1fed68c33b0c4b1cfbd1e25a71cdfb8f8f5
[ "Apache-2.0" ]
1
2018-03-15T08:58:37.000Z
2018-03-20T20:11:26.000Z
plugins/EstimationPlugin/src/base/measurement/TDRSSTwoWayRange.hpp
rdadan/GMAT-R2016a
d6a5b1fed68c33b0c4b1cfbd1e25a71cdfb8f8f5
[ "Apache-2.0" ]
3
2019-10-13T10:26:49.000Z
2020-12-09T07:06:55.000Z
//$Id: TDRSSTwoWayRange.hpp 1398 2011-04-21 20:39:37Z $ //------------------------------------------------------------------------------ // TDRSSTwoWayRange //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool // // Copyright (c) 2002 - 2015 United States Government as represented by the // Administrator of The National Aeronautics and Space Administration. // All Other Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // You may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.apache.org/licenses/LICENSE-2.0. // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either // express or implied. See the License for the specific language // governing permissions and limitations under the License. // // Developed jointly by NASA/GSFC and Thinking Systems, Inc. under FDSS Task 28 // // Author: Darrel J. Conway, Thinking Systems, Inc. // Created: 2010/05/10 // /** * The TDRSS 2-way range core measurement model. */ //------------------------------------------------------------------------------ #ifndef TDRSSTwoWayRange_hpp #define TDRSSTwoWayRange_hpp #include "estimation_defs.hpp" #include "TwoWayRange.hpp" /** * TDRSS 2-Way Range Measurement Model */ class ESTIMATION_API TDRSSTwoWayRange: public TwoWayRange { public: TDRSSTwoWayRange(const std::string nomme = ""); virtual ~TDRSSTwoWayRange(); TDRSSTwoWayRange(const TDRSSTwoWayRange& usn); TDRSSTwoWayRange& operator=(const TDRSSTwoWayRange& usn); virtual GmatBase* Clone() const; bool SetRefObject(GmatBase *obj, const Gmat::ObjectType type, const std::string &name); bool SetRefObject(GmatBase *obj, const Gmat::ObjectType type, const std::string &name, const Integer index); virtual bool Initialize(); virtual const std::vector<RealArray>& CalculateMeasurementDerivatives( GmatBase *obj, Integer id); virtual Event* GetEvent(UnsignedInt whichOne); virtual bool SetEventData(Event *locatedEvent); protected: /// Turnaround time at the TDRSS (aka transponder delay) on way to the s/c Real tdrssUplinkDelay; /// Turnaround time at the TDRSS (aka transponder delay) on way to the ground Real tdrssDownlinkDelay; /// Light transit time for the forward link Real forwardlinkTime; /// Light transit time for the return link Real backlinkTime; /// The event used to model the uplink LightTimeCorrection forwardlinkLeg; /// The event used to model the downlink LightTimeCorrection backlinkLeg; /// The distance covered during the uplink Real forwardlinkRange; /// The distance covered during the downlink Real backlinkRange; virtual bool Evaluate(bool withEvents = false); void SetHardwareDelays(bool loadEvents); virtual void InitializeMeasurement(); }; #endif /* TDRSSTwoWayRange_hpp */
34.967742
80
0.646986
Randl
b10fd8ec331ec6aa27ddc9f37789e1e88583a0b3
14,017
cc
C++
ee/group.cc
flipfrog/xee
2586ed5bc0b9f99d8b314e363e0e8f76f46575ba
[ "MIT" ]
null
null
null
ee/group.cc
flipfrog/xee
2586ed5bc0b9f99d8b314e363e0e8f76f46575ba
[ "MIT" ]
null
null
null
ee/group.cc
flipfrog/xee
2586ed5bc0b9f99d8b314e363e0e8f76f46575ba
[ "MIT" ]
null
null
null
// // group.cc: // #include <stdio.h> #include <stdlib.h> #include <math.h> #include <limits.h> #include <X11/Xlib.h> #include <local_types.h> #include <list.h> #include <eedefs.h> #include <shape.h> #include <shapeset.h> #include <frame.h> #include <xcontext.h> #include <board.h> #include <group.h> #include <misc.h> #include <geometry.h> #include <xfig.h> // // コンストラクタ // Group::Group( Board* board ): Shape( board ) { shape_type = ST_GROUP; _x = _y = _w = _h = 0; } // // コピーコンストラクタ // Group::Group( Group* group ): Shape( group ) { _x = group->_x, _y = group->_y; _w = group->_w, _h = group->_h; for( int i = 0 ; i < group->shape_slot.count() ; i++ ) shape_slot.append( group->shape_slot.get(i)->duplicate() ); } // // draw(): // void Group::draw( Window window, int x, int y ) { Display* dpy = board->xcontext->get_dpy(); GC gc = board->gc; int save_gp_draw_f = board->grip_disp; board->grip_disp = False; for( int i = 0 ; i < shape_slot.count() ; i++ ) shape_slot.get(i)->draw( window, ROUND(_x)+x, ROUND(_y)+y ); board->grip_disp = save_gp_draw_f; int left = ROUND(_x) + x - 3; int right = ROUND(_x) + ROUND(_w) + x - 3; int up = ROUND(_y) + y - 3; int down = ROUND(_y) + ROUND(_h) + y - 3; XDrawRectangle( dpy, window, gc, left, up, 5, 5 ); XDrawRectangle( dpy, window, gc, right, up, 5, 5 ); XDrawRectangle( dpy, window, gc, left, down, 5, 5 ); XDrawRectangle( dpy, window, gc, right, down, 5, 5 ); } // // hit(): // Boolean Group::hit( int x, int y, int hw ) { int left = ROUND(_x); int right = ROUND(_x) + ROUND(_w); int up = ROUND(_y); int down = ROUND(_y) + ROUND(_h); if( contain_chk( left, up, x, y, hw ) ) return True; if( contain_chk( right, up, x, y, hw ) ) return True; if(contain_chk( right, down, x, y, hw ) ) return True; if( contain_chk( left, down, x, y, hw ) ) return True; return False; } // // layout(): // EditResult Group::layout( XEvent* event ) { Display* dpy = event->xany.display; XSetFunction( dpy, board->gc, GXset ); XSetPlaneMask( dpy, board->gc, board->layout_mask ); static int last_x = -1, last_y; if( event->type == MotionNotify && proc_phase > 0 ){ int mx = event->xmotion.x, my = event->xmotion.y; board->quontize( mx, my ); if( last_x != mx || last_y != my ){ if( last_x >= 0 ){ XSetFunction( dpy, board->gc, GXclear ); int x1 = ROUND(_x), y1 = ROUND(_y), x2 = last_x, y2 = last_y; normal_rect( x1, y1, x2, y2 ); XDrawRectangle( dpy, event->xmotion.window, board->gc, x1, y1, x2-x1, y2-y1 ); XSetFunction( dpy, board->gc, GXset ); } int x1 = ROUND(_x), y1 = ROUND(_y), x2 = mx, y2 = my; normal_rect( x1, y1, x2, y2 ); XDrawRectangle( dpy, event->xmotion.window, board->gc, x1, y1, x2-x1, y2-y1 ); last_x = mx, last_y = my; } XSetFunction( dpy, board->gc, GXcopy ); XSetPlaneMask( dpy, board->gc, ~0 ); return EDIT_CONTINUE; } switch( proc_phase ){ case 0: // 一回目のクリック。 if( event->type != ButtonPress && event->xbutton.button != 1 ) return EDIT_CONTINUE; Window window = event->xbutton.window; int mx = event->xbutton.x, my = event->xbutton.y; board->quontize( mx, my ); _x = (double)mx, _y = (double)my; last_x = -1; proc_phase = 1; return EDIT_CONTINUE; break; case 1: // 二回目のクリック。 if( event->type != ButtonPress ) return EDIT_CONTINUE; window = event->xbutton.window; switch( event->xbutton.button ){ case 1: // 左ボタン矩形の確定。 mx = event->xbutton.x, my = event->xbutton.y; board->quontize( mx, my ); if( ROUND(_x) == mx && ROUND(_y) == my ){ XBell( dpy, 0 ); XSetFunction( dpy, board->gc, GXcopy ); XSetPlaneMask( dpy, board->gc, ~0 ); return EDIT_CONTINUE; } if( last_x >= 0 ){ XSetFunction( dpy, board->gc, GXclear ); int x1 = ROUND(_x), y1 = ROUND(_y), x2 = last_x, y2 = last_y; normal_rect( x1, y1, x2, y2 ); XDrawRectangle( dpy, event->xmotion.window, board->gc, x1, y1, x2-x1, y2-y1 ); XSetFunction( dpy, board->gc, GXset ); } int x1, x2, y1, y2; x1 = ROUND(_x), y1 = ROUND(_y), x2 = mx, y2 = my; normal_rect( x1, y1, x2, y2 ); _x = x1, _y = y1, _w = x2 - x1 - 1, _h = y2 - y1 - 1; for( int i = board->shapeset.count_shape()-1 ; i >= 0 ; i-- ){ Shape* shape = board->shapeset.get_shape(i); if( shape->contain( ROUND(_x), ROUND(_y), ROUND(_w), ROUND(_h) ) ){ shape_slot.append( shape->duplicate() ); XSetFunction( dpy, board->gc, GXclear ); XSetPlaneMask( dpy, board->gc, board->shape_mask ); shape->draw( event->xbutton.window, 0, 0 ); board->shapeset.unlink_shape( LIST_TOP, i, 1 ); } } if( shape_slot.count() == 0 ){ last_x = -1; proc_phase = 0; XSetFunction( dpy, board->gc, GXcopy ); XSetPlaneMask( dpy, board->gc, ~0 ); return EDIT_CANCEL; } double min_x=INT_MAX, min_y=INT_MAX, max_x=INT_MIN, max_y=INT_MIN; for( i = 0 ; i < shape_slot.count() ; i++ ){ Shape* shape = shape_slot.get(i); double x, y, w, h; shape->bound( x, y, w, h ); if( x < min_x ) min_x = x; if( x+w > max_x ) max_x = x+w; if( y < min_y ) min_y = y; if( y+h > max_y ) max_y = y+h; } _x = min_x, _y = min_y, _w = max_x - min_x, _h = max_y - min_y; for( i = 0 ; i < shape_slot.count() ; i++ ) shape_slot.get(i)->translate( -_x, -_y ); XSetFunction( dpy, board->gc, GXset ); XSetPlaneMask( dpy, board->gc, board->shape_mask ); draw( window, 0, 0 ); last_x = -1; proc_phase = 0; XSetFunction( dpy, board->gc, GXcopy ); XSetPlaneMask( dpy, board->gc, ~0 ); return EDIT_COMPLETE; break; case 3: // 右ボタン(キャンセル) if( last_x >= 0 ){ XSetFunction( dpy, board->gc, GXclear ); XSetPlaneMask( dpy, board->gc, board->layout_mask ); int x1 = ROUND(_x), y1 = ROUND(_y), x2 = last_x, y2 = last_y; normal_rect( x1, y1, x2, y2 ); XDrawRectangle( dpy, event->xmotion.window, board->gc, x1, y1, x2-x1, y2-y1 ); } last_x = -1; proc_phase = 0; XSetFunction( dpy, board->gc, GXcopy ); XSetPlaneMask( dpy, board->gc, ~0 ); return EDIT_CANCEL; break; } break; } return EDIT_CONTINUE; } // // save(): // void Group::save( FILE* fp ) { fprintf( fp, "group{\n" ); fprintf( fp, " geom = (%g,%g,%g,%g);\n", _x, _y, _w, _h ); for( int i = 0 ; i < shape_slot.count() ; i++ ) shape_slot.get(i)->save( fp ); fprintf( fp, "}\n" ); } // // tex(): // void Group::tex( FILE* fp, double h, double x, double y ) { for( int i = 0 ; i < shape_slot.count() ; i++ ) shape_slot.get(i)->tex( fp, h, _x+x, _y+y ); } // // bound(): // void Group::bound( double& x, double& y, double& w, double& h ) { double min_x = INT_MAX, min_y = INT_MAX, max_x = INT_MIN, max_y = INT_MIN; for( int i = 0 ; i < shape_slot.count() ; i++ ){ Shape* shape = shape_slot.get(i); double x, y, w, h; shape->bound( x, y, w, h ); if( x < min_x ) min_x = x; if( x+w > max_x ) max_x = x+w; if( y < min_y ) min_y = y; if( y+h > max_y ) max_y = y+h; } _w = max_x - min_x, _h = max_y - min_y; x = _x, y = _y; w = _w, h = _h; } // // translate(): // void Group::translate( double x, double y ) { _x += x, _y += y; } // // duplicate(): // Shape* Group::duplicate() { return new Group( this ); } // // contain(): // Boolean Group::contain( int x, int y, int w, int h ) { if( ROUND(_x) < x || ROUND(_x+_w) >= x+w ) return False; if( ROUND(_y) < y || ROUND(_y+_h) >= y+h ) return False; return True; } // // scale(): // void Group::scale( double rx, double ry ) { _x *= rx, _y *= ry; _w *= rx, _h *= ry; for( int i = 0 ; i < shape_slot.count() ; i++ ) shape_slot.get(i)->scale( rx, ry ); } // // リサイズ // EditResult Group::resize( XEvent* event ) { Display* dpy = event->xany.display; XSetFunction( dpy, board->gc, GXset ); XSetPlaneMask( dpy, board->gc, board->layout_mask ); static int last_x = -1, last_y; static int xx, yy; if( proc_phase == 1 && event->type == MotionNotify ){ int mx = event->xmotion.x, my = event->xmotion.y; board->quontize( mx, my ); if( last_x == mx && last_y == my ){ XSetFunction( dpy, board->gc, GXcopy ); XSetPlaneMask( dpy, board->gc, ~0 ); return EDIT_CONTINUE; } int x1 = xx, y1 = yy, x2 = last_x, y2 = last_y; normal_rect( x1, y1, x2, y2 ); if( last_x > 0 ){ XSetFunction( dpy, board->gc, GXclear ); XDrawRectangle( dpy, event->xbutton.window, board->gc, x1, y1, x2-x1-1, y2-y1-1 ); XSetFunction( dpy, board->gc, GXset ); } x1 = xx, y1 = yy, x2 = mx, y2 = my; normal_rect( x1, y1, x2, y2 ); XDrawRectangle( dpy, event->xbutton.window, board->gc, x1, y1, x2-x1-1, y2-y1-1 ); last_x = mx, last_y = my; XSetFunction( dpy, board->gc, GXcopy ); XSetPlaneMask( dpy, board->gc, ~0 ); return EDIT_CONTINUE; } switch( proc_phase ){ case 0: int mx = event->xbutton.x, my = event->xbutton.y; board->quontize( mx, my ); xx = ROUND(_x), yy = ROUND(_y+_h)-1; if( contain_chk( ROUND(_x+_w)-1, ROUND(_y+_h)-1, mx, my, 4 ) ) xx = ROUND(_x), yy = ROUND(_y); if( contain_chk( ROUND(_x), ROUND(_y+_h)-1, mx, my, 4 ) ) xx = ROUND(_x+_w)-1, yy = ROUND(_y); if( contain_chk( ROUND(_x), ROUND(_y), mx, my, 4 ) ) xx = ROUND(_x+_w)-1, yy = ROUND(_y+_h)-1; last_x = -1; proc_phase = 1; XSetFunction( dpy, board->gc, GXcopy ); XSetPlaneMask( dpy, board->gc, ~0 ); return EDIT_CONTINUE; break; case 1: if( event->type != ButtonPress ){ XSetFunction( dpy, board->gc, GXcopy ); XSetPlaneMask( dpy, board->gc, ~0 ); return EDIT_CONTINUE; } mx = event->xbutton.x, my = event->xbutton.y; board->quontize( mx, my ); switch( event->xbutton.button ){ case 1: // 左ボタン(決定) if( last_x < 0 || ( xx == last_x && yy == last_y ) ){ XBell( dpy, 0 ); XSetFunction( dpy, board->gc, GXcopy ); XSetPlaneMask( dpy, board->gc, ~0 ); return EDIT_CONTINUE; } int x1 = xx, y1 = yy, x2 = last_x, y2 = last_y; normal_rect( x1, y1, x2, y2 ); XSetFunction( dpy, board->gc, GXclear ); XDrawRectangle( dpy, event->xbutton.window, board->gc, x1, y1, x2-x1-1, y2-y1-1 ); XSetPlaneMask( dpy, board->gc, board->shape_mask ); draw( event->xbutton.window, 0, 0 ); scale( (double)(x2-x1-1)/_w, (double)(y2-y1-1)/_h ); _x = (double)x1, _y = (double)y1; XSetFunction( dpy, board->gc, GXset ); draw( event->xbutton.window, 0, 0 ); proc_phase = 0; XSetFunction( dpy, board->gc, GXcopy ); XSetPlaneMask( dpy, board->gc, ~0 ); return EDIT_COMPLETE; break; case 3: // 右ボタン(キャンセル) if( last_x > 0 ){ XSetFunction( dpy, board->gc, GXxor ); x1 = xx, y1 = yy, x2 = last_x, y2 = last_y; normal_rect( x1, y1, x2, y2 ); XSetFunction( dpy, board->gc, GXclear ); XDrawRectangle( dpy, event->xbutton.window, board->gc, x1, y1, x2-x1-1, y2-y1-1 ); } proc_phase = 0; XSetFunction( dpy, board->gc, GXcopy ); XSetPlaneMask( dpy, board->gc, ~0 ); return EDIT_CANCEL; break; } } return EDIT_CONTINUE; } // // reversx(): // void Group::reversx() { double bx, by, bw, bh; bound( bx, by, bw, bh ); for( int i = 0 ; i < shape_slot.count() ; i++ ){ double sx, sy, sw, sh; Shape* shape = shape_slot.get(i); shape->bound( sx, sy, sw, sh ); shape->translate( -sx, 0 ); shape->translate( bw, 0 ); shape->translate( -(sx+sw), 0 ); shape->reversx(); } } // // reversy(): // void Group::reversy() { double bx, by, bw, bh; bound( bx, by, bw, bh ); for( int i = 0 ; i < shape_slot.count() ; i++ ){ double sx, sy, sw, sh; Shape* shape = shape_slot.get(i); shape->bound( sx, sy, sw, sh ); shape->translate( 0, -sy ); shape->translate( 0, bh ); shape->translate( 0, -(sy+sh) ); shape->reversy(); } } // // update(): // void Group::update() { for( int i = 0 ; i < shape_slot.count() ; i++ ) shape_slot.get(i)->update(); double x, y, w, h; bound( x, y, w, h ); _w = w, _h = h; } // // xfig(): // void Group::xfig( FILE* fp, double x, double y ) { fprintf( fp, "%d %d %d %d %d\n", O_COMPOUND, ROUND(XFS(_x+x)), ROUND(XFS(_y+y)), ROUND(XFS(_x+_w+x)), ROUND(XFS(_y+_h+y)) ); for( int i = 0 ; i < shape_slot.count() ; i++ ) shape_slot.get(i)->xfig( fp, _x+x, _y+y ); fprintf( fp, "%d\n", O_END_COMPOUND ); } // // ungroup(): // void Group::ungroup( Window window ) { XSetPlaneMask( board->xcontext->get_dpy(), board->gc, board->shape_mask ); XSetFunction( board->xcontext->get_dpy(), board->gc, GXclear ); draw( window, 0, 0 ); XSetFunction( board->xcontext->get_dpy(), board->gc, GXset ); for( int j = 0 ; j < shape_slot.count() ; j++ ){ Shape* dup_shape = shape_slot.get(j)->duplicate(); dup_shape->translate( _x, _y ); dup_shape->draw( window, 0, 0 ); board->shapeset.append_shape( dup_shape ); } XSetFunction( board->xcontext->get_dpy(), board->gc, GXcopy ); XSetPlaneMask( board->xcontext->get_dpy(), board->gc, ~0 ); } // // rotate(): // void Group::rotate( XEvent* event ) { for( int i = 0 ; i < shape_slot.count() ; i++ ){ Shape* shape = shape_slot.get(i); shape->translate( _x, _y ); shape->rotate( event ); shape->translate( -_x, -_y ); } double min_x = INT_MAX, min_y = INT_MAX, max_x = INT_MIN, max_y = INT_MIN; for( i = 0 ; i < shape_slot.count() ; i++ ){ Shape* shape = shape_slot.get(i); double x, y, w, h; shape->bound( x, y, w, h ); if( x < min_x ) min_x = x; if( x+w > max_x ) max_x = x+w; if( y < min_y ) min_y = y; if( y+h > max_y ) max_y = y+h; } _x += min_x, _y += min_y; _w = max_x-min_x, _h = max_y-min_y; if( min_x != 0 || min_y != 0 ) for( i = 0 ; i < shape_slot.count() ; i++ ) shape_slot.get(i)->translate( -min_x, -min_y ); }
27.323587
76
0.565528
flipfrog
b1139ee33a58eb303c57e0999ee83ddb86828258
14,525
cpp
C++
tests/src/test_sparse_gemm_indexed.cpp
vishalbelsare/smallk
f0472b089ea3f594a26eb31c29d522a9d256829f
[ "Apache-2.0" ]
43
2015-02-02T06:23:52.000Z
2020-09-21T19:59:24.000Z
tests/src/test_sparse_gemm_indexed.cpp
vishalbelsare/smallk
f0472b089ea3f594a26eb31c29d522a9d256829f
[ "Apache-2.0" ]
6
2015-10-27T18:05:05.000Z
2016-11-30T18:33:59.000Z
tests/src/test_sparse_gemm_indexed.cpp
vishalbelsare/smallk
f0472b089ea3f594a26eb31c29d522a9d256829f
[ "Apache-2.0" ]
14
2015-10-27T21:22:19.000Z
2020-02-06T17:15:45.000Z
#include <iostream> #include <thread> #include "elemental.hpp" #include "sparse_matrix.hpp" #include "matrix_generator.hpp" #include "delimited_file.hpp" #include "index_set.hpp" #include "random.hpp" #include "timer.hpp" using std::cout; using std::cerr; using std::endl; // For the NMF formulation A~WH, we need the products AH' and W'A. bool SimpleTest(Random& rng); bool TestSparseGemmIndexedABt_Rank2 (Random& rng); bool TestSparseGemmIndexedBtA_Rank2 (Random& rng); namespace GemmIndexedTest { const unsigned int NUM_RUNS = 64; const double MAX_ACCEPTABLE_FNORM = 1.0e-10; const unsigned int MAX_DIM = 8192; } //----------------------------------------------------------------------------- bool TestSparseGemmIndexed() { Random rng; rng.SeedFromTime(); bool result0 = SimpleTest(rng); //bool result1 = TestSparseGemmIndexedAB(rng); bool result2 = TestSparseGemmIndexedABt_Rank2(rng); //bool result3 = TestSparseGemmIndexedBA(rng); bool result4 = TestSparseGemmIndexedBtA_Rank2(rng); return (result0 && result2 && result4); } //----------------------------------------------------------------------------- bool SimpleTest(Random& rng) { cout << "Running SimpleTest..."; cout.flush(); // A = 1 0 0 0 H = 1 2 3 4 == W' // 0 2 0 0 5 6 7 8 // 0 0 3 0 // 1 2 3 4 SparseMatrix<double> A(4, 4, 7); A.BeginLoad(); A.Load(0, 0, 1.0); A.Load(3, 0, 1.0); A.Load(1, 1, 2.0); A.Load(3, 1, 2.0); A.Load(2, 2, 3.0); A.Load(3, 2, 3.0); A.Load(3, 3, 4.0); A.EndLoad(); elem::Matrix<double> H(2, 4); H.Set(0, 0, 1.0); H.Set(0, 1, 2.0); H.Set(0, 2, 3.0); H.Set(0, 3, 4.0); H.Set(1, 0, 5.0); H.Set(1, 1, 6.0); H.Set(1, 2, 7.0); H.Set(1, 3, 8.0); elem::Matrix<double> W(4, 2); W.Set(0, 0, 1.0); W.Set(0, 1, 5.0); W.Set(1, 0, 2.0); W.Set(1, 1, 6.0); W.Set(2, 0, 3.0); W.Set(2, 1, 7.0); W.Set(3, 0, 4.0); W.Set(3, 1, 8.0); elem::Matrix<double> C1(2, 2), C2(2, 2); std::vector<unsigned int> col_indices = {1, 3}; std::vector<unsigned int> old_to_new_rows = {0xFFFFFFFF, 0, 0xFFFFFFFF, 1}; std::vector<unsigned int> new_to_old_rows = {1, 3}; unsigned int max_threads = 1; elem::Matrix<double> Hsubset(2, 2); Hsubset.Set(0, 0, H.Get(0, col_indices[0])); Hsubset.Set(0, 1, H.Get(0, col_indices[1])); Hsubset.Set(1, 0, H.Get(1, col_indices[0])); Hsubset.Set(1, 1, H.Get(1, col_indices[1])); //cout << "\nHsubset: " << endl; //elem::Print(Hsubset); elem::Matrix<double> Wsubset(2, 2); Wsubset.Set(0, 0, W.Get(new_to_old_rows[0], 0)); Wsubset.Set(0, 1, W.Get(new_to_old_rows[0], 1)); Wsubset.Set(1, 0, W.Get(new_to_old_rows[1], 0)); Wsubset.Set(1, 1, W.Get(new_to_old_rows[1], 1)); //cout << "\nWsubset: " << endl; //elem::Print(Wsubset); // compute the product C1 = AHsubset' = 4 12 // 20 44 GemmIndexed(NORMAL, TRANSPOSE, 1.0, A, Hsubset, 0.0, C1, max_threads, new_to_old_rows.size(), old_to_new_rows, col_indices); //cout << "\nC1: " << endl; //elem::Print(C1); bool ok1 = (4.0 == C1.Get(0, 0)) && (12.0 == C1.Get(0, 1)) && (20.0 == C1.Get(1, 0)) && (44.0 == C1.Get(1, 1)); // compute the product C2 = Wsubset'A = 5 12 // 13 24 GemmIndexed(TRANSPOSE, NORMAL, 1.0, Wsubset, A, 0.0, C2, max_threads, new_to_old_rows.size(), old_to_new_rows, col_indices); //cout << "\nC2: " << endl; //elem::Print(C2); bool ok2 = (12.0 == C2.Get(0, 0)) && (16.0 == C2.Get(0, 1)) && (28.0 == C2.Get(1, 0)) && (32.0 == C2.Get(1, 1)); cout << ( (ok1 && ok2) ? "passed." : "failed.") << endl; return (ok1 && ok2); } //----------------------------------------------------------------------------- bool TestSparseGemmIndexedABt_Rank2(Random& rng) { // C = alpha*A*B' + beta*C // // Matrix A is sparse and is mxn, but use s cols from col index set S. // Matrix B has 2 rows; matrix C has 2 cols. Timer timer; unsigned int max_threads = 2; SparseMatrix<double> A, Asubset; elem::Matrix<double> B, Bsubset, C1, C2, C1subset, C2subset; double min_sparsity = 1.0, max_sparsity = 0.0; double max_norm = 0.0, elapsed_subset = 0.0, elapsed_indexed = 0.0; cout << "Running indexed GEMM rank2 AB' test..." << endl; for (unsigned int i=0; i<GemmIndexedTest::NUM_RUNS; ++i) { unsigned int height_a = rng.RandomRangeInt(512, GemmIndexedTest::MAX_DIM); unsigned int width_a = rng.RandomRangeInt(512, GemmIndexedTest::MAX_DIM); // sparse_fraction ranges from (0.1 - 0.09, 0.1 + 0.09) double sparse_fraction = rng.RandomDouble(0.1, 0.09); unsigned int nonzeros_per_col = sparse_fraction * height_a; if (0 == nonzeros_per_col) nonzeros_per_col = 1; if (sparse_fraction < min_sparsity) min_sparsity = sparse_fraction; if (sparse_fraction > max_sparsity) max_sparsity = sparse_fraction; // generate a random alpha and beta on [-1, 1] double alpha = rng.RandomDouble(0.0, 1.0); double beta = rng.RandomDouble(0.0, 1.0); RandomSparseMatrix(A, nonzeros_per_col, rng, height_a, width_a); // set the dimensions of B and randomly initialize B.ResizeTo(2, width_a); RandomMatrix(B, rng); // set the dimensions of C1 and C2 and randomly initialize C1.ResizeTo(height_a, 2); RandomMatrix(C1, rng); C2 = C1; // generate a random set of column indices of A size_t index_set_size = rng.RandomRangeInt(1, width_a/2); std::vector<unsigned int> col_indices(index_set_size); RandomIndexSet(rng, width_a, index_set_size, col_indices); // compute the height of the most compact submatrix of A std::vector<unsigned int> old_to_new_rows, new_to_old_rows; A.SubMatrixRowsCompact(col_indices, old_to_new_rows, new_to_old_rows); unsigned int new_height = new_to_old_rows.size(); // resize Bsubset and Csubset to match Bsubset.ResizeTo(2, index_set_size); C1subset.ResizeTo(new_height, 2); C2subset = C1subset; // extract Bsubset from B (cols of B from index set) for (unsigned int c=0; c<index_set_size; ++c) { for (int r=0; r<Bsubset.Height(); ++r) { double val = B.Get(r, col_indices[c]); Bsubset.Set(r, c, val); } } old_to_new_rows.clear(); new_to_old_rows.clear(); timer.Start(); // extract a compact submatrix of A using the columns in col_indices A.SubMatrixColsCompact(Asubset, col_indices, old_to_new_rows, new_to_old_rows); assert(Asubset.Height() == new_height); // perform sparse Gemm on the subset Gemm(NORMAL, TRANSPOSE, alpha, Asubset, Bsubset, beta, C1subset, max_threads); timer.Stop(); elapsed_subset += timer.ReportMicroseconds(); timer.Start(); // perform indexed Gemm on the original matrix GemmIndexed(NORMAL, TRANSPOSE, alpha, A, Bsubset, beta, C2subset, max_threads, new_height, old_to_new_rows, col_indices); timer.Stop(); elapsed_indexed += timer.ReportMicroseconds(); // check residuals // C2 = -C1 + C2 elem::Axpy(-1.0, C1subset, C2subset); double fnorm = elem::Norm(C2subset, elem::FROBENIUS_NORM); cout << "\t[" << (i+1) << "/" << GemmIndexedTest::NUM_RUNS << "]: fnorm of residual: " << fnorm << endl; if (fnorm > max_norm) max_norm = fnorm; if (max_norm > GemmIndexedTest::MAX_ACCEPTABLE_FNORM) { cerr << "*** ERROR ***" << endl; //WriteDelimitedFile(D.LockedBuffer(), D.LDim(), D.Height(), D.Width(), "Derror.csv", 6); //WriteDelimitedFile(B.LockedBuffer(), B.LDim(), B.Height(), B.Width(), "Berror.csv", 6); break; } } // compute average runtimes per loop double t_copying = elapsed_subset * 0.001 / GemmIndexedTest::NUM_RUNS; double t_indexed = elapsed_indexed * 0.001 / GemmIndexedTest::NUM_RUNS; cout << endl; cout << "\t**** Results for Rank2 Indexed Sparse Gemm AB' Test ****" << endl; cout << endl; cout << "\t\t" << GemmIndexedTest::NUM_RUNS << " runs " << endl; cout << "\t\tMax residual Frobenius norm: " << max_norm << endl; cout << "\t\tElapsed time with data copying:\t" << t_copying << " ms." << endl; cout << "\t\tElapsed time with indexing:\t" << t_indexed << " ms." << endl; cout << endl; cout << "\t********************************************************" << endl; cout << endl; return (max_norm < GemmIndexedTest::MAX_ACCEPTABLE_FNORM); } //----------------------------------------------------------------------------- bool TestSparseGemmIndexedBtA_Rank2(Random& rng) { // C = alpha*B'*A + beta*C // // Matrix A is sparse and is mxn, but use s cols from col index set S. // Matrix B has 2 cols; matrix C has 2 rows. Timer timer; unsigned int hw_max_threads = std::thread::hardware_concurrency(); SparseMatrix<double> A, Asubset; elem::Matrix<double> B, Bsubset, C1, C2, C1subset, C2subset, D; // this variant of indexed gemm requires beta == 0 double beta = 0.0; double min_sparsity = 1.0, max_sparsity = 0.0; double max_norm = 0.0, elapsed_subset = 0.0, elapsed_indexed = 0.0; cout << "Running indexed GEMM rank2 B'A test..." << endl; for (unsigned int i=0; i<GemmIndexedTest::NUM_RUNS; ++i) { unsigned int height_a = rng.RandomRangeInt(512, GemmIndexedTest::MAX_DIM); unsigned int width_a = rng.RandomRangeInt(512, GemmIndexedTest::MAX_DIM); unsigned int max_threads = 1 + (rng.RandomInt() % hw_max_threads); // sparse_fraction ranges from (0.1 - 0.09, 0.1 + 0.09) double sparse_fraction = rng.RandomDouble(0.1, 0.09); unsigned int nonzeros_per_col = sparse_fraction * height_a; if (0 == nonzeros_per_col) nonzeros_per_col = 1; if (sparse_fraction < min_sparsity) min_sparsity = sparse_fraction; if (sparse_fraction > max_sparsity) max_sparsity = sparse_fraction; // generate a random alpha on [-1, 1] double alpha = rng.RandomDouble(0.0, 1.0); RandomSparseMatrix(A, nonzeros_per_col, rng, height_a, width_a); // set the dimensions of B and randomly initialize B.ResizeTo(height_a, 2); RandomMatrix(B, rng); // set the dimensions of C1 and C2 and randomly initialize C1.ResizeTo(2, width_a); RandomMatrix(C1, rng); C2 = C1; // generate a random set of column indices of A size_t index_set_size = rng.RandomRangeInt(1, width_a/2); // force rank2 some of the time if (0 == (i % 3)) index_set_size = 2; std::vector<unsigned int> col_indices(index_set_size); RandomIndexSet(rng, width_a, index_set_size, col_indices); // compute the height of the most compact submatrix of A std::vector<unsigned int> old_to_new_rows, new_to_old_rows; A.SubMatrixRowsCompact(col_indices, old_to_new_rows, new_to_old_rows); unsigned int new_height = new_to_old_rows.size(); // resize Bsubset and Csubset to match Bsubset.ResizeTo(new_height, 2); C1subset.ResizeTo(2, index_set_size); C2subset = C1subset; // extract B subset from B for (int c=0; c != Bsubset.Width(); ++c) { for (int r=0; r != Bsubset.Height(); ++r) { double val = B.Get(new_to_old_rows[r], c); Bsubset.Set(r, c, val); } } old_to_new_rows.clear(); new_to_old_rows.clear(); timer.Start(); // extract a submatrix of A using the columns in col_indices A.SubMatrixColsCompact(Asubset, col_indices, old_to_new_rows, new_to_old_rows); assert(Asubset.Height() == new_height); // perform sparse Gemm on the subset Gemm(TRANSPOSE, NORMAL, alpha, Bsubset, Asubset, beta, C1subset, max_threads); timer.Stop(); elapsed_subset += timer.ReportMicroseconds(); timer.Start(); // perform indexed Gemm GemmIndexed(TRANSPOSE, NORMAL, alpha, Bsubset, A, beta, C2subset, max_threads, new_height, old_to_new_rows, col_indices); timer.Stop(); elapsed_indexed += timer.ReportMicroseconds(); // check residuals // C2 = -C1 + C2 elem::Axpy(-1.0, C1subset, C2subset); double fnorm = elem::Norm(C2subset, elem::FROBENIUS_NORM); cout << "\t[" << (i+1) << "/" << GemmIndexedTest::NUM_RUNS << "]: fnorm of residual: " << fnorm << endl; if (fnorm > max_norm) max_norm = fnorm; if (max_norm > GemmIndexedTest::MAX_ACCEPTABLE_FNORM) { cerr << "*** ERROR ***" << endl; //WriteDelimitedFile(D.LockedBuffer(), D.LDim(), D.Height(), D.Width(), "Derror.csv", 6); //WriteDelimitedFile(B.LockedBuffer(), B.LDim(), B.Height(), B.Width(), "Berror.csv", 6); break; } } // compute average runtimes per loop double t_copying = elapsed_subset * 0.001 / GemmIndexedTest::NUM_RUNS; double t_indexed = elapsed_indexed * 0.001 / GemmIndexedTest::NUM_RUNS; cout << endl; cout << "\t**** Results for Rank2 Indexed Sparse Gemm B'A Test ****" << endl; cout << endl; cout << "\t\t" << GemmIndexedTest::NUM_RUNS << " runs " << endl; cout << "\t\tMax residual Frobenius norm: " << max_norm << endl; cout << "\t\tElapsed time with data copying:\t" << t_copying << " ms." << endl; cout << "\t\tElapsed time with indexing:\t" << t_indexed << " ms." << endl; cout << endl; cout << "\t********************************************************" << endl; cout << endl; return (max_norm < GemmIndexedTest::MAX_ACCEPTABLE_FNORM); }
35.426829
101
0.566265
vishalbelsare
b1153499bdc65651dcf77225f6d8b3ec159f7561
2,722
cpp
C++
src/testing.cpp
tcpcloud/debian-cassandra-cpp-driver
ad8e5b713dc8501620c890ba090963bb7b12de69
[ "Apache-2.0" ]
1
2021-12-18T04:23:26.000Z
2021-12-18T04:23:26.000Z
src/testing.cpp
tcpcloud/debian-cassandra-cpp-driver
ad8e5b713dc8501620c890ba090963bb7b12de69
[ "Apache-2.0" ]
1
2021-08-20T19:03:52.000Z
2021-08-20T19:03:52.000Z
src/testing.cpp
tcpcloud/debian-cassandra-cpp-driver
ad8e5b713dc8501620c890ba090963bb7b12de69
[ "Apache-2.0" ]
5
2016-05-03T15:53:22.000Z
2021-08-20T19:03:08.000Z
/* Copyright (c) 2014-2016 DataStax 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 "testing.hpp" #include "address.hpp" #include "get_time.hpp" #include "logger.hpp" #include "metadata.hpp" #include "murmur3.hpp" #include "result_response.hpp" #include "external_types.hpp" namespace cass { std::string get_host_from_future(CassFuture* future) { if (future->type() != cass::CASS_FUTURE_TYPE_RESPONSE) { return ""; } cass::ResponseFuture* response_future = static_cast<cass::ResponseFuture*>(future->from()); return response_future->get_host_address().to_string(); } unsigned get_connect_timeout_from_cluster(CassCluster* cluster) { return cluster->config().connect_timeout_ms(); } int get_port_from_cluster(CassCluster* cluster) { return cluster->config().port(); } std::string get_contact_points_from_cluster(CassCluster* cluster) { std::string str; const ContactPointList& contact_points = cluster->config().contact_points(); for (ContactPointList::const_iterator it = contact_points.begin(), end = contact_points.end(); it != end; ++it) { if (str.size() > 0) { str.push_back(','); } str.append(*it); } return str; } std::vector<std::string> get_user_data_type_field_names(const CassSchemaMeta* schema_meta, const std::string& keyspace, const std::string& udt_name) { std::vector<std::string> udt_field_names; if (schema_meta) { const cass::UserType* udt = schema_meta->get_user_type(keyspace, udt_name); if (udt) { for (cass::UserType::FieldVec::const_iterator it = udt->fields().begin(); it != udt->fields().end(); ++it) { udt_field_names.push_back((*it).name); } } } return udt_field_names; } int64_t create_murmur3_hash_from_string(const std::string &value) { return MurmurHash3_x64_128(value.data(), value.size(), 0); } uint64_t get_time_since_epoch_in_ms() { return cass::get_time_since_epoch_ms(); } uint64_t get_host_latency_average(CassSession* session, std::string ip_address, int port) { Address address; if (Address::from_string(ip_address, port, &address)) { return session->get_host(address)->get_current_average().average; } return 0; } } // namespace cass
28.652632
150
0.719324
tcpcloud
b117206c49426f5c8b2342a2d5174b9b4f49ee5b
14,895
cpp
C++
src/ADBSCEditDLL/src/WinClass/ToolBar/ToolBar.cpp
ClnViewer/ADB-Android-Viewer
c619fe626ab390b656893974700a0b6379159c03
[ "MIT" ]
9
2019-05-20T12:06:36.000Z
2022-03-24T19:11:06.000Z
src/ADBSCEditDLL/src/WinClass/ToolBar/ToolBar.cpp
ClnViewer/ADB-Android-Viewer
c619fe626ab390b656893974700a0b6379159c03
[ "MIT" ]
null
null
null
src/ADBSCEditDLL/src/WinClass/ToolBar/ToolBar.cpp
ClnViewer/ADB-Android-Viewer
c619fe626ab390b656893974700a0b6379159c03
[ "MIT" ]
3
2020-07-06T04:51:33.000Z
2021-07-26T20:08:02.000Z
/* MIT License Android remote Viewer, GUI ADB tools Android Viewer developed to view and control your android device from a PC. ADB exchange Android Viewer, support scale view, input tap from mouse, input swipe from keyboard, save/copy screenshot, etc.. Copyright (c) 2016-2019 PS GitHub: https://github.com/ClnViewer/ADB-Android-Viewer GitHub: https://github.com/ClnViewer/ADB-Android-Viewer/ADBSCEditDLL/ADBSCEdit Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sub license, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "../../SCEditInternal.h" #include <commctrl.h> namespace Editor { struct TBChangeButton { int32_t btnidx, cmdcur, cmdnew, imgidx, state; }; ToolBar::ToolBar() { Base::m_data = data(); } void ToolBar::show() { if (!Base::m_data.window) return; // Base::refresh(m_rebar.gethandle()); Base::refresh(Base::m_data.window); } MDIWin::WinData ToolBar::data() { MDIWin::WinData d( MDIWin::BaseData::MDIWinType::MWTYPE_TOOLBAR, // MDIWinType group MDIWin::BaseData::MDIWinType::MWTYPE_TOOLBAR, // MDIWinType type MDIWin::BaseData::MDIWinStyle::MWSTYLE_NONE, // MDIWinStyle std::string(), // Class name std::string(), // Title 0, 0 ); d.irdefault.set<int32_t>(0, 0, 0, 0); // % from main widow return d; } bool ToolBar::event_sizeinitBegin(ImageLite::IRECT<int32_t> const & ir) { do { if ((!Base::m_data.window) || (ir.w <= 0)) break; Base::m_data.irsize.set<int32_t>( 0, 0, ir.w - 150, (getsizebtn_() + 4) ); if (Base::m_data.irsize.empty()) break; Base::refresh(SWP_NOMOVE); } while (0); return true; } void ToolBar::event_size(ImageLite::IRECT<int32_t> const & irc, ImageLite::IRECT<int32_t> const &) { Base::m_data.irsize.set<int32_t>( 0, 0, ((irc.w <= 0) ? Base::m_data.irsize.w : irc.w), Base::m_data.irsize.h ); Base::resize(); } void ToolBar::event_resize() { RECT rc{}; HWND hwnd = m_rebar.gethandle(); if (!hwnd) hwnd = Base::m_data.window; if (!::GetClientRect(hwnd, &rc)) return; Base::m_data.irsize.set<int32_t>( 0, 0, rc.right, rc.bottom ); } std::tuple<bool, bool> ToolBar::event_initBegin() { try { Base::m_data.irsize = {}; do { if (!m_rebar.init(Base::m_data.wparent)) break; if (!m_search.init( m_rebar.gethandle(), Base::m_data.wparent )) break; if (!m_menu.init( m_rebar.gethandle(), Base::m_data.wparent )) break; Base::m_data.window = ::CreateWindowExA( WS_EX_COMPOSITED, TOOLBARCLASSNAME, "", WS_VISIBLE | WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | TBSTYLE_FLAT | TBSTYLE_WRAPABLE | TBSTYLE_TRANSPARENT | CCS_NORESIZE | CCS_NODIVIDER | CCS_NOPARENTALIGN, 0, 0, 1, 1, Base::m_data.wparent, (HMENU)ID_REBAR_TOOLBAR, MDIWin::Config::instance().gethinstance(), nullptr ); if (!Base::m_data.window) break; if (!setup_()) break; m_rebar.addband(Base::m_data.window, getsizebtn_() + 4); m_rebar.addband(m_search.gethandle(), 0); m_rebar.addband(m_menu.gethandle(), 0); m_rebar.showband(0); // MDIWin::Config::instance() .setclass<MDIWin::Config::HandleType::CLASS_TBAR>(this); // return { true, true }; } while (0); } catch (...) {} return { true, false }; } int32_t ToolBar::getsizebtn_() { if (!Base::m_data.window) return -1; LRESULT ret = ::SendMessage(Base::m_data.window, TB_GETBUTTONSIZE, 0, 0); auto p = MAKEPOINTS(ret); if (p.x != p.y) return -1; return p.y; } bool ToolBar::setup_() { ::SetLastError(0); const TBBUTTON tbb[] = { # define TB_ITEM(A,B,C,...) TB_ITEM_ ## B (A,B,C) # define TB_ITEM_TBSTYLE_BUTTON(A,B,C) \ { .iBitmap = __COUNTER__, .idCommand = C, .fsState = A, .fsStyle = B, .bReserved = {}, .dwData = 0, .iString = 0 }, # define TB_ITEM_TBSTYLE_SEP(A,B,C) \ { .iBitmap = 0, .idCommand = C, .fsState = A, .fsStyle = B, .bReserved = {}, .dwData = 0, .iString = 0 }, # define TB_CHANGE(...) # include "ToolBarItems.h" }; //int32_t imgcnt = (__COUNTER__ + 3); ImageLite::IPOINT<int32_t> ip{}; MDIWin::Config::instance().getiml( MDIWin::Config::ImageButtonList::IMLBTN_TITLEBAR_CTRL, ip ); if (ip.empty()) return false; ip.x += 2; ip.y += 2; ::SendMessage(Base::m_data.window, TB_BUTTONSTRUCTSIZE, (WPARAM)sizeof(TBBUTTON), 0); ::SendMessage(Base::m_data.window, TB_SETEXTENDEDSTYLE, 0, TBSTYLE_EX_DRAWDDARROWS); ::SendMessage(Base::m_data.window, TB_SETIMAGELIST, (WPARAM)0, (LPARAM) MDIWin::Config::instance().getiml(MDIWin::Config::ImageButtonList::IMLBTN_TOOLBAR_CTRL) ); ::SendMessage(Base::m_data.window, TB_SETBUTTONSIZE, 0, MAKELPARAM(ip.x, ip.y)); ::SendMessage(Base::m_data.window, TB_ADDBUTTONS, __NELE(tbb), (LPARAM)&tbb); ::SendMessage(Base::m_data.window, TB_SETPADDING, 0, MAKELPARAM(0, 0)); ::SendMessage(Base::m_data.window, TB_AUTOSIZE, 0, 0); ::SendMessage(Base::m_data.window, WM_SETFONT, (WPARAM)MDIWin::Config::instance().getfont(), (LPARAM)1); // return true; } // get search text std::string ToolBar::event() { return m_search.gettext(); } // change button void ToolBar::event(int32_t bidx, int32_t bcmd, int32_t bset, int32_t bimg) { static const TBChangeButton l_chbtn[] = { # define TB_CHANGE(A,B,C,D,E) \ { .btnidx = A, .cmdcur = B, .cmdnew = C, .imgidx = D, .state = E }, # define TB_ITEM(...) # include "ToolBarItems.h" }; do { if (bidx > ::SendMessage(Base::m_data.window, TB_BUTTONCOUNT, 0, 0)) break; TBBUTTON tbb{}; if (!::SendMessage(Base::m_data.window, TB_GETBUTTON, bidx, reinterpret_cast<LPARAM>(&tbb))) break; if (tbb.fsStyle == TBSTYLE_SEP) break; for (uint32_t i = 0U; i < __NELE(l_chbtn); i++) { if ((l_chbtn[i].btnidx == bidx) && ( ((bcmd == -1) && (l_chbtn[i].cmdcur == tbb.idCommand)) || ((bcmd != -1) && (l_chbtn[i].cmdnew == bcmd)) )) { // TBChangeButton btn{}; btn.cmdcur = tbb.idCommand; btn.cmdnew = ((bcmd == -1) ? l_chbtn[i].cmdnew : bcmd); btn.state = ((bset == -1) ? l_chbtn[i].state : bset); btn.imgidx = ((bimg == -1) ? l_chbtn[i].imgidx : bimg); // if ((btn.state != -1) && (btn.state != tbb.fsState)) ::SendMessage(Base::m_data.window, TB_SETSTATE, btn.cmdcur, (LPARAM)btn.state); // if ((btn.imgidx != -1) && (btn.imgidx != tbb.iBitmap)) ::SendMessage(Base::m_data.window, TB_CHANGEBITMAP, btn.cmdcur, btn.imgidx); // if ((btn.cmdnew != -1) && (btn.cmdnew != tbb.idCommand)) ::SendMessage(Base::m_data.window, TB_SETCMDID, btn.cmdcur, btn.cmdnew); // break; } } } while (0); } // set plugins toolBar menu void ToolBar::event(uint32_t mid, uint32_t off, std::vector<MDIWin::BaseData::dataMap> & v) { m_menu.add( static_cast<MenuBar::MainMenuId>(mid), off, v ); } // set style toolBar button (image/enable/disable) void ToolBar::event(int32_t id, bool isenable) { switch (id) { case IDM_EVENT_SCRUN_START: { event(TB_BTN_CHECK, -1, 0); event(TB_BTN_START, -1, 0); event(TB_BTN_EXIT, -1, 0); event(TB_BTN_STOP, -1, TBSTATE_ENABLED); m_menu.setenable(IDM_BTN_SCRUN_TEST, false); m_menu.setenable(IDM_BTN_SCRUN_START, false); m_menu.setenable(IDM_BTN_EXIT, false); m_menu.setenable(IDM_BTN_SCRUN_STOP, true); if (isenable) { event(TB_BTN_MODE, IDM_BTN_DBGDUMP); event(TB_BTN_NAVIGATTE, IDM_EDIT_SHOW_NAVIGATE, -1, 21); // m_menu.setcheck(IDM_BTN_DBGSTEP, true); m_menu.setcheck(IDM_BTN_DBGCYCLE, false); // m_menu.setenable(IDM_BTN_DBGDUMP, true); m_menu.setenable(IDM_BTN_DBGNEXT, true); } else { m_menu.setcheck(IDM_BTN_DBGSTEP, false); m_menu.setcheck(IDM_BTN_DBGCYCLE, true); // m_menu.setenable(IDM_BTN_DBGDUMP, false); m_menu.setenable(IDM_BTN_DBGNEXT, false); } break; } case IDM_EVENT_SCRUN_STOP: { event(TB_BTN_MODE, IDM_BTN_DBGCYCLE); event(TB_BTN_CHECK, -1, TBSTATE_ENABLED); event(TB_BTN_START, -1, TBSTATE_ENABLED); event(TB_BTN_EXIT, -1, TBSTATE_ENABLED); event(TB_BTN_STOP, -1, 0); event(TB_BTN_NAVIGATTE, IDM_EDIT_SHOW_NAVIGATE); // m_menu.setenable(IDM_BTN_SCRUN_TEST, true); m_menu.setenable(IDM_BTN_SCRUN_START, true); m_menu.setenable(IDM_BTN_EXIT, true); m_menu.setenable(IDM_BTN_SCRUN_STOP, false); // m_menu.setenable(IDM_BTN_DBGDUMP, false); m_menu.setenable(IDM_BTN_DBGNEXT, false); // m_menu.setcheck(IDM_BTN_DBGSTEP, false); m_menu.setcheck(IDM_BTN_DBGCYCLE, true); break; } case IDM_BTN_DBGMODE: { event(TB_BTN_MODE, ((isenable) ? IDM_BTN_DBGSTEP : IDM_BTN_DBGCYCLE) ); m_menu.setcheck(IDM_BTN_DBGSTEP, isenable); m_menu.setcheck(IDM_BTN_DBGCYCLE, !isenable); break; } case IDM_BTN_DBGSTEP: { event(TB_BTN_MODE, IDM_BTN_DBGSTEP); m_menu.setcheck(IDM_BTN_DBGSTEP, true); m_menu.setcheck(IDM_BTN_DBGCYCLE, false); break; } case IDM_BTN_DBGCYCLE: { event(TB_BTN_MODE, IDM_BTN_DBGCYCLE); m_menu.setcheck(IDM_BTN_DBGSTEP, false); m_menu.setcheck(IDM_BTN_DBGCYCLE, true); break; } case IDM_EVENT_EDIT_FINDTEXT: { if (isenable) event(TB_BTN_NAVIGATTE, IDM_EDIT_SHOW_NAVIGATE, -1, 21); else event(TB_BTN_NAVIGATTE, IDM_EDIT_SHOW_NAVIGATE); break; } case IDM_BTN_WINTOP: case IDM_BTN_EXTDBGV: case IDM_BTN_DBGMUTE: case IDM_EDIT_SHOW_ENDLINE: case IDM_EDIT_SHOW_INDENTG: { m_menu.setcheck(id, isenable); break; } default: break; } } };
35.891566
131
0.471031
ClnViewer
b11749b46733621b8a1da6e4fecb58a4fb627fda
11,629
cpp
C++
ACW Project Framework/System.cpp
Lentono/PhysicsSimulationACW
a73d22571a0742fd960740f04689f6ee095c3986
[ "MIT" ]
1
2021-06-06T10:29:12.000Z
2021-06-06T10:29:12.000Z
ACW Project Framework/System.cpp
Lentono/PhysicsSimulationACW
a73d22571a0742fd960740f04689f6ee095c3986
[ "MIT" ]
null
null
null
ACW Project Framework/System.cpp
Lentono/PhysicsSimulationACW
a73d22571a0742fd960740f04689f6ee095c3986
[ "MIT" ]
null
null
null
#include "System.h" #include <winuser.h> #include <iostream> #include <fstream> System::System() : m_initializationFailed(false), m_applicationName(nullptr), m_hInstance(nullptr), m_hwnd(nullptr), m_input(nullptr), m_graphics(nullptr) { auto screenWidth = 0; auto screenHeight = 0; //Initialize the Windows API InitializeWindows(screenWidth, screenHeight); //Create our input object for reading keyboard inputs m_input = new InputManager(); if (!m_input) { m_initializationFailed = true; return; } //Create our graphics object for handling the rendering of all the graphics m_graphics = new GraphicsRenderer(screenWidth, screenHeight, m_hwnd); if (m_graphics->GetInitializationState()) { m_initializationFailed = true; } m_screenWidth = screenWidth; m_screenHeight = screenHeight; }; // We don't need a copy/ move constructor for this class but it's best to have it defined so the compiler doesn't generate it for us System::System(const System& other) = default; System::System(System&& other) noexcept = default; System::~System() { //Release graphics object if (m_graphics) { delete m_graphics; m_graphics = nullptr; } if (m_input) { delete m_input; m_input = nullptr; } // Shutdown window ShutdownWindows(); } System& System::operator=(const System& other) = default; System& System::operator=(System&& other) noexcept = default; //This is the main application loop where we do all the application processing through the frame function until we quit. The frame function is called each loop. void System::Run() { MSG message; auto done = false; //Initialize message structure by filling a block of memory with zeros ZeroMemory(&message, sizeof(message)); //Loop until we get a quit message from the window or the user while (!done) { //Handle windows messages if (PeekMessage(&message, nullptr, 0, 0, PM_REMOVE)) { TranslateMessage(&message); DispatchMessage(&message); } //If windows ends the application then we exit out if (message.message == WM_QUIT) { done = true; } else { //Else we do the frame processing auto const result = Frame(); if (!result) { done = true; } } } } bool System::GetInitializationState() const { return m_initializationFailed; } //This is where all the application processing happens, we check to see if the user wants to quit the application, if not then we call the graphics objects frame function which will render the graphics. //More code will be added here as we add more functionality to the framework/ application. bool System::Frame() { //Check if user wants to quit the application if (m_input->IsKeyDown(VK_ESCAPE)) { return false; } if (m_input->IsKeyUp(0x31) && m_input->IsKeyUp(0x32) && m_input->IsKeyUp(0x52) && m_input->IsKeyUp(0x50) && m_input->IsKeyUp(0x55) && m_input->IsKeyUp(0x4A) && m_input->IsKeyUp(0x49) && m_input->IsKeyUp(0x4B) && m_input->IsKeyUp(0x4F) && m_input->IsKeyUp(0x4C) && m_input->IsKeyUp(0x54) && m_input->IsKeyUp(0x42) && m_input->IsKeyUp(VK_SPACE)) { m_input->ToggleDoOnce(true); } //Add Balls if (m_input->IsKeyDown(0x31) && m_input->DoOnce()) { m_graphics->AddNumberOfSpheres(m_hwnd); m_input->ToggleDoOnce(false); } //Add Cube if (m_input->IsKeyDown(0x32) && m_input->DoOnce()) { m_graphics->AddCube(m_hwnd); m_input->ToggleDoOnce(false); } //Reset System if (m_input->IsKeyDown(0x52) && m_input->DoOnce()) { m_graphics->ClearMoveableGameObjects(); m_input->ToggleDoOnce(false); } //Pause Simulation if (m_input->IsKeyDown(0x50) && m_input->DoOnce()) { m_graphics->TogglePauseSimulation(); m_input->ToggleDoOnce(false); } //Increase/Decrease TimeScale if (m_input->IsKeyDown(0x55) && m_input->DoOnce()) { m_graphics->AddTimeScale(1); m_input->ToggleDoOnce(false); } if (m_input->IsKeyDown(0x4A) && m_input->DoOnce()) { m_graphics->AddTimeScale(-1); m_input->ToggleDoOnce(false); } //Increase/Decrease Friction if (m_input->IsKeyDown(0x49) && m_input->DoOnce()) { m_graphics->AddFriction(0.1f); m_input->ToggleDoOnce(false); } if (m_input->IsKeyDown(0x4B) && m_input->DoOnce()) { m_graphics->AddFriction(-0.1f); m_input->ToggleDoOnce(false); } //Increase/Decrease Restitution if (m_input->IsKeyDown(0x4F) && m_input->DoOnce()) { m_graphics->AddRestitution(0.1f); m_input->ToggleDoOnce(false); } if (m_input->IsKeyDown(0x4C) && m_input->DoOnce()) { m_graphics->AddRestitution(-0.1f); m_input->ToggleDoOnce(false); } //Increase/Decrease Sphere Diameter if (m_input->IsKeyDown(0x54) && m_input->DoOnce()) { m_graphics->AddSphereDiameter(0.1f); m_input->ToggleDoOnce(false); } if (m_input->IsKeyDown(0x42) && m_input->DoOnce()) { m_graphics->AddSphereDiameter(-0.1f); m_input->ToggleDoOnce(false); } //Increase/Decrease Number Of Spheres if (m_input->IsKeyDown(VK_OEM_6)) { m_graphics->AddNumberOfSpheres(1); } if (m_input->IsKeyDown(VK_OEM_4)) { m_graphics->AddNumberOfSpheres(-1); } //Toggle Random Texture if (m_input->IsKeyDown(VK_SPACE) && m_input->DoOnce()) { m_graphics->ToggleRandomTexture(); m_input->ToggleDoOnce(false); } //Camera Controls if (m_input->IsKeyDown(0x57)) { m_graphics->GetCamera()->AddPositionY(1.0f); } if (m_input->IsKeyDown(0x53)) { m_graphics->GetCamera()->AddPositionY(-1.0f); } if (m_input->IsKeyDown(0x44)) { m_graphics->GetCamera()->AddPositionX(1.0f); } if (m_input->IsKeyDown(0x41)) { m_graphics->GetCamera()->AddPositionX(-1.0f); } if (m_input->IsKeyDown(VK_UP)) { m_graphics->GetCamera()->AddPositionZ(1.0f); } if (m_input->IsKeyDown(VK_DOWN)) { m_graphics->GetCamera()->AddPositionZ(-1.0f); } //Call graphics objects frame processing function auto const result = m_graphics->Frame(); return result; } //Our MessageHandler where we direct the windows system messages into. With this we can listen for certain information. //For now we just read key presses and key releases and notifiy our input object, all other information we just pass back to the default windows message handler. LRESULT CALLBACK System::MessageHandler(HWND hwnd, UINT const umsg, WPARAM const wparam, LPARAM const lparam) { switch(umsg) { //Check if a key has been pressed case WM_KEYDOWN: { // If a key is pressed then send it to our input object m_input->KeyDown(static_cast<unsigned int>(wparam)); return 0; } //Check if a key has been released case WM_KEYUP: { //If a key is released then send it to our input object m_input->KeyUp(static_cast<unsigned int>(wparam)); return 0; } //Send any other messages back to the default windows message handler default: { return DefWindowProc(hwnd, umsg, wparam, lparam); } } } //This is where we build the window we are rendering to. We start by initializing a default window which can be full screen or a set size, depending on the global variable FULL_SCREEN in the GraphicsClass.h void System::InitializeWindows(int& screenWidth, int& screenHeight) { //The windows class structure where we define the window information and register it WNDCLASSEX windowClass; //The device mode structure about the initialization and environment of our display device DEVMODE deviceEnvironment; int positionX; int positionY; //Get an external pointer to our object applicationHandle = this; //Get the instance of our application m_hInstance = GetModuleHandle(nullptr); //Name our application m_applicationName = "Real Time Graphics FrameWork ACW"; //Define our windows class with default settings windowClass.cbSize = sizeof(WNDCLASSEX); windowClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; //To do with redrawing the window if a movement or size adjustment occurs (CS_OWNDC allocates a unique device context) windowClass.lpfnWndProc = WndProc; windowClass.cbClsExtra = 0; windowClass.cbWndExtra = 0; windowClass.hInstance = m_hInstance; windowClass.hIcon = LoadIcon(nullptr, IDI_WINLOGO); windowClass.hCursor = LoadCursor(nullptr, IDC_ARROW); windowClass.hbrBackground = static_cast<HBRUSH>(GetStockObject(BLACK_BRUSH)); windowClass.lpszMenuName = nullptr; windowClass.lpszClassName = m_applicationName; windowClass.hIconSm = windowClass.hIcon; //Register our windows class RegisterClassEx(&windowClass); //Get the resolution of the users screen screenWidth = GetSystemMetrics(SM_CXSCREEN); screenHeight = GetSystemMetrics(SM_CYSCREEN); //Setup the display device depending on whether we are in full screen mode or windowed, if it's fullscreen we set the screen to the max size and 32bit, else to a defined resolution if (FULL_SCREEN) { //Can we just do ZeroMemory? //Initialize device structure by filling a block of memory with zeros ZeroMemory(&deviceEnvironment, sizeof(deviceEnvironment)); //memset(&deviceEnvironment, 0, sizeof(deviceEnvironment)); deviceEnvironment.dmSize = sizeof(deviceEnvironment); deviceEnvironment.dmPelsWidth = static_cast<unsigned long>(screenWidth); deviceEnvironment.dmPelsHeight = static_cast<unsigned long>(screenHeight); deviceEnvironment.dmBitsPerPel = 32; deviceEnvironment.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; //Change display settings to fullscreen using device environment ChangeDisplaySettings(&deviceEnvironment, CDS_FULLSCREEN); //Set the position of the window to the top left corner positionX = 0; positionY = 0; } else { screenWidth = 1360; screenHeight = 720; //Place window in the centre of the screen positionX = (GetSystemMetrics(SM_CXSCREEN) - screenWidth) / 2; positionY = (GetSystemMetrics(SM_CYSCREEN) - screenHeight) / 2; } //Create the window with the screen settings and get the handle to it m_hwnd = CreateWindowEx(WS_EX_APPWINDOW, m_applicationName, m_applicationName, WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_POPUP, positionX, positionY, screenWidth, screenHeight, nullptr, nullptr, m_hInstance, nullptr); //Show the window and bring it to the front of the applications ShowWindow(m_hwnd, SW_SHOW); SetForegroundWindow(m_hwnd); SetFocus(m_hwnd); //Hide the cursor ShowCursor(false); } //Reverts the screen settings and releases the window class and any handles associated with it void System::ShutdownWindows() { //Show the cursor ShowCursor(true); //Fix display settings if we're in full screen mode if (FULL_SCREEN) { ChangeDisplaySettings(nullptr, 0); } //Remove the window DestroyWindow(m_hwnd); m_hwnd = nullptr; //Remove the application instance by un-registering our window class UnregisterClass(m_applicationName, m_hInstance); m_hInstance = nullptr; //Release the pointer to this object applicationHandle = nullptr; } //This is where windows will sends its message to for us to intercept and use with our message handler, if we can't use it then we just return it back to the main windows message handler inside the MessageHandler function //We intercept this by giving this prototype function to the window procedure when we defined the window class structure for our window class (WNDCLASSEX), this way we hook into the messaging functionality and intercept messages LRESULT CALLBACK WndProc(HWND hwnd, UINT const umsg, WPARAM const wparam, LPARAM const lparam) { switch(umsg) { //Check if the window is being destroyed case WM_DESTROY: { PostQuitMessage(0); return 0; } //Check if the window is being closed case WM_CLOSE: { PostQuitMessage(0); return 0; } //All other messages pass to our message handler default: { return applicationHandle->MessageHandler(hwnd, umsg, wparam, lparam); } } }
27.491726
228
0.736177
Lentono
b11bbfb1c3b7aba8c6b64e42fa8a46265c859a34
3,353
cpp
C++
2017-05-24-practice/J.cpp
tangjz/Three-Investigators
46dc9b2f0fbb4fe89b075a81feaacc33feeb1b52
[ "MIT" ]
3
2018-04-02T06:00:51.000Z
2018-05-29T04:46:29.000Z
2017-05-24-practice/J.cpp
tangjz/Three-Investigators
46dc9b2f0fbb4fe89b075a81feaacc33feeb1b52
[ "MIT" ]
2
2018-03-31T17:54:30.000Z
2018-05-02T11:31:06.000Z
2017-05-24-practice/J.cpp
tangjz/Three-Investigators
46dc9b2f0fbb4fe89b075a81feaacc33feeb1b52
[ "MIT" ]
2
2018-10-07T00:08:06.000Z
2021-06-28T11:02:59.000Z
#include <cmath> #include <cstdio> #include <cstring> #include <cassert> #include <algorithm> using namespace std; typedef long long LL; typedef long double DB; const int maxn = 201, maxm = maxn * maxn, maxs = 13; const DB eps = 1e-8, INF = 1e4; inline int sgn(DB x) { assert(!std::isnan(x)); return (x > eps) - (x < -eps); } inline DB readDB() { static char buf[maxs]; scanf("%s", buf); LL ret = 0, base = 1; char *pat = buf; for( ; *pat && *pat != '.'; ++pat) ret = (ret << 3) + (ret << 1) + (*pat - '0'); if(*pat == '.') for(++pat; *pat; ++pat) { ret = (ret << 3) + (ret << 1) + (*pat - '0'); base = (base << 3) + (base << 1); } for( ; !(ret & 1) && !(base & 1); ret >>= 1, base >>= 1); for( ; !(ret % 5) && !(base % 5); ret /= 5, base /= 5); return (DB)ret / base; } inline void writeDB(DB x, char endc = '\0') { printf("%.20f", (double)x); endc && putchar(endc); } int N, M, S, T, lev[maxn], lnk[maxn], cur[maxn]; struct Edge { int nxt, v; DB w; } e[maxm << 2 | 1]; void addEdge(int u, int v, DB w) { e[M] = (Edge){lnk[u], v, w}; lnk[u] = M++; e[M] = (Edge){lnk[v], u, 0}; lnk[v] = M++; } bool bfs() { int L = 0, R = 0; static int que[maxn]; memset(lev, -1, N * sizeof(int)); lev[S] = 0; que[R++] = S; while(L < R) for(int u = que[L++], it = lnk[u]; it != -1; it = e[it].nxt) if(sgn(e[it].w) > 0 && lev[e[it].v] == -1) { lev[e[it].v] = lev[u] + 1; que[R++] = e[it].v; } return lev[T] != -1; } DB dfs(int u, DB upp) { if(u == T) return upp; DB ret = 0, tmp; for(int &it = cur[u]; ~it; it = e[it].nxt) if(lev[e[it].v] == lev[u] + 1 && sgn(e[it].w) > 0 && sgn(tmp = dfs(e[it].v, min(upp - ret, e[it].w))) > 0) { e[it].w -= tmp; e[it ^ 1].w += tmp; if(sgn((ret += tmp) - upp) >= 0) break; } if(!sgn(ret)) lev[u] = -1; return ret; } DB dinic(int s, int t, DB lim = INF) { DB flow = 0, tmp; for(S = s, T = t; bfs() && sgn(lim - flow) > 0; ) for(memcpy(cur, lnk, N * sizeof(int)); sgn(lim - flow) > 0 && sgn(tmp = dfs(S, lim - flow)) > 0; flow += tmp); return flow; } int n, m; DB v, a, fmx, wmx, zmx, cap[2][maxm], ans; int main() { scanf("%d%d", &n, &m); v = readDB(); a = readDB(); N = n; M = 0; memset(lnk, -1, N * sizeof(int)); for(int i = 0; i < m; ++i) { int u, v, w; scanf("%d%d%d", &u, &v, &w); --u; --v; addEdge(u, v, w); addEdge(v, u, w); } // M = 4 m fmx = dinic(0, 2); zmx = fmx + dinic(1, 2); for(int i = 0; i < M; i += 2) { if((i >> 1) & 1) cap[0][i >> 2] -= e[i ^ 1].w; else cap[0][i >> 2] += e[i ^ 1].w; e[i].w += e[i ^ 1].w; e[i ^ 1].w = 0; } wmx = dinic(1, 2, zmx); dinic(0, 2, zmx - wmx); for(int i = 0; i < M; i += 2) { if((i >> 1) & 1) cap[1][i >> 2] -= e[i ^ 1].w; else cap[1][i >> 2] += e[i ^ 1].w; e[i].w += e[i ^ 1].w; e[i ^ 1].w = 0; } ans = min(max((1 - a) * zmx, zmx - fmx), wmx); DB dt = sgn(fmx + wmx - zmx) > 0 ? (wmx - ans) / (fmx + wmx - zmx) : 0; for(int i = 0; i < m; ++i) { DB cc = dt * cap[0][i] + (1 - dt) * cap[1][i]; e[i << 2].w = sgn(cc) > 0 ? cc : 0; e[i << 2 | 2].w = sgn(cc) < 0 ? -cc : 0; } dinic(1, 2, ans); for(int i = 0; i < m; ++i) { DB cc = dt * cap[0][i] + (1 - dt) * cap[1][i], ww = e[i << 2 | 1].w - e[i << 2 | 3].w; writeDB((cc - ww) / v, ' '); writeDB(ww, '\n'); } writeDB(pow((zmx - ans) / v, a) * pow(ans, 1 - a), '\n'); return 0; }
24.837037
112
0.454817
tangjz
b11e6767c676a711884031bddd27416a1bcc3ee4
8,468
cpp
C++
gui/qt/toolwidgets/pinwidget.cpp
hein09/vipster
b92302bf2bb8b8941e239ce8cbc7209e1e615b0b
[ "BSD-2-Clause" ]
6
2015-12-02T15:33:27.000Z
2017-07-28T17:46:51.000Z
gui/qt/toolwidgets/pinwidget.cpp
hein09/vipster
b92302bf2bb8b8941e239ce8cbc7209e1e615b0b
[ "BSD-2-Clause" ]
3
2018-02-04T16:11:19.000Z
2018-03-16T16:23:29.000Z
gui/qt/toolwidgets/pinwidget.cpp
hein09/vipster
b92302bf2bb8b8941e239ce8cbc7209e1e615b0b
[ "BSD-2-Clause" ]
1
2017-07-05T11:44:55.000Z
2017-07-05T11:44:55.000Z
#include "../mainwindow.h" #include "pinwidget.h" #include "ui_pinwidget.h" #include <QMessageBox> using namespace Vipster; PinWidget::PinWidget(QWidget *parent) : BaseWidget(parent), ui(new Ui::PinWidget) { ui->setupUi(this); } PinWidget::~PinWidget() { delete ui; } void PinWidget::updateWidget(GUI::change_t change) { if(change & (GUI::Change::atoms | GUI::Change::trajec | GUI::Change::cell | GUI::Change::settings)){ // set gui-state on_stepList_currentRowChanged(ui->stepList->currentRow()); // update GPU data for(auto &dat: pinnedSteps){ const auto& settings = master->settings; dat->update(dat->curStep, settings.atRadVdW.val, settings.atRadFac.val, settings.bondRad.val); } } if((change & GUI::stepChanged) == GUI::stepChanged){ // disable add-button when already pinned for(auto &dat: pinnedSteps){ if(dat->curStep == master->curStep){ ui->addStep->setDisabled(true); return; } } ui->addStep->setEnabled(true); } } PinWidget::PinnedStep::PinnedStep(Step *step, const std::string& name, GUI::PBCVec mult) : GUI::StepData{step}, name{name}, mult{mult} {} void PinWidget::PinnedStep::draw(const Vec &off, const GUI::PBCVec &m, const Mat &cv, bool drawCell, void *context) { Vec off_loc = off + this->offset; Mat cv_loc = curStep->getCellVec() * curStep->getCellDim(AtomFmt::Bohr); auto mult_loc = curStep->hasCell() ? mult : GUI::PBCVec{{1,1,1}}; if(repeat){ for(int x=0; x<m[0]; ++x){ for(int y=0; y<m[1]; ++y){ for(int z=0; z<m[2]; ++z){ StepData::draw(off_loc + x*cv[0] + y*cv[1] + z*cv[2], mult_loc, cv_loc, drawCell & this->cell, context); } } } }else{ StepData::draw(off_loc, mult_loc, cv_loc, drawCell & this->cell, context); } } void PinWidget::setMult(int i) { if (!curPin) return; auto &mult = curPin->mult; if(sender() == ui->xMultBox){ mult[0] = static_cast<uint8_t>(i); }else if(sender() == ui->yMultBox){ mult[1] = static_cast<uint8_t>(i); }else if(sender() == ui->zMultBox){ mult[2] = static_cast<uint8_t>(i); } triggerUpdate(GUI::Change::extra); } void PinWidget::setOffset(double d) { if (!curPin) return; auto &off = curPin->offset; if(sender() == ui->xOffset){ off[0] = d; }else if(sender() == ui->yOffset){ off[1] = d; }else if(sender() == ui->zOffset){ off[2] = d; } triggerUpdate(GUI::Change::extra); } void PinWidget::on_showCell_toggled(bool checked) { if (!curPin) return; curPin->cell = checked; triggerUpdate(GUI::Change::extra); } void PinWidget::on_repeatStep_toggled(bool checked) { if (!curPin) return; curPin->repeat = checked; triggerUpdate(GUI::Change::extra); } void PinWidget::on_delStep_clicked() { // remove local infos ui->insertStep->setDisabled(true); if(curPin->curStep == master->curStep){ ui->addStep->setEnabled(true); } auto pos2 = std::find(pinnedSteps.begin(), pinnedSteps.end(), curPin); pinnedSteps.erase(pos2); delete ui->stepList->takeItem(ui->stepList->currentRow()); triggerUpdate(GUI::Change::extra); } void PinWidget::on_addStep_clicked() { ui->addStep->setDisabled(true); // add to list of steps pinnedSteps.push_back(std::make_shared<PinnedStep>(master->curStep, master->curMol->name + " (Step " + std::to_string(master->curVP->moldata[master->curMol].curStep) + ')', GUI::PBCVec{1,1,1})); pinnedSteps.back()->update(pinnedSteps.back()->curStep, master->settings.atRadVdW.val, master->settings.atRadFac.val, master->settings.bondRad.val); ui->stepList->addItem(QString::fromStdString(pinnedSteps.back()->name)); // enable in current viewport master->curVP->addExtraData(pinnedSteps.back(), true); triggerUpdate(GUI::Change::extra); } void PinWidget::on_stepList_currentRowChanged(int currentRow) { curPin = currentRow < 0 ? nullptr : pinnedSteps[currentRow]; auto hasPin = static_cast<bool>(curPin); auto hasCell = hasPin ? curPin->curStep->hasCell() : false; ui->insertStep->setEnabled(hasPin ? curPin->curStep != master->curStep : false); ui->delStep->setEnabled(hasPin); ui->showStep->setEnabled(hasPin); ui->repeatStep->setEnabled(hasPin); ui->xOffset->setEnabled(hasPin); ui->yOffset->setEnabled(hasPin); ui->zOffset->setEnabled(hasPin); ui->showCell->setEnabled(hasCell); ui->xMultBox->setEnabled(hasCell); ui->yMultBox->setEnabled(hasCell); ui->zMultBox->setEnabled(hasCell); ui->xFit->setEnabled(hasCell); ui->yFit->setEnabled(hasCell); ui->zFit->setEnabled(hasCell); if(hasPin){ QSignalBlocker block{ui->showStep}; ui->showStep->setChecked(master->curVP->hasExtraData(curPin, true)); QSignalBlocker block1{ui->showCell}; ui->showCell->setChecked(curPin->cell); QSignalBlocker block2{ui->repeatStep}; ui->repeatStep->setChecked(curPin->repeat); QSignalBlocker blockx{ui->xMultBox}; ui->xMultBox->setValue(curPin->mult[0]); QSignalBlocker blocky{ui->yMultBox}; ui->yMultBox->setValue(curPin->mult[1]); QSignalBlocker blockz{ui->zMultBox}; ui->zMultBox->setValue(curPin->mult[2]); QSignalBlocker blockox{ui->xOffset}; ui->xOffset->setValue(curPin->offset[0]); QSignalBlocker blockoy{ui->yOffset}; ui->yOffset->setValue(curPin->offset[1]); QSignalBlocker blockoz{ui->zOffset}; ui->zOffset->setValue(curPin->offset[2]); } } void PinWidget::on_insertStep_clicked() { if (!curPin || (curPin->curStep == master->curStep)) return; Step s = *curPin->curStep; s.asFmt(AtomFmt::Bohr).modShift(curPin->offset); std::array<bool,3> fit = {ui->xFit->isChecked(), ui->yFit->isChecked(), ui->zFit->isChecked()}; if (s.hasCell() && (curPin->mult != GUI::PBCVec{{1,1,1}})) { const auto &m = curPin->mult; s.modMultiply(m[0], m[1], m[2]); } if (s.hasCell() && (fit != std::array<bool,3>{{false, false, false}})){ auto fac = master->curStep->getCellDim(AtomFmt::Bohr) / s.getCellDim(AtomFmt::Bohr); auto cell = s.getCellVec(); const auto& target = master->curStep->getCellVec(); if (fit[0]) cell[0] = target[0] * fac; if (fit[1]) cell[1] = target[1] * fac; if (fit[2]) cell[2] = target[2] * fac; s.setCellVec(cell, true); } master->curStep->newAtoms(s); // immediately hide pinned step master->curVP->delExtraData(curPin, true); triggerUpdate(GUI::Change::atoms); } void PinWidget::on_showStep_toggled(bool checked) { if (!curPin) return; if (checked) { // insert into viewports extras master->curVP->addExtraData(curPin, true); }else{ // remove from viewports extras master->curVP->delExtraData(curPin, true); } triggerUpdate(GUI::Change::extra); } void PinWidget::on_helpButton_clicked() { QMessageBox::information(this, QString("About pinning"), "Pinned Steps are drawn along the currently active Step.\n\n" "\"Repeating\" a Step means it is drawn in periodic repetitions " "of the active Step, i.e. with the periodicity of the active Step.\n" "Contrarily, specifying the multipliers for the pinned Step " "itself draws it with its own periodicity.\n" "Specifying the offset allows the pinned Step to be shifted against the active Step " "without having to modify its structure.\n\n" "Inserting a Step takes both offset and multipliers into account, " "and additionally performs cell vector fitting if requested.\n\n" "Cell vector fitting can be used e.g. to create commensurable super cells. " "If fitting is enabled for a direction, " "the lattice will be shrunken or stretched to " "match this dimension in the active Step." ); }
34.563265
93
0.604393
hein09
b120c5c6ad2f91f35ea1d40a98d6b72d0b5ba393
17,114
cpp
C++
examples/pxScene2d/external/libnode-v10.15.3/deps/icu-small/source/i18n/numparse_decimal.cpp
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
12,278
2015-01-29T17:11:33.000Z
2022-03-31T21:12:00.000Z
examples/pxScene2d/external/libnode-v10.15.3/deps/icu-small/source/i18n/numparse_decimal.cpp
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
9,469
2015-01-30T05:33:07.000Z
2022-03-31T16:17:21.000Z
examples/pxScene2d/external/libnode-v10.15.3/deps/icu-small/source/i18n/numparse_decimal.cpp
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
892
2015-01-29T16:26:19.000Z
2022-03-20T07:44:30.000Z
// © 2018 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html #include "unicode/utypes.h" #if !UCONFIG_NO_FORMATTING // Allow implicit conversion from char16_t* to UnicodeString for this file: // Helpful in toString methods and elsewhere. #define UNISTR_FROM_STRING_EXPLICIT #include "numparse_types.h" #include "numparse_decimal.h" #include "static_unicode_sets.h" #include "numparse_utils.h" #include "unicode/uchar.h" #include "putilimp.h" #include "number_decimalquantity.h" using namespace icu; using namespace icu::numparse; using namespace icu::numparse::impl; DecimalMatcher::DecimalMatcher(const DecimalFormatSymbols& symbols, const Grouper& grouper, parse_flags_t parseFlags) { if (0 != (parseFlags & PARSE_FLAG_MONETARY_SEPARATORS)) { groupingSeparator = symbols.getConstSymbol(DecimalFormatSymbols::kMonetaryGroupingSeparatorSymbol); decimalSeparator = symbols.getConstSymbol(DecimalFormatSymbols::kMonetarySeparatorSymbol); } else { groupingSeparator = symbols.getConstSymbol(DecimalFormatSymbols::kGroupingSeparatorSymbol); decimalSeparator = symbols.getConstSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol); } bool strictSeparators = 0 != (parseFlags & PARSE_FLAG_STRICT_SEPARATORS); unisets::Key groupingKey = strictSeparators ? unisets::STRICT_ALL_SEPARATORS : unisets::ALL_SEPARATORS; // Attempt to find separators in the static cache groupingUniSet = unisets::get(groupingKey); unisets::Key decimalKey = unisets::chooseFrom( decimalSeparator, strictSeparators ? unisets::STRICT_COMMA : unisets::COMMA, strictSeparators ? unisets::STRICT_PERIOD : unisets::PERIOD); if (decimalKey >= 0) { decimalUniSet = unisets::get(decimalKey); } else if (!decimalSeparator.isEmpty()) { auto* set = new UnicodeSet(); set->add(decimalSeparator.char32At(0)); set->freeze(); decimalUniSet = set; fLocalDecimalUniSet.adoptInstead(set); } else { decimalUniSet = unisets::get(unisets::EMPTY); } if (groupingKey >= 0 && decimalKey >= 0) { // Everything is available in the static cache separatorSet = groupingUniSet; leadSet = unisets::get( strictSeparators ? unisets::DIGITS_OR_ALL_SEPARATORS : unisets::DIGITS_OR_STRICT_ALL_SEPARATORS); } else { auto* set = new UnicodeSet(); set->addAll(*groupingUniSet); set->addAll(*decimalUniSet); set->freeze(); separatorSet = set; fLocalSeparatorSet.adoptInstead(set); leadSet = nullptr; } UChar32 cpZero = symbols.getCodePointZero(); if (cpZero == -1 || !u_isdigit(cpZero) || u_digit(cpZero, 10) != 0) { // Uncommon case: okay to allocate. auto digitStrings = new UnicodeString[10]; fLocalDigitStrings.adoptInstead(digitStrings); for (int32_t i = 0; i <= 9; i++) { digitStrings[i] = symbols.getConstDigitSymbol(i); } } requireGroupingMatch = 0 != (parseFlags & PARSE_FLAG_STRICT_GROUPING_SIZE); groupingDisabled = 0 != (parseFlags & PARSE_FLAG_GROUPING_DISABLED); integerOnly = 0 != (parseFlags & PARSE_FLAG_INTEGER_ONLY); grouping1 = grouper.getPrimary(); grouping2 = grouper.getSecondary(); // Fraction grouping parsing is disabled for now but could be enabled later. // See http://bugs.icu-project.org/trac/ticket/10794 // fractionGrouping = 0 != (parseFlags & PARSE_FLAG_FRACTION_GROUPING_ENABLED); } bool DecimalMatcher::match(StringSegment& segment, ParsedNumber& result, UErrorCode& status) const { return match(segment, result, 0, status); } bool DecimalMatcher::match(StringSegment& segment, ParsedNumber& result, int8_t exponentSign, UErrorCode&) const { if (result.seenNumber() && exponentSign == 0) { // A number has already been consumed. return false; } else if (exponentSign != 0) { // scientific notation always comes after the number U_ASSERT(!result.quantity.bogus); } // Initial offset before any character consumption. int32_t initialOffset = segment.getOffset(); // Return value: whether to ask for more characters. bool maybeMore = false; // All digits consumed so far. number::impl::DecimalQuantity digitsConsumed; digitsConsumed.bogus = true; // The total number of digits after the decimal place, used for scaling the result. int32_t digitsAfterDecimalPlace = 0; // The actual grouping and decimal separators used in the string. // If non-null, we have seen that token. UnicodeString actualGroupingString; UnicodeString actualDecimalString; actualGroupingString.setToBogus(); actualDecimalString.setToBogus(); // Information for two groups: the previous group and the current group. // // Each group has three pieces of information: // // Offset: the string position of the beginning of the group, including a leading separator // if there was a leading separator. This is needed in case we need to rewind the parse to // that position. // // Separator type: // 0 => beginning of string // 1 => lead separator is a grouping separator // 2 => lead separator is a decimal separator // // Count: the number of digits in the group. If -1, the group has been validated. int32_t currGroupOffset = 0; int32_t currGroupSepType = 0; int32_t currGroupCount = 0; int32_t prevGroupOffset = -1; int32_t prevGroupSepType = -1; int32_t prevGroupCount = -1; while (segment.length() > 0) { maybeMore = false; // Attempt to match a digit. int8_t digit = -1; // Try by code point digit value. UChar32 cp = segment.getCodePoint(); if (u_isdigit(cp)) { segment.adjustOffset(U16_LENGTH(cp)); digit = static_cast<int8_t>(u_digit(cp, 10)); } // Try by digit string. if (digit == -1 && !fLocalDigitStrings.isNull()) { for (int32_t i = 0; i < 10; i++) { const UnicodeString& str = fLocalDigitStrings[i]; if (str.isEmpty()) { continue; } int32_t overlap = segment.getCommonPrefixLength(str); if (overlap == str.length()) { segment.adjustOffset(overlap); digit = static_cast<int8_t>(i); break; } maybeMore = maybeMore || (overlap == segment.length()); } } if (digit >= 0) { // Digit was found. if (digitsConsumed.bogus) { digitsConsumed.bogus = false; digitsConsumed.clear(); } digitsConsumed.appendDigit(digit, 0, true); currGroupCount++; if (!actualDecimalString.isBogus()) { digitsAfterDecimalPlace++; } continue; } // Attempt to match a literal grouping or decimal separator. bool isDecimal = false; bool isGrouping = false; // 1) Attempt the decimal separator string literal. // if (we have not seen a decimal separator yet) { ... } if (actualDecimalString.isBogus() && !decimalSeparator.isEmpty()) { int32_t overlap = segment.getCommonPrefixLength(decimalSeparator); maybeMore = maybeMore || (overlap == segment.length()); if (overlap == decimalSeparator.length()) { isDecimal = true; actualDecimalString = decimalSeparator; } } // 2) Attempt to match the actual grouping string literal. if (!actualGroupingString.isBogus()) { int32_t overlap = segment.getCommonPrefixLength(actualGroupingString); maybeMore = maybeMore || (overlap == segment.length()); if (overlap == actualGroupingString.length()) { isGrouping = true; } } // 2.5) Attempt to match a new the grouping separator string literal. // if (we have not seen a grouping or decimal separator yet) { ... } if (!groupingDisabled && actualGroupingString.isBogus() && actualDecimalString.isBogus() && !groupingSeparator.isEmpty()) { int32_t overlap = segment.getCommonPrefixLength(groupingSeparator); maybeMore = maybeMore || (overlap == segment.length()); if (overlap == groupingSeparator.length()) { isGrouping = true; actualGroupingString = groupingSeparator; } } // 3) Attempt to match a decimal separator from the equivalence set. // if (we have not seen a decimal separator yet) { ... } // The !isGrouping is to confirm that we haven't yet matched the current character. if (!isGrouping && actualDecimalString.isBogus()) { if (decimalUniSet->contains(cp)) { isDecimal = true; actualDecimalString = UnicodeString(cp); } } // 4) Attempt to match a grouping separator from the equivalence set. // if (we have not seen a grouping or decimal separator yet) { ... } if (!groupingDisabled && actualGroupingString.isBogus() && actualDecimalString.isBogus()) { if (groupingUniSet->contains(cp)) { isGrouping = true; actualGroupingString = UnicodeString(cp); } } // Leave if we failed to match this as a separator. if (!isDecimal && !isGrouping) { break; } // Check for conditions when we don't want to accept the separator. if (isDecimal && integerOnly) { break; } else if (currGroupSepType == 2 && isGrouping) { // Fraction grouping break; } // Validate intermediate grouping sizes. bool prevValidSecondary = validateGroup(prevGroupSepType, prevGroupCount, false); bool currValidPrimary = validateGroup(currGroupSepType, currGroupCount, true); if (!prevValidSecondary || (isDecimal && !currValidPrimary)) { // Invalid grouping sizes. if (isGrouping && currGroupCount == 0) { // Trailing grouping separators: these are taken care of below U_ASSERT(currGroupSepType == 1); } else if (requireGroupingMatch) { // Strict mode: reject the parse digitsConsumed.clear(); digitsConsumed.bogus = true; } break; } else if (requireGroupingMatch && currGroupCount == 0 && currGroupSepType == 1) { break; } else { // Grouping sizes OK so far. prevGroupOffset = currGroupOffset; prevGroupCount = currGroupCount; if (isDecimal) { // Do not validate this group any more. prevGroupSepType = -1; } else { prevGroupSepType = currGroupSepType; } } // OK to accept the separator. // Special case: don't update currGroup if it is empty; this allows two grouping // separators in a row in lenient mode. if (currGroupCount != 0) { currGroupOffset = segment.getOffset(); } currGroupSepType = isGrouping ? 1 : 2; currGroupCount = 0; if (isGrouping) { segment.adjustOffset(actualGroupingString.length()); } else { segment.adjustOffset(actualDecimalString.length()); } } // End of main loop. // Back up if there was a trailing grouping separator. // Shift prev -> curr so we can check it as a final group. if (currGroupSepType != 2 && currGroupCount == 0) { maybeMore = true; segment.setOffset(currGroupOffset); currGroupOffset = prevGroupOffset; currGroupSepType = prevGroupSepType; currGroupCount = prevGroupCount; prevGroupOffset = -1; prevGroupSepType = 0; prevGroupCount = 1; } // Validate final grouping sizes. bool prevValidSecondary = validateGroup(prevGroupSepType, prevGroupCount, false); bool currValidPrimary = validateGroup(currGroupSepType, currGroupCount, true); if (!requireGroupingMatch) { // The cases we need to handle here are lone digits. // Examples: "1,1" "1,1," "1,1,1" "1,1,1," ",1" (all parse as 1) // See more examples in numberformattestspecification.txt int32_t digitsToRemove = 0; if (!prevValidSecondary) { segment.setOffset(prevGroupOffset); digitsToRemove += prevGroupCount; digitsToRemove += currGroupCount; } else if (!currValidPrimary && (prevGroupSepType != 0 || prevGroupCount != 0)) { maybeMore = true; segment.setOffset(currGroupOffset); digitsToRemove += currGroupCount; } if (digitsToRemove != 0) { digitsConsumed.adjustMagnitude(-digitsToRemove); digitsConsumed.truncate(); } prevValidSecondary = true; currValidPrimary = true; } if (currGroupSepType != 2 && (!prevValidSecondary || !currValidPrimary)) { // Grouping failure. digitsConsumed.bogus = true; } // Strings that start with a separator but have no digits, // or strings that failed a grouping size check. if (digitsConsumed.bogus) { maybeMore = maybeMore || (segment.length() == 0); segment.setOffset(initialOffset); return maybeMore; } // We passed all inspections. Start post-processing. // Adjust for fraction part. digitsConsumed.adjustMagnitude(-digitsAfterDecimalPlace); // Set the digits, either normal or exponent. if (exponentSign != 0 && segment.getOffset() != initialOffset) { bool overflow = false; if (digitsConsumed.fitsInLong()) { int64_t exponentLong = digitsConsumed.toLong(false); U_ASSERT(exponentLong >= 0); if (exponentLong <= INT32_MAX) { auto exponentInt = static_cast<int32_t>(exponentLong); if (result.quantity.adjustMagnitude(exponentSign * exponentInt)) { overflow = true; } } else { overflow = true; } } else { overflow = true; } if (overflow) { if (exponentSign == -1) { // Set to zero result.quantity.clear(); } else { // Set to infinity result.quantity.bogus = true; result.flags |= FLAG_INFINITY; } } } else { result.quantity = digitsConsumed; } // Set other information into the result and return. if (!actualDecimalString.isBogus()) { result.flags |= FLAG_HAS_DECIMAL_SEPARATOR; } result.setCharsConsumed(segment); return segment.length() == 0 || maybeMore; } bool DecimalMatcher::validateGroup(int32_t sepType, int32_t count, bool isPrimary) const { if (requireGroupingMatch) { if (sepType == -1) { // No such group (prevGroup before first shift). return true; } else if (sepType == 0) { // First group. if (isPrimary) { // No grouping separators is OK. return true; } else { return count != 0 && count <= grouping2; } } else if (sepType == 1) { // Middle group. if (isPrimary) { return count == grouping1; } else { return count == grouping2; } } else { U_ASSERT(sepType == 2); // After the decimal separator. return true; } } else { if (sepType == 1) { // #11230: don't accept middle groups with only 1 digit. return count != 1; } else { return true; } } } bool DecimalMatcher::smokeTest(const StringSegment& segment) const { // The common case uses a static leadSet for efficiency. if (fLocalDigitStrings.isNull() && leadSet != nullptr) { return segment.startsWith(*leadSet); } if (segment.startsWith(*separatorSet) || u_isdigit(segment.getCodePoint())) { return true; } if (fLocalDigitStrings.isNull()) { return false; } for (int32_t i = 0; i < 10; i++) { if (segment.startsWith(fLocalDigitStrings[i])) { return true; } } return false; } UnicodeString DecimalMatcher::toString() const { return u"<Decimal>"; } #endif /* #if !UCONFIG_NO_FORMATTING */
37.285403
107
0.596354
madanagopaltcomcast
b12134d6db01c00384a15b06f234d4968cc887cb
312
cpp
C++
ClientEngine/game/engine/Stage/UnitPart/UnitEvent/UnitEventOperator.cpp
twesd/editor
10ea9f535115dadab5694fecdb0c499d0013ac1b
[ "MIT" ]
null
null
null
ClientEngine/game/engine/Stage/UnitPart/UnitEvent/UnitEventOperator.cpp
twesd/editor
10ea9f535115dadab5694fecdb0c499d0013ac1b
[ "MIT" ]
null
null
null
ClientEngine/game/engine/Stage/UnitPart/UnitEvent/UnitEventOperator.cpp
twesd/editor
10ea9f535115dadab5694fecdb0c499d0013ac1b
[ "MIT" ]
null
null
null
#include "UnitEventOperator.h" #include "../UnitBehavior.h" UnitEventOperator::UnitEventOperator(SharedParams_t params) : UnitEventBase(params) { } UnitEventOperator::~UnitEventOperator(void) { } // Выполняется ли условие bool UnitEventOperator::IsApprove( core::array<Event_t*>& events ) { return true; }
17.333333
83
0.762821
twesd
b121bdc43e5ad3e405cb939ff89ac2674e1a5f60
3,114
cpp
C++
willow/src/op/reducemedian.cpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
61
2020-07-06T17:11:46.000Z
2022-03-12T14:42:51.000Z
willow/src/op/reducemedian.cpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
1
2021-02-25T01:30:29.000Z
2021-11-09T11:13:14.000Z
willow/src/op/reducemedian.cpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
6
2020-07-15T12:33:13.000Z
2021-11-07T06:55:00.000Z
// Copyright (c) 2021 Graphcore Ltd. All rights reserved. #include <memory> #include <popart/op/reducemedian.hpp> #include <popart/opmanager.hpp> namespace popart { ReduceMedianOp::ReduceMedianOp( const OperatorIdentifier &opid, const nonstd::optional<std::vector<int64_t>> &axes, int64_t keepdims, const Op::Settings &settings) : ReduceOp(opid, axes, keepdims, settings) {} std::unique_ptr<Op> ReduceMedianOp::clone() const { return std::make_unique<ReduceMedianOp>(*this); } void ReduceMedianOp::setup() { ReduceOp::setup(); outInfo(getIndicesOutIndex()) = {DataType::INT32, outInfo(getOutIndex()).shape()}; } std::vector<std::unique_ptr<Op>> ReduceMedianOp::getGradOps() { std::vector<std::unique_ptr<Op>> result; result.emplace_back( std::make_unique<ReduceMedianGradOp>(*this, backward_shape)); return result; } bool ReduceMedianOp::canBeReplacedByIdentity() const { // Make sure the op is never replaced by identity as callers expect two // outputs and identity only has one. return false; } ReduceMedianGradOp::ReduceMedianGradOp(const ReduceMedianOp &fwd_op, const Shape &backward_shape) : ReduceGradOp(Onnx::CustomGradOperators::ReduceMedianGrad, fwd_op, backward_shape) {} std::unique_ptr<Op> ReduceMedianGradOp::clone() const { return std::make_unique<ReduceMedianGradOp>(*this); } const std::vector<GradInOutMapper> &ReduceMedianGradOp::gradInputInfo() const { static const std::vector<GradInOutMapper> inInfo = { // Gradient from the top for the median values (0). {getInIndex(), ReduceMedianOp::getOutIndex(), GradOpInType::GradOut}, // Indices computed during the forward pass (1). {getIndicesInIndex(), ReduceMedianOp::getIndicesOutIndex(), GradOpInType::Out}}; return inInfo; } namespace { static OpDefinition::DataTypes T = {DataType::UINT32, DataType::UINT64, DataType::INT32, DataType::INT64, DataType::FLOAT16, DataType::FLOAT}; static OpDefinition reduceMedianOpDef( {OpDefinition::Inputs({{"data", T}}), OpDefinition::Outputs({{"reduced", T}, {"indices", {DataType::INT32}}}), OpDefinition::Attributes({{"axes", {"*"}}, {"keepdims", {"*"}}})}); static OpCreator<ReduceMedianOp> ReduceMedianOpCreator( OpDefinitions({{Onnx::AiGraphcore::OpSet1::ReduceMedian, reduceMedianOpDef}}), [](const OpCreatorInfo &info) { int64_t keepdims = info.attributes.getAttribute<Attributes::Int>("keepdims", 1); nonstd::optional<std::vector<int64_t>> axes; if (info.attributes.hasAttribute("axes")) { axes = info.attributes.getAttribute<Attributes::Ints>("axes"); } return std::unique_ptr<Op>( new ReduceMedianOp(info.opid, axes, keepdims, info.settings)); }, true); } // namespace } // namespace popart
34.6
79
0.636159
gglin001
b122c0b8fc656809dc785c8d77afb2530c5e284f
4,159
cpp
C++
src/surrogate/benchmark/dtlz.cpp
lucasmpavelski/elmoead
35286d7b5407c7b7a72f13cedbdedd9ba27ae22d
[ "MIT" ]
1
2020-09-24T09:36:52.000Z
2020-09-24T09:36:52.000Z
src/surrogate/benchmark/dtlz.cpp
lucasmpavelski/elmoead
35286d7b5407c7b7a72f13cedbdedd9ba27ae22d
[ "MIT" ]
null
null
null
src/surrogate/benchmark/dtlz.cpp
lucasmpavelski/elmoead
35286d7b5407c7b7a72f13cedbdedd9ba27ae22d
[ "MIT" ]
null
null
null
#include "dtlz.h" namespace dtlz { #define PI 3.1415926535897932384626433832795 void DTLZ1(const double *x, double* f, const unsigned no_vars, const unsigned no_objs) { int i = 0; int j = 0; int n = no_vars; int k = n - no_objs + 1; double g = 0; for (i = n - k + 1; i <= n; i++) { g += pow(x[i-1]-0.5,2) - cos(20 * PI * (x[i-1]-0.5)); } g = 100 * (k + g); for (i = 1; i <= no_objs; i++) { double fi = 0.5 * (1 + g); for (j = no_objs - i; j >= 1; j--) { fi *= x[j-1]; } if (i > 1) { fi *= 1 - x[(no_objs - i + 1) - 1]; } f[i-1] = fi; } } void DTLZ2(const double *x, double* f, const unsigned no_vars, const unsigned no_objs) { int i = 0; int j = 0; int n = no_vars; int k = n - no_objs + 1; double g = 0; for (i = n - k + 1; i <= n; i++) { g += pow(x[i-1]-0.5,2); } for (i = 1; i <= no_objs; i++) { double fi = (1 + g); for (j = no_objs - i; j >= 1; j--) { fi *= cos(x[j-1] * PI / 2); } if (i > 1) { fi *= sin(x[(no_objs - i + 1) - 1] * PI / 2); } f[i-1] = fi; } } void DTLZ3(const double *x, double* f, const unsigned no_vars, const unsigned no_objs) { int i = 0; int j = 0; int n = no_vars; int k = n - no_objs + 1; double g = 0; for (i = n - k + 1; i <= n; i++) { g += pow(x[i-1]-0.5,2) - cos(20 * PI * (x[i-1]-0.5)); } g = 100 * (k + g); for (i = 1; i <= no_objs; i++) { double fi = (1 + g); for (j = no_objs - i; j >= 1; j--) { fi *= cos(x[j-1] * PI / 2); } if (i > 1) { fi *= sin(x[(no_objs - i + 1) - 1] * PI / 2); } f[i-1] = fi; } } void DTLZ4(const double *x, double* f, const unsigned no_vars, const unsigned no_objs) { int i = 0; int j = 0; double alpha = 100; int n = no_vars; int k = n - no_objs + 1; double g = 0; for (i = n - k + 1; i <= n; i++) { g += pow(x[i-1]-0.5,2); } for (i = 1; i <= no_objs; i++) { double fi = (1 + g); for (j = no_objs - i; j >= 1; j--) { fi *= cos(pow(x[j-1],alpha) * PI / 2); } if (i > 1) { fi *= sin(pow(x[(no_objs - i + 1) - 1],alpha) * PI / 2); } f[i-1] = fi; } } void DTLZ5(const double *x, double* f, const unsigned no_vars, const unsigned no_objs) { int i = 0; int j = 0; int n = no_vars; int k = n - no_objs + 1; double *theta = new double[no_objs]; double t = 0; double g = 0; for (i = n - k + 1; i <= n; i++) { g += pow(x[i-1] - 0.5, 2); } t = PI / (4 * (1 + g)); theta[0] = x[0] * PI / 2; for (i = 2; i <= no_objs - 1; i++) { theta[i-1] = t * (1 + 2 * g * x[i-1]); } for (i = 1; i <= no_objs; i++) { double fi = (1 + g); for (j = no_objs - i; j >= 1; j--) { fi *= cos(theta[j-1]); } if (i > 1) { fi *= sin(theta[(no_objs - i + 1) - 1]); } f[i-1] = fi; } delete theta; } void DTLZ6(const double *x, double* f, const unsigned no_vars, const unsigned no_objs) { int i = 0; int j = 0; int n = no_vars; int k = n - no_objs + 1; double *theta = new double[no_objs]; double t = 0; double g = 0; for (i = n - k + 1; i <= n; i++) { g += pow(x[i-1], 0.1); } t = PI / (4 * (1 + g)); theta[0] = x[0] * PI / 2; for (i = 2; i <= no_objs - 1; i++) { theta[i-1] = t * (1 + 2 * g * x[i-1]); } for (i = 1; i <= no_objs; i++) { double fi = (1 + g); for (j = no_objs - i; j >= 1; j--) { fi *= cos(theta[j-1]); } if (i > 1) { fi *= sin(theta[(no_objs - i + 1) - 1]); } f[i-1] = fi; } delete theta; } void DTLZ7(const double *x, double* f, const unsigned no_vars, const unsigned no_objs) { int i = 0; int j = 0; int n = no_vars; int k = n - no_objs + 1; double g = 0; double h = 0; for (i = n - k + 1; i <= n; i++) { g += x[i-1]; } g = 1 + 9 * g / k; for (i = 1; i <= no_objs - 1; i++) { f[i-1] = x[i-1]; } for (j = 1; j <= no_objs - 1; j++) { h += x[j-1] / (1 + g) * (1 + sin(3 * PI * x[j-1])); } h = no_objs - h; f[no_objs - 1] = (1 + g) * h; } } /* dtlz */
17.47479
86
0.425824
lucasmpavelski
b1234b04f5d5b32719bae0d76a70bf28e176c859
6,950
cc
C++
chrome/browser/speech/speech_recognition_request.cc
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
2
2017-09-02T19:08:28.000Z
2021-11-15T15:15:14.000Z
chrome/browser/speech/speech_recognition_request.cc
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
null
null
null
chrome/browser/speech/speech_recognition_request.cc
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
1
2020-04-13T05:45:10.000Z
2020-04-13T05:45:10.000Z
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/speech/speech_recognition_request.h" #include <vector> #include "app/l10n_util.h" #include "base/json/json_reader.h" #include "base/string_util.h" #include "base/values.h" #include "chrome/common/net/url_request_context_getter.h" #include "net/base/escape.h" #include "net/base/load_flags.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_status.h" namespace { const char* const kDefaultSpeechRecognitionUrl = "https://www.google.com/speech-api/v1/recognize?client=chromium&"; const char* const kHypothesesString = "hypotheses"; const char* const kUtteranceString = "utterance"; const char* const kConfidenceString = "confidence"; bool ParseServerResponse(const std::string& response_body, speech_input::SpeechInputResultArray* result) { if (response_body.empty()) { LOG(WARNING) << "ParseServerResponse: Response was empty."; return false; } DVLOG(1) << "ParseServerResponse: Parsing response " << response_body; // Parse the response, ignoring comments. std::string error_msg; scoped_ptr<Value> response_value(base::JSONReader::ReadAndReturnError( response_body, false, NULL, &error_msg)); if (response_value == NULL) { LOG(WARNING) << "ParseServerResponse: JSONReader failed : " << error_msg; return false; } if (!response_value->IsType(Value::TYPE_DICTIONARY)) { VLOG(1) << "ParseServerResponse: Unexpected response type " << response_value->GetType(); return false; } const DictionaryValue* response_object = static_cast<DictionaryValue*>(response_value.get()); // Get the hypotheses Value* hypotheses_value = NULL; if (!response_object->Get(kHypothesesString, &hypotheses_value)) { VLOG(1) << "ParseServerResponse: Missing hypotheses attribute."; return false; } DCHECK(hypotheses_value); if (!hypotheses_value->IsType(Value::TYPE_LIST)) { VLOG(1) << "ParseServerResponse: Unexpected hypotheses type " << hypotheses_value->GetType(); return false; } const ListValue* hypotheses_list = static_cast<ListValue*>(hypotheses_value); if (hypotheses_list->GetSize() == 0) { VLOG(1) << "ParseServerResponse: hypotheses list is empty."; return false; } size_t index = 0; for (; index < hypotheses_list->GetSize(); ++index) { Value* hypothesis = NULL; if (!hypotheses_list->Get(index, &hypothesis)) { LOG(WARNING) << "ParseServerResponse: Unable to read hypothesis value."; break; } DCHECK(hypothesis); if (!hypothesis->IsType(Value::TYPE_DICTIONARY)) { LOG(WARNING) << "ParseServerResponse: Unexpected value type " << hypothesis->GetType(); break; } const DictionaryValue* hypothesis_value = static_cast<DictionaryValue*>(hypothesis); string16 utterance; if (!hypothesis_value->GetString(kUtteranceString, &utterance)) { LOG(WARNING) << "ParseServerResponse: Missing utterance value."; break; } // It is not an error if the 'confidence' field is missing. double confidence = 0.0; hypothesis_value->GetReal(kConfidenceString, &confidence); result->push_back(speech_input::SpeechInputResultItem(utterance, confidence)); } if (index < hypotheses_list->GetSize()) { result->clear(); return false; } return true; } } // namespace namespace speech_input { int SpeechRecognitionRequest::url_fetcher_id_for_tests = 0; SpeechRecognitionRequest::SpeechRecognitionRequest( URLRequestContextGetter* context, Delegate* delegate) : url_context_(context), delegate_(delegate) { DCHECK(delegate); } SpeechRecognitionRequest::~SpeechRecognitionRequest() {} bool SpeechRecognitionRequest::Send(const std::string& language, const std::string& grammar, const std::string& hardware_info, const std::string& content_type, const std::string& audio_data) { DCHECK(!url_fetcher_.get()); std::vector<std::string> parts; std::string lang_param = language; if (lang_param.empty() && url_context_) { // If no language is provided then we use the first from the accepted // language list. If this list is empty then it defaults to "en-US". // Example of the contents of this list: "es,en-GB;q=0.8", "" URLRequestContext* request_context = url_context_->GetURLRequestContext(); DCHECK(request_context); std::string accepted_language_list = request_context->accept_language(); size_t separator = accepted_language_list.find_first_of(",;"); lang_param = accepted_language_list.substr(0, separator); } if (lang_param.empty()) lang_param = "en-US"; parts.push_back("lang=" + EscapeQueryParamValue(lang_param, true)); if (!grammar.empty()) parts.push_back("lm=" + EscapeQueryParamValue(grammar, true)); if (!hardware_info.empty()) parts.push_back("xhw=" + EscapeQueryParamValue(hardware_info, true)); // TODO(satish): Remove this hardcoded value once the page is allowed to // set this via an attribute. parts.push_back("maxresults=3"); GURL url(std::string(kDefaultSpeechRecognitionUrl) + JoinString(parts, '&')); url_fetcher_.reset(URLFetcher::Create(url_fetcher_id_for_tests, url, URLFetcher::POST, this)); url_fetcher_->set_upload_data(content_type, audio_data); url_fetcher_->set_request_context(url_context_); // The speech recognition API does not require user identification as part // of requests, so we don't send cookies or auth data for these requests to // prevent any accidental connection between users who are logged into the // domain for other services (e.g. bookmark sync) with the speech requests. url_fetcher_->set_load_flags( net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SEND_AUTH_DATA); url_fetcher_->Start(); return true; } void SpeechRecognitionRequest::OnURLFetchComplete( const URLFetcher* source, const GURL& url, const URLRequestStatus& status, int response_code, const ResponseCookies& cookies, const std::string& data) { DCHECK_EQ(url_fetcher_.get(), source); bool error = !status.is_success() || response_code != 200; SpeechInputResultArray result; if (!error) error = !ParseServerResponse(data, &result); url_fetcher_.reset(); DVLOG(1) << "SpeechRecognitionRequest: Invoking delegate with result."; delegate_->SetRecognitionResult(error, result); } } // namespace speech_input
35.641026
79
0.685468
Gitman1989
b123df61ecdfdab9fe73b5544f9aa45d9d601704
5,396
hpp
C++
include/amtrs/.driver/g3d-opengl-devices_shader.hpp
isaponsoft/libamtrs
5adf821ee15592fc3280985658ca8a4b175ffcaa
[ "BSD-2-Clause-FreeBSD" ]
1
2019-12-10T02:12:49.000Z
2019-12-10T02:12:49.000Z
include/amtrs/.driver/g3d-opengl-devices_shader.hpp
isaponsoft/libamtrs
5adf821ee15592fc3280985658ca8a4b175ffcaa
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
include/amtrs/.driver/g3d-opengl-devices_shader.hpp
isaponsoft/libamtrs
5adf821ee15592fc3280985658ca8a4b175ffcaa
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
/* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. * * Use of this source code is governed by a BSD-style license that * * can be found in the LICENSE file. */ #ifndef __libamtrs__graphics__opengl__devices_shader__hpp #define __libamtrs__graphics__opengl__devices_shader__hpp AMTRS_OPENGL_NAMESPACE_BEGIN class devices_shader : g3d::shader::memory { public: static constexpr GLuint novalue = static_cast<GLuint>(0); template<class Resources> static devices_shader* get_shader(g3d::shader* _shader, Resources* _resources) { devices_shader* thiz; if (auto m = _shader->get_memory(); m) { // すでにメモリが存在する thiz = static_cast<devices_shader*>(m); } else { // 新しくメモリを確保 thiz = new devices_shader(); _shader->set_memory(thiz); _resources->set(thiz); } // シェーダーがまだ作られていないかロストしているなら再度作成する if (thiz->mShader == novalue) { _shader->compile(); } return thiz; } void activate(const g3d::device_capacity& _capacity, const void* _uniforms) { AMTRS_G3D_OPENGL_GLGETERROR("Before glUseProgram") glUseProgram(mShader); AMTRS_G3D_OPENGL_GLGETERROR("glUseProgram") GLuint textureIndex = 0; for (const auto& uni : mUniformLayout) { if (uni.type == GL_TEXTURE_2D) { glUniform1i(uni.location, textureIndex); AMTRS_G3D_OPENGL_GLGETERROR("glUniform1i") ++textureIndex; } else { switch (uni.count) { case 4 : glUniform4fv(uni.location, 1, (const GLfloat*)((std::uintptr_t)_uniforms + uni.offset)); AMTRS_G3D_OPENGL_GLGETERROR("glUniform4fv") break; case 16 : glUniformMatrix4fv(uni.location, 1, GL_FALSE, (const GLfloat*)((std::uintptr_t)_uniforms + uni.offset)); AMTRS_G3D_OPENGL_GLGETERROR("glUniformMatrix4fv") break; } } } } template<class Callback> void enumrate_textures(const void* _uniforms, Callback&& _callback) { GLuint textureIndex = 0; for (const auto& uni : mUniformLayout) { if (uni.type == GL_TEXTURE_2D) { auto tex = *reinterpret_cast<g3d::texture**>((std::uintptr_t)_uniforms + uni.offset); _callback(textureIndex, static_cast<g3d::texture*>(tex)); ++textureIndex; } } } void deactivate() { GLuint textureIndex = 0; for (const auto& uni : mUniformLayout) { if (uni.type == GL_TEXTURE_2D) { glActiveTexture(GL_TEXTURE0 + textureIndex); AMTRS_G3D_OPENGL_GLGETERROR("glActiveTexture") glBindTexture(GL_TEXTURE_2D, 0); AMTRS_G3D_OPENGL_GLGETERROR("glBindTexture") ++textureIndex; } } glUseProgram(0); AMTRS_G3D_OPENGL_GLGETERROR("glUseProgram") } auto const& vtxlayout() const noexcept { return mVertexLayout; } protected: void on_gain() override { } void on_lost() override { if (mShader != novalue) { glDeleteShader(mShader); mShader = novalue; } } void on_compile(const attribute* _attrs, std::size_t _attr_size, const attribute* _uniforms, std::size_t _uniform_size, std::string _vertex, std::string _fragment) override { // シェーダープログラム mVertexProgram = std::move(_vertex); mFragmentProgram = std::move(_fragment); mShader = build(mVertexProgram, mFragmentProgram); // 頂点レイアウト mVertexLayout = vertex_layout::create_from_shader(mShader); mVertexLayout.mapping(_attrs, _attr_size); // 共有データレイアウト mUniformLayout = uniform_layout::create_from_shader(mShader); mUniformLayout.mapping(_uniforms, _uniform_size); } private: static GLuint build(std::string const& _vtx, std::string const& _frg) { GLuint vtxShader; GLuint frgShader; (void)glGetError(); vtxShader = compile(GL_VERTEX_SHADER, _vtx); if (vtxShader == novalue) { AMTRS_DEBUG_LOG("vtxShader error"); return novalue; } frgShader = compile(GL_FRAGMENT_SHADER, _frg); if (frgShader == novalue) { AMTRS_DEBUG_LOG("frgShader error"); glDeleteShader(vtxShader); return novalue; } // 二つをリンク GLint linkStatus = GL_FALSE; GLint shader = glCreateProgram(); if (shader == novalue) { AMTRS_DEBUG_LOG("shader error"); glDeleteShader(vtxShader); glDeleteShader(frgShader); return novalue; } glAttachShader(shader, vtxShader); glAttachShader(shader, frgShader); glLinkProgram(shader); glGetProgramiv(shader, GL_LINK_STATUS, &linkStatus); if (!linkStatus) { char temp[512+1] = ""; glGetShaderInfoLog(shader, sizeof(temp)-1, nullptr, temp); throw std::logic_error(temp); } glDeleteShader(vtxShader); glDeleteShader(frgShader); return shader; } static GLuint compile(GLenum _shaderType, std::string_view _program) { std::string program(_program); GLint compiled = GL_FALSE; GLuint shader = glCreateShader(_shaderType); const char* prgs[] = { program.c_str() }; glShaderSource(shader, 1, prgs, nullptr); glCompileShader(shader); glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled); if (!compiled) { char temp[512+1] = ""; glGetShaderInfoLog(shader, sizeof(temp)-1, nullptr, temp); AMTRS_DEBUG_LOG("Shader compile error: %s", temp); throw std::runtime_error(format<std::string>("shader compile error: %s", temp)); } return shader; } std::string mVertexProgram; std::string mFragmentProgram; GLuint mShader = novalue; vertex_layout mVertexLayout; uniform_layout mUniformLayout; }; AMTRS_OPENGL_NAMESPACE_END #endif
23.876106
173
0.696998
isaponsoft
b1254b1b4a4235059ad51cd479eb73ceb4aa9240
14,579
cxx
C++
TRD/TRDsim/AliTRDptrgFEB.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
TRD/TRDsim/AliTRDptrgFEB.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
TRD/TRDsim/AliTRDptrgFEB.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ //////////////////////////////////////////////////////////////////////////// // // Pre-Trigger simulation // // Authors: F. Reidt (Felix.Reidt@cern.ch) // // This class is used to simulate the front end box behavior of the // pretrigger system. Digits of T0 and V0 are used as input. A threshold // discrimination, masking and first processing with look up tables is // done during the simulation process // //////////////////////////////////////////////////////////////////////////// #include <TClonesArray.h> #include <TTree.h> #include "AliRunLoader.h" #include "AliLoader.h" #include "AliLog.h" #include "AliVZEROdigit.h" #include "AliVZEROCalibData.h" #include "AliT0digit.h" #include "AliTRDptrgParam.h" #include "AliTRDptrgLUT.h" #include "AliTRDptrgFEB.h" ClassImp(AliTRDptrgFEB) //______________________________________________________________________________ AliTRDptrgFEB::AliTRDptrgFEB(AliRunLoader *rl) : TObject(), fRunLoader(rl), fParam(0), fLUTArray(0), fType(AliTRDptrgParam::kUndefined), fOperatingMode(AliTRDptrgParam::kDigits), fInputChannelCount(0), fPosition(AliTRDptrgParam::kUnknown), fID(0), fThreshold(0) { // default constructor AliError("default ctor - not recommended"); } //______________________________________________________________________________ AliTRDptrgFEB::AliTRDptrgFEB(AliRunLoader *rl, AliTRDptrgParam::AliTRDptrgFEBType_t febType, AliTRDptrgParam::AliTRDptrgOperatingMode_t operatingMode, AliTRDptrgParam::AliTRDptrgFEBPosition_t position, Int_t id, AliTRDptrgParam *param) : TObject(), fRunLoader(rl), fParam(param), fLUTArray(0), fType(febType), fOperatingMode(operatingMode), fInputChannelCount(0), fPosition(position), fID(id), fThreshold(0x0) { // prefered constructor this->LoadParams(); // load configuration parameters } //______________________________________________________________________________ AliTRDptrgFEB::~AliTRDptrgFEB() { // destructor if (this->fParam == 0x0) { if (this->fThreshold != 0x0) { delete[] this->fThreshold; this->fThreshold = 0x0; } } // delete LUTArray this->fLUTArray.Delete(); } //______________________________________________________________________________ Int_t AliTRDptrgFEB::LoadDigits() { // loads T0 or V0 digits and discriminates them automatically if (this->fType == AliTRDptrgParam::kVZERO) { // load V0's digits -------------------------------------------------------- // behavior adapted for AliVZERODigitizer.cxx 40613 2010-04-22 09:57:15Z // get V0 run loader AliLoader* loader = this->fRunLoader->GetLoader( "VZEROLoader" ); if (!loader) { AliError("Cannot get VZERO loader"); return -1; } loader->LoadDigits("READ"); TTree* vzeroDigitsTree = loader->TreeD(); if (!vzeroDigitsTree) { AliError("Cannot get the VZERO digit tree"); return -1; } TClonesArray* vzeroDigits = NULL; TBranch* digitBranch = vzeroDigitsTree->GetBranch("VZERODigit"); digitBranch->SetAddress(&vzeroDigits); vzeroDigitsTree->GetEvent(0); Int_t nDigits = vzeroDigits->GetEntriesFast(); // get digit count AliDebug(5, Form("Found a whole of %d digits", nDigits)); Int_t inputVector = 0x0; // Vector which is feed into the LUT for (Int_t iDigit=0; iDigit<nDigits; iDigit++) { // loop over all digits AliDebug(5, "Looping over digit"); AliVZEROdigit* digit = (AliVZEROdigit*)vzeroDigits->At(iDigit); Int_t pmNumber = digit->PMNumber(); // Int_t board = pmNumber / 8; // changed in Version 40613 Int_t feeBoard = AliVZEROCalibData::GetBoardNumber(pmNumber); Int_t board = feeBoard % 4; // feeBoard V0-A: 1-4; V0-C: 5-8 => board: 1-4 Int_t channel = pmNumber % 8; Int_t position = -1; if ((pmNumber >= 32) && (pmNumber <= 63)) { // V0-A (matched v40613) position = 1; // AliTRDptrgParam::kA } else if ((pmNumber >= 0) && (pmNumber <= 31)) { // V0-C (matched v40613) position = 2; // kB } AliDebug(5, Form("pmNumber: %d; feeBoard: %d; board: %d; channel: %d; position %d", pmNumber, feeBoard, board, channel, position)); if (position == -1) { AliError("Wrong VZERO pmt position found"); loader->UnloadDigits(); return -1; } // check whether the digits belongs to the current FEB, otherwise omit it if ((position == this->fPosition) && (board == this->fID)) { AliDebug(5, "Found an digit corresponding to the current FEB"); Float_t value = digit->ADC(); AliDebug(5, Form("ADC value: %f\n", value)); Int_t channelBitMask = 0x01; // channel0 => 0x01; channel1=> 0x02; 2^(channel number) channelBitMask <<= channel; if (value >= this->fThreshold[channel]) { inputVector |= channelBitMask; AliDebug(5, Form("Threshold exceeded in channel %d, new inputVector 0x%x", channel, inputVector)); } } } AliDebug(5, Form("inputVector: 0x%x", inputVector)); loader->UnloadDigits(); return inputVector; } else if (this->fType == AliTRDptrgParam::kTZERO) { // load T0's digits -------------------------------------------------------- AliLoader * fT0Loader = this->fRunLoader->GetLoader("T0Loader"); // AliT0digit *fDigits; if (!fT0Loader) { AliError("Cannot get T0 loader"); return -1; } fT0Loader->LoadDigits("READ"); // Creating T0 data container TTree* treeD = fT0Loader->TreeD(); if (!treeD) { AliError("no digits tree"); return -1; } AliT0digit* digits = new AliT0digit(); TBranch *brDigits = treeD->GetBranch("T0"); if (brDigits) { brDigits->SetAddress(&digits); } else { AliError("Branch T0 DIGIT not found"); return -1; } brDigits->GetEntry(0); TArrayI qtc0(24); // Array must have 24 entries! TArrayI qtc1(24); // Array must have 24 entries! digits->GetQT0(qtc0); // baseline (reference level) digits->GetQT1(qtc1); // measurement value Int_t inputVector = 0x0; // vector to be fed into the look up table // PMT Positions // C: 0 to 11 // A: 12 to 23 // positions according to AliT0Digitizer.cxx Revision 37491 Int_t nStart = 0; if (this->fPosition == AliTRDptrgParam::kC) { // C nStart = 0; } else if (this->fPosition == AliTRDptrgParam::kA) { // A nStart = 12; } Int_t channelBitMask = 0x01; for (Int_t i = 0 + nStart; i < nStart + 12; i++) { //Int_t channelBitMask = 0x01; AliDebug(5, Form("channel: %d", i)); Int_t value = qtc1[i] - qtc0[i]; // calculate correct measurement value if (value > (Int_t)this->fThreshold[i - nStart]) { inputVector |= channelBitMask; // Add bit AliDebug(5, Form("Threshold exceeded in channel %d,", i)); AliDebug(5, Form("new inputVector 0x%x", inputVector)); AliDebug(5, Form("channelBitMask 0x%x", channelBitMask)); } channelBitMask <<= 1; // go on to the next channel } delete digits; return inputVector; } return -1; } //______________________________________________________________________________ Int_t AliTRDptrgFEB::LoadAndProcessHits() { // loads TO or VO hits and converts them to digits optimized for ptrg // afterwards the digits will be discriminated AliError("LoadAndProcessHits() - not yet implemented!\n"); if (this->fType == AliTRDptrgParam::kVZERO) { return 0; } else if (this->fType == AliTRDptrgParam::kTZERO) { return 0; } return -1; } //______________________________________________________________________________ Bool_t AliTRDptrgFEB::LoadParams() { // Load Parameters if (this->fParam == 0x0) { AliWarning("No paramater object specified - start loading defaults\n"); if (this->fType == AliTRDptrgParam::kVZERO) { // initialize threshold this->fThreshold = new UInt_t[8]; for (Int_t i = 0; i < 8; i++) { this->fThreshold[i] = 10; } // initialize LUTsoutputWidth=<value optimized out> AliTRDptrgLUT* lut = new AliTRDptrgLUT(); this->fLUTArray.AddLast(lut); lut = new AliTRDptrgLUT(); this->fLUTArray.AddLast(lut); // the following lines are only needed for test reasons Int_t* initData = new Int_t[256]; // 2^8 lut = dynamic_cast<AliTRDptrgLUT*>(this->fLUTArray.At(0)); if (lut) { for (Int_t i = 0; i < 256; i++ ) { initData[i] = i; } lut->InitTable(8, 8, initData, kTRUE); // make copy of initData } lut = dynamic_cast<AliTRDptrgLUT*>(this->fLUTArray.At(1)); if (lut) { for (Int_t i = 255; i >= 0; i--) { initData[255 - i] = i; // inverse ramp } lut->InitTable(8, 8, initData, kTRUE); } delete [] initData; } else { // initialize threshold this->fThreshold = new UInt_t[12]; for (Int_t i = 0; i < 12; i++) { this->fThreshold[i] = 10; } // initialize LUTsoutputWidth=<value optimized out> AliTRDptrgLUT* lut = new AliTRDptrgLUT(); this->fLUTArray.AddLast(lut); lut = new AliTRDptrgLUT(); // this->fRunLoader this->fLUTArray.AddLast(lut); // the following lines are only needed for test reasons lut = dynamic_cast<AliTRDptrgLUT*>(this->fLUTArray.At(0)); Int_t* initData = new Int_t[4096]; // 2^12 if (lut) { for (Int_t i = 0; i < 4096; i++ ) { initData[i] = i; } lut->InitTable(12, 12, initData, kTRUE); // make a copy of the table } lut = dynamic_cast<AliTRDptrgLUT*>(this->fLUTArray.At(1)); if (lut) { //for (Int_t i = 4095; i >= 0; i--) { for (Int_t i = 4096; i > 0; i--) { initData[4096 - i] = i; // inverse ramp } lut->InitTable(12, 12, initData, kTRUE); // make a copy of the table } delete [] initData; } return false; } else { // load parameters from object if (this->fType == AliTRDptrgParam::kVZERO) { // threshold this->fThreshold = this->fParam->GetFEBV0Thresholds(this->fPosition, (this->fID - 1)); // look up tables // 1 AliTRDptrgLUT* LUT = new AliTRDptrgLUT(); LUT->InitTable(8, 8, this->fParam->GetFEBV0LUT(this->fPosition, (this->fID - 1), 0), kFALSE); // do not make a copy of the table due to performance reasons this->fLUTArray.AddLast(LUT); // 2 LUT = new AliTRDptrgLUT(); LUT->InitTable(8, 8, this->fParam->GetFEBV0LUT(this->fPosition, (this->fID - 1), 1), kFALSE); // do not make a copy of the table due to performance reasons this->fLUTArray.AddLast(LUT); } else { // threshold this->fThreshold = this->fParam->GetFEBT0Thresholds(this->fPosition); // look up tables // 1 AliTRDptrgLUT* LUT = new AliTRDptrgLUT(); LUT->InitTable(12, 12, fParam->GetFEBT0LUT(this->fPosition, 0), kFALSE); // do not make a copy of the table due to performance reasosn this->fLUTArray.AddLast(LUT); // 2 LUT = new AliTRDptrgLUT(); LUT->InitTable(12, 12, fParam->GetFEBT0LUT(this->fPosition, 1), kFALSE); // do not make a copy of the table due to performance reasosn this->fLUTArray.AddLast(LUT); } return true; } return false; } //______________________________________________________________________________ Int_t* AliTRDptrgFEB::Simulate() { // simulates the FEB behavior and returns a 2 bit ouput // (least significant bits) Int_t *result = new Int_t; (*result) = -1; if (this->fOperatingMode == AliTRDptrgParam::kDigits) { Int_t inputVector = this->LoadDigits(); delete result; // delete error return value // perform look up Int_t nLUTs = this->fLUTArray.GetEntriesFast(); // get LUT count result = new Int_t[nLUTs + 1]; // generate new return array result[0] = nLUTs; // storage array length in the first array value for (Int_t iLUT = 0; iLUT < nLUTs; iLUT++) { // process the return value for each LUT and store the result in the array AliDebug(4, Form("FEB: (pos=%d,id=%d,lut=%d,vector=0x%x)", this->fPosition, this->fID, iLUT, inputVector)); AliTRDptrgLUT *lutTmp = dynamic_cast<AliTRDptrgLUT*>(this->fLUTArray[iLUT]); if (lutTmp) { result[iLUT + 1] = lutTmp->LookUp(inputVector); } AliDebug(4, Form("FEB result[%d] = 0x%x",(iLUT + 1),result[iLUT + 1])); } } else if (this->fOperatingMode == AliTRDptrgParam::kHits) { return result; } return result; }
34.223005
93
0.576651
AllaMaevskaya
b127350b502f277660f655415e9d6b020c14c583
3,482
cpp
C++
source/MaterialXTest/Document.cpp
lvxejay/MaterialX
d367fe00ad6dca5ba56370e8c97249779a6bcf71
[ "BSL-1.0" ]
null
null
null
source/MaterialXTest/Document.cpp
lvxejay/MaterialX
d367fe00ad6dca5ba56370e8c97249779a6bcf71
[ "BSL-1.0" ]
null
null
null
source/MaterialXTest/Document.cpp
lvxejay/MaterialX
d367fe00ad6dca5ba56370e8c97249779a6bcf71
[ "BSL-1.0" ]
1
2021-09-11T08:01:25.000Z
2021-09-11T08:01:25.000Z
// // TM & (c) 2017 Lucasfilm Entertainment Company Ltd. and Lucasfilm Ltd. // All rights reserved. See LICENSE.txt for license. // #include <MaterialXTest/Catch/catch.hpp> #include <MaterialXCore/Document.h> namespace mx = MaterialX; TEST_CASE("Document", "[document]") { // Create a document. mx::DocumentPtr doc = mx::createDocument(); // Create a node graph with a constant color output. mx::NodeGraphPtr nodeGraph = doc->addNodeGraph(); mx::NodePtr constant = nodeGraph->addNode("constant"); constant->setParameterValue("value", mx::Color3(0.5f, 0.5f, 0.5f)); mx::OutputPtr output = nodeGraph->addOutput(); output->setConnectedNode(constant); REQUIRE(doc->validate()); // Create and test a type mismatch. output->setType("float"); REQUIRE(!doc->validate()); output->setType("color3"); REQUIRE(doc->validate()); // Test hierarchical name paths. REQUIRE(constant->getNamePath() == "nodegraph1/node1"); REQUIRE(constant->getNamePath(nodeGraph) == "node1"); // Create a simple shader interface. mx::NodeDefPtr shader = doc->addNodeDef("", "surfaceshader", "simpleSrf"); mx::InputPtr diffColor = shader->addInput("diffColor", "color3"); mx::InputPtr specColor = shader->addInput("specColor", "color3"); mx::ParameterPtr roughness = shader->addParameter("roughness", "float"); // Create a material that instantiates the shader. mx::MaterialPtr material = doc->addMaterial(); mx::ShaderRefPtr shaderRef = material->addShaderRef("", "simpleSrf"); // Bind the diffuse color input to the constant color output. mx::BindInputPtr bindInput = shaderRef->addBindInput("diffColor"); bindInput->setConnectedOutput(output); REQUIRE(diffColor->getUpstreamElement(material) == output); // Create a collection mx::CollectionPtr collection = doc->addCollection(); REQUIRE(doc->getCollections().size() == 1); REQUIRE(doc->getCollection(collection->getName())); doc->removeCollection(collection->getName()); REQUIRE(doc->getCollections().size() == 0); // Create a property set mx::PropertySetPtr propertySet = doc->addPropertySet(); REQUIRE(doc->getPropertySets().size() == 1); REQUIRE(doc->getPropertySet(propertySet->getName()) != nullptr); doc->removePropertySet(propertySet->getName()); REQUIRE(doc->getPropertySets().size() == 0); // Generate and verify require string. doc->generateRequireString(); REQUIRE(doc->getRequireString().find(mx::Document::REQUIRE_STRING_MATNODEGRAPH) != std::string::npos); // Validate the document. REQUIRE(doc->validate()); // Copy and reorder the document. mx::DocumentPtr doc2 = doc->copy(); REQUIRE(*doc2 == *doc); int origIndex = doc2->getChildIndex(shader->getName()); doc2->setChildIndex(shader->getName(), origIndex + 1); REQUIRE(*doc2 != *doc); doc2->setChildIndex(shader->getName(), origIndex); REQUIRE(*doc2 == *doc); REQUIRE_THROWS_AS(doc2->setChildIndex(shader->getName(), 100), mx::Exception); // Create and test an orphaned element. mx::ElementPtr orphan; { mx::DocumentPtr doc3 = doc->copy(); for (mx::ElementPtr elem : doc3->traverseTree()) { if (elem->isA<mx::Node>("constant")) { orphan = elem; } } REQUIRE(orphan); } REQUIRE_THROWS_AS(orphan->getDocument(), mx::ExceptionOrphanedElement); }
36.270833
106
0.660827
lvxejay
b12926933ea89adc1fd24b53c6c34c05b9faf121
10,937
cpp
C++
src/fhgc.cpp
michel94/fhgc-tool
4d3f011f606d1fbdad6791d1cbcdfa9ab83796a0
[ "MIT" ]
1
2018-08-23T09:15:54.000Z
2018-08-23T09:15:54.000Z
src/fhgc.cpp
michel94/fhgc-tool
4d3f011f606d1fbdad6791d1cbcdfa9ab83796a0
[ "MIT" ]
null
null
null
src/fhgc.cpp
michel94/fhgc-tool
4d3f011f606d1fbdad6791d1cbcdfa9ab83796a0
[ "MIT" ]
null
null
null
#include <string> #include <fstream> #include <sstream> #include <iostream> #include <vector> using namespace std; string SRC = "src/"; string WG_SRC = SRC + "webgraph/"; struct Execution{ FILE* f; int retCode; Execution(FILE* f, int retCode){ this->f = f; this->retCode = retCode; } }; bool startswith(const string& path, const string& st){ return path.substr(0, st.size()) == st; } void help(){ cout << "Usage: ./fhgc <command>" << endl; cout << "Valid commands:" << endl << " create-dataset <dataset-in>/<raw-data> <dataset-out> [options]" << endl << " clusters faststep/louvain/LLP <dataset> <output-folder> [options]" << endl << " labels faststep/louvain/LLP <dataset> <output-file> [options]" << endl << " clusterings2labels <dataset> <clusterings-prefix> <output-file> [options]" << endl << " reorder <dataset-in> <dataset-out> <indexes>" << endl << " compare-clusters <cluster-file-1> <cluster-file-2> [options]" << endl << " compare-clusters-list <regex-clusters-1> <regex-clusters-2> [options]" << endl << " size <dataset> [<more datasets>]" << endl << " countClusters <cluster-file>" << endl << " help" << endl; } void readfile(FILE* f){ const int SIZE = 1000; char str[SIZE+1]; while(fgets(str, SIZE, f) != NULL){ cout << str; } } void readfile(FILE* f, ofstream& ost){ const int SIZE = 1000; char str[SIZE+1]; while(fgets(str, SIZE, f) != NULL){ ost << str; cout << str; } ost.close(); } Execution exec(string s){ FILE* f; f = popen(s.c_str(), "r"); readfile(f); int ret = pclose(f); return Execution(f, ret); } Execution exec(string s, ofstream& ost){ FILE* f; f = popen(s.c_str(), "r"); readfile(f, ost); int ret = pclose(f); return Execution(f, ret); } void ls(string path, vector<string>& files){ string s = string("ls -1 ") + path; FILE* f; f = popen(s.c_str(), "r"); const int SIZE = 1000; char str[SIZE+1]; while(fgets(str, SIZE, f) != NULL){ string fname(str); fname = fname.substr(0, fname.size()-1); files.push_back(fname); } } string join(vector<string>& l, string d){ string s; for(int i=0; i<(int)l.size()-1; i++) s += l[i] + d; s += l[l.size()-1]; return s; } int main(int argc, char** argv){ if(argc < 2){ help(); return 0; } string command = argv[1]; if(command == "create-dataset"){ if(argc < 4){ cout << "Usage: ./fhgc create-dataset" << endl << " create-dataset <raw-data> <dataset-out> [options]" << endl << "<raw-data>: file with one line per edge of the graph, with two integers per line." << endl << " By default, the vertex indexes start at one and the edges are considered undirected." << endl << "[options]:" << endl << " --shuffle: randomly shuffle the indexes of the vertices of the graph" << endl << " --sub0: assume that indexes of nodes of the input start at zero" << endl << " --directed: the edges are considered as directed links" << endl; return 1; }else{ string s = WG_SRC + string("create-dataset.new.sh "); for(int i=2; i<argc; i++){ s += argv[i]; s += " "; } cout << "Running: " << s << endl; int ret = exec(s).retCode; if(ret != 0) return 1; } }else if(command == "clusters" || command == "labels"){ bool CLUSTERS = false; if(command == "clusters") CLUSTERS = true; if(argc < 5){ cout << "Usage: ./fhgc " << command << endl; if(CLUSTERS) cout << " " << command << " faststep/louvain/LLP <dataset> <output-folder> [options]" << endl; else cout << " " << command << " faststep/louvain/LLP <dataset> <output-file> [options]" << endl; return 1; }else{ string method = argv[2]; string s; if(method == "LLP"){ s = WG_SRC + string("LLP.sh "); if(CLUSTERS) s += argv[3] + string(" /tmp/labels.txt -l ") + argv[4] + "/communities"; else s += argv[3] + string(" ") + argv[4]; }else if(method == "faststep"){ s = WG_SRC + string("faststep.sh "); if(CLUSTERS) s += argv[3] + string(" -c ") + argv[4]; else s += argv[3] + string(" ") + argv[4]; }else if(method == "louvain"){ s = WG_SRC + string("louvain.sh "); if(CLUSTERS) s += argv[3] + string(" -c ") + argv[4]; else s += argv[3] + string(" ") + argv[4]; }else{ cout << "Invalid method " << method << endl; return 1; } cout << "Running: " << s << endl; int ret = exec(s).retCode; if(ret != 0) cout << "Method failed with error: " << ret << endl; return ret != 0; } }else if(command == "reorder"){ if(argc < 5){ cout << "Usage: ./fhgc " << command << endl; cout << " reorder <dataset-in> <dataset-out> <indexes>" << endl; return 1; }else{ string s = WG_SRC + "transform.sh " + argv[2] + " " + argv[3] + " " + argv[4]; return exec(s).retCode; } }else if(command == "compare-clusters"){ if(argc < 4){ cout << "Usage: ./fhgc compare-clusters" << endl << " compare-clusters <cluster-file-1> <cluster-file-2>" << endl; return 1; }else{ string s = WG_SRC + "compareClusters " + argv[2] + " " + argv[3]; if(argc >= 5) s += string(" ") + argv[4]; cout << s << endl; return exec(s).retCode; } }else if(command == "compare-clusters-list"){ if(argc < 4){ cout << "Usage: ./fhgc compare-clusters-list" << endl << " <file-list-1> <file-list-2> [<more-file-lists>]" << endl << "[options]:" << endl << " --matrix <method1> <method2>: print the results in matrix form. Accepted values for method1 and method2 are \"LLP\", \"Louvain\" or \"Faststep\" " << endl; return 1; } bool printMatrix = false; bool genImage = false; string method1, method2; vector<vector<string> > filelists; string args = "--nmi"; for(int i=2; i<argc; i++){ if(startswith(argv[i], "--")){ if(string(argv[i]) == "--matrix"){ if(i+2 >= argc){ cout << "--matrix option expects the method names" << endl; return 1; } cout << "Printing matrix of results for methods " << argv[i+1] << " and " << argv[i+2] << endl; method1 = argv[i+1]; method2 = argv[i+2]; i += 2; printMatrix = true; }else if(string(argv[i]) == "--jaccard"){ args = "--jaccard"; }else if(string(argv[i]) == "--nmi"){ args = "--nmi"; }else if(string(argv[i]) == "--all-jaccards"){ args = "--all-jaccards"; }else if(string(argv[i]) == "--onmi"){ args = "--onmi"; }else if(string(argv[i]) == "--image"){ genImage = true; } }else{ string s = string("ls -1 ") + argv[i]; FILE* f; f = popen(s.c_str(), "r"); const int SIZE = 1000; char str[SIZE+1]; filelists.resize(filelists.size()+1); while(fgets(str, SIZE, f) != NULL){ string fname(str); fname = fname.substr(0, fname.size()-1); filelists[filelists.size()-1].push_back(fname); } } } string s = WG_SRC + "comparisonMatrix " + args + " "; for(int i=0; i<(int)filelists.size(); i++){ s += "\""; for(int j=0; j<(int)filelists[i].size(); j++){ s += filelists[i][j]; if(j<(int)filelists[i].size() - 1) s += "|"; } s += "\""; s += " "; } if(!printMatrix){ return exec(s).retCode; }else{ ofstream out("/tmp/comp.txt"); out << method1 << " with " << method2 << endl; int r = exec(s, out).retCode; if(r != 0) return r; string outputImage = ""; if(genImage) outputImage = " --image"; return exec(string("python ") + WG_SRC + "genCompMatrix.py /tmp/comp.txt" + outputImage).retCode; } }else if(command == "size"){ if(argc < 3){ cout << "Usage: ./fhgc size" << endl << " size <dataset> [<more datasets>]" << endl; return 1; } bool showPercentage = false; string firstGraph; int firstSize = 1; vector<string> args; for(int i=2; i<argc; i++){ string arg = argv[i]; if(startswith(arg, "--")){ if(arg == "--percent") showPercentage = true; continue; } if(firstGraph == "") firstGraph = arg; args.push_back(arg); } for(int i=0; i<(int)args.size(); i++){ string arg = args[i]; string s = string("ls -s --block-size=KB ") + arg + string(".graph"); FILE* f; f = popen(s.c_str(), "r"); const int SIZE = 1000; char str[SIZE+1]; while(fgets(str, SIZE, f) != NULL){ stringstream ss(str); string s1, s2; ss >> s1 >> s2; int fSize; istringstream(s1.substr(0, s1.size()-2)) >> fSize; if(firstGraph == arg) firstSize = fSize; if(showPercentage && firstGraph != arg) cout << arg << ": " << s1 << " " << 100 * (1.0 - (double)fSize / firstSize) << endl; else cout << arg << ": " << s1 << endl; } } }else if(command == "clusterings2labels"){ if(argc < 5){ cout << "Usage: ./fhgc clusterings2labels" << endl << " clusterings2labels <dataset> <clusterings-prefix> <output-file> [--hierarchical]" << endl << " - Generates a reordering for the graph using external data, either clusterings with multiple levels of granularity or hierarchical clusterings" << endl << endl << "Parameters:" << endl << " - <clusterings-prefix>: the prefix of the files containing the clusterings," << "e.g., \"communities-\" which corresponds to \"communities-0.txt\", \"communities-1.txt\", \"communities-2.txt\", etc. (files must start at zero and any file suffix is accepted)" << endl << " - --hierarchical: assumes that the communities are hierarchical" << endl; return 1; } vector<string> files; string prefix = argv[3]; ls(string(" ") + prefix + "*", files); vector<string> ordered(files.size()); int useOrder = true; for(int i=0; i<(int)files.size(); i++){ cout << files[i] << endl; string e = files[i].substr(prefix.size(), string::npos); stringstream ss(e); int n; ss >> n; if(n < (int) ordered.size()) ordered[n] = files[i]; else useOrder = false; } for(int i=0; i<(int)ordered.size(); i++) if(ordered[i].size() == 0){ useOrder = false; break; } string clusters = ""; if(useOrder){ clusters = join(ordered, ","); cout << "Using ordered clusterings" << endl; }else{ clusters = join(files, ","); cout << "Can't use ordered clusterings" << endl; } string s = string("java -cp src/law+faststep/jars/runtime/'*':src/law+faststep/build it.unimi.dsi.law.graph.LayeredLabelPropagation ") + argv[2] + " " + argv[4] + " -l my-labels --inClusters " + clusters; exec(s); s = string("src/webgraph/labels2txt.sh ") + argv[4] + string("; mv ") + argv[4] + string(".txt ") + argv[4]; exec(s); }else if(command == "countClusters"){ if(argc < 3){ cout << "Usage: ./fhgc countClusters" << endl << " countClusters <clusters-file>" << endl; return 1; } return exec(WG_SRC + "countClusters " + argv[2]).retCode; }else if(command == "help"){ help(); }else{ cout << "Invalid command" << endl; help(); } return 0; }
29.882514
206
0.567249
michel94
b12ca9731247ecf15d7d44f07a1e866c26b20f90
680
cpp
C++
bindings/python/gtn/_criterions.cpp
vineelpratap/gtn-1
56a6359dbf5cc2a3855893d57166141703b592d9
[ "MIT" ]
75
2021-06-03T00:37:34.000Z
2022-03-27T08:07:15.000Z
bindings/python/gtn/_criterions.cpp
vineelpratap/gtn-1
56a6359dbf5cc2a3855893d57166141703b592d9
[ "MIT" ]
12
2021-08-21T13:23:24.000Z
2022-03-01T02:23:16.000Z
bindings/python/gtn/_criterions.cpp
vineelpratap/gtn-1
56a6359dbf5cc2a3855893d57166141703b592d9
[ "MIT" ]
8
2021-06-03T02:29:36.000Z
2022-03-12T00:40:14.000Z
/* * Copyright (c) Meta, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include "gtn/gtn.h" using namespace gtn; using namespace gtn::criterion; namespace py = pybind11; using namespace py::literals; PYBIND11_MODULE(_criterions, m) { m.def( "ctc_loss", [](const Graph& logProbs, const std::vector<int>& target, int blankIdx) { py::gil_scoped_release release; return ctcLoss(logProbs, target, blankIdx); }, "log_probs"_a, "target"_a, "blank_idx"_a); }
22.666667
79
0.670588
vineelpratap
b12d0c30b8dbb3e84da28fd4bfc94639e4da0f39
3,659
cxx
C++
panda/src/pgraph/depthWriteAttrib.cxx
cmarshall108/panda3d-python3
8bea2c0c120b03ec1c9fd179701fdeb7510bb97b
[ "PHP-3.0", "PHP-3.01" ]
null
null
null
panda/src/pgraph/depthWriteAttrib.cxx
cmarshall108/panda3d-python3
8bea2c0c120b03ec1c9fd179701fdeb7510bb97b
[ "PHP-3.0", "PHP-3.01" ]
null
null
null
panda/src/pgraph/depthWriteAttrib.cxx
cmarshall108/panda3d-python3
8bea2c0c120b03ec1c9fd179701fdeb7510bb97b
[ "PHP-3.0", "PHP-3.01" ]
null
null
null
/** * PANDA 3D SOFTWARE * Copyright (c) Carnegie Mellon University. All rights reserved. * * All use of this software is subject to the terms of the revised BSD * license. You should have received a copy of this license along * with this source code in a file named "LICENSE." * * @file depthWriteAttrib.cxx * @author drose * @date 2002-03-04 */ #include "depthWriteAttrib.h" #include "graphicsStateGuardianBase.h" #include "dcast.h" #include "bamReader.h" #include "bamWriter.h" #include "datagram.h" #include "datagramIterator.h" TypeHandle DepthWriteAttrib::_type_handle; int DepthWriteAttrib::_attrib_slot; /** * Constructs a new DepthWriteAttrib object. */ CPT(RenderAttrib) DepthWriteAttrib:: make(DepthWriteAttrib::Mode mode) { DepthWriteAttrib *attrib = new DepthWriteAttrib(mode); return return_new(attrib); } /** * Returns a RenderAttrib that corresponds to whatever the standard default * properties for render attributes of this type ought to be. */ CPT(RenderAttrib) DepthWriteAttrib:: make_default() { return return_new(new DepthWriteAttrib); } /** * */ void DepthWriteAttrib:: output(std::ostream &out) const { out << get_type() << ":"; switch (get_mode()) { case M_off: out << "off"; break; case M_on: out << "on"; break; } } /** * Intended to be overridden by derived DepthWriteAttrib types to return a * unique number indicating whether this DepthWriteAttrib is equivalent to the * other one. * * This should return 0 if the two DepthWriteAttrib objects are equivalent, a * number less than zero if this one should be sorted before the other one, * and a number greater than zero otherwise. * * This will only be called with two DepthWriteAttrib objects whose get_type() * functions return the same. */ int DepthWriteAttrib:: compare_to_impl(const RenderAttrib *other) const { const DepthWriteAttrib *ta = (const DepthWriteAttrib *)other; return (int)_mode - (int)ta->_mode; } /** * Intended to be overridden by derived RenderAttrib types to return a unique * hash for these particular properties. RenderAttribs that compare the same * with compare_to_impl(), above, should return the same hash; RenderAttribs * that compare differently should return a different hash. */ size_t DepthWriteAttrib:: get_hash_impl() const { size_t hash = 0; hash = int_hash::add_hash(hash, (int)_mode); return hash; } /** * Tells the BamReader how to create objects of type DepthWriteAttrib. */ void DepthWriteAttrib:: register_with_read_factory() { BamReader::get_factory()->register_factory(get_class_type(), make_from_bam); } /** * Writes the contents of this object to the datagram for shipping out to a * Bam file. */ void DepthWriteAttrib:: write_datagram(BamWriter *manager, Datagram &dg) { RenderAttrib::write_datagram(manager, dg); dg.add_int8(_mode); } /** * This function is called by the BamReader's factory when a new object of * type DepthWriteAttrib is encountered in the Bam file. It should create the * DepthWriteAttrib and extract its information from the file. */ TypedWritable *DepthWriteAttrib:: make_from_bam(const FactoryParams &params) { DepthWriteAttrib *attrib = new DepthWriteAttrib; DatagramIterator scan; BamReader *manager; parse_params(params, scan, manager); attrib->fillin(scan, manager); return attrib; } /** * This internal function is called by make_from_bam to read in all of the * relevant data from the BamFile for the new DepthWriteAttrib. */ void DepthWriteAttrib:: fillin(DatagramIterator &scan, BamReader *manager) { RenderAttrib::fillin(scan, manager); _mode = (Mode)scan.get_int8(); }
26.708029
78
0.738453
cmarshall108
b12dc07fbd8023ba7e19db7eddedc097b3076b8d
149
hpp
C++
source/GcLib/directx/DxConstant.hpp
Mugenri/Touhou-Danmakufu-ph3sx-2
4ab7e40682341ff41d7467b83bb64c9a669a6064
[ "MIT" ]
null
null
null
source/GcLib/directx/DxConstant.hpp
Mugenri/Touhou-Danmakufu-ph3sx-2
4ab7e40682341ff41d7467b83bb64c9a669a6064
[ "MIT" ]
null
null
null
source/GcLib/directx/DxConstant.hpp
Mugenri/Touhou-Danmakufu-ph3sx-2
4ab7e40682341ff41d7467b83bb64c9a669a6064
[ "MIT" ]
null
null
null
#pragma once #include "../pch.h" #include "../gstd/GstdLib.hpp" #include "DxTypes.hpp" #if defined(DNH_PROJ_EXECUTOR) #include "Vertex.hpp" #endif
14.9
30
0.711409
Mugenri
b12f7a98a0c4855383f99c4281ec499021df7659
6,307
cc
C++
tensorflow/compiler/xla/service/memory_space_assignment_utils.cc
EricRemmerswaal/tensorflow
141ff27877579c81a213fa113bd1b474c1749aca
[ "Apache-2.0" ]
190,993
2015-11-09T13:17:30.000Z
2022-03-31T23:05:27.000Z
tensorflow/compiler/xla/service/memory_space_assignment_utils.cc
EricRemmerswaal/tensorflow
141ff27877579c81a213fa113bd1b474c1749aca
[ "Apache-2.0" ]
48,461
2015-11-09T14:21:11.000Z
2022-03-31T23:17:33.000Z
tensorflow/compiler/xla/service/memory_space_assignment_utils.cc
EricRemmerswaal/tensorflow
141ff27877579c81a213fa113bd1b474c1749aca
[ "Apache-2.0" ]
104,981
2015-11-09T13:40:17.000Z
2022-03-31T19:51:54.000Z
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/memory_space_assignment_utils.h" #include "tensorflow/compiler/xla/service/hlo_casting_utils.h" #include "tensorflow/compiler/xla/service/hlo_instructions.h" namespace xla { bool MemorySpaceAssignmentUtils::IsValueAllowedInAlternateMemory( const HloValue* value) { // If the buffer is a tuple, don't use this algorithm for now. The buffers // that are pointed to by the tuple will still use this algorithm. Because // tuples are cheap to place in the alternate memory (they are just pointers) // we don't need to use prefetch/evict logic. if (value->shape().IsTuple()) { VLOG(4) << "Keeping value " << value->ToShortString() << " in default mem because it is a tuple."; return false; } // Don't place scalars in the alternate memory. if (ShapeUtil::IsEffectiveScalar(value->shape())) { VLOG(4) << "Keeping value " << value->ToShortString() << " in default mem because it is a scalar."; return false; } // The semantics of TupleSelect are weird: TupleSelect doesn't define a // buffer, but just forwards the buffers in the either left or right side. // This means the two different inputs to TupleSelect must not alias, yet they // should be allocated in the same memory space, and both buffers must be kept // alive for the entire live range of TupleSelect. Instead, just don't // allocate TupleSelect in the alternate memory space. // TODO(berkin): Not allocating add-dependencies either since they need to be // treated specially. We should revisit this later. for (const HloPosition& position : value->positions()) { if (position.instruction->opcode() == HloOpcode::kTupleSelect || position.instruction->opcode() == HloOpcode::kAddDependency) { VLOG(4) << "Keeping value " << value->ToShortString() << " in default mem because it has a tuple-select or " << "add-dependency position."; return false; } } // Send and Recv HLOs return a request identifier. These should not be // allocated in the alternate memory. for (const HloPosition& position : value->positions()) { if ((position.instruction->opcode() == HloOpcode::kSend || position.instruction->opcode() == HloOpcode::kRecv) && DynCast<HloSendRecvInstruction>(position.instruction) ->is_host_transfer()) { // TODO(berkin): Host transfers using alternate memory space doesn't seem // to work at the moment. VLOG(4) << "Keeping value " << value->ToShortString() << " in default mem because it is a send/recv buffer used for " "host transfer."; return false; } if (auto* custom_call = DynCast<HloCustomCallInstruction>(position.instruction)) { for (const auto& pair : custom_call->output_to_operand_aliasing()) { if (position.index == pair.first) { VLOG(4) << "Keeping value " << value->ToShortString() << " in default mem because it is a custom-call output that " "aliases an operand buffer."; return false; } } } } return true; } bool MemorySpaceAssignmentUtils::IsIntervalAllowedInAlternateMemory( const GlobalDecreasingSizeBestFitHeap<HloValue>::BufferInterval& interval) { return IsValueAllowedInAlternateMemory(interval.buffer) && absl::c_all_of(interval.colocations, IsValueAllowedInAlternateMemory); } /*static*/ void MemorySpaceAssignmentUtils::HoistConstantOperations( HloModule& module) { CHECK(module.has_schedule()); HloSchedule& schedule = module.schedule(); for (const HloComputation* computation : module.MakeNonfusionComputations()) { CHECK(schedule.is_computation_scheduled(computation)); const HloInstructionSequence& sequence = schedule.sequence(computation); // Conservatively don't modify the schedule if any instruction has a control // successor or predecessor on a constant op. Computations with these // dependencies should be very rare anyway. bool contains_constant_successor_or_predecessors = false; for (HloInstruction* instruction : sequence.instructions()) { if (instruction->opcode() == HloOpcode::kConstant) { contains_constant_successor_or_predecessors |= !instruction->control_predecessors().empty(); contains_constant_successor_or_predecessors |= !instruction->control_successors().empty(); } else { auto is_constant = [](const HloInstruction* inst) { return inst->opcode() == HloOpcode::kConstant; }; contains_constant_successor_or_predecessors |= absl::c_find_if(instruction->control_predecessors(), is_constant) != instruction->control_predecessors().end(); contains_constant_successor_or_predecessors |= absl::c_find_if(instruction->control_successors(), is_constant) != instruction->control_successors().end(); } } if (contains_constant_successor_or_predecessors) { continue; } HloInstructionSequence new_sequence; for (HloInstruction* instruction : sequence.instructions()) { if (instruction->opcode() == HloOpcode::kConstant) { new_sequence.push_back(instruction); } } for (HloInstruction* instruction : sequence.instructions()) { if (instruction->opcode() != HloOpcode::kConstant) { new_sequence.push_back(instruction); } } CHECK_EQ(new_sequence.size(), sequence.size()); schedule.set_sequence(computation, new_sequence); } } } // namespace xla
42.904762
80
0.683051
EricRemmerswaal
b1325f3e14933c34ac5c16dba6e10221ff2415eb
18,257
cpp
C++
tests/record/test_array_fcall_method.cpp
hachetman/systemc-compiler
0cc81ace03336d752c0146340ff5763a20e3cefd
[ "Apache-2.0" ]
86
2020-10-23T15:59:47.000Z
2022-03-28T18:51:19.000Z
tests/record/test_array_fcall_method.cpp
hachetman/systemc-compiler
0cc81ace03336d752c0146340ff5763a20e3cefd
[ "Apache-2.0" ]
18
2020-12-14T13:11:26.000Z
2022-03-14T05:34:20.000Z
tests/record/test_array_fcall_method.cpp
hachetman/systemc-compiler
0cc81ace03336d752c0146340ff5763a20e3cefd
[ "Apache-2.0" ]
17
2020-10-29T16:19:43.000Z
2022-03-11T09:51:05.000Z
/****************************************************************************** * Copyright (c) 2020, Intel Corporation. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception. * *****************************************************************************/ #include "sct_assert.h" #include "systemc.h" #include <iostream> using namespace sc_core; // Record array elements as function parameters class A : public sc_module { public: sc_in<sc_uint<2>> a{"a"}; sc_signal<sc_uint<2>> as{"as"}; sc_in<sc_int<2>> as_i{"as_i"}; sc_signal<int> s{"s"}; SC_CTOR(A) { for (int i = 0; i < 3; i++) { spp[i] = new sc_signal<int>(""); } SC_METHOD(rec_arr_elem_func_param_val); sensitive << s; SC_METHOD(rec_arr_elem_func_param_val2); sensitive << s; SC_METHOD(rec_arr_elem_func_param_val3); sensitive << s; SC_METHOD(rec_arr_elem_func_param_ref); sensitive << s; SC_METHOD(rec_arr_elem_func_param_ref2); sensitive << s; SC_METHOD(rec_arr_elem_func_param_ref3); sensitive << s; SC_METHOD(arr_elem_in_index); sensitive << s << srr[0] << *spp[0]; // TODO: Fix me, #99 //SC_METHOD(rec_arr_elem_in_index); //sensitive << s; /*SC_METHOD(record_var_if); sensitive << a << as << as_i << s; SC_METHOD(record_var_if_bitwise); sensitive << a << as << as_i << s; SC_METHOD(record_var_if_arith); sensitive << a << as << as_i << s;*/ } //--------------------------------------------------------------------------- struct MyRec { sc_int<2> a; sc_uint<4> b; }; void f1(MyRec par) { int k = par.b; } int f1_two(MyRec par1, MyRec par2) { return (par1.b + par2.b); } // Record array element as function parameter by value void rec_arr_elem_func_param_val() { MyRec sr; f1(sr); MyRec sra[3]; f1(sra[1]); int i = s.read(); f1(sra[i]); } // Two record array elements as function parameters by value void rec_arr_elem_func_param_val2() { MyRec xr, yr; f1_two(xr, yr); MyRec xra[3]; MyRec yra[2]; f1_two(xra[2], yra[1]); f1_two(xra[2], xra[1]); f1_two(xra[2], xra[2]); f1_two(xra[2], yr); int i = f1_two(yr, xra[1]); } // Record array element at unknown index as function parameters by value void rec_arr_elem_func_param_val3() { int i = s.read(); MyRec qr; MyRec qra[3]; f1_two(qra[i], qra[i]); f1_two(qr, qra[i+1]); if (i) { f1_two(qra[i-1], qr); } else { if (i == 1) f1(qra[i]); } } //----------------------------------------------------------------------------- void f2(MyRec& par) { int k = par.b; } void f2_two(MyRec& par1, MyRec& par2) { int k = par1.b + par2.b; } int f2_two_cond(MyRec& par1, bool a, MyRec& par2) { return (a ? par1.b : par2.b); } // Record array element as function parameter by reference void rec_arr_elem_func_param_ref() { MyRec vr[3]; f2(vr[1]); int i = s.read(); f2(vr[i]); } // Two record array elements as function parameters by reference void rec_arr_elem_func_param_ref2() { MyRec er[3]; MyRec fr; f2_two(fr, er[2]); f2_two(er[1], er[2]); f2_two(er[1], er[1]); bool a; int i = s.read(); a = f2_two_cond(er[i], true, fr); f2_two_cond(er[i+1], a, er[i+1]); } int f3_val(sc_uint<4> par) { return (par+1); } int f3_ref(sc_uint<4>& par) { par++; return par; } // Record array elements as function parameters in IF, passed by reference void rec_arr_elem_func_param_ref3() { MyRec err[3]; MyRec frr; int i = s.read(); frr.a = f3_val(err[i].b); frr.a = f3_ref(err[i+1].b); f2_two(err[i], err[frr.a]); } // Use record array element as index for the same array sc_signal<int> srr[3]; sc_signal<int>* spp[3]; void arr_elem_in_index() { int i = s.read(); int irr[3]; irr[irr[1]] = 1; irr[irr[i]] = irr[i+1]; srr[srr[1]] = 1; srr[srr[i]] = srr[srr[i+1]+1]; *spp[spp[1]->read()] = 1; *spp[*spp[1]] = 1; *spp[*spp[i]] = *spp[i+*spp[i+1]]; } void rec_arr_elem_in_index() { MyRec err[3]; err[err[1].b].a = 1; } //----------------------------------------------------------------------------- // Function with records struct Simple { int a; sc_uint<2> b; Simple(): a(1){ } int geta(){ return a; } void seta(int bval){ a = bval; } }; struct Simple_arith { sc_uint<32> a; sc_uint<16> b; Simple_arith(): a(30), b(15){ } sc_uint<32> geta(){ return a; } sc_uint<32> getaplusb(){ return a + b; } sc_uint<32> getaminusb(){ return a - b; } sc_uint<32> getamultb(){ return a * b; } sc_uint<32> getadivb(){ return a / b; } sc_uint<32> getamodb(){ return a % b; } void seta(sc_uint<32> aval){ a = aval; } void setb(sc_uint<16> bval){ b = bval; } }; struct Simple_bitwise { sc_uint<32> a; sc_uint<16> b; Simple_bitwise(): a(30), b(15){ } sc_uint<32> geta(){ return a; } void seta(sc_uint<32> aval){ a = aval; } void setb(sc_uint<16> bval){ b = bval; } sc_uint<32> getaorb(){ return a | b; } sc_uint<32> getaandb(){ return a & b; } sc_uint<32> getnota(){ return !a; } sc_uint<32> getaxorb(){ return a ^ b; } sc_uint<32> getalorb(){ return a || b; } sc_uint<32> getalandb(){ return a && b; } }; Simple rec[16]; Simple_arith reca[16]; Simple_bitwise recb[16]; void record_var_if() { int num1 = 0; int num2 = 1; int val1 = 0; if (num1==0) { rec[num1].seta(val1); } else { rec[num1].seta(1); } if (num2!=1) { rec[num2].seta(0); } else { rec[num2].seta(1); } //cout << "rec[0] = "<< rec[0].a << endl; //cout << "rec[1] = "<< rec[1].a << endl; sct_assert_const(rec[0].geta()==0); sct_assert_const(rec[1].geta()==1); if (as_i.read()==0) { rec[as_i.read()].seta(35); rec[s.read()].seta(45); } else { rec[as_i.read()].seta(25); rec[s.read()].seta(50); } } void record_var_if_arith() { reca[0].seta(16); reca[0].setb(5); sct_assert_const(reca[0].getaplusb()== 21); sct_assert_const(reca[0].getaminusb()== 11); sct_assert_const(reca[0].getamultb()== 80); sct_assert_const(reca[0].getadivb()== 3); sct_assert_const(reca[0].getamodb()== 1); for(int i=0; i<17; i++) { reca[i].seta(i*3); reca[i].setb(i*2+2); //cout << "sc_assert (reca[" << i << "].getaplusb() == " << reca[i].getaplusb() << ");" << endl; //cout << "sc_assert (reca[" << i << "].getaminusb() == " << reca[i].getaminusb() << ");" << endl; //cout << "sc_assert (reca[" << i << "].getamultb() == " << reca[i].getamultb() << ");" << endl; //cout << "sc_assert (reca[" << i << "].getadivb() == " << reca[i].getadivb() << ");" << endl; //cout << "sc_assert (reca[" << i << "].getamodb() == " << reca[i].getamodb() << ");" << endl; } sc_assert (reca[0].getaplusb() == 2); sc_assert (reca[0].getaminusb() == 4294967294); sc_assert (reca[0].getamultb() == 0); sc_assert (reca[0].getadivb() == 0); sc_assert (reca[0].getamodb() == 0); sc_assert (reca[1].getaplusb() == 7); sc_assert (reca[1].getaminusb() == 4294967295); sc_assert (reca[1].getamultb() == 12); sc_assert (reca[1].getadivb() == 0); sc_assert (reca[1].getamodb() == 3); sc_assert (reca[2].getaplusb() == 12); sc_assert (reca[2].getaminusb() == 0); sc_assert (reca[2].getamultb() == 36); sc_assert (reca[2].getadivb() == 1); sc_assert (reca[2].getamodb() == 0); sc_assert (reca[3].getaplusb() == 17); sc_assert (reca[3].getaminusb() == 1); sc_assert (reca[3].getamultb() == 72); sc_assert (reca[3].getadivb() == 1); sc_assert (reca[3].getamodb() == 1); sc_assert (reca[4].getaplusb() == 22); sc_assert (reca[4].getaminusb() == 2); sc_assert (reca[4].getamultb() == 120); sc_assert (reca[4].getadivb() == 1); sc_assert (reca[4].getamodb() == 2); sc_assert (reca[5].getaplusb() == 27); sc_assert (reca[5].getaminusb() == 3); sc_assert (reca[5].getamultb() == 180); sc_assert (reca[5].getadivb() == 1); sc_assert (reca[5].getamodb() == 3); sc_assert (reca[6].getaplusb() == 32); sc_assert (reca[6].getaminusb() == 4); sc_assert (reca[6].getamultb() == 252); sc_assert (reca[6].getadivb() == 1); sc_assert (reca[6].getamodb() == 4); sc_assert (reca[7].getaplusb() == 37); sc_assert (reca[7].getaminusb() == 5); sc_assert (reca[7].getamultb() == 336); sc_assert (reca[7].getadivb() == 1); sc_assert (reca[7].getamodb() == 5); sc_assert (reca[8].getaplusb() == 42); sc_assert (reca[8].getaminusb() == 6); sc_assert (reca[8].getamultb() == 432); sc_assert (reca[8].getadivb() == 1); sc_assert (reca[8].getamodb() == 6); sc_assert (reca[9].getaplusb() == 47); sc_assert (reca[9].getaminusb() == 7); sc_assert (reca[9].getamultb() == 540); sc_assert (reca[9].getadivb() == 1); sc_assert (reca[9].getamodb() == 7); sc_assert (reca[10].getaplusb() == 52); sc_assert (reca[10].getaminusb() == 8); sc_assert (reca[10].getamultb() == 660); sc_assert (reca[10].getadivb() == 1); sc_assert (reca[10].getamodb() == 8); sc_assert (reca[11].getaplusb() == 57); sc_assert (reca[11].getaminusb() == 9); sc_assert (reca[11].getamultb() == 792); sc_assert (reca[11].getadivb() == 1); sc_assert (reca[11].getamodb() == 9); sc_assert (reca[12].getaplusb() == 62); sc_assert (reca[12].getaminusb() == 10); sc_assert (reca[12].getamultb() == 936); sc_assert (reca[12].getadivb() == 1); sc_assert (reca[12].getamodb() == 10); sc_assert (reca[13].getaplusb() == 67); sc_assert (reca[13].getaminusb() == 11); sc_assert (reca[13].getamultb() == 1092); sc_assert (reca[13].getadivb() == 1); sc_assert (reca[13].getamodb() == 11); sc_assert (reca[14].getaplusb() == 72); sc_assert (reca[14].getaminusb() == 12); sc_assert (reca[14].getamultb() == 1260); sc_assert (reca[14].getadivb() == 1); sc_assert (reca[14].getamodb() == 12); sc_assert (reca[15].getaplusb() == 77); sc_assert (reca[15].getaminusb() == 13); sc_assert (reca[15].getamultb() == 1440); sc_assert (reca[15].getadivb() == 1); sc_assert (reca[15].getamodb() == 13); sc_assert (reca[16].getaplusb() == 82); sc_assert (reca[16].getaminusb() == 14); sc_assert (reca[16].getamultb() == 1632); sc_assert (reca[16].getadivb() == 1); sc_assert (reca[16].getamodb() == 14); } void record_var_if_bitwise() { for(int i=0; i<17; i++) { recb[i].seta(i*3); recb[i].setb(i*2+2); //cout << "sc_assert (recb[" << i << "].getaorb() == " << recb[i].getaorb() << ");" << endl; //cout << "sc_assert (recb[" << i << "].getaandb() == " << recb[i].getaandb() << ");" << endl; //cout << "sc_assert (recb[" << i << "].getnota() == " << recb[i].getnota() << ");" << endl; //cout << "sc_assert (recb[" << i << "].getaxorb() == " << recb[i].getaxorb() << ");" << endl; //cout << "sc_assert (recb[" << i << "].getalorb() == " << recb[i].getalorb() << ");" << endl; //cout << "sc_assert (recb[" << i << "].getalandb() == " << recb[i].getalandb() << ");" << endl; } sc_assert (recb[0].getaorb() == 2); sc_assert (recb[0].getaandb() == 0); sc_assert (recb[0].getnota() == 1); sc_assert (recb[0].getaxorb() == 2); sc_assert (recb[0].getalorb() == 1); sc_assert (recb[0].getalandb() == 0); sc_assert (recb[1].getaorb() == 7); sc_assert (recb[1].getaandb() == 0); sc_assert (recb[1].getnota() == 0); sc_assert (recb[1].getaxorb() == 7); sc_assert (recb[1].getalorb() == 1); sc_assert (recb[1].getalandb() == 1); sc_assert (recb[2].getaorb() == 6); sc_assert (recb[2].getaandb() == 6); sc_assert (recb[2].getnota() == 0); sc_assert (recb[2].getaxorb() == 0); sc_assert (recb[2].getalorb() == 1); sc_assert (recb[2].getalandb() == 1); sc_assert (recb[3].getaorb() == 9); sc_assert (recb[3].getaandb() == 8); sc_assert (recb[3].getnota() == 0); sc_assert (recb[3].getaxorb() == 1); sc_assert (recb[3].getalorb() == 1); sc_assert (recb[3].getalandb() == 1); sc_assert (recb[4].getaorb() == 14); sc_assert (recb[4].getaandb() == 8); sc_assert (recb[4].getnota() == 0); sc_assert (recb[4].getaxorb() == 6); sc_assert (recb[4].getalorb() == 1); sc_assert (recb[4].getalandb() == 1); sc_assert (recb[5].getaorb() == 15); sc_assert (recb[5].getaandb() == 12); sc_assert (recb[5].getnota() == 0); sc_assert (recb[5].getaxorb() == 3); sc_assert (recb[5].getalorb() == 1); sc_assert (recb[5].getalandb() == 1); sc_assert (recb[6].getaorb() == 30); sc_assert (recb[6].getaandb() == 2); sc_assert (recb[6].getnota() == 0); sc_assert (recb[6].getaxorb() == 28); sc_assert (recb[6].getalorb() == 1); sc_assert (recb[6].getalandb() == 1); sc_assert (recb[7].getaorb() == 21); sc_assert (recb[7].getaandb() == 16); sc_assert (recb[7].getnota() == 0); sc_assert (recb[7].getaxorb() == 5); sc_assert (recb[7].getalorb() == 1); sc_assert (recb[7].getalandb() == 1); sc_assert (recb[8].getaorb() == 26); sc_assert (recb[8].getaandb() == 16); sc_assert (recb[8].getnota() == 0); sc_assert (recb[8].getaxorb() == 10); sc_assert (recb[8].getalorb() == 1); sc_assert (recb[8].getalandb() == 1); sc_assert (recb[9].getaorb() == 31); sc_assert (recb[9].getaandb() == 16); sc_assert (recb[9].getnota() == 0); sc_assert (recb[9].getaxorb() == 15); sc_assert (recb[9].getalorb() == 1); sc_assert (recb[9].getalandb() == 1); sc_assert (recb[10].getaorb() == 30); sc_assert (recb[10].getaandb() == 22); sc_assert (recb[10].getnota() == 0); sc_assert (recb[10].getaxorb() == 8); sc_assert (recb[10].getalorb() == 1); sc_assert (recb[10].getalandb() == 1); sc_assert (recb[11].getaorb() == 57); sc_assert (recb[11].getaandb() == 0); sc_assert (recb[11].getnota() == 0); sc_assert (recb[11].getaxorb() == 57); sc_assert (recb[11].getalorb() == 1); sc_assert (recb[11].getalandb() == 1); sc_assert (recb[12].getaorb() == 62); sc_assert (recb[12].getaandb() == 0); sc_assert (recb[12].getnota() == 0); sc_assert (recb[12].getaxorb() == 62); sc_assert (recb[12].getalorb() == 1); sc_assert (recb[12].getalandb() == 1); sc_assert (recb[13].getaorb() == 63); sc_assert (recb[13].getaandb() == 4); sc_assert (recb[13].getnota() == 0); sc_assert (recb[13].getaxorb() == 59); sc_assert (recb[13].getalorb() == 1); sc_assert (recb[13].getalandb() == 1); sc_assert (recb[14].getaorb() == 62); sc_assert (recb[14].getaandb() == 10); sc_assert (recb[14].getnota() == 0); sc_assert (recb[14].getaxorb() == 52); sc_assert (recb[14].getalorb() == 1); sc_assert (recb[14].getalandb() == 1); sc_assert (recb[15].getaorb() == 45); sc_assert (recb[15].getaandb() == 32); sc_assert (recb[15].getnota() == 0); sc_assert (recb[15].getaxorb() == 13); sc_assert (recb[15].getalorb() == 1); sc_assert (recb[15].getalandb() == 1); sc_assert (recb[16].getaorb() == 50); sc_assert (recb[16].getaandb() == 32); sc_assert (recb[16].getnota() == 0); sc_assert (recb[16].getaxorb() == 18); sc_assert (recb[16].getalorb() == 1); sc_assert (recb[16].getalandb() == 1); } }; class B_top : public sc_module { public: sc_signal<sc_uint<2>> a{"a"}; sc_signal<sc_uint<2>> as{"as"}; sc_signal<sc_int<2>> as_i{"as_i"}; A a_mod{"a_mod"}; SC_CTOR(B_top) { a_mod.a(a); a_mod.as_i(as_i); } }; int sc_main(int argc, char *argv[]) { B_top b_mod{"b_mod"}; sc_start(); return 0; }
31.208547
110
0.47872
hachetman
b136570926f748f7c9fc27a0a1d4efb792bc26ee
3,191
hpp
C++
hpp/Folder.impl.hpp
Ivy233/simple_diff
970bf8a0a624fc89b9c016fab44a87162feb2465
[ "MIT" ]
1
2021-11-30T07:47:52.000Z
2021-11-30T07:47:52.000Z
hpp/Folder.impl.hpp
Ivy233/simple_diff
970bf8a0a624fc89b9c016fab44a87162feb2465
[ "MIT" ]
null
null
null
hpp/Folder.impl.hpp
Ivy233/simple_diff
970bf8a0a624fc89b9c016fab44a87162feb2465
[ "MIT" ]
null
null
null
/* * File name: Folder.impl.hpp * Description: 文件夹类,用于捕捉所有文件夹下的非隐藏文件 * Author: 王锦润 * Version: 2 * Date: 2019.6.11 * History: 此程序被纳入git,可以直接使用git查询。 */ //防卫式声明,必须要有 //就算没有重复包含也建议有,这是代码习惯 #ifndef _FOLDER_IMPL_HPP_ #define _FOLDER_IMPL_HPP_ #include "Folder.hpp" #include <algorithm> #include <iostream> using std::cout; using std::endl; /* * Function: 构造函数 * Description: 构建文件夹,并搜索所有在文件夹下的文件 * Input: 文件路径 * Calls: _M_update_base, _M_update_ext */ Folder::Folder(const string &filedir) { _M_only_file = 0; //首先清空唯一文件属性 _M_update_base(filedir); //然后尝试更新文件夹路径 if (_M_only_file == 0 && _M_base_dir.size()) //如果更新成功,更新所有文件 _M_update_ext(""); //此处排序复杂度接近于线性,主要原因在于操作系统给出的文件句柄顺序 std::sort(_M_ext_dirs.begin(), _M_ext_dirs.end()); //排序使得有集合性质,方便调用差集,交集等集合运算 } /* * Function: print_everything * Description: 打印所有的文件路径 */ void Folder::print_everything() { cout << _M_only_file << endl; cout << _M_base_dir << endl; for (string ext_dir : _M_ext_dirs) cout << ext_dir << endl; } /* * Function: _M_update_base * Description: 检验文件/文件夹,如果为单个文件则同时更新basedir和extdir,如果不是则只更新basedir * Input: 文件路径filedir */ void Folder::_M_update_base(const string &filedir) { //首先清空文件属性 _M_base_dir.clear(); _M_ext_dirs.clear(); _finddata_t fileinfo; //C的结构体,用于访问文件系统 long hfile = 0; //文件句柄 if ((hfile = _findfirst(filedir.c_str(), &fileinfo)) != -1) //如果文件存在 { //如果是文件 if (fileinfo.attrib & _A_ARCH) { size_t pos = std::max(filedir.find_last_of('/') + 1, filedir.find_last_of('\\') + 1); _M_base_dir = filedir.substr(0, pos); //basedir更新 _M_ext_dirs.push_back(filedir.substr(pos)); //更新extdir _M_only_file = 1; } else if (fileinfo.attrib & _A_SUBDIR) { _M_base_dir = filedir; //更新文件夹 if (_M_base_dir.back() != '/' && _M_base_dir.back() != '\\') _M_base_dir.push_back('\\'); //如果没有则自动补全 } } //如果访问不到则啥都不做 else cout << "Wrong file or folder" << endl; } /* * Function: _M_update_base * Description: 检验文件/文件夹,如果为单个文件则同时更新basedir和extdir,如果不是则只更新basedir * Input: 文件路径filedir */ void Folder::_M_update_ext(const string &dir) { _finddata_t fileinfo; long hfile = 0; string p; if ((hfile = _findfirst(p.assign(_M_base_dir).append(dir).append("*").c_str(), &fileinfo)) != -1) //如果找到内容 { //按照文件更新 do { //如果是非隐藏文件夹则递归更新 if ((fileinfo.attrib & _A_SUBDIR) && (fileinfo.attrib & _A_HIDDEN) == 0) { //.和..是两个必备文件夹,..会递归到上层,需要避开 if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0) _M_update_ext(p.assign(dir).append(fileinfo.name).append("\\")); } //如果是文件则加入文件 else if ((fileinfo.attrib & _A_HIDDEN) == 0) _M_ext_dirs.push_back(p.assign(dir).append(fileinfo.name)); } while (_findnext(hfile, &fileinfo) == 0); //句柄的用处 } } #endif
30.390476
110
0.581636
Ivy233
b1377c40c3953e49eecbffa5f35254c03970b423
1,096
inl
C++
include/util/driver/value/size.inl
izenecloud/izenelib
9d5958100e2ce763fc75f27217adf982d7c9d902
[ "Apache-2.0" ]
31
2015-03-03T19:13:42.000Z
2020-09-03T08:11:56.000Z
include/util/driver/value/size.inl
izenecloud/izenelib
9d5958100e2ce763fc75f27217adf982d7c9d902
[ "Apache-2.0" ]
1
2016-12-24T00:12:11.000Z
2016-12-24T00:12:11.000Z
include/util/driver/value/size.inl
izenecloud/izenelib
9d5958100e2ce763fc75f27217adf982d7c9d902
[ "Apache-2.0" ]
8
2015-09-06T01:55:21.000Z
2021-12-20T02:16:13.000Z
#ifdef IZENELIB_DRIVER_VALUE_INLINE /** * @file izenelib/driver/value/size.inl * @author Ian Yang * @date Created <2010-06-08 11:31:29> * @brief Gets size of a value */ namespace izenelib { namespace driver { namespace detail { class ValueSizeVisitor : public boost::static_visitor<std::size_t> { public: typedef std::size_t size_type; /// @brief Returns 1 for all singular value template<typename T> size_type operator()(const T&) const { return 1; } /// @brief Returns 0 for Null size_type operator()(const Value::NullType&) const { return 0; } /// @brief Gets size of Array size_type operator()(const Value::ArrayType& value) const { return value.size(); } /// @brief Gets size of Object size_type operator()(const Value::ObjectType& value) const { return value.size(); } }; } // namespace detail std::size_t Value::size() const { return boost::apply_visitor(detail::ValueSizeVisitor(), value_); } }} // namespace izenelib::driver #endif // IZENELIB_DRIVER_VALUE_INLINE
20.296296
68
0.653285
izenecloud
b137e61bee75558bc1d3d25813a51c4b1b82a236
667
cpp
C++
Projects/PBINFO/Problema 4/main.cpp
Bengo923/Visual-Studio
863a273644b291c311d299bd5c7c4faf9db2d30e
[ "MIT" ]
1
2019-11-05T17:56:19.000Z
2019-11-05T17:56:19.000Z
Projects/PBINFO/Problema 4/main.cpp
Bengo923/PBINFO
863a273644b291c311d299bd5c7c4faf9db2d30e
[ "MIT" ]
null
null
null
Projects/PBINFO/Problema 4/main.cpp
Bengo923/PBINFO
863a273644b291c311d299bd5c7c4faf9db2d30e
[ "MIT" ]
null
null
null
// Problema 18 - Fisa Gradinariu (TEMA) #include "pch.h" #include "fstream" #include "iostream" using namespace std; // ifstream fin("date.in"); // ofstream fout("date.out"); int index = 1, v[101], suma1, suma2, aux1, aux2; int main() { int x; cin >> x; while (x != 0) { v[index] = x; index++; cin >> x; } for (int i = 1; i < index; i++) { suma1 = 0; suma2 = 0; aux1 = v[i]; aux2 = v[i + 1]; while (aux1) { suma1 = suma1 + aux1 % 10; aux1 = aux1 / 10; } while (aux2) { suma2 = suma2 + aux2 % 10; aux2 = aux2 / 10; } if (suma1 % 2 == 0 && suma2 % 2 == 1) { cout << v[i] << " " << v[i + 1] << endl; } } return 0; }
15.511628
48
0.503748
Bengo923
b139cd6dfa8267237cb80df9cc1f4f060750af3e
8,727
cpp
C++
translit_handler.cpp
EzerIT/ETCBC4BibleOL
06bef9600a42dc17d8f0b2210492c8bce8bed558
[ "MIT" ]
null
null
null
translit_handler.cpp
EzerIT/ETCBC4BibleOL
06bef9600a42dc17d8f0b2210492c8bce8bed558
[ "MIT" ]
null
null
null
translit_handler.cpp
EzerIT/ETCBC4BibleOL
06bef9600a42dc17d8f0b2210492c8bce8bed558
[ "MIT" ]
null
null
null
/* Copyright © 2017 Ezer IT Consulting. * Released under an MIT License. */ #include <deque> #include <map> #include <string> #include <iostream> #include "util.hpp" #include "translit_handler.hpp" #include "hebrew_transliterator.hpp" using namespace std; struct translit_strings { string g_word_translit; string g_word_nopunct_translit; string g_suffix_translit; string g_lex_translit; string g_prs_translit; string g_vbs_translit; string g_pfm_translit; string g_vbe_translit; string g_nme_translit; string g_uvf_translit; string g_voc_lex_translit; string qere_translit; }; class translit_handler : public handler { public: translit_handler(); virtual void list_features(set<string>&) override; virtual void prepare_object(map<string,string>&) override; virtual void finish_prepare() override; virtual string define_features() override; virtual string update_object(const map<string,string>&) override; private: // Transliteration context. We need five words (two before and two after the current one) deque<map<string,string>> words; map<int, translit_strings> transliterations; // Indexed by self void chk_o(const map<string,string> * fmapp); }; shared_ptr<handler> make_translit_handler() { return shared_ptr<handler>{new translit_handler}; } translit_handler::translit_handler() { // Start by providing two empty words of context words.emplace_back(map<string,string>{{"g_word_utf8",""},{"g_suffix_utf8",""}}); words.emplace_back(map<string,string>{{"g_word_utf8",""},{"g_suffix_utf8",""}}); } void translit_handler::list_features(set<string>& req) { initialize_translit_rules(); initialize_translit_verbrules(); req.insert({"g_prs_utf8", "g_vbs_utf8", "g_pfm_utf8", "g_vbe_utf8", "g_nme_utf8", "g_uvf_utf8", "g_word", "g_suffix_utf8", "g_word_utf8", "g_voc_lex_utf8", "qere_utf8", "lex", "sp", "ps", "gn", "nu", "vs", "vt"}); } void translit_handler::chk_o(const map<string,string> * fmapp) { if (!fmapp) // Running from finish_prepare(). Add final empty word of context words.emplace_back(map<string,string>{{"g_word_utf8",""},{"g_suffix_utf8",""}}); else words.emplace_back(*fmapp); if (words.size()==5) { // Now we can transliterate the middle word bool ketiv = !words[2].at("qere_utf8").empty(); translit_strings translits; translits.g_suffix_translit = suffix_transliterate(words[2].at("g_suffix_utf8")); words[2]["g_suffix_translit"] = translits.g_suffix_translit; // used by transliterate() translits.g_word_translit = transliterate(words[0].at("g_word_utf8")+words[0].at("g_suffix_utf8")+ words[1].at("g_word_utf8")+words[1].at("g_suffix_utf8"), words[2].at(ketiv ? "g_word_cons_utf8" : "g_word_utf8"), words[2].at("g_suffix_utf8")+ words[3].at("g_word_utf8")+words[3].at("g_suffix_utf8")+ words[4].at("g_word_utf8")+words[4].at("g_suffix_utf8"), words[2], ketiv, true, true); translits.g_prs_translit = transliterate("", words[2].at("g_prs_utf8"), "", words[2], false, false, false); translits.g_vbs_translit = transliterate("", words[2].at("g_vbs_utf8"), "", words[2], false, false, false); translits.g_pfm_translit = transliterate("", words[2].at("g_pfm_utf8"), "", words[2], false, false, false); translits.g_vbe_translit = transliterate("", words[2].at("g_vbe_utf8"), "", words[2], false, false, false); translits.g_nme_translit = transliterate("", words[2].at("g_nme_utf8"), "", words[2], false, false, false); translits.g_uvf_translit = transliterate("", words[2].at("g_uvf_utf8"), "", words[2], false, false, false); if (words[2].at("sp")=="verb") translits.g_voc_lex_translit = transliterate_verb_lex(words[2].at("g_voc_lex_utf8")); else translits.g_voc_lex_translit = transliterate("", words[2].at("g_voc_lex_utf8"), "", words[2], false, false, false); // No words have both a g_vbe_utf8 and a g_nme_utf8. // g_nme_utf8 always starts with a GERESH ("\u059c" or "\xd6\x9c") if (!words[2].at("g_vbe_utf8").empty()) translits.g_lex_translit = transliterate("", words[2].at("g_lex_utf8"), words[2].at("g_vbe_utf8") + words[2].at("g_uvf_utf8"), words[2], false, false, false); else if (!words[2].at("g_nme_utf8").empty()) { string nm = words[2]["g_nme_utf8"]; if (nm[0]!='\xd6' || nm[1]!='\x9c') cerr << "self=" << words[2].at("self") << " g_nme_utf8 does not start with GERES\n"; else translits.g_lex_translit = transliterate("", words[2].at("g_lex_utf8"), nm.substr(2) + words[2].at("g_uvf_utf8"), words[2], false, false, false); } else translits.g_lex_translit = transliterate("", words[2].at("g_lex_utf8"), words[2].at("g_uvf_utf8"), words[2], false, false, false); if (!words[2].at("qere_utf8").empty()) translits.qere_translit = transliterate("", words[2].at("qere_utf8"), "", words[2], false, false, false); char last_char = translits.g_word_translit.back(); string last_2_char = translits.g_word_translit.length()>=2 ? translits.g_word_translit.substr(translits.g_word_translit.length()-2) : "" ; if (last_char=='|' || last_char=='-' || last_char==' ') translits.g_word_nopunct_translit = translits.g_word_translit.substr(0, translits.g_word_translit.length()-1); else if (last_2_char=="\u05be") translits.g_word_nopunct_translit = translits.g_word_translit.substr(0, translits.g_word_translit.length()-2); else translits.g_word_nopunct_translit = translits.g_word_translit; if (translits.g_word_nopunct_translit == "HÎʔ") translits.g_word_nopunct_translit = "hîʔ"; transliterations[stol(words[2].at("self"))] = translits; words.pop_front(); } } void translit_handler::prepare_object(map<string,string>& fmap) { chk_o(&fmap); } void translit_handler::finish_prepare() { chk_o(nullptr); chk_o(nullptr); } string translit_handler::define_features() { return " ADD g_word_translit : string DEFAULT \"\";\n" " ADD g_word_nopunct_translit : string DEFAULT \"\";\n" " ADD g_suffix_translit : string DEFAULT \"\";\n" " ADD g_lex_translit : string DEFAULT \"\";\n" " ADD g_prs_translit : string DEFAULT \"\";\n" " ADD g_vbs_translit : string DEFAULT \"\";\n" " ADD g_pfm_translit : string DEFAULT \"\";\n" " ADD g_vbe_translit : string DEFAULT \"\";\n" " ADD g_nme_translit : string DEFAULT \"\";\n" " ADD g_uvf_translit : string DEFAULT \"\";\n" " ADD g_voc_lex_translit : string DEFAULT \"\";\n" " ADD qere_translit : string DEFAULT \"\";\n"; } string translit_handler::update_object(const map<string,string>& fmap) { const translit_strings& translits = transliterations.at(stoi(fmap.at("self"))); return " g_word_translit := \"" + translits.g_word_translit + "\";\n" " g_word_nopunct_translit := \"" + translits.g_word_nopunct_translit + "\";\n" " g_suffix_translit := \"" + translits.g_suffix_translit + "\";\n" " g_lex_translit := \"" + translits.g_lex_translit + "\";\n" " g_prs_translit := \"" + translits.g_prs_translit + "\";\n" " g_vbs_translit := \"" + translits.g_vbs_translit + "\";\n" " g_pfm_translit := \"" + translits.g_pfm_translit + "\";\n" " g_vbe_translit := \"" + translits.g_vbe_translit + "\";\n" " g_nme_translit := \"" + translits.g_nme_translit + "\";\n" " g_uvf_translit := \"" + translits.g_uvf_translit + "\";\n" " g_voc_lex_translit := \"" + translits.g_voc_lex_translit + "\";\n" " qere_translit := \"" + translits.qere_translit + "\";\n"; }
41.557143
170
0.588289
EzerIT
b139f85d86021b527fb4f534e28d0217a1fb71f3
2,888
cpp
C++
aws-cpp-sdk-servicecatalog/source/model/PortfolioShareType.cpp
ploki/aws-sdk-cpp
17074e3e48c7411f81294e2ee9b1550c4dde842c
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-servicecatalog/source/model/PortfolioShareType.cpp
ploki/aws-sdk-cpp
17074e3e48c7411f81294e2ee9b1550c4dde842c
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-servicecatalog/source/model/PortfolioShareType.cpp
ploki/aws-sdk-cpp
17074e3e48c7411f81294e2ee9b1550c4dde842c
[ "Apache-2.0" ]
1
2019-01-18T13:03:55.000Z
2019-01-18T13:03:55.000Z
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/servicecatalog/model/PortfolioShareType.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace ServiceCatalog { namespace Model { namespace PortfolioShareTypeMapper { static const int IMPORTED_HASH = HashingUtils::HashString("IMPORTED"); static const int AWS_SERVICECATALOG_HASH = HashingUtils::HashString("AWS_SERVICECATALOG"); static const int AWS_ORGANIZATIONS_HASH = HashingUtils::HashString("AWS_ORGANIZATIONS"); PortfolioShareType GetPortfolioShareTypeForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == IMPORTED_HASH) { return PortfolioShareType::IMPORTED; } else if (hashCode == AWS_SERVICECATALOG_HASH) { return PortfolioShareType::AWS_SERVICECATALOG; } else if (hashCode == AWS_ORGANIZATIONS_HASH) { return PortfolioShareType::AWS_ORGANIZATIONS; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<PortfolioShareType>(hashCode); } return PortfolioShareType::NOT_SET; } Aws::String GetNameForPortfolioShareType(PortfolioShareType enumValue) { switch(enumValue) { case PortfolioShareType::IMPORTED: return "IMPORTED"; case PortfolioShareType::AWS_SERVICECATALOG: return "AWS_SERVICECATALOG"; case PortfolioShareType::AWS_ORGANIZATIONS: return "AWS_ORGANIZATIONS"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return ""; } } } // namespace PortfolioShareTypeMapper } // namespace Model } // namespace ServiceCatalog } // namespace Aws
32.818182
98
0.660319
ploki
b13a972dfcdd32b01fbcab2c3dcd4bde042ee1a8
255
cpp
C++
pbdata/saf/AlnGroup.cpp
ggraham/blasr_libcpp
4abef36585bbb677ebc4acb9d4e44e82331d59f7
[ "RSA-MD" ]
4
2015-07-03T11:59:54.000Z
2018-05-17T00:03:22.000Z
pbdata/saf/AlnGroup.cpp
ggraham/blasr_libcpp
4abef36585bbb677ebc4acb9d4e44e82331d59f7
[ "RSA-MD" ]
79
2015-06-29T18:07:21.000Z
2018-09-19T13:38:39.000Z
pbdata/saf/AlnGroup.cpp
ggraham/blasr_libcpp
4abef36585bbb677ebc4acb9d4e44e82331d59f7
[ "RSA-MD" ]
19
2015-06-23T08:43:29.000Z
2021-04-28T18:37:47.000Z
#include <pbdata/saf/AlnGroup.hpp> int AlnGroup::FindPath(unsigned int idKey, std::string &val) { for (size_t i = 0; i < id.size(); i++) { if (idKey == id[i]) { val = path[i]; return 1; } } return 0; }
19.615385
60
0.490196
ggraham
b13bfaaff751458115f3b2e6bc2570bd39ae0b22
2,177
cc
C++
src/OutputForce.cc
Mopolino8/ibpm
644f356f5f15ddf8cfbc50432f95f3602802260f
[ "BSD-3-Clause" ]
null
null
null
src/OutputForce.cc
Mopolino8/ibpm
644f356f5f15ddf8cfbc50432f95f3602802260f
[ "BSD-3-Clause" ]
null
null
null
src/OutputForce.cc
Mopolino8/ibpm
644f356f5f15ddf8cfbc50432f95f3602802260f
[ "BSD-3-Clause" ]
1
2019-11-24T17:51:30.000Z
2019-11-24T17:51:30.000Z
// OutputForce.cc // // Description: // Implementation of output routine for writing a list of force coefficients. // // Author(s): // Clancy Rowley // Steve Brunton // // Date: 22 Aug 2008 // // $Revision$ // $LastChangedDate$ // $LastChangedBy$ // $HeadURL$ #include "OutputForce.h" #include "BaseFlow.h" #include "State.h" #include "Output.h" #include "VectorOperations.h" #include <stdio.h> #include <string> using namespace std; namespace ibpm { OutputForce::OutputForce(string filename) : _filename( filename ) {} bool OutputForce::init() { _fp = fopen( _filename.c_str(), "w" ); if ( _fp == NULL ) return false; else return true; } bool OutputForce::cleanup() { bool status = true; if ( _fp != NULL ) { status = fclose( _fp ); } return status; } // Method to compute lift, drag from state (x), angle of attack (alpha), and freestream velocity (mag) bool OutputForce::doOutput( const double alpha, const double mag, const State& x) { double xF, yF; // force in x and y direction in domain double drag, lift; // actual drag and lift, wrt alpha x.computeNetForce( xF, yF ); drag = xF * cos(alpha) + yF * sin(alpha); lift = xF * -1.*sin(alpha) + yF * cos(alpha); // Convert forces to lift and drag coefficients: // If L_d is dimensional lift, then in the nondimensionalization of the // code (lengths by c, density by rho, velocity by U), we have // L = L_d / (c rho U^2) // so // C_L = L_d / (1/2 rho U^2) // = 2 L drag *= 2./(mag*mag); lift *= 2./(mag*mag); if ( _fp == NULL ) return false; fprintf( _fp, "%5d %.5e %.5e %.5e\n", x.timestep, x.time, drag, lift ); fflush( _fp ); return true; } // If no other information is provided, assume zero angle of attack, unity freestrem velocity bool OutputForce::doOutput(const State& x) { double alpha = 0.; double mag = 1.; return doOutput(alpha, mag, x); } bool OutputForce::doOutput( const BaseFlow& q, const State& x) { double alpha = q.getAlpha(); double mag = q.getMag(); return doOutput(alpha, mag, x); } } // namespace ibpm
24.738636
102
0.617363
Mopolino8
b13c791bf3ca14b21d43409fe63b3a10840666f8
2,433
cpp
C++
mqtt/client.cpp
dkesler-execom/WolkSDK-Cpp
fd353d34affa5c252f5a1022c9fc1b6ae9a285a5
[ "Apache-2.0" ]
null
null
null
mqtt/client.cpp
dkesler-execom/WolkSDK-Cpp
fd353d34affa5c252f5a1022c9fc1b6ae9a285a5
[ "Apache-2.0" ]
null
null
null
mqtt/client.cpp
dkesler-execom/WolkSDK-Cpp
fd353d34affa5c252f5a1022c9fc1b6ae9a285a5
[ "Apache-2.0" ]
null
null
null
// client.cpp // Implementation of the client class for the mqtt C++ client library. /******************************************************************************* * Copyright (c) 2013-2017 Frank Pagliughi <fpagliughi@mindspring.com> * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Eclipse Distribution License v1.0 which accompany this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Frank Pagliughi - initial implementation and documentation *******************************************************************************/ #include "client.h" #include <memory> #include <iostream> namespace mqtt { const std::chrono::minutes client::DFLT_TIMEOUT = std::chrono::minutes(5); constexpr int client::DFLT_QOS; ///////////////////////////////////////////////////////////////////////////// client::client(const string& serverURI, const string& clientId, iclient_persistence* persistence /*=nullptr*/) : cli_(serverURI, clientId, persistence), timeout_(DFLT_TIMEOUT), userCallback_(nullptr) { } client::client(const string& serverURI, const string& clientId, const string& persistDir) : cli_(serverURI, clientId, persistDir), timeout_(DFLT_TIMEOUT), userCallback_(nullptr) { } client::client(const string& serverURI, const string& clientId, int maxBufferedMessages, iclient_persistence* persistence /*=nullptr*/) : cli_(serverURI, clientId, maxBufferedMessages, persistence), timeout_(DFLT_TIMEOUT), userCallback_(nullptr) { } client::client(const string& serverURI, const string& clientId, int maxBufferedMessages, const string& persistDir) : cli_(serverURI, clientId, maxBufferedMessages, persistDir), timeout_(DFLT_TIMEOUT), userCallback_(nullptr) { } void client::set_callback(callback& cb) { userCallback_ = &cb; cli_.set_callback(*this); } void client::subscribe(const string_collection& topicFilters) { qos_collection qos; for (size_t i=0; i<topicFilters.size(); ++i) qos.push_back(DFLT_QOS); cli_.subscribe(ptr(topicFilters), qos)->wait_for(timeout_); } ///////////////////////////////////////////////////////////////////////////// // end namespace mqtt }
30.037037
81
0.649404
dkesler-execom
b13de41571636040a9341e59272578a3a9d6b082
4,484
cpp
C++
tests/VkUploadPixelsTests.cpp
avaer/skia
b211ebc328e9df69f95fc58e7363775ec2d0c14d
[ "BSD-3-Clause" ]
3
2018-10-28T09:55:58.000Z
2018-12-09T05:09:38.000Z
tests/VkUploadPixelsTests.cpp
BensonDu/skia
b211ebc328e9df69f95fc58e7363775ec2d0c14d
[ "BSD-3-Clause" ]
1
2018-10-21T04:53:25.000Z
2018-10-21T04:53:25.000Z
tests/VkUploadPixelsTests.cpp
BensonDu/skia
b211ebc328e9df69f95fc58e7363775ec2d0c14d
[ "BSD-3-Clause" ]
4
2018-08-10T03:09:14.000Z
2018-10-21T00:04:47.000Z
/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ // This is a GPU-backend specific test. It relies on static intializers to work #include "SkTypes.h" #if defined(SK_VULKAN) #include "GrContextFactory.h" #include "GrContextPriv.h" #include "GrSurfaceProxy.h" #include "GrTest.h" #include "ProxyUtils.h" #include "SkGr.h" #include "Test.h" #include "TestUtils.h" #include "vk/GrVkGpu.h" using sk_gpu_test::GrContextFactory; void basic_texture_test(skiatest::Reporter* reporter, GrContext* context, SkColorType ct, bool renderTarget) { const int kWidth = 16; const int kHeight = 16; SkAutoTMalloc<GrColor> srcBuffer(kWidth*kHeight); SkAutoTMalloc<GrColor> dstBuffer(kWidth*kHeight); fill_pixel_data(kWidth, kHeight, srcBuffer.get()); auto proxy = sk_gpu_test::MakeTextureProxyFromData(context, renderTarget, kWidth, kHeight, ct, kTopLeft_GrSurfaceOrigin, srcBuffer, 0); REPORTER_ASSERT(reporter, proxy); if (proxy) { sk_sp<GrSurfaceContext> sContext = context->contextPriv().makeWrappedSurfaceContext(proxy); SkImageInfo dstInfo = SkImageInfo::Make(kWidth, kHeight, ct, kPremul_SkAlphaType); bool result = sContext->readPixels(dstInfo, dstBuffer, 0, 0, 0); REPORTER_ASSERT(reporter, result); REPORTER_ASSERT(reporter, does_full_buffer_contain_correct_color(srcBuffer, dstBuffer, kWidth, kHeight)); dstInfo = SkImageInfo::Make(10, 2, ct, kPremul_SkAlphaType); result = sContext->writePixels(dstInfo, srcBuffer, 0, 2, 10); REPORTER_ASSERT(reporter, result); memset(dstBuffer, 0, kWidth*kHeight*sizeof(GrColor)); result = sContext->readPixels(dstInfo, dstBuffer, 0, 2, 10); REPORTER_ASSERT(reporter, result); REPORTER_ASSERT(reporter, does_full_buffer_contain_correct_color(srcBuffer, dstBuffer, 10, 2)); } proxy = sk_gpu_test::MakeTextureProxyFromData(context, renderTarget, kWidth, kHeight, ct, kBottomLeft_GrSurfaceOrigin, srcBuffer, 0); REPORTER_ASSERT(reporter, proxy); if (proxy) { sk_sp<GrSurfaceContext> sContext = context->contextPriv().makeWrappedSurfaceContext(proxy); SkImageInfo dstInfo = SkImageInfo::Make(kWidth, kHeight, ct, kPremul_SkAlphaType); bool result = sContext->readPixels(dstInfo, dstBuffer, 0, 0, 0); REPORTER_ASSERT(reporter, result); REPORTER_ASSERT(reporter, does_full_buffer_contain_correct_color(srcBuffer, dstBuffer, kWidth, kHeight)); dstInfo = SkImageInfo::Make(4, 5, ct, kPremul_SkAlphaType); result = sContext->writePixels(dstInfo, srcBuffer, 0, 5, 4); REPORTER_ASSERT(reporter, result); memset(dstBuffer, 0, kWidth*kHeight*sizeof(GrColor)); result = sContext->readPixels(dstInfo, dstBuffer, 0, 5, 4); REPORTER_ASSERT(reporter, result); REPORTER_ASSERT(reporter, does_full_buffer_contain_correct_color(srcBuffer, dstBuffer, 4, 5)); } } DEF_GPUTEST_FOR_VULKAN_CONTEXT(VkUploadPixelsTests, reporter, ctxInfo) { // RGBA basic_texture_test(reporter, ctxInfo.grContext(), kRGBA_8888_SkColorType, false); basic_texture_test(reporter, ctxInfo.grContext(), kRGBA_8888_SkColorType, true); // BGRA basic_texture_test(reporter, ctxInfo.grContext(), kBGRA_8888_SkColorType, false); basic_texture_test(reporter, ctxInfo.grContext(), kBGRA_8888_SkColorType, true); } #endif
41.518519
99
0.564005
avaer
b140520194ff200a3a995ad3e1562425ee0b55d1
8,952
cpp
C++
src/chrono_vehicle/cosim/mbs/ChVehicleCosimVehicleNode.cpp
aluaces/chrono
675ff6c1105814973dd7f844bd19385d9760f90c
[ "BSD-3-Clause" ]
1,383
2015-02-04T14:17:40.000Z
2022-03-30T04:58:16.000Z
src/chrono_vehicle/cosim/mbs/ChVehicleCosimVehicleNode.cpp
pchaoWT/chrono
fd68d37d1d4ee75230dc1eea78ceff91cca7ac32
[ "BSD-3-Clause" ]
245
2015-01-11T15:30:51.000Z
2022-03-30T21:28:54.000Z
src/chrono_vehicle/cosim/mbs/ChVehicleCosimVehicleNode.cpp
pchaoWT/chrono
fd68d37d1d4ee75230dc1eea78ceff91cca7ac32
[ "BSD-3-Clause" ]
351
2015-02-04T14:17:47.000Z
2022-03-30T04:42:52.000Z
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2020 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban // ============================================================================= // // Wheeled vehicle system co-simulated with tire nodes and a terrain node. // // The global reference frame has Z up, X towards the front of the vehicle, and // Y pointing to the left. // // ============================================================================= #include <fstream> #include <algorithm> #include <set> #include <vector> #include "chrono/ChConfig.h" #include "chrono_vehicle/ChVehicleModelData.h" #include "chrono_vehicle/utils/ChUtilsJSON.h" #include "chrono_vehicle/wheeled_vehicle/vehicle/WheeledVehicle.h" #include "chrono_vehicle/cosim/mbs/ChVehicleCosimVehicleNode.h" using std::cout; using std::endl; namespace chrono { namespace vehicle { // ----------------------------------------------------------------------------- class WheeledVehicleDBPDriver : public ChDriver { public: WheeledVehicleDBPDriver(std::shared_ptr<ChWheeledVehicle> vehicle, std::shared_ptr<ChFunction> dbp_mot_func) : ChDriver(*vehicle), m_wheeled_vehicle(vehicle), m_func(dbp_mot_func) {} virtual void Synchronize(double time) override { m_steering = 0; m_braking = 0; double ang_speed = m_func->Get_y(time); for (auto& axle : m_wheeled_vehicle->GetAxles()) { axle->m_suspension->GetAxle(VehicleSide::LEFT)->SetPos_dt(ang_speed); axle->m_suspension->GetAxle(VehicleSide::RIGHT)->SetPos_dt(ang_speed); } } std::shared_ptr<ChWheeledVehicle> m_wheeled_vehicle; std::shared_ptr<ChFunction> m_func; }; // ----------------------------------------------------------------------------- ChVehicleCosimVehicleNode::ChVehicleCosimVehicleNode(const std::string& vehicle_json, const std::string& powertrain_json) : ChVehicleCosimMBSNode(), m_num_spindles(0) { m_vehicle = chrono_types::make_shared<WheeledVehicle>(m_system, vehicle_json); m_powertrain = ReadPowertrainJSON(powertrain_json); m_terrain = chrono_types::make_shared<ChTerrain>(); } ChVehicleCosimVehicleNode::~ChVehicleCosimVehicleNode() {} // ----------------------------------------------------------------------------- void ChVehicleCosimVehicleNode::InitializeMBS(const std::vector<ChVector<>>& tire_info, const ChVector2<>& terrain_size, double terrain_height) { // Initialize vehicle ChCoordsys<> init_pos(m_init_loc + ChVector<>(0, 0, terrain_height), Q_from_AngZ(m_init_yaw)); m_vehicle->Initialize(init_pos); m_vehicle->SetChassisVisualizationType(VisualizationType::MESH); m_vehicle->SetSuspensionVisualizationType(VisualizationType::PRIMITIVES); m_vehicle->SetSteeringVisualizationType(VisualizationType::PRIMITIVES); m_vehicle->SetWheelVisualizationType(VisualizationType::MESH); // Initialize powertrain m_vehicle->InitializePowertrain(m_powertrain); // Create and initialize the dummy tires int itire = 0; for (auto& axle : m_vehicle->GetAxles()) { for (auto& wheel : axle->GetWheels()) { auto tire = chrono_types::make_shared<DummyTire>(itire, tire_info[itire].x(), tire_info[itire].y(), tire_info[itire].z()); m_vehicle->InitializeTire(tire, wheel, VisualizationType::NONE); m_tires.push_back(tire); itire++; } } // Extract and cache spindle bodies auto num_axles = m_vehicle->GetNumberAxles(); m_num_spindles = 2 * num_axles; assert(m_num_spindles == (int)m_num_tire_nodes); auto total_mass = m_vehicle->GetVehicleMass(); for (int is = 0; is < m_num_spindles; is++) { auto tire_mass = tire_info[is].x(); m_spindle_loads.push_back(tire_mass + total_mass / m_num_spindles); } } // ----------------------------------------------------------------------------- int ChVehicleCosimVehicleNode::GetNumSpindles() const { return m_num_spindles; } std::shared_ptr<ChBody> ChVehicleCosimVehicleNode::GetSpindleBody(unsigned int i) const { VehicleSide side = (i % 2 == 0) ? VehicleSide::LEFT : VehicleSide::RIGHT; return m_vehicle->GetWheel(i / 2, side)->GetSpindle(); } double ChVehicleCosimVehicleNode::GetSpindleLoad(unsigned int i) const { return m_spindle_loads[i]; } BodyState ChVehicleCosimVehicleNode::GetSpindleState(unsigned int i) const { VehicleSide side = (i % 2 == 0) ? VehicleSide::LEFT : VehicleSide::RIGHT; auto spindle_body = m_vehicle->GetWheel(i / 2, side)->GetSpindle(); BodyState state; state.pos = spindle_body->GetPos(); state.rot = spindle_body->GetRot(); state.lin_vel = spindle_body->GetPos_dt(); state.ang_vel = spindle_body->GetWvel_par(); return state; } std::shared_ptr<ChBody> ChVehicleCosimVehicleNode::GetChassisBody() const { return m_vehicle->GetChassisBody(); } void ChVehicleCosimVehicleNode::OnInitializeDBPRig(std::shared_ptr<ChFunction> func) { // Disconnect the driveline m_vehicle->DisconnectDriveline(); // Overwrite any driver attached to the vehicle with a custom driver which imposes zero steering and braking and // directly sets the angular speed of the vehicle axleshafts as returned by the provided motor function. SetDriver(chrono_types::make_shared<WheeledVehicleDBPDriver>(m_vehicle, func)); } // ----------------------------------------------------------------------------- void ChVehicleCosimVehicleNode::PreAdvance() { // Synchronize vehicle systems double time = m_vehicle->GetChTime(); ChDriver::Inputs driver_inputs; if (m_driver) { driver_inputs = m_driver->GetInputs(); m_driver->Synchronize(time); } else { driver_inputs.m_steering = 0; driver_inputs.m_throttle = 0.5; driver_inputs.m_braking = 0; } m_vehicle->Synchronize(time, driver_inputs, *m_terrain); } void ChVehicleCosimVehicleNode::ApplySpindleForce(unsigned int i, const TerrainForce& spindle_force) { // Cache the spindle force on the corresponding dummy tire. This force will be applied to the associated ChWheel on // synchronization of the vehicle system (in PreAdvance) m_tires[i]->m_force = spindle_force; } // ----------------------------------------------------------------------------- void ChVehicleCosimVehicleNode::OnOutputData(int frame) { // Append to results output file if (m_outf.is_open()) { std::string del(" "); const ChVector<>& pos = m_vehicle->GetVehiclePos(); m_outf << m_system->GetChTime() << del; // Body states m_outf << pos.x() << del << pos.y() << del << pos.z() << del; // Solver statistics (for last integration step) m_outf << m_system->GetTimerStep() << del << m_system->GetTimerLSsetup() << del << m_system->GetTimerLSsolve() << del << m_system->GetTimerUpdate() << del; if (m_int_type == ChTimestepper::Type::HHT) { m_outf << m_integrator->GetNumIterations() << del << m_integrator->GetNumSetupCalls() << del << m_integrator->GetNumSolveCalls() << del; } m_outf << endl; } // Create and write frame output file. utils::CSV_writer csv(" "); csv << m_system->GetChTime() << endl; // current time WriteBodyInformation(csv); // vehicle body states std::string filename = OutputFilename(m_node_out_dir + "/simulation", "data", "dat", frame + 1, 5); csv.write_to_file(filename); if (m_verbose) cout << "[Vehicle node] write output file ==> " << filename << endl; } void ChVehicleCosimVehicleNode::WriteBodyInformation(utils::CSV_writer& csv) { // Write number of bodies csv << 1 + m_num_spindles << endl; // Write body state information auto chassis = m_vehicle->GetChassisBody(); csv << chassis->GetPos() << chassis->GetRot() << chassis->GetPos_dt() << chassis->GetRot_dt() << endl; for (auto& axle : m_vehicle->GetAxles()) { for (auto& wheel : axle->GetWheels()) { auto spindle_body = wheel->GetSpindle(); csv << spindle_body->GetPos() << spindle_body->GetRot() << spindle_body->GetPos_dt() << spindle_body->GetRot_dt() << endl; } } } } // end namespace vehicle } // end namespace chrono
38.093617
119
0.610813
aluaces
b14921bbd501308fc83cac6141b2bdb1cc90a6e0
1,431
inl
C++
unit_tests/api/cl_retain_release_sampler_tests.inl
FelipeMLopez/compute-runtime
3e3d2d3b3ac9129b1ee9c4251a2586fef0b300b8
[ "MIT" ]
3
2019-09-20T23:26:36.000Z
2019-10-03T17:44:12.000Z
unit_tests/api/cl_retain_release_sampler_tests.inl
FelipeMLopez/compute-runtime
3e3d2d3b3ac9129b1ee9c4251a2586fef0b300b8
[ "MIT" ]
null
null
null
unit_tests/api/cl_retain_release_sampler_tests.inl
FelipeMLopez/compute-runtime
3e3d2d3b3ac9129b1ee9c4251a2586fef0b300b8
[ "MIT" ]
3
2019-05-16T07:22:51.000Z
2019-11-11T03:05:32.000Z
/* * Copyright (C) 2017-2019 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "runtime/context/context.h" #include "cl_api_tests.h" using namespace NEO; typedef api_tests clRetainReleaseSamplerTests; namespace ULT { TEST_F(clRetainReleaseSamplerTests, GivenValidSamplerWhenRetainingThenSamplerReferenceCountIsIncremented) { cl_int retVal = CL_SUCCESS; auto sampler = clCreateSampler(pContext, CL_TRUE, CL_ADDRESS_CLAMP, CL_FILTER_NEAREST, &retVal); EXPECT_EQ(CL_SUCCESS, retVal); EXPECT_NE(nullptr, sampler); cl_uint theRef; retVal = clGetSamplerInfo(sampler, CL_SAMPLER_REFERENCE_COUNT, sizeof(cl_uint), &theRef, NULL); EXPECT_EQ(CL_SUCCESS, retVal); EXPECT_EQ(1u, theRef); retVal = clRetainSampler(sampler); EXPECT_EQ(CL_SUCCESS, retVal); retVal = clGetSamplerInfo(sampler, CL_SAMPLER_REFERENCE_COUNT, sizeof(cl_uint), &theRef, NULL); EXPECT_EQ(CL_SUCCESS, retVal); EXPECT_EQ(2u, theRef); retVal = clReleaseSampler(sampler); EXPECT_EQ(CL_SUCCESS, retVal); retVal = clGetSamplerInfo(sampler, CL_SAMPLER_REFERENCE_COUNT, sizeof(cl_uint), &theRef, NULL); EXPECT_EQ(CL_SUCCESS, retVal); EXPECT_EQ(1u, theRef); retVal = clReleaseSampler(sampler); EXPECT_EQ(CL_SUCCESS, retVal); } } // namespace ULT
29.8125
107
0.682041
FelipeMLopez
b14936afdabe04db37d6ccfb7c00fe785d633d16
27,372
cpp
C++
test/unit/common/test_data_descriptor.cpp
haampie/DLA-Future
b8f3c8af8eaa5732f035e3af3a65194fb24e7eb3
[ "BSD-3-Clause" ]
null
null
null
test/unit/common/test_data_descriptor.cpp
haampie/DLA-Future
b8f3c8af8eaa5732f035e3af3a65194fb24e7eb3
[ "BSD-3-Clause" ]
null
null
null
test/unit/common/test_data_descriptor.cpp
haampie/DLA-Future
b8f3c8af8eaa5732f035e3af3a65194fb24e7eb3
[ "BSD-3-Clause" ]
null
null
null
// // Distributed Linear Algebra with Future (DLAF) // // Copyright (c) 2018-2019, ETH Zurich // All rights reserved. // // Please, refer to the LICENSE file in the root directory. // SPDX-License-Identifier: BSD-3-Clause // #include "dlaf/common/data_descriptor.h" #include <memory> #include <type_traits> #include <gtest/gtest.h> #include "dlaf/types.h" #include "dlaf_test/util_types.h" using namespace dlaf; template <typename T> struct memory_data { std::unique_ptr<T[]> data; std::size_t num_blocks; std::size_t block_size; std::size_t stride; T& operator[](std::size_t index) { auto i_block = index / block_size; auto i_element = index % block_size; return data.get()[i_block * stride + i_element]; } }; template <class T> memory_data<T> create_memory(const std::size_t num_blocks, const std::size_t blocksize, const std::size_t stride) { assert(num_blocks > 0); assert(blocksize <= stride || stride == 0); if (num_blocks == 1) return {std::make_unique<T[]>(blocksize), num_blocks, blocksize, stride}; // the last element does not have additional padding // no additional padding to the next (non-existing) element auto distance = std::max(blocksize, stride); auto memory_footprint = (num_blocks - 1) * distance + blocksize; return {std::make_unique<T[]>(memory_footprint), num_blocks, blocksize, stride}; } enum class MEMORY_TYPE { ARRAY_CONTIGUOUS, ARRAY_STRIDED, ARRAY_CONTIGUOUS_AS_STRIDED }; template <class T> memory_data<T> create_memory(MEMORY_TYPE type) { switch (type) { case MEMORY_TYPE::ARRAY_CONTIGUOUS: // 1 block // 13 elements // E E E E E E E E E E E E E return create_memory<T>(1, 13, 0); case MEMORY_TYPE::ARRAY_STRIDED: // 3 blocks // 2 elements each // 5 elements between start of each block // E E - - - E E - - - E E (without padding at the end) return create_memory<T>(3, 2, 5); case MEMORY_TYPE::ARRAY_CONTIGUOUS_AS_STRIDED: // 3 blocks // 5 elements each // 5 elements between start of each block // E E E E E E E E E E E E E E E return create_memory<T>(3, 5, 5); default: throw std::runtime_error("Unknown memory type"); } } template <class Type> class DataDescriptorTest : public ::testing::Test {}; TYPED_TEST_SUITE(DataDescriptorTest, dlaf_test::ElementTypes); TYPED_TEST(DataDescriptorTest, MakeFromPointer) { TypeParam value = 26; TypeParam* value_ptr = &value; auto data = common::make_data(value_ptr, 1); EXPECT_EQ(value_ptr, data_pointer(data)); EXPECT_EQ(1, data_nblocks(data)); EXPECT_EQ(1, data_blocksize(data)); EXPECT_EQ(0, data_stride(data)); EXPECT_TRUE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, MakeFromPointerConst) { TypeParam value = 26; const TypeParam* value_ptr = &value; auto data = common::make_data(value_ptr, 1); EXPECT_EQ(value_ptr, data_pointer(data)); EXPECT_EQ(1, data_nblocks(data)); EXPECT_EQ(1, data_blocksize(data)); EXPECT_EQ(0, data_stride(data)); EXPECT_TRUE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<const TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, MakeFromCArray) { const int N = 13; TypeParam value_array[N]{}; auto data = common::make_data(value_array, N); EXPECT_EQ(&value_array[0], data_pointer(data)); EXPECT_EQ(1, data_nblocks(data)); EXPECT_EQ(std::extent<decltype(value_array)>::value, data_blocksize(data)); EXPECT_EQ(0, data_stride(data)); EXPECT_TRUE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, MakeFromCArrayConst) { const int N = 13; const TypeParam value_array[N]{}; auto data = common::make_data(value_array, N); EXPECT_EQ(&value_array[0], data_pointer(data)); EXPECT_EQ(1, data_nblocks(data)); EXPECT_EQ(std::extent<decltype(value_array)>::value, data_blocksize(data)); EXPECT_EQ(0, data_stride(data)); EXPECT_TRUE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<const TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, MakeFromContiguousArray) { memory_data<TypeParam> memory = create_memory<TypeParam>(MEMORY_TYPE::ARRAY_CONTIGUOUS); auto data = common::make_data(memory.data.get(), memory.num_blocks, memory.block_size, memory.stride); EXPECT_EQ(memory.data.get(), data_pointer(data)); EXPECT_EQ(memory.num_blocks, data_nblocks(data)); EXPECT_EQ(memory.block_size, data_blocksize(data)); EXPECT_EQ(memory.stride, data_stride(data)); EXPECT_TRUE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, MakeFromContiguousArrayConst) { memory_data<TypeParam> memory = create_memory<TypeParam>(MEMORY_TYPE::ARRAY_CONTIGUOUS); auto data = common::make_data(const_cast<const TypeParam*>(memory.data.get()), memory.num_blocks, memory.block_size, memory.stride); EXPECT_EQ(memory.data.get(), data_pointer(data)); EXPECT_EQ(memory.num_blocks, data_nblocks(data)); EXPECT_EQ(memory.block_size, data_blocksize(data)); EXPECT_EQ(memory.stride, data_stride(data)); EXPECT_TRUE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<const TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, MakeFromContiguousAsStridedArray) { memory_data<TypeParam> memory = create_memory<TypeParam>(MEMORY_TYPE::ARRAY_CONTIGUOUS_AS_STRIDED); auto data = common::make_data(memory.data.get(), memory.num_blocks, memory.block_size, memory.stride); EXPECT_EQ(memory.data.get(), data_pointer(data)); EXPECT_EQ(1, data_nblocks(data)); EXPECT_EQ(memory.num_blocks * memory.block_size, data_blocksize(data)); EXPECT_EQ(0, data_stride(data)); EXPECT_TRUE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, MakeFromContiguousAsStridedArrayConst) { memory_data<TypeParam> memory = create_memory<TypeParam>(MEMORY_TYPE::ARRAY_CONTIGUOUS_AS_STRIDED); auto data = common::make_data(const_cast<const TypeParam*>(memory.data.get()), memory.num_blocks, memory.block_size, memory.stride); EXPECT_EQ(memory.data.get(), data_pointer(data)); EXPECT_EQ(1, data_nblocks(data)); EXPECT_EQ(memory.num_blocks * memory.block_size, data_blocksize(data)); EXPECT_EQ(0, data_stride(data)); EXPECT_TRUE(data_iscontiguous(data)); EXPECT_TRUE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<const TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, MakeFromStridedArray) { memory_data<TypeParam> memory = create_memory<TypeParam>(MEMORY_TYPE::ARRAY_STRIDED); auto data = common::make_data(memory.data.get(), memory.num_blocks, memory.block_size, memory.stride); EXPECT_EQ(memory.data.get(), data_pointer(data)); EXPECT_EQ(memory.num_blocks, data_nblocks(data)); EXPECT_EQ(memory.block_size, data_blocksize(data)); EXPECT_EQ(memory.stride, data_stride(data)); EXPECT_FALSE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, MakeFromStridedArrayConst) { memory_data<TypeParam> memory = create_memory<TypeParam>(MEMORY_TYPE::ARRAY_STRIDED); auto data = common::make_data(const_cast<const TypeParam*>(memory.data.get()), memory.num_blocks, memory.block_size, memory.stride); EXPECT_EQ(memory.data.get(), data_pointer(data)); EXPECT_EQ(memory.num_blocks, data_nblocks(data)); EXPECT_EQ(memory.block_size, data_blocksize(data)); EXPECT_EQ(memory.stride, data_stride(data)); EXPECT_FALSE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<const TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, MakeBufferUniquePtr) { const std::size_t N = 13; auto data = common::Buffer<TypeParam>(N); EXPECT_NE(nullptr, data_pointer(data)); EXPECT_EQ(1, data_nblocks(data)); EXPECT_EQ(N, data_blocksize(data)); EXPECT_EQ(0, data_stride(data)); EXPECT_TRUE(data_iscontiguous(data)); } TYPED_TEST(DataDescriptorTest, CtorFromPointer) { TypeParam value = 26; TypeParam* value_ptr = &value; auto data = common::DataDescriptor<TypeParam>{value_ptr, 1}; EXPECT_EQ(value_ptr, data_pointer(data)); EXPECT_EQ(1, data_nblocks(data)); EXPECT_EQ(1, data_blocksize(data)); EXPECT_EQ(0, data_stride(data)); EXPECT_TRUE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, CtorFromPointerConst) { TypeParam value = 26; const TypeParam* value_ptr = &value; auto data = common::DataDescriptor<const TypeParam>{value_ptr, 1}; EXPECT_EQ(value_ptr, data_pointer(data)); EXPECT_EQ(1, data_nblocks(data)); EXPECT_EQ(1, data_blocksize(data)); EXPECT_EQ(0, data_stride(data)); EXPECT_TRUE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<const TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, CtorFromCArray) { const int N = 13; TypeParam value_array[N]{}; auto data = common::DataDescriptor<decltype(value_array)>{value_array}; EXPECT_EQ(&value_array[0], data_pointer(data)); EXPECT_EQ(1, data_nblocks(data)); EXPECT_EQ(std::extent<decltype(value_array)>::value, data_blocksize(data)); EXPECT_EQ(0, data_stride(data)); EXPECT_TRUE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, CtorFromCArrayConst) { const int N = 13; const TypeParam value_array[N]{}; auto data = common::DataDescriptor<decltype(value_array)>{value_array}; EXPECT_EQ(&value_array[0], data_pointer(data)); EXPECT_EQ(1, data_nblocks(data)); EXPECT_EQ(std::extent<decltype(value_array)>::value, data_blocksize(data)); EXPECT_EQ(0, data_stride(data)); EXPECT_TRUE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<const TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, CtorFromContiguousArray) { memory_data<TypeParam> memory = create_memory<TypeParam>(MEMORY_TYPE::ARRAY_CONTIGUOUS); auto data = common::make_data(memory.data.get(), memory.num_blocks, memory.block_size, memory.stride); EXPECT_EQ(memory.data.get(), data_pointer(data)); EXPECT_EQ(memory.num_blocks, data_nblocks(data)); EXPECT_EQ(memory.block_size, data_blocksize(data)); EXPECT_EQ(memory.stride, data_stride(data)); EXPECT_TRUE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, CtorFromContiguousArrayConst) { memory_data<TypeParam> memory = create_memory<TypeParam>(MEMORY_TYPE::ARRAY_CONTIGUOUS); auto data = common::make_data(const_cast<const TypeParam*>(memory.data.get()), memory.num_blocks, memory.block_size, memory.stride); EXPECT_EQ(memory.data.get(), data_pointer(data)); EXPECT_EQ(memory.num_blocks, data_nblocks(data)); EXPECT_EQ(memory.block_size, data_blocksize(data)); EXPECT_EQ(memory.stride, data_stride(data)); EXPECT_TRUE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<const TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, CtorFromContiguousAsStridedArray) { memory_data<TypeParam> memory = create_memory<TypeParam>(MEMORY_TYPE::ARRAY_CONTIGUOUS_AS_STRIDED); auto data = common::make_data(memory.data.get(), memory.num_blocks, memory.block_size, memory.stride); EXPECT_EQ(memory.data.get(), data_pointer(data)); EXPECT_EQ(1, data_nblocks(data)); EXPECT_EQ(memory.num_blocks * memory.block_size, data_blocksize(data)); EXPECT_EQ(0, data_stride(data)); EXPECT_TRUE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, CtorFromContiguousAsStridedArrayConst) { memory_data<TypeParam> memory = create_memory<TypeParam>(MEMORY_TYPE::ARRAY_CONTIGUOUS_AS_STRIDED); auto data = common::make_data(const_cast<const TypeParam*>(memory.data.get()), memory.num_blocks, memory.block_size, memory.stride); EXPECT_EQ(memory.data.get(), data_pointer(data)); EXPECT_EQ(1, data_nblocks(data)); EXPECT_EQ(memory.num_blocks * memory.block_size, data_blocksize(data)); EXPECT_EQ(0, data_stride(data)); EXPECT_TRUE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<const TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, CtorFromStridedArray) { memory_data<TypeParam> memory = create_memory<TypeParam>(MEMORY_TYPE::ARRAY_STRIDED); auto data = common::make_data(memory.data.get(), memory.num_blocks, memory.block_size, memory.stride); EXPECT_EQ(memory.data.get(), data_pointer(data)); EXPECT_EQ(memory.num_blocks, data_nblocks(data)); EXPECT_EQ(memory.block_size, data_blocksize(data)); EXPECT_EQ(memory.stride, data_stride(data)); EXPECT_FALSE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, CtorFromStridedArrayConst) { memory_data<TypeParam> memory = create_memory<TypeParam>(MEMORY_TYPE::ARRAY_STRIDED); auto data = common::make_data(const_cast<const TypeParam*>(memory.data.get()), memory.num_blocks, memory.block_size, memory.stride); EXPECT_EQ(memory.data.get(), data_pointer(data)); EXPECT_EQ(memory.num_blocks, data_nblocks(data)); EXPECT_EQ(memory.block_size, data_blocksize(data)); EXPECT_EQ(memory.stride, data_stride(data)); EXPECT_FALSE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<const TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, CtorBufferUniquePtr) { const std::size_t N = 13; auto data = common::Buffer<TypeParam>(N); EXPECT_NE(nullptr, data_pointer(data)); EXPECT_EQ(1, data_nblocks(data)); EXPECT_EQ(N, data_blocksize(data)); EXPECT_EQ(0, data_stride(data)); EXPECT_TRUE(data_iscontiguous(data)); } template <class TypeParam, class Buffer> void check_copy_ctor(Buffer& data) { auto data_copy = data; EXPECT_EQ(data_pointer(data), data_pointer(data_copy)); EXPECT_EQ(data_nblocks(data), data_nblocks(data_copy)); EXPECT_EQ(data_blocksize(data), data_blocksize(data_copy)); EXPECT_EQ(data_stride(data), data_stride(data_copy)); EXPECT_EQ(data_iscontiguous(data), data_iscontiguous(data_copy)); static_assert(common::is_data<decltype(data_copy)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<TypeParam, typename common::data_traits<decltype(data_copy)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, CopyCtorFromPointer) { TypeParam value = 26; auto data = common::make_data(&value, 1); check_copy_ctor<TypeParam>(data); const TypeParam value_const = value; auto data_const = common::make_data(&value_const, 1); check_copy_ctor<const TypeParam>(data_const); } TYPED_TEST(DataDescriptorTest, CopyCtorFromCArray) { const int N = 13; TypeParam value_array[N]{}; auto data = common::make_data(value_array, N); check_copy_ctor<TypeParam>(data); const TypeParam value_array_const[N]{}; auto data_const = common::make_data(value_array_const, N); check_copy_ctor<const TypeParam>(data_const); } TYPED_TEST(DataDescriptorTest, CopyCtorFromContiguousArray) { auto memory = create_memory<TypeParam>(MEMORY_TYPE::ARRAY_CONTIGUOUS); auto data = common::make_data(memory.data.get(), memory.num_blocks, memory.block_size, memory.stride); check_copy_ctor<TypeParam>(data); auto data_const = common::make_data(static_cast<const TypeParam*>(memory.data.get()), memory.num_blocks, memory.block_size, memory.stride); check_copy_ctor<const TypeParam>(data_const); } TYPED_TEST(DataDescriptorTest, CopyCtorFromContiguousAsStridedArray) { auto memory = create_memory<TypeParam>(MEMORY_TYPE::ARRAY_CONTIGUOUS_AS_STRIDED); auto data = common::make_data(memory.data.get(), memory.num_blocks, memory.block_size, memory.stride); check_copy_ctor<TypeParam>(data); auto data_const = common::make_data(static_cast<const TypeParam*>(memory.data.get()), memory.num_blocks, memory.block_size, memory.stride); check_copy_ctor<const TypeParam>(data_const); } TYPED_TEST(DataDescriptorTest, CopyCtorFromStridedArray) { auto memory = create_memory<TypeParam>(MEMORY_TYPE::ARRAY_STRIDED); auto data = common::make_data(memory.data.get(), memory.num_blocks, memory.block_size, memory.stride); check_copy_ctor<TypeParam>(data); auto data_const = common::make_data(const_cast<const TypeParam*>(memory.data.get()), memory.num_blocks, memory.block_size, memory.stride); check_copy_ctor<const TypeParam>(data_const); } template <class TypeParam, class Buffer> void check_temporary(Buffer& data) { auto data_temp = create_temporary_buffer(data); EXPECT_NE(common::data_pointer(data), common::data_pointer(data_temp)); EXPECT_EQ(common::data_count(data), common::data_count(data_temp)); EXPECT_TRUE(common::data_iscontiguous(data_temp)); } TYPED_TEST(DataDescriptorTest, CreateTemporaryFromPointer) { TypeParam value = 26; auto data = common::make_data(&value, 1); check_temporary<TypeParam>(data); const TypeParam value_const = value; auto data_const = common::make_data(&value_const, 1); check_temporary<const TypeParam>(data_const); } TYPED_TEST(DataDescriptorTest, CreateTemporaryFromCArray) { const int N = 13; TypeParam value_array[N]{}; auto data = common::make_data(value_array, N); check_temporary<TypeParam>(data); const TypeParam value_array_const[N]{}; auto data_const = common::make_data(value_array_const, N); check_temporary<const TypeParam>(data_const); } TYPED_TEST(DataDescriptorTest, CreateTemporaryFromContiguousArray) { auto memory = create_memory<TypeParam>(MEMORY_TYPE::ARRAY_CONTIGUOUS); auto data = common::make_data(memory.data.get(), memory.num_blocks, memory.block_size, memory.stride); check_temporary<TypeParam>(data); auto data_const = common::make_data(static_cast<const TypeParam*>(memory.data.get()), memory.num_blocks, memory.block_size, memory.stride); check_temporary<const TypeParam>(data_const); } TYPED_TEST(DataDescriptorTest, CreateTemporaryFromContiguousAsStridedArray) { auto memory = create_memory<TypeParam>(MEMORY_TYPE::ARRAY_CONTIGUOUS_AS_STRIDED); auto data = common::make_data(memory.data.get(), memory.num_blocks, memory.block_size, memory.stride); check_temporary<TypeParam>(data); auto data_const = common::make_data(static_cast<const TypeParam*>(memory.data.get()), memory.num_blocks, memory.block_size, memory.stride); check_temporary<const TypeParam>(data_const); } TYPED_TEST(DataDescriptorTest, CreateTemporaryFromStridedArray) { auto memory = create_memory<TypeParam>(MEMORY_TYPE::ARRAY_STRIDED); auto data = common::make_data(memory.data.get(), memory.num_blocks, memory.block_size, memory.stride); check_temporary<TypeParam>(data); auto data_const = common::make_data(const_cast<const TypeParam*>(memory.data.get()), memory.num_blocks, memory.block_size, memory.stride); check_temporary<const TypeParam>(data_const); } template <class T> auto create_data_from_memory(memory_data<T>& memory) { return common::make_data(memory.data.get(), memory.num_blocks, memory.block_size, memory.stride); } template <class T> auto create_const_data_from_memory(memory_data<T>& memory) { return common::make_data(const_cast<const T*>(memory.data.get()), memory.num_blocks, memory.block_size, memory.stride); } TYPED_TEST(DataDescriptorTest, CopyDataCArrays) { const int N = 13; TypeParam memory_src[N]; TypeParam memory_dst[N]; for (int i = 0; i < N; ++i) memory_src[i] = dlaf_test::TypeUtilities<TypeParam>::element(i, 0); auto data_src = common::make_data(const_cast<const TypeParam*>(memory_src), N); auto data_dest = common::make_data(memory_dst, N); common::copy(data_src, data_dest); for (int i = 0; i < N; ++i) EXPECT_EQ(dlaf_test::TypeUtilities<TypeParam>::element(i, 0), memory_dst[i]); } TYPED_TEST(DataDescriptorTest, CopyDataArrays) { auto memory_types = {MEMORY_TYPE::ARRAY_CONTIGUOUS, MEMORY_TYPE::ARRAY_CONTIGUOUS_AS_STRIDED, MEMORY_TYPE::ARRAY_STRIDED}; for (auto memory_type : memory_types) { auto memory_src = create_memory<TypeParam>(memory_type); auto memory_dest = create_memory<TypeParam>(memory_type); for (std::size_t i = 0; i < memory_src.num_blocks * memory_src.block_size; ++i) memory_src[i] = dlaf_test::TypeUtilities<TypeParam>::element(i, 0); auto data_src = create_const_data_from_memory(memory_src); auto data_dest = create_data_from_memory(memory_dest); common::copy(data_src, data_dest); for (std::size_t i = 0; i < memory_src.num_blocks * memory_src.block_size; ++i) EXPECT_EQ(dlaf_test::TypeUtilities<TypeParam>::element(i, 0), memory_dest[i]); } } TYPED_TEST(DataDescriptorTest, CopyDataHeterogeneous) { const std::size_t N = 26; const std::size_t N_GROUPS = 2; static_assert(N % N_GROUPS == 0, "Incompatible geometry"); std::vector<memory_data<TypeParam>> memory_types; // memory contiguous memory_types.emplace_back(create_memory<TypeParam>(1, N, 0)); // memory contiguous as strided memory_types.emplace_back(create_memory<TypeParam>(N_GROUPS, N / N_GROUPS, N / N_GROUPS)); // memory strided memory_types.emplace_back(create_memory<TypeParam>(N_GROUPS, N / N_GROUPS, N / N_GROUPS + 5)); // CArray as source for (auto& memory_dest : memory_types) { TypeParam memory_array[N]; for (std::size_t i = 0; i < N; ++i) memory_array[i] = dlaf_test::TypeUtilities<TypeParam>::element(i, 0); for (std::size_t i = 0; i < N; ++i) memory_dest[i] = 0; auto data_array = common::make_data(memory_array, N); auto data_dest = create_data_from_memory(memory_dest); copy(data_array, data_dest); for (std::size_t i = 0; i < N; ++i) EXPECT_EQ(dlaf_test::TypeUtilities<TypeParam>::element(i, 0), memory_dest[i]); } // CArray as destination for (auto& memory_src : memory_types) { TypeParam memory_array[N]; for (std::size_t i = 0; i < N; ++i) memory_array[i] = 0; for (std::size_t i = 0; i < N; ++i) memory_src[i] = dlaf_test::TypeUtilities<TypeParam>::element(i, 0); auto data_src = create_const_data_from_memory(memory_src); auto data_array = common::make_data(memory_array, N); copy(data_src, data_array); for (std::size_t i = 0; i < N; ++i) EXPECT_EQ(dlaf_test::TypeUtilities<TypeParam>::element(i, 0), memory_array[i]); } // Other combinations for (auto& memory_src : memory_types) { for (auto& memory_dest : memory_types) { if (&memory_src == &memory_dest) continue; for (std::size_t i = 0; i < N; ++i) memory_src[i] = dlaf_test::TypeUtilities<TypeParam>::element(i, 0); for (std::size_t i = 0; i < N; ++i) memory_dest[i] = 0; auto data_src = create_const_data_from_memory(memory_src); auto data_dest = create_data_from_memory(memory_dest); copy(data_src, data_dest); for (std::size_t i = 0; i < N; ++i) EXPECT_EQ(dlaf_test::TypeUtilities<TypeParam>::element(i, 0), memory_dest[i]); } } }
37.49589
105
0.716426
haampie
b14bc0829b9f8f176aef586a0dec353987a18f67
4,607
cpp
C++
GLSLParametricCurve/BezierCurve/BezierCurveMain.cpp
jxt1234/ThirdPartyUsefulCode
a91813b2b0b7c521ecceff2be40ba5962635bbfa
[ "Apache-2.0" ]
2
2017-04-12T13:47:48.000Z
2017-08-08T11:51:39.000Z
GLSLParametricCurve/BezierCurve/BezierCurveMain.cpp
jxt1234/ThirdPartyUsefulCode
a91813b2b0b7c521ecceff2be40ba5962635bbfa
[ "Apache-2.0" ]
null
null
null
GLSLParametricCurve/BezierCurve/BezierCurveMain.cpp
jxt1234/ThirdPartyUsefulCode
a91813b2b0b7c521ecceff2be40ba5962635bbfa
[ "Apache-2.0" ]
null
null
null
/* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/> */ #include <iostream> #define GLEW_STATIC #include <GL/glew.h> #include <gl/freeglut.h> #include "LoadShaders.h" #include <glm/glm.hpp> #include <glm/gtx/transform.hpp> #include <glm/gtc/type_ptr.hpp> using namespace glm; using namespace std; mat4 matMV; mat4 matP; enum eVertexArrayObject { VAOCurve, VAOCount }; enum eVertexBufferObject { VBOCurve, VBOCount }; enum eShader { BezierCurveShader, FixedFuncShader, ShaderCount }; GLuint vao[VAOCount]; GLuint vbo[VBOCount]; GLuint glsl[ShaderCount]; GLfloat curve_pts[][3] = { { -4.f, -3.f, 0.f }, { -2.f, 3.f, 0.f }, { 3.f, 2.f, 0.f }, { 4.f,-1.f, 0.f } }; const double WORLD_SIZE = 5.; void initBezierCurveShader() { ShaderInfo shader_info[] = { { GL_VERTEX_SHADER, "../src/glsl/bezier_curve.vert" }, { GL_TESS_CONTROL_SHADER, "../src/glsl/bezier_curve.tess" }, { GL_TESS_EVALUATION_SHADER, "../src/glsl/bezier_curve.eval" }, { GL_FRAGMENT_SHADER, "../src/glsl/bezier_curve.frag" }, { GL_NONE, NULL } }; glsl[BezierCurveShader] = LoadShaders(shader_info); glBindVertexArray( vao[ VAOCurve ] ); glBindBuffer( GL_ARRAY_BUFFER, vbo[ VBOCurve ] ); glBufferData( GL_ARRAY_BUFFER, sizeof(curve_pts), curve_pts, GL_STATIC_DRAW ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); glBindVertexArray( 0 ); } void initFixedFuncShader() { ShaderInfo ff_shader_info[] = { { GL_VERTEX_SHADER, "../src/glsl/vertex.glsl" }, { GL_FRAGMENT_SHADER, "../src/glsl/fragment.glsl" }, { GL_NONE, NULL } }; glsl[FixedFuncShader] = LoadShaders( ff_shader_info ); } void initGL() { glClearColor(0.7, 0.7, 0.7, 1.); glPointSize(3.); glEnable (GL_LINE_SMOOTH); glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glHint (GL_LINE_SMOOTH_HINT, GL_DONT_CARE); glGenVertexArrays( VAOCount, &vao[ 0 ] ); glGenBuffers( VBOCount, &vbo[ 0 ] ); initBezierCurveShader(); initFixedFuncShader(); glBindBuffer( GL_ARRAY_BUFFER, 0 ); glBindVertexArray( 0 ); } void cbReshape(int w, int h) { float ar = (float) w / h; glViewport(0,0, w,h); matP = glm::ortho( -WORLD_SIZE*ar, WORLD_SIZE*ar, -WORLD_SIZE, WORLD_SIZE, -1., 1. ); matMV = glm::mat4(1.); } void cbKey(unsigned char c, int w, int h ) { switch(c) { case 27:case'q': glutExit(); break; } } void drawBezierCurve() { glUseProgram( glsl[BezierCurveShader] ); GLuint locMatP = glGetUniformLocation( glsl[BezierCurveShader], "matProjection" ); GLuint locMatMV = glGetUniformLocation( glsl[BezierCurveShader], "matModelView" ); glUniformMatrix4fv( locMatP, 1, GL_FALSE, glm::value_ptr( matP ) ); glUniformMatrix4fv( locMatMV, 1, GL_FALSE, glm::value_ptr( matMV ) ); glBindVertexArray( vao[ VAOCurve ] ); glBindBuffer( GL_ARRAY_BUFFER, vbo[ VBOCurve ] ); glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, 0, 0 ); glEnableVertexAttribArray( 0 ); glPatchParameteri( GL_PATCH_VERTICES, 4 ); glDrawArrays( GL_PATCHES, 0, 4 ); glUseProgram( glsl[FixedFuncShader] ); locMatP = glGetUniformLocation( glsl[FixedFuncShader], "matProjection" ); locMatMV = glGetUniformLocation( glsl[FixedFuncShader], "matModelView" ); glUniformMatrix4fv( locMatP, 1, GL_FALSE, glm::value_ptr( matP ) ); glUniformMatrix4fv( locMatMV, 1, GL_FALSE, glm::value_ptr( matMV ) ); glDrawArrays( GL_LINE_STRIP, 0, 4 ); glDrawArrays( GL_POINTS, 0, 4 ); glBindVertexArray( 0 ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); glDisableVertexAttribArray( 0 ); } void cbDisplay() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); drawBezierCurve(); glutSwapBuffers(); } int main(int argc, char* argv[]) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE ); glutInitWindowSize(512, 512 ); glutInitContextProfile(GLUT_CORE_PROFILE); glutCreateWindow("Bezier Curve"); glutReshapeFunc(cbReshape); glutKeyboardFunc(cbKey); glutDisplayFunc(cbDisplay); glewExperimental = GL_TRUE; glewInit(); initGL(); glutMainLoop(); return 0; }
23.625641
86
0.712177
jxt1234
b14bc9a0f231be280762b19cb00aebf2e5c55308
5,199
cpp
C++
src/Apps/RtcClient/RtcClient.cpp
miseri/rtp_plus_plus
244ddd86f40f15247dd39ae7f9283114c2ef03a2
[ "BSD-3-Clause" ]
1
2021-07-14T08:15:05.000Z
2021-07-14T08:15:05.000Z
src/Apps/RtcClient/RtcClient.cpp
7956968/rtp_plus_plus
244ddd86f40f15247dd39ae7f9283114c2ef03a2
[ "BSD-3-Clause" ]
null
null
null
src/Apps/RtcClient/RtcClient.cpp
7956968/rtp_plus_plus
244ddd86f40f15247dd39ae7f9283114c2ef03a2
[ "BSD-3-Clause" ]
2
2021-07-14T08:15:02.000Z
2021-07-14T08:56:10.000Z
#include "RtcClientPch.h" #include "RtcClient.h" #include <grpc++/channel_interface.h> #include <grpc++/client_context.h> #include <grpc++/status.h> #include <grpc++/stream.h> using grpc::CompletionQueue; using grpc::ChannelInterface; using grpc::ClientContext; using grpc::ClientReader; using grpc::ClientReaderWriter; using grpc::ClientWriter; using grpc::Status; RtcClient::RtcClient(std::shared_ptr<ChannelInterface> channel) :stub_(peer_connection::PeerConnectionApi::NewStub(channel)) { } boost::optional<std::string> RtcClient::createOffer(const std::string& sContentType) { ClientContext context; peer_connection::OfferDescriptor desc; desc.set_content_type(sContentType); peer_connection::CreateSessionDescriptionResponse response; Status status = stub_->createOffer(&context, desc, &response); if (status.IsOk()) { LOG(INFO) << "RPC createOffer success"; if (response.response_code() == 200) { return boost::optional<std::string>(response.session_description().session_description()); } else { LOG(WARNING) << "Server returned error: " << response.response_code() << " " << response.response_description(); return boost::optional<std::string>(); } } else { LOG(WARNING) << "RPC createOffer failed"; return boost::optional<std::string>(); } } boost::optional<std::string> RtcClient::createAnswer(const std::string& sSessionDescription, const std::string& sContentType) { ClientContext context; peer_connection::AnswerDescriptor desc; peer_connection::SessionDescription* pOffer = new peer_connection::SessionDescription(); pOffer->set_content_type(sContentType); pOffer->set_session_description(sSessionDescription); desc.set_allocated_session_description(pOffer); peer_connection::CreateSessionDescriptionResponse response; Status status = stub_->createAnswer(&context, desc, &response); if (status.IsOk()) { LOG(INFO) << "RPC createAnswer success"; if (response.response_code() == 200) { return boost::optional<std::string>(response.session_description().session_description()); } else { LOG(WARNING) << "Server returned error: " << response.response_code() << " " << response.response_description(); return boost::optional<std::string>(); } } else { LOG(WARNING) << "RPC createAnswer failed"; return boost::optional<std::string>(); } } bool RtcClient::setRemoteDescription(const std::string& sSessionDescription, const std::string& sContentType) { ClientContext context; peer_connection::SessionDescription remoteSdp; remoteSdp.set_content_type(sContentType); remoteSdp.set_session_description(sSessionDescription); peer_connection::SetSessionDescriptionResponse response; Status status = stub_->setRemoteDescription (&context, remoteSdp, &response); if (status.IsOk()) { LOG(INFO) << "RPC setRemoteDescription success"; if (response.response_code() == 200) { return true; } else { LOG(WARNING) << "Server returned error: " << response.response_code() << " " << response.response_description(); return false; } } else { LOG(WARNING) << "RPC setRemoteDescription failed"; return false; } } bool RtcClient::startStreaming() { ClientContext context; peer_connection::StartStreamingRequest request; peer_connection::StartStreamingResponse response; Status status = stub_->startStreaming(&context, request, &response); if (status.IsOk()) { LOG(INFO) << "RPC startStreaming success"; if (response.response_code() == 200) { return true; } else { LOG(WARNING) << "startStreaming: Server returned error: " << response.response_code() << " " << response.response_description(); return false; } } else { LOG(WARNING) << "RPC startStreaming failed"; return false; } } bool RtcClient::stopStreaming() { ClientContext context; peer_connection::StopStreamingRequest request; peer_connection::StopStreamingResponse response; Status status = stub_->stopStreaming(&context, request, &response); if (status.IsOk()) { LOG(INFO) << "RPC stopStreaming success"; if (response.response_code() == 200) { return true; } else { LOG(WARNING) << "stopStreaming: Server returned error: " << response.response_code() << " " << response.response_description(); return false; } } else { LOG(WARNING) << "RPC stopStreaming failed"; return false; } } bool RtcClient::shutdownRemoteRtcServer() { ClientContext context; peer_connection::ShutdownRequest request; peer_connection::ShutdownResponse response; Status status = stub_->shutdown(&context, request, &response); if (status.IsOk()) { LOG(INFO) << "RPC shutdown success"; if (response.response_code() == 200) { return true; } else { LOG(WARNING) << "shutdown: Server returned error: " << response.response_code() << " " << response.response_description(); return false; } } else { LOG(WARNING) << "RPC shutdown failed"; return false; } } void RtcClient::reset() { stub_.reset(); }
25.737624
134
0.688017
miseri
b14cce1384a48e80692e55e175a6423c5fd03243
1,392
cpp
C++
Calculator/src/main/View/CalcScreen.cpp
Songtech-0912/InstantCalc
2b36a3a7c47a7ae358eea36a4e2d7f120456dc86
[ "MIT" ]
1
2020-09-27T12:55:41.000Z
2020-09-27T12:55:41.000Z
Calculator/src/main/View/CalcScreen.cpp
Songtech-0912/InstantCalc
2b36a3a7c47a7ae358eea36a4e2d7f120456dc86
[ "MIT" ]
177
2020-05-04T09:14:05.000Z
2022-03-25T00:02:12.000Z
Calculator/src/main/View/CalcScreen.cpp
Songtech-0912/InstantCalc
2b36a3a7c47a7ae358eea36a4e2d7f120456dc86
[ "MIT" ]
1
2021-10-31T04:42:41.000Z
2021-10-31T04:42:41.000Z
#ifndef TEST #include "CalcScreen.h" #include "../Any/View.h" #include <SDL.h> #include "../Any/Enums.h" #include "../Struct/Pair.h" #include "../Struct/Message.h" #include "../Struct/Rect.h" #include "../Struct/Point.h" #include "../Struct/Size.h" namespace ii887522::Calculator { CalcScreen::CalcScreen(SDL_Renderer*const renderer, const Rect& rect) : View{ renderer }, viewModel{ Rect{ Point{ rect.position.x, rect.position.y + 26 }, Size{ rect.size.w, rect.size.h - 26 } } }, rect{ rect } { } Action CalcScreen::reactMouseMotion(const SDL_MouseMotionEvent& motionEvent) { viewModel.reactMouseMotion(Point{ motionEvent.x, motionEvent.y }); return Action::NONE; } Action CalcScreen::reactRightMouseButtonDown(const SDL_MouseButtonEvent&) { viewModel.reactRightMouseButtonDown(); return Action::NONE; } Pair<Action, Message> CalcScreen::reactRightMouseButtonUp(const SDL_MouseButtonEvent&) { viewModel.reactRightMouseButtonUp(); return Pair{ Action::NONE, viewModel.getMessage() }; } Action CalcScreen::reactMouseLeaveWindow(const SDL_WindowEvent&) { viewModel.reactMouseLeaveWindow(); return Action::NONE; } void CalcScreen::render() { SDL_SetRenderDrawColor(getRenderer(), 192u, 192u, 192u, 255u); const SDL_Rect sdl_rect{ rect.position.x, rect.position.y, rect.size.w, rect.size.h }; SDL_RenderFillRect(getRenderer(), &sdl_rect); } } #endif
27.84
126
0.731322
Songtech-0912
b14d73045f84e5931765dac2cef570d38b7abdfa
1,740
cpp
C++
platform/default/src/mbgl/storage/asset_file_source.cpp
mueschm/mapbox-gl-native
b07db0f8d01f855dcd336aa1baabde94c5c1740d
[ "BSL-1.0", "Apache-2.0" ]
5
2019-12-02T07:13:06.000Z
2019-12-02T14:34:36.000Z
platform/default/src/mbgl/storage/asset_file_source.cpp
mueschm/mapbox-gl-native
b07db0f8d01f855dcd336aa1baabde94c5c1740d
[ "BSL-1.0", "Apache-2.0" ]
1
2020-11-21T06:55:47.000Z
2020-11-21T06:55:52.000Z
platform/default/src/mbgl/storage/asset_file_source.cpp
mueschm/mapbox-gl-native
b07db0f8d01f855dcd336aa1baabde94c5c1740d
[ "BSL-1.0", "Apache-2.0" ]
1
2020-01-03T21:38:55.000Z
2020-01-03T21:38:55.000Z
#include <mbgl/storage/asset_file_source.hpp> #include <mbgl/storage/file_source_request.hpp> #include <mbgl/storage/local_file_request.hpp> #include <mbgl/storage/response.hpp> #include <mbgl/util/string.hpp> #include <mbgl/util/thread.hpp> #include <mbgl/util/url.hpp> namespace { const std::string assetProtocol = "asset://"; } // namespace namespace mbgl { class AssetFileSource::Impl { public: Impl(ActorRef<Impl>, std::string root_) : root(std::move(root_)) { } void request(const std::string& url, ActorRef<FileSourceRequest> req) { if (!acceptsURL(url)) { Response response; response.error = std::make_unique<Response::Error>(Response::Error::Reason::Other, "Invalid asset URL"); req.invoke(&FileSourceRequest::setResponse, response); return; } // Cut off the protocol and prefix with path. const auto path = root + "/" + mbgl::util::percentDecode(url.substr(assetProtocol.size())); requestLocalFile(path, std::move(req)); } private: std::string root; }; AssetFileSource::AssetFileSource(const std::string& root) : impl(std::make_unique<util::Thread<Impl>>("AssetFileSource", root)) { } AssetFileSource::~AssetFileSource() = default; std::unique_ptr<AsyncRequest> AssetFileSource::request(const Resource& resource, Callback callback) { auto req = std::make_unique<FileSourceRequest>(std::move(callback)); impl->actor().invoke(&Impl::request, resource.url, req->actor()); return std::move(req); } bool AssetFileSource::acceptsURL(const std::string& url) { return 0 == url.rfind(assetProtocol, 0); } } // namespace mbgl
29
101
0.655747
mueschm
b151042c8b05ea1b56fee3bf423bc78e250072a4
12,920
cpp
C++
src/mailews/libews/src/impl/ews_push_notification_server.cpp
stonewell/exchange-ews-thunderbird
7b8cc41621ff29deb4145ad905344fecd60ccb0c
[ "MIT" ]
17
2016-02-24T15:13:04.000Z
2022-03-31T22:07:20.000Z
src/mailews/libews/src/impl/ews_push_notification_server.cpp
stonewell/exchange-ews-thunderbird
7b8cc41621ff29deb4145ad905344fecd60ccb0c
[ "MIT" ]
3
2016-02-24T20:05:09.000Z
2017-04-18T04:23:56.000Z
src/mailews/libews/src/impl/ews_push_notification_server.cpp
stonewell/exchange-ews-thunderbird
7b8cc41621ff29deb4145ad905344fecd60ccb0c
[ "MIT" ]
8
2018-06-01T08:32:35.000Z
2021-07-01T01:22:20.000Z
#include "libews.h" #include "ewsnNotificationServiceBindingService.h" #include "ewsnNotificationServiceBinding12Service.h" #include "ews_push_notification_server.h" #include <iostream> #include <sstream> #include <memory> #include "urlparser.h" #include "libews_c_subscribe_callback.h" #ifndef _WIN32 #define closesocket close #endif namespace ewsn { static bool get_sock_port(int sock, int & port) { struct sockaddr_in name; socklen_t namelen = sizeof(name); int err = getsockname(sock, (struct sockaddr*) &name, &namelen); if (err == -1) { return false; } port = ntohs(name.sin_port); return true; } static bool get_bind_ip(const char * ews_server, int ews_server_port, char* buffer, size_t buflen) { bool ret = false; int sock = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in name; socklen_t namelen = sizeof(name); int err; struct sockaddr_in serv; const char * p = NULL; struct hostent *server; if (sock == -1) return false; server = gethostbyname(ews_server); if (server == NULL) { return false; } memset(&serv, 0, sizeof(serv)); serv.sin_family = AF_INET; memmove((char *)&serv.sin_addr.s_addr, (char *)server->h_addr, server->h_length); serv.sin_port = htons(ews_server_port); err = connect(sock, (const struct sockaddr*) &serv, sizeof(serv)); if (err == -1) goto END; err = getsockname(sock, (struct sockaddr*) &name, &namelen); if (err == -1) goto END; p = inet_ntop(AF_INET, &name.sin_addr, buffer, buflen); if (!p) goto END; ret = true; END: closesocket(sock); return ret; } typedef ewsn2__NotificationType ews2__NotificationType; typedef ewsn2__BaseObjectChangedEventType ews2__BaseObjectChangedEventType; typedef _ewsn2__union_BaseObjectChangedEventType _ews2__union_BaseObjectChangedEventType; typedef ewsn2__ModifiedEventType ews2__ModifiedEventType; typedef ewsn2__MovedCopiedEventType ews2__MovedCopiedEventType; typedef _ewsn2__union_MovedCopiedEventType_ _ews2__union_MovedCopiedEventType_; typedef __ewsn2__union_NotificationType __ews2__union_NotificationType; #define SOAP_UNION__ews2__union_NotificationType_CopiedEvent SOAP_UNION__ewsn2__union_NotificationType_CopiedEvent #define SOAP_UNION__ews2__union_MovedCopiedEventType__OldFolderId SOAP_UNION__ewsn2__union_MovedCopiedEventType__OldFolderId #define SOAP_UNION__ews2__union_BaseObjectChangedEventType_FolderId SOAP_UNION__ewsn2__union_BaseObjectChangedEventType_FolderId #define SOAP_UNION__ews2__union_MovedCopiedEventType__OldItemId SOAP_UNION__ewsn2__union_MovedCopiedEventType__OldItemId #define SOAP_UNION__ews2__union_BaseObjectChangedEventType_ItemId SOAP_UNION__ewsn2__union_BaseObjectChangedEventType_ItemId #define SOAP_UNION__ews2__union_NotificationType_CreatedEvent SOAP_UNION__ewsn2__union_NotificationType_CreatedEvent #define SOAP_UNION__ews2__union_BaseObjectChangedEventType_FolderId SOAP_UNION__ewsn2__union_BaseObjectChangedEventType_FolderId #define SOAP_UNION__ews2__union_BaseObjectChangedEventType_ItemId SOAP_UNION__ewsn2__union_BaseObjectChangedEventType_ItemId #define SOAP_UNION__ews2__union_NotificationType_DeletedEvent SOAP_UNION__ewsn2__union_NotificationType_DeletedEvent #define SOAP_UNION__ews2__union_NotificationType_ModifiedEvent SOAP_UNION__ewsn2__union_NotificationType_ModifiedEvent #define SOAP_UNION__ews2__union_NotificationType_MovedEvent SOAP_UNION__ewsn2__union_NotificationType_MovedEvent #define SOAP_UNION__ews2__union_NotificationType_NewMailEvent SOAP_UNION__ewsn2__union_NotificationType_NewMailEvent #include "ews_gsoap_notification_handler.cpp" class DLL_LOCAL CLocalEwsGsoapNotificationServerImpl : public NotificationServiceBindingService { public: CLocalEwsGsoapNotificationServerImpl(ews::CEWSSession * pSession, ews::CEWSSubscriptionCallback * pCallback, char * ip, int port, bool useHttps) : m_pSession(pSession) , m_pCallback(pCallback) , m_Url("") , m_Error() , m_Ip(ip) , m_Port(port) , m_UseHttps(useHttps) , m_Running(false){ } virtual ~CLocalEwsGsoapNotificationServerImpl() { } public: const ews::CEWSError * GetLastError() const { return &m_Error; } const ews::CEWSString & GetURL() const { return m_Url; } virtual int SendNotification(ewsn::ewsn__SendNotificationResponseType* response, ewsn::ewsn__SendNotificationResultType&); virtual int run(int port); virtual int stop(); virtual SOAP_SOCKET bind(const char *host, int port, int backlog); virtual bool BuildUrl(); private: ews::CEWSSession * m_pSession; std::auto_ptr<ews::CEWSSubscriptionCallback> m_pCallback; ews::CEWSString m_Url; ews::CEWSError m_Error; public: char * m_Ip; int m_Port; bool m_UseHttps; bool m_Running; }; } using namespace ewsn; int ewsn::NotificationServiceBindingService::SendNotification(ewsn::ewsn__SendNotificationResponseType*, ewsn::ewsn__SendNotificationResultType&) { return SOAP_SVR_FAULT; } int ewsn::NotificationServiceBinding12Service::SendNotification(ewsn::ewsn__SendNotificationResponseType*, ewsn::ewsn__SendNotificationResultType&) { return SOAP_SVR_FAULT; } CLocalEWSPushNotificationServer::CLocalEWSPushNotificationServer(ews::CEWSSession * pSession, ews::CEWSSubscriptionCallback * pCallback, char * ip, int port, bool useHttps) : m_pSession(pSession) , m_pCallback(pCallback) , m_pServerImpl(new CLocalEwsGsoapNotificationServerImpl(m_pSession, m_pCallback, ip, port, useHttps)) { } CLocalEWSPushNotificationServer::~CLocalEWSPushNotificationServer() { } int CLocalEWSPushNotificationServer::Bind() { SOAP_SOCKET s = m_pServerImpl->bind(m_pServerImpl->m_Ip, m_pServerImpl->m_Port /*port*/, 100); if (!soap_valid_socket(s)) return EWS_FAIL; if (!m_pServerImpl->BuildUrl()) { return EWS_FAIL; } return EWS_SUCCESS; } int CLocalEWSPushNotificationServer::Run() { int ret = m_pServerImpl->run(0); if (ret == SOAP_OK) return EWS_SUCCESS; else { return EWS_FAIL; } } int CLocalEWSPushNotificationServer::Stop() { m_pServerImpl->stop(); return EWS_SUCCESS; } const ews::CEWSString & CLocalEWSPushNotificationServer::GetURL() const { return m_pServerImpl->GetURL(); } const ews::CEWSError * CLocalEWSPushNotificationServer::GetLastError() const { return m_pServerImpl->GetLastError(); } int CLocalEwsGsoapNotificationServerImpl::SendNotification(ewsn::ewsn__SendNotificationResponseType* response, ewsn::ewsn__SendNotificationResultType&) { ewsn::__ewsn__union_ArrayOfResponseMessagesType * __union_ArrayOfResponseMessagesType = response->ResponseMessages->__union_ArrayOfResponseMessagesType; ewsn::ewsn2__NotificationType * Notification = __union_ArrayOfResponseMessagesType->union_ArrayOfResponseMessagesType.SendNotificationResponseMessage->Notification; ewsn::ProcessNotificationMessage(Notification, m_pCallback.get()); return SOAP_OK; } bool CLocalEwsGsoapNotificationServerImpl::BuildUrl() { if (!soap_valid_socket(this->master)) { m_Error.SetErrorCode(EWS_FAIL); m_Error.SetErrorMessage("Build Url failed, invalid socket."); return false; } //build url int port = m_Port; char bind_ip[255] = {0}; char port_buf[255] = {0}; if (!m_Ip) { UrlParser parser(m_pSession->GetConnectionInfo()->Endpoint.GetData()); std::string endpoint_host; int endpoint_port = 0; endpoint_host = parser.GetHost(); if (parser.GetPort().empty()) { std::string schema = parser.GetSchema(); UrlParser::strToLower(schema); if (!schema.compare(std::string("https"))) { endpoint_port = 443; } else { endpoint_port = 80; } } else { endpoint_port = atoi(parser.GetPort().c_str()); } if (!get_sock_port(this->master, port) || !get_bind_ip(endpoint_host.c_str(), endpoint_port, bind_ip, 254)) { m_Error.SetErrorCode(EWS_FAIL); m_Error.SetErrorMessage("Build Url failed, unable to get port or ip."); return false; } } else { sprintf(bind_ip, "%s", m_Ip); } sprintf(port_buf, "%d", (port & 0xFFFF)); m_Url.Clear(); if (m_UseHttps) { m_Url.Append("https://"); } else { m_Url.Append("http://"); } m_Url.Append(bind_ip); m_Url.Append(":"); m_Url.Append(port_buf); return true; } int CLocalEwsGsoapNotificationServerImpl::stop() { m_Running = false; return 0; } int CLocalEwsGsoapNotificationServerImpl::run(int port) { this->accept_timeout = 5; m_Running = true; if (soap_valid_socket(this->master) || soap_valid_socket(bind(NULL, port, 100))) { while(m_Running) { SOAP_SOCKET s = accept(); if (!m_Running) { break; } if (!soap_valid_socket(s)) { if (this->errnum || !m_Running) break; continue; } if (serve()) break; soap_destroy(this); soap_end(this); } } if (this->error != SOAP_OK && m_Running) { m_Error.SetErrorCode(EWS_FAIL); std::stringstream os; os << "error code:" << this->error << std::endl; soap_stream_fault(os); m_Error.SetErrorMessage(os.str().c_str()); } m_Running = false; return this->error; } SOAP_SOCKET CLocalEwsGsoapNotificationServerImpl::bind(const char *host, int port, int backlog) { int ret = NotificationServiceBindingService::bind(host, port, backlog); if (this->error != SOAP_OK) { m_Error.SetErrorCode(EWS_FAIL); std::stringstream os; os << "error code:" << this->error << std::endl; soap_stream_fault(os); m_Error.SetErrorMessage(os.str().c_str()); } return ret; } int ews_notification_server_bind(ews_notification_server * server) { CLocalEWSPushNotificationServer * s = (CLocalEWSPushNotificationServer*)server; return s->Bind(); } int ews_notification_server_run(ews_notification_server * server) { CLocalEWSPushNotificationServer * s = (CLocalEWSPushNotificationServer*)server; return s->Run(); } int ews_notification_server_stop(ews_notification_server * server) { CLocalEWSPushNotificationServer * s = (CLocalEWSPushNotificationServer*)server; return s->Stop(); } int ews_free_notification_server(ews_notification_server * server) { CLocalEWSPushNotificationServer * s = (CLocalEWSPushNotificationServer*)server; delete s; return EWS_SUCCESS; } int ews_notification_server_get_url(ews_notification_server * server, char ** pp_url) { CLocalEWSPushNotificationServer * s = (CLocalEWSPushNotificationServer*)server; std::string url = s->GetURL().GetData(); *pp_url = strdup(url.c_str()); return EWS_SUCCESS; } ews_notification_server * ews_create_notification_server(ews_session * session, ews_event_notification_callback * pcallback, ews_notification_server_params * params ) { std::auto_ptr<ews::c::CLocalEWSSubscriptionCallback_C> callback(new ews::c::CLocalEWSSubscriptionCallback_C(pcallback)); std::auto_ptr<CLocalEWSPushNotificationServer> server(new CLocalEWSPushNotificationServer((ews::CEWSSession *)session, callback.release(), params? params->ip : NULL, params? params->port : 0, params? (params->use_https ? true : false) : false)); return (ews_notification_server*)server.release(); }
32.708861
147
0.655882
stonewell
b151a8d6e3b44fa6faebb6e4c111070d0dd085d1
1,950
hpp
C++
AirLib/include/physics/PhysicsEngineBase.hpp
whatseven/AirSim
fe7e4e7c782cf1077594c1ee6cc1bbfec3f66bd1
[ "MIT" ]
7
2020-05-22T18:00:19.000Z
2021-01-07T08:31:19.000Z
AirLib/include/physics/PhysicsEngineBase.hpp
Abdulkadir-Muhendis/AirSim
c6f0729006ecd6d792a750edc7e27021469c5649
[ "MIT" ]
4
2020-08-21T07:48:06.000Z
2021-03-14T21:06:41.000Z
AirLib/include/physics/PhysicsEngineBase.hpp
Abdulkadir-Muhendis/AirSim
c6f0729006ecd6d792a750edc7e27021469c5649
[ "MIT" ]
7
2020-05-22T20:08:22.000Z
2021-01-22T09:39:17.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef airsim_core_PhysicsEngineBase_hpp #define airsim_core_PhysicsEngineBase_hpp #include "common/UpdatableContainer.hpp" #include "common/Common.hpp" #include "PhysicsBody.hpp" namespace msr { namespace airlib { class PhysicsEngineBase : public UpdatableObject { public: virtual void update() override { UpdatableObject::update(); } virtual void reportState(StateReporter& reporter) override { unused(reporter); //default nothing to report for physics engine } //TODO: reduce copy-past from UpdatableContainer which has same code /********************** Container interface **********************/ typedef PhysicsBody* TUpdatableObjectPtr; typedef vector<TUpdatableObjectPtr> MembersContainer; typedef typename MembersContainer::iterator iterator; typedef typename MembersContainer::const_iterator const_iterator; typedef typename MembersContainer::value_type value_type; iterator begin() { return members_.begin(); } iterator end() { return members_.end(); } const_iterator begin() const { return members_.begin(); } const_iterator end() const { return members_.end(); } uint size() const { return static_cast<uint>(members_.size()); } const TUpdatableObjectPtr &at(uint index) const { return members_.at(index); } TUpdatableObjectPtr &at(uint index) { return members_.at(index); } //allow to override membership modifications virtual void clear() { members_.clear(); } virtual void insert(TUpdatableObjectPtr member) { members_.push_back(member); } virtual void erase_remove(TUpdatableObjectPtr obj) { members_.erase(std::remove(members_.begin(), members_.end(), obj), members_.end()); } private: MembersContainer members_; }; }} //namespace #endif
36.111111
94
0.692821
whatseven
b151e54b639883e69c4ddf8e8c5b17ccbaf6a1ac
137,676
cxx
C++
inetsrv/iis/iisrearc/iisplus/w3isapi/server_support.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetsrv/iis/iisrearc/iisplus/w3isapi/server_support.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetsrv/iis/iisrearc/iisplus/w3isapi/server_support.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 1999-2001 Microsoft Corporation Module Name : server_support.cxx Abstract: IIS Plus ServerSupportFunction command implementations Author: Wade Hilmo (wadeh) 05-Apr-2000 Project: w3isapi.dll --*/ #include "precomp.hxx" #include "isapi_context.hxx" #include "server_support.hxx" // // BUGBUG - stristr is declared in iisrearc\core\inc\irtlmisc.h, // but doesn't appear to be implemented anywhere. Because of the // way it's declared in that file, we have to use a different // function name here... // const char* stristr2( const char* pszString, const char* pszSubString ); HRESULT SSFSendResponseHeader( ISAPI_CONTEXT * pIsapiContext, LPSTR szStatus, LPSTR szHeaders ) /*++ Routine Description: Sends HTTP status and headers to the client. Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. szStatus - The status to send to the client (ie. "200 OK") szHeaders - Headers to send to the client (ie. foo1: value1\r\n\r\n") Return Value: HRESULT --*/ { IIsapiCore * pIsapiCore; HRESULT hr; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_SEND_RESPONSE_HEADER[%p]: Function Entry\r\n" " Status: '%s'\r\n" " Headers: '%s'\r\n" " <END>\r\n\r\n", pIsapiContext, szStatus, szHeaders )); } pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_SEND_RESPONSE_HEADER[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // We need validate the fKeepConn status for the request now, // since http.sys will generate the connection response // header based on it. // // If we're going to support keep-alive, then the // ISAPI must return either a content-length header, // or use chunked transfer encoding. We'll check for // that here. // if ( pIsapiContext->QueryClientKeepConn() ) { if ( szHeaders != NULL && ( stristr2( szHeaders, "content-length: " ) != NULL || stristr2( szHeaders, "transfer-encoding: chunked" ) != NULL ) ) { pIsapiContext->SetKeepConn( TRUE ); } } // // Since we automatically decided to keep the connection alive // or not, we should not honor HSE_STATUS_SUCCESS_AND_KEEP_CONN. // This maintains compatibility with previous IIS versions. // pIsapiContext->SetHonorAndKeepConn( FALSE ); // // Note that NULL is valid for both szStatus and szHeaders, // so there's no need to validate them. // hr = pIsapiCore->SendResponseHeaders( !pIsapiContext->QueryKeepConn(), szStatus, szHeaders, HSE_IO_SYNC ); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_SEND_RESPONSE_HEADER[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } else { pIsapiContext->SetHeadersSent( TRUE ); } IF_DEBUG( ISAPI_SSF_DETAILS ) { IF_DEBUG( ISAPI_SUCCESS_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_SEND_RESPONSE_HEADER[%p]: Succeeded\r\n" " <END>\r\n\r\n", pIsapiContext )); } } return hr; } HRESULT SSFSendResponseHeaderEx( ISAPI_CONTEXT * pIsapiContext, HSE_SEND_HEADER_EX_INFO * pHeaderInfo ) /*++ Routine Description: Sends HTTP status and headers to the client, and offers explicit control over keep-alive for this request. Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. pHeaderInfo - The response info to be passed to the client Return Value: HRESULT --*/ { IIsapiCore * pIsapiCore; HRESULT hr; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_SEND_RESPONSE_HEADER_EX[%p]: Function Entry\r\n" " Status: '%s'\r\n" " Headers: '%s'\r\n" " KeepConn: %d\r\n", pIsapiContext, pHeaderInfo->pszStatus, pHeaderInfo->pszHeader, pHeaderInfo->fKeepConn )); } pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_SEND_RESPONSE_HEADER_EX[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // Validate parameters // if ( pHeaderInfo == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_SEND_RESPONSE_HEADER_EX[%p]: Parameter validation failure\r\n" " pHeaderInfo: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // Set the keep connection flag. It can only be TRUE if the // ISAPI and the client both want keep alive. // // Note that we are trusting the ISAPI to provide some kind // of content length in the case where it's setting fKeepConn // to TRUE. This is the same behavior as IIS 5 which, for // performance reasons, doesn't try to parse the headers from // the ISAPI. // if ( pHeaderInfo->fKeepConn && pIsapiContext->QueryClientKeepConn() ) { pIsapiContext->SetKeepConn( TRUE ); } hr = pIsapiCore->SendResponseHeaders( !pIsapiContext->QueryKeepConn(), const_cast<LPSTR>( pHeaderInfo->pszStatus ), const_cast<LPSTR>( pHeaderInfo->pszHeader ), HSE_IO_SYNC ); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_SEND_RESPONSE_HEADER_EX[%p]: Failed.\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } else { pIsapiContext->SetHeadersSent( TRUE ); } IF_DEBUG( ISAPI_SSF_DETAILS ) { IF_DEBUG( ISAPI_SUCCESS_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_SEND_RESPONSE_HEADER_EX[%p]: Succeeded\r\n" " <END>\r\n", pIsapiContext )); } } return hr; } HRESULT SSFMapUrlToPath( ISAPI_CONTEXT * pIsapiContext, LPSTR szBuffer, LPDWORD pcbBuffer ) /*++ Routine Description: Maps a URL into a physical path Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. szBuffer - On entry, contains the URL to map. On return, contains the mapped physical path. pcbBuffer - On entry, the size of szBuffer. On successful return, the number of bytes copied to szUrl. On failed return, the number of bytes needed for the physical path. Return Value: HRESULT --*/ { IIsapiCore * pIsapiCore; HRESULT hr; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_MAP_URL_TO_PATH[%p]: Function Entry\r\n" " URL: %s\r\n" " <END>\r\n\r\n", pIsapiContext, szBuffer )); } pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_MAP_URL_TO_PATH[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // Validate parameters // if ( szBuffer == NULL || pcbBuffer == NULL || *pcbBuffer == 0 ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_MAP_URL_TO_PATH[%p]: Parameter validation failure\r\n" " Buffer: '%s'\r\n" " Buffer Size Ptr: %p\r\n" " Buffer Size: %d\r\n", pIsapiContext, pcbBuffer, pcbBuffer ? *pcbBuffer : 0 )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } hr = pIsapiCore->MapPath( reinterpret_cast<BYTE*>( szBuffer ), *pcbBuffer, pcbBuffer, FALSE ); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_MAP_URL_TO_PATH[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } IF_DEBUG( ISAPI_SSF_DETAILS ) { IF_DEBUG( ISAPI_SUCCESS_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_MAP_URL_TO_PATH[%p]: Succeeded\r\n" " Mapped URL: %s\r\n" " <END>\r\n\r\n", pIsapiContext, szBuffer )); } } return hr; } HRESULT SSFMapUrlToPathEx( ISAPI_CONTEXT * pIsapiContext, LPSTR szUrl, HSE_URL_MAPEX_INFO * pHseMapInfo, LPDWORD pcbMappedPath ) /*++ Routine Description: Maps a URL to a physical path and returns some metadata metrics for the URL to the caller. Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. szUrl - The URL to map pHseMapInfo - Upon return, contains the mapped URL info pcbMappedPath - If non-NULL, contains the buffer size needed to store the mapped physical path. Return Value: HRESULT --*/ { IIsapiCore * pIsapiCore; DWORD cbMapped; HRESULT hr; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_MAP_URL_TO_PATH_EX[%p]: Function Entry\r\n" " URL='%s'\r\n" " <END>\r\n\r\n", pIsapiContext, szUrl )); } pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_MA_URL_TO_PATH_EX[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // Additional parameter validation // if ( szUrl == NULL || pHseMapInfo == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_MAP_URL_TO_PATH_EX[%p]: Parameter validation failure\r\n" " URL: '%s'\r\n" " HSE_URL_MAPEX_INFO: %p\r\n" " <END>\r\n\r\n", pIsapiContext, szUrl, pHseMapInfo )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // The inline buffer within the HSE_URL_MAPEX_INFO structure // is defined as being MAX_PATH size. // cbMapped = MAX_PATH; pHseMapInfo->dwReserved1 = 0; pHseMapInfo->dwReserved2 = 0; hr = pIsapiCore->MapPathEx( reinterpret_cast<BYTE*>( szUrl ), (DWORD)strlen(szUrl) + 1, reinterpret_cast<BYTE*>( pHseMapInfo->lpszPath ), cbMapped, pcbMappedPath ? pcbMappedPath : &cbMapped, &pHseMapInfo->cchMatchingPath, &pHseMapInfo->cchMatchingURL, &pHseMapInfo->dwFlags, FALSE ); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_MAP_URL_TO_PATH_EX[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } return hr; } HRESULT SSFMapUnicodeUrlToPath( ISAPI_CONTEXT * pIsapiContext, LPWSTR szBuffer, LPDWORD pcbBuffer ) /*++ Routine Description: Maps a URL into a physical path Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. szBuffer - On entry, contains the URL to map. On return, contains the mapped physical path. pcbBuffer - On entry, the size of szBuffer. On successful return, the number of bytes copied to szUrl. On failed return, the number of bytes needed for the physical path. Return Value: HRESULT --*/ { IIsapiCore * pIsapiCore; HRESULT hr; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_MAP_UNICODE_URL_TO_PATH[%p]: Function Entry\r\n" " URL='%S'\r\n" " <END>\r\n\r\n", pIsapiContext, szBuffer )); } pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_MA_UNICODE_URL_TO_PATH[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // Validate parameters // if ( szBuffer == NULL || pcbBuffer == NULL || *pcbBuffer == 0 ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_MAP_UNICODE_URL_TO_PATH[%p]: Parameter validation failure\r\n" " Buffer: '%S'\r\n" " Buffer Size Ptr: %p\r\n" " Buffer Size: %d\r\n" " <END>\r\n\r\n", pIsapiContext, szBuffer, pcbBuffer, pcbBuffer ? *pcbBuffer : 0 )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } hr = pIsapiCore->MapPath( reinterpret_cast<BYTE*>( szBuffer ), *pcbBuffer, pcbBuffer, TRUE ); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_MAP_UNICODE_URL_TO_PATH[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } return hr; } HRESULT SSFMapUnicodeUrlToPathEx( ISAPI_CONTEXT * pIsapiContext, LPWSTR szUrl, HSE_UNICODE_URL_MAPEX_INFO *pHseMapInfo, LPDWORD pcbMappedPath ) /*++ Routine Description: Maps a URL to a physical path and returns some metadata metrics for the URL to the caller. Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. szUrl - The URL to map pHseMapInfo - Upon return, contains the mapped URL info pcbMappedPath - If non-NULL, contains the buffer size needed to store the mapped physical path. Return Value: HRESULT --*/ { IIsapiCore * pIsapiCore; DWORD cbMapped; HRESULT hr; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_MAP_UNICODE_URL_TO_PATH_EX[%p]: Function Entry\r\n" " URL='%S'\r\n" " <END>\r\n\r\n", pIsapiContext, szUrl )); } pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_MA_UNICODE_URL_TO_PATH_EX[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // Additional parameter validation // if ( szUrl == NULL || pHseMapInfo == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_MAP_UNICODE_URL_TO_PATH_EX[%p]: Parameter validation failure\r\n" " URL: '%s'\r\n" " pHseMapInfo: %p\r\n" " <END>\r\n\r\n", pIsapiContext, szUrl, pHseMapInfo )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // The inline buffer within the HSE_URL_MAPEX_INFO structure // is defined as being MAX_PATH size. // cbMapped = MAX_PATH * sizeof(WCHAR); hr = pIsapiCore->MapPathEx( reinterpret_cast<BYTE*>( szUrl ), (DWORD)(wcslen(szUrl) + 1)*sizeof(WCHAR), reinterpret_cast<BYTE*>( pHseMapInfo->lpszPath ), cbMapped, pcbMappedPath ? pcbMappedPath : &cbMapped, &pHseMapInfo->cchMatchingPath, &pHseMapInfo->cchMatchingURL, &pHseMapInfo->dwFlags, TRUE ); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_MAP_UNICODE_URL_TO_PATH_EX[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } return hr; } HRESULT SSFGetImpersonationToken( ISAPI_CONTEXT * pIsapiContext, HANDLE * phToken ) /*++ Routine Description: Returns a (non-duplicated) copy of the token that the server is using to impersonate the client for this request. Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. phToken - Upon return, contains a copy of the token. Return Value: HRESULT --*/ { DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_IMPERSONATION_TOKEN[%p]: Function Entry\r\n" " <END>\r\n\r\n", pIsapiContext )); } // // Validate parameters // if ( phToken == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_IMPERSONATION_TOKEN[%p]: Parameter validation failure\r\n" " Token Ptr: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } *phToken = pIsapiContext->QueryToken(); return NO_ERROR; } HRESULT SSFIsKeepConn( ISAPI_CONTEXT * pIsapiContext, BOOL * pfIsKeepAlive ) /*++ Routine Description: Returns information about whether the client wants us to keep the connection open or not at completion of this request. Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. pfIsKeepAlive - Upon return, TRUE if IIS will be keeping the connection alive, else FALSE. Return Value: HRESULT --*/ { DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_IS_KEEP_CONN[%p]: Function Entry\r\n" " <END>\r\n\r\n", pIsapiContext )); } // // Validate parameters // if ( pfIsKeepAlive == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_IS_KEEP_CONN[%p]: Parameter validation failure\r\n" " KeepAlive Ptr: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } *pfIsKeepAlive = pIsapiContext->QueryClientKeepConn(); return NO_ERROR; } HRESULT SSFDoneWithSession( ISAPI_CONTEXT * pIsapiContext, DWORD * pHseResult ) /*++ Routine Description: Notifies the server that the calling ISAPI is done with the ECB (and ISAPI_CONTEXT) for this request and that the server can clean up. Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. pHseResult - A pointer to the HSE_STATUS code that the extension wants to use. Return Value: HRESULT --*/ { IIsapiCore * pIsapiCore; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); DBG_ASSERT( pIsapiContext->QueryIoState() == NoAsyncIoPending ); DBG_REQUIRE( ( pIsapiCore = pIsapiContext->QueryIsapiCoreInterface() ) != NULL ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_DONE_WITH_SESSION[%p]: Function Entry\r\n" " <END>\r\n\r\n", pIsapiContext )); } // // If the caller wants to do STATUS_SUCCESS_AND_KEEP_CONN, // then we need to do that now. // // Note that this overrides our own determination of whether // the client can support keep-alive or not. We are trusting // the caller to have returned the right headers to make this // work with the client. // if ( pHseResult && *pHseResult == HSE_STATUS_SUCCESS_AND_KEEP_CONN ) { if ( pIsapiContext->QueryClientKeepConn() ) { pIsapiContext->SetKeepConn( TRUE ); pIsapiCore->SetConnectionClose( !pIsapiContext->QueryKeepConn() ); } } // // We'll just release the reference on IsapiContext. // Its destructor will do the rest. // pIsapiContext->DereferenceIsapiContext(); pIsapiContext = NULL; return NO_ERROR; } HRESULT SSFGetCertInfoEx( ISAPI_CONTEXT * pIsapiContext, CERT_CONTEXT_EX * pCertContext ) /*++ Routine Description: Returns certificate information about the client associated with this request. Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. pCertContext - Upon return, contains info about the client cert. Return Value: HRESULT --*/ { IIsapiCore * pIsapiCore; HRESULT hr; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_CERT_INFO_EX[%p]: Function Entry\r\n" " <END>\r\n\r\n", pIsapiContext )); } pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_CERT_INFO_EX[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // Validate parameters // if ( pCertContext == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_CERT_INFO_EX[%p]: Parameter validation failure\r\n" " CertContext Ptr: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } hr = pIsapiCore->GetCertificateInfoEx( pCertContext->cbAllocated, &( pCertContext->CertContext.dwCertEncodingType ), pCertContext->CertContext.pbCertEncoded, &( pCertContext->CertContext.cbCertEncoded ), &( pCertContext->dwCertificateFlags ) ); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_CERT_INFO_EX[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } return hr; } HRESULT SSFIoCompletion( ISAPI_CONTEXT * pIsapiContext, PFN_HSE_IO_COMPLETION pCompletionRoutine, LPVOID pHseIoContext ) /*++ Routine Description: Establishes the I/O completion routine and user-defined context to be used for asynchronous operations associated with this request. Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. pCompletionRoutine - The function to call upon I/O completion pHseIoContext - The user-defined context to be passed to the completion routine. Return Value: HRESULT --*/ { DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_IO_COMPLETION[%p]: Function Entry\r\n" " Completion Routine: %p\r\n" " Context: %p\r\n" " <END>\r\n\r\n", pIsapiContext, pCompletionRoutine, pHseIoContext )); } // // Validate parameters // if ( pCompletionRoutine == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_IO_COMPLETION[%p]: Parameter validation failure\r\n" " Completion Routine: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } pIsapiContext->SetPfnIoCompletion( pCompletionRoutine ); pIsapiContext->SetExtensionContext( pHseIoContext ); return NO_ERROR; } HRESULT SSFAsyncReadClient( ISAPI_CONTEXT * pIsapiContext, LPVOID pBuffer, LPDWORD pcbBuffer ) /*++ Routine Description: Queues an asynchronous read of data from the client. Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. pBuffer - Buffer to be filled with read data. pcbBuffer - The size of pBuffer Return Value: HRESULT --*/ { IIsapiCore * pIsapiCore; DWORD cbBuffer; HRESULT hr = NOERROR; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_ASYNC_READ_CLIENT[%p]: Function Entry\r\n" " Bytes to Read: %d\r\n" " <END>\r\n\r\n", pIsapiContext, pcbBuffer ? *pcbBuffer : 0 )); } pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_ASYNC_READ_CLIENT[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // Validate parameters // if ( pIsapiContext->QueryPfnIoCompletion() == NULL || pBuffer == NULL || pcbBuffer == NULL || *pcbBuffer == 0 ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_ASYNC_READ_CLIENT[%p]: Parameter validation failure\r\n" " Completion Routine: %p\r\n" " Buffer Ptr: %p\r\n" " Buffer Size Ptr: %p\r\n" " Buffer Size: %d\r\n" " <END>\r\n\r\n", pIsapiContext, pIsapiContext->QueryPfnIoCompletion(), pBuffer, pcbBuffer, pcbBuffer ? *pcbBuffer : 0 )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // Do the async ReadClient call // if ( pIsapiContext->TryInitAsyncIo( AsyncReadPending ) == FALSE ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_ASYNC_READ_CLIENT[%p]: Failed\r\n" " Another async operation is already pending\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // Since we're never actually reading any data in the async // case, we want to prevent pIsapiCore->ReadClient() from // modifying the buffer size we report back to the caller, // so we'll use a local for cbBuffer. // cbBuffer = *pcbBuffer; // // If this call will be going OOP, save a pointer to the // read buffer so that the core can fill it when the // operation completes. // if ( pIsapiContext->QueryIsOop() ) { DBG_ASSERT( pIsapiContext->QueryAsyncIoBuffer() == NULL ); DBG_ASSERT( pIsapiContext->QueryLastAsyncIo() == 0 ); pIsapiContext->SetAsyncIoBuffer( pBuffer ); pIsapiContext->SetLastAsyncIo( cbBuffer ); } hr = pIsapiCore->ReadClient( reinterpret_cast<DWORD64>( pIsapiContext ), pIsapiContext->QueryIsOop() ? NULL : reinterpret_cast<unsigned char*>( pBuffer ), pIsapiContext->QueryIsOop() ? 0 : cbBuffer, cbBuffer, &cbBuffer, HSE_IO_ASYNC ); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_ASYNC_READ_CLIENT[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } pIsapiContext->SetAsyncIoBuffer( NULL ); pIsapiContext->SetLastAsyncIo( 0 ); pIsapiContext->UninitAsyncIo(); } return hr; } HRESULT SSFTransmitFile( ISAPI_CONTEXT * pIsapiContext, HSE_TF_INFO * pTfInfo ) /*++ Routine Description: Transmits a file, a portion of a file, or some other data (in the event on a NULL file handle) to the client. Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. pTfInfo - Describes the desired transmit file action. Return Value: HRESULT --*/ { IIsapiCore * pIsapiCore; LARGE_INTEGER cbFileSize; HRESULT hr; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { STACK_STRA( strFilename,MAX_PATH ); DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_TRANSMIT_FILE[%p]: Function Entry\r\n" " Completion Routine: %p\r\n" " Context: %p\r\n" " File Handle: %p\r\n" " Status Code: '%s'\r\n" " Bytes To Write: %d\r\n" " Offset: %d\r\n" " <END>\r\n\r\n", pIsapiContext, pTfInfo ? pTfInfo->pfnHseIO : 0, pTfInfo ? pTfInfo->pContext : 0, pTfInfo ? pTfInfo->hFile : 0, pTfInfo ? pTfInfo->pszStatusCode : 0, pTfInfo ? pTfInfo->BytesToWrite : 0, pTfInfo ? pTfInfo->Offset : 0 )); IF_DEBUG( ISAPI_DUMP_BUFFERS ) { if ( pTfInfo ) { STACK_STRA( strHead,MAX_PATH ); STACK_STRA( strTail,MAX_PATH ); DWORD dwBytesToDump; dwBytesToDump = pTfInfo->HeadLength; if ( dwBytesToDump > MAX_DEBUG_DUMP ) { dwBytesToDump = MAX_DEBUG_DUMP; } if ( FAILED( strHead.CopyBinary( pTfInfo->pHead, dwBytesToDump ) ) ) { strHead.Copy( "" ); } dwBytesToDump = pTfInfo->TailLength; if ( dwBytesToDump > MAX_DEBUG_DUMP ) { dwBytesToDump = MAX_DEBUG_DUMP; } if ( FAILED( strTail.CopyBinary( pTfInfo->pTail, dwBytesToDump ) ) ) { strTail.Copy( "" ); } DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_TRANSMIT_FILE[%p]: Dump of up to %d bytes of head and tail data\r\n" " Head Data:\r\n" "%s" " Tail Data:\r\n" "%s" " <END>\r\n", pIsapiContext, MAX_DEBUG_DUMP, strHead.QueryStr(), strTail.QueryStr() )); } } } pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_TRANSMIT_FILE[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // Validate parameters - For TRANSMIT_FILE, this means: // // - We must have an ISAPI core interface to call through // - We must have an HSE_TF_INFO structure // - The HSE_IO_ASYNC flag must be set // - If HeadLength is set, pHead cannot be NULL // - If TailLength is set, pTail cannot be NULL // - We must have either a completion routine already set // in the ISAPI_CONTEXT, or the HSE_TF_INFO must provide // one // - There can be no other async operations in progress // if ( pTfInfo == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_TRANSMIT_FILE[%p]: Parameter validation failure\r\n" " Transmit File Info Ptr: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } if ( ( pTfInfo->dwFlags & HSE_IO_ASYNC ) == 0 || pTfInfo->hFile == INVALID_HANDLE_VALUE || ( pTfInfo->HeadLength != 0 && pTfInfo->pHead == NULL ) || ( pTfInfo->TailLength != 0 && pTfInfo->pTail == NULL ) || ( pIsapiContext->QueryPfnIoCompletion() == NULL && pTfInfo->pfnHseIO == NULL ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_TRANSMIT_FILE[%p]: Parameter validation failure\r\n" " %s\r\n", " File Handle: %p\r\n" " Head: %p\r\n" " Head Length: %d\r\n" " Tail: %p\r\n" " Tail Length: %d\r\n" " Completion Routine: %p\r\n" " <END>\r\n\r\n", pIsapiContext, pTfInfo->dwFlags & HSE_IO_ASYNC ? "Async flag set" : "Async flag not set", pTfInfo->hFile, pTfInfo->pHead, pTfInfo->HeadLength, pTfInfo->pTail, pTfInfo->TailLength, pTfInfo->pfnHseIO ? pTfInfo->pfnHseIO : pIsapiContext->QueryPfnIoCompletion() )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } if ( pIsapiContext->TryInitAsyncIo( AsyncWritePending ) == FALSE ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_TRANSMIT_FILE[%p]: Failed\r\n" " Another async operation is already pending.\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // We'll do some extra validation in the case where we've been // provided a file handle. // // Specifically, we'll check to make sure that the offset and // bytes-to-write are valid for the file. // // CODEWORK - Do we really need to do this, or can http.sys handle // it? Also, does http.sys treat zero bytes to write // the same as TransmitFile (ie. send the whole file?) // if ( pTfInfo->hFile != NULL ) { if (!GetFileSizeEx(pTfInfo->hFile, &cbFileSize)) { hr = HRESULT_FROM_WIN32( GetLastError() ); goto Done; } if ( pTfInfo->Offset > cbFileSize.QuadPart || (pTfInfo->Offset > 0 && pTfInfo->Offset == cbFileSize.QuadPart ) || pTfInfo->Offset + pTfInfo->BytesToWrite > cbFileSize.QuadPart ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_TRANSMIT_FILE[%p]: Parameter validation failure\r\n" " File Size: %d\r\n" " Offset: %d\r\n" " Bytes to Write: %d\r\n" " <END>\r\n\r\n", pIsapiContext, cbFileSize.QuadPart, pTfInfo->Offset, pTfInfo->BytesToWrite )); } hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); goto Done; } } else { // // No file handle, so initialize the size to zero // cbFileSize.QuadPart = 0; } // // If the HSE_TF_INFO includes I/O completion or context // information, override the existing settings. // if ( pTfInfo->pfnHseIO ) { pIsapiContext->SetPfnIoCompletion( pTfInfo->pfnHseIO ); } if ( pTfInfo->pContext ) { pIsapiContext->SetExtensionContext( pTfInfo->pContext ); } // // If the extension is setting HSE_IO_SEND_HEADERS, then we need // to determine if it's sending some kind of content length. If // it's not, then we need to set _fKeepConn to FALSE. // // CODEWORK // Note that we're making a bold assumption here that if // HSE_IO_SEND_HEADERS is set, then pHead points to a NULL // terminated string. // if ( pIsapiContext->QueryClientKeepConn() && pTfInfo->pHead && ( pTfInfo->dwFlags & HSE_IO_SEND_HEADERS ) && !( pTfInfo->dwFlags & HSE_IO_DISCONNECT_AFTER_SEND ) ) { if ( stristr2( (LPSTR)pTfInfo->pHead, "content-length: " ) != NULL || stristr2( (LPSTR)pTfInfo->pHead, "transfer-encoding: chunked" ) != NULL ) { pIsapiContext->SetKeepConn( TRUE ); } } if ( pIsapiContext->QueryKeepConn() == FALSE ) { pTfInfo->dwFlags |= HSE_IO_DISCONNECT_AFTER_SEND; } else { // // We need to clear the HSE_IO_DISCONNECT_AFTER_SEND flag // in the case where QueryKeepConn is TRUE. // pTfInfo->dwFlags &= ~HSE_IO_DISCONNECT_AFTER_SEND; } // // Save the BytesToWrite part as _cbLastAsyncIo, since the size of // pHead and pTail confuses ISAPI's that examine the cbWritten // value on completion. // ULARGE_INTEGER cbToWrite; if ( pTfInfo->BytesToWrite ) { cbToWrite.QuadPart = pTfInfo->BytesToWrite; } else { cbToWrite.QuadPart = cbFileSize.QuadPart - pTfInfo->Offset; } // // Note that ISAPI doesn't support large integer values, so the // best we can do here is to store the low bits. // pIsapiContext->SetLastAsyncIo( cbToWrite.LowPart ); hr = pIsapiCore->TransmitFile( reinterpret_cast<DWORD64>( pIsapiContext ), reinterpret_cast<DWORD_PTR>( pTfInfo->hFile ), pTfInfo->Offset, cbToWrite.QuadPart, (pTfInfo->dwFlags & HSE_IO_SEND_HEADERS) ? const_cast<LPSTR>( pTfInfo->pszStatusCode ) : NULL, reinterpret_cast<LPBYTE>( pTfInfo->pHead ), pTfInfo->HeadLength, reinterpret_cast<LPBYTE>( pTfInfo->pTail ), pTfInfo->TailLength, pTfInfo->dwFlags ); Done: if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_TRANSMIT_FILE[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } pIsapiContext->SetLastAsyncIo( 0 ); pIsapiContext->UninitAsyncIo(); } return hr; } HRESULT SSFSendRedirect( ISAPI_CONTEXT * pIsapiContext, LPSTR szUrl ) /*++ Routine Description: Sends a 302 redirect to the client associated with this request. Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. szUrl - The target URL for the redirection. Return Value: HRESULT --*/ { IIsapiCore * pIsapiCore; HRESULT hr; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_SEND_REDIRECT[%p]: Function Entry\r\n" " URL: '%s'\r\n" " <END>\r\n\r\n", pIsapiContext, szUrl )); } pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_SEND_REDIRECT[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // Validate parameters // if ( pIsapiContext == NULL || szUrl == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_SEND_REDIRECT[%p]: Parameter validation failure\r\n" " szUrl: '%s'\r\n" " <END>\r\n\r\n", pIsapiContext, szUrl )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } if ( pIsapiContext->QueryClientKeepConn() ) { pIsapiContext->SetKeepConn( TRUE ); } hr = pIsapiCore->SendRedirect( szUrl, !pIsapiContext->QueryKeepConn() ); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_SEND_REDIRECT[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } return hr; } HRESULT SSFIsConnected( ISAPI_CONTEXT * pIsapiContext, BOOL * pfIsConnected ) /*++ Routine Description: Returns the connection state (connected or not connected) of the client associated with this request. Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. pfIsConnected - TRUE upon return if the client is connected, else FALSE. Return Value: HRESULT --*/ { IIsapiCore * pIsapiCore; HRESULT hr; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_IS_CONNECTED[%p]: Function Entry\r\n" " <END>\r\n\r\n", pIsapiContext )); } pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_IS_CONNECTED[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // Validate parameters // if ( pfIsConnected == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_IS_CONNECTED[%p]: Parameter validation failure\r\n" " IsConnected Ptr: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } hr = pIsapiCore->TestConnection( pfIsConnected ); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_IS_CONNECTED[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } return hr; } HRESULT SSFAppendLog( ISAPI_CONTEXT * pIsapiContext, LPSTR szExtraParam ) /*++ Routine Description: Appends the string passed to the QueryString that will be logged Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. szExtraParam - The extra parameter to be logged Return Value: HRESULT --*/ { IIsapiCore * pIsapiCore; HRESULT hr; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_APPEND_LOG_PARAMETER[%p]: Function Entry\r\n" " Extra Param: '%s'\r\n" " <END>\r\n\r\n", pIsapiContext, szExtraParam )); } pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_APPEND_LOG_PARAMETER[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // Validate parameters // if ( szExtraParam == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_APPEND_LOG_PARAMETER[%p]: Parameter validation failure\r\n" " Extra Param: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } hr = pIsapiCore->AppendLog( szExtraParam, 0 ); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_APPEND_LOG_PARAMETER[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } return hr; } HRESULT SSFExecuteUrl( ISAPI_CONTEXT * pIsapiContext, VOID * pOrigExecUrlInfo, BOOL fIsUnicode ) /*++ Routine Description: Execute a child request Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. pOrigExecUrlInfo - Description of child request to execute fIsUnicode - Are we passing unicode data? Return Value: HRESULT --*/ { EXEC_URL_USER_INFO UserName; EXEC_URL_ENTITY_INFO Entity; EXEC_URL_INFO UrlInfo; IIsapiCore * pIsapiCore; HRESULT hr; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { HSE_EXEC_URL_ENTITY_INFO *pEntityInfo = NULL; if ( fIsUnicode ) { HSE_EXEC_UNICODE_URL_INFO *pInfo = (HSE_EXEC_UNICODE_URL_INFO *)pOrigExecUrlInfo; HSE_EXEC_UNICODE_URL_USER_INFO *pUserInfo = NULL; if ( pInfo ) { pUserInfo = pInfo->pUserInfo; pEntityInfo = pInfo->pEntity; } DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_UNICODE_URL[%p]: Function Entry\r\n" " URL: '%S'\r\n" " Method: '%s'\r\n" " Child Headers: '%s'\r\n" " Flags: 0x%08x (%d)\r\n" " Impersonation Token: %p\r\n" " Custom User Name: '%S'\r\n" " Custom Auth Type: '%s'\r\n" " <END>\r\n\r\n", pIsapiContext, pInfo ? pInfo->pszUrl : NULL, pInfo ? pInfo->pszMethod : NULL, pInfo ? pInfo->pszChildHeaders : NULL, pInfo ? pInfo->dwExecUrlFlags : 0, pInfo ? pInfo->dwExecUrlFlags : 0, pUserInfo ? pUserInfo->hImpersonationToken : NULL, pUserInfo ? pUserInfo->pszCustomUserName : NULL, pUserInfo ? pUserInfo->pszCustomAuthType : NULL )); } else { HSE_EXEC_URL_INFO *pInfo = (HSE_EXEC_URL_INFO *)pOrigExecUrlInfo; HSE_EXEC_URL_USER_INFO *pUserInfo = NULL; if ( pInfo ) { pUserInfo = pInfo->pUserInfo; pEntityInfo = pInfo->pEntity; } DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_UNICODE_URL[%p]: Function Entry\r\n" " URL: '%s'\r\n" " Method: '%s'\r\n" " Child Headers: '%s'\r\n" " Flags: 0x%08x (%d)\r\n" " Impersonation Token: %p\r\n" " Custom User Name: '%s'\r\n" " Custom Auth Type: '%s'\r\n" " <END>\r\n\r\n", pIsapiContext, pInfo ? pInfo->pszUrl : NULL, pInfo ? pInfo->pszMethod : NULL, pInfo ? pInfo->pszChildHeaders : NULL, pInfo ? pInfo->dwExecUrlFlags : 0, pInfo ? pInfo->dwExecUrlFlags : 0, pUserInfo ? pUserInfo->hImpersonationToken : NULL, pUserInfo ? pUserInfo->pszCustomUserName : NULL, pUserInfo ? pUserInfo->pszCustomAuthType : NULL )); } IF_DEBUG( ISAPI_DUMP_BUFFERS ) { if ( pEntityInfo ) { STACK_STRA( strBufferDump,512 ); DWORD dwBytesToDump = pEntityInfo->cbAvailable; if ( dwBytesToDump > MAX_DEBUG_DUMP ) { dwBytesToDump = MAX_DEBUG_DUMP; } if ( FAILED( strBufferDump.CopyBinary( pEntityInfo->lpbData, dwBytesToDump ) ) ) { strBufferDump.Copy( "" ); } DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_URL[%p]: Dump of up to %d bytes of entity\r\n" "%s" " <END>\r\n\r\n", pIsapiContext, MAX_DEBUG_DUMP, strBufferDump.QueryStr() )); } } } pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_URL[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } if ( pOrigExecUrlInfo == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_URL[%p]: Parameter validation failure\r\n" " ExecUrl Info: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // This is an async call, make sure a completion routine is set // if ( pIsapiContext->QueryPfnIoCompletion() == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_URL[%p]: Failed\r\n" " No I/O completion has been set: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } if ( pIsapiContext->TryInitAsyncIo( AsyncExecPending ) == FALSE ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_URL[%p]: Failed\r\n" " An async operation is already pending: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // If any of the optional parameters are not NULL, then ensure they are // not empty. Also, copy parameters to the marshallable structure // // Note that any failures from here on down need to goto Done so // that we properly uninitialize async IO. // if (fIsUnicode) { HSE_EXEC_UNICODE_URL_INFO *pExecUnicodeUrlInfo = (HSE_EXEC_UNICODE_URL_INFO *)pOrigExecUrlInfo; if ( pExecUnicodeUrlInfo->pszUrl != NULL ) { if ( pExecUnicodeUrlInfo->pszUrl[ 0 ] == L'\0' ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_UNICODE_URL[%p]: Parameter validation failure\r\n" " URL is an empty string.\r\n" " <END>\r\n\r\n", pIsapiContext )); } hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); goto Done; } UrlInfo.fIsUrlUnicode = TRUE; UrlInfo.pszUrl = (BYTE *)pExecUnicodeUrlInfo->pszUrl; UrlInfo.cbUrl = (DWORD)(wcslen(pExecUnicodeUrlInfo->pszUrl) + 1)*sizeof(WCHAR); } else { UrlInfo.pszUrl = NULL; UrlInfo.cbUrl = 0; } if ( pExecUnicodeUrlInfo->pszMethod != NULL ) { if ( pExecUnicodeUrlInfo->pszMethod[ 0 ] == '\0' ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_UNICODE_URL[%p]: Parameter validation failure\r\n" " Method is an empty string\r\n" " <END>\r\n\r\n", pIsapiContext )); } hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); goto Done; } } UrlInfo.pszMethod = pExecUnicodeUrlInfo->pszMethod; if ( pExecUnicodeUrlInfo->pszChildHeaders != NULL ) { if ( pExecUnicodeUrlInfo->pszChildHeaders[ 0 ] == '\0' ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_UNICODE_URL[%p]: Parameter validation failure\r\n" " ChildHeaders is an empty string\r\n" " <END>\r\n\r\n", pIsapiContext )); } hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); goto Done; } } UrlInfo.pszChildHeaders = pExecUnicodeUrlInfo->pszChildHeaders; if ( pExecUnicodeUrlInfo->pUserInfo != NULL ) { if ( pExecUnicodeUrlInfo->pUserInfo->pszCustomUserName == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_UNICODE_URL[%p]: Parameter validation failure\r\n" " Custom User Name: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); goto Done; } if ( pExecUnicodeUrlInfo->pUserInfo->pszCustomAuthType == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_UNICODE_URL[%p]: Parameter validation failure\r\n" " Custom Auth Type: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); goto Done; } UserName.fIsUserNameUnicode = TRUE; UserName.pszUserName = (BYTE *)pExecUnicodeUrlInfo->pUserInfo->pszCustomUserName; UserName.cbUserName = (DWORD)(wcslen(pExecUnicodeUrlInfo->pUserInfo->pszCustomUserName) + 1)*sizeof(WCHAR); UserName.pszAuthType = pExecUnicodeUrlInfo->pUserInfo->pszCustomAuthType; UserName.hImpersonationToken = (DWORD_PTR)pExecUnicodeUrlInfo->pUserInfo->hImpersonationToken; UrlInfo.pUserInfo = &UserName; } else { UrlInfo.pUserInfo = NULL; } // // If we are being told that there is available entity, ensure // that the buffer is not NULL // if ( pExecUnicodeUrlInfo->pEntity != NULL ) { if ( pExecUnicodeUrlInfo->pEntity->cbAvailable != 0 && pExecUnicodeUrlInfo->pEntity->lpbData == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_UNICODE_URL[%p]: Parameter validation failure\r\n" " Available Entity bytes: %d\r\n" " Available Entity Ptr: %p\r\n" " <END>\r\n\r\n", pIsapiContext, pExecUnicodeUrlInfo->pEntity->cbAvailable, pExecUnicodeUrlInfo->pEntity->lpbData )); } hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); goto Done; } Entity.cbAvailable = pExecUnicodeUrlInfo->pEntity->cbAvailable; Entity.lpbData = (BYTE *)pExecUnicodeUrlInfo->pEntity->lpbData; } else { // // If no entity body was set for this child execute, then // we should duplicate the original entity body. This means // we will need to bring over the preloaded entity for the // ISAPI which calls this routine. // Entity.cbAvailable = pIsapiContext->QueryECB()->cbAvailable; Entity.lpbData = pIsapiContext->QueryECB()->lpbData; } UrlInfo.pEntity = &Entity; UrlInfo.dwExecUrlFlags = pExecUnicodeUrlInfo->dwExecUrlFlags; } else { HSE_EXEC_URL_INFO *pExecAnsiUrlInfo = (HSE_EXEC_URL_INFO *)pOrigExecUrlInfo; if ( pExecAnsiUrlInfo->pszUrl != NULL ) { if ( pExecAnsiUrlInfo->pszUrl[ 0 ] == '\0' ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_URL[%p]: Parameter validation failure\r\n" " URL is an empty string\r\n" " <END>\r\n\r\n", pIsapiContext )); } hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); goto Done; } UrlInfo.fIsUrlUnicode = FALSE; UrlInfo.pszUrl = (BYTE *)pExecAnsiUrlInfo->pszUrl; UrlInfo.cbUrl = (DWORD)strlen(pExecAnsiUrlInfo->pszUrl) + 1; } else { UrlInfo.pszUrl = NULL; UrlInfo.cbUrl = 0; } if ( pExecAnsiUrlInfo->pszMethod != NULL ) { if ( pExecAnsiUrlInfo->pszMethod[ 0 ] == '\0' ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_URL[%p]: Parameter validation failure\r\n" " Method is an empty string\r\n" " <END>\r\n\r\n", pIsapiContext )); } hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); goto Done; } } UrlInfo.pszMethod = pExecAnsiUrlInfo->pszMethod; if ( pExecAnsiUrlInfo->pszChildHeaders != NULL ) { if ( pExecAnsiUrlInfo->pszChildHeaders[ 0 ] == '\0' ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_URL[%p]: Parameter validation failure\r\n" " ChildHeaders is an empty string\r\n" " <END>\r\n\r\n", pIsapiContext )); } hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); goto Done; } } UrlInfo.pszChildHeaders = pExecAnsiUrlInfo->pszChildHeaders; if ( pExecAnsiUrlInfo->pUserInfo != NULL ) { if ( pExecAnsiUrlInfo->pUserInfo->pszCustomUserName == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_URL[%p]: Parameter validation failure\r\n" " Custom User Name: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); goto Done; } if ( pExecAnsiUrlInfo->pUserInfo->pszCustomAuthType == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_URL[%p]: Parameter validation failure\r\n" " Custom Auth Type: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); goto Done; } UserName.fIsUserNameUnicode = FALSE; UserName.pszUserName = (BYTE *)pExecAnsiUrlInfo->pUserInfo->pszCustomUserName; UserName.cbUserName = (DWORD)strlen(pExecAnsiUrlInfo->pUserInfo->pszCustomUserName) + 1; UserName.pszAuthType = pExecAnsiUrlInfo->pUserInfo->pszCustomAuthType; UserName.hImpersonationToken = (DWORD_PTR)pExecAnsiUrlInfo->pUserInfo->hImpersonationToken; UrlInfo.pUserInfo = &UserName; } else { UrlInfo.pUserInfo = NULL; } // // If we are being told that there is available entity, ensure // that the buffer is not NULL // if ( pExecAnsiUrlInfo->pEntity != NULL ) { if ( pExecAnsiUrlInfo->pEntity->cbAvailable != 0 && pExecAnsiUrlInfo->pEntity->lpbData == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_URL[%p]: Parameter validation failure\r\n" " Available Entity Bytes: %d\r\n" " Available Entity Ptr: %p\r\n" " <END>\r\n\r\n", pIsapiContext, pExecAnsiUrlInfo->pEntity->cbAvailable, pExecAnsiUrlInfo->pEntity->lpbData )); } hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); goto Done; } Entity.cbAvailable = pExecAnsiUrlInfo->pEntity->cbAvailable; Entity.lpbData = (BYTE *)pExecAnsiUrlInfo->pEntity->lpbData; } else { // // If no entity body was set for this child execute, then // we should duplicate the original entity body. This means // we will need to bring over the preloaded entity for the // ISAPI which calls this routine. // Entity.cbAvailable = pIsapiContext->QueryECB()->cbAvailable; Entity.lpbData = pIsapiContext->QueryECB()->lpbData; } UrlInfo.pEntity = &Entity; UrlInfo.dwExecUrlFlags = pExecAnsiUrlInfo->dwExecUrlFlags; } // // All the heavy lifting is in W3CORE.DLL // hr = pIsapiCore->ExecuteUrl( reinterpret_cast<DWORD64>( pIsapiContext ), &UrlInfo ); Done: if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_URL[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } pIsapiContext->UninitAsyncIo(); } return hr; } HRESULT SSFGetExecuteUrlStatus( ISAPI_CONTEXT * pIsapiContext, HSE_EXEC_URL_STATUS* pExecUrlStatus ) /*++ Routine Description: Get status of last child execute Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. pExecUrlStatus - Filled with status Return Value: HRESULT --*/ { IIsapiCore * pIsapiCore; HRESULT hr; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_EXEC_URL_STATUS[%p]: Function Entry\r\n" " <END>\r\n\r\n", pIsapiContext )); } pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_EXEC_URL_STATUS[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } if ( pExecUrlStatus == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_EXEC_URL_STATUS[%p]: Parameter validation failure\r\n" " EXEC_URL Status Ptr: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } hr = pIsapiCore->GetExecuteUrlStatus( &(pExecUrlStatus->uHttpStatusCode), &(pExecUrlStatus->uHttpSubStatus), &(pExecUrlStatus->dwWin32Error) ); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_EXEC_URL_STATUS[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } return hr; } HRESULT SSFSendCustomError( ISAPI_CONTEXT * pIsapiContext, HSE_CUSTOM_ERROR_INFO * pCustomErrorInfo ) /*++ Routine Description: Send custom error to client Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. pCustomErrorInfo - Describes the custom error to send Return Value: HRESULT --*/ { IIsapiCore * pIsapiCore; HRESULT hr = NOERROR; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_SEND_CUSTOM_ERROR[%p]: Function Entry\r\n" " Status: '%s'\r\n" " SubError Code: %d\r\n" " <END>\r\n\r\n", pIsapiContext, pCustomErrorInfo ? pCustomErrorInfo->pszStatus : NULL, pCustomErrorInfo ? pCustomErrorInfo->uHttpSubError : 0 )); } pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_SEND_CUSTOM_ERROR[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } if ( pCustomErrorInfo == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_SEND_CUSTOM_ERROR[%p]: Parameter validation failure\r\n" " Custom Error Info Ptr: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // Ensure status is not empty // if ( pCustomErrorInfo->pszStatus != NULL ) { if ( pCustomErrorInfo->pszStatus[ 0 ] == '\0' ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_SEND_CUSTOM_ERROR[%p]: Parameter validation failure\r\n" " Status is an empty string\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } } // // If this is an async call, then make sure a completion routine is set // if ( pCustomErrorInfo->fAsync ) { if ( pIsapiContext->TryInitAsyncIo( AsyncExecPending ) == FALSE ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_SEND_CUSTOM_ERROR[%p]: Failed\r\n" " Another async operation is already pending\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } } hr = pIsapiCore->SendCustomError( pCustomErrorInfo->fAsync ? reinterpret_cast<DWORD64>( pIsapiContext ) : NULL, pCustomErrorInfo->pszStatus, pCustomErrorInfo->uHttpSubError ); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_SEND_CUSTOM_ERROR[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } if ( pCustomErrorInfo->fAsync ) { pIsapiContext->UninitAsyncIo(); } return hr; } return hr; } HRESULT SSFVectorSendDeprecated( ISAPI_CONTEXT * pIsapiContext, HSE_RESPONSE_VECTOR_DEPRECATED * pResponseVector ) /*++ Routine Description: The old deprecated vector-send Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. pResponseVector - The vector to be sent Return Value: HRESULT --*/ { HSE_RESPONSE_VECTOR RealResponseVector; STACK_BUFFER( buffResp, 512); HRESULT hr; IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_VECTOR_SEND_DEPRECATED[%p]: Function Entry\r\n" " <END>\r\n\r\n", pIsapiContext )); } if ( pResponseVector == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_VECTOR_SEND_DEPRECATED[%p]: Parameter validation failure\r\n" " Response Vector Ptr: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } RealResponseVector.dwFlags = pResponseVector->dwFlags; RealResponseVector.pszStatus = pResponseVector->pszStatus; RealResponseVector.pszHeaders = pResponseVector->pszHeaders; RealResponseVector.nElementCount = pResponseVector->nElementCount; if (!buffResp.Resize(pResponseVector->nElementCount * sizeof(HSE_VECTOR_ELEMENT))) { return HRESULT_FROM_WIN32( ERROR_NOT_ENOUGH_MEMORY ); } RealResponseVector.lpElementArray = (HSE_VECTOR_ELEMENT *)buffResp.QueryPtr(); for (DWORD i=0; i<pResponseVector->nElementCount; i++) { if (pResponseVector->lpElementArray[i].pBuffer != NULL) { RealResponseVector.lpElementArray[i].ElementType = HSE_VECTOR_ELEMENT_TYPE_MEMORY_BUFFER; RealResponseVector.lpElementArray[i].pvContext = pResponseVector->lpElementArray[i].pBuffer; RealResponseVector.lpElementArray[i].cbSize = pResponseVector->lpElementArray[i].cbSize; } else { RealResponseVector.lpElementArray[i].ElementType = HSE_VECTOR_ELEMENT_TYPE_FILE_HANDLE; RealResponseVector.lpElementArray[i].pvContext = pResponseVector->lpElementArray[i].hFile; RealResponseVector.lpElementArray[i].cbOffset = pResponseVector->lpElementArray[i].cbOffset; RealResponseVector.lpElementArray[i].cbSize = pResponseVector->lpElementArray[i].cbSize; } } hr = SSFVectorSend(pIsapiContext, &RealResponseVector); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_VECTOR_SEND_DEPRECATED[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } return hr; } HRESULT SSFVectorSend( ISAPI_CONTEXT * pIsapiContext, HSE_RESPONSE_VECTOR * pResponseVector ) /*++ Routine Description: Send an array of memory/file-handle/fragment-cache chunks Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. pResponseVector - The vector to be sent Return Value: HRESULT --*/ { IIsapiCore * pIsapiCore; ULONGLONG cbTotalSend = 0; STACK_BUFFER( buffResp, 512); HRESULT hr = NOERROR; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_VECTOR_SEND[%p]: Function Entry (%s)\r\n" " Status: '%s'\r\n" " Headers: '%s'\r\n" " Element Count: %d\r\n" " Flags: 0x%08x (%d)\r\n" " <END>\r\n\r\n", pIsapiContext, pResponseVector ? pResponseVector->dwFlags & HSE_IO_ASYNC ? "Asynchronous" : "Synchronous" : "", pResponseVector ? pResponseVector->pszStatus : NULL, pResponseVector ? pResponseVector->pszHeaders : NULL, pResponseVector ? pResponseVector->nElementCount : 0, pResponseVector ? pResponseVector->dwFlags : 0, pResponseVector ? pResponseVector->dwFlags : 0 )); IF_DEBUG( ISAPI_DUMP_BUFFERS ) { if ( pResponseVector && pResponseVector->nElementCount ) { STACK_STRA( strBufferDump,512 ); DWORD dwBytesToDump; DWORD i; for ( i = 0; i < pResponseVector->nElementCount; i++ ) { if ( pResponseVector->lpElementArray[i].ElementType == HSE_VECTOR_ELEMENT_TYPE_MEMORY_BUFFER ) { dwBytesToDump = pResponseVector->lpElementArray[i].cbSize; if ( dwBytesToDump > MAX_DEBUG_DUMP ) { dwBytesToDump = MAX_DEBUG_DUMP; } if ( FAILED( strBufferDump.CopyBinary( pResponseVector->lpElementArray[i].pvContext, dwBytesToDump ) ) ) { strBufferDump.Copy( "" ); } DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_VECTOR_SEND[%p]: Dump of up to %d bytes of element %d\r\n" "%s" " <END>\r\n\r\n", pIsapiContext, MAX_DEBUG_DUMP, i, strBufferDump.QueryStr() )); } else if ( pResponseVector->lpElementArray[i].ElementType == HSE_VECTOR_ELEMENT_TYPE_FILE_HANDLE ) { DBGPRINTF(( DBG_CONTEXT, "\r\n", " HSE_REQ_VECTOR_SEND[%p]: Element %d\r\n" " File Handle: %p\r\n" " Offset: %d\r\n" " Bytes To Send: %d\r\n" " <END>\r\n\r\n", pIsapiContext, pResponseVector->lpElementArray[i].pvContext, pResponseVector->lpElementArray[i].cbOffset, pResponseVector->lpElementArray[i].cbSize )); } } } } } pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_VECTOR_SEND[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // verify the data passed in // if ( pResponseVector == NULL || ( ( pResponseVector->dwFlags & HSE_IO_ASYNC ) != 0 && pIsapiContext->TryInitAsyncIo( AsyncVectorPending ) == FALSE ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_VECTOR_SEND[%p]: Failed\r\n" " Another async operation is already pending\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } if ((pResponseVector->dwFlags & HSE_IO_SYNC) && (pResponseVector->dwFlags & HSE_IO_ASYNC)) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_VECTOR_SEND[%p]: Parameter validation failure\r\n" " Both HSE_IO_SYNC and HSE_IO_ASYNC were specified\r\n" " <END>\r\n\r\n", pIsapiContext )); } hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); goto Failed; } if (pResponseVector->dwFlags & HSE_IO_SEND_HEADERS) { if ((pResponseVector->pszStatus == NULL) || (pResponseVector->pszHeaders == NULL)) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_VECTOR_SEND[%p]: Parameter validation failure\r\n" " HSE_IO_SEND_HEADERS was specified, but some required info is missing\r\n" " Status: '%s'\r\n" " Headers: '%s'\r\n" " <END>\r\n\r\n", pIsapiContext, pResponseVector->pszStatus, pResponseVector->pszHeaders )); } hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); goto Failed; } } else { if ((pResponseVector->pszStatus != NULL) || (pResponseVector->pszHeaders != NULL)) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_VECTOR_SEND[%p]: Parameter validation failure\r\n" " HSE_IO_SEND_HEADERS was not specified, yet status or header info was provided\r\n" " Status: '%s'\r\n" " Headers: '%s'\r\n" " <END>\r\n\r\n", pIsapiContext, pResponseVector->pszStatus, pResponseVector->pszHeaders )); } hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); goto Failed; } } if (!buffResp.Resize(pResponseVector->nElementCount * sizeof(VECTOR_ELEMENT))) { hr = HRESULT_FROM_WIN32( ERROR_NOT_ENOUGH_MEMORY ); goto Failed; } ZeroMemory(buffResp.QueryPtr(), pResponseVector->nElementCount * sizeof(VECTOR_ELEMENT)); VECTOR_ELEMENT *pVectorElement = (VECTOR_ELEMENT *)buffResp.QueryPtr(); HSE_VECTOR_ELEMENT *pHseVectorElement; for (DWORD i=0; i<pResponseVector->nElementCount; i++) { pHseVectorElement = &pResponseVector->lpElementArray[i]; if (pHseVectorElement->pvContext == NULL) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_VECTOR_SEND[%p]: Parameter validation failure\r\n" " Context: NULL on element %d in the array\r\n" " <END>\r\n\r\n", pIsapiContext, i )); } hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); goto Failed; } switch (pHseVectorElement->ElementType) { case HSE_VECTOR_ELEMENT_TYPE_MEMORY_BUFFER: if (pHseVectorElement->cbSize > MAXULONG) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_VECTOR_SEND[%p]: Parameter validation failure\r\n" " Invalid memory buffer size on element %d in the array\r\n" " Size: %d\r\n" " <END>\r\n\r\n", pIsapiContext, i, pHseVectorElement->cbSize )); } hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); goto Failed; } pVectorElement[i].pBuffer = (BYTE *)pHseVectorElement->pvContext; cbTotalSend += ( pVectorElement[i].cbBufSize = (DWORD)pHseVectorElement->cbSize ); break; case HSE_VECTOR_ELEMENT_TYPE_FILE_HANDLE: if (pHseVectorElement->pvContext == INVALID_HANDLE_VALUE) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_VECTOR_SEND[%p]: Parameter validation failure\r\n" " Handle on file handle element %d in the array is invalid\r\n" " File Handle: %p\r\n" " <END>\r\n\r\n", pIsapiContext, i, pHseVectorElement->pvContext )); } hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); goto Failed; } // // Treat 0 as "send the rest of the file" - same as TransmitFile // if (pHseVectorElement->cbSize == 0) { pHseVectorElement->cbSize = HTTP_BYTE_RANGE_TO_EOF; } pVectorElement[i].hFile = (DWORD_PTR)pHseVectorElement->pvContext; pVectorElement[i].cbOffset = pHseVectorElement->cbOffset; cbTotalSend += ( pVectorElement[i].cbFileSize = pHseVectorElement->cbSize ); break; case HSE_VECTOR_ELEMENT_TYPE_FRAGMENT: pVectorElement[i].pszFragmentName = (WCHAR *)pHseVectorElement->pvContext; break; default: IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_VECTOR_SEND[%p]: Parameter validation failure\r\n" " Unknown type on element %d in the array\r\n" " Element Type: %d\r\n" " <END>\r\n\r\n", pIsapiContext, i, pHseVectorElement->ElementType )); } hr = HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER); goto Failed; } } // // Set up the total number of bytes we are trying to send so that ISAPIs // are not confused // pIsapiContext->SetLastAsyncIo( (cbTotalSend > MAXULONG) ? MAXULONG : (DWORD)cbTotalSend ); // // In general, VECTOR_SEND shouldn't touch the connection flags // in the ISAPI_CONTEXT, since ISAPI tries to do the right thing // automatically. // // There are couple of scenarios, though, where we might have a // bit of connection management housekeeping to do. // // If the caller specified the HSE_IO_DISCONNECT_AFTER_SEND flag, // then we need to force the connection closed. // // Otherwise, there are two scenarios where we may need to force // the connection to stay open. // // First, if all of the below are true, we should set the // connection to be open: // // - The client requested keep-alive // - This call is sending headers (HSE_IO_SEND_HEADERS is set) // - The disconnect flag has not been set // // Second, if all of the below are true, we should set the // connection to be open. // // - The client requested keep-alive // - The ISAPI has not already sent headers // - The disconnect flag has not been set // - This is the final send // // One final note: This logic does not account for the case where // this call is sending headers, and the call fails for some reason. // In the asynchronous case, this would be somewhat complicated to // handle, since the completion routine would need to know both if // the caller was sending headers, and also that the I/O failed. // Presumably, if such a failure occurs, the most likely reason is // that the client already disconnected, or it would otherwise be // unlikely for the caller to do something to try and recover and // redo this send in a way that would succeed, which makes all of this // moot. // if ( pResponseVector->dwFlags & HSE_IO_DISCONNECT_AFTER_SEND ) { pIsapiContext->SetKeepConn( FALSE ); } else { if ( pIsapiContext->QueryClientKeepConn() ) { if ( (pResponseVector->dwFlags & HSE_IO_SEND_HEADERS) || ( pIsapiContext->QueryHeadersSent() == FALSE && (pResponseVector->dwFlags & HSE_IO_FINAL_SEND) ) ) { pIsapiContext->SetKeepConn( TRUE ); } } } hr = pIsapiCore->VectorSend( pResponseVector->dwFlags & HSE_IO_ASYNC ? reinterpret_cast<DWORD64>( pIsapiContext ) : NULL, !pIsapiContext->QueryKeepConn(), pResponseVector->pszStatus, pResponseVector->pszHeaders, pVectorElement, pResponseVector->nElementCount, !!(pResponseVector->dwFlags & HSE_IO_FINAL_SEND), !!(pResponseVector->dwFlags & HSE_IO_CACHE_RESPONSE) ); if ( FAILED( hr ) ) { goto Failed; } return hr; Failed: DBG_ASSERT( FAILED( hr ) ); IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_VECTOR_SEND[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } if ( pResponseVector->dwFlags & HSE_IO_ASYNC ) { pIsapiContext->SetLastAsyncIo( 0 ); pIsapiContext->UninitAsyncIo(); } return hr; } HRESULT SSFGetCustomErrorPage( ISAPI_CONTEXT * pIsapiContext, HSE_CUSTOM_ERROR_PAGE_INFO * pInfo ) { IIsapiCore * pIsapiCore; HRESULT hr; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_CUSTOM_ERROR_PAGE[%p]: Function Entry\r\n" " Error: %d\r\n" " SubError: %d\r\n" " <END>\r\n\r\n", pIsapiContext, pInfo ? pInfo->dwError : 0, pInfo ? pInfo->dwSubError : 0 )); } pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_CUSTOM_ERROR_PAGE[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // Validate arguments // if ( pInfo == NULL || ( pInfo->dwBufferSize != 0 && pInfo->pBuffer == NULL ) || pInfo->pdwBufferRequired == NULL || pInfo->pfIsFileError == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_CUSTOM_ERROR_PAGE[%p]: Parameter validation failure\r\n" " Info Ptr: %p\r\n" " Buffer Size: %d\r\n" " Buffer Ptr: %p\r\n" " Buffer Required Ptr: %p\r\n" " IsFileError Ptr: %p\r\n" " <END>\r\n\r\n", pIsapiContext, pInfo, pInfo ? pInfo->dwBufferSize : 0, pInfo ? pInfo->pBuffer : NULL, pInfo ? pInfo->pdwBufferRequired : NULL, pInfo ? pInfo->pfIsFileError : NULL )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } hr = pIsapiCore->GetCustomError( pInfo->dwError, pInfo->dwSubError, pInfo->dwBufferSize, reinterpret_cast<BYTE*>( pInfo->pBuffer ), pInfo->pdwBufferRequired, pInfo->pfIsFileError, pInfo->pfSendErrorBody ); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_CUSTOM_ERROR_PAGE[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } return hr; } HRESULT SSFIsInProcess( ISAPI_CONTEXT * pIsapiContext, DWORD * pdwAppFlag ) { LPWSTR szClsid; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_IS_IN_PROCESS[%p]: Function Entry\r\n" " <END>\r\n\r\n", pIsapiContext )); } if ( pdwAppFlag == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_IS_IN_PROCESS[%p]: Parameter validation failure\r\n" " AppFlag Ptr: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } szClsid = pIsapiContext->QueryClsid(); DBG_ASSERT( szClsid != NULL ); if ( wcslen( szClsid ) == 0 ) { *pdwAppFlag = HSE_APP_FLAG_IN_PROCESS; } else if ( _wcsicmp( szClsid, W3_OOP_POOL_WAM_CLSID ) == NULL ) { *pdwAppFlag = HSE_APP_FLAG_POOLED_OOP; } else { *pdwAppFlag = HSE_APP_FLAG_ISOLATED_OOP; } return NO_ERROR; } HRESULT SSFGetSspiInfo( ISAPI_CONTEXT * pIsapiContext, CtxtHandle * pCtxtHandle, CredHandle * pCredHandle ) { IIsapiCore * pIsapiCore; HRESULT hr; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); DBG_REQUIRE( ( pIsapiCore = pIsapiContext->QueryIsapiCoreInterface() ) != NULL ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_SSPI_INFO[%p]: Function Entry\r\n" " <END>\r\n\r\n", pIsapiContext )); } // // The CtxtHandle and CredHandle are only valid in their // local process. There is no way to duplicate them into // a dllhost. As a result, this function is inproc only. // if ( pIsapiContext->QueryIsOop() ) { return HRESULT_FROM_WIN32( ERROR_INVALID_FUNCTION ); } // // Validate parameters // if ( pCtxtHandle == NULL || pCredHandle == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_SSPI_INFO[%p]: Parameter validation Failure\r\n" " Context Handle Ptr: %p\r\n" " Credential Handle Ptr: %p\r\n" " <END>\r\n\r\n", pIsapiContext, pCtxtHandle, pCredHandle )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } hr = pIsapiCore->GetSspiInfo( reinterpret_cast<BYTE*>( pCredHandle ), sizeof( CredHandle ), reinterpret_cast<BYTE*>( pCtxtHandle ), sizeof( CtxtHandle ) ); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_SSPI_INFO[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } return hr; } HRESULT SSFGetVirtualPathToken( ISAPI_CONTEXT * pIsapiContext, LPSTR szUrl, HANDLE * pToken, BOOL fUnicode ) { IIsapiCore * pIsapiCore; HRESULT hr = S_OK; DWORD64 dwToken; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); DBG_REQUIRE( ( pIsapiCore = pIsapiContext->QueryIsapiCoreInterface() ) != NULL ); IF_DEBUG( ISAPI_SSF_DETAILS ) { if ( fUnicode ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_UNICODE_VIRTUAL_PATH_TOKEN[%p]: Function Entry\r\n" " URL: '%S'\r\n" " <END>\r\n\r\n", pIsapiContext, szUrl )); } else { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_VIRTUAL_PATH_TOKEN[%p]: Function Entry\r\n" " URL: '%s'\r\n" " <END>\r\n\r\n", pIsapiContext, szUrl )); } } // // Validate parameters // if ( szUrl == NULL || pToken == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { if ( fUnicode ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_UNICODE_VIRTUAL_PATH_TOKEN[%p]: Parameter validation failure\r\n" " URL: '%S'\r\n" " Token Ptr: %p\r\n" " <END>\r\n\r\n", pIsapiContext, szUrl, pToken )); } else { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_VIRTUAL_PATH_TOKEN[%p]: Parameter validation failure\r\n" " URL: '%s'\r\n" " Token Ptr: %p\r\n" " <END>\r\n\r\n", pIsapiContext, szUrl, pToken )); } } } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } hr = pIsapiCore->QueryToken( reinterpret_cast<BYTE*>( szUrl ), (DWORD)( fUnicode ? (wcslen( (LPWSTR)szUrl ) + 1 ) * sizeof(WCHAR) : strlen( szUrl ) + 1 ), TOKEN_VR_TOKEN, &dwToken, fUnicode ); if (FAILED(hr)) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_%sVIRTUAL_PATH_TOKEN[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", fUnicode ? "UNICODE_" : "", pIsapiContext, hr )); } return hr; } *pToken = (HANDLE)dwToken; return hr; } HRESULT SSFGetAnonymousToken( ISAPI_CONTEXT * pIsapiContext, LPSTR szUrl, HANDLE * pToken, BOOL fUnicode ) { IIsapiCore * pIsapiCore; DWORD64 dwToken; HRESULT hr; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); DBG_REQUIRE( ( pIsapiCore = pIsapiContext->QueryIsapiCoreInterface() ) != NULL ); IF_DEBUG( ISAPI_SSF_DETAILS ) { if ( fUnicode ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_UNICODE_ANONYMOUS_TOKEN[%p]: Function Entry\r\n" " URL: '%S'\r\n" " <END>\r\n\r\n", pIsapiContext, szUrl )); } else { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_ANONYMOUS_TOKEN[%p]: Function Entry\r\n" " URL: '%s\r\n" " <END>\r\n\r\n", pIsapiContext, szUrl )); } } // // Validate parameters // if ( szUrl == NULL || pToken == NULL ) { if ( fUnicode ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_UNICODE_ANONYMOUS_TOKEN[%p]: Parameter validation failure\r\n" " URL: '%S'\r\n" " Token Ptr: %p\r\n" " <END>\r\n\r\n", pIsapiContext, szUrl, pToken )); } } else { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_ANONYMOUS_TOKEN[%p]: Parameter validation failure\r\n" " URL: '%s'\r\n" " Token Ptr: %p\r\n" " <END>\r\n\r\n", pIsapiContext, szUrl, pToken )); } } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } hr = pIsapiCore->QueryToken( reinterpret_cast<BYTE*>( szUrl ), (DWORD)( fUnicode ? (wcslen( (LPWSTR)szUrl ) + 1 ) * sizeof(WCHAR) : strlen( szUrl ) + 1 ), TOKEN_ANONYMOUS_TOKEN, &dwToken, fUnicode ); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_%sANONYMOUS_TOKEN[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", fUnicode ? "UNICODE_" : "", pIsapiContext, hr )); } return hr; } *pToken = (HANDLE)dwToken; return hr; } HRESULT SSFReportUnhealthy( ISAPI_CONTEXT * pIsapiContext, LPSTR szReason ) { IIsapiCore * pIsapiCore; LPWSTR szImage; STACK_STRU( strReason, 512 ); DWORD cbImage; DWORD cbReason; HRESULT hr; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); DBG_REQUIRE( ( pIsapiCore = pIsapiContext->QueryIsapiCoreInterface() ) != NULL ); DBG_REQUIRE( ( szImage = pIsapiContext->QueryGatewayImage() ) != NULL ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_REPORT_UNHEALTHY[%p]: Function Entry\r\n" " Reason: '%s'\r\n" " <END>\r\n\r\n", pIsapiContext, szReason )); } cbImage = (DWORD)( wcslen( szImage ) + 1 ) * sizeof( WCHAR ); // // If the ISAPI has given a reason, we need to send it // as UNICODE. // if ( szReason == NULL ) { cbReason = 0; } else { hr = strReason.CopyA( szReason ); if ( FAILED( hr ) ) { return hr; } cbReason = ( strReason.QueryCCH() + 1 ) * sizeof( WCHAR ); } hr = pIsapiCore->ReportAsUnhealthy( reinterpret_cast<BYTE*>( szImage ), cbImage, cbReason ? reinterpret_cast<BYTE*>( strReason.QueryStr() ) : NULL, cbReason ); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_REPORT_UNHEALTHY[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } return hr; } HRESULT SSFNormalizeUrl( LPSTR pszURL ) /*++ Routine Description: Normalize URL Arguments: pszURL - On entry, contains not normalized URL. On return, contains normalized URL. Return Value: HRESULT --*/ { HRESULT hr; IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_NORMALIZE_URL[]: Function Entry\r\n" " URL: '%s'\r\n" " <END>\r\n\r\n", pszURL )); } // // Validate parameters // if ( pszURL == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_NORMALIZE_URL[]: Parameter validation failure\r\n" " URL: NULL\r\n" " <END>\r\n\r\n" )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } hr = NormalizeUrl( pszURL ); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_NORMALIZE_URL[]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", hr )); } return hr; } return hr; } HRESULT SSFAddFragmentToCache( ISAPI_CONTEXT * pIsapiContext, HSE_VECTOR_ELEMENT * pHseVectorElement, WCHAR * pszFragmentName ) /*++ Routine Description: Add the given fragment to the fragment-cache Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. pVectorElement - The fragment to be added pszFragmentName - The name of the fragment Return Value: HRESULT --*/ { IIsapiCore *pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); HRESULT hr; IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_ADD_FRAGMENT_TO_CACHE[%p]: Function Entry\r\n" " Fragment Name: '%S'\r\n" " <END>\r\n\r\n", pIsapiContext, pszFragmentName )); } if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_ADD_FRAGMENT_TO_CACHE[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // verify the data passed in // if ( pHseVectorElement == NULL || pszFragmentName == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_ADD_FRAGMENT_TO_CACHE[%p]: Parameter validation failure\r\n" " Vector Element Ptr: %p\r\n" " Fragment Name: '%s'\r\n" " <END>\r\n\r\n", pIsapiContext, pHseVectorElement, pszFragmentName )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } VECTOR_ELEMENT VectorElement; ZeroMemory(&VectorElement, sizeof VectorElement); if (pHseVectorElement->pvContext == NULL) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_ADD_FRAGMENT_TO_CACHE[%p]: Parameter validation failure\r\n" " Vector Element Context: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } switch (pHseVectorElement->ElementType) { case HSE_VECTOR_ELEMENT_TYPE_MEMORY_BUFFER: if (pHseVectorElement->cbSize > MAXULONG) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_ADD_FRAGMENT_TO_CACHE[%p]: Parameter validation failure\r\n" " Memory buffer size element invalid\r\n" " Size: %d\r\n" " <END>\r\n\r\n", pIsapiContext, pHseVectorElement->cbSize )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } VectorElement.pBuffer = (BYTE *)pHseVectorElement->pvContext; VectorElement.cbBufSize = (DWORD)pHseVectorElement->cbSize; break; case HSE_VECTOR_ELEMENT_TYPE_FILE_HANDLE: if (pHseVectorElement->pvContext == INVALID_HANDLE_VALUE) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_ADD_FRAGMENT_TO_CACHE[%p]: Parameter validation failure\r\n" " Element file handle invalid\r\n" " File Handle: %p\r\n" " <END>\r\n\r\n", pIsapiContext, pHseVectorElement->pvContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // Treat 0 as "send the rest of the file" - same as TransmitFile/VectorSend // if (pHseVectorElement->cbSize == 0) { pHseVectorElement->cbSize = HTTP_BYTE_RANGE_TO_EOF; } VectorElement.hFile = (DWORD_PTR)pHseVectorElement->pvContext; VectorElement.cbOffset = pHseVectorElement->cbOffset; VectorElement.cbFileSize = pHseVectorElement->cbSize; break; case HSE_VECTOR_ELEMENT_TYPE_FRAGMENT: default: IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_ADD_FRAGMENT_TO_CACHE[%p]: Parameter validation failure\r\n" " Unknown element type: %d\r\n" " Fragment Name: '%s'\r\n" " <END>\r\n\r\n", pIsapiContext, pHseVectorElement->ElementType )); } return HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER); } hr = pIsapiCore->AddFragmentToCache(&VectorElement, pszFragmentName); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_ADD_FRAGMENT_TO_CACHE[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } return hr; } HRESULT SSFReadFragmentFromCache( ISAPI_CONTEXT * pIsapiContext, WCHAR * pszFragmentName, BYTE * pvBuffer, DWORD * pcbSize ) /*++ Routine Description: Read the given fragment from the fragment-cache Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. pszFragmentName - The name of the fragment pvBuffer - The buffer to read the fragment in pcbSize - On entry, the size of the buffer and on exit, the number of bytes copied Return Value: HRESULT --*/ { IIsapiCore *pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); HRESULT hr; IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_READ_FRAGMENT_FROM_CACHE[%p]: Function Entry\r\n" " Fragment Name: '%S'\r\n" " <END>\r\n\r\n", pIsapiContext, pszFragmentName )); } if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_READ_FRAGMENT_FROM_CACHE[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // verify the data passed in // if ( pszFragmentName == NULL || pcbSize == NULL || (pvBuffer == NULL && *pcbSize != 0 ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_READ_FRAGMENT_FROM_CACHE[%p]: Parameter validation failure\r\n" " Fragment Name: '%s'\r\n" " Size Ptr: %p\r\n" " Size: %d\r\n" " Buffer Ptr: %p\r\n" " <END>\r\n\r\n", pIsapiContext, pszFragmentName, pcbSize, pcbSize ? *pcbSize : 0, pvBuffer )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } hr = pIsapiCore->ReadFragmentFromCache(pszFragmentName, pvBuffer, *pcbSize, pcbSize); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_READ_FRAGMENT_FROM_CACHE[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } return hr; } HRESULT SSFRemoveFragmentFromCache( ISAPI_CONTEXT * pIsapiContext, WCHAR * pszFragmentName ) /*++ Routine Description: Remove the given fragment from the fragment-cache Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. pszFragmentName - The name of the fragment Return Value: HRESULT --*/ { IIsapiCore *pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); HRESULT hr; IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_REMOVE_FRAGMENT_FROM_CACHE[%p]: Function Entry\r\n" " Fragment Name: '%S'\r\n" " <END>\r\n\r\n", pIsapiContext, pszFragmentName )); } if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_REMOVE_FRAGMENT_FROM_CACHE[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // verify the data passed in // if ( pszFragmentName == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_REMOVE_FRAGMENT_FROM_CACHE[%p]: Parameter validation failure\r\n" " Fragment Name: '%s'\r\n" " <END>\r\n\r\n", pIsapiContext, pszFragmentName )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } hr = pIsapiCore->RemoveFragmentFromCache(pszFragmentName); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_REMOVE_FRAGMENT_FROM_CACHE[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } return hr; } HRESULT SSFGetMetadataProperty( ISAPI_CONTEXT * pIsapiContext, DWORD_PTR dwPropertyId, BYTE * pbBuffer, DWORD * pcbBuffer ) /*++ Routine Description: Retrieve a property from the UT_FILE metadata associated with the URL of this request Arguments: pIsapiContext - ISAPI_CONTEXT dwPropertyId - MD_* metabase property ID pbBuffer - Points to buffer pcbBuffer - On input size of buffer, on output size needed/used Return Value: HRESULT --*/ { IIsapiCore * pIsapiCore; HRESULT hr; METADATA_RECORD * pRecord; DBG_ASSERT( pIsapiContext != NULL ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_METADATA_PROPERTY[%p]: Function Entry\r\n" " PropertyID: 0x%08x (%d)\r\n" " <END>\r\n\r\n", pIsapiContext, dwPropertyId, dwPropertyId )); } pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); DBG_ASSERT( pIsapiCore != NULL ); if ( pcbBuffer == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_METADATA_PROPERTY[%p]: Parameter validation failure\r\n" " Buffer Ptr: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } hr = pIsapiCore->GetMetadataProperty( (DWORD) dwPropertyId, pbBuffer, *pcbBuffer, pcbBuffer ); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_METADATA_PROPERTY[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } else { // // OK. Before we return the METADATA_RECORD back to caller, set the // pbMDData buffer pointer (since for OOP the pointer can only be // calculated on this side // DBG_ASSERT( *pcbBuffer >= sizeof( METADATA_RECORD ) ); pRecord = (METADATA_RECORD*) pbBuffer; pRecord->pbMDData = (BYTE*) (pRecord + 1); } return hr; } HRESULT SSFGetCacheInvalidationCallback( ISAPI_CONTEXT * pIsapiContext, PFN_HSE_CACHE_INVALIDATION_CALLBACK * pfnCallback ) /*++ Routine description: Get the callback function to use to flush a response from the http.sys cache Arguments: pIsapiContext - The ISAPI_CONTEXT corresponding to the request pfnCallback - On successful return, the address of the callback function Return: HRESULT --*/ { IIsapiCore * pIsapiCore; HRESULT hr; DBG_ASSERT( pIsapiContext != NULL ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_CACHE_INVALIDATION_CALLBACK[%p]: Function Entry\r\n" " <END>\r\n\r\n", pIsapiContext )); } pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); DBG_ASSERT( pIsapiCore != NULL ); if ( pfnCallback == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_CACHE_INVALIDATION_CALLBACK[%p]: Parameter validation failure\r\n" " Callback Ptr: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } hr = pIsapiCore->GetCacheInvalidationCallback((DWORD64 *)pfnCallback); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_CACHE_INVALIDATION_CALLBACK[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } return hr; } HRESULT SSFCloseConnection( ISAPI_CONTEXT * pIsapiContext ) { IIsapiCore * pIsapiCore; HRESULT hr; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); DBG_REQUIRE( ( pIsapiCore = pIsapiContext->QueryIsapiCoreInterface() ) != NULL ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_CLOSE_CONNECTION[%p]: Function Entry\r\n" " <END>\r\n\r\n", pIsapiContext )); } hr = pIsapiCore->CloseConnection(); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_CLOSE_CONNECTION[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } return hr; } // stristr (stolen from fts.c, wickn) // // case-insensitive version of strstr. // stristr returns a pointer to the first occurrence of // pszSubString in pszString. The search does not include // terminating nul characters. // // BUGBUG: is this DBCS-safe? const char* stristr2( const char* pszString, const char* pszSubString ) { const char *cp1 = (const char*) pszString, *cp2, *cp1a; char first; // get the first char in string to find first = pszSubString[0]; // first char often won't be alpha if (isalpha(first)) { first = (char) tolower(first); for ( ; *cp1 != '\0'; cp1++) { if (tolower(*cp1) == first) { for (cp1a = &cp1[1], cp2 = (const char*) &pszSubString[1]; ; cp1a++, cp2++) { if (*cp2 == '\0') return cp1; if (tolower(*cp1a) != tolower(*cp2)) break; } } } } else { for ( ; *cp1 != '\0' ; cp1++) { if (*cp1 == first) { for (cp1a = &cp1[1], cp2 = (const char*) &pszSubString[1]; ; cp1a++, cp2++) { if (*cp2 == '\0') return cp1; if (tolower(*cp1a) != tolower(*cp2)) break; } } } } return NULL; }
30.145829
129
0.464947
npocmaka
b1524e07f8eaa10642fa8ed49eaac42a1b87935b
1,526
cpp
C++
toolsets/test/clang_test.cpp
lukka/evoke
793a067e2d70c4c5da77f75c7aadc734d633068d
[ "Apache-2.0" ]
null
null
null
toolsets/test/clang_test.cpp
lukka/evoke
793a067e2d70c4c5da77f75c7aadc734d633068d
[ "Apache-2.0" ]
null
null
null
toolsets/test/clang_test.cpp
lukka/evoke
793a067e2d70c4c5da77f75c7aadc734d633068d
[ "Apache-2.0" ]
null
null
null
#include "dotted.h" #include "Component.h" #include "File.h" #include "Toolset.h" #include "Project.h" #include <algorithm> #include <set> #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_CASE(clang_compile) { Component c("hello", true); Project p("./"); File *input = p.CreateFile(c, "hello/src/gretting.cpp"); const std::set<std::string> includes {"hello/include"}; ClangToolset clang; auto cmd = clang.getCompileCommand("clang++", "-std=c++17", "obj/hello/src/gretting.cpp.obj", input, includes, false); BOOST_TEST(cmd == "clang++ -c -std=c++17 -o obj/hello/src/gretting.cpp.obj hello/src/gretting.cpp -Ihello/include"); } BOOST_AUTO_TEST_CASE(clang_archive) { Component c("mylib", true); Project p("./"); File *input = p.CreateFile(c, "obj/mylib/src/mylib.cpp.obj"); ClangToolset clang; auto cmd = clang.getArchiverCommand("ar", "lib/libmylib.lib", {input}); BOOST_TEST(cmd == "ar rcs lib/libmylib.lib obj/mylib/src/mylib.cpp.obj"); } BOOST_AUTO_TEST_CASE(clang_link) { Component c("mylib", true); c.type = "library"; c.buildSuccess = true; Project p("./"); File *input1 = p.CreateFile(c, "obj/hello/src/gretting.cpp.obj"); File *input2 = p.CreateFile(c, "obj/hello/src/main.cpp.obj"); ClangToolset clang; auto cmd = clang.getLinkerCommand("clang++", "bin/hello.exe", {input1, input2}, {{&c}}); BOOST_TEST(cmd == "clang++ -o bin/hello.exe obj/hello/src/gretting.cpp.obj obj/hello/src/main.cpp.obj -Lbuild/clang/lib -lmylib"); }
35.488372
134
0.669069
lukka
b1555e2995b958b94e86804ee67b6feff543f063
3,300
cpp
C++
src/PlatformUtils.cpp
TroyNeubauer/TMalloc
77be16040ddad08aea0f98611f70525c5f944cd6
[ "Apache-2.0" ]
null
null
null
src/PlatformUtils.cpp
TroyNeubauer/TMalloc
77be16040ddad08aea0f98611f70525c5f944cd6
[ "Apache-2.0" ]
null
null
null
src/PlatformUtils.cpp
TroyNeubauer/TMalloc
77be16040ddad08aea0f98611f70525c5f944cd6
[ "Apache-2.0" ]
null
null
null
#include "PlatformUtils.h" #include <Windows.h> #include <psapi.h> #include <TCHAR.h> #include <pdh.h> //total CPU usage static PDH_HQUERY cpuQuery; static PDH_HCOUNTER cpuTotal; //Process CPU time static ULARGE_INTEGER lastCPU, lastSysCPU, lastUserCPU; static int numProcessors; static HANDLE self; void PlatformUtils::Init() { PdhOpenQuery(NULL, NULL, &cpuQuery); PdhAddEnglishCounter(cpuQuery, "\\Processor(_Total)\\% Processor Time", NULL, &cpuTotal); PdhCollectQueryData(cpuQuery); SYSTEM_INFO sysInfo; FILETIME ftime, fsys, fuser; GetSystemInfo(&sysInfo); numProcessors = sysInfo.dwNumberOfProcessors; GetSystemTimeAsFileTime(&ftime); memcpy(&lastCPU, &ftime, sizeof(FILETIME)); self = GetCurrentProcess(); GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser); memcpy(&lastSysCPU, &fsys, sizeof(FILETIME)); memcpy(&lastUserCPU, &fuser, sizeof(FILETIME)); } void GetMemInfo(MEMORYSTATUSEX* memInfo) { memInfo->dwLength = sizeof(MEMORYSTATUSEX); GlobalMemoryStatusEx(memInfo); } unsigned long long PlatformUtils::GetTotalMachineVirtualMemory() { MEMORYSTATUSEX memInfo; GetMemInfo(&memInfo); DWORDLONG totalVirtualMem = memInfo.ullTotalPageFile; return totalVirtualMem; } unsigned long long PlatformUtils::GetSystemVirtualMemoryUsage() { MEMORYSTATUSEX memInfo; GetMemInfo(&memInfo); DWORDLONG virtualMemUsed = memInfo.ullTotalPageFile - memInfo.ullAvailPageFile; return virtualMemUsed; } unsigned long long PlatformUtils::GetProcessVirtualMemoryUsage() { PROCESS_MEMORY_COUNTERS_EX pmc; GetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS*)&pmc, sizeof(pmc)); SIZE_T virtualMemUsedByMe = pmc.PrivateUsage; return virtualMemUsedByMe; } //stats for physical memory unsigned long long PlatformUtils::GetTotalMachinePhysicalMemory() { MEMORYSTATUSEX memInfo; GetMemInfo(&memInfo); DWORDLONG totalPhysMem = memInfo.ullTotalPhys; return totalPhysMem; } unsigned long long PlatformUtils::GetSystemPhysicalMemoryUsage() { MEMORYSTATUSEX memInfo; GetMemInfo(&memInfo); DWORDLONG physMemUsed = memInfo.ullTotalPhys - memInfo.ullAvailPhys; return physMemUsed; } unsigned long long PlatformUtils::GetProcessPhysicalMemoryUsage() { PROCESS_MEMORY_COUNTERS_EX pmc; GetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS*)&pmc, sizeof(pmc)); SIZE_T physMemUsedByMe = pmc.WorkingSetSize; return physMemUsedByMe; } float PlatformUtils::GetSystemCPUUsagePercent() { PDH_FMT_COUNTERVALUE counterVal; PdhCollectQueryData(cpuQuery); PdhGetFormattedCounterValue(cpuTotal, PDH_FMT_DOUBLE, NULL, &counterVal); return (float) counterVal.doubleValue; } float PlatformUtils::GetProcessCPUUsagePercent() { FILETIME ftime, fsys, fuser; ULARGE_INTEGER now, sys, user; double percent; GetSystemTimeAsFileTime(&ftime); memcpy(&now, &ftime, sizeof(FILETIME)); GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser); memcpy(&sys, &fsys, sizeof(FILETIME)); memcpy(&user, &fuser, sizeof(FILETIME)); percent = (sys.QuadPart - lastSysCPU.QuadPart) + (user.QuadPart - lastUserCPU.QuadPart); percent /= (now.QuadPart - lastCPU.QuadPart); percent /= numProcessors; lastCPU = now; lastUserCPU = user; lastSysCPU = sys; return (float) (percent * 100.0); } int PlatformUtils::GetProcessorCount() { return numProcessors; }
26.190476
90
0.780303
TroyNeubauer
b1559583e47919e0a837b5fcd0bb97833b43ecc6
1,459
hpp
C++
libraries/plugins/witness/include/steem/plugins/witness/witness_plugin_objects.hpp
DunnCreativeSS/ccd
83531f2c902a7e8bea351c86c4ca0e4b03820d5b
[ "MIT" ]
1
2021-09-02T16:09:26.000Z
2021-09-02T16:09:26.000Z
libraries/plugins/witness/include/steem/plugins/witness/witness_plugin_objects.hpp
DunnCreativeSS/ccd
83531f2c902a7e8bea351c86c4ca0e4b03820d5b
[ "MIT" ]
null
null
null
libraries/plugins/witness/include/steem/plugins/witness/witness_plugin_objects.hpp
DunnCreativeSS/ccd
83531f2c902a7e8bea351c86c4ca0e4b03820d5b
[ "MIT" ]
null
null
null
#pragma once #include <CreateCoin/chain/CreateCoin_object_types.hpp> #ifndef CreateCoin_WITNESS_SPACE_ID #define CreateCoin_WITNESS_SPACE_ID 19 #endif namespace CreateCoin { namespace chain { struct by_account; } } namespace CreateCoin { namespace plugins { namespace witness { using namespace CreateCoin::chain; enum witness_object_types { witness_custom_op_object_type = ( CreateCoin_WITNESS_SPACE_ID << 8 ) }; class witness_custom_op_object : public object< witness_custom_op_object_type, witness_custom_op_object > { public: template< typename Constructor, typename Allocator > witness_custom_op_object( Constructor&& c, allocator< Allocator > a ) { c( *this ); } id_type id; account_name_type account; }; typedef multi_index_container< witness_custom_op_object, indexed_by< ordered_unique< tag< by_id >, member< witness_custom_op_object, witness_custom_op_object::id_type, &witness_custom_op_object::id > >, ordered_unique< tag< by_account >, member< witness_custom_op_object, account_name_type, &witness_custom_op_object::account > > >, allocator< witness_custom_op_object > > witness_custom_op_index; } } } FC_REFLECT( CreateCoin::plugins::witness::witness_custom_op_object, (id) (account) ) CHAINBASE_SET_INDEX_TYPE( CreateCoin::plugins::witness::witness_custom_op_object, CreateCoin::plugins::witness::witness_custom_op_index )
28.607843
139
0.751199
DunnCreativeSS
b15717f205bad2b2ea5706d07b6808061cd79de4
2,734
hpp
C++
cpp/include/raft/linalg/detail/eltwise.hpp
akifcorduk/raft
5de31e04f03ed457ec1cb1148be54ff1cf9888cd
[ "Apache-2.0" ]
null
null
null
cpp/include/raft/linalg/detail/eltwise.hpp
akifcorduk/raft
5de31e04f03ed457ec1cb1148be54ff1cf9888cd
[ "Apache-2.0" ]
null
null
null
cpp/include/raft/linalg/detail/eltwise.hpp
akifcorduk/raft
5de31e04f03ed457ec1cb1148be54ff1cf9888cd
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2022, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "functional.cuh" #include <raft/linalg/binary_op.hpp> #include <raft/linalg/unary_op.hpp> namespace raft { namespace linalg { namespace detail { template <typename InType, typename IdxType, typename OutType = InType> void scalarAdd(OutType* out, const InType* in, InType scalar, IdxType len, cudaStream_t stream) { raft::linalg::unaryOp(out, in, len, adds_scalar<InType, OutType>(scalar), stream); } template <typename InType, typename IdxType, typename OutType = InType> void scalarMultiply(OutType* out, const InType* in, InType scalar, IdxType len, cudaStream_t stream) { raft::linalg::unaryOp(out, in, len, multiplies_scalar<InType, OutType>(scalar), stream); } template <typename InType, typename IdxType, typename OutType = InType> void eltwiseAdd( OutType* out, const InType* in1, const InType* in2, IdxType len, cudaStream_t stream) { raft::linalg::binaryOp(out, in1, in2, len, thrust::plus<InType>(), stream); } template <typename InType, typename IdxType, typename OutType = InType> void eltwiseSub( OutType* out, const InType* in1, const InType* in2, IdxType len, cudaStream_t stream) { raft::linalg::binaryOp(out, in1, in2, len, thrust::minus<InType>(), stream); } template <typename InType, typename IdxType, typename OutType = InType> void eltwiseMultiply( OutType* out, const InType* in1, const InType* in2, IdxType len, cudaStream_t stream) { raft::linalg::binaryOp(out, in1, in2, len, thrust::multiplies<InType>(), stream); } template <typename InType, typename IdxType, typename OutType = InType> void eltwiseDivide( OutType* out, const InType* in1, const InType* in2, IdxType len, cudaStream_t stream) { raft::linalg::binaryOp(out, in1, in2, len, thrust::divides<InType>(), stream); } template <typename InType, typename IdxType, typename OutType = InType> void eltwiseDivideCheckZero( OutType* out, const InType* in1, const InType* in2, IdxType len, cudaStream_t stream) { raft::linalg::binaryOp(out, in1, in2, len, divides_check_zero<InType, OutType>(), stream); } }; // end namespace detail }; // end namespace linalg }; // end namespace raft
35.051282
100
0.740673
akifcorduk
b158572c0dd699fad0141dc51996b0c5bbcbbc73
2,413
cpp
C++
openjdk11/src/hotspot/cpu/arm/icBuffer_arm.cpp
iootclab/openjdk
b01fc962705eadfa96def6ecff46c44d522e0055
[ "Apache-2.0" ]
2
2018-06-19T05:43:32.000Z
2018-06-23T10:04:56.000Z
openjdk11/src/hotspot/cpu/arm/icBuffer_arm.cpp
iootclab/openjdk
b01fc962705eadfa96def6ecff46c44d522e0055
[ "Apache-2.0" ]
null
null
null
openjdk11/src/hotspot/cpu/arm/icBuffer_arm.cpp
iootclab/openjdk
b01fc962705eadfa96def6ecff46c44d522e0055
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2008, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #include "precompiled.hpp" #include "asm/assembler.hpp" #include "assembler_arm.inline.hpp" #include "code/icBuffer.hpp" #include "gc/shared/collectedHeap.inline.hpp" #include "interpreter/bytecodes.hpp" #include "memory/resourceArea.hpp" #include "nativeInst_arm.hpp" #include "oops/oop.inline.hpp" #define __ masm-> int InlineCacheBuffer::ic_stub_code_size() { return (AARCH64_ONLY(8) NOT_AARCH64(4)) * Assembler::InstructionSize; } void InlineCacheBuffer::assemble_ic_buffer_code(address code_begin, void* cached_value, address entry_point) { ResourceMark rm; CodeBuffer code(code_begin, ic_stub_code_size()); MacroAssembler* masm = new MacroAssembler(&code); InlinedAddress oop_literal((address) cached_value); __ ldr_literal(Ricklass, oop_literal); // FIXME: OK to remove reloc here? __ patchable_jump(entry_point, relocInfo::runtime_call_type, Rtemp); __ bind_literal(oop_literal); __ flush(); } address InlineCacheBuffer::ic_buffer_entry_point(address code_begin) { address jump_address; jump_address = code_begin + NativeInstruction::instruction_size; NativeJump* jump = nativeJump_at(jump_address); return jump->jump_destination(); } void* InlineCacheBuffer::ic_buffer_cached_value(address code_begin) { NativeMovConstReg* move = nativeMovConstReg_at(code_begin); return (void*)move->data(); } #undef __
36.014925
110
0.765437
iootclab
b15a1f47e0029a20ee776b4d9b169df9d89590b4
2,084
cpp
C++
beScene/source/beSerializationParameters.cpp
gcodebackups/breeze-2
1692b97f455c4bc856ec2f0eb8c0b86e708a398a
[ "MIT" ]
null
null
null
beScene/source/beSerializationParameters.cpp
gcodebackups/breeze-2
1692b97f455c4bc856ec2f0eb8c0b86e708a398a
[ "MIT" ]
null
null
null
beScene/source/beSerializationParameters.cpp
gcodebackups/breeze-2
1692b97f455c4bc856ec2f0eb8c0b86e708a398a
[ "MIT" ]
null
null
null
/****************************************************/ /* breeze Engine Scene Module (c) Tobias Zirr 2011 */ /****************************************************/ #include "beSceneInternal/stdafx.h" #include "beScene/beSerializationParameters.h" #include <beEntitySystem/beSerializationParameters.h> namespace beScene { // Gets the serialization parameter IDs. const SceneParameterIDs& GetSceneParameterIDs() { beCore::ParameterLayout &layout = beEntitySystem::GetSerializationParameters(); static SceneParameterIDs parameterIDs( layout.Add("beScene.ResourceManager"), layout.Add("beScene.Renderer"), layout.Add("beScene.RenderingController") ); return parameterIDs; } // Sets the given scene parameters in the given parameter set. void SetSceneParameters(beCore::ParameterSet &parameters, const SceneParameters &sceneParameters) { const beCore::ParameterLayout &layout = beEntitySystem::GetSerializationParameters(); const SceneParameterIDs& parameterIDs = GetSceneParameterIDs(); parameters.SetValue(layout, parameterIDs.ResourceManager, sceneParameters.ResourceManager); parameters.SetValue(layout, parameterIDs.Renderer, sceneParameters.Renderer); parameters.SetValue(layout, parameterIDs.RenderingController, sceneParameters.RenderingController); } // Sets the given scene parameters in the given parameter set. SceneParameters GetSceneParameters(const beCore::ParameterSet &parameters) { SceneParameters sceneParameters; const beCore::ParameterLayout &layout = beEntitySystem::GetSerializationParameters(); const SceneParameterIDs& parameterIDs = GetSceneParameterIDs(); sceneParameters.ResourceManager = parameters.GetValueChecked< beScene::ResourceManager* >(layout, parameterIDs.ResourceManager); sceneParameters.Renderer = parameters.GetValueChecked< EffectDrivenRenderer* >(layout, parameterIDs.Renderer); sceneParameters.RenderingController = parameters.GetValueChecked< RenderingController* >(layout, parameterIDs.RenderingController); return sceneParameters; } } // namespace
38.592593
133
0.753839
gcodebackups
b15ac9a062f21c3f2e67b4623c02db1fdbbf981a
77
cxx
C++
Modules/ThirdParty/VNL/src/vxl/core/vnl/Templates/vnl_vector_fixed+double.4-.cxx
rdsouza10/ITK
07cb23f9866768b5f4ee48ebec8766b6e19efc69
[ "Apache-2.0" ]
3
2019-11-19T09:47:25.000Z
2022-02-24T00:32:31.000Z
Modules/ThirdParty/VNL/src/vxl/core/vnl/Templates/vnl_vector_fixed+double.4-.cxx
rdsouza10/ITK
07cb23f9866768b5f4ee48ebec8766b6e19efc69
[ "Apache-2.0" ]
1
2019-03-18T14:19:49.000Z
2020-01-11T13:54:33.000Z
Modules/ThirdParty/VNL/src/vxl/core/vnl/Templates/vnl_vector_fixed+double.4-.cxx
rdsouza10/ITK
07cb23f9866768b5f4ee48ebec8766b6e19efc69
[ "Apache-2.0" ]
1
2022-02-24T00:32:36.000Z
2022-02-24T00:32:36.000Z
#include <vnl/vnl_vector_fixed.hxx> VNL_VECTOR_FIXED_INSTANTIATE(double,4);
19.25
39
0.831169
rdsouza10
b15bcd81aeaf9e3b64c09ca41e58b7b830d861fb
7,790
cc
C++
src/Core/Datatypes/Mesh/Tests/LatticeVolumeMeshTests.cc
kimjohn1/SCIRun
62ae6cb632100371831530c755ef0b133fb5c978
[ "MIT" ]
92
2015-02-09T22:42:11.000Z
2022-03-25T09:14:50.000Z
src/Core/Datatypes/Mesh/Tests/LatticeVolumeMeshTests.cc
kimjohn1/SCIRun
62ae6cb632100371831530c755ef0b133fb5c978
[ "MIT" ]
1,618
2015-01-05T19:39:13.000Z
2022-03-27T20:28:45.000Z
src/Core/Datatypes/Mesh/Tests/LatticeVolumeMeshTests.cc
kimjohn1/SCIRun
62ae6cb632100371831530c755ef0b133fb5c978
[ "MIT" ]
64
2015-02-20T17:51:23.000Z
2021-11-19T07:08:08.000Z
/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2020 Scientific Computing and Imaging Institute, University of Utah. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <gtest/gtest.h> #include <gmock/gmock.h> #include <boost/assign.hpp> //#include <Core/Datatypes/Mesh/MeshFactory.h> #include <Core/Datatypes/Legacy/Field/FieldInformation.h> #include <Core/Datatypes/Legacy/Field/LatVolMesh.h> using namespace SCIRun; using namespace SCIRun::Core::Datatypes; using namespace SCIRun::Core::Geometry; using ::testing::_; using ::testing::NiceMock; using ::testing::DefaultValue; using ::testing::Return; using namespace boost::assign; class LatticeVolumeMeshTests : public ::testing::Test { protected: void SetUp() override { int basisOrder = 1; FieldInformation lfi("LatVolMesh", basisOrder, "double"); int sizex,sizey,sizez; sizex = sizey = sizez = 2; Point minb(0,0,0); Point maxb(1,1,1); mesh_ = CreateMesh(lfi, sizex, sizey, sizez, minb, maxb); } MeshHandle mesh_; }; namespace { template <typename T> std::string join(const T& list) { std::ostringstream oss; const int SIZE = list.size(); for (int i = 0; i < SIZE; ++i) { oss << list[i]; if (i < SIZE - 1) oss << ", "; } return oss.str(); } } TEST_F(LatticeVolumeMeshTests, BasicCubeTest) { ASSERT_TRUE(mesh_.get() != nullptr); auto latVolVMesh = mesh_->vmesh(); ASSERT_TRUE(latVolVMesh != nullptr); VMesh::dimension_type dims; latVolVMesh->get_dimensions(dims); VMesh::dimension_type expectedDims; expectedDims += 2,2,2; EXPECT_EQ(expectedDims, dims); EXPECT_EQ(8, latVolVMesh->num_nodes()); EXPECT_EQ(12, latVolVMesh->num_edges()); EXPECT_EQ(6, latVolVMesh->num_faces()); EXPECT_EQ(1, latVolVMesh->num_elems()); #ifdef SCIRUN4_CODE_TO_BE_ENABLED_LATER ASSERT_TRUE(latVolVMesh->is_linearmesh()); ASSERT_FALSE(latVolVMesh->has_normals()); #endif } TEST_F(LatticeVolumeMeshTests, CubeIterationTest) { auto latVolVMesh = mesh_->vmesh(); { VMesh::Edge::iterator meshEdgeIter; VMesh::Edge::iterator meshEdgeEnd; VMesh::Node::array_type nodesFromEdge(2); latVolVMesh->end(meshEdgeEnd); std::ostringstream ostr; for (latVolVMesh->begin(meshEdgeIter); meshEdgeIter != meshEdgeEnd; ++meshEdgeIter) { // get nodes from edge VMesh::Edge::index_type edgeID = *meshEdgeIter; latVolVMesh->get_nodes(nodesFromEdge, edgeID); Point p0, p1; latVolVMesh->get_point(p0, nodesFromEdge[0]); latVolVMesh->get_point(p1, nodesFromEdge[1]); ostr << "Edge " << edgeID << " nodes=[" << nodesFromEdge[0] << " point=" << p0.get_string() << ", " << nodesFromEdge[1] << " point=" << p1.get_string() << "]" << std::endl; } EXPECT_EQ( "Edge 0 nodes=[0 point=[0, 0, 0], 1 point=[1, 0, 0]]\n" "Edge 1 nodes=[2 point=[0, 1, 0], 3 point=[1, 1, 0]]\n" "Edge 2 nodes=[4 point=[0, 0, 1], 5 point=[1, 0, 1]]\n" "Edge 3 nodes=[6 point=[0, 1, 1], 7 point=[1, 1, 1]]\n" "Edge 4 nodes=[0 point=[0, 0, 0], 2 point=[0, 1, 0]]\n" "Edge 5 nodes=[4 point=[0, 0, 1], 6 point=[0, 1, 1]]\n" "Edge 6 nodes=[1 point=[1, 0, 0], 3 point=[1, 1, 0]]\n" "Edge 7 nodes=[5 point=[1, 0, 1], 7 point=[1, 1, 1]]\n" "Edge 8 nodes=[0 point=[0, 0, 0], 4 point=[0, 0, 1]]\n" "Edge 9 nodes=[1 point=[1, 0, 0], 5 point=[1, 0, 1]]\n" "Edge 10 nodes=[2 point=[0, 1, 0], 6 point=[0, 1, 1]]\n" "Edge 11 nodes=[3 point=[1, 1, 0], 7 point=[1, 1, 1]]\n" , ostr.str()); } { VMesh::Face::iterator meshFaceIter; VMesh::Face::iterator meshFaceEnd; VMesh::Edge::array_type edgesFromFace(4); VMesh::Node::array_type nodesFromFace(4); latVolVMesh->end(meshFaceEnd); std::ostringstream ostr; for (latVolVMesh->begin(meshFaceIter); meshFaceIter != meshFaceEnd; ++meshFaceIter) { // get edges and nodes from face VMesh::Face::index_type faceID = *meshFaceIter; latVolVMesh->get_edges(edgesFromFace, faceID); ostr << "Face " << faceID << " edges=[" << join(edgesFromFace) << "]" << std::endl; latVolVMesh->get_nodes(nodesFromFace, faceID); ostr << "Face " << faceID << " nodes=[" << join(nodesFromFace) << "]" << std::endl; } EXPECT_EQ("Face 0 edges=[0, 1, 4, 6]\n" "Face 0 nodes=[0, 1, 3, 2]\n" "Face 1 edges=[2, 3, 5, 7]\n" "Face 1 nodes=[4, 6, 7, 5]\n" "Face 2 edges=[4, 5, 8, 10]\n" "Face 2 nodes=[0, 2, 6, 4]\n" "Face 3 edges=[6, 7, 9, 11]\n" "Face 3 nodes=[1, 5, 7, 3]\n" "Face 4 edges=[0, 2, 8, 9]\n" "Face 4 nodes=[0, 4, 5, 1]\n" "Face 5 edges=[1, 3, 10, 11]\n" "Face 5 nodes=[2, 3, 7, 6]\n" ,ostr.str()); } { VMesh::Cell::iterator meshCellIter; VMesh::Cell::iterator meshCellEnd; VMesh::Edge::array_type edgesFromCell(12); VMesh::Node::array_type nodesFromCell(8); latVolVMesh->end(meshCellEnd); std::ostringstream ostr; for (latVolVMesh->begin(meshCellIter); meshCellIter != meshCellEnd; ++meshCellIter) { // get edges and nodes from mesh element VMesh::Cell::index_type elemID = *meshCellIter; latVolVMesh->get_edges(edgesFromCell, elemID); ostr << "Cell " << elemID << " edges=[" << join(edgesFromCell) << "]" << std::endl; latVolVMesh->get_nodes(nodesFromCell, elemID); ostr << "Cell " << elemID << " nodes=["<< join(nodesFromCell) << "]" << std::endl; } EXPECT_EQ( "Cell 0 edges=[0, 1, 2, 3, 4, 6, 5, 7, 8, 9, 10, 11]\n" "Cell 0 nodes=[0, 1, 3, 2, 4, 5, 7, 6]\n", ostr.str()); } { VMesh::Node::iterator meshNodeIter; VMesh::Node::iterator meshNodeEnd; VMesh::Edge::array_type edgesFromNode(3); latVolVMesh->end(meshNodeEnd); std::ostringstream ostr; for (latVolVMesh->begin(meshNodeIter); meshNodeIter != meshNodeEnd; ++meshNodeIter) { // get edges and point from mesh node VMesh::Node::index_type nodeID = *meshNodeIter; Point p; latVolVMesh->get_point(p, nodeID); ostr << "Node " << nodeID << " point=" << p.get_string(); latVolVMesh->get_edges(edgesFromNode, nodeID); ostr << " edges=[" << join(edgesFromNode) << "]" << std::endl; } EXPECT_EQ("Node 0 point=[0, 0, 0] edges=[0, 4, 8]\n" "Node 1 point=[1, 0, 0] edges=[0, 6, 9]\n" "Node 2 point=[0, 1, 0] edges=[1, 6, 10]\n" "Node 3 point=[1, 1, 0] edges=[1, 8, 11]\n" "Node 4 point=[0, 0, 1] edges=[2, 5, 9]\n" "Node 5 point=[1, 0, 1] edges=[2, 7, 10]\n" "Node 6 point=[0, 1, 1] edges=[3, 7, 11]\n" "Node 7 point=[1, 1, 1] edges=[3, 9, 12]\n", ostr.str()); } }
31.92623
97
0.62362
kimjohn1
b15c0cbad4bfe40d6b175643ae4ef05aadad32a0
439
hpp
C++
library/ATF/tagNMTOOLBARA.hpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
library/ATF/tagNMTOOLBARA.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
library/ATF/tagNMTOOLBARA.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> #include <_TBBUTTON.hpp> #include <tagNMHDR.hpp> #include <tagRECT.hpp> START_ATF_NAMESPACE struct tagNMTOOLBARA { tagNMHDR hdr; int iItem; _TBBUTTON tbButton; int cchText; char *pszText; tagRECT rcButton; }; END_ATF_NAMESPACE
20.904762
108
0.67426
lemkova
b15d0d237ff0e7cce48d10ccabdcdcd397e7ad51
3,594
hxx
C++
src/tst/reporter.hxx
igagis/testy
a38281336816bec1651d818fa7aad89ecade17b2
[ "MIT" ]
8
2021-04-16T13:17:20.000Z
2022-01-05T09:14:03.000Z
src/tst/reporter.hxx
igagis/testy
a38281336816bec1651d818fa7aad89ecade17b2
[ "MIT" ]
16
2021-04-19T07:59:52.000Z
2022-02-07T11:14:55.000Z
src/tst/reporter.hxx
igagis/testy
a38281336816bec1651d818fa7aad89ecade17b2
[ "MIT" ]
3
2021-04-17T02:33:46.000Z
2022-02-21T15:37:55.000Z
/* MIT License Copyright (c) 2021 Ivan Gagis Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* ================ LICENSE END ================ */ #pragma once #include <string> #include <mutex> #include "suite.hpp" #include "application.hpp" #include "util.hxx" namespace tst{ class reporter{ private: std::mutex mutex; const application& app; const size_t num_tests; size_t num_failed = 0; size_t num_passed = 0; size_t num_disabled = 0; size_t num_errors = 0; // thread safe void report( const full_id& id, suite::status result, uint32_t dt, std::string&& message = std::string() ); public: uint32_t time_ms = 0; reporter(const application& app) : app(app), num_tests(app.num_tests()) {} // thread safe void report_pass(const full_id& id, uint32_t dt) { this->report(id, suite::status::passed, dt); } // thread safe void report_failure( const full_id& id, uint32_t dt, std::string&& message ) { this->report(id, suite::status::failed, dt, std::move(message)); } // thread safe void report_error( const full_id& id, uint32_t dt, std::string&& message ) { this->report(id, suite::status::errored, dt, std::move(message)); } // thread safe void report_skipped( const full_id& id, std::string&& message ) { this->report(id, suite::status::not_run, 0, std::move(message)); } // thread safe void report_disabled_test(const full_id& id){ this->report(id, suite::status::disabled, 0); } size_t num_unsuccessful()const noexcept{ return this->num_failed + this->num_errors; } size_t num_not_run()const noexcept{ return this->num_disabled + this->num_skipped(); } size_t num_ran()const noexcept{ return this->num_unsuccessful() + this->num_passed + this->num_disabled; } size_t num_skipped()const noexcept{ ASSERT(this->num_tests >= this->num_ran()) return this->num_tests - this->num_ran(); } void print_num_tests_run(std::ostream& o)const; void print_num_tests_about_to_run(std::ostream& o)const; void print_num_tests_passed(std::ostream& o)const; void print_num_tests_disabled(std::ostream& o)const; void print_num_tests_failed(std::ostream& o)const; void print_num_tests_skipped(std::ostream& o)const; void print_num_warnings(std::ostream& o)const; void print_outcome(std::ostream& o)const; bool is_failed()const noexcept{ return this->num_failed != 0 || this->num_errors != 0; } bool is_semi_passed()const noexcept{ return !this->is_failed() && this->num_skipped() == 0 && this->num_not_run() == 0; } void write_junit_report(const std::string& file_name)const; }; }
25.132867
84
0.720367
igagis
b15f3224e73fcfaa3b1b5f901633d592af8a948e
623
cpp
C++
SingleSource/Regression/C++/pointer_method2.cpp
Nuullll/llvm-test-suite
afbdd0a9ee7770e074708b68b34a6a5312bb0b36
[ "Apache-2.0" ]
84
2017-10-25T15:49:21.000Z
2021-11-28T21:25:54.000Z
SingleSource/Regression/C++/pointer_method2.cpp
Nuullll/llvm-test-suite
afbdd0a9ee7770e074708b68b34a6a5312bb0b36
[ "Apache-2.0" ]
519
2020-09-15T07:40:51.000Z
2022-03-31T20:51:15.000Z
SingleSource/Regression/C++/pointer_method2.cpp
Nuullll/llvm-test-suite
afbdd0a9ee7770e074708b68b34a6a5312bb0b36
[ "Apache-2.0" ]
117
2020-06-24T13:11:04.000Z
2022-03-23T15:44:23.000Z
#include <stdio.h> struct A { int a; virtual void foo() = 0; void bar() { printf("A::bar(): a=%x\n", a); } }; struct B { int b; virtual void foo() = 0; void bar() { printf("B::bar(): b=%x\n", b); } }; struct C : A, B { int c; virtual void foo() { printf("C::foo(), c=%x\n", c); } void bar() { printf("C::bar(), c=%x\n", c); } }; template <class T> void invoke(C &c, void (T::*fn)()) { (c.*fn)(); } int main() { C c; c.a = 0xff; c.b = 0xf0f; c.c = 0xf00f; invoke(c, &A::foo); invoke(c, &A::bar); invoke(c, &B::foo); invoke(c, &B::bar); invoke(c, &C::foo); invoke(c, &C::bar); }
16.394737
55
0.483146
Nuullll