blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 905
values | visit_date
timestamp[us]date 2015-08-09 11:21:18
2023-09-06 10:45:07
| revision_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-17 19:19:19
| committer_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-06 06:22:19
| github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-07 00:51:45
2023-09-14 21:58:39
⌀ | gha_created_at
timestamp[us]date 2008-03-27 23:40:48
2023-08-21 23:17:38
⌀ | gha_language
stringclasses 141
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 115
values | content
stringlengths 3
10.4M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
158
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e95f798991e2a30213616e1fc98ee445a273a12b | 05aed5fde6736718bd592193569056b8b2aff14f | /tergeo/include/tergeo/planning/base_planning.h | 7ee9e43b995276f6a017dffe502d6ff456858f92 | [] | no_license | csLinZhang/cncr | 39b33e7594b7950cde9ba294f728e5e8b0cfd9d8 | 540b708d086bea15c88c6b2863db13b6d3aba7e9 | refs/heads/master | 2023-07-04T08:23:02.193127 | 2021-08-11T08:02:21 | 2021-08-11T08:02:21 | 394,889,133 | 6 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 635 | h | #ifndef _TERGEO_PLANNING_BASE_PLANNING_H
#define _TERGEO_PLANNING_BASE_PLANNING_H
#include "tergeo/common/common.hpp"
#include <ros_msgs/PlanningPath.h>
namespace tergeo {
namespace planning {
class BasePlanning : public tergeo::core::IPlugin {
DECLARE_FACTORY(BasePlanning)
DECLARE_DEFAULT_STRUCTOR(BasePlanning)
public:
virtual common::Status init() = 0;
virtual common::Status start() = 0;
virtual void stop() = 0;
virtual bool plan(ros_msgs::PlanningPath &planning_path) = 0;
};
#define REGISTER_PLANNING_CLASS_CPP(sub_class) \
REGISTER_CLASS_CPP(tergeo::planning::BasePlanning, sub_class)
}
}
#endif | [
"[email protected]"
] | |
37ed3b31090361314359633839449c657095b9cb | 019870db548f9dbad19093de581d75686d68d6ca | /src/game/FlyStraightController.h | 0e2823468479d0ca90ae50fdebb2c5d31fae501b | [
"WTFPL"
] | permissive | davidhhyq/JVGS | cf8c54f6e557b1b31960cdd11ea03e1713e107f1 | 59be35ed61b355b445b82bf32796c0f229e21b60 | refs/heads/master | 2020-06-17T14:19:03.785109 | 2014-11-12T09:48:17 | 2014-11-12T09:48:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,078 | h | #ifndef JVGS_GAME_FLYSTRAIGHTCONTROLLER_H
#define JVGS_GAME_FLYSTRAIGHTCONTROLLER_H
#include "Controller.h"
namespace jvgs
{
namespace game
{
/** A controller that keeps the velocity of the entity.
*/
class FlyStraightController: public Controller
{
protected:
/* Override
*/
void loadData(TiXmlElement *element);
public:
/** Constructor.
* @param entity Entity to control.
*/
FlyStraightController(Entity *entity);
/** Constructor.
* @param entity Entity to control.
* @param element TiXmlElement to load data from.
*/
FlyStraightController(Entity *entity, TiXmlElement *element);
/** Destructor.
*/
virtual ~FlyStraightController();
/* Override
*/
virtual void affect(float ms);
};
}
}
#endif
| [
"[email protected]"
] | |
24806fbe19e5c38fe50634586c614d4e6cd62fac | f15d6c870d51ffa4a7e6151c42ceb5de0eedf46a | /ThirdParty/paraEllip3d_DEM_PD/src/Boundary/BoundaryTangent.h | 9b071795fc0493f721336ae7d1b59268d3690666 | [] | no_license | pinebai/ParSim | 1a5ee3687bd1582f31be9dbd88b3914769549095 | f787523ae6c47c87ff1a74e199c7068ca45dc780 | refs/heads/master | 2021-01-24T07:45:12.923015 | 2017-04-22T04:34:44 | 2017-04-22T04:34:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 788 | h | #ifndef BOUNDARY_TANGENT_H
#define BOUNDARY_TANGENT_H
#include <Core/Math/Vec.h>
#include <Core/Types/realtypes.h>
namespace dem {
/////////////////////////////////////
class BoundaryTangent
{
public:
std::size_t particleId;
Vec tgtForce;
Vec tgtDisp;
bool tgtLoading;
Vec tgtDispStart;
REAL tgtPeak;
public:
BoundaryTangent()
: particleId(0)
, tgtForce(0)
, tgtDisp(0)
, tgtLoading(false)
, tgtDispStart(0)
, tgtPeak(0)
{
}
BoundaryTangent(std::size_t _particleId, Vec _v1, Vec _v2, bool _b, Vec _v3,
REAL _tp)
: particleId(_particleId)
, tgtForce(std::move(_v1))
, tgtDisp(std::move(_v2))
, tgtLoading(_b)
, tgtDispStart(std::move(_v3))
, tgtPeak(_tp)
{
}
};
} // end namespace dem
#endif
| [
"[email protected]"
] | |
f4a06c8300bc9e4c5c8385189a96f2f72c547a4f | 73a8f3c9c640af08acbefe657bff62e3d1751fc2 | /Dependencies/Qt-5.4.1/include/QtLocation/qplacecontentrequest.h | 8971f2af3fc8a666b10adafe53d8a23afc3f5d3d | [] | no_license | knight666/pitstop | 8d5ad076a71055803df1601e1df1640430ad56ca | 4e541d90507f38f36274e50b0d702a284d648e27 | refs/heads/master | 2020-07-10T00:51:28.141786 | 2019-08-24T20:08:02 | 2019-08-24T20:08:02 | 204,123,196 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,786 | h | /****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtLocation module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QPLACECONTENTREQUEST_H
#define QPLACECONTENTREQUEST_H
#include <QSharedDataPointer>
#include <QtLocation/QPlaceContent>
QT_BEGIN_NAMESPACE
class QPlaceContentRequestPrivate;
class Q_LOCATION_EXPORT QPlaceContentRequest
{
public:
QPlaceContentRequest();
QPlaceContentRequest(const QPlaceContentRequest &other);
~QPlaceContentRequest();
QPlaceContentRequest &operator=(const QPlaceContentRequest &other);
bool operator==(const QPlaceContentRequest &other) const;
bool operator!=(const QPlaceContentRequest &other) const;
QPlaceContent::Type contentType() const;
void setContentType(QPlaceContent::Type type);
QString placeId() const;
void setPlaceId(const QString &identifier);
QVariant contentContext() const;
void setContentContext(const QVariant &context);
int limit() const;
void setLimit(int limit);
void clear();
private:
QSharedDataPointer<QPlaceContentRequestPrivate> d_ptr;
inline QPlaceContentRequestPrivate *d_func();
inline const QPlaceContentRequestPrivate *d_func() const;
};
QT_END_NAMESPACE
#endif
| [
"[email protected]"
] | |
ecf50d2c8b646fc469a89887d1532157b14613a1 | 110be4334b1caea9558a7bb8619944a66cdc8b0f | /Finite State Machines/FiniteStateMachineWithMessages/ProgramadorStates.cpp | 4e3cccfe8d73573c6e29a238b50a9439835d0c93 | [] | no_license | BarcampRD/Basic_Game_AI_Barcamp2014 | e5ae467b4ee59483172dc41630b8d60d851384ed | fa24a8d46e3821ce006e40aa32373945fe6989e2 | refs/heads/master | 2021-01-16T00:05:01.678986 | 2014-11-29T18:42:57 | 2014-11-29T18:42:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,771 | cpp | #include "Programador.h"
#include "ProgramadorStates.h"
#include "State.h"
#include "StateMachine.h"
#include "Locations.h"
#include "MessageDispatcher.h"
#include "MessageTypes.h"
#include <Windows.h>
#include <iostream>
using std::cout;
Program* Program::Instance()
{
static Program instance;
return &instance;
}
void Program::Enter(Programador* programador)
{
if (programador->Location() != work)
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 2);
cout << "\n" << "Juan" << ": " << "Es Hora de ponerse a Trabajar";
programador->ChangeLocation(work);
}
}
void Program::Execute(Programador* programador)
{
programador->WorkHour();
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 2);
cout << "\n" << "Juan" << ": " << "Codear es lo maximo";
if (programador->Sleepy())
{
programador->GetFSM()->ChangeState(Sleeping::Instance());
}
}
void Program::Exit(Programador* programador)
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 2);
cout << "\n" << "Juan" << ": " << "Suficiente codeo por hoy";
}
bool Program::OnMessage(Programador* pProgramador, const Telegram& msg)
{
return false;
}
Sleeping* Sleeping::Instance()
{
static Sleeping instance;
return &instance;
}
void Sleeping::Enter(Programador* programador)
{
if (programador->Location() != house)
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 2);
cout << "\n" << "Juan" << ": " << "A dormir un ratico";
programador->ChangeLocation(house);
}
}
void Sleeping::Execute(Programador* programador)
{
programador->SleepHour();
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 2);
cout << "\n" << "Juan" << ": " << "ZZZZZZZZZZZZZZZZZZ";
if (programador->SleepEnough())
{
programador->GetFSM()->ChangeState(Program::Instance());
}
}
void Sleeping::Exit(Programador* programador)
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 2);
cout << "\n" << "Juan" << ": " << "Otra buena siesta!!!!";
}
bool Sleeping::OnMessage(Programador* pProgramador, const Telegram& msg)
{
return false;
}
Global* Global::Instance()
{
static Global instance;
return &instance;
}
void Global::Enter(Programador* programador)
{}
void Global::Execute(Programador* programador)
{
if (programador->IsBored()){
programador->GetFSM()->ChangeState(DrinkBeer::Instance());
}
}
void Global::Exit(Programador* programador)
{}
bool Global::OnMessage(Programador* pProgramador, const Telegram& msg)
{
return false;
}
DrinkBeer* DrinkBeer::Instance()
{
static DrinkBeer instance;
return &instance;
}
void DrinkBeer::Enter(Programador* programador)
{
if (programador->Location() != bar)
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 2);
cout << "\n" << "Juan" << ": " << "Que aburrido estoy, vamos a beber un chin!!";
programador->ChangeLocation(bar);
programador->Drink();
Dispatch->DispatchMessage1(1, programador->ID(), 1, Msg_GiveMeBeer, NO_ADDITIONAL_INFO);
}
}
void DrinkBeer::Execute(Programador* programador)
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 2);
programador->HourInBar();
if (programador->Has_Drink())
{
cout << "\n" << "Juan" << ": " << "Esta buena la cerveza";
programador->Drink();
}
else
{
cout << "\n" << "Juan" << ": " << "Esperando mi bebida!!";
}
if (programador->NotBored())
{
programador->GetFSM()->RevertToPreviousState();
}
}
void DrinkBeer::Exit(Programador* programador)
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 2);
cout << "\n" << "Juan" << ": " << "Suficiente alcohol por ahora";
programador->FinishDrink();
}
bool DrinkBeer::OnMessage(Programador* programador, const Telegram& msg)
{
switch (msg.Msg)
{
case Msg_BeerReady:
{
programador->GetDrink();
return true;
}
}
return false;
} | [
"[email protected]"
] | |
829c8ad8b0a232336278a3a92f259452b1bf90b4 | a856ac02297bd3a1a115437216f82557092d3919 | /node_modules/react-native-windows/Microsoft.ReactNative/ReactHost/ReactInstanceWin.cpp | 81cc59e58adb8eb9a3795376b213581bacf06a7a | [
"MIT"
] | permissive | ashimiblessing/gopays | 599fbc1524ed928b4cdb085206487d700a319302 | 424024a2890a4595b9c56479477bae080fdbab3b | refs/heads/master | 2023-07-14T11:22:13.607122 | 2021-08-23T16:53:01 | 2021-08-23T16:53:01 | 399,151,997 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 30,855 | cpp | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "ReactInstanceWin.h"
#include "MoveOnCopy.h"
#include "MsoUtils.h"
#include <Base/CoreNativeModules.h>
#include <ReactUWP/CreateUwpModules.h>
#include <ReactUWP/Modules/I18nModule.h>
#include <Threading/MessageDispatchQueue.h>
#include <XamlUIService.h>
#include "ReactErrorProvider.h"
#include "Microsoft.ReactNative/Threading/MessageQueueThreadFactory.h"
#include "../../codegen/NativeClipboardSpec.g.h"
#include "NativeModules.h"
#include "NativeModulesProvider.h"
#include "Unicode.h"
#include <ReactWindowsCore/ViewManager.h>
#include <dispatchQueue/dispatchQueue.h>
#include "IReactDispatcher.h"
#include "Modules/AppStateData.h"
#include "Modules/ClipboardModule.h"
#include "Modules/DevSettingsModule.h"
#include <Utils/UwpPreparedScriptStore.h>
#include <Utils/UwpScriptStore.h>
#if defined(USE_HERMES)
#include "HermesRuntimeHolder.h"
#endif // USE_HERMES
#if defined(USE_V8)
#include <winrt/Windows.Storage.h>
#include "BaseScriptStoreImpl.h"
#include "V8JSIRuntimeHolder.h"
#endif // USE_V8
#include "RedBox.h"
#include <tuple>
#include "ChakraRuntimeHolder.h"
namespace react::uwp {
void AddStandardViewManagers(
std::vector<std::unique_ptr<facebook::react::IViewManager>> &viewManagers,
std::shared_ptr<IReactInstance> const &instance) noexcept;
void AddPolyesterViewManagers(
std::vector<std::unique_ptr<facebook::react::IViewManager>> &viewManagers,
std::shared_ptr<IReactInstance> const &instance) noexcept;
std::shared_ptr<facebook::react::IUIManager> CreateUIManager2(
std::vector<react::uwp::NativeViewManager> &&viewManagers) noexcept;
} // namespace react::uwp
namespace Mso::React {
//=============================================================================================
// ReactContext implementation
//=============================================================================================
ReactContext::ReactContext(
Mso::WeakPtr<ReactInstanceWin> &&reactInstance,
winrt::Microsoft::ReactNative::IReactPropertyBag const &properties) noexcept
: m_reactInstance{std::move(reactInstance)}, m_properties{properties} {}
winrt::Microsoft::ReactNative::IReactPropertyBag ReactContext::Properties() noexcept {
return m_properties;
}
void ReactContext::CallJSFunction(std::string &&module, std::string &&method, folly::dynamic &¶ms) noexcept {
if (auto instance = m_reactInstance.GetStrongPtr()) {
instance->CallJsFunction(std::move(module), std::move(method), std::move(params));
}
}
void ReactContext::DispatchEvent(int64_t viewTag, std::string &&eventName, folly::dynamic &&eventData) noexcept {
if (auto instance = m_reactInstance.GetStrongPtr()) {
instance->DispatchEvent(viewTag, std::move(eventName), std::move(eventData));
}
}
//=============================================================================================
// LoadedCallbackGuard ensures that the OnReactInstanceLoaded is always called.
// It calls OnReactInstanceLoaded in destructor with a cancellation error.
// If loading was previously succeeded this call with an error code is ignored.
//=============================================================================================
struct LoadedCallbackGuard {
LoadedCallbackGuard(ReactInstanceWin &reactInstance) noexcept : m_reactInstance{&reactInstance} {}
LoadedCallbackGuard(const LoadedCallbackGuard &other) = delete;
LoadedCallbackGuard &operator=(const LoadedCallbackGuard &other) = delete;
LoadedCallbackGuard(LoadedCallbackGuard &&other) = default;
LoadedCallbackGuard &operator=(LoadedCallbackGuard &&other) = default;
~LoadedCallbackGuard() noexcept {
if (m_reactInstance) {
m_reactInstance->OnReactInstanceLoaded(Mso::CancellationErrorProvider().MakeErrorCode(true));
}
}
private:
Mso::CntPtr<ReactInstanceWin> m_reactInstance;
};
//=============================================================================================
// ReactInstanceWin implementation
//=============================================================================================
ReactInstanceWin::ReactInstanceWin(
IReactHost &reactHost,
ReactOptions const &options,
Mso::Promise<void> &&whenCreated,
Mso::Promise<void> &&whenLoaded,
Mso::VoidFunctor &&updateUI) noexcept
: Super{reactHost.NativeQueue()},
m_weakReactHost{&reactHost},
m_options{options},
m_whenCreated{std::move(whenCreated)},
m_whenLoaded{std::move(whenLoaded)},
m_updateUI{std::move(updateUI)},
m_reactContext{Mso::Make<ReactContext>(this, options.Properties)},
m_legacyInstance{std::make_shared<react::uwp::UwpReactInstanceProxy>(
Mso::WeakPtr<Mso::React::IReactInstance>{this},
Mso::Copy(options.LegacySettings))} {
m_whenCreated.SetValue();
}
ReactInstanceWin::~ReactInstanceWin() noexcept {}
//! Initialize() is called from the native queue.
void ReactInstanceWin::Initialize() noexcept {
InitJSMessageThread();
InitNativeMessageThread();
InitUIMessageThread();
m_legacyReactInstance =
std::make_shared<react::uwp::UwpReactInstanceProxy>(this, Mso::Copy(m_options.LegacySettings));
// InitUIManager uses m_legacyReactInstance
InitUIManager();
Mso::PostFuture(
m_uiQueue,
[weakThis = Mso::WeakPtr{this}]() noexcept {
// Objects that must be created on the UI thread
if (auto strongThis = weakThis.GetStrongPtr()) {
auto const &legacyInstance = strongThis->m_legacyReactInstance;
strongThis->m_deviceInfo = std::make_shared<react::uwp::DeviceInfo>(legacyInstance);
strongThis->m_appTheme =
std::make_shared<react::uwp::AppTheme>(legacyInstance, strongThis->m_uiMessageThread.LoadWithLock());
react::uwp::I18nHelper().Instance().setInfo(react::uwp::I18nModule::GetI18nInfo());
strongThis->m_appearanceListener =
Mso::Make<react::uwp::AppearanceChangeListener>(legacyInstance, strongThis->m_uiQueue);
}
})
.Then(Queue(), [ this, weakThis = Mso::WeakPtr{this} ]() noexcept {
if (auto strongThis = weakThis.GetStrongPtr()) {
// auto cxxModulesProviders = GetCxxModuleProviders();
auto devSettings = std::make_shared<facebook::react::DevSettings>();
devSettings->useJITCompilation = m_options.EnableJITCompilation;
devSettings->debugHost = GetDebugHost();
devSettings->debugBundlePath = m_options.DeveloperSettings.SourceBundleName;
devSettings->liveReloadCallback = GetLiveReloadCallback();
devSettings->errorCallback = GetErrorCallback();
devSettings->loggingCallback = GetLoggingCallback();
m_redboxHandler = devSettings->redboxHandler = std::move(GetRedBoxHandler());
devSettings->useDirectDebugger = m_options.DeveloperSettings.UseDirectDebugger;
devSettings->debuggerBreakOnNextLine = m_options.DeveloperSettings.DebuggerBreakOnNextLine;
devSettings->debuggerPort = m_options.DeveloperSettings.DebuggerPort;
devSettings->debuggerRuntimeName = m_options.DeveloperSettings.DebuggerRuntimeName;
devSettings->useWebDebugger = m_options.DeveloperSettings.UseWebDebugger;
devSettings->useFastRefresh = m_options.DeveloperSettings.UseFastRefresh;
// devSettings->memoryTracker = GetMemoryTracker();
devSettings->bundleRootPath =
m_options.BundleRootPath.empty() ? "ms-appx:///Bundle/" : m_options.BundleRootPath;
m_bundleRootPath = devSettings->bundleRootPath;
devSettings->waitingForDebuggerCallback = GetWaitingForDebuggerCallback();
devSettings->debuggerAttachCallback = GetDebuggerAttachCallback();
// Now that ReactNativeWindows is building outside devmain, it is missing
// fix given by PR https://github.com/microsoft/react-native-windows/pull/2624 causing
// regression. We're turning off console redirection till the fix is available in devmain.
// Bug https://office.visualstudio.com/DefaultCollection/OC/_workitems/edit/3441551 is tracking this
devSettings->debuggerConsoleRedirection =
false; // JSHost::ChangeGate::ChakraCoreDebuggerConsoleRedirection();
m_appState = std::make_shared<react::uwp::AppState2>(*m_reactContext, m_uiQueue);
// Acquire default modules and then populate with custom modules
std::vector<facebook::react::NativeModuleDescription> cxxModules = react::uwp::GetCoreModules(
m_uiManager.Load(),
m_batchingUIThread,
m_uiMessageThread.Load(),
std::move(m_deviceInfo),
std::move(m_appState),
std::move(m_appTheme),
std::move(m_appearanceListener),
m_legacyReactInstance);
auto nmp = std::make_shared<winrt::Microsoft::ReactNative::NativeModulesProvider>();
nmp->AddModuleProvider(
L"Clipboard",
winrt::Microsoft::ReactNative::MakeTurboModuleProvider<
::Microsoft::ReactNative::Clipboard,
::Microsoft::ReactNativeSpecs::ClipboardSpec>());
auto modules = nmp->GetModules(m_reactContext, m_batchingUIThread);
cxxModules.insert(
cxxModules.end(), std::make_move_iterator(modules.begin()), std::make_move_iterator(modules.end()));
cxxModules.emplace_back(
Microsoft::ReactNative::DevSettingsModule::name,
[weakReactHost = strongThis->m_weakReactHost]() {
return std::make_unique<Microsoft::ReactNative::DevSettingsModule>([weakReactHost]() noexcept {
if (auto reactHost = weakReactHost.GetStrongPtr()) {
reactHost->ReloadInstance();
}
});
},
m_batchingUIThread);
if (m_options.ModuleProvider != nullptr) {
std::vector<facebook::react::NativeModuleDescription> customCxxModules =
m_options.ModuleProvider->GetModules(m_reactContext, m_batchingUIThread);
cxxModules.insert(std::end(cxxModules), std::begin(customCxxModules), std::end(customCxxModules));
}
if (m_options.LegacySettings.UseJsi) {
std::unique_ptr<facebook::jsi::ScriptStore> scriptStore = nullptr;
std::unique_ptr<facebook::jsi::PreparedScriptStore> preparedScriptStore = nullptr;
switch (m_options.LegacySettings.jsiEngine) {
case react::uwp::JSIEngine::Hermes:
#if defined(USE_HERMES)
devSettings->jsiRuntimeHolder = std::make_shared<facebook::react::HermesRuntimeHolder>();
devSettings->inlineSourceMap = false;
break;
#endif
case react::uwp::JSIEngine::V8:
#if defined(USE_V8)
preparedScriptStore =
std::make_unique<facebook::react::BasePreparedScriptStoreImpl>(getApplicationLocalFolder());
devSettings->jsiRuntimeHolder = std::make_shared<facebook::react::V8JSIRuntimeHolder>(
devSettings, m_jsMessageThread.Load(), std::move(scriptStore), std::move(preparedScriptStore));
break;
#endif
case react::uwp::JSIEngine::Chakra:
if (m_options.LegacySettings.EnableByteCodeCaching ||
!m_options.LegacySettings.ByteCodeFileUri.empty()) {
scriptStore = std::make_unique<react::uwp::UwpScriptStore>();
preparedScriptStore = std::make_unique<react::uwp::UwpPreparedScriptStore>(
winrt::to_hstring(m_options.LegacySettings.ByteCodeFileUri));
}
devSettings->jsiRuntimeHolder = std::make_shared<Microsoft::JSI::ChakraRuntimeHolder>(
devSettings, m_jsMessageThread.Load(), std::move(scriptStore), std::move(preparedScriptStore));
break;
}
}
try {
// We need to keep the instance wrapper alive as its destruction shuts down the native queue.
auto instanceWrapper = facebook::react::CreateReactInstance(
std::string(), // bundleRootPath
std::move(cxxModules),
nullptr,
m_uiManager.Load(),
m_jsMessageThread.Load(),
Mso::Copy(m_batchingUIThread),
std::move(devSettings));
m_instance.Exchange(Mso::Copy(instanceWrapper->GetInstance()));
m_instanceWrapper.Exchange(std::move(instanceWrapper));
if (auto onCreated = m_options.OnInstanceCreated.Get()) {
onCreated->Invoke(*this);
}
LoadJSBundles();
if (m_options.DeveloperSettings.IsDevModeEnabled && State() != ReactInstanceState::HasError) {
folly::dynamic params = folly::dynamic::array(
STRING(RN_PLATFORM),
m_options.DeveloperSettings.SourceBundleName.empty() ? m_options.Identity
: m_options.DeveloperSettings.SourceBundleName,
GetSourceBundleHost(),
GetSourceBundlePort(),
m_options.DeveloperSettings.UseFastRefresh);
m_instance.Load()->callJSFunction("HMRClient", "setup", std::move(params));
}
} catch (std::exception &e) {
OnErrorWithMessage(e.what());
OnErrorWithMessage("UwpReactInstance: Failed to create React Instance.");
} catch (winrt::hresult_error const &e) {
OnErrorWithMessage(Microsoft::Common::Unicode::Utf16ToUtf8(e.message().c_str(), e.message().size()));
OnErrorWithMessage("UwpReactInstance: Failed to create React Instance.");
} catch (...) {
OnErrorWithMessage("UwpReactInstance: Failed to create React Instance.");
}
}
});
}
void ReactInstanceWin::LoadJSBundles() noexcept {
//
// We use m_jsMessageThread to load JS bundles synchronously. In that case we only load
// them if the m_jsMessageThread is not shut down (quitSynchronous() is not called).
// After the load we call OnReactInstanceLoaded callback on native queue.
//
// Note that the instance could be destroyed while we are loading JS Bundles.
// Though, the JS engine is not destroyed until this work item is not finished.
// Thus, we check the m_isDestroyed flag to see if we should do an early exit.
// Also, since we have to guarantee that the OnReactInstanceLoaded callback is called before
// the OnReactInstanceDestroyed callback, the OnReactInstanceLoaded is called right before the
// OnReactInstanceDestroyed callback in the Destroy() method. In that case any OnReactInstanceLoaded
// calls after we finish this JS message queue work item is ignored.
//
// The LoadedCallbackGuard is used for the case when runOnQueue does not execute the lambda
// before destroying it. It may happen if the m_jsMessageThread is already shutdown.
// In that case, the LoadedCallbackGuard notifies about cancellation by calling OnReactInstanceLoaded.
// The OnReactInstanceLoaded internally only accepts the first call and ignores others.
//
if (m_options.DeveloperSettings.UseWebDebugger || m_options.DeveloperSettings.UseFastRefresh) {
// Getting bundle from the packager, so do everything async.
auto instanceWrapper = m_instanceWrapper.LoadWithLock();
instanceWrapper->loadBundle(Mso::Copy(m_options.Identity));
m_jsMessageThread.Load()->runOnQueue([
weakThis = Mso::WeakPtr{this},
loadCallbackGuard = Mso::MakeMoveOnCopyWrapper(LoadedCallbackGuard{*this})
]() noexcept {
if (auto strongThis = weakThis.GetStrongPtr()) {
if (strongThis->State() != ReactInstanceState::HasError) {
strongThis->OnReactInstanceLoaded(Mso::ErrorCode{});
}
}
});
} else {
m_jsMessageThread.Load()->runOnQueue([
weakThis = Mso::WeakPtr{this},
loadCallbackGuard = Mso::MakeMoveOnCopyWrapper(LoadedCallbackGuard{*this})
]() noexcept {
if (auto strongThis = weakThis.GetStrongPtr()) {
auto instance = strongThis->m_instance.LoadWithLock();
auto instanceWrapper = strongThis->m_instanceWrapper.LoadWithLock();
if (!instance || !instanceWrapper) {
return;
}
auto &options = strongThis->m_options;
try {
instanceWrapper->loadBundleSync(Mso::Copy(options.Identity));
} catch (...) {
strongThis->m_state = ReactInstanceState::HasError;
strongThis->AbandonJSCallQueue();
strongThis->OnReactInstanceLoaded(Mso::ExceptionErrorProvider().MakeErrorCode(std::current_exception()));
return;
}
// All JS bundles successfully loaded.
strongThis->OnReactInstanceLoaded(Mso::ErrorCode{});
}
});
}
}
void ReactInstanceWin::OnReactInstanceLoaded(const Mso::ErrorCode &errorCode) noexcept {
if (!m_isLoaded) {
Queue().InvokeElsePost([ weakThis = Mso::WeakPtr{this}, errorCode ]() noexcept {
if (auto strongThis = weakThis.GetStrongPtr()) {
if (!strongThis->m_isLoaded) {
strongThis->m_isLoaded = true;
if (!errorCode) {
strongThis->m_state = ReactInstanceState::Loaded;
strongThis->DrainJSCallQueue();
} else {
strongThis->m_state = ReactInstanceState::HasError;
strongThis->AbandonJSCallQueue();
}
if (auto onLoaded = strongThis->m_options.OnInstanceLoaded.Get()) {
onLoaded->Invoke(*strongThis, errorCode);
}
strongThis->m_whenLoaded.SetValue();
}
}
});
}
}
Mso::Future<void> ReactInstanceWin::Destroy() noexcept {
// This method must be called from the native queue.
VerifyIsInQueueElseCrash();
if (m_isDestroyed) {
return m_whenDestroyed.AsFuture();
}
m_isDestroyed = true;
m_state = ReactInstanceState::Unloaded;
AbandonJSCallQueue();
if (!m_isLoaded) {
OnReactInstanceLoaded(Mso::CancellationErrorProvider().MakeErrorCode(true));
}
if (auto onDestroyed = m_options.OnInstanceDestroyed.Get()) {
onDestroyed->Invoke(*this);
}
// Make sure that the instance is not destroyed yet
if (auto instance = m_instance.Exchange(nullptr)) {
// Release the message queues before the ui manager and instance.
m_nativeMessageThread.Exchange(nullptr);
m_jsMessageThread.Exchange(nullptr);
m_uiManager.Exchange(nullptr);
m_instanceWrapper.Exchange(nullptr);
m_jsDispatchQueue.Exchange(nullptr);
}
return m_whenDestroyed.AsFuture();
}
const ReactOptions &ReactInstanceWin::Options() const noexcept {
return m_options;
}
ReactInstanceState ReactInstanceWin::State() const noexcept {
return m_state;
}
void ReactInstanceWin::InitJSMessageThread() noexcept {
auto jsDispatchQueue = Mso::DispatchQueue::MakeLooperQueue();
// Create MessageQueueThread for the DispatchQueue
VerifyElseCrashSz(jsDispatchQueue, "m_jsDispatchQueue must not be null");
m_jsMessageThread.Exchange(std::make_shared<MessageDispatchQueue>(
jsDispatchQueue, Mso::MakeWeakMemberFunctor(this, &ReactInstanceWin::OnError), Mso::Copy(m_whenDestroyed)));
m_jsDispatchQueue.Exchange(std::move(jsDispatchQueue));
}
void ReactInstanceWin::InitNativeMessageThread() noexcept {
// Native queue was already given us in constructor.
m_nativeMessageThread.Exchange(
std::make_shared<MessageDispatchQueue>(Queue(), Mso::MakeWeakMemberFunctor(this, &ReactInstanceWin::OnError)));
}
void ReactInstanceWin::InitUIMessageThread() noexcept {
// Native queue was already given us in constructor.
m_uiQueue = winrt::Microsoft::ReactNative::implementation::ReactDispatcher::GetUIDispatchQueue(m_options.Properties);
VerifyElseCrashSz(m_uiQueue, "No UI Dispatcher provided");
m_uiMessageThread.Exchange(
std::make_shared<MessageDispatchQueue>(m_uiQueue, Mso::MakeWeakMemberFunctor(this, &ReactInstanceWin::OnError)));
m_batchingUIThread = react::uwp::MakeBatchingQueueThread(m_uiMessageThread.Load());
}
void ReactInstanceWin::InitUIManager() noexcept {
std::vector<std::unique_ptr<facebook::react::IViewManager>> viewManagers;
// Custom view managers
if (m_options.ViewManagerProvider) {
viewManagers = m_options.ViewManagerProvider->GetViewManagers(m_reactContext, m_legacyReactInstance);
}
react::uwp::AddStandardViewManagers(viewManagers, m_legacyReactInstance);
react::uwp::AddPolyesterViewManagers(viewManagers, m_legacyReactInstance);
auto uiManager = react::uwp::CreateUIManager2(std::move(viewManagers));
auto wkUIManger = std::weak_ptr<facebook::react::IUIManager>(uiManager);
m_reactContext->Properties().Set(
winrt::Microsoft::ReactNative::implementation::XamlUIService::XamlUIServiceProperty().Handle(),
winrt::make<winrt::Microsoft::ReactNative::implementation::XamlUIService>(std::move(wkUIManger), m_reactContext));
m_uiManager.Exchange(std::move(uiManager));
}
facebook::react::NativeLoggingHook ReactInstanceWin::GetLoggingCallback() noexcept {
if (m_options.OnLogging) {
return [logCallback = m_options.OnLogging](facebook::react::RCTLogLevel logLevel, const char *message) {
logCallback(static_cast<LogLevel>(logLevel), message);
};
} else {
// When no logging callback was specified, use a default one in DEBUG builds
#if DEBUG
return [telemetryTag{m_options.Identity}](facebook::react::RCTLogLevel logLevel, const char *message) {
std::ostringstream ss;
ss << "ReactNative ['" << telemetryTag << "'] (";
switch (logLevel) {
case facebook::react::RCTLogLevel::Trace:
ss << "trace";
break;
case facebook::react::RCTLogLevel::Info:
ss << "info";
break;
case facebook::react::RCTLogLevel::Warning:
ss << "warning";
break;
case facebook::react::RCTLogLevel::Error:
ss << "error";
break;
case facebook::react::RCTLogLevel::Fatal:
ss << "fatal";
break;
}
ss << "): '" << message << "'\n";
OutputDebugStringA(ss.str().c_str());
};
#else
return facebook::react::NativeLoggingHook{};
#endif
}
}
std::shared_ptr<IRedBoxHandler> ReactInstanceWin::GetRedBoxHandler() noexcept {
if (m_options.RedBoxHandler) {
return m_options.RedBoxHandler;
} else if (m_options.DeveloperSettings.IsDevModeEnabled) {
auto localWkReactHost = m_weakReactHost;
return CreateDefaultRedBoxHandler(std::move(localWkReactHost), Mso::Copy(m_uiQueue));
} else {
return {};
}
}
std::function<void()> ReactInstanceWin::GetLiveReloadCallback() noexcept {
// Live reload is enabled if we provide a callback function.
if (m_options.DeveloperSettings.UseLiveReload || m_options.DeveloperSettings.UseFastRefresh) {
return Mso::MakeWeakMemberStdFunction(this, &ReactInstanceWin::OnLiveReload);
}
return std::function<void()>{};
}
std::string ReactInstanceWin::GetSourceBundleHost() noexcept {
const ReactDevOptions &devOptions = m_options.DeveloperSettings;
return !devOptions.SourceBundleHost.empty() ? devOptions.SourceBundleHost : "localhost";
}
std::string ReactInstanceWin::GetSourceBundlePort() noexcept {
const ReactDevOptions &devOptions = m_options.DeveloperSettings;
return !devOptions.SourceBundlePort.empty() ? devOptions.SourceBundlePort : "8081";
}
std::string ReactInstanceWin::GetDebugHost() noexcept {
std::string debugHost;
const ReactDevOptions &devOptions = m_options.DeveloperSettings;
if (!devOptions.DebugHost.empty()) {
debugHost = devOptions.DebugHost;
} else {
debugHost = GetSourceBundleHost();
debugHost.append(":");
debugHost.append(GetSourceBundlePort());
}
return debugHost;
}
std::string ReactInstanceWin::GetBytecodeFileName() noexcept {
// use bytecode caching if enabled and not debugging
// (ChakraCore debugging does not work when bytecode caching is enabled)
// TODO: implement
// bool useByteCode = Mso::React::BytecodeOptimizationEnabled() && !m_options.DeveloperSettings.UseDirectDebugger;
// return useByteCode ? Mso::React::GetBytecodeFilePath(m_options.Identity) : "";
return "";
}
std::function<void(std::string)> ReactInstanceWin::GetErrorCallback() noexcept {
return Mso::MakeWeakMemberStdFunction(this, &ReactInstanceWin::OnErrorWithMessage);
}
void ReactInstanceWin::OnErrorWithMessage(const std::string &errorMessage) noexcept {
m_state = ReactInstanceState::HasError;
AbandonJSCallQueue();
if (m_redboxHandler && m_redboxHandler->isDevSupportEnabled()) {
ErrorInfo errorInfo;
errorInfo.Message = errorMessage;
errorInfo.Id = 0;
m_redboxHandler->showNewError(std::move(errorInfo), ErrorType::Native);
}
OnError(Mso::React::ReactErrorProvider().MakeErrorCode(Mso::React::ReactError{errorMessage.c_str()}));
m_updateUI();
}
void ReactInstanceWin::OnError(const Mso::ErrorCode &errorCode) noexcept {
InvokeInQueue([ this, errorCode ]() noexcept { m_options.OnError(errorCode); });
}
void ReactInstanceWin::OnLiveReload() noexcept {
if (auto reactHost = m_weakReactHost.GetStrongPtr()) {
reactHost->ReloadInstance();
}
}
std::function<void()> ReactInstanceWin::GetWaitingForDebuggerCallback() noexcept {
if (m_options.DeveloperSettings.UseWebDebugger) {
return Mso::MakeWeakMemberStdFunction(this, &ReactInstanceWin::OnWaitingForDebugger);
}
return {};
}
void ReactInstanceWin::OnWaitingForDebugger() noexcept {
auto state = m_state.load();
while (state == ReactInstanceState::Loading) {
if (m_state.compare_exchange_weak(state, ReactInstanceState::WaitingForDebugger)) {
break;
}
}
m_updateUI();
}
std::function<void()> ReactInstanceWin::GetDebuggerAttachCallback() noexcept {
if (m_options.DeveloperSettings.UseWebDebugger) {
return Mso::MakeWeakMemberStdFunction(this, &ReactInstanceWin::OnDebuggerAttach);
}
return {};
}
void ReactInstanceWin::OnDebuggerAttach() noexcept {
m_updateUI();
}
void ReactInstanceWin::DrainJSCallQueue() noexcept {
// Handle all items in the queue one by one.
for (;;) {
JSCallEntry entry; // To avoid callJSFunction under the lock
{
std::scoped_lock lock{m_mutex};
if (m_state == ReactInstanceState::Loaded && !m_jsCallQueue.empty()) {
entry = std::move(m_jsCallQueue.front());
m_jsCallQueue.pop_front();
} else {
break;
}
}
if (auto instance = m_instance.LoadWithLock()) {
instance->callJSFunction(std::move(entry.ModuleName), std::move(entry.MethodName), std::move(entry.Args));
}
}
}
void ReactInstanceWin::AbandonJSCallQueue() noexcept {
std::deque<JSCallEntry> jsCallQueue; // To avoid destruction under the lock
{
std::scoped_lock lock{m_mutex};
if (m_state == ReactInstanceState::HasError || m_state == ReactInstanceState::Unloaded) {
jsCallQueue = std::move(m_jsCallQueue);
}
}
}
void ReactInstanceWin::CallJsFunction(
std::string &&moduleName,
std::string &&method,
folly::dynamic &¶ms) noexcept {
bool shouldCall{false}; // To call callJSFunction outside of lock
{
std::scoped_lock lock{m_mutex};
if (m_state == ReactInstanceState::Loaded && m_jsCallQueue.empty()) {
shouldCall = true;
} else if (
m_state == ReactInstanceState::Loading || m_state == ReactInstanceState::WaitingForDebugger ||
(m_state == ReactInstanceState::Loaded && !m_jsCallQueue.empty())) {
m_jsCallQueue.push_back(JSCallEntry{std::move(moduleName), std::move(method), std::move(params)});
}
// otherwise ignore the call
}
if (shouldCall) {
if (auto instance = m_instance.LoadWithLock()) {
instance->callJSFunction(std::move(moduleName), std::move(method), std::move(params));
}
}
}
void ReactInstanceWin::DispatchEvent(int64_t viewTag, std::string &&eventName, folly::dynamic &&eventData) noexcept {
folly::dynamic params = folly::dynamic::array(viewTag, std::move(eventName), std::move(eventData));
CallJsFunction("RCTEventEmitter", "receiveEvent", std::move(params));
}
facebook::react::INativeUIManager *ReactInstanceWin::NativeUIManager() noexcept {
return m_uiManager.LoadWithLock()->getNativeUIManager();
}
std::shared_ptr<facebook::react::Instance> ReactInstanceWin::GetInnerInstance() noexcept {
return m_instance.LoadWithLock();
}
std::string ReactInstanceWin::GetBundleRootPath() noexcept {
return m_bundleRootPath.empty() ? m_options.LegacySettings.BundleRootPath : m_bundleRootPath;
}
std::shared_ptr<react::uwp::IReactInstance> ReactInstanceWin::UwpReactInstance() noexcept {
return m_legacyInstance;
}
void ReactInstanceWin::AttachMeasuredRootView(
facebook::react::IReactRootView *rootView,
folly::dynamic &&initialProps) noexcept {
if (auto instanceWrapper = m_instanceWrapper.LoadWithLock()) {
instanceWrapper->AttachMeasuredRootView(rootView, std::move(initialProps));
}
}
void ReactInstanceWin::DetachRootView(facebook::react::IReactRootView *rootView) noexcept {
if (auto instanceWrapper = m_instanceWrapper.LoadWithLock()) {
instanceWrapper->DetachRootView(rootView);
}
}
Mso::CntPtr<IReactInstanceInternal> MakeReactInstance(
IReactHost &reactHost,
ReactOptions &&options,
Mso::Promise<void> &&whenCreated,
Mso::Promise<void> &&whenLoaded,
Mso::VoidFunctor &&updateUI) noexcept {
return Mso::Make<ReactInstanceWin, IReactInstanceInternal>(
reactHost, std::move(options), std::move(whenCreated), std::move(whenLoaded), std::move(updateUI));
}
#if defined(USE_V8)
std::string ReactInstanceWin::getApplicationLocalFolder() {
auto local = winrt::Windows::Storage::ApplicationData::Current().LocalFolder().Path();
return Microsoft::Common::Unicode::Utf16ToUtf8(local.c_str(), local.size()) + "\\";
}
#endif
} // namespace Mso::React
| [
"[email protected]"
] | |
8f670ae00855f99272f1be1a97a1812a8c179406 | 715023da006513f0dd09e5c4267d371b8ba4e4f6 | /xray-svn-trunk/xr_3da/xrGame/ui/UIScriptWnd_script.cpp | e55bfbe6ec24bd90bd22de3a46ad42f440fd7563 | [] | no_license | tsnest/lost-alpha-dc-sources-master | 5727d58878b1d4036e8f68df9780f3d078e89f21 | fbb61af25da7e722d21492cbaebd6670d84e211c | refs/heads/main | 2023-02-11T16:37:16.570856 | 2021-01-09T17:09:49 | 2021-01-09T17:09:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,958 | cpp | #include "pch_script.h"
//UI-controls
#include "UIScriptWnd.h"
#include "UIButton.h"
#include "UI3tButton.h"
#include "UIMessageBox.h"
#include "UIPropertiesBox.h"
#include "UICheckButton.h"
#include "UIRadioButton.h"
#include "UIStatic.h"
#include "UIEditBox.h"
#include "UIFrameWindow.h"
#include "UIFrameLineWnd.h"
#include "UIProgressBar.h"
#include "UITabControl.h"
#include "uiscriptwnd_script.h"
using namespace luabind;
extern export_class &script_register_ui_window1(export_class &);
extern export_class &script_register_ui_window2(export_class &);
#pragma optimize("s",on)
void CUIDialogWndEx::script_register(lua_State *L)
{
export_class instance("CUIScriptWnd");
module(L)
[
script_register_ui_window2(
script_register_ui_window1(
instance
)
)
.def("Load", &BaseType::Load)
];
}
export_class &script_register_ui_window1(export_class &instance)
{
instance
.def( constructor<>())
.def("AddCallback", (void(BaseType::*)(LPCSTR, s16, const luabind::functor<void>&))&BaseType::AddCallback)
.def("AddCallback", (void(BaseType::*)(LPCSTR, s16, const luabind::functor<void>&, const luabind::object&))&BaseType::AddCallback)
.def("Register", (void (BaseType::*)(CUIWindow*))&BaseType::Register)
.def("Register", (void (BaseType::*)(CUIWindow*,LPCSTR))&BaseType::Register)
.def("GetButton", (CUIButton* (BaseType::*)(LPCSTR)) &BaseType::GetControl<CUIButton>)
.def("Get3tButton", (CUI3tButton* (BaseType::*)(LPCSTR)) &BaseType::GetControl<CUI3tButton>)
.def("GetMessageBox", (CUIMessageBox* (BaseType::*)(LPCSTR)) &BaseType::GetControl<CUIMessageBox>)
.def("GetPropertiesBox",(CUIPropertiesBox* (BaseType::*)(LPCSTR)) &BaseType::GetControl<CUIPropertiesBox>)
.def("GetCheckButton", (CUICheckButton* (BaseType::*)(LPCSTR)) &BaseType::GetControl<CUICheckButton>)
.def("GetRadioButton", (CUIRadioButton* (BaseType::*)(LPCSTR)) &BaseType::GetControl<CUIRadioButton>)
;return (instance);
} | [
"[email protected]"
] | |
c3203bc5e100b13e1941d962e5c9c0dc28d6631b | 432350046fe7020921165fec982c2073bc14a8ba | /src/loop_generator/Sound.h | d0724d2a84f9ce6711692c7dc6dff4b1a73094d1 | [] | no_license | taglo/AudioEditor | e2cc04dd621d400e0c00611f6972e9e7d0eeec20 | 8bca732b7af77ee6c77cbbcd1c95e00a63c627cd | refs/heads/master | 2020-04-06T03:33:22.641452 | 2016-09-16T04:30:31 | 2016-09-16T04:30:31 | 49,327,078 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 426 | h | /*
* File: Sound.h
* Author: tglo
*
* Created on 5 septembre 2016, 18:08
*
*
*/
#ifndef SOUND_H
#define SOUND_H
#include "../Sample.h"
#include <string>
class Sound : public Sample
{
public:
Sound();
string info;
bool estRythmique;
bool estTon;
std::vector<int> midi_note;
private:
};
#endif /* SOUND_H */
| [
"tglo@tglo-PC"
] | tglo@tglo-PC |
86f883ce37df8edf256e8a5d6554e2af6a5be8b7 | 62408a02b44f2fd20c6d54e1f5def0184e69194c | /CodeChef/AUSAG/23586243_AC_10ms_15462kB.cpp | a4cf7e6112142cb6a63938c80d5712285c83ca66 | [] | no_license | benedicka/Competitive-Programming | 24eb90b8150aead5c13287b62d9dc860c4b9232e | a94ccfc2d726e239981d598e98d1aa538691fa47 | refs/heads/main | 2023-03-22T10:14:34.889913 | 2021-03-16T05:33:43 | 2021-03-16T05:33:43 | 348,212,250 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,412 | cpp | #include <bits/stdc++.h>
using namespace std;
char y[100010],tmp[100010];
int ans,t,n,m,idx;
string x;
void computeLPSArray(char* pat, int m, int* lps)
{
int len = 0;
lps[0] = 0;
int i = 1;
while(i<m)
{
if (pat[i] == pat[len])
{
len++;
lps[i] = len;
i++;
}
else
{
if (len != 0)
{
len = lps[len-1];
}
else
{
lps[i] = 0;
i++;
}
}
}
}
void KMP(char* pat, char* txt)
{
int lenPat = strlen(pat);
int lenTxt = strlen(txt);
int lps[lenPat];
computeLPSArray(pat,lenPat,lps);
int i = 0;
int j = 0;
while (i < lenTxt)
{
if (pat[j] == txt[i])
{
j++;
i++;
}
if (j==lenPat)
{
ans++;
j = lps[j-1];
}
else if (i<lenTxt && pat[j]!=txt[i])
{
if (j!=0) j = lps[j-1];
else i++;
}
}
}
int main()
{
scanf("%d",&t);
for (int tc=1;tc<=t;tc++)
{
tmp[0] = '\0';
getline(cin,x);
getline(cin,x);
scanf("%s",&y);
int lem = x.size();
idx = 0;
for(int i=0;i<lem;i++)
{
if(x[i]!=' ')tmp[idx++] = x[i];
}
tmp[lem] = '\0';
//printf("x:%s\ny:%s\n",tmp,y);
ans = 0;
KMP(y,tmp);
printf("Case %d: %d\n",tc,ans);
}
return 0;
} | [
"[email protected]"
] | |
7c042e979c8753357d8ae1c0c285aa065b177de8 | d6f907bbdcc73c9d235792143829071c89f46a70 | /Chombo/lib/src/HOMappedConservation/NewMultiBlockFluxRegister.H | 6a6adb03a647ca4e2b63e335de56060ac17c1cd0 | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | permissive | LLNL/COGENT | 2095aa2dfda75f03b01d7d271ee01059ebaa99e0 | 955f848bcfb8811ebdf6c52c605efb3b71e5177c | refs/heads/master | 2023-08-23T19:00:32.957355 | 2023-05-06T03:05:11 | 2023-05-06T03:05:11 | 61,917,616 | 13 | 5 | null | 2023-01-20T22:18:06 | 2016-06-24T23:22:42 | C++ | UTF-8 | C++ | false | false | 5,176 | h | #ifdef CH_LANG_CC
/*
* _______ __
* / ___/ / ___ __ _ / / ___
* / /__/ _ \/ _ \/ V \/ _ \/ _ \
* \___/_//_/\___/_/_/_/_.__/\___/
* Please refer to Copyright.txt, in Chombo's root directory.
*/
#endif
#ifndef _NEWMULTIBLOCKFLUXREGISTER_H_
#define _NEWMULTIBLOCKFLUXREGISTER_H_
#include "LevelFluxRegister.H"
#include "BlockRegister.H"
#include "NamespaceHeader.H"
//NewMultiBlockFluxRegister-Derived from LevelFluxRegister to support multiblock grids.
/**
A LevelFluxRegister handles all the data choreography
necessary to create a levels worth of flux registers.
*/
///
/**
Full constructor. Calls the define function which creates
a levels worth of flux registers. a_domain is is coarse-level
domain.
If a_scaleFineFluxes is true (default then all fine fluxes are
scaled by 1/a_nRefine^(SpaceDim-1). Otherwise, no scaling is done.
*/
class NewMultiBlockFluxRegister : public LevelFluxRegister
{
public:
///
/**
domainCoar --coordinate system at coarser level
*/
NewMultiBlockFluxRegister(
RefCountedPtr<MultiBlockCoordSys> a_domCoar,
const DisjointBoxLayout& a_dblFine,
const DisjointBoxLayout& a_dblCoar,
int a_nRefine,
int a_nComp,
bool a_scaleFineFluxes=false,
int a_unrefinedDirection=-1)
{
define(a_domCoar,
a_dblFine,
a_dblCoar,
a_nRefine,
a_nComp,
a_scaleFineFluxes,
a_unrefinedDirection);
}
static int index(int a_dir, Side::LoHiSide a_side);
NewMultiBlockFluxRegister(const NewMultiBlockFluxRegister&);
NewMultiBlockFluxRegister()
{ };
~NewMultiBlockFluxRegister();
///
/**
domainCoar --coordinate system at coarser level
*/
virtual void define(RefCountedPtr<MultiBlockCoordSys> a_domainCoar,
const DisjointBoxLayout& a_dbl,
const DisjointBoxLayout& a_dblCoarse,
int a_nRefine,
int a_nComp,
bool a_scaleFineFluxes=false,
int a_unrefinedDirection=-1);
virtual void reflux(
LevelData<FArrayBox>& a_uCoarse,
Real a_scale);
virtual void reflux(LevelData<FArrayBox>& a_uCoarse,
const Interval& a_coarseVectorIntv,
Real a_scale);
virtual void reflux(LevelData<FArrayBox>& a_uCoarse,
const Interval& a_coarseVectorIntv,
const Interval& a_fluxInterval,
Real a_scale);
virtual void reflux(LevelData<FArrayBox>& a_uCoarse,
const Interval& a_coarse_interval,
const Interval& a_coarseVectorIntv,
const Interval& a_flux_interval,
Real a_scale);
virtual void setToZero();
virtual void incrementFine(
const FArrayBox& a_fineFlux,
Real a_scale,
const DataIndex& a_fineDataIndex,
const Interval& a_srcInterval,
const Interval& a_dstInterval,
int a_dir,
Side::LoHiSide a_sd);
virtual void incrementCoarse(
const FArrayBox& a_coarseFlux,
Real a_scale,
const DataIndex& a_coarseDataIndex,
const Interval& a_srcInterval,
const Interval& a_dstInterval,
int a_dir,
Side::LoHiSide a_sd);
private:
Vector<RefCountedPtr<BlockRegister > > m_coarRegisters;
Vector<RefCountedPtr<BlockRegister > > m_cofiRegisters;
LevelData<FluxBox > m_fluxCoFi;
Vector<RefCountedPtr<BlockRegister > > m_blockCFLocations;
LayoutData<Vector<Box> > m_fineBlockBoundaries;
int m_nComp;
// internal function to make define less monolithic
void defineBlockCFLocations(RefCountedPtr<MultiBlockCoordSys> a_domain,
const DisjointBoxLayout& a_dblFine,
const DisjointBoxLayout& a_dblCoar);
// internal function to make define less monolithic
void getCoFiBoxBlockList(std::list<Box> & a_blockBoxesCoFi,
RefCountedPtr<MultiBlockCoordSys>& a_domCoar,
const DisjointBoxLayout & a_dblFine);
// internal function to make define less monolithic
void defineBlockBoundaries( RefCountedPtr<MultiBlockCoordSys> a_domain,
const DisjointBoxLayout& a_dblFine);
};
#include "NamespaceFooter.H"
#endif // include guard
| [
"{dorr1,dorf1,hittinger1,ghosh5}@llnl.gov"
] | {dorr1,dorf1,hittinger1,ghosh5}@llnl.gov |
b52b0837aed00cd20a28c968c3e1bfeaf0dbbea5 | dc9d65f711d3507da390eefb57c7519c97e81c64 | /plugins/template/templateoptions.cpp | 638824843d9ea56510790a50d4b005bf028f44ed | [] | no_license | xjohncz/saje | 40cd6d3a11b07c7e4b0f205762aacbe7528e4906 | 7c8a6c1cfab57feacc2dd657c70380b38330e3ef | refs/heads/master | 2021-01-20T08:46:49.601271 | 2011-04-20T03:18:10 | 2011-04-20T03:18:10 | 35,888,997 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 282 | cpp | #include "templateoptions.h"
TemplateOptions::TemplateOptions(QWidget *parent)
: OptionsPageI(parent)
{
ui.setupUi(this);
reset();
}
TemplateOptions::~TemplateOptions()
{
}
bool TemplateOptions::apply() {
emit applied();
return true;
}
void TemplateOptions::reset() {
}
| [
"sje397@200c22c1-0253-0410-a7cc-2773c7d12e9d"
] | sje397@200c22c1-0253-0410-a7cc-2773c7d12e9d |
f49ba029837164e7745e32eadfc5bbfdad382ab2 | e763b855be527d69fb2e824dfb693d09e59cdacb | /aws-cpp-sdk-codepipeline/source/model/PutWebhookResult.cpp | c9b54b5021f19bfa508a28f8ce5f5e0327fb6e6d | [
"MIT",
"Apache-2.0",
"JSON"
] | permissive | 34234344543255455465/aws-sdk-cpp | 47de2d7bde504273a43c99188b544e497f743850 | 1d04ff6389a0ca24361523c58671ad0b2cde56f5 | refs/heads/master | 2023-06-10T16:15:54.618966 | 2018-05-07T23:32:08 | 2018-05-07T23:32:08 | 132,632,360 | 1 | 0 | Apache-2.0 | 2023-06-01T23:20:47 | 2018-05-08T15:56:35 | C++ | UTF-8 | C++ | false | false | 1,381 | cpp | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/codepipeline/model/PutWebhookResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::CodePipeline::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
PutWebhookResult::PutWebhookResult()
{
}
PutWebhookResult::PutWebhookResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
*this = result;
}
PutWebhookResult& PutWebhookResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
const JsonValue& jsonValue = result.GetPayload();
if(jsonValue.ValueExists("webhook"))
{
m_webhook = jsonValue.GetObject("webhook");
}
return *this;
}
| [
"[email protected]"
] | |
c7aba5d7b88b92d292215261c27573b7432516a4 | 32bb7451b752db485a59a8da1afaeb19511cd157 | /src/features/dynamic_feature.cpp | b675a8c5fa6895f941c2615134ae544f441983e4 | [] | no_license | RobinGenshin/GenshinLib | 905a40866d8ea9827cbcc26f1e9ed1a216b820d3 | 713c6a448f322559ed6056ac2626112cab051b2b | refs/heads/main | 2023-07-01T00:12:18.135966 | 2021-08-02T19:33:28 | 2021-08-02T19:33:28 | 389,718,728 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 998 | cpp | #include "dynamic_feature.h"
#include "feature_data.h"
#include "abstract_event.h"
#include "sim.h"
DynamicFeature::DynamicFeature(Component& _component, const FeatureData _data) : AbstractFeature(_component, _data), cd(0) {
AbstractFeature::isDynamic = true;
};
bool DynamicFeature::FieldCheck(Sim& sim, AbstractEvent& event) {
return ((event.get_player() == *(sim.current_player)) || !data.field);
};
void DynamicFeature::CheckEvent(Sim& sim, AbstractEvent& event, std::string timing) {
if (!enabled()) return;
if (cd > 0) return;
if (!FieldCheck(sim, event)) return;
if (!(timing == data.timing)) return;
for (auto& i : event.get_triggers()) {
if ((data.condition.front() == "any") || (std::find(data.condition.begin(), data.condition.end(), i) != data.condition.end())) {
Activate(sim);
return;
};
};
};
void DynamicFeature::Activate(Sim& sim) {
if (data.cd > float(0)) cd = data.cd;
};
void DynamicFeature::PassTime(float dt) {
cd = std::max(float(0), cd - dt);
}; | [
"[email protected]"
] | |
863b26218083ff9a779cc64879ff583aec3833f6 | 33ff050337ba4575042032d9602bf84dcf81435e | /src/blocksignature.cpp | 683377cd23c3b2da9573373e8b5919022c8535dd | [
"MIT"
] | permissive | robinadaptor/chronon | 5256b33fbe797bbdeb9c9a3c2091f0592afe6614 | 630b3945824c1b1cd2ea67ca80835a9f669b9124 | refs/heads/master | 2020-07-11T06:27:01.758237 | 2019-12-17T20:53:48 | 2019-12-17T20:53:48 | 145,383,639 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,726 | cpp | // Copyright (c) 2017-2018 PIVX developers
// Copyright (c) 2018-2019 Chronon developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "blocksignature.h"
#include "main.h"
bool SignBlockWithKey(CBlock& block, const CKey& key)
{
if (!key.Sign(block.GetHash(), block.vchBlockSig))
return error("%s: failed to sign block hash with key", __func__);
return true;
}
bool GetKeyIDFromUTXO(const CTxOut& txout, CKeyID& keyID)
{
std::vector<valtype> vSolutions;
txnouttype whichType;
if (!Solver(txout.scriptPubKey, whichType, vSolutions))
return false;
if (whichType == TX_PUBKEY) {
keyID = CPubKey(vSolutions[0]).GetID();
} else if (whichType == TX_PUBKEYHASH) {
keyID = CKeyID(uint160(vSolutions[0]));
}
return true;
}
bool SignBlock(CBlock& block, const CKeyStore& keystore)
{
CKeyID keyID;
if (block.IsProofOfWork()) {
bool fFoundID = false;
for (const CTxOut& txout :block.vtx[0].vout) {
if (!GetKeyIDFromUTXO(txout, keyID))
continue;
fFoundID = true;
break;
}
if (!fFoundID)
return error("%s: failed to find key for PoW", __func__);
} else {
if (!GetKeyIDFromUTXO(block.vtx[1].vout[1], keyID))
return error("%s: failed to find key for PoS", __func__);
}
CKey key;
if (!keystore.GetKey(keyID, key))
return error("%s: failed to get key from keystore", __func__);
return SignBlockWithKey(block, key);
}
bool CheckBlockSignature(const CBlock& block)
{
if (block.IsProofOfWork())
return block.vchBlockSig.empty();
if (block.vchBlockSig.empty())
return error("%s: vchBlockSig is empty!", __func__);
/** Each block is signed by the private key of the input that is staked. This can be either zCHN or normal UTXO
* zCHN: Each zCHN has a keypair associated with it. The serial number is a hash of the public key.
* UTXO: The public key that signs must match the public key associated with the first utxo of the coinstake tx.
*/
CPubKey pubkey;
txnouttype whichType;
std::vector<valtype> vSolutions;
const CTxOut& txout = block.vtx[1].vout[1];
if (!Solver(txout.scriptPubKey, whichType, vSolutions))
return false;
if (whichType == TX_PUBKEY || whichType == TX_PUBKEYHASH) {
valtype& vchPubKey = vSolutions[0];
pubkey = CPubKey(vchPubKey);
}
if (!pubkey.IsValid())
return error("%s: invalid pubkey %s", __func__, HexStr(pubkey));
return pubkey.Verify(block.GetHash(), block.vchBlockSig);
}
| [
"[email protected]"
] | |
fd55a7270c8cdc829cf2a755684d648c41bf29f1 | ec4eb7dfac2d50c71b1922ce717d7221be107817 | /GameEngine/src/Primitives/Tile.hpp | f50676636f64e6d6c04e8693f1e4d7ae9aa43103 | [] | no_license | bnelo12/Open-GL-3D-Game-Engine | 5549c15b20837ae45f3abd379d21bf02c9ba3acd | 52d6267485da6885d349c7d2ce1679e514be56da | refs/heads/master | 2021-01-19T05:33:14.024002 | 2017-05-03T18:56:34 | 2017-05-03T18:56:34 | 87,434,242 | 3 | 0 | null | 2017-05-03T18:55:16 | 2017-04-06T13:46:02 | C++ | UTF-8 | C++ | false | false | 368 | hpp | //
// Tile.hpp
// OpenGLGameEngine
//
// Created by Benjamin Elo on 4/16/17.
// Copyright © 2017 Elo Software. All rights reserved.
//
#ifndef Tile_hpp
#define Tile_hpp
#include "Primitive.hpp"
class Tile : public Primitive {
public:
Tile(std::vector<Texture*> lightingMaps, int radius);
private:
void init();
int radius;
};
#endif /* Tile_hpp */
| [
"[email protected]"
] | |
fef5f395318084b8207fbd386c03c2f9e0978a5f | 8dc84558f0058d90dfc4955e905dab1b22d12c08 | /third_party/blink/renderer/bindings/tests/results/core/unsigned_long_long_or_boolean_or_test_callback_interface.cc | 0874fd501c1541bfc8cf14cb5e987ba4b386cd6d | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | meniossin/src | 42a95cc6c4a9c71d43d62bc4311224ca1fd61e03 | 44f73f7e76119e5ab415d4593ac66485e65d700a | refs/heads/master | 2022-12-16T20:17:03.747113 | 2020-09-03T10:43:12 | 2020-09-03T10:43:12 | 263,710,168 | 1 | 0 | BSD-3-Clause | 2020-05-13T18:20:09 | 2020-05-13T18:20:08 | null | UTF-8 | C++ | false | false | 5,942 | cc | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file has been auto-generated from the Jinja2 template
// third_party/blink/renderer/bindings/templates/union_container.cpp.tmpl
// by the script code_generator_v8.py.
// DO NOT MODIFY!
// clang-format off
#include "third_party/blink/renderer/bindings/tests/results/core/unsigned_long_long_or_boolean_or_test_callback_interface.h"
#include "third_party/blink/renderer/bindings/core/v8/idl_types.h"
#include "third_party/blink/renderer/bindings/core/v8/native_value_traits_impl.h"
#include "third_party/blink/renderer/bindings/core/v8/to_v8_for_core.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_test_callback_interface.h"
namespace blink {
UnsignedLongLongOrBooleanOrTestCallbackInterface::UnsignedLongLongOrBooleanOrTestCallbackInterface() : type_(SpecificType::kNone) {}
bool UnsignedLongLongOrBooleanOrTestCallbackInterface::GetAsBoolean() const {
DCHECK(IsBoolean());
return boolean_;
}
void UnsignedLongLongOrBooleanOrTestCallbackInterface::SetBoolean(bool value) {
DCHECK(IsNull());
boolean_ = value;
type_ = SpecificType::kBoolean;
}
UnsignedLongLongOrBooleanOrTestCallbackInterface UnsignedLongLongOrBooleanOrTestCallbackInterface::FromBoolean(bool value) {
UnsignedLongLongOrBooleanOrTestCallbackInterface container;
container.SetBoolean(value);
return container;
}
V8TestCallbackInterface* UnsignedLongLongOrBooleanOrTestCallbackInterface::GetAsTestCallbackInterface() const {
DCHECK(IsTestCallbackInterface());
return test_callback_interface_;
}
void UnsignedLongLongOrBooleanOrTestCallbackInterface::SetTestCallbackInterface(V8TestCallbackInterface* value) {
DCHECK(IsNull());
test_callback_interface_ = value;
type_ = SpecificType::kTestCallbackInterface;
}
UnsignedLongLongOrBooleanOrTestCallbackInterface UnsignedLongLongOrBooleanOrTestCallbackInterface::FromTestCallbackInterface(V8TestCallbackInterface* value) {
UnsignedLongLongOrBooleanOrTestCallbackInterface container;
container.SetTestCallbackInterface(value);
return container;
}
uint64_t UnsignedLongLongOrBooleanOrTestCallbackInterface::GetAsUnsignedLongLong() const {
DCHECK(IsUnsignedLongLong());
return unsigned_long_long_;
}
void UnsignedLongLongOrBooleanOrTestCallbackInterface::SetUnsignedLongLong(uint64_t value) {
DCHECK(IsNull());
unsigned_long_long_ = value;
type_ = SpecificType::kUnsignedLongLong;
}
UnsignedLongLongOrBooleanOrTestCallbackInterface UnsignedLongLongOrBooleanOrTestCallbackInterface::FromUnsignedLongLong(uint64_t value) {
UnsignedLongLongOrBooleanOrTestCallbackInterface container;
container.SetUnsignedLongLong(value);
return container;
}
UnsignedLongLongOrBooleanOrTestCallbackInterface::UnsignedLongLongOrBooleanOrTestCallbackInterface(const UnsignedLongLongOrBooleanOrTestCallbackInterface&) = default;
UnsignedLongLongOrBooleanOrTestCallbackInterface::~UnsignedLongLongOrBooleanOrTestCallbackInterface() = default;
UnsignedLongLongOrBooleanOrTestCallbackInterface& UnsignedLongLongOrBooleanOrTestCallbackInterface::operator=(const UnsignedLongLongOrBooleanOrTestCallbackInterface&) = default;
void UnsignedLongLongOrBooleanOrTestCallbackInterface::Trace(blink::Visitor* visitor) {
visitor->Trace(test_callback_interface_);
}
void V8UnsignedLongLongOrBooleanOrTestCallbackInterface::ToImpl(v8::Isolate* isolate, v8::Local<v8::Value> v8Value, UnsignedLongLongOrBooleanOrTestCallbackInterface& impl, UnionTypeConversionMode conversionMode, ExceptionState& exceptionState) {
if (v8Value.IsEmpty())
return;
if (conversionMode == UnionTypeConversionMode::kNullable && IsUndefinedOrNull(v8Value))
return;
if (V8TestCallbackInterface::hasInstance(v8Value, isolate)) {
V8TestCallbackInterface* cppValue = V8TestCallbackInterface::ToImpl(v8::Local<v8::Object>::Cast(v8Value));
impl.SetTestCallbackInterface(cppValue);
return;
}
if (v8Value->IsBoolean()) {
impl.SetBoolean(v8Value.As<v8::Boolean>()->Value());
return;
}
if (v8Value->IsNumber()) {
uint64_t cppValue = NativeValueTraits<IDLUnsignedLongLong>::NativeValue(isolate, v8Value, exceptionState, kNormalConversion);
if (exceptionState.HadException())
return;
impl.SetUnsignedLongLong(cppValue);
return;
}
{
uint64_t cppValue = NativeValueTraits<IDLUnsignedLongLong>::NativeValue(isolate, v8Value, exceptionState, kNormalConversion);
if (exceptionState.HadException())
return;
impl.SetUnsignedLongLong(cppValue);
return;
}
}
v8::Local<v8::Value> ToV8(const UnsignedLongLongOrBooleanOrTestCallbackInterface& impl, v8::Local<v8::Object> creationContext, v8::Isolate* isolate) {
switch (impl.type_) {
case UnsignedLongLongOrBooleanOrTestCallbackInterface::SpecificType::kNone:
return v8::Null(isolate);
case UnsignedLongLongOrBooleanOrTestCallbackInterface::SpecificType::kBoolean:
return v8::Boolean::New(isolate, impl.GetAsBoolean());
case UnsignedLongLongOrBooleanOrTestCallbackInterface::SpecificType::kTestCallbackInterface:
return ToV8(impl.GetAsTestCallbackInterface(), creationContext, isolate);
case UnsignedLongLongOrBooleanOrTestCallbackInterface::SpecificType::kUnsignedLongLong:
return v8::Number::New(isolate, static_cast<double>(impl.GetAsUnsignedLongLong()));
default:
NOTREACHED();
}
return v8::Local<v8::Value>();
}
UnsignedLongLongOrBooleanOrTestCallbackInterface NativeValueTraits<UnsignedLongLongOrBooleanOrTestCallbackInterface>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) {
UnsignedLongLongOrBooleanOrTestCallbackInterface impl;
V8UnsignedLongLongOrBooleanOrTestCallbackInterface::ToImpl(isolate, value, impl, UnionTypeConversionMode::kNotNullable, exceptionState);
return impl;
}
} // namespace blink
| [
"[email protected]"
] | |
237a6323ccdb7c908cd31ecc012536b24383d2dd | 140d78334109e02590f04769ec154180b2eaf78d | /aws-cpp-sdk-redshift/source/model/CreateClusterSnapshotResult.cpp | 280dc2a643cf56fabf07d9a003b50772c0f62fd0 | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | coderTong/aws-sdk-cpp | da140feb7e5495366a8d2a6a02cf8b28ba820ff6 | 5cd0c0a03b667c5a0bd17394924abe73d4b3754a | refs/heads/master | 2021-07-08T07:04:40.181622 | 2017-08-22T21:50:00 | 2017-08-22T21:50:00 | 101,145,374 | 0 | 1 | Apache-2.0 | 2021-05-04T21:06:36 | 2017-08-23T06:24:37 | C++ | UTF-8 | C++ | false | false | 2,096 | cpp | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/redshift/model/CreateClusterSnapshotResult.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/logging/LogMacros.h>
#include <utility>
using namespace Aws::Redshift::Model;
using namespace Aws::Utils::Xml;
using namespace Aws::Utils::Logging;
using namespace Aws::Utils;
using namespace Aws;
CreateClusterSnapshotResult::CreateClusterSnapshotResult()
{
}
CreateClusterSnapshotResult::CreateClusterSnapshotResult(const AmazonWebServiceResult<XmlDocument>& result)
{
*this = result;
}
CreateClusterSnapshotResult& CreateClusterSnapshotResult::operator =(const AmazonWebServiceResult<XmlDocument>& result)
{
const XmlDocument& xmlDocument = result.GetPayload();
XmlNode rootNode = xmlDocument.GetRootElement();
XmlNode resultNode = rootNode;
if (!rootNode.IsNull() && (rootNode.GetName() != "CreateClusterSnapshotResult"))
{
resultNode = rootNode.FirstChild("CreateClusterSnapshotResult");
}
if(!resultNode.IsNull())
{
XmlNode snapshotNode = resultNode.FirstChild("Snapshot");
if(!snapshotNode.IsNull())
{
m_snapshot = snapshotNode;
}
}
if (!rootNode.IsNull()) {
XmlNode responseMetadataNode = rootNode.FirstChild("ResponseMetadata");
m_responseMetadata = responseMetadataNode;
AWS_LOGSTREAM_DEBUG("Aws::Redshift::Model::CreateClusterSnapshotResult", "x-amzn-request-id: " << m_responseMetadata.GetRequestId() );
}
return *this;
}
| [
"[email protected]"
] | |
f4899dc2a801c087340c290891ca4a4cddfc56ad | 50662dac46e7c2d6714ab3844146db1cb6db6ebb | /engine/Display/ClonedGallery.cpp | 9d04b29cd5f83e821f413580b3e896f54aec4b7d | [] | no_license | Happy-Ferret-Entertainment/creatures3 | d3eae9889cdefbfae5390ae0066433cf86b21e03 | 321245bed27cbacb52421d95c9ff4f0bf67a49eb | refs/heads/master | 2023-07-30T10:00:28.437468 | 2021-09-22T17:31:18 | 2021-09-22T17:31:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,117 | cpp | // --------------------------------------------------------------------------
// Filename: ClonedGallery.cpp
// Class: ClonedGallery
// Purpose: This class holds a series of bitmaps for an entity.
// Cloned galleries need to hold all their bitmap data locally
// so they do not use memory mapped files. Also we must be
// provided with the bae image and the number of images that belong
// to this particular gallery since there may be many sets of
// related sprites in a sprite file.
//
//
//
// Description: A cloned gallery cannot be compressed because its bitmaps
// are used as a canvas to display other sprites.
//
// History:
// -------
// 11Nov98 Alima Created
// --------------------------------------------------------------------------
#ifdef _MSC_VER
#pragma warning(disable:4786 4503)
#endif
#include "ClonedGallery.h"
#include "SharedGallery.h"
#include "System.h"
#include <stdio.h>
#include "ClonedSprite.h"
#include "ErrorMessageHandler.h"
#include "DisplayEngine.h"
#include "Bitmap.h"
#include "../File.h"
CREATURES_IMPLEMENT_SERIAL( ClonedGallery )
// ----------------------------------------------------------------------
// Method: Constructor
// Arguments: name - the gallery file to read from
// baseImage - the image in the sprite file
// to start loading from
// numImages - the number of images in the file that belong
// to this entity (starting from the base image)
//
//
// Description: Cloned Galleries keep their bitmap data locally
//
// ----------------------------------------------------------------------
ClonedGallery::ClonedGallery(FilePath const &name,
uint32 baseimage,
uint32 numImages)
:Gallery(name),
myBaseImage(baseimage)
{
myCount = numImages;
if(!InitBitmaps())
{
std::string string = ErrorMessageHandler::Format(theDisplayErrorTag,
(int)DisplayEngine::sidGalleryNotCreated,
std::string("ClonedGallery::ClonedGallery"),
name.GetFullPath().c_str());
throw(Gallery::GalleryException(string,__LINE__));
}
}
// ----------------------------------------------------------------------
// Method: Constructor
// Arguments: name - the gallery file to read from
// baseImage - the image in the sprite file
// to start loading from
// numImages - the number of images in the file that belong
// to this entity (starting from the base image)
//
//
// Description: Cloned Galleries keep their bitmap data locally
//
// ----------------------------------------------------------------------
ClonedGallery::ClonedGallery(FilePath const &name,
uint32 baseimage,
uint32 numImages,
uint32 defaultBitmapWidth,
uint32 defaultBitmapHeight)
:Gallery(name),
myBaseImage(baseimage)
{
myCount = numImages;
//create the correct number of bitmaps
myBitmaps=new Bitmap[myCount];
if(myBitmaps)
{
int offset = myCount * SpriteFileHeaderSize;
// only read in data specific to you
int i;
for( i = 0; i < myCount; i++)
{
myBitmaps[i].SetOffset(offset);
myBitmaps[i].SetWidth(defaultBitmapWidth);
myBitmaps[i].SetHeight(defaultBitmapHeight);
myBitmaps[i].CreateBlankCanvas();
offset+=defaultBitmapWidth * defaultBitmapHeight* 2;
}
}
}
ClonedGallery::~ClonedGallery()
{
if(myBitmaps) delete [] myBitmaps;
myBitmaps = NULL;
}
// ----------------------------------------------------------------------
// Method: Write
// Arguments: archive - archive being written to
// Returns: true if successful
// Description: Overridable function - writes details to archive,
// taking serialisation into account
// ----------------------------------------------------------------------
bool ClonedGallery::Write(CreaturesArchive &archive) const
{
Gallery::Write( archive );
archive << myBaseImage;
return true;
}
// ----------------------------------------------------------------------
// Method: Read
// Arguments: archive - archive being read from
// Returns: true if successful
// Description: Overridable function - reads detail of class from archive
// ----------------------------------------------------------------------
bool ClonedGallery::Read(CreaturesArchive &archive)
{
int32 version = archive.GetFileVersion();
if(version >= 3)
{
if(!Gallery::Read( archive ))
return false;
archive >> myBaseImage;
}
else
{
_ASSERT(false);
return false;
}
//success
SharedGallery::theSharedGallery().AddClonedGallery( this );
// Destination format is...
uint32 dest = DisplayEngine::theRenderer().GetMyPixelFormat();
uint32 from = RGB_555;
if( myPixelFormat & C16_FLAG_565 )
from = RGB_565;
int i;
for( i=0; i < myCount; i++)
{
myBitmaps[i].Convert(from, dest);
}
if( dest == RGB_555 ) // Clear the 565 bit
myPixelFormat = myPixelFormat & ~1;
else // Set the 565 bit
myPixelFormat = myPixelFormat | 1;
return true;
}
Sprite* ClonedGallery::CreateSprite(EntityImage* owner)
{
Sprite* sprite=new ClonedSprite(owner);
ASSERT(sprite);
return sprite;
}
// ----------------------------------------------------------------------
// Method: InitBitmaps
// Arguments: None
//
// Returns: None
//
// Description: Creates all the bitmaps from the given sprite file
//
//
//
// ----------------------------------------------------------------------
bool ClonedGallery::InitBitmaps()
{
if (myBitmaps) delete [] myBitmaps;
File file(myName.GetFullPath().data(),GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE);
// First four bytes is a set of flags to say whther this is
// a 565 or 555 sprite file. I am assuming this is a 565 file
file.Read(&myPixelFormat,4);
file.SeekToBegin();
if((myPixelFormat & C16_16BITFLAG))
{
return DecompressC16(file);
}
int x = myName.GetFullPath().find_last_of(".");
if(x == -1)
{
return false;
}
std::string ext = myName.GetFullPath().substr(x, 3);
// check for a preferred C16 version
if(ext[1] == 'C' || ext[1] == 'c')
{
return DecompressC16(file);
}
uint32 size = file.GetSize();
ASSERT(size);
if(size)
{
// First four bytes is a set of flags to say whther this is
// a 565 or 555 sprite file. I am assuming this is a 565 file
file.Read(&myPixelFormat,4);
// Now the number of images in the file
uint16 numImages =0;
file.Read(&numImages,2);
// but we really want to use our count as we were
// initialised
if(myCount == 0)
myCount = numImages;
//create the correct number of bitmaps
myBitmaps=new Bitmap[myCount];
if(myBitmaps)
{
int16 bitmap_width;
int16 bitmap_height;
uint32 offset = 0;
uint32 actualBitmap =0;
// only read in data specific to you
int i;
for( i = 0; i < numImages; i++)
{
// Set the offset
file.Read(&offset,4);
// Now read in the width and height as shorts
file.Read(&bitmap_width,2);
file.Read(&bitmap_height,2);
if(i >= myBaseImage && i < myBaseImage + myCount)
{
myBitmaps[actualBitmap].SetOffset(offset);
myBitmaps[actualBitmap].SetWidth(bitmap_width);
myBitmaps[actualBitmap].SetHeight(bitmap_height);
actualBitmap++;
}
}
//now read in each bit
// actualBitmap =0;
uint32 dest = DisplayEngine::theRenderer().GetMyPixelFormat();
uint32 from = RGB_555;
if( myPixelFormat & C16_FLAG_565 )
from = RGB_565;
for(i = 0; i < myCount; i++)
{
// look for your data in the file
file.Seek(myBitmaps[i].GetOffset(),File::Start);
myBitmaps[i].LoadFromS16(file);
// myPixelFormat isn't what Dan expects, so this doesn't work!
// The variable is pantsly and inconsistently initialised
myBitmaps[i].Convert(from, dest);
if( dest == RGB_555 ) // Clear the 565 bit
myPixelFormat = myPixelFormat & ~1;
else // Set the 565 bit
myPixelFormat = myPixelFormat | 1;
}
file.Close();
return true;
}
}
//!!! if the file didn't exist it wouldn't get
// this far
return false;
}
void ClonedGallery::Recolour(const uint16 tintTable[65536])
{
int i;
for( i = 0; i < myCount; i++)
{
myBitmaps[i].Recolour(tintTable);
}
}
bool ClonedGallery::DecompressC16(File& file)
{
if (myBitmaps) delete [] myBitmaps;
uint32 size = file.GetSize();
if(size)
{
// First four bytes is a set of flags to say whther this is
// a 565 or 555 sprite file. I am assuming this is a 565 file
file.Read(&myPixelFormat,4);
myPixelFormat = myPixelFormat & ~C16_16BITFLAG;
// Now the number of images in the file
//create the correct number of bitmaps
uint16 numImages = 0;
file.Read(&numImages,2);
if( myCount == 0 )
myCount = numImages;
myBitmaps=new Bitmap[myCount];
int16 bitmap_width;
int16 bitmap_height;
uint32 offset = 0;
int actualBitmap = 0;
int i;
for( i = 0; i < numImages; i++)
{
// read the offset
file.Read(&offset,4);
// Now read in the width and height as shorts
file.Read(&bitmap_width,2);
file.Read(&bitmap_height,2);
if( i >= myBaseImage && i < myBaseImage + myCount )
{
myBitmaps[actualBitmap].SetOffset(offset);
myBitmaps[actualBitmap].SetWidth(bitmap_width);
myBitmaps[actualBitmap].SetHeight(bitmap_height);
++actualBitmap;
}
// bitmap->SetScanLines(file);
// skip scan lines
uint32 scanValue = 0;
// do one less scan line because we have the first offset
// value in myOffset in the header
int h;
for( h = bitmap_height-1; h--;)
{
file.Read(&scanValue,sizeof(scanValue));
}
}
//now read in each bit
uint32 dest = DisplayEngine::theRenderer().GetMyPixelFormat();
uint32 from = RGB_555;
if( myPixelFormat & C16_FLAG_565 )
from = RGB_565;
for(i = 0; i < myCount; i++)
{
file.Seek(myBitmaps[i].GetOffset(),File::Start);
myBitmaps[i].DecompressC16(file);
if (dest != from)
myBitmaps[i].Convert(from, dest);
}
if( dest == RGB_555 ) // Clear the 565 bit
myPixelFormat = myPixelFormat & ~1;
else // Set the 565 bit
myPixelFormat = myPixelFormat | 1;
return true;
}
//!!! if the file didn't exist it wouldn't get
// this far
return false;
}
| [
"[email protected]"
] | |
fcb05d90096d3aef04bc87b46da3946257a64e19 | 0c983f98a7fbe90888d5cf8ce7db990739536b5d | /HP-Socket/Src/HttpClient.cpp | 77e6f41b403324a27315a4223770267b01f27e4b | [
"Apache-2.0"
] | permissive | 442830589/HP-Socket | 42b63e20b8296c53d836dda1fb25c8f9e30e97a1 | 3a02cfc448c966af2038a8a98b3585884ca656a9 | refs/heads/master | 2021-01-01T06:29:03.345127 | 2017-07-17T02:48:28 | 2017-07-17T02:48:28 | 97,435,281 | 1 | 0 | null | 2017-07-17T04:29:09 | 2017-07-17T04:29:09 | null | UTF-8 | C++ | false | false | 14,474 | cpp | /*
* Copyright: JessMA Open Source ([email protected])
*
* Version : 4.3.1
* Author : Bruce Liang
* Website : http://www.jessma.org
* Project : https://github.com/ldcsaa
* Blog : http://www.cnblogs.com/ldcsaa
* Wiki : http://www.oschina.net/p/hp-socket
* QQ Group : 75375912, 44636872
*
* 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 "stdafx.h"
#include "HttpClient.h"
template<class R, class T, USHORT default_port> BOOL CHttpClientT<R, T, default_port>::CheckParams()
{
if(m_enLocalVersion != HV_1_1 && m_enLocalVersion != HV_1_0)
{
SetLastError(SE_INVALID_PARAM, __FUNCTION__, ERROR_INVALID_PARAMETER);
return FALSE;
}
return __super::CheckParams();
}
template<class R, class T, USHORT default_port> BOOL CHttpClientT<R, T, default_port>::SendRequest(LPCSTR lpszMethod, LPCSTR lpszPath, const THeader lpHeaders[], int iHeaderCount, const BYTE* pBody, int iLength)
{
USES_CONVERSION;
WSABUF szBuffer[2];
CStringA strHeader;
LPCSTR lpszHost = nullptr;
USHORT usPort = 0;
GetRemoteHost(&lpszHost, &usPort);
if(usPort == default_port) usPort = 0;
CStringA strPath;
::AdjustRequestPath(lpszPath, strPath);
m_objHttp.SetRequestPath(lpszMethod, strPath);
m_objHttp.ReloadCookies();
::MakeRequestLine(lpszMethod, lpszPath, m_enLocalVersion, strHeader);
::MakeHeaderLines(lpHeaders, iHeaderCount, &m_objHttp.GetCookieMap(), iLength, TRUE, -1, lpszHost, usPort, strHeader);
::MakeHttpPacket(strHeader, pBody, iLength, szBuffer);
return SendPackets(szBuffer, 2);
}
template<class R, class T, USHORT default_port> BOOL CHttpClientT<R, T, default_port>::SendLocalFile(LPCSTR lpszFileName, LPCSTR lpszMethod, LPCSTR lpszPath, const THeader lpHeaders[] = nullptr, int iHeaderCount = 0)
{
if(
strcmp(lpszMethod, HTTP_METHOD_POST) != 0 &&
strcmp(lpszMethod, HTTP_METHOD_PUT) != 0 &&
strcmp(lpszMethod, HTTP_METHOD_PATCH) != 0 )
{
::SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
CAtlFile file;
CAtlFileMapping<> fmap;
HRESULT hr = ::ReadSmallFile(CA2T(lpszFileName), file, fmap);
if(FAILED(hr))
{
::SetLastError(HRESULT_CODE(hr));
return FALSE;
}
return SendRequest(lpszMethod, lpszPath, lpHeaders, iHeaderCount, (BYTE*)(char*)fmap, (int)fmap.GetMappingSize());
}
template<class R, class T, USHORT default_port> BOOL CHttpClientT<R, T, default_port>::SendWSMessage(BOOL bFinal, BYTE iReserved, BYTE iOperationCode, const BYTE lpszMask[4], BYTE* pData, int iLength, ULONGLONG ullBodyLen)
{
WSABUF szBuffer[2];
BYTE szHeader[HTTP_MAX_WS_HEADER_LEN];
if(!::MakeWSPacket(bFinal, iReserved, iOperationCode, lpszMask, pData, iLength, ullBodyLen, szHeader, szBuffer))
return FALSE;
return SendPackets(szBuffer, 2);
}
// ------------------------------------------------------------------------------------------------------------- //
template<class T, USHORT default_port> BOOL CHttpSyncClientT<T, default_port>::Start(LPCTSTR lpszRemoteAddress, USHORT usPort, BOOL bAsyncConnect, LPCTSTR lpszBindAddress)
{
CleanupRequestResult();
if(!__super::Start(lpszRemoteAddress, usPort, TRUE, lpszBindAddress))
return FALSE;
DWORD dwWait = m_dwConnectTimeout != 0 ? m_dwConnectTimeout : INFINITE;
BOOL isOK = ::WaitForSingleObject(m_evWait, dwWait) == WAIT_OBJECT_0;
if(!isOK || m_enProgress != HSRP_DONE)
{
int ec = m_enProgress == HSRP_WAITING ? WSAETIMEDOUT : WSAECONNREFUSED;
if(!isOK) Stop();
SetLastError(SE_CONNECT_SERVER, __FUNCTION__, ec);
return FALSE;
}
return TRUE;
}
template<class T, USHORT default_port> BOOL CHttpSyncClientT<T, default_port>::SendRequest(LPCSTR lpszMethod, LPCSTR lpszPath, const THeader lpHeaders[], int iHeaderCount, const BYTE* pBody, int iLength)
{
CleanupRequestResult();
if(!__super::SendRequest(lpszMethod, lpszPath, lpHeaders, iHeaderCount, pBody, iLength))
return FALSE;
DWORD dwWait = m_dwRequestTimeout != 0 ? m_dwRequestTimeout : INFINITE;
BOOL isOK = ::WaitForSingleObject(m_evWait, dwWait) == WAIT_OBJECT_0;
if(!isOK || m_enProgress != HSRP_DONE)
{
int ec = m_enProgress == HSRP_WAITING ? WSAETIMEDOUT :
(m_enProgress == HSRP_CLOSE ? WSAECONNABORTED : ERROR_INVALID_DATA);
if(!isOK) Stop();
SetLastError(SE_DATA_SEND, __FUNCTION__, ec);
return FALSE;
}
return TRUE;
}
template<class T, USHORT default_port> BOOL CHttpSyncClientT<T, default_port>::SendWSMessage(BOOL bFinal, BYTE iReserved, BYTE iOperationCode, const BYTE lpszMask[4], BYTE* pData, int iLength, ULONGLONG ullBodyLen)
{
CleanupRequestResult();
if(!__super::SendWSMessage(bFinal, iReserved, iOperationCode, lpszMask, pData, iLength, ullBodyLen))
return FALSE;
DWORD dwWait = m_dwRequestTimeout != 0 ? m_dwRequestTimeout : INFINITE;
BOOL isOK = ::WaitForSingleObject(m_evWait, dwWait) == WAIT_OBJECT_0;
if(!isOK || m_enProgress != HSRP_DONE)
{
int ec = m_enProgress == HSRP_WAITING ? WSAETIMEDOUT :
(m_enProgress == HSRP_CLOSE ? WSAECONNABORTED : ERROR_INVALID_DATA);
if(!isOK) Stop();
SetLastError(SE_DATA_SEND, __FUNCTION__, ec);
return FALSE;
}
return TRUE;
}
template<class T, USHORT default_port> BOOL CHttpSyncClientT<T, default_port>::OpenUrl(LPCSTR lpszMethod, LPCSTR lpszUrl, const THeader lpHeaders[], int iHeaderCount, const BYTE* pBody, int iLength, BOOL bForceReconnect)
{
BOOL bHttps;
USHORT usPort;
CStringA strHost;
CStringA strPath;
if(!::ParseUrl(lpszUrl, bHttps, strHost, usPort, strPath))
{
SetLastError(SE_CONNECT_SERVER, __FUNCTION__, WSAEADDRNOTAVAIL);
return FALSE;
}
if((bHttps && default_port == HTTP_DEFAULT_PORT) || (!bHttps && default_port == HTTPS_DEFAULT_PORT))
{
SetLastError(SE_CONNECT_SERVER, __FUNCTION__, WSAEPROTOTYPE);
return FALSE;
}
if(HasStarted())
{
BOOL bNeedStop = bForceReconnect;
if(!bNeedStop)
{
LPCSTR lpszHost = nullptr;
USHORT usPort2 = 0;
GetRemoteHost(&lpszHost, &usPort2);
if(strHost.CompareNoCase(lpszHost) != 0 || usPort != usPort2)
bNeedStop = TRUE;
}
if(bNeedStop) Stop();
}
EnServiceState state = GetState();
if(state != SS_STARTED)
{
if(state == SS_STARTING)
{
do
{
::Sleep(50);
state = GetState();
} while(state != SS_STARTED && state != SS_STOPPED);
}
else
{
while(state != SS_STOPPED)
{
::Sleep(50);
state = GetState();
}
Start(CA2T(strHost), usPort, FALSE, nullptr);
state = GetState();
}
if(state == SS_STOPPED)
return FALSE;
}
return SendRequest(lpszMethod, strPath, lpHeaders, iHeaderCount, pBody, iLength);
}
template<class T, USHORT default_port> BOOL CHttpSyncClientT<T, default_port>::CleanupRequestResult()
{
m_pHttpObj = &m_objHttp;
m_enProgress = HSRP_WAITING;
m_szBuffer.Free();
m_objHttp2.Reset();
m_evWait.Reset();
return TRUE;
}
template<class T, USHORT default_port> void CHttpSyncClientT<T, default_port>::SetRequestEvent(EnHttpSyncRequestProgress enProgress, BOOL bCopyHttpObj)
{
if(m_enProgress != HSRP_WAITING)
return;
m_enProgress = enProgress;
if(bCopyHttpObj)
{
m_objHttp2.CopyData(m_objHttp);
m_objHttp2.CopyWSContext(m_objHttp);
m_pHttpObj = &m_objHttp2;
}
m_evWait.Set();
}
template<class T, USHORT default_port> BOOL CHttpSyncClientT<T, default_port>::GetResponseBody(LPCBYTE* lpszBody, int* iLength)
{
ASSERT(lpszBody && iLength);
*lpszBody = m_szBuffer.Ptr();
*iLength = (int)m_szBuffer.Size();
return TRUE;
}
template<class T, USHORT default_port> EnHandleResult CHttpSyncClientT<T, default_port>::OnHandShake(ITcpClient* pSender, CONNID dwConnID)
{
EnHandleResult rs = HR_OK;
if(m_pListener2 != nullptr)
rs = m_pListener2->OnHandShake(pSender, dwConnID);
if(rs != HR_ERROR)
SetRequestEvent(HSRP_DONE, FALSE);
return rs;
}
template<class T, USHORT default_port> EnHandleResult CHttpSyncClientT<T, default_port>::OnClose(ITcpClient* pSender, CONNID dwConnID, EnSocketOperation enOperation, int iErrorCode)
{
EnHandleResult rs = HR_OK;
if(m_pListener2 != nullptr)
rs = m_pListener2->OnClose(pSender, dwConnID, enOperation, iErrorCode);
SetRequestEvent(HSRP_CLOSE);
return rs;
}
template<class T, USHORT default_port> EnHttpParseResult CHttpSyncClientT<T, default_port>::OnBody(IHttpClient* pSender, CONNID dwConnID, const BYTE* pData, int iLength)
{
EnHttpParseResult rs = HPR_OK;
if(m_pListener2 != nullptr)
rs = m_pListener2->OnBody(pSender, dwConnID, pData, iLength);
if(rs != HPR_ERROR)
m_szBuffer.Cat(pData, iLength);
return rs;
}
template<class T, USHORT default_port> EnHttpParseResult CHttpSyncClientT<T, default_port>::OnMessageComplete(IHttpClient* pSender, CONNID dwConnID)
{
EnHttpParseResult rs = HPR_OK;
if(m_pListener2 != nullptr)
rs = m_pListener2->OnMessageComplete(pSender, dwConnID);
if(rs != HPR_ERROR)
{
if(GetUpgradeType() == HUT_NONE)
SetRequestEvent(HSRP_DONE);
}
return rs;
}
template<class T, USHORT default_port> EnHttpParseResult CHttpSyncClientT<T, default_port>::OnUpgrade(IHttpClient* pSender, CONNID dwConnID, EnHttpUpgradeType enUpgradeType)
{
EnHttpParseResult rs = HPR_OK;
if(m_pListener2 != nullptr)
rs = m_pListener2->OnUpgrade(pSender, dwConnID, enUpgradeType);
if(rs != HPR_ERROR)
{
if(enUpgradeType == HUT_WEB_SOCKET)
{
SetRequestEvent(HSRP_DONE);
rs = HPR_OK;
}
else
{
SetRequestEvent(HSRP_ERROR);
rs = HPR_ERROR;
}
}
return rs;
}
template<class T, USHORT default_port> EnHttpParseResult CHttpSyncClientT<T, default_port>::OnParseError(IHttpClient* pSender, CONNID dwConnID, int iErrorCode, LPCSTR lpszErrorDesc)
{
EnHttpParseResult rs = HPR_OK;
if(m_pListener2 != nullptr)
rs = m_pListener2->OnParseError(pSender, dwConnID, iErrorCode, lpszErrorDesc);
SetRequestEvent(HSRP_ERROR);
return rs;
}
template<class T, USHORT default_port> EnHandleResult CHttpSyncClientT<T, default_port>::OnWSMessageBody(IHttpClient* pSender, CONNID dwConnID, const BYTE* pData, int iLength)
{
EnHandleResult rs = HR_OK;
if(m_pListener2 != nullptr)
rs = m_pListener2->OnWSMessageBody(pSender, dwConnID, pData, iLength);
if(rs != HR_ERROR)
m_szBuffer.Cat(pData, iLength);
return rs;
}
template<class T, USHORT default_port> EnHandleResult CHttpSyncClientT<T, default_port>::OnWSMessageComplete(IHttpClient* pSender, CONNID dwConnID)
{
EnHandleResult rs = HR_OK;
if(m_pListener2 != nullptr)
rs = m_pListener2->OnWSMessageComplete(pSender, dwConnID);
if(rs != HR_ERROR)
SetRequestEvent(HSRP_DONE);
return rs;
}
template<class T, USHORT default_port> EnHandleResult CHttpSyncClientT<T, default_port>::OnPrepareConnect(ITcpClient* pSender, CONNID dwConnID, SOCKET socket)
{
EnHandleResult rs = HR_OK;
if(m_pListener2 != nullptr)
return m_pListener2->OnPrepareConnect(pSender, dwConnID, socket);
return rs;
}
template<class T, USHORT default_port> EnHandleResult CHttpSyncClientT<T, default_port>::OnConnect(ITcpClient* pSender, CONNID dwConnID)
{
EnHandleResult rs = HR_OK;
if(m_pListener2 != nullptr)
return m_pListener2->OnConnect(pSender, dwConnID);
return rs;
}
template<class T, USHORT default_port> EnHandleResult CHttpSyncClientT<T, default_port>::OnSend(ITcpClient* pSender, CONNID dwConnID, const BYTE* pData, int iLength)
{
EnHandleResult rs = HR_OK;
if(m_pListener2 != nullptr)
return m_pListener2->OnSend(pSender, dwConnID, pData, iLength);
return rs;
}
template<class T, USHORT default_port> EnHttpParseResult CHttpSyncClientT<T, default_port>::OnMessageBegin(IHttpClient* pSender, CONNID dwConnID)
{
EnHttpParseResult rs = HPR_OK;
if(m_pListener2 != nullptr)
rs = m_pListener2->OnMessageBegin(pSender, dwConnID);
return rs;
}
template<class T, USHORT default_port> EnHttpParseResult CHttpSyncClientT<T, default_port>::OnStatusLine(IHttpClient* pSender, CONNID dwConnID, USHORT usStatusCode, LPCSTR lpszDesc)
{
EnHttpParseResult rs = HPR_OK;
if(m_pListener2 != nullptr)
rs = m_pListener2->OnStatusLine(pSender, dwConnID, usStatusCode, lpszDesc);
return rs;
}
template<class T, USHORT default_port> EnHttpParseResult CHttpSyncClientT<T, default_port>::OnHeader(IHttpClient* pSender, CONNID dwConnID, LPCSTR lpszName, LPCSTR lpszValue)
{
EnHttpParseResult rs = HPR_OK;
if(m_pListener2 != nullptr)
rs = m_pListener2->OnHeader(pSender, dwConnID, lpszName, lpszValue);
return rs;
}
template<class T, USHORT default_port> EnHttpParseResult CHttpSyncClientT<T, default_port>::OnHeadersComplete(IHttpClient* pSender, CONNID dwConnID)
{
EnHttpParseResult rs = HPR_OK;
if(m_pListener2 != nullptr)
rs = m_pListener2->OnHeadersComplete(pSender, dwConnID);
return rs;
}
template<class T, USHORT default_port> EnHttpParseResult CHttpSyncClientT<T, default_port>::OnChunkHeader(IHttpClient* pSender, CONNID dwConnID, int iLength)
{
EnHttpParseResult rs = HPR_OK;
if(m_pListener2 != nullptr)
rs = m_pListener2->OnChunkHeader(pSender, dwConnID, iLength);
return rs;
}
template<class T, USHORT default_port> EnHttpParseResult CHttpSyncClientT<T, default_port>::OnChunkComplete(IHttpClient* pSender, CONNID dwConnID)
{
EnHttpParseResult rs = HPR_OK;
if(m_pListener2 != nullptr)
rs = m_pListener2->OnChunkComplete(pSender, dwConnID);
return rs;
}
template<class T, USHORT default_port> EnHandleResult CHttpSyncClientT<T, default_port>::OnWSMessageHeader(IHttpClient* pSender, CONNID dwConnID, BOOL bFinal, BYTE iReserved, BYTE iOperationCode, const BYTE lpszMask[4], ULONGLONG ullBodyLen)
{
EnHandleResult rs = HR_OK;
if(m_pListener2 != nullptr)
rs = m_pListener2->OnWSMessageHeader(pSender, dwConnID, bFinal, iReserved, iOperationCode, lpszMask, ullBodyLen);
return rs;
}
// ------------------------------------------------------------------------------------------------------------- //
template class CHttpClientT<IHttpRequester, CTcpClient, HTTP_DEFAULT_PORT>;
template class CHttpSyncClientT<CTcpClient, HTTP_DEFAULT_PORT>;
#ifdef _SSL_SUPPORT
#include "SSLClient.h"
template class CHttpClientT<IHttpRequester, CSSLClient, HTTPS_DEFAULT_PORT>;
template class CHttpSyncClientT<CSSLClient, HTTPS_DEFAULT_PORT>;
#endif
| [
"[email protected]"
] | |
2a2fd424760bbf61fda1998f2822248be0ba6e2e | 35266a567d1f4e389bb234e72e2d8e4af06bb707 | /tests/TestLocalReturn.cpp | e2c76f6cd5dfe6254c4964dc37515138e4476c56 | [
"MIT"
] | permissive | WheretIB/nullc | 6c6ec4a0f53a28c1ede2c0e3e4a9d0af5437d96d | bac1a2b2c35676a61392c094b142b50b92952fc8 | refs/heads/master | 2022-11-11T03:38:03.706686 | 2022-11-06T01:55:45 | 2022-11-06T01:55:45 | 32,209,998 | 161 | 13 | MIT | 2022-11-06T01:55:46 | 2015-03-14T12:15:38 | C++ | UTF-8 | C++ | false | false | 2,678 | cpp | #include "TestBase.h"
const char *testLocalReturn1 =
"int ref boo(){ int a; return &a; }\r\n\
void clear(int a, b, c){}\r\n\
int ref x = boo();\r\n\
*x = 5;\r\n\
clear(0, 0, 0);\r\n\
return *x;";
TEST_RESULT("Returning pointer to local (obvious)", testLocalReturn1, "5");
const char *testLocalReturn2 =
"int ref foo(int ref x){ return x; }\r\n\
int ref boo(){ int a; return foo(&a); }\r\n\
void clear(int a, b, c){}\r\n\
int ref x = boo();\r\n\
*x = 5;\r\n\
clear(0, 0, 0);\r\n\
return *x;";
TEST_RESULT("Returning pointer to local (not obvious)", testLocalReturn2, "5");
const char *testLocalReturn3 =
"void clear(int a, b, c){}\r\n\
auto foo2(int x){ return &x; }\r\n\
int ref x = foo2(6);\r\n\
*x = 5;\r\n\
clear(0, 0, 0);\r\n\
return *x;";
TEST_RESULT("Returning pointer to local 3", testLocalReturn3, "5");
const char *testLocalReturn4 =
"void clear(int[10] a){}\r\n\
auto foo3(){ int[3] bar; int i = 2; return &bar[i]; }\r\n\
int ref x = foo3();\r\n\
*x = 5;\r\n\
clear({0,0,0,0,0,0,0,0,0,0});\r\n\
return *x;";
TEST_RESULT("Returning pointer to local 4", testLocalReturn4, "5");
const char *testLocalReturn5 =
"import std.math;\r\n\
void clear(int[16] a){}\r\n\
auto foo4(){ float4[3] bar; int i = 2; return &bar[i].x; }\r\n\
float ref x = foo4();\r\n\
*x = 5;\r\n\
clear({0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0});\r\n\
return int(*x);";
TEST_RESULT("Returning pointer to local 5", testLocalReturn5, "5");
const char *testLocalReturn6 =
"import std.math;\r\n\
void clear(int[32] a){}\r\n\
class Foo{ int[3] arr; float4[3] arr2;}\r\n\
auto foo5(){ Foo[3] bar; int i = 2; return &bar[i].arr[2]; }\r\n\
int ref x = foo5();\r\n\
*x = 5;\r\n\
clear({0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0});\r\n\
return *x;";
TEST_RESULT("Returning pointer to local 6", testLocalReturn6, "5");
const char *testLocalReturn7 =
"import std.math;\r\n\
void clear(int[64] a){}\r\n\
class Foo{ int[3] arr; float4[3] arr2;}\r\n\
auto foo6(){ Foo[3] bar; int i = 2; return &bar[i].arr2[2].w; }\r\n\
float ref x = foo6();\r\n\
*x = 5;\r\n\
clear({0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0});\r\n\
return int(*x);";
TEST_RESULT("Returning pointer to local 7", testLocalReturn7, "5");
const char *testLocalArrayReturn1 =
"char[] foo()\r\n\
{\r\n\
auto x = \"hello\";\r\n\
char[] y = x;\r\n\
return y;\r\n\
}\r\n\
void test(int a, b, c){}\r\n\
char[] res = foo();\r\n\
test(0,0,0);\r\n\
return res[0]-'g' + res[1]-'d';";
TEST_RESULT("Returning pointer to local array 1", testLocalArrayReturn1, "2");
| [
"[email protected]"
] | |
209123e60b3c7b75aa5683a2419bbcba1db97a09 | 4d42762ddb5034b84585170ca320f9903024fa7f | /build/iOS/Debug/include/Fuse.Navigation.EnterExitAnimation.h | fb808b94b026a7b906da09fb4672db53fbf7144c | [] | no_license | nikitph/omkareshwar-ios | 536def600f378946b95362e2e2f98f8f52b588e0 | 852a1d802b76dbc61c2c45164f180004b7d667e6 | refs/heads/master | 2021-01-01T18:58:16.397969 | 2017-08-01T18:53:20 | 2017-08-01T18:53:20 | 98,473,502 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,556 | h | // This file was generated based on '/Users/Omkareshwar/Library/Application Support/Fusetools/Packages/Fuse.Navigation/1.1.1/$.uno'.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Fuse.Animations.IBasePlayerFeedback.h>
#include <Fuse.Animations.IUnwrappedPlayerFeedback.h>
#include <Fuse.Binding.h>
#include <Fuse.INotifyUnrooted.h>
#include <Fuse.IProperties.h>
#include <Fuse.Navigation.NavigationAnimation.h>
#include <Fuse.Scripting.IScriptObject.h>
#include <Uno.Collections.ICollection-1.h>
#include <Uno.Collections.IEnumerable-1.h>
#include <Uno.Collections.IList-1.h>
namespace g{namespace Fuse{namespace Navigation{struct EnterExitAnimation;}}}
namespace g{namespace Fuse{namespace Navigation{struct NavigationArgs;}}}
namespace g{
namespace Fuse{
namespace Navigation{
// public abstract class EnterExitAnimation :1167
// {
::g::Fuse::Navigation::NavigationAnimation_type* EnterExitAnimation_typeof();
void EnterExitAnimation__ctor_6_fn(EnterExitAnimation* __this);
void EnterExitAnimation__ForceUpdate_fn(EnterExitAnimation* __this);
void EnterExitAnimation__IsMatch_fn(EnterExitAnimation* __this, double* progress, bool* __retval);
void EnterExitAnimation__OnNavigationStateChanged_fn(EnterExitAnimation* __this, uObject* sender, ::g::Fuse::Navigation::NavigationArgs* state);
struct EnterExitAnimation : ::g::Fuse::Navigation::NavigationAnimation
{
bool NegativeProgress;
bool PositiveProgress;
void ctor_6();
bool IsMatch(double progress);
};
// }
}}} // ::g::Fuse::Navigation
| [
"[email protected]"
] | |
4321603d31668832e4658c280be41d5c75f887e1 | 9547ed2d33735ead3bc7ee01097481978bdf1599 | /1180.cpp | 94df312f2c6b75b1c080a3e23107b333f850e3e3 | [] | no_license | EdsonYamamoto/URI-Online-Judge-Beginner | 31c7d9bdb75c5e4abab8967cef5e964e2325e883 | ec8020c67d9553003e84f1d0f19b27ce2c422d14 | refs/heads/master | 2021-01-12T02:57:20.391330 | 2017-02-16T18:35:32 | 2017-02-16T18:35:32 | 78,139,269 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 972 | cpp | /*
URI Online Judge | 1180
Menor e Posição
Adaptado por Neilor Tonin, URI Brasil
Timelimit: 1
Faça um programa que leia um valor N. Este N será o tamanho de um vetor X[N]. A seguir, leia cada um dos valores de X, encontre o menor elemento deste vetor e a sua posição dentro do vetor, mostrando esta informação.
Entrada
A primeira linha de entrada contem um único inteiro N (1 < N < 1000), indicando o número de elementos que deverão ser lidos em seguida para o vetor X[N] de inteiros. A segunda linha contém cada um dos N valores, separados por um espaço.
Saída
A primeira linha apresenta a mensagem “Menor valor:” seguida de um espaço e do menor valor lido na entrada. A segunda linha apresenta a mensagem “Posicao:” seguido de um espaço e da posição do vetor na qual se encontra o menor valor lido, lembrando que o vetor inicia na posição zero.
Exemplo de Entrada Exemplo de Saída
10
1 2 3 4 -5 6 7 8 9 10
Menor valor: -5
Posicao: 4
*/ | [
"[email protected]"
] | |
825c9fbaf17a4638273c220590250c95012a2264 | 205dfc86eb9b359fbd512713eb76881c28d29862 | /IOThread.cpp | 527d749f98c9e1d3159b806d97fb12eeea905e67 | [] | no_license | jcharpenay/MusicTools | eaab9d82d69fc36898a51d1130fbaac7f369d4ea | 18e839019262f220f2c6f50a76291d01f0c05954 | refs/heads/master | 2021-01-24T18:47:38.388878 | 2017-05-04T19:57:52 | 2017-05-04T19:57:52 | 84,478,211 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,903 | cpp | #include "Precompiled.h"
#include "Console.h"
#include "IOThread.h"
FileSystem::IOThread::IOThread( Explorer & _explorer, bool _verbose, int64_t _tasksMaxDataSize ) :
m_explorer( &_explorer ),
m_verbose( _verbose ),
m_tasksMaxDataSize( _tasksMaxDataSize ),
m_tasksCompleted( Event::MANUAL_RESET, Event::SET ),
m_wakeUp( Event::AUTO_RESET, Event::NOT_SET ) {
}
void FileSystem::IOThread::CreateFolder( const FolderID & _parentFolderID, const String & _folderName ) {
AddTask( new CreateFolderTask( _parentFolderID, _folderName ) );
}
void FileSystem::IOThread::DeleteFolder( const FolderID & _folderID ) {
AddTask( new DeleteFolderTask( _folderID ) );
}
void FileSystem::IOThread::CreateFile( const FolderID & _parentFolderID, const String & _fileName, File & _file, bool _readOnly ) {
AddTask( new CreateFileTask( _parentFolderID, _fileName, _file, _readOnly ) );
}
void FileSystem::IOThread::WriteFile( const FileID & _fileID, File & _file ) {
AddTask( new WriteFileTask( _fileID, _file ) );
}
void FileSystem::IOThread::DeleteFile( const FileID & _fileID ) {
AddTask( new DeleteFileTask( _fileID ) );
}
void FileSystem::IOThread::SetFileReadOnly( const FileID & _fileID, bool _readOnly ) {
AddTask( new SetFileReadOnlyTask( _fileID, _readOnly ) );
}
void FileSystem::IOThread::WaitTaskCompletion() {
m_tasksCompleted.Wait();
}
void FileSystem::IOThread::Run() {
while ( !ShouldStopThread() ) {
Task * task = GetCurrentTask();
if ( task != NULL ) {
task->Run( *m_explorer, m_verbose );
CurrentTaskCompleted();
} else {
m_wakeUp.Wait();
}
}
}
void FileSystem::IOThread::StopThreadRequested() {
m_wakeUp.Trigger();
}
FileSystem::IOThread::CreateFolderTask::CreateFolderTask( const FolderID & _parentFolderID, const String & _folderName ) :
m_parentFolderID( _parentFolderID ),
m_folderName( _folderName ) {
}
void FileSystem::IOThread::CreateFolderTask::Run( Explorer & _explorer, bool _verbose ) {
FolderID createdFolderID;
const bool succeeded = _explorer.CreateFolder( m_parentFolderID, m_folderName, createdFolderID );
if ( _verbose ) {
if ( succeeded ) {
Printf( TEXT( "Created folder \"%s\"\n" ), createdFolderID.GetPath().AsChar() );
} else {
Printf( TEXT( "Couldn't create folder \"%s\"\n" ), m_folderName.AsChar() );
}
}
}
FileSystem::IOThread::DeleteFolderTask::DeleteFolderTask( const FolderID & _folderID ) :
m_folderID( _folderID ) {
}
void FileSystem::IOThread::DeleteFolderTask::Run( Explorer & _explorer, bool _verbose ) {
const bool succeeded = _explorer.DeleteFolder( m_folderID );
if ( _verbose ) {
if ( succeeded ) {
Printf( TEXT( "Deleted folder \"%s\"\n" ), m_folderID.GetPath().AsChar() );
} else {
Printf( TEXT( "Couldn't delete folder \"%s\"\n" ), m_folderID.GetPath().AsChar() );
}
}
}
FileSystem::IOThread::CreateFileTask::CreateFileTask( const FolderID & _parentFolderID, const String & _fileName, File & _file, bool _readOnly ) :
m_parentFolderID( _parentFolderID ),
m_fileName( _fileName ),
m_file( &_file ),
m_readOnly( _readOnly ) {
}
void FileSystem::IOThread::CreateFileTask::Run( Explorer & _explorer, bool _verbose ) {
FileID createdFileID;
const bool succeeded = _explorer.CreateFile( m_parentFolderID, m_fileName, *m_file, createdFileID );
if ( succeeded && m_readOnly ) {
_explorer.SetFileReadOnly( createdFileID, true );
}
if ( _verbose ) {
if ( succeeded ) {
Printf( TEXT( "Created file \"%s\"\n" ), createdFileID.GetPath().AsChar() );
} else {
Printf( TEXT( "Couldn't create file \"%s\"\n" ), m_fileName.AsChar() );
}
}
}
int64_t FileSystem::IOThread::CreateFileTask::DataSize() const {
return m_file->GetBuffer().Size();
}
FileSystem::IOThread::WriteFileTask::WriteFileTask( const FileID & _fileID, File & _file ) :
m_fileID( _fileID ),
m_file( &_file ) {
}
void FileSystem::IOThread::WriteFileTask::Run( Explorer & _explorer, bool _verbose ) {
const bool succeeded = _explorer.WriteFile( m_fileID, *m_file );
if ( _verbose ) {
if ( succeeded ) {
Printf( TEXT( "Updated file \"%s\"\n" ), m_fileID.GetPath().AsChar() );
} else {
Printf( TEXT( "Couldn't write file \"%s\"\n" ), m_fileID.GetPath().AsChar() );
}
}
}
int64_t FileSystem::IOThread::WriteFileTask::DataSize() const {
return m_file->GetBuffer().Size();
}
FileSystem::IOThread::DeleteFileTask::DeleteFileTask( const FileID & _fileID ) :
m_fileID( _fileID ) {
}
void FileSystem::IOThread::DeleteFileTask::Run( Explorer & _explorer, bool _verbose ) {
const bool succeeded = _explorer.DeleteFile( m_fileID );
if ( _verbose ) {
if ( succeeded ) {
Printf( TEXT( "Deleted file \"%s\"\n" ), m_fileID.GetPath().AsChar() );
} else {
Printf( TEXT( "Couldn't delete file \"%s\"\n" ), m_fileID.GetPath().AsChar() );
}
}
}
FileSystem::IOThread::SetFileReadOnlyTask::SetFileReadOnlyTask( const FileID & _fileID, bool _readOnly ) :
m_fileID( _fileID ),
m_readOnly( _readOnly ) {
}
void FileSystem::IOThread::SetFileReadOnlyTask::Run( Explorer & _explorer, bool _verbose ) {
_explorer.SetFileReadOnly( m_fileID, m_readOnly );
}
void FileSystem::IOThread::AddTask( Task * _task ) {
if ( m_tasksMaxDataSize > 0 ) {
while ( m_tasksDataSize >= m_tasksMaxDataSize ) {
Sleep( 0 );
}
}
ScopedLock< SpinLock > scopedLock( m_tasksLock );
m_tasks.Add( _task );
m_tasksDataSize.Add( _task->DataSize() );
m_tasksCompleted.Reset();
m_wakeUp.Trigger();
}
FileSystem::IOThread::Task * FileSystem::IOThread::GetCurrentTask() {
ScopedLock< SpinLock > scopedLock( m_tasksLock );
if ( m_tasks.IsEmpty() ) {
return NULL;
} else {
return m_tasks.First();
}
}
void FileSystem::IOThread::CurrentTaskCompleted() {
Task * task;
{
ScopedLock< SpinLock > scopedLock( m_tasksLock );
task = m_tasks.First();
m_tasks.RemoveIndex( 0 );
m_tasksDataSize.Add( -task->DataSize() );
if ( m_tasks.IsEmpty() ) {
m_tasksCompleted.Trigger();
}
}
delete task;
}
| [
"[email protected]"
] | |
fedee17c4908a2e77ba4281c562e832ceb180ff1 | aec32cfe439afb339641c872e7417fa7ead1a386 | /proto.hpp | 02ffe7626aefb0c1e444415d6a4a35a190c0dbf0 | [] | no_license | glushenkovIG/taptaptap | 7acfb6d18b56d229de9f7380321c3d8b0148a349 | 1690066acd98ae9eb45f9b1e2997cede7e95d3cf | refs/heads/master | 2020-08-02T17:12:29.329407 | 2019-09-28T04:31:21 | 2019-09-28T04:31:21 | 211,441,444 | 0 | 0 | null | 2019-09-28T04:00:28 | 2019-09-28T04:00:28 | null | UTF-8 | C++ | false | false | 1,701 | hpp | #pragma once
#include <stdint.h>
namespace proto
{
#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
# define NEED_TO_BSWAP_EVERYTHING() 0
inline uint16_t bswap(uint16_t x) { return x; }
inline uint32_t bswap(uint32_t x) { return x; }
#elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
# define NEED_TO_BSWAP_EVERYTHING() 1
inline uint16_t bswap(uint16_t x) { return __builtin_bswap16(x); }
inline uint32_t bswap(uint32_t x) { return __builtin_bswap32(x); }
#else
# error "Here's a nickel kid..."
#endif
// This represents a value in network byte order (that is, big endian).
template<class T>
struct nbo
{
T raw;
T load() const { return bswap(raw); }
void store(T x) { raw = bswap(x); }
};
struct ipv4_Header
{
#if NEED_TO_BSWAP_EVERYTHING()
unsigned ihl : 4;
unsigned ver : 4;
#else
unsigned ver : 4;
unsigned ihl : 4;
#endif
uint8_t tos;
nbo<uint16_t> len;
nbo<uint16_t> id;
nbo<uint16_t> mixed;
uint8_t ttl;
uint8_t proto;
nbo<uint16_t> csum;
nbo<uint32_t> saddr;
nbo<uint32_t> daddr;
} __attribute__((packed));
enum
{
TCP_FIN = 1 << 0,
TCP_SYN = 1 << 1,
TCP_RST = 1 << 2,
TCP_PSH = 1 << 3,
TCP_ACK = 1 << 4,
TCP_URG = 1 << 5,
TCP_ECE = 1 << 6,
TCP_CWR = 1 << 7,
};
struct tcp_Header
{
nbo<uint16_t> sport;
nbo<uint16_t> dport;
nbo<uint32_t> seq;
nbo<uint32_t> ack;
#if NEED_TO_BSWAP_EVERYTHING()
unsigned reserved : 4;
unsigned data_offset : 4;
#else
unsigned data_offset : 4;
unsigned reserved : 4;
#endif
uint8_t flags;
nbo<uint16_t> win;
nbo<uint16_t> csum;
nbo<uint16_t> urgent_ptr;
} __attribute__((packed));
#undef NEED_TO_BSWAP_EVERYTHING
}
| [
"[email protected]"
] | |
5fa2d6b2c46213d671c896ee19f7605886b2582b | ab270b50335ae1e65ae487dbc513669917d2988f | /test/layout/011_09.ci.re | ba5ef055bbbb6e01a74ab5acb4b236415b0f787a | [
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-public-domain"
] | permissive | ryandesign/re2c | a2bab466e901d5214f16fd357d103d73873fadfd | e2f29c1691759aabac3398e363c7d455bd0fef6e | refs/heads/master | 2022-11-15T06:56:20.443998 | 2020-07-04T09:34:16 | 2020-07-04T09:39:45 | 277,114,415 | 1 | 0 | NOASSERTION | 2020-07-04T13:24:19 | 2020-07-04T13:24:19 | null | UTF-8 | C++ | false | false | 45 | re | /*!re2c
<x> "a"{1,2} => z {}
<y, x>*=>x{}
*/ | [
"[email protected]"
] | |
372a8977213f48b0e49976f5e3b11773acbdfcdf | 32ca6fefb239009c47ac5253fc64a15a4e1bf9f1 | /Cplusplus/EvolutionBasedPhysics/PositionBasedDynamics/PositionBasedFluids.cpp | a11fafd096c1dcee8de5834d8412d519e485beeb | [] | no_license | szmybs/PhysIKA_Cloud | aa371dc333703e7e0f963b249adbb6c90c7b41f2 | 9ad022d31e64fa48e5e1a9a2ae8e6702a3b321a1 | refs/heads/main | 2023-04-25T08:45:33.801882 | 2021-05-07T06:04:11 | 2021-05-07T06:04:11 | 312,967,199 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,029 | cpp | #include "PositionBasedFluids.h"
#include <cfloat>
#include "SPHKernels.h"
#include<iostream>
using namespace PBD;
// ----------------------------------------------------------------------------------------------
bool PositionBasedFluids::computePBFDensity(
const unsigned int particleIndex,
const unsigned int numberOfParticles,
const Vector3r x[],
const Real mass[],
const Vector3r boundaryX[],
const Real boundaryPsi[],
const unsigned int numNeighbors,
const unsigned int neighbors[],
const Real density0,
const bool boundaryHandling,
Real &density_err,
Real &density)
{
// Compute current density for particle i
density = mass[particleIndex] * CubicKernel::W_zero();
for (unsigned int j = 0; j < numNeighbors; j++)
{
const unsigned int neighborIndex = neighbors[j];
if (neighborIndex < numberOfParticles) // Test if fluid particle
{
density += mass[neighborIndex] * CubicKernel::W(x[particleIndex] - x[neighborIndex]);
}
else if (boundaryHandling)
{
// Boundary: Akinci2012
density += boundaryPsi[neighborIndex - numberOfParticles] * CubicKernel::W(x[particleIndex] - boundaryX[neighborIndex - numberOfParticles]);
}
}
density_err = std::max(density, density0) - density0;
return true;
}
// ----------------------------------------------------------------------------------------------
bool PositionBasedFluids::computePBFLagrangeMultiplier(
const unsigned int particleIndex,
const unsigned int numberOfParticles,
const Vector3r x[],
const Real mass[],
const Vector3r boundaryX[],
const Real boundaryPsi[],
const Real density,
const unsigned int numNeighbors,
const unsigned int neighbors[],
const Real density0,
const bool boundaryHandling,
Real &lambda)
{
const Real eps = 1.0e-6;
// Evaluate constraint function
const Real C = std::max(density / density0 - 1.0, 0.0); // clamp to prevent particle clumping at surface
if (C != 0.0)
{
// Compute gradients dC/dx_j
Real sum_grad_C2 = 0.0;
Vector3r gradC_i(0.0, 0.0, 0.0);
for (unsigned int j = 0; j < numNeighbors; j++)
{
const unsigned int neighborIndex = neighbors[j];
if (neighborIndex < numberOfParticles) // Test if fluid particle
{
const Vector3r gradC_j = -mass[neighborIndex] / density0 * CubicKernel::gradW(x[particleIndex] - x[neighborIndex]);
sum_grad_C2 += gradC_j.squaredNorm();
gradC_i -= gradC_j;
}
else if (boundaryHandling)
{
// Boundary: Akinci2012
const Vector3r gradC_j = -boundaryPsi[neighborIndex - numberOfParticles] / density0 * CubicKernel::gradW(x[particleIndex] - boundaryX[neighborIndex - numberOfParticles]);
sum_grad_C2 += gradC_j.squaredNorm();
gradC_i -= gradC_j;
}
}
sum_grad_C2 += gradC_i.squaredNorm();
// Compute lambda
lambda = -C / (sum_grad_C2 + eps);
}
else
lambda = 0.0;
return true;
}
// ----------------------------------------------------------------------------------------------
bool PositionBasedFluids::solveDensityConstraint(
const unsigned int particleIndex,
const unsigned int numberOfParticles,
const Vector3r x[],
const Real mass[],
const Vector3r boundaryX[],
const Real boundaryPsi[],
const unsigned int numNeighbors,
const unsigned int neighbors[],
const Real density0,
const bool boundaryHandling,
const Real lambda[],
Vector3r &corr)
{
// Compute position correction
corr.setZero();
for (unsigned int j = 0; j < numNeighbors; j++)
{
const unsigned int neighborIndex = neighbors[j];
if (neighborIndex < numberOfParticles) // Test if fluid particle
{
const Vector3r gradC_j = -mass[neighborIndex] / density0 * CubicKernel::gradW(x[particleIndex] - x[neighborIndex]);
corr -= (lambda[particleIndex] + lambda[neighborIndex]) * gradC_j;
}
else if (boundaryHandling)
{
// Boundary: Akinci2012
const Vector3r gradC_j = -boundaryPsi[neighborIndex - numberOfParticles] / density0 * CubicKernel::gradW(x[particleIndex] - boundaryX[neighborIndex - numberOfParticles]);
corr -= (lambda[particleIndex]) * gradC_j;
}
}
return true;
}
| [
"[email protected]"
] | |
99d0e0eda964197d579f4e447d4e9dbd8980dbdc | 07330519051b7d2d011dffed64a24c1abc342b6f | /lecture-15/src/array10b.cpp | 32023f655459673d8feb0c6df2fd6e7a958e7c0b | [] | no_license | CME211/notes | 42d0a793baa09922a49d03a413e797d9a61178a9 | 7d718adcf5555563a6e122f4c9487af2cfe6f07d | refs/heads/master | 2022-12-09T06:26:10.163812 | 2022-12-07T10:17:20 | 2022-12-07T10:17:20 | 66,503,685 | 260 | 193 | null | 2022-09-27T22:47:53 | 2016-08-24T22:14:44 | Jupyter Notebook | UTF-8 | C++ | false | false | 488 | cpp | #include <iostream>
#include <boost/multi_array.hpp>
int main() {
boost::multi_array<double, 2> a(boost::extents[3][3],
boost::fortran_storage_order());
double n = 0.;
for (unsigned int i = 0; i < 3; i++) {
for (unsigned int j = 0; j < 3; j++) {
a[i][j] = n;
n++;
}
}
auto b = a.data();
for (unsigned int n = 0; n < a.num_elements(); n++) {
std::cout << "b[" << n << "] = " << b[n] << std::endl;
}
return 0;
}
| [
"[email protected]"
] | |
e9be71d1d557633479b91b272d89ec39c8c6e518 | 66132ff2da5a05df042026b95a8042f582b11b55 | /libplasma2d/engine/bitmap_font.h | eb93ce0ade2c4be6c115c09c51a7754310d90967 | [] | no_license | robmerrell/plasma2d | c9816c4ec55d16dd88ad3fb42b0cf521006c5fb6 | a27a1f6b721f8f2184572b2b1c67ed1f9f13ca9a | refs/heads/master | 2016-09-05T10:38:59.501995 | 2012-08-29T05:04:30 | 2012-08-29T05:04:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,863 | h | /**
* Licensed under the MIT license. See LICENSE for details.
* Copyright (C) 2011 Rob Merrell
*/
#ifndef P2D_BITMAP_FONT_H
#define P2D_BITMAP_FONT_H
#include <string>
#include "../external/tinyxml/tinyxml.h"
#include "../external/glm/glm.hpp"
#include "../external/glm/gtc/matrix_transform.hpp"
#include "../external/glm/gtc/type_ptr.hpp"
#include "texture.h"
namespace p2d {
struct font_char {
int id;
float x;
float y;
float width;
float height;
float xoffset;
float yoffset;
float xadvance;
char letter; // only doing 1 byte per character right now
};
class BitmapFont {
private:
std::string font_name;
std::string full_font_path;
// font info
int scale_width;
int scale_height;
int font_size;
// TODO: fix the parser so that it doesn't crash on more than 256 characters
font_char char_collection[256]; // settle on 256 for now
Texture* texture;
public:
BitmapFont() {};
BitmapFont(std::string _text, Texture* _texture, float _x, float _y);
void loadFont(std::string _font_name, std::string _full_font_path);
void setFontTexture(Texture*);
Texture* getFontTexture();
void parse();
int getFontSize();
/**
* Get verticies and texture map info for specific characters
*/
glm::mat4x3 generateVertsForLetter(char _char);
glm::mat4 generateTexCoordsForLetter(char _char);
/**
* Get char specific info
*/
float getXAdvanceForLetter(char _char);
float getXOffsetForLetter(char _char);
float getYOffsetForLetter(char _char);
};
}
#endif | [
"[email protected]"
] | |
13e0903e3ce89a53c758673fec299fdfa5aaf50e | e4c432f43fb1711d7307a25d5bc07f64e26ae9de | /rdkafkacpp/example/TestPingConsumer.cpp | 74c6c89de66006cac8da327893b592e8bb157e0d | [] | no_license | longshadian/zylib | c456dc75470f9c6512a7d63b1182cb9eebcca999 | 9fde01c76a1c644d5daa46a645c8e1300e72c5bf | refs/heads/master | 2021-01-22T23:49:11.912633 | 2020-06-16T09:13:50 | 2020-06-16T09:13:50 | 85,669,581 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,563 | cpp | #include <iostream>
#include <string>
#include <cstdlib>
#include <cstdio>
#include <csignal>
#include <cstring>
#include <thread>
#include <chrono>
#include <ctime>
#include <algorithm>
#include <numeric>
#include <librdkafka/rdkafkacpp.h>
#include "Utility.h"
namespace test_ping_consumer
{
static bool consumer_run = true;
static bool producer_run = true;
static void sigterm(int sig) {
consumer_run = false;
}
::RdKafka::Producer* producer;
::RdKafka::Topic* topic;
void startProducer(std::thread* tout)
{
std::string brokers = "127.0.0.1:9092";
std::string errstr;
::RdKafka::Conf *conf = ::RdKafka::Conf::create(::RdKafka::Conf::CONF_GLOBAL);
conf->set("group.id", "xxx", errstr);
conf->set("metadata.broker.list", brokers, errstr);
utility::DeliveryReportCb* ex_dr_cb = new utility::DeliveryReportCb();
conf->set("dr_cb", ex_dr_cb, errstr);
::RdKafka::Conf *tconf = ::RdKafka::Conf::create(::RdKafka::Conf::CONF_TOPIC);
tconf->set("request.required.acks", "all", errstr);
std::vector<std::string> topics = { "tp.test2" };
producer = ::RdKafka::Producer::create(conf, errstr);
if (!producer) {
std::cerr << "Failed to create producer: " << errstr << std::endl;
exit(1);
}
topic = ::RdKafka::Topic::create(producer, topics[0], tconf, errstr);
if (!topic) {
std::cerr << ": Failed to create topic: " << errstr << std::endl;
exit(1);
}
std::cout << "start producer \n";
std::thread t([conf, tconf, ex_dr_cb]
{
while (producer_run) {
producer->poll(1);
}
delete topic;
delete producer;
delete conf;
delete tconf;
delete ex_dr_cb;
}
);
*tout = std::move(t);
}
int TestPingConsumer()
{
signal(SIGINT, sigterm);
signal(SIGTERM, sigterm);
std::thread p_thread{};
startProducer(&p_thread);
std::this_thread::sleep_for(std::chrono::seconds{ 1 });
std::string brokers = "127.0.0.1:9092";
std::string errstr;
RdKafka::Conf* conf = RdKafka::Conf::create(RdKafka::Conf::CONF_GLOBAL);
conf->set("group.id", "xxx", errstr);
conf->set("metadata.broker.list", brokers, errstr);
utility::RebalanceCb ex_rebalance_cb{};
conf->set("rebalance_cb", &ex_rebalance_cb, errstr);
utility::ConsumeCb ex_consume_cb{};
conf->set("consume_cb", &ex_consume_cb, errstr);
RdKafka::KafkaConsumer *consumer = RdKafka::KafkaConsumer::create(conf, errstr);
if (!consumer) {
std::cerr << "Failed to create consumer: " << errstr << std::endl;
exit(1);
}
delete conf;
auto* p = RdKafka::TopicPartition::create("tp.test1", 0);
consumer->assign({ p });
delete p;
while (consumer_run) {
RdKafka::Message* msg = consumer->consume(1);
auto str = utility::getMsgStr(*msg);
auto offset = msg->offset();
(void)offset;
delete msg;
if (!str.empty()) {
::RdKafka::ErrorCode resp = producer->produce(topic, 0, ::RdKafka::Producer::RK_MSG_COPY
, const_cast<char*>(str.c_str()), str.size()
, nullptr, nullptr);
if (resp) {
std::cout << "error send: " << ::RdKafka::err2str(resp) << "\n";
}
//if (!str.empty())
// std::cout << "recevie " << str << " " << offset << "\n";
}
}
consumer->close();
delete consumer;
producer_run = false;
p_thread.join();
::RdKafka::wait_destroyed(5000);
return 0;
}
}
| [
"[email protected]"
] | |
9d94e24c790d83c3f0868c369cc5d91d200d5e42 | 599086b068cf053dcfcccc030655e584d10e09d1 | /main/GgParam.h | 4074867994d42cd4a793765efa6636bee04616a7 | [] | no_license | dbgarlisch/ParamSetMerger | 92447fc0d8cd944198ee979084d99bdfa52c8517 | 2402b1f4baf84b6fef6a7ec49d039cb2557715c0 | refs/heads/master | 2020-03-29T15:15:10.758444 | 2018-09-24T05:10:35 | 2018-09-24T05:10:35 | 150,052,538 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,278 | h | #ifndef GGPARAM_H
#define GGPARAM_H
#include <iostream>
#include <string>
#include <vector>
#include "utils.h"
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
class GgParam {
public:
GgParam(const std::string &name = "", const std::string &val = "") :
name_(utils::trim(name)),
val_(val)
{
}
~GgParam()
{
}
void setName(const std::string &name) {
name_ = name; }
const std::string& getName() const {
return name_; }
void setValue(const std::string &val) {
val_ = val; }
const std::string& getValue() const {
return val_; }
protected:
friend std::ostream& operator<<(std::ostream& os, const GgParam &p);
private:
std::string name_;
std::string val_;
};
using GgParamArray1 = std::vector<GgParam>;
std::ostream& operator<<(std::ostream& os, const GgParam &p)
{
return os << "{name:\"" << p.name_ << "\", value:\"" << p.val_ << "\"}";
}
#endif // GGPARAM_H
| [
"[email protected]"
] | |
b93575dfba8175dec6d55883dcb96e72a01867a2 | a06542eb6d6d773c69d35586138d1fd4c8e04206 | /0519.cpp | 446cf567dd6746119c9ab8a372788a3ad88b8729 | [] | no_license | zakuro9715/aoj | 7dc69545d37fb73be154a38d1aa431fe8ef2a1f7 | d2d18f43482d98c99187a635fdae1eaeed830bb8 | refs/heads/master | 2021-03-12T20:09:13.546850 | 2015-09-22T14:38:58 | 2015-09-22T14:38:58 | 31,834,597 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 692 | cpp | #include<iostream>
#include<vector>
using namespace std;
bool done[5000];
vector<int> wins[5000], sorted;
void dfs(int n)
{
done[n] = true;
for(auto m : wins[n])
if(!done[m])
dfs(m);
sorted.push_back(n);
}
int N, M;
int main()
{
cin >> N >> M;
for(int i = 0; i < M; i++)
{
int a, b;
cin >> a >> b;
wins[--a].push_back(--b);
}
for(int i = 0; i < N; i++)
if(!done[i])
dfs(i);
bool plural = false;
for(int i = N - 1; i >= 0; i--)
{
auto m = sorted[i];
cout << m + 1 << endl;
if(i == 0)
break;
bool b = true;
for(auto n : wins[m])
b &= n != sorted[i - 1];
plural |= b;
}
cout << plural << endl;
}
| [
"[email protected]"
] | |
1e0ba5efe08c85ace4d1b01bf439ccb9df740219 | 1de313650993e7f9a8e2a56c951dfdd11d04082c | /src/GenerateOptions.hpp | 2921c6d39a71972fd10fadb06e8e085bc014a809 | [] | no_license | rars/satpi | eb92b82dabc06d6b5e97596d491c13fe2845019c | c1f8b445e8fb60417ef06b77edd4d319686a6ca3 | refs/heads/master | 2021-05-04T04:44:14.792732 | 2018-11-11T18:42:57 | 2018-11-11T18:42:57 | 70,991,424 | 0 | 0 | null | 2018-11-11T18:42:57 | 2016-10-15T14:07:47 | C++ | UTF-8 | C++ | false | false | 690 | hpp | /* GenerateOptions.hpp : Defines the options for the 'generate' command.
*
* Copyright (c) 2016 Richard Russell <https://rars.github.io/>
*
*/
#pragma once
#ifndef SATPI_GENERATEOPTIONS_HPP
#define SATPI_GENERATEOPTIONS_HPP
#include <cstdint>
#include <memory>
#include <string>
namespace satpi
{
class ProgramArguments;
struct GenerateOptions
{
public:
GenerateOptions(const std::shared_ptr<ProgramArguments>& programArguments);
const std::uint32_t NumVariables;
const std::uint32_t LiteralsPerClause;
const double ClausesPerVariableRatio;
const std::string OutputFilepath;
};
}
#endif /* SATPI_GENERATEOPTIONS_HPP */
| [
"[email protected]"
] | |
f39ec2a804e28ca3edc70c8e8dacf6b9385e55fd | ba474f314164a0a4430ebba00619b30740d5494e | /Binary Search/Leet744_FindSmallestGreaterThanTarget.cpp | ea85ef38d33081cb006b2e4529378931479053e2 | [] | no_license | nishant334567/ProblemSolving | 5cbd38e3abd2e6d11989b715dc0f090fdbdb3d55 | 796fe5fed6307b228eb705910f98fbc24251da64 | refs/heads/master | 2023-08-22T16:07:02.613103 | 2021-10-17T03:16:41 | 2021-10-17T03:16:41 | 399,654,779 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 672 | cpp | /* 744. Find Smallest Letter Greater Than Target */
/* Given the array is sorted in increasing order */
/* Any sorted sequence gives a feel to apply binary search */
class Solution {
public:
char nextGreatestLetter(vector<char>& letters, char target) {
int n = letters.size();
int t =target;
if(t>=letters[n-1])
return letters[0];
char res;
int l=0,r=n-1;
while(l<=r)
{
int mid = (l+r)/2;
if(letters[mid]<=target)
l = mid+1;
else{
res = letters[mid];
r = mid-1;
}
}
return res;
}
}; | [
"[email protected]"
] | |
1b241b959508ff3ad2db75ec847f3756d532bff9 | c7f9d4413c3b3a5afe52d0332c75e0f5e403510c | /app_update/stdafx.cpp | 2228ffeacec1007fb1ff0c097e9219a9a62df829 | [] | no_license | Echo-M/producingManagementAK47 | 4d9a86ac292f7371cde1ab02f9067b7cd539c107 | dcb7137816387a6f72b012a8fc6c2c660a7fa86e | refs/heads/master | 2021-01-20T17:46:29.023475 | 2016-07-28T05:20:58 | 2016-07-28T05:20:58 | 64,272,213 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 165 | cpp |
// stdafx.cpp : 只包括标准包含文件的源文件
// app_update.pch 将作为预编译头
// stdafx.obj 将包含预编译类型信息
#include "stdafx.h"
| [
"[email protected]"
] | |
e997b4fc8d8f5a13551915ec6e3aec6c1366245f | f2b2ee9f32d033211f63a6bc6b84202bad175b44 | /DlgAddRail/DlgAddRail/main.cpp | f87750754ee223d335b8155fd4a1008ffa483601 | [] | no_license | whjbinghun/learning | d10053e80983d72bcf7a8b734fb3d3311adc33b2 | 798367bb4f2a116317b49e726f8f2f0deb30c704 | refs/heads/master | 2021-01-18T23:31:11.933176 | 2016-12-30T05:21:11 | 2016-12-30T05:21:11 | 18,207,394 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 172 | cpp | #include "dlgaddrail.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
DlgAddRail w;
w.show();
return a.exec();
}
| [
"[email protected]"
] | |
20086db6323f5076ac8691527831d5cd114648f5 | 748eb6e5e6dbf8011c3c6e8e6a7b187927043c4d | /Wireframes Calc/TenCompound.cpp | c5ecb0db34d66000a28255cf6d51919b9635c6f3 | [] | no_license | apfitzen/Wireframes-Calc | cea6f7b2de5dbebc4fef260d483cc27abca5f8d3 | 624f7b1ba092e7af4bd284e6e7a9c025807fdc34 | refs/heads/master | 2021-01-20T18:33:42.643349 | 2016-07-01T05:08:37 | 2016-07-01T05:08:37 | 62,273,808 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 955 | cpp | //
// TenCompound.cpp
// Wireframes Calc 4
//
// Created by Aaron Pfitzenmaier on 1/4/15.
// Copyright (c) 2015 Aaron Pfitzenmaier. All rights reserved.
//
#include "TenCompound.h"
#include "Polyhedron.h"
TenCompound::TenCompound(const Polyhedron& polyhedron):Compound(polyhedron,10)
{
double twentyOne=20.905157447;
double sixtyNine=69.094842554;
double seven=7.761243904;
double fiftyTwo=52.238756096;
double thrityFive=35.264389689;
poly.at(0)->setRotation(0,0,-twentyOne);
poly.at(1)->setRotation(60,0,twentyOne);
poly.at(2)->setRotation(30,sixtyNine,0);
poly.at(3)->setRotation(90,-sixtyNine,0);
poly.at(4)->setRotation(90,twentyOne,90);
poly.at(5)->setRotation(30,-twentyOne,90);
poly.at(6)->setRotation(seven,thrityFive,45);
poly.at(7)->setRotation(fiftyTwo,thrityFive,-45);
poly.at(8)->setRotation(-seven,-thrityFive,45);
poly.at(9)->setRotation(-fiftyTwo,-thrityFive,-45);
}
| [
"[email protected]"
] | |
9ff6666ac2df74af46d642a5f4103eb243e9e48b | 8d03e03ed453b4ed2900d862703ee02cb8b5250d | /173-Binary-Search-Tree-Iterator/solution.cpp | 6d26b9b8b6d3782fe9679da170c5d7267f68df1b | [] | no_license | boy2000-007man/LeetCode | 37f92d6250e0501c5c8352bbd1cd8b61e315a3e7 | dbbfe4c8ff040bfc74ace21f4c31d9866338e670 | refs/heads/master | 2021-01-09T20:54:03.810660 | 2016-09-19T06:10:37 | 2016-09-19T06:10:37 | 56,504,013 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 946 | cpp | /**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
stack<pair<TreeNode *, bool>> stk;
public:
BSTIterator(TreeNode *root) {
if (root)
stk.push({root, false});
}
/** @return whether we have a next smallest number */
bool hasNext() {
return !stk.empty();
}
/** @return the next smallest number */
int next() {
while (!stk.top().second++)
if (stk.top().first->left)
stk.push({stk.top().first->left, false});
TreeNode *r = stk.top().first;
stk.pop();
if (r->right)
stk.push({r->right, false});
return r->val;
}
};
/**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/ | [
"[email protected]"
] | |
c9c43945e67a4433b7c485694d086237f637ed78 | 641e312cc315b4f62f53dcdb349d8a22fc4de1e7 | /TowerOfHanoi.cpp | 695e85ff5e7b3477294dba00cfd43f7ca6f6f677 | [] | no_license | manishsundriyal/Algorithms-DataStructures | c47824c86c62727ccec8179e6335e0aa96643124 | b20a180c5349281758a205c9abf1c4d3d90143b9 | refs/heads/master | 2021-01-01T17:53:56.260704 | 2019-04-25T17:57:03 | 2019-04-25T17:57:03 | 98,191,603 | 4 | 2 | null | 2019-10-01T16:03:10 | 2017-07-24T13:06:38 | C++ | UTF-8 | C++ | false | false | 481 | cpp | #include <iostream>
using namespace std;
void TowerOfHanoi(int No_of_dics,char source,char dest,char help){
if(No_of_dics==0) return;
TowerOfHanoi(No_of_dics-1,source,help,dest);
cout<<"Move disc from "<<source<<" to "<<dest<<endl;
TowerOfHanoi(No_of_dics-1,help,dest,source);
}
int main(){
int No_of_dics;
cin>>No_of_dics;
char source='S';
//source stack+
char dest='D';
//destinataion
char help='H';
//helper
TowerOfHanoi(No_of_dics,source,dest,help);
return 0;
} | [
"[email protected]"
] | |
4c4b14a823cd8698b3239b830826e4d3f975e31f | 8663866dca43b34ecdc1fc666b1c6d6fb2774b35 | /EDCervezas/ventanaeliminarcerveza.cpp | 4fa7e96d888a4f79cc6a5c392aeeb19a7e66e7d2 | [] | no_license | anthonylle/EDProgra2 | 90932dd40d0a5dbf5d0926790fd52ac86dfc5120 | 9a2b84a24e1a8e4aa0fd727f964720821bd1fb7b | refs/heads/master | 2021-05-31T22:54:40.109307 | 2016-06-09T03:28:54 | 2016-06-09T03:28:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,179 | cpp | #include "ventanaeliminarcerveza.h"
#include "ui_ventanaeliminarcerveza.h"
#include "grafo.h"
#include <QMessageBox>
VentanaEliminarCerveza::VentanaEliminarCerveza(Grafo * grafo,QWidget *parent) :
QDialog(parent),
ui(new Ui::VentanaEliminarCerveza)
{
ui->setupUi(this);
grafoPuntero = grafo;
ui->comboEstilos->clear();
for(int i = 0; i < grafo->obtenerEstilos().size(); i++){
ui->comboEstilos->addItem(grafo->obtenerEstilos()[i]->getNombre());
}
ui->comboCervezas->clear();
for(int i = 0; i < grafo->obtenerCervezasDeEstilo(ui->comboEstilos->currentText()).size(); i++){
ui->comboCervezas->addItem(grafo->obtenerCervezasDeEstilo(ui->comboEstilos->currentText())[i]->getNombre());
}
}
VentanaEliminarCerveza::~VentanaEliminarCerveza()
{
delete ui;
}
void VentanaEliminarCerveza::on_btnEliminar_clicked()
{
//FUNCION DEL GRAFO
grafoPuntero->eliminarVecino(ui->comboEstilos->currentText(),ui->comboCervezas->currentText());
QMessageBox *mensaje = new QMessageBox(this);
QString success = "Estilo: "+ui->comboEstilos->currentText()+ " <- desenlazado de -> Cerveza: "+ui->comboCervezas->currentText();
mensaje->setText(success);
mensaje->exec();
ui->comboCervezas->clear();
for(int i = 0; i < grafoPuntero->obtenerCervezasDeEstilo(ui->comboEstilos->currentText()).size(); i++){
ui->comboCervezas->addItem(grafoPuntero->obtenerCervezasDeEstilo(ui->comboEstilos->currentText())[i]->getNombre());
}
if(ui->comboCervezas->currentText() == ""){
ui->btnEliminar->setEnabled(false);
}
else{
ui->btnEliminar->setEnabled(true);
}
}
void VentanaEliminarCerveza::on_comboEstilos_currentIndexChanged(int index)
{
ui->comboCervezas->clear();
for(int i = 0; i < grafoPuntero->obtenerCervezasDeEstilo(ui->comboEstilos->currentText()).size(); i++){
ui->comboCervezas->addItem(grafoPuntero->obtenerCervezasDeEstilo(ui->comboEstilos->currentText())[i]->getNombre());
}
if(ui->comboCervezas->currentText() == ""){
ui->btnEliminar->setEnabled(false);
}
else{
ui->btnEliminar->setEnabled(true);
}
}
| [
"[email protected]"
] | |
7e38a7a49ca964cd9c75c6b7f1566d19b270f31a | 0af33c10d3c6cb817f5067743f06c71ad99bca0b | /done/rgpc17p4.cpp | 559f22d6e0c7c650522570ebb52c3cbb9f2a8e7d | [] | no_license | nathanlo99/dmoj_archive | 6d4f84b58d963109c73a52281a4aa06dd79bc1da | b137f8fa5894542a39e168c1f6485d622a119f42 | refs/heads/master | 2020-04-15T12:47:18.181614 | 2019-07-21T03:03:21 | 2019-07-21T03:03:21 | 62,849,549 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,325 | cpp | #include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
#include <tuple>
int n, m, a, b, d, dest, vis[1005], dist[1005], num[1005], in[1005], out[1005];
std::vector<std::pair<int, int> > adj[1005];
std::queue<int> q;
int main() {
scanf("%d %d", &n, &m);
for (int i = 0; i < m; i++) {
scanf("%d %d %d", &a, &b, &d);
a--; b--;
adj[a].push_back(std::make_pair(b, d));
out[a]++; in[b]++;
}
for (int i = 0; i < n; i++) {
if (in[i] == 0) {
q.push(i);
num[i] = 1;
}
}
for (int i = 0; i < n; i++) {
if (q.empty()) {
printf("-1\n");
return 0;
}
const int node = q.front(); q.pop();
for (std::pair<int, int> p : adj[node]) {
std::tie(dest, d) = p;
in[dest]--;
if (in[dest] == 0) q.push(dest);
if (dist[node] + d > dist[dest]) {
dist[dest] = dist[node] + d;
num[dest] = num[node] + 1;
} else if (dist[node] + d == dist[dest]) {
if (num[node] + 1 > num[dest])
num[dest] = num[node] + 1;
}
}
out[node] = 0;
}
printf("%d %d\n", dist[n - 1], num[n - 1]);
} | [
"[email protected]"
] | |
bae61b54e392eed5e859fe80a452e028ae0d7771 | 08b71476193080e05a4de24fe73be1c002d04e2b | /jongmanbook/fortress-1.cpp | e0d7b99ef0513af2d5aedad9de3da756a836360e | [] | no_license | sency90/allCode | 7321fae92f0a733742ea6831c43ce35898b1d915 | 1e3ad5f6ba929631641d7889c57a398d89be9419 | refs/heads/master | 2022-10-23T00:32:09.833362 | 2022-09-27T16:33:31 | 2022-09-27T16:33:31 | 43,256,814 | 6 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 945 | cpp | #include <stdio.h>
#include <algorithm>
using namespace std;
int c,n,ans;
struct st {
int x, y, r;
bool operator <(const st& a) const{
return r < a.r;
}
}fortress[100];
int buf[100];
int main() {
scanf("%d", &c);
while (c--) {
ans = 0;
scanf("%d", &n);
for (int i = 0; i < n; i++)
scanf("%d %d %d", &fortress[i].x, &fortress[i].y, &fortress[i].r);
sort(fortress, fortress + n);
for (int i = 0; i < n-1; i++)
for (int j = i + 1; j < n; j++) {
int dx = (fortress[i].x - fortress[j].x);
int dy = (fortress[i].y - fortress[j].y);
if (dx*dx + dy*dy < fortress[j].r*fortress[j].r) {
printf("buf[%d]:%d, buf[%d]:%d\n",i,buf[i],j,buf[j]);
ans = max(ans, buf[j] + buf[i]+1);
printf("ans:%d, buf[%d]+buf[%d]+1: %d\n",ans, j,i,buf[j]+buf[i]+1);
buf[j] = max(buf[j], buf[i] + 1);
break;
}
}
printf("%d\n", ans);
for (int i = 0; i < n; i++)buf[i] = 0;
}
}
| [
"[email protected]"
] | |
72c2a493e353c3d59cd05bb3b782a2fd3a416792 | 6a69d57c782e0b1b993e876ad4ca2927a5f2e863 | /vendor/samsung/common/packages/apps/SBrowser/src/chrome/browser/sync/glue/bookmark_data_type_controller_unittest.cc | 7898980260f51786cf200016a954ae9f9b6909f5 | [
"BSD-3-Clause"
] | permissive | duki994/G900H-Platform-XXU1BOA7 | c8411ef51f5f01defa96b3381f15ea741aa5bce2 | 4f9307e6ef21893c9a791c96a500dfad36e3b202 | refs/heads/master | 2020-05-16T20:57:07.585212 | 2015-05-11T11:03:16 | 2015-05-11T11:03:16 | 35,418,464 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 12,741 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sync/glue/bookmark_data_type_controller.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/callback.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/bookmarks/bookmark_model_factory.h"
#include "chrome/browser/bookmarks/bookmark_test_helpers.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/history/history_service.h"
#include "chrome/browser/history/history_service_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sync/glue/change_processor_mock.h"
#include "chrome/browser/sync/profile_sync_components_factory_mock.h"
#include "chrome/browser/sync/profile_sync_service_mock.h"
#include "chrome/test/base/profile_mock.h"
#include "components/browser_context_keyed_service/refcounted_browser_context_keyed_service.h"
#include "components/sync_driver/data_type_controller_mock.h"
#include "components/sync_driver/model_associator_mock.h"
#include "content/public/browser/notification_service.h"
#include "content/public/test/test_browser_thread.h"
#include "sync/api/sync_error.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using browser_sync::BookmarkDataTypeController;
using browser_sync::ChangeProcessorMock;
using browser_sync::DataTypeController;
using browser_sync::ModelAssociatorMock;
using browser_sync::ModelLoadCallbackMock;
using browser_sync::StartCallbackMock;
using content::BrowserThread;
using testing::_;
using testing::DoAll;
using testing::InvokeWithoutArgs;
using testing::Return;
using testing::SetArgumentPointee;
namespace {
class HistoryMock : public HistoryService {
public:
explicit HistoryMock(Profile* profile) : HistoryService(profile) {}
MOCK_METHOD0(BackendLoaded, bool(void));
protected:
virtual ~HistoryMock() {}
};
BrowserContextKeyedService* BuildBookmarkModel(
content::BrowserContext* context) {
Profile* profile = static_cast<Profile*>(context);
BookmarkModel* bookmark_model = new BookmarkModel(profile);
bookmark_model->Load(profile->GetIOTaskRunner());
return bookmark_model;
}
BrowserContextKeyedService* BuildBookmarkModelWithoutLoading(
content::BrowserContext* profile) {
return new BookmarkModel(static_cast<Profile*>(profile));
}
BrowserContextKeyedService* BuildHistoryService(
content::BrowserContext* profile) {
return new HistoryMock(static_cast<Profile*>(profile));
}
} // namespace
class SyncBookmarkDataTypeControllerTest : public testing::Test {
public:
SyncBookmarkDataTypeControllerTest()
: ui_thread_(BrowserThread::UI, &message_loop_),
service_(&profile_) {}
virtual void SetUp() {
model_associator_ = new ModelAssociatorMock();
change_processor_ = new ChangeProcessorMock();
history_service_ = static_cast<HistoryMock*>(
HistoryServiceFactory::GetInstance()->SetTestingFactoryAndUse(
&profile_, BuildHistoryService));
profile_sync_factory_.reset(
new ProfileSyncComponentsFactoryMock(model_associator_,
change_processor_));
bookmark_dtc_ = new BookmarkDataTypeController(profile_sync_factory_.get(),
&profile_,
&service_);
}
protected:
enum BookmarkLoadPolicy {
DONT_LOAD_MODEL,
LOAD_MODEL,
};
void CreateBookmarkModel(BookmarkLoadPolicy bookmark_load_policy) {
if (bookmark_load_policy == LOAD_MODEL) {
bookmark_model_ = static_cast<BookmarkModel*>(
BookmarkModelFactory::GetInstance()->SetTestingFactoryAndUse(
&profile_, BuildBookmarkModel));
test::WaitForBookmarkModelToLoad(bookmark_model_);
} else {
bookmark_model_ = static_cast<BookmarkModel*>(
BookmarkModelFactory::GetInstance()->SetTestingFactoryAndUse(
&profile_, BuildBookmarkModelWithoutLoading));
}
}
void SetStartExpectations() {
EXPECT_CALL(*history_service_,
BackendLoaded()).WillRepeatedly(Return(true));
EXPECT_CALL(model_load_callback_, Run(_, _));
}
void SetAssociateExpectations() {
EXPECT_CALL(*model_associator_, CryptoReadyIfNecessary()).
WillRepeatedly(Return(true));
EXPECT_CALL(*profile_sync_factory_, CreateBookmarkSyncComponents(_, _));
EXPECT_CALL(*model_associator_, SyncModelHasUserCreatedNodes(_)).
WillRepeatedly(DoAll(SetArgumentPointee<0>(true), Return(true)));
EXPECT_CALL(*model_associator_, AssociateModels(_, _)).
WillRepeatedly(Return(syncer::SyncError()));
EXPECT_CALL(service_, ActivateDataType(_, _, _));
}
void SetStopExpectations() {
EXPECT_CALL(service_, DeactivateDataType(_));
EXPECT_CALL(*model_associator_, DisassociateModels()).
WillOnce(Return(syncer::SyncError()));
}
void Start() {
bookmark_dtc_->LoadModels(
base::Bind(&ModelLoadCallbackMock::Run,
base::Unretained(&model_load_callback_)));
bookmark_dtc_->StartAssociating(
base::Bind(&StartCallbackMock::Run,
base::Unretained(&start_callback_)));
}
base::MessageLoopForUI message_loop_;
content::TestBrowserThread ui_thread_;
scoped_refptr<BookmarkDataTypeController> bookmark_dtc_;
scoped_ptr<ProfileSyncComponentsFactoryMock> profile_sync_factory_;
ProfileMock profile_;
BookmarkModel* bookmark_model_;
HistoryMock* history_service_;
ProfileSyncServiceMock service_;
ModelAssociatorMock* model_associator_;
ChangeProcessorMock* change_processor_;
StartCallbackMock start_callback_;
ModelLoadCallbackMock model_load_callback_;
};
TEST_F(SyncBookmarkDataTypeControllerTest, StartDependentsReady) {
CreateBookmarkModel(LOAD_MODEL);
SetStartExpectations();
SetAssociateExpectations();
EXPECT_EQ(DataTypeController::NOT_RUNNING, bookmark_dtc_->state());
EXPECT_CALL(start_callback_, Run(DataTypeController::OK, _, _));
Start();
EXPECT_EQ(DataTypeController::RUNNING, bookmark_dtc_->state());
}
TEST_F(SyncBookmarkDataTypeControllerTest, StartBookmarkModelNotReady) {
CreateBookmarkModel(DONT_LOAD_MODEL);
SetStartExpectations();
SetAssociateExpectations();
EXPECT_CALL(start_callback_, Run(DataTypeController::OK, _, _));
bookmark_dtc_->LoadModels(
base::Bind(&ModelLoadCallbackMock::Run,
base::Unretained(&model_load_callback_)));
EXPECT_EQ(DataTypeController::MODEL_STARTING, bookmark_dtc_->state());
bookmark_model_->Load(profile_.GetIOTaskRunner());
test::WaitForBookmarkModelToLoad(bookmark_model_);
EXPECT_EQ(DataTypeController::MODEL_LOADED, bookmark_dtc_->state());
bookmark_dtc_->StartAssociating(
base::Bind(&StartCallbackMock::Run,
base::Unretained(&start_callback_)));
EXPECT_EQ(DataTypeController::RUNNING, bookmark_dtc_->state());
}
TEST_F(SyncBookmarkDataTypeControllerTest, StartHistoryServiceNotReady) {
CreateBookmarkModel(LOAD_MODEL);
SetStartExpectations();
EXPECT_CALL(*history_service_,
BackendLoaded()).WillRepeatedly(Return(false));
bookmark_dtc_->LoadModels(
base::Bind(&ModelLoadCallbackMock::Run,
base::Unretained(&model_load_callback_)));
EXPECT_EQ(DataTypeController::MODEL_STARTING, bookmark_dtc_->state());
testing::Mock::VerifyAndClearExpectations(history_service_);
EXPECT_CALL(*history_service_, BackendLoaded()).WillRepeatedly(Return(true));
// Send the notification that the history service has finished loading the db.
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_HISTORY_LOADED,
content::Source<Profile>(&profile_),
content::NotificationService::NoDetails());
EXPECT_EQ(DataTypeController::MODEL_LOADED, bookmark_dtc_->state());
}
TEST_F(SyncBookmarkDataTypeControllerTest, StartFirstRun) {
CreateBookmarkModel(LOAD_MODEL);
SetStartExpectations();
SetAssociateExpectations();
EXPECT_CALL(*model_associator_, SyncModelHasUserCreatedNodes(_)).
WillRepeatedly(DoAll(SetArgumentPointee<0>(false), Return(true)));
EXPECT_CALL(start_callback_, Run(DataTypeController::OK_FIRST_RUN, _, _));
Start();
}
TEST_F(SyncBookmarkDataTypeControllerTest, StartBusy) {
CreateBookmarkModel(LOAD_MODEL);
EXPECT_CALL(*history_service_, BackendLoaded()).WillRepeatedly(Return(false));
EXPECT_CALL(model_load_callback_, Run(_, _));
bookmark_dtc_->LoadModels(
base::Bind(&ModelLoadCallbackMock::Run,
base::Unretained(&model_load_callback_)));
bookmark_dtc_->LoadModels(
base::Bind(&ModelLoadCallbackMock::Run,
base::Unretained(&model_load_callback_)));
}
TEST_F(SyncBookmarkDataTypeControllerTest, StartOk) {
CreateBookmarkModel(LOAD_MODEL);
SetStartExpectations();
SetAssociateExpectations();
EXPECT_CALL(*model_associator_, SyncModelHasUserCreatedNodes(_)).
WillRepeatedly(DoAll(SetArgumentPointee<0>(true), Return(true)));
EXPECT_CALL(start_callback_, Run(DataTypeController::OK, _, _));
Start();
}
TEST_F(SyncBookmarkDataTypeControllerTest, StartAssociationFailed) {
CreateBookmarkModel(LOAD_MODEL);
SetStartExpectations();
// Set up association to fail.
EXPECT_CALL(*profile_sync_factory_, CreateBookmarkSyncComponents(_, _));
EXPECT_CALL(*model_associator_, CryptoReadyIfNecessary()).
WillRepeatedly(Return(true));
EXPECT_CALL(*model_associator_, SyncModelHasUserCreatedNodes(_)).
WillRepeatedly(DoAll(SetArgumentPointee<0>(true), Return(true)));
EXPECT_CALL(*model_associator_, AssociateModels(_, _)).
WillRepeatedly(Return(syncer::SyncError(FROM_HERE,
syncer::SyncError::DATATYPE_ERROR,
"error",
syncer::BOOKMARKS)));
EXPECT_CALL(start_callback_,
Run(DataTypeController::ASSOCIATION_FAILED, _, _));
Start();
EXPECT_EQ(DataTypeController::DISABLED, bookmark_dtc_->state());
}
TEST_F(SyncBookmarkDataTypeControllerTest,
StartAssociationTriggersUnrecoverableError) {
CreateBookmarkModel(LOAD_MODEL);
SetStartExpectations();
// Set up association to fail with an unrecoverable error.
EXPECT_CALL(*profile_sync_factory_, CreateBookmarkSyncComponents(_, _));
EXPECT_CALL(*model_associator_, CryptoReadyIfNecessary()).
WillRepeatedly(Return(true));
EXPECT_CALL(*model_associator_, SyncModelHasUserCreatedNodes(_)).
WillRepeatedly(DoAll(SetArgumentPointee<0>(false), Return(false)));
EXPECT_CALL(start_callback_,
Run(DataTypeController::UNRECOVERABLE_ERROR, _, _));
Start();
EXPECT_EQ(DataTypeController::NOT_RUNNING, bookmark_dtc_->state());
}
TEST_F(SyncBookmarkDataTypeControllerTest, StartAborted) {
CreateBookmarkModel(LOAD_MODEL);
EXPECT_CALL(*history_service_, BackendLoaded()).WillRepeatedly(Return(false));
EXPECT_CALL(model_load_callback_, Run(_, _));
bookmark_dtc_->LoadModels(
base::Bind(&ModelLoadCallbackMock::Run,
base::Unretained(&model_load_callback_)));
bookmark_dtc_->Stop();
EXPECT_EQ(DataTypeController::NOT_RUNNING, bookmark_dtc_->state());
}
TEST_F(SyncBookmarkDataTypeControllerTest, Stop) {
CreateBookmarkModel(LOAD_MODEL);
SetStartExpectations();
SetAssociateExpectations();
SetStopExpectations();
EXPECT_EQ(DataTypeController::NOT_RUNNING, bookmark_dtc_->state());
EXPECT_CALL(start_callback_, Run(DataTypeController::OK, _, _));
Start();
EXPECT_EQ(DataTypeController::RUNNING, bookmark_dtc_->state());
bookmark_dtc_->Stop();
EXPECT_EQ(DataTypeController::NOT_RUNNING, bookmark_dtc_->state());
}
TEST_F(SyncBookmarkDataTypeControllerTest, OnSingleDatatypeUnrecoverableError) {
CreateBookmarkModel(LOAD_MODEL);
SetStartExpectations();
SetAssociateExpectations();
EXPECT_CALL(*model_associator_, SyncModelHasUserCreatedNodes(_)).
WillRepeatedly(DoAll(SetArgumentPointee<0>(true), Return(true)));
EXPECT_CALL(service_, DisableBrokenDatatype(_,_,_)).
WillOnce(InvokeWithoutArgs(bookmark_dtc_.get(),
&BookmarkDataTypeController::Stop));
SetStopExpectations();
EXPECT_CALL(start_callback_, Run(DataTypeController::OK, _, _));
Start();
// This should cause bookmark_dtc_->Stop() to be called.
bookmark_dtc_->OnSingleDatatypeUnrecoverableError(FROM_HERE, "Test");
base::RunLoop().RunUntilIdle();
}
| [
"[email protected]"
] | |
b3b43b7edc522765ef171b29d9c62c82c4ac0df6 | 33a8809391310e3fd0e8b8e748168287de99395d | /TWallet.cpp | e4c0915df0d8e2429241c099c17d59e0eb2383cd | [] | no_license | voodoo-chile/Cambrian-src | 4edcdccf016849f39ec57d2777578b61c4fa9a3b | 967b7d1fd41a5dacd89757f5cc76d2ec45b9bf05 | refs/heads/master | 2020-05-23T15:31:20.221828 | 2014-10-03T17:05:35 | 2014-10-03T17:05:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,643 | cpp | #ifndef PRECOMPILEDHEADERS_H
#include "PreCompiledHeaders.h"
#endif
const char c_szaWallet[] = "w";
class CHashElementVault : public CHashElement
{
public:
CVaultEventsForContact * m_pVault; // Vault of the hash element
};
class CHashTableVaults : public CHashTable
{
public:
CHashTableVaults();
void AddVault(const CVaultEventsForContact * pVault);
CVaultEventsForContact * PFindVaultRemove(const SHashSha1 * pHashContact);
public:
static const SHashSha1 * S_PGetHashKey(const CHashElementVault * pHashElement) { return &pHashElement->m_pVault->m_hashContact; } // This routine must have a compatible interface as PFn_PszGetHashKey()
};
CHashTableVaults::CHashTableVaults() : CHashTable((PFn_PszGetHashKey)S_PGetHashKey, eHashFunctionHashSha1)
{
SetHashElementSize(sizeof(CHashElementVault));
}
void
CHashTableVaults::AddVault(const CVaultEventsForContact * pVault)
{
CHashElementVault * pHashElement = (CHashElementVault *)PAllocateHashElement();
pHashElement->m_pVault = const_cast<CVaultEventsForContact *>(pVault);
Add(pHashElement);
}
// Find the vault matching the contact hash.
// If the vault is found, remove it from the hash table and return pointer to it.
// Return NULL if there is no vault matching the contact hash.
CVaultEventsForContact *
CHashTableVaults::PFindVaultRemove(const SHashSha1 * pHashContact)
{
Assert(pHashContact != NULL);
CHashElementVault * pHashElement = (CHashElementVault *)PFindHashElementAndRemove((PSZUC)pHashContact);
if (pHashElement != NULL)
return pHashElement->m_pVault;
return NULL;
}
TWallet * TWallet::s_palistWallet;
///////////////////////////////////////////////////////////////////////////////////////////////////
// Remove any reference of the deleted contact, so the application does not crash
void
TWallet::S_DetachFromContactsAboutBeingDeleted()
{
TWallet * pWallet = TWallet::s_palistWallet;
while (pWallet != NULL)
{
CVaultEventsForContact ** ppVaultStop;
CVaultEventsForContact ** ppVault = pWallet->m_arraypaVaults.PrgpGetVaultsStop(OUT &ppVaultStop);
while (ppVault != ppVaultStop)
{
CVaultEventsForContact * pVault = *ppVault++;
pVault->ContactUnbindIfAboutBeingDeleted();
}
pWallet = pWallet->m_pNext;
} // while
} // S_DetachFromContactsAboutBeingDeleted()
void
TWallet::S_AccountsAboutBeingDeleted()
{
S_DetachFromContactsAboutBeingDeleted(); // At the moment, there is no difference between account(s) and contact(s) being deleted
}
void
CArrayPtrVaults::BindVaultMatchingContactHash(TContact * pContact, const SHashSha1 * pHashContact)
{
CVaultEventsForContact ** ppVaultStop;
CVaultEventsForContact ** ppVault = PrgpGetVaultsStop(OUT &ppVaultStop);
while (ppVault != ppVaultStop)
{
CVaultEventsForContact * pVault = *ppVault++;
if (pVault->m_pContactParent_YZ != NULL)
continue;
if (HashSha1_FCompareEqual(&pVault->m_hashContact, pHashContact))
{
pVault->ContactBind(pContact);
return;
}
} // while
}
// Notify all wallets a new contact was added, giving the opportunity of a vault to decrypt itself if its hash matches with the new contact (this is the case when a contact was deleted, and later re-added)
void
TWallet::S_ContactAdded(TContact * pContact)
{
Assert(pContact != NULL);
Assert(pContact->EGetRuntimeClass() == RTI(TContact));
Assert(!pContact->m_strJidBare.FIsEmptyString());
// Find the hash table matching the configuration
TWallet * pWallet = TWallet::s_palistWallet;
while (pWallet != NULL)
{
SHashSha1 hashContact;
pWallet->GetHashOfContact(OUT &hashContact, IN pContact);
pWallet->m_arraypaVaults.BindVaultMatchingContactHash(pContact, IN &hashContact);
pWallet = pWallet->m_pNext;
} // while
} // S_ContactAdded()
// Determine which is the best wallet to allocate a transaction.
IEventWalletTransaction *
TWallet::S_PAllocateEventTransaction(TContact * pContact)
{
// At the moment, use the first wallet in the list, or allocate a new one
if (s_palistWallet == NULL)
g_oConfiguration.NavigationTree_DisplayWallet();
Assert(s_palistWallet != NULL);
return s_palistWallet->PAllocateEventTransaction(pContact);
}
void
TWallet::S_SaveAll()
{
TWallet * pWallet = TWallet::s_palistWallet;
while (pWallet != NULL)
{
pWallet->SerializeXmlToDisk();
pWallet = pWallet->m_pNext;
}
}
QString
TWallet::S_SGetPathFileNameFromPassword(PSZUC pszPassword)
{
SHashSha1 hashFileNameWallet;
HashSha1_CalculateFromSaltedPassword(OUT &hashFileNameWallet, eSaltPrefix_Wallet, IN pszPassword);
return g_oConfiguration.SGetPathOfFileName(IN &hashFileNameWallet);
}
extern TTreeItemDemo * g_pBanking; // Node to attach the wallet
// Open a wallet given a password. The password is used to determine the filename where the wallet is stored.
void
TWallet::S_FileOpen_MB(PSZUC pszPassword)
{
QString sPathFileName = S_SGetPathFileNameFromPassword(IN pszPassword);
// Before attempting to load a wallet from a file, check if the wallet is already opened
TWallet * pWallet = TWallet::s_palistWallet;
while (pWallet != NULL)
{
if (pWallet->m_sPathFileSave == sPathFileName)
{
pWallet->TreeItemW_SelectWithinNavigationTree(); // Select the wallet so the user may see it
return;
}
pWallet = pWallet->m_pNext;
}
CBin binWallet;
MessageLog_AppendTextFormatSev(eSeverityNoise, "Opening wallet $Q\n", &sPathFileName);
binWallet.BinFileReadE(sPathFileName); // Attempt to read the file. If the file is not found, create a new wallet
pWallet = new TWallet(pszPassword, sPathFileName, INOUT &binWallet); // Create a wallet object and let it decrypt and unserialize the transactions
pWallet->EUnserializeFromXml(INOUT &binWallet);
pWallet->TreeItemW_DisplayTransactionsBitcoin();
// pWallet->TreeItem_SelectWithinNavigationTree();
/*
EMessageBoxInformation("Unable to open wallet $Q", &sPathFileName);
delete pWallet;
*/
} // S_FileOpen_MB()
///////////////////////////////////////////////////////////////////////////////////////////////////
IEventWalletTransaction::IEventWalletTransaction(const TIMESTAMP * ptsEventID) : IEvent(ptsEventID)
{
m_amtQuantity = 0;
}
#define d_chAttribute_nAmount 'a'
#define d_chAttribute_strValue 'v'
#define d_chAttribute_strComment 'c'
// IEventWalletTransaction::IEvent::XmlSerializeCoreE()
EXml
IEventWalletTransaction::XmlSerializeCoreE(IOUT CBinXcpStanza * pbinXmlAttributes) const
{
pbinXmlAttributes->BinAppendXmlAttributeL64(d_chAttribute_nAmount, m_amtQuantity);
pbinXmlAttributes->BinAppendXmlAttributeCStr(d_chAttribute_strValue, m_strValue);
pbinXmlAttributes->BinAppendXmlAttributeCStr(d_chAttribute_strComment, m_strComment);
return eXml_zAttributesOnly;
}
// IEventWalletTransaction::IEvent::XmlUnserializeCore()
void
IEventWalletTransaction::XmlUnserializeCore(const CXmlNode * pXmlNodeElement)
{
pXmlNodeElement->UpdateAttributeValueL64(d_chAttribute_nAmount, OUT_F_UNCH &m_amtQuantity);
pXmlNodeElement->UpdateAttributeValueCStr(d_chAttribute_strValue, OUT_F_UNCH &m_strValue);
pXmlNodeElement->UpdateAttributeValueCStr(d_chAttribute_strComment, OUT_F_UNCH &m_strComment);
}
void
IEventWalletTransaction::ChatLogUpdateTextBlock(INOUT OCursor * poCursorTextBlock) CONST_MAY_CREATE_CACHE
{
_BinHtmlInitWithTime(OUT &g_strScratchBufferStatusBar);
g_strScratchBufferStatusBar.BinAppendText_VE(
Event_FIsEventTypeSent() ?
"<img src=':/ico/Bitcoin' valign='bottom' style='valign:bottom'/> You sent <b>{Am}</b> to <b>$s</b>" :
"<img src=':/ico/Bitcoin' valign='bottom' style='valign:bottom'/> You received <b>{Am}</b> from <b>$s</b>",
-m_amtQuantity, ChatLog_PszGetNickNameOfContact());
if (!m_strComment.FIsEmptyString())
g_strScratchBufferStatusBar.BinAppendText_VE(": <i>$S</i>", &m_strComment);
/*
QTextFrameFormat oTextFrameFormat;
oTextFrameFormat.setBorder(1);
oTextFrameFormat.setPadding(2);
oTextFrameFormat.setBorderStyle(QTextFrameFormat::BorderStyle_Solid);
oTextFrameFormat.setBorderBrush(QBrush(0xFF0000));
poCursorTextBlock->currentFrame()->setFrameFormat(oTextFrameFormat);
*/
//poCursorTextBlock->block().setBorderBrush();
poCursorTextBlock->InsertHtmlBin(g_strScratchBufferStatusBar, QBrush(0xFFFF99));
}
BOOL
IEventWalletTransaction::FuIsTransactionMatchingViewFlags(EWalletViewFlags eWalletViewFlags) const
{
if (eWalletViewFlags == eWalletViewFlag_kmDisplayTransactionsAll)
return TRUE;
if (eWalletViewFlags & eWalletViewFlag_kfDisplayTransactionsSent)
return (m_amtQuantity <= 0);
if (eWalletViewFlags & eWalletViewFlag_kfDisplayTransactionsReceived)
return (m_amtQuantity >= 0);
return FALSE;
}
EEventClass
CEventWalletTransactionSent::EGetEventClassForXCP() const
{
return CEventWalletTransactionReceived::c_eEventClass;
}
void
CArrayPtrEvents::Wallets_AppendEventsTransactionsFor(ITreeItem * pFilterBy, EWalletViewFlags eWalletViewFlags)
{
Assert(pFilterBy != NULL);
if (TWallet::s_palistWallet == NULL)
return; // There is no wallet opened, therefore no transactions
const RTI_ENUM rti = pFilterBy->EGetRuntimeClass();
if (rti == RTI(TWallet))
{
// Include all transactions related to a wallet, which means include all the vaults
TWallet * pWallet = (TWallet *)pFilterBy;
CVaultEventsForContact ** ppVaultStop;
CVaultEventsForContact ** ppVault = pWallet->m_arraypaVaults.PrgpGetVaultsStop(OUT &ppVaultStop);
while (ppVault != ppVaultStop)
{
CVaultEventsForContact * pVault = *ppVault++;
pVault->AppendAllEventsTransactionsMatchingViewFlags(IOUT this, eWalletViewFlags);
}
}
else if (rti == RTI(TContact))
{
// Include all transactions related to a contact
TWallet * pWallet = TWallet::s_palistWallet;
while (pWallet != NULL)
{
CVaultEventsForContact * pVault = pWallet->PFindVault((TContact *)pFilterBy);
if (pVault != NULL)
pVault->AppendAllEventsTransactionsMatchingViewFlags(IOUT this, eWalletViewFlags);
pWallet = pWallet->PGetNextWallet();
}
} // if...else
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// Constructor for adding a new vault. A new vault is added when a new event transaction for a contact.
// IMPLEMENTATION NOTES
// This code must in sync with the constructor CHashTableWalletTransactionContactFromConfiguration() to calculate the hash value.
CVaultEventsForContact::CVaultEventsForContact(TWallet * pWalletParent, TContact * pContactParent_NZ)
{
Assert(pWalletParent->EGetRuntimeClass() == RTI(TWallet));
Assert(pContactParent_NZ->EGetRuntimeClass() == RTI(TContact));
m_pWalletParent = pWalletParent;
m_pContactParent_YZ = pContactParent_NZ;
pWalletParent->GetHashOfContact(OUT &m_hashContact, pContactParent_NZ); // Calculate the hash value immediately; this is the only time it will be computed for the vault!
}
void
TWallet::GetHashOfContact(OUT SHashSha1 * pHashSha1, const TContact * pContact) const
{
Assert(pContact->EGetRuntimeClass() == RTI(TContact));
TAccountXmpp * pAccount = pContact->m_pAccount;
CChatConfiguration * pConfiguration = pAccount->m_pProfileParent->m_pConfigurationParent;
g_strScratchBufferStatusBar.BinInitFromBinaryData(IN pConfiguration->PGetSalt(), CChatConfiguration::c_cbSalt);
g_strScratchBufferStatusBar.BinAppendBinaryData(IN &m_hashSalt, sizeof(m_hashSalt));
g_strScratchBufferStatusBar.BinAppendCBinLowercaseAscii(pAccount->m_strJID);
g_strScratchBufferStatusBar.BinAppendCBinLowercaseAscii(pContact->m_strJidBare);
HashSha1_CalculateFromCBin(OUT pHashSha1, g_strScratchBufferStatusBar);
}
CVaultEventsForContact::~CVaultEventsForContact()
{
if (m_pContactParent_YZ != NULL)
{
Assert(m_pContactParent_YZ->EGetRuntimeClass() == RTI(TContact));
m_pContactParent_YZ->m_uFlagsTreeItem |= TContact::FTI_kfChatLogEvents_RepopulateAll; // Repopulate the Chat Log events which will remove the wallet transaction events
}
m_arraypaEvents.DeleteAllEvents();
}
void
CVaultEventsForContact::ContactBind(TContact * pContact)
{
Assert(pContact->EGetRuntimeClass() == RTI(TContact));
Assert(m_pContactParent_YZ == NULL);
m_pContactParent_YZ = pContact;
m_pContactParent_YZ->m_uFlagsTreeItem |= TContact::FTI_kfChatLogEvents_RepopulateAll | TContact::FTI_kfChatLogEvents_IncludeFromWallet;
}
// This is typically when a contact is being deleted
void
CVaultEventsForContact::ContactUnbindIfAboutBeingDeleted()
{
if (m_pContactParent_YZ != NULL)
{
Assert(m_pContactParent_YZ->EGetRuntimeClass() == RTI(TContact));
if (m_binEventsEncrypted.FIsEmptyBinary())
EventsEncryptCb();
if (m_pContactParent_YZ->TreeItemFlags_FuIsDeleted())
{
m_pContactParent_YZ = NULL;
m_arraypaEvents.DeleteAllEvents(); // The events are no longer available since its parent contact is about being deleted
}
}
}
/*
IEventWalletTransaction *
CVaultEventsForContact::PAllocateEventTransaction()
{
Assert(m_pContactParent_YZ != NULL);
Assert(m_pContactParent_YZ->EGetRuntimeClass() == RTI(TContact));
m_binEventsEncrypted.Empty(); // We need to re-encrypt the events
IEventWalletTransaction * pTransaction = new IEventWalletTransaction(m_pContactParent_YZ, NULL);
m_arraypaEvents.Add(PA_CHILD pTransaction);
Assert(pContactParent->EGetRuntimeClass() == RTI(TContact));
Assert(FALSE && "This code needs to be re-implemented and will crash!");
pContactParent->m_uFlagsTreeItem |= TContact::FTI_kfChatLogEventsRepopulateAll | TContact::FTI_kfChatLogEventsIncludeFromWallet;
return pTransaction;
}
*/
void
CVaultEventsForContact::AppendAllEventsTransactionsMatchingViewFlags(IOUT CArrayPtrEvents * parraypEventsTransactions, EWalletViewFlags eWalletViewFlags) CONST_MAY_CREATE_CACHE
{
Assert(parraypEventsTransactions != NULL);
if (m_arraypaEvents.FIsEmpty())
EventsDecrypt();
IEvent ** ppEventStop;
IEvent ** ppEvent = m_arraypaEvents.PrgpGetEventsStop(OUT &ppEventStop);
while (ppEvent != ppEventStop)
{
IEventWalletTransaction * pEvent = (IEventWalletTransaction *)*ppEvent++;
Assert(pEvent->m_tsEventID != d_ts_zNULL);
if (pEvent->EGetEventClass() != eEventClass_eWalletTransactionSent)
continue;
if (pEvent->FuIsTransactionMatchingViewFlags(eWalletViewFlags))
parraypEventsTransactions->Add(pEvent);
}
}
#define d_chXmlAttributeSalt 's'
#define d_szXmlAttributeSalt "s"
#define d_chXmlElementVault 'v'
#define d_szXmlElementVault "v"
#define d_chXmlAttributeContact 'c'
#define d_szXmlAttributeContact "c"
// Constructor to unserialize a vault.
CVaultEventsForContact::CVaultEventsForContact(TWallet * pWalletParent, const CXmlNode * pXmlNodeUnserialize)
{
Assert(pWalletParent->EGetRuntimeClass() == RTI(TWallet));
m_pWalletParent = pWalletParent;
m_pContactParent_YZ = NULL;
if (pXmlNodeUnserialize->UpdateAttributeValueHashSha1(d_chXmlAttributeContact, OUT_F_UNCH &m_hashContact))
{
// Extract the encrypted events (transactions) only if the SHA-1 appears as valid: the hash is necessary to decrypt the events, and without the this decryption key, this encrypted data remain encrypted forever, therefore polluting the database
m_binEventsEncrypted.BinAppendBinaryDataFromBase85Szv_ML(pXmlNodeUnserialize->m_pszuTagValue);
}
}
void
CVaultEventsForContact::EventsDecrypt()
{
Assert(m_arraypaEvents.FIsEmpty());
if (m_pContactParent_YZ != NULL)
{
//MessageLog_AppendTextFormatCo(d_coYellowDirty, "Vault Events for $S: {h|}\n$B\n", &m_pContactParent_YZ->m_strJidBare, &m_hashContact, &m_binEventsEncrypted);
CXmlTree oXmlTree;
if (oXmlTree.EParseFileDataToXmlNodesCopy_ML(IN m_binEventsEncrypted) == errSuccess)
m_arraypaEvents.EventsUnserializeFromDisk(IN &oXmlTree, m_pContactParent_YZ);
}
}
UINT
CVaultEventsForContact::EventsEncryptCb()
{
Assert(m_binEventsEncrypted.FIsEmptyBinary());
/*
g_strScratchBufferStatusBar.Empty();
m_arraypaEvents.EventsSerializeForDisk(INOUT &g_strScratchBufferStatusBar);
int cbEvents = g_strScratchBufferStatusBar.CbGetData();
if (cbEvents > 0)
m_binEventsEncrypted.BinAppendBinaryData(g_strScratchBufferStatusBar.PvGetDataUnsafe(), cbEvents);
Assert(cbEvents >= 0);
return cbEvents;
*/
return 0;
}
// Serialize a vault only if it has events.
void
CVaultEventsForContact::XmlSerializeVault(IOUT CBin * pbinXml)
{
if (m_binEventsEncrypted.FIsEmptyBinary())
{
// We need to serialize and encrypt the events
if (EventsEncryptCb() == 0)
return; // Nothing to serialize
}
pbinXml->BinAppendText_VE("<"d_szXmlElementVault" "d_szXmlAttributeContact"='{h|}'>{B|}</"d_szXmlElementVault">\n", &m_hashContact, &m_binEventsEncrypted);
}
EError
TWallet::EUnserializeFromXml(INOUT CBin * pbinWalletXml)
{
// Check if the 'decoded' XML appears as a valid XML. If not, it is likely the password was incorrect and therefore the decryption transformed the encrypted wallet to some random bytes of data.
(void)pbinWalletXml->FAssignFileSizeAndMd5(INOUT_F_UNCH &m_hashMd5LastSave); // Remember the MD5
CXmlTree oXmlTree;
if (oXmlTree.EParseFileDataToXmlNodesModify_ML(INOUT pbinWalletXml) == errSuccess)
{
//MessageLog_AppendTextFormatCo(d_coGreen, "Wallet:^N", &oXmlTree);
const CXmlNode * pXmlNodeRoot = oXmlTree.PGetRootNodeValidate(c_szaWallet);
if (pXmlNodeRoot != NULL)
{
// TBD: Get the name of the wallet
if (pXmlNodeRoot->UpdateAttributeValueHashSha1(d_chXmlAttributeSalt, OUT_F_UNCH &m_hashSalt))
{
CHashTableVaults oHashTableVaults;
const CXmlNode * pXmlNodeVault = pXmlNodeRoot->PFindElement(d_chXmlElementVault);
while (pXmlNodeVault != NULL)
{
CVaultEventsForContact * pVault = new CVaultEventsForContact(this, pXmlNodeVault);
m_arraypaVaults.Add(PA_CHILD pVault);
oHashTableVaults.AddVault(IN pVault);
pXmlNodeVault = pXmlNodeVault->m_pNextSibling;
}
// Bind each vault to a contact. This is done by searching every contact and matching them to a vault. Some vaults may have no contact because the contact may have been deleted.
// In the future, for performance reasons, the method GetHashOfContact() could be unrolled from the loop.
TAccountXmpp ** ppAccountStop;
TAccountXmpp ** ppAccount = g_arraypAccounts.PrgpGetAccountsStop(OUT &ppAccountStop);
while (ppAccount != ppAccountStop)
{
const TAccountXmpp * pAccount = *ppAccount++;
Assert(pAccount->EGetRuntimeClass() == RTI(TAccountXmpp));
TContact ** ppContactStop;
TContact ** ppContact = pAccount->PrgpGetContactsStop(OUT &ppContactStop);
while (ppContact != ppContactStop)
{
TContact * pContact = *ppContact++;
Assert(pContact != NULL);
Assert(pContact->EGetRuntimeClass() == RTI(TContact));
Assert(pContact->m_pAccount == pAccount);
SHashSha1 hashContact;
GetHashOfContact(OUT &hashContact, IN pContact);
CVaultEventsForContact * pVault = oHashTableVaults.PFindVaultRemove(IN &hashContact);
if (pVault != NULL)
pVault->ContactBind(pContact);
if (oHashTableVaults.GetElementsCount() == 0)
goto Done; // If there are no more elements in the hash table, then we are done
} // while
} // while
} // if
} // if
} // if
Done:
HashSha1_InitRandomIfEmpty(INOUT &m_hashSalt);
return errSuccess;
} // EUnserializeFromXml()
void
TWallet::SerializeXmlToDisk()
{
CBin binXml;
binXml.BinAppendText_VE("<$s "d_szXmlAttributeSalt"='{h|}'>\n", c_szaWallet, &m_hashSalt); // Name of the wallet
// Serialize each vault
CVaultEventsForContact ** ppVaultStop;
CVaultEventsForContact ** ppVault = m_arraypaVaults.PrgpGetVaultsStop(OUT &ppVaultStop);
while (ppVault != ppVaultStop)
{
CVaultEventsForContact * pVault = *ppVault++;
pVault->XmlSerializeVault(INOUT &binXml);
}
binXml.BinAppendText_VE("</$s>", c_szaWallet);
if (binXml.FAssignFileSizeAndMd5(INOUT_F_UNCH &m_hashMd5LastSave))
{
// Encrypt the file with the password
if (m_sPathFileSave.isEmpty())
m_sPathFileSave = S_SGetPathFileNameFromPassword(m_strNameDisplayTyped); // At the moment, use the display name as the password
EError err = binXml.BinFileWriteE(m_sPathFileSave);
Report(err == errSuccess);
}
} // SerializeXmlToDisk()
///////////////////////////////////////////////////////////////////////////////////////////////////
// This constructor must be followed by a call to EUnserializeFromXml() to return an error while loading the wallet.
TWallet::TWallet(PSZUC pszPassword, const QString & sPathFileWallet, INOUT CBin * pbinWalletEncrypted)
{
Assert(pszPassword != NULL);
Assert(!sPathFileWallet.isEmpty());
Assert(pbinWalletEncrypted != NULL);
m_pNext = s_palistWallet;
s_palistWallet = this; // Add the wallet to the global linked list
m_sPathFileSave = sPathFileWallet;
HashKey256_CalculateKeyFromPassword(OUT &m_hashKey, pszPassword);
InitToZeroes(OUT &m_hashMd5LastSave, sizeof(m_hashMd5LastSave));
HashSha1_InitEmpty(OUT &m_hashSalt);
if (!pbinWalletEncrypted->FIsEmptyBinary())
pbinWalletEncrypted->DataDecryptAES256(IN &m_hashKey);
TreeItemW_DisplayWithinNavigationTreeExpand(g_pBanking, (PSZAC)pszPassword, eMenuIconBitcoin); // Display the wallet in the navigation tree using the password as the name (in the future the name will be stored elsewhere)
}
TWallet::~TWallet()
{
// Delete each vault
CVaultEventsForContact ** ppVaultStop;
CVaultEventsForContact ** ppVault = m_arraypaVaults.PrgpGetVaultsStop(OUT &ppVaultStop);
while (ppVault != ppVaultStop)
{
CVaultEventsForContact * paVault = *ppVault++;
delete paVault;
}
m_arraypaVaults.RemoveAllElements();
// Remove the wallet from the global linked list
Assert(s_palistWallet != NULL);
if (s_palistWallet == this)
s_palistWallet = m_pNext;
else
{
TWallet * pWalletPrev = s_palistWallet;
TWallet * pWallet = pWalletPrev->m_pNext;
while (TRUE)
{
Assert(pWallet != NULL);
if (pWallet == this)
{
pWalletPrev->m_pNext = m_pNext;
break;
}
pWalletPrev = pWallet;
pWallet = pWallet->m_pNext;
if (pWallet == NULL)
break;
} // while
} // if...else
}
struct SBitcoinTransaction
{
PSZAC pszDescription;
int m_nAmountUSD;
};
const SBitcoinTransaction c_rgBitcoinTransactions[] =
{
{ "Rent", -800 },
{ "Coffee", -3 },
{ "Web Hosting", -160 },
{ "Domain Name", -13 },
{ "20 hours Spanish Lessons", -200 },
{ "Dental work", -60 },
{ "Purchaded more Bitcoins", +1500 },
{ "Garage Sale", +140 },
{ "Sold Widget", +20 },
{ "Sold BTC at Localbitcoins", -100 },
};
UINT g_uBitcoinValueUSD = 800; // How many USD are necessary to buy 1 BTC
#define d_ts_cWeeks 604800000 // Number of weeks in a timestamp
void
TWallet::GenerateDummyTransactions()
{
CArrayPtrContacts arraypContacts;
// Get all the contacts currently present
TAccountXmpp ** ppAccountStop;
TAccountXmpp ** ppAccount = g_arraypAccounts.PrgpGetAccountsStop(OUT &ppAccountStop);
while (ppAccount != ppAccountStop)
{
TAccountXmpp * pAccount = *ppAccount++;
pAccount->Contacts_Append(IOUT &arraypContacts);
}
const TIMESTAMP tsLastWeek = Timestamp_GetCurrentDateTime() - d_ts_cWeeks;
qsrand(tsLastWeek); // Initialize the random generator with a different seed
const int cContacts = arraypContacts.GetSize();
if (cContacts == 0)
return; // There is not a single contact, therefore no transactions to add
int cTransactions = cContacts * 10; // Generate an average of 10 transactions per contact
MessageLog_AppendTextFormatSev(eSeverityNoise, "Generating $i dummy transactions for wallet '$S'...\n", cTransactions, &m_strNameDisplayTyped);
while (cTransactions-- > 0)
{
TContact * pContact = (TContact *)arraypContacts.PvGetElementAtSafeRandom_YZ();
Assert(pContact != NULL);
CVaultEvents * pVault = pContact->m_paVaultEvents;
if (pVault == NULL)
continue;
IEvent * pEventLast = pVault->PGetEventLast_YZ();
if (pEventLast == NULL)
continue;
TIMESTAMP tsTransactionEnd = pEventLast->m_tsEventID;
if (tsTransactionEnd <= pContact->m_tsCreated)
continue;
TIMESTAMP tsTransactionBegin = pContact->m_tsCreated;
if (tsTransactionBegin < tsLastWeek)
tsTransactionBegin = tsLastWeek;
IEventWalletTransaction * pTransaction = PAllocateEventTransaction(pContact);
pTransaction->m_tsEventID = LGenerateRandomValueBetween(tsTransactionBegin, tsTransactionEnd);
const SBitcoinTransaction * pDescription = &c_rgBitcoinTransactions[qrand() % LENGTH(c_rgBitcoinTransactions)];
pTransaction->m_amtQuantity = (L64)pDescription->m_nAmountUSD * d_cSatoshisPerBitcoin / g_uBitcoinValueUSD;
pTransaction->m_strValue.Format("$i USD", pDescription->m_nAmountUSD);
pTransaction->m_strComment.BinInitFromStringWithNullTerminator(pDescription->pszDescription);
g_uBitcoinValueUSD += (qrand() % 4) - 1; // Make the exchange rate vary a bit
} // while
// Make sure the events of each vault are sorted, otherwise the unserializer will complain the events are out of order
CVaultEventsForContact ** ppVaultStop;
CVaultEventsForContact ** ppVault = m_arraypaVaults.PrgpGetVaultsStop(OUT &ppVaultStop);
while (ppVault != ppVaultStop)
{
CVaultEventsForContact * pVault = *ppVault++;
pVault->SortEventsByIDs();
}
TreeItem_GotFocus(); // Refresh the layout
} // GenerateDummyTransactions()
CVaultEventsForContact *
TWallet::PFindVault(TContact * pContact)
{
Assert(pContact->EGetRuntimeClass() == RTI(TContact));
CVaultEventsForContact ** ppVaultStop;
CVaultEventsForContact ** ppVault = m_arraypaVaults.PrgpGetVaultsStop(OUT &ppVaultStop);
while (ppVault != ppVaultStop)
{
CVaultEventsForContact * pVault = *ppVault++;
if (pVault->PGetContact_YZ() == pContact)
return pVault;
}
return NULL;
}
IEventWalletTransaction *
TWallet::PAllocateEventTransaction(TContact * pContact)
{
Assert(pContact->EGetRuntimeClass() == RTI(TContact));
// Find the vault where the transaction belongs
CVaultEventsForContact * pVault;
CVaultEventsForContact ** ppVaultStop;
CVaultEventsForContact ** ppVault = m_arraypaVaults.PrgpGetVaultsStop(OUT &ppVaultStop);
while (ppVault != ppVaultStop)
{
pVault = *ppVault++;
if (pVault->PGetContact_YZ() == pContact)
goto AddEventToVault;
}
pVault = new CVaultEventsForContact(this, pContact);
m_arraypaVaults.Add(PA_CHILD pVault);
AddEventToVault:
Assert(FALSE && "NYI");
return NULL; //pVault->PAllocateEventTransaction();
}
///////////////////////////////////////////////////////////////////////////////////////////////////
TWalletView::TWalletView(ITreeItem * pParentFilterBy, PSZAC pszName, EWalletViewFlags eWalletViewFlags)
{
m_pTreeItemFilterBy = pParentFilterBy;
m_eWalletViewFlags = eWalletViewFlags;
TreeItemW_DisplayWithinNavigationTreeExpand(pParentFilterBy, pszName, eMenuIconBitcoin);
}
TWalletView::~TWalletView()
{
MessageLog_AppendTextFormatCo(d_coGrayDark, "TWalletView::~TWalletView(0x$p)\n", this);
}
| [
"[email protected]"
] | |
f081acc69341e09f05ab69b72845e7622d94c2ff | aea4503904c1d608b8ff12a090e48e4622f253bf | /HomeWork7/Lesson17/main.cpp | 745797e43cbe6c50e40d9ff243e41810266b56a4 | [] | no_license | lusparon/C-semester3-hometasks | 0b7b8ab37f8bcfb6cfde8d095f303987d44311cb | 3cb82c6b4e2e5fa3726a9d7704285462286057c7 | refs/heads/master | 2020-05-07T11:01:23.365256 | 2019-04-09T21:22:36 | 2019-04-09T21:22:36 | 180,436,499 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 584 | cpp | #include "rsaed_files.h"
void main()
{
setlocale(LC_ALL,"RUSSIAN");
{
rsaed_ofile my_file("myfile.txt");
my_file << 25;
my_file << 50;
}
{
rsaed_ifile my_file("myfile.txt");
int x;
int y;
my_file >> x;
my_file >> y;
cout << "Файл целых: " << x << " " << y << endl;
}
{
rsaed_ofile my_file2("my_file2.txt");
my_file2 << 25.5;
my_file2 << 50.9;
}
{
rsaed_ifile my_file2("my_file2.txt");
double x;
double y;
my_file2 >> x;
my_file2 >> y;
cout << "Файл вещественных : " << x << " " << y << endl;
}
system("pause");
} | [
"[email protected]"
] | |
c2ee35e323eec2e715d100c83b6d65967347eeca | eda6e6c32e7fbe1e6120b6ca32f19f9520dddee9 | /samples/02_oop/2020_is/classes/vector.h | fac51fdd3e721705e64425d47a01598bdffb84bc | [
"MIT"
] | permissive | lacho55/lecture-notes | f4e53653b4c66b62cb37ffb85c9653e8ad8ca1e1 | 87f61ae1c734724d32c1e4a2fec8a30721911fa6 | refs/heads/master | 2021-05-20T04:14:03.314893 | 2020-03-26T12:26:38 | 2020-03-26T12:26:38 | 252,180,344 | 0 | 0 | null | 2020-04-01T13:17:14 | 2020-04-01T13:17:14 | null | UTF-8 | C++ | false | false | 690 | h | #pragma once
template <class T>
class Vector
{
private:
T *data;
size_t size;
public:
Vector ();
Vector (const Vector<T>& v);
void push_back (const T& x);
void push (const T& x);
Vector<T>& operator+= (const T& x);
Vector<T> operator+ (const T& x) const;
Vector<T>& operator+= (const Vector<T>& other);
Vector<T> operator+ (const Vector<T>& other) const;
T& operator[] (size_t i);
T operator[] (size_t i) const;
Vector<T>& operator= (const Vector<T>& v);
size_t length () const;
//operator ==
//operator !=
~Vector();
};
template <class T>
std::ostream& operator << (std::ostream& stream, const Vector<T>& v);
| [
"[email protected]"
] | |
eaa082cc952eb5612a367cf5ff1450f0b7efc958 | 4c6f1119543d9d5b3ab7078fc9abba43bb2a0f5b | /oddities.cpp | b84cd9089bcf3cc27cb9b5916cc37fe63b32f7f9 | [] | no_license | 0xecho/KattisSubmissions | 8072478b10dc4da42b8fa3504e7fc1923a1edc62 | 7cb981be49e1102e9c6254d15cb51af11fce164f | refs/heads/master | 2021-01-03T23:45:32.366936 | 2020-02-13T15:07:03 | 2020-02-13T15:07:03 | 240,287,563 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 851 | cpp |
#include <bits/stdc++.h>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstring>
#include <chrono>
#include <complex>
#define endl "\n"
#define ll long long int
#define vi vector<int>
#define vll vector<ll>
#define vvi vector < vi >
#define pii pair<int,int>
#define pll pair<long long, long long>
#define mod 1000000007
#define inf 1000000000000000001;
#define all(c) c.begin(),c.end()
#define mp(x,y) make_pair(x,y)
#define mem(a,val) memset(a,val,sizeof(a))
#define eb emplace_back
#define f first
#define s second
#define pb push_back
using namespace std;
int main()
{
std::ios::sync_with_stdio(false);
ll T,x;
cin>>T;
while(T--)
{
cin>>x;
cout<<x;
if(x%2==0) cout<<" is even";
else cout<<" is odd";
cout<<endl;
}
return 0;
}
| [
"[email protected]"
] | |
1b8356e125117f54c290e6142079b1a068994df1 | 74d63eb5ea2e33b5a1cb5c1b9c5bd4ef156a16be | /JSBSimMatlab/MexJSBSim.cpp | 2d85d4908e1908bb4bbb5d13bcb2bd09ee435072 | [] | no_license | podhrmic/JSBSim-Matlab | b3551576f06e546e467b68dc846e2a6b9a05454c | 9e6275ba386665eed3bd6156e97dceb4e7feb93f | refs/heads/master | 2021-07-20T10:34:17.255267 | 2021-07-15T17:57:42 | 2021-07-15T17:57:42 | 53,893,360 | 7 | 3 | null | 2016-09-10T03:47:40 | 2016-03-14T21:31:23 | C++ | UTF-8 | C++ | false | false | 10,365 | cpp | // MexJSBSim.cpp : Defines the entry point for the console application.
// by A. Bryant Nichols Jr. 2007
#include "mex.h"
#include "mclcppclass.h"
#include "matrix.h"
#include <iostream>
#include <string>
#include <vector>
#include <FGFDMExec.h>
#include <models/FGPropagate.h>
#include <models/FGAuxiliary.h>
#include <models/FGFCS.h>
#include "JSBSimInterface.h"
using namespace std;
// function prototypes
// ...
// this object should be persistent in memory until
// the MEX-function is cleared by Matlab
JSBSim::FGFDMExec FDMExec;
JSBSimInterface JI(&FDMExec);
void helpOptions() {
mexPrintf("function usage:\n" );
mexPrintf("result = MexJSBSim( string_directive [, string, value] )\n" );
mexPrintf("\n" );
mexPrintf("Examples:\n" );
mexPrintf(" res = MexJSBSim('help');\n" );
mexPrintf(" Prints this help text. returns 1 (always)\n\n" );
mexPrintf(" res = MexJSBSim('open','c172r');\n" );
mexPrintf(" returns 1 if success, 0 otherwise\n\n" );
mexPrintf(" res = MexJSBSim('SetVerbosity',<verbosity level>)\n" );
mexPrintf(" <verbosity level> = 'silent' or 0,\n" );
mexPrintf(" 'verbose' or 1,\n" );
mexPrintf(" 'very verbose' or 2,\n" );
mexPrintf(" returns 1 if success, 0 otherwise\n\n" );
mexPrintf(" res = MexJSBSim('get','fcs/elevator-cmd-norm')\n" );
mexPrintf(" returns the value of the property,\n" );
mexPrintf(" or -9999 if property not found\n\n" );
mexPrintf(" res = MexJSBSim('set','fcs/elevator-cmd-norm',-0.5)\n" );
mexPrintf(" returns 1 if success, 0 otherwise\n\n" );
mexPrintf(" res = MexJSBSim('set','elevator-cmd-norm',-0.5)\n" );
mexPrintf(" res = MexJSBSim('set','u-fps',80.5)\n" );
mexPrintf(" same as above, but it scans a set of predefined,\n" );
mexPrintf(" and commonly used variable names:\n" );
mexPrintf(" 'u-fps', 'v-fps', 'w-fps'\n" );
mexPrintf(" 'p-rad_sec', 'q-rad_sec', 'r-rad_sec'\n" );
mexPrintf(" 'h-sl-ft'\n" );
mexPrintf(" 'long-gc-deg'\n" );
mexPrintf(" 'lat-gc-deg'\n" );
mexPrintf(" 'phi-rad', 'theta-rad', 'psi-rad'\n" );
mexPrintf(" 'elevator-cmd-norm'\n" );
mexPrintf(" 'aileron-cmd-norm'\n" );
mexPrintf(" 'rudder-cmd-norm'\n\n" );
mexPrintf(" res = MexJSBSim('init',ic)\n" );
mexPrintf(" initializes the JSBSim::FGFDMExec by means of the\n" );
mexPrintf(" matlab structure ic.\n" );
mexPrintf(" The structure ic must have the two fields: name and value.\n" );
mexPrintf(" The Matlab user is forced to build such a structure first,\n" );
mexPrintf(" then to pass it to the mex-file. Example:\n" );
mexPrintf(" >> ic(1).name = 'u-fps'; ic(1).value = 80;\n" );
mexPrintf(" >> ic(2).name = 'v-fps'; ic(2).value = 0;\n" );
mexPrintf(" >> ic(3).name = 'w-fps'; ic(3).value = 0;\n" );
mexPrintf(" >> ic(4).name = 'p-rad_sec'; ic(4).value = 0;\n" );
mexPrintf(" >> MexJSBSim('init', ic);\n\n" );
mexPrintf(" returns 1 if success, 0 otherwise\n\n" );
mexPrintf(" res = MexJSBSim('dot',ic)\n" );
mexPrintf(" same as above, regarding input parameters.\n" );
mexPrintf(" returns a res vector containing the following time rates.\n" );
mexPrintf(" ___ body-axis velocity component rates\n");
mexPrintf(" res( 1) : u_dot (ft/s/s)\n");
mexPrintf(" res( 2) : v_dot (ft/s/s)\n");
mexPrintf(" res( 3) : w_dot (ft/s/s)\n");
mexPrintf(" ___ body-axis angular velocity component rates\n");
mexPrintf(" res( 4) : p_dot (rad/s/s)\n");
mexPrintf(" res( 5) : q_dot (rad/s/s)\n");
mexPrintf(" res( 6) : r_dot (rad/s/s)\n");
mexPrintf(" ___ orientation quaternion component rates\n");
mexPrintf(" res( 7) : q1_dot \n");
mexPrintf(" res( 8) : q2_dot \n");
mexPrintf(" res( 9) : q3_dot \n");
mexPrintf(" res(10) : q4_dot \n");
mexPrintf(" ___ ECEF position vector component rates\n");
mexPrintf(" res(11) : x_dot (ft/s)\n");
mexPrintf(" res(12) : y_dot (ft/s)\n");
mexPrintf(" res(13) : z_dot (ft/s)\n");
mexPrintf(" ___ Euler angle rates\n");
mexPrintf(" res(14) : phi_dot (rad/s)\n");
mexPrintf(" res(15) : theta_dot (rad/s)\n");
mexPrintf(" res(16) : psi_dot (rad/s)\n");
mexPrintf(" ___ Altitude rate\n");
mexPrintf(" res(17) : h_dot (ft/s)\n" );
mexPrintf(" ___ Aerodynamic angle rates\n");
mexPrintf(" res(18) : alpha_dot (rad/s)\n");
mexPrintf(" res(19) : beta_dot (rad/s)\n");
}
// the gataway function
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
string aircraftName = "";
string option = "";
if (nrhs>0)
{
char buf[128];
mwSize buflen;
buflen = mxGetNumberOfElements(prhs[0]) + 1;
mxGetString(prhs[0], buf, buflen);
if (nrhs==1)
{
option = string(buf);
if (option == "run")
{
if (JI.RunFDMExec())
{
plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
*mxGetPr(plhs[0]) = 1;
}
else
{
plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
*mxGetPr(plhs[0]) = 0;
}
}
else
{
if ( option == "help")
{
helpOptions();
plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
*mxGetPr(plhs[0]) = 1;
}
else
{
if ( option == "catalog")
{
JI.PrintCatalog();
plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
*mxGetPr(plhs[0]) = 1;
}
else
{
mexPrintf("Incorrect call to this function.\n\n");
helpOptions();
plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
*mxGetPr(plhs[0]) = 0;
}
}
}
}
if (nrhs>1)
{
option = string(buf);
if ( option == "open" )
{
if ( !JI.Open(prhs[1]) ) // load a/c in JSBSim
mexPrintf("JSBSim could not be started.\n");
else
{
plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
*mxGetPr(plhs[0]) = 1;
}
}
if ( option == "get" )
{
// TO DO: if ( !JI.Get(prhs[1]) )
double value;
if ( !JI.GetPropertyValue(prhs[1],value) )
{
mexPrintf("Check property name.\n");
// const char *buf = "PROPERTY NOT SET";
// plhs[0]= mxCreateCharMatrixFromStrings((mwSize)1, (const char **)buf);
plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
*mxGetPr(plhs[0]) = -9999;
return;
}
else
plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
*mxGetPr(plhs[0]) = value;
}
if ( option == "set" )
{
if (nrhs>2)
{
if ( !JI.SetPropertyValue(prhs[1],prhs[2]) )
{
mexPrintf("Property could not be set.\n");
plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
*mxGetPr(plhs[0]) = 0;
}
else
{
plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
*mxGetPr(plhs[0]) = 1;
}
}
else
{
plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
mexPrintf("ERROR: uncorrect use of 'set' option.\n");
*mxGetPr(plhs[0]) = 0;
}
}
if ( option == "SetVerbosity" )
{
if (nrhs==2)
{
if (!JI.SetVerbosity(prhs[1]) )
{
plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
*mxGetPr(plhs[0]) = 0;
}
else
{
plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
*mxGetPr(plhs[0]) = 1;
}
}
else
{
plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
mexPrintf("ERROR: uncorrect use of 'SetVerbosity' option.\n");
*mxGetPr(plhs[0]) = 0;
}
}
if ( option == "init" )
{
if ( !JI.Init(prhs[1]) )
{
mexPrintf("Initialization failed.\n");
plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
*mxGetPr(plhs[0]) = 0;
}
else
{
plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
*mxGetPr(plhs[0]) = 1;
}
}
if ( option == "dot" )
{
// create the vector that receives the calculated values
const unsigned int nStates = 19;
vector<double> statedot;
for(unsigned int i=0;i<nStates;i++)
statedot.push_back(0.0); // init to zero
if ( !JI.Init(prhs[1],statedot) ) // statedot modified by reference
{
mexPrintf("Calculation failed.\n");
plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
*mxGetPr(plhs[0]) = 0;
}
else // now statedot must be converted to a mxArray as needed
{
// see "doubleelement.c"
//const mwSize dims[]={1,nStates};
const mwSize dims[]={nStates};
double data[nStates];
for(unsigned int i=0;i<nStates;i++) // populate data
data[i] = statedot[i];
//for(unsigned int i=0;i<nStates;i++) mexPrintf("%d -> %f\n", i, statedot[i]);
double *start_of_pr;
size_t bytes_to_copy;
(void) nlhs; // unused param
// create a 1-by-nStates array of double
//plhs[0] = mxCreateNumericArray(2,dims,mxDOUBLE_CLASS,mxREAL);
plhs[0] = mxCreateNumericArray(1,dims,mxDOUBLE_CLASS,mxREAL); // produces a Matlab column vector
// populate the real part of the created array
start_of_pr = (double *)mxGetData(plhs[0]);
bytes_to_copy = nStates * mxGetElementSize(plhs[0]);
memcpy(start_of_pr,data,bytes_to_copy);
}
}
} // end of nrhs>1
} // end of nrhs>0
else
helpOptions();
return;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
| [
"[email protected]"
] | |
b5c1fd1d1487e2b2ac9d0ffce0b76e2084a64bb6 | 0b69a011c9ffee099841c140be95ed93c704fb07 | /problemsets/UVA/837.cpp | d88836841b57929143c1c5a7ad7fb9bd61e417c5 | [
"Apache-2.0"
] | permissive | juarezpaulino/coderemite | 4bd03f4f2780eb6013f07c396ba16aa7dbbceea8 | a4649d3f3a89d234457032d14a6646b3af339ac1 | refs/heads/main | 2023-01-31T11:35:19.779668 | 2020-12-18T01:33:46 | 2020-12-18T01:33:46 | 320,931,351 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,565 | cpp | /**
*
* Author: Juarez Paulino(coderemite)
* Email: [email protected]
*
*/
#include <cstdio>
#include <cmath>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
struct event {
double x, r;
char b;
bool operator<(const event &B) const {
if (x != B.x) return x < B.x;
if (b != B.b) return b < B.b;
return r < B.r;
}
};
int main() {
int T;
scanf("%d", &T);
while (T--) {
int N;
scanf("%d", &N);
vector<event> V(2*N, (event){0.,0.,0});
for (int i = 0; i < N; i++) {
double x1, x2, r;
scanf("%lf %*lf %lf %*lf %lf", &x1, &x2, &r);
V[i*2] = (event){x1, r, (x1 < x2)};
V[i*2+1] = (event){x2, r, (x2 < x1)};
}
sort(V.begin(), V.end());
vector<string> ret;
double c = 1.;
char s[20];
for (int i = 0; i < V.size(); i++) {
string r = "";
if (i == 0) r += "-inf ";
else { sprintf(s, "%.3lf ", V[i-1].x); r += s; }
sprintf(s, "%.3lf ", V[i].x); r += s;
sprintf(s, "%.3lf", c); r += s;
ret.push_back(r);
if (V[i].b) c *= V[i].r;
else c /= V[i].r;
}
string r = "";
sprintf(s, "%.3lf ", V[V.size()-1].x); r += s;
r += "+inf 1.000";
ret.push_back(r);
printf("%d\n", ret.size());
for (int i = 0; i < ret.size(); i++) printf("%s\n", ret[i].c_str());
if (T) putchar('\n');
}
return 0;
}
| [
"[email protected]"
] | |
f1a84eadbdc7538a3a0cf8db491a7a26cd6ffd18 | 4cd7f9447801592739d8b05c4f41f9f210fdb784 | /src/chrome/browser/ui/omnibox/omnibox_controller.h | a48ca9d807642e3f5c48d73bc18fb68b0586598f | [
"BSD-3-Clause"
] | permissive | crash0verrid3/Firework-Browser | 15fbcdcdf521f1b1a1f609310fba9a5ab520b92a | 9f2e99135fa4230581bde1806ca51e484372be50 | refs/heads/master | 2021-01-10T13:18:41.267236 | 2015-10-18T23:04:10 | 2015-10-18T23:04:10 | 44,147,842 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,758 | h | // Copyright 2013 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.
#ifndef CHROME_BROWSER_UI_OMNIBOX_OMNIBOX_CONTROLLER_H_
#define CHROME_BROWSER_UI_OMNIBOX_OMNIBOX_CONTROLLER_H_
#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "base/memory/scoped_ptr.h"
#include "base/strings/string16.h"
#include "chrome/browser/bitmap_fetcher/bitmap_fetcher_service.h"
#include "components/omnibox/browser/autocomplete_controller.h"
#include "components/omnibox/browser/autocomplete_controller_delegate.h"
#include "components/omnibox/browser/autocomplete_match.h"
class AUtocompleteInput;
struct AutocompleteMatch;
class AutocompleteResult;
class InstantController;
class OmniboxEditModel;
class OmniboxPopupModel;
class Profile;
namespace gfx {
class Rect;
}
// This class controls the various services that can modify the content
// for the omnibox, including AutocompleteController and InstantController. It
// is responsible of updating the omnibox content.
// TODO(beaudoin): Keep on expanding this class so that OmniboxEditModel no
// longer needs to hold any reference to AutocompleteController. Also make
// this the point of contact between InstantController and OmniboxEditModel.
// As the refactor progresses, keep the class comment up-to-date to
// precisely explain what this class is doing.
class OmniboxController : public AutocompleteControllerDelegate {
public:
OmniboxController(OmniboxEditModel* omnibox_edit_model,
Profile* profile);
~OmniboxController() override;
// The |current_url| field of input is only set for mobile ports.
void StartAutocomplete(const AutocompleteInput& input) const;
// AutocompleteControllerDelegate:
void OnResultChanged(bool default_match_changed) override;
AutocompleteController* autocomplete_controller() {
return autocomplete_controller_.get();
}
// Set |current_match_| to an invalid value, indicating that we do not yet
// have a valid match for the current text in the omnibox.
void InvalidateCurrentMatch();
void set_popup_model(OmniboxPopupModel* popup_model) {
popup_ = popup_model;
}
// TODO(beaudoin): The edit and popup model should be siblings owned by the
// LocationBarView, making this accessor unnecessary.
OmniboxPopupModel* popup_model() const { return popup_; }
const AutocompleteMatch& current_match() const { return current_match_; }
// Turns off keyword mode for the current match.
void ClearPopupKeywordMode() const;
const AutocompleteResult& result() const {
return autocomplete_controller_->result();
}
// TODO(beaudoin): Make private once OmniboxEditModel no longer refers to it.
void DoPreconnect(const AutocompleteMatch& match);
// Stores the bitmap in the OmniboxPopupModel.
void SetAnswerBitmap(const SkBitmap& bitmap);
private:
// Weak, it owns us.
// TODO(beaudoin): Consider defining a delegate to ease unit testing.
OmniboxEditModel* omnibox_edit_model_;
Profile* profile_;
OmniboxPopupModel* popup_;
scoped_ptr<AutocompleteController> autocomplete_controller_;
// TODO(beaudoin): This AutocompleteMatch is used to let the OmniboxEditModel
// know what it should display. Not every field is required for that purpose,
// but the ones specifically needed are unclear. We should therefore spend
// some time to extract these fields and use a tighter structure here.
AutocompleteMatch current_match_;
BitmapFetcherService::RequestId request_id_;
base::WeakPtrFactory<OmniboxController> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(OmniboxController);
};
#endif // CHROME_BROWSER_UI_OMNIBOX_OMNIBOX_CONTROLLER_H_
| [
"sasha@sasha-kaidalov"
] | sasha@sasha-kaidalov |
dcac38148be5765e49c1c6c763cf9e4ad4d050a2 | 4dff595d59df71df9eaf3ea1fda1a880abf297ec | /src/PlayerStatHUD.h | 9b9468163db5ec6b04f34a446998da92b5466e10 | [
"BSD-2-Clause"
] | permissive | dgi09/Tower-Defence | 125254e30e4f5c1ed37dacbfb420fb650df29543 | 2edd53d50c9f913d00de26e7e2bdc5e8b950cc02 | refs/heads/master | 2021-03-12T19:18:59.871669 | 2015-09-17T10:55:17 | 2015-09-17T10:55:17 | 42,649,877 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 478 | h | #pragma once
#include "HUDElement.h"
#include "IObserver.h"
#include <string>
#include "TextSprite.h"
#include "Sprite.h"
#include "SDL_ttf.h"
class Player;
class PlayerStatHUD : public HUDElement , public IObserver
{
TTF_Font * font;
Player * pl;
TextSprite lifeSprite;
TextSprite goldSprite;
public:
PlayerStatHUD(void);
~PlayerStatHUD(void);
void draw(SDL_Renderer * renderer);
void init();
void observeeChange(int type);
void setPlayer(Player * player);
};
| [
"[email protected]"
] | |
dc458020eb251a395be2b7edfece6606bc3d1b09 | 67b7a7085447b7561208ed6df95dd3133df580e2 | /jul03/unified_lod_5/mesh/mesh_reducer.cpp | dc29a0cc80eae825c5ca6da6d3840e2024c7c717 | [] | no_license | dwilliamson/GDMagArchive | 81fd5b708417697bfb2caf8a983dd3ad7decdaf7 | 701948bbd74b7ae765be8cdaf4ae0f875e2bbf8e | refs/heads/master | 2021-06-07T23:41:08.343776 | 2016-10-31T14:42:20 | 2016-10-31T14:42:20 | 72,441,821 | 74 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 32,883 | cpp | // @Cleanliness: Lightweight_Proximity_Grid should have an
// abstracted find() function. That would be nice.
#include "../framework.h"
#include "mesh_reducer.h"
#include "lightweight_proximity_grid.h"
#include "priority_queue.h"
#include "../mesh.h"
#include "error_quadric.h"
#include "mesh_topology_handler.h"
#include "mesh_builder.h"
#include <float.h>
#include <math.h>
extern float GetArea(Vector3 v0, Vector3 v1, Vector3 v2);
struct Reducer_Priority_Queue_Data {
int vertex0;
int vertex1;
};
inline int go_to_next_coincident_vertex(Mesh_Topology_Handler *handler, int cursor) {
assert(cursor < handler->mesh->num_vertices);
int next = handler->vertex_coincidence_chain[cursor];
return next;
}
void get_vertex_uv(Triangle_List_Mesh *mesh, int index, Vector3 *result) {
result->x = mesh->uvs[index].x;
result->y = mesh->uvs[index].y;
result->z = 0;
}
void get_vertex_uv(Triangle_List_Mesh *mesh, int index, float *u_ret, float *v_ret) {
*u_ret = mesh->uvs[index].x;
*v_ret = mesh->uvs[index].y;
}
void get_vertex_position(Triangle_List_Mesh *mesh, int index, Vector3 *result) {
*result = mesh->vertices[index];
}
void Mesh_Reducer::fill_point(float *point, int vertex_index, int material_index) {
float uv_weight = tuning.texture_space_importance_factor;
if (material_index != -1) {
float specific_material_factor = material_factor_uv_over_xyz[material_index];
uv_weight *= specific_material_factor;
}
point[0] = mesh->vertices[vertex_index].x;
point[1] = mesh->vertices[vertex_index].y;
point[2] = mesh->vertices[vertex_index].z;
point[3] = mesh->uvs[vertex_index].x * uv_weight;
point[4] = mesh->uvs[vertex_index].y * uv_weight;
}
void Mesh_Reducer::count_material_areas() {
// Initialize the ratio of UV space to XYZ space for
// each material.
// First build the material arrays and initialize them to 0.
material_area_uv = new float[mesh->num_materials];
material_area_xyz = new float[mesh->num_materials];
material_factor_uv_over_xyz = new float[mesh->num_materials];
int i;
for (i = 0; i < mesh->num_materials; i++) {
material_area_uv[i] = 0;
material_area_xyz[i] = 0;
material_factor_uv_over_xyz[i] = 0;
}
// Now we iterate over all the faces and add up corresponding
// areas. Etc.
for (i = 0; i < mesh->num_faces; i++) {
Reducer_Face *face = &topology_handler->faces[i];
int material_index = face->material;
int N0 = face->indices[0];
int N1 = face->indices[1];
int N2 = face->indices[2];
Vector3 pos0, pos1, pos2;
Vector3 tex0, tex1, tex2;
get_vertex_position(mesh, N0, &pos0);
get_vertex_position(mesh, N1, &pos1);
get_vertex_position(mesh, N2, &pos2);
get_vertex_uv(mesh, N0, &tex0);
get_vertex_uv(mesh, N1, &tex1);
get_vertex_uv(mesh, N2, &tex2);
float XYZArea = GetArea(pos0, pos1, pos2);
float UVArea = GetArea(tex0, tex1, tex2);
material_area_xyz[material_index] += XYZArea;
material_area_uv[material_index] += UVArea;
}
for (i = 0; i < mesh->num_materials; i++) {
if (material_area_uv[i]) {
material_factor_uv_over_xyz[i] = sqrt(material_area_xyz[i] / material_area_uv[i]);
} else {
material_factor_uv_over_xyz[i] = 0;
}
}
}
void Mesh_Reducer::add_face_constraint_to_quadrics(Reducer_Face *face) {
float point0[ERROR_QUADRIC_DIMENSIONS];
float point1[ERROR_QUADRIC_DIMENSIONS];
float point2[ERROR_QUADRIC_DIMENSIONS];
fill_point(point0, face->indices[0], face->material);
fill_point(point1, face->indices[1], face->material);
fill_point(point2, face->indices[2], face->material);
Error_Quadric *quadric0 = get_quadric(face->indices[0]);
Error_Quadric *quadric1 = get_quadric(face->indices[1]);
Error_Quadric *quadric2 = get_quadric(face->indices[2]);
quadric0->accumulate_plane(point0, point1, point2);
quadric1->accumulate_plane(point0, point1, point2);
quadric2->accumulate_plane(point0, point1, point2);
}
void Mesh_Reducer::init_quadrics() {
count_material_areas();
error_quadrics = new Error_Quadric[mesh->num_vertices];
int i;
for (i = 0; i < mesh->num_vertices; i++) {
error_quadrics[i].clear();
}
error_quadrics[0].init_index_table(); // Set up the static data.
for (i = 0; i < topology_handler->num_faces_remaining; i++) {
Reducer_Face *face = &topology_handler->faces[i];
if (!(face->flags & FACE_IS_A_SEAM_FILL)) {
add_face_constraint_to_quadrics(&topology_handler->faces[i]);
}
}
}
Error_Quadric *Mesh_Reducer::get_quadric(int index) {
return &error_quadrics[index];
}
Mesh_Reducer::Mesh_Reducer() {
tuning.material_boundary_penalty = 1000.0f;
tuning.topology_change_penalty = 2.0f;
tuning.icky_face_penalty = 1000.0f;
tuning.texture_space_importance_factor = 2.0f;
tuning.lonely_edge_constraint_factor = 3.0f;
mesh = NULL;
priority_queue = NULL;
proximity_grid = NULL;
error_quadrics = NULL;
num_target_faces = 1000;
num_lonely_edges_detected = 0;
hunt_radius_expansion_factor = 1;
topology_handler = NULL;
}
Mesh_Reducer::~Mesh_Reducer() {
delete proximity_grid;
delete priority_queue;
delete topology_handler;
delete [] error_quadrics;
delete [] material_area_uv;
delete [] material_area_xyz;
delete [] material_factor_uv_over_xyz;
}
float Mesh_Reducer::compute_collapse_error(int index0, int index1) {
// Step through every alias of index0. Find best match
// among aliases of index1. Compute error due to the move,
// accumulate to sum.
// When done, divide sum by number of index0 aliases to
// compute an average.
float error_sum = 0;
float penalty = 1;
int first_alias = index0;
int cursor = index0;
int vertices_considered = 0;
while (1) {
int dest = topology_handler->simple_find_alias_to_map_to(cursor, index1);
if (dest == -1) {
// Material boundary detected. There's no right answer
// here, so let's just collapse to the canonical vertex,
// and jack this reduction by a big penalty.
// (@Improvement: We might
// in future want to try to find the vertex with the
// least amount of error, or something.)
dest = index1;
penalty = tuning.material_boundary_penalty;
}
Error_Quadric *quadric0 = get_quadric(cursor);
Error_Quadric *quadric1 = get_quadric(dest);
assert(quadric0 != quadric1);
float pos_1_array[ERROR_QUADRIC_DIMENSIONS];
fill_point(pos_1_array, dest, topology_handler->material_touched_by_vertex[dest]);
float error = quadric0->evaluate_error(pos_1_array);
error_sum += error;
vertices_considered++;
cursor = topology_handler->vertex_coincidence_chain[cursor];
if (cursor == first_alias) break;
}
if (vertices_considered == 0) return 0;
if (tuning.topology_change_penalty) {
const float TOPOLOGY_CHANGE_EPSILON = 0.5f; // Arbitrary
if (topology_handler->collapse_changes_topology(index0, index1)) {
error_sum += TOPOLOGY_CHANGE_EPSILON;
error_sum *= tuning.topology_change_penalty;
}
}
if (topology_handler->collapse_creates_icky_face(index0, index1)) {
return FLT_MAX;
}
return (error_sum * penalty) / (float)vertices_considered;
// return (error_sum * penalty);
}
void Mesh_Reducer::update_best_candidates(int index0,
int index1,
float *best_error_result,
int *best_v1_result) {
if (index0 == index1) return;
assert(topology_handler->vertex_flags[index0] & VERTEX_IS_LIVE);
assert(topology_handler->vertex_flags[index1] & VERTEX_IS_LIVE);
float Error = compute_collapse_error(index0, index1);
if (Error < *best_error_result) {
*best_error_result = Error;
*best_v1_result = index1;
}
}
int get_vertex_index(Triangle_List_Mesh *mesh, Vector3 *pos) {
int index = pos - mesh->vertices;
assert(index >= 0);
assert(index < mesh->num_vertices);
return index;
}
inline int get_index_within_face(Triangle_List_Mesh *mesh, Reducer_Face *face, int vertex_index) {
int *canonical = mesh->canonical_vertex_map;
assert(canonical[vertex_index] == vertex_index);
int where_within_face;
if (canonical[face->indices[0]] == vertex_index) where_within_face = 0;
else if (canonical[face->indices[1]] == vertex_index) where_within_face = 1;
else if (canonical[face->indices[2]] == vertex_index) where_within_face = 2;
else where_within_face = -1;
return where_within_face;
}
inline bool Mesh_Reducer::vertex_is_marked(int index) {
return topology_handler->vertex_flags[index] & VERTEX_IS_MARKED;
}
inline void Mesh_Reducer::mark_vertex(int index) {
topology_handler->vertex_flags[index] |= VERTEX_IS_MARKED;
}
inline void Mesh_Reducer::unmark_vertex(int index) {
topology_handler->vertex_flags[index] &= ~VERTEX_IS_MARKED;
}
void Mesh_Reducer::collect_and_mark_vertex_star(int vertex_index, Auto_Array <int> *targets) {
Reducer_Face_Membership *membership = &topology_handler->face_membership[vertex_index];
int face_index;
Array_Foreach(&membership->faces, face_index) {
Reducer_Face *face = &topology_handler->faces[face_index];
int within = get_index_within_face(mesh, face, vertex_index);
assert(within != -1);
int n1 = face->indices[(within + 1) % 3];
int n2 = face->indices[(within + 2) % 3];
n1 = mesh->canonical_vertex_map[n1];
n2 = mesh->canonical_vertex_map[n2];
if (!vertex_is_marked(n1)) {
targets->add(n1);
mark_vertex(n1);
}
if (!vertex_is_marked(n2)) {
targets->add(n2);
mark_vertex(n2);
}
} Endeach;
}
float Mesh_Reducer::find_hunt_radius_for_vertex(int vertex_index, Auto_Array <int> *targets) {
float length_sum = 0;
int length_count = 0;
int other_index;
Array_Foreach(targets, other_index) {
length_count++;
Vector3 delta1 = mesh->vertices[other_index] - mesh->vertices[vertex_index];
length_sum += delta1.length();
} Endeach;
if (length_sum == 0) return 0; // @Think: something nonzero instead?
float length_average = length_sum / (float)length_count;
return length_average * hunt_radius_expansion_factor;
}
void Mesh_Reducer::update_best_candidates(int vertex_index,
float *best_error_result,
int *best_v1_result) {
Vector3 *pos = &mesh->vertices[vertex_index];
mark_vertex(vertex_index);
Auto_Array <int> potential_targets;
collect_and_mark_vertex_star(vertex_index, &potential_targets);
float hunt_radius = find_hunt_radius_for_vertex(vertex_index, &potential_targets);
int i0, i1, j0, j1, k0, k1;
i0 = proximity_grid->get_index_x(pos->x - hunt_radius);
i1 = proximity_grid->get_index_x(pos->x + hunt_radius);
j0 = proximity_grid->get_index_y(pos->y - hunt_radius);
j1 = proximity_grid->get_index_y(pos->y + hunt_radius);
k0 = proximity_grid->get_index_z(pos->z - hunt_radius);
k1 = proximity_grid->get_index_z(pos->z + hunt_radius);
float r2 = hunt_radius * hunt_radius;
int i, j, k;
for (k = k0; k <= k1; k++) {
for (j = j0; j <= j1; j++) {
for (i = i0; i <= i1; i++) {
int grid_index = proximity_grid->get_index(i, j, k);
Lightweight_Proximity_Grid_Square *grid_square = &proximity_grid->grid_squares[grid_index];
Auto_Array <Vector3 *> *vertices = &grid_square->vertices;
int n;
for (n = 0; n < vertices->live_items; n++) {
int other_index = get_vertex_index(mesh, vertices->data[n]);
if (!vertex_is_marked(other_index)) {
float d2 = distance_squared(*vertices->data[n], *pos);
if (d2 > r2) continue;
mark_vertex(other_index);
potential_targets.add(other_index);
}
}
}
}
}
unmark_vertex(vertex_index);
int other_index;
Array_Foreach(&potential_targets, other_index) {
unmark_vertex(other_index);
update_best_candidates(vertex_index, other_index,
best_error_result,
best_v1_result);
} Endeach;
if (*best_v1_result == -1) {
int other_index;
Array_Foreach(&potential_targets, other_index) {
update_best_candidates(vertex_index, other_index,
best_error_result,
best_v1_result);
} Endeach;
}
}
inline void Mesh_Reducer::update_single_vertex_without_queueing(int index,
float *error_result,
Reducer_Priority_Queue_Data *data_result) {
data_result->vertex0 = index;
data_result->vertex1 = -1;
float best_error = FLT_MAX;
update_best_candidates(index, &best_error,
&data_result->vertex1);
*error_result = best_error;
}
inline void Mesh_Reducer::queue_single_vertex(int index) {
assert(mesh->canonical_vertex_map[index] == index);
float best_error;
Reducer_Priority_Queue_Data _data;
update_single_vertex_without_queueing(index, &best_error, &_data);
if ((_data.vertex1 != -1) && (best_error < FLT_MAX)) {
Reducer_Priority_Queue_Data *data = new Reducer_Priority_Queue_Data;
*data = _data;
priority_queue->add(best_error, data);
}
}
void Mesh_Reducer::init_priority_queue() {
last_v0_examined = -1;
last_v1_examined = -1;
int i;
for (i = 0; i < topology_handler->max_vertices; i++) {
if (!(topology_handler->vertex_flags[i] & VERTEX_IS_LIVE)) continue;
if (mesh->canonical_vertex_map[i] != i) continue;
queue_single_vertex(i);
}
}
int Mesh_Reducer::find_alias_to_map_to(int from_index,
int to_index) {
int first_alias = to_index;
int cursor = first_alias;
int best_result = -1;
float best_distance2 = FLT_MAX;
float u0, v0;
get_vertex_uv(mesh, from_index, &u0, &v0);
// If we can find a vertex that represents uv coordinates within
// the same material, map to that guy.
while (1) {
if (topology_handler->material_touched_by_vertex[from_index] ==
topology_handler->material_touched_by_vertex[cursor]) {
Vector3 tex0, tex1;
get_vertex_uv(mesh, from_index, &tex0);
get_vertex_uv(mesh, cursor, &tex1);
float distance2 = (tex1 - tex0).length_squared();
if (distance2 < best_distance2) {
best_result = cursor;
best_distance2 = distance2;
}
}
// Go on to the next alias.
cursor = topology_handler->vertex_coincidence_chain[cursor];
if (cursor == first_alias) break;
}
if (best_result != -1) return best_result;
// Give up, just give them an arbitrary one. We could look into
// creating a new vertex as a future extension, or moving this
// one to the new position but... well... I just don't know.
return to_index;
}
void Mesh_Reducer::perform_one_reduction() {
int kill_v0 = -1;
int kill_v1 = -1;
float priority;
Reducer_Priority_Queue_Data *data;
while (1) {
bool success = false;
data = (Reducer_Priority_Queue_Data *)priority_queue->remove_head(&priority, &success);
if (!success) {
// @Improvement: Ugggh, this sucks, we need something better
while (priority_queue->num_items == 0) {
if (hunt_radius_expansion_factor > 10000) return; // XXXX Give up!
hunt_radius_expansion_factor *= 2;
init_priority_queue();
}
continue;
}
assert(success); // We must have one entry in queue per vertex
// on a face...
int v0 = data->vertex0;
int v1 = data->vertex1;
if ((topology_handler->vertex_flags[v0] & VERTEX_IS_LIVE) &&
(topology_handler->vertex_flags[v1] & VERTEX_IS_LIVE)) {
// This is still potentially a valid collapse (both vertices still
// exist) but we don't know whether other stuff has been collapsed
// into V0, invalidating the priority computation that caused us
// to just pull this guy off. So. We have this policy where we
// always re-evaluate guys and throw them back on the queue. If
// we get the same guy twice in a row, we really want to process
// him now, so away he goes. Otherwise, he can wait.
// Re-evaluate this guy and throw him back into the pond.
float new_priority;
update_single_vertex_without_queueing(v0, &new_priority, data);
if (data->vertex1 == -1) {
delete data;
continue;
}
if (new_priority <= priority) {
kill_v0 = data->vertex0;
kill_v1 = data->vertex1;
delete data;
break;
} else {
priority_queue->add(new_priority, data);
}
continue;
}
delete data;
// Hmm, we nuked either the source or destination vertex since
// that was completed...
// If it was the source vertex, just continue.
if (!(topology_handler->vertex_flags[v0] & VERTEX_IS_LIVE)) continue;
// If on the other hand that guy is still alive, we need to
// find a new place to tell him to go. So find one, and
// put it in the queue, and then keep on keepin' on.
queue_single_vertex(v0);
}
perform_one_reduction(kill_v0, kill_v1);
}
void Mesh_Reducer::perform_one_reduction(int kill_v0, int kill_v1) {
assert(kill_v1 >= 0);
int first_alias = kill_v0;
topology_handler->clear_faces_to_check();
while (1) {
int next = go_to_next_coincident_vertex(topology_handler, first_alias);
assert(next != kill_v1);
if (next == first_alias) break;
int map_to = find_alias_to_map_to(next, kill_v1);
// Accumulate quadrics.
if (error_quadrics) {
Error_Quadric *quadric0 = get_quadric(next);
Error_Quadric *quadric1 = get_quadric(map_to);
quadric1->accumulate_quadric(quadric0);
}
// Switch over the indices on all the faces.
topology_handler->remap_vertex_face_indices(next, map_to);
int next_next = go_to_next_coincident_vertex(topology_handler, next);
topology_handler->vertex_coincidence_chain[first_alias] = next_next;
topology_handler->vertex_coincidence_chain[next] = -1;
topology_handler->eliminate_vertex_from_mesh(next);
}
topology_handler->vertex_coincidence_chain[first_alias] = -1;
remove_vertex_from_grid(first_alias);
int map_to = find_alias_to_map_to(first_alias, kill_v1);
if (error_quadrics) { // If we are actually doing detail reduction...
Error_Quadric *quadric0 = get_quadric(first_alias);
Error_Quadric *quadric1 = get_quadric(map_to);
quadric1->accumulate_quadric(quadric0);
}
topology_handler->remap_vertex_face_indices(first_alias, map_to);
topology_handler->eliminate_vertex_from_mesh(first_alias);
topology_handler->check_degenerate_faces();
}
void Mesh_Reducer::compensate_for_lonely_edge(Reducer_Face *face,
int vertex_index0,
int vertex_index1) {
// Make some fake vertices that stick out from this face,
// so's we like can pass them to the quadric thingy to
// impose the constraint.
// We start by getting the XYZ normal of the face.
Vector3 position0;
Vector3 position1;
Vector3 position2;
get_vertex_position(mesh, face->indices[0], &position0);
get_vertex_position(mesh, face->indices[1], &position1);
get_vertex_position(mesh, face->indices[2], &position2);
Vector3 side1 = position1 - position0;
Vector3 side2 = position2 - position0;
Vector3 normal = cross_product(side1, side2);
int can0 = mesh->canonical_vertex_map[vertex_index0];
int can1 = mesh->canonical_vertex_map[vertex_index1];
assert(topology_handler->vertex_flags[can0] & VERTEX_IS_ON_LONELY_EDGE);
assert(topology_handler->vertex_flags[can1] & VERTEX_IS_ON_LONELY_EDGE);
// So that we don't do anything numerically bizarre, we will scale
// this normal vector so that it's the same length as the distance
// between vertex_index0 and vertex_index1.
Vector3 vertex_position_0, vertex_position_1;
get_vertex_position(mesh, vertex_index0, &vertex_position_0);
get_vertex_position(mesh, vertex_index1, &vertex_position_1);
float length = distance(vertex_position_0, vertex_position_1);
normal.safe_normalize();
normal.scale(length);
// Now let's gather the 2 points representing the edge. Then
// we'll manufacture a 3rd point, then tell the quadric guys
// to go deal. Right now we don't do anything with UV (unclear
// whether we should).
float point0[ERROR_QUADRIC_DIMENSIONS];
float point1[ERROR_QUADRIC_DIMENSIONS];
fill_point(point0, vertex_index0, face->material);
fill_point(point1, vertex_index1, face->material);
float point2[ERROR_QUADRIC_DIMENSIONS];
assert(ERROR_QUADRIC_DIMENSIONS == 5);
point2[0] = point1[0] + normal.x;
point2[1] = point1[1] + normal.y;
point2[2] = point1[2] + normal.z;
point2[3] = point1[3];
point2[4] = point1[4];
Error_Quadric *quadric0 = get_quadric(vertex_index0);
Error_Quadric *quadric1 = get_quadric(vertex_index1);
quadric0->accumulate_plane(point0, point1, point2, tuning.lonely_edge_constraint_factor);
quadric1->accumulate_plane(point0, point1, point2, tuning.lonely_edge_constraint_factor);
num_lonely_edges_detected++;
}
void Mesh_Reducer::handle_lonely_edges() {
// Look for all lonely edges on this mesh. For any that
// we find, add a constraint to keep that edge from moving
// much.
int i;
for (i = 0; i < mesh->num_vertices; i++) {
if (!(topology_handler->vertex_flags[i] & VERTEX_IS_LIVE)) continue;
int vertex_0_index = i;
int canonical0 = mesh->canonical_vertex_map[vertex_0_index];
Reducer_Face_Membership *membership = &topology_handler->face_membership[i];
// For each face this vertex is on, take this vertex
// and the 'forward' vertex along the face's winding
// order to constitute the edge we are looking at now.
// (We don't have to consider the guy behind us in the
// winding order, because we will process that edge when
// we are looking at that vertex, and he sees us in front
// of him.)
int j;
for (j = 0; j < membership->faces.live_items; j++) {
int face_index = membership->faces.data[j];
Reducer_Face *face = &topology_handler->faces[face_index];
int where_within_face = get_index_within_face(mesh, face, canonical0);
assert(where_within_face != -1);
int vertex_1_index = face->indices[(where_within_face + 1) % 3];
int canonical1 = mesh->canonical_vertex_map[vertex_1_index];
// Now... we search again through this vertex's membership
// list, to find ANOTHER face containing this vertex,
// which contains the edge appearing in the opposite winding
// order (canonical1 followed by canonical0). If we can find
// no such face, then this edge is lonely.
bool edge_is_lonely = true;
Reducer_Face_Membership *mem1 = &topology_handler->face_membership[canonical1];
int k;
for (k = 0; k < mem1->faces.live_items; k++) {
int face_index1 = mem1->faces.data[k];
if (face_index1 == face_index) continue;
Reducer_Face *face1 = &topology_handler->faces[face_index1];
int where_within_face = get_index_within_face(mesh, face1, canonical0);
if (where_within_face == -1) continue;
int vertex_2_index = face1->indices[(where_within_face + 2) % 3];
int canonical2 = mesh->canonical_vertex_map[vertex_2_index];
if (canonical2 == canonical1) {
edge_is_lonely = false;
break;
}
}
if (edge_is_lonely) {
topology_handler->vertex_flags[canonical0] |= VERTEX_IS_ON_LONELY_EDGE;
topology_handler->vertex_flags[canonical1] |= VERTEX_IS_ON_LONELY_EDGE;
compensate_for_lonely_edge(face, canonical0, canonical1);
}
}
}
}
void Mesh_Reducer::mark_face_as_seam(int index) {
assert(index >= 0);
assert(index < topology_handler->num_faces_remaining);
topology_handler->faces[index].flags |= FACE_IS_A_SEAM_FILL;
}
void Mesh_Reducer::collapse_similar_vertices(float threshold) {
double t2 = threshold * threshold;
float hunt_radius = threshold;
Auto_Array <int> to_collapse;
int n;
for (n = 0; n < mesh->num_vertices; n++) {
if (n != mesh->canonical_vertex_map[n]) continue;
if (!(topology_handler->vertex_flags[n] & VERTEX_IS_LIVE)) continue;
Vector3 *pos = &mesh->vertices[n];
int i0, i1, j0, j1, k0, k1;
i0 = proximity_grid->get_index_x(pos->x - hunt_radius);
i1 = proximity_grid->get_index_x(pos->x + hunt_radius);
j0 = proximity_grid->get_index_y(pos->y - hunt_radius);
j1 = proximity_grid->get_index_y(pos->y + hunt_radius);
k0 = proximity_grid->get_index_z(pos->z - hunt_radius);
k1 = proximity_grid->get_index_z(pos->z + hunt_radius);
to_collapse.reset();
int i, j, k;
for (k = k0; k <= k1; k++) {
for (j = j0; j <= j1; j++) {
for (i = i0; i <= i1; i++) {
int grid_index = proximity_grid->get_index(i, j, k);
Lightweight_Proximity_Grid_Square *grid_square = &proximity_grid->grid_squares[grid_index];
Auto_Array <Vector3 *> *vertices = &grid_square->vertices;
int k;
for (k = 0; k < vertices->live_items; k++) {
int other_index = get_vertex_index(mesh, vertices->data[k]);
if (other_index == n) continue;
assert(topology_handler->vertex_flags[other_index] & VERTEX_IS_LIVE);
double d2 = distance_squared(mesh->vertices[other_index], *pos);
if (d2 <= t2) to_collapse.add(other_index);
}
}
}
}
int target;
Array_Foreach(&to_collapse, target) {
perform_one_reduction(target, n);
topology_handler->check_degenerate_faces();
} Endeach;
}
}
void Mesh_Reducer::reduce(int _num_target_faces) {
// Do setup regarding quadrics, etc.
init_quadrics();
handle_lonely_edges();
priority_queue = new Priority_Queue(mesh->num_vertices * 10);
init_priority_queue();
// Actually do the reduction part now.
// AssertFacesAreSane(mesh);
initial_num_vertices = mesh->num_vertices;
num_target_faces = _num_target_faces;
while (topology_handler->num_faces_remaining > num_target_faces) {
perform_one_reduction();
if (hunt_radius_expansion_factor > 10000) break; // XXXX Give up!
}
}
Mesh_Builder *Mesh_Reducer::prepare_result(int **remap) {
assert(mesh);
assert(topology_handler);
topology_handler->compact_vertices();
int num_vertices = topology_handler->num_vertices_remaining;
int num_faces = topology_handler->num_faces_remaining;
Mesh_Builder *result = new Mesh_Builder(num_vertices, num_faces);
Vector2 *output_uvs = (Vector2 *)topology_handler->output_uvs;
Quaternion *output_tangent_frames = topology_handler->output_tangent_frames;
int *xref = new int[num_vertices];
int i;
for (i = 0; i < num_vertices; i++) {
int index = result->add_vertex(topology_handler->output_vertices[i],
output_uvs[i],
output_tangent_frames[i]);
assert(index == i);
xref[i] = index;
}
for (i = 0; i < num_faces; i++) {
Reducer_Face *face = &topology_handler->faces[i];
result->add_triangle(xref[face->indices[0]], xref[face->indices[1]],
xref[face->indices[2]], face->material);
}
if (remap) {
*remap = xref;
} else {
delete [] xref;
}
for (i = 0; i < mesh->num_materials; i++) {
// @Feature We don't check for no-longer-used materials and compact them.
// This probably doesn't happen very often anyway, BUT we probably
// we probably want to intentionally compact things into lower-res
// textures at some point, for which we allocate one material for
// the whole dude maybe? Oh that would change the material shaders
// and cause popping so it might actually suck.
// Hmm, who the hell knows.
result->add_material(&mesh->material_info[i]);
}
return result;
}
void Mesh_Reducer::get_result(Triangle_List_Mesh **result_return) {
int *remap;
Mesh_Builder *builder = prepare_result(&remap);
// @Robustness: 0.01f threshold, or adjustable distance
// @Robustness: integer remapper
Triangle_List_Mesh *result = builder->build_mesh();
int i;
for (i = 0; i < topology_handler->num_vertices_originally; i++) {
int xref = topology_handler->old_index_to_new_index[i];
topology_handler->old_index_to_new_index[i] = remap[xref];
}
delete [] remap;
*result_return = result;
}
// Mesh_Reducer looks at the dimensions of the model, then cooks up a
// roughly uniform 3D grid. Allocates that grid, iterates over
// the model and plunks every vertex into the grid square where
// it goes. At runtime we do a hunt_radius search through this grid,
// find everyone within a certain distance, and check them to see
// if they are a good collapse candidate. (This way we are
// checking non-edges as vertex collapse candidates, which seems
// like a really good idea given the input data I've seen.)
void Mesh_Reducer::init(Triangle_List_Mesh *_mesh) {
assert(mesh == NULL);
mesh = _mesh;
// Collect the dimensions of the mesh.
Vector3 v0, v1;
v0.x = v0.y = v0.z = FLT_MAX;
v1.x = v1.y = v1.z = -FLT_MAX;
int i;
for (i = 0; i < mesh->num_vertices; i++) {
Vector3 *v = &mesh->vertices[i];
if (v->x < v0.x) v0.x = v->x;
if (v->y < v0.y) v0.y = v->y;
if (v->z < v0.z) v0.z = v->z;
if (v->x > v1.x) v1.x = v->x;
if (v->y > v1.y) v1.y = v->y;
if (v->z > v1.z) v1.z = v->z;
}
if (mesh->num_vertices == 0) v1 = v0 = Vector3(0, 0, 0);
Vector3 dv = v1 - v0;
float widest = Max(dv.x, Max(dv.y, dv.z));
const int RESOLUTION = 12;
float ds = widest / (float)RESOLUTION;
proximity_grid = new Lightweight_Proximity_Grid;
proximity_grid->init(v0, dv, ds);
for (i = 0; i < mesh->num_vertices; i++) {
if (mesh->canonical_vertex_map[i] == i) {
Vector3 *pos = &mesh->vertices[i];
proximity_grid->add(pos);
}
}
topology_handler = new Mesh_Topology_Handler();
topology_handler->init(mesh);
}
void Mesh_Reducer::remove_vertex_from_grid(int vertex_index) {
if (vertex_index != mesh->canonical_vertex_map[vertex_index]) return;
Vector3 *pos = &mesh->vertices[vertex_index];
bool success = proximity_grid->remove(pos);
assert(success);
}
| [
"[email protected]"
] | |
5e47d0bea67f2cc34defa53011e0f7e54e0e1620 | 8d1382b7d1a070fc34a8ea8b2287acbeb49e7b46 | /s3/3-0.cpp | eca7ee962ead1047dc4bd3a3324bb782a6932b7e | [] | no_license | radicam-art/Cpp_project | aa5e92e88b9a47165e3626bc61df4124a730ec1a | 7c212f87417624c71b1d0b859cf0f2c6d1bf00d7 | refs/heads/main | 2023-08-17T10:45:59.686816 | 2021-09-22T01:35:30 | 2021-09-22T01:35:30 | 409,095,626 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 780 | cpp | #include <iostream>
class product
{
int id; //商品ID
public:
int get_id(); //商品IDのgetter
void set_id(int new_id); //商品IDのsetter
};
//getterは何も変更しない
int product::get_id()
{
return id;
}
//setterはメンバ変数を変更する
void product::set_id(int new_id)
{
id = new_id;
}
int main()
{
product p;
p.set_id(42); //ok. pはconstではない。
std::cout << p.get_id() << std::endl; //OK
const product cp{}; //{}の意味については5章5節
//ERROR. constなインスタンスのメンバを変更できてしまうと困る。
//cp.set_id(42);
//ERROR. しかしget_id()は何も変更しないのでOKであってほしい、、、
//std::cout << cp.get_id() << std::endl;
} | [
"[email protected]"
] | |
356265f62c9b6ebc87a020f9901c970a0d7f8ff7 | 978c0789f04aeb3b7b698c5f658272e67378361b | /src/Tonic/ControlCounter.cpp | 981c340a551f78beed7f9d6de04db7f404f3f0fe | [] | no_license | anhinga/Tonic | 4418965da2ac9ad3d83ffb915953079357a09a5b | 13d973903846864fc25185f3fbead49d290f7ac0 | refs/heads/master | 2021-01-18T03:39:32.641718 | 2013-06-03T14:03:03 | 2013-06-03T14:03:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 810 | cpp | //
// ControlCounter.cpp
// Tonic
//
// Created by Morgan Packard on 4/15/13.
// Copyright (c) 2013 Morgan Packard. All rights reserved.
//
#include "ControlCounter.h"
namespace Tonic { namespace Tonic_{
ControlCounter_::ControlCounter_(){
end = ControlValue(std::numeric_limits<float>::infinity());
}
void ControlCounter_::computeOutput(const SynthesisContext_ & context){
ControlGeneratorOutput tickOut = trigger.tick(context);
ControlGeneratorOutput endOut = end.tick(context);
lastOutput_.status = tickOut.status;
if (tickOut.status == ControlGeneratorStatusHasChanged) {
lastOutput_.value += 1;
if(lastOutput_.value > endOut.value){
lastOutput_.value = 0;
}
}
}
} // Namespace Tonic_
} // Namespace Tonic
| [
"[email protected]"
] | |
61c38385c51e8754e51ef25d40ed5b996d2c6a2b | cb0e94e234814236e706d30c7d940e813f07fd00 | /distributions/univariate/continuous/NoncentralChiSquaredRand.h | 771f71c1c641da5fc10cd6644f6b7b03834dcd6d | [
"MIT"
] | permissive | vishalbelsare/RandLib | 9cd2278fc8c6eb59548631ce11b20e1a963475af | 6536dadd6e532316848cade7e48f84fb40135767 | refs/heads/master | 2023-06-23T04:49:20.008681 | 2023-06-20T12:00:53 | 2023-06-20T12:00:53 | 146,628,254 | 0 | 0 | MIT | 2023-06-20T21:18:04 | 2018-08-29T16:30:03 | C++ | UTF-8 | C++ | false | false | 2,226 | h | #ifndef NONCENTRALCHISQUAREDRAND_H
#define NONCENTRALCHISQUAREDRAND_H
#include "ContinuousDistribution.h"
#include "GammaRand.h"
#include "NormalRand.h"
#include "../discrete/PoissonRand.h"
/**
* @brief The NoncentralChiSquaredRand class <BR>
* Noncentral Chi-Squared distribution
*
* Notation: X ~ χ'^2(k, λ)
*
* Related distributions: <BR>
* If X ~ χ'^2(k, 0), then X ~ χ^2(k) <BR>
* X ~ χ^2(k + 2J), where J ~ Po(λ)
*/
template < typename RealType = double >
class RANDLIBSHARED_EXPORT NoncentralChiSquaredRand : public ContinuousDistribution<RealType>
{
double k = 1; ///< degree
double lambda = 2; ///< noncentrality λ
double halfK = 0.5; ///< k / 2
double halfLambda = 1; ///< λ / 2
double sqrtLambda = M_SQRT2; ///< √λ
double logLambda = M_LN2; ///< log(λ)
PoissonRand<int> Y{};
public:
explicit NoncentralChiSquaredRand(double degree = 1, double noncentrality = 0);
String Name() const override;
SUPPORT_TYPE SupportType() const override { return RIGHTSEMIFINITE_T; }
RealType MinValue() const override { return 0; }
RealType MaxValue() const override { return INFINITY; }
void SetParameters(double degree, double noncentrality);
inline double GetDegree() const { return k; }
inline double GetNoncentrality() const { return lambda; }
double f(const RealType & x) const override;
double logf(const RealType & x) const override;
double F(const RealType & x) const override;
double S(const RealType & x) const override;
private:
RealType variateForDegreeEqualOne() const;
public:
static RealType Variate(double degree, double noncentrality, RandGenerator &randGenerator = ProbabilityDistribution<RealType>::staticRandGenerator);
RealType Variate() const override;
void Sample(std::vector<RealType> &outputData) const override;
void Reseed(unsigned long seed) const override;
long double Mean() const override;
long double Variance() const override;
RealType Mode() const override;
long double Skewness() const override;
long double ExcessKurtosis() const override;
private:
std::complex<double> CFImpl(double t) const override;
};
#endif // NONCENTRALCHISQUAREDRAND_H
| [
"[email protected]"
] | |
d465310432f4db2d92c542933beae98942e8fcfa | 0e267ed3b18fabc5cdfce4b047779f92af0a7e3e | /merge.cpp | 2c78a34bc56b91d30314afa72c9374704e9e1a36 | [] | no_license | ICinar/CodingTask | 6fbfb62614b01130706fd164274d41fd22b2f0fd | 2e712b56f28e7b24f4eafe050895d7e96d9e1f33 | refs/heads/main | 2023-04-06T00:24:39.979215 | 2021-04-29T13:07:08 | 2021-04-29T13:07:08 | 362,395,582 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,126 | cpp | #include "merge.h"
#include <exception>
//maximale Anzahl der Intervalle für die Liste.
const int stackSize = 10000;
/**
* Funktion für die Ermittlung der Merge und Consolenausgabe als Ergebnis
*
* @param vect Liste der Intervalle
* @return stack gemergte Intervallliste
*/
vector<Intervall> mergeFunction(vector <Intervall> vect) {
// Überprüfung ob die Liste zu groß ist, um eine Stackoverflow Exception zu vermeiden.
if (vect.size() > stackSize) {
throw std::runtime_error("Die Größe der Intervallliste ist sehr groß und kann nicht verarbeitet werden.");
}
// 1.Schritt Sortiere alle Startintervalle nach Reihenfolge
vect = sortieren(vect,0,vect.size()-1);
//2. Stack für die gemergte Intervalle
vector<Intervall> stack;
stack.push_back(vect[0]);
//3.Überprüfung der Überlappung und speichern in Stack
for (int i = 1; i < vect.size(); i++){
//erste Intervall von stack
Intervall first = stack[stack.size()-1];
//1.Fall Startwert der aktuellen Intervall ist nicht in Endwert des Stacks
if (first.ende < vect[i].anfang) {
stack.push_back(vect[i]);
}
//2.Fall Endwert von aktuellen Intervall und in Stack Intervall überlappen sich
else if (first.ende < vect[i].ende) {
first.ende = vect[i].ende;
stack.pop_back();
stack.push_back(first);
}
}
//4.Ausgabe der gemergten Intervalle
cout << "Output: ";
printIntervall(stack);
return stack;
}
/**
* Teilt die Intervalle und ermittelt den Pivotelement für Quicksort
*
* @param v Intervallliste, left erste Intervall, right letzte Intervall
* @return i gibt die Position der Pivotelement zurück
*/
int partition(vector<Intervall> &v, int left, int right) {
int i = left;
int j = right - 1;
Intervall pivot = v[right];
while (i < j) {
while (i < right && v[i].anfang < pivot.anfang) {
i++;
}
while (j > left && v[j].anfang >= pivot.anfang) {
j--;
}
if (i < j) {
swap(v[i], v[j]);
i++;
j--;
}
}
if (v[i].anfang > pivot.anfang) {
swap(v[i], v[right]);
}
return i;
}
/**
* Sortieralgorithmus (Quicksort) um die Start Intervall nach Reihenfolge zu sortieren
*
* @param vect Intervallliste, left erste Intervall, right letzte Intervall
* @return sortierte Intervallliste
*/
vector<Intervall> sortieren(vector<Intervall> &v, int left, int right) {
if (left < right) {
int pivot = partition(v, left, right);
sortieren(v, left, pivot - 1);
sortieren(v, pivot + 1, right);
}
return v;
}
/**
* Printfunktion für die Intervalle
*
* @param temp Intervallliste die in der Konsole ausgegeben werden soll
*/
void printIntervall(vector<Intervall> temp) {
for (int i = 0; i < temp.size(); i++)
cout<<"["<<temp[i].anfang<<";"<<temp[i].ende<<"] ";
cout <<endl;
}
| [
"[email protected]"
] | |
9352fd1eb99fd176cc5cfd20cd0f72b712ba6bb4 | 969ad0ccfef250abed8d6cdb421c1d682c00b2a8 | /HackerEarth/letsbegin.cpp | 744caf4323b2f9bf5c0fea703f35756e9313b97f | [] | no_license | mayankgrwl97/Competitive-Coding | 82d42e6a5a468006a849820fbfc0ab7df88496b8 | c62fcbaf0216974bc726f88cc672dbabccfd7a32 | refs/heads/master | 2020-05-22T02:48:08.456797 | 2016-10-21T08:56:41 | 2016-10-21T08:56:41 | 65,143,431 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 605 | cpp | #include <bits/stdc++.h>
using namespace std;
int prime[] = {2,3,5,7};
int dp[1000010];
int min1(int a, int b)
{
return (a<b ? a : b);
}
int min(int a, int b, int c, int d)
{
return (min1(a,b) < min1(c,d) ? min1(a,b) : min1(c,d));
}
void populate()
{
dp[0] = dp[1] = -1;
dp[2] = dp[3] = dp[5] = dp[7] = 1;
dp[4] = dp[6] = dp[8] = dp[9] = 2;
for(int i=10; i<=1000000; i++)
{
dp[i] = 1 + min(dp[i-2],dp[i-3], dp[i-5],dp[i-7]);
}
return;
}
int main()
{
freopen("input.txt","r",stdin);
int t,x;
cin>>t;
populate();
while(t--)
{
scanf("%d",&x);
printf("%d\n", dp[x]);
}
return 0;
} | [
"[email protected]"
] | |
c396ddd5a6045003cb250ff80f670ee32e58a916 | b0b710e714a7c973099e05f990a90cdab86a6384 | /level_zero/core/source/gen9/kbl/cmdqueue_kbl.cpp | 58500bcba19de7fc5e2961983fe772973bf84345 | [
"MIT"
] | permissive | gvvynplaine/compute-runtime | b22bd8952d58ac916a7c2b52c8f52860d18687c3 | fd492f28b036f3fa1685ecfbef86e64f8c7e3d8a | refs/heads/master | 2023-01-06T20:44:37.674507 | 2020-10-14T13:40:57 | 2020-10-15T08:22:30 | 304,321,890 | 0 | 0 | MIT | 2020-10-30T12:32:37 | 2020-10-15T12:39:15 | null | UTF-8 | C++ | false | false | 529 | cpp | /*
* Copyright (C) 2019-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "shared/source/gen9/hw_cmds.h"
#include "shared/source/gen9/hw_info.h"
#include "level_zero/core/source/cmdqueue/cmdqueue_hw.inl"
#include "level_zero/core/source/cmdqueue/cmdqueue_hw_base.inl"
#include "cmdqueue_extended.inl"
#include "igfxfmid.h"
namespace L0 {
template struct CommandQueueHw<IGFX_GEN9_CORE>;
static CommandQueuePopulateFactory<IGFX_KABYLAKE, CommandQueueHw<IGFX_GEN9_CORE>> populateKBL;
} // namespace L0
| [
"[email protected]"
] | |
7f64d02e3a0f52dd9bd90a3918472f4d604386ae | eafdba6a2e9ee8a31270d576f5da60df6e72eb0c | /퀼린드롬 (Easy)/퀼린드롬 (Easy).cpp | 7db2996deca83fa015998b8d144db6570af0c09f | [] | no_license | DahamChoi/Algorithm2 | a076b14bc0f7d86710a4447b2f64a2dc76624fd0 | 3fc30d1751c447e388b976a2ce7c5955513cbaa9 | refs/heads/master | 2023-06-01T10:21:51.507089 | 2021-06-27T09:00:53 | 2021-06-27T09:00:53 | 374,948,754 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,909 | cpp | #include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
unordered_map<char, char> quillindrom_table = {
{'A','A'},{'B',' '},{'C',' '},{'D',' '},{'E','3'},
{'F',' '},{'G',' '},{'H','H'},{'I','I'},{'J',' '},
{'K',' '},{'L',' '},{'M','M'},{'N',' '},{'O','O'},
{'P',' '},{'Q',' '},{'R',' '},{'S','2'},{'T','T'},
{'U','U'},{'V','V'},{'W','W'},{'X','X'},{'Y','Y'},
{'Z','5'},{'a',' '},{'b','d'},{'c',' '},{'d','b'},
{'e',' '},{'f',' '},{'g',' '},{'h',' '},{'i','i'},
{'j',' '},{'k',' '},{'l','l'},{'m','m'},{'n','n'},
{'o','o'},{'p','q'},{'q','p'},{'r','7'},{'s',' '},
{'t',' '},{'u','u'},{'v','v'},{'w','w'},{'x','x'},
{'y',' '},{'z',' '},{'0','0'},{'1','1'},{'2','S'},
{'3','E'},{'4',' '},{'5','Z'},{'6',' '},{'7','r'},
{'8','8'},{'9',' '}
};
string make_quillindrom(const string& str, int left, int right) {
string mid;
if (right - left == 2) {
char c = str[right - 1];
if (c != quillindrom_table[c]) {
if (toupper(c) == quillindrom_table[toupper(c)]) {
c = toupper(c);
}
else {
c = tolower(c);
}
}
mid += c;
}
string left_str, right_str;
while (left >= 0) {
left_str += str[left];
right_str += right < str.length() ? str[right] : quillindrom_table[str[left]];
if (right_str.back() == ' ' || quillindrom_table[left_str.back()] != right_str.back()) {
char upper_left = toupper(left_str.back());
char upper_right = quillindrom_table[toupper(left_str.back())];
char lower_left = tolower(left_str.back());
char lower_right = quillindrom_table[tolower(left_str.back())];
if (quillindrom_table[upper_left] == upper_right && upper_right != ' ') {
left_str.back() = upper_left;
right_str.back() = upper_right;
}
else if (quillindrom_table[lower_left] == lower_right && lower_right != ' ') {
left_str.back() = lower_left;
right_str.back() = lower_right;
}
else {
return "";
}
}
--left; ++right;
}
reverse(left_str.begin(), left_str.end());
return left_str + mid + right_str;
}
pair<string, string> make_quillindrom(const string& str, int mid) {
int left, right;
pair<string, string> result;
if (str[mid] != quillindrom_table[str[mid]]) {
if (isalpha(str[mid])) {
if (toupper(str[mid]) == quillindrom_table[toupper(str[mid])]) {
goto ODD;
}
else if (tolower(str[mid]) == quillindrom_table[tolower(str[mid])]) {
goto ODD;
}
}
}
else {
ODD:
left = mid - 1;
right = mid + 1;
result.first = make_quillindrom(str, left, right);
}
left = mid;
right = mid + 1;
result.second = make_quillindrom(str, left, right);
return result;
}
int main() {
ios::sync_with_stdio(false); cin.tie(NULL);
string str; cin >> str;
auto func = [](const char c1, const char c2) {
return toupper(c1) == toupper(c2);
};
string answer;
for (int i = str.length() / 2 - 1; i < str.length(); i++) {
pair<string, string> result = make_quillindrom(str, i);
if (!result.first.empty() && (str.length() == result.first.length()) && ::equal(str.begin(), str.end(), result.first.begin(), func)) {
answer = result.first;
}
if (!result.second.empty() && (str.length() == result.second.length()) && ::equal(str.begin(), str.end(), result.second.begin(), func)) {
answer = result.second;
}
}
if (answer.empty()) {
cout << -1;
}
else {
cout << answer;
}
return 0;
} | [
"[email protected]"
] | |
a206be9bfce26d3f6150205daeb7cdeaa5622b19 | fda1dc494cf4ae354b45aa58b863992487ae5183 | /main.cpp | 2a2b954214bd602104b8b2b105bfc30630097552 | [] | no_license | Zieng/library_manage_system | 6a551fceb2d3749bc3bc19b0644a2ead6614c670 | 39ebaa159b7d130e6f29b6afe5c442eaf471b505 | refs/heads/master | 2016-09-10T19:33:32.255751 | 2015-05-13T06:45:31 | 2015-05-13T06:45:31 | 35,532,485 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 771 | cpp | #include "mainwindow.h"
#include "logindialog.h"
#include <QApplication>
#include <QMessageBox>
#include <QtSql/QtSql>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlQuery>
#include <QtSql/QSqlDriver>
#include <QtGui>
#include <QTableWidget>
#include <QStringList>
#include <QDebug>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("localhost");
db.setDatabaseName("myLibrary");
db.setUserName("library_admi");
db.setPassword("jald234");
if (!db.open())
{
QMessageBox::critical(0, QObject::tr("Database Error"),
db.lastError().text());
}
MainWindow w;
w.set_db(&db);
w.show();
return a.exec();
}
| [
"[email protected]"
] | |
915e73bd5cd8eb1c82b7c8505e8fae89163f16ca | 90873d728ad3992c12820be5f7eae51664b067da | /src/algos/sorts.cpp | ba16bdb3f407f6ca4f5f698f102b06249dcf5814 | [
"MIT"
] | permissive | rschurade/braingl | 2f4cc5fb43f9d625d00e0aada62d7f6f9778d7a0 | 7a6b24adc1faf3c3b9044bb2fda6af4c9f3600a4 | refs/heads/master | 2021-01-10T04:30:23.977641 | 2016-02-06T17:42:59 | 2016-02-06T17:42:59 | 44,483,772 | 5 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 2,075 | cpp | /*
* sorts.cpp
*
* Created on: Nov 26, 2012
* @author Ralph Schurade
*/
#include "sorts.h"
#include <QDebug>
Sorts::Sorts()
{
}
Sorts::~Sorts()
{
}
void Sorts::quickFindFirstK( std::vector<int>& ids, std::vector<float>& vals, int left, int right, int k )
{
if ( right > left )
{
int pivotIndex = left + ( right - left ) / 2;
int pivotNewIndex = Sorts::partition(ids, vals, left, right, pivotIndex);
quickFindFirstK( ids, vals, left, pivotNewIndex-1, k );
if ( pivotNewIndex < k )
{
quickFindFirstK(ids, vals, pivotNewIndex+1, right, k);
}
}
}
int Sorts::partition( std::vector<int>& ids, std::vector<float>& vals, int left, int right, int pivotIndex )
{
int pivotValue = vals.at( ids.at( pivotIndex ) );
Sorts::swap ( ids, pivotIndex, right ); // Move pivot to end
int storeIndex = left;
for ( int i = left; i <= right; ++i ) // for i from left to right
{
if ( vals.at( ids.at (i ) ) > pivotValue )
{
Sorts::swap ( ids, storeIndex, i );
++storeIndex;
}
}
Sorts::swap ( ids, right, storeIndex ); // Move pivot to its final place
return storeIndex;
}
void Sorts::swap( std::vector<int>& ids, int id1, int id2 )
{
int tmp = ids.at( id1 );
ids[id1] = ids.at( id2 );
ids[id2] = tmp;
}
void Sorts::quickSort( std::vector<int>& ids, std::vector<float>& vals, int left, int right )
{
int i = left, j = right;
int tmp;
float pivot = vals.at( ids.at( left + ( right - left ) / 2 ) );
/* partition */
while ( i <= j )
{
while ( vals.at( ids.at( i ) ) > pivot )
++i;
while ( vals.at( ids.at( j ) ) < pivot )
--j;
if ( i <= j )
{
tmp = ids.at( i );
ids[i] = ids.at( j );
ids[j] = tmp;
++i;
--j;
}
};
/* recursion */
if ( left < j )
quickSort( ids, vals, left, j );
if ( i < right )
quickSort( ids, vals, i, right );
}
| [
"[email protected]"
] | |
74041146e247a0bbf1d6229550521f8074f2d8b4 | ec293f1df67855a0393c51f7d1b9acbf75b5b7ff | /main.cpp | cd6649d624599793cf044c3cfdf1e4bee0f37769 | [] | no_license | duxiaodong/globalGuiClass | 9350660022d00734f61574ce5252ff09de9d73d8 | 75d50623b48ebaace74d0010a264361e1664aa5a | refs/heads/master | 2021-01-01T16:49:21.855040 | 2014-10-20T13:46:36 | 2014-10-20T13:46:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 283 | cpp | #include <QtGui/QApplication>
#include "frmmain.h"
#include"myhelper.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MyHelper::SetUTF8Code();
MyHelper::SetStyle("black");
MyHelper::setChinese();
frmMain w;
w.show();
return a.exec();
}
| [
"[email protected]"
] | |
01c77ee7b28147fd2f120954466a4990a3cb4cf5 | 41ade9a3e3bb3d1443b1c763f3ee3423351f9cc8 | /wifip2p/Connection.h | 04104d6c860f0e8b2291b746e0f70c9d7f91bd0d | [] | no_license | nelsn/libwifip2p | 36441213ec64f4c4ad42cb09a8efdedd1fc42338 | cca6aa90f72fbfa10d939c48613abe3aa20ad265 | refs/heads/master | 2016-09-02T23:15:23.388735 | 2013-05-30T07:45:03 | 2013-05-30T07:45:03 | 9,692,759 | 1 | 0 | null | 2013-05-30T07:45:06 | 2013-04-26T10:23:17 | C++ | UTF-8 | C++ | false | false | 513 | h | /*
* Connection.h
*
* Created on: 15.02.2013
* Author: niels_w
*/
#ifndef CONNECTION_H_
#define CONNECTION_H_
#include "wifip2p/Peer.h"
#include "wifip2p/NetworkIntf.h"
namespace wifip2p {
class Connection {
public:
Connection(NetworkIntf nic);
Connection(Peer peer, NetworkIntf nic);
virtual ~Connection();
Peer getPeer() const;
void setPeer(Peer peer);
NetworkIntf getNetworkIntf() const;
private:
Peer peer;
NetworkIntf nic;
};
} /* namespace wifip2p */
#endif /* CONNECTION_H_ */
| [
"[email protected]"
] | |
5b49849c26198def81cf804822a017ecd3209f83 | 4635768758d53c76753797e3696327b16e15dba4 | /Othello/Hotti_Main.cpp | 9dccd4b18bc98e5aa7c9a8fcc037cb86b0625ceb | [] | no_license | tokabe333/AlgorithmBattlers--Server--_tentative_ | 8e2f1d4f4118dc1f21fff3d388f51bf73b78d5f3 | e64a192cc75e4fd6c63644ef4c7c06bfe4ae75d1 | refs/heads/master | 2023-01-15T07:01:57.258867 | 2020-11-27T09:55:17 | 2020-11-27T09:55:17 | 274,859,348 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 7,534 | cpp | #include "../Util/Common.h"
void show(ull black, ull white) {
ull counta = 0x8000000000000000;
for (int i = 1; i <= 64; ++i) {
if (counta & black) {
cout << "○";
} else if (counta & white) {
cout << "●";
} else {
cout << "□";
}
counta >>= 1;
if (!(i % 8)) {
cout << endl;
}
}
// cout << endl;
}
ull candidate(ull black, ull white, bool turn) {
ull cand = 0;
ull player = black * turn + white * (!turn);
ull opponent = black * (!turn) + white * turn;
ull wall = 0x7e7e7e7e7e7e7e7e;
ull o = opponent & wall;
ull left = o & (player << 1);
left |= o & (left << 1);
left |= o & (left << 1);
left |= o & (left << 1);
left |= o & (left << 1);
left |= o & (left << 1);
cand = (left << 1) & ~(player | opponent);
ull right = o & (player >> 1);
right |= o & (right >> 1);
right |= o & (right >> 1);
right |= o & (right >> 1);
right |= o & (right >> 1);
right |= o & (right >> 1);
cand |= (right >> 1) & ~(player | opponent);
wall = 0x00FFFFFFFFFFFF00;
o = opponent & wall;
ull up = o & (player << 8);
up |= o & (up << 8);
up |= o & (up << 8);
up |= o & (up << 8);
up |= o & (up << 8);
up |= o & (up << 8);
cand |= (up << 8) & ~(player | opponent);
wall = 0x00FFFFFFFFFFFF00;
o = opponent & wall;
ull down = o & (player >> 8);
down |= o & (down >> 8);
down |= o & (down >> 8);
down |= o & (down >> 8);
down |= o & (down >> 8);
down |= o & (down >> 8);
cand |= (down >> 8) & ~(player | opponent);
wall = 0x007e7e7e7e7e7e00;
o = opponent & wall;
ull rightup = o & (player << 7);
rightup |= o & (rightup << 7);
rightup |= o & (rightup << 7);
rightup |= o & (rightup << 7);
rightup |= o & (rightup << 7);
rightup |= o & (rightup << 7);
cand |= (rightup << 7) & ~(player | opponent);
ull rightdown = o & (player >> 9);
rightdown |= o & (rightdown >> 9);
rightdown |= o & (rightdown >> 9);
rightdown |= o & (rightdown >> 9);
rightdown |= o & (rightdown >> 9);
rightdown |= o & (rightdown >> 9);
cand |= (rightdown >> 9) & ~(player | opponent);
ull leftdown = o & (player >> 7);
leftdown |= o & (leftdown >> 7);
leftdown |= o & (leftdown >> 7);
leftdown |= o & (leftdown >> 7);
leftdown |= o & (leftdown >> 7);
leftdown |= o & (leftdown >> 7);
cand |= (leftdown >> 7) & ~(player | opponent);
ull leftup = o & (player << 9);
leftup |= o & (leftup << 9);
leftup |= o & (leftup << 9);
leftup |= o & (leftup << 9);
leftup |= o & (leftup << 9);
leftup |= o & (leftup << 9);
cand |= (leftup << 9) & ~(player | opponent);
return cand;
}
void putStone(ull *black, ull *white, bool turn, ull point) {
ull player = *black * turn + *white * (!turn) + point;
ull opponent = *black * (!turn) + *white * turn;
ull wall = 0x7e7e7e7e7e7e7e7e;
ull o = opponent & wall;
ull left = o & (point << 1);
left |= o & (left << 1);
left |= o & (left << 1);
left |= o & (left << 1);
left |= o & (left << 1);
left |= o & (left << 1);
left *= !!(player & (left << 1));
ull right = o & (point >> 1);
right |= o & (right >> 1);
right |= o & (right >> 1);
right |= o & (right >> 1);
right |= o & (right >> 1);
right |= o & (right >> 1);
right *= !!(player & (right >> 1));
wall = 0x00FFFFFFFFFFFF00;
o = opponent & wall;
ull up = o & (point << 8);
up |= o & (up << 8);
up |= o & (up << 8);
up |= o & (up << 8);
up |= o & (up << 8);
up |= o & (up << 8);
up *= !!(player & (up << 8));
wall = 0x00FFFFFFFFFFFF00;
o = opponent & wall;
ull down = o & (point >> 8);
down |= o & (down >> 8);
down |= o & (down >> 8);
down |= o & (down >> 8);
down |= o & (down >> 8);
down |= o & (down >> 8);
down *= !!(player & (down >> 8));
wall = 0x007e7e7e7e7e7e00;
o = opponent & wall;
ull rightup = o & (point << 7);
rightup |= o & (rightup << 7);
rightup |= o & (rightup << 7);
rightup |= o & (rightup << 7);
rightup |= o & (rightup << 7);
rightup |= o & (rightup << 7);
rightup *= !!(player & (rightup << 7));
ull leftdown = o & (point >> 7);
leftdown |= o & (leftdown >> 7);
leftdown |= o & (leftdown >> 7);
leftdown |= o & (leftdown >> 7);
leftdown |= o & (leftdown >> 7);
leftdown |= o & (leftdown >> 7);
leftdown *= !!(player & (leftdown >> 7));
ull rightdown = o & (point >> 9);
rightdown |= o & (rightdown >> 9);
rightdown |= o & (rightdown >> 9);
rightdown |= o & (rightdown >> 9);
rightdown |= o & (rightdown >> 9);
rightdown |= o & (rightdown >> 9);
rightdown *= !!(player & (rightdown >> 9));
ull leftup = o & (point << 9);
leftup |= o & (leftup << 9);
leftup |= o & (leftup << 9);
leftup |= o & (leftup << 9);
leftup |= o & (leftup << 9);
leftup |= o & (leftup << 9);
leftup *= !!(player & (leftup << 9));
ull rev = up | down | left | right | rightup | rightdown | leftdown | leftup;
player |= rev;
opponent -= rev;
*black = player * turn + opponent * (!turn);
*white = opponent * (turn) + player * (!turn);
}
int count(ull t) {
t = (t & 0x5555555555555555) + ((t & 0xAAAAAAAAAAAAAAAA) >> 1);
t = (t & 0x3333333333333333) + ((t & 0xCCCCCCCCCCCCCCCC) >> 2);
t = (t & 0x0F0F0F0F0F0F0F0F) + ((t & 0xF0F0F0F0F0F0F0F0) >> 4);
t = (t & 0x00FF00FF00FF00FF) + ((t & 0xFF00FF00FF00FF00) >> 8);
t = (t & 0x0000FFFF0000FFFF) + ((t & 0xFFFF0000FFFF0000) >> 16);
t = (t & 0x00000000FFFFFFFF) + ((t & 0xFFFFFFFF00000000) >> 32);
return t;
}
random_device rd{};
time_t t = time(0);
mt19937 randd(t);
ull Monkey(ull cand) {
int point = randd() % count(cand);
int index = 0;
ull counta = 1;
for (int i = 0; i < 64; ++i) {
if (counta & cand) {
if (index == point) {
return counta;
} else {
index++;
}
}
counta <<= 1;
}
}
int bitCount(ull player) {
int size = 64;
ull mask = 0x8000000000000000;
int count = 0;
for (int i = 0; i < size; ++i) {
if ((mask & player) != 0) count += 1;
// cout << "count:" << count << " mask:" << mask << " player:" << player
// << " and:" << (mask & player) << endl;
mask = mask >> 1;
}
return count;
}
// turn:1 先手 turn:2 後手
int main() {
time_t start, end;
double gameTime = 0;
for (int i = 0; i < 10; ++i) {
ull black = 0x0000000810000000;
ull white = 0x0000001008000000;
bool turn = 1;
ull cand = 0;
start = clock();
while (1) {
// show(black, white);
if (!count(cand)) {
cand = candidate(black, white, turn);
if (!count(cand)) {
break;
}
} else {
cand = candidate(black, white, turn);
if (!count(cand)) {
continue;
}
}
ull point = Monkey(cand);
cout << "monkey:" << point << endl;
putStone(&black, &white, turn, point);
turn = !turn;
// cout << "white:" << white << " black:" << black << endl;
}
end = clock();
gameTime += (end - start);
int blackScore = bitCount(black);
int whiteScore = bitCount(white);
// if (turn == 1) {
// int b = blackScore;
// blackScore = whiteScore;
// whiteScore = b;
// }
show(black, white);
string win = whiteScore > blackScore ? "白" : "黒";
cout << (whiteScore == blackScore ? "引き分け" : "win:" + win)
<< " 白:" << whiteScore << " 黒" << blackScore << " 黒盤:" << black
<< " 白盤:" << white << endl
<< endl;
}
cout << "time : " << gameTime / 1000 << "ms" << endl;
// show(black, white);
return 0;
} | [
"[email protected]"
] | |
e0d2a2d26d6e44e86ea052663ef8fa1083b3a8a2 | 49e49dbc78563a33f7c6ab182c250e5fe1126230 | /main.cpp | b1bb9c15e697d52f30644acd77841da052875ebb | [] | no_license | turtle11311/LogicEncryption | 617c504d7f30671b6c3f17c818a12db19d23e17c | 328257b67eb8c4ba3d8fff0bb28df1fb83019dcd | refs/heads/master | 2020-03-16T08:56:42.779416 | 2018-05-08T12:29:23 | 2018-05-08T12:29:23 | 132,605,486 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,157 | cpp | #include "include.h"
using namespace std;
extern void Abc_Start();
extern void Abc_Stop();
extern Bn_Ntk *Io_ReadBench(const char *pFileName);
extern void GenerateRandomPatterns(Bn_Ntk *bNtk);
extern void Simulation(Vec_Ptr_t *NodeDFS_Ary);
extern void BackupValue(Vec_Ptr_t *Node_Ary);
extern Wire_Corruption *CorruptionCompute(Bn_Ntk *bNtk);
extern void Bn_NtkDFS(Bn_Ntk *bNtk);
extern void ComputeLevel(Vec_Ptr_t *NodeDFS_Ary);
extern void PreOrderTraversal(Vec_Ptr_t *NodePOT_Ary, Bn_Node *bNode);
extern void PrintBn_Ntk(Bn_Ntk *bNtk, const char *pFileName);
extern int Id, gatecount;
void PrintCorruption(Bn_Ntk *bNtk);
int nWords = 32, nKeys = 64;
double nPatterns;
double keybound = 0.05;
Vec_Ptr_t *correct_Po;
//***********************************************
int main(int argc, char const *argv[]) {
mpfr_class::set_dprec(128);
int j, cnt = 0;
unsigned *tmp;
Bn_Ntk *bNtk;
Bn_Node *bNode, *KeyPi, *KeyGate;
Wire_Corruption *Key_loc;
Vec_Ptr_t *NodePOT_Ary = Vec_PtrAlloc(0);
// long Start_Time, End_Time;
// Read bench
bNtk = Io_ReadBench(argv[1]);
// PrintBn_Ntk(bNtk);
nKeys = (gatecount * keybound) + 0.5;
cout << "num_keys: " << nKeys << endl;
correct_Po = Vec_PtrAlloc(0);
nPatterns = 32 * nWords;
mpfr_class two;
two = "2";
Vec_PtrForEachEntryReverse(Bn_Node *, bNtk->Po_Ary, bNode, j) {
mpfr_pow_si(bNode->Weight.get_mpfr_t(), two.get_mpfr_t(), -(++cnt),
MPFR_RNDN);
};
Vec_PtrForEachEntry(Bn_Node *, bNtk->Node_Ary, bNode, j) {
bNode->Value = ALLOC(unsigned, nWords);
bNode->Backup = ALLOC(unsigned, nWords);
}
GenerateRandomPatterns(bNtk);
Simulation(bNtk->NodeDFS_Ary);
BackupValue(bNtk->NodeDFS_Ary);
Vec_PtrForEachEntry(Bn_Node *, bNtk->Po_Ary, bNode, j) {
tmp = ALLOC(unsigned, nWords);
for (int i = 0; i < nWords; ++i) tmp[i] = bNode->Value[i];
Vec_PtrPush(correct_Po, tmp);
}
for (int i = 0; i < nKeys; ++i) {
Key_loc = CorruptionCompute(bNtk);
// KeyPi
KeyPi = new Bn_Node();
KeyPi->Id = Id++;
KeyPi->Type = 1; // 0: pi, 1: keypi, 2: po, 3: internal
KeyPi->FType = 0; // 0: buff, 1: not, 2: and, 3: or, 4: nand, 5: nor,
// 6: xor, 7: nxor, 8: mux
KeyPi->Name = "ki" + to_string(i);
KeyPi->Value = ALLOC(unsigned, nWords);
KeyPi->Backup = ALLOC(unsigned, nWords);
Vec_PtrPush(bNtk->Key_Ary, KeyPi);
Vec_PtrPush(bNtk->Node_Ary, KeyPi);
for (int k = 0; k < nWords; ++k) {
KeyPi->Value[k] = RANDOM_UNSIGNED;
KeyPi->Backup[k] = KeyPi->Value[k];
}
// KeyGate
KeyGate = new Bn_Node();
KeyGate->Id = Id++;
KeyGate->Type = 3; // 0: pi, 1: keypi, 2: po, 3: internal
KeyGate->FType = 6; // 0: buff, 1: not, 2: and, 3: or, 4: nand, 5: nor,
// 6: xor, 7: nxor, 8: mux
KeyGate->Name = "kg" + to_string(i);
KeyGate->Value = ALLOC(unsigned, nWords);
KeyGate->Backup = ALLOC(unsigned, nWords);
Vec_PtrPush(bNtk->Node_Ary, KeyGate);
Vec_PtrPush(KeyPi->Fanout_Ary, KeyGate);
Vec_PtrPush(KeyGate->Fanin_Ary, KeyPi);
Vec_PtrPush(KeyGate->Fanin_Ary, Key_loc->ns);
Vec_PtrPush(KeyGate->Fanout_Ary, Key_loc->nd);
Vec_PtrRemove(Key_loc->ns->Fanout_Ary, Key_loc->nd);
Vec_PtrPush(Key_loc->ns->Fanout_Ary, KeyGate);
Vec_PtrRemove(Key_loc->nd->Fanin_Ary, Key_loc->ns);
Vec_PtrPush(Key_loc->nd->Fanin_Ary, KeyGate);
free(Key_loc);
PreOrderTraversal(NodePOT_Ary, KeyGate);
Simulation(NodePOT_Ary);
BackupValue(NodePOT_Ary);
}
Bn_NtkDFS(bNtk);
ComputeLevel(bNtk->NodeDFS_Ary);
PrintCorruption(bNtk);
PrintBn_Ntk(bNtk, argv[2]);
Vec_PtrForEachEntry(Bn_Node *, bNtk->Node_Ary, bNode, j) {
free(bNode->Value);
free(bNode->Backup);
delete bNode;
}
delete bNtk;
return 0;
}
void PrintCorruption(Bn_Ntk *bNtk) {
int j;
Bn_Node *bNode;
// unsigned * Po_value;
unsigned long long HD = 0;
mpfr_class MD;
/*unsigned *Tmp = ALLOC(unsigned, 1);
Vec_PtrForEachEntry(Bn_Node *, bNtk->Po_Ary, bNode, j) {
for (int i = 0; i < nWords; ++i) {
Tmp[0] = bNode->Value[i] ^ bNode->Backup[i];
for (int k = 0; k < 32; ++k)
if (GetBit(&Tmp[0], k) == 1)
MD += bNode->Weight;
}
}
cout << "MD: " << MD << " bitcount: " << bitcount << " nPatterns: " <<
nPatterns << endl;
cout << "Corruption value: " << fixed << setprecision(3) << (double)(MD
/ (bitcount * nPatterns)) << endl;*/
mpfr_class avg1;
avg1 = "0";
double avg2 = 0;
for (int i = 0; i < nWords; ++i) {
for (int k = 0; k < 32; ++k) {
MD = "0", HD = 0;
Vec_PtrForEachEntry(Bn_Node *, bNtk->Po_Ary, bNode, j) {
// cout << GetBit(&bNode->Value[i], k);
if (GetBit(&bNode->Value[i], k) !=
GetBit(&((unsigned *)Vec_PtrGetEntry(correct_Po, j))[i],
k)) {
MD += bNode->Weight;
HD++;
}
}
/*cout << endl;
Vec_PtrForEachEntry(unsigned *, correct_Po, Po_value, j) {
cout << GetBit(&Po_value[i], k);
}
cout << endl;
cout << "corruption_value: " << fixed << setprecision(3) <<
((double)MD / (bitcount)) << endl;
cout << "hamming_distance: " << fixed << setprecision(3) <<
((double)HD / bNtk->Po_Ary->nSize) << endl;*/
avg1 += MD;
avg2 += ((double)HD / bNtk->Po_Ary->nSize);
}
}
avg1 /= nPatterns;
mpfr_printf("CV: %.128Rf\n", avg1.get_mpfr_t());
cout << "HD: " << avg2 / nPatterns << endl;
}
| [
"[email protected]"
] | |
647849cb2dce79ef309b871f8d87a02baf83dbfd | 536656cd89e4fa3a92b5dcab28657d60d1d244bd | /chrome/browser/usb/web_usb_chooser.h | 61b9e9f41e43969955d8df5df8a164f58fc0078a | [
"BSD-3-Clause"
] | permissive | ECS-251-W2020/chromium | 79caebf50443f297557d9510620bf8d44a68399a | ac814e85cb870a6b569e184c7a60a70ff3cb19f9 | refs/heads/master | 2022-08-19T17:42:46.887573 | 2020-03-18T06:08:44 | 2020-03-18T06:08:44 | 248,141,336 | 7 | 8 | BSD-3-Clause | 2022-07-06T20:32:48 | 2020-03-18T04:52:18 | null | UTF-8 | C++ | false | false | 1,336 | h | // Copyright 2015 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.
#ifndef CHROME_BROWSER_USB_WEB_USB_CHOOSER_H_
#define CHROME_BROWSER_USB_WEB_USB_CHOOSER_H_
#include <memory>
#include <vector>
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "components/bubble/bubble_reference.h"
#include "third_party/blink/public/mojom/usb/web_usb_service.mojom.h"
namespace content {
class RenderFrameHost;
}
class UsbChooserController;
// This interface can be used by a webpage to request permission from user
// to access a certain device.
class WebUsbChooser {
public:
explicit WebUsbChooser(content::RenderFrameHost* render_frame_host);
virtual ~WebUsbChooser();
void GetPermission(
std::vector<device::mojom::UsbDeviceFilterPtr> device_filters,
blink::mojom::WebUsbService::GetPermissionCallback callback);
virtual void ShowChooser(
std::unique_ptr<UsbChooserController> controller) = 0;
virtual base::WeakPtr<WebUsbChooser> GetWeakPtr() = 0;
content::RenderFrameHost* render_frame_host() { return render_frame_host_; }
private:
content::RenderFrameHost* const render_frame_host_;
DISALLOW_COPY_AND_ASSIGN(WebUsbChooser);
};
#endif // CHROME_BROWSER_USB_WEB_USB_CHOOSER_H_
| [
"[email protected]"
] | |
7465ef9bb75b5f026a59cd43bec80576dcd20c7c | 67c00ac3536a2b9bec23507087309a4738aa41f8 | /cop_cad_plugins/src/ShapeBased3D.cpp | 571c8ebb2b61f76558d1ec549a772cc2a602d686 | [] | no_license | code-iai/ias_perception_aux | c1ab8cc0acbee4ee2ffe0b6149d96e6bdb88adfa | 2b47131471c5d941eb8ea97197c4cb5947a07c3c | refs/heads/master | 2020-05-19T10:38:41.103026 | 2013-06-24T09:05:12 | 2013-06-24T09:05:12 | 10,903,520 | 3 | 2 | null | null | null | null | MacCentralEurope | C++ | false | false | 21,310 | cpp | /*
* Copyright (C) 2009 by Ulrich Friedrich Klank <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/************************************************************************
ShapeBased3D.cpp - Copyright klank
**************************************************************************/
#include "ShapeBased3D.h"
#include "XMLTag.h"
#include "RelPoseHTuple.h"
#include "cpp/HalconCpp.h"
#include "SupportingPlaneDescriptor.h"
#include "SupportingPlaneDetector.h"
using namespace Halcon;
#include "ShapeModel.h"
#define XML_ATTRIBUTE_MINSCORE "MinScore"
#define XML_ATTRIBUTE_GREEDY "Greediness"
#define XML_ATTRIBUTE_LEVELS "Levels"
using namespace cop;
/**
* DEFAULT Values
*/
#define DEFAULT_MINSCORE 0.40
#define DEFAULT_GREEDINESS 0.80
#define DEFAULT_LEVELS 0
/**
* Macro for assigning standard values to the parameter list
*/
#define ASSIGN_DEFAULT_PARAM_LIST(m_paramNameList) \
(*m_paramNameList)[0] = "longitude_min"; \
(*m_paramNameList)[1] = "longitude_max"; \
(*m_paramNameList)[2] = "latitude_min"; \
(*m_paramNameList)[3] = "latitude_max"; \
(*m_paramNameList)[4] = "cam_roll_min"; \
(*m_paramNameList)[5] = "cam_roll_max"; \
(*m_paramNameList)[6] = "dist_min"; \
(*m_paramNameList)[7] = "dist_max"; \
(*m_paramNameList)[8] = "num_matches"; \
// Constructors/Destructors
//
ShapeBased3D::ShapeBased3D () :
LocateAlgorithm(),
m_minScore(DEFAULT_MINSCORE),
m_greediness(DEFAULT_GREEDINESS),
m_levels(DEFAULT_LEVELS)
{
m_paramList = new HTuple(10, 0.0);
m_paramNameList = new HTuple(10, "");
tuple_gen_const(9, 0.0, m_paramList);
tuple_gen_const(9, "", m_paramNameList);
ASSIGN_DEFAULT_PARAM_LIST(m_paramNameList)
(*m_paramNameList)[9] = "pose_refinement";
(*m_paramList)[9] = "none";
}
void ShapeBased3D::SetData (XMLTag* tag)
{
if(tag != NULL)
{
m_minScore = tag->GetPropertyDouble(XML_ATTRIBUTE_MINSCORE, DEFAULT_MINSCORE);
if(m_minScore < 0.2 || m_minScore > 0.99)
{
m_minScore = DEFAULT_MINSCORE;
}
m_greediness = tag->GetPropertyDouble(XML_ATTRIBUTE_GREEDY, DEFAULT_GREEDINESS);
if(m_greediness < 0.0 || m_greediness > 0.99)
{
m_greediness = DEFAULT_GREEDINESS;
}
m_levels = tag->GetPropertyInt(XML_ATTRIBUTE_LEVELS,DEFAULT_LEVELS);
if(m_levels < 0 || m_levels > 7)
{
m_levels = DEFAULT_LEVELS;
}
}
m_paramList = new HTuple(9, 0.0);
m_paramNameList = new HTuple(9, "");
ASSIGN_DEFAULT_PARAM_LIST(m_paramNameList);
(*m_paramNameList)[9] = "pose_refinement";
(*m_paramList)[9] = "none";
}
XMLTag* ShapeBased3D::Save()
{
XMLTag* tag = new XMLTag(GetName());
tag->AddProperty(XML_ATTRIBUTE_MINSCORE, m_minScore);
tag->AddProperty(XML_ATTRIBUTE_GREEDY, m_greediness);
tag->AddProperty(XML_ATTRIBUTE_LEVELS, m_levels);
return tag;
}
ShapeBased3D::~ShapeBased3D ( )
{
delete m_paramList;
delete m_paramNameList;
}
/**
* Given an valid last-pose of the object we want to try to track it.
* TODO: make sure, that we do not track on search sŁace changes.
*/
void GuidedPoseRestiction(Halcon::HTuple* paramList,Halcon::HTuple* paramNameList, Hlong model, double fraction, RelPose* pose, Halcon::HTuple camparam,Halcon::Hobject* reg, ShapeModelParamSet* pm)
{
Halcon::HTuple poseout, hpose, hommat3d, hommat3dInv, poserefabg, longitude, latitude, distance, camroll, row, col;
/* generate Tuple with the pose */
RelPoseHTuple::GetPose(pose, &hpose);
/* TOCHECK: what happens here*/
Halcon::trans_pose_shape_model_3d(model,hpose, "model_to_ref", &poseout);
/* Invert the pose*/
Halcon::pose_to_hom_mat3d(poseout, &hommat3d);
Halcon::hom_mat3d_invert(hommat3d, &hommat3dInv);
/* Calc cartesian */
Halcon::convert_point_3d_cart_to_spher(hommat3dInv[3].D(), hommat3dInv[7].D(),hommat3dInv[11].D(), "-y", "-z", &longitude, &latitude, &distance);
/* Coordinates for region */
Halcon::project_3d_point(hommat3d[3].D(), hommat3d[7].D(), hommat3d[11].D(), camparam, &row, &col);
#ifdef _DEBUG
printf("Tracked object in the image at %f %f (lon: %f lat %f dist %f) \n", row[0].D(), col[0].D(), longitude[0].D(),latitude[0].D(),distance[0].D());
#endif
Halcon::gen_circle(reg, row, col, 100);
Halcon::convert_pose_type(poseout, "Rp+T", "abg", "point", &poserefabg);
camroll = - (((poserefabg[5].D()) / 360) * 2 * M_PI);
double dlong = pm->m_longitudeMin * fraction; /*model->GetShapeModel3dParams((*paramNameList)[0].S())[0].D() * fraction;*/
double dlat = pm->m_latitudeMin * fraction; /*model->GetShapeModel3dParams((*paramNameList)[2].S())[0].D() * fraction;*/
double ddist = pm->m_distMin * fraction;; /*model->GetShapeModel3dParams((*paramNameList)[6].S())[0].D() * fraction;*/
(*paramList)[0] = longitude - dlong; /*long min*/
(*paramList)[1] = longitude + dlong; /*long max*/
(*paramList)[2] = latitude - dlat; /*lat min*/
(*paramList)[3] = latitude + dlat; /*lat max*/
(*paramList)[4] = pm->m_camRollMin; /*model->GetShapeModel3dParams((*paramNameList)[4].S()); cam roll min*/
(*paramList)[5] = pm->m_camRollMax; /*model->GetShapeModel3dParams((*paramNameList)[5].S()); cam roll max*/
(*paramList)[6] = distance - ddist; /*dist min*/
(*paramList)[7] = distance + ddist; /*dist max*/
}
/**
* Test a pose if it is inside the search space.
*/
bool CheckPose(Halcon::HTuple pose, ShapeModelParamSet* pm, Hlong model)
{
try
{
Halcon::HTuple poseout, hommat3d, hommat3dInv, poserefabg, longitude, latitude, distance, camroll;
/* generate Tuple with the pose */
/* TOCHECK: what happens here*/
Halcon::trans_pose_shape_model_3d(model,pose, "model_to_ref", &poseout);
/* Invert the pose*/
Halcon::pose_to_hom_mat3d(poseout, &hommat3d);
Halcon::hom_mat3d_invert(hommat3d, &hommat3dInv);
Halcon::convert_point_3d_cart_to_spher(hommat3dInv[3].D(), hommat3dInv[7].D(),hommat3dInv[11].D(), "-y", "-z", &longitude, &latitude, &distance);
/* Coordinates for region */
Halcon::convert_pose_type(poseout, "Rp+T", "abg", "point", &poserefabg);
camroll = - (((poserefabg[5].D()) / 360) * 2 * M_PI);
if(/*pm->m_longitudeMin < longitude + 0.05 &&
pm->m_longitudeMax > longitude - 0.05 &&
pm->m_latitudeMin < latitude + 0.05 &&
pm->m_latitudeMax > latitude - 0.05 && */
pm->m_distMin < distance + 0.1&&
pm->m_distMax > distance - 0.1 /*&&
pm->m_camRollMin < camroll + 0.3 &&
pm->m_camRollMax > camroll - 0.3*/)
return true;
return false;
}
catch(...)
{
printf("Check Pose failed,\n");
return true;
}
}
//
// Methods
//
int ShapeBased3D::FindBestSupportedMatch(int &numOfObjects, std::vector<std::vector< RelPose*> > poses, std::vector<double> quality)
{
double max_quali = -1.0;
int max_index = 0;
//int numOfObjectsLeft = numOfObjects;
for(unsigned int i = 0; i < quality.size(); i++)
{
if(quality[i] > max_quali)
{
if(poses[i].size() > 0)
{
max_quali = quality[i];
max_index = i;
/**TODO check hypothesis by overlapping with others*/
}
}
}
return max_index;
}
std::vector<RelPose*> ShapeBased3D::PerformForAll(Image* img, RelPose* camPose,Calibration* calib, RelPose* lastKnownPose, Signature& object, int &numOfObjects, double& qualityMeasure)
{
double max_eval = 0.0;
double max_initlevel = 0.0;
ShapeModel* shape = NULL;
std::vector< std::vector<RelPose*> > result;
std::vector< double > quality;
int i = 0;
while((shape = (ShapeModel*)object.GetElement(i++, DESCRIPTOR_SHAPE )) != NULL)
{
if(max_eval + max_initlevel < shape->GetQuality() + shape->m_initializationLevel)
{
max_eval = shape->GetQuality();
max_initlevel = shape->m_initializationLevel;
}
}
max_eval -= 0.1;
max_initlevel -= 0.1;
printf("Level to execute set to\neval: %f\ninit %f\n", max_eval, max_initlevel);
i = 0;
while((shape = (ShapeModel*)object.GetElement(i, DESCRIPTOR_SHAPE )) != NULL)
{
if(max_eval < shape->GetQuality() && max_initlevel < shape->m_initializationLevel )
{
try
{
int numOfObjectsInner = numOfObjects;
double qualityInner = qualityMeasure;
std::vector<RelPose*> vec = Inner(img, camPose, calib, lastKnownPose, object, numOfObjectsInner, qualityInner, i);
result.push_back(vec);
quality.push_back(qualityInner);
shape->m_showNow = false;
}
catch(const char* text)
{
shape->Evaluate(-1, 1.0);
printf("ShapeBased3D::PerformForAll: Error in one of the models: %s\n", text);
}
catch(Halcon::HException ex)
{
shape->Evaluate(-1, 1.0);
printf("ShapeBased3D::PerformForAll: Error in one of the models: %s\n", ex.message);
}
catch(...)
{
shape->Evaluate(-1, 1.0);
printf("ShapeBased3D::PerformForAll: Error in one of the models.\n");
}
}
i++;
}
int index_best = FindBestSupportedMatch(numOfObjects, result, quality);
#ifdef _DEBUG
printf("ShapeBased3D: Selected match of model %d as the best\n", index_best);
#endif
shape = ((ShapeModel*)object.GetElement(index_best, DESCRIPTOR_SHAPE ));
if(shape != NULL)
{
shape->m_showNow = true;
if(shape->m_initializationLevel < 0.3)
{
SupportingPlaneDetector detector;
double qualPlane = qualityMeasure;
int numOfObjectsInner = numOfObjects;
/**TODO incooperate usage of index*/
#ifdef _DEBUG
printf("ShapeBased3D: Trying to improve the Match (bad init Value: %f ) by projecting it on a supporting plane\n Searching...\n", shape->m_initializationLevel);
#endif
std::vector<RelPose*> poses = detector.Inner(img, camPose, calib, lastKnownPose, object, numOfObjectsInner, qualPlane, 0);
if(poses.size() > 0)
{
#ifdef _DEBUG
printf("Found a supporting plane\n");
#endif
/**TODO incooperate usage of index*/
if(result.size() != 0 && result[index_best].size() > 0)
{
shape->IntersectWithSupportingPlane(poses[0], result[index_best][0], camPose, calib);
}
}
}
}
if(result.size() == 0 || shape == NULL)
return std::vector<RelPose*>();
numOfObjects = result.size();
qualityMeasure = quality[index_best];
return result[index_best];
}
std::vector<RelPose*> ShapeBased3D::Perform(std::vector<Sensor*> sensors, RelPose* lastKnownPose_in, Signature& object, int &numOfObjects, double& qualityMeasure)
{
std::vector<RelPose*> result;
printf("GetFirstCam");
Camera* cam = Camera::GetFirstCamera(sensors);
#ifdef _DEBUG
printf("Got Camera: %s\n", cam != NULL ? cam->GetName().c_str() : "None");
#endif // _DEBUG
try
{
if(cam != NULL)
{
Calibration* calib = &(cam->m_calibration);
Image* img = cam->GetImage(-1);
RelPose* camPose = img->GetPose();
RelPose* lastKnownPose = RelPoseFactory::GetRelPose(lastKnownPose_in->m_uniqueID, camPose->m_uniqueID);
if(object.CountElems() > 1)
{
result = PerformForAll(img, camPose, calib, lastKnownPose, object, numOfObjects, qualityMeasure);
}
else
{
if(img != NULL && camPose != NULL)
result = Inner(img, camPose, calib, lastKnownPose, object, numOfObjects, qualityMeasure);
}
RelPoseFactory::FreeRelPose(&lastKnownPose);
}
else
{
numOfObjects = 0;
qualityMeasure = 0.0;
}
}
catch(const char *text)
{
/** If the model is not too small or too big in one of the views it might be good to check in another view*/
ROS_INFO("cop: ShapeBased3D has most probably selected the wrong sensor (%s), trying again with a different\n", cam->GetSensorID().c_str());
int num_cam = 0;
cam = NULL;
for(std::vector<Sensor*>::const_iterator it = sensors.begin(); it != sensors.end(); it++)
{
if((*it)->IsCamera())
{
if(num_cam++ > 1)
{
cam = (Camera*)(*it);
}
}
}
if(cam != NULL)
{
Calibration* calib = &(cam->m_calibration);
Image* img = cam->GetImage(-1);
RelPose* camPose = img->GetPose();
RelPose* lastKnownPose = RelPoseFactory::GetRelPose(lastKnownPose_in->m_uniqueID, camPose->m_uniqueID);
if(object.CountElems() > 1)
{
result = PerformForAll(img, camPose, calib, lastKnownPose, object, numOfObjects, qualityMeasure);
}
else
{
if(img != NULL && camPose != NULL)
result = Inner(img, camPose, calib, lastKnownPose, object, numOfObjects, qualityMeasure);
}
RelPoseFactory::FreeRelPose(&lastKnownPose);
}
else
{
numOfObjects = 0;
qualityMeasure = 0.0;
}
}
return result;
}
std::vector<RelPose*> ShapeBased3D::Inner(Image* img, RelPose* camPose,Calibration* calib, RelPose* lastKnownPose, Signature& object, int &numOfObjects, double& qualityMeasure, int i)
{
std::vector<RelPose*> result;
if(img->GetType() == ReadingType_HalconImage)
{
HTuple ViewPose, pose, CovPose, Score;
/*printf("Get Shape Model\n");*/
ShapeModel* sm = (ShapeModel*)(object.GetElement(i, DESCRIPTOR_SHAPE ));
if(sm == NULL)
{
printf("Shape Model not found\n");
return result;
}
#ifdef _DEBUG
/* RelPoseHTuple::Print(lastKnownPose);*/
#endif
bool trackPossible = TrackingPossible(*img, object, lastKnownPose);
#ifdef _DEBUG
printf("TrackingPossible result: %s\n", trackPossible ? "true" : "false");
#endif
trackPossible = false; /*TODO debug tracking*/
if(!trackPossible)
{
sm->SetShapeModelParamSet(lastKnownPose, calib);
}
ShapeModelParamSet* pm = sm->GetParamSet();
/*sm->m_showNow = true;
sm->Show(lastKnownPose, NULL);*/
double scale;
long model = sm->GetShapeModel(scale);
if(model == -1)
{
printf("BigProblem with shape models\n");
}
else
{
/*printf("Start Shape model detection\n");*/
qualityMeasure = 0.0;
Halcon::HTuple pointer, t, w, h;
Halcon::Hobject* obj = img->GetHImage();
Halcon::get_image_pointer1(*obj, &pointer, &t, &w, &h);
if(scale != 1.0)
{
Halcon::Hobject* zoomed = new Halcon::Hobject();
Halcon::zoom_image_size(*obj, zoomed, (int)(w[0].I()*scale), (int)(h[0].I()*scale), "constant");
obj = zoomed;
}
else
{
/*if(w != calib->m_width)
printf("nix gut");
Halcon::HTuple tup;
Halcon::count_channels(*obj, &tup);
if(tup[0].I() == 3)
{
Halcon::rgb1_to_gray(*obj, obj);
printf("RGB > Gray\n");
}*/
}
Halcon::get_image_pointer1(*obj, &pointer, &t, &w, &h);
(*m_paramList)[8] = numOfObjects;
if(trackPossible)
{
Halcon::Hobject region;
GuidedPoseRestiction(m_paramList, m_paramNameList, model, 0.1, object.GetObjectPose(), calib->CamParam(scale),®ion, pm);
/*Halcon::reduce_domain(*obj, region, obj);*/
}
else
{
/* Restriction of Search array (TODO derive it from estimated position)*/
(*m_paramList)[0] = pm->m_longitudeMin;/*long min*/
(*m_paramList)[1] = pm->m_longitudeMax;/*model->GetShapeModel3dParams((*m_paramNameList)[1].S()) * Partly; *long max*/
(*m_paramList)[2] = pm->m_latitudeMin;/*model->GetShapeModel3dParams((*m_paramNameList)[2].S()) * Partly; *lat min*/
(*m_paramList)[3] = pm->m_latitudeMax;/*model->GetShapeModel3dParams((*m_paramNameList)[3].S()) * Partly; *lat max*/
(*m_paramList)[4] = pm->m_camRollMin;/*model->GetShapeModel3dParams((*m_paramNameList)[4].S()); *cam roll min*/
(*m_paramList)[5] = pm->m_camRollMax;/*model->GetShapeModel3dParams((*m_paramNameList)[5].S()); *cam roll max*/
(*m_paramList)[6] = pm->m_distMin;/*model->GetShapeModel3dParams((*m_paramNameList)[6].S()); *dist min*/
(*m_paramList)[7] = pm->m_distMax;/*model->GetShapeModel3dParams((*m_paramNameList)[7].S()); *dist max*/
}
#ifdef _DEBUG
printf("Parameter for detection:\n%f %f // %f %f \n %f %f // %f %f\n", /*long min:*/(*m_paramList)[0].D(),
/*long max:*/(*m_paramList)[1].D(),
/*lat min:*/(*m_paramList)[2].D(),
/*lat max:*/(*m_paramList)[3].D(),
/*cam roll min:*/(*m_paramList)[4].D(),
/*cam roll max:*/(*m_paramList)[5].D(),
/*dist min:*/(*m_paramList)[6].D(),
/*dist max:*/(*m_paramList)[7].D());
//printf("Run FindShapeModel with minscore: %f \nlevels %d\ngreediness: %f\n", minScore, level, m_greediness);
#endif
try
{
if(pm->m_region != NULL)
{
/*assert(pm->m_region->GetSize() > 0);*/
HTuple tuple_temp1,tuple_temp2, empty_t;
get_shape_model_3d_params(model, (*m_paramNameList)[0].S(), &tuple_temp1);
get_shape_model_3d_params(model, (*m_paramNameList)[1].S(), &tuple_temp2);
#ifdef _DEBUG
printf("Start search Model: %ld . lonmin %f lonmax %f (minscore %f)\n", model, tuple_temp1[0].D(),tuple_temp2[0].D(), m_minScore);
#endif
Hobject img_tmp;
reduce_domain(*obj, pm->m_region->GetRegion(scale), &img_tmp);
find_shape_model_3d(img_tmp, model, /*< Image here*/
m_minScore, m_greediness, m_levels, /*< Min Score, Greediness, Levels*/
*m_paramNameList, *m_paramList, /*< Generic Params (gp), gp Values*/
&pose, &CovPose, &Score);/*< Cov,Score */
}
else
{
/*Halcon::HTuple level(2, 5);*/
/* level[1] = 3;*/
#ifdef _DEBUG
printf("Start search Model: %ld .\n", model);
#endif
find_shape_model_3d(*obj, model, /*< Image here*/
m_minScore, m_greediness, m_levels/*level*/, /*< Min Score, Greediness, Levels*/
*m_paramNameList, *m_paramList, /*< Generic Params (gp), gp Values*/
&pose, &CovPose, &Score);/*< Cov,Score */
}
}
catch(Halcon::HException ex)
{
printf("Finding failed: %s (img %d, %d)\n", ex.message, w[0].I(), h[0].I());
}
#ifdef _DEBUG
printf("Finished detection with %ld object%s found\n", Score.Num(), Score.Num()==1?"":"s");
#endif
if(Score.Num() > 0)
{
#ifdef _DEBUG
printf("Found %ld objects with max score %f\nPose: %f,%f,%f, // %f,%f,%f // %d\n", Score.Num(), Score[0].D(), pose[0].D(), pose[1].D(), pose[2].D(), pose[3].D(), pose[4].D(), pose[5].D(), pose[6].I());
#endif
qualityMeasure = Score[0].D();
numOfObjects = Score.Num();
HTuple pose_sel, cov_sel;
for(int i = 0; i < Score.Num(); i++)
{
tuple_select_range(pose, 0 + 7*i, 6 + 7*i, &pose_sel);
tuple_select_range(CovPose, 0+ 6*i, 5+ 6*i, &cov_sel);
if(CheckPose(pose_sel, pm, model))
{
if(false && object.GetObjectPose() != NULL && i == 0 && object.GetObjectPose()->m_uniqueID!=ID_WORLD)
{
result.push_back(RelPoseHTuple::FRelPose(pose_sel, cov_sel, camPose, object.GetObjectPose()->m_uniqueID));
result.back()->m_qualityMeasure = Score[i].D();
}
else
{
result.push_back(RelPoseHTuple::FRelPose(pose_sel, cov_sel, camPose));
result.back()->m_qualityMeasure = Score[i].D();
}
}
else
{
numOfObjects --;
/*qualityMeasure -= Score[i].D();*/
#ifdef _DEBUG
printf("One object out of search space! Removed\n");
#endif
}
}
if(numOfObjects > 0)
{
sm->SetLastMatchedImage(img, result[0]);
#ifdef _DEBUG
printf("Return from inner of ShapeBased3D (success)\n");
#endif
}
img->Free();
}
else
{
numOfObjects = 0;
#ifdef _DEBUG
printf("Return from inner of ShapeBased3D (no match)\n");
#endif
}
return result;
}
}
img->Free();
return result;
}
double ShapeBased3D::CheckSignature(const Signature& object, const std::vector<Sensor*> &sensors)
{
//TODO
printf("ShapeBased3D::CheckSignature: Obj %ld, num elems %ld\n", object.m_ID, object.CountElems());
if(object.GetElement(0,DESCRIPTOR_SHAPE) != NULL)
return 1.0;
else
return 0.0;
}
// Accessor methods
//
// Other methods
//
| [
"[email protected]"
] | |
c0525a58aad0d65d27f19046d722f3f60bf0db96 | 7954784bd51a7279cc7e90540dad3e3d1d9025f9 | /robot_setup_tf/src/tf_broadcaster.cpp | 2bc93dcd8c86f7e2fe8835c6dd7238e6c9f61e93 | [] | no_license | h2r/CartographerKinectTurtlebot | 2a490ac4a44d127ae4e06585ac56ffb01323e0dd | 0015c7588b017da36317dd8267d4d8b0c8ad01c9 | refs/heads/master | 2020-12-03T04:10:48.857744 | 2017-08-11T21:01:42 | 2017-08-11T21:01:42 | 95,825,205 | 3 | 2 | null | 2017-08-01T17:52:59 | 2017-06-29T22:26:40 | CMake | UTF-8 | C++ | false | false | 519 | cpp | #include <ros/ros.h>
#include <tf/transform_broadcaster.h>
int main(int argc, char** argv){
ros::init(argc, argv, "robot_tf_publisher");
ros::NodeHandle n;
ros::Rate r(100);
tf::TransformBroadcaster broadcaster;
while(n.ok()){
broadcaster.sendTransform(
tf::StampedTransform(
tf::Transform(tf::Quaternion(0, 0, 0, 1), tf::Vector3(0.1, 0.0, 0.2)),
ros::Time::now(),"base_link", "base_laser"));
r.sleep();
}
}
| [
"[email protected]"
] | |
892da8b1815ce11037e7ce66f735c2a36728af75 | 9c0fef3512bcc25341039942d45645f527b9c514 | /PAT/27 9OJ_1019.cpp | 59410cf2d28be4c54d0d8684a53a1637669dc676 | [] | no_license | KeyOfSpectator/PAT | b34fb20244b8e741d3d7a5550ea4e4f325e8fac1 | d7ce62ba39f6070ee15a262527bdbc3f5edfbbcc | refs/heads/master | 2021-01-13T02:30:10.683220 | 2015-12-22T13:14:08 | 2015-12-22T13:14:08 | 37,360,646 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,918 | cpp | ///* WA */
//
////
//// 27 9OJ_1019.cpp
//// PAT
////
//// Created by 冯诗淳 on 15/8/25.
//// Copyright (c) 2015年 KeyOfSpectator. All rights reserved.
////
//
//#include <stdio.h>
////#include <string.h>
//#include <stack>
//using namespace std;
//
//char str[210];
//stack<double> num_s;
//// + 1 - 2 * 3 / 4
//stack<int> op_s;
//
//int mat[][5] = {
// 1 , 0 , 0 , 0 , 0,
// 1 , 0 , 0 , 0 , 0,
// 1 , 1 , 1 , 0 , 0,
// 1 , 1 , 1 , 0 , 0,
//};
//
//void getOP( bool &isOP , int &opNum , int &index){
// if(index == 0 && op_s.empty() == true){
// isOP = true;
// opNum = 0;
// return;
// }
// if(str[index]==0){
// isOP = true;
// opNum = 0;
// return;
// }
// if(str[index]>='0' && str[index]<='9'){
// isOP = false;
// }
// else{
// isOP = true;
// if(str[index] == '+')
// opNum = 1;
// else if(str[index] == '-')
// opNum = 2;
// else if(str[index] == '*')
// opNum = 3;
// else if(str[index] == '/')
// opNum = 4;
// index += 2;
// return;
// }
// // num
// opNum = 0;
// for( ; str[index]!=' ' && str[index]!=0 ; index++){ // str[] = 0 str[] = '0'
// opNum *=10 ;
// opNum += str[index] - '0';
// }
// if(str[index] == ' ')
// index++;
// return;
//
//}
//
//int main(){
// freopen("/Users/KeyOfSpectator/input", "r", stdin);
// while(gets(str)){
// bool isOP ; int opNum , index = 0;
// if(str[0] == '0' && str[1] == 0) break;
// while(num_s.empty()==false) num_s.pop();
// while(op_s.empty()==false) op_s.pop();
// while(true){
// getOP(isOP , opNum , index);
// if(isOP == false){
// num_s.push((double)opNum);
// }
// else{
// double tmp;
// if(op_s.empty() == true || mat[opNum][op_s.top()] == 1){
// op_s.push(opNum);
// }
// else{
// while(mat[opNum][op_s.top()] == 0){
// int op_tmp = op_s.top();
// op_s.pop();
// double b = num_s.top();
// num_s.pop();
// double a = num_s.top();
// num_s.pop();
// if(op_tmp == 1) tmp = a+b;
// else if(op_tmp == 2) tmp = a-b;
// else if(op_tmp == 3) tmp = a*b;
// else tmp = a/b;
// num_s.push(tmp);
// }
// op_s.push(opNum); // ? !
// }
// }
// if(op_s.size() == 2 && op_s.top() == 0) break;
//
// }
// printf("%.2f\n" , num_s.top());
//
// }
//
//
// return 0;
//} | [
"[email protected]"
] | |
e13b4f235988d1dd7805d4cd0e5a6d6ec51882b6 | 0ddeb8332191894304924217751f346889c890cb | /rplidar_test/sdk/app/simple_grabber/main.cpp | d5499770694c44c65c7516fba4e7a6700e829883 | [] | no_license | koushireo/CG-1112-02-01-02-ALEX | 3018f27f7cd1df724898b58dc144f3758ecb2e06 | b680458f4b457db87d7554bbf8c0a620390d31f5 | refs/heads/master | 2020-04-29T11:23:19.669368 | 2019-04-17T13:40:20 | 2019-04-17T13:40:20 | 176,095,769 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,943 | cpp | /*
* RPLIDAR
* Simple Data Grabber Demo App
*
* Copyright (c) 2009 - 2014 RoboPeak Team
* http://www.robopeak.com
* Copyright (c) 2014 - 2016 Shanghai Slamtec Co., Ltd.
* http://www.slamtec.com
*
*/
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <ctime>
#include "rplidar.h" //RPLIDAR standard sdk, all-in-one header
#ifndef _countof
#define _countof(_Array) (int)(sizeof(_Array) / sizeof(_Array[0]))
#endif
#ifdef _WIN32
#include <Windows.h>
#define delay(x) ::Sleep(x)
#else
#include <unistd.h>
static inline void delay(_word_size_t ms){
while (ms>=1000){
usleep(1000*1000);
ms-=1000;
};
if (ms!=0)
usleep(ms*1000);
}
#endif
using namespace rp::standalone::rplidar;
void print_usage(int argc, const char * argv[])
{
printf("Simple LIDAR data grabber for RPLIDAR.\n"
"Version: "RPLIDAR_SDK_VERSION"\n"
"Usage:\n"
"%s <com port> [baudrate]\n"
"The default baudrate is 115200. Please refer to the datasheet for details.\n"
, argv[0]);
}
void plot_histogram(rplidar_response_measurement_node_t * nodes, size_t count)
{
const int BARCOUNT = 75;
const int MAXBARHEIGHT = 20;
const float ANGLESCALE = 360.0f/BARCOUNT;
float histogram[BARCOUNT];
for (int pos = 0; pos < _countof(histogram); ++pos) {
histogram[pos] = 0.0f;
}
float max_val = 0;
for (int pos =0 ; pos < (int)count; ++pos) {
int int_deg = (int)((nodes[pos].angle_q6_checkbit >> RPLIDAR_RESP_MEASUREMENT_ANGLE_SHIFT)/64.0f/ANGLESCALE);
if (int_deg >= BARCOUNT) int_deg = 0;
float cachedd = histogram[int_deg];
if (cachedd == 0.0f ) {
cachedd = nodes[pos].distance_q2/4.0f;
} else {
cachedd = (nodes[pos].distance_q2/4.0f + cachedd)/2.0f;
}
if (cachedd > max_val) max_val = cachedd;
histogram[int_deg] = cachedd;
}
for (int height = 0; height < MAXBARHEIGHT; ++height) {
float threshold_h = (MAXBARHEIGHT - height - 1) * (max_val/MAXBARHEIGHT);
for (int xpos = 0; xpos < BARCOUNT; ++xpos) {
if (histogram[xpos] >= threshold_h) {
putc('*', stdout);
}else {
putc(' ', stdout);
}
}
printf("\n");
}
for (int xpos = 0; xpos < BARCOUNT; ++xpos) {
putc('-', stdout);
}
printf("\n");
}
u_result capture_and_display(RPlidarDriver * drv)
{
u_result ans;
while(true){
rplidar_response_measurement_node_t nodes[360*2];
size_t count = _countof(nodes);
//printf("waiting for data...\n");
// fetech extactly one 0-360 degrees' scan
ans = drv->grabScanData(nodes, count);
if (IS_OK(ans) || ans == RESULT_OPERATION_TIMEOUT) {
drv->ascendScanData(nodes, count);
//plot_histogram(nodes, count);
//printf("Do you want to see all the data? (y/n) ");
//int key = getchar();
//if (key == 'Y' || key == 'y') {
printf(">");
for (int pos = 0; pos < (int)count ; ++pos) {
float raw_angle = ((nodes[pos].angle_q6_checkbit >> RPLIDAR_RESP_MEASUREMENT_ANGLE_SHIFT)/64.0f);
printf("t %03.2f d %08.2f \n",
/*nodes[pos].sync_quality & RPLIDAR_RESP_MEASUREMENT_SYNCBIT) ?" ":" ",*/
raw_angle,
nodes[pos].distance_q2/4.0f);
}
//}
} else {
printf("error code: %x\n", ans);
}
}
return ans;
}
int main(int argc, const char * argv[]) {
const char * opt_com_path = NULL;
_u32 opt_com_baudrate = 115200;
u_result op_result;
if (argc < 2) {
print_usage(argc, argv);
return -1;
}
opt_com_path = argv[1];
if (argc>2) opt_com_baudrate = strtoul(argv[2], NULL, 10);
// create the driver instance
RPlidarDriver * drv = RPlidarDriver::CreateDriver(RPlidarDriver::DRIVER_TYPE_SERIALPORT);
if (!drv) {
fprintf(stderr, "insufficent memory, exit\n");
exit(-2);
}
rplidar_response_device_health_t healthinfo;
rplidar_response_device_info_t devinfo;
do {
// try to connect
if (IS_FAIL(drv->connect(opt_com_path, opt_com_baudrate))) {
fprintf(stderr, "Error, cannot bind to the specified serial port %s.\n"
, opt_com_path);
break;
}
// retrieving the device info
////////////////////////////////////////
op_result = drv->getDeviceInfo(devinfo);
if (IS_FAIL(op_result)) {
if (op_result == RESULT_OPERATION_TIMEOUT) {
// you can check the detailed failure reason
fprintf(stderr, "Error, operation time out.\n");
} else {
fprintf(stderr, "Error, unexpected error, code: %x\n", op_result);
// other unexpected result
}
break;
}
// print out the device serial number, firmware and hardware version number..
printf("RPLIDAR S/N: ");
for (int pos = 0; pos < 16 ;++pos) {
printf("%02X", devinfo.serialnum[pos]);
}
printf("\n"
"Version: "RPLIDAR_SDK_VERSION"\n"
"Firmware Ver: %d.%02d\n"
"Hardware Rev: %d\n"
, devinfo.firmware_version>>8
, devinfo.firmware_version & 0xFF
, (int)devinfo.hardware_version);
// check the device health
////////////////////////////////////////
op_result = drv->getHealth(healthinfo);
if (IS_OK(op_result)) { // the macro IS_OK is the preperred way to judge whether the operation is succeed.
printf("RPLidar health status : ");
switch (healthinfo.status) {
case RPLIDAR_STATUS_OK:
printf("OK.");
break;
case RPLIDAR_STATUS_WARNING:
printf("Warning.");
break;
case RPLIDAR_STATUS_ERROR:
printf("Error.");
break;
}
printf(" (errorcode: %d)\n", healthinfo.error_code);
} else {
fprintf(stderr, "Error, cannot retrieve the lidar health code: %x\n", op_result);
break;
}
if (healthinfo.status == RPLIDAR_STATUS_ERROR) {
fprintf(stderr, "Error, rplidar internal error detected. Please reboot the device to retry.\n");
// enable the following code if you want rplidar to be reboot by software
// drv->reset();
break;
}
drv->startMotor();
// take only one 360 deg scan and display the result as a histogram
////////////////////////////////////////////////////////////////////////////////
if (IS_FAIL(drv->startScan( /* true */ ))) // you can force rplidar to perform scan operation regardless whether the motor is rotating
{
fprintf(stderr, "Error, cannot start the scan operation.\n");
break;
}
if (IS_FAIL(capture_and_display(drv))) {
fprintf(stderr, "Error, cannot grab scan data.\n");
break;
}
} while(0);
drv->stop();
drv->stopMotor();
RPlidarDriver::DisposeDriver(drv);
return 0;
}
| [
"[email protected]"
] | |
231f660b9dc9225d21508bd92fd05245e8038139 | 464a6fee4196ed46b197be6eefb3fc6135e1ac04 | /src/cam/cam.cpp | 5e25942523b978aabc7a2fe09ac493e8eff81946 | [] | no_license | WainDing/RKModules | 50a6b48738b4b497007e861835f0e0d2c7712c92 | a70bd9b668a3f8aa520ca4d482ada198e989a6cf | refs/heads/master | 2020-03-21T01:46:09.191409 | 2018-05-28T03:41:19 | 2018-05-28T03:41:19 | 137,961,305 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,644 | cpp | #include "cam.h"
#include "log.h"
#include <fcntl.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
RKMediaCam::RKMediaCam() {
}
RKMediaCam::~RKMediaCam() {
}
int RKMediaCam::Init(const char *dev, unsigned int v4l2Fmt, int w, int h) {
int ret =0;
int i = 0;
struct v4l2_format fmt;
struct v4l2_capability cap;
struct v4l2_requestbuffers req_bufs;
enum v4l2_buf_type type;
_w = w;
_h = h;
_fd = open(dev, O_RDWR, 0);
if (_fd == -1) {
log("cam", "failed to open dev %s because %d:%s", dev, errno, strerror(errno));
return -1;
}
ret = ioctl(_fd, VIDIOC_QUERYCAP, &cap);
if (ret == -1) {
log("cam", "dev %s isn't v4l2 device", dev);
return -1;
}
if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) {
log("cam", "dev %s don't supprt video capture.\n", dev);
return -1;
}
if (!(cap.capabilities & V4L2_CAP_STREAMING)) {
log("cam", "dev %s don't support video stream.\n", dev);
return -1;
}
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
ret = ioctl(_fd, VIDIOC_G_FMT, &fmt);
if (ret == -1) {
log("cam", "dev %s failed to get video fmt", dev);
return -1;
}
fmt.fmt.pix.width = w;
fmt.fmt.pix.height = h;
fmt.fmt.pix.pixelformat = v4l2Fmt;
ret = ioctl(_fd, VIDIOC_S_FMT, &fmt);
if (ret == -1) {
log("cam", "dev %s failed to set video fmt", dev);
return -1;
}
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
ret = ioctl(_fd, VIDIOC_G_FMT, &fmt);
if (ret == -1) {
log("cam", "dev %s failed to get video fmt", dev);
return -1;
}
if (fmt.fmt.pix.pixelformat != v4l2Fmt ||
fmt.fmt.pix.width != _w ||
fmt.fmt.pix.height != _h) {
log("cam", "dev %s doesn't support fmt:%c%c%c%c w:%d h:%d",dev ,
fmt.fmt.pix.pixelformat & 0xff, (fmt.fmt.pix.pixelformat >> 8) & 0xff,
(fmt.fmt.pix.pixelformat >> 16) & 0xff, (fmt.fmt.pix.pixelformat >> 24) & 0xff, _w, _h);
return -1;
}
log("cam", "dev %s support fmt:%c%c%c%c w:%d h:%d", dev ,
fmt.fmt.pix.pixelformat & 0xff, (fmt.fmt.pix.pixelformat >> 8) & 0xff,
(fmt.fmt.pix.pixelformat >> 16) & 0xff, (fmt.fmt.pix.pixelformat >> 24) & 0xff, _w, _h);
memset(&req_bufs, 0, sizeof(req_bufs));
req_bufs.count = 10;
req_bufs.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
req_bufs.memory = V4L2_MEMORY_MMAP;
ret = ioctl(_fd, VIDIOC_REQBUFS, &req_bufs);
if (ret == -1) {
log("cam", "failed to req bufs because %d:%s", errno, strerror(errno));
return -1;
}
_bufList = (CameraBuf *)malloc(10 * sizeof(CameraBuf));
if (!_bufList) {
log("cam", "failed to malloc _bufList");
return -1;
}
for (i = 0; i < 10; i++) {
struct v4l2_buffer buf;
memset(&buf, 0, sizeof(buf));
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
buf.index = i;
ret = ioctl(_fd, VIDIOC_QUERYBUF, &buf);
if (ret == -1) {
log("cam", "failed to query buf because %d:%s", errno, strerror(errno));
return -1;
}
_bufList[i].dataLen = buf.length;
_bufList[i].data = mmap(NULL, buf.length,
PROT_READ|PROT_WRITE,
MAP_SHARED, _fd,
buf.m.offset);
if (_bufList[i].data == MAP_FAILED) {
log("cam", "failed to mmap v4l2 buf to use space");
return -1;
}
}
for (i = 0; i < 10; i++) {
struct v4l2_buffer buf;
memset(&buf, 0, sizeof(buf));
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
buf.index = i;
ret = ioctl(_fd, VIDIOC_QBUF, &buf);
if (ret == -1) {
log("cam", "failed to qbuf because %d:%s", errno, strerror(errno));
return -1;
}
}
type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
ret = ioctl(_fd, VIDIOC_STREAMON, &type);
if (ret == -1) {
log("cam", "failed to open cam stream on");
return -1;
}
return 0;
}
int RKMediaCam::Deinit() {
int ret = 0;
int i = 0;
enum v4l2_buf_type type;
type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
ret = ioctl(_fd, VIDIOC_STREAMOFF, &type);
if (ret == -1) {
log("cam", "failed to close cam stream off");
return -1;
}
for (i = 0; i < 10; i++) {
if (munmap(_bufList[i].data, _bufList[i].dataLen) == -1) {
log("cam", "failed to unmap v4l2buf because %d %s.\n", errno,
strerror(errno));
return -1;
}
}
free(_bufList);
close(_fd);
return 0;
}
int RKMediaCam::GetFrame(CameraBuf *buf) {
int ret = 0;
struct v4l2_buffer vbuf;
memset(&vbuf, 0, sizeof(vbuf));
vbuf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
vbuf.memory = V4L2_MEMORY_MMAP;
ret = ioctl(_fd, VIDIOC_DQBUF, &vbuf);
if (ret == -1) {
log("cam", "failed to dequeue buf from cam");
return -1;
}
buf->data = _bufList[vbuf.index].data;
buf->dataLen = _bufList[vbuf.index].dataLen;
buf->vbuf = vbuf;
buf->bufIndex = vbuf.index;
return 0;
}
int RKMediaCam::FreeFrame(CameraBuf *buf) {
int ret = 0;
ret = ioctl(_fd, VIDIOC_QBUF, &buf->vbuf);
if (ret == -1) {
log("cam", "failed to queue buf from cam");
return -1;
}
return 0;
}
| [
"tiger@ubuntu"
] | tiger@ubuntu |
c0a9637722d11bd024d592bbf164a428d389abd7 | 6319da5ded0bcd7341988ed9637ba27276e78d06 | /fcuRtti.h | 5cf20229e194f68941eeff44e55e5e1263b6ad57 | [] | no_license | asaiyuta/fuckinCodeUtills | 32ccccb20ac3e6c27ae6465971aa84f02743b0d5 | 0e196849fb43b9eedfcdecb54cb023726b44126c | refs/heads/master | 2021-01-20T04:25:44.973118 | 2017-04-28T09:34:22 | 2017-04-28T09:34:22 | 89,691,103 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 489 | h | #pragma once
#include <typeinfo>
#include <cxxabi.h>
#include <string>
#include <stdlib.h>
namespace fcu{
template<typename T>
static std::string easyTypename(const T& obj){
const std::type_info& id = typeid(obj);
int stat(0);
std::string nameBuffer;
char *name = abi::__cxa_demangle(id.name(),0,0,&stat);
if(name!=NULL) {
if(stat == 0) {
nameBuffer = name;
free(name);
return nameBuffer;
}
free(name);
}
return "unknown";
}
} | [
"[email protected]"
] | |
1a6a8190d1a9fd43210c4057f29259d4921346d4 | 5fd8a8e9f9388e78a9c960d99a20307df2d816e5 | /Samples/2.0/ApiUsage/MeshLod/MeshLod.cpp | d9285b90c353e7336bc4cbdef479f3bc6d63d9e8 | [
"MIT"
] | permissive | OGRECave/ogre-next | a24431628fd613497ae60c32713f990cc77597de | 205710277c274c71f256d81d6b16fc65268721d9 | refs/heads/master | 2023-08-31T21:08:04.001321 | 2023-08-14T20:49:48 | 2023-08-14T20:52:07 | 205,727,113 | 915 | 250 | NOASSERTION | 2023-09-03T23:40:49 | 2019-09-01T20:11:06 | C++ | UTF-8 | C++ | false | false | 3,229 | cpp |
#include "GraphicsSystem.h"
#include "MeshLodGameState.h"
#include "Compositor/OgreCompositorManager2.h"
#include "OgreCamera.h"
#include "OgreConfigFile.h"
#include "OgreRoot.h"
#include "OgreSceneManager.h"
#include "OgreWindow.h"
// Declares WinMain / main
#include "MainEntryPointHelper.h"
#include "System/Android/AndroidSystems.h"
#include "System/MainEntryPoints.h"
#if OGRE_PLATFORM != OGRE_PLATFORM_ANDROID
# if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
INT WINAPI WinMainApp( HINSTANCE hInst, HINSTANCE hPrevInstance, LPSTR strCmdLine, INT nCmdShow )
# else
int mainApp( int argc, const char *argv[] )
# endif
{
return Demo::MainEntryPoints::mainAppSingleThreaded( DEMO_MAIN_ENTRY_PARAMS );
}
#endif
namespace Demo
{
class MeshLodGraphicsSystem final : public GraphicsSystem
{
void setupResources() override
{
GraphicsSystem::setupResources();
Ogre::ConfigFile cf;
cf.load( AndroidSystems::openFile( mResourcePath + "resources2.cfg" ) );
Ogre::String dataFolder = cf.getSetting( "DoNotUseAsResource", "Hlms", "" );
if( dataFolder.empty() )
dataFolder = AndroidSystems::isAndroid() ? "/" : "./";
else if( *( dataFolder.end() - 1 ) != '/' )
dataFolder += "/";
Ogre::String dataFolderSinbad = dataFolder;
dataFolder += "2.0/scripts/materials/PbsMaterials";
addResourceLocation( dataFolder, getMediaReadArchiveType(), "General" );
dataFolderSinbad += "packs/Sinbad.zip";
addResourceLocation( dataFolderSinbad, "Zip", "General" );
}
public:
MeshLodGraphicsSystem( GameState *gameState ) : GraphicsSystem( gameState ) {}
};
void MainEntryPoints::createSystems( GameState **outGraphicsGameState,
GraphicsSystem **outGraphicsSystem,
GameState **outLogicGameState, LogicSystem **outLogicSystem )
{
MeshLodGameState *gfxGameState = new MeshLodGameState(
"Shows how to automatically generate LODs from an existing mesh.\n"
"The mesh must be in v1 format because the MeshLodGenerator Component\n"
"hasn't yet been ported to v2 interfaces\n"
"However meshes can be converted back and forth between v1 <-> v2\n"
"to get LOD generation.\n"
"Once LODs have been generated, LOD display can work in either v1 or v2 mode\n"
"The model you're looking right now is in v2 mode" );
GraphicsSystem *graphicsSystem = new MeshLodGraphicsSystem( gfxGameState );
gfxGameState->_notifyGraphicsSystem( graphicsSystem );
*outGraphicsGameState = gfxGameState;
*outGraphicsSystem = graphicsSystem;
}
void MainEntryPoints::destroySystems( GameState *graphicsGameState, GraphicsSystem *graphicsSystem,
GameState *logicGameState, LogicSystem *logicSystem )
{
delete graphicsSystem;
delete graphicsGameState;
}
const char *MainEntryPoints::getWindowTitle() { return "Automatic LOD Generation Sample"; }
} // namespace Demo
| [
"[email protected]"
] | |
2e2e5652b3a9b29fb84783589db03ab180905b3e | c2cf4f4aefadb1d4aca3fc4e010c9bcbe61af628 | /Exam/03.SummerInAugust/Main.cpp | 727c74632e0fe9f8caafb55299c06a9a80225b0f | [] | no_license | krasi070/CPlusPlus | 4b10afce58a276d24a6cda68cc4cdce6ed86ad12 | 34a4c3a01b05fe1fdb396c1dd49444c510892043 | refs/heads/master | 2020-04-06T07:07:11.027794 | 2016-09-08T15:46:15 | 2016-09-08T15:46:15 | 60,217,347 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,334 | cpp | // Name: Krasimir Balchev
// Username: krasi070
#include <iostream>
#include "HolidaySpot.h"
#include "Country.h"
int main()
{
HolidaySpot *holidaySpot1 = new HolidaySpot("HS1", "11 2 23 12", "Sand", "Ocean", 7, 4, 12000, 35, 67, 10, 12, 100);
HolidaySpot *holidaySpot2 = new HolidaySpot("HS2", "11 3 23 42", "Rock", "Sea", 5, 10, 123000, 57, 120, 5, 6, 10);
HolidaySpot *holidaySpot3 = new HolidaySpot("HS3", "11 4 13 22", "Sand", "Pool", 3, 9, 12500, 100, 34, 12, 12, 1);
HolidaySpot *holidaySpot4 = new HolidaySpot("HS4", "11 5 23 12", "Tiles", "Puddle", 10, 10, 1000000, 1000, 0, 13, 14, 1.5f);
HolidaySpot *holidaySpot5 = new HolidaySpot("HS5", "11 6 23 72", "Sand", "Sea", 5, 5, 6000, 42.45f, 83, 7, 5, 3.1f);
Country country = Country("Bulgaria", "lv.", 0.51f);
country.addHolidaySpot(std::shared_ptr<HolidaySpot>(holidaySpot1));
country.addHolidaySpot(std::shared_ptr<HolidaySpot>(holidaySpot2));
country.addHolidaySpot(std::shared_ptr<HolidaySpot>(holidaySpot3));
country.addHolidaySpot(std::shared_ptr<HolidaySpot>(holidaySpot4));
country.addHolidaySpot(std::shared_ptr<HolidaySpot>(holidaySpot5));
country.getHolidaySpot(10, 12, 100); // this line doesn't work when you test it but if you debug it, it works perfectly fine :o
country.removeHolidaySpotByName("HS4");
country.joinThreads();
return 0;
} | [
"[email protected]"
] | |
1c85bf7be317a3389413959bc950e23a2f69b4fd | cc40b9c79179b7bb59092792fcb6051a8b1f64fa | /11th_POI/wys.cpp | 1fc1ef8ee6952d72876d0540e7c2e6d59c417309 | [] | no_license | hungp2812/POI | 9f56e9f63311714621f1805827987a193185a4c0 | 90817aff09bcf3b3b88abd1ac0bd27f543f93d8b | refs/heads/master | 2023-02-20T00:53:39.292680 | 2021-01-24T16:09:47 | 2021-01-24T16:09:47 | 326,450,671 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,098 | cpp | /*
/+==================================================+\
//+--------------------------------------------------+\\
|.|\\...>>>>>>> Hollwo_Pelw(ass) 's code <<<<<<<...//|.|
\\+--------------------------------------------------+//
\+==================================================+/
*/
#include <bits/stdc++.h>
using namespace std;
// type
typedef long long ll;
typedef long double ld;
// pair
#define F first
#define S second
#define pii pair<int, int>
#define pll pair<ll, ll>
#define pdd pair<ld, ld>
// vector & !!?(string)
#define eb emplace_back
#define pb push_back
#define all(a) a.begin(), a.end()
#define rall(a) a.rbegin(), a.rend()
#define sz(a) a.size()
#define len(a) a.length()
// I/O
#define open(file, in, out) if (fopen(file in, "r")) { \
freopen(file in, "r", stdin); \
freopen(file out, "w", stdout); \
}
#define FAST_IO std::ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define setpre(n) fixed << setprecision(n)
bool endline = false;
template<class T>
istream& operator >> (istream& inp, vector<T>& v){
for (auto& it : v) inp >> it;
return inp;
}
template<class T>
ostream& operator << (ostream& out, vector<T>& v){
for (auto& it : v) out << it << (endline ? "\n" : " ");
return out;
}
template<class T, class U>
istream& operator >> (istream& inp, pair<T, U>& v){
inp >> v.F >> v.S;
return inp;
}
template<class T, class U>
ostream& operator << (ostream& out, pair<T, U>& v){
out << v.F << ' ' << v.S;
return out;
}
#define debug(x) cout << #x << " : " << endl << x << endl;
// geometry calculate
#define pi acos(-1.0)
#define g_sin(a) sin(a*pi/180)
#define g_cos(a) cos(a*pi/180)
#define g_tan(a) tan(a*pi/180)
// set val
#define ms0(a) memset(a, 0, sizeof(a));
#define ms1(a) memset(a, 1, sizeof(a));
#define msn1(a) memset(a, -1, sizeof(a));
#define msinf(a) memset(a, 0x3f3f3f, sizeof(a));
// constant
const int mod1 = 998244353, mod = 1e9 + 7;
const int MAXN = 2e5 + 5 , MAXM = 3e5 + 5;
const int inf = (1<<30)-1; const ll linf = 1e18;
// code
#define left node << 1, tl, tm
#define right node << 1 | 1, tm + 1, tr
//#define int long long
int n, st[MAXN << 2], lz[MAXN << 2];
void app(int node, int v){
st[node] += v;
lz[node] += v;
}
void push(int node){
app(node << 1, lz[node]);
app(node << 1 | 1, lz[node]);
lz[node] = 0;
}
void upd(int l, int r, int v, int node = 1, int tl = 1, int tr = 2e5){
if (l > tr || l > r || tl > r) return ;
if (l <= tl && tr <= r) {
app(node, v);
return ;
}
int tm = (tl + tr) >> 1;
push(node);
upd(l, r, v, left);
upd(l, r, v, right);
st[node] = max(st[node << 1], st[node << 1 | 1]);
}
struct sq {
int l, r, t, v;
sq(int _l, int _r, int _t, int _v) : l(_l), r(_r), t(_t), v(_v) {}
};
vector<sq> query;
void Solve() {
cin >> n;
for (int i = 1, q; i <= n; i++){
cin >> q;
vector<pii> a(q + 1);
for (int i = 0, x; i < q; i++){
cin >> x;
if (i & 1){
// y coordinate
a[i].S = a[(i + q - 1) % q].S = x;
}else{
// x coordinate
a[i].F = a[(i + q - 1) % q].F = x;
}
}
for (int i = 0; i < q; i++){
if (a[i].S == a[(i + 1) % q].S){
int v = 1, l = a[i].F, r = a[(i + 1) % q].F;
if (l > r) swap(l, r), v = -v;
query.eb(l, r, a[i].S, v);
}
}
}
vector <int> xx;
for (auto q : query){
xx.pb(q.l);
xx.pb(q.r);
}
sort(all(xx));
xx.resize(unique(all(xx)) - xx.begin());
for (auto &q : query){
q.l = lower_bound(all(xx), q.l) - xx.begin() + 1;
q.r = lower_bound(all(xx), q.r) - xx.begin() + 1;
}
sort(all(query), [](const sq & a, const sq & b){
return a.t < b.t;
});
int res = 0;
for (int i = 0; i < query.size(); ){
int j = i;
while(j < query.size() && query[i].t == query[j].t)
j ++;
for (int k = i; k < j; k++)
upd(query[k].l, query[k].r - 1, query[k].v);
res = max(res, st[1]);
i = j;
}
cout << res;
}
signed main(){
open("", ".inp", ".out");
FAST_IO; int TC = 1;
// cin >> TC;
while(TC--) Solve();
return 0;
}
/*
\/-=====>>><<<-------- DEBUG -------->>><<<=====-\/
/\.............................................../\
+====================== INP ======================+
+====================== OUT ======================+
+======================*****======================+
\/...............................................\/
/\-=====>>><<<--------= END =-------->>><<<=====-/\
*/ | [
"[email protected]"
] | |
eaf709163ebcaa5075a8286ce3f747504408222d | 29e6263d91ca9d262d8f3a58eb0831dd70c878f0 | /main/bt_app_av.cpp | 8f321b5bb5469c68844dd5c6e813fd27a815c95b | [] | no_license | drewandre/palette_firmware_esp32 | 6e0b39265e6c0518192e0a0a945fe7880b5da89c | afeb04a37eba5683ee3126fdb337ee9b4d619a94 | refs/heads/master | 2023-04-13T14:24:31.970184 | 2023-04-05T05:36:04 | 2023-04-05T05:36:04 | 248,081,889 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 11,754 | cpp | #include "bt_app_av.hpp"
const char *BT_AV_TAG = "BT_AV";
const char *BT_RC_TG_TAG = "RCTG";
const char *BT_RC_CT_TAG = "RCCT";
// AVRCP used transaction label
#define APP_RC_CT_TL_GET_CAPS (0)
#define APP_RC_CT_TL_GET_META_DATA (1)
#define APP_RC_CT_TL_RN_TRACK_CHANGE (2)
#define APP_RC_CT_TL_RN_PLAYBACK_CHANGE (3)
#define APP_RC_CT_TL_RN_PLAY_POS_CHANGE (4)
/* a2dp event handler */
static void bt_av_hdl_a2d_evt(uint16_t event, void *p_param);
/* avrc CT event handler */
static void bt_av_hdl_avrc_ct_evt(uint16_t event, void *p_param);
/* avrc TG event handler */
static void bt_av_hdl_avrc_tg_evt(uint16_t event, void *p_param);
static uint32_t s_pkt_cnt = 0;
static esp_a2d_audio_state_t s_audio_state = ESP_A2D_AUDIO_STATE_STOPPED;
static const char *s_a2d_conn_state_str[] = {"Disconnected", "Connecting", "Connected", "Disconnecting"};
static const char *s_a2d_audio_state_str[] = {"Suspended", "Stopped", "Started"};
static esp_avrc_rn_evt_cap_mask_t s_avrc_peer_rn_cap;
static _lock_t s_volume_lock;
// static xTaskHandle s_vcs_task_hdl = NULL;
static uint8_t s_volume = 0;
static bool s_volume_notify;
/* callback for A2DP sink */
void bt_app_a2d_cb(esp_a2d_cb_event_t event, esp_a2d_cb_param_t *param)
{
switch (event)
{
case ESP_A2D_CONNECTION_STATE_EVT:
case ESP_A2D_AUDIO_STATE_EVT:
case ESP_A2D_AUDIO_CFG_EVT:
{
bt_app_work_dispatch(bt_av_hdl_a2d_evt, event, param, sizeof(esp_a2d_cb_param_t), NULL);
break;
}
default:
ESP_LOGE(BT_AV_TAG, "Invalid A2DP event: %d", event);
break;
}
}
void bt_app_a2d_data_cb(const uint8_t *data, uint32_t len)
{
write_ringbuf(data, len);
copy_a2dp_buffer_to_audio_analysis_buffer(data, len);
}
void bt_app_alloc_meta_buffer(esp_avrc_ct_cb_param_t *param)
{
esp_avrc_ct_cb_param_t *rc = (esp_avrc_ct_cb_param_t *)(param);
uint8_t *attr_text = (uint8_t *)malloc(rc->meta_rsp.attr_length + 1);
memcpy(attr_text, rc->meta_rsp.attr_text, rc->meta_rsp.attr_length);
attr_text[rc->meta_rsp.attr_length] = 0;
rc->meta_rsp.attr_text = attr_text;
}
void bt_app_rc_ct_cb(esp_avrc_ct_cb_event_t event, esp_avrc_ct_cb_param_t *param)
{
switch (event)
{
case ESP_AVRC_CT_METADATA_RSP_EVT:
bt_app_alloc_meta_buffer(param);
/* fall through */
case ESP_AVRC_CT_CONNECTION_STATE_EVT:
case ESP_AVRC_CT_PASSTHROUGH_RSP_EVT:
case ESP_AVRC_CT_CHANGE_NOTIFY_EVT:
case ESP_AVRC_CT_REMOTE_FEATURES_EVT:
case ESP_AVRC_CT_GET_RN_CAPABILITIES_RSP_EVT:
{
bt_app_work_dispatch(bt_av_hdl_avrc_ct_evt, event, param, sizeof(esp_avrc_ct_cb_param_t), NULL);
break;
}
default:
ESP_LOGE(BT_RC_CT_TAG, "Invalid AVRC event: %d", event);
break;
}
}
void bt_app_rc_tg_cb(esp_avrc_tg_cb_event_t event, esp_avrc_tg_cb_param_t *param)
{
switch (event)
{
case ESP_AVRC_TG_CONNECTION_STATE_EVT:
case ESP_AVRC_TG_REMOTE_FEATURES_EVT:
case ESP_AVRC_TG_PASSTHROUGH_CMD_EVT:
case ESP_AVRC_TG_SET_ABSOLUTE_VOLUME_CMD_EVT:
case ESP_AVRC_TG_REGISTER_NOTIFICATION_EVT:
bt_app_work_dispatch(bt_av_hdl_avrc_tg_evt, event, param, sizeof(esp_avrc_tg_cb_param_t), NULL);
break;
default:
ESP_LOGE(BT_RC_TG_TAG, "Invalid AVRC event: %d", event);
break;
}
}
static void bt_av_hdl_a2d_evt(uint16_t event, void *p_param)
{
ESP_LOGD(BT_AV_TAG, "%s evt %d", __func__, event);
esp_a2d_cb_param_t *a2d = NULL;
switch (event)
{
case ESP_A2D_CONNECTION_STATE_EVT:
{
a2d = (esp_a2d_cb_param_t *)(p_param);
uint8_t *bda = a2d->conn_stat.remote_bda;
ESP_LOGI(BT_AV_TAG, "A2DP connection state: %s, [%02x:%02x:%02x:%02x:%02x:%02x]",
s_a2d_conn_state_str[a2d->conn_stat.state], bda[0], bda[1], bda[2], bda[3], bda[4], bda[5]);
if (a2d->conn_stat.state == ESP_A2D_CONNECTION_STATE_DISCONNECTED)
{
esp_bt_gap_set_scan_mode(ESP_BT_CONNECTABLE, ESP_BT_GENERAL_DISCOVERABLE);
bt_i2s_task_shut_down();
}
else if (a2d->conn_stat.state == ESP_A2D_CONNECTION_STATE_CONNECTED)
{
esp_bt_gap_set_scan_mode(ESP_BT_NON_CONNECTABLE, ESP_BT_NON_DISCOVERABLE);
bt_i2s_task_start_up();
}
break;
}
case ESP_A2D_AUDIO_STATE_EVT:
{
a2d = (esp_a2d_cb_param_t *)(p_param);
ESP_LOGI(BT_AV_TAG, "A2DP audio state: %s", s_a2d_audio_state_str[a2d->audio_stat.state]);
s_audio_state = a2d->audio_stat.state;
if (ESP_A2D_AUDIO_STATE_STARTED == a2d->audio_stat.state)
{
s_pkt_cnt = 0;
}
break;
}
case ESP_A2D_AUDIO_CFG_EVT:
{
a2d = (esp_a2d_cb_param_t *)(p_param);
ESP_LOGI(BT_AV_TAG, "A2DP audio stream configuration, codec type %d", a2d->audio_cfg.mcc.type);
// for now only SBC stream is supported
if (a2d->audio_cfg.mcc.type == ESP_A2D_MCT_SBC)
{
int sample_rate = 16000;
char oct0 = a2d->audio_cfg.mcc.cie.sbc[0];
if (oct0 & (0x01 << 6))
{
sample_rate = 32000;
}
else if (oct0 & (0x01 << 5))
{
sample_rate = 44100;
}
else if (oct0 & (0x01 << 4))
{
sample_rate = 48000;
}
i2s_set_clk(I2S_NUM_0, sample_rate, I2S_BITS_PER_SAMPLE_16BIT, I2S_CHANNEL_STEREO);
ESP_LOGI(BT_AV_TAG, "Configure audio player %x-%x-%x-%x",
a2d->audio_cfg.mcc.cie.sbc[0],
a2d->audio_cfg.mcc.cie.sbc[1],
a2d->audio_cfg.mcc.cie.sbc[2],
a2d->audio_cfg.mcc.cie.sbc[3]);
ESP_LOGI(BT_AV_TAG, "Audio player configured, sample rate=%d", sample_rate);
}
break;
}
default:
ESP_LOGE(BT_AV_TAG, "%s unhandled evt %d", __func__, event);
break;
}
}
static void bt_av_new_track(void)
{
// request metadata
uint8_t attr_mask = ESP_AVRC_MD_ATTR_TITLE | ESP_AVRC_MD_ATTR_ARTIST | ESP_AVRC_MD_ATTR_ALBUM | ESP_AVRC_MD_ATTR_GENRE;
esp_avrc_ct_send_metadata_cmd(APP_RC_CT_TL_GET_META_DATA, attr_mask);
// register notification if peer support the event_id
if (esp_avrc_rn_evt_bit_mask_operation(ESP_AVRC_BIT_MASK_OP_TEST, &s_avrc_peer_rn_cap,
ESP_AVRC_RN_TRACK_CHANGE))
{
esp_avrc_ct_send_register_notification_cmd(APP_RC_CT_TL_RN_TRACK_CHANGE, ESP_AVRC_RN_TRACK_CHANGE, 0);
}
}
static void bt_av_playback_changed(void)
{
if (esp_avrc_rn_evt_bit_mask_operation(ESP_AVRC_BIT_MASK_OP_TEST, &s_avrc_peer_rn_cap,
ESP_AVRC_RN_PLAY_STATUS_CHANGE))
{
esp_avrc_ct_send_register_notification_cmd(APP_RC_CT_TL_RN_PLAYBACK_CHANGE, ESP_AVRC_RN_PLAY_STATUS_CHANGE, 0);
}
}
static void bt_av_play_pos_changed(void)
{
if (esp_avrc_rn_evt_bit_mask_operation(ESP_AVRC_BIT_MASK_OP_TEST, &s_avrc_peer_rn_cap,
ESP_AVRC_RN_PLAY_POS_CHANGED))
{
esp_avrc_ct_send_register_notification_cmd(APP_RC_CT_TL_RN_PLAY_POS_CHANGE, ESP_AVRC_RN_PLAY_POS_CHANGED, 10);
}
}
void bt_av_notify_evt_handler(uint8_t event_id, esp_avrc_rn_param_t *event_parameter)
{
switch (event_id)
{
case ESP_AVRC_RN_TRACK_CHANGE:
bt_av_new_track();
break;
case ESP_AVRC_RN_PLAY_STATUS_CHANGE:
ESP_LOGI(BT_AV_TAG, "Playback status changed: 0x%x", event_parameter->playback);
bt_av_playback_changed();
break;
case ESP_AVRC_RN_PLAY_POS_CHANGED:
ESP_LOGI(BT_AV_TAG, "Play position changed: %d-ms", event_parameter->play_pos);
bt_av_play_pos_changed();
break;
}
}
static void bt_av_hdl_avrc_ct_evt(uint16_t event, void *p_param)
{
ESP_LOGD(BT_RC_CT_TAG, "%s evt %d", __func__, event);
esp_avrc_ct_cb_param_t *rc = (esp_avrc_ct_cb_param_t *)(p_param);
switch (event)
{
case ESP_AVRC_CT_CONNECTION_STATE_EVT:
{
uint8_t *bda = rc->conn_stat.remote_bda;
ESP_LOGI(BT_RC_CT_TAG, "AVRC conn_state evt: state %d, [%02x:%02x:%02x:%02x:%02x:%02x]",
rc->conn_stat.connected, bda[0], bda[1], bda[2], bda[3], bda[4], bda[5]);
if (rc->conn_stat.connected)
{
// get remote supported event_ids of peer AVRCP Target
esp_avrc_ct_send_get_rn_capabilities_cmd(APP_RC_CT_TL_GET_CAPS);
}
else
{
// clear peer notification capability record
s_avrc_peer_rn_cap.bits = 0;
}
break;
}
case ESP_AVRC_CT_PASSTHROUGH_RSP_EVT:
{
ESP_LOGI(BT_RC_CT_TAG, "AVRC passthrough rsp: key_code 0x%x, key_state %d", rc->psth_rsp.key_code, rc->psth_rsp.key_state);
break;
}
case ESP_AVRC_CT_METADATA_RSP_EVT:
{
ESP_LOGI(BT_RC_CT_TAG, "AVRC metadata rsp: attribute id 0x%x, %s", rc->meta_rsp.attr_id, rc->meta_rsp.attr_text);
free(rc->meta_rsp.attr_text);
break;
}
case ESP_AVRC_CT_CHANGE_NOTIFY_EVT:
{
ESP_LOGI(BT_RC_CT_TAG, "AVRC event notification: %d", rc->change_ntf.event_id);
bt_av_notify_evt_handler(rc->change_ntf.event_id, &rc->change_ntf.event_parameter);
break;
}
case ESP_AVRC_CT_REMOTE_FEATURES_EVT:
{
ESP_LOGI(BT_RC_CT_TAG, "AVRC remote features %x, TG features %x", rc->rmt_feats.feat_mask, rc->rmt_feats.tg_feat_flag);
break;
}
case ESP_AVRC_CT_GET_RN_CAPABILITIES_RSP_EVT:
{
ESP_LOGI(BT_RC_CT_TAG, "remote rn_cap: count %d, bitmask 0x%x", rc->get_rn_caps_rsp.cap_count,
rc->get_rn_caps_rsp.evt_set.bits);
s_avrc_peer_rn_cap.bits = rc->get_rn_caps_rsp.evt_set.bits;
bt_av_new_track();
bt_av_playback_changed();
bt_av_play_pos_changed();
break;
}
default:
ESP_LOGE(BT_RC_CT_TAG, "%s unhandled evt %d", __func__, event);
break;
}
}
static void volume_set_by_controller(uint8_t volume)
{
_lock_acquire(&s_volume_lock);
s_volume = volume;
_lock_release(&s_volume_lock);
}
// static void volume_set_by_local_hos0t(uint8_t volume)
// {
// ESP_LOGI(BT_RC_TG_TAG, "Volume is set locally to: %d%%", (uint32_t)volume * 100 / 0x7f);
// _lock_acquire(&s_volume_lock);
// s_volume = volume;
// _lock_release(&s_volume_lock);
// if (s_volume_notify)
// {
// esp_avrc_rn_param_t rn_param;
// rn_param.volume = s_volume;
// esp_avrc_tg_send_rn_rsp(ESP_AVRC_RN_VOLUME_CHANGE, ESP_AVRC_RN_RSP_CHANGED, &rn_param);
// s_volume_notify = false;
// }
// }
static void bt_av_hdl_avrc_tg_evt(uint16_t event, void *p_param)
{
ESP_LOGD(BT_RC_TG_TAG, "%s evt %d", __func__, event);
esp_avrc_tg_cb_param_t *rc = (esp_avrc_tg_cb_param_t *)(p_param);
switch (event)
{
case ESP_AVRC_TG_CONNECTION_STATE_EVT:
{
uint8_t *bda = rc->conn_stat.remote_bda;
ESP_LOGI(BT_RC_TG_TAG, "AVRC conn_state evt: state %d, [%02x:%02x:%02x:%02x:%02x:%02x]",
rc->conn_stat.connected, bda[0], bda[1], bda[2], bda[3], bda[4], bda[5]);
break;
}
case ESP_AVRC_TG_PASSTHROUGH_CMD_EVT:
{
ESP_LOGI(BT_RC_TG_TAG, "AVRC passthrough cmd: key_code 0x%x, key_state %d", rc->psth_cmd.key_code, rc->psth_cmd.key_state);
break;
}
case ESP_AVRC_TG_SET_ABSOLUTE_VOLUME_CMD_EVT:
{
ESP_LOGI(BT_RC_TG_TAG, "AVRC set absolute volume: %f (%i)", (float)rc->set_abs_vol.volume / 0x7f, (int)rc->set_abs_vol.volume);
volume_set_by_controller(rc->set_abs_vol.volume);
audiobit_set_headphone_volume_float((float)rc->set_abs_vol.volume / 0x7f);
break;
}
case ESP_AVRC_TG_REGISTER_NOTIFICATION_EVT:
{
ESP_LOGI(BT_RC_TG_TAG, "AVRC register event notification: %d, param: 0x%x", rc->reg_ntf.event_id, rc->reg_ntf.event_parameter);
if (rc->reg_ntf.event_id == ESP_AVRC_RN_VOLUME_CHANGE)
{
s_volume_notify = true;
esp_avrc_rn_param_t rn_param;
rn_param.volume = s_volume;
esp_avrc_tg_send_rn_rsp(ESP_AVRC_RN_VOLUME_CHANGE, ESP_AVRC_RN_RSP_INTERIM, &rn_param);
}
break;
}
case ESP_AVRC_TG_REMOTE_FEATURES_EVT:
{
ESP_LOGI(BT_RC_TG_TAG, "AVRC remote features %x, CT features %x", rc->rmt_feats.feat_mask, rc->rmt_feats.ct_feat_flag);
break;
}
default:
ESP_LOGE(BT_RC_TG_TAG, "%s unhandled evt %d", __func__, event);
break;
}
} | [
"[email protected]"
] | |
b63c9bdb12b98200b2b09509bacb63e77aa173c6 | 0f7a4119185aff6f48907e8a5b2666d91a47c56b | /sstd_utility/windows_boost/boost/units/base_units/us/quart.hpp | b31e8752e84e9bfcb003f53d0ab817978416c680 | [] | no_license | jixhua/QQmlQuickBook | 6636c77e9553a86f09cd59a2e89a83eaa9f153b6 | 782799ec3426291be0b0a2e37dc3e209006f0415 | refs/heads/master | 2021-09-28T13:02:48.880908 | 2018-11-17T10:43:47 | 2018-11-17T10:43:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,122 | hpp | // Boost.Units - A C++ library for zero-overhead dimensional analysis and
// unit/quantity manipulation and conversion
//
// Copyright (C) 2003-2008 Matthias Christian Schabel
// Copyright (C) 2007-2008 Steven Watanabe
//
// 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_UNITS_BASE_UNITS_US_QUART_HPP_INCLUDED
#define BOOST_UNITS_BASE_UNITS_US_QUART_HPP_INCLUDED
#include <boost/units/scaled_base_unit.hpp>
#include <boost/units/static_rational.hpp>
#include <boost/units/scale.hpp>
#include <boost/units/base_units/us/pint.hpp>
namespace boost {
namespace units {
namespace us {
typedef scaled_base_unit<pint_base_unit, scale<2, static_rational<1> > > quart_base_unit;
} // namespace us
template<>
struct base_unit_info<us::quart_base_unit> {
static BOOST_CONSTEXPR const char* name() { return("quart (U.S.)"); }
static BOOST_CONSTEXPR const char* symbol() { return("qt"); }
};
} // namespace units
} // namespace boost
#endif // BOOST_UNITS_BASE_UNITS_US_QUART_HPP_INCLUDED
| [
"[email protected]"
] | |
ef7bf33186ecdbe538b9a172f670eb1e76ce6c37 | f1dcd8cf35663b3affd3e19d32ea27355ad93fd2 | /libthread_safe/include/thread_safe/gnu/c++/9/cmath | d00b4ce45d08dd9d6b7ac5a68e752bec8c167030 | [] | no_license | mgood7123/greenThreads | eb65665b9403cfc51c68dfd95e1ebac87eed96cd | 891ac222fa6eb6bcbd44d51d370ac1d059d6a50d | refs/heads/master | 2020-08-28T21:59:45.993320 | 2019-11-27T12:31:56 | 2019-11-27T12:31:56 | 217,831,766 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 49,112 | // -*- C++ -*- C forwarding header.
// Copyright (C) 1997-2019 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library 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, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
/** @file include/cmath
* This is a Standard C++ Library file. You should @c \#include this file
* in your programs, rather than any of the @a *.h implementation files.
*
* This is the C++ version of the Standard C Library header @c math.h,
* and its contents are (mostly) the same as that header, but are all
* contained in the namespace @c std (except for names which are defined
* as macros in C).
*/
//
// ISO C++ 14882: 26.5 C library
//
#pragma GCC system_header
#include "../bits/c++config.h"
#include "../bits/cpp_type_traits.h"
#include "../ext/type_traits.h"
#define _GLIBCXX_INCLUDE_NEXT_C_HEADERS
#include_next "../math.h"
#undef _GLIBCXX_INCLUDE_NEXT_C_HEADERS
#include "../bits/std_abs.h"
#ifndef _GLIBCXX_CMATH
#define _GLIBCXX_CMATH 1
// Get rid of those macros defined in <math.h> in lieu of real functions.
#undef div
#undef acos
#undef asin
#undef atan
#undef atan2
#undef ceil
#undef cos
#undef cosh
#undef exp
#undef fabs
#undef floor
#undef fmod
#undef frexp
#undef ldexp
#undef log
#undef log10
#undef modf
#undef pow
#undef sin
#undef sinh
#undef sqrt
#undef tan
#undef tanh
extern "C++"
{
namespace std _GLIBCXX_VISIBILITY(default)
{
_GLIBCXX_BEGIN_NAMESPACE_VERSION
using ::acos;
#ifndef __CORRECT_ISO_CPP_MATH_H_PROTO
inline _GLIBCXX_CONSTEXPR float
acos(float __x)
{ return __builtin_acosf(__x); }
inline _GLIBCXX_CONSTEXPR long double
acos(long double __x)
{ return __builtin_acosl(__x); }
#endif
template<typename _Tp>
inline _GLIBCXX_CONSTEXPR
typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
acos(_Tp __x)
{ return __builtin_acos(__x); }
using ::asin;
#ifndef __CORRECT_ISO_CPP_MATH_H_PROTO
inline _GLIBCXX_CONSTEXPR float
asin(float __x)
{ return __builtin_asinf(__x); }
inline _GLIBCXX_CONSTEXPR long double
asin(long double __x)
{ return __builtin_asinl(__x); }
#endif
template<typename _Tp>
inline _GLIBCXX_CONSTEXPR
typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
asin(_Tp __x)
{ return __builtin_asin(__x); }
using ::atan;
#ifndef __CORRECT_ISO_CPP_MATH_H_PROTO
inline _GLIBCXX_CONSTEXPR float
atan(float __x)
{ return __builtin_atanf(__x); }
inline _GLIBCXX_CONSTEXPR long double
atan(long double __x)
{ return __builtin_atanl(__x); }
#endif
template<typename _Tp>
inline _GLIBCXX_CONSTEXPR
typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
atan(_Tp __x)
{ return __builtin_atan(__x); }
using ::atan2;
#ifndef __CORRECT_ISO_CPP_MATH_H_PROTO
inline _GLIBCXX_CONSTEXPR float
atan2(float __y, float __x)
{ return __builtin_atan2f(__y, __x); }
inline _GLIBCXX_CONSTEXPR long double
atan2(long double __y, long double __x)
{ return __builtin_atan2l(__y, __x); }
#endif
template<typename _Tp, typename _Up>
inline _GLIBCXX_CONSTEXPR
typename __gnu_cxx::__promote_2<_Tp, _Up>::__type
atan2(_Tp __y, _Up __x)
{
typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type;
return atan2(__type(__y), __type(__x));
}
using ::ceil;
#ifndef __CORRECT_ISO_CPP_MATH_H_PROTO
inline _GLIBCXX_CONSTEXPR float
ceil(float __x)
{ return __builtin_ceilf(__x); }
inline _GLIBCXX_CONSTEXPR long double
ceil(long double __x)
{ return __builtin_ceill(__x); }
#endif
template<typename _Tp>
inline _GLIBCXX_CONSTEXPR
typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
ceil(_Tp __x)
{ return __builtin_ceil(__x); }
using ::cos;
#ifndef __CORRECT_ISO_CPP_MATH_H_PROTO
inline _GLIBCXX_CONSTEXPR float
cos(float __x)
{ return __builtin_cosf(__x); }
inline _GLIBCXX_CONSTEXPR long double
cos(long double __x)
{ return __builtin_cosl(__x); }
#endif
template<typename _Tp>
inline _GLIBCXX_CONSTEXPR
typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
cos(_Tp __x)
{ return __builtin_cos(__x); }
using ::cosh;
#ifndef __CORRECT_ISO_CPP_MATH_H_PROTO
inline _GLIBCXX_CONSTEXPR float
cosh(float __x)
{ return __builtin_coshf(__x); }
inline _GLIBCXX_CONSTEXPR long double
cosh(long double __x)
{ return __builtin_coshl(__x); }
#endif
template<typename _Tp>
inline _GLIBCXX_CONSTEXPR
typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
cosh(_Tp __x)
{ return __builtin_cosh(__x); }
using ::exp;
#ifndef __CORRECT_ISO_CPP_MATH_H_PROTO
inline _GLIBCXX_CONSTEXPR float
exp(float __x)
{ return __builtin_expf(__x); }
inline _GLIBCXX_CONSTEXPR long double
exp(long double __x)
{ return __builtin_expl(__x); }
#endif
template<typename _Tp>
inline _GLIBCXX_CONSTEXPR
typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
exp(_Tp __x)
{ return __builtin_exp(__x); }
using ::fabs;
#ifndef __CORRECT_ISO_CPP_MATH_H_PROTO
inline _GLIBCXX_CONSTEXPR float
fabs(float __x)
{ return __builtin_fabsf(__x); }
inline _GLIBCXX_CONSTEXPR long double
fabs(long double __x)
{ return __builtin_fabsl(__x); }
#endif
template<typename _Tp>
inline _GLIBCXX_CONSTEXPR
typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
fabs(_Tp __x)
{ return __builtin_fabs(__x); }
using ::floor;
#ifndef __CORRECT_ISO_CPP_MATH_H_PROTO
inline _GLIBCXX_CONSTEXPR float
floor(float __x)
{ return __builtin_floorf(__x); }
inline _GLIBCXX_CONSTEXPR long double
floor(long double __x)
{ return __builtin_floorl(__x); }
#endif
template<typename _Tp>
inline _GLIBCXX_CONSTEXPR
typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
floor(_Tp __x)
{ return __builtin_floor(__x); }
using ::fmod;
#ifndef __CORRECT_ISO_CPP_MATH_H_PROTO
inline _GLIBCXX_CONSTEXPR float
fmod(float __x, float __y)
{ return __builtin_fmodf(__x, __y); }
inline _GLIBCXX_CONSTEXPR long double
fmod(long double __x, long double __y)
{ return __builtin_fmodl(__x, __y); }
#endif
template<typename _Tp, typename _Up>
inline _GLIBCXX_CONSTEXPR
typename __gnu_cxx::__promote_2<_Tp, _Up>::__type
fmod(_Tp __x, _Up __y)
{
typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type;
return fmod(__type(__x), __type(__y));
}
using ::frexp;
#ifndef __CORRECT_ISO_CPP_MATH_H_PROTO
inline float
frexp(float __x, int* __exp)
{ return __builtin_frexpf(__x, __exp); }
inline long double
frexp(long double __x, int* __exp)
{ return __builtin_frexpl(__x, __exp); }
#endif
template<typename _Tp>
inline _GLIBCXX_CONSTEXPR
typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
frexp(_Tp __x, int* __exp)
{ return __builtin_frexp(__x, __exp); }
using ::ldexp;
#ifndef __CORRECT_ISO_CPP_MATH_H_PROTO
inline _GLIBCXX_CONSTEXPR float
ldexp(float __x, int __exp)
{ return __builtin_ldexpf(__x, __exp); }
inline _GLIBCXX_CONSTEXPR long double
ldexp(long double __x, int __exp)
{ return __builtin_ldexpl(__x, __exp); }
#endif
template<typename _Tp>
inline _GLIBCXX_CONSTEXPR
typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
ldexp(_Tp __x, int __exp)
{ return __builtin_ldexp(__x, __exp); }
using ::log;
#ifndef __CORRECT_ISO_CPP_MATH_H_PROTO
inline _GLIBCXX_CONSTEXPR float
log(float __x)
{ return __builtin_logf(__x); }
inline _GLIBCXX_CONSTEXPR long double
log(long double __x)
{ return __builtin_logl(__x); }
#endif
template<typename _Tp>
inline _GLIBCXX_CONSTEXPR
typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
log(_Tp __x)
{ return __builtin_log(__x); }
using ::log10;
#ifndef __CORRECT_ISO_CPP_MATH_H_PROTO
inline _GLIBCXX_CONSTEXPR float
log10(float __x)
{ return __builtin_log10f(__x); }
inline _GLIBCXX_CONSTEXPR long double
log10(long double __x)
{ return __builtin_log10l(__x); }
#endif
template<typename _Tp>
inline _GLIBCXX_CONSTEXPR
typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
log10(_Tp __x)
{ return __builtin_log10(__x); }
using ::modf;
#ifndef __CORRECT_ISO_CPP_MATH_H_PROTO
inline float
modf(float __x, float* __iptr)
{ return __builtin_modff(__x, __iptr); }
inline long double
modf(long double __x, long double* __iptr)
{ return __builtin_modfl(__x, __iptr); }
#endif
using ::pow;
#ifndef __CORRECT_ISO_CPP_MATH_H_PROTO
inline _GLIBCXX_CONSTEXPR float
pow(float __x, float __y)
{ return __builtin_powf(__x, __y); }
inline _GLIBCXX_CONSTEXPR long double
pow(long double __x, long double __y)
{ return __builtin_powl(__x, __y); }
#if __cplusplus < 201103L
// _GLIBCXX_RESOLVE_LIB_DEFECTS
// DR 550. What should the return type of pow(float,int) be?
inline double
pow(double __x, int __i)
{ return __builtin_powi(__x, __i); }
inline float
pow(float __x, int __n)
{ return __builtin_powif(__x, __n); }
inline long double
pow(long double __x, int __n)
{ return __builtin_powil(__x, __n); }
#endif
#endif
template<typename _Tp, typename _Up>
inline _GLIBCXX_CONSTEXPR
typename __gnu_cxx::__promote_2<_Tp, _Up>::__type
pow(_Tp __x, _Up __y)
{
typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type;
return pow(__type(__x), __type(__y));
}
using ::sin;
#ifndef __CORRECT_ISO_CPP_MATH_H_PROTO
inline _GLIBCXX_CONSTEXPR float
sin(float __x)
{ return __builtin_sinf(__x); }
inline _GLIBCXX_CONSTEXPR long double
sin(long double __x)
{ return __builtin_sinl(__x); }
#endif
template<typename _Tp>
inline _GLIBCXX_CONSTEXPR
typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
sin(_Tp __x)
{ return __builtin_sin(__x); }
using ::sinh;
#ifndef __CORRECT_ISO_CPP_MATH_H_PROTO
inline _GLIBCXX_CONSTEXPR float
sinh(float __x)
{ return __builtin_sinhf(__x); }
inline _GLIBCXX_CONSTEXPR long double
sinh(long double __x)
{ return __builtin_sinhl(__x); }
#endif
template<typename _Tp>
inline _GLIBCXX_CONSTEXPR
typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
sinh(_Tp __x)
{ return __builtin_sinh(__x); }
using ::sqrt;
#ifndef __CORRECT_ISO_CPP_MATH_H_PROTO
inline _GLIBCXX_CONSTEXPR float
sqrt(float __x)
{ return __builtin_sqrtf(__x); }
inline _GLIBCXX_CONSTEXPR long double
sqrt(long double __x)
{ return __builtin_sqrtl(__x); }
#endif
template<typename _Tp>
inline _GLIBCXX_CONSTEXPR
typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
sqrt(_Tp __x)
{ return __builtin_sqrt(__x); }
using ::tan;
#ifndef __CORRECT_ISO_CPP_MATH_H_PROTO
inline _GLIBCXX_CONSTEXPR float
tan(float __x)
{ return __builtin_tanf(__x); }
inline _GLIBCXX_CONSTEXPR long double
tan(long double __x)
{ return __builtin_tanl(__x); }
#endif
template<typename _Tp>
inline _GLIBCXX_CONSTEXPR
typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
tan(_Tp __x)
{ return __builtin_tan(__x); }
using ::tanh;
#ifndef __CORRECT_ISO_CPP_MATH_H_PROTO
inline _GLIBCXX_CONSTEXPR float
tanh(float __x)
{ return __builtin_tanhf(__x); }
inline _GLIBCXX_CONSTEXPR long double
tanh(long double __x)
{ return __builtin_tanhl(__x); }
#endif
template<typename _Tp>
inline _GLIBCXX_CONSTEXPR
typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
tanh(_Tp __x)
{ return __builtin_tanh(__x); }
#if _GLIBCXX_USE_C99_MATH
#if !_GLIBCXX_USE_C99_FP_MACROS_DYNAMIC
// These are possible macros imported from C99-land.
#undef fpclassify
#undef isfinite
#undef isinf
#undef isnan
#undef isnormal
#undef signbit
#undef isgreater
#undef isgreaterequal
#undef isless
#undef islessequal
#undef islessgreater
#undef isunordered
#if __cplusplus >= 201103L
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr int
fpclassify(float __x)
{ return __builtin_fpclassify(FP_NAN, FP_INFINITE, FP_NORMAL,
FP_SUBNORMAL, FP_ZERO, __x); }
constexpr int
fpclassify(double __x)
{ return __builtin_fpclassify(FP_NAN, FP_INFINITE, FP_NORMAL,
FP_SUBNORMAL, FP_ZERO, __x); }
constexpr int
fpclassify(long double __x)
{ return __builtin_fpclassify(FP_NAN, FP_INFINITE, FP_NORMAL,
FP_SUBNORMAL, FP_ZERO, __x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp>
constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
int>::__type
fpclassify(_Tp __x)
{ return __x != 0 ? FP_NORMAL : FP_ZERO; }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr bool
isfinite(float __x)
{ return __builtin_isfinite(__x); }
constexpr bool
isfinite(double __x)
{ return __builtin_isfinite(__x); }
constexpr bool
isfinite(long double __x)
{ return __builtin_isfinite(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp>
constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
bool>::__type
isfinite(_Tp __x)
{ return true; }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr bool
isinf(float __x)
{ return __builtin_isinf(__x); }
#if _GLIBCXX_HAVE_OBSOLETE_ISINF \
&& !_GLIBCXX_NO_OBSOLETE_ISINF_ISNAN_DYNAMIC
using ::isinf;
#else
constexpr bool
isinf(double __x)
{ return __builtin_isinf(__x); }
#endif
constexpr bool
isinf(long double __x)
{ return __builtin_isinf(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp>
constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
bool>::__type
isinf(_Tp __x)
{ return false; }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr bool
isnan(float __x)
{ return __builtin_isnan(__x); }
#if _GLIBCXX_HAVE_OBSOLETE_ISNAN \
&& !_GLIBCXX_NO_OBSOLETE_ISINF_ISNAN_DYNAMIC
using ::isnan;
#else
constexpr bool
isnan(double __x)
{ return __builtin_isnan(__x); }
#endif
constexpr bool
isnan(long double __x)
{ return __builtin_isnan(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp>
constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
bool>::__type
isnan(_Tp __x)
{ return false; }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr bool
isnormal(float __x)
{ return __builtin_isnormal(__x); }
constexpr bool
isnormal(double __x)
{ return __builtin_isnormal(__x); }
constexpr bool
isnormal(long double __x)
{ return __builtin_isnormal(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp>
constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
bool>::__type
isnormal(_Tp __x)
{ return __x != 0 ? true : false; }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
// Note: middle-end/36757 is fixed, __builtin_signbit is type-generic.
constexpr bool
signbit(float __x)
{ return __builtin_signbit(__x); }
constexpr bool
signbit(double __x)
{ return __builtin_signbit(__x); }
constexpr bool
signbit(long double __x)
{ return __builtin_signbit(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp>
constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
bool>::__type
signbit(_Tp __x)
{ return __x < 0 ? true : false; }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr bool
isgreater(float __x, float __y)
{ return __builtin_isgreater(__x, __y); }
constexpr bool
isgreater(double __x, double __y)
{ return __builtin_isgreater(__x, __y); }
constexpr bool
isgreater(long double __x, long double __y)
{ return __builtin_isgreater(__x, __y); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp, typename _Up>
constexpr typename
__gnu_cxx::__enable_if<(__is_arithmetic<_Tp>::__value
&& __is_arithmetic<_Up>::__value), bool>::__type
isgreater(_Tp __x, _Up __y)
{
typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type;
return __builtin_isgreater(__type(__x), __type(__y));
}
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr bool
isgreaterequal(float __x, float __y)
{ return __builtin_isgreaterequal(__x, __y); }
constexpr bool
isgreaterequal(double __x, double __y)
{ return __builtin_isgreaterequal(__x, __y); }
constexpr bool
isgreaterequal(long double __x, long double __y)
{ return __builtin_isgreaterequal(__x, __y); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp, typename _Up>
constexpr typename
__gnu_cxx::__enable_if<(__is_arithmetic<_Tp>::__value
&& __is_arithmetic<_Up>::__value), bool>::__type
isgreaterequal(_Tp __x, _Up __y)
{
typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type;
return __builtin_isgreaterequal(__type(__x), __type(__y));
}
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr bool
isless(float __x, float __y)
{ return __builtin_isless(__x, __y); }
constexpr bool
isless(double __x, double __y)
{ return __builtin_isless(__x, __y); }
constexpr bool
isless(long double __x, long double __y)
{ return __builtin_isless(__x, __y); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp, typename _Up>
constexpr typename
__gnu_cxx::__enable_if<(__is_arithmetic<_Tp>::__value
&& __is_arithmetic<_Up>::__value), bool>::__type
isless(_Tp __x, _Up __y)
{
typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type;
return __builtin_isless(__type(__x), __type(__y));
}
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr bool
islessequal(float __x, float __y)
{ return __builtin_islessequal(__x, __y); }
constexpr bool
islessequal(double __x, double __y)
{ return __builtin_islessequal(__x, __y); }
constexpr bool
islessequal(long double __x, long double __y)
{ return __builtin_islessequal(__x, __y); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp, typename _Up>
constexpr typename
__gnu_cxx::__enable_if<(__is_arithmetic<_Tp>::__value
&& __is_arithmetic<_Up>::__value), bool>::__type
islessequal(_Tp __x, _Up __y)
{
typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type;
return __builtin_islessequal(__type(__x), __type(__y));
}
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr bool
islessgreater(float __x, float __y)
{ return __builtin_islessgreater(__x, __y); }
constexpr bool
islessgreater(double __x, double __y)
{ return __builtin_islessgreater(__x, __y); }
constexpr bool
islessgreater(long double __x, long double __y)
{ return __builtin_islessgreater(__x, __y); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp, typename _Up>
constexpr typename
__gnu_cxx::__enable_if<(__is_arithmetic<_Tp>::__value
&& __is_arithmetic<_Up>::__value), bool>::__type
islessgreater(_Tp __x, _Up __y)
{
typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type;
return __builtin_islessgreater(__type(__x), __type(__y));
}
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr bool
isunordered(float __x, float __y)
{ return __builtin_isunordered(__x, __y); }
constexpr bool
isunordered(double __x, double __y)
{ return __builtin_isunordered(__x, __y); }
constexpr bool
isunordered(long double __x, long double __y)
{ return __builtin_isunordered(__x, __y); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp, typename _Up>
constexpr typename
__gnu_cxx::__enable_if<(__is_arithmetic<_Tp>::__value
&& __is_arithmetic<_Up>::__value), bool>::__type
isunordered(_Tp __x, _Up __y)
{
typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type;
return __builtin_isunordered(__type(__x), __type(__y));
}
#endif
#else
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value,
int>::__type
fpclassify(_Tp __f)
{
typedef typename __gnu_cxx::__promote<_Tp>::__type __type;
return __builtin_fpclassify(FP_NAN, FP_INFINITE, FP_NORMAL,
FP_SUBNORMAL, FP_ZERO, __type(__f));
}
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value,
int>::__type
isfinite(_Tp __f)
{
typedef typename __gnu_cxx::__promote<_Tp>::__type __type;
return __builtin_isfinite(__type(__f));
}
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value,
int>::__type
isinf(_Tp __f)
{
typedef typename __gnu_cxx::__promote<_Tp>::__type __type;
return __builtin_isinf(__type(__f));
}
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value,
int>::__type
isnan(_Tp __f)
{
typedef typename __gnu_cxx::__promote<_Tp>::__type __type;
return __builtin_isnan(__type(__f));
}
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value,
int>::__type
isnormal(_Tp __f)
{
typedef typename __gnu_cxx::__promote<_Tp>::__type __type;
return __builtin_isnormal(__type(__f));
}
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value,
int>::__type
signbit(_Tp __f)
{
typedef typename __gnu_cxx::__promote<_Tp>::__type __type;
return __builtin_signbit(__type(__f));
}
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value,
int>::__type
isgreater(_Tp __f1, _Tp __f2)
{
typedef typename __gnu_cxx::__promote<_Tp>::__type __type;
return __builtin_isgreater(__type(__f1), __type(__f2));
}
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value,
int>::__type
isgreaterequal(_Tp __f1, _Tp __f2)
{
typedef typename __gnu_cxx::__promote<_Tp>::__type __type;
return __builtin_isgreaterequal(__type(__f1), __type(__f2));
}
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value,
int>::__type
isless(_Tp __f1, _Tp __f2)
{
typedef typename __gnu_cxx::__promote<_Tp>::__type __type;
return __builtin_isless(__type(__f1), __type(__f2));
}
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value,
int>::__type
islessequal(_Tp __f1, _Tp __f2)
{
typedef typename __gnu_cxx::__promote<_Tp>::__type __type;
return __builtin_islessequal(__type(__f1), __type(__f2));
}
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value,
int>::__type
islessgreater(_Tp __f1, _Tp __f2)
{
typedef typename __gnu_cxx::__promote<_Tp>::__type __type;
return __builtin_islessgreater(__type(__f1), __type(__f2));
}
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value,
int>::__type
isunordered(_Tp __f1, _Tp __f2)
{
typedef typename __gnu_cxx::__promote<_Tp>::__type __type;
return __builtin_isunordered(__type(__f1), __type(__f2));
}
#endif // C++11
#endif /* _GLIBCXX_USE_C99_FP_MACROS_DYNAMIC */
#endif /* _GLIBCXX_USE_C99_MATH */
#if __cplusplus >= 201103L
#ifdef _GLIBCXX_USE_C99_MATH_TR1
#undef acosh
#undef acoshf
#undef acoshl
#undef asinh
#undef asinhf
#undef asinhl
#undef atanh
#undef atanhf
#undef atanhl
#undef cbrt
#undef cbrtf
#undef cbrtl
#undef copysign
#undef copysignf
#undef copysignl
#undef erf
#undef erff
#undef erfl
#undef erfc
#undef erfcf
#undef erfcl
#undef exp2
#undef exp2f
#undef exp2l
#undef expm1
#undef expm1f
#undef expm1l
#undef fdim
#undef fdimf
#undef fdiml
#undef fma
#undef fmaf
#undef fmal
#undef fmax
#undef fmaxf
#undef fmaxl
#undef fmin
#undef fminf
#undef fminl
#undef hypot
#undef hypotf
#undef hypotl
#undef ilogb
#undef ilogbf
#undef ilogbl
#undef lgamma
#undef lgammaf
#undef lgammal
#ifndef _GLIBCXX_NO_C99_ROUNDING_FUNCS
#undef llrint
#undef llrintf
#undef llrintl
#undef llround
#undef llroundf
#undef llroundl
#endif
#undef log1p
#undef log1pf
#undef log1pl
#undef log2
#undef log2f
#undef log2l
#undef logb
#undef logbf
#undef logbl
#undef lrint
#undef lrintf
#undef lrintl
#undef lround
#undef lroundf
#undef lroundl
#undef nan
#undef nanf
#undef nanl
#undef nearbyint
#undef nearbyintf
#undef nearbyintl
#undef nextafter
#undef nextafterf
#undef nextafterl
#undef nexttoward
#undef nexttowardf
#undef nexttowardl
#undef remainder
#undef remainderf
#undef remainderl
#undef remquo
#undef remquof
#undef remquol
#undef rint
#undef rintf
#undef rintl
#undef round
#undef roundf
#undef roundl
#undef scalbln
#undef scalblnf
#undef scalblnl
#undef scalbn
#undef scalbnf
#undef scalbnl
#undef tgamma
#undef tgammaf
#undef tgammal
#undef trunc
#undef truncf
#undef truncl
// types
using ::double_t;
using ::float_t;
// functions
using ::acosh;
using ::acoshf;
using ::acoshl;
using ::asinh;
using ::asinhf;
using ::asinhl;
using ::atanh;
using ::atanhf;
using ::atanhl;
using ::cbrt;
using ::cbrtf;
using ::cbrtl;
using ::copysign;
using ::copysignf;
using ::copysignl;
using ::erf;
using ::erff;
using ::erfl;
using ::erfc;
using ::erfcf;
using ::erfcl;
using ::exp2;
using ::exp2f;
using ::exp2l;
using ::expm1;
using ::expm1f;
using ::expm1l;
using ::fdim;
using ::fdimf;
using ::fdiml;
using ::fma;
using ::fmaf;
using ::fmal;
using ::fmax;
using ::fmaxf;
using ::fmaxl;
using ::fmin;
using ::fminf;
using ::fminl;
using ::hypot;
using ::hypotf;
using ::hypotl;
using ::ilogb;
using ::ilogbf;
using ::ilogbl;
using ::lgamma;
using ::lgammaf;
using ::lgammal;
#ifndef _GLIBCXX_NO_C99_ROUNDING_FUNCS
using ::llrint;
using ::llrintf;
using ::llrintl;
using ::llround;
using ::llroundf;
using ::llroundl;
#endif
using ::log1p;
using ::log1pf;
using ::log1pl;
using ::log2;
using ::log2f;
using ::log2l;
using ::logb;
using ::logbf;
using ::logbl;
using ::lrint;
using ::lrintf;
using ::lrintl;
using ::lround;
using ::lroundf;
using ::lroundl;
using ::nan;
using ::nanf;
using ::nanl;
using ::nearbyint;
using ::nearbyintf;
using ::nearbyintl;
using ::nextafter;
using ::nextafterf;
using ::nextafterl;
using ::nexttoward;
using ::nexttowardf;
using ::nexttowardl;
using ::remainder;
using ::remainderf;
using ::remainderl;
using ::remquo;
using ::remquof;
using ::remquol;
using ::rint;
using ::rintf;
using ::rintl;
using ::round;
using ::roundf;
using ::roundl;
using ::scalbln;
using ::scalblnf;
using ::scalblnl;
using ::scalbn;
using ::scalbnf;
using ::scalbnl;
using ::tgamma;
using ::tgammaf;
using ::tgammal;
using ::trunc;
using ::truncf;
using ::truncl;
/// Additional overloads.
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr float
acosh(float __x)
{ return __builtin_acoshf(__x); }
constexpr long double
acosh(long double __x)
{ return __builtin_acoshl(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp>
constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
acosh(_Tp __x)
{ return __builtin_acosh(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr float
asinh(float __x)
{ return __builtin_asinhf(__x); }
constexpr long double
asinh(long double __x)
{ return __builtin_asinhl(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp>
constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
asinh(_Tp __x)
{ return __builtin_asinh(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr float
atanh(float __x)
{ return __builtin_atanhf(__x); }
constexpr long double
atanh(long double __x)
{ return __builtin_atanhl(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp>
constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
atanh(_Tp __x)
{ return __builtin_atanh(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr float
cbrt(float __x)
{ return __builtin_cbrtf(__x); }
constexpr long double
cbrt(long double __x)
{ return __builtin_cbrtl(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp>
constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
cbrt(_Tp __x)
{ return __builtin_cbrt(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr float
copysign(float __x, float __y)
{ return __builtin_copysignf(__x, __y); }
constexpr long double
copysign(long double __x, long double __y)
{ return __builtin_copysignl(__x, __y); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp, typename _Up>
constexpr typename __gnu_cxx::__promote_2<_Tp, _Up>::__type
copysign(_Tp __x, _Up __y)
{
typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type;
return copysign(__type(__x), __type(__y));
}
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr float
erf(float __x)
{ return __builtin_erff(__x); }
constexpr long double
erf(long double __x)
{ return __builtin_erfl(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp>
constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
erf(_Tp __x)
{ return __builtin_erf(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr float
erfc(float __x)
{ return __builtin_erfcf(__x); }
constexpr long double
erfc(long double __x)
{ return __builtin_erfcl(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp>
constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
erfc(_Tp __x)
{ return __builtin_erfc(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr float
exp2(float __x)
{ return __builtin_exp2f(__x); }
constexpr long double
exp2(long double __x)
{ return __builtin_exp2l(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp>
constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
exp2(_Tp __x)
{ return __builtin_exp2(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr float
expm1(float __x)
{ return __builtin_expm1f(__x); }
constexpr long double
expm1(long double __x)
{ return __builtin_expm1l(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp>
constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
expm1(_Tp __x)
{ return __builtin_expm1(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr float
fdim(float __x, float __y)
{ return __builtin_fdimf(__x, __y); }
constexpr long double
fdim(long double __x, long double __y)
{ return __builtin_fdiml(__x, __y); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp, typename _Up>
constexpr typename __gnu_cxx::__promote_2<_Tp, _Up>::__type
fdim(_Tp __x, _Up __y)
{
typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type;
return fdim(__type(__x), __type(__y));
}
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr float
fma(float __x, float __y, float __z)
{ return __builtin_fmaf(__x, __y, __z); }
constexpr long double
fma(long double __x, long double __y, long double __z)
{ return __builtin_fmal(__x, __y, __z); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp, typename _Up, typename _Vp>
constexpr typename __gnu_cxx::__promote_3<_Tp, _Up, _Vp>::__type
fma(_Tp __x, _Up __y, _Vp __z)
{
typedef typename __gnu_cxx::__promote_3<_Tp, _Up, _Vp>::__type __type;
return fma(__type(__x), __type(__y), __type(__z));
}
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr float
fmax(float __x, float __y)
{ return __builtin_fmaxf(__x, __y); }
constexpr long double
fmax(long double __x, long double __y)
{ return __builtin_fmaxl(__x, __y); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp, typename _Up>
constexpr typename __gnu_cxx::__promote_2<_Tp, _Up>::__type
fmax(_Tp __x, _Up __y)
{
typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type;
return fmax(__type(__x), __type(__y));
}
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr float
fmin(float __x, float __y)
{ return __builtin_fminf(__x, __y); }
constexpr long double
fmin(long double __x, long double __y)
{ return __builtin_fminl(__x, __y); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp, typename _Up>
constexpr typename __gnu_cxx::__promote_2<_Tp, _Up>::__type
fmin(_Tp __x, _Up __y)
{
typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type;
return fmin(__type(__x), __type(__y));
}
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr float
hypot(float __x, float __y)
{ return __builtin_hypotf(__x, __y); }
constexpr long double
hypot(long double __x, long double __y)
{ return __builtin_hypotl(__x, __y); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp, typename _Up>
constexpr typename __gnu_cxx::__promote_2<_Tp, _Up>::__type
hypot(_Tp __x, _Up __y)
{
typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type;
return hypot(__type(__x), __type(__y));
}
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr int
ilogb(float __x)
{ return __builtin_ilogbf(__x); }
constexpr int
ilogb(long double __x)
{ return __builtin_ilogbl(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp>
constexpr
typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
int>::__type
ilogb(_Tp __x)
{ return __builtin_ilogb(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr float
lgamma(float __x)
{ return __builtin_lgammaf(__x); }
constexpr long double
lgamma(long double __x)
{ return __builtin_lgammal(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp>
constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
lgamma(_Tp __x)
{ return __builtin_lgamma(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr long long
llrint(float __x)
{ return __builtin_llrintf(__x); }
constexpr long long
llrint(long double __x)
{ return __builtin_llrintl(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp>
constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
long long>::__type
llrint(_Tp __x)
{ return __builtin_llrint(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr long long
llround(float __x)
{ return __builtin_llroundf(__x); }
constexpr long long
llround(long double __x)
{ return __builtin_llroundl(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp>
constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
long long>::__type
llround(_Tp __x)
{ return __builtin_llround(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr float
log1p(float __x)
{ return __builtin_log1pf(__x); }
constexpr long double
log1p(long double __x)
{ return __builtin_log1pl(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp>
constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
log1p(_Tp __x)
{ return __builtin_log1p(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
// DR 568.
constexpr float
log2(float __x)
{ return __builtin_log2f(__x); }
constexpr long double
log2(long double __x)
{ return __builtin_log2l(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp>
constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
log2(_Tp __x)
{ return __builtin_log2(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr float
logb(float __x)
{ return __builtin_logbf(__x); }
constexpr long double
logb(long double __x)
{ return __builtin_logbl(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp>
constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
logb(_Tp __x)
{ return __builtin_logb(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr long
lrint(float __x)
{ return __builtin_lrintf(__x); }
constexpr long
lrint(long double __x)
{ return __builtin_lrintl(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp>
constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
long>::__type
lrint(_Tp __x)
{ return __builtin_lrint(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr long
lround(float __x)
{ return __builtin_lroundf(__x); }
constexpr long
lround(long double __x)
{ return __builtin_lroundl(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp>
constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
long>::__type
lround(_Tp __x)
{ return __builtin_lround(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr float
nearbyint(float __x)
{ return __builtin_nearbyintf(__x); }
constexpr long double
nearbyint(long double __x)
{ return __builtin_nearbyintl(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp>
constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
nearbyint(_Tp __x)
{ return __builtin_nearbyint(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr float
nextafter(float __x, float __y)
{ return __builtin_nextafterf(__x, __y); }
constexpr long double
nextafter(long double __x, long double __y)
{ return __builtin_nextafterl(__x, __y); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp, typename _Up>
constexpr typename __gnu_cxx::__promote_2<_Tp, _Up>::__type
nextafter(_Tp __x, _Up __y)
{
typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type;
return nextafter(__type(__x), __type(__y));
}
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr float
nexttoward(float __x, long double __y)
{ return __builtin_nexttowardf(__x, __y); }
constexpr long double
nexttoward(long double __x, long double __y)
{ return __builtin_nexttowardl(__x, __y); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp>
constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
nexttoward(_Tp __x, long double __y)
{ return __builtin_nexttoward(__x, __y); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr float
remainder(float __x, float __y)
{ return __builtin_remainderf(__x, __y); }
constexpr long double
remainder(long double __x, long double __y)
{ return __builtin_remainderl(__x, __y); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp, typename _Up>
constexpr typename __gnu_cxx::__promote_2<_Tp, _Up>::__type
remainder(_Tp __x, _Up __y)
{
typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type;
return remainder(__type(__x), __type(__y));
}
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
inline float
remquo(float __x, float __y, int* __pquo)
{ return __builtin_remquof(__x, __y, __pquo); }
inline long double
remquo(long double __x, long double __y, int* __pquo)
{ return __builtin_remquol(__x, __y, __pquo); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp, typename _Up>
inline typename __gnu_cxx::__promote_2<_Tp, _Up>::__type
remquo(_Tp __x, _Up __y, int* __pquo)
{
typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type;
return remquo(__type(__x), __type(__y), __pquo);
}
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr float
rint(float __x)
{ return __builtin_rintf(__x); }
constexpr long double
rint(long double __x)
{ return __builtin_rintl(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp>
constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
rint(_Tp __x)
{ return __builtin_rint(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr float
round(float __x)
{ return __builtin_roundf(__x); }
constexpr long double
round(long double __x)
{ return __builtin_roundl(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp>
constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
round(_Tp __x)
{ return __builtin_round(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr float
scalbln(float __x, long __ex)
{ return __builtin_scalblnf(__x, __ex); }
constexpr long double
scalbln(long double __x, long __ex)
{ return __builtin_scalblnl(__x, __ex); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp>
constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
scalbln(_Tp __x, long __ex)
{ return __builtin_scalbln(__x, __ex); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr float
scalbn(float __x, int __ex)
{ return __builtin_scalbnf(__x, __ex); }
constexpr long double
scalbn(long double __x, int __ex)
{ return __builtin_scalbnl(__x, __ex); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp>
constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
scalbn(_Tp __x, int __ex)
{ return __builtin_scalbn(__x, __ex); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr float
tgamma(float __x)
{ return __builtin_tgammaf(__x); }
constexpr long double
tgamma(long double __x)
{ return __builtin_tgammal(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp>
constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
tgamma(_Tp __x)
{ return __builtin_tgamma(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_FP
constexpr float
trunc(float __x)
{ return __builtin_truncf(__x); }
constexpr long double
trunc(long double __x)
{ return __builtin_truncl(__x); }
#endif
#ifndef __CORRECT_ISO_CPP11_MATH_H_PROTO_INT
template<typename _Tp>
constexpr typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
trunc(_Tp __x)
{ return __builtin_trunc(__x); }
#endif
#endif // _GLIBCXX_USE_C99_MATH_TR1
#endif // C++11
#if __cplusplus > 201402L
// [c.math.hypot3], three-dimensional hypotenuse
#define __cpp_lib_hypot 201603
template<typename _Tp>
inline _Tp
__hypot3(_Tp __x, _Tp __y, _Tp __z)
{
__x = std::abs(__x);
__y = std::abs(__y);
__z = std::abs(__z);
if (_Tp __a = __x < __y ? __y < __z ? __z : __y : __x < __z ? __z : __x)
return __a * std::sqrt((__x / __a) * (__x / __a)
+ (__y / __a) * (__y / __a)
+ (__z / __a) * (__z / __a));
else
return {};
}
inline float
hypot(float __x, float __y, float __z)
{ return std::__hypot3<float>(__x, __y, __z); }
inline double
hypot(double __x, double __y, double __z)
{ return std::__hypot3<double>(__x, __y, __z); }
inline long double
hypot(long double __x, long double __y, long double __z)
{ return std::__hypot3<long double>(__x, __y, __z); }
template<typename _Tp, typename _Up, typename _Vp>
typename __gnu_cxx::__promote_3<_Tp, _Up, _Vp>::__type
hypot(_Tp __x, _Up __y, _Vp __z)
{
using __type = typename __gnu_cxx::__promote_3<_Tp, _Up, _Vp>::__type;
return std::__hypot3<__type>(__x, __y, __z);
}
#endif // C++17
#if __cplusplus > 201703L
// linear interpolation
# define __cpp_lib_interpolate 201902L
template<typename _Fp>
constexpr _Fp
__lerp(_Fp __a, _Fp __b, _Fp __t)
{
if (__a <= 0 && __b >= 0 || __a >= 0 && __b <= 0)
return __t * __b + (1 - __t) * __a;
if (__t == 1)
return __b; // exact
// Exact at __t=0, monotonic except near __t=1,
// bounded, determinate, and consistent:
const _Fp __x = __a + __t * (__b - __a);
return __t > 1 == __b > __a
? (__b < __x ? __x : __b)
: (__b > __x ? __x : __b); // monotonic near __t=1
}
constexpr float
lerp(float __a, float __b, float __t)
{ return std::__lerp(__a, __b, __t); }
constexpr double
lerp(double __a, double __b, double __t)
{ return std::__lerp(__a, __b, __t); }
constexpr long double
lerp(long double __a, long double __b, long double __t)
{ return std::__lerp(__a, __b, __t); }
#endif // C++20
_GLIBCXX_END_NAMESPACE_VERSION
} // namespace
#if _GLIBCXX_USE_STD_SPEC_FUNCS
# include "../bits/specfun.h"
#endif
} // extern "C++"
#endif
| [
"smallville7123"
] | smallville7123 |
|
af31c8e98827504d86873a9b19a162508f7e5846 | 435849051862b284b71c4517bf0695d41c217cd1 | /inheritance.cpp | 27c953577da4b4ecb7817f884b5cff3524a33270 | [] | no_license | iambramhaa/Aryalashok | 7afc49fe21dc65c3f7c3b88ab365796ff851a3f3 | 802a645acb42de05da4d1d088c1860c6fb9dffb9 | refs/heads/main | 2023-06-26T04:34:59.144585 | 2023-06-09T05:59:24 | 2023-06-09T05:59:24 | 379,574,076 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,178 | cpp | //C++ program to demonstrate inheritance
#include<iostream>
using namespace std;
// base class
class B
{
private:
int x;
protected:
int y;
public:
int z;
void getdata()
{
cout<<"Enter first number:";
cin>>x;
cout<<"Enter second number:";
cin>>y;
cout<<"Enter third number:";
cin>>z;
}
void showdata()
{
cout<<"X="<<x<<endl;
cout<<"Y="<<y<<endl;
cout<<"Z="<<z<<endl;
}
};
// derived class
class D : public B
{
private:
int k;
public:
void getk()
{
cout<<"Enter the value of k:";
cin>>k;
}
void output()
{
cout<<"K="<<k<<endl;
int s;
s=y+z+k;
cout<<"Sum of Y,Z & K="<<s;
}
};
int main()
{
// Create object of the D class
D d1;
// Calling members of the base class
d1.getdata();
d1.showdata();
// Calling member of the derived class
d1.getk();
d1.output();
return 0;
}
| [
"[email protected]"
] | |
7dc20af243a82a28c1adaac638b452b562cd911a | 02180b5871fed64aae1726c19ba8d4e482aa1180 | /YYacc/io.cpp | df8e51e801cd067edda5d8510ae1de4ecfb6a4be | [] | no_license | CyanideCentral/YYacc-Syntax-Parser | befca320db638384091c725e56cfa93c56b953f2 | 740c63ff0f9ff4005d09243800b8566059e84e4e | refs/heads/master | 2021-08-19T13:50:28.061960 | 2017-11-26T13:47:01 | 2017-11-26T13:47:01 | 110,690,097 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,662 | cpp | #include"class.h"
vector<string>* split(const string& str, const string& delimiters) {
string s = "";
vector<string>* substrs = new vector<string>;
for (int ptr = 0; ptr < str.length(); ptr++) {
//One of delimiters found
if (delimiters.find_first_of(str[ptr]) != string::npos) {
if (s.length() > 0) {
substrs->push_back(s);
s = string();
}
}
else {
s.push_back(str[ptr]);
}
}
if (s.length() > 0) {
substrs->push_back(s);
}
return substrs;
}
bool isWhiteSpace(const string& line) {
string ws = " \t\r\n";
for (int i = 0; i < line.length(); i++) {
if (ws.find_first_of(line[i]) == string::npos) return false;
}
return true;
}
void run() {
ifstream ifs;
ofstream ofs;
string fname;
int ln = 0;
//Request .y file
while (1) {
cout << "Please enter the path of yacc file:" << endl;
getline(cin, fname);
ifs.open(fname, ifstream::in);
if (ifs.is_open()) break;
cout << "File not found." << endl;
}
vector<string>* tokenlist = new vector<string>;
vector<Production*>* grammar = new vector<Production*>;
string line;
//Read tokens and start symbol
while (1) {
getline(ifs, line);
ln++;
if (isWhiteSpace(line)) {
continue;
}
if (line.substr(0, 2).compare("%%") == 0) {
break;
}
else if (line.substr(0, 6).compare("%token") == 0) {
vector<string>* sublist = split(line.substr(6), "\t ");
tokenlist->insert(tokenlist->end(), sublist->begin(), sublist->end());
delete sublist;
}
else if (line.substr(0, 6).compare("%start") == 0) {
if (grammar->size() > 0) {
cout << "Warning: multiple start symbols" << endl;
}
else {
//Add production S'->S
vector<string>* sublist = split(line.substr(6), " \t");
Production* first = new Production();
first->left = "S'";
first->right->push_back(sublist->at(0));
grammar->push_back(first);
delete sublist;
}
}
}
//Read Productions
string current = "";
while (1) {
getline(ifs, line);
ln++;
if (ifs.eof()) break;
//Delete comment section
int comment = line.find("/*");
if (comment != string::npos) {
line = line.substr(0, comment);
}
if (isWhiteSpace(line)) continue;
//New left symbol
if (line[0] != '\t'&&line[0] != ' ') {
vector<string>* strs = split(line, " \t");
if (line.substr(0, 2).compare("%%") == 0) {
break;
}
current = strs->at(0);
}
if (current.empty()) {
cout << "Warning: wrong syntax at line " << ln << endl;
}
//End of this left symbol's productions
if (line.substr(0, 2).compare("\t;") == 0) {
current = "";
}
//New production
if (line.substr(0, 2).compare("\t:") == 0 || line.substr(0, 2).compare("\t|") == 0) {
Production* p = new Production();
p->left = current;
delete p->right;
p->right = split(line.substr(2), " \t");
grammar->push_back(p);
//cout << p->toString();
}
}
string codeHead = "";
while (1) {
getline(ifs, line);
ln++;
if (ifs.eof()) break;
codeHead.append(line);
}
ifs.close();
GrammarAnalyzer* analyzer = new GrammarAnalyzer();
string pt = analyzer->toParsingTable(grammar, tokenlist);
while (1) {
cout << "Path of file to save source code of generated syntax analyzer:" << endl;
getline(cin, fname);
ofs.open(fname, ofstream::out | ofstream::trunc);
if (ofs.is_open()) break;
cout << "Invalid path." << endl;
}
//Code declaring production vector
ofs << "#include<iostream>\n#include<sstream>\n#include<fstream>\n#include<string>\n#include<algorithm>\n#include<unordered_set>\n#include<unordered_map>\n#include<vector>\n#include<stack>\n\nusing namespace std;\n\nvector<string>* split(const string& str, const string& delimiters) {\n\tstring s = \"\";\n\tvector<string>* substrs = new vector<string>;\n\tfor (int ptr = 0; ptr < str.length(); ptr++) {\n\t\t//One of delimiters found\n\t\tif (delimiters.find_first_of(str[ptr]) != string::npos) {\n\t\t\tif (s.length() > 0) {\n\t\t\t\tsubstrs->push_back(s);\n\t\t\t\ts = string();\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\ts.push_back(str[ptr]);\n\t\t}\n\t}\n\tif (s.length() > 0) {\n\t\tsubstrs->push_back(s);\n\t}\n\treturn substrs;\n}\n\nbool isWhiteSpace(const string& line) {\n\tstring ws = \" \\t\\r\\n\";\n\tfor (int i = 0; i < line.length(); i++) {\n\t\tif (ws.find_first_of(line[i]) == string::npos) return false;\n\t}\n\treturn true;\n}\n\nclass Production {\npublic:\n\tstring left;\n\tvector<string>* right;\n\n\tProduction(string leftNT);\n\t~Production();\n\tstring toString();\n\tProduction* extendRight(string symbol);\n\tProduction* clone();\n};\n\nProduction::Production(string leftNT) {\n\tleft = leftNT;\n\tright = new vector<string>;\n}\n\nProduction::~Production() {\n\tdelete right;\n}\n\nstring Production::toString() {\n\tostringstream os;\n\tos << left << \" -> \";\n\tfor (int i = 0; i < right->size(); i++) {\n\t\tos << right->at(i) << \" \";\n\t}\n\treturn os.str();\n}\n\nProduction * Production::extendRight(string symbol) {\n\tright->push_back(symbol);\n\treturn this;\n}\n\nProduction * Production::clone() {\n\tProduction* copy = new Production(left);\n\tfor (int i = 0; i < right->size(); i++) {\n\t\tcopy->right->push_back((*right)[i]);\n\t}\n\treturn copy;\n}\n\nclass Parser {\nprivate:\n\tvector<Production*>* grammar;\n\tvector<unordered_map<string, int>*>* pt;\npublic:\n\tParser(vector<Production*>* augGrammar, vector<unordered_map<string, int>*>* parsingTable);\n\t~Parser();\n\tvoid parse(vector<string>* tokens, ostream& out);\n};\n\nParser::Parser(vector<Production*>* augGrammar, vector<unordered_map<string, int>*>* parsingTable) {\n\tgrammar = augGrammar;\n\tpt = parsingTable;\n}\n\nParser::~Parser() {\n\tdelete grammar;\n\tdelete pt;\n}\n\nvoid Parser::parse(vector<string>* tokens, ostream & out) {\n\tint state = 0, i = 0;\n\ttokens->push_back(\"'$'\");\n\tstack<int>* stateStack = new stack<int>;\n\tstateStack->push(0);\n\tstack<string>* symbolStack = new stack<string>;\n\ttry {\n\t\twhile (1) {\n\t\t\tint action = pt->at(stateStack->top())->at(tokens->at(i));\n\t\t\t//shift\n\t\t\tif (action >= 0) {\n\t\t\t\tstateStack->push(action);\n\t\t\t\tsymbolStack->push(tokens->at(i));\n\t\t\t\ti++;\n\t\t\t}\n\t\t\t//reduce\n\t\t\telse {\n\t\t\t\taction = -action - 1;\n\t\t\t\tint plen = grammar->at(action)->right->size();\n\t\t\t\tfor (int j = 0; j < plen; j++) {\n\t\t\t\t\tstring back = symbolStack->top();\n\t\t\t\t\t//Production to reduce by contradicts with token in stack\n\t\t\t\t\tif (back.compare(grammar->at(action)->right->at(plen - 1 - j)) != 0) {\n\t\t\t\t\t\tcout << \"Parsing error at token #\" << i + 1 << \": \" << tokens->at(i);\n\t\t\t\t\t\tout << \" Parsing error encountered.\";\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tsymbolStack->pop();\n\t\t\t\t\tstateStack->pop();\n\t\t\t\t}\n\t\t\t\t//AKA 'acc'\n\t\t\t\tif (action == 0) {\n\t\t\t\t\tout << \"ACC\" << endl;\n\t\t\t\t\tcout << \"Parsing complete.\" << endl;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tout << grammar->at(action)->toString() << endl;\n\t\t\t\tsymbolStack->push(grammar->at(action)->left);\n\t\t\t\t//Perform goto\n\t\t\t\taction = pt->at(stateStack->top())->at(symbolStack->top());\n\t\t\t\tstateStack->push(action);\n\t\t\t}\n\t\t}\n\t}\n\tcatch (out_of_range e) {\n\t\tcout << \"Error caused by input.\" << endl;\n\t\treturn;\n\t}\n}\n\nint main() {\n";
ofs << endl << "vector<Production*>* grammar = new vector<Production*>();" << endl;
for (int i = 0; i < grammar->size(); i++) {
ofs << "grammar->push_back(new Production(\"" << grammar->at(i)->toString() << "\"));";
}
ofs << pt;
//main function
ofs << "\n\tifstream ifs;\n\tofstream ofs;\n\tstring fname;\n\tParser* parser = new Parser(grammar, pt);\n\twhile (1) {\n\t\twhile (1) {\n\t\t\tcout << \"Path of tokens file (or -q to quit):\" << endl;\n\t\t\tgetline(cin, fname);\n\t\t\tif (fname.compare(\"-q\") == 0) return 1;\n\t\t\tifs.open(fname);\n\t\t\tif (ifs.is_open()) break;\n\t\t\tcout << \"Invalid path.\" << endl;\n\t\t}\n\t\tbool toConsole = false;\n\t\twhile (1) {\n\t\t\tcout << \"Path of file to save sequence of reductions (or -c to show in console):\" << endl;\n\t\t\tgetline(cin, fname);\n\t\t\tif (fname.compare(\"-c\") == 0) {\n\t\t\t\ttoConsole = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tofs.open(fname, ofstream::out | ofstream::trunc);\n\t\t\tif (ofs.is_open()) break;\n\t\t\tcout << \"Invalid path.\" << endl;\n\t\t}\n\t\tvector<string>* input = new vector<string>;\n\t\twhile (1) {\n\t\t\tstring line;\n\t\t\tif (ifs.eof()) break;\n\t\t\tgetline(ifs, line);\n\t\t\tif (line.empty()) continue;\n\t\t\tinput->push_back(line);\n\t\t}\n\t\tparser->parse(input, toConsole ? cout : ofs);\n\t}\n\treturn 1;\n}";
cout << "Source code generated successfully." << endl;
} | [
"[email protected]"
] | |
011bada5ae2db628e01603729a6b6f024e219832 | c51369ec10ea3ed8f58c60bf10c592d4d5a0f742 | /03BuildingEscape/BuildingEscape/Source/BuildingEscape/Grabber.cpp | 6de8947c548c0d6b6fae7e415ca398bed80182c8 | [] | no_license | JonahBrooks/UnrealCourse | 6a3a1a0d8ef85accb3c67320cf336e9c2ff1b673 | ccc20379e9e300ab3d762e24e6791c2c7ef8a4e4 | refs/heads/master | 2021-01-15T16:42:53.692494 | 2020-06-09T04:39:26 | 2020-06-09T04:39:26 | 99,720,773 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,118 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "Grabber.h"
// Sets default values for this component's properties
UGrabber::UGrabber()
{
// Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
// off to improve performance if you don't need them.
PrimaryComponentTick.bCanEverTick = true;
// ...
}
// Called when the game starts
void UGrabber::BeginPlay()
{
Super::BeginPlay();
// ...
FindPhysicsHandleComponent();
SetupInputComponent();
}
/// Look for Physics Handle Component
void UGrabber::FindPhysicsHandleComponent()
{
PhysicsHandle = GetOwner()->FindComponentByClass<UPhysicsHandleComponent>();
if (!PhysicsHandle)
{
UE_LOG(LogTemp, Error, TEXT("%s: Physics Handle not found!"), *GetOwner()->GetName());
}
}
/// Look for attached input component that only appears at runtime
void UGrabber::SetupInputComponent()
{
InputComponent = GetOwner()->FindComponentByClass<UInputComponent>();
if (InputComponent)
{
InputComponent->BindAction("Grab", IE_Pressed, this, &UGrabber::Grab);
InputComponent->BindAction("Grab", IE_Released, this, &UGrabber::Release);
}
else
{
UE_LOG(LogTemp, Error, TEXT("%s: InputComponent not found!"), *GetOwner()->GetName());
}
}
FHitResult UGrabber::GetFirstPhysicsBodyInReach() const
{
/// Draw a red trace in the world to visualize
/*DrawDebugLine(
GetWorld(),
GetReachLineStart(),
GetReachLineEnd(),
FColor(255, 0, 0),
false,
0.f,
0,
10.f
);*/
///Setup Query parameters
FCollisionQueryParams TraceParameters = FCollisionQueryParams(TEXT(""), false, GetOwner());
/// Line-trace stuff
FHitResult Hit;
/// Ray-cast out to reach distance
GetWorld()->LineTraceSingleByObjectType(
Hit,
GetReachLineStart(),
GetReachLineEnd(),
FCollisionObjectQueryParams(ECollisionChannel::ECC_PhysicsBody),
TraceParameters
);
/// See what we hit
AActor* ActorHit = Hit.GetActor();
if (ActorHit)
{
UE_LOG(LogTemp, Warning, TEXT("LineTrace Hit: %s"), *(ActorHit->GetName()));
}
return Hit;
}
FVector UGrabber::GetReachLineEnd() const
{
FVector PlayerViewPointLocation;
FRotator PlayerViewPointRotation;
GetWorld()->GetFirstPlayerController()->GetPlayerViewPoint(PlayerViewPointLocation, PlayerViewPointRotation);
FVector LineTraceEnd = PlayerViewPointLocation + PlayerViewPointRotation.Vector()*Reach;
return LineTraceEnd;
}
FVector UGrabber::GetReachLineStart() const
{
FVector PlayerViewPointLocation;
FRotator PlayerViewPointRotation;
GetWorld()->GetFirstPlayerController()->GetPlayerViewPoint(PlayerViewPointLocation, PlayerViewPointRotation);
return PlayerViewPointLocation;
}
void UGrabber::Grab()
{
UE_LOG(LogTemp, Warning, TEXT("Grab key pressed!"));
/// LINE TRACE and see if we reach any actors with physics body collision channel set
FHitResult HitResult = GetFirstPhysicsBodyInReach();
UPrimitiveComponent* ComponentToGrab = HitResult.GetComponent();
AActor* ActorHit = HitResult.GetActor();
if (ActorHit)
{
// Or GrabComponentAtLocationWithRotation and supply ~->GetActorRotation()
PhysicsHandle->GrabComponentAtLocationWithRotation(
ComponentToGrab,
NAME_None,
ComponentToGrab->GetOwner()->GetActorLocation(),
ComponentToGrab->GetOwner()->GetActorRotation()
);
}
/// If we hit something, then attach a physics handle
// TODO: Attach physics handle
}
void UGrabber::Release()
{
UE_LOG(LogTemp, Warning, TEXT("Grab key released!"));
// TODO: Release physics handle
PhysicsHandle->ReleaseComponent();
}
// Called every frame
void UGrabber::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
// ...
// If physics handle is attached
if (PhysicsHandle->GrabbedComponent)
{
// move object we're holding
PhysicsHandle->SetTargetLocation(GetReachLineEnd());
}
}
| [
"[email protected]"
] | |
1d952635dd899f90872e396d9592cd255deca158 | caa8711db4a8c88ece0d36747a72ef94e9f70fef | /p246/kingquote/HqWxUi/HqDataModel.h | 0084ddfef3868cb8046b14b802dc270441ecceac | [] | no_license | freestockso/p135 | a773b47fe293f9d485482b18647cbcd49b019ff1 | dfe7f43f95dc565cc0e3a5ff71c53696e03b5c1f | refs/heads/master | 2020-12-11T07:25:18.969006 | 2016-06-25T07:32:26 | 2016-06-25T07:32:26 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,069 | h | #pragma once
#include "MyVListCtrl.h"
#include "../HqStorage/HqFile.h"
enum HqField
{
Fld_Code = 0,
Fld_Name,
FLd_LastMin,//最后分钟线
Fld_LastTime,//最后时间
Fld_Zdz,//涨跌值
Fld_Zdf,//涨跌幅
Fld_Preclose,
Fld_Openpx,
Fld_Highpx,
Fld_Lowpx,
Fld_Newpx,
Fld_Vol,
Fld_Money,
Fld_Position,
Fld_Max,
};
class HqDataModel : public MyListCtrlDataProvider
{
public:
HqDataModel();
~HqDataModel();
public:
void sethq(HqFile *hf)
{
m_hq = hf;
}
HqFile *gethq()
{
return m_hq;
}
void InitLc(MyVListCtrl *mlc);
//主要是要重载这个!!!
virtual wxString OnGetItemText(long item, long column) const;
virtual int OnGetItemCount();
virtual wxListItemAttr *OnGetItemColumnAttr(long item, long WXUNUSED(column))
{
if (item % 2)
{
return &m_attrForOddRows;
}
else
{
return &m_defaultCellAttr;
}
}
protected:
HqFile* m_hq;
wxArrayString m_colLabels;
wxListItemAttr m_attrForOddRows;
wxListItemAttr m_defaultCellAttr;
};
| [
"[email protected]"
] | |
8025768d92cfc908151ac5b2999fa42e683c017e | ed464cced849ae92b540f52c1d5f11ee16984fa6 | /Shootout Client/Shootout Client/player.h | 63c16fbb05ab12576e4dcba524b444249cf1b52c | [] | no_license | Tomiyou/Shootout-matura | 67dffc5c0a1f67ec3280cc555a7968c271984b2c | 1f835c9ecaab11244f999fe620afb225d14b11b7 | refs/heads/master | 2020-04-30T00:58:48.280368 | 2019-03-19T13:39:12 | 2019-03-19T13:39:12 | 176,516,210 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 895 | h | #ifndef PLAYER_H
#define PLAYER_H
#include "animatedsprite.h"
#include "globals.h"
#include "movement.h"
#include "Interpolator.h"
class Graphics;
class Player : public PlayerEntity {
public:
Player();
Player(Graphics &graphics, float x, float y, int id, char * name);
~Player();
void draw(Graphics &graphics);
void update(float &elapsedTime);
virtual void animationDone(int currentAnimation);
void setupAnimations();
// Moves player in direction by "dx" and "dy"
void moveLeft();
void moveRight();
void moveUp();
void moveDown();
void stopMoving();
void handleTileCollisions(std::vector<Rectangle> &others);
bool bulletCollision(const Rectangle &other);
void updatePosition(int ticks, int &x, int &y, int &hp);
int getHP();
private:
Direction _facing;
Movement _movement;
Interpolate _interpolate;
float _dx, _dy;
};
#endif
| [
"[email protected]"
] | |
979379d8954f749ac39c5ccf97cf8bd8431aaaa2 | 9d364070c646239b2efad7abbab58f4ad602ef7b | /platform/external/chromium_org/win8/test/open_with_dialog_controller.h | bfa49d8a8d7517bdbfbebc16eee258ffba7bfe1d | [
"BSD-3-Clause"
] | permissive | denix123/a32_ul | 4ffe304b13c1266b6c7409d790979eb8e3b0379c | b2fd25640704f37d5248da9cc147ed267d4771c2 | refs/heads/master | 2021-01-17T20:21:17.196296 | 2016-08-16T04:30:53 | 2016-08-16T04:30:53 | 65,786,970 | 0 | 2 | null | 2020-03-06T22:00:52 | 2016-08-16T04:15:54 | null | UTF-8 | C++ | false | false | 1,254 | h | // Copyright (c) 2013 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.
#ifndef WIN8_TEST_OPEN_WITH_DIALOG_CONTROLLER_H_
#define WIN8_TEST_OPEN_WITH_DIALOG_CONTROLLER_H_
#include <windows.h>
#include <vector>
#include "base/basictypes.h"
#include "base/callback_forward.h"
#include "base/memory/weak_ptr.h"
#include "base/strings/string16.h"
namespace win8 {
class OpenWithDialogController {
public:
typedef base::Callback<void(HRESULT, std::vector<base::string16>)>
SetDefaultCallback;
OpenWithDialogController();
~OpenWithDialogController();
void Begin(HWND parent_window,
const base::string16& url_protocol,
const base::string16& program,
const SetDefaultCallback& callback);
HRESULT RunSynchronously(HWND parent_window,
const base::string16& url_protocol,
const base::string16& program,
std::vector<base::string16>* choices);
private:
class Context;
base::WeakPtr<Context> context_;
DISALLOW_COPY_AND_ASSIGN(OpenWithDialogController);
};
}
#endif
| [
"[email protected]"
] | |
24941ae4c45b4697cd4a107ec0e8eecb15cdc04c | 21d23b20ff0484bbeae121d31ece49141f1a29bf | /soccer-2018/Main/Dribbler.ino | 030a40da246d7a73592357e11658f99ec9a8f0f6 | [
"MIT"
] | permissive | zwliew/RoboCup | 53bdc5a0d774d59fd3bbe21eeac591abffe49489 | 5ee079dd9d9871aa992f665eb642617035ab6178 | refs/heads/master | 2021-09-28T20:42:14.520536 | 2018-11-20T11:22:09 | 2018-11-20T11:22:21 | 114,205,560 | 0 | 0 | null | 2018-11-20T11:22:23 | 2017-12-14T05:14:24 | C++ | UTF-8 | C++ | false | false | 428 | ino | #define SPD_DRIB 2
#define DIR_DRIB 43
void InitDribbler() {
pinMode(DIR_DRIB, OUTPUT);
// Dribble outwards if the bot is the goalie, inwards otherwise.
#ifdef IS_STRIKER
digitalWrite(DIR_DRIB, LOW);
#else
digitalWrite(DIR_DRIB, HIGH);
#endif
#ifdef NO_DEBUG_OPT
Serial.println("Initialized dribbler.");
#endif
}
void Dribble() {
analogWrite(SPD_DRIB, 100);
}
void StopDribble() {
analogWrite(SPD_DRIB, 0);
}
| [
"[email protected]"
] | |
3c57de97be4456332c94ffb63e32b7f3f0d8f2b3 | e94d402c7e0142a88529f8bd14fe3142ee59c1e6 | /tools/muscle3.7/params.cpp | 70d39e3c7e72579e4bb4178e634ee80053194d1d | [] | no_license | shivashamloo/tcp-follow_up | 91610204771ba99c87a210c8e513b1c511e69100 | e483db1b2768f882a837e6fca695939d26371c94 | refs/heads/master | 2020-07-22T09:26:33.309331 | 2020-04-15T20:00:51 | 2020-04-15T20:00:51 | 207,148,876 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,027 | cpp | #include "muscle.h"
#include "objscore.h"
#include "profile.h"
#include "enumopts.h"
const double DEFAULT_MAX_MB_FRACT = 0.8;
SCORE g_scoreCenter = 0;
SCORE g_scoreGapExtend = 0;
SCORE g_scoreGapOpen2 = MINUS_INFINITY;
SCORE g_scoreGapExtend2 = MINUS_INFINITY;
SCORE g_scoreGapAmbig = 0;
SCORE g_scoreAmbigFactor = 0;
extern SCOREMATRIX VTML_LA;
extern SCOREMATRIX PAM200;
extern SCOREMATRIX PAM200NoCenter;
extern SCOREMATRIX VTML_SP;
extern SCOREMATRIX VTML_SPNoCenter;
extern SCOREMATRIX NUC_SP;
PTR_SCOREMATRIX g_ptrScoreMatrix;
const char *g_pstrInFileName = "-";
const char *g_pstrOutFileName = "-";
const char *g_pstrFASTAOutFileName = 0;
const char *g_pstrMSFOutFileName = 0;
const char *g_pstrClwOutFileName = 0;
const char *g_pstrClwStrictOutFileName = 0;
const char *g_pstrHTMLOutFileName = 0;
const char *g_pstrPHYIOutFileName = 0;
const char *g_pstrPHYSOutFileName = 0;
const char *g_pstrDistMxFileName1 = 0;
const char *g_pstrDistMxFileName2 = 0;
const char *g_pstrFileName1 = 0;
const char *g_pstrFileName2 = 0;
const char *g_pstrSPFileName = 0;
const char *g_pstrMatrixFileName = 0;
const char *g_pstrUseTreeFileName = 0;
bool g_bUseTreeNoWarn = false;
const char *g_pstrComputeWeightsFileName;
const char *g_pstrScoreFileName;
const char *g_pstrProf1FileName = 0;
const char *g_pstrProf2FileName = 0;
unsigned g_uSmoothWindowLength = 7;
unsigned g_uAnchorSpacing = 32;
unsigned g_uMaxTreeRefineIters = 1;
unsigned g_uRefineWindow = 200;
unsigned g_uWindowFrom = 0;
unsigned g_uWindowTo = 0;
unsigned g_uSaveWindow = uInsane;
unsigned g_uWindowOffset = 0;
unsigned g_uMaxSubFamCount = 5;
unsigned g_uHydrophobicRunLength = 5;
float g_dHydroFactor = (float) 1.2;
unsigned g_uMinDiagLength = 24; // TODO alpha -- should depend on alphabet?
unsigned g_uMaxDiagBreak = 1;
unsigned g_uDiagMargin = 5;
float g_dSUEFF = (float) 0.1;
bool g_bPrecompiledCenter = true;
bool g_bNormalizeCounts = false;
bool g_bDiags1 = false;
bool g_bDiags2 = false;
bool g_bAnchors = true;
bool g_bQuiet = false;
bool g_bVerbose = false;
bool g_bRefine = false;
bool g_bRefineW = false;
bool g_bProfDB = false;
bool g_bLow = false;
bool g_bSW = false;
bool g_bClusterOnly = false;
bool g_bProfile = false;
bool g_bPPScore = false;
bool g_bBrenner = false;
bool g_bDimer = false;
bool g_bVersion = false;
bool g_bStable = false;
bool g_bFASTA = false;
bool g_bPAS = false;
bool g_bTomHydro = false;
bool g_bMakeTree = false;
#if DEBUG
bool g_bCatchExceptions = false;
#else
bool g_bCatchExceptions = true;
#endif
bool g_bMSF = false;
bool g_bAln = false;
bool g_bClwStrict = false;
bool g_bHTML = false;
bool g_bPHYI = false;
bool g_bPHYS = false;
unsigned g_uMaxIters = 8;
unsigned long g_ulMaxSecs = 0;
unsigned g_uMaxMB = 500;
PPSCORE g_PPScore = PPSCORE_LE;
OBJSCORE g_ObjScore = OBJSCORE_SPM;
SEQWEIGHT g_SeqWeight1 = SEQWEIGHT_ClustalW;
SEQWEIGHT g_SeqWeight2 = SEQWEIGHT_ClustalW;
DISTANCE g_Distance1 = DISTANCE_Kmer6_6;
DISTANCE g_Distance2 = DISTANCE_PctIdKimura;
CLUSTER g_Cluster1 = CLUSTER_UPGMB;
CLUSTER g_Cluster2 = CLUSTER_UPGMB;
ROOT g_Root1 = ROOT_Pseudo;
ROOT g_Root2 = ROOT_Pseudo;
bool g_bDiags;
SEQTYPE g_SeqType = SEQTYPE_Auto;
TERMGAPS g_TermGaps = TERMGAPS_Half;
//------------------------------------------------------
// These parameters depending on the chosen prof-prof
// score (g_PPScore), initialized to "Undefined".
float g_dSmoothScoreCeil = fInsane;
float g_dMinBestColScore = fInsane;
float g_dMinSmoothScore = fInsane;
SCORE g_scoreGapOpen = fInsane;
//------------------------------------------------------
static unsigned atou(const char *s)
{
return (unsigned) atoi(s);
}
const char *MaxSecsToStr()
{
if (0 == g_ulMaxSecs)
return "(No limit)";
return SecsToStr(g_ulMaxSecs);
}
void ListParams()
{
Log("\n");
Log("%s\n", MUSCLE_LONG_VERSION);
Log("http://www.drive5.com/muscle\n");
Log("\n");
Log("Profile-profile score %s\n", PPSCOREToStr(g_PPScore));
Log("Max iterations %u\n", g_uMaxIters);
Log("Max trees %u\n", g_uMaxTreeRefineIters);
Log("Max time %s\n", MaxSecsToStr());
Log("Max MB %u\n", g_uMaxMB);
Log("Gap open %g\n", g_scoreGapOpen);
Log("Gap extend (dimer) %g\n", g_scoreGapExtend);
Log("Gap ambig factor %g\n", g_scoreAmbigFactor);
Log("Gap ambig penalty %g\n", g_scoreGapAmbig);
Log("Center (LE) %g\n", g_scoreCenter);
Log("Term gaps %s\n", TERMGAPSToStr(g_TermGaps));
Log("Smooth window length %u\n", g_uSmoothWindowLength);
Log("Refine window length %u\n", g_uRefineWindow);
Log("Min anchor spacing %u\n", g_uAnchorSpacing);
Log("Min diag length (lambda) %u\n", g_uMinDiagLength);
Log("Diag margin (mu) %u\n", g_uDiagMargin);
Log("Min diag break %u\n", g_uMaxDiagBreak);
Log("Hydrophobic window %u\n", g_uHydrophobicRunLength);
Log("Hydrophobic gap factor %g\n", g_dHydroFactor);
Log("Smooth score ceiling %g\n", g_dSmoothScoreCeil);
Log("Min best col score %g\n", g_dMinBestColScore);
Log("Min anchor score %g\n", g_dMinSmoothScore);
Log("SUEFF %g\n", g_dSUEFF);
Log("Brenner root MSA %s\n", BoolToStr(g_bBrenner));
Log("Normalize counts %s\n", BoolToStr(g_bNormalizeCounts));
Log("Diagonals (1) %s\n", BoolToStr(g_bDiags1));
Log("Diagonals (2) %s\n", BoolToStr(g_bDiags2));
Log("Anchors %s\n", BoolToStr(g_bAnchors));
Log("MSF output format %s\n", BoolToStr(g_bMSF));
Log("Phylip interleaved %s\n", BoolToStr(g_bPHYI));
Log("Phylip sequential %s\n", BoolToStr(g_bPHYS));
Log("ClustalW output format %s\n", BoolToStr(g_bAln));
Log("Catch exceptions %s\n", BoolToStr(g_bCatchExceptions));
Log("Quiet %s\n", BoolToStr(g_bQuiet));
Log("Refine %s\n", BoolToStr(g_bRefine));
Log("ProdfDB %s\n", BoolToStr(g_bProfDB));
Log("Low complexity profiles %s\n", BoolToStr(g_bLow));
Log("Objective score %s\n", OBJSCOREToStr(g_ObjScore));
Log("Distance method (1) %s\n", DISTANCEToStr(g_Distance1));
Log("Clustering method (1) %s\n", CLUSTERToStr(g_Cluster1));
Log("Root method (1) %s\n", ROOTToStr(g_Root1));
Log("Sequence weighting (1) %s\n", SEQWEIGHTToStr(g_SeqWeight1));
Log("Distance method (2) %s\n", DISTANCEToStr(g_Distance2));
Log("Clustering method (2) %s\n", CLUSTERToStr(g_Cluster2));
Log("Root method (2) %s\n", ROOTToStr(g_Root2));
Log("Sequence weighting (2) %s\n", SEQWEIGHTToStr(g_SeqWeight2));
Log("\n");
}
static void SetDefaultsLE()
{
g_ptrScoreMatrix = &VTML_LA;
//g_scoreGapOpen = (SCORE) -3.00;
//g_scoreCenter = (SCORE) -0.55;
g_scoreGapOpen = (SCORE) -2.9;
g_scoreCenter = (SCORE) -0.52;
g_bNormalizeCounts = true;
//g_dSmoothScoreCeil = 5.0;
//g_dMinBestColScore = 4.0;
//g_dMinSmoothScore = 2.0;
g_dSmoothScoreCeil = 3.0;
g_dMinBestColScore = 2.0;
g_dMinSmoothScore = 1.0;
g_Distance1 = DISTANCE_Kmer6_6;
g_Distance2 = DISTANCE_PctIdKimura;
}
static void SetDefaultsSP()
{
g_ptrScoreMatrix = &PAM200;
g_scoreGapOpen = -1439;
g_scoreCenter = 0.0; // center pre-added into score mx
g_bNormalizeCounts = false;
g_dSmoothScoreCeil = 200.0;
g_dMinBestColScore = 300.0;
g_dMinSmoothScore = 125.0;
g_Distance1 = DISTANCE_Kmer6_6;
g_Distance2 = DISTANCE_PctIdKimura;
}
static void SetDefaultsSV()
{
g_ptrScoreMatrix = &VTML_SP;
g_scoreGapOpen = -300;
g_scoreCenter = 0.0; // center pre-added into score mx
g_bNormalizeCounts = false;
g_dSmoothScoreCeil = 90.0;
g_dMinBestColScore = 130.0;
g_dMinSmoothScore = 40.0;
g_Distance1 = DISTANCE_Kmer6_6;
g_Distance2 = DISTANCE_PctIdKimura;
}
//static void SetDefaultsSPN()
// {
// g_ptrScoreMatrix = &NUC_SP;
//
// g_scoreGapOpen = -400;
// g_scoreCenter = 0.0; // center pre-added into score mx
//
// g_bNormalizeCounts = false;
//
// g_dSmoothScoreCeil = 999.0; // disable
// g_dMinBestColScore = 90;
// g_dMinSmoothScore = 90;
//
// g_Distance1 = DISTANCE_Kmer4_6;
// g_Distance2 = DISTANCE_PctIdKimura;
// }
static void SetDefaultsSPN_DNA()
{
g_ptrScoreMatrix = &NUC_SP;
g_scoreGapOpen = -400;
g_scoreCenter = 0.0; // center pre-added into score mx
g_scoreGapExtend = 0.0;
g_bNormalizeCounts = false;
g_dSmoothScoreCeil = 999.0; // disable
g_dMinBestColScore = 90;
g_dMinSmoothScore = 90;
g_Distance1 = DISTANCE_Kmer4_6;
g_Distance2 = DISTANCE_PctIdKimura;
}
static void SetDefaultsSPN_RNA()
{
g_ptrScoreMatrix = &NUC_SP;
g_scoreGapOpen = -420;
g_scoreCenter = -300; // total center = NUC_EXTEND - 300
g_scoreGapExtend = 0.0;
g_bNormalizeCounts = false;
g_dSmoothScoreCeil = 999.0; // disable
g_dMinBestColScore = 90;
g_dMinSmoothScore = 90;
g_Distance1 = DISTANCE_Kmer4_6;
g_Distance2 = DISTANCE_PctIdKimura;
}
static void FlagParam(const char *OptName, bool *ptrParam, bool bValueIfFlagSet)
{
bool bIsSet = FlagOpt(OptName);
if (bIsSet)
*ptrParam = bValueIfFlagSet;
}
static void StrParam(const char *OptName, const char **ptrptrParam)
{
const char *opt = ValueOpt(OptName);
if (0 != opt)
*ptrptrParam = opt;
}
static void FloatParam(const char *OptName, float *ptrParam)
{
const char *opt = ValueOpt(OptName);
if (0 != opt)
*ptrParam = (float) atof(opt);
}
static void UintParam(const char *OptName, unsigned *ptrParam)
{
const char *opt = ValueOpt(OptName);
if (0 != opt)
*ptrParam = atou(opt);
}
static void EnumParam(const char *OptName, EnumOpt *Opts, int *Param)
{
const char *Value = ValueOpt(OptName);
if (0 == Value)
return;
for (;;)
{
if (0 == Opts->pstrOpt)
Quit("Invalid parameter -%s %s", OptName, Value);
if (0 == stricmp(Value, Opts->pstrOpt))
{
*Param = Opts->iValue;
return;
}
++Opts;
}
}
static void SetPPDefaultParams()
{
switch (g_PPScore)
{
case PPSCORE_SP:
SetDefaultsSP();
break;
case PPSCORE_LE:
SetDefaultsLE();
break;
case PPSCORE_SV:
SetDefaultsSV();
break;
case PPSCORE_SPN:
switch (g_Alpha)
{
case ALPHA_DNA:
SetDefaultsSPN_DNA();
break;
case ALPHA_RNA:
SetDefaultsSPN_RNA();
break;
default:
Quit("Invalid alpha %d", g_Alpha);
}
break;
default:
Quit("Invalid g_PPScore");
}
}
static void SetPPCommandLineParams()
{
FloatParam("GapOpen", &g_scoreGapOpen);
FloatParam("GapOpen2", &g_scoreGapOpen2);
FloatParam("GapExtend", &g_scoreGapExtend);
FloatParam("GapExtend2", &g_scoreGapExtend2);
FloatParam("GapAmbig", &g_scoreAmbigFactor);
FloatParam("Center", &g_scoreCenter);
FloatParam("SmoothScoreCeil", &g_dSmoothScoreCeil);
FloatParam("MinBestColScore", &g_dMinBestColScore);
FloatParam("MinSmoothScore", &g_dMinSmoothScore);
EnumParam("Distance", DISTANCE_Opts, (int *) &g_Distance1);
EnumParam("Distance", DISTANCE_Opts, (int *) &g_Distance2);
EnumParam("Distance1", DISTANCE_Opts, (int *) &g_Distance1);
EnumParam("Distance2", DISTANCE_Opts, (int *) &g_Distance2);
}
void SetPPScore(bool bRespectFlagOpts)
{
if (bRespectFlagOpts)
{
if (FlagOpt("SP"))
g_PPScore = PPSCORE_SP;
else if (FlagOpt("LE"))
g_PPScore = PPSCORE_LE;
else if (FlagOpt("SV"))
g_PPScore = PPSCORE_SV;
else if (FlagOpt("SPN"))
g_PPScore = PPSCORE_SPN;
}
switch (g_PPScore)
{
case PPSCORE_LE:
case PPSCORE_SP:
case PPSCORE_SV:
if (ALPHA_RNA == g_Alpha || ALPHA_DNA == g_Alpha)
g_PPScore = PPSCORE_SPN;
break;
case PPSCORE_SPN:
if (ALPHA_Amino == g_Alpha)
g_PPScore = PPSCORE_LE;
break;
}
SetPPDefaultParams();
SetPPCommandLineParams();
if (g_bVerbose)
ListParams();
}
void SetPPScore(PPSCORE p)
{
g_PPScore = p;
SetPPScore(true);
}
static void SetMaxSecs()
{
float fMaxHours = 0.0;
FloatParam("MaxHours", &fMaxHours);
if (0.0 == fMaxHours)
return;
g_ulMaxSecs = (unsigned long) (fMaxHours*60*60);
}
static bool CanDoLowComplexity()
{
if (g_SeqWeight1 != SEQWEIGHT_ClustalW)
return false;
if (1 == g_uMaxIters)
return true;
return g_SeqWeight2 == SEQWEIGHT_ClustalW;
}
bool MissingCommand()
{
if (strcmp(g_pstrInFileName, "-"))
return false;
if (0 != g_pstrFileName1)
return false;
if (0 != g_pstrSPFileName)
return false;
return true;
}
void SetParams()
{
SetMaxSecs();
StrParam("in", &g_pstrInFileName);
StrParam("out", &g_pstrOutFileName);
StrParam("FASTAOut", &g_pstrFASTAOutFileName);
StrParam("ClwOut", &g_pstrClwOutFileName);
StrParam("ClwStrictOut", &g_pstrClwStrictOutFileName);
StrParam("HTMLOut", &g_pstrHTMLOutFileName);
StrParam("PHYIOut", &g_pstrPHYIOutFileName);
StrParam("PHYSOut", &g_pstrPHYSOutFileName);
StrParam("MSFOut", &g_pstrMSFOutFileName);
StrParam("in1", &g_pstrFileName1);
StrParam("in2", &g_pstrFileName2);
StrParam("Matrix", &g_pstrMatrixFileName);
StrParam("SPScore", &g_pstrSPFileName);
StrParam("UseTree_NoWarn", &g_pstrUseTreeFileName);
if (0 != g_pstrUseTreeFileName)
g_bUseTreeNoWarn = true;
StrParam("UseTree", &g_pstrUseTreeFileName);
StrParam("ComputeWeights", &g_pstrComputeWeightsFileName);
StrParam("ScoreFile", &g_pstrScoreFileName);
StrParam("DistMx1", &g_pstrDistMxFileName1);
StrParam("DistMx2", &g_pstrDistMxFileName2);
FlagParam("Core", &g_bCatchExceptions, false);
FlagParam("NoCore", &g_bCatchExceptions, true);
FlagParam("Diags1", &g_bDiags1, true);
FlagParam("Diags2", &g_bDiags2, true);
bool Diags = false;
FlagParam("Diags", &Diags, true);
if (Diags)
{
g_bDiags1 = true;
g_bDiags2 = true;
}
FlagParam("Anchors", &g_bAnchors, true);
FlagParam("NoAnchors", &g_bAnchors, false);
FlagParam("Quiet", &g_bQuiet, true);
FlagParam("Verbose", &g_bVerbose, true);
FlagParam("Version", &g_bVersion, true);
FlagParam("Stable", &g_bStable, true);
FlagParam("Group", &g_bStable, false);
FlagParam("Refine", &g_bRefine, true);
FlagParam("RefineW", &g_bRefineW, true);
FlagParam("ProfDB", &g_bProfDB, true);
FlagParam("SW", &g_bSW, true);
FlagParam("ClusterOnly", &g_bClusterOnly, true);
FlagParam("Profile", &g_bProfile, true);
FlagParam("PPScore", &g_bPPScore, true);
FlagParam("Brenner", &g_bBrenner, true);
FlagParam("Dimer", &g_bDimer, true);
FlagParam("MSF", &g_bMSF, true);
FlagParam("PHYI", &g_bPHYI, true);
FlagParam("PHYS", &g_bPHYS, true);
FlagParam("clw", &g_bAln, true);
FlagParam("HTML", &g_bHTML, true);
FlagParam("FASTA", &g_bFASTA, true);
FlagParam("PAS", &g_bPAS, true);
FlagParam("MakeTree", &g_bMakeTree, true);
bool b = false;
FlagParam("clwstrict", &b, true);
if (b)
{
g_bAln = true;
g_bClwStrict = true;
}
UintParam("MaxIters", &g_uMaxIters);
UintParam("MaxTrees", &g_uMaxTreeRefineIters);
UintParam("SmoothWindow", &g_uSmoothWindowLength);
UintParam("RefineWindow", &g_uRefineWindow);
UintParam("FromWindow", &g_uWindowFrom);
UintParam("ToWindow", &g_uWindowTo);
UintParam("SaveWindow", &g_uSaveWindow);
UintParam("WindowOffset", &g_uWindowOffset);
UintParam("AnchorSpacing", &g_uAnchorSpacing);
UintParam("DiagLength", &g_uMinDiagLength);
UintParam("DiagMargin", &g_uDiagMargin);
UintParam("DiagBreak", &g_uMaxDiagBreak);
UintParam("MaxSubFam", &g_uMaxSubFamCount);
UintParam("Hydro", &g_uHydrophobicRunLength);
FlagParam("TomHydro", &g_bTomHydro, true);
if (g_bTomHydro)
g_uHydrophobicRunLength = 0;
FloatParam("SUEFF", &g_dSUEFF);
FloatParam("HydroFactor", &g_dHydroFactor);
EnumParam("ObjScore", OBJSCORE_Opts, (int *) &g_ObjScore);
EnumParam("TermGaps", TERMGAPS_Opts, (int *) &g_TermGaps);
EnumParam("Weight", SEQWEIGHT_Opts, (int *) &g_SeqWeight1);
EnumParam("Weight", SEQWEIGHT_Opts, (int *) &g_SeqWeight2);
EnumParam("Weight1", SEQWEIGHT_Opts, (int *) &g_SeqWeight1);
EnumParam("Weight2", SEQWEIGHT_Opts, (int *) &g_SeqWeight2);
EnumParam("Cluster", CLUSTER_Opts, (int *) &g_Cluster1);
EnumParam("Cluster", CLUSTER_Opts, (int *) &g_Cluster2);
EnumParam("Cluster1", CLUSTER_Opts, (int *) &g_Cluster1);
EnumParam("Cluster2", CLUSTER_Opts, (int *) &g_Cluster2);
EnumParam("Root1", ROOT_Opts, (int *) &g_Root1);
EnumParam("Root2", ROOT_Opts, (int *) &g_Root2);
EnumParam("SeqType", SEQTYPE_Opts, (int *) &g_SeqType);
g_scoreGapAmbig = g_scoreGapOpen*g_scoreAmbigFactor;
g_bLow = CanDoLowComplexity();
if (g_bDimer)
g_bPrecompiledCenter = false;
UintParam("MaxMB", &g_uMaxMB);
if (0 == ValueOpt("MaxMB"))
g_uMaxMB = (unsigned) (GetRAMSizeMB()*DEFAULT_MAX_MB_FRACT);
}
| [
"[email protected]"
] | |
01ff7f9e26d472c1f18f65d074a05f077ce977d2 | 20c619a9216f2d9c70d384efc7f1427c1a149d5f | /Views/BattleWidget/battleWidget.h | af6c1933242656169e11b7df8186ae8dbb898329 | [] | no_license | guillaumeCombacal/JeuxDeRole | 583e491f6145a8d357a02f340722fddacc70225e | 4bc82472867b9db4b675b20d063c0ce8d7d21c58 | refs/heads/master | 2021-06-15T01:45:03.806625 | 2021-02-12T07:32:23 | 2021-02-12T07:32:23 | 136,516,660 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 325 | h | #ifndef BATTLEWIDGET_H
#define BATTLEWIDGET_H
#include <QWidget>
#include<QVBoxLayout>
#include<QLineEdit>
class BattleWidget : public QWidget
{
Q_OBJECT
private:
QVBoxLayout* m_pLayoutBattleMapWidget;
public:
explicit BattleWidget(QWidget *parent = 0);
signals:
public slots:
};
#endif // BATTLEWIDGET_H
| [
"[email protected]"
] | |
681abfc7350d8104f8ee75f86a29308165774ef1 | 3cf9e141cc8fee9d490224741297d3eca3f5feff | /C++ Benchmark Programs/Benchmark Files 1/classtester/autogen-sources/source-11997.cpp | b3aed038508a76fb0ea161e3ef53c6d7ae95b79b | [] | no_license | TeamVault/tauCFI | e0ac60b8106fc1bb9874adc515fc01672b775123 | e677d8cc7acd0b1dd0ac0212ff8362fcd4178c10 | refs/heads/master | 2023-05-30T20:57:13.450360 | 2021-06-14T09:10:24 | 2021-06-14T09:10:24 | 154,563,655 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,711 | cpp | struct c0;
void __attribute__ ((noinline)) tester0(c0* p);
struct c0
{
bool active0;
c0() : active0(true) {}
virtual ~c0()
{
tester0(this);
active0 = false;
}
virtual void f0(){}
};
void __attribute__ ((noinline)) tester0(c0* p)
{
p->f0();
}
struct c1;
void __attribute__ ((noinline)) tester1(c1* p);
struct c1
{
bool active1;
c1() : active1(true) {}
virtual ~c1()
{
tester1(this);
active1 = false;
}
virtual void f1(){}
};
void __attribute__ ((noinline)) tester1(c1* p)
{
p->f1();
}
struct c2;
void __attribute__ ((noinline)) tester2(c2* p);
struct c2 : virtual c1
{
bool active2;
c2() : active2(true) {}
virtual ~c2()
{
tester2(this);
c1 *p1_0 = (c1*)(c2*)(this);
tester1(p1_0);
active2 = false;
}
virtual void f2(){}
};
void __attribute__ ((noinline)) tester2(c2* p)
{
p->f2();
if (p->active1)
p->f1();
}
struct c3;
void __attribute__ ((noinline)) tester3(c3* p);
struct c3 : virtual c2, c0
{
bool active3;
c3() : active3(true) {}
virtual ~c3()
{
tester3(this);
c0 *p0_0 = (c0*)(c3*)(this);
tester0(p0_0);
c1 *p1_0 = (c1*)(c2*)(c3*)(this);
tester1(p1_0);
c2 *p2_0 = (c2*)(c3*)(this);
tester2(p2_0);
active3 = false;
}
virtual void f3(){}
};
void __attribute__ ((noinline)) tester3(c3* p)
{
p->f3();
if (p->active0)
p->f0();
if (p->active1)
p->f1();
if (p->active2)
p->f2();
}
struct c4;
void __attribute__ ((noinline)) tester4(c4* p);
struct c4 : c0, virtual c2, virtual c1
{
bool active4;
c4() : active4(true) {}
virtual ~c4()
{
tester4(this);
c0 *p0_0 = (c0*)(c4*)(this);
tester0(p0_0);
c1 *p1_0 = (c1*)(c2*)(c4*)(this);
tester1(p1_0);
c1 *p1_1 = (c1*)(c4*)(this);
tester1(p1_1);
c2 *p2_0 = (c2*)(c4*)(this);
tester2(p2_0);
active4 = false;
}
virtual void f4(){}
};
void __attribute__ ((noinline)) tester4(c4* p)
{
p->f4();
if (p->active0)
p->f0();
if (p->active1)
p->f1();
if (p->active2)
p->f2();
}
int __attribute__ ((noinline)) inc(int v) {return ++v;}
int main()
{
c0* ptrs0[25];
ptrs0[0] = (c0*)(new c0());
ptrs0[1] = (c0*)(c3*)(new c3());
ptrs0[2] = (c0*)(c4*)(new c4());
for (int i=0;i<3;i=inc(i))
{
tester0(ptrs0[i]);
delete ptrs0[i];
}
c1* ptrs1[25];
ptrs1[0] = (c1*)(new c1());
ptrs1[1] = (c1*)(c2*)(new c2());
ptrs1[2] = (c1*)(c2*)(c3*)(new c3());
ptrs1[3] = (c1*)(c2*)(c4*)(new c4());
ptrs1[4] = (c1*)(c4*)(new c4());
for (int i=0;i<5;i=inc(i))
{
tester1(ptrs1[i]);
delete ptrs1[i];
}
c2* ptrs2[25];
ptrs2[0] = (c2*)(new c2());
ptrs2[1] = (c2*)(c3*)(new c3());
ptrs2[2] = (c2*)(c4*)(new c4());
for (int i=0;i<3;i=inc(i))
{
tester2(ptrs2[i]);
delete ptrs2[i];
}
c3* ptrs3[25];
ptrs3[0] = (c3*)(new c3());
for (int i=0;i<1;i=inc(i))
{
tester3(ptrs3[i]);
delete ptrs3[i];
}
c4* ptrs4[25];
ptrs4[0] = (c4*)(new c4());
for (int i=0;i<1;i=inc(i))
{
tester4(ptrs4[i]);
delete ptrs4[i];
}
return 0;
}
| [
"[email protected]"
] | |
93a99011e32b174875eb17b7f5571636cded176f | 3c0327cdc6e7faf2f155c3410a04bdfa2f74fa32 | /src/chartcolor.cpp | b25fab7adcc5eaae5c6744a86998e7b236b40b53 | [] | no_license | cqin5/OMBI2013 | 6a98bc6010211b160befa510fcb8068c95860c10 | c4bab5d0f02cacc582162f00e7e7a25a38393f8e | refs/heads/master | 2020-12-24T17:26:58.319268 | 2013-12-04T20:24:34 | 2013-12-04T20:24:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,165 | cpp | #include "chartcolor.h"
/*!
* Author: Chuhan Qin, Group 6
* Description: This is the main window which is responsible for creating the graph,
* data passed to main window through the stub and are used for plotting
* Date: November 28, 2013
*/
/*!
* \brief chartcolour::chartcolour A library of eight different colours.
*/
chartcolour::chartcolour()
{
//! Set a color for each city based on the order of the cities in the list
colourLib.append(QColor(51,153,51)); //! Modern Green
colourLib.append(QColor(229,20,0)); //! Modern Red
colourLib.append(QColor(27,161,226)); //! Modern Blue
colourLib.append(QColor(240,150,9)); //! Modern Orange
colourLib.append(QColor(230,113,184)); //! Modern Pink
colourLib.append(QColor(160,80,0)); //! Modern Brown
colourLib.append(QColor(0,171,169)); //! Modern Teal
colourLib.append(QColor(162,0,255)); //! Modern Purple
}
/*!
* \brief chartcolour::getColour Returns a fancy colour
* \param i the index of the bar
* \return QColor based on the index
*/
QColor chartcolour::getColour(int i){
int code = i;
if(i>7)
code = code % 8;
return colourLib.at(code);
}
| [
"[email protected]"
] | |
d6138b71e09a469f57f02dcb7c0648ec7c1ce8f9 | f83ef53177180ebfeb5a3e230aa29794f52ce1fc | /ACE/ACE_wrappers/TAO/examples/RTScheduling/Fixed_Priority_Scheduler/test.cpp | 92b8bcd42423723a77d8ead0877ad625bfb8bfae | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-sun-iiop"
] | permissive | msrLi/portingSources | fe7528b3fd08eed4a1b41383c88ee5c09c2294ef | 57d561730ab27804a3172b33807f2bffbc9e52ae | refs/heads/master | 2021-07-08T01:22:29.604203 | 2019-07-10T13:07:06 | 2019-07-10T13:07:06 | 196,183,165 | 2 | 1 | Apache-2.0 | 2020-10-13T14:30:53 | 2019-07-10T10:16:46 | null | UTF-8 | C++ | false | false | 6,700 | cpp | #include "test.h"
#include "tao/RTScheduling/RTScheduler_Manager.h"
#include "tao/ORB_Core.h"
#include "ace/Arg_Shifter.h"
#include "../Task_Stats.h"
#include "../Synch_i.h"
#include "ace/OS_NS_errno.h"
#include "ace/Event_Handler.h"
#include "ace/Sig_Handler.h"
class TestShutdown : public ACE_Event_Handler
{
public:
TestShutdown (CORBA::ORB_ptr orb)
: orb_(CORBA::ORB::_duplicate (orb))
{
#if !defined(ACE_LACKS_UNIX_SIGNALS)
this->shutdown_.register_handler (SIGTERM, this);
this->shutdown_.register_handler (SIGINT, this);
#elif defined(ACE_WIN32)
this->shutdown_.register_handler (SIGINT, this);
#endif
}
~TestShutdown (void)
{
#if !defined(ACE_LACKS_UNIX_SIGNALS)
this->shutdown_.remove_handler (SIGTERM);
this->shutdown_.remove_handler (SIGINT);
#elif defined(ACE_WIN32)
this->shutdown_.remove_handler (SIGINT);
#endif
}
virtual int handle_signal (int, siginfo_t*, ucontext_t*)
{
ACE_DEBUG ((LM_DEBUG, "Shutting down...\n"));
this->orb_->shutdown ();
return 0;
}
private:
CORBA::ORB_var orb_;
ACE_Sig_Handler shutdown_;
};
DT_Test::DT_Test (void)
{
base_t = ACE_OS::gethrtime ();
}
void
DT_Test::check_supported_priorities (void)
{
// Check that we have sufficient priority range to run this
// test, i.e., more than 1 priority level.
this->thr_sched_policy_ = orb_->orb_core ()->orb_params ()->sched_policy ();
this->thr_scope_policy_ = orb_->orb_core ()->orb_params ()->scope_policy ();
if (thr_sched_policy_ == THR_SCHED_RR)
{
//if (TAO_debug_level > 0)
ACE_DEBUG ((LM_DEBUG, "Sched policy = THR_SCHED_RR\n"));
sched_policy_ = ACE_SCHED_RR;
}
else
if (thr_sched_policy_ == THR_SCHED_FIFO)
{
// if (TAO_debug_level > 0)
ACE_DEBUG ((LM_DEBUG, "Sched policy = THR_SCHED_FIFO\n"));
sched_policy_ = ACE_SCHED_FIFO;
}
else
{
if (TAO_debug_level > 0)
ACE_DEBUG ((LM_DEBUG, "Sched policy = THR_SCHED_OTHER\n"));
sched_policy_ = ACE_SCHED_OTHER;
}
if (thr_sched_policy_ == THR_SCHED_RR || thr_sched_policy_ == THR_SCHED_FIFO)
{
max_priority_ = ACE_Sched_Params::priority_max (sched_policy_);
min_priority_ = ACE_Sched_Params::priority_min (sched_policy_);
if (max_priority_ == min_priority_)
{
ACE_DEBUG ((LM_DEBUG,
"Not enough priority levels on this platform"
" to run the test, aborting\n"));
ACE_OS::exit (2);
}
else ACE_DEBUG ((LM_DEBUG, "max_priority = %d, min_priority = %d\n",
max_priority_, min_priority_));
}
}
int
DT_Test::init (int argc, ACE_TCHAR *argv [])
{
orb_ = CORBA::ORB_init (argc, argv);
this->check_supported_priorities ();
dt_creator_->orb (orb_.in ());
TASK_STATS::instance ()->init (dt_creator_->total_load ());
CORBA::Object_var manager_obj = orb_->resolve_initial_references ("RTSchedulerManager");
TAO_RTScheduler_Manager_var manager = TAO_RTScheduler_Manager::_narrow (manager_obj.in ());
ACE_NEW_RETURN (scheduler_,
Fixed_Priority_Scheduler (orb_.in ()),
-1);
manager->rtscheduler (scheduler_.in ());
CORBA::Object_var object =
orb_->resolve_initial_references ("RTScheduler_Current");
current_ =
RTScheduling::Current::_narrow (object.in ());
if (sched_policy_ != ACE_SCHED_OTHER)
{
//Set the main thread to max priority...
if (ACE_OS::sched_params (ACE_Sched_Params (sched_policy_,
55,
ACE_SCOPE_PROCESS)) != 0)
{
if (ACE_OS::last_error () == EPERM)
{
ACE_DEBUG ((LM_DEBUG,
"(%P|%t): user is not superuser, "
"test runs in time-shared class\n"));
}
else
ACE_ERROR ((LM_ERROR,
"(%P|%t): sched_params failed\n"));
}
}
return 0;
}
void
DT_Test::run (int argc, ACE_TCHAR* argv [])
{
init (argc,argv);
TestShutdown killer (this->orb_.in ());
if (this->dt_creator_->resolve_naming_service () == -1)
return;
//TASK_STATS::instance ()->init (this->dt_creator_->dt_count () * 100);
this->dt_creator_->activate_root_poa ();
this->dt_creator_->activate_poa_list ();
this->dt_creator_->activate_job_list ();
this->dt_creator_->activate_schedule ();
this->dt_creator_->register_synch_obj ();
ACE_DEBUG ((LM_DEBUG,
"Registered Synch Object\n"));
/*
dt_creator_->create_distributable_threads (current_.in ());
*/
this->activate_task ();
char msg [BUFSIZ];
ACE_OS::sprintf (msg, "ORB RUN\n");
this->dt_creator_->log_msg (msg);
orb_->run ();
ACE_Thread_Manager::instance ()->wait ();
orb_->destroy ();
}
void
DT_Test::dt_creator (FP_DT_Creator* dt_creator)
{
this->dt_creator_ = dt_creator;
}
FP_DT_Creator*
DT_Test::dt_creator (void)
{
return this->dt_creator_;
}
Fixed_Priority_Scheduler*
DT_Test::scheduler (void)
{
return this->scheduler_.in ();
}
int
DT_Test::activate_task (void)
{
ACE_DEBUG ((LM_DEBUG,
"Test Activate Task\n"));
long flags;
flags = THR_NEW_LWP | THR_JOINABLE;
flags |=
orb_->orb_core ()->orb_params ()->scope_policy () |
orb_->orb_core ()->orb_params ()->sched_policy ();
if (this->activate (flags,
1,
0,
50) == -1)
{
if (ACE_OS::last_error () == EPERM)
ACE_ERROR_RETURN ((LM_ERROR,
ACE_TEXT ("Insufficient privilege to run this test.\n")),
-1);
}
return 0;
}
int
DT_Test::svc (void)
{
try
{
ACE_DEBUG ((LM_DEBUG,
"In test::svc\n"));
dt_creator_->create_distributable_threads (current_.in ());
}
catch (const CORBA::BAD_INV_ORDER &)
{
// This exception can occur if ORB is already shutdown.
}
catch (const CORBA::Exception& ex)
{
ex._tao_print_exception ("Caught exception:");
return -1;
}
return 0;
}
CORBA::ORB_ptr
DT_Test::orb (void)
{
return this->orb_.in ();
}
int
ACE_TMAIN(int argc, ACE_TCHAR *argv[])
{
int status = 0;
ACE_Service_Config::static_svcs ()->insert (&ace_svc_desc_FP_DT_Creator);
try
{
DT_TEST::instance ()->run (argc, argv);
}
catch (const CORBA::Exception& ex)
{
ex._tao_print_exception ("Caught exception:");
status = 1;
}
ACE_Service_Config::static_svcs ()->remove (ACE_TEXT ("FP_DT_Creator"));
return status;
}
ACE_SINGLETON_TEMPLATE_INSTANTIATE(ACE_Singleton, DT_Test, TAO_SYNCH_MUTEX);
| [
"[email protected]"
] | |
16c79439a63ac28d68597b95c2c9fd2f7a23f281 | 6f432cd873af08b1e8229b73fbf3ae4c17d07d0e | /src/SvgEditDialog.cpp | 11617116aa20783840cf9e976bb91ff37b6dc7c4 | [] | no_license | neonsoftware/sndgui | acc37d717ef077d7ff0e096bc8b920a0ec324496 | 568b93c1b067a507ad15691e768449ff5ccb62ea | refs/heads/master | 2021-05-10T20:30:49.062860 | 2018-05-31T04:09:34 | 2018-05-31T04:09:34 | 118,193,099 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 874 | cpp | #include "SvgEditDialog.h"
#include "xmlsyntax.h"
#include <QDebug>
SvgEditorDialog::SvgEditorDialog(QWidget *parent) : QWidget(parent),
mFileSelector(new FileSelectorWidget),
mSvgEditor(new SvgEditorWidget),
mSvgPreviewer(new SvgPreviewWidget)
{
QSplitter *spli = new QSplitter;
spli->setContentsMargins(0,0,0,0);
spli->setHandleWidth(1);
spli->addWidget(mFileSelector);
spli->addWidget(mSvgEditor);
spli->addWidget(mSvgPreviewer);
QHBoxLayout *hl = new QHBoxLayout;
hl->setContentsMargins(0,0,0,0);
hl->setSpacing(0);
hl->addWidget(spli);
this->setLayout(hl);
QObject::connect(mFileSelector, &FileSelectorWidget::selectedFile,
mSvgEditor, &SvgEditorWidget::loadFile);
QObject::connect(mSvgEditor, &SvgEditorWidget::saved,
mSvgPreviewer, &SvgPreviewWidget::previewSvg);
}
| [
"[email protected]"
] | |
77b2c3e1ebc91c6d8494fdda5a1902dbfaca5de7 | 166f379495c6823c74062072f983c817126a7b0e | /riegeli/bytes/backward_writer.cc | f02b22e3316119946cb6b50d6e934ee1b8a32511 | [
"Apache-2.0"
] | permissive | lamarrr/riegeli | ba7307556415d5d71db52413330617e7445e3522 | dfb3b11877c5fb0357e21aaf9e6dab736674c081 | refs/heads/master | 2020-07-30T12:12:35.251919 | 2019-09-20T12:04:19 | 2019-09-20T18:13:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,936 | cc | // Copyright 2017 Google LLC
//
// 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 "riegeli/bytes/backward_writer.h"
#include <stddef.h>
#include <cstring>
#include <iterator>
#include <utility>
#include "absl/base/optimization.h"
#include "absl/strings/string_view.h"
#include "riegeli/base/base.h"
#include "riegeli/base/canonical_errors.h"
#include "riegeli/base/chain.h"
#include "riegeli/base/object.h"
#include "riegeli/base/status.h"
namespace riegeli {
bool BackwardWriter::Fail(Status status) {
start_ = nullptr;
cursor_ = nullptr;
limit_ = nullptr;
return Object::Fail(std::move(status));
}
bool BackwardWriter::FailOverflow() {
return Fail(ResourceExhaustedError("BackwardWriter position overflow"));
}
bool BackwardWriter::WriteSlow(absl::string_view src) {
RIEGELI_ASSERT_GT(src.size(), available())
<< "Failed precondition of BackwardWriter::WriteSlow(string_view): "
"length too small, use Write(string_view) instead";
do {
const size_t available_length = available();
if (available_length > 0) { // memcpy(nullptr, _, 0) is undefined.
cursor_ = limit_;
std::memcpy(cursor_, src.data() + src.size() - available_length,
available_length);
src.remove_suffix(available_length);
}
if (ABSL_PREDICT_FALSE(!PushSlow(1, src.size()))) return false;
} while (src.size() > available());
cursor_ -= src.size();
std::memcpy(cursor_, src.data(), src.size());
return true;
}
bool BackwardWriter::WriteSlow(const Chain& src) {
RIEGELI_ASSERT_GT(src.size(), UnsignedMin(available(), kMaxBytesToCopy))
<< "Failed precondition of BackwardWriter::WriteSlow(Chain): "
"length too small, use Write(Chain) instead";
for (Chain::Blocks::const_reverse_iterator iter = src.blocks().crbegin();
iter != src.blocks().crend(); ++iter) {
if (ABSL_PREDICT_FALSE(!Write(*iter))) return false;
}
return true;
}
bool BackwardWriter::WriteSlow(Chain&& src) {
RIEGELI_ASSERT_GT(src.size(), UnsignedMin(available(), kMaxBytesToCopy))
<< "Failed precondition of BackwardWriter::WriteSlow(Chain&&): "
"length too small, use Write(Chain&&) instead";
// Not std::move(src): forward to WriteSlow(const Chain&).
return WriteSlow(src);
}
bool BackwardWriter::Truncate(Position new_size) {
return Fail(UnimplementedError("BackwardWriter::Truncate() not supported"));
}
} // namespace riegeli
| [
"[email protected]"
] | |
a6d7804e65fe81806692bd1d643e59ec76a1afac | ee6bd5c6147cbfd49f7570509120ec51b63d432f | /142.cpp | 015d10adfbb20994956cded08d63a99c6fed6d79 | [] | no_license | ly569/hzoj | 8cb1a87a7dab40d2ed86fd70023d384f16adf3a1 | 5d6bb274f14250a276d42a32a8032b87bedf59fa | refs/heads/master | 2021-03-01T01:57:10.199027 | 2020-08-03T11:34:06 | 2020-08-03T11:34:06 | 245,746,498 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 591 | cpp | #include <iostream>
using namespace std;
int number_1(int n) {
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) return 0;
}
return 1;
}
int number_2(int n) {
if (n / 10000 == n % 10 && n / 1000 % 10 == n / 10 % 10) {
return 1;
} else {
return 0;
}
}
int main() {
int a, b;
cin >> a >> b;
int flag = 0;
for (int i = a; i <= b; i++) {
if (number_1(i) && number_2(i)) {
if (flag == 1) {
cout << " ";
}
cout << i;
flag = 1;
}
}
return 0;
} | [
"[email protected]"
] | |
a47280ab224a16ee51d86b883c9c74fb6730e34c | 21f7ad6af9e2b3b88015b4a9e676835bf47f348a | /EBUCoreProcessor/src/EBUCore_1_4/metadata/ebucoreDimension.cpp | ee4bdab8dfc019a2d40fc457e72ac67b1bbf0a59 | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | permissive | ebu/ebu-mxfsdk | 363535382f0bb4f70411cfa282b7498e8848c500 | d66e4b05354ec2b80365f1956f14678c6f7f6514 | refs/heads/master | 2020-04-05T00:35:11.681563 | 2017-07-12T12:55:20 | 2017-07-12T12:55:20 | 11,311,536 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,217 | cpp | /*
* Copyright 2012-2013 European Broadcasting Union and Limecraft, NV.
*
* 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.
*
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <libMXF++/MXF.h>
#include <EBUCore_1_4/metadata/EBUCoreDMS++.h>
using namespace std;
using namespace mxfpp;
using namespace EBUSDK::EBUCore::EBUCore_1_4::KLV;
ebucoreDimension::ebucoreDimension(HeaderMetadata *headerMetadata)
: ebucoreDimensionBase(headerMetadata)
{}
ebucoreDimension::ebucoreDimension(HeaderMetadata *headerMetadata, ::MXFMetadataSet *cMetadataSet)
: ebucoreDimensionBase(headerMetadata, cMetadataSet)
{}
ebucoreDimension::~ebucoreDimension()
{}
| [
"[email protected]"
] | |
6b75d8dd11115536c290d3989752c8dd85a0d97f | bdc7ac02c9c32ea050cf30a70d9d89fe5dd477dd | /src/DX/Light.h | 38e6138e1cf348a6f36f38cd5e0b8d3ca2efadff | [] | no_license | AlexLevick/DX11-Shaders | 20c36c108ff6e103cde542b6202ab7d424c28ac8 | 16ede1913c4b0f3b6c978210762459fdeda9b2d2 | refs/heads/master | 2020-03-23T20:40:12.940985 | 2018-07-23T18:44:13 | 2018-07-23T18:44:13 | 142,054,636 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,115 | h | #ifndef _LIGHT_H_
#define _LIGHT_H_
#include <directxmath.h>
using namespace DirectX;
class Light
{
public:
void* operator new(size_t i)
{
return _mm_malloc(i, 16);
}
void operator delete(void* p)
{
_mm_free(p);
}
void GenerateViewMatrix();
void GenerateProjectionMatrix(float, float);
// Setters
void SetAmbientColour(float, float, float, float);
void SetDiffuseColour(float, float, float, float);
void SetDirection(float, float, float);
void SetSpecularColour(float, float, float, float);
void SetSpecularPower(float);
void SetPosition(float, float, float);
void SetLookAt(float, float, float);
// Getters
XMFLOAT4 GetAmbientColour();
XMFLOAT4 GetDiffuseColour();
XMFLOAT3 GetDirection();
XMFLOAT4 GetSpecularColour();
float GetSpecularPower();
XMFLOAT3 GetPosition();
XMMATRIX GetViewMatrix();
XMMATRIX GetProjectionMatrix();
protected:
XMFLOAT4 m_ambientColour;
XMFLOAT4 m_diffuseColour;
XMFLOAT3 m_direction;
XMFLOAT4 m_specularColour;
float m_specularPower;
XMVECTOR m_position;
XMMATRIX m_viewMatrix;
XMMATRIX m_projectionMatrix;
XMVECTOR m_lookAt;
};
#endif | [
"[email protected]"
] | |
009980c7dbab13db84d30f159d1888c19a807285 | 819505a89146039be05aed3196b17a615cfa96b5 | /src/walletdb.cpp | e3e9fe8e9dfe53b8f3446cd7da3c776d050a88d4 | [
"MIT"
] | permissive | coinmaxous/maxocoin-master | 6ff6481e41aac50331fa8e5eb987ba96c27305d2 | 4fea4b2d54883fc1c33a2b005e3048b839376f90 | refs/heads/master | 2021-01-19T23:58:23.893963 | 2017-04-22T10:09:10 | 2017-04-22T10:09:10 | 89,060,838 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,828 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "walletdb.h"
#include "wallet.h"
#include <boost/version.hpp>
#include <boost/filesystem.hpp>
using namespace std;
using namespace boost;
static uint64_t nAccountingEntryNumber = 0;
extern bool fWalletUnlockStakingOnly;
//
// CWalletDB
//
bool CWalletDB::WriteName(const string& strAddress, const string& strName)
{
nWalletDBUpdated++;
return Write(make_pair(string("name"), strAddress), strName);
}
bool CWalletDB::EraseName(const string& strAddress)
{
// This should only be used for sending addresses, never for receiving addresses,
// receiving addresses must always have an address book entry if they're not change return.
nWalletDBUpdated++;
return Erase(make_pair(string("name"), strAddress));
}
bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)
{
account.SetNull();
return Read(make_pair(string("acc"), strAccount), account);
}
bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account)
{
return Write(make_pair(string("acc"), strAccount), account);
}
bool CWalletDB::WriteAccountingEntry(const uint64_t nAccEntryNum, const CAccountingEntry& acentry)
{
return Write(boost::make_tuple(string("acentry"), acentry.strAccount, nAccEntryNum), acentry);
}
bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry)
{
return WriteAccountingEntry(++nAccountingEntryNumber, acentry);
}
int64_t CWalletDB::GetAccountCreditDebit(const string& strAccount)
{
list<CAccountingEntry> entries;
ListAccountCreditDebit(strAccount, entries);
int64_t nCreditDebit = 0;
BOOST_FOREACH (const CAccountingEntry& entry, entries)
nCreditDebit += entry.nCreditDebit;
return nCreditDebit;
}
void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries)
{
bool fAllAccounts = (strAccount == "*");
Dbc* pcursor = GetCursor();
if (!pcursor)
throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor");
unsigned int fFlags = DB_SET_RANGE;
while (true)
{
// Read next record
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
if (fFlags == DB_SET_RANGE)
ssKey << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64_t(0));
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
fFlags = DB_NEXT;
if (ret == DB_NOTFOUND)
break;
else if (ret != 0)
{
pcursor->close();
throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB");
}
// Unserialize
string strType;
ssKey >> strType;
if (strType != "acentry")
break;
CAccountingEntry acentry;
ssKey >> acentry.strAccount;
if (!fAllAccounts && acentry.strAccount != strAccount)
break;
ssValue >> acentry;
ssKey >> acentry.nEntryNo;
entries.push_back(acentry);
}
pcursor->close();
}
DBErrors
CWalletDB::ReorderTransactions(CWallet* pwallet)
{
LOCK(pwallet->cs_wallet);
// Old wallets didn't have any defined order for transactions
// Probably a bad idea to change the output of this
// First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
typedef pair<CWalletTx*, CAccountingEntry*> TxPair;
typedef multimap<int64_t, TxPair > TxItems;
TxItems txByTime;
for (map<uint256, CWalletTx>::iterator it = pwallet->mapWallet.begin(); it != pwallet->mapWallet.end(); ++it)
{
CWalletTx* wtx = &((*it).second);
txByTime.insert(make_pair(wtx->nTimeReceived, TxPair(wtx, (CAccountingEntry*)0)));
}
list<CAccountingEntry> acentries;
ListAccountCreditDebit("", acentries);
BOOST_FOREACH(CAccountingEntry& entry, acentries)
{
txByTime.insert(make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry)));
}
int64_t& nOrderPosNext = pwallet->nOrderPosNext;
nOrderPosNext = 0;
std::vector<int64_t> nOrderPosOffsets;
for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
{
CWalletTx *const pwtx = (*it).second.first;
CAccountingEntry *const pacentry = (*it).second.second;
int64_t& nOrderPos = (pwtx != 0) ? pwtx->nOrderPos : pacentry->nOrderPos;
if (nOrderPos == -1)
{
nOrderPos = nOrderPosNext++;
nOrderPosOffsets.push_back(nOrderPos);
if (pacentry)
// Have to write accounting regardless, since we don't keep it in memory
if (!WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
return DB_LOAD_FAIL;
}
else
{
int64_t nOrderPosOff = 0;
BOOST_FOREACH(const int64_t& nOffsetStart, nOrderPosOffsets)
{
if (nOrderPos >= nOffsetStart)
++nOrderPosOff;
}
nOrderPos += nOrderPosOff;
nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
if (!nOrderPosOff)
continue;
// Since we're changing the order, write it back
if (pwtx)
{
if (!WriteTx(pwtx->GetHash(), *pwtx))
return DB_LOAD_FAIL;
}
else
if (!WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
return DB_LOAD_FAIL;
}
}
return DB_LOAD_OK;
}
class CWalletScanState {
public:
unsigned int nKeys;
unsigned int nCKeys;
unsigned int nKeyMeta;
bool fIsEncrypted;
bool fAnyUnordered;
int nFileVersion;
vector<uint256> vWalletUpgrade;
CWalletScanState() {
nKeys = nCKeys = nKeyMeta = 0;
fIsEncrypted = false;
fAnyUnordered = false;
nFileVersion = 0;
}
};
bool
ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue,
CWalletScanState &wss, string& strType, string& strErr)
{
try {
// Unserialize
// Taking advantage of the fact that pair serialization
// is just the two items serialized one after the other
ssKey >> strType;
if (strType == "name")
{
string strAddress;
ssKey >> strAddress;
ssValue >> pwallet->mapAddressBook[CBitcoinAddress(strAddress).Get()];
}
else if (strType == "tx")
{
uint256 hash;
ssKey >> hash;
CWalletTx& wtx = pwallet->mapWallet[hash];
ssValue >> wtx;
if (wtx.CheckTransaction() && (wtx.GetHash() == hash))
wtx.BindWallet(pwallet);
else
{
pwallet->mapWallet.erase(hash);
return false;
}
// Undo serialize changes in 31600
if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
{
if (!ssValue.empty())
{
char fTmp;
char fUnused;
ssValue >> fTmp >> fUnused >> wtx.strFromAccount;
strErr = strprintf("LoadWallet() upgrading tx ver=%d %d '%s' %s",
wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount.c_str(), hash.ToString().c_str());
wtx.fTimeReceivedIsTxTime = fTmp;
}
else
{
strErr = strprintf("LoadWallet() repairing tx ver=%d %s", wtx.fTimeReceivedIsTxTime, hash.ToString().c_str());
wtx.fTimeReceivedIsTxTime = 0;
}
wss.vWalletUpgrade.push_back(hash);
}
if (wtx.nOrderPos == -1)
wss.fAnyUnordered = true;
//// debug print
//printf("LoadWallet %s\n", wtx.GetHash().ToString().c_str());
//printf(" %12"PRId64" %s %s %s\n",
// wtx.vout[0].nValue,
// DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()).c_str(),
// wtx.hashBlock.ToString().substr(0,20).c_str(),
// wtx.mapValue["message"].c_str());
}
else if (strType == "acentry")
{
string strAccount;
ssKey >> strAccount;
uint64_t nNumber;
ssKey >> nNumber;
if (nNumber > nAccountingEntryNumber)
nAccountingEntryNumber = nNumber;
if (!wss.fAnyUnordered)
{
CAccountingEntry acentry;
ssValue >> acentry;
if (acentry.nOrderPos == -1)
wss.fAnyUnordered = true;
}
}
else if (strType == "key" || strType == "wkey")
{
vector<unsigned char> vchPubKey;
ssKey >> vchPubKey;
CKey key;
if (strType == "key")
{
wss.nKeys++;
CPrivKey pkey;
ssValue >> pkey;
key.SetPubKey(vchPubKey);
if (!key.SetPrivKey(pkey))
{
strErr = "Error reading wallet database: CPrivKey corrupt";
return false;
}
if (key.GetPubKey() != vchPubKey)
{
strErr = "Error reading wallet database: CPrivKey pubkey inconsistency";
return false;
}
if (!key.IsValid())
{
strErr = "Error reading wallet database: invalid CPrivKey";
return false;
}
}
else
{
CWalletKey wkey;
ssValue >> wkey;
key.SetPubKey(vchPubKey);
if (!key.SetPrivKey(wkey.vchPrivKey))
{
strErr = "Error reading wallet database: CPrivKey corrupt";
return false;
}
if (key.GetPubKey() != vchPubKey)
{
strErr = "Error reading wallet database: CWalletKey pubkey inconsistency";
return false;
}
if (!key.IsValid())
{
strErr = "Error reading wallet database: invalid CWalletKey";
return false;
}
}
if (!pwallet->LoadKey(key))
{
strErr = "Error reading wallet database: LoadKey failed";
return false;
}
}
else if (strType == "mkey")
{
unsigned int nID;
ssKey >> nID;
CMasterKey kMasterKey;
ssValue >> kMasterKey;
if(pwallet->mapMasterKeys.count(nID) != 0)
{
strErr = strprintf("Error reading wallet database: duplicate CMasterKey id %u", nID);
return false;
}
pwallet->mapMasterKeys[nID] = kMasterKey;
if (pwallet->nMasterKeyMaxID < nID)
pwallet->nMasterKeyMaxID = nID;
}
else if (strType == "ckey")
{
wss.nCKeys++;
vector<unsigned char> vchPubKey;
ssKey >> vchPubKey;
vector<unsigned char> vchPrivKey;
ssValue >> vchPrivKey;
if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey))
{
strErr = "Error reading wallet database: LoadCryptedKey failed";
return false;
}
wss.fIsEncrypted = true;
}
else if (strType == "keymeta")
{
CPubKey vchPubKey;
ssKey >> vchPubKey;
CKeyMetadata keyMeta;
ssValue >> keyMeta;
wss.nKeyMeta++;
pwallet->LoadKeyMetadata(vchPubKey, keyMeta);
// find earliest key creation time, as wallet birthday
if (!pwallet->nTimeFirstKey ||
(keyMeta.nCreateTime < pwallet->nTimeFirstKey))
pwallet->nTimeFirstKey = keyMeta.nCreateTime;
}
else if (strType == "defaultkey")
{
ssValue >> pwallet->vchDefaultKey;
}
else if (strType == "pool")
{
int64_t nIndex;
ssKey >> nIndex;
CKeyPool keypool;
ssValue >> keypool;
pwallet->setKeyPool.insert(nIndex);
// If no metadata exists yet, create a default with the pool key's
// creation time. Note that this may be overwritten by actually
// stored metadata for that key later, which is fine.
CKeyID keyid = keypool.vchPubKey.GetID();
if (pwallet->mapKeyMetadata.count(keyid) == 0)
pwallet->mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
}
else if (strType == "version")
{
ssValue >> wss.nFileVersion;
if (wss.nFileVersion == 10300)
wss.nFileVersion = 300;
}
else if (strType == "cscript")
{
uint160 hash;
ssKey >> hash;
CScript script;
ssValue >> script;
if (!pwallet->LoadCScript(script))
{
strErr = "Error reading wallet database: LoadCScript failed";
return false;
}
}
else if (strType == "orderposnext")
{
ssValue >> pwallet->nOrderPosNext;
}
} catch (...)
{
return false;
}
return true;
}
static bool IsKeyType(string strType)
{
return (strType== "key" || strType == "wkey" ||
strType == "mkey" || strType == "ckey");
}
DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
{
pwallet->vchDefaultKey = CPubKey();
CWalletScanState wss;
bool fNoncriticalErrors = false;
DBErrors result = DB_LOAD_OK;
try {
LOCK(pwallet->cs_wallet);
int nMinVersion = 0;
if (Read((string)"minversion", nMinVersion))
{
if (nMinVersion > CLIENT_VERSION)
return DB_TOO_NEW;
pwallet->LoadMinVersion(nMinVersion);
}
// Get cursor
Dbc* pcursor = GetCursor();
if (!pcursor)
{
printf("Error getting wallet database cursor\n");
return DB_CORRUPT;
}
while (true)
{
// Read next record
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
int ret = ReadAtCursor(pcursor, ssKey, ssValue);
if (ret == DB_NOTFOUND)
break;
else if (ret != 0)
{
printf("Error reading next record from wallet database\n");
return DB_CORRUPT;
}
// Try to be tolerant of single corrupt records:
string strType, strErr;
if (!ReadKeyValue(pwallet, ssKey, ssValue, wss, strType, strErr))
{
// losing keys is considered a catastrophic error, anything else
// we assume the user can live with:
if (IsKeyType(strType))
result = DB_CORRUPT;
else
{
// Leave other errors alone, if we try to fix them we might make things worse.
fNoncriticalErrors = true; // ... but do warn the user there is something wrong.
if (strType == "tx")
// Rescan if there is a bad transaction record:
SoftSetBoolArg("-rescan", true);
}
}
if (!strErr.empty())
printf("%s\n", strErr.c_str());
}
pcursor->close();
}
catch (...)
{
result = DB_CORRUPT;
}
if (fNoncriticalErrors && result == DB_LOAD_OK)
result = DB_NONCRITICAL_ERROR;
// Any wallet corruption at all: skip any rewriting or
// upgrading, we don't want to make it worse.
if (result != DB_LOAD_OK)
return result;
printf("nFileVersion = %d\n", wss.nFileVersion);
printf("Keys: %u plaintext, %u encrypted, %u w/ metadata, %u total\n",
wss.nKeys, wss.nCKeys, wss.nKeyMeta, wss.nKeys + wss.nCKeys);
// nTimeFirstKey is only reliable if all keys have metadata
if ((wss.nKeys + wss.nCKeys) != wss.nKeyMeta)
pwallet->nTimeFirstKey = 1; // 0 would be considered 'no value'
BOOST_FOREACH(uint256 hash, wss.vWalletUpgrade)
WriteTx(hash, pwallet->mapWallet[hash]);
// Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc:
if (wss.fIsEncrypted && (wss.nFileVersion == 40000 || wss.nFileVersion == 50000))
return DB_NEED_REWRITE;
if (wss.nFileVersion < CLIENT_VERSION) // Update
WriteVersion(CLIENT_VERSION);
if (wss.fAnyUnordered)
result = ReorderTransactions(pwallet);
return result;
}
void ThreadFlushWalletDB(void* parg)
{
// Make this thread recognisable as the wallet flushing thread
RenameThread("maxocoin-wallet");
const string& strFile = ((const string*)parg)[0];
static bool fOneThread;
if (fOneThread)
return;
fOneThread = true;
if (!GetBoolArg("-flushwallet", true))
return;
unsigned int nLastSeen = nWalletDBUpdated;
unsigned int nLastFlushed = nWalletDBUpdated;
int64_t nLastWalletUpdate = GetTime();
while (!fShutdown)
{
MilliSleep(500);
if (nLastSeen != nWalletDBUpdated)
{
nLastSeen = nWalletDBUpdated;
nLastWalletUpdate = GetTime();
}
if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)
{
TRY_LOCK(bitdb.cs_db,lockDb);
if (lockDb)
{
// Don't do this if any databases are in use
int nRefCount = 0;
map<string, int>::iterator mi = bitdb.mapFileUseCount.begin();
while (mi != bitdb.mapFileUseCount.end())
{
nRefCount += (*mi).second;
mi++;
}
if (nRefCount == 0 && !fShutdown)
{
map<string, int>::iterator mi = bitdb.mapFileUseCount.find(strFile);
if (mi != bitdb.mapFileUseCount.end())
{
printf("Flushing wallet.dat\n");
nLastFlushed = nWalletDBUpdated;
int64_t nStart = GetTimeMillis();
// Flush wallet.dat so it's self contained
bitdb.CloseDb(strFile);
bitdb.CheckpointLSN(strFile);
bitdb.mapFileUseCount.erase(mi++);
printf("Flushed wallet.dat %"PRId64"ms\n", GetTimeMillis() - nStart);
}
}
}
}
}
}
bool BackupWallet(const CWallet& wallet, const string& strDest)
{
if (!wallet.fFileBacked)
return false;
while (!fShutdown)
{
{
LOCK(bitdb.cs_db);
if (!bitdb.mapFileUseCount.count(wallet.strWalletFile) || bitdb.mapFileUseCount[wallet.strWalletFile] == 0)
{
// Flush log data to the dat file
bitdb.CloseDb(wallet.strWalletFile);
bitdb.CheckpointLSN(wallet.strWalletFile);
bitdb.mapFileUseCount.erase(wallet.strWalletFile);
// Copy wallet.dat
filesystem::path pathSrc = GetDataDir() / wallet.strWalletFile;
filesystem::path pathDest(strDest);
if (filesystem::is_directory(pathDest))
pathDest /= wallet.strWalletFile;
try {
#if BOOST_VERSION >= 104000
filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);
#else
filesystem::copy_file(pathSrc, pathDest);
#endif
printf("copied wallet.dat to %s\n", pathDest.string().c_str());
return true;
} catch(const filesystem::filesystem_error &e) {
printf("error copying wallet.dat to %s - %s\n", pathDest.string().c_str(), e.what());
return false;
}
}
}
MilliSleep(100);
}
return false;
}
//
// Try to (very carefully!) recover wallet.dat if there is a problem.
//
bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename, bool fOnlyKeys)
{
// Recovery procedure:
// move wallet.dat to wallet.timestamp.bak
// Call Salvage with fAggressive=true to
// get as much data as possible.
// Rewrite salvaged data to wallet.dat
// Set -rescan so any missing transactions will be
// found.
int64_t now = GetTime();
std::string newFilename = strprintf("wallet.%"PRId64".bak", now);
int result = dbenv.dbenv.dbrename(NULL, filename.c_str(), NULL,
newFilename.c_str(), DB_AUTO_COMMIT);
if (result == 0)
printf("Renamed %s to %s\n", filename.c_str(), newFilename.c_str());
else
{
printf("Failed to rename %s to %s\n", filename.c_str(), newFilename.c_str());
return false;
}
std::vector<CDBEnv::KeyValPair> salvagedData;
bool allOK = dbenv.Salvage(newFilename, true, salvagedData);
if (salvagedData.empty())
{
printf("Salvage(aggressive) found no records in %s.\n", newFilename.c_str());
return false;
}
printf("Salvage(aggressive) found %"PRIszu" records\n", salvagedData.size());
bool fSuccess = allOK;
Db* pdbCopy = new Db(&dbenv.dbenv, 0);
int ret = pdbCopy->open(NULL, // Txn pointer
filename.c_str(), // Filename
"main", // Logical db name
DB_BTREE, // Database type
DB_CREATE, // Flags
0);
if (ret > 0)
{
printf("Cannot create database file %s\n", filename.c_str());
return false;
}
CWallet dummyWallet;
CWalletScanState wss;
DbTxn* ptxn = dbenv.TxnBegin();
BOOST_FOREACH(CDBEnv::KeyValPair& row, salvagedData)
{
if (fOnlyKeys)
{
CDataStream ssKey(row.first, SER_DISK, CLIENT_VERSION);
CDataStream ssValue(row.second, SER_DISK, CLIENT_VERSION);
string strType, strErr;
bool fReadOK = ReadKeyValue(&dummyWallet, ssKey, ssValue,
wss, strType, strErr);
if (!IsKeyType(strType))
continue;
if (!fReadOK)
{
printf("WARNING: CWalletDB::Recover skipping %s: %s\n", strType.c_str(), strErr.c_str());
continue;
}
}
Dbt datKey(&row.first[0], row.first.size());
Dbt datValue(&row.second[0], row.second.size());
int ret2 = pdbCopy->put(ptxn, &datKey, &datValue, DB_NOOVERWRITE);
if (ret2 > 0)
fSuccess = false;
}
ptxn->commit(0);
pdbCopy->close(0);
delete pdbCopy;
return fSuccess;
}
bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename)
{
return CWalletDB::Recover(dbenv, filename, false);
}
| [
"[email protected]"
] | |
db1d00b79fbd5192cea08a75c8acaeb0a53c8f64 | 04b1803adb6653ecb7cb827c4f4aa616afacf629 | /third_party/blink/renderer/core/workers/experimental/task_worklet_global_scope.cc | 90f2dd00d731a6f1b7ded3c882b9345d1149396e | [
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | permissive | Samsung/Castanets | 240d9338e097b75b3f669604315b06f7cf129d64 | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | refs/heads/castanets_76_dev | 2023-08-31T09:01:04.744346 | 2021-07-30T04:56:25 | 2021-08-11T05:45:21 | 125,484,161 | 58 | 49 | BSD-3-Clause | 2022-10-16T19:31:26 | 2018-03-16T08:07:37 | null | UTF-8 | C++ | false | false | 3,790 | cc | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/workers/experimental/task_worklet_global_scope.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_no_argument_constructor.h"
#include "third_party/blink/renderer/core/workers/global_scope_creation_params.h"
#include "third_party/blink/renderer/core/workers/worker_thread.h"
#include "third_party/blink/renderer/platform/bindings/callback_method_retriever.h"
namespace blink {
class TaskDefinition final : public GarbageCollectedFinalized<TaskDefinition> {
public:
TaskDefinition(v8::Isolate* isolate,
v8::Local<v8::Value> instance,
v8::Local<v8::Function> process)
: instance_(isolate, instance), process_(isolate, process) {}
~TaskDefinition() = default;
v8::Local<v8::Value> InstanceLocal(v8::Isolate* isolate) {
return instance_.NewLocal(isolate);
}
v8::Local<v8::Function> ProcessLocal(v8::Isolate* isolate) {
return process_.NewLocal(isolate);
}
void Trace(blink::Visitor* visitor) {
visitor->Trace(instance_);
visitor->Trace(process_);
}
private:
// This object keeps the object and process function alive.
// It participates in wrapper tracing as it holds onto V8 wrappers.
TraceWrapperV8Reference<v8::Value> instance_;
TraceWrapperV8Reference<v8::Function> process_;
};
TaskWorkletGlobalScope::TaskWorkletGlobalScope(
std::unique_ptr<GlobalScopeCreationParams> creation_params,
WorkerThread* thread)
: WorkletGlobalScope(std::move(creation_params),
thread->GetWorkerReportingProxy(),
thread) {}
void TaskWorkletGlobalScope::Trace(blink::Visitor* visitor) {
WorkletGlobalScope::Trace(visitor);
visitor->Trace(task_definitions_);
}
void TaskWorkletGlobalScope::registerTask(const String& name,
V8NoArgumentConstructor* constructor,
ExceptionState& exception_state) {
DCHECK(IsContextThread());
if (task_definitions_.Contains(name)) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNotSupportedError,
"A class with name:'" + name + "' is already registered.");
return;
}
if (name.IsEmpty()) {
exception_state.ThrowTypeError("The empty string is not a valid name.");
return;
}
CallbackMethodRetriever retriever(constructor);
retriever.GetPrototypeObject(exception_state);
if (exception_state.HadException())
return;
v8::Local<v8::Function> process =
retriever.GetMethodOrThrow("process", exception_state);
if (exception_state.HadException())
return;
ScriptValue instance;
{
v8::TryCatch try_catch(constructor->GetIsolate());
if (!constructor->Construct().To(&instance)) {
exception_state.RethrowV8Exception(try_catch.Exception());
return;
}
}
TaskDefinition* definition = MakeGarbageCollected<TaskDefinition>(
constructor->GetIsolate(), instance.V8Value(), process);
task_definitions_.Set(name, definition);
}
v8::Local<v8::Value> TaskWorkletGlobalScope::GetInstanceForName(
const String& name,
v8::Isolate* isolate) {
TaskDefinition* definition = task_definitions_.at(name);
return definition ? definition->InstanceLocal(isolate)
: v8::Local<v8::Value>();
}
v8::Local<v8::Function> TaskWorkletGlobalScope::GetProcessFunctionForName(
const String& name,
v8::Isolate* isolate) {
TaskDefinition* definition = task_definitions_.at(name);
return definition ? definition->ProcessLocal(isolate)
: v8::Local<v8::Function>();
}
} // namespace blink
| [
"[email protected]"
] | |
3dde51c68a5e91a4fc037df08767fe15ae01bccb | c7f6aabcf4ed5b626ce3313d5f768448f74be499 | /1721.swapping-nodes-in-a-linked-list.cpp | 73aa0e527b88515f29cb6eb6c00fada7ce61eff1 | [] | no_license | liuchy0427/Leetcode-Solution | f1e9bcf1384c3dd80da4e3402a46d93c9c5ee369 | dcc21f22070eb9d28f692bf98c041c70100d6d77 | refs/heads/main | 2023-03-29T12:16:35.651228 | 2021-03-29T01:50:19 | 2021-03-29T01:50:19 | 331,563,788 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,052 | cpp | /*
* @lc app=leetcode id=1721 lang=cpp
*
* [1721] Swapping Nodes in a Linked List
*/
// @lc code=start
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* swapNodes(ListNode* head, int k) {
if(!head || !head->next) return head;
ListNode *k1,*k2;
ListNode *tmp = head;
int len = 0;
while(tmp){
len++;
tmp = tmp->next;
}
cout<<len<<endl;
tmp = head;
int count = 0;
while(tmp){
count++;
if(count == k)
k1 = tmp;
if(count == len - k+1)
k2 = tmp;
tmp = tmp->next;
}
int x = k1->val;
k1->val = k2->val;
k2->val = x;
return head;
}
};
// @lc code=end
| [
"[email protected]"
] | |
9dda35a1a7a1cd77328c78684ac058831f9d6086 | 4f091e5244a46d4354a2927b6724a6ccb5cc463b | /src/Editor/Gizmo.cpp | cb9dca20a7400db0f515dfeff9e416f2aac95302 | [] | no_license | Rubenknex/Afterlife | 52496b676c431675f2cd45b73e63276294967660 | 23c532c67c1caaa064f2bb3250d47ed7161599d9 | refs/heads/master | 2021-01-17T06:31:34.562628 | 2011-06-25T10:26:59 | 2011-06-25T10:26:59 | 1,747,198 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,994 | cpp | #include "Gizmo.h"
#include "../Game.h"
#include "../InputState.h"
#include "../Math.h"
#include "../Scene/Entities/Entity.h"
#include "../Scene/Entities/Object.h"
#include "../Scene/Scene.h"
Gizmo::Gizmo(Scene* scene) :
m_currentScene(scene),
m_gizmoMode(Gizmo::GM_MOVE),
m_editMode(Gizmo::EM_NONE),
m_selectedObject(NULL)
{
m_triangleUp.AddPoint(-5.0f, -48.0f, sf::Color::Blue);
m_triangleUp.AddPoint(0.0f, -58.0f, sf::Color::Blue);
m_triangleUp.AddPoint(5.0f, -48.0f, sf::Color::Blue);
m_triangleRight.AddPoint(48.0f, -5.0f, sf::Color::Red);
m_triangleRight.AddPoint(58.0f, 0.0f, sf::Color::Red);
m_triangleRight.AddPoint(48.0f, 5.0f, sf::Color::Red);
m_lineUp = sf::Shape::Line(0.0f, 0.0f, 0.0f, -50.0f, 1.0f, sf::Color::Blue);
m_lineRight = sf::Shape::Line(0.0f, 0.0f, 50.0f, 0.0f, 1.0f, sf::Color::Red);
m_lineRotate = sf::Shape::Line(0.0f, 0.0f, 50.0f, 0.0f, 1.0f, sf::Color::Blue);
m_lineScaleBlue = sf::Shape::Line(0.0f, 0.0f, 0.0f, -50.0f, 1.0f, sf::Color::Blue);
m_lineScaleRed = sf::Shape::Line(0.0f, 0.0f, 50.0f, 0.0f, 1.0f, sf::Color::Red);
m_rectangleCenter = sf::Shape::Rectangle(0.0f, -16.0f, 15.0f, 15.0f, sf::Color::Yellow, 1.0f, sf::Color::Yellow);
m_rectangleCenter.EnableFill(false);
m_rectangleCenter.EnableOutline(true);
m_rectangleUp = sf::Shape::Rectangle(-5.0f, -55.0f, 10.0f, 10.0f, sf::Color::Blue);
m_rectangleRight = sf::Shape::Rectangle(45.0f, -5.0f, 10.0f, 10.0f, sf::Color::Red);
m_circleKnob = sf::Shape::Circle(50.0f, 0.0f, 5.0f, sf::Color::Red);
}
Gizmo::~Gizmo()
{
}
void Gizmo::update(float dt)
{
if (g_input.isMouseButtonFirstDown(sf::Mouse::Left))
{
sf::Vector2f worldPos = g_Window->ConvertCoords(g_input.getMouseX(), g_input.getMouseY());
std::vector<Entity*> entities = m_currentScene->getEntitiesAtPosition(worldPos);
Object* bestObject = NULL;
for (int i = 0; i < (int)entities.size(); i++)
{
if (entities[i]->getType() == Entity::OBJECT)
{
if (bestObject == NULL || entities[i]->getDrawLayer() > bestObject->getDrawLayer())
bestObject = static_cast<Object*>(entities[i]);
}
}
if (bestObject != NULL)
m_selectedObject = bestObject;
}
if (g_input.isMouseButtonDown(sf::Mouse::Left) && m_selectedObject != NULL && g_input.getMouseDelta() != sf::Vector2i(0, 0))
{
sf::Vector2f objPos = m_selectedObject->getPosition();
sf::Vector2f mousePos = g_Window->ConvertCoords(g_input.getMouseX(), g_input.getMouseY());
switch (m_gizmoMode)
{
case Gizmo::GM_MOVE:
{
if (m_editMode != Gizmo::EM_MOVE_FREE && m_editMode != Gizmo::EM_MOVE_GLOBAL_X && m_editMode != Gizmo::EM_MOVE_GLOBAL_Y)
{
sf::FloatRect upArrowRect(objPos.x - 10.0f, objPos.y - 50.0f - 10.0f, 20.0f, 20.0f);
sf::FloatRect rightArrowRect(objPos.x + 50.0f - 10.0f, objPos.y - 10.0f, 20.0f, 20.0f);
sf::FloatRect freeRect(objPos.x, objPos.y - 15.0f, 15.0f, 15.0f);
if (freeRect.Contains(mousePos))
{
m_editMode = Gizmo::EM_MOVE_FREE;
}
else if (upArrowRect.Contains(mousePos))
{
m_editMode = Gizmo::EM_MOVE_GLOBAL_Y;
}
else if (rightArrowRect.Contains(mousePos))
{
m_editMode = Gizmo::EM_MOVE_GLOBAL_X;
}
}
}
break;
case Gizmo::GM_ROTATE:
{
float angle = m_selectedObject->getRotation();
sf::Vector2f dirNormal(cos(math::radians(angle)), sin(math::radians(angle)));
sf::Vector2f knobPos = objPos + dirNormal * 50.0f;
if (m_editMode != Gizmo::EM_ROTATE_FREE)
{
sf::FloatRect knobRect(knobPos.x - 10.0f, knobPos.y - 10.0f, 20.0f, 20.0f);
if (knobRect.Contains(mousePos))
{
m_editMode = Gizmo::EM_ROTATE_FREE;
}
}
}
break;
case Gizmo::GM_SCALE:
{
float angle = m_selectedObject->getRotation();
sf::Vector2f dirNormal(cos(math::radians(angle)), sin(math::radians(angle)));
sf::Vector2f localXRectPos = objPos + dirNormal * 50.0f;
sf::Vector2f localYRectPos = objPos + math::cross(dirNormal) * 50.0f;
if (m_editMode != Gizmo::EM_SCALE_LOCAL_X && m_editMode != Gizmo::EM_SCALE_LOCAL_Y)
{
sf::FloatRect localXRect(localXRectPos.x - 10.0f, localXRectPos.y - 10.0f, 20.0f, 20.0f);
sf::FloatRect localYRect(localYRectPos.x - 10.0f, localYRectPos.y - 10.0f, 20.0f, 20.0f);
sf::FloatRect freeRect(objPos.x - 10.0f, objPos.y - 10.0f, 20.0f, 20.0f);
if (localXRect.Contains(mousePos))
{
m_editMode = Gizmo::EM_SCALE_LOCAL_X;
}
else if (localYRect.Contains(mousePos))
{
m_editMode = Gizmo::EM_SCALE_LOCAL_Y;
}
else if (freeRect.Contains(mousePos))
{
m_editMode = Gizmo::EM_SCALE_FREE;
}
}
}
break;
}
}
else if (g_input.isMouseButtonFirstUp(sf::Mouse::Left))
{
m_editMode = Gizmo::EM_NONE;
}
if (m_selectedObject != NULL)
{
sf::Vector2f objPos = m_selectedObject->getPosition();
switch (m_editMode)
{
case Gizmo::EM_MOVE_FREE:
{
m_selectedObject->setPosition(sf::Vector2f(objPos.x + g_input.getMouseDelta().x, objPos.y + g_input.getMouseDelta().y));
}
break;
case Gizmo::EM_MOVE_GLOBAL_X:
{
m_selectedObject->setPosition(sf::Vector2f(objPos.x + g_input.getMouseDelta().x, objPos.y));
}
break;
case Gizmo::EM_MOVE_GLOBAL_Y:
{
m_selectedObject->setPosition(sf::Vector2f(objPos.x, objPos.y + g_input.getMouseDelta().y));
}
break;
case Gizmo::EM_ROTATE_FREE:
{
sf::Vector2f mousePos = g_Window->ConvertCoords(g_input.getMouseX(), g_input.getMouseY());
float objectMouseAngle = atan2(mousePos.y - objPos.y, mousePos.x - objPos.x);
m_selectedObject->setRotation(math::degrees(objectMouseAngle));
}
break;
case Gizmo::EM_SCALE_LOCAL_X:
{
sf::Vector2f scale = m_selectedObject->getScale();
scale.x += (float)g_input.getMouseDelta().x / 100.0f;
m_selectedObject->setScale(scale);
}
break;
case Gizmo::EM_SCALE_LOCAL_Y:
{
sf::Vector2f scale = m_selectedObject->getScale();
scale.y += (float)g_input.getMouseDelta().x / 100.0f;
m_selectedObject->setScale(scale);
}
break;
case Gizmo::EM_SCALE_FREE:
{
sf::Vector2f scale = m_selectedObject->getScale();
scale.x += (float)g_input.getMouseDelta().x / 100.0f;
scale.y += (float)g_input.getMouseDelta().x / 100.0f;
m_selectedObject->setScale(scale);
}
break;
}
}
if (g_input.isKeyFirstDown(sf::Key::T))
m_gizmoMode = Gizmo::GM_MOVE;
else if (g_input.isKeyFirstDown(sf::Key::R))
m_gizmoMode = Gizmo::GM_ROTATE;
else if (g_input.isKeyFirstDown(sf::Key::S))
m_gizmoMode = Gizmo::GM_SCALE;
}
void Gizmo::draw(sf::RenderTarget& target)
{
if (m_selectedObject != NULL)
{
sf::Vector2f objPos = m_selectedObject->getPosition();
switch (m_gizmoMode)
{
case Gizmo::GM_MOVE:
{
m_lineUp.SetPosition(objPos);
m_lineRight.SetPosition(objPos);
m_triangleUp.SetPosition(objPos);
m_triangleRight.SetPosition(objPos);
m_rectangleCenter.SetPosition(objPos);
m_rectangleCenter.SetRotation(0.0f);
target.Draw(m_rectangleCenter);
target.Draw(m_lineUp);
target.Draw(m_lineRight);
target.Draw(m_triangleUp);
target.Draw(m_triangleRight);
}
break;
case Gizmo::GM_ROTATE:
{
float angle = m_selectedObject->getRotation();
sf::Vector2f dirNormal(cos(math::radians(angle)), sin(math::radians(angle)));
m_lineRotate.SetPosition(objPos);
m_lineRotate.SetRotation(angle);
m_circleKnob.SetPosition(objPos);
m_circleKnob.SetRotation(angle);
target.Draw(m_lineRotate);
target.Draw(m_circleKnob);
}
break;
case Gizmo::GM_SCALE:
{
float angle = m_selectedObject->getRotation();
sf::Vector2f dirNormal(cos(math::radians(angle)), sin(math::radians(angle)));
m_rectangleCenter.SetPosition(objPos);
m_rectangleCenter.SetRotation(angle);
m_lineScaleBlue.SetPosition(objPos);
m_lineScaleBlue.SetRotation(angle);
m_lineScaleRed.SetPosition(objPos);
m_lineScaleRed.SetRotation(angle);
m_rectangleUp.SetRotation(angle);
m_rectangleUp.SetPosition(objPos);
m_rectangleRight.SetRotation(angle);
m_rectangleRight.SetPosition(objPos);
target.Draw(m_rectangleCenter);
target.Draw(m_lineScaleBlue);
target.Draw(m_lineScaleRed);
target.Draw(m_rectangleUp);
target.Draw(m_rectangleRight);
}
break;
}
}
}
void Gizmo::setMode(GizmoMode mode)
{
m_gizmoMode = mode;
}
void Gizmo::setSelectedObject(Object* object)
{
m_selectedObject = object;
}
Object* Gizmo::getSelectedObject() const
{
return m_selectedObject;
}
| [
"[email protected]"
] | |
f23fa871710db81101d25feb2d9020465b5e1faa | 112c3c38bb126eea23ea75d17512f51ae8aec26d | /third_party/Windows-CalcEngine/src/SingleLayerOptics/tst/SpecularAngularLayerProperty_102.unit.cpp | 1c3ce617ef6a09c1cc46c1eef869c52509cb178d | [
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | tsbyq/EnergyPlus | 1c49fe8e356009d904cff23c9b7640e13d77f72b | 208212976a28f796b2181f8bef621f050518f96d | refs/heads/develop | 2021-07-06T06:56:40.049207 | 2019-02-09T12:27:12 | 2019-02-09T12:27:12 | 136,358,541 | 2 | 0 | NOASSERTION | 2019-02-07T00:39:29 | 2018-06-06T16:46:56 | C++ | UTF-8 | C++ | false | false | 37,329 | cpp | #include <memory>
#include <gtest/gtest.h>
#include "WCESpectralAveraging.hpp"
#include "WCESingleLayerOptics.hpp"
#include "WCECommon.hpp"
using namespace SingleLayerOptics;
using namespace FenestrationCommon;
using namespace SpectralAveraging;
class TestSpecularAngularLayerProperty_102 : public testing::Test {
private:
std::shared_ptr< CAngularMeasurements > m_Measurements;
std::shared_ptr< CBSDFLayer > m_Layer;
std::shared_ptr< CMaterial > m_Material;
std::shared_ptr< CSeries > getSolarRadiationFile() {
std::shared_ptr< CSeries > aSolarRadiation = std::make_shared< CSeries >();
// Full ASTM E891-87 Table 1
aSolarRadiation->addProperty( 0.3000, 0.0 );
aSolarRadiation->addProperty( 0.3050, 3.4 );
aSolarRadiation->addProperty( 0.3100, 15.6 );
aSolarRadiation->addProperty( 0.3150, 41.1 );
aSolarRadiation->addProperty( 0.3200, 71.2 );
aSolarRadiation->addProperty( 0.3250, 100.2 );
aSolarRadiation->addProperty( 0.3300, 152.4 );
aSolarRadiation->addProperty( 0.3350, 155.6 );
aSolarRadiation->addProperty( 0.3400, 179.4 );
aSolarRadiation->addProperty( 0.3450, 186.7 );
aSolarRadiation->addProperty( 0.3500, 212.0 );
aSolarRadiation->addProperty( 0.3600, 240.5 );
aSolarRadiation->addProperty( 0.3700, 324.0 );
aSolarRadiation->addProperty( 0.3800, 362.4 );
aSolarRadiation->addProperty( 0.3900, 381.7 );
aSolarRadiation->addProperty( 0.4000, 556.0 );
aSolarRadiation->addProperty( 0.4100, 656.3 );
aSolarRadiation->addProperty( 0.4200, 690.8 );
aSolarRadiation->addProperty( 0.4300, 641.9 );
aSolarRadiation->addProperty( 0.4400, 798.5 );
aSolarRadiation->addProperty( 0.4500, 956.6 );
aSolarRadiation->addProperty( 0.4600, 990.0 );
aSolarRadiation->addProperty( 0.4700, 998.0 );
aSolarRadiation->addProperty( 0.4800, 1046.1 );
aSolarRadiation->addProperty( 0.4900, 1005.1 );
aSolarRadiation->addProperty( 0.5000, 1026.7 );
aSolarRadiation->addProperty( 0.5100, 1066.7 );
aSolarRadiation->addProperty( 0.5200, 1011.5 );
aSolarRadiation->addProperty( 0.5300, 1084.9 );
aSolarRadiation->addProperty( 0.5400, 1082.4 );
aSolarRadiation->addProperty( 0.5500, 1102.2 );
aSolarRadiation->addProperty( 0.5700, 1087.4 );
aSolarRadiation->addProperty( 0.5900, 1024.3 );
aSolarRadiation->addProperty( 0.6100, 1088.8 );
aSolarRadiation->addProperty( 0.6300, 1062.1 );
aSolarRadiation->addProperty( 0.6500, 1061.7 );
aSolarRadiation->addProperty( 0.6700, 1046.2 );
aSolarRadiation->addProperty( 0.6900, 859.2 );
aSolarRadiation->addProperty( 0.7100, 1002.4 );
aSolarRadiation->addProperty( 0.7180, 816.9 );
aSolarRadiation->addProperty( 0.7244, 842.8 );
aSolarRadiation->addProperty( 0.7400, 971.0 );
aSolarRadiation->addProperty( 0.7525, 956.3 );
aSolarRadiation->addProperty( 0.7575, 942.2 );
aSolarRadiation->addProperty( 0.7625, 524.8 );
aSolarRadiation->addProperty( 0.7675, 830.7 );
aSolarRadiation->addProperty( 0.7800, 908.9 );
aSolarRadiation->addProperty( 0.8000, 873.4 );
aSolarRadiation->addProperty( 0.8160, 712.0 );
aSolarRadiation->addProperty( 0.8237, 660.2 );
aSolarRadiation->addProperty( 0.8315, 765.5 );
aSolarRadiation->addProperty( 0.8400, 799.8 );
aSolarRadiation->addProperty( 0.8600, 815.2 );
aSolarRadiation->addProperty( 0.8800, 778.3 );
aSolarRadiation->addProperty( 0.9050, 630.4 );
aSolarRadiation->addProperty( 0.9150, 565.2 );
aSolarRadiation->addProperty( 0.9250, 586.4 );
aSolarRadiation->addProperty( 0.9300, 348.1 );
aSolarRadiation->addProperty( 0.9370, 224.2 );
aSolarRadiation->addProperty( 0.9480, 271.4 );
aSolarRadiation->addProperty( 0.9650, 451.2 );
aSolarRadiation->addProperty( 0.9800, 549.7 );
aSolarRadiation->addProperty( 0.9935, 630.1 );
aSolarRadiation->addProperty( 1.0400, 582.9 );
aSolarRadiation->addProperty( 1.0700, 539.7 );
aSolarRadiation->addProperty( 1.1000, 366.2 );
aSolarRadiation->addProperty( 1.1200, 98.1 );
aSolarRadiation->addProperty( 1.1300, 169.5 );
aSolarRadiation->addProperty( 1.1370, 118.7 );
aSolarRadiation->addProperty( 1.1610, 301.9 );
aSolarRadiation->addProperty( 1.1800, 406.8 );
aSolarRadiation->addProperty( 1.2000, 375.2 );
aSolarRadiation->addProperty( 1.2350, 423.6 );
aSolarRadiation->addProperty( 1.2900, 365.7 );
aSolarRadiation->addProperty( 1.3200, 223.4 );
aSolarRadiation->addProperty( 1.3500, 30.1 );
aSolarRadiation->addProperty( 1.3950, 1.4 );
aSolarRadiation->addProperty( 1.4425, 51.6 );
aSolarRadiation->addProperty( 1.4625, 97.0 );
aSolarRadiation->addProperty( 1.4770, 97.3 );
aSolarRadiation->addProperty( 1.4970, 167.1 );
aSolarRadiation->addProperty( 1.5200, 239.3 );
aSolarRadiation->addProperty( 1.5390, 248.8 );
aSolarRadiation->addProperty( 1.5580, 249.3 );
aSolarRadiation->addProperty( 1.5780, 222.3 );
aSolarRadiation->addProperty( 1.5920, 227.3 );
aSolarRadiation->addProperty( 1.6100, 210.5 );
aSolarRadiation->addProperty( 1.6300, 224.7 );
aSolarRadiation->addProperty( 1.6460, 215.9 );
aSolarRadiation->addProperty( 1.6780, 202.8 );
aSolarRadiation->addProperty( 1.7400, 158.2 );
aSolarRadiation->addProperty( 1.8000, 28.6 );
aSolarRadiation->addProperty( 1.8600, 1.8 );
aSolarRadiation->addProperty( 1.9200, 1.1 );
aSolarRadiation->addProperty( 1.9600, 19.7 );
aSolarRadiation->addProperty( 1.9850, 84.9 );
aSolarRadiation->addProperty( 2.0050, 25.0 );
aSolarRadiation->addProperty( 2.0350, 92.5 );
aSolarRadiation->addProperty( 2.0650, 56.3 );
aSolarRadiation->addProperty( 2.1000, 82.7 );
aSolarRadiation->addProperty( 2.1480, 76.2 );
aSolarRadiation->addProperty( 2.1980, 66.4 );
aSolarRadiation->addProperty( 2.2700, 65.0 );
aSolarRadiation->addProperty( 2.3600, 57.6 );
aSolarRadiation->addProperty( 2.4500, 19.8 );
aSolarRadiation->addProperty( 2.4940, 17.0 );
aSolarRadiation->addProperty( 2.5370, 3.0 );
aSolarRadiation->addProperty( 2.9410, 4.0 );
aSolarRadiation->addProperty( 2.9730, 7.0 );
aSolarRadiation->addProperty( 3.0050, 6.0 );
aSolarRadiation->addProperty( 3.0560, 3.0 );
aSolarRadiation->addProperty( 3.1320, 5.0 );
aSolarRadiation->addProperty( 3.1560, 18.0 );
aSolarRadiation->addProperty( 3.2040, 1.2 );
aSolarRadiation->addProperty( 3.2450, 3.0 );
aSolarRadiation->addProperty( 3.3170, 12.0 );
aSolarRadiation->addProperty( 3.3440, 3.0 );
aSolarRadiation->addProperty( 3.4500, 12.2 );
aSolarRadiation->addProperty( 3.5730, 11.0 );
aSolarRadiation->addProperty( 3.7650, 9.0 );
aSolarRadiation->addProperty( 4.0450, 6.9 );
return aSolarRadiation;
}
std::shared_ptr< CSingleAngularMeasurement > getSample1() {
std::shared_ptr< CSeries > aSolarRadiation = getSolarRadiationFile();
std::shared_ptr< CSpectralSampleData > aMeasurements0 = std::make_shared< CSpectralSampleData >();
// incident angle = 0
aMeasurements0->addRecord( 0.290, 0, 0.0481, 0.0481 );
aMeasurements0->addRecord( 0.295, 0, 0.0479, 0.0479 );
aMeasurements0->addRecord( 0.300, 0, 0.0476, 0.0476 );
aMeasurements0->addRecord( 0.305, 0, 0.0474, 0.0474 );
aMeasurements0->addRecord( 0.310, 0.007, 0.0471, 0.0471 );
aMeasurements0->addRecord( 0.315, 0.035, 0.047, 0.047 );
aMeasurements0->addRecord( 0.320, 0.0975, 0.0472, 0.0472 );
aMeasurements0->addRecord( 0.325, 0.2099, 0.0487, 0.0487 );
aMeasurements0->addRecord( 0.330, 0.3497, 0.0525, 0.0525 );
aMeasurements0->addRecord( 0.335, 0.4865, 0.0581, 0.0581 );
aMeasurements0->addRecord( 0.340, 0.6057, 0.0644, 0.0644 );
aMeasurements0->addRecord( 0.345, 0.7035, 0.0706, 0.0706 );
aMeasurements0->addRecord( 0.350, 0.7687, 0.0751, 0.0751 );
aMeasurements0->addRecord( 0.355, 0.812, 0.0783, 0.0783 );
aMeasurements0->addRecord( 0.360, 0.8429, 0.0806, 0.0806 );
aMeasurements0->addRecord( 0.365, 0.862, 0.0819, 0.0819 );
aMeasurements0->addRecord( 0.370, 0.8678, 0.0821, 0.0821 );
aMeasurements0->addRecord( 0.375, 0.8672, 0.0819, 0.0819 );
aMeasurements0->addRecord( 0.380, 0.8554, 0.0806, 0.0806 );
aMeasurements0->addRecord( 0.385, 0.8696, 0.0816, 0.0816 );
aMeasurements0->addRecord( 0.390, 0.8804, 0.0823, 0.0823 );
aMeasurements0->addRecord( 0.395, 0.8884, 0.0828, 0.0828 );
aMeasurements0->addRecord( 0.400, 0.8924, 0.083, 0.083 );
aMeasurements0->addRecord( 0.410, 0.8944, 0.0828, 0.0828 );
aMeasurements0->addRecord( 0.420, 0.8921, 0.0823, 0.0823 );
aMeasurements0->addRecord( 0.430, 0.8914, 0.082, 0.082 );
aMeasurements0->addRecord( 0.440, 0.8896, 0.0815, 0.0815 );
aMeasurements0->addRecord( 0.450, 0.8933, 0.0816, 0.0816 );
aMeasurements0->addRecord( 0.460, 0.8972, 0.0817, 0.0817 );
aMeasurements0->addRecord( 0.470, 0.8991, 0.0816, 0.0816 );
aMeasurements0->addRecord( 0.480, 0.9013, 0.0816, 0.0816 );
aMeasurements0->addRecord( 0.490, 0.9026, 0.0815, 0.0815 );
aMeasurements0->addRecord( 0.500, 0.9026, 0.0813, 0.0813 );
aMeasurements0->addRecord( 0.510, 0.9031, 0.0811, 0.0811 );
aMeasurements0->addRecord( 0.520, 0.9025, 0.0809, 0.0809 );
aMeasurements0->addRecord( 0.530, 0.9028, 0.0808, 0.0808 );
aMeasurements0->addRecord( 0.540, 0.9033, 0.0807, 0.0807 );
aMeasurements0->addRecord( 0.550, 0.9013, 0.0804, 0.0804 );
aMeasurements0->addRecord( 0.560, 0.8999, 0.0802, 0.0802 );
aMeasurements0->addRecord( 0.570, 0.8986, 0.0799, 0.0799 );
aMeasurements0->addRecord( 0.580, 0.8975, 0.0797, 0.0797 );
aMeasurements0->addRecord( 0.590, 0.8939, 0.0793, 0.0793 );
aMeasurements0->addRecord( 0.600, 0.8919, 0.079, 0.079 );
aMeasurements0->addRecord( 0.610, 0.891, 0.0789, 0.0789 );
aMeasurements0->addRecord( 0.620, 0.8853, 0.0783, 0.0783 );
aMeasurements0->addRecord( 0.630, 0.8838, 0.0781, 0.0781 );
aMeasurements0->addRecord( 0.640, 0.8806, 0.0777, 0.0777 );
aMeasurements0->addRecord( 0.650, 0.8769, 0.0773, 0.0773 );
aMeasurements0->addRecord( 0.660, 0.8735, 0.077, 0.077 );
aMeasurements0->addRecord( 0.670, 0.8731, 0.0769, 0.0769 );
aMeasurements0->addRecord( 0.680, 0.8665, 0.0763, 0.0763 );
aMeasurements0->addRecord( 0.690, 0.8637, 0.076, 0.076 );
aMeasurements0->addRecord( 0.700, 0.8607, 0.0757, 0.0757 );
aMeasurements0->addRecord( 0.710, 0.8557, 0.0753, 0.0753 );
aMeasurements0->addRecord( 0.720, 0.8531, 0.075, 0.075 );
aMeasurements0->addRecord( 0.730, 0.8487, 0.0746, 0.0746 );
aMeasurements0->addRecord( 0.740, 0.8418, 0.074, 0.074 );
aMeasurements0->addRecord( 0.750, 0.8406, 0.0738, 0.0738 );
aMeasurements0->addRecord( 0.760, 0.8358, 0.0734, 0.0734 );
aMeasurements0->addRecord( 0.770, 0.8341, 0.0732, 0.0732 );
aMeasurements0->addRecord( 0.780, 0.8324, 0.073, 0.073 );
aMeasurements0->addRecord( 0.790, 0.8232, 0.0723, 0.0723 );
aMeasurements0->addRecord( 0.800, 0.8246, 0.0723, 0.0723 );
aMeasurements0->addRecord( 0.850, 0.8076, 0.0708, 0.0708 );
aMeasurements0->addRecord( 0.900, 0.8002, 0.07, 0.07 );
aMeasurements0->addRecord( 0.950, 0.7907, 0.0692, 0.0692 );
aMeasurements0->addRecord( 1.000, 0.7862, 0.0687, 0.0687 );
aMeasurements0->addRecord( 1.050, 0.7849, 0.0685, 0.0685 );
aMeasurements0->addRecord( 1.100, 0.7848, 0.0683, 0.0683 );
aMeasurements0->addRecord( 1.150, 0.7864, 0.0683, 0.0683 );
aMeasurements0->addRecord( 1.200, 0.7894, 0.0685, 0.0685 );
aMeasurements0->addRecord( 1.250, 0.7944, 0.0687, 0.0687 );
aMeasurements0->addRecord( 1.300, 0.8014, 0.0691, 0.0691 );
aMeasurements0->addRecord( 1.350, 0.8088, 0.0695, 0.0695 );
aMeasurements0->addRecord( 1.400, 0.8168, 0.07, 0.07 );
aMeasurements0->addRecord( 1.450, 0.8261, 0.0705, 0.0705 );
aMeasurements0->addRecord( 1.500, 0.8366, 0.0712, 0.0712 );
aMeasurements0->addRecord( 1.550, 0.8444, 0.0716, 0.0716 );
aMeasurements0->addRecord( 1.600, 0.8506, 0.0719, 0.0719 );
aMeasurements0->addRecord( 1.650, 0.853, 0.072, 0.072 );
aMeasurements0->addRecord( 1.700, 0.8527, 0.0719, 0.0719 );
aMeasurements0->addRecord( 1.750, 0.8532, 0.0718, 0.0718 );
aMeasurements0->addRecord( 1.800, 0.8504, 0.0714, 0.0714 );
aMeasurements0->addRecord( 1.850, 0.8488, 0.0712, 0.0712 );
aMeasurements0->addRecord( 1.900, 0.8523, 0.0713, 0.0713 );
aMeasurements0->addRecord( 1.950, 0.8497, 0.071, 0.071 );
aMeasurements0->addRecord( 2.000, 0.848, 0.0708, 0.0708 );
aMeasurements0->addRecord( 2.050, 0.8488, 0.0707, 0.0707 );
aMeasurements0->addRecord( 2.100, 0.8505, 0.0707, 0.0707 );
aMeasurements0->addRecord( 2.150, 0.8408, 0.0699, 0.0699 );
aMeasurements0->addRecord( 2.200, 0.8304, 0.0691, 0.0691 );
aMeasurements0->addRecord( 2.250, 0.8277, 0.0688, 0.0688 );
aMeasurements0->addRecord( 2.300, 0.8303, 0.0688, 0.0688 );
aMeasurements0->addRecord( 2.350, 0.834, 0.069, 0.069 );
aMeasurements0->addRecord( 2.400, 0.8236, 0.0681, 0.0681 );
aMeasurements0->addRecord( 2.450, 0.8225, 0.0679, 0.0679 );
aMeasurements0->addRecord( 2.500, 0.8184, 0.0675, 0.0675 );
std::shared_ptr< CSpectralSample > aSample0 = std::make_shared< CSpectralSample >( aMeasurements0, aSolarRadiation );
std::shared_ptr< CSingleAngularMeasurement > aAngular0 = std::make_shared< CSingleAngularMeasurement >( aSample0, 0.0 );
return aAngular0;
}
std::shared_ptr< CSingleAngularMeasurement > getSample2() {
std::shared_ptr< CSeries > aSolarRadiation = getSolarRadiationFile();
std::shared_ptr< CSpectralSampleData > aMeasurements1 = std::make_shared< CSpectralSampleData >();
// incident angle = 10
aMeasurements1->addRecord( 0.290, 0, 0.0481, 0.0481 );
aMeasurements1->addRecord( 0.295, 0, 0.0479, 0.0479 );
aMeasurements1->addRecord( 0.300, 0, 0.0476, 0.0476 );
aMeasurements1->addRecord( 0.305, 0, 0.0474, 0.0474 );
aMeasurements1->addRecord( 0.310, 0.0068, 0.0471, 0.0471 );
aMeasurements1->addRecord( 0.315, 0.0343, 0.047, 0.047 );
aMeasurements1->addRecord( 0.320, 0.0961, 0.0472, 0.0472 );
aMeasurements1->addRecord( 0.325, 0.208, 0.0487, 0.0487 );
aMeasurements1->addRecord( 0.330, 0.3476, 0.0524, 0.0524 );
aMeasurements1->addRecord( 0.335, 0.4845, 0.058, 0.058 );
aMeasurements1->addRecord( 0.340, 0.6041, 0.0643, 0.0643 );
aMeasurements1->addRecord( 0.345, 0.7023, 0.0705, 0.0705 );
aMeasurements1->addRecord( 0.350, 0.7678, 0.0751, 0.0751 );
aMeasurements1->addRecord( 0.355, 0.8114, 0.0783, 0.0783 );
aMeasurements1->addRecord( 0.360, 0.8424, 0.0805, 0.0805 );
aMeasurements1->addRecord( 0.365, 0.8617, 0.0819, 0.0819 );
aMeasurements1->addRecord( 0.370, 0.8675, 0.0821, 0.0821 );
aMeasurements1->addRecord( 0.375, 0.8669, 0.0819, 0.0819 );
aMeasurements1->addRecord( 0.380, 0.8551, 0.0806, 0.0806 );
aMeasurements1->addRecord( 0.385, 0.8693, 0.0816, 0.0816 );
aMeasurements1->addRecord( 0.390, 0.8802, 0.0823, 0.0823 );
aMeasurements1->addRecord( 0.395, 0.8882, 0.0829, 0.0829 );
aMeasurements1->addRecord( 0.400, 0.8922, 0.083, 0.083 );
aMeasurements1->addRecord( 0.410, 0.8943, 0.0829, 0.0829 );
aMeasurements1->addRecord( 0.420, 0.8919, 0.0823, 0.0823 );
aMeasurements1->addRecord( 0.430, 0.8912, 0.082, 0.082 );
aMeasurements1->addRecord( 0.440, 0.8894, 0.0815, 0.0815 );
aMeasurements1->addRecord( 0.450, 0.8931, 0.0816, 0.0816 );
aMeasurements1->addRecord( 0.460, 0.8971, 0.0817, 0.0817 );
aMeasurements1->addRecord( 0.470, 0.8989, 0.0816, 0.0816 );
aMeasurements1->addRecord( 0.480, 0.9011, 0.0816, 0.0816 );
aMeasurements1->addRecord( 0.490, 0.9025, 0.0815, 0.0815 );
aMeasurements1->addRecord( 0.500, 0.9025, 0.0813, 0.0813 );
aMeasurements1->addRecord( 0.510, 0.903, 0.0812, 0.0812 );
aMeasurements1->addRecord( 0.520, 0.9024, 0.0809, 0.0809 );
aMeasurements1->addRecord( 0.530, 0.9027, 0.0808, 0.0808 );
aMeasurements1->addRecord( 0.540, 0.9032, 0.0807, 0.0807 );
aMeasurements1->addRecord( 0.550, 0.9011, 0.0804, 0.0804 );
aMeasurements1->addRecord( 0.560, 0.8998, 0.0802, 0.0802 );
aMeasurements1->addRecord( 0.570, 0.8985, 0.0799, 0.0799 );
aMeasurements1->addRecord( 0.580, 0.8974, 0.0797, 0.0797 );
aMeasurements1->addRecord( 0.590, 0.8937, 0.0793, 0.0793 );
aMeasurements1->addRecord( 0.600, 0.8917, 0.079, 0.079 );
aMeasurements1->addRecord( 0.610, 0.8908, 0.0789, 0.0789 );
aMeasurements1->addRecord( 0.620, 0.885, 0.0783, 0.0783 );
aMeasurements1->addRecord( 0.630, 0.8835, 0.0781, 0.0781 );
aMeasurements1->addRecord( 0.640, 0.8803, 0.0777, 0.0777 );
aMeasurements1->addRecord( 0.650, 0.8766, 0.0774, 0.0774 );
aMeasurements1->addRecord( 0.660, 0.8732, 0.077, 0.077 );
aMeasurements1->addRecord( 0.670, 0.8728, 0.0769, 0.0769 );
aMeasurements1->addRecord( 0.680, 0.8662, 0.0763, 0.0763 );
aMeasurements1->addRecord( 0.690, 0.8633, 0.076, 0.076 );
aMeasurements1->addRecord( 0.700, 0.8603, 0.0757, 0.0757 );
aMeasurements1->addRecord( 0.710, 0.8552, 0.0753, 0.0753 );
aMeasurements1->addRecord( 0.720, 0.8527, 0.075, 0.075 );
aMeasurements1->addRecord( 0.730, 0.8482, 0.0746, 0.0746 );
aMeasurements1->addRecord( 0.740, 0.8413, 0.074, 0.074 );
aMeasurements1->addRecord( 0.750, 0.8401, 0.0738, 0.0738 );
aMeasurements1->addRecord( 0.760, 0.8352, 0.0734, 0.0734 );
aMeasurements1->addRecord( 0.770, 0.8335, 0.0732, 0.0732 );
aMeasurements1->addRecord( 0.780, 0.8318, 0.073, 0.073 );
aMeasurements1->addRecord( 0.790, 0.8225, 0.0722, 0.0722 );
aMeasurements1->addRecord( 0.800, 0.824, 0.0723, 0.0723 );
aMeasurements1->addRecord( 0.850, 0.8069, 0.0708, 0.0708 );
aMeasurements1->addRecord( 0.900, 0.7994, 0.07, 0.07 );
aMeasurements1->addRecord( 0.950, 0.7899, 0.0691, 0.0691 );
aMeasurements1->addRecord( 1.000, 0.7854, 0.0686, 0.0686 );
aMeasurements1->addRecord( 1.050, 0.7841, 0.0684, 0.0684 );
aMeasurements1->addRecord( 1.100, 0.7839, 0.0683, 0.0683 );
aMeasurements1->addRecord( 1.150, 0.7856, 0.0683, 0.0683 );
aMeasurements1->addRecord( 1.200, 0.7886, 0.0684, 0.0684 );
aMeasurements1->addRecord( 1.250, 0.7936, 0.0687, 0.0687 );
aMeasurements1->addRecord( 1.300, 0.8006, 0.069, 0.069 );
aMeasurements1->addRecord( 1.350, 0.8081, 0.0695, 0.0695 );
aMeasurements1->addRecord( 1.400, 0.8162, 0.0699, 0.0699 );
aMeasurements1->addRecord( 1.450, 0.8255, 0.0705, 0.0705 );
aMeasurements1->addRecord( 1.500, 0.836, 0.0711, 0.0711 );
aMeasurements1->addRecord( 1.550, 0.8439, 0.0716, 0.0716 );
aMeasurements1->addRecord( 1.600, 0.8501, 0.0719, 0.0719 );
aMeasurements1->addRecord( 1.650, 0.8525, 0.072, 0.072 );
aMeasurements1->addRecord( 1.700, 0.8522, 0.0719, 0.0719 );
aMeasurements1->addRecord( 1.750, 0.8527, 0.0718, 0.0718 );
aMeasurements1->addRecord( 1.800, 0.8499, 0.0714, 0.0714 );
aMeasurements1->addRecord( 1.850, 0.8483, 0.0712, 0.0712 );
aMeasurements1->addRecord( 1.900, 0.8518, 0.0713, 0.0713 );
aMeasurements1->addRecord( 1.950, 0.8492, 0.071, 0.071 );
aMeasurements1->addRecord( 2.000, 0.8475, 0.0708, 0.0708 );
aMeasurements1->addRecord( 2.050, 0.8483, 0.0707, 0.0707 );
aMeasurements1->addRecord( 2.100, 0.85, 0.0707, 0.0707 );
aMeasurements1->addRecord( 2.150, 0.8402, 0.0699, 0.0699 );
aMeasurements1->addRecord( 2.200, 0.8298, 0.069, 0.069 );
aMeasurements1->addRecord( 2.250, 0.8271, 0.0687, 0.0687 );
aMeasurements1->addRecord( 2.300, 0.8297, 0.0688, 0.0688 );
aMeasurements1->addRecord( 2.350, 0.8334, 0.069, 0.069 );
aMeasurements1->addRecord( 2.400, 0.823, 0.0681, 0.0681 );
aMeasurements1->addRecord( 2.450, 0.8218, 0.0679, 0.0679 );
aMeasurements1->addRecord( 2.500, 0.8176, 0.0675, 0.0675 );
std::shared_ptr< CSpectralSample > aSample1 = std::make_shared< CSpectralSample >( aMeasurements1, aSolarRadiation );
std::shared_ptr< CSingleAngularMeasurement > aAngular1 = std::make_shared< CSingleAngularMeasurement >( aSample1, 10.0 );
return aAngular1;
}
std::shared_ptr< CSingleAngularMeasurement > getSample3() {
std::shared_ptr< CSeries > aSolarRadiation = getSolarRadiationFile();
std::shared_ptr< CSpectralSampleData > aMeasurements4 = std::make_shared< CSpectralSampleData >();
// incident angle = 40
aMeasurements4->addRecord( 0.290, 0, 0.0993, 0.0993 );
aMeasurements4->addRecord( 0.295, 0, 0.099, 0.099 );
aMeasurements4->addRecord( 0.300, 0, 0.0986, 0.0986 );
aMeasurements4->addRecord( 0.305, 0, 0.0984, 0.0984 );
aMeasurements4->addRecord( 0.310, 0.0023, 0.098, 0.098 );
aMeasurements4->addRecord( 0.315, 0.0161, 0.0978, 0.0978 );
aMeasurements4->addRecord( 0.320, 0.0553, 0.0979, 0.0979 );
aMeasurements4->addRecord( 0.325, 0.1392, 0.0996, 0.0996 );
aMeasurements4->addRecord( 0.330, 0.2575, 0.1049, 0.1049 );
aMeasurements4->addRecord( 0.335, 0.3836, 0.1143, 0.1143 );
aMeasurements4->addRecord( 0.340, 0.5002, 0.1261, 0.1261 );
aMeasurements4->addRecord( 0.345, 0.5999, 0.1387, 0.1387 );
aMeasurements4->addRecord( 0.350, 0.6682, 0.1485, 0.1485 );
aMeasurements4->addRecord( 0.355, 0.7145, 0.1556, 0.1556 );
aMeasurements4->addRecord( 0.360, 0.7478, 0.1609, 0.1609 );
aMeasurements4->addRecord( 0.365, 0.7686, 0.1643, 0.1643 );
aMeasurements4->addRecord( 0.370, 0.775, 0.1651, 0.1651 );
aMeasurements4->addRecord( 0.375, 0.7743, 0.1647, 0.1647 );
aMeasurements4->addRecord( 0.380, 0.7614, 0.1622, 0.1622 );
aMeasurements4->addRecord( 0.385, 0.7769, 0.1646, 0.1646 );
aMeasurements4->addRecord( 0.390, 0.7887, 0.1665, 0.1665 );
aMeasurements4->addRecord( 0.395, 0.7975, 0.1678, 0.1678 );
aMeasurements4->addRecord( 0.400, 0.8019, 0.1684, 0.1684 );
aMeasurements4->addRecord( 0.410, 0.8042, 0.1684, 0.1684 );
aMeasurements4->addRecord( 0.420, 0.8015, 0.1675, 0.1675 );
aMeasurements4->addRecord( 0.430, 0.8008, 0.167, 0.167 );
aMeasurements4->addRecord( 0.440, 0.7988, 0.1663, 0.1663 );
aMeasurements4->addRecord( 0.450, 0.8028, 0.1668, 0.1668 );
aMeasurements4->addRecord( 0.460, 0.8073, 0.1673, 0.1673 );
aMeasurements4->addRecord( 0.470, 0.8093, 0.1674, 0.1674 );
aMeasurements4->addRecord( 0.480, 0.8117, 0.1675, 0.1675 );
aMeasurements4->addRecord( 0.490, 0.8132, 0.1675, 0.1675 );
aMeasurements4->addRecord( 0.500, 0.8132, 0.1673, 0.1673 );
aMeasurements4->addRecord( 0.510, 0.8138, 0.1672, 0.1672 );
aMeasurements4->addRecord( 0.520, 0.8131, 0.1668, 0.1668 );
aMeasurements4->addRecord( 0.530, 0.8135, 0.1667, 0.1667 );
aMeasurements4->addRecord( 0.540, 0.814, 0.1666, 0.1666 );
aMeasurements4->addRecord( 0.550, 0.8117, 0.1661, 0.1661 );
aMeasurements4->addRecord( 0.560, 0.8102, 0.1656, 0.1656 );
aMeasurements4->addRecord( 0.570, 0.8088, 0.1652, 0.1652 );
aMeasurements4->addRecord( 0.580, 0.8076, 0.1648, 0.1648 );
aMeasurements4->addRecord( 0.590, 0.8035, 0.164, 0.164 );
aMeasurements4->addRecord( 0.600, 0.8013, 0.1634, 0.1634 );
aMeasurements4->addRecord( 0.610, 0.8003, 0.1632, 0.1632 );
aMeasurements4->addRecord( 0.620, 0.794, 0.1619, 0.1619 );
aMeasurements4->addRecord( 0.630, 0.7923, 0.1615, 0.1615 );
aMeasurements4->addRecord( 0.640, 0.7888, 0.1608, 0.1608 );
aMeasurements4->addRecord( 0.650, 0.7848, 0.16, 0.16 );
aMeasurements4->addRecord( 0.660, 0.781, 0.1593, 0.1593 );
aMeasurements4->addRecord( 0.670, 0.7806, 0.1591, 0.1591 );
aMeasurements4->addRecord( 0.680, 0.7733, 0.1578, 0.1578 );
aMeasurements4->addRecord( 0.690, 0.7702, 0.1571, 0.1571 );
aMeasurements4->addRecord( 0.700, 0.7669, 0.1565, 0.1565 );
aMeasurements4->addRecord( 0.710, 0.7614, 0.1555, 0.1555 );
aMeasurements4->addRecord( 0.720, 0.7586, 0.155, 0.155 );
aMeasurements4->addRecord( 0.730, 0.7537, 0.1541, 0.1541 );
aMeasurements4->addRecord( 0.740, 0.7462, 0.1528, 0.1528 );
aMeasurements4->addRecord( 0.750, 0.7449, 0.1525, 0.1525 );
aMeasurements4->addRecord( 0.760, 0.7396, 0.1515, 0.1515 );
aMeasurements4->addRecord( 0.770, 0.7378, 0.1512, 0.1512 );
aMeasurements4->addRecord( 0.780, 0.7359, 0.1508, 0.1508 );
aMeasurements4->addRecord( 0.790, 0.7259, 0.1491, 0.1491 );
aMeasurements4->addRecord( 0.800, 0.7275, 0.1493, 0.1493 );
aMeasurements4->addRecord( 0.850, 0.709, 0.1461, 0.1461 );
aMeasurements4->addRecord( 0.900, 0.7009, 0.1445, 0.1445 );
aMeasurements4->addRecord( 0.950, 0.6907, 0.1428, 0.1428 );
aMeasurements4->addRecord( 1.000, 0.6858, 0.1418, 0.1418 );
aMeasurements4->addRecord( 1.050, 0.6844, 0.1415, 0.1415 );
aMeasurements4->addRecord( 1.100, 0.6843, 0.1413, 0.1413 );
aMeasurements4->addRecord( 1.150, 0.686, 0.1414, 0.1414 );
aMeasurements4->addRecord( 1.200, 0.6892, 0.1418, 0.1418 );
aMeasurements4->addRecord( 1.250, 0.6946, 0.1424, 0.1424 );
aMeasurements4->addRecord( 1.300, 0.7021, 0.1434, 0.1434 );
aMeasurements4->addRecord( 1.350, 0.7101, 0.1445, 0.1445 );
aMeasurements4->addRecord( 1.400, 0.7188, 0.1457, 0.1457 );
aMeasurements4->addRecord( 1.450, 0.729, 0.1471, 0.1471 );
aMeasurements4->addRecord( 1.500, 0.7404, 0.1488, 0.1488 );
aMeasurements4->addRecord( 1.550, 0.7489, 0.15, 0.15 );
aMeasurements4->addRecord( 1.600, 0.7557, 0.1509, 0.1509 );
aMeasurements4->addRecord( 1.650, 0.7583, 0.1512, 0.1512 );
aMeasurements4->addRecord( 1.700, 0.758, 0.151, 0.151 );
aMeasurements4->addRecord( 1.750, 0.7585, 0.1509, 0.1509 );
aMeasurements4->addRecord( 1.800, 0.7554, 0.1503, 0.1503 );
aMeasurements4->addRecord( 1.850, 0.7537, 0.1498, 0.1498 );
aMeasurements4->addRecord( 1.900, 0.7575, 0.1503, 0.1503 );
aMeasurements4->addRecord( 1.950, 0.7546, 0.1497, 0.1497 );
aMeasurements4->addRecord( 2.000, 0.7528, 0.1492, 0.1492 );
aMeasurements4->addRecord( 2.050, 0.7536, 0.1492, 0.1492 );
aMeasurements4->addRecord( 2.100, 0.7555, 0.1494, 0.1494 );
aMeasurements4->addRecord( 2.150, 0.7449, 0.1475, 0.1475 );
aMeasurements4->addRecord( 2.200, 0.7335, 0.1456, 0.1456 );
aMeasurements4->addRecord( 2.250, 0.7305, 0.145, 0.145 );
aMeasurements4->addRecord( 2.300, 0.7334, 0.1453, 0.1453 );
aMeasurements4->addRecord( 2.350, 0.7374, 0.1458, 0.1458 );
aMeasurements4->addRecord( 2.400, 0.7261, 0.1439, 0.1439 );
aMeasurements4->addRecord( 2.450, 0.7248, 0.1436, 0.1436 );
aMeasurements4->addRecord( 2.500, 0.7203, 0.1427, 0.1427 );
std::shared_ptr< CSpectralSample > aSample4 = std::make_shared< CSpectralSample >( aMeasurements4, aSolarRadiation );
std::shared_ptr< CSingleAngularMeasurement > aAngular4 = std::make_shared< CSingleAngularMeasurement >( aSample4, 40.0 );
return aAngular4;
}
std::shared_ptr< CSingleAngularMeasurement > getSample4() {
std::shared_ptr< CSeries > aSolarRadiation = getSolarRadiationFile();
std::shared_ptr< CSpectralSampleData > aMeasurements9 = std::make_shared< CSpectralSampleData >();
// incident angle = 90
aMeasurements9->addRecord( 0.290, 0, 1, 1 );
aMeasurements9->addRecord( 0.295, 0, 1, 1 );
aMeasurements9->addRecord( 0.300, 0, 1, 1 );
aMeasurements9->addRecord( 0.305, 0, 1, 1 );
aMeasurements9->addRecord( 0.310, 0, 1, 1 );
aMeasurements9->addRecord( 0.315, 0, 1, 1 );
aMeasurements9->addRecord( 0.320, 0, 1, 1 );
aMeasurements9->addRecord( 0.325, 0, 1, 1 );
aMeasurements9->addRecord( 0.330, 0, 1, 1 );
aMeasurements9->addRecord( 0.335, 0, 1, 1 );
aMeasurements9->addRecord( 0.340, 0, 1, 1 );
aMeasurements9->addRecord( 0.345, 0, 1, 1 );
aMeasurements9->addRecord( 0.350, 0, 1, 1 );
aMeasurements9->addRecord( 0.355, 0, 1, 1 );
aMeasurements9->addRecord( 0.360, 0, 1, 1 );
aMeasurements9->addRecord( 0.365, 0, 1, 1 );
aMeasurements9->addRecord( 0.370, 0, 1, 1 );
aMeasurements9->addRecord( 0.375, 0, 1, 1 );
aMeasurements9->addRecord( 0.380, 0, 1, 1 );
aMeasurements9->addRecord( 0.385, 0, 1, 1 );
aMeasurements9->addRecord( 0.390, 0, 1, 1 );
aMeasurements9->addRecord( 0.395, 0, 1, 1 );
aMeasurements9->addRecord( 0.400, 0, 1, 1 );
aMeasurements9->addRecord( 0.410, 0, 1, 1 );
aMeasurements9->addRecord( 0.420, 0, 1, 1 );
aMeasurements9->addRecord( 0.430, 0, 1, 1 );
aMeasurements9->addRecord( 0.440, 0, 1, 1 );
aMeasurements9->addRecord( 0.450, 0, 1, 1 );
aMeasurements9->addRecord( 0.460, 0, 1, 1 );
aMeasurements9->addRecord( 0.470, 0, 1, 1 );
aMeasurements9->addRecord( 0.480, 0, 1, 1 );
aMeasurements9->addRecord( 0.490, 0, 1, 1 );
aMeasurements9->addRecord( 0.500, 0, 1, 1 );
aMeasurements9->addRecord( 0.510, 0, 1, 1 );
aMeasurements9->addRecord( 0.520, 0, 1, 1 );
aMeasurements9->addRecord( 0.530, 0, 1, 1 );
aMeasurements9->addRecord( 0.540, 0, 1, 1 );
aMeasurements9->addRecord( 0.550, 0, 1, 1 );
aMeasurements9->addRecord( 0.560, 0, 1, 1 );
aMeasurements9->addRecord( 0.570, 0, 1, 1 );
aMeasurements9->addRecord( 0.580, 0, 1, 1 );
aMeasurements9->addRecord( 0.590, 0, 1, 1 );
aMeasurements9->addRecord( 0.600, 0, 1, 1 );
aMeasurements9->addRecord( 0.610, 0, 1, 1 );
aMeasurements9->addRecord( 0.620, 0, 1, 1 );
aMeasurements9->addRecord( 0.630, 0, 1, 1 );
aMeasurements9->addRecord( 0.640, 0, 1, 1 );
aMeasurements9->addRecord( 0.650, 0, 1, 1 );
aMeasurements9->addRecord( 0.660, 0, 1, 1 );
aMeasurements9->addRecord( 0.670, 0, 1, 1 );
aMeasurements9->addRecord( 0.680, 0, 1, 1 );
aMeasurements9->addRecord( 0.690, 0, 1, 1 );
aMeasurements9->addRecord( 0.700, 0, 1, 1 );
aMeasurements9->addRecord( 0.710, 0, 1, 1 );
aMeasurements9->addRecord( 0.720, 0, 1, 1 );
aMeasurements9->addRecord( 0.730, 0, 1, 1 );
aMeasurements9->addRecord( 0.740, 0, 1, 1 );
aMeasurements9->addRecord( 0.750, 0, 1, 1 );
aMeasurements9->addRecord( 0.760, 0, 1, 1 );
aMeasurements9->addRecord( 0.770, 0, 1, 1 );
aMeasurements9->addRecord( 0.780, 0, 1, 1 );
aMeasurements9->addRecord( 0.790, 0, 1, 1 );
aMeasurements9->addRecord( 0.800, 0, 1, 1 );
aMeasurements9->addRecord( 0.850, 0, 1, 1 );
aMeasurements9->addRecord( 0.900, 0, 1, 1 );
aMeasurements9->addRecord( 0.950, 0, 1, 1 );
aMeasurements9->addRecord( 1.000, 0, 1, 1 );
aMeasurements9->addRecord( 1.050, 0, 1, 1 );
aMeasurements9->addRecord( 1.100, 0, 1, 1 );
aMeasurements9->addRecord( 1.150, 0, 1, 1 );
aMeasurements9->addRecord( 1.200, 0, 1, 1 );
aMeasurements9->addRecord( 1.250, 0, 1, 1 );
aMeasurements9->addRecord( 1.300, 0, 1, 1 );
aMeasurements9->addRecord( 1.350, 0, 1, 1 );
aMeasurements9->addRecord( 1.400, 0, 1, 1 );
aMeasurements9->addRecord( 1.450, 0, 1, 1 );
aMeasurements9->addRecord( 1.500, 0, 1, 1 );
aMeasurements9->addRecord( 1.550, 0, 1, 1 );
aMeasurements9->addRecord( 1.600, 0, 1, 1 );
aMeasurements9->addRecord( 1.650, 0, 1, 1 );
aMeasurements9->addRecord( 1.700, 0, 1, 1 );
aMeasurements9->addRecord( 1.750, 0, 1, 1 );
aMeasurements9->addRecord( 1.800, 0, 1, 1 );
aMeasurements9->addRecord( 1.850, 0, 1, 1 );
aMeasurements9->addRecord( 1.900, 0, 1, 1 );
aMeasurements9->addRecord( 1.950, 0, 1, 1 );
aMeasurements9->addRecord( 2.000, 0, 1, 1 );
aMeasurements9->addRecord( 2.050, 0, 1, 1 );
aMeasurements9->addRecord( 2.100, 0, 1, 1 );
aMeasurements9->addRecord( 2.150, 0, 1, 1 );
aMeasurements9->addRecord( 2.200, 0, 1, 1 );
aMeasurements9->addRecord( 2.250, 0, 1, 1 );
aMeasurements9->addRecord( 2.300, 0, 1, 1 );
aMeasurements9->addRecord( 2.350, 0, 1, 1 );
aMeasurements9->addRecord( 2.400, 0, 1, 1 );
aMeasurements9->addRecord( 2.450, 0, 1, 1 );
aMeasurements9->addRecord( 2.500, 0, 1, 1 );
std::shared_ptr< CSpectralSample > aSample9 = std::make_shared< CSpectralSample >( aMeasurements9, aSolarRadiation );
std::shared_ptr< CSingleAngularMeasurement > aAngular9 = std::make_shared< CSingleAngularMeasurement >( aSample9, 90.0 );
return aAngular9;
}
protected:
virtual void SetUp() {
std::shared_ptr< CSingleAngularMeasurement > aAngular0 = getSample1();
std::shared_ptr< CSingleAngularMeasurement > aAngular1 = getSample2();
std::shared_ptr< CSingleAngularMeasurement > aAngular4 = getSample3();
std::shared_ptr< CSingleAngularMeasurement > aAngular9 = getSample4();
// Need to extract common wavelengths
CCommonWavelengths aCommonWL;
std::vector< double > wl0 = aAngular0->getWavelengthsFromSample();
std::vector< double > wl10 = aAngular1->getWavelengthsFromSample();
std::vector< double > wl40 = aAngular4->getWavelengthsFromSample();
std::vector< double > wl90 = aAngular9->getWavelengthsFromSample();
aCommonWL.addWavelength( wl0 );
aCommonWL.addWavelength( wl10 );
aCommonWL.addWavelength( wl40 );
aCommonWL.addWavelength( wl90 );
std::vector< double > commonWavelengths = aCommonWL.getCombinedWavelengths( Combine::Interpolate );
// Creating angular sample
m_Measurements = std::make_shared< CAngularMeasurements >( aAngular0, commonWavelengths );
m_Measurements->addMeasurement( aAngular1 );
m_Measurements->addMeasurement( aAngular4 );
m_Measurements->addMeasurement( aAngular9 );
std::shared_ptr< CMaterial > aMaterial = std::make_shared< CMaterialMeasured >( m_Measurements, WavelengthRange::Solar );
m_Material = aMaterial;
}
public:
std::shared_ptr< CBSDFLayer > getLayer() {
return m_Layer;
};
std::shared_ptr< CAngularMeasurements > getMeasurements() const {
return m_Measurements;
};
std::shared_ptr< CMaterial > getMaterials() const {
return m_Material;
};
};
TEST_F( TestSpecularAngularLayerProperty_102, TestSpecularAngular10degree ) {
SCOPED_TRACE( "Begin Test: Specular and Angular layer to compare optical properties at different incident angles." );
double angle = 10;
std::shared_ptr< CMaterial > aMaterial = getMaterials();
double trans = aMaterial->getPropertyAtAngle( Property::T, Side::Front, angle );
double refleF = aMaterial->getPropertyAtAngle( Property::R, Side::Front, angle );
double refleB = aMaterial->getPropertyAtAngle( Property::R, Side::Back, angle );
EXPECT_NEAR( 0.843568244957253, trans, 1e-6 );
EXPECT_NEAR( 0.0743831876357468, refleF, 1e-6 );
EXPECT_NEAR( 0.0743831876357468, refleB, 1e-6 );
}
TEST_F( TestSpecularAngularLayerProperty_102, TestSpecularAngular25degree ) {
SCOPED_TRACE( "Begin Test: Specular and Angular layer to compare optical properties at different incident angles." );
double angle = 25;
std::shared_ptr< CMaterial > aMaterial = getMaterials();
double trans = aMaterial->getPropertyAtAngle( Property::T, Side::Front, angle );
double refleF = aMaterial->getPropertyAtAngle( Property::R, Side::Front, angle );
double refleB = aMaterial->getPropertyAtAngle( Property::R, Side::Back, angle );
std::vector< double > aTrans = aMaterial->getBandPropertiesAtAngle( Property::T, Side::Front, angle );
EXPECT_NEAR( 0.79636496475913876, trans, 1e-6 );
EXPECT_NEAR( 0.11405492103460167, refleF, 1e-6 );
EXPECT_NEAR( 0.11405492103460167, refleB, 1e-6 );
std::vector< double > correctT;
correctT.push_back( 0 );
correctT.push_back( 0 );
correctT.push_back( 0.00455 );
correctT.push_back( 0.0252 );
correctT.push_back( 0.0757 );
correctT.push_back( 0.1736 );
correctT.push_back( 0.30255 );
correctT.push_back( 0.43405 );
correctT.push_back( 0.55215 );
correctT.push_back( 0.6511 );
correctT.push_back( 0.718 );
correctT.push_back( 0.76295 );
correctT.push_back( 0.7951 );
correctT.push_back( 0.81515 );
correctT.push_back( 0.82125 );
correctT.push_back( 0.8206 );
correctT.push_back( 0.80825 );
correctT.push_back( 0.8231 );
correctT.push_back( 0.83445 );
correctT.push_back( 0.84285 );
correctT.push_back( 0.84705 );
correctT.push_back( 0.84925 );
correctT.push_back( 0.8467 );
correctT.push_back( 0.846 );
correctT.push_back( 0.8441 );
correctT.push_back( 0.84795 );
correctT.push_back( 0.8522 );
correctT.push_back( 0.8541 );
correctT.push_back( 0.8564 );
correctT.push_back( 0.85785 );
correctT.push_back( 0.85785 );
correctT.push_back( 0.8584 );
correctT.push_back( 0.85775 );
correctT.push_back( 0.8581 );
correctT.push_back( 0.8586 );
correctT.push_back( 0.8564 );
correctT.push_back( 0.855 );
correctT.push_back( 0.85365 );
correctT.push_back( 0.8525 );
correctT.push_back( 0.8486 );
correctT.push_back( 0.8465 );
correctT.push_back( 0.84555 );
correctT.push_back( 0.8395 );
correctT.push_back( 0.8379 );
correctT.push_back( 0.83455 );
correctT.push_back( 0.8307 );
correctT.push_back( 0.8271 );
correctT.push_back( 0.8267 );
correctT.push_back( 0.81975 );
correctT.push_back( 0.81675 );
correctT.push_back( 0.8136 );
correctT.push_back( 0.8083 );
correctT.push_back( 0.80565 );
correctT.push_back( 0.80095 );
correctT.push_back( 0.79375 );
correctT.push_back( 0.7925 );
correctT.push_back( 0.7874 );
correctT.push_back( 0.78565 );
correctT.push_back( 0.78385 );
correctT.push_back( 0.7742 );
correctT.push_back( 0.77575 );
correctT.push_back( 0.75795 );
correctT.push_back( 0.75015 );
correctT.push_back( 0.7403 );
correctT.push_back( 0.7356 );
correctT.push_back( 0.73425 );
correctT.push_back( 0.7341 );
correctT.push_back( 0.7358 );
correctT.push_back( 0.7389 );
correctT.push_back( 0.7441 );
correctT.push_back( 0.75135 );
correctT.push_back( 0.7591 );
correctT.push_back( 0.7675 );
correctT.push_back( 0.77725 );
correctT.push_back( 0.7882 );
correctT.push_back( 0.7964 );
correctT.push_back( 0.8029 );
correctT.push_back( 0.8054 );
correctT.push_back( 0.8051 );
correctT.push_back( 0.8056 );
correctT.push_back( 0.80265 );
correctT.push_back( 0.801 );
correctT.push_back( 0.80465 );
correctT.push_back( 0.8019 );
correctT.push_back( 0.80015 );
correctT.push_back( 0.80095 );
correctT.push_back( 0.80275 );
correctT.push_back( 0.79255 );
correctT.push_back( 0.78165 );
correctT.push_back( 0.7788 );
correctT.push_back( 0.78155 );
correctT.push_back( 0.7854 );
correctT.push_back( 0.77455 );
correctT.push_back( 0.7733 );
correctT.push_back( 0.76895 );
size_t size = aTrans.size();
EXPECT_EQ( size, correctT.size( ) );
for ( size_t i = 0; i < size; ++i ) {
EXPECT_NEAR( correctT[ i ], aTrans[ i ], 1e-6 );
}
}
| [
"[email protected]"
] | |
1cb077c8276103214caeddf57e73522d816892d5 | 5c60715592bb5223ffa3c4c618530b8817819a43 | /Archieved Programs/CF/113C.cpp | 2a7ec8446655b0fc670a1d69401ebd3edfc78fab | [] | no_license | PriyanshuDas/college-work | 619375c1c26d8fd779370f1233f74a2eb4a5aa77 | 3bbe23a02b2d1d7be5b45b71a380f908abf61090 | refs/heads/master | 2021-01-17T15:18:36.635721 | 2018-01-11T13:55:41 | 2018-01-11T13:55:41 | 64,319,704 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,599 | cpp | #include <bits/stdc++.h>
#define sf scanf
#define pf printf
#define ll long long int
#define ull unsigned long long int
#define mp make_pair
#define pb push_back
#define ins insert
#define P_max 300000001
#define limit 300000001
#define sq_lim 17321
using namespace std;
//ull l_pr[P_max+1];
bool sq[P_max+1] = {0};
bool not_prime[limit]; //limit defined in preprocessor directive
int main()
{
// N*log(N) Sieve
not_prime[0] = 1;
not_prime[1] = 1;
for(int i = 2; i < limit; i++) // 1 is not considered for prime factorization!
{
if(!not_prime[i])
{
for(ll j = i*i; j < limit && j > 0; j+= i) //Every time a prime is found, no of ops = limit/(prime), approx n*(logn)(logn)
{
not_prime[j] = 1;
}
}
}
/* Linear Prime Sieve
for(int i = 2; i < P_max; i++)
{
if(l_pr[i] == 0)
{
primes.pb(i);
l_pr[i] = i;
}
for(int j=0;j<primes.size()&&primes[j]*i<P_max&&primes[j]<=l_pr[i];j++)
{
l_pr[primes[j]*i] = primes[j];
}
}
*/
//cout << primes.size() << endl;
for(ull i = 1; i < sq_lim; i++)
{
for(ull j = i+1; j < sq_lim; j++)
{
ull tmp = i*i + j*j;
if(tmp >= P_max)
break;
sq[i*i+j*j] = 1;
}
}
/*for(int i = 0; i < 100; i++)
{
ull sq_l = sqrt(primes[i]);
for(ull j = 1; j <= sq_l; j++)
{
ull n = primes[i]-(j*j);
if(n > 0 && sq[(ull)sqrt(n)] == n)
{
ct++;
pf("%llu\t==\t%llu\t+\t%llu\t\t%d\n", primes[i], j*j, n, ct);
break;
}
}
}*/
ull l, r, ct = 0;
sf("%llu%llu", &l, &r);
for(ull i = l; i <= r; i++)
{
if(not_prime[i] == 0 && sq[i] == 1)
ct++;
}
cout << ct;
return 0;
}
| [
"[email protected]"
] |
Subsets and Splits