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
f150a727cad6a3e7269e4ced9a2a70305180e5ea
6,816
hpp
C++
include/intent/utils/Logger.hpp
open-intent-io/open-intent
57d8c4fc89c038f51138d51e776880e728152194
[ "MIT" ]
47
2016-07-05T15:20:33.000Z
2021-08-06T05:38:33.000Z
include/intent/utils/Logger.hpp
open-intent-io/open-intent
57d8c4fc89c038f51138d51e776880e728152194
[ "MIT" ]
30
2016-07-03T22:42:11.000Z
2017-11-17T15:58:10.000Z
include/intent/utils/Logger.hpp
open-intent-io/open-intent
57d8c4fc89c038f51138d51e776880e728152194
[ "MIT" ]
8
2016-07-22T20:07:58.000Z
2017-11-05T10:40:29.000Z
/* |---------------------------------------------------------| | ___ ___ _ _ | | / _ \ _ __ ___ _ __ |_ _|_ __ | |_ ___ _ __ | |_ | | | | | | '_ \ / _ \ '_ \ | || '_ \| __/ _ \ '_ \| __| | | | |_| | |_) | __/ | | || || | | | || __/ | | | |_ | | \___/| .__/ \___|_| |_|___|_| |_|\__\___|_| |_|\__| | | |_| | | | | - The users first... | | | | Authors: | | - Clement Michaud | | - Sergei Kireev | | | | Version: 1.0.0 | | | |---------------------------------------------------------| The MIT License (MIT) Copyright (c) 2016 - Clement Michaud, Sergei Kireev 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. */ #ifndef INTENT_LOGGER_HPP #define INTENT_LOGGER_HPP #include <iostream> #include "spdlog/spdlog.h" #include <string> #include <sstream> namespace intent { namespace log { class Logger { public: /** * \brief The severity levels handled by the logger */ struct SeverityLevel { enum type { TRACE, DEBUG, INFO, WARNING, ERROR, FATAL }; }; /** * @brief Initialize the logging system with the maximum severity level to * use. * \param severityLevel The maximum severity level to use. */ static void initialize(SeverityLevel::type severityLevel); /** * @brief Return the severity type for string. Return FATAL if nothing is * matching. * @param severity The string to convert into severity level * @return the severity level */ static SeverityLevel::type severityLevelFromString( const std::string& severity); /** * @brief Get the static instance of the logger * \return The logger instance */ static Logger& getInstance() { static Logger* logger = NULL; if (logger == NULL) { logger = new Logger(); SeverityLevel::type initialLevel = SeverityLevel::FATAL; if (const char* env_p = std::getenv("LOG_LEVEL")) { initialLevel = Logger::severityLevelFromString(env_p); } initialize(initialLevel); } return *logger; } template <int v> struct Int2Type { enum { value = v }; }; /** * \brief Logger by level of severity. */ template <SeverityLevel::type LogLevel> class LoggerWithLevel { public: /** * \brief Log a message from a string stream. */ LoggerWithLevel& operator<<(const std::stringstream& message) { //*this << message; return *this; } /** * \brief Log a message from an object that supports the stream operator. */ template <typename T> LoggerWithLevel& operator<<(const T& message) { std::stringstream ss; ss << message; log(ss.str(), Int2Type<LogLevel>()); return *this; } private: void log(const std::string& message, Int2Type<SeverityLevel::TRACE>) { spdlog::get("console")->trace(message); } void log(const std::string& message, Int2Type<SeverityLevel::DEBUG>) { spdlog::get("console")->debug(message); } void log(const std::string& message, Int2Type<SeverityLevel::INFO>) { spdlog::get("console")->info(message); } void log(const std::string& message, Int2Type<SeverityLevel::WARNING>) { spdlog::get("console")->warn(message); } void log(const std::string& message, Int2Type<SeverityLevel::ERROR>) { spdlog::get("console")->error(message); } void log(const std::string& message, Int2Type<SeverityLevel::FATAL>) { spdlog::get("console")->critical(message); } }; /** * @brief Get the trace logger * \return the trace logger */ inline LoggerWithLevel<Logger::SeverityLevel::TRACE>& trace() { return m_loggerTrace; } /** * @brief Get the debug logger * \return the debug logger */ inline LoggerWithLevel<Logger::SeverityLevel::DEBUG>& debug() { return m_loggerDebug; } /** * @brief Get the info logger * \return the info logger */ inline LoggerWithLevel<Logger::SeverityLevel::INFO>& info() { return m_loggerInfo; } /** * @brief Get the warning logger * \return the warning logger */ inline LoggerWithLevel<Logger::SeverityLevel::WARNING>& warning() { return m_loggerWarning; } /** * @brief Get the error logger * \return the error logger */ inline LoggerWithLevel<Logger::SeverityLevel::ERROR>& error() { return m_loggerError; } /** * @brief Get the fatal logger * \return the fatal logger */ inline LoggerWithLevel<Logger::SeverityLevel::FATAL>& fatal() { return m_loggerFatal; } private: Logger() {} LoggerWithLevel<Logger::SeverityLevel::TRACE> m_loggerTrace; LoggerWithLevel<Logger::SeverityLevel::DEBUG> m_loggerDebug; LoggerWithLevel<Logger::SeverityLevel::INFO> m_loggerInfo; LoggerWithLevel<Logger::SeverityLevel::WARNING> m_loggerWarning; LoggerWithLevel<Logger::SeverityLevel::ERROR> m_loggerError; LoggerWithLevel<Logger::SeverityLevel::FATAL> m_loggerFatal; }; } } #define INTENT_LOG_TRACE() intent::log::Logger::getInstance().trace() #define INTENT_LOG_DEBUG() intent::log::Logger::getInstance().debug() #define INTENT_LOG_INFO() intent::log::Logger::getInstance().info() #define INTENT_LOG_WARNING() intent::log::Logger::getInstance().warning() #define INTENT_LOG_ERROR() intent::log::Logger::getInstance().error() #define INTENT_LOG_FATAL() intent::log::Logger::getInstance().fatal() #endif
30.841629
79
0.606808
open-intent-io
f15150a1d26756736ba76e08aba31173a98f6fe0
1,631
hpp
C++
PhysicsSandbox/Physics2dTCS/Physics2dStandardTCS.hpp
jodavis42/PhysicsSandbox
3119caaa77721041440cdc1b3cf96d4bd9e2d98b
[ "MIT" ]
1
2022-03-26T21:08:19.000Z
2022-03-26T21:08:19.000Z
PhysicsSandbox/Physics2dTCS/Physics2dStandardTCS.hpp
jodavis42/PhysicsSandbox
3119caaa77721041440cdc1b3cf96d4bd9e2d98b
[ "MIT" ]
null
null
null
PhysicsSandbox/Physics2dTCS/Physics2dStandardTCS.hpp
jodavis42/PhysicsSandbox
3119caaa77721041440cdc1b3cf96d4bd9e2d98b
[ "MIT" ]
null
null
null
#pragma once #include "Common/CommonStandard.hpp" #include "Physics2dCore/Detection/Broadphase/BroadphaseLayerType.hpp" namespace SandboxGeometry { class Ray2d; class RayResult2d; }//SandboxBroadphase2d namespace SandboxBroadphase2d { class IBroadphase2d; }//SandboxBroadphase2d namespace Physics2dCore { class RigidBody2d; class Collider2d; class Physics2dEffect; class PropertyChangedEvent; class Collider2dPair; class ContactManifold2d; class IBroadphase2dManager; class Collider2dRaycastResult; class IConstraint2dSolver; class SimpleConstraint2dSolver; }//namespace Physics2dCore namespace Physics2dTCS { using Math::Vector2; using Math::Vector3; using Math::Vector4; using Math::Matrix2; using Math::Matrix3; using Math::Matrix4; using Math::Quaternion; using Ray2d = SandboxGeometry::Ray2d; using RayResult2d = SandboxGeometry::RayResult2d; using IBroadphase2d = SandboxBroadphase2d::IBroadphase2d; using RigidBody2d = Physics2dCore::RigidBody2d; using Collider2d = Physics2dCore::Collider2d; using Physics2dEffect = Physics2dCore::Physics2dEffect; using Collider2dRaycastResult = Physics2dCore::Collider2dRaycastResult; using PropertyChangedEvent = Physics2dCore::PropertyChangedEvent; using IBroadphase2dManager = Physics2dCore::IBroadphase2dManager; using IConstraint2dSolver = Physics2dCore::IConstraint2dSolver; using SimpleConstraint2dSolver = Physics2dCore::SimpleConstraint2dSolver; namespace BroadphaseLayerType = Physics2dCore::BroadphaseLayerType; template <typename T> using Array = Zero::Array<T>; class PhysicsSpace2dTCS; class RigidBody2dTCS; class Collider2dTCS; }//namespace Physics2dTCS
22.652778
73
0.83691
jodavis42
f153798264f9e5ceabb5a78ff90e481c3147998f
5,048
cxx
C++
main/oox/source/drawingml/colorchoicecontext.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/oox/source/drawingml/colorchoicecontext.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/oox/source/drawingml/colorchoicecontext.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #include "oox/drawingml/colorchoicecontext.hxx" #include "oox/helper/attributelist.hxx" #include "oox/drawingml/color.hxx" using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::RuntimeException; using ::com::sun::star::xml::sax::SAXException; using ::com::sun::star::xml::sax::XFastAttributeList; using ::com::sun::star::xml::sax::XFastContextHandler; using ::oox::core::ContextHandler; namespace oox { namespace drawingml { // ============================================================================ ColorValueContext::ColorValueContext( ContextHandler& rParent, Color& rColor ) : ContextHandler( rParent ), mrColor( rColor ) { } void ColorValueContext::startFastElement( sal_Int32 nElement, const Reference< XFastAttributeList >& rxAttribs ) throw (SAXException, RuntimeException) { AttributeList aAttribs( rxAttribs ); switch( nElement ) { case A_TOKEN( scrgbClr ): mrColor.setScrgbClr( aAttribs.getInteger( XML_r, 0 ), aAttribs.getInteger( XML_g, 0 ), aAttribs.getInteger( XML_b, 0 ) ); break; case A_TOKEN( srgbClr ): mrColor.setSrgbClr( aAttribs.getIntegerHex( XML_val, 0 ) ); break; case A_TOKEN( hslClr ): mrColor.setHslClr( aAttribs.getInteger( XML_hue, 0 ), aAttribs.getInteger( XML_sat, 0 ), aAttribs.getInteger( XML_lum, 0 ) ); break; case A_TOKEN( sysClr ): mrColor.setSysClr( aAttribs.getToken( XML_val, XML_TOKEN_INVALID ), aAttribs.getIntegerHex( XML_lastClr, -1 ) ); break; case A_TOKEN( schemeClr ): mrColor.setSchemeClr( aAttribs.getToken( XML_val, XML_TOKEN_INVALID ) ); break; case A_TOKEN( prstClr ): mrColor.setPrstClr( aAttribs.getToken( XML_val, XML_TOKEN_INVALID ) ); break; } } Reference< XFastContextHandler > ColorValueContext::createFastChildContext( sal_Int32 nElement, const Reference< XFastAttributeList >& rxAttribs ) throw (SAXException, RuntimeException) { AttributeList aAttribs( rxAttribs ); switch( nElement ) { case A_TOKEN( alpha ): case A_TOKEN( alphaMod ): case A_TOKEN( alphaOff ): case A_TOKEN( blue ): case A_TOKEN( blueMod ): case A_TOKEN( blueOff ): case A_TOKEN( hue ): case A_TOKEN( hueMod ): case A_TOKEN( hueOff ): case A_TOKEN( lum ): case A_TOKEN( lumMod ): case A_TOKEN( lumOff ): case A_TOKEN( green ): case A_TOKEN( greenMod ): case A_TOKEN( greenOff ): case A_TOKEN( red ): case A_TOKEN( redMod ): case A_TOKEN( redOff ): case A_TOKEN( sat ): case A_TOKEN( satMod ): case A_TOKEN( satOff ): case A_TOKEN( shade ): case A_TOKEN( tint ): mrColor.addTransformation( nElement, aAttribs.getInteger( XML_val, 0 ) ); break; case A_TOKEN( comp ): case A_TOKEN( gamma ): case A_TOKEN( gray ): case A_TOKEN( inv ): case A_TOKEN( invGamma ): mrColor.addTransformation( nElement ); break; } return 0; } // ============================================================================ ColorContext::ColorContext( ContextHandler& rParent, Color& rColor ) : ContextHandler( rParent ), mrColor( rColor ) { } Reference< XFastContextHandler > ColorContext::createFastChildContext( sal_Int32 nElement, const Reference< XFastAttributeList >& ) throw (SAXException, RuntimeException) { switch( nElement ) { case A_TOKEN( scrgbClr ): case A_TOKEN( srgbClr ): case A_TOKEN( hslClr ): case A_TOKEN( sysClr ): case A_TOKEN( schemeClr ): case A_TOKEN( prstClr ): return new ColorValueContext( *this, mrColor ); } return 0; } // ============================================================================ } // namespace drawingml } // namespace oox
32.152866
117
0.590729
Grosskopf
f154891fe957b8a229fd4fc55bc08da83cf36c73
1,549
cpp
C++
Examples/SceneSwitch/src/main.cpp
dodoknight/CogEngine
fda1193c2d1258ba9780e1025933d33a8dce2284
[ "MIT" ]
3
2016-06-01T10:14:00.000Z
2016-10-11T15:53:45.000Z
Examples/SceneSwitch/src/main.cpp
dormantor/ofxCogEngine
fda1193c2d1258ba9780e1025933d33a8dce2284
[ "MIT" ]
null
null
null
Examples/SceneSwitch/src/main.cpp
dormantor/ofxCogEngine
fda1193c2d1258ba9780e1025933d33a8dce2284
[ "MIT" ]
1
2020-08-15T17:01:00.000Z
2020-08-15T17:01:00.000Z
#include "ofxCogMain.h" #include "BehaviorEnt.h" #include "NodeBuilder.h" #include "ofxTextLabel.h" #include "NetworkManager.h" #include "Mesh.h" #include "NetMessage.h" #include "Interpolator.h" #include "AttribAnimator.h" #include "UpdateMessage.h" #include "Stage.h" #include "LuaScripting.h" /* * * The code below is implemented in lua script * class SceneSwitcher : public Behavior { public: SceneSwitcher() { } void OnInit() { SubscribeForMessages(ACT_BUTTON_CLICKED); } void OnMessage(Msg& msg) { if (msg.HasAction(ACT_BUTTON_CLICKED)) { auto stage = GETCOMPONENT(Stage); string actualScene = stage->GetActualScene()->GetName(); string newScene = actualScene.compare("scene1") == 0 ? "scene2" : "scene1"; if (msg.GetContextNode()->GetTag().compare("previous_but") == 0) { stage->SwitchToScene(stage->FindSceneByName(newScene), TweenDirection::RIGHT); } if (msg.GetContextNode()->GetTag().compare("next_but") == 0) { stage->SwitchToScene(stage->FindSceneByName(newScene), TweenDirection::LEFT); } } } void Update(uint64 delta, uint64 absolute) { } };*/ class ExampleApp : public ofxCogApp { void RegisterComponents() { REGISTER_COMPONENT(new LuaScripting()); //REGISTER_BEHAVIOR(SceneSwitcher); } void InitEngine() { ofxCogEngine::GetInstance().SetFps(100); ofxCogEngine::GetInstance().Init(); ofxCogEngine::GetInstance().LoadStage(); } void InitStage(Stage* stage) { } }; int main() { ofSetupOpenGL(800, 450, OF_WINDOW); ofRunApp(new ExampleApp()); return 0; }
21.513889
82
0.701097
dodoknight
f1593e60eb478e7426da26ba59ec367786c7a7c7
18,733
cpp
C++
Source/AccelByteUe4Sdk/Private/Api/AccelByteEntitlementApi.cpp
leowind/accelbyte-unreal-sdk-plugin
73a7bf289abbba8141767eb16005aaf8293f8a63
[ "MIT" ]
null
null
null
Source/AccelByteUe4Sdk/Private/Api/AccelByteEntitlementApi.cpp
leowind/accelbyte-unreal-sdk-plugin
73a7bf289abbba8141767eb16005aaf8293f8a63
[ "MIT" ]
null
null
null
Source/AccelByteUe4Sdk/Private/Api/AccelByteEntitlementApi.cpp
leowind/accelbyte-unreal-sdk-plugin
73a7bf289abbba8141767eb16005aaf8293f8a63
[ "MIT" ]
null
null
null
// Copyright (c) 2018 - 2020 AccelByte Inc. All Rights Reserved. // This is licensed software from AccelByte Inc, for limitations // and restrictions contact your company contract manager. #include "Api/AccelByteEntitlementApi.h" #include "Core/AccelByteError.h" #include "Core/AccelByteRegistry.h" #include "Core/AccelByteReport.h" #include "Core/AccelByteHttpRetryScheduler.h" #include "JsonUtilities.h" #include "EngineMinimal.h" #include "Core/AccelByteSettings.h" namespace AccelByte { namespace Api { Entitlement::Entitlement(const AccelByte::Credentials& Credentials, const AccelByte::Settings& Setting) : Credentials(Credentials), Settings(Setting){} Entitlement::~Entitlement(){} void Entitlement::QueryUserEntitlements(const FString& EntitlementName, const FString& ItemId, const int32& Offset, const int32& Limit, const THandler<FAccelByteModelsEntitlementPagingSlicedResult>& OnSuccess, const FErrorHandler& OnError, EAccelByteEntitlementClass EntitlementClass = EAccelByteEntitlementClass::NONE, EAccelByteAppType AppType = EAccelByteAppType::NONE ) { FReport::Log(FString(__FUNCTION__)); FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken()); FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/users/%s/entitlements"), *Settings.PlatformServerUrl, *Credentials.GetNamespace(), *Credentials.GetUserId()); FString Query = TEXT(""); if (!EntitlementName.IsEmpty()) { Query.Append(Query.IsEmpty() ? TEXT("") : TEXT("&")); Query.Append(FString::Printf(TEXT("entitlementName=%s"), *EntitlementName)); } if (!ItemId.IsEmpty()) { Query.Append(Query.IsEmpty() ? TEXT("") : TEXT("&")); Query.Append(FString::Printf(TEXT("itemId=%s"), *ItemId)); } if (Offset>=0) { Query.Append(Query.IsEmpty() ? TEXT("") : TEXT("&")); Query.Append(FString::Printf(TEXT("offset=%d"), Offset)); } if (Limit>=0) { Query.Append(Query.IsEmpty() ? TEXT("") : TEXT("&")); Query.Append(FString::Printf(TEXT("limit=%d"), Limit)); } if (EntitlementClass != EAccelByteEntitlementClass::NONE) { Query.Append(Query.IsEmpty() ? TEXT("") : TEXT("&")); Query.Append(FString::Printf(TEXT("entitlementClazz=%s"), *FindObject<UEnum>(ANY_PACKAGE, TEXT("EAccelByteEntitlementClass"), true)->GetNameStringByValue((int32)EntitlementClass))); } if (AppType != EAccelByteAppType::NONE) { Query.Append(Query.IsEmpty() ? TEXT("") : TEXT("&")); Query.Append(FString::Printf(TEXT("appType=%s"), *FindObject<UEnum>(ANY_PACKAGE, TEXT("EAccelByteAppType"), true)->GetNameStringByValue((int32)AppType))); } Url.Append(Query.IsEmpty() ? TEXT("") : FString::Printf(TEXT("?%s"),*Query)); FString Verb = TEXT("GET"); FString ContentType = TEXT("application/json"); FString Accept = TEXT("application/json"); FString Content; FHttpRequestPtr Request = FHttpModule::Get().CreateRequest(); Request->SetURL(Url); Request->SetHeader(TEXT("Authorization"), Authorization); Request->SetVerb(Verb); Request->SetHeader(TEXT("Content-Type"), ContentType); Request->SetHeader(TEXT("Accept"), Accept); Request->SetContentAsString(Content); FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds()); } void Entitlement::QueryUserEntitlements(const FString& EntitlementName, const TArray<FString>& ItemIds, const int32& Offset, const int32& Limit, const THandler<FAccelByteModelsEntitlementPagingSlicedResult>& OnSuccess, const FErrorHandler& OnError, EAccelByteEntitlementClass EntitlementClass, EAccelByteAppType AppType) { FReport::Log(FString(__FUNCTION__)); FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken()); FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/users/%s/entitlements"), *Settings.PlatformServerUrl, *Credentials.GetNamespace(), *Credentials.GetUserId()); FString Query = TEXT(""); if (!EntitlementName.IsEmpty()) { Query.Append(Query.IsEmpty() ? TEXT("") : TEXT("&")); Query.Append(FString::Printf(TEXT("entitlementName=%s"), *EntitlementName)); } for (const FString& ItemId : ItemIds) { if (!ItemId.IsEmpty()) { Query.Append(Query.IsEmpty() ? TEXT("") : TEXT("&")); Query.Append(FString::Printf(TEXT("itemId=%s"), *ItemId)); } } if (Offset>=0) { Query.Append(Query.IsEmpty() ? TEXT("") : TEXT("&")); Query.Append(FString::Printf(TEXT("offset=%d"), Offset)); } if (Limit>=0) { Query.Append(Query.IsEmpty() ? TEXT("") : TEXT("&")); Query.Append(FString::Printf(TEXT("limit=%d"), Limit)); } if (EntitlementClass != EAccelByteEntitlementClass::NONE) { Query.Append(Query.IsEmpty() ? TEXT("") : TEXT("&")); Query.Append(FString::Printf(TEXT("entitlementClazz=%s"), *FindObject<UEnum>(ANY_PACKAGE, TEXT("EAccelByteEntitlementClass"), true)->GetNameStringByValue((int32)EntitlementClass))); } if (AppType != EAccelByteAppType::NONE) { Query.Append(Query.IsEmpty() ? TEXT("") : TEXT("&")); Query.Append(FString::Printf(TEXT("appType=%s"), *FindObject<UEnum>(ANY_PACKAGE, TEXT("EAccelByteAppType"), true)->GetNameStringByValue((int32)AppType))); } Url.Append(Query.IsEmpty() ? TEXT("") : FString::Printf(TEXT("?%s"),*Query)); FString Verb = TEXT("GET"); FString ContentType = TEXT("application/json"); FString Accept = TEXT("application/json"); FString Content; FHttpRequestPtr Request = FHttpModule::Get().CreateRequest(); Request->SetURL(Url); Request->SetHeader(TEXT("Authorization"), Authorization); Request->SetVerb(Verb); Request->SetHeader(TEXT("Content-Type"), ContentType); Request->SetHeader(TEXT("Accept"), Accept); Request->SetContentAsString(Content); FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds()); } void Entitlement::GetUserEntitlementById(const FString& Entitlementid, const THandler<FAccelByteModelsEntitlementInfo>& OnSuccess, const FErrorHandler& OnError) { FReport::Log(FString(__FUNCTION__)); FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken()); FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/users/%s/entitlements/%s"), *Settings.PlatformServerUrl, *Credentials.GetNamespace(), *Credentials.GetUserId(), *Entitlementid); FString Verb = TEXT("GET"); FString ContentType = TEXT("application/json"); FString Accept = TEXT("application/json"); FHttpRequestPtr Request = FHttpModule::Get().CreateRequest(); Request->SetURL(Url); Request->SetHeader(TEXT("Authorization"), Authorization); Request->SetVerb(Verb); Request->SetHeader(TEXT("Content-Type"), ContentType); Request->SetHeader(TEXT("Accept"), Accept); FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds()); } void Entitlement::GetUserEntitlementOwnershipByAppId(const FString& AppId, const THandler<FAccelByteModelsEntitlementOwnership>& OnSuccess, const FErrorHandler& OnError) { FReport::Log(FString(__FUNCTION__)); FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken()); FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/users/me/entitlements/ownership/byAppId?appId=%s"), *Settings.PlatformServerUrl, *Settings.PublisherNamespace, *AppId); FString Verb = TEXT("GET"); FString ContentType = TEXT("application/json"); FString Accept = TEXT("application/json"); FHttpRequestPtr Request = FHttpModule::Get().CreateRequest(); Request->SetURL(Url); Request->SetHeader(TEXT("Authorization"), Authorization); Request->SetVerb(Verb); Request->SetHeader(TEXT("Content-Type"), ContentType); Request->SetHeader(TEXT("Accept"), Accept); FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds()); } void Entitlement::GetUserEntitlementOwnershipBySku(const FString& Sku, const THandler<FAccelByteModelsEntitlementOwnership>& OnSuccess, const FErrorHandler& OnError) { FReport::Log(FString(__FUNCTION__)); FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken()); FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/users/me/entitlements/ownership/bySku?sku=%s"), *Settings.PlatformServerUrl, *Settings.PublisherNamespace, *Sku); FString Verb = TEXT("GET"); FString ContentType = TEXT("application/json"); FString Accept = TEXT("application/json"); FHttpRequestPtr Request = FHttpModule::Get().CreateRequest(); Request->SetURL(Url); Request->SetHeader(TEXT("Authorization"), Authorization); Request->SetVerb(Verb); Request->SetHeader(TEXT("Content-Type"), ContentType); Request->SetHeader(TEXT("Accept"), Accept); FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds()); } void Entitlement::GetUserEntitlementOwnershipAny(const TArray<FString> ItemIds, const TArray<FString> AppIds, const TArray<FString> Skus, const THandler<FAccelByteModelsEntitlementOwnership> OnSuccess, const FErrorHandler& OnError) { FReport::Log(FString(__FUNCTION__)); if (ItemIds.Num() < 1 && AppIds.Num() < 1 && Skus.Num() < 1) { OnError.ExecuteIfBound(EHttpResponseCodes::NotFound, TEXT("Please provide at least one itemId, AppId or Sku.")); } else { FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken()); FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/users/me/entitlements/ownership/any"), *Settings.PlatformServerUrl, *Settings.PublisherNamespace); int paramCount = 0; for (int i = 0; i < ItemIds.Num(); i++) { Url.Append((paramCount == 0) ? TEXT("?") : TEXT("&")).Append(TEXT("itemIds=")).Append(ItemIds[i]); paramCount++; } for (int i = 0; i < AppIds.Num(); i++) { Url.Append((paramCount == 0) ? TEXT("?") : TEXT("&")).Append(TEXT("appIds=")).Append(AppIds[i]); paramCount++; } for (int i = 0; i < Skus.Num(); i++) { Url.Append((paramCount == 0) ? TEXT("?") : TEXT("&")).Append(TEXT("skus=")).Append(Skus[i]); paramCount++; } FString Verb = TEXT("GET"); FString ContentType = TEXT("application/json"); FString Accept = TEXT("application/json"); FHttpRequestPtr Request = FHttpModule::Get().CreateRequest(); Request->SetURL(Url); Request->SetHeader(TEXT("Authorization"), Authorization); Request->SetVerb(Verb); Request->SetHeader(TEXT("Content-Type"), ContentType); Request->SetHeader(TEXT("Accept"), Accept); FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds()); } } void Entitlement::ConsumeUserEntitlement(const FString& EntitlementId, const int32& UseCount, const THandler<FAccelByteModelsEntitlementInfo>& OnSuccess, const FErrorHandler& OnError) { FReport::Log(FString(__FUNCTION__)); FAccelByteModelsConsumeUserEntitlementRequest ConsumeUserEntitlementRequest; ConsumeUserEntitlementRequest.UseCount = UseCount; FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken()); FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/users/%s/entitlements/%s/decrement"), *Settings.PlatformServerUrl, *Credentials.GetNamespace(), *Credentials.GetUserId(), *EntitlementId); FString Verb = TEXT("PUT"); FString ContentType = TEXT("application/json"); FString Accept = TEXT("application/json"); FString Content; FJsonObjectConverter::UStructToJsonObjectString(ConsumeUserEntitlementRequest, Content); FHttpRequestPtr Request = FHttpModule::Get().CreateRequest(); Request->SetURL(Url); Request->SetHeader(TEXT("Authorization"), Authorization); Request->SetVerb(Verb); Request->SetHeader(TEXT("Content-Type"), ContentType); Request->SetHeader(TEXT("Accept"), Accept); Request->SetContentAsString(Content); FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds()); } void Entitlement::CreateDistributionReceiver(const FString& ExtUserId, const FAccelByteModelsAttributes Attributes, const FVoidHandler& OnSuccess, const FErrorHandler& OnError) { FReport::Log(FString(__FUNCTION__)); FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken()); FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/users/%s/entitlements/receivers/%s"), *Settings.PlatformServerUrl, *Credentials.GetNamespace(), *Credentials.GetUserId(), *ExtUserId); FAccelByteModelsDistributionAttributes DistributionAttributes; DistributionAttributes.Attributes = Attributes; FString Verb = TEXT("POST"); FString ContentType = TEXT("application/json"); FString Accept = TEXT("application/json"); FString Content; FJsonObjectConverter::UStructToJsonObjectString(DistributionAttributes, Content); FHttpRequestPtr Request = FHttpModule::Get().CreateRequest(); Request->SetURL(Url); Request->SetHeader(TEXT("Authorization"), Authorization); Request->SetVerb(Verb); Request->SetHeader(TEXT("Content-Type"), ContentType); Request->SetHeader(TEXT("Accept"), Accept); Request->SetContentAsString(Content); FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds()); } void Entitlement::DeleteDistributionReceiver(const FString& ExtUserId, const FString& UserId, const FVoidHandler& OnSuccess, const FErrorHandler& OnError) { FReport::Log(FString(__FUNCTION__)); FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken()); FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/users/%s/entitlements/receivers/%s"), *Settings.PlatformServerUrl, *Credentials.GetNamespace(), *UserId, *ExtUserId); FString Verb = TEXT("DELETE"); FString ContentType = TEXT("application/json"); FString Accept = TEXT("application/json"); FHttpRequestPtr Request = FHttpModule::Get().CreateRequest(); Request->SetURL(Url); Request->SetHeader(TEXT("Authorization"), Authorization); Request->SetVerb(Verb); Request->SetHeader(TEXT("Content-Type"), ContentType); Request->SetHeader(TEXT("Accept"), Accept); FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds()); } void Entitlement::GetDistributionReceiver(const FString& PublisherNamespace, const FString& PublisherUserId, const THandler<TArray<FAccelByteModelsDistributionReceiver>>& OnSuccess, const FErrorHandler& OnError) { FReport::Log(FString(__FUNCTION__)); FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken()); FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/users/%s/entitlements/receivers"), *Settings.PlatformServerUrl, *PublisherNamespace, *PublisherUserId); FString Query = TEXT(""); if (!Credentials.GetNamespace().IsEmpty()) { Query.Append(Query.IsEmpty() ? TEXT("") : TEXT("&")); Query.Append(FString::Printf(TEXT("targetNamespace=%s"), *Credentials.GetNamespace())); } Url.Append(Query.IsEmpty() ? TEXT("") : FString::Printf(TEXT("?%s"),*Query)); FString Verb = TEXT("GET"); FString ContentType = TEXT("application/json"); FString Accept = TEXT("application/json"); FHttpRequestPtr Request = FHttpModule::Get().CreateRequest(); Request->SetURL(Url); Request->SetHeader(TEXT("Authorization"), Authorization); Request->SetVerb(Verb); Request->SetHeader(TEXT("Content-Type"), ContentType); Request->SetHeader(TEXT("Accept"), Accept); FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds()); } void Entitlement::UpdateDistributionReceiver(const FString& ExtUserId, const FAccelByteModelsAttributes Attributes, const FVoidHandler& OnSuccess, const FErrorHandler& OnError) { FReport::Log(FString(__FUNCTION__)); FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken()); FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/users/%s/entitlements/receivers/%s"), *Settings.PlatformServerUrl, *Credentials.GetNamespace(), *Credentials.GetUserId(), *ExtUserId); FAccelByteModelsDistributionAttributes DistributionAttributes; DistributionAttributes.Attributes = Attributes; FString Verb = TEXT("PUT"); FString ContentType = TEXT("application/json"); FString Accept = TEXT("application/json"); FString Content; FJsonObjectConverter::UStructToJsonObjectString(DistributionAttributes, Content); FHttpRequestPtr Request = FHttpModule::Get().CreateRequest(); Request->SetURL(Url); Request->SetHeader(TEXT("Authorization"), Authorization); Request->SetVerb(Verb); Request->SetHeader(TEXT("Content-Type"), ContentType); Request->SetHeader(TEXT("Accept"), Accept); Request->SetContentAsString(Content); FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds()); } void Entitlement::SyncPlatformPurchase(EAccelBytePlatformSync PlatformType, const FVoidHandler& OnSuccess, const FErrorHandler& OnError) { FReport::Log(FString(__FUNCTION__)); FString PlatformText = TEXT(""); FString Content = TEXT("{}"); FString platformUserId = Credentials.GetPlatformUserId(); switch (PlatformType) { case EAccelBytePlatformSync::STEAM: PlatformText = TEXT("steam"); if (platformUserId.IsEmpty()) { OnError.ExecuteIfBound(static_cast<int32>(ErrorCodes::IsNotLoggedIn), TEXT("User not logged in with 3rd Party Platform")); return; } Content = FString::Printf(TEXT("{\"steamId\": \"%s\", \"appId\": %s}"), *Credentials.GetPlatformUserId(), *Settings.AppId); break; case EAccelBytePlatformSync::XBOX_LIVE: PlatformText = TEXT("xbl"); break; case EAccelBytePlatformSync::PLAYSTATION: PlatformText = TEXT("psn"); break; default: OnError.ExecuteIfBound(static_cast<int32>(ErrorCodes::InvalidRequest), TEXT("Platform Sync Type is not found")); return; } FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken()); FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/users/%s/iap/%s/sync"), *Settings.PlatformServerUrl, *Credentials.GetNamespace(), *Credentials.GetUserId(), *PlatformText); FString Verb = TEXT("PUT"); FString ContentType = TEXT("application/json"); FString Accept = TEXT("application/json"); FHttpRequestPtr Request = FHttpModule::Get().CreateRequest(); Request->SetURL(Url); Request->SetHeader(TEXT("Authorization"), Authorization); Request->SetVerb(Verb); Request->SetHeader(TEXT("Content-Type"), ContentType); Request->SetHeader(TEXT("Accept"), Accept); Request->SetContentAsString(Content); FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds()); } } // Namespace Api }
43.363426
373
0.746917
leowind
f1598a41dbce24d7e5924bfd644a22825be54e6d
5,663
cpp
C++
src/core/analyzer/StandardTokenizer.cpp
SRCH2/srch2-ngn
925f36971aa6a8b31cdc59f7992790169e97ee00
[ "BSD-3-Clause" ]
14
2016-01-15T20:26:54.000Z
2018-11-26T20:47:43.000Z
src/core/analyzer/StandardTokenizer.cpp
SRCH2/srch2-ngn
925f36971aa6a8b31cdc59f7992790169e97ee00
[ "BSD-3-Clause" ]
2
2016-04-26T05:29:01.000Z
2016-05-07T00:13:38.000Z
src/core/analyzer/StandardTokenizer.cpp
SRCH2/srch2-ngn
925f36971aa6a8b31cdc59f7992790169e97ee00
[ "BSD-3-Clause" ]
7
2016-02-27T11:35:59.000Z
2018-11-26T20:47:59.000Z
/* * Copyright (c) 2016, SRCH2 * 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 SRCH2 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 SRCH2 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. */ /* * StandardTokenizer.cpp * * Created on: 2013-5-17 */ #include <iostream> #include "StandardTokenizer.h" #include "util/Assert.h" namespace srch2 { namespace instantsearch { StandardTokenizer::StandardTokenizer() :Tokenizer() {} bool StandardTokenizer::incrementToken() { (tokenStreamContainer->currentToken).clear(); // CharOffset starts from 1. tokenStreamContainer->currentTokenOffset = tokenStreamContainer->offset + 1; CharType previousChar = (CharType) ' '; //originally, set the previous character is ' '; while (true) { ///check whether the scanning is over. if ((tokenStreamContainer->offset) >= (tokenStreamContainer->completeCharVector).size()) { if (tokenStreamContainer->currentToken.empty()) { return false; } else { tokenStreamContainer->currentTokenPosition++; return true; } } CharType currentChar = (tokenStreamContainer->completeCharVector)[tokenStreamContainer->offset]; if ((tokenStreamContainer->offset) - 1 >= 0) //check whether the previous character exists. { previousChar = (tokenStreamContainer->completeCharVector)[(tokenStreamContainer->offset) - 1]; } (tokenStreamContainer->offset)++; ///we need combine previous character and current character to decide a word unsigned previousCharacterType = characterSet.getCharacterType(previousChar); unsigned currentCharacterType = characterSet.getCharacterType(currentChar); switch (currentCharacterType) { case CharSet::WHITESPACE: if (!(tokenStreamContainer->currentToken).empty()) { tokenStreamContainer->currentTokenPosition++; return true; } tokenStreamContainer->currentTokenOffset++; break; case CharSet::LATIN_TYPE: case CharSet::BOPOMOFO_TYPE: case CharSet::DELIMITER_TYPE: //check if the types of previous character and current character are the same if (previousCharacterType == currentCharacterType) { (tokenStreamContainer->currentToken).push_back(currentChar); } else if (previousCharacterType == CharSet::DELIMITER_TYPE || currentCharacterType == CharSet::DELIMITER_TYPE) { /* * delimiters will go with both LATIN and BOPPMOFO types. * e.g for C++ C is Latin type and + is Delimiter type. We do not want to split * them into to C and ++. * * We also do not want to tokenize "c+b" because NonalphaNumericFilter will tokenize * it later. */ (tokenStreamContainer->currentToken).push_back(currentChar); }else { if (!(tokenStreamContainer->currentToken).empty()) //if the currentToken is not null, we need produce the token { (tokenStreamContainer->offset)--; tokenStreamContainer->currentTokenPosition++; return true; } else (tokenStreamContainer->currentToken).push_back(currentChar); } break; default: //other character type if (!(tokenStreamContainer->currentToken).empty()) { (tokenStreamContainer->offset)--; } else { (tokenStreamContainer->currentToken).push_back(currentChar); } if (tokenStreamContainer->currentToken.empty()) { return false; } else { tokenStreamContainer->currentTokenPosition++; return true; } } } ASSERT(false); return false; } bool StandardTokenizer::processToken() { tokenStreamContainer->type = ANALYZED_ORIGINAL_TOKEN; return this->incrementToken(); } StandardTokenizer::~StandardTokenizer() { // TODO Auto-generated destructor stub } } }
41.036232
127
0.640473
SRCH2
f15dfc458f630348f1f54efe4cc1c3112c668762
3,125
cpp
C++
src/Lib/Messaging/Message.cpp
gravitationalwavedc/gwcloud_job_server
fb96ed1dc6baa240d1a38ac1adcd246577285294
[ "MIT" ]
null
null
null
src/Lib/Messaging/Message.cpp
gravitationalwavedc/gwcloud_job_server
fb96ed1dc6baa240d1a38ac1adcd246577285294
[ "MIT" ]
8
2020-06-06T08:39:37.000Z
2021-09-22T18:01:47.000Z
src/Lib/Messaging/Message.cpp
gravitationalwavedc/gwcloud_job_server
fb96ed1dc6baa240d1a38ac1adcd246577285294
[ "MIT" ]
null
null
null
// // Created by lewis on 2/26/20. // #include "Message.h" #include <utility> #include "../../Cluster/Cluster.h" using namespace std; #ifdef BUILD_TESTS Message::Message(uint32_t msgId) { // Constructor only used for testing // Resize the data array to 64kb data.reserve(1024 * 64); // Reset the index index = 0; // Store the id id = msgId; } #endif Message::Message(uint32_t msgId, Message::Priority priority, const std::string& source) { // Resize the data array to 64kb data.reserve(1024 * 64); // Reset the index index = 0; // Set the priority this->priority = priority; // Set the source this->source = source; // Push the source push_string(source); // Push the id push_uint(msgId); } Message::Message(const vector<uint8_t>& vdata) { data = vdata; index = 0; priority = Message::Priority::Lowest; source = pop_string(); id = pop_uint(); } void Message::push_bool(bool v) { push_ubyte(v ? 1 : 0); } bool Message::pop_bool() { auto result = pop_ubyte(); return result == 1; } void Message::push_ubyte(uint8_t v) { data.push_back(v); } uint8_t Message::pop_ubyte() { auto result = data[index++]; return result; } void Message::push_byte(int8_t v) { push_ubyte((uint8_t) v); } int8_t Message::pop_byte() { return (int8_t) pop_ubyte(); } #define push_type(t, r) void Message::push_##t (r v) { \ uint8_t pdata[sizeof(v)]; \ \ *((typeof(v)*) &pdata) = v; \ \ for (unsigned char i : pdata) \ push_ubyte(i); \ } #define pop_type(t, r) r Message::pop_##t() { \ uint8_t pdata[sizeof(r)]; \ \ for (auto i = 0; i < sizeof(r); i++) \ pdata[i] = pop_ubyte(); \ \ return *(r*) &pdata; \ } #define add_type(t, r) push_type(t, r) pop_type(t, r) add_type(ushort, uint16_t) add_type(short, int16_t) add_type(uint, uint32_t) add_type(int, int32_t) add_type(ulong, uint64_t) add_type(long, int64_t) add_type(float, float) add_type(double, double) void Message::push_string(const std::string& v) { push_ulong(v.size()); data.insert(data.end(), v.begin(), v.end()); } std::string Message::pop_string() { auto result = pop_bytes(); // Write string terminator result.push_back(0); return std::string((char *) result.data()); } void Message::push_bytes(const std::vector<uint8_t>& v) { push_ulong(v.size()); data.insert(data.end(), v.begin(), v.end()); } std::vector<uint8_t> Message::pop_bytes() { auto len = pop_ulong(); auto result = std::vector<uint8_t>(&data[index], &data[index] + len); index += len; return result; } void Message::send(Cluster* pCluster) { pCluster->queueMessage(source, &data, priority); }
21.258503
89
0.54848
gravitationalwavedc
f15f88b741604ccfffcee89d8b457a4d06de6c7f
949
cpp
C++
src/logic/role/role_manager.cpp
lanhuanjun/game_server
64fb7ca39db776fa9471f4c71a76c31759ace7a4
[ "MIT" ]
null
null
null
src/logic/role/role_manager.cpp
lanhuanjun/game_server
64fb7ca39db776fa9471f4c71a76c31759ace7a4
[ "MIT" ]
1
2020-01-15T12:46:05.000Z
2020-01-15T12:46:05.000Z
src/logic/role/role_manager.cpp
lanhuanjun/game_server
64fb7ca39db776fa9471f4c71a76c31759ace7a4
[ "MIT" ]
null
null
null
#include "role_manager.h" #include "role_rmi.h" #include <third-party/coroutine/gs_co.h> #include <core/tools/gs_random.h> MNG_IMPL(role, IRoleManager, CRoleManager) CRoleManager::CRoleManager() : m_last_call(0) { } CRoleManager::~CRoleManager() { } void CRoleManager::Init() { } void CRoleManager::Update() { if (svc_run_msec() - m_last_call > 1000) { m_last_call = svc_run_msec(); START_TASK(&CRoleManager::TestCall, this); } } void CRoleManager::TestCall() { Rmi<IRoleManager> svc_lobby(__ANY_LOBBY__); int32_t a = gs::rand(1, 1000); int32_t b = gs::rand(1, 1000); int32_t res = svc_lobby.RmiTest_Add(a, b); LOG(INFO) << a << " + " << b << " = " << res; if (rmi_last_err() != RMI_CODE_OK) { rmi_clear_err(); } } void CRoleManager::Destroy() { } int CRoleManager::RmiTest_Add(int a, int b) { LOG(INFO) << "call: a:" << a << " b:" << b; return a + b; }
19.367347
50
0.610116
lanhuanjun
f161a296a2b14adc45ae38221a97574055384874
1,449
hpp
C++
ufora/BackendGateway/ComputedGraph/Typedefs.hpp
ufora/ufora
04db96ab049b8499d6d6526445f4f9857f1b6c7e
[ "Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause" ]
571
2015-11-05T20:07:07.000Z
2022-01-24T22:31:09.000Z
ufora/BackendGateway/ComputedGraph/Typedefs.hpp
timgates42/ufora
04db96ab049b8499d6d6526445f4f9857f1b6c7e
[ "Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause" ]
218
2015-11-05T20:37:55.000Z
2021-05-30T03:53:50.000Z
ufora/BackendGateway/ComputedGraph/Typedefs.hpp
timgates42/ufora
04db96ab049b8499d6d6526445f4f9857f1b6c7e
[ "Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause" ]
40
2015-11-07T21:42:19.000Z
2021-05-23T03:48:19.000Z
/*************************************************************************** Copyright 2015 Ufora 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. ****************************************************************************/ #pragma once #include "../../FORA/Core/Type.hppml" #include "../../core/PolymorphicSharedPtr.hpp" #include <boost/python.hpp> #include <map> #include <string> #define COMPUTED_GRAPH_TIMING 1 namespace ComputedGraph { typedef boost::python::list py_list; typedef unsigned long id_type; typedef std::pair<id_type, id_type> class_id_type; typedef enum { attrKey, attrMutable, attrProperty, attrFunction, attrNotCached, attrClassAttribute, attrUnknown } attr_type; class Graph; class Location; class LocationProperty; class Root; class LocationType; class PropertyStorage; class InstanceStorage; typedef PolymorphicSharedPtr<Root> RootPtr; typedef PolymorphicSharedWeakPtr<Root> WeakRootPtr; }
23.370968
77
0.6853
ufora
f1656e7e7093214be79d698b5e333ad40b8117f4
858
cpp
C++
Quasics2017Code/Nike/src/Commands/Lights/SetLightColor.cpp
quasics/quasics-frc-sw-2015
e5a4f1b4e209ba941f12c2cc41759854f3c5420b
[ "BSD-3-Clause" ]
5
2016-12-16T19:05:05.000Z
2021-03-05T01:23:27.000Z
Quasics2017Code/Nike-2018/src/Commands/Lights/SetLightColor.cpp
quasics/quasics-frc-sw-2015
e5a4f1b4e209ba941f12c2cc41759854f3c5420b
[ "BSD-3-Clause" ]
null
null
null
Quasics2017Code/Nike-2018/src/Commands/Lights/SetLightColor.cpp
quasics/quasics-frc-sw-2015
e5a4f1b4e209ba941f12c2cc41759854f3c5420b
[ "BSD-3-Clause" ]
2
2020-01-03T01:52:43.000Z
2022-02-02T01:23:45.000Z
#include "SetLightColor.h" SetLightColor::SetLightColor(ArduinoController::ColorMode colorMode) { // Use Requires() here to declare subsystem dependencies // eg. Requires(Robot::chassis.get()); Requires(Robot::arduinoController.get()); kColorMode = colorMode; } // Called just before this Command runs the first time void SetLightColor::Initialize() { Robot::arduinoController->SetLightColor(kColorMode); } // Called repeatedly when this Command is scheduled to run void SetLightColor::Execute() { } // Make this return true when this Command no longer needs to run execute() bool SetLightColor::IsFinished() { return true; } // Called once after isFinished returns true void SetLightColor::End() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run void SetLightColor::Interrupted() { }
24.514286
75
0.757576
quasics
f166428d95194f06fca58d2691a7c5a2a98b55c8
243
cpp
C++
main.cpp
Milerius/make_ui_great_again
c00ae4c5aab5d23ef7db1fe2052786ea57c580f4
[ "MIT" ]
1
2019-12-22T16:57:13.000Z
2019-12-22T16:57:13.000Z
main.cpp
Milerius/make_ui_great_again
c00ae4c5aab5d23ef7db1fe2052786ea57c580f4
[ "MIT" ]
null
null
null
main.cpp
Milerius/make_ui_great_again
c00ae4c5aab5d23ef7db1fe2052786ea57c580f4
[ "MIT" ]
null
null
null
// // Created by Roman Szterg on 18/12/2019. // #include "ui.wrapper.hpp" int main() { antara_gui gui("example", 200, 200); while (not gui.is_close()) { gui.pre_update(); gui.show_demo(); gui.update(); } }
16.2
41
0.555556
Milerius
f16775511f36e93433292026986065f31f690529
1,683
hpp
C++
lib/fizzy/leb128.hpp
imapp-pl/fizzy
69e154ad7b910809f2219839d328b93168020135
[ "Apache-2.0" ]
null
null
null
lib/fizzy/leb128.hpp
imapp-pl/fizzy
69e154ad7b910809f2219839d328b93168020135
[ "Apache-2.0" ]
null
null
null
lib/fizzy/leb128.hpp
imapp-pl/fizzy
69e154ad7b910809f2219839d328b93168020135
[ "Apache-2.0" ]
null
null
null
#pragma once #include "types.hpp" #include <cstdint> #include <stdexcept> namespace fizzy { template <typename T> std::pair<T, const uint8_t*> leb128u_decode(const uint8_t* input) { static_assert(!std::numeric_limits<T>::is_signed); T result = 0; int result_shift = 0; for (; result_shift < std::numeric_limits<T>::digits; ++input, result_shift += 7) { // TODO this ignores the bits in the last byte other than the least significant one // So would not reject some invalid encoding with those bits set. result |= static_cast<T>((static_cast<T>(*input) & 0x7F) << result_shift); if ((*input & 0x80) == 0) return {result, input + 1}; } throw std::runtime_error("Invalid LEB128 encoding: too many bytes."); } template <typename T> std::pair<T, const uint8_t*> leb128s_decode(const uint8_t* input) { static_assert(std::numeric_limits<T>::is_signed); using T_unsigned = typename std::make_unsigned<T>::type; T_unsigned result = 0; int result_shift = 0; for (; result_shift < std::numeric_limits<T_unsigned>::digits; ++input, result_shift += 7) { result |= static_cast<T_unsigned>((static_cast<T_unsigned>(*input) & 0x7F) << result_shift); if ((*input & 0x80) == 0) { // sign extend if ((*input & 0x40) != 0) { auto const mask = static_cast<T_unsigned>(~T_unsigned{0} << (result_shift + 7)); result |= mask; } return {static_cast<T>(result), input + 1}; } } throw std::runtime_error("Invalid LEB128 encoding: too many bytes."); } } // namespace fizzy
30.053571
100
0.612002
imapp-pl
f167c1efcef212b5f08300085e2c43bcc7d477af
329
hpp
C++
cpp/include/cg3/common/test_scenes.hpp
tychota/cg3-path-tracer
548519121cacb01a4be835c0bece21238b56f92b
[ "Beerware" ]
null
null
null
cpp/include/cg3/common/test_scenes.hpp
tychota/cg3-path-tracer
548519121cacb01a4be835c0bece21238b56f92b
[ "Beerware" ]
null
null
null
cpp/include/cg3/common/test_scenes.hpp
tychota/cg3-path-tracer
548519121cacb01a4be835c0bece21238b56f92b
[ "Beerware" ]
null
null
null
# pragma once # include "cg3/common/scene.hpp" # include <memory> std::shared_ptr< Scene > create_rt_test_scene( tiny_vec< size_t, 2 > resolution ); std::shared_ptr< Scene > create_pt_test_scene( tiny_vec< size_t, 2 > resolution ); std::shared_ptr< Scene > create_cornell_box_test_scene( tiny_vec< size_t, 2 > resolution );
27.416667
91
0.744681
tychota
f167c309a65dcaef7f40a57b865f68687cdcdfc5
8,673
cpp
C++
test/posix/integration/stat/stat_tests.cpp
jaeh/IncludeOS
1cc2bcf36758ff5ef3099e0c0c1ee55f0bb1de02
[ "Apache-2.0" ]
3,673
2015-12-01T22:14:02.000Z
2019-03-22T03:07:20.000Z
test/posix/integration/stat/stat_tests.cpp
jaeh/IncludeOS
1cc2bcf36758ff5ef3099e0c0c1ee55f0bb1de02
[ "Apache-2.0" ]
960
2015-12-01T20:40:36.000Z
2019-03-22T13:21:21.000Z
test/posix/integration/stat/stat_tests.cpp
AndreasAakesson/IncludeOS
891b960a0a7473c08cd0d93a2bba7569c6d88b48
[ "Apache-2.0" ]
357
2015-12-02T09:32:50.000Z
2019-03-22T09:32:34.000Z
#include <service> #include <info> #include <cassert> #define __SPU__ #include <sys/stat.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> #include <fcntl.h> void print_stat(struct stat buffer); void stat_tests() { int res; char* nullbuf = nullptr; char shortbuf[4]; char buf[1024]; struct stat buffer; res = stat("folder1", nullptr); printf("stat("") with nullptr result: %d\n", res); if (res == -1) { printf("stat error: %s\n", strerror(errno)); } else { print_stat(buffer); } CHECKSERT(res == -1 && errno == EFAULT, "stat() with nullptr buffer fails with EFAULT"); res = stat("/mnt/disk/folder1", &buffer); printf("stat(\"folder1\") result: %d\n", res); if (res == -1) { printf("stat error: %s\n", strerror(errno)); } else { print_stat(buffer); } CHECKSERT(res == 0, "stat() of folder that exists is ok"); res = stat("/mnt/disk/file1", &buffer); printf("stat(\"file1\") result: %d\n", res); if (res == -1) { printf("stat error: %s\n", strerror(errno)); } else { print_stat(buffer); } CHECKSERT(res == 0, "stat() of file that exists is ok"); res = stat("folder666", &buffer); printf("stat(\"folder1\") result: %d\n", res); if (res == -1) { printf("stat error: %s\n", strerror(errno)); } else { print_stat(buffer); } CHECKSERT(res == -1, "stat() of folder that does not exist fails"); res = stat("file666", &buffer); printf("stat(\"file666\") result: %d\n", res); if (res == -1) { printf("stat error: %s\n", strerror(errno)); } else { print_stat(buffer); } CHECKSERT(res == -1, "stat() of file that does not exist fails"); res = chdir(nullptr); printf("chdir result (to nullptr): %d\n", res); if (res == -1) { printf("chdir error: %s\n", strerror(errno)); } CHECKSERT(res == -1, "chdir(nullptr) should fail"); res = chdir(""); printf("chdir result (to empty string): %d\n", res); if (res == -1) { printf("chdir error: %s\n", strerror(errno)); } CHECKSERT(res == -1, "chdir(\"\") should fail"); res = chdir("file2"); printf("chdir result (not a folder): %d\n", res); if (res == -1) { printf("chdir error: %s\n", strerror(errno)); } CHECKSERT(res == -1, "chdir() to a file should fail"); res = chdir("/mnt/disk/folder1"); printf("chdir result (existing folder): %d\n", res); if (res == -1) { printf("chdir error: %s\n", strerror(errno)); } CHECKSERT(res == 0, "chdir (absolute) to folder that exists is ok"); printf("changing dir\n"); res = chdir("/mnt/disk/folder1"); printf("chdir res: %d\n", res); res = fstatat(AT_FDCWD, "file1", &buffer, 0); printf("fstatat(\"file1\") result: %d\n", res); if (res == -1) { printf("fstatat error: %s\n", strerror(errno)); } else { print_stat(buffer); } CHECKSERT(res == 0, "fstatat() of file that exists is ok"); res = chdir("/folder1"); printf("chdir result (existing folder, absolute): %d\n", res); if (res == -1) { printf("chdir error: %s\n", strerror(errno)); } res = chdir("."); printf("chdir result (to \".\"): %d\n", res); if (res == -1) { printf("chdir error: %s\n", strerror(errno)); } CHECKSERT(res == 0, "chdir(\".\") is ok"); res = chdir("foldera"); printf("chdir result (to subfolder of cwd): %d\n", res); if (res == -1) { printf("chdir error: %s\n", strerror(errno)); } CHECKSERT(res == 0, "chdir to subfolder of cwd is ok"); /** If buf is a null pointer, the behavior of getcwd() is unspecified. http://pubs.opengroup.org/onlinepubs/9699919799/functions/getcwd.html Changed behavior of getcwd to Expect buf isn't nullptr. TODO: It's nice to have these test cases in there, but it will require the test to throw on contract violation **/ /** char* nullcwd = getcwd(nullbuf, 0); printf("getcwd result (nullptr, size 0): %s\n", nullcwd == nullptr ? "NULL" : nullcwd); if (nullcwd == nullptr) { printf("getcwd error: %s\n", strerror(errno)); } CHECKSERT(nullcwd == nullptr && errno == EINVAL, "getcwd() with 0-size buffer should fail with EINVAL"); nullcwd = getcwd(nullptr, 1024); printf("getcwd result (nullptr): %s\n", nullcwd == nullptr ? "NULL" : nullcwd); if (nullcwd == nullptr) { printf("getcwd error: %s\n", strerror(errno)); } CHECKSERT(nullcwd == nullptr, "getcwd() with nullptr buffer should fail"); **/ char* shortcwd = getcwd(shortbuf, 4); printf("getcwd result (small buffer): %s\n", shortcwd == nullptr ? "NULL" : shortcwd); if (shortcwd == nullptr) { printf("getcwd error: %s\n", strerror(errno)); } CHECKSERT(shortcwd == nullptr && errno == ERANGE, "getcwd() with too small buffer should fail with ERANGE"); char* cwd = getcwd(buf, 1024); printf("getcwd result (adequate buffer): %s\n", cwd); if (cwd == nullptr) { printf("getcwd error: %s\n", strerror(errno)); } CHECKSERT(cwd, "getcwd() with adequate buffer is ok"); res = chmod("/dev/null", S_IRUSR); printf("chmod result: %d\n", res); if (res == -1) { printf("chmod error: %s\n", strerror(errno)); } CHECKSERT(res == -1, "chmod() should fail on read-only memdisk"); int fd = STDOUT_FILENO; close(fd); res = fchmod(fd, S_IWUSR); printf("fchmod result: %d\n", res); if (res == -1) { printf("fchmod error: %s\n", strerror(errno)); } CHECKSERT(res == -1, "fchmod() on non-open FD should fail"); res = fchmodat(fd, "test", S_IRUSR, AT_SYMLINK_NOFOLLOW); printf("fchmodat result: %d\n", res); if (res == -1) { printf("fchmodat error: %s\n", strerror(errno)); } CHECKSERT(res == -1, "fchmodat() on non-open FD should fail"); res = fstat(fd, &buffer); printf("fstat result: %d\n", res); if (res == -1) { printf("fstat error: %s\n", strerror(errno)); } res = fstatat(fd, "test", &buffer, AT_SYMLINK_NOFOLLOW); printf("fstatat result: %d\n", res); if (res == -1) { printf("fstatat error: %s\n", strerror(errno)); } CHECKSERT(res == -1, "fstatat() on non-open FD should fail"); res = futimens(fd, nullptr); printf("futimens result: %d\n", res); if (res == -1) { printf("futimens error: %s\n", strerror(errno)); } CHECKSERT(res == -1, "futimens() on non-open FD should fail"); res = utimensat(fd, "test", nullptr, AT_SYMLINK_NOFOLLOW); printf("utimensat result: %d\n", res); if (res == -1) { printf("utimensat error: %s\n", strerror(errno)); } CHECKSERT(res == -1, "utimensat() on non-open FD should fail"); /* res = lstat("/", &buffer); printf("lstat result: %d\n", res); if (res == -1) { printf("lstat error: %s\n", strerror(errno)); } */ res = mkdir("/dev/sda1/root", S_IWUSR); printf("mkdir result: %d\n", res); if (res == -1) { printf("mkdir error: %s\n", strerror(errno)); } CHECKSERT(res == -1, "mkdir() on read-only memdisk should fail"); res = mkdirat(fd, "root", S_IWUSR); printf("mkdirat result: %d\n", res); if (res == -1) { printf("mkdirat error: %s\n", strerror(errno)); } CHECKSERT(res == -1, "mkdirat() on non-open FD should fail"); res = mkfifo("/FILE_FIFO", S_IWUSR); printf("mkfifo result: %d\n", res); if (res == -1) { printf("mkfifo error: %s\n", strerror(errno)); } CHECKSERT(res == -1, "mkfifo() on read-only memdisk should fail"); res = mkfifoat(AT_FDCWD, "test", S_IWUSR); printf("mkfifoat result: %d\n", res); if (res == -1) { printf("mkfifoat error: %s\n", strerror(errno)); } CHECKSERT(res == -1, "mkfifoat() on non-open FD should fail"); /* res = mknod("/dev/null", S_IWUSR, 0); printf("mknod result: %d\n", res); if (res == -1) { printf("mknod error: %s\n", strerror(errno)); } */ res = mknodat(AT_FDCWD, "test", S_IWUSR, 0); printf("mknodat result: %d\n", res); if (res == -1) { printf("mknodat error: %s\n", strerror(errno)); } CHECKSERT(res == -1, "mknodat() on non-open FD should fail"); mode_t old_umask = umask(0); printf("Old umask: %d\n", old_umask); } void print_stat(struct stat buffer) { printf("st_dev: %d\n", buffer.st_dev); printf("st_ino: %hu\n", buffer.st_ino); printf("st_mode: %d\n", buffer.st_mode); printf("st_nlink: %d\n", buffer.st_nlink); printf("st_uid: %d\n", buffer.st_uid); printf("st_gid: %d\n", buffer.st_gid); printf("st_rdev: %d\n", buffer.st_rdev); printf("st_size: %ld\n", buffer.st_size); printf("st_atime: %ld\n", buffer.st_atime); printf("st_ctime: %ld\n", buffer.st_ctime); printf("st_mtime: %ld\n", buffer.st_mtime); printf("st_blksize: %ld\n", buffer.st_blksize); printf("st_blocks: %ld\n", buffer.st_blocks); }
26.851393
110
0.597717
jaeh
f167c38e4e81c73098fe1565099d4de20e0a5d9d
1,828
cpp
C++
src/mupnp/device/ST.cpp
cybergarage/CyberLink4CC
ccbda234b920ec88a36392102c1d5247c074a734
[ "BSD-3-Clause" ]
null
null
null
src/mupnp/device/ST.cpp
cybergarage/CyberLink4CC
ccbda234b920ec88a36392102c1d5247c074a734
[ "BSD-3-Clause" ]
null
null
null
src/mupnp/device/ST.cpp
cybergarage/CyberLink4CC
ccbda234b920ec88a36392102c1d5247c074a734
[ "BSD-3-Clause" ]
null
null
null
/****************************************************************** * * mUPnP for C++ * * Copyright (C) Satoshi Konno 2002 * * This is licensed under BSD-style license, see file COPYING. * ******************************************************************/ #include <mupnp/device/ST.h> #include <uhttp/util/StringUtil.h> using namespace std; using namespace uHTTP; bool mUPnP::ST::IsAllDevice(const std::string &value) { String valStr = value; if (valStr.equals(ALL_DEVICE) == true) return true; string quoteStr; quoteStr.append("\""); quoteStr.append(ALL_DEVICE); quoteStr.append("\""); return valStr.equals(quoteStr.c_str()); } bool mUPnP::ST::IsRootDevice(const std::string &value) { String valStr = value; if (valStr.equals(ROOT_DEVICE) == true) return true; string quoteStr; quoteStr.append("\""); quoteStr.append(ROOT_DEVICE); quoteStr.append("\""); return valStr.equals(quoteStr.c_str()); } bool mUPnP::ST::IsUUIDDevice(const std::string &value) { String valStr = value; if (valStr.startsWith(UUID_DEVICE) == true) return true; string quoteStr; quoteStr.append("\""); quoteStr.append(UUID_DEVICE); quoteStr.append("\""); return valStr.startsWith(quoteStr.c_str()); } bool mUPnP::ST::IsURNDevice(const std::string &value) { String valStr = value; if (valStr.startsWith(URN_DEVICE) == true) return true; string quoteStr; quoteStr.append("\""); quoteStr.append(URN_DEVICE); quoteStr.append("\""); return valStr.startsWith(quoteStr.c_str()); } bool mUPnP::ST::IsURNService(const std::string &value) { String valStr = value; if (valStr.startsWith(URN_SERVICE) == true) return true; string quoteStr; quoteStr.append("\""); quoteStr.append(URN_SERVICE); quoteStr.append("\""); return valStr.startsWith(quoteStr.c_str()); }
25.746479
68
0.637309
cybergarage
f16c2bc9b7aa5f81849334c7d7ca60f6aff3567a
13,729
cpp
C++
testMultiplePutGet/src/pvaPutGetSleep.cpp
mrkraimer/testClientCPP
2d1608678e173bd36bbf34fe64b4182b00ba4074
[ "MIT" ]
null
null
null
testMultiplePutGet/src/pvaPutGetSleep.cpp
mrkraimer/testClientCPP
2d1608678e173bd36bbf34fe64b4182b00ba4074
[ "MIT" ]
null
null
null
testMultiplePutGet/src/pvaPutGetSleep.cpp
mrkraimer/testClientCPP
2d1608678e173bd36bbf34fe64b4182b00ba4074
[ "MIT" ]
null
null
null
/* * Copyright information and license terms for this software can be * found in the file LICENSE that is included with the distribution */ /** * @author Marty Kraimer * @date 2021.02 */ #include <iostream> #include <time.h> #include <unistd.h> #include <epicsGetopt.h> #include <epicsThread.h> #include <pv/pvAccess.h> #include <pv/clientFactory.h> #include <pv/caProvider.h> #include <pv/convert.h> #include <pv/createRequest.h> using std::tr1::static_pointer_cast; using namespace std; using namespace epics::pvData; using namespace epics::pvAccess; using namespace epics::pvAccess::ca; class ExampleRequester; typedef std::tr1::shared_ptr<ExampleRequester> ExampleRequesterPtr; class ExampleRequester : public ChannelRequester, public ChannelPutRequester, public ChannelGetRequester, public std::tr1::enable_shared_from_this<ExampleRequester> { private: const string channelName; public: bool channelConnected = false; bool channelPutConnected = false; bool channelPutDone = false; bool channelGetConnected = false; bool channelGetDone = false; Channel::shared_pointer theChannel; ChannelPut::shared_pointer theChannelPut; Structure::const_shared_pointer theChannelPutStructure; ChannelGet::shared_pointer theChannelGet; PVStructure::shared_pointer theChannelGetPVStructure; ExampleRequester(const string & channelName) : channelName(channelName) {} virtual std::string getRequesterName(){ throw std::runtime_error("getRequesterName not implemented"); } virtual void channelCreated(const Status& status, Channel::shared_pointer const & channel) { if(status.isOK()) {return;} string message = string("channel ") + channelName + " channelCreated status=" + status.getMessage(); throw std::runtime_error(message); } virtual void channelStateChange(Channel::shared_pointer const & channel, Channel::ConnectionState connectionState) { if(connectionState==Channel::CONNECTED) { channelConnected = true; theChannel = channel; } else { string message = string("channel ") + channelName + " connection state " + Channel::ConnectionStateNames[connectionState]; throw std::runtime_error(message); } } virtual void channelPutConnect( const Status& status, ChannelPut::shared_pointer const & channelPut, Structure::const_shared_pointer const & structure) { if(status.isOK()) { channelPutConnected = true; theChannelPut = channelPut; theChannelPutStructure = structure; return; } string message = string("channel ") + channelName + " channelPutConnect status=" + status.getMessage(); throw std::runtime_error(message); } virtual void putDone( const Status& status, ChannelPut::shared_pointer const & channelPut) { channelPutDone = true; if(status.isOK()) {return;} cout << "channel=" << channelName << " channelPutDone status=" << status.getMessage() << "\n"; } virtual void getDone( const Status& status, ChannelPut::shared_pointer const & channelPut, PVStructure::shared_pointer const & pvStructure, BitSet::shared_pointer const & bitSet) { string message = string("channel ") + channelName + " channelPut:get not implemented"; throw std::runtime_error(message); } virtual void channelGetConnect( const Status& status, ChannelGet::shared_pointer const & channelGet, Structure::const_shared_pointer const & structure) { if(status.isOK()) { channelGetConnected = true; theChannelGet = channelGet; return; } string message = string("channel ") + channelName + " channelGetConnect status=" + status.getMessage(); throw std::runtime_error(message); } virtual void getDone( const Status& status, ChannelGet::shared_pointer const & channelGet, PVStructure::shared_pointer const & pvStructure, BitSet::shared_pointer const & bitSet) { channelGetDone = true; theChannelGetPVStructure = pvStructure; if(status.isOK()) {return;} cout << "channel=" << channelName << " channelGetDone status=" << status.getMessage() << "\n"; } }; static PVDataCreatePtr pvDataCreate = getPVDataCreate(); static ConvertPtr convert = getConvert(); static void example( string providerName, shared_vector<const string> const &channelNames) { ChannelProviderRegistry::shared_pointer channelRegistry(ChannelProviderRegistry::clients()); if(providerName=="pva") { ClientFactory::start(); } else if(providerName=="ca") { CAClientFactory::start(); } else { cerr << "provider " << providerName << " not known" << endl; throw std::runtime_error("unknown provider"); } int num = channelNames.size(); shared_vector<ExampleRequesterPtr> exampleRequester(num); for(int i=0; i<num; i++) { exampleRequester[i] = ExampleRequesterPtr(new ExampleRequester(channelNames[i])); } ChannelProvider::shared_pointer channelProvider; shared_vector<Channel::shared_pointer> channels(num); shared_vector<ChannelPut::shared_pointer> channelPuts(num); shared_vector<ChannelGet::shared_pointer> channelGets(num); channelProvider = channelRegistry->getProvider(providerName); for(int i=0; i<num; i++) { channels[i] = channelProvider->createChannel( channelNames[i],exampleRequester[i],ChannelProvider::PRIORITY_DEFAULT); } clock_t startTime; clock_t endTime; startTime = clock(); while(true) { epicsThreadSleep(.1); endTime = clock(); double seconds = (double)(endTime - startTime)/CLOCKS_PER_SEC; if(seconds>5.0) { for(int i=0; i<num; i++) { if(!exampleRequester[i]->channelConnected) { cout << "channel=" << channelNames[i] << " connect failed " <<"\n"; } } throw std::runtime_error("connect exception"); } int numConnected = 0; for(int i=0; i<num; i++) { if(exampleRequester[i]->channelConnected) numConnected++; } if(numConnected==num) break; } CreateRequest::shared_pointer createRequest(CreateRequest::create()); PVStructurePtr pvRequest = createRequest->createRequest("value"); for(int i=0; i<num; i++) { channelPuts[i] = channels[i]->createChannelPut(exampleRequester[i],pvRequest); channelGets[i] = channels[i]->createChannelGet(exampleRequester[i],pvRequest); } startTime = clock(); while(true) { epicsThreadSleep(.1); endTime = clock(); double seconds = (double)(endTime - startTime)/CLOCKS_PER_SEC; if(seconds>5.0) { for(int i=0; i<num; i++) { if(!exampleRequester[i]->channelGetConnected) { cout << "channel=" << channelNames[i] << " channelGetConnected failed " <<"\n"; } } throw std::runtime_error("connect exception"); } int numConnected = 0; for(int i=0; i<num; i++) { if(exampleRequester[i]->channelGetConnected) numConnected++; } if(numConnected==num) break; } startTime = clock(); while(true) { epicsThreadSleep(.1); endTime = clock(); double seconds = (double)(endTime - startTime)/CLOCKS_PER_SEC; if(seconds>5.0) { for(int i=0; i<num; i++) { if(!exampleRequester[i]->channelPutConnected) { cout << "channel=" << channelNames[i] << " channelPutConnected failed " <<"\n"; } } throw std::runtime_error("connect exception"); } int numConnected = 0; for(int i=0; i<num; i++) { if(exampleRequester[i]->channelPutConnected) numConnected++; } if(numConnected==num) break; } int successCount = 0; int failedCount = 0; startTime = clock(); int numiter = 10000; int value = 0; for(int i = 0; i< numiter; i+= 1) { bool correctData = true; value++; if(value>127) value = 0; string strValue = to_string(value); for(int j=0; j<num; j++) { PVStructurePtr pvStructure = pvDataCreate->createPVStructure( exampleRequester[j]->theChannelPutStructure); BitSetPtr bitSet(BitSetPtr(new BitSet(pvStructure->getNumberFields()))); PVScalarPtr pvScalar(pvStructure->getSubField<PVScalar>("value")); bitSet->set(pvScalar->getFieldOffset()); convert->fromString(pvScalar,strValue); try { exampleRequester[j]->theChannelPut->put(pvStructure,bitSet); } catch (std::exception& e) { cout << "i=" << i << " channelName=" << channelNames[j] << " put exception " << e.what() << endl; correctData = false; } } int numTry = 0; while(true) { if(numTry>100) { throw std::runtime_error("put timed out"); } int numDone = 0; for(int j=0; j<num; j++) { if(exampleRequester[j]->channelPutDone) numDone++; } if(numDone==num) break; epicsThreadSleep(.001); } for(int j=0; j<num; j++) { try { exampleRequester[j]->theChannelGet->get(); } catch (std::exception& e) { cout << "i=" << i << " channelName=" << channelNames[j] << " get exception " << e.what() << endl; } } numTry = 0; while(true) { if(numTry>100) { throw std::runtime_error("get timed out"); } int numDone = 0; for(int j=0; j<num; j++) { if(exampleRequester[j]->channelGetDone) numDone++; } if(numDone==num) break; epicsThreadSleep(.001); } for(int j=0; j<num; j++) { PVStructurePtr pvStructure = exampleRequester[j]->theChannelGetPVStructure; PVScalarPtr pvScalar = pvStructure->getSubField<PVScalar>("value"); string getValue = convert->toString(pvScalar); if(strValue!=getValue){ cout << "i=" << i << " channelName=" << channelNames[j] << " expected=" << strValue << " got=" << getValue << "\n"; correctData = false; } } for(int j=0; j<num; j++) { exampleRequester[j]->channelPutDone = false; exampleRequester[j]->channelGetDone = false; } if(correctData) { successCount++; } else { failedCount++; } } double seconds = (double)(clock() - startTime)/CLOCKS_PER_SEC; cout << "time=" << seconds << " per interation=" << seconds/numiter << "\n"; cout << "SUCCESS COUNT: " << successCount << endl; cout << "FAILED COUNT: " << failedCount << endl; channelGets.clear(); channelPuts.clear(); channels.clear(); exampleRequester.clear(); if(providerName=="pva") { ClientFactory::stop(); } else { CAClientFactory::stop(); } channelRegistry.reset(); } int main(int argc,char *argv[]) { string provider("pva"); shared_vector<string> channelNames; channelNames.push_back("PVRbyte"); channelNames.push_back("PVRshort"); channelNames.push_back("PVRint"); channelNames.push_back("PVRlong"); channelNames.push_back("PVRubyte"); channelNames.push_back("PVRushort"); channelNames.push_back("PVRuint"); channelNames.push_back("PVRulong"); channelNames.push_back("PVRfloat"); channelNames.push_back("PVRdouble"); int opt; while((opt = getopt(argc, argv, "hp:")) != -1) { switch(opt) { case 'p': provider = optarg; break; case 'h': cout << " -h -p provider channelNames " << endl; cout << "default" << endl; cout << "-p " << provider << " " << channelNames << endl; return 0; default: std::cerr<<"Unknown argument: "<<opt<<"\n"; return -1; } } bool pvaSrv(((provider.find("pva")==string::npos) ? false : true)); bool caSrv(((provider.find("ca")==string::npos) ? false : true)); if(pvaSrv&&caSrv) { cerr<< "multiple providers are not allowed\n"; return 1; } cout << "_____pvaClientPutGet starting_______\n"; try { int nPvs = argc - optind; /* Remaining arg list are PV names */ if (nPvs!=0) { channelNames.clear(); while(optind < argc) { channelNames.push_back(argv[optind]); optind++; } } cout << " channelNames " << channelNames << endl; shared_vector<const string> names(freeze(channelNames)); example(provider,names); cout << "_____pvaClientPutGet done_______\n"; } catch (std::exception& e) { cout << "exception " << e.what() << endl; return 1; } return 0; }
35.845953
111
0.5771
mrkraimer
f16cff1e25753675382ed1c15ea4d3165627f0a0
1,794
cpp
C++
graph-source-code/141-E/3793087.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/141-E/3793087.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/141-E/3793087.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
//Language: GNU C++ #include <iostream> #include <vector> #include <algorithm> #include <string> #include <cstdio> using namespace std; const int nmax = 1010; int n,m; int se[nmax][nmax],me[nmax][nmax],u,v; int color_s[nmax],color[nmax]; int nc=1; vector < int > res; void dfs(int u,int c){ color_s[u] = c; for(int j = 1;j<=n;j++) if(color_s[j]==0 && me[u][j]>0) dfs(j,c); } void uni(int u,int v){ int c = color[u]; for(int i=1;i<=n;i++) if(color[i]==c) color[i] = color[v]; } int main() { int u,v; char c; scanf("%d%d", &n, &m); for(int i=1;i<=m;i++){ scanf("%d %d %c",&u,&v,&c); if(c == 'S') se[u][v] = i; else me[u][v] = i; if(c == 'S') se[v][u] = i; else me[v][u] = i; } for(int i=1;i<=n;i++) if(color_s[i]==0) dfs(i,nc++); if(n%2==0){ cout << -1 << endl; return 0; } if(n == 1 ){ cout << 0 << endl; return 0; } u = (n-1)/2; for(int i=1;i<=n;i++) color[i] = i; for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) if(se[i][j]>0 && color_s[i]!=color_s[j] && color[i]!=color[j] && u!=0) { uni(i,j); res.push_back(se[i][j]); u--;} for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) if(se[i][j]>0 && color_s[i]==color_s[j] && color[i]!=color[j] && u!=0) { uni(i,j); res.push_back(se[i][j]); u--;} if(u!=0){ cout << -1 << endl; return 0; } u = (n-1) / 2; for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) if(me[i][j]>0 && color[i]!=color[j] && u!=0) { uni(i,j); res.push_back(me[i][j]); u--;} if(res.size()!=n-1){ cout << -1 << endl; return 0; } cout << n-1 << endl; for(int i=0;i<n-1;i++) cout << res[i] << ' '; cout << endl; return 0; }
24.243243
77
0.444259
AmrARaouf
f16d1cdb27f16e68f138487b6cdb79fe5e7f8f74
5,858
hpp
C++
rpc_examples/RpcServer.hpp
cd606/tm_examples
5ea8e9774f5070fbcc073c71c39bcb7febef88a7
[ "Apache-2.0" ]
1
2020-05-22T08:47:00.000Z
2020-05-22T08:47:00.000Z
rpc_examples/RpcServer.hpp
cd606/tm_examples
5ea8e9774f5070fbcc073c71c39bcb7febef88a7
[ "Apache-2.0" ]
null
null
null
rpc_examples/RpcServer.hpp
cd606/tm_examples
5ea8e9774f5070fbcc073c71c39bcb7febef88a7
[ "Apache-2.0" ]
null
null
null
#ifndef RPC_SERVER_HPP_ #define RPC_SERVER_HPP_ #include <tm_kit/infra/GenericLift.hpp> #include <unordered_map> #include "RpcInterface.hpp" namespace rpc_examples { template <class R> auto simpleFacility() -> typename R::template OnOrderFacilityPtr<Input,Output> { using namespace dev::cd606::tm; using GL = typename infra::GenericLift<typename R::AppType>; return GL::lift(infra::LiftAsFacility{}, [](Input &&input) -> Output { return {input.y+":"+std::to_string(input.x)}; }); } template <class R> auto clientStreamFacility() -> typename R::template OnOrderFacilityPtr<Input,Output> { using M = typename R::AppType; class Facility final : public M::template AbstractOnOrderFacility<Input,Output> { private: struct PerIDData { std::string res; int remainingCount; }; std::unordered_map<typename M::EnvironmentType::IDType, PerIDData> remainingInputs_; public: Facility() : remainingInputs_() {} virtual ~Facility() = default; virtual void handle(typename M::template InnerData< typename M::template Key<Input> > &&input) override final { auto id = input.timedData.value.id(); auto const &realInput = input.timedData.value.key(); auto iter = remainingInputs_.find(id); if (iter == remainingInputs_.end()) { iter = remainingInputs_.insert({ id, PerIDData { realInput.y+":"+std::to_string(realInput.x) , realInput.x-1 } }).first; } else { iter->second.res += ","+realInput.y+":"+std::to_string(realInput.x); --iter->second.remainingCount; } if (iter->second.remainingCount <= 0) { this->publish( input.environment , typename M::template Key<Output> { id, {std::move(iter->second.res)} } , true //this is the last (and only) one output for this input ); remainingInputs_.erase(iter); } } }; return M::template fromAbstractOnOrderFacility(new Facility()); } template <class R> auto serverStreamFacility() -> typename R::template OnOrderFacilityPtr<Input,Output> { using M = typename R::AppType; class Facility final : public M::template AbstractOnOrderFacility<Input,Output> { public: Facility() {} virtual ~Facility() = default; virtual void handle(typename M::template InnerData< typename M::template Key<Input> > &&input) override final { auto id = input.timedData.value.id(); auto const &realInput = input.timedData.value.key(); int resultCount = std::max(1,realInput.x); Output o {realInput.y+":"+std::to_string(realInput.x)}; for (int ii=1; ii<=resultCount; ++ii) { this->publish( input.environment , typename M::template Key<Output> { id, o } , (ii == resultCount) ); } } }; return M::template fromAbstractOnOrderFacility(new Facility()); } template <class R> auto bothStreamFacility() -> typename R::template OnOrderFacilityPtr<Input,Output> { using M = typename R::AppType; class Facility final : public M::template AbstractOnOrderFacility<Input,Output> { private: struct PerIDData { std::vector<Output> res; int remainingCount; }; std::unordered_map<typename M::EnvironmentType::IDType, PerIDData> remainingInputs_; public: Facility() : remainingInputs_() {} virtual ~Facility() = default; virtual void handle(typename M::template InnerData< typename M::template Key<Input> > &&input) override final { auto id = input.timedData.value.id(); auto const &realInput = input.timedData.value.key(); auto iter = remainingInputs_.find(id); if (iter == remainingInputs_.end()) { iter = remainingInputs_.insert({ id, PerIDData { {Output {realInput.y+":"+std::to_string(realInput.x)}} , realInput.x-1 } }).first; } else { iter->second.res.push_back(Output {realInput.y+":"+std::to_string(realInput.x)}); --iter->second.remainingCount; } if (iter->second.remainingCount <= 0) { int sz = iter->second.res.size(); for (int ii=0; ii<sz; ++ii) { this->publish( input.environment , typename M::template Key<Output> { id, std::move(iter->second.res[ii]) } , (ii==sz-1) ); } remainingInputs_.erase(iter); } } }; return M::template fromAbstractOnOrderFacility(new Facility()); } } #endif
40.123288
101
0.485831
cd606
f16de14756fc2d2d5852a7a7a9a4b907937f8e5d
1,348
cpp
C++
Plugins/Tweaks/FixArmorDexBonusUnderOne.cpp
summonFox/unified
47ab7d051fe52c26e2928b569e9fe7aec5aa8705
[ "MIT" ]
111
2018-01-16T18:49:19.000Z
2022-03-13T12:33:54.000Z
Plugins/Tweaks/FixArmorDexBonusUnderOne.cpp
summonFox/unified
47ab7d051fe52c26e2928b569e9fe7aec5aa8705
[ "MIT" ]
636
2018-01-17T10:05:31.000Z
2022-03-28T20:06:03.000Z
Plugins/Tweaks/FixArmorDexBonusUnderOne.cpp
summonFox/unified
47ab7d051fe52c26e2928b569e9fe7aec5aa8705
[ "MIT" ]
110
2018-01-16T19:05:54.000Z
2022-03-28T03:44:16.000Z
#include "nwnx.hpp" #include "API/CNWRules.hpp" #include "API/CNWSCreature.hpp" #include "API/CNWSCreatureStats.hpp" #include "API/CNWSInventory.hpp" #include "API/CNWSItem.hpp" #include "API/CTwoDimArrays.hpp" namespace Tweaks { using namespace NWNXLib; using namespace NWNXLib::API; void FixArmorDexBonusUnderOne() __attribute__((constructor)); void FixArmorDexBonusUnderOne() { if (!Config::Get<bool>("FIX_ARMOR_DEX_BONUS_UNDER_ONE", false)) return; LOG_INFO("Allowing armors with max DEX bonus under 1."); static Hooks::Hook s_ReplacedFunc = Hooks::HookFunction(Functions::_ZN17CNWSCreatureStats9GetDEXModEi, (void*)+[](CNWSCreatureStats *pThis, int32_t bArmorDexCap) -> uint8_t { auto nDexAC = pThis->m_nDexterityModifier; if (bArmorDexCap) { auto pArmor = pThis->m_pBaseCreature->m_pInventory->GetItemInSlot(Constants::EquipmentSlot::Chest); int nTempValue = 0; if (pArmor && (nTempValue = pArmor->ComputeArmorClass()) > 0) { Globals::Rules()->m_p2DArrays->m_pArmorTable->GetINTEntry(nTempValue, CExoString("DEXBONUS"), &nTempValue); if (nTempValue < nDexAC) nDexAC = static_cast<char>(nTempValue); } } return nDexAC; }, Hooks::Order::Final); } }
28.680851
123
0.660237
summonFox
f16e00fb02c76edea15ca84b7c9d391418773adc
159
cpp
C++
character/Character.cpp
iliam-12/Bomberman
62c688704e34bf1ec762adc76390a545b056e0cc
[ "MIT" ]
null
null
null
character/Character.cpp
iliam-12/Bomberman
62c688704e34bf1ec762adc76390a545b056e0cc
[ "MIT" ]
null
null
null
character/Character.cpp
iliam-12/Bomberman
62c688704e34bf1ec762adc76390a545b056e0cc
[ "MIT" ]
null
null
null
/* ** EPITECH PROJECT, 2021 ** Projects ** File description: ** Character */ #include "Character.hpp" Character::Character() { } Character::~Character() { }
9.9375
24
0.660377
iliam-12
f1703130c69af6364a5de7c77c94f25e1c1c0483
1,850
hpp
C++
debug/client/gdb/TcpTransport.hpp
myArea51/binnavi
021e62dcb7c3fae2a99064b0ea497cb221dc7238
[ "Apache-2.0" ]
3,083
2015-08-19T13:31:12.000Z
2022-03-30T09:22:21.000Z
debug/client/gdb/TcpTransport.hpp
Jason-Cooke/binnavi
b98b191d8132cbde7186b486d23a217fcab4ec44
[ "Apache-2.0" ]
99
2015-08-19T14:42:49.000Z
2021-04-13T10:58:32.000Z
debug/client/gdb/TcpTransport.hpp
Jason-Cooke/binnavi
b98b191d8132cbde7186b486d23a217fcab4ec44
[ "Apache-2.0" ]
613
2015-08-19T14:15:44.000Z
2022-03-26T04:40:55.000Z
// Copyright 2011-2016 Google 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. #ifndef TCPTRANSPORT_HPP #define TCPTRANSPORT_HPP #include <string> #include "Transport.hpp" #include "../conns/GenericSocketFunctions.hpp" /** * Transport class that can be used to create TCP connections to the gbdserver. */ class TcpTransport : public Transport { private: // Address of the host where the gdbserver is running. std::string host; // Port where the gdbserver is listening. unsigned int port; // Socket that can be used to connect with the gdbserver. SOCKET gdbSocket; public: /** * Creates a new TCP/IP connection to the GDB server. * * @param host Host address of the GDB server connection. * @param port Port of the GDB server. */ TcpTransport(const std::string& host, unsigned int port) : host(host), port(port) { } // Opens the TCP/IP connection to the GDB server. NaviError open(); // Closes the TCP/IP connection to the GDB server. NaviError close(); // Checks whether data is available from the GDB server. bool hasData() const; // Sends data to the GDB server. NaviError send(const char* buffer, unsigned int size) const; // Receives data from the GDB server. NaviError read(char* buffer, unsigned int size) const; }; #endif
27.205882
79
0.714595
myArea51
f17333fa914f67298836ac2d09f1dc1d58bbd82f
12,350
cpp
C++
tests/string.tests.cpp
dynamic-static/dynamic_static.string
ea28d847e97d5f83c2051b722f6b4e4f508e55a6
[ "MIT" ]
null
null
null
tests/string.tests.cpp
dynamic-static/dynamic_static.string
ea28d847e97d5f83c2051b722f6b4e4f508e55a6
[ "MIT" ]
null
null
null
tests/string.tests.cpp
dynamic-static/dynamic_static.string
ea28d847e97d5f83c2051b722f6b4e4f508e55a6
[ "MIT" ]
null
null
null
/* ========================================== Copyright (c) 2016-2021 dynamic_static Licensed under the MIT license http://opensource.org/licenses/MIT ========================================== */ #include "dynamic_static/string.hpp" #include "catch2/catch.hpp" namespace dst { namespace tests { static const std::string TheQuickBrownFox { "The quick brown fox jumps over the lazy dog!" }; /** Validates that string::Proxy constructs correctly */ TEST_CASE("string::Proxy::Proxy()", "[string]") { SECTION("string::Proxy::Proxy(char)") { string::Proxy proxy('c'); CHECK(proxy == "c"); } SECTION("string::Proxy::Proxy(std::string)") { string::Proxy proxy(TheQuickBrownFox); CHECK(proxy == TheQuickBrownFox); } SECTION("string::Proxy::Proxy(const char*) (valid)") { string::Proxy proxy(TheQuickBrownFox.c_str()); CHECK(proxy == TheQuickBrownFox); } SECTION("string::Proxy::Proxy(const char*) (invalid)") { char* pStr = nullptr; string::Proxy proxy(pStr); CHECK(proxy == std::string()); } } /** Validates string::contains() */ TEST_CASE("string::contains()", "[string]") { SECTION("Successful true") { REQUIRE(string::contains(TheQuickBrownFox, "fox")); REQUIRE(string::contains(TheQuickBrownFox, "rown fox ju")); REQUIRE(string::contains(TheQuickBrownFox, 'j')); REQUIRE(string::contains(TheQuickBrownFox, '!')); } SECTION("Successful false") { REQUIRE_FALSE(string::contains(TheQuickBrownFox, "bat")); REQUIRE_FALSE(string::contains(TheQuickBrownFox, '7')); REQUIRE_FALSE(string::contains(TheQuickBrownFox, '?')); } SECTION("Empty str true") { REQUIRE(string::contains(TheQuickBrownFox, std::string())); REQUIRE(string::contains(std::string(), std::string())); } SECTION("Empty str false") { REQUIRE_FALSE(string::contains(std::string(), TheQuickBrownFox)); } } /** Validates string::starts_with() */ TEST_CASE("string::starts_with()", "[string]") { SECTION("Successful true") { REQUIRE(string::starts_with(TheQuickBrownFox, 'T')); REQUIRE(string::starts_with(TheQuickBrownFox, "The")); REQUIRE(string::starts_with(TheQuickBrownFox, "The quick")); REQUIRE(string::starts_with(TheQuickBrownFox, TheQuickBrownFox)); } SECTION("Successful false") { REQUIRE_FALSE(string::starts_with(TheQuickBrownFox, "he quick brown fox")); REQUIRE_FALSE(string::starts_with(TheQuickBrownFox, "the")); REQUIRE_FALSE(string::starts_with(TheQuickBrownFox, '8')); } SECTION("Empty str true") { REQUIRE(string::starts_with(TheQuickBrownFox, std::string())); REQUIRE(string::starts_with(std::string(), std::string())); } SECTION("Empty str false") { REQUIRE_FALSE(string::starts_with(std::string(), TheQuickBrownFox)); } } /** Validates string::ends_with() */ TEST_CASE("string::ends_with()", "[string]") { SECTION("Successful true") { REQUIRE(string::ends_with(TheQuickBrownFox, '!')); REQUIRE(string::ends_with(TheQuickBrownFox, "dog!")); REQUIRE(string::ends_with(TheQuickBrownFox, "lazy dog!")); REQUIRE(string::ends_with(TheQuickBrownFox, TheQuickBrownFox)); } SECTION("Successful false") { REQUIRE_FALSE(string::ends_with(TheQuickBrownFox, "he quick brown fox")); REQUIRE_FALSE(string::ends_with(TheQuickBrownFox, "the")); REQUIRE_FALSE(string::ends_with(TheQuickBrownFox, '8')); } SECTION("Empty str true") { REQUIRE(string::ends_with(TheQuickBrownFox, std::string())); REQUIRE(string::ends_with(std::string(), std::string())); } SECTION("Empty str false") { REQUIRE_FALSE(string::ends_with(std::string(), TheQuickBrownFox)); } } /** Validates string::replace() */ TEST_CASE("string::replace()", "[string]") { SECTION("Successful replace") { auto str = TheQuickBrownFox; str = string::replace(str, '!', '.'); str = string::replace(str, "quick", "slow"); str = string::replace(str, "jumps", "trips"); str = string::replace(str, "lazy", "sleeping"); REQUIRE(str == "The slow brown fox trips over the sleeping dog."); } SECTION("Unsuccessful replace") { auto str = TheQuickBrownFox; str = string::replace(str, "fox", "fox"); str = string::replace(str, std::string(), "bird"); str = string::replace(str, "cat", "dog"); str = string::replace(str, "frog", std::string()); REQUIRE(str == TheQuickBrownFox); } SECTION("Empty str replace") { auto str = std::string(); str = string::replace(str, '!', '.'); str = string::replace(str, "quick", "slow"); str = string::replace(str, "jumps", "trips"); str = string::replace(str, "lazy", "sleeping"); REQUIRE(str == std::string()); } SECTION("Successful multi Replacement") { auto str = string::replace( TheQuickBrownFox, { { '!', '.' }, { "quick", "slow" }, { "jumps", "trips" }, { "lazy", "sleeping" }, } ); REQUIRE(str == "The slow brown fox trips over the sleeping dog."); } SECTION("Unsuccessful multi Replacement") { auto str = string::replace( TheQuickBrownFox, { { "fox", "fox" }, { std::string(), "bird" }, { "cat", "dog" }, { "frog", std::string() }, } ); REQUIRE(str == TheQuickBrownFox); } SECTION("Empty str multi Replacement") { auto str = string::replace( std::string(), { { "!", "." }, { "quick", "slow" }, { "jumps", "trips" }, { "lazy", "sleeping" }, } ); REQUIRE(str == std::string()); } } /** Validates string::remove() */ TEST_CASE("string::remove()", "[string]") { SECTION("Successful remove") { auto str = TheQuickBrownFox; str = string::remove(str, "The "); str = string::remove(str, '!'); str = string::remove(str, "brown "); str = string::remove(str, "lazy "); REQUIRE(str == "quick fox jumps over the dog"); } SECTION("Unsuccessful remove") { auto str = TheQuickBrownFox; str = string::remove(str, '9'); str = string::remove(str, "antelope"); str = string::remove(str, "The "); str = string::remove(str, " fox "); REQUIRE(str == TheQuickBrownFox); } } /** Validates string::reduce_sequence() */ TEST_CASE("string::reduce_sequence()", "[string]") { std::string str = "some\\ugly\\/\\//\\path\\with\\a/////broken\\\\extension.....ext"; str = string::replace(str, '\\', "/"); str = string::reduce_sequence(str, '/'); str = string::reduce_sequence(str, "."); str = string::replace(str, "ugly", "nice"); str = string::replace(str, "broken", "decent"); REQUIRE(str == "some/nice/path/with/a/decent/extension.ext"); } /** Validates string::scrub_path() */ TEST_CASE("string::scrub_path()", "[string]") { std::string str = "some//file/\\path/with\\various\\//conventions.txt"; REQUIRE(string::scrub_path(str) == "some/file/path/with/various/conventions.txt"); } /** Validates string::scrub_path() */ TEST_CASE("string::is_whitespace()", "[string]") { SECTION("Successful true") { REQUIRE(string::is_whitespace(' ')); REQUIRE(string::is_whitespace('\f')); REQUIRE(string::is_whitespace('\n')); REQUIRE(string::is_whitespace('\r')); REQUIRE(string::is_whitespace('\t')); REQUIRE(string::is_whitespace('\v')); REQUIRE(string::is_whitespace(" \f\n\r\t\v")); } SECTION("Successful false") { REQUIRE_FALSE(string::is_whitespace('0')); REQUIRE_FALSE(string::is_whitespace(" \f\n\r text \t\v")); } } /** Validates string::trim_leading_whitespace() */ TEST_CASE("string::trim_leading_whitespace()", "[string]") { auto str = " " + TheQuickBrownFox + " "; REQUIRE(string::trim_leading_whitespace(str) == TheQuickBrownFox + " "); } /** Validates string::trim_trailing_whitespace() */ TEST_CASE("string::trim_trailing_whitespace()", "[string]") { auto str = " " + TheQuickBrownFox + " "; REQUIRE(string::trim_trailing_whitespace(str) == " " + TheQuickBrownFox); } /** Validates string::trim_whitespace() */ TEST_CASE("string::trim_whitespace()", "[string]") { auto str = " " + TheQuickBrownFox + " "; REQUIRE(string::trim_whitespace(str) == TheQuickBrownFox); } /** Validates string::is_upper() */ TEST_CASE("string::is_upper()", "[string]") { SECTION("Successful true") { REQUIRE(string::is_upper('Z')); REQUIRE(string::is_upper("THE")); } SECTION("Successful false") { REQUIRE_FALSE(string::is_upper('z')); REQUIRE_FALSE(string::is_upper(TheQuickBrownFox)); } } /** Validates string::to_upper() */ TEST_CASE("string::to_upper()", "[string]") { REQUIRE(string::to_upper(TheQuickBrownFox) == "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG!"); } /** Validates string::is_lower() */ TEST_CASE("string::is_lower()", "[string]") { SECTION("Successful true") { REQUIRE(string::is_lower('z')); REQUIRE(string::is_lower("the")); } SECTION("Successful false") { REQUIRE_FALSE(string::is_lower('Z')); REQUIRE_FALSE(string::is_lower(TheQuickBrownFox)); } } /** Validates string::to_lower() */ TEST_CASE("string::to_lower()", "[string]") { REQUIRE(string::to_lower("THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG!") == "the quick brown fox jumps over the lazy dog!"); } /** Validates string::get_line() */ TEST_CASE("string::get_line()", "[string]") { std::vector<std::string> lines { { "The quick\n" }, { "brown fox\n" }, { "jumps over\n" }, { "the lazy\n" }, { "dog." }, }; std::string str; for (auto const& line : lines) { str += line; } CHECK(string::get_line(str, str.find("quick")) == lines[0]); CHECK(string::get_line(str, str.find("brown")) == lines[1]); CHECK(string::get_line(str, str.find("over")) == lines[2]); CHECK(string::get_line(str, str.find("lazy")) == lines[3]); CHECK(string::get_line(str, str.find("dog")) == lines[4]); } /** Validates string::split() */ TEST_CASE("string::split()", "[string]") { const std::vector<std::string> Tokens { "The", "quick", "brown", "fox" }; SECTION("Empty str") { REQUIRE(string::split(std::string(), " ").empty()); } SECTION("char delimiter") { REQUIRE(string::split("The;quick;brown;fox", ';') == Tokens); } SECTION("char delimiter (prefix)") { REQUIRE(string::split(";The;quick;brown;fox", ';') == Tokens); } SECTION("char delimiter (postfix)") { REQUIRE(string::split("The;quick;brown;fox;", ';') == Tokens); } SECTION("char delimiter (prefix and postfix)") { REQUIRE(string::split(";The;quick;brown;fox;", ';') == Tokens); } SECTION("std::string delimiter") { REQUIRE(string::split("The COW quick COW brown COW fox COW ", " COW ") == Tokens); } } /** Validates string::split_snake_case() */ TEST_CASE("string::split_snake_case()", "[string]") { const std::vector<std::string> Tokens { "the", "quick", "brown", "fox" }; REQUIRE(string::split_snake_case("the_quick_brown_fox") == Tokens); } /** Validates string::split_camel_case() */ TEST_CASE("string::split_camel_case()", "[string]") { const std::vector<std::string> Tokens { "The", "Quick", "Brown", "FOX" }; REQUIRE(string::split_camel_case("TheQuickBrownFOX") == Tokens); } /** Validates string::to_hex_string() */ TEST_CASE("to_hex_string()", "[string]") { REQUIRE(to_hex_string(3735928559) == "0xdeadbeef"); REQUIRE(to_hex_string(3735928559, false) == "deadbeef"); } } // namespace tests } // namespace dst
28.196347
128
0.576923
dynamic-static
f1764c9614f45b517ed5a136610b6a355f71f426
1,638
cc
C++
components/permissions/notification_permission_ui_selector.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
components/permissions/notification_permission_ui_selector.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
components/permissions/notification_permission_ui_selector.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2020 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 "components/permissions/notification_permission_ui_selector.h" #include "base/optional.h" namespace permissions { // static bool NotificationPermissionUiSelector::ShouldSuppressAnimation( base::Optional<QuietUiReason> reason) { if (!reason) return true; switch (*reason) { case QuietUiReason::kEnabledInPrefs: case QuietUiReason::kPredictedVeryUnlikelyGrant: return false; case QuietUiReason::kTriggeredByCrowdDeny: case QuietUiReason::kTriggeredDueToAbusiveRequests: case QuietUiReason::kTriggeredDueToAbusiveContent: return true; } } NotificationPermissionUiSelector::Decision::Decision( base::Optional<QuietUiReason> quiet_ui_reason, base::Optional<WarningReason> warning_reason) : quiet_ui_reason(quiet_ui_reason), warning_reason(warning_reason) {} NotificationPermissionUiSelector::Decision::~Decision() = default; NotificationPermissionUiSelector::Decision::Decision(const Decision&) = default; NotificationPermissionUiSelector::Decision& NotificationPermissionUiSelector::Decision::operator=(const Decision&) = default; // static NotificationPermissionUiSelector::Decision NotificationPermissionUiSelector::Decision::UseNormalUiAndShowNoWarning() { return Decision(UseNormalUi(), ShowNoWarning()); } base::Optional<PermissionUmaUtil::PredictionGrantLikelihood> NotificationPermissionUiSelector::PredictedGrantLikelihoodForUKM() { return base::nullopt; } } // namespace permissions
32.76
80
0.795482
Ron423c
f176b8bcd1d2f3be8e21be281432fc659e9960be
7,059
cpp
C++
src/lab_extra/compute_shaders/compute_shaders.cpp
MihaiAnghel07/Tema1-Elemente-de-Grafica-pe-Calculator
6f6cc6645d036cf4997f9e8028389cdbb1bb6a56
[ "MIT", "BSD-3-Clause" ]
6
2016-10-10T14:27:17.000Z
2020-10-09T09:31:37.000Z
src/lab_extra/compute_shaders/compute_shaders.cpp
MihaiAnghel07/Tema1-Elemente-de-Grafica-pe-Calculator
6f6cc6645d036cf4997f9e8028389cdbb1bb6a56
[ "MIT", "BSD-3-Clause" ]
9
2021-10-05T11:03:59.000Z
2022-02-25T19:01:53.000Z
src/lab_extra/compute_shaders/compute_shaders.cpp
MihaiAnghel07/Tema1-Elemente-de-Grafica-pe-Calculator
6f6cc6645d036cf4997f9e8028389cdbb1bb6a56
[ "MIT", "BSD-3-Clause" ]
23
2016-11-05T12:55:01.000Z
2021-05-13T16:55:40.000Z
#include "lab_extra/compute_shaders/compute_shaders.h" #include <string> #include <vector> #include <iostream> using namespace std; using namespace extra; static inline GLuint NumGroupSize(int dataSize, int groupSize) { return (dataSize + groupSize - 1) / groupSize; } static void DispatchCompute(unsigned int sizeX, unsigned int sizeY, unsigned int sizeZ, unsigned int workGroupSize, bool synchronize = true) { glDispatchCompute(NumGroupSize(sizeX, workGroupSize), NumGroupSize(sizeY, workGroupSize), NumGroupSize(sizeZ, workGroupSize)); if (synchronize) { glMemoryBarrier(GL_ALL_BARRIER_BITS); } CheckOpenGLError(); } /* * To find out more about `FrameStart`, `Update`, `FrameEnd` * and the order in which they are called, see `world.cpp`. */ ComputeShaders::ComputeShaders() { } ComputeShaders::~ComputeShaders() { delete frameBuffer; delete texture1; delete texture2; } void ComputeShaders::Init() { auto camera = GetSceneCamera(); camera->SetPositionAndRotation(glm::vec3(0, 5, 4), glm::quat(glm::vec3(-30 * TO_RADIANS, 0, 0))); camera->Update(); // Load a mesh from file into GPU memory { Mesh* mesh = new Mesh("sphere"); mesh->LoadMesh(PATH_JOIN(window->props.selfDir, RESOURCE_PATH::MODELS, "primitives"), "sphere.obj"); meshes[mesh->GetMeshID()] = mesh; } { Mesh* mesh = new Mesh("bamboo"); mesh->LoadMesh(PATH_JOIN(window->props.selfDir, RESOURCE_PATH::MODELS, "vegetation", "bamboo"), "bamboo.obj"); meshes[mesh->GetMeshID()] = mesh; } { Mesh* mesh = new Mesh("quad"); mesh->LoadMesh(PATH_JOIN(window->props.selfDir, RESOURCE_PATH::MODELS, "primitives"), "quad.obj"); mesh->UseMaterials(false); meshes[mesh->GetMeshID()] = mesh; } const string shaderPath = PATH_JOIN(window->props.selfDir, SOURCE_PATH::EXTRA, "compute_shaders", "shaders"); // Create a shader program for rendering to texture { Shader *shader = new Shader("ComputeShaders"); shader->AddShader(PATH_JOIN(shaderPath, "VertexShader.glsl"), GL_VERTEX_SHADER); shader->AddShader(PATH_JOIN(shaderPath, "FragmentShader.glsl"), GL_FRAGMENT_SHADER); shader->CreateAndLink(); shaders[shader->GetName()] = shader; } { Shader *shader = new Shader("FullScreenPass"); shader->AddShader(PATH_JOIN(shaderPath, "FullScreenPass.VS.glsl"), GL_VERTEX_SHADER); shader->AddShader(PATH_JOIN(shaderPath, "FullScreenPass.FS.glsl"), GL_FRAGMENT_SHADER); shader->CreateAndLink(); shaders[shader->GetName()] = shader; } { Shader *shader = new Shader("ComputeShader"); shader->AddShader(PATH_JOIN(shaderPath, "ComputeShader.CS.glsl"), GL_COMPUTE_SHADER); shader->CreateAndLink(); shaders[shader->GetName()] = shader; } auto resolution = window->GetResolution(); frameBuffer = new FrameBuffer(); frameBuffer->Generate(resolution.x, resolution.y, 3); texture1 = new Texture2D(); texture1->Create(nullptr, resolution.x, resolution.y, 4); texture2 = new Texture2D(); texture2->Create(nullptr, resolution.x, resolution.y, 4); } void ComputeShaders::FrameStart() { } void ComputeShaders::Update(float deltaTimeSeconds) { angle += 0.5f * deltaTimeSeconds; ClearScreen(); { frameBuffer->Bind(); DrawScene(); } // Run compute shader { auto shader = shaders["ComputeShader"]; shader->Use(); glm::ivec2 resolution = frameBuffer->GetResolution(); glBindImageTexture(0, frameBuffer->GetTextureID(0), 0, GL_FALSE, 0, GL_READ_WRITE, GL_RGBA32F); glBindImageTexture(1, texture1->GetTextureID(), 0, GL_FALSE, 0, GL_READ_WRITE, GL_RGBA8); DispatchCompute(resolution.x, resolution.y, 1, 16, true); } // Render the scene normaly FrameBuffer::BindDefault(); if (fullScreenPass) { { auto shader = shaders["FullScreenPass"]; shader->Use(); { int locTexture = shader->GetUniformLocation("texture_1"); glUniform1i(locTexture, 0); frameBuffer->BindTexture(0, GL_TEXTURE0); } { int locTexture = shader->GetUniformLocation("texture_2"); glUniform1i(locTexture, 1); frameBuffer->BindTexture(1, GL_TEXTURE0 + 1); } { int locTexture = shader->GetUniformLocation("texture_3"); glUniform1i(locTexture, 2); frameBuffer->BindTexture(2, GL_TEXTURE0 + 2); } { int locTexture = shader->GetUniformLocation("texture_4"); glUniform1i(locTexture, 3); glActiveTexture(GL_TEXTURE0 + 3); glBindTexture(GL_TEXTURE_2D, texture1->GetTextureID()); } int locTextureID = shader->GetUniformLocation("textureID"); glUniform1i(locTextureID, textureID); glm::mat4 modelMatrix(1); RenderMesh(meshes["quad"], shader, modelMatrix); } } } void ComputeShaders::DrawScene() { for (int i = 0; i < 16; i++) { float rotateAngle = (angle + i) * ((i % 2) * 2 - 1); glm::vec3 position = glm::vec3(-4 + (i % 4) * 2.5, 0, -2 + (i / 4) * 2.5); glm::mat4 modelMatrix = glm::translate(glm::mat4(1), position); modelMatrix = glm::rotate(modelMatrix, rotateAngle, glm::vec3(0, 1, 0)); modelMatrix = glm::scale(modelMatrix, glm::vec3(0.1f)); RenderMesh(meshes["bamboo"], shaders["ComputeShaders"], modelMatrix); } } void ComputeShaders::FrameEnd() { DrawCoordinateSystem(); } /* * These are callback functions. To find more about callbacks and * how they behave, see `input_controller.h`. */ void ComputeShaders::OnInputUpdate(float deltaTime, int mods) { // Treat continuous update based on input } void ComputeShaders::OnKeyPress(int key, int mods) { // Add key press event if (key == GLFW_KEY_F) { fullScreenPass = !fullScreenPass; } for (int i = 1; i < 9; i++) { if (key == GLFW_KEY_0 + i) { textureID = i - 1; } } } void ComputeShaders::OnKeyRelease(int key, int mods) { // Add key release event } void ComputeShaders::OnMouseMove(int mouseX, int mouseY, int deltaX, int deltaY) { // Add mouse move event } void ComputeShaders::OnMouseBtnPress(int mouseX, int mouseY, int button, int mods) { // Add mouse button press event } void ComputeShaders::OnMouseBtnRelease(int mouseX, int mouseY, int button, int mods) { // Add mouse button release event } void ComputeShaders::OnMouseScroll(int mouseX, int mouseY, int offsetX, int offsetY) { // Treat mouse scroll event } void ComputeShaders::OnWindowResize(int width, int height) { frameBuffer->Resize(width, height, 32); // Treat window resize event }
26.04797
140
0.627568
MihaiAnghel07
f179f7a91dfbb650165567c7a4008dfb576354df
360
cpp
C++
Online Judges/UVALive/6758/2766212_AC_3ms_0kB.cpp
moni-roy/COPC
f5918304815413c18574ef4af2e23a604bd9f704
[ "MIT" ]
4
2017-02-20T17:41:14.000Z
2019-07-15T14:15:34.000Z
Online Judges/UVALive/6758/2766212_AC_3ms_0kB.cpp
moni-roy/COPC
f5918304815413c18574ef4af2e23a604bd9f704
[ "MIT" ]
null
null
null
Online Judges/UVALive/6758/2766212_AC_3ms_0kB.cpp
moni-roy/COPC
f5918304815413c18574ef4af2e23a604bd9f704
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { int ts,n,a,x,y,es,hd; cin>>ts; while(ts--) { cin>>n>>x>>y; for(int i=0;i<n;i++) { cin>>a; if(i==0) es=a; if(i==n-1) hd=a; } if(es==x&&hd==y) cout<<"BOTH"<<endl; else if(es==x) cout<<"EASY"<<endl; else if(hd==y) cout<<"HARD"<<endl; else cout<<"OKAY"<<endl; } return 0; }
15.652174
38
0.516667
moni-roy
f17b57f4ccf32c1801240cb141d9cc052e330e35
2,859
cpp
C++
src_vc141/queue/MirrorBuffer.cpp
nneesshh/mytoolkit
336ae9c7077c8687a8cf8a2ce4aec804c28ab90c
[ "Apache-2.0" ]
null
null
null
src_vc141/queue/MirrorBuffer.cpp
nneesshh/mytoolkit
336ae9c7077c8687a8cf8a2ce4aec804c28ab90c
[ "Apache-2.0" ]
null
null
null
src_vc141/queue/MirrorBuffer.cpp
nneesshh/mytoolkit
336ae9c7077c8687a8cf8a2ce4aec804c28ab90c
[ "Apache-2.0" ]
2
2020-11-04T03:07:09.000Z
2020-11-05T08:14:45.000Z
//------------------------------------------------------------------------------ // MirrorBuffer.cpp // (C) 2016 n.lee //------------------------------------------------------------------------------ #include "MirrorBuffer.h" // Round up to the next power of two static uint32_t next_pot(uint32_t x) { --x; x |= x >> 1; // handle 2 bit numbers x |= x >> 2; // handle 4 bit numbers x |= x >> 4; // handle 8 bit numbers x |= x >> 8; // handle 16 bit numbers x |= x >> 16; // handle 32 bit numbers return ++x; } //------------------------------------------------------------------------------ /** */ CMirrorBuffer::CMirrorBuffer(size_t size) : _xbuf(new char[2 * size]) , _size(size) , _datalen(0) , _first(0) , _last(0) , _bytes(0) { } //------------------------------------------------------------------------------ /** */ CMirrorBuffer::~CMirrorBuffer() { delete[] _xbuf; } //------------------------------------------------------------------------------ /** */ bool CMirrorBuffer::Write(const char *s, size_t l) { if (l > 0) { if (_datalen + l > _size) { char *tmp = _xbuf; size_t sz = _size; // realloc _size = next_pot(_datalen + 1); if (_size <= 64 * 1024 * 1024) { _xbuf = new char[2 * _size]; // at max 2 * 64 Megabytes memcpy(_xbuf, tmp, sz); memcpy(_xbuf + _size, tmp, sz); delete[] tmp; } else { // overflow return false; } } _bytes += (unsigned long)l; // check block crossed mirror border if (_last + l > _size) { // size left until mirror border crossing size_t l1 = _size - _last; // always copy full block to buffer(_xbuf) + tail pointer(_last) // because we have doubled the buffer size as mirror for performance reasons memcpy(_xbuf + _last, s, l); memcpy(_xbuf, s + l1, l - l1); _last = l - l1; } else { memcpy(_xbuf + _last, s, l); // append tail memcpy(_xbuf + _size + _last, s, l); // append double buffer tail _last += l; } _datalen += l; } return true; } //------------------------------------------------------------------------------ /** */ bool CMirrorBuffer::Read(size_t l, std::string& out) { const char *start = GetStart(); if (Skip(l)) { out += std::string(start, l); return true; } return false; } //------------------------------------------------------------------------------ /** */ bool CMirrorBuffer::Skip(size_t l) { if (l > 0) { if (l > _datalen) { return false; // not enough chars } // check block crossed mirror border if (_first + l > _size) { size_t l1 = _size - _first; _first = l - l1; } else { _first += l; } _datalen -= l; if (!_datalen) { _first = _last = 0; } } return true; } /** -- EOF -- **/
21.496241
81
0.434767
nneesshh
f17ba655540cfb9782ec5e74f3f052b3f38ac763
1,261
cc
C++
aiks/paint_pass_delegate.cc
eyebrowsoffire/impeller
bdb74c046327bf1203b4293806399ccf57bf1c6e
[ "BSD-3-Clause" ]
null
null
null
aiks/paint_pass_delegate.cc
eyebrowsoffire/impeller
bdb74c046327bf1203b4293806399ccf57bf1c6e
[ "BSD-3-Clause" ]
2
2022-03-16T05:29:37.000Z
2022-03-31T05:35:03.000Z
aiks/paint_pass_delegate.cc
eyebrowsoffire/impeller
bdb74c046327bf1203b4293806399ccf57bf1c6e
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2013 The Flutter 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 "impeller/aiks/paint_pass_delegate.h" #include "impeller/entity/contents/contents.h" #include "impeller/entity/contents/texture_contents.h" namespace impeller { PaintPassDelegate::PaintPassDelegate(Paint paint, std::optional<Rect> coverage) : paint_(std::move(paint)), coverage_(std::move(coverage)) {} // |EntityPassDelgate| PaintPassDelegate::~PaintPassDelegate() = default; // |EntityPassDelgate| std::optional<Rect> PaintPassDelegate::GetCoverageRect() { return coverage_; } // |EntityPassDelgate| bool PaintPassDelegate::CanElide() { return paint_.color.IsTransparent(); } // |EntityPassDelgate| bool PaintPassDelegate::CanCollapseIntoParentPass() { return paint_.color.IsOpaque(); } // |EntityPassDelgate| std::shared_ptr<Contents> PaintPassDelegate::CreateContentsForSubpassTarget( std::shared_ptr<Texture> target) { auto contents = std::make_shared<TextureContents>(); contents->SetTexture(target); contents->SetSourceRect(IRect::MakeSize(target->GetSize())); contents->SetOpacity(paint_.color.alpha); return contents; } } // namespace impeller
28.659091
79
0.762887
eyebrowsoffire
f17e3fa2dd08809c92c8eb600fd8d011d386bf9f
1,664
cpp
C++
src/xray/editor/world/sources/property_integer_values_value_getter.cpp
ixray-team/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
3
2021-10-30T09:36:14.000Z
2022-03-26T17:00:06.000Z
src/xray/editor/world/sources/property_integer_values_value_getter.cpp
acidicMercury8/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
null
null
null
src/xray/editor/world/sources/property_integer_values_value_getter.cpp
acidicMercury8/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:08.000Z
2022-03-26T17:00:08.000Z
//////////////////////////////////////////////////////////////////////////// // Created : 09.01.2008 // Author : Dmitriy Iassenev // Copyright (C) GSC Game World - 2009 //////////////////////////////////////////////////////////////////////////// #include "pch.h" #include "property_integer_values_value_getter.h" using System::Collections::IList; using System::Collections::ArrayList; using System::Object; using System::String; property_integer_values_value_getter::property_integer_values_value_getter ( integer_getter_type^ getter, integer_setter_type^ setter, string_collection_getter_type^ collection_getter, string_collection_size_getter_type^ collection_size_getter ) : inherited (getter, setter), m_collection_getter (collection_getter), m_collection_size_getter(collection_size_getter) { } Object ^property_integer_values_value_getter::get_value () { int value = safe_cast<int>(inherited::get_value()); if (value < 0) value = 0; int count = collection()->Count; if (value >= count) value = count - 1; return (value); } void property_integer_values_value_getter::set_value (Object ^object) { String^ string_value = dynamic_cast<String^>(object); int index = collection()->IndexOf(string_value); ASSERT ((index >= 0)); inherited::set_value (index); } IList^ property_integer_values_value_getter::collection () { ArrayList^ collection = gcnew ArrayList(); u32 count = m_collection_size_getter(); for (u32 i=0; i<count; ++i) { collection->Add (m_collection_getter(i)); } return (collection); }
28.20339
77
0.631611
ixray-team
f181038812497d9604a0b6af20668d4db4e0b5f5
1,847
hpp
C++
tensors++/exceptions/tensor_formation.hpp
Razdeep/ml-plus-plus
02c2c2cc2e05c9e7de4c7155ebdab78a3c519ed2
[ "Apache-2.0" ]
null
null
null
tensors++/exceptions/tensor_formation.hpp
Razdeep/ml-plus-plus
02c2c2cc2e05c9e7de4c7155ebdab78a3c519ed2
[ "Apache-2.0" ]
null
null
null
tensors++/exceptions/tensor_formation.hpp
Razdeep/ml-plus-plus
02c2c2cc2e05c9e7de4c7155ebdab78a3c519ed2
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2018 Ashar <ashar786khan@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef TENSOR_FORMATION_HPP #define TENSOR_FORMATION_HPP #include <exception> #include <string> namespace tensors { namespace exceptions { class tensor_index_exception : public std::exception { const char *message; public: tensor_index_exception(std::string z) : message(z.c_str()){}; virtual const char *what() const noexcept final override { return ("Index for the tensor is invalid :" + std::string(message)).c_str(); } }; class initializer_exception : public std::exception { const char *message; public: initializer_exception(std::string z) : message(z.c_str()){}; virtual const char *what() const noexcept final override { return ("Unable to initialize, check that you have a valid constructor in " "the template type : " + std::string(message)) .c_str(); } }; class bad_init_shape : public std::exception { const char *message; public: bad_init_shape(std::string z) : message(z.c_str()){}; virtual const char *what() const noexcept final override { return ("Shape for Construction of Tensor is invalid. " + std::string(message)) .c_str(); } }; } // namespace exceptions } // namespace tensors #endif
28.415385
80
0.691933
Razdeep
f181881e8df62be95726c998d262bd3c1e562926
5,528
hpp
C++
code/w32/Delta.hpp
AndreLouisCaron/w32
75b26a149e268138cbcf43e6f4669756ac4ac850
[ "BSD-2-Clause" ]
9
2015-12-30T15:21:20.000Z
2021-03-21T04:23:14.000Z
code/w32/Delta.hpp
AndreLouisCaron/w32
75b26a149e268138cbcf43e6f4669756ac4ac850
[ "BSD-2-Clause" ]
1
2022-01-02T11:12:57.000Z
2022-01-02T11:12:57.000Z
code/w32/Delta.hpp
AndreLouisCaron/w32
75b26a149e268138cbcf43e6f4669756ac4ac850
[ "BSD-2-Clause" ]
5
2018-04-09T04:44:58.000Z
2020-04-10T12:51:51.000Z
#ifndef _w32_Delta_hpp__ #define _w32_Delta_hpp__ // Copyright (c) 2009-2012, Andre Caron (andre.l.caron@gmail.com) // 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. // // 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 w32/Delta.hpp * @brief Relative offsets for @c w32::Time instances. */ #include "__configure__.hpp" #include <w32/types.hpp> namespace w32 { //! @addtogroup w32 //! @{ /*! * @brief Relative offset for @c Time instances. * * The native resolution for time deltas is a 100 nanoseconds (1/10 of a * microsecond). Keep in mind that not all functions that accept a @c Time * instance support such a fine-grained resolution. Many operate at a * resolution larger than 1 millisecond. * * @see Time */ class Delta { /* class methods. */ public: /*! * @brief One microsecond (us) delta. */ static Delta microsecond (); /*! * @brief One millisecond (ms) delta. */ static Delta millisecond (); /*! * @brief One second (s) delta. */ static Delta second (); /*! * @brief One minute (m) delta. */ static Delta minute (); /*! * @brief One hour (h) delta. */ static Delta hour (); /*! * @brief One day (d) delta. */ static Delta day (); /*! * @brief One year (d) delta (365 days). * @see leap_year() */ static Delta year (); /*! * @brief One leap year (d) delta (366 days). * @see year() */ static Delta leap_year (); /* data. */ private: // Number of slices of 100 nanoseconds. qword myTicks; /* construction. */ public: /*! * @brief Create a null delta, represents "no offset". */ Delta (); private: // For internal use only. Delta ( qword ticks ); /* methods. */ public: /*! * @brief Get the delta as an integer multiple of the native resolution. * * @note The native resolution is 100 nanoseconds (1/10 us). */ qword ticks () const; dword microseconds () const; dword milliseconds () const; dword seconds () const; /* operators. */ public: /*! * @brief Compute an integer multiple of the delta. */ Delta& operator*= ( int rhs ); /*! * @brief Compute a multiple of the delta. */ Delta& operator*= ( double rhs ); /*! * @brief Compute an integer fraction of the delta. */ Delta& operator/= ( int rhs ); /*! * @brief Increase the time delta. */ Delta& operator+= ( const Delta& rhs ); /*! * @brief Decrease the time delta. */ Delta& operator-= ( const Delta& rhs ); }; /*! * @brief Increase the time delta. */ Delta operator+ ( const Delta& lhs, const Delta& rhs ); /*! * @brief Decrease the time delta. */ Delta operator- ( const Delta& lhs, const Delta& rhs ); /*! * @brief Compute an integer multiple of a delta. */ Delta operator* ( const Delta& lhs, int rhs ); /*! * @brief Compute an integer multiple of a delta. */ Delta operator* ( int lhs, const Delta& rhs ); /*! * @brief Compute a multiple of a delta. */ Delta operator* ( const Delta& lhs, double rhs ); /*! * @brief Compute a multiple of a delta. */ Delta operator* ( double lhs, const Delta& rhs ); /*! * @brief Compute an integer fraction of a delta. */ Delta operator/ ( const Delta& lhs, int rhs ); /*! * @brief Compute the relative size of two delta. */ double operator/ ( const Delta& lhs, const Delta& rhs ); bool operator> ( const Delta& lhs, const Delta& rhs ); bool operator< ( const Delta& lhs, const Delta& rhs ); bool operator<= ( const Delta& lhs, const Delta& rhs ); bool operator>= ( const Delta& lhs, const Delta& rhs ); //! @} } #endif /* _w32_Delta_hpp__ */
26.834951
80
0.577605
AndreLouisCaron
f187285a2755508662a53f8b5719f3edde0b0143
10,386
cpp
C++
util/stream/ios_ut.cpp
jjzhang166/balancer
84addf52873d8814b8fd30289f2fcfcec570c151
[ "Unlicense" ]
39
2015-03-12T19:49:24.000Z
2020-11-11T09:58:15.000Z
util/stream/ios_ut.cpp
jjzhang166/balancer
84addf52873d8814b8fd30289f2fcfcec570c151
[ "Unlicense" ]
null
null
null
util/stream/ios_ut.cpp
jjzhang166/balancer
84addf52873d8814b8fd30289f2fcfcec570c151
[ "Unlicense" ]
11
2016-01-14T16:42:00.000Z
2022-01-17T11:47:33.000Z
#include "ios.h" #include "glue.h" #include "tokenizer.h" #include <string> #include <iostream> #include <library/unittest/registar.h> #include <util/string/cast.h> #include <util/memory/tempbuf.h> #include <util/charset/recyr.hh> class TStreamsTest: public TTestBase { UNIT_TEST_SUITE(TStreamsTest); UNIT_TEST(TestGenericRead); UNIT_TEST(TestGenericWrite); UNIT_TEST(TestReadLine); UNIT_TEST(TestMemoryStream); UNIT_TEST(TestStreamBufAdaptor); UNIT_TEST(TestBufferedIO); UNIT_TEST(TestBufferStream); UNIT_TEST(TestTokenizer); UNIT_TEST(TestStringStream); UNIT_TEST(TestWtrokaInput); UNIT_TEST(TestWtrokaOutput); UNIT_TEST(TestIStreamOperators); UNIT_TEST_SUITE_END(); public: void TestGenericRead(); void TestGenericWrite(); void TestReadLine(); void TestMemoryStream(); void TestStreamBufAdaptor(); void TestBufferedIO(); void TestBufferStream(); void TestTokenizer(); void TestStringStream(); void TestWtrokaInput(); void TestWtrokaOutput(); void TestIStreamOperators(); }; UNIT_TEST_SUITE_REGISTRATION(TStreamsTest); void TStreamsTest::TestIStreamOperators() { Stroka data ("first line\r\nsecond\t\xd1\x82\xd0\xb5\xd1\x81\xd1\x82 line\r\n 1 -4 59 4320000000009999999 c\n -1.5 1e-110"); TStringInput si(data); Stroka l1; Stroka l2; Stroka l3; Wtroka w1; Stroka l4; ui16 i1; i16 i2; i32 i3; ui64 i4; char c1; unsigned char c2; float f1; double f2; si >> l1 >> l2 >> l3 >> w1 >> l4 >> i1 >> i2 >> i3 >> i4 >> c1 >> c2 >> f1 >> f2; UNIT_ASSERT_EQUAL(l1, "first"); UNIT_ASSERT_EQUAL(l2, "line"); { char buf[128]; size_t in_readed = 0; size_t out_writed = 0; RecodeFromUnicode(CODES_WIN, w1.c_str(), buf, w1.size(), sizeof(buf) - 1, in_readed, out_writed); buf[out_writed] = 0; UNIT_ASSERT_EQUAL(strcmp(buf, "\xf2\xe5\xf1\xf2"), 0); } UNIT_ASSERT_EQUAL(l3, "second"); UNIT_ASSERT_EQUAL(l4, "line"); UNIT_ASSERT_EQUAL(i1, 1); UNIT_ASSERT_EQUAL(i2, -4); UNIT_ASSERT_EQUAL(i3, 59); UNIT_ASSERT_EQUAL(i4, 4320000000009999999ULL); UNIT_ASSERT_EQUAL(c1, 'c'); UNIT_ASSERT_EQUAL(c2, '\n'); UNIT_ASSERT_EQUAL(f1, -1.5); UNIT_ASSERT_EQUAL(f2, 1e-110); } void TStreamsTest::TestStringStream() { TStringStream s; s << "qw\r\n1234" << "\n" << 34; UNIT_ASSERT_EQUAL(s.ReadLine(), "qw"); UNIT_ASSERT_EQUAL(s.ReadLine(), "1234"); s << "\r\n" << 123.1; UNIT_ASSERT_EQUAL(s.ReadLine(), "34"); UNIT_ASSERT_EQUAL(s.ReadLine(), "123.1"); UNIT_ASSERT_EQUAL(s.Str(), "qw\r\n1234\n34\r\n123.1"); } void TStreamsTest::TestGenericRead() { Stroka s("1234567890"); TStringInput si(s); char buf[1024]; UNIT_ASSERT_EQUAL(si.Read(buf, 6), 6); UNIT_ASSERT_EQUAL(memcmp(buf, "123456", 6), 0); UNIT_ASSERT_EQUAL(si.Read(buf, 6), 4); UNIT_ASSERT_EQUAL(memcmp(buf, "7890", 4), 0); } void TStreamsTest::TestGenericWrite() { Stroka s; TStringOutput so(s); so.Write("123456", 6); so.Write("7890", 4); UNIT_ASSERT_EQUAL(s, "1234567890"); } void TStreamsTest::TestReadLine() { Stroka data("1234\r\n5678\nqw"); TStringInput si(data); UNIT_ASSERT_EQUAL(si.ReadLine(), "1234"); UNIT_ASSERT_EQUAL(si.ReadLine(), "5678"); UNIT_ASSERT_EQUAL(si.ReadLine(), "qw"); } void TStreamsTest::TestMemoryStream() { char buf[1024]; TMemoryOutput mo(buf, sizeof(buf)); bool ehandled = false; try { for (size_t i = 0; i < sizeof(buf) + 1; ++i) { mo.Write(i % 127); } } catch (...) { ehandled = true; } UNIT_ASSERT_EQUAL(ehandled, true); for (size_t i = 0; i < sizeof(buf); ++i) { UNIT_ASSERT_EQUAL(buf[i], (char)(i % 127)); } } class TIO: public std::iostream { public: inline TIO(TStreamBufAdaptor* buf) : std::iostream(0) { std::istream::init(buf); std::ostream::init(buf); } }; void TStreamsTest::TestStreamBufAdaptor() { Stroka in("1234\r\n123456\r\n"); Stroka out; TStringInput si(in); TStringOutput so(out); { TStreamBufAdaptor strbuf(&si, 1024, &so, 1024); TIO io(&strbuf); std::string st; io >> st; UNIT_ASSERT_EQUAL(st, "1234"); io >> st; UNIT_ASSERT_EQUAL(st, "123456"); io << "qwerty"; io.flush(); io << "123456"; } UNIT_ASSERT_EQUAL(out, "qwerty123456"); } class TMyStringOutput: public TOutputStream { public: inline TMyStringOutput(Stroka& s, size_t buflen) throw () : S_(s) , BufLen_(buflen) { } virtual ~TMyStringOutput() throw () { } virtual void DoWrite(const void* data, size_t len) { S_.Write(data, len); UNIT_ASSERT(len < BufLen_ || ((len % BufLen_) == 0)); } virtual void DoWriteV(const TPart* p, size_t count) { Stroka s; for (size_t i = 0; i < count; ++i) { s.append((const char*)p[i].buf, p[i].len); } DoWrite(~s, +s); } private: TStringOutput S_; const size_t BufLen_; }; void TStreamsTest::TestBufferedIO() { Stroka s; { const size_t buflen = 7; TBuffered<TMyStringOutput> bo(buflen, s, buflen); for (size_t i = 0; i < 1000; ++i) { Stroka str(" "); str += ToString(i % 10); bo.Write(~str, +str); } bo.Finish(); } UNIT_ASSERT_EQUAL(+s, 2000); { const size_t buflen = 11; TBuffered<TStringInput> bi(buflen, s); for (size_t i = 0; i < 1000; ++i) { Stroka str(" "); str += ToString(i % 10); char buf[3]; UNIT_ASSERT_EQUAL(bi.Load(buf, 2), 2); buf[2] = 0; UNIT_ASSERT_EQUAL(str, buf); } } s.clear(); { const size_t buflen = 13; TBuffered<TMyStringOutput> bo(buflen, s, buflen); Stroka f = "1234567890"; for (size_t i = 0; i < 10; ++i) { f += f; } for (size_t i = 0; i < 1000; ++i) { bo.Write(~f, i); } bo.Finish(); } } void TStreamsTest::TestBufferStream() { TBufferStream stream; Stroka s = "test"; stream.Write(~s, +s); char buf[5]; size_t readed = stream.Read(buf, 4); UNIT_ASSERT_EQUAL(4, readed); UNIT_ASSERT_EQUAL(0, strncmp(~s, buf, 4)); stream.Write(~s, +s); readed = stream.Read(buf, 2); UNIT_ASSERT_EQUAL(2, readed); UNIT_ASSERT_EQUAL(0, strncmp("te", buf, 2)); readed = stream.Read(buf, 2); UNIT_ASSERT_EQUAL(2, readed); UNIT_ASSERT_EQUAL(0, strncmp("st", buf, 2)); readed = stream.Read(buf, 2); UNIT_ASSERT_EQUAL(0, readed); } struct TTestEof { inline bool operator() (char ch) const throw () { return ch == '\n'; } }; void TStreamsTest::TestTokenizer() { const Stroka parts[] = { "qwerty", "1234567890" }; const size_t count = sizeof(parts) / sizeof(*parts); Stroka s; for (size_t i = 0; i < count; ++i) { s += parts[i]; s += "\n"; } TMemoryInput mi(~s, +s); typedef TStreamTokenizer<TTestEof> TTokenizer; TTokenizer tokenizer(&mi); size_t cur = 0; for (TTokenizer::TIterator it = tokenizer.Begin(); it != tokenizer.End(); ++it) { UNIT_ASSERT(cur < count); UNIT_ASSERT_EQUAL(Stroka(it->Data(), it->Length()), parts[cur]); ++cur; } } #if defined (_MSC_VER) # pragma warning(disable:4309) /*truncation of constant value*/ #endif namespace { const char Text[] = { // UTF8 encoded "one \ntwo\r\nthree\n\tfour\nfive\n" in russian and ... 0xD1, 0x80, 0xD0, 0xB0, 0xD0, 0xB7, ' ', '\n', 0xD0, 0xB4, 0xD0, 0xB2, 0xD0, 0xB0, '\r', '\n', 0xD1, 0x82, 0xD1, 0x80, 0xD0, 0xB8, '\n', '\t', 0xD1, 0x87, 0xD0, 0xB5, 0xD1, 0x82, 0xD1, 0x8B, 0xD1, 0x80, 0xD0, 0xB5, '\n', 0xD0, 0xBF, 0xD1, 0x8F, 0xD1, 0x82, 0xD1, 0x8C, '\n', // ... additional test cases '\r', '\n', '\n', '\r', // this char goes to the front of the next string 'o', 'n', 'e', ' ', 't', 'w', 'o', '\n', '1', '2', '3', '\r', '\n', '\t', '\r', ' ', 0 }; const char Expected[][20] = { // UTF8 encoded "one ", "two", "three", "\tfour", "five" in russian and ... { 0xD1, 0x80, 0xD0, 0xB0, 0xD0, 0xB7, 0x20, 0x00 }, { 0xD0, 0xB4, 0xD0, 0xB2, 0xD0, 0xB0, 0x00 }, { 0xD1, 0x82, 0xD1, 0x80, 0xD0, 0xB8, 0x00 }, { 0x09, 0xD1, 0x87, 0xD0, 0xB5, 0xD1, 0x82, 0xD1, 0x8B, 0xD1, 0x80, 0xD0, 0xB5, 0x00 }, { 0xD0, 0xBF, 0xD1, 0x8F, 0xD1, 0x82, 0xD1, 0x8C, 0x00 }, // ... additional test cases { 0x00 }, { 0x00 }, { '\r', 'o', 'n', 'e', ' ', 't', 'w', 'o' }, { '1', '2', '3' }, { '\t', '\r', ' ' } }; } void TStreamsTest::TestWtrokaInput() { TTempBuf buffer(sizeof(Text) * sizeof(wchar16)); wchar16* const data = (wchar16*)buffer.Data(); const Stroka s(Text); TStringInput is(s); Wtroka w; size_t i = 0; while (is.ReadLine(w)) { UNIT_ASSERT(i < sizeof(Expected) / sizeof(Expected[0])); size_t read = 0, written = 0; RecodeToUnicode(CODES_UTF8, Expected[i], data, strlen(Expected[i]), sizeof(Text) - 1, read, written); data[written] = 0; UNIT_ASSERT(w == data); ++i; } } void TStreamsTest::TestWtrokaOutput() { Stroka s; TStringOutput os(s); const size_t n = sizeof(Expected) / sizeof(Expected[0]); for (size_t i = 0; i < n; ++i) { const size_t len = strlen(Expected[i]); Wtroka w((int)len); size_t read = 0, written = 0; RecodeToUnicode(CODES_UTF8, Expected[i], w.begin(), len, len, read, written); w.remove(written); os << w; if (i == 1 || i == 5 || i == 8) os << '\r'; if (i < n - 1) os << '\n'; } UNIT_ASSERT(s == Text); }
25.208738
128
0.547083
jjzhang166
f18e4b27b552d210e912eaf35ef4a0d5efb20573
1,030
cpp
C++
Source/GUI/Submenus/HUD.cpp
HatchesPls/GrandTheftAutoV-Cheat
f06011362a0a8297439b260a670f5091118ef5de
[ "curl", "MIT" ]
31
2021-07-13T21:24:58.000Z
2022-03-31T13:04:38.000Z
Source/GUI/Submenus/HUD.cpp
HatchesPls/GrandTheftAutoV-Cheat
f06011362a0a8297439b260a670f5091118ef5de
[ "curl", "MIT" ]
12
2021-07-28T16:53:58.000Z
2022-03-31T22:51:03.000Z
Source/GUI/Submenus/HUD.cpp
HowYouDoinMate/GrandTheftAutoV-Cheat
1a345749fc676b7bf2c5cd4df63ed6c9b80ff377
[ "curl", "MIT" ]
12
2020-08-16T15:57:52.000Z
2021-06-23T13:08:53.000Z
#include "../Header/Cheat Functions/FiberMain.h" using namespace Cheat; int HUDColorRed, HUDColorGreen, HUDColorBlue, HUDColorAlpha; void GUI::Submenus::HUD() { GUI::Title("HUD"); GUI::Toggle("Disable HUD", CheatFeatures::DisableHUDBool, "Prevents all HUD elements from being visible"); GUI::Toggle("Hide Minimap", CheatFeatures::HideMinimapBool, "Not needed when Disable HUD is enabled"); GUI::Break("Color", SELECTABLE_CENTER_TEXT); GUI::Int("Red", HUDColorRed, 0, 255, 1, "", SELECTABLE_DISABLE_SAVE | SELECTABLE_RETURN_VALUE_CHANGE); GUI::Int("Green", HUDColorGreen, 0, 255, 1, "", SELECTABLE_DISABLE_SAVE | SELECTABLE_RETURN_VALUE_CHANGE); GUI::Int("Blue", HUDColorBlue, 0, 255, 1, "", SELECTABLE_DISABLE_SAVE | SELECTABLE_RETURN_VALUE_CHANGE); GUI::Int("Alpha", HUDColorAlpha, 0, 255, 1, "", SELECTABLE_DISABLE_SAVE | SELECTABLE_RETURN_VALUE_CHANGE); if (GUI::Option("Change", "")) { for (int i = 0; i <= 223; i++) { UI::_SET_HUD_COLOUR(i, HUDColorRed, HUDColorGreen, HUDColorBlue, HUDColorAlpha); } } }
46.818182
107
0.73301
HatchesPls
f1939d344d0611eefaf236413473731281bb235f
15,136
cpp
C++
DotGenerator2.cpp
PollyP/TraceVizPintool
0c76e660834c6b77ffe944169d4afbd04e16ed0a
[ "MIT" ]
6
2020-04-25T12:45:52.000Z
2021-12-15T01:24:54.000Z
DotGenerator2.cpp
PollyP/TraceVizPintool
0c76e660834c6b77ffe944169d4afbd04e16ed0a
[ "MIT" ]
5
2020-04-17T21:03:30.000Z
2020-04-24T20:17:28.000Z
DotGenerator2.cpp
PollyP/TraceVizPintool
0c76e660834c6b77ffe944169d4afbd04e16ed0a
[ "MIT" ]
null
null
null
/*** Copyright 2020 P.S.Powledge Permission is hereby granted, free of charge, to any person obtaining a copy of this softwareand 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 noticeand 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 <algorithm> #include <assert.h> #include <fstream> #include <sstream> #include <map> #include <set> #include <string> #include <vector> #include "DotGenerator2.h" using namespace std; extern ofstream logfile; extern string get_filename(string pathplusfname); extern string truncate_string(string inputs, int new_length);; extern void find_and_replace_all(string& data, string replacee, string replacer); /********************************************************************************************************************************** * * * Section2Color: map section indexes to colors * * * /*********************************************************************************************************************************/ Section2ColorPtr Section2Color::inst = NULL; const string Section2Color::colors[] = { "yellow", "pink", "lightblue", "orange", "green", "tan", }; Section2Color *Section2Color::getInstance() { if (Section2Color::inst == NULL) { Section2Color::inst = new Section2Color(); } return Section2Color::inst; } string Section2Color::getColor(int section_idx) { int idx = section_idx % Section2Color::colors->length(); return Section2Color::inst->colors[idx]; } /********************************************************************************************************************************** * * * NodeItem: class to hold info about nodes * * * /*********************************************************************************************************************************/ ostream& operator<<(ostream& os, const DotNodeItem& n) { os << " nodeid: " << n.nodeid << " label " << n.label << " color: " << n.color ; return os; } /********************************************************************************************************************************** * * * NodeManager: class to manage nodes * * * /*********************************************************************************************************************************/ DotNodeManager::DotNodeManager() { this->node_counter = 0; } DotNodeManager::~DotNodeManager() { this->node_counter = 0; // clean up the heap from all the internally-created (ie placeholder) nodes // note: the class that added nodes via addNode() is responsible for reclaiming that heap. for (auto n : this->placeholder_nodes) { delete n; } } vector<int> DotNodeManager::getTids() { vector<int> ret; for (map<int, string>::iterator it = this->tidlist.begin(); it != this->tidlist.end(); ++it) { ret.push_back(it->first); } sort(ret.begin(), ret.end()); return ret; } void DotNodeManager::addNode(DotNodeItemPtr n) { this->tidlist[n->tid] = ""; this->node_map[this->node_counter] = n; this->node_counter++; } vector<DotNodeItemPtr> DotNodeManager::getNodes() { vector<DotNodeItemPtr> ret; for (pair<int, DotNodeItemPtr> element : this->node_map) { DotNodeItemPtr n = element.second; ret.push_back(n); } return ret; } vector<DotNodeItemPtr> DotNodeManager::getNodesForTid(int tid) { vector<DotNodeItemPtr> ret; for (pair<int, DotNodeItemPtr> element : this->node_map) { int node_idx = element.first; DotNodeItemPtr n = element.second; // does this node come from this tid? if (n->tid != tid) { // no, generate a placeholder node first n = this->getPlaceholderNode(tid, node_idx); } ret.push_back(n); } return ret; } vector<pair<DotNodeItemPtr,DotNodeItemPtr>> DotNodeManager::getNodesThatJumpTids() { vector<pair<DotNodeItemPtr,DotNodeItemPtr>> ret; for (pair<int, DotNodeItemPtr> kv : this->node_map) { int i = kv.first; DotNodeItemPtr n = kv.second; if (this->node_map.find(i + 1) != this->node_map.end()) { DotNodeItemPtr nextnode = this->node_map[i + 1]; if (n->tid != nextnode->tid) { pair<DotNodeItemPtr, DotNodeItemPtr> apair = { n, nextnode }; ret.push_back(apair); } } } return ret; } DotNodeItemPtr DotNodeManager::getPlaceholderNode(int tid, int node_idx) { // build unique node id stringstream ss; ss << "cluster_" << tid << "_node_" << node_idx; // create the nodeitem // heap management is in class dtor DotNodeItemPtr ret = new DotNodeItem(tid, ss.str(), "placeholder", "red"); ret->isplaceholder = true; // add the placeholder node on a list so we can reclaim the heap this->placeholder_nodes.push_back(ret); return ret; } ostream& operator<<(ostream& os, DotNodeManager& nm) { os << "nm state:\n"; os << "\tnode counter: " << nm.node_counter << "\n"; vector<int> tids = nm.getTids(); os << "\ttid count = " << tids.size() << "\n"; for (auto t : tids) { os << "\ttid = " << t << "\n"; vector<DotNodeItemPtr> nodes = nm.getNodesForTid(t); for (auto n : nodes) { os << "\t\t" << *n << "\n"; } } return os; } /********************************************************************************************************************************** * * * DotGenerator2: class to generate the dot file * * * /*********************************************************************************************************************************/ DotGenerator::DotGenerator(const char * fname, const char *comment) { this->fname = fname; this->file_output.open(this->fname.c_str(), ios::out | ios::trunc); if (this->file_output.is_open() != true) { logfile << "could not open " << fname << endl; return; } this->node_manager = new DotNodeManager(); assert(this->node_manager != NULL); this->sections2colors = Section2Color::getInstance(); this->file_output << "digraph {" << endl; this->file_output << "\t# " << comment << endl; this->file_output << "\tlabel=\"" << comment << "\";" << endl; this->file_output << "\tcompound=true;" << endl; this->file_output << "\tedge[style=\"invis\"];" << endl; this->file_output << "\tnode [shape=rectangle, style=filled, height=1.5, width=6.0, fixedsize=true, margin=.25]; # units=inches" << endl; this->file_output << endl; } DotGenerator::~DotGenerator() { // finish writing output file this->closeOutputFile(); // clean up heap'ed memory vector<DotNodeItemPtr> nodes = this->node_manager->getNodes(); for (auto n : nodes) { delete n; } // clean up heap'ed memory, part two delete this->node_manager; } void DotGenerator::addNewImage(int tid, string imgname, int secidx, ADDRINT start_address ) { // build a unique node id string node_id = this->buildNodeId(tid); // build a label for the node string filename = get_filename(imgname); find_and_replace_all(imgname, "\\", "\\\\"); string trunc_imgname = truncate_string(imgname, max_imgname_len); stringstream ss2; ss2 << "image load: mapped " << filename << " to " << hex << showbase << start_address << "\\lfull path: " << trunc_imgname << "\\l"; string label = ss2.str(); // turn this into a node and add it to our nodemanager DotNodeItemPtr n = new DotNodeItem(tid, node_id, label, "lightgray"); assert(n != NULL); this->addImageLoadNode(n); } void DotGenerator::addNewLibCall(int tid, string symbol, string imgname, int secidx, ADDRINT addr, string calling_address, string details) { // if there's a lot of text, make the node larger bool needsLargeNode = false; if (details != "") { needsLargeNode = true; } // build a unique node id string node_id = this->buildNodeId(tid); // build a label for the node string filename = get_filename(imgname); find_and_replace_all(imgname, "\\", "\\\\"); string trunc_imgname = truncate_string(imgname, max_imgname_len); string trunc_symbol = truncate_string(symbol, max_symbol_len); stringstream ss2; ss2 << "library call from " << calling_address << " \\l" << trunc_symbol << " (" << hex << showbase << addr << ", " << filename << ") \\l" << "full path: " << trunc_imgname << " \\l"; ss2 << details; string label = ss2.str(); // map the section idx to a background color string color = this->sections2colors->getColor(secidx); // turn this into a node and add it to our nodemanager DotNodeItemPtr n = new DotNodeItem(tid, node_id, label, color); assert(n != NULL); if (needsLargeNode) { this->addLargeLibCallNode(n); } else { this->addLibCallNode(n); } } string DotGenerator::formatDetailsLines(vector<string> input_strings) { stringstream ss; for (auto is : input_strings) { ss << is << "\\l"; } return ss.str(); } void DotGenerator::closeOutputFile() { if (this->file_output.is_open()) { this->buildClusters(); this->file_output << "}" << endl; this->file_output.close(); } } void DotGenerator::buildClusters() { // for every thread we saw ... vector<int> tids = this->node_manager->getTids(); for (const auto tid : tids) { // get the nodes associated with that thread vector<DotNodeItemPtr> nodes = this->node_manager->getNodesForTid(tid); if (nodes.size() == 0) { continue; } // turn the nodes into a cluster // step 1. build cluster header stringstream ss; ss << "cluster_" << tid; string cluster_id = ss.str(); this->file_output << endl; this->file_output << "\tsubgraph " << cluster_id << " {" << endl; this->file_output << "\t\t# " << cluster_id << endl; this->file_output << "\t\tlabel=\"thread #" << tid << "\"" << endl; // step 2. xdot doesn't give you a way to line up the nodes // as a grid, so I create placeholder nodes to get things to // line up. yes, it's a horrible hack. :( anyway, i need to first // define the placeholder nodes in the cluster. this->file_output << "\t\t# placeholder nodes" << endl; for (int i = 0; i < (int)nodes.size(); i++) { if (nodes[i]->isplaceholder) { this->file_output << "\t\tnode [label=\"" << nodes[i]->label << "\", style=invis, fillcolor=\"" << nodes[i]->color << "\", height=1.25] " << nodes[i]->nodeid << ";" << endl; } } // step 3. link up the nodes in this cluster. stringstream ss2; ss2 << "\t\t" << nodes.front()->nodeid; for ( int i = 1 ; i < (int)nodes.size() ; i++ ) { ss2 << " -> " << nodes[i]->nodeid << " "; } // step 4. build cluster tail this->file_output << ss2.str() << ";" << endl; this->file_output << "\t} # subgraph for " << cluster_id << endl; } // is the application multithreaded? If so make the various threads line us nicely in the output // by building links for each node in thread x that is followed by a node in thread y vector<pair<DotNodeItemPtr,DotNodeItemPtr>> jumppairs = this->node_manager->getNodesThatJumpTids(); if ( jumppairs.size() > 0 ) { this->file_output << "\n\n\t# thread jumps" << endl; for (const auto jumppair : jumppairs) { // xdot builds really strange diagrams when you have descendent clusters linking back to ancestor clusters. leave them out. //if (true) if (jumppair.first->nodeid < jumppair.second->nodeid) { this->file_output << "\t" << jumppair.first->nodeid << " -> " << jumppair.second->nodeid << ";" << endl; } } } } // build a unique node id string DotGenerator::buildNodeId(int tid) { stringstream ss; ss << "cluster_" << tid << "_node_" << this->node_manager->node_counter; return ss.str(); } // write this node to file output and add it to the node manager for later clustering/linking. void DotGenerator::addImageLoadNode(DotNodeItemPtr n) { this->file_output << "\tnode [label=\"" << n->label << "\", style=\"filled, rounded\", fillcolor=\"" << n->color << "\", height=0.75] " << n->nodeid << ";" << endl; this->node_manager->addNode(n); } // write this node to file output and add it to the node manager for later clustering/linking. void DotGenerator::addLargeLibCallNode(DotNodeItemPtr n) { this->file_output << "\tnode [label=\"" << n->label << "\", style=filled, fillcolor=\"" << n->color << "\", height=1.25] " << n->nodeid << ";" << endl; this->node_manager->addNode(n); } // write this node to file output and add it to the node manager for later clustering/linking. void DotGenerator::addLibCallNode(DotNodeItemPtr n) { this->file_output << "\tnode [label=\"" << n->label << "\", style=filled, fillcolor=\"" << n->color << "\", height=1.0] " << n->nodeid << ";" << endl; this->node_manager->addNode(n); } // dump the state to an ostream inline ostream& operator<<(ostream& os, const DotGenerator& dg) { os << "dg state:\n"; os << "\tfname: " << dg.fname; os << "\tnm: " << *(dg.node_manager); return os; }
34.636156
185
0.544662
PollyP
f1968e5e82d78cd2ab6a7204e17c7b55d9f51753
202
cpp
C++
ue4_c++/1/bp2/bp2.cpp
mohamadem60mdem/a5
c6f53364cc148862129acd1c6334d104f5e6bef3
[ "MIT" ]
null
null
null
ue4_c++/1/bp2/bp2.cpp
mohamadem60mdem/a5
c6f53364cc148862129acd1c6334d104f5e6bef3
[ "MIT" ]
null
null
null
ue4_c++/1/bp2/bp2.cpp
mohamadem60mdem/a5
c6f53364cc148862129acd1c6334d104f5e6bef3
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "bp2.h" #include "Modules/ModuleManager.h" IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, bp2, "bp2" );
28.857143
78
0.787129
mohamadem60mdem
1af940e1d38d3161c5216d6fae8d230388d44cce
18,618
cpp
C++
hi_snex/unit_test/snex_jit_IndexTest.cpp
Matt-Dub/HISE
ae2dd1653e1c8d749a9088edcd573de6252b0b96
[ "Intel" ]
null
null
null
hi_snex/unit_test/snex_jit_IndexTest.cpp
Matt-Dub/HISE
ae2dd1653e1c8d749a9088edcd573de6252b0b96
[ "Intel" ]
null
null
null
hi_snex/unit_test/snex_jit_IndexTest.cpp
Matt-Dub/HISE
ae2dd1653e1c8d749a9088edcd573de6252b0b96
[ "Intel" ]
null
null
null
/* =========================================================================== * * This file is part of HISE. * Copyright 2016 Christoph Hart * * HISE 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. * * HISE 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 HISE. If not, see <http://www.gnu.org/licenses/>. * * Commercial licences for using HISE in an closed source project are * available on request. Please visit the project's website to get more * information about commercial licencing: * * http://www.hartinstruments.net/hise/ * * HISE is based on the JUCE library, * which also must be licenced for commercial applications: * * http://www.juce.com * * =========================================================================== */ namespace snex { namespace jit { using namespace juce; #define TEST_ALL_INDEXES 1 template <typename IndexType> struct IndexTester { using Type = typename IndexType::Type; static constexpr int Limit = IndexType::LogicType::getUpperLimit(); static constexpr bool isLoopTest() { return std::is_same<index::looped_logic<Limit>, typename IndexType::LogicType>(); } IndexTester(UnitTest* test_, StringArray opt, int dynamicSize = 0) : test(*test_), indexName(IndexType::toString()), optimisations(opt), ArraySize(Limit != 0 ? Limit : dynamicSize) { test.beginTest("Testing " + indexName); runTest(); } private: const int ArraySize; const String indexName; void runTest() { testLoopRange(0.0, 0.0); testLoopRange(0.0, 1.0); testLoopRange(0.5, 1.0); testLoopRange(0.3, 0.6); #if TEST_ALL_INDEXES testIncrementors(FunctionClass::SpecialSymbols::IncOverload); testIncrementors(FunctionClass::SpecialSymbols::DecOverload); testIncrementors(FunctionClass::SpecialSymbols::PostIncOverload); testIncrementors(FunctionClass::SpecialSymbols::PostDecOverload); testAssignAndCast(); testFloatAlphaAndIndex(); testSpanAccess(); testDynAccess(); #endif testInterpolators(); } Range<int> getLoopRange(double nStart, double nEnd) { auto s = roundToInt(jlimit(0.0, 1.0, nStart) * (double)Limit); auto e = roundToInt(jlimit(0.0, 1.0, nEnd) * (double)Limit); return Range<int>(s, e); } String getLoopRangeCode(double start, double end) { auto l = getLoopRange(start, end); String c; c << ".setLoopRange(" << l.getStart() << ", " << l.getEnd() << ");"; return c; } void testLoopRange(double normalisedStart, double normalisedEnd) { if constexpr (isLoopTest() && IndexType::LogicType::hasBoundCheck()) { cppgen::Base c(cppgen::Base::OutputType::AddTabs); span<Type, Limit> data; String spanCode; initialiseSpan(spanCode, data); c << indexName << " i;"; c << spanCode; c << "T test(T input)"; { cppgen::StatementBlock sb(c); c << "i" << getLoopRangeCode(normalisedStart, normalisedEnd); c << "i = input;"; c << "return data[i];"; } test.logMessage("Testing loop range " + indexName + getLoopRangeCode(normalisedStart, normalisedEnd)); c.replaceWildcard("T", Types::Helpers::getTypeNameFromTypeId<Type>()); auto obj = compile(c.toString()); // Test Routine ============================================== auto testWithValue = [&](Type testValue) { IndexType i; auto lr = getLoopRange(normalisedStart, normalisedEnd); i.setLoopRange(lr.getStart(), lr.getEnd()); i = testValue; auto expected = data[i]; auto actual = obj["test"].template call<Type>(testValue); String message = indexName; message << " with value " << String(testValue); test.expectWithinAbsoluteError(actual, expected, Type(0.0001), message); }; // Test List ======================================================= testWithValue(0.5); #if SNEX_WRAP_ALL_NEGATIVE_INDEXES testWithValue(-1.5); #endif testWithValue(20.0); testWithValue(-1); testWithValue(Limit * 0.99); testWithValue(Limit * 1.2); testWithValue(Limit * 141.2); testWithValue(Limit * 8141.92); testWithValue(0.3); testWithValue(8.0); testWithValue(Limit / 3); } } void testInterpolators() { if constexpr (!IndexType::canReturnReference() && IndexType::LogicType::hasBoundCheck()) { // Test Code =================================================== cppgen::Base c(cppgen::Base::OutputType::AddTabs); span<Type, Limit> data; String spanCode; initialiseSpan(spanCode, data); c << indexName + " i;"; c << spanCode; c << "T test(T input)"; { cppgen::StatementBlock sb(c); c << "i = input;"; c << "i.setLoopRange(0, 0);"; c << "return data[i];"; } test.logMessage("Testing interpolator " + indexName); c.replaceWildcard("T", Types::Helpers::getTypeNameFromTypeId<Type>()); auto obj = compile(c.toString()); // Test Routine ============================================== auto testWithValue = [&](Type testValue) { IndexType i; i = testValue; auto expected = data[i]; auto actual = obj["test"].template call<Type>(testValue); String message = indexName; message << " with value " << String(testValue); test.expectWithinAbsoluteError(actual, expected, Type(0.0001), message); }; // Test List ======================================================= testWithValue(0.5); #if SNEX_WRAP_ALL_NEGATIVE_INDEXES testWithValue(-1.5); #endif testWithValue(20.0); testWithValue(Limit * 0.99); testWithValue(Limit * 1.2); testWithValue(0.3); testWithValue(8.0); testWithValue(Limit / 3); } } void testSpanAccess() { if constexpr (Limit != 0 && !isInterpolator()) { // Test Code =================================================== cppgen::Base c(cppgen::Base::OutputType::AddTabs); span<int, Limit> data; String spanCode; initialiseSpan(spanCode, data); c << spanCode; c << indexName + " i;"; c << "int test(T input)"; { cppgen::StatementBlock sb(c); c.addWithSemicolon("i = input;"); c.addWithSemicolon("return data[i];"); } c << "int test2(T input)"; { cppgen::StatementBlock sb(c); c << "i = input;"; c << "data[i] = (T)50;"; c << "return data[i];"; } test.logMessage("Testing " + indexName + " span[]"); c.replaceWildcard("T", Types::Helpers::getTypeNameFromTypeId<Type>()); auto obj = compile(c.toString()); // Test Routine ============================================== auto testWithValue = [&](Type testValue) { if (IndexType::LogicType::hasBoundCheck()) { IndexType i; i = testValue; auto expectedValue = data[i]; auto actualValue = obj["test"].template call<int>(testValue); String m = indexName; m << "::operator[]"; m << " with value " << String(testValue); test.expectEquals(actualValue, expectedValue, m); data[i] = Type(50); auto e2 = data[i]; auto a2 = obj["test2"].template call<int>(testValue); m << "(write access)"; test.expectEquals(e2, a2, m); } else { test.logMessage("skip [] access for unsafe index"); } }; // Test List ======================================================= if (std::is_floating_point<Type>()) { testWithValue(0.5); testWithValue(Limit + 0.5); testWithValue(Limit / 3.f); testWithValue(-0.5 * Limit); } else { testWithValue(80); testWithValue(Limit); testWithValue(Limit - 1); testWithValue(-1); testWithValue(0); testWithValue(1); testWithValue(Limit + 1); testWithValue(-Limit + 1); } } } void testDynAccess() { if constexpr (!isInterpolator()) { // Test Code =================================================== heap<int> data; data.setSize(ArraySize); cppgen::Base c(cppgen::Base::OutputType::AddTabs); String spanCode; initialiseSpan(spanCode, data); dyn<int> d; d.referTo(data); c << spanCode; c << "dyn<int> d;"; c << indexName + " i;"; c << "int test(XXX input)"; { cppgen::StatementBlock sb(c); c << "d.referTo(data);"; c << "i = input;"; c << "return d[i];"; } test.logMessage("Testing " + indexName + " dyn[]"); c.replaceWildcard("XXX", Types::Helpers::getTypeNameFromTypeId<Type>()); auto obj = compile(c.toString()); // Test Routine ============================================== auto testWithValue = [&](Type testValue) { if (IndexType::LogicType::hasBoundCheck()) { IndexType i; i = testValue; auto expectedValue = d[i]; auto actualValue = obj["test"].template call<int>(testValue); String m = indexName; m << "::operator[]"; m << "(dyn) with value " << String(testValue); test.expectEquals(actualValue, expectedValue, m); } else { test.logMessage("skip [] access for unsafe index"); } }; // Test List ======================================================= if (std::is_floating_point<Type>()) { testWithValue(0.5); testWithValue(Limit + 0.5); testWithValue(Limit / 3.f); #if SNEX_WRAP_ALL_NEGATIVE_INDEXES testWithValue(-12.215 * Limit); #endif } else { testWithValue(80); testWithValue(Limit); testWithValue(Limit - 1); testWithValue(-1); testWithValue(0); testWithValue(1); testWithValue(Limit + 1); testWithValue(-Limit + 1); } } } template <typename Container> void initialiseSpan(String& asCode, Container& data) { auto elementType = Types::Helpers::getTypeFromTypeId<typename Container::DataType>(); asCode << "span<" << Types::Helpers::getTypeName(elementType) << ", " << ArraySize << "> data = { "; for (int i = 0; i < ArraySize; i++) { asCode << Types::Helpers::getCppValueString(var(i), elementType) << ", "; data[i] = (typename Container::DataType)i; } asCode = asCode.upToLastOccurrenceOf(", ", false, false); asCode << " };"; } static constexpr bool isInterpolator() { return !IndexType::canReturnReference(); } static constexpr bool hasDynamicBounds() { return IndexType::LogicType::hasDynamicBounds(); } void testFloatAlphaAndIndex() { if constexpr (std::is_floating_point<Type>() && !isInterpolator()) { if constexpr (hasDynamicBounds()) { // Test Code =================================================== cppgen::Base c(cppgen::Base::OutputType::AddTabs); c << indexName + " i;"; c << "T testAlpha(T input, int limit)"; { cppgen::StatementBlock sb(c); c.addWithSemicolon("i = input;"); c.addWithSemicolon("return i.getAlpha(limit);"); } c << "int testIndex(T input, int delta, int limit)"; { cppgen::StatementBlock sb(c); c.addWithSemicolon("i = input;"); c.addWithSemicolon("return i.getIndex(limit, delta);"); } test.logMessage("Testing " + indexName + "::getAlpha"); c.replaceWildcard("T", Types::Helpers::getTypeNameFromTypeId<Type>()); auto obj = compile(c.toString()); // Test Routine ============================================== auto testWithValue = [&](Type testValue, int deltaValue, int limit) { IndexType i; i = testValue; auto expectedAlpha = i.getAlpha(limit); auto actualAlpha = obj["testAlpha"].template call<Type>(testValue, limit); String am = indexName; am << "::getAlpha()"; am << " with value " << String(testValue); test.expectWithinAbsoluteError(actualAlpha, expectedAlpha, Type(0.00001), am); auto expectedIndex = i.getIndex(limit, deltaValue); auto actualIndex = obj["testIndex"].template call<int>(testValue, deltaValue, limit); String im = indexName; im << "::getIndex()"; im << " with value " << String(testValue) << " and delta " << String(deltaValue); test.expectEquals(actualIndex, expectedIndex, im); }; // Test List ======================================================= testWithValue(0.51, 0, 48); testWithValue(12.3, 0, 64); testWithValue(-0.52, -1, 91); testWithValue(Limit - 0.44, 2, 10); testWithValue(Limit + 25.2, 1, 16); testWithValue(Limit / 0.325 - 1, 9, 1); testWithValue(Limit * 9.029, 4, 2); testWithValue(Limit * -0.42, Limit + 2, 32); testWithValue(324.42, -Limit + 2, 57); } else { // Test Code =================================================== cppgen::Base c(cppgen::Base::OutputType::AddTabs); c << indexName + " i;"; c << "T testAlpha(T input)"; { cppgen::StatementBlock sb(c); c.addWithSemicolon("i = input;"); c.addWithSemicolon("return i.getAlpha(0);"); } c << "int testIndex(T input, int delta)"; { cppgen::StatementBlock sb(c); c.addWithSemicolon("i = input;"); c.addWithSemicolon("return i.getIndex(0, delta);"); } test.logMessage("Testing " + indexName + "::getAlpha"); c.replaceWildcard("T", Types::Helpers::getTypeNameFromTypeId<Type>()); auto obj = compile(c.toString()); // Test Routine ============================================== auto testWithValue = [&](Type testValue, int deltaValue) { IndexType i; i = testValue; auto expectedAlpha = i.getAlpha(0); auto actualAlpha = obj["testAlpha"].template call<Type>(testValue); String am = indexName; am << "::getAlpha()"; am << " with value " << String(testValue); test.expectWithinAbsoluteError(actualAlpha, expectedAlpha, Type(0.00001), am); auto expectedIndex = i.getIndex(0, deltaValue); auto actualIndex = obj["testIndex"].template call<int>(testValue, deltaValue); String im = indexName; im << "::getIndex()"; im << " with value " << String(testValue) << " and delta " << String(deltaValue); test.expectEquals(actualIndex, expectedIndex, im); }; // Test List ======================================================= testWithValue(0.51, 0); testWithValue(12.3, 0); testWithValue(-0.52, -1); testWithValue(Limit - 0.44, 2); testWithValue(Limit + 25.2, 1); testWithValue(Limit / 0.325 - 1, 9); testWithValue(Limit * 9.029, 4); testWithValue(Limit * 0.42, Limit + 2); testWithValue(324.42, -Limit + 2); } } } void testIncrementors(FunctionClass::SpecialSymbols incType) { if constexpr (std::is_integral<Type>() && !IndexType::LogicType::hasDynamicBounds()) { // Test Code =================================================== cppgen::Base c(cppgen::Base::OutputType::AddTabs); c << indexName + " i;"; c << "int test(int input)"; String op; { cppgen::StatementBlock sb(c); c.addWithSemicolon("i = input"); switch (incType) { case FunctionClass::IncOverload: op = "++i;"; break; case FunctionClass::PostIncOverload: op = "i++;"; break; case FunctionClass::DecOverload: op = "--i;"; break; case FunctionClass::PostDecOverload: op = "i--;"; break; default: op = ""; break; } c.addWithSemicolon("return (int)" + op); } test.logMessage("Testing " + indexName + "::" + FunctionClass::getSpecialSymbol({}, incType).toString()); auto obj = compile(c.toString()); // Test Routine ============================================== auto testWithValue = [&](int testValue) { IndexType i; i = testValue; int expected; switch (incType) { case FunctionClass::IncOverload: expected = (int)++i; break; case FunctionClass::PostIncOverload: expected = (int)i++; break; case FunctionClass::DecOverload: expected = (int)--i; break; case FunctionClass::PostDecOverload: expected = (int)i--; break; default: expected = 0; break; } auto actual = obj["test"].template call<int>(testValue); String message = indexName; message << ": " << op; message << " with value " << String(testValue); test.expectEquals(actual, expected, message); }; // Test List ======================================================= testWithValue(0); testWithValue(-1); testWithValue(Limit - 1); testWithValue(Limit + 1); testWithValue(Limit); testWithValue(Limit * 2); testWithValue(-Limit); testWithValue(Limit / 3); } } void testAssignAndCast() { if constexpr (Limit != 0) { test.logMessage("Testing assignment and type cast "); // Test Code =================================================== cppgen::Base c(cppgen::Base::OutputType::AddTabs); c << indexName + " i;"; c << "T test(T input)"; { cppgen::StatementBlock sb(c); c.addWithSemicolon("i = input"); c.addWithSemicolon("return (T)i"); } c.replaceWildcard("T", Types::Helpers::getTypeNameFromTypeId<Type>()); auto obj = compile(c.toString()); // Test Routine ============================================== auto testWithValue = [&](Type testValue) { IndexType i; i = testValue; auto expected = (Type)i; auto actual = obj["test"].template call<Type>(testValue); String message = indexName; message << " with value " << String(testValue); test.expectWithinAbsoluteError(actual, expected, Type(0.00001), message); }; // Test List ======================================================= if constexpr (std::is_floating_point<Type>()) { testWithValue(Type(Limit - 0.4)); testWithValue(Type(Limit + 0.1)); testWithValue(Type(Limit + 2.4)); testWithValue(Type(-0.2)); testWithValue(Type(-80.2)); } else { testWithValue(Type(0)); testWithValue(Type(Limit - 1)); testWithValue(Type(Limit)); testWithValue(Type(Limit + 1)); testWithValue(Type(-1)); testWithValue(Type(-Limit - 2)); testWithValue(Type(Limit * 32 + 9)); } } } JitObject compile(const String& code) { for (auto& o : optimisations) s.addOptimization(o); Compiler compiler(s); SnexObjectDatabase::registerObjects(compiler, 2); auto obj = compiler.compileJitObject(code); test.expect(compiler.getCompileResult().wasOk(), compiler.getCompileResult().getErrorMessage()); return obj; } GlobalScope s; UnitTest& test; StringArray optimisations; }; } }
25.786704
108
0.58422
Matt-Dub
1afcabee2775407f5e2b23d38e2ba2e62705fa63
1,013
hh
C++
include/distro/semver.hh
mbits-libs/libdistro
350f94ba004b21c30eb9a1a345a92b94eacf6ae6
[ "MIT" ]
null
null
null
include/distro/semver.hh
mbits-libs/libdistro
350f94ba004b21c30eb9a1a345a92b94eacf6ae6
[ "MIT" ]
null
null
null
include/distro/semver.hh
mbits-libs/libdistro
350f94ba004b21c30eb9a1a345a92b94eacf6ae6
[ "MIT" ]
null
null
null
// Copyright 2021 midnightBITS // Use of this source code is governed by a MIT-style license that can be // found in the LICENSE file. #pragma once #include <optional> #include <string> #include <variant> #include <vector> namespace distro { class semver { public: class comp { std::variant<unsigned, std::string> value; public: comp() = default; comp(unsigned val) : value{val} {} comp(std::string const& val) : value{val} {} comp(std::string&& val) : value{std::move(val)} {} std::string to_string() const; bool operator<(comp const& rhs) const; bool operator==(comp const& rhs) const; static comp from_string(std::string_view comp); }; unsigned major; unsigned minor; unsigned patch; std::vector<comp> prerelease; std::vector<std::string> meta; std::string to_string() const; bool operator<(semver const& rhs) const; bool operator==(semver const& rhs) const; static std::optional<semver> from_string(std::string_view view); }; } // namespace distro
24.707317
73
0.687068
mbits-libs
2101331a0292dcc4225c749946f0ebf7e07afd9b
7,052
cpp
C++
cali-linker/modules/ipc_module.cpp
cali-library-isolation/Cali-library-isolation
550893293f66b0428a7b66e1ab80d9f5b7a4bbf4
[ "Apache-2.0" ]
7
2021-03-26T06:52:31.000Z
2022-03-11T09:42:57.000Z
cali-linker/modules/ipc_module.cpp
cali-library-isolation/Cali-library-isolation
550893293f66b0428a7b66e1ab80d9f5b7a4bbf4
[ "Apache-2.0" ]
null
null
null
cali-linker/modules/ipc_module.cpp
cali-library-isolation/Cali-library-isolation
550893293f66b0428a7b66e1ab80d9f5b7a4bbf4
[ "Apache-2.0" ]
1
2022-02-25T06:57:17.000Z
2022-02-25T06:57:17.000Z
#include <memory> #include <stdexcept> #include <memory> #include <iostream> #include <llvm/IR/Module.h> #include <llvm/Linker/Linker.h> #include <llvm/Support/raw_ostream.h> #include <llvm/IRReader/IRReader.h> #include <llvm/Support/SourceMgr.h> #include <llvm/IR/Verifier.h> #include "ipc_module.h" #include "llvm_module.h" #include "../stdlib-is-shit.h" #include "../cali_linker/archive-wrapper.h" #include "../cali_linker/debug.h" #include "../cali_linker/linker_replacement.h" #include "../cali_linker/randomness.h" namespace ipcrewriter { std::shared_ptr<IpcModule> IpcModule::newIpcModuleFromFile(const std::string &filename, bool isMainModule, YamlConfig *config, const ContextConfig *contextConfig) { if (endsWith(filename, ".bc") || endsWith(filename, ".ll") || endsWith(filename, ".o")) { return std::shared_ptr<IpcModule>(new LlvmIpcModule(filename, isMainModule, config, contextConfig)); } if (endsWith(filename, ".so") || endsWith(filename, ".a")) { return std::shared_ptr<IpcModule>(new BinaryIpcModule(filename, isMainModule, config, contextConfig)); } throw std::invalid_argument("No supported extension"); } const std::set<std::string> &IpcModule::getImports() const { return imports; } const std::set<std::string> &IpcModule::getExports() const { return exports; } const std::string &IpcModule::getSource() const { return source; } const std::vector<std::string> &IpcModule::getLogEntries() { return logEntries; } static int linked_things = 0; std::shared_ptr<IpcModule> CompositeIpcModule::newIpcModulesFromFiles(std::vector<std::string> &files, bool isMainModule, YamlConfig *config, const ContextConfig *contextConfig, const std::string &output_filename) { std::vector<std::shared_ptr<IpcModule>> binary_modules; std::set<std::string> seen_files; std::set<std::string> ignored; // Prepare LLVM linker LlvmIpcModule::context.enableDebugTypeODRUniquing(); // Load initial llvm bitcode file, containing some libc stubs filesystem::path stubsFilename = applicationPath; stubsFilename.append("libc-stubs.bc"); llvm::SMDiagnostic error; auto composite_module = parseIRFile(stubsFilename.string(), error, LlvmIpcModule::context); composite_module->setModuleIdentifier("llvm-linked-things_" + output_filename + "_" + std::to_string(linked_things++) + '-' + getRandomString() + ".bc"); // Prepare linker llvm::Linker L(*composite_module); int linked_modules = 0; auto linkerflags = config->linkerOverride ? llvm::Linker::Flags::OverrideFromSrc : llvm::Linker::Flags::None; // Helper function - link an additional LLVM file to the unique LLVM module auto addLlvmModule = [&linked_modules, &L, linkerflags](std::unique_ptr<llvm::Module> module) { if (L.linkInModule(std::move(module), linkerflags)) throw std::runtime_error("Could not link module"); linked_modules++; }; for (const auto &filename: files) { // file missing? if (!exists(filename)) { std::cerr << "Warning: file not found (" << filename << ")" << std::endl; continue; } // Check if file has already been loaded if (!seen_files.insert(absolute(filename)).second) { std::cerr << "Already seen: " << filename << std::endl; continue; } // Shared libraries if (endsWith(filename, ".so")) { binary_modules.push_back(std::shared_ptr<IpcModule>(new BinaryIpcModule(filename, isMainModule, config, contextConfig))); continue; } // LLVM files if (endsWith(filename, ".bc") || endsWith(filename, ".ll")) { auto m = llvm::parseIRFile(filename, error, LlvmIpcModule::context); if (filename.find("libstdc++") != std::string::npos) for (auto &g: m->functions()) if (g.hasName()) ignored.insert(g.getName()); addLlvmModule(std::move(m)); } // object files if (endsWith(filename, ".o")) { auto header = read_file_limit(filename, 4); if (header == "BC\xc0\xde") { addLlvmModule(llvm::parseIRFile(filename, error, LlvmIpcModule::context)); } else if (header == "\x7f""ELF") { binary_modules.push_back(std::shared_ptr<IpcModule>(new BinaryIpcModule(filename, isMainModule, config, contextConfig))); } else { std::cerr << "Can\'t determine type of file " + filename << std::endl; } } // static libraries if (endsWith(filename, ".a")) { bool binary_added = false; dbg_cout << "Open archive " << filename << std::endl; libarchive::Archive archive(filename); int i = 0; for (auto it: archive) { //if (it.name() != "magick_libMagickCore_6_Q16_la-ps.o" && it.name() != "magick_libMagickCore_6_Q16_la-string.o") // continue; //TODO hack // if (i++ == 3) // break; //TODO hack if (endsWith(it.name(), ".o") || endsWith(it.name(), ".bc") || endsWith(it.name(), ".lo")) { dbg_cout << "- Archive entry: " << it.name() << std::endl; std::string buffer = it.read(); if (buffer.substr(0, 4) == "BC\xc0\xde") { auto buffer2 = llvm::MemoryBuffer::getMemBufferCopy(buffer); auto m = llvm::parseIR(buffer2->getMemBufferRef(), error, LlvmIpcModule::context); if (!m) error.print(it.name().c_str(), llvm::errs()); if (filename.find("libstdc++") != std::string::npos) for (auto &g: m->functions()) if (g.hasName()) ignored.insert(g.getName()); addLlvmModule(std::move(m)); } else if (buffer.substr(0, 4) == "\x7f""ELF") { if (!binary_added) { binary_modules.push_back(std::shared_ptr<IpcModule>(new BinaryIpcModule(filename, isMainModule, config, contextConfig, true))); binary_added = true; } } else { std::cerr << "Can\'t determine type of file " + it.name() << " in archive " << filename << std::endl; } } } } } if (llvm::verifyModule(*composite_module, &llvm::errs())) { throw std::runtime_error("linked module is broken!"); } // build composite if (linked_modules == 0 && binary_modules.size() == 1) return binary_modules[0]; if (linked_modules == 1 && binary_modules.empty()) return std::shared_ptr<IpcModule>(new LlvmIpcModule(std::move(composite_module), isMainModule, config, contextConfig)); auto m = std::make_shared<CompositeIpcModule>(isMainModule, config, contextConfig); if (linked_modules > 0) { auto llvmModule = std::shared_ptr<IpcModule>(new LlvmIpcModule(std::move(composite_module), isMainModule, config, contextConfig)); dbg_cout << ignored.size() << " ignored symbols" << std::endl; llvmModule->ignored = std::move(ignored); m->add(llvmModule); } for (const auto &bm: binary_modules) m->add(bm); return m; } CompositeIpcModule::CompositeIpcModule(bool isMainModule, YamlConfig *config, const ContextConfig *contextConfig) : IpcModule("", isMainModule, config, contextConfig) {} const std::vector<std::string> &CompositeIpcModule::getLogEntries() { logEntries.clear(); for (auto &m: modules) { for (auto &s: m->getLogEntries()) logEntries.push_back(s); } return logEntries; } }
36.729167
155
0.671583
cali-library-isolation
21041a67704d748cb24c61d6086c7bb68d188097
2,329
hpp
C++
includes/matrix.hpp
TheLandfill/tsp
ae2b90c8a44f4521373259a587d4c91c5bc318a3
[ "MIT" ]
null
null
null
includes/matrix.hpp
TheLandfill/tsp
ae2b90c8a44f4521373259a587d4c91c5bc318a3
[ "MIT" ]
null
null
null
includes/matrix.hpp
TheLandfill/tsp
ae2b90c8a44f4521373259a587d4c91c5bc318a3
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <filesystem> #include <fstream> #include <iostream> #include <stdexcept> template<typename T> class Matrix { public: Matrix(); Matrix(const std::filesystem::path& path); template<typename Func> Matrix(size_t num_rows, size_t num_cols, Func rng); void write_to_file(const std::filesystem::path& path) const; T at(size_t row, size_t col) const; T& at(size_t row, size_t col); size_t get_num_rows() const; size_t get_num_cols() const; private: size_t num_rows, num_cols; std::vector<T> data; }; template<typename T> Matrix<T>::Matrix() : num_rows(0), num_cols(0), data() {} template<typename T> Matrix<T>::Matrix(const std::filesystem::path& path) { std::ifstream reader{path}; if (!reader.is_open()) { std::string error_message; error_message.reserve(1024); error_message += "File `"; error_message += path; error_message += "` not found!"; throw std::runtime_error(error_message); } reader >> num_rows >> num_cols; data.resize(num_rows * num_cols); for (size_t row = 0; row < num_rows; row++) { for (size_t col = 0; col < num_cols; col++) { if(!(reader >> at(row, col))) { std::cerr << "Could not read element at (" << row << ", " << col << ")!\n"; throw std::runtime_error("Error Reading Element!"); } } } } template<typename T> template<typename Func> Matrix<T>::Matrix(size_t nr, size_t nc, Func rng) : num_rows(nr), num_cols(nc) { data.reserve(nr * nc); for (size_t row = 0; row < num_rows; row++) { for (size_t col = 0; col < num_cols; col++) { data.emplace_back(rng()); } } } template<typename T> void Matrix<T>::write_to_file(const std::filesystem::path& path) const { std::ofstream writer{path}; writer << num_rows << " " << num_cols << "\n"; for (size_t row = 0; row < num_rows; row++) { for (size_t col = 0; col < num_cols - 1; col++) { writer << at(row, col) << " "; } writer << at(row, num_cols - 1) << "\n"; } } template<typename T> T Matrix<T>::at(size_t row, size_t col) const { return data.at(row * num_cols + col); } template<typename T> T& Matrix<T>::at(size_t row, size_t col) { return data.at(row * num_cols + col); } template<typename T> size_t Matrix<T>::get_num_rows() const { return num_rows; } template<typename T> size_t Matrix<T>::get_num_cols() const { return num_cols; }
23.29
79
0.656934
TheLandfill
21062d454eb17252c77fefab529e1c42ce286dca
1,577
hpp
C++
partners_api/ads/ads_utils.hpp
vicpopov/omim
664b458998fb0f2405f68ae830c2798e027b2dcc
[ "Apache-2.0" ]
4,879
2015-09-30T10:56:36.000Z
2022-03-31T18:43:03.000Z
partners_api/ads/ads_utils.hpp
mbrukman/omim
d22fe2b6e0beee697f096e931df97a64f9db9dc1
[ "Apache-2.0" ]
7,549
2015-09-30T10:52:53.000Z
2022-03-31T22:04:22.000Z
partners_api/ads/ads_utils.hpp
mbrukman/omim
d22fe2b6e0beee697f096e931df97a64f9db9dc1
[ "Apache-2.0" ]
1,493
2015-09-30T10:43:06.000Z
2022-03-21T09:16:49.000Z
#pragma once #include "storage/storage_defines.hpp" #include <cstdint> #include <initializer_list> #include <string> #include <unordered_set> namespace ads { class WithSupportedLanguages { public: virtual ~WithSupportedLanguages() = default; void AppendSupportedUserLanguages(std::initializer_list<std::string> const & languages); bool IsLanguageSupported(std::string const & lang) const; private: std::unordered_set<int8_t> m_supportedUserLanguages; }; class WithSupportedCountries { public: virtual ~WithSupportedCountries() = default; void AppendSupportedCountries(std::initializer_list<storage::CountryId> const & countries); void AppendExcludedCountries(std::initializer_list<storage::CountryId> const & countries); bool IsCountrySupported(storage::CountryId const & countryId) const; bool IsCountryExcluded(storage::CountryId const & countryId) const; private: // All countries are supported when empty. std::unordered_set<storage::CountryId> m_supportedCountries; std::unordered_set<storage::CountryId> m_excludedCountries; }; class WithSupportedUserPos { public: virtual ~WithSupportedUserPos() = default; void AppendSupportedUserPosCountries(std::initializer_list<storage::CountryId> const & countries); void AppendExcludedUserPosCountries(std::initializer_list<storage::CountryId> const & countries); bool IsUserPosCountrySupported(storage::CountryId const & countryId) const; bool IsUserPosCountryExcluded(storage::CountryId const & countryId) const; private: WithSupportedCountries m_countries; }; } // namespace ads
29.203704
100
0.795815
vicpopov
210a6edaf9fae2e3b58701a703c2479ecb6ce056
31,405
cxx
C++
ds/adsi/nw312/cschema.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
ds/adsi/nw312/cschema.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
ds/adsi/nw312/cschema.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//--------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1992 - 1996 // // File: cschema.cxx // // Contents: Windows NT 3.51 // // // History: 01-09-96 yihsins Created. // //---------------------------------------------------------------------------- #include "nwcompat.hxx" #pragma hdrstop /******************************************************************/ /* Class CNWCOMPATSchema /******************************************************************/ DEFINE_IDispatch_Implementation(CNWCOMPATSchema) DEFINE_IADs_Implementation(CNWCOMPATSchema) CNWCOMPATSchema::CNWCOMPATSchema() { VariantInit( &_vFilter ); ENLIST_TRACKING(CNWCOMPATSchema); } CNWCOMPATSchema::~CNWCOMPATSchema() { VariantClear( &_vFilter ); delete _pDispMgr; } HRESULT CNWCOMPATSchema::CreateSchema( BSTR bstrParent, BSTR bstrName, DWORD dwObjectState, REFIID riid, void **ppvObj ) { CNWCOMPATSchema FAR *pSchema = NULL; HRESULT hr = S_OK; hr = AllocateSchemaObject( &pSchema ); BAIL_ON_FAILURE(hr); hr = pSchema->InitializeCoreObject( bstrParent, bstrName, SCHEMA_CLASS_NAME, NO_SCHEMA, CLSID_NWCOMPATSchema, dwObjectState ); BAIL_ON_FAILURE(hr); hr = pSchema->QueryInterface( riid, ppvObj ); BAIL_ON_FAILURE(hr); pSchema->Release(); RRETURN(hr); error: delete pSchema; RRETURN_EXP_IF_ERR(hr); } STDMETHODIMP CNWCOMPATSchema::QueryInterface(REFIID iid, LPVOID FAR* ppv) { if (ppv == NULL) { RRETURN(E_POINTER); } if (IsEqualIID(iid, IID_IUnknown)) { *ppv = (IADs FAR *) this; } else if (IsEqualIID(iid, IID_IDispatch)) { *ppv = (IADs FAR *)this; } else if (IsEqualIID(iid, IID_ISupportErrorInfo)) { *ppv = (ISupportErrorInfo FAR *) this; } else if (IsEqualIID(iid, IID_IADsContainer)) { *ppv = (IADsContainer FAR *)this; } else if (IsEqualIID(iid, IID_IADs)) { *ppv = (IADs FAR *) this; } else { *ppv = NULL; return E_NOINTERFACE; } AddRef(); return NOERROR; } /* ISupportErrorInfo method */ STDMETHODIMP CNWCOMPATSchema::InterfaceSupportsErrorInfo( THIS_ REFIID riid ) { if (IsEqualIID(riid, IID_IADs) || IsEqualIID(riid, IID_IADsContainer)) { RRETURN(S_OK); } else { RRETURN(S_FALSE); } } /* IADs methods */ STDMETHODIMP CNWCOMPATSchema::SetInfo(THIS) { RRETURN_EXP_IF_ERR(E_NOTIMPL); } STDMETHODIMP CNWCOMPATSchema::GetInfo(THIS) { RRETURN(S_OK); } /* IADsContainer methods */ STDMETHODIMP CNWCOMPATSchema::get_Count(long FAR* retval) { HRESULT hr; if ( !retval ) RRETURN_EXP_IF_ERR(E_ADS_BAD_PARAMETER); *retval = g_cNWCOMPATClasses + g_cNWCOMPATSyntax; RRETURN(S_OK); } STDMETHODIMP CNWCOMPATSchema::get_Filter(THIS_ VARIANT FAR* pVar) { HRESULT hr; if ( !pVar ) RRETURN_EXP_IF_ERR(E_ADS_BAD_PARAMETER); VariantInit( pVar ); hr = VariantCopy( pVar, &_vFilter ); RRETURN_EXP_IF_ERR(hr); } STDMETHODIMP CNWCOMPATSchema::put_Filter(THIS_ VARIANT Var) { HRESULT hr; hr = VariantCopy( &_vFilter, &Var ); RRETURN_EXP_IF_ERR(hr); } STDMETHODIMP CNWCOMPATSchema::put_Hints(THIS_ VARIANT Var) { RRETURN_EXP_IF_ERR( E_NOTIMPL); } STDMETHODIMP CNWCOMPATSchema::get_Hints(THIS_ VARIANT FAR* pVar) { RRETURN_EXP_IF_ERR(E_NOTIMPL); } STDMETHODIMP CNWCOMPATSchema::GetObject( THIS_ BSTR ClassName, BSTR RelativeName, IDispatch * FAR* ppObject) { TCHAR szBuffer[MAX_PATH]; HRESULT hr = S_OK; if (!RelativeName || !*RelativeName) { RRETURN_EXP_IF_ERR(E_ADS_UNKNOWN_OBJECT); } memset(szBuffer, 0, sizeof(szBuffer)); wcscpy(szBuffer, _ADsPath); wcscat(szBuffer, L"/"); wcscat(szBuffer, RelativeName); if (ClassName && *ClassName) { wcscat(szBuffer,L","); wcscat(szBuffer, ClassName); } hr = ::GetObject( szBuffer, (LPVOID *)ppObject ); BAIL_ON_FAILURE(hr); error: RRETURN_EXP_IF_ERR(hr); } STDMETHODIMP CNWCOMPATSchema::get__NewEnum(THIS_ IUnknown * FAR* retval) { HRESULT hr; IEnumVARIANT *penum = NULL; if ( !retval ) RRETURN_EXP_IF_ERR(E_ADS_BAD_PARAMETER); *retval = NULL; // // Create new enumerator for items currently // in collection and QI for IUnknown // hr = CNWCOMPATSchemaEnum::Create( (CNWCOMPATSchemaEnum **)&penum, _ADsPath, _Name, _vFilter ); BAIL_ON_FAILURE(hr); hr = penum->QueryInterface( IID_IUnknown, (VOID FAR* FAR*)retval ); BAIL_ON_FAILURE(hr); if ( penum ) penum->Release(); RRETURN(hr); error: if ( penum ) delete penum; RRETURN_EXP_IF_ERR(hr); } STDMETHODIMP CNWCOMPATSchema::Create( THIS_ BSTR ClassName, BSTR RelativeName, IDispatch * FAR* ppObject) { RRETURN_EXP_IF_ERR(E_NOTIMPL); } STDMETHODIMP CNWCOMPATSchema::Delete(THIS_ BSTR SourceName, BSTR Type) { RRETURN_EXP_IF_ERR(E_NOTIMPL); } STDMETHODIMP CNWCOMPATSchema::CopyHere( THIS_ BSTR SourceName, BSTR NewName, IDispatch * FAR* ppObject ) { RRETURN_EXP_IF_ERR(E_NOTIMPL); } STDMETHODIMP CNWCOMPATSchema::MoveHere( THIS_ BSTR SourceName, BSTR NewName, IDispatch * FAR* ppObject ) { RRETURN_EXP_IF_ERR(E_NOTIMPL); } HRESULT CNWCOMPATSchema::AllocateSchemaObject(CNWCOMPATSchema FAR * FAR * ppSchema) { CNWCOMPATSchema FAR *pSchema = NULL; CAggregatorDispMgr FAR *pDispMgr = NULL; HRESULT hr = S_OK; pSchema = new CNWCOMPATSchema(); if ( pSchema == NULL ) hr = E_OUTOFMEMORY; BAIL_ON_FAILURE(hr); pDispMgr = new CAggregatorDispMgr; if ( pDispMgr == NULL ) hr = E_OUTOFMEMORY; BAIL_ON_FAILURE(hr); hr = LoadTypeInfoEntry( pDispMgr, LIBID_ADs, IID_IADs, (IADs *) pSchema, DISPID_REGULAR ); BAIL_ON_FAILURE(hr); hr = LoadTypeInfoEntry( pDispMgr, LIBID_ADs, IID_IADsContainer, (IADsContainer *) pSchema, DISPID_NEWENUM ); BAIL_ON_FAILURE(hr); pSchema->_pDispMgr = pDispMgr; *ppSchema = pSchema; RRETURN(hr); error: delete pDispMgr; delete pSchema; RRETURN(hr); } /******************************************************************/ /* Class CNWCOMPATClass /******************************************************************/ DEFINE_IDispatch_Implementation(CNWCOMPATClass) DEFINE_IADs_Implementation(CNWCOMPATClass) CNWCOMPATClass::CNWCOMPATClass() : _pDispMgr( NULL ), _aPropertyInfo( NULL ), _cPropertyInfo( 0 ), _bstrCLSID( NULL ), _bstrOID( NULL ), _bstrPrimaryInterface( NULL ), _fAbstract( FALSE ), _fContainer( FALSE ), _bstrHelpFileName( NULL ), _lHelpFileContext( 0 ) { VariantInit( &_vMandatoryProperties ); VariantInit( &_vOptionalProperties ); VariantInit( &_vPossSuperiors ); VariantInit( &_vContainment ); VariantInit( &_vFilter ); ENLIST_TRACKING(CNWCOMPATClass); } CNWCOMPATClass::~CNWCOMPATClass() { if ( _bstrCLSID ) { ADsFreeString( _bstrCLSID ); } if ( _bstrOID ) { ADsFreeString( _bstrOID ); } if ( _bstrPrimaryInterface ) { ADsFreeString( _bstrPrimaryInterface ); } if ( _bstrHelpFileName ) { ADsFreeString( _bstrHelpFileName ); } VariantClear( &_vMandatoryProperties ); VariantClear( &_vOptionalProperties ); VariantClear( &_vPossSuperiors ); VariantClear( &_vContainment ); VariantClear( &_vFilter ); delete _pDispMgr; } HRESULT CNWCOMPATClass::CreateClass( BSTR bstrParent, CLASSINFO *pClassInfo, DWORD dwObjectState, REFIID riid, void **ppvObj ) { CNWCOMPATClass FAR *pClass = NULL; HRESULT hr = S_OK; BSTR bstrTmp = NULL; hr = AllocateClassObject( &pClass ); BAIL_ON_FAILURE(hr); pClass->_aPropertyInfo = pClassInfo->aPropertyInfo; pClass->_cPropertyInfo = pClassInfo->cPropertyInfo; pClass->_lHelpFileContext = pClassInfo->lHelpFileContext; pClass->_fContainer = (VARIANT_BOOL) pClassInfo->fContainer; pClass->_fAbstract = (VARIANT_BOOL) pClassInfo->fAbstract; hr = StringFromCLSID( (REFCLSID) *(pClassInfo->pPrimaryInterfaceGUID), &bstrTmp ); BAIL_ON_FAILURE(hr); hr = ADsAllocString( bstrTmp, &pClass->_bstrPrimaryInterface ); BAIL_ON_FAILURE(hr); CoTaskMemFree( bstrTmp ); bstrTmp = NULL; hr = StringFromCLSID( (REFCLSID) *(pClassInfo->pCLSID), &bstrTmp ); BAIL_ON_FAILURE(hr); hr = ADsAllocString( bstrTmp, &pClass->_bstrCLSID ); BAIL_ON_FAILURE(hr); CoTaskMemFree( bstrTmp ); bstrTmp = NULL; hr = ADsAllocString( pClassInfo->bstrOID, &pClass->_bstrOID); BAIL_ON_FAILURE(hr); hr = MakeVariantFromStringList( pClassInfo->bstrMandatoryProperties, &(pClass->_vMandatoryProperties)); BAIL_ON_FAILURE(hr); hr = MakeVariantFromStringList( pClassInfo->bstrOptionalProperties, &(pClass->_vOptionalProperties)); BAIL_ON_FAILURE(hr); hr = MakeVariantFromStringList( pClassInfo->bstrPossSuperiors, &(pClass->_vPossSuperiors)); BAIL_ON_FAILURE(hr); hr = MakeVariantFromStringList( pClassInfo->bstrContainment, &(pClass->_vContainment)); BAIL_ON_FAILURE(hr); hr = ADsAllocString( pClassInfo->bstrHelpFileName, &pClass->_bstrHelpFileName); BAIL_ON_FAILURE(hr); hr = pClass->InitializeCoreObject( bstrParent, pClassInfo->bstrName, CLASS_CLASS_NAME, NO_SCHEMA, CLSID_NWCOMPATClass, dwObjectState ); BAIL_ON_FAILURE(hr); hr = pClass->QueryInterface( riid, ppvObj ); BAIL_ON_FAILURE(hr); pClass->Release(); RRETURN(hr); error: if ( bstrTmp != NULL ) CoTaskMemFree( bstrTmp ); delete pClass; RRETURN_EXP_IF_ERR(hr); } STDMETHODIMP CNWCOMPATClass::QueryInterface(REFIID iid, LPVOID FAR* ppv) { if (ppv == NULL) { RRETURN(E_POINTER); } if (IsEqualIID(iid, IID_IUnknown)) { *ppv = (IADsClass FAR * ) this; } else if (IsEqualIID(iid, IID_IDispatch)) { *ppv = (IADs FAR *) this; } else if (IsEqualIID(iid, IID_ISupportErrorInfo)) { *ppv = (ISupportErrorInfo FAR *) this; } else if (IsEqualIID(iid, IID_IADs)) { *ppv = (IADs FAR *) this; } else if (IsEqualIID(iid, IID_IADsClass)) { *ppv = (IADsClass FAR *) this; } else { *ppv = NULL; return E_NOINTERFACE; } AddRef(); return NOERROR; } /* ISupportErrorInfo method */ STDMETHODIMP CNWCOMPATClass::InterfaceSupportsErrorInfo( THIS_ REFIID riid ) { if (IsEqualIID(riid, IID_IADs) || IsEqualIID(riid, IID_IADsClass)) { RRETURN(S_OK); } else { RRETURN(S_FALSE); } } /* IADs methods */ STDMETHODIMP CNWCOMPATClass::SetInfo(THIS) { RRETURN_EXP_IF_ERR(E_NOTIMPL); } STDMETHODIMP CNWCOMPATClass::GetInfo(THIS) { RRETURN(S_OK); } /* IADsClass methods */ STDMETHODIMP CNWCOMPATClass::get_PrimaryInterface( THIS_ BSTR FAR *pbstrGUID ) { HRESULT hr; if ( !pbstrGUID ) RRETURN_EXP_IF_ERR(E_ADS_BAD_PARAMETER); hr = ADsAllocString( _bstrPrimaryInterface, pbstrGUID ); RRETURN_EXP_IF_ERR(hr); } STDMETHODIMP CNWCOMPATClass::get_CLSID( THIS_ BSTR FAR *pbstrCLSID ) { HRESULT hr; if ( !pbstrCLSID ) RRETURN_EXP_IF_ERR(E_ADS_BAD_PARAMETER); hr = ADsAllocString( _bstrCLSID, pbstrCLSID ); RRETURN_EXP_IF_ERR(hr); } STDMETHODIMP CNWCOMPATClass::put_CLSID( THIS_ BSTR bstrCLSID ) { RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED); } STDMETHODIMP CNWCOMPATClass::get_OID( THIS_ BSTR FAR *pbstrOID ) { HRESULT hr; if ( !pbstrOID ) RRETURN_EXP_IF_ERR(E_ADS_BAD_PARAMETER); hr = ADsAllocString( _bstrOID, pbstrOID ); RRETURN_EXP_IF_ERR(hr); } STDMETHODIMP CNWCOMPATClass::put_OID( THIS_ BSTR bstrOID ) { RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED); } STDMETHODIMP CNWCOMPATClass::get_Abstract( THIS_ VARIANT_BOOL FAR *pfAbstract ) { if ( !pfAbstract ) RRETURN_EXP_IF_ERR(E_ADS_BAD_PARAMETER); *pfAbstract = _fAbstract? VARIANT_TRUE : VARIANT_FALSE; RRETURN(S_OK); } STDMETHODIMP CNWCOMPATClass::put_Abstract( THIS_ VARIANT_BOOL fAbstract ) { RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED); } STDMETHODIMP CNWCOMPATClass::get_Auxiliary( THIS_ VARIANT_BOOL FAR *pfAuxiliary ) { if ( !pfAuxiliary ) RRETURN_EXP_IF_ERR(E_ADS_BAD_PARAMETER); *pfAuxiliary = VARIANT_FALSE; RRETURN(S_OK); } STDMETHODIMP CNWCOMPATClass::put_Auxiliary( THIS_ VARIANT_BOOL fAuxiliary ) { RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED); } STDMETHODIMP CNWCOMPATClass::get_MandatoryProperties( THIS_ VARIANT FAR *pvMandatoryProperties ) { HRESULT hr; VariantInit( pvMandatoryProperties ); hr = VariantCopy( pvMandatoryProperties, &_vMandatoryProperties ); RRETURN_EXP_IF_ERR(hr); } STDMETHODIMP CNWCOMPATClass::put_MandatoryProperties( THIS_ VARIANT vMandatoryProperties ) { RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED); } STDMETHODIMP CNWCOMPATClass::get_DerivedFrom( THIS_ VARIANT FAR *pvDerivedFrom ) { RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED); } STDMETHODIMP CNWCOMPATClass::put_DerivedFrom( THIS_ VARIANT vDerivedFrom ) { RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED); } STDMETHODIMP CNWCOMPATClass::get_AuxDerivedFrom( THIS_ VARIANT FAR *pvAuxDerivedFrom ) { RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED); } STDMETHODIMP CNWCOMPATClass::put_AuxDerivedFrom( THIS_ VARIANT vAuxDerivedFrom ) { RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED); } STDMETHODIMP CNWCOMPATClass::get_PossibleSuperiors( THIS_ VARIANT FAR *pvPossSuperiors ) { HRESULT hr; VariantInit( pvPossSuperiors ); hr = VariantCopy( pvPossSuperiors, &_vPossSuperiors ); RRETURN_EXP_IF_ERR(hr); } STDMETHODIMP CNWCOMPATClass::put_PossibleSuperiors( THIS_ VARIANT vPossSuperiors ) { RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED); } STDMETHODIMP CNWCOMPATClass::get_Containment( THIS_ VARIANT FAR *pvContainment ) { HRESULT hr; VariantInit( pvContainment ); hr = VariantCopy( pvContainment, &_vContainment ); RRETURN_EXP_IF_ERR(hr); } STDMETHODIMP CNWCOMPATClass::put_Containment( THIS_ VARIANT vContainment ) { RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED); } STDMETHODIMP CNWCOMPATClass::get_Container( THIS_ VARIANT_BOOL FAR *pfContainer ) { if ( !pfContainer ) RRETURN_EXP_IF_ERR(E_ADS_BAD_PARAMETER); *pfContainer = _fContainer? VARIANT_TRUE : VARIANT_FALSE; RRETURN(S_OK); } STDMETHODIMP CNWCOMPATClass::put_Container( THIS_ VARIANT_BOOL fContainer ) { RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED); } STDMETHODIMP CNWCOMPATClass::get_HelpFileName( THIS_ BSTR FAR *pbstrHelpFileName ) { HRESULT hr; if ( !pbstrHelpFileName ) RRETURN_EXP_IF_ERR(E_ADS_BAD_PARAMETER); hr = ADsAllocString( _bstrHelpFileName, pbstrHelpFileName ); RRETURN_EXP_IF_ERR(hr); } STDMETHODIMP CNWCOMPATClass::put_HelpFileName( THIS_ BSTR bstrHelpFile ) { RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED); } STDMETHODIMP CNWCOMPATClass::get_HelpFileContext( THIS_ long FAR *plHelpContext ) { if ( !plHelpContext ) RRETURN_EXP_IF_ERR(E_ADS_BAD_PARAMETER); *plHelpContext = _lHelpFileContext; RRETURN(S_OK); } STDMETHODIMP CNWCOMPATClass::put_HelpFileContext( THIS_ long lHelpContext ) { RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED); } STDMETHODIMP CNWCOMPATClass::Qualifiers(THIS_ IADsCollection FAR* FAR* ppQualifiers) { RRETURN_EXP_IF_ERR(E_NOTIMPL); } HRESULT CNWCOMPATClass::AllocateClassObject(CNWCOMPATClass FAR * FAR * ppClass) { CNWCOMPATClass FAR *pClass = NULL; CAggregatorDispMgr FAR *pDispMgr = NULL; HRESULT hr = S_OK; pClass = new CNWCOMPATClass(); if ( pClass == NULL ) hr = E_OUTOFMEMORY; BAIL_ON_FAILURE(hr); pDispMgr = new CAggregatorDispMgr; if ( pDispMgr == NULL ) hr = E_OUTOFMEMORY; BAIL_ON_FAILURE(hr); hr = LoadTypeInfoEntry( pDispMgr, LIBID_ADs, IID_IADs, (IADs *) pClass, DISPID_REGULAR ); BAIL_ON_FAILURE(hr); hr = LoadTypeInfoEntry( pDispMgr, LIBID_ADs, IID_IADsClass, (IADsClass *) pClass, DISPID_REGULAR ); BAIL_ON_FAILURE(hr); pClass->_pDispMgr = pDispMgr; *ppClass = pClass; RRETURN(hr); error: delete pDispMgr; delete pClass; RRETURN(hr); } /******************************************************************/ /* Class CNWCOMPATProperty /******************************************************************/ DEFINE_IDispatch_Implementation(CNWCOMPATProperty) DEFINE_IADs_Implementation(CNWCOMPATProperty) CNWCOMPATProperty::CNWCOMPATProperty() : _pDispMgr( NULL ), _bstrOID( NULL ), _bstrSyntax( NULL ), _lMaxRange( 0 ), _lMinRange( 0 ), _fMultiValued( FALSE ) { ENLIST_TRACKING(CNWCOMPATProperty); } CNWCOMPATProperty::~CNWCOMPATProperty() { if ( _bstrOID ) { ADsFreeString( _bstrOID ); } if ( _bstrSyntax ) { ADsFreeString( _bstrSyntax ); } delete _pDispMgr; } HRESULT CNWCOMPATProperty::CreateProperty( BSTR bstrParent, PROPERTYINFO *pPropertyInfo, DWORD dwObjectState, REFIID riid, void **ppvObj ) { CNWCOMPATProperty FAR * pProperty = NULL; HRESULT hr = S_OK; hr = AllocatePropertyObject( &pProperty ); BAIL_ON_FAILURE(hr); hr = ADsAllocString( pPropertyInfo->bstrOID, &pProperty->_bstrOID); BAIL_ON_FAILURE(hr); hr = ADsAllocString( pPropertyInfo->bstrSyntax, &pProperty->_bstrSyntax); BAIL_ON_FAILURE(hr); pProperty->_lMaxRange = pPropertyInfo->lMaxRange; pProperty->_lMinRange = pPropertyInfo->lMinRange; pProperty->_fMultiValued = (VARIANT_BOOL) pPropertyInfo->fMultiValued; hr = pProperty->InitializeCoreObject( bstrParent, pPropertyInfo->szPropertyName, PROPERTY_CLASS_NAME, NO_SCHEMA, CLSID_NWCOMPATProperty, dwObjectState ); BAIL_ON_FAILURE(hr); hr = pProperty->QueryInterface( riid, ppvObj ); BAIL_ON_FAILURE(hr); pProperty->Release(); RRETURN(hr); error: delete pProperty; RRETURN_EXP_IF_ERR(hr); } STDMETHODIMP CNWCOMPATProperty::QueryInterface(REFIID iid, LPVOID FAR* ppv) { if (ppv == NULL) { RRETURN(E_POINTER); } if (IsEqualIID(iid, IID_IUnknown)) { *ppv = (IADsProperty FAR *) this; } else if (IsEqualIID(iid, IID_IDispatch)) { *ppv = (IADs FAR *) this; } else if (IsEqualIID(iid, IID_ISupportErrorInfo)) { *ppv = (ISupportErrorInfo FAR *) this; } else if (IsEqualIID(iid, IID_IADs)) { *ppv = (IADs FAR *) this; } else if (IsEqualIID(iid, IID_IADsProperty)) { *ppv = (IADsProperty FAR *) this; } else { *ppv = NULL; return E_NOINTERFACE; } AddRef(); return NOERROR; } /* ISupportErrorInfo method */ STDMETHODIMP CNWCOMPATProperty::InterfaceSupportsErrorInfo( THIS_ REFIID riid ) { if (IsEqualIID(riid, IID_IADs) || IsEqualIID(riid, IID_IADsProperty)) { RRETURN(S_OK); } else { RRETURN(S_FALSE); } } /* IADs methods */ STDMETHODIMP CNWCOMPATProperty::SetInfo(THIS) { RRETURN_EXP_IF_ERR(E_NOTIMPL); } STDMETHODIMP CNWCOMPATProperty::GetInfo(THIS) { RRETURN(S_OK); } /* IADsProperty methods */ STDMETHODIMP CNWCOMPATProperty::get_OID( THIS_ BSTR FAR *pbstrOID ) { HRESULT hr; if ( !pbstrOID ) RRETURN_EXP_IF_ERR(E_ADS_BAD_PARAMETER); hr = ADsAllocString( _bstrOID, pbstrOID ); RRETURN_EXP_IF_ERR(hr); } STDMETHODIMP CNWCOMPATProperty::put_OID( THIS_ BSTR bstrOID ) { RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED); } STDMETHODIMP CNWCOMPATProperty::get_Syntax( THIS_ BSTR FAR *pbstrSyntax ) { HRESULT hr; if ( !pbstrSyntax ) RRETURN_EXP_IF_ERR(E_ADS_BAD_PARAMETER); hr = ADsAllocString( _bstrSyntax, pbstrSyntax ); RRETURN_EXP_IF_ERR(hr); } STDMETHODIMP CNWCOMPATProperty::put_Syntax( THIS_ BSTR bstrSyntax ) { RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED); } STDMETHODIMP CNWCOMPATProperty::get_MaxRange( THIS_ long FAR *plMaxRange ) { if ( !plMaxRange ) RRETURN_EXP_IF_ERR(E_ADS_BAD_PARAMETER); *plMaxRange = _lMaxRange; RRETURN(S_OK); } STDMETHODIMP CNWCOMPATProperty::put_MaxRange( THIS_ long lMaxRange ) { RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED); } STDMETHODIMP CNWCOMPATProperty::get_MinRange( THIS_ long FAR *plMinRange ) { if ( !plMinRange ) RRETURN_EXP_IF_ERR(E_ADS_BAD_PARAMETER); *plMinRange = _lMinRange; RRETURN(S_OK); } STDMETHODIMP CNWCOMPATProperty::put_MinRange( THIS_ long lMinRange ) { RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED); } STDMETHODIMP CNWCOMPATProperty::get_MultiValued( THIS_ VARIANT_BOOL FAR *pfMultiValued ) { if ( !pfMultiValued ) RRETURN_EXP_IF_ERR(E_ADS_BAD_PARAMETER); *pfMultiValued = _fMultiValued? VARIANT_TRUE: VARIANT_FALSE; RRETURN(S_OK); } STDMETHODIMP CNWCOMPATProperty::put_MultiValued( THIS_ VARIANT_BOOL fMultiValued ) { RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED); } STDMETHODIMP CNWCOMPATProperty::Qualifiers(THIS_ IADsCollection FAR* FAR* ppQualifiers) { RRETURN_EXP_IF_ERR(E_NOTIMPL); } HRESULT CNWCOMPATProperty::AllocatePropertyObject(CNWCOMPATProperty FAR * FAR * ppProperty) { CNWCOMPATProperty FAR *pProperty = NULL; CAggregatorDispMgr FAR *pDispMgr = NULL; HRESULT hr = S_OK; pProperty = new CNWCOMPATProperty(); if ( pProperty == NULL ) hr = E_OUTOFMEMORY; BAIL_ON_FAILURE(hr); pDispMgr = new CAggregatorDispMgr; if ( pDispMgr == NULL ) hr = E_OUTOFMEMORY; BAIL_ON_FAILURE(hr); hr = LoadTypeInfoEntry( pDispMgr, LIBID_ADs, IID_IADs, (IADs *) pProperty, DISPID_REGULAR ); BAIL_ON_FAILURE(hr); hr = LoadTypeInfoEntry( pDispMgr, LIBID_ADs, IID_IADsProperty, (IADsProperty *) pProperty, DISPID_REGULAR ); BAIL_ON_FAILURE(hr); pProperty->_pDispMgr = pDispMgr; *ppProperty = pProperty; RRETURN(hr); error: delete pDispMgr; delete pProperty; RRETURN(hr); } /******************************************************************/ /* Class CNWCOMPATSyntax /******************************************************************/ DEFINE_IDispatch_Implementation(CNWCOMPATSyntax) DEFINE_IADs_Implementation(CNWCOMPATSyntax) CNWCOMPATSyntax::CNWCOMPATSyntax() { ENLIST_TRACKING(CNWCOMPATSyntax); } CNWCOMPATSyntax::~CNWCOMPATSyntax() { delete _pDispMgr; } HRESULT CNWCOMPATSyntax::CreateSyntax( BSTR bstrParent, SYNTAXINFO *pSyntaxInfo, DWORD dwObjectState, REFIID riid, void **ppvObj ) { CNWCOMPATSyntax FAR *pSyntax = NULL; HRESULT hr = S_OK; hr = AllocateSyntaxObject( &pSyntax ); BAIL_ON_FAILURE(hr); hr = pSyntax->InitializeCoreObject( bstrParent, pSyntaxInfo->bstrName, SYNTAX_CLASS_NAME, NO_SCHEMA, CLSID_NWCOMPATSyntax, dwObjectState ); BAIL_ON_FAILURE(hr); pSyntax->_lOleAutoDataType = pSyntaxInfo->lOleAutoDataType; hr = pSyntax->QueryInterface( riid, ppvObj ); BAIL_ON_FAILURE(hr); pSyntax->Release(); RRETURN(hr); error: delete pSyntax; RRETURN_EXP_IF_ERR(hr); } STDMETHODIMP CNWCOMPATSyntax::QueryInterface(REFIID iid, LPVOID FAR* ppv) { if (ppv == NULL) { RRETURN(E_POINTER); } if (IsEqualIID(iid, IID_IUnknown)) { *ppv = (IADs FAR *) this; } else if (IsEqualIID(iid, IID_IDispatch)) { *ppv = (IADs FAR *) this; } else if (IsEqualIID(iid, IID_ISupportErrorInfo)) { *ppv = (ISupportErrorInfo FAR *) this; } else if (IsEqualIID(iid, IID_IADs)) { *ppv = (IADs FAR *) this; } else if (IsEqualIID(iid, IID_IADsSyntax)) { *ppv = (IADsSyntax FAR *) this; } else { *ppv = NULL; return E_NOINTERFACE; } AddRef(); return NOERROR; } /* ISupportErrorInfo method */ STDMETHODIMP CNWCOMPATSyntax::InterfaceSupportsErrorInfo( THIS_ REFIID riid ) { if (IsEqualIID(riid, IID_IADs) || IsEqualIID(riid, IID_IADsSyntax)) { RRETURN(S_OK); } else { RRETURN(S_FALSE); } } /* IADs methods */ STDMETHODIMP CNWCOMPATSyntax::SetInfo(THIS) { RRETURN_EXP_IF_ERR(E_NOTIMPL); } STDMETHODIMP CNWCOMPATSyntax::GetInfo(THIS) { RRETURN(S_OK); } HRESULT CNWCOMPATSyntax::AllocateSyntaxObject(CNWCOMPATSyntax FAR * FAR * ppSyntax) { CNWCOMPATSyntax FAR *pSyntax = NULL; CAggregatorDispMgr FAR *pDispMgr = NULL; HRESULT hr = S_OK; pSyntax = new CNWCOMPATSyntax(); if ( pSyntax == NULL ) hr = E_OUTOFMEMORY; BAIL_ON_FAILURE(hr); pDispMgr = new CAggregatorDispMgr; if ( pDispMgr == NULL ) hr = E_OUTOFMEMORY; BAIL_ON_FAILURE(hr); hr = LoadTypeInfoEntry( pDispMgr, LIBID_ADs, IID_IADsSyntax, (IADsSyntax *) pSyntax, DISPID_REGULAR ); BAIL_ON_FAILURE(hr); pSyntax->_pDispMgr = pDispMgr; *ppSyntax = pSyntax; RRETURN(hr); error: delete pDispMgr; delete pSyntax; RRETURN(hr); } STDMETHODIMP CNWCOMPATSyntax::get_OleAutoDataType( THIS_ long FAR *plOleAutoDataType ) { if ( !plOleAutoDataType ) RRETURN_EXP_IF_ERR(E_ADS_BAD_PARAMETER); *plOleAutoDataType = _lOleAutoDataType; RRETURN(S_OK); } STDMETHODIMP CNWCOMPATSyntax::put_OleAutoDataType( THIS_ long lOleAutoDataType ) { RRETURN_EXP_IF_ERR(E_ADS_PROPERTY_NOT_SUPPORTED); } /******************************************************************/ /* Misc Helpers /******************************************************************/ HRESULT MakeVariantFromStringList( BSTR bstrList, VARIANT *pvVariant ) { HRESULT hr = S_OK; SAFEARRAY *aList = NULL; SAFEARRAYBOUND aBound; BSTR pszTempList = NULL; if ( bstrList != NULL ) { long i = 0; long nCount = 1; TCHAR c; BSTR pszSrc; hr = ADsAllocString( bstrList, &pszTempList ); BAIL_ON_FAILURE(hr); while ( c = pszTempList[i] ) { if ( c == TEXT(',')) { pszTempList[i] = 0; nCount++; } i++; } aBound.lLbound = 0; aBound.cElements = nCount; aList = SafeArrayCreate( VT_VARIANT, 1, &aBound ); if ( aList == NULL ) { hr = E_OUTOFMEMORY; BAIL_ON_FAILURE(hr); } pszSrc = pszTempList; for ( i = 0; i < nCount; i++ ) { VARIANT v; VariantInit(&v); V_VT(&v) = VT_BSTR; hr = ADsAllocString( pszSrc, &(V_BSTR(&v))); BAIL_ON_FAILURE(hr); hr = SafeArrayPutElement( aList, &i, &v ); VariantClear(&v); BAIL_ON_FAILURE(hr); pszSrc += _tcslen( pszSrc ) + 1; } VariantInit( pvVariant ); V_VT(pvVariant) = VT_ARRAY | VT_VARIANT; V_ARRAY(pvVariant) = aList; ADsFreeString( pszTempList ); pszTempList = NULL; } else { aBound.lLbound = 0; aBound.cElements = 0; aList = SafeArrayCreate( VT_VARIANT, 1, &aBound ); if ( aList == NULL ) { hr = E_OUTOFMEMORY; BAIL_ON_FAILURE(hr); } VariantInit( pvVariant ); V_VT(pvVariant) = VT_ARRAY | VT_VARIANT; V_ARRAY(pvVariant) = aList; } RRETURN(S_OK); error: if ( pszTempList ) ADsFreeString( pszTempList ); if ( aList ) SafeArrayDestroy( aList ); return hr; } STDMETHODIMP CNWCOMPATClass::get_OptionalProperties( THIS_ VARIANT FAR *retval ) { HRESULT hr; VariantInit( retval); hr = VariantCopy( retval, &_vOptionalProperties ); RRETURN_EXP_IF_ERR(hr); } STDMETHODIMP CNWCOMPATClass::put_OptionalProperties( THIS_ VARIANT vOptionalProperties ) { HRESULT hr = E_NOTIMPL; RRETURN_EXP_IF_ERR(hr); } STDMETHODIMP CNWCOMPATClass::get_NamingProperties( THIS_ VARIANT FAR *retval ) { RRETURN_EXP_IF_ERR(E_NOTIMPL); } STDMETHODIMP CNWCOMPATClass::put_NamingProperties( THIS_ VARIANT vNamingProperties ) { RRETURN_EXP_IF_ERR(E_NOTIMPL); }
22.416131
84
0.595128
npocmaka
21132bbe7dbd51afb2918827974fcddfdb3c2dcb
269
cpp
C++
Linked List Exercises/Ex1/Ex1 - SingleLinkedList/CNode.cpp
ferp132/math
96f765b93554a2ad3a279575d6c60b1107b0bf35
[ "MIT" ]
null
null
null
Linked List Exercises/Ex1/Ex1 - SingleLinkedList/CNode.cpp
ferp132/math
96f765b93554a2ad3a279575d6c60b1107b0bf35
[ "MIT" ]
null
null
null
Linked List Exercises/Ex1/Ex1 - SingleLinkedList/CNode.cpp
ferp132/math
96f765b93554a2ad3a279575d6c60b1107b0bf35
[ "MIT" ]
null
null
null
#include "CNode.h" CNode::CNode() { } void CNode::SetData(int iData) { data = iData; } int CNode::GetData() const { return data; } void CNode::SetNextNode(CNode *newnextNode) { nextNode = newnextNode; } CNode * CNode::GetNextNode() const { return nextNode; }
9.962963
43
0.672862
ferp132
2115560a3bd1e622ef0aad2f7fa0b18a961e5632
4,829
cpp
C++
src/brdf/LitSphereWindow.cpp
davidlee80/GI
820ccba1323daaff3453e61f679ee04ed36a91b9
[ "MS-PL" ]
1
2022-03-16T01:41:13.000Z
2022-03-16T01:41:13.000Z
src/brdf/LitSphereWindow.cpp
davidlee80/GI
820ccba1323daaff3453e61f679ee04ed36a91b9
[ "MS-PL" ]
null
null
null
src/brdf/LitSphereWindow.cpp
davidlee80/GI
820ccba1323daaff3453e61f679ee04ed36a91b9
[ "MS-PL" ]
null
null
null
/* Copyright Disney Enterprises, Inc. All rights reserved. This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software. 1. Definitions The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law. A "contribution" is the original software, or any additions or changes to the software. A "contributor" is any person that distributes its contribution under this license. "Licensed patents" are a contributor's patent claims that read directly on its contribution. 2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create. (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software. 3. Conditions and Limitations (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks. (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically. (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software. (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license. (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non- infringement. */ #include <QtGui> #include <QCheckBox> #include "LitSphereWindow.h" #include "LitSphereWidget.h" #include "ParameterWindow.h" #include "FloatVarWidget.h" LitSphereWindow::LitSphereWindow( ParameterWindow* paramWindow ) { glWidget = new LitSphereWidget( this, paramWindow->getBRDFList() ); // so we can tell the parameter window when the incident vector changes (from dragging on the sphere) connect( glWidget, SIGNAL(incidentVectorChanged( float, float )), paramWindow, SLOT(incidentVectorChanged( float, float )) ); connect( paramWindow, SIGNAL(incidentDirectionChanged(float,float)), glWidget, SLOT(incidentDirectionChanged(float,float)) ); connect( paramWindow, SIGNAL(brdfListChanged(std::vector<brdfPackage>)), glWidget, SLOT(brdfListChanged(std::vector<brdfPackage>)) ); QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->addWidget(glWidget); QHBoxLayout *buttonLayout = new QHBoxLayout; mainLayout->addLayout(buttonLayout); doubleTheta = new QCheckBox( "Double theta" ); doubleTheta->setChecked( true ); connect( doubleTheta, SIGNAL(stateChanged(int)), glWidget, SLOT(doubleThetaChanged(int)) ); buttonLayout->addWidget(doubleTheta); useNDotL = new QCheckBox( "Multiply by N . L" ); useNDotL->setChecked( true ); connect( useNDotL, SIGNAL(stateChanged(int)), glWidget, SLOT(useNDotLChanged(int)) ); buttonLayout->addWidget(useNDotL); FloatVarWidget* fv; #if 0 fv = new FloatVarWidget("Brightness", 0, 100.0, 1.0); connect(fv, SIGNAL(valueChanged(float)), glWidget, SLOT(brightnessChanged(float))); mainLayout->addWidget(fv); #endif fv = new FloatVarWidget("Gamma", 1.0, 5.0, 2.2); connect(fv, SIGNAL(valueChanged(float)), glWidget, SLOT(gammaChanged(float))); mainLayout->addWidget(fv); fv = new FloatVarWidget("Exposure", -6.0, 6.0, 0.0); connect(fv, SIGNAL(valueChanged(float)), glWidget, SLOT(exposureChanged(float))); mainLayout->addWidget(fv); setLayout(mainLayout); setWindowTitle( "Lit Sphere" ); } void LitSphereWindow::setShowing( bool s ) { if( glWidget ) glWidget->setShowing( s ); }
44.302752
137
0.75937
davidlee80
2115d2997d7bdca32560608377c3a692242d4c9c
1,404
cpp
C++
shader.cpp
a12n/rematrix
e539a5573a99665ba7b21e1c2114508060dcd163
[ "MIT" ]
2
2022-01-15T16:27:05.000Z
2022-01-15T16:48:03.000Z
shader.cpp
a12n/rematrix
e539a5573a99665ba7b21e1c2114508060dcd163
[ "MIT" ]
null
null
null
shader.cpp
a12n/rematrix
e539a5573a99665ba7b21e1c2114508060dcd163
[ "MIT" ]
null
null
null
#include "shader.hpp" namespace rematrix { shader::shader(GLenum type) : id{glCreateShader(type)} { if (id == 0) { throw runtime_error("couldn't create shader"); } } shader::shader(shader&& other) noexcept : id{other.id} { const_cast<GLuint&>(other.id) = 0; } shader::~shader() { glDeleteShader(id); } shader& shader::operator=(shader&& other) noexcept { const_cast<GLuint&>(id) = other.id; const_cast<GLuint&>(other.id) = 0; return *this; } void shader::compile(const char* src) { glShaderSource(id, 1, &src, nullptr); glCompileShader(id); GLint ok; glGetShaderiv(id, GL_COMPILE_STATUS, &ok); if (! ok) { GLint length; glGetShaderiv(id, GL_INFO_LOG_LENGTH, &length); string log(length, '\0'); glGetShaderInfoLog(id, length, nullptr, log.data()); throw runtime_error(log); } } //---------------------------------------------------------------------------- vertex_shader::vertex_shader() : shader{GL_VERTEX_SHADER} { } vertex_shader::vertex_shader(const char* src) : vertex_shader() { compile(src); } //---------------------------------------------------------------------------- fragment_shader::fragment_shader() : shader{GL_FRAGMENT_SHADER} { } fragment_shader::fragment_shader(const char* src) : fragment_shader() { compile(src); } } // namespace rematrix
18.72
78
0.569088
a12n
21183747e45a590a7bcb6551ed6718d017a80d99
181,084
cxx
C++
inetcore/winhttp/v5.1/ihttprequest/httprequest.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetcore/winhttp/v5.1/ihttprequest/httprequest.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetcore/winhttp/v5.1/ihttprequest/httprequest.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/* * HttpRequest.cxx * * WinHttp.WinHttpRequest COM component * * Copyright (C) 2000 Microsoft Corporation. All rights reserved. * * * Much of this code was stolen from our Xml-Http friends over in * inetcore\xml\http\xmlhttp.cxx. Thanks very much! * */ #include <wininetp.h> #include "httprequest.hxx" #include <olectl.h> #include "EnumConns.hxx" //IEnumConnections implementator #include "EnumCP.hxx" //IEnumConnectionPoints implementator #include "multilang.hxx" ///////////////////////////////////////////////////////////////////////////// // private function prototypes static void PreWideCharToUtf8(WCHAR * buffer, UINT cch, UINT * cb, bool * bSimpleConversion); static void WideCharToUtf8(WCHAR * buffer, UINT cch, BYTE * bytebuffer, bool bSimpleConversion); static HRESULT BSTRToUTF8(char ** psz, DWORD * pcbUTF8, BSTR bstr, bool * pbSetUtf8Charset); static HRESULT AsciiToBSTR(BSTR * pbstr, char * sz, int cch); static HRESULT GetBSTRFromVariant(VARIANT varVariant, BSTR * pBstr); static BOOL GetBoolFromVariant(VARIANT varVariant, BOOL fDefault); static DWORD GetDwordFromVariant(VARIANT varVariant, DWORD dwDefault); static long GetLongFromVariant(VARIANT varVariant, long lDefault); static HRESULT CreateVector(VARIANT * pVar, const BYTE * pData, DWORD cElems); static HRESULT ReadFromStream(char ** ppData, ULONG * pcbData, IStream * pStm); static void MessageLoop(); static DWORD UpdateTimeout(DWORD dwTimeout, DWORD dwStartTime); static HRESULT FillExcepInfo(HRESULT hr, EXCEPINFO * pExcepInfo); static BOOL IsValidVariant(VARIANT v); static HRESULT ParseSelectedCert(BSTR bstrSelection, LPBOOL pfLocalMachine, BSTR *pbstrStore, BSTR *pbstrSubject); static BOOL GetContentLengthIfResponseNotChunked(HINTERNET hHttpRequest, DWORD * pdwContentLength); static HRESULT SecureFailureFromStatus(DWORD dwFlags); static BOOL s_fWndClassRegistered; // Change the name of the window class for each new version of WinHTTP static const char * s_szWinHttpEventMarshallerWndClass = "_WinHttpEventMarshaller51"; static CMimeInfoCache* g_pMimeInfoCache = NULL; BOOL IsValidHeaderName(LPCWSTR lpszHeaderName); #define SafeRelease(p) \ { \ if (p) \ (p)->Release();\ (p) = NULL;\ } #ifndef HWND_MESSAGE #define HWND_MESSAGE ((HWND)-3) #endif #define SIZEOF_BUFFER (8192) inline BOOL IsValidBstr(BSTR bstr) { return (bstr == NULL) || (!IsBadStringPtrW(bstr, (UINT_PTR)-1)); } #ifndef WINHTTP_STATIC_LIBRARY STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, void ** ppv) { if (rclsid != CLSID_WinHttpRequest) return CLASS_E_CLASSNOTAVAILABLE; if (!WinHttpCheckPlatform()) return CLASS_E_CLASSNOTAVAILABLE; if (riid != IID_IClassFactory || ppv == NULL) return E_INVALIDARG; CClassFactory * pCF = New CClassFactory(); if (pCF) { *ppv = static_cast<IClassFactory *>(pCF); pCF->AddRef(); return NOERROR; } else { *ppv = NULL; return E_OUTOFMEMORY; } } CClassFactory::CClassFactory() { _cRefs = 0; InterlockedIncrement(&g_cSessionCount); } STDMETHODIMP CClassFactory::QueryInterface(REFIID riid, void ** ppvObject) { if (ppvObject == NULL) return E_INVALIDARG; if (riid == IID_IClassFactory || riid == IID_IUnknown) { *ppvObject = static_cast<IClassFactory *>(this); AddRef(); return NOERROR; } else return E_NOINTERFACE; } ULONG STDMETHODCALLTYPE CClassFactory::AddRef() { return ++_cRefs; } ULONG STDMETHODCALLTYPE CClassFactory::Release() { if (--_cRefs == 0) { delete this; InterlockedDecrement(&g_cSessionCount); return 0; } return _cRefs; } STDMETHODIMP CClassFactory::CreateInstance(IUnknown * pUnkOuter, REFIID riid, void ** ppvObject) { if (pUnkOuter != NULL) return CLASS_E_NOAGGREGATION; if (ppvObject == NULL) return E_INVALIDARG; if( !DelayLoad(&g_moduleOle32) || !DelayLoad(&g_moduleOleAut32)) { return E_UNEXPECTED; } return CreateHttpRequest(riid, ppvObject); } STDMETHODIMP CClassFactory::LockServer(BOOL fLock) { if (fLock) InterlockedIncrement(&g_cSessionCount); else InterlockedDecrement(&g_cSessionCount); return NOERROR; } STDAPI DllCanUnloadNow() { return ((g_cSessionCount == 0) && (g_pAsyncCount == NULL || g_pAsyncCount->GetRef() == 0)) ? S_OK : S_FALSE; } #else STDAPI WinHttpCreateHttpRequestComponent(REFIID riid, void ** ppvObject) { return CreateHttpRequest(riid, ppvObject); } #endif //WINHTTP_STATIC_LIBRARY STDMETHODIMP CreateHttpRequest(REFIID riid, void ** ppvObject) { CHttpRequest * pHttpRequest = New CHttpRequest(); HRESULT hr; if (pHttpRequest) { hr = pHttpRequest->QueryInterface(riid, ppvObject); if (FAILED(hr)) { delete pHttpRequest; } } else hr = E_OUTOFMEMORY; return hr; } /* * CHttpRequest::CHttpRequest constructor * */ CHttpRequest::CHttpRequest() { InterlockedIncrement(&g_cSessionCount); Initialize(); } /* * CHttpRequest::~CHttpRequest destructor * */ CHttpRequest::~CHttpRequest() { ReleaseResources(); InterlockedDecrement(&g_cSessionCount); } #define MIDL_DEFINE_GUID(type,name,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) \ const type name = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}} MIDL_DEFINE_GUID(IID, IID_IWinHttpRequest_TechBeta,0x06f29373,0x5c5a,0x4b54,0xb0,0x25,0x6e,0xf1,0xbf,0x8a,0xbf,0x0e); MIDL_DEFINE_GUID(IID, IID_IWinHttpRequestEvents_TechBeta,0xcff7bd4c,0x6689,0x4bbe,0x91,0xc2,0x0f,0x55,0x9e,0x8b,0x88,0xa7); HRESULT STDMETHODCALLTYPE CHttpRequest::QueryInterface(REFIID riid, void ** ppv) { HRESULT hr = NOERROR; if (ppv == NULL) { hr = E_INVALIDARG; } else if (riid == IID_IWinHttpRequest || riid == IID_IDispatch || riid == IID_IWinHttpRequest_TechBeta || riid == IID_IUnknown) { *ppv = static_cast<IWinHttpRequest *>(this); AddRef(); } else if (riid == IID_IConnectionPointContainer) { *ppv = static_cast<IConnectionPointContainer *>(this); AddRef(); } else if (riid == IID_ISupportErrorInfo) { *ppv = static_cast<ISupportErrorInfo *>(this); AddRef(); } else if (riid == IID_IProvideClassInfo) { *ppv = static_cast<IProvideClassInfo *>(static_cast<IProvideClassInfo2 *>(this)); AddRef(); } else if (riid == IID_IProvideClassInfo2) { *ppv = static_cast<IProvideClassInfo2 *>(this); AddRef(); } else hr = E_NOINTERFACE; return hr; } ULONG STDMETHODCALLTYPE CHttpRequest::AddRef() { if (GetCurrentThreadId() == _dwMainThreadId) ++_cRefsOnMainThread; return InterlockedIncrement(&_cRefs); } ULONG STDMETHODCALLTYPE CHttpRequest::Release() { if (GetCurrentThreadId() == _dwMainThreadId) { if ((--_cRefsOnMainThread == 0) && _fAsync) { // Clean up the Event Marshaller. This must be done // on the main thread. _CP.ShutdownEventSinksMarshaller(); // If the worker thread is still running, abort it // and wait for it to run down. Abort(); } } DWORD cRefs = InterlockedDecrement(&_cRefs); if (cRefs == 0) { delete this; return 0; } else return cRefs; } HRESULT CHttpRequest::GetHttpRequestTypeInfo(REFGUID guid, ITypeInfo ** ppTypeInfo) { HRESULT hr = NOERROR; ITypeLib * pTypeLib; char szPath[MAX_PATH+1]; OLECHAR wszPath[MAX_PATH+1]; GetModuleFileName(GlobalDllHandle, szPath, sizeof(szPath)-1); // leave room for null char szPath[sizeof(szPath)-1] = '\0'; // guarantee null-termination MultiByteToWideChar(CP_ACP, 0, szPath, -1, wszPath, MAX_PATH); hr = DL(LoadTypeLib)(wszPath, &pTypeLib); if (SUCCEEDED(hr)) { hr = pTypeLib->GetTypeInfoOfGuid(guid, ppTypeInfo); pTypeLib->Release(); } return hr; } STDMETHODIMP CHttpRequest::GetTypeInfoCount(UINT * pctinfo) { if (!pctinfo) return E_INVALIDARG; *pctinfo = 1; return NOERROR; } STDMETHODIMP CHttpRequest::GetTypeInfo(UINT iTInfo, LCID, ITypeInfo ** ppTInfo) { if (!ppTInfo) return E_INVALIDARG; *ppTInfo = NULL; if (iTInfo != 0) return DISP_E_BADINDEX; if (!_pTypeInfo) { HRESULT hr = GetHttpRequestTypeInfo(IID_IWinHttpRequest, &_pTypeInfo); if (FAILED(hr)) return hr; } *ppTInfo = _pTypeInfo; _pTypeInfo->AddRef(); return NOERROR; } struct IDMAPPING { const OLECHAR * wszMemberName; DISPID dispId; }; static const IDMAPPING IdMapping[] = { { L"Open", DISPID_HTTPREQUEST_OPEN }, { L"SetRequestHeader", DISPID_HTTPREQUEST_SETREQUESTHEADER }, { L"Send", DISPID_HTTPREQUEST_SEND }, { L"Status", DISPID_HTTPREQUEST_STATUS }, { L"WaitForResponse", DISPID_HTTPREQUEST_WAITFORRESPONSE }, { L"GetResponseHeader", DISPID_HTTPREQUEST_GETRESPONSEHEADER }, { L"ResponseBody", DISPID_HTTPREQUEST_RESPONSEBODY }, { L"ResponseText", DISPID_HTTPREQUEST_RESPONSETEXT }, { L"ResponseStream", DISPID_HTTPREQUEST_RESPONSESTREAM }, { L"StatusText", DISPID_HTTPREQUEST_STATUSTEXT }, { L"SetAutoLogonPolicy", DISPID_HTTPREQUEST_SETAUTOLOGONPOLICY }, { L"SetClientCertificate", DISPID_HTTPREQUEST_SETCLIENTCERTIFICATE }, { L"SetCredentials", DISPID_HTTPREQUEST_SETCREDENTIALS }, { L"SetProxy", DISPID_HTTPREQUEST_SETPROXY }, { L"GetAllResponseHeaders", DISPID_HTTPREQUEST_GETALLRESPONSEHEADERS }, { L"Abort", DISPID_HTTPREQUEST_ABORT }, { L"SetTimeouts", DISPID_HTTPREQUEST_SETTIMEOUTS }, { L"Option", DISPID_HTTPREQUEST_OPTION } }; STDMETHODIMP CHttpRequest::GetIDsOfNames(REFIID riid, LPOLESTR * rgszNames, UINT cNames, LCID , DISPID * rgDispId) { if (riid != IID_NULL) return E_INVALIDARG; HRESULT hr = NOERROR; if (cNames > 0) { hr = DISP_E_UNKNOWNNAME; for (int i = 0; i < (sizeof(IdMapping)/sizeof(IdMapping[0])); i++) { if (StrCmpIW(rgszNames[0], IdMapping[i].wszMemberName) == 0) { hr = NOERROR; rgDispId[0] = IdMapping[i].dispId; break; } } } return hr; } // _DispGetParamSafe // // A wrapper around the OLE Automation DispGetParam API that protects // the call with a __try/__except block. Needed for casting to BSTR, // as bogus BSTR pointers can cause an AV in VariantChangeType (which // DispGetParam calls). // static HRESULT _DispGetParamSafe ( DISPPARAMS * pDispParams, DISPID dispid, VARTYPE vt, VARIANT * pvarResult, unsigned int * puArgErr ) { HRESULT hr; __try { hr = DL(DispGetParam)(pDispParams, dispid, vt, pvarResult, puArgErr); } __except (EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } return hr; } // _DispGetOptionalParam // // Helper routine to fetch optional parameters. If DL(DispGetParam) returns // DISP_E_PARAMNOTFOUND, the error is converted to NOERROR. // static inline HRESULT _DispGetOptionalParam ( DISPPARAMS * pDispParams, DISPID dispid, VARTYPE vt, VARIANT * pvarResult, unsigned int * puArgErr ) { HRESULT hr = _DispGetParamSafe(pDispParams, dispid, vt, pvarResult, puArgErr); return (hr == DISP_E_PARAMNOTFOUND) ? NOERROR : hr; } STDMETHODIMP CHttpRequest::Invoke(DISPID dispIdMember, REFIID riid, LCID, WORD wFlags, DISPPARAMS * pDispParams, VARIANT * pVarResult, EXCEPINFO * pExcepInfo, UINT * puArgErr) { HRESULT hr = NOERROR; unsigned int uArgErr; if (wFlags & ~(DISPATCH_METHOD | DISPATCH_PROPERTYGET | DISPATCH_PROPERTYPUT)) return E_INVALIDARG; if (riid != IID_NULL) return DISP_E_UNKNOWNINTERFACE; if (IsBadReadPtr(pDispParams, sizeof(DISPPARAMS))) return E_INVALIDARG; if (!puArgErr) { puArgErr = &uArgErr; } else if (IsBadWritePtr(puArgErr, sizeof(UINT))) { return E_INVALIDARG; } if (pVarResult) { if (IsBadWritePtr(pVarResult, sizeof(VARIANT))) return E_INVALIDARG; DL(VariantInit)(pVarResult); } switch (dispIdMember) { case DISPID_HTTPREQUEST_ABORT: { hr = Abort(); break; } case DISPID_HTTPREQUEST_SETPROXY: { VARIANT varProxySetting; VARIANT varProxyServer; VARIANT varBypassList; DL(VariantInit)(&varProxySetting); DL(VariantInit)(&varProxyServer); DL(VariantInit)(&varBypassList); hr = DL(DispGetParam)(pDispParams, 0, VT_I4, &varProxySetting, puArgErr); if (SUCCEEDED(hr)) { hr = _DispGetOptionalParam(pDispParams, 1, VT_BSTR, &varProxyServer, puArgErr); } if (SUCCEEDED(hr)) { hr = _DispGetOptionalParam(pDispParams, 2, VT_BSTR, &varBypassList, puArgErr); } if (SUCCEEDED(hr)) { hr = SetProxy(V_I4(&varProxySetting), varProxyServer, varBypassList); } DL(VariantClear)(&varProxySetting); DL(VariantClear)(&varProxyServer); DL(VariantClear)(&varBypassList); break; } case DISPID_HTTPREQUEST_SETCREDENTIALS: { VARIANT varUserName; VARIANT varPassword; VARIANT varAuthTarget; DL(VariantInit)(&varUserName); DL(VariantInit)(&varPassword); DL(VariantInit)(&varAuthTarget); hr = _DispGetParamSafe(pDispParams, 0, VT_BSTR, &varUserName, puArgErr); if (SUCCEEDED(hr)) { hr = _DispGetParamSafe(pDispParams, 1, VT_BSTR, &varPassword, puArgErr); } if (SUCCEEDED(hr)) { hr = DL(DispGetParam)(pDispParams, 2, VT_I4, &varAuthTarget, puArgErr); } if (SUCCEEDED(hr)) { hr = SetCredentials(V_BSTR(&varUserName), V_BSTR(&varPassword), V_I4(&varAuthTarget)); } DL(VariantClear)(&varUserName); DL(VariantClear)(&varPassword); DL(VariantClear)(&varAuthTarget); break; } case DISPID_HTTPREQUEST_OPEN: { VARIANT varMethod; VARIANT varUrl; VARIANT varAsync; DL(VariantInit)(&varMethod); DL(VariantInit)(&varUrl); DL(VariantInit)(&varAsync); hr = _DispGetParamSafe(pDispParams, 0, VT_BSTR, &varMethod, puArgErr); if (SUCCEEDED(hr)) { hr = _DispGetParamSafe(pDispParams, 1, VT_BSTR, &varUrl, puArgErr); } if (SUCCEEDED(hr)) { hr = _DispGetOptionalParam(pDispParams, 2, VT_BOOL, &varAsync, puArgErr); } if (SUCCEEDED(hr)) { hr = Open(V_BSTR(&varMethod), V_BSTR(&varUrl), varAsync); } DL(VariantClear)(&varMethod); DL(VariantClear)(&varUrl); DL(VariantClear)(&varAsync); break; } case DISPID_HTTPREQUEST_SETREQUESTHEADER: { VARIANT varHeader; VARIANT varValue; DL(VariantInit)(&varHeader); DL(VariantInit)(&varValue); hr = _DispGetParamSafe(pDispParams, 0, VT_BSTR, &varHeader, puArgErr); if (SUCCEEDED(hr)) { hr = _DispGetParamSafe(pDispParams, 1, VT_BSTR, &varValue, puArgErr); } if (SUCCEEDED(hr)) { hr = SetRequestHeader(V_BSTR(&varHeader), V_BSTR(&varValue)); } DL(VariantClear)(&varHeader); DL(VariantClear)(&varValue); break; } case DISPID_HTTPREQUEST_GETRESPONSEHEADER: { VARIANT varHeader; DL(VariantInit)(&varHeader); hr = _DispGetParamSafe(pDispParams, 0, VT_BSTR, &varHeader, puArgErr); if (SUCCEEDED(hr)) { BSTR bstrValue = NULL; hr = GetResponseHeader(V_BSTR(&varHeader), &bstrValue); if (SUCCEEDED(hr) && pVarResult) { V_VT(pVarResult) = VT_BSTR; V_BSTR(pVarResult) = bstrValue; } else DL(SysFreeString)(bstrValue); } DL(VariantClear)(&varHeader); break; } case DISPID_HTTPREQUEST_GETALLRESPONSEHEADERS: { BSTR bstrResponseHeaders = NULL; hr = GetAllResponseHeaders(&bstrResponseHeaders); if (SUCCEEDED(hr) && pVarResult) { V_VT(pVarResult) = VT_BSTR; V_BSTR(pVarResult) = bstrResponseHeaders; } else DL(SysFreeString)(bstrResponseHeaders); break; } case DISPID_HTTPREQUEST_SEND: { if (pDispParams->cArgs <= 1) { VARIANT varEmptyBody; DL(VariantInit)(&varEmptyBody); hr = Send((pDispParams->cArgs == 0) ? varEmptyBody : pDispParams->rgvarg[0]); } else { hr = DISP_E_BADPARAMCOUNT; } break; } case DISPID_HTTPREQUEST_STATUS: { long Status; hr = get_Status(&Status); if (SUCCEEDED(hr) && pVarResult) { V_VT(pVarResult) = VT_I4; V_I4(pVarResult) = Status; } break; } case DISPID_HTTPREQUEST_STATUSTEXT: { BSTR bstrStatus = NULL; hr = get_StatusText(&bstrStatus); if (SUCCEEDED(hr) && pVarResult) { V_VT(pVarResult) = VT_BSTR; V_BSTR(pVarResult) = bstrStatus; } else DL(SysFreeString)(bstrStatus); break; } case DISPID_HTTPREQUEST_RESPONSETEXT: { BSTR bstrResponse = NULL; hr = get_ResponseText(&bstrResponse); if (SUCCEEDED(hr) && pVarResult) { V_VT(pVarResult) = VT_BSTR; V_BSTR(pVarResult) = bstrResponse; } else DL(SysFreeString)(bstrResponse); break; } case DISPID_HTTPREQUEST_RESPONSEBODY: { if (pVarResult) { hr = get_ResponseBody(pVarResult); } break; } case DISPID_HTTPREQUEST_RESPONSESTREAM: { if (pVarResult) { hr = get_ResponseStream(pVarResult); } break; } case DISPID_HTTPREQUEST_OPTION: { VARIANT varOption; WinHttpRequestOption Option; DL(VariantInit)(&varOption); hr = DL(DispGetParam)(pDispParams, 0, VT_I4, &varOption, puArgErr); if (FAILED(hr)) break; Option = static_cast<WinHttpRequestOption>(V_I4(&varOption)); if (wFlags & (DISPATCH_METHOD | DISPATCH_PROPERTYGET)) { if (pVarResult) { hr = get_Option(Option, pVarResult); } } else if (wFlags & DISPATCH_PROPERTYPUT) { hr = put_Option(Option, pDispParams->rgvarg[0]); } DL(VariantClear)(&varOption); break; } case DISPID_HTTPREQUEST_WAITFORRESPONSE: { VARIANT varTimeout; VARIANT_BOOL boolSucceeded = FALSE; DL(VariantInit)(&varTimeout); hr = _DispGetOptionalParam(pDispParams, 0, VT_I4, &varTimeout, puArgErr); if (SUCCEEDED(hr)) { hr = WaitForResponse(varTimeout, &boolSucceeded); } if (pVarResult) { V_VT(pVarResult) = VT_BOOL; V_BOOL(pVarResult) = boolSucceeded; } DL(VariantClear)(&varTimeout); break; } case DISPID_HTTPREQUEST_SETTIMEOUTS: { VARIANT varResolveTimeout; VARIANT varConnectTimeout; VARIANT varSendTimeout; VARIANT varReceiveTimeout; DL(VariantInit)(&varResolveTimeout); DL(VariantInit)(&varConnectTimeout); DL(VariantInit)(&varSendTimeout); DL(VariantInit)(&varReceiveTimeout); hr = DL(DispGetParam)(pDispParams, 0, VT_I4, &varResolveTimeout, puArgErr); if (SUCCEEDED(hr)) { hr = DL(DispGetParam)(pDispParams, 1, VT_I4, &varConnectTimeout, puArgErr); } if (SUCCEEDED(hr)) { hr = DL(DispGetParam)(pDispParams, 2, VT_I4, &varSendTimeout, puArgErr); } if (SUCCEEDED(hr)) { hr = DL(DispGetParam)(pDispParams, 3, VT_I4, &varReceiveTimeout, puArgErr); } if (SUCCEEDED(hr)) { hr = SetTimeouts(V_I4(&varResolveTimeout), V_I4(&varConnectTimeout), V_I4(&varSendTimeout), V_I4(&varReceiveTimeout)); } DL(VariantClear)(&varResolveTimeout); DL(VariantClear)(&varConnectTimeout); DL(VariantClear)(&varSendTimeout); DL(VariantClear)(&varReceiveTimeout); break; } case DISPID_HTTPREQUEST_SETCLIENTCERTIFICATE: { VARIANT varClientCertificate; DL(VariantInit)(&varClientCertificate); hr = _DispGetParamSafe(pDispParams, 0, VT_BSTR, &varClientCertificate, puArgErr); if (SUCCEEDED(hr)) { hr = SetClientCertificate(V_BSTR(&varClientCertificate)); } DL(VariantClear)(&varClientCertificate); break; } case DISPID_HTTPREQUEST_SETAUTOLOGONPOLICY: { VARIANT varAutoLogonPolicy; DL(VariantInit)(&varAutoLogonPolicy); hr = DL(DispGetParam)(pDispParams, 0, VT_I4, &varAutoLogonPolicy, puArgErr); if (SUCCEEDED(hr)) { WinHttpRequestAutoLogonPolicy AutoLogonPolicy; AutoLogonPolicy = static_cast<WinHttpRequestAutoLogonPolicy>(V_I4(&varAutoLogonPolicy)); hr = SetAutoLogonPolicy(AutoLogonPolicy); } DL(VariantClear)(&varAutoLogonPolicy); break; } default: hr = DISP_E_MEMBERNOTFOUND; break; } if (FAILED(hr) && (pExcepInfo != NULL)) { hr = FillExcepInfo(hr, pExcepInfo); } return hr; } static HRESULT FillExcepInfo(HRESULT hr, EXCEPINFO * pExcepInfo) { // Don't create excepinfo for these errors to mimic oleaut behavior. if( hr == DISP_E_BADPARAMCOUNT || hr == DISP_E_NONAMEDARGS || hr == DISP_E_MEMBERNOTFOUND || hr == E_INVALIDARG) { return hr; } // clear out exception info IErrorInfo * pei = NULL; pExcepInfo->wCode = 0; pExcepInfo->scode = hr; // if error info exists, use it DL(GetErrorInfo)(0, &pei); if (pei) { // give back to OLE DL(SetErrorInfo)(0, pei); pei->GetHelpContext(&pExcepInfo->dwHelpContext); pei->GetSource(&pExcepInfo->bstrSource); pei->GetDescription(&pExcepInfo->bstrDescription); pei->GetHelpFile(&pExcepInfo->bstrHelpFile); // give complete ownership to OLEAUT pei->Release(); hr = DISP_E_EXCEPTION; } return hr; } STDMETHODIMP CHttpRequest::InterfaceSupportsErrorInfo(REFIID riid) { return (riid == IID_IWinHttpRequest) ? S_OK : S_FALSE; } STDMETHODIMP CHttpRequest::GetClassInfo(ITypeInfo ** ppTI) { if (!ppTI) return E_POINTER; *ppTI = NULL; return GetHttpRequestTypeInfo(CLSID_WinHttpRequest, ppTI); } STDMETHODIMP CHttpRequest::GetGUID(DWORD dwGuidKind, GUID * pGUID) { if (!pGUID) return E_POINTER; if (dwGuidKind == GUIDKIND_DEFAULT_SOURCE_DISP_IID) { *pGUID = IID_IWinHttpRequestEvents; } else return E_INVALIDARG; return NOERROR; } STDMETHODIMP CHttpRequest::EnumConnectionPoints(IEnumConnectionPoints ** ppEnum) { if (!ppEnum) return E_POINTER; *ppEnum = static_cast<IEnumConnectionPoints*>( new CEnumConnectionPoints(static_cast<IConnectionPoint*>(&_CP)) ); return (*ppEnum) ? S_OK : E_OUTOFMEMORY; } STDMETHODIMP CHttpRequest::FindConnectionPoint(REFIID riid, IConnectionPoint ** ppCP) { if (!ppCP) return E_POINTER; if (riid == IID_IWinHttpRequestEvents) { return _CP.QueryInterface(IID_IConnectionPoint, (void **)ppCP); } else if (riid == IID_IWinHttpRequestEvents_TechBeta) { _CP.DisableOnError(); return _CP.QueryInterface(IID_IConnectionPoint, (void **)ppCP); } else return CONNECT_E_NOCONNECTION; } STDMETHODIMP CHttpRequest::CHttpRequestEventsCP::QueryInterface(REFIID riid, void ** ppvObject) { if (!ppvObject) return E_INVALIDARG; if (riid == IID_IUnknown || riid == IID_IConnectionPoint) { *ppvObject = static_cast<IUnknown *>(static_cast<IConnectionPoint *>(this)); AddRef(); return NOERROR; } return E_NOINTERFACE; } ULONG STDMETHODCALLTYPE CHttpRequest::CHttpRequestEventsCP::AddRef() { return Px()->AddRef(); } ULONG STDMETHODCALLTYPE CHttpRequest::CHttpRequestEventsCP::Release() { return Px()->Release(); } STDMETHODIMP CHttpRequest::CHttpRequestEventsCP::GetConnectionInterface(IID * pIID) { if (!pIID) return E_POINTER; *pIID = IID_IWinHttpRequestEvents; return NOERROR; } STDMETHODIMP CHttpRequest::CHttpRequestEventsCP::GetConnectionPointContainer ( IConnectionPointContainer ** ppCPC ) { if (!ppCPC) return E_POINTER; return Px()->QueryInterface(IID_IConnectionPointContainer, (void **)ppCPC); } STDMETHODIMP CHttpRequest::CHttpRequestEventsCP::Advise(IUnknown * pUnk, DWORD * pdwCookie) { if (!pUnk || !pdwCookie) { return E_POINTER; } IWinHttpRequestEvents * pIWinHttpRequestEvents; HRESULT hr; hr = pUnk->QueryInterface(IID_IWinHttpRequestEvents, (void **)&pIWinHttpRequestEvents); // RENO 39279: if the QI for IWinHttpRequestEvents fails, try the older // IID from the Tech Beta. if (FAILED(hr)) { hr = pUnk->QueryInterface(IID_IWinHttpRequestEvents_TechBeta, (void **)&pIWinHttpRequestEvents); if (SUCCEEDED(hr)) { // The OnError event should have already been disabled in // CHttpRequest::FindConnectionPoint(), but it doesn't // hurt to be paranoid. DisableOnError(); } } if (SUCCEEDED(hr)) { *pdwCookie = _SinkArray.Add(static_cast<IUnknown *>(pIWinHttpRequestEvents)); if (*pdwCookie) { _cConnections++; hr = NOERROR; } else { hr = E_OUTOFMEMORY; } } else hr = CONNECT_E_CANNOTCONNECT; return hr; } STDMETHODIMP CHttpRequest::CHttpRequestEventsCP::Unadvise(DWORD dwCookie) { IUnknown * pSink = _SinkArray.GetUnknown(dwCookie); if (pSink) { _SinkArray.Remove(dwCookie); pSink->Release(); --_cConnections; } return NOERROR; } STDMETHODIMP CHttpRequest::CHttpRequestEventsCP::EnumConnections(IEnumConnections ** ppEnum) { if (!ppEnum) return E_POINTER; *ppEnum = NULL; DWORD_PTR size = _SinkArray.end() - _SinkArray.begin(); CONNECTDATA* pCD = NULL; if (size != 0) { //allocate data on stack, we usually expect just 1 or few connections, //so it's ok to allocate such ammount of data on stack __try { pCD = (CONNECTDATA*)_alloca(size * sizeof(CONNECTDATA[1])); } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { return E_OUTOFMEMORY; } } IUnknown** ppUnk = _SinkArray.begin(); for (DWORD i = 0; i < size; ++i) { pCD[i].pUnk = ppUnk[i]; pCD[i].dwCookie = i + 1; } CEnumConnections* pE = new CEnumConnections(); if (pE) { HRESULT hr = pE->Init(pCD, (DWORD)size); if ( SUCCEEDED(hr) ) *ppEnum = static_cast<IEnumConnections*>(pE); else delete pE; return hr; } else return E_OUTOFMEMORY; } void CHttpRequest::CHttpRequestEventsCP::FireOnResponseStart(long Status, BSTR ContentType) { if (_cConnections > 0 && !Px()->_bAborted) { GetSink()->OnResponseStart(Status, ContentType); } } void CHttpRequest::CHttpRequestEventsCP::FireOnResponseDataAvailable ( const BYTE * rgbData, DWORD cbData ) { if (_cConnections > 0 && !Px()->_bAborted) { VARIANT varData; HRESULT hr; DL(VariantInit)(&varData); hr = CreateVector(&varData, rgbData, cbData); if (SUCCEEDED(hr)) { GetSink()->OnResponseDataAvailable(&V_ARRAY(&varData)); } DL(VariantClear)(&varData); } } void CHttpRequest::CHttpRequestEventsCP::FireOnResponseFinished() { if (_cConnections > 0 && !Px()->_bAborted) { GetSink()->OnResponseFinished(); } } void CHttpRequest::CHttpRequestEventsCP::FireOnError(HRESULT hr) { if ((_cConnections > 0) && (!Px()->_bAborted) && (!_bOnErrorDisabled)) { IErrorInfo * pErrorInfo = CreateErrorObject(hr); BSTR bstrErrorDescription = NULL; if (pErrorInfo) { pErrorInfo->GetDescription(&bstrErrorDescription); pErrorInfo->Release(); } GetSink()->OnError((long) hr, bstrErrorDescription); DL(SysFreeString)(bstrErrorDescription); } } HRESULT CHttpRequest::CHttpRequestEventsCP::CreateEventSinksMarshaller() { HRESULT hr = NOERROR; if (_cConnections > 0) { SafeRelease(_pSinkMarshaller); hr = CWinHttpRequestEventsMarshaller::Create(&_SinkArray, &_pSinkMarshaller); } return hr; } void CHttpRequest::CHttpRequestEventsCP::ShutdownEventSinksMarshaller() { if (_pSinkMarshaller) _pSinkMarshaller->Shutdown(); } void CHttpRequest::CHttpRequestEventsCP::ReleaseEventSinksMarshaller() { SafeRelease(_pSinkMarshaller); } void CHttpRequest::CHttpRequestEventsCP::FreezeEvents() { if (_pSinkMarshaller) _pSinkMarshaller->FreezeEvents(); } void CHttpRequest::CHttpRequestEventsCP::UnfreezeEvents() { if (_pSinkMarshaller) _pSinkMarshaller->UnfreezeEvents(); } CHttpRequest::CHttpRequestEventsCP::~CHttpRequestEventsCP() { // If any connections are still alive, unadvise them. if (_cConnections > 0) { _SinkArray.ReleaseAll(); _cConnections = 0; } } /* * CHttpRequest::Initialize * * Purpose: * Zero all data members * */ void CHttpRequest::Initialize() { _cRefs = 0; _pTypeInfo = NULL; _bstrUserAgent = NULL; _dwProxySetting = WINHTTP_ACCESS_TYPE_DEFAULT_PROXY; _bstrProxyServer = NULL; _bstrBypassList = NULL; _eState = CHttpRequest::CREATED; _fAsync = FALSE; #if !defined(TRUE_ASYNC) _hWorkerThread = NULL; #endif//!TRUE_ASYNC _cRefsOnMainThread = 0; _dwMainThreadId = GetCurrentThreadId(); _hrAsyncResult = NOERROR; _bAborted = false; _bSetTimeouts = false; _bSetUtf8Charset = false; _hInet = NULL; _hConnection = NULL; _hHTTP = NULL; _ResolveTimeout = 0; _ConnectTimeout = 0; _SendTimeout = 0; _ReceiveTimeout = 0; _cbRequestBody = 0; _szRequestBuffer = NULL; _dwCodePage = CP_UTF8; _dwEscapeFlag = WINHTTP_FLAG_ESCAPE_DISABLE_QUERY; _cbResponseBody = 0; _pResponseStream = NULL; _hAbortedConnectObject = NULL; _hAbortedRequestObject = NULL; _bstrCertSubject = NULL; _bstrCertStore = NULL; _fCertLocalMachine = FALSE; _fCheckForRevocation = FALSE; _dwSslIgnoreFlags = 0; _dwSecureProtocols = DEFAULT_SECURE_PROTOCOLS; _hrSecureFailure = HRESULT_FROM_WIN32(ERROR_WINHTTP_SECURE_FAILURE); _bEnableSslImpersonation = FALSE; _bMethodGET = FALSE; _bHttp1_1Mode = TRUE; #ifdef TRUE_ASYNC _hCompleteEvent = NULL; _bRetriedWithCert = FALSE; _Buffer = NULL; #endif _dwAutoLogonPolicy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_DEFAULT; _dwRedirectPolicy = WINHTTP_OPTION_REDIRECT_POLICY_DEFAULT; _lMaxAutomaticRedirects = GlobalMaxHttpRedirects; _lMaxResponseHeaderSize = GlobalMaxHeaderSize; _lMaxResponseDrainSize = GlobalMaxDrainSize; _dwPassportConfig = (WINHTTP_DISABLE_PASSPORT_AUTH | WINHTTP_DISABLE_PASSPORT_KEYRING); } /* * CHttpRequest::ReleaseResources * * Purpose: * Release all handles, events, and buffers * */ void CHttpRequest::ReleaseResources() { SafeRelease(_pTypeInfo); #if !defined(TRUE_ASYNC) if (_hWorkerThread) { CloseHandle(_hWorkerThread); _hWorkerThread = NULL; } #endif//!TRUE_ASYNC _CP.ReleaseEventSinksMarshaller(); // // Derefence aborted handle objects (if any). // if (_hAbortedRequestObject != NULL) { DereferenceObject(_hAbortedRequestObject); _hAbortedRequestObject = NULL; } if (_hAbortedConnectObject != NULL) { DereferenceObject(_hAbortedConnectObject); _hAbortedConnectObject = NULL; } if (_hHTTP) { HINTERNET temp = _hHTTP; _hHTTP = NULL; WinHttpCloseHandle(temp); } if (_hConnection) { HINTERNET temp = _hConnection; _hConnection = NULL; WinHttpCloseHandle(temp); } if (_hInet) { HINTERNET temp = _hInet; _hInet = NULL; WinHttpCloseHandle(temp); } if (_szRequestBuffer) { delete [] _szRequestBuffer; _szRequestBuffer = NULL; } SafeRelease(_pResponseStream); if (_bstrUserAgent) { DL(SysFreeString)(_bstrUserAgent); _bstrUserAgent = NULL; } if (_bstrProxyServer) { DL(SysFreeString)(_bstrProxyServer); _bstrProxyServer = NULL; } if (_bstrBypassList) { DL(SysFreeString)(_bstrBypassList); _bstrBypassList = NULL; } if (_bstrCertSubject) { DL(SysFreeString)(_bstrCertSubject); _bstrCertSubject = NULL; } if (_bstrCertStore) { DL(SysFreeString)(_bstrCertStore); _bstrCertStore = NULL; } #ifdef TRUE_ASYNC if (_hCompleteEvent != NULL) { CloseHandle(_hCompleteEvent); _hCompleteEvent = NULL; } if (_Buffer != NULL) { delete [] _Buffer; } #endif } /* * CHttpRequest::Reset * * Purpose: * Release all resources and initialize data members * */ void CHttpRequest::Reset() { ReleaseResources(); Initialize(); } /* * CHttpRequest::Recycle * * Purpose: * Recycle object * */ void CHttpRequest::Recycle() { DEBUG_ENTER((DBG_HTTP, None, "IWinHttpRequest::Recycle", NULL)); // // Wait for the worker thread to shut down. This shouldn't take long // since the Abort will close the Request and Connection handles. // if ( #ifdef TRUE_ASYNC _hCompleteEvent #else _hWorkerThread #endif//TRUE_ASYNC ) { DWORD dwWaitResult; for (;;) { dwWaitResult = MsgWaitForMultipleObjects(1, #ifdef TRUE_ASYNC &_hCompleteEvent #else &_hWorkerThread #endif//TRUE_ASYNC , FALSE, INFINITE, QS_ALLINPUT); if (dwWaitResult == (WAIT_OBJECT_0 + 1)) { // Message waiting in the message queue. // Run message pump to clear queue. MessageLoop(); } else { break; } } #ifdef TRUE_ASYNC CloseHandle(_hCompleteEvent); _hCompleteEvent = NULL; #else CloseHandle(_hWorkerThread); _hWorkerThread = NULL; #endif//TRUE_ASYNC } _hConnection = NULL; _hHTTP = NULL; // // Derefence aborted handle objects (if any). // if (_hAbortedRequestObject != NULL) { DereferenceObject(_hAbortedRequestObject); _hAbortedRequestObject = NULL; } if (_hAbortedConnectObject != NULL) { DereferenceObject(_hAbortedConnectObject); _hAbortedConnectObject = NULL; } //sergekh: we shouldn't reset _fAsync to know the state of _hInet //_fAsync = FALSE; _hrAsyncResult = NOERROR; _bAborted = false; // don't reset timeouts, keep any that were set. _cbRequestBody = 0; _cbResponseBody = 0; if (_szRequestBuffer) { delete [] _szRequestBuffer; _szRequestBuffer = NULL; } SafeRelease(_pResponseStream); _CP.ShutdownEventSinksMarshaller(); _CP.ReleaseEventSinksMarshaller(); // Allow events to fire; Abort() would have frozen them from firing. _CP.UnfreezeEvents(); SetState(CHttpRequest::CREATED); DEBUG_LEAVE(0); } static BOOL GetContentLengthIfResponseNotChunked( HINTERNET hHttpRequest, DWORD * pdwContentLength ) { char szTransferEncoding[16]; // big enough for "chunked" or "identity" DWORD cb; BOOL fRetCode; cb = sizeof(szTransferEncoding) - 1; fRetCode = HttpQueryInfoA( hHttpRequest, WINHTTP_QUERY_CONTENT_TRANSFER_ENCODING, WINHTTP_HEADER_NAME_BY_INDEX, szTransferEncoding, &cb, 0); if (!fRetCode || lstrcmpi(szTransferEncoding, "identity") == 0) { // Determine the content length cb = sizeof(DWORD); fRetCode = HttpQueryInfoA( hHttpRequest, WINHTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX, pdwContentLength, &cb, 0); } else { fRetCode = FALSE; } return fRetCode; } /* * CHttpRequest::ReadResponse * * Purpose: * Read the response bits * * Parameters: * None * * Errors: * E_FAIL * E_OUTOFMEMORY */ HRESULT CHttpRequest::ReadResponse() { HRESULT hr = NOERROR; BOOL fRetCode; long lStatus; BSTR bstrContentType = NULL; DWORD dwContentLength = 0; BYTE * Buffer = NULL; SetState(CHttpRequest::RECEIVING); hr = get_Status(&lStatus); if (FAILED(hr)) goto Error; hr = _GetResponseHeader(L"Content-Type", &bstrContentType); if (FAILED(hr)) { bstrContentType = DL(SysAllocString)(L""); if (bstrContentType == NULL) goto ErrorOutOfMemory; hr = NOERROR; } INET_ASSERT((_pResponseStream == NULL) && (_cbResponseBody == 0)); hr = DL(CreateStreamOnHGlobal)(NULL, TRUE, &_pResponseStream); if (SUCCEEDED(hr)) { // Determine the content length fRetCode = GetContentLengthIfResponseNotChunked(_hHTTP, &dwContentLength); // pre-set response stream size if we have a Content-Length if (fRetCode) { ULARGE_INTEGER size; size.LowPart = dwContentLength; size.HighPart = 0; _pResponseStream->SetSize(size); } else { // Content-Length was not specified in the response, but this // does not mean Content-Length==0. We will keep reading until // either no more data is available. Set dwContentLength to 4GB // to trick our read loop into reading until eof is reached. dwContentLength = (DWORD)(-1L); ULARGE_INTEGER size; // Set initial size of the response stream to 8K. size.LowPart = SIZEOF_BUFFER; size.HighPart = 0; _pResponseStream->SetSize(size); } } else goto ErrorOutOfMemory; // // Allocate an 8K buffer to read the response data in chunks. // Buffer = New BYTE[SIZEOF_BUFFER]; if (!Buffer) { goto ErrorOutOfMemory; } // // Fire the initial OnResponseStart event // _CP.FireOnResponseStart(lStatus, bstrContentType); // Skip read loop if Content-Length==0. if (dwContentLength == 0) { goto Finished; } // // Read data until there is no more - we need to buffer the data // while (!_bAborted) { DWORD cbAvail = 0; DWORD cbRead = 0; fRetCode = WinHttpQueryDataAvailable(_hHTTP, &cbAvail); if (!fRetCode) { goto ErrorFail; } // Read up to 8K (sizeof Buffer) of data. cbAvail = min(cbAvail, SIZEOF_BUFFER); fRetCode = WinHttpReadData(_hHTTP, Buffer, cbAvail, &cbRead); if (!fRetCode) { goto ErrorFail; } if (cbRead != 0) { hr = _pResponseStream->Write(Buffer, cbRead, NULL); if (FAILED(hr)) { goto ErrorOutOfMemory; } _CP.FireOnResponseDataAvailable((const BYTE *)Buffer, cbRead); _cbResponseBody += cbRead; } // If WinHttpReadData indicates there is no more data to read, // or we've read as much data as the Content-Length header tells // us to expect, then we're finished reading the response. if ((cbRead == 0) || (_cbResponseBody >= dwContentLength)) { ULARGE_INTEGER size; // set final size on stream size.LowPart = _cbResponseBody; size.HighPart = 0; _pResponseStream->SetSize(size); break; } } Finished: SetState(CHttpRequest::RESPONSE); _CP.FireOnResponseFinished(); hr = NOERROR; Cleanup: if (bstrContentType) DL(SysFreeString)(bstrContentType); if (Buffer) delete [] Buffer; return hr; ErrorOutOfMemory: hr = E_OUTOFMEMORY; goto Error; ErrorFail: hr = HRESULT_FROM_WIN32(::GetLastError()); _CP.FireOnError(hr); goto Error; Error: SafeRelease(_pResponseStream); _cbResponseBody = NULL; goto Cleanup; } STDMETHODIMP CHttpRequest::SetProxy(HTTPREQUEST_PROXY_SETTING ProxySetting, VARIANT varProxyServer, VARIANT varBypassList) { HRESULT hr = NOERROR; if (!IsValidVariant(varProxyServer) || !IsValidVariant(varBypassList)) return E_INVALIDARG; DEBUG_ENTER_API((DBG_HTTP, Dword, "IWinHttpRequest::SetProxy", "HTTPREQUEST_PROXY_SETTING: %d, VARIANT, VARIANT", ProxySetting )); if (_bstrProxyServer) { DL(SysFreeString)(_bstrProxyServer); _bstrProxyServer = NULL; } if (_bstrBypassList) { DL(SysFreeString)(_bstrBypassList); _bstrBypassList = NULL; } switch (ProxySetting) { case HTTPREQUEST_PROXYSETTING_PRECONFIG: _dwProxySetting = WINHTTP_ACCESS_TYPE_DEFAULT_PROXY; break; case HTTPREQUEST_PROXYSETTING_DIRECT: _dwProxySetting = WINHTTP_ACCESS_TYPE_NO_PROXY; break; case HTTPREQUEST_PROXYSETTING_PROXY: _dwProxySetting = WINHTTP_ACCESS_TYPE_NAMED_PROXY; hr = GetBSTRFromVariant(varProxyServer, &_bstrProxyServer); if (SUCCEEDED(hr)) { hr = GetBSTRFromVariant(varBypassList, &_bstrBypassList); } if (FAILED(hr)) { hr = E_INVALIDARG; } break; default: hr = E_INVALIDARG; break; } if (SUCCEEDED(hr)) { if (_hHTTP) { WINHTTP_PROXY_INFOW ProxyInfo; memset(&ProxyInfo, 0, sizeof(ProxyInfo)); ProxyInfo.dwAccessType = _dwProxySetting; ProxyInfo.lpszProxy = _bstrProxyServer; ProxyInfo.lpszProxyBypass = _bstrBypassList; if (!WinHttpSetOption(_hHTTP, WINHTTP_OPTION_PROXY, &ProxyInfo, sizeof(ProxyInfo))) { hr = HRESULT_FROM_WIN32(GetLastError()); } if (SUCCEEDED(hr) && !WinHttpSetOption(_hInet, WINHTTP_OPTION_PROXY, &ProxyInfo, sizeof(ProxyInfo))) { hr = HRESULT_FROM_WIN32(GetLastError()); } } } SetErrorInfo(hr); DEBUG_LEAVE_API(hr); return hr; } STDMETHODIMP CHttpRequest::SetCredentials( BSTR bstrUserName, BSTR bstrPassword, HTTPREQUEST_SETCREDENTIALS_FLAGS Flags) { HRESULT hr; DEBUG_ENTER_API((DBG_HTTP, Dword, "IWinHttpRequest::SetCredentials", "BSTR %Q, BSTR *, Flags: %x", _hHTTP? bstrUserName: L"", Flags )); // Must call Open method before SetCredentials. if (! _hHTTP) { goto ErrorCannotCallBeforeOpen; } if (!IsValidBstr(bstrUserName) || !IsValidBstr(bstrPassword)) return E_INVALIDARG; if (Flags == HTTPREQUEST_SETCREDENTIALS_FOR_SERVER) { // Set Username and Password. if (!WinHttpSetOption( _hHTTP, WINHTTP_OPTION_USERNAME, bstrUserName, lstrlenW(bstrUserName))) goto ErrorFail; if (!WinHttpSetOption( _hHTTP, WINHTTP_OPTION_PASSWORD, bstrPassword, lstrlenW(bstrPassword)+1)) // 596411 allow empty/blank password goto ErrorFail; } else if (Flags == HTTPREQUEST_SETCREDENTIALS_FOR_PROXY) { // Set Username and Password. if (!WinHttpSetOption( _hHTTP, WINHTTP_OPTION_PROXY_USERNAME, bstrUserName, lstrlenW(bstrUserName))) goto ErrorFail; if (!WinHttpSetOption( _hHTTP, WINHTTP_OPTION_PROXY_PASSWORD, bstrPassword, lstrlenW(bstrPassword)+1)) // 596411 allow empty/blank password goto ErrorFail; } else { DEBUG_LEAVE_API(E_INVALIDARG); return E_INVALIDARG; } hr = NOERROR; Cleanup: SetErrorInfo(hr); DEBUG_LEAVE_API(hr); return hr; ErrorCannotCallBeforeOpen: hr = HRESULT_FROM_WIN32(ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN); goto Cleanup; ErrorFail: hr = HRESULT_FROM_WIN32(::GetLastError()); goto Cleanup; } /* * CHttpRequest::Open * * Purpose: * Open a logical HTTP connection * * Parameters: * bstrMethod IN HTTP method (GET, PUT, ...) * bstrUrl IN Target URL * * Errors: * E_FAIL * E_INVALIDARG * E_OUTOFMEMORY * E_ACCESSDENIED * Errors from InternetOpenA and WinHttpCrackUrlA and InternetConnectA * and HttpOpenRequestA */ STDMETHODIMP CHttpRequest::Open( BSTR bstrMethod, BSTR bstrUrl, VARIANT varAsync) { HRESULT hr = NOERROR; BSTR bstrHostName = NULL; BSTR bstrUrlPath = NULL; DWORD dwHttpOpenFlags = 0; DWORD dw; URL_COMPONENTSW url; // Validate that we are called from our apartment's thread. if (GetCurrentThreadId() != _dwMainThreadId) return RPC_E_WRONG_THREAD; // Validate parameters if (!bstrMethod || !bstrUrl || !IsValidBstr(bstrMethod) || !IsValidBstr(bstrUrl) || !lstrlenW(bstrMethod) || // cannot have empty method !lstrlenW(bstrUrl) || // cannot have empty url !IsValidVariant(varAsync)) return E_INVALIDARG; BOOL newAsync = GetBoolFromVariant(varAsync, FALSE); DEBUG_ENTER_API((DBG_HTTP, Dword, "IWinHttpRequest::Open", "method: %Q, url: %Q, async: %d", bstrMethod, bstrUrl, newAsync )); // Check for reinitialization if (_eState != CHttpRequest::CREATED) { // // Abort any request in progress. // This will also recycle the object. // Abort(); } // //check if session has the async state we need // if (_hInet) { if ((_fAsync && !newAsync) || (!_fAsync && newAsync)) //XOR { //state is not the same, close session WinHttpCloseHandle(_hInet); _hInet = NULL; } } _fAsync = newAsync; // // Open an Internet Session if one does not already exist. // if (!_hInet) { _hInet = WinHttpOpen( GetUserAgentString(), _dwProxySetting, _bstrProxyServer, _bstrBypassList, #ifdef TRUE_ASYNC _fAsync ? WINHTTP_FLAG_ASYNC : 0 #else 0 #endif//TRUE_ASYNC ); if (!_hInet) goto ErrorFail; DWORD dwEnableFlags = _bEnableSslImpersonation ? 0 : WINHTTP_ENABLE_SSL_REVERT_IMPERSONATION; if (dwEnableFlags) { WinHttpSetOption(_hInet, WINHTTP_OPTION_ENABLE_FEATURE, (LPVOID)&dwEnableFlags, sizeof(dwEnableFlags)); } } // // If any timeouts were set previously, apply them. // if (_bSetTimeouts) { if (!WinHttpSetTimeouts(_hInet, (int)_ResolveTimeout, (int)_ConnectTimeout, (int)_SendTimeout, (int)_ReceiveTimeout)) goto ErrorFail; } // // Set the code page on the Session handle; the Connect // handle will also inherit this value. // if (!WinHttpSetOption(_hInet, WINHTTP_OPTION_CODEPAGE, &_dwCodePage, sizeof(_dwCodePage))) goto ErrorFail; if (!WinHttpSetOption(_hInet, WINHTTP_OPTION_SECURE_PROTOCOLS, (LPVOID)&_dwSecureProtocols, sizeof(_dwSecureProtocols))) goto ErrorFail; if (!WinHttpSetOption(_hInet, WINHTTP_OPTION_REDIRECT_POLICY, (LPVOID)&_dwRedirectPolicy, sizeof(DWORD))) goto ErrorFail; if (!WinHttpSetOption(_hInet, WINHTTP_OPTION_CONFIGURE_PASSPORT_AUTH, (LPVOID)&_dwPassportConfig, sizeof(DWORD))) goto ErrorFail; // Break the URL into the required components ZeroMemory(&url, sizeof(URL_COMPONENTSW)); url.dwStructSize = sizeof(URL_COMPONENTSW); url.dwHostNameLength = 1; url.dwUrlPathLength = 1; url.dwExtraInfoLength = 1; if (!WinHttpCrackUrl(bstrUrl, 0, 0, &url)) goto ErrorFail; // Check for non-http schemes if (url.nScheme != INTERNET_SCHEME_HTTP && url.nScheme != INTERNET_SCHEME_HTTPS) goto ErrorUnsupportedScheme; // IE6/Reno Bug #6236: if the client does not specify a resource path, // then add the "/". if (url.dwUrlPathLength == 0) { INET_ASSERT(url.dwExtraInfoLength == 0); url.lpszUrlPath = L"/"; url.dwUrlPathLength = 1; } bstrHostName = DL(SysAllocStringLen)(url.lpszHostName, url.dwHostNameLength); bstrUrlPath = DL(SysAllocStringLen)(url.lpszUrlPath, lstrlenW(url.lpszUrlPath)); if (!bstrHostName || !bstrUrlPath) goto ErrorOutOfMemory; INET_ASSERT(_hConnection == NULL); INET_ASSERT(_hHTTP == NULL); _hConnection = WinHttpConnect( _hInet, bstrHostName, url.nPort, 0); if (!_hConnection) goto ErrorFail; if (url.nScheme == INTERNET_SCHEME_HTTPS) { dwHttpOpenFlags |= WINHTTP_FLAG_SECURE; } // // Apply EscapePercentInURL option. // dwHttpOpenFlags |= _dwEscapeFlag; _hHTTP = WinHttpOpenRequest( _hConnection, bstrMethod, bstrUrlPath, _bHttp1_1Mode ? L"HTTP/1.1" : L"HTTP/1.0", NULL, NULL, dwHttpOpenFlags); if (!_hHTTP) goto ErrorFail; if ((StrCmpIW(bstrMethod, L"GET") == 0) || (StrCmpIW(bstrMethod, L"HEAD") == 0)) { _bMethodGET = TRUE; } if (_fCheckForRevocation) { DWORD dwOptions = WINHTTP_ENABLE_SSL_REVOCATION; WinHttpSetOption(_hHTTP, WINHTTP_OPTION_ENABLE_FEATURE, (LPVOID)&dwOptions, sizeof(dwOptions)); } // Set the SSL ignore flags through an undocumented front door if (_dwSslIgnoreFlags) { WinHttpSetOption(_hHTTP, WINHTTP_OPTION_SECURITY_FLAGS, (LPVOID)&_dwSslIgnoreFlags, sizeof(_dwSslIgnoreFlags)); } if (!WinHttpSetOption(_hHTTP, WINHTTP_OPTION_AUTOLOGON_POLICY, (void *) &_dwAutoLogonPolicy, sizeof(_dwAutoLogonPolicy))) goto ErrorFail; dw = (DWORD)_lMaxAutomaticRedirects; if (!WinHttpSetOption(_hHTTP, WINHTTP_OPTION_MAX_HTTP_AUTOMATIC_REDIRECTS, (void *) &dw, sizeof(dw))) goto ErrorFail; dw = (DWORD)_lMaxResponseHeaderSize; if (!WinHttpSetOption(_hHTTP, WINHTTP_OPTION_MAX_RESPONSE_HEADER_SIZE, (void *) &dw, sizeof(dw))) goto ErrorFail; dw = (DWORD)_lMaxResponseDrainSize; if (!WinHttpSetOption(_hHTTP, WINHTTP_OPTION_MAX_RESPONSE_DRAIN_SIZE, (void *) &dw, sizeof(dw))) goto ErrorFail; SetState(CHttpRequest::OPENED); hr = NOERROR; Cleanup: if (bstrHostName) DL(SysFreeString)(bstrHostName);; if (bstrUrlPath) DL(SysFreeString)(bstrUrlPath); SetErrorInfo(hr); DEBUG_LEAVE_API(hr); return hr; ErrorUnsupportedScheme: hr = HRESULT_FROM_WIN32(ERROR_WINHTTP_UNRECOGNIZED_SCHEME); goto Cleanup; ErrorOutOfMemory: hr = E_OUTOFMEMORY; goto Error; ErrorFail: if (_hHTTP) { WinHttpCloseHandle(_hHTTP); _hHTTP = NULL; } if (_hConnection) { WinHttpCloseHandle(_hConnection); _hConnection = NULL; } hr = HRESULT_FROM_WIN32(GetLastError()); goto Cleanup; Error: goto Cleanup; } /* * CHttpRequest::SetRequestHeader * * Purpose: * Set a request header * * Parameters: * bstrHeader IN HTTP request header * bstrValue IN Header value * * Errors: * E_FAIL * E_INVALIDARG * E_UNEXPECTED */ STDMETHODIMP CHttpRequest::SetRequestHeader(BSTR bstrHeader, BSTR bstrValue) { WCHAR * wszHeaderValue = NULL; DWORD cchHeaderValue; DWORD dwModifiers = HTTP_ADDREQ_FLAG_ADD; HRESULT hr = NOERROR; // Validate header parameter (null or zero-length value is allowed) if (!bstrHeader || !IsValidBstr(bstrHeader) || (lstrlenW(bstrHeader)==0) || !IsValidBstr(bstrValue) || !IsValidHeaderName(bstrHeader)) return E_INVALIDARG; DEBUG_ENTER_API((DBG_HTTP, Dword, "IWinHttpRequest::SetRequestHeader", "header: %Q, value: %Q", bstrHeader, bstrValue )); // Validate state if (_eState < CHttpRequest::OPENED) goto ErrorCannotCallBeforeOpen; else if (_eState >= CHttpRequest::SENDING) goto ErrorCannotCallAfterSend; // Ignore attempts to set the Content-Length header; the // content length is computed and sent automatically. if (StrCmpIW(bstrHeader, L"Content-Length") == 0) goto Cleanup; if (StrCmpIW(bstrHeader, L"Cookie") == 0) dwModifiers |= HTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON; cchHeaderValue = lstrlenW(bstrHeader) + lstrlenW(bstrValue) + 2 /* wcslen(L": ") */ + 2 /* wcslen(L"\r\n") */; wszHeaderValue = New WCHAR [cchHeaderValue + 1]; if (!wszHeaderValue) goto ErrorOutOfMemory; wcscpy(wszHeaderValue, bstrHeader); wcscat(wszHeaderValue, L": "); if (bstrValue) wcscat(wszHeaderValue, bstrValue); wcscat(wszHeaderValue, L"\r\n"); // For blank header values, erase the header by setting the // REPLACE flag. if (lstrlenW(bstrValue) == 0) { dwModifiers |= HTTP_ADDREQ_FLAG_REPLACE; } if (! WinHttpAddRequestHeaders(_hHTTP, wszHeaderValue, (DWORD)-1L, dwModifiers)) goto ErrorFail; hr = NOERROR; Cleanup: if (wszHeaderValue) delete [] wszHeaderValue; SetErrorInfo(hr); DEBUG_LEAVE_API(hr); return hr; ErrorOutOfMemory: hr = E_OUTOFMEMORY; goto Error; ErrorCannotCallBeforeOpen: hr = HRESULT_FROM_WIN32(ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN); goto Error; ErrorCannotCallAfterSend: hr = HRESULT_FROM_WIN32(ERROR_WINHTTP_CANNOT_CALL_AFTER_SEND); goto Error; ErrorFail: hr = HRESULT_FROM_WIN32(GetLastError()); goto Error; Error: goto Cleanup; } /* * CHttpRequest::SetRequiredRequestHeaders * * Purpose: * Set implicit request headers * * Parameters: * None * * Errors: * E_FAIL * E_UNEXPECTED * E_OUTOFMEMORY * Errors from WinHttpAddRequestHeaders and WinHttpSendRequest */ HRESULT CHttpRequest::SetRequiredRequestHeaders() { HRESULT hr = NOERROR; if (!(_bMethodGET && _cbRequestBody == 0)) { char szContentLengthHeader[sizeof("Content-Length") + sizeof(": ") + 15 + // content-length value sizeof("\r\n") + 1]; lstrcpy(szContentLengthHeader, "Content-Length: "); _ltoa(_cbRequestBody, szContentLengthHeader + 16, /* "Content-Length: " */ 10); lstrcat(szContentLengthHeader, "\r\n"); if (! HttpAddRequestHeadersA(_hHTTP, szContentLengthHeader, (DWORD)-1L, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE)) { hr = E_FAIL; } } // Add an Accept: */* header if no other Accept header // has been set. Ignore any return code, since it is // not fatal if this fails. HttpAddRequestHeadersA(_hHTTP, "Accept: */*", (DWORD)-1L, HTTP_ADDREQ_FLAG_ADD_IF_NEW); if (_bSetUtf8Charset) { CHAR szContentType[256]; BOOL fRetCode; DWORD cb = sizeof(szContentType) - sizeof("Content-Type: ") - sizeof("; Charset=UTF-8"); LPSTR pszNewContentType = NULL; lstrcpy(szContentType, "Content-Type: "); fRetCode = HttpQueryInfoA(_hHTTP, HTTP_QUERY_FLAG_REQUEST_HEADERS | HTTP_QUERY_CONTENT_TYPE, WINHTTP_HEADER_NAME_BY_INDEX, szContentType + sizeof("Content-Type: ") - 1, &cb, 0); if (fRetCode) { if (!StrStrIA(szContentType, "charset")) { lstrcat(szContentType, "; Charset=UTF-8"); pszNewContentType = szContentType; } } else if (GetLastError() == ERROR_WINHTTP_HEADER_NOT_FOUND) { pszNewContentType = "Content-Type: text/plain; Charset=UTF-8"; } if (pszNewContentType) { fRetCode = HttpAddRequestHeadersA(_hHTTP, pszNewContentType, (DWORD)-1L, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE); INET_ASSERT(fRetCode); } } return hr; } #if !defined(TRUE_ASYNC) DWORD WINAPI WinHttpRequestSendAsync(LPVOID lpParameter) { #ifdef WINHTTP_FOR_MSXML // // MSXML needs to initialize its thread local storage data. // It does not do this during DLL_THREAD_ATTACH, so our // worker thread must explicitly call into MSXML to initialize // its TLS for this thread. // InitializeMsxmlTLS(); #endif HRESULT hr; DWORD dwExitCode; CHttpRequest * pWinHttpRequest = reinterpret_cast<CHttpRequest *>(lpParameter); INET_ASSERT(pWinHttpRequest != NULL); dwExitCode = pWinHttpRequest->SendAsync(); pWinHttpRequest->Release(); // If this worker thread was impersonating, revert to the default // process identity. RevertToSelf(); return dwExitCode; } #endif//!TRUE_ASYNC /* * CHttpRequest::CreateAsyncWorkerThread * */ #if !defined(TRUE_ASYNC) HRESULT CHttpRequest::CreateAsyncWorkerThread() { DWORD dwWorkerThreadId; HANDLE hThreadToken = NULL; HRESULT hr; hr = _CP.CreateEventSinksMarshaller(); if (FAILED(hr)) return hr; hr = NOERROR; // // If the current thread is impersonating, then grab its access token // and revert the current thread (so it is nolonger impersonating). // After creating the worker thread, we will make the main thread // impersonate again. Apparently you should not call CreateThread // while impersonating. // if (OpenThreadToken(GetCurrentThread(), (TOKEN_IMPERSONATE | TOKEN_READ), FALSE, &hThreadToken)) { INET_ASSERT(hThreadToken != 0); RevertToSelf(); } // Create the worker thread suspended. _hWorkerThread = CreateThread(NULL, 0, WinHttpRequestSendAsync, (void *)static_cast<CHttpRequest *>(this), CREATE_SUSPENDED, &dwWorkerThreadId); // If CreateThread fails, grab the error code now. if (!_hWorkerThread) { hr = HRESULT_FROM_WIN32(GetLastError()); } // // If the main thread was impersonating, then: // (1) have the worker thread impersonate the same user, and // (2) have the main thread resume impersonating the // client too (since we called RevertToSelf above). // if (hThreadToken) { if (_hWorkerThread) { (void)SetThreadToken(&_hWorkerThread, hThreadToken); } (void)SetThreadToken(NULL, hThreadToken); CloseHandle(hThreadToken); } // If the worker thread was created, start it running. if (_hWorkerThread) { // The worker thread owns a ref count on the component. // Don't call AddRef() as it will attribute the ref count // to the main thread. _cRefs++; ResumeThread(_hWorkerThread); } else { _CP.ShutdownEventSinksMarshaller(); _CP.ReleaseEventSinksMarshaller(); } return hr; } #endif//!TRUE_ASYNC /* * CHttpRequest::Send * * Purpose: * Send the HTTP request * * Parameters: * varBody IN Request body * * Errors: * E_FAIL * E_UNEXPECTED * E_OUTOFMEMORY * Errors from WinHttpAddRequestHeaders and WinHttpSendRequest */ STDMETHODIMP CHttpRequest::Send(VARIANT varBody) { HRESULT hr = NOERROR; BOOL fRetCode = FALSE; BOOL fRetryWithClientAuth = TRUE; // Validate that we are called from our apartment's thread. if (GetCurrentThreadId() != _dwMainThreadId) return RPC_E_WRONG_THREAD; // Validate parameter if (!IsValidVariant(varBody)) return E_INVALIDARG; DEBUG_ENTER2_API((DBG_HTTP, Dword, "IWinHttpRequest::Send", "VARIANT varBody" )); TRACE_ENTER2_API((DBG_HTTP, Dword, "IWinHttpRequest::Send", _hHTTP, "VARIANT varBody" )); // Validate state if (_eState < CHttpRequest::OPENED) goto ErrorCannotCallBeforeOpen; if (_fAsync) { if ((_eState > CHttpRequest::OPENED) && (_eState < CHttpRequest::RESPONSE)) goto ErrorPending; } // Get the request body hr = SetRequestBody(varBody); if (FAILED(hr)) goto Error; hr = SetRequiredRequestHeaders(); if (FAILED(hr)) goto Error; try_again: SetState(CHttpRequest::SENDING); if (_fAsync) { #if !defined(TRUE_ASYNC) hr = CreateAsyncWorkerThread(); #else hr = StartAsyncSend(); #endif//!TRUE_ASYNC if (FAILED(hr)) goto Error; } else { //register callback if (WINHTTP_INVALID_STATUS_CALLBACK == WinHttpSetStatusCallback(_hHTTP, SyncCallback, WINHTTP_CALLBACK_STATUS_SECURE_FAILURE, NULL)) goto ErrorFail; // Send the HTTP request fRetCode = WinHttpSendRequest( _hHTTP, NULL, 0, // No header info here _szRequestBuffer, _cbRequestBody, _cbRequestBody, reinterpret_cast<DWORD_PTR>(this)); if (!fRetCode) { goto ErrorFail; } SetState(CHttpRequest::SENT); fRetCode = WinHttpReceiveResponse(_hHTTP, NULL); if (!fRetCode) { goto ErrorFail; } // Read the response data hr = ReadResponse(); if (FAILED(hr)) goto Error; } hr = NOERROR; Cleanup: SetErrorInfo(hr); DEBUG_LEAVE_API(hr); return hr; ErrorCannotCallBeforeOpen: hr = HRESULT_FROM_WIN32(ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN); goto Error; ErrorPending: hr = E_PENDING; goto Error; ErrorFail: hr = HRESULT_FROM_WIN32(GetLastError()); if (!_fAsync && hr == HRESULT_FROM_WIN32(ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED) && fRetryWithClientAuth) { fRetryWithClientAuth = FALSE; // Try to enumerate the first cert in the reverted user context, // select the cert (per object sesssion, not global), and send // the request again. if (SelectCertificate()) goto try_again; } else if (hr == HRESULT_FROM_WIN32(ERROR_WINHTTP_SECURE_FAILURE)) { INET_ASSERT(FAILED(_hrSecureFailure)); hr = _hrSecureFailure; } _CP.FireOnError(hr); goto Cleanup; Error: goto Cleanup; } /* * CHttpRequest::SendAsync * * Purpose: * Send the HTTP request * * Parameters: * varBody IN Request body * * Errors: * E_FAIL * E_UNEXPECTED * E_OUTOFMEMORY * Errors from WinHttpAddRequestHeaders and WinHttpSendRequest */ #if !defined(TRUE_ASYNC) DWORD CHttpRequest::SendAsync() { DWORD dwLastError = 0; DWORD fRetCode; HRESULT hr; BOOL fRetryWithClientAuth = TRUE; try_again: if (_bAborted || !_hHTTP) goto ErrorUnexpected; // Send the HTTP request fRetCode = WinHttpSendRequest( _hHTTP, NULL, 0, // No header info here _szRequestBuffer, _cbRequestBody, _cbRequestBody, 0); if (!fRetCode) goto ErrorFail; SetState(CHttpRequest::SENT); fRetCode = WinHttpReceiveResponse(_hHTTP, NULL); if (!fRetCode) goto ErrorFail; if (!_bAborted) { hr = ReadResponse(); if (FAILED(hr)) { if (hr == E_OUTOFMEMORY) goto ErrorOutOfMemory; goto ErrorFail; } } hr = NOERROR; Cleanup: _hrAsyncResult = hr; return dwLastError; ErrorUnexpected: dwLastError = ERROR_WINHTTP_INTERNAL_ERROR; hr = HRESULT_FROM_WIN32(dwLastError); goto Cleanup; ErrorFail: dwLastError = GetLastError(); if (dwLastError == ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED && fRetryWithClientAuth) { fRetryWithClientAuth = FALSE; // Try to enumerate the first cert in the reverted user context, // select the cert (per object sesssion, not global), and send // the request again. if (SelectCertificate()) { SetState(CHttpRequest::SENDING); goto try_again; } } hr = HRESULT_FROM_WIN32(dwLastError); goto Cleanup; ErrorOutOfMemory: dwLastError = ERROR_NOT_ENOUGH_MEMORY; hr = E_OUTOFMEMORY; goto Cleanup; } #endif//!TRUE_ASYNC STDMETHODIMP CHttpRequest::WaitForResponse(VARIANT varTimeout, VARIANT_BOOL * pboolSucceeded) { HRESULT hr = NOERROR; bool bSucceeded= true; DWORD dwTimeout; // Validate that we are called from our apartment's thread. if (GetCurrentThreadId() != _dwMainThreadId) return RPC_E_WRONG_THREAD; // Validate parameters; null pboolSucceeded pointer is Ok. if (!IsValidVariant(varTimeout) || (pboolSucceeded && IsBadWritePtr(pboolSucceeded, sizeof(VARIANT_BOOL)))) return E_INVALIDARG; // Get the timeout value. Disallow numbers // less than -1 (which means INFINITE). if (GetLongFromVariant(varTimeout, INFINITE) < -1L) return E_INVALIDARG; dwTimeout = GetDwordFromVariant(varTimeout, INFINITE); DEBUG_ENTER_API((DBG_HTTP, Dword, "IWinHttpRequest::WaitForResponse", "Timeout: %d, VARIANT_BOOL* pboolSucceeded: %#x", dwTimeout, pboolSucceeded )); // Validate state. if (_eState < CHttpRequest::SENDING) goto ErrorCannotCallBeforeSend; // // WaitForResponse is a no-op if we're not in async mode. // if (_fAsync && #ifdef TRUE_ASYNC _hCompleteEvent #else _hWorkerThread #endif ) { // // Has the worker thread has already finished or event signaled? // if (WaitForSingleObject( #ifdef TRUE_ASYNC _hCompleteEvent #else _hWorkerThread #endif , 0) == WAIT_TIMEOUT) { // // Convert Timeout from seconds to milliseconds. Any timeout // value over 4 million seconds (~46 days) is "rounded up" // to INFINITE. :) // if (dwTimeout > 4000000) // avoid overflow { dwTimeout = INFINITE; } else { // convert to milliseconds dwTimeout *= 1000; } DWORD dwStartTime; DWORD dwWaitResult; bool bWaitAgain; do { dwStartTime = GetTickCount(); dwWaitResult = MsgWaitForMultipleObjects(1, #ifdef TRUE_ASYNC &_hCompleteEvent #else &_hWorkerThread #endif , FALSE, dwTimeout, QS_ALLINPUT); bWaitAgain = false; switch (dwWaitResult) { case WAIT_OBJECT_0: // Thread exited. MessageLoop(); hr = _hrAsyncResult; bSucceeded = SUCCEEDED(hr); break; case WAIT_OBJECT_0 + 1: // Message waiting in the message queue. // Run message pump to clear queue. MessageLoop(); //check if object was not aborted if (_eState != CHttpRequest::CREATED) bWaitAgain = true; else hr = _hrAsyncResult; break; case WAIT_TIMEOUT: // Timeout. bSucceeded = false; break; case (-1): default: // Error. goto ErrorFail; break; } // If we're going to continue waiting for the worker // thread, decrease timeout appropriately. if (bWaitAgain) { dwTimeout = UpdateTimeout(dwTimeout, dwStartTime); } } while (bWaitAgain); } else { // If the worker thread is already done, then pump messages // to clear any events that it may have posted. MessageLoop(); hr = _hrAsyncResult; bSucceeded = SUCCEEDED(hr); } } //check if object was aborted if (_eState == CHttpRequest::CREATED) bSucceeded = false; Cleanup: if (pboolSucceeded) { *pboolSucceeded = (bSucceeded ? VARIANT_TRUE : VARIANT_FALSE); } if (hr == HRESULT_FROM_WIN32(ERROR_WINHTTP_SECURE_FAILURE)) { INET_ASSERT(FAILED(_hrSecureFailure)); hr = _hrSecureFailure; } SetErrorInfo(hr); DEBUG_PRINT_API(ASYNC, INFO, (bSucceeded ? "Succeeded set to true\n" : "Succeeded set to false\n")) DEBUG_LEAVE_API(hr); return hr; ErrorFail: hr = HRESULT_FROM_WIN32(GetLastError()); goto Error; ErrorCannotCallBeforeSend: hr = HRESULT_FROM_WIN32(ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND); goto Error; Error: bSucceeded = false; goto Cleanup; } STDMETHODIMP CHttpRequest::Abort() { DEBUG_ENTER_API((DBG_HTTP, Dword, "IWinHttpRequest::Abort", NULL )); // Validate that we are called from our apartment's thread. if (GetCurrentThreadId() != _dwMainThreadId) return RPC_E_WRONG_THREAD; // // Abort if not already aborted and not in the CREATED state, // (meaning at least the Open method has been called). // if ((_eState > CHttpRequest::CREATED) && !_bAborted) { DWORD error; _bAborted = true; // Tell our connection point manager to abort any // events "in flight"--i.e., abort any events that // may have already been posted by the worker thread. _CP.FreezeEvents(); if (_hHTTP) { // // Add a ref count on the HTTP Request handle. // INET_ASSERT(_hAbortedRequestObject == NULL); error = MapHandleToAddress(_hHTTP, (LPVOID *)&_hAbortedRequestObject, FALSE); INET_ASSERT(error == 0); WinHttpCloseHandle(_hHTTP); _hHTTP = NULL; } if (_hConnection) { // // Add a ref count on the Connection handle. // INET_ASSERT(_hAbortedConnectObject == NULL); error = MapHandleToAddress(_hConnection, (LPVOID *)&_hAbortedConnectObject, FALSE); INET_ASSERT(error == 0); WinHttpCloseHandle(_hConnection); _hConnection = NULL; } // Recycle the object. Recycle(); } DEBUG_LEAVE_API(NOERROR); return NOERROR; } STDMETHODIMP CHttpRequest::SetTimeouts(long ResolveTimeout, long ConnectTimeout, long SendTimeout, long ReceiveTimeout) { if ((ResolveTimeout < -1L) || (ConnectTimeout < -1L) || (SendTimeout < -1L) || (ReceiveTimeout < -1L)) { return E_INVALIDARG; } HRESULT hr = NOERROR; _ResolveTimeout = (DWORD) ResolveTimeout; _ConnectTimeout = (DWORD) ConnectTimeout; _SendTimeout = (DWORD) SendTimeout; _ReceiveTimeout = (DWORD) ReceiveTimeout; _bSetTimeouts = true; if (_hHTTP) { DWORD fRetCode; fRetCode = WinHttpSetTimeouts(_hHTTP, (int)_ResolveTimeout, (int)_ConnectTimeout, (int)_SendTimeout, (int)_ReceiveTimeout); if (!fRetCode) hr = E_INVALIDARG; } return hr; } STDMETHODIMP CHttpRequest::SetClientCertificate(BSTR ClientCertificate) { BOOL fCertLocalMachine = FALSE; BSTR bstrCertStore = NULL; BSTR bstrCertSubject = NULL; HRESULT hr; if (!IsValidBstr(ClientCertificate)) goto ErrorInvalidArg; hr = ParseSelectedCert(ClientCertificate, &fCertLocalMachine, &bstrCertStore, &bstrCertSubject ); // Only fill in new selection if parsed successfully. if (hr == S_OK) { _fCertLocalMachine = fCertLocalMachine; if (_bstrCertStore) DL(SysFreeString)(_bstrCertStore); _bstrCertStore = bstrCertStore; if (_bstrCertSubject) DL(SysFreeString)(_bstrCertSubject); _bstrCertSubject = bstrCertSubject; } if (_hHTTP) { // We will try again later if this fails now, so // don't worry about detecting an error. SelectCertificate(); } Exit: SetErrorInfo(hr); return hr; ErrorInvalidArg: hr = E_INVALIDARG; goto Exit; } STDMETHODIMP CHttpRequest::SetAutoLogonPolicy(WinHttpRequestAutoLogonPolicy AutoLogonPolicy) { HRESULT hr; switch (AutoLogonPolicy) { case AutoLogonPolicy_Always: _dwAutoLogonPolicy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_LOW; break; case AutoLogonPolicy_OnlyIfBypassProxy: _dwAutoLogonPolicy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_MEDIUM; break; case AutoLogonPolicy_Never: _dwAutoLogonPolicy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_HIGH; break; default: goto ErrorInvalidArg; } if (_hHTTP) { if (!WinHttpSetOption(_hHTTP, WINHTTP_OPTION_AUTOLOGON_POLICY, (void *) &_dwAutoLogonPolicy, sizeof(_dwAutoLogonPolicy))) goto ErrorFail; } hr = NOERROR; Exit: SetErrorInfo(hr); return hr; ErrorInvalidArg: hr = E_INVALIDARG; goto Exit; ErrorFail: hr = HRESULT_FROM_WIN32(GetLastError()); goto Exit; } /* * CHttpRequest::SetRequestBody * * Purpose: * Set the request body * * Parameters: * varBody IN Request body * * Errors: * E_FAIL * E_OUTOFMEMORY * E_UNEXPECTED */ HRESULT CHttpRequest::SetRequestBody(VARIANT varBody) { HRESULT hr = NOERROR; VARIANT varTemp; SAFEARRAY * psa = NULL; VARIANT * pvarBody = NULL; // varBody is validated by CHttpRequest::Send(). DL(VariantInit)(&varTemp); // Free a previously set body and its response if (_szRequestBuffer) { delete [] _szRequestBuffer; _szRequestBuffer = NULL; _cbRequestBody = 0; } _bSetUtf8Charset = false; SafeRelease(_pResponseStream); _cbResponseBody = 0; if (V_ISBYREF(&varBody)) { pvarBody = varBody.pvarVal; } else { pvarBody = &varBody; } // Check for an empty body if (V_VT(pvarBody) == VT_EMPTY || V_VT(pvarBody) == VT_NULL || V_VT(pvarBody) == VT_ERROR) goto Cleanup; // // Extract the body: BSTR or array of UI1 // // We need to explicitly look for the byte array since it will be converted // to a BSTR by DL(VariantChangeType). if (V_ISARRAY(pvarBody) && (V_VT(pvarBody) & VT_UI1)) { BYTE * pb = NULL; long lUBound = 0; long lLBound = 0; psa = V_ARRAY(pvarBody); // We only handle 1 dimensional arrays if (DL(SafeArrayGetDim)(psa) != 1) goto ErrorFail; // Get access to the blob hr = DL(SafeArrayAccessData)(psa, (void **)&pb); if (FAILED(hr)) goto Error; // Compute the data size from the upper and lower array bounds hr = DL(SafeArrayGetLBound)(psa, 1, &lLBound); if (FAILED(hr)) goto Error; hr = DL(SafeArrayGetUBound)(psa, 1, &lUBound); if (FAILED(hr)) goto Error; _cbRequestBody = lUBound - lLBound + 1; if (_cbRequestBody > 0) { // Copy the data into the request buffer _szRequestBuffer = New char [_cbRequestBody]; if (!_szRequestBuffer) { _cbRequestBody = 0; goto ErrorOutOfMemory; } ::memcpy(_szRequestBuffer, pb, _cbRequestBody); } DL(SafeArrayUnaccessData)(psa); psa = NULL; } else { BSTR bstrBody = NULL; bool bFreeString = false; // // Try a BSTR; avoiding to call GetBSTRFromVariant (which makes // a copy) if possible. // if (V_VT(pvarBody) == VT_BSTR) { bstrBody = V_BSTR(pvarBody); // direct BSTR string, do not free bFreeString = false; } else { hr = GetBSTRFromVariant(*pvarBody, &bstrBody); if (SUCCEEDED(hr)) { bFreeString = true; } else if (hr == E_INVALIDARG) { // GetBSTRFromVariant will return E_INVALIDARG if the // call to VariantChangeType AVs. The VARIANT may be // valid, but may simply not contain a BSTR, so if // some other error is returned (most likely // DISP_E_MISMATCH), then continue and see if the // VARIANT contains an IStream object. goto Error; } } if (bstrBody) { hr = BSTRToUTF8(&_szRequestBuffer, &_cbRequestBody, bstrBody, &_bSetUtf8Charset); if (bFreeString) DL(SysFreeString)(bstrBody); if (FAILED(hr)) goto Error; } else { // Try a Stream if (V_VT(pvarBody) == VT_UNKNOWN || V_VT(pvarBody) == VT_DISPATCH) { IStream * pStm = NULL; __try { hr = pvarBody->punkVal->QueryInterface( IID_IStream, (void **)&pStm); } __except (EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } if (FAILED(hr)) goto Error; hr = ReadFromStream( &_szRequestBuffer, &_cbRequestBody, pStm); pStm->Release(); if (FAILED(hr)) goto Error; } } } hr = NOERROR; Cleanup: DL(VariantClear)(&varTemp); if (psa) DL(SafeArrayUnaccessData)(psa); return hr; ErrorOutOfMemory: hr = E_OUTOFMEMORY; goto Error; ErrorFail: hr = HRESULT_FROM_WIN32(GetLastError()); goto Error; Error: goto Cleanup; } /* * CHttpRequest::GetResponseHeader * * Purpose: * Get a response header * * Parameters: * bstrHeader IN HTTP request header * pbstrValue OUT Header value * * Errors: * E_FAIL * E_INVALIDARG * E_OUTOFMEMORY * E_UNEXPECTED * Errors from WinHttpQueryHeaders */ STDMETHODIMP CHttpRequest::GetResponseHeader(BSTR bstrHeader, BSTR * pbstrValue) { return _GetResponseHeader(bstrHeader, pbstrValue); } #ifdef TRUE_ASYNC HRESULT CHttpRequest::_GetResponseHeader(OLECHAR * wszHeader, BSTR * pbstrValue) { HRESULT hr; // Validate state if (_eState < CHttpRequest::SENDING) hr = HRESULT_FROM_WIN32(ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND); else hr = _GetResponseHeader2(wszHeader, pbstrValue, _hHTTP); SetErrorInfo(hr); return hr; } HRESULT CHttpRequest::_GetResponseHeader2(OLECHAR * wszHeader, BSTR * pbstrValue, HINTERNET hInternet) { HRESULT hr = NOERROR; WCHAR * wszHeaderValue = NULL; DWORD cb; BOOL fRetCode; // Validate parameters if (IsBadReadPtr(wszHeader, 2) || IsBadWritePtr(pbstrValue, sizeof(BSTR)) || !lstrlenW(wszHeader)) return E_INVALIDARG; *pbstrValue = NULL; cb = 64; // arbitrary size in which many header values will fit wszHeaderValue = New WCHAR[cb]; if (!wszHeaderValue) goto ErrorOutOfMemory; RetryQuery: // Determine length of requested header fRetCode = WinHttpQueryHeaders( hInternet, HTTP_QUERY_CUSTOM, wszHeader, wszHeaderValue, &cb, 0); // Check for ERROR_INSUFFICIENT_BUFFER - reallocate the buffer and retry if (!fRetCode) { switch (GetLastError()) { case ERROR_INSUFFICIENT_BUFFER: { delete [] wszHeaderValue; wszHeaderValue = New WCHAR[cb]; // should this be cb/2? if (!wszHeaderValue) goto ErrorOutOfMemory; goto RetryQuery; } case ERROR_HTTP_HEADER_NOT_FOUND: goto ErrorFail; default: goto ErrorFail; } } *pbstrValue = DL(SysAllocString)(wszHeaderValue); if (!*pbstrValue) goto ErrorOutOfMemory; hr = NOERROR; Cleanup: if (wszHeaderValue) delete [] wszHeaderValue; return hr; ErrorOutOfMemory: hr = E_OUTOFMEMORY; goto Error; ErrorFail: hr = HRESULT_FROM_WIN32(GetLastError()); goto Error; Error: goto Cleanup; } #else//TRUE_ASYNC HRESULT CHttpRequest::_GetResponseHeader(OLECHAR * wszHeader, BSTR * pbstrValue) { HRESULT hr = NOERROR; WCHAR * wszHeaderValue = NULL; DWORD cb; BOOL fRetCode; // Validate parameters if (IsBadReadPtr(wszHeader, 2) || IsBadWritePtr(pbstrValue, sizeof(BSTR)) || !lstrlenW(wszHeader)) return E_INVALIDARG; // Validate state if (_eState < CHttpRequest::SENDING) goto ErrorCannotCallBeforeSend; *pbstrValue = NULL; cb = 64; // arbitrary size in which many header values will fit wszHeaderValue = New WCHAR[cb]; if (!wszHeaderValue) goto ErrorOutOfMemory; RetryQuery: // Determine length of requested header fRetCode = WinHttpQueryHeaders( _hHTTP, HTTP_QUERY_CUSTOM, wszHeader, wszHeaderValue, &cb, 0); // Check for ERROR_INSUFFICIENT_BUFFER - reallocate the buffer and retry if (!fRetCode) { switch (GetLastError()) { case ERROR_INSUFFICIENT_BUFFER: { delete [] wszHeaderValue; wszHeaderValue = New WCHAR[cb]; // should this be cb/2? if (!wszHeaderValue) goto ErrorOutOfMemory; goto RetryQuery; } case ERROR_HTTP_HEADER_NOT_FOUND: goto ErrorFail; default: goto ErrorFail; } } *pbstrValue = DL(SysAllocString)(wszHeaderValue); if (!*pbstrValue) goto ErrorOutOfMemory; hr = NOERROR; Cleanup: if (wszHeaderValue) delete [] wszHeaderValue; SetErrorInfo(hr); return hr; ErrorOutOfMemory: hr = E_OUTOFMEMORY; goto Error; ErrorFail: hr = HRESULT_FROM_WIN32(GetLastError()); goto Error; ErrorCannotCallBeforeSend: hr = HRESULT_FROM_WIN32(ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND); goto Error; Error: goto Cleanup; } #endif//TRUE_ASYNC /* * CHttpRequest::GetAllResponseHeaders * * Purpose: * Return the response headers * * Parameters: * pbstrHeaders IN/OUT CRLF delimited headers * * Errors: * E_FAIL * E_INVALIDARG * E_OUTOFMEMORY * E_UNEXPECTED */ STDMETHODIMP CHttpRequest::GetAllResponseHeaders(BSTR * pbstrHeaders) { HRESULT hr = NOERROR; BOOL fRetCode; WCHAR * wszAllHeaders = NULL; WCHAR * wszFirstHeader = NULL; DWORD cb = 0; // Validate parameter if (IsBadWritePtr(pbstrHeaders, sizeof(BSTR))) return E_INVALIDARG; // Validate state if (_eState < CHttpRequest::SENDING) goto ErrorCannotCallBeforeSend; *pbstrHeaders = NULL; RetryQuery: // Determine the length of all headers and then get all the headers fRetCode = WinHttpQueryHeaders( _hHTTP, HTTP_QUERY_RAW_HEADERS_CRLF, WINHTTP_HEADER_NAME_BY_INDEX, wszAllHeaders, &cb, 0); if (!fRetCode) { // Allocate a buffer large enough to hold all headers if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) { if (wszAllHeaders != NULL) { delete [] wszAllHeaders; wszAllHeaders = NULL; } wszAllHeaders = New WCHAR[cb]; if (!wszAllHeaders) goto ErrorOutOfMemory; goto RetryQuery; } else { goto ErrorFail; } } // Bypass status line - jump past first CRLF (0x13, 0x10) wszFirstHeader = wcschr(wszAllHeaders, '\n'); if (*wszFirstHeader == '\n') { *pbstrHeaders = DL(SysAllocString)(wszFirstHeader + 1); if (!*pbstrHeaders) goto ErrorOutOfMemory; } hr = NOERROR; Cleanup: if (wszAllHeaders) delete [] wszAllHeaders; SetErrorInfo(hr); return hr; ErrorOutOfMemory: hr = E_OUTOFMEMORY; goto Error; ErrorFail: hr = HRESULT_FROM_WIN32(GetLastError()); goto Error; ErrorCannotCallBeforeSend: hr = HRESULT_FROM_WIN32(ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND); goto Error; Error: if (pbstrHeaders) { DL(SysFreeString)(*pbstrHeaders); *pbstrHeaders = NULL; } goto Cleanup; } /* * CHttpRequest::get_status * * Purpose: * Get the request status code * * Parameters: * plStatus OUT HTTP request status code * * Errors: * E_FAIL * E_INVALIDARG * E_UNEXPECTED */ STDMETHODIMP CHttpRequest::get_Status(long * plStatus) { HRESULT hr = NOERROR; DWORD cb = sizeof(DWORD); BOOL fRetCode; DWORD dwStatus; // Validate parameter if (IsBadWritePtr(plStatus, sizeof(long))) return E_INVALIDARG; // Validate state if (_eState < CHttpRequest::SENDING) goto ErrorCannotCallBeforeSend; else if (_eState < CHttpRequest::RECEIVING) goto ErrorRequestInProgress; fRetCode = HttpQueryInfoA( _hHTTP, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX, &dwStatus, &cb, 0); if (!fRetCode) goto ErrorFail; *plStatus = dwStatus; hr = NOERROR; Cleanup: SetErrorInfo(hr); return hr; ErrorCannotCallBeforeSend: hr = HRESULT_FROM_WIN32(ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND); goto Error; ErrorRequestInProgress: hr = E_PENDING; goto Error; ErrorFail: hr = HRESULT_FROM_WIN32(GetLastError()); goto Error; Error: goto Cleanup; } /* * CHttpRequest::get_StatusText * * Purpose: * Get the request status text * * Parameters: * pbstrStatus OUT HTTP request status text * * Errors: * E_FAIL * E_INVALIDARG * E_UNEXPECTED */ STDMETHODIMP CHttpRequest::get_StatusText(BSTR * pbstrStatus) { HRESULT hr = NOERROR; WCHAR wszStatusText[32]; WCHAR * pwszStatusText = wszStatusText; BOOL fFreeStatusString = FALSE; DWORD cb; BOOL fRetCode; // Validate parameter if (IsBadWritePtr(pbstrStatus, sizeof(BSTR))) return E_INVALIDARG; // Validate state // Validate state if (_eState < CHttpRequest::SENDING) goto ErrorCannotCallBeforeSend; else if (_eState < CHttpRequest::RECEIVING) goto ErrorRequestInProgress; *pbstrStatus = NULL; cb = sizeof(wszStatusText) / sizeof(WCHAR); RetryQuery: fRetCode = WinHttpQueryHeaders( _hHTTP, HTTP_QUERY_STATUS_TEXT, WINHTTP_HEADER_NAME_BY_INDEX, pwszStatusText, &cb, 0); if (!fRetCode) { // Check for ERROR_INSUFFICIENT_BUFFER error if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) { // Reallocate the status text buffer if (fFreeStatusString) delete [] pwszStatusText; pwszStatusText = New WCHAR[cb]; if (!pwszStatusText) goto ErrorOutOfMemory; fFreeStatusString = TRUE; goto RetryQuery; } else { goto ErrorFail; } } // Convert the status text to a BSTR *pbstrStatus = DL(SysAllocString)(pwszStatusText); if (!*pbstrStatus) goto ErrorOutOfMemory; hr = NOERROR; Cleanup: if (fFreeStatusString) delete [] pwszStatusText; SetErrorInfo(hr); return hr; ErrorOutOfMemory: hr = E_OUTOFMEMORY; goto Error; ErrorCannotCallBeforeSend: hr = HRESULT_FROM_WIN32(ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND); goto Error; ErrorRequestInProgress: hr = E_PENDING; goto Error; ErrorFail: hr = HRESULT_FROM_WIN32(GetLastError()); goto Cleanup; Error: goto Cleanup; } /* * CHttpRequest::get_ResponseBody * * Purpose: * Retrieve the response body as a SAFEARRAY of UI1 * * Parameters: * pvarBody OUT Response blob * * Errors: * E_INVALIDARG * E_UNEXPECTED * E_PENDING */ STDMETHODIMP CHttpRequest::get_ResponseBody(VARIANT * pvarBody) { HRESULT hr = NOERROR; // Validate parameter if (IsBadWritePtr(pvarBody, sizeof(VARIANT))) return E_INVALIDARG; // Validate state if (_eState < CHttpRequest::SENDING) goto ErrorCannotCallBeforeSend; else if (_eState < CHttpRequest::RESPONSE) goto ErrorPending; DL(VariantInit)(pvarBody); if (_cbResponseBody != 0) { HGLOBAL hGlobal; hr = DL(GetHGlobalFromStream)(_pResponseStream, &hGlobal); if (FAILED(hr)) goto Error; const BYTE * pResponseData = (const BYTE *) GlobalLock(hGlobal); if (!pResponseData) goto ErrorFail; hr = CreateVector(pvarBody, pResponseData, _cbResponseBody); GlobalUnlock(hGlobal); if (FAILED(hr)) goto Error; } else { V_VT(pvarBody) = VT_EMPTY; } hr = NOERROR; Cleanup: SetErrorInfo(hr); return hr; ErrorCannotCallBeforeSend: hr = HRESULT_FROM_WIN32(ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND); goto Error; ErrorPending: hr = E_PENDING; goto Error; ErrorFail: hr = HRESULT_FROM_WIN32(::GetLastError()); goto Error; Error: if (pvarBody) DL(VariantClear)(pvarBody); goto Cleanup; } /* * CHttpRequest::get_ResponseText * * Purpose: * Retrieve the response body as a BSTR * * Parameters: * pbstrBody OUT response as a BSTR * * Errors: * E_INVALIDARG * E_OUTOFMEMORY * E_UNEXPECTED * E_PENDING */ STDMETHODIMP CHttpRequest::get_ResponseText(BSTR * pbstrBody) { HRESULT hr; MIMECSETINFO mimeSetInfo; IMultiLanguage * pMultiLanguage = NULL; IMultiLanguage2 * pMultiLanguage2 = NULL; CHAR szContentType[1024]; DWORD cb; BSTR bstrCharset = NULL; HGLOBAL hGlobal = NULL; char * pResponseData = NULL; // Validate parameter if (IsBadWritePtr(pbstrBody, sizeof(BSTR))) return E_INVALIDARG; // Validate state if (_eState < CHttpRequest::SENDING) goto ErrorCannotCallBeforeSend; else if (_eState < CHttpRequest::RESPONSE) goto ErrorPending; if (!_hHTTP) { hr = E_UNEXPECTED; goto Error; } if (_cbResponseBody != 0) { hr = DL(GetHGlobalFromStream)(_pResponseStream, &hGlobal); if (FAILED(hr)) goto Error; pResponseData = (char *) GlobalLock(hGlobal); if (!pResponseData) goto ErrorFail; } else { *pbstrBody = NULL; } // Check if charset is present. cb = sizeof(szContentType); if (HttpQueryInfoA(_hHTTP, WINHTTP_QUERY_CONTENT_TYPE, NULL, szContentType, &cb, NULL)) { LPSTR lpszCharset; LPSTR lpszCharsetEnd; if ((lpszCharset = StrStrIA(szContentType, "charset=")) != NULL) { LPSTR lpszBeginQuote = NULL; LPSTR lpszEndQuote = NULL; if ((lpszBeginQuote = StrChrA(lpszCharset, '\"')) != NULL) { lpszEndQuote = StrChrA(lpszBeginQuote+1, '\"'); } if (lpszEndQuote) { lpszCharset = lpszBeginQuote + 1; lpszCharsetEnd = lpszEndQuote; } else { lpszCharset += sizeof("charset=")-1; lpszCharsetEnd = StrChrA(lpszCharset, ';'); } // only **STRLEN** to be passed to AsciiToBSTR AsciiToBSTR(&bstrCharset, lpszCharset, (int)(lpszCharsetEnd ? (lpszCharsetEnd-lpszCharset) : lstrlen(lpszCharset))); } } if (!bstrCharset) { // use ISO-8859-1 mimeSetInfo.uiInternetEncoding = 28591; mimeSetInfo.uiCodePage = 1252; // note unitialized wszCharset - not cached, not used. } else { // obtain codepage corresponding to charset if (!g_pMimeInfoCache) { //create the mimeinfo cache. DWORD dwStatus = 0; if (!GlobalDataInitCritSec.Lock()) { goto ErrorOutOfMemory; } if (!g_pMimeInfoCache) { g_pMimeInfoCache = new CMimeInfoCache(&dwStatus); if(!g_pMimeInfoCache || dwStatus) { if (g_pMimeInfoCache) delete g_pMimeInfoCache; g_pMimeInfoCache = NULL; GlobalDataInitCritSec.Unlock(); goto ErrorOutOfMemory; } } GlobalDataInitCritSec.Unlock(); } //check the cache for info if (S_OK != g_pMimeInfoCache->GetCharsetInfo(bstrCharset, &mimeSetInfo)) { // if info not in cache, get from mlang hr = DL(CoCreateInstance)(CLSID_CMultiLanguage, NULL, CLSCTX_INPROC_SERVER, IID_IMultiLanguage, (void**)&pMultiLanguage); if (FAILED(hr)) { goto ConvertError; } INET_ASSERT (pMultiLanguage); pMultiLanguage->QueryInterface(IID_IMultiLanguage2, (void **)&pMultiLanguage2); pMultiLanguage->Release(); if (!pMultiLanguage2) { goto ConvertError; } if (FAILED((pMultiLanguage2)->GetCharsetInfo(bstrCharset, &mimeSetInfo))) { //Check for known-exceptions if (!StrCmpNIW(bstrCharset, L"ISO8859_1", MAX_MIMECSET_NAME)) { mimeSetInfo.uiInternetEncoding = 28591; mimeSetInfo.uiCodePage = 1252; StrCpyNW(mimeSetInfo.wszCharset, L"ISO8859_1", lstrlenW(L"ISO8859_1")+1); } else { goto ConvertError; } } // add obtained info to cache. g_pMimeInfoCache->AddCharsetInfo(&mimeSetInfo); } } // here only if we have mimeSetInfo filled in correctly. hr = MultiByteToWideCharInternal(pbstrBody, pResponseData, (int)_cbResponseBody, mimeSetInfo.uiInternetEncoding, &pMultiLanguage2); if (hr != S_OK) { MultiByteToWideCharInternal(pbstrBody, pResponseData, (int)_cbResponseBody, mimeSetInfo.uiCodePage, &pMultiLanguage2); } Cleanup: if (hGlobal) GlobalUnlock(hGlobal); if (pMultiLanguage2) { pMultiLanguage2->Release(); } SetErrorInfo(hr); return hr; ErrorCannotCallBeforeSend: hr = HRESULT_FROM_WIN32(ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND); goto Error; ErrorPending: hr = E_PENDING; goto Error; ErrorFail: hr = HRESULT_FROM_WIN32(::GetLastError()); goto Error; ErrorOutOfMemory: hr = E_OUTOFMEMORY; goto Error; Error: goto Cleanup; ConvertError: hr = HRESULT_FROM_WIN32(ERROR_NO_UNICODE_TRANSLATION); goto Cleanup; } STDMETHODIMP CHttpRequest::get_ResponseStream(VARIANT * pvarBody) { HRESULT hr = NOERROR; IStream * pStm = NULL; // Validate parameter if (IsBadWritePtr(pvarBody, sizeof(VARIANT))) return E_INVALIDARG; // Validate state if (_eState < CHttpRequest::SENDING) goto ErrorCannotCallBeforeSend; else if (_eState < CHttpRequest::RESPONSE) goto ErrorPending; DL(VariantInit)(pvarBody); hr = CreateStreamOnResponse(&pStm); if (FAILED(hr)) goto Error; V_VT(pvarBody) = VT_UNKNOWN; pvarBody->punkVal = pStm; hr = NOERROR; Cleanup: SetErrorInfo(hr); return hr; ErrorCannotCallBeforeSend: hr = HRESULT_FROM_WIN32(ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND); goto Error; ErrorPending: hr = E_PENDING; goto Error; Error: if (pvarBody) DL(VariantClear)(pvarBody); goto Cleanup; } void CHttpRequest::SetState(State state) { if (_fAsync) { InterlockedExchange((long *)&_eState, state); } else { _eState = state; } } /* * CHttpRequest::CreateStreamOnResponse * * Purpose: * Create a Stream containing the Response data * * Parameters: * ppStm IN/OUT Stream * * Errors: * E_INVALIDARG * E_OUTOFMEMORY */ HRESULT CHttpRequest::CreateStreamOnResponse(IStream ** ppStm) { HRESULT hr = NOERROR; LARGE_INTEGER liReset = { 0, 0 }; if (!ppStm) goto ErrorInvalidArg; *ppStm = NULL; if (_cbResponseBody) { INET_ASSERT(_pResponseStream); hr = _pResponseStream->Clone(ppStm); if (FAILED(hr)) goto Error; } else { // // No response body, return an empty stream object // ULARGE_INTEGER size = { 0, 0 }; hr = DL(CreateStreamOnHGlobal)(NULL, TRUE, ppStm); if (FAILED(hr)) goto Error; (*ppStm)->SetSize(size); } hr = (*ppStm)->Seek(liReset, STREAM_SEEK_SET, NULL); if (FAILED(hr)) goto Error; hr = NOERROR; Cleanup: return hr; ErrorInvalidArg: hr = E_INVALIDARG; goto Error; Error: if (ppStm) SafeRelease(*ppStm); goto Cleanup; } STDMETHODIMP CHttpRequest::get_Option(WinHttpRequestOption Option, VARIANT * Value) { HRESULT hr; if (IsBadWritePtr(Value, sizeof(VARIANT))) return E_INVALIDARG; switch (Option) { case WinHttpRequestOption_UserAgentString: { V_BSTR(Value) = DL(SysAllocString)(GetUserAgentString()); if (V_BSTR(Value) == NULL) goto ErrorOutOfMemory; V_VT(Value) = VT_BSTR; break; } case WinHttpRequestOption_URL: { WCHAR * pwszUrl = NULL; DWORD dwBufferSize = 0; if (_eState < CHttpRequest::OPENED) goto ErrorCannotCallBeforeOpen; if (!WinHttpQueryOption(_hHTTP, WINHTTP_OPTION_URL, NULL, &dwBufferSize) && (GetLastError() == ERROR_INSUFFICIENT_BUFFER)) { pwszUrl = New WCHAR[dwBufferSize + 1]; if (!pwszUrl) goto ErrorOutOfMemory; if (WinHttpQueryOption(_hHTTP, WINHTTP_OPTION_URL, pwszUrl, &dwBufferSize)) { V_BSTR(Value) = DL(SysAllocString)(pwszUrl); V_VT(Value) = VT_BSTR; hr = NOERROR; } else { hr = E_FAIL; } delete [] pwszUrl; if (FAILED(hr)) { goto ErrorFail; } else if (V_BSTR(Value) == NULL) { goto ErrorOutOfMemory; } } break; } case WinHttpRequestOption_URLCodePage: V_I4(Value) = (long) _dwCodePage; V_VT(Value) = VT_I4; break; case WinHttpRequestOption_EscapePercentInURL: V_BOOL(Value) = (_dwEscapeFlag & WINHTTP_FLAG_ESCAPE_PERCENT) ? VARIANT_TRUE : VARIANT_FALSE; V_VT(Value) = VT_BOOL; break; case WinHttpRequestOption_EnableCertificateRevocationCheck: V_BOOL(Value) = _fCheckForRevocation ? VARIANT_TRUE : VARIANT_FALSE; V_VT(Value) = VT_BOOL; break; case WinHttpRequestOption_SslErrorIgnoreFlags: if (_dwSslIgnoreFlags) V_I4(Value) = (long) (_dwSslIgnoreFlags & SslErrorFlag_Ignore_All); else V_I4(Value) = (long) 0; V_VT(Value) = VT_I4; break; case WinHttpRequestOption_UrlEscapeDisable: V_BOOL(Value) = (_dwEscapeFlag & WINHTTP_FLAG_ESCAPE_DISABLE) ? VARIANT_TRUE : VARIANT_FALSE; V_VT(Value) = VT_BOOL; break; case WinHttpRequestOption_UrlEscapeDisableQuery: V_BOOL(Value) = (_dwEscapeFlag & WINHTTP_FLAG_ESCAPE_DISABLE_QUERY) ? VARIANT_TRUE : VARIANT_FALSE; V_VT(Value) = VT_BOOL; break; case WinHttpRequestOption_EnableRedirects: BOOL bEnableRedirects; if (_dwRedirectPolicy == WINHTTP_OPTION_REDIRECT_POLICY_NEVER) { bEnableRedirects = FALSE; } else { bEnableRedirects = TRUE; // for this particular query we return TRUE even HTTPS->HTTP is not allowed // we are consistent with the SetOption where TRUE means "we allow redirs // except HTTPS->HTTP ones } V_BOOL(Value) = bEnableRedirects ? VARIANT_TRUE: VARIANT_FALSE; V_VT(Value) = VT_BOOL; break; case WinHttpRequestOption_EnableHttpsToHttpRedirects: V_BOOL(Value) = ((_dwRedirectPolicy == WINHTTP_OPTION_REDIRECT_POLICY_ALWAYS) ? VARIANT_TRUE : VARIANT_FALSE); V_VT(Value) = VT_BOOL; break; case WinHttpRequestOption_EnablePassportAuthentication: V_BOOL(Value) = ((_dwPassportConfig == (WINHTTP_DISABLE_PASSPORT_AUTH | WINHTTP_DISABLE_PASSPORT_KEYRING)) ? VARIANT_FALSE : VARIANT_TRUE); V_VT(Value) = VT_BOOL; break; case WinHttpRequestOption_MaxAutomaticRedirects: V_I4(Value) = _lMaxAutomaticRedirects; V_VT(Value) = VT_I4; break; case WinHttpRequestOption_MaxResponseHeaderSize: V_I4(Value) = _lMaxResponseHeaderSize; V_VT(Value) = VT_I4; break; case WinHttpRequestOption_MaxResponseDrainSize: V_I4(Value) = _lMaxResponseDrainSize; V_VT(Value) = VT_I4; break; case WinHttpRequestOption_EnableTracing: { BOOL fEnableTracing; DWORD dwBufferSize = sizeof(BOOL); if (!WinHttpQueryOption(NULL, WINHTTP_OPTION_ENABLETRACING, (LPVOID)&fEnableTracing, &dwBufferSize)) goto ErrorFail; V_BOOL(Value) = fEnableTracing ? VARIANT_TRUE : VARIANT_FALSE; V_VT(Value) = VT_BOOL; break; } case WinHttpRequestOption_RevertImpersonationOverSsl: V_BOOL(Value) = _bEnableSslImpersonation ? VARIANT_FALSE : VARIANT_TRUE; V_VT(Value) = VT_BOOL; break; case WinHttpRequestOption_EnableHttp1_1: V_BOOL(Value) = _bHttp1_1Mode ? VARIANT_TRUE : VARIANT_FALSE; V_VT(Value) = VT_BOOL; break; default: DL(VariantInit)(Value); hr = E_INVALIDARG; goto Error; } hr = NOERROR; Cleanup: SetErrorInfo(hr); return hr; ErrorCannotCallBeforeOpen: hr = HRESULT_FROM_WIN32(ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN); goto Error; ErrorOutOfMemory: hr = E_OUTOFMEMORY; goto Error; ErrorFail: hr = HRESULT_FROM_WIN32(GetLastError()); goto Error; Error: goto Cleanup; } STDMETHODIMP CHttpRequest::put_Option(WinHttpRequestOption Option, VARIANT Value) { HRESULT hr; if (!IsValidVariant(Value)) return E_INVALIDARG; switch (Option) { case WinHttpRequestOption_UserAgentString: { BSTR bstrUserAgent; hr = GetBSTRFromVariant(Value, &bstrUserAgent); if (FAILED(hr) || !bstrUserAgent) return E_INVALIDARG; if (*bstrUserAgent == L'\0') { DL(SysFreeString)(bstrUserAgent); return E_INVALIDARG; } if (_hInet) { if (!WinHttpSetOption(_hInet, WINHTTP_OPTION_USER_AGENT, bstrUserAgent, lstrlenW(bstrUserAgent))) { goto ErrorFail; } } if (_hHTTP) { if (!WinHttpSetOption(_hHTTP, WINHTTP_OPTION_USER_AGENT, bstrUserAgent, lstrlenW(bstrUserAgent))) { goto ErrorFail; } } if (_bstrUserAgent) DL(SysFreeString)(_bstrUserAgent); _bstrUserAgent = bstrUserAgent; break; } case WinHttpRequestOption_URL: // The URL cannot be set using the Option property. return E_INVALIDARG; case WinHttpRequestOption_URLCodePage: { _dwCodePage = GetDwordFromVariant(Value, CP_UTF8); if (_hInet) { if (!WinHttpSetOption(_hInet, WINHTTP_OPTION_CODEPAGE, &_dwCodePage, sizeof(_dwCodePage))) goto ErrorFail; } if (_hConnection) { if (!WinHttpSetOption(_hConnection, WINHTTP_OPTION_CODEPAGE, &_dwCodePage, sizeof(_dwCodePage))) goto ErrorFail; } break; } case WinHttpRequestOption_EscapePercentInURL: { BOOL fEscapePercent = GetBoolFromVariant(Value, FALSE); if (fEscapePercent) _dwEscapeFlag |= WINHTTP_FLAG_ESCAPE_PERCENT; else _dwEscapeFlag &= ~(DWORD)WINHTTP_FLAG_ESCAPE_PERCENT; break; } case WinHttpRequestOption_UrlEscapeDisable: { BOOL fEscape = GetBoolFromVariant(Value, FALSE); if (fEscape) _dwEscapeFlag |= WINHTTP_FLAG_ESCAPE_DISABLE; else _dwEscapeFlag &= ~(DWORD)WINHTTP_FLAG_ESCAPE_DISABLE; break; } case WinHttpRequestOption_UrlEscapeDisableQuery: { BOOL fEscape = GetBoolFromVariant(Value, FALSE); if (fEscape) _dwEscapeFlag |= WINHTTP_FLAG_ESCAPE_DISABLE_QUERY; else _dwEscapeFlag &= ~(DWORD)WINHTTP_FLAG_ESCAPE_DISABLE_QUERY; break; } case WinHttpRequestOption_EnableCertificateRevocationCheck: { _fCheckForRevocation = GetBoolFromVariant(Value, TRUE); if (_hHTTP && _fCheckForRevocation) { DWORD dwOptions = WINHTTP_ENABLE_SSL_REVOCATION; WinHttpSetOption(_hHTTP, WINHTTP_OPTION_ENABLE_FEATURE, (LPVOID)&dwOptions, sizeof(dwOptions)); } break; } case WinHttpRequestOption_SslErrorIgnoreFlags: { DWORD dwSslIgnoreFlags = GetDwordFromVariant(Value, _dwSslIgnoreFlags); if (dwSslIgnoreFlags & ~SECURITY_INTERNET_MASK) { return E_INVALIDARG; } dwSslIgnoreFlags &= SslErrorFlag_Ignore_All; if (_hHTTP) { // Set the SSL ignore flags through an undocumented front door if (!WinHttpSetOption(_hHTTP, WINHTTP_OPTION_SECURITY_FLAGS, (LPVOID)&dwSslIgnoreFlags, sizeof(dwSslIgnoreFlags))) goto ErrorFail; } _dwSslIgnoreFlags = dwSslIgnoreFlags; break; } case WinHttpRequestOption_SelectCertificate: { BSTR bstrCertSelection; hr = GetBSTRFromVariant(Value, &bstrCertSelection); if (FAILED(hr)) { hr = E_INVALIDARG; goto Error; } hr = SetClientCertificate(bstrCertSelection); DL(SysFreeString)(bstrCertSelection); if (FAILED(hr)) goto Error; break; } case WinHttpRequestOption_EnableRedirects: { BOOL fEnableRedirects = GetBoolFromVariant(Value, TRUE); DWORD dwRedirectPolicy = fEnableRedirects ? WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP : WINHTTP_OPTION_REDIRECT_POLICY_NEVER; if ((dwRedirectPolicy == WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP) && (_dwRedirectPolicy == WINHTTP_OPTION_REDIRECT_POLICY_ALWAYS)) { // "always" -> "disalow" transition no-op // this means the app enabled HTTPS->HTTP before this call, and attempt to enable redir // should not move us away from the always state break; } if (_hInet) { if (!WinHttpSetOption(_hInet, WINHTTP_OPTION_REDIRECT_POLICY, (LPVOID)&dwRedirectPolicy, sizeof(DWORD))) goto ErrorFail; } if (_hHTTP) { if (!WinHttpSetOption(_hHTTP, WINHTTP_OPTION_REDIRECT_POLICY, (LPVOID)&dwRedirectPolicy, sizeof(DWORD))) goto ErrorFail; } _dwRedirectPolicy = dwRedirectPolicy; break; } case WinHttpRequestOption_EnableHttpsToHttpRedirects: { BOOL fEnableHttpsToHttpRedirects = GetBoolFromVariant(Value, FALSE); DWORD dwRedirectPolicy = (fEnableHttpsToHttpRedirects ? WINHTTP_OPTION_REDIRECT_POLICY_ALWAYS : WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP); if (_dwRedirectPolicy == WINHTTP_OPTION_REDIRECT_POLICY_NEVER) { // "never" -> "always" or "never" -> "disalow" transition not allowed // this means the app disabled redirect before this call, it will have to re-enable redirect // before it can enable or disable HTTPS->HTTP break; } if (_hInet) { if (!WinHttpSetOption(_hInet, WINHTTP_OPTION_REDIRECT_POLICY, (LPVOID)&dwRedirectPolicy, sizeof(DWORD))) goto ErrorFail; } if (_hHTTP) { if (!WinHttpSetOption(_hHTTP, WINHTTP_OPTION_REDIRECT_POLICY, (LPVOID)&dwRedirectPolicy, sizeof(DWORD))) goto ErrorFail; } _dwRedirectPolicy = dwRedirectPolicy; break; } case WinHttpRequestOption_SecureProtocols: { DWORD dwSecureProtocols = GetDwordFromVariant(Value, _dwSecureProtocols); if (dwSecureProtocols & ~WINHTTP_FLAG_SECURE_PROTOCOL_ALL) { return E_INVALIDARG; } _dwSecureProtocols = dwSecureProtocols; if (_hInet) { // Set the per session SSL protocols. // This can be done at any time, so there's no need to // keep track of this here. if (!WinHttpSetOption(_hInet, WINHTTP_OPTION_SECURE_PROTOCOLS, (LPVOID)&dwSecureProtocols, sizeof(dwSecureProtocols))) goto ErrorFail; } break; } case WinHttpRequestOption_EnablePassportAuthentication: { BOOL fEnablePassportAuth = GetBoolFromVariant(Value, FALSE); DWORD dwPassportConfig = (fEnablePassportAuth ? (WINHTTP_ENABLE_PASSPORT_AUTH | WINHTTP_ENABLE_PASSPORT_KEYRING) : (WINHTTP_DISABLE_PASSPORT_AUTH | WINHTTP_DISABLE_PASSPORT_KEYRING)); if (_hInet) { if (!WinHttpSetOption(_hInet, WINHTTP_OPTION_CONFIGURE_PASSPORT_AUTH, (LPVOID)&dwPassportConfig, sizeof(DWORD))) goto ErrorFail; } _dwPassportConfig = dwPassportConfig; break; } case WinHttpRequestOption_EnableTracing: { BOOL fEnableTracing = GetBoolFromVariant(Value, TRUE); if (!WinHttpSetOption(NULL, WINHTTP_OPTION_ENABLETRACING, (LPVOID)&fEnableTracing, sizeof(BOOL))) goto ErrorFail; break; } case WinHttpRequestOption_RevertImpersonationOverSsl: { if (_hInet) { // Must be called before the Open method because // the open method also creates a request handle. hr = HRESULT_FROM_WIN32(ERROR_WINHTTP_CANNOT_CALL_AFTER_OPEN); goto Error; } else { _bEnableSslImpersonation = (GetBoolFromVariant(Value, TRUE) ? FALSE : TRUE); } break; } case WinHttpRequestOption_MaxAutomaticRedirects: case WinHttpRequestOption_MaxResponseHeaderSize: case WinHttpRequestOption_MaxResponseDrainSize: { DWORD dwSetting = (DWORD)-1; LONG* plResultTarget = NULL; switch(Option) { case WinHttpRequestOption_MaxAutomaticRedirects: dwSetting = WINHTTP_OPTION_MAX_HTTP_AUTOMATIC_REDIRECTS; plResultTarget = &_lMaxAutomaticRedirects; break; case WinHttpRequestOption_MaxResponseHeaderSize: dwSetting = WINHTTP_OPTION_MAX_RESPONSE_HEADER_SIZE; plResultTarget = &_lMaxResponseHeaderSize; break; case WinHttpRequestOption_MaxResponseDrainSize: dwSetting = WINHTTP_OPTION_MAX_RESPONSE_DRAIN_SIZE; plResultTarget = &_lMaxResponseDrainSize; break; default: INET_ASSERT(0); // shouldn't be possible goto ErrorFail; } LONG lInput = GetLongFromVariant(Value, -1); DWORD dwInput = (DWORD)lInput; DWORD dwInputSize = sizeof(dwInput); if (lInput < 0 || lInput != (LONG)dwInput) { hr = HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER); goto Error; } if (_hHTTP != NULL && TRUE != WinHttpSetOption( _hHTTP, dwSetting, &dwInput, dwInputSize)) { goto ErrorFail; } *plResultTarget = lInput; break; } case WinHttpRequestOption_EnableHttp1_1: if (_hHTTP != NULL) { hr = HRESULT_FROM_WIN32(ERROR_WINHTTP_CANNOT_CALL_AFTER_OPEN); goto Error; } _bHttp1_1Mode = GetBoolFromVariant(Value, TRUE); break; default: return E_INVALIDARG; } hr = NOERROR; Cleanup: SetErrorInfo(hr); return hr; ErrorFail: hr = HRESULT_FROM_WIN32(GetLastError()); goto Error; Error: goto Cleanup; } IErrorInfo * CHttpRequest::CreateErrorObject(HRESULT hr) { INET_ASSERT(FAILED(hr)); ICreateErrorInfo * pCErrInfo = NULL; IErrorInfo * pErrInfo = NULL; DWORD error = hr; DWORD dwFmtMsgFlag = FORMAT_MESSAGE_FROM_SYSTEM; HMODULE hModule = NULL; DWORD rc; LPWSTR pwszMessage = NULL; const DWORD dwSize = 512; pwszMessage = New WCHAR[dwSize]; if (pwszMessage == NULL) return NULL; if (HRESULT_FACILITY(hr) == FACILITY_WIN32) { DWORD errcode = HRESULT_CODE(hr); if ((errcode > WINHTTP_ERROR_BASE) && (errcode <= WINHTTP_ERROR_LAST)) { dwFmtMsgFlag = FORMAT_MESSAGE_FROM_HMODULE; hModule = GetModuleHandle("winhttp.dll"); error = errcode; } } rc = ::FormatMessageW(dwFmtMsgFlag, hModule, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language pwszMessage, dwSize, NULL); if (rc != 0) { if (SUCCEEDED(DL(CreateErrorInfo)(&pCErrInfo))) { if (SUCCEEDED(pCErrInfo->QueryInterface(IID_IErrorInfo, (void **) &pErrInfo))) { pCErrInfo->SetSource(L"WinHttp.WinHttpRequest"); pCErrInfo->SetGUID(IID_IWinHttpRequest); pCErrInfo->SetDescription(pwszMessage); } pCErrInfo->Release(); } } delete [] pwszMessage; return pErrInfo; } void CHttpRequest::SetErrorInfo(HRESULT hr) { if (FAILED(hr)) { IErrorInfo * pErrInfo = CreateErrorObject(hr); if (pErrInfo) { DL(SetErrorInfo)(0, pErrInfo); pErrInfo->Release(); } } } BOOL CHttpRequest::SelectCertificate() { HCERTSTORE hCertStore = NULL; BOOL fRet = FALSE; HANDLE hThreadToken = NULL; PCCERT_CONTEXT pCertContext = NULL; // Make sure security DLLs are loaded if (LoadSecurity() != ERROR_SUCCESS) return FALSE; // If impersonating, revert while trying to obtain the cert if (!_bEnableSslImpersonation && OpenThreadToken(GetCurrentThread(), (TOKEN_IMPERSONATE | TOKEN_READ), FALSE, &hThreadToken)) { INET_ASSERT(hThreadToken != 0); RevertToSelf(); } hCertStore = (*g_pfnCertOpenStore)(CERT_STORE_PROV_SYSTEM, 0, 0, CERT_STORE_OPEN_EXISTING_FLAG | CERT_STORE_READONLY_FLAG | (_fCertLocalMachine ? CERT_SYSTEM_STORE_LOCAL_MACHINE: CERT_SYSTEM_STORE_CURRENT_USER), _bstrCertStore ? _bstrCertStore : L"MY"); if (!hCertStore) { TRACE_PRINT_API(THRDINFO, INFO, ("Unable to open certificate store %s\\%Q; GetLastError() = %s [%d]\n", _fCertLocalMachine? "Local Machine": "Current User", _bstrCertStore ? _bstrCertStore : L"MY", InternetMapError(::GetLastError()), ::GetLastError() )); goto Cleanup; } if (_bstrCertSubject && _bstrCertSubject[0]) { CERT_RDN SubjectRDN; CERT_RDN_ATTR rdnAttr; rdnAttr.pszObjId = szOID_COMMON_NAME; rdnAttr.dwValueType = CERT_RDN_ANY_TYPE; rdnAttr.Value.cbData = lstrlenW(_bstrCertSubject) * sizeof(WCHAR); rdnAttr.Value.pbData = (BYTE *) _bstrCertSubject; SubjectRDN.cRDNAttr = 1; SubjectRDN.rgRDNAttr = &rdnAttr; // // First try an exact match for the certificate lookup. // If that fails, then try a prefix match. // pCertContext = (*g_pfnCertFindCertificateInStore)(hCertStore, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, CERT_CASE_INSENSITIVE_IS_RDN_ATTRS_FLAG | CERT_UNICODE_IS_RDN_ATTRS_FLAG, CERT_FIND_SUBJECT_ATTR, &SubjectRDN, NULL); if (! pCertContext) { pCertContext = (*g_pfnCertFindCertificateInStore)(hCertStore, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0, CERT_FIND_SUBJECT_STR, (LPVOID) _bstrCertSubject, NULL); } } else { pCertContext = (*g_pfnCertFindCertificateInStore)(hCertStore, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0, CERT_FIND_ANY, NULL, NULL); } if (pCertContext) { fRet = WinHttpSetOption(_hHTTP, WINHTTP_OPTION_CLIENT_CERT_CONTEXT, (LPVOID) pCertContext, sizeof(CERT_CONTEXT)); } else { TRACE_PRINT_API(THRDINFO, INFO, ("Unable to find certificate %Q in store %s\\%Q; GetLastError() = %s [%d]\n", _bstrCertSubject, _fCertLocalMachine? "Local Machine": "Current User", _bstrCertStore ? _bstrCertStore : L"MY", InternetMapError(::GetLastError()), ::GetLastError() )); } Cleanup: if (pCertContext) (*g_pfnCertFreeCertificateContext)(pCertContext); if (hCertStore) (*g_pfnCertCloseStore)(hCertStore, 0); // Restore the impersonating state for the current thread. if (hThreadToken) { (void)SetThreadToken(NULL, hThreadToken); CloseHandle(hThreadToken); } return fRet; } /* * ParseSelectedCert * * Purpose: * Given a certificate, breakdown the location * (local machine vs. current user), store (MY, CA, etc.), and * subject name of the form: * "[CURRENT_USER | LOCAL_MACHINE [\store]\]cert_subject_name" * * The backslash character is the delimiter, and the CURRENT_USER vs. * LOCAL_MACHINE choice can optionally include a store (any store * can be chosen). If there are more than two backslash characters * present in the string, this function assumes everything after the * second backslash is the cert subject name fragment to use for finding * a match. * * If the optional pieces are not specified "CURRENT_USER\MY" are * the defaults chosen. * * The pbstrLocation, pbstrStore, and pbstrSubject parameters * are allocated and filled in with the default or parsed strings, or set * to NULL if a failure occurs (e.g. out of memory or invalid param). * The caller should free all params on success via DL(SysFreeString). */ HRESULT ParseSelectedCert(BSTR bstrSelection, LPBOOL pfLocalMachine, BSTR *pbstrStore, BSTR *pbstrSubject ) { HRESULT hr = S_OK; LPWSTR lpwszSelection = bstrSelection; LPWSTR lpwszStart = lpwszSelection; *pfLocalMachine = FALSE; *pbstrStore = NULL; *pbstrSubject = NULL; if (!bstrSelection) { // When NULL, fill in an empty string to simulate first enum *pbstrSubject = DL(SysAllocString)(L""); if (!*pbstrSubject) { hr = E_OUTOFMEMORY; goto quit; } // Need to also fill in the default "MY" store. goto DefaultStore; } while (*lpwszSelection && *lpwszSelection != L'\\') lpwszSelection++; if (*lpwszSelection == L'\\') { // LOCAL_MACHINE vs. CURRENT_USER was selected. // Check for invalid arg since it must match either. if (!wcsncmp(lpwszStart, L"LOCAL_MACHINE", lpwszSelection-lpwszStart)) { *pfLocalMachine = TRUE; } else if (wcsncmp(lpwszStart, L"CURRENT_USER", lpwszSelection-lpwszStart)) { hr = E_INVALIDARG; goto quit; } // else already defaults to having *pfLocalMachine initialized to FALSE lpwszStart = ++lpwszSelection; // Now look for the optional choice on the store while (*lpwszSelection && *lpwszSelection != L'\\') lpwszSelection++; if (*lpwszSelection == L'\\') { // Accept any store name. // When opening the store, it will fail if the selected // store does not exist. *pbstrStore = DL(SysAllocStringLen)(lpwszStart, (UINT) (lpwszSelection-lpwszStart)); if (!*pbstrStore) { hr = E_OUTOFMEMORY; goto Cleanup; } lpwszStart = ++lpwszSelection; } } // lpwszStart points to the portion designating the subject string // which could be part or all of pbstrSelection. // // If the string is empty, then fill in an empty string, which // will mean to use the first enumerated cert. *pbstrSubject = DL(SysAllocString)(lpwszStart); if (!*pbstrSubject) { hr = E_OUTOFMEMORY; goto Cleanup; } DefaultStore: // Fill in MY store default if the store name wasn't specified. if (!*pbstrStore) { // Default to MY store *pbstrStore = DL(SysAllocString)(L"MY"); if (!*pbstrStore) { hr = E_OUTOFMEMORY; goto Cleanup; } } quit: return hr; Cleanup: if (*pbstrStore) { DL(SysFreeString)(*pbstrStore); *pbstrStore = NULL; } if (*pbstrSubject) { DL(SysFreeString)(*pbstrSubject); *pbstrSubject = NULL; } goto quit; } #ifdef TRUE_ASYNC HRESULT CHttpRequest::PrepareToReadData(HINTERNET hInternet) { HRESULT hr = NOERROR; BSTR bstrContentType = NULL; DWORD dwStatus = 0; BOOL fRetCode; DWORD cb; // Get the content length _dwContentLength = 0; fRetCode = GetContentLengthIfResponseNotChunked(hInternet, &_dwContentLength); INET_ASSERT((_pResponseStream == NULL) && (_cbResponseBody == 0)); hr = DL(CreateStreamOnHGlobal)(NULL, TRUE, &_pResponseStream); if (FAILED(hr)) goto ErrorFail; // pre-set response stream size if we have a Content-Length if (fRetCode) { ULARGE_INTEGER size; size.LowPart = _dwContentLength; size.HighPart = 0; _pResponseStream->SetSize(size); } else { // Content-Length was not specified in the response, but this // does not mean Content-Length==0. We will keep reading until // either no more data is available. Set dwContentLength to 4GB // to trick our read loop into reading until QDA reports EOF _dwContentLength = (DWORD)(-1L); ULARGE_INTEGER size; size.LowPart = SIZEOF_BUFFER; size.HighPart = 0; _pResponseStream->SetSize(size); } if ((_dwContentLength > 0) && (_Buffer == NULL)) { _Buffer = New BYTE[SIZEOF_BUFFER]; if (!_Buffer) { goto ErrorOutOfMemory; } } //get status cb = sizeof(dwStatus); if (!HttpQueryInfoA( hInternet, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX, &dwStatus, &cb, 0)) goto ErrorFail; //get content type hr = _GetResponseHeader2(L"Content-Type", &bstrContentType, hInternet); if (FAILED(hr)) { bstrContentType = DL(SysAllocString)(L""); if (bstrContentType == NULL) goto ErrorOutOfMemory; hr = NOERROR; } _CP.FireOnResponseStart((long)dwStatus, bstrContentType); hr = NOERROR; Cleanup: if (bstrContentType) DL(SysFreeString)(bstrContentType); return hr; ErrorOutOfMemory: hr = E_OUTOFMEMORY; goto Error; ErrorFail: hr = HRESULT_FROM_WIN32(GetLastError()); goto Error; Error: SafeRelease(_pResponseStream); _cbResponseBody = NULL; goto Cleanup; } #define ASYNC_SEND_CALLBACK_NOTIFICATIONS \ WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE |\ WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE |\ WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE |\ WINHTTP_CALLBACK_STATUS_READ_COMPLETE |\ WINHTTP_CALLBACK_STATUS_REQUEST_ERROR |\ WINHTTP_CALLBACK_STATUS_SECURE_FAILURE HRESULT CHttpRequest::StartAsyncSend() { DEBUG_ENTER((DBG_HTTP, Dword, "IWinHttpRequest::StartAsyncSend", NULL )); HRESULT hr; hr = _CP.CreateEventSinksMarshaller(); if (FAILED(hr)) goto Error; hr = NOERROR; //init vars _hrAsyncResult = NOERROR; _dwNumberOfBytesAvailable = 0; _cbNumberOfBytesRead = 0; if (!_hCompleteEvent) { _hCompleteEvent = CreateEvent(NULL, TRUE, FALSE, NULL); if (_hCompleteEvent == NULL) goto ErrorFail; } else { if (!ResetEvent(_hCompleteEvent)) goto ErrorFail; } //register callback if (WINHTTP_INVALID_STATUS_CALLBACK == WinHttpSetStatusCallback(_hHTTP, AsyncCallback, ASYNC_SEND_CALLBACK_NOTIFICATIONS, NULL)) goto ErrorFail; // Initiate async HTTP request SetState(SENDING); if (!WinHttpSendRequest( _hHTTP, NULL, 0, // No header info here _szRequestBuffer, _cbRequestBody, _cbRequestBody, reinterpret_cast<DWORD_PTR>(this))) goto ErrorFailWinHttpAPI; Cleanup: DEBUG_LEAVE(hr); return hr; ErrorFail: hr = HRESULT_FROM_WIN32(GetLastError()); Error: if (_hCompleteEvent) { CloseHandle(_hCompleteEvent); _hCompleteEvent = NULL; } goto Cleanup; ErrorFailWinHttpAPI: hr = HRESULT_FROM_WIN32(GetLastError()); _CP.FireOnError(hr); goto Error; } void CHttpRequest::CompleteDataRead(bool bNotAborted, HINTERNET hInternet) { DEBUG_ENTER((DBG_HTTP, None, "IWinHttpRequest::CompleteDataRead", "bNotAborted: %s", bNotAborted ? "true" : "false" )); //unregister callback WinHttpSetStatusCallback(hInternet, NULL, ASYNC_SEND_CALLBACK_NOTIFICATIONS, NULL); if (_pResponseStream) { ULARGE_INTEGER size; // set final size on stream size.LowPart = _cbResponseBody; size.HighPart = 0; _pResponseStream->SetSize(size); } if (bNotAborted) _CP.FireOnResponseFinished(); SetEvent(_hCompleteEvent); DEBUG_LEAVE(0); } void CALLBACK CHttpRequest::SyncCallback( HINTERNET hInternet, DWORD_PTR dwContext, DWORD dwInternetStatus, LPVOID lpvStatusInformation, DWORD dwStatusInformationLength) { UNREFERENCED_PARAMETER(hInternet); UNREFERENCED_PARAMETER(dwStatusInformationLength); DEBUG_ENTER((DBG_HTTP, None, "CHttpRequest::SyncCallback", "hInternet: %#x, dwContext: %#x, dwInternetStatus:%#x, %#x, %#d", hInternet, dwContext, dwInternetStatus, lpvStatusInformation, dwStatusInformationLength )); if (dwContext == NULL) { return; } CHttpRequest * pRequest = reinterpret_cast<CHttpRequest*>(dwContext); // unexpected notification? INET_ASSERT(dwInternetStatus == WINHTTP_CALLBACK_STATUS_SECURE_FAILURE); if (!pRequest->_bAborted) { switch (dwInternetStatus) { case WINHTTP_CALLBACK_STATUS_SECURE_FAILURE: pRequest->_hrSecureFailure = SecureFailureFromStatus(*((DWORD *)lpvStatusInformation)); break; } } DEBUG_LEAVE(0); } void CALLBACK CHttpRequest::AsyncCallback(HINTERNET hInternet, DWORD_PTR dwContext, DWORD dwInternetStatus, LPVOID lpvStatusInformation, DWORD dwStatusInformationLength) { DEBUG_ENTER((DBG_HTTP, None, "IWinHttpRequest::AsyncCallback", "hInternet: %#x, dwContext: %#x, dwInternetStatus:%#x, %#x, %#d", hInternet, dwContext, dwInternetStatus, lpvStatusInformation, dwStatusInformationLength )); if (dwContext == NULL) { DEBUG_PRINT_API(ASYNC, FATAL, ("Unexpected: dwContext parameter is zero!\n")) DEBUG_LEAVE(0); return; } CHttpRequest* pRequest = reinterpret_cast<CHttpRequest*>(dwContext); if ((dwInternetStatus & ASYNC_SEND_CALLBACK_NOTIFICATIONS) == 0) { //unexpected notification DEBUG_PRINT_API(ASYNC, FATAL, ("Unexpected dwInternetStatus value!\n")) pRequest->_hrAsyncResult = HRESULT_FROM_WIN32(ERROR_WINHTTP_INTERNAL_ERROR); goto Error; } if (pRequest->_bAborted) goto Aborted; DWORD dwBytesToRead = 0; switch (dwInternetStatus) { case WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE : //SR completed pRequest->SetState(SENT); if (!::WinHttpReceiveResponse(hInternet, NULL)) goto ErrorFail; break; case WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE : //RR completed, read data pRequest->SetState(RECEIVING); pRequest->_hrAsyncResult = pRequest->PrepareToReadData(hInternet); if (FAILED(pRequest->_hrAsyncResult)) goto Error; if (pRequest->_dwContentLength == 0) { goto RequestComplete; } //start reading data dwBytesToRead = min(pRequest->_dwContentLength, SIZEOF_BUFFER); break; case WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE : //QDA completed INET_ASSERT(dwStatusInformationLength == sizeof(DWORD)); pRequest->_dwNumberOfBytesAvailable = *(LPDWORD)lpvStatusInformation; if (pRequest->_dwNumberOfBytesAvailable) dwBytesToRead = min(pRequest->_dwNumberOfBytesAvailable, SIZEOF_BUFFER); //continue read else goto RequestComplete; //no more data to read break; case WINHTTP_CALLBACK_STATUS_READ_COMPLETE : //RD completed pRequest->_cbNumberOfBytesRead = dwStatusInformationLength; if (pRequest->_cbNumberOfBytesRead) { HRESULT hr = pRequest->_pResponseStream->Write(pRequest->_Buffer, pRequest->_cbNumberOfBytesRead, NULL); if (FAILED(hr)) { pRequest->_hrAsyncResult = E_OUTOFMEMORY; goto Error; } pRequest->_CP.FireOnResponseDataAvailable((const BYTE *)pRequest->_Buffer, pRequest->_cbNumberOfBytesRead); pRequest->_cbResponseBody += pRequest->_cbNumberOfBytesRead; if (pRequest->_cbResponseBody >= pRequest->_dwContentLength) { goto RequestComplete; } else { //perform QDA to make sure there is no more data to read if (pRequest->_bAborted) goto Aborted; if (!WinHttpQueryDataAvailable(hInternet, NULL)) goto ErrorFail; } } else goto RequestComplete; //no more data to read break; case WINHTTP_CALLBACK_STATUS_SECURE_FAILURE: pRequest->_hrSecureFailure = SecureFailureFromStatus(*((DWORD *)lpvStatusInformation)); goto Cleanup; case WINHTTP_CALLBACK_STATUS_REQUEST_ERROR : { DWORD dwError = ((LPWINHTTP_ASYNC_RESULT)lpvStatusInformation)->dwError; if (dwError == ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED) { if (!pRequest->_bRetriedWithCert) { pRequest->_bRetriedWithCert = TRUE; if (pRequest->SelectCertificate()) { // Initiate async HTTP request pRequest->SetState(SENDING); if (!WinHttpSendRequest( hInternet, NULL, 0, // No header info here pRequest->_szRequestBuffer, pRequest->_cbRequestBody, pRequest->_cbRequestBody, reinterpret_cast<DWORD_PTR>(pRequest))) goto ErrorFail; break; } } } goto ErrorFail; } } if (dwBytesToRead) { if (pRequest->_bAborted) goto Aborted; if (!WinHttpReadData(hInternet, pRequest->_Buffer, dwBytesToRead, NULL)) goto ErrorFail; } Cleanup: DEBUG_LEAVE(0); return; Aborted: pRequest->CompleteDataRead(false, hInternet); goto Cleanup; ErrorFail: pRequest->_hrAsyncResult = HRESULT_FROM_WIN32(GetLastError()); if (pRequest->_hrAsyncResult == HRESULT_FROM_WIN32(ERROR_WINHTTP_SECURE_FAILURE)) { INET_ASSERT(FAILED(pRequest->_hrSecureFailure)); pRequest->_hrAsyncResult = pRequest->_hrSecureFailure; } pRequest->_CP.FireOnError(pRequest->_hrAsyncResult); Error: DEBUG_PRINT_API(ASYNC, ERROR, ("Error set: %#x\n", pRequest->_hrAsyncResult)) pRequest->CompleteDataRead(false, hInternet); goto Cleanup; RequestComplete: pRequest->SetState(RESPONSE); pRequest->CompleteDataRead(true, hInternet); goto Cleanup; } #endif//TRUE_ASYNC /* * BSTRToUTF8 * * Purpose: * Convert a BSTR to UTF-8 * */ static HRESULT BSTRToUTF8(char ** psz, DWORD * pcbUTF8, BSTR bstr, bool * pbSetUtf8Charset) { UINT cch = lstrlenW(bstr); bool bSimpleConversion = false; *pcbUTF8 = 0; *psz = NULL; if (cch == 0) return NOERROR; PreWideCharToUtf8(bstr, cch, (UINT *)pcbUTF8, &bSimpleConversion); *psz = New char [*pcbUTF8 + 1]; if (!*psz) return E_OUTOFMEMORY; WideCharToUtf8(bstr, cch, (BYTE *)*psz, bSimpleConversion); (*psz)[*pcbUTF8] = 0; if (pbSetUtf8Charset) { *pbSetUtf8Charset = !bSimpleConversion; } return NOERROR; } /** * Scans buffer and translates Unicode characters into UTF8 characters */ static void PreWideCharToUtf8( WCHAR * buffer, UINT cch, UINT * cb, bool * bSimpleConversion) { UINT count = 0; DWORD dw1; bool surrogate = false; for (UINT i = cch; i > 0; i--) { DWORD dw = *buffer; if (surrogate) // is it the second char of a surrogate pair? { if (dw >= 0xdc00 && dw <= 0xdfff) { // four bytes 0x11110xxx 0x10xxxxxx 0x10xxxxxx 0x10xxxxxx count += 4; surrogate = false; buffer++; continue; } else // Then dw1 must be a three byte character { count += 3; } surrogate = false; } if (dw < 0x80) // one byte, 0xxxxxxx { count++; } else if (dw < 0x800) // two WORDS, 110xxxxx 10xxxxxx { count += 2; } else if (dw >= 0xd800 && dw <= 0xdbff) // Assume that it is the first char of surrogate pair { if (i == 1) // last wchar in buffer break; dw1 = dw; surrogate = true; } else // three bytes, 1110xxxx 10xxxxxx 10xxxxxx { count += 3; } buffer++; } *cb = count; *bSimpleConversion = (cch == count); } /** * Scans buffer and translates Unicode characters into UTF8 characters */ static void WideCharToUtf8( WCHAR * buffer, UINT cch, BYTE * bytebuffer, bool bSimpleConversion) { DWORD dw1 = 0; bool surrogate = false; INET_ASSERT(bytebuffer != NULL); if (bSimpleConversion) { for (UINT i = cch; i > 0; i--) { DWORD dw = *buffer; *bytebuffer++ = (byte)dw; buffer++; } } else { for (UINT i = cch; i > 0; i--) { DWORD dw = *buffer; if (surrogate) // is it the second char of a surrogate pair? { if (dw >= 0xdc00 && dw <= 0xdfff) { // four bytes 0x11110xxx 0x10xxxxxx 0x10xxxxxx 0x10xxxxxx ULONG ucs4 = (dw1 - 0xd800) * 0x400 + (dw - 0xdc00) + 0x10000; *bytebuffer++ = (byte)(( ucs4 >> 18) | 0xF0); *bytebuffer++ = (byte)((( ucs4 >> 12) & 0x3F) | 0x80); *bytebuffer++ = (byte)((( ucs4 >> 6) & 0x3F) | 0x80); *bytebuffer++ = (byte)(( ucs4 & 0x3F) | 0x80); surrogate = false; buffer++; continue; } else // Then dw1 must be a three byte character { *bytebuffer++ = (byte)(( dw1 >> 12) | 0xE0); *bytebuffer++ = (byte)((( dw1 >> 6) & 0x3F) | 0x80); *bytebuffer++ = (byte)(( dw1 & 0x3F) | 0x80); } surrogate = false; } if (dw < 0x80) // one byte, 0xxxxxxx { *bytebuffer++ = (byte)dw; } else if ( dw < 0x800) // two WORDS, 110xxxxx 10xxxxxx { *bytebuffer++ = (byte)((dw >> 6) | 0xC0); *bytebuffer++ = (byte)((dw & 0x3F) | 0x80); } else if (dw >= 0xd800 && dw <= 0xdbff) // Assume that it is the first char of surrogate pair { if (i == 1) // last wchar in buffer break; dw1 = dw; surrogate = true; } else // three bytes, 1110xxxx 10xxxxxx 10xxxxxx { *bytebuffer++ = (byte)(( dw >> 12) | 0xE0); *bytebuffer++ = (byte)((( dw >> 6) & 0x3F) | 0x80); *bytebuffer++ = (byte)(( dw & 0x3F) | 0x80); } buffer++; } } } /* * AsciiToBSTR * * Purpose: * Convert an ascii string to a BSTR * * only **STRLEN** to be passed to AsciiToBSTR (not including terminating NULL, if any) * */ static HRESULT AsciiToBSTR(BSTR * pbstr, char * sz, int cch) { int cwch; INET_ASSERT (cch != -1); // Determine how big the ascii string will be cwch = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, sz, cch, NULL, 0); *pbstr = DL(SysAllocStringLen)(NULL, cwch); if (!*pbstr) return E_OUTOFMEMORY; cch = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, sz, cch, *pbstr, cwch); return NOERROR; } /* * GetBSTRFromVariant * * Purpose: * Convert a VARIANT to a BSTR * * If VariantChangeType raises an exception, then an E_INVALIDARG * error is returned. */ static HRESULT GetBSTRFromVariant(VARIANT varVariant, BSTR * pBstr) { VARIANT varTemp; HRESULT hr = NOERROR; *pBstr = NULL; if (V_VT(&varVariant) != VT_EMPTY && V_VT(&varVariant) != VT_NULL && V_VT(&varVariant) != VT_ERROR) { DL(VariantInit)(&varTemp); __try { hr = DL(VariantChangeType)( &varTemp, &varVariant, 0, VT_BSTR); if (SUCCEEDED(hr)) { *pBstr = V_BSTR(&varTemp); // take over ownership of BSTR } } __except (EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } } // DON'T clear the variant because we stole the BSTR //DL(VariantClear)(&varTemp); return hr; } /* * GetBoolFromVariant * * Purpose: * Convert a VARIANT to a Boolean * */ static BOOL GetBoolFromVariant(VARIANT varVariant, BOOL fDefault) { HRESULT hr; BOOL fResult = fDefault; if (V_VT(&varVariant) != VT_EMPTY && V_VT(&varVariant) != VT_NULL && V_VT(&varVariant) != VT_ERROR) { VARIANT varTemp; DL(VariantInit)(&varTemp); hr = DL(VariantChangeType)( &varTemp, &varVariant, 0, VT_BOOL); if (FAILED(hr)) goto Cleanup; fResult = V_BOOL(&varTemp) == VARIANT_TRUE ? TRUE : FALSE; } hr = NOERROR; Cleanup: return fResult; } /* * GetDwordFromVariant * * Purpose: * Convert a VARIANT to a DWORD * */ static DWORD GetDwordFromVariant(VARIANT varVariant, DWORD dwDefault) { HRESULT hr; DWORD dwResult = dwDefault; if (V_VT(&varVariant) != VT_EMPTY && V_VT(&varVariant) != VT_NULL && V_VT(&varVariant) != VT_ERROR) { VARIANT varTemp; DL(VariantInit)(&varTemp); hr = DL(VariantChangeType)( &varTemp, &varVariant, 0, VT_UI4); if (FAILED(hr)) goto Cleanup; dwResult = V_UI4(&varTemp); } hr = NOERROR; Cleanup: return dwResult; } /* * GetLongFromVariant * * Purpose: * Convert a VARIANT to a DWORD * */ static long GetLongFromVariant(VARIANT varVariant, long lDefault) { HRESULT hr; long lResult = lDefault; if (V_VT(&varVariant) != VT_EMPTY && V_VT(&varVariant) != VT_NULL && V_VT(&varVariant) != VT_ERROR) { VARIANT varTemp; DL(VariantInit)(&varTemp); hr = DL(VariantChangeType)( &varTemp, &varVariant, 0, VT_I4); if (FAILED(hr)) goto Cleanup; lResult = V_I4(&varTemp); } hr = NOERROR; Cleanup: return lResult; } /** * Helper to create a char safearray from a string */ static HRESULT CreateVector(VARIANT * pVar, const BYTE * pData, DWORD cElems) { HRESULT hr; BYTE * pB; SAFEARRAY * psa = DL(SafeArrayCreateVector)(VT_UI1, 0, cElems); if (!psa) { hr = E_OUTOFMEMORY; goto Cleanup; } hr = DL(SafeArrayAccessData)(psa, (void **)&pB); if (FAILED(hr)) goto Error; memcpy(pB, pData, cElems); DL(SafeArrayUnaccessData)(psa); INET_ASSERT((pVar->vt == VT_EMPTY) || (pVar->vt == VT_NULL)); V_ARRAY(pVar) = psa; pVar->vt = VT_ARRAY | VT_UI1; hr = NOERROR; Cleanup: return hr; Error: if (psa) DL(SafeArrayDestroy)(psa); goto Cleanup; } /* * ReadFromStream * * Purpose: * Extract the contents of a stream into a buffer. * * Parameters: * ppBuf IN/OUT Buffer * pStm IN Stream * * Errors: * E_INVALIDARG * E_OUTOFMEMORY */ static HRESULT ReadFromStream(char ** ppData, ULONG * pcbData, IStream * pStm) { HRESULT hr = NOERROR; char * pBuffer = NULL; // Buffer ULONG cbBuffer = 0; // Bytes in buffer ULONG cbData = 0; // Bytes of data in buffer ULONG cbRead = 0; // Bytes read from stream ULONG cbNewSize = 0; char * pNewBuf = NULL; if (!ppData || !pStm) return E_INVALIDARG; *ppData = NULL; *pcbData = 0; while (TRUE) { if (cbData + 512 > cbBuffer) { cbNewSize = (cbData ? cbData*2 : 4096); pNewBuf = New char[cbNewSize+1]; if (!pNewBuf) goto ErrorOutOfMemory; if (cbData) ::memcpy(pNewBuf, pBuffer, cbData); cbBuffer = cbNewSize; delete[] pBuffer; pBuffer = pNewBuf; pBuffer[cbData] = 0; } hr = pStm->Read( &pBuffer[cbData], cbBuffer - cbData, &cbRead); if (FAILED(hr)) goto Error; cbData += cbRead; pBuffer[cbData] = 0; // No more data if (cbRead == 0) break; } *ppData = pBuffer; *pcbData = cbData; hr = NOERROR; Cleanup: return hr; ErrorOutOfMemory: hr = E_OUTOFMEMORY; goto Error; Error: if (pBuffer) delete [] pBuffer; goto Cleanup; } static void MessageLoop() { MSG msg; // There is a window message available. Dispatch it. while (PeekMessage(&msg, NULL, NULL, NULL, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } } static DWORD UpdateTimeout(DWORD dwTimeout, DWORD dwStartTime) { if (dwTimeout != INFINITE) { DWORD dwTimeNow = GetTickCount(); DWORD dwElapsedTime; if (dwTimeNow >= dwStartTime) { dwElapsedTime = dwTimeNow - dwStartTime; } else { dwElapsedTime = dwTimeNow + (0xFFFFFFFF - dwStartTime); } if (dwElapsedTime < dwTimeout) { dwTimeout -= dwElapsedTime; } else { dwTimeout = 0; } } return dwTimeout; } DWORD CSinkArray::Add(IUnknown * pUnk) { ULONG iIndex; IUnknown** pp = NULL; if (_nSize == 0) // no connections { _pUnk = pUnk; _nSize = 1; return 1; } else if (_nSize == 1) { // create array pp = (IUnknown **)ALLOCATE_ZERO_MEMORY(sizeof(IUnknown*)* _DEFAULT_VECTORLENGTH); if (pp == NULL) return 0; *pp = _pUnk; _ppUnk = pp; _nSize = _DEFAULT_VECTORLENGTH; } for (pp = begin(); pp < end(); pp++) { if (*pp == NULL) { *pp = pUnk; iIndex = ULONG(pp-begin()); return iIndex+1; } } int nAlloc = _nSize*2; pp = (IUnknown **)REALLOCATE_MEMORY_ZERO(_ppUnk, sizeof(IUnknown*)*nAlloc); if (pp == NULL) return 0; _ppUnk = pp; _ppUnk[_nSize] = pUnk; iIndex = _nSize; _nSize = nAlloc; return iIndex+1; } BOOL CSinkArray::Remove(DWORD dwCookie) { ULONG iIndex; if (dwCookie == NULL) return FALSE; if (_nSize == 0) return FALSE; iIndex = dwCookie-1; if (iIndex >= (ULONG)_nSize) return FALSE; if (_nSize == 1) { _nSize = 0; return TRUE; } begin()[iIndex] = NULL; return TRUE; } void CSinkArray::ReleaseAll() { for (IUnknown ** pp = begin(); pp < end(); pp++) { if (*pp != NULL) { SafeRelease(*pp); } } } HRESULT STDMETHODCALLTYPE CSinkArray::QueryInterface(REFIID, void **) { return E_NOTIMPL; } ULONG STDMETHODCALLTYPE CSinkArray::AddRef() { return 2; } ULONG STDMETHODCALLTYPE CSinkArray::Release() { return 1; } void STDMETHODCALLTYPE CSinkArray::OnResponseStart(long Status, BSTR bstrContentType) { for (IUnknown ** pp = begin(); pp < end(); pp++) { if (*pp != NULL) { IWinHttpRequestEvents * pSink; pSink = static_cast<IWinHttpRequestEvents *>(*pp); if (((*(DWORD_PTR **)pSink)[3]) != NULL) { pSink->OnResponseStart(Status, bstrContentType); } } } } void STDMETHODCALLTYPE CSinkArray::OnResponseDataAvailable(SAFEARRAY ** ppsaData) { for (IUnknown ** pp = begin(); pp < end(); pp++) { if (*pp != NULL) { IWinHttpRequestEvents * pSink; pSink = static_cast<IWinHttpRequestEvents *>(*pp); if (((*(DWORD_PTR **)pSink)[4]) != NULL) { pSink->OnResponseDataAvailable(ppsaData); } } } } void STDMETHODCALLTYPE CSinkArray::OnResponseFinished(void) { for (IUnknown ** pp = begin(); pp < end(); pp++) { if (*pp != NULL) { IWinHttpRequestEvents * pSink; pSink = static_cast<IWinHttpRequestEvents *>(*pp); if (((*(DWORD_PTR **)pSink)[5]) != NULL) { pSink->OnResponseFinished(); } } } } void STDMETHODCALLTYPE CSinkArray::OnError(long ErrorNumber, BSTR ErrorDescription) { for (IUnknown ** pp = begin(); pp < end(); pp++) { if (*pp != NULL) { IWinHttpRequestEvents * pSink; pSink = static_cast<IWinHttpRequestEvents *>(*pp); if (((*(DWORD_PTR **)pSink)[6]) != NULL) { pSink->OnError(ErrorNumber, ErrorDescription); } } } } CWinHttpRequestEventsMarshaller::CWinHttpRequestEventsMarshaller ( CSinkArray * pSinkArray, HWND hWnd ) { INET_ASSERT((pSinkArray != NULL) && (hWnd != NULL)); _pSinkArray = pSinkArray; _hWnd = hWnd; _cRefs = 0; _bFireEvents = true; _cs.Init(); } CWinHttpRequestEventsMarshaller::~CWinHttpRequestEventsMarshaller() { INET_ASSERT(_pSinkArray == NULL); INET_ASSERT(_hWnd == NULL); INET_ASSERT(_cRefs == 0); } HRESULT CWinHttpRequestEventsMarshaller::Create ( CSinkArray * pSinkArray, CWinHttpRequestEventsMarshaller ** ppSinkMarshaller ) { CWinHttpRequestEventsMarshaller * pSinkMarshaller = NULL; HWND hWnd = NULL; HRESULT hr = NOERROR; if (!RegisterWinHttpEventMarshallerWndClass()) goto ErrorFail; hWnd = CreateWindowEx(0, s_szWinHttpEventMarshallerWndClass, NULL, 0, 0, 0, 0, 0, (IsPlatformWinNT() && GlobalPlatformVersion5) ? HWND_MESSAGE : NULL, NULL, GlobalDllHandle, NULL); if (!hWnd) goto ErrorFail; pSinkMarshaller = New CWinHttpRequestEventsMarshaller(pSinkArray, hWnd); if (!pSinkMarshaller) goto ErrorOutOfMemory; SetLastError(0); SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR) pSinkMarshaller); if (GetLastError() != 0) goto ErrorFail; pSinkMarshaller->AddRef(); *ppSinkMarshaller = pSinkMarshaller; Exit: if (FAILED(hr)) { if (pSinkMarshaller) { delete pSinkMarshaller; } else if (hWnd) { DestroyWindow(hWnd); } } return hr; ErrorFail: hr = HRESULT_FROM_WIN32(GetLastError()); goto Exit; ErrorOutOfMemory: hr = E_OUTOFMEMORY; goto Exit; } void CWinHttpRequestEventsMarshaller::Shutdown() { if (_cs.Lock()) { FreezeEvents(); if (_hWnd) { MessageLoop(); DestroyWindow(_hWnd); _hWnd = NULL; } _pSinkArray = NULL; _cs.Unlock(); } } LRESULT CALLBACK CWinHttpRequestEventsMarshaller::WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (msg >= WHREM_MSG_ON_RESPONSE_START && msg <= WHREM_MSG_ON_ERROR) { CWinHttpRequestEventsMarshaller * pMarshaller; CSinkArray * pSinkArray = NULL; bool bOkToFireEvents = false; pMarshaller = (CWinHttpRequestEventsMarshaller *) GetWindowLongPtr(hWnd, GWLP_USERDATA); if (pMarshaller) { pSinkArray = pMarshaller->GetSinkArray(); bOkToFireEvents = pMarshaller->OkToFireEvents(); } switch (msg) { case WHREM_MSG_ON_RESPONSE_START: { BSTR bstrContentType = (BSTR) lParam; if (bOkToFireEvents) { pSinkArray->OnResponseStart((long) wParam, bstrContentType); } if (bstrContentType) { DL(SysFreeString)(bstrContentType); } } break; case WHREM_MSG_ON_RESPONSE_DATA_AVAILABLE: { SAFEARRAY * psaData = (SAFEARRAY *) wParam; if (bOkToFireEvents) { pSinkArray->OnResponseDataAvailable(&psaData); } if (psaData) { DL(SafeArrayDestroy)(psaData); } } break; case WHREM_MSG_ON_RESPONSE_FINISHED: if (bOkToFireEvents) { pSinkArray->OnResponseFinished(); } break; case WHREM_MSG_ON_ERROR: { BSTR bstrErrorDescription = (BSTR) lParam; if (bOkToFireEvents) { pSinkArray->OnError((long) wParam, bstrErrorDescription); } if (bstrErrorDescription) { DL(SysFreeString)(bstrErrorDescription); } } break; } return 0; } else { return DefWindowProc(hWnd, msg, wParam, lParam); } } HRESULT STDMETHODCALLTYPE CWinHttpRequestEventsMarshaller::QueryInterface(REFIID riid, void ** ppv) { HRESULT hr = NOERROR; if (ppv == NULL) { hr = E_INVALIDARG; } else if (riid == IID_IWinHttpRequestEvents || riid == IID_IUnknown) { *ppv = static_cast<IWinHttpRequestEvents *>(this); AddRef(); } else hr = E_NOINTERFACE; return hr; } ULONG STDMETHODCALLTYPE CWinHttpRequestEventsMarshaller::AddRef() { return InterlockedIncrement(&_cRefs); } ULONG STDMETHODCALLTYPE CWinHttpRequestEventsMarshaller::Release() { DWORD cRefs = InterlockedDecrement(&_cRefs); if (cRefs == 0) { delete this; return 0; } else return cRefs; } void STDMETHODCALLTYPE CWinHttpRequestEventsMarshaller::OnResponseStart(long Status, BSTR bstrContentType) { if (_cs.Lock()) { if (OkToFireEvents()) { BSTR bstrContentTypeCopy; bstrContentTypeCopy = DL(SysAllocString)(bstrContentType); PostMessage(_hWnd, WHREM_MSG_ON_RESPONSE_START, (WPARAM) Status, (LPARAM) bstrContentTypeCopy); // Note: ownership of bstrContentTypeCopy is transferred to the // message window, so the string is not freed here. } _cs.Unlock(); } } void STDMETHODCALLTYPE CWinHttpRequestEventsMarshaller::OnResponseDataAvailable(SAFEARRAY ** ppsaData) { if (_cs.Lock()) { if (OkToFireEvents()) { SAFEARRAY * psaDataCopy = NULL; if (SUCCEEDED(DL(SafeArrayCopy)(*ppsaData, &psaDataCopy))) { PostMessage(_hWnd, WHREM_MSG_ON_RESPONSE_DATA_AVAILABLE, (WPARAM) psaDataCopy, 0); } // Note: ownership of psaDataCopy is transferred to the // message window, so the array is not freed here. } _cs.Unlock(); } } void STDMETHODCALLTYPE CWinHttpRequestEventsMarshaller::OnResponseFinished(void) { if (_cs.Lock()) { if (OkToFireEvents()) { PostMessage(_hWnd, WHREM_MSG_ON_RESPONSE_FINISHED, 0, 0); } _cs.Unlock(); } } void STDMETHODCALLTYPE CWinHttpRequestEventsMarshaller::OnError(long ErrorNumber, BSTR ErrorDescription) { if (_cs.Lock()) { if (OkToFireEvents()) { BSTR bstrErrorDescriptionCopy; bstrErrorDescriptionCopy = DL(SysAllocString)(ErrorDescription); PostMessage(_hWnd, WHREM_MSG_ON_ERROR, (WPARAM) ErrorNumber, (LPARAM) bstrErrorDescriptionCopy); // Note: ownership of bstrErrorDescriptionCopy is transferred to // the message window, so the string is not freed here. } _cs.Unlock(); } } BOOL RegisterWinHttpEventMarshallerWndClass() { if (s_fWndClassRegistered) return TRUE; // only one thread should be here if (!GeneralInitCritSec.Lock()) return FALSE; if (s_fWndClassRegistered == FALSE) { WNDCLASS wndclass; wndclass.style = 0; wndclass.lpfnWndProc = &CWinHttpRequestEventsMarshaller::WndProc; wndclass.cbClsExtra = 0; wndclass.cbWndExtra = 0; wndclass.hInstance = GlobalDllHandle; wndclass.hIcon = NULL; wndclass.hCursor = NULL;; wndclass.hbrBackground = (HBRUSH)NULL; wndclass.lpszMenuName = NULL; wndclass.lpszClassName = s_szWinHttpEventMarshallerWndClass; // Register the window class if (RegisterClass(&wndclass)) { s_fWndClassRegistered = TRUE; } } GeneralInitCritSec.Unlock(); return s_fWndClassRegistered; } void CleanupWinHttpRequestGlobals() { if (s_fWndClassRegistered) { // Register the window class if (UnregisterClass(s_szWinHttpEventMarshallerWndClass, GlobalDllHandle)) { s_fWndClassRegistered = FALSE; } } if (g_pMimeInfoCache) { delete g_pMimeInfoCache; g_pMimeInfoCache = NULL; } } static BOOL IsValidVariant(VARIANT v) { BOOL fOk = TRUE; if (V_ISBYREF(&v)) { if (IsBadReadPtr(v.pvarVal, sizeof(VARIANT))) { fOk = FALSE; goto Exit; } else v = *(v.pvarVal); } switch (v.vt) { case VT_BSTR: fOk = IsValidBstr(v.bstrVal); break; case (VT_BYREF | VT_BSTR): fOk = !IsBadReadPtr(v.pbstrVal, sizeof(BSTR)); break; case (VT_BYREF | VT_VARIANT): fOk = !IsBadReadPtr(v.pvarVal, sizeof(VARIANT)) && IsValidVariant(*(v.pvarVal)); break; case VT_UNKNOWN: case VT_DISPATCH: fOk = !IsBadReadPtr(v.punkVal, sizeof(void *)); break; } Exit: return fOk; } static HRESULT SecureFailureFromStatus(DWORD dwFlags) { DWORD error; if (dwFlags & WINHTTP_CALLBACK_STATUS_FLAG_CERT_REV_FAILED) { error = ERROR_WINHTTP_SECURE_CERT_REV_FAILED; } else if (dwFlags & WINHTTP_CALLBACK_STATUS_FLAG_CERT_WRONG_USAGE) { error = ERROR_WINHTTP_SECURE_CERT_WRONG_USAGE; } else if (dwFlags & WINHTTP_CALLBACK_STATUS_FLAG_INVALID_CERT) { error = ERROR_WINHTTP_SECURE_INVALID_CERT; } else if (dwFlags & WINHTTP_CALLBACK_STATUS_FLAG_CERT_REVOKED) { error = ERROR_WINHTTP_SECURE_CERT_REVOKED; } else if (dwFlags & WINHTTP_CALLBACK_STATUS_FLAG_INVALID_CA) { error = ERROR_WINHTTP_SECURE_INVALID_CA; } else if (dwFlags & WINHTTP_CALLBACK_STATUS_FLAG_CERT_CN_INVALID) { error = ERROR_WINHTTP_SECURE_CERT_CN_INVALID; } else if (dwFlags & WINHTTP_CALLBACK_STATUS_FLAG_CERT_DATE_INVALID) { error = ERROR_WINHTTP_SECURE_CERT_DATE_INVALID; } else if (dwFlags & WINHTTP_CALLBACK_STATUS_FLAG_SECURITY_CHANNEL_ERROR) { error = ERROR_WINHTTP_SECURE_CHANNEL_ERROR; } else { error = ERROR_WINHTTP_SECURE_FAILURE; } return HRESULT_FROM_WIN32(error); }
25.511975
148
0.535812
npocmaka
2118ad4c107117fafa59610627f5627cff57c214
1,409
hpp
C++
include/Nazara/VulkanRenderer/Wrapper/Semaphore.hpp
jayrulez/NazaraEngine
e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
11
2019-11-27T00:40:43.000Z
2020-01-29T14:31:52.000Z
include/Nazara/VulkanRenderer/Wrapper/Semaphore.hpp
jayrulez/NazaraEngine
e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
7
2019-11-27T00:29:08.000Z
2020-01-08T18:53:39.000Z
include/Nazara/VulkanRenderer/Wrapper/Semaphore.hpp
jayrulez/NazaraEngine
e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
7
2019-11-27T10:27:40.000Z
2020-01-15T17:43:33.000Z
// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com) // This file is part of the "Nazara Engine - Vulkan renderer" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_VULKANRENDERER_WRAPPER_SEMAPHORE_HPP #define NAZARA_VULKANRENDERER_WRAPPER_SEMAPHORE_HPP #include <Nazara/Prerequisites.hpp> #include <Nazara/VulkanRenderer/Wrapper/DeviceObject.hpp> namespace Nz { namespace Vk { class Semaphore : public DeviceObject<Semaphore, VkSemaphore, VkSemaphoreCreateInfo, VK_OBJECT_TYPE_SEMAPHORE> { friend DeviceObject; public: Semaphore() = default; Semaphore(const Semaphore&) = delete; Semaphore(Semaphore&&) = default; ~Semaphore() = default; using DeviceObject::Create; inline bool Create(Device& device, VkSemaphoreCreateFlags flags = 0, const VkAllocationCallbacks* allocator = nullptr); Semaphore& operator=(const Semaphore&) = delete; Semaphore& operator=(Semaphore&&) = delete; private: static inline VkResult CreateHelper(Device& device, const VkSemaphoreCreateInfo* createInfo, const VkAllocationCallbacks* allocator, VkSemaphore* handle); static inline void DestroyHelper(Device& device, VkSemaphore handle, const VkAllocationCallbacks* allocator); }; } } #include <Nazara/VulkanRenderer/Wrapper/Semaphore.inl> #endif // NAZARA_VULKANRENDERER_WRAPPER_SEMAPHORE_HPP
32.767442
158
0.771469
jayrulez
2118d9f3e23256b269fc4834c33f50650dc05636
5,646
cc
C++
deps/autodock/bestpdb.cc
neonious/Neonious-Node
2859e60ca3f1303127d589d0f50c2aa2b281bc95
[ "MIT" ]
null
null
null
deps/autodock/bestpdb.cc
neonious/Neonious-Node
2859e60ca3f1303127d589d0f50c2aa2b281bc95
[ "MIT" ]
null
null
null
deps/autodock/bestpdb.cc
neonious/Neonious-Node
2859e60ca3f1303127d589d0f50c2aa2b281bc95
[ "MIT" ]
null
null
null
/* $Id: bestpdb.cc,v 1.11 2014/06/12 01:44:07 mp Exp $ AutoDock Copyright (C) 2009 The Scripps Research Institute. All rights reserved. AutoDock is a Trade Mark of The Scripps Research Institute. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif /* bestpdb.cc */ #include <stdio.h> #include <string.h> #include "constants.h" #include "print_rem.h" #include "strindex.h" #include "print_avsfld.h" #include "bestpdb.h" extern int keepresnum; extern char dock_param_fn[]; void bestpdb( const int ncluster, const int num_in_clu[MAX_RUNS], const int cluster[MAX_RUNS][MAX_RUNS], const Real econf[MAX_RUNS], const Real crd[MAX_RUNS][MAX_ATOMS][SPACE], const char atomstuff[MAX_ATOMS][MAX_CHARS], const int natom, const Boole B_write_all_clusmem, const Real ref_rms[MAX_RUNS], const int outlev, FILE *const logFile) { register int i=0, j=0, k=0, confnum=0; int c = 0, kmax = 0, /* imol = 0, */ indpf = 0, off[7], nframes = 0, stride = 0, c1 = 1, i1 = 1; char filnm[PATH_MAX], label[MAX_CHARS]; char AtmNamResNamNumInsCode[20]; /* PDB record 0-origin indices 11-29 (from blank after serial_number to just before xcrd */ pr( logFile, "\n\tLOWEST ENERGY DOCKED CONFORMATION from EACH CLUSTER"); pr( logFile, "\n\t___________________________________________________\n\n\n" ); if (keepresnum > 0 ) { pr( logFile, "\nKeeping original residue number (specified in the input PDBQ file) for outputting.\n\n"); } else { pr( logFile, "\nResidue number will be the conformation's rank.\n\n"); } for (i = 0; i < ncluster; i++) { i1 = i + 1; if (B_write_all_clusmem) { kmax = num_in_clu[i]; } else { kmax = 1; /* write lowest-energy only */ } for ( k = 0; k < kmax; k++ ) { c = cluster[i][k]; c1 = c + 1; fprintf( logFile, "USER DPF = %s\n", dock_param_fn); fprintf( logFile, "USER Conformation Number = %d\n", ++confnum); print_rem(logFile, i1, num_in_clu[i], c1, ref_rms[c]); if (keepresnum > 0) { fprintf( logFile, "USER x y z Rank Run Energy RMS\n"); for (j = 0; j < natom; j++) { sprintf(AtmNamResNamNumInsCode, "%-19.19s", &atomstuff[j][11]); // retain original residue number (in fact, all fields // from blank after atom serial number to start of coords) // replace occupancy by cluster index, // tempfactor by conformation index within cluster, // add two non-standard fields with energy and RMSD from reference #define FORMAT_PDBQT_ATOM_RANKRUN_STR "ATOM %5d%-19.19s%8.3f%8.3f%8.3f%6d%6d %+6.2f %8.3f\n" fprintf(logFile, FORMAT_PDBQT_ATOM_RANKRUN_STR, j+1, AtmNamResNamNumInsCode, crd[c][j][X], crd[c][j][Y], crd[c][j][Z], i1, c1, econf[c], ref_rms[c] ); } /* j */ } else { fprintf( logFile, "USER Rank x y z Run Energy RMS\n"); for (j = 0; j < natom; j++) { sprintf(AtmNamResNamNumInsCode, "%-11.11s%4d%-4.4s", &atomstuff[j][11], i1, &atomstuff[j][26]); // replace original residue number by cluster index // replace occupancy by conformation index within cluster // tempfactor by energy // add one non-standard field with RMSD from reference #define FORMAT_PDBQT_ATOM_RANKRUN_NUM "ATOM %5d%-19.19s%8.3f%8.3f%8.3f%6d%+6.2f %6.3f\n" fprintf(logFile, FORMAT_PDBQT_ATOM_RANKRUN_NUM, j+1, AtmNamResNamNumInsCode, crd[c][j][X], crd[c][j][Y], crd[c][j][Z], c1, econf[c], ref_rms[c] ); } /* j */ } fprintf( logFile, "TER\n" ); fprintf( logFile, "ENDMDL\n" ); fflush( logFile ); nframes++; } /* for k */ } /* for i */ fprintf( logFile, "\n" ); strcpy(label, "x y z Rank Run Energy RMS\0" ); if (keepresnum > 0) { off[0]=5; off[1]=6; off[2]=7; off[3]=8; off[4]=9; off[5]=10; off[6]=11; stride=12; } else { off[0]=5; off[1]=6; off[2]=7; off[3]=4; off[4]=8; off[5]=9; off[6]=10; stride=11; } /* if */ indpf = strindex( dock_param_fn, ".dpf" ); strncpy( filnm, dock_param_fn, (size_t)indpf ); filnm[ indpf ] = '\0'; strcat( filnm, ".dlg.pdb\0" ); print_avsfld( logFile, 7, natom, nframes, off, stride, label, filnm ); } /* EOF */
34.851852
128
0.559511
neonious
211b8423298a8334dde179387b9288bb7e847119
68,192
cpp
C++
source/game/guis/UserInterfaceLocal.cpp
JasonHutton/QWTA
7f42dc70eb230cf69a8048fc98d647a486e752f1
[ "MIT" ]
2
2021-05-02T18:37:48.000Z
2021-07-18T16:18:14.000Z
source/game/guis/UserInterfaceLocal.cpp
JasonHutton/QWTA
7f42dc70eb230cf69a8048fc98d647a486e752f1
[ "MIT" ]
null
null
null
source/game/guis/UserInterfaceLocal.cpp
JasonHutton/QWTA
7f42dc70eb230cf69a8048fc98d647a486e752f1
[ "MIT" ]
null
null
null
// Copyright (C) 2007 Id Software, Inc. // #include "../precompiled.h" #pragma hdrstop #if defined( _DEBUG ) && !defined( ID_REDIRECT_NEWDELETE ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #include "UserInterfaceLocal.h" #include "UserInterfaceExpressions.h" #include "UserInterfaceManagerLocal.h" #include "UIWindow.h" #include "../../sys/sys_local.h" using namespace sdProperties; idCVar sdUserInterfaceLocal::g_debugGUIEvents( "g_debugGUIEvents", "0", CVAR_GAME | CVAR_INTEGER, "Show the results of events" ); idCVar sdUserInterfaceLocal::g_debugGUI( "g_debugGUI", "0", CVAR_GAME | CVAR_INTEGER, "1 - Show GUI window outlines\n2 - Show GUI window names\n3 - Only show visible windows" ); idCVar sdUserInterfaceLocal::g_debugGUITextRect( "g_debugGUITextRect", "0", CVAR_GAME | CVAR_BOOL, "Show windows' text rectangle outlines" ); idCVar sdUserInterfaceLocal::g_debugGUITextScale( "g_debugGUITextScale", "24", CVAR_GAME | CVAR_FLOAT, "Size that the debug GUI info font is drawn in." ); idCVar sdUserInterfaceLocal::s_volumeMusic_dB( "s_volumeMusic_dB", "0", CVAR_GAME | CVAR_SOUND | CVAR_ARCHIVE | CVAR_FLOAT, "music volume in dB" ); #ifdef SD_PUBLIC_BETA_BUILD idCVar sdUserInterfaceLocal::g_skipIntro( "g_skipIntro", "1", CVAR_GAME | CVAR_BOOL | CVAR_ROM, "skip the opening intro movie" ); #else idCVar sdUserInterfaceLocal::g_skipIntro( "g_skipIntro", "0", CVAR_GAME | CVAR_BOOL | CVAR_ARCHIVE | CVAR_PROFILE, "skip the opening intro movie" ); #endif // Crosshair idCVar sdUserInterfaceLocal::gui_crosshairDef( "gui_crosshairDef", "crosshairs", CVAR_GAME | CVAR_ARCHIVE | CVAR_PROFILE, "name of def containing crosshair" ); idCVar sdUserInterfaceLocal::gui_crosshairKey( "gui_crosshairKey", "pin_01", CVAR_GAME | CVAR_ARCHIVE | CVAR_PROFILE, "name of crosshair key in def specified by gui_crosshairDef" ); idCVar sdUserInterfaceLocal::gui_crosshairAlpha( "gui_crosshairAlpha", "0.5", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of crosshair" ); idCVar sdUserInterfaceLocal::gui_crosshairSpreadAlpha( "gui_crosshairSpreadAlpha", "0.5", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of spread components" ); idCVar sdUserInterfaceLocal::gui_crosshairStatsAlpha( "gui_crosshairStatsAlpha", "0", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of health/ammo/reload components" ); idCVar sdUserInterfaceLocal::gui_crosshairGrenadeAlpha( "gui_crosshairGrenadeAlpha", "0.5", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of grenade timer components" ); idCVar sdUserInterfaceLocal::gui_crosshairSpreadScale( "gui_crosshairSpreadScale", "1", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "amount to scale the spread indicator movement" ); idCVar sdUserInterfaceLocal::gui_crosshairColor( "gui_crosshairColor", "1 1 1 1", CVAR_GAME | CVAR_ARCHIVE | CVAR_PROFILE, "RGB color tint for crosshair elements" ); // HUD idCVar sdUserInterfaceLocal::gui_chatAlpha( "gui_chatAlpha", "1", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of chat text" ); idCVar sdUserInterfaceLocal::gui_fireTeamAlpha( "gui_fireTeamAlpha", "1", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of fireteam list" ); idCVar sdUserInterfaceLocal::gui_commandMapAlpha( "gui_commandMapAlpha", "1", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of command map" ); idCVar sdUserInterfaceLocal::gui_objectiveListAlpha( "gui_objectiveListAlpha", "1", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of objective list" ); idCVar sdUserInterfaceLocal::gui_personalBestsAlpha( "gui_personalBestsAlpha", "1", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of personal bests display list" ); idCVar sdUserInterfaceLocal::gui_objectiveStatusAlpha( "gui_objectiveStatusAlpha", "1", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of objective status" ); idCVar sdUserInterfaceLocal::gui_obitAlpha( "gui_obitAlpha", "1", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of obituaries" ); idCVar sdUserInterfaceLocal::gui_voteAlpha( "gui_voteAlpha", "1", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of vote" ); idCVar sdUserInterfaceLocal::gui_tooltipAlpha( "gui_tooltipAlpha", "1", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of tooltips" ); idCVar sdUserInterfaceLocal::gui_vehicleAlpha( "gui_vehicleAlpha", "1", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of vehicle information" ); idCVar sdUserInterfaceLocal::gui_vehicleDirectionAlpha( "gui_vehicleDirectionAlpha", "0.5", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "alpha of vehicle direction indicators" ); idCVar sdUserInterfaceLocal::gui_showRespawnText( "gui_showRespawnText", "1", CVAR_GAME | CVAR_BOOL | CVAR_ARCHIVE | CVAR_PROFILE, "show text about respawning when in limbo or dead" ); idCVar sdUserInterfaceLocal::gui_tooltipDelay( "gui_tooltipDelay", "0.7", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "Delay in seconds before tooltips pop up." ); idCVar sdUserInterfaceLocal::gui_doubleClickTime( "gui_doubleClickTime", "0.2", CVAR_GAME | CVAR_FLOAT | CVAR_ARCHIVE | CVAR_PROFILE, "Delay in seconds between considering two mouse clicks a double-click" ); idStrList sdUserInterfaceLocal::parseStack; const int sdUserInterfaceLocal::TOOLTIP_MOVE_TOLERANCE = 2; idBlockAlloc< uiCachedMaterial_t, 64 > sdUserInterfaceLocal::materialCacheAllocator; const char* sdUserInterfaceLocal::partNames[ FP_MAX ] = { "tl", "t", "tr", "l", "r", "bl", "b", "br", "c", }; /* =============================================================================== sdPropertyBinder =============================================================================== */ /* ================ sdPropertyBinder::ClearPropertyExpression ================ */ void sdPropertyBinder::ClearPropertyExpression( int propertyKey, int propertyIndex ) { boundProperty_t& bp = indexedProperties[ propertyKey ]; int index = bp.second + propertyIndex; if ( !propertyExpressions[ index ] ) { return; } int count = sdProperties::CountForPropertyType( propertyExpressions[ index ]->GetType() ); int i; for ( i = 0; i < count; i++ ) { if ( !propertyExpressions[ index + i ] ) { continue; } propertyExpressions[ index + i ]->Detach(); propertyExpressions[ index + i ] = NULL; } } /* ================ sdPropertyBinder::Clear ================ */ void sdPropertyBinder::Clear( void ) { indexedProperties.Clear(); propertyExpressions.Clear(); } /* ================ sdPropertyBinder::IndexForProperty ================ */ int sdPropertyBinder::IndexForProperty( sdProperties::sdProperty* property ) { int i; for ( i = 0; i < indexedProperties.Num(); i++ ) { if ( indexedProperties[ i ].first == property ) { return i; } } boundProperty_t& bp = indexedProperties.Alloc(); bp.first = property; bp.second = propertyExpressions.Num(); int count = CountForPropertyType( property->GetValueType() ); if ( count == -1 ) { gameLocal.Error( "sdPropertyBinder::IndexForProperty Property has Invalid Field Count" ); } for ( i = 0; i < count; i++ ) { propertyExpressions.Append( NULL ); } return indexedProperties.Num() - 1; } /* ================ sdPropertyBinder::SetPropertyExpression ================ */ void sdPropertyBinder::SetPropertyExpression( int propertyKey, int propertyIndex, sdUIExpression* expression, sdUserInterfaceScope* scope ) { boundProperty_t& bp = indexedProperties[ propertyKey ]; int index = bp.second + propertyIndex; int count = sdProperties::CountForPropertyType( expression->GetType() ); int i; for ( i = 0; i < count; i++ ) { if ( propertyExpressions[ index + i ] ) { propertyExpressions[ index + i ]->Detach(); propertyExpressions[ index + i ] = NULL; } } propertyExpressions[ index ] = expression; propertyExpressions[ index ]->SetProperty( bp.first, propertyIndex, propertyKey, scope ); } /* =============================================================================== sdUserInterfaceState =============================================================================== */ /* ================ sdUserInterfaceState::~sdUserInterfaceState ================ */ sdUserInterfaceState::~sdUserInterfaceState( void ) { for ( int i = 0; i < expressions.Num(); i++ ) { expressions[ i ]->Free(); } expressions.Clear(); } /* ============ sdUserInterfaceState::GetName ============ */ const char* sdUserInterfaceState::GetName() const { return ui->GetName(); } /* ============ sdUserInterfaceState::GetSubScope ============ */ sdUserInterfaceScope* sdUserInterfaceState::GetSubScope( const char* name ) { if ( !idStr::Icmp( name, "module" ) ) { return ( ui->GetModule() != NULL ) ? ui->GetModule()->GetScope() : NULL; } if( !idStr::Icmp( name, "gui" ) ) { return this; } if( !idStr::Icmp( name, "timeline" ) ) { return ui->GetTimelineManager(); } sdUIObject* window = ui->GetWindow( name ); if ( window ) { return &window->GetScope(); } return NULL; } /* ================ sdUserInterfaceState::GetProperty ================ */ sdProperties::sdProperty* sdUserInterfaceState::GetProperty( const char* name ) { return properties.GetProperty( name, PT_INVALID, false ); } /* ============ sdUserInterfaceState::GetProperty ============ */ sdProperties::sdProperty* sdUserInterfaceState::GetProperty( const char* name, sdProperties::ePropertyType type ) { sdProperties::sdProperty* prop = properties.GetProperty( name, PT_INVALID, false ); if ( prop && prop->GetValueType() != type && type != PT_INVALID ) { gameLocal.Error( "sdUserInterfaceState::GetProperty: type mismatch for property '%s'", name ); } return prop; } /* ================ sdUserInterfaceState::SetPropertyExpression ================ */ void sdUserInterfaceState::SetPropertyExpression( int propertyKey, int propertyIndex, sdUIExpression* expression ) { boundProperties.SetPropertyExpression( propertyKey, propertyIndex, expression, this ); } /* ================ sdUserInterfaceState::ClearPropertyExpression ================ */ void sdUserInterfaceState::ClearPropertyExpression( int propertyKey, int propertyIndex ) { boundProperties.ClearPropertyExpression( propertyKey, propertyIndex ); } /* ================ sdUserInterfaceState::RunFunction ================ */ void sdUserInterfaceState::RunFunction( int expressionIndex ) { expressions[ expressionIndex ]->Evaluate(); } /* ================ sdUserInterfaceState::IndexForProperty ================ */ int sdUserInterfaceState::IndexForProperty( sdProperties::sdProperty* property ) { return boundProperties.IndexForProperty( property ); } /* ============ sdUserInterfaceState::GetEvent ============ */ sdUIEventHandle sdUserInterfaceState::GetEvent( const sdUIEventInfo& info ) const { return ui->GetEvent( info ); } /* ============ sdUserInterfaceState::AddEvent ============ */ void sdUserInterfaceState::AddEvent( const sdUIEventInfo& info, sdUIEventHandle scriptHandle ) { ui->AddEvent( info, scriptHandle ); } /* ============ sdUserInterfaceState::ClearExpressions ============ */ void sdUserInterfaceState::ClearExpressions() { for ( int i = 0; i < expressions.Num(); i++ ) { expressions[ i ]->Free(); } expressions.Clear(); } /* ============ sdUserInterfaceState::Clear ============ */ void sdUserInterfaceState::Clear() { properties.Clear(); transitionExpressions.Clear(); boundProperties.Clear(); } /* ============ sdUserInterfaceState::GetFunction ============ */ sdUIFunctionInstance* sdUserInterfaceState::GetFunction( const char* name ) { return ui->GetFunction( name ); } /* ============ sdUserInterfaceState::RunNamedFunction ============ */ bool sdUserInterfaceState::RunNamedFunction( const char* name, sdUIFunctionStack& stack ) { const sdUserInterfaceLocal::uiFunction_t* func = sdUserInterfaceLocal::FindFunction( name ); if ( !func ) { return false; } CALL_MEMBER_FN_PTR( ui, func->GetFunction() )( stack ); return true; } /* ============ sdUserInterfaceState::FindPropertyName ============ */ const char* sdUserInterfaceState::FindPropertyName( sdProperties::sdProperty* property, sdUserInterfaceScope*& scope ) { scope = this; const char* name = properties.NameForProperty( property ); if ( name != NULL ) { return name; } for ( int i = 0 ; i < ui->GetNumWindows(); i++ ) { sdUIObject* obj = ui->GetWindow( i ); name = obj->GetScope().FindPropertyName( property, scope ); if ( name != NULL ) { return name; } } return NULL; } /* ============ sdUserInterfaceState::GetEvaluator ============ */ sdUIEvaluatorTypeBase* sdUserInterfaceState::GetEvaluator( const char* name ) { return GetUI()->GetEvaluator( name ); } /* ============ sdUserInterfaceState::Update ============ */ void sdUserInterfaceState::Update( void ) { int i; for ( i = 0; i < transitionExpressions.Num(); ) { sdUIExpression* expression = transitionExpressions[ i ]; if ( !expression->UpdateValue() ) { transitionExpressions.RemoveIndex( i ); } else { i++; } } } /* ================ sdUserInterfaceState::AddTransition ================ */ void sdUserInterfaceState::AddTransition( sdUIExpression* expression ) { transitionExpressions.AddUnique( expression ); } /* ================ sdUserInterfaceState::RemoveTransition ================ */ void sdUserInterfaceState::RemoveTransition( sdUIExpression* expression ) { transitionExpressions.Remove( expression ); } /* ============ sdUserInterfaceState::OnSnapshotHitch ============ */ void sdUserInterfaceState::OnSnapshotHitch( int delta ) { for( int i = 0; i < transitionExpressions.Num(); i++ ) { transitionExpressions[ i ]->OnSnapshotHitch( delta ); } } /* =============================================================================== sdUserInterfaceLocal =============================================================================== */ idHashMap< sdUserInterfaceLocal::uiFunction_t* > sdUserInterfaceLocal::uiFunctions; idList< sdUIEvaluatorTypeBase* > sdUserInterfaceLocal::uiEvaluators; SD_UI_PUSH_CLASS_TAG( sdUserInterfaceLocal ) const char* sdUserInterfaceLocal::eventNames[ GE_NUM_EVENTS ] = { SD_UI_EVENT_TAG( "onCreate", "", "Called on window creation" ), SD_UI_EVENT_TAG( "onActivate", "", "This happens when the GUI is activated." ), SD_UI_EVENT_TAG( "onDeactivate", "", "This happens when the GUI is activated." ), SD_UI_EVENT_TAG( "onNamedEvent", "[Event ...]", "Called when one of the events specified occurs" ), SD_UI_EVENT_TAG( "onPropertyChanged", "[Property ...]", "Called when one of the properties specified occurs" ), SD_UI_EVENT_TAG( "onCVarChanged", "[CVar ...]", "Called when one of the CVars' value changes" ), SD_UI_EVENT_TAG( "onCancel", "", "Called when any key bound to the _menuCancel is pressed" ), SD_UI_EVENT_TAG( "onCancel", "", "Called when any key bound to the _menuCancel is pressed" ), SD_UI_EVENT_TAG( "onToolTipEvent", "", "Called when a tooltip event occurs" ), }; SD_UI_POP_CLASS_TAG /* ================ sdUserInterfaceLocal::sdUserInterfaceLocal ================ */ sdUserInterfaceLocal::sdUserInterfaceLocal( int _spawnId, bool _isUnique, bool _isPermanent, sdHudModule* _module ) : spawnId( _spawnId ), desktop( NULL ), focusedWindow( NULL ), entity( NULL ), guiTime( 0.0f ){ guiDecl = NULL; theme = NULL; module = _module; bindContext = NULL; shaderParms.SetNum( MAX_ENTITY_SHADER_PARMS - 4 ); for( int i = 0 ; i < shaderParms.Num(); i++ ) { shaderParms[ i ] = 0.0f; } flags.isActive = false; flags.isUnique = _isUnique; flags.isPermanent = _isPermanent; flags.shouldUpdate = true; currentTime = 0; scriptState.Init( this ); UI_ADD_STR_CALLBACK( cursorMaterialName, sdUserInterfaceLocal, OnCursorMaterialNameChanged ) UI_ADD_STR_CALLBACK( postProcessMaterialName,sdUserInterfaceLocal, OnPostProcessMaterialNameChanged ) UI_ADD_STR_CALLBACK( focusedWindowName, sdUserInterfaceLocal, OnFocusedWindowNameChanged ) UI_ADD_STR_CALLBACK( screenSaverName, sdUserInterfaceLocal, OnScreenSaverMaterialNameChanged ) UI_ADD_STR_CALLBACK( themeName, sdUserInterfaceLocal, OnThemeNameChanged ) UI_ADD_STR_CALLBACK( bindContextName, sdUserInterfaceLocal, OnBindContextChanged ) UI_ADD_VEC2_CALLBACK( screenDimensions, sdUserInterfaceLocal, OnScreenDimensionChanged ) postProcessMaterial = NULL; screenSaverMaterial = NULL; lastMouseMoveTime = 0; nextAllowToolTipTime = 0; generalStacks.SetGranularity( 1 ); } /* ============ sdUserInterfaceLocal::Init ============ */ void sdUserInterfaceLocal::Init() { scriptState.GetPropertyHandler().RegisterProperty( "cursorMaterial", cursorMaterialName ); scriptState.GetPropertyHandler().RegisterProperty( "cursorSize", cursorSize ); scriptState.GetPropertyHandler().RegisterProperty( "cursorColor", cursorColor ); scriptState.GetPropertyHandler().RegisterProperty( "cursorPos", cursorPos ); scriptState.GetPropertyHandler().RegisterProperty( "postProcessMaterial", postProcessMaterialName ); scriptState.GetPropertyHandler().RegisterProperty( "focusedWindow", focusedWindowName ); scriptState.GetPropertyHandler().RegisterProperty( "screenDimensions", screenDimensions ); scriptState.GetPropertyHandler().RegisterProperty( "screenCenter", screenCenter ); scriptState.GetPropertyHandler().RegisterProperty( "screenSaverName", screenSaverName ); scriptState.GetPropertyHandler().RegisterProperty( "time", guiTime ); scriptState.GetPropertyHandler().RegisterProperty( "theme", themeName ); scriptState.GetPropertyHandler().RegisterProperty( "bindContext", bindContextName ); scriptState.GetPropertyHandler().RegisterProperty( "flags", scriptFlags ); scriptState.GetPropertyHandler().RegisterProperty( "inputScale", inputScale ); scriptState.GetPropertyHandler().RegisterProperty( "blankWStr", blankWStr ); inputScale = 1.0f; cursorSize = idVec2( 32.0f, 32.0f ); cursorColor = GetColor( "system/cursor" ); screenSaverName = "system/screensaver"; cursorMaterialName = "system/cursor"; scriptFlags = GUI_INTERACTIVE | GUI_SCREENSAVER; screenDimensions = idVec2( SCREEN_WIDTH, SCREEN_HEIGHT ); screenDimensions .SetReadOnly( true ); screenCenter = idVec2( SCREEN_WIDTH * 0.5f, SCREEN_HEIGHT * 0.5f ); screenCenter .SetReadOnly( true ); guiTime.SetReadOnly( true ); blankWStr.SetReadOnly( true ); cursorPos = screenCenter; focusedWindow = NULL; focusedWindowName = ""; flags.ignoreLocalCursorUpdates = false; flags.shouldUpdate = true; toolTipWindow = NULL; toolTipSource = NULL; tooltipAnchor = vec2_origin; postProcessMaterialName = ""; themeName = "default"; generalStacks.Clear(); scriptStack.Clear(); colorStack.Clear(); colorStack.SetGranularity( 1 ); currentColor = colorWhite; } /* ================ sdUserInterfaceLocal::~sdUserInterfaceLocal ================ */ sdUserInterfaceLocal::~sdUserInterfaceLocal( void ) { parseStack.Clear(); Clear(); } /* ============ sdUserInterfaceLocal::PushTrace ============ */ void sdUserInterfaceLocal::PushTrace( const char* info ) { parseStack.Append( info ); } /* ============ sdUserInterfaceLocal::PopTrace ============ */ void sdUserInterfaceLocal::PopTrace() { if( parseStack.Num() == 0 ) { gameLocal.Warning( "sdUserInterfaceLocal::PopTrace: Stack underflow" ); return; } parseStack.RemoveIndex( parseStack.Num() - 1 ); } /* ============ sdUserInterfaceLocal::PrintStackTrace ============ */ void sdUserInterfaceLocal::PrintStackTrace() { if( parseStack.Num() == 0 ) { return; } gameLocal.Printf( "^3===============================================\n" ); for( int i = parseStack.Num() - 1; i >= 0; i-- ) { gameLocal.Printf( "%s\n", parseStack[ i ].c_str() ); } gameLocal.Printf( "^3===============================================\n" ); parseStack.Clear(); } /* ================ sdUserInterfaceLocal::Load ================ */ bool sdUserInterfaceLocal::Load( const char* name ) { if ( guiDecl ) { assert( false ); return false; } guiDecl = gameLocal.declGUIType[ name ]; if ( guiDecl == NULL ) { gameLocal.Warning( "sdUserInterfaceLocal::Load Invalid GUI '%s'", name ); return false; } Init(); PushTrace( va( "Loading %s", GetName() ) ); scriptStack.SetID( GetName() ); const sdDeclGUITheme* theme = gameLocal.declGUIThemeType.LocalFind( "default" ); declManager->AddDependency( GetDecl(), theme ); idTokenCache& tokenCache = declManager->GetGlobalTokenCache(); try { sdUIWindow::SetupProperties( scriptState.GetPropertyHandler(), guiDecl->GetProperties(), this, tokenCache ); int i; for ( i = 0; i < guiDecl->GetNumWindows(); i++ ) { const sdDeclGUIWindow* windowDecl = guiDecl->GetWindow( i ); PushTrace( windowDecl->GetName() ); sdUIObject* object = uiManager->CreateWindow( windowDecl->GetTypeName() ); if ( !object ) { gameLocal.Error( "sdUserInterfaceLocal::Load Invalid Window Type '%s'", windowDecl->GetTypeName() ); } object->CreateProperties( this, windowDecl, tokenCache ); object->CreateTimelines( this, windowDecl, tokenCache ); if( windows.Find( object->GetName() ) != windows.End() ) { gameLocal.Error( "Window named '%s' already exists", object->GetName() ); } windows.Set( object->GetName(), object ); PopTrace(); } CreateEvents( guiDecl, tokenCache ); assert( windows.Num() == guiDecl->GetNumWindows() ); for ( i = 0; i < guiDecl->GetNumWindows(); i++ ) { GetWindow( i )->InitEvents(); } for ( i = 0; i < guiDecl->GetNumWindows(); i++ ) { GetWindow( i )->CreateEvents( this, guiDecl->GetWindow( i ), tokenCache ); } for ( i = 0; i < guiDecl->GetNumWindows(); i++ ) { GetWindow( i )->CacheEvents(); } desktop = GetWindow( "desktop" )->Cast< sdUIWindow >(); if( desktop == NULL ) { gameLocal.Warning( "sdUserInterfaceLocal::Load: could not find 'desktop' in '%s'", name ); } toolTipWindow = GetWindow( "toolTip" )->Cast< sdUIWindow >(); // parent all the nested windows for ( i = 0; i < guiDecl->GetNumWindows(); i++ ) { const sdDeclGUIWindow* windowDecl = guiDecl->GetWindow( i ); const idStrList& children = windowDecl->GetChildren(); PushTrace( windowDecl->GetName() ); windowHash_t::Iterator parentIter = windows.Find( windowDecl->GetName() ); if( parentIter == windows.End() ) { gameLocal.Error( "sdUserInterfaceLocal::Could not find window '%s'", windowDecl->GetName() ); } for( int childIndex = 0; childIndex < children.Num(); childIndex++ ) { windowHash_t::Iterator iter = windows.Find( children[ childIndex ] ); if( iter == windows.End() ) { gameLocal.Error( "sdUserInterfaceLocal::Could not find window '%s'", children[ childIndex ].c_str() ); } iter->second->SetParent( parentIter->second ); } PopTrace(); } // run constructors now that everything is parented for ( i = 0; i < guiDecl->GetNumWindows(); i++ ) { GetWindow( i )->RunEvent( sdUIEventInfo( sdUIObject::OE_CREATE, 0 ) ); GetWindow( i )->OnCreate(); } } catch ( idException& exception ) { PrintStackTrace(); throw exception; } PopTrace(); return true; } /* ================ sdUserInterfaceLocal::Draw ================ */ void sdUserInterfaceLocal::Draw() { #ifdef _DEBUG if( guiDecl && guiDecl->GetBreakOnDraw() ) { assert( !"BREAK_ON_DRAW" ); } #endif // _DEBUG if ( !desktop ) { return; } deviceContext->SetRegisters( shaderParms.Begin() ); bool allowScreenSaver = TestGUIFlag( GUI_SCREENSAVER ) && !TestGUIFlag( GUI_FULLSCREEN ); if ( IsActive() || !allowScreenSaver ) { desktop->ApplyLayout(); desktop->Draw(); desktop->FinalDraw(); if ( TestGUIFlag( GUI_SHOWCURSOR ) ) { deviceContext->DrawMaterial( cursorPos.GetValue().x, cursorPos.GetValue().y, cursorSize.GetValue().x, cursorSize.GetValue().y, cursorMaterial, cursorColor ); } } else if ( screenSaverMaterial != NULL && allowScreenSaver ) { deviceContext->DrawMaterial( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, screenSaverMaterial, colorWhite ); } if( g_debugGUI.GetBool() ) { sdBounds2D rect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT ); deviceContext->SetColor( colorWhite ); deviceContext->SetFontSize( g_debugGUITextScale.GetFloat() ); deviceContext->DrawText( va( L"%hs", guiDecl->GetName() ), rect, DTF_CENTER | DTF_VCENTER | DTF_SINGLELINE ); } UpdateToolTip(); if ( postProcessMaterial != NULL ) { deviceContext->DrawMaterial( 0.0f, 0.0f, SCREEN_WIDTH, SCREEN_HEIGHT, postProcessMaterial, colorWhite ); } assert( colorStack.Num() == 0 ); } /* ============ sdUserInterfaceLocal::UpdateToolTip ============ */ void sdUserInterfaceLocal::UpdateToolTip() { if( TestGUIFlag( GUI_TOOLTIPS ) ) { if( toolTipWindow == NULL ) { gameLocal.Warning( "%s: could not find windowDef 'tooltip' for updating", GetName() ); ClearGUIFlag( GUI_TOOLTIPS ); return; } if( toolTipSource == NULL && GetCurrentTime() >= nextAllowToolTipTime ) { if( !keyInputManager->AnyKeysDown() ) { // try to spawn a new tool-tip if( toolTipSource = desktop->UpdateToolTip( cursorPos ) ) { tooltipAnchor = cursorPos; } else { nextAllowToolTipTime = GetCurrentTime() + SEC2MS( gui_tooltipDelay.GetFloat() ); } } } else if( toolTipSource != NULL ) { bool keepWindow = false; if( sdUIWindow* window = toolTipSource->Cast< sdUIWindow >() ) { // see if the cursor has moved outside of the tool-tip window sdBounds2D bounds( window->GetWorldRect() ); keepWindow = bounds.ContainsPoint( cursorPos ); } if( !keepWindow ) { toolTipSource = NULL; nextAllowToolTipTime = GetCurrentTime() + SEC2MS( gui_tooltipDelay.GetFloat() ); } } if( !toolTipSource ) { CancelToolTip(); return; } if( idMath::Fabs( cursorPos.GetValue().x - tooltipAnchor.x ) >= TOOLTIP_MOVE_TOLERANCE || idMath::Fabs( cursorPos.GetValue().y - tooltipAnchor.y ) >= TOOLTIP_MOVE_TOLERANCE ) { CancelToolTip(); nextAllowToolTipTime = GetCurrentTime() + SEC2MS( gui_tooltipDelay.GetFloat() ); return; } sdProperties::sdProperty* toolText = toolTipSource->GetScope().GetProperty( "toolTipText", PT_WSTRING ); sdProperties::sdProperty* active = toolTipWindow->GetScope().GetProperty( "active", PT_FLOAT ); sdProperties::sdProperty* tipText = toolTipWindow->GetScope().GetProperty( "tipText", PT_WSTRING ); sdProperties::sdProperty* rect = toolTipWindow->GetScope().GetProperty( "rect", PT_VEC4 ); if( toolText && tipText && active ) { *tipText->value.wstringValue = *toolText->value.wstringValue; *active->value.floatValue = 1.0f; } if( rect != NULL ) { idVec4 temp = *rect->value.vec4Value; temp.x = cursorPos.GetValue().x; temp.y = cursorPos.GetValue().y + cursorSize.GetValue().y * 0.5f; if( temp.x + temp.z >= screenDimensions.GetValue().x ) { temp.x -= temp.z; } if( temp.y + temp.w >= screenDimensions.GetValue().y ) { temp.y -= temp.w + cursorSize.GetValue().y * 0.5f;; } *rect->value.vec4Value = temp; } tooltipAnchor = cursorPos; nextAllowToolTipTime = 0; } } /* ============ sdUserInterfaceLocal::CancelToolTip ============ */ void sdUserInterfaceLocal::CancelToolTip() { if( !toolTipWindow ) { return; } sdProperties::sdProperty* active = toolTipWindow->GetScope().GetProperty( "active" ); if( active ) { *active->value.floatValue = 0.0f; } toolTipSource = NULL; } /* ================ sdUserInterfaceLocal::GetWindow ================ */ sdUIObject* sdUserInterfaceLocal::GetWindow( const char* name ) { windowHash_t::Iterator iter = windows.Find( name ); if( iter == windows.End() ) { return NULL; } return iter->second; } /* ================ sdUserInterfaceLocal::GetWindow ================ */ const sdUIObject* sdUserInterfaceLocal::GetWindow( const char* name ) const { windowHash_t::ConstIterator iter = windows.Find( name ); if( iter == windows.End() ) { return NULL; } return iter->second; } /* ============ sdUserInterfaceLocal::Clear ============ */ void sdUserInterfaceLocal::Clear() { scriptState.ClearExpressions(); // we must do this before we destroy any windows, since a window could be watching other windows' properties DisconnectGlobalCallbacks(); windowHash_t::Iterator iter = windows.Begin(); while( iter != windows.End() ) { iter->second->DisconnectGlobalCallbacks(); ++iter; } for( int i = 0; i < materialCache.Num(); i++ ) { uiMaterialCache_t::Iterator entry = materialCache.FindIndex( i ); entry->second->material.Clear(); materialCacheAllocator.Free( entry->second ); } materialCache.Clear(); timelineWindows.Clear(); windows.DeleteValues(); windows.Clear(); externalProperties.DeleteContents( true ); scriptState.Clear(); script.Clear(); scriptStack.Clear(); if( timelines.Get() != NULL ) { timelines->Clear(); } focusedWindow = NULL; desktop = NULL; guiDecl = NULL; toolTipSource = NULL; toolTipWindow = NULL; themeName = ""; focusedWindowName = ""; cursorMaterialName = ""; cursorSize = vec2_zero; cursorColor = vec4_zero; screenSaverName = ""; postProcessMaterialName = ""; } /* ============ sdUserInterfaceLocal::RegisterTimelineWindow ============ */ void sdUserInterfaceLocal::RegisterTimelineWindow( sdUIObject* window ) { timelineWindows.Alloc() = window; } idCVar sdUserInterfaceLocal::gui_invertMenuPitch( "gui_invertMenuPitch", "0", CVAR_BOOL | CVAR_ARCHIVE | CVAR_PROFILE, "invert mouse movement in in-game menus" ); /* ============ sdUserInterfaceLocal::PostEvent ============ */ bool sdUserInterfaceLocal::PostEvent( const sdSysEvent* event ) { if ( !desktop || !IsInteractive() ) { return false; } if ( event->IsControllerButtonEvent() || event->IsKeyEvent() ) { if ( bindContext != NULL ) { bool down; sdKeyCommand* cmd = keyInputManager->GetCommand( bindContext, *keyInputManager->GetKeyForEvent( *event, down ) ); if ( cmd != NULL ) { keyInputManager->ProcessUserCmdEvent( *event ); return true; } } } // save these off for the events if ( !flags.ignoreLocalCursorUpdates && event->IsMouseEvent() ) { idVec2 pos = cursorPos; idVec2 scaledDelta( event->GetXCoord(), event->GetYCoord() ); scaledDelta *= inputScale; if ( TestGUIFlag( GUI_FULLSCREEN ) ) { scaledDelta.x *= ( 1.0f / deviceContext->GetAspectRatioCorrection() ); } pos.x += scaledDelta.x; if ( TestGUIFlag( GUI_USE_MOUSE_PITCH ) && gui_invertMenuPitch.GetBool() ) { pos.y -= scaledDelta.y; } else { pos.y += scaledDelta.y; } pos.x = idMath::ClampFloat( 0.0f, screenDimensions.GetValue().x, pos.x ); pos.y = idMath::ClampFloat( 0.0f, screenDimensions.GetValue().y, pos.y ); cursorPos = pos; } bool retVal = false; if ( !TestGUIFlag( GUI_SHOWCURSOR ) && ( event->IsMouseEvent() || ( event->IsMouseButtonEvent() && event->GetMouseButton() >= M_MOUSE1 && event->GetMouseButton() <= M_MOUSE12 ) && !TestGUIFlag( GUI_NON_FOCUSED_MOUSE_EVENTS ) )) { retVal = false; } else { if ( event->IsMouseButtonEvent() && event->IsButtonDown() ) { if( focusedWindow ) { retVal |= focusedWindow->HandleFocus( event ); } if( !retVal ) { retVal |= desktop->HandleFocus( event ); } nextAllowToolTipTime = GetCurrentTime() + SEC2MS( gui_tooltipDelay.GetFloat() ); } if( ( ( event->IsMouseButtonEvent() || event->IsKeyEvent() ) && event->IsButtonDown() ) || event->IsGuiEvent() ) { CancelToolTip(); nextAllowToolTipTime = GetCurrentTime() + SEC2MS( gui_tooltipDelay.GetFloat() ); } if ( focusedWindow == NULL && focusedWindowName.GetValue().Length() ) { SetFocus( GetWindow( focusedWindowName.GetValue().c_str() )->Cast< sdUIWindow >() ); } if ( focusedWindow ) { bool focusedRetVal = focusedWindow->PostEvent( event ); retVal |= focusedRetVal; if( !focusedRetVal ) { // give immediate parents that capture key events a crack if( !retVal && event->IsKeyEvent() || event->IsGuiEvent() ) { sdUIObject* parent = focusedWindow->GetNode().GetParent(); while( parent != NULL && retVal == false ) { if( sdUIWindow* window = parent->Cast< sdUIWindow >() ) { if( window->TestFlag( sdUIWindow::WF_CAPTURE_KEYS ) ) { retVal |= parent->PostEvent( event ); } } parent = parent->GetNode().GetParent(); } } } } if( !retVal ) { retVal |= desktop->PostEvent( event ); } } // eat everything but the F-Keys if ( TestGUIFlag( GUI_CATCH_ALL_EVENTS ) ) { keyNum_t keyNum; if ( event->IsKeyEvent() ) { keyNum = event->GetKey(); } else { keyNum = K_INVALID; } if ( ( keyNum != K_INVALID && ( keyNum < K_F1 || keyNum > K_F15 ) ) || ( event->IsControllerButtonEvent() ) ) { retVal = true; } } if( TestGUIFlag( GUI_TOOLTIPS ) && event->IsMouseEvent() ) { lastMouseMoveTime = GetCurrentTime(); } return retVal; } /* ============ sdUserInterfaceLocal::Shutdown ============ */ void sdUserInterfaceLocal::Shutdown( void ) { uiFunctions.DeleteContents(); uiEvaluators.DeleteContents( true ); } /* ============ sdUserInterfaceLocal::FindFunction ============ */ sdUserInterfaceLocal::uiFunction_t* sdUserInterfaceLocal::FindFunction( const char* name ) { sdUserInterfaceLocal::uiFunction_t** ptr; return uiFunctions.Get( name, &ptr ) ? *ptr : NULL; } /* ============ sdUserInterfaceLocal::GetFunction ============ */ sdUIFunctionInstance* sdUserInterfaceLocal::GetFunction( const char* name ) { uiFunction_t* function = FindFunction( name ); if ( function == NULL ) { return NULL; } return new sdUITemplateFunctionInstance< sdUserInterfaceLocal, sdUITemplateFunctionInstance_Identifier >( this, function ); } /* ============ sdUserInterfaceLocal::GetEvaluator ============ */ sdUIEvaluatorTypeBase* sdUserInterfaceLocal::GetEvaluator( const char* name ) { int i; for ( i = 0; i < uiEvaluators.Num(); i++ ) { if ( !idStr::Cmp( uiEvaluators[ i ]->GetName(), name ) ) { return uiEvaluators[ i ]; } } return NULL; } /* ================ sdUserInterfaceLocal::CreateEvents ================ */ void sdUserInterfaceLocal::CreateEvents( const sdDeclGUI* guiDecl, idTokenCache& tokenCache ) { parseStack.Clear(); const idList< sdDeclGUIProperty* >& guiProperties = guiDecl->GetProperties(); events.Clear(); events.SetNumEvents( GE_NUM_EVENTS ); namedEvents.Clear(); sdUserInterfaceLocal::PushTrace( va( "sdUserInterfaceLocal::CreateEvents for gui '%s'", guiDecl->GetName() )); idList<unsigned short> constructorTokens; bool hasValues = sdDeclGUI::CreateConstructor( guiDecl->GetProperties(), constructorTokens, tokenCache ); if( hasValues ) { sdUserInterfaceLocal::PushTrace( "<constructor>" ); idLexer parser( sdDeclGUI::LEXER_FLAGS ); parser.LoadTokenStream( constructorTokens, tokenCache, "sdUserInterfaceLocal::CreateEvents" ); sdUIEventInfo constructionEvent( GE_CONSTRUCTOR, 0 ); GetScript().ParseEvent( &parser, constructionEvent, &scriptState ); RunEvent( constructionEvent ); sdUserInterfaceLocal::PopTrace(); } if( guiDecl->GetTimelines().GetNumTimelines() > 0 ) { timelines.Reset( new sdUITimelineManager( *this, scriptState, script )); timelines->CreateTimelines( guiDecl->GetTimelines(), guiDecl ); timelines->CreateProperties( guiDecl->GetTimelines(), guiDecl, tokenCache ); } const idList< sdDeclGUIEvent* >& guiEvents = guiDecl->GetEvents(); idList< sdUIEventInfo > eventList; for ( int i = 0; i < guiEvents.Num(); i++ ) { const sdDeclGUIEvent* eventInfo = guiEvents[ i ]; sdUserInterfaceLocal::PushTrace( tokenCache[ eventInfo->GetName() ] ); eventList.Clear(); EnumerateEvents( tokenCache[ eventInfo->GetName() ], eventInfo->GetFlags(), eventList, tokenCache ); for ( int j = 0; j < eventList.Num(); j++ ) { idLexer parser( sdDeclGUI::LEXER_FLAGS ); parser.LoadTokenStream( eventInfo->GetTokenIndices(), tokenCache, tokenCache[ eventInfo->GetName() ] ); GetScript().ParseEvent( &parser, eventList[ j ], &scriptState ); } sdUserInterfaceLocal::PopTrace(); } if( timelines.Get() != NULL ) { timelines->CreateEvents( guiDecl->GetTimelines(), guiDecl, tokenCache ); } RunEvent( sdUIEventInfo( GE_CREATE, 0 ) ); } /* ================ sdUserInterfaceLocal::EnumerateEvents ================ */ void sdUserInterfaceLocal::EnumerateEvents( const char* name, const idList<unsigned short>& flags, idList< sdUIEventInfo >& events, const idTokenCache& tokenCache ) { if ( !idStr::Icmp( name, "onActivate" ) ) { events.Append( sdUIEventInfo( GE_ACTIVATE, 0 ) ); return; } if ( !idStr::Icmp( name, "onDeactivate" ) ) { events.Append( sdUIEventInfo( GE_DEACTIVATE, 0 ) ); return; } if ( !idStr::Icmp( name, "onCancel" ) ) { events.Append( sdUIEventInfo( GE_CANCEL, 0 ) ); return; } if ( !idStr::Icmp( name, "onNamedEvent" ) ) { int i; for ( i = 0; i < flags.Num(); i++ ) { events.Append( sdUIEventInfo( GE_NAMED, NamedEventHandleForString( tokenCache[ flags[ i ] ] ) ) ); } return; } if( !idStr::Icmp( name, "onCVarChanged" ) ) { int i; for( i = 0; i < flags.Num(); i++ ) { const idToken& name = tokenCache[ flags[ i ] ]; idCVar* cvar = cvarSystem->Find( name.c_str() ); if( cvar == NULL ) { gameLocal.Error( "Event 'onCVarChanged' could not find cvar '%s'", name.c_str() ); return; } int eventHandle = NamedEventHandleForString( name.c_str() ); cvarCallback_t* callback = new cvarCallback_t( *this, *cvar, eventHandle ); cvarCallbacks.Append( callback ); events.Append( sdUIEventInfo( GE_CVARCHANGED, eventHandle ) ); } return; } if ( !idStr::Icmp( name, "onToolTipEvent" ) ) { events.Append( sdUIEventInfo( GE_TOOLTIPEVENT, 0 ) ); return; } if ( !idStr::Icmp( name, "onPropertyChanged" ) ) { int i; for ( i = 0; i < flags.Num(); i++ ) { const idToken& name = tokenCache[ flags[ i ] ]; // do a proper lookup, so windows can watch guis and vice-versa idLexer p( sdDeclGUI::LEXER_FLAGS ); p.LoadMemory( name, name.Length(), "onPropertyChanged event handler" ); sdUserInterfaceScope* propertyScope = gameLocal.GetUserInterfaceScope( GetState(), &p ); idToken token; p.ReadToken( &token ); sdProperty* prop = propertyScope->GetProperty( token ); if( !prop ) { gameLocal.Error( "sdUserInterfaceLocal::EnumerateEvents: event 'onPropertyChanged' could not find property '%s'", name.c_str() ); return; } int eventHandle = NamedEventHandleForString( name.c_str() ); int cbHandle = -1; switch( prop->GetValueType() ) { case PT_VEC4: cbHandle = prop->value.vec4Value->AddOnChangeHandler( sdFunctions::sdBindMem1< void, int, const idVec4&, const idVec4& >( &sdUserInterfaceLocal::OnVec4PropertyChanged, this , eventHandle ) ); break; case PT_VEC3: cbHandle = prop->value.vec3Value->AddOnChangeHandler( sdFunctions::sdBindMem1< void, int, const idVec3&, const idVec3& >( &sdUserInterfaceLocal::OnVec3PropertyChanged, this , eventHandle ) ); break; case PT_VEC2: cbHandle = prop->value.vec2Value->AddOnChangeHandler( sdFunctions::sdBindMem1< void, int, const idVec2&, const idVec2& >( &sdUserInterfaceLocal::OnVec2PropertyChanged, this , eventHandle ) ); break; case PT_INT: cbHandle = prop->value.intValue->AddOnChangeHandler( sdFunctions::sdBindMem1< void, int, const int, const int >( &sdUserInterfaceLocal::OnIntPropertyChanged, this , eventHandle ) ); break; case PT_FLOAT: cbHandle = prop->value.floatValue->AddOnChangeHandler( sdFunctions::sdBindMem1< void, int, const float, const float >( &sdUserInterfaceLocal::OnFloatPropertyChanged, this , eventHandle ) ); break; case PT_STRING: cbHandle = prop->value.stringValue->AddOnChangeHandler( sdFunctions::sdBindMem1< void, int, const idStr&, const idStr& >( &sdUserInterfaceLocal::OnStringPropertyChanged, this , eventHandle ) ); break; case PT_WSTRING: cbHandle = prop->value.wstringValue->AddOnChangeHandler( sdFunctions::sdBindMem1< void, int, const idWStr&, const idWStr& >( &sdUserInterfaceLocal::OnWStringPropertyChanged, this , eventHandle ) ); break; } toDisconnect.Append( callbackHandler_t( prop, cbHandle )); events.Append( sdUIEventInfo( GE_PROPCHANGED, eventHandle ) ); } return; } gameLocal.Error( "sdUserInterfaceLocal::EnumerateEvents: unknown event '%s'", name ); } /* ================ sdUserInterfaceLocal::Activate ================ */ void sdUserInterfaceLocal::Activate( void ) { if( !guiDecl ) { return; } if ( flags.isActive ) { return; } flags.isActive = true; CancelToolTip(); if ( NonGameGui() ) { SetCurrentTime( sys->Milliseconds() ); } else { SetCurrentTime( gameLocal.time + gameLocal.timeOffset ); } Update(); if( timelines.Get() != NULL ) { timelines->ResetAllTimelines(); } int i; for ( i = 0; i < windows.Num(); i++ ) { sdUIObject* object = windows.FindIndex( i )->second; if( sdUIWindow* window = object->Cast< sdUIWindow >() ) { window->OnActivate(); } } RunEvent( sdUIEventInfo( GE_ACTIVATE, 0 ) ); } /* ================ sdUserInterfaceLocal::Deactivate ================ */ void sdUserInterfaceLocal::Deactivate( bool forceDeactivate ) { if( !guiDecl ) { return; } if ( !flags.isActive || ( !forceDeactivate && !TestGUIFlag( GUI_SCREENSAVER ) )) { return; } flags.isActive = false; if( timelines.Get() != NULL ) { timelines->ClearAllTimelines(); } RunEvent( sdUIEventInfo( GE_DEACTIVATE, 0 ) ); } /* ================ sdUserInterfaceLocal::Update ================ */ void sdUserInterfaceLocal::Update( void ) { if ( !IsActive() ) { return; } guiTime.SetReadOnly( false ); guiTime = currentTime; guiTime.SetReadOnly( true ); screenDimensions.SetReadOnly( false ); screenCenter.SetReadOnly( false ); if ( TestGUIFlag( GUI_FULLSCREEN ) ) { float adjustedWidth = idMath::Ceil( SCREEN_WIDTH * ( 1.0f / deviceContext->GetAspectRatioCorrection() ) ); screenDimensions.SetIndex( 0, adjustedWidth ); } else { screenDimensions.SetIndex( 0, SCREEN_WIDTH ); } screenCenter.SetIndex( 0 , screenDimensions.GetValue().x / 2.0f ); screenCenter.SetReadOnly( true ); screenDimensions.SetReadOnly( true ); if ( timelines.Get() != NULL ) { timelines->Run( currentTime ); } for ( int i = 0; i < timelineWindows.Num(); i++ ) { sdUITimelineManager* manager = timelineWindows[ i ]->GetTimelineManager(); manager->Run( currentTime ); } scriptState.Update(); } /* ================ sdUserInterfaceLocal::AddEvent ================ */ void sdUserInterfaceLocal::AddEvent( const sdUIEventInfo& info, sdUIEventHandle scriptHandle ) { events.AddEvent( info, scriptHandle ); } /* ================ sdUserInterfaceLocal::GetEvent ================ */ sdUIEventHandle sdUserInterfaceLocal::GetEvent( const sdUIEventInfo& info ) const { return events.GetEvent( info ); } /* ============ sdUserInterfaceLocal::RunEvent ============ */ bool sdUserInterfaceLocal::RunEvent( const sdUIEventInfo& info ) { return GetScript().RunEventHandle( GetEvent( info ), &scriptState ); } /* ============ sdUserInterfaceLocal::SetFocus ============ */ void sdUserInterfaceLocal::SetFocus( sdUIWindow* focus ) { if( focusedWindow == focus ) { return; } if( focusedWindow ) { focusedWindow->OnLoseFocus(); } focusedWindow = focus; if( focusedWindow ) { focusedWindow->OnGainFocus(); } } /* ============ sdUserInterfaceLocal::OnCursorMaterialNameChanged ============ */ void sdUserInterfaceLocal::OnCursorMaterialNameChanged( const idStr& oldValue, const idStr& newValue ) { if( newValue.Length() ) { cursorMaterial = gameLocal.declMaterialType.LocalFind( GetMaterial( newValue )); if( cursorMaterial && cursorMaterial->GetSort() < SS_POST_PROCESS ) { if ( cursorMaterial->GetSort() != SS_GUI && cursorMaterial->GetSort() != SS_NEAREST ) { gameLocal.Warning( "sdUserInterfaceLocal::OnCursorMaterialNameChanged: material %s used in gui '%s' without proper sort", cursorMaterial->GetName(), GetName() ); } } } else { cursorMaterial = NULL; } } /* ============ sdUserInterfaceLocal::OnPostProcessMaterialNameChanged ============ */ void sdUserInterfaceLocal::OnPostProcessMaterialNameChanged( const idStr& oldValue, const idStr& newValue ) { if( newValue.Length() ) { postProcessMaterial = gameLocal.declMaterialType.LocalFind( GetMaterial( newValue )); } else { postProcessMaterial = NULL; } } /* ============ sdUserInterfaceLocal::OnFocusedWindowNameChanged ============ */ void sdUserInterfaceLocal::OnFocusedWindowNameChanged( const idStr& oldValue, const idStr& newValue ) { SetFocus( GetWindow( newValue )->Cast< sdUIWindow >() ); if( newValue.Length() && !focusedWindow ) { gameLocal.Warning( "sdUserInterfaceLocal::OnFocusedWindowNameChanged: '%s' could not find windowDef '%s' for focus", GetName(), newValue.c_str() ); } } /* ============ sdUserInterfaceLocal::OnOnScreenSaverMaterialNameChanged ============ */ void sdUserInterfaceLocal::OnScreenSaverMaterialNameChanged( const idStr& oldValue, const idStr& newValue ) { if( newValue.Length() ) { screenSaverMaterial = gameLocal.declMaterialType.LocalFind( GetMaterial( newValue )); } else { screenSaverMaterial = NULL; } } /* ============ sdUserInterfaceLocal::SetRenderCallback ============ */ void sdUserInterfaceLocal::SetRenderCallback( const char* objectName, uiRenderCallback_t callback, uiRenderCallbackType_t type ) { sdUIWindow* object = GetWindow( objectName )->Cast< sdUIWindow >(); if( object == NULL ) { gameLocal.Error( "sdUserInterfaceLocal::SetRenderCallback: could not find window '%s'", objectName ); } object->SetRenderCallback( callback, type ); } /* ============ sdUserInterfaceLocal::PostNamedEvent ============ */ bool sdUserInterfaceLocal::PostNamedEvent( const char* event, bool allowMissing ) { assert( event ); int index = namedEvents.FindIndex( event ); if( index == -1 ) { if( !allowMissing ) { gameLocal.Error( "sdUserInterfaceLocal::PostNamedEvent: could not find event '%s' in '%s'", event, guiDecl != NULL ? guiDecl->GetName() : "unknown GUI" ); } return false; } if( g_debugGUIEvents.GetBool() ) { gameLocal.Printf( "GUI '%s': named event '%s'\n", GetName(), event ); } return RunEvent( sdUIEventInfo( GE_NAMED, index ) ); } /* ============ sdUserInterfaceLocal::NamedEventHandleForString ============ */ int sdUserInterfaceLocal::NamedEventHandleForString( const char* name ) { int index = namedEvents.FindIndex( name ); if( index == -1 ) { index = namedEvents.Append( name ) ; } return index; } /* ============ sdUserInterfaceLocal::OnStringPropertyChanged ============ */ void sdUserInterfaceLocal::OnStringPropertyChanged( int event, const idStr& oldValue, const idStr& newValue ) { RunEvent( sdUIEventInfo( GE_PROPCHANGED, event ) ); } /* ============ sdUserInterfaceLocal::OnWStringPropertyChanged ============ */ void sdUserInterfaceLocal::OnWStringPropertyChanged( int event, const idWStr& oldValue, const idWStr& newValue ) { RunEvent( sdUIEventInfo( GE_PROPCHANGED, event ) ); } /* ============ sdUserInterfaceLocal::OnIntPropertyChanged ============ */ void sdUserInterfaceLocal::OnIntPropertyChanged( int event, const int oldValue, const int newValue ) { RunEvent( sdUIEventInfo( GE_PROPCHANGED, event ) ); } /* ============ sdUserInterfaceLocal::OnFloatPropertyChanged ============ */ void sdUserInterfaceLocal::OnFloatPropertyChanged( int event, const float oldValue, const float newValue ) { RunEvent( sdUIEventInfo( GE_PROPCHANGED, event ) ); } /* ============ sdUserInterfaceLocal::OnVec4PropertyChanged ============ */ void sdUserInterfaceLocal::OnVec4PropertyChanged( int event, const idVec4& oldValue, const idVec4& newValue ) { RunEvent( sdUIEventInfo( GE_PROPCHANGED, event ) ); } /* ============ sdUserInterfaceLocal::OnVec3PropertyChanged ============ */ void sdUserInterfaceLocal::OnVec3PropertyChanged( int event, const idVec3& oldValue, const idVec3& newValue ) { RunEvent( sdUIEventInfo( GE_PROPCHANGED, event ) ); } /* ============ sdUserInterfaceLocal::OnVec2PropertyChanged ============ */ void sdUserInterfaceLocal::OnVec2PropertyChanged( int event, const idVec2& oldValue, const idVec2& newValue ) { RunEvent( sdUIEventInfo( GE_PROPCHANGED, event ) ); } /* ============ sdUserInterfaceLocal::SetCursor ============ */ void sdUserInterfaceLocal::SetCursor( const int x, const int y ) { idVec2 pos( idMath::ClampInt( 0, SCREEN_WIDTH, x ), idMath::ClampInt( 0, SCREEN_HEIGHT, y ) ); cursorPos = pos; } /* ============ sdUserInterfaceLocal::SetTheme ============ */ void sdUserInterfaceLocal::SetTheme( const char* theme ) { const sdDeclGUITheme* newTheme = gameLocal.declGUIThemeType.LocalFind( theme, false ); if( !newTheme ) { newTheme = gameLocal.declGUIThemeType.LocalFind( "default", true ); } if( this->theme != newTheme ) { bool isActive = IsActive(); if ( isActive ) { Deactivate( true ); } this->theme = newTheme; if ( guiDecl != NULL ) { declManager->AddDependency( GetDecl(), newTheme ); // regenerate idStr name = guiDecl->GetName(); guiDecl = NULL; Clear(); Load( name ); } if ( isActive ) { Activate(); } } } /* ============ sdUserInterfaceLocal::GetMaterial ============ */ const char* sdUserInterfaceLocal::GetMaterial( const char* key ) const { if( key[ 0 ] == '\0' ) { return ""; } const char* out = GetDecl() ? GetDecl()->GetMaterials().GetString( key, "" ) : ""; if( out[ 0 ] == '\0' && GetTheme() ) { out = GetTheme()->GetMaterial( key ); } return out; } /* ============ sdUserInterfaceLocal::GetSound ============ */ const char* sdUserInterfaceLocal::GetSound( const char* key ) const { if( key[ 0 ] == '\0' ) { return ""; } if( idStr::Icmpn( key, "::", 2 ) == 0 ) { return key + 2; } const char* out = GetDecl() ? GetDecl()->GetSounds().GetString( key, "" ) : ""; if( out[ 0 ] == '\0' && GetTheme() ) { out = GetTheme()->GetSound( key ); } return out; } /* ============ sdUserInterfaceLocal::GetColor ============ */ idVec4 sdUserInterfaceLocal::GetColor( const char* key ) const { if( key[ 0 ] == '\0' ) { return colorWhite; } idVec4 out; if( !GetDecl() || !GetDecl()->GetColors().GetVec4( key, "1 1 1 1", out ) && GetTheme() ) { out = GetTheme()->GetColor( key ); } return out; } /* ============ sdUserInterfaceLocal::ApplyLatchedTheme ============ */ void sdUserInterfaceLocal::ApplyLatchedTheme() { if ( latchedTheme.Length() > 0 ) { SetTheme( latchedTheme ); latchedTheme.Clear(); } } /* ============ sdUserInterfaceLocal::OnThemeNameChanged ============ */ void sdUserInterfaceLocal::OnThemeNameChanged( const idStr& oldValue, const idStr& newValue ) { if( newValue.IsEmpty() ) { latchedTheme = "default"; } else { latchedTheme = newValue; } } /* ============ sdUserInterfaceLocal::OnBindContextChanged ============ */ void sdUserInterfaceLocal::OnBindContextChanged( const idStr& oldValue, const idStr& newValue ) { if ( newValue.IsEmpty() ) { bindContext = NULL; } else { bindContext = keyInputManager->AllocBindContext( newValue.c_str() ); } } /* ============ sdUserInterfaceLocal::OnScreenDimensionChanged ============ */ void sdUserInterfaceLocal::OnScreenDimensionChanged( const idVec2& oldValue, const idVec2& newValue ) { windowHash_t::Iterator iter = windows.Begin(); while( iter != windows.End() ) { if( sdUIWindow* window = iter->second->Cast< sdUIWindow >() ) { window->MakeLayoutDirty(); } ++iter; } } /* ============ sdUserInterfaceLocal::Translate ============ */ bool sdUserInterfaceLocal::Translate( const idKey& key, sdKeyCommand** cmd ) { if ( bindContext == NULL ) { return false; } *cmd = keyInputManager->GetCommand( bindContext, key ); return *cmd != NULL; } /* ============ sdUserInterfaceLocal::EndLevelLoad ============ */ void sdUserInterfaceLocal::EndLevelLoad() { uiMaterialCache_t::Iterator cacheIter= materialCache.Begin(); while( cacheIter != materialCache.End() ) { uiCachedMaterial_t& cached = *( cacheIter->second ); LookupPartSizes( cached.parts.Begin(), cached.parts.Num() ); SetupMaterialInfo( cached.material ); ++cacheIter; } windowHash_t::Iterator iter = windows.Begin(); while( iter != windows.End() ) { iter->second->EndLevelLoad(); ++iter; } } /* ============ sdUserInterfaceLocal::PopGeneralScriptVar ============ */ void sdUserInterfaceLocal::PopGeneralScriptVar( const char* stackName, idStr& str ) { if( stackName[ 0 ] == '\0' ) { gameLocal.Error( "sdUserInterfaceLocal::PopGeneralScriptVar: empty stack name" ); } stringStack_t& stack = generalStacks[ stackName ]; if( stack.Num() == 0 ) { gameLocal.Error( "sdUserInterfaceLocal::PopGeneralScriptVar: stack underflow for '%s'", stackName ); } int index = stack.Num() - 1; str = stack[ index ]; stack.SetNum( index ); } /* ============ sdUserInterfaceLocal::PushGeneralScriptVar ============ */ void sdUserInterfaceLocal::PushGeneralScriptVar( const char* stackName, const char* str ) { if( stackName[ 0 ] == '\0' ) { gameLocal.Error( "sdUserInterfaceLocal::PushGeneralScriptVar: empty stack name" ); } generalStacks[ stackName ].Append( str ); } /* ============ sdUserInterfaceLocal::GetGeneralScriptVar ============ */ void sdUserInterfaceLocal::GetGeneralScriptVar( const char* stackName, idStr& str ) { if( stackName[ 0 ] == '\0' ) { gameLocal.Error( "sdUserInterfaceLocal::GetGeneralScriptVar: empty stack name" ); } stringStack_t& stack = generalStacks[ stackName ]; if( stack.Num() == 0 ) { gameLocal.Error( "sdUserInterfaceLocal::GetGeneralScriptVar: stack underflow for '%s'", stackName ); } int index = stack.Num() - 1; str = stack[ index ]; } /* ============ sdUserInterfaceLocal::ClearGeneralStrings ============ */ void sdUserInterfaceLocal::ClearGeneralStrings( const char* stackName ) { if( stackName[ 0 ] == '\0' ) { gameLocal.Error( "sdUserInterfaceLocal::ClearGeneralStrings: empty stack name" ); } stringStack_t& stack = generalStacks[ stackName ]; stack.Clear(); } /* ============ sdUserInterfaceLocal::OnCVarChanged ============ */ void sdUserInterfaceLocal::OnCVarChanged( idCVar& cvar, int id ) { bool result = RunEvent( sdUIEventInfo( GE_CVARCHANGED, id ) ); if( result && sdUserInterfaceLocal::g_debugGUIEvents.GetInteger() ) { gameLocal.Printf( "%s: OnCVarChanged\n", GetName() ); } } /* ============ sdUserInterfaceLocal::OnInputInit ============ */ void sdUserInterfaceLocal::OnInputInit( void ) { if ( bindContextName.GetValue().IsEmpty() ) { bindContext = NULL; } else { bindContext = keyInputManager->AllocBindContext( bindContextName.GetValue().c_str() ); } } /* ============ sdUserInterfaceLocal::OnInputShutdown ============ */ void sdUserInterfaceLocal::OnInputShutdown( void ) { bindContext = NULL; } /* ============ sdUserInterfaceLocal::OnLanguageInit ============ */ void sdUserInterfaceLocal::OnLanguageInit( void ) { if ( desktop != NULL ) { desktop->OnLanguageInit(); sdUIObject::OnLanguageInit_r( desktop ); } } /* ============ sdUserInterfaceLocal::OnLanguageShutdown ============ */ void sdUserInterfaceLocal::OnLanguageShutdown( void ) { if ( desktop != NULL ) { desktop->OnLanguageShutdown(); sdUIObject::OnLanguageShutdown_r( desktop ); } } /* ============ sdUserInterfaceLocal::MakeLayoutDirty ============ */ void sdUserInterfaceLocal::MakeLayoutDirty() { if ( desktop != NULL ) { desktop->MakeLayoutDirty(); sdUIObject::MakeLayoutDirty_r( desktop ); } } /* ============ sdUserInterfaceLocal::SetCachedMaterial ============ */ uiMaterialCache_t::Iterator sdUserInterfaceLocal::SetCachedMaterial( const char* alias, const char* newMaterial, int& handle ) { uiMaterialCache_t::Iterator findResult = FindCachedMaterial( alias, handle ); if( findResult == materialCache.End() ) { uiMaterialCache_t::InsertResult result = materialCache.Set( alias, materialCacheAllocator.Alloc() ); findResult = result.first; } handle = findResult - materialCache.Begin(); uiCachedMaterial_t& cached = *( findResult->second ); idStr material; bool globalLookup = false; bool literal = false; int offset = ParseMaterial( newMaterial, material, globalLookup, literal, cached.drawMode ); if( cached.drawMode != BDM_SINGLE_MATERIAL && cached.drawMode != BDM_USE_ST ) { InitPartsForBaseMaterial( material, cached ); return findResult; } if( globalLookup ) { material = "::" + material; } if( literal ) { LookupMaterial( va( "literal: %hs", newMaterial + offset ), cached.material ); } else if( ( material.Length() && !globalLookup ) || ( material.Length() > 2 && globalLookup ) ) { LookupMaterial( material, cached.material ); } return findResult; } /* ============ sdUserInterfaceLocal::FindCachedMaterial ============ */ uiMaterialCache_t::Iterator sdUserInterfaceLocal::FindCachedMaterial( const char* alias, int& handle ) { uiMaterialCache_t::Iterator iter = materialCache.Find( alias ); if( iter == materialCache.End() ) { handle = -1; } else { handle = iter - materialCache.Begin(); } return iter; } /* ============ sdUserInterfaceLocal::FindCachedMaterialForHandle ============ */ uiMaterialCache_t::Iterator sdUserInterfaceLocal::FindCachedMaterialForHandle( int handle ) { if( handle < 0 || handle >= materialCache.Num() ) { return materialCache.End(); } return materialCache.Begin() + handle; } /* ============ sdUserInterfaceLocal::LookupPartSizes ============ */ void sdUserInterfaceLocal::LookupPartSizes( uiDrawPart_t* parts, int num ) { for ( int i= 0; i < num; i++ ) { uiDrawPart_t& part = parts[ i ]; if ( part.mi.material == NULL || ( part.width != 0 && part.height != 0 ) ) { continue; } if ( part.mi.material->GetNumStages() == 0 ) { part.mi.material = NULL; continue; } SetupMaterialInfo( part.mi, &part.width, &part.height ); if ( part.width == 0 || part.height == 0 ) { assert( 0 ); part.mi.material = NULL; } } } /* ============ sdUserInterfaceLocal::SetupMaterialInfo ============ */ void sdUserInterfaceLocal::SetupMaterialInfo( uiMaterialInfo_t& mi, int* baseWidth, int* baseHeight ) { if( mi.material == NULL ) { return; } if( const idImage* image = mi.material->GetEditorImage() ) { if( image->sourceWidth == 0 ) { // the image hasn't been loaded yet, so defer texture coordinate calculation mi.flags.lookupST = true; return; } } if( !mi.flags.lookupST ) { return; } if( const idImage* image = mi.material->GetEditorImage() ) { // if they're zeroed assume 0-1 range if( mi.st0.Compare( vec2_zero, idMath::FLT_EPSILON ) && mi.st1.Compare( vec2_zero, idMath::FLT_EPSILON ) ) { mi.st0.Set( 0.0f, 0.0f ); mi.st1.Set( 1.0f, 1.0f ); if( baseWidth != NULL ) { *baseWidth = image->sourceWidth; } if( baseHeight != NULL ) { *baseHeight = image->sourceHeight; } } else { if( baseWidth != NULL ) { *baseWidth = idMath::Ftoi( mi.st1.x ); } if( baseHeight != NULL ) { *baseHeight = idMath::Ftoi( mi.st1.y ); } mi.st0.x = mi.st0.x / static_cast< float >( image->sourceWidth ); mi.st0.y = mi.st0.y / static_cast< float >( image->sourceHeight ); mi.st1.x = mi.st0.x + ( mi.st1.x / static_cast< float >( image->sourceWidth ) ); mi.st1.y = mi.st0.y + ( mi.st1.y / static_cast< float >( image->sourceHeight ) ); } } if( mi.flags.flipX ) { idSwap( mi.st0.x, mi.st1.x ); } if( mi.flags.flipY ) { idSwap( mi.st0.y, mi.st1.y ); } mi.flags.lookupST = false; } /* ============ sdUserInterfaceLocal::ParseMaterial ============ */ int sdUserInterfaceLocal::ParseMaterial( const char* mat, idStr& outMaterial, bool& globalLookup, bool& literal, uiDrawMode_e& mode ) { idLexer src( mat, idStr::Length( mat ), "ParseMaterial", LEXFL_ALLOWPATHNAMES ); idToken token; outMaterial.Empty(); globalLookup = false; literal = false; mode = BDM_SINGLE_MATERIAL; int materialStart = 0; while( !src.HadError() ) { materialStart = src.GetFileOffset(); if( !src.ReadToken( &token )) { break; } if( token.Icmp( "literal:" ) == 0 ) { literal = true; continue; } if( token.Icmp( "_frame" ) == 0 ) { mode = BDM_FRAME; continue; } if( token.Icmp( "_st" ) == 0 ) { mode = BDM_USE_ST; continue; } if( token.Icmp( "_3v" ) == 0 ) { mode = BDM_TRI_PART_V; continue; } if( token.Icmp( "_3h" ) == 0 ) { mode = BDM_TRI_PART_H; continue; } if( token.Icmp( "_5h" ) == 0 ) { mode = BDM_FIVE_PART_H; continue; } if( token == "::" ) { globalLookup = true; continue; } outMaterial = token; break; } return materialStart; } /* ============ sdUserInterfaceLocal::InitPartsForBaseMaterial ============ */ void sdUserInterfaceLocal::InitPartsForBaseMaterial( const char* material, uiCachedMaterial_t& cached ) { cached.parts.SetNum( FP_MAX ); if( cached.drawMode == BDM_FIVE_PART_H ) { SetupPart( cached.parts[ FP_TOPLEFT ], partNames[ FP_TOPLEFT ], material ); SetupPart( cached.parts[ FP_LEFT ], partNames[ FP_LEFT ], material ); // stretched SetupPart( cached.parts[ FP_CENTER ], partNames[ FP_CENTER ], material ); SetupPart( cached.parts[ FP_RIGHT ], partNames[ FP_RIGHT ], material ); // stretched SetupPart( cached.parts[ FP_TOPRIGHT ], partNames[ FP_TOPRIGHT ], material ); return; } if( cached.drawMode == BDM_TRI_PART_H ) { SetupPart( cached.parts[ FP_LEFT ], partNames[ FP_LEFT ], material ); SetupPart( cached.parts[ FP_RIGHT ], partNames[ FP_RIGHT ], material ); SetupPart( cached.parts[ FP_CENTER ], partNames[ FP_CENTER ], material ); return; } if( cached.drawMode == BDM_TRI_PART_V ) { SetupPart( cached.parts[ FP_TOP ], partNames[ FP_TOP ], material ); SetupPart( cached.parts[ FP_BOTTOM ], partNames[ FP_BOTTOM ], material ); SetupPart( cached.parts[ FP_CENTER ], partNames[ FP_CENTER ], material ); return; } for( int i = 0; i < FP_MAX; i++ ) { SetupPart( cached.parts[ i ], partNames[ i ], material ); } } /* ============ sdUserInterfaceLocal::SetupPart ============ */ void sdUserInterfaceLocal::SetupPart( uiDrawPart_t& part, const char* partName, const char* material ) { if( idStr::Length( material ) == 0 ) { part.mi.material = NULL; part.width = 0; part.height = 0; return; } LookupMaterial( va( "%s_%s", material, partName ), part.mi, &part.width, &part.height ); if( part.mi.material->GetNumStages() == 0 ) { part.mi.material = NULL; part.width = 0; part.height = 0; return; } } /* ============ sdUserInterfaceLocal::LookupMaterial ============ */ void sdUserInterfaceLocal::LookupMaterial( const char* materialName, uiMaterialInfo_t& mi, int* baseWidth, int* baseHeight ) { mi.Clear(); bool globalLookup = false; static const char* LITERAL_ID = "literal:"; static const int LITERAL_ID_LENGTH = idStr::Length( LITERAL_ID ); bool literal = !idStr::Icmpn( LITERAL_ID, materialName, LITERAL_ID_LENGTH ); if( !literal ) { globalLookup = !idStr::Icmpn( "::", materialName, 2 ); if( globalLookup ) { materialName += 2; } } if( globalLookup ) { if(idStr::Length( materialName ) == 0 ) { mi.material = declHolder.FindMaterial( "_default" ); } else { mi.material = declHolder.FindMaterial( materialName ); } } else { const char* materialInfo = materialName; if( literal ) { materialInfo += LITERAL_ID_LENGTH; } else { materialInfo = GetMaterial( materialName ); } idToken token; char buffer[128]; token.SetStaticBuffer( buffer, sizeof(buffer) ); idLexer src( materialInfo, idStr::Length( materialInfo ), "LookupMaterial", LEXFL_ALLOWPATHNAMES ); src.ReadToken( &token ); // material name if( token.Length() == 0 ) { mi.material = declHolder.FindMaterial( "_default" ); } else { mi.material = declHolder.FindMaterial( token ); } while( src.ReadToken( &token )) { if( token == "," ) { continue; } if( token.Icmp( "flipX" ) == 0 ) { mi.flags.flipX = true; continue; } if( token.Icmp( "flipY" ) == 0 ) { mi.flags.flipY = true; continue; } static idVec4 vec; if( token.Icmp( "rect" ) == 0 ) { src.Parse1DMatrix( 4, vec.ToFloatPtr(), true ); mi.st0.x = vec.x; mi.st0.y = vec.y; mi.st1.x = vec.z; mi.st1.y = vec.w; continue; } src.Error( "Unknown token '%s'", token.c_str() ); break; } } if ( mi.material->GetSort() < SS_POST_PROCESS ) { if ( mi.material->GetSort() != SS_GUI && mi.material->GetSort() != SS_NEAREST ) { gameLocal.Warning( "LookupMaterial: '%s' material '%s' (alias '%s') used without proper sort", GetName(), mi.material->GetName(), materialName ); } } mi.flags.lookupST = true; SetupMaterialInfo( mi, baseWidth, baseHeight ); } /* ============ sdUserInterfaceLocal::PushColor ============ */ void sdUserInterfaceLocal::PushColor( const idVec4& color ) { currentColor = color; colorStack.Push( deviceContext->SetColorMultiplier( color ) ); } /* ============ sdUserInterfaceLocal::PopColor ============ */ idVec4 sdUserInterfaceLocal::PopColor() { idVec4 c = colorStack.Top(); deviceContext->SetColorMultiplier( c ); colorStack.Pop(); currentColor = c; return c; } /* ============ sdUserInterfaceLocal::TopColor ============ */ const idVec4& sdUserInterfaceLocal::TopColor() const{ return currentColor; } /* ============ sdUserInterfaceLocal::OnSnapshotHitch ============ */ void sdUserInterfaceLocal::OnSnapshotHitch( int delta ) { scriptState.OnSnapshotHitch( delta ); if( timelines.IsValid() ) { timelines->OnSnapshotHitch( delta ); } } /* ============ sdUserInterfaceLocal::OnToolTipEvent ============ */ void sdUserInterfaceLocal::OnToolTipEvent( const char* arg ) { sdUIEventInfo event( GE_TOOLTIPEVENT, 0 ); if ( event.eventType.IsValid() ) { PushScriptVar( arg ); RunEvent( sdUIEventInfo( GE_TOOLTIPEVENT, 0 ) ); ClearScriptStack(); } }
28.907164
208
0.64534
JasonHutton
211beb59677d3c88fe37fd2d46ea5ced20f24cd1
7,492
cpp
C++
source/Structure/custom_plugins/plugins/HIL_server/server.cpp
Guiraffo/ProVANT_Simulator
ef2260204b13f39a9f83ad2ab88a9552a0699bff
[ "MIT" ]
null
null
null
source/Structure/custom_plugins/plugins/HIL_server/server.cpp
Guiraffo/ProVANT_Simulator
ef2260204b13f39a9f83ad2ab88a9552a0699bff
[ "MIT" ]
null
null
null
source/Structure/custom_plugins/plugins/HIL_server/server.cpp
Guiraffo/ProVANT_Simulator
ef2260204b13f39a9f83ad2ab88a9552a0699bff
[ "MIT" ]
null
null
null
#include "server.h" #include <time.h> #include "XMLRead.h" namespace gazebo { HilServer::HilServer() { Fr = 0; Fl = 0; Tr = 0; Tl = 0; } HilServer::~HilServer() { try { } catch (std::exception& e) { std::cout << e.what() << std::endl; } } void HilServer::Update() { // static int i = 0; // mutex.lock(); std::lock_guard<std::mutex> lck(mtx); SetInputVANT20(Fr, Fl, Tr, Tl); // std::cout << "Fr: " << Fr << std::endl; // std::cout << "Fl: " << Fl << std::endl; // std::cout << "Tr: " << Tr << std::endl; // std::cout << "Tl: " << Tl << std::endl; // mutex.unlock(); // i++; // std::cout << "Contador: " << i << std::endl; } void HilServer::thread() { struct timespec start, stop; std::chrono::high_resolution_clock::time_point tf; std::chrono::high_resolution_clock::time_point tf2; std::chrono::high_resolution_clock::time_point to; std::chrono::high_resolution_clock::time_point to2; // clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start); to = std::chrono::high_resolution_clock::now(); to2 = to; while (true) { Frame frame; frame = receive(serial); if (frame.unbuild()) { float flag = frame.getFloat(); if (flag == 1) // Envia os estados { // std::cout << "1" << std::endl; // clock_gettime(CLOCK_REALTIME, &stop); /*double result = (stop.tv_sec - start.tv_sec) * 1e3 + (stop.tv_nsec - start.tv_nsec) / 1e6; // in microseconds std::cout << result << std::endl; clock_gettime(CLOCK_REALTIME, &start);*/ // depois tf = std::chrono::high_resolution_clock::now(); std::chrono::duration<double, std::nano> delta_t = tf - to; std::chrono::duration<double, std::nano> delta_t2 = tf - to2; // std::chrono::duration<double,std::ratio<1l,1000000l>> delta_t = // std::chrono::duration_cast<std::chrono::miliseconds>(tf - to); std::cout << delta_t.count() / 1000000.0 << "," << delta_t2.count() / 1000000000.0 << ","; // std::cout << model->GetWorld()->GetRealTime().FormattedString() << ","; // antes to = tf; GetStatesVANT20(); SetSerialData(); } else { if (flag == 0) // se 0 { // std::cout << "0" << std::endl; // mutex.lock(); std::lock_guard<std::mutex> lck(mtx); Fr = frame.getFloat(); Fl = frame.getFloat(); Tr = frame.getFloat(); Tl = frame.getFloat(); std::cout << Fr << ","; std::cout << Fl << ","; std::cout << Tr << ","; std::cout << Tl << std::endl; // mutex.unlock(); } else { if (flag == 3) // Updates the control inputs { std::lock_guard<std::mutex> lck(mtx); Fr = frame.getFloat(); Fl = frame.getFloat(); Tr = frame.getFloat(); Tl = frame.getFloat(); // Frame frame2; // frame2.addFloat(3); // frame2.build(); // serial.send(frame2.buffer(),frame2.buffer_size()); model->GetWorld()->SetPaused(false); } else { std::cout << "Deu ruim" << std::endl; } } } } } } void HilServer::Load(physics::ModelPtr _model, sdf::ElementPtr _sdf) { try { model = _model; // std::cout << "Load" << std::endl; // conectando comunicação serial // if (!serial.connect("/tmp/ttyS1",115200)) exit(1); if (serial.connect("/dev/ttyUSB0", 921600 /*576000*/)) { // obtendo dados do arquivo de descrição "model.sdf" NameOfJointR_ = XMLRead::ReadXMLString("NameOfJointR", _sdf); NameOfJointL_ = XMLRead::ReadXMLString("NameOfJointL", _sdf); link_name_ = XMLRead::ReadXMLString("bodyName", _sdf); link_right_ = XMLRead::ReadXMLString("BrushlessR", _sdf); link_left_ = XMLRead::ReadXMLString("BrushlessL", _sdf); // apontando ponteiros para acesso a dados do mundo, elo e juntas world = _model->GetWorld(); link = _model->GetLink(link_name_); linkR = _model->GetLink(link_right_); linkL = _model->GetLink(link_left_); juntaR = _model->GetJoint(NameOfJointR_); juntaL = _model->GetJoint(NameOfJointL_); // Iniciando comunicação serial t = new boost::thread(boost::bind(&gazebo::HilServer::thread, this)); // configurando temporizador para callback updateConnection = event::Events::ConnectWorldUpdateBegin([this](const common::UpdateInfo& info) { (void)info; // Supress unused variable warning this->Update(); }); } } catch (std::exception& e) { std::cout << e.what() << std::endl; } } void HilServer::Reset() { } // Método para enviar dados para o sistema embarcado void HilServer::SetSerialData() { Frame frame; frame.addFloat(x); frame.addFloat(y); frame.addFloat(z); frame.addFloat(roll); frame.addFloat(pitch); frame.addFloat(yaw); frame.addFloat(alphar); frame.addFloat(alphal); frame.addFloat(vx); frame.addFloat(vy); frame.addFloat(vz); frame.addFloat(wx); frame.addFloat(wy); frame.addFloat(wz); frame.addFloat(dalphar); frame.addFloat(dalphal); frame.build(); serial.send(frame.buffer(), frame.buffer_size()); // std::cout << "Dados:" << std::endl; std::cout << x << ","; std::cout << y << ","; std::cout << z << ","; std::cout << roll << ","; std::cout << pitch << ","; std::cout << yaw << ","; std::cout << alphar << ","; std::cout << alphal << ","; std::cout << vx << ","; std::cout << vy << ","; std::cout << vz << ","; std::cout << wx << ","; std::cout << wy << ","; std::cout << wz << ","; std::cout << dalphar << ","; std::cout << dalphal << ","; } // Método para Ler dados de simulação void HilServer::GetStatesVANT20() { // dados da pose inicial ignition::math::Pose3d pose = link->WorldPose(); x = pose.Pos().X(); // x y = pose.Pos().Y(); // y z = pose.Pos().Z(); // z roll = pose.Rot().Euler().X(); // roll pitch = pose.Rot().Euler().Y(); // pitch yaw = pose.Rot().Euler().Z(); // yaw alphar = juntaR->Position(0); // alphaR alphal = juntaL->Position(0); // alphaL ignition::math::Vector3d linear = link->WorldLinearVel(); vx = linear.X(); // vx vy = linear.Y(); // vy vz = linear.Z(); // vz ignition::math::Vector3d angular = link->WorldAngularVel(); wx = angular.X(); // wx wy = angular.Y(); // wy wz = angular.Z(); // wz dalphar = juntaR->GetVelocity(0); // dalphaR dalphal = juntaL->GetVelocity(0); // dalphaL } // Método para escrever dados de simulação void HilServer::SetInputVANT20(double Fr_, double Fl_, double Tr_, double Tl_) { // Força de propulsão do motor direito ignition::math::Vector3d forceR(0, 0, Fr_); ignition::math::Vector3d torqueR(0, 0, 0.0178947368 * Fr_); linkR->AddRelativeForce(forceR); linkR->AddRelativeTorque(torqueR); // Força de propulsão do motor esquerdo ignition::math::Vector3d forceL(0, 0, Fl_); ignition::math::Vector3d torqueL(0, 0, -0.0178947368 * Fl_); linkL->AddRelativeForce(forceL); linkL->AddRelativeTorque(torqueL); // Torque do servo direito juntaR->SetForce(0, Tr_); // Torque do servo esquerdo juntaL->SetForce(0, Tl_); } GZ_REGISTER_MODEL_PLUGIN(HilServer) } // namespace gazebo
28.271698
109
0.565937
Guiraffo
21226db6b728ae585642f38bf1fefebb733d5f6f
1,109
cpp
C++
Source/FactoryGame/FGTrainStationIdentifier.cpp
iam-Legend/Project-Assembly
1ff3587704232d5e330515bc0d2aceb64ff09a7f
[ "MIT" ]
null
null
null
Source/FactoryGame/FGTrainStationIdentifier.cpp
iam-Legend/Project-Assembly
1ff3587704232d5e330515bc0d2aceb64ff09a7f
[ "MIT" ]
null
null
null
Source/FactoryGame/FGTrainStationIdentifier.cpp
iam-Legend/Project-Assembly
1ff3587704232d5e330515bc0d2aceb64ff09a7f
[ "MIT" ]
null
null
null
// This file has been automatically generated by the Unreal Header Implementation tool #include "FGTrainStationIdentifier.h" AFGTrainStationIdentifier::AFGTrainStationIdentifier(){ } void AFGTrainStationIdentifier::GetLifetimeReplicatedProps( TArray< FLifetimeProperty >& OutLifetimeProps) const{ } void AFGTrainStationIdentifier::PreSaveGame_Implementation( int32 saveVersion, int32 gameVersion){ } void AFGTrainStationIdentifier::PostSaveGame_Implementation( int32 saveVersion, int32 gameVersion){ } void AFGTrainStationIdentifier::PreLoadGame_Implementation( int32 saveVersion, int32 gameVersion){ } void AFGTrainStationIdentifier::PostLoadGame_Implementation( int32 saveVersion, int32 gameVersion){ } void AFGTrainStationIdentifier::GatherDependencies_Implementation( TArray< UObject* >& out_dependentObjects){ } bool AFGTrainStationIdentifier::NeedTransform_Implementation(){ return bool(); } bool AFGTrainStationIdentifier::ShouldSave_Implementation() const{ return bool(); } void AFGTrainStationIdentifier::SetStationName( const FText& text){ } void AFGTrainStationIdentifier::OnRep_StationName(){ }
69.3125
115
0.844905
iam-Legend
2124cf8ff359f5a282dceaf7782c4d55b2d40165
16,693
cpp
C++
Source/Samples/65_PhysicsTest/ConvexCast.cpp
extobias/Urho3D
7d08ccac1ff9e9e28076ea879530c6b23974ba42
[ "MIT" ]
null
null
null
Source/Samples/65_PhysicsTest/ConvexCast.cpp
extobias/Urho3D
7d08ccac1ff9e9e28076ea879530c6b23974ba42
[ "MIT" ]
null
null
null
Source/Samples/65_PhysicsTest/ConvexCast.cpp
extobias/Urho3D
7d08ccac1ff9e9e28076ea879530c6b23974ba42
[ "MIT" ]
null
null
null
#include "ConvexCast.h" #include <Urho3D/Core/Profiler.h> #include <Urho3D/IO/Log.h> #include <Urho3D/Scene/Node.h> #include <Urho3D/Scene/Scene.h> #include <Urho3D/Graphics/StaticModel.h> #include <Urho3D/Graphics/Model.h> #include <Urho3D/Graphics/DebugRenderer.h> #include <Urho3D/Resource/ResourceCache.h> #include <Urho3D/Physics/RigidBody.h> #include <Urho3D/Physics/CollisionShape.h> #include <Urho3D/Physics/PhysicsWorld.h> #include <Urho3D/Physics/PhysicsUtils.h> #include <Urho3D/Physics/PhysicsEvents.h> #include <Urho3D/Math/Ray.h> #include <Urho3D/Editor/EditorModelDebug.h> #include <Bullet/BulletDynamics/Dynamics/btRigidBody.h> #include <Bullet/BulletCollision/CollisionShapes/btCompoundShape.h> #include <BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h> #include <Bullet/BulletCollision/CollisionDispatch/btCollisionWorld.h> static const btVector3 WHITE(1.0f, 1.0f, 1.0f); static const btVector3 GREEN(0.0f, 1.0f, 0.0f); struct AllConvexResultCallback : public btCollisionWorld::ConvexResultCallback { AllConvexResultCallback(const btVector3& convexFromWorld, const btVector3& convexToWorld) :m_convexFromWorld(convexFromWorld), m_convexToWorld(convexToWorld), m_hitCollisionObject(0) { // URHO3D_LOGERRORF("AllConvexResultCallback ctor <%i>", m_hitPointWorld.size()); } btVector3 m_convexFromWorld;//used to calculate hitPointWorld from hitFraction btVector3 m_convexToWorld; // btVector3 m_hitNormalWorld; // btVector3 m_hitPointWorld; const btCollisionObject* m_hitCollisionObject; btAlignedObjectArray<const btCollisionObject*> m_collisionObjects; btAlignedObjectArray<btVector3> m_hitNormalWorld; btAlignedObjectArray<btVector3> m_hitPointWorld; btAlignedObjectArray<btVector3> m_hitPointLocal; btAlignedObjectArray<btScalar> m_hitFractions; btAlignedObjectArray<int> m_hitShapePart; btAlignedObjectArray<int> m_hitTriangleIndex; virtual btScalar addSingleResult(btCollisionWorld::LocalConvexResult& convexResult, bool normalInWorldSpace) { //caller already does the filter on the m_closestHitFraction // Assert(convexResult.m_hitFraction <= m_closestHitFraction); //m_closestHitFraction = convexResult.m_hitFraction; //m_hitCollisionObject = convexResult.m_hitCollisionObject; //if (normalInWorldSpace) //{ // m_hitNormalWorld = convexResult.m_hitNormalLocal; //} //else //{ // ///need to transform normal into worldspace // m_hitNormalWorld = m_hitCollisionObject->getWorldTransform().getBasis()*convexResult.m_hitNormalLocal; //} //m_hitPointWorld = convexResult.m_hitPointLocal; //return convexResult.m_hitFraction; // return m_closestHitFraction; // URHO3D_LOGERRORF("addSingleResult fraction <%f>", convexResult.m_hitFraction); m_closestHitFraction = convexResult.m_hitFraction; m_hitCollisionObject = convexResult.m_hitCollisionObject; m_collisionObjects.push_back(convexResult.m_hitCollisionObject); btVector3 hitNormalWorld; if (normalInWorldSpace) { hitNormalWorld = convexResult.m_hitNormalLocal; } else { ///need to transform normal into worldspace hitNormalWorld = m_hitCollisionObject->getWorldTransform().getBasis() * convexResult.m_hitNormalLocal; } m_hitNormalWorld.push_back(hitNormalWorld); btVector3 hitPointWorld; hitPointWorld.setInterpolate3(m_convexFromWorld, m_convexToWorld, convexResult.m_hitFraction); m_hitPointWorld.push_back(hitPointWorld); m_hitFractions.push_back(convexResult.m_hitFraction); m_hitPointLocal.push_back(convexResult.m_hitPointLocal); if (convexResult.m_localShapeInfo) { m_hitShapePart.push_back(convexResult.m_localShapeInfo->m_shapePart); m_hitTriangleIndex.push_back(convexResult.m_localShapeInfo->m_triangleIndex); } else { m_hitShapePart.push_back(-1); m_hitTriangleIndex.push_back(-1); } return convexResult.m_hitFraction; } }; ConvexCast::ConvexCast(Context* context) : Component(context), hasHit_(false), radius_(0.40f), hitPointsSize_(0), hitBody_(nullptr) { } ConvexCast::~ConvexCast() { } void ConvexCast::RegisterObject(Context* context) { context->RegisterFactory<ConvexCast>(); } void ConvexCast::OnNodeSet(Node* node) { if (!node) return; ResourceCache* cache = GetSubsystem<ResourceCache>(); // auto* wheelObject = shapeNode_->CreateComponent<StaticModel>(); // wheelObject->SetModel(cache->GetResource<Model>("Models/Cylinder.mdl")); // auto* wheelBody = wheelNode->CreateComponent<RigidBody>(); shape_ = node->CreateComponent<CollisionShape>(); // shape_->SetCylinder(radius_ * 2, radius_, Vector3::ZERO); shape_->SetSphere(radius_ * 2); } void ConvexCast::SetRadius(float r) { radius_ = r; shape_->SetCylinder(radius_ * 2, radius_, Vector3::ZERO); } void ConvexCast::UpdateTransform(WheelInfo& wheel, float steeringTimer) { // cylinder rotation Quaternion rot(90.0f, Vector3::FORWARD); // steering rotation rot = rot * Quaternion(45.0f * Urho3D::Sign(wheel.steering_) * 1.0f, Vector3::RIGHT); shape_->SetRotation(rot); // va relativo al centro del nodo, sino habria que hacer la transformacion con hardPointCS_ // respecto a la posicion/rotacion del nodo // Quaternion rot = node_->GetRotation(); // hardPointWS_ = node_->GetPosition() + rot * offset_; } float ConvexCast::Update(WheelInfo& wheel, RigidBody* hullBody, float steeringTimer, bool debug, bool interpolateNormal) { URHO3D_PROFILE(ConvexCastUpdate); UpdateTransform(wheel, steeringTimer); Scene* scene = GetScene(); if (!scene) return 0.0f; PhysicsWorld* pw = scene->GetComponent<PhysicsWorld>(); btCollisionWorld* world = pw->GetWorld(); Quaternion worldRotation = node_->GetRotation() * shape_->GetRotation(); Vector3 direction = wheel.raycastInfo_.wheelDirectionWS_.Normalized(); // Ray ray(wheel.raycastInfo_.hardPointWS_, wheel.wheelDirectionCS_); Ray ray(wheel.raycastInfo_.hardPointWS_, direction); Vector3 startPos = ray.origin_; Vector3 endPos = ray.origin_ + wheel.raycastInfo_.suspensionLength_ * 1.0f * ray.direction_; //Vector3 startPos = Vector3(0.0f, 1.0f, 0.0f); //Vector3 endPos = Vector3(0.0f, -1.0f, 0.0f); Quaternion startRot = worldRotation; Quaternion endRot = worldRotation; AllConvexResultCallback convexCallback(ToBtVector3(startPos), ToBtVector3(endPos)); convexCallback.m_collisionFilterGroup = (short)0xffff; convexCallback.m_collisionFilterMask = (short)1 << 0; btCollisionShape* shape = shape_->GetCollisionShape(); world->convexSweepTest(reinterpret_cast<btConvexShape*>(shape), btTransform(ToBtQuaternion(startRot), convexCallback.m_convexFromWorld), btTransform(ToBtQuaternion(endRot), convexCallback.m_convexToWorld), convexCallback, world->getDispatchInfo().m_allowedCcdPenetration); hasHit_ = false; hitPointsSize_ = 0; hitIndex_ = -1; hitDistance_.Clear(); hitFraction_.Clear(); hitPointWorld_.Clear(); hitNormalWorld_.Clear(); hitPointLocal_.Clear(); hitShapePart_.Clear(); hitTriangleIndex_.Clear(); float distance = 1000.0f; hitPointsSize_ = convexCallback.m_hitPointWorld.size(); for (int i = 0; i < hitPointsSize_; i++) { hitPoint_ = ToVector3(convexCallback.m_hitPointWorld.at(i)); hitPointWorld_.Push(hitPoint_); hitPointLocal_.Push(ToVector3(convexCallback.m_hitPointLocal.at(i))); hitNormal_ = ToVector3(convexCallback.m_hitNormalWorld.at(i)); hitNormalWorld_.Push(hitNormal_); hitFraction_.Push((float)convexCallback.m_hitFractions.at(i)); if (i < convexCallback.m_hitShapePart.size()) { hitShapePart_.Push(convexCallback.m_hitShapePart.at(i)); hitTriangleIndex_.Push(convexCallback.m_hitTriangleIndex.at(i)); } // use most closest to startPos point as index float d = (hitPoint_ - startPos).Length(); hitDistance_.Push(d); if (distance > d) { distance = d; hitIndex_ = i; } } float angNormal = 0.0f; if (convexCallback.hasHit() && hitIndex_ != -1) { hasHit_ = true; hitBody_ = static_cast<RigidBody*>(convexCallback.m_collisionObjects.at(hitIndex_)->getUserPointer()); wheel.raycastInfo_.isInContact_ = true; wheel.raycastInfo_.distance_ = Max(hitDistance_.At(hitIndex_), wheel.raycastInfo_.suspensionMinRest_); if (hitDistance_.At(hitIndex_) < wheel.raycastInfo_.suspensionMinRest_) { // wheel.raycastInfo_.contactPoint_ = wheel.raycastInfo_.hardPointWS_ + wheel.wheelDirectionCS_ * wheel.raycastInfo_.suspensionMinRest_; wheel.raycastInfo_.contactPoint_ = wheel.raycastInfo_.hardPointWS_ + direction * wheel.raycastInfo_.suspensionMinRest_; } // else if (hitDistance_.At(hitIndex_) > wheel.raycastInfo_.suspensionMaxRest_) // { // wheel.raycastInfo_.contactPoint_ = wheel.raycastInfo_.hardPointWS_ + wheel.wheelDirectionCS_ * wheel.raycastInfo_.suspensionMaxRest_; // } else { wheel.raycastInfo_.contactPoint_ = hitPointWorld_.At(hitIndex_); } wheel.raycastInfo_.contactPointLocal_ = hitPointLocal_.At(hitIndex_); // angNormal = hitNormalWorld_.At(hitIndex_).DotProduct(wheel.raycastInfo_.contactNormal_); // if((acos(angNormal) * M_RADTODEG) > 30.0f) // { // wheel.raycastInfo_.contactNormal_ = -wheel.wheelDirectionCS_; // } // else { if (interpolateNormal) { const btRigidBody* hitBody = btRigidBody::upcast(convexCallback.m_collisionObjects.at(hitIndex_)); btCollisionShape* hitShape = (btCollisionShape*)hitBody->getCollisionShape(); if (hitShape->getShapeType() == SCALED_TRIANGLE_MESH_SHAPE_PROXYTYPE) { btVector3 in = pw->InterpolateMeshNormal(hitBody->getWorldTransform(), hitShape, hitShapePart_.At(hitIndex_), hitTriangleIndex_.At(hitIndex_), ToBtVector3(hitPointWorld_.At(hitIndex_)), GetComponent<DebugRenderer>()); wheel.raycastInfo_.contactNormal_ = ToVector3(in); } else { // result.normal_ = ToVector3(rayCallback.m_hitNormalWorld); wheel.raycastInfo_.contactNormal_ = hitNormalWorld_.At(hitIndex_); } } else { wheel.raycastInfo_.contactNormal_ = hitNormalWorld_.At(hitIndex_); } } // Node* node = hitBody_->GetNode(); // btVector3 scale = ToBtVector3(node->GetScale()); // IntVector3 vc; // if (hitIndex_ < hitShapePart_.Size()) // { // bool collisionOk = PhysicsWorld::GetCollisionMask(convexCallback.m_collisionObjects[hitIndex_], // ToBtVector3(hitPointWorld_.At(hitIndex_)), hitShapePart_.At(hitIndex_), // hitTriangleIndex_.At(hitIndex_), scale, vc); // if (collisionOk) // { // const VertexCollisionMaskFlags& c0 = (const VertexCollisionMaskFlags)(vc.x_); // const VertexCollisionMaskFlags& c1 = (const VertexCollisionMaskFlags)(vc.y_); // const VertexCollisionMaskFlags& c2 = (const VertexCollisionMaskFlags)(vc.z_); // // color = GetFaceColor(c0); // if((c0 & (TRACK_ROAD | TRACK_BORDER | OFFTRACK_WEAK | OFFTRACK_HEAVY)) // && (c1 & (TRACK_ROAD | TRACK_BORDER | OFFTRACK_WEAK | OFFTRACK_HEAVY)) // && (c2 & (TRACK_ROAD | TRACK_BORDER | OFFTRACK_WEAK | OFFTRACK_HEAVY)) // && c0 == c1 && c0 == c2 && c1 == c2) // { // wheel.raycastInfo_.contactMaterial_ = c0.AsInteger(); // } // else // { // wheel.raycastInfo_.contactMaterial_ = TRACK_ROAD; // } // } // else // { // wheel.raycastInfo_.contactMaterial_ = TRACK_ROAD; // } // } // else // { // wheel.raycastInfo_.contactMaterial_ = TRACK_ROAD; // } float project = wheel.raycastInfo_.contactNormal_.DotProduct(wheel.raycastInfo_.wheelDirectionWS_); angNormal = project; Vector3 relPos = wheel.raycastInfo_.contactPoint_ - hullBody->GetPosition(); Vector3 contactVel = hullBody->GetVelocityAtPoint(relPos); float projVel = wheel.raycastInfo_.contactNormal_.DotProduct(contactVel); if (project >= -0.1f) { wheel.raycastInfo_.suspensionRelativeVelocity_ = 0.0f; } else { float inv = btScalar(-1.) / project; wheel.raycastInfo_.suspensionRelativeVelocity_ = projVel * inv; } } else { hitBody_ = nullptr; wheel.raycastInfo_.isInContact_ = false; wheel.raycastInfo_.distance_ = 0.0f; wheel.raycastInfo_.contactNormal_ = -wheel.raycastInfo_.wheelDirectionWS_; wheel.raycastInfo_.contactPoint_ = wheel.raycastInfo_.hardPointWS_ + wheel.raycastInfo_.wheelDirectionWS_; // wheel.raycastInfo_.suspensionRelativeVelocity_ = 0.0f; } return wheel.raycastInfo_.suspensionRelativeVelocity_; } void ConvexCast::DebugDraw(const WheelInfo& wheel, Vector3 centerOfMass, bool first, float speed, Vector3 angularVel) { DebugRenderer* debug = GetScene()->GetComponent<DebugRenderer>(); PhysicsWorld* pw = GetScene()->GetComponent<PhysicsWorld>(); btCollisionWorld* world = pw->GetWorld(); Ray ray(wheel.raycastInfo_.hardPointWS_, wheel.raycastInfo_.wheelDirectionWS_); Vector3 startPos = ray.origin_; Vector3 endPos = ray.origin_ + wheel.raycastInfo_.suspensionLength_ * 1.0f * ray.direction_; Sphere startSphere(startPos, 0.1f); debug->AddSphere(startSphere, Color::GREEN, false); Sphere endSphere(endPos, 0.15f); debug->AddSphere(endSphere, Color::RED, false); Vector<Color> colors; colors.Push(Color::WHITE); colors.Push(Color::GRAY); colors.Push(Color::BLACK); colors.Push(Color::RED); colors.Push(Color::GREEN); colors.Push(Color::BLUE); colors.Push(Color::CYAN); colors.Push(Color::MAGENTA); colors.Push(Color::YELLOW); // Vector3 local(hitPointLocal_.At(i)); Vector3 local(wheel.raycastInfo_.contactPointLocal_); // Color color = colors.At(i % 9); Sphere sphere(local, 0.01f); debug->AddSphere(sphere, Color::YELLOW, false); // Vector3 hit(wheel.raycastInfo_.contactPoint_ - centerOfMass); Vector3 hit(wheel.raycastInfo_.contactPoint_); Sphere sphereHit(hit, 0.005f); debug->AddSphere(sphereHit, wheel.raycastInfo_.isInContact_ ? Color::GREEN : Color::BLUE, false); // normal Vector3 normal(wheel.raycastInfo_.contactNormal_); debug->AddLine(hit, hit + normal.Normalized(), Color::YELLOW, false); // debug->AddCylinder(hit, radius_, radius_, Color::BLUE, false); pw->SetDebugRenderer(debug); pw->SetDebugDepthTest(true); Matrix3x4 worldTransform = node_->GetTransform(); Quaternion rotation = shape_->GetRotation(); Quaternion torqueRot(speed, Vector3::UP); Quaternion worldRotation(worldTransform.Rotation() * rotation * torqueRot); Vector3 worldPosition(hit); world->debugDrawObject(btTransform(ToBtQuaternion(worldRotation), ToBtVector3(worldPosition)), shape_->GetCollisionShape(), btVector3(0.0f, first ? 1.0 : 0.0f, !first ? 1.0f : 0.0f)); pw->SetDebugRenderer(nullptr); // cylinder // Vector3 shapePosition(hitPoint_); // Quaternion shapeRotation(worldTransform.Rotation() * shape_->GetRotation()); // bool bodyActive = false; // pw->SetDebugRenderer(debug); // pw->SetDebugDepthTest(false); // world->debugDrawObject(btTransform(ToBtQuaternion(shapeRotation), ToBtVector3(shapePosition)), shape_->GetCollisionShape(), bodyActive ? WHITE : GREEN); // pw->SetDebugRenderer(nullptr); }
38.641204
162
0.669322
extobias
213161364f5852b94b7252b7341bc026849b6443
396
cpp
C++
clang/test/SemaCXX/atomic-ops.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
3,102
2015-01-04T02:28:35.000Z
2022-03-30T12:53:41.000Z
clang/test/SemaCXX/atomic-ops.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
clang/test/SemaCXX/atomic-ops.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
1,868
2015-01-03T04:27:11.000Z
2022-03-25T13:37:35.000Z
// RUN: %clang_cc1 %s -verify -fsyntax-only -triple=i686-linux-gnu -std=c++11 // We crashed when we couldn't properly convert the first arg of __atomic_* to // an lvalue. void PR28623() { void helper(int); // expected-note{{target}} void helper(char); // expected-note{{target}} __atomic_store_n(helper, 0, 0); // expected-error{{reference to overloaded function could not be resolved}} }
39.6
109
0.709596
medismailben
213226a3b9022a3fe4e11c9ac1eb3b5125a2a6aa
1,631
cpp
C++
src/prod/src/Reliability/Failover/fm/BackgroundThreadContext.cpp
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
2,542
2018-03-14T21:56:12.000Z
2019-05-06T01:18:20.000Z
src/prod/src/Reliability/Failover/fm/BackgroundThreadContext.cpp
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
994
2019-05-07T02:39:30.000Z
2022-03-31T13:23:04.000Z
src/prod/src/Reliability/Failover/fm/BackgroundThreadContext.cpp
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
300
2018-03-14T21:57:17.000Z
2019-05-06T20:07:00.000Z
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace std; using namespace Common; using namespace Reliability; using namespace Reliability::FailoverManagerComponent; BackgroundThreadContext::BackgroundThreadContext(wstring const & contextId) : contextId_(contextId) { } void BackgroundThreadContext::TransferUnprocessedFailoverUnits(BackgroundThreadContext & original) { swap(unprocessedFailoverUnits_, original.unprocessedFailoverUnits_); } bool BackgroundThreadContext::MergeUnprocessedFailoverUnits(set<FailoverUnitId> const & failoverUnitIds) { if (unprocessedFailoverUnits_.size() == 0) { unprocessedFailoverUnits_ = failoverUnitIds; } else { for (auto it = unprocessedFailoverUnits_.begin(); it != unprocessedFailoverUnits_.end();) { if (failoverUnitIds.find(*it) == failoverUnitIds.end()) { unprocessedFailoverUnits_.erase(it++); } else { ++it; } } } return (unprocessedFailoverUnits_.size() == 0); } void BackgroundThreadContext::ClearUnprocessedFailoverUnits() { unprocessedFailoverUnits_.clear(); } void BackgroundThreadContext::WriteTo(TextWriter& w, FormatOptions const &) const { w.Write("{0}: Unprocessed={1:3}", contextId_, unprocessedFailoverUnits_); }
29.125
104
0.642551
gridgentoo
2133fea2d2f423786a1f5dff1923a21c5d135256
1,218
hpp
C++
src/clustering/generic/registration_metadata.hpp
sauter-hq/rethinkdb
f34541d501bcf109c2825a7a1b67cf8fd39b9133
[ "Apache-2.0" ]
null
null
null
src/clustering/generic/registration_metadata.hpp
sauter-hq/rethinkdb
f34541d501bcf109c2825a7a1b67cf8fd39b9133
[ "Apache-2.0" ]
null
null
null
src/clustering/generic/registration_metadata.hpp
sauter-hq/rethinkdb
f34541d501bcf109c2825a7a1b67cf8fd39b9133
[ "Apache-2.0" ]
null
null
null
// Copyright 2010-2014 RethinkDB, all rights reserved. #ifndef CLUSTERING_GENERIC_REGISTRATION_METADATA_HPP_ #define CLUSTERING_GENERIC_REGISTRATION_METADATA_HPP_ #include "containers/uuid.hpp" #include "rpc/mailbox/typed.hpp" #include "rpc/semilattice/joins/macros.hpp" template<class business_card_t> class registrar_business_card_t { public: typedef uuid_u registration_id_t; typedef mailbox_t<void(registration_id_t, peer_id_t, business_card_t)> create_mailbox_t; typename create_mailbox_t::address_t create_mailbox; typedef mailbox_t<void(registration_id_t)> delete_mailbox_t; typename delete_mailbox_t::address_t delete_mailbox; registrar_business_card_t() { } registrar_business_card_t( const typename create_mailbox_t::address_t &cm, const typename delete_mailbox_t::address_t &dm) : create_mailbox(cm), delete_mailbox(dm) { } RDB_MAKE_ME_SERIALIZABLE_2(registrar_business_card_t, create_mailbox, delete_mailbox); }; template <class business_card_t> RDB_MAKE_EQUALITY_COMPARABLE_2(registrar_business_card_t<business_card_t>, create_mailbox, delete_mailbox); #endif /* CLUSTERING_GENERIC_REGISTRATION_METADATA_HPP_ */
32.918919
92
0.791461
sauter-hq
213501518e2260911a4440b08ed8399758618c3c
5,921
cc
C++
mojo/services/media/common/cpp/video_converter.cc
jason-simmons/flutter_buildroot
1c9494e60378bd119d910d530344077fc091b3a5
[ "BSD-3-Clause" ]
null
null
null
mojo/services/media/common/cpp/video_converter.cc
jason-simmons/flutter_buildroot
1c9494e60378bd119d910d530344077fc091b3a5
[ "BSD-3-Clause" ]
null
null
null
mojo/services/media/common/cpp/video_converter.cc
jason-simmons/flutter_buildroot
1c9494e60378bd119d910d530344077fc091b3a5
[ "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 "mojo/services/media/common/cpp/video_converter.h" namespace mojo { namespace media { VideoConverter::VideoConverter() { BuildColorspaceTable(); } VideoConverter::~VideoConverter() {} namespace { uint8_t ToByte(float f) { if (f < 0.0f) { return 0u; } if (f > 255.0f) { return 255u; } return static_cast<uint8_t>(f); } size_t ColorspaceTableOffset(uint8_t y, uint8_t u, uint8_t v) { return (y << 8u | u) << 8u | v; } } // namespace void VideoConverter::BuildColorspaceTable() { colorspace_table_.reset(new uint32_t[256 * 256 * 256]); uint32_t* p = colorspace_table_.get(); for (size_t iy = 0; iy < 256; ++iy) { for (size_t iu = 0; iu < 256; ++iu) { for (size_t iv = 0; iv < 256; ++iv) { float y = static_cast<float>(iy); float u = static_cast<float>(iu); float v = static_cast<float>(iv); // R = 1.164(Y - 16) + 1.596(V - 128) uint8_t r = ToByte(1.164f * (y - 16.0f) + 1.596f * (v - 128.0f)); // G = 1.164(Y - 16) - 0.813(V - 128) - 0.391(U - 128) uint8_t g = ToByte(1.164f * (y - 16.0f) - 0.813f * (v - 128.0f) - 0.391f * (u - 128.0f)); // B = 1.164(Y - 16) + 2.018(U - 128) uint8_t b = ToByte(1.164f * (y - 16.0f) + 2.018f * (u - 128.0f)); *p = r | (g << 8u) | (b << 16u) | (255u << 24u); ++p; } } } } void VideoConverter::SetMediaType(const MediaTypePtr& media_type) { MOJO_DCHECK(media_type); MOJO_DCHECK(media_type->medium == MediaTypeMedium::VIDEO); MOJO_DCHECK(media_type->encoding == MediaType::kVideoEncodingUncompressed); MOJO_DCHECK(media_type->details); const VideoMediaTypeDetailsPtr& details = media_type->details->get_video(); MOJO_DCHECK(details); MOJO_DCHECK(details->pixel_format == PixelFormat::YV12) << "only YV12 video conversion is currently implemented"; layout_ = VideoPacketLayout(details->pixel_format, details->width, details->height, details->coded_width, details->coded_height); media_type_set_ = true; } Size VideoConverter::GetSize() { Size size; if (media_type_set_) { size.width = layout_.width(); size.height = layout_.height(); } else { size.width = 0; size.height = 0; } return size; } void VideoConverter::ConvertFrame(uint8_t* rgba_buffer, uint32_t view_width, uint32_t view_height, void* payload, uint64_t payload_size) { MOJO_DCHECK(rgba_buffer != nullptr); MOJO_DCHECK(view_width != 0); MOJO_DCHECK(view_height != 0); MOJO_DCHECK(payload != nullptr); MOJO_DCHECK(payload_size != 0); MOJO_DCHECK(media_type_set_) << "need to call SetMediaType before ConvertFrame"; uint32_t height = std::min(layout_.height(), view_height); uint32_t width = std::min(layout_.width(), view_width); // YV12 frames have three separate planes. The Y plane has 8-bit Y values for // each pixel. The U and V planes have 8-bit U and V values for 2x2 grids of // pixels, so those planes are each 1/4 the size of the Y plane. Both the // inner and outer loops below are unrolled to deal with the 2x2 logic. size_t dest_line_stride = view_width; size_t y_line_stride = layout_.line_stride_for_plane(VideoPacketLayout::kYPlaneIndex); size_t u_line_stride = layout_.line_stride_for_plane(VideoPacketLayout::kUPlaneIndex); size_t v_line_stride = layout_.line_stride_for_plane(VideoPacketLayout::kVPlaneIndex); uint32_t* dest_line = reinterpret_cast<uint32_t*>( rgba_buffer + dest_line_stride * (view_height - 1) * sizeof(uint32_t)); uint8_t* y_line = reinterpret_cast<uint8_t*>(payload) + layout_.plane_offset_for_plane(VideoPacketLayout::kYPlaneIndex); uint8_t* u_line = reinterpret_cast<uint8_t*>(payload) + layout_.plane_offset_for_plane(VideoPacketLayout::kUPlaneIndex); uint8_t* v_line = reinterpret_cast<uint8_t*>(payload) + layout_.plane_offset_for_plane(VideoPacketLayout::kVPlaneIndex); for (uint32_t line = 0; line < height; ++line) { ConvertLine(dest_line, y_line, u_line, v_line, width); dest_line -= dest_line_stride; y_line += y_line_stride; // Notice we aren't updating u_line and v_line here. // If we hadn't unrolled the loop, it would have ended here. if (++line == height) { break; } ConvertLine(dest_line, y_line, u_line, v_line, width); dest_line -= dest_line_stride; y_line += y_line_stride; // Here, we ARE updating u_line and v_line, because we've moved vertically // out of the 2x2 grid. u_line += u_line_stride; v_line += v_line_stride; } } void VideoConverter::ConvertLine(uint32_t* dest_pixel, uint8_t* y_pixel, uint8_t* u_pixel, uint8_t* v_pixel, uint32_t width) { for (uint32_t pixel = 0; pixel < width; ++pixel) { *dest_pixel = colorspace_table_ .get()[ColorspaceTableOffset(*y_pixel, *u_pixel, *v_pixel)]; ++dest_pixel; ++y_pixel; // Notice we aren't incrementing u_pixel and v_pixel here. // If we hadn't unrolled the loop, it would have ended here. if (++pixel == width) { break; } *dest_pixel = colorspace_table_ .get()[ColorspaceTableOffset(*y_pixel, *u_pixel, *v_pixel)]; ++dest_pixel; ++y_pixel; // Here, we ARE incrementing u_pixel and v_pixel, because we've moved // horizontally out of the 2x2 grid. ++u_pixel; ++v_pixel; } } } // namespace media } // namespace mojo
31
79
0.629623
jason-simmons
2138950715d1c7f2b8c86bd9a09b4d6ba5a296dc
1,247
cpp
C++
gk/spritesheet.cpp
rpav/GameKernel
1f3eb863b58243f5f14aa76283b60a259d881522
[ "MIT" ]
11
2016-04-28T15:09:19.000Z
2019-07-15T15:58:59.000Z
gk/spritesheet.cpp
rpav/GameKernel
1f3eb863b58243f5f14aa76283b60a259d881522
[ "MIT" ]
null
null
null
gk/spritesheet.cpp
rpav/GameKernel
1f3eb863b58243f5f14aa76283b60a259d881522
[ "MIT" ]
null
null
null
#include <rpav/log.hpp> #include <stdlib.h> #include "gk/gk.hpp" #include "gk/gl.hpp" #include "gk/spritesheet.hpp" using namespace rpav; void gk_process_spritesheet_create(gk_context* gk, gk_cmd_spritesheet_create* cmd) { auto sheet = (gk_spritesheet*)malloc(sizeof(gk_spritesheet)); switch(cmd->format) { case GK_SSF_TEXTUREPACKER_JSON: gk_load_ssf_texturepacker_json(gk, cmd, sheet); break; default: say("Unknown sprite sheet format ", cmd->format); gk_seterror(gk, GK_ERROR_SSF_UNKNOWN); break; } // If there is an error, the loader should free everything it // allocates if(gk_haserror(gk)) goto error; cmd->sheet = sheet; return; error: free(sheet); } void gk_free_one_sheet(gk_spritesheet* sheet) { GL_CHECK(glDeleteTextures(1, (GLuint*)&sheet->tex)); gl_error: free(sheet->sprites); for(size_t i = 0; i < sheet->nsprites; ++i) free(sheet->names[i]); free(sheet->names); free(sheet); } void gk_process_spritesheet_destroy(gk_context*, gk_cmd_spritesheet_destroy* cmd) { for(size_t i = 0; i < cmd->nsheets; ++i) { auto sheet = cmd->sheets[i]; gk_free_one_sheet(sheet); } }
22.672727
82
0.648757
rpav
213abf05b084f9f7df27ceb2c4505f6b15f9c57d
797
cpp
C++
Example/datetime_21/main.cpp
KwangjoJeong/Boost
29c4e2422feded66a689e3aef73086c5cf95b6fe
[ "MIT" ]
null
null
null
Example/datetime_21/main.cpp
KwangjoJeong/Boost
29c4e2422feded66a689e3aef73086c5cf95b6fe
[ "MIT" ]
null
null
null
Example/datetime_21/main.cpp
KwangjoJeong/Boost
29c4e2422feded66a689e3aef73086c5cf95b6fe
[ "MIT" ]
null
null
null
#include <boost/date_time/gregorian/gregorian.hpp> #include <string> #include <vector> #include <locale> #include <iostream> using namespace boost::gregorian; int main() { std::locale::global(std::locale{"German"}); std::string months[12]{"Januar", "Februar", "M\xe4rz", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"}; std::string weekdays[7]{"Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"}; date d{2014, 5, 12}; date_facet *df = new date_facet{"%A, %d. %B %Y"}; df->long_month_names(std::vector<std::string>{months, months + 12}); df->long_weekday_names(std::vector<std::string>{weekdays, weekdays + 7}); std::cout.imbue(std::locale{std::cout.getloc(), df}); std::cout << d << '\n'; }
33.208333
70
0.643664
KwangjoJeong
213ae5345d9ad68812860bb69e049e602d81045e
683
cpp
C++
FPS_Multiplayer_UE4/Source/TestRyseUp/Private/Items/ConsumableActor.cpp
agerith/FPS_Multiplayer_UE4
61e2d330c06740de1f19219833ff177c444fdb5c
[ "MIT" ]
1
2022-03-22T07:27:29.000Z
2022-03-22T07:27:29.000Z
FPS_Multiplayer_UE4/Source/TestRyseUp/Private/Items/ConsumableActor.cpp
agerith/FPS_Multiplayer_UE4
61e2d330c06740de1f19219833ff177c444fdb5c
[ "MIT" ]
null
null
null
FPS_Multiplayer_UE4/Source/TestRyseUp/Private/Items/ConsumableActor.cpp
agerith/FPS_Multiplayer_UE4
61e2d330c06740de1f19219833ff177c444fdb5c
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "ConsumableActor.h" #include "TestRyseUp.h" #include "ConsumableActor.h" #include "TestRyseUpCharacter.h" AConsumableActor::AConsumableActor(const class FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { /* A default to tweak per food variation in Blueprint */ Nutrition = 40; bAllowRespawn = true; RespawnDelay = 60.0f; RespawnDelayRange = 20.0f; } void AConsumableActor::OnUsed(APawn* InstigatorPawn) { ATestRyseUpCharacter* Pawn = Cast<ATestRyseUpCharacter>(InstigatorPawn); if (Pawn) { Pawn->RestoreLife(Nutrition); } Super::OnUsed(InstigatorPawn); }
20.088235
85
0.764275
agerith
213bbd49b3a68fc5ca0914014d611b44f3cc9037
1,348
cpp
C++
array_and_matrixs/Kth_smallest_element_in_a_sorted_matrix.cpp
zm66260/Data_Structure_and_Algorithms
f3e6d60a9f0ddf1a8fe943dedc089172bc8c833e
[ "MIT" ]
null
null
null
array_and_matrixs/Kth_smallest_element_in_a_sorted_matrix.cpp
zm66260/Data_Structure_and_Algorithms
f3e6d60a9f0ddf1a8fe943dedc089172bc8c833e
[ "MIT" ]
null
null
null
array_and_matrixs/Kth_smallest_element_in_a_sorted_matrix.cpp
zm66260/Data_Structure_and_Algorithms
f3e6d60a9f0ddf1a8fe943dedc089172bc8c833e
[ "MIT" ]
null
null
null
// 378 kth smallest element in a sorted matrix // Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix. // Note that it is the kth smallest element in the sorted order, not the kth distinct element. // Example: // matrix = [ // [ 1, 5, 9], // [10, 11, 13], // [12, 13, 15] // ], // k = 8, // return 13. // Note: // You may assume k is always valid, 1 ≤ k ≤ n2. #include<vector> using namespace std; class Solution { public: int kthSmallest(vector<vector<int>>& matrix, int k) { int left = matrix[0][0]; int right = matrix[matrix.size()-1][matrix.size()-1]; while(left < right){ int mid = (left + right) / 2; int count = searchMatrix(matrix, mid); if(count < k){ left = mid+1; } else{right = mid;} } return left; } int searchMatrix(vector<vector<int>>& matrix, int midvalue){ int r = matrix.size()-1; int c = 0; int count = 0; while(r >= 0 && c < matrix[0].size()){ if(matrix[r][c] <= midvalue){ c++; count += r + 1; } else{r--;} } return count; } };
24.962963
135
0.488131
zm66260
2140e3c5363de17751581b959591bd74662371a7
11,246
cpp
C++
implementations/ugene/src/plugins/enzymes/src/EnzymesPlugin.cpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
implementations/ugene/src/plugins/enzymes/src/EnzymesPlugin.cpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
implementations/ugene/src/plugins/enzymes/src/EnzymesPlugin.cpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2020 UniPro <ugene@unipro.ru> * http://ugene.net * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "EnzymesPlugin.h" #include <QDir> #include <QMenu> #include <QMessageBox> #include <U2Core/AnnotationSelection.h> #include <U2Core/AppContext.h> #include <U2Core/AutoAnnotationsSupport.h> #include <U2Core/DNAAlphabet.h> #include <U2Core/GAutoDeleteList.h> #include <U2Core/QObjectScopedPointer.h> #include <U2Gui/DialogUtils.h> #include <U2Gui/GUIUtils.h> #include <U2Gui/MainWindow.h> #include <U2Gui/ToolsMenu.h> #include <U2Test/GTestFrameworkComponents.h> #include <U2View/ADVConstants.h> #include <U2View/ADVSequenceObjectContext.h> #include <U2View/ADVSequenceWidget.h> #include <U2View/ADVUtils.h> #include <U2View/AnnotatedDNAView.h> #include "ConstructMoleculeDialog.h" #include "CreateFragmentDialog.h" #include "DigestSequenceDialog.h" #include "EnzymesQuery.h" #include "EnzymesTests.h" #include "FindEnzymesDialog.h" #include "FindEnzymesTask.h" const QString CREATE_PCR_PRODUCT_ACTION_NAME = "Create PCR product"; namespace U2 { extern "C" Q_DECL_EXPORT Plugin *U2_PLUGIN_INIT_FUNC() { EnzymesPlugin *plug = new EnzymesPlugin(); return plug; } EnzymesPlugin::EnzymesPlugin() : Plugin(tr("Restriction analysis"), tr("Finds and annotates restriction sites on a DNA sequence.")), ctxADV(NULL) { if (AppContext::getMainWindow()) { createToolsMenu(); QList<QAction *> actions; actions.append(openDigestSequenceDialog); actions.append(openConstructMoleculeDialog); actions.append(openCreateFragmentDialog); ctxADV = new EnzymesADVContext(this, actions); ctxADV->init(); AppContext::getAutoAnnotationsSupport()->registerAutoAnnotationsUpdater(new FindEnzymesAutoAnnotationUpdater()); } EnzymesSelectorWidget::setupSettings(); FindEnzymesDialog::initDefaultSettings(); GTestFormatRegistry *tfr = AppContext::getTestFramework()->getTestFormatRegistry(); XMLTestFormat *xmlTestFormat = qobject_cast<XMLTestFormat *>(tfr->findFormat("XML")); assert(xmlTestFormat != NULL); QDActorPrototypeRegistry *qdpr = AppContext::getQDActorProtoRegistry(); qdpr->registerProto(new QDEnzymesActorPrototype()); GAutoDeleteList<XMLTestFactory> *l = new GAutoDeleteList<XMLTestFactory>(this); l->qlist = EnzymeTests::createTestFactories(); foreach (XMLTestFactory *f, l->qlist) { bool res = xmlTestFormat->registerTestFactory(f); assert(res); Q_UNUSED(res); } } void EnzymesPlugin::createToolsMenu() { openDigestSequenceDialog = new QAction(tr("Digest into fragments..."), this); openDigestSequenceDialog->setObjectName(ToolsMenu::CLONING_FRAGMENTS); openConstructMoleculeDialog = new QAction(tr("Construct molecule..."), this); openConstructMoleculeDialog->setObjectName(ToolsMenu::CLONING_CONSTRUCT); openCreateFragmentDialog = new QAction(tr("Create fragment..."), this); openCreateFragmentDialog->setObjectName("Create Fragment"); connect(openDigestSequenceDialog, SIGNAL(triggered()), SLOT(sl_onOpenDigestSequenceDialog())); connect(openConstructMoleculeDialog, SIGNAL(triggered()), SLOT(sl_onOpenConstructMoleculeDialog())); connect(openCreateFragmentDialog, SIGNAL(triggered()), SLOT(sl_onOpenCreateFragmentDialog())); ToolsMenu::addAction(ToolsMenu::CLONING_MENU, openDigestSequenceDialog); ToolsMenu::addAction(ToolsMenu::CLONING_MENU, openConstructMoleculeDialog); } void EnzymesPlugin::sl_onOpenDigestSequenceDialog() { GObjectViewWindow *w = GObjectViewUtils::getActiveObjectViewWindow(); if (w == NULL) { QMessageBox::information(QApplication::activeWindow(), openDigestSequenceDialog->text(), tr("There is no active sequence object.\nTo start partition open sequence document.")); return; } AnnotatedDNAView *view = qobject_cast<AnnotatedDNAView *>(w->getObjectView()); if (view == NULL) { QMessageBox::information(QApplication::activeWindow(), openDigestSequenceDialog->text(), tr("There is no active sequence object.\nTo start partition open sequence document.")); return; } if (!view->getSequenceInFocus()->getSequenceObject()->getAlphabet()->isNucleic()) { QMessageBox::information(QApplication::activeWindow(), openDigestSequenceDialog->text(), tr("Can not digest into fragments non-nucleic sequence.")); return; } QObjectScopedPointer<DigestSequenceDialog> dlg = new DigestSequenceDialog(view->getSequenceInFocus(), QApplication::activeWindow()); dlg->exec(); } void EnzymesPlugin::sl_onOpenCreateFragmentDialog() { GObjectViewWindow *w = GObjectViewUtils::getActiveObjectViewWindow(); if (w == NULL) { QMessageBox::information(QApplication::activeWindow(), openCreateFragmentDialog->text(), tr("There is no active sequence object.\nTo create fragment open sequence document.")); return; } AnnotatedDNAView *view = qobject_cast<AnnotatedDNAView *>(w->getObjectView()); if (view == NULL) { QMessageBox::information(QApplication::activeWindow(), openCreateFragmentDialog->text(), tr("There is no active sequence object.\nTo create fragment open sequence document.")); return; } U2SequenceObject *dnaObj = view->getSequenceInFocus()->getSequenceObject(); assert(dnaObj != NULL); if (!dnaObj->getAlphabet()->isNucleic()) { QMessageBox::information(QApplication::activeWindow(), openCreateFragmentDialog->text(), tr("The sequence doesn't have nucleic alphabet, it can not be used in cloning.")); return; } QObjectScopedPointer<CreateFragmentDialog> dlg = new CreateFragmentDialog(view->getSequenceInFocus(), QApplication::activeWindow()); dlg->exec(); } void EnzymesPlugin::sl_onOpenConstructMoleculeDialog() { Project *p = AppContext::getProject(); if (p == NULL) { QMessageBox::information(QApplication::activeWindow(), openConstructMoleculeDialog->text(), tr("There is no active project.\nTo start ligation create a project or open an existing.")); return; } QList<DNAFragment> fragments = DNAFragment::findAvailableFragments(); QObjectScopedPointer<ConstructMoleculeDialog> dlg = new ConstructMoleculeDialog(fragments, QApplication::activeWindow()); dlg->exec(); } ////////////////////////////////////////////////////////////////////////// EnzymesADVContext::EnzymesADVContext(QObject *p, const QList<QAction *> &actions) : GObjectViewWindowContext(p, ANNOTATED_DNA_VIEW_FACTORY_ID), cloningActions(actions) { } void EnzymesADVContext::initViewContext(GObjectView *view) { AnnotatedDNAView *av = qobject_cast<AnnotatedDNAView *>(view); ADVGlobalAction *a = new ADVGlobalAction(av, QIcon(":enzymes/images/enzymes.png"), tr("Find restriction sites..."), 50); a->setObjectName("Find restriction sites"); a->addAlphabetFilter(DNAAlphabet_NUCL); connect(a, SIGNAL(triggered()), SLOT(sl_search())); GObjectViewAction *createPCRProductAction = new GObjectViewAction(av, av, tr("Create PCR product...")); createPCRProductAction->setObjectName(CREATE_PCR_PRODUCT_ACTION_NAME); connect(createPCRProductAction, SIGNAL(triggered()), SLOT(sl_createPCRProduct())); addViewAction(createPCRProductAction); } void EnzymesADVContext::sl_search() { GObjectViewAction *action = qobject_cast<GObjectViewAction *>(sender()); assert(action != NULL); AnnotatedDNAView *av = qobject_cast<AnnotatedDNAView *>(action->getObjectView()); assert(av != NULL); ADVSequenceObjectContext *seqCtx = av->getSequenceInFocus(); assert(seqCtx->getAlphabet()->isNucleic()); QObjectScopedPointer<FindEnzymesDialog> d = new FindEnzymesDialog(seqCtx); d->exec(); } // TODO: move definitions to core #define PRIMER_ANNOTATION_GROUP_NAME "pair" #define PRIMER_ANNOTATION_NAME "primer" void EnzymesADVContext::buildMenu(GObjectView *v, QMenu *m) { AnnotatedDNAView *av = qobject_cast<AnnotatedDNAView *>(v); SAFE_POINT(NULL != av, "Invalid sequence view", ); CHECK(av->getSequenceInFocus()->getAlphabet()->isNucleic(), ); QMenu *cloningMenu = new QMenu(tr("Cloning"), m); cloningMenu->menuAction()->setObjectName("Cloning"); cloningMenu->addActions(cloningActions); QAction *exportMenuAction = GUIUtils::findAction(m->actions(), ADV_MENU_EXPORT); m->insertMenu(exportMenuAction, cloningMenu); if (!av->getAnnotationsSelection()->getAnnotations().isEmpty()) { Annotation *a = av->getAnnotationsSelection()->getAnnotations().first(); const QString annName = a->getName(); const QString groupName = a->getGroup()->getName(); const int annCount = a->getGroup()->getAnnotations().size(); if (annName == PRIMER_ANNOTATION_NAME && groupName.startsWith(PRIMER_ANNOTATION_GROUP_NAME) && 2 == annCount) { QAction *a = findViewAction(v, CREATE_PCR_PRODUCT_ACTION_NAME); SAFE_POINT(NULL != a, "Invalid menu action", ); cloningMenu->addAction(a); } } } void EnzymesADVContext::sl_createPCRProduct() { GObjectViewAction *action = qobject_cast<GObjectViewAction *>(sender()); SAFE_POINT(action != NULL, "Invalid action object!", ); AnnotatedDNAView *av = qobject_cast<AnnotatedDNAView *>(action->getObjectView()); SAFE_POINT(av != NULL, "Invalid DNA view!", ); const QList<Annotation *> &annotations = av->getAnnotationsSelection()->getAnnotations(); CHECK(!annotations.isEmpty(), ) Annotation *a = annotations.first(); AnnotationGroup *group = a->getGroup(); if (group->getName().startsWith(PRIMER_ANNOTATION_GROUP_NAME)) { SAFE_POINT(group->getAnnotations().size() == 2, "Invalid selected annotation count!", ); Annotation *a1 = group->getAnnotations().at(0); Annotation *a2 = group->getAnnotations().at(1); int startPos = a1->getLocation()->regions.at(0).startPos; SAFE_POINT(a2->getLocation()->strand == U2Strand::Complementary, "Invalid annotation's strand!", ); int endPos = a2->getLocation()->regions.at(0).endPos(); U2SequenceObject *seqObj = av->getSequenceInFocus()->getSequenceObject(); U2Region region(startPos, endPos - startPos); QObjectScopedPointer<CreateFragmentDialog> dlg = new CreateFragmentDialog(seqObj, region, av->getSequenceWidgetInFocus()); dlg->setWindowTitle("Create PCR product"); dlg->exec(); } } } // namespace U2
41.962687
192
0.719811
r-barnes
2144d745cb7793cdcf3192ce282aa7c44d78366f
1,027
cpp
C++
src/terminal/MockTerm.cpp
dandycheung/contour
1364ec488def8a0494503b9879b370b3669e81f9
[ "Apache-2.0" ]
404
2021-07-01T11:38:20.000Z
2022-03-31T19:16:18.000Z
src/terminal/MockTerm.cpp
dandycheung/contour
1364ec488def8a0494503b9879b370b3669e81f9
[ "Apache-2.0" ]
204
2021-07-01T10:10:01.000Z
2022-03-26T09:46:05.000Z
src/terminal/MockTerm.cpp
dandycheung/contour
1364ec488def8a0494503b9879b370b3669e81f9
[ "Apache-2.0" ]
38
2019-09-27T19:53:37.000Z
2021-07-01T09:47:44.000Z
/** * This file is part of the "libterminal" project * Copyright (c) 2019-2020 Christian Parpart <christian@parpart.family> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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 <terminal/MockTerm.h> #include <terminal/Screen.h> #include <crispy/App.h> #include <cstdlib> namespace terminal { MockTerm::MockTerm(PageSize _size, LineCount _hist): screen(_size, *this, false, false, _hist) { char const* logFilterString = getenv("LOG"); if (logFilterString) { logstore::configure(logFilterString); crispy::App::customizeLogStoreOutput(); } } } // namespace terminal
28.527778
94
0.723466
dandycheung
2149bb38100acbec14d976cefb541cbbc261dddf
3,832
cpp
C++
tests/iclBLAS/test_Icamin.cpp
intel/clGPU
bf099c547a17d12a81c23314a54fc7fe175a86a7
[ "Apache-2.0" ]
61
2018-02-20T06:01:50.000Z
2021-09-08T05:55:44.000Z
tests/iclBLAS/test_Icamin.cpp
intel/clGPU
bf099c547a17d12a81c23314a54fc7fe175a86a7
[ "Apache-2.0" ]
2
2018-04-21T06:59:30.000Z
2019-01-12T17:08:54.000Z
tests/iclBLAS/test_Icamin.cpp
intel/clGPU
bf099c547a17d12a81c23314a54fc7fe175a86a7
[ "Apache-2.0" ]
19
2018-02-19T17:18:04.000Z
2021-02-25T02:00:53.000Z
// Copyright (c) 2017-2018 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <gtest/gtest.h> #include <iclBLAS.h> TEST(Icamin, naive) { const int n = 128; const int incx = 1; oclComplex_t x[n * incx]; for (int i = 0; i < n; ++i) { x[i] = { i + 100.f, i + 100.f }; } x[55] = { -55.f, -55.f}; x[88] = { -55.f, -55.f}; x[99] = { -55.f, -55.f}; int result[1] = { 0 }; int ref = 55; iclblasHandle_t handle; iclblasStatus_t status = ICLBLAS_STATUS_SUCCESS; status = iclblasCreate(&handle); ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS); status = iclblasIcamin(handle, n, x, incx, result); ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS); status = iclblasDestroy(handle); ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS); EXPECT_EQ(ref, *result); } TEST(Icamin, opt_simd16) { const int n = 4096; const int incx = 1; oclComplex_t x[n * incx]; for (int i = 0; i < n * incx; ++i) { x[i] = { i + 100.f, i + 100.f }; } x[56] = { -55.f, -55.f}; x[88] = { -55.f, -55.f}; //Should omitt, lowest value but higher index x[99] = { -55.f, -55.f}; //Should omitt this lowest value as incx is 2 int result[1] = { 0 }; int ref = 56 / incx; iclblasHandle_t handle; iclblasStatus_t status = ICLBLAS_STATUS_SUCCESS; status = iclblasCreate(&handle); ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS); status = iclblasIcamin(handle, n, x, incx, result); ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS); status = iclblasDestroy(handle); ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS); EXPECT_EQ(ref, *result); } TEST(Icamin, opt_simd16_incx) { const int n = 4096; const int incx = 2; oclComplex_t x[n * incx]; for (int i = 0; i < n * incx; ++i) { x[i] = { i + 100.f, i + 100.f }; } x[55] = { -25.f, -25.f }; //Should omitt this lowest value as incx is 2 x[56] = { -55.f, -55.f }; x[88] = { -55.f, -55.f }; //Should omitt, lowest value but higher index x[99] = { -55.f, -55.f }; //Should omitt this lowest value as incx is 2 int result[1] = { 0 }; int ref = 56 / incx; iclblasHandle_t handle; iclblasStatus_t status = ICLBLAS_STATUS_SUCCESS; status = iclblasCreate(&handle); ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS); status = iclblasIcamin(handle, n, x, incx, result); ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS); status = iclblasDestroy(handle); ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS); EXPECT_EQ(ref, *result); } TEST(Icamin, opt_simd16_2stage) { const int n = 80000; const int incx = 1; oclComplex_t x[n * incx]; for (int i = 0; i < n * incx; ++i) { x[i] = { i + 100.f, i + 100.f }; } x[555] = {-20.f, -20.f}; x[1111] = {-20.f, -20.f}; x[79999] = {-20.f, -20.f}; int result[1] = { 0 }; int ref = 555; iclblasHandle_t handle; iclblasStatus_t status = ICLBLAS_STATUS_SUCCESS; status = iclblasCreate(&handle); ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS); status = iclblasIcamin(handle, n, x, incx, result); ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS); status = iclblasDestroy(handle); ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS); EXPECT_EQ(ref, *result); }
23.084337
75
0.615605
intel
214b8ca98d0ead4be58052703f42634928e0f03d
876
cpp
C++
android-31/javax/crypto/spec/GCMParameterSpec.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/javax/crypto/spec/GCMParameterSpec.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-29/javax/crypto/spec/GCMParameterSpec.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "../../../JByteArray.hpp" #include "./GCMParameterSpec.hpp" namespace javax::crypto::spec { // Fields // QJniObject forward GCMParameterSpec::GCMParameterSpec(QJniObject obj) : JObject(obj) {} // Constructors GCMParameterSpec::GCMParameterSpec(jint arg0, JByteArray arg1) : JObject( "javax.crypto.spec.GCMParameterSpec", "(I[B)V", arg0, arg1.object<jbyteArray>() ) {} GCMParameterSpec::GCMParameterSpec(jint arg0, JByteArray arg1, jint arg2, jint arg3) : JObject( "javax.crypto.spec.GCMParameterSpec", "(I[BII)V", arg0, arg1.object<jbyteArray>(), arg2, arg3 ) {} // Methods JByteArray GCMParameterSpec::getIV() const { return callObjectMethod( "getIV", "()[B" ); } jint GCMParameterSpec::getTLen() const { return callMethod<jint>( "getTLen", "()I" ); } } // namespace javax::crypto::spec
19.043478
85
0.660959
YJBeetle
214e9f5ce6327bebe9d5b15be003ba8b0ab70867
565
cpp
C++
2019-06/5 - Range generators.cpp
st-louis-cpp-meetup/Presentations
2e3a31a6285aabf295a9bf494bf7470844196857
[ "CC-BY-4.0" ]
2
2019-06-20T13:22:30.000Z
2020-03-05T01:19:19.000Z
2019-06/5 - Range generators.cpp
st-louis-cpp-meetup/Presentations
2e3a31a6285aabf295a9bf494bf7470844196857
[ "CC-BY-4.0" ]
null
null
null
2019-06/5 - Range generators.cpp
st-louis-cpp-meetup/Presentations
2e3a31a6285aabf295a9bf494bf7470844196857
[ "CC-BY-4.0" ]
null
null
null
//-std=c++2a -I/opt/compiler-explorer/libs/cmcstl2/include -fconcepts #include <iostream> #include <experimental/ranges/ranges> // from cmcstl2 namespace ranges = std::experimental::ranges; namespace view = std::experimental::ranges::view; //range generators (range adaptors) int main() { auto count_to_10 = view::iota(1, 11); auto one_int = view::single(37); auto no_ints = view::empty<int>; auto infinite_count = view::iota(1); auto only1234 = view::counted(infinite_count.begin(), 4); for (int x: count_to_10) { std::cout << x << " "; } }
28.25
69
0.684956
st-louis-cpp-meetup
2152b04ecd089a71683f2dc143d9592c6998b5ec
24,300
cpp
C++
plugins/protein/src/ToonRendererDeferred.cpp
reinago/megamol
0438e26e5134a0050a00c6d8d747175a08f85fd9
[ "BSD-3-Clause" ]
null
null
null
plugins/protein/src/ToonRendererDeferred.cpp
reinago/megamol
0438e26e5134a0050a00c6d8d747175a08f85fd9
[ "BSD-3-Clause" ]
null
null
null
plugins/protein/src/ToonRendererDeferred.cpp
reinago/megamol
0438e26e5134a0050a00c6d8d747175a08f85fd9
[ "BSD-3-Clause" ]
null
null
null
/* * ToonRendererDeferred.cpp * * Copyright (C) 2011 by Universitaet Stuttgart (VISUS). * All rights reserved. */ #include "stdafx.h" #include "mmcore/param/EnumParam.h" #include "mmcore/param/BoolParam.h" #include "mmcore/param/IntParam.h" #include "mmcore/param/FloatParam.h" #include "mmcore/view/CallRender3D.h" #include "mmcore/view/CallRenderDeferred3D.h" #include "mmcore/CoreInstance.h" #include "vislib/graphics/gl/ShaderSource.h" #include "mmcore/utility/log/Log.h" #include "ToonRendererDeferred.h" #include "vislib/graphics/gl/IncludeAllGL.h" using namespace megamol::protein; /* * ToonRendererDeferred::ToonRendererDeferred */ ToonRendererDeferred::ToonRendererDeferred(void) : megamol::core::view::AbstractRendererDeferred3D(), threshFineLinesParam("linesFine", "Threshold for fine silhouette."), threshCoarseLinesParam("linesCoarse", "Threshold for coarse silhouette."), ssaoParam("toggleSSAO", "Toggle Screen Space Ambient Occlusion."), ssaoRadiusParam("ssaoRadius", "Radius for SSAO samples."), illuminationParam("illumination", "Change local lighting."), colorParam("toggleColor", "Toggle coloring."), widthFBO(-1), heightFBO(-1) { // Threshold for fine lines this->threshFineLinesParam << new megamol::core::param::FloatParam(9.5f, 0.0f, 9.95f); this->MakeSlotAvailable(&this->threshFineLinesParam); // Threshold for coarse lines this->threshCoarseLinesParam << new megamol::core::param::FloatParam(7.9f, 0.0f, 9.95f); this->MakeSlotAvailable(&this->threshCoarseLinesParam); // Toggle SSAO this->ssaoParam << new megamol::core::param::BoolParam(false); this->MakeSlotAvailable(&this->ssaoParam); // Toggle local lighting megamol::core::param::EnumParam *illuParam = new megamol::core::param::EnumParam(0); illuParam->SetTypePair(0, "None"); illuParam->SetTypePair(1, "Phong-Shading"); illuParam->SetTypePair(2, "Toon-Shading"); this->illuminationParam << illuParam; this->MakeSlotAvailable(&illuminationParam); // Toggle coloring this->colorParam << new megamol::core::param::BoolParam(false); this->MakeSlotAvailable(&this->colorParam); // SSAO radius param this->ssaoRadiusParam << new megamol::core::param::FloatParam(1.0, 0.0); this->MakeSlotAvailable(&this->ssaoRadiusParam); } /* * ToonRendererDeferred::create */ bool ToonRendererDeferred::create(void) { vislib::graphics::gl::ShaderSource vertSrc; vislib::graphics::gl::ShaderSource fragSrc; // Init random number generator srand((unsigned)time(0)); // Create 4x4-texture with random rotation vectors if(!this->createRandomRotSampler()) { return false; } // Create sampling kernel if(!this->createRandomKernel(16)) { return false; } megamol::core::CoreInstance *ci = this->GetCoreInstance(); if(!ci) { return false; } if(!areExtsAvailable("GL_EXT_framebuffer_object GL_ARB_draw_buffers")) { return false; } if(!vislib::graphics::gl::GLSLShader::InitialiseExtensions()) { return false; } if(!isExtAvailable("GL_ARB_texture_non_power_of_two")) return false; // Try to load the gradient shader if(!ci->ShaderSourceFactory().MakeShaderSource("proteinDeferred::sobel::vertex", vertSrc)) { megamol::core::utility::log::Log::DefaultLog.WriteMsg(megamol::core::utility::log::Log::LEVEL_ERROR, "%s: Unable to load gradient vertex shader source", this->ClassName() ); return false; } if(!ci->ShaderSourceFactory().MakeShaderSource("proteinDeferred::sobel::fragment", fragSrc)) { megamol::core::utility::log::Log::DefaultLog.WriteMsg(megamol::core::utility::log::Log::LEVEL_ERROR, "%s: Unable to load gradient fragment shader source", this->ClassName() ); return false; } try { if(!this->sobelShader.Create(vertSrc.Code(), vertSrc.Count(), fragSrc.Code(), fragSrc.Count())) throw vislib::Exception("Generic creation failure", __FILE__, __LINE__); } catch(vislib::Exception &e){ megamol::core::utility::log::Log::DefaultLog.WriteMsg(megamol::core::utility::log::Log::LEVEL_ERROR, "%s: Unable to create shader: %s\n", this->ClassName(), e.GetMsgA()); return false; } // Try to load the ssao shader if(!ci->ShaderSourceFactory().MakeShaderSource("proteinDeferred::ssao::vertex", vertSrc)) { megamol::core::utility::log::Log::DefaultLog.WriteMsg(megamol::core::utility::log::Log::LEVEL_ERROR, "%s: Unable to load gradient vertex shader source", this->ClassName() ); return false; } if(!ci->ShaderSourceFactory().MakeShaderSource("proteinDeferred::ssao::fragment", fragSrc)) { megamol::core::utility::log::Log::DefaultLog.WriteMsg(megamol::core::utility::log::Log::LEVEL_ERROR, "%s: Unable to load gradient fragment shader source", this->ClassName() ); return false; } try { if(!this->ssaoShader.Create(vertSrc.Code(), vertSrc.Count(), fragSrc.Code(), fragSrc.Count())) throw vislib::Exception("Generic creation failure", __FILE__, __LINE__); } catch(vislib::Exception &e){ megamol::core::utility::log::Log::DefaultLog.WriteMsg(megamol::core::utility::log::Log::LEVEL_ERROR, "%s: Unable to create shader: %s\n", this->ClassName(), e.GetMsgA()); return false; } // Try to load the toon shader if(!ci->ShaderSourceFactory().MakeShaderSource("proteinDeferred::toon::vertex", vertSrc)) { megamol::core::utility::log::Log::DefaultLog.WriteMsg(megamol::core::utility::log::Log::LEVEL_ERROR, "%s: Unable to load toon vertex shader source", this->ClassName() ); return false; } if(!ci->ShaderSourceFactory().MakeShaderSource("proteinDeferred::toon::fragment", fragSrc)) { megamol::core::utility::log::Log::DefaultLog.WriteMsg(megamol::core::utility::log::Log::LEVEL_ERROR, "%s: Unable to load toon fragment shader source", this->ClassName() ); return false; } try { if(!this->toonShader.Create(vertSrc.Code(), vertSrc.Count(), fragSrc.Code(), fragSrc.Count())) throw vislib::Exception("Generic creation failure", __FILE__, __LINE__); } catch(vislib::Exception &e){ megamol::core::utility::log::Log::DefaultLog.WriteMsg(megamol::core::utility::log::Log::LEVEL_ERROR, "%s: Unable to create shader: %s\n", this->ClassName(), e.GetMsgA()); return false; } return true; } /* * ToonRendererDeferred::release */ void ToonRendererDeferred::release(void) { this->toonShader.Release(); this->sobelShader.Release(); this->ssaoShader.Release(); glDeleteTextures(1, &this->colorBuffer); glDeleteTextures(1, &this->normalBuffer); glDeleteTextures(1, &this->gradientBuffer); glDeleteTextures(1, &this->depthBuffer); glDeleteTextures(1, &this->ssaoBuffer); glDeleteTextures(1, &this->randomKernel); glDeleteTextures(1, &this->rotationSampler); glDeleteFramebuffers(1, &this->fbo); } /* * ToonRendererDeferred::~ToonRendererDeferred */ ToonRendererDeferred::~ToonRendererDeferred(void) { this->Release(); } /* * ToonRendererDeferred::GetExtents */ bool ToonRendererDeferred::GetExtents(megamol::core::Call& call) { megamol::core::view::CallRender3D *crIn = dynamic_cast< megamol::core::view::CallRender3D*>(&call); if(crIn == NULL) return false; megamol::core::view:: CallRenderDeferred3D *crOut = this->rendererSlot.CallAs< megamol::core::view::CallRenderDeferred3D>(); if(crOut == NULL) return false; // Call for getExtends if(!(*crOut)(core::view::AbstractCallRender::FnGetExtents)) return false; // Set extends of for incoming render call crIn->AccessBoundingBoxes() = crOut->GetBoundingBoxes(); crIn->SetLastFrameTime(crOut->LastFrameTime()); crIn->SetTimeFramesCount(crOut->TimeFramesCount()); return true; } /* * ToonRendererDeferred::Render */ bool ToonRendererDeferred::Render(megamol::core::Call& call) { if(!updateParams()) return false; megamol::core::view::CallRender3D *crIn = dynamic_cast< megamol::core::view::CallRender3D*>(&call); if(crIn == NULL) return false; megamol::core::view::CallRenderDeferred3D *crOut = this->rendererSlot.CallAs< megamol::core::view::CallRenderDeferred3D>(); if(crOut == NULL) return false; crOut->SetCameraParameters(crIn->GetCameraParameters()); // Set call time crOut->SetTime(crIn->Time()); float curVP[4]; glGetFloatv(GL_VIEWPORT, curVP); vislib::math::Vector<float, 3> ray(0, 0,-1); vislib::math::Vector<float, 3> up(0, 1, 0); vislib::math::Vector<float, 3> right(1, 0, 0); up *= sinf(crIn->GetCameraParameters()->HalfApertureAngle()); right *= sinf(crIn->GetCameraParameters()->HalfApertureAngle()) * curVP[2] / curVP[3]; // Recreate FBO if necessary if((curVP[2] != this->widthFBO) || (curVP[3] != this->heightFBO)) { if(!this->createFBO(static_cast<UINT>(curVP[2]), static_cast<UINT>(curVP[3]))) { return false; } this->widthFBO = (int)curVP[2]; this->heightFBO = (int)curVP[3]; } /// 1. Offscreen rendering /// // Enable rendering to FBO glBindFramebufferEXT(GL_FRAMEBUFFER, this->fbo); // Enable rendering to color attachents 0 and 1 GLenum mrt[] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1}; glDrawBuffers(2, mrt); glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, this->colorBuffer, 0); glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, this->normalBuffer, 0); glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, this->depthBuffer, 0); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Call for render (*crOut)(core::view::AbstractCallRender::FnRender); // Detach texture that are not needed anymore glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0); glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, 0, 0); glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0); // Prepare rendering screen quad glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glEnable(GL_TEXTURE_2D); glDisable(GL_DEPTH_TEST); /// 2. Calculate gradient using the sobel operator /// GLenum mrt2[] = {GL_COLOR_ATTACHMENT0}; glDrawBuffers(1, mrt2); glDepthMask(GL_FALSE); // Disable writing to depth buffer // Attach gradient texture glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, this->gradientBuffer, 0); this->sobelShader.Enable(); glUniform1i(this->sobelShader.ParameterLocation("depthBuffer"), 0); // Bind depth texture glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, this->depthBuffer); // Depth buffer // Draw glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex2f(-1.0f, -1.0f); glTexCoord2f(1, 0); glVertex2f(1.0f, -1.0f); glTexCoord2f(1, 1); glVertex2f(1.0f, 1.0f); glTexCoord2f(0, 1); glVertex2f(-1.0f, 1.0f); glEnd(); this->sobelShader.Disable(); glBindTexture(GL_TEXTURE_2D, 0); /// 3. Calculate ssao value if needed /// if(this->ssaoParam.Param<core::param::BoolParam>()->Value()) { // Attach ssao buffer glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, this->ssaoBuffer, 0); this->ssaoShader.Enable(); glUniform4f(this->ssaoShader.ParameterLocation("clip"), crIn->GetCameraParameters()->NearClip(), // Near crIn->GetCameraParameters()->FarClip(), // Far tan(crIn->GetCameraParameters()->HalfApertureAngle()) * crIn->GetCameraParameters()->NearClip(), // Top tan(crIn->GetCameraParameters()->HalfApertureAngle()) * crIn->GetCameraParameters()->NearClip() * curVP[2] / curVP[3]); // Right glUniform2f(this->ssaoShader.ParameterLocation("winSize"), curVP[2], curVP[3]); glUniform1i(this->ssaoShader.ParameterLocation("depthBuff"), 0); glUniform1i(this->ssaoShader.ParameterLocation("rotSampler"), 1); glUniform1i(this->ssaoShader.ParameterLocation("normalBuff"), 2); glUniform1f(this->ssaoShader.ParameterLocation("ssaoRadius"), this->ssaoRadiusParam.Param<core::param::FloatParam>()->Value()); // Bind depth texture glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, this->rotationSampler); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, this->normalBuffer); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, this->depthBuffer); // Draw glBegin(GL_QUADS); glNormal3fv((ray - right - up).PeekComponents()); glTexCoord2f(0, 0); glVertex2f(-1.0f, -1.0f); glNormal3fv((ray + right - up).PeekComponents()); glTexCoord2f(1, 0); glVertex2f(1.0f, -1.0f); glNormal3fv((ray + right + up).PeekComponents()); glTexCoord2f(1, 1); glVertex2f(1.0f, 1.0f); glNormal3fv((ray - right + up).PeekComponents()); glTexCoord2f(0, 1); glVertex2f(-1.0f, 1.0f); glEnd(); this->ssaoShader.Disable(); glBindTexture(GL_TEXTURE_2D, 0); } // Disable rendering to framebuffer glBindFramebufferEXT(GL_FRAMEBUFFER, 0); /// 4. Deferred shading /// glDepthMask(GL_TRUE); // Enable writing to depth buffer // Preserve the current framebuffer content (e.g. back of the bounding box) glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); this->toonShader.Enable(); glUniform2f(this->toonShader.ParameterLocation("clip"), crIn->GetCameraParameters()->NearClip(), crIn->GetCameraParameters()->FarClip()); glUniform2f(this->toonShader.ParameterLocation("winSize"), curVP[2], curVP[3]); glUniform1i(this->toonShader.ParameterLocation("depthBuffer"), 0); glUniform1i(this->toonShader.ParameterLocation("colorBuffer"), 1); glUniform1i(this->toonShader.ParameterLocation("normalBuffer"), 2); glUniform1i(this->toonShader.ParameterLocation("gradientBuffer"), 3); glUniform1i(this->toonShader.ParameterLocation("ssaoBuffer"), 4); glUniform1f(this->toonShader.ParameterLocation("threshFine"), (10.0f - this->threshFineLinesParam.Param<core::param::FloatParam>()->Value())*0.1f); glUniform1f(this->toonShader.ParameterLocation("threshCoarse"), (10.0f - this->threshCoarseLinesParam.Param<core::param::FloatParam>()->Value())*0.1f); glUniform1i(this->toonShader.ParameterLocation("ssao"), this->ssaoParam.Param<core::param::BoolParam>()->Value()); glUniform1i(this->toonShader.ParameterLocation("lighting"), this->illuminationParam.Param<core::param::EnumParam>()->Value()); glUniform1i(this->toonShader.ParameterLocation("withColor"), this->colorParam.Param<core::param::BoolParam>()->Value()); // Bind textures glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, this->colorBuffer); // Color buffer glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, this->normalBuffer); // Normal buffer glActiveTexture(GL_TEXTURE3); glBindTexture(GL_TEXTURE_2D, this->gradientBuffer); // Gradient buffer glActiveTexture(GL_TEXTURE4); glBindTexture(GL_TEXTURE_2D, this->ssaoBuffer); // SSAO buffer glGenerateMipmapEXT(GL_TEXTURE_2D); // Generate mip map levels for ssao texture glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, this->depthBuffer); // Depth buffer // Draw quad glBegin(GL_QUADS); glNormal3fv((ray - right - up).PeekComponents()); glTexCoord2f(0, 0); glVertex2f(-1.0f, -1.0f); glNormal3fv((ray + right - up).PeekComponents()); glTexCoord2f(1, 0); glVertex2f(1.0f, -1.0f); glNormal3fv((ray + right + up).PeekComponents()); glTexCoord2f(1, 1); glVertex2f(1.0f, 1.0f); glNormal3fv((ray - right + up).PeekComponents()); glTexCoord2f(0, 1); glVertex2f(-1.0f, 1.0f); glEnd(); this->toonShader.Disable(); glBindTexture(GL_TEXTURE_2D, 0); glDisable(GL_TEXTURE_2D); glEnable(GL_DEPTH_TEST); glDisable(GL_BLEND); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); return true; } /* * ToonRendererDeferred::createFBO */ bool ToonRendererDeferred::createFBO(UINT width, UINT height) { // Delete textures + fbo if necessary if(glIsFramebufferEXT(this->fbo)) { glDeleteTextures(1, &this->colorBuffer); glDeleteTextures(1, &this->normalBuffer); glDeleteTextures(1, &this->gradientBuffer); glDeleteTextures(1, &this->depthBuffer); glDeleteTextures(1, &this->ssaoBuffer); glDeleteFramebuffersEXT(1, &this->fbo); } glEnable(GL_TEXTURE_2D); glGenTextures(1, &this->colorBuffer); glBindTexture(GL_TEXTURE_2D, this->colorBuffer); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBindTexture(GL_TEXTURE_2D, 0); // Normal buffer glGenTextures(1, &this->normalBuffer); glBindTexture(GL_TEXTURE_2D, this->normalBuffer); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBindTexture(GL_TEXTURE_2D, 0); // Gradient buffer // TODO Texture format glGenTextures(1, &this->gradientBuffer); glBindTexture(GL_TEXTURE_2D, this->gradientBuffer); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBindTexture(GL_TEXTURE_2D, 0); // SSAO buffer // TODO Texture format glGenTextures(1, &this->ssaoBuffer); glBindTexture(GL_TEXTURE_2D, this->ssaoBuffer); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBindTexture(GL_TEXTURE_2D, 0); // Depth buffer glGenTextures(1, &this->depthBuffer); glBindTexture(GL_TEXTURE_2D, this->depthBuffer); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, width, height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, 0); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBindTexture(GL_TEXTURE_2D, 0); // Generate framebuffer glGenFramebuffersEXT(1, &this->fbo); GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER); if(status != GL_FRAMEBUFFER_COMPLETE) { megamol::core::utility::log::Log::DefaultLog.WriteMsg(megamol::core::utility::log::Log::LEVEL_ERROR, "Could not create FBO"); return false; } // Detach all textures glBindFramebufferEXT(GL_FRAMEBUFFER, 0); return true; } /* * ToonRendererDeferred::updateParams */ bool ToonRendererDeferred::updateParams() { return true; } /* * ToonRendererDeferred::createRandomRotSampler */ bool ToonRendererDeferred::createRandomRotSampler() { float data [4][4][3]; for(unsigned int s = 0; s < 4; s++) { for(unsigned int t = 0; t < 4; t++) { data[s][t][0] = getRandomFloat(-1.0, 1.0, 3); data[s][t][1] = getRandomFloat(-1.0, 1.0, 3); data[s][t][2] = 0.0; // Compute magnitude float mag = sqrt(data[s][t][0]*data[s][t][0] + data[s][t][1]*data[s][t][1] + data[s][t][2]*data[s][t][2]); // Normalize data[s][t][0] /= mag; data[s][t][1] /= mag; data[s][t][2] /= mag; // Map to range 0 ... 1 data[s][t][0] += 1.0; data[s][t][0] /= 2.0; data[s][t][1] += 1.0; data[s][t][1] /= 2.0; data[s][t][2] += 1.0; data[s][t][2] /= 2.0; } } glGenTextures(1, &this->rotationSampler); glBindTexture(GL_TEXTURE_2D, this->rotationSampler); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, 4, 4, 0, GL_RGB, GL_FLOAT, data); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glBindTexture(GL_TEXTURE_2D, 0); if(glGetError() != GL_NO_ERROR) return false; return true; } /* * ToonRendererDeferred::getRandomFloat */ float ToonRendererDeferred::getRandomFloat(float min, float max, unsigned int prec) { // Note: RAND_MAX is only guaranteed to be at least 32767, so prec should not be more than 4 float base = 10.0; float precision = pow(base, (int)prec); int range = (int)(max*precision - min*precision + 1); return static_cast<float>(rand()%range + min*precision) / precision; } /* * ToonRendererDeferred::::createRandomKernel */ // TODO enforce lower boundary to prevent numerical problems leading to artifacts bool ToonRendererDeferred::createRandomKernel(UINT size) { float *kernel; kernel = new float[size*3]; for(unsigned int s = 0; s < size; s++) { float scale = float(s) / float(size); scale *= scale; scale = 0.1f*(1.0f - scale) + scale; // Interpolate between 0.1 ... 1.0 kernel[s*3 + 0] = getRandomFloat(-1.0, 1.0, 3); kernel[s*3 + 1] = getRandomFloat(-1.0, 1.0, 3); kernel[s*3 + 2] = getRandomFloat( 0.0, 1.0, 3); // Compute magnitude float mag = sqrt(kernel[s*3 + 0]*kernel[s*3 + 0] + kernel[s*3 + 1]*kernel[s*3 + 1] + kernel[s*3 + 2]*kernel[s*3 + 2]); // Normalize kernel[s*3 + 0] /= mag; kernel[s*3 + 1] /= mag; kernel[s*3 + 2] /= mag; // Scale values kernel[s*3 + 0] *= scale; kernel[s*3 + 1] *= scale; kernel[s*3 + 2] *= scale; // Map values to range 0 ... 1 kernel[s*3 + 0] += 1.0; kernel[s*3 + 0] /= 2.0; kernel[s*3 + 1] += 1.0; kernel[s*3 + 1] /= 2.0; kernel[s*3 + 2] += 1.0; kernel[s*3 + 2] /= 2.0; } glGenTextures(1, &this->randomKernel); glBindTexture(GL_TEXTURE_2D, this->randomKernel); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, size, 1, 0, GL_RGB, GL_FLOAT, kernel); glBindTexture(GL_TEXTURE_2D, 0); delete[] kernel; if(glGetError() != GL_NO_ERROR) return false; return true; }
37.732919
144
0.672675
reinago
215435cad45bb8acd7b8cd20bc77538694699099
1,134
cpp
C++
luogu/p1067.cpp
ajidow/Answers_of_OJ
70e0c02d9367c3a154b83a277edbf158f32484a3
[ "MIT" ]
null
null
null
luogu/p1067.cpp
ajidow/Answers_of_OJ
70e0c02d9367c3a154b83a277edbf158f32484a3
[ "MIT" ]
null
null
null
luogu/p1067.cpp
ajidow/Answers_of_OJ
70e0c02d9367c3a154b83a277edbf158f32484a3
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main(int argc, char const *argv[]) { int power; cin >> power; int num[power+1]; // int i; for (i = 0; i < power+1; ++i) { cin >> num[i]; } // int sub = power; if (num[0] == 1){ cout << "x" << "^" << sub; }else if (num[0] == -1) { cout << "-x^" << sub; }else{ cout << num[0] << "x" << "^" << sub; } sub--; for (i = 1; i < power-1; ++i) { if ( num[i] != 1 && num[i] != -1 ){ if (num[i] > 0) { cout << "+" << num[i] << "x" << "^" << sub; }else if (num[i] < 0) { cout << num[i] << "x" << "^" << sub; } }else if (num[i] == 1) { cout << "+" << "x" << "^" << sub; }else if (num[i] == -1) { cout << "-" << "x" << "^" << sub; } sub--; } if (num[power-1] != 1 && num[power-1] != -1)\ { if (num[power-1] < 0) { cout << num[power-1] << "x"; }else if (num[power-1] > 0) { cout << "+" << num[power-1] << "x"; } }else if (num[power-1] == 1) { cout << "+x"; }else{ cout << "-x"; } if (num[power] > 0) { cout << "+" << num[power]; }else if (num[power] < 0) { cout << num[power]; } return 0; }
15.324324
47
0.395062
ajidow
21552ab246534cf24cf1ad5f67ad7ee779c09346
20,590
hpp
C++
libs/boost_1_72_0/boost/locale/message.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
libs/boost_1_72_0/boost/locale/message.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
libs/boost_1_72_0/boost/locale/message.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
// // Copyright (c) 2009-2011 Artyom Beilis (Tonkikh) // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #ifndef BOOST_LOCALE_MESSAGE_HPP_INCLUDED #define BOOST_LOCALE_MESSAGE_HPP_INCLUDED #include <boost/locale/config.hpp> #ifdef BOOST_MSVC #pragma warning(push) #pragma warning(disable : 4275 4251 4231 4660) #endif #include <boost/locale/formatting.hpp> #include <locale> #include <memory> #include <set> #include <string> #include <vector> // glibc < 2.3.4 declares those as macros if compiled with optimization turned // on #ifdef gettext #undef gettext #undef ngettext #undef dgettext #undef dngettext #endif namespace boost { namespace locale { /// /// \defgroup message Message Formatting (translation) /// /// This module provides message translation functionality, i.e. allow your /// application to speak native language /// /// @{ /// /// \cond INTERNAL template <typename CharType> struct base_message_format : public std::locale::facet {}; /// \endcond /// /// \brief This facet provides message formatting abilities /// template <typename CharType> class message_format : public base_message_format<CharType> { public: /// /// Character type /// typedef CharType char_type; /// /// String type /// typedef std::basic_string<CharType> string_type; /// /// Default constructor /// message_format(size_t refs = 0) : base_message_format<CharType>(refs) {} /// /// This function returns a pointer to the string for a message defined by a /// \a context and identification string \a id. Both create a single key for /// message lookup in a domain defined by \a domain_id. /// /// If \a context is NULL it is not considered to be a part of the key /// /// If a translated string is found, it is returned, otherwise NULL is /// returned /// /// virtual char_type const *get(int domain_id, char_type const *context, char_type const *id) const = 0; /// /// This function returns a pointer to the string for a plural message defined /// by a \a context and identification string \a single_id. /// /// If \a context is NULL it is not considered to be a part of the key /// /// Both create a single key for message lookup in /// a domain defined \a domain_id. \a n is used to pick the correct /// translation string for a specific number. /// /// If a translated string is found, it is returned, otherwise NULL is /// returned /// /// virtual char_type const *get(int domain_id, char_type const *context, char_type const *single_id, int n) const = 0; /// /// Convert a string that defines \a domain to the integer id used by \a get /// functions /// virtual int domain(std::string const &domain) const = 0; /// /// Convert the string \a msg to target locale's encoding. If \a msg is /// already in target encoding it would be returned otherwise the converted /// string is stored in temporary \a buffer and buffer.c_str() is returned. /// /// Note: for char_type that is char16_t, char32_t and wchar_t it is no-op, /// returns msg /// virtual char_type const *convert(char_type const *msg, string_type &buffer) const = 0; #if defined(__SUNPRO_CC) && defined(_RWSTD_VER) std::locale::id &__get_id(void) const { return id; } #endif protected: virtual ~message_format() {} }; /// \cond INTERNAL namespace details { inline bool is_us_ascii_char(char c) { // works for null terminated strings regardless char "signness" return 0 < c && c < 0x7F; } inline bool is_us_ascii_string(char const *msg) { while (*msg) { if (!is_us_ascii_char(*msg++)) return false; } return true; } template <typename CharType> struct string_cast_traits { static CharType const *cast(CharType const *msg, std::basic_string<CharType> & /*unused*/) { return msg; } }; template <> struct string_cast_traits<char> { static char const *cast(char const *msg, std::string &buffer) { if (is_us_ascii_string(msg)) return msg; buffer.reserve(strlen(msg)); char c; while ((c = *msg++) != 0) { if (is_us_ascii_char(c)) buffer += c; } return buffer.c_str(); } }; } // namespace details /// \endcond /// /// \brief This class represents a message that can be converted to a specific /// locale message /// /// It holds the original ASCII string that is queried in the dictionary when /// converting to the output string. The created string may be UTF-8, UTF-16, /// UTF-32 or other 8-bit encoded string according to the target character type /// and locale encoding. /// template <typename CharType> class basic_message { public: typedef CharType char_type; ///< The character this message object is used with typedef std::basic_string<char_type> string_type; ///< The string type this object can be used with typedef message_format<char_type> facet_type; ///< The type of the facet the messages are fetched with /// /// Create default empty message /// basic_message() : n_(0), c_id_(0), c_context_(0), c_plural_(0) {} /// /// Create a simple message from 0 terminated string. The string should exist /// until the message is destroyed. Generally useful with static constant /// strings /// explicit basic_message(char_type const *id) : n_(0), c_id_(id), c_context_(0), c_plural_(0) {} /// /// Create a simple plural form message from 0 terminated strings. The strings /// should exist until the message is destroyed. Generally useful with static /// constant strings. /// /// \a n is the number, \a single and \a plural are singular and plural forms /// of the message /// explicit basic_message(char_type const *single, char_type const *plural, int n) : n_(n), c_id_(single), c_context_(0), c_plural_(plural) {} /// /// Create a simple message from 0 terminated strings, with context /// information. The string should exist /// until the message is destroyed. Generally useful with static constant /// strings /// explicit basic_message(char_type const *context, char_type const *id) : n_(0), c_id_(id), c_context_(context), c_plural_(0) {} /// /// Create a simple plural form message from 0 terminated strings, with /// context. The strings should exist until the message is destroyed. /// Generally useful with static constant strings. /// /// \a n is the number, \a single and \a plural are singular and plural forms /// of the message /// explicit basic_message(char_type const *context, char_type const *single, char_type const *plural, int n) : n_(n), c_id_(single), c_context_(context), c_plural_(plural) {} /// /// Create a simple message from a string. /// explicit basic_message(string_type const &id) : n_(0), c_id_(0), c_context_(0), c_plural_(0), id_(id) {} /// /// Create a simple plural form message from strings. /// /// \a n is the number, \a single and \a plural are single and plural forms of /// the message /// explicit basic_message(string_type const &single, string_type const &plural, int number) : n_(number), c_id_(0), c_context_(0), c_plural_(0), id_(single), plural_(plural) {} /// /// Create a simple message from a string with context. /// explicit basic_message(string_type const &context, string_type const &id) : n_(0), c_id_(0), c_context_(0), c_plural_(0), id_(id), context_(context) {} /// /// Create a simple plural form message from strings. /// /// \a n is the number, \a single and \a plural are single and plural forms of /// the message /// explicit basic_message(string_type const &context, string_type const &single, string_type const &plural, int number) : n_(number), c_id_(0), c_context_(0), c_plural_(0), id_(single), context_(context), plural_(plural) {} /// /// Copy an object /// basic_message(basic_message const &other) : n_(other.n_), c_id_(other.c_id_), c_context_(other.c_context_), c_plural_(other.c_plural_), id_(other.id_), context_(other.context_), plural_(other.plural_) {} /// /// Assign other message object to this one /// basic_message const &operator=(basic_message const &other) { if (this == &other) { return *this; } basic_message tmp(other); swap(tmp); return *this; } /// /// Swap two message objects /// void swap(basic_message &other) { std::swap(n_, other.n_); std::swap(c_id_, other.c_id_); std::swap(c_context_, other.c_context_); std::swap(c_plural_, other.c_plural_); id_.swap(other.id_); context_.swap(other.context_); plural_.swap(other.plural_); } /// /// Message class can be explicitly converted to string class /// operator string_type() const { return str(); } /// /// Translate message to a string in the default global locale, using default /// domain /// string_type str() const { std::locale loc; return str(loc, 0); } /// /// Translate message to a string in the locale \a locale, using default /// domain /// string_type str(std::locale const &locale) const { return str(locale, 0); } /// /// Translate message to a string using locale \a locale and message domain \a /// domain_id /// string_type str(std::locale const &locale, std::string const &domain_id) const { int id = 0; if (std::has_facet<facet_type>(locale)) id = std::use_facet<facet_type>(locale).domain(domain_id); return str(locale, id); } /// /// Translate message to a string using the default locale and message domain /// \a domain_id /// string_type str(std::string const &domain_id) const { int id = 0; std::locale loc; if (std::has_facet<facet_type>(loc)) id = std::use_facet<facet_type>(loc).domain(domain_id); return str(loc, id); } /// /// Translate message to a string using locale \a loc and message domain index /// \a id /// string_type str(std::locale const &loc, int id) const { string_type buffer; char_type const *ptr = write(loc, id, buffer); if (ptr == buffer.c_str()) return buffer; else buffer = ptr; return buffer; } /// /// Translate message and write to stream \a out, using imbued locale and /// domain set to the stream /// void write(std::basic_ostream<char_type> &out) const { std::locale const &loc = out.getloc(); int id = ios_info::get(out).domain_id(); string_type buffer; out << write(loc, id, buffer); } private: char_type const *plural() const { if (c_plural_) return c_plural_; if (plural_.empty()) return 0; return plural_.c_str(); } char_type const *context() const { if (c_context_) return c_context_; if (context_.empty()) return 0; return context_.c_str(); } char_type const *id() const { return c_id_ ? c_id_ : id_.c_str(); } char_type const *write(std::locale const &loc, int domain_id, string_type &buffer) const { char_type const *translated = 0; static const char_type empty_string[1] = {0}; char_type const *id = this->id(); char_type const *context = this->context(); char_type const *plural = this->plural(); if (*id == 0) return empty_string; facet_type const *facet = 0; if (std::has_facet<facet_type>(loc)) facet = &std::use_facet<facet_type>(loc); if (facet) { if (!plural) { translated = facet->get(domain_id, context, id); } else { translated = facet->get(domain_id, context, id, n_); } } if (!translated) { char_type const *msg = plural ? (n_ == 1 ? id : plural) : id; if (facet) { translated = facet->convert(msg, buffer); } else { translated = details::string_cast_traits<char_type>::cast(msg, buffer); } } return translated; } /// members int n_; char_type const *c_id_; char_type const *c_context_; char_type const *c_plural_; string_type id_; string_type context_; string_type plural_; }; /// /// Convenience typedef for char /// typedef basic_message<char> message; /// /// Convenience typedef for wchar_t /// typedef basic_message<wchar_t> wmessage; #ifdef BOOST_LOCALE_ENABLE_CHAR16_T /// /// Convenience typedef for char16_t /// typedef basic_message<char16_t> u16message; #endif #ifdef BOOST_LOCALE_ENABLE_CHAR32_T /// /// Convenience typedef for char32_t /// typedef basic_message<char32_t> u32message; #endif /// /// Translate message \a msg and write it to stream /// template <typename CharType> std::basic_ostream<CharType> &operator<<(std::basic_ostream<CharType> &out, basic_message<CharType> const &msg) { msg.write(out); return out; } /// /// \anchor boost_locale_translate_family \name Indirect message translation /// function family /// @{ /// /// \brief Translate a message, \a msg is not copied /// template <typename CharType> inline basic_message<CharType> translate(CharType const *msg) { return basic_message<CharType>(msg); } /// /// \brief Translate a message in context, \a msg and \a context are not copied /// template <typename CharType> inline basic_message<CharType> translate(CharType const *context, CharType const *msg) { return basic_message<CharType>(context, msg); } /// /// \brief Translate a plural message form, \a single and \a plural are not /// copied /// template <typename CharType> inline basic_message<CharType> translate(CharType const *single, CharType const *plural, int n) { return basic_message<CharType>(single, plural, n); } /// /// \brief Translate a plural message from in constext, \a context, \a single /// and \a plural are not copied /// template <typename CharType> inline basic_message<CharType> translate(CharType const *context, CharType const *single, CharType const *plural, int n) { return basic_message<CharType>(context, single, plural, n); } /// /// \brief Translate a message, \a msg is copied /// template <typename CharType> inline basic_message<CharType> translate(std::basic_string<CharType> const &msg) { return basic_message<CharType>(msg); } /// /// \brief Translate a message in context,\a context and \a msg is copied /// template <typename CharType> inline basic_message<CharType> translate(std::basic_string<CharType> const &context, std::basic_string<CharType> const &msg) { return basic_message<CharType>(context, msg); } /// /// \brief Translate a plural message form in constext, \a context, \a single /// and \a plural are copied /// template <typename CharType> inline basic_message<CharType> translate(std::basic_string<CharType> const &context, std::basic_string<CharType> const &single, std::basic_string<CharType> const &plural, int n) { return basic_message<CharType>(context, single, plural, n); } /// /// \brief Translate a plural message form, \a single and \a plural are copied /// template <typename CharType> inline basic_message<CharType> translate(std::basic_string<CharType> const &single, std::basic_string<CharType> const &plural, int n) { return basic_message<CharType>(single, plural, n); } /// @} /// /// \anchor boost_locale_gettext_family \name Direct message translation /// functions family /// /// /// Translate message \a id according to locale \a loc /// template <typename CharType> std::basic_string<CharType> gettext(CharType const *id, std::locale const &loc = std::locale()) { return basic_message<CharType>(id).str(loc); } /// /// Translate plural form according to locale \a loc /// template <typename CharType> std::basic_string<CharType> ngettext(CharType const *s, CharType const *p, int n, std::locale const &loc = std::locale()) { return basic_message<CharType>(s, p, n).str(loc); } /// /// Translate message \a id according to locale \a loc in domain \a domain /// template <typename CharType> std::basic_string<CharType> dgettext(char const *domain, CharType const *id, std::locale const &loc = std::locale()) { return basic_message<CharType>(id).str(loc, domain); } /// /// Translate plural form according to locale \a loc in domain \a domain /// template <typename CharType> std::basic_string<CharType> dngettext(char const *domain, CharType const *s, CharType const *p, int n, std::locale const &loc = std::locale()) { return basic_message<CharType>(s, p, n).str(loc, domain); } /// /// Translate message \a id according to locale \a loc in context \a context /// template <typename CharType> std::basic_string<CharType> pgettext(CharType const *context, CharType const *id, std::locale const &loc = std::locale()) { return basic_message<CharType>(context, id).str(loc); } /// /// Translate plural form according to locale \a loc in context \a context /// template <typename CharType> std::basic_string<CharType> npgettext(CharType const *context, CharType const *s, CharType const *p, int n, std::locale const &loc = std::locale()) { return basic_message<CharType>(context, s, p, n).str(loc); } /// /// Translate message \a id according to locale \a loc in domain \a domain in /// context \a context /// template <typename CharType> std::basic_string<CharType> dpgettext(char const *domain, CharType const *context, CharType const *id, std::locale const &loc = std::locale()) { return basic_message<CharType>(context, id).str(loc, domain); } /// /// Translate plural form according to locale \a loc in domain \a domain in /// context \a context /// template <typename CharType> std::basic_string<CharType> dnpgettext(char const *domain, CharType const *context, CharType const *s, CharType const *p, int n, std::locale const &loc = std::locale()) { return basic_message<CharType>(context, s, p, n).str(loc, domain); } /// /// \cond INTERNAL /// template <> struct BOOST_LOCALE_DECL base_message_format<char> : public std::locale::facet { base_message_format(size_t refs = 0) : std::locale::facet(refs) {} static std::locale::id id; }; template <> struct BOOST_LOCALE_DECL base_message_format<wchar_t> : public std::locale::facet { base_message_format(size_t refs = 0) : std::locale::facet(refs) {} static std::locale::id id; }; #ifdef BOOST_LOCALE_ENABLE_CHAR16_T template <> struct BOOST_LOCALE_DECL base_message_format<char16_t> : public std::locale::facet { base_message_format(size_t refs = 0) : std::locale::facet(refs) {} static std::locale::id id; }; #endif #ifdef BOOST_LOCALE_ENABLE_CHAR32_T template <> struct BOOST_LOCALE_DECL base_message_format<char32_t> : public std::locale::facet { base_message_format(size_t refs = 0) : std::locale::facet(refs) {} static std::locale::id id; }; #endif /// \endcond /// /// @} /// namespace as { /// \cond INTERNAL namespace details { struct set_domain { std::string domain_id; }; template <typename CharType> std::basic_ostream<CharType> &operator<<(std::basic_ostream<CharType> &out, set_domain const &dom) { int id = std::use_facet<message_format<CharType>>(out.getloc()) .domain(dom.domain_id); ios_info::get(out).domain_id(id); return out; } } // namespace details /// \endcond /// /// \addtogroup manipulators /// /// @{ /// /// Manipulator for switching message domain in ostream, /// /// \note The returned object throws std::bad_cast if the I/O stream does not /// have \ref message_format facet installed /// inline #ifdef BOOST_LOCALE_DOXYGEN unspecified_type #else details::set_domain #endif domain(std::string const &id) { details::set_domain tmp = {id}; return tmp; } /// @} } // namespace as } // namespace locale } // namespace boost #ifdef BOOST_MSVC #pragma warning(pop) #endif #endif // vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
28.636996
80
0.657067
henrywarhurst
215e2ba19080e1f82bcc2a2e33d9b5e21c576525
1,538
cc
C++
fhiclcpp/test/types/searchAllowedConfiguration_t.cc
art-framework-suite/fhicl-cpp
302a8ca52dba4b922812ead406599cd535676252
[ "BSD-3-Clause" ]
null
null
null
fhiclcpp/test/types/searchAllowedConfiguration_t.cc
art-framework-suite/fhicl-cpp
302a8ca52dba4b922812ead406599cd535676252
[ "BSD-3-Clause" ]
2
2021-12-10T14:54:24.000Z
2022-03-25T16:33:23.000Z
fhiclcpp/test/types/searchAllowedConfiguration_t.cc
art-framework-suite/fhicl-cpp
302a8ca52dba4b922812ead406599cd535676252
[ "BSD-3-Clause" ]
null
null
null
#define BOOST_TEST_MODULE (search allowed configuration test) #include "boost/test/unit_test.hpp" #include "fhiclcpp/types/Atom.h" #include "fhiclcpp/types/Sequence.h" #include "fhiclcpp/types/Table.h" #include "fhiclcpp/types/Tuple.h" #include "fhiclcpp/types/detail/SearchAllowedConfiguration.h" #include <string> using namespace fhicl; using namespace fhicl::detail; using namespace std; auto supports_key = SearchAllowedConfiguration::supports_key; namespace { struct S { Atom<int> test{Name{"atom"}}; Sequence<int, 2> seq{Name{"sequence"}}; Tuple<int, double, bool> tuple{Name{"tuple"}}; struct U { Atom<int> test{Name{"nested_atom"}}; }; Tuple<Sequence<int, 2>, bool> tuple2{Name{"tuple2"}}; Table<U> table2{Name{"table2"}}; }; } BOOST_AUTO_TEST_SUITE(searchAllowedConfiguration_test) BOOST_AUTO_TEST_CASE(table_t) { Table<S> t{Name{"table"}}; BOOST_TEST(supports_key(t, "atom")); BOOST_TEST(!supports_key(t, "table.atom")); BOOST_TEST(!supports_key(t, "table.sequence")); BOOST_TEST(supports_key(t, "sequence")); BOOST_TEST(supports_key(t, "sequence[0]")); BOOST_TEST(!supports_key(t, "[0]")); BOOST_TEST(supports_key(t, "table2")); BOOST_TEST(supports_key(t, "tuple2[0][1]")); BOOST_TEST(supports_key(t, "tuple2[1]")); } BOOST_AUTO_TEST_CASE(seqInSeq_t) { Sequence<Sequence<int, 2>> s{Name{"nestedSequence"}}; BOOST_TEST(supports_key(s, "[0]")); BOOST_TEST(supports_key(s, "[0][0]")); BOOST_TEST(supports_key(s, "[0][1]")); } BOOST_AUTO_TEST_SUITE_END()
26.982456
61
0.708062
art-framework-suite
216191eae850363824975047adbcbd028eb99cc8
13,627
hpp
C++
engine/common/ShadersGL.hpp
ColinGilbert/noobwerkz-engine
f5670e98ca0dada8865be9ab82d25d3acf549ebe
[ "Apache-2.0" ]
23
2015-03-02T10:56:40.000Z
2021-01-27T03:32:49.000Z
engine/common/ShadersGL.hpp
ColinGilbert/noobwerkz-engine-borked
f5670e98ca0dada8865be9ab82d25d3acf549ebe
[ "Apache-2.0" ]
73
2015-04-14T09:39:05.000Z
2020-11-11T21:49:10.000Z
engine/common/ShadersGL.hpp
ColinGilbert/noobwerkz-engine-borked
f5670e98ca0dada8865be9ab82d25d3acf549ebe
[ "Apache-2.0" ]
3
2016-02-22T01:29:32.000Z
2018-01-02T06:07:12.000Z
#pragma once namespace noob { namespace glsl { //////////////////////////////////////////////////////////// // Extremely useful for getting rid of shader conditionals //////////////////////////////////////////////////////////// // http://theorangeduck.com/page/avoiding-shader-conditionals static const std::string shader_conditionals( "vec4 noob_when_eq(vec4 x, vec4 y) \n" "{ \n" " return 1.0 - abs(sign(x - y)); \n" "} \n" "vec4 noob_when_neq(vec4 x, vec4 y) \n" "{ \n" " return abs(sign(x - y)); \n" "} \n" "vec4 noob_when_gt(vec4 x, vec4 y) \n" "{ \n" " return max(sign(x - y), 0.0); \n" "} \n" "vec4 noob_when_lt(vec4 x, vec4 y) \n" "{ \n" " return min(1.0 - sign(x - y), 1.0); \n" "} \n" "vec4 noob_when_ge(vec4 x, vec4 y) \n" "{ \n" " return 1.0 - noob_when_lt(x, y); \n" "} \n" "vec4 noob_when_le(vec4 x, vec4 y) \n" "{ \n" " return 1.0 - noob_when_gt(x, y); \n" "} \n" "vec4 noob_and(vec4 a, vec4 b) \n" "{ \n" " return a * b; \n" "} \n" "vec4 noob_or(vec4 a, vec4 b) \n" "{ \n" " return min(a + b, 1.0); \n" "} \n" //"vec4 xor(vec4 a, vec4 b) \n" //"{ \n" //" return (a + b) % 2.0; \n" //"} \n" "vec4 noob_not(vec4 a) \n" "{ \n" " return 1.0 - a; \n" "} \n" "float noob_when_eq(float x, float y) \n" "{ \n" " return 1.0 - abs(sign(x - y)); \n" "} \n" "float noob_when_neq(float x, float y) \n" "{ \n" " return abs(sign(x - y)); \n" "} \n" "float noob_when_gt(float x, float y) \n" "{ \n" " return max(sign(x - y), 0.0); \n" "} \n" "float noob_when_lt(float x, float y) \n" "{ \n" " return min(1.0 - sign(x - y), 1.0); \n" "} \n" "float noob_when_ge(float x, float y) \n" "{ \n" " return 1.0 - noob_when_lt(x, y); \n" "} \n" "float noob_when_le(float x, float y) \n" "{ \n" " return 1.0 - noob_when_gt(x, y); \n" "} \n"); ////////////////////////////////// // Goes before every shader ////////////////////////////////// static const std::string shader_prefix( "#version 300 es \n" "precision mediump float; \n"); ////////////////////////// // Vertex shaders ////////////////////////// static const std::string vs_instancing_src = noob::concat(shader_prefix, std::string( "layout(location = 0) in vec4 a_pos; \n" "layout(location = 1) in vec4 a_normal; \n" "layout(location = 2) in vec4 a_vert_colour; \n" "layout(location = 3) in vec4 a_instance_colour; \n" "layout(location = 4) in mat4 a_model_mat; \n" "uniform mat4 view_matrix; \n" "uniform mat4 projection_matrix; \n" "out vec4 v_world_pos; \n" "out vec4 v_world_normal; \n" "out vec4 v_vert_colour; \n" "void main() \n" "{ \n" " v_world_pos = a_model_mat * a_pos; \n" " mat4 modelview_mat = view_matrix * a_model_mat; \n" " v_world_normal = a_model_mat * vec4(a_normal.xyz, 0); \n" " v_vert_colour = a_vert_colour * a_instance_colour; \n" " mat4 mvp_mat = projection_matrix * modelview_mat; \n" " gl_Position = mvp_mat * a_pos; \n" "} \n")); static const std::string vs_terrain_src = noob::concat(shader_prefix, std::string( "layout(location = 0) in vec4 a_pos; \n" "layout(location = 1) in vec4 a_normal; \n" "layout(location = 2) in vec4 a_vert_colour; \n" "out vec4 v_world_pos; \n" "out vec4 v_world_normal; \n" "out vec4 v_vert_colour; \n" "uniform mat4 mvp; \n" "uniform mat4 view_matrix; \n" "void main() \n" "{ \n" " v_world_pos = a_pos; \n" " v_world_normal = vec4(a_normal.xyz, 0); \n" " v_vert_colour = a_vert_colour; \n" " gl_Position = mvp * a_pos; \n" "} \n")); static const std::string vs_billboard_src = noob::concat(shader_prefix, std::string( "layout(location = 0) in vec4 a_pos_uv; \n" "layout(location = 1) in vec4 a_colour; \n" "out vec2 v_uv; \n" "out vec4 v_colour; \n" "void main() \n" "{ \n" " v_uv = vec2(a_pos_uv[2], a_pos_uv[3]); \n" " v_colour = a_colour; \n" " gl_Position = vec4(a_pos_uv[0], a_pos_uv[1], 0.0, 1.0); \n" "} \n")); ////////////////////////// // Fragment shaders ////////////////////////// static const std::string lambert_diffuse( "float lambert_diffuse(vec3 light_direction, vec3 surface_normal) \n" "{ \n" " return max(0.0, dot(light_direction, surface_normal)); \n" "} \n"); static const std::string blinn_phong_specular( "float blinn_phong_specular(vec3 light_direction, vec3 view_direction, vec3 surface_normal, float shininess) \n" "{ \n" " vec3 H = normalize(view_direction + light_direction); \n" " return pow(max(0.0, dot(surface_normal, H)), shininess); \n" "} \n"); static const std::string fs_instancing_src = noob::concat(shader_prefix, lambert_diffuse, blinn_phong_specular, std::string( "in vec4 v_world_pos; \n" "in vec4 v_world_normal; \n" "in vec4 v_vert_colour; \n" "layout (location = 0) out vec4 out_colour; \n" "uniform vec3 eye_pos; \n" "uniform vec3 directional_light; \n" "void main() \n" "{ \n" " vec3 view_direction = normalize(eye_pos - v_world_pos.xyz); \n" " float diffuse = lambert_diffuse(-directional_light, v_world_normal.xyz); \n" " float specular = blinn_phong_specular(-directional_light, -view_direction, v_world_normal.xyz, 10.0); \n" " float light = 0.1 + diffuse + specular; \n" " out_colour = vec4(clamp(v_vert_colour.xyz * light, 0.0, 1.0), 1.0); \n" "} \n")); static const std::string fs_terrain_src = noob::concat(shader_prefix, lambert_diffuse, blinn_phong_specular, shader_conditionals, std::string( "in vec4 v_world_pos; \n" "in vec4 v_world_normal; \n" "in vec4 v_vert_colour; \n" "layout(location = 0) out vec4 out_colour; \n" "uniform sampler2D texture_0; \n" "uniform vec4 colour_0; \n" "uniform vec4 colour_1; \n" "uniform vec4 colour_2; \n" "uniform vec4 colour_3; \n" "uniform vec3 blend_0; \n" "uniform vec2 blend_1; \n" "uniform vec3 tex_scales; \n" "uniform vec3 eye_pos; \n" "uniform vec3 directional_light; \n" "void main() \n" "{ \n" " vec3 normal_blend = normalize(max(abs(v_world_normal.xyz), 0.0001)); \n" " float b = normal_blend.x + normal_blend.y + normal_blend.z; \n" " normal_blend /= b; \n" // "RGB-only. Try it out for great wisdom! // "vec4 xaxis = vec4(1.0, 0.0, 0.0, 1.0); \n" // "vec4 yaxis = vec4(0.0, 1.0, 0.0, 1.0); \n" // "vec4 zaxis = vec4(0.0, 0.0, 1.0, 1.0); \n" " vec4 xaxis = vec4(texture(texture_0, v_world_pos.yz * tex_scales.x).rgb, 1.0); \n" " vec4 yaxis = vec4(texture(texture_0, v_world_pos.xz * tex_scales.y).rgb, 1.0); \n" " vec4 zaxis = vec4(texture(texture_0, v_world_pos.xy * tex_scales.z).rgb, 1.0); \n" " vec4 tex = xaxis * normal_blend.x + yaxis * normal_blend.y + zaxis * normal_blend.z; \n" " float tex_r = blend_0.x * tex.r; \n" " float tex_g = blend_0.y * tex.g; \n" " float tex_b = blend_0.z * tex.b; \n" " vec4 tex_weighted = vec4(tex_r, tex_g, tex_b, 1.0); \n" " float tex_falloff = (tex_r + tex_g + tex_b) * 0.3333; \n" " float ratio_0_to_1 = noob_when_le(tex_falloff, blend_1.x) * ((tex_falloff + blend_1.x) * 0.5); \n" " float ratio_1_to_2 = noob_when_le(tex_falloff, blend_1.y) * noob_when_gt(tex_falloff, blend_1.x) * ((tex_falloff + blend_1.y) * 0.5); \n" " float ratio_2_to_3 = noob_when_ge(tex_falloff, blend_1.y) * ((tex_falloff + 1.0) * 0.5); \n" " vec4 tex_final = ((colour_0 + colour_1) * ratio_0_to_1) + ((colour_1 + colour_2) * ratio_1_to_2) + ((colour_2 + colour_3) * ratio_2_to_3); \n" " vec3 view_direction = normalize(eye_pos - v_world_pos.xyz); \n" " float diffuse = lambert_diffuse(-directional_light, v_world_normal.xyz); \n" " float specular = blinn_phong_specular(-directional_light, -view_direction, v_world_normal.xyz, 10.0); \n" " float light = 0.1 + diffuse + specular; \n" " out_colour = vec4(clamp(tex_final.xyz * light, 0.0, 1.0), 1.0); \n" "} \n")); static const std::string fs_text_src = noob::concat(shader_prefix, std::string( "in vec2 v_uv; \n" "in vec4 v_colour; \n" "layout(location = 0) out vec4 out_colour; \n" "uniform sampler2D texture_0; \n" "void main() \n" "{ \n" " float f = texture(texture_0, v_uv).x; \n" " out_colour = vec4(v_colour.rgb, v_colour.a * f); \n" "} \n")); /* static std::string get_light( "vec3 get_light(vec3 world_pos, vec3 world_normal, vec3 eye_pos, vec3 light_pos, vec3 light_rgb) \n" "{ \n" " // vec3 normal = normalize(world_normal); \n" " vec3 view_direction = normalize(eye_pos - world_pos); \n" " vec3 light_direction = normalize(light_pos - world_pos); \n" " float light_distance = length(light_pos - world_pos); \n" " float falloff = attenuation_reid(light_pos, light_rgb, light_distance); \n" " // Uncomment to use orenNayar, cookTorrance, etc \n" " // float falloff = attenuation_madams(u_light_pos_r[ii].w, 0.5, light_distance); \n" " // float roughness = u_rough_albedo_fresnel.x; \n" " // float albedo = u_rough_albedo_fresnel.y; \n" " // float fresnel = u_rough_albedo_fresnel.z; \n" " float diffuse_coeff = lambert_diffuse(light_direction, world_normal); \n" " // float diffuse_coeff = oren+nayar_diffuse(light_direction, view_direction, world_normal, roughness, albedo); \n" " float diffuse = (diffuse_coeff * falloff); \n" " // float specular = 0.0; \n" " float specular = blinn_phong_specular(light_direction, view_direction, world_normal, u_shine); \n" " // float specular = cook_torrance_specular(light_direction, view_direction, world_normal, roughness, fresnel); \n" " vec3 light_colour = (diffuse + specular) * light_rgb; \n" " return light_colour; \n" "} \n"); static std::string vs_texture_2d_src( "#version 300 es \n" "layout(location = 0) in vec4 a_position; \n" "layout(location = 1) in vec2 a_texCoord; \n" "out vec2 v_texCoord; \n" "void main() \n" "{ \n" " gl_Position = a_position; \n" " v_texCoord = a_texCoord; \n" "} \n"); static std::string fs_texture_2d_src( "#version 300 es \n" "precision mediump float; \n" "in vec2 v_texCoord; \n" "layout(location = 0) out vec4 outColor; \n" "uniform sampler2D s_texture; \n" "void main() \n" "{ \n" " outColor = texture( s_texture, v_texCoord ); \n" "} \n"); static std::string vs_cubemap_src( "#version 300 es \n" "layout(location = 0) in vec4 a_position; \n" "layout(location = 1) in vec3 a_normal; \n" "out vec3 v_normal; \n" "void main() \n" "{ \n" " gl_Position = a_position; \n" " v_normal = a_normal; \n" "} \n"); static std::string fs_cubemap_src( "#version 300 es \n" "precision mediump float; \n" "in vec3 v_normal; \n" "layout(location = 0) out vec4 outColor; \n" "uniform samplerCube s_texture; \n" "void main() \n" "{ \n" " outColor = texture(s_texture, v_normal); \n" "} \n"); */ } }
44.825658
149
0.488736
ColinGilbert
2167af865b1236cabbe027af392640cc9abe4441
981
cpp
C++
ch15/test15_5.cpp
imshenzhuo/CppPrimer
87c74c0a36223e86571c2aedd9da428c06b04f4d
[ "CC0-1.0" ]
3
2019-09-21T13:03:57.000Z
2020-04-05T02:42:53.000Z
ch15/test15_5.cpp
imshenzhuo/CppPrimer
87c74c0a36223e86571c2aedd9da428c06b04f4d
[ "CC0-1.0" ]
null
null
null
ch15/test15_5.cpp
imshenzhuo/CppPrimer
87c74c0a36223e86571c2aedd9da428c06b04f4d
[ "CC0-1.0" ]
null
null
null
/************************************************************************* > File Name: test15_5.cpp > Author: shenzhuo > Mail: im.shenzhuo@gmail.com > Created Time: 2019年09月19日 星期四 09时59分30秒 ************************************************************************/ #include<iostream> using namespace std; class Base{ public: int base_public; protected: int base_protected; private: int base_private; }; class Pub_De : public Base { public: void f() { cout << base_protected << endl; } }; class Pri_De : private Base { public: void f() { cout << base_public << endl; cout << base_protected << endl; // cout << base_private << endl; } }; int main(int argc, char const *argv[]) { Pub_De pd; pd.base_public = 100; // error // pd.base_protected = 100; pd.f(); Pri_De ppd; // ppd.base_protected = 100; // ppd.base_public = 100; ppd.f(); return 0; }
17.210526
74
0.490316
imshenzhuo
2169d87f42c3bb36d5124a27fe42b92ffddc9bcf
9,994
cpp
C++
deepracer_follow_the_leader_ws/build/deepracer_interfaces_pkg/rosidl_typesupport_c/deepracer_interfaces_pkg/srv/nav_throttle_srv__type_support.cpp
amitjain-3/working_add
ddd3b10d854477e86bf7a8558b3d447ec03a8a5f
[ "Apache-2.0" ]
1
2022-03-11T20:15:27.000Z
2022-03-11T20:15:27.000Z
deepracer_follow_the_leader_ws/build/deepracer_interfaces_pkg/rosidl_typesupport_c/deepracer_interfaces_pkg/srv/nav_throttle_srv__type_support.cpp
amitjain-3/working_add
ddd3b10d854477e86bf7a8558b3d447ec03a8a5f
[ "Apache-2.0" ]
null
null
null
deepracer_follow_the_leader_ws/build/deepracer_interfaces_pkg/rosidl_typesupport_c/deepracer_interfaces_pkg/srv/nav_throttle_srv__type_support.cpp
amitjain-3/working_add
ddd3b10d854477e86bf7a8558b3d447ec03a8a5f
[ "Apache-2.0" ]
null
null
null
// generated from rosidl_typesupport_c/resource/idl__type_support.cpp.em // with input from deepracer_interfaces_pkg:srv/NavThrottleSrv.idl // generated code does not contain a copyright notice #include "cstddef" #include "rosidl_runtime_c/message_type_support_struct.h" #include "deepracer_interfaces_pkg/msg/rosidl_typesupport_c__visibility_control.h" #include "deepracer_interfaces_pkg/srv/detail/nav_throttle_srv__struct.h" #include "rosidl_typesupport_c/identifier.h" #include "rosidl_typesupport_c/message_type_support_dispatch.h" #include "rosidl_typesupport_c/type_support_map.h" #include "rosidl_typesupport_c/visibility_control.h" #include "rosidl_typesupport_interface/macros.h" namespace deepracer_interfaces_pkg { namespace srv { namespace rosidl_typesupport_c { typedef struct _NavThrottleSrv_Request_type_support_ids_t { const char * typesupport_identifier[2]; } _NavThrottleSrv_Request_type_support_ids_t; static const _NavThrottleSrv_Request_type_support_ids_t _NavThrottleSrv_Request_message_typesupport_ids = { { "rosidl_typesupport_fastrtps_c", // ::rosidl_typesupport_fastrtps_c::typesupport_identifier, "rosidl_typesupport_introspection_c", // ::rosidl_typesupport_introspection_c::typesupport_identifier, } }; typedef struct _NavThrottleSrv_Request_type_support_symbol_names_t { const char * symbol_name[2]; } _NavThrottleSrv_Request_type_support_symbol_names_t; #define STRINGIFY_(s) #s #define STRINGIFY(s) STRINGIFY_(s) static const _NavThrottleSrv_Request_type_support_symbol_names_t _NavThrottleSrv_Request_message_typesupport_symbol_names = { { STRINGIFY(ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_fastrtps_c, deepracer_interfaces_pkg, srv, NavThrottleSrv_Request)), STRINGIFY(ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_introspection_c, deepracer_interfaces_pkg, srv, NavThrottleSrv_Request)), } }; typedef struct _NavThrottleSrv_Request_type_support_data_t { void * data[2]; } _NavThrottleSrv_Request_type_support_data_t; static _NavThrottleSrv_Request_type_support_data_t _NavThrottleSrv_Request_message_typesupport_data = { { 0, // will store the shared library later 0, // will store the shared library later } }; static const type_support_map_t _NavThrottleSrv_Request_message_typesupport_map = { 2, "deepracer_interfaces_pkg", &_NavThrottleSrv_Request_message_typesupport_ids.typesupport_identifier[0], &_NavThrottleSrv_Request_message_typesupport_symbol_names.symbol_name[0], &_NavThrottleSrv_Request_message_typesupport_data.data[0], }; static const rosidl_message_type_support_t NavThrottleSrv_Request_message_type_support_handle = { rosidl_typesupport_c__typesupport_identifier, reinterpret_cast<const type_support_map_t *>(&_NavThrottleSrv_Request_message_typesupport_map), rosidl_typesupport_c__get_message_typesupport_handle_function, }; } // namespace rosidl_typesupport_c } // namespace srv } // namespace deepracer_interfaces_pkg #ifdef __cplusplus extern "C" { #endif ROSIDL_TYPESUPPORT_C_EXPORT_deepracer_interfaces_pkg const rosidl_message_type_support_t * ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_c, deepracer_interfaces_pkg, srv, NavThrottleSrv_Request)() { return &::deepracer_interfaces_pkg::srv::rosidl_typesupport_c::NavThrottleSrv_Request_message_type_support_handle; } #ifdef __cplusplus } #endif // already included above // #include "cstddef" // already included above // #include "rosidl_runtime_c/message_type_support_struct.h" // already included above // #include "deepracer_interfaces_pkg/msg/rosidl_typesupport_c__visibility_control.h" // already included above // #include "deepracer_interfaces_pkg/srv/detail/nav_throttle_srv__struct.h" // already included above // #include "rosidl_typesupport_c/identifier.h" // already included above // #include "rosidl_typesupport_c/message_type_support_dispatch.h" // already included above // #include "rosidl_typesupport_c/type_support_map.h" // already included above // #include "rosidl_typesupport_c/visibility_control.h" // already included above // #include "rosidl_typesupport_interface/macros.h" namespace deepracer_interfaces_pkg { namespace srv { namespace rosidl_typesupport_c { typedef struct _NavThrottleSrv_Response_type_support_ids_t { const char * typesupport_identifier[2]; } _NavThrottleSrv_Response_type_support_ids_t; static const _NavThrottleSrv_Response_type_support_ids_t _NavThrottleSrv_Response_message_typesupport_ids = { { "rosidl_typesupport_fastrtps_c", // ::rosidl_typesupport_fastrtps_c::typesupport_identifier, "rosidl_typesupport_introspection_c", // ::rosidl_typesupport_introspection_c::typesupport_identifier, } }; typedef struct _NavThrottleSrv_Response_type_support_symbol_names_t { const char * symbol_name[2]; } _NavThrottleSrv_Response_type_support_symbol_names_t; #define STRINGIFY_(s) #s #define STRINGIFY(s) STRINGIFY_(s) static const _NavThrottleSrv_Response_type_support_symbol_names_t _NavThrottleSrv_Response_message_typesupport_symbol_names = { { STRINGIFY(ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_fastrtps_c, deepracer_interfaces_pkg, srv, NavThrottleSrv_Response)), STRINGIFY(ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_introspection_c, deepracer_interfaces_pkg, srv, NavThrottleSrv_Response)), } }; typedef struct _NavThrottleSrv_Response_type_support_data_t { void * data[2]; } _NavThrottleSrv_Response_type_support_data_t; static _NavThrottleSrv_Response_type_support_data_t _NavThrottleSrv_Response_message_typesupport_data = { { 0, // will store the shared library later 0, // will store the shared library later } }; static const type_support_map_t _NavThrottleSrv_Response_message_typesupport_map = { 2, "deepracer_interfaces_pkg", &_NavThrottleSrv_Response_message_typesupport_ids.typesupport_identifier[0], &_NavThrottleSrv_Response_message_typesupport_symbol_names.symbol_name[0], &_NavThrottleSrv_Response_message_typesupport_data.data[0], }; static const rosidl_message_type_support_t NavThrottleSrv_Response_message_type_support_handle = { rosidl_typesupport_c__typesupport_identifier, reinterpret_cast<const type_support_map_t *>(&_NavThrottleSrv_Response_message_typesupport_map), rosidl_typesupport_c__get_message_typesupport_handle_function, }; } // namespace rosidl_typesupport_c } // namespace srv } // namespace deepracer_interfaces_pkg #ifdef __cplusplus extern "C" { #endif ROSIDL_TYPESUPPORT_C_EXPORT_deepracer_interfaces_pkg const rosidl_message_type_support_t * ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_c, deepracer_interfaces_pkg, srv, NavThrottleSrv_Response)() { return &::deepracer_interfaces_pkg::srv::rosidl_typesupport_c::NavThrottleSrv_Response_message_type_support_handle; } #ifdef __cplusplus } #endif // already included above // #include "cstddef" #include "rosidl_runtime_c/service_type_support_struct.h" // already included above // #include "deepracer_interfaces_pkg/msg/rosidl_typesupport_c__visibility_control.h" // already included above // #include "rosidl_typesupport_c/identifier.h" #include "rosidl_typesupport_c/service_type_support_dispatch.h" // already included above // #include "rosidl_typesupport_c/type_support_map.h" // already included above // #include "rosidl_typesupport_interface/macros.h" namespace deepracer_interfaces_pkg { namespace srv { namespace rosidl_typesupport_c { typedef struct _NavThrottleSrv_type_support_ids_t { const char * typesupport_identifier[2]; } _NavThrottleSrv_type_support_ids_t; static const _NavThrottleSrv_type_support_ids_t _NavThrottleSrv_service_typesupport_ids = { { "rosidl_typesupport_fastrtps_c", // ::rosidl_typesupport_fastrtps_c::typesupport_identifier, "rosidl_typesupport_introspection_c", // ::rosidl_typesupport_introspection_c::typesupport_identifier, } }; typedef struct _NavThrottleSrv_type_support_symbol_names_t { const char * symbol_name[2]; } _NavThrottleSrv_type_support_symbol_names_t; #define STRINGIFY_(s) #s #define STRINGIFY(s) STRINGIFY_(s) static const _NavThrottleSrv_type_support_symbol_names_t _NavThrottleSrv_service_typesupport_symbol_names = { { STRINGIFY(ROSIDL_TYPESUPPORT_INTERFACE__SERVICE_SYMBOL_NAME(rosidl_typesupport_fastrtps_c, deepracer_interfaces_pkg, srv, NavThrottleSrv)), STRINGIFY(ROSIDL_TYPESUPPORT_INTERFACE__SERVICE_SYMBOL_NAME(rosidl_typesupport_introspection_c, deepracer_interfaces_pkg, srv, NavThrottleSrv)), } }; typedef struct _NavThrottleSrv_type_support_data_t { void * data[2]; } _NavThrottleSrv_type_support_data_t; static _NavThrottleSrv_type_support_data_t _NavThrottleSrv_service_typesupport_data = { { 0, // will store the shared library later 0, // will store the shared library later } }; static const type_support_map_t _NavThrottleSrv_service_typesupport_map = { 2, "deepracer_interfaces_pkg", &_NavThrottleSrv_service_typesupport_ids.typesupport_identifier[0], &_NavThrottleSrv_service_typesupport_symbol_names.symbol_name[0], &_NavThrottleSrv_service_typesupport_data.data[0], }; static const rosidl_service_type_support_t NavThrottleSrv_service_type_support_handle = { rosidl_typesupport_c__typesupport_identifier, reinterpret_cast<const type_support_map_t *>(&_NavThrottleSrv_service_typesupport_map), rosidl_typesupport_c__get_service_typesupport_handle_function, }; } // namespace rosidl_typesupport_c } // namespace srv } // namespace deepracer_interfaces_pkg #ifdef __cplusplus extern "C" { #endif ROSIDL_TYPESUPPORT_C_EXPORT_deepracer_interfaces_pkg const rosidl_service_type_support_t * ROSIDL_TYPESUPPORT_INTERFACE__SERVICE_SYMBOL_NAME(rosidl_typesupport_c, deepracer_interfaces_pkg, srv, NavThrottleSrv)() { return &::deepracer_interfaces_pkg::srv::rosidl_typesupport_c::NavThrottleSrv_service_type_support_handle; } #ifdef __cplusplus } #endif
33.877966
157
0.843606
amitjain-3
216aa3a32caa8ada6f2adda842ffc176e2b4676a
1,491
cpp
C++
libnd4j/include/helpers/impl/ProviderRNG.cpp
KolyaIvankov/deeplearning4j
61c02d31fa950259d7458a021de7db167a3410ae
[ "Apache-2.0" ]
null
null
null
libnd4j/include/helpers/impl/ProviderRNG.cpp
KolyaIvankov/deeplearning4j
61c02d31fa950259d7458a021de7db167a3410ae
[ "Apache-2.0" ]
null
null
null
libnd4j/include/helpers/impl/ProviderRNG.cpp
KolyaIvankov/deeplearning4j
61c02d31fa950259d7458a021de7db167a3410ae
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://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. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ // // Created by Yurii Shyrma on 27.01.2018 // #include <helpers/ProviderRNG.h> #include <NativeOps.h> namespace nd4j { ProviderRNG::ProviderRNG() { Nd4jLong *buffer = new Nd4jLong[100000]; std::lock_guard<std::mutex> lock(_mutex); #ifndef __CUDABLAS__ // at this moment we don't have streams etc, so let's just skip this for now _rng = (nd4j::random::RandomBuffer *) initRandom(nullptr, 123, 100000, (Nd4jPointer) buffer); #endif // if(_rng != nullptr) } ProviderRNG& ProviderRNG::getInstance() { static ProviderRNG instance; return instance; } random::RandomBuffer* ProviderRNG::getRNG() const { return _rng; } std::mutex ProviderRNG::_mutex; }
28.673077
101
0.625755
KolyaIvankov
2173d652f61867037b50442277f36bca9603f213
2,651
cpp
C++
libs/lfd/src/resource_file.cpp
tiaanl/red5
ea7593b38f61f64f8aeb7d58854106bd58c05736
[ "MIT" ]
1
2020-11-24T13:26:11.000Z
2020-11-24T13:26:11.000Z
libs/lfd/src/resource_file.cpp
tiaanl/red5
ea7593b38f61f64f8aeb7d58854106bd58c05736
[ "MIT" ]
null
null
null
libs/lfd/src/resource_file.cpp
tiaanl/red5
ea7593b38f61f64f8aeb7d58854106bd58c05736
[ "MIT" ]
null
null
null
#include "lfd/resource_file.h" #include <base/streams/file_input_stream.h> #include <base/streams/file_output_stream.h> std::vector<ResourceEntry> ResourceFile::loadEntries() const { if (!std::filesystem::exists(m_path)) { spdlog::error("Resource file not found: {}", m_path.string()); return {}; } spdlog::info("Loading entries from resource file: {}", m_path.string()); base::FileInputStream stream{m_path}; // TODO: Check if the file was opened successfully. // Read ResourceMap header. auto type = static_cast<ResourceType>(stream.readU32()); if (type != ResourceType::ResourceMap) { spdlog::error("Invalid LFD file. ({})", m_path.string()); return {}; } U8 name[9] = {}; stream.read(name, 8); U32 size = stream.readU32(); #if 0 spdlog::info("ResourceMap :: type: {}, name: {}, size: {}", resourceTypeToString(type), name, size); #endif // 0 // Skip the header block and get the details from the individual resource headers. stream.advance(size); std::vector<ResourceEntry> entries; for (MemSize i = 0; i < size / 16; ++i) { auto resource = readResourceEntry(&stream); if (resource.has_value()) { #if 0 spdlog::info("entry: ({}) {}", resourceTypeToString(resource.value().type()), resource.value().name()); #endif // 0 entries.emplace_back(std::move(resource.value())); } } return entries; } // static std::optional<ResourceEntry> ResourceFile::readResourceEntry(base::InputStream* stream) { ResourceType type = static_cast<ResourceType>(stream->readU32()); char name[9] = {}; stream->read(name, 8); U32 size = stream->readU32(); std::vector<U8> data; data.resize(size); stream->read(data.data(), size); return ResourceEntry{type, name, std::move(data)}; } void writeHeader(base::OutputStream* stream, ResourceType resourceType, std::string_view name, MemSize size) { stream->writeU32(static_cast<U32>(resourceType)); U8 nameBuf[8] = {}; std::memcpy(nameBuf, name.data(), std::min(name.length(), sizeof(nameBuf))); stream->write(nameBuf, sizeof(nameBuf)); stream->writeU32(static_cast<U32>(size)); } void ResourceFile::saveEntries(const std::vector<ResourceEntry>& entries) { base::FileOutputStream stream{m_path}; writeHeader(&stream, ResourceType::ResourceMap, "resource", entries.size() * 16); for (auto& entry : entries) { writeHeader(&stream, entry.type(), entry.name(), entry.data().size()); } for (auto& entry : entries) { writeHeader(&stream, entry.type(), entry.name(), entry.data().size()); stream.write(entry.data().data(), entry.data().size()); } }
29.786517
102
0.6639
tiaanl
2175d53d0705dd963399a9aa73bb84b81a9ecb1c
1,056
cpp
C++
source/System/ThreadPool/ThreadPool.cpp
Fabrice-Praxinos/ULIS
232ad5c0804da1202d8231fda67ff4aea70f57ef
[ "RSA-MD" ]
30
2020-09-16T17:39:36.000Z
2022-02-17T08:32:53.000Z
source/System/ThreadPool/ThreadPool.cpp
Fabrice-Praxinos/ULIS
232ad5c0804da1202d8231fda67ff4aea70f57ef
[ "RSA-MD" ]
7
2020-11-23T14:37:15.000Z
2022-01-17T11:35:32.000Z
source/System/ThreadPool/ThreadPool.cpp
Fabrice-Praxinos/ULIS
232ad5c0804da1202d8231fda67ff4aea70f57ef
[ "RSA-MD" ]
5
2020-09-17T00:39:14.000Z
2021-08-30T16:14:07.000Z
// IDDN FR.001.250001.004.S.X.2019.000.00000 // ULIS is subject to copyright laws and is the legal and intellectual property of Praxinos,Inc /* * ULIS *__________________ * @file ThreadPool.cpp * @author Clement Berthaud * @brief This file provides the definition for the FThreadPool class. * @copyright Copyright 2018-2021 Praxinos, Inc. All Rights Reserved. * @license Please refer to LICENSE.md */ #include "System/ThreadPool/ThreadPool.h" #include "System/ThreadPool/ThreadPool_Private.h" ULIS_NAMESPACE_BEGIN FThreadPool::~FThreadPool() { delete d; } FThreadPool::FThreadPool( uint32 iNumWorkers ) : d( new FThreadPool_Private( iNumWorkers ) ) { } void FThreadPool::WaitForCompletion() { d->WaitForCompletion(); } void FThreadPool::SetNumWorkers( uint32 iNumWorkers ) { d->SetNumWorkers( iNumWorkers ); } uint32 FThreadPool::GetNumWorkers() const { return d->GetNumWorkers(); } //static uint32 FThreadPool::MaxWorkers() { return FThreadPool_Private::MaxWorkers(); } ULIS_NAMESPACE_END
19.924528
95
0.726326
Fabrice-Praxinos
2176fc5c1440deffd1d7d730d1a7a59bbbaadeda
15,840
cpp
C++
src/mame/drivers/mjsister.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
26
2015-03-31T06:25:51.000Z
2021-12-14T09:29:04.000Z
src/mame/drivers/mjsister.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
null
null
null
src/mame/drivers/mjsister.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
10
2015-03-27T05:45:51.000Z
2022-02-04T06:57:36.000Z
// license:BSD-3-Clause // copyright-holders:Uki /***************************************************************************** Mahjong Sisters (c) 1986 Toa Plan Driver by Uki *****************************************************************************/ #include "emu.h" #include "cpu/z80/z80.h" #include "machine/74259.h" #include "video/mc6845.h" #include "sound/ay8910.h" #include "sound/dac.h" #include "emupal.h" #include "screen.h" #include "speaker.h" #define MCLK 12000000 class mjsister_state : public driver_device { public: mjsister_state(const machine_config &mconfig, device_type type, const char *tag) : driver_device(mconfig, type, tag), m_maincpu(*this, "maincpu"), m_mainlatch(*this, "mainlatch%u", 1), m_palette(*this, "palette"), m_crtc(*this, "crtc"), m_dac(*this, "dac"), m_rombank(*this, "rombank"), m_vrambank(*this, "vrambank") { } void mjsister(machine_config &config); protected: virtual void machine_start() override; virtual void machine_reset() override; virtual void device_timer(emu_timer &timer, device_timer_id id, int param, void *ptr) override; private: enum { TIMER_DAC }; /* video-related */ bool m_video_enable; int m_colorbank; /* misc */ int m_input_sel1; int m_input_sel2; bool m_irq_enable; uint32_t m_dac_adr; uint32_t m_dac_bank; uint32_t m_dac_adr_s; uint32_t m_dac_adr_e; uint32_t m_dac_busy; /* devices */ required_device<cpu_device> m_maincpu; required_device_array<ls259_device, 2> m_mainlatch; required_device<palette_device> m_palette; required_device<hd6845s_device> m_crtc; required_device<dac_byte_interface> m_dac; /* memory */ required_memory_bank m_rombank; required_memory_bank m_vrambank; std::unique_ptr<uint8_t[]> m_vram; void dac_adr_s_w(uint8_t data); void dac_adr_e_w(uint8_t data); DECLARE_WRITE_LINE_MEMBER(rombank_w); DECLARE_WRITE_LINE_MEMBER(flip_screen_w); DECLARE_WRITE_LINE_MEMBER(colorbank_w); DECLARE_WRITE_LINE_MEMBER(video_enable_w); DECLARE_WRITE_LINE_MEMBER(irq_enable_w); DECLARE_WRITE_LINE_MEMBER(vrambank_w); DECLARE_WRITE_LINE_MEMBER(dac_bank_w); DECLARE_WRITE_LINE_MEMBER(coin_counter_w); void input_sel1_w(uint8_t data); void input_sel2_w(uint8_t data); uint8_t keys_r(); TIMER_CALLBACK_MEMBER(dac_callback); INTERRUPT_GEN_MEMBER(interrupt); uint32_t screen_update(screen_device &screen, bitmap_rgb32 &bitmap, const rectangle &cliprect); void mjsister_io_map(address_map &map); void mjsister_map(address_map &map); emu_timer *m_dac_timer; MC6845_UPDATE_ROW(crtc_update_row); }; /************************************* * * Video emulation * *************************************/ uint32_t mjsister_state::screen_update(screen_device &screen, bitmap_rgb32 &bitmap, const rectangle &cliprect) { if (m_video_enable) m_crtc->screen_update(screen, bitmap, cliprect); else bitmap.fill(m_palette->black_pen(), cliprect); return 0; } MC6845_UPDATE_ROW( mjsister_state::crtc_update_row ) { const pen_t *pen = m_palette->pens(); if (flip_screen()) y = 240 - y; for (int i = 0; i < x_count; i++) { uint8_t x1 = i * 2 + 0; uint8_t x2 = i * 2 + 1; if (flip_screen()) { x1 = 256 - x1; x2 = 256 - x2; } // background layer uint8_t data_bg = m_vram[0x400 + ((ma << 3) | (ra << 7) | i)]; bitmap.pix(y, x1) = pen[m_colorbank << 5 | ((data_bg & 0x0f) >> 0)]; bitmap.pix(y, x2) = pen[m_colorbank << 5 | ((data_bg & 0xf0) >> 4)]; // foreground layer uint8_t data_fg = m_vram[0x8000 | (0x400 + ((ma << 3) | (ra << 7) | i))]; uint8_t c1 = ((data_fg & 0x0f) >> 0); uint8_t c2 = ((data_fg & 0xf0) >> 4); // 0 is transparent if (c1) bitmap.pix(y, x1) = pen[m_colorbank << 5 | 0x10 | c1]; if (c2) bitmap.pix(y, x2) = pen[m_colorbank << 5 | 0x10 | c2]; } } /************************************* * * Memory handlers * *************************************/ void mjsister_state::device_timer(emu_timer &timer, device_timer_id id, int param, void *ptr) { switch(id) { case TIMER_DAC: dac_callback(ptr, param); break; default: throw emu_fatalerror("Unknown id in mjsister_state::device_timer"); } } TIMER_CALLBACK_MEMBER(mjsister_state::dac_callback) { uint8_t *DACROM = memregion("samples")->base(); m_dac->write(DACROM[(m_dac_bank * 0x10000 + m_dac_adr++) & 0x1ffff]); if (((m_dac_adr & 0xff00 ) >> 8) != m_dac_adr_e) m_dac_timer->adjust(attotime::from_hz(MCLK) * 1024); else m_dac_busy = 0; } void mjsister_state::dac_adr_s_w(uint8_t data) { m_dac_adr_s = data; } void mjsister_state::dac_adr_e_w(uint8_t data) { m_dac_adr_e = data; m_dac_adr = m_dac_adr_s << 8; if (m_dac_busy == 0) synchronize(TIMER_DAC); m_dac_busy = 1; } WRITE_LINE_MEMBER(mjsister_state::rombank_w) { m_rombank->set_entry((m_mainlatch[0]->q0_r() << 1) | m_mainlatch[1]->q6_r()); } WRITE_LINE_MEMBER(mjsister_state::flip_screen_w) { flip_screen_set(state); } WRITE_LINE_MEMBER(mjsister_state::colorbank_w) { m_colorbank = (m_mainlatch[0]->output_state() >> 2) & 7; } WRITE_LINE_MEMBER(mjsister_state::video_enable_w) { m_video_enable = state; } WRITE_LINE_MEMBER(mjsister_state::irq_enable_w) { m_irq_enable = state; if (!m_irq_enable) m_maincpu->set_input_line(0, CLEAR_LINE); } WRITE_LINE_MEMBER(mjsister_state::vrambank_w) { m_vrambank->set_entry(state); } WRITE_LINE_MEMBER(mjsister_state::dac_bank_w) { m_dac_bank = state; } WRITE_LINE_MEMBER(mjsister_state::coin_counter_w) { machine().bookkeeping().coin_counter_w(0, state); } void mjsister_state::input_sel1_w(uint8_t data) { m_input_sel1 = data; } void mjsister_state::input_sel2_w(uint8_t data) { m_input_sel2 = data; } uint8_t mjsister_state::keys_r() { int p, i, ret = 0; static const char *const keynames[] = { "KEY0", "KEY1", "KEY2", "KEY3", "KEY4", "KEY5" }; p = m_input_sel1 & 0x3f; // p |= ((m_input_sel2 & 8) << 4) | ((m_input_sel2 & 0x20) << 1); for (i = 0; i < 6; i++) { if (BIT(p, i)) ret |= ioport(keynames[i])->read(); } return ret; } /************************************* * * Address maps * *************************************/ void mjsister_state::mjsister_map(address_map &map) { map(0x0000, 0x77ff).rom(); map(0x7800, 0x7fff).ram(); map(0x8000, 0xffff).bankr("rombank").bankw("vrambank"); } void mjsister_state::mjsister_io_map(address_map &map) { map.global_mask(0xff); map(0x00, 0x00).w(m_crtc, FUNC(hd6845s_device::address_w)); map(0x01, 0x01).rw(m_crtc, FUNC(hd6845s_device::register_r), FUNC(hd6845s_device::register_w)); map(0x10, 0x10).w("aysnd", FUNC(ay8910_device::address_w)); map(0x11, 0x11).r("aysnd", FUNC(ay8910_device::data_r)); map(0x12, 0x12).w("aysnd", FUNC(ay8910_device::data_w)); map(0x20, 0x20).r(FUNC(mjsister_state::keys_r)); map(0x21, 0x21).portr("IN0"); map(0x30, 0x30).w("mainlatch1", FUNC(ls259_device::write_nibble_d0)); map(0x31, 0x31).w("mainlatch2", FUNC(ls259_device::write_nibble_d0)); map(0x32, 0x32).w(FUNC(mjsister_state::input_sel1_w)); map(0x33, 0x33).w(FUNC(mjsister_state::input_sel2_w)); map(0x34, 0x34).w(FUNC(mjsister_state::dac_adr_s_w)); map(0x35, 0x35).w(FUNC(mjsister_state::dac_adr_e_w)); // map(0x36, 0x36) // writes 0xf8 here once } /************************************* * * Input ports * *************************************/ static INPUT_PORTS_START( mjsister ) PORT_START("DSW1") PORT_DIPNAME( 0x07, 0x07, DEF_STR( Coinage ) ) PORT_DIPLOCATION("DSW1:8,7,6") PORT_DIPSETTING( 0x03, DEF_STR( 5C_1C ) ) PORT_DIPSETTING( 0x00, DEF_STR( 4C_1C ) ) PORT_DIPSETTING( 0x01, DEF_STR( 3C_1C ) ) PORT_DIPSETTING( 0x02, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x07, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x06, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0x05, DEF_STR( 1C_3C ) ) PORT_DIPSETTING( 0x04, DEF_STR( 1C_4C ) ) PORT_DIPUNUSED_DIPLOC( 0x08, 0x08, "DSW1:5") PORT_DIPNAME( 0x30, 0x30, DEF_STR( Difficulty ) ) PORT_DIPLOCATION("DSW1:4,3") // see code at $141C PORT_DIPSETTING( 0x30, "0" ) PORT_DIPSETTING( 0x20, "1" ) PORT_DIPSETTING( 0x10, "2" ) PORT_DIPSETTING( 0x00, "3" ) PORT_DIPNAME( 0x40, 0x40, DEF_STR( Test ) ) PORT_DIPLOCATION("DSW1:2") PORT_DIPSETTING( 0x40, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x80, 0x80, DEF_STR( Flip_Screen ) ) PORT_DIPLOCATION("DSW1:1") PORT_DIPSETTING( 0x80, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_START("DSW2") /* not on PCB */ PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNUSED ) PORT_START("IN0") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_COIN2 ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_SERVICE3 ) PORT_OPTIONAL PORT_NAME("Memory Reset 1") // only tested in service mode? PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_GAMBLE_BOOK ) PORT_OPTIONAL PORT_NAME("Analyzer") // only tested in service mode? PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_SERVICE ) PORT_TOGGLE PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_SERVICE4 ) PORT_OPTIONAL PORT_NAME("Memory Reset 2") // only tested in service mode? PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_GAMBLE_PAYOUT ) PORT_OPTIONAL // only tested in service mode? PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_COIN1 ) PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_OTHER ) PORT_NAME("Hopper") PORT_CODE(KEYCODE_8) // only tested in service mode? PORT_START("KEY0") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_MAHJONG_A ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_MAHJONG_B ) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_MAHJONG_C ) PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_MAHJONG_D ) PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_MAHJONG_LAST_CHANCE ) PORT_BIT( 0xe0, IP_ACTIVE_HIGH, IPT_UNUSED ) PORT_START("KEY1") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_MAHJONG_E ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_MAHJONG_F ) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_MAHJONG_G ) PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_MAHJONG_H ) PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_MAHJONG_SCORE ) PORT_BIT( 0xe0, IP_ACTIVE_HIGH, IPT_UNUSED ) PORT_START("KEY2") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_MAHJONG_I ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_MAHJONG_J ) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_MAHJONG_K ) PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_MAHJONG_L ) PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_MAHJONG_DOUBLE_UP ) PORT_BIT( 0xe0, IP_ACTIVE_HIGH, IPT_UNUSED ) PORT_START("KEY3") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_MAHJONG_M ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_MAHJONG_N ) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_MAHJONG_CHI ) PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_MAHJONG_PON ) PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_MAHJONG_FLIP_FLOP ) PORT_BIT( 0xe0, IP_ACTIVE_HIGH, IPT_UNUSED ) PORT_START("KEY4") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_MAHJONG_KAN ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_MAHJONG_REACH ) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_MAHJONG_RON ) PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_UNKNOWN ) PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_MAHJONG_BIG ) PORT_BIT( 0xe0, IP_ACTIVE_HIGH, IPT_UNUSED ) PORT_START("KEY5") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_START1 ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_MAHJONG_BET ) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_UNKNOWN ) PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_UNKNOWN ) PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_MAHJONG_SMALL ) PORT_BIT( 0xe0, IP_ACTIVE_HIGH, IPT_UNUSED ) INPUT_PORTS_END /************************************* * * Machine driver * *************************************/ void mjsister_state::machine_start() { uint8_t *ROM = memregion("maincpu")->base(); m_rombank->configure_entries(0, 4, &ROM[0x10000], 0x8000); m_vram = make_unique_clear<uint8_t[]>(0x10000); m_vrambank->configure_entries(0, 2, m_vram.get(), 0x8000); m_dac_timer = timer_alloc(TIMER_DAC); save_pointer(NAME(m_vram), 0x10000); save_item(NAME(m_dac_busy)); save_item(NAME(m_video_enable)); save_item(NAME(m_colorbank)); save_item(NAME(m_input_sel1)); save_item(NAME(m_input_sel2)); save_item(NAME(m_irq_enable)); save_item(NAME(m_dac_adr)); save_item(NAME(m_dac_bank)); save_item(NAME(m_dac_adr_s)); save_item(NAME(m_dac_adr_e)); } void mjsister_state::machine_reset() { m_dac_busy = 0; m_video_enable = 0; m_input_sel1 = 0; m_input_sel2 = 0; m_dac_adr = 0; m_dac_bank = 0; m_dac_adr_s = 0; m_dac_adr_e = 0; } INTERRUPT_GEN_MEMBER(mjsister_state::interrupt) { if (m_irq_enable) m_maincpu->set_input_line(0, ASSERT_LINE); } void mjsister_state::mjsister(machine_config &config) { /* basic machine hardware */ Z80(config, m_maincpu, MCLK/2); /* 6.000 MHz */ m_maincpu->set_addrmap(AS_PROGRAM, &mjsister_state::mjsister_map); m_maincpu->set_addrmap(AS_IO, &mjsister_state::mjsister_io_map); m_maincpu->set_periodic_int(FUNC(mjsister_state::interrupt), attotime::from_hz(2*60)); LS259(config, m_mainlatch[0]); m_mainlatch[0]->q_out_cb<0>().set(FUNC(mjsister_state::rombank_w)); m_mainlatch[0]->q_out_cb<1>().set(FUNC(mjsister_state::flip_screen_w)); m_mainlatch[0]->q_out_cb<2>().set(FUNC(mjsister_state::colorbank_w)); m_mainlatch[0]->q_out_cb<3>().set(FUNC(mjsister_state::colorbank_w)); m_mainlatch[0]->q_out_cb<4>().set(FUNC(mjsister_state::colorbank_w)); m_mainlatch[0]->q_out_cb<5>().set(FUNC(mjsister_state::video_enable_w)); m_mainlatch[0]->q_out_cb<6>().set(FUNC(mjsister_state::irq_enable_w)); m_mainlatch[0]->q_out_cb<7>().set(FUNC(mjsister_state::vrambank_w)); LS259(config, m_mainlatch[1]); m_mainlatch[1]->q_out_cb<2>().set(FUNC(mjsister_state::coin_counter_w)); m_mainlatch[1]->q_out_cb<5>().set(FUNC(mjsister_state::dac_bank_w)); m_mainlatch[1]->q_out_cb<6>().set(FUNC(mjsister_state::rombank_w)); /* video hardware */ screen_device &screen(SCREEN(config, "screen", SCREEN_TYPE_RASTER)); screen.set_raw(MCLK/2, 384, 0, 256, 268, 0, 240); // 6 MHz? screen.set_screen_update(FUNC(mjsister_state::screen_update)); PALETTE(config, m_palette, palette_device::RGB_444_PROMS, "proms", 256); HD6845S(config, m_crtc, MCLK/4); // 3 MHz? m_crtc->set_screen("screen"); m_crtc->set_show_border_area(false); m_crtc->set_char_width(2); m_crtc->set_update_row_callback(FUNC(mjsister_state::crtc_update_row)); /* sound hardware */ SPEAKER(config, "speaker").front_center(); ay8910_device &aysnd(AY8910(config, "aysnd", MCLK/8)); aysnd.port_a_read_callback().set_ioport("DSW1"); aysnd.port_b_read_callback().set_ioport("DSW2"); aysnd.add_route(ALL_OUTPUTS, "speaker", 0.15); DAC_8BIT_R2R(config, "dac", 0).add_route(ALL_OUTPUTS, "speaker", 0.5); // unknown DAC } /************************************* * * ROM definition(s) * *************************************/ ROM_START( mjsister ) ROM_REGION( 0x30000, "maincpu", 0 ) /* CPU */ ROM_LOAD( "ms00.bin", 0x00000, 0x08000, CRC(9468c33b) SHA1(63aecdcaa8493d58549dfd1d217743210cf953bc) ) ROM_LOAD( "ms01t.bin", 0x10000, 0x10000, CRC(a7b6e530) SHA1(fda9bea214968a8814d2c43226b3b32316581050) ) /* banked */ ROM_LOAD( "ms02t.bin", 0x20000, 0x10000, CRC(7752b5ba) SHA1(84dcf27a62eb290ba07c85af155897ec72f320a8) ) /* banked */ ROM_REGION( 0x20000, "samples", 0 ) /* samples */ ROM_LOAD( "ms03.bin", 0x00000, 0x10000, CRC(10a68e5e) SHA1(a0e2fa34c1c4f34642f65fbf17e9da9c2554a0c6) ) ROM_LOAD( "ms04.bin", 0x10000, 0x10000, CRC(641b09c1) SHA1(15cde906175bcb5190d36cc91cbef003ef91e425) ) ROM_REGION( 0x00400, "proms", 0 ) /* color PROMs */ ROM_LOAD( "ms05.bpr", 0x0000, 0x0100, CRC(dd231a5f) SHA1(be008593ac8ba8f5a1dd5b188dc7dc4c03016805) ) // R ROM_LOAD( "ms06.bpr", 0x0100, 0x0100, CRC(df8e8852) SHA1(842a891440aef55a560d24c96f249618b9f4b97f) ) // G ROM_LOAD( "ms07.bpr", 0x0200, 0x0100, CRC(6cb3a735) SHA1(468ae3d40552dc2ec24f5f2988850093d73948a6) ) // B ROM_LOAD( "ms08.bpr", 0x0300, 0x0100, CRC(da2b3b38) SHA1(4de99c17b227653bc1b904f1309f447f5a0ab516) ) // ? ROM_END /************************************* * * Game driver(s) * *************************************/ GAME( 1986, mjsister, 0, mjsister, mjsister, mjsister_state, empty_init, ROT0, "Toaplan", "Mahjong Sisters (Japan)", MACHINE_SUPPORTS_SAVE )
30.286807
140
0.696843
Robbbert
217ba72be5dff268cda027470b84457415138e80
5,641
hpp
C++
rmf_traffic/include/rmf_traffic/schedule/Patch.hpp
methylDragon/rmf_core
4099921bea576c2fde87c3dc852cc4d8f86a5d1a
[ "Apache-2.0" ]
109
2019-10-31T02:02:50.000Z
2022-03-30T04:42:19.000Z
rmf_traffic/include/rmf_traffic/schedule/Patch.hpp
methylDragon/rmf_core
4099921bea576c2fde87c3dc852cc4d8f86a5d1a
[ "Apache-2.0" ]
155
2019-11-15T04:43:31.000Z
2021-04-22T09:45:32.000Z
rmf_traffic/include/rmf_traffic/schedule/Patch.hpp
methylDragon/rmf_core
4099921bea576c2fde87c3dc852cc4d8f86a5d1a
[ "Apache-2.0" ]
51
2019-10-31T11:30:34.000Z
2022-01-27T03:07:01.000Z
/* * Copyright (C) 2020 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef RMF_TRAFFIC__SCHEDULE__PATCH_HPP #define RMF_TRAFFIC__SCHEDULE__PATCH_HPP #include <rmf_traffic/schedule/Change.hpp> #include <rmf_traffic/detail/bidirectional_iterator.hpp> #include <rmf_utils/optional.hpp> namespace rmf_traffic { namespace schedule { //============================================================================== /// A container of Database changes class Patch { public: template<typename E, typename I, typename F> using base_iterator = rmf_traffic::detail::bidirectional_iterator<E, I, F>; class Participant { public: /// Constructor /// /// \param[in] id /// The ID of the participant that is being changed /// /// \param[in] erasures /// The information about which routes to erase /// /// \param[in] delays /// The information about what delays have occurred /// /// \param[in] additions /// The information about which routes to add Participant( ParticipantId id, Change::Erase erasures, std::vector<Change::Delay> delays, Change::Add additions); /// The ID of the participant that this set of changes will patch. ParticipantId participant_id() const; /// The route erasures to perform. /// /// These erasures should be performed before any other changes. const Change::Erase& erasures() const; /// The sequence of delays to apply. /// /// These delays should be applied in sequential order after the erasures /// are performed, and before any additions are performed. const std::vector<Change::Delay>& delays() const; /// The set of additions to perfom. /// /// These additions should be applied after all other changes. const Change::Add& additions() const; class Implementation; private: rmf_utils::impl_ptr<Implementation> _pimpl; }; class IterImpl; using const_iterator = base_iterator<const Participant, IterImpl, Patch>; /// Constructor. Mirrors should evaluate the fields of the Patch class in the /// order of these constructor arguments. /// /// \param[in] removed_participants /// Information about which participants have been unregistered since the /// last update. /// /// \param[in] new_participants /// Information about which participants have been registered since the last /// update. /// /// \param[in] changes /// Information about how the participants have changed since the last /// update. /// /// \param[in] cull /// Information about how the database has culled old data since the last /// update. /// /// \param[in] latest_version /// The lastest version of the database that this Patch represents. Patch( std::vector<Change::UnregisterParticipant> removed_participants, std::vector<Change::RegisterParticipant> new_participants, std::vector<Participant> changes, rmf_utils::optional<Change::Cull> cull, Version latest_version); // TODO(MXG): Consider using a persistent reliable topic to broadcast the // active participant information instead of making it part of the patch. // Ideally this information would not need to change frequently, so it doesn't // necessarily need to be in the Patch scheme. The addition and loss of // participants is significant enough that we should guarantee it's always // transmitted correctly. // // The current scheme makes an assumption that remote mirrors will always // either sync up before unregistered participant information is culled, or // else they will perform a complete refresh. This might be a point of // vulnerability if a remote mirror is not being managed correctly. /// Get a list of which participants have been unregistered. This should be /// evaluated first in the patch. const std::vector<Change::UnregisterParticipant>& unregistered() const; /// Get a list of new participants that have been registered. This should be /// evaluated after the unregistered participants. const std::vector<Change::RegisterParticipant>& registered() const; /// Returns an iterator to the first element of the Patch. const_iterator begin() const; /// Returns an iterator to the element following the last element of the /// Patch. This iterator acts as a placeholder; attempting to dereference it /// results in undefined behavior. const_iterator end() const; /// Get the number of elements in this Patch. std::size_t size() const; /// Get the cull information for this patch if a cull has occurred. const Change::Cull* cull() const; /// Get the latest version of the Database that informed this Patch. Version latest_version() const; class Implementation; private: rmf_utils::impl_ptr<Implementation> _pimpl; }; } // namespace schedule namespace detail { extern template class bidirectional_iterator< const schedule::Patch::Participant, schedule::Patch::IterImpl, schedule::Patch >; } } // namespace rmf_traffic #endif // RMF_TRAFFIC__SCHEDULE__PATCH_HPP
32.41954
80
0.70413
methylDragon
217ce3bf4403f4609173fa5aab979476f2cc2c60
833
cpp
C++
CodeForces/Complete/800-899/878A-ShortProgram.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
CodeForces/Complete/800-899/878A-ShortProgram.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
CodeForces/Complete/800-899/878A-ShortProgram.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
#include <cstdio> int main(){ const int N = 10; long n; scanf("%ld\n", &n); int action[N]; for(int p = 0; p < N; p++){action[p] = -1;} while(n--){ char x; int u; scanf("%c %d\n", &x, &u); for(int p = 0; p < N; p++){ bool v = u & 1; if(x == '&' && !v){action[p] = 0;} else if(x == '|' && v){action[p] = 1;} else if(x == '^' && v){action[p] = 1 - action[p];} u /= 2; } } int andint(0); for(int p = N - 1; p >= 0; p--){andint *= 2; andint += 1 - (action[p] == 0);} int orint(0); for(int p = N - 1; p >= 0; p--){orint *= 2; orint += (action[p] == 1);} int xorint(0); for(int p = N - 1; p >= 0; p--){xorint *= 2; xorint += (action[p] == 2);} printf("3\n& %d\n| %d\n^ %d\n", andint, orint, xorint); return 0; }
32.038462
96
0.402161
Ashwanigupta9125
217f4eea802c216218e09170d96722b90697c39b
7,191
cpp
C++
test/state_machine_test.cpp
kariem2k/rive-cpp
f58c3b3d48ea03947a76971bce17e7f567cf0de0
[ "MIT" ]
139
2020-08-17T20:10:24.000Z
2022-03-28T12:22:44.000Z
test/state_machine_test.cpp
kariem2k/rive-cpp
f58c3b3d48ea03947a76971bce17e7f567cf0de0
[ "MIT" ]
89
2020-08-28T16:41:01.000Z
2022-03-28T19:10:49.000Z
test/state_machine_test.cpp
kariem2k/rive-cpp
f58c3b3d48ea03947a76971bce17e7f567cf0de0
[ "MIT" ]
19
2020-10-19T00:54:40.000Z
2022-02-28T05:34:17.000Z
#include <rive/core/binary_reader.hpp> #include <rive/file.hpp> #include <rive/animation/state_machine_bool.hpp> #include <rive/animation/state_machine_layer.hpp> #include <rive/animation/animation_state.hpp> #include <rive/animation/entry_state.hpp> #include <rive/animation/state_transition.hpp> #include <rive/animation/state_machine_instance.hpp> #include <rive/animation/state_machine_input_instance.hpp> #include <rive/animation/blend_state_1d.hpp> #include <rive/animation/blend_animation_1d.hpp> #include <rive/animation/blend_state_direct.hpp> #include <rive/animation/blend_state_transition.hpp> #include "catch.hpp" #include <cstdio> TEST_CASE("file with state machine be read", "[file]") { FILE* fp = fopen("../../test/assets/rocket.riv", "r"); REQUIRE(fp != nullptr); fseek(fp, 0, SEEK_END); auto length = ftell(fp); fseek(fp, 0, SEEK_SET); uint8_t* bytes = new uint8_t[length]; REQUIRE(fread(bytes, 1, length, fp) == length); auto reader = rive::BinaryReader(bytes, length); rive::File* file = nullptr; auto result = rive::File::import(reader, &file); REQUIRE(result == rive::ImportResult::success); REQUIRE(file != nullptr); auto artboard = file->artboard(); REQUIRE(artboard != nullptr); REQUIRE(artboard->animationCount() == 3); REQUIRE(artboard->stateMachineCount() == 1); auto stateMachine = artboard->stateMachine("Button"); REQUIRE(stateMachine != nullptr); REQUIRE(stateMachine->layerCount() == 1); REQUIRE(stateMachine->inputCount() == 2); auto hover = stateMachine->input("Hover"); REQUIRE(hover != nullptr); REQUIRE(hover->is<rive::StateMachineBool>()); auto press = stateMachine->input("Press"); REQUIRE(press != nullptr); REQUIRE(press->is<rive::StateMachineBool>()); auto layer = stateMachine->layer(0); REQUIRE(layer->stateCount() == 6); REQUIRE(layer->anyState() != nullptr); REQUIRE(layer->entryState() != nullptr); REQUIRE(layer->exitState() != nullptr); int foundAnimationStates = 0; for (int i = 0; i < layer->stateCount(); i++) { auto state = layer->state(i); if (state->is<rive::AnimationState>()) { foundAnimationStates++; REQUIRE(state->as<rive::AnimationState>()->animation() != nullptr); } } REQUIRE(foundAnimationStates == 3); REQUIRE(layer->entryState()->transitionCount() == 1); auto stateTo = layer->entryState()->transition(0)->stateTo(); REQUIRE(stateTo != nullptr); REQUIRE(stateTo->is<rive::AnimationState>()); REQUIRE(stateTo->as<rive::AnimationState>()->animation() != nullptr); REQUIRE(stateTo->as<rive::AnimationState>()->animation()->name() == "idle"); auto idleState = stateTo->as<rive::AnimationState>(); REQUIRE(idleState->transitionCount() == 2); for (int i = 0; i < idleState->transitionCount(); i++) { auto transition = idleState->transition(i); if (transition->stateTo() ->as<rive::AnimationState>() ->animation() ->name() == "Roll_over") { // Check the condition REQUIRE(transition->conditionCount() == 1); } } rive::StateMachineInstance smi(artboard->stateMachine("Button")); REQUIRE(smi.getBool("Hover")->name() == "Hover"); REQUIRE(smi.getBool("Press")->name() == "Press"); REQUIRE(smi.getBool("Hover") != nullptr); REQUIRE(smi.getBool("Press") != nullptr); REQUIRE(smi.stateChangedCount() == 0); REQUIRE(smi.currentAnimationCount() == 0); delete file; delete[] bytes; } TEST_CASE("file with blend states loads correctly", "[file]") { FILE* fp = fopen("../../test/assets/blend_test.riv", "r"); REQUIRE(fp != nullptr); fseek(fp, 0, SEEK_END); auto length = ftell(fp); fseek(fp, 0, SEEK_SET); uint8_t* bytes = new uint8_t[length]; REQUIRE(fread(bytes, 1, length, fp) == length); auto reader = rive::BinaryReader(bytes, length); rive::File* file = nullptr; auto result = rive::File::import(reader, &file); REQUIRE(result == rive::ImportResult::success); REQUIRE(file != nullptr); auto artboard = file->artboard(); REQUIRE(artboard != nullptr); REQUIRE(artboard->animationCount() == 4); REQUIRE(artboard->stateMachineCount() == 2); auto stateMachine = artboard->stateMachine("blend"); REQUIRE(stateMachine != nullptr); REQUIRE(stateMachine->layerCount() == 1); auto layer = stateMachine->layer(0); REQUIRE(layer->stateCount() == 5); REQUIRE(layer->anyState() != nullptr); REQUIRE(layer->entryState() != nullptr); REQUIRE(layer->exitState() != nullptr); REQUIRE(layer->state(1)->is<rive::BlendState1D>()); REQUIRE(layer->state(2)->is<rive::BlendState1D>()); auto blendStateA = layer->state(1)->as<rive::BlendState1D>(); auto blendStateB = layer->state(2)->as<rive::BlendState1D>(); REQUIRE(blendStateA->animationCount() == 3); REQUIRE(blendStateB->animationCount() == 3); auto animation = blendStateA->animation(0); REQUIRE(animation->is<rive::BlendAnimation1D>()); auto animation1D = animation->as<rive::BlendAnimation1D>(); REQUIRE(animation1D->animation() != nullptr); REQUIRE(animation1D->animation()->name() == "horizontal"); REQUIRE(animation1D->value() == 0.0f); animation = blendStateA->animation(1); REQUIRE(animation->is<rive::BlendAnimation1D>()); animation1D = animation->as<rive::BlendAnimation1D>(); REQUIRE(animation1D->animation() != nullptr); REQUIRE(animation1D->animation()->name() == "vertical"); REQUIRE(animation1D->value() == 100.0f); animation = blendStateA->animation(2); REQUIRE(animation->is<rive::BlendAnimation1D>()); animation1D = animation->as<rive::BlendAnimation1D>(); REQUIRE(animation1D->animation() != nullptr); REQUIRE(animation1D->animation()->name() == "rotate"); REQUIRE(animation1D->value() == 0.0f); REQUIRE(blendStateA->transitionCount() == 1); REQUIRE(blendStateA->transition(0)->is<rive::BlendStateTransition>()); REQUIRE(blendStateA->transition(0) ->as<rive::BlendStateTransition>() ->exitBlendAnimation() != nullptr); delete file; delete[] bytes; } TEST_CASE("animation state with no animation doesn't crash", "[file]") { FILE* fp = fopen("../../test/assets/multiple_state_machines.riv", "r"); REQUIRE(fp != nullptr); fseek(fp, 0, SEEK_END); auto length = ftell(fp); fseek(fp, 0, SEEK_SET); uint8_t* bytes = new uint8_t[length]; REQUIRE(fread(bytes, 1, length, fp) == length); auto reader = rive::BinaryReader(bytes, length); rive::File* file = nullptr; auto result = rive::File::import(reader, &file); REQUIRE(result == rive::ImportResult::success); REQUIRE(file != nullptr); auto artboard = file->artboard(); REQUIRE(artboard != nullptr); REQUIRE(artboard->animationCount() == 1); REQUIRE(artboard->stateMachineCount() == 4); auto stateMachine = artboard->stateMachine("two"); REQUIRE(stateMachine != nullptr); REQUIRE(stateMachine->layerCount() == 1); auto layer = stateMachine->layer(0); REQUIRE(layer->stateCount() == 4); REQUIRE(layer->anyState() != nullptr); REQUIRE(layer->entryState() != nullptr); REQUIRE(layer->exitState() != nullptr); REQUIRE(layer->state(3)->is<rive::AnimationState>()); auto animationState = layer->state(3)->as<rive::AnimationState>(); REQUIRE(animationState->animation() == nullptr); rive::StateMachineInstance smi(stateMachine); smi.advance(artboard, 0.0f); delete file; delete[] bytes; }
32.686364
77
0.695175
kariem2k
217f5897f31a0f6f3f653e816a6c592dc13fd832
13,022
cpp
C++
designer/src/gaugespeed.cpp
HangYongmao/quc
ce33d0e0bd36ec5b777ca312d0c88f27169bace1
[ "MIT" ]
19
2019-09-05T07:11:16.000Z
2021-12-17T09:30:50.000Z
designer/src/gaugespeed.cpp
zhoujuan-ht17/quc
ce33d0e0bd36ec5b777ca312d0c88f27169bace1
[ "MIT" ]
null
null
null
designer/src/gaugespeed.cpp
zhoujuan-ht17/quc
ce33d0e0bd36ec5b777ca312d0c88f27169bace1
[ "MIT" ]
22
2019-08-13T06:50:31.000Z
2022-03-22T12:52:22.000Z
#pragma execution_character_set("utf-8") #include "gaugespeed.h" #include "qpainter.h" #include "qmath.h" #include "qtimer.h" #include "qlcdnumber.h" #include "qdebug.h" GaugeSpeed::GaugeSpeed(QWidget *parent) : QWidget(parent) { minValue = 0; maxValue = 100; value = 0; precision = 2; scaleMajor = 8; scaleMinor = 1; startAngle = 50; endAngle = 50; animation = false; animationStep = 0.5; ringWidth = 10; ringStartPercent = 25; ringMidPercent = 50; ringEndPercent = 25; ringColorStart = QColor(2, 242, 177); ringColorMid = QColor(45, 196, 248); ringColorEnd = QColor(254, 68, 138); pointerColor = QColor(178, 221, 253); textColor = QColor(50, 50, 50); reverse = false; currentValue = 0; timer = new QTimer(this); timer->setInterval(10); connect(timer, SIGNAL(timeout()), this, SLOT(updateValue())); //显示数码管 lcd = new QLCDNumber(5, this); lcd->setSegmentStyle(QLCDNumber::Flat); lcd->setFrameShape(QFrame::NoFrame); QPalette pal = lcd->palette(); pal.setColor(QPalette::Foreground, textColor); lcd->setPalette(pal); setFont(QFont("Arial", 7)); } GaugeSpeed::~GaugeSpeed() { if (timer->isActive()) { timer->stop(); } } void GaugeSpeed::resizeEvent(QResizeEvent *) { int width = this->width(); int height = this->height(); int lcdWidth = width / 4; int lcdHeight = height / 9; lcd->setGeometry((width - lcdWidth) / 2, height - (2.2 * lcdHeight), lcdWidth, lcdHeight); } void GaugeSpeed::paintEvent(QPaintEvent *) { int width = this->width(); int height = this->height(); int side = qMin(width, height); //绘制准备工作,启用反锯齿,平移坐标轴中心,等比例缩放 QPainter painter(this); painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing); painter.translate(width / 2, height / 2); painter.scale(side / 200.0, side / 200.0); //绘制圆环 drawRing(&painter); //绘制刻度线 drawScale(&painter); //绘制刻度值 drawScaleNum(&painter); //根据指示器形状绘制指示器 drawPointer(&painter); //绘制当前值 drawText(&painter); } void GaugeSpeed::drawRing(QPainter *painter) { int radius = 100; painter->save(); QPen pen = painter->pen(); pen.setCapStyle(Qt::FlatCap); pen.setWidthF(ringWidth); radius = radius - ringWidth; QRectF rect = QRectF(-radius, -radius, radius * 2, radius * 2); //计算总范围角度,根据占比例自动计算三色圆环范围角度 double angleAll = 360.0 - startAngle - endAngle; double angleStart = angleAll * (double)ringStartPercent / 100; double angleMid = angleAll * (double)ringMidPercent / 100; double angleEnd = angleAll * (double)ringEndPercent / 100; //绘制第一圆环 pen.setColor(ringColorStart); painter->setPen(pen); painter->drawArc(rect, (270 - startAngle - angleStart) * 16, angleStart * 16); //绘制第二圆环 pen.setColor(ringColorMid); painter->setPen(pen); painter->drawArc(rect, (270 - startAngle - angleStart - angleMid) * 16, angleMid * 16); //绘制第三圆环 pen.setColor(ringColorEnd); painter->setPen(pen); painter->drawArc(rect, (270 - startAngle - angleStart - angleMid - angleEnd) * 16, angleEnd * 16); painter->restore(); } void GaugeSpeed::drawScale(QPainter *painter) { int radius = 94; painter->save(); QPen pen = painter->pen(); pen.setColor(textColor); pen.setCapStyle(Qt::RoundCap); painter->rotate(startAngle); int steps = (scaleMajor * scaleMinor); double angleStep = (360.0 - startAngle - endAngle) / steps; //计算圆环对应大刻度范围索引 int indexStart = steps * (double)ringStartPercent / 100 + 1; int indexMid = steps * (double)ringMidPercent / 100 - 1; int indexEnd = steps * (double)ringEndPercent / 100 + 1; int index = 0; for (int i = 0; i <= steps; i++) { if (i % scaleMinor == 0) { //根据所在圆环范围切换颜色 if (index < indexStart) { pen.setColor(ringColorStart); } else if (index < (indexStart + indexMid)) { pen.setColor(ringColorMid); } else if (index < (indexStart + indexMid + indexEnd)) { pen.setColor(ringColorEnd); } index++; pen.setWidthF(1.5); painter->setPen(pen); painter->drawLine(0, radius - 13, 0, radius); } else { pen.setWidthF(0.5); painter->setPen(pen); painter->drawLine(0, radius - 5, 0, radius); } painter->rotate(angleStep); } painter->restore(); } void GaugeSpeed::drawScaleNum(QPainter *painter) { int radius = 70; painter->save(); painter->setPen(textColor); double startRad = (360 - startAngle - 90) * (M_PI / 180); double deltaRad = (360 - startAngle - endAngle) * (M_PI / 180) / scaleMajor; for (int i = 0; i <= scaleMajor; i++) { double sina = sin(startRad - i * deltaRad); double cosa = cos(startRad - i * deltaRad); double value = 1.0 * i * ((maxValue - minValue) / scaleMajor) + minValue; QString strValue = QString("%1M").arg((double)value, 0, 'f', 0); double textWidth = fontMetrics().width(strValue); double textHeight = fontMetrics().height(); int x = radius * cosa - textWidth / 2; int y = -radius * sina + textHeight / 4; painter->drawText(x, y, strValue); } painter->restore(); } void GaugeSpeed::drawPointer(QPainter *painter) { int radius = 62; painter->save(); painter->setPen(Qt::NoPen); painter->setBrush(pointerColor); QPolygon pts; pts.setPoints(4, -5, 0, 0, -8, 5, 0, 0, radius); painter->rotate(startAngle); double degRotate = (360.0 - startAngle - endAngle) / (maxValue - minValue) * (currentValue - minValue); painter->rotate(degRotate); painter->drawConvexPolygon(pts); painter->restore(); } void GaugeSpeed::drawText(QPainter *painter) { int radius = 100; painter->save(); painter->setPen(textColor); QRectF unitRect(-radius, radius / 3, radius * 2, radius / 4); QString strUnit = QString("%1").arg("Mbps"); painter->setFont(QFont("Arial", 5)); painter->drawText(unitRect, Qt::AlignCenter, strUnit); QRectF textRect(-radius, radius / 2.3, radius * 2, radius / 3); QString strValue = QString("%1").arg((double)currentValue, 0, 'f', precision); strValue = QString("%1").arg(strValue, 5, QLatin1Char('0')); painter->setFont(QFont("Arial", 15)); #if 0 lcd->setVisible(false); painter->drawText(textRect, Qt::AlignCenter, strValue); #else lcd->display(strValue); #endif painter->restore(); } void GaugeSpeed::updateValue() { if (!reverse) { if (currentValue >= value) { timer->stop(); } else { currentValue += animationStep; } } else { if (currentValue <= value) { timer->stop(); } else { currentValue -= animationStep; } } update(); } double GaugeSpeed::getMinValue() const { return this->minValue; } double GaugeSpeed::getMaxValue() const { return this->maxValue; } double GaugeSpeed::getValue() const { return this->value; } int GaugeSpeed::getPrecision() const { return this->precision; } int GaugeSpeed::getScaleMajor() const { return this->scaleMajor; } int GaugeSpeed::getScaleMinor() const { return this->scaleMinor; } int GaugeSpeed::getStartAngle() const { return this->startAngle; } int GaugeSpeed::getEndAngle() const { return this->endAngle; } bool GaugeSpeed::getAnimation() const { return this->animation; } double GaugeSpeed::getAnimationStep() const { return this->animationStep; } int GaugeSpeed::getRingWidth() const { return this->ringWidth; } int GaugeSpeed::getRingStartPercent() const { return this->ringStartPercent; } int GaugeSpeed::getRingMidPercent() const { return this->ringMidPercent; } int GaugeSpeed::getRingEndPercent() const { return this->ringEndPercent; } QColor GaugeSpeed::getRingColorStart() const { return this->ringColorStart; } QColor GaugeSpeed::getRingColorMid() const { return this->ringColorMid; } QColor GaugeSpeed::getRingColorEnd() const { return this->ringColorEnd; } QColor GaugeSpeed::getPointerColor() const { return this->pointerColor; } QColor GaugeSpeed::getTextColor() const { return this->textColor; } QSize GaugeSpeed::sizeHint() const { return QSize(200, 200); } QSize GaugeSpeed::minimumSizeHint() const { return QSize(50, 50); } void GaugeSpeed::setRange(double minValue, double maxValue) { //如果最小值大于或者等于最大值则不设置 if (minValue >= maxValue) { return; } this->minValue = minValue; this->maxValue = maxValue; //如果目标值不在范围值内,则重新设置目标值 if (value < minValue || value > maxValue) { setValue(value); } update(); } void GaugeSpeed::setRange(int minValue, int maxValue) { setRange((double)minValue, (double)maxValue); } void GaugeSpeed::setMinValue(double minValue) { setRange(minValue, maxValue); } void GaugeSpeed::setMaxValue(double maxValue) { setRange(minValue, maxValue); } void GaugeSpeed::setValue(double value) { //值小于最小值或者值大于最大值或者值和当前值一致则无需处理 if (value < minValue || value > maxValue || value == this->value) { return; } if (value > this->value) { reverse = false; } else if (value < this->value) { reverse = true; } this->value = value; emit valueChanged(value); if (!animation) { currentValue = this->value; update(); } else { timer->start(); } } void GaugeSpeed::setValue(int value) { setValue((double)value); } void GaugeSpeed::setPrecision(int precision) { //最大精确度为 3 if (precision <= 3 && this->precision != precision) { this->precision = precision; update(); } } void GaugeSpeed::setScaleMajor(int scaleMajor) { if (this->scaleMajor != scaleMajor) { this->scaleMajor = scaleMajor; update(); } } void GaugeSpeed::setScaleMinor(int scaleMinor) { if (this->scaleMinor != scaleMinor) { this->scaleMinor = scaleMinor; update(); } } void GaugeSpeed::setStartAngle(int startAngle) { if (this->startAngle != startAngle) { this->startAngle = startAngle; update(); } } void GaugeSpeed::setEndAngle(int endAngle) { if (this->endAngle != endAngle) { this->endAngle = endAngle; update(); } } void GaugeSpeed::setAnimation(bool animation) { if (this->animation != animation) { this->animation = animation; update(); } } void GaugeSpeed::setAnimationStep(double animationStep) { if (this->animationStep != animationStep) { this->animationStep = animationStep; update(); } } void GaugeSpeed::setRingWidth(int ringWidth) { if (this->ringWidth != ringWidth) { this->ringWidth = ringWidth; update(); } } void GaugeSpeed::setRingStartPercent(int ringStartPercent) { //所占比例不能小于1 或者总比例不能大于100 if (ringStartPercent < 1 || (ringStartPercent + ringMidPercent + ringEndPercent) > 100) { return; } if (this->ringStartPercent != ringStartPercent) { this->ringStartPercent = ringStartPercent; update(); } } void GaugeSpeed::setRingMidPercent(int ringMidPercent) { //所占比例不能小于1 或者总比例不能大于100 if (ringStartPercent < 1 || (ringStartPercent + ringMidPercent + ringEndPercent) > 100) { return; } if (this->ringMidPercent != ringMidPercent) { this->ringMidPercent = ringMidPercent; update(); } } void GaugeSpeed::setRingEndPercent(int ringEndPercent) { //所占比例不能小于1 或者总比例不能大于100 if (ringStartPercent < 1 || (ringStartPercent + ringMidPercent + ringEndPercent) > 100) { return; } if (this->ringEndPercent != ringEndPercent) { this->ringEndPercent = ringEndPercent; update(); } } void GaugeSpeed::setRingColorStart(const QColor &ringColorStart) { if (this->ringColorStart != ringColorStart) { this->ringColorStart = ringColorStart; update(); } } void GaugeSpeed::setRingColorMid(const QColor &ringColorMid) { if (this->ringColorMid != ringColorMid) { this->ringColorMid = ringColorMid; update(); } } void GaugeSpeed::setRingColorEnd(const QColor &ringColorEnd) { if (this->ringColorEnd != ringColorEnd) { this->ringColorEnd = ringColorEnd; update(); } } void GaugeSpeed::setPointerColor(const QColor &pointerColor) { if (this->pointerColor != pointerColor) { this->pointerColor = pointerColor; update(); } } void GaugeSpeed::setTextColor(const QColor &textColor) { if (this->textColor != textColor) { QPalette pal = lcd->palette(); pal.setColor(QPalette::Foreground, textColor); lcd->setPalette(pal); this->textColor = textColor; update(); } }
22.37457
107
0.624712
HangYongmao
2186f8dcb78f27fa11418cdb0781536905738bba
1,408
cpp
C++
tcp_async_server.cpp
opensvn/boost_learning
7f21551a7f3db38bea2c31d95d0c8b4e00f4537e
[ "BSL-1.0" ]
null
null
null
tcp_async_server.cpp
opensvn/boost_learning
7f21551a7f3db38bea2c31d95d0c8b4e00f4537e
[ "BSL-1.0" ]
null
null
null
tcp_async_server.cpp
opensvn/boost_learning
7f21551a7f3db38bea2c31d95d0c8b4e00f4537e
[ "BSL-1.0" ]
1
2021-10-01T04:27:44.000Z
2021-10-01T04:27:44.000Z
#include <iostream> #include <boost/asio.hpp> #include <boost/bind.hpp> #include <boost/shared_ptr.hpp> using namespace std; using namespace boost::asio; class server { private: io_service &ios; ip::tcp::acceptor acceptor; typedef boost::shared_ptr<ip::tcp::socket> sock_pt; public: server(io_service& io): ios(io), acceptor(ios, ip::tcp::endpoint(ip::tcp::v4(), 6688)) { start(); } void start() { sock_pt sock(new ip::tcp::socket(ios)); acceptor.async_accept(*sock, boost::bind(&server::accept_handler, this, placeholders::error, sock)); } void accept_handler(const boost::system::error_code &ec, sock_pt sock) { if (ec) return; cout << "client:"; cout << sock->remote_endpoint().address() << endl; sock->async_write_some(buffer("hello asio"), boost::bind(&server::write_handler, this, placeholders::error)); start(); } void write_handler(const boost::system::error_code&) { cout << "send msg complete." << endl; } }; int main() { try { cout << "server start." << endl; io_service ios; server s(ios); ios.run(); } catch (exception &e) { cout << e.what() << endl; } return 0; }
22.349206
95
0.534801
opensvn
218d6bab407dc672e26ebb0c57f15c812c5e9714
3,332
cpp
C++
test/dmtimerevent/main.cpp
brinkqiang/dmtimer
3a8c18a3366ccc31e79d1e79df512769cb8b0633
[ "MIT" ]
18
2018-03-05T14:42:46.000Z
2021-07-28T06:25:29.000Z
test/dmtimerevent/main.cpp
brinkqiang/dmtimer
3a8c18a3366ccc31e79d1e79df512769cb8b0633
[ "MIT" ]
null
null
null
test/dmtimerevent/main.cpp
brinkqiang/dmtimer
3a8c18a3366ccc31e79d1e79df512769cb8b0633
[ "MIT" ]
5
2018-03-20T12:01:07.000Z
2020-01-25T12:01:13.000Z
#include "dmutil.h" #include "dmtimermodule.h" #include "dmsingleton.h" #include "dmthread.h" #include "dmconsole.h" #include "dmtypes.h" #include "dmtimereventnode.h" class CPlayer : public CDMTimerNode { public: virtual void OnTimer(uint64_t qwIDEvent); }; class CMain : public IDMConsoleSink, public IDMThread, public CDMThreadCtrl, public CDMTimerNode, public TSingleton<CMain>, public CDMTimerEventNode { friend class TSingleton<CMain>; enum { eMAX_PLAYER = 100 * 1, eMAX_PLAYER_EVENT = 10, }; typedef enum { eTimerID_UUID = 0, eTimerID_STOP, } ETimerID; typedef enum { eTimerTime_UUID = 1000, eTimerTime_STOP = 20000, } ETimerTime; public: virtual void ThrdProc() { std::cout << "test start" << std::endl; SetTimer(eTimerID_UUID, eTimerTime_UUID, dm::any(std::string("hello world"))); SleepMs(300); CDMTimerModule::Instance()->Run(); SetTimer(eTimerID_STOP, eTimerTime_STOP, eTimerTime_STOP); AddEvent(ETimerEventType_EVERYDAY); bool bBusy = false; while (!m_bStop) { bBusy = false; if (CDMTimerModule::Instance()->Run()) { bBusy = true; } if (__Run()) { bBusy = true; } if (!bBusy) { SleepMs(1); } } std::cout << "test stop" << std::endl; } virtual void Terminate() { m_bStop = true; } virtual void OnCloseEvent() { Stop(); } virtual void OnTimer(uint64_t qwIDEvent, dm::any& oAny) { switch (qwIDEvent) { case eTimerID_UUID: { std::cout << DMFormatDateTime() << " " << CMain::Instance()->GetOnTimerCount() << " " << dm::any_cast<std::string>(oAny) << std::endl; } break; case eTimerID_STOP: { std::cout << DMFormatDateTime() << " test stopping..." << std::endl; Stop(); } break; default: break; } } virtual void OnEvent(ETimerEventType eEvent) { switch (eEvent) { case ETimerEventType_EVERYDAY: { } break; default: break; } } void AddOnTimerCount() { ++m_qwOnTimerCount; } uint64_t GetOnTimerCount() { return m_qwOnTimerCount; } private: CMain() : m_bStop(false), m_qwOnTimerCount(0) { HDMConsoleMgr::Instance()->SetHandlerHook(this); } virtual ~CMain() { } private: bool __Run() { return false; } private: volatile bool m_bStop; CPlayer m_oPlayers[eMAX_PLAYER]; uint64_t m_qwOnTimerCount; }; void CPlayer::OnTimer(uint64_t qwIDEvent) { CMain::Instance()->AddOnTimerCount(); } int main(int argc, char* argv[]) { CMain::Instance()->Start(CMain::Instance()); CMain::Instance()->WaitFor(); return 0; }
19.260116
91
0.498199
brinkqiang
2193656d0b9f2642e5b595c56ccea59f64666e1c
3,122
cpp
C++
PixelSortSDL2/application.cpp
ohookins/cpp_experiments
3b7bba2a625ef72e20cc3b90191a7683bb85740f
[ "MIT" ]
1
2018-03-31T06:41:37.000Z
2018-03-31T06:41:37.000Z
PixelSortSDL2/application.cpp
ohookins/cpp_experiments
3b7bba2a625ef72e20cc3b90191a7683bb85740f
[ "MIT" ]
null
null
null
PixelSortSDL2/application.cpp
ohookins/cpp_experiments
3b7bba2a625ef72e20cc3b90191a7683bb85740f
[ "MIT" ]
null
null
null
#include "application.h" #include "mypixel.h" #include <iostream> Application::Application() { // Define size of pixel array pixels = new MyPixel*[dimension]; for (int p = 0; p < dimension; p++) { pixels[p] = new MyPixel[dimension]; } } Application::~Application() { for (int p = 0; p < dimension; p++) { delete pixels[p]; } delete pixels; } void Application::DrawRandomColorAt(int x, int y) { MyPixel pixel; SDL_SetRenderDrawColor(renderer, pixel.r, pixel.g, pixel.b, pixel.a); SDL_RenderDrawPoint(renderer, x, y); pixels[y][x] = pixel; Refresh(); } void Application::Run() { SDL_Init(SDL_INIT_VIDEO); if (SDL_WasInit(SDL_INIT_VIDEO) != 0) { std::cout << "SDL2 Video was initialised" << std::endl; } window = SDL_CreateWindow("PixelSort", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, dimension, dimension, SDL_WINDOW_OPENGL); if (window == NULL) { std::cout << "Could not create window: " << SDL_GetError() << std::endl; return; } renderer = SDL_CreateRenderer(window, SDL_RENDERER_ACCELERATED, -1); // Initialize the array and display with random colours for (int y = 0; y < dimension; y++) { for (int x = 0; x < dimension; x++) { DrawRandomColorAt(x, y); } } // Perform the sort, which draws the results as it progresses. Quicksort(0, dimension*dimension-1); // Leave the result on the screen for 10 seconds, then cleanup and quit. SDL_Delay(10000); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); } void Application::Quicksort (int lo, int hi) { if (lo < hi) { int p = Partition(lo, hi); Quicksort(lo, p - 1); Quicksort(p + 1, hi); } } int Application::Partition (int lo, int hi) { //std::cout << "partitioning from " << lo << " to " << hi << std::endl; //std::cout << "pivot is at x:" << hi%dimension << " y:" << hi/dimension << std::endl; MyPixel pivot = pixels[hi/dimension][hi%dimension]; int i = lo - 1; for (int j = lo; j < hi; j++) { if (pixels[j/dimension][j%dimension].Hue() < pivot.Hue()) { i++; SwapAndDrawPixels(i, j); } } SwapAndDrawPixels(hi, i+1); return i + 1; } void Application::SwapAndDrawPixels(int a, int b) { int ax = a%dimension; int ay = a/dimension; int bx = b%dimension; int by = b/dimension; // Swap pixels. Coordinate swapping needs fixing badly. MyPixel temp = pixels[ay][ax]; pixels[ay][ax] = pixels[by][bx]; pixels[by][bx] = temp; // Draw first pixel SDL_SetRenderDrawColor(renderer, pixels[ay][ax].r, pixels[ay][ax].g, pixels[ay][ax].b, pixels[ay][ax].a); SDL_RenderDrawPoint(renderer, ax, ay); // Draw second pixel SDL_SetRenderDrawColor(renderer, pixels[by][bx].r, pixels[by][bx].g, pixels[by][bx].b, pixels[by][bx].a); SDL_RenderDrawPoint(renderer, bx, by); Refresh(); } void Application::Refresh() { if (frameCount++ % speedUp == 0) { SDL_RenderPresent(renderer); } }
27.147826
134
0.60442
ohookins
2195e9f70920cf15b460a1e62e81d31f933d994b
379
cpp
C++
taichi/program/aot_module_builder.cpp
squarefk/test_actions
dd3b0305c49b577102786eb1c24c590ef160bc30
[ "MIT" ]
1
2022-01-29T11:59:50.000Z
2022-01-29T11:59:50.000Z
taichi/program/aot_module_builder.cpp
squarefk/test_actions
dd3b0305c49b577102786eb1c24c590ef160bc30
[ "MIT" ]
null
null
null
taichi/program/aot_module_builder.cpp
squarefk/test_actions
dd3b0305c49b577102786eb1c24c590ef160bc30
[ "MIT" ]
1
2021-08-09T15:47:24.000Z
2021-08-09T15:47:24.000Z
#include "taichi/program/aot_module_builder.h" #include "taichi/program/kernel.h" namespace taichi { namespace lang { void AotModuleBuilder::add(const std::string &identifier, Kernel *kernel) { if (!kernel->lowered() && Kernel::supports_lowering(kernel->arch)) { kernel->lower(); } add_per_backend(identifier, kernel); } } // namespace lang } // namespace taichi
22.294118
75
0.71504
squarefk
219c956c8719ced56b9a4b6d165247f51722f3f6
5,874
hpp
C++
include/El/core/imports/scalapack/pblas.hpp
justusc/Elemental
145ccb28411f3f0c65ca30ecea776df33297e4ff
[ "BSD-3-Clause" ]
null
null
null
include/El/core/imports/scalapack/pblas.hpp
justusc/Elemental
145ccb28411f3f0c65ca30ecea776df33297e4ff
[ "BSD-3-Clause" ]
null
null
null
include/El/core/imports/scalapack/pblas.hpp
justusc/Elemental
145ccb28411f3f0c65ca30ecea776df33297e4ff
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2009-2015, Jack Poulson All rights reserved. This file is part of Elemental and is under the BSD 2-Clause License, which can be found in the LICENSE file in the root directory, or at http://opensource.org/licenses/BSD-2-Clause */ #pragma once #ifndef EL_IMPORTS_SCALAPACK_PBLAS_HPP #define EL_IMPORTS_SCALAPACK_PBLAS_HPP #ifdef EL_HAVE_SCALAPACK namespace El { namespace pblas { // Level 2 // ======= // Gemv // ---- void Gemv ( char trans, int m, int n, float alpha, const float* A, const int* descA, const float* x, const int* descx, int incx, float beta, float* y, const int* descy, int incy ); void Gemv ( char trans, int m, int n, double alpha, const double* A, const int* descA, const double* x, const int* descx, int incx, double beta, double* y, const int* descy, int incy ); void Gemv ( char trans, int m, int n, scomplex alpha, const scomplex* A, const int* descA, const scomplex* x, const int* descx, int incx, scomplex beta, scomplex* y, const int* descy, int incy ); void Gemv ( char trans, int m, int n, dcomplex alpha, const dcomplex* A, const int* descA, const dcomplex* x, const int* descx, int incx, dcomplex beta, dcomplex* y, const int* descy, int incy ); // Hemv // ---- void Hemv ( char uplo, int n, scomplex alpha, const scomplex* A, const int* descA, const scomplex* x, const int* descx, int incx, scomplex beta, scomplex* y, const int* descy, int incy ); void Hemv ( char uplo, int n, dcomplex alpha, const dcomplex* A, const int* descA, const dcomplex* x, const int* descx, int incx, dcomplex beta, dcomplex* y, const int* descy, int incy ); // Symv // ---- void Symv ( char uplo, int n, float alpha, const float* A, const int* descA, const float* x, const int* descx, int incx, float beta, float* y, const int* descy, int incy ); void Symv ( char uplo, int n, double alpha, const double* A, const int* descA, const double* x, const int* descx, int incx, double beta, double* y, const int* descy, int incy ); // Trmv // ---- void Trmv ( char uplo, char trans, char diag, int n, const float* A, const int* descA, float* x, const int* descx, int incx ); void Trmv ( char uplo, char trans, char diag, int n, const double* A, const int* descA, double* x, const int* descx, int incx ); void Trmv ( char uplo, char trans, char diag, int n, const scomplex* A, const int* descA, scomplex* x, const int* descx, int incx ); void Trmv ( char uplo, char trans, char diag, int n, const dcomplex* A, const int* descA, dcomplex* x, const int* descx, int incx ); // Trsv // ---- void Trsv ( char uplo, char trans, char diag, int n, const float* A, const int* descA, float* x, const int* descx, int incx ); void Trsv ( char uplo, char trans, char diag, int n, const double* A, const int* descA, double* x, const int* descx, int incx ); void Trsv ( char uplo, char trans, char diag, int n, const scomplex* A, const int* descA, scomplex* x, const int* descx, int incx ); void Trsv ( char uplo, char trans, char diag, int n, const dcomplex* A, const int* descA, dcomplex* x, const int* descx, int incx ); // Level 3 // ======= // Gemm // ---- void Gemm ( char transa, char transb, int m, int n, int k, float alpha, const float* A, const int* descA, const float* B, const int* descB, float beta, float* C, const int* descC ); void Gemm ( char transa, char transb, int m, int n, int k, double alpha, const double* A, const int* descA, const double* B, const int* descB, double beta, double* C, const int* descC ); void Gemm ( char transa, char transb, int m, int n, int k, scomplex alpha, const scomplex* A, const int* descA, const scomplex* B, const int* descB, scomplex beta, scomplex* C, const int* descC ); void Gemm ( char transa, char transb, int m, int n, int k, dcomplex alpha, const dcomplex* A, const int* descA, const dcomplex* B, const int* descB, dcomplex beta, dcomplex* C, const int* descC ); // Trmm // ---- void Trmm ( char side, char uplo, char trans, char diag, int m, int n, float alpha, const float* A, const int* descA, float* B, const int* descB ); void Trmm ( char side, char uplo, char trans, char diag, int m, int n, double alpha, const double* A, const int* descA, double* B, const int* descB ); void Trmm ( char side, char uplo, char trans, char diag, int m, int n, scomplex alpha, const scomplex* A, const int* descA, scomplex* B, const int* descB ); void Trmm ( char side, char uplo, char trans, char diag, int m, int n, dcomplex alpha, const dcomplex* A, const int* descA, dcomplex* B, const int* descB ); // Trsm // ---- void Trsm ( char side, char uplo, char trans, char diag, int m, int n, float alpha, const float* A, const int* descA, float* B, const int* descB ); void Trsm ( char side, char uplo, char trans, char diag, int m, int n, double alpha, const double* A, const int* descA, double* B, const int* descB ); void Trsm ( char side, char uplo, char trans, char diag, int m, int n, scomplex alpha, const scomplex* A, const int* descA, scomplex* B, const int* descB ); void Trsm ( char side, char uplo, char trans, char diag, int m, int n, dcomplex alpha, const dcomplex* A, const int* descA, dcomplex* B, const int* descB ); } // namespace pblas } // namespace El #endif // ifdef EL_HAVE_SCALAPACK #endif // ifndef EL_IMPORTS_SCALAPACK_PBLAS_HPP
33
73
0.617297
justusc
219ce3d770cb1c2fc6349c0242f5d60a31f39091
129,544
cc
C++
SimFastTiming/FastTimingCommon/src/BTLPulseShape.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
null
null
null
SimFastTiming/FastTimingCommon/src/BTLPulseShape.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
null
null
null
SimFastTiming/FastTimingCommon/src/BTLPulseShape.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
null
null
null
#include "SimFastTiming/FastTimingCommon/interface/BTLPulseShape.h" BTLPulseShape::~BTLPulseShape() { } BTLPulseShape::BTLPulseShape() : MTDShapeBase() { buildMe() ; } void BTLPulseShape::fillShape( MTDShapeBase::DVec& aVec ) const { // --- Pulse shape for a signal of 100 p.e. aVec = { 1.0989088528e-08, // time = 0.00 ns 1.0991907162e-08, // time = 0.01 ns 1.0997329492e-08, // time = 0.02 ns 1.1003584377e-08, // time = 0.03 ns 1.1009992029e-08, // time = 0.04 ns 1.1012972201e-08, // time = 0.05 ns 1.1021256463e-08, // time = 0.06 ns 1.1026509483e-08, // time = 0.07 ns 1.1031466074e-08, // time = 0.08 ns 1.1036719205e-08, // time = 0.09 ns 1.1041674131e-08, // time = 0.10 ns 1.1047045612e-08, // time = 0.11 ns 1.1051815463e-08, // time = 0.12 ns 1.1054848370e-08, // time = 0.13 ns 1.1061600969e-08, // time = 0.14 ns 1.1068583716e-08, // time = 0.15 ns 1.1072180173e-08, // time = 0.16 ns 1.1079616224e-08, // time = 0.17 ns 1.1085058982e-08, // time = 0.18 ns 1.1088839624e-08, // time = 0.19 ns 1.1093972185e-08, // time = 0.20 ns 1.1097449848e-08, // time = 0.21 ns 1.1101024100e-08, // time = 0.22 ns 1.1101378705e-08, // time = 0.23 ns 1.1097040176e-08, // time = 0.24 ns 1.1084638429e-08, // time = 0.25 ns 1.1066582650e-08, // time = 0.26 ns 1.1029894220e-08, // time = 0.27 ns 1.0982672327e-08, // time = 0.28 ns 1.0898173142e-08, // time = 0.29 ns 1.0793557714e-08, // time = 0.30 ns 1.0620891611e-08, // time = 0.31 ns 1.0409881734e-08, // time = 0.32 ns 1.0082901958e-08, // time = 0.33 ns 9.0983337531e-09, // time = 0.34 ns 8.3805116180e-09, // time = 0.35 ns 7.3771350140e-09, // time = 0.36 ns 6.1367581017e-09, // time = 0.37 ns 4.4798341703e-09, // time = 0.38 ns 2.4086144190e-09, // time = 0.39 ns -2.4227331252e-10, // time = 0.40 ns -3.5583425095e-09, // time = 0.41 ns -7.6733522869e-09, // time = 0.42 ns -1.2741777300e-08, // time = 0.43 ns -1.8940880864e-08, // time = 0.44 ns -2.6472953385e-08, // time = 0.45 ns -3.5567657153e-08, // time = 0.46 ns -4.6484470717e-08, // time = 0.47 ns -5.9515207540e-08, // time = 0.48 ns -7.4986613807e-08, // time = 0.49 ns -9.3263022860e-08, // time = 0.50 ns -1.1474906514e-07, // time = 0.51 ns -1.3989241809e-07, // time = 0.52 ns -1.6918658396e-07, // time = 0.53 ns -2.0317369820e-07, // time = 0.54 ns -2.4244733021e-07, // time = 0.55 ns -2.8765528814e-07, // time = 0.56 ns -3.3950240930e-07, // time = 0.57 ns -3.9875332170e-07, // time = 0.58 ns -4.6623516570e-07, // time = 0.59 ns -5.4284025963e-07, // time = 0.60 ns -6.2952871471e-07, // time = 0.61 ns -7.2733098444e-07, // time = 0.62 ns -8.3735028311e-07, // time = 0.63 ns -9.6076490319e-07, // time = 0.64 ns -1.0988305380e-06, // time = 0.65 ns -1.2528823705e-06, // time = 0.66 ns -1.4243370704e-06, // time = 0.67 ns -1.6146946558e-06, // time = 0.68 ns -1.8255402069e-06, // time = 0.69 ns -2.0585454268e-06, // time = 0.70 ns -2.3154700360e-06, // time = 0.71 ns -2.5981629969e-06, // time = 0.72 ns -2.9085635581e-06, // time = 0.73 ns -3.2487021228e-06, // time = 0.74 ns -3.6207009125e-06, // time = 0.75 ns -4.0267744512e-06, // time = 0.76 ns -4.4692298292e-06, // time = 0.77 ns -4.9504667756e-06, // time = 0.78 ns -5.4729775211e-06, // time = 0.79 ns -6.0393464427e-06, // time = 0.80 ns -6.6522494926e-06, // time = 0.81 ns -7.3144534150e-06, // time = 0.82 ns -8.0288147384e-06, // time = 0.83 ns -8.7982785562e-06, // time = 0.84 ns -9.6258770734e-06, // time = 0.85 ns -1.0514727944e-05, // time = 0.86 ns -1.1468032388e-05, // time = 0.87 ns -1.2489073082e-05, // time = 0.88 ns -1.3581211839e-05, // time = 0.89 ns -1.4747887069e-05, // time = 0.90 ns -1.5992611032e-05, // time = 0.91 ns -1.7318966874e-05, // time = 0.92 ns -1.8730605462e-05, // time = 0.93 ns -2.0231242013e-05, // time = 0.94 ns -2.1824652529e-05, // time = 0.95 ns -2.3514670035e-05, // time = 0.96 ns -2.5305180625e-05, // time = 0.97 ns -2.7200119336e-05, // time = 0.98 ns -2.9203465828e-05, // time = 0.99 ns -3.1319239909e-05, // time = 1.00 ns -3.3551496885e-05, // time = 1.01 ns -3.5904322755e-05, // time = 1.02 ns -3.8381829254e-05, // time = 1.03 ns -4.0988148755e-05, // time = 1.04 ns -4.3727429032e-05, // time = 1.05 ns -4.6603827889e-05, // time = 1.06 ns -4.9621507686e-05, // time = 1.07 ns -5.2784629731e-05, // time = 1.08 ns -5.6097348584e-05, // time = 1.09 ns -5.9563806262e-05, // time = 1.10 ns -6.3188126349e-05, // time = 1.11 ns -6.6974408037e-05, // time = 1.12 ns -7.0926720924e-05, // time = 1.13 ns -7.5049099141e-05, // time = 1.14 ns -7.9345531193e-05, // time = 1.15 ns -8.3819956734e-05, // time = 1.16 ns -8.8476260003e-05, // time = 1.17 ns -9.3318263438e-05, // time = 1.18 ns -9.8349721632e-05, // time = 1.19 ns -1.0357431515e-04, // time = 1.20 ns -1.0899564437e-04, // time = 1.21 ns -1.1461722328e-04, // time = 1.22 ns -1.2044247342e-04, // time = 1.23 ns -1.2647471763e-04, // time = 1.24 ns -1.3271717411e-04, // time = 1.25 ns -1.3917295025e-04, // time = 1.26 ns -1.4584503675e-04, // time = 1.27 ns -1.5273630162e-04, // time = 1.28 ns -1.5984948437e-04, // time = 1.29 ns -1.6718719027e-04, // time = 1.30 ns -1.7475188462e-04, // time = 1.31 ns -1.8254588721e-04, // time = 1.32 ns -1.9057136684e-04, // time = 1.33 ns -1.9883033599e-04, // time = 1.34 ns -2.0732464557e-04, // time = 1.35 ns -2.1605597986e-04, // time = 1.36 ns -2.2502585153e-04, // time = 1.37 ns -2.3423559683e-04, // time = 1.38 ns -2.4368637096e-04, // time = 1.39 ns -2.5337914358e-04, // time = 1.40 ns -2.6331469448e-04, // time = 1.41 ns -2.7349360942e-04, // time = 1.42 ns -2.8391627619e-04, // time = 1.43 ns -2.9458288078e-04, // time = 1.44 ns -3.0549340385e-04, // time = 1.45 ns -3.1664761726e-04, // time = 1.46 ns -3.2804508092e-04, // time = 1.47 ns -3.3968513979e-04, // time = 1.48 ns -3.5156692107e-04, // time = 1.49 ns -3.6368933162e-04, // time = 1.50 ns -3.7605105565e-04, // time = 1.51 ns -3.8865055252e-04, // time = 1.52 ns -4.0148605485e-04, // time = 1.53 ns -4.1455556680e-04, // time = 1.54 ns -4.2785686263e-04, // time = 1.55 ns -4.4138748543e-04, // time = 1.56 ns -4.5514474611e-04, // time = 1.57 ns -4.6912572260e-04, // time = 1.58 ns -4.8332725934e-04, // time = 1.59 ns -4.9774596689e-04, // time = 1.60 ns -5.1237822188e-04, // time = 1.61 ns -5.2722016714e-04, // time = 1.62 ns -5.4226771206e-04, // time = 1.63 ns -5.5751653319e-04, // time = 1.64 ns -5.7296207508e-04, // time = 1.65 ns -5.8859955132e-04, // time = 1.66 ns -6.0442394582e-04, // time = 1.67 ns -6.2043001434e-04, // time = 1.68 ns -6.3661228620e-04, // time = 1.69 ns -6.5296506622e-04, // time = 1.70 ns -6.6948243690e-04, // time = 1.71 ns -6.8615826080e-04, // time = 1.72 ns -7.0298618312e-04, // time = 1.73 ns -7.1995963450e-04, // time = 1.74 ns -7.3707183401e-04, // time = 1.75 ns -7.5431579238e-04, // time = 1.76 ns -7.7168431535e-04, // time = 1.77 ns -7.8917000729e-04, // time = 1.78 ns -8.0676527497e-04, // time = 1.79 ns -8.2446233149e-04, // time = 1.80 ns -8.4225320045e-04, // time = 1.81 ns -8.6012972022e-04, // time = 1.82 ns -8.7808354870e-04, // time = 1.83 ns -8.9610616512e-04, // time = 1.84 ns -9.1418888139e-04, // time = 1.85 ns -9.3232283629e-04, // time = 1.86 ns -9.5049901013e-04, // time = 1.87 ns -9.6870822595e-04, // time = 1.88 ns -9.8694115563e-04, // time = 1.89 ns -1.0051883255e-03, // time = 1.90 ns -1.0234401218e-03, // time = 1.91 ns -1.0416867967e-03, // time = 1.92 ns -1.0599184739e-03, // time = 1.93 ns -1.0781251549e-03, // time = 1.94 ns -1.0962967247e-03, // time = 1.95 ns -1.1144229579e-03, // time = 1.96 ns -1.1324935253e-03, // time = 1.97 ns -1.1504979999e-03, // time = 1.98 ns -1.1684258631e-03, // time = 1.99 ns -1.1862665113e-03, // time = 2.00 ns -1.2040092622e-03, // time = 2.01 ns -1.2216433615e-03, // time = 2.02 ns -1.2391579888e-03, // time = 2.03 ns -1.2565422649e-03, // time = 2.04 ns -1.2737852580e-03, // time = 2.05 ns -1.2908759901e-03, // time = 2.06 ns -1.3078034437e-03, // time = 2.07 ns -1.3245565688e-03, // time = 2.08 ns -1.3411242886e-03, // time = 2.09 ns -1.3574955070e-03, // time = 2.10 ns -1.3736591146e-03, // time = 2.11 ns -1.3896039953e-03, // time = 2.12 ns -1.4053190331e-03, // time = 2.13 ns -1.4207931181e-03, // time = 2.14 ns -1.4360151533e-03, // time = 2.15 ns -1.4509740610e-03, // time = 2.16 ns -1.4656587888e-03, // time = 2.17 ns -1.4800583162e-03, // time = 2.18 ns -1.4941616608e-03, // time = 2.19 ns -1.5079578842e-03, // time = 2.20 ns -1.5214360984e-03, // time = 2.21 ns -1.5345854715e-03, // time = 2.22 ns -1.5473952339e-03, // time = 2.23 ns -1.5598546839e-03, // time = 2.24 ns -1.5719531936e-03, // time = 2.25 ns -1.5836802143e-03, // time = 2.26 ns -1.5950252824e-03, // time = 2.27 ns -1.6059780247e-03, // time = 2.28 ns -1.6165281633e-03, // time = 2.29 ns -1.6266655216e-03, // time = 2.30 ns -1.6363800289e-03, // time = 2.31 ns -1.6456617252e-03, // time = 2.32 ns -1.6545007667e-03, // time = 2.33 ns -1.6628874298e-03, // time = 2.34 ns -1.6708121163e-03, // time = 2.35 ns -1.6782653573e-03, // time = 2.36 ns -1.6852378175e-03, // time = 2.37 ns -1.6917203012e-03, // time = 2.38 ns -1.6977037542e-03, // time = 2.39 ns -1.7031792681e-03, // time = 2.40 ns -1.7081380846e-03, // time = 2.41 ns -1.7125715987e-03, // time = 2.42 ns -1.7164713625e-03, // time = 2.43 ns -1.7198290885e-03, // time = 2.44 ns -1.7226366526e-03, // time = 2.45 ns -1.7248860974e-03, // time = 2.46 ns -1.7265696347e-03, // time = 2.47 ns -1.7276796487e-03, // time = 2.48 ns -1.7282086985e-03, // time = 2.49 ns -1.7281495201e-03, // time = 2.50 ns -1.7274950291e-03, // time = 2.51 ns -1.7262383228e-03, // time = 2.52 ns -1.7243726818e-03, // time = 2.53 ns -1.7218915725e-03, // time = 2.54 ns -1.7187886480e-03, // time = 2.55 ns -1.7150577502e-03, // time = 2.56 ns -1.7106929109e-03, // time = 2.57 ns -1.7056883528e-03, // time = 2.58 ns -1.7000384913e-03, // time = 2.59 ns -1.6937379346e-03, // time = 2.60 ns -1.6867814849e-03, // time = 2.61 ns -1.6791641390e-03, // time = 2.62 ns -1.6708810885e-03, // time = 2.63 ns -1.6619277206e-03, // time = 2.64 ns -1.6522996178e-03, // time = 2.65 ns -1.6419925584e-03, // time = 2.66 ns -1.6310025160e-03, // time = 2.67 ns -1.6193256595e-03, // time = 2.68 ns -1.6069583529e-03, // time = 2.69 ns -1.5938971545e-03, // time = 2.70 ns -1.5801388166e-03, // time = 2.71 ns -1.5656802850e-03, // time = 2.72 ns -1.5505186975e-03, // time = 2.73 ns -1.5346513840e-03, // time = 2.74 ns -1.5180758648e-03, // time = 2.75 ns -1.5007898494e-03, // time = 2.76 ns -1.4827912360e-03, // time = 2.77 ns -1.4640781092e-03, // time = 2.78 ns -1.4446487391e-03, // time = 2.79 ns -1.4245015792e-03, // time = 2.80 ns -1.4036352652e-03, // time = 2.81 ns -1.3820486123e-03, // time = 2.82 ns -1.3597406141e-03, // time = 2.83 ns -1.3367104399e-03, // time = 2.84 ns -1.3129574327e-03, // time = 2.85 ns -1.2884811073e-03, // time = 2.86 ns -1.2632811475e-03, // time = 2.87 ns -1.2373574043e-03, // time = 2.88 ns -1.2107098932e-03, // time = 2.89 ns -1.1833387916e-03, // time = 2.90 ns -1.1552444364e-03, // time = 2.91 ns -1.1264273217e-03, // time = 2.92 ns -1.0968880957e-03, // time = 2.93 ns -1.0666275581e-03, // time = 2.94 ns -1.0356466577e-03, // time = 2.95 ns -1.0039464889e-03, // time = 2.96 ns -9.7152828955e-04, // time = 2.97 ns -9.3839343764e-04, // time = 2.98 ns -9.0454344845e-04, // time = 2.99 ns -8.6997997154e-04, // time = 3.00 ns -8.3470478776e-04, // time = 3.01 ns -7.9871980617e-04, // time = 3.02 ns -7.6202706096e-04, // time = 3.03 ns -7.2462870834e-04, // time = 3.04 ns -6.8652702340e-04, // time = 3.05 ns -6.4772439695e-04, // time = 3.06 ns -6.0822333237e-04, // time = 3.07 ns -5.6802644240e-04, // time = 3.08 ns -5.2713644594e-04, // time = 3.09 ns -4.8555616488e-04, // time = 3.10 ns -4.4328852086e-04, // time = 3.11 ns -4.0033653207e-04, // time = 3.12 ns -3.5670331004e-04, // time = 3.13 ns -3.1239205647e-04, // time = 3.14 ns -2.6740605998e-04, // time = 3.15 ns -2.2174869298e-04, // time = 3.16 ns -1.7542340844e-04, // time = 3.17 ns -1.2843373679e-04, // time = 3.18 ns -8.0783282762e-05, // time = 3.19 ns -3.2475722243e-05, // time = 3.20 ns 1.6485200779e-05, // time = 3.21 ns 6.6095677302e-05, // time = 3.22 ns 1.1635183635e-04, // time = 3.23 ns 1.6724974797e-04, // time = 3.24 ns 2.1878542624e-04, // time = 3.25 ns 2.7095483219e-04, // time = 3.26 ns 3.2375387672e-04, // time = 3.27 ns 3.7717842347e-04, // time = 3.28 ns 4.3122429166e-04, // time = 3.29 ns 4.8588725888e-04, // time = 3.30 ns 5.4116306386e-04, // time = 3.31 ns 5.9704740916e-04, // time = 3.32 ns 6.5353596389e-04, // time = 3.33 ns 7.1062436634e-04, // time = 3.34 ns 7.6830822657e-04, // time = 3.35 ns 8.2658312899e-04, // time = 3.36 ns 8.8544463489e-04, // time = 3.37 ns 9.4488820643e-04, // time = 3.38 ns 1.0049094504e-03, // time = 3.39 ns 1.0655038807e-03, // time = 3.40 ns 1.1266669869e-03, // time = 3.41 ns 1.1883942488e-03, // time = 3.42 ns 1.2506811381e-03, // time = 3.43 ns 1.3135231205e-03, // time = 3.44 ns 1.3769156571e-03, // time = 3.45 ns 1.4408542068e-03, // time = 3.46 ns 1.5053342278e-03, // time = 3.47 ns 1.5703511797e-03, // time = 3.48 ns 1.6359005250e-03, // time = 3.49 ns 1.7019777312e-03, // time = 3.50 ns 1.7685782720e-03, // time = 3.51 ns 1.8356976293e-03, // time = 3.52 ns 1.9033312948e-03, // time = 3.53 ns 1.9714747707e-03, // time = 3.54 ns 2.0401235722e-03, // time = 3.55 ns 2.1092732279e-03, // time = 3.56 ns 2.1789192818e-03, // time = 3.57 ns 2.2490572943e-03, // time = 3.58 ns 2.3196828431e-03, // time = 3.59 ns 2.3907915249e-03, // time = 3.60 ns 2.4623789561e-03, // time = 3.61 ns 2.5344407742e-03, // time = 3.62 ns 2.6069726385e-03, // time = 3.63 ns 2.6799702312e-03, // time = 3.64 ns 2.7534292657e-03, // time = 3.65 ns 2.8273454612e-03, // time = 3.66 ns 2.9004936634e-03, // time = 3.67 ns 2.9753041809e-03, // time = 3.68 ns 3.0505592690e-03, // time = 3.69 ns 3.1262547713e-03, // time = 3.70 ns 3.2023865546e-03, // time = 3.71 ns 3.2789505127e-03, // time = 3.72 ns 3.3559425677e-03, // time = 3.73 ns 3.4333586712e-03, // time = 3.74 ns 3.5111948046e-03, // time = 3.75 ns 3.5894469797e-03, // time = 3.76 ns 3.6681112388e-03, // time = 3.77 ns 3.7471836550e-03, // time = 3.78 ns 3.8266603326e-03, // time = 3.79 ns 3.9065374069e-03, // time = 3.80 ns 3.9868110444e-03, // time = 3.81 ns 4.0674774430e-03, // time = 3.82 ns 4.1485328319e-03, // time = 3.83 ns 4.2299734716e-03, // time = 3.84 ns 4.3117956536e-03, // time = 3.85 ns 4.3939957008e-03, // time = 3.86 ns 4.4765699668e-03, // time = 3.87 ns 4.5595148362e-03, // time = 3.88 ns 4.6428267257e-03, // time = 3.89 ns 4.7167852365e-03, // time = 3.90 ns 4.8007790901e-03, // time = 3.91 ns 4.8602278847e-03, // time = 3.92 ns 4.9448283036e-03, // time = 3.93 ns 5.0297795076e-03, // time = 3.94 ns 5.1150781817e-03, // time = 3.95 ns 5.2007209700e-03, // time = 3.96 ns 5.2867045217e-03, // time = 3.97 ns 5.3730255059e-03, // time = 3.98 ns 5.4596806154e-03, // time = 3.99 ns 5.5466665690e-03, // time = 4.00 ns 5.6339801110e-03, // time = 4.01 ns 5.7216180108e-03, // time = 4.02 ns 5.8095770632e-03, // time = 4.03 ns 5.8978540871e-03, // time = 4.04 ns 5.9864459255e-03, // time = 4.05 ns 6.0753494447e-03, // time = 4.06 ns 6.1645615335e-03, // time = 4.07 ns 6.2540791032e-03, // time = 4.08 ns 6.3438990863e-03, // time = 4.09 ns 6.4340184360e-03, // time = 4.10 ns 6.5244341258e-03, // time = 4.11 ns 6.6151431482e-03, // time = 4.12 ns 6.7061425143e-03, // time = 4.13 ns 6.7974292525e-03, // time = 4.14 ns 6.8890004077e-03, // time = 4.15 ns 6.9808530397e-03, // time = 4.16 ns 7.0729842211e-03, // time = 4.17 ns 7.1653910353e-03, // time = 4.18 ns 7.2580705721e-03, // time = 4.19 ns 7.3440609829e-03, // time = 4.20 ns 7.4372574280e-03, // time = 4.21 ns 7.5073204958e-03, // time = 4.22 ns 7.6009774774e-03, // time = 4.23 ns 7.7647108412e-03, // time = 4.24 ns 7.8590715385e-03, // time = 4.25 ns 7.9484164301e-03, // time = 4.26 ns 8.0432639316e-03, // time = 4.27 ns 8.1138466413e-03, // time = 4.28 ns 8.2091218951e-03, // time = 4.29 ns 8.2682310074e-03, // time = 4.30 ns 8.3882494626e-03, // time = 4.31 ns 8.4485916243e-03, // time = 4.32 ns 8.6238415442e-03, // time = 4.33 ns 8.6992927207e-03, // time = 4.34 ns 8.7960008706e-03, // time = 4.35 ns 8.8872807764e-03, // time = 4.36 ns 9.0087432445e-03, // time = 4.37 ns 9.0330481367e-03, // time = 4.38 ns 9.1791618919e-03, // time = 4.39 ns 9.2393257128e-03, // time = 4.40 ns 9.3512527409e-03, // time = 4.41 ns 9.4301714377e-03, // time = 4.42 ns 9.5490812208e-03, // time = 4.43 ns 9.6185900085e-03, // time = 4.44 ns 9.7501114884e-03, // time = 4.45 ns 9.8311335529e-03, // time = 4.46 ns 9.9453750716e-03, // time = 4.47 ns 1.0032655612e-02, // time = 4.48 ns 1.0129949633e-02, // time = 4.49 ns 1.0233282313e-02, // time = 4.50 ns 1.0330049789e-02, // time = 4.51 ns 1.0428020767e-02, // time = 4.52 ns 1.0519332740e-02, // time = 4.53 ns 1.0663759777e-02, // time = 4.54 ns 1.0713409214e-02, // time = 4.55 ns 1.0821962628e-02, // time = 4.56 ns 1.0928230994e-02, // time = 4.57 ns 1.1043194443e-02, // time = 4.58 ns 1.1124551205e-02, // time = 4.59 ns 1.1240042896e-02, // time = 4.60 ns 1.1394909737e-02, // time = 4.61 ns 1.1441355211e-02, // time = 4.62 ns 1.1583062859e-02, // time = 4.63 ns 1.1668960709e-02, // time = 4.64 ns 1.1762635066e-02, // time = 4.65 ns 1.1897117463e-02, // time = 4.66 ns 1.1949376610e-02, // time = 4.67 ns 1.2065564472e-02, // time = 4.68 ns 1.2235715286e-02, // time = 4.69 ns 1.2314042756e-02, // time = 4.70 ns 1.2417100757e-02, // time = 4.71 ns 1.2520291356e-02, // time = 4.72 ns 1.2618292406e-02, // time = 4.73 ns 1.2721731609e-02, // time = 4.74 ns 1.2812262041e-02, // time = 4.75 ns 1.2915930238e-02, // time = 4.76 ns 1.3000112926e-02, // time = 4.77 ns 1.3103994632e-02, // time = 4.78 ns 1.3186315779e-02, // time = 4.79 ns 1.3290401753e-02, // time = 4.80 ns 1.3476565381e-02, // time = 4.81 ns 1.3558770823e-02, // time = 4.82 ns 1.3663242074e-02, // time = 4.83 ns 1.3746429521e-02, // time = 4.84 ns 1.3851081299e-02, // time = 4.85 ns 1.3936013604e-02, // time = 4.86 ns 1.4040837033e-02, // time = 4.87 ns 1.4128651587e-02, // time = 4.88 ns 1.4233637367e-02, // time = 4.89 ns 1.4325700198e-02, // time = 4.90 ns 1.4430838689e-02, // time = 4.91 ns 1.4634285904e-02, // time = 4.92 ns 1.4739635467e-02, // time = 4.93 ns 1.4845049260e-02, // time = 4.94 ns 1.4950523396e-02, // time = 4.95 ns 1.5056054031e-02, // time = 4.96 ns 1.5161637389e-02, // time = 4.97 ns 1.5267269775e-02, // time = 4.98 ns 1.5372947583e-02, // time = 4.99 ns 1.5478667303e-02, // time = 5.00 ns 1.5584425527e-02, // time = 5.01 ns 1.5690218947e-02, // time = 5.02 ns 1.5796044353e-02, // time = 5.03 ns 1.5901898634e-02, // time = 5.04 ns 1.6007778772e-02, // time = 5.05 ns 1.6113681836e-02, // time = 5.06 ns 1.6219604975e-02, // time = 5.07 ns 1.6325545415e-02, // time = 5.08 ns 1.6431500448e-02, // time = 5.09 ns 1.6537467426e-02, // time = 5.10 ns 1.6643443754e-02, // time = 5.11 ns 1.6749426882e-02, // time = 5.12 ns 1.6855414301e-02, // time = 5.13 ns 1.6961403529e-02, // time = 5.14 ns 1.7067392113e-02, // time = 5.15 ns 1.7173377618e-02, // time = 5.16 ns 1.7279357622e-02, // time = 5.17 ns 1.7385329714e-02, // time = 5.18 ns 1.7491291488e-02, // time = 5.19 ns 1.7597240536e-02, // time = 5.20 ns 1.7703174451e-02, // time = 5.21 ns 1.7809090822e-02, // time = 5.22 ns 1.7914987227e-02, // time = 5.23 ns 1.8020861240e-02, // time = 5.24 ns 1.8126710423e-02, // time = 5.25 ns 1.8232532328e-02, // time = 5.26 ns 1.8338324496e-02, // time = 5.27 ns 1.8444084459e-02, // time = 5.28 ns 1.8549809734e-02, // time = 5.29 ns 1.8655497834e-02, // time = 5.30 ns 1.8761146256e-02, // time = 5.31 ns 1.8866752493e-02, // time = 5.32 ns 1.8972314029e-02, // time = 5.33 ns 1.9077828342e-02, // time = 5.34 ns 1.9183292903e-02, // time = 5.35 ns 1.9288705183e-02, // time = 5.36 ns 1.9394062647e-02, // time = 5.37 ns 1.9499362761e-02, // time = 5.38 ns 1.9604602991e-02, // time = 5.39 ns 1.9709780805e-02, // time = 5.40 ns 1.9814893674e-02, // time = 5.41 ns 1.9919939073e-02, // time = 5.42 ns 2.0024914485e-02, // time = 5.43 ns 2.0129817397e-02, // time = 5.44 ns 2.0234645308e-02, // time = 5.45 ns 2.0339395722e-02, // time = 5.46 ns 2.0444066159e-02, // time = 5.47 ns 2.0548654146e-02, // time = 5.48 ns 2.0653157225e-02, // time = 5.49 ns 2.0757572950e-02, // time = 5.50 ns 2.0861898891e-02, // time = 5.51 ns 2.0966132631e-02, // time = 5.52 ns 2.1070271770e-02, // time = 5.53 ns 2.1174313924e-02, // time = 5.54 ns 2.1278256725e-02, // time = 5.55 ns 2.1382097823e-02, // time = 5.56 ns 2.1485834887e-02, // time = 5.57 ns 2.1589465602e-02, // time = 5.58 ns 2.1692987672e-02, // time = 5.59 ns 2.1796398820e-02, // time = 5.60 ns 2.1899696790e-02, // time = 5.61 ns 2.2002879342e-02, // time = 5.62 ns 2.2105944257e-02, // time = 5.63 ns 2.2208889335e-02, // time = 5.64 ns 2.2311712397e-02, // time = 5.65 ns 2.2414411282e-02, // time = 5.66 ns 2.2516983850e-02, // time = 5.67 ns 2.2619427980e-02, // time = 5.68 ns 2.2721741570e-02, // time = 5.69 ns 2.2823922540e-02, // time = 5.70 ns 2.2925968827e-02, // time = 5.71 ns 2.3027878390e-02, // time = 5.72 ns 2.3129649206e-02, // time = 5.73 ns 2.3231279271e-02, // time = 5.74 ns 2.3332766602e-02, // time = 5.75 ns 2.3434109235e-02, // time = 5.76 ns 2.3535305224e-02, // time = 5.77 ns 2.3636352643e-02, // time = 5.78 ns 2.3737249584e-02, // time = 5.79 ns 2.3837994159e-02, // time = 5.80 ns 2.3938584498e-02, // time = 5.81 ns 2.4039018750e-02, // time = 5.82 ns 2.4139295081e-02, // time = 5.83 ns 2.4239411677e-02, // time = 5.84 ns 2.4339366743e-02, // time = 5.85 ns 2.4439158498e-02, // time = 5.86 ns 2.4538785183e-02, // time = 5.87 ns 2.4638245056e-02, // time = 5.88 ns 2.4737536390e-02, // time = 5.89 ns 2.4836657480e-02, // time = 5.90 ns 2.4935606635e-02, // time = 5.91 ns 2.5034382182e-02, // time = 5.92 ns 2.5132982467e-02, // time = 5.93 ns 2.5231405850e-02, // time = 5.94 ns 2.5329650711e-02, // time = 5.95 ns 2.5427715445e-02, // time = 5.96 ns 2.5525598466e-02, // time = 5.97 ns 2.5623298201e-02, // time = 5.98 ns 2.5720813097e-02, // time = 5.99 ns 2.5818141616e-02, // time = 6.00 ns 2.5915282237e-02, // time = 6.01 ns 2.6012233454e-02, // time = 6.02 ns 2.6108993779e-02, // time = 6.03 ns 2.6205561738e-02, // time = 6.04 ns 2.6301935875e-02, // time = 6.05 ns 2.6398114748e-02, // time = 6.06 ns 2.6494096932e-02, // time = 6.07 ns 2.6589881018e-02, // time = 6.08 ns 2.6685465611e-02, // time = 6.09 ns 2.6780849333e-02, // time = 6.10 ns 2.6876030820e-02, // time = 6.11 ns 2.6971008724e-02, // time = 6.12 ns 2.7065781713e-02, // time = 6.13 ns 2.7160348468e-02, // time = 6.14 ns 2.7254707686e-02, // time = 6.15 ns 2.7348858078e-02, // time = 6.16 ns 2.7442798373e-02, // time = 6.17 ns 2.7536527310e-02, // time = 6.18 ns 2.7630043645e-02, // time = 6.19 ns 2.7723346149e-02, // time = 6.20 ns 2.7816433605e-02, // time = 6.21 ns 2.7909304812e-02, // time = 6.22 ns 2.8001958582e-02, // time = 6.23 ns 2.8094393742e-02, // time = 6.24 ns 2.8186609131e-02, // time = 6.25 ns 2.8278603605e-02, // time = 6.26 ns 2.8370376030e-02, // time = 6.27 ns 2.8461925288e-02, // time = 6.28 ns 2.8553250273e-02, // time = 6.29 ns 2.8644349892e-02, // time = 6.30 ns 2.8735223067e-02, // time = 6.31 ns 2.8825868731e-02, // time = 6.32 ns 2.8916285832e-02, // time = 6.33 ns 2.9006473329e-02, // time = 6.34 ns 2.9096430194e-02, // time = 6.35 ns 2.9186155413e-02, // time = 6.36 ns 2.9275647982e-02, // time = 6.37 ns 2.9364906913e-02, // time = 6.38 ns 2.9453931227e-02, // time = 6.39 ns 2.9542719958e-02, // time = 6.40 ns 2.9631272154e-02, // time = 6.41 ns 2.9719586872e-02, // time = 6.42 ns 2.9807663183e-02, // time = 6.43 ns 2.9895500169e-02, // time = 6.44 ns 2.9983096924e-02, // time = 6.45 ns 3.0070452553e-02, // time = 6.46 ns 3.0157566173e-02, // time = 6.47 ns 3.0244436913e-02, // time = 6.48 ns 3.0331063911e-02, // time = 6.49 ns 3.0417446319e-02, // time = 6.50 ns 3.0503583299e-02, // time = 6.51 ns 3.0589474023e-02, // time = 6.52 ns 3.0675117675e-02, // time = 6.53 ns 3.0760513450e-02, // time = 6.54 ns 3.0845660553e-02, // time = 6.55 ns 3.0930558200e-02, // time = 6.56 ns 3.1015205618e-02, // time = 6.57 ns 3.1099602044e-02, // time = 6.58 ns 3.1183746726e-02, // time = 6.59 ns 3.1267638921e-02, // time = 6.60 ns 3.1351277899e-02, // time = 6.61 ns 3.1434662936e-02, // time = 6.62 ns 3.1517793322e-02, // time = 6.63 ns 3.1600668355e-02, // time = 6.64 ns 3.1683287345e-02, // time = 6.65 ns 3.1765649608e-02, // time = 6.66 ns 3.1847754474e-02, // time = 6.67 ns 3.1929601281e-02, // time = 6.68 ns 3.2011189377e-02, // time = 6.69 ns 3.2092518118e-02, // time = 6.70 ns 3.2173586873e-02, // time = 6.71 ns 3.2254395017e-02, // time = 6.72 ns 3.2334941937e-02, // time = 6.73 ns 3.2415227027e-02, // time = 6.74 ns 3.2495249694e-02, // time = 6.75 ns 3.2575009350e-02, // time = 6.76 ns 3.2654505420e-02, // time = 6.77 ns 3.2733737335e-02, // time = 6.78 ns 3.2812704537e-02, // time = 6.79 ns 3.2891406477e-02, // time = 6.80 ns 3.2969842615e-02, // time = 6.81 ns 3.3048012418e-02, // time = 6.82 ns 3.3125915365e-02, // time = 6.83 ns 3.3203550943e-02, // time = 6.84 ns 3.3280918645e-02, // time = 6.85 ns 3.3358017977e-02, // time = 6.86 ns 3.3434848450e-02, // time = 6.87 ns 3.3511409587e-02, // time = 6.88 ns 3.3587700917e-02, // time = 6.89 ns 3.3663721980e-02, // time = 6.90 ns 3.3739472321e-02, // time = 6.91 ns 3.3814951497e-02, // time = 6.92 ns 3.3890159072e-02, // time = 6.93 ns 3.3965094619e-02, // time = 6.94 ns 3.4039757717e-02, // time = 6.95 ns 3.4114147958e-02, // time = 6.96 ns 3.4188264937e-02, // time = 6.97 ns 3.4262108261e-02, // time = 6.98 ns 3.4335677544e-02, // time = 6.99 ns 3.4408972408e-02, // time = 7.00 ns 3.4481992483e-02, // time = 7.01 ns 3.4554737407e-02, // time = 7.02 ns 3.4627206828e-02, // time = 7.03 ns 3.4699400399e-02, // time = 7.04 ns 3.4771317782e-02, // time = 7.05 ns 3.4842958649e-02, // time = 7.06 ns 3.4914322677e-02, // time = 7.07 ns 3.4985409552e-02, // time = 7.08 ns 3.5056218968e-02, // time = 7.09 ns 3.5126750628e-02, // time = 7.10 ns 3.5197004239e-02, // time = 7.11 ns 3.5266979521e-02, // time = 7.12 ns 3.5336676196e-02, // time = 7.13 ns 3.5406093999e-02, // time = 7.14 ns 3.5475232668e-02, // time = 7.15 ns 3.5544091952e-02, // time = 7.16 ns 3.5612671605e-02, // time = 7.17 ns 3.5680971390e-02, // time = 7.18 ns 3.5748991078e-02, // time = 7.19 ns 3.5816730445e-02, // time = 7.20 ns 3.5884189277e-02, // time = 7.21 ns 3.5951367365e-02, // time = 7.22 ns 3.6018264510e-02, // time = 7.23 ns 3.6084880518e-02, // time = 7.24 ns 3.6151215202e-02, // time = 7.25 ns 3.6217268385e-02, // time = 7.26 ns 3.6283039894e-02, // time = 7.27 ns 3.6348529564e-02, // time = 7.28 ns 3.6413737239e-02, // time = 7.29 ns 3.6478662768e-02, // time = 7.30 ns 3.6543306006e-02, // time = 7.31 ns 3.6607666819e-02, // time = 7.32 ns 3.6671745075e-02, // time = 7.33 ns 3.6735540652e-02, // time = 7.34 ns 3.6799053435e-02, // time = 7.35 ns 3.6862283314e-02, // time = 7.36 ns 3.6925230186e-02, // time = 7.37 ns 3.6987893957e-02, // time = 7.38 ns 3.7050274537e-02, // time = 7.39 ns 3.7112371844e-02, // time = 7.40 ns 3.7174185802e-02, // time = 7.41 ns 3.7235716342e-02, // time = 7.42 ns 3.7296963401e-02, // time = 7.43 ns 3.7357926924e-02, // time = 7.44 ns 3.7418606859e-02, // time = 7.45 ns 3.7479003165e-02, // time = 7.46 ns 3.7539115804e-02, // time = 7.47 ns 3.7598944746e-02, // time = 7.48 ns 3.7658489965e-02, // time = 7.49 ns 3.7717751444e-02, // time = 7.50 ns 3.7776729171e-02, // time = 7.51 ns 3.7835423140e-02, // time = 7.52 ns 3.7893833352e-02, // time = 7.53 ns 3.7951959812e-02, // time = 7.54 ns 3.8009802534e-02, // time = 7.55 ns 3.8067361534e-02, // time = 7.56 ns 3.8124636839e-02, // time = 7.57 ns 3.8181628477e-02, // time = 7.58 ns 3.8238336486e-02, // time = 7.59 ns 3.8294760907e-02, // time = 7.60 ns 3.8350901786e-02, // time = 7.61 ns 3.8406759179e-02, // time = 7.62 ns 3.8462333144e-02, // time = 7.63 ns 3.8517623746e-02, // time = 7.64 ns 3.8572631054e-02, // time = 7.65 ns 3.8627355146e-02, // time = 7.66 ns 3.8681796102e-02, // time = 7.67 ns 3.8735954008e-02, // time = 7.68 ns 3.8789828959e-02, // time = 7.69 ns 3.8843421050e-02, // time = 7.70 ns 3.8896730386e-02, // time = 7.71 ns 3.8949757074e-02, // time = 7.72 ns 3.9002501228e-02, // time = 7.73 ns 3.9054962968e-02, // time = 7.74 ns 3.9107142416e-02, // time = 7.75 ns 3.9159039703e-02, // time = 7.76 ns 3.9210654962e-02, // time = 7.77 ns 3.9261988333e-02, // time = 7.78 ns 3.9313039960e-02, // time = 7.79 ns 3.9363809992e-02, // time = 7.80 ns 3.9414298585e-02, // time = 7.81 ns 3.9464505896e-02, // time = 7.82 ns 3.9514432090e-02, // time = 7.83 ns 3.9564077336e-02, // time = 7.84 ns 3.9613441807e-02, // time = 7.85 ns 3.9662525682e-02, // time = 7.86 ns 3.9711329143e-02, // time = 7.87 ns 3.9759852379e-02, // time = 7.88 ns 3.9808095582e-02, // time = 7.89 ns 3.9856058947e-02, // time = 7.90 ns 3.9903742678e-02, // time = 7.91 ns 3.9951146980e-02, // time = 7.92 ns 3.9998272062e-02, // time = 7.93 ns 4.0045118140e-02, // time = 7.94 ns 4.0091685433e-02, // time = 7.95 ns 4.0137974165e-02, // time = 7.96 ns 4.0183984562e-02, // time = 7.97 ns 4.0229716858e-02, // time = 7.98 ns 4.0275171288e-02, // time = 7.99 ns 4.0320348093e-02, // time = 8.00 ns 4.0365247518e-02, // time = 8.01 ns 4.0409869810e-02, // time = 8.02 ns 4.0454215224e-02, // time = 8.03 ns 4.0498284015e-02, // time = 8.04 ns 4.0542076445e-02, // time = 8.05 ns 4.0585592779e-02, // time = 8.06 ns 4.0628833284e-02, // time = 8.07 ns 4.0671798234e-02, // time = 8.08 ns 4.0714487906e-02, // time = 8.09 ns 4.0756902579e-02, // time = 8.10 ns 4.0799042538e-02, // time = 8.11 ns 4.0840908071e-02, // time = 8.12 ns 4.0882499469e-02, // time = 8.13 ns 4.0923817027e-02, // time = 8.14 ns 4.0964861045e-02, // time = 8.15 ns 4.1005631825e-02, // time = 8.16 ns 4.1046129674e-02, // time = 8.17 ns 4.1086354900e-02, // time = 8.18 ns 4.1126307818e-02, // time = 8.19 ns 4.1165988744e-02, // time = 8.20 ns 4.1205397998e-02, // time = 8.21 ns 4.1244535904e-02, // time = 8.22 ns 4.1283402790e-02, // time = 8.23 ns 4.1321998985e-02, // time = 8.24 ns 4.1360324823e-02, // time = 8.25 ns 4.1398380641e-02, // time = 8.26 ns 4.1436166781e-02, // time = 8.27 ns 4.1473683584e-02, // time = 8.28 ns 4.1510931399e-02, // time = 8.29 ns 4.1547910575e-02, // time = 8.30 ns 4.1584621466e-02, // time = 8.31 ns 4.1621064427e-02, // time = 8.32 ns 4.1657239819e-02, // time = 8.33 ns 4.1693148003e-02, // time = 8.34 ns 4.1728789345e-02, // time = 8.35 ns 4.1764164214e-02, // time = 8.36 ns 4.1799272982e-02, // time = 8.37 ns 4.1834116022e-02, // time = 8.38 ns 4.1868693712e-02, // time = 8.39 ns 4.1903006433e-02, // time = 8.40 ns 4.1937054567e-02, // time = 8.41 ns 4.1970838502e-02, // time = 8.42 ns 4.2004358625e-02, // time = 8.43 ns 4.2037615328e-02, // time = 8.44 ns 4.2070609006e-02, // time = 8.45 ns 4.2103340056e-02, // time = 8.46 ns 4.2135808878e-02, // time = 8.47 ns 4.2168015875e-02, // time = 8.48 ns 4.2199961451e-02, // time = 8.49 ns 4.2231646015e-02, // time = 8.50 ns 4.2263069977e-02, // time = 8.51 ns 4.2294233751e-02, // time = 8.52 ns 4.2325137751e-02, // time = 8.53 ns 4.2355782397e-02, // time = 8.54 ns 4.2386168109e-02, // time = 8.55 ns 4.2416295310e-02, // time = 8.56 ns 4.2446164425e-02, // time = 8.57 ns 4.2475775884e-02, // time = 8.58 ns 4.2505130116e-02, // time = 8.59 ns 4.2534227555e-02, // time = 8.60 ns 4.2563068635e-02, // time = 8.61 ns 4.2591653795e-02, // time = 8.62 ns 4.2619983474e-02, // time = 8.63 ns 4.2648058114e-02, // time = 8.64 ns 4.2675878161e-02, // time = 8.65 ns 4.2703444060e-02, // time = 8.66 ns 4.2730756261e-02, // time = 8.67 ns 4.2757815216e-02, // time = 8.68 ns 4.2784621377e-02, // time = 8.69 ns 4.2811175199e-02, // time = 8.70 ns 4.2837477142e-02, // time = 8.71 ns 4.2863527663e-02, // time = 8.72 ns 4.2889327226e-02, // time = 8.73 ns 4.2914876294e-02, // time = 8.74 ns 4.2940175333e-02, // time = 8.75 ns 4.2965224811e-02, // time = 8.76 ns 4.2990025198e-02, // time = 8.77 ns 4.3014576966e-02, // time = 8.78 ns 4.3038880588e-02, // time = 8.79 ns 4.3062936541e-02, // time = 8.80 ns 4.3086745303e-02, // time = 8.81 ns 4.3110307352e-02, // time = 8.82 ns 4.3133623171e-02, // time = 8.83 ns 4.3156693242e-02, // time = 8.84 ns 4.3179518051e-02, // time = 8.85 ns 4.3202098085e-02, // time = 8.86 ns 4.3224433832e-02, // time = 8.87 ns 4.3246525782e-02, // time = 8.88 ns 4.3268374428e-02, // time = 8.89 ns 4.3289980264e-02, // time = 8.90 ns 4.3311343785e-02, // time = 8.91 ns 4.3332465488e-02, // time = 8.92 ns 4.3353345872e-02, // time = 8.93 ns 4.3373985438e-02, // time = 8.94 ns 4.3394384688e-02, // time = 8.95 ns 4.3414544124e-02, // time = 8.96 ns 4.3434464253e-02, // time = 8.97 ns 4.3454145581e-02, // time = 8.98 ns 4.3473588617e-02, // time = 8.99 ns 4.3492793869e-02, // time = 9.00 ns 4.3511761849e-02, // time = 9.01 ns 4.3530493070e-02, // time = 9.02 ns 4.3548988046e-02, // time = 9.03 ns 4.3567247292e-02, // time = 9.04 ns 4.3585271325e-02, // time = 9.05 ns 4.3603060663e-02, // time = 9.06 ns 4.3620615826e-02, // time = 9.07 ns 4.3637937335e-02, // time = 9.08 ns 4.3655025711e-02, // time = 9.09 ns 4.3671881478e-02, // time = 9.10 ns 4.3688505162e-02, // time = 9.11 ns 4.3704897287e-02, // time = 9.12 ns 4.3721058381e-02, // time = 9.13 ns 4.3736988972e-02, // time = 9.14 ns 4.3752689590e-02, // time = 9.15 ns 4.3768160766e-02, // time = 9.16 ns 4.3783403030e-02, // time = 9.17 ns 4.3798416918e-02, // time = 9.18 ns 4.3813202961e-02, // time = 9.19 ns 4.3827761696e-02, // time = 9.20 ns 4.3842093659e-02, // time = 9.21 ns 4.3856199386e-02, // time = 9.22 ns 4.3870079417e-02, // time = 9.23 ns 4.3883734290e-02, // time = 9.24 ns 4.3897164545e-02, // time = 9.25 ns 4.3910370724e-02, // time = 9.26 ns 4.3923353370e-02, // time = 9.27 ns 4.3936113024e-02, // time = 9.28 ns 4.3948650231e-02, // time = 9.29 ns 4.3960965536e-02, // time = 9.30 ns 4.3973059484e-02, // time = 9.31 ns 4.3984932623e-02, // time = 9.32 ns 4.3996585499e-02, // time = 9.33 ns 4.4008018661e-02, // time = 9.34 ns 4.4019232657e-02, // time = 9.35 ns 4.4030228038e-02, // time = 9.36 ns 4.4041005354e-02, // time = 9.37 ns 4.4051565157e-02, // time = 9.38 ns 4.4061907998e-02, // time = 9.39 ns 4.4072034430e-02, // time = 9.40 ns 4.4081945006e-02, // time = 9.41 ns 4.4091640281e-02, // time = 9.42 ns 4.4101120809e-02, // time = 9.43 ns 4.4110387146e-02, // time = 9.44 ns 4.4119439848e-02, // time = 9.45 ns 4.4128279471e-02, // time = 9.46 ns 4.4136906572e-02, // time = 9.47 ns 4.4145321709e-02, // time = 9.48 ns 4.4153525441e-02, // time = 9.49 ns 4.4161518326e-02, // time = 9.50 ns 4.4169300924e-02, // time = 9.51 ns 4.4176873794e-02, // time = 9.52 ns 4.4184237498e-02, // time = 9.53 ns 4.4191392594e-02, // time = 9.54 ns 4.4198339646e-02, // time = 9.55 ns 4.4205079215e-02, // time = 9.56 ns 4.4211611862e-02, // time = 9.57 ns 4.4217938150e-02, // time = 9.58 ns 4.4224058643e-02, // time = 9.59 ns 4.4229973903e-02, // time = 9.60 ns 4.4235684494e-02, // time = 9.61 ns 4.4241190981e-02, // time = 9.62 ns 4.4246493927e-02, // time = 9.63 ns 4.4251593898e-02, // time = 9.64 ns 4.4256491458e-02, // time = 9.65 ns 4.4261187173e-02, // time = 9.66 ns 4.4265681608e-02, // time = 9.67 ns 4.4269975329e-02, // time = 9.68 ns 4.4274068903e-02, // time = 9.69 ns 4.4277962895e-02, // time = 9.70 ns 4.4281657872e-02, // time = 9.71 ns 4.4285154401e-02, // time = 9.72 ns 4.4288453049e-02, // time = 9.73 ns 4.4291554383e-02, // time = 9.74 ns 4.4294458970e-02, // time = 9.75 ns 4.4297167378e-02, // time = 9.76 ns 4.4299680174e-02, // time = 9.77 ns 4.4301997927e-02, // time = 9.78 ns 4.4304121204e-02, // time = 9.79 ns 4.4306050573e-02, // time = 9.80 ns 4.4307786602e-02, // time = 9.81 ns 4.4309329860e-02, // time = 9.82 ns 4.4310680914e-02, // time = 9.83 ns 4.4311840333e-02, // time = 9.84 ns 4.4312808686e-02, // time = 9.85 ns 4.4313586540e-02, // time = 9.86 ns 4.4314174465e-02, // time = 9.87 ns 4.4314573028e-02, // time = 9.88 ns 4.4314782799e-02, // time = 9.89 ns 4.4314804345e-02, // time = 9.90 ns 4.4314638236e-02, // time = 9.91 ns 4.4314285039e-02, // time = 9.92 ns 4.4313745323e-02, // time = 9.93 ns 4.4313019656e-02, // time = 9.94 ns 4.4312108607e-02, // time = 9.95 ns 4.4311012744e-02, // time = 9.96 ns 4.4309732634e-02, // time = 9.97 ns 4.4308268847e-02, // time = 9.98 ns 4.4306943489e-02, // time = 9.99 ns 4.4305497338e-02, // time = 10.00 ns 4.4304148409e-02, // time = 10.01 ns 4.4302503963e-02, // time = 10.02 ns 4.4300287188e-02, // time = 10.03 ns 4.4297890382e-02, // time = 10.04 ns 4.4295313621e-02, // time = 10.05 ns 4.4292557310e-02, // time = 10.06 ns 4.4289621962e-02, // time = 10.07 ns 4.4286508124e-02, // time = 10.08 ns 4.4283216357e-02, // time = 10.09 ns 4.4279747225e-02, // time = 10.10 ns 4.4276101295e-02, // time = 10.11 ns 4.4272279131e-02, // time = 10.12 ns 4.4268281299e-02, // time = 10.13 ns 4.4264108366e-02, // time = 10.14 ns 4.4259760895e-02, // time = 10.15 ns 4.4255239453e-02, // time = 10.16 ns 4.4250544605e-02, // time = 10.17 ns 4.4245676914e-02, // time = 10.18 ns 4.4240636946e-02, // time = 10.19 ns 4.4235425264e-02, // time = 10.20 ns 4.4230042432e-02, // time = 10.21 ns 4.4224489014e-02, // time = 10.22 ns 4.4218765573e-02, // time = 10.23 ns 4.4212872672e-02, // time = 10.24 ns 4.4206810874e-02, // time = 10.25 ns 4.4200580741e-02, // time = 10.26 ns 4.4194182835e-02, // time = 10.27 ns 4.4187617718e-02, // time = 10.28 ns 4.4180885951e-02, // time = 10.29 ns 4.4173988094e-02, // time = 10.30 ns 4.4166924710e-02, // time = 10.31 ns 4.4159696357e-02, // time = 10.32 ns 4.4152303597e-02, // time = 10.33 ns 4.4144746988e-02, // time = 10.34 ns 4.4137027089e-02, // time = 10.35 ns 4.4129144460e-02, // time = 10.36 ns 4.4121099658e-02, // time = 10.37 ns 4.4112893242e-02, // time = 10.38 ns 4.4104525770e-02, // time = 10.39 ns 4.4095997798e-02, // time = 10.40 ns 4.4087309883e-02, // time = 10.41 ns 4.4078462582e-02, // time = 10.42 ns 4.4069456450e-02, // time = 10.43 ns 4.4060292043e-02, // time = 10.44 ns 4.4050969916e-02, // time = 10.45 ns 4.4041490624e-02, // time = 10.46 ns 4.4031854720e-02, // time = 10.47 ns 4.4022062757e-02, // time = 10.48 ns 4.4012115291e-02, // time = 10.49 ns 4.4002012872e-02, // time = 10.50 ns 4.3991756053e-02, // time = 10.51 ns 4.3981345386e-02, // time = 10.52 ns 4.3970781422e-02, // time = 10.53 ns 4.3960064712e-02, // time = 10.54 ns 4.3949195806e-02, // time = 10.55 ns 4.3938175253e-02, // time = 10.56 ns 4.3927003603e-02, // time = 10.57 ns 4.3915681405e-02, // time = 10.58 ns 4.3904209206e-02, // time = 10.59 ns 4.3892587554e-02, // time = 10.60 ns 4.3880816996e-02, // time = 10.61 ns 4.3868898079e-02, // time = 10.62 ns 4.3856831349e-02, // time = 10.63 ns 4.3844617351e-02, // time = 10.64 ns 4.3832256629e-02, // time = 10.65 ns 4.3819749728e-02, // time = 10.66 ns 4.3807097193e-02, // time = 10.67 ns 4.3794299565e-02, // time = 10.68 ns 4.3781357387e-02, // time = 10.69 ns 4.3768271201e-02, // time = 10.70 ns 4.3755041549e-02, // time = 10.71 ns 4.3741668971e-02, // time = 10.72 ns 4.3728154008e-02, // time = 10.73 ns 4.3714497198e-02, // time = 10.74 ns 4.3700699081e-02, // time = 10.75 ns 4.3686760195e-02, // time = 10.76 ns 4.3672681077e-02, // time = 10.77 ns 4.3658462266e-02, // time = 10.78 ns 4.3644104296e-02, // time = 10.79 ns 4.3629607703e-02, // time = 10.80 ns 4.3614973023e-02, // time = 10.81 ns 4.3600200791e-02, // time = 10.82 ns 4.3585291539e-02, // time = 10.83 ns 4.3570245801e-02, // time = 10.84 ns 4.3555064109e-02, // time = 10.85 ns 4.3539746996e-02, // time = 10.86 ns 4.3524294991e-02, // time = 10.87 ns 4.3508708626e-02, // time = 10.88 ns 4.3492988430e-02, // time = 10.89 ns 4.3477134932e-02, // time = 10.90 ns 4.3461148660e-02, // time = 10.91 ns 4.3445030142e-02, // time = 10.92 ns 4.3428779906e-02, // time = 10.93 ns 4.3412398476e-02, // time = 10.94 ns 4.3395886379e-02, // time = 10.95 ns 4.3379244138e-02, // time = 10.96 ns 4.3362472279e-02, // time = 10.97 ns 4.3345571325e-02, // time = 10.98 ns 4.3328541797e-02, // time = 10.99 ns 4.3311384218e-02, // time = 11.00 ns 4.3294099109e-02, // time = 11.01 ns 4.3276686989e-02, // time = 11.02 ns 4.3259148379e-02, // time = 11.03 ns 4.3241483798e-02, // time = 11.04 ns 4.3223693763e-02, // time = 11.05 ns 4.3205778791e-02, // time = 11.06 ns 4.3187739400e-02, // time = 11.07 ns 4.3169576104e-02, // time = 11.08 ns 4.3151289419e-02, // time = 11.09 ns 4.3132879858e-02, // time = 11.10 ns 4.3114347936e-02, // time = 11.11 ns 4.3095694164e-02, // time = 11.12 ns 4.3076919054e-02, // time = 11.13 ns 4.3058023118e-02, // time = 11.14 ns 4.3039006865e-02, // time = 11.15 ns 4.3019870805e-02, // time = 11.16 ns 4.3000615446e-02, // time = 11.17 ns 4.2981241296e-02, // time = 11.18 ns 4.2961748862e-02, // time = 11.19 ns 4.2942138650e-02, // time = 11.20 ns 4.2922411165e-02, // time = 11.21 ns 4.2902566911e-02, // time = 11.22 ns 4.2882606392e-02, // time = 11.23 ns 4.2862530111e-02, // time = 11.24 ns 4.2842338570e-02, // time = 11.25 ns 4.2822032269e-02, // time = 11.26 ns 4.2801611709e-02, // time = 11.27 ns 4.2781077388e-02, // time = 11.28 ns 4.2760429806e-02, // time = 11.29 ns 4.2739669461e-02, // time = 11.30 ns 4.2718796848e-02, // time = 11.31 ns 4.2697812463e-02, // time = 11.32 ns 4.2676716802e-02, // time = 11.33 ns 4.2655510359e-02, // time = 11.34 ns 4.2634193627e-02, // time = 11.35 ns 4.2612767097e-02, // time = 11.36 ns 4.2591231263e-02, // time = 11.37 ns 4.2569586614e-02, // time = 11.38 ns 4.2547833639e-02, // time = 11.39 ns 4.2525972829e-02, // time = 11.40 ns 4.2504004669e-02, // time = 11.41 ns 4.2481929649e-02, // time = 11.42 ns 4.2459748252e-02, // time = 11.43 ns 4.2437460966e-02, // time = 11.44 ns 4.2415068273e-02, // time = 11.45 ns 4.2392570658e-02, // time = 11.46 ns 4.2369968603e-02, // time = 11.47 ns 4.2347262589e-02, // time = 11.48 ns 4.2324453096e-02, // time = 11.49 ns 4.2301540605e-02, // time = 11.50 ns 4.2278525595e-02, // time = 11.51 ns 4.2255408542e-02, // time = 11.52 ns 4.2232189924e-02, // time = 11.53 ns 4.2208870217e-02, // time = 11.54 ns 4.2185449896e-02, // time = 11.55 ns 4.2161929435e-02, // time = 11.56 ns 4.2138309306e-02, // time = 11.57 ns 4.2114589983e-02, // time = 11.58 ns 4.2090771936e-02, // time = 11.59 ns 4.2066855636e-02, // time = 11.60 ns 4.2042841552e-02, // time = 11.61 ns 4.2018730152e-02, // time = 11.62 ns 4.1994521904e-02, // time = 11.63 ns 4.1970217275e-02, // time = 11.64 ns 4.1945816729e-02, // time = 11.65 ns 4.1921320731e-02, // time = 11.66 ns 4.1896729746e-02, // time = 11.67 ns 4.1872044235e-02, // time = 11.68 ns 4.1847264660e-02, // time = 11.69 ns 4.1822391482e-02, // time = 11.70 ns 4.1797425160e-02, // time = 11.71 ns 4.1772366154e-02, // time = 11.72 ns 4.1747214921e-02, // time = 11.73 ns 4.1721971918e-02, // time = 11.74 ns 4.1696637600e-02, // time = 11.75 ns 4.1671212423e-02, // time = 11.76 ns 4.1645696840e-02, // time = 11.77 ns 4.1620091304e-02, // time = 11.78 ns 4.1594396268e-02, // time = 11.79 ns 4.1568612181e-02, // time = 11.80 ns 4.1542739495e-02, // time = 11.81 ns 4.1516778657e-02, // time = 11.82 ns 4.1490730116e-02, // time = 11.83 ns 4.1464594319e-02, // time = 11.84 ns 4.1438371711e-02, // time = 11.85 ns 4.1412062738e-02, // time = 11.86 ns 4.1385667844e-02, // time = 11.87 ns 4.1359187471e-02, // time = 11.88 ns 4.1332622061e-02, // time = 11.89 ns 4.1305972056e-02, // time = 11.90 ns 4.1279237896e-02, // time = 11.91 ns 4.1252420019e-02, // time = 11.92 ns 4.1225518863e-02, // time = 11.93 ns 4.1198534866e-02, // time = 11.94 ns 4.1171468463e-02, // time = 11.95 ns 4.1144320090e-02, // time = 11.96 ns 4.1117090179e-02, // time = 11.97 ns 4.1089779165e-02, // time = 11.98 ns 4.1062387479e-02, // time = 11.99 ns 4.1034915552e-02, // time = 12.00 ns 4.1007363814e-02, // time = 12.01 ns 4.0979732694e-02, // time = 12.02 ns 4.0952022619e-02, // time = 12.03 ns 4.0924234018e-02, // time = 12.04 ns 4.0896367315e-02, // time = 12.05 ns 4.0868422935e-02, // time = 12.06 ns 4.0840401303e-02, // time = 12.07 ns 4.0812302841e-02, // time = 12.08 ns 4.0784127970e-02, // time = 12.09 ns 4.0755877113e-02, // time = 12.10 ns 4.0727550688e-02, // time = 12.11 ns 4.0699149114e-02, // time = 12.12 ns 4.0670672810e-02, // time = 12.13 ns 4.0642122192e-02, // time = 12.14 ns 4.0613497675e-02, // time = 12.15 ns 4.0584799674e-02, // time = 12.16 ns 4.0556028603e-02, // time = 12.17 ns 4.0527184875e-02, // time = 12.18 ns 4.0498268902e-02, // time = 12.19 ns 4.0469281093e-02, // time = 12.20 ns 4.0440221859e-02, // time = 12.21 ns 4.0411091608e-02, // time = 12.22 ns 4.0381890748e-02, // time = 12.23 ns 4.0352619685e-02, // time = 12.24 ns 4.0323278825e-02, // time = 12.25 ns 4.0293868572e-02, // time = 12.26 ns 4.0264389331e-02, // time = 12.27 ns 4.0234841502e-02, // time = 12.28 ns 4.0205225489e-02, // time = 12.29 ns 4.0175541690e-02, // time = 12.30 ns 4.0145790507e-02, // time = 12.31 ns 4.0115972336e-02, // time = 12.32 ns 4.0086087576e-02, // time = 12.33 ns 4.0056136622e-02, // time = 12.34 ns 4.0026119871e-02, // time = 12.35 ns 3.9996037716e-02, // time = 12.36 ns 3.9965890550e-02, // time = 12.37 ns 3.9935678767e-02, // time = 12.38 ns 3.9905402756e-02, // time = 12.39 ns 3.9875062909e-02, // time = 12.40 ns 3.9844659615e-02, // time = 12.41 ns 3.9814193261e-02, // time = 12.42 ns 3.9783664235e-02, // time = 12.43 ns 3.9753072924e-02, // time = 12.44 ns 3.9722419711e-02, // time = 12.45 ns 3.9691704982e-02, // time = 12.46 ns 3.9660929118e-02, // time = 12.47 ns 3.9630092504e-02, // time = 12.48 ns 3.9599195518e-02, // time = 12.49 ns 3.9568238542e-02, // time = 12.50 ns 3.9537221954e-02, // time = 12.51 ns 3.9506146133e-02, // time = 12.52 ns 3.9475011455e-02, // time = 12.53 ns 3.9443818296e-02, // time = 12.54 ns 3.9412567031e-02, // time = 12.55 ns 3.9381258034e-02, // time = 12.56 ns 3.9349891678e-02, // time = 12.57 ns 3.9318468335e-02, // time = 12.58 ns 3.9286988375e-02, // time = 12.59 ns 3.9255452169e-02, // time = 12.60 ns 3.9223860085e-02, // time = 12.61 ns 3.9192212491e-02, // time = 12.62 ns 3.9160509754e-02, // time = 12.63 ns 3.9128752239e-02, // time = 12.64 ns 3.9096940311e-02, // time = 12.65 ns 3.9065074334e-02, // time = 12.66 ns 3.9033154671e-02, // time = 12.67 ns 3.9001181684e-02, // time = 12.68 ns 3.8969155732e-02, // time = 12.69 ns 3.8937077176e-02, // time = 12.70 ns 3.8904946374e-02, // time = 12.71 ns 3.8872763685e-02, // time = 12.72 ns 3.8840529464e-02, // time = 12.73 ns 3.8808244067e-02, // time = 12.74 ns 3.8775907849e-02, // time = 12.75 ns 3.8743521164e-02, // time = 12.76 ns 3.8711084363e-02, // time = 12.77 ns 3.8678597799e-02, // time = 12.78 ns 3.8646061823e-02, // time = 12.79 ns 3.8613476783e-02, // time = 12.80 ns 3.8580843028e-02, // time = 12.81 ns 3.8548160906e-02, // time = 12.82 ns 3.8515430764e-02, // time = 12.83 ns 3.8482652946e-02, // time = 12.84 ns 3.8449827798e-02, // time = 12.85 ns 3.8416955663e-02, // time = 12.86 ns 3.8384036883e-02, // time = 12.87 ns 3.8351071800e-02, // time = 12.88 ns 3.8318060755e-02, // time = 12.89 ns 3.8285004087e-02, // time = 12.90 ns 3.8251902134e-02, // time = 12.91 ns 3.8218755234e-02, // time = 12.92 ns 3.8185563724e-02, // time = 12.93 ns 3.8152327939e-02, // time = 12.94 ns 3.8119048214e-02, // time = 12.95 ns 3.8085724881e-02, // time = 12.96 ns 3.8052358274e-02, // time = 12.97 ns 3.8018948725e-02, // time = 12.98 ns 3.7985496563e-02, // time = 12.99 ns 3.7952002118e-02, // time = 13.00 ns 3.7918465719e-02, // time = 13.01 ns 3.7884887693e-02, // time = 13.02 ns 3.7851268367e-02, // time = 13.03 ns 3.7817608066e-02, // time = 13.04 ns 3.7783907116e-02, // time = 13.05 ns 3.7750165838e-02, // time = 13.06 ns 3.7716384557e-02, // time = 13.07 ns 3.7682563594e-02, // time = 13.08 ns 3.7648703269e-02, // time = 13.09 ns 3.7614803902e-02, // time = 13.10 ns 3.7580865812e-02, // time = 13.11 ns 3.7546889316e-02, // time = 13.12 ns 3.7512874731e-02, // time = 13.13 ns 3.7478822373e-02, // time = 13.14 ns 3.7444732556e-02, // time = 13.15 ns 3.7410605595e-02, // time = 13.16 ns 3.7376441801e-02, // time = 13.17 ns 3.7342241487e-02, // time = 13.18 ns 3.7308004963e-02, // time = 13.19 ns 3.7273732540e-02, // time = 13.20 ns 3.7239424526e-02, // time = 13.21 ns 3.7205081229e-02, // time = 13.22 ns 3.7170702956e-02, // time = 13.23 ns 3.7136290012e-02, // time = 13.24 ns 3.7101842704e-02, // time = 13.25 ns 3.7067361334e-02, // time = 13.26 ns 3.7032846206e-02, // time = 13.27 ns 3.6998297622e-02, // time = 13.28 ns 3.6963715882e-02, // time = 13.29 ns 3.6929101288e-02, // time = 13.30 ns 3.6894454138e-02, // time = 13.31 ns 3.6859774731e-02, // time = 13.32 ns 3.6825063363e-02, // time = 13.33 ns 3.6790320330e-02, // time = 13.34 ns 3.6755545929e-02, // time = 13.35 ns 3.6720740454e-02, // time = 13.36 ns 3.6685904197e-02, // time = 13.37 ns 3.6651037451e-02, // time = 13.38 ns 3.6616140509e-02, // time = 13.39 ns 3.6581213659e-02, // time = 13.40 ns 3.6546257192e-02, // time = 13.41 ns 3.6511271397e-02, // time = 13.42 ns 3.6476256561e-02, // time = 13.43 ns 3.6441212970e-02, // time = 13.44 ns 3.6406140911e-02, // time = 13.45 ns 3.6371040669e-02, // time = 13.46 ns 3.6335912526e-02, // time = 13.47 ns 3.6300756767e-02, // time = 13.48 ns 3.6265573673e-02, // time = 13.49 ns 3.6230363524e-02, // time = 13.50 ns 3.6195126602e-02, // time = 13.51 ns 3.6159863185e-02, // time = 13.52 ns 3.6124573552e-02, // time = 13.53 ns 3.6089257979e-02, // time = 13.54 ns 3.6053916744e-02, // time = 13.55 ns 3.6018550121e-02, // time = 13.56 ns 3.5983158385e-02, // time = 13.57 ns 3.5947741810e-02, // time = 13.58 ns 3.5912300667e-02, // time = 13.59 ns 3.5876835230e-02, // time = 13.60 ns 3.5841345767e-02, // time = 13.61 ns 3.5805832551e-02, // time = 13.62 ns 3.5770295848e-02, // time = 13.63 ns 3.5734735927e-02, // time = 13.64 ns 3.5699153056e-02, // time = 13.65 ns 3.5663547500e-02, // time = 13.66 ns 3.5627919525e-02, // time = 13.67 ns 3.5592269394e-02, // time = 13.68 ns 3.5556597371e-02, // time = 13.69 ns 3.5520903719e-02, // time = 13.70 ns 3.5485188699e-02, // time = 13.71 ns 3.5449452572e-02, // time = 13.72 ns 3.5413695597e-02, // time = 13.73 ns 3.5377918034e-02, // time = 13.74 ns 3.5342120139e-02, // time = 13.75 ns 3.5306302171e-02, // time = 13.76 ns 3.5270464385e-02, // time = 13.77 ns 3.5234607036e-02, // time = 13.78 ns 3.5198730378e-02, // time = 13.79 ns 3.5162834666e-02, // time = 13.80 ns 3.5126920151e-02, // time = 13.81 ns 3.5090987085e-02, // time = 13.82 ns 3.5055035719e-02, // time = 13.83 ns 3.5019066302e-02, // time = 13.84 ns 3.4983079083e-02, // time = 13.85 ns 3.4947074311e-02, // time = 13.86 ns 3.4911052232e-02, // time = 13.87 ns 3.4875013092e-02, // time = 13.88 ns 3.4838957138e-02, // time = 13.89 ns 3.4802884612e-02, // time = 13.90 ns 3.4766795760e-02, // time = 13.91 ns 3.4730690823e-02, // time = 13.92 ns 3.4694570043e-02, // time = 13.93 ns 3.4658433662e-02, // time = 13.94 ns 3.4622281919e-02, // time = 13.95 ns 3.4586115053e-02, // time = 13.96 ns 3.4549933302e-02, // time = 13.97 ns 3.4513736905e-02, // time = 13.98 ns 3.4477526097e-02, // time = 13.99 ns 3.4441301115e-02, // time = 14.00 ns 3.4405062192e-02, // time = 14.01 ns 3.4368809563e-02, // time = 14.02 ns 3.4332543462e-02, // time = 14.03 ns 3.4296264119e-02, // time = 14.04 ns 3.4259971766e-02, // time = 14.05 ns 3.4223666635e-02, // time = 14.06 ns 3.4187348954e-02, // time = 14.07 ns 3.4151018952e-02, // time = 14.08 ns 3.4114676857e-02, // time = 14.09 ns 3.4078322897e-02, // time = 14.10 ns 3.4041957297e-02, // time = 14.11 ns 3.4005580282e-02, // time = 14.12 ns 3.3969192077e-02, // time = 14.13 ns 3.3932792906e-02, // time = 14.14 ns 3.3896382992e-02, // time = 14.15 ns 3.3859962556e-02, // time = 14.16 ns 3.3823531819e-02, // time = 14.17 ns 3.3787091003e-02, // time = 14.18 ns 3.3750640325e-02, // time = 14.19 ns 3.3714180005e-02, // time = 14.20 ns 3.3677710261e-02, // time = 14.21 ns 3.3641231309e-02, // time = 14.22 ns 3.3604743366e-02, // time = 14.23 ns 3.3568246646e-02, // time = 14.24 ns 3.3531741364e-02, // time = 14.25 ns 3.3495227734e-02, // time = 14.26 ns 3.3458705968e-02, // time = 14.27 ns 3.3422176279e-02, // time = 14.28 ns 3.3385638877e-02, // time = 14.29 ns 3.3349093973e-02, // time = 14.30 ns 3.3312541776e-02, // time = 14.31 ns 3.3275982494e-02, // time = 14.32 ns 3.3239416337e-02, // time = 14.33 ns 3.3202843510e-02, // time = 14.34 ns 3.3166264219e-02, // time = 14.35 ns 3.3129678671e-02, // time = 14.36 ns 3.3093087070e-02, // time = 14.37 ns 3.3056489620e-02, // time = 14.38 ns 3.3019886522e-02, // time = 14.39 ns 3.2983277981e-02, // time = 14.40 ns 3.2946664197e-02, // time = 14.41 ns 3.2910045370e-02, // time = 14.42 ns 3.2873421700e-02, // time = 14.43 ns 3.2836793387e-02, // time = 14.44 ns 3.2800160628e-02, // time = 14.45 ns 3.2763523621e-02, // time = 14.46 ns 3.2726882563e-02, // time = 14.47 ns 3.2690237648e-02, // time = 14.48 ns 3.2653589073e-02, // time = 14.49 ns 3.2616937031e-02, // time = 14.50 ns 3.2580281716e-02, // time = 14.51 ns 3.2543623320e-02, // time = 14.52 ns 3.2506962036e-02, // time = 14.53 ns 3.2470298054e-02, // time = 14.54 ns 3.2433631564e-02, // time = 14.55 ns 3.2396962757e-02, // time = 14.56 ns 3.2360291820e-02, // time = 14.57 ns 3.2323618943e-02, // time = 14.58 ns 3.2286944311e-02, // time = 14.59 ns 3.2250268112e-02, // time = 14.60 ns 3.2213590531e-02, // time = 14.61 ns 3.2176911753e-02, // time = 14.62 ns 3.2140231962e-02, // time = 14.63 ns 3.2103551342e-02, // time = 14.64 ns 3.2066870075e-02, // time = 14.65 ns 3.2030188342e-02, // time = 14.66 ns 3.1993506326e-02, // time = 14.67 ns 3.1956824206e-02, // time = 14.68 ns 3.1920142162e-02, // time = 14.69 ns 3.1883460373e-02, // time = 14.70 ns 3.1846779017e-02, // time = 14.71 ns 3.1810098270e-02, // time = 14.72 ns 3.1773418311e-02, // time = 14.73 ns 3.1736739314e-02, // time = 14.74 ns 3.1700061454e-02, // time = 14.75 ns 3.1663384907e-02, // time = 14.76 ns 3.1626709845e-02, // time = 14.77 ns 3.1590036441e-02, // time = 14.78 ns 3.1553364868e-02, // time = 14.79 ns 3.1516695297e-02, // time = 14.80 ns 3.1480027899e-02, // time = 14.81 ns 3.1443362843e-02, // time = 14.82 ns 3.1406700299e-02, // time = 14.83 ns 3.1370040435e-02, // time = 14.84 ns 3.1333383418e-02, // time = 14.85 ns 3.1296729417e-02, // time = 14.86 ns 3.1260078597e-02, // time = 14.87 ns 3.1223431124e-02, // time = 14.88 ns 3.1186787162e-02, // time = 14.89 ns 3.1150146876e-02, // time = 14.90 ns 3.1113510429e-02, // time = 14.91 ns 3.1076877984e-02, // time = 14.92 ns 3.1040249703e-02, // time = 14.93 ns 3.1003625747e-02, // time = 14.94 ns 3.0967006277e-02, // time = 14.95 ns 3.0930391453e-02, // time = 14.96 ns 3.0893781433e-02, // time = 14.97 ns 3.0857176376e-02, // time = 14.98 ns 3.0820576440e-02, // time = 14.99 ns 3.0783981783e-02, // time = 15.00 ns 3.0747392559e-02, // time = 15.01 ns 3.0710808926e-02, // time = 15.02 ns 3.0674231037e-02, // time = 15.03 ns 3.0637659048e-02, // time = 15.04 ns 3.0601093112e-02, // time = 15.05 ns 3.0564533381e-02, // time = 15.06 ns 3.0527980008e-02, // time = 15.07 ns 3.0491433145e-02, // time = 15.08 ns 3.0454892941e-02, // time = 15.09 ns 3.0418359549e-02, // time = 15.10 ns 3.0381833116e-02, // time = 15.11 ns 3.0345313791e-02, // time = 15.12 ns 3.0308801723e-02, // time = 15.13 ns 3.0272297060e-02, // time = 15.14 ns 3.0235799947e-02, // time = 15.15 ns 3.0199310532e-02, // time = 15.16 ns 3.0162828958e-02, // time = 15.17 ns 3.0126355372e-02, // time = 15.18 ns 3.0089889918e-02, // time = 15.19 ns 3.0053432737e-02, // time = 15.20 ns 3.0016983975e-02, // time = 15.21 ns 2.9980543771e-02, // time = 15.22 ns 2.9944112269e-02, // time = 15.23 ns 2.9907689608e-02, // time = 15.24 ns 2.9871275929e-02, // time = 15.25 ns 2.9834871372e-02, // time = 15.26 ns 2.9798476074e-02, // time = 15.27 ns 2.9762090175e-02, // time = 15.28 ns 2.9725713811e-02, // time = 15.29 ns 2.9689347120e-02, // time = 15.30 ns 2.9652990237e-02, // time = 15.31 ns 2.9616643299e-02, // time = 15.32 ns 2.9580306441e-02, // time = 15.33 ns 2.9543979795e-02, // time = 15.34 ns 2.9507663497e-02, // time = 15.35 ns 2.9471357680e-02, // time = 15.36 ns 2.9435062474e-02, // time = 15.37 ns 2.9398778013e-02, // time = 15.38 ns 2.9362504428e-02, // time = 15.39 ns 2.9326241848e-02, // time = 15.40 ns 2.9289990404e-02, // time = 15.41 ns 2.9253750225e-02, // time = 15.42 ns 2.9217521439e-02, // time = 15.43 ns 2.9181304175e-02, // time = 15.44 ns 2.9145098560e-02, // time = 15.45 ns 2.9108904720e-02, // time = 15.46 ns 2.9072722782e-02, // time = 15.47 ns 2.9036552871e-02, // time = 15.48 ns 2.9000395112e-02, // time = 15.49 ns 2.8964249629e-02, // time = 15.50 ns 2.8928116546e-02, // time = 15.51 ns 2.8891995986e-02, // time = 15.52 ns 2.8855888071e-02, // time = 15.53 ns 2.8819792924e-02, // time = 15.54 ns 2.8783710665e-02, // time = 15.55 ns 2.8747641415e-02, // time = 15.56 ns 2.8711585294e-02, // time = 15.57 ns 2.8675542421e-02, // time = 15.58 ns 2.8639512916e-02, // time = 15.59 ns 2.8603496896e-02, // time = 15.60 ns 2.8567494479e-02, // time = 15.61 ns 2.8531505783e-02, // time = 15.62 ns 2.8495530923e-02, // time = 15.63 ns 2.8459570015e-02, // time = 15.64 ns 2.8423623175e-02, // time = 15.65 ns 2.8387690517e-02, // time = 15.66 ns 2.8351772156e-02, // time = 15.67 ns 2.8315868205e-02, // time = 15.68 ns 2.8279978776e-02, // time = 15.69 ns 2.8244103983e-02, // time = 15.70 ns 2.8208243937e-02, // time = 15.71 ns 2.8172398749e-02, // time = 15.72 ns 2.8136568529e-02, // time = 15.73 ns 2.8100753389e-02, // time = 15.74 ns 2.8064953436e-02, // time = 15.75 ns 2.8029168781e-02, // time = 15.76 ns 2.7993399532e-02, // time = 15.77 ns 2.7957645795e-02, // time = 15.78 ns 2.7921907680e-02, // time = 15.79 ns 2.7886185291e-02, // time = 15.80 ns 2.7850478736e-02, // time = 15.81 ns 2.7814788119e-02, // time = 15.82 ns 2.7779113546e-02, // time = 15.83 ns 2.7743455121e-02, // time = 15.84 ns 2.7707812948e-02, // time = 15.85 ns 2.7672187131e-02, // time = 15.86 ns 2.7636577771e-02, // time = 15.87 ns 2.7600984972e-02, // time = 15.88 ns 2.7565408834e-02, // time = 15.89 ns 2.7529849459e-02, // time = 15.90 ns 2.7494306948e-02, // time = 15.91 ns 2.7458781401e-02, // time = 15.92 ns 2.7423272916e-02, // time = 15.93 ns 2.7387781594e-02, // time = 15.94 ns 2.7352307532e-02, // time = 15.95 ns 2.7316850828e-02, // time = 15.96 ns 2.7281411579e-02, // time = 15.97 ns 2.7245989883e-02, // time = 15.98 ns 2.7210585836e-02, // time = 15.99 ns 2.7175199533e-02, // time = 16.00 ns 2.7139831069e-02, // time = 16.01 ns 2.7104480540e-02, // time = 16.02 ns 2.7069148038e-02, // time = 16.03 ns 2.7033833659e-02, // time = 16.04 ns 2.6998537495e-02, // time = 16.05 ns 2.6963259639e-02, // time = 16.06 ns 2.6928000183e-02, // time = 16.07 ns 2.6892759217e-02, // time = 16.08 ns 2.6857536834e-02, // time = 16.09 ns 2.6822333124e-02, // time = 16.10 ns 2.6787148177e-02, // time = 16.11 ns 2.6751982082e-02, // time = 16.12 ns 2.6716834929e-02, // time = 16.13 ns 2.6681706805e-02, // time = 16.14 ns 2.6646597800e-02, // time = 16.15 ns 2.6611507999e-02, // time = 16.16 ns 2.6576437491e-02, // time = 16.17 ns 2.6541386361e-02, // time = 16.18 ns 2.6506354697e-02, // time = 16.19 ns 2.6471342582e-02, // time = 16.20 ns 2.6436350103e-02, // time = 16.21 ns 2.6401377343e-02, // time = 16.22 ns 2.6366424387e-02, // time = 16.23 ns 2.6331491317e-02, // time = 16.24 ns 2.6296578219e-02, // time = 16.25 ns 2.6261685172e-02, // time = 16.26 ns 2.6226812261e-02, // time = 16.27 ns 2.6191959565e-02, // time = 16.28 ns 2.6157127167e-02, // time = 16.29 ns 2.6122315147e-02, // time = 16.30 ns 2.6087523585e-02, // time = 16.31 ns 2.6052752560e-02, // time = 16.32 ns 2.6018002152e-02, // time = 16.33 ns 2.5983272440e-02, // time = 16.34 ns 2.5948563501e-02, // time = 16.35 ns 2.5913875413e-02, // time = 16.36 ns 2.5879208254e-02, // time = 16.37 ns 2.5844562101e-02, // time = 16.38 ns 2.5809937029e-02, // time = 16.39 ns 2.5775333114e-02, // time = 16.40 ns 2.5740750433e-02, // time = 16.41 ns 2.5706189059e-02, // time = 16.42 ns 2.5671649067e-02, // time = 16.43 ns 2.5637130532e-02, // time = 16.44 ns 2.5602633527e-02, // time = 16.45 ns 2.5568158124e-02, // time = 16.46 ns 2.5533704397e-02, // time = 16.47 ns 2.5499272418e-02, // time = 16.48 ns 2.5464862258e-02, // time = 16.49 ns 2.5430473988e-02, // time = 16.50 ns 2.5396107680e-02, // time = 16.51 ns 2.5361763404e-02, // time = 16.52 ns 2.5327441230e-02, // time = 16.53 ns 2.5293141227e-02, // time = 16.54 ns 2.5258863464e-02, // time = 16.55 ns 2.5224608010e-02, // time = 16.56 ns 2.5190374933e-02, // time = 16.57 ns 2.5156164300e-02, // time = 16.58 ns 2.5121976180e-02, // time = 16.59 ns 2.5087810638e-02, // time = 16.60 ns 2.5053667742e-02, // time = 16.61 ns 2.5019547556e-02, // time = 16.62 ns 2.4985450147e-02, // time = 16.63 ns 2.4951375580e-02, // time = 16.64 ns 2.4917323920e-02, // time = 16.65 ns 2.4883295230e-02, // time = 16.66 ns 2.4849289575e-02, // time = 16.67 ns 2.4815307017e-02, // time = 16.68 ns 2.4781347621e-02, // time = 16.69 ns 2.4747411447e-02, // time = 16.70 ns 2.4713498560e-02, // time = 16.71 ns 2.4679609019e-02, // time = 16.72 ns 2.4645742887e-02, // time = 16.73 ns 2.4611900225e-02, // time = 16.74 ns 2.4578081092e-02, // time = 16.75 ns 2.4544285550e-02, // time = 16.76 ns 2.4510513657e-02, // time = 16.77 ns 2.4476765472e-02, // time = 16.78 ns 2.4443041055e-02, // time = 16.79 ns 2.4409340465e-02, // time = 16.80 ns 2.4375663758e-02, // time = 16.81 ns 2.4342010993e-02, // time = 16.82 ns 2.4308382226e-02, // time = 16.83 ns 2.4274777516e-02, // time = 16.84 ns 2.4241196917e-02, // time = 16.85 ns 2.4207640486e-02, // time = 16.86 ns 2.4174108279e-02, // time = 16.87 ns 2.4140600351e-02, // time = 16.88 ns 2.4107116756e-02, // time = 16.89 ns 2.4073657549e-02, // time = 16.90 ns 2.4040222784e-02, // time = 16.91 ns 2.4006812515e-02, // time = 16.92 ns 2.3973426795e-02, // time = 16.93 ns 2.3940065676e-02, // time = 16.94 ns 2.3906729212e-02, // time = 16.95 ns 2.3873417454e-02, // time = 16.96 ns 2.3840130454e-02, // time = 16.97 ns 2.3806868263e-02, // time = 16.98 ns 2.3773630933e-02, // time = 16.99 ns 2.3740418513e-02, // time = 17.00 ns 2.3707231054e-02, // time = 17.01 ns 2.3674068607e-02, // time = 17.02 ns 2.3640931219e-02, // time = 17.03 ns 2.3607818940e-02, // time = 17.04 ns 2.3574731820e-02, // time = 17.05 ns 2.3541669906e-02, // time = 17.06 ns 2.3508633246e-02, // time = 17.07 ns 2.3475621887e-02, // time = 17.08 ns 2.3442635878e-02, // time = 17.09 ns 2.3409675265e-02, // time = 17.10 ns 2.3376740093e-02, // time = 17.11 ns 2.3343830411e-02, // time = 17.12 ns 2.3310946262e-02, // time = 17.13 ns 2.3278087693e-02, // time = 17.14 ns 2.3245254748e-02, // time = 17.15 ns 2.3212447473e-02, // time = 17.16 ns 2.3179665911e-02, // time = 17.17 ns 2.3146910106e-02, // time = 17.18 ns 2.3114180103e-02, // time = 17.19 ns 2.3081475944e-02, // time = 17.20 ns 2.3048797672e-02, // time = 17.21 ns 2.3016145330e-02, // time = 17.22 ns 2.2983518960e-02, // time = 17.23 ns 2.2950918604e-02, // time = 17.24 ns 2.2918344303e-02, // time = 17.25 ns 2.2885796099e-02, // time = 17.26 ns 2.2853274032e-02, // time = 17.27 ns 2.2820778143e-02, // time = 17.28 ns 2.2788308472e-02, // time = 17.29 ns 2.2755865059e-02, // time = 17.30 ns 2.2723447942e-02, // time = 17.31 ns 2.2691057162e-02, // time = 17.32 ns 2.2658692758e-02, // time = 17.33 ns 2.2626354766e-02, // time = 17.34 ns 2.2594043227e-02, // time = 17.35 ns 2.2561758177e-02, // time = 17.36 ns 2.2529499654e-02, // time = 17.37 ns 2.2497267694e-02, // time = 17.38 ns 2.2465062336e-02, // time = 17.39 ns 2.2432883615e-02, // time = 17.40 ns 2.2400731568e-02, // time = 17.41 ns 2.2368606229e-02, // time = 17.42 ns 2.2336507636e-02, // time = 17.43 ns 2.2304435822e-02, // time = 17.44 ns 2.2272390824e-02, // time = 17.45 ns 2.2240372674e-02, // time = 17.46 ns 2.2208381409e-02, // time = 17.47 ns 2.2176417060e-02, // time = 17.48 ns 2.2144479663e-02, // time = 17.49 ns 2.2112569250e-02, // time = 17.50 ns 2.2080685854e-02, // time = 17.51 ns 2.2048829508e-02, // time = 17.52 ns 2.2017000244e-02, // time = 17.53 ns 2.1985198095e-02, // time = 17.54 ns 2.1953423092e-02, // time = 17.55 ns 2.1921675266e-02, // time = 17.56 ns 2.1889954648e-02, // time = 17.57 ns 2.1858261270e-02, // time = 17.58 ns 2.1826595161e-02, // time = 17.59 ns 2.1794956353e-02, // time = 17.60 ns 2.1763344874e-02, // time = 17.61 ns 2.1731760755e-02, // time = 17.62 ns 2.1700204024e-02, // time = 17.63 ns 2.1668674712e-02, // time = 17.64 ns 2.1637172845e-02, // time = 17.65 ns 2.1605698454e-02, // time = 17.66 ns 2.1574251565e-02, // time = 17.67 ns 2.1542832207e-02, // time = 17.68 ns 2.1511440407e-02, // time = 17.69 ns 2.1480076193e-02, // time = 17.70 ns 2.1448739591e-02, // time = 17.71 ns 2.1417430629e-02, // time = 17.72 ns 2.1386149332e-02, // time = 17.73 ns 2.1354895726e-02, // time = 17.74 ns 2.1323669837e-02, // time = 17.75 ns 2.1292471692e-02, // time = 17.76 ns 2.1261301314e-02, // time = 17.77 ns 2.1230158730e-02, // time = 17.78 ns 2.1199043963e-02, // time = 17.79 ns 2.1167957038e-02, // time = 17.80 ns 2.1136897980e-02, // time = 17.81 ns 2.1105866811e-02, // time = 17.82 ns 2.1074863556e-02, // time = 17.83 ns 2.1043888238e-02, // time = 17.84 ns 2.1012940879e-02, // time = 17.85 ns 2.0982021504e-02, // time = 17.86 ns 2.0951130133e-02, // time = 17.87 ns 2.0920266789e-02, // time = 17.88 ns 2.0889431495e-02, // time = 17.89 ns 2.0858624271e-02, // time = 17.90 ns 2.0827845140e-02, // time = 17.91 ns 2.0797094122e-02, // time = 17.92 ns 2.0766371238e-02, // time = 17.93 ns 2.0735676509e-02, // time = 17.94 ns 2.0705009956e-02, // time = 17.95 ns 2.0674371597e-02, // time = 17.96 ns 2.0643761453e-02, // time = 17.97 ns 2.0613179544e-02, // time = 17.98 ns 2.0582625889e-02, // time = 17.99 ns 2.0552100507e-02, // time = 18.00 ns 2.0521603416e-02, // time = 18.01 ns 2.0491134636e-02, // time = 18.02 ns 2.0460694184e-02, // time = 18.03 ns 2.0430282079e-02, // time = 18.04 ns 2.0399898337e-02, // time = 18.05 ns 2.0369542978e-02, // time = 18.06 ns 2.0339216018e-02, // time = 18.07 ns 2.0308917474e-02, // time = 18.08 ns 2.0278647362e-02, // time = 18.09 ns 2.0248405701e-02, // time = 18.10 ns 2.0218192504e-02, // time = 18.11 ns 2.0188007790e-02, // time = 18.12 ns 2.0157851573e-02, // time = 18.13 ns 2.0127723869e-02, // time = 18.14 ns 2.0097624693e-02, // time = 18.15 ns 2.0067554061e-02, // time = 18.16 ns 2.0037511987e-02, // time = 18.17 ns 2.0007498486e-02, // time = 18.18 ns 1.9977513572e-02, // time = 18.19 ns 1.9947557260e-02, // time = 18.20 ns 1.9917629563e-02, // time = 18.21 ns 1.9887730494e-02, // time = 18.22 ns 1.9857860068e-02, // time = 18.23 ns 1.9828018298e-02, // time = 18.24 ns 1.9798205196e-02, // time = 18.25 ns 1.9768420775e-02, // time = 18.26 ns 1.9738665047e-02, // time = 18.27 ns 1.9708938026e-02, // time = 18.28 ns 1.9679239723e-02, // time = 18.29 ns 1.9649570149e-02, // time = 18.30 ns 1.9619929317e-02, // time = 18.31 ns 1.9590317237e-02, // time = 18.32 ns 1.9560733922e-02, // time = 18.33 ns 1.9531179381e-02, // time = 18.34 ns 1.9501653626e-02, // time = 18.35 ns 1.9472156666e-02, // time = 18.36 ns 1.9442688514e-02, // time = 18.37 ns 1.9413249177e-02, // time = 18.38 ns 1.9383838666e-02, // time = 18.39 ns 1.9354456992e-02, // time = 18.40 ns 1.9325104162e-02, // time = 18.41 ns 1.9295780187e-02, // time = 18.42 ns 1.9266485075e-02, // time = 18.43 ns 1.9237218835e-02, // time = 18.44 ns 1.9207981475e-02, // time = 18.45 ns 1.9178773005e-02, // time = 18.46 ns 1.9149593432e-02, // time = 18.47 ns 1.9120442763e-02, // time = 18.48 ns 1.9091321007e-02, // time = 18.49 ns 1.9062228172e-02, // time = 18.50 ns 1.9033164264e-02, // time = 18.51 ns 1.9004129290e-02, // time = 18.52 ns 1.8975123258e-02, // time = 18.53 ns 1.8946146174e-02, // time = 18.54 ns 1.8917198045e-02, // time = 18.55 ns 1.8888278877e-02, // time = 18.56 ns 1.8859388676e-02, // time = 18.57 ns 1.8830527447e-02, // time = 18.58 ns 1.8801695197e-02, // time = 18.59 ns 1.8772891932e-02, // time = 18.60 ns 1.8744117655e-02, // time = 18.61 ns 1.8715372373e-02, // time = 18.62 ns 1.8686656090e-02, // time = 18.63 ns 1.8657968812e-02, // time = 18.64 ns 1.8629310542e-02, // time = 18.65 ns 1.8600681285e-02, // time = 18.66 ns 1.8572081045e-02, // time = 18.67 ns 1.8543509826e-02, // time = 18.68 ns 1.8514967631e-02, // time = 18.69 ns 1.8486454465e-02, // time = 18.70 ns 1.8457970331e-02, // time = 18.71 ns 1.8429515231e-02, // time = 18.72 ns 1.8401089169e-02, // time = 18.73 ns 1.8372692148e-02, // time = 18.74 ns 1.8344324170e-02, // time = 18.75 ns 1.8315985238e-02, // time = 18.76 ns 1.8287675354e-02, // time = 18.77 ns 1.8259394521e-02, // time = 18.78 ns 1.8231142739e-02, // time = 18.79 ns 1.8202920011e-02, // time = 18.80 ns 1.8174726338e-02, // time = 18.81 ns 1.8146561722e-02, // time = 18.82 ns 1.8118426164e-02, // time = 18.83 ns 1.8090319665e-02, // time = 18.84 ns 1.8062242226e-02, // time = 18.85 ns 1.8034193847e-02, // time = 18.86 ns 1.8006174529e-02, // time = 18.87 ns 1.7978184272e-02, // time = 18.88 ns 1.7950223077e-02, // time = 18.89 ns 1.7922290943e-02, // time = 18.90 ns 1.7894387870e-02, // time = 18.91 ns 1.7866513858e-02, // time = 18.92 ns 1.7838668907e-02, // time = 18.93 ns 1.7810853015e-02, // time = 18.94 ns 1.7783066182e-02, // time = 18.95 ns 1.7755308406e-02, // time = 18.96 ns 1.7727579687e-02, // time = 18.97 ns 1.7699880024e-02, // time = 18.98 ns 1.7672209414e-02, // time = 18.99 ns 1.7644567856e-02, // time = 19.00 ns 1.7616955348e-02, // time = 19.01 ns 1.7589371888e-02, // time = 19.02 ns 1.7561817474e-02, // time = 19.03 ns 1.7534292104e-02, // time = 19.04 ns 1.7506795775e-02, // time = 19.05 ns 1.7479328485e-02, // time = 19.06 ns 1.7451890230e-02, // time = 19.07 ns 1.7424481009e-02, // time = 19.08 ns 1.7397100816e-02, // time = 19.09 ns 1.7369749651e-02, // time = 19.10 ns 1.7342427508e-02, // time = 19.11 ns 1.7315134385e-02, // time = 19.12 ns 1.7287870277e-02, // time = 19.13 ns 1.7260635181e-02, // time = 19.14 ns 1.7233429093e-02, // time = 19.15 ns 1.7206252009e-02, // time = 19.16 ns 1.7179103924e-02, // time = 19.17 ns 1.7151984833e-02, // time = 19.18 ns 1.7124894733e-02, // time = 19.19 ns 1.7097833619e-02, // time = 19.20 ns 1.7070801485e-02, // time = 19.21 ns 1.7043798326e-02, // time = 19.22 ns 1.7016824138e-02, // time = 19.23 ns 1.6989878914e-02, // time = 19.24 ns 1.6962962650e-02, // time = 19.25 ns 1.6936075340e-02, // time = 19.26 ns 1.6909216978e-02, // time = 19.27 ns 1.6882387558e-02, // time = 19.28 ns 1.6855587073e-02, // time = 19.29 ns 1.6828815519e-02, // time = 19.30 ns 1.6802072889e-02, // time = 19.31 ns 1.6775359175e-02, // time = 19.32 ns 1.6748674372e-02, // time = 19.33 ns 1.6722018473e-02, // time = 19.34 ns 1.6695391470e-02, // time = 19.35 ns 1.6668793357e-02, // time = 19.36 ns 1.6642224127e-02, // time = 19.37 ns 1.6615683772e-02, // time = 19.38 ns 1.6589172286e-02, // time = 19.39 ns 1.6562689660e-02, // time = 19.40 ns 1.6536235886e-02, // time = 19.41 ns 1.6509810957e-02, // time = 19.42 ns 1.6483414866e-02, // time = 19.43 ns 1.6457047603e-02, // time = 19.44 ns 1.6430709162e-02, // time = 19.45 ns 1.6404399532e-02, // time = 19.46 ns 1.6378118707e-02, // time = 19.47 ns 1.6351866677e-02, // time = 19.48 ns 1.6325643434e-02, // time = 19.49 ns 1.6299448968e-02, // time = 19.50 ns 1.6273283272e-02, // time = 19.51 ns 1.6247146335e-02, // time = 19.52 ns 1.6221038149e-02, // time = 19.53 ns 1.6194958704e-02, // time = 19.54 ns 1.6168907992e-02, // time = 19.55 ns 1.6142886001e-02, // time = 19.56 ns 1.6116892723e-02, // time = 19.57 ns 1.6090928148e-02, // time = 19.58 ns 1.6064992266e-02, // time = 19.59 ns 1.6039085067e-02, // time = 19.60 ns 1.6013206540e-02, // time = 19.61 ns 1.5987356676e-02, // time = 19.62 ns 1.5961535464e-02, // time = 19.63 ns 1.5935742893e-02, // time = 19.64 ns 1.5909978953e-02, // time = 19.65 ns 1.5884243634e-02, // time = 19.66 ns 1.5858536923e-02, // time = 19.67 ns 1.5832858811e-02, // time = 19.68 ns 1.5807209286e-02, // time = 19.69 ns 1.5781588337e-02, // time = 19.70 ns 1.5755995952e-02, // time = 19.71 ns 1.5730432121e-02, // time = 19.72 ns 1.5704896831e-02, // time = 19.73 ns 1.5679390071e-02, // time = 19.74 ns 1.5653911830e-02, // time = 19.75 ns 1.5628462095e-02, // time = 19.76 ns 1.5603040854e-02, // time = 19.77 ns 1.5577648095e-02, // time = 19.78 ns 1.5552283807e-02, // time = 19.79 ns 1.5526947976e-02, // time = 19.80 ns 1.5501640591e-02, // time = 19.81 ns 1.5476361638e-02, // time = 19.82 ns 1.5451111106e-02, // time = 19.83 ns 1.5425888981e-02, // time = 19.84 ns 1.5400695251e-02, // time = 19.85 ns 1.5375529902e-02, // time = 19.86 ns 1.5350392921e-02, // time = 19.87 ns 1.5325284297e-02, // time = 19.88 ns 1.5300204014e-02, // time = 19.89 ns 1.5275152060e-02, // time = 19.90 ns 1.5250128421e-02, // time = 19.91 ns 1.5225133084e-02, // time = 19.92 ns 1.5200166035e-02, // time = 19.93 ns 1.5175227260e-02, // time = 19.94 ns 1.5150316746e-02, // time = 19.95 ns 1.5125434477e-02, // time = 19.96 ns 1.5100580441e-02, // time = 19.97 ns 1.5075754624e-02, // time = 19.98 ns 1.5050957010e-02, // time = 19.99 ns 1.5016287700e-02, // time = 20.00 ns 1.4998974872e-02, // time = 20.01 ns 1.4979204709e-02, // time = 20.02 ns 1.4954517054e-02, // time = 20.03 ns 1.4929857433e-02, // time = 20.04 ns 1.4905225904e-02, // time = 20.05 ns 1.4880622472e-02, // time = 20.06 ns 1.4856047130e-02, // time = 20.07 ns 1.4831499863e-02, // time = 20.08 ns 1.4806980657e-02, // time = 20.09 ns 1.4770254430e-02, // time = 20.10 ns 1.4745819134e-02, // time = 20.11 ns 1.4721402415e-02, // time = 20.12 ns 1.4697010588e-02, // time = 20.13 ns 1.4672645743e-02, // time = 20.14 ns 1.4648308556e-02, // time = 20.15 ns 1.4623999231e-02, // time = 20.16 ns 1.4599717822e-02, // time = 20.17 ns 1.4575464330e-02, // time = 20.18 ns 1.4551238743e-02, // time = 20.19 ns 1.4527041045e-02, // time = 20.20 ns 1.4502871218e-02, // time = 20.21 ns 1.4478729243e-02, // time = 20.22 ns 1.4454615103e-02, // time = 20.23 ns 1.4430528780e-02, // time = 20.24 ns 1.4406470255e-02, // time = 20.25 ns 1.4382439511e-02, // time = 20.26 ns 1.4358436530e-02, // time = 20.27 ns 1.4334461295e-02, // time = 20.28 ns 1.4310513787e-02, // time = 20.29 ns 1.4286593991e-02, // time = 20.30 ns 1.4262701887e-02, // time = 20.31 ns 1.4238837459e-02, // time = 20.32 ns 1.4215000689e-02, // time = 20.33 ns 1.4191191559e-02, // time = 20.34 ns 1.4167410053e-02, // time = 20.35 ns 1.4143656153e-02, // time = 20.36 ns 1.4119929840e-02, // time = 20.37 ns 1.4096231098e-02, // time = 20.38 ns 1.4072559908e-02, // time = 20.39 ns 1.4048916253e-02, // time = 20.40 ns 1.4025300115e-02, // time = 20.41 ns 1.4001711475e-02, // time = 20.42 ns 1.3978150317e-02, // time = 20.43 ns 1.3954616621e-02, // time = 20.44 ns 1.3931110369e-02, // time = 20.45 ns 1.3907631544e-02, // time = 20.46 ns 1.3884180126e-02, // time = 20.47 ns 1.3860756099e-02, // time = 20.48 ns 1.3837359442e-02, // time = 20.49 ns 1.3813990137e-02, // time = 20.50 ns 1.3790648167e-02, // time = 20.51 ns 1.3767333511e-02, // time = 20.52 ns 1.3744046152e-02, // time = 20.53 ns 1.3720786070e-02, // time = 20.54 ns 1.3697553246e-02, // time = 20.55 ns 1.3674347662e-02, // time = 20.56 ns 1.3651169298e-02, // time = 20.57 ns 1.3628018135e-02, // time = 20.58 ns 1.3604894154e-02, // time = 20.59 ns 1.3581797336e-02, // time = 20.60 ns 1.3558727660e-02, // time = 20.61 ns 1.3535685109e-02, // time = 20.62 ns 1.3512669661e-02, // time = 20.63 ns 1.3489681299e-02, // time = 20.64 ns 1.3466720001e-02, // time = 20.65 ns 1.3443785750e-02, // time = 20.66 ns 1.3420878524e-02, // time = 20.67 ns 1.3397998305e-02, // time = 20.68 ns 1.3375145073e-02, // time = 20.69 ns 1.3352318808e-02, // time = 20.70 ns 1.3329519490e-02, // time = 20.71 ns 1.3306747100e-02, // time = 20.72 ns 1.3284001618e-02, // time = 20.73 ns 1.3261283024e-02, // time = 20.74 ns 1.3238591299e-02, // time = 20.75 ns 1.3215926421e-02, // time = 20.76 ns 1.3193288372e-02, // time = 20.77 ns 1.3170677131e-02, // time = 20.78 ns 1.3148092678e-02, // time = 20.79 ns 1.3125534993e-02, // time = 20.80 ns 1.3103004056e-02, // time = 20.81 ns 1.3080499846e-02, // time = 20.82 ns 1.3058022344e-02, // time = 20.83 ns 1.3035571529e-02, // time = 20.84 ns 1.3013147382e-02, // time = 20.85 ns 1.2990749882e-02, // time = 20.86 ns 1.2968379009e-02, // time = 20.87 ns 1.2946034743e-02, // time = 20.88 ns 1.2923717064e-02, // time = 20.89 ns 1.2901425953e-02, // time = 20.90 ns 1.2879161388e-02, // time = 20.91 ns 1.2856923349e-02, // time = 20.92 ns 1.2834711817e-02, // time = 20.93 ns 1.2812526770e-02, // time = 20.94 ns 1.2790368188e-02, // time = 20.95 ns 1.2768236050e-02, // time = 20.96 ns 1.2746130336e-02, // time = 20.97 ns 1.2724051024e-02, // time = 20.98 ns 1.2701998096e-02, // time = 20.99 ns 1.2679971529e-02, // time = 21.00 ns 1.2657971305e-02, // time = 21.01 ns 1.2635997404e-02, // time = 21.02 ns 1.2614049807e-02, // time = 21.03 ns 1.2592128496e-02, // time = 21.04 ns 1.2570233453e-02, // time = 21.05 ns 1.2548364661e-02, // time = 21.06 ns 1.2526522104e-02, // time = 21.07 ns 1.2504705768e-02, // time = 21.08 ns 1.2482915639e-02, // time = 21.09 ns 1.2461151701e-02, // time = 21.10 ns 1.2439413942e-02, // time = 21.11 ns 1.2417702343e-02, // time = 21.12 ns 1.2396016886e-02, // time = 21.13 ns 1.2374357543e-02, // time = 21.14 ns 1.2352724280e-02, // time = 21.15 ns 1.2331117058e-02, // time = 21.16 ns 1.2309535830e-02, // time = 21.17 ns 1.2287980541e-02, // time = 21.18 ns 1.2266451146e-02, // time = 21.19 ns 1.2244947618e-02, // time = 21.20 ns 1.2223469918e-02, // time = 21.21 ns 1.2202018020e-02, // time = 21.22 ns 1.2180591904e-02, // time = 21.23 ns 1.2159191557e-02, // time = 21.24 ns 1.2137816971e-02, // time = 21.25 ns 1.2116468137e-02, // time = 21.26 ns 1.2095145048e-02, // time = 21.27 ns 1.2073847695e-02, // time = 21.28 ns 1.2052576067e-02, // time = 21.29 ns 1.2031330150e-02, // time = 21.30 ns 1.2010109929e-02, // time = 21.31 ns 1.1988915386e-02, // time = 21.32 ns 1.1967746502e-02, // time = 21.33 ns 1.1946603256e-02, // time = 21.34 ns 1.1925485626e-02, // time = 21.35 ns 1.1904393589e-02, // time = 21.36 ns 1.1883327122e-02, // time = 21.37 ns 1.1862286202e-02, // time = 21.38 ns 1.1841270803e-02, // time = 21.39 ns 1.1820280902e-02, // time = 21.40 ns 1.1799316474e-02, // time = 21.41 ns 1.1778377495e-02, // time = 21.42 ns 1.1757463941e-02, // time = 21.43 ns 1.1736575786e-02, // time = 21.44 ns 1.1715713008e-02, // time = 21.45 ns 1.1694875581e-02, // time = 21.46 ns 1.1674063481e-02, // time = 21.47 ns 1.1653276684e-02, // time = 21.48 ns 1.1632515166e-02, // time = 21.49 ns 1.1611778905e-02, // time = 21.50 ns 1.1591067878e-02, // time = 21.51 ns 1.1570382064e-02, // time = 21.52 ns 1.1549721444e-02, // time = 21.53 ns 1.1529086000e-02, // time = 21.54 ns 1.1508475712e-02, // time = 21.55 ns 1.1487890561e-02, // time = 21.56 ns 1.1467330520e-02, // time = 21.57 ns 1.1446795555e-02, // time = 21.58 ns 1.1426285625e-02, // time = 21.59 ns 1.1405800681e-02, // time = 21.60 ns 1.1385340671e-02, // time = 21.61 ns 1.1364905541e-02, // time = 21.62 ns 1.1344495242e-02, // time = 21.63 ns 1.1324109728e-02, // time = 21.64 ns 1.1303748943e-02, // time = 21.65 ns 1.1283412801e-02, // time = 21.66 ns 1.1263101145e-02, // time = 21.67 ns 1.1242813832e-02, // time = 21.68 ns 1.1222551015e-02, // time = 21.69 ns 1.1202313079e-02, // time = 21.70 ns 1.1182100220e-02, // time = 21.71 ns 1.1161912403e-02, // time = 21.72 ns 1.1141750008e-02, // time = 21.73 ns 1.1121612327e-02, // time = 21.74 ns 1.1101499066e-02, // time = 21.75 ns 1.1081410331e-02, // time = 21.76 ns 1.1067976241e-02, // time = 21.77 ns 1.1044908155e-02, // time = 21.78 ns 1.1028872778e-02, // time = 21.79 ns 1.1008810991e-02, // time = 21.80 ns 1.0984749703e-02, // time = 21.81 ns 1.0965697621e-02, // time = 21.82 ns 1.0949209463e-02, // time = 21.83 ns 1.0927025688e-02, // time = 21.84 ns 1.0903226244e-02, // time = 21.85 ns 1.0882034161e-02, // time = 21.86 ns 1.0871869227e-02, // time = 21.87 ns 1.0844507113e-02, // time = 21.88 ns 1.0824722074e-02, // time = 21.89 ns 1.0805547399e-02, // time = 21.90 ns 1.0786429128e-02, // time = 21.91 ns 1.0766725739e-02, // time = 21.92 ns 1.0747047650e-02, // time = 21.93 ns 1.0727393354e-02, // time = 21.94 ns 1.0707761991e-02, // time = 21.95 ns 1.0688153385e-02, // time = 21.96 ns 1.0668567902e-02, // time = 21.97 ns 1.0649006263e-02, // time = 21.98 ns 1.0629469347e-02, // time = 21.99 ns 1.0609957980e-02, // time = 22.00 ns 1.0590472756e-02, // time = 22.01 ns 1.0571013926e-02, // time = 22.02 ns 1.0551581378e-02, // time = 22.03 ns 1.0532174710e-02, // time = 22.04 ns 1.0512793349e-02, // time = 22.05 ns 1.0493436667e-02, // time = 22.06 ns 1.0474104084e-02, // time = 22.07 ns 1.0454795119e-02, // time = 22.08 ns 1.0435509415e-02, // time = 22.09 ns 1.0416246751e-02, // time = 22.10 ns 1.0397006972e-02, // time = 22.11 ns 1.0377790019e-02, // time = 22.12 ns 1.0358595898e-02, // time = 22.13 ns 1.0339424658e-02, // time = 22.14 ns 1.0320276370e-02, // time = 22.15 ns 1.0301151114e-02, // time = 22.16 ns 1.0282048967e-02, // time = 22.17 ns 1.0262970003e-02, // time = 22.18 ns 1.0243914284e-02, // time = 22.19 ns 1.0224881864e-02, // time = 22.20 ns 1.0205872785e-02, // time = 22.21 ns 1.0186887079e-02, // time = 22.22 ns 1.0167924769e-02, // time = 22.23 ns 1.0148985871e-02, // time = 22.24 ns 1.0130070392e-02, // time = 22.25 ns 1.0111178334e-02, // time = 22.26 ns 1.0092309695e-02, // time = 22.27 ns 1.0073464467e-02, // time = 22.28 ns 1.0054642639e-02, // time = 22.29 ns 1.0035844199e-02, // time = 22.30 ns 1.0017069130e-02, // time = 22.31 ns 9.9983174167e-03, // time = 22.32 ns 9.9795890394e-03, // time = 22.33 ns 9.9608839784e-03, // time = 22.34 ns 9.9422022121e-03, // time = 22.35 ns 9.9235437171e-03, // time = 22.36 ns 9.9049084681e-03, // time = 22.37 ns 9.8862964367e-03, // time = 22.38 ns 9.8677075920e-03, // time = 22.39 ns 9.8491418994e-03, // time = 22.40 ns 9.8305993210e-03, // time = 22.41 ns 9.8120798159e-03, // time = 22.42 ns 9.7935833414e-03, // time = 22.43 ns 9.7751098544e-03, // time = 22.44 ns 9.7566593134e-03, // time = 22.45 ns 9.7382316804e-03, // time = 22.46 ns 9.7198269230e-03, // time = 22.47 ns 9.7014450152e-03, // time = 22.48 ns 9.6830859380e-03, // time = 22.49 ns 9.6647496789e-03, // time = 22.50 ns 9.6464362300e-03, // time = 22.51 ns 9.6281455868e-03, // time = 22.52 ns 9.6098777456e-03, // time = 22.53 ns 9.5916327019e-03, // time = 22.54 ns 9.5734104487e-03, // time = 22.55 ns 9.5552109758e-03, // time = 22.56 ns 9.5370342686e-03, // time = 22.57 ns 9.5188803084e-03, // time = 22.58 ns 9.5007490724e-03, // time = 22.59 ns 9.4826405342e-03, // time = 22.60 ns 9.4645546646e-03, // time = 22.61 ns 9.4464914319e-03, // time = 22.62 ns 9.4284508026e-03, // time = 22.63 ns 9.4104327423e-03, // time = 22.64 ns 9.3924372159e-03, // time = 22.65 ns 9.3744641884e-03, // time = 22.66 ns 9.3565136247e-03, // time = 22.67 ns 9.3385854906e-03, // time = 22.68 ns 9.3206797526e-03, // time = 22.69 ns 9.3027963781e-03, // time = 22.70 ns 9.2849353348e-03, // time = 22.71 ns 9.2670965911e-03, // time = 22.72 ns 9.2492801168e-03, // time = 22.73 ns 9.2314858829e-03, // time = 22.74 ns 9.2137138610e-03, // time = 22.75 ns 9.1959640236e-03, // time = 22.76 ns 9.1782363438e-03, // time = 22.77 ns 9.1605307954e-03, // time = 22.78 ns 9.1428473526e-03, // time = 22.79 ns 9.1251859900e-03, // time = 22.80 ns 9.1075466826e-03, // time = 22.81 ns 9.0899294058e-03, // time = 22.82 ns 9.0723341354e-03, // time = 22.83 ns 9.0547608470e-03, // time = 22.84 ns 9.0372095169e-03, // time = 22.85 ns 9.0196801213e-03, // time = 22.86 ns 9.0021726364e-03, // time = 22.87 ns 8.9846870387e-03, // time = 22.88 ns 8.9672233047e-03, // time = 22.89 ns 8.9497814108e-03, // time = 22.90 ns 8.9323613336e-03, // time = 22.91 ns 8.9149630496e-03, // time = 22.92 ns 8.8975865353e-03, // time = 22.93 ns 8.8802317672e-03, // time = 22.94 ns 8.8628987219e-03, // time = 22.95 ns 8.8455873756e-03, // time = 22.96 ns 8.8282977048e-03, // time = 22.97 ns 8.8110296860e-03, // time = 22.98 ns 8.7937832953e-03, // time = 22.99 ns 8.7765585091e-03, // time = 23.00 ns 8.7593553036e-03, // time = 23.01 ns 8.7421736551e-03, // time = 23.02 ns 8.7250135397e-03, // time = 23.03 ns 8.7078749334e-03, // time = 23.04 ns 8.6907578125e-03, // time = 23.05 ns 8.6736621530e-03, // time = 23.06 ns 8.6565879308e-03, // time = 23.07 ns 8.6395351221e-03, // time = 23.08 ns 8.6225037027e-03, // time = 23.09 ns 8.6054936487e-03, // time = 23.10 ns 8.5885049359e-03, // time = 23.11 ns 8.5715375403e-03, // time = 23.12 ns 8.5545914377e-03, // time = 23.13 ns 8.5376666040e-03, // time = 23.14 ns 8.5207630152e-03, // time = 23.15 ns 8.5038806469e-03, // time = 23.16 ns 8.4870194752e-03, // time = 23.17 ns 8.4701794758e-03, // time = 23.18 ns 8.4533606245e-03, // time = 23.19 ns 8.4365628971e-03, // time = 23.20 ns 8.4197862696e-03, // time = 23.21 ns 8.4030307176e-03, // time = 23.22 ns 8.3862962170e-03, // time = 23.23 ns 8.3695827437e-03, // time = 23.24 ns 8.3528902733e-03, // time = 23.25 ns 8.3362187818e-03, // time = 23.26 ns 8.3195682449e-03, // time = 23.27 ns 8.3029386385e-03, // time = 23.28 ns 8.2863299383e-03, // time = 23.29 ns 8.2697421203e-03, // time = 23.30 ns 8.2531751601e-03, // time = 23.31 ns 8.2366290337e-03, // time = 23.32 ns 8.2201037168e-03, // time = 23.33 ns 8.2035991854e-03, // time = 23.34 ns 8.1871154152e-03, // time = 23.35 ns 8.1706523822e-03, // time = 23.36 ns 8.1542100621e-03, // time = 23.37 ns 8.1377884308e-03, // time = 23.38 ns 8.1213874642e-03, // time = 23.39 ns 8.1050071382e-03, // time = 23.40 ns 8.0886474287e-03, // time = 23.41 ns 8.0723083115e-03, // time = 23.42 ns 8.0559897626e-03, // time = 23.43 ns 8.0396917578e-03, // time = 23.44 ns 8.0234142731e-03, // time = 23.45 ns 8.0071572844e-03, // time = 23.46 ns 7.9909207676e-03, // time = 23.47 ns 7.9747046987e-03, // time = 23.48 ns 7.9585090536e-03, // time = 23.49 ns 7.9423338083e-03, // time = 23.50 ns 7.9261789387e-03, // time = 23.51 ns 7.9100444208e-03, // time = 23.52 ns 7.8939302306e-03, // time = 23.53 ns 7.8778363441e-03, // time = 23.54 ns 7.8617627373e-03, // time = 23.55 ns 7.8457093862e-03, // time = 23.56 ns 7.8296762667e-03, // time = 23.57 ns 7.8136633551e-03, // time = 23.58 ns 7.7976706272e-03, // time = 23.59 ns 7.7816980591e-03, // time = 23.60 ns 7.7657456269e-03, // time = 23.61 ns 7.7498133066e-03, // time = 23.62 ns 7.7339010744e-03, // time = 23.63 ns 7.7180089063e-03, // time = 23.64 ns 7.7021367784e-03, // time = 23.65 ns 7.6862846668e-03, // time = 23.66 ns 7.6704525476e-03, // time = 23.67 ns 7.6546403970e-03, // time = 23.68 ns 7.6388481911e-03, // time = 23.69 ns 7.6230759060e-03, // time = 23.70 ns 7.6073235179e-03, // time = 23.71 ns 7.5915910030e-03, // time = 23.72 ns 7.5758783374e-03, // time = 23.73 ns 7.5601854974e-03, // time = 23.74 ns 7.5445124591e-03, // time = 23.75 ns 7.5288591988e-03, // time = 23.76 ns 7.5132256926e-03, // time = 23.77 ns 7.4976119169e-03, // time = 23.78 ns 7.4820178478e-03, // time = 23.79 ns 7.4664434616e-03, // time = 23.80 ns 7.4508887347e-03, // time = 23.81 ns 7.4353536432e-03, // time = 23.82 ns 7.4198381635e-03, // time = 23.83 ns 7.4043422719e-03, // time = 23.84 ns 7.3888659447e-03, // time = 23.85 ns 7.3734091582e-03, // time = 23.86 ns 7.3579718887e-03, // time = 23.87 ns 7.3425541127e-03, // time = 23.88 ns 7.3271558065e-03, // time = 23.89 ns 7.3117769465e-03, // time = 23.90 ns 7.2964175091e-03, // time = 23.91 ns 7.2810774706e-03, // time = 23.92 ns 7.2657568076e-03, // time = 23.93 ns 7.2504554963e-03, // time = 23.94 ns 7.2351735134e-03, // time = 23.95 ns 7.2199108352e-03, // time = 23.96 ns 7.2046674382e-03, // time = 23.97 ns 7.1894432989e-03, // time = 23.98 ns 7.1742383938e-03, // time = 23.99 ns 7.1590526994e-03, // time = 24.00 ns 7.1438861923e-03, // time = 24.01 ns 7.1287388489e-03, // time = 24.02 ns 7.1136106459e-03, // time = 24.03 ns 7.0985015598e-03, // time = 24.04 ns 7.0834115671e-03, // time = 24.05 ns 7.0683406446e-03, // time = 24.06 ns 7.0532887688e-03, // time = 24.07 ns 7.0382559163e-03, // time = 24.08 ns 7.0232420637e-03, // time = 24.09 ns 7.0082471878e-03, // time = 24.10 ns 6.9932712652e-03, // time = 24.11 ns 6.9783142726e-03, // time = 24.12 ns 6.9633761866e-03, // time = 24.13 ns 6.9484569841e-03, // time = 24.14 ns 6.9335566417e-03, // time = 24.15 ns 6.9186751362e-03, // time = 24.16 ns 6.9038124443e-03, // time = 24.17 ns 6.8889685429e-03, // time = 24.18 ns 6.8741434087e-03, // time = 24.19 ns 6.8593370185e-03, // time = 24.20 ns 6.8445493491e-03, // time = 24.21 ns 6.8297803775e-03, // time = 24.22 ns 6.8150300804e-03, // time = 24.23 ns 6.8002984347e-03, // time = 24.24 ns 6.7855854173e-03, // time = 24.25 ns 6.7708910052e-03, // time = 24.26 ns 6.7562151752e-03, // time = 24.27 ns 6.7415579042e-03, // time = 24.28 ns 6.7269191693e-03, // time = 24.29 ns 6.7122989475e-03, // time = 24.30 ns 6.6976972156e-03, // time = 24.31 ns 6.6831139507e-03, // time = 24.32 ns 6.6685491299e-03, // time = 24.33 ns 6.6540027302e-03, // time = 24.34 ns 6.6394747286e-03, // time = 24.35 ns 6.6249651022e-03, // time = 24.36 ns 6.6104738281e-03, // time = 24.37 ns 6.5960008834e-03, // time = 24.38 ns 6.5815462453e-03, // time = 24.39 ns 6.5671098908e-03, // time = 24.40 ns 6.5526917973e-03, // time = 24.41 ns 6.5382919418e-03, // time = 24.42 ns 6.5239103015e-03, // time = 24.43 ns 6.5095468537e-03, // time = 24.44 ns 6.4952015756e-03, // time = 24.45 ns 6.4808744445e-03, // time = 24.46 ns 6.4665654376e-03, // time = 24.47 ns 6.4522745323e-03, // time = 24.48 ns 6.4380017058e-03, // time = 24.49 ns 6.4237469356e-03, // time = 24.50 ns 6.4095101989e-03, // time = 24.51 ns 6.3952914730e-03, // time = 24.52 ns 6.3810907356e-03, // time = 24.53 ns 6.3669079638e-03, // time = 24.54 ns 6.3527431352e-03, // time = 24.55 ns 6.3385962272e-03, // time = 24.56 ns 6.3244672172e-03, // time = 24.57 ns 6.3103560829e-03, // time = 24.58 ns 6.2962628016e-03, // time = 24.59 ns 6.2821873509e-03, // time = 24.60 ns 6.2681297084e-03, // time = 24.61 ns 6.2540898516e-03, // time = 24.62 ns 6.2400677581e-03, // time = 24.63 ns 6.2260634056e-03, // time = 24.64 ns 6.2120767717e-03, // time = 24.65 ns 6.1981078340e-03, // time = 24.66 ns 6.1841565702e-03, // time = 24.67 ns 6.1702229580e-03, // time = 24.68 ns 6.1563069751e-03, // time = 24.69 ns 6.1424085993e-03, // time = 24.70 ns 6.1285278083e-03, // time = 24.71 ns 6.1146645799e-03, // time = 24.72 ns 6.1008188919e-03, // time = 24.73 ns 6.0869907222e-03, // time = 24.74 ns 6.0731800485e-03, // time = 24.75 ns 6.0593868488e-03, // time = 24.76 ns 6.0456111009e-03, // time = 24.77 ns 6.0318527828e-03, // time = 24.78 ns 6.0181118724e-03, // time = 24.79 ns 6.0043883476e-03, // time = 24.80 ns 5.9906821865e-03, // time = 24.81 ns 5.9769933670e-03, // time = 24.82 ns 5.9633218671e-03, // time = 24.83 ns 5.9496676650e-03, // time = 24.84 ns 5.9360307386e-03, // time = 24.85 ns 5.9224110660e-03, // time = 24.86 ns 5.9088086254e-03, // time = 24.87 ns 5.8952233950e-03, // time = 24.88 ns 5.8816553528e-03, // time = 24.89 ns 5.8681044770e-03, // time = 24.90 ns 5.8545707460e-03, // time = 24.91 ns 5.8410541378e-03, // time = 24.92 ns 5.8275546307e-03, // time = 24.93 ns 5.8140722031e-03, // time = 24.94 ns 5.8006068331e-03, // time = 24.95 ns 5.7871584992e-03, // time = 24.96 ns 5.7737271797e-03, // time = 24.97 ns 5.7603128529e-03, // time = 24.98 ns 5.7469154972e-03, // time = 24.99 ns 5.7335350911e-03, // time = 25.00 ns 5.7201716130e-03, // time = 25.01 ns 5.7068250413e-03, // time = 25.02 ns 5.6934953545e-03, // time = 25.03 ns 5.6801825312e-03, // time = 25.04 ns 5.6668865498e-03, // time = 25.05 ns 5.6536073889e-03, // time = 25.06 ns 5.6403450271e-03, // time = 25.07 ns 5.6270994430e-03, // time = 25.08 ns 5.6138706153e-03, // time = 25.09 ns 5.6006585225e-03, // time = 25.10 ns 5.5874631433e-03, // time = 25.11 ns 5.5742844565e-03, // time = 25.12 ns 5.5611224407e-03, // time = 25.13 ns 5.5479770747e-03, // time = 25.14 ns 5.5348483372e-03, // time = 25.15 ns 5.5217362071e-03, // time = 25.16 ns 5.5086406632e-03, // time = 25.17 ns 5.4955616842e-03, // time = 25.18 ns 5.4824992491e-03, // time = 25.19 ns 5.4694533368e-03, // time = 25.20 ns 5.4564239261e-03, // time = 25.21 ns 5.4434109959e-03, // time = 25.22 ns 5.4304145253e-03, // time = 25.23 ns 5.4174344933e-03, // time = 25.24 ns 5.4044708787e-03, // time = 25.25 ns 5.3915236606e-03, // time = 25.26 ns 5.3785928182e-03, // time = 25.27 ns 5.3656783304e-03, // time = 25.28 ns 5.3527801763e-03, // time = 25.29 ns 5.3398983352e-03, // time = 25.30 ns 5.3270327860e-03, // time = 25.31 ns 5.3141835080e-03, // time = 25.32 ns 5.3013504804e-03, // time = 25.33 ns 5.2885336824e-03, // time = 25.34 ns 5.2757330932e-03, // time = 25.35 ns 5.2629486920e-03, // time = 25.36 ns 5.2501804583e-03, // time = 25.37 ns 5.2374283712e-03, // time = 25.38 ns 5.2246924101e-03, // time = 25.39 ns 5.2119725543e-03, // time = 25.40 ns 5.1992687833e-03, // time = 25.41 ns 5.1865810764e-03, // time = 25.42 ns 5.1739094130e-03, // time = 25.43 ns 5.1612537727e-03, // time = 25.44 ns 5.1486141348e-03, // time = 25.45 ns 5.1359904788e-03, // time = 25.46 ns 5.1233827843e-03, // time = 25.47 ns 5.1107910309e-03, // time = 25.48 ns 5.0982151979e-03, // time = 25.49 ns 5.0856552652e-03, // time = 25.50 ns 5.0731112122e-03, // time = 25.51 ns 5.0605830185e-03, // time = 25.52 ns 5.0480706640e-03, // time = 25.53 ns 5.0355741281e-03, // time = 25.54 ns 5.0230933906e-03, // time = 25.55 ns 5.0106284313e-03, // time = 25.56 ns 4.9981792298e-03, // time = 25.57 ns 4.9857457660e-03, // time = 25.58 ns 4.9733280196e-03, // time = 25.59 ns 4.9609259704e-03, // time = 25.60 ns 4.9485395983e-03, // time = 25.61 ns 4.9361688832e-03, // time = 25.62 ns 4.9238138048e-03, // time = 25.63 ns 4.9114743431e-03, // time = 25.64 ns 4.8991504781e-03, // time = 25.65 ns 4.8868421897e-03, // time = 25.66 ns 4.8745494578e-03, // time = 25.67 ns 4.8622722624e-03, // time = 25.68 ns 4.8500105836e-03, // time = 25.69 ns 4.8377644013e-03, // time = 25.70 ns 4.8255336957e-03, // time = 25.71 ns 4.8133184469e-03, // time = 25.72 ns 4.8011186348e-03, // time = 25.73 ns 4.7889342397e-03, // time = 25.74 ns 4.7767652417e-03, // time = 25.75 ns 4.7646116209e-03, // time = 25.76 ns 4.7524733577e-03, // time = 25.77 ns 4.7403504320e-03, // time = 25.78 ns 4.7282428243e-03, // time = 25.79 ns 4.7161505147e-03, // time = 25.80 ns 4.7040734836e-03, // time = 25.81 ns 4.6920117112e-03, // time = 25.82 ns 4.6799651779e-03, // time = 25.83 ns 4.6679338640e-03, // time = 25.84 ns 4.6559177499e-03, // time = 25.85 ns 4.6439168160e-03, // time = 25.86 ns 4.6319310426e-03, // time = 25.87 ns 4.6199604102e-03, // time = 25.88 ns 4.6080048993e-03, // time = 25.89 ns 4.5960644903e-03, // time = 25.90 ns 4.5841391638e-03, // time = 25.91 ns 4.5722289003e-03, // time = 25.92 ns 4.5603336802e-03, // time = 25.93 ns 4.5484534842e-03, // time = 25.94 ns 4.5365882929e-03, // time = 25.95 ns 4.5247380869e-03, // time = 25.96 ns 4.5129028467e-03, // time = 25.97 ns 4.5010825531e-03, // time = 25.98 ns 4.4892771867e-03, // time = 25.99 ns 4.4774867283e-03, // time = 26.00 ns 4.4657111584e-03, // time = 26.01 ns 4.4539504580e-03, // time = 26.02 ns 4.4422046077e-03, // time = 26.03 ns 4.4304735883e-03, // time = 26.04 ns 4.4187573807e-03, // time = 26.05 ns 4.4070559656e-03, // time = 26.06 ns 4.3953693239e-03, // time = 26.07 ns 4.3836974365e-03, // time = 26.08 ns 4.3720402843e-03, // time = 26.09 ns 4.3603978482e-03, // time = 26.10 ns 4.3487701091e-03, // time = 26.11 ns 4.3371570479e-03, // time = 26.12 ns 4.3255586458e-03, // time = 26.13 ns 4.3139748836e-03, // time = 26.14 ns 4.3024057424e-03, // time = 26.15 ns 4.2908512033e-03, // time = 26.16 ns 4.2793112472e-03, // time = 26.17 ns 4.2677858554e-03, // time = 26.18 ns 4.2562750088e-03, // time = 26.19 ns 4.2447786888e-03, // time = 26.20 ns 4.2332968763e-03, // time = 26.21 ns 4.2218295526e-03, // time = 26.22 ns 4.2103766990e-03, // time = 26.23 ns 4.1989382965e-03, // time = 26.24 ns 4.1875143265e-03, // time = 26.25 ns 4.1761047702e-03, // time = 26.26 ns 4.1647096089e-03, // time = 26.27 ns 4.1533288239e-03, // time = 26.28 ns 4.1419623967e-03, // time = 26.29 ns 4.1306103084e-03, // time = 26.30 ns 4.1192725405e-03, // time = 26.31 ns 4.1079490745e-03, // time = 26.32 ns 4.0966398916e-03, // time = 26.33 ns 4.0853449735e-03, // time = 26.34 ns 4.0740643014e-03, // time = 26.35 ns 4.0627978570e-03, // time = 26.36 ns 4.0515456217e-03, // time = 26.37 ns 4.0403075772e-03, // time = 26.38 ns 4.0290837048e-03, // time = 26.39 ns 4.0178739863e-03, // time = 26.40 ns 4.0066784031e-03, // time = 26.41 ns 3.9954969370e-03, // time = 26.42 ns 3.9843295696e-03, // time = 26.43 ns 3.9731762826e-03, // time = 26.44 ns 3.9620370576e-03, // time = 26.45 ns 3.9509118764e-03, // time = 26.46 ns 3.9398007206e-03, // time = 26.47 ns 3.9287035722e-03, // time = 26.48 ns 3.9176204128e-03, // time = 26.49 ns 3.9065512242e-03, // time = 26.50 ns 3.8954959883e-03, // time = 26.51 ns 3.8844546869e-03, // time = 26.52 ns 3.8734273020e-03, // time = 26.53 ns 3.8624138153e-03, // time = 26.54 ns 3.8514142089e-03, // time = 26.55 ns 3.8404284646e-03, // time = 26.56 ns 3.8294565644e-03, // time = 26.57 ns 3.8184984903e-03, // time = 26.58 ns 3.8075542244e-03, // time = 26.59 ns 3.7966237486e-03, // time = 26.60 ns 3.7857070450e-03, // time = 26.61 ns 3.7748040957e-03, // time = 26.62 ns 3.7639148828e-03, // time = 26.63 ns 3.7530393883e-03, // time = 26.64 ns 3.7421775946e-03, // time = 26.65 ns 3.7313294836e-03, // time = 26.66 ns 3.7204950377e-03, // time = 26.67 ns 3.7096742390e-03, // time = 26.68 ns 3.6988670698e-03, // time = 26.69 ns 3.6880735123e-03, // time = 26.70 ns 3.6772935488e-03, // time = 26.71 ns 3.6665271616e-03, // time = 26.72 ns 3.6557743331e-03, // time = 26.73 ns 3.6450350456e-03, // time = 26.74 ns 3.6343092815e-03, // time = 26.75 ns 3.6235970231e-03, // time = 26.76 ns 3.6128982529e-03, // time = 26.77 ns 3.6022129534e-03, // time = 26.78 ns 3.5915411070e-03, // time = 26.79 ns 3.5808826962e-03, // time = 26.80 ns 3.5702377035e-03, // time = 26.81 ns 3.5596061114e-03, // time = 26.82 ns 3.5489879026e-03, // time = 26.83 ns 3.5383830595e-03, // time = 26.84 ns 3.5277915649e-03, // time = 26.85 ns 3.5172134012e-03, // time = 26.86 ns 3.5066485513e-03, // time = 26.87 ns 3.4960969977e-03, // time = 26.88 ns 3.4855587231e-03, // time = 26.89 ns 3.4750337104e-03, // time = 26.90 ns 3.4645219421e-03, // time = 26.91 ns 3.4540234011e-03, // time = 26.92 ns 3.4435380702e-03, // time = 26.93 ns 3.4330659321e-03, // time = 26.94 ns 3.4226069698e-03, // time = 26.95 ns 3.4121611661e-03, // time = 26.96 ns 3.4017285038e-03, // time = 26.97 ns 3.3913089659e-03, // time = 26.98 ns 3.3809025352e-03, // time = 26.99 ns 3.3705091948e-03, // time = 27.00 ns 3.3601289276e-03, // time = 27.01 ns 3.3497617166e-03, // time = 27.02 ns 3.3394075448e-03, // time = 27.03 ns 3.3290663953e-03, // time = 27.04 ns 3.3187382511e-03, // time = 27.05 ns 3.3084230954e-03, // time = 27.06 ns 3.2981209112e-03, // time = 27.07 ns 3.2878316816e-03, // time = 27.08 ns 3.2775553898e-03, // time = 27.09 ns 3.2672920191e-03, // time = 27.10 ns 3.2570415525e-03, // time = 27.11 ns 3.2468039734e-03, // time = 27.12 ns 3.2365792649e-03, // time = 27.13 ns 3.2263674103e-03, // time = 27.14 ns 3.2161683930e-03, // time = 27.15 ns 3.2059821963e-03, // time = 27.16 ns 3.1958088034e-03, // time = 27.17 ns 3.1856481978e-03, // time = 27.18 ns 3.1755003628e-03, // time = 27.19 ns 3.1653652818e-03, // time = 27.20 ns 3.1552429383e-03, // time = 27.21 ns 3.1451333157e-03, // time = 27.22 ns 3.1350363975e-03, // time = 27.23 ns 3.1249521672e-03, // time = 27.24 ns 3.1148806083e-03, // time = 27.25 ns 3.1048217043e-03, // time = 27.26 ns 3.0947754388e-03, // time = 27.27 ns 3.0847417955e-03, // time = 27.28 ns 3.0747207578e-03, // time = 27.29 ns 3.0647123095e-03, // time = 27.30 ns 3.0547164342e-03, // time = 27.31 ns 3.0447331155e-03, // time = 27.32 ns 3.0347623372e-03, // time = 27.33 ns 3.0248040830e-03, // time = 27.34 ns 3.0148583366e-03, // time = 27.35 ns 3.0049250818e-03, // time = 27.36 ns 2.9950043023e-03, // time = 27.37 ns 2.9850959821e-03, // time = 27.38 ns 2.9752001049e-03, // time = 27.39 ns 2.9653166546e-03, // time = 27.40 ns 2.9554456150e-03, // time = 27.41 ns 2.9455869701e-03, // time = 27.42 ns 2.9357407037e-03, // time = 27.43 ns 2.9259067999e-03, // time = 27.44 ns 2.9160852426e-03, // time = 27.45 ns 2.9062760157e-03, // time = 27.46 ns 2.8964791033e-03, // time = 27.47 ns 2.8866944894e-03, // time = 27.48 ns 2.8769221581e-03, // time = 27.49 ns 2.8671620934e-03, // time = 27.50 ns 2.8574142794e-03, // time = 27.51 ns 2.8476787003e-03, // time = 27.52 ns 2.8379553402e-03, // time = 27.53 ns 2.8282441832e-03, // time = 27.54 ns 2.8185452136e-03, // time = 27.55 ns 2.8088584156e-03, // time = 27.56 ns 2.7991837733e-03, // time = 27.57 ns 2.7895212710e-03, // time = 27.58 ns 2.7798708930e-03, // time = 27.59 ns 2.7702326236e-03, // time = 27.60 ns 2.7606064471e-03, // time = 27.61 ns 2.7509923479e-03, // time = 27.62 ns 2.7413903102e-03, // time = 27.63 ns 2.7318003186e-03, // time = 27.64 ns 2.7222223572e-03, // time = 27.65 ns 2.7126564107e-03, // time = 27.66 ns 2.7031024635e-03, // time = 27.67 ns 2.6935604999e-03, // time = 27.68 ns 2.6840305046e-03, // time = 27.69 ns 2.6745124619e-03, // time = 27.70 ns 2.6650063565e-03, // time = 27.71 ns 2.6555121729e-03, // time = 27.72 ns 2.6460298956e-03, // time = 27.73 ns 2.6365595093e-03, // time = 27.74 ns 2.6271009985e-03, // time = 27.75 ns 2.6176543479e-03, // time = 27.76 ns 2.6082195422e-03, // time = 27.77 ns 2.5987965661e-03, // time = 27.78 ns 2.5893854041e-03, // time = 27.79 ns 2.5799860412e-03, // time = 27.80 ns 2.5705984619e-03, // time = 27.81 ns 2.5612226511e-03, // time = 27.82 ns 2.5518585935e-03, // time = 27.83 ns 2.5425062740e-03, // time = 27.84 ns 2.5331656774e-03, // time = 27.85 ns 2.5238367885e-03, // time = 27.86 ns 2.5145195922e-03, // time = 27.87 ns 2.5052140734e-03, // time = 27.88 ns 2.4959202170e-03, // time = 27.89 ns 2.4866380080e-03, // time = 27.90 ns 2.4773674312e-03, // time = 27.91 ns 2.4681084716e-03, // time = 27.92 ns 2.4588611144e-03, // time = 27.93 ns 2.4496253443e-03, // time = 27.94 ns 2.4404011466e-03, // time = 27.95 ns 2.4311885062e-03, // time = 27.96 ns 2.4219874083e-03, // time = 27.97 ns 2.4127978379e-03, // time = 27.98 ns 2.4036197802e-03, // time = 27.99 ns 2.3944532202e-03, // time = 28.00 ns 2.3852981432e-03, // time = 28.01 ns 2.3761545344e-03, // time = 28.02 ns 2.3670223788e-03, // time = 28.03 ns 2.3579016619e-03, // time = 28.04 ns 2.3487923687e-03, // time = 28.05 ns 2.3396944846e-03, // time = 28.06 ns 2.3306079948e-03, // time = 28.07 ns 2.3215328847e-03, // time = 28.08 ns 2.3124691395e-03, // time = 28.09 ns 2.3034167447e-03, // time = 28.10 ns 2.2943756856e-03, // time = 28.11 ns 2.2853459475e-03, // time = 28.12 ns 2.2763275159e-03, // time = 28.13 ns 2.2673203762e-03, // time = 28.14 ns 2.2583245139e-03, // time = 28.15 ns 2.2493399144e-03, // time = 28.16 ns 2.2403665632e-03, // time = 28.17 ns 2.2314044458e-03, // time = 28.18 ns 2.2224535478e-03, // time = 28.19 ns 2.2135138547e-03, // time = 28.20 ns 2.2045853520e-03, // time = 28.21 ns 2.1956680254e-03, // time = 28.22 ns 2.1867618604e-03, // time = 28.23 ns 2.1778668428e-03, // time = 28.24 ns 2.1689829581e-03, // time = 28.25 ns 2.1601101920e-03, // time = 28.26 ns 2.1512485302e-03, // time = 28.27 ns 2.1423979585e-03, // time = 28.28 ns 2.1335584625e-03, // time = 28.29 ns 2.1247300280e-03, // time = 28.30 ns 2.1159126407e-03, // time = 28.31 ns 2.1071062866e-03, // time = 28.32 ns 2.0983109512e-03, // time = 28.33 ns 2.0895266206e-03, // time = 28.34 ns 2.0807532806e-03, // time = 28.35 ns 2.0719909170e-03, // time = 28.36 ns 2.0632395157e-03, // time = 28.37 ns 2.0544990626e-03, // time = 28.38 ns 2.0457695437e-03, // time = 28.39 ns 2.0370509449e-03, // time = 28.40 ns 2.0283432521e-03, // time = 28.41 ns 2.0196464515e-03, // time = 28.42 ns 2.0109605289e-03, // time = 28.43 ns 2.0022854704e-03, // time = 28.44 ns 1.9936212621e-03, // time = 28.45 ns 1.9849678901e-03, // time = 28.46 ns 1.9763253403e-03, // time = 28.47 ns 1.9676935990e-03, // time = 28.48 ns 1.9590726522e-03, // time = 28.49 ns 1.9504624861e-03, // time = 28.50 ns 1.9418630869e-03, // time = 28.51 ns 1.9332744408e-03, // time = 28.52 ns 1.9246965339e-03, // time = 28.53 ns 1.9161293526e-03, // time = 28.54 ns 1.9075728830e-03, // time = 28.55 ns 1.8990271113e-03, // time = 28.56 ns 1.8904920240e-03, // time = 28.57 ns 1.8819676073e-03, // time = 28.58 ns 1.8734538474e-03, // time = 28.59 ns 1.8649507309e-03, // time = 28.60 ns 1.8564582440e-03, // time = 28.61 ns 1.8479763731e-03, // time = 28.62 ns 1.8395051046e-03, // time = 28.63 ns 1.8310444249e-03, // time = 28.64 ns 1.8225943205e-03, // time = 28.65 ns 1.8141547779e-03, // time = 28.66 ns 1.8057257835e-03, // time = 28.67 ns 1.7973073238e-03, // time = 28.68 ns 1.7888993853e-03, // time = 28.69 ns 1.7805019546e-03, // time = 28.70 ns 1.7721150182e-03, // time = 28.71 ns 1.7637385628e-03, // time = 28.72 ns 1.7553725748e-03, // time = 28.73 ns 1.7470170410e-03, // time = 28.74 ns 1.7386719479e-03, // time = 28.75 ns 1.7303372822e-03, // time = 28.76 ns 1.7220130306e-03, // time = 28.77 ns 1.7136991797e-03, // time = 28.78 ns 1.7053957164e-03, // time = 28.79 ns 1.6971026272e-03, // time = 28.80 ns 1.6888198990e-03, // time = 28.81 ns 1.6805475185e-03, // time = 28.82 ns 1.6722854726e-03, // time = 28.83 ns 1.6640337479e-03, // time = 28.84 ns 1.6557923314e-03, // time = 28.85 ns 1.6475612099e-03, // time = 28.86 ns 1.6393403702e-03, // time = 28.87 ns 1.6311297992e-03, // time = 28.88 ns 1.6229294839e-03, // time = 28.89 ns 1.6147394111e-03, // time = 28.90 ns 1.6065595678e-03, // time = 28.91 ns 1.5983899409e-03, // time = 28.92 ns 1.5902305175e-03, // time = 28.93 ns 1.5820812844e-03, // time = 28.94 ns 1.5739422288e-03, // time = 28.95 ns 1.5658133377e-03, // time = 28.96 ns 1.5576945980e-03, // time = 28.97 ns 1.5495859969e-03, // time = 28.98 ns 1.5414875215e-03, // time = 28.99 ns 1.5333991588e-03, // time = 29.00 ns 1.5253208960e-03, // time = 29.01 ns 1.5172527202e-03, // time = 29.02 ns 1.5091946187e-03, // time = 29.03 ns 1.5011465785e-03, // time = 29.04 ns 1.4931085869e-03, // time = 29.05 ns 1.4850806311e-03, // time = 29.06 ns 1.4770626983e-03, // time = 29.07 ns 1.4690547757e-03, // time = 29.08 ns 1.4610568508e-03, // time = 29.09 ns 1.4530689107e-03, // time = 29.10 ns 1.4450909427e-03, // time = 29.11 ns 1.4371229342e-03, // time = 29.12 ns 1.4291648726e-03, // time = 29.13 ns 1.4212167451e-03, // time = 29.14 ns 1.4132785392e-03, // time = 29.15 ns 1.4053502423e-03, // time = 29.16 ns 1.3974318418e-03, // time = 29.17 ns 1.3895233251e-03, // time = 29.18 ns 1.3816246796e-03, // time = 29.19 ns 1.3737358930e-03, // time = 29.20 ns 1.3658569526e-03, // time = 29.21 ns 1.3579878459e-03, // time = 29.22 ns 1.3501285606e-03, // time = 29.23 ns 1.3422790841e-03, // time = 29.24 ns 1.3344394039e-03, // time = 29.25 ns 1.3266095078e-03, // time = 29.26 ns 1.3187893832e-03, // time = 29.27 ns 1.3109790178e-03, // time = 29.28 ns 1.3031783993e-03, // time = 29.29 ns 1.2953875152e-03, // time = 29.30 ns 1.2876063533e-03, // time = 29.31 ns 1.2798349013e-03, // time = 29.32 ns 1.2720731468e-03, // time = 29.33 ns 1.2643210776e-03, // time = 29.34 ns 1.2565786814e-03, // time = 29.35 ns 1.2488459459e-03, // time = 29.36 ns 1.2411228591e-03, // time = 29.37 ns 1.2334094086e-03, // time = 29.38 ns 1.2257055822e-03, // time = 29.39 ns 1.2180113679e-03, // time = 29.40 ns 1.2103267534e-03, // time = 29.41 ns 1.2026517266e-03, // time = 29.42 ns 1.1949862755e-03, // time = 29.43 ns 1.1873303878e-03, // time = 29.44 ns 1.1796840516e-03, // time = 29.45 ns 1.1720472547e-03, // time = 29.46 ns 1.1644199851e-03, // time = 29.47 ns 1.1568022308e-03, // time = 29.48 ns 1.1491939798e-03, // time = 29.49 ns 1.1415952200e-03, // time = 29.50 ns 1.1340059396e-03, // time = 29.51 ns 1.1264261265e-03, // time = 29.52 ns 1.1188557688e-03, // time = 29.53 ns 1.1112948545e-03, // time = 29.54 ns 1.1037433719e-03, // time = 29.55 ns 1.0962013089e-03, // time = 29.56 ns 1.0886686537e-03, // time = 29.57 ns 1.0811453945e-03, // time = 29.58 ns 1.0736315194e-03, // time = 29.59 ns 1.0661270166e-03, // time = 29.60 ns 1.0586318743e-03, // time = 29.61 ns 1.0511460807e-03, // time = 29.62 ns 1.0436696241e-03, // time = 29.63 ns 1.0362024926e-03, // time = 29.64 ns 1.0287446746e-03, // time = 29.65 ns 1.0212961583e-03, // time = 29.66 ns 1.0138569320e-03, // time = 29.67 ns 1.0064269841e-03, // time = 29.68 ns 9.9900630290e-04, // time = 29.69 ns 9.9159487670e-04, // time = 29.70 ns 9.8419269388e-04, // time = 29.71 ns 9.7679974285e-04, // time = 29.72 ns 9.6941601200e-04, // time = 29.73 ns 9.6204148974e-04, // time = 29.74 ns 9.5467616451e-04, // time = 29.75 ns 9.4732002476e-04, // time = 29.76 ns 9.3997305896e-04, // time = 29.77 ns 9.3263525559e-04, // time = 29.78 ns 9.2530660316e-04, // time = 29.79 ns 9.1798709017e-04, // time = 29.80 ns 9.1067670517e-04, // time = 29.81 ns 9.0337543670e-04, // time = 29.82 ns 8.9608327334e-04, // time = 29.83 ns 8.8880020366e-04, // time = 29.84 ns 8.8152621627e-04, // time = 29.85 ns 8.7426129978e-04, // time = 29.86 ns 8.6700544283e-04, // time = 29.87 ns 8.5975863408e-04, // time = 29.88 ns 8.5252086217e-04, // time = 29.89 ns 8.4529211581e-04, // time = 29.90 ns 8.3807238368e-04, // time = 29.91 ns 8.3086165450e-04, // time = 29.92 ns 8.2365991702e-04, // time = 29.93 ns 8.1646715996e-04, // time = 29.94 ns 8.0928337211e-04, // time = 29.95 ns 8.0210854224e-04, // time = 29.96 ns 7.9494265915e-04, // time = 29.97 ns 7.8778571165e-04, // time = 29.98 ns 7.8063768857e-04, // time = 29.99 ns 7.7155314684e-04, // time = 30.00 ns 7.6656313013e-04, // time = 30.01 ns 7.6086528589e-04, // time = 30.02 ns 7.5375088195e-04, // time = 30.03 ns 7.4664531521e-04, // time = 30.04 ns 7.3954859750e-04, // time = 30.05 ns 7.3246072530e-04, // time = 30.06 ns 7.2538169006e-04, // time = 30.07 ns 7.1831148155e-04, // time = 30.08 ns 7.1125008902e-04, // time = 30.09 ns 7.0419750158e-04, // time = 30.10 ns 6.9715370826e-04, // time = 30.11 ns 6.9011869811e-04, // time = 30.12 ns 6.8309246019e-04, // time = 30.13 ns 6.7607498357e-04, // time = 30.14 ns 6.6906625733e-04, // time = 30.15 ns 6.6206627057e-04, // time = 30.16 ns 6.5507501240e-04, // time = 30.17 ns 6.4809247196e-04, // time = 30.18 ns 6.4111863838e-04, // time = 30.19 ns 6.3415350083e-04, // time = 30.20 ns 6.2719704848e-04, // time = 30.21 ns 6.2024927053e-04, // time = 30.22 ns 6.1331015619e-04, // time = 30.23 ns 6.0637969469e-04, // time = 30.24 ns 5.9945787526e-04, // time = 30.25 ns 5.9254468716e-04, // time = 30.26 ns 5.8564011966e-04, // time = 30.27 ns 5.7874416204e-04, // time = 30.28 ns 5.7185680362e-04, // time = 30.29 ns 5.6497803371e-04, // time = 30.30 ns 5.5810784163e-04, // time = 30.31 ns 5.5124621675e-04, // time = 30.32 ns 5.4439314842e-04, // time = 30.33 ns 5.3754862603e-04, // time = 30.34 ns 5.3071263896e-04, // time = 30.35 ns 5.2388517663e-04, // time = 30.36 ns 5.1706622848e-04, // time = 30.37 ns 5.1025578392e-04, // time = 30.38 ns 5.0345383243e-04, // time = 30.39 ns 4.9666036348e-04, // time = 30.40 ns 4.8987536655e-04, // time = 30.41 ns 4.8309883115e-04, // time = 30.42 ns 4.7633074679e-04, // time = 30.43 ns 4.6957110300e-04, // time = 30.44 ns 4.6281988934e-04, // time = 30.45 ns 4.5607709536e-04, // time = 30.46 ns 4.4934271065e-04, // time = 30.47 ns 4.4261672479e-04, // time = 30.48 ns 4.3589912740e-04, // time = 30.49 ns 4.2918990810e-04, // time = 30.50 ns 4.2248905653e-04, // time = 30.51 ns 4.1579656234e-04, // time = 30.52 ns 4.0911241520e-04, // time = 30.53 ns 4.0243660479e-04, // time = 30.54 ns 3.9576912082e-04, // time = 30.55 ns 3.8910995299e-04, // time = 30.56 ns 3.8245909104e-04, // time = 30.57 ns 3.7581652470e-04, // time = 30.58 ns 3.6918224373e-04, // time = 30.59 ns 3.6255623791e-04, // time = 30.60 ns 3.5593849703e-04, // time = 30.61 ns 3.4932901089e-04, // time = 30.62 ns 3.4272776929e-04, // time = 30.63 ns 3.3613476208e-04, // time = 30.64 ns 3.2954997911e-04, // time = 30.65 ns 3.2297341022e-04, // time = 30.66 ns 3.1640504531e-04, // time = 30.67 ns 3.0984487425e-04, // time = 30.68 ns 3.0329288696e-04, // time = 30.69 ns 2.9674907335e-04, // time = 30.70 ns 2.9021342336e-04, // time = 30.71 ns 2.8368592694e-04, // time = 30.72 ns 2.7716657406e-04, // time = 30.73 ns 2.7065535468e-04, // time = 30.74 ns 2.6415225880e-04, // time = 30.75 ns 2.5765727644e-04, // time = 30.76 ns 2.5117039760e-04, // time = 30.77 ns 2.4469161233e-04, // time = 30.78 ns 2.3822091068e-04, // time = 30.79 ns 2.3175828271e-04, // time = 30.80 ns 2.2530371850e-04, // time = 30.81 ns 2.1885720814e-04, // time = 30.82 ns 2.1241874175e-04, // time = 30.83 ns 2.0598830943e-04, // time = 30.84 ns 1.9956590134e-04, // time = 30.85 ns 1.9315150761e-04, // time = 30.86 ns 1.8674511842e-04, // time = 30.87 ns 1.8034672394e-04, // time = 30.88 ns 1.7395631437e-04, // time = 30.89 ns 1.6757387991e-04, // time = 30.90 ns 1.6119941079e-04, // time = 30.91 ns 1.5483289723e-04, // time = 30.92 ns 1.4847432949e-04, // time = 30.93 ns 1.4212369784e-04, // time = 30.94 ns 1.3578099255e-04, // time = 30.95 ns 1.2944620391e-04, // time = 30.96 ns 1.2311932223e-04, // time = 30.97 ns 1.1680033782e-04, // time = 30.98 ns 1.1048924103e-04, // time = 30.99 ns 1.0418602220e-04 };// time = 31.00 ns }
41.493914
67
0.568425
nistefan
219dd34be04d01ba0039885fdc414cc282d234e3
15,257
cpp
C++
BAPSPresenter/SecurityDialog.cpp
UniversityRadioYork/BAPS2
af80b66cdd7a980cf34714bef7b5260167714ca5
[ "BSD-3-Clause" ]
4
2018-12-20T20:58:46.000Z
2019-05-22T21:32:43.000Z
BAPSPresenter/SecurityDialog.cpp
UniversityRadioYork/BAPS2
af80b66cdd7a980cf34714bef7b5260167714ca5
[ "BSD-3-Clause" ]
9
2018-12-22T00:55:13.000Z
2019-01-21T10:08:30.000Z
BAPSPresenter/SecurityDialog.cpp
UniversityRadioYork/BAPS2
af80b66cdd7a980cf34714bef7b5260167714ca5
[ "BSD-3-Clause" ]
1
2018-12-21T19:32:48.000Z
2018-12-21T19:32:48.000Z
#include "StdAfx.h" #include "SecurityDialog.h" #include "UtilityMacros.h" #undef MessageBox using namespace BAPSPresenter; void SecurityDialog::receiveUserCount(System::Object^ _count) { grantButton->Enabled = false; revokeButton->Enabled = false; availablePermissionList->Enabled = false; permissionList->Enabled = false; newPasswordText->Enabled = false; newPasswordText->Text = "12345"; confirmNewPasswordText->Enabled = false; confirmNewPasswordText->Text = "12345"; setPasswordButton->Enabled = false; deleteUserButton->Enabled = false; selectedUserLabel->Text = "<Select User>"; permissionList->Items->Clear(); availablePermissionList->Items->Clear(); userList->Enabled = false; userList->Items->Clear(); userCount = safe_cast<int>(_count); if (userCount == 0) { status = SD_DORMANT; userList->Enabled=true; } } void SecurityDialog::receiveUserInfo(System::String^ username, System::Object^ _permissions) { int permissions = safe_cast<int>(_permissions); userList->Items->Add(gcnew UserInfo(username, permissions)); userCount--; if (userCount == 0) { status = SD_DORMANT; userList->Enabled=true; } } void SecurityDialog::receivePermissionCount(System::Object^ _count) { permissionCount = safe_cast<int>(_count); permissionInfo = gcnew array<PermissionInfo^>(permissionCount); } void SecurityDialog::receivePermissionInfo(System::Object^ _permissionCode, System::String^ description) { int permissionCode = safe_cast<int>(_permissionCode); permissionInfo[permissionInfo->Length-permissionCount] = gcnew PermissionInfo(permissionCode, description); permissionCount--; if (permissionCount == 0) { status = SD_GETUSERS; Command cmd = BAPSNET_CONFIG | BAPSNET_GETUSERS; msgQueue->Enqueue(gcnew ActionMessage(cmd)); } } void SecurityDialog::receiveUserResult(System::Object^ _resultCode, System::String^ description) { SecurityStatus tempStatus = SD_DORMANT; int resultCode = safe_cast<int>(_resultCode); switch (status) { case SD_AWAITING_INIT: case SD_GETUSERS: System::Windows::Forms::MessageBox::Show(System::String::Concat("Cannot open Security Manager, reason: ", description), "Error:", System::Windows::Forms::MessageBoxButtons::OK); this->Close(); break; case SD_DORMANT: System::Windows::Forms::MessageBox::Show("A recoverable error has occurred, this dialog will be closed. (Result rcvd but no cmd issued)", "Error:", System::Windows::Forms::MessageBoxButtons::OK); this->Close(); break; case SD_ADDUSER: if (resultCode == 0) { newUsernameText->Text=""; passwordText->Text=""; confirmPasswordText->Text=""; addUserButton->Enabled=true; tempStatus = SD_GETUSERS; status = SD_GETUSERS; Command cmd = BAPSNET_CONFIG | BAPSNET_GETUSERS; msgQueue->Enqueue(gcnew ActionMessage(cmd)); } else { System::Windows::Forms::MessageBox::Show(System::String::Concat("Cannot add user, reason: ", description), "Error:", System::Windows::Forms::MessageBoxButtons::OK); } break; case SD_SETPASSWORD: if (resultCode == 0) { newPasswordText->Text="12345"; confirmNewPasswordText->Text="12345"; setPasswordButton->Enabled=true; } else { System::Windows::Forms::MessageBox::Show(System::String::Concat("Cannot set password, reason: ", description), "Error:", System::Windows::Forms::MessageBoxButtons::OK); } break; case SD_REMOVEUSER: if (resultCode == 0) { tempStatus = SD_GETUSERS; status = SD_GETUSERS; Command cmd = BAPSNET_CONFIG | BAPSNET_GETUSERS; msgQueue->Enqueue(gcnew ActionMessage(cmd)); } else { System::Windows::Forms::MessageBox::Show(System::String::Concat("Cannot delete user, reason: ", description), "Error:", System::Windows::Forms::MessageBoxButtons::OK); } break; case SD_REVOKEPERMISSION: if (resultCode == 0) { tempStatus = SD_GETUSERS; status = SD_GETUSERS; Command cmd = BAPSNET_CONFIG | BAPSNET_GETUSERS; msgQueue->Enqueue(gcnew ActionMessage(cmd)); } else { System::Windows::Forms::MessageBox::Show(System::String::Concat("Cannot revoke permission, reason: ", description), "Error:", System::Windows::Forms::MessageBoxButtons::OK); } break; case SD_GRANTPERMISSION: if (resultCode == 0) { tempStatus = SD_GETUSERS; status = SD_GETUSERS; Command cmd = BAPSNET_CONFIG | BAPSNET_GETUSERS; msgQueue->Enqueue(gcnew ActionMessage(cmd)); } else { System::Windows::Forms::MessageBox::Show(System::String::Concat("Cannot grant permission, reason: ", description), "Error:", System::Windows::Forms::MessageBoxButtons::OK); } break; } status = tempStatus; } System::Void SecurityDialog::refreshButton_Click(System::Object ^ sender, System::EventArgs ^ e) { if (status == SD_DORMANT) { addUserButton->Enabled=false; status = SD_GETUSERS; Command cmd = BAPSNET_CONFIG | BAPSNET_GETUSERS; msgQueue->Enqueue(gcnew ActionMessage(cmd)); } else { System::Windows::Forms::MessageBox::Show("A command is still being processed please wait and try again", "Notice:", System::Windows::Forms::MessageBoxButtons::OK); } } System::Void SecurityDialog::deleteUserButton_Click(System::Object ^ sender, System::EventArgs ^ e) { if (status == SD_DORMANT) { System::Windows::Forms::DialogResult dr; dr = System::Windows::Forms::MessageBox::Show("Are you sure you wish to delete the selcted user?", "Notice:", System::Windows::Forms::MessageBoxButtons::YesNo); if (dr == System::Windows::Forms::DialogResult::Yes) { status = SD_REMOVEUSER; Command cmd = BAPSNET_CONFIG | BAPSNET_REMOVEUSER; msgQueue->Enqueue(gcnew ActionMessageString(cmd, selectedUserLabel->Text)); } } else { System::Windows::Forms::MessageBox::Show("A command is still being processed please wait and try again", "Notice:", System::Windows::Forms::MessageBoxButtons::OK); } } System::Void SecurityDialog::newUserText_Leave(System::Object ^ sender, System::EventArgs ^ e) { bool valid = (newUsernameText->Text->Length>0 && System::String::Compare(passwordText->Text, confirmPasswordText->Text) == 0); addUserButton->Enabled = valid; if (!valid) { newUsernameLabel->ForeColor = System::Drawing::Color::Red; confirmPasswordLabel->ForeColor = System::Drawing::Color::Red; } else { newUsernameLabel->ForeColor = System::Drawing::SystemColors::ControlText; confirmPasswordLabel->ForeColor = System::Drawing::SystemColors::ControlText; } } System::Void SecurityDialog::changePassword_TextChanged(System::Object ^ sender, System::EventArgs ^ e) { bool valid = (System::String::Compare(newPasswordText->Text, confirmNewPasswordText->Text) == 0); setPasswordButton->Enabled = valid; if (!valid) { confirmNewPasswordLabel->ForeColor = System::Drawing::Color::Red; } else { confirmNewPasswordLabel->ForeColor = System::Drawing::SystemColors::ControlText; } } System::Void SecurityDialog::addUserButton_Click(System::Object ^ sender, System::EventArgs ^ e) { if (status == SD_DORMANT) { addUserButton->Enabled=false; status = SD_ADDUSER; Command cmd = BAPSNET_CONFIG | BAPSNET_ADDUSER; msgQueue->Enqueue(gcnew ActionMessageStringString(cmd, newUsernameText->Text, passwordText->Text)); } else { System::Windows::Forms::MessageBox::Show("A command is still being processed please wait and try again", "Notice:", System::Windows::Forms::MessageBoxButtons::OK); } } System::Void SecurityDialog::setPasswordButton_Click(System::Object ^ sender, System::EventArgs ^ e) { if (status == SD_DORMANT) { setPasswordButton->Enabled=false; status = SD_SETPASSWORD; Command cmd = BAPSNET_CONFIG | BAPSNET_SETPASSWORD; msgQueue->Enqueue(gcnew ActionMessageStringString(cmd, selectedUserLabel->Text, newPasswordText->Text)); } else { System::Windows::Forms::MessageBox::Show("A command is still being processed please wait and try again", "Notice:", System::Windows::Forms::MessageBoxButtons::OK); } } System::Void SecurityDialog::userList_SelectedIndexChanged(System::Object ^ sender, System::EventArgs ^ e) { grantButton->Enabled = false; revokeButton->Enabled = false; availablePermissionList->Enabled = false; permissionList->Enabled = false; newPasswordText->Enabled = false; newPasswordText->Text = "12345"; confirmNewPasswordText->Enabled = false; confirmNewPasswordText->Text = "12345"; setPasswordButton->Enabled = false; deleteUserButton->Enabled = false; UserInfo^ userInfo; if (userList->SelectedIndex != -1) { userInfo = static_cast<UserInfo^>(userList->Items[userList->SelectedIndex]); } else { userInfo = gcnew UserInfo("<None>", 0); } selectedUserLabel->Text = userInfo->username; int permissions = userInfo->permissions; permissionList->Items->Clear(); availablePermissionList->Items->Clear(); int i; for (i = 0 ; i < permissionInfo->Length ; i++) { if (ISFLAGSET(permissions, permissionInfo[i]->permissionCode)) { permissionList->Items->Add(permissionInfo[i]); } else { availablePermissionList->Items->Add(permissionInfo[i]); } } availablePermissionList->Enabled = true; permissionList->Enabled = true; newPasswordText->Enabled = true; confirmNewPasswordText->Enabled = true; deleteUserButton->Enabled = true; } System::Void SecurityDialog::permissionList_SelectedIndexChanged(System::Object ^ sender, System::EventArgs ^ e) { revokeButton->Enabled = (permissionList->SelectedIndex != -1); } System::Void SecurityDialog::availablePermissionList_SelectedIndexChanged(System::Object ^ sender, System::EventArgs ^ e) { grantButton->Enabled = (availablePermissionList->SelectedIndex != -1); } System::Void SecurityDialog::revokeButton_Click(System::Object ^ sender, System::EventArgs ^ e) { if (status == SD_DORMANT) { status = SD_REVOKEPERMISSION; int permission = static_cast<PermissionInfo^>(permissionList->Items[permissionList->SelectedIndex])->permissionCode; Command cmd = BAPSNET_CONFIG | BAPSNET_REVOKEPERMISSION; msgQueue->Enqueue(gcnew ActionMessageStringU32int(cmd, selectedUserLabel->Text, permission)); } else { System::Windows::Forms::MessageBox::Show("A command is still being processed please wait and try again", "Notice:", System::Windows::Forms::MessageBoxButtons::OK); } } System::Void SecurityDialog::grantButton_Click(System::Object ^ sender, System::EventArgs ^ e) { if (status == SD_DORMANT) { status = SD_GRANTPERMISSION; int permission = static_cast<PermissionInfo^>(availablePermissionList->Items[availablePermissionList->SelectedIndex])->permissionCode; Command cmd = BAPSNET_CONFIG | BAPSNET_GRANTPERMISSION; msgQueue->Enqueue(gcnew ActionMessageStringU32int(cmd, selectedUserLabel->Text, permission)); } else { System::Windows::Forms::MessageBox::Show("A command is still being processed please wait and try again", "Notice:", System::Windows::Forms::MessageBoxButtons::OK); } } void SecurityDialog::receiveIPDenyCount(System::Object^ _count) { denyCount = safe_cast<int>(_count); deniedIPList->Enabled=false; deniedIPList->Items->Clear(); if (denyCount == 0) { if (status == SD_GETIPRESTRICTIONS) { status = SD_GETIPRESTRICTIONS2; } else { status = SD_DORMANT; } deniedIPList->Enabled=true; } } void SecurityDialog::receiveIPAllowCount(System::Object^ _count) { allowCount = safe_cast<int>(_count); allowedIPList->Enabled=false; allowedIPList->Items->Clear(); if (allowCount == 0) { if (status == SD_GETIPRESTRICTIONS) { status = SD_GETIPRESTRICTIONS2; } else { status = SD_DORMANT; } allowedIPList->Enabled=true; } } void SecurityDialog::receiveIPDeny(System::String^ ipaddress, System::Object^ _mask) { int mask = safe_cast<int>(_mask); deniedIPList->Items->Add(gcnew IPRestriction(ipaddress, mask)); denyCount--; if (denyCount == 0) { if (status == SD_GETIPRESTRICTIONS) { status = SD_GETIPRESTRICTIONS2; } else { status = SD_DORMANT; } deniedIPList->Enabled=true; } } void SecurityDialog::receiveIPAllow(System::String^ ipaddress, System::Object^ _mask) { int mask = safe_cast<int>(_mask); allowedIPList->Items->Add(gcnew IPRestriction(ipaddress, mask)); allowCount--; if (allowCount == 0) { if (status == SD_GETIPRESTRICTIONS) { status = SD_GETIPRESTRICTIONS2; } else { status = SD_DORMANT; } allowedIPList->Enabled=true; } } System::Void SecurityDialog::securityPageControl_SelectedIndexChanged(System::Object ^ sender, System::EventArgs ^ e) { if (securityPageControl->SelectedTab == userManagerPage) { if (status == SD_DORMANT) { status = SD_GETUSERS; Command cmd = BAPSNET_CONFIG | BAPSNET_GETUSERS; msgQueue->Enqueue(gcnew ActionMessage(cmd)); } else { System::Windows::Forms::MessageBox::Show("A command is still being processed please wait and use the refresh button to update the form.", "Notice:", System::Windows::Forms::MessageBoxButtons::OK); } } else if (securityPageControl->SelectedTab == connectionManagerPage) { if (status == SD_DORMANT) { status = SD_GETIPRESTRICTIONS; Command cmd = BAPSNET_CONFIG | BAPSNET_GETIPRESTRICTIONS; msgQueue->Enqueue(gcnew ActionMessage(cmd)); } else { System::Windows::Forms::MessageBox::Show("A command is still being processed please wait and use the refresh button to update the form.", "Notice:", System::Windows::Forms::MessageBoxButtons::OK); } } } void SecurityDialog::receiveConfigError(System::Object^ _resultCode, System::String^ description) { int resultCode = safe_cast<int>(_resultCode); if (resultCode != 0) { System::Windows::Forms::MessageBox::Show(System::String::Concat("Unable to alter IP list, reason: ", description), "Error:", System::Windows::Forms::MessageBoxButtons::OK); } status = SD_GETIPRESTRICTIONS; Command cmd = BAPSNET_CONFIG | BAPSNET_GETIPRESTRICTIONS; msgQueue->Enqueue(gcnew ActionMessage(cmd)); } System::Void SecurityDialog::alterRestrictionButton_Click(System::Object ^ sender, System::EventArgs ^ e) { if (status == SD_DORMANT) { try { int cmdMask = safe_cast<int>(static_cast<System::Windows::Forms::Button^>(sender)->Tag); status = SD_ALTERIPRESTRICTION; Command cmd = BAPSNET_CONFIG | BAPSNET_ALTERIPRESTRICTION | cmdMask; msgQueue->Enqueue(gcnew ActionMessageStringU32int(cmd, ipAddressText->Text, (u32int)System::Convert::ToInt32(maskText->Text))); } catch (System::FormatException^ ) { System::Windows::Forms::MessageBox::Show("The mask value must be an integer.", "Error:", System::Windows::Forms::MessageBoxButtons::OK); status = SD_DORMANT; } } else { System::Windows::Forms::MessageBox::Show("A command is still being processed please wait and use the refresh button to update the form.", "Notice:", System::Windows::Forms::MessageBoxButtons::OK); } } System::Void SecurityDialog::SecurityDialog_KeyDown(System::Object^ sender, System::Windows::Forms::KeyEventArgs^ e) { bool ignore = false; switch (e->KeyCode) { case 'S' : /** Ctrl+s opens this window, we don't want another **/ if (e->Control & e->Shift) { ignore = true; } } if (!ignore) { MethodInvokerObjKeyEventArgs^ mi = gcnew MethodInvokerObjKeyEventArgs(bapsPresenterMain, &BAPSPresenterMain::BAPSPresenterMain_KeyDown); array<System::Object^>^ dd = gcnew array<System::Object^>(2) {bapsPresenterMain, e}; this->Invoke(mi, dd); } }
32.324153
199
0.730878
UniversityRadioYork
219f4474b7a0e490495e53119708bdffb0737351
950
cpp
C++
test/linux/main.cpp
77Z/Shadow-Engine
a07121d56dcf71a040580e9d4e563f36a70123a3
[ "MIT" ]
3
2020-08-31T20:38:54.000Z
2021-06-17T12:31:44.000Z
test/linux/main.cpp
77Z/Shadow-Engine
a07121d56dcf71a040580e9d4e563f36a70123a3
[ "MIT" ]
3
2020-08-31T19:08:43.000Z
2022-03-25T19:11:50.000Z
test/linux/main.cpp
77Z/Shadow-Engine
a07121d56dcf71a040580e9d4e563f36a70123a3
[ "MIT" ]
null
null
null
//Copyright © Vince Richter 2020 //Copyright © 77Z™ 2020 #include "main.h" void print(std::string text) { std::cout << text << std::endl; } inline bool exists(const std::string& name) { struct stat buffer; return (stat (name.c_str(), &buffer) == 0); } int main() { print("Running Linux Style Tests"); if (exists("./node_modules/electron/dist/electron")) { print("Test 1 Passed"); } else { print("Test 1 Failed"); exit(1); } if (exists("./node_modules/node-pty/build/Release/pty.node")) { print("Test 2 Passed"); } else { print("Test 2 Failed"); exit(1); } if (exists("./node_modules/uuid/dist/index.js")) { print("Test 3 Passed"); } else { print("Test 3 Failed"); exit(1); } print("All tests passed (Linux)"); //Every Test Passed, exit with code 0 return 0; }
21.111111
68
0.532632
77Z
21a0be3e9e52fc6864f119b94e882cd0fb50af9f
2,681
cpp
C++
ExaHyPE/kernels/aderdg/generic/fortran/3d/amrRoutines3D.cpp
yungcheeze/exahype
897970ea2836132e1c221eec7bd1a717afee97ae
[ "BSD-3-Clause" ]
2
2019-08-14T22:41:26.000Z
2020-02-04T19:30:24.000Z
ExaHyPE/kernels/aderdg/generic/fortran/3d/amrRoutines3D.cpp
yungcheeze/exahype
897970ea2836132e1c221eec7bd1a717afee97ae
[ "BSD-3-Clause" ]
null
null
null
ExaHyPE/kernels/aderdg/generic/fortran/3d/amrRoutines3D.cpp
yungcheeze/exahype
897970ea2836132e1c221eec7bd1a717afee97ae
[ "BSD-3-Clause" ]
3
2019-07-22T10:27:36.000Z
2020-05-11T12:25:29.000Z
/** * This file is part of the ExaHyPE project. * Copyright (c) 2016 http://exahype.eu * All rights reserved. * * The project has received funding from the European Union's Horizon * 2020 research and innovation programme under grant agreement * No 671698. For copyrights and licensing, please consult the webpage. * * Released under the BSD 3 Open Source License. * For the full license text, see LICENSE.txt **/ #include "kernels/aderdg/generic/Kernels.h" #include "tarch/la/Scalar.h" #include "tarch/la/ScalarOperations.h" #include "kernels/GaussLegendreQuadrature.h" #include "kernels/DGMatrices.h" #if DIMENSIONS == 3 void kernels::aderdg::generic::fortran::faceUnknownsProlongation(double* lQhbndFine, double* lFhbndFine, const double* lQhbndCoarse, const double* lFhbndCoarse, const int coarseGridLevel, const int fineGridLevel, const tarch::la::Vector<DIMENSIONS-1, int>& subfaceIndex, const int numberOfVariables, const int basisSize){ // @todo Please implement! } void kernels::aderdg::generic::fortran::faceUnknownsRestriction(double* lQhbndCoarse, double* lFhbndCoarse, const double* lQhbndFine, const double* lFhbndFine, const int coarseGridLevel, const int fineGridLevel, const tarch::la::Vector<DIMENSIONS-1, int>& subfaceIndex, const int numberOfVariables, const int basisSize){ // @todo Please implement! } void kernels::aderdg::generic::fortran::volumeUnknownsProlongation(double* luhFine, const double* luhCoarse, const int coarseGridLevel, const int fineGridLevel, const tarch::la::Vector<DIMENSIONS, int>& subcellIndex, const int numberOfVariables, const int basisSize){ // @todo Please implement! } void kernels::aderdg::generic::fortran::volumeUnknownsRestriction(double* luhCoarse, const double* luhFine, const int coarseGridLevel, const int fineGridLevel, const tarch::la::Vector<DIMENSIONS, int>& subcellIndex, const int numberOfVariables, const int basisSize){ // @todo Please implement! } #endif
42.555556
87
0.56658
yungcheeze
21a16fb2c835e0de58984b52ed7b0ce6a9144ce8
6,168
cpp
C++
source/function.cpp
Venkster123/Zhetapi
9a034392c06733c57d892afde300e90c4b7036f9
[ "MIT" ]
27
2020-06-05T15:39:31.000Z
2022-01-07T05:03:01.000Z
source/function.cpp
Venkster123/Zhetapi
9a034392c06733c57d892afde300e90c4b7036f9
[ "MIT" ]
1
2021-02-12T04:51:40.000Z
2021-02-12T04:51:40.000Z
source/function.cpp
Venkster123/Zhetapi
9a034392c06733c57d892afde300e90c4b7036f9
[ "MIT" ]
4
2021-02-12T04:39:55.000Z
2021-11-15T08:00:06.000Z
#include "../engine/function.hpp" #include "../engine/engine.hpp" #include "../engine/core/operation_base.hpp" namespace zhetapi { // Static variables Engine *Function::shared_context = new Engine(); double Function::h = 0.0001; // Methods // TODO: use macro ZHP_TOKEN_METHOD(ftn_deriv_method) { // TODO: remove assert (and use a special one that throw mistch errs) assert(args.size() == 0); Function *fptr = dynamic_cast <Function *> (tptr); // Differentiate on first arg by default return fptr->differentiate(fptr->_params[0]).copy(); } MethodTable Function::mtable ({ {"derivative", {&ftn_deriv_method, "NA"}} }); // Constructors Function::Function() : _threads(1), Token(&Function::mtable) {} Function::Function(const char *str) : Function(std::string(str)) {} // TODO: Take an Engine as an input as well: there is no need to delay rvalue resolution Function::Function(const std::string &str, Engine *context) : _threads(1), Token(&Function::mtable) { // TODO: Remove this (duplication) std::string pack; std::string tmp; size_t count; size_t index; size_t start; size_t end; size_t i; bool valid; bool sb; bool eb; count = 0; valid = false; sb = false; eb = false; // Split string into expression and symbols for (i = 0; i < str.length(); i++) { if (str[i] == '=') { valid = true; index = i; ++count; } } if (!valid || count != 1) throw invalid_definition(); _symbol = str.substr(0, index); // Determine parameters' symbols for (start = -1, i = 0; i < _symbol.length(); i++) { if (str[i] == '(' && start == -1) { start = i; sb = true; } if (str[i] == ')') { end = i; eb = true; } } if (!sb || !eb) throw invalid_definition(); pack = _symbol.substr(start + 1, end - start - 1); for (i = 0; i < pack.length(); i++) { if (pack[i] == ',' && !tmp.empty()) { _params.push_back(tmp); tmp.clear(); } else if (!isspace(pack[i])) { tmp += pack[i]; } } if (!tmp.empty()) _params.push_back(tmp); // Determine function's symbol _symbol = _symbol.substr(0, start); // Construct the tree manager _manager = node_manager(context, str.substr(++index), _params); /* using namespace std; cout << "FUNCTION manager:" << endl; print(); */ } // Member-wise construction (TODO: change to Args) Function::Function(const std::string &symbol, const std::vector <std::string> &params, const node_manager &manager) : _symbol(symbol), _params(params), _manager(manager), _threads(1), Token(&Function::mtable) {} Function::Function(const Function &other) : _symbol(other._symbol), _params(other._params), _manager(other._manager), _threads(1), Token(&Function::mtable) {} // Getters bool Function::is_variable(const std::string &str) const { return std::find(_params.begin(), _params.end(), str) != _params.end(); } std::string &Function::symbol() { return _symbol; } const std::string Function::symbol() const { return _symbol; } void Function::set_threads(size_t threads) { _threads = threads; } // Computational utilities Token *Function::evaluate(Engine *ctx, const std::vector<Token *> &ins) { // TODO: refactor params to args // TODO: create an assert macro (or constexpr) thats throws if (ins.size() != _params.size()) throw Functor::insufficient_args(ins.size(), _params.size()); return _manager.substitute_and_compute(ctx, ins); } // TODO: useless Token *Function::compute(const std::vector <Token *> &ins, Engine *ctx) { if (ins.size() != _params.size()) throw Functor::insufficient_args(ins.size(), _params.size()); return _manager.substitute_and_compute(ctx, ins); } // TODO: remove this (no user is going to use this) Token *Function::operator()(const std::vector <Token *> &toks, Engine *context) { return compute(toks, context); } template <class ... A> Token *Function::derivative(const std::string &str, A ... args) { std::vector <Token *> Tokens; gather(Tokens, args...); assert(Tokens.size() == _params.size()); size_t i = index(str); assert(i != -1); // Right Token *right; Tokens[i] = detail::compute("+", {Tokens[i], new Operand <double> (h)}); for (size_t k = 0; k < Tokens.size(); k++) { if (k != i) Tokens[k] = Tokens[k]->copy(); } right = _manager.substitute_and_compute(shared_context, Tokens); // Left Token *left; Tokens[i] = detail::compute("-", {Tokens[i], new Operand <double> (2.0 * h)}); for (size_t k = 0; k < Tokens.size(); k++) { if (k != i) Tokens[k] = Tokens[k]->copy(); } left = _manager.substitute_and_compute(shared_context, Tokens); // Compute Token *diff = detail::compute("-", {right, left}); diff = detail::compute("/", {diff, new Operand <double> (2.0 * h)}); return diff; } Function Function::differentiate(const std::string &str) const { // Improve naming later std::string name = "d" + _symbol + "/d" + str; node_manager dm = _manager; dm.differentiate(str); Function df = Function(name, _params, dm); return df; } // Virtual functions Token::type Function::caller() const { return Token::ftn; } std::string Function::dbg_str() const { return display(); } Token *Function::copy() const { return new Function(*this); } bool Function::operator==(Token *tptr) const { Function *ftn = dynamic_cast <Function *> (tptr); if (!ftn) return false; return ftn->_symbol == _symbol; } // Printing utilities void Function::print() const { _manager.print(); } std::string Function::display() const { std::string str = _symbol + "("; size_t n = _params.size(); for (size_t i = 0; i < n; i++) { str += _params[i]; if (i < n - 1) str += ", "; } str += ") = " + _manager.display(); return str; } std::ostream &operator<<(std::ostream &os, const Function &ftr) { os << ftr.display(); return os; } // Comparing bool operator<(const Function &a, const Function &b) { return a.symbol() < b.symbol(); } bool operator>(const Function &a, const Function &b) { return a.symbol() > b.symbol(); } size_t Function::index(const std::string &str) const { auto itr = std::find(_params.begin(), _params.end(), str); if (itr == _params.end()) return -1; return std::distance(_params.begin(), itr); } }
19.769231
88
0.645266
Venkster123
21a19ad1a17a1917353ab7501f275153fac025e1
20,888
cc
C++
src/benchmark.cc
mtrofin/benchmark
99cfbdd53357477fb328aa54d271178911bd2a84
[ "Apache-2.0" ]
null
null
null
src/benchmark.cc
mtrofin/benchmark
99cfbdd53357477fb328aa54d271178911bd2a84
[ "Apache-2.0" ]
null
null
null
src/benchmark.cc
mtrofin/benchmark
99cfbdd53357477fb328aa54d271178911bd2a84
[ "Apache-2.0" ]
null
null
null
// Copyright 2015 Google 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 "benchmark/benchmark.h" #include "benchmark_api_internal.h" #include "benchmark_runner.h" #include "internal_macros.h" #ifndef BENCHMARK_OS_WINDOWS #ifndef BENCHMARK_OS_FUCHSIA #include <sys/resource.h> #endif #include <sys/time.h> #include <unistd.h> #endif #include <algorithm> #include <atomic> #include <condition_variable> #include <cstdio> #include <cstdlib> #include <fstream> #include <iostream> #include <limits> #include <map> #include <memory> #include <random> #include <string> #include <thread> #include <utility> #include "absl/flags/flag.h" #include "absl/flags/parse.h" #include "absl/synchronization/mutex.h" #include "check.h" #include "colorprint.h" #include "commandlineflags.h" #include "complexity.h" #include "counter.h" #include "internal_macros.h" #include "log.h" #include "mutex.h" #include "perf_counters.h" #include "re.h" #include "statistics.h" #include "string_util.h" #include "thread_manager.h" #include "thread_timer.h" ABSL_FLAG( bool, benchmark_list_tests, false, "Print a list of benchmarks. This option overrides all other options."); ABSL_FLAG(std::string, benchmark_filter, ".", "A regular expression that specifies the set of benchmarks to " "execute. If this flag is empty, or if this flag is the string " "\"all\", all benchmarks linked into the binary are run."); ABSL_FLAG( double, benchmark_min_time, 0.5, "Minimum number of seconds we should run benchmark before results are " "considered significant. For cpu-time based tests, this is the lower " "bound on the total cpu time used by all threads that make up the test. " "For real-time based tests, this is the lower bound on the elapsed time of " "the benchmark execution, regardless of number of threads."); ABSL_FLAG(int32_t, benchmark_repetitions, 1, "The number of runs of each benchmark. If greater than 1, the mean " "and standard deviation of the runs will be reported."); ABSL_FLAG( bool, benchmark_enable_random_interleaving, false, "If set, enable random interleaving of repetitions of all benchmarks. See " "http://github.com/google/benchmark/issues/1051 for details."); ABSL_FLAG(bool, benchmark_report_aggregates_only, false, "Report the result of each benchmark repetitions. When 'true' is " "specified only the mean, standard deviation, and other statistics " "are reported for repeated benchmarks. Affects all reporters."); ABSL_FLAG( bool, benchmark_display_aggregates_only, false, "Display the result of each benchmark repetitions. When 'true' is " "specified only the mean, standard deviation, and other statistics are " "displayed for repeated benchmarks. Unlike " "benchmark_report_aggregates_only, only affects the display reporter, but " "*NOT* file reporter, which will still contain all the output."); ABSL_FLAG(std::string, benchmark_format, "console", "The format to use for console output. Valid values are 'console', " "'json', or 'csv'."); ABSL_FLAG(std::string, benchmark_out_format, "json", "The format to use for file output. Valid values are 'console', " "'json', or 'csv'."); ABSL_FLAG(std::string, benchmark_out, "", "The file to write additional output to."); ABSL_FLAG(std::string, benchmark_color, "auto", "Whether to use colors in the output. Valid values: 'true'/'yes'/1, " "'false'/'no'/0, and 'auto'. 'auto' means to use colors if the " "output is being sent to a terminal and the TERM environment " "variable is set to a terminal type that supports colors."); ABSL_FLAG( bool, benchmark_counters_tabular, false, "Whether to use tabular format when printing user counters to the console. " "Valid values: 'true'/'yes'/1, 'false'/'no'/0. Defaults to false."); ABSL_FLAG(int32_t, v, 0, "The level of verbose logging to output."); ABSL_FLAG(std::vector<std::string>, benchmark_perf_counters, {}, "List of additional perf counters to collect, in libpfm format. For " "more information about libpfm: " "https://man7.org/linux/man-pages/man3/libpfm.3.html"); ABSL_FLAG(std::string, benchmark_context, "", "Extra context to include in the output formatted as comma-separated " "key-value pairs. Kept internal as it's only used for parsing from " "env/command line."); namespace benchmark { namespace internal { std::map<std::string, std::string>* global_context = nullptr; // FIXME: wouldn't LTO mess this up? void UseCharPointer(char const volatile*) {} } // namespace internal State::State(IterationCount max_iters, const std::vector<int64_t>& ranges, int thread_i, int n_threads, internal::ThreadTimer* timer, internal::ThreadManager* manager, internal::PerfCountersMeasurement* perf_counters_measurement) : total_iterations_(0), batch_leftover_(0), max_iterations(max_iters), started_(false), finished_(false), error_occurred_(false), range_(ranges), complexity_n_(0), counters(), thread_index_(thread_i), threads_(n_threads), timer_(timer), manager_(manager), perf_counters_measurement_(perf_counters_measurement) { BM_CHECK(max_iterations != 0) << "At least one iteration must be run"; BM_CHECK_LT(thread_index_, threads_) << "thread_index must be less than threads"; // Note: The use of offsetof below is technically undefined until C++17 // because State is not a standard layout type. However, all compilers // currently provide well-defined behavior as an extension (which is // demonstrated since constexpr evaluation must diagnose all undefined // behavior). However, GCC and Clang also warn about this use of offsetof, // which must be suppressed. #if defined(__INTEL_COMPILER) #pragma warning push #pragma warning(disable : 1875) #elif defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Winvalid-offsetof" #endif // Offset tests to ensure commonly accessed data is on the first cache line. const int cache_line_size = 64; static_assert(offsetof(State, error_occurred_) <= (cache_line_size - sizeof(error_occurred_)), ""); #if defined(__INTEL_COMPILER) #pragma warning pop #elif defined(__GNUC__) #pragma GCC diagnostic pop #endif } void State::PauseTiming() { // Add in time accumulated so far BM_CHECK(started_ && !finished_ && !error_occurred_); timer_->StopTimer(); if (perf_counters_measurement_) { auto measurements = perf_counters_measurement_->StopAndGetMeasurements(); for (const auto& name_and_measurement : measurements) { auto name = name_and_measurement.first; auto measurement = name_and_measurement.second; BM_CHECK_EQ(counters[name], 0.0); counters[name] = Counter(measurement, Counter::kAvgIterations); } } } void State::ResumeTiming() { BM_CHECK(started_ && !finished_ && !error_occurred_); timer_->StartTimer(); if (perf_counters_measurement_) { perf_counters_measurement_->Start(); } } void State::SkipWithError(const char* msg) { BM_CHECK(msg); error_occurred_ = true; { MutexLock l(manager_->GetBenchmarkMutex()); if (manager_->results.has_error_ == false) { manager_->results.error_message_ = msg; manager_->results.has_error_ = true; } } total_iterations_ = 0; if (timer_->running()) timer_->StopTimer(); } void State::SetIterationTime(double seconds) { timer_->SetIterationTime(seconds); } void State::SetLabel(const char* label) { MutexLock l(manager_->GetBenchmarkMutex()); manager_->results.report_label_ = label; } void State::StartKeepRunning() { BM_CHECK(!started_ && !finished_); started_ = true; total_iterations_ = error_occurred_ ? 0 : max_iterations; manager_->StartStopBarrier(); if (!error_occurred_) ResumeTiming(); } void State::FinishKeepRunning() { BM_CHECK(started_ && (!finished_ || error_occurred_)); if (!error_occurred_) { PauseTiming(); } // Total iterations has now wrapped around past 0. Fix this. total_iterations_ = 0; finished_ = true; manager_->StartStopBarrier(); } namespace internal { namespace { // Flushes streams after invoking reporter methods that write to them. This // ensures users get timely updates even when streams are not line-buffered. void FlushStreams(BenchmarkReporter* reporter) { if (!reporter) return; std::flush(reporter->GetOutputStream()); std::flush(reporter->GetErrorStream()); } // Reports in both display and file reporters. void Report(BenchmarkReporter* display_reporter, BenchmarkReporter* file_reporter, const RunResults& run_results) { auto report_one = [](BenchmarkReporter* reporter, bool aggregates_only, const RunResults& results) { assert(reporter); // If there are no aggregates, do output non-aggregates. aggregates_only &= !results.aggregates_only.empty(); if (!aggregates_only) reporter->ReportRuns(results.non_aggregates); if (!results.aggregates_only.empty()) reporter->ReportRuns(results.aggregates_only); }; report_one(display_reporter, run_results.display_report_aggregates_only, run_results); if (file_reporter) report_one(file_reporter, run_results.file_report_aggregates_only, run_results); FlushStreams(display_reporter); FlushStreams(file_reporter); } void RunBenchmarks(const std::vector<BenchmarkInstance>& benchmarks, BenchmarkReporter* display_reporter, BenchmarkReporter* file_reporter) { // Note the file_reporter can be null. BM_CHECK(display_reporter != nullptr); // Determine the width of the name field using a minimum width of 10. bool might_have_aggregates = absl::GetFlag(FLAGS_benchmark_repetitions) > 1; size_t name_field_width = 10; size_t stat_field_width = 0; for (const BenchmarkInstance& benchmark : benchmarks) { name_field_width = std::max<size_t>(name_field_width, benchmark.name().str().size()); might_have_aggregates |= benchmark.repetitions() > 1; for (const auto& Stat : benchmark.statistics()) stat_field_width = std::max<size_t>(stat_field_width, Stat.name_.size()); } if (might_have_aggregates) name_field_width += 1 + stat_field_width; // Print header here BenchmarkReporter::Context context; context.name_field_width = name_field_width; // Keep track of running times of all instances of each benchmark family. std::map<int /*family_index*/, BenchmarkReporter::PerFamilyRunReports> per_family_reports; if (display_reporter->ReportContext(context) && (!file_reporter || file_reporter->ReportContext(context))) { FlushStreams(display_reporter); FlushStreams(file_reporter); size_t num_repetitions_total = 0; std::vector<internal::BenchmarkRunner> runners; runners.reserve(benchmarks.size()); for (const BenchmarkInstance& benchmark : benchmarks) { BenchmarkReporter::PerFamilyRunReports* reports_for_family = nullptr; if (benchmark.complexity() != oNone) reports_for_family = &per_family_reports[benchmark.family_index()]; runners.emplace_back(benchmark, reports_for_family); int num_repeats_of_this_instance = runners.back().GetNumRepeats(); num_repetitions_total += num_repeats_of_this_instance; if (reports_for_family) reports_for_family->num_runs_total += num_repeats_of_this_instance; } assert(runners.size() == benchmarks.size() && "Unexpected runner count."); std::vector<size_t> repetition_indices; repetition_indices.reserve(num_repetitions_total); for (size_t runner_index = 0, num_runners = runners.size(); runner_index != num_runners; ++runner_index) { const internal::BenchmarkRunner& runner = runners[runner_index]; std::fill_n(std::back_inserter(repetition_indices), runner.GetNumRepeats(), runner_index); } assert(repetition_indices.size() == num_repetitions_total && "Unexpected number of repetition indexes."); if (absl::GetFlag(FLAGS_benchmark_enable_random_interleaving)) { std::random_device rd; std::mt19937 g(rd()); std::shuffle(repetition_indices.begin(), repetition_indices.end(), g); } for (size_t repetition_index : repetition_indices) { internal::BenchmarkRunner& runner = runners[repetition_index]; runner.DoOneRepetition(); if (runner.HasRepeatsRemaining()) continue; // FIXME: report each repetition separately, not all of them in bulk. RunResults run_results = runner.GetResults(); // Maybe calculate complexity report if (const auto* reports_for_family = runner.GetReportsForFamily()) { if (reports_for_family->num_runs_done == reports_for_family->num_runs_total) { auto additional_run_stats = ComputeBigO(reports_for_family->Runs); run_results.aggregates_only.insert(run_results.aggregates_only.end(), additional_run_stats.begin(), additional_run_stats.end()); per_family_reports.erase( (int)reports_for_family->Runs.front().family_index); } } Report(display_reporter, file_reporter, run_results); } } display_reporter->Finalize(); if (file_reporter) file_reporter->Finalize(); FlushStreams(display_reporter); FlushStreams(file_reporter); } // Disable deprecated warnings temporarily because we need to reference // CSVReporter but don't want to trigger -Werror=-Wdeprecated-declarations #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif std::unique_ptr<BenchmarkReporter> CreateReporter( std::string const&& name, ConsoleReporter::OutputOptions output_opts) { typedef std::unique_ptr<BenchmarkReporter> PtrType; if (name == "console") { return PtrType(new ConsoleReporter(output_opts)); } else if (name == "json") { return PtrType(new JSONReporter); } else if (name == "csv") { return PtrType(new CSVReporter); } else { std::cerr << "Unexpected format: '" << name << "'\n"; std::exit(1); } } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif } // end namespace bool IsZero(double n) { return std::abs(n) < std::numeric_limits<double>::epsilon(); } ConsoleReporter::OutputOptions GetOutputOptions(bool force_no_color) { int output_opts = ConsoleReporter::OO_Defaults; auto is_benchmark_color = [force_no_color]() -> bool { if (force_no_color) { return false; } if (absl::GetFlag(FLAGS_benchmark_color) == "auto") { return IsColorTerminal(); } return IsTruthyFlagValue(absl::GetFlag(FLAGS_benchmark_color)); }; if (is_benchmark_color()) { output_opts |= ConsoleReporter::OO_Color; } else { output_opts &= ~ConsoleReporter::OO_Color; } if (absl::GetFlag(FLAGS_benchmark_counters_tabular)) { output_opts |= ConsoleReporter::OO_Tabular; } else { output_opts &= ~ConsoleReporter::OO_Tabular; } return static_cast<ConsoleReporter::OutputOptions>(output_opts); } } // end namespace internal size_t RunSpecifiedBenchmarks() { return RunSpecifiedBenchmarks(nullptr, nullptr); } size_t RunSpecifiedBenchmarks(BenchmarkReporter* display_reporter) { return RunSpecifiedBenchmarks(display_reporter, nullptr); } size_t RunSpecifiedBenchmarks(BenchmarkReporter* display_reporter, BenchmarkReporter* file_reporter) { std::string spec = absl::GetFlag(FLAGS_benchmark_filter); if (spec.empty() || spec == "all") spec = "."; // Regexp that matches all benchmarks // Setup the reporters std::ofstream output_file; std::unique_ptr<BenchmarkReporter> default_display_reporter; std::unique_ptr<BenchmarkReporter> default_file_reporter; if (!display_reporter) { default_display_reporter = internal::CreateReporter( absl::GetFlag(FLAGS_benchmark_format), internal::GetOutputOptions()); display_reporter = default_display_reporter.get(); } auto& Out = display_reporter->GetOutputStream(); auto& Err = display_reporter->GetErrorStream(); const std::string fname = absl::GetFlag(FLAGS_benchmark_out); if (fname.empty() && file_reporter) { Err << "A custom file reporter was provided but " "--benchmark_out=<file> was not specified." << std::endl; std::exit(1); } if (!fname.empty()) { output_file.open(fname); if (!output_file.is_open()) { Err << "invalid file name: '" << fname << "'" << std::endl; std::exit(1); } if (!file_reporter) { default_file_reporter = internal::CreateReporter( absl::GetFlag(FLAGS_benchmark_out_format), ConsoleReporter::OO_None); file_reporter = default_file_reporter.get(); } file_reporter->SetOutputStream(&output_file); file_reporter->SetErrorStream(&output_file); } std::vector<internal::BenchmarkInstance> benchmarks; if (!FindBenchmarksInternal(spec, &benchmarks, &Err)) return 0; if (benchmarks.empty()) { Err << "Failed to match any benchmarks against regex: " << spec << "\n"; return 0; } if (absl::GetFlag(FLAGS_benchmark_list_tests)) { for (auto const& benchmark : benchmarks) Out << benchmark.name().str() << "\n"; } else { internal::RunBenchmarks(benchmarks, display_reporter, file_reporter); } return benchmarks.size(); } void RegisterMemoryManager(MemoryManager* manager) { internal::memory_manager = manager; } void AddCustomContext(const std::string& key, const std::string& value) { if (internal::global_context == nullptr) { internal::global_context = new std::map<std::string, std::string>(); } if (!internal::global_context->emplace(key, value).second) { std::cerr << "Failed to add custom context \"" << key << "\" as it already " << "exists with value \"" << value << "\"\n"; } } namespace internal { void PrintUsageAndExit() { fprintf(stdout, "benchmark" " [--benchmark_list_tests={true|false}]\n" " [--benchmark_filter=<regex>]\n" " [--benchmark_min_time=<min_time>]\n" " [--benchmark_repetitions=<num_repetitions>]\n" " [--benchmark_enable_random_interleaving={true|false}]\n" " [--benchmark_report_aggregates_only={true|false}]\n" " [--benchmark_display_aggregates_only={true|false}]\n" " [--benchmark_format=<console|json|csv>]\n" " [--benchmark_out=<filename>]\n" " [--benchmark_out_format=<json|console|csv>]\n" " [--benchmark_color={auto|true|false}]\n" " [--benchmark_counters_tabular={true|false}]\n" " [--benchmark_perf_counters=<counter>,...]\n" " [--benchmark_context=<key>=<value>,...]\n" " [--v=<verbosity>]\n"); exit(0); } void ValidateCommandLineFlags() { for (auto const& flag : {absl::GetFlag(FLAGS_benchmark_format), absl::GetFlag(FLAGS_benchmark_out_format)}) { if (flag != "console" && flag != "json" && flag != "csv") { PrintUsageAndExit(); } } if (absl::GetFlag(FLAGS_benchmark_color).empty()) { PrintUsageAndExit(); } for (const auto& kv : benchmark::KvPairsFromEnv( absl::GetFlag(FLAGS_benchmark_context).c_str(), {})) { AddCustomContext(kv.first, kv.second); } } int InitializeStreams() { static std::ios_base::Init init; return 0; } } // end namespace internal std::vector<char*> Initialize(int* argc, char** argv) { using namespace benchmark; BenchmarkReporter::Context::executable_name = (argc && *argc > 0) ? argv[0] : "unknown"; auto unparsed = absl::ParseCommandLine(*argc, argv); *argc = static_cast<int>(unparsed.size()); benchmark::internal::ValidateCommandLineFlags(); internal::LogLevel() = absl::GetFlag(FLAGS_v); return unparsed; } void Shutdown() { delete internal::global_context; } } // end namespace benchmark
35.463497
80
0.69121
mtrofin
426f8c942f3ef9d9433a3321aedf5ad1d7a5757f
1,819
cpp
C++
ibp_external__libtommatch_set01__bn_mp_clamp.cpp
dmitry-lipetsk/libtommath-for-ibprovider--set01
b7b8e7cf76bd0b2d265d0c31a99836a3b4bad882
[ "WTFPL" ]
null
null
null
ibp_external__libtommatch_set01__bn_mp_clamp.cpp
dmitry-lipetsk/libtommath-for-ibprovider--set01
b7b8e7cf76bd0b2d265d0c31a99836a3b4bad882
[ "WTFPL" ]
null
null
null
ibp_external__libtommatch_set01__bn_mp_clamp.cpp
dmitry-lipetsk/libtommath-for-ibprovider--set01
b7b8e7cf76bd0b2d265d0c31a99836a3b4bad882
[ "WTFPL" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// #include <_pch_.h> #pragma hdrstop #include "source/external/libtommath/set01/ibp_external__libtommatch_set01__tommath_private.h" namespace ibp{namespace external{namespace libtommath{namespace set01{ //////////////////////////////////////////////////////////////////////////////// /* LibTomMath, multiple-precision integer library -- Tom St Denis * * LibTomMath is a library that provides multiple-precision * integer arithmetic as well as number theoretic functionality. * * The library was designed directly after the MPI library by * Michael Fromberger but has been written from scratch with * additional optimizations in place. * * The library is free for all purposes without any express * guarantee it works. * * Tom St Denis, tomstdenis@gmail.com, http://libtom.org */ /* trim unused digits * * This is used to ensure that leading zero digits are * trimed and the leading "used" digit will be non-zero * Typically very fast. Also fixes the sign if there * are no more leading digits */ void mp_clamp(mp_int* const a) { DEBUG_CODE(mp_debug__check_int__light(a);) // decrease used while the most significant digit is zero. const mp_digit* p=(a->dp + a->used); for(;;) { if(p == a->dp) { a->used = 0; a->sign = MP_ZPOS; DEBUG_CODE(mp_debug__check_int__total(a);) return; }//if const mp_digit* const newP = (p - 1); if((*newP) != 0) break; p = newP; }//for[ever] assert(p != a->dp); assert(p >= a->dp); assert(p <= (a->dp + a->used)); a->used = (p - a->dp); DEBUG_CODE(mp_debug__check_int__total(a);) }//mp_clamp //////////////////////////////////////////////////////////////////////////////// }/*nms set01*/}/*nms libtommath*/}/*nms external*/}/*nms ibp*/
24.581081
94
0.601979
dmitry-lipetsk
4272eab0047a8e82ba1850062b8318565e9f0b9d
7,231
cpp
C++
live/src/v20180801/model/CreateLiveRecordRequest.cpp
li5ch/tencentcloud-sdk-cpp
12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4
[ "Apache-2.0" ]
null
null
null
live/src/v20180801/model/CreateLiveRecordRequest.cpp
li5ch/tencentcloud-sdk-cpp
12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4
[ "Apache-2.0" ]
null
null
null
live/src/v20180801/model/CreateLiveRecordRequest.cpp
li5ch/tencentcloud-sdk-cpp
12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/live/v20180801/model/CreateLiveRecordRequest.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using namespace TencentCloud::Live::V20180801::Model; using namespace rapidjson; using namespace std; CreateLiveRecordRequest::CreateLiveRecordRequest() : m_streamNameHasBeenSet(false), m_appNameHasBeenSet(false), m_domainNameHasBeenSet(false), m_startTimeHasBeenSet(false), m_endTimeHasBeenSet(false), m_recordTypeHasBeenSet(false), m_fileFormatHasBeenSet(false), m_highlightHasBeenSet(false), m_mixStreamHasBeenSet(false), m_streamParamHasBeenSet(false) { } string CreateLiveRecordRequest::ToJsonString() const { Document d; d.SetObject(); Document::AllocatorType& allocator = d.GetAllocator(); if (m_streamNameHasBeenSet) { Value iKey(kStringType); string key = "StreamName"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, Value(m_streamName.c_str(), allocator).Move(), allocator); } if (m_appNameHasBeenSet) { Value iKey(kStringType); string key = "AppName"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, Value(m_appName.c_str(), allocator).Move(), allocator); } if (m_domainNameHasBeenSet) { Value iKey(kStringType); string key = "DomainName"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, Value(m_domainName.c_str(), allocator).Move(), allocator); } if (m_startTimeHasBeenSet) { Value iKey(kStringType); string key = "StartTime"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, Value(m_startTime.c_str(), allocator).Move(), allocator); } if (m_endTimeHasBeenSet) { Value iKey(kStringType); string key = "EndTime"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, Value(m_endTime.c_str(), allocator).Move(), allocator); } if (m_recordTypeHasBeenSet) { Value iKey(kStringType); string key = "RecordType"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, Value(m_recordType.c_str(), allocator).Move(), allocator); } if (m_fileFormatHasBeenSet) { Value iKey(kStringType); string key = "FileFormat"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, Value(m_fileFormat.c_str(), allocator).Move(), allocator); } if (m_highlightHasBeenSet) { Value iKey(kStringType); string key = "Highlight"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_highlight, allocator); } if (m_mixStreamHasBeenSet) { Value iKey(kStringType); string key = "MixStream"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_mixStream, allocator); } if (m_streamParamHasBeenSet) { Value iKey(kStringType); string key = "StreamParam"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, Value(m_streamParam.c_str(), allocator).Move(), allocator); } StringBuffer buffer; Writer<StringBuffer> writer(buffer); d.Accept(writer); return buffer.GetString(); } string CreateLiveRecordRequest::GetStreamName() const { return m_streamName; } void CreateLiveRecordRequest::SetStreamName(const string& _streamName) { m_streamName = _streamName; m_streamNameHasBeenSet = true; } bool CreateLiveRecordRequest::StreamNameHasBeenSet() const { return m_streamNameHasBeenSet; } string CreateLiveRecordRequest::GetAppName() const { return m_appName; } void CreateLiveRecordRequest::SetAppName(const string& _appName) { m_appName = _appName; m_appNameHasBeenSet = true; } bool CreateLiveRecordRequest::AppNameHasBeenSet() const { return m_appNameHasBeenSet; } string CreateLiveRecordRequest::GetDomainName() const { return m_domainName; } void CreateLiveRecordRequest::SetDomainName(const string& _domainName) { m_domainName = _domainName; m_domainNameHasBeenSet = true; } bool CreateLiveRecordRequest::DomainNameHasBeenSet() const { return m_domainNameHasBeenSet; } string CreateLiveRecordRequest::GetStartTime() const { return m_startTime; } void CreateLiveRecordRequest::SetStartTime(const string& _startTime) { m_startTime = _startTime; m_startTimeHasBeenSet = true; } bool CreateLiveRecordRequest::StartTimeHasBeenSet() const { return m_startTimeHasBeenSet; } string CreateLiveRecordRequest::GetEndTime() const { return m_endTime; } void CreateLiveRecordRequest::SetEndTime(const string& _endTime) { m_endTime = _endTime; m_endTimeHasBeenSet = true; } bool CreateLiveRecordRequest::EndTimeHasBeenSet() const { return m_endTimeHasBeenSet; } string CreateLiveRecordRequest::GetRecordType() const { return m_recordType; } void CreateLiveRecordRequest::SetRecordType(const string& _recordType) { m_recordType = _recordType; m_recordTypeHasBeenSet = true; } bool CreateLiveRecordRequest::RecordTypeHasBeenSet() const { return m_recordTypeHasBeenSet; } string CreateLiveRecordRequest::GetFileFormat() const { return m_fileFormat; } void CreateLiveRecordRequest::SetFileFormat(const string& _fileFormat) { m_fileFormat = _fileFormat; m_fileFormatHasBeenSet = true; } bool CreateLiveRecordRequest::FileFormatHasBeenSet() const { return m_fileFormatHasBeenSet; } int64_t CreateLiveRecordRequest::GetHighlight() const { return m_highlight; } void CreateLiveRecordRequest::SetHighlight(const int64_t& _highlight) { m_highlight = _highlight; m_highlightHasBeenSet = true; } bool CreateLiveRecordRequest::HighlightHasBeenSet() const { return m_highlightHasBeenSet; } int64_t CreateLiveRecordRequest::GetMixStream() const { return m_mixStream; } void CreateLiveRecordRequest::SetMixStream(const int64_t& _mixStream) { m_mixStream = _mixStream; m_mixStreamHasBeenSet = true; } bool CreateLiveRecordRequest::MixStreamHasBeenSet() const { return m_mixStreamHasBeenSet; } string CreateLiveRecordRequest::GetStreamParam() const { return m_streamParam; } void CreateLiveRecordRequest::SetStreamParam(const string& _streamParam) { m_streamParam = _streamParam; m_streamParamHasBeenSet = true; } bool CreateLiveRecordRequest::StreamParamHasBeenSet() const { return m_streamParamHasBeenSet; }
24.429054
85
0.718296
li5ch
427418928443107ac12ac31e6e1e5edd3f7a20cc
940
cpp
C++
datasets/github_cpp_10/10/153.cpp
yijunyu/demo-fast
11c0c84081a3181494b9c469bda42a313c457ad2
[ "BSD-2-Clause" ]
1
2019-05-03T19:27:45.000Z
2019-05-03T19:27:45.000Z
datasets/github_cpp_10/10/153.cpp
yijunyu/demo-vscode-fast
11c0c84081a3181494b9c469bda42a313c457ad2
[ "BSD-2-Clause" ]
null
null
null
datasets/github_cpp_10/10/153.cpp
yijunyu/demo-vscode-fast
11c0c84081a3181494b9c469bda42a313c457ad2
[ "BSD-2-Clause" ]
null
null
null
/* * EditDistance.cpp * * Created on: Aug 11, 2015 * Author: user #include<iostream> #include<cstring> using namespace std; void editDistance(char X[],char Y[],int m,int n){ int edit[m+1][n+1]; int delcost,inscost,samecost; //Initialize table for(int i=0;i<=m;i++){ for(int j=0;j<=n;j++){ edit[i][j]=-1; } } for(int i=0;i<=m;i++){ edit[i][0]=i; } for(int j=0;j<=n;j++){ edit[0][j]=j; } for(int i=1;i<=m;i++){ for(int j=1;j<=n;j++){ delcost=edit[i-1][j]+1; inscost=edit[i][j-1]+1; samecost=edit[i-1][j-1]; samecost+=(X[i-1]!=Y[j-1]); edit[i][j]=min(delcost,min(inscost,samecost)); } } cout<<"Minimum no. of edits are "<<edit[m][n]<<endl; //Printing edit distance table for(int i=0;i<=m;i++){ for(int j=0;j<=n;j++){ cout<<edit[i][j]<<" "; } cout<<endl; } } int main(){ char X[]="SUNDAY"; char Y[]="SATURDAY"; editDistance(X,Y,strlen(X),strlen(Y)); } */
17.735849
53
0.544681
yijunyu
42760f70fcbb3e61191edeedac9efce62403ccca
18,364
hpp
C++
3rdparty/GPSTk/core/lib/GNSSEph/PackedNavBits.hpp
mfkiwl/ICE
e660d031bb1bcea664db1de4946fd8781be5b627
[ "MIT" ]
50
2019-10-12T01:22:20.000Z
2022-02-15T23:28:26.000Z
3rdparty/GPSTk/core/lib/GNSSEph/PackedNavBits.hpp
wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation
2f1ff054b7c5059da80bb3b2f80c05861a02cc36
[ "MIT" ]
null
null
null
3rdparty/GPSTk/core/lib/GNSSEph/PackedNavBits.hpp
wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation
2f1ff054b7c5059da80bb3b2f80c05861a02cc36
[ "MIT" ]
14
2019-11-05T01:50:29.000Z
2021-08-06T06:23:44.000Z
//============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 3.0 of the License, or // any later version. // // The GPSTk is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with GPSTk; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA // // Copyright 2004, The University of Texas at Austin // //============================================================================ //============================================================================ // //This software developed by Applied Research Laboratories at the University of //Texas at Austin, under contract to an agency or agencies within the U.S. //Department of Defense. The U.S. Government retains all rights to use, //duplicate, distribute, disclose, or release this software. // //Pursuant to DoD Directive 523024 // // DISTRIBUTION STATEMENT A: This software has been approved for public // release, distribution is unlimited. // //============================================================================= /** * @file PackedNavBits.hpp * Engineering units navigation message abstraction. */ #ifndef GPSTK_PACKEDNAVBITS_HPP #define GPSTK_PACKEDNAVBITS_HPP #include <vector> #include <cstddef> #include "gpstkplatform.h" //#include <stdint.h> #include <string> #include "ObsID.hpp" #include "NavID.hpp" #include "SatID.hpp" #include "CommonTime.hpp" #include "Exception.hpp" namespace gpstk { /// @ingroup ephemcalc //@{ class PackedNavBits { public: /// empty constructor PackedNavBits(); /// explicit constructor PackedNavBits(const SatID& satSysArg, const ObsID& obsIDArg, const CommonTime& transmitTimeArg); /// explicit constructor PackedNavBits(const SatID& satSysArg, const ObsID& obsIDArg, const std::string rxString, const CommonTime& transmitTimeArg); /// explicit constructor PackedNavBits(const SatID& satSysArg, const ObsID& obsIDArg, const NavID& navIDArg, const std::string rxString, const CommonTime& transmitTimeArg); PackedNavBits(const PackedNavBits& right); // Copy constructor //PackedNavBits& operator=(const PackedNavBits& right); // Copy assignment PackedNavBits* clone() const; void setSatID(const SatID& satSysArg); void setObsID(const ObsID& obsIDArg); void setNavID(const NavID& navIDArg); void setRxID(const std::string rxString); void setTime(const CommonTime& transmitTimeArg); void clearBits(); /* Returnst the satellite system ID for a particular SV */ SatID getsatSys() const; /* Returns Observation type, Carrier, and Tracking Code */ ObsID getobsID() const; /* Return navigation message ID */ NavID getNavID() const; /* Returns string defining the receiver that collected the data. NOTE: This was a late addition to PackedNavBits and may not be present in all applications */ std::string getRxID() const; /* Returns time of transmission from SV */ CommonTime getTransmitTime() const; /* Returns the number of bits */ size_t getNumBits() const; /* Output the contents of this class to the given stream. */ void dump(std::ostream& s = std::cout) const throw(); /*** UNPACKING FUNCTIONS *********************************/ /* Unpack an unsigned long integer */ unsigned long asUnsignedLong(const int startBit, const int numBits, const int scale ) const; /* Unpack a signed long integer */ long asLong(const int startBit, const int numBits, const int scale ) const; /* Unpack an unsigned double */ double asUnsignedDouble( const int startBit, const int numBits, const int power2) const; /* Unpack a signed double */ double asSignedDouble( const int startBit, const int numBits, const int power2) const; /* Unpack a double with units of semicircles */ double asDoubleSemiCircles( const int startBit, const int numBits, const int power2) const; /* Unpack a string */ std::string asString(const int startBit, const int numChars) const; // The following three methods were added to support // GLONASS sign/magnitude real values. // // Since GLONASS has no disjoint fields (at least not // up through ICD Edition 5.1) there are no methods // for unpacking disjoint-field sign/mag quantities. /* Unpack a sign/mag long */ long asSignMagLong(const int startBit, const int numBits, const int scale) const; /* Unpack a sign/mag double */ double asSignMagDouble( const int startBit, const int numBits, const int power2) const; /* Unpack a sign/mag double with units of semi-circles */ double asSignMagDoubleSemiCircles( const int startBit, const int numBits, const int power2) const; /* Unpack mehthods that join multiple disjoint navigation message areas as a single field NOTE: startBit1 is associated with the most significant section startBit2 is associated with the least significant section */ /* Unpack a split unsigned long integer */ unsigned long asUnsignedLong(const unsigned startBits[], const unsigned numBits[], const unsigned len, const int scale ) const; /* Unpack a signed long integer */ long asLong(const unsigned startBits[], const unsigned numBits[], const unsigned len, const int scale ) const; /* Unpack a split unsigned double */ double asUnsignedDouble( const unsigned startBits[], const unsigned numBits[], const unsigned len, const int power2) const; /* Unpack a split signed double */ double asSignedDouble( const unsigned startBits[], const unsigned numBits[], const unsigned len, const int power2) const; /* Unpack a split double with units of semicircles */ double asDoubleSemiCircles( const unsigned startBits[], const unsigned numBits[], const unsigned len, const int power2) const; bool asBool( const unsigned bitNum) const; /*** PACKING FUNCTIONS *********************************/ /* Pack an unsigned long integer */ void addUnsignedLong( const unsigned long value, const int numBits, const int scale ) throw(InvalidParameter); /* Pack a signed long integer */ void addLong( const long value, const int numBits, const int scale ) throw(InvalidParameter); /* Pack an unsigned double */ void addUnsignedDouble( const double value, const int numBits, const int power2) throw(InvalidParameter); /* Pack a signed double */ void addSignedDouble( const double value, const int numBits, const int power2) throw(InvalidParameter); /* Pack a double with units of semicircles */ void addDoubleSemiCircles( const double radians, const int numBits, const int power2) throw(InvalidParameter); /** * Pack a string. * Characters in String limited to those defined in IS-GPS-200 Section 20.3.3.5.1.8 * numChars represents number of chars (8 bits each) to add to PackedBits. * If numChars < length of String only, chars 1..numChars will be added. * If numChars > length of String, blanks will be added at the end. */ void addString(const std::string String, const int numChars) throw(InvalidParameter); void addPackedNavBits( const PackedNavBits &pnb) throw(InvalidParameter); /* * Output the packed bits as a set of 32 bit * hex values, four per line, without any * additional information. * Returns the number of bits in the object. */ int outputPackedBits(std::ostream& s = std::cout, const short numPerLine=4, const char delimiter = ' ', const short numBitsPerWord=32 ) const; /* * The equality operator insists that ALL the metadata * and the complete bit patterns must match. * However, there are frequently occaisions when only * a subset of the metadata need be checked, and sometimes * only certain set of bits. Therefore, operator==( ) is * supplemented by matchBits( ) and matchMetaData( ) */ bool operator==(const PackedNavBits& right) const; /* * There are frequently cases in which we want to know * if a pair of PackedNavBits objects are from the same * SV, but we might want to allow for different receivers * and/or different ObsIDs. Therefore, matchMetaData( ) * allows specification of the particular metadata items * that are to be checked using a bit-flag system. */ static const unsigned int mmTIME = 0x0001; // Check transmitTime static const unsigned int mmSAT = 0x0002; // Check SatID static const unsigned int mmOBS = 0x0004; // Check ObsID static const unsigned int mmRX = 0x0008; // Check Receiver ID static const unsigned int mmNAV = 0x0010; // Check NavID static const unsigned int mmALL = 0xFFFF; // Check ALL metadata static const unsigned int mmNONE = 0x0000; // NO metadata checks bool matchMetaData(const PackedNavBits& right, const unsigned flagBits=mmALL) const; /* * Return true if all bits between start and end are identical * between this object and right. Default is to compare all * bits. * * This method allows comparison of the "unchanging" data in * nav messages while avoiding the time tags. */ bool matchBits(const PackedNavBits& right, const short startBit=0, const short endBit=-1) const; /* * This is the most flexible of the matching methods. * A default of match(right) will yield the same * result as operator==( ). * However, the arguments provide the means to * specifically check bits sequences and/or * selectively check the metadata. */ bool match(const PackedNavBits& right, const short startBit=0, const short endBit=-1, const unsigned flagBits=mmALL) const; /* * This version was the original equality checker. As * first implemented, it checks ONLY SAT and OBS for * equality. Therefore, it is maintained with that * default functionality. That is to say, when * checkOverhead==true, the result is the same as a call * to matchBits(right,startBit,endBit, (mmSAT|mmOBS)). * * For clarity, it is suggested that new code use * operator==(), * matchMetaData(), and/or * matchBits( ) using explicit flags. * * This version was REMOVED because of ambiguity * in the signature. * * The checkOverhead option allows the user to ignore * the associated metadata. E.g. ObsID, SatID. * bool matchBits(const PackedNavBits& right, const short startBit=0, const short endBit=-1, const bool checkOverhead) const; */ /** * The less than operator is defined in order to support use * with the NavFilter classes. The idea is to provide a * "sort" for bits contained in the class. Matching strings * will fail both a < b and b < a; however, in the process * all matching strings can be sorted into sets and the * "winner" determined. */ bool operator<(const PackedNavBits& right) const; /** * Bitwise invert contents of this object. */ void invert( ); /** * Bit wise copy from another PackecNavBits. * None of the meta-data (transmit time, SatID, ObsID) * will be changed. * This method is intended for use between two * PackedNavBits objecst that are ALREADY the * same size (in bits). It will throw an * InvalidParameter exception if called using two * objects that are NOT the same size. * Yes, we could define a copy that would account * for the difference, but the pre-existing model * for PNB is that the bits_used variable records * the # of bits used as items are added to the end * of the bit array. I didn't want copyBits( ) * to confuse that model by modifying bits_used. */ void copyBits(const PackedNavBits& from, const short startBit=0, const short endBit=-1) throw(InvalidParameter); /** * This method is not typically used in production; however it * is used in test support. It assumes the PNB object is already * created and is already sized to hold at least (startBit+numBits) * bits. If this is not true, an exception is thrown. * It overwrites the data that is already present with * the provided value / scale. If value / scale is too large to * fit in numBits, then an exception is thrown. */ void insertUnsignedLong(const unsigned long value, const int startBit, const int numBits, const int scale=1 ) throw(InvalidParameter); /** * Reset number of bits */ void reset_num_bits(const int new_bits_used=0); /* Resize the vector holding the packed data. */ void trimsize(); /** * Raw bit input * This function is intended as a test-support function. * It assumes a string of the form * ### 0xABCDABCD 0xABCDABCD 0xABCDABCD * where * ### is the number of bits to expect in the remainder * of the line. * 0xABCDABCD are each 32-bit unsigned hex numbers, left * justified. The number of bits needs to match or * exceed ### * The function returns if the read is succeessful. * Otherwise,the function throws an exception */ void rawBitInput(const std::string inString ) throw(InvalidParameter); void setXmitCoerced(bool tf=true) {xMitCoerced=tf;} bool isXmitCoerced() const {return xMitCoerced;} private: SatID satSys; /**< System ID (based on RINEX defintions */ ObsID obsID; /**< Defines carrier and code tracked */ NavID navID; /**< Defines the navigation message tracked */ std::string rxID; /**< Defines the receiver that collected the data */ CommonTime transmitTime; /**< Time nav message is transmitted */ std::vector<bool> bits; /**< Holds the packed data */ int bits_used; bool xMitCoerced; /**< Used to indicate that the transmit time is NOT directly derived from the SOW in the message */ /** Unpack the bits */ uint64_t asUint64_t(const int startBit, const int numBits ) const throw(InvalidParameter); /** Pack the bits */ void addUint64_t( const uint64_t value, const int numBits ); /** Extend the sign bit for signed values */ int64_t SignExtend( const int startBit, const int numBits ) const; /** Scales doubles by their corresponding scale factor */ double ScaleValue( const double value, const int power2) const; }; // class PackedNavBits //@} std::ostream& operator<<(std::ostream& s, const PackedNavBits& pnb); } // namespace #endif
40.808889
92
0.556415
mfkiwl
42768a0b65d6e98e69e348eb23106fa73cff1c2a
741
cc
C++
base/at_exit.cc
Arpan-2109/caroline
23aba9ac9a35697c02358aeb88ed121d3d97a99c
[ "MIT" ]
1
2017-07-27T15:08:19.000Z
2017-07-27T15:08:19.000Z
base/at_exit.cc
Arpan-2109/caroline
23aba9ac9a35697c02358aeb88ed121d3d97a99c
[ "MIT" ]
null
null
null
base/at_exit.cc
Arpan-2109/caroline
23aba9ac9a35697c02358aeb88ed121d3d97a99c
[ "MIT" ]
1
2020-10-01T08:46:10.000Z
2020-10-01T08:46:10.000Z
// Copyright (c) 2014 The Caroline authors. All rights reserved. // Use of this source file is governed by a MIT license that can be found in the // LICENSE file. // @author Aleksandr Derbenev <13alexac@gmail.com> #include "base/at_exit.h" namespace base { AtExitManager* AtExitManager::instance_ = nullptr; AtExitManager::AtExitManager() : previous_instance_(instance_) { instance_ = this; } AtExitManager::~AtExitManager() { for (; !callbacks_.empty(); callbacks_.pop()) callbacks_.top()(); instance_ = previous_instance_; } // static AtExitManager* AtExitManager::GetInstance() { return instance_; } void AtExitManager::RegisterCallback(AtExitCallback callback) { callbacks_.push(callback); } } // namespace base
22.454545
80
0.735493
Arpan-2109
4278bd904a9c2025b90f02a445961a9ce574a0f6
20,942
cc
C++
content/renderer/loader/url_loader_client_impl_unittest.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
content/renderer/loader/url_loader_client_impl_unittest.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
content/renderer/loader/url_loader_client_impl_unittest.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// 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 "content/renderer/loader/url_loader_client_impl.h" #include <vector> #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "content/renderer/loader/navigation_response_override_parameters.h" #include "content/renderer/loader/resource_dispatcher.h" #include "content/renderer/loader/test_request_peer.h" #include "mojo/public/cpp/bindings/binding.h" #include "mojo/public/cpp/bindings/interface_ptr.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" #include "net/url_request/redirect_info.h" #include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h" #include "services/network/public/mojom/url_loader_factory.mojom.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h" namespace content { class URLLoaderClientImplTest : public ::testing::Test, public network::mojom::URLLoaderFactory { protected: URLLoaderClientImplTest() : dispatcher_(new ResourceDispatcher()) { request_id_ = dispatcher_->StartAsync( std::make_unique<network::ResourceRequest>(), 0, blink::scheduler::GetSingleThreadTaskRunnerForTesting(), TRAFFIC_ANNOTATION_FOR_TESTS, false, false, std::make_unique<TestRequestPeer>(dispatcher_.get(), &request_peer_context_), base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>(this), std::vector<std::unique_ptr<URLLoaderThrottle>>(), nullptr /* navigation_response_override_params */, nullptr /* continue_navigation_function */); request_peer_context_.request_id = request_id_; base::RunLoop().RunUntilIdle(); EXPECT_TRUE(url_loader_client_); } void TearDown() override { url_loader_client_ = nullptr; } void CreateLoaderAndStart(network::mojom::URLLoaderRequest request, int32_t routing_id, int32_t request_id, uint32_t options, const network::ResourceRequest& url_request, network::mojom::URLLoaderClientPtr client, const net::MutableNetworkTrafficAnnotationTag& traffic_annotation) override { url_loader_client_ = std::move(client); } void Clone(network::mojom::URLLoaderFactoryRequest request) override { NOTREACHED(); } static MojoCreateDataPipeOptions DataPipeOptions() { MojoCreateDataPipeOptions options; options.struct_size = sizeof(MojoCreateDataPipeOptions); options.flags = MOJO_CREATE_DATA_PIPE_FLAG_NONE; options.element_num_bytes = 1; options.capacity_num_bytes = 4096; return options; } base::MessageLoop message_loop_; std::unique_ptr<ResourceDispatcher> dispatcher_; TestRequestPeer::Context request_peer_context_; int request_id_ = 0; network::mojom::URLLoaderClientPtr url_loader_client_; }; TEST_F(URLLoaderClientImplTest, OnReceiveResponse) { network::ResourceResponseHead response_head; url_loader_client_->OnReceiveResponse(response_head, nullptr); EXPECT_FALSE(request_peer_context_.received_response); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(request_peer_context_.received_response); } TEST_F(URLLoaderClientImplTest, ResponseBody) { network::ResourceResponseHead response_head; url_loader_client_->OnReceiveResponse(response_head, nullptr); EXPECT_FALSE(request_peer_context_.received_response); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(request_peer_context_.received_response); mojo::DataPipe data_pipe(DataPipeOptions()); url_loader_client_->OnStartLoadingResponseBody( std::move(data_pipe.consumer_handle)); uint32_t size = 5; MojoResult result = data_pipe.producer_handle->WriteData( "hello", &size, MOJO_WRITE_DATA_FLAG_NONE); ASSERT_EQ(MOJO_RESULT_OK, result); EXPECT_EQ(5u, size); base::RunLoop().RunUntilIdle(); EXPECT_EQ("hello", request_peer_context_.data); } TEST_F(URLLoaderClientImplTest, OnReceiveRedirect) { network::ResourceResponseHead response_head; net::RedirectInfo redirect_info; url_loader_client_->OnReceiveRedirect(redirect_info, response_head); EXPECT_EQ(0, request_peer_context_.seen_redirects); base::RunLoop().RunUntilIdle(); EXPECT_EQ(1, request_peer_context_.seen_redirects); } TEST_F(URLLoaderClientImplTest, OnDataDownloaded) { network::ResourceResponseHead response_head; url_loader_client_->OnReceiveResponse(response_head, nullptr); url_loader_client_->OnDataDownloaded(8, 13); url_loader_client_->OnDataDownloaded(2, 1); EXPECT_FALSE(request_peer_context_.received_response); EXPECT_EQ(0, request_peer_context_.total_downloaded_data_length); EXPECT_EQ(0, request_peer_context_.total_encoded_data_length); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(request_peer_context_.received_response); EXPECT_EQ(10, request_peer_context_.total_downloaded_data_length); EXPECT_EQ(14, request_peer_context_.total_encoded_data_length); } TEST_F(URLLoaderClientImplTest, OnReceiveCachedMetadata) { network::ResourceResponseHead response_head; std::vector<uint8_t> metadata; metadata.push_back('a'); url_loader_client_->OnReceiveResponse(response_head, nullptr); url_loader_client_->OnReceiveCachedMetadata(metadata); EXPECT_FALSE(request_peer_context_.received_response); EXPECT_TRUE(request_peer_context_.cached_metadata.empty()); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(request_peer_context_.received_response); ASSERT_EQ(1u, request_peer_context_.cached_metadata.size()); EXPECT_EQ('a', request_peer_context_.cached_metadata[0]); } TEST_F(URLLoaderClientImplTest, OnTransferSizeUpdated) { network::ResourceResponseHead response_head; url_loader_client_->OnReceiveResponse(response_head, nullptr); url_loader_client_->OnTransferSizeUpdated(4); url_loader_client_->OnTransferSizeUpdated(4); EXPECT_FALSE(request_peer_context_.received_response); EXPECT_EQ(0, request_peer_context_.total_encoded_data_length); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(request_peer_context_.received_response); EXPECT_EQ(8, request_peer_context_.total_encoded_data_length); } TEST_F(URLLoaderClientImplTest, OnCompleteWithoutResponseBody) { network::ResourceResponseHead response_head; network::URLLoaderCompletionStatus status; url_loader_client_->OnReceiveResponse(response_head, nullptr); url_loader_client_->OnComplete(status); EXPECT_FALSE(request_peer_context_.received_response); EXPECT_FALSE(request_peer_context_.complete); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(request_peer_context_.received_response); EXPECT_TRUE(request_peer_context_.complete); } TEST_F(URLLoaderClientImplTest, OnCompleteWithResponseBody) { network::ResourceResponseHead response_head; network::URLLoaderCompletionStatus status; url_loader_client_->OnReceiveResponse(response_head, nullptr); mojo::DataPipe data_pipe(DataPipeOptions()); url_loader_client_->OnStartLoadingResponseBody( std::move(data_pipe.consumer_handle)); uint32_t size = 5; MojoResult result = data_pipe.producer_handle->WriteData( "hello", &size, MOJO_WRITE_DATA_FLAG_NONE); ASSERT_EQ(MOJO_RESULT_OK, result); EXPECT_EQ(5u, size); data_pipe.producer_handle.reset(); EXPECT_FALSE(request_peer_context_.received_response); EXPECT_EQ("", request_peer_context_.data); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(request_peer_context_.received_response); EXPECT_EQ("hello", request_peer_context_.data); url_loader_client_->OnComplete(status); EXPECT_FALSE(request_peer_context_.complete); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(request_peer_context_.received_response); EXPECT_EQ("hello", request_peer_context_.data); EXPECT_TRUE(request_peer_context_.complete); } // Due to the lack of ordering guarantee, it is possible that the response body // bytes arrives after the completion message. URLLoaderClientImpl should // restore the order. TEST_F(URLLoaderClientImplTest, OnCompleteShouldBeTheLastMessage) { network::ResourceResponseHead response_head; network::URLLoaderCompletionStatus status; url_loader_client_->OnReceiveResponse(response_head, nullptr); mojo::DataPipe data_pipe(DataPipeOptions()); url_loader_client_->OnStartLoadingResponseBody( std::move(data_pipe.consumer_handle)); url_loader_client_->OnComplete(status); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(request_peer_context_.received_response); EXPECT_FALSE(request_peer_context_.complete); uint32_t size = 5; MojoResult result = data_pipe.producer_handle->WriteData( "hello", &size, MOJO_WRITE_DATA_FLAG_NONE); ASSERT_EQ(MOJO_RESULT_OK, result); EXPECT_EQ(5u, size); base::RunLoop().RunUntilIdle(); EXPECT_EQ("hello", request_peer_context_.data); EXPECT_FALSE(request_peer_context_.complete); data_pipe.producer_handle.reset(); base::RunLoop().RunUntilIdle(); EXPECT_EQ("hello", request_peer_context_.data); EXPECT_TRUE(request_peer_context_.complete); } TEST_F(URLLoaderClientImplTest, CancelOnReceiveResponse) { request_peer_context_.cancel_on_receive_response = true; network::ResourceResponseHead response_head; network::URLLoaderCompletionStatus status; url_loader_client_->OnReceiveResponse(response_head, nullptr); mojo::DataPipe data_pipe(DataPipeOptions()); url_loader_client_->OnStartLoadingResponseBody( std::move(data_pipe.consumer_handle)); url_loader_client_->OnComplete(status); EXPECT_FALSE(request_peer_context_.received_response); EXPECT_FALSE(request_peer_context_.complete); EXPECT_FALSE(request_peer_context_.cancelled); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(request_peer_context_.received_response); EXPECT_FALSE(request_peer_context_.complete); EXPECT_TRUE(request_peer_context_.cancelled); } TEST_F(URLLoaderClientImplTest, CancelOnReceiveData) { request_peer_context_.cancel_on_receive_data = true; network::ResourceResponseHead response_head; network::URLLoaderCompletionStatus status; mojo::DataPipe data_pipe(DataPipeOptions()); uint32_t size = 5; MojoResult result = data_pipe.producer_handle->WriteData( "hello", &size, MOJO_WRITE_DATA_FLAG_NONE); ASSERT_EQ(MOJO_RESULT_OK, result); EXPECT_EQ(5u, size); url_loader_client_->OnReceiveResponse(response_head, nullptr); url_loader_client_->OnStartLoadingResponseBody( std::move(data_pipe.consumer_handle)); url_loader_client_->OnComplete(status); EXPECT_FALSE(request_peer_context_.received_response); EXPECT_EQ("", request_peer_context_.data); EXPECT_FALSE(request_peer_context_.complete); EXPECT_FALSE(request_peer_context_.cancelled); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(request_peer_context_.received_response); EXPECT_EQ("hello", request_peer_context_.data); EXPECT_FALSE(request_peer_context_.complete); EXPECT_TRUE(request_peer_context_.cancelled); } TEST_F(URLLoaderClientImplTest, Defer) { network::ResourceResponseHead response_head; network::URLLoaderCompletionStatus status; url_loader_client_->OnReceiveResponse(response_head, nullptr); url_loader_client_->OnComplete(status); EXPECT_FALSE(request_peer_context_.received_response); EXPECT_FALSE(request_peer_context_.complete); dispatcher_->SetDefersLoading(request_id_, true); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(request_peer_context_.received_response); EXPECT_FALSE(request_peer_context_.complete); dispatcher_->SetDefersLoading(request_id_, false); EXPECT_FALSE(request_peer_context_.received_response); EXPECT_FALSE(request_peer_context_.complete); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(request_peer_context_.received_response); EXPECT_TRUE(request_peer_context_.complete); } TEST_F(URLLoaderClientImplTest, DeferWithResponseBody) { network::ResourceResponseHead response_head; network::URLLoaderCompletionStatus status; url_loader_client_->OnReceiveResponse(response_head, nullptr); mojo::DataPipe data_pipe(DataPipeOptions()); uint32_t size = 5; MojoResult result = data_pipe.producer_handle->WriteData( "hello", &size, MOJO_WRITE_DATA_FLAG_NONE); ASSERT_EQ(MOJO_RESULT_OK, result); EXPECT_EQ(5u, size); data_pipe.producer_handle.reset(); url_loader_client_->OnStartLoadingResponseBody( std::move(data_pipe.consumer_handle)); url_loader_client_->OnComplete(status); EXPECT_FALSE(request_peer_context_.received_response); EXPECT_FALSE(request_peer_context_.complete); EXPECT_EQ("", request_peer_context_.data); dispatcher_->SetDefersLoading(request_id_, true); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(request_peer_context_.received_response); EXPECT_FALSE(request_peer_context_.complete); EXPECT_EQ("", request_peer_context_.data); dispatcher_->SetDefersLoading(request_id_, false); EXPECT_FALSE(request_peer_context_.received_response); EXPECT_FALSE(request_peer_context_.complete); EXPECT_EQ("", request_peer_context_.data); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(request_peer_context_.received_response); EXPECT_TRUE(request_peer_context_.complete); EXPECT_EQ("hello", request_peer_context_.data); } // As "transfer size update" message is handled specially in the implementation, // we have a separate test. TEST_F(URLLoaderClientImplTest, DeferWithTransferSizeUpdated) { network::ResourceResponseHead response_head; network::URLLoaderCompletionStatus status; url_loader_client_->OnReceiveResponse(response_head, nullptr); mojo::DataPipe data_pipe(DataPipeOptions()); uint32_t size = 5; MojoResult result = data_pipe.producer_handle->WriteData( "hello", &size, MOJO_WRITE_DATA_FLAG_NONE); ASSERT_EQ(MOJO_RESULT_OK, result); EXPECT_EQ(5u, size); data_pipe.producer_handle.reset(); url_loader_client_->OnStartLoadingResponseBody( std::move(data_pipe.consumer_handle)); url_loader_client_->OnTransferSizeUpdated(4); url_loader_client_->OnComplete(status); EXPECT_FALSE(request_peer_context_.received_response); EXPECT_FALSE(request_peer_context_.complete); EXPECT_EQ("", request_peer_context_.data); EXPECT_EQ(0, request_peer_context_.total_encoded_data_length); dispatcher_->SetDefersLoading(request_id_, true); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(request_peer_context_.received_response); EXPECT_FALSE(request_peer_context_.complete); EXPECT_EQ("", request_peer_context_.data); EXPECT_EQ(0, request_peer_context_.total_encoded_data_length); dispatcher_->SetDefersLoading(request_id_, false); EXPECT_FALSE(request_peer_context_.received_response); EXPECT_FALSE(request_peer_context_.complete); EXPECT_EQ("", request_peer_context_.data); EXPECT_EQ(0, request_peer_context_.total_encoded_data_length); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(request_peer_context_.received_response); EXPECT_TRUE(request_peer_context_.complete); EXPECT_EQ("hello", request_peer_context_.data); EXPECT_EQ(4, request_peer_context_.total_encoded_data_length); } TEST_F(URLLoaderClientImplTest, SetDeferredDuringFlushingDeferredMessage) { request_peer_context_.defer_on_redirect = true; net::RedirectInfo redirect_info; network::ResourceResponseHead response_head; network::URLLoaderCompletionStatus status; url_loader_client_->OnReceiveRedirect(redirect_info, response_head); url_loader_client_->OnReceiveResponse(response_head, nullptr); mojo::DataPipe data_pipe(DataPipeOptions()); uint32_t size = 5; MojoResult result = data_pipe.producer_handle->WriteData( "hello", &size, MOJO_WRITE_DATA_FLAG_NONE); ASSERT_EQ(MOJO_RESULT_OK, result); EXPECT_EQ(5u, size); data_pipe.producer_handle.reset(); url_loader_client_->OnStartLoadingResponseBody( std::move(data_pipe.consumer_handle)); url_loader_client_->OnTransferSizeUpdated(4); url_loader_client_->OnComplete(status); EXPECT_EQ(0, request_peer_context_.seen_redirects); EXPECT_FALSE(request_peer_context_.received_response); EXPECT_FALSE(request_peer_context_.complete); EXPECT_EQ("", request_peer_context_.data); EXPECT_EQ(0, request_peer_context_.total_encoded_data_length); dispatcher_->SetDefersLoading(request_id_, true); base::RunLoop().RunUntilIdle(); EXPECT_EQ(0, request_peer_context_.seen_redirects); EXPECT_FALSE(request_peer_context_.received_response); EXPECT_FALSE(request_peer_context_.complete); EXPECT_EQ("", request_peer_context_.data); EXPECT_EQ(0, request_peer_context_.total_encoded_data_length); dispatcher_->SetDefersLoading(request_id_, false); EXPECT_EQ(0, request_peer_context_.seen_redirects); EXPECT_FALSE(request_peer_context_.received_response); EXPECT_FALSE(request_peer_context_.complete); EXPECT_EQ("", request_peer_context_.data); EXPECT_EQ(0, request_peer_context_.total_encoded_data_length); base::RunLoop().RunUntilIdle(); EXPECT_EQ(1, request_peer_context_.seen_redirects); EXPECT_FALSE(request_peer_context_.received_response); EXPECT_FALSE(request_peer_context_.complete); EXPECT_EQ("", request_peer_context_.data); EXPECT_EQ(0, request_peer_context_.total_encoded_data_length); EXPECT_FALSE(request_peer_context_.cancelled); dispatcher_->SetDefersLoading(request_id_, false); base::RunLoop().RunUntilIdle(); EXPECT_EQ(1, request_peer_context_.seen_redirects); EXPECT_TRUE(request_peer_context_.received_response); EXPECT_TRUE(request_peer_context_.complete); EXPECT_EQ("hello", request_peer_context_.data); EXPECT_EQ(4, request_peer_context_.total_encoded_data_length); EXPECT_FALSE(request_peer_context_.cancelled); } TEST_F(URLLoaderClientImplTest, SetDeferredDuringFlushingDeferredMessageOnTransferSizeUpdated) { request_peer_context_.defer_on_transfer_size_updated = true; network::ResourceResponseHead response_head; network::URLLoaderCompletionStatus status; url_loader_client_->OnReceiveResponse(response_head, nullptr); url_loader_client_->OnTransferSizeUpdated(4); url_loader_client_->OnComplete(status); EXPECT_FALSE(request_peer_context_.received_response); EXPECT_FALSE(request_peer_context_.complete); EXPECT_EQ(0, request_peer_context_.total_encoded_data_length); dispatcher_->SetDefersLoading(request_id_, true); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(request_peer_context_.received_response); EXPECT_FALSE(request_peer_context_.complete); EXPECT_EQ(0, request_peer_context_.total_encoded_data_length); dispatcher_->SetDefersLoading(request_id_, false); EXPECT_FALSE(request_peer_context_.received_response); EXPECT_FALSE(request_peer_context_.complete); EXPECT_EQ(0, request_peer_context_.total_encoded_data_length); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(request_peer_context_.received_response); EXPECT_FALSE(request_peer_context_.complete); EXPECT_EQ(4, request_peer_context_.total_encoded_data_length); EXPECT_FALSE(request_peer_context_.cancelled); dispatcher_->SetDefersLoading(request_id_, false); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(request_peer_context_.received_response); EXPECT_TRUE(request_peer_context_.complete); EXPECT_EQ(4, request_peer_context_.total_encoded_data_length); EXPECT_FALSE(request_peer_context_.cancelled); } TEST_F(URLLoaderClientImplTest, CancelOnReceiveDataWhileFlushing) { request_peer_context_.cancel_on_receive_data = true; dispatcher_->SetDefersLoading(request_id_, true); network::ResourceResponseHead response_head; network::URLLoaderCompletionStatus status; mojo::DataPipe data_pipe(DataPipeOptions()); uint32_t size = 5; MojoResult result = data_pipe.producer_handle->WriteData( "hello", &size, MOJO_WRITE_DATA_FLAG_NONE); ASSERT_EQ(MOJO_RESULT_OK, result); EXPECT_EQ(5u, size); url_loader_client_->OnReceiveResponse(response_head, nullptr); url_loader_client_->OnStartLoadingResponseBody( std::move(data_pipe.consumer_handle)); url_loader_client_->OnComplete(status); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(request_peer_context_.received_response); EXPECT_EQ("", request_peer_context_.data); EXPECT_FALSE(request_peer_context_.complete); EXPECT_FALSE(request_peer_context_.cancelled); dispatcher_->SetDefersLoading(request_id_, false); EXPECT_FALSE(request_peer_context_.received_response); EXPECT_EQ("", request_peer_context_.data); EXPECT_FALSE(request_peer_context_.complete); EXPECT_FALSE(request_peer_context_.cancelled); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(request_peer_context_.received_response); EXPECT_EQ("hello", request_peer_context_.data); EXPECT_FALSE(request_peer_context_.complete); EXPECT_TRUE(request_peer_context_.cancelled); } } // namespace content
38.00726
93
0.798682
zipated
427dadf50206b481428f745d6378efe7af5a3e14
1,896
cpp
C++
source/Matrix.cpp
cburggie/matrixemu
1ec74e26f2a201caf5577eabd57c0ab5ad83d94f
[ "MIT" ]
null
null
null
source/Matrix.cpp
cburggie/matrixemu
1ec74e26f2a201caf5577eabd57c0ab5ad83d94f
[ "MIT" ]
null
null
null
source/Matrix.cpp
cburggie/matrixemu
1ec74e26f2a201caf5577eabd57c0ab5ad83d94f
[ "MIT" ]
null
null
null
//namespace matrixemu #include <Terminal.h> //class Terminal #include <Column.h> //class Column #include <Linker.h> //class Linker<T> #include <Matrix.h> //Implementing this //namespace std #include <cstdlib> //rand() using namespace matrixemu; Matrix::Matrix() { terminal = new Terminal(); columns = new Linker<Column>(); } Matrix::~Matrix() { if (terminal) delete terminal; if (columns) delete columns; } void Matrix::run(int frames) { //we run until we've rendered enough frames or our terminal member has //detected a quit signal from the user. //we clear the screen when we're done and exit. setupColors(); int i, spawnpoint = 0; for (i = 0; i < frames; i++) { if (i == spawnpoint) { addNewColumn(); spawnpoint += 1 + (rand() % 5); } drawFrame(i); terminal->pause(25); //25 ms pause or 40 fps if (terminal->done()) break; } terminal->blank(); terminal->draw(); } void Matrix::setupColors() { int r[8], g[8], b[8], i; for (i = 0; i < 8; i++) { r[i] = 0; g[i] = 125 * i; b[i] = 0; } terminal->makePalette(8,r,g,b); } void Matrix::addNewColumn() { //init new column; int xpos, speed, length; xpos = rand() % terminal->getWidth(); speed = 1 + (rand() % 10); length = 1 + (rand() % 50); Column * column = new Column(terminal, xpos); if (!column) { return; } column->setSpeed(speed); column->setLength(length); //init new link and add to list Linker<Column> * link = new Linker<Column>(column); if (!link) { delete column; return; } link->append(columns); } void Matrix::drawFrame(int timestamp) { Linker<Column> * node = columns->next(); Linker<Column> * tmp; terminal->blank(); while (node != columns) { tmp = node->next(); node->get()->draw(timestamp); //delete node if it's offscreen now if (node->get()->offscreen()) { delete node; } node = tmp; } terminal->draw(); }
16.205128
71
0.617616
cburggie
427ee3368d8d95736ded6ebd83e6d7aaf7f3496f
61,687
hpp
C++
include/bf_rt/bf_rt_table.hpp
mestery/p4-dpdk-target
9e7bafa442d3e008749f9ee0e1364bc5e9acfc13
[ "Apache-2.0" ]
17
2021-10-21T17:55:24.000Z
2022-03-11T11:04:33.000Z
include/bf_rt/bf_rt_table.hpp
mestery/p4-dpdk-target
9e7bafa442d3e008749f9ee0e1364bc5e9acfc13
[ "Apache-2.0" ]
9
2021-12-20T10:24:50.000Z
2022-03-21T17:42:13.000Z
include/bf_rt/bf_rt_table.hpp
mestery/p4-dpdk-target
9e7bafa442d3e008749f9ee0e1364bc5e9acfc13
[ "Apache-2.0" ]
7
2021-11-02T22:08:04.000Z
2022-03-09T23:26:03.000Z
/* * Copyright(c) 2021 Intel Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** @file bf_rt_table.hpp * * @brief Contains BF-RT Table APIs */ #ifndef _BF_RT_TABLE_HPP #define _BF_RT_TABLE_HPP #include <string> #include <cstring> #include <vector> #include <map> #include <memory> #include <set> #include <unordered_map> #include <bf_rt/bf_rt_session.hpp> #include <bf_rt/bf_rt_table_data.hpp> #include <bf_rt/bf_rt_table_key.hpp> #include <bf_rt/bf_rt_table_attributes.hpp> #include <bf_rt/bf_rt_table_operations.hpp> namespace bfrt { // Forward declarations enum class TableAttributesIdleTableMode; /** * @brief Class for Annotations. Contains 2 strings to uniquely identify an * annotation. These annotations can be on a Table, Action, Key or Data Field * * Possible list of annotations are below. This list is not exhaustive since * pragmas can be annotations too like alpm_partition ones which will vary * according to the params given -> * 1. ("$bfrt_field_class","register_data") If a Data field is a register data. * Register data fields are to be set using one value but while * tableEntryGet, this field returns a vector(one value for each field) * 2. ("$bfrt_port_type_class","dev_port") If the data field is a dev_port. * 3. ("$bfrt_port_type_class","port_hdl_conn_id") If the data field is a port * handle conn ID. * 4. ("$bfrt_port_type_class","port_hdl_chnl_id") If the data field is a port * handle channel ID. * 5. ("$bfrt_port_type_class","port_name") If the data field is a port name. * 6. ("$bfrt_port_type_class","fp_port") If the data field is a front panel * port. * 7. ("isFieldSlice","true") If a Data field is a slice of bigger field. * 8. ("@defaultonly","") If an action is to be default only * 9. ("$bfrt_field_imp_level", "level") Importance level of a field. All *fields * start off with an importance level of 1 */ class Annotation { public: Annotation(std::string name, std::string value) : name_(name), value_(value) { full_name_ = name_ + "." + value_; }; bool operator<(const Annotation &other) const; bool operator==(const Annotation &other) const; bool operator==(const std::string &other_str) const; bf_status_t fullNameGet(std::string *fullName) const; const std::string name_{""}; const std::string value_{""}; struct Less { bool operator()(const Annotation &lhs, const Annotation &rhs) const { return lhs < rhs; } }; private: std::string full_name_{""}; }; /** * @brief We wrap the annotation in a reference wrapper because we want to send * the actual object to the API user and not a copy. */ using AnnotationSet = std::set<std::reference_wrapper<const Annotation>, Annotation::Less>; /** * @brief Class to contain metadata of Table Objs like Data and Key Fields, * and perform functions like EntryAdd, AttributeSet, OperationsExecute etc<br> * <B>Creation: </B> Cannot be created. can only be queried from \ref * bfrt::BfRtInfo */ class BfRtTable { public: /** * @brief Enum of Flags needed for Table Get Request * (Deprecated. Please use generic flag support) */ enum class BfRtTableGetFlag { /** Read from hw */ GET_FROM_HW, /** Read from sw value */ GET_FROM_SW }; /** * @brief Enum of Flags needed for Table Modify Incremental Request * (Deprecated. Please use generic flag support) */ enum class BfRtTableModIncFlag { /** Flag to add the given data incrementally to the existing table entry */ MOD_INC_ADD = 0, /** Flag to delete the given data from the existing table entry */ MOD_INC_DELETE = 1 }; /** * @brief Table types. Users are discouraged from using this especially when * creating table-agnostic generic applications like a CLI or RPC server */ enum class TableType { /** Match action table*/ MATCH_DIRECT = 0, /** Match action table with actions of the table implemented using an "ActionProfile" */ MATCH_INDIRECT = 1, /** Match action table with actions of the table implemented using an "ActionSelector"*/ MATCH_INDIRECT_SELECTOR = 2, /** Action Profile table*/ ACTION_PROFILE = 3, /** Action Selector table*/ SELECTOR = 4, /** Counter table*/ COUNTER = 5, /** Meter table*/ METER = 6, /** Register table*/ REGISTER = 7, /** Port Metadata table.*/ PORT_METADATA = 11, /** Port Configuration */ PORT_CFG = 15, /** Port Stats */ PORT_STAT = 16, /** Port Hdl to Dev_port Conversion table */ PORT_HDL_INFO = 17, /** Front panel Idx to Dev_port Conversion table */ PORT_FRONT_PANEL_IDX_INFO = 18, /** Port Str to Dev_port Conversion table */ PORT_STR_INFO = 19, /** Mirror configuration table */ MIRROR_CFG = 30, /** Device Config Table */ DEV_CFG = 36, /** Debug Counters table */ DBG_CNT = 57, /** Logical table debug debug counters table */ LOG_DBG_CNT = 58, /** Register param table */ REG_PARAM = 64, /** Action Selector Get Member table */ SELECTOR_GET_MEMBER = 69, INVALID = 76 }; /** * @brief enum of table APIs available */ enum class TableApi { /** Entry Add. Most common API. Applicable to most tables*/ ADD = 0, /** Entry Modify. Applicable to most tables*/ MODIFY = 1, /** Entry Modify incremental. Useful in cases where the data is an array and only one element needs to be changed.*/ MODIFY_INC = 2, /** Entry Delete. Not applicable for some tables like counter, register, meter*/ DELETE = 3, /** Clear. Only applicable for tables which have DELETE right now*/ CLEAR = 4, /** Default Entry Set. Only applicable for Match action tables, direct or indirect. If table has const default action, then this would fail*/ DEFAULT_ENTRY_SET = 5, /** Default Entry Reset. Only applicable for Match action tables, direct or indirect. Idempotent*/ DEFAULT_ENTRY_RESET = 6, /** Default Entry Get. Only applicable for Match action tables, direct or indirect.*/ DEFAULT_ENTRY_GET = 7, /** Entry Get. Applicable to most tables.*/ GET = 8, /** Entry Get First. Applicable to most tables.*/ GET_FIRST = 9, /** Entry Get Next n entries. Applicable for most tables*/ GET_NEXT_N = 10, /** Get Usage. get the current usage of the tables. Not applicable for some tables like counter, register, meter */ USAGE_GET = 11, /** Get entry by handle instead of key. */ GET_BY_HANDLE = 12, /** Get entry key by handle. */ KEY_GET = 13, /** Get entry handle from key. */ HANDLE_GET = 14, /** Invalid not supported API. */ INVALID_API = 15 }; /** * @brief Vector of pair of Key and Data. The key and data need to be * allocated * and pushed in the vector before being passed in to the appropriate Get API. */ using keyDataPairs = std::vector<std::pair<BfRtTableKey *, BfRtTableData *>>; virtual ~BfRtTable() = default; //// Table APIs /** * @name Table APIs * @{ */ /** * @name Old flags wrapper section * @{ */ /** * @brief Add an entry to the table * @deprecated Please use function version with new flags argument. * * @param[in] session Session Object * @param[in] dev_tgt Device target * @param[in] key Entry Key * @param[in] data Entry Data * * @return Status of the API call */ virtual bf_status_t tableEntryAdd(const BfRtSession &session, const bf_rt_target_t &dev_tgt, const BfRtTableKey &key, const BfRtTableData &data) const = 0; /** * @brief Modify an existing entry of the table * @deprecated Please use function version with new flags argument. * * @param[in] session Session Object * @param[in] dev_tgt Device target * @param[in] key Entry Key * @param[in] data Entry Data * * @return Status of the API call */ virtual bf_status_t tableEntryMod(const BfRtSession &session, const bf_rt_target_t &dev_tgt, const BfRtTableKey &key, const BfRtTableData &data) const = 0; /** * @brief Modify only a part of an existing entry of the table. * - Either add or delete the given data to the existing entry. * @deprecated Please use function version with new flags argument. * * @param[in] session Session Object * @param[in] dev_tgt Device target * @param[in] key Entry Key * @param[in] data Entry Data * @param[in] flag Modify inc flag (ADD or DEL) * * @return Status of the API call */ virtual bf_status_t tableEntryModInc( const BfRtSession &session, const bf_rt_target_t &dev_tgt, const BfRtTableKey &key, const BfRtTableData &data, const BfRtTable::BfRtTableModIncFlag &flag) const = 0; /** * @brief Delete an entry of the table * @deprecated Please use function version with new flags argument. * * @param[in] session Session Object * @param[in] dev_tgt Device target * @param[in] key Entry Key * * @return Status of the API call */ virtual bf_status_t tableEntryDel(const BfRtSession &session, const bf_rt_target_t &dev_tgt, const BfRtTableKey &key) const = 0; /** * @brief Clear a table. Delete all entries. * @deprecated Please use function version with new flags argument. * * @param[in] session Session Object * @param[in] dev_tgt Device target * * @return Status of the API call */ virtual bf_status_t tableClear(const BfRtSession &session, const bf_rt_target_t &dev_tgt) const = 0; /** * @brief Set the default Entry of the table * @deprecated Please use function version with new flags argument. * * @details There can be a P4 defined default entry with parameters. This API * modifies any existing default entry to the one passed in here. Note that * this API is idempotent and should be called either when modifying an * existing default entry or to program one newly. There could be a particular * action which is designated as a default-only action. In that case, an error * is returned if the action id of the data object passed in here is different * from the designated default action. * * @param[in] session Session Object * @param[in] dev_tgt Device target * @param[in] data Entry Data * * @return Status of the API call */ virtual bf_status_t tableDefaultEntrySet(const BfRtSession &session, const bf_rt_target_t &dev_tgt, const BfRtTableData &data) const = 0; /** * @brief Reset the default Entry of the table * @deprecated Please use function version with new flags argument. * * @details The default entry of the table is reset to the P4 specified * default action with parameters, if it exists, else its reset to a "no-op" * * @param[in] session Session Object * @param[in] dev_tgt Device target * * @return Status of the API call */ virtual bf_status_t tableDefaultEntryReset( const BfRtSession &session, const bf_rt_target_t &dev_tgt) const = 0; /** * @brief Get the default Entry of the table * @deprecated Please use function version with new flags argument. * * @details The default entry returned will be the one programmed or the P4 * defined one, if it exists. Note that, when the entry is obtained from * software, the P4 defined default entry will not be available if the default * entry was not programmed ever. However, when the entry is obtained from * hardware, the P4 defined default entry will be returned even if the default * entry was not programmed ever. * * @param[in] session Session Object * @param[in] dev_tgt Device target * @param[in] flag Get Flags * @param[inout] data Entry Data, if not empty will be used to filter * returned fields * * @return Status of the API call */ virtual bf_status_t tableDefaultEntryGet( const BfRtSession &session, const bf_rt_target_t &dev_tgt, const BfRtTable::BfRtTableGetFlag &flag, BfRtTableData *data) const = 0; /** * @brief Get an entry from the table * @deprecated Please use function version with new flags argument. * * @param[in] session Session Object * @param[in] dev_tgt Device target * @param[in] key Entry Key * @param[in] flag Get Flags * @param[inout] data Entry Data, if not empty will be used to filter * returned fields * * @return Status of the API call */ virtual bf_status_t tableEntryGet(const BfRtSession &session, const bf_rt_target_t &dev_tgt, const BfRtTableKey &key, const BfRtTable::BfRtTableGetFlag &flag, BfRtTableData *data) const = 0; /** * @brief Get an entry from the table by handle * @deprecated Please use function version with new flags argument. * * @param[in] session Session Object * @param[in] dev_tgt Device target * @param[in] flag Get Flags * @param[in] entry_handle Handle to the entry * @param[out] key Entry Key * @param[inout] data Entry Data, if not empty will be used to filter * returned fields * * @return Status of the API call */ virtual bf_status_t tableEntryGet(const BfRtSession &session, const bf_rt_target_t &dev_tgt, const BfRtTable::BfRtTableGetFlag &flag, const bf_rt_handle_t &entry_handle, BfRtTableKey *key, BfRtTableData *data) const = 0; /** * @brief Get an entry key from the table by handle * @deprecated Please use function version with new flags argument. * * @param[in] session Session Object * @param[in] dev_tgt Device target * @param[in] entry_handle Handle to the entry * @param[out] entry_tgt Target device for specified entry handle, * may not match dev_tgt values * @param[out] key Entry Key * * @return Status of the API call */ virtual bf_status_t tableEntryKeyGet(const BfRtSession &session, const bf_rt_target_t &dev_tgt, const bf_rt_handle_t &entry_handle, bf_rt_target_t *entry_tgt, BfRtTableKey *key) const = 0; /** * @brief Get an entry handle from the table * @deprecated Please use function version with new flags argument. * * @param[in] session Session Object * @param[in] dev_tgt Device target * @param[in] key Entry Key * @param[out] entry_handle Handle to the entry * * @return Status of the API call */ virtual bf_status_t tableEntryHandleGet( const BfRtSession &session, const bf_rt_target_t &dev_tgt, const BfRtTableKey &key, bf_rt_handle_t *entry_handle) const = 0; /** * @brief Get the first entry of the table * @deprecated Please use function version with new flags argument. * * @param[in] session Session Object * @param[in] dev_tgt Device target * @param[in] flag Get Flags * @param[out] key Entry Key * @param[inout] data Entry Data, if not empty will be used to filter * returned fields * * @return Status of the API call */ virtual bf_status_t tableEntryGetFirst( const BfRtSession &session, const bf_rt_target_t &dev_tgt, const BfRtTable::BfRtTableGetFlag &flag, BfRtTableKey *key, BfRtTableData *data) const = 0; /** * @brief Get next N entries of the table following the entry that is * specificed by key. * If the N queried for is greater than the actual entries, then * all the entries present are returned. * N must be greater than zero. * @deprecated Please use function version with new flags argument. * * @param[in] session Session Object * @param[in] dev_tgt Device target * @param[in] key Entry Key from which N entries are queried * @param[in] n Number of entries queried 'N' * @param[in] flag Get Flags * @param[out] key_data_pairs Vector of N Pairs(key, data). This vector needs * to have N entries before the API call is made, else error is returned * @param[out] num_returned Actual number of entries returned * * @return Status of the API call */ virtual bf_status_t tableEntryGetNext_n( const BfRtSession &session, const bf_rt_target_t &dev_tgt, const BfRtTableKey &key, const uint32_t &n, const BfRtTable::BfRtTableGetFlag &flag, keyDataPairs *key_data_pairs, uint32_t *num_returned) const = 0; /** * @brief Current Usage of the table * @deprecated Please use function version with new flags argument. * * @param[in] session Session Object * @param[in] dev_tgt Device target * @param[in] flag Get Flags * @param[out] count Table usage * * @return Status of the API call */ virtual bf_status_t tableUsageGet(const BfRtSession &session, const bf_rt_target_t &dev_tgt, const BfRtTable::BfRtTableGetFlag &flag, uint32_t *count) const = 0; /** * @brief The maximum size of the table. Note that this size might * be different than present in bf-rt.json especially for Match Action * Tables. This is because sometimes MATs might reserve some space for * atomic modfies and hence might be 1 or 2 < json size * @deprecated Please use function version with new flags argument. * * @param[in] session Session Object * @param[in] dev_tgt Device target * @param[out] size Number of total available entries * * @return Status of the API call */ virtual bf_status_t tableSizeGet(const BfRtSession &session, const bf_rt_target_t &dev_tgt, size_t *size) const = 0; /** @} */ // End of old flags wrapper section */ /** * @brief Add an entry to the table * * @param[in] session Session Object * @param[in] dev_tgt Device target * @param[in] flags Call flags * @param[in] key Entry Key * @param[in] data Entry Data * * @return Status of the API call */ virtual bf_status_t tableEntryAdd(const BfRtSession &session, const bf_rt_target_t &dev_tgt, const uint64_t &flags, const BfRtTableKey &key, const BfRtTableData &data) const = 0; /** * @brief Modify an existing entry of the table * * @param[in] session Session Object * @param[in] dev_tgt Device target * @param[in] flags Call flags * @param[in] key Entry Key * @param[in] data Entry Data * * @return Status of the API call */ virtual bf_status_t tableEntryMod(const BfRtSession &session, const bf_rt_target_t &dev_tgt, const uint64_t &flags, const BfRtTableKey &key, const BfRtTableData &data) const = 0; /** * @brief Modify only a part of an existing entry of the table. * - Either add or delete the given data to the existing entry. * * @param[in] session Session Object * @param[in] dev_tgt Device target * @param[in] flags Call flags * @param[in] key Entry Key * @param[in] data Entry Data * @param[in] flag Modify inc flag (ADD or DEL) * * @return Status of the API call */ virtual bf_status_t tableEntryModInc(const BfRtSession &session, const bf_rt_target_t &dev_tgt, const uint64_t &flags, const BfRtTableKey &key, const BfRtTableData &data) const = 0; /** * @brief Delete an entry of the table * * @param[in] session Session Object * @param[in] dev_tgt Device target * @param[in] flags Call flags * @param[in] key Entry Key * * @return Status of the API call */ virtual bf_status_t tableEntryDel(const BfRtSession &session, const bf_rt_target_t &dev_tgt, const uint64_t &flags, const BfRtTableKey &key) const = 0; /** * @brief Clear a table. Delete all entries. This API also resets default * entry if present and is not const default. If table has always present * entries like Counter table, then this table resets all the entries * instead. * * @param[in] session Session Object * @param[in] dev_tgt Device target * @param[in] flags Call flags * * @return Status of the API call */ virtual bf_status_t tableClear(const BfRtSession &session, const bf_rt_target_t &dev_tgt, const uint64_t &flags) const = 0; /** * @brief Set the default Entry of the table * * @details There can be a P4 defined default entry with parameters. This API * modifies any existing default entry to the one passed in here. Note that * this API is idempotent and should be called either when modifying an * existing default entry or to program one newly. There could be a particular * action which is designated as a default-only action. In that case, an error * is returned if the action id of the data object passed in here is different * from the designated default action. * * @param[in] session Session Object * @param[in] dev_tgt Device target * @param[in] flags Call flags * @param[in] data Entry Data * * @return Status of the API call */ virtual bf_status_t tableDefaultEntrySet(const BfRtSession &session, const bf_rt_target_t &dev_tgt, const uint64_t &flags, const BfRtTableData &data) const = 0; /** * @brief Reset the default Entry of the table * * @details The default entry of the table is reset to the P4 specified * default action with parameters, if it exists, else its reset to a "no-op" * * @param[in] session Session Object * @param[in] dev_tgt Device target * @param[in] flags Call flags * * @return Status of the API call */ virtual bf_status_t tableDefaultEntryReset(const BfRtSession &session, const bf_rt_target_t &dev_tgt, const uint64_t &flags) const = 0; /** * @brief Get the default Entry of the table * * @details The default entry returned will be the one programmed or the P4 * defined one, if it exists. Note that, when the entry is obtained from * software, the P4 defined default entry will not be available if the default * entry was not programmed ever. However, when the entry is obtained from * hardware, the P4 defined default entry will be returned even if the default * entry was not programmed ever. * * @param[in] session Session Object * @param[in] dev_tgt Device target * @param[in] flags Call flags * @param[inout] data Entry Data, if not empty will be used to filter * returned fields * * @return Status of the API call */ virtual bf_status_t tableDefaultEntryGet(const BfRtSession &session, const bf_rt_target_t &dev_tgt, const uint64_t &flags, BfRtTableData *data) const = 0; /** * @brief Get an entry from the table * * @param[in] session Session Object * @param[in] dev_tgt Device target * @param[in] flags Call flags * @param[in] key Entry Key * @param[inout] data Entry Data, if not empty will be used to filter * returned fields * * @return Status of the API call */ virtual bf_status_t tableEntryGet(const BfRtSession &session, const bf_rt_target_t &dev_tgt, const uint64_t &flags, const BfRtTableKey &key, BfRtTableData *data) const = 0; /** * @brief Get an entry from the table by handle * * @param[in] session Session Object * @param[in] dev_tgt Device target * @param[in] flags Call flags * @param[in] entry_handle Handle to the entry * @param[out] key Entry Key * @param[inout] data Entry Data, if not empty will be used to filter * returned fields * * @return Status of the API call */ virtual bf_status_t tableEntryGet(const BfRtSession &session, const bf_rt_target_t &dev_tgt, const uint64_t &flags, const bf_rt_handle_t &entry_handle, BfRtTableKey *key, BfRtTableData *data) const = 0; /** * @brief Get an entry key from the table by handle * * @param[in] session Session Object * @param[in] dev_tgt Device target * @param[in] flags Call flags * @param[in] entry_handle Handle to the entry * @param[out] entry_tgt Target device for specified entry handle, * may not match dev_tgt values * @param[out] key Entry Key * * @return Status of the API call */ virtual bf_status_t tableEntryKeyGet(const BfRtSession &session, const bf_rt_target_t &dev_tgt, const uint64_t &flags, const bf_rt_handle_t &entry_handle, bf_rt_target_t *entry_tgt, BfRtTableKey *key) const = 0; /** * @brief Get an entry handle from the table * * @param[in] session Session Object * @param[in] dev_tgt Device target * @param[in] flags Call flags * @param[in] key Entry Key * @param[out] entry_handle Handle to the entry * * @return Status of the API call */ virtual bf_status_t tableEntryHandleGet( const BfRtSession &session, const bf_rt_target_t &dev_tgt, const uint64_t &flags, const BfRtTableKey &key, bf_rt_handle_t *entry_handle) const = 0; /** * @brief Get the first entry of the table * * @param[in] session Session Object * @param[in] dev_tgt Device target * @param[in] flags Call flags * @param[out] key Entry Key * @param[inout] data Entry Data, if not empty will be used to filter * returned fields * * @return Status of the API call */ virtual bf_status_t tableEntryGetFirst(const BfRtSession &session, const bf_rt_target_t &dev_tgt, const uint64_t &flags, BfRtTableKey *key, BfRtTableData *data) const = 0; /** * @brief Get next N entries of the table following the entry that is * specificed by key. * If the N queried for is greater than the actual entries, then * all the entries present are returned. * N must be greater than zero. * * @param[in] session Session Object * @param[in] dev_tgt Device target * @param[in] flags Call flags * @param[in] key Entry Key from which N entries are queried * @param[in] n Number of entries queried 'N' * @param[out] key_data_pairs Vector of N Pairs(key, data). This vector needs * to have N entries before the API call is made, else error is returned * @param[out] num_returned Actual number of entries returned * * @return Status of the API call */ virtual bf_status_t tableEntryGetNext_n(const BfRtSession &session, const bf_rt_target_t &dev_tgt, const uint64_t &flags, const BfRtTableKey &key, const uint32_t &n, keyDataPairs *key_data_pairs, uint32_t *num_returned) const = 0; /** * @brief Current Usage of the table * * @param[in] session Session Object * @param[in] dev_tgt Device target * @param[in] flags Call flags * @param[out] count Table usage * * @return Status of the API call */ virtual bf_status_t tableUsageGet(const BfRtSession &session, const bf_rt_target_t &dev_tgt, const uint64_t &flags, uint32_t *count) const = 0; /** * @brief The maximum size of the table. Note that this size might * be different than present in bf-rt.json especially for Match Action * Tables. This is because sometimes MATs might reserve some space for * atomic modfies and hence might be 1 or 2 < json size * * @param[in] session Session Object * @param[in] dev_tgt Device target * @param[in] flags Call flags * @param[out] size Number of total available entries * * @return Status of the API call */ virtual bf_status_t tableSizeGet(const BfRtSession &session, const bf_rt_target_t &dev_tgt, const uint64_t &flags, size_t *size) const = 0; /***** End of APIs with flags *******/ /** * @brief Get name of the table * * @param[out] name Name of the table * * @return Status of the API call */ virtual bf_status_t tableNameGet(std::string *name) const = 0; /** * @brief Get ID of the table * * @param[out] id ID of the table * * @return Status of the API call */ virtual bf_status_t tableIdGet(bf_rt_id_t *id) const = 0; /** * @brief The type of the table * * @param[out] table_type Type of the table * * @return Status of the API call */ virtual bf_status_t tableTypeGet(BfRtTable::TableType *table_type) const = 0; /** * @brief Get whether this table has a const default action * * @param[out] has_const_default_action If default action is const * * @return Status of the API call */ virtual bf_status_t tableHasConstDefaultAction( bool *has_const_default_action) const = 0; /** * @brief Get whether this table is a const table * * @param[out] is_const If table is const * * @return Status of the API call */ virtual bf_status_t tableIsConst(bool *is_const) const = 0; /** * @brief Get a set of annotations on a Table * * @param[out] annotations Set of annotations on a Table * * @return Status of the API call */ virtual bf_status_t tableAnnotationsGet(AnnotationSet *annotations) const = 0; using TableApiSet = std::set<std::reference_wrapper<const TableApi>>; /** * @brief Get a set of APIs which are supported by this table. * * @param[out] tableApiset The set of APIs which are supported by this table * * @return Status of the API call */ virtual bf_status_t tableApiSupportedGet(TableApiSet *tableApis) const = 0; /** @} */ // End of group Table //// Key APIs /** * @name Key APIs * @{ */ /** * @brief Allocate key for the table * * @param[out] key_ret Key object returned * * @return Status of the API call */ virtual bf_status_t keyAllocate( std::unique_ptr<BfRtTableKey> *key_ret) const = 0; /** * @brief Get a vector of Key field IDs * * @param[out] id Vector of Key field IDs * * @return Status of the API call */ virtual bf_status_t keyFieldIdListGet(std::vector<bf_rt_id_t> *id) const = 0; /** * @brief Get field type of Key Field * * @param[in] field_id Field ID * @param[out] field_type Field Type (Exact/Ternary/LPM/Range) * * @return Status of the API call */ virtual bf_status_t keyFieldTypeGet(const bf_rt_id_t &field_id, KeyFieldType *field_type) const = 0; /** * @brief Get data type of Key Field * * @param[in] field_id Field ID * @param[out] data_type Field Type (uint64, float, string) * * @return Status of the API call */ virtual bf_status_t keyFieldDataTypeGet(const bf_rt_id_t &field_id, DataType *data_type) const = 0; /** * @brief Get field ID of Key Field from name * * @param[in] name Key Field name * @param[out] field_id Field ID * * @return Status of the API call */ virtual bf_status_t keyFieldIdGet(const std::string &name, bf_rt_id_t *field_id) const = 0; /** * @brief Get field size * * @param[in] field_id Field ID * @param[out] size Field Size in bits * * @return Status of the API call */ virtual bf_status_t keyFieldSizeGet(const bf_rt_id_t &field_id, size_t *size) const = 0; /** * @brief Get whether Key Field is of type ptr or not. If the field is * of ptr type, then only ptr sets/gets are applicable on the field. Else * both the ptr versions and the uint64_t versions work * * @param[in] field_id Field ID * @param[out] is_ptr Boolean type indicating whether Field is of type ptr * * @return Status of the API call */ virtual bf_status_t keyFieldIsPtrGet(const bf_rt_id_t &field_id, bool *is_ptr) const = 0; /** * @brief Get name of field * * @param[in] field_id Field ID * @param[out] name Field name * * @return Status of the API call */ virtual bf_status_t keyFieldNameGet(const bf_rt_id_t &field_id, std::string *name) const = 0; /** * @brief Reset the key object associated with the table * * @param[inout] Pointer to a key object, previously allocated using * keyAllocate on the table. * * @return Status of the API call. Error is returned if the key object is not *associated with the table. */ virtual bf_status_t keyReset(BfRtTableKey *key) const = 0; /** * @brief Get a list of all the allowed values that a particular field can * have. This API is only for fields with string type. If the returned * vector is empty, it indicates that the allowed choices have not been * published in bfrt json * * @param[in] field_id Field ID * @param[out] choices Vector of const references of the values that are * allowed for this field * * @return Status of the API call */ virtual bf_status_t keyFieldAllowedChoicesGet( const bf_rt_id_t &field_id, std::vector<std::reference_wrapper<const std::string>> *choices) const = 0; /** @} */ // End of group Key //// Data APIs /** * @name Data APIs * There are 2 base versions of every Data API. One, which takes in an * action_id and another which doesn't. If action_id is specified it will * always be set. * * @{ */ /** * @brief Allocate Data Object for the table * * @param[out] data_ret Data Object returned * * @return Status of the API call */ virtual bf_status_t dataAllocate( std::unique_ptr<BfRtTableData> *data_ret) const = 0; /** * @brief Allocate Data Object for the table * * @param[in] action_id Action ID * @param[out] data_ret Data Object returned * * @return Status of the API call */ virtual bf_status_t dataAllocate( const bf_rt_id_t &action_id, std::unique_ptr<BfRtTableData> *data_ret) const = 0; /** * @brief Data Allocate with a list of field-ids. This allocates the data * object for * the list of field-ids. The field-ids passed must be valid for this table. * The Data Object then entertains APIs to read/write only those set of fields * * @param[in] fields Vector of field IDs * @param[out] data_ret Data Object returned * * @return Status of the API call */ virtual bf_status_t dataAllocate( const std::vector<bf_rt_id_t> &fields, std::unique_ptr<BfRtTableData> *data_ret) const = 0; /** * @brief Data Allocate with a list of field-ids. This allocates the data * object for * the list of field-ids. The field-ids passed must be valid for this table. * The Data Object then entertains APIs to read/write only those set of fields * * @param[in] fields Vector of field IDs * @param[in] action_id Action ID * @param[out] data_ret Data Object returned * * @return Status of the API call */ virtual bf_status_t dataAllocate( const std::vector<bf_rt_id_t> &fields, const bf_rt_id_t &action_id, std::unique_ptr<BfRtTableData> *data_ret) const = 0; /** * @brief Data Allocate for a container field ID. Container ID * is field ID of a container field. If container ID doesn't * exist, then the API will fail * * @param[in] container_id Field ID of container * @param[out] data_ret Data Object returned * * @return Status of the API call */ virtual bf_status_t dataAllocateContainer( const bf_rt_id_t &container_id, std::unique_ptr<BfRtTableData> *data_ret) const = 0; /** * @brief Data Allocate for a container field ID. Container ID * is field ID of a container field. If container ID doesn't * exist for the action ID, the API will fail * * @param[in] container_id Field ID of container * @param[in] action_id Action ID * @param[out] data_ret Data Object returned * * @return Status of the API call */ virtual bf_status_t dataAllocateContainer( const bf_rt_id_t &container_id, const bf_rt_id_t &action_id, std::unique_ptr<BfRtTableData> *data_ret) const = 0; /** * @brief Data Allocate for a container field ID. Container ID * is field ID of a container field. If container ID doesn't * exist, then the API will fail. The field ID list should * contain fields only pertaining to the container for mod/ * get * * @param[in] container_id Field ID of container * @param[in] fields Vector of field IDs * @param[out] data_ret Data Object returned * * @return Status of the API call */ virtual bf_status_t dataAllocateContainer( const bf_rt_id_t &container_id, const std::vector<bf_rt_id_t> &fields, std::unique_ptr<BfRtTableData> *data_ret) const = 0; /** * @brief Data Allocate for a container field ID. Container ID * is field ID of a container field. If container ID doesn't * exist in the action ID, then the API will fail. * The field ID list should * contain fields only pertaining to the container for mod/ * get * * @param[in] container_id Field ID of container * @param[in] fields Vector of field IDs * @param[in] action_id Action ID * @param[out] data_ret Data Object returned * * @return Status of the API call */ virtual bf_status_t dataAllocateContainer( const bf_rt_id_t &container_id, const std::vector<bf_rt_id_t> &fields, const bf_rt_id_t &action_id, std::unique_ptr<BfRtTableData> *data_ret) const = 0; /** * @brief Get vector of DataField IDs. Only applicable for tables * without Action IDs * * @param[out] id Vector of IDs * * @return Status of the API call */ virtual bf_status_t dataFieldIdListGet(std::vector<bf_rt_id_t> *id) const = 0; /** * @brief Get vector of DataField IDs for a particular action. If action * doesn't exist, then common fields list is returned. * * @param[in] action_id Action ID * @param[out] id Vector of IDs * * @return Status of the API call */ virtual bf_status_t dataFieldIdListGet(const bf_rt_id_t &action_id, std::vector<bf_rt_id_t> *id) const = 0; /** * @brief Get vector of DataField IDs for a container's field id. * * @param[in] field Field ID of container * @param[out] id Vector of IDs * * @return Status of the API call */ virtual bf_status_t containerDataFieldIdListGet( const bf_rt_id_t &field_id, std::vector<bf_rt_id_t> *id) const = 0; /** * @brief Get the field ID of a Data Field from a name. * * @param[in] name Name of a Data field * @param[out] field_id Field ID * * @return Status of the API call */ virtual bf_status_t dataFieldIdGet(const std::string &name, bf_rt_id_t *field_id) const = 0; /** * @brief Get the field ID of a Data Field from a name * * @param[in] name Name of a Data field * @param[in] action_id Action ID * @param[out] field_id Field ID * * @return Status of the API call */ virtual bf_status_t dataFieldIdGet(const std::string &name, const bf_rt_id_t &action_id, bf_rt_id_t *field_id) const = 0; /** * @brief Get the Size of a field. * For container fields this function will return number * of elements inside the container. * * @param[in] field_id Field ID * @param[out] size Size of the field in bits * * @return Status of the API call */ virtual bf_status_t dataFieldSizeGet(const bf_rt_id_t &field_id, size_t *size) const = 0; /** * @brief Get the Size of a field. * * @param[in] field_id Field ID * @param[in] action_id Action ID * @param[out] size Size of the field in bits * * @return Status of the API call */ virtual bf_status_t dataFieldSizeGet(const bf_rt_id_t &field_id, const bf_rt_id_t &action_id, size_t *size) const = 0; /** * @brief Get whether a field is a ptr type. * Only the ptr versions of setValue/getValue will work on fields * for which this API returns true * * @param[in] field_id Field ID * @param[out] is_ptr Boolean value indicating if it is ptr type * * @return Status of the API call */ virtual bf_status_t dataFieldIsPtrGet(const bf_rt_id_t &field_id, bool *is_ptr) const = 0; /** * @brief Get whether a field is a ptr type. * Only the ptr versions of setValue/getValue will work on fields * for which this API returns true * * @param[in] field_id Field ID * @param[in] action_id Action ID * @param[out] is_ptr Boolean value indicating if it is ptr type * * @return Status of the API call */ virtual bf_status_t dataFieldIsPtrGet(const bf_rt_id_t &field_id, const bf_rt_id_t &action_id, bool *is_ptr) const = 0; /** * @brief Get whether a field is mandatory. * * @param[in] field_id Field ID * @param[out] is_mandatory Boolean value indicating if it is mandatory * * @return Status of the API call */ virtual bf_status_t dataFieldMandatoryGet(const bf_rt_id_t &field_id, bool *is_mandatory) const = 0; /** * @brief Get whether a field is mandatory. * * @param[in] field_id Field ID * @param[in] action_id Action ID * @param[out] is_mandatory Boolean value indicating if it is mandatory * * @return Status of the API call */ virtual bf_status_t dataFieldMandatoryGet(const bf_rt_id_t &field_id, const bf_rt_id_t &action_id, bool *is_mandatory) const = 0; /** * @brief Get whether a field is ReadOnly. * * @param[in] field_id Field ID * @param[out] is_read_only Boolean value indicating if it is ReadOnly * * @return Status of the API call */ virtual bf_status_t dataFieldReadOnlyGet(const bf_rt_id_t &field_id, bool *is_read_only) const = 0; /** * @brief Get the IDs of oneof siblings of a field. If a field is part of a * oneof , for example, consider $ACTION_MEMBER_ID and $SELECTOR_GROUP_ID. then * this API will return [field_ID($ACTION_MEMBER_ID)] for $SELECTOR_GROUP_ID. * * * @param[in] field_id Field ID * @param[out] oneof_siblings Set containing field IDs of oneof siblings * * @return Status of the API call */ virtual bf_status_t dataFieldOneofSiblingsGet( const bf_rt_id_t &field_id, const bf_rt_id_t &action_id, std::set<bf_rt_id_t> *oneof_siblings) const = 0; /** * @brief Get the IDs of oneof siblings of a field. If a field is part of a * oneof , for example, consider $ACTION_MEMBER_ID and $SELECTOR_GROUP_ID. then * this API will return [field_ID($ACTION_MEMBER_ID)] for $SELECTOR_GROUP_ID. * * * @param[in] field_id Field ID * @param[out] oneof_siblings Set containing field IDs of oneof siblings * * @return Status of the API call */ virtual bf_status_t dataFieldOneofSiblingsGet( const bf_rt_id_t &field_id, std::set<bf_rt_id_t> *oneof_siblings) const = 0; /** * @brief Get whether a field is ReadOnly. * * @param[in] field_id Field ID * @param[in] action_id Action ID * @param[out] is_read_only Boolean value indicating if it is ReadOnly * * @return Status of the API call */ virtual bf_status_t dataFieldReadOnlyGet(const bf_rt_id_t &field_id, const bf_rt_id_t &action_id, bool *is_read_only) const = 0; /** * @brief Get the Name of a field. * * @param[in] field_id Field ID * @param[out] name Name of the field * * @return Status of the API call */ virtual bf_status_t dataFieldNameGet(const bf_rt_id_t &field_id, std::string *name) const = 0; /** * @brief Get the Name of a field * * @param[in] field_id Field ID * @param[in] action_id Action ID * @param[out] name Name of the field * * @return Status of the API call */ virtual bf_status_t dataFieldNameGet(const bf_rt_id_t &field_id, const bf_rt_id_t &action_id, std::string *name) const = 0; /** * @brief Get the Data type of a field (INT/BOOL/ENUM/INT_ARR/BOOL_ARR) * * @param[in] field_id Field ID * @param[out] type Data type of a data field * * @return Status of the API call */ virtual bf_status_t dataFieldDataTypeGet(const bf_rt_id_t &field_id, DataType *type) const = 0; /** * @brief Get the Data type of a field (INT/BOOL/ENUM/INT_ARR/BOOL_ARR) * * @param[in] field_id Field ID * @param[in] action_id Action ID * @param[out] type Data type of a data field * * @return Status of the API call */ virtual bf_status_t dataFieldDataTypeGet(const bf_rt_id_t &field_id, const bf_rt_id_t &action_id, DataType *type) const = 0; /** * @brief Reset the data object previously allocated using dataAllocate on the * table * * @details Calling this API resets the action-id in the object to an * invalid value. Typically this needs to be done when doing an entry get, * since the caller does not know the action-id associated with the entry. * Using the data object for an entry add on a table where action-id is * applicable will result in an error. * * @param[in/out] data Pointer to the data object allocated using dataAllocate * on the table. * * @return Status of the API call. An error is returned if the data object is * not associated with the table */ virtual bf_status_t dataReset(BfRtTableData *data) const = 0; /** * @brief Reset the data object previously allocated using dataAllocate on the * table * * @details Calling this API sets the action-id in the object to the * passed in value. * * @param[in] action_id new action id of the object * the table. * @param[in/out] Pointer to the data object allocated using dataAllocate on * the table. * * @return Status of the API call. An error is returned if the data object is * not associated with the table or if action-id is not applicable on the * table. */ virtual bf_status_t dataReset(const bf_rt_id_t &action_id, BfRtTableData *data) const = 0; /** * @brief Reset the data object previously allocated using dataAllocate on the *table * * @details Calling this API resets the action-id in the object to an * invalid value. Typically this needs to be done when doing an entry get, * since the caller does not know the action-id associated with the entry. * Using the data object for an entry add on a table where action-id is * applicable will result in an error. The data object will contain the passed * in vector of field-ids active. This is typically done when reading an * entry's fields. Note that, the fields passed in must be common data fields * across all action-ids (common data fields, such as direct counter/direct * meter etc), for tables on which action-id is applicable. * * @param[in] fields Vector of field-ids that are to be activated in the data * object the table. * @param[in/out] Pointer to the data object allocated using dataAllocate on * the table. * * @return Status of the API call. An error is returned if the data object is * not associated with the table, or if any field-id is action-specific, for * tables on which action-id is applicable.. */ virtual bf_status_t dataReset(const std::vector<bf_rt_id_t> &fields, BfRtTableData *data) const = 0; /** * @brief Reset the data object previously allocated using dataAllocate on the * table * * @details Calling this API sets the action-id in the object to the * passed in value and the list of fields passed in will be active in the data * object. The list of fields passed in must belong to the passed in action-id * or common across all action-ids associated with the table. * * @param[in] fields Vector of field-ids that are to be activated in the data * object the table. * @param[in] action_id new action id of the object * the table. * @param[in/out] Pointer to the data object allocated using dataAllocate on * the table. * * @return Status of the API call. An error is returned if the data object is * not associated with the table or if action-id is not applicable on the * table. */ virtual bf_status_t dataReset(const std::vector<bf_rt_id_t> &fields, const bf_rt_id_t &action_id, BfRtTableData *data) const = 0; /** * @brief Get a list of all the allowed values that a particular field can * have. This API is only for fields with string type. If the returned * vector is empty, it indicates that the allowed choices have not been * published in bfrt json * * @param[in] field_id Field ID * @param[out] choices Vector of const references of the values that are * allowed for this field * * @return Status of the API call */ virtual bf_status_t dataFieldAllowedChoicesGet( const bf_rt_id_t &field_id, std::vector<std::reference_wrapper<const std::string>> *choices) const = 0; /** * @brief Get a list of all the allowed values that a particular field can * have. This API is only for fields with string type. If the returned * vector is empty, it indicates that the allowed choices have not been * published in bfrt json * * @param[in] field_id Field ID * @param[in] action_id Action ID * @param[out] choices Vector of const references of the values that are * allowed for this field * * @return Status of the API call */ virtual bf_status_t dataFieldAllowedChoicesGet( const bf_rt_id_t &field_id, const bf_rt_id_t &action_id, std::vector<std::reference_wrapper<const std::string>> *choices) const = 0; /** * @brief Get a set of annotations on a data field * * @param[in] field_id Field ID * @param[out] annotations Set of annotations on a data field * * @return Status of the API call */ virtual bf_status_t dataFieldAnnotationsGet( const bf_rt_id_t &field_id, AnnotationSet *annotations) const = 0; /** * @brief Get a set of annotations on a data field * * @param[in] field_id Field ID * @param[in] action_id Action ID * @param[out] annotations Set of annotations on a data field * * @return Status of the API call */ virtual bf_status_t dataFieldAnnotationsGet( const bf_rt_id_t &field_id, const bf_rt_id_t &action_id, AnnotationSet *annotations) const = 0; /** @} */ // End of group Data // Action ID APIs /** * @name Action ID APIs * @{ */ /** * @brief Get Action ID from Name * * @param[in] name Action Name * @param[out] action_id Action ID * * @return Status of the API call */ virtual bf_status_t actionIdGet(const std::string &name, bf_rt_id_t *action_id) const = 0; /** * @brief Get Action Name * * @param[in] action_id Action ID * @param[out] name Action Name * * @return Status of the API call */ virtual bf_status_t actionNameGet(const bf_rt_id_t &action_id, std::string *name) const = 0; /** * @brief Get vector of Action IDs * * @param[out] action_id Vector of Action IDs * * @return Status of the API call */ virtual bf_status_t actionIdListGet( std::vector<bf_rt_id_t> *action_id) const = 0; /** * @brief Are Action IDs applicable for this table * * @retval True : If Action ID applicable * @retval False : If not * */ virtual bool actionIdApplicable() const = 0; /** * @brief Get a set of annotations for this action. * * @param[in] action_id Action ID * @param[out] annotations Set of annotations * * @return Status of the API call */ virtual bf_status_t actionAnnotationsGet( const bf_rt_id_t &action_id, AnnotationSet *annotations) const = 0; /** @} */ // End of group Action IDs // table attribute APIs /** * @name Attribute APIs * @{ */ /** * @brief Allocate Attribute object of the table. * * @param[in] type Type of the attribute * @param[out] attr Attribute object returned * * @return Status of the API call */ virtual bf_status_t attributeAllocate( const TableAttributesType &type, std::unique_ptr<BfRtTableAttributes> *attr) const = 0; /** * @brief Allocate Attribute object of the table. This API * is to be used when idle_table attribute is being set * * @param[in] type Type of the attribute * @param[in] idle_table_type Idle table type (POLL/NOTIFY) * @param[out] attr Attribute object returned * * @return Status of the API call */ virtual bf_status_t attributeAllocate( const TableAttributesType &type, const TableAttributesIdleTableMode &idle_table_type, std::unique_ptr<BfRtTableAttributes> *attr) const = 0; /** * @brief Reset Attribute object of the table. * * @param[in] type Type of the attribute * @param[out] attr Attribute object returned * * @return Status of the API call */ virtual bf_status_t attributeReset( const TableAttributesType &type, std::unique_ptr<BfRtTableAttributes> *attr) const = 0; /** * @brief Reset Attribute type and the Idle Table Mode * * @param[in] type Type of the attribute * @param[in] idle_table_type Idle table type (POLL/NOTIFY) * @param[out] attr Attribute object returned * * @return Status of the API call */ virtual bf_status_t attributeReset( const TableAttributesType &type, const TableAttributesIdleTableMode &idle_table_type, std::unique_ptr<BfRtTableAttributes> *attr) const = 0; /** * @name Old flags wrapper section * @{ */ /** * @brief Apply an Attribute from an Attribute Object on the * table. Before using this API, the Attribute object needs to * be allocated and all the necessary values need to * be set on the Attribute object * @deprecated Please use function version with new flags argument. * * @param[in] session Session Object * @param[in] dev_tgt Device Target * @param[in] tableAttributes Attribute Object * * @return Status of the API call */ virtual bf_status_t tableAttributesSet( const BfRtSession &session, const bf_rt_target_t &dev_tgt, const BfRtTableAttributes &tableAttributes) const = 0; /** * @brief Get the current Attributes set on the table. The attribute * object passed in as input param needs to be allocated first with * the required attribute type. * @deprecated Please use function version with new flags argument. * * @param[in] session Session Object * @param[in] dev_tgt Device Target * @param[out] tableAttributes Attribute Object * * @return Status of the API call */ virtual bf_status_t tableAttributesGet( const BfRtSession &session, const bf_rt_target_t &dev_tgt, BfRtTableAttributes *tableAttributes) const = 0; /** @} */ // End of old flags wrapper section */ /** * @brief Apply an Attribute from an Attribute Object on the * table. Before using this API, the Attribute object needs to * be allocated and all the necessary values need to * be set on the Attribute object * * @param[in] session Session Object * @param[in] dev_tgt Device Target * @param[in] flags Call flags * @param[in] tableAttributes Attribute Object * * @return Status of the API call */ virtual bf_status_t tableAttributesSet( const BfRtSession &session, const bf_rt_target_t &dev_tgt, const uint64_t &flags, const BfRtTableAttributes &tableAttributes) const = 0; /** * @brief Get the current Attributes set on the table. The attribute * object passed in as input param needs to be allocated first with * the required attribute type. * * @param[in] session Session Object * @param[in] dev_tgt Device Target * @param[in] flags Call flags * @param[out] tableAttributes Attribute Object * * @return Status of the API call */ virtual bf_status_t tableAttributesGet( const BfRtSession &session, const bf_rt_target_t &dev_tgt, const uint64_t &flags, BfRtTableAttributes *tableAttributes) const = 0; /** * @brief Get the set of supported attributes * * @param[out] type_set Set of the supported Attributes * * @return Status of the API call */ virtual bf_status_t tableAttributesSupported( std::set<TableAttributesType> *type_set) const = 0; /** @} */ // End of group Attributes // table operations APIs /** * @name Operations APIs * @{ */ /** * @brief Allocate Operations object * * @param[in] type Operations type * @param[out] table_ops Operations Object returned * * @return Status of the API call */ virtual bf_status_t operationsAllocate( const TableOperationsType &type, std::unique_ptr<BfRtTableOperations> *table_ops) const = 0; /** * @brief Get set of supported Operations * * @param[out] type_set Set of supported Operations * * @return Status of the API call */ virtual bf_status_t tableOperationsSupported( std::set<TableOperationsType> *type_set) const = 0; /** * @brief Execute Operations on a table. User * needs to allocate operation object with correct * type and then pass it to this API * * @param[in] tableOperations Operations Object * * @return Status of the API call */ virtual bf_status_t tableOperationsExecute( const BfRtTableOperations &tableOperations) const = 0; /** @} */ // End of group Operations }; } // bfrt #endif // _BF_RT_TABLE_HPP
34.462011
80
0.630262
mestery
428076b9e4ff076bd95fb24def4b4ac59b016772
2,905
inl
C++
Engine/Core/Headers/Molten/Renderer/Shader/Visual/VisualShaderConstant.inl
jimmiebergmann/CurseEngine
74a0502e36327f893c8e4f3e7cbe5b9d38fbe194
[ "MIT" ]
2
2019-11-11T21:17:14.000Z
2019-11-11T22:07:26.000Z
Engine/Core/Headers/Molten/Renderer/Shader/Visual/VisualShaderConstant.inl
jimmiebergmann/CurseEngine
74a0502e36327f893c8e4f3e7cbe5b9d38fbe194
[ "MIT" ]
null
null
null
Engine/Core/Headers/Molten/Renderer/Shader/Visual/VisualShaderConstant.inl
jimmiebergmann/CurseEngine
74a0502e36327f893c8e4f3e7cbe5b9d38fbe194
[ "MIT" ]
1
2020-04-05T03:50:57.000Z
2020-04-05T03:50:57.000Z
/* * MIT License * * Copyright (c) 2021 Jimmie Bergmann * * 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. * */ namespace Molten::Shader::Visual { // Constant implementations. template<typename TDataType> OutputPin<TDataType>& Constant<TDataType>::GetOutput() { return m_output; } template<typename TDataType> const OutputPin<TDataType>& Constant<TDataType>::GetOutput() const { return m_output; } template<typename TDataType> VariableDataType Constant<TDataType>::GetDataType() const { return VariableTrait<TDataType>::dataType; } template<typename TDataType> size_t Constant<TDataType>::GetOutputPinCount() const { return 1; } template<typename TDataType> Pin* Constant<TDataType>::GetOutputPin(const size_t index) { if (index >= 1) { return nullptr; } return &m_output; } template<typename TDataType> const Pin* Constant<TDataType>::GetOutputPin(const size_t index) const { if (index >= 1) { return nullptr; } return &m_output; } template<typename TDataType> std::vector<Pin*> Constant<TDataType>::GetOutputPins() { return { &m_output }; } template<typename TDataType> std::vector<const Pin*> Constant<TDataType>::GetOutputPins() const { return { &m_output }; } template<typename TDataType> const TDataType& Constant<TDataType>::GetValue() const { return m_value; } template<typename TDataType> void Constant<TDataType>::SetValue(const TDataType& value) { m_value = value; } template<typename TDataType> Constant<TDataType>::Constant(Script& script, const TDataType& value) : ConstantBase(script), m_value(value), m_output(*this) {} }
28.203883
80
0.67642
jimmiebergmann
4282699a05745276022b2dfd0b68112ee07565d8
2,255
cpp
C++
src/Hola_Common/src/Base/ShaderCompiler.cpp
dfnzhc/Hola
d0fd46e9966baafd03c994e49efaa3dd8057309e
[ "MIT" ]
null
null
null
src/Hola_Common/src/Base/ShaderCompiler.cpp
dfnzhc/Hola
d0fd46e9966baafd03c994e49efaa3dd8057309e
[ "MIT" ]
null
null
null
src/Hola_Common/src/Base/ShaderCompiler.cpp
dfnzhc/Hola
d0fd46e9966baafd03c994e49efaa3dd8057309e
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "ShaderCompiler.h" #include "Misc/Misc.h" //-------------------------------------------------------------------------------------- // 哈希一串源代码,并在它的 #include 文件中递归 //-------------------------------------------------------------------------------------- size_t HashShaderString(const char *pRootDir, const char *pShader, size_t hash) { hash = Hash(pShader, strlen(pShader), hash); const char *pch = pShader; while (*pch != 0) { if (*pch == '/') // parse comments { pch++; if (*pch != 0 && *pch == '/') { pch++; while (*pch != 0 && *pch != '\n') pch++; } else if (*pch != 0 && *pch == '*') { pch++; while ( (*pch != 0 && *pch != '*') && (*(pch+1) != 0 && *(pch+1) != '/')) pch++; } } else if (*pch == '#') // parse #include { pch++; const char include[] = "include"; int i = 0; while ((*pch!= 0) && *pch == include[i]) { pch++; i++; } if (i == strlen(include)) { while (*pch != 0 && *pch == ' ') pch++; if (*pch != 0 && *pch == '\"') { pch++; const char *pName = pch; while (*pch != 0 && *pch != '\"') pch++; char includeName[1024]; strcpy_s<1024>(includeName, pRootDir); strncat_s<1024>(includeName, pName, pch - pName); pch++; char *pShaderCode = NULL; if (ReadFile(includeName, &pShaderCode, NULL, false)) { hash = HashShaderString(pRootDir, pShaderCode, hash); free(pShaderCode); } } } } else { pch++; } } return hash; }
29.285714
89
0.2949
dfnzhc
4285112808835de0c0cd70175a6e99999ba1b8b8
1,852
cpp
C++
modules/task_2/vodeneev_m_broadcast/ops_mpi.cpp
Vodeneev/pp_2020_autumn_math
9b7e5ec56e09474c9880810a6124e3e416bb7e16
[ "BSD-3-Clause" ]
null
null
null
modules/task_2/vodeneev_m_broadcast/ops_mpi.cpp
Vodeneev/pp_2020_autumn_math
9b7e5ec56e09474c9880810a6124e3e416bb7e16
[ "BSD-3-Clause" ]
null
null
null
modules/task_2/vodeneev_m_broadcast/ops_mpi.cpp
Vodeneev/pp_2020_autumn_math
9b7e5ec56e09474c9880810a6124e3e416bb7e16
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2020 Mikhail Vodeneev #include <mpi.h> #include <math.h> #include <random> #include <ctime> #include <vector> #include <algorithm> #include "../../../modules/test_tasks/test_mpi/ops_mpi.h" int Bcast(void* buffer, int count, MPI_Datatype datatype, int root, MPI_Comm comm) { int size, rank; MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (root > size) { printf("Error"); return 1; } if ((size == 1) && (root != 0)) { printf("Error"); return 1; } if (root != 0) { if (rank == root) { MPI_Send(buffer, count, datatype, 0, 0, MPI_COMM_WORLD); } else if (rank == 0) { MPI_Status status; MPI_Recv(buffer, count, datatype, root, 0, MPI_COMM_WORLD, &status); } } if ((size == 1) && (root != 0)) { printf("Error"); return 1; } if (size == 1) { return 0; } if (size == 2) { if (rank == 0) { MPI_Send(buffer, count, datatype, 1, 0, MPI_COMM_WORLD); } else { MPI_Status status; MPI_Recv(buffer, count, datatype, 0, 0, MPI_COMM_WORLD, &status); } return 0; } if (rank == 0) { MPI_Send(buffer, count, datatype, 1, 0, MPI_COMM_WORLD); MPI_Send(buffer, count, datatype, 2, 0, MPI_COMM_WORLD); } else { MPI_Status status; MPI_Recv(buffer, count, datatype, (rank - 1) / 2, 0, MPI_COMM_WORLD, &status); if (2 * rank + 1 < size) { MPI_Send(buffer, count, datatype, 2 * rank + 1, 0, MPI_COMM_WORLD); } if (2 * rank + 2 < size) { MPI_Send(buffer, count, datatype, 2 * rank + 2, 0, MPI_COMM_WORLD); } } return 0; }
25.369863
80
0.513499
Vodeneev