hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
2e678131155f7b22525a6341caec35ed9dd8edc9
2,310
cpp
C++
Svc/TlmChan/test/perf/TelemChanImplTester.cpp
AlperenCetin0/fprime
7e20febd34019c730da1358567e7a512592de4d8
[ "Apache-2.0" ]
9,182
2017-07-06T15:51:35.000Z
2022-03-30T11:20:33.000Z
Svc/TlmChan/test/perf/TelemChanImplTester.cpp
AlperenCetin0/fprime
7e20febd34019c730da1358567e7a512592de4d8
[ "Apache-2.0" ]
719
2017-07-14T17:56:01.000Z
2022-03-31T02:41:35.000Z
Svc/TlmChan/test/perf/TelemChanImplTester.cpp
AlperenCetin0/fprime
7e20febd34019c730da1358567e7a512592de4d8
[ "Apache-2.0" ]
1,216
2017-07-12T15:41:08.000Z
2022-03-31T21:44:37.000Z
/* * PrmDbImplTester.cpp * * Created on: Mar 18, 2015 * Author: tcanham */ #include <Svc/TlmChan/test/ut/TelemChanImplTester.hpp> #include <Fw/Com/FwComBuffer.hpp> #include <Fw/Com/FwComPacket.hpp> #include <Os/IntervalTimer.hpp> #include <cstdio> namespace Svc { TelemStoreComponentBaseFriend::TelemStoreComponentBaseFriend(Svc::TelemStoreComponentBase& inst) : m_baseInst(inst) { } Fw::QueuedComponentBase::MsgDispatchStatus TelemStoreComponentBaseFriend::doDispatch() { return this->m_baseInst.doDispatch(); } void TelemChanImplTester::init(NATIVE_INT_TYPE instance) { Svc::TelemStoreComponentTesterBase::init(); } void TelemChanImplTester::pktSend_handler(NATIVE_INT_TYPE portNum, Fw::ComBuffer &data) { } TelemChanImplTester::TelemChanImplTester(Svc::TelemChanImpl& inst) : Svc::TelemStoreComponentTesterBase("testerbase"),m_impl(inst), m_baseFriend(inst) { } TelemChanImplTester::~TelemChanImplTester() { } void TelemChanImplTester::doPerfTest(U32 iterations) { Os::IntervalTimer timer; Fw::TlmBuffer buff; Fw::TlmBuffer readBack; Fw::SerializeStatus stat; Fw::Time timeTag; U32 testVal = 10; U32 retestVal = 0; // prefill telemetry to force a linear search to the end for (U32 entry = 0; entry < TelemChanImpl::NUM_TLM_ENTRIES - 1; entry++) { Fw::TlmBuffer fakeBuff; this->tlmRecv_out(0,entry,timeTag,buff); } timer.start(); for (U32 iter = 0; iter < iterations; iter++) { // create telemetry item buff.resetSer(); stat = buff.serialize(testVal); this->tlmRecv_out(0,TelemChanImpl::NUM_TLM_ENTRIES - 1,timeTag,buff); // Read back value this->tlmGet_out(0,TelemChanImpl::NUM_TLM_ENTRIES - 1,timeTag,readBack); // deserialize value retestVal = 0; buff.deserialize(retestVal); if (retestVal != testVal) { printf("Mismatch: %d %d\n",testVal,retestVal); break; } } timer.stop(); printf("Write total: %d ave: %d\n",timer.getDiffUsec(),timer.getDiffUsec()/iterations); } } /* namespace SvcTest */
28.170732
156
0.628571
AlperenCetin0
2e687517f1bae373b295ae672fba6fb05fa50aeb
398
hpp
C++
include/lol/def/LcdsSummoner.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
1
2020-07-22T11:14:55.000Z
2020-07-22T11:14:55.000Z
include/lol/def/LcdsSummoner.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
null
null
null
include/lol/def/LcdsSummoner.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
4
2018-12-01T22:48:21.000Z
2020-07-22T11:14:56.000Z
#pragma once #include "../base_def.hpp" namespace lol { struct LcdsSummoner { uint64_t sumId; std::string name; }; inline void to_json(json& j, const LcdsSummoner& v) { j["sumId"] = v.sumId; j["name"] = v.name; } inline void from_json(const json& j, LcdsSummoner& v) { v.sumId = j.at("sumId").get<uint64_t>(); v.name = j.at("name").get<std::string>(); } }
24.875
57
0.595477
Maufeat
2e6b27a4fe30376e21dae59740f0e78f44cb209e
540
cpp
C++
src/osd/modules/render/bgfx/clear.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
26
2015-03-31T06:25:51.000Z
2021-12-14T09:29:04.000Z
emulator/src/osd/modules/render/bgfx/clear.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
emulator/src/osd/modules/render/bgfx/clear.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
10
2015-03-27T05:45:51.000Z
2022-02-04T06:57:36.000Z
// license:BSD-3-Clause // copyright-holders:Ryan Holtz //============================================================ // // clear.cpp - View clear info for a BGFX chain entry // //============================================================ #include "clear.h" clear_state::clear_state(uint64_t flags, uint32_t color, float depth, uint8_t stencil) : m_flags(flags) , m_color(color) , m_depth(depth) , m_stencil(stencil) { } void clear_state::bind(int view) const { bgfx::setViewClear(view, m_flags, m_color, m_depth, m_stencil); }
23.478261
86
0.553704
Robbbert
2e6c9d912756aa7d03e6668fd249eb38a70d9156
2,006
cc
C++
cpp/src/arrow/python/ipc.cc
timkpaine/arrow
a96297e65e17e728e4321cdecc7ace146e1363fb
[ "CC-BY-3.0", "Apache-2.0", "CC0-1.0", "MIT" ]
9,734
2016-02-17T13:22:12.000Z
2022-03-31T09:35:00.000Z
cpp/src/arrow/python/ipc.cc
timkpaine/arrow
a96297e65e17e728e4321cdecc7ace146e1363fb
[ "CC-BY-3.0", "Apache-2.0", "CC0-1.0", "MIT" ]
11,470
2016-02-19T15:30:28.000Z
2022-03-31T23:27:21.000Z
cpp/src/arrow/python/ipc.cc
XpressAI/arrow
eafd885e06f6bbc1eb169ed64016f804c1810bec
[ "CC-BY-3.0", "Apache-2.0", "CC0-1.0", "MIT" ]
2,637
2016-02-17T10:56:29.000Z
2022-03-31T08:20:13.000Z
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "arrow/python/ipc.h" #include <memory> #include "arrow/python/pyarrow.h" namespace arrow { namespace py { PyRecordBatchReader::PyRecordBatchReader() {} Status PyRecordBatchReader::Init(std::shared_ptr<Schema> schema, PyObject* iterable) { schema_ = std::move(schema); iterator_.reset(PyObject_GetIter(iterable)); return CheckPyError(); } std::shared_ptr<Schema> PyRecordBatchReader::schema() const { return schema_; } Status PyRecordBatchReader::ReadNext(std::shared_ptr<RecordBatch>* batch) { PyAcquireGIL lock; if (!iterator_) { // End of stream batch->reset(); return Status::OK(); } OwnedRef py_batch(PyIter_Next(iterator_.obj())); if (!py_batch) { RETURN_IF_PYERROR(); // End of stream batch->reset(); iterator_.reset(); return Status::OK(); } return unwrap_batch(py_batch.obj()).Value(batch); } Result<std::shared_ptr<RecordBatchReader>> PyRecordBatchReader::Make( std::shared_ptr<Schema> schema, PyObject* iterable) { auto reader = std::shared_ptr<PyRecordBatchReader>(new PyRecordBatchReader()); RETURN_NOT_OK(reader->Init(std::move(schema), iterable)); return reader; } } // namespace py } // namespace arrow
29.5
86
0.728814
timkpaine
2e6dfda112f1d2c91261561e0c813d3e05d8dfb3
52
hpp
C++
src/boost_fusion_include_iterator_facade.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_fusion_include_iterator_facade.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_fusion_include_iterator_facade.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/fusion/include/iterator_facade.hpp>
26
51
0.826923
miathedev
2e6e177ecabb8032e0cbfe6ca574ed9bc19f6566
421
cpp
C++
archive/codevs.1010.cpp
woshiluo/oi
5637fb81b0e25013314783dc387f7fc93bf9d4b9
[ "Apache-2.0" ]
null
null
null
archive/codevs.1010.cpp
woshiluo/oi
5637fb81b0e25013314783dc387f7fc93bf9d4b9
[ "Apache-2.0" ]
null
null
null
archive/codevs.1010.cpp
woshiluo/oi
5637fb81b0e25013314783dc387f7fc93bf9d4b9
[ "Apache-2.0" ]
null
null
null
#include <cstdio> using namespace std; long long dx[8]={+2,+2,-2,-2,+1,+1,-1,-1}; long long dy[8]={+1,-1,+1,-1,+2,-2,+2,-2}; long long f[20][20],n,m,x,y; int main(){ scanf("%d%d%d%d",&n,&m,&x,&y); for(int i=x;i<=n;i++){ for(int j=y;j<=m;j++){ for(int k=0;k<8;k++){ long long tx,ty; tx+=dx[k]+i; ty+=dy[k]+j; } } } }
20.047619
42
0.384798
woshiluo
2e730121679a0e9825893bb04949e16672d017f5
1,324
cpp
C++
src/SensorPaths.cpp
serve-bh-bmc/dbus-sensors
f69fbf998745bf006748c3b6ba6558443b560d21
[ "Apache-2.0" ]
15
2019-02-26T03:44:55.000Z
2021-11-04T23:58:51.000Z
src/SensorPaths.cpp
serve-bh-bmc/dbus-sensors
f69fbf998745bf006748c3b6ba6558443b560d21
[ "Apache-2.0" ]
17
2019-01-23T19:47:44.000Z
2022-03-31T23:03:43.000Z
src/SensorPaths.cpp
serve-bh-bmc/dbus-sensors
f69fbf998745bf006748c3b6ba6558443b560d21
[ "Apache-2.0" ]
21
2019-08-07T03:32:20.000Z
2022-01-27T09:40:22.000Z
#include <SensorPaths.hpp> #include <cstring> #include <regex> #include <string> namespace sensor_paths { // This is an allowlist of the units a sensor can measure. Should be in sync // with // phosphor-dbus-interfaces/blob/master/xyz/openbmc_project/Sensor/Value.interface.yaml#L35 std::string getPathForUnits(const std::string& units) { if (units == "DegreesC" || units == unitDegreesC) { return "temperature"; } if (units == "RPMS" || units == unitRPMs) { return "fan_tach"; } if (units == "Volts" || units == unitVolts) { return "voltage"; } if (units == "Meters" || units == unitMeters) { return "altitude"; } if (units == "Amperes" || units == unitAmperes) { return "current"; } if (units == "Watts" || units == unitWatts) { return "power"; } if (units == "Joules" || units == unitJoules) { return "energy"; } if (units == "Percent" || units == unitPercent) { return "Utilization"; } if (units == "Pascals" || units == unitPascals) { return "pressure"; } return ""; } std::string escapePathForDbus(const std::string& name) { return std::regex_replace(name, std::regex("[^a-zA-Z0-9_/]+"), "_"); } } // namespace sensor_paths
21.704918
91
0.570242
serve-bh-bmc
2e731c8dbab974f00b7d31b4d795a1fdf380ee35
2,480
hpp
C++
VideoParsers/VideoParsers/MP4/Box/HandlerReferenceBox.hpp
suxinde2009/VideoParsers
f5456a234984efa17e33dc6dbb397e6e2f32ebe0
[ "MIT" ]
null
null
null
VideoParsers/VideoParsers/MP4/Box/HandlerReferenceBox.hpp
suxinde2009/VideoParsers
f5456a234984efa17e33dc6dbb397e6e2f32ebe0
[ "MIT" ]
null
null
null
VideoParsers/VideoParsers/MP4/Box/HandlerReferenceBox.hpp
suxinde2009/VideoParsers
f5456a234984efa17e33dc6dbb397e6e2f32ebe0
[ "MIT" ]
null
null
null
/** ============================================================================== MIT License Copyright (c) 2011-Present __承_影__ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ============================================================================== */ #ifndef HandlerReferenceBox_hpp #define HandlerReferenceBox_hpp #include <stdio.h> #include <iostream> #include <vector> #include "PtrBuffer.hpp" #include "Box.hpp" #include "FullBox.hpp" namespace VP { //hdlr class HandlerReferenceBox : public FullBox { public: HandlerReferenceBox(std::shared_ptr<PtrBuffer> buffer) : FullBox(buffer) {} virtual void parser(size_t& size) { FullBox::parser(size); pre_defined_ = buffer_->readBig32(); handler_type_ = buffer_->readBig32(); for(int i=0;i<3;i++) { reserved_[i] = buffer_->readBig32(); } if(handler_type_ == Box::parseName("vide")) { //video } else if(handler_type_ == Box::parseName("soun")) { //aduio } else if(handler_type_ == Box::parseName("mla ")) { //mp2 } else if(handler_type_ == Box::parseName("subp") || handler_type_ == Box::parseName("clcp")) { //subtitle } size_t len = size_ - 24 - 8; while(len > 0) { uint8_t val = 0; buffer_->read(val); name_ += char(val); len--; } } protected: uint32_t pre_defined_; uint32_t handler_type_; uint32_t reserved_[3]; std::string name_; }; } #endif /* HandlerReferenceBox_hpp */
25.306122
79
0.656855
suxinde2009
2e73b93677774b452ec9617a1e5c2ba15ef644b1
24,080
cpp
C++
admin/wmi/wbem/winmgmt/coredll/olesrvr.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
admin/wmi/wbem/winmgmt/coredll/olesrvr.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
admin/wmi/wbem/winmgmt/coredll/olesrvr.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (C) 1996-2001 Microsoft Corporation Module Name: OLESRVR.CPP Abstract: "Main" file for wbemcore.dll: implements all DLL entry points. Classes defined and implemeted: CWbemLocator History: raymcc 16-Jul-96 Created. raymcc 05-May-97 Security extensions --*/ #include "precomp.h" #include <stdio.h> #include <time.h> #include <initguid.h> #include <wbemcore.h> #include <intprov.h> #include <genutils.h> #include <wbemint.h> #include <windows.h> #include <helper.h> // {A83EF168-CA8D-11d2-B33D-00104BCC4B4A} DEFINE_GUID(CLSID_IntProv, 0xa83ef168, 0xca8d, 0x11d2, 0xb3, 0x3d, 0x0, 0x10, 0x4b, 0xcc, 0x4b, 0x4a); LPTSTR g_pWorkDir = 0; LPTSTR g_pDbDir = 0; LPTSTR g_pAutorecoverDir = 0; DWORD g_dwQueueSize = 1; HINSTANCE g_hInstance; BOOL g_bDontAllowNewConnections = FALSE; IWbemEventSubsystem_m4* g_pEss_m4 = NULL; bool g_bDefaultMofLoadingNeeded = false; IClassFactory* g_pContextFac = NULL; IClassFactory* g_pPathFac = NULL; IClassFactory* g_pQueryFact = NULL; BOOL g_ShutdownCalled = FALSE; extern "C" HRESULT APIENTRY Shutdown(BOOL bProcessShutdown, BOOL bIsSystemShutdown); extern "C" HRESULT APIENTRY Reinitialize(DWORD dwReserved); BOOL IsWhistlerPersonal ( ) ; BOOL IsWhistlerProfessional ( ) ; void UpdateArbitratorValues ( ) ; //*************************************************************************** // // DllMain // // Dll entry point function. Called when wbemcore.dll is loaded into memory. // Performs basic system initialization on startup and system shutdown on // unload. See ConfigMgr::InitSystem and ConfigMgr::Shutdown in cfgmgr.h for // more details. // // PARAMETERS: // // HINSTANCE hinstDLL The handle to our DLL. // DWORD dwReason DLL_PROCESS_ATTACH on load, // DLL_PROCESS_DETACH on shutdown, // DLL_THREAD_ATTACH/DLL_THREAD_DETACH otherwise. // LPVOID lpReserved Reserved // // RETURN VALUES: // // TRUE is successful, FALSE if a fatal error occured. // NT behaves very ugly if FALSE is returned. // //*************************************************************************** BOOL WINAPI DllMain( HINSTANCE hinstDLL, DWORD dwReason, LPVOID lpReserved ) { if (dwReason == DLL_PROCESS_ATTACH) { g_hInstance = hinstDLL; if (CStaticCritSec::anyFailure()) return FALSE; } else if (dwReason == DLL_PROCESS_DETACH) { DEBUGTRACE((LOG_WBEMCORE, "wbemcore!DllMain(DLL_PROCESS_DETACH)\n")); #ifdef DBG if (!RtlDllShutdownInProgress()) { if (!gClientCounter.OkToUnload()) DebugBreak(); } #endif /*DBG*/ } else if ( dwReason == DLL_THREAD_ATTACH ) { TlsSetValue(CCoreQueue::GetSecFlagTlsIndex(),(LPVOID)1); } return TRUE; } //*************************************************************************** // // class CFactory // // Generic implementation of IClassFactory for CWbemLocator. // // See Brockschmidt for details of IClassFactory interface. // //*************************************************************************** enum InitType {ENSURE_INIT, ENSURE_INIT_WAIT_FOR_CLIENT, OBJECT_HANDLES_OWN_INIT}; template<class TObj> class CFactory : public IClassFactory { public: CFactory(BOOL bUser, InitType it); ~CFactory(); // // IUnknown members // STDMETHODIMP QueryInterface(REFIID, LPVOID *); STDMETHODIMP_(ULONG) AddRef(void); STDMETHODIMP_(ULONG) Release(void); // // IClassFactory members // STDMETHODIMP CreateInstance(LPUNKNOWN, REFIID, LPVOID *); STDMETHODIMP LockServer(BOOL); private: ULONG m_cRef; InitType m_it; BOOL m_bUser; LIST_ENTRY m_Entry; }; ///////////////////////////////////////////////////////////////////////////// // // Count number of objects and number of locks on this DLL. // ULONG g_cObj = 0; ULONG g_cLock = 0; long g_lInitCount = -1; // 0 DURING INTIALIZATION, 1 OR MORE LATER ON! static CWbemCriticalSection g_csInit; bool g_bPreviousFail = false; HRESULT g_hrLastEnsuredInitializeError = WBEM_S_NO_ERROR; HRESULT EnsureInitialized() { if(g_bPreviousFail) return g_hrLastEnsuredInitializeError; g_csInit.Enter(); OnDeleteObjIf0<CWbemCriticalSection, void (CWbemCriticalSection::*)(void), &CWbemCriticalSection::Leave> LeaveMe(&g_csInit); // If we have been shut down by WinMgmt, bail out. if(g_bDontAllowNewConnections) { return CO_E_SERVER_STOPPING; } //Check again! Previous connection could have been holding us off, and //may have failed! if(g_bPreviousFail) return g_hrLastEnsuredInitializeError; HRESULT hres; if(InterlockedIncrement(&g_lInitCount) == 0) { // Init Systems hres = ConfigMgr::InitSystem(); if(FAILED(hres)) { g_bPreviousFail = true; g_hrLastEnsuredInitializeError = hres; ConfigMgr::FatalInitializationError(hres); return hres; } LeaveMe.dismiss(); g_csInit.Leave(); // Get WINMGMT to run hres = ConfigMgr::SetReady(); if(FAILED(hres)) { g_bPreviousFail = true; g_hrLastEnsuredInitializeError = hres; ConfigMgr::FatalInitializationError(hres); return hres; } // if here, everything is OK g_bPreviousFail = false; g_hrLastEnsuredInitializeError = WBEM_S_NO_ERROR; InterlockedIncrement(&g_lInitCount); } else { InterlockedDecrement(&g_lInitCount); } return S_OK; } //*************************************************************************** // // DllGetClassObject // // Standard OLE In-Process Server entry point to return an class factory // instance. Before returning a class factory, this function performs an // additional round of initialization --- see ConfigMgr::SetReady in cfgmgr.h // // PARAMETERS: // // IN RECLSID rclsid The CLSID of the object whose class factory is // required. // IN REFIID riid The interface required from the class factory. // OUT LPVOID* ppv Destination for the class factory. // // RETURNS: // // S_OK Success // E_NOINTERFACE An interface other that IClassFactory was asked for // E_OUTOFMEMORY // E_FAILED Initialization failed, or an unsupported clsid was // asked for. // //*************************************************************************** extern "C" HRESULT APIENTRY DllGetClassObject( REFCLSID rclsid, REFIID riid, LPVOID * ppv ) { HRESULT hr; // // Check that we can provide the interface. // if (IID_IUnknown != riid && IID_IClassFactory != riid) return ResultFromScode(E_NOINTERFACE); IClassFactory *pFactory; // // Verify the caller is asking for our type of object. // if (CLSID_InProcWbemLevel1Login == rclsid) { pFactory = new CFactory<CWbemLevel1Login>(TRUE, OBJECT_HANDLES_OWN_INIT); } else if(CLSID_ActualWbemAdministrativeLocator == rclsid) { pFactory = new CFactory<CWbemAdministrativeLocator>(FALSE, OBJECT_HANDLES_OWN_INIT); } else if(CLSID_ActualWbemAuthenticatedLocator == rclsid) { pFactory = new CFactory<CWbemAuthenticatedLocator>(TRUE, OBJECT_HANDLES_OWN_INIT); } else if(CLSID_ActualWbemUnauthenticatedLocator == rclsid) { pFactory = new CFactory<CWbemUnauthenticatedLocator>(TRUE, OBJECT_HANDLES_OWN_INIT); } else if(CLSID_IntProv == rclsid) { pFactory = new CFactory<CIntProv>(TRUE, ENSURE_INIT_WAIT_FOR_CLIENT); } else if(CLSID_IWmiCoreServices == rclsid) { pFactory = new CFactory<CCoreServices>(FALSE, ENSURE_INIT); } else { return E_FAIL; } if (!pFactory) return ResultFromScode(E_OUTOFMEMORY); hr = pFactory->QueryInterface(riid, ppv); if (FAILED(hr)) delete pFactory; return hr; } //*************************************************************************** // // DllCanUnloadNow // // Standard OLE entry point for server shutdown request. Allows shutdown // only if no outstanding objects or locks are present. // // RETURN VALUES: // // S_OK May unload now. // S_FALSE May not. // //*************************************************************************** extern "C" HRESULT APIENTRY DllCanUnloadNow(void) { DEBUGTRACE((LOG_WBEMCORE,"+ DllCanUnloadNow()\n")); if(!IsDcomEnabled()) return S_FALSE; if(IsNtSetupRunning()) { DEBUGTRACE((LOG_WBEMCORE, "- DllCanUnloadNow() returning S_FALSE because setup is running\n")); return S_FALSE; } if(gClientCounter.OkToUnload()) { Shutdown(FALSE,FALSE); // NO Process , NO System DEBUGTRACE((LOG_WBEMCORE, "- DllCanUnloadNow() S_OK\n")); _DBG_ASSERT(gClientCounter.OkToUnload()); return S_OK; } else { DEBUGTRACE((LOG_WBEMCORE, "- DllCanUnloadNow() S_FALSE\n")); return S_FALSE; } } //*************************************************************************** // // UpdateBackupReg // // Updates the backup default options in registry. // // RETURN VALUES: // //*************************************************************************** void UpdateBackupReg() { HKEY hKey = 0; if (RegOpenKey(HKEY_LOCAL_MACHINE, WBEM_REG_WINMGMT, &hKey) == ERROR_SUCCESS) // SEC:REVIEWED 2002-03-22 : OK { char szBuff[20]; DWORD dwSize = sizeof(szBuff); unsigned long ulType = REG_SZ; if ((RegQueryValueEx(hKey, __TEXT("Backup Interval Threshold"), 0, &ulType, (unsigned char*)szBuff, &dwSize) == ERROR_SUCCESS) && (strcmp(szBuff, "60") == 0)) // SEC:REVIEWED 2002-03-22 : OK { RegSetValueEx(hKey, __TEXT("Backup Interval Threshold"), 0, REG_SZ, (const BYTE*)(__TEXT("30")), (2+1) * sizeof(TCHAR)); // SEC:REVIEWED 2002-03-22 : OK } RegCloseKey(hKey); } } //*************************************************************************** // // UpdateBackupReg // // Updates the unchecked task count value for the arbitrator. // // RETURN VALUES: // //*************************************************************************** #define ARB_DEFAULT_TASK_COUNT_LESSTHAN_SERVER 50 #define ARB_DEFAULT_TASK_COUNT_GREATERHAN_SERVER 250 void UpdateArbitratorValues () { HKEY hKey = 0; if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WBEM_REG_WINMGMT, 0, KEY_ALL_ACCESS, &hKey) == ERROR_SUCCESS) // SEC:REVIEWED 2002-03-22 : OK { DWORD dwValue = 0 ; DWORD dwSize = sizeof (DWORD) ; DWORD ulType = 0 ; if ((RegQueryValueEx(hKey, __TEXT("Unchecked Task Count"), 0, &ulType, LPBYTE(&dwValue), &dwSize) == ERROR_SUCCESS) ) // SEC:REVIEWED 2002-03-22 : OK { if ( !IsWhistlerPersonal ( ) && !IsWhistlerProfessional ( ) && ( dwValue == ARB_DEFAULT_TASK_COUNT_LESSTHAN_SERVER ) ) { DWORD dwNewValue = ARB_DEFAULT_TASK_COUNT_GREATERHAN_SERVER ; RegSetValueEx(hKey, __TEXT("Unchecked Task Count"), 0, REG_DWORD, (const BYTE*)&dwNewValue, sizeof(DWORD)); // SEC:REVIEWED 2002-03-22 : OK } } else { // // Registry key non-existent // if ( !IsWhistlerPersonal ( ) && !IsWhistlerProfessional ( ) ) { DWORD dwNewValue = ARB_DEFAULT_TASK_COUNT_GREATERHAN_SERVER ; RegSetValueEx(hKey, __TEXT("Unchecked Task Count"), 0, REG_DWORD, (const BYTE*)&dwNewValue, sizeof(DWORD)); // SEC:REVIEWED 2002-03-22 : OK } else { DWORD dwNewValue = ARB_DEFAULT_TASK_COUNT_LESSTHAN_SERVER ; RegSetValueEx(hKey, __TEXT("Unchecked Task Count"), 0, REG_DWORD, (const BYTE*)&dwNewValue, sizeof(DWORD)); // SEC:REVIEWED 2002-03-22 : OK } } RegCloseKey(hKey); } } //*************************************************************************** // // BOOL IsWhistlerPersonal () // // Returns true if machine is running Whistler Personal // // //*************************************************************************** BOOL IsWhistlerPersonal () { BOOL bRet = TRUE ; OSVERSIONINFOEXW verInfo ; verInfo.dwOSVersionInfoSize = sizeof ( OSVERSIONINFOEX ) ; if ( GetVersionExW ( (LPOSVERSIONINFOW) &verInfo ) == TRUE ) { if ( ( verInfo.wSuiteMask != VER_SUITE_PERSONAL ) && ( verInfo.dwPlatformId == VER_PLATFORM_WIN32_NT ) ) { bRet = FALSE ; } } return bRet ; } //*************************************************************************** // // BOOL IsWhistlerProfessional () // // Returns true if machine is running Whistler Professional // // //*************************************************************************** BOOL IsWhistlerProfessional () { BOOL bRet = TRUE ; OSVERSIONINFOEXW verInfo ; verInfo.dwOSVersionInfoSize = sizeof ( OSVERSIONINFOEX ) ; if ( GetVersionExW ( (LPOSVERSIONINFOW) &verInfo ) == TRUE ) { if ( ( verInfo.wProductType != VER_NT_WORKSTATION ) && ( verInfo.dwPlatformId == VER_PLATFORM_WIN32_NT ) ) { bRet = FALSE ; } } return bRet ; } //*************************************************************************** // // DllRegisterServer // // Standard OLE entry point for registering the server. // // RETURN VALUES: // // S_OK Registration was successful // E_FAIL Registration failed. // //*************************************************************************** extern "C" HRESULT APIENTRY DllRegisterServer(void) { TCHAR* szModel = (IsDcomEnabled() ? __TEXT("Both") : __TEXT("Apartment")); RegisterDLL(g_hInstance, CLSID_ActualWbemAdministrativeLocator, __TEXT(""), szModel, NULL); RegisterDLL(g_hInstance, CLSID_ActualWbemAuthenticatedLocator, __TEXT(""), szModel, NULL); RegisterDLL(g_hInstance, CLSID_ActualWbemUnauthenticatedLocator, __TEXT(""), szModel, NULL); RegisterDLL(g_hInstance, CLSID_InProcWbemLevel1Login, __TEXT(""), szModel, NULL); RegisterDLL(g_hInstance, CLSID_IntProv, __TEXT(""), szModel, NULL); RegisterDLL(g_hInstance, CLSID_IWmiCoreServices, __TEXT(""), szModel, NULL); // Write the setup time into the registry. This isnt actually needed // by dcom, but the code did need to be stuck in some place which // is called upon setup long lRes; DWORD ignore; HKEY key; lRes = RegCreateKeyEx(HKEY_LOCAL_MACHINE, // SEC:REVIEWED 2002-03-22 : OK, inherits ACEs from higher key WBEM_REG_WINMGMT, NULL, NULL, REG_OPTION_NON_VOLATILE, KEY_READ | KEY_WRITE, NULL, &key, &ignore); if(lRes == ERROR_SUCCESS) { SYSTEMTIME st; GetSystemTime(&st); // get the gmt time TCHAR cTime[MAX_PATH]; // convert to localized format! lRes = GetDateFormat(LOCALE_SYSTEM_DEFAULT, DATE_LONGDATE, &st, NULL, cTime, MAX_PATH); if(lRes) { StringCchCat(cTime, MAX_PATH, __TEXT(" GMT")); lRes = RegSetValueEx(key, __TEXT("SetupDate"), 0, REG_SZ, // SEC:REVIEWED 2002-03-22 : OK (BYTE *)cTime, (lstrlen(cTime)+1) * sizeof(TCHAR)); // SEC:REVIEWED 2002-03-22 : OK } lRes = GetTimeFormat(LOCALE_SYSTEM_DEFAULT, 0, &st, NULL, cTime, MAX_PATH); if(lRes) { StringCchCat(cTime, MAX_PATH, __TEXT(" GMT")); lRes = RegSetValueEx(key, __TEXT("SetupTime"), 0, REG_SZ, // SEC:REVIEWED 2002-03-22 : OK (BYTE *)cTime, (lstrlen(cTime)+1) * sizeof(TCHAR)); // SEC:REVIEWED 2002-03-22 : OK } CloseHandle(key); } UpdateBackupReg(); UpdateArbitratorValues ( ) ; return S_OK; } //*************************************************************************** // // DllUnregisterServer // // Standard OLE entry point for unregistering the server. // // RETURN VALUES: // // S_OK Unregistration was successful // E_FAIL Unregistration failed. // //*************************************************************************** extern "C" HRESULT APIENTRY DllUnregisterServer(void) { UnRegisterDLL(CLSID_ActualWbemAdministrativeLocator, NULL); UnRegisterDLL(CLSID_ActualWbemAuthenticatedLocator, NULL); UnRegisterDLL(CLSID_ActualWbemUnauthenticatedLocator, NULL); UnRegisterDLL(CLSID_InProcWbemLevel1Login, NULL); UnRegisterDLL(CLSID_IntProv, NULL); UnRegisterDLL(CLSID_IWmiCoreServices, NULL); HKEY hKey; long lRes = RegOpenKeyEx (HKEY_LOCAL_MACHINE, // SEC:REVIEWED 2002-03-22 : OK WBEM_REG_WINMGMT, 0, KEY_ALL_ACCESS, &hKey); // SEC:REVIEWED 2002-03-22 : OK if(lRes == ERROR_SUCCESS) { RegDeleteValue(hKey, __TEXT("SetupDate")); RegDeleteValue(hKey, __TEXT("SetupTime")); RegCloseKey(hKey); } return S_OK; } //*************************************************************************** // // CFactory::CFactory // // Constructs the class factory given the CLSID of the objects it is supposed // to create. // //*************************************************************************** template<class TObj> CFactory<TObj>::CFactory(BOOL bUser, InitType it) { m_cRef = 0; m_bUser = bUser; m_it = it; gClientCounter.AddClientPtr(&m_Entry); } //*************************************************************************** // // CFactory::~CFactory // // Destructor. // //*************************************************************************** template<class TObj> CFactory<TObj>::~CFactory() { gClientCounter.RemoveClientPtr(&m_Entry); } //*************************************************************************** // // CFactory::QueryInterface, AddRef and Release // // Standard IUnknown methods. // //*************************************************************************** template<class TObj> STDMETHODIMP CFactory<TObj>::QueryInterface(REFIID riid, LPVOID * ppv) { *ppv = 0; if (IID_IUnknown==riid || IID_IClassFactory==riid) { *ppv = this; AddRef(); return NOERROR; } return ResultFromScode(E_NOINTERFACE); } template<class TObj> ULONG CFactory<TObj>::AddRef() { return ++m_cRef; } template<class TObj> ULONG CFactory<TObj>::Release() { if (0 != --m_cRef) return m_cRef; delete this; return 0; } //*************************************************************************** // // CFactory::CreateInstance // // As mandated by IClassFactory, creates a new instance of its object // (CWbemLocator). // // PARAMETERS: // // LPUNKNOWN pUnkOuter IUnknown of the aggregator. Must be NULL. // REFIID riid Interface ID required. // LPVOID * ppvObj Destination for the interface pointer. // // RETURN VALUES: // // S_OK Success // CLASS_E_NOAGGREGATION pUnkOuter must be NULL // E_NOINTERFACE No such interface supported. // //*************************************************************************** template<class TObj> STDMETHODIMP CFactory<TObj>::CreateInstance( LPUNKNOWN pUnkOuter, REFIID riid, LPVOID * ppvObj) { TObj* pObj; HRESULT hr; // Defaults *ppvObj=NULL; if(m_it == ENSURE_INIT || m_it == ENSURE_INIT_WAIT_FOR_CLIENT) { hr = EnsureInitialized(); if(FAILED(hr)) return hr; if(m_it == ENSURE_INIT_WAIT_FOR_CLIENT) { // Wait until user-ready hr = ConfigMgr::WaitUntilClientReady(); if(FAILED(hr)) return hr; } } // We aren't supporting aggregation. if (pUnkOuter) return CLASS_E_NOAGGREGATION; pObj = new TObj; if (!pObj) return E_OUTOFMEMORY; // // Initialize the object and verify that it can return the // interface in question. // hr = pObj->QueryInterface(riid, ppvObj); // // Kill the object if initial creation or Init failed. // if (FAILED(hr)) delete pObj; return hr; } //*************************************************************************** // // CFactory::LockServer // // Increments or decrements the lock count of the server. The DLL will not // unload while the lock count is positive. // // PARAMETERS: // // BOOL fLock If TRUE, locks; otherwise, unlocks. // // RETURN VALUES: // // S_OK // //*************************************************************************** template<class TObj> STDMETHODIMP CFactory<TObj>::LockServer(BOOL fLock) { if (fLock) InterlockedIncrement((LONG *) &g_cLock); else InterlockedDecrement((LONG *) &g_cLock); return NOERROR; } void WarnESSOfShutdown(LONG lSystemShutDown) { if(g_lInitCount != -1) { IWbemEventSubsystem_m4* pEss = ConfigMgr::GetEssSink(); if(pEss) { pEss->LastCallForCore(lSystemShutDown); pEss->Release(); } } } // // we can have Shutdown called twice in a row, because // DllCanUnloadNow will do that, once triggered by CoFreeUnusedLibraries // extern "C" HRESULT APIENTRY Shutdown(BOOL bProcessShutdown, BOOL bIsSystemShutdown) { CEnterWbemCriticalSection enterCs(&g_csInit); if (!bIsSystemShutdown) { DEBUGTRACE((LOG_WBEMCORE, " wbemcore!Shutdown(%d)" " g_ShutdownCalled = %d g_lInitCount = %d)\n", bProcessShutdown, g_ShutdownCalled,g_lInitCount)); } if (g_ShutdownCalled) { return S_OK; } else { g_ShutdownCalled = TRUE; } if(bProcessShutdown) { WarnESSOfShutdown((LONG)bIsSystemShutdown); } if(g_lInitCount == -1) { return S_OK; } if(!bProcessShutdown) WarnESSOfShutdown((LONG)bIsSystemShutdown); g_lInitCount = -1; ConfigMgr::Shutdown(bProcessShutdown,bIsSystemShutdown); if (!bIsSystemShutdown) { DEBUGTRACE((LOG_WBEMCORE,"****** WinMgmt Shutdown ******************\n")); } return S_OK; } extern "C" HRESULT APIENTRY Reinitialize(DWORD dwReserved) { if(g_ShutdownCalled) { CEnterWbemCriticalSection enterCs(&g_csInit); DEBUGTRACE((LOG_WBEMCORE, "wbemcore!Reinitialize(%d) (g_ShutdownCalled = %d)\n", dwReserved, g_ShutdownCalled)); if(g_ShutdownCalled == FALSE) return S_OK; g_dwQueueSize = 1; g_pEss_m4 = NULL; g_lInitCount = -1; g_bDefaultMofLoadingNeeded = false; g_bDontAllowNewConnections = FALSE; g_pContextFac = NULL; g_pPathFac = NULL; g_pQueryFact = NULL; g_ShutdownCalled = FALSE; g_bPreviousFail = false; g_hrLastEnsuredInitializeError = WBEM_S_NO_ERROR; } return S_OK; }
28.296122
200
0.549834
npocmaka
2e7413220b0009c6df42a9faafc50ddcc1cfd62b
18,049
cpp
C++
silkworm/db/chaindb.cpp
gcolvin/silkworm
11cb3ea2aa215185eb96a460f87c67f83bdc6620
[ "Apache-2.0" ]
null
null
null
silkworm/db/chaindb.cpp
gcolvin/silkworm
11cb3ea2aa215185eb96a460f87c67f83bdc6620
[ "Apache-2.0" ]
null
null
null
silkworm/db/chaindb.cpp
gcolvin/silkworm
11cb3ea2aa215185eb96a460f87c67f83bdc6620
[ "Apache-2.0" ]
null
null
null
/* Copyright 2020 The Silkworm Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "chaindb.hpp" #include <boost/algorithm/string.hpp> #include <boost/interprocess/mapped_region.hpp> namespace silkworm::lmdb { void DatabaseConfig::set_readonly(bool value) { if (value) { flags |= MDB_RDONLY; } else { flags &= ~MDB_RDONLY; } } Environment::Environment(const DatabaseConfig& config) { if (config.path.empty()) { throw std::invalid_argument("Invalid argument : config.path"); } // Check data file exists and get its size // If it exists then map_size can only be either: // 0 - map_size is adjusted by LMDB to effective data size // any value >= data file size // *WARNING* setting a map_size != 0 && < data_size causes // LMDB to truncate data file thus losing data size_t data_file_size{0}; size_t data_map_size{0}; boost::filesystem::path data_path{config.path}; bool nosubdir{(config.flags & MDB_NOSUBDIR) == MDB_NOSUBDIR}; if (!nosubdir) { data_path /= boost::filesystem::path{"data.mdb"}; } if (boost::filesystem::exists(data_path)) { if (!boost::filesystem::is_regular_file(data_path)) { throw std::runtime_error(data_path.string() + " is not a regular file"); } data_file_size = boost::filesystem::file_size(data_path); } data_map_size = std::max(data_file_size, config.map_size); // Ensure map_size is multiple of host page_size if (data_map_size) { size_t host_page_size{boost::interprocess::mapped_region::get_page_size()}; data_map_size = ((data_map_size + host_page_size - 1) / host_page_size) * host_page_size; } err_handler(mdb_env_create(&handle_)); err_handler(mdb_env_set_mapsize(handle_, data_map_size)); err_handler(mdb_env_set_maxdbs(handle_, config.max_tables)); // Eventually open data file (this may throw) path_ = (nosubdir ? data_path.string() : data_path.parent_path().string()); err_handler(mdb_env_open(handle_, path_.c_str(), config.flags, config.mode)); } Environment::~Environment() noexcept { close(); } bool Environment::is_ro(void) { unsigned int env_flags{0}; err_handler(get_flags(&env_flags)); return ((env_flags & MDB_RDONLY) == MDB_RDONLY); } void Environment::close() noexcept { if (handle_) { mdb_env_close(handle_); handle_ = nullptr; } } int Environment::get_info(MDB_envinfo* info) { if (!info) { throw std::invalid_argument("Invalid argument : info"); } return mdb_env_info(handle_, info); } int Environment::get_flags(unsigned int* flags) { if (!flags) { throw std::invalid_argument("Invalid argument : flags"); } return mdb_env_get_flags(handle_, flags); } int Environment::get_mapsize(size_t* size) { MDB_envinfo info{}; int rc{get_info(&info)}; if (!rc) { *size = info.me_mapsize; } return rc; } int Environment::get_filesize(size_t* size) { if (!path_.size()) return ENOENT; uint32_t flags{0}; int rc{get_flags(&flags)}; if (rc) return rc; boost::filesystem::path data_path{path_}; bool nosubdir{(flags & MDB_NOSUBDIR) == MDB_NOSUBDIR}; if (!nosubdir) data_path /= boost::filesystem::path{"data.mdb"}; if (boost::filesystem::exists(data_path) && boost::filesystem::is_regular_file(data_path)) { *size = boost::filesystem::file_size(data_path); return MDB_SUCCESS; } return ENOENT; } int Environment::get_max_keysize(void) { return mdb_env_get_maxkeysize(handle_); } int Environment::get_max_readers(unsigned int* count) { if (!count) { throw std::invalid_argument("Invalid argument : count"); } return mdb_env_get_maxreaders(handle_, count); } int Environment::set_flags(const unsigned int flags, const bool onoff) { return mdb_env_set_flags(handle_, flags, onoff ? 1 : 0); } int Environment::set_mapsize(size_t size) { /* * A size == 0 means LMDB will auto adjust to * actual data file size. * In all other cases prevent setting map_size * to a lower value as it may truncate data file * (observed on Windows) */ if (size) { size_t actual_map_size{0}; int rc{get_mapsize(&actual_map_size)}; if (rc) return rc; if (size < actual_map_size) { throw std::runtime_error("Can't set a map_size lower than data file size."); } size_t host_page_size{boost::interprocess::mapped_region::get_page_size()}; size = ((size + host_page_size - 1) / host_page_size) * host_page_size; } return mdb_env_set_mapsize(handle_, size); } int Environment::set_max_dbs(const unsigned int count) { return mdb_env_set_maxdbs(handle_, count); } int Environment::set_max_readers(const unsigned int count) { return mdb_env_set_maxreaders(handle_, count); } int Environment::sync(const bool force) { return mdb_env_sync(handle_, force); } int Environment::get_ro_txns(void) noexcept { return ro_txns_[std::this_thread::get_id()]; } int Environment::get_rw_txns(void) noexcept { return rw_txns_[std::this_thread::get_id()]; } void Environment::touch_ro_txns(int count) noexcept { std::lock_guard<std::mutex> l(count_mtx_); ro_txns_[std::this_thread::get_id()] += count; } void Environment::touch_rw_txns(int count) noexcept { std::lock_guard<std::mutex> l(count_mtx_); rw_txns_[std::this_thread::get_id()] += count; } std::unique_ptr<Transaction> Environment::begin_transaction(unsigned int flags) { if (this->is_ro()) { flags |= MDB_RDONLY; } return std::make_unique<Transaction>(this, flags); } std::unique_ptr<Transaction> Environment::begin_ro_transaction(unsigned int flags) { // Simple overload to ensure MDB_RDONLY is set flags |= MDB_RDONLY; return begin_transaction(flags); } std::unique_ptr<Transaction> Environment::begin_rw_transaction(unsigned int flags) { // Simple overload to ensure MDB_RDONLY is NOT set flags &= ~MDB_RDONLY; return begin_transaction(flags); } /* * Transactions */ Transaction::Transaction(Environment* parent, MDB_txn* txn, unsigned int flags) : parent_env_{parent}, handle_{txn}, flags_{flags} {} MDB_txn* Transaction::open_transaction(Environment* parent_env, MDB_txn* parent_txn, unsigned int flags) { /* * A transaction and its cursors must only be used by a single thread, * and a thread may only have one transaction at a time. * If MDB_NOTLS is in use this does not apply to read-only transactions */ if (parent_env->get_rw_txns()) { throw std::runtime_error("Rw transaction already pending in this thread"); } // Ensure we don't open a rw tx in a ro env unsigned int env_flags{0}; err_handler(parent_env->get_flags(&env_flags)); bool env_ro{(env_flags & MDB_RDONLY) == MDB_RDONLY}; bool txn_ro{(flags & MDB_RDONLY) == MDB_RDONLY}; if (env_ro && !txn_ro) { throw std::runtime_error("Can't open a RW transaction on a RO environment"); } bool env_notls{(env_flags & MDB_NOTLS) == MDB_NOTLS}; if (txn_ro && !env_notls) { if (parent_env->get_ro_txns()) { throw std::runtime_error("RO transaction already pending in this thread"); } } MDB_txn* retvar{nullptr}; int maxtries{3}; int rc{0}; do { rc = mdb_txn_begin(*(parent_env->handle()), parent_txn, flags, &retvar); if (rc == MDB_MAP_RESIZED) { /* * If mapsize is resized by another process call mdb_env_set_mapsize * with a size of zero to adapt to new size */ err_handler(parent_env->set_mapsize(0)); } else if (rc == MDB_SUCCESS) { if (txn_ro) { parent_env->touch_ro_txns(1); } else { parent_env->touch_rw_txns(1); } break; } } while (--maxtries > 0); err_handler(rc); return retvar; } MDB_dbi Transaction::open_dbi(const char* name, unsigned int flags) { MDB_dbi newdbi{0}; err_handler(mdb_dbi_open(handle_, name, flags, &newdbi)); return newdbi; } Transaction::Transaction(Environment* parent, unsigned int flags) : Transaction(parent, open_transaction(parent, nullptr, flags), flags) {} Transaction::~Transaction() { abort(); } size_t Transaction::get_id(void) { return mdb_txn_id(handle_); } bool Transaction::is_ro(void) { return ((flags_ & MDB_RDONLY) == MDB_RDONLY); } std::unique_ptr<Table> Transaction::open(const TableConfig& config, unsigned flags) { flags |= config.flags; MDB_dbi dbi{open_dbi(config.name, flags)}; // Apply custom comparators (if any) // Uncomment the following when necessary // switch (config.key_comparator) // use mdb_set_compare //{ // default: // break; //} // Apply custom dup comparators (if any) switch (config.dup_comparator) // use mdb_set_dupsort { case TableCustomDupComparator::ExcludeSuffix32: err_handler(mdb_set_dupsort(handle_, dbi, dup_cmp_exclude_suffix32)); break; default: break; } return std::make_unique<Table>(this, dbi, config.name); } std::unique_ptr<Table> Transaction::open(MDB_dbi dbi) { if (dbi > 1) { throw std::invalid_argument("dbi can only be 0 or 1"); } return std::make_unique<Table>(this, dbi, nullptr); } void Transaction::abort(void) { if (handle_) { mdb_txn_abort(handle_); if (is_ro()) { parent_env_->touch_ro_txns(-1); } else { parent_env_->touch_rw_txns(-1); } handle_ = nullptr; } } int Transaction::commit(void) { if (!handle_) return MDB_BAD_TXN; int rc{mdb_txn_commit(handle_)}; if (rc == MDB_SUCCESS) { if (is_ro()) { parent_env_->touch_ro_txns(-1); } else { parent_env_->touch_rw_txns(-1); } handle_ = nullptr; } return rc; } /* * Tables */ Table::Table(Transaction* parent, MDB_dbi dbi, const char* name) : Table::Table(parent, dbi, name, open_cursor(parent, dbi)) {} Table::~Table() { close(); } MDB_cursor* Table::open_cursor(Transaction* parent, MDB_dbi dbi) { if (!*parent->handle()) { throw std::runtime_error("Database or transaction closed"); } MDB_cursor* retvar{nullptr}; err_handler(mdb_cursor_open(*parent->handle(), dbi, &retvar)); return retvar; } Table::Table(Transaction* parent, MDB_dbi dbi, const char* name, MDB_cursor* cursor) : parent_txn_{parent}, dbi_{dbi}, name_{name ? name : ""}, handle_{cursor} {} int Table::get_flags(unsigned int* flags) { return mdb_dbi_flags(*parent_txn_->handle(), dbi_, flags); } int Table::get_stat(MDB_stat* stat) { return mdb_stat(*parent_txn_->handle(), dbi_, stat); } int Table::get_rcount(size_t* count) { MDB_stat stat{}; int rc{get_stat(&stat)}; if (rc == MDB_SUCCESS) { *count = stat.ms_entries; } return rc; } std::string Table::get_name(void) { switch (dbi_) { case FREE_DBI: return {"[FREE_DBI]"}; case MAIN_DBI: return {"[MAIN_DBI]"}; default: break; } return name_; } MDB_dbi Table::get_dbi(void) { return dbi_; } int Table::clear() { close(); return mdb_drop(parent_txn_->handle_, dbi_, 0); } int Table::drop() { close(); dbi_dropped_ = true; return mdb_drop(parent_txn_->handle_, dbi_, 1); } int Table::get(MDB_val* key, MDB_val* data, MDB_cursor_op operation) { return mdb_cursor_get(handle_, key, data, operation); } int Table::put(MDB_val* key, MDB_val* data, unsigned int flag) { return mdb_cursor_put(handle_, key, data, flag); } std::optional<ByteView> Table::get(ByteView key) { MDB_val key_val{db::to_mdb_val(key)}; MDB_val data; int rc{get(&key_val, &data, MDB_SET)}; if (rc == MDB_NOTFOUND) { return {}; } err_handler(rc); return db::from_mdb_val(data); } std::optional<ByteView> Table::get(ByteView key, ByteView sub_key) { MDB_val key_val{db::to_mdb_val(key)}; MDB_val data{db::to_mdb_val(sub_key)}; int rc{get(&key_val, &data, MDB_GET_BOTH_RANGE)}; if (rc == MDB_NOTFOUND) { return {}; } err_handler(rc); ByteView x{db::from_mdb_val(data)}; if (!has_prefix(x, sub_key)) { return {}; } else { x.remove_prefix(sub_key.length()); return x; } } void Table::del(ByteView key) { if (get(key)) { err_handler(del_current()); } } void Table::del(ByteView key, ByteView sub_key) { if (get(key, sub_key)) { err_handler(del_current()); } } std::optional<db::Entry> Table::seek(ByteView prefix) { MDB_val key_val{db::to_mdb_val(prefix)}; MDB_val data; MDB_cursor_op op{prefix.empty() ? MDB_FIRST : MDB_SET_RANGE}; int rc{get(&key_val, &data, op)}; if (rc == MDB_NOTFOUND) { return {}; } err_handler(rc); db::Entry entry; entry.key = db::from_mdb_val(key_val); entry.value = db::from_mdb_val(data); return entry; } int Table::seek(MDB_val* key, MDB_val* data) { return get(key, data, MDB_SET_RANGE); } int Table::seek_exact(MDB_val* key, MDB_val* data) { return get(key, data, MDB_SET); } int Table::get_current(MDB_val* key, MDB_val* data) { return get(key, data, MDB_GET_CURRENT); } int Table::del_current(bool alldupkeys) { if (alldupkeys) { unsigned int flags{0}; int rc{get_flags(&flags)}; if (rc) { return rc; } if ((flags & MDB_DUPSORT) != MDB_DUPSORT) { alldupkeys = false; } } return mdb_cursor_del(handle_, alldupkeys ? MDB_NODUPDATA : 0); } int Table::get_first(MDB_val* key, MDB_val* data) { return get(key, data, MDB_FIRST); } int Table::get_first_dup(MDB_val* key, MDB_val* data) { return get(key, data, MDB_FIRST_DUP); } int Table::get_prev(MDB_val* key, MDB_val* data) { return get(key, data, MDB_PREV); } int Table::get_prev_dup(MDB_val* key, MDB_val* data) { return get(key, data, MDB_PREV_DUP); } int Table::get_next(MDB_val* key, MDB_val* data) { return get(key, data, MDB_NEXT); } int Table::get_next_dup(MDB_val* key, MDB_val* data) { return get(key, data, MDB_NEXT_DUP); } int Table::get_next_nodup(MDB_val* key, MDB_val* data) { return get(key, data, MDB_NEXT_NODUP); } int Table::get_last(MDB_val* key, MDB_val* data) { return get(key, data, MDB_LAST); } int Table::get_dcount(size_t* count) { return mdb_cursor_count(handle_, count); } void Table::put(ByteView key, ByteView data, unsigned flags) { MDB_val key_val{db::to_mdb_val(key)}; MDB_val data_val{db::to_mdb_val(data)}; err_handler(put(&key_val, &data_val, flags)); } int Table::put_current(MDB_val* key, MDB_val* data) { return put(key, data, MDB_CURRENT); } int Table::put_nodup(MDB_val* key, MDB_val* data) { return put(key, data, MDB_NODUPDATA); } int Table::put_noovrw(MDB_val* key, MDB_val* data) { return put(key, data, MDB_NOOVERWRITE); } int Table::put_reserve(MDB_val* key, MDB_val* data) { return put(key, data, MDB_RESERVE); } int Table::put_append(MDB_val* key, MDB_val* data) { return put(key, data, MDB_APPEND); } int Table::put_append_dup(MDB_val* key, MDB_val* data) { return put(key, data, MDB_APPENDDUP); } int Table::put_multiple(MDB_val* key, MDB_val* data) { return put(key, data, MDB_MULTIPLE); } void Table::close() { // Free the cursor handle // There is no need to close the dbi_ handle if (handle_) { mdb_cursor_close(handle_); handle_ = nullptr; } } std::shared_ptr<Environment> get_env(DatabaseConfig config) { struct Value { std::weak_ptr<Environment> wp; uint32_t flags{0}; }; static std::map<size_t, Value> s_envs; static std::mutex s_mtx; // Compute flags for required instance // We actually don't care for MDB_RDONLY uint32_t compare_flags{config.flags ? (config.flags &= ~MDB_RDONLY) : 0}; // There's a 1:1 relation among env and the opened // database file. Build a hash of the path. // Note that windows is case insensitive std::string pathstr{boost::algorithm::to_lower_copy(config.path)}; std::hash<std::string> pathhash; size_t envkey{pathhash(pathstr)}; // Only one thread at a time std::lock_guard<std::mutex> l(s_mtx); // Locate env if already exists auto iter = s_envs.find(envkey); if (iter != s_envs.end()) { if (iter->second.flags != compare_flags) { err_handler(MDB_INCOMPATIBLE); } auto item = iter->second.wp.lock(); if (item && item->is_opened()) { return item; } else { s_envs.erase(iter); } } // Create new instance and open db file(s) // Data file is opened/created on constructor auto newitem = std::make_shared<Environment>(config); s_envs[envkey] = {newitem, compare_flags}; return newitem; } int dup_cmp_exclude_suffix32(const MDB_val* a, const MDB_val* b) { size_t lenA{(a->mv_size >= 32) ? a->mv_size - 32 : a->mv_size}; size_t lenB{(b->mv_size >= 32) ? b->mv_size - 32 : b->mv_size}; size_t len{lenA}; int64_t len_diff{(int64_t)lenA - (int64_t)(lenB)}; if (len_diff > 0) { len = lenB; len_diff = 1; } int diff{memcmp(a->mv_data, b->mv_data, len)}; return diff ? diff : (len_diff < 0 ? -1 : (int)len_diff); } } // namespace silkworm::lmdb
32.230357
115
0.653499
gcolvin
2e745caf97f63b1786f8767cea664aa369fc178b
1,871
hpp
C++
libs/core/execution/include/hpx/execution/traits/detail/simd/vector_pack_load_store.hpp
Andrea-MariaDB-2/hpx
e230dddce4a8783817f38e07f5a77e624f64f826
[ "BSL-1.0" ]
1,822
2015-01-03T11:22:37.000Z
2022-03-31T14:49:59.000Z
libs/core/execution/include/hpx/execution/traits/detail/simd/vector_pack_load_store.hpp
Andrea-MariaDB-2/hpx
e230dddce4a8783817f38e07f5a77e624f64f826
[ "BSL-1.0" ]
3,288
2015-01-05T17:00:23.000Z
2022-03-31T18:49:41.000Z
libs/core/execution/include/hpx/execution/traits/detail/simd/vector_pack_load_store.hpp
Andrea-MariaDB-2/hpx
e230dddce4a8783817f38e07f5a77e624f64f826
[ "BSL-1.0" ]
431
2015-01-07T06:22:14.000Z
2022-03-31T14:50:04.000Z
// Copyright (c) 2021 Srinivas Yadav // Copyright (c) 2016-2017 Hartmut Kaiser // // SPDX-License-Identifier: BSL-1.0 // 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) #pragma once #include <hpx/config.hpp> #if defined(HPX_HAVE_CXX20_EXPERIMENTAL_SIMD) #include <cstddef> #include <iterator> #include <memory> #include <experimental/simd> /////////////////////////////////////////////////////////////////////////////// namespace hpx { namespace parallel { namespace traits { /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// template <typename V, typename ValueType, typename Enable> struct vector_pack_load { template <typename Iter> static V aligned(Iter const& iter) { return V(std::addressof(*iter), std::experimental::vector_aligned); } template <typename Iter> static V unaligned(Iter const& iter) { return V(std::addressof(*iter), std::experimental::element_aligned); } }; /////////////////////////////////////////////////////////////////////////// template <typename V, typename ValueType, typename Enable> struct vector_pack_store { template <typename Iter> static void aligned(V& value, Iter const& iter) { value.copy_to( std::addressof(*iter), std::experimental::vector_aligned); } template <typename Iter> static void unaligned(V& value, Iter const& iter) { value.copy_to( std::addressof(*iter), std::experimental::element_aligned); } }; }}} // namespace hpx::parallel::traits #endif
30.672131
80
0.525387
Andrea-MariaDB-2
2e785579f8d9d1af563bbe8c74a7144bb21d7a33
2,136
hpp
C++
xs/src/boost/range/detail/iterator.hpp
born2b/Slic3r
589a0b3ac1a50f84de694b89cc10abcac45c0ae6
[ "CC-BY-3.0" ]
460
2016-01-13T12:49:34.000Z
2022-02-20T04:10:40.000Z
xs/src/boost/range/detail/iterator.hpp
born2b/Slic3r
589a0b3ac1a50f84de694b89cc10abcac45c0ae6
[ "CC-BY-3.0" ]
197
2017-07-06T16:53:59.000Z
2019-05-31T17:57:51.000Z
xs/src/boost/range/detail/iterator.hpp
born2b/Slic3r
589a0b3ac1a50f84de694b89cc10abcac45c0ae6
[ "CC-BY-3.0" ]
148
2016-01-17T03:16:43.000Z
2022-03-17T12:20:36.000Z
// Boost.Range library // // Copyright Thorsten Ottosen 2003-2004. Use, modification and // distribution is subject to 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) // // For more information, see http://www.boost.org/libs/range/ // #ifndef BOOST_RANGE_DETAIL_ITERATOR_HPP #define BOOST_RANGE_DETAIL_ITERATOR_HPP #include <boost/range/detail/common.hpp> #include <boost/range/detail/remove_extent.hpp> #include <boost/static_assert.hpp> ////////////////////////////////////////////////////////////////////////////// // missing partial specialization workaround. ////////////////////////////////////////////////////////////////////////////// namespace boost { namespace range_detail { template< typename T > struct range_iterator_ { template< typename C > struct pts { typedef int type; }; }; template<> struct range_iterator_<std_container_> { template< typename C > struct pts { typedef BOOST_RANGE_DEDUCED_TYPENAME C::iterator type; }; }; template<> struct range_iterator_<std_pair_> { template< typename P > struct pts { typedef BOOST_RANGE_DEDUCED_TYPENAME P::first_type type; }; }; template<> struct range_iterator_<array_> { template< typename T > struct pts { typedef BOOST_RANGE_DEDUCED_TYPENAME remove_extent<T>::type* type; }; }; } template< typename C > class range_mutable_iterator { typedef BOOST_RANGE_DEDUCED_TYPENAME range_detail::range<C>::type c_type; public: typedef typename range_detail::range_iterator_<c_type>::BOOST_NESTED_TEMPLATE pts<C>::type type; }; } #endif
27.037975
106
0.519195
born2b
2e7b3571188db7f172cd05e9d084156af98dc8f7
7,768
hpp
C++
lib/random.hpp
jplevyak/pyc
9f4bc49be78ba29427841460945ce63826fcd857
[ "BSD-3-Clause" ]
3
2019-08-21T22:01:35.000Z
2021-07-25T00:21:28.000Z
lib/random.hpp
jplevyak/pyc
9f4bc49be78ba29427841460945ce63826fcd857
[ "BSD-3-Clause" ]
null
null
null
lib/random.hpp
jplevyak/pyc
9f4bc49be78ba29427841460945ce63826fcd857
[ "BSD-3-Clause" ]
null
null
null
#ifndef __RANDOM_HPP #define __RANDOM_HPP #include "builtin.hpp" #include "math.hpp" #include "time.hpp" using namespace __shedskin__; namespace __random__ { class Random; class WichmannHill; extern class_ *cl_Random; class Random : public pyobj { /** Random number generator base class used by bound module functions. Used to instantiate instances of Random to get generators that don't share state. Especially useful for multi-threaded programs, creating a different instance of Random for each thread, and using the jumpahead() method to ensure that the generated sequences seen by each thread don't overlap. Class Random can also be subclassed if you want to use a different basic generator of your own devising: in that case, override the following methods: random(), seed(), getstate(), setstate() and jumpahead(). */ public: int gauss_switch; int VERSION; double gauss_next; list<int> *mt; int mti; virtual double random(); double paretovariate(double alpha); int randrange(int stop); int randrange(int start, int stop); int randrange(int start, int stop, int step); double betavariate(double alpha, double beta); double normalvariate(double mu, double sigma); double _genrand_res53(); void *seed(); void *seed(int a); double weibullvariate(double alpha, double beta); Random(); Random(int a); int _init_by_array(list<int> *init_key); int randint(int a, int b); double vonmisesvariate(double mu, double kappa); double gammavariate(double alpha, double beta); double uniform(double a, double b); double stdgamma(double alpha, double ainv, double bbb, double ccc); double expovariate(double lambd); int getrandbits(int k); virtual int setstate(list<double> *state); double lognormvariate(double mu, double sigma); int _init_genrand(int s); double gauss(double mu, double sigma); template <class A> A choice(pyseq<A> *seq); template <class A> int shuffle(pyseq<A> *x); template <class A> list<A> *sample(pyiter<A> *population, int k); template <class A> list<A> *sample(pyseq<A> *population, int k); int _genrand_int32(); virtual list<double> *getstate(); double cunifvariate(double mean, double arc); }; extern class_ *cl_WichmannHill; class WichmannHill : public Random { public: tuple2<int, int> *_seed; void *__whseed(int x, int y, int z); double random(); void *seed(); void *seed(int a); WichmannHill(); WichmannHill(int a); void *whseed(); void *whseed(int a); int setstate(list<double> *state); int jumpahead(int n); list<double> *getstate(); }; extern int UPPER; extern double LOG4; extern double SG_MAGICCONST; extern list<str *> * __all__; extern int BPF; extern Random * _inst; extern int MATRIX_A; extern int M; extern int LOWER; extern int N; extern int MAXWIDTH; extern int MAXINT; extern str * __name__; extern double NV_MAGICCONST; extern int MAXBITS; void __init(); void *seed(); void *seed(int a); double random(); list<double> *getstate(); int setstate(list<double> *state); int randrange(int stop); int randrange(int start, int stop); int randrange(int start, int stop, int step); int randint(int a, int b); template <class A> A choice(pyseq<A> *seq); template <class A> int shuffle(pyseq<A> *x); template <class A> list<A> *sample(pyiter<A> *population, int k); template <class A> list<A> *sample(pyseq<A> *population, int k); double uniform(double a, double b); double normalvariate(double mu, double sigma); double lognormvariate(double mu, double sigma); double cunifvariate(double mean, double arc); double expovariate(double lambd); double vonmisesvariate(double mu, double kappa); double gammavariate(double alpha, double beta); double stdgamma(double alpha, double ainv, double bbb, double ccc); double gauss(double mu, double sigma); double betavariate(double alpha, double beta); double paretovariate(double alpha); double weibullvariate(double alpha, double beta); int getrandbits(int k); template <class A> A choice(pyseq<A> *seq) { return _inst->choice(seq); } template <class A> int shuffle(pyseq<A> *x) { return _inst->shuffle(x); } template <class A> list<A> *sample(pyiter<A> *population, int k) { return sample(__list(population), k); } template <class A> list<A> *sample(pyseq<A> *population, int k) { return _inst->sample(population, k); } template <class A> int Random::shuffle(pyseq<A> *x) { /** x, random=random.random -> shuffle list x in place; return None. Note that for even rather small len(x), the total number of permutations of x is larger than the period of most random number generators; this implies that "most" permutations of a long sequence can never be generated. */ A __31, __32; int __29, __30, i, j; FAST_FOR_NEG(i,(len(x)-1),0,-1,29,30) j = __int((this->random()*(i+1))); __31 = x->__getitem__(j); __32 = x->__getitem__(i); ELEM((x),i) = __31; ELEM((x),j) = __32; END_FOR return 0; } template <class A> list<A> *Random::sample(pyiter<A> *population, int k) { return sample(__list(population), k); } template <class A> list<A> *Random::sample(pyseq<A> *population, int k) { /** Chooses k unique random elements from a population sequence. Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices). Members of the population need not be hashable or unique. If the population contains repeats, then each occurrence is a possible selection in the sample. */ str *const_5, *const_6; const_5 = new str("sample larger than population"); const_6 = new str("population to sample has no members"); A __39; dict<int, A> *selected; int __33, __34, __37, __38, i, j, n; list<A> *pool, *result; n = len(population); if ((!((0<=k)&&(k<=n)))) { throw (new ValueError(const_5)); } if ((n==0)) { throw (new ValueError(const_6)); } result = ((new list<A>(1, population->__getitem__(0))))->__mul__(k); if ((n<(6*k))) { pool = __list(population); FAST_FOR(i,0,k,1,33,34) j = __int((this->random()*(n-i))); ELEM((result),i) = pool->__getfast__(j); ELEM((pool),j) = pool->__getfast__(((n-i)-1)); END_FOR } else { try { ((n>0) && ___bool((new tuple2<A, A>(3, population->__getitem__(0), population->__getitem__(__floordiv(n, 2)), population->__getitem__((n-1)))))); } catch (TypeError *) { population = __tuple(population); } catch (KeyError *) { population = __tuple(population); } selected = (new dict<int, A>()); FAST_FOR(i,0,k,1,37,38) j = __int((this->random()*n)); while(selected->__contains__(j)) { j = __int((this->random()*n)); } __39 = population->__getitem__(j); ELEM((result),i) = __39; selected->__setitem__(j, __39); END_FOR } return result; } template <class A> A Random::choice(pyseq<A> *seq) { /** Choose a random element from a non-empty sequence. */ return seq->__getitem__(__int((this->random()*len(seq)))); } } // module namespace #endif
30.582677
157
0.647013
jplevyak
2e848f245b5f81110c8b662c0796f425a6e459c0
13,740
cpp
C++
src/renderer/displayer/raster/raster.cpp
lPrimemaster/Liquid
72c11bf96cccb3f93725f46f0e0756a1b732163c
[ "MIT" ]
null
null
null
src/renderer/displayer/raster/raster.cpp
lPrimemaster/Liquid
72c11bf96cccb3f93725f46f0e0756a1b732163c
[ "MIT" ]
null
null
null
src/renderer/displayer/raster/raster.cpp
lPrimemaster/Liquid
72c11bf96cccb3f93725f46f0e0756a1b732163c
[ "MIT" ]
null
null
null
#include "raster.h" #include "../../raycaster/geometry.h" #include "../overlay.h" #include "../../../utils/shaderloader.h" #include "../../raycaster/hittable/model.h" #include <vector> #include <tuple> #include <unordered_map> internal Vector3 rasterCamFront; internal Vector3 rasterCamPos; internal Vector3 rasterCamUp; internal u32 rasterScreenW; internal u32 rasterScreenH; struct RasterData { GLuint vao, vbo; u64 vtxCount; }; internal std::vector<RasterData> rasterDataArray[Geometry::TYPESIZE]; internal GLuint program; internal std::vector<Vector3> rasterRandomColors; internal void CreateRasterSphere(i32 ico_it) { std::vector<Vector3> vertices; std::vector<i32> indices; f32 t = (1.0f + sqrtf(5.0f)) / 2.0f; f32 len = sqrtf(1 + t*t); f32 a = 1 / len; f32 b = t / len; // Create initial vertices vertices.push_back(Vector3(-a, b, 0)); vertices.push_back(Vector3( a, b, 0)); vertices.push_back(Vector3(-a, -b, 0)); vertices.push_back(Vector3( a, -b, 0)); vertices.push_back(Vector3( 0, -a, b)); vertices.push_back(Vector3( 0, a, b)); vertices.push_back(Vector3( 0, -a, -b)); vertices.push_back(Vector3( 0, a, -b)); vertices.push_back(Vector3( b, 0, -a)); vertices.push_back(Vector3( b, 0, a)); vertices.push_back(Vector3(-b, 0, -a)); vertices.push_back(Vector3(-b, 0, a)); // Create initial faces / tris using FaceVec = std::vector<std::tuple<i32, i32, i32>>; FaceVec faces; // 5 faces around point 0 faces.push_back(std::make_tuple(0, 11, 5)); faces.push_back(std::make_tuple(0, 5, 1)); faces.push_back(std::make_tuple(0, 1, 7)); faces.push_back(std::make_tuple(0, 7, 10)); faces.push_back(std::make_tuple(0, 10, 11)); // 5 adjacent faces faces.push_back(std::make_tuple(1, 5, 9)); faces.push_back(std::make_tuple(5, 11, 4)); faces.push_back(std::make_tuple(11, 10, 2)); faces.push_back(std::make_tuple(10, 7, 6)); faces.push_back(std::make_tuple(7, 1, 8)); // 5 faces around point 3 faces.push_back(std::make_tuple(3, 9, 4)); faces.push_back(std::make_tuple(3, 4, 2)); faces.push_back(std::make_tuple(3, 2, 6)); faces.push_back(std::make_tuple(3, 6, 8)); faces.push_back(std::make_tuple(3, 8, 9)); // 5 adjacent faces faces.push_back(std::make_tuple(4, 9, 5)); faces.push_back(std::make_tuple(2, 4, 11)); faces.push_back(std::make_tuple(6, 2, 10)); faces.push_back(std::make_tuple(8, 6, 7)); faces.push_back(std::make_tuple(9, 8, 1)); std::unordered_map<i64, i32> middlePointIndexCache; auto getMiddlePoint = [&](i32 p1, i32 p2) -> i32 { // first check if we have it already bool firstIsSmaller = p1 < p2; i64 smallerIndex = firstIsSmaller ? p1 : p2; i64 greaterIndex = firstIsSmaller ? p2 : p1; i64 key = (smallerIndex << 32) + greaterIndex; if(middlePointIndexCache.find(key) != middlePointIndexCache.end()) { return middlePointIndexCache.at(key); } // not in cache, calculate it Vector3 point1 = vertices[p1]; Vector3 point2 = vertices[p2]; Vector3 middle = Vector3( (point1.x + point2.x) / 2.0f, (point1.y + point2.y) / 2.0f, (point1.z + point2.z) / 2.0f ); vertices.push_back(middle.normalized()); i32 i = (i32)vertices.size() - 1; middlePointIndexCache.emplace(key, i); return i; }; // refine triangles with recursion for (i32 i = 0; i < ico_it; i++) { FaceVec facesR; for(auto t : faces) { i32 v1 = std::get<0>(t); i32 v2 = std::get<1>(t); i32 v3 = std::get<2>(t); // replace triangle by 4 triangles i32 a = getMiddlePoint(v1, v2); i32 b = getMiddlePoint(v2, v3); i32 c = getMiddlePoint(v3, v1); facesR.push_back(std::make_tuple(v1, a, c)); facesR.push_back(std::make_tuple(v2, b, a)); facesR.push_back(std::make_tuple(v3, c, b)); facesR.push_back(std::make_tuple(a, b, c)); } faces = facesR; } std::vector<f32> rawVertexData; // done we dont use EBO for this for(auto t : faces) { Vector3 v1 = vertices[std::get<0>(t)]; Vector3 v2 = vertices[std::get<1>(t)]; Vector3 v3 = vertices[std::get<2>(t)]; // flat // Vector3 w = v2 - v1; // Vector3 u = v3 - v1; // Vector3 N = Vector3::Cross(w, v); // smooth Vector3 n1 = v1; Vector3 n2 = v2; Vector3 n3 = v3; rawVertexData.push_back(v1.x); rawVertexData.push_back(v1.y); rawVertexData.push_back(v1.z); rawVertexData.push_back(n1.x); rawVertexData.push_back(n1.y); rawVertexData.push_back(n1.z); rawVertexData.push_back(v2.x); rawVertexData.push_back(v2.y); rawVertexData.push_back(v2.z); rawVertexData.push_back(n2.x); rawVertexData.push_back(n2.y); rawVertexData.push_back(n2.z); rawVertexData.push_back(v3.x); rawVertexData.push_back(v3.y); rawVertexData.push_back(v3.z); rawVertexData.push_back(n3.x); rawVertexData.push_back(n3.y); rawVertexData.push_back(n3.z); } // Now fill the opengl buffer RasterData data; data.vtxCount = rawVertexData.size() / 2; glGenVertexArrays(1, &data.vao); glGenBuffers(1, &data.vbo); glBindVertexArray(data.vao); glBindBuffer(GL_ARRAY_BUFFER, data.vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(f32) * rawVertexData.size(), rawVertexData.data(), GL_STATIC_DRAW); // Position glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(f32), (void*)0); glEnableVertexAttribArray(0); // Normals glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(f32), (void*)(3 * sizeof(f32))); glEnableVertexAttribArray(1); rasterDataArray[Geometry::SPHERE].push_back(data); } internal void CreateRasterCube() { RasterData& data = rasterDataArray[0].at(0); glGenVertexArrays(1, &data.vao); glGenBuffers(1, &data.vbo); glBindVertexArray(data.vao); f32 vertices[] = { -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, // 0 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, // 1 0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, // 2 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, // 0 -0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, // 1 -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, // 2 -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, // 0 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, // 1 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, // 2 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, // 0 -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, // 1 -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, // 2 -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, // 0 -0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, // 1 -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, // 2 -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, // 0 -0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, // 1 -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, // 2 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, // 0 0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, // 1 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, // 2 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, // 0 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, // 1 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, // 2 -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, // 0 0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, // 1 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, // 2 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, // 0 -0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, // 1 -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, // 2 -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, // 0 0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, // 1 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, // 2 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, // 0 -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, // 1 -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f // 2 }; glBindBuffer(GL_ARRAY_BUFFER, data.vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // Position glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(f32), (void*)0); glEnableVertexAttribArray(0); // Normals glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(f32), (void*)(3 * sizeof(f32))); glEnableVertexAttribArray(1); } // TODO : Refactor this for general callbacks for both raster and rt with switch based on options internal void mouse_callback(GLFWwindow* window, double xpos, double ypos) { if(glfwGetMouseButton(window, 1) != GLFW_PRESS) return; static const f32 D2R = PI / 180.0f; static f32 pitch = 0; static f32 yaw = 0; f32 xoffset = (f32)xpos - rasterScreenW / 2; f32 yoffset = rasterScreenH / 2 - (f32)ypos; glfwSetCursorPos(window, rasterScreenW / 2, rasterScreenH / 2); static const f32 sensitivity = 0.1f; xoffset *= sensitivity; yoffset *= sensitivity; yaw += xoffset; pitch += yoffset; if(pitch > 89.0f) pitch = 89.0f; if(pitch < -89.0f) pitch = -89.0f; Vector3 direction; direction.x = cosf(D2R * yaw) * cosf(D2R * pitch); direction.y = sinf(D2R * pitch); direction.z = sinf(D2R * yaw) * cosf(D2R * pitch); rasterCamFront = direction.normalized(); } internal void mousebtn_callback(GLFWwindow* window, int button, int action, int mods) { if(button == 1 && action == GLFW_RELEASE) { // Update rt camera for current view // TODO: Make this an option instead in the future Scene* iworld = (Scene*)glfwGetWindowUserPointer(window); iworld->renderCamera->updateView(rasterCamPos, rasterCamPos + rasterCamFront); } } void Raster::SetupRaster(GLFWwindow* window, Overlay::RenderSettings* rs) { // TODO: Remove hardcode - process viewport dim change rasterScreenW = 1280; rasterScreenH = 720; glfwSetCursorPosCallback(window, mouse_callback); glfwSetMouseButtonCallback(window, mousebtn_callback); program = ShaderLoader::LoadSimpleShader("shaders/raster"); // Create default internal rendering models (cube and sphere) // CreateRasterCube(); CreateRasterSphere(5); } void Raster::CleanRaster() { for(i32 i = 0; i < Geometry::TYPESIZE; i++) { for(auto& v : rasterDataArray[i]) { glDeleteVertexArrays(1, &v.vao); glDeleteBuffers(1, &v.vbo); } rasterDataArray[i].clear(); } glDeleteProgram(program); } internal Vector3 ProcessInputIncrementFPS(GLFWwindow *window, Vector3& camFront, Vector3& camUp) { Vector3 R; if(glfwGetMouseButton(window, 1) != GLFW_PRESS) return R; // Return zero vec if no right click static const float cameraSpeed = 0.05f; // adjust accordingly if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) R = R + cameraSpeed * camFront; if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) R = R - cameraSpeed * camFront; if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) R = R - Vector3::Cross(camFront, camUp).normalized() * cameraSpeed; if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) R = R + Vector3::Cross(camFront, camUp).normalized() * cameraSpeed; return R; } internal Matrix4 UpdateCamera(GLFWwindow* window, Scene* world, Overlay::RenderSettings* rs) { rasterCamPos = rasterCamPos + ProcessInputIncrementFPS(window, rasterCamFront, rasterCamUp); return Matrix4::LookAt(rasterCamPos, rasterCamPos + rasterCamFront, rasterCamUp); } void Raster::UpdateRasterSceneOnLoad(Scene* world) { rasterCamPos = world->renderCamera->origin; rasterCamFront = world->renderCamera->direction; rasterCamUp = world->renderCamera->up; } void Raster::RenderRaster(GLFWwindow* window, Scene* world, Overlay::RenderSettings* rs) { if(world->top == nullptr || !rs->rasterRender.load()) return; glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glClearDepth(1.0); // glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); Matrix4 P = world->renderCamera->projection; Matrix4 V = UpdateCamera(window, world, rs); glUseProgram(program); glUniformMatrix4fv( glGetUniformLocation(program, "projection"), 1, GL_FALSE, &P.data[0][0] ); glUniformMatrix4fv( glGetUniformLocation(program, "view"), 1, GL_FALSE, &V.data[0][0] ); // Display a cube for each obj in scene i32 i = 0; for(auto o : world->objList) { if(i >= rasterRandomColors.size()) { rasterRandomColors.push_back(Vector3( Random::RandomF32Range(0, 1), Random::RandomF32Range(0, 1), Random::RandomF32Range(0, 1) )); } // FIX: Redo the bvh's for transform coordinates .... Matrix4 M = o->transform.tmatrix; glUniformMatrix4fv( glGetUniformLocation(program, "model"), 1, GL_FALSE, &M.data[0][0] ); glUniform3fv( glGetUniformLocation(program, "objectColor"), 1, rasterRandomColors[i++].data ); RasterData& data = rasterDataArray[o->model->mesh->type].at(0); glBindVertexArray(data.vao); glDrawArrays(GL_TRIANGLES, 0, (GLsizei)data.vtxCount); } // glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glDisable(GL_DEPTH_TEST); }
32.40566
108
0.586681
lPrimemaster
2e872c91eabd0911e4d5b6946e678ef4b55d4e8d
10,809
cpp
C++
G/GeographicLibWrapper/src/GeographicLibWrapper.cpp
sharanry/Yggdrasil
d89cb4ffdc8e96ad39b6242b3574c59561c1b546
[ "MIT" ]
195
2018-09-14T22:41:36.000Z
2022-03-16T03:35:17.000Z
G/GeographicLibWrapper/src/GeographicLibWrapper.cpp
sharanry/Yggdrasil
d89cb4ffdc8e96ad39b6242b3574c59561c1b546
[ "MIT" ]
2,176
2018-12-20T07:05:43.000Z
2022-03-31T21:39:20.000Z
G/GeographicLibWrapper/src/GeographicLibWrapper.cpp
sharanry/Yggdrasil
d89cb4ffdc8e96ad39b6242b3574c59561c1b546
[ "MIT" ]
455
2018-09-27T21:28:33.000Z
2022-03-23T06:27:44.000Z
#include "jlcxx/jlcxx.hpp" #include <GeographicLib/Geocentric.hpp> #include <GeographicLib/Geoid.hpp> #include <GeographicLib/GravityCircle.hpp> #include <GeographicLib/GravityModel.hpp> #include <GeographicLib/MagneticCircle.hpp> #include <GeographicLib/MagneticModel.hpp> #include <GeographicLib/Math.hpp> #include <GeographicLib/NormalGravity.hpp> using namespace GeographicLib; JLCXX_MODULE define_julia_module(jlcxx::Module &mod) { typedef Math::real real; mod.add_type<Geocentric>("Geocentric") .constructor<real, real>() .method("forward", [](const Geocentric &g, real lat, real lon, real h, real &X, real &Y, real &Z) { return g.Forward(lat, lon, h, X, Y, Z); }) .method("forward", [](const Geocentric &g, real lat, real lon, real h, real &X, real &Y, real &Z, std::vector<real> &M) { return g.Forward(lat, lon, h, X, Y, Z, M); }) .method("reverse", [](const Geocentric &g, real X, real Y, real Z, real &lat, real &lon, real &h) { return g.Reverse(X, Y, Z, lat, lon, h); }) .method("reverse", [](const Geocentric &g, real X, real Y, real Z, real &lat, real &lon, real &h, std::vector<real> &M) { return g.Reverse(X, Y, Z, lat, lon, h, M); }) .method("init", &Geocentric::Init) .method("equatorial_radius", &Geocentric::EquatorialRadius) .method("flattening", &Geocentric::Flattening) .method("wgs84_geocentric", &Geocentric::WGS84); mod.add_bits<Geoid::convertflag>("ConvertFlag", jlcxx::julia_type("CppEnum")); mod.set_const("ELLIPSOIDTOGEOID", Geoid::ELLIPSOIDTOGEOID); mod.set_const("NONE", Geoid::NONE); mod.set_const("GEOIDTOELLIPSOID", Geoid::GEOIDTOELLIPSOID); mod.add_type<Geoid>("Geoid") .constructor<const std::string &, const std::string &, bool, bool>() .method(&Geoid::operator()) .method("cache_area", &Geoid::CacheArea) .method("cache_all", &Geoid::CacheAll) .method("cache_clear", &Geoid::CacheClear) .method("convert_height", &Geoid::ConvertHeight) .method("description", &Geoid::Description) .method("date_time", &Geoid::DateTime) .method("geoid_file", &Geoid::GeoidFile) .method("geoid_name", &Geoid::GeoidName) .method("geoid_directory", &Geoid::GeoidDirectory) .method("interpolation", &Geoid::Interpolation) .method("max_error", &Geoid::MaxError) .method("rms_error", &Geoid::RMSError) .method("offset", &Geoid::Offset) .method("scale", &Geoid::Scale) .method("thread_safe", &Geoid::ThreadSafe) .method("cache", &Geoid::Cache) .method("cache_west", &Geoid::CacheWest) .method("cache_east", &Geoid::CacheEast) .method("cache_north", &Geoid::CacheNorth) .method("cache_south", &Geoid::CacheSouth) .method("equatorial_radius", &Geoid::EquatorialRadius) .method("flattening", &Geoid::Flattening) .method("default_geoid_path", &Geoid::DefaultGeoidPath) .method("default_geoid_name", &Geoid::DefaultGeoidName); mod.add_type<NormalGravity>("NormalGravity") .constructor<real, real, real, real, bool>() .method("surface_gravity", &NormalGravity::SurfaceGravity) .method("gravity", &NormalGravity::Gravity) .method("u", &NormalGravity::U) .method("v0", &NormalGravity::V0) .method("phi", &NormalGravity::Phi) .method("init", &NormalGravity::Init) .method("equatorial_radius", &NormalGravity::EquatorialRadius) .method("mass_constant", &NormalGravity::MassConstant) .method("dynamical_form_factor", &NormalGravity::DynamicalFormFactor) .method("angular_velocity", &NormalGravity::AngularVelocity) .method("flattening", &NormalGravity::Flattening) .method("equatorial_gravity", &NormalGravity::EquatorialGravity) .method("polar_gravity", &NormalGravity::PolarGravity) .method("gravity_flattening", &NormalGravity::GravityFlattening) .method("surface_potential", &NormalGravity::SurfacePotential) .method("earth", &NormalGravity::Earth) .method("wgs84_normal_gravity", &NormalGravity::WGS84) .method("grs80_normal_gravity", &NormalGravity::GRS80) .method("j2_to_flattening", &NormalGravity::J2ToFlattening) .method("flattening_to_j2", &NormalGravity::FlatteningToJ2); mod.add_type<GravityCircle>("GravityCircle") .method("gravity", &GravityCircle::Gravity) .method("disturbance", &GravityCircle::Disturbance) .method("geoid_height", &GravityCircle::GeoidHeight) .method("spherical_anomaly", &GravityCircle::SphericalAnomaly) .method("w", [](const GravityCircle &g, real lon, real &gX, real &gY, real &gZ) { return g.W(lon, gX, gY, gZ); }) .method("v", [](const GravityCircle &g, real lon, real &GX, real &GY, real &GZ) { return g.V(lon, GX, GY, GZ); }) .method("t", [](const GravityCircle &g, real lon, real &deltaX, real &deltaY, real &deltaZ) { return g.T(lon, deltaX, deltaY, deltaZ); }) .method("t", [](const GravityCircle &g, real lon) { return g.T(lon); }) .method("init", &GravityCircle::Init) .method("equatorial_radius", &GravityCircle::EquatorialRadius) .method("flattening", &GravityCircle::Flattening) .method("latitude", &GravityCircle::Latitude) .method("height", &GravityCircle::Height) .method("capabilities", [](const GravityCircle &g) { return g.Capabilities(); }) .method("capabilities", [](const GravityCircle &g, unsigned testcaps) { return g.Capabilities(testcaps); }); mod.add_type<GravityModel>("GravityModel") .constructor<const std::string &, const std::string &, int, int>() .method("gravity", &GravityModel::Gravity) .method("disturbance", &GravityModel::Disturbance) .method("geoid_height", &GravityModel::GeoidHeight) .method("spherical_anomaly", &GravityModel::SphericalAnomaly) .method("w", &GravityModel::W) .method("v", &GravityModel::V) .method("t", [](const GravityModel &g, real X, real Y, real Z, real &deltaX, real &deltaY, real &deltaZ) { return g.T(X, Y, Z, deltaX, deltaY, deltaZ); }) .method("t", [](const GravityModel &g, real X, real Y, real Z) { return g.T(X, Y, Z); }) .method("u", &GravityModel::U) .method("phi", &GravityModel::Phi) .method("circle", &GravityModel::Circle) .method("reference_ellipsoid", &GravityModel::ReferenceEllipsoid) .method("description", &GravityModel::Description) .method("date_time", &GravityModel::DateTime) .method("gravity_file", &GravityModel::GravityFile) .method("gravity_model_name", &GravityModel::GravityModelName) .method("gravity_model_directory", &GravityModel::GravityModelDirectory) .method("equatorial_radius", &GravityModel::EquatorialRadius) .method("mass_constant", &GravityModel::MassConstant) .method("reference_mass_constant", &GravityModel::ReferenceMassConstant) .method("angular_velocity", &GravityModel::AngularVelocity) .method("flattening", &GravityModel::Flattening) .method("degree", &GravityModel::Degree) .method("order", &GravityModel::Order) .method("default_gravity_path", &GravityModel::DefaultGravityPath) .method("default_gravity_name", &GravityModel::DefaultGravityName); mod.add_type<MagneticCircle>("MagneticCircle") .method([](const MagneticCircle &m, real lon, real &Bx, real &By, real &Bz) { return m(lon, Bx, By, Bz); }) .method([](const MagneticCircle &m, real lon, real &Bx, real &By, real &Bz, real &Bxt, real &Byt, real &Bzt) { return m(lon, Bx, By, Bz, Bxt, Byt, Bzt); }) .method("field_geocentric", [](const MagneticCircle &m, real lon, real &BX, real &BY, real &BZ, real &BXt, real &BYt, real &BZt) { return m.FieldGeocentric(lon, BX, BY, BZ, BXt, BYt, BZt); }) .method("init", &MagneticCircle::Init) .method("equatorial_radius", &MagneticCircle::EquatorialRadius) .method("flattening", &MagneticCircle::Flattening) .method("latitude", &MagneticCircle::Latitude) .method("height", &MagneticCircle::Height) .method("time", &MagneticCircle::Time); mod.add_type<MagneticModel>("MagneticModel") .constructor<const std::string &, const std::string &, const Geocentric &, int, int>() .method([](const MagneticModel &m, real t, real lat, real lon, real h, real &Bx, real &By, real &Bz) { return m(t, lat, lon, h, Bx, By, Bz); }) .method([](const MagneticModel &m, real t, real lat, real lon, real h, real &Bx, real &By, real &Bz, real &Bxt, real &Byt, real &Bzt) { return m(t, lat, lon, h, Bx, By, Bz, Bxt, Byt, Bzt); }) .method("circle", &MagneticModel::Circle) .method("field_geocentric", &MagneticModel::FieldGeocentric) .method("field_components", [](const MagneticModel &m, real Bx, real By, real Bz, real &H, real &F, real &D, real &I) { return m.FieldComponents(Bx, By, Bz, H, F, D, I); }) .method("field_components", [](const MagneticModel &m, real Bx, real By, real Bz, real Bxt, real Byt, real Bzt, real &H, real &F, real &D, real &I, real &Ht, real &Ft, real &Dt, real &It) { return m.FieldComponents(Bx, By, Bz, Bxt, Byt, Bzt, H, F, D, I, Ht, Ft, Dt, It); }) .method("description", &MagneticModel::Description) .method("date_time", &MagneticModel::DateTime) .method("magnetic_file", &MagneticModel::MagneticFile) .method("magnetic_model_name", &MagneticModel::MagneticModelName) .method("magnetic_model_directory", &MagneticModel::MagneticModelDirectory) .method("min_height", &MagneticModel::MinHeight) .method("max_height", &MagneticModel::MaxHeight) .method("min_time", &MagneticModel::MinTime) .method("max_time", &MagneticModel::MaxTime) .method("equitorial_radius", &MagneticModel::EquatorialRadius) .method("flattening", &MagneticModel::Flattening) .method("degree", &MagneticModel::Degree) .method("order", &MagneticModel::Order) .method("default_magnetic_path", &MagneticModel::DefaultMagneticPath) .method("default_magnetic_name", &MagneticModel::DefaultMagneticName); }
50.746479
80
0.626515
sharanry
2e87a05e30cad53a553570694c70b6ca7cca34ec
4,745
cpp
C++
Island Simulation/src/assimp_model.cpp
GairePravesh/Graphics
638cc40f7d87e3c118dbe28b539eff5c7d319b1f
[ "MIT" ]
null
null
null
Island Simulation/src/assimp_model.cpp
GairePravesh/Graphics
638cc40f7d87e3c118dbe28b539eff5c7d319b1f
[ "MIT" ]
1
2019-12-29T17:06:34.000Z
2019-12-29T17:06:34.000Z
Island Simulation/src/assimp_model.cpp
GairePravesh/Graphics
638cc40f7d87e3c118dbe28b539eff5c7d319b1f
[ "MIT" ]
2
2019-10-05T18:11:45.000Z
2019-10-27T07:40:12.000Z
#include "assimp_model.h" CVertexBufferObject CAssimpModel::vboModelData; UINT CAssimpModel::uiVAO; vector<CTexture> CAssimpModel::tTextures; /*----------------------------------------------- Name: GetDirectoryPath Params: sFilePath - guess ^^ Result: Returns directory name only from filepath. /*---------------------------------------------*/ string GetDirectoryPath(string sFilePath) { // Get directory path string sDirectory = ""; RFOR(i, ESZ(sFilePath)-1)if(sFilePath[i] == '\\' || sFilePath[i] == '/') { sDirectory = sFilePath.substr(0, i+1); break; } return sDirectory; } CAssimpModel::CAssimpModel() { bLoaded = false; } /*----------------------------------------------- Name: LoadModelFromFile Params: sFilePath - guess ^^ Result: Loads model using Assimp library. /*---------------------------------------------*/ bool CAssimpModel::LoadModelFromFile(char* sFilePath) { if(vboModelData.GetBufferID() == 0) { vboModelData.CreateVBO(); tTextures.reserve(50); } Assimp::Importer importer; const aiScene* scene = importer.ReadFile( sFilePath, aiProcess_CalcTangentSpace | aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcess_SortByPType); if(!scene) { return false; } const int iVertexTotalSize = sizeof(aiVector3D)*2+sizeof(aiVector2D); int iTotalVertices = 0; FOR(i, scene->mNumMeshes) { aiMesh* mesh = scene->mMeshes[i]; int iMeshFaces = mesh->mNumFaces; iMaterialIndices.push_back(mesh->mMaterialIndex); int iSizeBefore = vboModelData.GetCurrentSize(); iMeshStartIndices.push_back(iSizeBefore/iVertexTotalSize); FOR(j, iMeshFaces) { const aiFace& face = mesh->mFaces[j]; FOR(k, 3) { aiVector3D pos = mesh->mVertices[face.mIndices[k]]; aiVector3D uv = mesh->mTextureCoords[0][face.mIndices[k]]; aiVector3D normal = mesh->HasNormals() ? mesh->mNormals[face.mIndices[k]] : aiVector3D(1.0f, 1.0f, 1.0f); vboModelData.AddData(&pos, sizeof(aiVector3D)); vboModelData.AddData(&uv, sizeof(aiVector2D)); vboModelData.AddData(&normal, sizeof(aiVector3D)); } } int iMeshVertices = mesh->mNumVertices; iTotalVertices += iMeshVertices; iMeshSizes.push_back((vboModelData.GetCurrentSize()-iSizeBefore)/iVertexTotalSize); } iNumMaterials = scene->mNumMaterials; vector<int> materialRemap(iNumMaterials); FOR(i, iNumMaterials) { const aiMaterial* material = scene->mMaterials[i]; int a = 5; int texIndex = 0; aiString path; // filename if(material->GetTexture(aiTextureType_DIFFUSE, texIndex, &path) == AI_SUCCESS) { string sDir = GetDirectoryPath(sFilePath); string sTextureName = path.data; string sFullPath = sDir+sTextureName; int iTexFound = -1; FOR(j, ESZ(tTextures))if(sFullPath == tTextures[j].GetPath()) { iTexFound = j; break; } if(iTexFound != -1)materialRemap[i] = iTexFound; else { CTexture tNew; tNew.LoadTexture2D(sFullPath, true); materialRemap[i] = ESZ(tTextures); tTextures.push_back(tNew); } } } FOR(i, ESZ(iMeshSizes)) { int iOldIndex = iMaterialIndices[i]; iMaterialIndices[i] = materialRemap[iOldIndex]; } return bLoaded = true; } /*----------------------------------------------- Name: FinalizeVBO Params: none Result: Uploads all loaded model data in one global models' VBO. /*---------------------------------------------*/ void CAssimpModel::FinalizeVBO() { glGenVertexArrays(1, &uiVAO); glBindVertexArray(uiVAO); vboModelData.BindVBO(); vboModelData.UploadDataToGPU(GL_STATIC_DRAW); // Vertex positions glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 2*sizeof(aiVector3D)+sizeof(aiVector2D), 0); // Texture coordinates glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 2*sizeof(aiVector3D)+sizeof(aiVector2D), (void*)sizeof(aiVector3D)); // Normal vectors glEnableVertexAttribArray(2); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 2*sizeof(aiVector3D)+sizeof(aiVector2D), (void*)(sizeof(aiVector3D)+sizeof(aiVector2D))); } /*----------------------------------------------- Name: BindModelsVAO Params: none Result: Binds VAO of models with their VBO. /*---------------------------------------------*/ void CAssimpModel::BindModelsVAO() { glBindVertexArray(uiVAO); } /*----------------------------------------------- Name: RenderModel Params: none Result: Guess what it does ^^. /*---------------------------------------------*/ void CAssimpModel::RenderModel() { if(!bLoaded)return; int iNumMeshes = ESZ(iMeshSizes); FOR(i, iNumMeshes) { int iMatIndex = iMaterialIndices[i]; tTextures[iMatIndex].BindTexture(); glDrawArrays(GL_TRIANGLES, iMeshStartIndices[i], iMeshSizes[i]); } }
24.209184
138
0.645522
GairePravesh
2e89af6e23e822c321ff6dde00197c26eb6568a0
476
cpp
C++
TC4/application/torpedo.cpp
rhuancaetano/openGL
796845b31f0d0b84ac28aabc1c9bf5365648831e
[ "MIT" ]
null
null
null
TC4/application/torpedo.cpp
rhuancaetano/openGL
796845b31f0d0b84ac28aabc1c9bf5365648831e
[ "MIT" ]
null
null
null
TC4/application/torpedo.cpp
rhuancaetano/openGL
796845b31f0d0b84ac28aabc1c9bf5365648831e
[ "MIT" ]
null
null
null
#include <GL/glut.h> #include "torpedo.h" void desenhaTorpedo(double radius){ glColor3f( 0.0, 0.0, 0.35); glBegin(GL_QUADS); glVertex2f( -radius*0.1, radius*0.3); glVertex2f( -radius*0.1, -radius*0.3); glVertex2f( radius*0.1, -radius*0.3); glVertex2f( radius*0.1, radius*0.3); glEnd(); } void Torpedo::drawTorpedo(){ glPushMatrix(); glTranslatef(this->x, this->y, 0.0); glRotatef(this->theta, 0.0, 0.0, 1.0); desenhaTorpedo(this->radius); glPopMatrix(); }
25.052632
40
0.663866
rhuancaetano
2e8a12096e876a21e1bff433bf4669d7fa9ff9c4
1,265
cc
C++
FlavoEngine/src/entityx/Entity.cc
Thirrash/FlavoEngine
fc3e867dc726d1a37ddd81bb6a1691833014703a
[ "MIT" ]
null
null
null
FlavoEngine/src/entityx/Entity.cc
Thirrash/FlavoEngine
fc3e867dc726d1a37ddd81bb6a1691833014703a
[ "MIT" ]
null
null
null
FlavoEngine/src/entityx/Entity.cc
Thirrash/FlavoEngine
fc3e867dc726d1a37ddd81bb6a1691833014703a
[ "MIT" ]
null
null
null
/* * Copyright (C) 2012 Alec Thomas <alec@swapoff.org> * All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. * * Author: Alec Thomas <alec@swapoff.org> */ #include <algorithm> #include "entityx/Entity.h" namespace Engine { const Entity::Id Entity::INVALID; BaseComponent::Family BaseComponent::family_counter_ = 0; void Entity::invalidate() { id_ = INVALID; manager_ = nullptr; } void Entity::destroy() { assert(valid()); manager_->destroy(id_); invalidate(); } std::bitset<Engine::MAX_COMPONENTS> Entity::component_mask() const { return manager_->component_mask(id_); } EntityManager::EntityManager(EventManager &event_manager) : event_manager_(event_manager) { } EntityManager::~EntityManager() { reset(); } void EntityManager::reset() { for (Entity entity : entities_for_debugging()) entity.destroy(); for (BasePool *pool : component_pools_) { if (pool) delete pool; } component_pools_.clear(); entity_component_mask_.clear(); entity_version_.clear(); free_list_.clear(); index_counter_ = 0; } EntityCreatedEvent::~EntityCreatedEvent() {} EntityDestroyedEvent::~EntityDestroyedEvent() {} } // namespace entityx
21.810345
91
0.72253
Thirrash
2e8ebf02c8d7a693bbe3571ba7d8934993fd90bc
2,174
cc
C++
components/download/content/internal/context_menu_download.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
components/download/content/internal/context_menu_download.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
components/download/content/internal/context_menu_download.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/download/content/public/context_menu_download.h" #include "components/download/public/common/download_url_parameters.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/context_menu_params.h" #include "content/public/browser/download_manager.h" #include "content/public/browser/download_request_utils.h" #include "content/public/browser/web_contents.h" #include "content/public/common/referrer.h" #include "net/traffic_annotation/network_traffic_annotation.h" namespace download { void CreateContextMenuDownload(content::WebContents* web_contents, const content::ContextMenuParams& params, const std::string& origin, bool is_link) { const GURL& url = is_link ? params.link_url : params.src_url; const GURL& referring_url = params.frame_url.is_empty() ? params.page_url : params.frame_url; content::DownloadManager* dlm = web_contents->GetBrowserContext()->GetDownloadManager(); std::unique_ptr<download::DownloadUrlParameters> dl_params( content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame( web_contents, url, TRAFFIC_ANNOTATION_WITHOUT_PROTO("Download via context menu"))); content::Referrer referrer = content::Referrer::SanitizeForRequest( url, content::Referrer(referring_url.GetAsReferrer(), params.referrer_policy)); dl_params->set_referrer(referrer.url); dl_params->set_referrer_policy( content::Referrer::ReferrerPolicyForUrlRequest(referrer.policy)); if (is_link) dl_params->set_referrer_encoding(params.frame_charset); if (!is_link) dl_params->set_prefer_cache(true); dl_params->set_prompt(false); dl_params->set_request_origin(origin); dl_params->set_suggested_name(params.suggested_filename); dl_params->set_download_source(download::DownloadSource::CONTEXT_MENU); dlm->DownloadUrl(std::move(dl_params)); } } // namespace download
43.48
80
0.74885
zealoussnow
2e97e6284fa93032a648662d58452b139ca0663d
2,090
cpp
C++
code/ip/fc_separation/full_coverage_gtest.cpp
d-krupke/turncost
2bbe1f1b31eddca5c6e686988e715be7d76c37a3
[ "MIT" ]
null
null
null
code/ip/fc_separation/full_coverage_gtest.cpp
d-krupke/turncost
2bbe1f1b31eddca5c6e686988e715be7d76c37a3
[ "MIT" ]
null
null
null
code/ip/fc_separation/full_coverage_gtest.cpp
d-krupke/turncost
2bbe1f1b31eddca5c6e686988e715be7d76c37a3
[ "MIT" ]
null
null
null
// // Created by Dominik Krupke, http://krupke.cc on 9/14/17. // #include <gtest/gtest.h> #include "../../problem_instance/grid_graph.h" #include "../general_cc_solver/ip_solver.h" #include "../../apx/approximation.h" #include "../../problem_instance/save_and_load.h" #include "../integer_programming.h" TEST(FcIp, BaseTest) { using namespace turncostcover; std::set<turncostcover::Coordinate> coords = {{0, 0}, {1, 0}, {2, 0}, {3, 0}, {4, 0}}; turncostcover::GridGraph graph{coords}; turncostcover::Costs costs; costs.turn_costs = 5; costs.dist_costs = 1; turncostcover::ip_formulation1::IpSolver solver{graph, costs}; auto apx_solution = apx::ApproximateTour(graph, costs); solver.AddSolution(apx_solution); solver.Solve(); ASSERT_EQ(std::lround(solver.GetObjectiveValue()), 8 * costs.dist_costs + 4 * costs.turn_costs); } TEST(FcIp, Large) { std::string file = "./assets/fc_500_dense_3.gg"; auto graph = turncostcover::LoadInstance(file); turncostcover::Costs costs; costs.turn_costs = 5; costs.dist_costs = 1; auto solution = turncostcover::ip::ComputeOptimalTour(graph, costs, 120); ASSERT_EQ(solution.GetNumComponents(), 1); ASSERT_EQ(solution.GetCoverageObjectiveValue(costs), 998); ASSERT_EQ(solution.GetCoverageObjectiveValue(costs), solution.GetLowerBound()); } TEST(FcIp, DeAssis) { std::string file = "/home/doms/Work/master_thesis/0998-10-91-149.in"; auto graph = turncostcover::LoadInstance(file); ASSERT_TRUE(graph.IsConnected()); turncostcover::Costs costs; costs.turn_costs = 1; costs.dist_costs = 0; auto solution = turncostcover::ip::ComputeOptimalTour(graph, costs, 120); ASSERT_EQ(solution.GetNumComponents(), 1); ASSERT_EQ(solution.GetCoverageObjectiveValue(costs), 30);//just for testing, doesn't match ASSERT_EQ(solution.GetCoverageObjectiveValue(costs), solution.GetLowerBound()); }
36.034483
98
0.655981
d-krupke
2e9b2a25a5037805bf27928d511bd9136237cf6c
1,104
cpp
C++
src/bubblesort.cpp
jtanisha-ee/data_s
864bdcbaac861e50d3262b0f651e809962fba2f6
[ "MIT" ]
null
null
null
src/bubblesort.cpp
jtanisha-ee/data_s
864bdcbaac861e50d3262b0f651e809962fba2f6
[ "MIT" ]
null
null
null
src/bubblesort.cpp
jtanisha-ee/data_s
864bdcbaac861e50d3262b0f651e809962fba2f6
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; #include <array> /* In the first pass, once the largest element is reached,it keeps on being swapped until it gets to the last position of the sequence. In the second pass, once the second largest element is reached, it keeps on being swapped until it gets to the second-to-last position of the sequence. In general,at the end of the ith pass,the right-most i elements of the sequence (that is, those at indices from n − 1 down to n − i) are in final position. number of passes made by bubble sort is limited to no. elements 'n' the ith pass can be limited to the first n-i+1 elements for eg. for a sequence of 5 elemts, the 3rd pass is ltd to the first 3 elems. time complexity O(n^2) */ void bubblesort(int *s[]) { int len = sizeof(*s)/sizeof(s[0]); for (int i = 0; i<len; i++) { for(int j =1; j<len-i;j++) { int prev = s[j-1]; int next = s[j]; if(prev > next) { int tmp = prev; prev = next; next = tmp; } } } } int main () { int s[] = {16,3,77,40,5,11}; bubblesort(&s); for (int i = 0;i<6;i++) { cout <<s[i]<<", "; } }
20.830189
82
0.655797
jtanisha-ee
2e9b63c03a4058027d44cbc03d6036f140b0986f
7,616
cpp
C++
cpp/mlp_cpu/mlp.cpp
julitopower/LearnMachineLearning
47526dd1fb52293c8199cc11207978144513bf5c
[ "BSD-2-Clause" ]
null
null
null
cpp/mlp_cpu/mlp.cpp
julitopower/LearnMachineLearning
47526dd1fb52293c8199cc11207978144513bf5c
[ "BSD-2-Clause" ]
null
null
null
cpp/mlp_cpu/mlp.cpp
julitopower/LearnMachineLearning
47526dd1fb52293c8199cc11207978144513bf5c
[ "BSD-2-Clause" ]
1
2020-07-19T11:31:10.000Z
2020-07-19T11:31:10.000Z
#include <iostream> #include <fstream> #include <vector> #include <map> #include <string> #include <chrono> #include <thread> #include "mlp.hpp" namespace { namespace mx = mxnet::cpp; namespace ch = std::chrono; // The names of the model and params files are // fixed const std::string MODEL_FILENAME {"model.json"}; const std::string PARAMS_FILENAME {"model-params.json"}; // Utility function to read an entire file into a string static void readall (const std::string& path, std::string *content) { std::ifstream ifs(path, std::ios::in | std::ios::binary); ifs.seekg(0, std::ios::end); size_t length = ifs.tellg(); content->resize(length); ifs.seekg(0, std::ios::beg); ifs.read(&content->at(0), content->size()); } } // This constructor initializes the network, and // leaves it ready for execution Mlp::Mlp(const MlpParams& params) : params_{params} { const std::size_t layers = params.hidden.size(); // Let's define the network first auto data = mx::Symbol::Variable("data"); auto label = mx::Symbol::Variable("labels"); // Reserve space for parameters weights_.resize(layers); biases_.resize(layers); outputs_.resize(layers); // Build each layer for (auto i = 0U; i < layers; i++) { const auto& istr = std::to_string(i); weights_[i] = mx::Symbol::Variable(std::string("w") + istr); biases_[i] = mx::Symbol::Variable(std::string("b") + istr); mx::Symbol fc = mx::FullyConnected(std::string("fc") + istr, i == 0 ? data : outputs_[i-1], weights_[i], biases_[i], params.hidden[i]); if (i == layers - 1) { outputs_[i] = fc; } else { outputs_[i] = mx::Activation(std::string("act") + istr, fc, mx::ActivationActType::kRelu); } } // Define the outpu network_ = mx::SoftmaxOutput("softmax", outputs_[layers - 1], label); //////////////////////////////////////////////////////////////////////////////// // Now that the network has been built, we need to configure it //////////////////////////////////////////////////////////////////////////////// auto ctx = mx::Context::cpu(); args_["data"] = mx::NDArray(mx::Shape(params.batch_size, params.dim), ctx); args_["labels"] = mx::NDArray(mx::Shape(params.batch_size), ctx); // Let MXNet infer shapes other parameters such as weights network_.InferArgsMap(ctx, &args_, args_); // Initialize all parameters with uniform distribution U(-0.01, 0.01) auto initializer = mx::Uniform(0.01); for (auto& arg : args_) { // arg.first is parameter name, and arg.second is the value initializer(arg.first, &arg.second); } // Create sgd optimizer opt_ = mx::OptimizerRegistry::Find("sgd"); opt_->SetParam("lr", params.learning_rate) ->SetParam("wd", params.weight_decay); // Create executor by binding parameters to the model exec_ = network_.SimpleBind(ctx, args_); } Mlp::Mlp(const std::string& dir) { // Load the params const std::string params_filepath = dir + "/" + PARAMS_FILENAME; args_ = mx::NDArray::LoadToMap(params_filepath); // Load the network const std::string model_filepath = dir + "/" + MODEL_FILENAME; network_ = mx::Symbol::Load(model_filepath); // Initialize the executor // Create executor by binding parameters to the model auto ctx = mx::Context::cpu(); exec_ = network_.SimpleBind(ctx, args_); } void Mlp::fit(const std::string& data_train_csv_path, const std::string& labels_train_csv_path, const std::string& data_test_path, const std::string& labels_test_path) { bool test = true; if (data_test_path == "" || labels_test_path == "") { test = false; } // Let's load the data auto train_iter = mx::MXDataIter("CSVIter") .SetParam("data_csv", data_train_csv_path) .SetParam("label_csv", labels_train_csv_path) .SetParam("data_shape", mx::Shape{params_.dim}) .SetParam("label_shape", mx::Shape{1}) .SetParam("batch_size", params_.batch_size) .CreateDataIter(); auto test_iter = mx::MXDataIter("CSVIter"); if (test) { test_iter.SetParam("data_csv", data_test_path) .SetParam("label_csv", labels_test_path) .SetParam("data_shape", mx::Shape{params_.dim}) .SetParam("label_shape", mx::Shape{1}) .SetParam("batch_size", params_.batch_size) .CreateDataIter(); } // There is a bug in MxNet prefetcher, sleeping // for a little while seems to avoid it std::this_thread::sleep_for(ch::milliseconds{100}); const auto arg_names = network_.ListArguments(); auto epochs = params_.epochs; auto tic = ch::system_clock::now(); while (epochs > 0) { train_iter.Reset(); while (train_iter.Next()) { auto data_batch = train_iter.GetDataBatch(); // Set data and label data_batch.data.CopyTo(&args_["data"]); data_batch.label.CopyTo(&args_["labels"]); args_["data"].WaitAll(); args_["labels"].WaitAll(); // Compute gradients exec_->Forward(true); exec_->Backward(); // Update parameters for (size_t i = 0; i < arg_names.size(); ++i) { if (arg_names[i] == "data" || arg_names[i] == "labels") continue; opt_->Update(i, exec_->arg_arrays[i], exec_->grad_arrays[i]); } } --epochs; if (!test) { continue; } mx::Accuracy acc; test_iter.Reset(); while (test_iter.Next()) { auto data_batch = test_iter.GetDataBatch(); data_batch.data.CopyTo(&args_["data"]); data_batch.label.CopyTo(&args_["labels"]); // Forward pass is enough as no gradient is needed when evaluating exec_->Forward(false); acc.Update(data_batch.label, exec_->outputs[0]); } std::cout << "Epoch: " << epochs << " " << acc.Get() << std::endl;; } auto toc = ch::system_clock::now(); std::cout << ch::duration_cast<ch::milliseconds>(toc - tic).count() << std::endl; }; std::vector<mx::NDArray> Mlp::predict(const std::string& filepath) { // Record start time for reporting purposes const auto tic = ch::system_clock::now(); // Infer feature dim from the arguments const std::uint32_t feature_dim = args_["data"].GetShape()[1]; // Let's load the data. By not defining labels, we are telling MxNet // there are no labels const mx_uint batch = 16; auto train_iter = mx::MXDataIter("CSVIter") .SetParam("data_csv", filepath) .SetParam("data_shape", mx::Shape{feature_dim}) .SetParam("batch_size", batch) .CreateDataIter(); train_iter.Reset(); // Iterate through the batches std::vector<mx::NDArray> results; const auto ctx = mx::Context::cpu(); while (train_iter.Next()) { // Get batch const auto& data_batch = train_iter.GetDataBatch(); // Set data and label data_batch.data.CopyTo(&args_["data"]); data_batch.label.CopyTo(&args_["labels"]); args_["data"].WaitAll(); args_["labels"].WaitAll(); // Compute gradients exec_->Forward(true); // Gather results mx::NDArray res{mx::Shape{exec_->outputs[0].GetShape()}, ctx}; exec_->outputs[0].CopyTo(&res); res.WaitAll(); results.push_back(res); } // Report latency and return const auto toc = ch::system_clock::now(); std::cout << ch::duration_cast<ch::milliseconds>(toc - tic).count() << std::endl; return results; } void Mlp::reset() {}; void Mlp::save_model(const std::string &dir) { // First save the model const std::string model_filepath = dir + "/" + MODEL_FILENAME; network_.Save(model_filepath); // Now we need to save the parameters const std::string params_filepath = dir + "/" + PARAMS_FILENAME; mx::NDArray::Save(params_filepath, args_); }
31.60166
96
0.637999
julitopower
2e9c8600bcf010fcc6cc796767a48da741634605
989
cpp
C++
ch04/u1339.cpp
brucegua/aoapcii
1d9bd8958a93e0424d20bcfb644ddc6f152e4963
[ "Apache-2.0" ]
null
null
null
ch04/u1339.cpp
brucegua/aoapcii
1d9bd8958a93e0424d20bcfb644ddc6f152e4963
[ "Apache-2.0" ]
null
null
null
ch04/u1339.cpp
brucegua/aoapcii
1d9bd8958a93e0424d20bcfb644ddc6f152e4963
[ "Apache-2.0" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <algorithm> #include <string.h> using namespace std; int main1339() { #ifdef LOCAL freopen("1339.in", "r", stdin); #endif // LOCAL char a[110], b[110]; // record the two strings int ca[26] = {0}; int cb[26] = {0}; // count of the characters in the strings bool can_map; // if the one string could map into another while (scanf("%s\n", a) != EOF) { scanf("%s\n", b); memset(ca, 0, sizeof(ca)); memset(cb, 0, sizeof(cb)); for (char* t = a; *t != '\0'; t++) { ca[*t-'A']++; } for (char* t = b; *t != '\0'; t++) { cb[*t-'A']++; } sort(ca, ca+26); sort(cb, cb+26); can_map = true; for (int i = 0; i < 26; i++) { if (ca[i] != cb[i]) { can_map = false; } } if (can_map) printf("YES\n"); else printf("NO\n"); } return 0; }
22.477273
64
0.443883
brucegua
2e9f261035ffb5c2f33e15ee01ab9e4c2633f055
500
cc
C++
src/developer/debug/zxdb/symbols/module_symbols.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
210
2019-02-05T12:45:09.000Z
2022-03-28T07:59:06.000Z
src/developer/debug/zxdb/symbols/module_symbols.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
56
2021-06-03T03:16:25.000Z
2022-03-20T01:07:44.000Z
src/developer/debug/zxdb/symbols/module_symbols.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
73
2019-03-06T18:55:23.000Z
2022-03-26T12:04:51.000Z
// Copyright 2018 The Fuchsia 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 "src/developer/debug/zxdb/symbols/module_symbols.h" namespace zxdb { ModuleSymbols::ModuleSymbols() : weak_factory_(this) {} ModuleSymbols::~ModuleSymbols() { if (deletion_cb_) deletion_cb_(this); } fxl::WeakPtr<ModuleSymbols> ModuleSymbols::GetWeakPtr() { return weak_factory_.GetWeakPtr(); } } // namespace zxdb
26.315789
94
0.748
allansrc
2ea740c58f2e94ecc087bfb77d6d2c9bdb5c5d9e
6,287
cpp
C++
SerialPrograms/Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterOverride.cpp
pifopi/Arduino-Source
e926d9f9154a27a33d976240ae956c9460e64cf9
[ "MIT" ]
9
2021-03-06T20:37:22.000Z
2022-03-09T02:34:47.000Z
SerialPrograms/Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterOverride.cpp
pifopi/Arduino-Source
e926d9f9154a27a33d976240ae956c9460e64cf9
[ "MIT" ]
44
2021-05-31T21:33:14.000Z
2022-02-25T17:40:50.000Z
SerialPrograms/Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterOverride.cpp
pifopi/Arduino-Source
e926d9f9154a27a33d976240ae956c9460e64cf9
[ "MIT" ]
16
2021-03-21T16:00:21.000Z
2022-03-26T08:02:11.000Z
/* Encounter Filter * * From: https://github.com/PokemonAutomation/Arduino-Source * */ #include <QtGlobal> #include "Common/Cpp/Exception.h" #include "Common/Qt/QtJsonTools.h" #include "Common/Qt/NoWheelComboBox.h" #include "Pokemon/Resources/Pokemon_PokeballNames.h" #include "Pokemon/Resources/Pokemon_PokemonSlugs.h" #include "Pokemon/Options/Pokemon_BallSelectWidget.h" #include "Pokemon/Options/Pokemon_NameSelectWidget.h" #include "PokemonSwSh_EncounterFilterEnums.h" #include "PokemonSwSh_EncounterFilterOverride.h" namespace PokemonAutomation{ namespace NintendoSwitch{ namespace PokemonSwSh{ EncounterFilterOverride::EncounterFilterOverride(bool rare_stars) : m_rare_stars(rare_stars) // , shininess(rare_stars ? ShinyFilter::SQUARE_ONLY : ShinyFilter::STAR_ONLY) {} void EncounterFilterOverride::load_json(const QJsonValue& json){ QJsonObject obj = json.toObject(); { QString value; if (json_get_string(value, obj, "Action")){ auto iter = EncounterAction_MAP.find(value); if (iter != EncounterAction_MAP.end()){ action = iter->second; } } } { QString value; json_get_string(value, obj, "Ball"); pokeball_slug = value.toUtf8().data(); } { QString value; json_get_string(value, obj, "Species"); pokemon_slug = value.toStdString(); } { QString value; if (json_get_string(value, obj, "ShinyFilter")){ auto iter = ShinyFilter_MAP.find(value); if (iter != ShinyFilter_MAP.end()){ shininess = iter->second; } } } } QJsonValue EncounterFilterOverride::to_json() const{ QJsonObject obj; obj.insert("Action", EncounterAction_NAMES[(size_t)action]); obj.insert("Ball", QString::fromStdString(pokeball_slug)); obj.insert("Species", QString::fromStdString(pokemon_slug)); obj.insert("ShinyFilter", ShinyFilter_NAMES[(size_t)shininess]); return obj; } std::unique_ptr<EditableTableRow> EncounterFilterOverride::clone() const{ return std::unique_ptr<EditableTableRow>(new EncounterFilterOverride(*this)); } std::vector<QWidget*> EncounterFilterOverride::make_widgets(QWidget& parent){ std::vector<QWidget*> widgets; BallSelectWidget* ball_select = make_ball_select(parent); widgets.emplace_back(make_action_box(parent, *ball_select)); widgets.emplace_back(ball_select); widgets.emplace_back(make_species_select(parent)); widgets.emplace_back(make_shiny_box(parent)); return widgets; } QWidget* EncounterFilterOverride::make_action_box(QWidget& parent, BallSelectWidget& ball_select){ QComboBox* box = new NoWheelComboBox(&parent); for (const QString& action : EncounterAction_NAMES){ box->addItem(action); } box->setCurrentIndex((int)action); switch (action){ case EncounterAction::StopProgram: case EncounterAction::RunAway: ball_select.setEnabled(false); break; case EncounterAction::ThrowBalls: case EncounterAction::ThrowBallsAndSave: ball_select.setEnabled(true); break; } box->connect( box, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged), box, [&](int index){ if (index < 0){ index = 0; } action = (EncounterAction)index; switch ((EncounterAction)index){ case EncounterAction::StopProgram: case EncounterAction::RunAway: ball_select.setEnabled(false); break; case EncounterAction::ThrowBalls: case EncounterAction::ThrowBallsAndSave: ball_select.setEnabled(true); break; } } ); return box; } BallSelectWidget* EncounterFilterOverride::make_ball_select(QWidget& parent){ using namespace Pokemon; BallSelectWidget* box = new BallSelectWidget(parent, POKEBALL_SLUGS(), pokeball_slug); box->connect( box, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged), box, [&, box](int index){ pokeball_slug = box->slug(); } ); return box; } QWidget* EncounterFilterOverride::make_species_select(QWidget& parent){ using namespace Pokemon; NameSelectWidget* box = new NameSelectWidget(parent, NATIONAL_DEX_SLUGS(), pokemon_slug); box->connect( box, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged), box, [&, box](int index){ pokemon_slug = box->slug(); } ); return box; } QWidget* EncounterFilterOverride::make_shiny_box(QWidget& parent){ QComboBox* box = new NoWheelComboBox(&parent); if (m_rare_stars){ box->addItem(ShinyFilter_NAMES[(int)ShinyFilter::NOT_SHINY]); box->addItem(ShinyFilter_NAMES[(int)ShinyFilter::SQUARE_ONLY]); }else{ box->addItem(ShinyFilter_NAMES[(int)ShinyFilter::ANYTHING]); box->addItem(ShinyFilter_NAMES[(int)ShinyFilter::NOT_SHINY]); box->addItem(ShinyFilter_NAMES[(int)ShinyFilter::ANY_SHINY]); box->addItem(ShinyFilter_NAMES[(int)ShinyFilter::STAR_ONLY]); box->addItem(ShinyFilter_NAMES[(int)ShinyFilter::SQUARE_ONLY]); box->addItem(ShinyFilter_NAMES[(int)ShinyFilter::NOTHING]); } ShinyFilter current = shininess; for (int c = 0; c < box->count(); c++){ if (box->itemText(c) == ShinyFilter_NAMES[(int)current]){ box->setCurrentIndex(c); break; } } box->connect( box, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged), box, [&, box](int index){ if (index < 0){ return; } QString text = box->itemText(index); auto iter = ShinyFilter_MAP.find(text); if (iter == ShinyFilter_MAP.end()){ PA_THROW_StringException("Invalid option: " + text); } shininess = iter->second; } ); return box; } } } }
34.168478
99
0.627803
pifopi
2ea765d3f49e91c0220d188cdf92d6192629e78c
9,293
cpp
C++
Source/System/Math/Algebra/Vector2.cpp
arian153/Engine-5
34f85433bc0a74a7ebe7da350d3f3698de77226e
[ "MIT" ]
2
2020-01-09T07:48:24.000Z
2020-01-09T07:48:26.000Z
Source/System/Math/Algebra/Vector2.cpp
arian153/Engine-5
34f85433bc0a74a7ebe7da350d3f3698de77226e
[ "MIT" ]
null
null
null
Source/System/Math/Algebra/Vector2.cpp
arian153/Engine-5
34f85433bc0a74a7ebe7da350d3f3698de77226e
[ "MIT" ]
null
null
null
#include "Vector2.hpp" #include "..//Utility/Utility.hpp" #include <ostream> #include "Matrix22.hpp" #include "Vector3.hpp" #include "Vector4.hpp" #include "../Utility/VectorDef.hpp" namespace Engine5 { Vector2::Vector2(Real x, Real y) : x(x), y(y) { } Vector2::Vector2(Real arr[2]) : x(arr[0]), y(arr[1]) { } Vector2::Vector2(const Vector3& rhs) : x(rhs.x), y(rhs.y) { } Vector2::Vector2(const Vector4& rhs) : x(rhs.x), y(rhs.y) { } Vector2::Vector2(const Vector2& rhs) : x(rhs.x), y(rhs.y) { } Vector2::~Vector2() { } void Vector2::Set(Real _x, Real _y) { x = _x; y = _y; } void Vector2::SetZero() { x = 0.0f; y = 0.0f; } void Vector2::SetInverse() { x = 1.0f / x; y = 1.0f / y; } void Vector2::SetNegate() { x = -x; y = -y; } void Vector2::SetNormalize() { Real length = sqrtf(x * x + y * y); if (length > 0.f) { (*this) *= (1.f / length); } } void Vector2::SetHalf() { this->x *= 0.5f; this->y *= 0.5f; } void Vector2::SetClean() { if (Math::IsZero(x)) x = 0.0f; if (Math::IsZero(y)) y = 0.0f; } void Vector2::SetProjection(const Vector2& a, const Vector2& b) { Real multiplier = (a.DotProduct(b)) / (b.DotProduct(b)); this->x = b.x * multiplier; this->y = b.y * multiplier; } Real Vector2::Length() const { return sqrtf(x * x + y * y); } Real Vector2::LengthSquared() const { return (x * x + y * y); } Real Vector2::DistanceTo(const Vector2& rhs) const { Real _x = rhs.x - this->x; Real _y = rhs.y - this->y; return sqrtf(_x * _x + _y * _y); } Real Vector2::DistanceSquaredTo(const Vector2& rhs) const { Real _x = rhs.x - this->x; Real _y = rhs.y - this->y; return (_x * _x + _y * _y); } Vector2 Vector2::ProjectionTo(const Vector2& rhs) const { Vector2 result = rhs; Real multiplier = ((*this).DotProduct(rhs)) / (rhs.DotProduct(rhs)); result *= multiplier; return result; } Vector2 Vector2::ProjectionFrom(const Vector2& rhs) const { Vector2 result = *this; Real multiplier = (rhs.DotProduct(*this)) / ((*this).DotProduct(*this)); result *= multiplier; return result; } Vector2 Vector2::Unit() const { Vector2 result = *this; result.SetNormalize(); return result; } Vector2 Vector2::Half() const { Vector2 result = *this; result.SetHalf(); return result; } Vector2 Vector2::Inverse() const { return Vector2( Math::IsZero(x) ? 0.0f : 1.0f / this->x, Math::IsZero(y) ? 0.0f : 1.0f / this->y); } Real Vector2::DotProduct(const Vector2& rhs) const { return (x * rhs.x + y * rhs.y); } Real Vector2::CrossProduct(const Vector2& rhs) const { return (x * rhs.y - y * rhs.x); } Vector2 Vector2::CrossProduct(const Real& rhs) const { return Vector2(rhs * y, -rhs * x); } Matrix22 Vector2::OuterProduct(const Vector2& rhs) const { return Matrix22( this->x * rhs.x, this->x * rhs.y, this->y * rhs.x, this->y * rhs.y); } Vector2 Vector2::HadamardProduct(const Vector2& rhs) const { return Vector2(x * rhs.x, y * rhs.y); } bool Vector2::IsValid() const { return Math::IsValid(x) && Math::IsValid(y); } bool Vector2::IsZero() const { return Math::IsZero(x) && Math::IsZero(y); } bool Vector2::IsEqual(const Vector2& rhs) const { return Math::IsEqual(x, rhs.x) && Math::IsEqual(y, rhs.y); } bool Vector2::IsNotEqual(const Vector2& rhs) const { return Math::IsNotEqual(x, rhs.x) || Math::IsNotEqual(y, rhs.y); } Real Vector2::GrepVec1(size_t flag0) const { return (*this)[SafeFlag(flag0)]; } Vector2 Vector2::GrepVec2(size_t flag0, size_t flag1) const { return Vector2((*this)[SafeFlag(flag0)], (*this)[SafeFlag(flag1)]); } Vector3 Vector2::GrepVec3(size_t flag0, size_t flag1, size_t flag2) const { return Vector3((*this)[SafeFlag(flag0)], (*this)[SafeFlag(flag1)], (*this)[SafeFlag(flag2)]); } Vector4 Vector2::GrepVec4(size_t flag0, size_t flag1, size_t flag2, size_t flag3) const { return Vector4((*this)[SafeFlag(flag0)], (*this)[SafeFlag(flag1)], (*this)[SafeFlag(flag2)], (*this)[SafeFlag(flag3)]); } size_t Vector2::SafeFlag(size_t given) const { return given > Math::Vector::Y ? Math::Vector::Y : given; } bool Vector2::operator==(const Vector2& rhs) const { return Math::IsEqual(x, rhs.x) && Math::IsEqual(y, rhs.y); } bool Vector2::operator!=(const Vector2& rhs) const { return Math::IsNotEqual(x, rhs.x) || Math::IsNotEqual(y, rhs.y); } Vector2 Vector2::operator-() const { return Vector2(-x, -y); } Vector2& Vector2::operator=(const Vector2& rhs) { if (this != &rhs) { x = rhs.x; y = rhs.y; } return *this; } Vector2& Vector2::operator=(const Vector3& rhs) { x = rhs.x; y = rhs.y; return *this; } Vector2& Vector2::operator=(const Vector4& rhs) { x = rhs.x; y = rhs.y; return *this; } Vector2& Vector2::operator=(Real rhs) { x = rhs; y = rhs; return *this; } Vector2& Vector2::operator+=(const Vector2& rhs) { x += rhs.x; y += rhs.y; return *this; } Vector2& Vector2::operator+=(Real real) { x += real; y += real; return *this; } Vector2& Vector2::operator-=(const Vector2& rhs) { x -= rhs.x; y -= rhs.y; return *this; } Vector2& Vector2::operator-=(Real real) { x -= real; y -= real; return *this; } Vector2& Vector2::operator*=(Real real) { x *= real; y *= real; return *this; } Vector2& Vector2::operator/=(Real real) { x /= real; y /= real; return *this; } Vector2 Vector2::operator+(const Vector2& rhs) const { return Vector2(x + rhs.x, y + rhs.y); } Vector2 Vector2::operator+(Real real) const { return Vector2(x + real, y + real); } Vector2 Vector2::operator-(const Vector2& rhs) const { return Vector2(x - rhs.x, y - rhs.y); } Vector2 Vector2::operator-(Real real) const { return Vector2(x - real, y - real); } Vector2 Vector2::operator*(Real real) const { return Vector2(x * real, y * real); } Vector2 Vector2::operator/(Real real) const { return Vector2(x / real, y / real); } Vector2& Vector2::operator++() { ++x; ++y; return *this; } Vector2 Vector2::operator++(int) { Vector2 result(*this); ++(*this); return result; } Vector2& Vector2::operator--() { --x; --y; return *this; } Vector2 Vector2::operator--(int) { Vector2 result(*this); --(*this); return result; } Real Vector2::operator[](size_t i) const { return (&x)[i]; } Real& Vector2::operator[](size_t i) { return (&x)[i]; } Real DotProduct(const Vector2& vec1, const Vector2& vec2) { return vec1.DotProduct(vec2); } Real CrossProduct(const Vector2& vec1, const Vector2& vec2) { return (vec1.x * vec2.y - vec1.y * vec2.x); } Vector2 CrossProduct(Real vec1, const Vector2& vec2) { return Vector2(-vec1 * vec2.y, vec1 * vec2.x); } Vector2 CrossProduct(const Vector2& vec1, Real vec2) { return Vector2(vec2 * vec1.y, -vec2 * vec1.x); } Matrix22 OuterProduct(const Vector2& vec1, const Vector2& vec2) { return vec1.OuterProduct(vec2); } Vector2 HadamardProduct(const Vector2& vec1, const Vector2& vec2) { return vec1.HadamardProduct(vec2); } Vector2 Projection(const Vector2& vec1, const Vector2& vec2) { return vec1.ProjectionTo(vec2); } Vector2 LinearInterpolation(const Vector2& start, const Vector2& end, Real t) { Vector2 result; result.x = (1.0f - t) * start.x + t * end.x; result.y = (1.0f - t) * start.y + t * end.y; return result; } std::ostream& operator<<(std::ostream& os, const Vector2& rhs) { os << "[" << rhs.x << ", " << rhs.y << "]"; return os; } Vector2 operator*(Real real, const Vector2& vector) { return Vector2(vector.x * real, vector.y * real); } }
21.216895
127
0.512213
arian153
2eabd19caedf684dddacc7e02a50132630e3b801
828
cpp
C++
daily_challenge/February_LeetCoding_Challenge_2021/longestWordInDictionaryThroughDeleting.cpp
archit-1997/LeetCode
7c0f74da0836d3b0855f09bae8960f81a384f3f3
[ "MIT" ]
1
2021-01-27T16:37:36.000Z
2021-01-27T16:37:36.000Z
daily_challenge/February_LeetCoding_Challenge_2021/longestWordInDictionaryThroughDeleting.cpp
archit-1997/LeetCode
7c0f74da0836d3b0855f09bae8960f81a384f3f3
[ "MIT" ]
null
null
null
daily_challenge/February_LeetCoding_Challenge_2021/longestWordInDictionaryThroughDeleting.cpp
archit-1997/LeetCode
7c0f74da0836d3b0855f09bae8960f81a384f3f3
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; bool compare(string &a, string &b) { if (a.size() == b.size()) return a < b; return a.size() > b.size(); } class Solution { public: bool find(string &a, string &b, int i, int j) { // if we have found the string if (i == a.size()) return true; // if we have reached the end if (j == b.size()) return false; if (a[i] == b[j]) return find(a, b, i + 1, j + 1); else return find(a, b, i, j + 1); } string findLongestWord(string s, vector<string> &dictionary) { sort(dictionary.begin(), dictionary.end(), compare); for (int i = 0; i < dictionary.size(); i++) { // if this word is a subsequence of s if (find(dictionary[i], s, 0, 0)) { return dictionary[i]; } } return ""; } };
21.789474
64
0.539855
archit-1997
2eaf65447a7e7a2f0cf95263fbca227bef909f12
1,563
cpp
C++
Project/Source/Panels/PanelAudioMixer.cpp
TBD-org/TBD-Engine
8b45d5a2a92e26bd0ec034047b8188e871fab0f9
[ "MIT" ]
7
2021-04-26T21:32:12.000Z
2022-02-14T13:48:53.000Z
Project/Source/Panels/PanelAudioMixer.cpp
TBD-org/RealBugEngine
0131fde0abc2d86137500acd6f63ed8f0fc2835f
[ "MIT" ]
66
2021-04-24T10:08:07.000Z
2021-10-05T16:52:56.000Z
Project/Source/Panels/PanelAudioMixer.cpp
TBD-org/TBD-Engine
8b45d5a2a92e26bd0ec034047b8188e871fab0f9
[ "MIT" ]
1
2021-07-13T21:26:13.000Z
2021-07-13T21:26:13.000Z
#include "PanelAudioMixer.h" #include "Application.h" #include "Modules/ModuleEditor.h" #include "Modules/ModuleScene.h" #include "Modules/ModuleAudio.h" #include "Utils/Pool.h" #include "Scene.h" #include "imgui.h" #include "IconsForkAwesome.h" #include <string> #include "Utils/Logging.h" #include "Utils/Leaks.h" PanelAudioMixer::PanelAudioMixer() : Panel("Audio Mixer", false) {} void PanelAudioMixer::Update() { ImGui::SetNextWindowSize(ImVec2(400.0f, 400.0f), ImGuiCond_FirstUseEver); std::string windowName = std::string(ICON_FK_MUSIC " ") + name; if (ImGui::Begin(windowName.c_str(), &enabled, ImGuiWindowFlags_AlwaysAutoResize)) { if (App->scene->scene->audioListenerComponents.Count() == 0) { ImGui::End(); return; } float gainMainChannel = App->audio->GetGainMainChannel(); float gainMusicChannel = App->audio->GetGainMusicChannel(); float gainSFXChannel = App->audio->GetGainSFXChannel(); ImGui::TextColored(App->editor->titleColor, "Main Volume"); if (ImGui::SliderFloat("##main_volume", &gainMainChannel, 0.f, 1.f)) { App->audio->SetGainMainChannel(gainMainChannel); } ImGui::Separator(); ImGui::NewLine(); ImGui::TextColored(App->editor->titleColor, "Music Volume"); if (ImGui::SliderFloat("##music_volume", &gainMusicChannel, 0.f, 1.f)) { App->audio->SetGainMusicChannel(gainMusicChannel); } ImGui::TextColored(App->editor->titleColor, "SFX Volume"); if (ImGui::SliderFloat("##sfx_volume", &gainSFXChannel, 0.f, 1.f)) { App->audio->SetGainSFXChannel(gainSFXChannel); } } ImGui::End(); }
31.26
85
0.715291
TBD-org
2eb0fd271ab45086b7e6849c69a1408d86b223c0
14,728
cc
C++
src/modular/lib/modular_config/modular_config_xdr_unittest.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
5
2022-01-10T20:22:17.000Z
2022-01-21T20:14:17.000Z
src/modular/lib/modular_config/modular_config_xdr_unittest.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
1
2022-03-01T01:12:04.000Z
2022-03-01T01:17:26.000Z
src/modular/lib/modular_config/modular_config_xdr_unittest.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
null
null
null
// Copyright 2019 The Fuchsia 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 "src/modular/lib/modular_config/modular_config_xdr.h" #include <fuchsia/modular/internal/cpp/fidl.h> #include <fuchsia/modular/session/cpp/fidl.h> #include <fuchsia/sys/cpp/fidl.h> #include <algorithm> #include <cctype> #include <gtest/gtest.h> #include "src/lib/files/file.h" #include "src/modular/lib/modular_config/modular_config.h" #include "src/modular/lib/modular_config/modular_config_constants.h" namespace modular { // Tests that default JSON values are set correctly when BasemgrConfig contains no values. TEST(ModularConfigXdr, BasemgrWriteDefaultValues) { static constexpr auto kExpectedJson = R"({ "enable_cobalt": true, "use_session_shell_for_story_shell_factory": false, "session_shells": [ { "url": "fuchsia-pkg://fuchsia.com/dev_session_shell#meta/dev_session_shell.cmx", "args": [] } ], "story_shell_url": "fuchsia-pkg://fuchsia.com/dev_story_shell#meta/dev_story_shell.cmx" })"; rapidjson::Document expected_json_doc; expected_json_doc.Parse(kExpectedJson); ASSERT_FALSE(expected_json_doc.HasParseError()); // Serialize an empty BasemgrConfig to JSON. rapidjson::Document write_config_json_doc; fuchsia::modular::session::BasemgrConfig write_config; XdrWrite(&write_config_json_doc, &write_config, XdrBasemgrConfig); EXPECT_EQ(expected_json_doc, write_config_json_doc); } // Tests that default values are set correctly for BasemgrConfig when reading an empty config. TEST(ModularConfigXdr, BasemgrReadDefaultValues) { // Deserialize an empty JSON document into BasemgrConfig. rapidjson::Document read_json_doc; read_json_doc.SetObject(); fuchsia::modular::session::BasemgrConfig read_config; EXPECT_TRUE(XdrRead(&read_json_doc, &read_config, XdrBasemgrConfig)); EXPECT_TRUE(read_config.enable_cobalt()); EXPECT_FALSE(read_config.use_session_shell_for_story_shell_factory()); ASSERT_EQ(1u, read_config.session_shell_map().size()); EXPECT_EQ(modular_config::kDefaultSessionShellUrl, read_config.session_shell_map().at(0).name()); EXPECT_EQ(modular_config::kDefaultSessionShellUrl, read_config.session_shell_map().at(0).config().app_config().url()); EXPECT_EQ(modular_config::kDefaultStoryShellUrl, read_config.story_shell().app_config().url()); } // Tests that values are set correctly for BasemgrConfig when reading JSON. // All of the fields are set to a non-default value. TEST(ModularConfigXdr, BasemgrReadValues) { static constexpr auto kTestSessionShellUrl = "fuchsia-pkg://fuchsia.com/test_session_shell#meta/test_session_shell.cmx"; static constexpr auto kTestStoryShellUrl = "fuchsia-pkg://fuchsia.com/test_story_shell#meta/test_story_shell.cmx"; static constexpr auto kJson = R"({ "enable_cobalt": false, "use_session_shell_for_story_shell_factory": true, "session_shells": [ { "url": "fuchsia-pkg://fuchsia.com/test_session_shell#meta/test_session_shell.cmx" } ], "story_shell_url": "fuchsia-pkg://fuchsia.com/test_story_shell#meta/test_story_shell.cmx" })"; rapidjson::Document json_doc; json_doc.Parse(kJson); ASSERT_FALSE(json_doc.HasParseError()); // Deserialize it from the JSON string to a BasemgrConfig. fuchsia::modular::session::BasemgrConfig read_config; EXPECT_TRUE(XdrRead(&json_doc, &read_config, XdrBasemgrConfig)); EXPECT_FALSE(read_config.enable_cobalt()); EXPECT_TRUE(read_config.use_session_shell_for_story_shell_factory()); ASSERT_EQ(1u, read_config.session_shell_map().size()); const auto& session_shell = read_config.session_shell_map().at(0); ASSERT_TRUE(session_shell.has_config()); ASSERT_TRUE(session_shell.config().has_app_config()); EXPECT_EQ(kTestSessionShellUrl, session_shell.config().app_config().url()); EXPECT_EQ(0u, session_shell.config().app_config().args().size()); ASSERT_TRUE(read_config.has_story_shell()); ASSERT_TRUE(read_config.story_shell().has_app_config()); ASSERT_EQ(kTestStoryShellUrl, read_config.story_shell().app_config().url()); EXPECT_EQ(0u, read_config.story_shell().app_config().args().size()); } // Tests that default JSON values are set correctly when SessionmgrConfig contains no values. TEST(ModularConfigXdr, SessionmgrWriteDefaultValues) { static constexpr auto kExpectedJson = R"({ "enable_cobalt": true, "startup_agents": null, "session_agents": null, "component_args": null, "agent_service_index": null, "restart_session_on_agent_crash": null, "disable_agent_restart_on_crash": false })"; rapidjson::Document expected_json_doc; expected_json_doc.Parse(kExpectedJson); ASSERT_FALSE(expected_json_doc.HasParseError()); // Serialize an empty SessionmgrConfig to JSON. rapidjson::Document write_config_json_doc; fuchsia::modular::session::SessionmgrConfig write_config; XdrWrite(&write_config_json_doc, &write_config, XdrSessionmgrConfig); EXPECT_EQ(expected_json_doc, write_config_json_doc); } // Tests that default values are set correctly for SessionmgrConfig when reading an empty config. TEST(ModularConfigXdr, SessionmgrReadDefaultValues) { // Deserialize an empty JSON document into SessionmgrConfig. rapidjson::Document read_json_doc; read_json_doc.SetObject(); fuchsia::modular::session::SessionmgrConfig read_config; EXPECT_TRUE(XdrRead(&read_json_doc, &read_config, XdrSessionmgrConfig)); EXPECT_TRUE(read_config.enable_cobalt()); EXPECT_EQ(0u, read_config.startup_agents().size()); EXPECT_EQ(0u, read_config.session_agents().size()); EXPECT_EQ(0u, read_config.restart_session_on_agent_crash().size()); EXPECT_FALSE(read_config.disable_agent_restart_on_crash()); } // Tests that values are set correctly for SessionmgrConfig when reading JSON and // that values in the JSON document are equal to those in SessionmgrConfig when writing JSON. // All of the fields are set to a non-default value. TEST(ModularConfigXdr, SessionmgrReadWriteValues) { static constexpr auto kStartupAgentUrl = "fuchsia-pkg://fuchsia.com/startup_agent#meta/startup_agent.cmx"; static constexpr auto kSessionAgentUrl = "fuchsia-pkg://fuchsia.com/session_agent#meta/session_agent.cmx"; static constexpr auto kAgentServiceName = "fuchsia.modular.ModularConfigXdrTest"; static constexpr auto kAgentUrl = "fuchsia-pkg://example.com/test_agent#meta/test_agent.cmx"; static constexpr auto kAgentComponentArg = "--test_agent_component_arg"; static constexpr auto kExpectedJson = R"( { "enable_cobalt": false, "startup_agents": [ "fuchsia-pkg://fuchsia.com/startup_agent#meta/startup_agent.cmx" ], "session_agents": [ "fuchsia-pkg://fuchsia.com/session_agent#meta/session_agent.cmx" ], "component_args": [ { "uri": "fuchsia-pkg://example.com/test_agent#meta/test_agent.cmx", "args": ["--test_agent_component_arg"] } ], "agent_service_index": [ { "service_name": "fuchsia.modular.ModularConfigXdrTest", "agent_url": "fuchsia-pkg://example.com/test_agent#meta/test_agent.cmx" } ], "restart_session_on_agent_crash": [ "fuchsia-pkg://fuchsia.com/session_agent#meta/session_agent.cmx" ], "disable_agent_restart_on_crash": true })"; rapidjson::Document expected_json_doc; expected_json_doc.Parse(kExpectedJson); ASSERT_FALSE(expected_json_doc.HasParseError()); // Create a SessionmgrConfig with non-default values. fuchsia::modular::session::SessionmgrConfig write_config; write_config.set_enable_cobalt(false); write_config.mutable_startup_agents()->push_back(kStartupAgentUrl); write_config.mutable_session_agents()->push_back(kSessionAgentUrl); write_config.set_disable_agent_restart_on_crash(true); fuchsia::modular::session::AppConfig component_arg; component_arg.set_url(kAgentUrl); component_arg.mutable_args()->push_back(kAgentComponentArg); write_config.mutable_component_args()->push_back(std::move(component_arg)); fuchsia::modular::session::AgentServiceIndexEntry agent_entry; agent_entry.set_service_name(kAgentServiceName); agent_entry.set_agent_url(kAgentUrl); write_config.mutable_agent_service_index()->push_back(std::move(agent_entry)); write_config.mutable_restart_session_on_agent_crash()->push_back(kSessionAgentUrl); // Serialize the config to JSON. rapidjson::Document write_config_json_doc; XdrWrite(&write_config_json_doc, &write_config, XdrSessionmgrConfig); EXPECT_EQ(expected_json_doc, write_config_json_doc); // Deserialize it from the expected JSON to a SessionmgrConfig. fuchsia::modular::session::SessionmgrConfig read_config; EXPECT_TRUE(XdrRead(&expected_json_doc, &read_config, XdrSessionmgrConfig)); EXPECT_FALSE(read_config.enable_cobalt()); EXPECT_EQ(1u, read_config.startup_agents().size()); EXPECT_EQ(1u, read_config.session_agents().size()); EXPECT_EQ(kStartupAgentUrl, read_config.startup_agents().at(0)); EXPECT_EQ(kSessionAgentUrl, read_config.session_agents().at(0)); EXPECT_EQ(kAgentUrl, read_config.component_args().at(0).url()); ASSERT_EQ(1u, read_config.component_args().at(0).args().size()); EXPECT_EQ(kAgentComponentArg, read_config.component_args().at(0).args().at(0)); EXPECT_EQ(kAgentServiceName, read_config.agent_service_index().at(0).service_name()); EXPECT_EQ(kAgentUrl, read_config.agent_service_index().at(0).agent_url()); EXPECT_EQ(kSessionAgentUrl, read_config.restart_session_on_agent_crash().at(0)); EXPECT_TRUE(read_config.disable_agent_restart_on_crash()); } // Tests that default values are set correctly for ModularConfig when reading an empty config. TEST(ModularConfigXdr, ModularReadDefaultValues) { // Deserialize an empty JSON document into ModularConfig. rapidjson::Document read_json_doc; read_json_doc.SetObject(); fuchsia::modular::session::ModularConfig read_config; EXPECT_TRUE(XdrRead(&read_json_doc, &read_config, XdrModularConfig)); EXPECT_TRUE(read_config.has_basemgr_config()); EXPECT_TRUE(read_config.has_sessionmgr_config()); } // Tests that default JSON values are set correctly when ModularConfig contains no values. TEST(ModularConfigXdr, ModularWriteDefaultValues) { static constexpr auto kExpectedJson = R"({ "basemgr": { "enable_cobalt": true, "use_session_shell_for_story_shell_factory": false, "session_shells": [ { "url": "fuchsia-pkg://fuchsia.com/dev_session_shell#meta/dev_session_shell.cmx", "args": [] } ], "story_shell_url": "fuchsia-pkg://fuchsia.com/dev_story_shell#meta/dev_story_shell.cmx" }, "sessionmgr": { "enable_cobalt": true, "startup_agents": [], "session_agents": [], "component_args": [], "agent_service_index": [], "restart_session_on_agent_crash": [], "disable_agent_restart_on_crash": false } })"; rapidjson::Document expected_json_doc; expected_json_doc.Parse(kExpectedJson); ASSERT_FALSE(expected_json_doc.HasParseError()); // Serialize an empty ModularConfig to JSON. rapidjson::Document write_config_json_doc; fuchsia::modular::session::ModularConfig write_config; XdrWrite(&write_config_json_doc, &write_config, XdrModularConfig); EXPECT_EQ(expected_json_doc, write_config_json_doc); } // Tests that values are set correctly for ModularConfig when reading JSON and // that values in the JSON document are equal to those in ModularConfig when writing JSON. TEST(ModularConfigXdr, ModularReadWriteValues) { static constexpr auto kExpectedJson = R"( { "basemgr": { "enable_cobalt": false, "use_session_shell_for_story_shell_factory": false, "session_shells": [ { "url": "fuchsia-pkg://fuchsia.com/dev_session_shell#meta/dev_session_shell.cmx", "args": [] } ], "story_shell_url": "fuchsia-pkg://fuchsia.com/dev_story_shell#meta/dev_story_shell.cmx" }, "sessionmgr": { "enable_cobalt": false, "startup_agents": null, "session_agents": null, "component_args": null, "agent_service_index": null, "restart_session_on_agent_crash": null, "disable_agent_restart_on_crash": false } })"; rapidjson::Document expected_json_doc; expected_json_doc.Parse(kExpectedJson); ASSERT_FALSE(expected_json_doc.HasParseError()); // Create a BasemgrConfig with field set to a non-default value. fuchsia::modular::session::BasemgrConfig basemgr_config; basemgr_config.set_enable_cobalt(false); // Create a SessionmgrConfig with field set to a non-default value. fuchsia::modular::session::SessionmgrConfig sessionmgr_config; sessionmgr_config.set_enable_cobalt(false); // Create a ModularConfig from the BasemgrConfig and SessionmgrConfig fuchsia::modular::session::ModularConfig write_config; write_config.set_basemgr_config(std::move(basemgr_config)); write_config.set_sessionmgr_config(std::move(sessionmgr_config)); // Serialize the config to JSON. rapidjson::Document write_config_json_doc; XdrWrite(&write_config_json_doc, &write_config, XdrModularConfig); EXPECT_EQ(expected_json_doc, write_config_json_doc); // Deserialize it from the expected JSON to a ModularConfig. fuchsia::modular::session::ModularConfig read_config; EXPECT_TRUE(XdrRead(&expected_json_doc, &read_config, XdrModularConfig)); EXPECT_TRUE(read_config.has_basemgr_config()); EXPECT_FALSE(read_config.basemgr_config().enable_cobalt()); EXPECT_TRUE(read_config.has_sessionmgr_config()); EXPECT_FALSE(read_config.sessionmgr_config().enable_cobalt()); } // Tests that XdrModularConfig returns default values when reading an empty object. TEST(ModularConfigXdr, ModularConfigReadDefaultValues) { // Deserialize an empty JSON document into ModularConfig. rapidjson::Document read_json_doc; read_json_doc.SetObject(); fuchsia::modular::session::ModularConfig config; EXPECT_TRUE(XdrRead(&read_json_doc, &config, XdrModularConfig)); ASSERT_TRUE(config.has_basemgr_config()); EXPECT_TRUE(config.basemgr_config().enable_cobalt()); ASSERT_EQ(1u, config.basemgr_config().session_shell_map().size()); EXPECT_EQ(modular_config::kDefaultSessionShellUrl, config.basemgr_config().session_shell_map().at(0).name()); ASSERT_TRUE(config.has_sessionmgr_config()); EXPECT_TRUE(config.sessionmgr_config().enable_cobalt()); } } // namespace modular
41.60452
99
0.751494
allansrc
2eb35dba0a0e6768130e3de707821abe5197840a
2,305
cpp
C++
interleaving-string/main.cpp
rickytan/LeetCode
7df9a47928552babaf5d2abf1d153bd92d44be09
[ "MIT" ]
1
2015-04-04T18:32:31.000Z
2015-04-04T18:32:31.000Z
interleaving-string/main.cpp
rickytan/LeetCode
7df9a47928552babaf5d2abf1d153bd92d44be09
[ "MIT" ]
null
null
null
interleaving-string/main.cpp
rickytan/LeetCode
7df9a47928552babaf5d2abf1d153bd92d44be09
[ "MIT" ]
null
null
null
#include <string> #include <iostream> #include <map> #include <stack> #include <vector> using namespace std; class Solution { public: bool isInterleave(string s1, string s2, string s3) { if(s3.length() != s1.length() + s2.length()) return false; vector<vector<bool> > table(s1.length() + 1, vector<bool>(s2.length() + 1, false)); for (int i=0; i<= s1.length(); ++i) { for (int j=0; j<=s2.length(); ++j) { if (i == 0 && j == 0) { table[i][j] = true; } else if (i == 0) { table[i][j] = table[i][j-1] && s2[j-1] == s3[i+j-1]; } else if (j == 0) { table[i][j] = table[i-1][j] && s1[i-1] == s3[i+j-1]; } else { table[i][j] = table[i][j-1] && s2[j-1] == s3[i+j-1] || table[i-1][j] && s1[i-1] == s3[i+j-1]; } } } return table[s1.length()][s2.length()]; } bool isInter(const char *s1, const char *s2, const char *s3) { int p1 = 0, p2 = 0; for (int i=0;s3[i];++i) { if (s1[p1] == s3[i] && s2[p2] == s3[i]) { if (isInter(s1+p1+1, s2+p2, s3+i+1)) { return true; } if (isInter(s1+p1, s2+p2+1, s3+i+1)) { return true; } return false; } else if (s1[p1] == s3[i]) { p1++; } else if (s2[p2] == s3[i]) { p2++; } else return false; } return (!s1[p1] && !s2[p2]); } }; int main() { Solution s; cout << s.isInterleave("bbbbbabbbbabaababaaaabbababbaaabbabbaaabaaaaababbbababbbbbabbbbababbabaabababbbaabababababbbaaababaa", "babaaaabbababbbabbbbaabaabbaabbbbaabaaabaababaaaabaaabbaaabaaaabaabaabbbbbbbbbbbabaaabbababbabbabaab", "babbbabbbaaabbababbbbababaabbabaabaaabbbbabbbaaabbbaaaaabbbbaabbaaabababbaaaaaabababbababaababbababbbababbbbaaaabaabbabbaaaaabbabbaaaabbbaabaaabaababaababbaaabbbbbabbbbaabbabaabbbbabaaabbababbabbabbab"); return 0; }
32.464789
439
0.465944
rickytan
2eb515a61c830996042031068e594e344273b81c
22,273
cc
C++
pdb/src/storageManager/headers/PDBStorageManagerFrontendTemplate.cc
SeraphL/plinycompute
7788bc2b01d83f4ff579c13441d0ba90734b54a2
[ "Apache-2.0" ]
3
2019-05-04T05:17:30.000Z
2020-02-21T05:01:59.000Z
pdb/src/storageManager/headers/PDBStorageManagerFrontendTemplate.cc
dcbdan/plinycompute
a6f1c8ac8f75c09615f08752c82179f33cfc6d89
[ "Apache-2.0" ]
3
2020-02-20T19:50:46.000Z
2020-06-25T14:31:51.000Z
pdb/src/storageManager/headers/PDBStorageManagerFrontendTemplate.cc
dcbdan/plinycompute
a6f1c8ac8f75c09615f08752c82179f33cfc6d89
[ "Apache-2.0" ]
5
2019-02-19T23:17:24.000Z
2020-08-03T01:08:04.000Z
// // Created by dimitrije on 2/17/19. // #ifndef PDB_PDBSTORAGEMANAGERFRONTENDTEMPLATE_H #define PDB_PDBSTORAGEMANAGERFRONTENDTEMPLATE_H #include <PDBStorageManagerFrontend.h> #include <HeapRequestHandler.h> #include <StoDispatchData.h> #include <PDBBufferManagerInterface.h> #include <PDBBufferManagerFrontEnd.h> #include <StoStoreOnPageRequest.h> #include <boost/filesystem/path.hpp> #include <boost/filesystem/operations.hpp> #include <fstream> #include <HeapRequest.h> #include <StoGetNextPageRequest.h> #include <StoGetNextPageResult.h> #include "CatalogServer.h" #include <StoGetPageRequest.h> #include <StoGetPageResult.h> #include <StoGetSetPagesResult.h> #include <StoRemovePageSetRequest.h> #include <StoMaterializePageResult.h> #include <StoFeedPageRequest.h> template <class T> std::pair<bool, std::string> pdb::PDBStorageManagerFrontend::handleGetPageRequest(const pdb::Handle<pdb::StoGetPageRequest> &request, std::shared_ptr<T> &sendUsingMe) { /// 1. Check if we have a page // create the set identifier auto set = make_shared<pdb::PDBSet>(request->databaseName, request->setName); // find the if this page is valid if not try to find another one... auto res = getValidPage(set, request->page); // set the result bool hasPage = res.first; uint64_t pageNum = res.second; /// 2. If we don't have it or it is not in a valid state it send back a NACK if(!hasPage) { // make an allocation block const pdb::UseTemporaryAllocationBlock tempBlock{1024}; // create an allocation block to hold the response pdb::Handle<pdb::StoGetPageResult> response = pdb::makeObject<pdb::StoGetPageResult>(0, 0, false); // sends result to requester string error; sendUsingMe->sendObject(response, error); // This is an issue we simply return false only a manager can serve pages return make_pair(false, error); } /// 3. Ok we have it, grab the page and compress it. // grab the page auto page = this->getFunctionalityPtr<PDBBufferManagerInterface>()->getPage(set, pageNum); // grab the vector auto* pageRecord = (pdb::Record<pdb::Vector<pdb::Handle<pdb::Object>>> *) (page->getBytes()); // grab an anonymous page to store the compressed stuff //TODO this kind of sucks since the max compressed size can be larger than the actual size auto maxCompressedSize = std::min<size_t>(snappy::MaxCompressedLength(pageRecord->numBytes()), 128 * 1024 * 1024); auto compressedPage = getFunctionalityPtr<PDBBufferManagerInterface>()->getPage(maxCompressedSize); // compress the record size_t compressedSize; snappy::RawCompress((char*) pageRecord, pageRecord->numBytes(), (char*)compressedPage->getBytes(), &compressedSize); /// 4. Send the compressed page // make an allocation block const pdb::UseTemporaryAllocationBlock tempBlock{1024}; // create an allocation block to hold the response pdb::Handle<pdb::StoGetPageResult> response = pdb::makeObject<pdb::StoGetPageResult>(compressedSize, pageNum, true); // sends result to requester string error; sendUsingMe->sendObject(response, error); // now, send the bytes if (!sendUsingMe->sendBytes(compressedPage->getBytes(), compressedSize, error)) { this->logger->error(error); this->logger->error("sending page bytes: not able to send data to client.\n"); // we are done here return make_pair(false, string(error)); } // we are done! return make_pair(true, string("")); } template <class Communicator, class Requests> std::pair<bool, std::string> pdb::PDBStorageManagerFrontend::handleDispatchedData(pdb::Handle<pdb::StoDispatchData> request, std::shared_ptr<Communicator> sendUsingMe) { /// 1. Get the page from the distributed storage // the error std::string error; // grab the buffer manager auto bufferManager = std::dynamic_pointer_cast<pdb::PDBBufferManagerFrontEnd>(getFunctionalityPtr<pdb::PDBBufferManagerInterface>()); // figure out how large the compressed payload is size_t numBytes = sendUsingMe->getSizeOfNextObject(); // grab a page to write this auto page = bufferManager->getPage(numBytes); // grab the bytes auto success = sendUsingMe->receiveBytes(page->getBytes(), error); // did we fail if(!success) { // create an allocation block to hold the response const UseTemporaryAllocationBlock tempBlock{1024}; Handle<SimpleRequestResult> response = makeObject<SimpleRequestResult>(false, error); // sends result to requester sendUsingMe->sendObject(response, error); return std::make_pair(false, error); } // figure out the size so we can increment it // check the uncompressed size size_t uncompressedSize = 0; snappy::GetUncompressedLength((char*) page->getBytes(), numBytes, &uncompressedSize); /// 2. Figure out the page we want to put this thing onto uint64_t pageNum; { // lock the stuff that keeps track of the last page unique_lock<std::mutex> lck(pageMutex); // make the set auto set = std::make_shared<PDBSet>(request->databaseName, request->setName); // get the next page pageNum = getNextFreePage(set); // indicate that we are writing to this page startWritingToPage(set, pageNum); // increment the set size incrementSetSize(set, uncompressedSize); } /// 3. Initiate the storing on the backend PDBCommunicatorPtr communicatorToBackend = make_shared<PDBCommunicator>(); if (!communicatorToBackend->connectToLocalServer(logger, getConfiguration()->ipcFile, error)) { return std::make_pair(false, error); } // create an allocation block to hold the response const UseTemporaryAllocationBlock tempBlock{1024}; Handle<StoStoreOnPageRequest> response = makeObject<StoStoreOnPageRequest>(request->databaseName, request->setName, pageNum, request->compressedSize); // send the thing to the backend if (!communicatorToBackend->sendObject(response, error)) { // make the set auto set = std::make_shared<PDBSet>(request->databaseName, request->setName); // set the indicators and send a NACK to the client since we failed handleDispatchFailure(set, pageNum, uncompressedSize, sendUsingMe); // finish return std::make_pair(false, error); } /// 4. Forward the page to the backend // forward the page if(!bufferManager->forwardPage(page, communicatorToBackend, error)) { // we could not forward the page auto set = std::make_shared<PDBSet>(request->databaseName, request->setName); // set the indicators and send a NACK to the client since we failed handleDispatchFailure(set, pageNum, uncompressedSize, sendUsingMe); // finish return std::make_pair(false, error); } /// 5. Wait for the backend to finish the stuff success = Requests::template waitHeapRequest<SimpleRequestResult, bool>(logger, communicatorToBackend, false, [&](Handle<SimpleRequestResult> result) { // check the result if (result != nullptr && result->getRes().first) { return true; } // since we failed just invalidate the set auto set = std::make_shared<PDBSet>(request->databaseName, request->setName); { // lock the stuff unique_lock<std::mutex> lck(pageMutex); // finish writing to the set endWritingToPage(set, pageNum); // return the page to the free list freeSetPage(set, pageNum); // decrement the size of the set decrementSetSize(set, uncompressedSize); } // log the error error = "Error response from distributed-storage: " + result->getRes().second; logger->error("Error response from distributed-storage: " + result->getRes().second); return false; }); // finish writing to the set endWritingToPage(std::make_shared<PDBSet>(request->databaseName, request->setName), pageNum); /// 6. Send the response that we are done // create an allocation block to hold the response Handle<SimpleRequestResult> simpleResponse = makeObject<SimpleRequestResult>(success, error); // sends result to requester success = sendUsingMe->sendObject(simpleResponse, error) && success; // finish return std::make_pair(success, error); } template<class Communicator, class Requests> std::pair<bool, std::string> pdb::PDBStorageManagerFrontend::handleGetSetPages(pdb::Handle<pdb::StoGetSetPagesRequest> request, shared_ptr<Communicator> sendUsingMe) { // the error std::string error; bool success; // check if the set exists if(!getFunctionalityPtr<pdb::PDBCatalogClient>()->setExists(request->databaseName, request->setName)) { // set the error error = "The set the pages were requested does not exist!"; success = false; // make an allocation block const UseTemporaryAllocationBlock tempBlock{1024}; // make a NACK response pdb::Handle<pdb::StoGetSetPagesResult> result = pdb::makeObject<pdb::StoGetSetPagesResult>(); // sends result to requester sendUsingMe->sendObject(result, error); // return the result return std::make_pair(success, error); } // make the set identifier auto set = std::make_shared<PDBSet>(request->databaseName, request->setName); std::vector<uint64_t> pages; { // lock the stuff unique_lock<std::mutex> lck(pageMutex); // try to find the page auto it = this->pageStats.find(set); if(it != this->pageStats.end()) { // reserve the pages pages.reserve(it->second.lastPage); // do we even have this page uint64_t currPage = 0; while(currPage <= it->second.lastPage) { // check if the page is valid if(pageExists(set, currPage) && !isPageBeingWrittenTo(set, currPage) && !isPageFree(set, currPage)) { pages.emplace_back(currPage); } // if not try to go to the next one currPage++; } } } // make an allocation block const UseTemporaryAllocationBlock tempBlock{pages.size() * sizeof(uint64_t) + 1024}; // make the result pdb::Handle<pdb::StoGetSetPagesResult> result = pdb::makeObject<pdb::StoGetSetPagesResult>(pages, true); // sends result to requester success = sendUsingMe->sendObject(result, error); // return the result return std::make_pair(success, error); } template<class Communicator, class Requests> std::pair<bool, std::string> pdb::PDBStorageManagerFrontend::handleMaterializeSet(pdb::Handle<pdb::StoMaterializePageSetRequest> request, shared_ptr<Communicator> sendUsingMe) { /// TODO this has to be more robust, right now this is just here to do the job! // success indicators bool success = true; std::string error; /// 1. Check if the set exists // check if the set exists if(!getFunctionalityPtr<pdb::PDBCatalogClient>()->setExists(request->databaseName, request->setName)) { // set the error error = "The set requested to materialize results does not exist!"; success = true; } /// 2. send an ACK or NACK depending on whether the set exists // make an allocation block const UseTemporaryAllocationBlock tempBlock{1024}; // create an allocation block to hold the response Handle<SimpleRequestResult> simpleResponse = makeObject<SimpleRequestResult>(success, error); // sends result to requester sendUsingMe->sendObject(simpleResponse, error); // if we failed end here if(!success) { // return the result return std::make_pair(success, error); } /// 3. Send pages over the wire to the backend // grab the buffer manager auto bufferManager = std::dynamic_pointer_cast<pdb::PDBBufferManagerFrontEnd>(getFunctionalityPtr<pdb::PDBBufferManagerInterface>()); // make the set auto set = std::make_shared<PDBSet>(request->databaseName, request->setName); // this is going to count the total size of the pages uint64_t totalSize = 0; // start forwarding the pages bool hasNext = true; while (hasNext) { uint64_t pageNum; { // lock to do the bookkeeping unique_lock<std::mutex> lck(pageMutex); // get the next page pageNum = getNextFreePage(set); // indicate that we are writing to this page startWritingToPage(set, pageNum); } // get the page auto page = bufferManager->getPage(set, pageNum); // forward the page to the backend success = bufferManager->forwardPage(page, sendUsingMe, error); // did we fail? if(!success) { // lock to do the bookkeeping unique_lock<std::mutex> lck(pageMutex); // finish writing to the set endWritingToPage(set, pageNum); // return the page to the free list freeSetPage(set, pageNum); // free the lock lck.unlock(); // do we need to update the set size if(totalSize != 0) { // broadcast the set size change so far this->getFunctionalityPtr<PDBCatalogClient>()->incrementSetSize(set->getDBName(), set->getSetName(), totalSize, error); } // finish here since this is not recoverable on the backend return std::make_pair(success, "Error occurred while forwarding the page to the backend.\n" + error); } // the size we want to freeze this thing to size_t freezeSize = 0; // wait for the storage finish result success = RequestFactory::waitHeapRequest<StoMaterializePageResult, bool>(logger, sendUsingMe, false, [&](Handle<StoMaterializePageResult> result) { // check the result if (result != nullptr && result->success) { // set the freeze size freezeSize = result->materializeSize; // set the has next hasNext = result->hasNext; // finish return result->success; } // set the error error = "Backend materializing the page failed!"; // we failed return so return false; }); // did we fail? if(!success) { // lock to do the bookkeeping unique_lock<std::mutex> lck(pageMutex); // finish writing to the set endWritingToPage(set, pageNum); // return the page to the free list freeSetPage(set, pageNum); // free the lock lck.unlock(); // do we need to update the set size if(totalSize != 0) { // broadcast the set size change so far this->getFunctionalityPtr<PDBCatalogClient>()->incrementSetSize(set->getDBName(), set->getSetName(), totalSize, error); } // finish return std::make_pair(success, error); } // ok we did not freeze the page page->freezeSize(freezeSize); // end writing to a page { // lock to do the bookkeeping unique_lock<std::mutex> lck(pageMutex); // finish writing to the set endWritingToPage(set, pageNum); // decrement the size of the set incrementSetSize(set, freezeSize); } // increment the set size totalSize += freezeSize; } /// 4. Update the set size // broadcast the set size change so far success = this->getFunctionalityPtr<PDBCatalogClient>()->incrementSetSize(set->getDBName(), set->getSetName(), totalSize, error); /// 5. Finish this // we succeeded return std::make_pair(success, error); } template <class Communicator> std::pair<bool, std::string> pdb::PDBStorageManagerFrontend::handleRemovePageSet(pdb::Handle<pdb::StoRemovePageSetRequest> &request, std::shared_ptr<Communicator> &sendUsingMe) { // the error std::string error; /// 1. Connect to the backend // connect to the backend std::shared_ptr<Communicator> communicatorToBackend = make_shared<Communicator>(); if (!communicatorToBackend->connectToLocalServer(logger, getConfiguration()->ipcFile, error)) { return std::make_pair(false, error); } /// 2. Forward the request // sends result to requester bool success = communicatorToBackend->sendObject(request, error, 1024); // did we succeed in send the stuff if(!success) { return std::make_pair(false, error); } /// 4. Wait for response // wait for the storage finish result success = RequestFactory::waitHeapRequest<SimpleRequestResult, bool>(logger, communicatorToBackend, false, [&](Handle<SimpleRequestResult> result) { // check the result if (result != nullptr && result->getRes().first) { // finish return true; } // set the error error = result->getRes().second; // we failed return so return false; }); /// 5. Send a response // create an allocation block to hold the response const UseTemporaryAllocationBlock tempBlock{1024}; // create the response pdb::Handle<pdb::SimpleRequestResult> simpleResponse = pdb::makeObject<pdb::SimpleRequestResult>(success, error); // sends result to requester sendUsingMe->sendObject(simpleResponse, error); // return return std::make_pair(success, error); } template <class Communicator> std::pair<bool, std::string> pdb::PDBStorageManagerFrontend::handleClearSetRequest(pdb::Handle<pdb::StoClearSetRequest> &request, std::shared_ptr<Communicator> &sendUsingMe) { std::string error; // lock the structures std::unique_lock<std::mutex> lck{pageMutex}; // make the set auto set = std::make_shared<PDBSet>(request->databaseName, request->setName); // remove the stats pageStats.erase(set); // make sure we have no pages that we are writing to auto it = pagesBeingWrittenTo.find(set); if(it != pagesBeingWrittenTo.end() && !it->second.empty()) { // set the error error = "There are currently pages being written to, failed to remove the set."; // create an allocation block to hold the response const UseTemporaryAllocationBlock tempBlock{1024}; Handle<SimpleRequestResult> response = makeObject<SimpleRequestResult>(false, error); // sends result to requester sendUsingMe->sendObject(response, error); // return return std::make_pair(false, error); } // remove the pages being written to pagesBeingWrittenTo.erase(set); // remove the skipped pages freeSkippedPages.erase(set); // get the buffer manger auto bufferManager = std::dynamic_pointer_cast<pdb::PDBBufferManagerFrontEnd>(getFunctionalityPtr<pdb::PDBBufferManagerInterface>()); // clear the set from the buffer manager bufferManager->clearSet(set); // create an allocation block to hold the response const UseTemporaryAllocationBlock tempBlock{1024}; Handle<SimpleRequestResult> response = makeObject<SimpleRequestResult>(true, error); // sends result to requester sendUsingMe->sendObject(response, error); // return return std::make_pair(true, error); } template <class Communicator> std::pair<bool, std::string> pdb::PDBStorageManagerFrontend::handleStartFeedingPageSetRequest(pdb::Handle<pdb::StoStartFeedingPageSetRequest> &request, std::shared_ptr<Communicator> &sendUsingMe) { bool success = true; std::string error; /// 1. Connect to the backend // try to connect to the backend int32_t retries = 0; PDBCommunicatorPtr communicatorToBackend = make_shared<PDBCommunicator>(); while (!communicatorToBackend->connectToLocalServer(logger, getConfiguration()->ipcFile, error)) { // if we are out of retries finish if(retries >= getConfiguration()->maxRetries) { success = false; break; } // we used up a retry retries++; } // if we could not connect to the backend we failed if(!success) { // return return std::make_pair(success, error); } /// 2. Forward the request to the backend success = communicatorToBackend->sendObject(request, error, 1024); // if we succeeded in sending the object, we expect an ack if(success) { // create an allocation block to hold the response const UseTemporaryAllocationBlock localBlock{1024}; // get the next object auto result = communicatorToBackend->template getNextObject<pdb::SimpleRequestResult>(success, error); // set the success indicator... success = result != nullptr && result->res; } /// 3. Send a response to the other node about the status // create an allocation block to hold the response const UseTemporaryAllocationBlock tempBlock{1024}; // create the response for the other node pdb::Handle<pdb::SimpleRequestResult> simpleResponse = pdb::makeObject<pdb::SimpleRequestResult>(success, error); // sends result to requester success = sendUsingMe->sendObject(simpleResponse, error); /// 4. If everything went well, start getting the pages from the other node // get the buffer manager auto bufferManager = std::dynamic_pointer_cast<pdb::PDBBufferManagerFrontEnd>(getFunctionalityPtr<pdb::PDBBufferManagerInterface>()); // if everything went well start receiving the pages while(success) { /// 4.1 Get the signal that there are more pages // create an allocation block to hold the response const UseTemporaryAllocationBlock localBlock{1024}; // get the next object auto hasPage = sendUsingMe->template getNextObject<pdb::StoFeedPageRequest>(success, error); // if we failed break if(!success) { break; } /// 4.2 Forward that signal so that the backend knows that there are more pages // forward the feed page request success = communicatorToBackend->sendObject<pdb::StoFeedPageRequest>(hasPage, error, 1024); // if we failed break if(!success) { break; } // do we have a page, if we don't finish if(!hasPage->hasNextPage){ break; } /// 4.3 Get the page from the other node // get the page of the size we need auto page = bufferManager->getPage(hasPage->pageSize); // grab the bytes success = sendUsingMe->receiveBytes(page->getBytes(), error); // if we failed finish if(!success) { break; } /// 4.4 Forward the page to the backend // forward the page to the backend success = bufferManager->forwardPage(page, communicatorToBackend, error); } // return return std::make_pair(success, error); } #endif //PDB_PDBSTORAGEMANAGERFRONTENDTEMPLATE_H
30.510959
178
0.690387
SeraphL
e481bbb449f85fb3a4e5d64d1e86a9035bc0c598
537
cpp
C++
third_party/boost/libs/gil/toolbox/test/is_similar.cpp
Jackarain/tinyrpc
07060e3466776aa992df8574ded6c1616a1a31af
[ "BSL-1.0" ]
32
2019-02-27T06:57:07.000Z
2021-08-29T10:56:19.000Z
third_party/boost/libs/gil/toolbox/test/is_similar.cpp
avplayer/cxxrpc
7049b4079fac78b3828e68f787d04d699ce52f6d
[ "BSL-1.0" ]
1
2019-04-04T18:00:00.000Z
2019-04-04T18:00:00.000Z
third_party/boost/libs/gil/toolbox/test/is_similar.cpp
avplayer/cxxrpc
7049b4079fac78b3828e68f787d04d699ce52f6d
[ "BSL-1.0" ]
5
2019-08-20T13:45:04.000Z
2022-03-01T18:23:49.000Z
// // Copyright 2013 Christian Henning // // 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 // #include <boost/gil.hpp> #include <boost/gil/extension/toolbox/metafunctions/is_similar.hpp> #include <boost/test/unit_test.hpp> using namespace boost; using namespace gil; BOOST_AUTO_TEST_SUITE( toolbox_tests ) BOOST_AUTO_TEST_CASE( is_similar_test ) { // TODO: fill the test } BOOST_AUTO_TEST_SUITE_END()
22.375
68
0.735568
Jackarain
e487f3b200f80540bf1d3f7c13fe1cea9a296a27
25,748
cpp
C++
Libraries/RobsJuceModules/rosic/legacy/HighOrderEqualizer.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
34
2017-04-19T18:26:02.000Z
2022-02-15T17:47:26.000Z
Libraries/RobsJuceModules/rosic/legacy/HighOrderEqualizer.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
307
2017-05-04T21:45:01.000Z
2022-02-03T00:59:01.000Z
Libraries/RobsJuceModules/rosic/legacy/HighOrderEqualizer.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
4
2017-09-05T17:04:31.000Z
2021-12-15T21:24:28.000Z
#include "HighOrderEqualizer.h" //---------------------------------------------------------------------------- // construction/destruction: HighOrderEqualizer::HighOrderEqualizer() { // init member variables: sampleRate = 44100.0; stereoMode = STEREO_LINKED; bypassAll = false; int s, c, k; // indices for eq-stage, channel, and frequency-bin double freq, gain, q; int mode, order; // set up the lowpass- and highpass-filters: for(c=0; c<numChannels; c++) { setLpfOrder(0, c); setLpfCutoff(20000.0, c); setHpfOrder(0, c); setHpfCutoff(20.0, c); } // set up the equalizer-chains: for(s=0; s<numEqStages; s++) { gain = 1.0; q = 1.0; order = 2; switch(s) { case 0: { freq = 125.0; mode = HighOrderEqualizer::PEAK; //gain = 12.0; } break; case 1: { freq = 250.0; mode = HighOrderEqualizer::PEAK; } break; case 2: { freq = 1000.0; mode = HighOrderEqualizer::PEAK; } break; case 3: { freq = 4000.0; mode = HighOrderEqualizer::PEAK; } break; case 4: { freq = 8000.0; mode = HighOrderEqualizer::HIGH_SHELV; } break; } // end of switch(s) for(c=0; c<numChannels; c++) { setEqMode(mode, s, c); setEqOrder(order, s, c); setEqFreq(freq, s, c); setEqGain(gain, s, c); setEqQ(q, s, c); } } // set up the global volume factors: vol[0] = 1.0; vol[1] = 1.0; // init the arrays for the magnitude response plot: double fMin = 15.625; double fMax = 32000.0; double f; // current frequency; for(k=0; k<numBins; k++) { // calculate current frequency: f = mapLinearToExponential(k, 0, numBins-1, fMin, fMax); // calculate some dependent quantities and store them into their arrays: freqs[k] = f; floatFrequencies[k] = (float) f; omegas[k] = 2*PI*f/sampleRate; cosOmegas[k] = cos(omegas[k]); cos2Omegas[k] = cos(2*omegas[k]); // init the individual magnitude-arrays with 0.0 dB: for(c=0; c<numChannels; c++) { hpfResponses[c][k] = 0.0; lpfResponses[c][k] = 0.0; floatMagnitudes[c][k] = 0.0f; for(s=0; s<numEqStages; s++) eqResponses[s][c][k] = 0.0; } } } HighOrderEqualizer::~HighOrderEqualizer() { } //---------------------------------------------------------------------------- // parameter settings: void HighOrderEqualizer::setSampleRate(double newSampleRate) { intA c, s, k; // for indexing the eq-stage, channel and bin AudioModule::setSampleRate(newSampleRate); // our member "sampleRate" is up // to date now // tell the embedded IirDesigner-object the new sample-rate: designer.setSampleRate(sampleRate); // re-calculate coefficients for all the embedded BiquadCascade-objects: for(c=0; c<numChannels; c++) { updateHpfCoeffs(c); for(s=0; s<numEqStages; s++) updateEqCoeffs(s,c); updateLpfCoeffs(c); } // re-calculate the omega-arrays for the magnitude response plot: double f; // for the current frequency for(k=0; k<numBins; k++) { // get the current frequency from the freq-array: f = freqs[k]; // calculate some dependent quantities and store them into their arrays: omegas[k] = 2*PI*f/sampleRate; cosOmegas[k] = cos(omegas[k]); cos2Omegas[k] = cos(2*omegas[k]); } // update the individual magnitude-arrays: for(c=0; c<numChannels; c++) { updateHpfFreqResponse(c); for(s=0; s<numEqStages; s++) updateEqFreqResponse(s,c); updateLpfFreqResponse(c); updateOverallFreqResponse(c); } // make sure, that the filter-chains use the same set of coefficients in // stereo-linked mode: setStereoMode(stereoMode); } void HighOrderEqualizer::setStereoMode(int newStereoMode) { intA slope, s; hpf[1].initBiquadCoeffs(); for(s=0; s<numEqStages; s++) eq[s][1].initBiquadCoeffs(); lpf[1].initBiquadCoeffs(); if( newStereoMode == STEREO_LINKED ) { // tell the BiquadCascade-objects how many biquad stages are to be used: slope = hpfOrder[0]; if( isEven(slope) ) hpf[1].setNumStages( slope/2 ); else hpf[1].setNumStages( (slope+1)/2 ); for(s=0; s<numEqStages; s++) { slope = eqOrder[s][0]; if( eqMode[s][0] == LOW_SHELV || eqMode[s][0] == HIGH_SHELV ) // filter order is the same as the slope-value - half as many // biquad-stages are required (up to a left-over one-pole stage): { if( isEven(slope) ) eq[s][1].setNumStages( slope/2 ); else eq[s][1].setNumStages( (slope+1)/2 ); } else if(eqMode[s][0] == PEAK || eqMode[s][0] == NOTCH) // filter order is twice the slope-value - just as many biquad-stages // are required: eq[s][1].setNumStages( slope ); else if(eqMode[s][0] == BYPASS) eq[s][1].setNumStages( 0 ); } slope = lpfOrder[0]; if( isEven(slope) ) lpf[1].setNumStages( slope/2 ); else lpf[1].setNumStages( (slope+1)/2 ); // pass the coeffs for the left filters to the BiquadCascade-objects for // right filters when we are in STEREO_LINKED mode: hpf[1].setCoeffs(&(b0hp[0][0]), &(b1hp[0][0]), &(b2hp[0][0]), &(a1hp[0][0]), &(a2hp[0][0]) ); for(s=0; s<numEqStages; s++) { eq[s][1].setCoeffs(&(b0eq[s][0][0]), &(b1eq[s][0][0]), &(b2eq[s][0][0]), &(a1eq[s][0][0]), &(a2eq[s][0][0]) ); } lpf[1].setCoeffs(&(b0lp[0][0]), &(b1lp[0][0]), &(b2lp[0][0]), &(a1lp[0][0]), &(a2lp[0][0]) ); } // in the other cases, the right-channel filters use their own sets of // coefficients: else { // tell the BiquadCascade-objects how many biquad stages are to be used: slope = hpfOrder[1]; if( isEven(slope) ) hpf[1].setNumStages( slope/2 ); else hpf[1].setNumStages( (slope+1)/2 ); for(s=0; s<numEqStages; s++) { slope = eqOrder[s][1]; if( eqMode[s][1] == LOW_SHELV || eqMode[s][1] == HIGH_SHELV ) // filter order is the same as the slope-value - half as many // biquad-stages are required (up to a left-over one-pole stage): { if( isEven(slope) ) eq[s][1].setNumStages( slope/2 ); else eq[s][1].setNumStages( (slope+1)/2 ); } else if(eqMode[s][1] == PEAK || eqMode[s][1] == NOTCH) // filter order is twice the slope-value - just as many biquad-stages // are required: eq[s][1].setNumStages( slope ); else if(eqMode[s][1] == BYPASS) eq[s][1].setNumStages( 0 ); } slope = lpfOrder[1]; if( isEven(slope) ) lpf[1].setNumStages( slope/2 ); else lpf[1].setNumStages( (slope+1)/2 ); // pass the coeffs for the right filters to the BiquadCascade-objects for // right filters when we are not in STEREO_LINKED mode: hpf[1].setCoeffs(&(b0hp[1][0]), &(b1hp[1][0]), &(b2hp[1][0]), &(a1hp[1][0]), &(a2hp[1][0]) ); for(s=0; s<numEqStages; s++) { eq[s][1].setCoeffs(&(b0eq[s][1][0]), &(b1eq[s][1][0]), &(b2eq[s][1][0]), &(a1eq[s][1][0]), &(a2eq[s][1][0]) ); } lpf[1].setCoeffs(&(b0lp[1][0]), &(b1lp[1][0]), &(b2lp[1][0]), &(a1lp[1][0]), &(a2lp[1][0]) ); } // update the frequency-response curves, if the stereo-mode has been changed: if( newStereoMode != stereoMode ) { stereoMode = newStereoMode; updateOverallFreqResponse(0); } } void HighOrderEqualizer::setLpfOrder(int newLpfOrder, int channel) { static intA c; c = channel; // make sure that we don't try to access an invalid adress: if( c<0 || c>(numChannels-1) ) return; else if( newLpfOrder >= 0 && newLpfOrder <= 2*maxBiquadsInFilter ) lpfOrder[c] = newLpfOrder; updateLpfCoeffs(c); setStereoMode(stereoMode); // makes sure that the new coeffs are passed to the // right-channel filters in stereo-linked mode updateLpfFreqResponse(c); updateOverallFreqResponse(c); } void HighOrderEqualizer::setLpfCutoff(double newLpfCutoff, int channel) { static intA c; c = channel; // make sure that we don't try to access an invalid adress: if( c<0 || c>(numChannels-1) ) return; else if( newLpfCutoff >= 20.0 && newLpfCutoff <= 20000.0 ) lpfCutoff[c] = newLpfCutoff; updateLpfCoeffs(c); setStereoMode(stereoMode); updateLpfFreqResponse(c); updateOverallFreqResponse(c); } void HighOrderEqualizer::setHpfOrder(int newHpfOrder, int channel) { static intA c; c = channel; // make sure that we don't try to access an invalid adress: if( c<0 || c>(numChannels-1) ) return; else if( newHpfOrder >= 0 && newHpfOrder <= 2*maxBiquadsInFilter ) hpfOrder[c] = newHpfOrder; updateHpfCoeffs(c); setStereoMode(stereoMode); updateHpfFreqResponse(c); updateOverallFreqResponse(c); } void HighOrderEqualizer::setHpfCutoff(double newHpfCutoff, int channel) { static intA c; c = channel; // make sure that we don't try to access an invalid adress: if( c<0 || c>(numChannels-1) ) return; else if( newHpfCutoff >= 20.0 && newHpfCutoff <= 20000.0 ) hpfCutoff[c] = newHpfCutoff; updateHpfCoeffs(c); setStereoMode(stereoMode); updateHpfFreqResponse(c); updateOverallFreqResponse(c); } void HighOrderEqualizer::setEqMode(int newMode, int stage, int channel) { static intA s, c; s = stage; c = channel; // make sure that we don't try to access an invalid adress: if( s<0 || s>(numEqStages-1) || c<0 || c>(numChannels-1) ) return; else if( newMode >= HighOrderEqualizer::BYPASS && newMode <= HighOrderEqualizer::HIGH_SHELV ) { eqMode[s][c] = newMode; } updateEqCoeffs(s,c); setStereoMode(stereoMode); updateEqFreqResponse(s,c); updateOverallFreqResponse(c); } void HighOrderEqualizer::setEqOrder(int newOrder, int stage, int channel) { static intA s, c; s = stage; c = channel; // make sure that we don't try to access an invalid adress: if( s<0 || s>(numEqStages-1) || c<0 || c>(numChannels-1) ) return; else if( newOrder >= 0 && newOrder <= maxBiquadsInEq ) eqOrder[s][c] = newOrder; updateEqCoeffs(s,c); setStereoMode(stereoMode); updateEqFreqResponse(s,c); updateOverallFreqResponse(c); } void HighOrderEqualizer::setEqFreq(double newFreq, int stage, int channel) { static intA s, c; s = stage; c = channel; // make sure that we don't try to access an invalid adress: if( s<0 || s>(numEqStages-1) || c<0 || c>(numChannels-1) ) return; else if( newFreq >= 20.0 && newFreq <= 20000.0 ) eqFreq[s][c] = newFreq; updateEqCoeffs(s,c); setStereoMode(stereoMode); updateEqFreqResponse(s,c); updateOverallFreqResponse(c); } void HighOrderEqualizer::setEqGain(double newGain, int stage, int channel) { static intA s, c; s = stage; c = channel; // make sure that we don't try to access an invalid adress: if( s<0 || s>(numEqStages-1) || c<0 || c>(numChannels-1) ) return; else eqGain[s][c] = dB2amp(newGain); updateEqCoeffs(s,c); setStereoMode(stereoMode); updateEqFreqResponse(s,c); updateOverallFreqResponse(c); } void HighOrderEqualizer::setEqQ(double newQ, int stage, int channel) { static intA s, c; s = stage; c = channel; // make sure that we don't try to access an invalid adress: if( s<0 || s>(numEqStages-1) || c<0 || c>(numChannels-1) ) return; else if( newQ > 0.00001 ) eqQ[s][c] = newQ; updateEqCoeffs(s,c); setStereoMode(stereoMode); updateEqFreqResponse(s,c); updateOverallFreqResponse(c); } void HighOrderEqualizer::setLevel(double newLevel, int channel) { if( channel == 0 ) vol[0] = dB2amp(newLevel); else if ( channel == 1 ) vol[1] = dB2amp(newLevel); updateOverallFreqResponse(channel); } void HighOrderEqualizer::setBypassAll(bool newBypassAll) { bypassAll = newBypassAll; } //---------------------------------------------------------------------------- // others: void HighOrderEqualizer::resetHpfCoeffs(int channel) { static intA c, b; // indices for thechannel and biquad-stage if( channel >= 0 && channel < numChannels) c = channel; else return; for(b=0; b<maxBiquadsInFilter; b++) { b0hp[c][b] = 1.0; b1hp[c][b] = 0.0; b2hp[c][b] = 0.0; a1hp[c][b] = 0.0; a2hp[c][b] = 0.0; } } void HighOrderEqualizer::resetEqCoeffs(int stage, int channel) { static intA s, c, b; s = stage; c = channel; // make sure that we don't try to access an invalid adress: if( s<0 || s>(numEqStages-1) || c<0 || c>(numChannels-1) ) return; else { for(b=0; b<maxBiquadsInEq; b++) { b0eq[s][c][b] = 1.0; b1eq[s][c][b] = 0.0; b2eq[s][c][b] = 0.0; a1eq[s][c][b] = 0.0; a2eq[s][c][b] = 0.0; } } // let the embedded BiquadCascade-object reset it's internal copies of the // coeffcients, too: eq[s][c].initBiquadCoeffs(); } void HighOrderEqualizer::resetLpfCoeffs(int channel) { static intA c, b; // indices for thechannel and biquad-stage if( channel >= 0 && channel < numChannels) c = channel; else return; for(b=0; b<maxBiquadsInFilter; b++) { b0lp[c][b] = 1.0; b1lp[c][b] = 0.0; b2lp[c][b] = 0.0; a1lp[c][b] = 0.0; a2lp[c][b] = 0.0; } } void HighOrderEqualizer::updateHpfCoeffs(int channel) { static doubleA freq; static intA slope; static intA c; c = channel; // reset the highpass-coefficients to neutral values: resetHpfCoeffs(c); // select the appropriate parameter-set: freq = hpfCutoff[c]; slope = hpfOrder[c]; // tell the BiquadCascade-object which realizes the highpass-filter how many // biquad stages are to be used: if( isEven(slope) ) hpf[c].setNumStages( slope/2 ); else hpf[c].setNumStages( (slope+1)/2 ); // set up the filter-designer: designer.setMode(IirDesigner::HIGHPASS); designer.setFreq1(freq); designer.setSlope(slope); // let the designer calculate the equalizer-coefficients: designer.getBiquadCascadeCoeffs(&(b0hp[c][0]), &(b1hp[c][0]), &(b2hp[c][0]), &(a1hp[c][0]), &(a2hp[c][0]) ); // pass the coefficients to the appropriate BiquadCascade-object: hpf[c].setCoeffs(&(b0hp[c][0]), &(b1hp[c][0]), &(b2hp[c][0]), &(a1hp[c][0]), &(a2hp[c][0]) ); } void HighOrderEqualizer::updateEqCoeffs(int stage, int channel) { static doubleA freq, lowFreq, highFreq, gain, q; static intA mode, slope; static intA s, c; s = stage; c = channel; // reset the equalizer-coefficients to neutral values: resetEqCoeffs(s,c); // select the appropriate parameter-set: freq = eqFreq[s][c]; gain = eqGain[s][c]; q = eqQ[s][c]; mode = eqMode[s][c]; slope = eqOrder[s][c]; // calculate corner frequency for shelving modes or lower and upper // corner-frequencies for peaking- and notch-modes: if( mode == HighOrderEqualizer::BYPASS ) { // tell the embedded IirDesigner-object the corner frequency: designer.setFreq1(freq); } else if( mode == HighOrderEqualizer::LOW_SHELV || mode == HighOrderEqualizer::HIGH_SHELV) { // tell the embedded IirDesigner-object the corner frequency: designer.setFreq1(freq); } else if( mode == HighOrderEqualizer::PEAK || mode == HighOrderEqualizer::NOTCH) { // calculate lower and upper corner-frequencies for peaking and // notch-filters: lowFreq = freq * ( sqrt(1.0+1.0/(4.0*q*q)) - 1.0/(2.0*q) ); highFreq = lowFreq + freq/q; // restrict the range of the corner-frequencies: if( lowFreq > 0.94*0.5*sampleRate ) lowFreq = 0.94*0.5*sampleRate; // should actually never happen for // sampleRates >= 44.1 kHz if( highFreq > 0.95*0.5*sampleRate ) highFreq = 0.95*0.5*sampleRate; // this, however, could easily happen // tell the embedded IirDesigner-object the corner-frequencies: designer.setFreq1(lowFreq); designer.setFreq2(highFreq); } // "translate" the mode index of the HighOrderEqualizer-class into the // corresponding mode index of the IirDesigner-class and set up the mode in // the embedded IirDesigner-object: switch( mode ) { case HighOrderEqualizer::BYPASS: { designer.setMode(IirDesigner::BYPASS); eq[s][c].setNumStages(0); } break; case HighOrderEqualizer::LOW_SHELV: { designer.setMode(IirDesigner::LOW_SHELV); if( isEven(slope) ) eq[s][c].setNumStages( slope/2 ); else eq[s][c].setNumStages( (slope+1)/2 ); } break; case HighOrderEqualizer::PEAK: { designer.setMode(IirDesigner::PEAK); eq[s][c].setNumStages(slope); } break; case HighOrderEqualizer::NOTCH: { designer.setMode(IirDesigner::BANDREJECT); eq[s][c].setNumStages(slope); } break; case HighOrderEqualizer::HIGH_SHELV: { designer.setMode(IirDesigner::HIGH_SHELV); if( isEven(eqOrder[s][c]) ) eq[s][c].setNumStages( slope/2 ); else eq[s][c].setNumStages( (slope+1)/2 ); } break; default: { designer.setMode(IirDesigner::BYPASS); eq[s][c].setNumStages(0); } } // end of switch(eqMode[stage][channel]) // set up the order- and gain-parameters in the embedded IirDesigner-object: designer.setSlope(slope); designer.setGain(gain); // let the designer calculate the equalizer-coefficients: designer.getBiquadCascadeCoeffs(&(b0eq[s][c][0]), &(b1eq[s][c][0]), &(b2eq[s][c][0]), &(a1eq[s][c][0]), &(a2eq[s][c][0]) ); // pass the coefficients to the appropriate BiquadCascade-object: eq[s][c].setCoeffs(&(b0eq[s][c][0]), &(b1eq[s][c][0]), &(b2eq[s][c][0]), &(a1eq[s][c][0]), &(a2eq[s][c][0]) ); } void HighOrderEqualizer::updateLpfCoeffs(int channel) { static doubleA freq; static intA slope; static intA c; c = channel; // reset the highpass-coefficients to neutral values: resetLpfCoeffs(c); // select the appropriate parameter-set: freq = lpfCutoff[c]; slope = lpfOrder[c]; // tell the BiquadCascade-object which realizes the highpass-filter how many // biquad stages are to be used: if( isEven(slope) ) lpf[c].setNumStages( slope/2 ); else lpf[c].setNumStages( (slope+1)/2 ); // set up the filter-designer: designer.setMode(IirDesigner::LOWPASS); designer.setFreq1(freq); designer.setSlope(slope); // let the designer calculate the equalizer-coefficients: designer.getBiquadCascadeCoeffs(&(b0lp[c][0]), &(b1lp[c][0]), &(b2lp[c][0]), &(a1lp[c][0]), &(a2lp[c][0]) ); // pass the coefficients to the appropriate BiquadCascade-object: lpf[c].setCoeffs(&(b0lp[c][0]), &(b1lp[c][0]), &(b2lp[c][0]), &(a1lp[c][0]), &(a2lp[c][0]) ); } void HighOrderEqualizer::updateHpfFreqResponse(int channel) { static intA c, k, b; // indices for channel, bin and biquad-stage static doubleA num, den, accu, tmp; c = channel; // make sure that we don't try to access an invalid adress: if( c<0 || c>(numChannels-1) ) return; for(k=0; k<numBins; k++) { // accumulate the squared magnitude responses of the individual // biquad-stages: accu = 1.0; for(b=0; b<maxBiquadsInFilter; b++) { // calculate the numerator of the squared magnitude of biquad-stage b: num = b0hp[c][b] * b0hp[c][b] + b1hp[c][b] * b1hp[c][b] + b2hp[c][b] * b2hp[c][b] + 2*cosOmegas[k] * ( b0hp[c][b]*b1hp[c][b] + b1hp[c][b]*b2hp[c][b]) + 2*cos2Omegas[k] * b0hp[c][b]*b2hp[c][b]; // calculate the denominator of the squared magnitude of biquad-stage b: den = 1.0 * 1.0 + a1hp[c][b] * a1hp[c][b] + a2hp[c][b] * a2hp[c][b] + 2*cosOmegas[k] * ( 1.0*a1hp[c][b] + a1hp[c][b]*a2hp[c][b]) + 2*cos2Omegas[k] * 1.0*a2hp[c][b]; // multiply the accumulator with the squared magnitude of biquad-stage b: accu *= (num/den); } // end of "for(b=0; b<maxBiquadsInEq; b++)" // take the square root of the accumulated squared magnitude response - this // is the desired magnitude of the biquad cascade at bin k: tmp = sqrt(accu); // convert this value to decibels: tmp = 20.0 * log10(tmp); // store the calculated dB-value in bin k of the freq-response of the // highpass-filter for channel c: hpfResponses[c][k] = tmp; } } void HighOrderEqualizer::updateEqFreqResponse(int stage, int channel) { static intA s, c, k, b; // indices for eq-stage, channel, bin and // biquad-stage inside the eq-stage static doubleA num, den, accu, tmp; s = stage; c = channel; // make sure that we don't try to access an invalid adress: if( s<0 || s>(numEqStages-1) || c<0 || c>(numChannels-1) ) return; for(k=0; k<numBins; k++) { // accumulate the squared magnitude responses of the individual // biquad-stages: accu = 1.0; for(b=0; b<maxBiquadsInEq; b++) { // calculate the numerator of the squared magnitude of biquad-stage b: num = b0eq[s][c][b] * b0eq[s][c][b] + b1eq[s][c][b] * b1eq[s][c][b] + b2eq[s][c][b] * b2eq[s][c][b] + 2*cosOmegas[k] * ( b0eq[s][c][b]*b1eq[s][c][b] + b1eq[s][c][b]*b2eq[s][c][b]) + 2*cos2Omegas[k] * b0eq[s][c][b]*b2eq[s][c][b]; // calculate the denominator of the squared magnitude of biquad-stage b: den = 1.0 * 1.0 + a1eq[s][c][b] * a1eq[s][c][b] + a2eq[s][c][b] * a2eq[s][c][b] + 2*cosOmegas[k] * ( 1.0*a1eq[s][c][b] + a1eq[s][c][b]*a2eq[s][c][b]) + 2*cos2Omegas[k] * 1.0*a2eq[s][c][b]; // multiply the accumulator with the squared magnitude of biquad-stage b: accu *= (num/den); } // end of "for(b=0; b<maxBiquadsInEq; b++)" // take the square root of the accumulated squared magnitude response - this // is the desired magnitude of the biquad cascade at bin k: tmp = sqrt(accu); // convert this value to decibels: tmp = 20.0 * log10(tmp); // store the calculated dB-value in bin k of the freq-response of eq-stage // s for channel c: eqResponses[s][c][k] = tmp; } } void HighOrderEqualizer::updateLpfFreqResponse(int channel) { static intA c, k, b; // indices for channel, bin and biquad-stage static doubleA num, den, accu, tmp; c = channel; // make sure that we don't try to access an invalid adress: if( c<0 || c>(numChannels-1) ) return; for(k=0; k<numBins; k++) { // accumulate the squared magnitude responses of the individual // biquad-stages: accu = 1.0; for(b=0; b<maxBiquadsInFilter; b++) { // calculate the numerator of the squared magnitude of biquad-stage b: num = b0lp[c][b] * b0lp[c][b] + b1lp[c][b] * b1lp[c][b] + b2lp[c][b] * b2lp[c][b] + 2*cosOmegas[k] * ( b0lp[c][b]*b1lp[c][b] + b1lp[c][b]*b2lp[c][b]) + 2*cos2Omegas[k] * b0lp[c][b]*b2lp[c][b]; // calculate the denominator of the squared magnitude of biquad-stage b: den = 1.0 * 1.0 + a1lp[c][b] * a1lp[c][b] + a2lp[c][b] * a2lp[c][b] + 2*cosOmegas[k] * ( 1.0*a1lp[c][b] + a1lp[c][b]*a2lp[c][b]) + 2*cos2Omegas[k] * 1.0*a2lp[c][b]; // multiply the accumulator with the squared magnitude of biquad-stage b: accu *= (num/den); } // end of "for(b=0; b<maxBiquadsInEq; b++)" // take the square root of the accumulated squared magnitude response - this // is the desired magnitude of the biquad cascade at bin k: tmp = sqrt(accu); // convert this value to decibels: tmp = 20.0 * log10(tmp); // store the calculated dB-value in bin k of the freq-response of the // highpass-filter for channel c: lpfResponses[c][k] = tmp; } } void HighOrderEqualizer::updateOverallFreqResponse(int channel) { static intA s, c, k; static doubleA accu; c = channel; // make sure that we don't try to access an invalid adress: if( c<0 || c>(numChannels-1) ) return; for(k=0; k<numBins; k++) { if( stereoMode != MONO_10 ) { accu = amp2dB(vol[c]); accu += hpfResponses[c][k]; accu += lpfResponses[c][k]; for(s=0; s<numEqStages; s++) accu += eqResponses[s][c][k]; // typecast and store: floatMagnitudes[c][k] = (float) accu; } else if( stereoMode == MONO_10 ) // we need to add both channels freq responses in this case { accu = amp2dB(vol[0]); accu += amp2dB(vol[1]); accu += hpfResponses[0][k]; accu += hpfResponses[1][k]; accu += lpfResponses[0][k]; accu += lpfResponses[1][k]; for(s=0; s<numEqStages; s++) { accu += eqResponses[s][0][k]; accu += eqResponses[s][1][k]; } // typecast and store: floatMagnitudes[0][k] = (float) accu; } } // end of for(k=0; k<numBins; k++) } void HighOrderEqualizer::getMagnitudeResponse(int channel, int* arrayLengths, float** freqArray, float** magArray) { // assign the number of bins to the output-slot "arrayLengths": *arrayLengths = numBins; // assign the output-slot *freqArray to the single-precision frequency-array: *freqArray = floatFrequencies; // assign the output-slot *magArray to the single-precision magnitude-array // for the requested channel: *magArray = &(floatMagnitudes[channel][0]); }
27.131718
82
0.596901
RobinSchmidt
e48826a61286c965d7d880025652f2a2bf5c9be2
4,415
cxx
C++
com/svcdlls/trksvcs/utest/tbackup.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
com/svcdlls/trksvcs/utest/tbackup.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
com/svcdlls/trksvcs/utest/tbackup.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1996. // // File: tbackup.cxx // // Contents: testing backup read/write // // History: 1-Aug-97 weiruc Created. // //-------------------------------------------------------------------------- #include <pch.cxx> #pragma hdrstop #define TRKDATA_ALLOCATE #include <trkwks.hxx> #include <cfiletim.hxx> #include <ocidl.h> // DWORD g_Debug = TRKDBG_ERROR; #define BUFFERSIZE 1000 EXTERN_C void __cdecl _tmain(int argc, TCHAR **argv) { HANDLE hFile = INVALID_HANDLE_VALUE; HANDLE hBackupFile = INVALID_HANDLE_VALUE; BYTE rgbBuffer[BUFFERSIZE]; DWORD dwBytesRead = 0; DWORD dwBytesWritten = 0; LPVOID pReadContext = NULL; LPVOID pWriteContext = NULL; BOOL fReadSuccessful = TRUE; if(argc != 3) { _tprintf(TEXT("usage: %s <testfile> <backupfile>\n"), argv[0]); goto Exit; } EnablePrivilege( SE_RESTORE_NAME ); // open test file hFile = CreateFile(argv[1], GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if(INVALID_HANDLE_VALUE == hFile) { _tprintf(TEXT("Can't open (%s), %08x\n"), argv[1], GetLastError()); goto Exit; } // open backup file hBackupFile = CreateFile(argv[2], GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS, NULL); if(INVALID_HANDLE_VALUE == hBackupFile) { _tprintf(TEXT("Can't open (%s), %08x\n"), argv[2], GetLastError()); goto Exit; } // All we are doing is to backup read a file and backup write the file to // a different file. We are assuming the file is smaller than the // BUFFERSIZE. while(TRUE) { if(!BackupRead(hFile, rgbBuffer, BUFFERSIZE, &dwBytesRead, FALSE, FALSE, &pReadContext)) { _tprintf(TEXT("BackupRead failed, %08x\n"), GetLastError()); break; } else { _tprintf(TEXT(" %d bytes read\n"), dwBytesRead); } if(0 == dwBytesRead) { break; } if(!BackupWrite(hBackupFile, rgbBuffer, dwBytesRead, &dwBytesWritten, FALSE, FALSE, &pWriteContext)) { _tprintf(TEXT("BackupWrite failed, %08x\n"), GetLastError()); break; } else { _tprintf(TEXT(" %d bytes wrote\n"), dwBytesWritten); } } // Deallocate data structures used by BackupRead/Write. if(!BackupRead(hFile, rgbBuffer, BUFFERSIZE, &dwBytesRead, TRUE, TRUE, &pReadContext)) { _tprintf(TEXT("Last BackupRead failed, %08x\n"), GetLastError()); } if(!BackupWrite(hBackupFile, rgbBuffer, dwBytesRead, &dwBytesWritten, TRUE, TRUE, &pWriteContext)) { _tprintf(TEXT("Last BackupWrite failed, %08x\n"), GetLastError()); } Exit: if(INVALID_HANDLE_VALUE != hFile) { if(!CloseHandle(hFile)) { _tprintf(TEXT("Can't close (%s), %08x\n"), argv[1], GetLastError()); } } if(INVALID_HANDLE_VALUE != hBackupFile) { if(!CloseHandle(hBackupFile)) { _tprintf(TEXT("Can't close (%s), %08x\n"), argv[2], GetLastError()); } } }
28.856209
81
0.443262
npocmaka
e48b6ead79613720535e7e42d9bb3d47e592dfee
1,584
cpp
C++
net/http/headers/HttpAcceptCharSet.cpp
wangsun1983/Obotcha
2464e53599305703f5150df72bf73579a39d8ef4
[ "MIT" ]
27
2019-04-27T00:51:22.000Z
2022-03-30T04:05:44.000Z
net/http/headers/HttpAcceptCharSet.cpp
wangsun1983/Obotcha
2464e53599305703f5150df72bf73579a39d8ef4
[ "MIT" ]
9
2020-05-03T12:17:50.000Z
2021-10-15T02:18:47.000Z
net/http/headers/HttpAcceptCharSet.cpp
wangsun1983/Obotcha
2464e53599305703f5150df72bf73579a39d8ef4
[ "MIT" ]
1
2019-04-16T01:45:36.000Z
2019-04-16T01:45:36.000Z
#include "HttpAcceptCharSet.hpp" #include "HttpHeaderContentParser.hpp" #include "Math.hpp" namespace obotcha { _HttpAcceptCharSetItem::_HttpAcceptCharSetItem(String s,float w) { weight = w; type = s; } _HttpAcceptCharSet::_HttpAcceptCharSet() { charsets = createArrayList<HttpAcceptCharSetItem>(); } _HttpAcceptCharSet::_HttpAcceptCharSet(String s) { import(s); } void _HttpAcceptCharSet::import(String s) { st(HttpHeaderContentParser)::import(s,[this](String directive,String parameter) { if(parameter == nullptr) { HttpAcceptCharSetItem item = createHttpAcceptCharSetItem(directive); charsets->add(item); } else { if(directive->equals("q")) { charsets->get(charsets->size() - 1)->weight = parameter->toBasicFloat(); } } }); } ArrayList<HttpAcceptCharSetItem> _HttpAcceptCharSet::get() { return charsets; } void _HttpAcceptCharSet::add(String s,float w) { charsets->add(createHttpAcceptCharSetItem(s,w)); } String _HttpAcceptCharSet::toString() { String charset = ""; auto iterator = charsets->getIterator(); while(iterator->hasValue()) { HttpAcceptCharSetItem item = iterator->getValue(); if(st(Math)::compareFloat(item->weight,1.0) == st(Math)::AlmostEqual) { charset = charset->append(item->type,","); } else { charset = charset->append(item->type,";q=",createString(item->weight,2),","); } iterator->next(); } return charset->subString(0,charset->size() - 1); } }
27.310345
89
0.642677
wangsun1983
e490a1deae2b20f9c9a4f2a9cb1cff04bb35e725
2,840
cpp
C++
lang_sim_main.cpp
crabster15/LangEvolve
76991783ba6ab24b28a62aefdc3d42fc09299cc5
[ "MIT" ]
null
null
null
lang_sim_main.cpp
crabster15/LangEvolve
76991783ba6ab24b28a62aefdc3d42fc09299cc5
[ "MIT" ]
null
null
null
lang_sim_main.cpp
crabster15/LangEvolve
76991783ba6ab24b28a62aefdc3d42fc09299cc5
[ "MIT" ]
null
null
null
#include "Base_word.h" #include "wordMod.hpp" #include "xmlhandler.h" #include <iostream> #include "Constants.h" #include <vector> #include <memory> std::vector<std::shared_ptr<Word>> RunGeneration(std::vector<std::shared_ptr<Word>> Wordlist, std::string characterSet, std::string vowelSet, MeaningHandle* mhandle){ std::vector<std::shared_ptr<Word>> newwordlist; std::unique_ptr<WordMod> Modhandleptr(new WordMod(characterSet, vowelSet)); srand (time(NULL)); for(int Words = 0; Words < Wordlist.size() - 1; Words++){ int changed = rand() % 100 + 1; if(changed <= PERCENT_CHANGE){ std::vector<int> WordMask = Modhandleptr->CreateChangedMask(Wordlist[Words]->get_word()); std::string newWordstr = Modhandleptr->ApplyCharMask(Wordlist[Words]->get_word(), WordMask); int meaningchanged = rand() % 100 + 1; if(meaningchanged <= MEANING_CHANGE_DEFAULT){ //set it hard coded to false mhandle->GetMeaning(false,newWordstr); } // create a different way to std::shared_ptr<Word> newwordptr(new Word(newWordstr, Wordlist[Words]->get_word(), Wordlist[Words]->get_meaning())); newwordlist.push_back(newwordptr); } } std::vector<std::shared_ptr<Word>> purgedwordlist = Modhandleptr->DeleteRepeats(newwordlist); std::cout << "size of newword list:" << newwordlist.size() << std::endl; return purgedwordlist; } std::vector<std::shared_ptr<Word>> Run_sim(int generations, std::vector<std::shared_ptr<Word>> originDict, std::string characterSet, std::string vowelSet, MeaningHandle* mhandle){ std::vector<std::shared_ptr<Word>> WordList; for(int WordIndex = 0; WordIndex < originDict.size() - 1; WordIndex++){ WordList.push_back(originDict[WordIndex]); } for(int CurrGen = 0; CurrGen < generations; CurrGen++){ std::vector<std::shared_ptr<Word>> NewWordList = RunGeneration(WordList, characterSet, vowelSet, mhandle); for(int WordIndex = 0; WordIndex < NewWordList.size() - 1; WordIndex++){ WordList.push_back(NewWordList[WordIndex]); } // debugging word list for(int i = 0; i < WordList.size() - 1; i++){ } } return WordList; } void log_sim(Xmlhandler * handle, std::vector<std::shared_ptr<Word>> WordList){ // log all of the new words into an xml file handle->LogWords(WordList); } int main(int argc, char *argv[]){ Xmlhandler * handleptr = new Xmlhandler(argv[1]); // second arg is default dictionary of terms MeaningHandle * Mhandleptr = new MeaningHandle(argv[2]); int generations = handleptr->GetGenerations(); std::vector<std::shared_ptr<Word>> originDict = handleptr->GetWords(); std::string characterSet = handleptr->GetCharSet(); std::string vowelSet = handleptr->GetVowSet(); std::vector<std::shared_ptr<Word>> GeneratedWords = Run_sim(generations, originDict, characterSet, vowelSet, Mhandleptr); log_sim(handleptr, GeneratedWords); return 0; }
41.764706
179
0.721127
crabster15
e498539f226f24e2ee571a1e4ceb7ab0f620143a
2,944
cpp
C++
src/monitors/ntff.cpp
johnaparker/fields
7b8daf42dcc140448b2fa9e3ba7122bd69bbcb01
[ "MIT" ]
null
null
null
src/monitors/ntff.cpp
johnaparker/fields
7b8daf42dcc140448b2fa9e3ba7122bd69bbcb01
[ "MIT" ]
null
null
null
src/monitors/ntff.cpp
johnaparker/fields
7b8daf42dcc140448b2fa9e3ba7122bd69bbcb01
[ "MIT" ]
2
2020-09-09T18:13:24.000Z
2021-02-16T08:40:02.000Z
#include "monitors/ntff.h" namespace qbox { ntff_point::ntff_point(const ComplexArray& S, const h5cpp::h5file &file, const h5cpp::h5group &group ): S(S) { file_name = file.get_name(); group_path = group.get_path(); } ntff_point::ntff_point(const ComplexArray& S, const std::string &file_name, const std::string &group_path): S(S), file_name(file_name), group_path(group_path) {}; void ntff_point::write() { h5cpp::h5file f(file_name, h5cpp::io::rw); auto g = f.open_group(group_path); h5cpp::write_array<std::complex<double>>(S, g, "ntff_point"); } ntff_sphere::ntff_sphere(const ComplexTensor& S, const h5cpp::h5file &file, const h5cpp::h5group &group ): S(S) { file_name = file.get_name(); group_path = group.get_path(); } ntff_sphere::ntff_sphere(const ComplexTensor& S, const std::string &file_name, const std::string &group_path): S(S), file_name(file_name), group_path(group_path) {}; void ntff_sphere::write() { h5cpp::h5file f(file_name, h5cpp::io::rw); auto g = f.open_group(group_path); h5cpp::write_tensor(S, g, "ntff_sphere"); } ComplexArray compute_ntff_point(const complex_dft_tensor<1> &E, const complex_dft_tensor<1> &H, const Array &freq, const vec &center, const vec &pc) { const int Nfreq = freq.size(); vec p = pc - center; double r = p.norm(); Array omega = 2*M_PI*freq; Array k = omega; ComplexArray factor = Eigen::exp(1i*(M_PI/4 - k*r))/Eigen::sqrt(8*r*M_PI*k); ComplexArray integral = ComplexArray::Zero(Nfreq); //*** find a way to write this generically // vec tangent = surf.tangent; // vec normal = surf.normal.array().cwiseAbs(); //*** this needs to be outward normal // double Jsgn = tangent.dot(vec(1,1)); // double Msgn = tangent.dot(vec(-1,1)); // const auto E = fourier("Ez"); // const auto H = surf.dim[0] == 0 ? fourier("Hy") : fourier("Hx"); // for (int i = 0; i < length; i++) { // vec p_prime = surf.a + tangent*i*F->dx - center; //*** account for yee grid half-step here // double angle = p.dot(normal)/r; //*** worry about the sign of normal here // for (int j = 0; j < Nfreq; j++) { // auto Ec = E.real(i,j) + 1i*E.imag(i,j); // auto Hc = H.real(i,j) + 1i*H.imag(i,j); // auto Jeq_term = Jsgn*omega[j]*Hc; // auto Meq_term = Msgn*k[j]*Ec*angle; // auto integand = (Jeq_term + Meq_term)*exp(1i*k[j]*p.dot(p_prime)/r); // integral[j] += integand; // } // } return factor*integral; } ComplexTensor compute_ntff_sphere(const complex_dft_tensor<1> &E, const complex_dft_tensor<1> &H, double da, sign Sign) { } }
39.783784
169
0.572011
johnaparker
e499a4ee0d6914d7563b9ba5ede631c8412527bf
881
cpp
C++
src/terminal/gui/Rectangle.cpp
KeinR/Etermal
9bf66f6be6ae8585b763dd902701e72013a5abcc
[ "MIT" ]
null
null
null
src/terminal/gui/Rectangle.cpp
KeinR/Etermal
9bf66f6be6ae8585b763dd902701e72013a5abcc
[ "MIT" ]
null
null
null
src/terminal/gui/Rectangle.cpp
KeinR/Etermal
9bf66f6be6ae8585b763dd902701e72013a5abcc
[ "MIT" ]
null
null
null
#include "Rectangle.h" #include "../Resources.h" etm::Rectangle::Rectangle(Resources *res): res(res) { } void etm::Rectangle::setColor(const Color &color) { this->color = color; } void etm::Rectangle::setX(float x) { model.x = x; } void etm::Rectangle::setY(float y) { model.y = y; } void etm::Rectangle::setWidth(float width) { model.width = width; } void etm::Rectangle::setHeight(float height) { model.height = height; } float etm::Rectangle::getX() { return model.x; } float etm::Rectangle::getY() { return model.y; } float etm::Rectangle::getWidth() { return model.width; } float etm::Rectangle::getHeight() { return model.height; } bool etm::Rectangle::hasPoint(float x, float y) { return model.hasPoint(x, y); } void etm::Rectangle::render() { model.set(res); color.set(res->getShader()); res->renderRectangle(); }
18.744681
53
0.649262
KeinR
e49a75643fab03bbc49e892f05ba3fc99e5c0fad
2,433
cc
C++
chrome/browser/extensions/extension_installer.cc
devasia1000/chromium
919a8a666862fb866a6bb7aa7f3ae8c0442b4828
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2019-02-03T05:19:48.000Z
2021-11-15T15:07:21.000Z
chrome/browser/extensions/extension_installer.cc
devasia1000/chromium
919a8a666862fb866a6bb7aa7f3ae8c0442b4828
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/extensions/extension_installer.cc
devasia1000/chromium
919a8a666862fb866a6bb7aa7f3ae8c0442b4828
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// 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. #include "chrome/browser/extensions/extension_installer.h" #include "base/bind.h" #include "chrome/browser/extensions/extension_system.h" #include "chrome/browser/extensions/management_policy.h" #include "chrome/browser/profiles/profile.h" #include "content/public/browser/browser_thread.h" #if defined(ENABLE_MANAGED_USERS) #include "chrome/browser/managed_mode/managed_user_service.h" #include "chrome/browser/managed_mode/managed_user_service_factory.h" #endif namespace extensions { ExtensionInstaller::ExtensionInstaller(Profile* profile) : requirements_checker_(new RequirementsChecker()), profile_(profile), weak_ptr_factory_(this) { } ExtensionInstaller::~ExtensionInstaller() { } void ExtensionInstaller::CheckRequirements( const RequirementsCallback& callback) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); requirements_checker_->Check(extension_, callback); } #if defined(ENABLE_MANAGED_USERS) void ExtensionInstaller::ShowPassphraseDialog( content::WebContents* web_contents, const base::Closure& authorization_callback) { ManagedUserService* service = ManagedUserServiceFactory::GetForProfile(profile()); // Check whether the profile is managed. if (service->ProfileIsManaged()) { service->RequestAuthorization( web_contents, base::Bind(&ExtensionInstaller::OnAuthorizationResult, weak_ptr_factory_.GetWeakPtr(), authorization_callback)); return; } authorization_callback.Run(); } void ExtensionInstaller::OnAuthorizationResult( const base::Closure& authorization_callback, bool success) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); if (success) { ManagedUserService* service = ManagedUserServiceFactory::GetForProfile(profile_); if (service->ProfileIsManaged()) service->AddElevationForExtension(extension_->id()); } authorization_callback.Run(); } #endif string16 ExtensionInstaller::CheckManagementPolicy() { string16 error; bool allowed = ExtensionSystem::Get(profile_)->management_policy()->UserMayLoad( extension_, &error); DCHECK(allowed || !error.empty()); return error; } } // namespace extensions
31.192308
74
0.750103
devasia1000
e49b5a592e2cadde1a9f4149115932db038c2c73
4,265
hpp
C++
include/lol/def/LolLootPlayerLoot.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
1
2020-07-22T11:14:55.000Z
2020-07-22T11:14:55.000Z
include/lol/def/LolLootPlayerLoot.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
null
null
null
include/lol/def/LolLootPlayerLoot.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
4
2018-12-01T22:48:21.000Z
2020-07-22T11:14:56.000Z
#pragma once #include "../base_def.hpp" #include "LolLootItemOwnershipStatus.hpp" #include "LolLootRedeemableStatus.hpp" namespace lol { struct LolLootPlayerLoot { std::string lootName; std::string lootId; std::string refId; std::string localizedName; std::string localizedDescription; std::string itemDesc; std::string displayCategories; std::string rarity; std::string tags; std::string type; std::string asset; std::string tilePath; std::string splashPath; std::string shadowPath; std::string upgradeLootName; std::string upgradeEssenceName; std::string disenchantLootName; LolLootItemOwnershipStatus itemStatus; LolLootItemOwnershipStatus parentItemStatus; LolLootRedeemableStatus redeemableStatus; int32_t count; int32_t rentalGames; int32_t storeItemId; int32_t parentStoreItemId; int32_t value; int32_t upgradeEssenceValue; int32_t disenchantValue; int64_t expiryTime; int64_t rentalSeconds; bool isNew; bool isRental; }; inline void to_json(json& j, const LolLootPlayerLoot& v) { j["lootName"] = v.lootName; j["lootId"] = v.lootId; j["refId"] = v.refId; j["localizedName"] = v.localizedName; j["localizedDescription"] = v.localizedDescription; j["itemDesc"] = v.itemDesc; j["displayCategories"] = v.displayCategories; j["rarity"] = v.rarity; j["tags"] = v.tags; j["type"] = v.type; j["asset"] = v.asset; j["tilePath"] = v.tilePath; j["splashPath"] = v.splashPath; j["shadowPath"] = v.shadowPath; j["upgradeLootName"] = v.upgradeLootName; j["upgradeEssenceName"] = v.upgradeEssenceName; j["disenchantLootName"] = v.disenchantLootName; j["itemStatus"] = v.itemStatus; j["parentItemStatus"] = v.parentItemStatus; j["redeemableStatus"] = v.redeemableStatus; j["count"] = v.count; j["rentalGames"] = v.rentalGames; j["storeItemId"] = v.storeItemId; j["parentStoreItemId"] = v.parentStoreItemId; j["value"] = v.value; j["upgradeEssenceValue"] = v.upgradeEssenceValue; j["disenchantValue"] = v.disenchantValue; j["expiryTime"] = v.expiryTime; j["rentalSeconds"] = v.rentalSeconds; j["isNew"] = v.isNew; j["isRental"] = v.isRental; } inline void from_json(const json& j, LolLootPlayerLoot& v) { v.lootName = j.at("lootName").get<std::string>(); v.lootId = j.at("lootId").get<std::string>(); v.refId = j.at("refId").get<std::string>(); v.localizedName = j.at("localizedName").get<std::string>(); v.localizedDescription = j.at("localizedDescription").get<std::string>(); v.itemDesc = j.at("itemDesc").get<std::string>(); v.displayCategories = j.at("displayCategories").get<std::string>(); v.rarity = j.at("rarity").get<std::string>(); v.tags = j.at("tags").get<std::string>(); v.type = j.at("type").get<std::string>(); v.asset = j.at("asset").get<std::string>(); v.tilePath = j.at("tilePath").get<std::string>(); v.splashPath = j.at("splashPath").get<std::string>(); v.shadowPath = j.at("shadowPath").get<std::string>(); v.upgradeLootName = j.at("upgradeLootName").get<std::string>(); v.upgradeEssenceName = j.at("upgradeEssenceName").get<std::string>(); v.disenchantLootName = j.at("disenchantLootName").get<std::string>(); v.itemStatus = j.at("itemStatus").get<LolLootItemOwnershipStatus>(); v.parentItemStatus = j.at("parentItemStatus").get<LolLootItemOwnershipStatus>(); v.redeemableStatus = j.at("redeemableStatus").get<LolLootRedeemableStatus>(); v.count = j.at("count").get<int32_t>(); v.rentalGames = j.at("rentalGames").get<int32_t>(); v.storeItemId = j.at("storeItemId").get<int32_t>(); v.parentStoreItemId = j.at("parentStoreItemId").get<int32_t>(); v.value = j.at("value").get<int32_t>(); v.upgradeEssenceValue = j.at("upgradeEssenceValue").get<int32_t>(); v.disenchantValue = j.at("disenchantValue").get<int32_t>(); v.expiryTime = j.at("expiryTime").get<int64_t>(); v.rentalSeconds = j.at("rentalSeconds").get<int64_t>(); v.isNew = j.at("isNew").get<bool>(); v.isRental = j.at("isRental").get<bool>(); } }
40.619048
85
0.652052
Maufeat
e49ba1239d6b3154853f8ef12232d790e217f69f
16,006
cpp
C++
implementations/ugene/src/plugins/kraken_support/src/KrakenBuildWorkerFactory.cpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
implementations/ugene/src/plugins/kraken_support/src/KrakenBuildWorkerFactory.cpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
implementations/ugene/src/plugins/kraken_support/src/KrakenBuildWorkerFactory.cpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2020 UniPro <ugene@unipro.ru> * http://ugene.net * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include <limits> #include <QThread> #include <U2Core/AppContext.h> #include <U2Core/AppResources.h> #include <U2Core/AppSettings.h> #include <U2Designer/DelegateEditors.h> #include <U2Lang/ActorPrototypeRegistry.h> #include <U2Lang/BaseSlots.h> #include <U2Lang/BaseTypes.h> #include <U2Lang/URLAttribute.h> #include <U2Lang/WorkflowEnv.h> #include "../../ngs_reads_classification/src/GenomicLibraryDelegate.h" #include "../../ngs_reads_classification/src/NgsReadsClassificationPlugin.h" #include "KrakenBuildPrompter.h" #include "KrakenBuildValidator.h" #include "KrakenBuildWorker.h" #include "KrakenBuildWorkerFactory.h" #include "KrakenSupport.h" namespace U2 { namespace LocalWorkflow { const QString KrakenBuildWorkerFactory::ACTOR_ID = "kraken-build"; const QString KrakenBuildWorkerFactory::OUTPUT_PORT_ID = "out"; const QString KrakenBuildWorkerFactory::MODE_ATTR_ID = "mode"; const QString KrakenBuildWorkerFactory::INPUT_DATABASE_NAME_ATTR_ID = "input-database"; const QString KrakenBuildWorkerFactory::NEW_DATABASE_NAME_ATTR_ID = "database"; const QString KrakenBuildWorkerFactory::GENOMIC_LIBRARY_ATTR_ID = "genomic-library"; const QString KrakenBuildWorkerFactory::NUMBER_OF_K_MERS_ATTR_ID = "number-of-k-mers"; const QString KrakenBuildWorkerFactory::K_MER_LENGTH_ATTR_ID = "k-mer-length"; const QString KrakenBuildWorkerFactory::MINIMIZER_LENGTH_ATTR_ID = "minimizer-length"; const QString KrakenBuildWorkerFactory::MAXIMUM_DATABASE_SIZE_ATTR_ID = "maximum-database-size"; const QString KrakenBuildWorkerFactory::SHRINK_BLOCK_OFFSET_ATTR_ID = "shrink-block-offset"; const QString KrakenBuildWorkerFactory::CLEAN_ATTR_ID = "clean"; const QString KrakenBuildWorkerFactory::WORK_ON_DISK_ATTR_ID = "work-on-disk"; const QString KrakenBuildWorkerFactory::JELLYFISH_HASH_SIZE_ATTR_ID = "jellyfish-hash-size"; const QString KrakenBuildWorkerFactory::THREADS_NUMBER_ATTR_ID = "threads"; KrakenBuildWorkerFactory::KrakenBuildWorkerFactory() : DomainFactory(ACTOR_ID) { } Worker *KrakenBuildWorkerFactory::createWorker(Actor *actor) { return new KrakenBuildWorker(actor); } void KrakenBuildWorkerFactory::init() { QList<PortDescriptor *> ports; { Descriptor outSlotDesc(BaseSlots::URL_SLOT().getId(), KrakenBuildPrompter::tr("Output URL"), KrakenBuildPrompter::tr("Output URL.")); QMap<Descriptor, DataTypePtr> outType; outType[outSlotDesc] = BaseTypes::STRING_TYPE(); Descriptor outPortDesc(OUTPUT_PORT_ID, KrakenBuildPrompter::tr("Output Kraken database"), KrakenBuildPrompter::tr("URL to the folder with the Kraken database.")); ports << new PortDescriptor(outPortDesc, DataTypePtr(new MapDataType(ACTOR_ID + "-out", outType)), false /*input*/, true /*multi*/); } QList<Attribute *> attributes; { Descriptor modeDesc(MODE_ATTR_ID, KrakenBuildPrompter::tr("Mode"), KrakenBuildPrompter::tr("Select \"Build\" to create a new database from a genomic library (--build).<br><br>" "Select \"Shrink\" to shrink an existing database to have only specified number of k-mers (--shrink).")); Descriptor inputDatabaseNameDesc(INPUT_DATABASE_NAME_ATTR_ID, KrakenBuildPrompter::tr("Input database"), KrakenBuildPrompter::tr("Name of the input database that should be shrunk (corresponds to --db that is used with --shrink).")); Descriptor newDatabaseNameDesc(NEW_DATABASE_NAME_ATTR_ID, KrakenBuildPrompter::tr("Database"), KrakenBuildPrompter::tr("Name of the output Kraken database (corresponds to --db that is used with --build, and to --new-db that is used with --shrink).")); Descriptor genomicLibraryDesc(GENOMIC_LIBRARY_ATTR_ID, KrakenBuildPrompter::tr("Genomic library"), KrakenBuildPrompter::tr("Genomes that should be used to build the database.<br><br>" "The genomes should be specified in FASTA format. The sequence IDs must contain either a GI number or a taxonomy ID (see documentation for details).")); Descriptor numberOfKmersDesc(NUMBER_OF_K_MERS_ATTR_ID, KrakenBuildPrompter::tr("Number of k-mers"), KrakenBuildPrompter::tr("The new database will contain the specified number of k-mers selected from across the input database.")); Descriptor kMerLengthDesc(K_MER_LENGTH_ATTR_ID, KrakenBuildPrompter::tr("K-mer length"), KrakenBuildPrompter::tr("K-mer length in bp (--kmer-len).")); Descriptor minimizerLengthDesc(MINIMIZER_LENGTH_ATTR_ID, KrakenBuildPrompter::tr("Minimizer length"), KrakenBuildPrompter::tr("Minimizer length in bp (--minimizer-len).<br><br>" "The minimizers serve to keep k-mers that are adjacent in query sequences close to each other in the database, which allows Kraken to exploit the CPU cache.<br><br>" "Changing the value of the parameter can significantly affect the speed of Kraken, and neither increasing nor decreasing of the value will guarantee faster or slower speed.")); Descriptor maximumDatabaseSizeDesc(MAXIMUM_DATABASE_SIZE_ATTR_ID, KrakenBuildPrompter::tr("Maximum database size"), KrakenBuildPrompter::tr("By default, a full database build is done.<br><br>" "To shrink the database before the full build, input the size of the database in Mb " "(this corresponds to the --max-db-size parameter, but Mb is used instead of Gb). " "The size is specified together for the database and the index.")); Descriptor shrinkBlockOffsetDesc(SHRINK_BLOCK_OFFSET_ATTR_ID, KrakenBuildPrompter::tr("Shrink block offset"), KrakenBuildPrompter::tr("When shrinking, select the k-mer that is NUM positions from the end of a block of k-mers (--shrink-block-offset).")); Descriptor cleanDesc(CLEAN_ATTR_ID, KrakenBuildPrompter::tr("Clean"), KrakenBuildPrompter::tr("Remove unneeded files from a built database to reduce the disk usage (--clean).")); Descriptor workOnDiskDesc(WORK_ON_DISK_ATTR_ID, KrakenBuildPrompter::tr("Work on disk"), KrakenBuildPrompter::tr("Perform most operations on disk rather than in RAM (this will slow down build in most cases).")); Descriptor jellyfishHashSizeDesc(JELLYFISH_HASH_SIZE_ATTR_ID, KrakenBuildPrompter::tr("Jellyfish hash size"), KrakenBuildPrompter::tr("The \"kraken-build\" tool uses the \"jellyfish\" tool. This parameter specifies the hash size for Jellyfish.<br><br>" "Supply a smaller hash size to Jellyfish, if you encounter problems with allocating enough memory during the build process (--jellyfish-hash-size).<br><br>" "By default, the parameter is not used.")); Descriptor threadNumberDesc(THREADS_NUMBER_ATTR_ID, KrakenBuildPrompter::tr("Number of threads"), KrakenBuildPrompter::tr("Use multiple threads (--threads).")); Attribute *modeAttribute = new Attribute(modeDesc, BaseTypes::STRING_TYPE(), false, KrakenBuildTaskSettings::BUILD); Attribute *inputDatabaseNameAttribute = new Attribute(inputDatabaseNameDesc, BaseTypes::STRING_TYPE(), true); Attribute *newDatabaseName = new Attribute(newDatabaseNameDesc, BaseTypes::STRING_TYPE(), true); Attribute *genomicLibraryAttribute = new Attribute(genomicLibraryDesc, BaseTypes::URL_DATASETS_TYPE(), true); Attribute *numberOfKmersAttribute = new Attribute(numberOfKmersDesc, BaseTypes::NUM_TYPE(), true, 10000); Attribute *kMerLengthAttribute = new Attribute(kMerLengthDesc, BaseTypes::NUM_TYPE(), false, 31); Attribute *minimizerLengthAttribute = new Attribute(minimizerLengthDesc, BaseTypes::NUM_TYPE(), false, 15); ; Attribute *maximumDatabaseSizeAttribute = new Attribute(maximumDatabaseSizeDesc, BaseTypes::NUM_TYPE(), false, 0); Attribute *shrinkBlockOffsetAttribute = new Attribute(shrinkBlockOffsetDesc, BaseTypes::NUM_TYPE(), false, 1); Attribute *cleanAttribute = new Attribute(cleanDesc, BaseTypes::BOOL_TYPE(), false, true); Attribute *workOnDiskAttribute = new Attribute(workOnDiskDesc, BaseTypes::BOOL_TYPE(), false, false); Attribute *jellyfishHashSizeAttribute = new Attribute(jellyfishHashSizeDesc, BaseTypes::NUM_TYPE(), false, 0); Attribute *threadNumberAttribute = new Attribute(threadNumberDesc, BaseTypes::NUM_TYPE(), false, AppContext::getAppSettings()->getAppResourcePool()->getIdealThreadCount()); attributes << modeAttribute; attributes << inputDatabaseNameAttribute; attributes << newDatabaseName; attributes << genomicLibraryAttribute; attributes << numberOfKmersAttribute; attributes << kMerLengthAttribute; attributes << minimizerLengthAttribute; attributes << maximumDatabaseSizeAttribute; attributes << shrinkBlockOffsetAttribute; attributes << cleanAttribute; attributes << workOnDiskAttribute; attributes << jellyfishHashSizeAttribute; attributes << threadNumberAttribute; inputDatabaseNameAttribute->addRelation(new VisibilityRelation(MODE_ATTR_ID, KrakenBuildTaskSettings::SHRINK)); genomicLibraryAttribute->addRelation(new VisibilityRelation(MODE_ATTR_ID, KrakenBuildTaskSettings::BUILD)); numberOfKmersAttribute->addRelation(new VisibilityRelation(MODE_ATTR_ID, KrakenBuildTaskSettings::SHRINK)); maximumDatabaseSizeAttribute->addRelation(new VisibilityRelation(MODE_ATTR_ID, KrakenBuildTaskSettings::BUILD)); shrinkBlockOffsetAttribute->addRelation(new VisibilityRelation(MODE_ATTR_ID, KrakenBuildTaskSettings::SHRINK)); cleanAttribute->addRelation(new VisibilityRelation(MODE_ATTR_ID, KrakenBuildTaskSettings::BUILD)); jellyfishHashSizeAttribute->addRelation(new VisibilityRelation(MODE_ATTR_ID, KrakenBuildTaskSettings::BUILD)); } QMap<QString, PropertyDelegate *> delegates; { QVariantMap modeValues; modeValues[KrakenSupport::tr("Build")] = KrakenBuildTaskSettings::BUILD; modeValues[KrakenSupport::tr("Shrink")] = KrakenBuildTaskSettings::SHRINK; delegates[MODE_ATTR_ID] = new ComboBoxDelegate(modeValues); delegates[INPUT_DATABASE_NAME_ATTR_ID] = new URLDelegate("", "kraken/database", false, true, false); const URLDelegate::Options options = URLDelegate::AllowSelectOnlyExistingDir | URLDelegate::SelectFileToSave | URLDelegate::DoNotUseWorkflowOutputFolder; delegates[NEW_DATABASE_NAME_ATTR_ID] = new URLDelegate("", "kraken/database", options); delegates[GENOMIC_LIBRARY_ATTR_ID] = new GenomicLibraryDelegate(); QVariantMap numberOfKmersProperties; numberOfKmersProperties["minimum"] = 1; numberOfKmersProperties["maximum"] = std::numeric_limits<int>::max(); numberOfKmersProperties["accelerated"] = true; delegates[NUMBER_OF_K_MERS_ATTR_ID] = new SpinBoxDelegate(numberOfKmersProperties); QVariantMap kMerLengthProperties; kMerLengthProperties["minimum"] = 3; kMerLengthProperties["maximum"] = 31; delegates[K_MER_LENGTH_ATTR_ID] = new SpinBoxDelegate(kMerLengthProperties); QVariantMap minimizerLengthProperties; minimizerLengthProperties["minimum"] = 1; minimizerLengthProperties["maximum"] = 30; delegates[MINIMIZER_LENGTH_ATTR_ID] = new SpinBoxDelegate(minimizerLengthProperties); QVariantMap maximumDatabaseSizeProperties; maximumDatabaseSizeProperties["minimum"] = 0; maximumDatabaseSizeProperties["maximum"] = std::numeric_limits<int>::max(); maximumDatabaseSizeProperties["suffix"] = " Mb"; maximumDatabaseSizeProperties["specialValueText"] = KrakenBuildPrompter::tr("No limit"); maximumDatabaseSizeProperties["accelerated"] = true; delegates[MAXIMUM_DATABASE_SIZE_ATTR_ID] = new SpinBoxDelegate(maximumDatabaseSizeProperties); QVariantMap shrinkBlockOffsetProperties; shrinkBlockOffsetProperties["minimum"] = 1; shrinkBlockOffsetProperties["maximum"] = std::numeric_limits<int>::max(); delegates[SHRINK_BLOCK_OFFSET_ATTR_ID] = new SpinBoxDelegate(shrinkBlockOffsetProperties); delegates[CLEAN_ATTR_ID] = new ComboBoxWithBoolsDelegate(); delegates[WORK_ON_DISK_ATTR_ID] = new ComboBoxWithBoolsDelegate(); QVariantMap jelyfishHashSizeProperties; jelyfishHashSizeProperties["minimum"] = 0; jelyfishHashSizeProperties["maximum"] = std::numeric_limits<int>::max(); jelyfishHashSizeProperties["suffix"] = " M"; jelyfishHashSizeProperties["specialValueText"] = KrakenBuildPrompter::tr("Skip"); delegates[JELLYFISH_HASH_SIZE_ATTR_ID] = new SpinBoxDelegate(jelyfishHashSizeProperties); QVariantMap threadsNumberProperties; threadsNumberProperties["minimum"] = 1; threadsNumberProperties["maximum"] = QThread::idealThreadCount(); delegates[THREADS_NUMBER_ATTR_ID] = new SpinBoxDelegate(threadsNumberProperties); } Descriptor desc(ACTOR_ID, KrakenBuildPrompter::tr("Build Kraken Database"), KrakenBuildPrompter::tr("Build a Kraken database from a genomic library or shrink a Kraken database.")); ActorPrototype *proto = new IntegralBusActorPrototype(desc, ports, attributes); proto->setEditor(new DelegateEditor(delegates)); proto->setPrompter(new KrakenBuildPrompter(NULL)); proto->addExternalTool(KrakenSupport::BUILD_TOOL_ID); proto->setValidator(new KrakenBuildValidator()); WorkflowEnv::getProtoRegistry()->registerProto(NgsReadsClassificationPlugin::WORKFLOW_ELEMENTS_GROUP, proto); DomainFactory *localDomain = WorkflowEnv::getDomainRegistry()->getById(LocalDomainFactory::ID); localDomain->registerEntry(new KrakenBuildWorkerFactory()); } void KrakenBuildWorkerFactory::cleanup() { delete WorkflowEnv::getProtoRegistry()->unregisterProto(ACTOR_ID); DomainFactory *localDomain = WorkflowEnv::getDomainRegistry()->getById(LocalDomainFactory::ID); delete localDomain->unregisterEntry(ACTOR_ID); } } // namespace LocalWorkflow } // namespace U2
65.868313
310
0.698863
r-barnes
e49e32a2edcd3104e05757da2a954d8d12b00832
2,181
cpp
C++
Raytracer/src/driver.cpp
rickyguerin/Animated-Ray-Tracer
cc1afe776c904b2280e5552f5c4654391658382a
[ "MIT" ]
null
null
null
Raytracer/src/driver.cpp
rickyguerin/Animated-Ray-Tracer
cc1afe776c904b2280e5552f5c4654391658382a
[ "MIT" ]
null
null
null
Raytracer/src/driver.cpp
rickyguerin/Animated-Ray-Tracer
cc1afe776c904b2280e5552f5c4654391658382a
[ "MIT" ]
null
null
null
#include <vector> #include <string> #include <iostream> #include "../header/world.h" #include "../header/camera.h" #include "../header/WorldProgram/cameraProgram.h" // Turn i into a string padded with 0s up to length n std::string padInt(int i, int n) { int numZeros = n - 1; int copy = i / 10; while (copy > 0) { numZeros--; copy /= 10; } std::string pad = ""; pad.append("0000000000", numZeros); return pad + std::to_string(i); } int main() { // Create the World World world(glm::vec3(0.0f, 0.3f, 0.5f)); world.addProgram("world/hextree/ground/bottom/backLeft.triangle"); world.addProgram("world/hextree/ground/bottom/frontLeft.triangle"); world.addProgram("world/hextree/ground/bottom/backRight.triangle"); world.addProgram("world/hextree/ground/bottom/frontRight.triangle"); world.addProgram("world/hextree/ground/bottom/right.triangle"); world.addProgram("world/hextree/ground/bottom/left.triangle"); world.addProgram("world/hextree/ground/top/backLeft.triangle"); world.addProgram("world/hextree/ground/top/frontLeft.triangle"); world.addProgram("world/hextree/ground/top/backRight.triangle"); world.addProgram("world/hextree/ground/top/frontRight.triangle"); world.addProgram("world/hextree/ground/top/right.triangle"); world.addProgram("world/hextree/ground/top/left.triangle"); world.addProgram("world/hextree/ground/walls/front.triangle"); world.addProgram("world/hextree/ground/walls/frontRight.triangle"); world.addProgram("world/hextree/ground/walls/right.triangle"); world.addProgram("world/hextree/br.sphere"); world.addProgram("world/hextree/main.light"); // Read the CameraProgram CameraProgram camProg("world/hextree/main.camera"); // Animation frame information const float fps = 60.0; const float duration = 12.0; const unsigned frames = fps * duration; // Animation timer float time = 3.0; const float spf = duration / frames; // Render frames for (int i = 0; i < frames; i++) { std::cout << "Rendering frame " << padInt(i, 4) << " / " << padInt(frames - 1, 4) << "\n"; camProg.getCamera(time).render(world, "../images/temp/output_" + padInt(i, 4), 2048, 2048, time); time += spf; } return 0; }
30.291667
99
0.715727
rickyguerin
e49f9f60bdb3636f69eff0e4436372a34ed41a15
1,424
cpp
C++
36.cpp
Alex-Amber/LeetCode
c8d09e86cee52648f84ca2afed8dd0f13e51ab58
[ "MIT" ]
null
null
null
36.cpp
Alex-Amber/LeetCode
c8d09e86cee52648f84ca2afed8dd0f13e51ab58
[ "MIT" ]
null
null
null
36.cpp
Alex-Amber/LeetCode
c8d09e86cee52648f84ca2afed8dd0f13e51ab58
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; using ull = uint64_t; using ll = int64_t; using ld = long double; class Solution { public: const int num = 9; const int num_sub = 3; bool isValidSudoku(vector< vector<char> >& board) { bitset<10> record; // Use a bitset to record whether an integer repeats // Check the validality of each row for (int i = 0; i != num; ++i) { record.reset(); for (int j = 0; j != num; ++j) { if (board[i][j] != '.') { int elem = board[i][j] - '0'; if (record.test(elem)) return false; else record.set(elem); } } } // Check the validality of each column for (int j = 0; j != num; ++j) { record.reset(); for (int i = 0; i != num; ++i) { if (board[i][j] != '.') { int elem = board[i][j] - '0'; if (record.test(elem)) return false; else record.set(elem); } } } // Check the validality of each sub grid for (int i = 0; i != num_sub; ++i) { for (int j = 0; j != num_sub; ++j) { record.reset(); for (int m = 0; m != num_sub; ++m) { for (int n = 0; n != num_sub; ++n) { if (board[i * num_sub + m][j * num_sub + n] != '.') { int elem = board[i * num_sub + m][j * num_sub + n] - '0'; if (record.test(elem)) return false; else record.set(elem); } } } } } return true; } };
19.506849
74
0.496489
Alex-Amber
e4a0875f9ff2c13cb24aa40b14e0842a8e73b35b
2,188
cpp
C++
graph_data_analytic/src/randLocalGraph.cpp
bxtx999/gm_scripts
de1e7a7d5717caf09f9b81fd627ac95ab01e1924
[ "MIT" ]
null
null
null
graph_data_analytic/src/randLocalGraph.cpp
bxtx999/gm_scripts
de1e7a7d5717caf09f9b81fd627ac95ab01e1924
[ "MIT" ]
null
null
null
graph_data_analytic/src/randLocalGraph.cpp
bxtx999/gm_scripts
de1e7a7d5717caf09f9b81fd627ac95ab01e1924
[ "MIT" ]
null
null
null
#include "parseCommandLine.h" #include "graphIO.h" #include "utils.h" #include "parallel.h" using namespace benchIO; // Generates an undirected graph with n vertices with approximately degree // neighbors per vertex. // Edges are distributed so they appear to come from // a dim-dimensional space. In particular an edge (i,j) will have // probability roughly proportional to (1/|i-j|)^{(d+1)/d}, giving // separators of size about n^{(d-1)/d}. template<class intT> edgeArray<intT> edgeRandomWithDimension(intT dim, intT nonZeros, intT numRows) { double degree = (double) nonZeros / numRows; edge<intT> *E = newA(edge<intT>, nonZeros); parallel_for (intT k = 0; k < nonZeros; k++) { intT i = k / degree; intT j; if (dim == 0) { uintT h = k; do { j = ((h = hashInt(h)) % numRows); if (j < 0 || j >= numRows) { cout << h << " " << j << endl; abort(); } } while (j == i); } else { intT pow = dim + 2; uintT h = k; do { while ((((h = hashInt(h)) % 1000003) < 500001)) pow += dim; j = (i + ((h = hashInt(h)) % (((long) 1) << pow))) % numRows; } while (j == i); } E[k].u = i; E[k].v = j; } return edgeArray<intT>(E, numRows, numRows, nonZeros); } //Generates a graph with n vertices and m edges, possibly with //duplicates, and then removes duplicate edges and symmetrizes the //graph. int main(int argc, char *argv[]) { commandLine P(argc, argv, "[-s] [-m <numedges>] [-d <dims>] n <outFile>"); std::pair<intT, char *> in = P.sizeAndFileName(); long n = in.first; char *fname = in.second; int dim = P.getOptionIntValue("-d", 0); long m = P.getOptionLongValue("-m", 10 * n); bool sym = P.getOptionValue("-s"); edgeArray<uintT> EA = edgeRandomWithDimension<uintT>(dim, m, n); graph<uintT> G = graphFromEdges<uintT>(EA, sym); EA.del(); writeGraphToFile<uintT>(G, fname); G.del(); return 0; }
35.290323
81
0.531536
bxtx999
e4a0adec3a081726617c249772a237b663b5ac4b
568
hh
C++
src/Zynga/Framework/StorableObject/V1/Test/Mock/Broken/ValidButHasConstructorArgs.hh
chintan-j-patel/zynga-hacklang-framework
d9893b8873e3c8c7223772fd3c94d2531760172a
[ "MIT" ]
19
2018-04-23T09:30:48.000Z
2022-03-06T21:35:18.000Z
src/Zynga/Framework/StorableObject/V1/Test/Mock/Broken/ValidButHasConstructorArgs.hh
chintan-j-patel/zynga-hacklang-framework
d9893b8873e3c8c7223772fd3c94d2531760172a
[ "MIT" ]
22
2017-11-27T23:39:25.000Z
2019-08-09T08:56:57.000Z
src/Zynga/Framework/StorableObject/V1/Test/Mock/Broken/ValidButHasConstructorArgs.hh
chintan-j-patel/zynga-hacklang-framework
d9893b8873e3c8c7223772fd3c94d2531760172a
[ "MIT" ]
28
2017-11-16T20:53:56.000Z
2021-01-04T11:13:17.000Z
<?hh // strict namespace Zynga\Framework\StorableObject\V1\Test\Mock\Broken; use Zynga\Framework\StorableObject\V1\Interfaces\FieldsInterface; use Zynga\Framework\StorableObject\V1\Test\Mock\Valid; class ValidButHasConstructorArgs extends Valid { public function __construct(string $myPrettyArg) { parent::__construct(); // -- // kaboooomski! as the storable objects as a whole don't typically have args, // therefor it will explode when fed to some of the systems that expect to // allocate storable objects with no args. // -- } }
25.818182
81
0.735915
chintan-j-patel
e4a25ae66a4dc49558b76de90781f0583983420d
170
cpp
C++
tutorials/learncpp.com#1.0#1/input_and_output__i_o_/input_with_istream/source8.cpp
officialrafsan/CppDroid
5fb2cc7750fea53b1ea6ff47b5094da6e95e9224
[ "MIT" ]
null
null
null
tutorials/learncpp.com#1.0#1/input_and_output__i_o_/input_with_istream/source8.cpp
officialrafsan/CppDroid
5fb2cc7750fea53b1ea6ff47b5094da6e95e9224
[ "MIT" ]
null
null
null
tutorials/learncpp.com#1.0#1/input_and_output__i_o_/input_with_istream/source8.cpp
officialrafsan/CppDroid
5fb2cc7750fea53b1ea6ff47b5094da6e95e9224
[ "MIT" ]
null
null
null
int main() { char strBuf[100]; cin.getline(strBuf, 100); cout << strBuf << endl; cout << cin.gcount() << " characters were read" << endl; return 0; }
18.888889
60
0.558824
officialrafsan
e4a4bcfee6d925db8fdb261b96b3d77acaa3cb88
771
hpp
C++
libraries/chain/include/scorum/chain/database/process_user_activity.hpp
scorum/scorum
1da00651f2fa14bcf8292da34e1cbee06250ae78
[ "MIT" ]
53
2017-10-28T22:10:35.000Z
2022-02-18T02:20:48.000Z
libraries/chain/include/scorum/chain/database/process_user_activity.hpp
Scorum/Scorum
fb4aa0b0960119b97828865d7a5b4d0409af7876
[ "MIT" ]
38
2017-11-25T09:06:51.000Z
2018-10-31T09:17:22.000Z
libraries/chain/include/scorum/chain/database/process_user_activity.hpp
Scorum/Scorum
fb4aa0b0960119b97828865d7a5b4d0409af7876
[ "MIT" ]
27
2018-01-08T19:43:35.000Z
2022-01-14T10:50:42.000Z
#pragma once #include <scorum/chain/tasks_base.hpp> #include <scorum/protocol/transaction.hpp> #include <scorum/protocol/types.hpp> namespace scorum { namespace chain { namespace database_ns { using scorum::protocol::signed_transaction; class user_activity_context { public: explicit user_activity_context(data_service_factory_i& services, const signed_transaction&); data_service_factory_i& services() const { return _services; } const signed_transaction& transaction() const { return _trx; } private: data_service_factory_i& _services; const signed_transaction& _trx; }; class process_user_activity_task : public task<user_activity_context> { public: void on_apply(user_activity_context& ctx); }; } } }
17.930233
96
0.743191
scorum
e4a5d342c7ead4b2906d5e38b99a3e88b00f9e95
8,876
cc
C++
media/blink/webmediaplayer_util.cc
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
media/blink/webmediaplayer_util.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
media/blink/webmediaplayer_util.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
// 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. #include "media/blink/webmediaplayer_util.h" #include <math.h> #include <stddef.h> #include <string> #include <utility> #include "base/metrics/histogram_macros.h" #include "media/base/bind_to_current_loop.h" #include "media/base/media_client.h" #include "third_party/WebKit/public/platform/URLConversion.h" #include "third_party/WebKit/public/platform/WebMediaPlayerEncryptedMediaClient.h" namespace media { blink::WebTimeRanges ConvertToWebTimeRanges( const Ranges<base::TimeDelta>& ranges) { blink::WebTimeRanges result(ranges.size()); for (size_t i = 0; i < ranges.size(); ++i) { result[i].start = ranges.start(i).InSecondsF(); result[i].end = ranges.end(i).InSecondsF(); } return result; } blink::WebMediaPlayer::NetworkState PipelineErrorToNetworkState( PipelineStatus error) { switch (error) { case PIPELINE_ERROR_NETWORK: case PIPELINE_ERROR_READ: case CHUNK_DEMUXER_ERROR_EOS_STATUS_NETWORK_ERROR: return blink::WebMediaPlayer::NetworkStateNetworkError; case PIPELINE_ERROR_INITIALIZATION_FAILED: case PIPELINE_ERROR_COULD_NOT_RENDER: case PIPELINE_ERROR_EXTERNAL_RENDERER_FAILED: case DEMUXER_ERROR_COULD_NOT_OPEN: case DEMUXER_ERROR_COULD_NOT_PARSE: case DEMUXER_ERROR_NO_SUPPORTED_STREAMS: case DECODER_ERROR_NOT_SUPPORTED: return blink::WebMediaPlayer::NetworkStateFormatError; case PIPELINE_ERROR_DECODE: case PIPELINE_ERROR_ABORT: case PIPELINE_ERROR_INVALID_STATE: case CHUNK_DEMUXER_ERROR_APPEND_FAILED: case CHUNK_DEMUXER_ERROR_EOS_STATUS_DECODE_ERROR: case AUDIO_RENDERER_ERROR: return blink::WebMediaPlayer::NetworkStateDecodeError; case PIPELINE_OK: NOTREACHED() << "Unexpected status! " << error; } return blink::WebMediaPlayer::NetworkStateFormatError; } namespace { // Helper enum for reporting scheme histograms. enum URLSchemeForHistogram { kUnknownURLScheme, kMissingURLScheme, kHttpURLScheme, kHttpsURLScheme, kFtpURLScheme, kChromeExtensionURLScheme, kJavascriptURLScheme, kFileURLScheme, kBlobURLScheme, kDataURLScheme, kFileSystemScheme, kMaxURLScheme = kFileSystemScheme // Must be equal to highest enum value. }; URLSchemeForHistogram URLScheme(const GURL& url) { if (!url.has_scheme()) return kMissingURLScheme; if (url.SchemeIs("http")) return kHttpURLScheme; if (url.SchemeIs("https")) return kHttpsURLScheme; if (url.SchemeIs("ftp")) return kFtpURLScheme; if (url.SchemeIs("chrome-extension")) return kChromeExtensionURLScheme; if (url.SchemeIs("javascript")) return kJavascriptURLScheme; if (url.SchemeIs("file")) return kFileURLScheme; if (url.SchemeIs("blob")) return kBlobURLScheme; if (url.SchemeIs("data")) return kDataURLScheme; if (url.SchemeIs("filesystem")) return kFileSystemScheme; return kUnknownURLScheme; } std::string LoadTypeToString(blink::WebMediaPlayer::LoadType load_type) { switch (load_type) { case blink::WebMediaPlayer::LoadTypeURL: return "SRC"; case blink::WebMediaPlayer::LoadTypeMediaSource: return "MSE"; case blink::WebMediaPlayer::LoadTypeMediaStream: return "MS"; } NOTREACHED(); return "Unknown"; } } // namespace void ReportMetrics(blink::WebMediaPlayer::LoadType load_type, const GURL& url, const blink::WebSecurityOrigin& security_origin) { // Report URL scheme, such as http, https, file, blob etc. UMA_HISTOGRAM_ENUMERATION("Media.URLScheme", URLScheme(url), kMaxURLScheme + 1); // Report load type, such as URL, MediaSource or MediaStream. UMA_HISTOGRAM_ENUMERATION("Media.LoadType", load_type, blink::WebMediaPlayer::LoadTypeMax + 1); // Report the origin from where the media player is created. if (GetMediaClient()) { GURL security_origin_url(url::Origin(security_origin).GetURL()); GetMediaClient()->RecordRapporURL( "Media.OriginUrl." + LoadTypeToString(load_type), security_origin_url); // For MSE, also report usage by secure/insecure origin. if (load_type == blink::WebMediaPlayer::LoadTypeMediaSource) { if (security_origin.isPotentiallyTrustworthy()) { GetMediaClient()->RecordRapporURL("Media.OriginUrl.MSE.Secure", security_origin_url); } else { GetMediaClient()->RecordRapporURL("Media.OriginUrl.MSE.Insecure", security_origin_url); } } } } void ReportPipelineError(blink::WebMediaPlayer::LoadType load_type, const blink::WebSecurityOrigin& security_origin, PipelineStatus error) { DCHECK_NE(PIPELINE_OK, error); // Report the origin from where the media player is created. if (!GetMediaClient()) return; GetMediaClient()->RecordRapporURL( "Media.OriginUrl." + LoadTypeToString(load_type) + ".PipelineError", url::Origin(security_origin).GetURL()); } void RecordOriginOfHLSPlayback(const GURL& origin_url) { if (media::GetMediaClient()) GetMediaClient()->RecordRapporURL("Media.OriginUrl.HLS", origin_url); } EmeInitDataType ConvertToEmeInitDataType( blink::WebEncryptedMediaInitDataType init_data_type) { switch (init_data_type) { case blink::WebEncryptedMediaInitDataType::Webm: return EmeInitDataType::WEBM; case blink::WebEncryptedMediaInitDataType::Cenc: return EmeInitDataType::CENC; case blink::WebEncryptedMediaInitDataType::Keyids: return EmeInitDataType::KEYIDS; case blink::WebEncryptedMediaInitDataType::Unknown: return EmeInitDataType::UNKNOWN; } NOTREACHED(); return EmeInitDataType::UNKNOWN; } blink::WebEncryptedMediaInitDataType ConvertToWebInitDataType( EmeInitDataType init_data_type) { switch (init_data_type) { case EmeInitDataType::WEBM: return blink::WebEncryptedMediaInitDataType::Webm; case EmeInitDataType::CENC: return blink::WebEncryptedMediaInitDataType::Cenc; case EmeInitDataType::KEYIDS: return blink::WebEncryptedMediaInitDataType::Keyids; case EmeInitDataType::UNKNOWN: return blink::WebEncryptedMediaInitDataType::Unknown; } NOTREACHED(); return blink::WebEncryptedMediaInitDataType::Unknown; } namespace { // This class wraps a scoped blink::WebSetSinkIdCallbacks pointer such that // copying objects of this class actually performs moving, thus // maintaining clear ownership of the blink::WebSetSinkIdCallbacks pointer. // The rationale for this class is that the SwichOutputDevice method // can make a copy of its base::Callback parameter, which implies // copying its bound parameters. // SwitchOutputDevice actually wants to move its base::Callback // parameter since only the final copy will be run, but base::Callback // does not support move semantics and there is no base::MovableCallback. // Since scoped pointers are not copyable, we cannot bind them directly // to a base::Callback in this case. Thus, we use this helper class, // whose copy constructor transfers ownership of the scoped pointer. class SetSinkIdCallback { public: explicit SetSinkIdCallback(blink::WebSetSinkIdCallbacks* web_callback) : web_callback_(web_callback) {} SetSinkIdCallback(const SetSinkIdCallback& other) : web_callback_(std::move(other.web_callback_)) {} ~SetSinkIdCallback() {} friend void RunSetSinkIdCallback(const SetSinkIdCallback& callback, OutputDeviceStatus result); private: // Mutable is required so that Pass() can be called in the copy // constructor. mutable std::unique_ptr<blink::WebSetSinkIdCallbacks> web_callback_; }; void RunSetSinkIdCallback(const SetSinkIdCallback& callback, OutputDeviceStatus result) { if (!callback.web_callback_) return; switch (result) { case OUTPUT_DEVICE_STATUS_OK: callback.web_callback_->onSuccess(); break; case OUTPUT_DEVICE_STATUS_ERROR_NOT_FOUND: callback.web_callback_->onError(blink::WebSetSinkIdError::NotFound); break; case OUTPUT_DEVICE_STATUS_ERROR_NOT_AUTHORIZED: callback.web_callback_->onError(blink::WebSetSinkIdError::NotAuthorized); break; case OUTPUT_DEVICE_STATUS_ERROR_INTERNAL: callback.web_callback_->onError(blink::WebSetSinkIdError::Aborted); break; default: NOTREACHED(); } callback.web_callback_ = nullptr; } } // namespace OutputDeviceStatusCB ConvertToOutputDeviceStatusCB( blink::WebSetSinkIdCallbacks* web_callbacks) { return media::BindToCurrentLoop( base::Bind(RunSetSinkIdCallback, SetSinkIdCallback(web_callbacks))); } } // namespace media
34.403101
82
0.7331
google-ar
e4a6bcf445420fa1c711a231504e125773cfe241
3,731
cpp
C++
examples/imagestack/imagestack.cpp
kraj/egt
7065fd97e8bc61b0b0555bd48461ac9b2160ac7a
[ "Apache-2.0" ]
null
null
null
examples/imagestack/imagestack.cpp
kraj/egt
7065fd97e8bc61b0b0555bd48461ac9b2160ac7a
[ "Apache-2.0" ]
null
null
null
examples/imagestack/imagestack.cpp
kraj/egt
7065fd97e8bc61b0b0555bd48461ac9b2160ac7a
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2018 Microchip Technology Inc. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 */ #include <egt/detail/imagecache.h> #include <egt/ui> #include <memory> #include <string> #include <vector> using namespace egt; class MainWindow : public TopWindow { public: class LauncherItem : public Frame { public: LauncherItem(const Image& image) : m_background(image) { set_boxtype(Theme::boxtype::none); flags().set(Widget::flag::no_layout); m_background.set_align(alignmask::expand); m_background.set_image_align(alignmask::expand); add(m_background); } private: ImageLabel m_background; }; MainWindow() { set_background(Image("background.png")); auto egt_logo = std::make_shared<ImageLabel>(Image("@128px/egt_logo_black.png")); egt_logo->set_align(alignmask::center | alignmask::top); egt_logo->set_margin(5); add(egt_logo); m_animation.set_starting(0); m_animation.set_duration(std::chrono::seconds(2)); m_animation.set_easing_func(easing_cubic_easeout); m_animation.on_change(std::bind(&MainWindow::move_boxes, this, std::placeholders::_1)); m_seq.add(m_delay); m_seq.add(m_animation); load(); } void handle(Event& event) override { TopWindow::handle(event); switch (event.id()) { case eventid::pointer_drag_start: m_seq.reset(); if (!m_boxes.empty()) m_start = m_boxes.front()->x(); break; case eventid::pointer_drag: move_boxes(event.pointer().point.x() - event.pointer().drag_start.x()); event.stop(); break; case eventid::pointer_drag_stop: if (!m_boxes.empty()) { m_start = m_boxes.front()->x(); m_animation.set_ending(width() - m_boxes.front()->width() - m_boxes.front()->x()); m_seq.start(); } break; default: break; } } void move_boxes(int diff = 0) { if (m_boxes.empty()) return; const auto& last = m_boxes.back(); if (diff < 0 && last->x() <= center().x()) return; auto x = m_start + diff; for (auto& box : m_boxes) { if (x + box->width() > width()) x = width() - box->width(); box->set_x(x); x += box->width() + 10; } } private: void load() { for (auto x = 0; x < 9; x++) { auto image = Image("image" + std::to_string(x) + ".png"); auto box = std::make_shared<LauncherItem>(image); box->resize(Size(width() / 4, height() - 100)); m_boxes.push_back(box); } for (auto& box : detail::reverse_iterate(m_boxes)) { box->set_y(center().y() - box->height() / 2); box->set_x(width() - box->width()); add(box); } if (!m_boxes.empty()) { m_start = m_boxes.front()->x(); move_boxes(); } } std::vector<std::shared_ptr<LauncherItem>> m_boxes; int m_start{0}; AnimationSequence m_seq; AnimationDelay m_delay{std::chrono::seconds(2)}; PropertyAnimator m_animation; }; int main(int argc, const char** argv) { Application app(argc, argv, "imagestack"); detail::add_search_path("images/"); MainWindow window; window.show(); return app.run(); }
25.209459
98
0.523184
kraj
e4aa7bc5caa16ee5b317585d134715ca1860f424
1,997
cpp
C++
data_structure/DISJOINT.cpp
searchstar2017/acmtool
03392b8909a3d45f10c2711ca4ad9ba69f64a481
[ "MIT" ]
null
null
null
data_structure/DISJOINT.cpp
searchstar2017/acmtool
03392b8909a3d45f10c2711ca4ad9ba69f64a481
[ "MIT" ]
null
null
null
data_structure/DISJOINT.cpp
searchstar2017/acmtool
03392b8909a3d45f10c2711ca4ad9ba69f64a481
[ "MIT" ]
null
null
null
struct DISJOINT { //static const int maxn = MAXN; int s[maxn]; void Init(int n){ memset(s, -1, (n+1) * sizeof(s[0])); } int FindRoot(int a){ return s[a] < 0 ? a : (s[a] = FindRoot(s[a])); } void Union(int a, int b){ UnionRoot(FindRoot(a), FindRoot(b)); } void UnionRoot(int a, int b){ if(a == b)return; if(s[a] > s[b]) swap(a,b); s[a] += s[b]; s[b] = a; } }; //simple struct DISJOINT{ int s[MAXN_DISJOINT]; void Init(int n){ memset(s, -1, (n+1) * sizeof(s[0])); } int FindRoot(int a){ int b = a; while(s[a] >= 0) a = s[a]; while(s[b] >= 0){ int tmp = s[b]; s[b] = a; b = tmp; } return a; } void UnionRoot(int a, int b){ if(a != b) s[b] = a; } void Union(int a, int b){ UnionRoot(FindRoot(a), FindRoot(b)); } }; //DISJOINT with value template<typename DistType> struct DISJOINT_VAL{ int s[MAX_NODE_DISJOINT_VAL]; DistType d[MAX_NODE_DISJOINT_VAL]; void Init(int n){ memset(s, -1, (n+1) * sizeof(s[0])); memset(d, 0, (n+1) * sizeof(d[0])); } DistType RootDist(int& a){ int b = a; DistType sum_d = 0; DistType pre_d = 0; while(s[a] >= 0){ sum_d += d[a]; a = s[a]; } while(b != a){ int tmp = s[b]; s[b] = a; DistType tmp_d = d[b]; d[b] = sum_d - pre_d; pre_d += tmp_d; b = tmp; } return sum_d; } //d_ba means the distance from b to a //Assume that a != b void UnionRoot(int a, int b, DistType d_ba){ s[b] = a; d[b] = d_ba; } void Union(int a, int b, DistType d_ba){ DistType d_a = RootDist(a); DistType d_b = RootDist(b); UnionRoot(a, b, d_a + d_ba - d_b); } };
21.706522
54
0.440661
searchstar2017
e4ac414390032b70b006dead5f56634170460fae
13,994
hpp
C++
Metrics/test/head/TestMetricsInitializer.hpp
guillaumetousignant/euler3D
7bdfaae7f6b774232b6fc9f83d40a67ccee9a8ae
[ "MIT" ]
1
2019-02-11T00:45:37.000Z
2019-02-11T00:45:37.000Z
Metrics/test/head/TestMetricsInitializer.hpp
guillaumetousignant/euler3D
7bdfaae7f6b774232b6fc9f83d40a67ccee9a8ae
[ "MIT" ]
null
null
null
Metrics/test/head/TestMetricsInitializer.hpp
guillaumetousignant/euler3D
7bdfaae7f6b774232b6fc9f83d40a67ccee9a8ae
[ "MIT" ]
null
null
null
#define CATCH_CONFIG_MAIN #include <catch.hpp> //Project files #include "Block.h" #include "MetricsInitializer.h" //using namespace std; void buildConnectivity(Block *iBlock) { uint nbCells = 1; uint nbCellsTot = 6; uint nbFacesTot = 5; uint nbNodesTot = 5; iBlock->n_real_cells_in_block_ = nbCells; iBlock->n_all_cells_in_block_ = nbCellsTot; iBlock->n_faces_in_block_ = nbFacesTot; iBlock->n_nodes_in_block_ = nbNodesTot; iBlock->block_cells_ = new Cell*[nbCellsTot]; iBlock->block_faces_ = new Face*[nbFacesTot]; iBlock->block_nodes_ = new Node*[nbNodesTot]; for(uint i(0);i < nbCellsTot;i++) { iBlock->block_cells_[i] = new Cell; } for(uint i(0);i < nbFacesTot;i++) { iBlock->block_faces_[i] = new Face; } for(uint i(0);i < nbNodesTot;i++) { iBlock->block_nodes_[i] = new Node; } iBlock->block_cells_[0]->n_faces_per_cell_ = nbFacesTot; iBlock->block_cells_[0]->n_nodes_per_cell_ = nbNodesTot; //Init nb of faces for each ghots cells for(uint i(1);i < nbCellsTot;i++) { iBlock->block_cells_[i]->n_faces_per_cell_ = 1; } //Init Cell block connectivity internal uint cell2cell_size = 1; iBlock->block_cells_[0]->cell_2_cells_connectivity_ = new int[cell2cell_size]; iBlock->block_cells_[0]->cell_2_cells_connectivity_[0] = 0; iBlock->block_cells_[0]->cell_2_faces_connectivity_ = new int[nbFacesTot]; iBlock->block_cells_[0]->cell_2_faces_connectivity_[0] = 0; iBlock->block_cells_[0]->cell_2_faces_connectivity_[1] = 1; iBlock->block_cells_[0]->cell_2_faces_connectivity_[2] = 2; iBlock->block_cells_[0]->cell_2_faces_connectivity_[3] = 3; iBlock->block_cells_[0]->cell_2_faces_connectivity_[4] = 4; iBlock->block_cells_[0]->cell_2_nodes_connectivity_ = new int[nbNodesTot]; iBlock->block_cells_[0]->cell_2_nodes_connectivity_[0] = 0; iBlock->block_cells_[0]->cell_2_nodes_connectivity_[1] = 1; iBlock->block_cells_[0]->cell_2_nodes_connectivity_[2] = 2; iBlock->block_cells_[0]->cell_2_nodes_connectivity_[3] = 3; iBlock->block_cells_[0]->cell_2_nodes_connectivity_[4] = 4; //Init ghost connectivity uint nbCell2CellGhost = 1; uint nbFacesPerGhost = 1; for(uint i(1);i < nbCellsTot;i++) { iBlock->block_cells_[i]->cell_2_cells_connectivity_ = new int[nbCell2CellGhost]; iBlock->block_cells_[i]->cell_2_cells_connectivity_[0] = 0; iBlock->block_cells_[i]->cell_2_faces_connectivity_ = new int[nbFacesPerGhost]; iBlock->block_cells_[i]->cell_2_faces_connectivity_[0] = (i - 1); } //Setting nb of nodes for all faces const uint nbNodesTriangle = 3; const uint nbNodesSquare = 4; for(uint i(0);i < nbFacesTot - 1;i++) iBlock->block_faces_[i]->n_nodes_per_face_ = nbNodesTriangle; // Triangles iBlock->block_faces_[nbFacesTot - 1]->n_nodes_per_face_ = nbNodesSquare; //Square int face2cells_[5][2]; // 5 is nbFacesTot face2cells_[0][0] = 0; face2cells_[0][1] = 1; face2cells_[1][0] = 0; face2cells_[1][1] = 2; face2cells_[2][0] = 0; face2cells_[2][1] = 3; face2cells_[3][0] = 0; face2cells_[3][1] = 4; face2cells_[4][0] = 0; face2cells_[4][1] = 5; for(uint i(0);i < nbFacesTot;i++) { iBlock->block_faces_[i]->face_2_cells_connectivity_ = new int[2]; for(int j(0);j < 2;j++) { int value = face2cells_[i][j]; iBlock->block_faces_[i]->face_2_cells_connectivity_[j] = value; } } //First face iBlock->block_faces_[0]->face_2_nodes_connectivity_ = new int[nbNodesTriangle]; iBlock->block_faces_[0]->face_2_nodes_connectivity_[0] = 0; iBlock->block_faces_[0]->face_2_nodes_connectivity_[1] = 1; iBlock->block_faces_[0]->face_2_nodes_connectivity_[2] = 4; //Second face iBlock->block_faces_[1]->face_2_nodes_connectivity_ = new int[nbNodesTriangle]; iBlock->block_faces_[1]->face_2_nodes_connectivity_[0] = 1; iBlock->block_faces_[1]->face_2_nodes_connectivity_[1] = 2; iBlock->block_faces_[1]->face_2_nodes_connectivity_[2] = 4; //Third face iBlock->block_faces_[2]->face_2_nodes_connectivity_ = new int[nbNodesTriangle]; iBlock->block_faces_[2]->face_2_nodes_connectivity_[0] = 2; iBlock->block_faces_[2]->face_2_nodes_connectivity_[1] = 3; iBlock->block_faces_[2]->face_2_nodes_connectivity_[2] = 4; //Fourth face iBlock->block_faces_[3]->face_2_nodes_connectivity_ = new int[nbNodesTriangle]; iBlock->block_faces_[3]->face_2_nodes_connectivity_[0] = 3; iBlock->block_faces_[3]->face_2_nodes_connectivity_[1] = 0; iBlock->block_faces_[3]->face_2_nodes_connectivity_[2] = 4; //Fifth face iBlock->block_faces_[4]->face_2_nodes_connectivity_ = new int[nbNodesSquare]; iBlock->block_faces_[4]->face_2_nodes_connectivity_[0] = 0; iBlock->block_faces_[4]->face_2_nodes_connectivity_[1] = 3; iBlock->block_faces_[4]->face_2_nodes_connectivity_[2] = 2; iBlock->block_faces_[4]->face_2_nodes_connectivity_[3] = 1; int node2cells[1] = {0}; for(int i(0);i < iBlock->n_nodes_in_block_;i++) iBlock->block_nodes_[i]->node_2_cells_connectivity_ = node2cells; iBlock->block_nodes_[0]->node_coordinates_[0] = 1.0; iBlock->block_nodes_[0]->node_coordinates_[1] = 0.0; iBlock->block_nodes_[0]->node_coordinates_[2] = 0.0; iBlock->block_nodes_[1]->node_coordinates_[0] = 0.0; iBlock->block_nodes_[1]->node_coordinates_[1] = 1.0; iBlock->block_nodes_[1]->node_coordinates_[2] = 0.0; iBlock->block_nodes_[2]->node_coordinates_[0] = -1.0; iBlock->block_nodes_[2]->node_coordinates_[1] = 0.0; iBlock->block_nodes_[2]->node_coordinates_[2] = 0.0; iBlock->block_nodes_[3]->node_coordinates_[0] = 0.0; iBlock->block_nodes_[3]->node_coordinates_[1] = -1.0; iBlock->block_nodes_[3]->node_coordinates_[2] = 0.0; iBlock->block_nodes_[4]->node_coordinates_[0] = 0.0; iBlock->block_nodes_[4]->node_coordinates_[1] = 0.0; iBlock->block_nodes_[4]->node_coordinates_[2] = 2.0; } void tearDown(Block *iBlock) { uint nbCellsTot = 6; uint nbFacesTot = 5; for(uint i(0);i < nbCellsTot;i++) { delete [] iBlock->block_cells_[i]->cell_2_cells_connectivity_; delete [] iBlock->block_cells_[i]->cell_2_faces_connectivity_; } delete [] iBlock->block_cells_[0]->cell_2_nodes_connectivity_; for(uint i(0);i < nbFacesTot;i++) { delete [] iBlock->block_faces_[i]->face_2_cells_connectivity_; delete [] iBlock->block_faces_[i]->face_2_nodes_connectivity_; } delete [] iBlock->block_cells_; delete [] iBlock->block_faces_; delete [] iBlock->block_nodes_; } TEST_CASE( "TestComputeCenterCells", "Prove that center cells are well defined" ) { int blockId = 0; Block *blockData = new Block(blockId); buildConnectivity(blockData); MetricsInitializer *metricsInit = new MetricsInitializer(blockData); metricsInit->doInit(); double centerCoord[3] = {0.0,0.0,0.4}; double resCenterCoord[3] = {0.0, 0.0, 0.0}; /* In comment because the method of center cell computing has changed //Test for internal cell and ghost cells for(int i(0);i < blockData->n_all_cells_in_block_;i++) { resCenterCoord[0] = blockData->block_cells_[i]->cell_coordinates_[0]; resCenterCoord[1] = blockData->block_cells_[i]->cell_coordinates_[1]; resCenterCoord[2] = blockData->block_cells_[i]->cell_coordinates_[2]; REQUIRE(centerCoord[0] == resCenterCoord[0]); REQUIRE(centerCoord[1] == resCenterCoord[1]); REQUIRE(centerCoord[2] == resCenterCoord[2]); } */ tearDown(blockData); delete blockData; blockData = nullptr; delete metricsInit; metricsInit = nullptr; } TEST_CASE("TestComputeCenterFaces", "Prove that center of faces are correct") { int blockId = 0; Block *blockData = new Block(blockId); buildConnectivity(blockData); MetricsInitializer *metricsInit = new MetricsInitializer(blockData); metricsInit->doInit(); int const nbNodesTriangle = 3; int const nbNodesRect = 4; double centerFace1[nbNodesTriangle]; double centerFace2[nbNodesTriangle]; double centerFace3[nbNodesTriangle]; double centerFace4[nbNodesTriangle]; double centerFace5[nbNodesRect]; double epsilon = 0.01; centerFace1[0] = 0.33; centerFace1[1] = 0.33; centerFace1[2] = 0.67; for(int i(0);i<nbNodesTriangle;i++) { REQUIRE(blockData->block_faces_[0]->face_center_[i] <= centerFace1[i] + epsilon); REQUIRE(blockData->block_faces_[0]->face_center_[i] >= centerFace1[i] - epsilon); } centerFace2[0] = -0.33; centerFace2[1] = 0.33; centerFace2[2] = 0.67; for(int i(0);i<nbNodesTriangle;i++) { REQUIRE(blockData->block_faces_[1]->face_center_[i] <= centerFace2[i] + epsilon); REQUIRE(blockData->block_faces_[1]->face_center_[i] >= centerFace2[i] - epsilon); } centerFace3[0] = -0.33; centerFace3[1] = -0.33; centerFace3[2] = 0.67; for(int i(0);i<nbNodesTriangle;i++) { REQUIRE(blockData->block_faces_[2]->face_center_[i] <= centerFace3[i] + epsilon); REQUIRE(blockData->block_faces_[2]->face_center_[i] >= centerFace3[i] - epsilon); } centerFace4[0] = 0.33; centerFace4[1] = -0.33; centerFace4[2] = 0.67; for(int i(0);i<nbNodesTriangle;i++) { REQUIRE(blockData->block_faces_[3]->face_center_[i] <= centerFace4[i] + epsilon); REQUIRE(blockData->block_faces_[3]->face_center_[i] >= centerFace4[i] - epsilon); } centerFace5[0] = 0.0; centerFace5[1] = 0.0; centerFace5[2] = 0.0; centerFace5[3] = 0.0; for(int i(0);i<nbNodesTriangle;i++) { REQUIRE(blockData->block_faces_[4]->face_center_[i] <= centerFace5[i] + epsilon); REQUIRE(blockData->block_faces_[4]->face_center_[i] >= centerFace5[i] - epsilon); } tearDown(blockData); delete blockData; blockData = nullptr; delete metricsInit; metricsInit = nullptr; } TEST_CASE( "TestComputeNormals", "Prove that normals of each faces are well defined" ) { int blockId = 0; Block *blockData = new Block(blockId); buildConnectivity(blockData); MetricsInitializer *metricsInit = new MetricsInitializer(blockData); metricsInit->doInit(); int const nbCoordVect = 3; double normalFace1[nbCoordVect]; double normalFace2[nbCoordVect]; double normalFace3[nbCoordVect]; double normalFace4[nbCoordVect]; double normalFace5[nbCoordVect]; double epsilon = 0.01; normalFace1[0] = 1.0; normalFace1[1] = 1.0; normalFace1[2] = 0.5; for(int i(0);i<nbCoordVect;i++) { REQUIRE(blockData->block_faces_[0]->face_normals_[i] <= normalFace1[i] + epsilon); REQUIRE(blockData->block_faces_[0]->face_normals_[i] >= normalFace1[i] - epsilon); } normalFace2[0] = -1.0; normalFace2[1] = 1.0; normalFace2[2] = 0.5; for(int i(0);i<nbCoordVect;i++) { REQUIRE(blockData->block_faces_[1]->face_normals_[i] <= normalFace2[i] + epsilon); REQUIRE(blockData->block_faces_[1]->face_normals_[i] >= normalFace2[i] - epsilon); } normalFace3[0] = -1.0; normalFace3[1] = -1.0; normalFace3[2] = 0.5; for(int i(0);i<nbCoordVect;i++) { REQUIRE(blockData->block_faces_[2]->face_normals_[i] <= normalFace3[i] + epsilon); REQUIRE(blockData->block_faces_[2]->face_normals_[i] >= normalFace3[i] - epsilon); } normalFace4[0] = 1.0; normalFace4[1] = -1.0; normalFace4[2] = 0.5; for(int i(0);i<nbCoordVect;i++) { REQUIRE(blockData->block_faces_[3]->face_normals_[i] <= normalFace4[i] + epsilon); REQUIRE(blockData->block_faces_[3]->face_normals_[i] >= normalFace4[i] - epsilon); } normalFace5[0] = 0.0; normalFace5[1] = 0.0; normalFace5[2] = -2.0; for(int i(0);i<nbCoordVect;i++) { REQUIRE(blockData->block_faces_[4]->face_normals_[i] <= normalFace5[i] + epsilon); REQUIRE(blockData->block_faces_[4]->face_normals_[i] >= normalFace5[i] - epsilon); } tearDown(blockData); delete blockData; blockData = nullptr; delete metricsInit; metricsInit = nullptr; } TEST_CASE("Test ComputeAreaFaces", "Testing if areas are well defined") { int blockId = 0; Block *blockData = new Block(blockId); buildConnectivity(blockData); MetricsInitializer *metricsInit = new MetricsInitializer(blockData); metricsInit->doInit(); int const nbFaces = 5; double area[nbFaces]; area[0] = 1.5; area[1] = 1.5; area[2] = 1.5; area[3] = 1.5; area[4] = 2; for(int i(0);i < nbFaces;i++) REQUIRE(blockData->block_faces_[i]->face_area_ == area[i]); tearDown(blockData); delete blockData; blockData = nullptr; delete metricsInit; metricsInit = nullptr; } TEST_CASE("Test interpolation vector") { int blockId = 0; Block *blockData = new Block(blockId); buildConnectivity(blockData); MetricsInitializer *metricsInit = new MetricsInitializer(blockData); metricsInit->doInit(); double eps = 0.01; double vec_interp_left[3]; vec_interp_left[0] = 0.33; vec_interp_left[1] = 0.33; vec_interp_left[2] = 0.27; double *result_left = blockData->block_faces_[0]->left_cell_r_vector_; for(int i(0);i < 3;i++) { REQUIRE(result_left[i] <= vec_interp_left[i] + eps); REQUIRE(result_left[i] >= vec_interp_left[i] - eps); } tearDown(blockData); delete blockData; blockData = nullptr; delete metricsInit; metricsInit = nullptr; result_left = nullptr; }
28.385396
94
0.653566
guillaumetousignant
e4ac58e1fef53241e76504df4f18e0de6b8294fc
3,650
cpp
C++
src/gui_scrollframe_glues.cpp
cschreib/lxgui
b317774d9b4296dda8a70b994950987378a05678
[ "MIT" ]
50
2015-01-15T10:00:31.000Z
2022-02-04T20:45:25.000Z
src/gui_scrollframe_glues.cpp
cschreib/lxgui
b317774d9b4296dda8a70b994950987378a05678
[ "MIT" ]
88
2020-03-15T17:40:04.000Z
2022-03-15T08:21:44.000Z
src/gui_scrollframe_glues.cpp
cschreib/lxgui
b317774d9b4296dda8a70b994950987378a05678
[ "MIT" ]
19
2017-03-11T04:32:01.000Z
2022-01-12T22:47:12.000Z
#include "lxgui/gui_scrollframe.hpp" #include "lxgui/gui_uiobject_tpl.hpp" #include "lxgui/gui_frame.hpp" #include "lxgui/gui_out.hpp" #include "lxgui/gui_manager.hpp" #include <sol/state.hpp> /** A @{Frame} with scrollable content. * This frame has a special child frame, the "scroll child". The scroll * child is rendered on a separate render target, which is then rendered * on the screen. This allows clipping the content of the scroll child * and only display a portion of it (as if scrolling on a page). The * displayed portion is controlled by the scroll value, which can be * changed in both the vertical and horizontal directions. * * By default, the mouse wheel movement will not trigger any scrolling; * this has to be explicitly implemented using the `OnMouseWheel` callback * and the @{ScrollFrame:set_horizontal_scroll} function. * * __Events.__ Hard-coded events available to all @{ScrollFrame}s, * in addition to those from @{Frame}: * * - `OnHorizontalScroll`: Triggered by @{ScrollFrame:set_horizontal_scroll}. * - `OnScrollRangeChanged`: Triggered whenever the range of the scroll value * changes. This happens either when the size of the scrollable content * changes, or when the size of the scroll frame changes. * - `OnVerticalScroll`: Triggered by @{ScrollFrame:set_vertical_scroll}. * * Inherits all methods from: @{UIObject}, @{Frame}. * * Child classes: none. * @classmod ScrollFrame */ namespace lxgui { namespace gui { void scroll_frame::register_on_lua(sol::state& mLua) { auto mClass = mLua.new_usertype<scroll_frame>("ScrollFrame", sol::base_classes, sol::bases<uiobject, frame>(), sol::meta_function::index, member_function<&scroll_frame::get_lua_member_>(), sol::meta_function::new_index, member_function<&scroll_frame::set_lua_member_>()); /** @function get_horizontal_scroll */ mClass.set_function("get_horizontal_scroll", member_function<&scroll_frame::get_horizontal_scroll>()); /** @function get_horizontal_scroll_range */ mClass.set_function("get_horizontal_scroll_range", member_function<&scroll_frame::get_horizontal_scroll_range>()); /** @function get_scroll_child */ mClass.set_function("get_scroll_child", member_function< // select the right overload for Lua static_cast<const utils::observer_ptr<frame>& (scroll_frame::*)()>(&scroll_frame::get_scroll_child)>()); /** @function get_vertical_scroll */ mClass.set_function("get_vertical_scroll", member_function<&scroll_frame::get_vertical_scroll>()); /** @function get_vertical_scroll_range */ mClass.set_function("get_vertical_scroll_range", member_function<&scroll_frame::get_vertical_scroll_range>()); /** @function set_horizontal_scroll */ mClass.set_function("set_horizontal_scroll", member_function<&scroll_frame::set_horizontal_scroll>()); /** @function set_scroll_child */ mClass.set_function("set_scroll_child", [](scroll_frame& mSelf, std::variant<std::string, frame*> mChild) { utils::observer_ptr<frame> pChild = get_object<frame>(mSelf.get_manager(), mChild); utils::owner_ptr<frame> pScrollChild; if (pChild) pScrollChild = utils::static_pointer_cast<frame>(pChild->release_from_parent()); mSelf.set_scroll_child(std::move(pScrollChild)); }); /** @function set_vertical_scroll */ mClass.set_function("set_vertical_scroll", member_function<&scroll_frame::set_vertical_scroll>()); } } }
38.020833
119
0.704932
cschreib
e4ace4f777ad42177cdd89605133622ec5e91f98
2,003
cc
C++
ui/wm/core/nested_accelerator_controller.cc
domenic/mojo
53dda76fed90a47c35ed6e06baf833a0d44495b8
[ "BSD-3-Clause" ]
5
2019-05-24T01:25:34.000Z
2020-04-06T05:07:01.000Z
ui/wm/core/nested_accelerator_controller.cc
domenic/mojo
53dda76fed90a47c35ed6e06baf833a0d44495b8
[ "BSD-3-Clause" ]
1
2018-02-10T21:00:08.000Z
2018-03-20T05:09:50.000Z
ui/wm/core/nested_accelerator_controller.cc
domenic/mojo
53dda76fed90a47c35ed6e06baf833a0d44495b8
[ "BSD-3-Clause" ]
5
2016-12-23T04:21:10.000Z
2020-06-18T13:52:33.000Z
// 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. #include "ui/wm/core/nested_accelerator_controller.h" #include "base/auto_reset.h" #include "base/bind.h" #include "base/run_loop.h" #include "ui/wm/core/nested_accelerator_delegate.h" #include "ui/wm/core/nested_accelerator_dispatcher.h" namespace wm { NestedAcceleratorController::NestedAcceleratorController( NestedAcceleratorDelegate* delegate) : dispatcher_delegate_(delegate) { DCHECK(delegate); } NestedAcceleratorController::~NestedAcceleratorController() { } void NestedAcceleratorController::PrepareNestedLoopClosures( base::MessagePumpDispatcher* nested_dispatcher, base::Closure* run_closure, base::Closure* quit_closure) { scoped_ptr<NestedAcceleratorDispatcher> old_accelerator_dispatcher = accelerator_dispatcher_.Pass(); accelerator_dispatcher_ = NestedAcceleratorDispatcher::Create( dispatcher_delegate_.get(), nested_dispatcher); scoped_ptr<base::RunLoop> run_loop = accelerator_dispatcher_->CreateRunLoop(); *quit_closure = base::Bind(&NestedAcceleratorController::QuitNestedMessageLoop, base::Unretained(this), run_loop->QuitClosure()); *run_closure = base::Bind(&NestedAcceleratorController::RunNestedMessageLoop, base::Unretained(this), base::Passed(&run_loop), base::Passed(&old_accelerator_dispatcher)); } void NestedAcceleratorController::RunNestedMessageLoop( scoped_ptr<base::RunLoop> run_loop, scoped_ptr<NestedAcceleratorDispatcher> old_accelerator_dispatcher) { run_loop->Run(); accelerator_dispatcher_ = old_accelerator_dispatcher.Pass(); } void NestedAcceleratorController::QuitNestedMessageLoop( const base::Closure& quit_runloop) { quit_runloop.Run(); accelerator_dispatcher_.reset(); } } // namespace wm
34.534483
80
0.742886
domenic
e4b1fe8725e8463861252d0160580b68ddaf3698
3,071
cpp
C++
src/OISBState.cpp
fire-archive/oisb
2e1a1a5f58dee986122a1aef8a98e5e610a845a4
[ "Zlib" ]
null
null
null
src/OISBState.cpp
fire-archive/oisb
2e1a1a5f58dee986122a1aef8a98e5e610a845a4
[ "Zlib" ]
null
null
null
src/OISBState.cpp
fire-archive/oisb
2e1a1a5f58dee986122a1aef8a98e5e610a845a4
[ "Zlib" ]
null
null
null
/* The zlib/libpng License Copyright (c) 2009-2010 Martin Preisler This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "OISBState.h" #include "OISBDevice.h" #include "OISException.h" namespace OISB { State::State(Device* parent, const String& name): mParent(parent), mName(name), mIsActive(false), mChanged(false) {} State::~State() {} BindableType State::getBindableType() const { return BT_STATE; } String State::getBindableName() const { return "State: " + getFullName(); } bool State::isActive() const { return mIsActive; } bool State::hasChanged() const { return mChanged; } String State::getFullName() const { return mParent->getName() + "/" + getName(); } void State::listProperties(PropertyList& list) { Bindable::listProperties(list); list.push_back("StateName"); list.push_back("ParentDeviceName"); } void State::impl_setProperty(const String& name, const String& value) { if (name == "StateName") { OIS_EXCEPT(OIS::E_InvalidParam, "'StateName' is a read only, you can't set it!"); } else if (name == "ParentDeviceName") { OIS_EXCEPT(OIS::E_InvalidParam, "'ParentDeviceName' is a read only, you can't set it!"); } else { // nothing matched, delegate up Bindable::impl_setProperty(name, value); } } String State::impl_getProperty(const String& name) const { if (name == "StateName") { return getName(); } else if (name == "ParentDeviceName") { // no need to check, every state must have a valid parent return mParent->getName(); } else { // nothing matched, delegate up return Bindable::impl_getProperty(name); } } void State::activate() { mIsActive = true; notifyActivated(); } void State::deactivate() { mIsActive = false; notifyDeactivated(); } }
24.96748
101
0.592966
fire-archive
e4b25daf69025b5c61391c1080fe95f41af759d9
7,098
cpp
C++
src/Ethereum/ABI/ParamFactory.cpp
Khaos-Labs/khaos-wallet-core
2c06d49fddf978e0815b208dddef50ee2011c551
[ "MIT" ]
2
2020-11-16T08:06:30.000Z
2021-06-18T03:21:44.000Z
src/Ethereum/ABI/ParamFactory.cpp
Khaos-Labs/khaos-wallet-core
2c06d49fddf978e0815b208dddef50ee2011c551
[ "MIT" ]
null
null
null
src/Ethereum/ABI/ParamFactory.cpp
Khaos-Labs/khaos-wallet-core
2c06d49fddf978e0815b208dddef50ee2011c551
[ "MIT" ]
null
null
null
// Copyright © 2017-2020 Khaos Wallet. // // This file is part of Trust. The full Trust copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. #include "ParamFactory.h" #include "HexCoding.h" #include <nlohmann/json.hpp> #include <boost/algorithm/string/predicate.hpp> using namespace std; using namespace boost::algorithm; using json = nlohmann::json; namespace TW::Ethereum::ABI { static int parseBitSize(const std::string& type) { int size = stoi(type); if (size < 8 || size > 256 || size % 8 != 0 || size == 8 || size == 16 || size == 32 || size == 64 || size == 256) { throw invalid_argument("invalid bit size"); } return size; } static std::shared_ptr<ParamBase> makeUInt(const std::string& type) { auto bits = parseBitSize(type); return make_shared<ParamUIntN>(bits); } static std::shared_ptr<ParamBase> makeInt(const std::string& type) { auto bits = parseBitSize(type); return make_shared<ParamIntN>(bits); } static bool isArrayType(const std::string& type) { return ends_with(type, "[]") && type.length() >= 3; } static std::string getArrayElemType(const std::string& arrayType) { if (ends_with(arrayType, "[]") && arrayType.length() >= 3) { return arrayType.substr(0, arrayType.length() - 2); } return ""; } std::shared_ptr<ParamBase> ParamFactory::make(const std::string& type) { shared_ptr<ParamBase> param; if (isArrayType(type)) { auto elemType = getArrayElemType(type); auto elemParam = make(elemType); if (!elemParam) { return param; } param = make_shared<ParamArray>(elemParam); } else if (type == "address") { param = make_shared<ParamAddress>(); } else if (type == "uint8") { param = make_shared<ParamUInt8>(); } else if (type == "uint16") { param = make_shared<ParamUInt16>(); } else if (type == "uint32") { param = make_shared<ParamUInt32>(); } else if (type == "uint64") { param = make_shared<ParamUInt64>(); } else if (type == "uint256" || type == "uint") { param = make_shared<ParamUInt256>(); } else if (type == "int8") { param = make_shared<ParamInt8>(); } else if (type == "int16") { param = make_shared<ParamInt16>(); } else if (type == "int32") { param = make_shared<ParamInt32>(); } else if (type == "int64") { param = make_shared<ParamInt64>(); } else if (type == "int256" || type == "int") { param = make_shared<ParamInt256>(); } else if (starts_with(type, "uint")) { param = makeUInt(type.substr(4, type.size() - 1)); } else if (starts_with(type, "int")) { param = makeInt(type.substr(3, type.size() - 1)); } else if (type == "bool") { param = make_shared<ParamBool>(); } else if (type == "bytes") { param = make_shared<ParamByteArray>(); } else if (starts_with(type, "bytes")) { auto bits = stoi(type.substr(5, type.size() - 1)); param = make_shared<ParamByteArrayFix>(bits); } else if (type == "string") { param = make_shared<ParamString>(); } return param; } std::string joinArrayElems(const std::vector<std::string>& strings) { auto array = json::array(); for (auto i = 0; i < strings.size(); ++i) { // parse to prevent quotes on simple values auto value = json::parse(strings[i], nullptr, false); if (value.is_discarded()) { // fallback value = json(strings[i]); } array.push_back(value); } return array.dump(); } std::string ParamFactory::getValue(const std::shared_ptr<ParamBase>& param, const std::string& type) { std::string result = ""; if (isArrayType(type)) { auto values = getArrayValue(param, type); result = joinArrayElems(values); } else if (type == "address") { auto value = dynamic_pointer_cast<ParamAddress>(param); result = hexEncoded(value->getData()); } else if (type == "uint8") { result = boost::lexical_cast<std::string>((uint)dynamic_pointer_cast<ParamUInt8>(param)->getVal()); } else if (type == "uint16") { result = boost::lexical_cast<std::string>(dynamic_pointer_cast<ParamUInt16>(param)->getVal()); } else if (type == "uint32") { result = boost::lexical_cast<std::string>(dynamic_pointer_cast<ParamUInt32>(param)->getVal()); } else if (type == "uint64") { result = boost::lexical_cast<std::string>(dynamic_pointer_cast<ParamUInt64>(param)->getVal()); } else if (type == "uint256" || type == "uint") { result = boost::lexical_cast<std::string>(dynamic_pointer_cast<ParamUInt256>(param)->getVal()); } else if (type == "int8") { result = boost::lexical_cast<std::string>((int)dynamic_pointer_cast<ParamInt8>(param)->getVal()); } else if (type == "int16") { result = boost::lexical_cast<std::string>(dynamic_pointer_cast<ParamInt16>(param)->getVal()); } else if (type == "int32") { result = boost::lexical_cast<std::string>(dynamic_pointer_cast<ParamInt32>(param)->getVal()); } else if (type == "int64") { result = boost::lexical_cast<std::string>(dynamic_pointer_cast<ParamInt64>(param)->getVal()); } else if (type == "int256" || type == "int") { result = boost::lexical_cast<std::string>(dynamic_pointer_cast<ParamInt256>(param)->getVal()); } else if (starts_with(type, "uint")) { auto value = dynamic_pointer_cast<ParamUIntN>(param); result = boost::lexical_cast<std::string>(value->getVal()); } else if (starts_with(type, "int")) { auto value = dynamic_pointer_cast<ParamIntN>(param); result = boost::lexical_cast<std::string>(value->getVal()); } else if (type == "bool") { auto value = dynamic_pointer_cast<ParamBool>(param); result = value->getVal() ? "true" : "false"; } else if (type == "bytes") { auto value = dynamic_pointer_cast<ParamByteArray>(param); result = hexEncoded(value->getVal()); } else if (starts_with(type, "bytes")) { auto value = dynamic_pointer_cast<ParamByteArrayFix>(param); result = hexEncoded(value->getVal()); } else if (type == "string") { auto value = dynamic_pointer_cast<ParamString>(param); result = value->getVal(); } return result; } std::vector<std::string> ParamFactory::getArrayValue(const std::shared_ptr<ParamBase>& param, const std::string& type) { if (!isArrayType(type)) { return std::vector<std::string>(); } auto array = dynamic_pointer_cast<ParamArray>(param); if (!array) { return std::vector<std::string>(); } auto elemType = getArrayElemType(type); auto elems = array->getVal(); std::vector<std::string> values(elems.size()); for (auto i = 0; i < elems.size(); ++i) { values[i] = getValue(elems[i], elemType); } return values; } } // namespace TW::Ethereum::ABI
39.653631
120
0.615807
Khaos-Labs
e4b675eaf8699a46535ae1317fdafc07483d5fb8
3,426
hh
C++
include/ignition/transport/TopicUtils.hh
amtj/ign-transport
3b386bf46efd2fc0b847aa7fd3911b1d9d27546c
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
include/ignition/transport/TopicUtils.hh
amtj/ign-transport
3b386bf46efd2fc0b847aa7fd3911b1d9d27546c
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
include/ignition/transport/TopicUtils.hh
amtj/ign-transport
3b386bf46efd2fc0b847aa7fd3911b1d9d27546c
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2014 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef __IGN_TRANSPORT_TOPICUTILS_HH_INCLUDED__ #define __IGN_TRANSPORT_TOPICUTILS_HH_INCLUDED__ #include <cstdint> #include <string> #include "ignition/transport/Helpers.hh" namespace ignition { namespace transport { /// \class TopicUtils TopicUtils.hh ignition/transport/TopicUtils.hh /// \brief This class provides different utilities related with topics. class IGNITION_TRANSPORT_VISIBLE TopicUtils { /// \brief Determines if a namespace is valid. A namespace's length must /// not exceed kMaxNameLength. /// \param[in] _ns Namespace to be checked. /// \return true if the namespace is valid. public: static bool IsValidNamespace(const std::string &_ns); /// \brief Determines if a partition is valid. /// The same rules to validate a topic name applies to a partition with /// the addition of the empty string, which is a valid partition (meaning /// no partition is used). A partition name's length must not exceed /// kMaxNameLength. /// \param[in] _partition Partition to be checked. /// \return true if the partition is valid. public: static bool IsValidPartition(const std::string &_partition); /// \brief Determines if a topic name is valid. A topic name is any /// non-empty alphanumeric string. The symbol '/' is also allowed as part /// of a topic name. The symbol '@' is not allowed in a topic name /// because it is used as a partition delimitier. A topic name's length /// must not exceed kMaxNameLength. /// Examples of valid topics: abc, /abc, /abc/de, /abc/de/ /// \param[in] _topic Topic name to be checked. /// \return true if the topic name is valid. public: static bool IsValidTopic(const std::string &_topic); /// \brief Get the full topic path given a namespace and a topic name. /// A fully qualified topic name's length must not exceed kMaxNameLength. /// \param[in] _partition Partition name. /// \param[in] _ns Namespace. /// \param[in] _topic Topic name. /// \param[out] _name Fully qualified topic name. /// \return True if the fully qualified name is valid /// (if partition, namespace and topic are correct). public: static bool FullyQualifiedName(const std::string &_partition, const std::string &_ns, const std::string &_topic, std::string &_name); /// \brief The kMaxNameLength specifies the maximum number of characters /// allowed in a namespace, a partition name, a topic name, and a fully /// qualified topic name. public: static const uint16_t kMaxNameLength = 65535; }; } } #endif
42.296296
79
0.665791
amtj
e4b93506670e4671f2ce9f66df16fe12be3a11c1
4,653
inl
C++
lib/NoesisGUI-2.2.0/Include/NsCore/Queue.inl
guillaume-haerinck/imac-tower-defense
365a32642ea0d3ad8b2b7d63347d585c44d9f670
[ "MIT" ]
44
2019-06-06T21:33:30.000Z
2022-03-26T06:18:23.000Z
lib/NoesisGUI-2.2.0/Include/NsCore/Queue.inl
guillaume-haerinck/imac-tower-defense
365a32642ea0d3ad8b2b7d63347d585c44d9f670
[ "MIT" ]
1
2019-09-27T12:04:52.000Z
2019-09-29T13:30:42.000Z
lib/NoesisGUI-2.2.0/Include/NsCore/Queue.inl
guillaume-haerinck/imac-tower-defense
365a32642ea0d3ad8b2b7d63347d585c44d9f670
[ "MIT" ]
8
2019-07-26T16:44:26.000Z
2020-11-24T17:56:18.000Z
//////////////////////////////////////////////////////////////////////////////////////////////////// // NoesisGUI - http://www.noesisengine.com // Copyright (c) 2013 Noesis Technologies S.L. All Rights Reserved. //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// namespace eastl { //////////////////////////////////////////////////////////////////////////////////////////////////// // queue //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// template<class T, typename Container> inline queue<T, Container>::queue() : mContainer() { } //////////////////////////////////////////////////////////////////////////////////////////////////// template<class T, typename Container> inline queue<T, Container>::queue(const this_type& other) : mContainer(other.mContainer) { } //////////////////////////////////////////////////////////////////////////////////////////////////// template<class T, typename Container> inline typename queue<T, Container>::this_type& queue<T, Container>::operator=(const this_type& other) { mContainer = other.mContainer; return *this; } //////////////////////////////////////////////////////////////////////////////////////////////////// template<class T, typename Container> inline void queue<T, Container>::push(const value_type& value) { mContainer.push_back(value); } //////////////////////////////////////////////////////////////////////////////////////////////////// template<class T, typename Container> inline void queue<T, Container>::pop() { mContainer.pop_front(); } //////////////////////////////////////////////////////////////////////////////////////////////////// template<class T, typename Container> inline typename queue<T, Container>::reference queue<T, Container>::front() { return const_cast<reference>(static_cast<const this_type*>(this)->front()); } //////////////////////////////////////////////////////////////////////////////////////////////////// template<class T, typename Container> inline typename queue<T, Container>::const_reference queue<T, Container>::front() const { return mContainer.front(); } //////////////////////////////////////////////////////////////////////////////////////////////////// template<class T, typename Container> inline typename queue<T, Container>::reference queue<T, Container>::back() { return const_cast<reference>(static_cast<const this_type*>(this)->back()); } //////////////////////////////////////////////////////////////////////////////////////////////////// template<class T, typename Container> inline typename queue<T, Container>::const_reference queue<T, Container>::back() const { return mContainer.back(); } //////////////////////////////////////////////////////////////////////////////////////////////////// template<class T, typename Container> inline bool queue<T, Container>::empty() const { return mContainer.empty(); } //////////////////////////////////////////////////////////////////////////////////////////////////// template<class T, typename Container> inline typename queue<T, Container>::size_type queue<T, Container>::size() const { return mContainer.size(); } //////////////////////////////////////////////////////////////////////////////////////////////////// template<class T, typename Container> inline typename queue<T, Container>::container_type& queue<T, Container>::get_container() { return mContainer; } } //////////////////////////////////////////////////////////////////////////////////////////////////// // NsQueue //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// template<class T, typename Container> inline NsQueue<T, Container>::NsQueue() : BaseType() { } //////////////////////////////////////////////////////////////////////////////////////////////////// template<class T, typename Container> inline NsQueue<T, Container>::NsQueue(const ThisType& other) : BaseType(other) { } //////////////////////////////////////////////////////////////////////////////////////////////////// template<class T, typename Container> inline typename NsQueue<T, Container>::ThisType& NsQueue<T, Container>::operator=(const ThisType& other) { return static_cast<ThisType&>(BaseType::operator=(other)); }
34.984962
100
0.381689
guillaume-haerinck
e4b941a9020b7231e60ddc242dab3041593dd531
6,630
cpp
C++
Source/Parsing/ParsingAutomaton_EPDA.cpp
milizhang/Vlpp
34a1217c1738587d0c723ed3227a79777636faf1
[ "MS-PL" ]
2
2020-04-16T15:51:41.000Z
2021-06-05T06:38:20.000Z
Source/Parsing/ParsingAutomaton_EPDA.cpp
milizhang/Vlpp
34a1217c1738587d0c723ed3227a79777636faf1
[ "MS-PL" ]
null
null
null
Source/Parsing/ParsingAutomaton_EPDA.cpp
milizhang/Vlpp
34a1217c1738587d0c723ed3227a79777636faf1
[ "MS-PL" ]
null
null
null
#include "ParsingAutomaton.h" #include "../Collections/Operation.h" namespace vl { namespace parsing { using namespace collections; using namespace definitions; namespace analyzing { /*********************************************************************** CreateEpsilonPDAVisitor ***********************************************************************/ class CreateEpsilonPDAVisitor : public Object, public ParsingDefinitionGrammar::IVisitor { public: Ptr<Automaton> automaton; ParsingDefinitionRuleDefinition* rule; ParsingDefinitionGrammar* ruleGrammar; State* startState; State* endState; Transition* result; CreateEpsilonPDAVisitor(Ptr<Automaton> _automaton, ParsingDefinitionRuleDefinition* _rule, ParsingDefinitionGrammar* _ruleGrammar, State* _startState, State* _endState) :automaton(_automaton) ,rule(_rule) ,ruleGrammar(_ruleGrammar) ,startState(_startState) ,endState(_endState) ,result(0) { } static Transition* Create(ParsingDefinitionGrammar* grammar, Ptr<Automaton> automaton, ParsingDefinitionRuleDefinition* rule, ParsingDefinitionGrammar* ruleGrammar, State* startState, State* endState) { CreateEpsilonPDAVisitor visitor(automaton, rule, ruleGrammar, startState, endState); grammar->Accept(&visitor); return visitor.result; } Transition* Create(ParsingDefinitionGrammar* grammar, State* startState, State* endState) { return Create(grammar, automaton, rule, ruleGrammar, startState, endState); } void Visit(ParsingDefinitionPrimitiveGrammar* node)override { result=automaton->Symbol(startState, endState, automaton->symbolManager->CacheGetSymbol(node)); } void Visit(ParsingDefinitionTextGrammar* node)override { result=automaton->Symbol(startState, endState, automaton->symbolManager->CacheGetSymbol(node)); } void Visit(ParsingDefinitionSequenceGrammar* node)override { State* middleState=automaton->EndState(startState->ownerRule, ruleGrammar, node->first.Obj()); Create(node->first.Obj(), startState, middleState); Create(node->second.Obj(), middleState, endState); } void Visit(ParsingDefinitionAlternativeGrammar* node)override { Create(node->first.Obj(), startState, endState); Create(node->second.Obj(), startState, endState); } void Visit(ParsingDefinitionLoopGrammar* node)override { State* loopStart=automaton->StartState(startState->ownerRule, ruleGrammar, node->grammar.Obj()); automaton->Epsilon(startState, loopStart); automaton->Epsilon(loopStart, endState); Create(node->grammar.Obj(), loopStart, loopStart); } void Visit(ParsingDefinitionOptionalGrammar* node)override { Create(node->grammar.Obj(), startState, endState); automaton->Epsilon(startState, endState); } void Visit(ParsingDefinitionCreateGrammar* node)override { State* middleState=automaton->EndState(startState->ownerRule, ruleGrammar, node->grammar.Obj()); Create(node->grammar.Obj(), startState, middleState); Transition* transition=automaton->Epsilon(middleState, endState); Ptr<Action> action=new Action; action->actionType=Action::Create; action->actionSource=automaton->symbolManager->CacheGetType(node->type.Obj(), 0); action->creatorRule=rule; transition->actions.Add(action); } void Visit(ParsingDefinitionAssignGrammar* node)override { Transition* transition=Create(node->grammar.Obj(), startState, endState); Ptr<Action> action=new Action; action->actionType=Action::Assign; action->actionSource=automaton->symbolManager->CacheGetSymbol(node); action->creatorRule=rule; transition->actions.Add(action); } void Visit(ParsingDefinitionUseGrammar* node)override { Transition* transition=Create(node->grammar.Obj(), startState, endState); Ptr<Action> action=new Action; action->actionType=Action::Using; action->creatorRule=rule; transition->actions.Add(action); } void Visit(ParsingDefinitionSetterGrammar* node)override { State* middleState=automaton->EndState(startState->ownerRule, ruleGrammar, node->grammar.Obj()); Create(node->grammar.Obj(), startState, middleState); Transition* transition=automaton->Epsilon(middleState, endState); Ptr<Action> action=new Action; action->actionType=Action::Setter; action->actionSource=automaton->symbolManager->CacheGetSymbol(node); action->actionTarget=action->actionSource->GetDescriptorSymbol()->GetSubSymbolByName(node->value); action->creatorRule=rule; transition->actions.Add(action); } }; /*********************************************************************** CreateRuleEpsilonPDA ***********************************************************************/ void CreateRuleEpsilonPDA(Ptr<Automaton> automaton, Ptr<definitions::ParsingDefinitionRuleDefinition> rule, ParsingSymbolManager* manager) { Ptr<RuleInfo> ruleInfo=new RuleInfo; automaton->ruleInfos.Add(rule.Obj(), ruleInfo); ruleInfo->rootRuleStartState=automaton->RootRuleStartState(rule.Obj()); ruleInfo->rootRuleEndState=automaton->RootRuleEndState(rule.Obj()); ruleInfo->startState=automaton->RuleStartState(rule.Obj()); automaton->TokenBegin(ruleInfo->rootRuleStartState, ruleInfo->startState); FOREACH(Ptr<ParsingDefinitionGrammar>, grammar, rule->grammars) { State* grammarStartState=automaton->StartState(rule.Obj(), grammar.Obj(), grammar.Obj()); State* grammarEndState=automaton->EndState(rule.Obj(), grammar.Obj(), grammar.Obj()); grammarEndState->stateName+=L".End"; grammarEndState->endState=true; automaton->Epsilon(ruleInfo->startState, grammarStartState); automaton->TokenFinish(grammarEndState, ruleInfo->rootRuleEndState); ruleInfo->endStates.Add(grammarEndState); CreateEpsilonPDAVisitor::Create(grammar.Obj(), automaton, rule.Obj(), grammar.Obj(), grammarStartState, grammarEndState); } } /*********************************************************************** CreateEpsilonPDA ***********************************************************************/ Ptr<Automaton> CreateEpsilonPDA(Ptr<definitions::ParsingDefinition> definition, ParsingSymbolManager* manager) { Ptr<Automaton> automaton=new Automaton(manager); FOREACH(Ptr<ParsingDefinitionRuleDefinition>, rule, definition->rules) { CreateRuleEpsilonPDA(automaton, rule, manager); } return automaton; } } } }
37.247191
204
0.679638
milizhang
e4baccba4b6fc73c24c6a806d6f405465c6e3878
33,016
cxx
C++
drs4monitor/src/MonitorFrame.cxx
CMSROMA/DRS4_DAQ
8ff60a58a1a254d56b2afedaf788ecf5afc67afc
[ "MIT" ]
null
null
null
drs4monitor/src/MonitorFrame.cxx
CMSROMA/DRS4_DAQ
8ff60a58a1a254d56b2afedaf788ecf5afc67afc
[ "MIT" ]
null
null
null
drs4monitor/src/MonitorFrame.cxx
CMSROMA/DRS4_DAQ
8ff60a58a1a254d56b2afedaf788ecf5afc67afc
[ "MIT" ]
null
null
null
/* * MonitorFrame.cxx * * Created on: Apr 16, 2017 * Author: S. Lukic */ #include "TApplication.h" #include <TGClient.h> #include "TGButton.h" #include "TGTextView.h" #include "TGText.h" #include "TGTextEntry.h" #include "TGTextBuffer.h" #include "TGComboBox.h" #include "TGLabel.h" #include "TGProgressBar.h" #include "TCanvas.h" #include "TRootCanvas.h" #include "TH1F.h" #include "TH2F.h" #include "TTimeStamp.h" #include "TFile.h" #include "TString.h" #include "TLegend.h" #include "TLegendEntry.h" #include "MonitorFrame.h" #include "Riostream.h" #include "TMath.h" #include "DAQ-config.h" #include "DRS4_fifo.h" #include "DRS4_writer.h" #include "DRS4_reader.h" #include "observables.h" using namespace DRS4_data; MonitorFrame::MonitorFrame(const TGWindow *p, config * const opt, DRS * const _drs) : TGMainFrame(p, 250, 350), // limits(opt->histolo, opt->histohi), options(opt), // fCanvas01(new TCanvas("DRS4Canvas01", "DRS4 Monitor 01", opt->_w, opt->_h)), // frCanvas01(new TRootCanvas(fCanvas01, "DRS4 Monitor 01", 0, 200, opt->_w, opt->_h)), // fCanvas02(new TCanvas("DRS4Canvas02", "DRS4 Monitor 02", opt->_w, opt->_h)), // frCanvas02(new TRootCanvas(fCanvas02, "DRS4 Monitor 02", 0, 200, opt->_w, opt->_h)), // fCanvas2D(new TCanvas("DRS4Canvas2D", "DRS4 Monitor 2D", opt->_w*2/3, opt->_h)), // frCanvas2D(new TRootCanvas(fCanvas2D, "DRS4 Monitor 2D", 0, 200, opt->_w*2/3, opt->_h)), // fCanvasOsc(new TCanvas("DRS4CanvasOsc", "DRS4 oscillogram", opt->_w/3, opt->_h/2)), // frCanvasOsc(new TRootCanvas(fCanvasOsc, "DRS4 oscillogram", 0, 200, opt->_w/3, opt->_h/2)), // tRed(opt->_tRed), tRed2D(opt->_tRed2D), baseLineWidth(opt->baseLineWidth), basename("default"), filename("default"), timestamped(false), // eTot12(NULL), ePrompt12(NULL), time12(NULL), time34(NULL), timeLastSave(0), lastSpill(0), confStatus(-1), rate(NULL), drs(_drs), fifo(new DRS4_fifo), writer(NULL), rawWave(NULL), event(NULL), headers(NULL), nEvtMax(opt->nEvtMax), iEvtSerial(0), iEvtProcessed(0), spillSize(10000),interSpillTime(0), file(NULL), #ifdef ROOT_OUTPUT outTree(NULL), h4daqEvent(NULL), #endif f_stop(false), f_stopWhenEmpty(false), f_running(false) // timePoints(NULL), amplitudes(NULL) // itRed(0), itRed2D(0) { // Observables obs; // for(int iobs=0; iobs<nObservables; iobs++) { // kObservables kobs = static_cast<kObservables>(iobs); // histo[0][iobs] = new TH1F(Form("h1%d", iobs), Form("%s - S1; %s_{1} (%s)", obs.Title(kobs), obs.Title(kobs), obs.Unit(kobs)), opt->histoNbins[iobs], opt->histolo[iobs], opt->histohi[iobs]); // histo[1][iobs] = new TH1F(Form("h2%d", iobs), Form("%s - S2; %s_{2} (%s)", obs.Title(kobs), obs.Title(kobs), obs.Unit(kobs)), opt->histoNbins[iobs], opt->histolo[iobs], opt->histohi[iobs]); // } // eTot12 = new TH2F("eTot12", Form("eTot2 vs. eTot1; %s_{1} (%s); %s_{2} (%s)", obs.Title(eTot), obs.Unit(eTot), obs.Title(eTot), obs.Unit(eTot)), // opt->histoNbins[eTot]/opt->_xRed, opt->histolo[eTot], opt->histohi[eTot], // opt->histoNbins[eTot]/opt->_xRed, opt->histolo[eTot], opt->histohi[eTot]); // ePrompt12 = new TH2F("ePrompt12", Form("ePrompt2 vs. ePrompt1; %s_{1} (%s); %s_{2} (%s)", obs.Title(ePrompt), obs.Unit(ePrompt), obs.Title(ePrompt), obs.Unit(ePrompt)), // opt->histoNbins[ePrompt]/opt->_xRed, opt->histolo[ePrompt], opt->histohi[ePrompt], // opt->histoNbins[ePrompt]/opt->_xRed, opt->histolo[ePrompt], opt->histohi[ePrompt]); // time12 = new TH2F("time12", Form("t_{2} vs. t_{1}; %s_{1} (%s); %s_{2} (%s)", obs.Title(arrivalTime), obs.Unit(arrivalTime), obs.Title(arrivalTime), obs.Unit(arrivalTime)), // opt->histoNbins[arrivalTime]/opt->_xRed, opt->histolo[arrivalTime], opt->histohi[arrivalTime], // opt->histoNbins[arrivalTime]/opt->_xRed, opt->histolo[arrivalTime], opt->histohi[arrivalTime]); // time34 = new TH2F("time34", "t_{4} vs. t_{3}; t_{3} (ns); t_{4} (ns)", 100, 0., 100., 100, 0., 100.); // if( gApplication->Argc() > 1 ) basename = gApplication->Argv()[1]; // std::cout << "basename = " << basename << "\n"; // Placement of histograms // unsigned ny = int(sqrt(float(nObservables))); // unsigned nx = int(ceil(nObservables / ny)); // fCanvas01->Divide(nx, ny, .002, .002); // fCanvas02->Divide(nx, ny, .002, .002); // for( unsigned ih=0; ih<nObservables; ih++) { // fCanvas01->cd(ih+1); histo[0][ih]->Draw(); // fCanvas02->cd(ih+1); histo[1][ih]->Draw(); // } // fCanvas2D->Divide(2, 2, .002, .002); // fCanvas2D->cd(1); eTot12->Draw("colz"); // fCanvas2D->cd(2); ePrompt12->Draw("colz"); // fCanvas2D->cd(3); time12->Draw("colz"); // fCanvas2D->cd(4); time34->Draw("colz"); // eTot12->SetStats(0); // ePrompt12->SetStats(0); // time12->SetStats(0); // time34->SetStats(0); // fCanvasOsc->cd(); // fCanvasOsc->GetListOfPrimitives()->SetOwner(); // fCanvasOsc->SetTickx(); // fCanvasOsc->SetTicky(); // TH1F *oscFrame = new TH1F("OscFrame", "Oscillograms; t (ns); A (mV)", 10, 0., 200.); // oscFrame->SetBit(kCanDelete, false); // oscFrame->SetMinimum(-550); // oscFrame->SetMaximum( 50); // oscFrame->SetStats(false); // oscFrame->Draw(); // oscFrame=NULL; // TLegend * oscLeg = new TLegend(.68, .45, .88, .6); // oscLeg->SetBorderSize(0); // oscLeg->SetFillStyle(4001); // oscLeg->SetTextFont(42); // oscLeg->SetTextSize(.05); // TLegendEntry *leS1 = oscLeg->AddEntry("S1", " S1", "l"); // leS1->SetLineColor(kBlue); // leS1->SetLineWidth(2); // TLegendEntry *leS2 = oscLeg->AddEntry("S2", " S2", "l"); // leS2->SetLineColor(kRed); // leS2->SetLineWidth(2); // oscLeg->Draw(); TGFontPool *pool = gClient->GetFontPool(); // family , size (minus value - in pixels, positive value - in points), weight, slant // kFontWeightNormal, kFontSlantRoman are defined in TGFont.h TGFont *font = pool->GetFont("helvetica", 14, kFontWeightBold, kFontSlantOblique); // TGFont *font = pool->GetFont("-adobe-helvetica-bold-r-normal-*-15-*-*-*-*-*-iso8859-1"); // font->Print(); FontStruct_t ft = font->GetFontStruct(); TGHorizontalFrame *hframeI = new TGHorizontalFrame(this,250,60); TGLabel *nEvtMaxL = new TGLabel(hframeI, "Nevt: "); nEvtMaxL->SetTextFont(ft); hframeI->AddFrame(nEvtMaxL, new TGLayoutHints(kLHintsCenterX,5,1,3,4)); nEvtMaxT = new TGTextEntry(hframeI, new TGTextBuffer(4)); nEvtMaxT->SetText(Form("%d",nEvtMax)); hframeI->AddFrame(nEvtMaxT, new TGLayoutHints(kLHintsCenterX,1,5,3,4)); TGLabel *confL = new TGLabel(hframeI, "Conf: "); confL->SetTextFont(ft); hframeI->AddFrame(confL, new TGLayoutHints(kLHintsCenterX,5,1,3,4)); // confT = new TGTextEntry(hframeI, new TGTextBuffer(10)); // confT->SetText(basename); // confT->SetEnabled(true); confT = new TGComboBox(hframeI); confT->Resize(80,22); confT->AddEntry("PED",0); confT->AddEntry("LED",1); confT->AddEntry("SOURCE",2); confT->Select(0); hframeI->AddFrame(confT, new TGLayoutHints(kLHintsCenterX,1,5,3,4)); TGLabel *runIdL = new TGLabel(hframeI, "RunId: "); runIdL->SetTextFont(ft); hframeI->AddFrame(runIdL, new TGLayoutHints(kLHintsCenterX,5,1,3,4)); runIdT = new TGTextEntry(hframeI, new TGTextBuffer(10)); runIdT->SetText("test"); hframeI->AddFrame(runIdT, new TGLayoutHints(kLHintsCenterX,1,5,3,4)); AddFrame(hframeI, new TGLayoutHints(kLHintsCenterX | kLHintsTop | kLHintsExpandY,2,2,2,2)); TGHorizontalFrame *hframeI_1 = new TGHorizontalFrame(this,250,60); TGLabel *spillSizeL = new TGLabel(hframeI_1, "SpillSize: "); spillSizeL->SetTextFont(ft); hframeI_1->AddFrame(spillSizeL, new TGLayoutHints(kLHintsCenterX,5,1,3,4)); spillSizeT = new TGTextEntry(hframeI_1, new TGTextBuffer(4)); spillSizeT->SetText(Form("%d",spillSize)); hframeI_1->AddFrame(spillSizeT, new TGLayoutHints(kLHintsCenterX,1,5,3,4)); TGLabel *interSpillTimeL = new TGLabel(hframeI_1, "InterSpill Time (s): "); interSpillTimeL->SetTextFont(ft); hframeI_1->AddFrame(interSpillTimeL, new TGLayoutHints(kLHintsCenterX,5,1,3,4)); interSpillTimeT = new TGTextEntry(hframeI_1, new TGTextBuffer(4)); interSpillTimeT->SetText(Form("%d",interSpillTime)); hframeI_1->AddFrame(interSpillTimeT, new TGLayoutHints(kLHintsCenterX,1,5,3,4)); ledScan = new TGCheckButton(hframeI_1, "LED SCAN", 4); ledScan->SetState(kButtonUp); hframeI_1->AddFrame(ledScan, new TGLayoutHints(kLHintsCenterX,1,5,3,4)); AddFrame(hframeI_1, new TGLayoutHints(kLHintsLeft | kLHintsTop | kLHintsExpandY,2,2,2,2)); TGHorizontalFrame *hframeO = new TGHorizontalFrame(this,250,60); TGLabel *outFileL = new TGLabel(hframeO, "OutFile: "); outFileL->SetTextFont(ft); hframeO->AddFrame(outFileL, new TGLayoutHints(kLHintsCenterX,5,1,3,4)); outFileT = new TGTextEntry(hframeO, new TGTextBuffer(40)); outFileT->SetText(""); outFileT->SetEnabled(false); hframeO->AddFrame(outFileT, new TGLayoutHints(kLHintsCenterX,1,5,3,4)); AddFrame(hframeO, new TGLayoutHints(kLHintsLeft | kLHintsTop | kLHintsExpandY,2,2,2,2)); // Create a horizontal frame widget with buttons TGHorizontalFrame *hframe = new TGHorizontalFrame(this,250,60); TGTextButton *start = new TGTextButton(hframe,"&Start"); start->Connect("Clicked()","MonitorFrame", this, "Start()"); start->SetFont(ft); hframe->AddFrame(start, new TGLayoutHints(kLHintsCenterX,5,5,3,4)); TGTextButton *stop = new TGTextButton(hframe,"&Stop"); stop->Connect("Clicked()","MonitorFrame",this,"Stop()"); stop->SetFont(ft); hframe->AddFrame(stop, new TGLayoutHints(kLHintsCenterX,5,5,3,4)); TGTextButton *hardstop = new TGTextButton(hframe,"&Stop!"); hardstop->Connect("Clicked()","MonitorFrame",this,"HardStop()"); hardstop->SetFont(ft); hframe->AddFrame(hardstop, new TGLayoutHints(kLHintsCenterX,5,5,3,4)); /* TGTextButton *save = new TGTextButton(hframe,"&Save"); save->Connect("Clicked()","MonitorFrame",this,"Save()"); save->SetFont(ft); hframe->AddFrame(save, new TGLayoutHints(kLHintsCenterX,5,5,3,4)); TGTextButton *exportText = new TGTextButton(hframe,"&Export Text"); exportText->Connect("Clicked()","MonitorFrame",this,"ExportText()"); exportText->SetFont(ft); hframe->AddFrame(exportText, new TGLayoutHints(kLHintsCenterX,5,5,3,4)); */ TGTextButton *exit = new TGTextButton(hframe,"&Exit"); exit->Connect("Clicked()", "MonitorFrame",this,"Exit()"); exit->SetFont(ft); // exit->Connect("Clicked()", "TApplication", gApplication, "Terminate(0)"); hframe->AddFrame(exit, new TGLayoutHints(kLHintsCenterX,5,5,3,4)); AddFrame(hframe, new TGLayoutHints(kLHintsCenterX | kLHintsTop | kLHintsExpandY,2,2,2,2)); // Create a horizontal frame widget with text displays TGHorizontalFrame *hframeT = new TGHorizontalFrame(this,250,60); TGLabel *nEvtAcqL = new TGLabel(hframeT, "N acq.: "); nEvtAcqL->SetTextFont(ft); hframeT->AddFrame(nEvtAcqL, new TGLayoutHints(kLHintsCenterX,5,1,3,4)); nEvtAcqT = new TGLabel(hframeT, Form("%-15i", 0)); nEvtAcqT->SetTextFont(ft); hframeT->AddFrame(nEvtAcqT, new TGLayoutHints(kLHintsCenterX,1,5,3,4)); TGLabel *nEvtProL = new TGLabel(hframeT, "N proc.: "); nEvtProL->SetTextFont(ft); hframeT->AddFrame(nEvtProL, new TGLayoutHints(kLHintsCenterX,5,1,3,4)); nEvtProT = new TGLabel(hframeT, Form("%-15i", 0)); nEvtProT->SetTextFont(ft); hframeT->AddFrame(nEvtProT, new TGLayoutHints(kLHintsCenterX,1,5,3,4)); TGLabel *rateL = new TGLabel(hframeT, "Rate: "); rateL->SetTextFont(ft); hframeT->AddFrame(rateL, new TGLayoutHints(kLHintsCenterX,5,1,3,4)); rateT = new TGLabel(hframeT, "0.000 evt/s"); rateT->SetTextFont(ft); hframeT->AddFrame(rateT, new TGLayoutHints(kLHintsCenterX,1,5,3,4)); AddFrame(hframeT, new TGLayoutHints(kLHintsCenterX | kLHintsTop | kLHintsExpandY,2,2,2,2)); // Create a horizontal frame widget with displays of board status TGHorizontalFrame *hframeB = new TGHorizontalFrame(this,250,60); TGLabel *temperatureL = new TGLabel(hframeB, "T = "); temperatureL->SetTextFont(ft); hframeB->AddFrame(temperatureL, new TGLayoutHints(kLHintsCenterX,5,1,3,4)); temperatureT = new TGLabel( hframeB, Form("%.1f\xB0", drs->GetBoard(0)->GetTemperature())); temperatureT->SetTextFont(ft); hframeB->AddFrame(temperatureT, new TGLayoutHints(kLHintsCenterX,1,5,3,4)); TGTextButton *refresh = new TGTextButton(hframeB,"&Refresh"); refresh->Connect("Clicked()","MonitorFrame",this,"RefreshT()"); refresh->SetFont(ft); hframeB->AddFrame(refresh, new TGLayoutHints(kLHintsCenterX,5,5,3,4)); AddFrame(hframeB, new TGLayoutHints(kLHintsCenterX | kLHintsTop | kLHintsExpandY,2,2,2,2)); TGHorizontalFrame *hframeP = new TGHorizontalFrame(this,250,60); fHProg2 = new TGHProgressBar(hframeP, TGProgressBar::kFancy, 100); fHProg2->SetBarColor("lightblue"); fHProg2->ShowPosition(kTRUE, kFALSE, "%.0f events"); fHProg2->SetRange(0,nEvtMax); fHProg2->Reset(); hframeP->AddFrame(fHProg2, new TGLayoutHints(kLHintsTop | kLHintsCenterX | kLHintsExpandX, 1,1,1,1)); AddFrame(hframeP, new TGLayoutHints(kLHintsCenterX | kLHintsTop | kLHintsExpandX,2,2,2,2)); std::cout << "Added labels.\n"; // Set a name to the main frame SetWindowName("DRS4 DAQ Control"); // Map all subwindows of main frame MapSubwindows(); // Initialize the layout algorithm Resize(GetDefaultSize()); // Map main frame MapWindow(); std::cout << "Constructed main window.\n"; #ifdef ROOT_OUTPUT outTree = new TTree ("H4tree", "H4 testbeam tree") ; h4daqEvent = new H4DAQ::Event(outTree) ; #endif } MonitorFrame::~MonitorFrame() { std::cout << "Cleanup main frame.\n"; // for(int iobs=0; iobs<nObservables; iobs++) { // delete histo[0][iobs]; // histo[0][iobs] = NULL; // delete histo[1][iobs]; // histo[1][iobs] = NULL; // } // delete eTot12; eTot12 = NULL; // delete ePrompt12; ePrompt12 = NULL; // delete time12; time12 = NULL; // delete time34; time34 = NULL; // if (fCanvas01) delete fCanvas01; fCanvas01 = NULL; // if (frCanvas01) delete frCanvas01; // if (fCanvas02) delete fCanvas02; // if (frCanvas02) delete frCanvas02; // if (fCanvas2D) delete fCanvas2D; // if (frCanvas2D) delete frCanvas2D; // if (fCanvasOsc) delete fCanvasOsc; // if (frCanvasOsc) delete frCanvasOsc; if (writer) { delete writer; writer = NULL; } if (fifo) { delete fifo; fifo = NULL; } if (drs) { // Make sure board(s) are idle before exiting for (int iboard = 0; iboard<drs->GetNumberOfBoards(); iboard++) { drs->GetBoard(iboard)->Reinit(); } delete drs; drs = NULL; } if (headers) { delete headers; headers = NULL; } if (rawWave) { delete rawWave; rawWave = NULL; } if (event) { delete event; event = NULL; } } void MonitorFrame::Exit() { HardStop(); gApplication->SetReturnFromRun(true); gApplication->Terminate(0); } void MonitorFrame::Start() { if (f_running) { return; } bool leds=ledScan->GetState()==kButtonDown; std::cout << "Starting Monitor frame.\n"; if (leds) std::cout << "Performing LED Scan\n"; nEvtMaxT->SetEnabled(false); spillSizeT->SetEnabled(false); interSpillTimeT->SetEnabled(false); runIdT->SetEnabled(false); confT->SetEnabled(false); ledScan->SetEnabled(false); lastSpill=0; if(!drs) { std::cout << "MonitorFrame::Start() - ERROR: DRS object empty." << std::endl; return; } if(drs->GetNumberOfBoards() < 1) { std::cout << "MonitorFrame::Start() - ERROR: No DRS boards present." << std::endl; return; } ParseConfig(); ConfigDRS(); if(writer) { if (writer->isRunning() || writer->isJoinable()) { std::cout << "WARNING: Attempt to start while writer is running.!" << std::endl; return; } delete writer; } fifo->Discard(); #ifdef LED_SCAN writer = new DRS4_writer(drs, fifo,leds); #else writer = new DRS4_writer(drs, fifo); #endif if(options->triggerSource == 0) { writer->setAutoTrigger(); } temperatureT->SetText(Form("%.1f\xB0", writer->Temperature())); /*** Clear histograms ***/ // for(int iobs=0; iobs<nObservables; iobs++) { // histo[0][iobs]->Reset(); // histo[1][iobs]->Reset(); // } // eTot12->Reset(); // ePrompt12->Reset(); // time12->Reset(); // time34->Reset(); fHProg2->Reset(); timer.Start(); timeLastSave = 0; iEvtProcessed=0; headers = DRS4_data::DRSHeaders::MakeDRSHeaders(drs); if (StartNewFile() != 0) { writer->stop(); delete writer; writer = NULL; return; } rate = new MonitorFrame::RateEstimator(); rate->Push(0, 1.e-9); // One false time value to avoid division by zero DoDraw(true); /*** Start writer ***/ nEvtMax=TString(nEvtMaxT->GetText()).Atoi(); spillSize=TString(spillSizeT->GetText()).Atoi(); interSpillTime=TString(interSpillTimeT->GetText()).Atoi(); writer->setSpillSize(spillSize); writer->setInterSpillTime(interSpillTime); writer->setLedScan(leds); fHProg2->SetRange(0,nEvtMax); writer->start(nEvtMax); while (!writer->isRunning()) { std::this_thread::sleep_for(std::chrono::milliseconds(10)); }; /*** Start monitor ***/ Run(); /*** Cleanup after the run finishes ***/ #ifndef ROOT_OUTPUT if (file) { if (file->is_open()) { file->close(); } delete file; file = NULL; } #else if (file) { if (file->IsOpen()) { file->cd() ; outTree->Write ("",TObject::kOverwrite) ; file->Close(); outTree->Reset(); } delete file; file = NULL; } #endif f_running = false; if (rate) { delete rate; rate = NULL; } if (headers) { delete headers; headers = NULL; } if (writer) { delete writer; writer = NULL; } #ifdef ROOT_OUTPUT if (outTree) { delete outTree; outTree = NULL; } if (h4daqEvent) { delete h4daqEvent; event = NULL; } #endif } int MonitorFrame::Run() { std::cout << "Monitor on CPU " << sched_getcpu() << "\n"; f_stop = false; f_stopWhenEmpty = false; f_running = true; // Time calibrations const bool tCalibrated = true; // Whether time points should come calibrated const bool tRotated = true; // Whether time points should come rotated // Voltage calibrations const bool applyResponseCalib = true; // Remove noise and offset variations const bool adjustToClock = false; // Extra rotation of amplitudes in the calibration step - SET TO FALSE ! const bool adjustToClockForFile = false; const bool applyOffsetCalib = false; // ? unsigned iEvtLocal = 0; while(!f_stop) { rawWave = fifo->Read(); if(rawWave) { iEvtSerial = rawWave->header.getEventNumber(); //start new file when reached spill size if (iEvtLocal>0 && iEvtLocal%spillSize == 0) { StartNewFile(); //a new spill in H4DAQ language } iEvtLocal++; //std::cout << "Read event #" << iEvtSerial << std::endl; // std::cout << "Trigger cell is " << rawWave->header.getTriggerCell() << std::endl; event = new DRS4_data::Event(iEvtSerial, lastSpill, rawWave->header, drs); // Observables *obs[2] = {NULL, NULL}; int16_t wf[4][kNumberOfBins]; for(int iboard=0; iboard<headers->ChTimes()->size(); iboard++) { DRSBoard *b = drs->GetBoard(iboard); /* decode waveform (Y) arrays in mV */ for (unsigned char ichan=0 ; ichan<4 ; ichan++) { b->GetWave(rawWave->eventWaves.at(iboard)->waveforms, 0, ichan*2, static_cast<short*>(wf[ichan]), applyResponseCalib, int(rawWave->header.getTriggerCell()), -1, adjustToClockForFile, 0, applyOffsetCalib); } RemoveSpikes(wf, 20, 2); for (unsigned char ichan=0 ; ichan<4 ; ichan++) { // float timebins[kNumberOfBins]; // b->GetTime(0, ichan*2, int(rawWave->header.getTriggerCell()), timebins, tCalibrated, tRotated); // float amplitude[kNumberOfBins]; for (unsigned ibin=0; ibin<kNumberOfBins; ibin++) { // amplitude[ibin] = static_cast<float>(wf[ichan][ibin]) / 10; event->getChData(iboard, ichan)->data[ibin] = wf[ichan][ibin] ; } // if (ichan<2 && iboard==0) { // obs[ichan] = WaveProcessor::ProcessOnline(timebins, amplitude, kNumberOfBins, 4., baseLineWidth); // obs[ichan]->hist->SetName(Form("Oscillogram_ch%d", ichan+1)); // } } // Loop over the channels } // Loop over the boards iEvtProcessed++; // FillHistos(obs); // if(obs[0]) { // delete obs[0]; obs[0] = NULL; // } // if(obs[1]) { // delete obs[1]; obs[1] = NULL; // } #ifndef ROOT_OUTPUT event->write(file); #else //Fill H4DAQ event structure h4daqEvent->clear(); fillH4Event(headers,event,h4daqEvent); h4daqEvent->Fill(); // std::cout << "Filled event " << h4daqEvent->id.evtNumber << std::endl; #endif delete event; event = NULL; delete rawWave; rawWave = NULL; // if(iEvtProcessed%500 == 0) { // std::cout << "Processed event #" << iEvtProcessed << std::endl; // } } // If rawWave (fifo not empty) else { if( f_stopWhenEmpty ) { f_stop = true; break; } else { std::this_thread::sleep_for(std::chrono::milliseconds(10)); } // if(f_stopWhenEmpty) } // if(rawWave) gClient->ProcessEventsFor(this); if (!writer->isRunning()) { f_stopWhenEmpty = true; } if ( int(timer.RealTime()*100) % 20 == 0 ) DoDraw(true); timer.Continue(); } // !f_stop DoDraw(true); nEvtMaxT->SetEnabled(true); spillSizeT->SetEnabled(true); interSpillTimeT->SetEnabled(true); runIdT->SetEnabled(true); confT->SetEnabled(true); ledScan->SetEnabled(true); std::cout << "Events processed: " << iEvtProcessed << "\n"; std::cout << Form("Elapsed time: %6.2f s.\n", timer.RealTime()); std::cout << Form("Event rate: %6.2f events/s \n", float(iEvtProcessed)/timer.RealTime()); f_running = false; return 0; } void MonitorFrame::Stop() { if(!f_running) return; if (f_stopWhenEmpty) return; std::cout << "\n\nStopping acquisition.\n"; writer->stop(); timer.Stop(); nEvtMaxT->SetEnabled(true); spillSizeT->SetEnabled(true); interSpillTimeT->SetEnabled(true); runIdT->SetEnabled(true); confT->SetEnabled(true); ledScan->SetEnabled(true); f_stopWhenEmpty = true; } void MonitorFrame::HardStop() { if(!f_running) return; if(f_stop) return; std::cout << "\n\nStopping acquisition and monitor.\n"; writer->stop(); timer.Stop(); f_stop = true; f_stopWhenEmpty = true; nEvtMaxT->SetEnabled(true); spillSizeT->SetEnabled(true); interSpillTimeT->SetEnabled(true); runIdT->SetEnabled(true); confT->SetEnabled(true); ledScan->SetEnabled(true); fifo->Discard(); } void MonitorFrame::RefreshT() { double t; if (writer) { t = writer->Temperature(); } else { t = drs->GetBoard(0)->GetTemperature(); } temperatureT->SetText(Form("%.1f\xB0", t)); } void MonitorFrame::FillHistos(Observables *obs[2]) { // for(unsigned ichan=0; ichan<2; ichan++) { // for(int iobs=0; iobs<nObservables; iobs++) { // histo[ichan][iobs]->Fill(obs[ichan]->Value(static_cast<kObservables>(iobs))); // } // } // eTot12->Fill(obs[0]->Value(eTot), obs[1]->Value(eTot)); // ePrompt12->Fill(obs[0]->Value(ePrompt), obs[1]->Value(ePrompt)); // time12->Fill(obs[0]->Value(arrivalTime), obs[1]->Value(arrivalTime)); // // TODO: calculate and process t3 and t4 // itRed++; itRed2D++; // if (itRed >= tRed) { // itRed=0; // bool draw2D = false; // if(itRed2D >= tRed2D) { // itRed2D=0; // itRed=0; // draw2D = true; // } // DoDraw(draw2D); // fCanvasOsc->cd(); // // Remove previous oscillograms // TList *listp = gPad->GetListOfPrimitives(); // TObject *last = listp->Last(); // if (last->IsA() == obs[0]->hist->IsA()) { // listp->RemoveLast(); // delete dynamic_cast<TH1F*>(last); // last = listp->Last(); // if (last->IsA() == obs[0]->hist->IsA()) { // listp->RemoveLast(); // delete dynamic_cast<TH1F*>(last); // } // } // // obs[0]->hist->Rebin(3); // obs[0]->hist->SetLineColor(kBlue); // obs[0]->hist->Scale(-1); // obs[0]->hist->DrawCopy("same hist l")->SetBit(kCanDelete); // // obs[1]->hist->Rebin(3); // obs[1]->hist->SetLineColor(kRed); // obs[1]->hist->Scale(-1); // obs[1]->hist->DrawCopy("same hist l")->SetBit(kCanDelete); // fCanvasOsc->Update(); // } } // FillHistos() void MonitorFrame::DoDraw(bool all) { // Draws function graphics in randomly chosen interval // fCanvas01->Paint(); // fCanvas02->Paint(); // fCanvas01->Update(); // fCanvas02->Update(); // if(all) { // fCanvas2D->Paint(); // fCanvas2D->Update(); // } unsigned nAcq = writer->NEvents(); unsigned timeLast = fifo->timeLastEvent(); nEvtAcqT->SetText(Form("%-10i", nAcq)); nEvtProT->SetText(Form("%-10i", iEvtProcessed)); fHProg2->SetPosition(iEvtProcessed); rate->Push(nAcq, static_cast<double>(timeLast)/1000); rateT->SetText(Form("%5.3g evt/s", rate->Get())); temperatureT->SetText(Form("%.1f\xB0", writer->Temperature())); timer.Continue(); } void MonitorFrame::AutoSave() { TTimeStamp ts(std::time(NULL), 0); filename = basename; filename += "_autosave_"; filename += ts.GetDate(0); filename += "-"; filename += ts.GetTime(0); timestamped = true; Save(); filename = basename; timestamped=false; } void MonitorFrame::Save() { // if ( !timestamped ) { // TTimeStamp ts(std::time(NULL), 0); // filename = basename; // filename += "_"; // filename += ts.GetDate(0); // filename += "-"; // filename += ts.GetTime(0); // } // TString rootfilename(filename); rootfilename += ".root"; // TFile output(rootfilename.Data(), "RECREATE"); // if(!(output.IsOpen())) { // std::cout << "\nCannot open output root file " << rootfilename.Data() << ".\n"; // // gApplication->Terminate(0); // } // for(int iobs=0; iobs<nObservables; iobs++) { // histo[0][iobs]->Clone()->Write(); // histo[1][iobs]->Clone()->Write(); // } // eTot12->Clone()->Write(); // ePrompt12->Clone()->Write(); // time12->Clone()->Write(); // time34->Clone()->Write(); // output.Close(); // std::cout << "\nSaved data in " << rootfilename.Data() << "\n"; // timeLastSave = timer.RealTime(); timer.Continue(); } void MonitorFrame::ExportText() { /* if ( !timestamped ) { TTimeStamp ts(std::time(NULL), 0); filename = basename; filename += "_"; filename += ts.GetDate(0); filename += "-"; filename += ts.GetTime(0); } TString textfilename(filename); textfilename += ".dat"; std::ofstream exportfile(textfilename.Data(), std::ios::trunc); if (!exportfile.is_open()) { std::cout << "\nCannot open file " << textfilename.Data() << " for writing.\n"; return; } for (kObservables i=0; i<nObservables; i++) { exportfile << Form(" %s(1) ", obs->Name(i)); } for (kObservables i=0; i<nObservables; i++) { exportfile << Form(" %s(2) ", obs->Name(i)); } exportfile << "\n"; for (int iEvt=0; iEvt<events->GetEntries(); iEvt++) { events->GetEvent(iEvt); for (kObservables i=0; i<nObservables; i++) { exportfile << Form("%8.3f", ???); } for (kObservables i=0; i<nObservables; i++) { exportfile << Form("%8.3f", ???); } exportfile << "\n"; } exportfile.close(); std::cout << "\nSaved text data in " << textfilename.Data() << "\n"; */ } void MonitorFrame::RateEstimator::Push(int count, double time) { rateCounts.push(count); rateTimes.push(time); int nEvtRate = rateCounts.back() - rateCounts.front(); if (nEvtRate) { evtRate = double(nEvtRate) / (rateTimes.back() - rateTimes.front()); } else { evtRate = 0; } if(nEvtRate >= rateCountPeriod || rateCounts.size() > maxSize) { rateCounts.pop(); rateTimes.pop(); } } int MonitorFrame::StartNewFile() { lastSpill++; TTimeStamp ts(std::time(NULL), 0); filename = options->outDir+ "/"; filename += TString(runIdT->GetText()); if (!gSystem->OpenDirectory(filename.Data())) gSystem->mkdir(filename.Data()); filename += Form("/%d",lastSpill); filename += "_"; filename += ts.GetDate(0); filename += "-"; filename += ts.GetTime(0); //filename = outDir / runId / spillNumber_timestamp.dat #ifndef ROOT_OUTPUT if (file) { if (file->is_open()) { file->close(); } } else { file = new std::ofstream(); } filename += ".dat"; std::cout << "Opening output file " << filename << std::endl; file->open(filename, std::ios_base::binary & std::ios_base::trunc) ; if( file->fail() ) { std::cout << "ERROR: Cannot open file " << filename << " for writing.\n"; return -1; } /*** Write file header and time calibration ***/ std::cout << "Writing headers and time calibration to file." << std::endl; if (!headers) { headers = DRS4_data::DRSHeaders::MakeDRSHeaders(drs); } headers->write(file); #else if (file) { if (file->IsOpen()) { file->cd () ; outTree->Write ("",TObject::kOverwrite) ; file->Close(); outTree->Reset(); } } filename += ".root"; std::cout << "Opening output file " << filename << std::endl; file = TFile::Open(filename, "RECREATE") ; if (!file->IsOpen()) { std::cout << "ERROR: Cannot open file " << filename << " for writing.\n"; return -1; } #endif outFileT->SetText(filename.Data()); return 0; } void MonitorFrame::ParseConfig() { if (!options) return; //do not need reconfig // if (confStatus == confT->GetSelected()) // return; //Configuration possibilities TString inputFile; if(confT->GetSelected() == 0) inputFile="conf/ped.conf"; else if(confT->GetSelected() == 1) inputFile="conf/led.conf"; else if(confT->GetSelected() == 2) inputFile="conf/source.conf"; std::ifstream input(inputFile); if(!input.is_open()) { std::cout << "Cannot open input file " << inputFile << ".\n"; return ; } if (options->ParseOptions(&input) < 0) { std::cout << "Error parsing options.\n"; return; } confStatus = confT->GetSelected(); options->DumpOptions(); } void MonitorFrame::ConfigDRS() { if (!drs) return; /* * We allow more than one board with synchronized triggers. * For simplicity, we assume that 4 channels are acquired from each board. */ /* use first board with highest serial number as the master board */ drs->SortBoards(); DRSBoard *mb = drs->GetBoard(0); /* common configuration for all boards */ for (int iboard=0 ; iboard<drs->GetNumberOfBoards() ; iboard++) { std::cout << "Configuring board #" << iboard << std::endl; DRSBoard *b = drs->GetBoard(iboard); /* initialize board */ std::cout << "Initializing." << std::endl; b->Init(); /* select external reference clock for slave modules */ /* NOTE: this only works if the clock chain is connected */ if (iboard > 0) { if (b->GetFirmwareVersion() >= 21260) { // this only works with recent firmware versions if (b->GetScaler(5) > 300000) // check if external clock is connected b->SetRefclk(true); // switch to external reference clock } } /* set sampling frequency */ std::cout << "Setting frequency to " << options->sampleRate << " GHz." << std::endl; b->SetFrequency(options->sampleRate, true); /* set input range to -0.5V ... +0.5V */ std::cout << "Setting input range to (-0.5V -> +0.5V)." << std::endl; b->SetInputRange(options->inputRange); /* enable hardware trigger * (1, 0) = "fast trigger", "analog trigger" * Board types 8, 9 always need (1, 0) * other board types take (1, 0) for external (LEMO/FP/TRBUS) * and (0, 1) for internal trigger (analog threshold). */ b->EnableTrigger(1, 0); if (iboard == 0) { /* master board: enable hardware trigger on CH1 at -50 mV negative edge */ std::cout << "Configuring master board." << std::endl; b->SetTranspMode(1); b->SetTriggerSource(options->triggerSource); // set CH1 as source b->SetTriggerLevel(options->triggerLevel); // -50 mV b->SetTriggerPolarity(options->triggerNegative); // negative edge b->SetTriggerDelayNs(options->trigDelay); // Trigger delay shifts waveform left } else { /* slave boards: enable hardware trigger on Trigger IN */ std::cout << "Configuring slave board." << std::endl; b->SetTriggerSource(1<<4); // set Trigger IN as source b->SetTriggerPolarity(false); // positive edge } } // End loop for common configuration }
30.884939
196
0.634026
CMSROMA
e4bae3cb7fcc5f993c72157ed02a0e4b90e716e5
2,829
cpp
C++
targets/all/io/tests/pipes/Pipes.cpp
minuteos/lib
288fe4f9221fb431e15792421e21084f29dccdce
[ "MIT" ]
null
null
null
targets/all/io/tests/pipes/Pipes.cpp
minuteos/lib
288fe4f9221fb431e15792421e21084f29dccdce
[ "MIT" ]
null
null
null
targets/all/io/tests/pipes/Pipes.cpp
minuteos/lib
288fe4f9221fb431e15792421e21084f29dccdce
[ "MIT" ]
null
null
null
/* * Copyright (c) 2019 triaxis s.r.o. * Licensed under the MIT license. See LICENSE.txt file in the repository root * for full license information. * * io/tests/pipes/Pipes.cpp */ #include <testrunner/TestCase.h> #include <kernel/kernel.h> #include <io/io.h> namespace { using namespace io; using namespace kernel; TEST_CASE("01 Simple Pipe") { Scheduler s; Pipe p; struct S { static async(Writer, PipeWriter w) async_def() { await(w.Write, "TEST"); w.Close(); } async_end static async(Reader, PipeReader r) async_def() { size_t n; n = await(r.Read); AssertEqual(n, 4u); AssertEqual(r.Available(), 4u); AssertEqual(r.IsComplete(), true); Assert(r.Matches("TEST")); r.Advance(n); } async_end }; s.Add(&S::Reader, p); s.Add(&S::Writer, p); s.Run(); Assert(p.IsCompleted()); } TEST_CASE("02 Multi Write") { Scheduler s; Pipe p; struct S { static async(Writer, PipeWriter w) async_def() { await(w.Write, "TE"); async_yield(); await(w.Write, "ST"); w.Close(); } async_end static async(Reader, PipeReader r) async_def() { size_t n; n = await(r.Read); AssertEqual(n, 2u); AssertEqual(r.Available(), 2u); AssertEqual(r.IsComplete(), false); Assert(r.Matches("TE")); n = await(r.Read, 3); AssertEqual(n, 4u); AssertEqual(r.Available(), 4u); AssertEqual(r.IsComplete(), true); Assert(r.Matches("TEST")); r.Advance(n); } async_end }; s.Add(&S::Reader, p); s.Add(&S::Writer, p); s.Run(); Assert(p.IsCompleted()); } TEST_CASE("03 Read Until") { Scheduler s; Pipe p; struct S { static async(Writer, PipeWriter w) async_def() { await(w.Write, "Line 1\nLine 2"); w.Close(); } async_end static async(Reader, PipeReader r) async_def() { size_t n; n = await(r.ReadUntil, '\n'); AssertEqual(n, 7u); Assert(r.Matches("Line 1\n")); r.Advance(n); n = await(r.ReadUntil, '\n'); AssertEqual(n, 0u); AssertEqual(r.IsComplete(), true); AssertEqual(r.Available(), 6u); Assert(r.Matches("Line 2")); // no terminator r.Advance(6); } async_end }; s.Add(&S::Reader, p); s.Add(&S::Writer, p); s.Run(); Assert(p.IsCompleted()); } }
20.207143
78
0.481796
minuteos
e4bb426bd9fae6c5ae9cd39131dad34e8c6ead2b
2,300
cpp
C++
src/qPoly.cpp
MaddTheSane/executor
2a8baf83066ead802ae22e567af41d74a4e920ff
[ "MIT" ]
12
2016-02-01T06:26:19.000Z
2022-01-09T00:14:20.000Z
src/qPoly.cpp
MaddTheSane/executor
2a8baf83066ead802ae22e567af41d74a4e920ff
[ "MIT" ]
2
2017-07-16T02:24:15.000Z
2018-02-14T04:15:37.000Z
src/qPoly.cpp
MaddTheSane/executor
2a8baf83066ead802ae22e567af41d74a4e920ff
[ "MIT" ]
4
2017-04-07T13:55:46.000Z
2022-01-09T00:14:17.000Z
/* Copyright 1986, 1989, 1990 by Abacus Research and * Development, Inc. All rights reserved. */ #if !defined (OMIT_RCSID_STRINGS) char ROMlib_rcsid_qPoly[] = "$Id: qPoly.c 63 2004-12-24 18:19:43Z ctm $"; #endif /* Forward declarations in QuickDraw.h (DO NOT DELETE THIS LINE) */ /* HLock checked by ctm on Mon May 13 17:55:01 MDT 1991 */ #include "rsys/common.h" #include "QuickDraw.h" #include "MemoryMgr.h" #include "rsys/quick.h" #include "rsys/cquick.h" using namespace Executor; P0(PUBLIC pascal trap, PolyHandle, OpenPoly) { PolyHandle ph; ph = (PolyHandle) NewHandle ((Size) SMALLPOLY); HxX(ph, polySize) = CWC (SMALLPOLY); PORT_POLY_SAVE_X (thePort) = RM ((Handle) ph); HidePen(); return(ph); } P0(PUBLIC pascal trap, void, ClosePoly) { INTEGER top = 32767, left = 32767, bottom = -32767, right = -32767; INTEGER *ip, *ep, i; PolyHandle ph; ph = (PolyHandle) PORT_POLY_SAVE (thePort); for (ip = (INTEGER *)((char *)STARH(ph) + SMALLPOLY), ep = (INTEGER *)((char *)STARH(ph) + Hx(ph, polySize)); ip != ep;) { if ((i = CW(*ip)) <= top) top = i; ++ip; if (i >= bottom) bottom = i; if ((i = CW(*ip)) <= left) left = i; ++ip; if (i >= right) right = i; } HxX(ph, polyBBox.top) = CW(top); HxX(ph, polyBBox.left) = CW(left); HxX(ph, polyBBox.bottom) = CW(bottom); HxX(ph, polyBBox.right) = CW(right); PORT_POLY_SAVE_X (thePort) = (Handle)CWC (0); ShowPen(); } P1(PUBLIC pascal trap, void, KillPoly, PolyHandle, poly) { DisposHandle((Handle) poly); } P3(PUBLIC pascal trap, void, OffsetPoly, PolyHandle, poly, INTEGER, dh, INTEGER, dv) /* Note: IM I-191 is wrong */ { Point *pp, *ep; if (dh || dv) { HxX(poly, polyBBox.top) = CW(Hx(poly, polyBBox.top) + dv); HxX(poly, polyBBox.bottom) = CW(Hx(poly, polyBBox.bottom) + dv); HxX(poly, polyBBox.left) = CW(Hx(poly, polyBBox.left) + dh); HxX(poly, polyBBox.right) = CW(Hx(poly, polyBBox.right) + dh); pp = HxX(poly, polyPoints); ep = (Point *) (((char *) STARH(poly)) + Hx(poly, polySize)); while (pp != ep) { pp->h = CW(CW(pp->h) + (dh)); pp->v = CW(CW(pp->v) + (dv)); pp++; } } }
26.436782
71
0.576522
MaddTheSane
e4bd5fc30070a2ee30344c2331d642ac1b2b571d
7,723
cpp
C++
Lesson7/Activity01/Util.cpp
mkkekkonen/AdvancedCpp
f29598fed3c30d090f9c6c93bb0409135ca1c32e
[ "MIT" ]
30
2019-09-02T11:55:44.000Z
2022-03-09T14:43:27.000Z
Lesson7/Activity01/Util.cpp
animewasmistake/Advanced-CPlusPlus
b2ba3fc955b1dc0c617b0b2543fc82ad36573ff2
[ "MIT" ]
null
null
null
Lesson7/Activity01/Util.cpp
animewasmistake/Advanced-CPlusPlus
b2ba3fc955b1dc0c617b0b2543fc82ad36573ff2
[ "MIT" ]
24
2019-08-05T07:08:08.000Z
2022-03-08T07:48:35.000Z
#include<CommonHeader.h> // Utility function to remove spaces and tabs from start of string and end of string.. string trim (string &str) { // remove space and tab from string. string res(""); if ((str.find(' ') != string::npos) || (str.find('\t') != string::npos)){ // if space or tab found.. size_t begin, end; if ((begin = str.find_first_not_of(" \t")) != string::npos){ // if string is not empty.. end = str.find_last_not_of(" \t"); if ( end >= begin ) res = str.substr(begin, end - begin + 1); } }else{ res = str; // No space or tab found.. } str = res; return res; } // Utility function to check if string contains only digits ( 0-9) and only single '.' // eg . 1121.23 , .113, 121. are valid, but 231.14.143 is not valid. bool isAllNumbers(const string &str){ // make sure, it only contains digit and only single '.' if any return ( all_of(str.begin(), str.end(), [](char c) { return ( isdigit(c) || (c == '.')); }) && (count(str.begin(), str.end(), '.') <= 1) ); } //Utility function to check if string contains only digits (0-9).. bool isDigit(const string &str){ return ( all_of(str.begin(), str.end(), [](char c) { return isdigit(c); })); } // Utility function, where single line of file <infile> is parsed using delimiter. // And store the tokens in vector of string. void parseLine(ifstream &infile, vector<string> & vec, char delimiter){ string line, token; getline(infile, line); istringstream ss(line); vec.clear(); while(getline(ss, token, delimiter)) // break line using delimiter vec.push_back(token); // store tokens in vector of string } // Utility function to check if vector string of 2 strings contain correct // currency and conversion ratio. currency should be 3 characters, conversion ratio // should be in decimal number format. bool parseCurrencyParameters( vector<string> & vec){ trim(vec[0]); trim(vec[1]); return ( (!vec[0].empty()) && (vec[0].size() == 3) && (!vec[1].empty()) && (isAllNumbers(vec[1])) ); } // Utility function, to check if vector of string has correct format for records parsed from Record File. // CustomerId, OrderId, ProductId, Quantity should be in integer format // TotalPrice Regional and USD should be in decimal number format // Currecny should be present in map. bool checkRecord(vector<string> &split){ // Trim all string in vector for (auto &s : split) trim(s); if ( !(isDigit(split[0]) && isDigit(split[3]) && isDigit(split[4]) && isDigit(split[5])) ){ cerr << "ERROR: Record with customer id:" << split[0] << " doesnt have right DIGIT parameter" << endl; return false; } if ( !(isAllNumbers(split[6]) && isAllNumbers(split[8])) ){ cerr << "ERROR: Record with customer id:" << split[0] << " doesnt have right NUMBER parameter" << endl; return false; } if ( currencyMap.find(split[7]) == currencyMap.end() ){ cerr << "ERROR: Record with customer id :" << split[0] << " has currency :" << split[7] << " not present in map" << endl; return false; } return true; } // Function to test initial conditions of file.. // Check if file is present and has correct header information. bool checkFile(ifstream &inFile, string &fileName, string parameter, char delimiter, string &error){ bool flag = true; inFile.open(fileName); if ( inFile.fail() ){ error = "Failed opening " + fileName + " file, with error: " + strerror(errno); flag = false; } if (flag){ vector<string> split; // Parse first line as header and make sure it contains parameter as first token. parseLine(inFile, split, delimiter); if (split.empty()){ error = fileName + " is empty"; flag = false; } else if ( split[0].find(parameter) == string::npos ){ error = "In " + fileName + " file, first line doesnt contain header "; flag = false; } } return flag; } // Function to parse Config file. Each line will have '<name> = <value> format // Store CurrencyConversion file and Record File parameters correctly. bool parseConfig() { ifstream confFile; string error; if (!checkFile(confFile, configFile, "CONFIGURATION_FILE", '=', error)){ cerr << "ERROR: " << error << endl; return false; } bool flag = true; vector<string> split; while (confFile.good()){ parseLine(confFile, split, '='); if ( split.size() == 2 ){ string name = trim(split[0]); string value = trim(split[1]); if ( name == "currencyFile" ) currencyFile = value; else if ( name == "recordFile") recordFile = value; } } if ( currencyFile.empty() || recordFile.empty() ){ cerr << "ERROR : currencyfile or recordfile not set correctly." << endl; flag = false; } return flag; } // Function to parse CurrencyConversion file and store values in Map. bool fillCurrencyMap() { ifstream currFile; string error; if (!checkFile(currFile, currencyFile, "Currency", '|', error)){ cerr << "ERROR: " << error << endl; return false; } bool flag = true; vector<string> split; while (currFile.good()){ parseLine(currFile, split, '|'); if (split.size() == 2){ if (parseCurrencyParameters(split)){ currencyMap[split[0]] = static_cast<float>(atof(split[1].c_str())); // make sure currency is valid. } else { cerr << "ERROR: Processing Currency Conversion file for Currency: "<< split[0] << endl; flag = false; break; } } else if (!split.empty()){ cerr << "ERROR: Processing Currency Conversion , got incorrect parameters for Currency: " << split[0] << endl; flag = false; break; } } return flag; } // Function to parse Record File .. bool parseRecordFile(){ ifstream recFile; string error; if (!checkFile(recFile, recordFile, "Customer Id", '|', error)){ cerr << "ERROR: " << error << endl; return false; } bool flag = true; vector<string> split; while(recFile.good()){ parseLine(recFile, split, '|'); if (split.size() == 9){ if (checkRecord(split)){ vecRecord.push_back(split); //Construct struct record and save it in vector... }else{ cerr << "ERROR : Parsing Record, for Customer Id: " << split[0] << endl; flag = false; break; } } else if (!split.empty()){ cerr << "ERROR: Processing Record, for Customer Id: " << split[0] << endl; flag = false; break; } } return flag; } void displayCurrencyMap(){ cout << "Currency MAP :" << endl; for (auto p : currencyMap) cout << p.first <<" : " << p.second << endl; cout << endl; } ostream& operator<<(ostream& os, const record &rec){ os << rec.customerId <<"|" << rec.firstName << "|" << rec.lastName << "|" << rec.orderId << "|" << rec.productId << "|" << rec.quantity << "|" << fixed << setprecision(2) << rec.totalPriceRegional << "|" << rec.currency << "|" << fixed << setprecision(2) << rec.totalPriceUsd << endl; return os; } void displayRecords(){ cout << " Displaying records with '|' delimiter" << endl; for (auto rec : vecRecord){ cout << rec; } cout << endl; }
34.477679
129
0.573482
mkkekkonen
e4bd71f54771127f3de4aae60424d5533a82ef8b
1,460
cpp
C++
07-functions/7.22-optional-rectangles-sizes/solution.cpp
trangnart/cis22a
498a7b37d12a13efa7749849dc95d9892d1786be
[ "MIT" ]
2
2020-09-04T22:06:06.000Z
2020-09-09T04:00:25.000Z
07-functions/7.22-optional-rectangles-sizes/solution.cpp
trangnart/cis22a
498a7b37d12a13efa7749849dc95d9892d1786be
[ "MIT" ]
14
2020-08-24T01:44:36.000Z
2021-01-01T08:44:17.000Z
07-functions/7.22-optional-rectangles-sizes/solution.cpp
trangnart/cis22a
498a7b37d12a13efa7749849dc95d9892d1786be
[ "MIT" ]
1
2020-09-04T22:13:13.000Z
2020-09-04T22:13:13.000Z
#include <iostream> #include <string> #include <fstream> using namespace std; bool FirstRectangleSmaller(int, int, int, int, int, int, int, int); void CompareRectangles(const string &); int main() { const string FILENAME = "input.txt"; // cout << FirstRectangleSmaller(1,1,2,3,0,0,10,10) << endl; CompareRectangles(FILENAME); return 0; } bool FirstRectangleSmaller(int r1xul, int r1yul, int r1xbr, int r1ybr, int r2xul, int r2yul, int r2xbr, int r2ybr) { int r1Area = (r1xbr - r1xul) * (r1ybr - r1yul); int r2Area = (r2xbr - r2xul) * (r2ybr - r2yul); return abs(r1Area) < abs(r2Area); } void CompareRectangles(const string &filename) { ifstream inFS(filename); int r1x1, r1y1, r1x2, r1y2, r2x1, r2y1, r2x2, r2y2; if (!inFS.is_open()) { cout << "Cannot open file " << filename << endl; return; } while (!inFS.eof()) { inFS >> r1x1 >> r1y1 >> r1x2 >> r1y2 >> r2x1 >> r2y1 >> r2x2 >> r2y2; if (inFS.fail()) { continue; } string tf = FirstRectangleSmaller(r1x1, r1y1, r1x2, r1y2, r2x1, r2y1, r2x2, r2y2) ? "true" : "false"; cout << "(" << r1x1 << "," << r1y1 << ") " << "(" << r1x2 << "," << r1y2 << ") < " << "(" << r2x1 << "," << r2y1 << ") " << "(" << r2x2 << "," << r2y2 << ") is " << tf << endl; } }
24.333333
81
0.506849
trangnart
e4bf33e81a6c08724e9ee4bc7a8ee96aa8056c78
12,582
hpp
C++
include/message_logger/log/log_messages_ros.hpp
ANYbotics/message_logger
66f9f0795f3a6395b6ee2ab7ac5f0df2ffd05f42
[ "BSD-3-Clause" ]
5
2019-12-27T02:04:55.000Z
2022-01-11T13:29:27.000Z
include/message_logger/log/log_messages_ros.hpp
ANYbotics/message_logger
66f9f0795f3a6395b6ee2ab7ac5f0df2ffd05f42
[ "BSD-3-Clause" ]
1
2020-10-22T16:36:03.000Z
2020-10-23T05:53:12.000Z
include/message_logger/log/log_messages_ros.hpp
ANYbotics/message_logger
66f9f0795f3a6395b6ee2ab7ac5f0df2ffd05f42
[ "BSD-3-Clause" ]
4
2019-12-27T02:04:57.000Z
2020-10-22T16:19:18.000Z
/********************************************************************** * Software License Agreement (BSD License) * * Copyright (c) 2014, Christian Gehring * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Autonomous Systems Lab nor ETH Zurich * nor the names of its contributors may be used to endorse or * promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /*! * @file log_messages_ros.hpp * @author Christian Gehring * @date Dec, 2014 * @brief */ #pragma once #include <ros/console.h> #include "message_logger/log/log_messages_backend.hpp" namespace message_logger { namespace log { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #define MELO_LOG(level, ...) \ { \ std::stringstream melo_stringstream; \ melo_stringstream << message_logger::log::parseMemberName(__PRETTY_FUNCTION__) << message_logger::log::getLogColor(level) << message_logger::common::internal::melo_string_format(__VA_ARGS__) << message_logger::log::getResetColor(); \ switch (level) { \ case message_logger::log::levels::Debug: \ { \ ROS_DEBUG("%s", melo_stringstream.str().c_str()); \ } \ break; \ case message_logger::log::levels::Info: \ { \ ROS_INFO("%s", melo_stringstream.str().c_str()); \ } \ break; \ case message_logger::log::levels::Warn: \ { \ ROS_WARN("%s", melo_stringstream.str().c_str()); \ } \ break; \ case message_logger::log::levels::Error: \ { \ ROS_ERROR("%s", melo_stringstream.str().c_str()); \ } \ break; \ case message_logger::log::levels::Fatal: \ { \ ROS_FATAL("%s", melo_stringstream.str().c_str()); \ std::stringstream melo_assert_stringstream; \ melo_assert_stringstream << message_logger::log::colorFatal << message_logger::common::internal::melo_string_format(__VA_ARGS__) << message_logger::log::getResetColor(); \ message_logger::common::internal::melo_throw_exception<message_logger::log::melo_fatal>("[FATAL] ", __FUNCTION__,__FILE__,__LINE__, melo_assert_stringstream.str()); \ } \ break; \ default: \ { \ ROS_INFO(__VA_ARGS__); \ } \ break; \ } \ } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #define MELO_LOG_STREAM(level, message) \ { \ std::stringstream melo_stringstream; \ melo_stringstream << message_logger::log::parseMemberName(__PRETTY_FUNCTION__) << message_logger::log::getLogColor(level) << message << message_logger::log::getResetColor(); \ switch (level) { \ case message_logger::log::levels::Debug: \ { \ ROS_DEBUG_STREAM(melo_stringstream.str()); \ } \ break; \ case message_logger::log::levels::Info: \ { \ ROS_INFO_STREAM(melo_stringstream.str()); \ } \ break; \ case message_logger::log::levels::Warn: \ { \ ROS_WARN_STREAM(melo_stringstream.str()); \ } \ break; \ case message_logger::log::levels::Error: \ { \ ROS_ERROR_STREAM(melo_stringstream.str()); \ } \ break; \ case message_logger::log::levels::Fatal: \ { \ ROS_FATAL_STREAM(melo_stringstream.str()); \ std::stringstream melo_assert_stringstream; \ melo_assert_stringstream << message_logger::log::colorFatal << message << message_logger::log::getResetColor(); \ message_logger::common::internal::melo_throw_exception<message_logger::log::melo_fatal>("[FATAL] ", __FUNCTION__,__FILE__,__LINE__, melo_assert_stringstream.str()); \ } \ break; \ default: \ { \ ROS_INFO_STREAM(message); \ } \ break; \ } \ } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #define MELO_LOG_FP(level, ...) MELO_LOG(level, __VA_ARGS__) //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #define MELO_LOG_STREAM_FP(level, message) MELO_LOG_STREAM(level, message) //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #define MELO_LOG_ONCE(level, ...) \ { \ std::stringstream melo_stringstream; \ melo_stringstream << message_logger::log::parseMemberName(__PRETTY_FUNCTION__) << message_logger::log::getLogColor(level) << message_logger::common::internal::melo_string_format(__VA_ARGS__) << message_logger::log::getResetColor(); \ switch (level) { \ case message_logger::log::levels::Debug: \ { \ ROS_DEBUG_ONCE("%s", melo_stringstream.str().c_str()); \ } \ break; \ case message_logger::log::levels::Info: \ { \ ROS_INFO_ONCE("%s", melo_stringstream.str().c_str()); \ } \ break; \ case message_logger::log::levels::Warn: \ { \ ROS_WARN_ONCE("%s", melo_stringstream.str().c_str()); \ } \ break; \ case message_logger::log::levels::Error: \ { \ ROS_ERROR_ONCE("%s", melo_stringstream.str().c_str()); \ } \ break; \ case message_logger::log::levels::Fatal: \ { \ ROS_FATAL_ONCE("%s", melo_stringstream.str().c_str()); \ std::stringstream melo_assert_stringstream; \ melo_assert_stringstream << message_logger::log::colorFatal << message_logger::common::internal::melo_string_format(__VA_ARGS__) << message_logger::log::getResetColor(); \ message_logger::common::internal::melo_throw_exception<message_logger::log::melo_fatal>("[FATAL] ", __FUNCTION__,__FILE__,__LINE__, melo_assert_stringstream.str()); \ } \ break; \ default: \ { \ ROS_INFO_ONCE(__VA_ARGS__); \ } \ break; \ } \ } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #define MELO_LOG_STREAM_ONCE(level, message) \ { \ std::stringstream melo_stringstream; \ melo_stringstream << message_logger::log::parseMemberName(__PRETTY_FUNCTION__) << message_logger::log::getLogColor(level) << message << message_logger::log::getResetColor(); \ switch (level) { \ case message_logger::log::levels::Debug: \ { \ ROS_DEBUG_STREAM_ONCE(melo_stringstream.str()); \ } \ break; \ case message_logger::log::levels::Info: \ { \ ROS_INFO_STREAM_ONCE(melo_stringstream.str()); \ } \ break; \ case message_logger::log::levels::Warn: \ { \ ROS_WARN_STREAM_ONCE(melo_stringstream.str()); \ } \ break; \ case message_logger::log::levels::Error: \ { \ ROS_ERROR_STREAM_ONCE(melo_stringstream.str()); \ } \ break; \ case message_logger::log::levels::Fatal: \ { \ ROS_FATAL_STREAM_ONCE(melo_stringstream.str()); \ std::stringstream melo_assert_stringstream; \ melo_assert_stringstream << message_logger::log::colorFatal << message << message_logger::log::getResetColor(); \ message_logger::common::internal::melo_throw_exception<message_logger::log::melo_fatal>("[FATAL] ", __FUNCTION__,__FILE__,__LINE__, melo_assert_stringstream.str()); \ } \ break; \ default: \ { \ ROS_INFO_STREAM_ONCE(message); \ } \ break; \ } \ } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #define MELO_LOG_THROTTLE(rate, level, ...) \ { \ std::stringstream melo_stringstream; \ melo_stringstream << message_logger::log::parseMemberName(__PRETTY_FUNCTION__) << message_logger::log::getLogColor(level) << message_logger::common::internal::melo_string_format(__VA_ARGS__) << message_logger::log::getResetColor(); \ switch (level) { \ case message_logger::log::levels::Debug: \ { \ ROS_DEBUG_THROTTLE(rate, "%s", melo_stringstream.str().c_str()); \ } \ break; \ case message_logger::log::levels::Info: \ { \ ROS_INFO_THROTTLE(rate, "%s", melo_stringstream.str().c_str()); \ } \ break; \ case message_logger::log::levels::Warn: \ { \ ROS_WARN_THROTTLE(rate, "%s", melo_stringstream.str().c_str()); \ } \ break; \ case message_logger::log::levels::Error: \ { \ ROS_ERROR_THROTTLE(rate, "%s", melo_stringstream.str().c_str()); \ } \ break; \ case message_logger::log::levels::Fatal: \ { \ ROS_FATAL_THROTTLE(rate, "%s", melo_stringstream.str().c_str()); \ std::stringstream melo_assert_stringstream; \ melo_assert_stringstream << message_logger::log::colorFatal << message_logger::common::internal::melo_string_format(__VA_ARGS__) << message_logger::log::getResetColor(); \ message_logger::common::internal::melo_throw_exception<message_logger::log::melo_fatal>("[FATAL] ", __FUNCTION__,__FILE__,__LINE__, melo_assert_stringstream.str()); \ } \ break; \ default: \ { \ ROS_INFO_THROTTLE(rate, __VA_ARGS__); \ } \ break; \ } \ } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #define MELO_LOG_THROTTLE_STREAM(rate, level, message) \ { \ std::stringstream melo_stringstream; \ melo_stringstream << message_logger::log::parseMemberName(__PRETTY_FUNCTION__) << message_logger::log::getLogColor(level) << message << message_logger::log::getResetColor(); \ switch (level) { \ case message_logger::log::levels::Debug: \ { \ ROS_DEBUG_STREAM_THROTTLE(rate, melo_stringstream.str()); \ } \ break; \ case message_logger::log::levels::Info: \ { \ ROS_INFO_STREAM_THROTTLE(rate, melo_stringstream.str()); \ } \ break; \ case message_logger::log::levels::Warn: \ { \ ROS_WARN_STREAM_THROTTLE(rate, melo_stringstream.str()); \ } \ break; \ case message_logger::log::levels::Error: \ { \ ROS_ERROR_STREAM_THROTTLE(rate, melo_stringstream.str()); \ } \ break; \ case message_logger::log::levels::Fatal: \ { \ ROS_FATAL_STREAM_THROTTLE(rate, melo_stringstream.str()); \ std::stringstream melo_assert_stringstream; \ melo_assert_stringstream << message_logger::log::colorFatal << message << message_logger::log::getResetColor(); \ message_logger::common::internal::melo_throw_exception<message_logger::log::melo_fatal>("[FATAL] ", __FUNCTION__,__FILE__,__LINE__, melo_assert_stringstream.str()); \ } \ break; \ default: \ { \ ROS_INFO_STREAM_THROTTLE(rate, message); \ } \ break; \ } \ } } // namespace log } // namespace message_logger
40.456592
239
0.57924
ANYbotics
e4c2c8ef4dd7da05aa38ce489af1310c13e1027f
77
cpp
C++
Ardulib2d/Arduboy2D.cpp
madya121/Ardulib2d
dc93424975c6a0a584b0d32d115b099bf9d0fbd1
[ "MIT" ]
null
null
null
Ardulib2d/Arduboy2D.cpp
madya121/Ardulib2d
dc93424975c6a0a584b0d32d115b099bf9d0fbd1
[ "MIT" ]
null
null
null
Ardulib2d/Arduboy2D.cpp
madya121/Ardulib2d
dc93424975c6a0a584b0d32d115b099bf9d0fbd1
[ "MIT" ]
null
null
null
#include "Arduboy2D.h" Arduboy2D::Arduboy2D() { camera = new Camera(); }
11
24
0.649351
madya121
e4c2d6719bb14bdc1338819e4e17506f48316526
1,983
hpp
C++
srcs/common/trackgrouptypebox.hpp
Reflectioner/heif
bdac2fc9c66d8c1e8994eaf81f1a5db116b863ab
[ "BSD-3-Clause" ]
null
null
null
srcs/common/trackgrouptypebox.hpp
Reflectioner/heif
bdac2fc9c66d8c1e8994eaf81f1a5db116b863ab
[ "BSD-3-Clause" ]
null
null
null
srcs/common/trackgrouptypebox.hpp
Reflectioner/heif
bdac2fc9c66d8c1e8994eaf81f1a5db116b863ab
[ "BSD-3-Clause" ]
null
null
null
/* This file is part of Nokia HEIF library * * Copyright (c) 2015-2020 Nokia Corporation and/or its subsidiary(-ies). All rights reserved. * * Contact: heif@nokia.com * * This software, including documentation, is protected by copyright controlled by Nokia Corporation and/ or its * subsidiaries. All rights are reserved. * * Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior * written consent of Nokia. */ #ifndef TRACKGROUPTYPEBOX_HPP #define TRACKGROUPTYPEBOX_HPP #include <cstdint> #include "bitstream.hpp" #include "customallocator.hpp" #include "fullbox.hpp" /** @brief Track Group Type Box class. Extends from FullBox. * @details inside 'trgr' box as specified in the ISOBMFF specification */ class TrackGroupTypeBox : public FullBox { public: TrackGroupTypeBox(FourCCInt boxType, std::uint32_t trackGroupId = 0); ~TrackGroupTypeBox() override = default; /** @brief Gets track group id. * @returns std::uint32_t containing track group id. */ std::uint32_t getTrackGroupId() const; /** @brief Sets track group id. Applicable to track group type boxes of type obsp. * The pair of track_group_id and track_group_type identifies a track group * @param [in] bitstr Bitstream that contains the box data */ void setTrackGroupId(std::uint32_t trackGroupId); /** @brief Creates the bitstream that represents the box in the ISOBMFF file * @param [out] bitstr Bitstream that contains the box data. */ void writeBox(ISOBMFF::BitStream& bitstr) const override; /** @brief Parses an Track Group Type Box bitstream and fills in the necessary member variables * @param [in] bitstr Bitstream that contains the box data */ void parseBox(ISOBMFF::BitStream& bitstr) override; virtual TrackGroupTypeBox* clone() const; private: std::uint32_t mTrackGroupId; ///< indicates the grouping type }; #endif /* TRACKGROUPTYPEBOX_HPP */
35.410714
115
0.732728
Reflectioner
e4c2e59d9d0f2f2f0dab3bc91641611aaa7602a6
4,575
cxx
C++
Code/Filter/vtkMimxComputeNormalsFromPolydataFilter.cxx
Piyusha23/IAFEMesh
e91b34c9eaa9c8ecc4ebb5d16f4c13f330d75c9f
[ "BSD-4-Clause-UC" ]
null
null
null
Code/Filter/vtkMimxComputeNormalsFromPolydataFilter.cxx
Piyusha23/IAFEMesh
e91b34c9eaa9c8ecc4ebb5d16f4c13f330d75c9f
[ "BSD-4-Clause-UC" ]
null
null
null
Code/Filter/vtkMimxComputeNormalsFromPolydataFilter.cxx
Piyusha23/IAFEMesh
e91b34c9eaa9c8ecc4ebb5d16f4c13f330d75c9f
[ "BSD-4-Clause-UC" ]
null
null
null
/*========================================================================= Program: MIMX Meshing Toolkit Module: $RCSfile: vtkMimxComputeNormalsFromPolydataFilter.cxx,v $ Language: C++ Date: $Date: 2012/12/07 19:08:59 $ Version: $Revision: 1.1.1.1 $ Musculoskeletal Imaging, Modelling and Experimentation (MIMX) Center for Computer Aided Design The University of Iowa Iowa City, IA 52242 http://www.ccad.uiowa.edu/mimx/ Copyright (c) The University of Iowa. All rights reserved. See MIMXCopyright.txt or http://www.ccad.uiowa.edu/mimx/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "vtkMimxComputeNormalsFromPolydataFilter.h" #include "vtkPolyData.h" #include "vtkTriangle.h" #include "vtkCellArray.h" #include "vtkCellData.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPointSet.h" #include "vtkPoints.h" vtkCxxRevisionMacro(vtkMimxComputeNormalsFromPolydataFilter, "$Revision: 1.1.1.1 $"); vtkStandardNewMacro(vtkMimxComputeNormalsFromPolydataFilter); vtkMimxComputeNormalsFromPolydataFilter::vtkMimxComputeNormalsFromPolydataFilter() { } vtkMimxComputeNormalsFromPolydataFilter::~vtkMimxComputeNormalsFromPolydataFilter() { } //---------------------------------------------------------------------------- int vtkMimxComputeNormalsFromPolydataFilter::RequestData( vtkInformation *vtkNotUsed(request), vtkInformationVector **inputVector, vtkInformationVector *outputVector) { // get the info objects vtkInformation *inInfo = inputVector[0]->GetInformationObject(0); vtkInformation *outInfo = outputVector->GetInformationObject(0); // get the input and ouptut vtkPolyData *input = vtkPolyData::SafeDownCast( inInfo->Get(vtkDataObject::DATA_OBJECT())); vtkPointSet *output = vtkPointSet::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); vtkPoints *Normals = vtkPoints::New( ); double initialValue = -2.0; vtkIdType numberOfPoints = input->GetNumberOfPoints(); vtkCellArray *cellArray = input->GetPolys(); // Gives number of surface faces Normals->SetNumberOfPoints( numberOfPoints ); for ( vtkIdType i = 0; i < numberOfPoints; i++ ) { Normals->InsertPoint( i, initialValue, initialValue, initialValue); } vtkIdType* pts=0; vtkIdType t=0; int num_neigh; vtkTriangle* tria = vtkTriangle::New(); for( int j = 0; j < numberOfPoints; j++ ) { num_neigh = 0; cellArray->InitTraversal(); vtkPoints* Store_Coor = vtkPoints::New(); Store_Coor->SetNumberOfPoints(1); while(cellArray->GetNextCell(t,pts)) { if(pts[0] == j) { Store_Coor->InsertPoint(num_neigh,pts[0],pts[1],pts[3]); num_neigh++; } if(pts[1] == j) { Store_Coor->InsertPoint(num_neigh,pts[1],pts[2],pts[0]); num_neigh++; } if(pts[2] == j) { Store_Coor->InsertPoint(num_neigh,pts[2],pts[3],pts[1]); num_neigh++; } if(pts[3] == j) { Store_Coor->InsertPoint(num_neigh,pts[3],pts[0],pts[2]); num_neigh++; } } int num_ent = Store_Coor->GetNumberOfPoints(); double x_comp = 0, y_comp = 0, z_comp = 0; double x1[3],x2[3],x3[3],normal[3]; double x[3]; if(num_neigh !=0) { for(int i=0;i<num_ent;i++) { Store_Coor->GetPoint(i,x); input->GetPoint(static_cast<int>(x[0]),x1); input->GetPoint(static_cast<int>(x[1]),x2); input->GetPoint(static_cast<int>(x[2]),x3); tria->ComputeNormal(x1,x2,x3,normal); x_comp = x_comp + normal[0]; y_comp = y_comp + normal[1]; z_comp = z_comp + normal[2]; } if(num_ent !=0) { x_comp = x_comp / num_ent; y_comp = y_comp / num_ent; z_comp = z_comp / num_ent; double norm = sqrt(pow(x_comp,2)+ pow(y_comp,2)+pow(z_comp,2)); x_comp = x_comp / norm; y_comp = y_comp / norm; z_comp = z_comp / norm; Normals->SetPoint( j, x_comp, y_comp, z_comp); } } Store_Coor->Delete(); } output->SetPoints( Normals ); Normals->Delete(); return 1; } void vtkMimxComputeNormalsFromPolydataFilter::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); }
29.707792
86
0.637377
Piyusha23
e4c3edb528753931a872af3e2b75920b4466f9a9
1,810
hpp
C++
acl/include/acl_cpp/aliyun/oss/model/GetObjectRequest.hpp
feixiao/C-C-_practice
ed5f953912dcb481265b2ca86707b41d8b449642
[ "Apache-2.0" ]
4
2016-10-30T13:10:26.000Z
2021-12-31T13:32:14.000Z
acl/include/acl_cpp/aliyun/oss/model/GetObjectRequest.hpp
feixiao/C-C-_practice
ed5f953912dcb481265b2ca86707b41d8b449642
[ "Apache-2.0" ]
null
null
null
acl/include/acl_cpp/aliyun/oss/model/GetObjectRequest.hpp
feixiao/C-C-_practice
ed5f953912dcb481265b2ca86707b41d8b449642
[ "Apache-2.0" ]
3
2019-05-31T06:13:16.000Z
2021-12-31T13:32:15.000Z
#pragma once #include "acl_cpp/acl_cpp_define.hpp" #include <list> #include "acl_cpp/stdlib/string.hpp" namespace acl { class dbuf_pool; class ResponseHeaderOverrides; class ACL_CPP_API GetObjectRequest { public: GetObjectRequest(const char* bucket, const char* key, dbuf_pool* pool = NULL); ~GetObjectRequest(); GetObjectRequest& setBucketName(const char* name); GetObjectRequest& setKey(const char* key); GetObjectRequest& setRange(long long int start, long long int end); GetObjectRequest& setMatchingETagConstraints( const std::list<string>& etags); GetObjectRequest& setNonmatchingETagConstraints( const std::list<string>& etags); GetObjectRequest& setUnmodifiedSinceConstraint(time_t date); GetObjectRequest& setModifiedSinceConstraint(time_t date); GetObjectRequest& setResponseHeaders( ResponseHeaderOverrides* responseHeaders); void reset(); const char* getBucketName() const { return bucket_; } const char* getKey() const { return key_; } void getRange(long long int& start, long long int& end) const { start = range_[0]; end = range_[1]; } const std::list<char*>& getMatchingETagConstraints() const { return matching_etags_; } const std::list<char*>& getNonmatchingETagConstraints() const { return non_matching_etags_; } time_t getUnmodifiedSinceConstraint() const { return unmodified_since_; } time_t getModifiedSinceConstraint() const { return modified_since_; } ResponseHeaderOverrides* getResponseHeaders() const { return response_headers_; } private: dbuf_pool* pool_; char* bucket_; char* key_; long long int range_[2]; std::list<char*> matching_etags_; std::list<char*> non_matching_etags_; time_t unmodified_since_; time_t modified_since_; ResponseHeaderOverrides* response_headers_; }; } // namespace acl
20.804598
68
0.762431
feixiao
e4c4b8226a759244643383bef43e7f5f911968fa
616
hpp
C++
SDL2Cpp/SDL2Cpp/include/SDL2Cpp/Thread.hpp
jasonwnorris/SDL2Cpp
ece3bc247adab1b127303340d8463cb19d585d81
[ "MIT" ]
3
2015-02-04T20:35:10.000Z
2015-10-26T16:45:27.000Z
SDL2Cpp/SDL2Cpp/include/SDL2Cpp/Thread.hpp
jasonwnorris/SDL2Cpp
ece3bc247adab1b127303340d8463cb19d585d81
[ "MIT" ]
null
null
null
SDL2Cpp/SDL2Cpp/include/SDL2Cpp/Thread.hpp
jasonwnorris/SDL2Cpp
ece3bc247adab1b127303340d8463cb19d585d81
[ "MIT" ]
null
null
null
// Thread.hpp #ifndef __SDL2_THREAD_H__ #define __SDL2_THREAD_H__ // SDL Includes #include <SDL.h> namespace SDL2 { class Thread { public: Thread(); virtual ~Thread(); void Start(Uint32 pDelay = 0); void Stop(); void Wait(); void StopAndWait(); void SetPriority(SDL_ThreadPriority pPriority); int GetID() const; const char* GetName() const; bool IsRunning() const; bool IsStopped() const; protected: virtual void Run() = 0; private: static int Execute(void* pData); volatile bool mRunning; volatile bool mStopped; SDL_Thread* mThread; }; } #endif
15.02439
50
0.663961
jasonwnorris
e4c63b09538c9a7c7a7ca06a2f0c0177bfc2803f
50,917
cpp
C++
third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinatorTest.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinatorTest.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinatorTest.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2012 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "core/page/scrolling/ScrollingCoordinator.h" #include "build/build_config.h" #include "core/css/CSSStyleSheet.h" #include "core/css/StyleSheetList.h" #include "core/exported/WebViewBase.h" #include "core/frame/FrameTestHelpers.h" #include "core/frame/LocalFrameView.h" #include "core/frame/VisualViewport.h" #include "core/frame/WebLocalFrameBase.h" #include "core/html/HTMLIFrameElement.h" #include "core/layout/LayoutEmbeddedContent.h" #include "core/layout/api/LayoutViewItem.h" #include "core/layout/compositing/CompositedLayerMapping.h" #include "core/layout/compositing/PaintLayerCompositor.h" #include "core/page/Page.h" #include "platform/geometry/IntPoint.h" #include "platform/geometry/IntRect.h" #include "platform/graphics/GraphicsLayer.h" #include "platform/testing/RuntimeEnabledFeaturesTestHelpers.h" #include "platform/testing/URLTestHelpers.h" #include "platform/testing/UnitTestHelpers.h" #include "public/platform/Platform.h" #include "public/platform/WebCache.h" #include "public/platform/WebLayer.h" #include "public/platform/WebLayerPositionConstraint.h" #include "public/platform/WebLayerTreeView.h" #include "public/platform/WebURLLoaderMockFactory.h" #include "public/web/WebSettings.h" #include "public/web/WebViewClient.h" #include "testing/gtest/include/gtest/gtest.h" namespace blink { class ScrollingCoordinatorTest : public ::testing::Test, public ::testing::WithParamInterface<bool>, private ScopedRootLayerScrollingForTest { public: ScrollingCoordinatorTest() : ScopedRootLayerScrollingForTest(GetParam()), base_url_("http://www.test.com/") { helper_.Initialize(nullptr, nullptr, nullptr, &ConfigureSettings); GetWebView()->Resize(IntSize(320, 240)); // macOS attaches main frame scrollbars to the VisualViewport so the // VisualViewport layers need to be initialized. GetWebView()->UpdateAllLifecyclePhases(); WebFrameWidgetBase* main_frame_widget = GetWebView()->MainFrameImpl()->FrameWidget(); main_frame_widget->SetRootGraphicsLayer(GetWebView() ->MainFrameImpl() ->GetFrame() ->View() ->GetLayoutViewItem() .Compositor() ->RootGraphicsLayer()); } ~ScrollingCoordinatorTest() override { Platform::Current() ->GetURLLoaderMockFactory() ->UnregisterAllURLsAndClearMemoryCache(); } void NavigateTo(const std::string& url) { FrameTestHelpers::LoadFrame(GetWebView()->MainFrameImpl(), url); } void LoadHTML(const std::string& html) { FrameTestHelpers::LoadHTMLString(GetWebView()->MainFrameImpl(), html, URLTestHelpers::ToKURL("about:blank")); } void ForceFullCompositingUpdate() { GetWebView()->UpdateAllLifecyclePhases(); } void RegisterMockedHttpURLLoad(const std::string& file_name) { URLTestHelpers::RegisterMockedURLLoadFromBase( WebString::FromUTF8(base_url_), testing::CoreTestDataPath(), WebString::FromUTF8(file_name)); } WebLayer* GetRootScrollLayer() { GraphicsLayer* layer = GetFrame()->View()->LayoutViewportScrollableArea()->LayerForScrolling(); return layer ? layer->PlatformLayer() : nullptr; } WebViewBase* GetWebView() const { return helper_.WebView(); } LocalFrame* GetFrame() const { return helper_.LocalMainFrame()->GetFrame(); } WebLayerTreeView* GetWebLayerTreeView() const { return GetWebView()->LayerTreeView(); } protected: std::string base_url_; private: static void ConfigureSettings(WebSettings* settings) { settings->SetAcceleratedCompositingEnabled(true); settings->SetPreferCompositingToLCDTextEnabled(true); } FrameTestHelpers::WebViewHelper helper_; }; INSTANTIATE_TEST_CASE_P(All, ScrollingCoordinatorTest, ::testing::Bool()); TEST_P(ScrollingCoordinatorTest, fastScrollingByDefault) { GetWebView()->Resize(WebSize(800, 600)); LoadHTML("<div id='spacer' style='height: 1000px'></div>"); ForceFullCompositingUpdate(); // Make sure the scrolling coordinator is active. LocalFrameView* frame_view = GetFrame()->View(); Page* page = GetFrame()->GetPage(); ASSERT_TRUE(page->GetScrollingCoordinator()); ASSERT_TRUE(page->GetScrollingCoordinator()->CoordinatesScrollingForFrameView( frame_view)); // Fast scrolling should be enabled by default. WebLayer* root_scroll_layer = GetRootScrollLayer(); ASSERT_TRUE(root_scroll_layer); ASSERT_TRUE(root_scroll_layer->Scrollable()); ASSERT_FALSE(root_scroll_layer->ShouldScrollOnMainThread()); ASSERT_EQ(WebEventListenerProperties::kNothing, GetWebLayerTreeView()->EventListenerProperties( WebEventListenerClass::kTouchStartOrMove)); ASSERT_EQ(WebEventListenerProperties::kNothing, GetWebLayerTreeView()->EventListenerProperties( WebEventListenerClass::kMouseWheel)); WebLayer* inner_viewport_scroll_layer = page->GetVisualViewport().ScrollLayer()->PlatformLayer(); ASSERT_TRUE(inner_viewport_scroll_layer->Scrollable()); ASSERT_FALSE(inner_viewport_scroll_layer->ShouldScrollOnMainThread()); } TEST_P(ScrollingCoordinatorTest, fastScrollingCanBeDisabledWithSetting) { GetWebView()->Resize(WebSize(800, 600)); LoadHTML("<div id='spacer' style='height: 1000px'></div>"); GetWebView()->GetSettings()->SetThreadedScrollingEnabled(false); ForceFullCompositingUpdate(); // Make sure the scrolling coordinator is active. LocalFrameView* frame_view = GetFrame()->View(); Page* page = GetFrame()->GetPage(); ASSERT_TRUE(page->GetScrollingCoordinator()); ASSERT_TRUE(page->GetScrollingCoordinator()->CoordinatesScrollingForFrameView( frame_view)); // Main scrolling should be enabled with the setting override. WebLayer* root_scroll_layer = GetRootScrollLayer(); ASSERT_TRUE(root_scroll_layer); ASSERT_TRUE(root_scroll_layer->Scrollable()); ASSERT_TRUE(root_scroll_layer->ShouldScrollOnMainThread()); // Main scrolling should also propagate to inner viewport layer. WebLayer* inner_viewport_scroll_layer = page->GetVisualViewport().ScrollLayer()->PlatformLayer(); ASSERT_TRUE(inner_viewport_scroll_layer->Scrollable()); ASSERT_TRUE(inner_viewport_scroll_layer->ShouldScrollOnMainThread()); } TEST_P(ScrollingCoordinatorTest, fastFractionalScrollingDiv) { bool orig_fractional_offsets_enabled = RuntimeEnabledFeatures::FractionalScrollOffsetsEnabled(); RuntimeEnabledFeatures::SetFractionalScrollOffsetsEnabled(true); RegisterMockedHttpURLLoad("fractional-scroll-div.html"); NavigateTo(base_url_ + "fractional-scroll-div.html"); ForceFullCompositingUpdate(); Document* document = GetFrame()->GetDocument(); Element* scrollable_element = document->getElementById("scroller"); DCHECK(scrollable_element); scrollable_element->setScrollTop(1.0); scrollable_element->setScrollLeft(1.0); ForceFullCompositingUpdate(); // Make sure the fractional scroll offset change 1.0 -> 1.2 gets propagated // to compositor. scrollable_element->setScrollTop(1.2); scrollable_element->setScrollLeft(1.2); ForceFullCompositingUpdate(); LayoutObject* layout_object = scrollable_element->GetLayoutObject(); ASSERT_TRUE(layout_object->IsBox()); LayoutBox* box = ToLayoutBox(layout_object); ASSERT_TRUE(box->UsesCompositedScrolling()); CompositedLayerMapping* composited_layer_mapping = box->Layer()->GetCompositedLayerMapping(); ASSERT_TRUE(composited_layer_mapping->HasScrollingLayer()); DCHECK(composited_layer_mapping->ScrollingContentsLayer()); WebLayer* web_scroll_layer = composited_layer_mapping->ScrollingContentsLayer()->PlatformLayer(); ASSERT_TRUE(web_scroll_layer); ASSERT_NEAR(1.2f, web_scroll_layer->ScrollPosition().x, 0.01f); ASSERT_NEAR(1.2f, web_scroll_layer->ScrollPosition().y, 0.01f); RuntimeEnabledFeatures::SetFractionalScrollOffsetsEnabled( orig_fractional_offsets_enabled); } static WebLayer* WebLayerFromElement(Element* element) { if (!element) return 0; LayoutObject* layout_object = element->GetLayoutObject(); if (!layout_object || !layout_object->IsBoxModelObject()) return 0; PaintLayer* layer = ToLayoutBoxModelObject(layout_object)->Layer(); if (!layer) return 0; if (!layer->HasCompositedLayerMapping()) return 0; CompositedLayerMapping* composited_layer_mapping = layer->GetCompositedLayerMapping(); GraphicsLayer* graphics_layer = composited_layer_mapping->MainGraphicsLayer(); if (!graphics_layer) return 0; return graphics_layer->PlatformLayer(); } TEST_P(ScrollingCoordinatorTest, fastScrollingForFixedPosition) { RegisterMockedHttpURLLoad("fixed-position.html"); NavigateTo(base_url_ + "fixed-position.html"); ForceFullCompositingUpdate(); // Fixed position should not fall back to main thread scrolling. WebLayer* root_scroll_layer = GetRootScrollLayer(); ASSERT_TRUE(root_scroll_layer); ASSERT_FALSE(root_scroll_layer->ShouldScrollOnMainThread()); Document* document = GetFrame()->GetDocument(); { Element* element = document->getElementById("div-tl"); ASSERT_TRUE(element); WebLayer* layer = WebLayerFromElement(element); ASSERT_TRUE(layer); WebLayerPositionConstraint constraint = layer->PositionConstraint(); ASSERT_TRUE(constraint.is_fixed_position); ASSERT_TRUE(!constraint.is_fixed_to_right_edge && !constraint.is_fixed_to_bottom_edge); } { Element* element = document->getElementById("div-tr"); ASSERT_TRUE(element); WebLayer* layer = WebLayerFromElement(element); ASSERT_TRUE(layer); WebLayerPositionConstraint constraint = layer->PositionConstraint(); ASSERT_TRUE(constraint.is_fixed_position); ASSERT_TRUE(constraint.is_fixed_to_right_edge && !constraint.is_fixed_to_bottom_edge); } { Element* element = document->getElementById("div-bl"); ASSERT_TRUE(element); WebLayer* layer = WebLayerFromElement(element); ASSERT_TRUE(layer); WebLayerPositionConstraint constraint = layer->PositionConstraint(); ASSERT_TRUE(constraint.is_fixed_position); ASSERT_TRUE(!constraint.is_fixed_to_right_edge && constraint.is_fixed_to_bottom_edge); } { Element* element = document->getElementById("div-br"); ASSERT_TRUE(element); WebLayer* layer = WebLayerFromElement(element); ASSERT_TRUE(layer); WebLayerPositionConstraint constraint = layer->PositionConstraint(); ASSERT_TRUE(constraint.is_fixed_position); ASSERT_TRUE(constraint.is_fixed_to_right_edge && constraint.is_fixed_to_bottom_edge); } { Element* element = document->getElementById("span-tl"); ASSERT_TRUE(element); WebLayer* layer = WebLayerFromElement(element); ASSERT_TRUE(layer); WebLayerPositionConstraint constraint = layer->PositionConstraint(); ASSERT_TRUE(constraint.is_fixed_position); ASSERT_TRUE(!constraint.is_fixed_to_right_edge && !constraint.is_fixed_to_bottom_edge); } { Element* element = document->getElementById("span-tr"); ASSERT_TRUE(element); WebLayer* layer = WebLayerFromElement(element); ASSERT_TRUE(layer); WebLayerPositionConstraint constraint = layer->PositionConstraint(); ASSERT_TRUE(constraint.is_fixed_position); ASSERT_TRUE(constraint.is_fixed_to_right_edge && !constraint.is_fixed_to_bottom_edge); } { Element* element = document->getElementById("span-bl"); ASSERT_TRUE(element); WebLayer* layer = WebLayerFromElement(element); ASSERT_TRUE(layer); WebLayerPositionConstraint constraint = layer->PositionConstraint(); ASSERT_TRUE(constraint.is_fixed_position); ASSERT_TRUE(!constraint.is_fixed_to_right_edge && constraint.is_fixed_to_bottom_edge); } { Element* element = document->getElementById("span-br"); ASSERT_TRUE(element); WebLayer* layer = WebLayerFromElement(element); ASSERT_TRUE(layer); WebLayerPositionConstraint constraint = layer->PositionConstraint(); ASSERT_TRUE(constraint.is_fixed_position); ASSERT_TRUE(constraint.is_fixed_to_right_edge && constraint.is_fixed_to_bottom_edge); } } TEST_P(ScrollingCoordinatorTest, fastScrollingForStickyPosition) { RegisterMockedHttpURLLoad("sticky-position.html"); NavigateTo(base_url_ + "sticky-position.html"); ForceFullCompositingUpdate(); // Sticky position should not fall back to main thread scrolling. WebLayer* root_scroll_layer = GetRootScrollLayer(); ASSERT_TRUE(root_scroll_layer); EXPECT_FALSE(root_scroll_layer->ShouldScrollOnMainThread()); Document* document = GetFrame()->GetDocument(); { Element* element = document->getElementById("div-tl"); ASSERT_TRUE(element); WebLayer* layer = WebLayerFromElement(element); ASSERT_TRUE(layer); WebLayerStickyPositionConstraint constraint = layer->StickyPositionConstraint(); ASSERT_TRUE(constraint.is_sticky); EXPECT_TRUE(constraint.is_anchored_top && constraint.is_anchored_left && !constraint.is_anchored_right && !constraint.is_anchored_bottom); EXPECT_EQ(1.f, constraint.top_offset); EXPECT_EQ(1.f, constraint.left_offset); EXPECT_EQ(IntRect(100, 100, 10, 10), IntRect(constraint.scroll_container_relative_sticky_box_rect)); EXPECT_EQ( IntRect(100, 100, 200, 200), IntRect(constraint.scroll_container_relative_containing_block_rect)); } { Element* element = document->getElementById("div-tr"); ASSERT_TRUE(element); WebLayer* layer = WebLayerFromElement(element); ASSERT_TRUE(layer); WebLayerStickyPositionConstraint constraint = layer->StickyPositionConstraint(); ASSERT_TRUE(constraint.is_sticky); EXPECT_TRUE(constraint.is_anchored_top && !constraint.is_anchored_left && constraint.is_anchored_right && !constraint.is_anchored_bottom); } { Element* element = document->getElementById("div-bl"); ASSERT_TRUE(element); WebLayer* layer = WebLayerFromElement(element); ASSERT_TRUE(layer); WebLayerStickyPositionConstraint constraint = layer->StickyPositionConstraint(); ASSERT_TRUE(constraint.is_sticky); EXPECT_TRUE(!constraint.is_anchored_top && constraint.is_anchored_left && !constraint.is_anchored_right && constraint.is_anchored_bottom); } { Element* element = document->getElementById("div-br"); ASSERT_TRUE(element); WebLayer* layer = WebLayerFromElement(element); ASSERT_TRUE(layer); WebLayerStickyPositionConstraint constraint = layer->StickyPositionConstraint(); ASSERT_TRUE(constraint.is_sticky); EXPECT_TRUE(!constraint.is_anchored_top && !constraint.is_anchored_left && constraint.is_anchored_right && constraint.is_anchored_bottom); } { Element* element = document->getElementById("span-tl"); ASSERT_TRUE(element); WebLayer* layer = WebLayerFromElement(element); ASSERT_TRUE(layer); WebLayerStickyPositionConstraint constraint = layer->StickyPositionConstraint(); ASSERT_TRUE(constraint.is_sticky); EXPECT_TRUE(constraint.is_anchored_top && constraint.is_anchored_left && !constraint.is_anchored_right && !constraint.is_anchored_bottom); } { Element* element = document->getElementById("span-tlbr"); ASSERT_TRUE(element); WebLayer* layer = WebLayerFromElement(element); ASSERT_TRUE(layer); WebLayerStickyPositionConstraint constraint = layer->StickyPositionConstraint(); ASSERT_TRUE(constraint.is_sticky); EXPECT_TRUE(constraint.is_anchored_top && constraint.is_anchored_left && constraint.is_anchored_right && constraint.is_anchored_bottom); EXPECT_EQ(1.f, constraint.top_offset); EXPECT_EQ(1.f, constraint.left_offset); EXPECT_EQ(1.f, constraint.right_offset); EXPECT_EQ(1.f, constraint.bottom_offset); } { Element* element = document->getElementById("composited-top"); ASSERT_TRUE(element); WebLayer* layer = WebLayerFromElement(element); ASSERT_TRUE(layer); WebLayerStickyPositionConstraint constraint = layer->StickyPositionConstraint(); ASSERT_TRUE(constraint.is_sticky); EXPECT_TRUE(constraint.is_anchored_top); EXPECT_EQ(IntRect(100, 110, 10, 10), IntRect(constraint.scroll_container_relative_sticky_box_rect)); EXPECT_EQ( IntRect(100, 100, 200, 200), IntRect(constraint.scroll_container_relative_containing_block_rect)); } } TEST_P(ScrollingCoordinatorTest, touchEventHandler) { RegisterMockedHttpURLLoad("touch-event-handler.html"); NavigateTo(base_url_ + "touch-event-handler.html"); ForceFullCompositingUpdate(); ASSERT_EQ(WebEventListenerProperties::kBlocking, GetWebLayerTreeView()->EventListenerProperties( WebEventListenerClass::kTouchStartOrMove)); } TEST_P(ScrollingCoordinatorTest, touchEventHandlerPassive) { RegisterMockedHttpURLLoad("touch-event-handler-passive.html"); NavigateTo(base_url_ + "touch-event-handler-passive.html"); ForceFullCompositingUpdate(); ASSERT_EQ(WebEventListenerProperties::kPassive, GetWebLayerTreeView()->EventListenerProperties( WebEventListenerClass::kTouchStartOrMove)); } TEST_P(ScrollingCoordinatorTest, touchEventHandlerBoth) { RegisterMockedHttpURLLoad("touch-event-handler-both.html"); NavigateTo(base_url_ + "touch-event-handler-both.html"); ForceFullCompositingUpdate(); ASSERT_EQ(WebEventListenerProperties::kBlockingAndPassive, GetWebLayerTreeView()->EventListenerProperties( WebEventListenerClass::kTouchStartOrMove)); } TEST_P(ScrollingCoordinatorTest, wheelEventHandler) { RegisterMockedHttpURLLoad("wheel-event-handler.html"); NavigateTo(base_url_ + "wheel-event-handler.html"); ForceFullCompositingUpdate(); ASSERT_EQ(WebEventListenerProperties::kBlocking, GetWebLayerTreeView()->EventListenerProperties( WebEventListenerClass::kMouseWheel)); } TEST_P(ScrollingCoordinatorTest, wheelEventHandlerPassive) { RegisterMockedHttpURLLoad("wheel-event-handler-passive.html"); NavigateTo(base_url_ + "wheel-event-handler-passive.html"); ForceFullCompositingUpdate(); ASSERT_EQ(WebEventListenerProperties::kPassive, GetWebLayerTreeView()->EventListenerProperties( WebEventListenerClass::kMouseWheel)); } TEST_P(ScrollingCoordinatorTest, wheelEventHandlerBoth) { RegisterMockedHttpURLLoad("wheel-event-handler-both.html"); NavigateTo(base_url_ + "wheel-event-handler-both.html"); ForceFullCompositingUpdate(); ASSERT_EQ(WebEventListenerProperties::kBlockingAndPassive, GetWebLayerTreeView()->EventListenerProperties( WebEventListenerClass::kMouseWheel)); } TEST_P(ScrollingCoordinatorTest, scrollEventHandler) { RegisterMockedHttpURLLoad("scroll-event-handler.html"); NavigateTo(base_url_ + "scroll-event-handler.html"); ForceFullCompositingUpdate(); ASSERT_TRUE(GetWebLayerTreeView()->HaveScrollEventHandlers()); } TEST_P(ScrollingCoordinatorTest, updateEventHandlersDuringTeardown) { RegisterMockedHttpURLLoad("scroll-event-handler-window.html"); NavigateTo(base_url_ + "scroll-event-handler-window.html"); ForceFullCompositingUpdate(); // Simulate detaching the document from its DOM window. This should not // cause a crash when the WebViewImpl is closed by the test runner. GetFrame()->GetDocument()->Shutdown(); } TEST_P(ScrollingCoordinatorTest, clippedBodyTest) { RegisterMockedHttpURLLoad("clipped-body.html"); NavigateTo(base_url_ + "clipped-body.html"); ForceFullCompositingUpdate(); WebLayer* root_scroll_layer = GetRootScrollLayer(); ASSERT_TRUE(root_scroll_layer); ASSERT_EQ(0u, root_scroll_layer->NonFastScrollableRegion().size()); } TEST_P(ScrollingCoordinatorTest, overflowScrolling) { RegisterMockedHttpURLLoad("overflow-scrolling.html"); NavigateTo(base_url_ + "overflow-scrolling.html"); ForceFullCompositingUpdate(); // Verify the properties of the accelerated scrolling element starting from // the LayoutObject all the way to the WebLayer. Element* scrollable_element = GetFrame()->GetDocument()->getElementById("scrollable"); DCHECK(scrollable_element); LayoutObject* layout_object = scrollable_element->GetLayoutObject(); ASSERT_TRUE(layout_object->IsBox()); ASSERT_TRUE(layout_object->HasLayer()); LayoutBox* box = ToLayoutBox(layout_object); ASSERT_TRUE(box->UsesCompositedScrolling()); ASSERT_EQ(kPaintsIntoOwnBacking, box->Layer()->GetCompositingState()); CompositedLayerMapping* composited_layer_mapping = box->Layer()->GetCompositedLayerMapping(); ASSERT_TRUE(composited_layer_mapping->HasScrollingLayer()); DCHECK(composited_layer_mapping->ScrollingContentsLayer()); GraphicsLayer* graphics_layer = composited_layer_mapping->ScrollingContentsLayer(); ASSERT_EQ(box->Layer()->GetScrollableArea(), graphics_layer->GetScrollableArea()); WebLayer* web_scroll_layer = composited_layer_mapping->ScrollingContentsLayer()->PlatformLayer(); ASSERT_TRUE(web_scroll_layer->Scrollable()); ASSERT_TRUE(web_scroll_layer->UserScrollableHorizontal()); ASSERT_TRUE(web_scroll_layer->UserScrollableVertical()); #if defined(OS_ANDROID) // Now verify we've attached impl-side scrollbars onto the scrollbar layers ASSERT_TRUE(composited_layer_mapping->LayerForHorizontalScrollbar()); ASSERT_TRUE(composited_layer_mapping->LayerForHorizontalScrollbar() ->HasContentsLayer()); ASSERT_TRUE(composited_layer_mapping->LayerForVerticalScrollbar()); ASSERT_TRUE(composited_layer_mapping->LayerForVerticalScrollbar() ->HasContentsLayer()); #endif } TEST_P(ScrollingCoordinatorTest, overflowHidden) { RegisterMockedHttpURLLoad("overflow-hidden.html"); NavigateTo(base_url_ + "overflow-hidden.html"); ForceFullCompositingUpdate(); // Verify the properties of the accelerated scrolling element starting from // the LayoutObject all the way to the WebLayer. Element* overflow_element = GetFrame()->GetDocument()->getElementById("unscrollable-y"); DCHECK(overflow_element); LayoutObject* layout_object = overflow_element->GetLayoutObject(); ASSERT_TRUE(layout_object->IsBox()); ASSERT_TRUE(layout_object->HasLayer()); LayoutBox* box = ToLayoutBox(layout_object); ASSERT_TRUE(box->UsesCompositedScrolling()); ASSERT_EQ(kPaintsIntoOwnBacking, box->Layer()->GetCompositingState()); CompositedLayerMapping* composited_layer_mapping = box->Layer()->GetCompositedLayerMapping(); ASSERT_TRUE(composited_layer_mapping->HasScrollingLayer()); DCHECK(composited_layer_mapping->ScrollingContentsLayer()); GraphicsLayer* graphics_layer = composited_layer_mapping->ScrollingContentsLayer(); ASSERT_EQ(box->Layer()->GetScrollableArea(), graphics_layer->GetScrollableArea()); WebLayer* web_scroll_layer = composited_layer_mapping->ScrollingContentsLayer()->PlatformLayer(); ASSERT_TRUE(web_scroll_layer->Scrollable()); ASSERT_TRUE(web_scroll_layer->UserScrollableHorizontal()); ASSERT_FALSE(web_scroll_layer->UserScrollableVertical()); overflow_element = GetFrame()->GetDocument()->getElementById("unscrollable-x"); DCHECK(overflow_element); layout_object = overflow_element->GetLayoutObject(); ASSERT_TRUE(layout_object->IsBox()); ASSERT_TRUE(layout_object->HasLayer()); box = ToLayoutBox(layout_object); ASSERT_TRUE(box->GetScrollableArea()->UsesCompositedScrolling()); ASSERT_EQ(kPaintsIntoOwnBacking, box->Layer()->GetCompositingState()); composited_layer_mapping = box->Layer()->GetCompositedLayerMapping(); ASSERT_TRUE(composited_layer_mapping->HasScrollingLayer()); DCHECK(composited_layer_mapping->ScrollingContentsLayer()); graphics_layer = composited_layer_mapping->ScrollingContentsLayer(); ASSERT_EQ(box->Layer()->GetScrollableArea(), graphics_layer->GetScrollableArea()); web_scroll_layer = composited_layer_mapping->ScrollingContentsLayer()->PlatformLayer(); ASSERT_TRUE(web_scroll_layer->Scrollable()); ASSERT_FALSE(web_scroll_layer->UserScrollableHorizontal()); ASSERT_TRUE(web_scroll_layer->UserScrollableVertical()); } TEST_P(ScrollingCoordinatorTest, iframeScrolling) { RegisterMockedHttpURLLoad("iframe-scrolling.html"); RegisterMockedHttpURLLoad("iframe-scrolling-inner.html"); NavigateTo(base_url_ + "iframe-scrolling.html"); ForceFullCompositingUpdate(); // Verify the properties of the accelerated scrolling element starting from // the LayoutObject all the way to the WebLayer. Element* scrollable_frame = GetFrame()->GetDocument()->getElementById("scrollable"); ASSERT_TRUE(scrollable_frame); LayoutObject* layout_object = scrollable_frame->GetLayoutObject(); ASSERT_TRUE(layout_object); ASSERT_TRUE(layout_object->IsLayoutEmbeddedContent()); LayoutEmbeddedContent* layout_embedded_content = ToLayoutEmbeddedContent(layout_object); ASSERT_TRUE(layout_embedded_content); LocalFrameView* inner_frame_view = layout_embedded_content->ChildFrameView(); ASSERT_TRUE(inner_frame_view); LayoutViewItem inner_layout_view_item = inner_frame_view->GetLayoutViewItem(); ASSERT_FALSE(inner_layout_view_item.IsNull()); PaintLayerCompositor* inner_compositor = inner_layout_view_item.Compositor(); ASSERT_TRUE(inner_compositor->InCompositingMode()); GraphicsLayer* scroll_layer = inner_frame_view->LayoutViewportScrollableArea()->LayerForScrolling(); ASSERT_TRUE(scroll_layer); ASSERT_EQ(inner_frame_view->LayoutViewportScrollableArea(), scroll_layer->GetScrollableArea()); WebLayer* web_scroll_layer = scroll_layer->PlatformLayer(); ASSERT_TRUE(web_scroll_layer->Scrollable()); #if defined(OS_ANDROID) // Now verify we've attached impl-side scrollbars onto the scrollbar layers GraphicsLayer* horizontal_scrollbar_layer = inner_frame_view->LayoutViewportScrollableArea() ->LayerForHorizontalScrollbar(); ASSERT_TRUE(horizontal_scrollbar_layer); ASSERT_TRUE(horizontal_scrollbar_layer->HasContentsLayer()); GraphicsLayer* vertical_scrollbar_layer = inner_frame_view->LayoutViewportScrollableArea() ->LayerForVerticalScrollbar(); ASSERT_TRUE(vertical_scrollbar_layer); ASSERT_TRUE(vertical_scrollbar_layer->HasContentsLayer()); #endif } TEST_P(ScrollingCoordinatorTest, rtlIframe) { RegisterMockedHttpURLLoad("rtl-iframe.html"); RegisterMockedHttpURLLoad("rtl-iframe-inner.html"); NavigateTo(base_url_ + "rtl-iframe.html"); ForceFullCompositingUpdate(); // Verify the properties of the accelerated scrolling element starting from // the LayoutObject all the way to the WebLayer. Element* scrollable_frame = GetFrame()->GetDocument()->getElementById("scrollable"); ASSERT_TRUE(scrollable_frame); LayoutObject* layout_object = scrollable_frame->GetLayoutObject(); ASSERT_TRUE(layout_object); ASSERT_TRUE(layout_object->IsLayoutEmbeddedContent()); LayoutEmbeddedContent* layout_embedded_content = ToLayoutEmbeddedContent(layout_object); ASSERT_TRUE(layout_embedded_content); LocalFrameView* inner_frame_view = layout_embedded_content->ChildFrameView(); ASSERT_TRUE(inner_frame_view); LayoutViewItem inner_layout_view_item = inner_frame_view->GetLayoutViewItem(); ASSERT_FALSE(inner_layout_view_item.IsNull()); PaintLayerCompositor* inner_compositor = inner_layout_view_item.Compositor(); ASSERT_TRUE(inner_compositor->InCompositingMode()); GraphicsLayer* scroll_layer = inner_frame_view->LayoutViewportScrollableArea()->LayerForScrolling(); ASSERT_TRUE(scroll_layer); ASSERT_EQ(inner_frame_view->LayoutViewportScrollableArea(), scroll_layer->GetScrollableArea()); WebLayer* web_scroll_layer = scroll_layer->PlatformLayer(); ASSERT_TRUE(web_scroll_layer->Scrollable()); int expected_scroll_position = 958 + (inner_frame_view->LayoutViewportScrollableArea() ->VerticalScrollbar() ->IsOverlayScrollbar() ? 0 : 15); ASSERT_EQ(expected_scroll_position, web_scroll_layer->ScrollPosition().x); } TEST_P(ScrollingCoordinatorTest, setupScrollbarLayerShouldNotCrash) { RegisterMockedHttpURLLoad("setup_scrollbar_layer_crash.html"); NavigateTo(base_url_ + "setup_scrollbar_layer_crash.html"); ForceFullCompositingUpdate(); // This test document setup an iframe with scrollbars, then switch to // an empty document by javascript. } TEST_P(ScrollingCoordinatorTest, scrollbarsForceMainThreadOrHaveWebScrollbarLayer) { RegisterMockedHttpURLLoad("trivial-scroller.html"); NavigateTo(base_url_ + "trivial-scroller.html"); ForceFullCompositingUpdate(); Document* document = GetFrame()->GetDocument(); Element* scrollable_element = document->getElementById("scroller"); DCHECK(scrollable_element); LayoutObject* layout_object = scrollable_element->GetLayoutObject(); ASSERT_TRUE(layout_object->IsBox()); LayoutBox* box = ToLayoutBox(layout_object); ASSERT_TRUE(box->UsesCompositedScrolling()); CompositedLayerMapping* composited_layer_mapping = box->Layer()->GetCompositedLayerMapping(); GraphicsLayer* scrollbar_graphics_layer = composited_layer_mapping->LayerForVerticalScrollbar(); ASSERT_TRUE(scrollbar_graphics_layer); bool has_web_scrollbar_layer = !scrollbar_graphics_layer->DrawsContent(); ASSERT_TRUE( has_web_scrollbar_layer || scrollbar_graphics_layer->PlatformLayer()->ShouldScrollOnMainThread()); } #if defined(OS_MACOSX) || defined(OS_ANDROID) TEST_P(ScrollingCoordinatorTest, DISABLED_setupScrollbarLayerShouldSetScrollLayerOpaque) #else TEST_P(ScrollingCoordinatorTest, setupScrollbarLayerShouldSetScrollLayerOpaque) #endif { RegisterMockedHttpURLLoad("wide_document.html"); NavigateTo(base_url_ + "wide_document.html"); ForceFullCompositingUpdate(); LocalFrameView* frame_view = GetFrame()->View(); ASSERT_TRUE(frame_view); GraphicsLayer* scrollbar_graphics_layer = frame_view->LayoutViewportScrollableArea()->LayerForHorizontalScrollbar(); ASSERT_TRUE(scrollbar_graphics_layer); WebLayer* platform_layer = scrollbar_graphics_layer->PlatformLayer(); ASSERT_TRUE(platform_layer); WebLayer* contents_layer = scrollbar_graphics_layer->ContentsLayer(); ASSERT_TRUE(contents_layer); // After scrollableAreaScrollbarLayerDidChange, // if the main frame's scrollbarLayer is opaque, // contentsLayer should be opaque too. ASSERT_EQ(platform_layer->Opaque(), contents_layer->Opaque()); } TEST_P(ScrollingCoordinatorTest, FixedPositionLosingBackingShouldTriggerMainThreadScroll) { GetWebView()->GetSettings()->SetPreferCompositingToLCDTextEnabled(false); RegisterMockedHttpURLLoad("fixed-position-losing-backing.html"); NavigateTo(base_url_ + "fixed-position-losing-backing.html"); ForceFullCompositingUpdate(); WebLayer* scroll_layer = GetRootScrollLayer(); ASSERT_TRUE(scroll_layer); Document* document = GetFrame()->GetDocument(); Element* fixed_pos = document->getElementById("fixed"); EXPECT_TRUE(static_cast<LayoutBoxModelObject*>(fixed_pos->GetLayoutObject()) ->Layer() ->HasCompositedLayerMapping()); EXPECT_FALSE(scroll_layer->ShouldScrollOnMainThread()); fixed_pos->SetInlineStyleProperty(CSSPropertyTransform, CSSValueNone); ForceFullCompositingUpdate(); EXPECT_FALSE(static_cast<LayoutBoxModelObject*>(fixed_pos->GetLayoutObject()) ->Layer() ->HasCompositedLayerMapping()); EXPECT_TRUE(scroll_layer->ShouldScrollOnMainThread()); } TEST_P(ScrollingCoordinatorTest, CustomScrollbarShouldTriggerMainThreadScroll) { GetWebView()->GetSettings()->SetPreferCompositingToLCDTextEnabled(true); GetWebView()->SetDeviceScaleFactor(2.f); RegisterMockedHttpURLLoad("custom_scrollbar.html"); NavigateTo(base_url_ + "custom_scrollbar.html"); ForceFullCompositingUpdate(); Document* document = GetFrame()->GetDocument(); Element* container = document->getElementById("container"); Element* content = document->getElementById("content"); DCHECK_EQ(container->getAttribute(HTMLNames::classAttr), "custom_scrollbar"); DCHECK(container); DCHECK(content); LayoutObject* layout_object = container->GetLayoutObject(); ASSERT_TRUE(layout_object->IsBox()); LayoutBox* box = ToLayoutBox(layout_object); ASSERT_TRUE(box->UsesCompositedScrolling()); CompositedLayerMapping* composited_layer_mapping = box->Layer()->GetCompositedLayerMapping(); GraphicsLayer* scrollbar_graphics_layer = composited_layer_mapping->LayerForVerticalScrollbar(); ASSERT_TRUE(scrollbar_graphics_layer); ASSERT_TRUE( scrollbar_graphics_layer->PlatformLayer()->ShouldScrollOnMainThread()); ASSERT_TRUE( scrollbar_graphics_layer->PlatformLayer()->MainThreadScrollingReasons() & MainThreadScrollingReason::kCustomScrollbarScrolling); // remove custom scrollbar class, the scrollbar is expected to scroll on // impl thread as it is an overlay scrollbar. container->removeAttribute("class"); ForceFullCompositingUpdate(); scrollbar_graphics_layer = composited_layer_mapping->LayerForVerticalScrollbar(); ASSERT_FALSE( scrollbar_graphics_layer->PlatformLayer()->ShouldScrollOnMainThread()); ASSERT_FALSE( scrollbar_graphics_layer->PlatformLayer()->MainThreadScrollingReasons() & MainThreadScrollingReason::kCustomScrollbarScrolling); } TEST_P(ScrollingCoordinatorTest, BackgroundAttachmentFixedShouldTriggerMainThreadScroll) { RegisterMockedHttpURLLoad("iframe-background-attachment-fixed.html"); RegisterMockedHttpURLLoad("iframe-background-attachment-fixed-inner.html"); RegisterMockedHttpURLLoad("white-1x1.png"); NavigateTo(base_url_ + "iframe-background-attachment-fixed.html"); ForceFullCompositingUpdate(); Element* iframe = GetFrame()->GetDocument()->getElementById("iframe"); ASSERT_TRUE(iframe); LayoutObject* layout_object = iframe->GetLayoutObject(); ASSERT_TRUE(layout_object); ASSERT_TRUE(layout_object->IsLayoutEmbeddedContent()); LayoutEmbeddedContent* layout_embedded_content = ToLayoutEmbeddedContent(layout_object); ASSERT_TRUE(layout_embedded_content); LocalFrameView* inner_frame_view = layout_embedded_content->ChildFrameView(); ASSERT_TRUE(inner_frame_view); LayoutViewItem inner_layout_view_item = inner_frame_view->GetLayoutViewItem(); ASSERT_FALSE(inner_layout_view_item.IsNull()); PaintLayerCompositor* inner_compositor = inner_layout_view_item.Compositor(); ASSERT_TRUE(inner_compositor->InCompositingMode()); GraphicsLayer* scroll_layer = inner_frame_view->LayoutViewportScrollableArea()->LayerForScrolling(); ASSERT_TRUE(scroll_layer); ASSERT_EQ(inner_frame_view->LayoutViewportScrollableArea(), scroll_layer->GetScrollableArea()); WebLayer* web_scroll_layer = scroll_layer->PlatformLayer(); ASSERT_TRUE(web_scroll_layer->Scrollable()); ASSERT_TRUE(web_scroll_layer->MainThreadScrollingReasons() & MainThreadScrollingReason::kHasBackgroundAttachmentFixedObjects); // Remove fixed background-attachment should make the iframe // scroll on cc. auto* iframe_doc = toHTMLIFrameElement(iframe)->contentDocument(); iframe = iframe_doc->getElementById("scrollable"); ASSERT_TRUE(iframe); iframe->removeAttribute("class"); ForceFullCompositingUpdate(); layout_object = iframe->GetLayoutObject(); ASSERT_TRUE(layout_object); scroll_layer = layout_object->GetFrameView() ->LayoutViewportScrollableArea() ->LayerForScrolling(); ASSERT_TRUE(scroll_layer); web_scroll_layer = scroll_layer->PlatformLayer(); ASSERT_TRUE(web_scroll_layer->Scrollable()); ASSERT_FALSE(web_scroll_layer->MainThreadScrollingReasons() & MainThreadScrollingReason::kHasBackgroundAttachmentFixedObjects); // Force main frame to scroll on main thread. All its descendants // should scroll on main thread as well. Element* element = GetFrame()->GetDocument()->getElementById("scrollable"); element->setAttribute( "style", "background-image: url('white-1x1.png'); background-attachment: fixed;", ASSERT_NO_EXCEPTION); ForceFullCompositingUpdate(); layout_object = iframe->GetLayoutObject(); ASSERT_TRUE(layout_object); scroll_layer = layout_object->GetFrameView() ->LayoutViewportScrollableArea() ->LayerForScrolling(); ASSERT_TRUE(scroll_layer); web_scroll_layer = scroll_layer->PlatformLayer(); ASSERT_TRUE(web_scroll_layer->Scrollable()); ASSERT_TRUE(web_scroll_layer->MainThreadScrollingReasons() & MainThreadScrollingReason::kHasBackgroundAttachmentFixedObjects); } // Upon resizing the content size, the main thread scrolling reason // kHasNonLayerViewportConstrainedObject should be updated on all frames TEST_P(ScrollingCoordinatorTest, RecalculateMainThreadScrollingReasonsUponResize) { GetWebView()->GetSettings()->SetPreferCompositingToLCDTextEnabled(false); RegisterMockedHttpURLLoad("has-non-layer-viewport-constrained-objects.html"); NavigateTo(base_url_ + "has-non-layer-viewport-constrained-objects.html"); ForceFullCompositingUpdate(); Element* element = GetFrame()->GetDocument()->getElementById("scrollable"); ASSERT_TRUE(element); LayoutObject* layout_object = element->GetLayoutObject(); ASSERT_TRUE(layout_object); GraphicsLayer* scroll_layer = layout_object->GetFrameView() ->LayoutViewportScrollableArea() ->LayerForScrolling(); WebLayer* web_scroll_layer; if (!RuntimeEnabledFeatures::RootLayerScrollingEnabled()) { ASSERT_TRUE(scroll_layer); web_scroll_layer = scroll_layer->PlatformLayer(); ASSERT_TRUE(web_scroll_layer->Scrollable()); ASSERT_FALSE( web_scroll_layer->MainThreadScrollingReasons() & MainThreadScrollingReason::kHasNonLayerViewportConstrainedObjects); } // When the div becomes to scrollable it should scroll on main thread element->setAttribute("style", "overflow:scroll;height:2000px;will-change:transform;", ASSERT_NO_EXCEPTION); ForceFullCompositingUpdate(); layout_object = element->GetLayoutObject(); ASSERT_TRUE(layout_object); scroll_layer = layout_object->GetFrameView() ->LayoutViewportScrollableArea() ->LayerForScrolling(); ASSERT_TRUE(scroll_layer); web_scroll_layer = scroll_layer->PlatformLayer(); ASSERT_TRUE(web_scroll_layer->Scrollable()); ASSERT_TRUE( web_scroll_layer->MainThreadScrollingReasons() & MainThreadScrollingReason::kHasNonLayerViewportConstrainedObjects); // The main thread scrolling reason should be reset upon the following change element->setAttribute("style", "overflow:scroll;height:200px;will-change:transform;", ASSERT_NO_EXCEPTION); ForceFullCompositingUpdate(); layout_object = element->GetLayoutObject(); ASSERT_TRUE(layout_object); scroll_layer = layout_object->GetFrameView() ->LayoutViewportScrollableArea() ->LayerForScrolling(); if (!RuntimeEnabledFeatures::RootLayerScrollingEnabled()) { ASSERT_TRUE(scroll_layer); web_scroll_layer = scroll_layer->PlatformLayer(); ASSERT_TRUE(web_scroll_layer->Scrollable()); ASSERT_FALSE( web_scroll_layer->MainThreadScrollingReasons() & MainThreadScrollingReason::kHasNonLayerViewportConstrainedObjects); } } class NonCompositedMainThreadScrollingReasonTest : public ScrollingCoordinatorTest { static const uint32_t kLCDTextRelatedReasons = MainThreadScrollingReason::kHasOpacityAndLCDText | MainThreadScrollingReason::kHasTransformAndLCDText | MainThreadScrollingReason::kBackgroundNotOpaqueInRectAndLCDText | MainThreadScrollingReason::kIsNotStackingContextAndLCDText; protected: NonCompositedMainThreadScrollingReasonTest() { RegisterMockedHttpURLLoad("two_scrollable_area.html"); NavigateTo(base_url_ + "two_scrollable_area.html"); } void TestNonCompositedReasons(const std::string& target, const uint32_t reason) { GetWebView()->GetSettings()->SetPreferCompositingToLCDTextEnabled(false); Document* document = GetFrame()->GetDocument(); Element* container = document->getElementById("scroller1"); container->setAttribute("class", target.c_str(), ASSERT_NO_EXCEPTION); ForceFullCompositingUpdate(); PaintLayerScrollableArea* scrollable_area = ToLayoutBoxModelObject(container->GetLayoutObject()) ->GetScrollableArea(); ASSERT_TRUE(scrollable_area); EXPECT_TRUE(scrollable_area->GetNonCompositedMainThreadScrollingReasons() & reason); Element* container2 = document->getElementById("scroller2"); PaintLayerScrollableArea* scrollable_area2 = ToLayoutBoxModelObject(container2->GetLayoutObject()) ->GetScrollableArea(); ASSERT_TRUE(scrollable_area2); // Different scrollable area should remain unaffected. EXPECT_FALSE( scrollable_area2->GetNonCompositedMainThreadScrollingReasons() & reason); LocalFrameView* frame_view = GetFrame()->View(); ASSERT_TRUE(frame_view); EXPECT_FALSE(frame_view->GetMainThreadScrollingReasons() & reason); // Remove attribute from the scroller 1 would lead to scroll on impl. container->removeAttribute("class"); ForceFullCompositingUpdate(); EXPECT_FALSE(scrollable_area->GetNonCompositedMainThreadScrollingReasons() & reason); EXPECT_FALSE(frame_view->GetMainThreadScrollingReasons() & reason); // Add target attribute would again lead to scroll on main thread container->setAttribute("class", target.c_str(), ASSERT_NO_EXCEPTION); ForceFullCompositingUpdate(); EXPECT_TRUE(scrollable_area->GetNonCompositedMainThreadScrollingReasons() & reason); EXPECT_FALSE(frame_view->GetMainThreadScrollingReasons() & reason); if ((reason & kLCDTextRelatedReasons) && !(reason & ~kLCDTextRelatedReasons)) { GetWebView()->GetSettings()->SetPreferCompositingToLCDTextEnabled(true); ForceFullCompositingUpdate(); EXPECT_FALSE( scrollable_area->GetNonCompositedMainThreadScrollingReasons()); EXPECT_FALSE(frame_view->GetMainThreadScrollingReasons()); } } }; INSTANTIATE_TEST_CASE_P(All, NonCompositedMainThreadScrollingReasonTest, ::testing::Bool()); TEST_P(NonCompositedMainThreadScrollingReasonTest, TransparentTest) { TestNonCompositedReasons("transparent", MainThreadScrollingReason::kHasOpacityAndLCDText); } TEST_P(NonCompositedMainThreadScrollingReasonTest, TransformTest) { TestNonCompositedReasons("transform", MainThreadScrollingReason::kHasTransformAndLCDText); } TEST_P(NonCompositedMainThreadScrollingReasonTest, BackgroundNotOpaqueTest) { TestNonCompositedReasons( "background-not-opaque", MainThreadScrollingReason::kBackgroundNotOpaqueInRectAndLCDText); } TEST_P(NonCompositedMainThreadScrollingReasonTest, BorderRadiusTest) { TestNonCompositedReasons("border-radius", MainThreadScrollingReason::kHasBorderRadius); } TEST_P(NonCompositedMainThreadScrollingReasonTest, ClipTest) { TestNonCompositedReasons("clip", MainThreadScrollingReason::kHasClipRelatedProperty); } TEST_P(NonCompositedMainThreadScrollingReasonTest, ClipPathTest) { uint32_t clip_reason = MainThreadScrollingReason::kHasClipRelatedProperty; GetWebView()->GetSettings()->SetPreferCompositingToLCDTextEnabled(false); Document* document = GetFrame()->GetDocument(); // Test ancestor with ClipPath Element* element = document->body(); ASSERT_TRUE(element); element->setAttribute(HTMLNames::styleAttr, "clip-path:circle(115px at 20px 20px);"); Element* container = document->getElementById("scroller1"); ASSERT_TRUE(container); ForceFullCompositingUpdate(); PaintLayerScrollableArea* scrollable_area = ToLayoutBoxModelObject(container->GetLayoutObject())->GetScrollableArea(); ASSERT_TRUE(scrollable_area); EXPECT_TRUE(scrollable_area->GetNonCompositedMainThreadScrollingReasons() & clip_reason); LocalFrameView* frame_view = GetFrame()->View(); ASSERT_TRUE(frame_view); EXPECT_FALSE(frame_view->GetMainThreadScrollingReasons() & clip_reason); // Remove clip path from ancestor. element->removeAttribute(HTMLNames::styleAttr); ForceFullCompositingUpdate(); EXPECT_FALSE(scrollable_area->GetNonCompositedMainThreadScrollingReasons() & clip_reason); EXPECT_FALSE(frame_view->GetMainThreadScrollingReasons() & clip_reason); // Test descendant with ClipPath element = document->getElementById("content1"); ASSERT_TRUE(element); element->setAttribute(HTMLNames::styleAttr, "clip-path:circle(115px at 20px 20px);"); ForceFullCompositingUpdate(); EXPECT_TRUE(scrollable_area->GetNonCompositedMainThreadScrollingReasons() & clip_reason); EXPECT_FALSE(frame_view->GetMainThreadScrollingReasons() & clip_reason); // Remove clip path from descendant. element->removeAttribute(HTMLNames::styleAttr); ForceFullCompositingUpdate(); EXPECT_FALSE(scrollable_area->GetNonCompositedMainThreadScrollingReasons() & clip_reason); EXPECT_FALSE(frame_view->GetMainThreadScrollingReasons() & clip_reason); } TEST_P(NonCompositedMainThreadScrollingReasonTest, LCDTextEnabledTest) { TestNonCompositedReasons("transparent border-radius", MainThreadScrollingReason::kHasOpacityAndLCDText | MainThreadScrollingReason::kHasBorderRadius); } TEST_P(NonCompositedMainThreadScrollingReasonTest, BoxShadowTest) { TestNonCompositedReasons( "box-shadow", MainThreadScrollingReason::kHasBoxShadowFromNonRootLayer); } TEST_P(NonCompositedMainThreadScrollingReasonTest, StackingContextTest) { GetWebView()->GetSettings()->SetPreferCompositingToLCDTextEnabled(false); Document* document = GetFrame()->GetDocument(); Element* container = document->getElementById("scroller1"); ASSERT_TRUE(container); ForceFullCompositingUpdate(); // If a scroller contains all its children, it's not a stacking context. PaintLayerScrollableArea* scrollable_area = ToLayoutBoxModelObject(container->GetLayoutObject())->GetScrollableArea(); ASSERT_TRUE(scrollable_area); EXPECT_TRUE(scrollable_area->GetNonCompositedMainThreadScrollingReasons() & MainThreadScrollingReason::kIsNotStackingContextAndLCDText); GetWebView()->GetSettings()->SetPreferCompositingToLCDTextEnabled(true); ForceFullCompositingUpdate(); EXPECT_FALSE(scrollable_area->GetNonCompositedMainThreadScrollingReasons() & MainThreadScrollingReason::kIsNotStackingContextAndLCDText); GetWebView()->GetSettings()->SetPreferCompositingToLCDTextEnabled(false); // Adding "contain: paint" to force a stacking context leads to promotion. container->setAttribute("style", "contain: paint", ASSERT_NO_EXCEPTION); ForceFullCompositingUpdate(); EXPECT_FALSE(scrollable_area->GetNonCompositedMainThreadScrollingReasons()); } TEST_P(NonCompositedMainThreadScrollingReasonTest, CompositedWithLCDTextRelatedReasonsTest) { // With "will-change:transform" we composite elements with // LCDTextRelatedReasons only. For elements with other // NonCompositedReasons, we don't create scrollingLayer for their // CompositedLayerMapping therefore they don't get composited. GetWebView()->GetSettings()->SetPreferCompositingToLCDTextEnabled(false); Document* document = GetFrame()->GetDocument(); Element* container = document->getElementById("scroller1"); ASSERT_TRUE(container); container->setAttribute("class", "composited transparent", ASSERT_NO_EXCEPTION); ForceFullCompositingUpdate(); PaintLayerScrollableArea* scrollable_area = ToLayoutBoxModelObject(container->GetLayoutObject())->GetScrollableArea(); ASSERT_TRUE(scrollable_area); EXPECT_FALSE(scrollable_area->GetNonCompositedMainThreadScrollingReasons()); Element* container2 = document->getElementById("scroller2"); ASSERT_TRUE(container2); container2->setAttribute("class", "composited border-radius", ASSERT_NO_EXCEPTION); ForceFullCompositingUpdate(); PaintLayerScrollableArea* scrollable_area2 = ToLayoutBoxModelObject(container2->GetLayoutObject()) ->GetScrollableArea(); ASSERT_TRUE(scrollable_area2); EXPECT_TRUE(scrollable_area2->GetNonCompositedMainThreadScrollingReasons() & MainThreadScrollingReason::kHasBorderRadius); } } // namespace blink
40.506762
80
0.752126
metux
e4c870af5a321951fa3ff9bc318e87486b09b59e
365
cpp
C++
code/main.cpp
fawkesLi-lhh/Vagrant
15adbf52fb55235f68b3d576c5a8433cf8ee5b41
[ "Apache-2.0" ]
3
2021-02-19T14:06:26.000Z
2021-03-11T13:28:03.000Z
code/main.cpp
fawkesLi-lhh/Vagrant
15adbf52fb55235f68b3d576c5a8433cf8ee5b41
[ "Apache-2.0" ]
null
null
null
code/main.cpp
fawkesLi-lhh/Vagrant
15adbf52fb55235f68b3d576c5a8433cf8ee5b41
[ "Apache-2.0" ]
null
null
null
#include <vector> #include <cstdlib> #include <iostream> #include <set> #include <string> #include <cstring> #include <algorithm> #include <dirent.h> #include <unistd.h> #include "Vagrant/vagrant.h" #include "Vagrant/server/Server.h" #include "Classes/Login.h" signed main() { Server server; server.addUrl(new Login()); server.loop(); return 0; }
17.380952
34
0.687671
fawkesLi-lhh
e4c9b2e839a3a6a8eb1df537cd50049a27d07002
514
cc
C++
src/tsl_array_map.cc
agutikov/hash-table-shootout
fb98881843b8a3510ff0a9d90a6bf1ba8dbd9690
[ "CC0-1.0" ]
null
null
null
src/tsl_array_map.cc
agutikov/hash-table-shootout
fb98881843b8a3510ff0a9d90a6bf1ba8dbd9690
[ "CC0-1.0" ]
null
null
null
src/tsl_array_map.cc
agutikov/hash-table-shootout
fb98881843b8a3510ff0a9d90a6bf1ba8dbd9690
[ "CC0-1.0" ]
null
null
null
#include <inttypes.h> #include <string> #include <tsl/array_map.h> #include <string_view> template<class CharT> struct str_hash { std::size_t operator()(const CharT* key, std::size_t key_size) const { return std::hash<std::string_view>()(std::string_view(key, key_size)); } }; typedef tsl::array_map<char, int64_t, str_hash<char>> str_hash_t; #include "hash_map_str_base.h" #undef INSERT_STR_INTO_HASH #define INSERT_STR_INTO_HASH(key, value) str_hash.insert(key, value) #include "template.c"
24.47619
78
0.733463
agutikov
e4ced3dbe4972567aa73cf3489254377ce7ed420
8,558
cpp
C++
src/Evaluator.cpp
bmhowe34/qwixxmaster
106d1da67c8c0e6378b7f55757f84396d124b05b
[ "MIT" ]
2
2019-04-09T10:27:48.000Z
2020-04-19T23:35:34.000Z
src/Evaluator.cpp
bmhowe34/qwixxmaster
106d1da67c8c0e6378b7f55757f84396d124b05b
[ "MIT" ]
2
2020-04-20T01:01:20.000Z
2020-04-22T21:52:53.000Z
src/Evaluator.cpp
bmhowe34/qwixxmaster
106d1da67c8c0e6378b7f55757f84396d124b05b
[ "MIT" ]
1
2020-04-22T01:10:28.000Z
2020-04-22T01:10:28.000Z
#include "Evaluator.h" #include <algorithm> #include <iostream> #include <memory> #include "State.h" #include "RandomDice.h" #include "BruteForceRollGenerator.h" #include "StringUtils.h" #include "MemoryManager.h" namespace{ size_t encode_min_max_0_based(size_t first, size_t second){ size_t max=std::max(first, second); size_t min=std::min(first, second); return max*(max+1)/2+min; } size_t COLOR_MAX_ID=78; size_t calc_max_index(){ size_t two_colors=encode_min_max_0_based(COLOR_MAX_ID, COLOR_MAX_ID); return (encode_min_max_0_based(two_colors, two_colors)+1)*5; } size_t calc_color_id(const ColorState &cs){ return (cs.last-1)*cs.last/2+cs.cnt; } size_t calc_2color_id(const ColorState &cs1, const ColorState &cs2){ size_t first=calc_color_id(cs1); size_t second=calc_color_id(cs2); return encode_min_max_0_based(first, second); } size_t calc_id(const State &state){ size_t id1=calc_2color_id(state.get_color_state(cRED), state.get_color_state(cYELLOW)); ColorState sGreen=state.get_color_state(cGREEN); sGreen.last=14-sGreen.last; ColorState sBlue=state.get_color_state(cBLUE); sBlue.last=14-sBlue.last; size_t id2=calc_2color_id(sGreen, sBlue); size_t id=encode_min_max_0_based(id1, id2); return id*5+state.get_missed(); } } namespace { double STATE_NOT_EVALUATED=-300.0;//actually -16 is the worst what can happen! } size_t Evaluator::get_next_player(size_t current_player) const{ return (current_player+1)%player_number; } Evaluator::Evaluator(size_t sampling_number_, size_t player_number_): sampling_number(sampling_number_), player_number(player_number_), mem(player_number*(calc_max_index()+1), STATE_NOT_EVALUATED) {} float Evaluator::evaluate_state(const State &state, size_t current_player){ size_t id=calc_id(state)+current_player*(calc_max_index()+1); if(mem.at(id)==STATE_NOT_EVALUATED){ if(state.ended()){ mem.at(id)=state.score(); } else{ double value=0; if(current_player==0){//it is my turn std::unique_ptr<RollGenerator> gen; if(sampling_number==0) gen.reset(new BruteForceRollGenerator()); else gen.reset(new GlobalRollGenerator(sampling_number)); while(gen->has_next()){ RollPair roll_pair=gen->get_next(); value+=roll_pair.probability*evaluate_roll(state, roll_pair.roll); } } else{//it is not my turn, only short roll can be used std::unique_ptr<ShortRollGenerator> gen; if(sampling_number==0 || sampling_number>=21) //there are at most 21 different dice rolls! gen.reset(new BruteForceShortRollGenerator()); else gen.reset(new GlobalShortRollGenerator(sampling_number)); while(gen->has_next()){ ShortRollPair roll_pair=gen->get_next(); value+=roll_pair.probability*evaluate_roll(state, roll_pair.roll, current_player); } } mem.at(id)=static_cast<float>(value); } } return mem.at(id); } float Evaluator::evaluate_without_whites(const State &state, const DiceRoll &roll, size_t current_player){ size_t next_player=get_next_player(current_player); // no whites! float best=-1e6; State cur=state; for(size_t dice=4;dice<=5;dice++){ if(dice==5 && roll[4]==roll[5]) break; for(size_t j=0;j<COLOR_CNT;j++){ Color color=static_cast<Color>(j); unsigned char save_last=cur.last[j]; unsigned char save_cnt=cur.cnt[j]; if(cur.take(color, roll[color]+roll[dice])){ best=std::max(best, evaluate_state(cur, next_player)); cur.last[j]=save_last; cur.cnt[j]=save_cnt; } } } return best; } float Evaluator::evaluate_roll(const State &state, const DiceRoll &roll){ //for full roll the current player is always 0! size_t current_player=0; size_t next_player=get_next_player(0); //always an option: take miss State cur=state; cur.add_miss(); float best=evaluate_state(cur, next_player); //take whites: for (size_t i=0;i<COLOR_CNT;i++){ Color color=static_cast<Color>(i); cur=state; if(cur.take(color, roll[4]+roll[5])){ best=std::max(best, evaluate_state(cur, next_player)); if (!cur.ended()){ best=std::max(best, evaluate_without_whites(cur, roll, current_player)); } } } return std::max(best, evaluate_without_whites(state, roll, current_player)); } float Evaluator::evaluate_roll(const State &state, const ShortDiceRoll &roll, size_t current_player){ size_t next_player=get_next_player(current_player); //it is allowed not to take float best=evaluate_state(state, next_player); //take whites: for (size_t i=0;i<COLOR_CNT;i++){ Color color=static_cast<Color>(i); State cur=state; if(cur.take(color, roll.at(0)+roll.at(1))){ best=std::max(best, evaluate_state(cur, next_player)); } } return best; } void Evaluator::evaluate_without_whites(const State &state, const DiceRoll &roll, MoveInfos &res, const std::string &prefix, size_t current_player){ size_t next_player=get_next_player(current_player); for(size_t dice=4;dice<=5;dice++) for(size_t j=0;j<COLOR_CNT;j++){ Color color=static_cast<Color>(j); State cur=state; if(cur.take(color, roll[color]+roll[dice])) res.push_back(std::make_pair(evaluate_state(cur, next_player),prefix+ color2str(color)+" "+stringutils::int2str(roll[color]+roll[dice]))); } } Evaluator::MoveInfos Evaluator::get_roll_evaluation(const State &state, const DiceRoll &roll){ MoveInfos res; //for full roll the current player is always 0! size_t current_player=0; size_t next_player=get_next_player(current_player); //always an option: take miss State cur=state; cur.add_miss(); res.push_back(std::make_pair(evaluate_state(cur, next_player), "miss")); //take whites: for (size_t i=0;i<COLOR_CNT;i++){ Color color=static_cast<Color>(i); cur=state; if(cur.take(color, roll.at(4)+roll.at(5))){ std::string move=color2str(color)+" "+stringutils::int2str(roll.at(4)+roll.at(5)); res.push_back(std::make_pair(evaluate_state(cur, next_player), move)); if (!cur.ended()){ //additional color dice? evaluate_without_whites(cur, roll, res, move+",", current_player); } } } // no whites! evaluate_without_whites(state, roll, res, "", current_player); sort(res.begin(), res.end(), std::greater<MoveInfo>()); return res; } Evaluator::MoveInfos Evaluator::get_short_roll_evaluation(const State &state, const ShortDiceRoll &roll, size_t current_player){ MoveInfos res; size_t next_player=get_next_player(current_player); //I'm allowed not to take anything: res.push_back(std::make_pair(evaluate_state(state, next_player), "nothing")); //take whites: for (size_t i=0;i<COLOR_CNT;i++){ Color color=static_cast<Color>(i); State cur=state; if(cur.take(color, roll.at(0)+roll.at(1))){ std::string move=color2str(color)+" "+stringutils::int2str(roll.at(0)+roll.at(1)); res.push_back(std::make_pair(evaluate_state(cur, next_player), move)); } } sort(res.begin(), res.end(), std::greater<MoveInfo>()); return res; } std::pair<size_t, size_t> Evaluator::save_memory_to_file(const std::string &filename) const{ MemoryManager::save_memory(filename, mem); size_t not_set=std::count(mem.begin(), mem.end(), STATE_NOT_EVALUATED); return std::make_pair(mem.size(), not_set); } std::pair<size_t, size_t> Evaluator::load_memory_from_file(const std::string &filename){ MemoryManager::load_memory(filename, mem); size_t not_set=std::count(mem.begin(), mem.end(), STATE_NOT_EVALUATED); return std::make_pair(mem.size(), not_set); } size_t Evaluator::get_number_of_players() const{ return player_number; }
33.042471
161
0.636364
bmhowe34
e4cfad283dd9d846667f11cde2626250066208e2
49,214
cpp
C++
src/isbiad.cpp
nporsche/fastbit
91d06c68b9f4a0a0cc39da737d1c880ab21fe947
[ "BSD-3-Clause-LBNL" ]
null
null
null
src/isbiad.cpp
nporsche/fastbit
91d06c68b9f4a0a0cc39da737d1c880ab21fe947
[ "BSD-3-Clause-LBNL" ]
null
null
null
src/isbiad.cpp
nporsche/fastbit
91d06c68b9f4a0a0cc39da737d1c880ab21fe947
[ "BSD-3-Clause-LBNL" ]
null
null
null
// $Id$ // Author: John Wu <John.Wu at ACM.org> // Copyright (c) 2000-2015 the Regents of the University of California // // This file contains the implementation of the class called ibis::sbiad. // // The word sbiad is the Italian translation of the English word fade. // // fade -- multicomponent range-encoded bitmap index // sbiad -- multicomponent interval-encoded bitmap index // sapid -- multicomponent equality-encoded bitmap index // #if defined(_WIN32) && defined(_MSC_VER) #pragma warning(disable:4786) // some identifier longer than 256 characters #endif #include "irelic.h" #include "part.h" #include "column.h" #include "resource.h" //////////////////////////////////////////////////////////////////////// // functions of ibis::sbiad // /// Constructor. If an index exists in the specified location, it will be /// read, otherwise a new bitmap index will be created from current data. ibis::sbiad::sbiad(const ibis::column* c, const char* f, const uint32_t nbase) : ibis::fade(0) { if (c == 0) return; // nothing can be done col = c; try { if (c->partition()->nRows() < 1000000) { construct1(f, nbase); // uses more temporary space } else { construct2(f, nbase); // scan data twice } if (ibis::gVerbose > 2) { ibis::util::logger lg; lg() << "sbiad[" << col->partition()->name() << '.' << col->name() << "]::ctor -- constructed a " << bases.size() << "-component interval index with " << bits.size() << " bitmap" << (bits.size()>1?"s":"") << " for " << nrows << " row" << (nrows>1?"s":""); if (ibis::gVerbose > 6) { lg() << "\n"; print(lg()); } } } catch (...) { LOGGER(ibis::gVerbose > 1) << "Warning -- sbiad[" << col->partition()->name() << '.' << col->name() << "]::ctor received an exception, cleaning up ..."; clear(); throw; } } // constructor /// Reconstruct an index from a storage object. /// The content of the file (following the 8-byte header) is as follows: ///@code /// nrows(uint32_t) -- the number of bits in a bit sequence /// nobs (uint32_t) -- the number of bit sequences /// card (uint32_t) -- the number of distinct values, i.e., cardinality /// (padding to ensure the next data element is on 8-byte boundary) /// values (double[card]) -- the distinct values as doubles /// offset([nobs+1]) -- the starting positions of the bit sequences /// (as bit vectors) /// nbases(uint32_t) -- the number of components (bases) used /// cnts (uint32_t[card]) -- the counts for each distinct value /// bases(uint32_t[nbases]) -- the bases sizes /// bitvectors -- the bitvectors one after another ///@endcode ibis::sbiad::sbiad(const ibis::column* c, ibis::fileManager::storage* st, size_t start) : ibis::fade(c, st, start) { if (ibis::gVerbose > 2) { ibis::util::logger lg; lg() << "sbiad[" << col->partition()->name() << '.' << col->name() << "]::ctor -- initialized a " << bases.size() << "-component interval index with " << bits.size() << " bitmap" << (bits.size()>1?"s":"") << " for " << nrows << " row" << (nrows>1?"s":"") << " from a storage object @ " << st; if (ibis::gVerbose > 6) { lg() << "\n"; print(lg()); } } } // reconstruct data from content of a file // the argument is the name of the directory or the file name int ibis::sbiad::write(const char* dt) const { if (vals.empty()) return -1; std::string fnm, evt; evt = "sbiad"; if (col != 0 && ibis::gVerbose > 1) { evt += '['; evt += col->fullname(); evt += ']'; } evt += "::write"; if (ibis::gVerbose > 1 && dt != 0) { evt += '('; evt += dt; evt += ')'; } indexFileName(fnm, dt); if (fnm.empty()) { return 0; } else if (0 != str && 0 != str->filename() && 0 == fnm.compare(str->filename())) { LOGGER(ibis::gVerbose > 0) << "Warning -- " << evt << " can not overwrite the index file \"" << fnm << "\" while it is used as a read-only file map"; return 0; } else if (fname != 0 && *fname != 0 && 0 == fnm.compare(fname)) { activate(); // read everything into memory fname = 0; // break the link with the named file } ibis::fileManager::instance().flushFile(fnm.c_str()); if (fname != 0 || str != 0) activate(); // need all bitvectors int fdes = UnixOpen(fnm.c_str(), OPEN_WRITENEW, OPEN_FILEMODE); if (fdes < 0) { ibis::fileManager::instance().flushFile(fnm.c_str()); fdes = UnixOpen(fnm.c_str(), OPEN_WRITENEW, OPEN_FILEMODE); if (fdes < 0) { LOGGER(ibis::gVerbose > 0) << "Warning -- " << evt << " failed to open \"" << fnm << "\" for writing"; return -2; } } IBIS_BLOCK_GUARD(UnixClose, fdes); #if defined(_WIN32) && defined(_MSC_VER) (void)_setmode(fdes, _O_BINARY); #endif #if defined(HAVE_FLOCK) ibis::util::flock flck(fdes); if (flck.isLocked() == false) { LOGGER(ibis::gVerbose > 0) << "Warning -- " << evt << " failed to acquire an exclusive lock " "on file " << fnm << " for writing, another thread must be " "writing the index now"; return -6; } #endif #ifdef FASTBIT_USE_LONG_OFFSETS const bool useoffset64 = true; #else const bool useoffset64 = (getSerialSize()+8 > 0x80000000UL); #endif char header[] = "#IBIS\13\0\0"; header[5] = (char)ibis::index::SBIAD; header[6] = (char)(useoffset64 ? 8 : 4); off_t ierr = UnixWrite(fdes, header, 8); if (ierr < 8) { LOGGER(ibis::gVerbose > 0) << "Warning -- " << evt << " failed to write the 8-byte header, ierr = " << ierr; return -3; } if (useoffset64) ierr = ibis::fade::write64(fdes); else ierr = ibis::fade::write32(fdes); if (ierr >= 0) { #if defined(FASTBIT_SYNC_WRITE) #if _POSIX_FSYNC+0 > 0 (void) UnixFlush(fdes); // write to disk #elif defined(_WIN32) && defined(_MSC_VER) (void) _commit(fdes); #endif #endif LOGGER(ierr >= 0 && ibis::gVerbose > 5) << evt << " wrote " << bits.size() << " bitmap" << (bits.size()>1?"s":"") << " to " << fnm; } return ierr; } // ibis::sbiad::write /// This version of the constructor take one pass throught the data. It /// constructs a ibis::index::VMap first, then construct the sbiad from the /// VMap. It uses more computer memory than the two-pass version, but will /// probably run a little faster. void ibis::sbiad::construct1(const char* f, const uint32_t nbase) { VMap bmap; // a map between values and their position try { mapValues(f, bmap); } catch (...) { // need to clean up bmap LOGGER(ibis::gVerbose >= 0) << "sbiad::construct reclaiming storage " "allocated to bitvectors (" << bmap.size() << ")"; for (VMap::iterator it = bmap.begin(); it != bmap.end(); ++ it) delete (*it).second; bmap.clear(); ibis::fileManager::instance().signalMemoryAvailable(); throw; } if (bmap.empty()) return; nrows = (*(bmap.begin())).second->size(); if (nrows != col->partition()->nRows()) { for (VMap::iterator it = bmap.begin(); it != bmap.end(); ++ it) delete (*it).second; bmap.clear(); ibis::fileManager::instance().signalMemoryAvailable(); LOGGER(ibis::gVerbose >= 0) << "Warning -- sbiad::construct1 the bitvectors " "do not have the expected size(" << col->partition()->nRows() << "). stopping.."; throw ibis::bad_alloc("incorrect bitvector sizes"); } // convert bmap into the current data structure // fill the arrays vals and cnts const uint32_t card = bmap.size(); vals.reserve(card); cnts.reserve(card); for (VMap::const_iterator it = bmap.begin(); it != bmap.end(); ++it) { vals.push_back((*it).first); cnts.push_back((*it).second->cnt()); } // fill the array bases setBases(bases, card, nbase); // count the number of bitvectors to genreate const uint32_t nb = bases.size(); uint32_t nobs = 0; uint32_t i; for (i = 0; i < nb; ++i) nobs += bases[i]; // allocate enough bitvectors in bits bits.resize(nobs); for (i = 0; i < nobs; ++i) bits[i] = 0; if (ibis::gVerbose > 5) { col->logMessage("sbiad::construct", "initialized the array of " "bitvectors, start converting %lu bitmaps into %lu-" "component range code (with %lu bitvectors)", static_cast<long unsigned>(vals.size()), static_cast<long unsigned>(nb), static_cast<long unsigned>(nobs)); } // converting to multi-level equality encoding first i = 0; for (VMap::const_iterator it = bmap.begin(); it != bmap.end(); ++it, ++i) { uint32_t offset = 0; uint32_t ii = i; for (uint32_t j = 0; j < nb; ++j) { uint32_t k = ii % bases[j]; if (bits[offset+k]) { *(bits[offset+k]) |= *((*it).second); } else { bits[offset+k] = new ibis::bitvector(); bits[offset+k]->copy(*((*it).second)); // expected to be operated on more than 64 times if (vals.size() > 64*bases[j]) bits[offset+k]->decompress(); } ii /= bases[j]; offset += bases[j]; } delete (*it).second; // no longer need the bitmap } for (i = 0; i < nobs; ++i) { if (bits[i] == 0) { bits[i] = new ibis::bitvector(); bits[i]->set(0, nrows); } } #if DEBUG+0 > 0 || _DEBUG+0 > 0 if (ibis::gVerbose > 11) { LOGGER(ibis::gVerbose >= 0) << "DEBUG -- sbiad::construct1 converted" << bmap.size() << " bitmaps for each distinct value into " << bits.size() << bases.size() << "-component equality encoded bitmaps"; } #endif // sum up the bitvectors according to the interval-encoding array_t<bitvector*> beq; beq.swap(bits); try { // use a try block to ensure the bitvectors in beq are freed uint32_t ke = 0; bits.clear(); for (i = 0; i < nb; ++i) { if (bases[i] > 2) { nobs = (bases[i] - 1) / 2; bits.push_back(new ibis::bitvector); bits.back()->copy(*(beq[ke])); if (nobs > 64) bits.back()->decompress(); for (uint32_t j = ke+1; j <= ke+nobs; ++j) *(bits.back()) |= *(beq[j]); bits.back()->compress(); for (uint32_t j = 1; j < bases[i]-nobs; ++j) { bits.push_back(*(bits.back()) - *(beq[ke+j-1])); *(bits.back()) |= *(beq[ke+j+nobs]); bits.back()->compress(); } for (uint32_t j = ke; j < ke+bases[i]; ++j) { delete beq[j]; beq[j] = 0; } } else { bits.push_back(beq[ke]); if (bases[i] > 1) { delete beq[ke+1]; beq[ke+1] = 0; } } ke += bases[i]; } } catch (...) { LOGGER(ibis::gVerbose > 1) << "Warning -- column::[" << col->name() << "]::construct1 encountered an exception while converting " "to inverval encoding, cleaning up ..."; for (uint32_t i = 0; i < beq.size(); ++ i) delete beq[i]; throw; } beq.clear(); #if DEBUG+0 > 0 || _DEBUG+0 > 0 if (ibis::gVerbose > 11) { LOGGER(ibis::gVerbose >= 0) << "DEBUG -- sbiad::construct1 completed " << "converting equality encoding to interval encoding"; } #endif optionalUnpack(bits, col->indexSpec()); // write out the current content if (ibis::gVerbose > 8) { ibis::util::logger lg; print(lg()); } } // ibis::sbiad::construct1 /// Assign bit values for a given key value. Assume that the array @c vals /// is initialized properly, this function converts the value @cval into a /// set of bits to be stored in the bit vectors contained in @c bits. /// /// @note to be used by @c construct2 to build a new ibis::sbiad index. void ibis::sbiad::setBit(const uint32_t i, const double val) { if (val > vals.back()) return; if (val < vals[0]) return; // perform a binary search to locate position of val in vals uint32_t ii = 0, jj = vals.size() - 1; uint32_t kk = (ii + jj) / 2; while (kk > ii) { if (vals[kk] < val) { ii = kk; kk = (kk + jj) / 2; } else if (vals[kk] > val) { jj = kk; kk = (ii + kk) / 2; } else { ii = kk; jj = kk; } } if (vals[jj] == val) { // vals[jj] is the same as val kk = jj; } else if (vals[ii] == val) { // vals[ii] is the same as val kk = ii; } else { // doesn't match a know value -- shouldn't be return; } // now we know what bitvectors to modify const uint32_t nb = bases.size(); uint32_t offset = 0; // offset into bits for (ii = 0; ii < nb; ++ ii) { jj = kk % bases[ii]; bits[offset+jj]->setBit(i, 1); kk /= bases[ii]; offset += bases[ii]; } } // ibis::sbiad::setBit /// Generate a new sbiad index by passing through the data twice. /// - (1) scan the data to generate a list of distinct values and their count. /// - (2) scan the data a second time to produce the bit vectors. void ibis::sbiad::construct2(const char* f, const uint32_t nbase) { { // a block to limit the scope of hst histogram hst; mapValues(f, hst); // scan the data to produce the histogram if (hst.empty()) // no data, of course no index return; // convert histogram into two arrays const uint32_t nhst = hst.size(); vals.resize(nhst); cnts.resize(nhst); histogram::const_iterator it = hst.begin(); for (uint32_t i = 0; i < nhst; ++i) { vals[i] = (*it).first; cnts[i] = (*it).second; ++ it; } } // determine the base sizes setBases(bases, vals.size(), nbase); const uint32_t nb = bases.size(); int ierr; // allocate the correct number of bitvectors uint32_t nobs = 0; for (uint32_t ii = 0; ii < nb; ++ii) nobs += bases[ii]; bits.resize(nobs); for (uint32_t ii = 0; ii < nobs; ++ii) bits[ii] = new ibis::bitvector; std::string fnm; // name of the data file dataFileName(fnm, f); nrows = col->partition()->nRows(); ibis::bitvector mask; { // name of mask file associated with the data file array_t<ibis::bitvector::word_t> arr; std::string mname(fnm); mname += ".msk"; if (ibis::fileManager::instance().getFile(mname.c_str(), arr) == 0) mask.copy(ibis::bitvector(arr)); // convert arr to a bitvector else mask.set(1, nrows); // default mask } // need to do different things for different columns switch (col->type()) { case ibis::TEXT: case ibis::UINT: {// unsigned int array_t<uint32_t> val; if (! fnm.empty()) ierr = ibis::fileManager::instance().getFile(fnm.c_str(), val); else ierr = col->getValuesArray(&val); if (ierr < 0 || val.empty()) { LOGGER(ibis::gVerbose > 0) << "Warning -- sbiad::construct2 failed to retrieve any value"; break; } if (val.size() > mask.size()) { col->logWarning("sbiad::construct", "the data file \"%s\" " "contains more elements (%lu) then expected " "(%lu)", fnm.c_str(), static_cast<long unsigned>(val.size()), static_cast<long unsigned>(mask.size())); mask.adjustSize(nrows, nrows); } ibis::bitvector::indexSet iset = mask.firstIndexSet(); uint32_t nind = iset.nIndices(); const ibis::bitvector::word_t *iix = iset.indices(); while (nind) { if (iset.isRange()) { // a range uint32_t k = (iix[1] < nrows ? iix[1] : nrows); for (uint32_t i = *iix; i < k; ++i) setBit(i, val[i]); } else if (*iix+ibis::bitvector::bitsPerLiteral() < nrows) { // a list of indices for (uint32_t i = 0; i < nind; ++i) { uint32_t k = iix[i]; setBit(k, val[k]); } } else { for (uint32_t i = 0; i < nind; ++i) { uint32_t k = iix[i]; if (k < nrows) setBit(k, val[k]); } } ++iset; nind = iset.nIndices(); if (*iix >= nrows) nind = 0; } // while (nind) break;} case ibis::INT: {// signed int array_t<int32_t> val; if (! fnm.empty()) ierr = ibis::fileManager::instance().getFile(fnm.c_str(), val); else ierr = col->getValuesArray(&val); if (ierr < 0 || val.empty()) { LOGGER(ibis::gVerbose > 0) << "Warning -- sbiad::construct2 failed to retrieve any value"; break; } if (val.size() > mask.size()) { col->logWarning("sbiad::construct", "the data file \"%s\" " "contains more elements (%lu) then expected " "(%lu)", fnm.c_str(), static_cast<long unsigned>(val.size()), static_cast<long unsigned>(mask.size())); mask.adjustSize(nrows, nrows); } ibis::bitvector::indexSet iset = mask.firstIndexSet(); uint32_t nind = iset.nIndices(); const ibis::bitvector::word_t *iix = iset.indices(); while (nind) { if (iset.isRange()) { // a range uint32_t k = (iix[1] < nrows ? iix[1] : nrows); for (uint32_t i = *iix; i < k; ++i) setBit(i, val[i]); } else if (*iix+ibis::bitvector::bitsPerLiteral() < nrows) { // a list of indices for (uint32_t i = 0; i < nind; ++i) { uint32_t k = iix[i]; setBit(k, val[k]); } } else { for (uint32_t i = 0; i < nind; ++i) { uint32_t k = iix[i]; if (k < nrows) setBit(k, val[k]); } } ++iset; nind = iset.nIndices(); if (*iix >= nrows) nind = 0; } // while (nind) break;} case ibis::ULONG: {// unsigned long int array_t<uint64_t> val; if (! fnm.empty()) ierr = ibis::fileManager::instance().getFile(fnm.c_str(), val); else ierr = col->getValuesArray(&val); if (ierr < 0 || val.empty()) { LOGGER(ibis::gVerbose > 0) << "Warning -- sbiad::construct2 failed to retrieve any value"; break; } if (val.size() > mask.size()) { col->logWarning("sbiad::construct", "the data file \"%s\" " "contains more elements (%lu) then expected " "(%lu)", fnm.c_str(), static_cast<long unsigned>(val.size()), static_cast<long unsigned>(mask.size())); mask.adjustSize(nrows, nrows); } ibis::bitvector::indexSet iset = mask.firstIndexSet(); uint32_t nind = iset.nIndices(); const ibis::bitvector::word_t *iix = iset.indices(); while (nind) { if (iset.isRange()) { // a range uint32_t k = (iix[1] < nrows ? iix[1] : nrows); for (uint32_t i = *iix; i < k; ++i) setBit(i, val[i]); } else if (*iix+ibis::bitvector::bitsPerLiteral() < nrows) { // a list of indices for (uint32_t i = 0; i < nind; ++i) { uint32_t k = iix[i]; setBit(k, val[k]); } } else { for (uint32_t i = 0; i < nind; ++i) { uint32_t k = iix[i]; if (k < nrows) setBit(k, val[k]); } } ++iset; nind = iset.nIndices(); if (*iix >= nrows) nind = 0; } // while (nind) break;} case ibis::LONG: {// signed long int array_t<int64_t> val; if (! fnm.empty()) ierr = ibis::fileManager::instance().getFile(fnm.c_str(), val); else ierr = col->getValuesArray(&val); if (ierr < 0 || val.empty()) { LOGGER(ibis::gVerbose > 0) << "Warning -- sbiad::construct2 failed to retrieve any value"; break; } if (val.size() > mask.size()) { col->logWarning("sbiad::construct", "the data file \"%s\" " "contains more elements (%lu) then expected " "(%lu)", fnm.c_str(), static_cast<long unsigned>(val.size()), static_cast<long unsigned>(mask.size())); mask.adjustSize(nrows, nrows); } ibis::bitvector::indexSet iset = mask.firstIndexSet(); uint32_t nind = iset.nIndices(); const ibis::bitvector::word_t *iix = iset.indices(); while (nind) { if (iset.isRange()) { // a range uint32_t k = (iix[1] < nrows ? iix[1] : nrows); for (uint32_t i = *iix; i < k; ++i) setBit(i, val[i]); } else if (*iix+ibis::bitvector::bitsPerLiteral() < nrows) { // a list of indices for (uint32_t i = 0; i < nind; ++i) { uint32_t k = iix[i]; setBit(k, val[k]); } } else { for (uint32_t i = 0; i < nind; ++i) { uint32_t k = iix[i]; if (k < nrows) setBit(k, val[k]); } } ++iset; nind = iset.nIndices(); if (*iix >= nrows) nind = 0; } // while (nind) break;} case ibis::USHORT: {// unsigned short int array_t<uint16_t> val; if (! fnm.empty()) ierr = ibis::fileManager::instance().getFile(fnm.c_str(), val); else ierr = col->getValuesArray(&val); if (ierr < 0 || val.empty()) { LOGGER(ibis::gVerbose > 0) << "Warning -- sbiad::construct2 failed to retrieve any value"; break; } if (val.size() > mask.size()) { col->logWarning("sbiad::construct", "the data file \"%s\" " "contains more elements (%lu) then expected " "(%lu)", fnm.c_str(), static_cast<long unsigned>(val.size()), static_cast<long unsigned>(mask.size())); mask.adjustSize(nrows, nrows); } ibis::bitvector::indexSet iset = mask.firstIndexSet(); uint32_t nind = iset.nIndices(); const ibis::bitvector::word_t *iix = iset.indices(); while (nind) { if (iset.isRange()) { // a range uint32_t k = (iix[1] < nrows ? iix[1] : nrows); for (uint32_t i = *iix; i < k; ++i) setBit(i, val[i]); } else if (*iix+ibis::bitvector::bitsPerLiteral() < nrows) { // a list of indices for (uint32_t i = 0; i < nind; ++i) { uint32_t k = iix[i]; setBit(k, val[k]); } } else { for (uint32_t i = 0; i < nind; ++i) { uint32_t k = iix[i]; if (k < nrows) setBit(k, val[k]); } } ++iset; nind = iset.nIndices(); if (*iix >= nrows) nind = 0; } // while (nind) break;} case ibis::SHORT: {// signed short int array_t<int16_t> val; if (! fnm.empty()) ierr = ibis::fileManager::instance().getFile(fnm.c_str(), val); else ierr = col->getValuesArray(&val); if (ierr < 0 || val.empty()) { LOGGER(ibis::gVerbose > 0) << "Warning -- sbiad::construct2 failed to retrieve any value"; break; } if (val.size() > mask.size()) { col->logWarning("sbiad::construct", "the data file \"%s\" " "contains more elements (%lu) then expected " "(%lu)", fnm.c_str(), static_cast<long unsigned>(val.size()), static_cast<long unsigned>(mask.size())); mask.adjustSize(nrows, nrows); } ibis::bitvector::indexSet iset = mask.firstIndexSet(); uint32_t nind = iset.nIndices(); const ibis::bitvector::word_t *iix = iset.indices(); while (nind) { if (iset.isRange()) { // a range uint32_t k = (iix[1] < nrows ? iix[1] : nrows); for (uint32_t i = *iix; i < k; ++i) setBit(i, val[i]); } else if (*iix+ibis::bitvector::bitsPerLiteral() < nrows) { // a list of indices for (uint32_t i = 0; i < nind; ++i) { uint32_t k = iix[i]; setBit(k, val[k]); } } else { for (uint32_t i = 0; i < nind; ++i) { uint32_t k = iix[i]; if (k < nrows) setBit(k, val[k]); } } ++iset; nind = iset.nIndices(); if (*iix >= nrows) nind = 0; } // while (nind) break;} case ibis::UBYTE: {// unsigned char array_t<unsigned char> val; if (! fnm.empty()) ierr = ibis::fileManager::instance().getFile(fnm.c_str(), val); else ierr = col->getValuesArray(&val); if (ierr < 0 || val.empty()) { LOGGER(ibis::gVerbose > 0) << "Warning -- sbiad::construct2 failed to retrieve any value"; break; } if (val.size() > mask.size()) { col->logWarning("sbiad::construct", "the data file \"%s\" " "contains more elements (%lu) then expected " "(%lu)", fnm.c_str(), static_cast<long unsigned>(val.size()), static_cast<long unsigned>(mask.size())); mask.adjustSize(nrows, nrows); } ibis::bitvector::indexSet iset = mask.firstIndexSet(); uint32_t nind = iset.nIndices(); const ibis::bitvector::word_t *iix = iset.indices(); while (nind) { if (iset.isRange()) { // a range uint32_t k = (iix[1] < nrows ? iix[1] : nrows); for (uint32_t i = *iix; i < k; ++i) setBit(i, val[i]); } else if (*iix+ibis::bitvector::bitsPerLiteral() < nrows) { // a list of indices for (uint32_t i = 0; i < nind; ++i) { uint32_t k = iix[i]; setBit(k, val[k]); } } else { for (uint32_t i = 0; i < nind; ++i) { uint32_t k = iix[i]; if (k < nrows) setBit(k, val[k]); } } ++iset; nind = iset.nIndices(); if (*iix >= nrows) nind = 0; } // while (nind) break;} case ibis::BYTE: {// signed char array_t<signed char> val; if (! fnm.empty()) ierr = ibis::fileManager::instance().getFile(fnm.c_str(), val); else ierr = col->getValuesArray(&val); if (ierr < 0 || val.empty()) { LOGGER(ibis::gVerbose > 0) << "Warning -- sbiad::construct2 failed to retrieve any value"; break; } if (val.size() > mask.size()) { col->logWarning("sbiad::construct", "the data file \"%s\" " "contains more elements (%lu) then expected " "(%lu)", fnm.c_str(), static_cast<long unsigned>(val.size()), static_cast<long unsigned>(mask.size())); mask.adjustSize(nrows, nrows); } ibis::bitvector::indexSet iset = mask.firstIndexSet(); uint32_t nind = iset.nIndices(); const ibis::bitvector::word_t *iix = iset.indices(); while (nind) { if (iset.isRange()) { // a range uint32_t k = (iix[1] < nrows ? iix[1] : nrows); for (uint32_t i = *iix; i < k; ++i) setBit(i, val[i]); } else if (*iix+ibis::bitvector::bitsPerLiteral() < nrows) { // a list of indices for (uint32_t i = 0; i < nind; ++i) { uint32_t k = iix[i]; setBit(k, val[k]); } } else { for (uint32_t i = 0; i < nind; ++i) { uint32_t k = iix[i]; if (k < nrows) setBit(k, val[k]); } } ++iset; nind = iset.nIndices(); if (*iix >= nrows) nind = 0; } // while (nind) break;} case ibis::FLOAT: {// (4-byte) floating-point values array_t<float> val; if (! fnm.empty()) ierr = ibis::fileManager::instance().getFile(fnm.c_str(), val); else ierr = col->getValuesArray(&val); if (ierr < 0 || val.empty()) { LOGGER(ibis::gVerbose > 0) << "Warning -- sbiad::construct2 failed to retrieve any value"; break; } if (val.size() > mask.size()) { col->logWarning("sbiad::construct", "the data file \"%s\" " "contains more elements (%lu) then expected " "(%lu)", fnm.c_str(), static_cast<long unsigned>(val.size()), static_cast<long unsigned>(mask.size())); mask.adjustSize(nrows, nrows); } ibis::bitvector::indexSet iset = mask.firstIndexSet(); uint32_t nind = iset.nIndices(); const ibis::bitvector::word_t *iix = iset.indices(); while (nind) { if (iset.isRange()) { // a range uint32_t k = (iix[1] < nrows ? iix[1] : nrows); for (uint32_t i = *iix; i < k; ++i) setBit(i, val[i]); } else if (*iix+ibis::bitvector::bitsPerLiteral() < nrows) { // a list of indices for (uint32_t i = 0; i < nind; ++i) { uint32_t k = iix[i]; setBit(k, val[k]); } } else { for (uint32_t i = 0; i < nind; ++i) { uint32_t k = iix[i]; if (k < nrows) setBit(k, val[k]); } } ++iset; nind = iset.nIndices(); if (*iix >= nrows) nind = 0; } // while (nind) break;} case ibis::DOUBLE: {// (8-byte) floating-point values array_t<double> val; if (! fnm.empty()) ierr = ibis::fileManager::instance().getFile(fnm.c_str(), val); else ierr = col->getValuesArray(&val); if (ierr < 0 || val.empty()) { LOGGER(ibis::gVerbose > 0) << "Warning -- sbiad::construct2 failed to retrieve any value"; break; } if (val.size() > mask.size()) { col->logWarning("sbiad::construct", "the data file \"%s\" " "contains more elements (%lu) then expected " "(%lu)", fnm.c_str(), static_cast<long unsigned>(val.size()), static_cast<long unsigned>(mask.size())); mask.adjustSize(nrows, nrows); } ibis::bitvector::indexSet iset = mask.firstIndexSet(); uint32_t nind = iset.nIndices(); const ibis::bitvector::word_t *iix = iset.indices(); while (nind) { if (iset.isRange()) { // a range uint32_t k = (iix[1] < nrows ? iix[1] : nrows); for (uint32_t i = *iix; i < k; ++i) setBit(i, val[i]); } else if (*iix+ibis::bitvector::bitsPerLiteral() < nrows) { // a list of indices for (uint32_t i = 0; i < nind; ++i) { uint32_t k = iix[i]; setBit(k, val[k]); } } else { for (uint32_t i = 0; i < nind; ++i) { uint32_t k = iix[i]; if (k < nrows) setBit(k, val[k]); } } ++iset; nind = iset.nIndices(); if (*iix >= nrows) nind = 0; } // while (nind) break;} case ibis::CATEGORY: // no need for a separate index col->logWarning("sbiad::ctor", "no need for another index"); return; default: col->logWarning("sbiad::ctor", "failed to create bit sbiad index " "for column type %s", ibis::TYPESTRING[(int)col->type()]); return; } // make sure all bit vectors are the same size for (uint32_t i = 0; i < nobs; ++i) { bits[i]->adjustSize(0, nrows); } // sum up the bitvectors according to interval-encoding array_t<bitvector*> beq; beq.swap(bits); try { uint32_t ke = 0; bits.clear(); for (uint32_t i = 0; i < nb; ++i) { if (bases[i] > 2) { nobs = (bases[i] - 1) / 2; bits.push_back(new ibis::bitvector); bits.back()->copy(*(beq[ke])); if (nobs > 64) bits.back()->decompress(); for (uint32_t j = ke+1; j <= ke+nobs; ++j) *(bits.back()) |= *(beq[j]); bits.back()->compress(); for (uint32_t j = 1; j < bases[i]-nobs; ++j) { bits.push_back(*(bits.back()) - *(beq[ke+j-1])); *(bits.back()) |= *(beq[ke+j+nobs]); bits.back()->compress(); } for (uint32_t j = ke; j < ke+bases[i]; ++j) { delete beq[j]; beq[j] = 0; } } else { bits.push_back(beq[ke]); if (bases[i] > 1) { delete beq[ke+1]; beq[ke+1] = 0; } } ke += bases[i]; } } catch (...) { LOGGER(ibis::gVerbose > 1) << "Warning -- column::[" << col->name() << "]::construct2 encountered an exception while converting " "to inverval encoding, cleaning up ..."; for (uint32_t i = 0; i < beq.size(); ++ i) delete beq[i]; throw; } beq.clear(); optionalUnpack(bits, col->indexSpec()); // write out the current content if (ibis::gVerbose > 8) { ibis::util::logger lg; print(lg()); } } // ibis::sbiad::construct2 // a simple function to test the speed of the bitvector operations void ibis::sbiad::speedTest(std::ostream& out) const { if (nrows == 0) return; uint32_t i, nloops = 1000000000 / nrows; if (nloops < 2) nloops = 2; ibis::horometer timer; col->logMessage("sbiad::speedTest", "testing the speed of operator -"); activate(); // need all bitvectors for (i = 0; i < bits.size()-1; ++i) { ibis::bitvector* tmp; tmp = *(bits[i+1]) & *(bits[i]); delete tmp; timer.start(); for (uint32_t j=0; j<nloops; ++j) { tmp = *(bits[i+1]) & *(bits[i]); delete tmp; } timer.stop(); { ibis::util::ioLock lock; out << bits[i]->size() << " " << static_cast<double>(bits[i]->bytes() + bits[i+1]->bytes()) * 4.0 / static_cast<double>(bits[i]->size()) << " " << bits[i]->cnt() << " " << bits[i+1]->cnt() << " " << timer.realTime() / nloops << "\n"; } } } // ibis::sbiad::speedTest // the printing function void ibis::sbiad::print(std::ostream& out) const { out << "index(multicomponent interval ncomp=" << bases.size() << ") for " << col->partition()->name() << '.' << col->name() << " contains " << bits.size() << " bitvectors for " << nrows << " objects with " << vals.size() << " distinct values\nThe base sizes: "; for (uint32_t i=0; i<bases.size(); ++i) out << bases[i] << ' '; const uint32_t nobs = bits.size(); out << "\nbitvector information (number of set bits, number of " "bytes)\n"; for (uint32_t i=0; i<nobs; ++i) { if (bits[i]) { out << i << '\t' << bits[i]->cnt() << '\t' << bits[i]->bytes() << "\n"; } } if (ibis::gVerbose > 6) { // also print the list of distinct values out << "distinct values, number of apparences\n"; for (uint32_t i=0; i<vals.size(); ++i) { out.precision(12); out << vals[i] << '\t' << cnts[i] << "\n"; } } out << "\n"; } // ibis::sbiad::print // create index based data in dt -- have to start from data directly long ibis::sbiad::append(const char* dt, const char* df, uint32_t nnew) { const uint32_t nb = bases.size(); clear(); // clear the current content construct2(dt, nb); // scan data twice to build the new index //write(dt); // write out the new content return nnew; } // ibis::sbiad::append // compute the bitvector that represents the answer for x = b void ibis::sbiad::evalEQ(ibis::bitvector& res, uint32_t b) const { #if DEBUG+0 > 0 || _DEBUG+0 > 0 LOGGER(ibis::gVerbose >= 0) << "DEBUG -- sbiad::evalEQ(" << b << ")..."; #endif if (b >= vals.size()) { res.set(0, nrows); } else { uint32_t nb2; uint32_t offset = 0; res.set(1, nrows); for (uint32_t i = 0; i < bases.size(); ++i) { uint32_t k = b % bases[i]; if (bases[i] > 2) { ibis::bitvector *tmp; nb2 = (bases[i]-1) / 2; if (k+1+nb2 < bases[i]) { if (bits[offset+k] == 0) activate(offset+k); if (bits[offset+k]) { if (bits[offset+k+1] == 0) activate(offset+k+1); if (bits[offset+k+1]) tmp = *(bits[offset+k]) - *(bits[offset+k+1]); else tmp = new ibis::bitvector(*(bits[offset+k])); } else { tmp = 0; } } else if (k > nb2) { if (bits[offset+k-nb2] == 0) activate(offset+k-nb2); if (bits[offset+k-nb2]) { if (bits[offset+k-nb2-1] == 0) activate(offset+k-nb2-1); if (bits[offset+k-nb2-1]) tmp = *(bits[offset+k-nb2]) - *(bits[offset+k-nb2-1]); else tmp = new ibis::bitvector(*(bits[offset+k-nb2])); } else { tmp = 0; } } else { if (bits[offset] == 0) activate(offset); if (bits[offset+k] == 0) activate(offset+k); if (bits[offset] && bits[offset+k]) tmp = *(bits[offset]) & *(bits[offset+k]); else tmp = 0; } if (tmp) res &= *tmp; else res.set(0, res.size()); delete tmp; offset += bases[i] - nb2; } else { if (bits[offset] == 0) activate(offset); if (0 == k) { if (bits[offset]) res &= *(bits[offset]); else res.set(0, res.size()); } else if (bits[offset]) { res -= *(bits[offset]); } ++ offset; } b /= bases[i]; } } } // evalEQ // compute the bitvector that is the answer for the query x <= b void ibis::sbiad::evalLE(ibis::bitvector& res, uint32_t b) const { #if DEBUG+0 > 0 || _DEBUG+0 > 0 LOGGER(ibis::gVerbose >= 0) << "DEBUG -- sbiad::evalLE(" << b << ")..."; #endif if (b+1 >= vals.size()) { res.set(1, nrows); } else { uint32_t k, nb2; uint32_t i = 0; // index into components uint32_t offset = 0; // skip till the first component that isn't the maximum value while (i < bases.size() && b % bases[i] == bases[i]-1) { offset += (bases[i]>2 ? bases[i]-(bases[i]-1)/2 : 1); b /= bases[i]; ++ i; } // copy the first non-maximum component if (i < bases.size()) { k = b % bases[i]; if (bits[offset] == 0) activate(offset); if (bits[offset]) res.copy(*(bits[offset])); else res.set(0, nrows); if (bases[i] > 2) { nb2 = (bases[i]-1)/2; if (k < nb2) { const uint32_t j = offset+k+1; if (bits[j] == 0) activate(j); if (bits[j]) res -= *(bits[j]); } else if (k > nb2) { const uint32_t j = offset+k-nb2; if (bits[j] == 0) activate(j); if (bits[j]) res |= *(bits[j]); } offset += bases[i] - nb2; } else { if (k != 0) res.flip(); ++ offset; } b /= bases[i]; } else { res.set(1, nrows); } ++ i; // deal with the remaining components while (i < bases.size()) { k = b % bases[i]; nb2 = (bases[i] - 1) / 2; if (bases[i] > 2) { if (k < nb2) { ibis::bitvector* tmp; if (bits[offset+k] == 0) activate(offset+k); if (bits[offset+k]) res &= *(bits[offset+k]); else res.set(0, res.size()); if (bits[offset+k+1] == 0) activate(offset+k+1); if (bits[offset+k+1]) res -= *(bits[offset+k+1]); if (k > 0) { if (bits[offset] == 0) activate(offset); if (bits[offset]) { if (bits[offset+k]) { tmp = *(bits[offset]) - *(bits[offset+k]); res |= *tmp; delete tmp; } else { res |= *(bits[offset]); } } } } else if (k > nb2) { if (k+1 < bases[i]) { if (bits[offset+k-nb2] == 0) activate(offset+k-nb2); if (bits[offset+k-nb2]) res &= *(bits[offset+k-nb2]); else res.set(0, res.size()); } if (bits[offset+k-nb2-1] == 0) activate(offset+k-nb2-1); if (bits[offset+k-nb2-1]) res |= *(bits[offset+k-nb2-1]); if (k > nb2+1) { if (bits[offset] == 0) activate(offset); if (bits[offset]) res |= *(bits[offset]); } } else { // k = nb2 if (bits[offset] == 0) activate(offset); if (bits[offset]) { if (bits[offset+k] == 0) activate(offset+k); if (bits[offset+k]) { res &= *(bits[offset]); ibis::bitvector* tmp = *(bits[offset]) - *(bits[offset+k]); res |= *tmp; delete tmp; } else { res.copy(*(bits[offset])); } } else { res.set(0, res.size()); } } offset += (bases[i] - nb2); } else { if (bits[offset] == 0) activate(offset); if (bits[offset]) { if (k == 0) res &= *(bits[offset]); else res |= *(bits[offset]); } else if (k == 0) { res.set(0, res.size()); } ++ offset; } b /= bases[i]; ++ i; } } } // evalLE // compute the bitvector that answers the query b0 < x <= b1 void ibis::sbiad::evalLL(ibis::bitvector& res, uint32_t b0, uint32_t b1) const { #if DEBUG+0 > 0 || _DEBUG+0 > 0 LOGGER(ibis::gVerbose >= 0) << "DEBUG -- sbiad::evalLL(" << b0 << ", " << b1 << ")..."; #endif if (b0 >= b1) { // no hit res.set(0, nrows); } else if (b1+1 >= vals.size()) { // x > b0 evalLE(res, b0); res.flip(); } else { // the intended general case // res temporarily stores the result of x <= b1 ibis::bitvector low; // x <= b0 uint32_t k0, k1, nb2; uint32_t i = 0; uint32_t offset = 0; // skip till the first component that isn't the maximum value while (i < bases.size()) { k0 = b0 % bases[i]; k1 = b1 % bases[i]; if (k0 == bases[i]-1 && k1 == bases[i]-1) { offset += (bases[i]>2 ? bases[i] - (bases[i]-1)/2 : 1); b0 /= bases[i]; b1 /= bases[i]; ++ i; } else { break; } } // the first non-maximum component if (i < bases.size()) { k0 = b0 % bases[i]; k1 = b1 % bases[i]; if (bases[i] > 2) { nb2 = (bases[i]-1) / 2; if (k0+1 < bases[i]) { if (bits[offset] == 0) activate(offset); if (bits[offset]) low.copy(*(bits[offset])); else low.set(0, nrows); if (k0 < nb2) { if (bits[offset+k0+1] == 0) activate(offset+k0+1); if (bits[offset+k0+1] != 0) low -= *(bits[offset+k0+1]); } else if (k0 > nb2) { if (bits[offset+k0-nb2] == 0) activate(offset+k0-nb2); if (bits[offset+k0-nb2] != 0) low |= *(bits[offset+k0-nb2]); } #if DEBUG+0 > 0 || _DEBUG+0 > 0 if (ibis::gVerbose > 30 || (low.bytes() < (1U << ibis::gVerbose))) { LOGGER(ibis::gVerbose >= 0) << "DEBUG -- sbiad::evalLL: low " "(component[" << i << "] <= " << k0 << ") " << low; } #endif } else { low.set(1, nrows); } if (k1+1 < bases[i]) { if (bits[offset] == 0) activate(offset); if (bits[offset]) res.copy(*(bits[offset])); else res.set(0, nrows); if (k1 < nb2) { if (bits[offset+k1+1] == 0) activate(offset+k1+1); if (bits[offset+k1+1] != 0) res -= *(bits[offset+k1+1]); } else if (k1 > nb2) { if (bits[offset+k1-nb2] == 0) activate(offset+k1-nb2); if (bits[offset+k1-nb2] != 0) res |= *(bits[offset+k1-nb2]); } #if DEBUG+0 > 0 || _DEBUG+0 > 0 if (ibis::gVerbose > 30 || (res.bytes() < (1U << ibis::gVerbose))) { LOGGER(ibis::gVerbose >= 0) << "DEBUG -- sbiad::evalLL: high " "(component[" << i << "] <= " << k1 << ") " << res; } #endif } else { res.set(1, nrows); } offset += bases[i] - nb2; } else { // bases[i] >= 2 if (k0 == 0) { if (bits[offset] == 0) activate(offset); if (bits[offset] != 0) low = *(bits[offset]); else low.set(0, nrows); } else { low.set(1, nrows); } if (k1 == 0) { if (bits[offset] == 0) activate(offset); if (bits[offset] != 0) res = *(bits[offset]); else res.set(0, nrows); } else { res.set(1, nrows); } ++ offset; } b0 /= bases[i]; b1 /= bases[i]; } else { res.set(0, nrows); } ++ i; // deal with the remaining components while (i < bases.size()) { ibis::bitvector* tmp; if (b1 > b0) { // low and res has to be separated k0 = b0 % bases[i]; k1 = b1 % bases[i]; b0 /= bases[i]; b1 /= bases[i]; if (bases[i] > 2) { nb2 = (bases[i] - 1) / 2; // update low according to k0 if (k0+nb2+1 < bases[i]) { if (bits[offset+k0] == 0) activate(offset+k0); if (bits[offset+k0] != 0) low &= *(bits[offset+k0]); else low.set(0, low.size()); if (bits[offset+k0+1] == 0) activate(offset+k0+1); if (bits[offset+k0+1] != 0) low -= *(bits[offset+k0+1]); if (k0 > 0) { if (bits[offset] == 0) activate(offset); if (bits[offset] != 0) { if (bits[offset+k0] == 0) activate(offset+k0); if (bits[offset+k0] != 0) { tmp = *(bits[offset]) - *(bits[offset+k0]); low |= *tmp; delete tmp; } } else { low |= *(bits[offset]); } } } else if (k0 > nb2) { if (k0+1 < bases[i]) { if (bits[offset+k0-nb2] == 0) activate(offset+k0-nb2); if (bits[offset+k0-nb2] != 0) low &= *(bits[offset+k0-nb2]); else low.set(0, low.size()); } if (bits[offset+k0-nb2-1] == 0) activate(offset+k0-nb2-1); if (bits[offset+k0-nb2-1] != 0) low |= *(bits[offset+k0-nb2-1]); if (k0 > nb2+1) { if (bits[offset] == 0) activate(offset); if (bits[offset] != 0) low |= *(bits[offset]); } } else { // k0 = nb2 // res &= (bits[offset] & bits[offset+k0]) // res |= (bits[offset] - bits[offset+k0]) if (bits[offset] == 0) activate(offset); if (bits[offset] != 0) { if (bits[offset+k0] == 0) activate(offset+k0); if (bits[offset+k0]) { low &= *(bits[offset]); tmp = *(bits[offset]) - *(bits[offset+k0]); low |= *tmp; delete tmp; } else { low.copy(*(bits[offset])); } } else { low.set(0, low.size()); } } #if DEBUG+0 > 0 || _DEBUG+0 > 0 if (ibis::gVerbose > 30 || (low.bytes() < (1U << ibis::gVerbose))) { LOGGER(ibis::gVerbose >= 0) << "DEBUG -- sbiad::evalLL: low " "(component[" << i << "] <= " << k0 << ") " << low; } #endif // update res according to k1 if (k1+nb2+1 < bases[i]) { if (bits[offset+k1] == 0) activate(offset+k1); if (bits[offset+k1] != 0) res &= *(bits[offset+k1]); else res.set(0, res.size()); if (bits[offset+k1+1] == 0) activate(offset+k1+1); if (bits[offset+k1+1] != 0) res -= *(bits[offset+k1+1]); if (k1 > 0) { if (bits[offset] == 0) activate(offset); if (bits[offset]) { if (bits[offset+k1]) { tmp = *(bits[offset]) - *(bits[offset+k1]); res |= *tmp; delete tmp; } else { res |= *(bits[offset]); } } } } else if (k1 > nb2) { if (k1+1 < bases[i]) { if (bits[offset+k1-nb2] == 0) activate(offset+k1-nb2); if (bits[offset+k1-nb2] != 0) res &= *(bits[offset+k1-nb2]); else res.set(0, res.size()); } if (bits[offset+k1-nb2-1] == 0) activate(offset+k1-nb2-1); if (bits[offset+k1-nb2-1] != 0) res |= *(bits[offset+k1-nb2-1]); if (k1 > nb2+1) { if (bits[offset] == 0) activate(offset); if (bits[offset] != 0) res |= *(bits[offset]); } } else { // k1 = nb2 if (bits[offset] == 0) activate(offset); if (bits[offset] != 0) { if (bits[offset+k1] == 0) activate(offset+k1); if (bits[offset+k1] != 0) { res &= *(bits[offset]); tmp = *(bits[offset]) - *(bits[offset+k1]); res |= *tmp; delete tmp; } else { res.copy(*bits[offset]); } } else { res.set(0, res.size()); } } #if DEBUG+0 > 0 || _DEBUG+0 > 0 if (ibis::gVerbose > 30 || (res.bytes() < (1U << ibis::gVerbose))) { LOGGER(ibis::gVerbose >= 0) << "DEBUG -- sbiad::evalLL: high " "(component[" << i << "] <= " << k1 << ") " << res; } #endif offset += (bases[i] - nb2); } else { // bases[i] <= 2 if (bits[offset] == 0) activate(offset); if (bits[offset]) { if (k0 == 0) low &= *(bits[offset]); else low |= *(bits[offset]); if (k1 == 0) res &= *(bits[offset]); else res |= *(bits[offset]); } else { if (k0 == 0) low.set(0, low.size()); if (k1 == 0) res.set(0, low.size()); } } } else { // the more significant components are the same res -= low; low.clear(); // no longer need low while (i < bases.size()) { k1 = b1 % bases[i]; if (bases[i] > 2) { nb2 = (bases[i]-1) / 2; if (k1+1+nb2 < bases[i]) { if (bits[offset+k1] == 0) activate(offset+k1); if (bits[offset+k1] != 0) { if (bits[offset+k1+1] == 0) activate(offset+k1+1); if (bits[offset+k1+1] != 0) tmp = *(bits[offset+k1]) - *(bits[offset+k1+1]); else tmp = new ibis::bitvector(*(bits[offset+k1])); } else { tmp = 0; } } else if (k1 > nb2) { if (bits[offset+k1-nb2] == 0) activate(offset+k1-nb2); if (bits[offset+k1-nb2] != 0) { if (bits[offset+k1-nb2-1] == 0) activate(offset+k1-nb2-1); if (bits[offset+k1-nb2-1] != 0) tmp = *(bits[offset+k1-nb2]) - *(bits[offset+k1-nb2-1]); else tmp = new ibis::bitvector (*(bits[offset+k1-nb2])); } else { tmp = 0; } } else { // k1 = nb2 if (bits[offset] == 0) activate(offset); if (bits[offset] != 0) { if (bits[offset+k1] == 0) activate(offset+k1); if (bits[offset+k1] != 0) tmp = *(bits[offset]) & *(bits[offset+k1]); else tmp = new ibis::bitvector(*(bits[offset])); } else { tmp = 0; } } if (tmp) { res &= *tmp; delete tmp; } else { res.set(0, res.size()); } offset += bases[i] - nb2; } else { // bases[i] <= 2 if (bits[offset] == 0) activate(offset); if (bits[offset] != 0) { if (k1 == 0) res &= *(bits[offset]); else res -= *(bits[offset]); } else if (k1 == 0) { res.set(0, res.size()); } ++ offset; } #if DEBUG+0 > 0 || _DEBUG+0 > 0 if (ibis::gVerbose > 30 || (res.bytes() < (1U << ibis::gVerbose))) { LOGGER(ibis::gVerbose >= 0) << "DEBUG -- sbiad::evalLL: res " "(component[" << i << "] <= " << k1 << ") " << res; } #endif b1 /= bases[i]; ++ i; } // while (i < bases.size()) } ++ i; } if (low.size() == res.size()) { // subtract low from res res -= low; low.clear(); } } } // evalLL // Evaluate the query expression long ibis::sbiad::evaluate(const ibis::qContinuousRange& expr, ibis::bitvector& lower) const { if (bits.empty()) { lower.set(0, nrows); return 0; } // values in the range [hit0, hit1) satisfy the query expression uint32_t hit0, hit1; locate(expr, hit0, hit1); // actually accumulate the bits in the range [hit0, hit1) if (hit1 <= hit0) { lower.set(0, nrows); } else if (hit0+1 == hit1) { // equal to one single value evalEQ(lower, hit0); } else if (hit0 == 0) { // < hit1 evalLE(lower, hit1-1); } else if (hit1 == vals.size()) { // >= hit0 (as NOT (<= hit0-1)) evalLE(lower, hit0-1); lower.flip(); } else { // need to go through most bitvectors four times evalLL(lower, hit0-1, hit1-1); // (hit0-1, hit1-1] } return lower.cnt(); } // ibis::sbiad::evaluate // Evaluate a set of discrete range conditions. long ibis::sbiad::evaluate(const ibis::qDiscreteRange& expr, ibis::bitvector& lower) const { const ibis::array_t<double>& varr = expr.getValues(); lower.set(0, nrows); for (unsigned i = 0; i < varr.size(); ++ i) { unsigned int itmp = locate(varr[i]); if (itmp > 0 && vals[itmp-1] == varr[i]) { -- itmp; ibis::bitvector tmp; evalEQ(tmp, itmp); if (tmp.size() == lower.size()) lower |= tmp; } } return lower.cnt(); } // ibis::sbiad::evaluate
27.310766
79
0.538201
nporsche
e4dac40bfd168b6f7794ccb6182f0e80bc9147fa
876
cpp
C++
src/libutils/platform/endian_utils.cpp
nkming2/libutils
e044c8f1265aad50092e008d7706142c3029096a
[ "MIT" ]
null
null
null
src/libutils/platform/endian_utils.cpp
nkming2/libutils
e044c8f1265aad50092e008d7706142c3029096a
[ "MIT" ]
1
2015-03-10T06:29:14.000Z
2015-03-10T06:29:14.000Z
src/libutils/platform/endian_utils.cpp
nkming2/libutils
e044c8f1265aad50092e008d7706142c3029096a
[ "MIT" ]
null
null
null
/* * endian_utils.cpp * * Author: Ming Tsang * Copyright (c) 2014 Ming Tsang * Refer to LICENSE for details */ #include <cstdint> #include <algorithm> #include "libutils/platform/endian_utils.h" #include "libutils/type/misc.h" namespace utils { namespace platform { namespace { bool IsBigEndian_() { const uint16_t bom = 0xFFFE; return (reinterpret_cast<const Byte*>(&bom)[0] == 0xFF); } } bool EndianUtils::IsBigEndian() { static const bool is_be = IsBigEndian_(); return is_be; } uint16_t EndianUtils::Translate16(const uint16_t from) { uint16_t to = from; Byte *bytes = reinterpret_cast<Byte*>(&to); std::swap(bytes[0], bytes[1]); return to; } uint32_t EndianUtils::Translate32(const uint32_t from) { uint32_t to = from; Byte *bytes = reinterpret_cast<Byte*>(&to); std::swap(bytes[0], bytes[3]); std::swap(bytes[1], bytes[2]); return to; } } }
15.642857
57
0.696347
nkming2
e4db8b780e9091e8fa9ca4723add404eaa8786bd
5,343
cpp
C++
simulation.cpp
jayvalentine/evosim
05c01f38314fb8fb556cfc1736530fff5ec0eb1c
[ "MIT" ]
null
null
null
simulation.cpp
jayvalentine/evosim
05c01f38314fb8fb556cfc1736530fff5ec0eb1c
[ "MIT" ]
null
null
null
simulation.cpp
jayvalentine/evosim
05c01f38314fb8fb556cfc1736530fff5ec0eb1c
[ "MIT" ]
null
null
null
#include "simulation.h" Simulation::Simulation(World * w, int minCreatures, unsigned int rate) { creatures = std::vector<std::shared_ptr<Creature>>(); world = w; minimumCreatures = minCreatures; stepRate = rate; steps = 0; } void Simulation::RunFor(unsigned long seconds) { for (unsigned long s = 0; s < seconds; s++) { // Number of steps per second. for (unsigned long r = 0; r < stepRate; r++) { Step(); } } } void Simulation::AddInitialCreature(Point initialPosition) { // Create a new neural network for the creature. NeuralNetwork * net = new NeuralNetwork(13, 4, 0); // Initialise the network with 3 random synapses. for (int i = 0; i < 3; i++) { Evolution::AddRandomSynapse(net); } // Create the creature's attributes. Creature::Attributes attr; attr.red = Random::UInt(0, 255); attr.green = Random::UInt(0, 255); attr.blue = Random::UInt(0, 255); attr.maxSpeed = Random::Double(1, 50); attr.maxSize = Random::Double(25, 100); attr.lifespan = Random::Double(1000, 2500); attr.sightDistance = Random::Double(50, 120); attr.eyeRotation = Random::Double(0, M_PI / 2); if (world->GetTile(initialPosition)->Type() == World::TileType::LAND) attr.breathing = Creature::BreathingType::LAND; else attr.breathing = Creature::BreathingType::WATER; // Create a new shared_ptr for the creature; Creature * creature = new Creature(world, initialPosition, net, attr, 0, stepRate); AddCreature(creature); } void Simulation::AddOffspringCreature(Creature * creature) { // Create a new neural network for the creature and copy the synapses of the old one. NeuralNetwork * net = new NeuralNetwork(13, 4, creature->Net()->Hidden().size()); for (auto s : creature->Net()->Synapses()) { net->AddSynapse(s->Start(), s->End(), s->Weight()); } // Mutate the network. Evolution::Mutate(net); // Clone the creature's attributes and mutate a bit. Creature::Attributes attr = creature->GetAttributes(); // Color. attr.red += Random::Int(-10, 10); attr.green += Random::Int(-10, 10); attr.blue += Random::Int(-10, 10); // Cap these at 0-255. if (attr.red > 255) attr.red = 255; if (attr.green > 255) attr.green = 255; if (attr.blue > 255) attr.blue = 255; attr.maxSpeed += Random::Double(-5, 5); if (attr.maxSpeed < 1) attr.maxSpeed = 1; attr.maxSize += Random::Double(-10, 10); if (attr.maxSize < 25) attr.maxSize = 25; // Creature inherits lifespan directly. attr.sightDistance += Random::Double(-5, 5); if (attr.sightDistance < 0) attr.sightDistance = 0; else if (attr.sightDistance > 200) attr.sightDistance = 200; attr.eyeRotation += Random::Double(-0.10, 0.10); if (attr.eyeRotation < 0.05) attr.eyeRotation = 0.05; else if (attr.eyeRotation > (M_PI / 2)) attr.eyeRotation = M_PI / 2; // Small chance to become amphibious. if (Random::Double(0, 1) < 0.00001) { attr.breathing = Creature::BreathingType::BOTH; } // Create a new shared_ptr for the creature Creature * offspring = new Creature(world, creature->GetPosition(), net, attr, creature->Generation() + 1, stepRate); AddCreature(offspring); } void Simulation::AddCreature(const Creature * creature) { // Create a shared_ptr and add to the vector. std::shared_ptr<Creature> ptr = std::make_shared<Creature>(*creature); creatures.push_back(ptr); } void Simulation::Step(void) { world->Step(stepRate); for (int i = 0; i < creatures.size(); i++) { Creature::StepState state = creatures[i]->Step(stepRate); if (state == Creature::StepState::GIVE_BIRTH) { AddOffspringCreature(creatures[i].get()); } } // Remove any creatures which have died. std::vector<int> deadIndexes = std::vector<int>(); for (int i = 0; i < creatures.size(); i++) { if (creatures[i]->Dead()) { // What comes from the earth, goes back to it. // Dead creatures add some food to their environment. double foodToAdd = std::pow(creatures[i]->GetSize(), 3); if (foodToAdd < 0) foodToAdd = 0; world->GetTile(creatures[i]->GetPosition())->IncreaseFood(foodToAdd); deadIndexes.push_back(i); } } // Starting from the back of the list we've just constructed, // remove the dead creatures. while (deadIndexes.size() > 0) { int index = deadIndexes[deadIndexes.size() - 1]; deadIndexes.pop_back(); creatures[index].reset(); creatures.erase(creatures.begin() + index); } // If there are fewer creatures than the minimum, add creatures to pad out. int creaturesToAdd = (minimumCreatures - creatures.size()) + (minimumCreatures / 2); for (int i = 0; i < creaturesToAdd; i++) { AddInitialCreature(Point(Random::Double(0, world->Width()), Random::Double(0, world->Height()))); } steps++; } unsigned int Simulation::Steps(void) { return steps; } unsigned int Simulation::SimulationTime(void) { // Divide the number of steps by the rate to get the time in seconds. return steps / stepRate; }
28.420213
121
0.620625
jayvalentine
e4dc1de71d07d72be3859246a17fed274a348476
1,317
hpp
C++
swizzle/lexer/FileInfo.hpp
SenorAgosto/Swizzle
52c221de9fa293b0006f07a41b140d2afcc1a9ed
[ "BSD-4-Clause" ]
null
null
null
swizzle/lexer/FileInfo.hpp
SenorAgosto/Swizzle
52c221de9fa293b0006f07a41b140d2afcc1a9ed
[ "BSD-4-Clause" ]
null
null
null
swizzle/lexer/FileInfo.hpp
SenorAgosto/Swizzle
52c221de9fa293b0006f07a41b140d2afcc1a9ed
[ "BSD-4-Clause" ]
null
null
null
#pragma once #include <swizzle/lexer/LineInfo.hpp> #include <cstddef> #include <string> namespace swizzle { namespace lexer { class Token; }} namespace swizzle { namespace lexer { // Information about where a token starts and ends class FileInfo { public: FileInfo(); FileInfo(const std::string& filename); FileInfo(const std::string& filename, const LineInfo& start); FileInfo(const std::string& filename, const LineInfo& start, const LineInfo& end); const std::string& filename() const { return filename_; } const LineInfo& end() const { return end_; } LineInfo& end() { return end_; } const LineInfo& start() const { return start_; } LineInfo& start() { return start_; } void incrementLine() { end_.incrementLine(); } void incrementColumn() { end_.incrementColumn(); } void incrementColumnBy(const std::size_t count) { end_.incrementColumnBy(count); } void advanceBy(const char c); void advanceBy(const Token& token); void advanceTo(const FileInfo& info); bool empty() const { return start_ == end_; } private: std::string filename_; LineInfo start_; LineInfo end_; }; }}
27.4375
90
0.607441
SenorAgosto
e4dc392fbb4cfffe7373f1bb1c9b50e02f93b7c8
1,115
cpp
C++
1560f2.cpp
wky32768/Mr.Shua
9c6c7f22c9f80f9af51e9e6e88ea91ac7965fb21
[ "MIT" ]
null
null
null
1560f2.cpp
wky32768/Mr.Shua
9c6c7f22c9f80f9af51e9e6e88ea91ac7965fb21
[ "MIT" ]
null
null
null
1560f2.cpp
wky32768/Mr.Shua
9c6c7f22c9f80f9af51e9e6e88ea91ac7965fb21
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int t,xx,x,k,a[21],cnt; bool vis[105]; int tot() { memset(vis,0,sizeof vis); int n=0; for(int i=cnt;i>=1;i--) { if(vis[a[i]]==0) { vis[a[i]]=1; n++; if(n>k) return 0; } } return 1; } signed main() { cin>>t; while(t--) { cin>>xx>>k; x=xx; cnt=0; while(x) {a[++cnt]=x%10; x/=10;} int now=0; while(tot()==0) { memset(vis,0,sizeof vis); int n=0; for(int i=cnt;i>=1;i--) { if(vis[a[i]]==0) { vis[a[i]]=1; n++; } if(n>k) {now=i;break;} } // cout<<"now="<<now<<'\n'; a[now]++; if(a[now]==10) {a[now]=0;a[now+1]++;} for(int i=now-1;i>=1;i--) a[i]=0; // for(int i=cnt;i>=1;i--) cout<<a[i]; // puts(""); } for(int i=cnt;i>=1;i--) cout<<a[i]; puts(""); } return 0; }
24.23913
51
0.328251
wky32768
e4de0274c235641531abf69e10ca8aad9f9d6bab
17,243
cpp
C++
Source/aiden_geo_tutorial/Private/FoliageCaptureActor.cpp
SquarerFive/cesium-procedural-foliage
428b99d3ad2643b5c491b027ee7110b4e673e117
[ "Apache-2.0" ]
13
2021-07-29T12:33:44.000Z
2022-03-28T08:38:51.000Z
Source/aiden_geo_tutorial/Private/FoliageCaptureActor.cpp
SquarerFive/cesium-procedural-foliage
428b99d3ad2643b5c491b027ee7110b4e673e117
[ "Apache-2.0" ]
3
2021-10-11T15:54:21.000Z
2021-12-19T00:01:21.000Z
Source/aiden_geo_tutorial/Private/FoliageCaptureActor.cpp
SquarerFive/cesium-procedural-foliage
428b99d3ad2643b5c491b027ee7110b4e673e117
[ "Apache-2.0" ]
5
2021-10-07T06:42:10.000Z
2022-03-29T07:51:48.000Z
// Fill out your copyright notice in the Description page of Project Settings. #include "FoliageCaptureActor.h" #include "Kismet/KismetMathLibrary.h" // Sets default values AFoliageCaptureActor::AFoliageCaptureActor() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; } // Called when the game starts or when spawned void AFoliageCaptureActor::BeginPlay() { Super::BeginPlay(); ResetAndCreateHISMComponents(); FCoreDelegates::PreWorldOriginOffset.AddLambda([&](UWorld* World, FIntVector CurrentOrigin, FIntVector NewOrigin) { bIsRebasing = true; WorldOffset = FVector(NewOrigin - CurrentOrigin); }); FCoreDelegates::PostWorldOriginOffset.AddLambda([&](UWorld* World, FIntVector CurrentOrigin, FIntVector NewOrigin) { bIsRebasing = false; WorldOffset = FVector(0.); }); } // Called every frame void AFoliageCaptureActor::Tick(float DeltaTime) { Super::Tick(DeltaTime); if (Ticks > UpdateFoliageAfterNumFrames && !bIsBuilding) { Ticks = 0; int32 ComponentsUpdated = 0; for (TPair<FFoliageGeometryType, TArray<UFoliageHISM*>>& FoliageHISMPair : HISMFoliageMap) { for (UFoliageHISM* FoliageHISM : FoliageHISMPair.Value) { // if (!IsValid(FoliageHISM)) { continue; } if (FoliageHISM->bMarkedForClear) { #if !FOLIAGE_REDUCE_FLICKER_APPROACH_ENABLED FoliageHISM->ClearInstances(); FoliageHISM->bCleared = true; FoliageHISM->bMarkedForClear = false; ComponentsUpdated++; #endif } else if (FoliageHISM->bMarkedForAdd) { #if FOLIAGE_REDUCE_FLICKER_APPROACH_ENABLED FoliageHISM->ClearInstances(); #endif FoliageHISM->PreAllocateInstancesMemory(FoliageHISM->Transforms.Num()); FoliageHISM->AddInstances(FoliageHISM->Transforms, false); FoliageHISM->bMarkedForAdd = false; FoliageHISM->Transforms.Empty(); FoliageHISM->bCleared = false; ComponentsUpdated++; } if (ComponentsUpdated > MaxComponentsToUpdatePerFrame) { break; } } if (ComponentsUpdated > MaxComponentsToUpdatePerFrame) { break; } } if (IsValid(Georeference)) { if (AllISMsMarkedAsCleared() && !bInstancesClearedCalled && IsWaiting()) { OnInstancesCleared(); } } } Ticks++; } void AFoliageCaptureActor::BuildFoliageTransforms(UTextureRenderTarget2D* FoliageDistributionMap, UTextureRenderTarget2D* NormalAndDepthMap, FBox RTWorldBounds) { // Need to check whether the CesiumGeoreference actor and input RTs are valid. if (!IsValid(Georeference)) { UE_LOG(LogTemp, Warning, TEXT("Georeference is invalid! Not spawning in foliage")); return; } if (!IsValid(NormalAndDepthMap) || !IsValid(FoliageDistributionMap)) { UE_LOG(LogTemp, Warning, TEXT("Invaid inputs for FoliageCaptureActor!")); return; } if (FoliageTypes.Num() == 0) { UE_LOG(LogTemp, Warning, TEXT("No foliage types added!")); return; } bIsBuilding = true; // Find the geographic bounds of the RT const glm::dvec3 MinGeographic = Georeference->TransformUnrealToLongitudeLatitudeHeight( glm::dvec3( RTWorldBounds.Min.X, RTWorldBounds.Min.Y, RTWorldBounds.Min.Z )); const glm::dvec3 MaxGeographic = Georeference->TransformUnrealToLongitudeLatitudeHeight( glm::dvec3( RTWorldBounds.Max.X, RTWorldBounds.Max.Y, RTWorldBounds.Max.Z ) ); const glm::dvec4 GeographicExtents2D = glm::dvec4( MinGeographic.x, MinGeographic.y, MaxGeographic.x, MaxGeographic.y ); // Setup pixel extraction const int32 TotalPixels = FoliageDistributionMap->SizeX * FoliageDistributionMap->SizeY; TArray<FLinearColor>* ClassificationPixels = new TArray<FLinearColor>(); TArray<FLinearColor>* NormalPixels = new TArray<FLinearColor>(); FOnRenderTargetRead OnRenderTargetRead; OnRenderTargetRead.BindLambda( [this, FoliageDistributionMap, ClassificationPixels, NormalPixels, GeographicExtents2D, TotalPixels]( bool bSuccess) mutable { if (!bSuccess) { bIsBuilding = false; return; } const int32 Width = FoliageDistributionMap->SizeX; TMap<UFoliageHISM*, int32> NewInstanceCountMap; FFoliageTransforms FoliageTransforms; for (int Index = 0; Index < TotalPixels; ++Index) { // Get the 2D pixel coordinates. const double X = Index % Width; const double Y = Index / Width; // Extract classification, normals and depth from the pixel arrays. const FLinearColor Classification = (*ClassificationPixels)[Index]; const FLinearColor NormalDepth = (*NormalPixels)[Index]; // Convert the RGB channel in the NormalDepth array to a FVector FVector Normal = FVector(NormalDepth.R, NormalDepth.G, NormalDepth.B); // Project the Alpha channel in NormalDepth to elevation (in metres) const double Elevation = GetHeightFromDepth(NormalDepth.A); // Project pixel coords to geographic. const glm::dvec3 GeographicCoords = PixelToGeographicLocation(X, Y, Elevation, FoliageDistributionMap, GeographicExtents2D); // Then project to UE world coordinates const glm::dvec3 EngineCoords = Georeference->TransformLongitudeLatitudeHeightToUnreal(GeographicCoords); // Compute east north up const FMatrix EastNorthUpEngine = Georeference->InaccurateComputeEastNorthUpToUnreal( FVector(EngineCoords.x, EngineCoords.y, EngineCoords.z)); for (FFoliageClassificationType& FoliageType : FoliageTypes) { // If classification pixel colour matches the classification of FoliageType if (Classification == FoliageType.ColourClassification) { bool bHasDoneRaycast = false; FVector Location = FVector(EngineCoords.x, EngineCoords.y, EngineCoords.z); if (FoliageType.bAlignToSurfaceWithRaycast) { CorrectFoliageTransform(Location, EastNorthUpEngine, Location, Normal, bHasDoneRaycast); } // Iterate through the mesh types inside FoliageType for (FFoliageGeometryType& FoliageGeometryType : FoliageType.FoliageTypes) { if (FMath::FRand() >= FoliageGeometryType.Density) { continue; } // Find rotation and scale const float Scale = FoliageGeometryType.Scale.Interpolate(FMath::FRand()); FRotator Rotation; if (FoliageGeometryType.bAlignToNormal) { Rotation = UKismetMathLibrary::MakeRotFromZ(Normal); } else { Rotation = EastNorthUpEngine.Rotator(); } // Apply a random angle to the rotation yaw if RandomYaw is true. if (FoliageGeometryType.bRandomYaw) { Rotation = UKismetMathLibrary::RotatorFromAxisAndAngle( Rotation.Quaternion().GetUpVector(), FMath::FRandRange( 0.0, 360.0 )); } // Find HISM with minimum amount of transforms. UFoliageHISM* MinimumHISM = HISMFoliageMap[FoliageGeometryType][0]; for (UFoliageHISM* HISM : HISMFoliageMap[FoliageGeometryType]) { if (FoliageTransforms.HISMTransformMap.Contains(HISM) && FoliageTransforms.HISMTransformMap.Contains(MinimumHISM)) { if (FoliageTransforms.HISMTransformMap[HISM].Num() < FoliageTransforms.HISMTransformMap[MinimumHISM].Num()) { MinimumHISM = HISM; } } } if (!IsValid(MinimumHISM)) { UE_LOG(LogTemp, Error, TEXT("MinimumHISM is invalid!")); } Location += WorldOffset; // Add our transform, and make it relative to the actor. FTransform NewTransform = FTransform( Rotation, Location + (Rotation.Quaternion(). GetUpVector() * FoliageGeometryType.ZOffset. Interpolate(FMath::FRand())), FVector(Scale) ).GetRelativeTransform(GetTransform()); if (NewTransform.IsRotationNormalized()) { if (!FoliageTransforms.HISMTransformMap.Contains(MinimumHISM)) { FoliageTransforms.HISMTransformMap.Add(MinimumHISM, TArray{ NewTransform }); } else { FoliageTransforms.HISMTransformMap[MinimumHISM].Add(NewTransform); } } } } } } delete ClassificationPixels; delete NormalPixels; ClassificationPixels = nullptr; NormalPixels = nullptr; AsyncTask(ENamedThreads::GameThread, [FoliageTransforms, this]() { // Marked for add for (const TPair<UFoliageHISM*, TArray<FTransform>>& Pair : FoliageTransforms.HISMTransformMap) { Pair.Key->Transforms.Append(Pair.Value); Pair.Key->bMarkedForAdd = true; } bIsBuilding = false; }); }); // Extract the pixels from the render targets, calling OnRenderTargetRead when complete. ReadLinearColorPixelsAsync(OnRenderTargetRead, TArray<FTextureRenderTargetResource*>{ FoliageDistributionMap->GameThread_GetRenderTargetResource(), NormalAndDepthMap->GameThread_GetRenderTargetResource() }, TArray<TArray<FLinearColor>*>{ ClassificationPixels, NormalPixels }); } void AFoliageCaptureActor::ClearFoliageInstances() { // Ensure the transforms array on the HISMs are cleared before building. for (TPair<FFoliageGeometryType, TArray<UFoliageHISM*>>& FoliageHISMPair : HISMFoliageMap) { for (UFoliageHISM* FoliageHISM : FoliageHISMPair.Value) { if (IsValid(FoliageHISM)) { FoliageHISM->Transforms.Empty(); FoliageHISM->bMarkedForClear = true; } } } } void AFoliageCaptureActor::ResetAndCreateHISMComponents() { for (FFoliageClassificationType& FoliageType : FoliageTypes) { for (FFoliageGeometryType& FoliageGeometryType : FoliageType.FoliageTypes) { if (FoliageGeometryType.Mesh == nullptr) { continue; } if (HISMFoliageMap.Contains(FoliageGeometryType)) { for (UFoliageHISM* HISM : HISMFoliageMap[FoliageGeometryType]) { if (IsValid(HISM)) { HISM->DestroyComponent(); } } HISMFoliageMap[FoliageGeometryType].Empty(); } HISMFoliageMap.Remove(FoliageGeometryType); for (int32 i = 0; i < FoliageType.PooledHISMsToCreatePerFoliageType; ++i) { UFoliageHISM* HISM = NewObject<UFoliageHISM>(this); HISM->SetupAttachment(GetRootComponent()); HISM->RegisterComponent(); HISM->SetStaticMesh(FoliageGeometryType.Mesh); HISM->SetCollisionEnabled(FoliageGeometryType.bCollidesWithWorld ? ECollisionEnabled::QueryAndPhysics : ECollisionEnabled::NoCollision); HISM->SetCullDistances(FoliageGeometryType.CullingDistances.Min, FoliageGeometryType.CullingDistances.Max); // This may cause a slight hitch when enabled. HISM->bAffectDistanceFieldLighting = FoliageGeometryType.bAffectsDistanceFieldLighting; if (!HISMFoliageMap.Contains(FoliageGeometryType)) { HISMFoliageMap.Add(FoliageGeometryType, TArray<UFoliageHISM*>{HISM}); } else { HISMFoliageMap[FoliageGeometryType].Add(HISM); } } } } } void AFoliageCaptureActor::OnUpdate_Implementation(const FVector& NewLocation) { // Align the actor to face the planet surface. // SetActorLocation(NewLocation); NewActorLocation = NewLocation; bInstancesClearedCalled = false; const FRotator PlanetAlignedRotation = Georeference->InaccurateComputeEastNorthUpToUnreal(NewLocation).Rotator(); SetActorRotation( PlanetAlignedRotation ); // Get grid min and max coords. const int32 Size = GridSize.X > 0 ? GridSize.X : 1; const FVector Start = GetActorTransform().TransformPosition(FVector(-(CaptureWidth * Size) / 2, 0, 0)); const FVector End = GetActorTransform().TransformPosition(FVector((CaptureWidth * Size) / 2, 0, 0)); // Find the distance (in degrees) between the grid min and max. glm::dvec3 GeoStart = Georeference->TransformUnrealToLongitudeLatitudeHeight(VectorToDVector(Start)); glm::dvec3 GeoEnd = Georeference->TransformUnrealToLongitudeLatitudeHeight(VectorToDVector(End)); GeoStart.z = CaptureElevation; GeoEnd.z = CaptureElevation; CaptureWidthInDegrees = glm::distance(GeoStart, GeoEnd) / 2; bIsWaiting = true; #if FOLIAGE_REDUCE_FLICKER_APPROACH_ENABLED OnInstancesCleared(); #else ClearFoliageInstances(); #endif } void AFoliageCaptureActor::OnInstancesCleared_Implementation() { if (NewActorLocation.IsSet()) { glm::dvec3 GeoPosition = Georeference->TransformUnrealToLongitudeLatitudeHeight( VectorToDVector(*NewActorLocation) ); GeoPosition.z = CaptureElevation; glm::dvec3 EnginePosition = Georeference->TransformLongitudeLatitudeHeightToUnreal(GeoPosition); FVector EnginePositionVector = FVector(EnginePosition.x, EnginePosition.y, EnginePosition.z); ActorOffset = EnginePositionVector - GetActorLocation(); SetActorLocation( EnginePositionVector ); #if FOLIAGE_REDUCE_FLICKER_APPROACH_ENABLED OffsetAllInstances(ActorOffset); #endif NewActorLocation.Reset(); bIsWaiting = false; } } bool AFoliageCaptureActor::IsBuilding() const { return bIsBuilding; } bool AFoliageCaptureActor::IsWaiting() const { return bIsWaiting; } void AFoliageCaptureActor::CorrectFoliageTransform(const FVector& InEngineCoordinates, const FMatrix& InEastNorthUp, FVector& OutCorrectedPosition, FVector& OutSurfaceNormals, bool& bSuccess) const { UWorld* World = GetWorld(); if (IsValid(World)) { const FVector Up = InEastNorthUp.ToQuat().GetUpVector(); FHitResult HitResult; World->LineTraceSingleByChannel(HitResult, InEngineCoordinates + (Up * 6000), InEngineCoordinates - (Up * 6000), ECollisionChannel::ECC_Visibility); if (HitResult.bBlockingHit) { bSuccess = true; OutCorrectedPosition = HitResult.ImpactPoint; OutSurfaceNormals = HitResult.ImpactNormal; } } } double AFoliageCaptureActor::GetHeightFromDepth(const double& Value) const { return CaptureElevation - (1 - Value) / 0.00001 / 100; } glm::dvec3 AFoliageCaptureActor::PixelToGeographicLocation(const double& X, const double& Y, const double& Altitude, UTextureRenderTarget2D* RT, const glm::dvec4& GeographicExtents) const { // Normalize the ranges of the coords const double AX = X / static_cast<double>(RT->SizeX); const double AY = Y / static_cast<double>(RT->SizeY); const double Long = FMath::Lerp<double>( GeographicExtents.x, GeographicExtents.z, 1 - AY); const double Lat = FMath::Lerp<double>( GeographicExtents.y, GeographicExtents.w, AX); return glm::dvec3(Long, Lat, Altitude); } FIntPoint AFoliageCaptureActor::GeographicToPixelLocation(const double& Longitude, const double& Latitude, UTextureRenderTarget2D* RT, const glm::dvec4& GeographicExtents) const { // Normalize long and lat const double LongitudeRange = GeographicExtents.z - GeographicExtents.x; const double LatitudeRange = GeographicExtents.w - GeographicExtents.y; const double ALongitude = (Longitude - GeographicExtents.x) / LongitudeRange; const double ALatitude = (Latitude - GeographicExtents.y) / LatitudeRange; const double X = FMath::Lerp<double>(0, RT->SizeX, ALatitude); const double Y = FMath::Lerp<double>(RT->SizeY, 0, ALongitude); return FIntPoint(X, Y); } void AFoliageCaptureActor::ReadLinearColorPixelsAsync( FOnRenderTargetRead OnRenderTargetRead, TArray<FTextureRenderTargetResource*> RTs, TArray<TArray<FLinearColor>*> OutImageData, FReadSurfaceDataFlags InFlags, FIntRect InRect, ENamedThreads::Type ExitThread) { if (InRect == FIntRect(0, 0, 0, 0)) { InRect = FIntRect(0, 0, RTs[0]->GetSizeXY().X, RTs[0]->GetSizeXY().Y); } struct FReadSurfaceContext { TArray<FTextureRenderTargetResource*> SrcRenderTargets; TArray<TArray<FLinearColor>*> OutData; FIntRect Rect; FReadSurfaceDataFlags Flags; }; for (auto DT : OutImageData) { DT->Reset(); } FReadSurfaceContext Context = { RTs, OutImageData, InRect, InFlags }; if (!Context.OutData[0]) { UE_LOG(LogTemp, Error, TEXT("Buffer invalid!")); return; } ENQUEUE_RENDER_COMMAND(ReadSurfaceCommand)( [Context, OnRenderTargetRead, ExitThread](FRHICommandListImmediate& RHICmdList) { const FIntRect Rect = Context.Rect; const FReadSurfaceDataFlags Flags = Context.Flags; int i = 0; for (FRenderTarget* RT : Context.SrcRenderTargets) { const FTexture2DRHIRef& RefRenderTarget = RT-> GetRenderTargetTexture(); TArray<FLinearColor>* Buffer = Context.OutData[i]; RHICmdList.ReadSurfaceData( RefRenderTarget, Rect, *Buffer, Flags ); i++; } // instead of blocking the game thread, execute the delegate when finished. AsyncTask( ExitThread, [OnRenderTargetRead, Context]() { OnRenderTargetRead.Execute((*Context.OutData[0]).Num() > 0); }); }); } glm::dvec3 AFoliageCaptureActor::VectorToDVector(const FVector& InVector) { return glm::dvec3(InVector.X, InVector.Y, InVector.Z); }
30.846154
123
0.702604
SquarerFive
e4de834d0e9f197ec43b12a7b93efad5ce83e3bc
2,627
cpp
C++
src/utils/fileio/SkeletonFile.cpp
Ibujah/compactskel
8a54b5f0123490c4e8120537ae2b56d5ec2a34c9
[ "MIT" ]
4
2019-04-15T08:50:30.000Z
2021-02-03T10:44:03.000Z
src/utils/fileio/SkeletonFile.cpp
Ibujah/compactskel
8a54b5f0123490c4e8120537ae2b56d5ec2a34c9
[ "MIT" ]
null
null
null
src/utils/fileio/SkeletonFile.cpp
Ibujah/compactskel
8a54b5f0123490c4e8120537ae2b56d5ec2a34c9
[ "MIT" ]
null
null
null
/* Copyright (c) 2016 Bastien Durix Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * \file SkeletonFile.h * \brief Input/output functions for skeletons * \author Bastien Durix */ #include "SkeletonFile.h" #include <fstream> namespace fileio { void writeSkeleton(const skeleton::GraphSkel2d::Ptr grskel, const std::map<unsigned int, std::vector<unsigned int> >& deldat, const std::string& nodname, const std::string& edgname, const std::string& delname) { std::ofstream fnod(nodname); std::ofstream fedg(edgname); std::ofstream fdel(delname); if(!fnod || !fedg || !fdel) { std::cout << "Problem" << std::endl; return; } std::list<unsigned int> nods; grskel->getAllNodes(nods); for(std::list<unsigned int>::iterator it = nods.begin(); it != nods.end(); it++) { mathtools::geometry::euclidian::HyperSphere<2> cir1 = grskel->getNode<mathtools::geometry::euclidian::HyperSphere<2> >(*it); Eigen::Vector2d pt = cir1.getCenter().getCoords(); double rad = cir1.getRadius(); fnod << pt.x() << " " << pt.y() << " " << rad << std::endl; } std::list<std::pair<unsigned int,unsigned int> > edges; grskel->getAllEdges(edges); for(std::list<std::pair<unsigned int,unsigned int> >::iterator it = edges.begin(); it != edges.end(); it++) { fedg << it->first << " " << it->second << std::endl; } for(auto it : deldat) { fdel << it.first << " : "; for(auto itn : it.second) fdel << itn << ", "; fdel << std::endl; } fnod.close(); fedg.close(); fdel.close(); } }
31.650602
126
0.669204
Ibujah
e4dfdfde7542f9293ddd30e45076d4a208f9cc6b
524
cpp
C++
cpp/0238_productExceptSelf.cpp
linhx25/leetcode
9cf1d6d2372fd8777825c8107780b7f3c934fe20
[ "MIT" ]
1
2021-04-16T12:54:56.000Z
2021-04-16T12:54:56.000Z
cpp/0238_productExceptSelf.cpp
linhx25/leetcode
9cf1d6d2372fd8777825c8107780b7f3c934fe20
[ "MIT" ]
null
null
null
cpp/0238_productExceptSelf.cpp
linhx25/leetcode
9cf1d6d2372fd8777825c8107780b7f3c934fe20
[ "MIT" ]
1
2021-04-26T13:20:41.000Z
2021-04-26T13:20:41.000Z
// 1.最简单做法:遍历一遍得到连乘,每个元素单独除一遍即可; // 2.不能使用除法: // (1)先遍历一遍,得到每个位置的左连乘(不包括该位置) // (2)从右边开始遍历,获得右连乘,随后更新每个位置的左连乘 class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { vector<int> res(nums.size()); int right=1; res[0]=1; for(auto i=1;i<nums.size();i++) res[i]=res[i-1]*nums[i-1]; for(auto i=nums.size()-2;i>0;i--) { right*=nums[i+1]; res[i]*=right; } res[0]=right*nums[1]; return res; } };
23.818182
54
0.51145
linhx25
e4e00ea3d9d442924535e46cc8e4cd9ec884694d
3,345
hpp
C++
rmf_schedule_visualizer/src/VisualizerData.hpp
Briancbn/rmf_schedule_visualizer
b6f61b6ddbdf34fe539256c9cb6c420408574f81
[ "Apache-2.0" ]
null
null
null
rmf_schedule_visualizer/src/VisualizerData.hpp
Briancbn/rmf_schedule_visualizer
b6f61b6ddbdf34fe539256c9cb6c420408574f81
[ "Apache-2.0" ]
null
null
null
rmf_schedule_visualizer/src/VisualizerData.hpp
Briancbn/rmf_schedule_visualizer
b6f61b6ddbdf34fe539256c9cb6c420408574f81
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2019 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef RMF_SCHEDULE_VISUALIZER__SRC__VISUALIZERDATA_HPP #define RMF_SCHEDULE_VISUALIZER__SRC__VISUALIZERDATA_HPP #include <rmf_traffic_ros2/schedule/MirrorManager.hpp> #include <rmf_traffic/Trajectory.hpp> #include <rmf_traffic/schedule/Viewer.hpp> #include <rmf_traffic_ros2/StandardNames.hpp> #include <rmf_traffic_msgs/msg/negotiation_notice.hpp> #include <rmf_traffic_msgs/msg/negotiation_conclusion.hpp> #include <rmf_schedule_visualizer/CommonData.hpp> #include <rclcpp/node.hpp> #include <std_msgs/msg/string.hpp> #include <websocketpp/config/asio_no_tls.hpp> #include <websocketpp/server.hpp> #include <set> #include <mutex> #include <unordered_set> namespace rmf_schedule_visualizer { class VisualizerDataNode : public rclcpp::Node { public: using Element = rmf_traffic::schedule::Viewer::View::Element; using ConflictNotice = rmf_traffic_msgs::msg::NegotiationNotice; using ConflictConclusion = rmf_traffic_msgs::msg::NegotiationConclusion; /// Builder function which returns a pointer to VisualizerNode when /// the Mirror Manager is readied and websocket is started. /// A nullptr is returned if initialization fails. static std::shared_ptr<VisualizerDataNode> make( std::string node_name, rmf_traffic::Duration wait_time = std::chrono::seconds(10)); /// Function to query Mirror Manager for trajectories. std::vector<rmf_traffic::Trajectory> get_trajectories( RequestParam request_param); /// Function to query Mirror Manager for elements containing /// trajectory and ID pairs. std::vector<Element> get_elements(RequestParam request_param); std::unordered_set<uint64_t> get_conflicts() const; rmf_traffic::Time now(); std::mutex& get_mutex(); public: struct Data { rmf_traffic_ros2::schedule::MirrorManager mirror; Data(rmf_traffic_ros2::schedule::MirrorManager mirror_) : mirror(std::move(mirror_)) { // Do nothing } }; // Create a VisualizerData node with a specified name VisualizerDataNode(std::string _node_name); void debug_cb(std_msgs::msg::String::UniquePtr msg); using DebugSub = rclcpp::Subscription<std_msgs::msg::String>; DebugSub::SharedPtr debug_sub; rclcpp::Subscription<ConflictNotice>::SharedPtr _conflict_notice_sub; rclcpp::Subscription<ConflictConclusion>::SharedPtr _conflict_conclusion_sub; void start(Data data); std::vector<rmf_traffic::Trajectory> _trajectories; std::string _node_name; std::unique_ptr<Data> data; std::mutex _mutex; std::unordered_map< rmf_traffic::schedule::Version, std::vector<rmf_traffic::schedule::ParticipantId>> _conflicts; }; } // namespace rmf_schedule_visualizer #endif // RMF_SCHEDULE_VISUALIZER__SRC__VISUALIZERDATA_HPP
30.688073
79
0.767414
Briancbn
e4e2f28c025a45a5b1d530ad4f16d9ea7beea7a6
928
cpp
C++
src/examples/textured_triangle/textured_triangle_shader.cpp
DavidSlayback/megaverse
6ce21c9df5ee4d157f4a69b98de3ef1569bc8ccc
[ "MIT" ]
149
2021-06-09T01:28:57.000Z
2022-03-30T20:31:25.000Z
src/examples/textured_triangle/textured_triangle_shader.cpp
DavidSlayback/megaverse
6ce21c9df5ee4d157f4a69b98de3ef1569bc8ccc
[ "MIT" ]
4
2021-06-30T17:06:18.000Z
2022-02-17T21:58:13.000Z
src/examples/textured_triangle/textured_triangle_shader.cpp
DavidSlayback/megaverse
6ce21c9df5ee4d157f4a69b98de3ef1569bc8ccc
[ "MIT" ]
13
2021-07-10T06:49:24.000Z
2022-03-08T05:11:35.000Z
#include "textured_triangle_shader.hpp" #include <Corrade/Containers/Reference.h> #include <Corrade/Utility/Resource.h> #include <Magnum/GL/Context.h> #include <Magnum/GL/Shader.h> #include <Magnum/GL/Version.h> namespace Magnum { TexturedTriangleShader::TexturedTriangleShader() { MAGNUM_ASSERT_GL_VERSION_SUPPORTED(GL::Version::GL330); const Utility::Resource rs{"textured-triangle-data"}; GL::Shader vert{GL::Version::GL330, GL::Shader::Type::Vertex}; GL::Shader frag{GL::Version::GL330, GL::Shader::Type::Fragment}; vert.addSource(rs.get("textured_triangle_shader.vert")); frag.addSource(rs.get("textured_triangle_shader.frag")); CORRADE_INTERNAL_ASSERT_OUTPUT(GL::Shader::compile({vert, frag})); attachShaders({vert, frag}); CORRADE_INTERNAL_ASSERT_OUTPUT(link()); _colorUniform = uniformLocation("color"); setUniform(uniformLocation("textureData"), TextureUnit); } }
28.121212
70
0.738147
DavidSlayback
e4e341e35f00763121e29e0d057557464476432e
2,706
hpp
C++
modules/core/integration/include/nt2/toolbox/integration/options.hpp
timblechmann/nt2
6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce
[ "BSL-1.0" ]
2
2016-09-14T00:23:53.000Z
2018-01-14T12:51:18.000Z
modules/core/integration/include/nt2/toolbox/integration/options.hpp
timblechmann/nt2
6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce
[ "BSL-1.0" ]
null
null
null
modules/core/integration/include/nt2/toolbox/integration/options.hpp
timblechmann/nt2
6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce
[ "BSL-1.0" ]
null
null
null
//============================================================================== // Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef NT2_TOOLBOX_INTEGRATION_OPTIONS_HPP_INCLUDED #define NT2_TOOLBOX_INTEGRATION_OPTIONS_HPP_INCLUDED #include <cstddef> #include <nt2/sdk/option/options.hpp> #include <nt2/include/constants/sqrteps.hpp> namespace nt2 { /** * Named parameter for passing number of iterations to iterative algortihms **/ NT2_REGISTER_PARAMETERS(iterations_); namespace tolerance { /** * Named parameter for passing absolute tolerance to iterative algorithms **/ NT2_REGISTER_PARAMETERS(absolute_); /** * Named parameter for passing relative tolerance to iterative algorithms **/ NT2_REGISTER_PARAMETERS(relative_); /** * Named parameter for passing residual tolerance to iterative algorithms **/ NT2_REGISTER_PARAMETERS(residual_); } } namespace nt2 { namespace details { // INTERNAL ONLY // integration_settings gather the classical set of settings required // for an integration process from either the list of values or from an // options pack expressions template<typename T> struct integration_settings { typedef T value_type; // required on MSVC for some unknown reason BOOST_FORCEINLINE static T Sqrteps() { return nt2::Sqrteps<T>(); } integration_settings ( std::size_t it = 100 , value_type at = Sqrteps() , value_type rt = Sqrteps() , value_type rst = Sqrteps() ) : maximum_iterations(it), absolute_tolerance(at) , relative_tolerance(rt), residual_tolerance(rst) {} template<class Expr> integration_settings ( nt2::details::option_expr<Expr> const& x) : maximum_iterations(x(nt2::iterations_ , 100 )) , absolute_tolerance(x(nt2::tolerance::absolute_, Sqrteps() )) , relative_tolerance(x(nt2::tolerance::relative_, Sqrteps() )) , residual_tolerance(x(nt2::tolerance::residual_, Sqrteps() )) {} std::size_t maximum_iterations; value_type absolute_tolerance; value_type relative_tolerance; value_type residual_tolerance; }; } } #endif
33.825
80
0.609387
timblechmann
e4e3ca21e90fde907f4e39a80b029a65935ce82f
954
cpp
C++
emulator/Hardware.cpp
arturmazurek/dcpu
0647fc521b04ba71b793eedeb62c7add3111576c
[ "MIT" ]
null
null
null
emulator/Hardware.cpp
arturmazurek/dcpu
0647fc521b04ba71b793eedeb62c7add3111576c
[ "MIT" ]
null
null
null
emulator/Hardware.cpp
arturmazurek/dcpu
0647fc521b04ba71b793eedeb62c7add3111576c
[ "MIT" ]
null
null
null
// // Hardware.cpp // dcpu // // Created by Artur Mazurek on 08.09.2013. // Copyright (c) 2013 Artur Mazurek. All rights reserved. // #include "Hardware.h" #include <cassert> #include "Core.h" #include "DCPUException.h" Hardware::Hardware(uint32_t hardwareId, uint16_t version, uint32_t manufacturer) : m_hardwareId{hardwareId}, m_version{version}, m_manufacturer{manufacturer} { } void Hardware::attachedTo(Core* ownerCore) { m_ownerCore = ownerCore; } void Hardware::receiveInterrupt() { assert(m_ownerCore); if(!m_ownerCore) { throw UnattachedHardware("Sending interrupt to unattached hardware"); } doReceiveInterrupt(*m_ownerCore); } void Hardware::sendInterrupt(uint16_t message) const { } uint32_t Hardware::hardwareId() const { return m_hardwareId; } uint16_t Hardware::version() const { return m_version; } uint32_t Hardware::manufacturer() const { return m_manufacturer; }
19.875
82
0.708595
arturmazurek
e4e62835e3211e21adfb136995ef2f08a3b6901d
1,397
cpp
C++
snippets/cpp/VS_Snippets_CLR_System/system.Runtime.InteropServices.TypelibConverter.ConvertAssemblyToTypelib1/CPP/convert2.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
2
2020-02-22T09:30:21.000Z
2021-08-02T23:44:31.000Z
snippets/cpp/VS_Snippets_CLR_System/system.Runtime.InteropServices.TypelibConverter.ConvertAssemblyToTypelib1/CPP/convert2.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
555
2019-09-23T22:22:58.000Z
2021-07-15T18:51:12.000Z
snippets/cpp/VS_Snippets_CLR_System/system.Runtime.InteropServices.TypelibConverter.ConvertAssemblyToTypelib1/CPP/convert2.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
3
2020-01-29T16:31:15.000Z
2021-08-24T07:00:15.000Z
// <snippet1> using namespace System; using namespace System::Reflection; using namespace System::Reflection::Emit; using namespace System::Runtime::InteropServices; [ComImport, GuidAttribute("00020406-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType::InterfaceIsIUnknown), ComVisible(false)] interface class UCOMICreateITypeLib { void CreateTypeInfo(); void SetName(); void SetVersion(); void SetGuid(); void SetDocString(); void SetHelpFileName(); void SetHelpContext(); void SetLcid(); void SetLibFlags(); void SaveAllChanges(); }; public ref class ConversionEventHandler: public ITypeLibExporterNotifySink { public: virtual void ReportEvent( ExporterEventKind eventKind, int eventCode, String^ eventMsg ) { // Handle the warning event here. } virtual Object^ ResolveRef( Assembly^ a ) { // Resolve the reference here and return a correct type library. return nullptr; } }; int main() { Assembly^ a = Assembly::LoadFrom( "MyAssembly.dll" ); TypeLibConverter^ converter = gcnew TypeLibConverter; ConversionEventHandler^ eventHandler = gcnew ConversionEventHandler; UCOMICreateITypeLib^ typeLib = dynamic_cast<UCOMICreateITypeLib^>(converter->ConvertAssemblyToTypeLib( a, "MyTypeLib.dll", static_cast<TypeLibExporterFlags>(0), eventHandler )); typeLib->SaveAllChanges(); } // </snippet1>
27.94
180
0.745168
BohdanMosiyuk
e4e7b247b69c9c62b595db1d8ecd9171b15a29fd
1,094
cc
C++
cpp/Offline_sampling.cc
iskhanba/epicode
fda752e5e016ab64011083450be91bec9ee8358a
[ "MIT" ]
null
null
null
cpp/Offline_sampling.cc
iskhanba/epicode
fda752e5e016ab64011083450be91bec9ee8358a
[ "MIT" ]
null
null
null
cpp/Offline_sampling.cc
iskhanba/epicode
fda752e5e016ab64011083450be91bec9ee8358a
[ "MIT" ]
null
null
null
// Copyright (c) 2015 Elements of Programming Interviews. All rights reserved. #include <algorithm> #include <cassert> #include <iostream> #include <random> #include <vector> #include "./Offline_sampling.h" using std::cout; using std::default_random_engine; using std::endl; using std::random_device; using std::swap; using std::uniform_int_distribution; using std::vector; int main(int argc, char* argv[]) { int n, k; default_random_engine gen((random_device())()); if (argc == 2) { n = atoi(argv[1]); uniform_int_distribution<int> dis(1, n); k = dis(gen); } else if (argc == 3) { n = atoi(argv[1]); k = atoi(argv[2]); } else { uniform_int_distribution<int> n_dis(1, 1000000); n = n_dis(gen); uniform_int_distribution<int> k_dis(1, n); k = k_dis(gen); } vector<int> A(n); iota(A.begin(), A.end(), 0); cout << n << ' ' << k << endl; RandomSampling(k, &A); for (int i = 0; i < A.size(); i++) { cout << i << ":" << A[i] << " "; } cout << endl; return 0; }
24.311111
78
0.571298
iskhanba
e4e98a060da8913c927916cc83c32fbb5b508fe6
4,339
cpp
C++
10-11/VmWriter.cpp
jomiller/nand2tetris
4be20996e1b5185654ef4de5234a9543f957d6fc
[ "MIT" ]
1
2020-10-13T07:06:37.000Z
2020-10-13T07:06:37.000Z
10-11/VmWriter.cpp
jomiller/nand2tetris
4be20996e1b5185654ef4de5234a9543f957d6fc
[ "MIT" ]
null
null
null
10-11/VmWriter.cpp
jomiller/nand2tetris
4be20996e1b5185654ef4de5234a9543f957d6fc
[ "MIT" ]
null
null
null
/* * This file is part of Nand2Tetris. * * Copyright © 2013-2020 Jonathan Miller * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "VmWriter.h" #include <Assert.h> #include <Util.h> #include <frozen/unordered_map.h> #include <string_view> #include <utility> n2t::VmWriter::VmWriter(std::filesystem::path filename) : m_filename{std::move(filename)}, m_file{m_filename.string().data()} { throwUnless<std::runtime_error>(m_file.good(), "Could not open output file ({})", m_filename.string()); } n2t::VmWriter::~VmWriter() noexcept { try { if (!m_closed) { m_file.close(); std::filesystem::remove(m_filename); } } catch (...) { } } void n2t::VmWriter::writePush(SegmentType segment, int16_t index) { m_file << "push " << toString(segment) << " " << index << '\n'; } void n2t::VmWriter::writePop(SegmentType segment, int16_t index) { m_file << "pop " << toString(segment) << " " << index << '\n'; } void n2t::VmWriter::writeArithmetic(ArithmeticCommand command) { // clang-format off static constexpr auto commands = frozen::make_unordered_map<ArithmeticCommand, std::string_view>( { {ArithmeticCommand::Add, "add"}, {ArithmeticCommand::Sub, "sub"}, {ArithmeticCommand::Neg, "neg"}, {ArithmeticCommand::And, "and"}, {ArithmeticCommand::Or, "or"}, {ArithmeticCommand::Not, "not"}, {ArithmeticCommand::Eq, "eq"}, {ArithmeticCommand::Gt, "gt"}, {ArithmeticCommand::Lt, "lt"} }); // clang-format on const auto iter = commands.find(command); // NOLINT(readability-qualified-auto) N2T_ASSERT((iter != commands.end()) && "Invalid arithmetic command"); m_file << iter->second << '\n'; } void n2t::VmWriter::writeLabel(const std::string& label) { m_file << "label " << label << '\n'; } void n2t::VmWriter::writeGoto(const std::string& label) { m_file << "goto " << label << '\n'; } void n2t::VmWriter::writeIf(const std::string& label) { m_file << "if-goto " << label << '\n'; } void n2t::VmWriter::writeFunction(const std::string& functionName, int16_t numLocals) { m_file << "function " << functionName << " " << numLocals << '\n'; } void n2t::VmWriter::writeReturn() { m_file << "return\n"; } void n2t::VmWriter::writeCall(const std::string& functionName, int16_t numArguments) { m_file << "call " << functionName << " " << numArguments << '\n'; } void n2t::VmWriter::close() { m_file.close(); m_closed = true; } std::string_view n2t::VmWriter::toString(SegmentType segment) { // clang-format off static constexpr auto segments = frozen::make_unordered_map<SegmentType, std::string_view>( { {SegmentType::Constant, "constant"}, {SegmentType::Static, "static"}, {SegmentType::Pointer, "pointer"}, {SegmentType::Temp, "temp"}, {SegmentType::Argument, "argument"}, {SegmentType::Local, "local"}, {SegmentType::This, "this"}, {SegmentType::That, "that"} }); // clang-format on const auto iter = segments.find(segment); // NOLINT(readability-qualified-auto) N2T_ASSERT((iter != segments.end()) && "Invalid memory segment"); return iter->second; }
29.924138
107
0.651302
jomiller
e4f17dfd32c13132bc78515fb43194c63b27ae5a
1,131
hpp
C++
team_AASM/find_optimal_cell.hpp
AlinGeorgescu/Halite-III-Bot
79bcf45c0f131c35c6b60eced56a4c3f01453845
[ "CC0-1.0" ]
null
null
null
team_AASM/find_optimal_cell.hpp
AlinGeorgescu/Halite-III-Bot
79bcf45c0f131c35c6b60eced56a4c3f01453845
[ "CC0-1.0" ]
null
null
null
team_AASM/find_optimal_cell.hpp
AlinGeorgescu/Halite-III-Bot
79bcf45c0f131c35c6b60eced56a4c3f01453845
[ "CC0-1.0" ]
null
null
null
#pragma once #include "hlt/game.hpp" using namespace std; using namespace hlt; /** Greedy search of optimal cell. */ Position optimal_mine_cell(shared_ptr<Ship> ship, unique_ptr<GameMap>& game_map) { Position optimal; int max = 0; for (int y = 0; y < game_map->height; ++y) { for (int x = 0; x < game_map->width; ++x) { /** * Choose a cell as target as long as it is not targeted by other * ship. */ if (!game_map->cells[y][x].marked_as_target) { Position checked = {x, y}; int distance = game_map->calculate_distance(ship->position, checked); if (distance) { int ratio = game_map->cells[y][x].halite / distance; if (ratio > max) { max = ratio; optimal = checked; } } } } } /** Mark cell as targeted. */ game_map->cells[optimal.y][optimal.x].marked_as_target = true; return optimal; }
26.928571
77
0.478338
AlinGeorgescu
e4f26e33e7ab5a681f5e23c1e42f3c9498740718
634
cxx
C++
Modules/ThirdParty/VNL/src/vxl/core/vnl/Templates/vcl_complex+vnl_rational-.cxx
jcfr/ITK
6632b7f968c3827e8a3bcc9812e05b4e2064676e
[ "Apache-2.0" ]
null
null
null
Modules/ThirdParty/VNL/src/vxl/core/vnl/Templates/vcl_complex+vnl_rational-.cxx
jcfr/ITK
6632b7f968c3827e8a3bcc9812e05b4e2064676e
[ "Apache-2.0" ]
null
null
null
Modules/ThirdParty/VNL/src/vxl/core/vnl/Templates/vcl_complex+vnl_rational-.cxx
jcfr/ITK
6632b7f968c3827e8a3bcc9812e05b4e2064676e
[ "Apache-2.0" ]
null
null
null
#include <vcl_iostream.h> #include <vnl/vnl_rational.h> #include <vcl_complex.hxx> // this function will tickle implicit templates for // some compilers and detect missing instances for others. template <class T> vcl_complex<T> vcl_complex_instances_ticker(T *) { vcl_complex<T> z(1, 2); return vcl_conj(z); } template vcl_complex<vnl_rational> vcl_complex_instances_ticker(vnl_rational *); // macro to implement an operator>>, for compilers that need it. # define implement_rsh(T) \ vcl_istream &operator>>(vcl_istream &is, vcl_complex<T > &z) { \ T r, i; \ is >> r >> i; \ z = vcl_complex<T >(r, i); \ return is; \ }
26.416667
80
0.712934
jcfr
e4f2ac64bb0bb542747626b0228b4d045918b6b6
17,128
cpp
C++
3DSnake/GodRays.cpp
lerignoux/3D_snake
3932d5cc3462cfffa1867f766857fa7f3a29a170
[ "MIT" ]
null
null
null
3DSnake/GodRays.cpp
lerignoux/3D_snake
3932d5cc3462cfffa1867f766857fa7f3a29a170
[ "MIT" ]
null
null
null
3DSnake/GodRays.cpp
lerignoux/3D_snake
3932d5cc3462cfffa1867f766857fa7f3a29a170
[ "MIT" ]
null
null
null
// ---------------------------------------------------------------------------- // Light shafts demo variables // ---------------------------------------------------------------------------- #include "GodRays.h" // God ray data struct struct GodRayData { GodRayData() { } // Arrays information: // [0] -> Current value // [1] -> Final value // [2] -> Step value // [3] -> Final-Current value // [4] -> Step addition Ogre::Radian MainAngle[5]; float Radius[5]; Ogre::Radian RotateAngle[5]; float Dimension; } GDData[_def_NumberOfRays]; using namespace std; using namespace Ogre; GodRays::GodRays(Ogre::SceneManager *mSceneMgr, Camera* mLightCamera, SceneNode* mLightCameraSN, int num): mSceneMgr(mSceneMgr), mLightCamera(mLightCamera), mLightCameraSN(mLightCameraSN), ID(num) { raySceneNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("RaySceneNode"+num); // cout << "God Rays Constructed" << endl; } GodRays::~GodRays() { } /** Calcule the current ray position from ray data @param RayData Ray data @return Two vertex position stored in a Ogre::Vector4 */ Ogre::Vector4 GodRays::calculateRayPosition(const GodRayData& RayData) { // cout << "calculating position" << endl; Ogre::Vector2 A = Ogre::Vector2( Ogre::Math::Sin(RayData.MainAngle[0]), Ogre::Math::Cos(RayData.MainAngle[0]))*RayData.Radius[0]; Ogre::Vector2 B = Ogre::Vector2( Ogre::Math::Sin(RayData.RotateAngle[0]), Ogre::Math::Cos(RayData.RotateAngle[0]))*RayData.Dimension; Ogre::Vector4 Result = Ogre::Vector4( // X1 A.x - B.x, // Y1 A.y - B.y, // X2 A.x + B.y, // Y2 A.y + B.y); // cout << "position calculated" << endl; return Result; } /** Update god rays @param RaysLength Rays lenght @param FarWidth Far clip distance width(Assuming Width = Heigth) @param Delta Delta Time since last frame */ void GodRays::updateRays(const float& RaysLength, const float& FarWidth, const int& NumberOfRays, float Delta) { cout<< "updating rays" << endl; Delta *= _def_Simulation_Speed; mManualGodRays->beginUpdate(1); for(int k = 0; k < NumberOfRays; k++) { // Add steps GDData[k].Radius[0] += GDData[k].Radius[2]*Delta; GDData[k].Radius[4] += GDData[k].Radius[2]*Delta; GDData[k].MainAngle[0] += GDData[k].MainAngle[2]*Delta; GDData[k].MainAngle[4] += GDData[k].MainAngle[2]*Delta; GDData[k].RotateAngle[0] += GDData[k].RotateAngle[2]*Delta; GDData[k].RotateAngle[4] += GDData[k].RotateAngle[2]*Delta; // Check if final values needs to be recalculate if (Ogre::Math::Abs(GDData[k].Radius[4]) > Ogre::Math::Abs(GDData[k].Radius[3])) { GDData[k].Radius[1] = Ogre::Math::RangeRandom(-FarWidth/2, FarWidth/2); GDData[k].Radius[3] = GDData[k].Radius[1] - GDData[k].Radius[0]; GDData[k].Radius[2] = GDData[k].Radius[3] / Ogre::Math::RangeRandom(90,100); GDData[k].Radius[4] = 0; } if (Ogre::Math::Abs(GDData[k].MainAngle[4].valueRadians()) > Ogre::Math::Abs(GDData[k].MainAngle[3].valueRadians())) { GDData[k].MainAngle[1] = Ogre::Degree(Ogre::Math::RangeRandom(0, 360)); GDData[k].MainAngle[3] = GDData[k].MainAngle[1] - GDData[k].MainAngle[0]; GDData[k].MainAngle[2] = GDData[k].MainAngle[3] / Ogre::Math::RangeRandom(90,100); GDData[k].MainAngle[4] = Ogre::Radian(0); } if (Ogre::Math::Abs(GDData[k].RotateAngle[4].valueRadians()) > Ogre::Math::Abs(GDData[k].RotateAngle[3].valueRadians())) { GDData[k].RotateAngle[1] = Ogre::Degree(Ogre::Math::RangeRandom(0, 360)); GDData[k].RotateAngle[3] = GDData[k].RotateAngle[1] - GDData[k].RotateAngle[0]; GDData[k].RotateAngle[2] = GDData[k].RotateAngle[3] / Ogre::Math::RangeRandom(90,100); GDData[k].RotateAngle[4] = Ogre::Radian(0); } // Get the position from ray data Ogre::Vector4 Pos = calculateRayPosition(GDData[k]); // A mManualGodRays->position(0, 0, 0); mManualGodRays->textureCoord(0.5,0); // B mManualGodRays->position(Pos.x, Pos.y, -RaysLength); mManualGodRays->textureCoord(0,1); // C mManualGodRays->position(Pos.z, Pos.w, -RaysLength); mManualGodRays->textureCoord(1,1); } mManualGodRays->end(); cout << "rays updated" << endl; } // ---------------------------------------------------------------------------- // Define the application object // This is derived from ExampleApplication which is the class OGRE provides to // make it easier to set up OGRE without rewriting the same code all the time. // You can override extra methods of ExampleApplication if you want to further // specialise the setup routine, otherwise the only mandatory override is the // 'createScene' method which is where you set up your own personal scene. // ---------------------------------------------------------------------------- // class LightShaftsListener : public ExampleFrameListener // { // public: // SceneManager *mSceneMgr; // Real mKeyBuffer; // Real mKnotRotation; // bool mRotateEnable; // bool mRotateKnot; // // LightShaftsListener(RenderWindow* win, Camera* cam, SceneManager *sm) // : ExampleFrameListener(win,cam) // , mSceneMgr(sm) // , mKeyBuffer(-1) // , mKnotRotation(0) // , mRotateEnable(false) // , mRotateKnot(false) // { // } // // bool frameStarted(const FrameEvent &e) // { // mKeyboard->capture(); // // // Enable/disable knot rotation // if (mKeyboard->isKeyDown(OIS::KC_B) && mKeyBuffer < 0) // { // mRotateKnot = !mRotateKnot; // // mKeyBuffer = 0.5f; // } // // // Show/hide knot // if (mKeyboard->isKeyDown(OIS::KC_N) && mKeyBuffer < 0) // { // mKnotSN->getAttachedObject(0)->setVisible( // !mKnotSN->getAttachedObject(0)->isVisible()); // // mKeyBuffer = 0.5f; // } // // mKeyBuffer -= e.timeSinceLastFrame; // // // Update light position // updatePosition(e); // // // Get frustum corners to calculate far plane dimension // const Ogre::Vector3 *FrustumCorners = mLightCamera->getWorldSpaceCorners(); // float FarWidth = (FrustumCorners[4] - FrustumCorners[5]).length(); // // // Update god rays // updateRays(mLightCamera->getFarClipDistance(), FarWidth, _def_NumberOfRays, e.timeSinceLastFrame); // // updateDebugOverlay(); // // return true; // } // // void updatePosition(const FrameEvent &e) // { // // Fixed camera position // mCamera->setPosition(Ogre::Vector3(0,0,0)); // // if (mRotateKnot) // { // mKnotRotation += 25*e.timeSinceLastFrame; // // mKnotSN->setOrientation( // Ogre::Quaternion( // Ogre::Degree(mKnotRotation), // Ogre::Vector3(0,1,0))); // } // } // // void updateDebugOverlay() // { // Ogre::OverlayElement* guiDbg = OverlayManager::getSingleton().getOverlayElement("Core/DebugText"); // guiDbg->setCaption( // "Show/hide knot("+Ogre::StringConverter::toString(mKnotSN->getAttachedObject(0)->isVisible())+"): Press N to change\n" + // "Rotate knot("+Ogre::StringConverter::toString(mRotateKnot)+"): Press B to change"); // } // }; // class SampleApp : public ExampleApplication // { // public: // // Basic constructor // SampleApp() // {} // // protected: // // // Just override the mandatory create scene method // void createScene(void) // { // // Set some camera params // mCamera->setFarClipDistance(1000); // mCamera->setNearClipDistance(0.25f); // mCamera->setDirection(0,0,1); // // mWindow->getViewport(0)->setBackgroundColour(Ogre::ColourValue(0.1, 0.4, 0.9)); // // // Set up light 0 // Ogre::Light *mLight0 = mSceneMgr->createLight("Light0"); // mLight0->setType(Light::LT_POINT); // mLight0->setPosition(0,200,0); // mLight0->setDiffuseColour(0.9, 0.9, 0.9); // mLight0->setSpecularColour(1, 1, 1); // // // Set up our light camera // mLightCamera = mSceneMgr->createCamera("LightCamera"); // mLightCamera->setProjectionType(Ogre::PT_PERSPECTIVE); // // Not forget to set near+far distance in materials // mLightCamera->setNearClipDistance(8); // mLightCamera->setFarClipDistance(40); // mLightCamera->setAspectRatio(1); // mLightCamera->setFOVy(Ogre::Degree(17.5f)); // mLightCamera->setDebugDisplayEnabled(true); // mLightCameraSN = mSceneMgr->getRootSceneNode()->createChildSceneNode(); // mLightCameraSN->setPosition(0,40,0); // mLightCameraSN->attachObject(mLightCamera); // mLightCameraSN->setDirection(0, -1, 0); // // // Create god rays // createGodRays(mSceneMgr, mLightCameraSN, mLightCamera, _def_NumberOfRays, 0.45f); // // // Create a RRT for depth/shadow map // createLightCameraRTT(); // // // Set a knot // Ogre::Entity *mKnot = mSceneMgr->createEntity("Knot", "knot.mesh"); // mKnot->setMaterialName("Knot"); // mKnot->setVisible(false); // mKnotSN = mLightCameraSN->createChildSceneNode(); // mKnotSN->attachObject(mKnot); // mKnotSN->setPosition(0, 0, -17.5f); // mKnotSN->setScale(0.0225, 0.0225, 0.0225); // // mCamera->lookAt(mLightCameraSN->getPosition()); // // // NOTE: If you change light(Sun) position/orientation, recall it!(IE: each frame) // updateMaterialsParameters(); // // // Add frame listener // mRoot->addFrameListener(new LightShaftsListener(mWindow, mCamera, mSceneMgr)); // } /** Call it every frame if the light position/orientation changes! */ // void updateMaterialsParameters() // { // // Upload current position to light shafts materials // static_cast<Ogre::MaterialPtr>(Ogre::MaterialManager::getSingleton().getByName("GodRays"))-> // getTechnique(0)->getPass(0)->getFragmentProgramParameters()-> // setNamedConstant( "uLightPosition", mLightCameraSN->getPosition()); // static_cast<Ogre::MaterialPtr>(Ogre::MaterialManager::getSingleton().getByName("GodRaysDepth"))-> // getTechnique(0)->getPass(0)->getFragmentProgramParameters()-> // setNamedConstant( "uLightPosition", mLightCameraSN->getPosition()); // // // For projective texturing // const Ogre::Matrix4 PROJECTIONCLIPSPACE2DTOIMAGESPACE_PERSPECTIVE( // 0.5, 0, 0, 0.5, // 0, -0.5, 0, 0.5, // 0, 0, 1, 0, // 0, 0, 0, 1); // // Ogre::Matrix4 TexViewProj = // PROJECTIONCLIPSPACE2DTOIMAGESPACE_PERSPECTIVE * // mLightCamera->getProjectionMatrixWithRSDepth() * // mLightCamera->getViewMatrix(); // // static_cast<Ogre::MaterialPtr>(Ogre::MaterialManager::getSingleton().getByName("GodRays"))-> // getTechnique(0)->getPass(0)->getVertexProgramParameters()-> // setNamedConstant( "uTexViewProj", TexViewProj ); // } bool GodRays::createGodRays(Ogre::SceneManager *mSceneMgr, Ogre::SceneNode* mSceneNode, Ogre::Camera *LightCamera, const int &NumberOfRays, const float &RaysSize) { cout << "creating rays"<< endl; // Calculate how long rays should be // float RaysLength = LightCamera->getFarClipDistance(); float RaysLength = 1000; cout << "length set" << endl; // Get frustum corners to calculate near/far planes dimensions // const Ogre::Vector3 *FrustumCorners = LightCamera->getWorldSpaceCorners(); const Ogre::Vector3 FrustumCorners[8] = {Vector3(1000,1000,1000),Vector3(1500,1000,1000),Vector3(1500,1000,1500),Vector3(1000,1000,1500),Vector3(1000,0,1000),Vector3(1500,0,1000),Vector3(1500,0,1500),Vector3(1000,0,1500)}; cout << "frustum corners founds" << endl; // Calcule far plane dimensions float FarWidth = (FrustumCorners[4] - FrustumCorners[5]).length(), FarHeigth = (FrustumCorners[5] - FrustumCorners[6]).length(); cout << "creating manual god rays " << endl; // Create our manual objetc to create god rays poligons mManualGodRays = mSceneMgr->createManualObject("ManualGodRays"+ID); mManualGodRays->setDynamic(true); // God rays are rendered as triangles with add blend // ______ // / SUN / // /_____/ // /\ A(0,0) // / \ // / \ // / RAY \ // / \ // /B_________\C // // Sun // (-,-) (+,-) // 0,0 1,0 // A _________B // | | // | | // | O | // |(-,+) |(+,+) // |0,1_______|1,1 // C D mManualGodRays->begin("GodRaysSun", Ogre::RenderOperation::OT_TRIANGLE_LIST); mManualGodRays->setRenderQueueGroup(Ogre::RENDER_QUEUE_9); float SunScale = 0.75; // cout << "setting positions" << endl; // Firs triangle ACD // A mManualGodRays->position(-FarWidth*SunScale/2, -FarHeigth*SunScale/2, 0); mManualGodRays->textureCoord(0,0); mManualGodRays->index(0); // C mManualGodRays->position(-FarWidth*SunScale/2, FarHeigth*SunScale/2, 0); mManualGodRays->textureCoord(0,1); mManualGodRays->index(1); // D mManualGodRays->position(FarWidth*SunScale/2, FarHeigth*SunScale/2, 0); mManualGodRays->textureCoord(1,1); mManualGodRays->index(2); // Second triangle ABD // A mManualGodRays->position(-FarWidth*SunScale/2, -FarHeigth*SunScale/2, 0); mManualGodRays->textureCoord(0,0); mManualGodRays->index(3); // B mManualGodRays->position(FarWidth*SunScale/2, -FarHeigth*SunScale/2, 0); mManualGodRays->textureCoord(1,0); mManualGodRays->index(4); // D mManualGodRays->position(FarWidth*SunScale/2, FarHeigth*SunScale/2, 0); mManualGodRays->textureCoord(1,1); mManualGodRays->index(5); mManualGodRays->end(); // Rays mManualGodRays->begin("GodRays", Ogre::RenderOperation::OT_TRIANGLE_LIST); mManualGodRays->setRenderQueueGroup(Ogre::RENDER_QUEUE_9); for(int k = 0; k < NumberOfRays; k++) { float RandomSize = Ogre::Math::RangeRandom(0.5,2); GDData[k].Dimension = RaysSize*RandomSize; GDData[k].Radius[0] = Ogre::Math::RangeRandom(-FarWidth/2, FarWidth/2); GDData[k].MainAngle[0] = Ogre::Degree(Ogre::Math::RangeRandom(0, 45)); GDData[k].RotateAngle[0] = Ogre::Degree(Ogre::Math::RangeRandom(0, 360)); GDData[k].Radius[1] = Ogre::Math::RangeRandom(-FarWidth/2, FarWidth/2); GDData[k].MainAngle[1] = Ogre::Degree(Ogre::Math::RangeRandom(0, 45)); GDData[k].RotateAngle[1] = Ogre::Degree(Ogre::Math::RangeRandom(0, 360)); GDData[k].Radius[3] = GDData[k].Radius[1] - GDData[k].Radius[0]; GDData[k].MainAngle[3] = GDData[k].MainAngle[1] - GDData[k].MainAngle[0]; GDData[k].RotateAngle[3] = GDData[k].RotateAngle[1] - GDData[k].RotateAngle[0]; GDData[k].Radius[2] = GDData[k].Radius[3] / Ogre::Math::RangeRandom(90,100); GDData[k].MainAngle[2] = GDData[k].MainAngle[3] / Ogre::Math::RangeRandom(90,100); GDData[k].RotateAngle[2] = GDData[k].RotateAngle[3] / Ogre::Math::RangeRandom(90,100); GDData[k].Radius[4] = 0; GDData[k].MainAngle[4] = Ogre::Radian(0); GDData[k].RotateAngle[4] = Ogre::Radian(0); Ogre::Vector4 Pos = calculateRayPosition(GDData[k]); // A mManualGodRays->position(0, 0, 0); mManualGodRays->textureCoord(0.5,0); mManualGodRays->index(k*3); // B mManualGodRays->position(Pos.x, Pos.y, -RaysLength); mManualGodRays->textureCoord(0,1); mManualGodRays->index(k*3+1); // C mManualGodRays->position(Pos.z, Pos.w, -RaysLength); mManualGodRays->textureCoord(1,1); mManualGodRays->index(k*3+2); } // cout << "end loop" << endl; mManualGodRays->end(); raySceneNode->attachObject(mManualGodRays); // cout << "rays created" << endl; return true; } void GodRays::createLightCameraRTT() { cout << "creating rtt cam" << endl; // Creat a texture for use as rtt Ogre::TexturePtr LightCameraRTT = Ogre::TextureManager::getSingleton() .createManual("LightDepthMap", "General", Ogre::TEX_TYPE_2D, /*256*256 must be sufficient*/ 256, 256, 0, Ogre::PF_R8G8B8, Ogre::TU_RENDERTARGET); cout << "manually created" << endl; Ogre::RenderTarget* RT_Texture = LightCameraRTT->getBuffer()->getRenderTarget(); cout << "starting viewport" << endl; Ogre::Viewport *RT_Texture_Viewport = RT_Texture->addViewport(mLightCamera); RT_Texture_Viewport->setClearEveryFrame(true); RT_Texture_Viewport->setBackgroundColour(Ogre::ColourValue::White); RT_Texture_Viewport->setOverlaysEnabled(false); RT_Texture_Viewport->setSkiesEnabled(false); cout << "viewport end" << endl; // Add our depth listener RT_Texture->addListener(new LightDepthMapRttListener(mSceneMgr,mManualGodRays)); cout << "LightDepthMapRttListener made" << endl; // Fill the texture in our material /* static_cast<Ogre::MaterialPtr>(Ogre::MaterialManager::getSingleton().getByName("GodRays"))-> getTechnique(0)->getPass(0)->getTextureUnitState(0)-> setTextureName("LightDepthMap");*/ cout << "rtt cam created" << endl; } void GodRays::yaw(Degree degree) { raySceneNode->yaw(degree); } void GodRays::pitch(Degree degree) { raySceneNode->pitch(degree); } void GodRays::roll(Degree degree) { raySceneNode->roll(degree); } void GodRays::move(Vector3 position) { raySceneNode->setPosition(position); }
34.324649
224
0.64199
lerignoux
e4f2bb925d5c929687a8c10830eae36f2b56c563
66,448
cpp
C++
Userland/Libraries/LibJS/Bytecode/ASTCodegen.cpp
gSpera/serenity
5eb0f63c5463ad69286868978ce65fa4705a457c
[ "BSD-2-Clause" ]
2
2022-02-08T09:18:50.000Z
2022-02-21T17:57:23.000Z
Userland/Libraries/LibJS/Bytecode/ASTCodegen.cpp
gSpera/serenity
5eb0f63c5463ad69286868978ce65fa4705a457c
[ "BSD-2-Clause" ]
null
null
null
Userland/Libraries/LibJS/Bytecode/ASTCodegen.cpp
gSpera/serenity
5eb0f63c5463ad69286868978ce65fa4705a457c
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2021, Andreas Kling <kling@serenityos.org> * Copyright (c) 2021, Linus Groh <linusg@serenityos.org> * Copyright (c) 2021, Gunnar Beutner <gbeutner@serenityos.org> * Copyright (c) 2021, Marcin Gasperowicz <xnooga@gmail.com> * * SPDX-License-Identifier: BSD-2-Clause */ #include <AK/Format.h> #include <LibJS/AST.h> #include <LibJS/Bytecode/Generator.h> #include <LibJS/Bytecode/Instruction.h> #include <LibJS/Bytecode/Op.h> #include <LibJS/Bytecode/Register.h> #include <LibJS/Bytecode/StringTable.h> #include <LibJS/Runtime/Environment.h> namespace JS { Bytecode::CodeGenerationErrorOr<void> ASTNode::generate_bytecode(Bytecode::Generator&) const { return Bytecode::CodeGenerationError { this, "Missing generate_bytecode()"sv, }; } Bytecode::CodeGenerationErrorOr<void> ScopeNode::generate_bytecode(Bytecode::Generator& generator) const { Optional<Bytecode::CodeGenerationError> maybe_error; size_t pushed_scope_count = 0; auto const failing_completion = Completion(Completion::Type::Throw, {}, {}); if (is<BlockStatement>(*this) || is<SwitchStatement>(*this)) { // Perform the steps of BlockDeclarationInstantiation. if (has_lexical_declarations()) { generator.begin_variable_scope(Bytecode::Generator::BindingMode::Lexical, Bytecode::Generator::SurroundingScopeKind::Block); pushed_scope_count++; } (void)for_each_lexically_scoped_declaration([&](Declaration const& declaration) -> ThrowCompletionOr<void> { auto is_constant_declaration = declaration.is_constant_declaration(); declaration.for_each_bound_name([&](auto const& name) { auto index = generator.intern_identifier(name); if (is_constant_declaration || !generator.has_binding(index)) { generator.register_binding(index); generator.emit<Bytecode::Op::CreateVariable>(index, Bytecode::Op::EnvironmentMode::Lexical, is_constant_declaration); } }); if (is<FunctionDeclaration>(declaration)) { auto& function_declaration = static_cast<FunctionDeclaration const&>(declaration); auto const& name = function_declaration.name(); auto index = generator.intern_identifier(name); generator.emit<Bytecode::Op::NewFunction>(function_declaration); generator.emit<Bytecode::Op::SetVariable>(index, Bytecode::Op::SetVariable::InitializationMode::Initialize); } return {}; }); } else if (is<Program>(*this)) { // Perform the steps of GlobalDeclarationInstantiation. generator.begin_variable_scope(Bytecode::Generator::BindingMode::Global, Bytecode::Generator::SurroundingScopeKind::Global); pushed_scope_count++; // 1. Let lexNames be the LexicallyDeclaredNames of script. // 2. Let varNames be the VarDeclaredNames of script. // 3. For each element name of lexNames, do (void)for_each_lexically_declared_name([&](auto const& name) -> ThrowCompletionOr<void> { auto identifier = generator.intern_identifier(name); // a. If env.HasVarDeclaration(name) is true, throw a SyntaxError exception. // b. If env.HasLexicalDeclaration(name) is true, throw a SyntaxError exception. if (generator.has_binding(identifier)) { // FIXME: Throw an actual SyntaxError instance. generator.emit<Bytecode::Op::NewString>(generator.intern_string(String::formatted("SyntaxError: toplevel variable already declared: {}", name))); generator.emit<Bytecode::Op::Throw>(); return {}; } // FIXME: c. If hasRestrictedGlobalProperty is true, throw a SyntaxError exception. // d. If hasRestrictedGlobal is true, throw a SyntaxError exception. return {}; }); // 4. For each element name of varNames, do (void)for_each_var_declared_name([&](auto const& name) -> ThrowCompletionOr<void> { auto identifier = generator.intern_identifier(name); // a. If env.HasLexicalDeclaration(name) is true, throw a SyntaxError exception. if (generator.has_binding(identifier)) { // FIXME: Throw an actual SyntaxError instance. generator.emit<Bytecode::Op::NewString>(generator.intern_string(String::formatted("SyntaxError: toplevel variable already declared: {}", name))); generator.emit<Bytecode::Op::Throw>(); } return {}; }); // 5. Let varDeclarations be the VarScopedDeclarations of script. // 6. Let functionsToInitialize be a new empty List. Vector<FunctionDeclaration const&> functions_to_initialize; // 7. Let declaredFunctionNames be a new empty List. HashTable<FlyString> declared_function_names; // 8. For each element d of varDeclarations, in reverse List order, do (void)for_each_var_function_declaration_in_reverse_order([&](FunctionDeclaration const& function) -> ThrowCompletionOr<void> { // a. If d is neither a VariableDeclaration nor a ForBinding nor a BindingIdentifier, then // i. Assert: d is either a FunctionDeclaration, a GeneratorDeclaration, an AsyncFunctionDeclaration, or an AsyncGeneratorDeclaration. // Note: This is checked in for_each_var_function_declaration_in_reverse_order. // ii. NOTE: If there are multiple function declarations for the same name, the last declaration is used. // iii. Let fn be the sole element of the BoundNames of d. // iv. If fn is not an element of declaredFunctionNames, then if (declared_function_names.set(function.name()) != AK::HashSetResult::InsertedNewEntry) return {}; // FIXME: 1. Let fnDefinable be ? env.CanDeclareGlobalFunction(fn). // FIXME: 2. If fnDefinable is false, throw a TypeError exception. // 3. Append fn to declaredFunctionNames. // Note: Already done in step iv. above. // 4. Insert d as the first element of functionsToInitialize. functions_to_initialize.prepend(function); return {}; }); // 9. Let declaredVarNames be a new empty List. HashTable<FlyString> declared_var_names; // 10. For each element d of varDeclarations, do (void)for_each_var_scoped_variable_declaration([&](Declaration const& declaration) { // a. If d is a VariableDeclaration, a ForBinding, or a BindingIdentifier, then // Note: This is done in for_each_var_scoped_variable_declaration. // i. For each String vn of the BoundNames of d, do return declaration.for_each_bound_name([&](auto const& name) -> ThrowCompletionOr<void> { // 1. If vn is not an element of declaredFunctionNames, then if (declared_function_names.contains(name)) return {}; // FIXME: a. Let vnDefinable be ? env.CanDeclareGlobalVar(vn). // FIXME: b. If vnDefinable is false, throw a TypeError exception. // c. If vn is not an element of declaredVarNames, then // i. Append vn to declaredVarNames. declared_var_names.set(name); return {}; }); }); // 11. NOTE: No abnormal terminations occur after this algorithm step if the global object is an ordinary object. However, if the global object is a Proxy exotic object it may exhibit behaviours that cause abnormal terminations in some of the following steps. // 12. NOTE: Annex B.3.2.2 adds additional steps at this point. // 12. Let strict be IsStrict of script. // 13. If strict is false, then if (!verify_cast<Program>(*this).is_strict_mode()) { // a. Let declaredFunctionOrVarNames be the list-concatenation of declaredFunctionNames and declaredVarNames. // b. For each FunctionDeclaration f that is directly contained in the StatementList of a Block, CaseClause, or DefaultClause Contained within script, do (void)for_each_function_hoistable_with_annexB_extension([&](FunctionDeclaration& function_declaration) { // i. Let F be StringValue of the BindingIdentifier of f. auto& function_name = function_declaration.name(); // ii. If replacing the FunctionDeclaration f with a VariableStatement that has F as a BindingIdentifier would not produce any Early Errors for script, then // Note: This step is already performed during parsing and for_each_function_hoistable_with_annexB_extension so this always passes here. // 1. If env.HasLexicalDeclaration(F) is false, then auto index = generator.intern_identifier(function_name); if (generator.has_binding(index, Bytecode::Generator::BindingMode::Lexical)) return; // FIXME: a. Let fnDefinable be ? env.CanDeclareGlobalVar(F). // b. If fnDefinable is true, then // i. NOTE: A var binding for F is only instantiated here if it is neither a VarDeclaredName nor the name of another FunctionDeclaration. // ii. If declaredFunctionOrVarNames does not contain F, then if (!declared_function_names.contains(function_name) && !declared_var_names.contains(function_name)) { // i. Perform ? env.CreateGlobalVarBinding(F, false). generator.emit<Bytecode::Op::CreateVariable>(index, Bytecode::Op::EnvironmentMode::Var, false); // ii. Append F to declaredFunctionOrVarNames. declared_function_names.set(function_name); } // iii. When the FunctionDeclaration f is evaluated, perform the following steps in place of the FunctionDeclaration Evaluation algorithm provided in 15.2.6: // i. Let genv be the running execution context's VariableEnvironment. // ii. Let benv be the running execution context's LexicalEnvironment. // iii. Let fobj be ! benv.GetBindingValue(F, false). // iv. Perform ? genv.SetMutableBinding(F, fobj, false). // v. Return NormalCompletion(empty). function_declaration.set_should_do_additional_annexB_steps(); }); } // 15. For each element d of lexDeclarations, do (void)for_each_lexically_scoped_declaration([&](Declaration const& declaration) -> ThrowCompletionOr<void> { // a. NOTE: Lexically declared names are only instantiated here but not initialized. // b. For each element dn of the BoundNames of d, do return declaration.for_each_bound_name([&](auto const& name) -> ThrowCompletionOr<void> { auto identifier = generator.intern_identifier(name); // i. If IsConstantDeclaration of d is true, then generator.register_binding(identifier); if (declaration.is_constant_declaration()) { // 1. Perform ? env.CreateImmutableBinding(dn, true). generator.emit<Bytecode::Op::CreateVariable>(identifier, Bytecode::Op::EnvironmentMode::Lexical, true); } else { // ii. Else, // 1. Perform ? env.CreateMutableBinding(dn, false). generator.emit<Bytecode::Op::CreateVariable>(identifier, Bytecode::Op::EnvironmentMode::Lexical, false); } return {}; }); }); // 16. For each Parse Node f of functionsToInitialize, do for (auto& function_declaration : functions_to_initialize) { // FIXME: Do this more correctly. // a. Let fn be the sole element of the BoundNames of f. // b. Let fo be InstantiateFunctionObject of f with arguments env and privateEnv. generator.emit<Bytecode::Op::NewFunction>(function_declaration); // c. Perform ? env.CreateGlobalFunctionBinding(fn, fo, false). auto const& name = function_declaration.name(); auto index = generator.intern_identifier(name); if (!generator.has_binding(index)) { generator.register_binding(index, Bytecode::Generator::BindingMode::Var); generator.emit<Bytecode::Op::CreateVariable>(index, Bytecode::Op::EnvironmentMode::Lexical, false); } generator.emit<Bytecode::Op::SetVariable>(index, Bytecode::Op::SetVariable::InitializationMode::Initialize); } // 17. For each String vn of declaredVarNames, do // a. Perform ? env.CreateGlobalVarBinding(vn, false). for (auto& var_name : declared_var_names) generator.register_binding(generator.intern_identifier(var_name), Bytecode::Generator::BindingMode::Var); } else { // Perform the steps of FunctionDeclarationInstantiation. generator.begin_variable_scope(Bytecode::Generator::BindingMode::Var, Bytecode::Generator::SurroundingScopeKind::Function); pushed_scope_count++; if (has_lexical_declarations()) { generator.begin_variable_scope(Bytecode::Generator::BindingMode::Lexical, Bytecode::Generator::SurroundingScopeKind::Function); pushed_scope_count++; } // FIXME: Implement this boi correctly. (void)for_each_lexically_scoped_declaration([&](Declaration const& declaration) -> ThrowCompletionOr<void> { auto is_constant_declaration = declaration.is_constant_declaration(); declaration.for_each_bound_name([&](auto const& name) { auto index = generator.intern_identifier(name); if (is_constant_declaration || !generator.has_binding(index)) { generator.register_binding(index); generator.emit<Bytecode::Op::CreateVariable>(index, Bytecode::Op::EnvironmentMode::Lexical, is_constant_declaration); } }); if (is<FunctionDeclaration>(declaration)) { auto& function_declaration = static_cast<FunctionDeclaration const&>(declaration); if (auto result = function_declaration.generate_bytecode(generator); result.is_error()) { maybe_error = result.release_error(); // To make `for_each_lexically_scoped_declaration` happy. return failing_completion; } auto const& name = function_declaration.name(); auto index = generator.intern_identifier(name); if (!generator.has_binding(index)) { generator.register_binding(index); generator.emit<Bytecode::Op::CreateVariable>(index, Bytecode::Op::EnvironmentMode::Lexical, false); } generator.emit<Bytecode::Op::SetVariable>(index, Bytecode::Op::SetVariable::InitializationMode::InitializeOrSet); } return {}; }); } if (maybe_error.has_value()) return maybe_error.release_value(); for (auto& child : children()) { TRY(child.generate_bytecode(generator)); if (generator.is_current_block_terminated()) break; } for (size_t i = 0; i < pushed_scope_count; ++i) generator.end_variable_scope(); return {}; } Bytecode::CodeGenerationErrorOr<void> EmptyStatement::generate_bytecode(Bytecode::Generator&) const { return {}; } Bytecode::CodeGenerationErrorOr<void> ExpressionStatement::generate_bytecode(Bytecode::Generator& generator) const { return m_expression->generate_bytecode(generator); } Bytecode::CodeGenerationErrorOr<void> BinaryExpression::generate_bytecode(Bytecode::Generator& generator) const { TRY(m_lhs->generate_bytecode(generator)); auto lhs_reg = generator.allocate_register(); generator.emit<Bytecode::Op::Store>(lhs_reg); TRY(m_rhs->generate_bytecode(generator)); switch (m_op) { case BinaryOp::Addition: generator.emit<Bytecode::Op::Add>(lhs_reg); break; case BinaryOp::Subtraction: generator.emit<Bytecode::Op::Sub>(lhs_reg); break; case BinaryOp::Multiplication: generator.emit<Bytecode::Op::Mul>(lhs_reg); break; case BinaryOp::Division: generator.emit<Bytecode::Op::Div>(lhs_reg); break; case BinaryOp::Modulo: generator.emit<Bytecode::Op::Mod>(lhs_reg); break; case BinaryOp::Exponentiation: generator.emit<Bytecode::Op::Exp>(lhs_reg); break; case BinaryOp::GreaterThan: generator.emit<Bytecode::Op::GreaterThan>(lhs_reg); break; case BinaryOp::GreaterThanEquals: generator.emit<Bytecode::Op::GreaterThanEquals>(lhs_reg); break; case BinaryOp::LessThan: generator.emit<Bytecode::Op::LessThan>(lhs_reg); break; case BinaryOp::LessThanEquals: generator.emit<Bytecode::Op::LessThanEquals>(lhs_reg); break; case BinaryOp::LooselyInequals: generator.emit<Bytecode::Op::LooselyInequals>(lhs_reg); break; case BinaryOp::LooselyEquals: generator.emit<Bytecode::Op::LooselyEquals>(lhs_reg); break; case BinaryOp::StrictlyInequals: generator.emit<Bytecode::Op::StrictlyInequals>(lhs_reg); break; case BinaryOp::StrictlyEquals: generator.emit<Bytecode::Op::StrictlyEquals>(lhs_reg); break; case BinaryOp::BitwiseAnd: generator.emit<Bytecode::Op::BitwiseAnd>(lhs_reg); break; case BinaryOp::BitwiseOr: generator.emit<Bytecode::Op::BitwiseOr>(lhs_reg); break; case BinaryOp::BitwiseXor: generator.emit<Bytecode::Op::BitwiseXor>(lhs_reg); break; case BinaryOp::LeftShift: generator.emit<Bytecode::Op::LeftShift>(lhs_reg); break; case BinaryOp::RightShift: generator.emit<Bytecode::Op::RightShift>(lhs_reg); break; case BinaryOp::UnsignedRightShift: generator.emit<Bytecode::Op::UnsignedRightShift>(lhs_reg); break; case BinaryOp::In: generator.emit<Bytecode::Op::In>(lhs_reg); break; case BinaryOp::InstanceOf: generator.emit<Bytecode::Op::InstanceOf>(lhs_reg); break; default: VERIFY_NOT_REACHED(); } return {}; } Bytecode::CodeGenerationErrorOr<void> LogicalExpression::generate_bytecode(Bytecode::Generator& generator) const { TRY(m_lhs->generate_bytecode(generator)); // lhs // jump op (true) end (false) rhs // rhs // jump always (true) end // end auto& rhs_block = generator.make_block(); auto& end_block = generator.make_block(); switch (m_op) { case LogicalOp::And: generator.emit<Bytecode::Op::JumpConditional>().set_targets( Bytecode::Label { rhs_block }, Bytecode::Label { end_block }); break; case LogicalOp::Or: generator.emit<Bytecode::Op::JumpConditional>().set_targets( Bytecode::Label { end_block }, Bytecode::Label { rhs_block }); break; case LogicalOp::NullishCoalescing: generator.emit<Bytecode::Op::JumpNullish>().set_targets( Bytecode::Label { rhs_block }, Bytecode::Label { end_block }); break; default: VERIFY_NOT_REACHED(); } generator.switch_to_basic_block(rhs_block); TRY(m_rhs->generate_bytecode(generator)); generator.emit<Bytecode::Op::Jump>().set_targets( Bytecode::Label { end_block }, {}); generator.switch_to_basic_block(end_block); return {}; } Bytecode::CodeGenerationErrorOr<void> UnaryExpression::generate_bytecode(Bytecode::Generator& generator) const { TRY(m_lhs->generate_bytecode(generator)); switch (m_op) { case UnaryOp::BitwiseNot: generator.emit<Bytecode::Op::BitwiseNot>(); break; case UnaryOp::Not: generator.emit<Bytecode::Op::Not>(); break; case UnaryOp::Plus: generator.emit<Bytecode::Op::UnaryPlus>(); break; case UnaryOp::Minus: generator.emit<Bytecode::Op::UnaryMinus>(); break; case UnaryOp::Typeof: generator.emit<Bytecode::Op::Typeof>(); break; case UnaryOp::Void: generator.emit<Bytecode::Op::LoadImmediate>(js_undefined()); break; default: return Bytecode::CodeGenerationError { this, "Unimplemented operation"sv, }; } return {}; } Bytecode::CodeGenerationErrorOr<void> NumericLiteral::generate_bytecode(Bytecode::Generator& generator) const { generator.emit<Bytecode::Op::LoadImmediate>(m_value); return {}; } Bytecode::CodeGenerationErrorOr<void> BooleanLiteral::generate_bytecode(Bytecode::Generator& generator) const { generator.emit<Bytecode::Op::LoadImmediate>(Value(m_value)); return {}; } Bytecode::CodeGenerationErrorOr<void> NullLiteral::generate_bytecode(Bytecode::Generator& generator) const { generator.emit<Bytecode::Op::LoadImmediate>(js_null()); return {}; } Bytecode::CodeGenerationErrorOr<void> BigIntLiteral::generate_bytecode(Bytecode::Generator& generator) const { generator.emit<Bytecode::Op::NewBigInt>(Crypto::SignedBigInteger::from_base(10, m_value.substring(0, m_value.length() - 1))); return {}; } Bytecode::CodeGenerationErrorOr<void> StringLiteral::generate_bytecode(Bytecode::Generator& generator) const { generator.emit<Bytecode::Op::NewString>(generator.intern_string(m_value)); return {}; } Bytecode::CodeGenerationErrorOr<void> RegExpLiteral::generate_bytecode(Bytecode::Generator& generator) const { auto source_index = generator.intern_string(m_pattern); auto flags_index = generator.intern_string(m_flags); generator.emit<Bytecode::Op::NewRegExp>(source_index, flags_index); return {}; } Bytecode::CodeGenerationErrorOr<void> Identifier::generate_bytecode(Bytecode::Generator& generator) const { generator.emit<Bytecode::Op::GetVariable>(generator.intern_identifier(m_string)); return {}; } Bytecode::CodeGenerationErrorOr<void> AssignmentExpression::generate_bytecode(Bytecode::Generator& generator) const { // FIXME: Implement this for BindingPatterns too. auto& lhs = m_lhs.get<NonnullRefPtr<Expression>>(); if (m_op == AssignmentOp::Assignment) { TRY(m_rhs->generate_bytecode(generator)); return generator.emit_store_to_reference(lhs); } TRY(generator.emit_load_from_reference(lhs)); Bytecode::BasicBlock* rhs_block_ptr { nullptr }; Bytecode::BasicBlock* end_block_ptr { nullptr }; // Logical assignments short circuit. if (m_op == AssignmentOp::AndAssignment) { // &&= rhs_block_ptr = &generator.make_block(); end_block_ptr = &generator.make_block(); generator.emit<Bytecode::Op::JumpConditional>().set_targets( Bytecode::Label { *rhs_block_ptr }, Bytecode::Label { *end_block_ptr }); } else if (m_op == AssignmentOp::OrAssignment) { // ||= rhs_block_ptr = &generator.make_block(); end_block_ptr = &generator.make_block(); generator.emit<Bytecode::Op::JumpConditional>().set_targets( Bytecode::Label { *end_block_ptr }, Bytecode::Label { *rhs_block_ptr }); } else if (m_op == AssignmentOp::NullishAssignment) { // ??= rhs_block_ptr = &generator.make_block(); end_block_ptr = &generator.make_block(); generator.emit<Bytecode::Op::JumpNullish>().set_targets( Bytecode::Label { *rhs_block_ptr }, Bytecode::Label { *end_block_ptr }); } if (rhs_block_ptr) generator.switch_to_basic_block(*rhs_block_ptr); // lhs_reg is a part of the rhs_block because the store isn't necessary // if the logical assignment condition fails. auto lhs_reg = generator.allocate_register(); generator.emit<Bytecode::Op::Store>(lhs_reg); TRY(m_rhs->generate_bytecode(generator)); switch (m_op) { case AssignmentOp::AdditionAssignment: generator.emit<Bytecode::Op::Add>(lhs_reg); break; case AssignmentOp::SubtractionAssignment: generator.emit<Bytecode::Op::Sub>(lhs_reg); break; case AssignmentOp::MultiplicationAssignment: generator.emit<Bytecode::Op::Mul>(lhs_reg); break; case AssignmentOp::DivisionAssignment: generator.emit<Bytecode::Op::Div>(lhs_reg); break; case AssignmentOp::ModuloAssignment: generator.emit<Bytecode::Op::Mod>(lhs_reg); break; case AssignmentOp::ExponentiationAssignment: generator.emit<Bytecode::Op::Exp>(lhs_reg); break; case AssignmentOp::BitwiseAndAssignment: generator.emit<Bytecode::Op::BitwiseAnd>(lhs_reg); break; case AssignmentOp::BitwiseOrAssignment: generator.emit<Bytecode::Op::BitwiseOr>(lhs_reg); break; case AssignmentOp::BitwiseXorAssignment: generator.emit<Bytecode::Op::BitwiseXor>(lhs_reg); break; case AssignmentOp::LeftShiftAssignment: generator.emit<Bytecode::Op::LeftShift>(lhs_reg); break; case AssignmentOp::RightShiftAssignment: generator.emit<Bytecode::Op::RightShift>(lhs_reg); break; case AssignmentOp::UnsignedRightShiftAssignment: generator.emit<Bytecode::Op::UnsignedRightShift>(lhs_reg); break; case AssignmentOp::AndAssignment: case AssignmentOp::OrAssignment: case AssignmentOp::NullishAssignment: break; // These are handled above. default: return Bytecode::CodeGenerationError { this, "Unimplemented operation"sv, }; } TRY(generator.emit_store_to_reference(lhs)); if (end_block_ptr) { generator.emit<Bytecode::Op::Jump>().set_targets( Bytecode::Label { *end_block_ptr }, {}); generator.switch_to_basic_block(*end_block_ptr); } return {}; } Bytecode::CodeGenerationErrorOr<void> WhileStatement::generate_bytecode(Bytecode::Generator& generator) const { // test // jump if_false (true) end (false) body // body // jump always (true) test // end auto& test_block = generator.make_block(); auto& body_block = generator.make_block(); auto& end_block = generator.make_block(); // Init result register generator.emit<Bytecode::Op::LoadImmediate>(js_undefined()); auto result_reg = generator.allocate_register(); generator.emit<Bytecode::Op::Store>(result_reg); // jump to the test block generator.emit<Bytecode::Op::Jump>().set_targets( Bytecode::Label { test_block }, {}); generator.switch_to_basic_block(test_block); TRY(m_test->generate_bytecode(generator)); generator.emit<Bytecode::Op::JumpConditional>().set_targets( Bytecode::Label { body_block }, Bytecode::Label { end_block }); generator.switch_to_basic_block(body_block); generator.begin_continuable_scope(Bytecode::Label { test_block }); generator.begin_breakable_scope(Bytecode::Label { end_block }); TRY(m_body->generate_bytecode(generator)); if (!generator.is_current_block_terminated()) { generator.emit<Bytecode::Op::Jump>().set_targets( Bytecode::Label { test_block }, {}); generator.end_continuable_scope(); generator.end_breakable_scope(); generator.switch_to_basic_block(end_block); generator.emit<Bytecode::Op::Load>(result_reg); } return {}; } Bytecode::CodeGenerationErrorOr<void> DoWhileStatement::generate_bytecode(Bytecode::Generator& generator) const { // jump always (true) body // test // jump if_false (true) end (false) body // body // jump always (true) test // end auto& test_block = generator.make_block(); auto& body_block = generator.make_block(); auto& end_block = generator.make_block(); // Init result register generator.emit<Bytecode::Op::LoadImmediate>(js_undefined()); auto result_reg = generator.allocate_register(); generator.emit<Bytecode::Op::Store>(result_reg); // jump to the body block generator.emit<Bytecode::Op::Jump>().set_targets( Bytecode::Label { body_block }, {}); generator.switch_to_basic_block(test_block); TRY(m_test->generate_bytecode(generator)); generator.emit<Bytecode::Op::JumpConditional>().set_targets( Bytecode::Label { body_block }, Bytecode::Label { end_block }); generator.switch_to_basic_block(body_block); generator.begin_continuable_scope(Bytecode::Label { test_block }); generator.begin_breakable_scope(Bytecode::Label { end_block }); TRY(m_body->generate_bytecode(generator)); if (!generator.is_current_block_terminated()) { generator.emit<Bytecode::Op::Jump>().set_targets( Bytecode::Label { test_block }, {}); generator.end_continuable_scope(); generator.end_breakable_scope(); generator.switch_to_basic_block(end_block); generator.emit<Bytecode::Op::Load>(result_reg); } return {}; } Bytecode::CodeGenerationErrorOr<void> ForStatement::generate_bytecode(Bytecode::Generator& generator) const { // init // jump always (true) test // test // jump if_true (true) body (false) end // body // jump always (true) update // update // jump always (true) test // end // If 'test' is missing, fuse the 'test' and 'body' basic blocks // If 'update' is missing, fuse the 'body' and 'update' basic blocks Bytecode::BasicBlock* test_block_ptr { nullptr }; Bytecode::BasicBlock* body_block_ptr { nullptr }; Bytecode::BasicBlock* update_block_ptr { nullptr }; auto& end_block = generator.make_block(); if (m_init) TRY(m_init->generate_bytecode(generator)); body_block_ptr = &generator.make_block(); if (m_test) test_block_ptr = &generator.make_block(); else test_block_ptr = body_block_ptr; if (m_update) update_block_ptr = &generator.make_block(); else update_block_ptr = body_block_ptr; generator.emit<Bytecode::Op::LoadImmediate>(js_undefined()); auto result_reg = generator.allocate_register(); generator.emit<Bytecode::Op::Store>(result_reg); generator.emit<Bytecode::Op::Jump>().set_targets( Bytecode::Label { *test_block_ptr }, {}); if (m_test) { generator.switch_to_basic_block(*test_block_ptr); TRY(m_test->generate_bytecode(generator)); generator.emit<Bytecode::Op::JumpConditional>().set_targets( Bytecode::Label { *body_block_ptr }, Bytecode::Label { end_block }); } generator.switch_to_basic_block(*body_block_ptr); generator.begin_continuable_scope(Bytecode::Label { *update_block_ptr }); generator.begin_breakable_scope(Bytecode::Label { end_block }); TRY(m_body->generate_bytecode(generator)); generator.end_continuable_scope(); if (!generator.is_current_block_terminated()) { if (m_update) { generator.emit<Bytecode::Op::Jump>().set_targets( Bytecode::Label { *update_block_ptr }, {}); generator.switch_to_basic_block(*update_block_ptr); TRY(m_update->generate_bytecode(generator)); } generator.emit<Bytecode::Op::Jump>().set_targets( Bytecode::Label { *test_block_ptr }, {}); generator.end_breakable_scope(); generator.switch_to_basic_block(end_block); generator.emit<Bytecode::Op::Load>(result_reg); } return {}; } Bytecode::CodeGenerationErrorOr<void> ObjectExpression::generate_bytecode(Bytecode::Generator& generator) const { generator.emit<Bytecode::Op::NewObject>(); if (m_properties.is_empty()) return {}; auto object_reg = generator.allocate_register(); generator.emit<Bytecode::Op::Store>(object_reg); for (auto& property : m_properties) { if (property.type() != ObjectProperty::Type::KeyValue) return Bytecode::CodeGenerationError { this, "Unimplemented property kind"sv, }; if (is<StringLiteral>(property.key())) { auto& string_literal = static_cast<StringLiteral const&>(property.key()); Bytecode::IdentifierTableIndex key_name = generator.intern_identifier(string_literal.value()); TRY(property.value().generate_bytecode(generator)); generator.emit<Bytecode::Op::PutById>(object_reg, key_name); } else { TRY(property.key().generate_bytecode(generator)); auto property_reg = generator.allocate_register(); generator.emit<Bytecode::Op::Store>(property_reg); TRY(property.value().generate_bytecode(generator)); generator.emit<Bytecode::Op::PutByValue>(object_reg, property_reg); } } generator.emit<Bytecode::Op::Load>(object_reg); return {}; } Bytecode::CodeGenerationErrorOr<void> ArrayExpression::generate_bytecode(Bytecode::Generator& generator) const { Vector<Bytecode::Register> element_regs; for (auto& element : m_elements) { if (element) { TRY(element->generate_bytecode(generator)); if (is<SpreadExpression>(*element)) { return Bytecode::CodeGenerationError { this, "Unimplemented element kind: SpreadExpression"sv, }; } } else { generator.emit<Bytecode::Op::LoadImmediate>(Value {}); } auto element_reg = generator.allocate_register(); generator.emit<Bytecode::Op::Store>(element_reg); element_regs.append(element_reg); } generator.emit_with_extra_register_slots<Bytecode::Op::NewArray>(element_regs.size(), element_regs); return {}; } Bytecode::CodeGenerationErrorOr<void> MemberExpression::generate_bytecode(Bytecode::Generator& generator) const { return generator.emit_load_from_reference(*this); } Bytecode::CodeGenerationErrorOr<void> FunctionDeclaration::generate_bytecode(Bytecode::Generator& generator) const { if (m_is_hoisted) { auto index = generator.intern_identifier(name()); generator.emit<Bytecode::Op::GetVariable>(index); generator.emit<Bytecode::Op::SetVariable>(index, Bytecode::Op::SetVariable::InitializationMode::Initialize, Bytecode::Op::EnvironmentMode::Var); } return {}; } Bytecode::CodeGenerationErrorOr<void> FunctionExpression::generate_bytecode(Bytecode::Generator& generator) const { generator.emit<Bytecode::Op::NewFunction>(*this); return {}; } static Bytecode::CodeGenerationErrorOr<void> generate_binding_pattern_bytecode(Bytecode::Generator& generator, BindingPattern const& pattern, Bytecode::Op::SetVariable::InitializationMode, Bytecode::Register const& value_reg); static Bytecode::CodeGenerationErrorOr<void> generate_object_binding_pattern_bytecode(Bytecode::Generator& generator, BindingPattern const& pattern, Bytecode::Op::SetVariable::InitializationMode initialization_mode, Bytecode::Register const& value_reg) { Vector<Bytecode::Register> excluded_property_names; auto has_rest = false; if (pattern.entries.size() > 0) has_rest = pattern.entries[pattern.entries.size() - 1].is_rest; for (auto& [name, alias, initializer, is_rest] : pattern.entries) { if (is_rest) { VERIFY(name.has<NonnullRefPtr<Identifier>>()); VERIFY(alias.has<Empty>()); VERIFY(!initializer); auto identifier = name.get<NonnullRefPtr<Identifier>>()->string(); auto interned_identifier = generator.intern_identifier(identifier); generator.emit_with_extra_register_slots<Bytecode::Op::CopyObjectExcludingProperties>(excluded_property_names.size(), value_reg, excluded_property_names); generator.emit<Bytecode::Op::SetVariable>(interned_identifier, initialization_mode); return {}; } Bytecode::StringTableIndex name_index; if (name.has<NonnullRefPtr<Identifier>>()) { auto identifier = name.get<NonnullRefPtr<Identifier>>()->string(); name_index = generator.intern_string(identifier); if (has_rest) { auto excluded_name_reg = generator.allocate_register(); excluded_property_names.append(excluded_name_reg); generator.emit<Bytecode::Op::NewString>(name_index); generator.emit<Bytecode::Op::Store>(excluded_name_reg); } generator.emit<Bytecode::Op::Load>(value_reg); generator.emit<Bytecode::Op::GetById>(generator.intern_identifier(identifier)); } else { auto expression = name.get<NonnullRefPtr<Expression>>(); TRY(expression->generate_bytecode(generator)); if (has_rest) { auto excluded_name_reg = generator.allocate_register(); excluded_property_names.append(excluded_name_reg); generator.emit<Bytecode::Op::Store>(excluded_name_reg); } generator.emit<Bytecode::Op::GetByValue>(value_reg); } if (initializer) { auto& if_undefined_block = generator.make_block(); auto& if_not_undefined_block = generator.make_block(); generator.emit<Bytecode::Op::JumpUndefined>().set_targets( Bytecode::Label { if_undefined_block }, Bytecode::Label { if_not_undefined_block }); generator.switch_to_basic_block(if_undefined_block); TRY(initializer->generate_bytecode(generator)); generator.emit<Bytecode::Op::Jump>().set_targets( Bytecode::Label { if_not_undefined_block }, {}); generator.switch_to_basic_block(if_not_undefined_block); } if (alias.has<NonnullRefPtr<BindingPattern>>()) { auto& binding_pattern = *alias.get<NonnullRefPtr<BindingPattern>>(); auto nested_value_reg = generator.allocate_register(); generator.emit<Bytecode::Op::Store>(nested_value_reg); TRY(generate_binding_pattern_bytecode(generator, binding_pattern, initialization_mode, nested_value_reg)); } else if (alias.has<Empty>()) { if (name.has<NonnullRefPtr<Expression>>()) { // This needs some sort of SetVariableByValue opcode, as it's a runtime binding return Bytecode::CodeGenerationError { name.get<NonnullRefPtr<Expression>>().ptr(), "Unimplemented name/alias pair: Empty/Expression"sv, }; } auto& identifier = alias.get<NonnullRefPtr<Identifier>>()->string(); generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(identifier), initialization_mode); } else { auto& identifier = alias.get<NonnullRefPtr<Identifier>>()->string(); generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(identifier), initialization_mode); } } return {}; } static Bytecode::CodeGenerationErrorOr<void> generate_array_binding_pattern_bytecode(Bytecode::Generator& generator, BindingPattern const& pattern, Bytecode::Op::SetVariable::InitializationMode initialization_mode, Bytecode::Register const& value_reg) { /* * Consider the following destructuring assignment: * * let [a, b, c, d, e] = o; * * It would be fairly trivial to just loop through this iterator, getting the value * at each step and assigning them to the binding sequentially. However, this is not * correct: once an iterator is exhausted, it must not be called again. This complicates * the bytecode. In order to accomplish this, we do the following: * * - Reserve a special boolean register which holds 'true' if the iterator is exhausted, * and false otherwise * - When we are retrieving the value which should be bound, we first check this register. * If it is 'true', we load undefined into the accumulator. Otherwise, we grab the next * value from the iterator and store it into the accumulator. * * Note that the is_exhausted register does not need to be loaded with false because the * first IteratorNext bytecode is _not_ proceeded by an exhausted check, as it is * unnecessary. */ auto is_iterator_exhausted_register = generator.allocate_register(); auto iterator_reg = generator.allocate_register(); generator.emit<Bytecode::Op::Load>(value_reg); generator.emit<Bytecode::Op::GetIterator>(); generator.emit<Bytecode::Op::Store>(iterator_reg); bool first = true; auto temp_iterator_result_reg = generator.allocate_register(); auto assign_accumulator_to_alias = [&](auto& alias) { return alias.visit( [&](Empty) -> Bytecode::CodeGenerationErrorOr<void> { // This element is an elision return {}; }, [&](NonnullRefPtr<Identifier> const& identifier) -> Bytecode::CodeGenerationErrorOr<void> { auto interned_index = generator.intern_identifier(identifier->string()); generator.emit<Bytecode::Op::SetVariable>(interned_index, initialization_mode); return {}; }, [&](NonnullRefPtr<BindingPattern> const& pattern) -> Bytecode::CodeGenerationErrorOr<void> { // Store the accumulator value in a permanent register auto target_reg = generator.allocate_register(); generator.emit<Bytecode::Op::Store>(target_reg); return generate_binding_pattern_bytecode(generator, pattern, initialization_mode, target_reg); }, [&](NonnullRefPtr<MemberExpression> const& expr) -> Bytecode::CodeGenerationErrorOr<void> { return Bytecode::CodeGenerationError { expr.ptr(), "Unimplemented alias mode: MemberExpression"sv, }; }); }; for (auto& [name, alias, initializer, is_rest] : pattern.entries) { VERIFY(name.has<Empty>()); if (is_rest) { if (first) { // The iterator has not been called, and is thus known to be not exhausted generator.emit<Bytecode::Op::Load>(iterator_reg); generator.emit<Bytecode::Op::IteratorToArray>(); } else { auto& if_exhausted_block = generator.make_block(); auto& if_not_exhausted_block = generator.make_block(); auto& continuation_block = generator.make_block(); generator.emit<Bytecode::Op::Load>(is_iterator_exhausted_register); generator.emit<Bytecode::Op::JumpConditional>().set_targets( Bytecode::Label { if_exhausted_block }, Bytecode::Label { if_not_exhausted_block }); generator.switch_to_basic_block(if_exhausted_block); generator.emit<Bytecode::Op::NewArray>(); generator.emit<Bytecode::Op::Jump>().set_targets( Bytecode::Label { continuation_block }, {}); generator.switch_to_basic_block(if_not_exhausted_block); generator.emit<Bytecode::Op::Load>(iterator_reg); generator.emit<Bytecode::Op::IteratorToArray>(); generator.emit<Bytecode::Op::Jump>().set_targets( Bytecode::Label { continuation_block }, {}); generator.switch_to_basic_block(continuation_block); } return assign_accumulator_to_alias(alias); } // In the first iteration of the loop, a few things are true which can save // us some bytecode: // - the iterator result is still in the accumulator, so we can avoid a load // - the iterator is not yet exhausted, which can save us a jump and some // creation auto& iterator_is_exhausted_block = generator.make_block(); if (!first) { auto& iterator_is_not_exhausted_block = generator.make_block(); generator.emit<Bytecode::Op::Load>(is_iterator_exhausted_register); generator.emit<Bytecode::Op::JumpConditional>().set_targets( Bytecode::Label { iterator_is_exhausted_block }, Bytecode::Label { iterator_is_not_exhausted_block }); generator.switch_to_basic_block(iterator_is_not_exhausted_block); generator.emit<Bytecode::Op::Load>(iterator_reg); } generator.emit<Bytecode::Op::IteratorNext>(); generator.emit<Bytecode::Op::Store>(temp_iterator_result_reg); generator.emit<Bytecode::Op::IteratorResultDone>(); generator.emit<Bytecode::Op::Store>(is_iterator_exhausted_register); // We still have to check for exhaustion here. If the iterator is exhausted, // we need to bail before trying to get the value auto& no_bail_block = generator.make_block(); generator.emit<Bytecode::Op::JumpConditional>().set_targets( Bytecode::Label { iterator_is_exhausted_block }, Bytecode::Label { no_bail_block }); generator.switch_to_basic_block(no_bail_block); // Get the next value in the iterator generator.emit<Bytecode::Op::Load>(temp_iterator_result_reg); generator.emit<Bytecode::Op::IteratorResultValue>(); auto& create_binding_block = generator.make_block(); generator.emit<Bytecode::Op::Jump>().set_targets( Bytecode::Label { create_binding_block }, {}); // The iterator is exhausted, so we just load undefined and continue binding generator.switch_to_basic_block(iterator_is_exhausted_block); generator.emit<Bytecode::Op::LoadImmediate>(js_undefined()); generator.emit<Bytecode::Op::Jump>().set_targets( Bytecode::Label { create_binding_block }, {}); // Create the actual binding. The value which this entry must bind is now in the // accumulator. We can proceed, processing the alias as a nested destructuring // pattern if necessary. generator.switch_to_basic_block(create_binding_block); TRY(assign_accumulator_to_alias(alias)); first = false; } return {}; } static Bytecode::CodeGenerationErrorOr<void> generate_binding_pattern_bytecode(Bytecode::Generator& generator, BindingPattern const& pattern, Bytecode::Op::SetVariable::InitializationMode initialization_mode, Bytecode::Register const& value_reg) { if (pattern.kind == BindingPattern::Kind::Object) return generate_object_binding_pattern_bytecode(generator, pattern, initialization_mode, value_reg); return generate_array_binding_pattern_bytecode(generator, pattern, initialization_mode, value_reg); } Bytecode::CodeGenerationErrorOr<void> VariableDeclaration::generate_bytecode(Bytecode::Generator& generator) const { for (auto& declarator : m_declarations) { if (declarator.init()) TRY(declarator.init()->generate_bytecode(generator)); else generator.emit<Bytecode::Op::LoadImmediate>(js_undefined()); auto initialization_mode = is_lexical_declaration() ? Bytecode::Op::SetVariable::InitializationMode::Initialize : Bytecode::Op::SetVariable::InitializationMode::Set; TRY(declarator.target().visit( [&](NonnullRefPtr<Identifier> const& id) -> Bytecode::CodeGenerationErrorOr<void> { generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(id->string()), initialization_mode); return {}; }, [&](NonnullRefPtr<BindingPattern> const& pattern) -> Bytecode::CodeGenerationErrorOr<void> { auto value_register = generator.allocate_register(); generator.emit<Bytecode::Op::Store>(value_register); return generate_binding_pattern_bytecode(generator, pattern, initialization_mode, value_register); })); } return {}; } Bytecode::CodeGenerationErrorOr<void> CallExpression::generate_bytecode(Bytecode::Generator& generator) const { auto callee_reg = generator.allocate_register(); auto this_reg = generator.allocate_register(); generator.emit<Bytecode::Op::LoadImmediate>(js_undefined()); generator.emit<Bytecode::Op::Store>(this_reg); if (is<NewExpression>(this)) { TRY(m_callee->generate_bytecode(generator)); generator.emit<Bytecode::Op::Store>(callee_reg); } else if (is<SuperExpression>(*m_callee)) { return Bytecode::CodeGenerationError { this, "Unimplemented callee kind: SuperExpression"sv, }; } else if (is<MemberExpression>(*m_callee)) { auto& member_expression = static_cast<const MemberExpression&>(*m_callee); if (is<SuperExpression>(member_expression.object())) { return Bytecode::CodeGenerationError { this, "Unimplemented callee kind: MemberExpression on SuperExpression"sv, }; } TRY(member_expression.object().generate_bytecode(generator)); generator.emit<Bytecode::Op::Store>(this_reg); if (member_expression.is_computed()) { TRY(member_expression.property().generate_bytecode(generator)); generator.emit<Bytecode::Op::GetByValue>(this_reg); } else { auto identifier_table_ref = generator.intern_identifier(verify_cast<Identifier>(member_expression.property()).string()); generator.emit<Bytecode::Op::GetById>(identifier_table_ref); } generator.emit<Bytecode::Op::Store>(callee_reg); } else { // FIXME: this = global object in sloppy mode. TRY(m_callee->generate_bytecode(generator)); generator.emit<Bytecode::Op::Store>(callee_reg); } Vector<Bytecode::Register> argument_registers; for (auto& arg : m_arguments) { TRY(arg.value->generate_bytecode(generator)); auto arg_reg = generator.allocate_register(); generator.emit<Bytecode::Op::Store>(arg_reg); argument_registers.append(arg_reg); } Bytecode::Op::Call::CallType call_type; if (is<NewExpression>(*this)) { call_type = Bytecode::Op::Call::CallType::Construct; } else { call_type = Bytecode::Op::Call::CallType::Call; } generator.emit_with_extra_register_slots<Bytecode::Op::Call>(argument_registers.size(), call_type, callee_reg, this_reg, argument_registers); return {}; } Bytecode::CodeGenerationErrorOr<void> ReturnStatement::generate_bytecode(Bytecode::Generator& generator) const { if (m_argument) TRY(m_argument->generate_bytecode(generator)); if (generator.is_in_generator_or_async_function()) generator.emit<Bytecode::Op::Yield>(nullptr); else generator.emit<Bytecode::Op::Return>(); return {}; } Bytecode::CodeGenerationErrorOr<void> YieldExpression::generate_bytecode(Bytecode::Generator& generator) const { VERIFY(generator.is_in_generator_function()); if (m_is_yield_from) { return Bytecode::CodeGenerationError { this, "Unimplemented form: `yield*`"sv, }; } if (m_argument) TRY(m_argument->generate_bytecode(generator)); auto& continuation_block = generator.make_block(); generator.emit<Bytecode::Op::Yield>(Bytecode::Label { continuation_block }); generator.switch_to_basic_block(continuation_block); return {}; } Bytecode::CodeGenerationErrorOr<void> IfStatement::generate_bytecode(Bytecode::Generator& generator) const { // test // jump if_true (true) true (false) false // true // jump always (true) end // false // jump always (true) end // end auto& true_block = generator.make_block(); auto& false_block = generator.make_block(); TRY(m_predicate->generate_bytecode(generator)); generator.emit<Bytecode::Op::JumpConditional>().set_targets( Bytecode::Label { true_block }, Bytecode::Label { false_block }); Bytecode::Op::Jump* true_block_jump { nullptr }; generator.switch_to_basic_block(true_block); generator.emit<Bytecode::Op::LoadImmediate>(js_undefined()); TRY(m_consequent->generate_bytecode(generator)); if (!generator.is_current_block_terminated()) true_block_jump = &generator.emit<Bytecode::Op::Jump>(); generator.switch_to_basic_block(false_block); auto& end_block = generator.make_block(); generator.emit<Bytecode::Op::LoadImmediate>(js_undefined()); if (m_alternate) TRY(m_alternate->generate_bytecode(generator)); if (!generator.is_current_block_terminated()) generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { end_block }, {}); if (true_block_jump) true_block_jump->set_targets(Bytecode::Label { end_block }, {}); generator.switch_to_basic_block(end_block); return {}; } Bytecode::CodeGenerationErrorOr<void> ContinueStatement::generate_bytecode(Bytecode::Generator& generator) const { generator.emit<Bytecode::Op::Jump>().set_targets( generator.nearest_continuable_scope(), {}); return {}; } Bytecode::CodeGenerationErrorOr<void> DebuggerStatement::generate_bytecode(Bytecode::Generator&) const { return {}; } Bytecode::CodeGenerationErrorOr<void> ConditionalExpression::generate_bytecode(Bytecode::Generator& generator) const { // test // jump if_true (true) true (false) false // true // jump always (true) end // false // jump always (true) end // end auto& true_block = generator.make_block(); auto& false_block = generator.make_block(); auto& end_block = generator.make_block(); TRY(m_test->generate_bytecode(generator)); generator.emit<Bytecode::Op::JumpConditional>().set_targets( Bytecode::Label { true_block }, Bytecode::Label { false_block }); generator.switch_to_basic_block(true_block); TRY(m_consequent->generate_bytecode(generator)); generator.emit<Bytecode::Op::Jump>().set_targets( Bytecode::Label { end_block }, {}); generator.switch_to_basic_block(false_block); TRY(m_alternate->generate_bytecode(generator)); generator.emit<Bytecode::Op::Jump>().set_targets( Bytecode::Label { end_block }, {}); generator.switch_to_basic_block(end_block); return {}; } Bytecode::CodeGenerationErrorOr<void> SequenceExpression::generate_bytecode(Bytecode::Generator& generator) const { for (auto& expression : m_expressions) TRY(expression.generate_bytecode(generator)); return {}; } Bytecode::CodeGenerationErrorOr<void> TemplateLiteral::generate_bytecode(Bytecode::Generator& generator) const { auto string_reg = generator.allocate_register(); for (size_t i = 0; i < m_expressions.size(); i++) { TRY(m_expressions[i].generate_bytecode(generator)); if (i == 0) { generator.emit<Bytecode::Op::Store>(string_reg); } else { generator.emit<Bytecode::Op::ConcatString>(string_reg); } } generator.emit<Bytecode::Op::Load>(string_reg); return {}; } Bytecode::CodeGenerationErrorOr<void> TaggedTemplateLiteral::generate_bytecode(Bytecode::Generator& generator) const { TRY(m_tag->generate_bytecode(generator)); auto tag_reg = generator.allocate_register(); generator.emit<Bytecode::Op::Store>(tag_reg); Vector<Bytecode::Register> string_regs; auto& expressions = m_template_literal->expressions(); for (size_t i = 0; i < expressions.size(); ++i) { if (i % 2 != 0) continue; TRY(expressions[i].generate_bytecode(generator)); auto string_reg = generator.allocate_register(); generator.emit<Bytecode::Op::Store>(string_reg); string_regs.append(string_reg); } generator.emit_with_extra_register_slots<Bytecode::Op::NewArray>(string_regs.size(), string_regs); auto strings_reg = generator.allocate_register(); generator.emit<Bytecode::Op::Store>(strings_reg); Vector<Bytecode::Register> argument_regs; argument_regs.append(strings_reg); for (size_t i = 0; i < expressions.size(); ++i) { if (i % 2 == 0) continue; TRY(expressions[i].generate_bytecode(generator)); auto string_reg = generator.allocate_register(); generator.emit<Bytecode::Op::Store>(string_reg); argument_regs.append(string_reg); } Vector<Bytecode::Register> raw_string_regs; for (auto& raw_string : m_template_literal->raw_strings()) { TRY(raw_string.generate_bytecode(generator)); auto raw_string_reg = generator.allocate_register(); generator.emit<Bytecode::Op::Store>(raw_string_reg); raw_string_regs.append(raw_string_reg); } generator.emit_with_extra_register_slots<Bytecode::Op::NewArray>(raw_string_regs.size(), raw_string_regs); auto raw_strings_reg = generator.allocate_register(); generator.emit<Bytecode::Op::Store>(raw_strings_reg); generator.emit<Bytecode::Op::Load>(strings_reg); generator.emit<Bytecode::Op::PutById>(raw_strings_reg, generator.intern_identifier("raw")); generator.emit<Bytecode::Op::LoadImmediate>(js_undefined()); auto this_reg = generator.allocate_register(); generator.emit<Bytecode::Op::Store>(this_reg); generator.emit_with_extra_register_slots<Bytecode::Op::Call>(argument_regs.size(), Bytecode::Op::Call::CallType::Call, tag_reg, this_reg, move(argument_regs)); return {}; } Bytecode::CodeGenerationErrorOr<void> UpdateExpression::generate_bytecode(Bytecode::Generator& generator) const { TRY(generator.emit_load_from_reference(*m_argument)); Optional<Bytecode::Register> previous_value_for_postfix_reg; if (!m_prefixed) { previous_value_for_postfix_reg = generator.allocate_register(); generator.emit<Bytecode::Op::Store>(*previous_value_for_postfix_reg); } if (m_op == UpdateOp::Increment) generator.emit<Bytecode::Op::Increment>(); else generator.emit<Bytecode::Op::Decrement>(); TRY(generator.emit_store_to_reference(*m_argument)); if (!m_prefixed) generator.emit<Bytecode::Op::Load>(*previous_value_for_postfix_reg); return {}; } Bytecode::CodeGenerationErrorOr<void> ThrowStatement::generate_bytecode(Bytecode::Generator& generator) const { TRY(m_argument->generate_bytecode(generator)); generator.emit<Bytecode::Op::Throw>(); return {}; } Bytecode::CodeGenerationErrorOr<void> BreakStatement::generate_bytecode(Bytecode::Generator& generator) const { generator.emit<Bytecode::Op::Jump>().set_targets( generator.nearest_breakable_scope(), {}); return {}; } Bytecode::CodeGenerationErrorOr<void> TryStatement::generate_bytecode(Bytecode::Generator& generator) const { auto& saved_block = generator.current_block(); Optional<Bytecode::Label> handler_target; Optional<Bytecode::Label> finalizer_target; Bytecode::BasicBlock* next_block { nullptr }; if (m_finalizer) { auto& finalizer_block = generator.make_block(); generator.switch_to_basic_block(finalizer_block); TRY(m_finalizer->generate_bytecode(generator)); if (!generator.is_current_block_terminated()) { next_block = &generator.make_block(); auto next_target = Bytecode::Label { *next_block }; generator.emit<Bytecode::Op::ContinuePendingUnwind>(next_target); } finalizer_target = Bytecode::Label { finalizer_block }; } if (m_handler) { auto& handler_block = generator.make_block(); generator.switch_to_basic_block(handler_block); TRY(m_handler->parameter().visit( [&](FlyString const& parameter) -> Bytecode::CodeGenerationErrorOr<void> { if (!parameter.is_empty()) { // FIXME: We need a separate DeclarativeEnvironment here generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(parameter)); } return {}; }, [&](NonnullRefPtr<BindingPattern> const&) -> Bytecode::CodeGenerationErrorOr<void> { // FIXME: Implement this path when the above DeclarativeEnvironment issue is dealt with. return Bytecode::CodeGenerationError { this, "Unimplemented catch argument: BindingPattern"sv, }; })); TRY(m_handler->body().generate_bytecode(generator)); handler_target = Bytecode::Label { handler_block }; if (!generator.is_current_block_terminated()) { if (m_finalizer) { generator.emit<Bytecode::Op::LeaveUnwindContext>(); generator.emit<Bytecode::Op::Jump>(finalizer_target); } else { VERIFY(!next_block); next_block = &generator.make_block(); auto next_target = Bytecode::Label { *next_block }; generator.emit<Bytecode::Op::Jump>(next_target); } } } auto& target_block = generator.make_block(); generator.switch_to_basic_block(saved_block); generator.emit<Bytecode::Op::EnterUnwindContext>(Bytecode::Label { target_block }, handler_target, finalizer_target); generator.switch_to_basic_block(target_block); TRY(m_block->generate_bytecode(generator)); if (!generator.is_current_block_terminated()) { if (m_finalizer) { generator.emit<Bytecode::Op::Jump>(finalizer_target); } else { auto& block = generator.make_block(); generator.emit<Bytecode::Op::FinishUnwind>(Bytecode::Label { block }); next_block = &block; } } generator.switch_to_basic_block(next_block ? *next_block : saved_block); return {}; } Bytecode::CodeGenerationErrorOr<void> SwitchStatement::generate_bytecode(Bytecode::Generator& generator) const { auto discriminant_reg = generator.allocate_register(); TRY(m_discriminant->generate_bytecode(generator)); generator.emit<Bytecode::Op::Store>(discriminant_reg); Vector<Bytecode::BasicBlock&> case_blocks; Bytecode::BasicBlock* default_block { nullptr }; Bytecode::BasicBlock* next_test_block = &generator.make_block(); generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { *next_test_block }, {}); for (auto& switch_case : m_cases) { auto& case_block = generator.make_block(); if (switch_case.test()) { generator.switch_to_basic_block(*next_test_block); TRY(switch_case.test()->generate_bytecode(generator)); generator.emit<Bytecode::Op::StrictlyEquals>(discriminant_reg); next_test_block = &generator.make_block(); generator.emit<Bytecode::Op::JumpConditional>().set_targets(Bytecode::Label { case_block }, Bytecode::Label { *next_test_block }); } else { default_block = &case_block; } case_blocks.append(case_block); } generator.switch_to_basic_block(*next_test_block); auto& end_block = generator.make_block(); if (default_block != nullptr) { generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { *default_block }, {}); } else { generator.emit<Bytecode::Op::LoadImmediate>(js_undefined()); generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { end_block }, {}); } auto current_block = case_blocks.begin(); generator.begin_breakable_scope(Bytecode::Label { end_block }); for (auto& switch_case : m_cases) { generator.switch_to_basic_block(*current_block); generator.emit<Bytecode::Op::LoadImmediate>(js_undefined()); for (auto& statement : switch_case.children()) { TRY(statement.generate_bytecode(generator)); } if (!generator.is_current_block_terminated()) { auto next_block = current_block; next_block++; if (next_block.is_end()) { generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { end_block }, {}); } else { generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { *next_block }, {}); } } current_block++; } generator.end_breakable_scope(); generator.switch_to_basic_block(end_block); return {}; } Bytecode::CodeGenerationErrorOr<void> ClassDeclaration::generate_bytecode(Bytecode::Generator& generator) const { TRY(m_class_expression->generate_bytecode(generator)); generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(m_class_expression.ptr()->name()), Bytecode::Op::SetVariable::InitializationMode::Initialize); return {}; } Bytecode::CodeGenerationErrorOr<void> ClassExpression::generate_bytecode(Bytecode::Generator& generator) const { generator.emit<Bytecode::Op::NewClass>(*this); return {}; } Bytecode::CodeGenerationErrorOr<void> ThisExpression::generate_bytecode(Bytecode::Generator& generator) const { generator.emit<Bytecode::Op::ResolveThisBinding>(); return {}; } Bytecode::CodeGenerationErrorOr<void> AwaitExpression::generate_bytecode(Bytecode::Generator& generator) const { VERIFY(generator.is_in_async_function()); // Transform `await expr` to `yield expr` TRY(m_argument->generate_bytecode(generator)); auto& continuation_block = generator.make_block(); generator.emit<Bytecode::Op::Yield>(Bytecode::Label { continuation_block }); generator.switch_to_basic_block(continuation_block); return {}; } }
41.220844
267
0.660532
gSpera
e4f40cc473b23988ba0cc7e6ab9abe4bcd889592
1,437
cpp
C++
tests/unrepresentable_operation_error.test.cpp
atimholt/rational_geometry
2738ac352dc527b2c2d5f4d3197692161a0d34b1
[ "MIT" ]
null
null
null
tests/unrepresentable_operation_error.test.cpp
atimholt/rational_geometry
2738ac352dc527b2c2d5f4d3197692161a0d34b1
[ "MIT" ]
null
null
null
tests/unrepresentable_operation_error.test.cpp
atimholt/rational_geometry
2738ac352dc527b2c2d5f4d3197692161a0d34b1
[ "MIT" ]
null
null
null
#include "../src/rational_geometry/unrepresentable_operation_error.hpp" #include "doctest.h" #include <ostream> #include <string> #include <typeinfo> namespace rational_geometry { TEST_CASE("Testing unrepresentable_operation_error.hpp") { SUBCASE("class unrepresentable_operation_error") { SUBCASE("Constructors") { auto a = unrepresentable_operation_error<int>("This error is a test", 12, 8); CHECK(a.get_minimum_fix_factor() == 2); } SUBCASE("accumulate_fix_factor()") { int fix_factor{1}; const int kDenom{12}; try { throw unrepresentable_operation_error<int>{"An error", kDenom, 8}; } catch (const unrepresentable_operation_error<int>& e) { e.accumulate_fix_factor(fix_factor); } CHECK(fix_factor == 2); try { throw unrepresentable_operation_error<int>{"An error", kDenom, 9}; } catch (const unrepresentable_operation_error<int>& e) { e.accumulate_fix_factor(fix_factor); } REQUIRE(fix_factor == 2 * 3); // Runtime returns on what to put into the code manually: auto kFixFactorAccumulated = 2 * 3; auto kNewDenom = kDenom * kFixFactorAccumulated; // These don't throw: // // Rational<int, kNewDenom> a{[any int value]}; // // a / 8; a / 9; } } } } // namespace rational_geometry // vim:set et ts=2 sw=2 sts=2:
21.447761
78
0.631176
atimholt
e4fd7df13e2271077ed77daa1a65b22b8ed19a5d
685
hpp
C++
include/server/service/utils.hpp
jhermsmeier/osrm-backend
7b11cd3a11c939c957eeff71af7feddaa86e7f82
[ "BSD-2-Clause" ]
13
2019-02-21T02:02:41.000Z
2021-09-09T13:49:31.000Z
include/server/service/utils.hpp
serarca/osrm-backend
3b4e2e83ef85983df1381dbeacd0ea5d4b9bbbcb
[ "BSD-2-Clause" ]
288
2019-02-21T01:34:04.000Z
2021-03-27T12:19:10.000Z
include/server/service/utils.hpp
serarca/osrm-backend
3b4e2e83ef85983df1381dbeacd0ea5d4b9bbbcb
[ "BSD-2-Clause" ]
4
2019-06-21T20:51:59.000Z
2021-01-13T09:22:24.000Z
#include <boost/format.hpp> namespace osrm { namespace server { namespace service { const constexpr char PARAMETER_SIZE_MISMATCH_MSG[] = "Number of elements in %1% size %2% does not match coordinate size %3%"; template <typename ParamT> bool constrainParamSize(const char *msg_template, const char *name, const ParamT &param, const std::size_t target_size, std::string &help) { if (param.size() > 0 && param.size() != target_size) { help = (boost::format(msg_template) % name % param.size() % target_size).str(); return true; } return false; } } } }
22.833333
87
0.583942
jhermsmeier
9000fb3b8702118f57f3a3a312660835ace9ec11
1,746
cpp
C++
CCSDSlib/source/PacketFixedLength.cpp
nhaflinger/CCSDSlib
23bd332078c6c8a1a3e70bacdb9a81f0da9403a3
[ "MIT" ]
1
2021-06-10T13:14:27.000Z
2021-06-10T13:14:27.000Z
CCSDSlib/source/PacketFixedLength.cpp
nhaflinger/CCSDSlib
23bd332078c6c8a1a3e70bacdb9a81f0da9403a3
[ "MIT" ]
null
null
null
CCSDSlib/source/PacketFixedLength.cpp
nhaflinger/CCSDSlib
23bd332078c6c8a1a3e70bacdb9a81f0da9403a3
[ "MIT" ]
null
null
null
#ifdef __linux__ //linux code goes here #elif defined(_WIN32) || defined(WIN32) #define WIN32_LEAN_AND_MEAN #include <windows.h> #endif #include "PacketFixedLength.h" using namespace std; PacketFixedLength::PacketFixedLength() { } PacketFixedLength::~PacketFixedLength() { } map<string, string> PacketFixedLength::loadFile(string file_path) { map<string, string> field_map; ifstream in_file(file_path, ios::binary); if (in_file.good()) { in_file.seekg(0, ios::end); int num_bytes = (int)in_file.tellg(); in_file.seekg(0, ios::beg); char c = in_file.get(); m_file_bytes.push_back('\0'); while (in_file.good()) { c = in_file.get(); m_file_bytes.push_back(c); } } else { cout << "File does not exist!" << endl; } PacketDecode decoder; decoder.decodeFixedLength(m_file_bytes, m_packet_fields); field_map = decoder.fieldMap(); m_primary_header = decoder.primaryHeader(); return field_map; } map<string, string> PacketFixedLength::decodePacket(const vector<char>& file_bytes) { map<string, string> field_map; m_file_bytes = file_bytes; PacketDecode decoder; decoder.decodeFixedLength(m_file_bytes, m_packet_fields); field_map = decoder.fieldMap(); m_primary_header = decoder.primaryHeader(); return field_map; } vector<char> PacketFixedLength::encodePacket(const map<string, string>& field_map, bool secondary_header) { PacketEncode encoder; encoder.setPrimaryHeader(m_primary_header); if (secondary_header) { encoder.setSecondaryHeader(m_secondary_header); } encoder.setFieldMap(field_map); vector<char> packed_bytes = encoder.encodeFixedLength(m_packet_fields, secondary_header); return packed_bytes; }
22.101266
106
0.71764
nhaflinger
07e5868483e4085ce759c4c9760a7f4a5e01bf3b
15,061
cpp
C++
pizjuce/image/src/imagePlugin.cpp
nonameentername/pizmidi
a985e3d2bf8f02e3c0a87300dfbb82c35608bbd2
[ "BSD-Source-Code" ]
null
null
null
pizjuce/image/src/imagePlugin.cpp
nonameentername/pizmidi
a985e3d2bf8f02e3c0a87300dfbb82c35608bbd2
[ "BSD-Source-Code" ]
null
null
null
pizjuce/image/src/imagePlugin.cpp
nonameentername/pizmidi
a985e3d2bf8f02e3c0a87300dfbb82c35608bbd2
[ "BSD-Source-Code" ]
1
2021-01-26T12:25:01.000Z
2021-01-26T12:25:01.000Z
#include "imagePlugin.h" #include "imagePluginEditor.h" //============================================================================== /* This function must be implemented to create the actual plugin object that you want to use. */ PizAudioProcessor* JUCE_CALLTYPE createPluginFilter() { return new imagePluginFilter(); } ImageBank::ImageBank () : ValueTree("ImageBank") { //default values for (int b=0;b<128;b++) { ValueTree bank("BankValues"); bank.setProperty("bankIndex",b,0); for (int p=0;p<128;p++) { ValueTree pv("ProgValues"); pv.setProperty("progIndex",p,0); pv.setProperty("name","Bank " + String(b) + " Image " + String(p+1),0); pv.setProperty("icon",String("Images") + File::separator + "Bank " + String(b) + File::separator + String(p+1) + ".svg",0); pv.setProperty("text",String::empty,0); pv.setProperty("bgcolor",Colour(0xFFFFFFFF).toString(),0); pv.setProperty("textcolor",Colour(0xFF000000).toString(),0); pv.setProperty("h",400,0); pv.setProperty("w",400,0); bank.addChild(pv,p,0); } this->addChild(bank,b,0); } ValueTree settings("GlobalSettings"); settings.setProperty("lastProgram",0,0); settings.setProperty("lastBank",0,0); settings.setProperty("channel",0,0); settings.setProperty("noteInput",false,0); settings.setProperty("usePC",true,0); this->addChild(settings,128,0); } //============================================================================== imagePluginFilter::imagePluginFilter() { iconPath = getCurrentPath() + File::separator + "images"; // create built-in programs programs = new ImageBank();//new JuceProgram[16384]; if (!loadDefaultFxb()) { //for(int b=0;b<128;b++) //{ // for(int i=0;i<128;i++){ // programs[b*128+i].icon = String("Images") + File::separator + "Bank " + String(b) + File::separator + String(i+1) + ".svg"; // programs[b*128+i].name = "Bank " + String(b) + " Image " + String(i+1); // } //} } //start up with the first program init = true; curBank = 0; curProgram = 0; setCurrentBank (0,0); } imagePluginFilter::~imagePluginFilter() { if (programs) delete programs; } //============================================================================== float imagePluginFilter::getParameter (int index) { return param[index]; } void imagePluginFilter::setParameter (int index, float newValue) { switch(index) { case kChannel: if (param[index] != newValue) { param[index] = newValue; programs->getChildWithName("GlobalSettings").setProperty("channel",roundFloatToInt(newValue*16.f),0); sendChangeMessage (); } break; default: break; } } const String imagePluginFilter::getParameterName (int index) { if (index == kChannel) return "Channel"; return String::empty; } const String imagePluginFilter::getParameterText (int index) { if (index==kChannel) { if (roundFloatToInt(param[kChannel]*16.0f)==0) return String("Any"); else return String(roundFloatToInt(param[kChannel]*16.0f)); } return String::empty; } const String imagePluginFilter::getInputChannelName (const int channelIndex) const { return String (channelIndex + 1); } const String imagePluginFilter::getOutputChannelName (const int channelIndex) const { return String (channelIndex + 1); } bool imagePluginFilter::isInputChannelStereoPair (int index) const { return true; } bool imagePluginFilter::isOutputChannelStereoPair (int index) const { return true; } //======================Programs================================================ void imagePluginFilter::setCurrentProgram (int index) { //save non-parameter info to the old program, except the first time if (!init) { programs->set(curBank,curProgram,"h",lastUIHeight); programs->set(curBank,curProgram,"w",lastUIWidth); programs->set(curBank,curProgram,"icon",icon); programs->set(curBank,curProgram,"text",text); programs->set(curBank,curProgram,"bgcolor",bgcolor.toString()); programs->set(curBank,curProgram,"textcolor",textcolor.toString()); } init = false; //then set the new program curProgram = index; param[kChannel] = (float)programs->getChildWithName("GlobalSettings").getProperty("channel")*0.0625f; lastUIHeight = programs->get(curBank,curProgram,"h"); lastUIWidth = programs->get(curBank,curProgram,"w"); icon = programs->get(curBank,curProgram,"icon"); text = programs->get(curBank,curProgram,"text"); bgcolor = Colour::fromString(programs->get(curBank,curProgram,"bgcolor")); textcolor = Colour::fromString(programs->get(curBank,curProgram,"textcolor")); noteInput = programs->getChildWithName("GlobalSettings").getProperty("noteInput"); usePC = programs->getChildWithName("GlobalSettings").getProperty("usePC"); sendChangeMessage(); } void imagePluginFilter::setCurrentBank(int index, int program) { if (!init) { programs->set(curBank,curProgram,"h",lastUIHeight); programs->set(curBank,curProgram,"w",lastUIWidth); programs->set(curBank,curProgram,"icon",icon); programs->set(curBank,curProgram,"text",text); programs->set(curBank,curProgram,"bgcolor",bgcolor.toString()); programs->set(curBank,curProgram,"textcolor",textcolor.toString()); } init = true; curBank = index; if (program==-1) program = curProgram; updateHostDisplay(); setCurrentProgram(program); } void imagePluginFilter::changeProgramName(int index, const String &newName) { programs->set(curBank,index,"name",newName); } const String imagePluginFilter::getProgramName(int index) { return programs->get(curBank,index,"name"); } int imagePluginFilter::getCurrentProgram() { return curProgram; } //============================================================================== void imagePluginFilter::prepareToPlay (double sampleRate, int samplesPerBlock) { // do your pre-playback setup stuff here.. } void imagePluginFilter::releaseResources() { // when playback stops, you can use this as an opportunity to free up any // spare memory, etc. } void imagePluginFilter::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages) { for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i) { buffer.clear (i, 0, buffer.getNumSamples()); } const int channel = roundFloatToInt(param[kChannel]*16.0f); MidiBuffer::Iterator mid_buffer_iter(midiMessages); MidiMessage midi_message(0xFE); int sample_number; while(mid_buffer_iter.getNextEvent(midi_message,sample_number)) { if (channel==0 || midi_message.isForChannel(channel)) { if (midi_message.isController() && midi_message.getControllerNumber()==0 && usePC) { setCurrentBank(midi_message.getControllerValue()); updateHostDisplay(); } else if (midi_message.isProgramChange() && usePC) { setCurrentProgram(midi_message.getProgramChangeNumber()); updateHostDisplay(); } else if (midi_message.isNoteOn() && noteInput) { setCurrentProgram(midi_message.getNoteNumber()); updateHostDisplay(); } } } midiMessages.clear(); } //============================================================================== AudioProcessorEditor* imagePluginFilter::createEditor() { return new imagePluginEditor (this); } //============================================================================== void imagePluginFilter::getCurrentProgramStateInformation (MemoryBlock& destData) { // make sure the non-parameter settings are copied to the current program programs->set(curBank,curProgram,"h",lastUIHeight); programs->set(curBank,curProgram,"w",lastUIWidth); programs->set(curBank,curProgram,"icon",icon); programs->set(curBank,curProgram,"text",text); programs->set(curBank,curProgram,"bgcolor",bgcolor.toString()); programs->set(curBank,curProgram,"textcolor",textcolor.toString()); // you can store your parameters as binary data if you want to or if you've got // a load of binary to put in there, but if you're not doing anything too heavy, // XML is a much cleaner way of doing it - here's an example of how to store your // params as XML.. // create an outer XML element.. XmlElement xmlState ("MYPLUGINSETTINGS"); // add some attributes to it.. xmlState.setAttribute ("pluginVersion", 1); xmlState.setAttribute ("bank", getCurrentBank()); xmlState.setAttribute ("program", getCurrentProgram()); xmlState.setAttribute ("progname", getProgramName(getCurrentProgram())); for (int i=0;i<kNumParams;i++) { xmlState.setAttribute (String(i), param[i]); } xmlState.setAttribute ("uiWidth", lastUIWidth); xmlState.setAttribute ("uiHeight", lastUIHeight); xmlState.setAttribute ("icon", icon); xmlState.setAttribute ("text", text); xmlState.setAttribute ("bgcolor", (int)(bgcolor.getARGB() & 0x00FFFFFF)); xmlState.setAttribute ("textcolor", (int)(textcolor.getARGB() & 0x00FFFFFF)); xmlState.setAttribute ("noteInput", noteInput); xmlState.setAttribute ("usePC", usePC); // then use this helper function to stuff it into the binary blob and return it.. copyXmlToBinary (xmlState, destData); } void imagePluginFilter::getStateInformation(MemoryBlock &destData) { // make sure the non-parameter settings are copied to the current program programs->set(curBank,curProgram,"h",lastUIHeight); programs->set(curBank,curProgram,"w",lastUIWidth); programs->set(curBank,curProgram,"icon",icon); programs->set(curBank,curProgram,"text",text); programs->set(curBank,curProgram,"bgcolor",bgcolor.toString()); programs->set(curBank,curProgram,"textcolor",textcolor.toString()); programs->getChildWithName("GlobalSettings").setProperty("lastBank",curBank,0); programs->getChildWithName("GlobalSettings").setProperty("lastProgram",curProgram,0); programs->getChildWithName("GlobalSettings").setProperty("noteInput",noteInput,0); programs->getChildWithName("GlobalSettings").setProperty("usePC",usePC,0); programs->writeToStream(MemoryOutputStream(destData,false)); } void imagePluginFilter::setCurrentProgramStateInformation (const void* data, int sizeInBytes) { // use this helper function to get the XML from this binary blob.. ScopedPointer<XmlElement> const xmlState = getXmlFromBinary (data, sizeInBytes); if (xmlState != 0) { // check that it's the right type of xml.. if (xmlState->hasTagName ("MYPLUGINSETTINGS")) { // ok, now pull out our parameters.. changeProgramName(getCurrentProgram(),xmlState->getStringAttribute ("progname", "Default")); for (int i=0;i<kNumParams;i++) { param[i] = (float) xmlState->getDoubleAttribute (String(i), param[i]); } lastUIWidth = xmlState->getIntAttribute ("uiWidth", lastUIWidth); lastUIHeight = xmlState->getIntAttribute ("uiHeight", lastUIHeight); icon = xmlState->getStringAttribute ("icon", icon); text = xmlState->getStringAttribute ("text", text); bgcolor = Colour(xmlState->getIntAttribute ("bgcolor", bgcolor.getARGB()) | 0x00000000); textcolor = Colour(xmlState->getIntAttribute ("textcolor", bgcolor.contrasting(0.8f).getARGB()) | 0x00000000); noteInput = xmlState->getBoolAttribute ("noteInput", noteInput); usePC = xmlState->getBoolAttribute ("usePC", usePC); sendChangeMessage (); } } } void imagePluginFilter::setStateInformation (const void* data, int sizeInBytes) { ScopedPointer<XmlElement> const xmlState = getXmlFromBinary (data, sizeInBytes); if (xmlState == 0) { ValueTree vt = ValueTree::readFromStream(MemoryInputStream(data,sizeInBytes,false)); if (vt.isValid()) { programs->removeAllChildren(0); for (int i=0;i<vt.getNumChildren();i++) { programs->addChild(vt.getChild(i).createCopy(),i,0); } } init=true; setCurrentBank(vt.getChild(128).getProperty("lastBank",0),vt.getChild(128).getProperty("lastProgram",0)); } else { if (xmlState->hasTagName ("MYPLUGINSETTINGS")) { if (xmlState->getIntAttribute("pluginVersion")<2) { fullscreen = xmlState->getBoolAttribute ("fullscreen", false); for (int p=0;p<getNumPrograms();p++) { String prefix = "P" + String(p) + "."; programs->set(0,p,"channel",(float) xmlState->getDoubleAttribute (prefix+String(0), 0)); programs->set(0,p,"w",xmlState->getIntAttribute (prefix+"uiWidth", 400)); programs->set(0,p,"h", xmlState->getIntAttribute (prefix+"uiHeight", 400)); programs->set(0,p,"icon", xmlState->getStringAttribute (prefix+"icon", String::empty)); programs->set(0,p,"text", xmlState->getStringAttribute (prefix+"text", String::empty)); programs->set(0,p,"bgcolor", Colour(xmlState->getIntAttribute (prefix+"bgcolor")).toString()); programs->set(0,p,"textcolor", Colour(xmlState->getIntAttribute ("textcolor")).toString()); programs->set(0,p,"name", xmlState->getStringAttribute (prefix+"progname", String::empty)); } init=true; setCurrentBank(0,xmlState->getIntAttribute("program", 0)); } else { //fullscreen = xmlState->getBoolAttribute ("fullscreen", false); //for (int b=0;b<128;b++) { // XmlElement* xmlBank = xmlState->getChildByName("Bank"+String(b)); // for (int p=0;p<getNumPrograms();p++) { // int prog = b*128+p; // String prefix = "P" + String(p) + "_"; // for (int i=0;i<kNumParams;i++) { // programs[prog].param[i] = (float) xmlBank->getDoubleAttribute (prefix+String(i), programs[prog].param[i]); // } // programs[prog].lastUIWidth = xmlBank->getIntAttribute (prefix+"uiWidth", programs[prog].lastUIWidth); // programs[prog].lastUIHeight = xmlBank->getIntAttribute (prefix+"uiHeight", programs[prog].lastUIHeight); // programs[prog].icon = xmlBank->getStringAttribute (prefix+"icon", programs[prog].icon); // programs[prog].text = xmlBank->getStringAttribute (prefix+"text", programs[prog].text); // programs[prog].bgcolor = Colour(xmlBank->getIntAttribute (prefix+"bgcolor", programs[prog].bgcolor.getARGB()) | 0xFF000000); // programs[prog].textcolor = Colour(xmlBank->getIntAttribute ("textcolor", programs[prog].bgcolor.contrasting(0.8f).getARGB()) | 0x00000000); // programs[prog].name = xmlBank->getStringAttribute (prefix+"progname", programs[prog].name); // } //} //init=true; //setCurrentBank(xmlState->getIntAttribute("bank"),xmlState->getIntAttribute("program")); } } } } void imagePluginFilter::setBankColours(Colour colour, Colour text) { for (int i=0;i<getNumPrograms();i++) { programs->set(curBank,i,"bgcolor",colour.toString()); programs->set(curBank,i,"textcolor",text.toString()); } } void imagePluginFilter::applySizeToBank(int h, int w) { for (int i=0;i<getNumPrograms();i++) { programs->set(curBank,i,"h",h); programs->set(curBank,i,"w",w); } } void imagePluginFilter::clearAllImages() { for (int i=0;i<getNumPrograms();i++) programs->set(curBank,i,"icon", String("")); }
36.291566
147
0.66795
nonameentername
07eaf40d3f0a233b8b1574b1e9a0e7927bae8267
1,311
cpp
C++
c++ problems asked in interview/704. Binary Search.cpp
rj011/Hacktoberfest2021-4
0aa981d4ba5e71c86cc162d34fe57814050064c2
[ "MIT" ]
41
2021-10-03T16:03:52.000Z
2021-11-14T18:15:33.000Z
c++ problems asked in interview/704. Binary Search.cpp
rj011/Hacktoberfest2021-4
0aa981d4ba5e71c86cc162d34fe57814050064c2
[ "MIT" ]
175
2021-10-03T10:47:31.000Z
2021-10-20T11:55:32.000Z
c++ problems asked in interview/704. Binary Search.cpp
rj011/Hacktoberfest2021-4
0aa981d4ba5e71c86cc162d34fe57814050064c2
[ "MIT" ]
208
2021-10-03T11:24:04.000Z
2021-10-31T17:27:59.000Z
Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1. You must write an algorithm with O(log n) runtime complexity. Example 1: Input: nums = [-1,0,3,5,9,12], target = 9 Output: 4 Explanation: 9 exists in nums and its index is 4 Example 2: Input: nums = [-1,0,3,5,9,12], target = 2 Output: -1 Explanation: 2 does not exist in nums so return -1 Solution : Time Complexity - O(logn) where n is the number of elements in the array. This algorithm follows the divide and conquer ; it divides the array based on the situation where the target element is. Space Complexity - O(1) which is constant because I am not using any extra space for storage. class Solution { public: int search(vector<int>& nums, int target) { int low =0, high = nums.size()-1; while(low<=high) { int mid = (low+high)/2; if(nums[mid]==target) return mid; else if(nums[mid]>target){ high = mid-1; } else{ low=mid+1; } } return -1; } };
29.133333
135
0.577422
rj011
07f164fc4e58f06307a47c51638aa3831438f707
28,524
cxx
C++
reduce_includes/reduce_includes.cxx
linev/misc
4627ab0e62da1e66c3c4d656498463724713e891
[ "MIT" ]
null
null
null
reduce_includes/reduce_includes.cxx
linev/misc
4627ab0e62da1e66c3c4d656498463724713e891
[ "MIT" ]
null
null
null
reduce_includes/reduce_includes.cxx
linev/misc
4627ab0e62da1e66c3c4d656498463724713e891
[ "MIT" ]
1
2019-07-05T09:42:45.000Z
2019-07-05T09:42:45.000Z
#include <cstdio> #include <string> #include <fstream> #include <streambuf> #include <cstdlib> #include <cstring> #include <streambuf> #include <vector> #include <algorithm> #include <stdio.h> std::string ReadFile(const char *fname) { std::ifstream t(fname, std::ios::binary); std::string str; t.seekg(0, std::ios::end); str.reserve(t.tellg()); t.seekg(0, std::ios::beg); str.assign((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>()); return str; } void WriteFile(const char *fname, const std::string &content) { std::ofstream ostrm(fname, std::ios::binary); ostrm.write(content.c_str(), content.length()); } const char *exec_cmd = nullptr; const char *go4arg = "$$go4obj$$"; const char *qtarg = "$$qtobj$$"; int ProcessFile(const char *fname) { std::string content = ReadFile(fname); printf("Processing %s len %d\n", fname, (int) content.length()); if (content.length() < 20) return 0; auto lastpos = content.length() - 8; int nremoved = 0; bool modified = false; while (true) { auto pos = content.rfind("#include", lastpos); if (pos == std::string::npos) break; content.insert(pos,"//"); WriteFile(fname, content); std::string exec = exec_cmd; auto p1 = exec.find(go4arg); if (p1 != std::string::npos) { exec.erase(p1, strlen(go4arg)); std::string objname = fname; auto dot = objname.rfind("."); objname.resize(dot+1); objname.append("o"); // replace extension by object file exec.insert(p1,objname); std::string rmfile = "rm -f "; rmfile.append(objname); system(rmfile.c_str()); } else if ((p1 = exec.find(qtarg)) != std::string::npos) { exec.erase(p1, strlen(qtarg)); std::string objname = fname; auto dot = objname.rfind("."); objname.resize(dot+1); objname.append("o"); // replace extension by object file auto slash = objname.rfind("/"); if (slash != std::string::npos) objname.erase(0, slash+1); objname.insert(0,".obj/"); exec.insert(p1,objname); std::string rmfile = "rm -f "; rmfile.append(objname); system(rmfile.c_str()); } int res = system(exec.c_str()); if ((p1 != std::string::npos) && (res==0)) { std::string info = content.substr(pos, 50); auto newline = info.find("\n"); if (newline != std::string::npos) info.resize(newline); printf("Exec %s res %d place %s\n", exec.c_str(), res, info.c_str()); } if (res == 0) { nremoved++; } else { content.erase(pos,2); modified = true; } if (pos < 8) break; // #include is 8 symbols long lastpos = pos-8; } if (modified) WriteFile(fname, content); if (nremoved > 0) printf("File %s removed %d\n", fname, nremoved); return nremoved; } bool SameInclude(const std::string &name1, const std::string &name2) { if (name1 == name2) return true; if ((name1[0] != 'c') && (name2[0] != 'c')) return false; static const std::vector<std::string> vect1 = { "cassert", "cctype", "cerrno", "cfenv", "cfloat", "inttypes.h", "climits", "clocale", "cmath", "csetjmp", "csignal", "cstdarg", "cstddef", "cstdint", "cstdio", "cstring", "cstdlib", "ctime", "cuchar", "cwchar", "cwctype" }; static const std::vector<std::string> vect2 = { "assert.h", "ctype.h", "errno.h", "fenv.h", "float.h", "inttypes.h", "limits.h", "locale.h", "math.h", "setjmp.h", "signal.h", "stdarg.h", "stddef.h", "stdint.h", "stdio.h", "string.h", "stdlib.h", "time.h", "uchar.h", "wchar.h", "wctype.h" }; std::string n1, n2; if (name2[0] == 'c') { n1 = name2; n2 = name1; } else { n1 = name1; n2 = name2; } auto pos1 = std::find(std::begin(vect1), std::end(vect1), n1); if (pos1 == std::end(vect1)) return false; int indx = pos1 - std::begin(vect1); return vect2[indx] == n2; } int FindDuplicate(const char *fname) { std::string content = ReadFile(fname); auto len = content.length(); if (len < 20) return 0; int lastpos = 0; std::vector<std::string> includes; while (lastpos < len) { auto pos = content.find("#include", lastpos); if (pos == std::string::npos) break; if (pos > 5) { // simple check if include at the begin of the line auto p0 = pos - 1; while ((p0 > pos - 5) && ((content[p0] == ' ') || (content[p0] == '\t'))) p0--; if (content[p0] != '\n') { lastpos = pos + 11; continue; } } pos += 9; while ((pos < len) && (content[pos] == ' ')) pos++; if (pos>=len) break; char symb; while ((pos < len) && (content[pos] == ' ') && (content[pos] != '\"')) pos++; if (content[pos] == '<') symb = '>'; else if (content[pos] == '\"') symb = '\"'; else { lastpos = pos+1; continue; } auto pos2 = pos+1; while ((pos2 < len) && (content[pos2] != symb)) pos2++; if (pos2>=len) break; lastpos = pos2+1; if (pos2-pos>100) continue; std::string inclname = content.substr(pos+1, pos2-pos-1); includes.emplace_back(content.substr(pos+1, pos2-pos-1)); } if (includes.size() < 2) return 0; int dupl = 0; for (int n1=0;n1<includes.size()-1;++n1) { auto &name1 = includes[n1]; for (int n2=n1+1;n2<includes.size();++n2) { auto &name2 = includes[n2]; if (SameInclude(name1, name2)) { printf("File %s has duplicated include %s\n", fname, name1.c_str()); dupl++; } } } return dupl; } int CheckRootHeader(const char *fname) { std::string content = ReadFile(fname); int res = 0; if (content.find("Rtypes.h") != std::string::npos) { if ((content.find("ClassDef") == std::string::npos) && (content.find("BIT(") == std::string::npos)) { res = 1; printf("%s not really using Rtypes.h, replace by RtypesCore.h\n", fname); } } static const std::vector<std::string> std_types = { "vector", "deque", "list", "set", "multiset", "map", "multimap", "unordered_set", "unordered_multiset", "unordered_map", "unordered_multimap" }; for(auto &name : std_types) { std::string incl = std::string("<") + name + std::string(">"); std::string srch = std::string("std::") + name + std::string("<"); std::string srch2 = srch; if (name == "map") { srch2 = "std::multimap"; } if (name == "unordered_map") { srch2 = "std::unordered_multimap"; } if (name == "multimap") { incl = "<map>"; srch2 = "std::map"; } if (name == "unordered_multimap") { incl = "<unordered_map>"; srch2 = "std::unordered_map"; } if (content.find(incl) != std::string::npos) { if ((content.find(srch) == std::string::npos) && (content.find(srch2) == std::string::npos)) { res = 1; printf("%s not used %s include\n", fname, incl.c_str()); } } else if (content.find(srch) != std::string::npos) { res = 1; printf("%s using std::%s without %s include\n", fname, name.c_str(), incl.c_str()); } } auto poss = content.find("#include <string>"); if (poss != std::string::npos) { if (content.find("std::string", poss+20) == std::string::npos) { res = 1; printf("%s not used <string> include\n", fname); } } else if (content.find("std::string") != std::string::npos) { res = 1; printf("%s using std::string without <string> include\n", fname); } poss = content.find("<sstream>"); if (poss != std::string::npos) { if (content.find("stringstream", poss+10) == std::string::npos) { res = 1; printf("%s not used <sstream> include\n", fname); } } else if (content.find("stringstream") != std::string::npos) { res = 1; printf("%s using std::stringstream without <sstream> include\n", fname); } poss = content.find("#include <utility>"); if (poss != std::string::npos) { if (((content.find("std::pair", poss+20) == std::string::npos) && (content.find("std::tuple", poss+20) == std::string::npos)) || (content.find("map>") != std::string::npos)) { res = 1; printf("%s check usage of <utility> include\n", fname); } } else if (((content.find("std::pair") != std::string::npos) || (content.find("std::tuple") != std::string::npos)) && (content.find("map>") == std::string::npos)) { res = 1; printf("%s using std::pair or std::tuple without <utility> include\n", fname); } auto pos0 = content.find("Riostream.h"); if (pos0 != std::string::npos) { if ((content.find("ostream", pos0+8) == std::string::npos) && (content.find("fstream", pos0+8) == std::string::npos) && (content.find("std::cout", pos0+8) == std::string::npos) && (content.find("std::cerr", pos0+8) == std::string::npos) && (content.find("std::endl", pos0+8) == std::string::npos)) { printf("%s not used Riostream.h\n", fname); res = 1; } } else { pos0 = content.find("<iostream>"); if (pos0 != std::string::npos) { if ((content.find("cout", pos0+8) == std::string::npos) && (content.find("istream", pos0+8) == std::string::npos) && (content.find("ostream", pos0+8) == std::string::npos) && (content.find("cin", pos0+8) == std::string::npos) && (content.find("cerr", pos0+8) == std::string::npos) && (content.find("endl", pos0+8) == std::string::npos)) { printf("%s not used <iostream>\n", fname); res = 1; } } pos0 = content.find("<fstream>"); if (pos0 != std::string::npos) { if ((content.find("fstream", pos0+8) == std::string::npos)) { printf("%s not used <fstream>\n", fname); res = 1; } } pos0 = content.find("<iomanip>"); if (pos0 != std::string::npos) { if ((content.find("setw", pos0+8) == std::string::npos) && (content.find("setprecision", pos0+8) == std::string::npos) && (content.find("setfill", pos0+8) == std::string::npos) && (content.find("setiosflags", pos0+8) == std::string::npos) && (content.find("setbase", pos0+8) == std::string::npos)) { printf("%s not used <iomanip>\n", fname); res = 1; } } } static const std::vector<std::string> test_types = { "TObject", "TNamed", "TString" }; for(auto &clname : test_types) { std::string incname = clname + ".h"; auto pos = content.find(incname); if (pos != std::string::npos) { if (content.find(clname, pos+incname.length()) == std::string::npos) { printf("%s not used %s\n", fname, incname.c_str()); res = 1; } } } return res; const char* name1 = strrchr(fname, '/'); if (!name1) name1 = fname; else name1++; const char* name2 = strrchr(fname, '.'); if (!name2) return 0; std::string expected = std::string("ROOT_") + std::string(name1, name2-name1); if (content.find("#pragma once") != std::string::npos) return res; pos0 = content.find(std::string("#ifndef ") + expected); if (pos0 == std::string::npos) { printf("%s not found #ifndef %s\n", fname, expected.c_str()); return 1; } auto pos1 = content.find(std::string("#define ") + expected); if ((pos1 == std::string::npos) || (pos1 < pos0)) { printf("%s not found #define %s\n", fname, expected.c_str()); return 1; } return res; } int CheckRootSource(const char *fname) { std::string content = ReadFile(fname); int res = 0; auto pos0 = content.find("TROOT.h"); if (pos0 != std::string::npos) { if ((content.find("ROOT::") == std::string::npos) && (content.find("gROOT") == std::string::npos) && (content.find("TROOT", pos0+6) == std::string::npos)) { res = 1; printf("%s not used TROOT.h\n", fname); } } if (content.find("TMath.h") != std::string::npos) { if (content.find("TMath::") == std::string::npos) { res = 1; printf("%s not used TMath.h\n", fname); } } if (content.find("TStyle.h") != std::string::npos) { if (content.find("gStyle")==std::string::npos) { res = 1; printf("%s not used TStyle.h\n", fname); } } if (content.find("TEnv.h") != std::string::npos) { if (content.find("gEnv")==std::string::npos) { res = 1; printf("%s not used TEnv.h\n", fname); } } pos0 = content.find("TVirtualX.h"); if (pos0 != std::string::npos) { if ((content.find("gVirtualX", pos0+10)==std::string::npos) && (content.find("TVirtualX", pos0+10)==std::string::npos)) { res = 1; printf("%s not used TVirtualX.h\n", fname); } } if (content.find("RVersion.h") != std::string::npos) { if ((content.find("ROOT_RELEASE")==std::string::npos) && (content.find("ROOT_VERSION")==std::string::npos)) { res = 1; printf("%s not used RVersion.h\n", fname); } } if (content.find("TVirtualGL.h") != std::string::npos) { if (content.find("gGLManager")==std::string::npos) { res = 1; printf("%s not used TVirtualGL.h\n", fname); } } pos0 = content.find("TVirtualPad.h"); if (pos0 != std::string::npos) { if ((content.find("gPad", pos0+9)==std::string::npos) && (content.find("fPad", pos0+9)==std::string::npos) && (content.find("GetSelectedPad()", pos0+9)==std::string::npos) && (content.find("TVirtualPad", pos0+9)==std::string::npos)) { res = 1; printf("%s not used TVirtualPad.h\n", fname); } } if (content.find("TGClient.h") != std::string::npos) { if ((content.find("gClient")==std::string::npos) && (content.find("fClient")==std::string::npos)) { res = 1; printf("%s not used TGClient.h\n", fname); } } if ((content.find("TPad.h") != std::string::npos) && (content.find("TCanvas.h") != std::string::npos)) { printf("%s both TPad.h and TCanvas.h found\n", fname); res = 1; } pos0 = content.find("TPad.h"); if (pos0 != std::string::npos) { bool has_gpad = (content.find("gPad", pos0+5) != std::string::npos); bool has_pad = (content.find("TPad", pos0+5) != std::string::npos); if (has_gpad && !has_pad) { printf("%s only gPad used with TPad.h, replace by TVirtualPad.h\n", fname); res = 1; } if (!has_gpad && !has_pad) { printf("%s not used TPad.h\n", fname); res = 1; } } pos0 = content.find("TCanvas.h"); if (pos0 != std::string::npos) { bool has_gpad = (content.find("gPad", pos0+8) != std::string::npos); bool has_pad = (content.find("TPad", pos0+8) != std::string::npos); bool has_canvas = (content.find("TCanvas", pos0+8) != std::string::npos); bool has_get = (content.find("GetCanvas()", pos0+8) != std::string::npos); if (has_gpad && !has_pad && !has_canvas && !has_get) { printf("%s only gPad used with TCanvas.h, replace by TVirtualPad.h\n", fname); res = 1; } if (has_gpad && has_pad && !has_canvas && !has_get) { printf("%s only TPad used with TCanvas.h, replace by TPad.h\n", fname); res = 1; } if (!has_gpad && !has_pad && !has_canvas && !has_get) { printf("%s not used TCanvas.h\n", fname); res = 1; } } pos0 = content.find("TSystem.h"); if (pos0 != std::string::npos) { bool has_gsys = (content.find("gSystem", pos0+8) != std::string::npos); bool has_sys = (content.find("TSystem", pos0+8) != std::string::npos); bool has_types = false; static const std::vector<std::string> sys_types = { "FileStat_t", "UserGroup_t", "SysInfo_t", "CpuInfo_t", "MemInfo_t", "ProcInfo_t", "RedirectHandle_t", "TProcessEventTimer", "gProgPath", "gProgName", "gRootDir", "gSystemMutex" }; if (!has_gsys && !has_sys) { for (auto &name : sys_types) if (content.find(name, pos0+8) != std::string::npos) { has_types = true; break; } printf("%s not used TSystem.h, has types = %s\n", fname, (has_types ? "true" : "false")); res = 1; } } pos0 = content.find("TDirectory.h"); if (pos0 != std::string::npos) { if ((content.find("TDirectory",pos0+10)==std::string::npos) && (content.find("GetDirectory", pos0+7) == std::string::npos) && (content.find("gDirectory",pos0+10)==std::string::npos)) { res = 1; printf("%s not used TDirectory.h\n", fname); } } pos0 = content.find("TApplication.h"); if (pos0 != std::string::npos) { if ((content.find("TApplication",pos0+12)==std::string::npos) && (content.find("GetApplication()->",pos0+12)==std::string::npos) && (content.find("gApplication",pos0+12)==std::string::npos)) { res = 1; printf("%s not used TApplication.h\n", fname); } } pos0 = content.find("TRint.h"); if (pos0 != std::string::npos) { if (content.find("TRint", pos0+8) == std::string::npos) { printf("%s not used TRint.h\n", fname); res = 1; } } pos0 = content.find("TFile.h"); if ((pos0 != std::string::npos) && (content.find("GetCurrentFile", pos0+7) == std::string::npos) && (content.find("GetFile", pos0+7) == std::string::npos)) { bool has_gfile = (content.find("gFile", pos0+7) != std::string::npos); bool has_gdir = (content.find("gDirectory", pos0+7) != std::string::npos); bool has_file = (content.find("TFile", pos0+7) != std::string::npos); if (has_gdir && !has_gfile && !has_file) { printf("%s only gDirectory used with TFile.h, replace by TDirectory.h\n", fname); res = 1; } if (!has_gdir && !has_gfile && !has_file) { printf("%s not used TFile.h\n", fname); res = 1; } } pos0 = content.find("TKey.h"); if (pos0 != std::string::npos) { if ((content.find("TKey",pos0+10)==std::string::npos) && (content.find("GetKey",pos0+10)==std::string::npos)) { res = 1; printf("%s not used TKey.h\n", fname); } } pos0 = content.find("TTree.h"); if (pos0 != std::string::npos) { bool has_gtree = (content.find("gTree", pos0+7) != std::string::npos); bool has_tree = (content.find("TTree", pos0+7) != std::string::npos); if (!has_gtree && !has_tree) { printf("%s not used TTree.h\n", fname); res = 1; } } pos0 = content.find("TColor.h"); if (pos0 != std::string::npos) { if (content.find("TColor", pos0+8) == std::string::npos) { printf("%s not used TColor.h\n", fname); res = 1; } } pos0 = content.find("Riostream.h"); if (pos0 != std::string::npos) { if ((content.find("ostream", pos0+8) == std::string::npos) && (content.find("fstream", pos0+8) == std::string::npos) && (content.find("std::cout", pos0+8) == std::string::npos) && (content.find("std::cerr", pos0+8) == std::string::npos) && (content.find("std::endl", pos0+8) == std::string::npos)) { printf("%s not used Riostream.h\n", fname); res = 1; } } else { pos0 = content.find("<iostream>"); if (pos0 != std::string::npos) { if ((content.find("cout", pos0+8) == std::string::npos) && (content.find("istream", pos0+8) == std::string::npos) && (content.find("ostream", pos0+8) == std::string::npos) && (content.find("cin", pos0+8) == std::string::npos) && (content.find("cerr", pos0+8) == std::string::npos) && (content.find("endl", pos0+8) == std::string::npos)) { printf("%s not used <iostream>\n", fname); res = 1; } } pos0 = content.find("<fstream>"); if (pos0 != std::string::npos) { if ((content.find("fstream", pos0+8) == std::string::npos)) { printf("%s not used <fstream>\n", fname); res = 1; } } pos0 = content.find("<iomanip>"); if (pos0 != std::string::npos) { if ((content.find("setw", pos0+8) == std::string::npos) && (content.find("setprecision", pos0+8) == std::string::npos) && (content.find("setfill", pos0+8) == std::string::npos) && (content.find("setiosflags", pos0+8) == std::string::npos) && (content.find("setbase", pos0+8) == std::string::npos)) { printf("%s not used <iomanip>\n", fname); res = 1; } else { printf("OK iostream\n"); } } } pos0 = content.find("TClass.h"); if (pos0 != std::string::npos) { if ((content.find("IsA()->", pos0+8) == std::string::npos) && (content.find("Class()->", pos0+8) == std::string::npos) && (content.find("TClass", pos0+8) == std::string::npos)) { printf("%s not uses TClass.h\n", fname); res = 1; } } pos0 = content.find("TView.h"); if (pos0 != std::string::npos) { if ((content.find("TView", pos0+8) == std::string::npos) && (content.find("GetView()", pos0+8) == std::string::npos)) { printf("%s not uses TView.h\n", fname); res = 1; } } pos0 = content.find("TRandom.h"); if (pos0 != std::string::npos) { if ((content.find("gRandom", pos0+8) == std::string::npos) && (content.find("TRandom", pos0+8) == std::string::npos)) { printf("%s not uses TRandom.h\n", fname); res = 1; } } pos0 = content.find("TGMenu.h"); if (pos0 != std::string::npos) { if ((content.find("TGMenuBar", pos0+8) == std::string::npos) && (content.find("TGPopupMenu", pos0+8) == std::string::npos) && (content.find("TGMenuEntry", pos0+8) == std::string::npos) && (content.find("TGMenuTitle", pos0+8) == std::string::npos)) { printf("%s not uses TGMenu.h\n", fname); res = 1; } } pos0 = content.find("TGSplitter.h"); if (pos0 != std::string::npos) { if ((content.find("TGSplitter", pos0+8) == std::string::npos) && (content.find("TGVSplitter", pos0+8) == std::string::npos) && (content.find("TGHSplitter", pos0+8) == std::string::npos) && (content.find("fSplitter", pos0+8) == std::string::npos)) { printf("%s not uses TGSplitter.h\n", fname); res = 1; } } pos0 = content.find("TGTab.h"); if (pos0 != std::string::npos) { if ((content.find("TGTab", pos0+8) == std::string::npos) && (content.find("fTab", pos0+8) == std::string::npos)) { printf("%s not uses TGTab.h\n", fname); res = 1; } } pos0 = content.find("TGDockableFrame.h"); if (pos0 != std::string::npos) { if ((content.find("TGDockableFrame", pos0+8) == std::string::npos) && (content.find("GetToolDock()->", pos0+8) == std::string::npos)) { printf("%s not uses TGDockableFrame.h\n", fname); res = 1; } } pos0 = content.find("TGDoubleSlider.h"); if (pos0 != std::string::npos) { if ((content.find("TGDoubleSlider", pos0+8) == std::string::npos) && (content.find("TGDoubleVSlider", pos0+8) == std::string::npos) && (content.find("TGDoubleHSlider", pos0+8) == std::string::npos) && (content.find("GetSlider()", pos0+8) == std::string::npos) && (content.find("Slider->", pos0+8) == std::string::npos)) { printf("%s not uses TGDoubleSlider.h\n", fname); res = 1; } } pos0 = content.find("TGSlider.h"); if (pos0 != std::string::npos) { if ((content.find("TGSlider", pos0+8) == std::string::npos) && (content.find("TGHSlider", pos0+8) == std::string::npos) && (content.find("TGVSlider", pos0+8) == std::string::npos) && (content.find("fSlider", pos0+8) == std::string::npos)) { printf("%s not uses TGSlider.h\n", fname); res = 1; } } pos0 = content.find("TGButton.h"); if (pos0 != std::string::npos) { if ((content.find("TGButton", pos0+8) == std::string::npos) && (content.find("TGTextButton", pos0+8) == std::string::npos) && (content.find("TGPictureButton", pos0+8) == std::string::npos) && (content.find("TGCheckButton", pos0+8) == std::string::npos) && (content.find("TGRadioButton", pos0+8) == std::string::npos) && (content.find("TGSplitButton", pos0+8) == std::string::npos)) { printf("%s not uses TGButton.h\n", fname); res = 1; } } pos0 = content.find("TGFSContainer.h"); if (pos0 != std::string::npos) { if ((content.find("TGFileItem", pos0+8) == std::string::npos) && (content.find("TGFileContainer", pos0+8) == std::string::npos)) { printf("%s not uses TGFSContainer.h\n", fname); res = 1; } } pos0 = content.find("TGTextEditDialogs.h"); if (pos0 != std::string::npos) { if ((content.find("TGSearchDialog", pos0+8) == std::string::npos) && (content.find("TGPrintDialog", pos0+8) == std::string::npos) && (content.find("TGGotoDialog", pos0+8) == std::string::npos)) { printf("%s not uses TGTextEditDialogs.h\n", fname); res = 1; } } static const std::vector<std::string> test_types = { "TObjString", "TTimer", "TUrl", "TBrowser", "TImage", "TDatime", "TTimeStamp", "TDate", "TVectorD", "TMatrixD", "THStack", "TArc", "TLine", "TText", "TLatex", "TCutG", "TBox", "TGaxis", "TPaveText", "TPaveStats", "TGraph", "TMarker", "TPoint", "TEllipse", "TPolyLine3D", "TPolyMarker3D", "TLegend", "TProfile", "TH1", "TH2", "TH3", "TF1", "TF2", "TF3", "TBuffer", "TMap", "TStopwatch", "TExec", "TMemFile", "TNamed", "TObject", // gui classes "TGCanvas", "TGColorDialog", "TGColorSelect", "TGComboBox", "TGFileBrowser", "TGFileDialog", "TGFontDialog", "TGFont", "TGFrame", "TGFSComboBox", "TGIcon", "TGInputDialog", "TGLabel", "TGLayout", "TGListBox", "TGListTree", "TGListView", "TGMdiDecorFrame", "TGMdiFrame", "TGMdi", "TGMdiMainFrame", "TGMdiMenu", "TGMsgBox", "TGNumberEntry", "TGObject", "TGPack", "TGPasswdDialog", "TGPicture", "TGProgressBar", "TGScrollBar", "TGSimpleTable", "TGSimpleTableInterface", "TGSpeedo", "TGSplitFrame", "TGStatusBar", "TGTableCell", "TGTable", "TGTableHeader", "TGTableLayout", "TGTextBuffer", "TGTextEdit", "TGTextEditor", "TGTextEntry", "TGText", "TGTextView", "TGToolBar", "TGToolTip", "TGuiBuilder", "TGView", "TGXYLayout" }; for(auto &clname : test_types) { std::string incname = clname + ".h"; auto pos = content.find(incname); if (pos != std::string::npos) { if (content.find(clname, pos+incname.length()) == std::string::npos) { printf("%s not used %s\n", fname, incname.c_str()); res = 1; } } } return res; } int main(int argc, const char **argv) { printf("Reduce includes utility v0.5\n"); if (argc < 3) { printf("Too few arguments\n"); return 1; } exec_cmd = argv[1]; printf("Build cmd: %s\n", exec_cmd); int sum = 0; const char *kind = "removed"; if (!strcmp(exec_cmd,"duplicate")) { kind = "duplicated"; for (int n=2; n<argc; ++n) sum += FindDuplicate(argv[n]); } else if (!strcmp(exec_cmd,"roothdr")) { kind = "roothdr"; for (int n=2; n<argc; ++n) sum += CheckRootHeader(argv[n]); } else if (!strcmp(exec_cmd,"rootsrc")) { kind = "rootsrc"; for (int n=2; n<argc; ++n) sum += CheckRootSource(argv[n]); } else { for (int n=2; n<argc; ++n) sum += ProcessFile(argv[n]); } printf("Files %d Total %s includes %d\n", argc-2, kind, sum); return 0; }
33.957143
135
0.534743
linev
07f1fda9b0cbc86c226ca508d9ff756a62166e8e
2,868
cpp
C++
src/model.cpp
nek0bit/LoopCube
882296f32bfe3a8b1765950a9b8c9e24af75d009
[ "MIT" ]
9
2020-04-03T21:20:02.000Z
2021-08-23T19:57:57.000Z
src/model.cpp
nek0bit/LoopCube
882296f32bfe3a8b1765950a9b8c9e24af75d009
[ "MIT" ]
2
2020-12-05T01:05:58.000Z
2021-01-23T04:41:24.000Z
src/model.cpp
nek0bit/LoopCube
882296f32bfe3a8b1765950a9b8c9e24af75d009
[ "MIT" ]
4
2020-07-04T13:47:33.000Z
2021-09-11T15:29:08.000Z
#include "model.hpp" Model::Model(const GLuint shader, const std::vector<Vertex>& vertices) : refCount{std::make_shared<int>(1)}, vao{0}, vbo{0}, size{0}, shader{shader} { if (shader != 0) { glGenVertexArrays(1, &vao); glGenBuffers(1, &vbo); if (vertices.size() > 0) setBufferData(vertices); } } Model::~Model() { if (*refCount == 1 && shader != 0) { glDeleteBuffers(1, &vbo); glDeleteVertexArrays(1, &vao); } (*refCount)--; } // Copy Model::Model(const Model& source) : refCount{source.refCount}, vao{source.vao}, vbo{source.vbo}, size{source.size}, shader{source.shader} { (*refCount)++; } // Move Model::Model(Model&& source) : refCount{std::move(source.refCount)}, vao{std::move(source.vao)}, vbo{std::move(source.vbo)}, size{std::move(source.size)}, shader{std::move(source.shader)} { // Probably simpler to do it this way (*refCount)++; } void Model::setBufferData(const std::vector<Vertex>& vertices, const GLenum usage) { if (shader != 0) { // Bind both values glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vbo); size = vertices.size(); // Used for glDrawArrays size glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex) * vertices.size(), &vertices[0], usage); setupVertexLayout(); } } void Model::setupVertexLayout() { constexpr uint8_t Stride = sizeof(Vertex); constexpr uint8_t positionSize = 3; constexpr uint8_t texCoordOffset = sizeof(glm::vec3); // First element in struct constexpr uint8_t texCoordSize = 2; const GLuint positionAttribute = glGetAttribLocation(shader, "position"); const GLuint texCoordAttribute = glGetAttribLocation(shader, "texCoord"); // Position // InputAttrib - valSize - Type - shouldNormalize - Stride - Offset glVertexAttribPointer(positionAttribute, positionSize, GL_FLOAT, GL_FALSE, Stride, 0); // texCoord glVertexAttribPointer(texCoordAttribute, texCoordSize, GL_FLOAT, GL_FALSE, Stride, (void*)(texCoordOffset)); // Enable Attrib Arrays glEnableVertexAttribArray(positionAttribute); glEnableVertexAttribArray(texCoordAttribute); } void Model::draw(const GLint& uModel, const GLint& uTex, const glm::vec3& translate, const glm::vec3& scale, const glm::vec2& texturePos) const noexcept { glBindVertexArray(vao); glm::mat4 model{1.0f}; model = glm::translate(model, translate); model = glm::scale(model, scale); glUniformMatrix4fv(uModel, 1, GL_FALSE, glm::value_ptr(model)); glUniform2fv(uTex, 1, glm::value_ptr(texturePos)); glDrawArrays(GL_TRIANGLES, 0, size); }
26.803738
93
0.623431
nek0bit
07f6ea22cf57c8391558d0117cae5868c4e7ce4d
189,298
cc
C++
vs/src/VsClient.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
vs/src/VsClient.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
vs/src/VsClient.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/vs/VsClient.h> #include <alibabacloud/core/SimpleCredentialsProvider.h> using namespace AlibabaCloud; using namespace AlibabaCloud::Location; using namespace AlibabaCloud::Vs; using namespace AlibabaCloud::Vs::Model; namespace { const std::string SERVICE_NAME = "vs"; } VsClient::VsClient(const Credentials &credentials, const ClientConfiguration &configuration) : RpcServiceClient(SERVICE_NAME, std::make_shared<SimpleCredentialsProvider>(credentials), configuration) { auto locationClient = std::make_shared<LocationClient>(credentials, configuration); endpointProvider_ = std::make_shared<EndpointProvider>(locationClient, configuration.regionId(), SERVICE_NAME, ""); } VsClient::VsClient(const std::shared_ptr<CredentialsProvider>& credentialsProvider, const ClientConfiguration & configuration) : RpcServiceClient(SERVICE_NAME, credentialsProvider, configuration) { auto locationClient = std::make_shared<LocationClient>(credentialsProvider, configuration); endpointProvider_ = std::make_shared<EndpointProvider>(locationClient, configuration.regionId(), SERVICE_NAME, ""); } VsClient::VsClient(const std::string & accessKeyId, const std::string & accessKeySecret, const ClientConfiguration & configuration) : RpcServiceClient(SERVICE_NAME, std::make_shared<SimpleCredentialsProvider>(accessKeyId, accessKeySecret), configuration) { auto locationClient = std::make_shared<LocationClient>(accessKeyId, accessKeySecret, configuration); endpointProvider_ = std::make_shared<EndpointProvider>(locationClient, configuration.regionId(), SERVICE_NAME, ""); } VsClient::~VsClient() {} VsClient::AddDeviceOutcome VsClient::addDevice(const AddDeviceRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return AddDeviceOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return AddDeviceOutcome(AddDeviceResult(outcome.result())); else return AddDeviceOutcome(outcome.error()); } void VsClient::addDeviceAsync(const AddDeviceRequest& request, const AddDeviceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, addDevice(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::AddDeviceOutcomeCallable VsClient::addDeviceCallable(const AddDeviceRequest &request) const { auto task = std::make_shared<std::packaged_task<AddDeviceOutcome()>>( [this, request]() { return this->addDevice(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::AddRenderingDeviceInternetPortsOutcome VsClient::addRenderingDeviceInternetPorts(const AddRenderingDeviceInternetPortsRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return AddRenderingDeviceInternetPortsOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return AddRenderingDeviceInternetPortsOutcome(AddRenderingDeviceInternetPortsResult(outcome.result())); else return AddRenderingDeviceInternetPortsOutcome(outcome.error()); } void VsClient::addRenderingDeviceInternetPortsAsync(const AddRenderingDeviceInternetPortsRequest& request, const AddRenderingDeviceInternetPortsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, addRenderingDeviceInternetPorts(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::AddRenderingDeviceInternetPortsOutcomeCallable VsClient::addRenderingDeviceInternetPortsCallable(const AddRenderingDeviceInternetPortsRequest &request) const { auto task = std::make_shared<std::packaged_task<AddRenderingDeviceInternetPortsOutcome()>>( [this, request]() { return this->addRenderingDeviceInternetPorts(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::AddVsPullStreamInfoConfigOutcome VsClient::addVsPullStreamInfoConfig(const AddVsPullStreamInfoConfigRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return AddVsPullStreamInfoConfigOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return AddVsPullStreamInfoConfigOutcome(AddVsPullStreamInfoConfigResult(outcome.result())); else return AddVsPullStreamInfoConfigOutcome(outcome.error()); } void VsClient::addVsPullStreamInfoConfigAsync(const AddVsPullStreamInfoConfigRequest& request, const AddVsPullStreamInfoConfigAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, addVsPullStreamInfoConfig(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::AddVsPullStreamInfoConfigOutcomeCallable VsClient::addVsPullStreamInfoConfigCallable(const AddVsPullStreamInfoConfigRequest &request) const { auto task = std::make_shared<std::packaged_task<AddVsPullStreamInfoConfigOutcome()>>( [this, request]() { return this->addVsPullStreamInfoConfig(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::BatchBindDirectoriesOutcome VsClient::batchBindDirectories(const BatchBindDirectoriesRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return BatchBindDirectoriesOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return BatchBindDirectoriesOutcome(BatchBindDirectoriesResult(outcome.result())); else return BatchBindDirectoriesOutcome(outcome.error()); } void VsClient::batchBindDirectoriesAsync(const BatchBindDirectoriesRequest& request, const BatchBindDirectoriesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, batchBindDirectories(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::BatchBindDirectoriesOutcomeCallable VsClient::batchBindDirectoriesCallable(const BatchBindDirectoriesRequest &request) const { auto task = std::make_shared<std::packaged_task<BatchBindDirectoriesOutcome()>>( [this, request]() { return this->batchBindDirectories(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::BatchBindParentPlatformDevicesOutcome VsClient::batchBindParentPlatformDevices(const BatchBindParentPlatformDevicesRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return BatchBindParentPlatformDevicesOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return BatchBindParentPlatformDevicesOutcome(BatchBindParentPlatformDevicesResult(outcome.result())); else return BatchBindParentPlatformDevicesOutcome(outcome.error()); } void VsClient::batchBindParentPlatformDevicesAsync(const BatchBindParentPlatformDevicesRequest& request, const BatchBindParentPlatformDevicesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, batchBindParentPlatformDevices(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::BatchBindParentPlatformDevicesOutcomeCallable VsClient::batchBindParentPlatformDevicesCallable(const BatchBindParentPlatformDevicesRequest &request) const { auto task = std::make_shared<std::packaged_task<BatchBindParentPlatformDevicesOutcome()>>( [this, request]() { return this->batchBindParentPlatformDevices(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::BatchBindPurchasedDevicesOutcome VsClient::batchBindPurchasedDevices(const BatchBindPurchasedDevicesRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return BatchBindPurchasedDevicesOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return BatchBindPurchasedDevicesOutcome(BatchBindPurchasedDevicesResult(outcome.result())); else return BatchBindPurchasedDevicesOutcome(outcome.error()); } void VsClient::batchBindPurchasedDevicesAsync(const BatchBindPurchasedDevicesRequest& request, const BatchBindPurchasedDevicesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, batchBindPurchasedDevices(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::BatchBindPurchasedDevicesOutcomeCallable VsClient::batchBindPurchasedDevicesCallable(const BatchBindPurchasedDevicesRequest &request) const { auto task = std::make_shared<std::packaged_task<BatchBindPurchasedDevicesOutcome()>>( [this, request]() { return this->batchBindPurchasedDevices(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::BatchBindTemplateOutcome VsClient::batchBindTemplate(const BatchBindTemplateRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return BatchBindTemplateOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return BatchBindTemplateOutcome(BatchBindTemplateResult(outcome.result())); else return BatchBindTemplateOutcome(outcome.error()); } void VsClient::batchBindTemplateAsync(const BatchBindTemplateRequest& request, const BatchBindTemplateAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, batchBindTemplate(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::BatchBindTemplateOutcomeCallable VsClient::batchBindTemplateCallable(const BatchBindTemplateRequest &request) const { auto task = std::make_shared<std::packaged_task<BatchBindTemplateOutcome()>>( [this, request]() { return this->batchBindTemplate(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::BatchBindTemplatesOutcome VsClient::batchBindTemplates(const BatchBindTemplatesRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return BatchBindTemplatesOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return BatchBindTemplatesOutcome(BatchBindTemplatesResult(outcome.result())); else return BatchBindTemplatesOutcome(outcome.error()); } void VsClient::batchBindTemplatesAsync(const BatchBindTemplatesRequest& request, const BatchBindTemplatesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, batchBindTemplates(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::BatchBindTemplatesOutcomeCallable VsClient::batchBindTemplatesCallable(const BatchBindTemplatesRequest &request) const { auto task = std::make_shared<std::packaged_task<BatchBindTemplatesOutcome()>>( [this, request]() { return this->batchBindTemplates(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::BatchDeleteDevicesOutcome VsClient::batchDeleteDevices(const BatchDeleteDevicesRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return BatchDeleteDevicesOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return BatchDeleteDevicesOutcome(BatchDeleteDevicesResult(outcome.result())); else return BatchDeleteDevicesOutcome(outcome.error()); } void VsClient::batchDeleteDevicesAsync(const BatchDeleteDevicesRequest& request, const BatchDeleteDevicesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, batchDeleteDevices(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::BatchDeleteDevicesOutcomeCallable VsClient::batchDeleteDevicesCallable(const BatchDeleteDevicesRequest &request) const { auto task = std::make_shared<std::packaged_task<BatchDeleteDevicesOutcome()>>( [this, request]() { return this->batchDeleteDevices(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::BatchDeleteVsDomainConfigsOutcome VsClient::batchDeleteVsDomainConfigs(const BatchDeleteVsDomainConfigsRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return BatchDeleteVsDomainConfigsOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return BatchDeleteVsDomainConfigsOutcome(BatchDeleteVsDomainConfigsResult(outcome.result())); else return BatchDeleteVsDomainConfigsOutcome(outcome.error()); } void VsClient::batchDeleteVsDomainConfigsAsync(const BatchDeleteVsDomainConfigsRequest& request, const BatchDeleteVsDomainConfigsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, batchDeleteVsDomainConfigs(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::BatchDeleteVsDomainConfigsOutcomeCallable VsClient::batchDeleteVsDomainConfigsCallable(const BatchDeleteVsDomainConfigsRequest &request) const { auto task = std::make_shared<std::packaged_task<BatchDeleteVsDomainConfigsOutcome()>>( [this, request]() { return this->batchDeleteVsDomainConfigs(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::BatchForbidVsStreamOutcome VsClient::batchForbidVsStream(const BatchForbidVsStreamRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return BatchForbidVsStreamOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return BatchForbidVsStreamOutcome(BatchForbidVsStreamResult(outcome.result())); else return BatchForbidVsStreamOutcome(outcome.error()); } void VsClient::batchForbidVsStreamAsync(const BatchForbidVsStreamRequest& request, const BatchForbidVsStreamAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, batchForbidVsStream(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::BatchForbidVsStreamOutcomeCallable VsClient::batchForbidVsStreamCallable(const BatchForbidVsStreamRequest &request) const { auto task = std::make_shared<std::packaged_task<BatchForbidVsStreamOutcome()>>( [this, request]() { return this->batchForbidVsStream(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::BatchResumeVsStreamOutcome VsClient::batchResumeVsStream(const BatchResumeVsStreamRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return BatchResumeVsStreamOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return BatchResumeVsStreamOutcome(BatchResumeVsStreamResult(outcome.result())); else return BatchResumeVsStreamOutcome(outcome.error()); } void VsClient::batchResumeVsStreamAsync(const BatchResumeVsStreamRequest& request, const BatchResumeVsStreamAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, batchResumeVsStream(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::BatchResumeVsStreamOutcomeCallable VsClient::batchResumeVsStreamCallable(const BatchResumeVsStreamRequest &request) const { auto task = std::make_shared<std::packaged_task<BatchResumeVsStreamOutcome()>>( [this, request]() { return this->batchResumeVsStream(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::BatchSetVsDomainConfigsOutcome VsClient::batchSetVsDomainConfigs(const BatchSetVsDomainConfigsRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return BatchSetVsDomainConfigsOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return BatchSetVsDomainConfigsOutcome(BatchSetVsDomainConfigsResult(outcome.result())); else return BatchSetVsDomainConfigsOutcome(outcome.error()); } void VsClient::batchSetVsDomainConfigsAsync(const BatchSetVsDomainConfigsRequest& request, const BatchSetVsDomainConfigsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, batchSetVsDomainConfigs(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::BatchSetVsDomainConfigsOutcomeCallable VsClient::batchSetVsDomainConfigsCallable(const BatchSetVsDomainConfigsRequest &request) const { auto task = std::make_shared<std::packaged_task<BatchSetVsDomainConfigsOutcome()>>( [this, request]() { return this->batchSetVsDomainConfigs(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::BatchStartDevicesOutcome VsClient::batchStartDevices(const BatchStartDevicesRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return BatchStartDevicesOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return BatchStartDevicesOutcome(BatchStartDevicesResult(outcome.result())); else return BatchStartDevicesOutcome(outcome.error()); } void VsClient::batchStartDevicesAsync(const BatchStartDevicesRequest& request, const BatchStartDevicesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, batchStartDevices(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::BatchStartDevicesOutcomeCallable VsClient::batchStartDevicesCallable(const BatchStartDevicesRequest &request) const { auto task = std::make_shared<std::packaged_task<BatchStartDevicesOutcome()>>( [this, request]() { return this->batchStartDevices(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::BatchStartStreamsOutcome VsClient::batchStartStreams(const BatchStartStreamsRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return BatchStartStreamsOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return BatchStartStreamsOutcome(BatchStartStreamsResult(outcome.result())); else return BatchStartStreamsOutcome(outcome.error()); } void VsClient::batchStartStreamsAsync(const BatchStartStreamsRequest& request, const BatchStartStreamsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, batchStartStreams(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::BatchStartStreamsOutcomeCallable VsClient::batchStartStreamsCallable(const BatchStartStreamsRequest &request) const { auto task = std::make_shared<std::packaged_task<BatchStartStreamsOutcome()>>( [this, request]() { return this->batchStartStreams(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::BatchStopDevicesOutcome VsClient::batchStopDevices(const BatchStopDevicesRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return BatchStopDevicesOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return BatchStopDevicesOutcome(BatchStopDevicesResult(outcome.result())); else return BatchStopDevicesOutcome(outcome.error()); } void VsClient::batchStopDevicesAsync(const BatchStopDevicesRequest& request, const BatchStopDevicesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, batchStopDevices(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::BatchStopDevicesOutcomeCallable VsClient::batchStopDevicesCallable(const BatchStopDevicesRequest &request) const { auto task = std::make_shared<std::packaged_task<BatchStopDevicesOutcome()>>( [this, request]() { return this->batchStopDevices(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::BatchStopStreamsOutcome VsClient::batchStopStreams(const BatchStopStreamsRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return BatchStopStreamsOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return BatchStopStreamsOutcome(BatchStopStreamsResult(outcome.result())); else return BatchStopStreamsOutcome(outcome.error()); } void VsClient::batchStopStreamsAsync(const BatchStopStreamsRequest& request, const BatchStopStreamsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, batchStopStreams(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::BatchStopStreamsOutcomeCallable VsClient::batchStopStreamsCallable(const BatchStopStreamsRequest &request) const { auto task = std::make_shared<std::packaged_task<BatchStopStreamsOutcome()>>( [this, request]() { return this->batchStopStreams(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::BatchUnbindDirectoriesOutcome VsClient::batchUnbindDirectories(const BatchUnbindDirectoriesRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return BatchUnbindDirectoriesOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return BatchUnbindDirectoriesOutcome(BatchUnbindDirectoriesResult(outcome.result())); else return BatchUnbindDirectoriesOutcome(outcome.error()); } void VsClient::batchUnbindDirectoriesAsync(const BatchUnbindDirectoriesRequest& request, const BatchUnbindDirectoriesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, batchUnbindDirectories(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::BatchUnbindDirectoriesOutcomeCallable VsClient::batchUnbindDirectoriesCallable(const BatchUnbindDirectoriesRequest &request) const { auto task = std::make_shared<std::packaged_task<BatchUnbindDirectoriesOutcome()>>( [this, request]() { return this->batchUnbindDirectories(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::BatchUnbindParentPlatformDevicesOutcome VsClient::batchUnbindParentPlatformDevices(const BatchUnbindParentPlatformDevicesRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return BatchUnbindParentPlatformDevicesOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return BatchUnbindParentPlatformDevicesOutcome(BatchUnbindParentPlatformDevicesResult(outcome.result())); else return BatchUnbindParentPlatformDevicesOutcome(outcome.error()); } void VsClient::batchUnbindParentPlatformDevicesAsync(const BatchUnbindParentPlatformDevicesRequest& request, const BatchUnbindParentPlatformDevicesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, batchUnbindParentPlatformDevices(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::BatchUnbindParentPlatformDevicesOutcomeCallable VsClient::batchUnbindParentPlatformDevicesCallable(const BatchUnbindParentPlatformDevicesRequest &request) const { auto task = std::make_shared<std::packaged_task<BatchUnbindParentPlatformDevicesOutcome()>>( [this, request]() { return this->batchUnbindParentPlatformDevices(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::BatchUnbindPurchasedDevicesOutcome VsClient::batchUnbindPurchasedDevices(const BatchUnbindPurchasedDevicesRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return BatchUnbindPurchasedDevicesOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return BatchUnbindPurchasedDevicesOutcome(BatchUnbindPurchasedDevicesResult(outcome.result())); else return BatchUnbindPurchasedDevicesOutcome(outcome.error()); } void VsClient::batchUnbindPurchasedDevicesAsync(const BatchUnbindPurchasedDevicesRequest& request, const BatchUnbindPurchasedDevicesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, batchUnbindPurchasedDevices(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::BatchUnbindPurchasedDevicesOutcomeCallable VsClient::batchUnbindPurchasedDevicesCallable(const BatchUnbindPurchasedDevicesRequest &request) const { auto task = std::make_shared<std::packaged_task<BatchUnbindPurchasedDevicesOutcome()>>( [this, request]() { return this->batchUnbindPurchasedDevices(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::BatchUnbindTemplateOutcome VsClient::batchUnbindTemplate(const BatchUnbindTemplateRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return BatchUnbindTemplateOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return BatchUnbindTemplateOutcome(BatchUnbindTemplateResult(outcome.result())); else return BatchUnbindTemplateOutcome(outcome.error()); } void VsClient::batchUnbindTemplateAsync(const BatchUnbindTemplateRequest& request, const BatchUnbindTemplateAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, batchUnbindTemplate(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::BatchUnbindTemplateOutcomeCallable VsClient::batchUnbindTemplateCallable(const BatchUnbindTemplateRequest &request) const { auto task = std::make_shared<std::packaged_task<BatchUnbindTemplateOutcome()>>( [this, request]() { return this->batchUnbindTemplate(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::BatchUnbindTemplatesOutcome VsClient::batchUnbindTemplates(const BatchUnbindTemplatesRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return BatchUnbindTemplatesOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return BatchUnbindTemplatesOutcome(BatchUnbindTemplatesResult(outcome.result())); else return BatchUnbindTemplatesOutcome(outcome.error()); } void VsClient::batchUnbindTemplatesAsync(const BatchUnbindTemplatesRequest& request, const BatchUnbindTemplatesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, batchUnbindTemplates(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::BatchUnbindTemplatesOutcomeCallable VsClient::batchUnbindTemplatesCallable(const BatchUnbindTemplatesRequest &request) const { auto task = std::make_shared<std::packaged_task<BatchUnbindTemplatesOutcome()>>( [this, request]() { return this->batchUnbindTemplates(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::BindDirectoryOutcome VsClient::bindDirectory(const BindDirectoryRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return BindDirectoryOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return BindDirectoryOutcome(BindDirectoryResult(outcome.result())); else return BindDirectoryOutcome(outcome.error()); } void VsClient::bindDirectoryAsync(const BindDirectoryRequest& request, const BindDirectoryAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, bindDirectory(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::BindDirectoryOutcomeCallable VsClient::bindDirectoryCallable(const BindDirectoryRequest &request) const { auto task = std::make_shared<std::packaged_task<BindDirectoryOutcome()>>( [this, request]() { return this->bindDirectory(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::BindParentPlatformDeviceOutcome VsClient::bindParentPlatformDevice(const BindParentPlatformDeviceRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return BindParentPlatformDeviceOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return BindParentPlatformDeviceOutcome(BindParentPlatformDeviceResult(outcome.result())); else return BindParentPlatformDeviceOutcome(outcome.error()); } void VsClient::bindParentPlatformDeviceAsync(const BindParentPlatformDeviceRequest& request, const BindParentPlatformDeviceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, bindParentPlatformDevice(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::BindParentPlatformDeviceOutcomeCallable VsClient::bindParentPlatformDeviceCallable(const BindParentPlatformDeviceRequest &request) const { auto task = std::make_shared<std::packaged_task<BindParentPlatformDeviceOutcome()>>( [this, request]() { return this->bindParentPlatformDevice(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::BindPurchasedDeviceOutcome VsClient::bindPurchasedDevice(const BindPurchasedDeviceRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return BindPurchasedDeviceOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return BindPurchasedDeviceOutcome(BindPurchasedDeviceResult(outcome.result())); else return BindPurchasedDeviceOutcome(outcome.error()); } void VsClient::bindPurchasedDeviceAsync(const BindPurchasedDeviceRequest& request, const BindPurchasedDeviceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, bindPurchasedDevice(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::BindPurchasedDeviceOutcomeCallable VsClient::bindPurchasedDeviceCallable(const BindPurchasedDeviceRequest &request) const { auto task = std::make_shared<std::packaged_task<BindPurchasedDeviceOutcome()>>( [this, request]() { return this->bindPurchasedDevice(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::BindTemplateOutcome VsClient::bindTemplate(const BindTemplateRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return BindTemplateOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return BindTemplateOutcome(BindTemplateResult(outcome.result())); else return BindTemplateOutcome(outcome.error()); } void VsClient::bindTemplateAsync(const BindTemplateRequest& request, const BindTemplateAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, bindTemplate(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::BindTemplateOutcomeCallable VsClient::bindTemplateCallable(const BindTemplateRequest &request) const { auto task = std::make_shared<std::packaged_task<BindTemplateOutcome()>>( [this, request]() { return this->bindTemplate(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::ContinuousAdjustOutcome VsClient::continuousAdjust(const ContinuousAdjustRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return ContinuousAdjustOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return ContinuousAdjustOutcome(ContinuousAdjustResult(outcome.result())); else return ContinuousAdjustOutcome(outcome.error()); } void VsClient::continuousAdjustAsync(const ContinuousAdjustRequest& request, const ContinuousAdjustAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, continuousAdjust(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::ContinuousAdjustOutcomeCallable VsClient::continuousAdjustCallable(const ContinuousAdjustRequest &request) const { auto task = std::make_shared<std::packaged_task<ContinuousAdjustOutcome()>>( [this, request]() { return this->continuousAdjust(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::ContinuousMoveOutcome VsClient::continuousMove(const ContinuousMoveRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return ContinuousMoveOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return ContinuousMoveOutcome(ContinuousMoveResult(outcome.result())); else return ContinuousMoveOutcome(outcome.error()); } void VsClient::continuousMoveAsync(const ContinuousMoveRequest& request, const ContinuousMoveAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, continuousMove(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::ContinuousMoveOutcomeCallable VsClient::continuousMoveCallable(const ContinuousMoveRequest &request) const { auto task = std::make_shared<std::packaged_task<ContinuousMoveOutcome()>>( [this, request]() { return this->continuousMove(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::CreateClusterOutcome VsClient::createCluster(const CreateClusterRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return CreateClusterOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return CreateClusterOutcome(CreateClusterResult(outcome.result())); else return CreateClusterOutcome(outcome.error()); } void VsClient::createClusterAsync(const CreateClusterRequest& request, const CreateClusterAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, createCluster(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::CreateClusterOutcomeCallable VsClient::createClusterCallable(const CreateClusterRequest &request) const { auto task = std::make_shared<std::packaged_task<CreateClusterOutcome()>>( [this, request]() { return this->createCluster(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::CreateDeviceOutcome VsClient::createDevice(const CreateDeviceRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return CreateDeviceOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return CreateDeviceOutcome(CreateDeviceResult(outcome.result())); else return CreateDeviceOutcome(outcome.error()); } void VsClient::createDeviceAsync(const CreateDeviceRequest& request, const CreateDeviceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, createDevice(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::CreateDeviceOutcomeCallable VsClient::createDeviceCallable(const CreateDeviceRequest &request) const { auto task = std::make_shared<std::packaged_task<CreateDeviceOutcome()>>( [this, request]() { return this->createDevice(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::CreateDeviceAlarmOutcome VsClient::createDeviceAlarm(const CreateDeviceAlarmRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return CreateDeviceAlarmOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return CreateDeviceAlarmOutcome(CreateDeviceAlarmResult(outcome.result())); else return CreateDeviceAlarmOutcome(outcome.error()); } void VsClient::createDeviceAlarmAsync(const CreateDeviceAlarmRequest& request, const CreateDeviceAlarmAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, createDeviceAlarm(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::CreateDeviceAlarmOutcomeCallable VsClient::createDeviceAlarmCallable(const CreateDeviceAlarmRequest &request) const { auto task = std::make_shared<std::packaged_task<CreateDeviceAlarmOutcome()>>( [this, request]() { return this->createDeviceAlarm(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::CreateDeviceSnapshotOutcome VsClient::createDeviceSnapshot(const CreateDeviceSnapshotRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return CreateDeviceSnapshotOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return CreateDeviceSnapshotOutcome(CreateDeviceSnapshotResult(outcome.result())); else return CreateDeviceSnapshotOutcome(outcome.error()); } void VsClient::createDeviceSnapshotAsync(const CreateDeviceSnapshotRequest& request, const CreateDeviceSnapshotAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, createDeviceSnapshot(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::CreateDeviceSnapshotOutcomeCallable VsClient::createDeviceSnapshotCallable(const CreateDeviceSnapshotRequest &request) const { auto task = std::make_shared<std::packaged_task<CreateDeviceSnapshotOutcome()>>( [this, request]() { return this->createDeviceSnapshot(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::CreateDirectoryOutcome VsClient::createDirectory(const CreateDirectoryRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return CreateDirectoryOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return CreateDirectoryOutcome(CreateDirectoryResult(outcome.result())); else return CreateDirectoryOutcome(outcome.error()); } void VsClient::createDirectoryAsync(const CreateDirectoryRequest& request, const CreateDirectoryAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, createDirectory(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::CreateDirectoryOutcomeCallable VsClient::createDirectoryCallable(const CreateDirectoryRequest &request) const { auto task = std::make_shared<std::packaged_task<CreateDirectoryOutcome()>>( [this, request]() { return this->createDirectory(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::CreateGroupOutcome VsClient::createGroup(const CreateGroupRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return CreateGroupOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return CreateGroupOutcome(CreateGroupResult(outcome.result())); else return CreateGroupOutcome(outcome.error()); } void VsClient::createGroupAsync(const CreateGroupRequest& request, const CreateGroupAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, createGroup(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::CreateGroupOutcomeCallable VsClient::createGroupCallable(const CreateGroupRequest &request) const { auto task = std::make_shared<std::packaged_task<CreateGroupOutcome()>>( [this, request]() { return this->createGroup(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::CreateParentPlatformOutcome VsClient::createParentPlatform(const CreateParentPlatformRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return CreateParentPlatformOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return CreateParentPlatformOutcome(CreateParentPlatformResult(outcome.result())); else return CreateParentPlatformOutcome(outcome.error()); } void VsClient::createParentPlatformAsync(const CreateParentPlatformRequest& request, const CreateParentPlatformAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, createParentPlatform(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::CreateParentPlatformOutcomeCallable VsClient::createParentPlatformCallable(const CreateParentPlatformRequest &request) const { auto task = std::make_shared<std::packaged_task<CreateParentPlatformOutcome()>>( [this, request]() { return this->createParentPlatform(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::CreateRenderingDeviceOutcome VsClient::createRenderingDevice(const CreateRenderingDeviceRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return CreateRenderingDeviceOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return CreateRenderingDeviceOutcome(CreateRenderingDeviceResult(outcome.result())); else return CreateRenderingDeviceOutcome(outcome.error()); } void VsClient::createRenderingDeviceAsync(const CreateRenderingDeviceRequest& request, const CreateRenderingDeviceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, createRenderingDevice(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::CreateRenderingDeviceOutcomeCallable VsClient::createRenderingDeviceCallable(const CreateRenderingDeviceRequest &request) const { auto task = std::make_shared<std::packaged_task<CreateRenderingDeviceOutcome()>>( [this, request]() { return this->createRenderingDevice(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::CreateStreamSnapshotOutcome VsClient::createStreamSnapshot(const CreateStreamSnapshotRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return CreateStreamSnapshotOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return CreateStreamSnapshotOutcome(CreateStreamSnapshotResult(outcome.result())); else return CreateStreamSnapshotOutcome(outcome.error()); } void VsClient::createStreamSnapshotAsync(const CreateStreamSnapshotRequest& request, const CreateStreamSnapshotAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, createStreamSnapshot(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::CreateStreamSnapshotOutcomeCallable VsClient::createStreamSnapshotCallable(const CreateStreamSnapshotRequest &request) const { auto task = std::make_shared<std::packaged_task<CreateStreamSnapshotOutcome()>>( [this, request]() { return this->createStreamSnapshot(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::CreateTemplateOutcome VsClient::createTemplate(const CreateTemplateRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return CreateTemplateOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return CreateTemplateOutcome(CreateTemplateResult(outcome.result())); else return CreateTemplateOutcome(outcome.error()); } void VsClient::createTemplateAsync(const CreateTemplateRequest& request, const CreateTemplateAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, createTemplate(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::CreateTemplateOutcomeCallable VsClient::createTemplateCallable(const CreateTemplateRequest &request) const { auto task = std::make_shared<std::packaged_task<CreateTemplateOutcome()>>( [this, request]() { return this->createTemplate(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DeleteBucketOutcome VsClient::deleteBucket(const DeleteBucketRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DeleteBucketOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DeleteBucketOutcome(DeleteBucketResult(outcome.result())); else return DeleteBucketOutcome(outcome.error()); } void VsClient::deleteBucketAsync(const DeleteBucketRequest& request, const DeleteBucketAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, deleteBucket(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DeleteBucketOutcomeCallable VsClient::deleteBucketCallable(const DeleteBucketRequest &request) const { auto task = std::make_shared<std::packaged_task<DeleteBucketOutcome()>>( [this, request]() { return this->deleteBucket(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DeleteClusterOutcome VsClient::deleteCluster(const DeleteClusterRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DeleteClusterOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DeleteClusterOutcome(DeleteClusterResult(outcome.result())); else return DeleteClusterOutcome(outcome.error()); } void VsClient::deleteClusterAsync(const DeleteClusterRequest& request, const DeleteClusterAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, deleteCluster(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DeleteClusterOutcomeCallable VsClient::deleteClusterCallable(const DeleteClusterRequest &request) const { auto task = std::make_shared<std::packaged_task<DeleteClusterOutcome()>>( [this, request]() { return this->deleteCluster(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DeleteDeviceOutcome VsClient::deleteDevice(const DeleteDeviceRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DeleteDeviceOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DeleteDeviceOutcome(DeleteDeviceResult(outcome.result())); else return DeleteDeviceOutcome(outcome.error()); } void VsClient::deleteDeviceAsync(const DeleteDeviceRequest& request, const DeleteDeviceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, deleteDevice(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DeleteDeviceOutcomeCallable VsClient::deleteDeviceCallable(const DeleteDeviceRequest &request) const { auto task = std::make_shared<std::packaged_task<DeleteDeviceOutcome()>>( [this, request]() { return this->deleteDevice(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DeleteDirectoryOutcome VsClient::deleteDirectory(const DeleteDirectoryRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DeleteDirectoryOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DeleteDirectoryOutcome(DeleteDirectoryResult(outcome.result())); else return DeleteDirectoryOutcome(outcome.error()); } void VsClient::deleteDirectoryAsync(const DeleteDirectoryRequest& request, const DeleteDirectoryAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, deleteDirectory(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DeleteDirectoryOutcomeCallable VsClient::deleteDirectoryCallable(const DeleteDirectoryRequest &request) const { auto task = std::make_shared<std::packaged_task<DeleteDirectoryOutcome()>>( [this, request]() { return this->deleteDirectory(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DeleteGroupOutcome VsClient::deleteGroup(const DeleteGroupRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DeleteGroupOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DeleteGroupOutcome(DeleteGroupResult(outcome.result())); else return DeleteGroupOutcome(outcome.error()); } void VsClient::deleteGroupAsync(const DeleteGroupRequest& request, const DeleteGroupAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, deleteGroup(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DeleteGroupOutcomeCallable VsClient::deleteGroupCallable(const DeleteGroupRequest &request) const { auto task = std::make_shared<std::packaged_task<DeleteGroupOutcome()>>( [this, request]() { return this->deleteGroup(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DeleteParentPlatformOutcome VsClient::deleteParentPlatform(const DeleteParentPlatformRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DeleteParentPlatformOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DeleteParentPlatformOutcome(DeleteParentPlatformResult(outcome.result())); else return DeleteParentPlatformOutcome(outcome.error()); } void VsClient::deleteParentPlatformAsync(const DeleteParentPlatformRequest& request, const DeleteParentPlatformAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, deleteParentPlatform(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DeleteParentPlatformOutcomeCallable VsClient::deleteParentPlatformCallable(const DeleteParentPlatformRequest &request) const { auto task = std::make_shared<std::packaged_task<DeleteParentPlatformOutcome()>>( [this, request]() { return this->deleteParentPlatform(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DeletePresetOutcome VsClient::deletePreset(const DeletePresetRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DeletePresetOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DeletePresetOutcome(DeletePresetResult(outcome.result())); else return DeletePresetOutcome(outcome.error()); } void VsClient::deletePresetAsync(const DeletePresetRequest& request, const DeletePresetAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, deletePreset(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DeletePresetOutcomeCallable VsClient::deletePresetCallable(const DeletePresetRequest &request) const { auto task = std::make_shared<std::packaged_task<DeletePresetOutcome()>>( [this, request]() { return this->deletePreset(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DeleteRenderingDeviceInternetPortsOutcome VsClient::deleteRenderingDeviceInternetPorts(const DeleteRenderingDeviceInternetPortsRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DeleteRenderingDeviceInternetPortsOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DeleteRenderingDeviceInternetPortsOutcome(DeleteRenderingDeviceInternetPortsResult(outcome.result())); else return DeleteRenderingDeviceInternetPortsOutcome(outcome.error()); } void VsClient::deleteRenderingDeviceInternetPortsAsync(const DeleteRenderingDeviceInternetPortsRequest& request, const DeleteRenderingDeviceInternetPortsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, deleteRenderingDeviceInternetPorts(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DeleteRenderingDeviceInternetPortsOutcomeCallable VsClient::deleteRenderingDeviceInternetPortsCallable(const DeleteRenderingDeviceInternetPortsRequest &request) const { auto task = std::make_shared<std::packaged_task<DeleteRenderingDeviceInternetPortsOutcome()>>( [this, request]() { return this->deleteRenderingDeviceInternetPorts(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DeleteRenderingDevicesOutcome VsClient::deleteRenderingDevices(const DeleteRenderingDevicesRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DeleteRenderingDevicesOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DeleteRenderingDevicesOutcome(DeleteRenderingDevicesResult(outcome.result())); else return DeleteRenderingDevicesOutcome(outcome.error()); } void VsClient::deleteRenderingDevicesAsync(const DeleteRenderingDevicesRequest& request, const DeleteRenderingDevicesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, deleteRenderingDevices(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DeleteRenderingDevicesOutcomeCallable VsClient::deleteRenderingDevicesCallable(const DeleteRenderingDevicesRequest &request) const { auto task = std::make_shared<std::packaged_task<DeleteRenderingDevicesOutcome()>>( [this, request]() { return this->deleteRenderingDevices(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DeleteTemplateOutcome VsClient::deleteTemplate(const DeleteTemplateRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DeleteTemplateOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DeleteTemplateOutcome(DeleteTemplateResult(outcome.result())); else return DeleteTemplateOutcome(outcome.error()); } void VsClient::deleteTemplateAsync(const DeleteTemplateRequest& request, const DeleteTemplateAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, deleteTemplate(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DeleteTemplateOutcomeCallable VsClient::deleteTemplateCallable(const DeleteTemplateRequest &request) const { auto task = std::make_shared<std::packaged_task<DeleteTemplateOutcome()>>( [this, request]() { return this->deleteTemplate(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DeleteVsPullStreamInfoConfigOutcome VsClient::deleteVsPullStreamInfoConfig(const DeleteVsPullStreamInfoConfigRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DeleteVsPullStreamInfoConfigOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DeleteVsPullStreamInfoConfigOutcome(DeleteVsPullStreamInfoConfigResult(outcome.result())); else return DeleteVsPullStreamInfoConfigOutcome(outcome.error()); } void VsClient::deleteVsPullStreamInfoConfigAsync(const DeleteVsPullStreamInfoConfigRequest& request, const DeleteVsPullStreamInfoConfigAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, deleteVsPullStreamInfoConfig(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DeleteVsPullStreamInfoConfigOutcomeCallable VsClient::deleteVsPullStreamInfoConfigCallable(const DeleteVsPullStreamInfoConfigRequest &request) const { auto task = std::make_shared<std::packaged_task<DeleteVsPullStreamInfoConfigOutcome()>>( [this, request]() { return this->deleteVsPullStreamInfoConfig(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DeleteVsStreamsNotifyUrlConfigOutcome VsClient::deleteVsStreamsNotifyUrlConfig(const DeleteVsStreamsNotifyUrlConfigRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DeleteVsStreamsNotifyUrlConfigOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DeleteVsStreamsNotifyUrlConfigOutcome(DeleteVsStreamsNotifyUrlConfigResult(outcome.result())); else return DeleteVsStreamsNotifyUrlConfigOutcome(outcome.error()); } void VsClient::deleteVsStreamsNotifyUrlConfigAsync(const DeleteVsStreamsNotifyUrlConfigRequest& request, const DeleteVsStreamsNotifyUrlConfigAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, deleteVsStreamsNotifyUrlConfig(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DeleteVsStreamsNotifyUrlConfigOutcomeCallable VsClient::deleteVsStreamsNotifyUrlConfigCallable(const DeleteVsStreamsNotifyUrlConfigRequest &request) const { auto task = std::make_shared<std::packaged_task<DeleteVsStreamsNotifyUrlConfigOutcome()>>( [this, request]() { return this->deleteVsStreamsNotifyUrlConfig(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeAccountStatOutcome VsClient::describeAccountStat(const DescribeAccountStatRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeAccountStatOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeAccountStatOutcome(DescribeAccountStatResult(outcome.result())); else return DescribeAccountStatOutcome(outcome.error()); } void VsClient::describeAccountStatAsync(const DescribeAccountStatRequest& request, const DescribeAccountStatAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeAccountStat(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeAccountStatOutcomeCallable VsClient::describeAccountStatCallable(const DescribeAccountStatRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeAccountStatOutcome()>>( [this, request]() { return this->describeAccountStat(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeClusterOutcome VsClient::describeCluster(const DescribeClusterRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeClusterOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeClusterOutcome(DescribeClusterResult(outcome.result())); else return DescribeClusterOutcome(outcome.error()); } void VsClient::describeClusterAsync(const DescribeClusterRequest& request, const DescribeClusterAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeCluster(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeClusterOutcomeCallable VsClient::describeClusterCallable(const DescribeClusterRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeClusterOutcome()>>( [this, request]() { return this->describeCluster(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeClusterDevicesOutcome VsClient::describeClusterDevices(const DescribeClusterDevicesRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeClusterDevicesOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeClusterDevicesOutcome(DescribeClusterDevicesResult(outcome.result())); else return DescribeClusterDevicesOutcome(outcome.error()); } void VsClient::describeClusterDevicesAsync(const DescribeClusterDevicesRequest& request, const DescribeClusterDevicesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeClusterDevices(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeClusterDevicesOutcomeCallable VsClient::describeClusterDevicesCallable(const DescribeClusterDevicesRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeClusterDevicesOutcome()>>( [this, request]() { return this->describeClusterDevices(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeClustersOutcome VsClient::describeClusters(const DescribeClustersRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeClustersOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeClustersOutcome(DescribeClustersResult(outcome.result())); else return DescribeClustersOutcome(outcome.error()); } void VsClient::describeClustersAsync(const DescribeClustersRequest& request, const DescribeClustersAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeClusters(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeClustersOutcomeCallable VsClient::describeClustersCallable(const DescribeClustersRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeClustersOutcome()>>( [this, request]() { return this->describeClusters(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeDeviceOutcome VsClient::describeDevice(const DescribeDeviceRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeDeviceOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeDeviceOutcome(DescribeDeviceResult(outcome.result())); else return DescribeDeviceOutcome(outcome.error()); } void VsClient::describeDeviceAsync(const DescribeDeviceRequest& request, const DescribeDeviceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeDevice(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeDeviceOutcomeCallable VsClient::describeDeviceCallable(const DescribeDeviceRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeDeviceOutcome()>>( [this, request]() { return this->describeDevice(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeDeviceChannelsOutcome VsClient::describeDeviceChannels(const DescribeDeviceChannelsRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeDeviceChannelsOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeDeviceChannelsOutcome(DescribeDeviceChannelsResult(outcome.result())); else return DescribeDeviceChannelsOutcome(outcome.error()); } void VsClient::describeDeviceChannelsAsync(const DescribeDeviceChannelsRequest& request, const DescribeDeviceChannelsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeDeviceChannels(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeDeviceChannelsOutcomeCallable VsClient::describeDeviceChannelsCallable(const DescribeDeviceChannelsRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeDeviceChannelsOutcome()>>( [this, request]() { return this->describeDeviceChannels(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeDeviceGatewayOutcome VsClient::describeDeviceGateway(const DescribeDeviceGatewayRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeDeviceGatewayOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeDeviceGatewayOutcome(DescribeDeviceGatewayResult(outcome.result())); else return DescribeDeviceGatewayOutcome(outcome.error()); } void VsClient::describeDeviceGatewayAsync(const DescribeDeviceGatewayRequest& request, const DescribeDeviceGatewayAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeDeviceGateway(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeDeviceGatewayOutcomeCallable VsClient::describeDeviceGatewayCallable(const DescribeDeviceGatewayRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeDeviceGatewayOutcome()>>( [this, request]() { return this->describeDeviceGateway(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeDeviceURLOutcome VsClient::describeDeviceURL(const DescribeDeviceURLRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeDeviceURLOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeDeviceURLOutcome(DescribeDeviceURLResult(outcome.result())); else return DescribeDeviceURLOutcome(outcome.error()); } void VsClient::describeDeviceURLAsync(const DescribeDeviceURLRequest& request, const DescribeDeviceURLAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeDeviceURL(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeDeviceURLOutcomeCallable VsClient::describeDeviceURLCallable(const DescribeDeviceURLRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeDeviceURLOutcome()>>( [this, request]() { return this->describeDeviceURL(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeDevicesOutcome VsClient::describeDevices(const DescribeDevicesRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeDevicesOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeDevicesOutcome(DescribeDevicesResult(outcome.result())); else return DescribeDevicesOutcome(outcome.error()); } void VsClient::describeDevicesAsync(const DescribeDevicesRequest& request, const DescribeDevicesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeDevices(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeDevicesOutcomeCallable VsClient::describeDevicesCallable(const DescribeDevicesRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeDevicesOutcome()>>( [this, request]() { return this->describeDevices(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeDirectoriesOutcome VsClient::describeDirectories(const DescribeDirectoriesRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeDirectoriesOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeDirectoriesOutcome(DescribeDirectoriesResult(outcome.result())); else return DescribeDirectoriesOutcome(outcome.error()); } void VsClient::describeDirectoriesAsync(const DescribeDirectoriesRequest& request, const DescribeDirectoriesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeDirectories(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeDirectoriesOutcomeCallable VsClient::describeDirectoriesCallable(const DescribeDirectoriesRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeDirectoriesOutcome()>>( [this, request]() { return this->describeDirectories(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeDirectoryOutcome VsClient::describeDirectory(const DescribeDirectoryRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeDirectoryOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeDirectoryOutcome(DescribeDirectoryResult(outcome.result())); else return DescribeDirectoryOutcome(outcome.error()); } void VsClient::describeDirectoryAsync(const DescribeDirectoryRequest& request, const DescribeDirectoryAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeDirectory(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeDirectoryOutcomeCallable VsClient::describeDirectoryCallable(const DescribeDirectoryRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeDirectoryOutcome()>>( [this, request]() { return this->describeDirectory(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeGroupOutcome VsClient::describeGroup(const DescribeGroupRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeGroupOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeGroupOutcome(DescribeGroupResult(outcome.result())); else return DescribeGroupOutcome(outcome.error()); } void VsClient::describeGroupAsync(const DescribeGroupRequest& request, const DescribeGroupAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeGroup(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeGroupOutcomeCallable VsClient::describeGroupCallable(const DescribeGroupRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeGroupOutcome()>>( [this, request]() { return this->describeGroup(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeGroupsOutcome VsClient::describeGroups(const DescribeGroupsRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeGroupsOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeGroupsOutcome(DescribeGroupsResult(outcome.result())); else return DescribeGroupsOutcome(outcome.error()); } void VsClient::describeGroupsAsync(const DescribeGroupsRequest& request, const DescribeGroupsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeGroups(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeGroupsOutcomeCallable VsClient::describeGroupsCallable(const DescribeGroupsRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeGroupsOutcome()>>( [this, request]() { return this->describeGroups(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeNodeDevicesInfoOutcome VsClient::describeNodeDevicesInfo(const DescribeNodeDevicesInfoRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeNodeDevicesInfoOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeNodeDevicesInfoOutcome(DescribeNodeDevicesInfoResult(outcome.result())); else return DescribeNodeDevicesInfoOutcome(outcome.error()); } void VsClient::describeNodeDevicesInfoAsync(const DescribeNodeDevicesInfoRequest& request, const DescribeNodeDevicesInfoAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeNodeDevicesInfo(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeNodeDevicesInfoOutcomeCallable VsClient::describeNodeDevicesInfoCallable(const DescribeNodeDevicesInfoRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeNodeDevicesInfoOutcome()>>( [this, request]() { return this->describeNodeDevicesInfo(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeParentPlatformOutcome VsClient::describeParentPlatform(const DescribeParentPlatformRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeParentPlatformOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeParentPlatformOutcome(DescribeParentPlatformResult(outcome.result())); else return DescribeParentPlatformOutcome(outcome.error()); } void VsClient::describeParentPlatformAsync(const DescribeParentPlatformRequest& request, const DescribeParentPlatformAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeParentPlatform(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeParentPlatformOutcomeCallable VsClient::describeParentPlatformCallable(const DescribeParentPlatformRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeParentPlatformOutcome()>>( [this, request]() { return this->describeParentPlatform(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeParentPlatformDevicesOutcome VsClient::describeParentPlatformDevices(const DescribeParentPlatformDevicesRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeParentPlatformDevicesOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeParentPlatformDevicesOutcome(DescribeParentPlatformDevicesResult(outcome.result())); else return DescribeParentPlatformDevicesOutcome(outcome.error()); } void VsClient::describeParentPlatformDevicesAsync(const DescribeParentPlatformDevicesRequest& request, const DescribeParentPlatformDevicesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeParentPlatformDevices(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeParentPlatformDevicesOutcomeCallable VsClient::describeParentPlatformDevicesCallable(const DescribeParentPlatformDevicesRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeParentPlatformDevicesOutcome()>>( [this, request]() { return this->describeParentPlatformDevices(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeParentPlatformsOutcome VsClient::describeParentPlatforms(const DescribeParentPlatformsRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeParentPlatformsOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeParentPlatformsOutcome(DescribeParentPlatformsResult(outcome.result())); else return DescribeParentPlatformsOutcome(outcome.error()); } void VsClient::describeParentPlatformsAsync(const DescribeParentPlatformsRequest& request, const DescribeParentPlatformsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeParentPlatforms(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeParentPlatformsOutcomeCallable VsClient::describeParentPlatformsCallable(const DescribeParentPlatformsRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeParentPlatformsOutcome()>>( [this, request]() { return this->describeParentPlatforms(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribePresetsOutcome VsClient::describePresets(const DescribePresetsRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribePresetsOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribePresetsOutcome(DescribePresetsResult(outcome.result())); else return DescribePresetsOutcome(outcome.error()); } void VsClient::describePresetsAsync(const DescribePresetsRequest& request, const DescribePresetsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describePresets(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribePresetsOutcomeCallable VsClient::describePresetsCallable(const DescribePresetsRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribePresetsOutcome()>>( [this, request]() { return this->describePresets(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribePurchasedDeviceOutcome VsClient::describePurchasedDevice(const DescribePurchasedDeviceRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribePurchasedDeviceOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribePurchasedDeviceOutcome(DescribePurchasedDeviceResult(outcome.result())); else return DescribePurchasedDeviceOutcome(outcome.error()); } void VsClient::describePurchasedDeviceAsync(const DescribePurchasedDeviceRequest& request, const DescribePurchasedDeviceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describePurchasedDevice(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribePurchasedDeviceOutcomeCallable VsClient::describePurchasedDeviceCallable(const DescribePurchasedDeviceRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribePurchasedDeviceOutcome()>>( [this, request]() { return this->describePurchasedDevice(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribePurchasedDevicesOutcome VsClient::describePurchasedDevices(const DescribePurchasedDevicesRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribePurchasedDevicesOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribePurchasedDevicesOutcome(DescribePurchasedDevicesResult(outcome.result())); else return DescribePurchasedDevicesOutcome(outcome.error()); } void VsClient::describePurchasedDevicesAsync(const DescribePurchasedDevicesRequest& request, const DescribePurchasedDevicesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describePurchasedDevices(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribePurchasedDevicesOutcomeCallable VsClient::describePurchasedDevicesCallable(const DescribePurchasedDevicesRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribePurchasedDevicesOutcome()>>( [this, request]() { return this->describePurchasedDevices(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeRecordsOutcome VsClient::describeRecords(const DescribeRecordsRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeRecordsOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeRecordsOutcome(DescribeRecordsResult(outcome.result())); else return DescribeRecordsOutcome(outcome.error()); } void VsClient::describeRecordsAsync(const DescribeRecordsRequest& request, const DescribeRecordsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeRecords(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeRecordsOutcomeCallable VsClient::describeRecordsCallable(const DescribeRecordsRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeRecordsOutcome()>>( [this, request]() { return this->describeRecords(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeRenderingDevicesOutcome VsClient::describeRenderingDevices(const DescribeRenderingDevicesRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeRenderingDevicesOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeRenderingDevicesOutcome(DescribeRenderingDevicesResult(outcome.result())); else return DescribeRenderingDevicesOutcome(outcome.error()); } void VsClient::describeRenderingDevicesAsync(const DescribeRenderingDevicesRequest& request, const DescribeRenderingDevicesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeRenderingDevices(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeRenderingDevicesOutcomeCallable VsClient::describeRenderingDevicesCallable(const DescribeRenderingDevicesRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeRenderingDevicesOutcome()>>( [this, request]() { return this->describeRenderingDevices(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeStreamOutcome VsClient::describeStream(const DescribeStreamRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeStreamOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeStreamOutcome(DescribeStreamResult(outcome.result())); else return DescribeStreamOutcome(outcome.error()); } void VsClient::describeStreamAsync(const DescribeStreamRequest& request, const DescribeStreamAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeStream(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeStreamOutcomeCallable VsClient::describeStreamCallable(const DescribeStreamRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeStreamOutcome()>>( [this, request]() { return this->describeStream(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeStreamURLOutcome VsClient::describeStreamURL(const DescribeStreamURLRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeStreamURLOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeStreamURLOutcome(DescribeStreamURLResult(outcome.result())); else return DescribeStreamURLOutcome(outcome.error()); } void VsClient::describeStreamURLAsync(const DescribeStreamURLRequest& request, const DescribeStreamURLAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeStreamURL(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeStreamURLOutcomeCallable VsClient::describeStreamURLCallable(const DescribeStreamURLRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeStreamURLOutcome()>>( [this, request]() { return this->describeStreamURL(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeStreamVodListOutcome VsClient::describeStreamVodList(const DescribeStreamVodListRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeStreamVodListOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeStreamVodListOutcome(DescribeStreamVodListResult(outcome.result())); else return DescribeStreamVodListOutcome(outcome.error()); } void VsClient::describeStreamVodListAsync(const DescribeStreamVodListRequest& request, const DescribeStreamVodListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeStreamVodList(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeStreamVodListOutcomeCallable VsClient::describeStreamVodListCallable(const DescribeStreamVodListRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeStreamVodListOutcome()>>( [this, request]() { return this->describeStreamVodList(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeStreamsOutcome VsClient::describeStreams(const DescribeStreamsRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeStreamsOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeStreamsOutcome(DescribeStreamsResult(outcome.result())); else return DescribeStreamsOutcome(outcome.error()); } void VsClient::describeStreamsAsync(const DescribeStreamsRequest& request, const DescribeStreamsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeStreams(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeStreamsOutcomeCallable VsClient::describeStreamsCallable(const DescribeStreamsRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeStreamsOutcome()>>( [this, request]() { return this->describeStreams(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeTemplateOutcome VsClient::describeTemplate(const DescribeTemplateRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeTemplateOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeTemplateOutcome(DescribeTemplateResult(outcome.result())); else return DescribeTemplateOutcome(outcome.error()); } void VsClient::describeTemplateAsync(const DescribeTemplateRequest& request, const DescribeTemplateAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeTemplate(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeTemplateOutcomeCallable VsClient::describeTemplateCallable(const DescribeTemplateRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeTemplateOutcome()>>( [this, request]() { return this->describeTemplate(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeTemplatesOutcome VsClient::describeTemplates(const DescribeTemplatesRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeTemplatesOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeTemplatesOutcome(DescribeTemplatesResult(outcome.result())); else return DescribeTemplatesOutcome(outcome.error()); } void VsClient::describeTemplatesAsync(const DescribeTemplatesRequest& request, const DescribeTemplatesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeTemplates(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeTemplatesOutcomeCallable VsClient::describeTemplatesCallable(const DescribeTemplatesRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeTemplatesOutcome()>>( [this, request]() { return this->describeTemplates(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeVodStreamURLOutcome VsClient::describeVodStreamURL(const DescribeVodStreamURLRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeVodStreamURLOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeVodStreamURLOutcome(DescribeVodStreamURLResult(outcome.result())); else return DescribeVodStreamURLOutcome(outcome.error()); } void VsClient::describeVodStreamURLAsync(const DescribeVodStreamURLRequest& request, const DescribeVodStreamURLAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeVodStreamURL(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeVodStreamURLOutcomeCallable VsClient::describeVodStreamURLCallable(const DescribeVodStreamURLRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeVodStreamURLOutcome()>>( [this, request]() { return this->describeVodStreamURL(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeVsCertificateDetailOutcome VsClient::describeVsCertificateDetail(const DescribeVsCertificateDetailRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeVsCertificateDetailOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeVsCertificateDetailOutcome(DescribeVsCertificateDetailResult(outcome.result())); else return DescribeVsCertificateDetailOutcome(outcome.error()); } void VsClient::describeVsCertificateDetailAsync(const DescribeVsCertificateDetailRequest& request, const DescribeVsCertificateDetailAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeVsCertificateDetail(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeVsCertificateDetailOutcomeCallable VsClient::describeVsCertificateDetailCallable(const DescribeVsCertificateDetailRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeVsCertificateDetailOutcome()>>( [this, request]() { return this->describeVsCertificateDetail(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeVsCertificateListOutcome VsClient::describeVsCertificateList(const DescribeVsCertificateListRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeVsCertificateListOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeVsCertificateListOutcome(DescribeVsCertificateListResult(outcome.result())); else return DescribeVsCertificateListOutcome(outcome.error()); } void VsClient::describeVsCertificateListAsync(const DescribeVsCertificateListRequest& request, const DescribeVsCertificateListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeVsCertificateList(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeVsCertificateListOutcomeCallable VsClient::describeVsCertificateListCallable(const DescribeVsCertificateListRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeVsCertificateListOutcome()>>( [this, request]() { return this->describeVsCertificateList(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeVsDomainBpsDataOutcome VsClient::describeVsDomainBpsData(const DescribeVsDomainBpsDataRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeVsDomainBpsDataOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeVsDomainBpsDataOutcome(DescribeVsDomainBpsDataResult(outcome.result())); else return DescribeVsDomainBpsDataOutcome(outcome.error()); } void VsClient::describeVsDomainBpsDataAsync(const DescribeVsDomainBpsDataRequest& request, const DescribeVsDomainBpsDataAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeVsDomainBpsData(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeVsDomainBpsDataOutcomeCallable VsClient::describeVsDomainBpsDataCallable(const DescribeVsDomainBpsDataRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeVsDomainBpsDataOutcome()>>( [this, request]() { return this->describeVsDomainBpsData(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeVsDomainCertificateInfoOutcome VsClient::describeVsDomainCertificateInfo(const DescribeVsDomainCertificateInfoRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeVsDomainCertificateInfoOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeVsDomainCertificateInfoOutcome(DescribeVsDomainCertificateInfoResult(outcome.result())); else return DescribeVsDomainCertificateInfoOutcome(outcome.error()); } void VsClient::describeVsDomainCertificateInfoAsync(const DescribeVsDomainCertificateInfoRequest& request, const DescribeVsDomainCertificateInfoAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeVsDomainCertificateInfo(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeVsDomainCertificateInfoOutcomeCallable VsClient::describeVsDomainCertificateInfoCallable(const DescribeVsDomainCertificateInfoRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeVsDomainCertificateInfoOutcome()>>( [this, request]() { return this->describeVsDomainCertificateInfo(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeVsDomainConfigsOutcome VsClient::describeVsDomainConfigs(const DescribeVsDomainConfigsRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeVsDomainConfigsOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeVsDomainConfigsOutcome(DescribeVsDomainConfigsResult(outcome.result())); else return DescribeVsDomainConfigsOutcome(outcome.error()); } void VsClient::describeVsDomainConfigsAsync(const DescribeVsDomainConfigsRequest& request, const DescribeVsDomainConfigsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeVsDomainConfigs(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeVsDomainConfigsOutcomeCallable VsClient::describeVsDomainConfigsCallable(const DescribeVsDomainConfigsRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeVsDomainConfigsOutcome()>>( [this, request]() { return this->describeVsDomainConfigs(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeVsDomainDetailOutcome VsClient::describeVsDomainDetail(const DescribeVsDomainDetailRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeVsDomainDetailOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeVsDomainDetailOutcome(DescribeVsDomainDetailResult(outcome.result())); else return DescribeVsDomainDetailOutcome(outcome.error()); } void VsClient::describeVsDomainDetailAsync(const DescribeVsDomainDetailRequest& request, const DescribeVsDomainDetailAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeVsDomainDetail(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeVsDomainDetailOutcomeCallable VsClient::describeVsDomainDetailCallable(const DescribeVsDomainDetailRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeVsDomainDetailOutcome()>>( [this, request]() { return this->describeVsDomainDetail(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeVsDomainPvDataOutcome VsClient::describeVsDomainPvData(const DescribeVsDomainPvDataRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeVsDomainPvDataOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeVsDomainPvDataOutcome(DescribeVsDomainPvDataResult(outcome.result())); else return DescribeVsDomainPvDataOutcome(outcome.error()); } void VsClient::describeVsDomainPvDataAsync(const DescribeVsDomainPvDataRequest& request, const DescribeVsDomainPvDataAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeVsDomainPvData(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeVsDomainPvDataOutcomeCallable VsClient::describeVsDomainPvDataCallable(const DescribeVsDomainPvDataRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeVsDomainPvDataOutcome()>>( [this, request]() { return this->describeVsDomainPvData(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeVsDomainPvUvDataOutcome VsClient::describeVsDomainPvUvData(const DescribeVsDomainPvUvDataRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeVsDomainPvUvDataOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeVsDomainPvUvDataOutcome(DescribeVsDomainPvUvDataResult(outcome.result())); else return DescribeVsDomainPvUvDataOutcome(outcome.error()); } void VsClient::describeVsDomainPvUvDataAsync(const DescribeVsDomainPvUvDataRequest& request, const DescribeVsDomainPvUvDataAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeVsDomainPvUvData(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeVsDomainPvUvDataOutcomeCallable VsClient::describeVsDomainPvUvDataCallable(const DescribeVsDomainPvUvDataRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeVsDomainPvUvDataOutcome()>>( [this, request]() { return this->describeVsDomainPvUvData(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeVsDomainRecordDataOutcome VsClient::describeVsDomainRecordData(const DescribeVsDomainRecordDataRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeVsDomainRecordDataOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeVsDomainRecordDataOutcome(DescribeVsDomainRecordDataResult(outcome.result())); else return DescribeVsDomainRecordDataOutcome(outcome.error()); } void VsClient::describeVsDomainRecordDataAsync(const DescribeVsDomainRecordDataRequest& request, const DescribeVsDomainRecordDataAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeVsDomainRecordData(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeVsDomainRecordDataOutcomeCallable VsClient::describeVsDomainRecordDataCallable(const DescribeVsDomainRecordDataRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeVsDomainRecordDataOutcome()>>( [this, request]() { return this->describeVsDomainRecordData(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeVsDomainRegionDataOutcome VsClient::describeVsDomainRegionData(const DescribeVsDomainRegionDataRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeVsDomainRegionDataOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeVsDomainRegionDataOutcome(DescribeVsDomainRegionDataResult(outcome.result())); else return DescribeVsDomainRegionDataOutcome(outcome.error()); } void VsClient::describeVsDomainRegionDataAsync(const DescribeVsDomainRegionDataRequest& request, const DescribeVsDomainRegionDataAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeVsDomainRegionData(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeVsDomainRegionDataOutcomeCallable VsClient::describeVsDomainRegionDataCallable(const DescribeVsDomainRegionDataRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeVsDomainRegionDataOutcome()>>( [this, request]() { return this->describeVsDomainRegionData(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeVsDomainReqBpsDataOutcome VsClient::describeVsDomainReqBpsData(const DescribeVsDomainReqBpsDataRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeVsDomainReqBpsDataOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeVsDomainReqBpsDataOutcome(DescribeVsDomainReqBpsDataResult(outcome.result())); else return DescribeVsDomainReqBpsDataOutcome(outcome.error()); } void VsClient::describeVsDomainReqBpsDataAsync(const DescribeVsDomainReqBpsDataRequest& request, const DescribeVsDomainReqBpsDataAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeVsDomainReqBpsData(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeVsDomainReqBpsDataOutcomeCallable VsClient::describeVsDomainReqBpsDataCallable(const DescribeVsDomainReqBpsDataRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeVsDomainReqBpsDataOutcome()>>( [this, request]() { return this->describeVsDomainReqBpsData(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeVsDomainReqTrafficDataOutcome VsClient::describeVsDomainReqTrafficData(const DescribeVsDomainReqTrafficDataRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeVsDomainReqTrafficDataOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeVsDomainReqTrafficDataOutcome(DescribeVsDomainReqTrafficDataResult(outcome.result())); else return DescribeVsDomainReqTrafficDataOutcome(outcome.error()); } void VsClient::describeVsDomainReqTrafficDataAsync(const DescribeVsDomainReqTrafficDataRequest& request, const DescribeVsDomainReqTrafficDataAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeVsDomainReqTrafficData(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeVsDomainReqTrafficDataOutcomeCallable VsClient::describeVsDomainReqTrafficDataCallable(const DescribeVsDomainReqTrafficDataRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeVsDomainReqTrafficDataOutcome()>>( [this, request]() { return this->describeVsDomainReqTrafficData(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeVsDomainSnapshotDataOutcome VsClient::describeVsDomainSnapshotData(const DescribeVsDomainSnapshotDataRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeVsDomainSnapshotDataOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeVsDomainSnapshotDataOutcome(DescribeVsDomainSnapshotDataResult(outcome.result())); else return DescribeVsDomainSnapshotDataOutcome(outcome.error()); } void VsClient::describeVsDomainSnapshotDataAsync(const DescribeVsDomainSnapshotDataRequest& request, const DescribeVsDomainSnapshotDataAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeVsDomainSnapshotData(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeVsDomainSnapshotDataOutcomeCallable VsClient::describeVsDomainSnapshotDataCallable(const DescribeVsDomainSnapshotDataRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeVsDomainSnapshotDataOutcome()>>( [this, request]() { return this->describeVsDomainSnapshotData(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeVsDomainTrafficDataOutcome VsClient::describeVsDomainTrafficData(const DescribeVsDomainTrafficDataRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeVsDomainTrafficDataOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeVsDomainTrafficDataOutcome(DescribeVsDomainTrafficDataResult(outcome.result())); else return DescribeVsDomainTrafficDataOutcome(outcome.error()); } void VsClient::describeVsDomainTrafficDataAsync(const DescribeVsDomainTrafficDataRequest& request, const DescribeVsDomainTrafficDataAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeVsDomainTrafficData(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeVsDomainTrafficDataOutcomeCallable VsClient::describeVsDomainTrafficDataCallable(const DescribeVsDomainTrafficDataRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeVsDomainTrafficDataOutcome()>>( [this, request]() { return this->describeVsDomainTrafficData(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeVsDomainUvDataOutcome VsClient::describeVsDomainUvData(const DescribeVsDomainUvDataRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeVsDomainUvDataOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeVsDomainUvDataOutcome(DescribeVsDomainUvDataResult(outcome.result())); else return DescribeVsDomainUvDataOutcome(outcome.error()); } void VsClient::describeVsDomainUvDataAsync(const DescribeVsDomainUvDataRequest& request, const DescribeVsDomainUvDataAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeVsDomainUvData(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeVsDomainUvDataOutcomeCallable VsClient::describeVsDomainUvDataCallable(const DescribeVsDomainUvDataRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeVsDomainUvDataOutcome()>>( [this, request]() { return this->describeVsDomainUvData(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeVsPullStreamInfoConfigOutcome VsClient::describeVsPullStreamInfoConfig(const DescribeVsPullStreamInfoConfigRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeVsPullStreamInfoConfigOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeVsPullStreamInfoConfigOutcome(DescribeVsPullStreamInfoConfigResult(outcome.result())); else return DescribeVsPullStreamInfoConfigOutcome(outcome.error()); } void VsClient::describeVsPullStreamInfoConfigAsync(const DescribeVsPullStreamInfoConfigRequest& request, const DescribeVsPullStreamInfoConfigAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeVsPullStreamInfoConfig(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeVsPullStreamInfoConfigOutcomeCallable VsClient::describeVsPullStreamInfoConfigCallable(const DescribeVsPullStreamInfoConfigRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeVsPullStreamInfoConfigOutcome()>>( [this, request]() { return this->describeVsPullStreamInfoConfig(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeVsStorageTrafficUsageDataOutcome VsClient::describeVsStorageTrafficUsageData(const DescribeVsStorageTrafficUsageDataRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeVsStorageTrafficUsageDataOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeVsStorageTrafficUsageDataOutcome(DescribeVsStorageTrafficUsageDataResult(outcome.result())); else return DescribeVsStorageTrafficUsageDataOutcome(outcome.error()); } void VsClient::describeVsStorageTrafficUsageDataAsync(const DescribeVsStorageTrafficUsageDataRequest& request, const DescribeVsStorageTrafficUsageDataAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeVsStorageTrafficUsageData(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeVsStorageTrafficUsageDataOutcomeCallable VsClient::describeVsStorageTrafficUsageDataCallable(const DescribeVsStorageTrafficUsageDataRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeVsStorageTrafficUsageDataOutcome()>>( [this, request]() { return this->describeVsStorageTrafficUsageData(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeVsStorageUsageDataOutcome VsClient::describeVsStorageUsageData(const DescribeVsStorageUsageDataRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeVsStorageUsageDataOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeVsStorageUsageDataOutcome(DescribeVsStorageUsageDataResult(outcome.result())); else return DescribeVsStorageUsageDataOutcome(outcome.error()); } void VsClient::describeVsStorageUsageDataAsync(const DescribeVsStorageUsageDataRequest& request, const DescribeVsStorageUsageDataAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeVsStorageUsageData(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeVsStorageUsageDataOutcomeCallable VsClient::describeVsStorageUsageDataCallable(const DescribeVsStorageUsageDataRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeVsStorageUsageDataOutcome()>>( [this, request]() { return this->describeVsStorageUsageData(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeVsStreamsNotifyUrlConfigOutcome VsClient::describeVsStreamsNotifyUrlConfig(const DescribeVsStreamsNotifyUrlConfigRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeVsStreamsNotifyUrlConfigOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeVsStreamsNotifyUrlConfigOutcome(DescribeVsStreamsNotifyUrlConfigResult(outcome.result())); else return DescribeVsStreamsNotifyUrlConfigOutcome(outcome.error()); } void VsClient::describeVsStreamsNotifyUrlConfigAsync(const DescribeVsStreamsNotifyUrlConfigRequest& request, const DescribeVsStreamsNotifyUrlConfigAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeVsStreamsNotifyUrlConfig(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeVsStreamsNotifyUrlConfigOutcomeCallable VsClient::describeVsStreamsNotifyUrlConfigCallable(const DescribeVsStreamsNotifyUrlConfigRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeVsStreamsNotifyUrlConfigOutcome()>>( [this, request]() { return this->describeVsStreamsNotifyUrlConfig(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeVsStreamsOnlineListOutcome VsClient::describeVsStreamsOnlineList(const DescribeVsStreamsOnlineListRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeVsStreamsOnlineListOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeVsStreamsOnlineListOutcome(DescribeVsStreamsOnlineListResult(outcome.result())); else return DescribeVsStreamsOnlineListOutcome(outcome.error()); } void VsClient::describeVsStreamsOnlineListAsync(const DescribeVsStreamsOnlineListRequest& request, const DescribeVsStreamsOnlineListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeVsStreamsOnlineList(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeVsStreamsOnlineListOutcomeCallable VsClient::describeVsStreamsOnlineListCallable(const DescribeVsStreamsOnlineListRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeVsStreamsOnlineListOutcome()>>( [this, request]() { return this->describeVsStreamsOnlineList(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeVsStreamsPublishListOutcome VsClient::describeVsStreamsPublishList(const DescribeVsStreamsPublishListRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeVsStreamsPublishListOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeVsStreamsPublishListOutcome(DescribeVsStreamsPublishListResult(outcome.result())); else return DescribeVsStreamsPublishListOutcome(outcome.error()); } void VsClient::describeVsStreamsPublishListAsync(const DescribeVsStreamsPublishListRequest& request, const DescribeVsStreamsPublishListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeVsStreamsPublishList(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeVsStreamsPublishListOutcomeCallable VsClient::describeVsStreamsPublishListCallable(const DescribeVsStreamsPublishListRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeVsStreamsPublishListOutcome()>>( [this, request]() { return this->describeVsStreamsPublishList(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeVsTopDomainsByFlowOutcome VsClient::describeVsTopDomainsByFlow(const DescribeVsTopDomainsByFlowRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeVsTopDomainsByFlowOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeVsTopDomainsByFlowOutcome(DescribeVsTopDomainsByFlowResult(outcome.result())); else return DescribeVsTopDomainsByFlowOutcome(outcome.error()); } void VsClient::describeVsTopDomainsByFlowAsync(const DescribeVsTopDomainsByFlowRequest& request, const DescribeVsTopDomainsByFlowAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeVsTopDomainsByFlow(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeVsTopDomainsByFlowOutcomeCallable VsClient::describeVsTopDomainsByFlowCallable(const DescribeVsTopDomainsByFlowRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeVsTopDomainsByFlowOutcome()>>( [this, request]() { return this->describeVsTopDomainsByFlow(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeVsUpPeakPublishStreamDataOutcome VsClient::describeVsUpPeakPublishStreamData(const DescribeVsUpPeakPublishStreamDataRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeVsUpPeakPublishStreamDataOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeVsUpPeakPublishStreamDataOutcome(DescribeVsUpPeakPublishStreamDataResult(outcome.result())); else return DescribeVsUpPeakPublishStreamDataOutcome(outcome.error()); } void VsClient::describeVsUpPeakPublishStreamDataAsync(const DescribeVsUpPeakPublishStreamDataRequest& request, const DescribeVsUpPeakPublishStreamDataAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeVsUpPeakPublishStreamData(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeVsUpPeakPublishStreamDataOutcomeCallable VsClient::describeVsUpPeakPublishStreamDataCallable(const DescribeVsUpPeakPublishStreamDataRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeVsUpPeakPublishStreamDataOutcome()>>( [this, request]() { return this->describeVsUpPeakPublishStreamData(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::DescribeVsUserResourcePackageOutcome VsClient::describeVsUserResourcePackage(const DescribeVsUserResourcePackageRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DescribeVsUserResourcePackageOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DescribeVsUserResourcePackageOutcome(DescribeVsUserResourcePackageResult(outcome.result())); else return DescribeVsUserResourcePackageOutcome(outcome.error()); } void VsClient::describeVsUserResourcePackageAsync(const DescribeVsUserResourcePackageRequest& request, const DescribeVsUserResourcePackageAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, describeVsUserResourcePackage(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::DescribeVsUserResourcePackageOutcomeCallable VsClient::describeVsUserResourcePackageCallable(const DescribeVsUserResourcePackageRequest &request) const { auto task = std::make_shared<std::packaged_task<DescribeVsUserResourcePackageOutcome()>>( [this, request]() { return this->describeVsUserResourcePackage(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::ForbidVsStreamOutcome VsClient::forbidVsStream(const ForbidVsStreamRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return ForbidVsStreamOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return ForbidVsStreamOutcome(ForbidVsStreamResult(outcome.result())); else return ForbidVsStreamOutcome(outcome.error()); } void VsClient::forbidVsStreamAsync(const ForbidVsStreamRequest& request, const ForbidVsStreamAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, forbidVsStream(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::ForbidVsStreamOutcomeCallable VsClient::forbidVsStreamCallable(const ForbidVsStreamRequest &request) const { auto task = std::make_shared<std::packaged_task<ForbidVsStreamOutcome()>>( [this, request]() { return this->forbidVsStream(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::GetBucketInfoOutcome VsClient::getBucketInfo(const GetBucketInfoRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return GetBucketInfoOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return GetBucketInfoOutcome(GetBucketInfoResult(outcome.result())); else return GetBucketInfoOutcome(outcome.error()); } void VsClient::getBucketInfoAsync(const GetBucketInfoRequest& request, const GetBucketInfoAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, getBucketInfo(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::GetBucketInfoOutcomeCallable VsClient::getBucketInfoCallable(const GetBucketInfoRequest &request) const { auto task = std::make_shared<std::packaged_task<GetBucketInfoOutcome()>>( [this, request]() { return this->getBucketInfo(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::GotoPresetOutcome VsClient::gotoPreset(const GotoPresetRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return GotoPresetOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return GotoPresetOutcome(GotoPresetResult(outcome.result())); else return GotoPresetOutcome(outcome.error()); } void VsClient::gotoPresetAsync(const GotoPresetRequest& request, const GotoPresetAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, gotoPreset(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::GotoPresetOutcomeCallable VsClient::gotoPresetCallable(const GotoPresetRequest &request) const { auto task = std::make_shared<std::packaged_task<GotoPresetOutcome()>>( [this, request]() { return this->gotoPreset(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::ListBucketsOutcome VsClient::listBuckets(const ListBucketsRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return ListBucketsOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return ListBucketsOutcome(ListBucketsResult(outcome.result())); else return ListBucketsOutcome(outcome.error()); } void VsClient::listBucketsAsync(const ListBucketsRequest& request, const ListBucketsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, listBuckets(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::ListBucketsOutcomeCallable VsClient::listBucketsCallable(const ListBucketsRequest &request) const { auto task = std::make_shared<std::packaged_task<ListBucketsOutcome()>>( [this, request]() { return this->listBuckets(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::ListDeviceChannelsOutcome VsClient::listDeviceChannels(const ListDeviceChannelsRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return ListDeviceChannelsOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return ListDeviceChannelsOutcome(ListDeviceChannelsResult(outcome.result())); else return ListDeviceChannelsOutcome(outcome.error()); } void VsClient::listDeviceChannelsAsync(const ListDeviceChannelsRequest& request, const ListDeviceChannelsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, listDeviceChannels(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::ListDeviceChannelsOutcomeCallable VsClient::listDeviceChannelsCallable(const ListDeviceChannelsRequest &request) const { auto task = std::make_shared<std::packaged_task<ListDeviceChannelsOutcome()>>( [this, request]() { return this->listDeviceChannels(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::ListDeviceRecordsOutcome VsClient::listDeviceRecords(const ListDeviceRecordsRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return ListDeviceRecordsOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return ListDeviceRecordsOutcome(ListDeviceRecordsResult(outcome.result())); else return ListDeviceRecordsOutcome(outcome.error()); } void VsClient::listDeviceRecordsAsync(const ListDeviceRecordsRequest& request, const ListDeviceRecordsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, listDeviceRecords(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::ListDeviceRecordsOutcomeCallable VsClient::listDeviceRecordsCallable(const ListDeviceRecordsRequest &request) const { auto task = std::make_shared<std::packaged_task<ListDeviceRecordsOutcome()>>( [this, request]() { return this->listDeviceRecords(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::ListObjectsOutcome VsClient::listObjects(const ListObjectsRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return ListObjectsOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return ListObjectsOutcome(ListObjectsResult(outcome.result())); else return ListObjectsOutcome(outcome.error()); } void VsClient::listObjectsAsync(const ListObjectsRequest& request, const ListObjectsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, listObjects(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::ListObjectsOutcomeCallable VsClient::listObjectsCallable(const ListObjectsRequest &request) const { auto task = std::make_shared<std::packaged_task<ListObjectsOutcome()>>( [this, request]() { return this->listObjects(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::ModifyDeviceOutcome VsClient::modifyDevice(const ModifyDeviceRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return ModifyDeviceOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return ModifyDeviceOutcome(ModifyDeviceResult(outcome.result())); else return ModifyDeviceOutcome(outcome.error()); } void VsClient::modifyDeviceAsync(const ModifyDeviceRequest& request, const ModifyDeviceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, modifyDevice(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::ModifyDeviceOutcomeCallable VsClient::modifyDeviceCallable(const ModifyDeviceRequest &request) const { auto task = std::make_shared<std::packaged_task<ModifyDeviceOutcome()>>( [this, request]() { return this->modifyDevice(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::ModifyDeviceAlarmOutcome VsClient::modifyDeviceAlarm(const ModifyDeviceAlarmRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return ModifyDeviceAlarmOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return ModifyDeviceAlarmOutcome(ModifyDeviceAlarmResult(outcome.result())); else return ModifyDeviceAlarmOutcome(outcome.error()); } void VsClient::modifyDeviceAlarmAsync(const ModifyDeviceAlarmRequest& request, const ModifyDeviceAlarmAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, modifyDeviceAlarm(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::ModifyDeviceAlarmOutcomeCallable VsClient::modifyDeviceAlarmCallable(const ModifyDeviceAlarmRequest &request) const { auto task = std::make_shared<std::packaged_task<ModifyDeviceAlarmOutcome()>>( [this, request]() { return this->modifyDeviceAlarm(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::ModifyDeviceCaptureOutcome VsClient::modifyDeviceCapture(const ModifyDeviceCaptureRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return ModifyDeviceCaptureOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return ModifyDeviceCaptureOutcome(ModifyDeviceCaptureResult(outcome.result())); else return ModifyDeviceCaptureOutcome(outcome.error()); } void VsClient::modifyDeviceCaptureAsync(const ModifyDeviceCaptureRequest& request, const ModifyDeviceCaptureAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, modifyDeviceCapture(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::ModifyDeviceCaptureOutcomeCallable VsClient::modifyDeviceCaptureCallable(const ModifyDeviceCaptureRequest &request) const { auto task = std::make_shared<std::packaged_task<ModifyDeviceCaptureOutcome()>>( [this, request]() { return this->modifyDeviceCapture(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::ModifyDeviceChannelsOutcome VsClient::modifyDeviceChannels(const ModifyDeviceChannelsRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return ModifyDeviceChannelsOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return ModifyDeviceChannelsOutcome(ModifyDeviceChannelsResult(outcome.result())); else return ModifyDeviceChannelsOutcome(outcome.error()); } void VsClient::modifyDeviceChannelsAsync(const ModifyDeviceChannelsRequest& request, const ModifyDeviceChannelsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, modifyDeviceChannels(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::ModifyDeviceChannelsOutcomeCallable VsClient::modifyDeviceChannelsCallable(const ModifyDeviceChannelsRequest &request) const { auto task = std::make_shared<std::packaged_task<ModifyDeviceChannelsOutcome()>>( [this, request]() { return this->modifyDeviceChannels(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::ModifyDirectoryOutcome VsClient::modifyDirectory(const ModifyDirectoryRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return ModifyDirectoryOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return ModifyDirectoryOutcome(ModifyDirectoryResult(outcome.result())); else return ModifyDirectoryOutcome(outcome.error()); } void VsClient::modifyDirectoryAsync(const ModifyDirectoryRequest& request, const ModifyDirectoryAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, modifyDirectory(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::ModifyDirectoryOutcomeCallable VsClient::modifyDirectoryCallable(const ModifyDirectoryRequest &request) const { auto task = std::make_shared<std::packaged_task<ModifyDirectoryOutcome()>>( [this, request]() { return this->modifyDirectory(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::ModifyGroupOutcome VsClient::modifyGroup(const ModifyGroupRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return ModifyGroupOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return ModifyGroupOutcome(ModifyGroupResult(outcome.result())); else return ModifyGroupOutcome(outcome.error()); } void VsClient::modifyGroupAsync(const ModifyGroupRequest& request, const ModifyGroupAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, modifyGroup(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::ModifyGroupOutcomeCallable VsClient::modifyGroupCallable(const ModifyGroupRequest &request) const { auto task = std::make_shared<std::packaged_task<ModifyGroupOutcome()>>( [this, request]() { return this->modifyGroup(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::ModifyParentPlatformOutcome VsClient::modifyParentPlatform(const ModifyParentPlatformRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return ModifyParentPlatformOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return ModifyParentPlatformOutcome(ModifyParentPlatformResult(outcome.result())); else return ModifyParentPlatformOutcome(outcome.error()); } void VsClient::modifyParentPlatformAsync(const ModifyParentPlatformRequest& request, const ModifyParentPlatformAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, modifyParentPlatform(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::ModifyParentPlatformOutcomeCallable VsClient::modifyParentPlatformCallable(const ModifyParentPlatformRequest &request) const { auto task = std::make_shared<std::packaged_task<ModifyParentPlatformOutcome()>>( [this, request]() { return this->modifyParentPlatform(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::ModifyTemplateOutcome VsClient::modifyTemplate(const ModifyTemplateRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return ModifyTemplateOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return ModifyTemplateOutcome(ModifyTemplateResult(outcome.result())); else return ModifyTemplateOutcome(outcome.error()); } void VsClient::modifyTemplateAsync(const ModifyTemplateRequest& request, const ModifyTemplateAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, modifyTemplate(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::ModifyTemplateOutcomeCallable VsClient::modifyTemplateCallable(const ModifyTemplateRequest &request) const { auto task = std::make_shared<std::packaged_task<ModifyTemplateOutcome()>>( [this, request]() { return this->modifyTemplate(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::OpenVsServiceOutcome VsClient::openVsService(const OpenVsServiceRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return OpenVsServiceOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return OpenVsServiceOutcome(OpenVsServiceResult(outcome.result())); else return OpenVsServiceOutcome(outcome.error()); } void VsClient::openVsServiceAsync(const OpenVsServiceRequest& request, const OpenVsServiceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, openVsService(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::OpenVsServiceOutcomeCallable VsClient::openVsServiceCallable(const OpenVsServiceRequest &request) const { auto task = std::make_shared<std::packaged_task<OpenVsServiceOutcome()>>( [this, request]() { return this->openVsService(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::OperateRenderingDevicesOutcome VsClient::operateRenderingDevices(const OperateRenderingDevicesRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return OperateRenderingDevicesOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return OperateRenderingDevicesOutcome(OperateRenderingDevicesResult(outcome.result())); else return OperateRenderingDevicesOutcome(outcome.error()); } void VsClient::operateRenderingDevicesAsync(const OperateRenderingDevicesRequest& request, const OperateRenderingDevicesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, operateRenderingDevices(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::OperateRenderingDevicesOutcomeCallable VsClient::operateRenderingDevicesCallable(const OperateRenderingDevicesRequest &request) const { auto task = std::make_shared<std::packaged_task<OperateRenderingDevicesOutcome()>>( [this, request]() { return this->operateRenderingDevices(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::PrepareUploadOutcome VsClient::prepareUpload(const PrepareUploadRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return PrepareUploadOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return PrepareUploadOutcome(PrepareUploadResult(outcome.result())); else return PrepareUploadOutcome(outcome.error()); } void VsClient::prepareUploadAsync(const PrepareUploadRequest& request, const PrepareUploadAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, prepareUpload(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::PrepareUploadOutcomeCallable VsClient::prepareUploadCallable(const PrepareUploadRequest &request) const { auto task = std::make_shared<std::packaged_task<PrepareUploadOutcome()>>( [this, request]() { return this->prepareUpload(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::PutBucketOutcome VsClient::putBucket(const PutBucketRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return PutBucketOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return PutBucketOutcome(PutBucketResult(outcome.result())); else return PutBucketOutcome(outcome.error()); } void VsClient::putBucketAsync(const PutBucketRequest& request, const PutBucketAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, putBucket(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::PutBucketOutcomeCallable VsClient::putBucketCallable(const PutBucketRequest &request) const { auto task = std::make_shared<std::packaged_task<PutBucketOutcome()>>( [this, request]() { return this->putBucket(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::ResetRenderingDevicesOutcome VsClient::resetRenderingDevices(const ResetRenderingDevicesRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return ResetRenderingDevicesOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return ResetRenderingDevicesOutcome(ResetRenderingDevicesResult(outcome.result())); else return ResetRenderingDevicesOutcome(outcome.error()); } void VsClient::resetRenderingDevicesAsync(const ResetRenderingDevicesRequest& request, const ResetRenderingDevicesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, resetRenderingDevices(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::ResetRenderingDevicesOutcomeCallable VsClient::resetRenderingDevicesCallable(const ResetRenderingDevicesRequest &request) const { auto task = std::make_shared<std::packaged_task<ResetRenderingDevicesOutcome()>>( [this, request]() { return this->resetRenderingDevices(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::ResumeVsStreamOutcome VsClient::resumeVsStream(const ResumeVsStreamRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return ResumeVsStreamOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return ResumeVsStreamOutcome(ResumeVsStreamResult(outcome.result())); else return ResumeVsStreamOutcome(outcome.error()); } void VsClient::resumeVsStreamAsync(const ResumeVsStreamRequest& request, const ResumeVsStreamAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, resumeVsStream(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::ResumeVsStreamOutcomeCallable VsClient::resumeVsStreamCallable(const ResumeVsStreamRequest &request) const { auto task = std::make_shared<std::packaged_task<ResumeVsStreamOutcome()>>( [this, request]() { return this->resumeVsStream(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::SetPresetOutcome VsClient::setPreset(const SetPresetRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return SetPresetOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return SetPresetOutcome(SetPresetResult(outcome.result())); else return SetPresetOutcome(outcome.error()); } void VsClient::setPresetAsync(const SetPresetRequest& request, const SetPresetAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, setPreset(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::SetPresetOutcomeCallable VsClient::setPresetCallable(const SetPresetRequest &request) const { auto task = std::make_shared<std::packaged_task<SetPresetOutcome()>>( [this, request]() { return this->setPreset(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::SetVsDomainCertificateOutcome VsClient::setVsDomainCertificate(const SetVsDomainCertificateRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return SetVsDomainCertificateOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return SetVsDomainCertificateOutcome(SetVsDomainCertificateResult(outcome.result())); else return SetVsDomainCertificateOutcome(outcome.error()); } void VsClient::setVsDomainCertificateAsync(const SetVsDomainCertificateRequest& request, const SetVsDomainCertificateAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, setVsDomainCertificate(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::SetVsDomainCertificateOutcomeCallable VsClient::setVsDomainCertificateCallable(const SetVsDomainCertificateRequest &request) const { auto task = std::make_shared<std::packaged_task<SetVsDomainCertificateOutcome()>>( [this, request]() { return this->setVsDomainCertificate(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::SetVsStreamsNotifyUrlConfigOutcome VsClient::setVsStreamsNotifyUrlConfig(const SetVsStreamsNotifyUrlConfigRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return SetVsStreamsNotifyUrlConfigOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return SetVsStreamsNotifyUrlConfigOutcome(SetVsStreamsNotifyUrlConfigResult(outcome.result())); else return SetVsStreamsNotifyUrlConfigOutcome(outcome.error()); } void VsClient::setVsStreamsNotifyUrlConfigAsync(const SetVsStreamsNotifyUrlConfigRequest& request, const SetVsStreamsNotifyUrlConfigAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, setVsStreamsNotifyUrlConfig(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::SetVsStreamsNotifyUrlConfigOutcomeCallable VsClient::setVsStreamsNotifyUrlConfigCallable(const SetVsStreamsNotifyUrlConfigRequest &request) const { auto task = std::make_shared<std::packaged_task<SetVsStreamsNotifyUrlConfigOutcome()>>( [this, request]() { return this->setVsStreamsNotifyUrlConfig(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::StartDeviceOutcome VsClient::startDevice(const StartDeviceRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return StartDeviceOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return StartDeviceOutcome(StartDeviceResult(outcome.result())); else return StartDeviceOutcome(outcome.error()); } void VsClient::startDeviceAsync(const StartDeviceRequest& request, const StartDeviceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, startDevice(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::StartDeviceOutcomeCallable VsClient::startDeviceCallable(const StartDeviceRequest &request) const { auto task = std::make_shared<std::packaged_task<StartDeviceOutcome()>>( [this, request]() { return this->startDevice(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::StartParentPlatformOutcome VsClient::startParentPlatform(const StartParentPlatformRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return StartParentPlatformOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return StartParentPlatformOutcome(StartParentPlatformResult(outcome.result())); else return StartParentPlatformOutcome(outcome.error()); } void VsClient::startParentPlatformAsync(const StartParentPlatformRequest& request, const StartParentPlatformAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, startParentPlatform(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::StartParentPlatformOutcomeCallable VsClient::startParentPlatformCallable(const StartParentPlatformRequest &request) const { auto task = std::make_shared<std::packaged_task<StartParentPlatformOutcome()>>( [this, request]() { return this->startParentPlatform(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::StartRecordStreamOutcome VsClient::startRecordStream(const StartRecordStreamRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return StartRecordStreamOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return StartRecordStreamOutcome(StartRecordStreamResult(outcome.result())); else return StartRecordStreamOutcome(outcome.error()); } void VsClient::startRecordStreamAsync(const StartRecordStreamRequest& request, const StartRecordStreamAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, startRecordStream(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::StartRecordStreamOutcomeCallable VsClient::startRecordStreamCallable(const StartRecordStreamRequest &request) const { auto task = std::make_shared<std::packaged_task<StartRecordStreamOutcome()>>( [this, request]() { return this->startRecordStream(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::StartStreamOutcome VsClient::startStream(const StartStreamRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return StartStreamOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return StartStreamOutcome(StartStreamResult(outcome.result())); else return StartStreamOutcome(outcome.error()); } void VsClient::startStreamAsync(const StartStreamRequest& request, const StartStreamAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, startStream(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::StartStreamOutcomeCallable VsClient::startStreamCallable(const StartStreamRequest &request) const { auto task = std::make_shared<std::packaged_task<StartStreamOutcome()>>( [this, request]() { return this->startStream(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::StartTransferStreamOutcome VsClient::startTransferStream(const StartTransferStreamRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return StartTransferStreamOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return StartTransferStreamOutcome(StartTransferStreamResult(outcome.result())); else return StartTransferStreamOutcome(outcome.error()); } void VsClient::startTransferStreamAsync(const StartTransferStreamRequest& request, const StartTransferStreamAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, startTransferStream(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::StartTransferStreamOutcomeCallable VsClient::startTransferStreamCallable(const StartTransferStreamRequest &request) const { auto task = std::make_shared<std::packaged_task<StartTransferStreamOutcome()>>( [this, request]() { return this->startTransferStream(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::StopAdjustOutcome VsClient::stopAdjust(const StopAdjustRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return StopAdjustOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return StopAdjustOutcome(StopAdjustResult(outcome.result())); else return StopAdjustOutcome(outcome.error()); } void VsClient::stopAdjustAsync(const StopAdjustRequest& request, const StopAdjustAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, stopAdjust(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::StopAdjustOutcomeCallable VsClient::stopAdjustCallable(const StopAdjustRequest &request) const { auto task = std::make_shared<std::packaged_task<StopAdjustOutcome()>>( [this, request]() { return this->stopAdjust(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::StopDeviceOutcome VsClient::stopDevice(const StopDeviceRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return StopDeviceOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return StopDeviceOutcome(StopDeviceResult(outcome.result())); else return StopDeviceOutcome(outcome.error()); } void VsClient::stopDeviceAsync(const StopDeviceRequest& request, const StopDeviceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, stopDevice(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::StopDeviceOutcomeCallable VsClient::stopDeviceCallable(const StopDeviceRequest &request) const { auto task = std::make_shared<std::packaged_task<StopDeviceOutcome()>>( [this, request]() { return this->stopDevice(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::StopMoveOutcome VsClient::stopMove(const StopMoveRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return StopMoveOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return StopMoveOutcome(StopMoveResult(outcome.result())); else return StopMoveOutcome(outcome.error()); } void VsClient::stopMoveAsync(const StopMoveRequest& request, const StopMoveAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, stopMove(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::StopMoveOutcomeCallable VsClient::stopMoveCallable(const StopMoveRequest &request) const { auto task = std::make_shared<std::packaged_task<StopMoveOutcome()>>( [this, request]() { return this->stopMove(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::StopRecordStreamOutcome VsClient::stopRecordStream(const StopRecordStreamRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return StopRecordStreamOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return StopRecordStreamOutcome(StopRecordStreamResult(outcome.result())); else return StopRecordStreamOutcome(outcome.error()); } void VsClient::stopRecordStreamAsync(const StopRecordStreamRequest& request, const StopRecordStreamAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, stopRecordStream(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::StopRecordStreamOutcomeCallable VsClient::stopRecordStreamCallable(const StopRecordStreamRequest &request) const { auto task = std::make_shared<std::packaged_task<StopRecordStreamOutcome()>>( [this, request]() { return this->stopRecordStream(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::StopStreamOutcome VsClient::stopStream(const StopStreamRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return StopStreamOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return StopStreamOutcome(StopStreamResult(outcome.result())); else return StopStreamOutcome(outcome.error()); } void VsClient::stopStreamAsync(const StopStreamRequest& request, const StopStreamAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, stopStream(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::StopStreamOutcomeCallable VsClient::stopStreamCallable(const StopStreamRequest &request) const { auto task = std::make_shared<std::packaged_task<StopStreamOutcome()>>( [this, request]() { return this->stopStream(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::StopTransferStreamOutcome VsClient::stopTransferStream(const StopTransferStreamRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return StopTransferStreamOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return StopTransferStreamOutcome(StopTransferStreamResult(outcome.result())); else return StopTransferStreamOutcome(outcome.error()); } void VsClient::stopTransferStreamAsync(const StopTransferStreamRequest& request, const StopTransferStreamAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, stopTransferStream(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::StopTransferStreamOutcomeCallable VsClient::stopTransferStreamCallable(const StopTransferStreamRequest &request) const { auto task = std::make_shared<std::packaged_task<StopTransferStreamOutcome()>>( [this, request]() { return this->stopTransferStream(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::SyncCatalogsOutcome VsClient::syncCatalogs(const SyncCatalogsRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return SyncCatalogsOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return SyncCatalogsOutcome(SyncCatalogsResult(outcome.result())); else return SyncCatalogsOutcome(outcome.error()); } void VsClient::syncCatalogsAsync(const SyncCatalogsRequest& request, const SyncCatalogsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, syncCatalogs(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::SyncCatalogsOutcomeCallable VsClient::syncCatalogsCallable(const SyncCatalogsRequest &request) const { auto task = std::make_shared<std::packaged_task<SyncCatalogsOutcome()>>( [this, request]() { return this->syncCatalogs(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::SyncDeviceChannelsOutcome VsClient::syncDeviceChannels(const SyncDeviceChannelsRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return SyncDeviceChannelsOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return SyncDeviceChannelsOutcome(SyncDeviceChannelsResult(outcome.result())); else return SyncDeviceChannelsOutcome(outcome.error()); } void VsClient::syncDeviceChannelsAsync(const SyncDeviceChannelsRequest& request, const SyncDeviceChannelsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, syncDeviceChannels(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::SyncDeviceChannelsOutcomeCallable VsClient::syncDeviceChannelsCallable(const SyncDeviceChannelsRequest &request) const { auto task = std::make_shared<std::packaged_task<SyncDeviceChannelsOutcome()>>( [this, request]() { return this->syncDeviceChannels(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::UnbindDirectoryOutcome VsClient::unbindDirectory(const UnbindDirectoryRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return UnbindDirectoryOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return UnbindDirectoryOutcome(UnbindDirectoryResult(outcome.result())); else return UnbindDirectoryOutcome(outcome.error()); } void VsClient::unbindDirectoryAsync(const UnbindDirectoryRequest& request, const UnbindDirectoryAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, unbindDirectory(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::UnbindDirectoryOutcomeCallable VsClient::unbindDirectoryCallable(const UnbindDirectoryRequest &request) const { auto task = std::make_shared<std::packaged_task<UnbindDirectoryOutcome()>>( [this, request]() { return this->unbindDirectory(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::UnbindParentPlatformDeviceOutcome VsClient::unbindParentPlatformDevice(const UnbindParentPlatformDeviceRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return UnbindParentPlatformDeviceOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return UnbindParentPlatformDeviceOutcome(UnbindParentPlatformDeviceResult(outcome.result())); else return UnbindParentPlatformDeviceOutcome(outcome.error()); } void VsClient::unbindParentPlatformDeviceAsync(const UnbindParentPlatformDeviceRequest& request, const UnbindParentPlatformDeviceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, unbindParentPlatformDevice(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::UnbindParentPlatformDeviceOutcomeCallable VsClient::unbindParentPlatformDeviceCallable(const UnbindParentPlatformDeviceRequest &request) const { auto task = std::make_shared<std::packaged_task<UnbindParentPlatformDeviceOutcome()>>( [this, request]() { return this->unbindParentPlatformDevice(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::UnbindPurchasedDeviceOutcome VsClient::unbindPurchasedDevice(const UnbindPurchasedDeviceRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return UnbindPurchasedDeviceOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return UnbindPurchasedDeviceOutcome(UnbindPurchasedDeviceResult(outcome.result())); else return UnbindPurchasedDeviceOutcome(outcome.error()); } void VsClient::unbindPurchasedDeviceAsync(const UnbindPurchasedDeviceRequest& request, const UnbindPurchasedDeviceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, unbindPurchasedDevice(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::UnbindPurchasedDeviceOutcomeCallable VsClient::unbindPurchasedDeviceCallable(const UnbindPurchasedDeviceRequest &request) const { auto task = std::make_shared<std::packaged_task<UnbindPurchasedDeviceOutcome()>>( [this, request]() { return this->unbindPurchasedDevice(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::UnbindTemplateOutcome VsClient::unbindTemplate(const UnbindTemplateRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return UnbindTemplateOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return UnbindTemplateOutcome(UnbindTemplateResult(outcome.result())); else return UnbindTemplateOutcome(outcome.error()); } void VsClient::unbindTemplateAsync(const UnbindTemplateRequest& request, const UnbindTemplateAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, unbindTemplate(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::UnbindTemplateOutcomeCallable VsClient::unbindTemplateCallable(const UnbindTemplateRequest &request) const { auto task = std::make_shared<std::packaged_task<UnbindTemplateOutcome()>>( [this, request]() { return this->unbindTemplate(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::UnlockDeviceOutcome VsClient::unlockDevice(const UnlockDeviceRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return UnlockDeviceOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return UnlockDeviceOutcome(UnlockDeviceResult(outcome.result())); else return UnlockDeviceOutcome(outcome.error()); } void VsClient::unlockDeviceAsync(const UnlockDeviceRequest& request, const UnlockDeviceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, unlockDevice(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::UnlockDeviceOutcomeCallable VsClient::unlockDeviceCallable(const UnlockDeviceRequest &request) const { auto task = std::make_shared<std::packaged_task<UnlockDeviceOutcome()>>( [this, request]() { return this->unlockDevice(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::UpdateBucketInfoOutcome VsClient::updateBucketInfo(const UpdateBucketInfoRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return UpdateBucketInfoOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return UpdateBucketInfoOutcome(UpdateBucketInfoResult(outcome.result())); else return UpdateBucketInfoOutcome(outcome.error()); } void VsClient::updateBucketInfoAsync(const UpdateBucketInfoRequest& request, const UpdateBucketInfoAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, updateBucketInfo(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::UpdateBucketInfoOutcomeCallable VsClient::updateBucketInfoCallable(const UpdateBucketInfoRequest &request) const { auto task = std::make_shared<std::packaged_task<UpdateBucketInfoOutcome()>>( [this, request]() { return this->updateBucketInfo(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::UpdateClusterOutcome VsClient::updateCluster(const UpdateClusterRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return UpdateClusterOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return UpdateClusterOutcome(UpdateClusterResult(outcome.result())); else return UpdateClusterOutcome(outcome.error()); } void VsClient::updateClusterAsync(const UpdateClusterRequest& request, const UpdateClusterAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, updateCluster(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::UpdateClusterOutcomeCallable VsClient::updateClusterCallable(const UpdateClusterRequest &request) const { auto task = std::make_shared<std::packaged_task<UpdateClusterOutcome()>>( [this, request]() { return this->updateCluster(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::UpdateRenderingDeviceSpecOutcome VsClient::updateRenderingDeviceSpec(const UpdateRenderingDeviceSpecRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return UpdateRenderingDeviceSpecOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return UpdateRenderingDeviceSpecOutcome(UpdateRenderingDeviceSpecResult(outcome.result())); else return UpdateRenderingDeviceSpecOutcome(outcome.error()); } void VsClient::updateRenderingDeviceSpecAsync(const UpdateRenderingDeviceSpecRequest& request, const UpdateRenderingDeviceSpecAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, updateRenderingDeviceSpec(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::UpdateRenderingDeviceSpecOutcomeCallable VsClient::updateRenderingDeviceSpecCallable(const UpdateRenderingDeviceSpecRequest &request) const { auto task = std::make_shared<std::packaged_task<UpdateRenderingDeviceSpecOutcome()>>( [this, request]() { return this->updateRenderingDeviceSpec(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::UpdateVsPullStreamInfoConfigOutcome VsClient::updateVsPullStreamInfoConfig(const UpdateVsPullStreamInfoConfigRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return UpdateVsPullStreamInfoConfigOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return UpdateVsPullStreamInfoConfigOutcome(UpdateVsPullStreamInfoConfigResult(outcome.result())); else return UpdateVsPullStreamInfoConfigOutcome(outcome.error()); } void VsClient::updateVsPullStreamInfoConfigAsync(const UpdateVsPullStreamInfoConfigRequest& request, const UpdateVsPullStreamInfoConfigAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, updateVsPullStreamInfoConfig(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::UpdateVsPullStreamInfoConfigOutcomeCallable VsClient::updateVsPullStreamInfoConfigCallable(const UpdateVsPullStreamInfoConfigRequest &request) const { auto task = std::make_shared<std::packaged_task<UpdateVsPullStreamInfoConfigOutcome()>>( [this, request]() { return this->updateVsPullStreamInfoConfig(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VsClient::UploadDeviceRecordOutcome VsClient::uploadDeviceRecord(const UploadDeviceRecordRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return UploadDeviceRecordOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return UploadDeviceRecordOutcome(UploadDeviceRecordResult(outcome.result())); else return UploadDeviceRecordOutcome(outcome.error()); } void VsClient::uploadDeviceRecordAsync(const UploadDeviceRecordRequest& request, const UploadDeviceRecordAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, uploadDeviceRecord(request), context); }; asyncExecute(new Runnable(fn)); } VsClient::UploadDeviceRecordOutcomeCallable VsClient::uploadDeviceRecordCallable(const UploadDeviceRecordRequest &request) const { auto task = std::make_shared<std::packaged_task<UploadDeviceRecordOutcome()>>( [this, request]() { return this->uploadDeviceRecord(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); }
34.708104
239
0.783585
aliyun