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
3c00ea4af063368d366e43bfb10b205d09d4aa39
322
hpp
C++
engine/core/math/interpolation/LerpXYZf/LerpXYZf.hpp
PiroDev/graphics-engine
bf1e5f57878c02421e2e8a787d94ce6074637402
[ "Apache-2.0" ]
null
null
null
engine/core/math/interpolation/LerpXYZf/LerpXYZf.hpp
PiroDev/graphics-engine
bf1e5f57878c02421e2e8a787d94ce6074637402
[ "Apache-2.0" ]
null
null
null
engine/core/math/interpolation/LerpXYZf/LerpXYZf.hpp
PiroDev/graphics-engine
bf1e5f57878c02421e2e8a787d94ce6074637402
[ "Apache-2.0" ]
null
null
null
#pragma once #include "core/math/interpolation/Lerp/Lerp.hpp" struct LerpXYZf { template <typename T> T operator()(T a, T b, float t) { Lerp lerp; float x = lerp(a.X(), b.X(), t); float y = lerp(a.Y(), b.Y(), t); float z = lerp(a.Z(), b.Z(), t); return {x,y,z}; } };
20.125
48
0.5
PiroDev
3c02a882093d7ce5efc1f9f88864a71c28d87af1
14,382
cpp
C++
APEX_1.4/shared/general/PxUserProfilerCallback/src/PsUserProfilerPVD.cpp
DoubleTT-Changan/0715
acbd071531ca4f3e2a82525b92f60824178c39fa
[ "Unlicense" ]
null
null
null
APEX_1.4/shared/general/PxUserProfilerCallback/src/PsUserProfilerPVD.cpp
DoubleTT-Changan/0715
acbd071531ca4f3e2a82525b92f60824178c39fa
[ "Unlicense" ]
null
null
null
APEX_1.4/shared/general/PxUserProfilerCallback/src/PsUserProfilerPVD.cpp
DoubleTT-Changan/0715
acbd071531ca4f3e2a82525b92f60824178c39fa
[ "Unlicense" ]
null
null
null
// // 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 NVIDIA CORPORATION 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 ``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. // // Copyright (c) 2008-2019 NVIDIA Corporation. All rights reserved. #include <assert.h> #include <stdio.h> #include <new> #include <windows.h> #include <PxAllocatorCallback.h> #include <PxErrorCallback.h> #include <PsFoundation.h> #include "PxUserProfilerCallback.h" #include "PxSimpleTypes.h" #include "PsHashMap.h" #include "SimpleHash.h" #include "PsMutex.h" #include "PxUserProfilerParent.h" namespace physx { using namespace pubfnd; using namespace shdfnd; }; #include "MemTracker.h" #include "PxProfileZone.h" #include "PxProfileZoneManager.h" #include "PxProfileEventSystem.h" #include "PxProfileEventHandler.h" #include "PxProfileEventNames.h" #include "PxProfileZone.h" #include "PxProfileScopedEvent.h" #include "PxProfileCompileTimeEventFilter.h" #include "PxProfileScopedEvent.h" #include "PVDBinding.h" #include "PvdConnectionType.h" #include "PVDBindingUserAllocator.h" #include "PVDBindingErrorStream.h" //#pragma comment(lib,"PhysXProfileSDK.lib") namespace PVD { struct SLocalFoundation { static PVDBindingUserAllocator sAllocator; physx::profile::PVDBindingErrorStream mErrorStream; SLocalFoundation() { using namespace physx::shdfnd; Foundation::createInstance(PX_PUBLIC_FOUNDATION_VERSION, mErrorStream, sAllocator); } ~SLocalFoundation() { using namespace physx::shdfnd; Foundation::destroyInstance(); } }; PVDBindingUserAllocator SLocalFoundation::sAllocator(""); } namespace physx { using namespace physx::pubfnd3; }; #ifdef WIN32 #include <windows.h> #endif #pragma warning(disable:4100 4996) using namespace physx; namespace PX_USER_PROFILER_CALLBACK { typedef SimpleHash< PxU16 > EventPVDMap; class PxUserProfilerCallbackPVD; class PxUserProfilerCallbackPVD : public PxUserProfilerCallback, public UserAllocated { public: PxUserProfilerCallbackPVD(PxUserProfilerParent *parent,const PxUserProfilerCallback::Desc &desc) { mActive = desc.profilerActive; mParent = parent; mOwnsPvdBinding = false; if ( desc.useMemTracker ) { mMemTracker = createMemTracker(); mMemTracker->setLogLevel(desc.logEveryAllocation,desc.logEveryFrame,desc.verifySingleThreaded); } else { mMemTracker = NULL; } mPvdBinding = desc.pvdBinding; if ( desc.createProfilerContext ) { // TODO: Create PVD binding here! mPvdBinding = &PVD::PvdBinding::create( false ); //Attempt to connect automatically to pvd. mPvdBinding->connect( "localhost", DEFAULT_PVD_BINDING_PORT, DEFAULT_PVD_BINDING_TIMEOUT_MS, PVD::PvdConnectionType::Profile | PVD::PvdConnectionType::Memory ); mOwnsPvdBinding = true; } mProfileZone = NULL; if ( mPvdBinding ) { mProfileZone = &mPvdBinding->getProfileManager().createProfileZone("PxUserProfilerCallback",PxProfileNames(),0x4000); } } virtual ~PxUserProfilerCallbackPVD(void) { if ( mMemTracker ) { releaseMemTracker(mMemTracker); } releaseProfiler(); } void releaseProfiler(void) { if ( mProfileZone ) { mProfileZone->release(); mProfileZone = NULL; } if ( mPvdBinding && mOwnsPvdBinding ) { mPvdBinding->release(); mPvdBinding = NULL; mOwnsPvdBinding = false; } } virtual bool trackInfo(const void *mem,TrackInfo &info) { bool ret = false; if ( mMemTracker ) { mMemMutex.lock(); ret = mMemTracker->trackInfo(mem,info); mMemMutex.unlock(); } return ret; } virtual void trackAlloc(void *mem,size_t size,MemoryType type,const char *context,const char *className,const char *fileName,physx::PxU32 lineno) { if ( mMemTracker ) { mMemMutex.lock(); mMemTracker->trackAlloc( getCurrentThreadId(), mem, size, type, context, className, fileName, lineno); mMemMutex.unlock(); } } virtual void trackRealloc(void *oldMem, void *newMem, size_t newSize, const char *context, const char *className, const char *fileName, physx::PxU32 lineno) { if ( mMemTracker ) { mMemMutex.lock(); mMemTracker->trackRealloc( getCurrentThreadId(), oldMem, newMem, newSize, context, className, fileName, lineno); mMemMutex.unlock(); } } virtual void trackFree(void *mem,MemoryType type,const char *context,const char *fileName,physx::PxU32 lineno) { if ( mMemTracker ) { mMemMutex.lock(); mMemTracker->trackFree(getCurrentThreadId(), mem, type, context, fileName, lineno); mMemMutex.unlock(); } } virtual const char * trackValidateFree(void *mem,MemoryType type,const char *context,const char *fileName,physx::PxU32 lineno) { const char *ret = NULL; if ( mMemTracker ) { mMemMutex.lock(); ret = mMemTracker->trackValidateFree(getCurrentThreadId(), mem, type, context, fileName, lineno); mMemMutex.unlock(); } return ret; } size_t getCurrentThreadId(void) { size_t ret = 0; #ifdef WIN32 ret = GetCurrentThreadId(); #endif return ret; } virtual bool memoryReport(MemoryReportFormat format,const char *fname,bool reportAllLeaks) // detect memory leaks and, if any, write out a report to the filename specified. { bool ret = false; if ( mMemTracker ) { mMemMutex.lock(); size_t leakCount; size_t leaked = mMemTracker->detectLeaks(leakCount); if ( leaked ) { physx::PxU32 dataLen; void *mem = mMemTracker->generateReport(format,fname,dataLen,reportAllLeaks); if ( mem ) { FILE *fph = fopen(fname,"wb"); fwrite(mem,dataLen,1,fph); fclose(fph); mMemTracker->releaseReportMemory(mem); } ret = true; // it leaked memory! } mMemMutex.unlock(); } return ret; } /** \brief This method is used to generate a memory usage report in memory. If it returns NULL then no active memory blocks are registered. (i.e. no leaks on application exit. */ virtual const void * memoryReport(MemoryReportFormat format, // The format to output the report in. const char *reportName, // The name of the report. bool reportAllLeaks, // Whether or not to output every single memory leak. *WARNING* Only enable this if you know you wish to identify a specific limited number of memory leaks. physx::PxU32 &reportSize) // The size of the output report. { const void *ret = NULL; if ( mMemTracker ) { mMemMutex.lock(); size_t leakCount; size_t leaked = mMemTracker->detectLeaks(leakCount); if ( leaked ) { physx::PxU32 dataLen; void *mem = mMemTracker->generateReport(format,reportName,dataLen,reportAllLeaks); if ( mem ) { ret = mem; reportSize = dataLen; } } mMemMutex.unlock(); } return ret; } /** \brief Releases the memory allocated for a previous memory report. */ virtual void releaseMemoryReport(const void *reportData) { if ( mMemTracker ) { mMemMutex.lock(); mMemTracker->releaseReportMemory((void *)reportData); mMemMutex.unlock(); } } virtual void profileStat(const char *statName, // The descriptive name of this statistic PxU64 context, // The context of this statistic. Data is presented 'in context' by PVD. This parameter is ignored by other profiler tools. physx::PxI64 statValue, // Up to a 16 bit signed integer value for the statistic. const char *fileName, // The source code file name where this statistic event was generated. physx::PxU32 lineno) // The source code line number where this statistic event was generated. { if ( mProfileZone ) { PxU16 eventId = mProfileZone->getEventIdForName(statName); mProfileZone->eventValue(eventId,context,statValue); } } // Mark the beginning of a profile zone. virtual void profileBegin(const char *str,physx::pubfnd3::PxU64 context,const char *fileName,physx::PxU32 lineno) { if ( mProfileZone ) { PxU16 eventId = mProfileZone->getEventIdForName(str); mProfileZone->startEvent(eventId,context); } } virtual void profileBegin(const char *str,physx::pubfnd3::PxU64 context,physx::pubfnd3::PxU32 threadId,const char *fileName,physx::PxU32 lineno) { if ( mProfileZone ) { PxU16 eventId = mProfileZone->getEventIdForName(str); mProfileZone->startEvent(eventId,context,threadId); } } // Mark the end of a profile zone virtual void profileEnd(const char *event,physx::pubfnd3::PxU64 context) { if ( mProfileZone ) { PxU16 eventId = mProfileZone->getEventIdForName(event); mProfileZone->stopEvent(eventId,context); } } virtual void profileEnd(const char *event,physx::pubfnd3::PxU64 context,physx::pubfnd3::PxU32 threadId) { if ( mProfileZone ) { PxU16 eventId = mProfileZone->getEventIdForName(event); mProfileZone->stopEvent(eventId,context,threadId); } } void profileMessageChannel(MessageChannelType type,const char *channel,const char *message,...) { } virtual void profileSectionName(const char *fmt,...) { } virtual void profileFrame(void) { mMemMutex.lock(); if ( mMemTracker ) { mMemTracker->trackFrame(); mMemTracker->plotStats(); } mMemMutex.unlock(); //If we don't own the pvd binding then apex or physx will be providing frame markers if ( mOwnsPvdBinding ) { PxU64 instPtr = static_cast<PxU64>( reinterpret_cast<size_t>( this ) ); mPvdBinding->endFrame( instPtr ); mPvdBinding->beginFrame( instPtr ); } } virtual void release(void) { PxUserProfilerParent *parent = mParent; delete this; parent->release(); } virtual void objectInit(void *mem,const char *object,const char *fileName,physx::PxU32 lineno) { } virtual void objectKill(void *mem,const char *fileName,physx::PxU32 lineno) { } virtual void objectInitArray(void *mem,size_t objectSize,size_t arraySize,const char *object,const char *fileName,physx::PxU32 lineno) { } virtual void objectKillArray(void *mem,const char *fileName,physx::PxU32 lineno) { } virtual void setProfilerHandle(Type type,void *context) { if ( type == PT_PVD ) { releaseProfiler(); { mPvdBinding = (PVD::PvdBinding *)context; if ( mPvdBinding ) mProfileZone = &mPvdBinding->getProfileManager().createProfileZone("PxUserProfilerCallback",PxProfileNames(),0x4000); } } } virtual void *getProfilerHandle(void) { return mPvdBinding; } /** \brief Reports the 'Type' of 3rd party profiler SDK being used. */ virtual Type getProfilerType(void) { return PT_PVD; } virtual void setProfilerActive(bool state) { mActive = state; } virtual bool getProfilerActive(void) const { return mActive; } /** \brief Processes a single data point to be plotted by the profiler. */ virtual void profilePlot(PlotType type, // How to display/format the data. physx::PxF32 value, // The data value to plot. const char *name) // The name of the data item. { } /** \brief Processes a single data point to be plotted by the profiler. */ virtual void profilePlot(PlotType type, // How to display/format the data. physx::PxF64 value, // The data value to plot. const char *name) // The name of the data item. { } /** \brief Processes a single data point to be plotted by the profiler. */ virtual void profilePlot(PlotType type, // How to display/format the data. PxU64 value, // The data value to plot. const char *name) // The name of the data item. { } /** \brief Processes a single data point to be plotted by the profiler. */ virtual void profilePlot(PlotType type, // How to display/format the data. physx::PxI64 value, // The data value to plot. const char *name) // The name of the data item. { } /** \brief Processes a single data point to be plotted by the profiler. */ virtual void profilePlot(PlotType type, // How to display/format the data. physx::PxU32 value, // The data value to plot. const char *name) // The name of the data item. { } /** \brief Processes a single data point to be plotted by the profiler. */ virtual void profilePlot(PlotType type, // How to display/format the data. physx::PxI32 value, // The data value to plot. const char *name) // The name of the data item. { } private: bool mActive; MemTracker *mMemTracker; PVD::PvdBinding *mPvdBinding; physx::PxProfileZone *mProfileZone; physx::Mutex mMemMutex; PxUserProfilerParent *mParent; bool mOwnsPvdBinding; }; PxUserProfilerCallback * createPxUserProfilerCallbackPVD(PxUserProfilerParent *parent,const PxUserProfilerCallback::Desc &desc) { PxUserProfilerCallbackPVD *ret = PX_NEW(PxUserProfilerCallbackPVD)(parent,desc); return static_cast<PxUserProfilerCallback *>(ret); } };
25.913514
190
0.697052
DoubleTT-Changan
3c040770e78affea2ff73870cff5f6f02a5cf003
4,909
hpp
C++
src/physics/thermal_conduction.hpp
joshessman-llnl/serac
1365a8f9ca372f0c50008b4b8f5f718955e4b80c
[ "BSD-3-Clause" ]
null
null
null
src/physics/thermal_conduction.hpp
joshessman-llnl/serac
1365a8f9ca372f0c50008b4b8f5f718955e4b80c
[ "BSD-3-Clause" ]
null
null
null
src/physics/thermal_conduction.hpp
joshessman-llnl/serac
1365a8f9ca372f0c50008b4b8f5f718955e4b80c
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2019-2020, Lawrence Livermore National Security, LLC and // other Serac Project Developers. See the top-level LICENSE file for // details. // // SPDX-License-Identifier: (BSD-3-Clause) /** * @file thermal_solver.hpp * * @brief An object containing the solver for a thermal conduction PDE */ #ifndef THERMAL_CONDUCTION #define THERMAL_CONDUCTION #include "mfem.hpp" #include "physics/base_physics.hpp" #include "physics/operators/thermal_operators.hpp" namespace serac { /** * @brief An object containing the solver for a thermal conduction PDE * * This is a generic linear thermal diffusion oeprator of the form * * M du/dt = -kappa Ku + f * * where M is a mass matrix, K is a stiffness matrix, and f is a * thermal load vector. */ class ThermalConduction : public BasePhysics { public: /** * @brief Construct a new Thermal Solver object * * @param[in] order The order of the thermal field discretization * @param[in] mesh The MFEM parallel mesh to solve the PDE on */ ThermalConduction(int order, std::shared_ptr<mfem::ParMesh> mesh); /** * @brief Set essential temperature boundary conditions (strongly enforced) * * @param[in] temp_bdr The boundary attributes on which to enforce a temperature * @param[in] temp_bdr_coef The prescribed boundary temperature */ void setTemperatureBCs(const std::set<int>& temp_bdr, std::shared_ptr<mfem::Coefficient> temp_bdr_coef); /** * @brief Set flux boundary conditions (weakly enforced) * * @param[in] flux_bdr The boundary attributes on which to enforce a heat flux (weakly enforced) * @param[in] flux_bdr_coef The prescribed boundary heat flux */ void setFluxBCs(const std::set<int>& flux_bdr, std::shared_ptr<mfem::Coefficient> flux_bdr_coef); /** * @brief Advance the timestep * * @param[inout] dt The timestep to advance. For adaptive time integration methods, the actual timestep is returned. */ void advanceTimestep(double& dt) override; /** * @brief Set the thermal conductivity * * @param[in] kappa The thermal conductivity */ void setConductivity(std::unique_ptr<mfem::Coefficient>&& kappa); /** * @brief Set the temperature state vector from a coefficient * * @param[in] temp The temperature coefficient */ void setTemperature(mfem::Coefficient& temp); /** * @brief Set the thermal body source from a coefficient * * @param[in] source The source function coefficient */ void setSource(std::unique_ptr<mfem::Coefficient>&& source); /** * @brief Get the temperature state * * @return A pointer to the current temperature finite element state */ std::shared_ptr<serac::FiniteElementState> temperature() { return temperature_; }; /** * @brief Complete the initialization and allocation of the data structures. * * This must be called before StaticSolve() or AdvanceTimestep(). If allow_dynamic * = false, do not allocate the mass matrix or dynamic operator */ void completeSetup() override; /** * @brief Set the linear solver parameters for both the M and K matrices * * @param[in] params The linear solver parameters */ void setLinearSolverParameters(const serac::LinearSolverParameters& params); /** * @brief Destroy the Thermal Solver object */ virtual ~ThermalConduction() = default; protected: /** * @brief The temperature finite element state */ std::shared_ptr<serac::FiniteElementState> temperature_; /** * @brief Mass bilinear form object */ std::unique_ptr<mfem::ParBilinearForm> M_form_; /** * @brief Stiffness bilinear form object */ std::unique_ptr<mfem::ParBilinearForm> K_form_; /** * @brief Assembled mass matrix */ std::unique_ptr<mfem::HypreParMatrix> M_mat_; /** * @brief Assembled stiffness matrix */ std::unique_ptr<mfem::HypreParMatrix> K_mat_; /** * @brief Thermal load linear form */ std::unique_ptr<mfem::ParLinearForm> l_form_; /** * @brief Assembled BC load vector */ std::unique_ptr<mfem::HypreParVector> bc_rhs_; /** * @brief Assembled RHS vector */ std::unique_ptr<mfem::HypreParVector> rhs_; /** * @brief Linear solver for the K operator */ std::unique_ptr<mfem::CGSolver> K_solver_; /** * @brief Preconditioner for the K operator */ std::unique_ptr<mfem::HypreSmoother> K_prec_; /** * @brief Conduction coefficient */ std::unique_ptr<mfem::Coefficient> kappa_; /** * @brief Body source coefficient */ std::unique_ptr<mfem::Coefficient> source_; /** * @brief Time integration operator */ std::unique_ptr<DynamicConductionOperator> dyn_oper_; /** * @brief Linear solver parameters */ serac::LinearSolverParameters lin_params_; /** * @brief Solve the Quasi-static operator */ void quasiStaticSolve(); }; } // namespace serac #endif
25.435233
118
0.693013
joshessman-llnl
3c05ee821a724213154ecb7978d814b923c73db2
5,423
cpp
C++
REDSI_1160929_1161573/boost_1_67_0/libs/spirit/test/qi/real5.cpp
Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo
eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8
[ "MIT" ]
198
2015-01-13T05:47:18.000Z
2022-03-09T04:46:46.000Z
libs/boost/libs/spirit/test/qi/real5.cpp
flingone/frameworks_base_cmds_remoted
4509d9f0468137ed7fd8d100179160d167e7d943
[ "Apache-2.0" ]
9
2015-01-28T16:33:19.000Z
2020-04-12T23:03:28.000Z
libs/boost/libs/spirit/test/qi/real5.cpp
flingone/frameworks_base_cmds_remoted
4509d9f0468137ed7fd8d100179160d167e7d943
[ "Apache-2.0" ]
139
2015-01-15T20:09:31.000Z
2022-01-31T15:21:16.000Z
/*============================================================================= Copyright (c) 2001-2011 Joel de Guzman Copyright (c) 2001-2011 Hartmut Kaiser Copyright (c) 2011 Bryce Lelbach 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) =============================================================================*/ #include "real.hpp" int main() { using spirit_test::test; using spirit_test::test_attr; /////////////////////////////////////////////////////////////////////////// // parameterized signed real number tests /////////////////////////////////////////////////////////////////////////// { using boost::spirit::qi::double_; double d; BOOST_TEST(test("+1234", double_(1234))); BOOST_TEST(!test("+1234", double_(-1234))); BOOST_TEST(test_attr("+1234", double_(1234), d)); BOOST_TEST(compare(d, 1234)); BOOST_TEST(!test_attr("+1234", double_(-1234), d)); BOOST_TEST(test("-1234", double_(-1234))); BOOST_TEST(!test("-1234", double_(1234))); BOOST_TEST(test_attr("-1234", double_(-1234), d)); BOOST_TEST(compare(d, -1234)); BOOST_TEST(!test_attr("-1234", double_(1234), d)); BOOST_TEST(test("+1.2e3", double_(1.2e3))); BOOST_TEST(!test("+1.2e3", double_(-1.2e3))); BOOST_TEST(test_attr("+1.2e3", double_(1.2e3), d)); BOOST_TEST(compare(d, 1.2e3)); BOOST_TEST(!test_attr("+1.2e3", double_(-1.2e3), d)); BOOST_TEST(test("-1.2e3", double_(-1.2e3))); BOOST_TEST(!test("-1.2e3", double_(1.2e3))); BOOST_TEST(test_attr("-1.2e3", double_(-1.2e3), d)); BOOST_TEST(compare(d, -1.2e3)); BOOST_TEST(!test_attr("-1.2e3", double_(1.2e3), d)); } /////////////////////////////////////////////////////////////////////////// // parameterized unsigned real number tests /////////////////////////////////////////////////////////////////////////// { using boost::spirit::qi::real_parser; using boost::spirit::qi::ureal_policies; double d; real_parser<double, ureal_policies<double> > udouble; BOOST_TEST(test("1234", udouble(1234))); BOOST_TEST(!test("1234", udouble(4321))); BOOST_TEST(test_attr("1234", udouble(1234), d)); BOOST_TEST(compare(d, 1234)); BOOST_TEST(!test_attr("1234", udouble(4321), d)); BOOST_TEST(test("1.2e3", udouble(1.2e3))); BOOST_TEST(!test("1.2e3", udouble(3.2e1))); BOOST_TEST(test_attr("1.2e3", udouble(1.2e3), d)); BOOST_TEST(compare(d, 1.2e3)); BOOST_TEST(!test_attr("1.2e3", udouble(3.2e1), d)); } /////////////////////////////////////////////////////////////////////////// // parameterized custom data type /////////////////////////////////////////////////////////////////////////// { using boost::math::concepts::real_concept; using boost::spirit::qi::real_parser; using boost::spirit::qi::real_policies; real_parser<real_concept, real_policies<real_concept> > custom_real; real_concept d; BOOST_TEST(test("-1234", custom_real(-1234))); BOOST_TEST(!test("-1234", custom_real(4321))); BOOST_TEST(test_attr("-1234", custom_real(-1234), d)); BOOST_TEST(compare(d, -1234)); BOOST_TEST(!test_attr("-1234", custom_real(-4321), d)); BOOST_TEST(test("1.2e3", custom_real(1.2e3))); BOOST_TEST(!test("1.2e3", custom_real(-1.2e3))); BOOST_TEST(test_attr("1.2e3", custom_real(1.2e3), d)); BOOST_TEST(compare(d, 1.2e3)); BOOST_TEST(!test_attr("1.2e3", custom_real(-3.2e1), d)); } /////////////////////////////////////////////////////////////////////////// // parameterized lazy tests /////////////////////////////////////////////////////////////////////////// { using boost::phoenix::ref; using boost::spirit::qi::double_; double n = 1.2e3, m = 3.2e1; BOOST_TEST(test("1.2e3", double_(ref(n)))); BOOST_TEST(!test("1.2e3", double_(ref(m)))); } /////////////////////////////////////////////////////////////////////////// // literal real number tests /////////////////////////////////////////////////////////////////////////// { using boost::spirit::qi::lit; BOOST_TEST(test("+1.2e3", lit(1.2e3))); BOOST_TEST(!test("+1.2e3", lit(-1.2e3))); BOOST_TEST(test("-1.2e3", lit(-1.2e3))); BOOST_TEST(!test("-1.2e3", lit(1.2e3))); BOOST_TEST(test("1.2e3", lit(1.2e3))); BOOST_TEST(!test("1.2e3", lit(3.2e1))); } /////////////////////////////////////////////////////////////////////////// // literal lazy tests /////////////////////////////////////////////////////////////////////////// { using boost::spirit::qi::lit; using boost::phoenix::ref; double n = 1.2e3, m = 3.2e1; BOOST_TEST(test("1.2e3", lit(ref(n)))); BOOST_TEST(!test("1.2e3", lit(ref(m)))); } return boost::report_errors(); }
39.297101
80
0.44551
Wultyc
3c072513e9cc8f1ca894d5db59629249bf10f939
3,411
hh
C++
src/ros_tf_listener.hh
MaximilienNaveau/dynamic_graph_bridge
6dafe58f9e72263fd361efa824c26ac49b96276d
[ "BSD-2-Clause" ]
null
null
null
src/ros_tf_listener.hh
MaximilienNaveau/dynamic_graph_bridge
6dafe58f9e72263fd361efa824c26ac49b96276d
[ "BSD-2-Clause" ]
null
null
null
src/ros_tf_listener.hh
MaximilienNaveau/dynamic_graph_bridge
6dafe58f9e72263fd361efa824c26ac49b96276d
[ "BSD-2-Clause" ]
1
2021-11-29T16:46:35.000Z
2021-11-29T16:46:35.000Z
#ifndef DYNAMIC_GRAPH_ROS_TF_LISTENER_HH # define DYNAMIC_GRAPH_ROS_TF_LISTENER_HH # include <boost/bind.hpp> # include <tf/transform_listener.h> # include <dynamic-graph/entity.h> # include <dynamic-graph/signal.h> # include <dynamic-graph/command-bind.h> # include <sot/core/matrix-geometry.hh> namespace dynamicgraph { class RosTfListener; namespace internal { struct TransformListenerData { typedef Signal<sot::MatrixHomogeneous, int> signal_t; tf::TransformListener& listener; const std::string toFrame, fromFrame; tf::StampedTransform transform; signal_t signal; TransformListenerData (tf::TransformListener& l, const std::string& to, const std::string& from, const std::string& signame) : listener (l) , toFrame (to) , fromFrame (from) , signal (signame) { signal.setFunction (boost::bind(&TransformListenerData::getTransform, this, _1, _2)); } sot::MatrixHomogeneous& getTransform (sot::MatrixHomogeneous& res, int time) { static const ros::Time rosTime(0); try { listener.lookupTransform (toFrame, fromFrame, rosTime, transform); } catch (const tf::TransformException& ex) { res.setIdentity(); ROS_ERROR("Enable to get transform at time %i: %s",time,ex.what()); return res; } for (sot::MatrixHomogeneous::Index r = 0; r < 3; ++r) { for (sot::MatrixHomogeneous::Index c = 0; c < 3; ++c) res.linear ()(r,c) = transform.getBasis().getRow(r)[c]; res.translation()[r] = transform.getOrigin()[r]; } return res; } }; } // end of internal namespace. class RosTfListener : public Entity { DYNAMIC_GRAPH_ENTITY_DECL(); public: typedef internal::TransformListenerData TransformListenerData; RosTfListener (const std::string& name) : Entity (name) { std::string docstring = "\n" " Add a signal containing the transform between two frames.\n" "\n" " Input:\n" " - to : frame name\n" " - from: frame name,\n" " - signalName: the signal name in dynamic-graph" "\n"; addCommand ("add", command::makeCommandVoid3(*this, &RosTfListener::add, docstring)); } ~RosTfListener () { for (Map_t::const_iterator _it = listenerDatas.begin(); _it != listenerDatas.end(); ++_it) delete _it->second; } void add (const std::string& to, const std::string& from, const std::string& signame) { if (listenerDatas.find(signame) != listenerDatas.end()) throw std::invalid_argument ("A signal " + signame + " already exists in RosTfListener " + getName()); boost::format signalName ("RosTfListener(%1%)::output(MatrixHomo)::%2%"); signalName % getName () % signame; TransformListenerData* tld = new TransformListenerData ( listener, to, from, signalName.str()); signalRegistration (tld->signal); listenerDatas[signame] = tld; } private: typedef std::map<std::string, TransformListenerData*> Map_t; Map_t listenerDatas; tf::TransformListener listener; }; } // end of namespace dynamicgraph. #endif // DYNAMIC_GRAPH_ROS_TF_LISTENER_HH
31.293578
98
0.609792
MaximilienNaveau
3c077c72ae28c607e34fab4c2021cee4a682f1d7
10,797
cpp
C++
testing/test_preparacion.cpp
miglesias91/scraping
4ac5a81ff5172afce3915db7a49dd4cc7845ac2a
[ "Apache-2.0" ]
null
null
null
testing/test_preparacion.cpp
miglesias91/scraping
4ac5a81ff5172afce3915db7a49dd4cc7845ac2a
[ "Apache-2.0" ]
18
2018-02-12T01:11:17.000Z
2018-05-10T17:15:02.000Z
testing/test_preparacion.cpp
miglesias91/scraping
4ac5a81ff5172afce3915db7a49dd4cc7845ac2a
[ "Apache-2.0" ]
null
null
null
// catch2 #include <catch.hpp> // scraping #include <scraping/include/IAdministradorScraping.h> // analisis #include <analisis/include/FuerzaEnNoticia.h> #include <analisis/include/Sentimiento.h> #include <analisis/include/ResultadoFuerzaEnNoticia.h> #include <analisis/include/ResultadoSentimiento.h> // preparacion #include <preparacion/include/ResultadoAnalisisMedio.h> #include <preparacion/include/ResultadoAnalisisContenido.h> #include <preparacion/include/ResultadoAnalisisDiario.h> using namespace scraping::preparacion; TEST_CASE("almacenar_y_recuperar_resultado_analisis_medio_correctamente", "preparacion[.]") { scraping::analisis::tecnicas::FuerzaEnNoticia fuerza_en_noticia; scraping::analisis::tecnicas::Sentimiento sentimiento; std::vector<std::string> bolsa_de_palabras_1 = { "jerusalen", "suenan", "sirenas", "alarma", "jerusalen", "sur", "israel", "disparo", "jerusalen", "cohete", "gaza", "israel" }; std::vector<std::string> bolsa_de_palabras_2 = { "jerusalen", "suenan", "sirenas", "alarma", "jerusalen", "sur", "israel", "disparo", "jerusalen", "cohete", "gaza", "israel", "holis", "chau" }; scraping::analisis::tecnicas::ResultadoFuerzaEnNoticia * resultado_1 = new scraping::analisis::tecnicas::ResultadoFuerzaEnNoticia(); fuerza_en_noticia.aplicar(bolsa_de_palabras_1, resultado_1); scraping::analisis::tecnicas::ResultadoSentimiento * resultado_1_sentimiento = new scraping::analisis::tecnicas::ResultadoSentimiento(); sentimiento.aplicar(bolsa_de_palabras_1, resultado_1_sentimiento); scraping::preparacion::ResultadoAnalisisMedio resultado_analisis_1(resultado_1); resultado_analisis_1.setResultadoSentimiento(resultado_1_sentimiento); resultado_analisis_1.setId(new herramientas::utiles::ID(1234)); scraping::IAdministradorScraping::getInstanciaAdminResultadosDiarios()->almacenar(&resultado_analisis_1); scraping::analisis::tecnicas::ResultadoFuerzaEnNoticia * resultado_2 = new scraping::analisis::tecnicas::ResultadoFuerzaEnNoticia(); fuerza_en_noticia.aplicar(bolsa_de_palabras_2, resultado_2); scraping::analisis::tecnicas::ResultadoSentimiento * resultado_2_sentimiento = new scraping::analisis::tecnicas::ResultadoSentimiento(); sentimiento.aplicar(bolsa_de_palabras_2, resultado_2_sentimiento); scraping::preparacion::ResultadoAnalisisMedio resultado_analisis_2(resultado_2); resultado_analisis_2.setResultadoSentimiento(resultado_2_sentimiento); resultado_analisis_2.setId(new herramientas::utiles::ID(4321)); scraping::IAdministradorScraping::getInstanciaAdminResultadosDiarios()->almacenar(&resultado_analisis_2); // recupero los resultados de medios almacenados y los combino. scraping::preparacion::ResultadoAnalisisMedio resultado_analisis_1_recuperado; resultado_analisis_1_recuperado.setId(resultado_analisis_1.getId()->copia()); scraping::IAdministradorScraping::getInstanciaAdminResultadosDiarios()->recuperar(&resultado_analisis_1_recuperado); scraping::preparacion::ResultadoAnalisisMedio resultado_analisis_2_recuperado; resultado_analisis_2_recuperado.setId(resultado_analisis_2.getId()->copia()); scraping::IAdministradorScraping::getInstanciaAdminResultadosDiarios()->recuperar(&resultado_analisis_2_recuperado); resultado_analisis_1_recuperado.combinarCon(&resultado_analisis_2_recuperado); scraping::analisis::tecnicas::ResultadoFuerzaEnNoticia * resultado_fuerza_en_noticia_combinado = resultado_analisis_1_recuperado.getResultadoFuerzaEnNoticia(); REQUIRE(std::round(100. * 11.4948416) == std::round(100. * resultado_fuerza_en_noticia_combinado->getFuerza("jerusalen"))); REQUIRE(std::round(100. * 7.66322803) == std::round(100. * resultado_fuerza_en_noticia_combinado->getFuerza("israel"))); REQUIRE(std::round(100. * 3.83161402) == std::round(100. * resultado_fuerza_en_noticia_combinado->getFuerza("gaza"))); REQUIRE(std::round(100. * 1.93951929) == std::round(100. * resultado_fuerza_en_noticia_combinado->getFuerza("holis"))); REQUIRE(std::round(100. * 1.93951929) == std::round(100. * resultado_fuerza_en_noticia_combinado->getFuerza("chau"))); } TEST_CASE("almacenar_y_recuperar_resultado_analisis_contenido_correctamente", "preparacion[.]") { scraping::analisis::tecnicas::FuerzaEnNoticia fuerza_en_noticia; std::vector<std::string> bolsa_de_palabras_1 = { "jerusalen", "suenan", "sirenas", "alarma", "jerusalen", "sur", "israel", "disparo", "jerusalen", "cohete", "gaza", "israel" }; std::vector<std::string> bolsa_de_palabras_2 = { "jerusalen", "suenan", "sirenas", "alarma", "jerusalen", "sur", "israel", "disparo", "jerusalen", "cohete", "gaza", "israel", "holis", "chau" }; scraping::analisis::tecnicas::ResultadoFuerzaEnNoticia * resultado_1 = new scraping::analisis::tecnicas::ResultadoFuerzaEnNoticia(); fuerza_en_noticia.aplicar(bolsa_de_palabras_1, resultado_1); scraping::preparacion::ResultadoAnalisisContenido resultado_analisis_1(resultado_1); resultado_analisis_1.setId(new herramientas::utiles::ID(1234)); scraping::IAdministradorScraping::getInstanciaAdminResultadosDiarios()->almacenar(&resultado_analisis_1); scraping::analisis::tecnicas::ResultadoFuerzaEnNoticia * resultado_2 = new scraping::analisis::tecnicas::ResultadoFuerzaEnNoticia(); fuerza_en_noticia.aplicar(bolsa_de_palabras_2, resultado_2); scraping::preparacion::ResultadoAnalisisContenido resultado_analisis_2(resultado_2); resultado_analisis_2.setId(new herramientas::utiles::ID(4321)); scraping::IAdministradorScraping::getInstanciaAdminResultadosDiarios()->almacenar(&resultado_analisis_2); // recupero los resultados de contenidos almacenados y los combino. scraping::preparacion::ResultadoAnalisisContenido resultado_analisis_1_recuperado; resultado_analisis_1_recuperado.setId(resultado_analisis_1.getId()->copia()); scraping::IAdministradorScraping::getInstanciaAdminResultadosDiarios()->recuperar(&resultado_analisis_1_recuperado); scraping::preparacion::ResultadoAnalisisContenido resultado_analisis_2_recuperado; resultado_analisis_2_recuperado.setId(resultado_analisis_2.getId()->copia()); scraping::IAdministradorScraping::getInstanciaAdminResultadosDiarios()->recuperar(&resultado_analisis_2_recuperado); resultado_analisis_1_recuperado.combinarCon(&resultado_analisis_2_recuperado); scraping::analisis::tecnicas::ResultadoFuerzaEnNoticia * resultado_fuerza_en_noticia_combinado = resultado_analisis_1_recuperado.getResultadoFuerzaEnNoticia(); REQUIRE(std::round(100. * 11.4948416) == std::round(100. * resultado_fuerza_en_noticia_combinado->getFuerza("jerusalen"))); REQUIRE(std::round(100. * 7.66322803) == std::round(100. * resultado_fuerza_en_noticia_combinado->getFuerza("israel"))); REQUIRE(std::round(100. * 3.83161402) == std::round(100. * resultado_fuerza_en_noticia_combinado->getFuerza("gaza"))); REQUIRE(std::round(100. * 1.93951929) == std::round(100. * resultado_fuerza_en_noticia_combinado->getFuerza("holis"))); REQUIRE(std::round(100. * 1.93951929) == std::round(100. * resultado_fuerza_en_noticia_combinado->getFuerza("chau"))); } TEST_CASE("almacenar_y_recuperar_resultado_analisis_diario_correctamente", "preparacion[.]") { scraping::analisis::tecnicas::FuerzaEnNoticia fuerza_en_noticia; std::vector<std::string> bolsa_de_palabras_1 = { "jerusalen", "suenan", "sirenas", "alarma", "jerusalen", "sur", "israel", "disparo", "jerusalen", "cohete", "gaza", "israel" }; std::vector<std::string> bolsa_de_palabras_2 = { "jerusalen", "suenan", "sirenas", "alarma", "jerusalen", "sur", "israel", "disparo", "jerusalen", "cohete", "gaza", "israel", "holis", "chau" }; scraping::preparacion::ResultadoAnalisisDiario resultado_diario; resultado_diario.setId(new herramientas::utiles::ID(1)); // medio 1 scraping::analisis::tecnicas::ResultadoFuerzaEnNoticia * resultado_1 = new scraping::analisis::tecnicas::ResultadoFuerzaEnNoticia(); fuerza_en_noticia.aplicar(bolsa_de_palabras_1, resultado_1); scraping::preparacion::ResultadoAnalisisMedio * resultado_analisis_1 = new scraping::preparacion::ResultadoAnalisisMedio(resultado_1); resultado_analisis_1->setId(new herramientas::utiles::ID(1234)); resultado_diario.agregarResultadoDeMedio(resultado_analisis_1); // medio 2 scraping::analisis::tecnicas::ResultadoFuerzaEnNoticia * resultado_2 = new scraping::analisis::tecnicas::ResultadoFuerzaEnNoticia(); fuerza_en_noticia.aplicar(bolsa_de_palabras_2, resultado_2); scraping::preparacion::ResultadoAnalisisMedio * resultado_analisis_2 = new scraping::preparacion::ResultadoAnalisisMedio(resultado_2); resultado_analisis_2->setId(new herramientas::utiles::ID(4321)); resultado_diario.agregarResultadoDeMedio(resultado_analisis_2); // almacena el resultado diario scraping::IAdministradorScraping::getInstanciaAdminResultadosDiarios()->almacenar(&resultado_diario); // lo recupero en otro resultado creado scraping::preparacion::ResultadoAnalisisDiario resultado_diario_recuperado; resultado_diario_recuperado.setId(resultado_diario.getId()->copia()); scraping::IAdministradorScraping::getInstanciaAdminResultadosDiarios()->recuperar(&resultado_diario_recuperado); scraping::preparacion::ResultadoAnalisisMedio * resultado_analisis_recuperado_1 = resultado_diario_recuperado.getResultadoMedio(resultado_analisis_1->getId()->numero()); scraping::preparacion::ResultadoAnalisisMedio * resultado_analisis_recuperado_2 = resultado_diario_recuperado.getResultadoMedio(resultado_analisis_2->getId()->numero()); resultado_analisis_recuperado_1->combinarCon(resultado_analisis_recuperado_2); scraping::analisis::tecnicas::ResultadoFuerzaEnNoticia * resultado_fuerza_en_noticia_combinado = resultado_analisis_recuperado_1->getResultadoFuerzaEnNoticia(); delete resultado_analisis_1; delete resultado_analisis_2; REQUIRE(std::round(100. * 11.4948416) == std::round(100. * resultado_fuerza_en_noticia_combinado->getFuerza("jerusalen"))); REQUIRE(std::round(100. * 7.66322803) == std::round(100. * resultado_fuerza_en_noticia_combinado->getFuerza("israel"))); REQUIRE(std::round(100. * 3.83161402) == std::round(100. * resultado_fuerza_en_noticia_combinado->getFuerza("gaza"))); REQUIRE(std::round(100. * 1.93951929) == std::round(100. * resultado_fuerza_en_noticia_combinado->getFuerza("holis"))); REQUIRE(std::round(100. * 1.93951929) == std::round(100. * resultado_fuerza_en_noticia_combinado->getFuerza("chau"))); }
61.346591
198
0.770029
miglesias91
3c0980f7da1a152303ec234ac70fba4b60892112
1,035
cpp
C++
Applied/CCore/src/ToMemBase.cpp
SergeyStrukov/CCore-2-xx
118aa4011ee7cc587298d6373b6587540e044a83
[ "BSL-1.0" ]
null
null
null
Applied/CCore/src/ToMemBase.cpp
SergeyStrukov/CCore-2-xx
118aa4011ee7cc587298d6373b6587540e044a83
[ "BSL-1.0" ]
null
null
null
Applied/CCore/src/ToMemBase.cpp
SergeyStrukov/CCore-2-xx
118aa4011ee7cc587298d6373b6587540e044a83
[ "BSL-1.0" ]
null
null
null
/* ToMemBase.cpp */ //---------------------------------------------------------------------------------------- // // Project: CCore 2.00 // // Tag: Applied Mini // // License: Boost Software License - Version 1.0 - August 17th, 2003 // // see http://www.boost.org/LICENSE_1_0.txt or the local copy // // Copyright (c) 2015 Sergey Strukov. All rights reserved. // //---------------------------------------------------------------------------------------- #include <CCore/inc/ToMemBase.h> #include <CCore/inc/MemBase.h> namespace CCore { /* class ToMemBase */ uint8 * ToMemBase::alloc(ulen len_) { ptr=static_cast<uint8 *>(MemAlloc(len_)); len=len_; return ptr; } ToMemBase::ToMemBase() { ptr=0; len=0; } ToMemBase::~ToMemBase() { MemFree(ptr); } ToMemBase & ToMemBase::operator = (ToMemBase &&obj) noexcept { if( this!=&obj ) { uint8 *todel=Replace(ptr,Replace_null(obj.ptr)); len=Replace_null(obj.len); MemFree(todel); } return *this; } } // namespace CCore
17.25
90
0.516908
SergeyStrukov
3c121eb334096ff2c91a202bd462c2666a5b976f
758
hpp
C++
code/modules/data/AddListItemModule.hpp
TU-Berlin-CVRS/uipf
57f4afcfdece904e82624453a938aafdfde8df41
[ "BSD-2-Clause" ]
8
2015-07-07T16:38:38.000Z
2020-11-26T13:52:18.000Z
code/modules/data/AddListItemModule.hpp
TU-Berlin-CVRS/uipf
57f4afcfdece904e82624453a938aafdfde8df41
[ "BSD-2-Clause" ]
129
2015-07-14T19:06:30.000Z
2019-05-29T20:40:00.000Z
code/modules/data/AddListItemModule.hpp
TU-Berlin-CVRS/uipf
57f4afcfdece904e82624453a938aafdfde8df41
[ "BSD-2-Clause" ]
6
2015-08-20T19:00:07.000Z
2020-11-26T13:52:19.000Z
#ifndef _ADDLISTITEMMODULE_ #define _ADDLISTITEMMODULE_ #include "../../framework/ModuleInterface.hpp" #include "../../framework/ModuleBase.hpp" namespace uipf{ // Create an empty list class AddListItemModule : public QObject, ModuleBase { Q_OBJECT Q_PLUGIN_METADATA(IID "org.tu-berlin.uipf.ModuleInterface" ) Q_INTERFACES(uipf::ModuleInterface) public: // constructor tells ModuleBase our name so we don't need to implement name() AddListItemModule(void): ModuleBase("addListItem"){}; // destructor needs to be virtual otherwise it not called due polymorphism virtual ~AddListItemModule(void){}; void run( DataManager& data ) const Q_DECL_OVERRIDE; uipf::MetaData getMetaData() const Q_DECL_OVERRIDE; }; } #endif //AddListItemModule
23.6875
79
0.766491
TU-Berlin-CVRS
3c1398ed48d4bdd319bbdb28b953104965bcf0ca
6,390
cpp
C++
update-client-hub/modules/lwm2m-mbed/source/lwm2m-monitor.cpp
marcuschangarm/mbed-cloud-client
d7edc529ed3722c811ff401440ef58ea980bf543
[ "Apache-2.0" ]
27
2018-04-04T12:06:23.000Z
2020-10-16T08:58:38.000Z
update-client-hub/modules/lwm2m-mbed/source/lwm2m-monitor.cpp
marcuschangarm/mbed-cloud-client
d7edc529ed3722c811ff401440ef58ea980bf543
[ "Apache-2.0" ]
41
2018-07-12T08:09:39.000Z
2020-11-06T13:47:43.000Z
update-client-hub/modules/lwm2m-mbed/source/lwm2m-monitor.cpp
marcuschangarm/mbed-cloud-client
d7edc529ed3722c811ff401440ef58ea980bf543
[ "Apache-2.0" ]
53
2018-04-16T08:36:25.000Z
2020-11-02T15:50:43.000Z
// ---------------------------------------------------------------------------- // Copyright 2016-2019 ARM Ltd. // // SPDX-License-Identifier: Apache-2.0 // // 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 "update-client-common/arm_uc_config.h" #if defined(ARM_UC_ENABLE) && (ARM_UC_ENABLE == 1) #include "update-lwm2m-mbed-apis.h" #include "update-client-lwm2m/lwm2m-monitor.h" #include "update-client-lwm2m/FirmwareUpdateResource.h" #include "update-client-lwm2m/DeviceMetadataResource.h" /** * @brief Get driver version. * @return Driver version. */ uint32_t ARM_UCS_LWM2M_MONITOR_GetVersion(void) { return 0; } /** * @brief Get Source capabilities. * @return Struct containing capabilites. See definition above. */ ARM_MONITOR_CAPABILITIES ARM_UCS_LWM2M_MONITOR_GetCapabilities(void) { ARM_MONITOR_CAPABILITIES result; result.state = 1; result.result = 1; result.version = 1; result.reserved = 30; return result; } /** * @brief Initialize Monitor. * @return Error code. */ arm_uc_error_t ARM_UCS_LWM2M_MONITOR_Initialize(void (*notification_handler)(void)) { ARM_UC_INIT_ERROR(retval, ERR_NONE); FirmwareUpdateResource::Initialize(); FirmwareUpdateResource::addNotificationCallback(notification_handler); DeviceMetadataResource::Initialize(); return retval; } /** * @brief Uninitialized Monitor. * @return Error code. */ arm_uc_error_t ARM_UCS_LWM2M_MONITOR_Uninitialize(void) { ARM_UC_INIT_ERROR(retval, ERR_NONE); return retval; } /** * @brief Send Update Client state. * @details From the OMA LWM2M Technical Specification: * * Indicates current state with respect to this firmware update. * This value is set by the LWM2M Client in accordance with state * and arm_uc_monitor_state_t type. * * @return Error code. */ arm_uc_error_t ARM_UCS_LWM2M_MONITOR_SendState(arm_uc_monitor_state_t an_update_state) { ARM_UC_INIT_ERROR(result, ERR_NONE); // If out of range of a legitimate update-state, return an "invalid-parameter" error to the caller, // otherwise try send the new state to the monitor. if (!ARM_UC_IsValidState(an_update_state)) { ARM_UC_SET_ERROR(result, ERR_INVALID_PARAMETER); } else { FirmwareUpdateResource::arm_ucs_lwm2m_state_t state = (FirmwareUpdateResource::arm_ucs_lwm2m_state_t)an_update_state; if (FirmwareUpdateResource::sendState(state) != 0) { ARM_UC_SET_ERROR(result, ERR_UNSPECIFIED); } } return result; } arm_uc_monitor_state_t ARM_UCS_LWM2M_MONITOR_GetState() { return (arm_uc_monitor_state_t)FirmwareUpdateResource::getState(); } /** * @brief Send update result. * @details From the OMA LWM2M Technical Specification: * Contains the result of downloading or updating the firmware * This Resource MAY be reported by sending Observe operation. * * @return Error code. */ arm_uc_error_t ARM_UCS_LWM2M_MONITOR_SendUpdateResult(arm_uc_monitor_result_t an_update_result) { ARM_UC_INIT_ERROR(result, ERR_NONE); // If out of range of a legitimate update-result, send an "unspecified-error" result. if (!ARM_UC_IsValidResult(an_update_result)) { ARM_UC_SET_ERROR(result, ERR_INVALID_PARAMETER); } else { // Cast the arm_uc_monitor_result_t to a arm_ucs_lwm2m_result_t, and send it. FirmwareUpdateResource::arm_ucs_lwm2m_result_t code = (FirmwareUpdateResource::arm_ucs_lwm2m_result_t)an_update_result; if (FirmwareUpdateResource::sendUpdateResult(code) != 0) { ARM_UC_SET_ERROR(result, ERR_UNSPECIFIED); } } return result; } /** * @brief Send current firmware name. * @details The firmware name is the SHA256 hash. * @param name Pointer to buffer struct. Hash is stored as byte array. * @return Error code. */ arm_uc_error_t ARM_UCS_LWM2M_MONITOR_SendName(arm_uc_buffer_t *name) { ARM_UC_INIT_ERROR(result, ERR_NONE); if (!name || !name->ptr) { ARM_UC_SET_ERROR(result, ERR_INVALID_PARAMETER); } else if (FirmwareUpdateResource::sendPkgName(name->ptr, name->size) != 0) { ARM_UC_SET_ERROR(result, ERR_UNSPECIFIED); } return result; } /** * @brief Send current firmware version. * @details The firmware version is the timestamp from the manifest that * authorized the firmware. * @param version Timestamp, 64 bit unsigned integer. * @return Error code. */ arm_uc_error_t ARM_UCS_LWM2M_MONITOR_SendVersion(uint64_t version) { ARM_UC_INIT_ERROR(result, ERR_NONE); if (FirmwareUpdateResource::sendPkgVersion(version) != 0) { ARM_UC_SET_ERROR(result, ERR_UNSPECIFIED); } return result; } /** * @brief Set the bootloader hash. * @details The bootloader hash is a hash of the bootloader. This is * used for tracking the version of the bootloader used. * @param name Pointer to buffer struct. Hash is stored as byte array. * @return Error code. */ arm_uc_error_t ARM_UCS_LWM2M_MONITOR_SetBootloaderHash(arm_uc_buffer_t *hash) { ARM_UC_INIT_ERROR(result, ERR_NONE); if (DeviceMetadataResource::setBootloaderHash(hash) != 0) { ARM_UC_SET_ERROR(result, ERR_UNSPECIFIED); } return result; } /** * @brief Set the OEM bootloader hash. * @details If the end-user has modified the bootloader the hash of the * modified bootloader can be set here. * @param name Pointer to buffer struct. Hash is stored as byte array. * @return Error code. */ arm_uc_error_t ARM_UCS_LWM2M_MONITOR_SetOEMBootloaderHash(arm_uc_buffer_t *hash) { ARM_UC_INIT_ERROR(result, ERR_NONE); if (DeviceMetadataResource::setOEMBootloaderHash(hash) != 0) { ARM_UC_SET_ERROR(result, ERR_UNSPECIFIED); } return result; } #endif
31.477833
103
0.707042
marcuschangarm
3c1c58b0c647d3925e2cb2cb3232b4a8e84ef37c
872
cpp
C++
Pearly/src/Pearly/Renderer/Texture.cpp
JumpyLionnn/Pearly
2dce5f54144980cecd998a325422e56bff6c4c83
[ "Apache-2.0" ]
null
null
null
Pearly/src/Pearly/Renderer/Texture.cpp
JumpyLionnn/Pearly
2dce5f54144980cecd998a325422e56bff6c4c83
[ "Apache-2.0" ]
null
null
null
Pearly/src/Pearly/Renderer/Texture.cpp
JumpyLionnn/Pearly
2dce5f54144980cecd998a325422e56bff6c4c83
[ "Apache-2.0" ]
null
null
null
#include "prpch.h" #include "Texture.h" #include "Renderer.h" #include "Platform/OpenGL/OpenGLTexture.h" namespace Pearly { Ref<Texture2D> Texture2D::Create(uint32 width, uint32 height) { switch (Renderer::GetAPI()) { case RendererAPI::API::None: PR_CORE_ASSERT(false, "Renderer API None is currently not supported!"); return nullptr; case RendererAPI::API::OpenGL: return CreateRef<OpenGLTexture2D>(width, height); } PR_CORE_ASSERT(false, "Unknown Renderer API!"); return nullptr; } Ref<Texture2D> Texture2D::Create(const std::string& path) { switch (Renderer::GetAPI()) { case RendererAPI::API::None: PR_CORE_ASSERT(false, "Renderer API None is currently not supported!"); return nullptr; case RendererAPI::API::OpenGL: return CreateRef<OpenGLTexture2D>(path); } PR_CORE_ASSERT(false, "Unknown Renderer API!"); return nullptr; } }
27.25
118
0.729358
JumpyLionnn
3c1c7c358e69b48e1cbcf46064731ce14d8014f6
688
cpp
C++
Aizu/CesarCipher.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
1
2018-08-28T19:58:40.000Z
2018-08-28T19:58:40.000Z
Aizu/CesarCipher.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
2
2017-04-16T00:48:05.000Z
2017-08-03T20:12:26.000Z
Aizu/CesarCipher.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
4
2016-03-04T19:42:00.000Z
2018-01-08T11:42:00.000Z
#include <string> #include <iostream> #include <algorithm> using namespace std; string decode(string s, int v) { string ans = s; for(int i = 0; i < (int) s.size(); i++) { if(s[i] >= 'a' && s[i] <= 'z') { ans[i] = (s[i] + v) % 26 + 'a'; } } return ans; } int main() { string s; while(getline(cin, s)) { for(int i = 0; 26; i++) { string tmp = decode(s, i); if(tmp.find("this") != string::npos || tmp.find("the") != string::npos || tmp.find("that") != string::npos) { cout << tmp << endl; break; } } } return 0; }
22.933333
122
0.412791
aajjbb
3c1f396558e74f120b6cc10dc576dad44e7bce4f
3,048
cpp
C++
src/rtsp/RtpSink.cpp
7956968/miniRtspServer
1de66d613941cd036d63ef32e7284ed68cb4b8a4
[ "MIT" ]
10
2020-07-28T01:14:49.000Z
2021-08-19T04:33:49.000Z
src/rtsp/RtpSink.cpp
TaoistLuo/miniRtspServer
1de66d613941cd036d63ef32e7284ed68cb4b8a4
[ "MIT" ]
null
null
null
src/rtsp/RtpSink.cpp
TaoistLuo/miniRtspServer
1de66d613941cd036d63ef32e7284ed68cb4b8a4
[ "MIT" ]
3
2020-09-15T11:14:55.000Z
2020-09-30T08:39:45.000Z
/************************************************************************* Copyright (c) 2020 Taoist Luo Create by: Taoist Luo CSDN:https://blog.csdn.net/daichanzhang9734/article/details/107549026 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 <arpa/inet.h> #include "RtpSink.h" #include "Mylog.h" RtpSink::RtpSink(Env* env,MediaSource* mediaSource, int payloadType) : mMediaSource(mediaSource), mSendPacketCallback(NULL), mCsrcLen(0), mExtension(0), mPadding(0), mVersion(RTP_VESION), mPayloadType(payloadType), mMarker(0), mSeq(0), mTimestamp(0), mEnv(env) { uint32_t frameTime = 1000/(mMediaSource->getFps()); mEnv->addTimer(timeoutCallback,frameTime,true,this); mSSRC = rand(); } RtpSink::~RtpSink() { delete mTimerEvent; } void RtpSink::setSendFrameCallback(SendPacketCallback cb, void* arg1, void* arg2) { mSendPacketCallback = cb; mArg1 = arg1; mArg2 = arg2; } void RtpSink::sendRtpPacket(RtpPacket* packet) { RtpHeader* rtpHead = packet->mRtpHeadr; rtpHead->csrcLen = mCsrcLen; rtpHead->extension = mExtension; rtpHead->padding = mPadding; rtpHead->version = mVersion; rtpHead->payloadType = mPayloadType; rtpHead->marker = mMarker; rtpHead->seq = htons(mSeq); rtpHead->timestamp = htonl(mTimestamp); rtpHead->ssrc = htonl(mSSRC); packet->mSize += RTP_HEADER_SIZE; if(mSendPacketCallback) mSendPacketCallback(mArg1, mArg2, packet); } void RtpSink::timeoutCallback(void* arg) { RtpSink* rtpSink = (RtpSink*)arg; AVFrame* frame = rtpSink->mMediaSource->getFrame(); if(!frame) { LOGI("get frame was NULL\n"); return; } rtpSink->handleFrame(frame); rtpSink->mMediaSource->putFrame(frame); } void RtpSink::start(int ms) { //mTimerEvent->setTimeout((uint32_t)ms); mTimerEvent->start(ms*1000,true); } void RtpSink::stop() { //mEnv->scheduler()->removeTimedEvent(mTimerId); }
29.882353
81
0.682415
7956968
3c1fa063e155984fd3faf5cd2db03ea607393732
22,608
cpp
C++
olp-cpp-sdk-core/tests/client/PendingUrlRequestsTest.cpp
OstapKL/here-data-sdk-cpp
0f7e9078fd1b273d868337d4f859512ffd1782fb
[ "Apache-2.0" ]
21
2019-07-03T07:26:52.000Z
2019-09-04T08:35:07.000Z
olp-cpp-sdk-core/tests/client/PendingUrlRequestsTest.cpp
OstapKL/here-data-sdk-cpp
0f7e9078fd1b273d868337d4f859512ffd1782fb
[ "Apache-2.0" ]
639
2019-09-13T17:14:24.000Z
2020-05-13T11:49:14.000Z
olp-cpp-sdk-core/tests/client/PendingUrlRequestsTest.cpp
OstapKL/here-data-sdk-cpp
0f7e9078fd1b273d868337d4f859512ffd1782fb
[ "Apache-2.0" ]
21
2020-05-14T15:32:28.000Z
2022-03-15T13:52:33.000Z
/* * Copyright (C) 2020 HERE Europe B.V. * * 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. * * SPDX-License-Identifier: Apache-2.0 * License-Filename: LICENSE */ #include <chrono> #include <future> #include <queue> #include <sstream> #include <string> #include <thread> #include <gmock/gmock.h> #include <gtest/gtest.h> #include <olp/core/client/ApiError.h> #include <olp/core/client/OlpClient.h> #include <olp/core/http/Network.h> #include <olp/core/logging/Log.h> #include "client/PendingUrlRequests.h" namespace { using olp::client::HttpResponse; using olp::http::ErrorCode; using ::testing::_; namespace client = olp::client; namespace http = olp::http; static const std::string kGoodResponse = "Response1234"; static const std::string kBadResponse = "Cancelled"; constexpr int kCancelledStatus = static_cast<int>(http::ErrorCode::CANCELLED_ERROR); constexpr http::RequestId kRequestId = 1234u; constexpr auto kSleepFor = std::chrono::seconds(1); constexpr auto kWaitFor = std::chrono::seconds(5); client::HttpResponse GetHttpResponse(ErrorCode error, std::string status) { return client::HttpResponse(static_cast<int>(error), status); } client::HttpResponse GetHttpResponse(int http_status, std::string status, http::Headers headers = {}) { std::stringstream stream; stream.str(std::move(status)); return client::HttpResponse(http_status, std::move(stream), std::move(headers)); } client::HttpResponse GetCancelledResponse() { return {kCancelledStatus, "Operation cancelled"}; } TEST(HttpResponseTest, Copy) { { SCOPED_TRACE("Error response"); auto response = GetHttpResponse(ErrorCode::CANCELLED_ERROR, kBadResponse); auto copy_response = response; std::string status; std::string copy_status; response.GetResponse(status); copy_response.GetResponse(copy_status); EXPECT_FALSE(status.empty()); EXPECT_FALSE(copy_status.empty()); EXPECT_TRUE(response.GetHeaders().empty()); EXPECT_TRUE(copy_response.GetHeaders().empty()); EXPECT_EQ(kBadResponse, status); EXPECT_EQ(response.GetStatus(), static_cast<int>(ErrorCode::CANCELLED_ERROR)); EXPECT_EQ(copy_response.GetStatus(), response.GetStatus()); EXPECT_EQ(status, copy_status); } { SCOPED_TRACE("Valid response"); http::Headers headers = {{"header1", "value1"}, {"header2", "value2"}}; auto response = GetHttpResponse(http::HttpStatusCode::OK, kGoodResponse, headers); auto copy_response = response; std::string status; std::string copy_status; response.GetResponse(status); copy_response.GetResponse(copy_status); EXPECT_FALSE(status.empty()); EXPECT_FALSE(copy_status.empty()); EXPECT_EQ(response.GetHeaders(), headers); EXPECT_EQ(copy_response.GetHeaders(), headers); EXPECT_EQ(kGoodResponse, status); EXPECT_EQ(response.GetStatus(), http::HttpStatusCode::OK); EXPECT_EQ(copy_response.GetStatus(), response.GetStatus()); EXPECT_EQ(status, copy_status); } } TEST(HttpResponseTest, Move) { { SCOPED_TRACE("Error response"); auto response = GetHttpResponse(ErrorCode::CANCELLED_ERROR, kBadResponse); auto copy_response = std::move(response); std::string status; std::string copy_status; response.GetResponse(status); copy_response.GetResponse(copy_status); EXPECT_TRUE(status.empty()); EXPECT_FALSE(copy_status.empty()); EXPECT_TRUE(response.GetHeaders().empty()); EXPECT_TRUE(copy_response.GetHeaders().empty()); EXPECT_EQ(kBadResponse, copy_status); EXPECT_EQ(copy_response.GetStatus(), static_cast<int>(ErrorCode::CANCELLED_ERROR)); } { SCOPED_TRACE("Valid response"); http::Headers headers = {{"header1", "value1"}, {"header2", "value2"}}; auto response = GetHttpResponse(http::HttpStatusCode::OK, kGoodResponse, headers); auto copy_response = std::move(response); std::string status; std::string copy_status; response.GetResponse(status); copy_response.GetResponse(copy_status); EXPECT_TRUE(status.empty()); EXPECT_FALSE(copy_status.empty()); EXPECT_TRUE(response.GetHeaders().empty()); EXPECT_EQ(copy_response.GetHeaders(), headers); EXPECT_EQ(kGoodResponse, copy_status); EXPECT_EQ(copy_response.GetStatus(), http::HttpStatusCode::OK); } } void CheckHttResponse(client::HttpResponse& in, int status, const std::string& response, const http::Headers& headers) { std::string response_in; in.GetResponse(response_in); EXPECT_EQ(response_in, response); EXPECT_EQ(in.GetHeaders(), headers); EXPECT_EQ(in.GetStatus(), status); } TEST(PendingUrlRequestsTest, IsCancelled) { client::PendingUrlRequests pending_requests; const std::string url1 = "url1"; const std::string url2 = "url2"; auto check_cancelled = [&](client::HttpResponse response) { ASSERT_EQ(response.GetStatus(), kCancelledStatus); }; auto check_not_cancelled = [&](client::HttpResponse response) { ASSERT_NE(response.GetStatus(), kCancelledStatus); }; auto complete_call = [&](http::RequestId request_id, const std::string& url) { std::this_thread::sleep_for(kSleepFor); pending_requests.OnRequestCompleted( request_id, url, GetHttpResponse(http::HttpStatusCode::OK, kGoodResponse, {{"header1", "value1"}, {"header2", "value2"}})); }; { SCOPED_TRACE("Cancel one request"); auto request_valid = pending_requests[url1]; auto request_cancelled = pending_requests[url2]; ASSERT_TRUE(request_valid && request_cancelled); request_valid->Append(check_not_cancelled); auto request_id = request_cancelled->Append(check_cancelled); ASSERT_FALSE(request_valid->IsCancelled()); ASSERT_FALSE(request_cancelled->IsCancelled()); std::future<void> future1, future2; request_valid->ExecuteOrCancelled([&](http::RequestId& id) { id = kRequestId; future1 = std::async(std::launch::async, complete_call, id, url1); return client::CancellationToken([] { // Should not be called EXPECT_TRUE(false) << "Cancellation called on not cancelled request"; }); }); request_cancelled->ExecuteOrCancelled([&](http::RequestId& id) { id = kRequestId + 1; return client::CancellationToken([&] { future2 = std::async(std::launch::async, complete_call, id, url2); }); }); EXPECT_TRUE(pending_requests.Cancel(url2, request_id)); EXPECT_FALSE(request_valid->IsCancelled()); EXPECT_TRUE(request_cancelled->IsCancelled()); ASSERT_EQ(future1.wait_for(kWaitFor), std::future_status::ready); ASSERT_EQ(future2.wait_for(kWaitFor), std::future_status::ready); // Cancell all and wait to leave a clean state for the next scope ASSERT_TRUE(pending_requests.CancelAllAndWait()); } { SCOPED_TRACE("Cancel all requests"); auto request1 = pending_requests[url1]; auto request2 = pending_requests[url2]; ASSERT_TRUE(request1 && request2); request1->Append(check_cancelled); request2->Append(check_cancelled); ASSERT_FALSE(request1->IsCancelled()); ASSERT_FALSE(request2->IsCancelled()); std::future<void> future1, future2; request1->ExecuteOrCancelled([&](http::RequestId& id) { id = kRequestId; return client::CancellationToken([&] { future1 = std::async(std::launch::async, complete_call, id, url1); }); }); request2->ExecuteOrCancelled([&](http::RequestId& id) { id = kRequestId + 1; return client::CancellationToken([&] { future2 = std::async(std::launch::async, complete_call, id, url2); }); }); EXPECT_TRUE(pending_requests.CancelAll()); EXPECT_TRUE(request1->IsCancelled()); EXPECT_TRUE(request2->IsCancelled()); ASSERT_EQ(future1.wait_for(kWaitFor), std::future_status::ready); ASSERT_EQ(future2.wait_for(kWaitFor), std::future_status::ready); } } TEST(PendingUrlRequestsTest, CancelAllAndWait) { client::PendingUrlRequests pending_requests; const std::string url1 = "url1"; const std::string url2 = "url2"; auto request1 = pending_requests[url1]; auto request2 = pending_requests[url2]; ASSERT_TRUE(request1 && request2); auto check_cancelled = [&](client::HttpResponse response) { ASSERT_EQ(response.GetStatus(), kCancelledStatus); }; request1->Append(check_cancelled); request2->Append(check_cancelled); auto cancel_call = [&](http::RequestId request_id, const std::string& url) { std::this_thread::sleep_for(std::chrono::seconds(1)); pending_requests.OnRequestCompleted(request_id, url, GetCancelledResponse()); }; const http::RequestId request_id = 1234; std::future<void> future1, future2; request1->ExecuteOrCancelled([&](http::RequestId& id) { id = request_id; return client::CancellationToken([&] { future1 = std::async(std::launch::async, cancel_call, id, url1); }); }); request2->ExecuteOrCancelled([&](http::RequestId& id) { id = request_id + 1; return client::CancellationToken([&] { future2 = std::async(std::launch::async, cancel_call, id, url2); }); }); // Once CancelAllAndWait is called, it should wait for all responses else we // face crashes ASSERT_TRUE(pending_requests.CancelAllAndWait()); ASSERT_EQ(future1.wait_for(std::chrono::milliseconds(1)), std::future_status::ready); ASSERT_EQ(future2.wait_for(std::chrono::milliseconds(1)), std::future_status::ready); } TEST(PendingUrlRequestsTest, ExecuteOrCancelled) { client::PendingUrlRequests pending_requests; const std::string url = "url"; auto check_cancelled = [&](client::HttpResponse response) { ASSERT_EQ(response.GetStatus(), kCancelledStatus); }; // Check that ExecuteOrCancelled is behaving correctly auto request_ptr = pending_requests[url]; ASSERT_TRUE(request_ptr); ASSERT_FALSE(request_ptr->IsCancelled()); ASSERT_EQ(request_ptr.use_count(), 2); request_ptr->Append(check_cancelled); bool is_cancelled = false; bool cancel_func_called = false; std::future<void> future; // Set request Id request_ptr->ExecuteOrCancelled( [&](http::RequestId& id) { return client::CancellationToken([&] { is_cancelled = true; id = kRequestId; future = std::async( std::launch::async, [&](http::RequestId request_id, const std::string& url) { std::this_thread::sleep_for(kSleepFor); pending_requests.OnRequestCompleted( request_id, url, GetHttpResponse( http::HttpStatusCode::OK, kGoodResponse, {{"header1", "value1"}, {"header2", "value2"}})); }, id, url); }); }, [] { EXPECT_TRUE(false) << "Cancel function should not be called!"; }); // Now cancel request and call again request_ptr->CancelOperation(); request_ptr->ExecuteOrCancelled( [](http::RequestId&) { EXPECT_TRUE(false) << "Execute function should not be called!"; return client::CancellationToken(); }, [&] { cancel_func_called = true; }); EXPECT_TRUE(is_cancelled); EXPECT_TRUE(cancel_func_called); ASSERT_EQ(future.wait_for(kWaitFor), std::future_status::ready); } TEST(PendingUrlRequestsTest, SameUrlAfterCancel) { // This test covers the use-case were you have a cancelled request which is in // the process of waiting for the network cancel answer and afterwards a new // request with the same URL. In this case both should exist at the same time, // one in the pending request list the other in the cancelled list. client::PendingUrlRequests pending_requests; const std::string url = "url1"; std::future<void> future_cancelled, future_valid; auto check_cancelled = [&](client::HttpResponse response) { ASSERT_EQ(response.GetStatus(), kCancelledStatus); }; auto check_not_cancelled = [&](client::HttpResponse response) { ASSERT_NE(response.GetStatus(), kCancelledStatus); }; // Add request to be cancelled auto request_ptr = pending_requests[url]; ASSERT_TRUE(request_ptr); ASSERT_FALSE(request_ptr->IsCancelled()); ASSERT_EQ(request_ptr.use_count(), 2); auto cancel_id = request_ptr->Append(check_cancelled); request_ptr->ExecuteOrCancelled([&](http::RequestId& id) { id = kRequestId; return client::CancellationToken([&] { future_cancelled = std::async(std::launch::async, [&](http::RequestId request_id, const std::string& url) { std::this_thread::sleep_for(kSleepFor); pending_requests.OnRequestCompleted( request_id, url, GetHttpResponse( http::HttpStatusCode::OK, kGoodResponse, {{"header1", "value1"}, {"header2", "value2"}})); }, id, url); }); }); // Now cancel the request EXPECT_TRUE(pending_requests.Cancel(url, cancel_id)); ASSERT_TRUE(request_ptr->IsCancelled()); // Add second request with the same url auto new_request_ptr = pending_requests[url]; ASSERT_TRUE(new_request_ptr); ASSERT_FALSE(new_request_ptr->IsCancelled()); ASSERT_EQ(new_request_ptr.use_count(), 2); ASSERT_FALSE(new_request_ptr == request_ptr); new_request_ptr->Append(check_not_cancelled); new_request_ptr->ExecuteOrCancelled([&](http::RequestId& id) { id = kRequestId + 1; future_valid = std::async( std::launch::async, [&](http::RequestId request_id, const std::string& url) { std::this_thread::sleep_for(kSleepFor); pending_requests.OnRequestCompleted( request_id, url, GetHttpResponse(http::HttpStatusCode::OK, kGoodResponse, {{"header1", "value1"}, {"header2", "value2"}})); }, id, url); return client::CancellationToken(); }); ASSERT_EQ(future_cancelled.wait_for(kWaitFor), std::future_status::ready); ASSERT_EQ(future_valid.wait_for(kWaitFor), std::future_status::ready); } TEST(PendingUrlRequestsTest, CallbackCalled) { client::PendingUrlRequests pending_requests; const std::string url = "url1"; { SCOPED_TRACE("Single callback"); auto request_ptr = pending_requests[url]; ASSERT_TRUE(request_ptr); ASSERT_FALSE(request_ptr->IsCancelled()); ASSERT_EQ(request_ptr.use_count(), 2); // Add one callback and check that it is triggered client::HttpResponse response_out; EXPECT_EQ(0u, request_ptr->Append([&](client::HttpResponse response) { response_out = std::move(response); })); // Set request Id const http::RequestId request_id = 1234; request_ptr->ExecuteOrCancelled( [&](http::RequestId& id) { id = request_id; return client::CancellationToken(); }, [] { EXPECT_TRUE(false) << "Cancel function should not be called!"; }); // Relese the pending request from local var to make sure we don't have // any issues there. request_ptr.reset(); // Now mark the request as completed and expect the callback to be called http::Headers headers = {{"header1", "value1"}, {"header2", "value2"}}; const auto response_in = GetHttpResponse(http::HttpStatusCode::OK, kGoodResponse, headers); pending_requests.OnRequestCompleted(request_id, url, response_in); EXPECT_NO_FATAL_FAILURE(CheckHttResponse( response_out, response_in.GetStatus(), kGoodResponse, headers)); ASSERT_EQ(pending_requests.Size(), 0u) << "Pending requests should be empty"; } { SCOPED_TRACE("Multiple callbacks"); auto request_ptr = pending_requests[url]; ASSERT_TRUE(request_ptr); ASSERT_FALSE(request_ptr->IsCancelled()); ASSERT_EQ(request_ptr.use_count(), 2); // Add one callback and check that it is triggered client::HttpResponse response_out_1, response_out_2; EXPECT_EQ(0u, request_ptr->Append([&](client::HttpResponse response) { response_out_1 = std::move(response); })); EXPECT_EQ(1u, request_ptr->Append([&](client::HttpResponse response) { response_out_2 = std::move(response); })); // Set request Id const http::RequestId request_id = 1234; request_ptr->ExecuteOrCancelled( [&](http::RequestId& id) { id = request_id; return client::CancellationToken(); }, [] { EXPECT_TRUE(false) << "Cancel function should not be called!"; }); // Relese the pending request from local var to make sure we don't have // any issues there. request_ptr.reset(); // Now mark the request as completed and expect the callback to be called http::Headers headers = {{"header1", "value1"}, {"header2", "value2"}}; pending_requests.OnRequestCompleted( request_id, url, GetHttpResponse(http::HttpStatusCode::OK, kGoodResponse, headers)); EXPECT_NO_FATAL_FAILURE(CheckHttResponse( response_out_1, http::HttpStatusCode::OK, kGoodResponse, headers)); EXPECT_NO_FATAL_FAILURE(CheckHttResponse( response_out_2, http::HttpStatusCode::OK, kGoodResponse, headers)); ASSERT_EQ(pending_requests.Size(), 0u) << "Pending requests should be empty"; } { SCOPED_TRACE("Multiple callbacks, one cancelled"); auto request_ptr = pending_requests[url]; ASSERT_TRUE(request_ptr); ASSERT_FALSE(request_ptr->IsCancelled()); ASSERT_EQ(request_ptr.use_count(), 2); client::HttpResponse response_good, response_cancelled; EXPECT_EQ(0u, request_ptr->Append([&](client::HttpResponse response) { response_good = std::move(response); })); auto callback_id = request_ptr->Append([&](client::HttpResponse response) { response_cancelled = std::move(response); }); EXPECT_EQ(callback_id, 1u); // Set request Id const http::RequestId request_id = 1234; request_ptr->ExecuteOrCancelled( [&](http::RequestId& id) { id = request_id; return client::CancellationToken(); }, [] { EXPECT_TRUE(false) << "Cancel function should not be called!"; }); // Cancel second request and check that request is not cancelled fully pending_requests.Cancel(url, callback_id); ASSERT_FALSE(request_ptr->IsCancelled()); http::Headers headers = {{"header1", "value1"}, {"header2", "value2"}}; pending_requests.OnRequestCompleted( request_id, url, GetHttpResponse(http::HttpStatusCode::OK, kGoodResponse, headers)); EXPECT_NO_FATAL_FAILURE(CheckHttResponse( response_good, http::HttpStatusCode::OK, kGoodResponse, headers)); std::string cancelled_response; auto cancelled_expected = GetCancelledResponse(); cancelled_expected.GetResponse(cancelled_response); EXPECT_NO_FATAL_FAILURE(CheckHttResponse(response_cancelled, cancelled_expected.GetStatus(), cancelled_response, {})); } } TEST(PendingUrlRequestsTest, CancelCallback) { client::PendingUrlRequests pending_requests; const std::string url1 = "url1", url2 = "url2", url3 = "url3"; http::RequestId request_id = 1234; auto response_call = [&](http::RequestId request_id, const std::string& url) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); pending_requests.OnRequestCompleted( request_id, url, GetHttpResponse(http::HttpStatusCode::OK, kGoodResponse)); }; { SCOPED_TRACE("Single callback cancelled"); auto request_ptr = pending_requests[url1]; ASSERT_TRUE(request_ptr); // Add one callback and check that it is triggered and it is cancelled auto callback_id = request_ptr->Append([&](client::HttpResponse response) { ASSERT_EQ(response.GetStatus(), kCancelledStatus); }); request_ptr->ExecuteOrCancelled([&](http::RequestId& id) { id = ++request_id; return client::CancellationToken(); }); EXPECT_TRUE(pending_requests.Cancel(url1, callback_id)); // Trigger and wait for response std::async(std::launch::async, response_call, request_id, url1).get(); } { SCOPED_TRACE("Multiple callbacks, one cancelled"); auto request_ptr = pending_requests[url1]; ASSERT_TRUE(request_ptr); // Add one callback and check that it is triggered and it is cancelled request_ptr->Append([&](client::HttpResponse response) { ASSERT_NE(response.GetStatus(), kCancelledStatus); }); request_ptr->ExecuteOrCancelled([&](http::RequestId& id) { id = ++request_id; return client::CancellationToken(); }); auto callback_id = request_ptr->Append([&](client::HttpResponse response) { ASSERT_EQ(response.GetStatus(), kCancelledStatus); }); EXPECT_TRUE(pending_requests.Cancel(url1, callback_id)); // Trigger and wait for response std::async(std::launch::async, response_call, request_id, url1).get(); } { SCOPED_TRACE("Multiple callbacks, unknown cancelled"); auto request_ptr = pending_requests[url1]; ASSERT_TRUE(request_ptr); // Add one callback and check that it is triggered and it is cancelled request_ptr->Append([&](client::HttpResponse response) { ASSERT_NE(response.GetStatus(), kCancelledStatus); }); auto callback_id = request_ptr->Append([&](client::HttpResponse response) { ASSERT_NE(response.GetStatus(), kCancelledStatus); }); request_ptr->ExecuteOrCancelled([&](http::RequestId& id) { id = ++request_id; return client::CancellationToken(); }); EXPECT_FALSE(pending_requests.Cancel(url1, callback_id + 15)); // Trigger and wait for response std::async(std::launch::async, response_call, request_id, url1).get(); } } } // namespace
33.394387
80
0.675159
OstapKL
3c212a755a5bb5e9b921802faf3207fc8dd6b63f
2,448
cpp
C++
android-31/android/inputmethodservice/AbstractInputMethodService.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/android/inputmethodservice/AbstractInputMethodService.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-31/android/inputmethodservice/AbstractInputMethodService.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "../../JArray.hpp" #include "../content/Intent.hpp" #include "./AbstractInputMethodService_AbstractInputMethodImpl.hpp" #include "./AbstractInputMethodService_AbstractInputMethodSessionImpl.hpp" #include "../view/KeyEvent_DispatcherState.hpp" #include "../view/MotionEvent.hpp" #include "../../java/io/FileDescriptor.hpp" #include "../../java/io/PrintWriter.hpp" #include "./AbstractInputMethodService.hpp" namespace android::inputmethodservice { // Fields // QJniObject forward AbstractInputMethodService::AbstractInputMethodService(QJniObject obj) : android::app::Service(obj) {} // Constructors AbstractInputMethodService::AbstractInputMethodService() : android::app::Service( "android.inputmethodservice.AbstractInputMethodService", "()V" ) {} // Methods android::view::KeyEvent_DispatcherState AbstractInputMethodService::getKeyDispatcherState() const { return callObjectMethod( "getKeyDispatcherState", "()Landroid/view/KeyEvent$DispatcherState;" ); } jboolean AbstractInputMethodService::isUiContext() const { return callMethod<jboolean>( "isUiContext", "()Z" ); } JObject AbstractInputMethodService::onBind(android::content::Intent arg0) const { return callObjectMethod( "onBind", "(Landroid/content/Intent;)Landroid/os/IBinder;", arg0.object() ); } android::inputmethodservice::AbstractInputMethodService_AbstractInputMethodImpl AbstractInputMethodService::onCreateInputMethodInterface() const { return callObjectMethod( "onCreateInputMethodInterface", "()Landroid/inputmethodservice/AbstractInputMethodService$AbstractInputMethodImpl;" ); } android::inputmethodservice::AbstractInputMethodService_AbstractInputMethodSessionImpl AbstractInputMethodService::onCreateInputMethodSessionInterface() const { return callObjectMethod( "onCreateInputMethodSessionInterface", "()Landroid/inputmethodservice/AbstractInputMethodService$AbstractInputMethodSessionImpl;" ); } jboolean AbstractInputMethodService::onGenericMotionEvent(android::view::MotionEvent arg0) const { return callMethod<jboolean>( "onGenericMotionEvent", "(Landroid/view/MotionEvent;)Z", arg0.object() ); } jboolean AbstractInputMethodService::onTrackballEvent(android::view::MotionEvent arg0) const { return callMethod<jboolean>( "onTrackballEvent", "(Landroid/view/MotionEvent;)Z", arg0.object() ); } } // namespace android::inputmethodservice
30.6
159
0.774918
YJBeetle
3c21ffb618f6158cc3d225adc5e6ead2a878075f
396
cpp
C++
ds3runtime/scripts/sync_call_script.cpp
tremwil/DS3RuntimeScripting
50508bbf9295f87c459722ea3bea015c85a36de5
[ "MIT" ]
8
2021-06-05T21:59:53.000Z
2022-02-03T10:00:09.000Z
ds3runtime/scripts/sync_call_script.cpp
tremwil/DS3RuntimeScripting
50508bbf9295f87c459722ea3bea015c85a36de5
[ "MIT" ]
null
null
null
ds3runtime/scripts/sync_call_script.cpp
tremwil/DS3RuntimeScripting
50508bbf9295f87c459722ea3bea015c85a36de5
[ "MIT" ]
5
2021-05-17T19:49:29.000Z
2022-02-26T11:00:29.000Z
/* * DS3RuntimeScripting * Contributers: Amir */ #pragma once #include "pch.h" #include "sync_call_script.h" #include "ds3runtime/ds3runtime.h" namespace ds3runtime { void SyncCallScript::execute() { for (auto bulletSpawn : syncBullets) bulletSpawn.launch(); syncBullets.clear(); } void SyncCallScript::launchBulletSync(BulletSpawn bulletSpawn) { syncBullets.push_back(bulletSpawn); } }
17.217391
64
0.760101
tremwil
3c228ea65f934c84c768568390d6b2a66ab56a81
1,250
cpp
C++
LeetCode/SwapNodesInPairs.cpp
Michael-Ma/Coding-Practice
6ab3d76ae1cd3a97046b399c59d6bf2b135d7b5f
[ "MIT" ]
null
null
null
LeetCode/SwapNodesInPairs.cpp
Michael-Ma/Coding-Practice
6ab3d76ae1cd3a97046b399c59d6bf2b135d7b5f
[ "MIT" ]
null
null
null
LeetCode/SwapNodesInPairs.cpp
Michael-Ma/Coding-Practice
6ab3d76ae1cd3a97046b399c59d6bf2b135d7b5f
[ "MIT" ]
null
null
null
#include <sstream> #include <stdio.h> #include <string> #include <cstring> #include <iostream> #include <vector> #include <map> #include <stack> #include <queue> #include <set> #include <cmath> #include <algorithm> #include <cfloat> #include <climits> //#include <unordered_set> //#include <unordered_map> using namespace std; // Definition for singly-linked list. struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; /* Time Complexity : O(n) Space Complexity : O(1) Trick: Special Cases : Summary: using dummy head is pretty neat! */ class Solution { public: ListNode* swapPairs(ListNode* head) { if(head==NULL || head->next==NULL){ return head; } ListNode* dummyHead = new ListNode(0); dummyHead->next = head; ListNode* cur = head->next; ListNode* pre = dummyHead; while(cur != NULL){ pre->next->next = cur->next; cur->next = pre->next; pre->next = cur; cur = cur->next->next; if(cur!=NULL){ cur = cur->next; pre = pre->next->next; } } return dummyHead->next; } };
21.186441
46
0.5528
Michael-Ma
3c2343c690bdbd2d26b2f2643ed7bff7572a6670
11,419
cpp
C++
src/task_jump_2.cpp
RPGP1/task-draft
5459ea24b717c690d00909b77a76f599828f3566
[ "Unlicense" ]
null
null
null
src/task_jump_2.cpp
RPGP1/task-draft
5459ea24b717c690d00909b77a76f599828f3566
[ "Unlicense" ]
null
null
null
src/task_jump_2.cpp
RPGP1/task-draft
5459ea24b717c690d00909b77a76f599828f3566
[ "Unlicense" ]
null
null
null
#include "task_jump.hpp" namespace TaskManager { namespace Expr { Jump::JumpManager::JumpManagerOperator::JumpManagerOperator(const std::shared_ptr<JumpManager>& _jump_manager, const std::shared_ptr<TaskSet>& _taskset) noexcept : JumpIf{_jump_manager, _taskset}, JumpBackIf{_jump_manager, _taskset} { } Jump::JumpManager::JumpManagerOperator::JumpManagerOperator(std::shared_ptr<JumpManager>&& _jump_manager, std::shared_ptr<TaskSet>&& _taskset) noexcept : JumpIf{_jump_manager, _taskset}, JumpBackIf{std::move(_jump_manager), std::move(_taskset)} { } Jump::JumpManager::JumpManagerOperator::JumpIfCondition::JumpIfCondition(const std::shared_ptr<JumpManager>& _jump_manager, int _priority, const std::function<bool()>& _func, const std::shared_ptr<TaskSet>& _taskset) noexcept : m_jump_manager{_jump_manager}, m_priority{_priority}, m_func{_func}, m_taskset{_taskset} { } Jump::JumpManager::JumpManagerOperator::JumpIfCondition::JumpIfCondition(const std::shared_ptr<JumpManager>& _jump_manager, int _priority, std::function<bool()>&& _func, const std::shared_ptr<TaskSet>& _taskset) noexcept : m_jump_manager{_jump_manager}, m_priority{_priority}, m_func{std::move(_func)}, m_taskset{_taskset} { } Jump::JumpManager::JumpManagerOperator::JumpIfCondition::JumpIfCondition(std::shared_ptr<JumpManager>&& _jump_manager, int _priority, const std::function<bool()>& _func, std::shared_ptr<TaskSet>&& _taskset) noexcept : m_jump_manager{std::move(_jump_manager)}, m_priority{_priority}, m_func{_func}, m_taskset{std::move(_taskset)} { } Jump::JumpManager::JumpManagerOperator::JumpIfCondition::JumpIfCondition(std::shared_ptr<JumpManager>&& _jump_manager, int _priority, std::function<bool()>&& _func, std::shared_ptr<TaskSet>&& _taskset) noexcept : m_jump_manager{_jump_manager}, m_priority{_priority}, m_func{std::move(_func)}, m_taskset{std::move(_taskset)} { } Jump Jump::JumpManager::JumpManagerOperator::JumpIfCondition::operator()(std::nullptr_t) const& noexcept { if (m_jump_manager) { if (auto& jump_list = m_jump_manager->m_jump_list) { (*jump_list)[m_priority].emplace_back(m_func, JumpType::OneWay, nullptr); } } return {m_taskset, m_jump_manager}; } Jump Jump::JumpManager::JumpManagerOperator::JumpIfCondition::operator()(std::nullptr_t) && noexcept { if (m_jump_manager) { if (auto& jump_list = m_jump_manager->m_jump_list) { (*jump_list)[m_priority].emplace_back(std::move(m_func), JumpType::OneWay, nullptr); } } return {std::move(m_taskset), std::move(m_jump_manager)}; } Jump::JumpManager::JumpManagerOperator::JumpIfClass::JumpIfClass(const std::shared_ptr<JumpManager>& _jump_manager, const std::shared_ptr<TaskSet>& _taskset) noexcept : m_jump_manager{_jump_manager}, m_taskset{_taskset} { } Jump::JumpManager::JumpManagerOperator::JumpIfClass Jump::JumpManager::JumpManagerOperator::JumpIfClass::operator[](int _priority) const& noexcept { JumpIfClass tmp{*this}; tmp.m_priority = _priority; return tmp; } Jump::JumpManager::JumpManagerOperator::JumpIfClass Jump::JumpManager::JumpManagerOperator::JumpIfClass::operator[](int _priority) && noexcept { JumpIfClass tmp{std::move(*this)}; tmp.m_priority = _priority; return tmp; } Jump::JumpManager::JumpManagerOperator::JumpIfCondition Jump::JumpManager::JumpManagerOperator::JumpIfClass::operator[](const std::function<bool()>& _func) const& noexcept { return {m_jump_manager, m_priority, _func, m_taskset}; } Jump::JumpManager::JumpManagerOperator::JumpIfCondition Jump::JumpManager::JumpManagerOperator::JumpIfClass::operator[](std::function<bool()>&& _func) const& noexcept { return {m_jump_manager, m_priority, std::move(_func), m_taskset}; } Jump::JumpManager::JumpManagerOperator::JumpIfCondition Jump::JumpManager::JumpManagerOperator::JumpIfClass::operator()(const std::function<bool()>& _func) const& noexcept { return {m_jump_manager, m_priority, _func, m_taskset}; } Jump::JumpManager::JumpManagerOperator::JumpIfCondition Jump::JumpManager::JumpManagerOperator::JumpIfClass::operator()(std::function<bool()>&& _func) const& noexcept { return {m_jump_manager, m_priority, std::move(_func), m_taskset}; } Jump::JumpManager::JumpManagerOperator::JumpIfCondition Jump::JumpManager::JumpManagerOperator::JumpIfClass::operator[](const std::function<bool()>& _func) && noexcept { return {std::move(m_jump_manager), m_priority, _func, std::move(m_taskset)}; } Jump::JumpManager::JumpManagerOperator::JumpIfCondition Jump::JumpManager::JumpManagerOperator::JumpIfClass::operator[](std::function<bool()>&& _func) && noexcept { return {std::move(m_jump_manager), m_priority, std::move(_func), std::move(m_taskset)}; } Jump::JumpManager::JumpManagerOperator::JumpIfCondition Jump::JumpManager::JumpManagerOperator::JumpIfClass::operator()(const std::function<bool()>& _func) && noexcept { return {std::move(m_jump_manager), m_priority, _func, std::move(m_taskset)}; } Jump::JumpManager::JumpManagerOperator::JumpIfCondition Jump::JumpManager::JumpManagerOperator::JumpIfClass::operator()(std::function<bool()>&& _func) && noexcept { return {std::move(m_jump_manager), m_priority, std::move(_func), std::move(m_taskset)}; } Jump::JumpManager::JumpManagerOperator::JumpBackIfCondition::JumpBackIfCondition(const std::shared_ptr<JumpManager>& _jump_manager, int _priority, const std::function<bool()>& _func, const std::shared_ptr<TaskSet>& _taskset) noexcept : m_jump_manager{_jump_manager}, m_priority{_priority}, m_func{_func}, m_taskset{_taskset} { } Jump::JumpManager::JumpManagerOperator::JumpBackIfCondition::JumpBackIfCondition(const std::shared_ptr<JumpManager>& _jump_manager, int _priority, std::function<bool()>&& _func, const std::shared_ptr<TaskSet>& _taskset) noexcept : m_jump_manager{_jump_manager}, m_priority{_priority}, m_func{std::move(_func)}, m_taskset{_taskset} { } Jump::JumpManager::JumpManagerOperator::JumpBackIfCondition::JumpBackIfCondition(std::shared_ptr<JumpManager>&& _jump_manager, int _priority, const std::function<bool()>& _func, std::shared_ptr<TaskSet>&& _taskset) noexcept : m_jump_manager{std::move(_jump_manager)}, m_priority{_priority}, m_func{_func}, m_taskset{std::move(_taskset)} { } Jump::JumpManager::JumpManagerOperator::JumpBackIfCondition::JumpBackIfCondition(std::shared_ptr<JumpManager>&& _jump_manager, int _priority, std::function<bool()>&& _func, std::shared_ptr<TaskSet>&& _taskset) noexcept : m_jump_manager{std::move(_jump_manager)}, m_priority{_priority}, m_func{std::move(_func)}, m_taskset{std::move(_taskset)} { } Jump Jump::JumpManager::JumpManagerOperator::JumpBackIfCondition::operator()(std::nullptr_t) const& noexcept { if (m_jump_manager) { if (auto& jump_list = m_jump_manager->m_jump_list) { (*jump_list)[m_priority].emplace_back(m_func, JumpType::ReturnBack, nullptr); } } return {m_taskset, m_jump_manager}; } Jump Jump::JumpManager::JumpManagerOperator::JumpBackIfCondition::operator()(std::nullptr_t) && noexcept { if (m_jump_manager) { if (auto& jump_list = m_jump_manager->m_jump_list) { (*jump_list)[m_priority].emplace_back(std::move(m_func), JumpType::ReturnBack, nullptr); } } return {std::move(m_taskset), std::move(m_jump_manager)}; } Jump::JumpManager::JumpManagerOperator::JumpBackIfClass::JumpBackIfClass(const std::shared_ptr<JumpManager>& _jump_manager, const std::shared_ptr<TaskSet>& _taskset) noexcept : m_jump_manager{_jump_manager}, m_taskset{_taskset} { } Jump::JumpManager::JumpManagerOperator::JumpBackIfClass::JumpBackIfClass(std::shared_ptr<JumpManager>&& _jump_manager, std::shared_ptr<TaskSet>&& _taskset) noexcept : m_jump_manager{std::move(_jump_manager)}, m_taskset{std::move(_taskset)} { } Jump::JumpManager::JumpManagerOperator::JumpBackIfClass Jump::JumpManager::JumpManagerOperator::JumpBackIfClass::operator[](int _priority) const& noexcept { JumpBackIfClass tmp{*this}; tmp.m_priority = _priority; return tmp; } Jump::JumpManager::JumpManagerOperator::JumpBackIfClass Jump::JumpManager::JumpManagerOperator::JumpBackIfClass::operator[](int _priority) && noexcept { JumpBackIfClass tmp{std::move(*this)}; tmp.m_priority = _priority; return tmp; } Jump::JumpManager::JumpManagerOperator::JumpBackIfCondition Jump::JumpManager::JumpManagerOperator::JumpBackIfClass::operator[](const std::function<bool()>& _func) const& noexcept { return {m_jump_manager, m_priority, _func, m_taskset}; } Jump::JumpManager::JumpManagerOperator::JumpBackIfCondition Jump::JumpManager::JumpManagerOperator::JumpBackIfClass::operator[](std::function<bool()>&& _func) const& noexcept { return {m_jump_manager, m_priority, std::move(_func), m_taskset}; } Jump::JumpManager::JumpManagerOperator::JumpBackIfCondition Jump::JumpManager::JumpManagerOperator::JumpBackIfClass::operator()(const std::function<bool()>& _func) const& noexcept { return {m_jump_manager, m_priority, _func, m_taskset}; } Jump::JumpManager::JumpManagerOperator::JumpBackIfCondition Jump::JumpManager::JumpManagerOperator::JumpBackIfClass::operator()(std::function<bool()>&& _func) const& noexcept { return {m_jump_manager, m_priority, std::move(_func), m_taskset}; } Jump::JumpManager::JumpManagerOperator::JumpBackIfCondition Jump::JumpManager::JumpManagerOperator::JumpBackIfClass::operator[](const std::function<bool()>& _func) && noexcept { return {std::move(m_jump_manager), m_priority, _func, std::move(m_taskset)}; } Jump::JumpManager::JumpManagerOperator::JumpBackIfCondition Jump::JumpManager::JumpManagerOperator::JumpBackIfClass::operator[](std::function<bool()>&& _func) && noexcept { return {std::move(m_jump_manager), m_priority, std::move(_func), std::move(m_taskset)}; } Jump::JumpManager::JumpManagerOperator::JumpBackIfCondition Jump::JumpManager::JumpManagerOperator::JumpBackIfClass::operator()(const std::function<bool()>& _func) && noexcept { return {std::move(m_jump_manager), m_priority, _func, std::move(m_taskset)}; } Jump::JumpManager::JumpManagerOperator::JumpBackIfCondition Jump::JumpManager::JumpManagerOperator::JumpBackIfClass::operator()(std::function<bool()>&& _func) && noexcept { return {std::move(m_jump_manager), m_priority, std::move(_func), std::move(m_taskset)}; } } //namespace Expr } //namespace TaskManager
47.978992
237
0.694894
RPGP1
3c2501530d7d4246a772f5c0f774edcf08c6e9dc
3,857
cpp
C++
libraries/wallet/cache.cpp
siwelo/bitshares-2
03561bfcf97801b44863bd51c400aae3ba51e3b0
[ "MIT" ]
null
null
null
libraries/wallet/cache.cpp
siwelo/bitshares-2
03561bfcf97801b44863bd51c400aae3ba51e3b0
[ "MIT" ]
null
null
null
libraries/wallet/cache.cpp
siwelo/bitshares-2
03561bfcf97801b44863bd51c400aae3ba51e3b0
[ "MIT" ]
null
null
null
/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * 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. Any modified source or binaries are used only with the BitShares network. * * 2. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 3. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <graphene/chain/account_object.hpp> #include <graphene/chain/asset_object.hpp> #include <graphene/chain/committee_member_object.hpp> #include <graphene/chain/witness_object.hpp> #include <graphene/chain/market_evaluator.hpp> #include <graphene/chain/proposal_object.hpp> #include <graphene/chain/operation_history_object.hpp> #include <graphene/chain/withdraw_permission_object.hpp> using namespace fc; using namespace graphene::chain; namespace graphene { namespace wallet { template< typename ObjectType > object* create_object_of_type( const variant& v ) { return new ObjectType( v.as<ObjectType>() ); } object* create_object( const variant& v ) { const variant_object& obj = v.get_object(); object_id_type obj_id = obj["id"].as< object_id_type >(); FC_ASSERT( obj_id.type() == protocol_ids ); // // Sufficiently clever template metaprogramming might // be able to convince the compiler to emit this switch // instead of creating it explicitly. // switch( obj_id.space() ) { /* case null_object_type: return nullptr; case base_object_type: return create_object_of_type< base_object >( v ); */ case account_object_type: return create_object_of_type< account_object >( v ); case asset_object_type: return create_object_of_type< asset_object >( v ); case force_settlement_object_type: return create_object_of_type< force_settlement_object >( v ); case committee_member_object_type: return create_object_of_type< committee_member_object >( v ); case witness_object_type: return create_object_of_type< witness_object >( v ); case limit_order_object_type: return create_object_of_type< limit_order_object >( v ); case call_order_object_type: return create_object_of_type< call_order_object >( v ); /* case custom_object_type: return create_object_of_type< custom_object >( v ); */ case proposal_object_type: return create_object_of_type< proposal_object >( v ); case operation_history_object_type: return create_object_of_type< operation_history_object >( v ); case withdraw_permission_object_type: return create_object_of_type< withdraw_permission_object >( v ); default: ; } FC_ASSERT( false, "unknown type_id" ); } } }
41.473118
208
0.736064
siwelo
3c28ada0362a0193875e578cf0ea0346d40baf4f
409
cpp
C++
cahttp/SimpleBuf.cpp
netmindms/cahttp
ea85a7b9143db5ebe96df1ac18476a30e9351248
[ "MIT" ]
null
null
null
cahttp/SimpleBuf.cpp
netmindms/cahttp
ea85a7b9143db5ebe96df1ac18476a30e9351248
[ "MIT" ]
null
null
null
cahttp/SimpleBuf.cpp
netmindms/cahttp
ea85a7b9143db5ebe96df1ac18476a30e9351248
[ "MIT" ]
null
null
null
/* * SimpleBuf.cpp * * Created on: Oct 21, 2015 * Author: netmind */ #include "SimpleBuf.h" SimpleBuf::SimpleBuf() { buffer = nullptr; capacity = 0; size = 0; } SimpleBuf::~SimpleBuf() { if(buffer) { free(buffer); } } void SimpleBuf::alloc(size_t bsize) { if(buffer) { free(buffer); } buffer = (char*)malloc(bsize); if(buffer) { capacity = bsize; } else { capacity = 0; } }
12.029412
37
0.594132
netmindms
3c298f4a5eaab9ef894d24e30415b6742ef64ff5
1,116
cpp
C++
Session_05/2019/00_Particle/src/ofApp.cpp
SAIC-ATS/ARTTECH3135
179805d373601ac92dcdbb51ddc4925fc65f7c22
[ "MIT" ]
26
2015-09-23T12:31:16.000Z
2020-12-14T03:19:19.000Z
Session_05/2019/00_Particle/src/ofApp.cpp
SAIC-ATS/ARTTECH3135
179805d373601ac92dcdbb51ddc4925fc65f7c22
[ "MIT" ]
2
2017-07-05T18:14:52.000Z
2017-10-31T00:04:13.000Z
Session_05/2019/00_Particle/src/ofApp.cpp
SAIC-ATS/ARTTECH3135
179805d373601ac92dcdbb51ddc4925fc65f7c22
[ "MIT" ]
37
2015-09-19T22:10:32.000Z
2019-12-07T19:35:55.000Z
#include "ofApp.h" void ofApp::setup() { // ofSetFrameRate(1) ofBackground(80); position.x = ofGetWidth() / 2; position.y = 0; position.z = 0; // Alternative syntax. velocity = { 0, 0, 0 }; // Acceleration due to gravity. // We only accelerate in the +y direction (down on screen). acceleration = { 0, .5, 0 }; } void ofApp::update() { // position.x = position.x + velocity.x; // position.y = position.y + velocity.y; // position.z = position.z + velocity.z; // is ... // position = position + velocity; // is ... velocity += acceleration; position += velocity; // "Bounce on the bottom condition." if (position.y + ballRadius > ofGetHeight()) { // Change its direction! velocity.y = velocity.y * -1; // Steal some of its velocity. velocity.y = velocity.y * 0.90; // Reset the ball to the "correct" position. position.y = ofGetHeight() - ballRadius; } } void ofApp::draw() { ofDrawCircle(position, ballRadius); }
19.241379
63
0.545699
SAIC-ATS
3c2a85dfd511265cc1c722cc0044f23ef623185f
1,245
cpp
C++
source/tracer/GlobalTrace.cpp
xzrunner/raytracing
c130691a92fab2cc9605f04534f42ca9b99e6fde
[ "MIT" ]
null
null
null
source/tracer/GlobalTrace.cpp
xzrunner/raytracing
c130691a92fab2cc9605f04534f42ca9b99e6fde
[ "MIT" ]
null
null
null
source/tracer/GlobalTrace.cpp
xzrunner/raytracing
c130691a92fab2cc9605f04534f42ca9b99e6fde
[ "MIT" ]
null
null
null
#include "raytracing/tracer/GlobalTrace.h" #include "raytracing/world/World.h" #include "raytracing/material/Material.h" #include "raytracing/utilities/ShadeRec.h" #include "raytracing/utilities/Constants.h" namespace rt { GlobalTrace::GlobalTrace(const World& world) : Tracer(world) { } RGBColor GlobalTrace::TraceRay(const Ray& ray, int depth) const { if (depth > m_world.GetViewPlane().GetMaxDepth()) { // return BLACK; return WHITE; } else { ShadeRec sr(m_world.HitObjects(ray)); if (sr.hit_an_object) { sr.depth = depth; sr.ray = ray; return sr.material->GlobalShade(sr); } else { return m_world.GetBackgroundColor(); } } } RGBColor GlobalTrace::TraceRay(const Ray& ray, double& tmin, int depth) const { if (depth > m_world.GetViewPlane().GetMaxDepth()) { tmin = HUGE_VALUE; // return BLACK; return WHITE; } else { ShadeRec sr(m_world.HitObjects(ray)); if (sr.hit_an_object) { sr.depth = depth; sr.ray = ray; tmin = sr.t; // required for colored transparency return sr.material->GlobalShade(sr); } else { tmin = HUGE_VALUE; return m_world.GetBackgroundColor(); } } } }
19.453125
77
0.636145
xzrunner
3c2be3f54066c35c1347d5d37632df34d158eded
14,453
cc
C++
pagespeed/kernel/cache/purge_context_test.cc
oschaaf/incubator-pagespeed-mod
12a4d582a6eed9114aae6474b4e5fddfa7e4908c
[ "MIT" ]
null
null
null
pagespeed/kernel/cache/purge_context_test.cc
oschaaf/incubator-pagespeed-mod
12a4d582a6eed9114aae6474b4e5fddfa7e4908c
[ "MIT" ]
null
null
null
pagespeed/kernel/cache/purge_context_test.cc
oschaaf/incubator-pagespeed-mod
12a4d582a6eed9114aae6474b4e5fddfa7e4908c
[ "MIT" ]
null
null
null
/* * 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 "pagespeed/kernel/cache/purge_context.h" #include "pagespeed/kernel/base/basictypes.h" #include "pagespeed/kernel/base/gtest.h" #include "pagespeed/kernel/base/mem_file_system.h" #include "pagespeed/kernel/base/mock_message_handler.h" #include "pagespeed/kernel/base/mock_timer.h" #include "pagespeed/kernel/base/named_lock_manager.h" #include "pagespeed/kernel/base/named_lock_tester.h" #include "pagespeed/kernel/base/null_statistics.h" #include "pagespeed/kernel/base/scoped_ptr.h" #include "pagespeed/kernel/base/statistics.h" #include "pagespeed/kernel/base/thread_system.h" #include "pagespeed/kernel/thread/mock_scheduler.h" #include "pagespeed/kernel/thread/scheduler_based_abstract_lock.h" #include "pagespeed/kernel/util/file_system_lock_manager.h" #include "pagespeed/kernel/util/platform.h" #include "pagespeed/kernel/util/simple_stats.h" namespace { const int kMaxBytes = 100; const char kPurgeFile[] = "/cache/cache.flush"; const char kBasePath[] = "/cache"; } // namespace namespace net_instaweb { class PurgeContextTest : public ::testing::Test, public ::testing::WithParamInterface<bool> { public: void CorruptWrittenFileHook(const GoogleString& filename) { EXPECT_TRUE(file_system_.WriteFile(filename.c_str(), "bogus", &message_handler_)); } void CorruptFileAndAddNewUpdate(const GoogleString& filename) { EXPECT_TRUE(file_system_.WriteFile(filename.c_str(), "bogus", &message_handler_)); lock_->Unlock(); ASSERT_TRUE(lock_tester_.LockTimedWaitStealOld(0, 0, lock_.get())); purge_context1_->AddPurgeUrl("a", 500000, ExpectSuccess()); } bool PollAndTest(const GoogleString& url, int64 now_ms, const CopyOnWrite<PurgeSet>& purge_set, PurgeContext* purge_context) { purge_context->PollFileSystem(); return purge_set->IsValid(url, now_ms); } bool PollAndTest1(const GoogleString& url, int64 now_ms) { return PollAndTest(url, now_ms, purge_set1_, purge_context1_.get()); } bool PollAndTest2(const GoogleString& url, int64 now_ms) { return PollAndTest(url, now_ms, purge_set2_, purge_context2_.get()); } protected: PurgeContextTest() : thread_system_(Platform::CreateThreadSystem()), timer_(thread_system_->NewMutex(), MockTimer::kApr_5_2010_ms), message_handler_(thread_system_->NewMutex()), file_system_(thread_system_.get(), &timer_), scheduler_(thread_system_.get(), &timer_), lock_manager_(&file_system_, kBasePath, &scheduler_, &message_handler_), lock_tester_(thread_system_.get()) { if (HasValidStats()) { statistics_.reset(new SimpleStats(thread_system_.get())); } else { statistics_.reset(new NullStatistics); } PurgeContext::InitStats(statistics_.get()); purge_context1_.reset(MakePurgeContext()); purge_context2_.reset(MakePurgeContext()); purge_context1_->SetUpdateCallback( NewPermanentCallback(this, &PurgeContextTest::UpdatePurgeSet1)); purge_context2_->SetUpdateCallback( NewPermanentCallback(this, &PurgeContextTest::UpdatePurgeSet2)); message_handler_.AddPatternToSkipPrinting("*opening input file*"); } bool HasValidStats() const { return GetParam(); } PurgeContext* MakePurgeContext() { return new PurgeContext(kPurgeFile, &file_system_, &timer_, kMaxBytes, thread_system_.get(), &lock_manager_, &scheduler_, statistics_.get(), &message_handler_); } GoogleString LockName() { return purge_context1_->LockName(); } void ExpectSuccessHelper(bool x, StringPiece reason) { EXPECT_TRUE(x); } PurgeContext::PurgeCallback* ExpectSuccess() { return NewCallback(this, &PurgeContextTest::ExpectSuccessHelper); } void ExpectFailureHelper(bool x, StringPiece reason) { EXPECT_FALSE(x); } PurgeContext::PurgeCallback* ExpectFailure() { return NewCallback(this, &PurgeContextTest::ExpectFailureHelper); } int64 LockContentionStart(PurgeContext::PurgeCallback* callback) { scheduler_.AdvanceTimeMs(10 * Timer::kSecondMs); lock_.reset(lock_manager_.CreateNamedLock(LockName())); EXPECT_TRUE(lock_tester_.LockTimedWaitStealOld(0, 0, lock_.get())); EXPECT_TRUE(lock_->Held()); int64 now_ms = timer_.NowMs(); purge_context1_->SetCachePurgeGlobalTimestampMs(now_ms, callback); // We don't check pending_purges_ in PollAndTestValid; the invalidation will // only be visible to purge_context1 when it can acquire the lock and // write its records. EXPECT_TRUE(PollAndTest1("b", now_ms - 1)); EXPECT_TRUE(PollAndTest2("b", now_ms - 1)); // Advance time by a second; which is not enough to steal the lock, // so we still consider 'b' to be valid in both contexts. scheduler_.AdvanceTimeMs(1 * Timer::kSecondMs); EXPECT_TRUE(PollAndTest1("b", now_ms - 1)); EXPECT_TRUE(PollAndTest2("b", now_ms - 1)); scheduler_.AdvanceTimeMs(1 * Timer::kSecondMs); // Not enough to steal it. return now_ms; } int num_cancellations() { return statistics_->GetVariable(PurgeContext::kCancellations)->Get(); } int num_contentions() { return statistics_->GetVariable(PurgeContext::kContentions)->Get(); } int file_parse_failures() { return statistics_->GetVariable(PurgeContext::kFileParseFailures)->Get(); } int num_file_stats() { return statistics_->GetVariable(PurgeContext::kFileStats)->Get(); } int ExpectStat(int expected_value) const { return HasValidStats() ? expected_value : 0; } int file_writes() { return statistics_->GetVariable(PurgeContext::kFileWrites)->Get(); } void UpdatePurgeSet1(const CopyOnWrite<PurgeSet>& purge_set) { purge_set1_ = purge_set; } void UpdatePurgeSet2(const CopyOnWrite<PurgeSet>& purge_set) { purge_set2_ = purge_set; } scoped_ptr<ThreadSystem> thread_system_; MockTimer timer_; MockMessageHandler message_handler_; MemFileSystem file_system_; MockScheduler scheduler_; FileSystemLockManager lock_manager_; scoped_ptr<Statistics> statistics_; scoped_ptr<PurgeContext> purge_context1_; scoped_ptr<PurgeContext> purge_context2_; CopyOnWrite<PurgeSet> purge_set1_; CopyOnWrite<PurgeSet> purge_set2_; scoped_ptr<NamedLock> lock_; NamedLockTester lock_tester_; }; TEST_P(PurgeContextTest, Empty) { EXPECT_TRUE(PollAndTest1("a", 500)); } TEST_P(PurgeContextTest, InvalidationSharing) { // Set up a write-delay on purge_context1_, but let purge_context2_ have // immediate writes. purge_context1_->set_request_batching_delay_ms(1000); scheduler_.AdvanceTimeMs(1000); purge_context1_->SetCachePurgeGlobalTimestampMs(400000, ExpectSuccess()); purge_context1_->AddPurgeUrl("a", 500000, ExpectSuccess()); EXPECT_EQ(0, file_writes()); EXPECT_EQ(0, num_file_stats()); // Prior to waiting for the new purge requests to be written, the purges // will not take effect. EXPECT_TRUE(PollAndTest1("a", 500000)); EXPECT_TRUE(PollAndTest1("b", 399999)); // Wait a second for the write-timer to fire, then both purges will be // written together in one file-write. scheduler_.AdvanceTimeMs(1000); EXPECT_EQ(ExpectStat(1), file_writes()); EXPECT_EQ(ExpectStat(2), num_file_stats()); if (!HasValidStats()) { scheduler_.AdvanceTimeMs(6000); } EXPECT_FALSE(PollAndTest1("a", 500000)); EXPECT_TRUE(PollAndTest1("a", 500001)); EXPECT_FALSE(PollAndTest1("b", 399999)); EXPECT_FALSE(PollAndTest1("b", 400000)); EXPECT_TRUE(PollAndTest1("b", 400001)); // These will get transmitted to purge_context2_, which has not // yet read the cache invalidation file, but will pick up the // changes from the file system. EXPECT_FALSE(PollAndTest2("a", 500000)); EXPECT_TRUE(PollAndTest2("a", 500001)); EXPECT_FALSE(PollAndTest2("b", 399999)); EXPECT_FALSE(PollAndTest2("b", 400000)); EXPECT_TRUE(PollAndTest2("b", 400001)); EXPECT_EQ(ExpectStat(4), num_file_stats()); // Now push a time-based flush the other direction. Because // we only poll the file system periodically we do have to advance // time. purge_context2_->SetCachePurgeGlobalTimestampMs(600000, ExpectSuccess()); if (!HasValidStats()) { scheduler_.AdvanceTimeMs(6000); } // This will have immediate effect because purge_context2_ has no write-delay. EXPECT_FALSE(PollAndTest2("a", 500001)); // There will also be no delay for purge_context1 because purge_context2_ // found a new version of the purge file, it updated shared stat "purge_index" // which is cheaply checked in every context on every poll. EXPECT_FALSE(PollAndTest1("a", 500001)); scheduler_.AdvanceTimeMs(10 * Timer::kSecondMs); // force poll EXPECT_FALSE(PollAndTest1("a", 500001)); EXPECT_TRUE(PollAndTest1("b", 600001)); EXPECT_FALSE(PollAndTest2("a", 500001)); EXPECT_TRUE(PollAndTest2("b", 600001)); // Now invalidate 'b' till 700k. purge_context2_->AddPurgeUrl("b", 700000, ExpectSuccess()); scheduler_.AdvanceTimeMs(HasValidStats() ? 1000 : 6000); EXPECT_FALSE(PollAndTest2("b", 700000)); // Again, this new value is immediately reflected in purge_context1. EXPECT_FALSE(PollAndTest1("b", 700000)); scheduler_.AdvanceTimeMs(10 * Timer::kSecondMs); // force poll EXPECT_FALSE(PollAndTest1("b", 700000)); EXPECT_TRUE(PollAndTest1("b", 700001)); EXPECT_FALSE(PollAndTest2("b", 700000)); EXPECT_TRUE(PollAndTest2("b", 700001)); EXPECT_EQ(0, file_parse_failures()); } TEST_P(PurgeContextTest, EmptyPurgeFile) { // The currently documented mechanism to flush the entire cache is // to simply touch CACHE_DIR/cache.flush. This mode of operation // requires disabling purging in the context. purge_context1_->set_enable_purge(false); scheduler_.AdvanceTimeMs(10 * Timer::kSecondMs); ASSERT_TRUE(file_system_.WriteFile(kPurgeFile, "", &message_handler_)); EXPECT_FALSE(PollAndTest1("b", timer_.NowMs() - 1)); EXPECT_TRUE(PollAndTest1("b", timer_.NowMs() + 1)); EXPECT_EQ(0, file_parse_failures()); } TEST_P(PurgeContextTest, LockContentionFailure) { int64 now_ms = LockContentionStart(ExpectFailure()); // Release & retake the lock making it harder to steal by refreshing it. lock_->Unlock(); ASSERT_TRUE(lock_tester_.LockTimedWaitStealOld(0, 0, lock_.get())); // Get our ExpectFailure callback called and confirm that the invalidation // didn't have any effect. scheduler_.AdvanceTimeMs(10 * Timer::kSecondMs); EXPECT_TRUE(PollAndTest1("b", now_ms - 1)); EXPECT_TRUE(PollAndTest2("b", now_ms - 1)); EXPECT_EQ(ExpectStat(1), num_cancellations()); EXPECT_EQ(ExpectStat(0), num_contentions()); EXPECT_EQ(ExpectStat(0), file_parse_failures()); } TEST_P(PurgeContextTest, LockContentionSuccess) { int64 now_ms = LockContentionStart(ExpectSuccess()); // Now advance time by 10 seconds; this should ensure that we steal // the lock and can write the invalidation records for all to see. scheduler_.AdvanceTimeMs(10 * Timer::kSecondMs); EXPECT_FALSE(PollAndTest1("b", now_ms - 1)); EXPECT_FALSE(PollAndTest2("b", now_ms - 1)); EXPECT_EQ(0, num_cancellations()); EXPECT_EQ(0, num_contentions()); EXPECT_EQ(0, file_parse_failures()); } TEST_P(PurgeContextTest, FileWriteConflict) { int64 now_ms = LockContentionStart(ExpectSuccess()); file_system_.set_write_callback( NewCallback(this, &PurgeContextTest::CorruptWrittenFileHook)); // Now advance time by 10 seconds; this should ensure that we steal // the lock and can write the invalidation records for all to see. // Unfortunately the file-write will not be verified and will have // to grab the lock and do it again. scheduler_.AdvanceTimeMs(10 * Timer::kSecondMs); EXPECT_FALSE(PollAndTest1("b", now_ms - 1)); EXPECT_FALSE(PollAndTest2("b", now_ms - 1)); EXPECT_EQ(0, num_cancellations()); EXPECT_EQ(ExpectStat(1), num_contentions()); EXPECT_EQ(ExpectStat(1), file_parse_failures()); } TEST_P(PurgeContextTest, FileWriteConflictWithInterveningUpdate) { int64 now_ms = LockContentionStart(ExpectSuccess()); file_system_.set_write_callback( NewCallback(this, &PurgeContextTest::CorruptFileAndAddNewUpdate)); // Now advance time by 10 seconds; this should ensure that we steal // the lock and can write the invalidation records for all to see. // Unfortunately the file-write will not be verified and will have // to grab the lock and do it again. scheduler_.AdvanceTimeMs(10 * Timer::kSecondMs); EXPECT_FALSE(PollAndTest1("b", now_ms - 1)); EXPECT_FALSE(PollAndTest2("b", now_ms - 1)); EXPECT_EQ(0, num_cancellations()); EXPECT_EQ(ExpectStat(1), num_contentions()); EXPECT_EQ(ExpectStat(1), file_parse_failures()); } TEST_P(PurgeContextTest, InvalidTimestampInPurgeRecord) { ASSERT_TRUE(file_system_.WriteFile( kPurgeFile, "-1\n" // Valid initial timestamp "x\n" // not enough tokens "2000000000000 y\n" // timestamp(ms) in far future "-2 z\n" // timestamp(ms) in far past "500 a\n", // valid record should be parsed. &message_handler_)); EXPECT_FALSE(PollAndTest1("a", 500)); EXPECT_EQ(ExpectStat(3), file_parse_failures()); EXPECT_TRUE(PollAndTest1("a", 501)); EXPECT_EQ(ExpectStat(6), file_parse_failures()); } // We test with use_null_statistics == GetParam() as both true and false. INSTANTIATE_TEST_SUITE_P(PurgeContextTestInstance, PurgeContextTest, ::testing::Bool()); } // namespace net_instaweb
37.736292
80
0.724555
oschaaf
3c2d3da65db418eef95a86d9a5506e1b320c14fb
32,729
cc
C++
src/win32/base/uninstall_helper.cc
soleilpqd/mozc
4767ce2f2b6a63f1f139daea6e98bc7a564d5e4e
[ "BSD-3-Clause" ]
1
2017-09-01T20:55:40.000Z
2017-09-01T20:55:40.000Z
src/win32/base/uninstall_helper.cc
soleilpqd/mozc
4767ce2f2b6a63f1f139daea6e98bc7a564d5e4e
[ "BSD-3-Clause" ]
null
null
null
src/win32/base/uninstall_helper.cc
soleilpqd/mozc
4767ce2f2b6a63f1f139daea6e98bc7a564d5e4e
[ "BSD-3-Clause" ]
2
2020-02-12T15:24:27.000Z
2020-02-22T13:36:21.000Z
// Copyright 2010-2016, 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: // // * 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 Google Inc. 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. #include "win32/base/uninstall_helper.h" #define _ATL_NO_AUTOMATIC_NAMESPACE #define _WTL_NO_AUTOMATIC_NAMESPACE #include <atlbase.h> #include <atlcom.h> #include <msctf.h> #include <strsafe.h> #include <objbase.h> #include <iomanip> #include <map> #include <memory> #include <sstream> #include "base/logging.h" #include "base/scoped_handle.h" #include "base/system_util.h" #include "base/win_util.h" #include "win32/base/imm_registrar.h" #include "win32/base/imm_util.h" #include "win32/base/immdev.h" #include "win32/base/tsf_profile.h" namespace mozc { namespace win32 { using ATL::CComPtr; using ATL::CRegKey; using std::unique_ptr; namespace { typedef map<int, DWORD> PreloadOrderToKLIDMap; // Windows NT 6.0, 6.1 and 6.2 const CLSID CLSID_IMJPTIP = { 0x03b5835f, 0xf03c, 0x411b, {0x9c, 0xe2, 0xaa, 0x23, 0xe1, 0x17, 0x1e, 0x36} }; const GUID GUID_IMJPTIP = { 0xa76c93d9, 0x5523, 0x4e90, {0xaa, 0xfa, 0x4d, 0xb1, 0x12, 0xf9, 0xac, 0x76} }; const LANGID kLANGJaJP = MAKELANGID(LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN); const wchar_t kRegKeyboardLayouts[] = L"SYSTEM\\CurrentControlSet\\Control\\Keyboard Layouts"; const wchar_t kPreloadKeyName[] = L"Keyboard Layout\\Preload"; // Registry element size limits are described in the link below. // http://msdn.microsoft.com/en-us/library/ms724872(VS.85).aspx const DWORD kMaxValueNameLength = 16383; // Timeout value used by a work around against b/5765783. // Note that the following timeout threshold is not well tested. // TODO(yukawa): Investigate the best timeout threshold. b/6165722 const uint32 kWaitForAsmCacheReadyEventTimeout = 10000; // 10 sec. // Converts an unsigned integer to a wide string. wstring utow(unsigned int i) { wstringstream ss; ss << i; return ss.str(); } wstring GetIMEFileNameFromKeyboardLayout( const CRegKey &key, const KeyboardLayoutID &klid) { CRegKey subkey; LONG result = subkey.Open(key, klid.ToString().c_str(), KEY_READ); if (ERROR_SUCCESS != result) { return L""; } wchar_t filename_buffer[kMaxValueNameLength]; ULONG filename_length_including_null = kMaxValueNameLength; result = subkey.QueryStringValue( L"Ime File", filename_buffer, &filename_length_including_null); // Note that |filename_length_including_null| contains NUL terminator. if ((ERROR_SUCCESS != result) || (filename_length_including_null <= 1)) { return L""; } const ULONG filename_length = (filename_length_including_null - 1); const wstring filename(filename_buffer); // Note that |filename_length| does not contain NUL character. DCHECK_EQ(filename_length, filename.size()); return filename; } bool GenerateKeyboardLayoutList(vector<KeyboardLayoutInfo> *keyboard_layouts) { if (keyboard_layouts == nullptr) { return false; } keyboard_layouts->clear(); CRegKey key; LONG result = key.Open( HKEY_LOCAL_MACHINE, kRegKeyboardLayouts, KEY_READ); if (ERROR_SUCCESS != result) { return false; } wchar_t value_name[kMaxValueNameLength]; for (DWORD enum_reg_index = 0;; ++enum_reg_index) { DWORD value_name_length = kMaxValueNameLength; result = key.EnumKey( enum_reg_index, value_name, &value_name_length); if (ERROR_NO_MORE_ITEMS == result) { return true; } if (ERROR_SUCCESS != result) { return true; } // Note that |value_name_length| does not contain NUL character. const KeyboardLayoutID klid( wstring(value_name, value_name + value_name_length)); if (!klid.has_id()) { continue; } KeyboardLayoutInfo info; info.klid = klid.id(); info.ime_filename = GetIMEFileNameFromKeyboardLayout(key, klid); keyboard_layouts->push_back(info); } return true; } bool GenerateKeyboardLayoutMap(map<DWORD, wstring> *keyboard_layouts) { if (keyboard_layouts == nullptr) { return false; } vector<KeyboardLayoutInfo> keyboard_layout_list; if (!GenerateKeyboardLayoutList(&keyboard_layout_list)) { return false; } for (size_t i = 0; i < keyboard_layout_list.size(); ++i) { const KeyboardLayoutInfo &layout = keyboard_layout_list[i]; (*keyboard_layouts)[layout.klid] = layout.ime_filename; } return true; } wstring GetIMEFileName(HKL hkl) { const UINT num_chars_without_null = ::ImmGetIMEFileName(hkl, nullptr, 0); const size_t num_chars_with_null = num_chars_without_null + 1; unique_ptr<wchar_t[]> buffer(new wchar_t[num_chars_with_null]); const UINT num_copied = ::ImmGetIMEFileName(hkl, buffer.get(), num_chars_with_null); // |num_copied| does not include terminating null character. return wstring(buffer.get(), buffer.get() + num_copied); } bool GetInstalledProfilesByLanguageForTSF( LANGID langid, vector<LayoutProfileInfo> *installed_profiles) { ScopedCOMInitializer com_initializer; if (FAILED(com_initializer.error_code())) { return false; } HRESULT hr = S_OK; CComPtr<ITfInputProcessorProfiles> profiles; hr = profiles.CoCreateInstance(CLSID_TF_InputProcessorProfiles); if (FAILED(hr)) { return false; } CComPtr<IEnumTfLanguageProfiles> enum_profiles; hr = profiles->EnumLanguageProfiles(langid, &enum_profiles); if (FAILED(hr)) { return false; } while (true) { ULONG num_fetched = 0; TF_LANGUAGEPROFILE src = {0}; hr = enum_profiles->Next(1, &src, &num_fetched); if (FAILED(hr)) { return false; } if ((hr == S_FALSE) || (num_fetched != 1)) { break; } if (src.catid != GUID_TFCAT_TIP_KEYBOARD) { continue; } LayoutProfileInfo profile; profile.langid = src.langid; profile.is_default = (src.fActive != FALSE); BOOL enabled = FALSE; hr = profiles->IsEnabledLanguageProfile( src.clsid, langid, src.guidProfile, &enabled); if (SUCCEEDED(hr)) { profile.is_enabled = (enabled != FALSE); } profile.clsid = src.clsid; profile.profile_guid = src.guidProfile; profile.is_tip = true; installed_profiles->push_back(profile); } return true; } bool GetInstalledProfilesByLanguageForIMM32( LANGID langid, vector<LayoutProfileInfo> *installed_profiles) { vector<KeyboardLayoutInfo> keyboard_layouts; if (!GenerateKeyboardLayoutList(&keyboard_layouts)) { DLOG(ERROR) << "GenerateKeyboardLayoutList failed."; return false; } for (size_t i = 0; i < keyboard_layouts.size(); ++i) { const KeyboardLayoutInfo &info = keyboard_layouts[i]; const LANGID info_langid = static_cast<LANGID>(info.klid & 0xffff); if (info_langid == langid) { LayoutProfileInfo profile; profile.langid = langid; profile.is_tip = false; profile.klid = info.klid; // TODO(yukawa): determine |profile.is_default| // TODO(yukawa): determine |profile.is_enabled| profile.ime_filename = info.ime_filename; installed_profiles->push_back(profile); } } return true; } bool GetPreloadLayoutsMain(PreloadOrderToKLIDMap *preload_map) { if (preload_map == nullptr) { return false; } // Retrieve keys under kPreloadKeyName. CRegKey preload_key; LONG result = preload_key.Open(HKEY_CURRENT_USER, kPreloadKeyName); if (ERROR_SUCCESS != result) { return false; } wchar_t value_name[kMaxValueNameLength]; const DWORD kMaxValueLength = 256; BYTE value[kMaxValueLength]; for (DWORD i = 0;; ++i) { DWORD value_name_length = kMaxValueNameLength; DWORD value_length = kMaxValueLength; result = RegEnumValue(preload_key, i, value_name, &value_name_length, nullptr, // reserved (must be nullptr) nullptr, // type (optional) value, &value_length); if (ERROR_NO_MORE_ITEMS == result) { break; } if (ERROR_SUCCESS != result) { return false; } const int ivalue_name = _wtoi(value_name); const wstring wvalue(reinterpret_cast<wchar_t*>(value), (value_length / sizeof(wchar_t)) - 1); KeyboardLayoutID klid(wvalue); if (!klid.has_id()) { continue; } (*preload_map)[ivalue_name] = klid.id(); } return true; } wstring GUIDToString(const GUID &guid) { wchar_t buffer[256]; const int character_length_with_null = ::StringFromGUID2(guid, buffer, arraysize(buffer)); if (character_length_with_null <= 0) { return L""; } const size_t character_length_without_null = character_length_with_null - 1; return wstring(buffer, buffer + character_length_without_null); } wstring LANGIDToString(LANGID langid) { wchar_t buffer[5]; HRESULT hr = ::StringCchPrintf(buffer, arraysize(buffer), L"%04x", langid); if (FAILED(hr)) { return L""; } return buffer; } bool BroadcastNewIME(const KeyboardLayoutInfo &layout) { KeyboardLayoutID klid(layout.klid); // We cannot use const HKL because |&mozc_hkl| will be cast into PVOID. HKL hkl = ::LoadKeyboardLayout(klid.ToString().c_str(), KLF_ACTIVATE); // SPI_SETDEFAULTINPUTLANG ensures that new process in this session will // use |hkl| by default but this setting is volatile even if you specified // SPIF_UPDATEINIFILE flag. // SPI_SETDEFAULTINPUTLANG does not work perfectly for a HKL substituted // by a TIP on Windows XP. It works for notepad but wordpad still uses // the previous layout. Consider to use // ITfInputProcessorProfiles::SetDefaultLanguageProfile for TIP backed // layout. if (::SystemParametersInfo( SPI_SETDEFAULTINPUTLANG, 0, &hkl, SPIF_SENDCHANGE) == FALSE) { LOG(ERROR) << "SystemParameterInfo failed: " << GetLastError(); return false; } // A work around against b/5765783. if (!ImeUtil::WaitForAsmCacheReady(kWaitForAsmCacheReadyEventTimeout)) { DLOG(ERROR) << "ImeUtil::WaitForAsmCacheReady failed."; } // Broadcasting WM_INPUTLANGCHANGEREQUEST so that existing process in the // current session will change their input method to |hkl|. This mechanism // also works against a HKL which is substituted by a TIP on Windows XP. // Note: we have virtually the same code in imm_util.cc too. // TODO(yukawa): Make a common function around WM_INPUTLANGCHANGEREQUEST. DWORD recipients = BSM_APPLICATIONS; const LONG result = ::BroadcastSystemMessage( BSF_POSTMESSAGE, &recipients, WM_INPUTLANGCHANGEREQUEST, INPUTLANGCHANGE_SYSCHARSET, reinterpret_cast<LPARAM>(hkl)); if (result == 0) { const int error = ::GetLastError(); LOG(ERROR) << "BroadcastSystemMessage failed. error = " << error; return false; } return true; } bool BroadcastNewTIPOnVista(const LayoutProfileInfo &profile) { ScopedCOMInitializer com_initializer; if (FAILED(com_initializer.error_code())) { return false; } CComPtr<ITfInputProcessorProfileMgr> profile_manager; HRESULT hr = S_OK; hr = profile_manager.CoCreateInstance(CLSID_TF_InputProcessorProfiles); if (FAILED(hr)) { return false; } const DWORD activate_flags = TF_IPPMF_FORSESSION | TF_IPPMF_ENABLEPROFILE | TF_IPPMF_DONTCARECURRENTINPUTLANGUAGE; hr = profile_manager->ActivateProfile( TF_PROFILETYPE_INPUTPROCESSOR, profile.langid, profile.clsid, profile.profile_guid, nullptr, activate_flags); if (FAILED(hr)) { return false; } return true; } bool EnableAndBroadcastNewLayout( const LayoutProfileInfo &profile, bool broadcast_change) { if (profile.is_tip) { ScopedCOMInitializer com_initializer; if (FAILED(com_initializer.error_code())) { return false; } CComPtr<ITfInputProcessorProfileMgr> profile_manager; HRESULT hr = S_OK; hr = profile_manager.CoCreateInstance(CLSID_TF_InputProcessorProfiles); if (FAILED(hr)) { return false; } DWORD activate_flags = TF_IPPMF_ENABLEPROFILE | TF_IPPMF_DONTCARECURRENTINPUTLANGUAGE; if (broadcast_change) { activate_flags |= TF_IPPMF_FORSESSION; } hr = profile_manager->ActivateProfile( TF_PROFILETYPE_INPUTPROCESSOR, profile.langid, profile.clsid, profile.profile_guid, nullptr, activate_flags); if (FAILED(hr)) { DLOG(ERROR) << "ActivateProfile failed"; return false; } return true; } // |profile| is IME. if (!broadcast_change) { return true; } KeyboardLayoutInfo layout; layout.klid = profile.klid; layout.ime_filename = profile.ime_filename; if (!BroadcastNewIME(layout)) { DLOG(ERROR) << "BroadcastNewIME failed"; return false; } return true; } bool GetActiveKeyboardLayouts(vector<HKL> *keyboard_layouts) { if (keyboard_layouts == nullptr) { return false; } keyboard_layouts->clear(); const int num_keyboard_layout = ::GetKeyboardLayoutList(0, nullptr); unique_ptr<HKL[]> buffer(new HKL[num_keyboard_layout]); const int num_copied = ::GetKeyboardLayoutList(num_keyboard_layout, buffer.get()); keyboard_layouts->assign(buffer.get(), buffer.get() + num_copied); return true; } void EnableAndSetDefaultIfLayoutIsTIP(const KeyboardLayoutInfo &layout) { ScopedCOMInitializer com_initializer; if (FAILED(com_initializer.error_code())) { return; } HRESULT hr = S_OK; CComPtr<ITfInputProcessorProfiles> profiles; hr = profiles.CoCreateInstance(CLSID_TF_InputProcessorProfiles); if (FAILED(hr)) { return; } CComPtr<ITfInputProcessorProfileSubstituteLayout> substitute_layout; hr = profiles.QueryInterface(&substitute_layout); if (FAILED(hr)) { return; } CComPtr<IEnumTfLanguageProfiles> enum_profiles; const LANGID langid = static_cast<LANGID>(layout.klid); hr = profiles->EnumLanguageProfiles(langid, &enum_profiles); if (FAILED(hr)) { return; } while (true) { ULONG num_fetched = 0; TF_LANGUAGEPROFILE profile = {0}; hr = enum_profiles->Next(1, &profile, &num_fetched); if (FAILED(hr)) { return; } if ((hr == S_FALSE) || (num_fetched != 1)) { return; } if (profile.catid != GUID_TFCAT_TIP_KEYBOARD) { continue; } HKL hkl = nullptr; hr = substitute_layout->GetSubstituteKeyboardLayout(profile.clsid, profile.langid, profile.guidProfile, &hkl); if (FAILED(hr)) { DLOG(ERROR) << "GetSubstituteKeyboardLayout failed"; continue; } if (!WinUtil::SystemEqualString( GetIMEFileName(hkl), layout.ime_filename, true)) { continue; } BOOL enabled = TRUE; hr = profiles->EnableLanguageProfile(profile.clsid, profile.langid, profile.guidProfile, TRUE); if (FAILED(hr)) { DLOG(ERROR) << "EnableLanguageProfile failed"; continue; } hr = profiles->SetDefaultLanguageProfile(profile.langid, profile.clsid, profile.guidProfile); if (FAILED(hr)) { DLOG(ERROR) << "SetDefaultLanguageProfile failed"; continue; } return; } return; } // This function lists all the active keyboard layouts up and unloads each // layout based on the specified condition. If |exclude| is true, this // function unloads any active IME if it is included in |ime_filenames|. // If |exclude| is false, this function unloads any active IME unless it is // included in |ime_filenames|. void UnloadActivatedKeyboardMain(const vector<wstring> &ime_filenames, bool exclude) { vector<HKL> loaded_layouts; if (!GetActiveKeyboardLayouts(&loaded_layouts)) { return; } for (size_t i = 0; i < loaded_layouts.size(); ++i) { const HKL hkl = loaded_layouts[i]; const wstring ime_filename = GetIMEFileName(hkl); if (ime_filename.empty()) { continue; } bool can_unload = !exclude; for (size_t j = 0; j < ime_filenames.size(); ++j) { if (WinUtil::SystemEqualString(ime_filename, ime_filenames[j], true)) { can_unload = exclude; break; } } if (can_unload) { ::UnloadKeyboardLayout(hkl); } } } void UnloadProfilesForVista( const vector<LayoutProfileInfo> &profiles_to_be_removed) { vector <wstring> ime_filenames; for (size_t i = 0; i < profiles_to_be_removed.size(); ++i) { ime_filenames.push_back(profiles_to_be_removed[i].ime_filename); } UnloadActivatedKeyboardMain(ime_filenames, true); } bool IsEqualProfile(const LayoutProfileInfo &lhs, const LayoutProfileInfo &rhs) { // Check if the profile type (TIP or IME) is the same. if (lhs.is_tip != rhs.is_tip) { return false; } // Check if the target language is the same. if (lhs.langid != rhs.langid) { return false; } if (lhs.is_tip) { // If both of them are TIP, check if they have the same CLSID and Profile // GUID. Otherwise, they are different from each other. DCHECK(rhs.is_tip); if (::IsEqualCLSID(lhs.clsid, rhs.clsid) == 0) { return false; } if (::IsEqualGUID(lhs.profile_guid, rhs.profile_guid) == 0) { return false; } return true; } // If both of them are IME, check if they have the same KLID and IME file // name (if any). Otherwise, they are different from each other. DCHECK(!lhs.is_tip); DCHECK(!rhs.is_tip); if (lhs.klid != rhs.klid) { return false; } if (!WinUtil::SystemEqualString( lhs.ime_filename.c_str(), rhs.ime_filename.c_str(), true)) { return false; } return true; } bool IsEqualPreload(const PreloadOrderToKLIDMap &current_preload_map, const vector<KeyboardLayoutInfo> &new_preload_layouts) { if (current_preload_map.size() != new_preload_layouts.size()) { return false; } int index = 0; for (PreloadOrderToKLIDMap::const_iterator it = current_preload_map.begin(); it != current_preload_map.end(); ++it) { const DWORD klid = it->second; DCHECK_GE(index, 0); DCHECK_LT(index, new_preload_layouts.size()); if (klid != new_preload_layouts[index].klid) { return false; } ++index; } return true; } // Currently only keyboard layouts which have IME filename are supported. bool RemoveHotKeyForIME( const vector<KeyboardLayoutInfo> &layouts_to_be_removed) { bool succeeded = true; for (DWORD id = IME_HOTKEY_DSWITCH_FIRST; id <= IME_HOTKEY_DSWITCH_LAST; ++id) { UINT modifiers = 0; UINT virtual_key = 0; HKL hkl = nullptr; BOOL result = ::ImmGetHotKey(id, &modifiers, &virtual_key, &hkl); if (result == FALSE) { continue; } if (hkl == nullptr) { continue; } const wstring ime_name = GetIMEFileName(hkl); for (size_t i = 0; i < layouts_to_be_removed.size(); ++i) { const KeyboardLayoutInfo &layout = layouts_to_be_removed[i]; if (layout.ime_filename.empty()) { continue; } if (!WinUtil::SystemEqualString(layout.ime_filename, ime_name, true)) { continue; } // ImmSetHotKey fails when both 2nd and 3rd arguments are valid while 4th // argument is nullptr. To remove the HotKey, pass 0 to them. result = ::ImmSetHotKey(id, 0, 0, nullptr); if (result == FALSE) { succeeded = false; } break; } } return succeeded; } // Currently this function is Mozc-specific. // TODO(yukawa): Generalize this function for any IME. void RemoveHotKeyForVista(const vector<LayoutProfileInfo> &installed_profiles) { vector<KeyboardLayoutInfo> hotkey_remove_targets; for (size_t i = 0; i < installed_profiles.size(); ++i) { const LayoutProfileInfo &profile = installed_profiles[i]; if (!profile.is_tip && WinUtil::SystemEqualString( profile.ime_filename, ImmRegistrar::GetFileNameForIME(), true)) { // This is the full IMM32 version of Google Japanese Input. KeyboardLayoutInfo info; info.klid = profile.klid; info.ime_filename = profile.ime_filename; hotkey_remove_targets.push_back(info); continue; } } if (!RemoveHotKeyForIME(hotkey_remove_targets)) { DLOG(ERROR) << "RemoveHotKeyForIME failed."; } } } // namespace KeyboardLayoutInfo::KeyboardLayoutInfo() : klid(0) {} LayoutProfileInfo::LayoutProfileInfo() : langid(0), clsid(CLSID_NULL), profile_guid(GUID_NULL), klid(0), is_default(false), is_tip(false), is_enabled(false) {} // Currently this function is Mozc-specific. // TODO(yukawa): Generalize this function for any IME and/or TIP. bool UninstallHelper::GetNewEnabledProfileForVista( const vector<LayoutProfileInfo> &current_profiles, const vector<LayoutProfileInfo> &installed_profiles, LayoutProfileInfo *current_default, LayoutProfileInfo *new_default, vector<LayoutProfileInfo> *removed_profiles) { if (current_default == nullptr) { return false; } // Initialize in case no entry is marked as default. *current_default = LayoutProfileInfo(); if (new_default == nullptr) { return false; } if (removed_profiles == nullptr) { return false; } removed_profiles->clear(); bool default_found = false; bool default_set = false; for (size_t i = 0; i < current_profiles.size(); ++i) { const LayoutProfileInfo &profile = current_profiles[i]; if (profile.is_default) { *current_default = profile; } if (!profile.is_tip && WinUtil::SystemEqualString( profile.ime_filename, ImmRegistrar::GetFileNameForIME(), true)) { // This is the full IMM32 version of Google Japanese Input. removed_profiles->push_back(profile); continue; } if (profile.is_tip && ::IsEqualCLSID(TsfProfile::GetTextServiceGuid(), profile.clsid) && ::IsEqualGUID(TsfProfile::GetProfileGuid(), profile.profile_guid)) { // This is the full TSF version of Google Japanese Input. removed_profiles->push_back(profile); continue; } if (!default_found && profile.is_enabled && profile.is_default) { default_found = true; default_set = true; *new_default = profile; } if (!default_found && !default_set && profile.is_enabled) { default_set = true; *new_default = profile; } } if (!default_set) { // TODO(yukawa): Consider this case. // Use MS-IME as a fallback. new_default->langid = MAKELANGID(LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN); new_default->clsid = CLSID_IMJPTIP; new_default->profile_guid = GUID_IMJPTIP; new_default->klid = 0; new_default->ime_filename.clear(); new_default->is_default = true; new_default->is_tip = true; new_default->is_enabled = false; } return true; } bool UninstallHelper::GetInstalledProfilesByLanguage( LANGID langid, vector<LayoutProfileInfo> *installed_profiles) { if (installed_profiles == nullptr) { return false; } installed_profiles->clear(); if (!GetInstalledProfilesByLanguageForTSF(langid, installed_profiles)) { // Actually this can fail if user have explicitly unregistered TSF modules // like b/2636769. We do not return false because it would be better to // continue with the result of GetInstalledProfilesByLanguageForIMM32. LOG(ERROR) << "GetInstalledProfilesByLanguageForTSF failed."; } if (!GetInstalledProfilesByLanguageForIMM32(langid, installed_profiles)) { LOG(ERROR) << "GetInstalledProfilesByLanguageForIMM32 failed."; return false; } return true; } bool UninstallHelper::GetCurrentProfilesForVista( vector<LayoutProfileInfo> *current_profiles) { if (current_profiles == nullptr) { return false; } current_profiles->clear(); map<DWORD, wstring> keyboard_layouts; if (!GenerateKeyboardLayoutMap(&keyboard_layouts)) { return false; } { const UINT num_element = ::EnumEnabledLayoutOrTip( nullptr, nullptr, nullptr, nullptr, 0); unique_ptr<LAYOUTORTIPPROFILE[]> buffer( new LAYOUTORTIPPROFILE[num_element]); const UINT num_copied = ::EnumEnabledLayoutOrTip( nullptr, nullptr, nullptr, buffer.get(), num_element); for (size_t i = 0; i < num_copied; ++i) { const LAYOUTORTIPPROFILE &src = buffer[i]; if (src.catid != GUID_TFCAT_TIP_KEYBOARD) { continue; } LayoutProfileInfo profile; profile.langid = src.langid; profile.is_default = ((src.dwFlags & LOT_DEFAULT) == LOT_DEFAULT); profile.is_enabled = !((src.dwFlags & LOT_DISABLED) == LOT_DISABLED); profile.clsid = src.clsid; profile.profile_guid = src.guidProfile; if ((src.dwProfileType & LOTP_INPUTPROCESSOR) == LOTP_INPUTPROCESSOR) { profile.is_tip = true; current_profiles->push_back(profile); continue; } if ((src.dwProfileType & LOTP_KEYBOARDLAYOUT) == LOTP_KEYBOARDLAYOUT) { const wstring id(src.szId); // A valid |profile.szId| should consists of language ID (LANGID) and // keyboard layout ID (KILD) as follows. // <LangID 1>:<KLID 1> // "0411:E0200411" // Check if |id.size()| is expected. if (id.size() != 13) { continue; } // Extract KLID. It should be 8-letter hexadecimal code begins at 6th // character in the |id|, that is, |id.substr(5, 8)|. const KeyboardLayoutID klid(id.substr(5, 8)); if (!klid.has_id()) { continue; } profile.klid = klid.id(); if (keyboard_layouts.find(profile.klid) != keyboard_layouts.end()) { profile.ime_filename = keyboard_layouts[profile.klid]; } profile.is_tip = false; current_profiles->push_back(profile); continue; } } } // release |buffer| return true; } bool UninstallHelper::RemoveProfilesForVista( const vector<LayoutProfileInfo> &profiles_to_be_removed) { if (profiles_to_be_removed.size() == 0) { // Nothing to do. return true; } const wstring &profile_string = ComposeProfileStringForVista( profiles_to_be_removed); const BOOL result = ::InstallLayoutOrTipUserReg( nullptr, nullptr, nullptr, profile_string.c_str(), ILOT_UNINSTALL); return result != FALSE; } wstring UninstallHelper::ComposeProfileStringForVista( const vector<LayoutProfileInfo> &profiles) { wstringstream ss; for (size_t i = 0; i < profiles.size(); ++i) { const LayoutProfileInfo &info = profiles[i]; if (i != 0) { ss << L";"; } const wstring &langid_string = LANGIDToString(info.langid); if (langid_string.empty()) { continue; } if (info.is_tip) { const wstring &clsid_string = GUIDToString(info.clsid); const wstring &guid_string = GUIDToString(info.profile_guid); if (clsid_string.empty() || guid_string.empty()) { continue; } ss << langid_string << L":" << clsid_string << guid_string; } else { const KeyboardLayoutID klid(info.klid); ss << langid_string << L":" << klid.ToString(); } } return ss.str(); } bool UninstallHelper::SetDefaultForVista( const LayoutProfileInfo &current_default, const LayoutProfileInfo &new_default, bool broadcast_change) { if (current_default.is_default && current_default.is_enabled && IsEqualProfile(current_default, new_default)) { // |new_default| is alreasy default and enabled. return true; } if (!EnableAndBroadcastNewLayout(new_default, broadcast_change)) { // We do not return false here because the main task of this function is // setting the specified profile to default. DLOG(ERROR) << "EnableAndBroadcastNewLayout failed."; } vector<LayoutProfileInfo> profile_list; profile_list.push_back(new_default); const wstring profile_string = ComposeProfileStringForVista(profile_list); if (profile_string.empty()) { return false; } DWORD flag = 0; if (!broadcast_change) { // If |broadcast_change| prevent the SetDefaultLayoutOrTip API from // disturbing the current session in case the thread is impersonated. flag = SDLOT_NOAPPLYTOCURRENTSESSION; } if (!::SetDefaultLayoutOrTip(profile_string.c_str(), flag)) { DLOG(ERROR) << "SetDefaultLayoutOrTip failed"; return false; } return true; } bool UninstallHelper::RestoreUserIMEEnvironmentForVista(bool broadcast_change) { vector<LayoutProfileInfo> installed_profiles; if (!GetInstalledProfilesByLanguage(kLANGJaJP, &installed_profiles)) { return false; } RemoveHotKeyForVista(installed_profiles); vector<LayoutProfileInfo> current_profiles; if (!GetCurrentProfilesForVista(&current_profiles)) { return false; } LayoutProfileInfo current_default; LayoutProfileInfo new_default; vector<LayoutProfileInfo> removed_profiles; if (!GetNewEnabledProfileForVista(current_profiles, installed_profiles, &current_default, &new_default, &removed_profiles)) { return false; } if (!SetDefaultForVista(current_default, new_default, broadcast_change)) { DLOG(ERROR) << "SetDefaultForVista failed."; } if (!RemoveProfilesForVista(removed_profiles)) { DLOG(ERROR) << "RemoveProfilesForVista failed."; } if (broadcast_change) { // Unload unnecessary keyboard layouts. UnloadProfilesForVista(removed_profiles); } return true; } bool UninstallHelper::RestoreUserIMEEnvironmentMain() { // Basically this function is called from the "non-deferred" custom action // with "non-elevated" user privileges, which is enough and prefarable to // update entries under HKCU. Assuming the desktop is available, // broadcast messages into existing processes so that these processes // start to use the new default IME. const bool kBroadcastNewIME = true; return RestoreUserIMEEnvironmentForVista(kBroadcastNewIME); } bool UninstallHelper::EnsureIMEIsRemovedForCurrentUser( bool disable_hkcu_cache) { if (disable_hkcu_cache) { // For some reason, HKCU in a deferred, non-impersonated custom action is // occasionally mapped not to the HKU/.Default but to the active user's // profile as if the current thread is impersonated to the active user. // To fix up this, we should disable per-process registry cache by calling // RegDisablePredefinedCache API. const LRESULT result = ::RegDisablePredefinedCache(); if (result != ERROR_SUCCESS) { DLOG(ERROR) << "IsServiceThread failed. result = " << result; return false; } } // Since this function is targeting for the service account, IME change // notification will not be sent in case it causes unwilling side-effects // against other important processes running in the service session. const bool kBroadcastNewIME = false; return RestoreUserIMEEnvironmentForVista(kBroadcastNewIME); } } // namespace win32 } // namespace mozc
31.470192
80
0.682697
soleilpqd
3c2ea94823802909038a93a49ee82226fd5f3c2f
1,966
hpp
C++
lkCommon/include/lkCommon/Utils/StaticStack.hpp
lookeypl/lkCommon
efd08396f2b151a320e103bd8111b745246b44e8
[ "WTFPL" ]
1
2020-11-11T20:05:19.000Z
2020-11-11T20:05:19.000Z
lkCommon/include/lkCommon/Utils/StaticStack.hpp
lookeypl/lkCommon
efd08396f2b151a320e103bd8111b745246b44e8
[ "WTFPL" ]
null
null
null
lkCommon/include/lkCommon/Utils/StaticStack.hpp
lookeypl/lkCommon
efd08396f2b151a320e103bd8111b745246b44e8
[ "WTFPL" ]
null
null
null
#pragma once #define _LKCOMMON_UTILS_STATIC_STACK_HPP_ #include "lkCommon/lkCommon.hpp" #include <stddef.h> namespace lkCommon { namespace Utils { /** * A lightweight LIFO stack implementation with zero dynamic allocations. * * @warning For performance, this stack does not perform any checks on * Release code. All error checks are done with asserts. */ template <typename T, size_t N> class StaticStack { T mStack[N]; size_t mStackPointer; public: /** * Constructs and initializes stack. */ StaticStack(); /** * Default destructor. */ ~StaticStack() = default; /** * Push existing element on top of stack. * * @p[in] element Element to be pushed on top of stack. * * @note Exceptional situations (like exceeding stack's size) are detected * only with debug assertions. */ void Push(const T& element); /** * Construct in-place element on top of stack. * * @p[in] args Arguments passed to element's constructor. * * @note Exceptional situations (like exceeding stack's size) are detected * only with debug assertions. */ template <typename... Args> void Emplace(Args&&... args); /** * Get stack element on top. * * @return Top element from stack. Element is considered as non-existent * on stack after this call (meaning, subsequent Push calls can * overwrite it). * * @note Popping on an empty stack is detected with assertion only in Debug * build. */ T Pop(); /** * Acquire stack's max possible size. */ constexpr size_t Capacity() const { return N; } /** * Acquire amount of elements already on Stack. */ LKCOMMON_INLINE size_t Size() const { return mStackPointer; } }; } // namespace Utils } // namespace lkCommon #include "StaticStackImpl.hpp"
22.340909
79
0.614954
lookeypl
3c30881f3aad26bed6c86ade953ddee0fd8b2a95
2,248
cc
C++
onnxruntime/core/language_interop_ops/torch/refcount_tracker.cc
photoszzt/onnxruntime
523db6ef443b0a41de1401004ae4b394dad3314c
[ "MIT" ]
1
2022-03-08T05:02:44.000Z
2022-03-08T05:02:44.000Z
onnxruntime/core/language_interop_ops/torch/refcount_tracker.cc
photoszzt/onnxruntime
523db6ef443b0a41de1401004ae4b394dad3314c
[ "MIT" ]
null
null
null
onnxruntime/core/language_interop_ops/torch/refcount_tracker.cc
photoszzt/onnxruntime
523db6ef443b0a41de1401004ae4b394dad3314c
[ "MIT" ]
1
2022-03-08T05:02:40.000Z
2022-03-08T05:02:40.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "orttraining/core/framework/torch/python_common.h" #include <iostream> #include "core/common/logging/logging.h" #include "core/language_interop_ops/torch/refcount_tracker.h" #include "core/platform/env.h" namespace onnxruntime { namespace language_interop_ops { namespace torch { void RefCountTracker::TrackPyObject(RefCountTracker::ObjCategory category, PyObject* py_obj, const std::string& log_tag) { #ifdef NDEBUG ORT_UNUSED_PARAMETER(category); ORT_UNUSED_PARAMETER(py_obj); ORT_UNUSED_PARAMETER(log_tag); #else AddressInfos& addrs = addr_info_map_[category]; assert(py_obj != NULL); void* addr = static_cast<void*>(py_obj); auto it = addrs.find(addr); if (it == addrs.end()) { addrs.insert({addr, {log_tag}}); } else { addrs[addr].push_back(log_tag); } LOGS_DEFAULT(WARNING) << "Track" << ObjCategoryToString(category) << "\tAddress: [" << addr << "]\tRefCnt: " << Py_REFCNT(addr) << "\tLogTag: " << log_tag; #endif } void RefCountTracker::DumpDetails(const std::string& phase_name) const { #ifdef NDEBUG ORT_UNUSED_PARAMETER(phase_name); #else std::ostringstream oss; oss << "======================" << phase_name << "=================" << std::endl; for (auto addr_info_it = addr_info_map_.begin(); addr_info_it != addr_info_map_.end(); ++addr_info_it) { oss << "Category: " << ObjCategoryToString(addr_info_it->first) << std::endl; for (auto it = addr_info_it->second.begin(); it != addr_info_it->second.end(); ++it) { oss << "\tAddress: [" << it->first << "] \tRefCnt: " << Py_REFCNT(it->first) << " \tLogTag: ("; for (auto vit = it->second.begin(); vit != it->second.end(); ++vit) { oss << *vit << ","; } oss << ")\n"; } } oss << "==========================================================" << std::endl; LOGS_DEFAULT(WARNING) << oss.str(); #endif } void RefCountTracker::Reset() { #ifndef NDEBUG for (auto addr_info_it = addr_info_map_.begin(); addr_info_it != addr_info_map_.end(); ++addr_info_it) { addr_info_it->second.clear(); } #endif } } // namespace torch } // namespace language_interop_ops } // namespace onnxruntime
34.060606
157
0.645463
photoszzt
3c31a7333ef325b2160eee5fec0ba91d676f1ed5
1,359
cpp
C++
uva.onlinejudge.org/MagicNumbers.cpp
facug91/OJ-Solutions
9aa55be066ce5596e4e64737c28cd3ff84e092fe
[ "Apache-2.0" ]
6
2016-09-10T03:16:34.000Z
2020-04-07T14:45:32.000Z
uva.onlinejudge.org/MagicNumbers.cpp
facug91/OJ-Solutions
9aa55be066ce5596e4e64737c28cd3ff84e092fe
[ "Apache-2.0" ]
null
null
null
uva.onlinejudge.org/MagicNumbers.cpp
facug91/OJ-Solutions
9aa55be066ce5596e4e64737c28cd3ff84e092fe
[ "Apache-2.0" ]
2
2018-08-11T20:55:35.000Z
2020-01-15T23:23:11.000Z
/* By: facug91 From: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=412 Name: Magic Numbers Date: 08/03/2016 */ #include <bits/stdc++.h> #define endl "\n" #define EPS 1e-9 #define MP make_pair #define F first #define S second #define DB(x) cerr << " #" << (#x) << ": " << (x) #define DBL(x) cerr << " #" << (#x) << ": " << (x) << endl const double PI = acos(-1.0); #define INF 1000000000 //#define MOD 1000000007ll //#define MAXN 1000005 using namespace std; typedef long long ll; typedef unsigned long long llu; typedef pair<int, int> ii; typedef pair<ii, ii> iiii; typedef vector<int> vi; typedef vector<ii> vii; typedef vector<iiii> viiii; ll n, m; bool use[10]; bool noRepetitions (ll n) { memset(use, 0, sizeof use); while (n) { if (use[n%10]) return false; use[n%10] = true; n /= 10; } return true; } int main () { #ifdef ONLINE_JUDGE ios_base::sync_with_stdio(0); cin.tie(0); #endif //cout<<fixed<<setprecision(3); //cerr<<fixed<<setprecision(3); //cin.ignore(INT_MAX, ' '); //cout << setfill('0') << setw(5) int tc = 1, i, j; cin>>tc; while (tc--) { cin>>n; m = 1ll; while (n * m <= 10000000000ll) { if (noRepetitions(m) && noRepetitions(m*n)) cout<<n * m<<" / "<<m<<" = "<<n<<endl; m++; } if (tc) cout<<endl; } return 0; }
22.278689
126
0.604121
facug91
3c367342b0ae3cec2e0d19dc53bc66c2d47489e8
440
cpp
C++
src/tibb/src/TabbedScene.cpp
ssaracut/titanium_mobile_blackberry
952a8100086dcc625584e33abc2dc03340cbb219
[ "Apache-2.0" ]
3
2015-03-07T15:41:18.000Z
2015-11-05T05:07:45.000Z
src/tibb/src/TabbedScene.cpp
ssaracut/titanium_mobile_blackberry
952a8100086dcc625584e33abc2dc03340cbb219
[ "Apache-2.0" ]
1
2015-04-12T11:50:33.000Z
2015-04-12T21:13:19.000Z
src/tibb/src/TabbedScene.cpp
ssaracut/titanium_mobile_blackberry
952a8100086dcc625584e33abc2dc03340cbb219
[ "Apache-2.0" ]
5
2015-01-13T17:14:41.000Z
2015-05-25T16:54:26.000Z
/** * Appcelerator Titanium Mobile * Copyright (c) 2012-2013 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ #include "TabbedScene.h" #include <bb/cascades/TabbedPane> using namespace bb::cascades; namespace titanium { TabbedScene::TabbedScene() : Scene(new TabbedPane()) { } } // namespace titanium
20
70
0.736364
ssaracut
3c3b84b33eb21b9907e828c0780fc54e40a10b95
3,853
cpp
C++
hardware/aw/lib/libcapture/buffer_allocator.cpp
ghsecuritylab/Android-7.0
e65af741a5cd5ac6e49e8735b00b456d00f6c0d0
[ "MIT" ]
10
2020-04-17T04:02:36.000Z
2021-11-23T11:38:42.000Z
hardware/aw/lib/libcapture/buffer_allocator.cpp
ghsecuritylab/Android-7.0
e65af741a5cd5ac6e49e8735b00b456d00f6c0d0
[ "MIT" ]
3
2020-02-19T16:53:25.000Z
2021-04-29T07:28:40.000Z
hardware/aw/lib/libcapture/buffer_allocator.cpp
ghsecuritylab/Android-7.0
e65af741a5cd5ac6e49e8735b00b456d00f6c0d0
[ "MIT" ]
5
2019-12-25T04:05:02.000Z
2022-01-14T16:57:55.000Z
/* * sunxi DE2.0 Write-Back utils library * -- Physically contiguous memory allocator interface * * Copyright (C) 2015-2018 AllwinnerTech, Inc. * * Contacts: * Zeng.Yajian <zengyajian@allwinnertech.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. */ #include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/ioctl.h> #include <unistd.h> #include <linux/ion.h> #include <ion/ion.h> #include "log.h" #include "hwc_capture.h" #define ION_ALLOC_ALIGN (1024 * 4) #define DEV_NAME "/dev/ion" struct ion_allocator { struct buffer_allocator interface; int fd; int ref; }; struct buffer_node { struct buffer_handle handle; ion_user_handle_t ion_handle; #ifdef _WRITE_BACK_DEBUG_ unsigned char *vir_address; int mapfd; #endif }; static struct buffer_handle * __buffer_alloc( struct buffer_allocator *allocator, int format, int width, int height); static int __buffer_free(struct buffer_allocator *allocator, struct buffer_handle *handle); struct buffer_allocator * buffer_allocator_initial(void) { int fd = ion_open(); if (fd < 0) { logerr("ion open error!\n"); return NULL; } struct ion_allocator *allocator = (struct ion_allocator *)malloc(sizeof(struct ion_allocator)); if (!allocator) { close(fd); return NULL; } allocator->fd = fd; allocator->ref = 0; allocator->interface.alloc = __buffer_alloc; allocator->interface.free = __buffer_free; return &(allocator->interface); } int buffer_allocator_destroy(struct buffer_allocator *allocator) { struct ion_allocator *alloc = (struct ion_allocator *)allocator; if (!alloc || alloc->ref) { loginfo("%s: null or reference error, cant't destroy buffer allocator\n", __func__); return -1; } ion_close(alloc->fd); free(alloc); return 0; } static struct buffer_handle * __buffer_alloc(struct buffer_allocator *allocator, int format, int width, int height) { int retval; int size = width * height * 4; struct ion_allocator *alloc = (struct ion_allocator *)allocator; struct buffer_node *node = (struct buffer_node *)malloc(sizeof(struct buffer_node)); if (!alloc || (size <= 0) || !node) return NULL; #ifndef IOMMU_ENABLE /* ION_HEAP_CARVEOUT_MASK is not support in suni50w2p1 platform */ retval = ion_alloc(alloc->fd, size, ION_ALLOC_ALIGN, ION_HEAP_TYPE_DMA_MASK, 0, &node->ion_handle); #else retval = ion_alloc(alloc->fd, size, ION_ALLOC_ALIGN, ION_HEAP_SYSTEM_MASK, 0, &node->ion_handle); #endif if (retval) { logerr("ion alloc failed, size %d\n", size); free(node); return NULL; } alloc->ref++; node->handle.size = size; #ifdef IOMMU_ENABLE /* int ion_share(int fd, ion_user_handle_t handle, int *share_fd) */ ion_share(alloc->fd, node->ion_handle, &node->handle.fd); #else node->handle.phy_address = ion_getphyadr(alloc->fd, node->ion_handle); #endif #ifdef _WRITE_BACK_DEBUG_ unsigned char *ptr; int map_fd = -1; retval = ion_map(alloc->fd, node->ion_handle, size, PROT_READ | PROT_WRITE, MAP_SHARED, 0, &ptr, &map_fd); if (retval != 0) { logerr("ion map failed, '%s'\n", strerror(errno)); goto __out; } node->vir_address = ptr; node->mapfd = map_fd; __out: #endif return &(node->handle); } static int __buffer_free(struct buffer_allocator *allocator, struct buffer_handle *handle) { struct ion_allocator *alloc = (struct ion_allocator *)allocator; struct buffer_node *node = (struct buffer_node *)handle; if (!alloc || !node) return -1; alloc->ref--; close(handle->fd); ion_free(alloc->fd, node->ion_handle); #ifdef _WRITE_BACK_DEBUG_ munmap(node->vir_address, node->size); close(node->mapfd); #endif free(node); return 0; }
25.019481
92
0.720737
ghsecuritylab
3c426f062de1b588cf562c6fb8184caeb0d0aa15
3,238
cpp
C++
src/gui/profile_list_model.cpp
adam-currie/fannn
b8433b9cc223b98a976590796986a2b0a1e68a68
[ "MIT" ]
2
2021-10-16T01:43:03.000Z
2021-12-12T20:28:43.000Z
src/gui/profile_list_model.cpp
adam-currie/fannn
b8433b9cc223b98a976590796986a2b0a1e68a68
[ "MIT" ]
null
null
null
src/gui/profile_list_model.cpp
adam-currie/fannn
b8433b9cc223b98a976590796986a2b0a1e68a68
[ "MIT" ]
null
null
null
#include "profile_list_model.h" #include "profile_persister.h" #include <algorithm> #include <stdexcept> #include <string> #include "containers_util.h" using std::string; using Fannn::Util::contains; ProfileListModel::ProfileListModel(QObject *parent) : QAbstractListModel(parent) { auto persister = Fannn::ProfilePersister(Fannn::ProfilePersister::getActiveProfileName()); persister.load(); setCurrentProfile(new ProfileModel(this, persister)); } void ProfileListModel::setCurrentProfile(ProfileModel *value) { if(_currentProfile != value){ //todo: delete old profile model? _currentProfile = value; emit currentProfileChanged(value); loadProfileNames(); } } QVariant ProfileListModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); return QString::fromStdString(profileNames.at(index.row())); } Qt::ItemFlags ProfileListModel::flags(const QModelIndex &index) const { //todo return Qt::NoItemFlags; } int ProfileListModel::rowCount(const QModelIndex &parent) const { return profileNames.size(); } void ProfileListModel::loadProfileNames() { auto newNames = Fannn::ProfilePersister::getProfileNames(); if (_currentProfile) { //put at front //and make sure it's on the list even if not read from disk, cause we can just save it anyway string curName = _currentProfile->name().toStdString(); for (auto iter = newNames.begin(); iter != newNames.end(); ++iter) { if (*iter == curName) { newNames.erase(iter); break; } } newNames.insert(newNames.begin(), curName); } if (newNames != profileNames) { beginResetModel(); profileNames = newNames; endResetModel(); } } int ProfileListModel::indexOf(QString profileName) { for(int i=0; i<profileNames.size(); i++) if (profileNames[i] == profileName.toStdString()) return i; throw std::out_of_range("'" + profileName.toStdString() + "' not found"); } void ProfileListModel::createAndSwitchTo() { //we want this to be up to date auto latestProfileNames = Fannn::ProfilePersister::getProfileNames(); string name = "profile1"; for (int i=2; latestProfileNames>>contains(name); ++i) name = "profile" + std::to_string(i); Fannn::ProfilePersister pp(name); pp.save(); //need to mark our territory setCurrentProfile(new ProfileModel(this, pp)); } void ProfileListModel::loadProfile(QString name) { Fannn::ProfilePersister persister(name.toStdString()); persister.load();//todo: LoadError setCurrentProfile(new ProfileModel(this, persister)); } void ProfileListModel::setActiveProfileName(QString profileName) { string newName = profileName.toStdString(); string oldName = Fannn::ProfilePersister::getActiveProfileName(); if (newName != oldName) { Fannn::ProfilePersister::setActiveProfileName(newName); emit activeProfileNameChanged(QString::fromStdString(newName)); } } QString ProfileListModel::activeProfileName() const { return QString::fromStdString(Fannn::ProfilePersister::getActiveProfileName()); }
31.436893
101
0.684064
adam-currie
3c43bf70da25fd81b8ba016b6ce73a5c16e7f0d8
19,774
cxx
C++
resip/recon/UserAgent.cxx
dulton/reSipServer
ac4241df81c1e3eef2e678271ffef4dda1fc6747
[ "Apache-2.0" ]
1
2019-04-15T14:10:58.000Z
2019-04-15T14:10:58.000Z
resip/recon/UserAgent.cxx
dulton/reSipServer
ac4241df81c1e3eef2e678271ffef4dda1fc6747
[ "Apache-2.0" ]
null
null
null
resip/recon/UserAgent.cxx
dulton/reSipServer
ac4241df81c1e3eef2e678271ffef4dda1fc6747
[ "Apache-2.0" ]
2
2019-10-31T09:11:09.000Z
2021-09-17T01:00:49.000Z
#ifdef HAVE_CONFIG_H #include "config.h" #endif #include "UserAgent.hxx" #include "UserAgentDialogSetFactory.hxx" #include "UserAgentCmds.hxx" #include "UserAgentServerAuthManager.hxx" #include "UserAgentClientSubscription.hxx" #include "UserAgentRegistration.hxx" #include "ReconSubsystem.hxx" #include "reflow/FlowManagerSubsystem.hxx" #include <reTurn/ReTurnSubsystem.hxx> #include <rutil/Log.hxx> #include <rutil/Logger.hxx> #include <resip/dum/ClientAuthManager.hxx> #include <resip/dum/ClientSubscription.hxx> #include <resip/dum/ServerSubscription.hxx> #include <resip/dum/ClientRegistration.hxx> #include <resip/dum/KeepAliveManager.hxx> #include <resip/dum/AppDialogSet.hxx> #if defined(USE_SSL) #include <resip/stack/ssl/Security.hxx> #endif #include <rutil/WinLeakCheck.hxx> using namespace recon; using namespace resip; using namespace std; #define RESIPROCATE_SUBSYSTEM ReconSubsystem::RECON UserAgent::UserAgent(ConversationManager* conversationManager, SharedPtr<UserAgentMasterProfile> profile, AfterSocketCreationFuncPtr socketFunc) : mCurrentSubscriptionHandle(1), mCurrentConversationProfileHandle(1), mDefaultOutgoingConversationProfileHandle(0), mConversationManager(conversationManager), mProfile(profile), #if defined(USE_SSL) mSecurity(new Security(profile->certPath())), #else mSecurity(0), #endif mStack(mSecurity, profile->getAdditionalDnsServers(), &mSelectInterruptor, false /* stateless */, socketFunc), mDum(mStack), mStackThread(mStack, mSelectInterruptor), mDumShutdown(false) { assert(mConversationManager); mConversationManager->setUserAgent(this); addTransports(); // Set Enum Suffixes mStack.setEnumSuffixes(profile->getEnumSuffixes()); // Enable/Disable Statistics Manager mStack.statisticsManagerEnabled() = profile->statisticsManagerEnabled(); // Install Handlers mDum.setMasterProfile(mProfile); mDum.setClientRegistrationHandler(this); mDum.setClientAuthManager(std::auto_ptr<ClientAuthManager>(new ClientAuthManager)); mDum.setKeepAliveManager(std::auto_ptr<KeepAliveManager>(new KeepAliveManager)); mDum.setRedirectHandler(mConversationManager); mDum.setInviteSessionHandler(mConversationManager); mDum.setDialogSetHandler(mConversationManager); mDum.addOutOfDialogHandler(OPTIONS, mConversationManager); mDum.addOutOfDialogHandler(REFER, mConversationManager); mDum.addClientSubscriptionHandler("refer", mConversationManager); mDum.addServerSubscriptionHandler("refer", mConversationManager); //mDum.addClientSubscriptionHandler(Symbols::Presence, this); //mDum.addClientPublicationHandler(Symbols::Presence, this); //mDum.addOutOfDialogHandler(NOTIFY, this); //mDum.addServerSubscriptionHandler("message-summary", this); // Set AppDialogSetFactory auto_ptr<AppDialogSetFactory> dsf(new UserAgentDialogSetFactory(*mConversationManager)); mDum.setAppDialogSetFactory(dsf); // Set UserAgentServerAuthManager SharedPtr<ServerAuthManager> uasAuth( new UserAgentServerAuthManager(*this)); mDum.setServerAuthManager(uasAuth); } UserAgent::~UserAgent() { shutdown(); } void UserAgent::startup() { mStackThread.run(); } SubscriptionHandle UserAgent::getNewSubscriptionHandle() { Lock lock(mSubscriptionHandleMutex); return mCurrentSubscriptionHandle++; } void UserAgent::registerSubscription(UserAgentClientSubscription *subscription) { mSubscriptions[subscription->getSubscriptionHandle()] = subscription; } void UserAgent::unregisterSubscription(UserAgentClientSubscription *subscription) { mSubscriptions.erase(subscription->getSubscriptionHandle()); } ConversationProfileHandle UserAgent::getNewConversationProfileHandle() { Lock lock(mConversationProfileHandleMutex); return mCurrentConversationProfileHandle++; } void UserAgent::registerRegistration(UserAgentRegistration *registration) { mRegistrations[registration->getConversationProfileHandle()] = registration; } void UserAgent::unregisterRegistration(UserAgentRegistration *registration) { mRegistrations.erase(registration->getConversationProfileHandle()); } void UserAgent::process(int timeoutMs) { mDum.process(timeoutMs); } void UserAgent::shutdown() { UserAgentShutdownCmd* cmd = new UserAgentShutdownCmd(this); mDum.post(cmd); // Wait for Dum to shutdown while(!mDumShutdown) { process(100); } mStackThread.shutdown(); mStackThread.join(); } void UserAgent::logDnsCache() { mStack.logDnsCache(); } void UserAgent::clearDnsCache() { mStack.clearDnsCache(); } void UserAgent::post(ApplicationMessage& message, unsigned int ms) { if(ms > 0) { mStack.postMS(message, ms, &mDum); } else { mDum.post(&message); } } void UserAgent::setLogLevel(Log::Level level, LoggingSubsystem subsystem) { switch(subsystem) { case SubsystemAll: Log::setLevel(level); break; case SubsystemContents: Log::setLevel(level, Subsystem::CONTENTS); break; case SubsystemDns: Log::setLevel(level, Subsystem::DNS); break; case SubsystemDum: Log::setLevel(level, Subsystem::DUM); break; case SubsystemSdp: Log::setLevel(level, Subsystem::SDP); break; case SubsystemSip: Log::setLevel(level, Subsystem::SIP); break; case SubsystemTransaction: Log::setLevel(level, Subsystem::TRANSACTION); break; case SubsystemTransport: Log::setLevel(level, Subsystem::TRANSPORT); break; case SubsystemStats: Log::setLevel(level, Subsystem::STATS); break; case SubsystemRecon: Log::setLevel(level, ReconSubsystem::RECON); break; case SubsystemFlowManager: Log::setLevel(level, FlowManagerSubsystem::FLOWMANAGER); break; case SubsystemReTurn: Log::setLevel(level, ReTurnSubsystem::RETURN); break; } } ConversationProfileHandle UserAgent::addConversationProfile(SharedPtr<ConversationProfile> conversationProfile, bool defaultOutgoing) { ConversationProfileHandle handle = getNewConversationProfileHandle(); AddConversationProfileCmd* cmd = new AddConversationProfileCmd(this, handle, conversationProfile, defaultOutgoing); mDum.post(cmd); return handle; } void UserAgent::setDefaultOutgoingConversationProfile(ConversationProfileHandle handle) { SetDefaultOutgoingConversationProfileCmd* cmd = new SetDefaultOutgoingConversationProfileCmd(this, handle); mDum.post(cmd); } void UserAgent::destroyConversationProfile(ConversationProfileHandle handle) { DestroyConversationProfileCmd* cmd = new DestroyConversationProfileCmd(this, handle); mDum.post(cmd); } SubscriptionHandle UserAgent::createSubscription(const Data& eventType, const NameAddr& target, unsigned int subscriptionTime, const Mime& mimeType) { SubscriptionHandle handle = getNewSubscriptionHandle(); CreateSubscriptionCmd* cmd = new CreateSubscriptionCmd(this, handle, eventType, target, subscriptionTime, mimeType); mDum.post(cmd); return handle; } void UserAgent::destroySubscription(SubscriptionHandle handle) { DestroySubscriptionCmd* cmd = new DestroySubscriptionCmd(this, handle); mDum.post(cmd); } SharedPtr<ConversationProfile> UserAgent::getDefaultOutgoingConversationProfile() { if(mDefaultOutgoingConversationProfileHandle != 0) { return mConversationProfiles[mDefaultOutgoingConversationProfileHandle]; } else { assert(false); ErrLog( << "getDefaultOutgoingConversationProfile: something is wrong - no profiles to return"); return SharedPtr<ConversationProfile>((ConversationProfile*)0); } } SharedPtr<ConversationProfile> UserAgent::getIncomingConversationProfile(const SipMessage& msg) { assert(msg.isRequest()); // Examine the sip message, and select the most appropriate conversation profile // Check if request uri matches registration contact const Uri& requestUri = msg.header(h_RequestLine).uri(); RegistrationMap::iterator regIt; for(regIt = mRegistrations.begin(); regIt != mRegistrations.end(); regIt++) { const NameAddrs& contacts = regIt->second->getContactAddresses(); NameAddrs::const_iterator naIt; for(naIt = contacts.begin(); naIt != contacts.end(); naIt++) { InfoLog( << "getIncomingConversationProfile: comparing requestUri=" << requestUri << " to contactUri=" << (*naIt).uri()); if((*naIt).uri() == requestUri) { ConversationProfileMap::iterator conIt = mConversationProfiles.find(regIt->first); if(conIt != mConversationProfiles.end()) { return conIt->second; } } } } // Check if To header matches default from Data toAor = msg.header(h_To).uri().getAor(); ConversationProfileMap::iterator conIt; for(conIt = mConversationProfiles.begin(); conIt != mConversationProfiles.end(); conIt++) { InfoLog( << "getIncomingConversationProfile: comparing toAor=" << toAor << " to defaultFromAor=" << conIt->second->getDefaultFrom().uri().getAor()); if(isEqualNoCase(toAor, conIt->second->getDefaultFrom().uri().getAor())) { return conIt->second; } } // If can't find any matches, then return the default outgoing profile InfoLog( << "getIncomingConversationProfile: no matching profile found, falling back to default outgoing profile"); return getDefaultOutgoingConversationProfile(); } SharedPtr<UserAgentMasterProfile> UserAgent::getUserAgentMasterProfile() { return mProfile; } DialogUsageManager& UserAgent::getDialogUsageManager() { return mDum; } ConversationManager* UserAgent::getConversationManager() { return mConversationManager; } void UserAgent::onDumCanBeDeleted() { mDumShutdown = true; } void UserAgent::addTransports() { const std::vector<UserAgentMasterProfile::TransportInfo>& transports = mProfile->getTransports(); std::vector<UserAgentMasterProfile::TransportInfo>::const_iterator i; for(i = transports.begin(); i != transports.end(); i++) { try { switch((*i).mProtocol) { #ifdef USE_SSL case TLS: #ifdef USE_DTLS case DTLS: #endif mDum.addTransport((*i).mProtocol, (*i).mPort, (*i).mIPVersion, (*i).mIPInterface, (*i).mSipDomainname, Data::Empty, (*i).mSslType); break; #endif case UDP: case TCP: mDum.addTransport((*i).mProtocol, (*i).mPort, (*i).mIPVersion, (*i).mIPInterface); break; default: WarningLog (<< "Failed to add " << Tuple::toData((*i).mProtocol) << " transport - unsupported type"); } } catch (BaseException& e) { WarningLog (<< "Caught: " << e); WarningLog (<< "Failed to add " << Tuple::toData((*i).mProtocol) << " transport on " << (*i).mPort); } } } void UserAgent::startApplicationTimer(unsigned int timerId, unsigned int durationMs, unsigned int seqNumber) { UserAgentTimeout t(*this, timerId, durationMs, seqNumber); post(t, durationMs); } void UserAgent::onApplicationTimer(unsigned int timerId, unsigned int durationMs, unsigned int seqNumber) { // Default implementation is to do nothing - application should override this } void UserAgent::onSubscriptionTerminated(SubscriptionHandle handle, unsigned int statusCode) { // Default implementation is to do nothing - application should override this } void UserAgent::onSubscriptionNotify(SubscriptionHandle handle, const Data& notifyData) { // Default implementation is to do nothing - application should override this } void UserAgent::shutdownImpl() { mDum.shutdown(this); // End all subscriptions SubscriptionMap tempSubs = mSubscriptions; // Create copy for safety, since ending Subscriptions can immediately remove themselves from map SubscriptionMap::iterator i; for(i = tempSubs.begin(); i != tempSubs.end(); i++) { i->second->end(); } // Unregister all registrations RegistrationMap tempRegs = mRegistrations; // Create copy for safety, since ending can immediately remove themselves from map RegistrationMap::iterator j; for(j = tempRegs.begin(); j != tempRegs.end(); j++) { j->second->end(); } mConversationManager->shutdown(); } void UserAgent::addConversationProfileImpl(ConversationProfileHandle handle, SharedPtr<ConversationProfile> conversationProfile, bool defaultOutgoing) { // Store new profile mConversationProfiles[handle] = conversationProfile; conversationProfile->setHandle(handle); #ifdef USE_SSL // If this is the first profile ever set - then use the aor defined in it as the aor used in // the DTLS certificate for the DtlsFactory - TODO - improve this sometime so that we can change the aor in // the cert at runtime to equal the aor in the default conversation profile if(!mDefaultOutgoingConversationProfileHandle) { mConversationManager->getFlowManager().initializeDtlsFactory(conversationProfile->getDefaultFrom().uri().getAor().c_str()); } #endif // Set the default outgoing if requested to do so, or we don't have one yet if(defaultOutgoing || mDefaultOutgoingConversationProfileHandle == 0) { setDefaultOutgoingConversationProfileImpl(handle); } // Register new profile if(conversationProfile->getDefaultRegistrationTime() != 0) { UserAgentRegistration *registration = new UserAgentRegistration(*this, mDum, handle); mDum.send(mDum.makeRegistration(conversationProfile->getDefaultFrom(), conversationProfile, registration)); } } void UserAgent::setDefaultOutgoingConversationProfileImpl(ConversationProfileHandle handle) { mDefaultOutgoingConversationProfileHandle = handle; } void UserAgent::destroyConversationProfileImpl(ConversationProfileHandle handle) { // Remove matching registration if found RegistrationMap::iterator it = mRegistrations.find(handle); if(it != mRegistrations.end()) { it->second->end(); } // Remove from ConversationProfile map mConversationProfiles.erase(handle); // If this Conversation Profile was the default - select the first item in the map as the new default if(handle == mDefaultOutgoingConversationProfileHandle) { ConversationProfileMap::iterator it = mConversationProfiles.begin(); if(it != mConversationProfiles.end()) { setDefaultOutgoingConversationProfileImpl(it->first); } else { setDefaultOutgoingConversationProfileImpl(0); } } } void UserAgent::createSubscriptionImpl(SubscriptionHandle handle, const Data& eventType, const NameAddr& target, unsigned int subscriptionTime, const Mime& mimeType) { // Ensure we have a client subscription handler for this event type if(!mDum.getClientSubscriptionHandler(eventType)) { mDum.addClientSubscriptionHandler(eventType, this); } // Ensure that the request Mime type is supported in the dum profile if(!mProfile->isMimeTypeSupported(NOTIFY, mimeType)) { mProfile->addSupportedMimeType(NOTIFY, mimeType); } UserAgentClientSubscription *subscription = new UserAgentClientSubscription(*this, mDum, handle); mDum.send(mDum.makeSubscription(target, getDefaultOutgoingConversationProfile(), eventType, subscriptionTime, subscription)); } void UserAgent::destroySubscriptionImpl(SubscriptionHandle handle) { SubscriptionMap::iterator it = mSubscriptions.find(handle); if(it != mSubscriptions.end()) { it->second->end(); } } //////////////////////////////////////////////////////////////////////////////// // Registration Handler //////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// void UserAgent::onSuccess(ClientRegistrationHandle h, const SipMessage& msg) { dynamic_cast<UserAgentRegistration *>(h->getAppDialogSet().get())->onSuccess(h, msg); } void UserAgent::onFailure(ClientRegistrationHandle h, const SipMessage& msg) { dynamic_cast<UserAgentRegistration *>(h->getAppDialogSet().get())->onFailure(h, msg); } void UserAgent::onRemoved(ClientRegistrationHandle h, const SipMessage&msg) { dynamic_cast<UserAgentRegistration *>(h->getAppDialogSet().get())->onRemoved(h, msg); } int UserAgent::onRequestRetry(ClientRegistrationHandle h, int retryMinimum, const SipMessage& msg) { return dynamic_cast<UserAgentRegistration *>(h->getAppDialogSet().get())->onRequestRetry(h, retryMinimum, msg); } //////////////////////////////////////////////////////////////////////////////// // ClientSubscriptionHandler /////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// void UserAgent::onUpdatePending(ClientSubscriptionHandle h, const SipMessage& msg, bool outOfOrder) { dynamic_cast<UserAgentClientSubscription *>(h->getAppDialogSet().get())->onUpdatePending(h, msg, outOfOrder); } void UserAgent::onUpdateActive(ClientSubscriptionHandle h, const SipMessage& msg, bool outOfOrder) { dynamic_cast<UserAgentClientSubscription *>(h->getAppDialogSet().get())->onUpdateActive(h, msg, outOfOrder); } void UserAgent::onUpdateExtension(ClientSubscriptionHandle h, const SipMessage& msg, bool outOfOrder) { dynamic_cast<UserAgentClientSubscription *>(h->getAppDialogSet().get())->onUpdateExtension(h, msg, outOfOrder); } void UserAgent::onTerminated(ClientSubscriptionHandle h, const SipMessage* msg) { dynamic_cast<UserAgentClientSubscription *>(h->getAppDialogSet().get())->onTerminated(h, msg); } void UserAgent::onNewSubscription(ClientSubscriptionHandle h, const SipMessage& msg) { dynamic_cast<UserAgentClientSubscription *>(h->getAppDialogSet().get())->onNewSubscription(h, msg); } int UserAgent::onRequestRetry(ClientSubscriptionHandle h, int retryMinimum, const SipMessage& msg) { return dynamic_cast<UserAgentClientSubscription *>(h->getAppDialogSet().get())->onRequestRetry(h, retryMinimum, msg); } /* ==================================================================== Copyright (c) 2007-2008, Plantronics, 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. 3. Neither the name of Plantronics 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. ==================================================================== */
31.337559
160
0.720239
dulton
3c44dad3e7d587cb64e9ea95f0df343b6e50e1ff
1,499
hpp
C++
libraries/chain/include/ngk/chain/webassembly/ngk-vm-oc/ngk-vm-oc.hpp
tianhao13/ngkchain
25d59f3161dd85c8cf9b4ce4bd210bd859deca05
[ "MIT" ]
4
2020-10-21T02:26:35.000Z
2021-02-14T13:15:18.000Z
libraries/chain/include/ngk/chain/webassembly/ngk-vm-oc/ngk-vm-oc.hpp
tianhao13/ngkchain
25d59f3161dd85c8cf9b4ce4bd210bd859deca05
[ "MIT" ]
null
null
null
libraries/chain/include/ngk/chain/webassembly/ngk-vm-oc/ngk-vm-oc.hpp
tianhao13/ngkchain
25d59f3161dd85c8cf9b4ce4bd210bd859deca05
[ "MIT" ]
4
2020-11-02T11:25:56.000Z
2021-01-22T14:12:22.000Z
#pragma once #include <ngk/chain/types.hpp> #include <ngk/chain/webassembly/ngk-vm-oc/ngk-vm-oc.h> #include <exception> #include <stdint.h> #include <stddef.h> #include <setjmp.h> #include <vector> #include <list> namespace ngk { namespace chain { class apply_context; namespace ngkvmoc { using control_block = ngk_vm_oc_control_block; struct no_offset{}; struct code_offset{ size_t offset; }; //relative to code_begin struct intrinsic_ordinal{ size_t ordinal; }; using ngkvmoc_optional_offset_or_import_t = fc::static_variant<no_offset, code_offset, intrinsic_ordinal>; struct code_descriptor { digest_type code_hash; uint8_t vm_version; uint8_t codegen_version; size_t code_begin; ngkvmoc_optional_offset_or_import_t start; unsigned apply_offset; int starting_memory_pages; size_t initdata_begin; unsigned initdata_size; unsigned initdata_prologue_size; }; enum ngkvmoc_exitcode : int { NGKVMOC_EXIT_CLEAN_EXIT = 1, NGKVMOC_EXIT_CHECKTIME_FAIL, NGKVMOC_EXIT_SEGV, NGKVMOC_EXIT_EXCEPTION }; }}} FC_REFLECT(ngk::chain::ngkvmoc::no_offset, ); FC_REFLECT(ngk::chain::ngkvmoc::code_offset, (offset)); FC_REFLECT(ngk::chain::ngkvmoc::intrinsic_ordinal, (ordinal)); FC_REFLECT(ngk::chain::ngkvmoc::code_descriptor, (code_hash)(vm_version)(codegen_version)(code_begin)(start)(apply_offset)(starting_memory_pages)(initdata_begin)(initdata_size)(initdata_prologue_size)); #define NGKVMOC_INTRINSIC_INIT_PRIORITY __attribute__((init_priority(198)))
26.767857
202
0.784523
tianhao13
3c47704ffffe4ef4c955177924b541d952ea6157
46,864
cpp
C++
src/updater.cpp
smarttowel/AppImageUpdate
ac5376d70e55bb9d4684a5bede555f0bbcbfb249
[ "MIT" ]
null
null
null
src/updater.cpp
smarttowel/AppImageUpdate
ac5376d70e55bb9d4684a5bede555f0bbcbfb249
[ "MIT" ]
null
null
null
src/updater.cpp
smarttowel/AppImageUpdate
ac5376d70e55bb9d4684a5bede555f0bbcbfb249
[ "MIT" ]
null
null
null
// system headers+ #include <algorithm> #include <chrono> #include <deque> #include <fnmatch.h> #include <fstream> #include <iostream> #include <libgen.h> #include <mutex> #include <sstream> #include <thread> #include <unistd.h> // library headers #include <zsclient.h> #include <hashlib/sha256.h> #include <cpr/cpr.h> #include <ftw.h> // local headers #include "appimage/update.h" #include "util.h" #include "update_methods/pling_v1_zsync.h" // convenience declaration typedef std::lock_guard<std::mutex> lock_guard; namespace appimage { namespace update { class Updater::Private { public: Private() : state(INITIALIZED), pathToAppImage(), zSyncClient(nullptr), thread(nullptr), mutex(), overwrite(false) {}; ~Private() { delete zSyncClient; } public: // data std::string pathToAppImage; // state State state; // ZSync client -- will be instantiated only if necessary zsync2::ZSyncClient* zSyncClient; // threading std::thread* thread; std::mutex mutex; // status messages std::deque<std::string> statusMessages; // defines whether to overwrite original file bool overwrite; public: enum UpdateInformationType { INVALID = -1, ZSYNC_GENERIC = 0, ZSYNC_GITHUB_RELEASES, ZSYNC_BINTRAY, ZSYNC_PLING_V1, }; struct AppImage { std::string filename; int appImageVersion; std::string rawUpdateInformation; UpdateInformationType updateInformationType; std::string zsyncUrl; std::string signature; AppImage() : appImageVersion(-1), updateInformationType(INVALID) {}; }; typedef struct AppImage AppImage; public: void issueStatusMessage(const std::string& message) { statusMessages.push_back(message); } static const std::string readAppImageSignature(const std::string& pathToAppImage) { return readElfSection(pathToAppImage, ".sha256_sig"); } static const std::string hashAppImage(const std::string& pathToAppImage) { // read offset and length of signature section to skip it later unsigned long sigOffset = 0, sigLength = 0; unsigned long keyOffset = 0, keyLength = 0; if (!appimage_get_elf_section_offset_and_length(pathToAppImage.c_str(), ".sha256_sig", &sigOffset, &sigLength)) return ""; if (!appimage_get_elf_section_offset_and_length(pathToAppImage.c_str(), ".sig_key", &keyOffset, &keyLength)) return ""; std::ifstream ifs(pathToAppImage); if (!ifs) return ""; SHA256 digest; // validate.c uses "offset" as chunk size, but that value might be quite high, and therefore uses // a lot of memory // TODO: use a smaller value (maybe use a prime factorization and use the biggest prime factor?) const ssize_t chunkSize = 4096; std::vector<char> buffer(chunkSize, 0); ssize_t totalBytesRead = 0; // bytes that should be skipped when reading the next chunk // when e.g., a section that must be ignored spans over more than one chunk, this amount of bytes is // being nulled & skipped before reading data from the file again std::streamsize bytesToSkip = 0; ifs.seekg(0, ifs.end); const ssize_t fileSize = ifs.tellg(); ifs.seekg(0, ifs.beg); while (ifs) { ssize_t bytesRead = 0; auto bytesLeftInChunk = std::min(chunkSize, (fileSize - totalBytesRead)); if (bytesLeftInChunk <= 0) break; auto skipBytes = [&bytesRead, &bytesLeftInChunk, &buffer, &ifs, &totalBytesRead](ssize_t count) { if (count <= 0) return; const auto start = buffer.begin() + bytesRead; std::fill_n(start, count, '\0'); bytesRead += count; totalBytesRead += count; bytesLeftInChunk -= count; ifs.seekg(count, std::ios::cur); }; auto readBytes = [&bytesRead, &bytesLeftInChunk, &buffer, &ifs, &totalBytesRead](ssize_t count) { if (count <= 0) return; ifs.read(buffer.data() + bytesRead, count); bytesRead += ifs.gcount(); totalBytesRead += count; bytesLeftInChunk -= bytesRead; }; auto checkSkipSection = [&](const ssize_t sectionOffset, const ssize_t sectionLength) { // check whether signature starts in current chunk const ssize_t sectionOffsetDelta = sectionOffset - totalBytesRead; if (sectionOffsetDelta >= 0 && sectionOffsetDelta < bytesLeftInChunk) { // read until section begins readBytes(sectionOffsetDelta); // calculate how many bytes must be nulled in this chunk // the rest will be nulled in the following chunk(s) auto bytesLeft = sectionLength; const auto bytesToNullInCurrentChunk = std::min(bytesLeftInChunk, bytesLeft); // null these bytes skipBytes(bytesToNullInCurrentChunk); // calculate how many bytes must be nulled in future chunks bytesLeft -= bytesToNullInCurrentChunk; bytesToSkip = bytesLeft; } }; // check whether bytes must be skipped from previous sections if (bytesToSkip > 0) { auto bytesToSkipInCurrentChunk = std::min(chunkSize, bytesToSkip); skipBytes(bytesToSkipInCurrentChunk); bytesToSkip -= bytesToSkipInCurrentChunk; } // check whether one of the sections that must be skipped are in the current chunk, and if they // are, skip those sections in the current and future sections checkSkipSection(sigOffset, sigLength); checkSkipSection(keyOffset, keyLength); // read remaining bytes in chunk, given the file has still data to be read if (ifs && bytesLeftInChunk > 0) { readBytes(bytesLeftInChunk); } // update hash with data from buffer digest.add(buffer.data(), static_cast<size_t>(bytesRead)); } return digest.getHash(); } const AppImage* readAppImage(const std::string& pathToAppImage) { // error state: empty AppImage path if (pathToAppImage.empty()) { issueStatusMessage("Path to AppImage must not be empty."); return nullptr; } // check whether file exists std::ifstream ifs(pathToAppImage); // if file can't be opened, it's an error if (!ifs || !ifs.good()) { issueStatusMessage("Failed to access AppImage file: " + pathToAppImage); return nullptr; } // read magic number ifs.seekg(8, std::ios::beg); std::vector<char> magicByte(4, '\0'); ifs.read(magicByte.data(), 3); // validate first two bytes are A and I if (magicByte[0] != 'A' && magicByte[1] != 'I') { std::ostringstream oss; oss << "Invalid magic bytes: " << (int) magicByte[0] << (int) magicByte[1]; issueStatusMessage(oss.str()); } int appImageType = -1; // the third byte contains the version switch (magicByte[2]) { case '\x01': appImageType = 1; break; case '\x02': appImageType = 2; break; default: // see fallback in the final else block in the next if construct break; } // read update information in the file std::string updateInformation; // also read signature in the file std::string signature; if (appImageType == 1) { // update information is always at the same position, and has a fixed length static constexpr auto position = 0x8373; static constexpr auto length = 512; ifs.seekg(position); std::vector<char> rawUpdateInformation(length, 0); ifs.read(rawUpdateInformation.data(), length); updateInformation = rawUpdateInformation.data(); } else if (appImageType == 2) { // try to read ELF section .upd_info updateInformation = readElfSection(pathToAppImage, ".upd_info"); // type 2 supports signatures, so we can extract it here, too signature = readAppImageSignature(pathToAppImage); } else { // final try: type 1 AppImages do not have to set the magic bytes, although they should // if the file is both an ELF and an ISO9660 file, we'll suspect it to be a type 1 AppImage, and // proceed with a warning static constexpr int elfMagicPos = 1; static const std::string elfMagicValue = "ELF"; static constexpr int isoMagicPos = 32769; static const std::string isoMagicValue = "CD001"; ifs.seekg(elfMagicPos); std::vector<char> elfMagicPosData(elfMagicValue.size() + 1, '\0'); ifs.read(elfMagicPosData.data(), elfMagicValue.size()); auto elfMagicAvailable = (elfMagicPosData.data() == elfMagicValue); ifs.seekg(isoMagicPos); std::vector<char> isoMagicPosData(isoMagicValue.size() + 1, '\0'); ifs.read(isoMagicPosData.data(), isoMagicValue.size()); auto isoMagicAvailable = (isoMagicPosData.data() == isoMagicValue); if (isoMagicAvailable) { issueStatusMessage("Guessing AppImage type 1 or ISO"); appImageType = 1; } else { // all possible methods attempted, ultimately fail here issueStatusMessage("No such AppImage type: " + std::to_string(magicByte[2])); return nullptr; } } UpdateInformationType uiType = INVALID; std::string zsyncUrl; // parse update information auto uiParts = split(updateInformation, '|'); // make sure uiParts isn't empty if (!uiParts.empty()) { // TODO: GitHub releases type should consider pre-releases when there's no other types of releases if (uiParts[0] == "gh-releases-zsync") { // validate update information if (uiParts.size() != 5) { std::ostringstream oss; oss << "Update information has invalid parameter count. Please contact the author of " << "the AppImage and ask them to revise the update information. They should consult " << "the AppImage specification, there might have been changes to the update" << "information."; issueStatusMessage(oss.str()); } else { uiType = ZSYNC_GITHUB_RELEASES; auto username = uiParts[1]; auto repository = uiParts[2]; auto tag = uiParts[3]; auto filename = uiParts[4]; std::stringstream url; url << "https://api.github.com/repos/" << username << "/" << repository << "/releases/"; if (tag.find("latest") != std::string::npos) { issueStatusMessage("Fetching latest release information from GitHub API"); url << "latest"; } else { std::ostringstream oss; oss << "Fetching release information for tag \"" << tag << "\" from GitHub API."; issueStatusMessage(oss.str()); url << "tags/" << tag; } auto response = cpr::Get(url.str()); // counter that will be evaluated later to give some meaningful feedback why parsing API // response might have failed int downloadUrlLines = 0; int matchingUrls = 0; // continue only if HTTP status is good if (response.status_code >= 200 && response.status_code < 300) { // in contrary to the original implementation, instead of converting wildcards into // all-matching regular expressions, we have the power of fnmatch() available, a real wildcard // implementation // unfortunately, this is still hoping for GitHub's JSON API to return a pretty printed // response which can be parsed like this std::stringstream responseText(response.text); std::string currentLine; // not ideal, but allows for returning a match for the entire line auto pattern = "*" + filename + "*"; // iterate through all lines to find a possible download URL and compare it to the pattern while (std::getline(responseText, currentLine)) { if (currentLine.find("browser_download_url") != std::string::npos) { downloadUrlLines++; if (fnmatch(pattern.c_str(), currentLine.c_str(), 0) == 0) { matchingUrls++; auto parts = split(currentLine, '"'); zsyncUrl = parts.back(); break; } } } } else { issueStatusMessage("GitHub API request failed!"); } if (downloadUrlLines <= 0) { std::ostringstream oss; oss << "Could not find any artifacts in release data. " << "Please contact the author of the AppImage and tell them the files are missing " << "on the releases page."; issueStatusMessage(oss.str()); } else if (matchingUrls <= 0) { std::ostringstream oss; oss << "None of the artifacts matched the pattern in the update information. " << "The pattern is most likely invalid, e.g., due to changes in the filenames of " << "the AppImages. Please contact the author of the AppImage and ask them to " << "revise the update information."; issueStatusMessage(oss.str()); } else if (zsyncUrl.empty()) { // unlike that this code will ever be reached, the other two messages should cover all // cases in which a ZSync URL is missing // if it does, however, it's most likely that GitHub's API didn't return a URL issueStatusMessage("Failed to parse GitHub's response."); } } } else if (uiParts[0] == "bintray-zsync") { // TODO: better error handling if (uiParts.size() == 5) { uiType = ZSYNC_BINTRAY; auto username = uiParts[1]; auto repository = uiParts[2]; auto packageName = uiParts[3]; auto filename = uiParts[4]; std::stringstream downloadUrl; downloadUrl << "https://dl.bintray.com/" << username << "/" << repository << "/" << filename; if (downloadUrl.str().find("_latestVersion") == std::string::npos) { zsyncUrl = downloadUrl.str(); } else { std::stringstream redirectorUrl; redirectorUrl << "https://bintray.com/" << username << "/" << repository << "/" << packageName << "/_latestVersion"; auto versionResponse = cpr::Head(redirectorUrl.str()); // this request is supposed to be redirected // due to how cpr works, we can't check for a redirection status, as we get the response for // the redirected request // therefore, we check for a 2xx response, and then can inspect and compare the redirected URL if (versionResponse.status_code >= 200 && versionResponse.status_code < 400) { auto redirectedUrl = versionResponse.url; // if they're different, it's probably been successful if (redirectorUrl.str() != redirectedUrl) { // the last part will contain the current version auto packageVersion = static_cast<std::string>(split(redirectedUrl, '/').back()); auto urlTemplate = downloadUrl.str(); // split by _latestVersion, insert correct value, compose final value auto pos = urlTemplate.find("_latestVersion"); auto firstPart = urlTemplate.substr(0, pos); auto secondPart = urlTemplate.substr(pos + std::string("_latestVersion").length()); zsyncUrl = firstPart + packageVersion + secondPart; } } } } } else if (uiParts[0] == "zsync") { // validate update information if (uiParts.size() == 2) { uiType = ZSYNC_GENERIC; zsyncUrl = uiParts.back(); } else { std::ostringstream oss; oss << "Update information has invalid parameter count. Please contact the author of " << "the AppImage and ask them to revise the update information. They should consult " << "the AppImage specification, there might have been changes to the update" << "information."; issueStatusMessage(oss.str()); } } else if (methods::PlingV1Zsync::isUpdateStringAccepted(uiParts)) { uiType = ZSYNC_PLING_V1; auto updateMethod = methods::PlingV1Zsync(uiParts); auto availableDownloads = updateMethod.getAvailableDownloads(); auto latestReleaseUrl = updateMethod.findLatestRelease(availableDownloads); zsyncUrl = updateMethod.resolveZsyncUrl(latestReleaseUrl); } else { // unknown type } } auto* appImage = new AppImage(); appImage->filename = pathToAppImage; appImage->appImageVersion = appImageType; appImage->rawUpdateInformation = updateInformation; appImage->updateInformationType = uiType; appImage->zsyncUrl = zsyncUrl; appImage->signature = signature; return appImage; } bool validateAppImage(AppImage const* appImage) { // a null pointer is clearly a sign if (appImage == nullptr) { std::ostringstream oss; oss << "Parsing AppImage failed. See previous message for details. " << "Are you sure the file is an AppImage?"; issueStatusMessage(oss.str()); return false; } // first check whether there's update information at all if (appImage->rawUpdateInformation.empty()) { std::ostringstream oss; oss << "Could not find update information in the AppImage. " << "Please contact the author of the AppImage and ask them to embed update information."; issueStatusMessage(oss.str()); return false; } // now check whether a ZSync URL could be composed by readAppImage // this is the only supported update type at the moment if (appImage->zsyncUrl.empty()) { std::ostringstream oss; oss << "ZSync URL not available. See previous messages for details."; issueStatusMessage(oss.str()); return false; } // check whether update information is available if (appImage->updateInformationType == INVALID) { std::stringstream oss; oss << "Could not detect update information type." << "Please contact the author of the AppImage and ask them whether the update information " << "is correct."; issueStatusMessage(oss.str()); return false; } return true; } // thread runner void runUpdate() { // initialization { lock_guard guard(mutex); // make sure it runs only once at a time // should never occur, but you never know if (state != INITIALIZED) return; // if there is a ZSync client (e.g., because an update check has been run), clean it up // this ensures that a fresh instance will be used for the update run if (zSyncClient != nullptr) { delete zSyncClient; zSyncClient = nullptr; } // WARNING: if you don't want to shoot yourself in the foot, make sure to read in the AppImage // while locking the mutex and/or before the RUNNING state to make sure readAppImage() finishes // before progress() and such can be called! Otherwise, progress() etc. will return an error state, // causing e.g., main(), to interrupt the thread and finish. auto* appImage = readAppImage(pathToAppImage); if (!validateAppImage(appImage)) { // cleanup delete appImage; state = ERROR; return; } if (appImage->updateInformationType == ZSYNC_BINTRAY) { issueStatusMessage("Updating from Bintray via ZSync"); } else if (appImage->updateInformationType == ZSYNC_GITHUB_RELEASES) { issueStatusMessage("Updating from GitHub Releases via ZSync"); } else if (appImage->updateInformationType == ZSYNC_GENERIC) { issueStatusMessage("Updating from generic server via ZSync"); } if (appImage->updateInformationType == ZSYNC_GITHUB_RELEASES || appImage->updateInformationType == ZSYNC_BINTRAY || appImage->updateInformationType == ZSYNC_PLING_V1 || appImage->updateInformationType == ZSYNC_GENERIC) { // doesn't matter which type it is exactly, they all work like the same zSyncClient = new zsync2::ZSyncClient(appImage->zsyncUrl, pathToAppImage, overwrite); // enable ranges optimizations zSyncClient->setRangesOptimizationThreshold(64 * 4096); // make sure the new AppImage goes into the same directory as the old one // unfortunately, to be able to use dirname(), one has to copy the C string first auto* path = strdup(appImage->filename.c_str()); std::string dirPath = dirname(path); free(path); zSyncClient->setCwd(dirPath); } else { // error unsupported type issueStatusMessage("Error: update method not implemented"); // cleanup delete appImage; state = ERROR; return; } // cleanup delete appImage; state = RUNNING; } // keep state -- by default, an error (false) is assumed bool result = false; // run phase { // check whether it's a zsync operation if (zSyncClient != nullptr) { result = zSyncClient->run(); } } // end phase { lock_guard guard(mutex); if (result) { state = SUCCESS; } else { state = ERROR; } } } bool checkForChanges(bool& updateAvailable, const unsigned int method = 0) { lock_guard guard(mutex); if (state != INITIALIZED) return false; // TODO: this code is somewhat duplicated in run() // should probably be extracted to separate function auto* appImage = readAppImage(pathToAppImage); // validate AppImage if(!validateAppImage(appImage)) return false; if (appImage->updateInformationType == ZSYNC_GITHUB_RELEASES || appImage->updateInformationType == ZSYNC_BINTRAY || appImage->updateInformationType == ZSYNC_PLING_V1 || appImage->updateInformationType == ZSYNC_GENERIC ) { zSyncClient = new zsync2::ZSyncClient(appImage->zsyncUrl, pathToAppImage); return zSyncClient->checkForChanges(updateAvailable, method); } zSyncClient = nullptr; // return error in case of unknown update information issueStatusMessage("Unknown update information type, aborting."); return false; } }; Updater::Updater(const std::string& pathToAppImage, bool overwrite) { // initialize data class d = new Updater::Private(); // workaround for AppImageLauncher filesystem d->pathToAppImage = ailfsRealpath(pathToAppImage); d->overwrite = overwrite; // check whether file exists, otherwise throw exception std::ifstream f(d->pathToAppImage); if(!f || !f.good()) { auto errorMessage = std::strerror(errno); throw std::invalid_argument(errorMessage + std::string(": ") + d->pathToAppImage); } } Updater::~Updater() { delete d; } void Updater::runUpdate() { // alias for private function return d->runUpdate(); } bool Updater::start() { // lock mutex lock_guard guard(d->mutex); // prevent multiple start calls if(d->state != INITIALIZED) return false; // if there's a thread managed by this class already, should not start another one and lose access to // this one if(d->thread) return false; // create thread d->thread = new std::thread(&Updater::runUpdate, this); return true; } bool Updater::isDone() { lock_guard guard(d->mutex); return d->state != INITIALIZED && d->state != RUNNING && d->state != STOPPING; } bool Updater::hasError() { lock_guard guard(d->mutex); return d->state == ERROR; } bool Updater::progress(double& progress) { lock_guard guard(d->mutex); if (d->state == INITIALIZED) { // this protects update checks from returning progress, which would only occur when using method 0 progress = 0; return true; } else if (d->state == SUCCESS || d->state == ERROR) { progress = 1; return true; } if (d->zSyncClient != nullptr) { progress = d->zSyncClient->progress(); return true; } return false; } bool Updater::stop() { throw std::runtime_error("not implemented"); } bool Updater::nextStatusMessage(std::string& message) { // first, check own message queue if (!d->statusMessages.empty()) { message = d->statusMessages.front(); d->statusMessages.pop_front(); return true; } // next, check zsync client for a message if (d->zSyncClient != nullptr) { std::string zsyncMessage; if (!d->zSyncClient->nextStatusMessage(zsyncMessage)) return false; // show that the message is coming from zsync2 message = "zsync2: " + zsyncMessage; return true; } return false; } Updater::State Updater::state() { return d->state; } bool Updater::checkForChanges(bool &updateAvailable, const unsigned int method) { return d->checkForChanges(updateAvailable, method); } bool Updater::describeAppImage(std::string& description) const { std::ostringstream oss; auto* appImage = d->readAppImage(d->pathToAppImage); if (appImage == nullptr) return false; oss << "Parsing file: " << appImage->filename << std::endl; oss << "AppImage type: " << appImage->appImageVersion << std::endl; oss << "Raw update information: "; if (appImage->rawUpdateInformation.empty()) oss << "<empty>"; else oss << appImage->rawUpdateInformation; oss << std::endl; oss << "Update information type: "; if (appImage->updateInformationType == d->ZSYNC_GENERIC) oss << "Generic ZSync URL"; else if (appImage->updateInformationType == d->ZSYNC_BINTRAY) oss << "ZSync via Bintray"; else if (appImage->updateInformationType == d->ZSYNC_GITHUB_RELEASES) oss << "ZSync via GitHub Releases"; else if (appImage->updateInformationType == d->ZSYNC_PLING_V1) oss << "ZSync via OCS"; else if (appImage->updateInformationType == d->INVALID) oss << "Invalid (parsing failed/no update information available)"; else oss << "Unknown error"; oss << std::endl; if (!appImage->zsyncUrl.empty()) oss << "Assembled ZSync URL: " << appImage->zsyncUrl << std::endl; else oss << "Failed to assemble ZSync URL. AppImageUpdate can not be used with this AppImage."; description = oss.str(); return true; } bool Updater::pathToNewFile(std::string& path) const { // only available update method is via ZSync if (d->zSyncClient) return d->zSyncClient->pathToNewFile(path); return false; } bool Updater::remoteFileSize(off_t& fileSize) const { // only available update method is via ZSync if (d->zSyncClient != nullptr) return d->zSyncClient->remoteFileSize(fileSize); return false; } Updater::ValidationState Updater::validateSignature() { std::string pathToNewAppImage; if (!this->pathToNewFile(pathToNewAppImage)) { // return generic error return VALIDATION_FAILED; } auto pathToOldAppImage = abspath(d->pathToAppImage); if (pathToOldAppImage == pathToNewAppImage) { pathToOldAppImage = pathToNewAppImage + ".zs-old"; } auto oldSignature = d->readAppImageSignature(pathToOldAppImage); auto newSignature = d->readAppImageSignature(pathToNewAppImage); // remove any spaces and/or newline characters there might be on the left or right of the payload zsync2::trim(oldSignature, '\n'); zsync2::trim(newSignature, '\n'); zsync2::trim(oldSignature); zsync2::trim(newSignature); auto oldSigned = !oldSignature.empty(); auto newSigned = !newSignature.empty(); auto oldDigest = d->hashAppImage(pathToOldAppImage); auto newDigest = d->hashAppImage(pathToNewAppImage); auto oldDigestOrig = readElfSection(pathToOldAppImage, ".sha256_sig"); auto newDigestOrig = readElfSection(pathToNewAppImage, ".sha256_sig"); std::string tempDir; { char* buffer; char* pattern = strdup("/tmp/AppImageUpdate-XXXXXX"); if ((buffer = mkdtemp(pattern)) == nullptr) { d->issueStatusMessage("Failed to create temporary directory"); return VALIDATION_TEMPDIR_CREATION_FAILED; } tempDir = buffer; free(pattern); } auto tempFile = [&tempDir](const std::string& filename, const std::string& contents) { std::stringstream path; path << tempDir << "/" << filename; auto x = path.str(); std::ofstream ofs(path.str()); ofs.write(contents.c_str(), contents.size()); return path.str(); }; if (!oldSigned && !newSigned) return VALIDATION_NOT_SIGNED; else if (oldSigned && !newSigned) return VALIDATION_NO_LONGER_SIGNED; // store digests and signatures in files so they can be passed to gpg2 auto oldDigestFilename = tempFile("old-digest", oldDigest); auto newDigestFilename = tempFile("new-digest", newDigest); auto oldSignatureFilename = tempFile("old-signature", oldSignature); auto newSignatureFilename = tempFile("new-signature", newSignature); auto cleanup = [&tempDir]() { // cleanup auto unlinkCb = [](const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf) { int rv = remove(fpath); if (rv) perror(fpath); return rv; }; nftw(tempDir.c_str(), unlinkCb, 64, FTW_DEPTH | FTW_PHYS); rmdir(tempDir.c_str()); }; // find gpg2 binary auto gpg2Path = findInPATH("gpg2"); if (gpg2Path.empty()) { cleanup(); return VALIDATION_GPG2_MISSING; } const auto tempKeyRingPath = tempDir + "/keyring"; // create keyring file, otherwise GPG will complain std::ofstream ofs(tempKeyRingPath); ofs.close(); auto importKeyFromAppImage = [&tempKeyRingPath, &gpg2Path](const std::string& path) { auto key = readElfSection(path, ".sig_key"); if (key.empty()) return false; std::ostringstream oss; oss << "'" << gpg2Path << "' " << "--no-default-keyring --keyring '" << tempKeyRingPath << "' --import"; auto command = oss.str(); auto proc = popen(oss.str().c_str(), "w"); fwrite(key.c_str(), key.size(), sizeof(char), proc); auto retval = pclose(proc); return retval == 0; }; importKeyFromAppImage(pathToOldAppImage); importKeyFromAppImage(pathToNewAppImage); auto verifySignature = [this, &gpg2Path, &tempKeyRingPath]( const std::string& signatureFile, const std::string& digestFile, bool& keyFound, bool& goodSignature, std::string& keyID, std::string& keyOwner ) { std::ostringstream oss; oss << "'" << gpg2Path << "'" << " --keyring '" << tempKeyRingPath << "'" << " --verify '" << signatureFile << "' '" << digestFile << "' 2>&1"; auto command = oss.str(); // make sure output is in English setenv("LANGUAGE", "C", 1); setenv("LANG", "C", 1); setenv("LC_ALL", "C", 1); auto* proc = popen(command.c_str(), "r"); if (proc == nullptr) return false; char* currentLine = nullptr; size_t lineSize = 0; keyFound = true; goodSignature = false; while (getline(&currentLine, &lineSize, proc) != -1) { std::string line = currentLine; trim(line, '\n'); trim(line); d->issueStatusMessage(std::string("gpg2: ") + line); auto splitOwner = [&line]() { auto parts = split(line, '"'); if (parts.size() < 2) return std::string(); auto skip = parts[0].length(); return line.substr(skip + 1, line.length() - skip - 2); }; if (stringStartsWith(line, "gpg: Signature made")) { // extract key auto parts = split(line); if (*(parts.end() - 3) == "key" && *(parts.end() - 2) == "ID") keyID = parts.back(); } else if (stringStartsWith(line, "gpg: Good signature from")) { goodSignature = true; keyOwner = splitOwner(); } else if (stringStartsWith(line, "gpg: BAD signature from")) { goodSignature = false; keyOwner = splitOwner(); } else if (stringStartsWith(line, "gpg: Can't check signature: No public key")) { keyFound = false; } } auto rv = pclose(proc); return true; }; bool oldKeyFound = false, newKeyFound = false, oldSignatureGood = false, newSignatureGood = false; std::string oldKeyID, newKeyID, oldKeyOwner, newKeyOwner; if (oldSigned) { if (!verifySignature(oldSignatureFilename, oldDigestFilename, oldKeyFound, oldSignatureGood, oldKeyID, oldKeyOwner)) { cleanup(); return VALIDATION_GPG2_CALL_FAILED; } } if (newSigned) { if (!verifySignature(newSignatureFilename, newDigestFilename, newKeyFound, newSignatureGood, newKeyID, newKeyOwner)) { cleanup(); return VALIDATION_GPG2_CALL_FAILED; } } if (!oldKeyFound || !newKeyFound) { // if the keys haven't been embedded in the AppImages, we treat them as not signed // see https://github.com/AppImage/AppImageUpdate/issues/16#issuecomment-370932698 for details cleanup(); return VALIDATION_NOT_SIGNED; } if (!oldSignatureGood || !newSignatureGood) { cleanup(); return VALIDATION_BAD_SIGNATURE; } if (oldSigned && newSigned) { if (oldKeyID != newKeyID) { cleanup(); return VALIDATION_KEY_CHANGED; } } cleanup(); return VALIDATION_PASSED; } std::string Updater::signatureValidationMessage(const Updater::ValidationState& state) { static const std::map<ValidationState, std::string> validationMessages = { {VALIDATION_PASSED, "Signature validation successful"}, // warning states {VALIDATION_WARNING, "Signature validation warning"}, {VALIDATION_NOT_SIGNED, "AppImage not signed"}, {VALIDATION_GPG2_MISSING, "gpg2 command not found, please install"}, // error states {VALIDATION_FAILED, "Signature validation failed"}, {VALIDATION_GPG2_CALL_FAILED, "Call to gpg2 failed"}, {VALIDATION_TEMPDIR_CREATION_FAILED, "Failed to create temporary directory"}, {VALIDATION_NO_LONGER_SIGNED, "AppImage no longer comes with signature"}, {VALIDATION_BAD_SIGNATURE, "Bad signature"}, {VALIDATION_KEY_CHANGED, "Key changed for signing AppImages"}, }; if (validationMessages.count(state) > 0) { return validationMessages.at(state); } return "Unknown validation state"; } std::string Updater::updateInformation() const { const auto* appImage = d->readAppImage(d->pathToAppImage); if (appImage == nullptr) throw std::runtime_error("Failed to parse AppImage"); return appImage->rawUpdateInformation; } bool Updater::restoreOriginalFile() { std::string newFilePath; if (!pathToNewFile(newFilePath)) { throw std::runtime_error("Failed to get path to new file"); } // make sure to compare absolute, resolved paths newFilePath = abspath(newFilePath); const auto& oldFilePath = abspath(d->pathToAppImage); // restore original file std::remove(newFilePath.c_str()); if (oldFilePath == newFilePath) { std::rename((newFilePath + ".zs-old").c_str(), newFilePath.c_str()); } } void Updater::copyPermissionsToNewFile() { std::string oldFilePath = abspath(d->pathToAppImage); std::string newFilePath; if (!pathToNewFile(newFilePath)) { throw std::runtime_error("Failed to get path to new file"); } // make sure to compare absolute, resolved paths newFilePath = abspath(newFilePath); appimage::update::copyPermissions(oldFilePath, newFilePath); } } }
41.88025
134
0.485959
smarttowel
3c48c916165d83ea1649606af974f6d4ae2b10e1
21,267
cpp
C++
bebop_driver/src/bebop.cpp
itssme/bebop_autonomy
f061c8a2c45526eb79c1ba0aaa09618bbd9408d0
[ "BSD-3-Clause" ]
2
2019-02-12T14:55:21.000Z
2021-02-15T23:32:36.000Z
bebop_driver/src/bebop.cpp
itssme/bebop_autonomy
f061c8a2c45526eb79c1ba0aaa09618bbd9408d0
[ "BSD-3-Clause" ]
null
null
null
bebop_driver/src/bebop.cpp
itssme/bebop_autonomy
f061c8a2c45526eb79c1ba0aaa09618bbd9408d0
[ "BSD-3-Clause" ]
null
null
null
/** Software License Agreement (BSD) \file bebop.cpp \authors Mani Monajjemi <mmonajje@sfu.ca> \copyright Copyright (c) 2015, Autonomy Lab (Simon Fraser University), 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 Autonomy Lab 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 WAR- RANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, IN- DIRECT, 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 <stdexcept> #include <cmath> #include <string> #include <algorithm> #include <vector> #include <boost/bind.hpp> #include <boost/thread/locks.hpp> #include <boost/make_shared.hpp> extern "C" { #include "libARCommands/ARCommands.h" #include "libARDiscovery/ARDiscovery.h" #include <libARController/ARController.h> } #include <bebop_driver/bebop.h> #include "bebop_driver/BebopArdrone3Config.h" #include "bebop_driver/bebop_video_decoder.h" // include all callback wrappers #include "bebop_driver/autogenerated/ardrone3_state_callbacks.h" #include "bebop_driver/autogenerated/common_state_callbacks.h" #include "bebop_driver/autogenerated/ardrone3_setting_callbacks.h" /* * Bebop coordinate systems * * Velocities: * * +x : East * +y : South * +z : Down * * Attitude: * * +x : forward * +y : right * +z : down * +yaw : CW * * ROS coordinate system (REP 105) * * +x : forward * +y : left * +z : up * +yaw : CCW * * Move function (setPilotingPCMD, conforms with Attiude, except for gaz) * * +roll : right * +pitch : forward * +gaz : up * +yaw : CW * */ namespace bebop_driver { const char* Bebop::LOG_TAG = "BebopSDK"; void Bebop::StateChangedCallback(eARCONTROLLER_DEVICE_STATE new_state, eARCONTROLLER_ERROR error, void *bebop_void_ptr) { // TODO(mani-monaj): Log error Bebop* bebop_ptr_ = static_cast<Bebop*>(bebop_void_ptr); switch (new_state) { case ARCONTROLLER_DEVICE_STATE_STOPPED: ARSAL_Sem_Post(&(bebop_ptr_->state_sem_)); break; case ARCONTROLLER_DEVICE_STATE_RUNNING: ARSAL_Sem_Post(&(bebop_ptr_->state_sem_)); break; } } void Bebop::CommandReceivedCallback(eARCONTROLLER_DICTIONARY_KEY cmd_key, ARCONTROLLER_DICTIONARY_ELEMENT_t *element_dict_ptr, void *bebop_void_ptr) { static long int lwp_id = util::GetLWPId(); static bool lwp_id_printed = false; if (!lwp_id_printed) { ARSAL_PRINT(ARSAL_PRINT_INFO, LOG_TAG, "Command Received Callback LWP id is: %ld", lwp_id); lwp_id_printed = true; } Bebop* bebop_ptr = static_cast<Bebop*>(bebop_void_ptr); if (!bebop_ptr->IsConnected()) return; ARCONTROLLER_DICTIONARY_ELEMENT_t *single_element_ptr = NULL; if (element_dict_ptr) { // We are only interested in single key dictionaries HASH_FIND_STR(element_dict_ptr, ARCONTROLLER_DICTIONARY_SINGLE_KEY, single_element_ptr); if (single_element_ptr) { callback_map_t::iterator it = bebop_ptr->callback_map_.find(cmd_key); if (it != bebop_ptr->callback_map_.end()) { // TODO(mani-monaj): Check if we can find the time from the packets it->second->Update(element_dict_ptr->arguments, ros::Time::now()); } } } } // This callback is called within the same context as FrameReceivedCallback() eARCONTROLLER_ERROR Bebop::DecoderConfigCallback(ARCONTROLLER_Stream_Codec_t codec, void *bebop_void_ptr) { Bebop* bebop_ptr = static_cast<Bebop*>(bebop_void_ptr); if (codec.type == ARCONTROLLER_STREAM_CODEC_TYPE_H264) { ARSAL_PRINT(ARSAL_PRINT_INFO, LOG_TAG, "H264 configuration packet received: #SPS: %d #PPS: %d (MP4? %d)", codec.parameters.h264parameters.spsSize, codec.parameters.h264parameters.ppsSize, codec.parameters.h264parameters.isMP4Compliant); if (!bebop_ptr->video_decoder_ptr_->SetH264Params( codec.parameters.h264parameters.spsBuffer, codec.parameters.h264parameters.spsSize, codec.parameters.h264parameters.ppsBuffer, codec.parameters.h264parameters.ppsSize)) { return ARCONTROLLER_ERROR; } } else { ARSAL_PRINT(ARSAL_PRINT_WARNING, LOG_TAG, "Codec type is not H264"); return ARCONTROLLER_ERROR; } return ARCONTROLLER_OK; } // This Callback runs in ARCONTROLLER_Stream_ReaderThreadRun context and blocks it until it returns eARCONTROLLER_ERROR Bebop::FrameReceivedCallback(ARCONTROLLER_Frame_t *frame, void *bebop_void_ptr) { static long int lwp_id = util::GetLWPId(); static bool lwp_id_printed = false; if (!lwp_id_printed) { ARSAL_PRINT(ARSAL_PRINT_INFO, LOG_TAG, "Frame Recv & Decode LWP id: %ld", lwp_id); lwp_id_printed = true; } if (!frame) { ARSAL_PRINT(ARSAL_PRINT_WARNING, LOG_TAG, "Received frame is NULL"); return ARCONTROLLER_ERROR_NO_VIDEO; } Bebop* bebop_ptr = static_cast<Bebop*>(bebop_void_ptr); if (!bebop_ptr->IsConnected()) return ARCONTROLLER_ERROR; { boost::unique_lock<boost::mutex> lock(bebop_ptr->frame_avail_mutex_); if (bebop_ptr->is_frame_avail_) { ARSAL_PRINT(ARSAL_PRINT_WARNING, LOG_TAG, "Previous frame might have been missed."); } if (!bebop_ptr->video_decoder_ptr_->Decode(frame)) { ARSAL_PRINT(ARSAL_PRINT_ERROR, LOG_TAG, "Video decode failed"); } else { bebop_ptr->is_frame_avail_ = true; // ARSAL_PRINT(ARSAL_PRINT_INFO, LOG_TAG, "FRAME IS READY"); bebop_ptr->frame_avail_cond_.notify_one(); } } return ARCONTROLLER_OK; } Bebop::Bebop(ARSAL_Print_Callback_t custom_print_callback): is_connected_(false), is_streaming_started_(false), device_ptr_(NULL), device_controller_ptr_(NULL), error_(ARCONTROLLER_OK), device_state_(ARCONTROLLER_DEVICE_STATE_MAX), video_decoder_ptr_(new bebop_driver::VideoDecoder()), is_frame_avail_(false) // out_file("/tmp/ts.txt") { // Redirect all calls to AR_PRINT_* to this function if provided if (custom_print_callback) ARSAL_Print_SetCallback(custom_print_callback); ARSAL_PRINT(ARSAL_PRINT_INFO, LOG_TAG, "Bebop Cnstr()"); } Bebop::~Bebop() { // This is the last resort, the program must run Cleanup() fo // proper disconnection and free if (device_ptr_) ARDISCOVERY_Device_Delete(&device_ptr_); if (device_controller_ptr_) ARCONTROLLER_Device_Delete(&device_controller_ptr_); } void Bebop::Connect(ros::NodeHandle& nh, ros::NodeHandle& priv_nh, const std::string& bebop_ip) { try { if (is_connected_) throw std::runtime_error("Already inited"); // TODO(mani-monaj): Error checking; ARSAL_Sem_Init(&state_sem_, 0, 0); eARDISCOVERY_ERROR error_discovery = ARDISCOVERY_OK; device_ptr_ = ARDISCOVERY_Device_New(&error_discovery); if (error_discovery != ARDISCOVERY_OK) { throw std::runtime_error("Discovery failed: " + std::string(ARDISCOVERY_Error_ToString(error_discovery))); } // set/save ip bebop_ip_ = bebop_ip; // TODO(mani-monaj): Make ip and port params error_discovery = ARDISCOVERY_Device_InitWifi(device_ptr_, ARDISCOVERY_PRODUCT_ARDRONE, "Bebop", bebop_ip_.c_str(), 44444); if (error_discovery != ARDISCOVERY_OK) { throw std::runtime_error("Discovery failed: " + std::string(ARDISCOVERY_Error_ToString(error_discovery))); } device_controller_ptr_ = ARCONTROLLER_Device_New(device_ptr_, &error_); ThrowOnCtrlError(error_, "Creation of device controller failed: "); ARDISCOVERY_Device_Delete(&device_ptr_); // callback_map is not being modified after this initial update #define UPDTAE_CALLBACK_MAP #include "bebop_driver/autogenerated/ardrone3_state_callback_includes.h" #include "bebop_driver/autogenerated/common_state_callback_includes.h" #include "bebop_driver/autogenerated/ardrone3_setting_callback_includes.h" #undef UPDTAE_CALLBACK_MAP ThrowOnCtrlError(ARCONTROLLER_Device_Start(device_controller_ptr_), "Controller device start failed"); ThrowOnCtrlError( ARCONTROLLER_Device_AddStateChangedCallback( device_controller_ptr_, Bebop::StateChangedCallback, reinterpret_cast<void*>(this)), "Registering state callback failed"); ThrowOnCtrlError( ARCONTROLLER_Device_AddCommandReceivedCallback( device_controller_ptr_, Bebop::CommandReceivedCallback, reinterpret_cast<void*>(this)), "Registering command callback failed"); // ThrowOnCtrlError( // ARCONTROLLER_Device_SetVideoStreamMP4Compliant( // device_controller_ptr_, 1), // "Enforcing MP4 compliancy failed"); // The forth argument is frame timeout callback ThrowOnCtrlError( ARCONTROLLER_Device_SetVideoStreamCallbacks( device_controller_ptr_, Bebop::DecoderConfigCallback, Bebop::FrameReceivedCallback, NULL , reinterpret_cast<void*>(this)), "Registering video callback failed"); // This semaphore is touched inside the StateCallback ARSAL_Sem_Wait(&state_sem_); device_state_ = ARCONTROLLER_Device_GetState(device_controller_ptr_, &error_); if ((error_ != ARCONTROLLER_OK) || (device_state_ != ARCONTROLLER_DEVICE_STATE_RUNNING)) { throw std::runtime_error("Waiting for device failed: " + std::string(ARCONTROLLER_Error_ToString(error_))); } // Enforce termination of video streaming ... (use Start/Stop streaming to enable/disable this) ThrowOnCtrlError(device_controller_ptr_->aRDrone3->sendMediaStreamingVideoEnable( device_controller_ptr_->aRDrone3, 0), "Stopping video stream failed."); } catch (const std::runtime_error& e) { Cleanup(); throw e; } is_connected_ = true; ARSAL_PRINT(ARSAL_PRINT_INFO, LOG_TAG, "BebopSDK inited, lwp_id: %ld", util::GetLWPId()); } void Bebop::Cleanup() { ARSAL_PRINT(ARSAL_PRINT_INFO, LOG_TAG, "Bebop Cleanup()"); if (device_controller_ptr_) { device_state_ = ARCONTROLLER_Device_GetState(device_controller_ptr_, &error_); if ((error_ == ARCONTROLLER_OK) && (device_state_ != ARCONTROLLER_DEVICE_STATE_STOPPED)) { ARSAL_PRINT(ARSAL_PRINT_INFO, LOG_TAG, "Disconnecting ..."); error_ = ARCONTROLLER_Device_Stop(device_controller_ptr_); if (error_ == ARCONTROLLER_OK) { ARSAL_Sem_Wait(&state_sem_); } } ARCONTROLLER_Device_Delete(&device_controller_ptr_); } is_connected_ = false; ARSAL_Sem_Destroy(&state_sem_); } void Bebop::StartStreaming() { if (is_streaming_started_) { ARSAL_PRINT(ARSAL_PRINT_WARNING, LOG_TAG, "Video streaming is already started ..."); return; } try { ThrowOnInternalError("Starting video stream failed"); // Start video streaming ThrowOnCtrlError(device_controller_ptr_->aRDrone3->sendMediaStreamingVideoEnable( device_controller_ptr_->aRDrone3, 1), "Starting video stream failed."); is_streaming_started_ = true; ARSAL_PRINT(ARSAL_PRINT_WARNING, LOG_TAG, "Video streaming started ..."); } catch (const std::runtime_error& e) { ARSAL_PRINT(ARSAL_PRINT_INFO, LOG_TAG, "Failed to start video streaming ..."); is_streaming_started_ = false; throw e; } } void Bebop::StopStreaming() { if (!is_streaming_started_) return; try { ThrowOnInternalError("Stopping video stream failed"); // Stop video streaming ThrowOnCtrlError(device_controller_ptr_->aRDrone3->sendMediaStreamingVideoEnable( device_controller_ptr_->aRDrone3, 0), "Stopping video stream failed."); is_streaming_started_ = false; } catch (const std::runtime_error& e) { ARSAL_PRINT(ARSAL_PRINT_ERROR, LOG_TAG, "Failed to stop video streaming ..."); } } void Bebop::Disconnect() { if (!is_connected_) return; if (is_streaming_started_) StopStreaming(); Cleanup(); ARSAL_PRINT(ARSAL_PRINT_INFO, LOG_TAG, "Disconnected from Bebop ..."); } void Bebop::SetDate(const std::string &date) { ThrowOnInternalError("Setting Date Failed"); ThrowOnCtrlError( device_controller_ptr_->common->sendCommonCurrentDate(device_controller_ptr_->common, const_cast<char*>(date.c_str())), "Setting Date Failed"); } void Bebop::RequestAllSettings() { ThrowOnInternalError("Request Settings Failed"); ThrowOnCtrlError( device_controller_ptr_->common->sendSettingsAllSettings(device_controller_ptr_->common), "Request Settings Failed"); } void Bebop::ResetAllSettings() { ThrowOnInternalError("Reset Settings Failed"); ThrowOnCtrlError( device_controller_ptr_->common->sendSettingsReset(device_controller_ptr_->common), "Reset Settings Failed"); ARSAL_PRINT(ARSAL_PRINT_INFO, LOG_TAG, "All settings of the drone have been reset to default values."); } void Bebop::UpdateSettings(const BebopArdrone3Config &config) { ThrowOnInternalError("Update Settings Failed"); // For all callback_map members // 1) Check if they are derived from AbstractSetting type // 1.1) Pass the config objects to them // boost::lock_guard<boost::mutex> lock(callback_map_mutex_); for (callback_map_t::iterator it = callback_map_.begin(); it != callback_map_.end(); it++) { // Convert the base class pointer (AbstractCommand) to the derived class pointer (AbstractSetting) // In case of State classes, do nothing boost::shared_ptr<cb::AbstractSetting> setting_ptr = boost::dynamic_pointer_cast<cb::AbstractSetting>(it->second); if (setting_ptr) { setting_ptr->UpdateBebopFromROS(config, device_controller_ptr_); } } } void Bebop::Takeoff() { ThrowOnInternalError("Takeoff failed"); ThrowOnCtrlError( device_controller_ptr_->aRDrone3->sendPilotingTakeOff(device_controller_ptr_->aRDrone3), "Takeoff failed"); } void Bebop::Land() { ThrowOnInternalError("Land failed"); ThrowOnCtrlError( device_controller_ptr_->aRDrone3->sendPilotingLanding(device_controller_ptr_->aRDrone3), "Land failed"); } void Bebop::Emergency() { ThrowOnInternalError("Emergency failed"); ThrowOnCtrlError( device_controller_ptr_->aRDrone3->sendPilotingEmergency(device_controller_ptr_->aRDrone3), "Emergency failed"); } void Bebop::FlatTrim() { ThrowOnInternalError("FlatTrim failed"); ThrowOnCtrlError( device_controller_ptr_->aRDrone3->sendPilotingFlatTrim(device_controller_ptr_->aRDrone3), "FlatTrim failed"); } void Bebop::NavigateHome(const bool &start_stop) { ThrowOnInternalError("Navigate home failed"); ThrowOnCtrlError( device_controller_ptr_->aRDrone3->sendPilotingNavigateHome( device_controller_ptr_->aRDrone3, start_stop ? 1 : 0), "Navigate home failed"); } void Bebop::StartAutonomousFlight(const std::string &filepath) { ThrowOnInternalError("Start autonomous flight failed"); ThrowOnCtrlError( device_controller_ptr_->common->sendMavlinkStart(device_controller_ptr_->common, const_cast<char*>(filepath.c_str()), (eARCOMMANDS_COMMON_MAVLINK_START_TYPE)0), "Start autonomous flight failed"); } void Bebop::PauseAutonomousFlight() { ThrowOnInternalError("Pause autonomous flight failed"); ThrowOnCtrlError( device_controller_ptr_->common->sendMavlinkPause(device_controller_ptr_->common), "Pause autonomous flight failed"); } void Bebop::StopAutonomousFlight() { ThrowOnInternalError("Stop autonomous flight failed"); ThrowOnCtrlError( device_controller_ptr_->common->sendMavlinkStop(device_controller_ptr_->common), "Stop autonomous flight failed"); } void Bebop::AnimationFlip(const uint8_t &anim_id) { ThrowOnInternalError("Animation failed"); if (anim_id >= ARCOMMANDS_ARDRONE3_ANIMATIONS_FLIP_DIRECTION_MAX) { throw std::runtime_error("Inavlid animation id"); } ThrowOnCtrlError( device_controller_ptr_->aRDrone3->sendAnimationsFlip( device_controller_ptr_->aRDrone3, static_cast<eARCOMMANDS_ARDRONE3_ANIMATIONS_FLIP_DIRECTION>( anim_id % ARCOMMANDS_ARDRONE3_ANIMATIONS_FLIP_DIRECTION_MAX)), "Navigate home failed"); } void Bebop::Move(const double &roll, const double &pitch, const double &gaz_speed, const double &yaw_speed) { // TODO(mani-monaj): Bound check ThrowOnInternalError("Move failure"); // If roll or pitch value are non-zero, enabel roll/pitch flag const bool do_rp = !((fabs(roll) < 0.001) && (fabs(pitch) < 0.001)); // If all values are zero, hover const bool do_hover = !do_rp && (fabs(yaw_speed) < 0.001) && (fabs(gaz_speed) < 0.001); if (do_hover) { ARSAL_PRINT(ARSAL_PRINT_DEBUG, LOG_TAG, "STOP"); ThrowOnCtrlError( device_controller_ptr_->aRDrone3->setPilotingPCMD( device_controller_ptr_->aRDrone3, 0, 0, 0, 0, 0, 0)); } else { ThrowOnCtrlError( device_controller_ptr_->aRDrone3->setPilotingPCMD( device_controller_ptr_->aRDrone3, do_rp, static_cast<int8_t>(roll * 100.0), static_cast<int8_t>(pitch * 100.0), static_cast<int8_t>(yaw_speed * 100.0), static_cast<int8_t>(gaz_speed * 100.0), 0)); } } // in degrees void Bebop::MoveCamera(const double &tilt, const double &pan) { ThrowOnInternalError("Camera Move Failure"); ThrowOnCtrlError(device_controller_ptr_->aRDrone3->setCameraOrientationV2( device_controller_ptr_->aRDrone3, static_cast<float>(tilt), static_cast<float>(pan))); } uint32_t Bebop::GetFrontCameraFrameWidth() const { return video_decoder_ptr_->GetFrameWidth(); } uint32_t Bebop::GetFrontCameraFrameHeight() const { return video_decoder_ptr_->GetFrameHeight(); } bool Bebop::GetFrontCameraFrame(std::vector<uint8_t> &buffer, uint32_t& width, uint32_t& height) const { boost::unique_lock<boost::mutex> lock(frame_avail_mutex_); ARSAL_PRINT(ARSAL_PRINT_DEBUG, LOG_TAG, "Waiting for frame to become available ..."); while (!is_frame_avail_) { frame_avail_cond_.wait(lock); } // ARSAL_PRINT(ARSAL_PRINT_INFO, LOG_TAG, "COPY STARTED"); const uint32_t num_bytes = video_decoder_ptr_->GetFrameWidth() * video_decoder_ptr_->GetFrameHeight() * 3; if (num_bytes == 0) { ARSAL_PRINT(ARSAL_PRINT_WARNING, LOG_TAG, "No picture size"); return false; } buffer.resize(num_bytes); // New frame is ready std::copy(video_decoder_ptr_->GetFrameRGBRawCstPtr(), video_decoder_ptr_->GetFrameRGBRawCstPtr() + num_bytes, buffer.begin()); width = video_decoder_ptr_->GetFrameWidth(); height = video_decoder_ptr_->GetFrameHeight(); is_frame_avail_ = false; // ARSAL_PRINT(ARSAL_PRINT_INFO, LOG_TAG, "COPY ENDED"); return true; } void Bebop::TakeSnapshot() { ThrowOnInternalError("Snapshot Failure"); ThrowOnCtrlError( device_controller_ptr_->aRDrone3->sendMediaRecordPictureV2( device_controller_ptr_->aRDrone3)); } void Bebop::SetExposure(const float& exposure) { ThrowOnInternalError("Failed to set exposure"); // TODO fairf4x: Check bounds ? ThrowOnCtrlError( device_controller_ptr_->aRDrone3->sendPictureSettingsExpositionSelection(device_controller_ptr_->aRDrone3, (float)exposure) ); } void Bebop::ToggleVideoRecording(const bool start) { ThrowOnInternalError("Video Toggle Failure"); ThrowOnCtrlError(device_controller_ptr_->aRDrone3->sendMediaRecordVideoV2( device_controller_ptr_->aRDrone3, start ? ARCOMMANDS_ARDRONE3_MEDIARECORD_VIDEOV2_RECORD_START : ARCOMMANDS_ARDRONE3_MEDIARECORD_VIDEOV2_RECORD_STOP)); } void Bebop::ThrowOnInternalError(const std::string &message) { if (!is_connected_ || !device_controller_ptr_) { throw std::runtime_error(message); } } void Bebop::ThrowOnCtrlError(const eARCONTROLLER_ERROR &error, const std::string &message) { if (error != ARCONTROLLER_OK) { throw std::runtime_error(message + std::string(ARCONTROLLER_Error_ToString(error))); } } } // namespace bebop_driver
32.972093
168
0.723045
itssme
3c49a66397cc303da71c8dc0b892af4fc3ba9fac
438
cpp
C++
Stack/main.cpp
NagiSenbon/ADTcpp
5038d4cc9d919af55f84f19f7de3c8b71235ab18
[ "MIT" ]
2
2019-01-31T15:01:37.000Z
2019-02-01T12:56:30.000Z
Stack/main.cpp
NagiSenbon/ADTcpp
5038d4cc9d919af55f84f19f7de3c8b71235ab18
[ "MIT" ]
null
null
null
Stack/main.cpp
NagiSenbon/ADTcpp
5038d4cc9d919af55f84f19f7de3c8b71235ab18
[ "MIT" ]
null
null
null
#include <iostream> //#include "Stack_Vector.h" //template<typename T> using Stack = Stack_Vector<T>; #include "Stack_List.h" template<typename T> using Stack = Stack_List<T>; using namespace std; int main() { Stack<int> st; for ( int i = 0; i < 10; i++ ) { st.push( i ); } for ( int i = 0; i < 10; i++ ) { cout << st.top() << "\n"; st.pop(); } cout << "the stack is empty : " << st.empty() << endl; st.pop(); return 0; }
20.857143
55
0.577626
NagiSenbon
3c4f3f361156e50919990a425ca6a2f03a632f65
1,431
cpp
C++
skia/docs/examples/Color_Type_ARGB_4444.cpp
jiangkang/renderer-dog
8081732e2b4dbdb97c8d1f5e23f9e52c6362ff85
[ "MIT" ]
1
2019-03-25T15:37:48.000Z
2019-03-25T15:37:48.000Z
docs/examples/Color_Type_ARGB_4444.cpp
bryphe/esy-skia
9810a02f28270535de10b584bffc536182224c83
[ "BSD-3-Clause" ]
1
2020-09-13T11:08:17.000Z
2020-09-13T11:08:17.000Z
skia/docs/examples/Color_Type_ARGB_4444.cpp
jiangkang/renderer-dog
8081732e2b4dbdb97c8d1f5e23f9e52c6362ff85
[ "MIT" ]
null
null
null
// Copyright 2019 Google LLC. // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. #include "fiddle/examples.h" // HASH=33a360c3404ac21db801943336843d8e REG_FIDDLE(Color_Type_ARGB_4444, 256, 96, false, 0) { void draw(SkCanvas* canvas) { canvas->scale(16, 16); SkBitmap bitmap; SkImageInfo imageInfo = SkImageInfo::Make(2, 2, kARGB_4444_SkColorType, kPremul_SkAlphaType); bitmap.allocPixels(imageInfo); SkCanvas offscreen(bitmap); offscreen.clear(SK_ColorGREEN); canvas->drawBitmap(bitmap, 0, 0); auto pack4444 = [](unsigned a, unsigned r, unsigned g, unsigned b) -> uint16_t { return (a << 0) | (b << 4) | (g << 8) | (r << 12); }; uint16_t red4444[] = { pack4444(0xF, 0xF, 0x0, 0x0), pack4444(0xF, 0xb, 0x0, 0x0), pack4444(0xF, 0x7, 0x0, 0x0), pack4444(0xF, 0x3, 0x0, 0x0) }; uint16_t blue4444[] = { pack4444(0xF, 0x0, 0x0, 0xF), pack4444(0xF, 0x0, 0x0, 0xb), pack4444(0xF, 0x0, 0x0, 0x7), pack4444(0xF, 0x0, 0x0, 0x3) }; SkPixmap redPixmap(imageInfo, &red4444, imageInfo.minRowBytes()); if (bitmap.writePixels(redPixmap, 0, 0)) { canvas->drawBitmap(bitmap, 2, 2); } SkPixmap bluePixmap(imageInfo, &blue4444, imageInfo.minRowBytes()); if (bitmap.writePixels(bluePixmap, 0, 0)) { canvas->drawBitmap(bitmap, 4, 4); } } } // END FIDDLE
46.16129
100
0.639413
jiangkang
3c511c5a89914a48912e42920f3246b389530021
2,662
hpp
C++
include/utility/persistent_container/container_config.hpp
SakuraLife/utility
b9bf26198917b6dc415520f74eb3eebf8aa8195e
[ "Unlicense" ]
2
2017-12-10T10:59:48.000Z
2017-12-13T04:11:14.000Z
include/utility/persistent_container/container_config.hpp
SakuraLife/utility
b9bf26198917b6dc415520f74eb3eebf8aa8195e
[ "Unlicense" ]
null
null
null
include/utility/persistent_container/container_config.hpp
SakuraLife/utility
b9bf26198917b6dc415520f74eb3eebf8aa8195e
[ "Unlicense" ]
null
null
null
#ifndef ___UTILITY__PERSISTENT__CONTAINER__CONFIG___ #define ___UTILITY__PERSISTENT__CONTAINER__CONFIG___ #include<utility/config/utility_config.hpp> namespace utility { namespace persistent_container { namespace config { struct cache_config { public: typedef unsigned short counter_type; public: constexpr static size_t max_record = 65535UL; public: UTILITY_ALWAYS_INLINE static inline counter_type init_state(counter_type __now) noexcept { return 0;} UTILITY_ALWAYS_INLINE static inline counter_type discard_state(counter_type __now) noexcept { return __now;} UTILITY_ALWAYS_INLINE static inline void update_state(counter_type& __now) noexcept { ++__now;} public: UTILITY_ALWAYS_INLINE static inline bool is_vaild( counter_type __init, counter_type __discard ) noexcept { return __discard == 0;} UTILITY_ALWAYS_INLINE static inline bool is_vaild( counter_type __need, counter_type __init, counter_type __discard ) noexcept { return __need <= __discard && __need > __init;} UTILITY_ALWAYS_INLINE static inline bool is_invaild( counter_type __init, counter_type __discard ) noexcept { return __discard != 0;} UTILITY_ALWAYS_INLINE static inline bool is_invaild( counter_type __need, counter_type __init, counter_type __discard ) noexcept { return !is_vaild(__need, __discard, __init);} UTILITY_ALWAYS_INLINE static inline bool is_reserved( counter_type __need, counter_type __init ) { return __need > __init;} public: UTILITY_ALWAYS_INLINE static inline size_t steps(counter_type __now) noexcept { return __now-1;} UTILITY_ALWAYS_INLINE static inline size_t next(counter_type __now, size_t __len) noexcept { return __now+__len;} static inline size_t prev(counter_type __now, size_t __len) noexcept { return __now-__len;} }; typedef cache_config base_cache_sg; } using config::base_cache_sg; } namespace p_container { namespace config { using persistent_container::config::base_cache_sg; } using persistent_container::config::base_cache_sg; } } #endif // ! ___UTILITY__PERSISTENT__CONTAINER__CONFIG___
30.597701
80
0.624718
SakuraLife
3c51eda04e38e0dcf0de0889ffad75eccef24b46
3,281
hpp
C++
include/nix/DataSet.hpp
stoewer/nix
7fe4669284b60b6a27228c2da7d3f61a77c943dc
[ "BSD-3-Clause" ]
53
2015-02-10T01:04:34.000Z
2021-04-24T14:26:04.000Z
include/nix/DataSet.hpp
stoewer/nix
7fe4669284b60b6a27228c2da7d3f61a77c943dc
[ "BSD-3-Clause" ]
262
2015-01-09T13:24:21.000Z
2021-07-02T13:45:31.000Z
include/nix/DataSet.hpp
gicmo/nix
17a5b90e6c12a22e921c181b79eb2a3db1bf61af
[ "BSD-3-Clause" ]
34
2015-03-27T16:41:14.000Z
2020-03-27T06:47:59.000Z
// Copyright (c) 2014, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. // // Author: Christian Kellner <kellner@bio.lmu.de> #ifndef NIX_DATA_IO_H #define NIX_DATA_IO_H #include <nix/Dimensions.hpp> #include <nix/Hydra.hpp> #include <nix/Platform.hpp> namespace nix { class NIXAPI DataSet { public: template<typename T> void getData(T &value) const; template<typename T> void setData(const T &value); template<typename T> void getData(T &value, const NDSize &count, const NDSize &offset) const; template<typename T> void getData(T &value, const NDSize &offset) const; template<typename T> void setData(const T &value, const NDSize &offset); void getData(DataType dtype, void *data, const NDSize &count, const NDSize &offset) const { ioRead(dtype, data, count, offset); } void setData(DataType dtype, const void *data, const NDSize &count, const NDSize &offset) { ioWrite(dtype, data, count, offset); } // *** the virtual interface *** virtual void dataExtent(const NDSize &extent) = 0; virtual NDSize dataExtent() const = 0; virtual DataType dataType() const = 0; virtual ~DataSet() {} protected: virtual void ioRead(DataType dtype, void *data, const NDSize &count, const NDSize &offset) const = 0; virtual void ioWrite(DataType dtype, const void *data, const NDSize &count, const NDSize &offset) = 0; }; template<typename T> void DataSet::getData(T &value) const { Hydra<T> hydra(value); NDSize extent = dataExtent(); hydra.resize(extent); DataType dtype = hydra.element_data_type(); NDSize shape = hydra.shape(); getData(dtype, hydra.data(), shape, {}); } template<typename T> void DataSet::setData(const T &value) { const Hydra<const T> hydra(value); DataType dtype = hydra.element_data_type(); NDSize shape = hydra.shape(); dataExtent(shape); setData(dtype, hydra.data(), shape, {}); } template<typename T> void DataSet::getData(T &value, const NDSize &count, const NDSize &offset) const { Hydra<T> hydra(value); DataType dtype = hydra.element_data_type(); hydra.resize(count); getData(dtype, hydra.data(), count, offset); } template<typename T> void DataSet::getData(T &value, const NDSize &offset) const { Hydra<T> hydra(value); DataType dtype = hydra.element_data_type(); NDSize count = hydra.shape(); if (! count) { count = NDSize(offset.size(), 1); } getData(dtype, hydra.data(), count, offset); } template<typename T> void DataSet::setData(const T &value, const NDSize &offset) { const Hydra<const T> hydra(value); DataType dtype = hydra.element_data_type(); NDSize shape = hydra.shape(); setData(dtype, hydra.data(), shape, offset); } } #endif
24.485075
97
0.619933
stoewer
3c5627ae8d7edb3d1b23dfb28c9c6b5da0a91d5b
6,818
cxx
C++
Podd/THaBPM.cxx
leadmocha/analyzer
ab26d755dbe816975e4165479c9fbefc4c4ca069
[ "BSD-3-Clause" ]
null
null
null
Podd/THaBPM.cxx
leadmocha/analyzer
ab26d755dbe816975e4165479c9fbefc4c4ca069
[ "BSD-3-Clause" ]
null
null
null
Podd/THaBPM.cxx
leadmocha/analyzer
ab26d755dbe816975e4165479c9fbefc4c4ca069
[ "BSD-3-Clause" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // // // THaBPM // // // // Class for a BPM // // measuring signals from four antennas // // and the position at the BPM (without phase correction) // // works with standard ADCs (lecroy like types) // // is good for unrastered beam, or to get average positions // // // /////////////////////////////////////////////////////////////////////////////// #include "THaBPM.h" #include "THaEvData.h" #include "THaDetMap.h" #include "VarDef.h" #include "VarType.h" #include "TMath.h" #include <vector> static const UInt_t NCHAN = 4; using namespace std; //_____________________________________________________________________________ THaBPM::THaBPM( const char* name, const char* description, THaApparatus* apparatus ) : THaBeamDet(name,description,apparatus), fRawSignal(NCHAN),fPedestals(NCHAN),fCorSignal(NCHAN),fRotPos(NCHAN/2), fRot2HCSPos(NCHAN/2,NCHAN/2), fCalibRot(0) { // Constructor } //_____________________________________________________________________________ Int_t THaBPM::ReadDatabase( const TDatime& date ) { // ReadDatabase: if detectors cant be added to detmap // or entry for bpms is missing -> kInitError // otherwise -> kOk const char* const here = "ReadDatabase"; vector<Int_t> detmap; Double_t pedestals[NCHAN], rotations[NCHAN], offsets[2]; FILE* file = OpenFile( date ); if( !file ) return kInitError; fOrigin.SetXYZ(0,0,0); Int_t err = ReadGeometry( file, date ); if( !err ) { // Read configuration parameters DBRequest config_request[] = { { "detmap", &detmap, kIntV }, { nullptr } }; err = LoadDB( file, date, config_request, fPrefix ); } UInt_t flags = THaDetMap::kFillLogicalChannel | THaDetMap::kFillModel; if( !err && FillDetMap(detmap, flags, here) <= 0 ) { err = kInitError; // Error already printed by FillDetMap } if( !err ) { memset( pedestals, 0, sizeof(pedestals) ); memset( rotations, 0, sizeof(rotations) ); memset( offsets , 0, sizeof( offsets ) ); DBRequest calib_request[] = { { "calib_rot", &fCalibRot }, { "pedestals", pedestals, kDouble, NCHAN, true }, { "rotmatrix", rotations, kDouble, NCHAN, true }, { "offsets" , offsets, kDouble, 2 , true }, { nullptr } }; err = LoadDB( file, date, calib_request, fPrefix ); } fclose(file); if( err ) return err; fOffset(0) = offsets[0]; fOffset(1) = offsets[1]; fPedestals.SetElements( pedestals ); fRot2HCSPos(0,0) = rotations[0]; fRot2HCSPos(0,1) = rotations[1]; fRot2HCSPos(1,0) = rotations[2]; fRot2HCSPos(1,1) = rotations[3]; return kOK; } //_____________________________________________________________________________ Int_t THaBPM::DefineVariables( EMode mode ) { // Initialize global variables and lookup table for decoder if( mode == kDefine && fIsSetup ) return kOK; fIsSetup = ( mode == kDefine ); // Register variables in global list RVarDef vars[] = { { "rawcur.1", "current in antenna 1", "GetRawSignal0()"}, { "rawcur.2", "current in antenna 2", "GetRawSignal1()"}, { "rawcur.3", "current in antenna 3", "GetRawSignal2()"}, { "rawcur.4", "current in antenna 4", "GetRawSignal3()"}, { "x", "reconstructed x-position", "fPosition.fX"}, { "y", "reconstructed y-position", "fPosition.fY"}, { "z", "reconstructed z-position", "fPosition.fZ"}, { "rotpos1", "position in bpm system","GetRotPosX()"}, { "rotpos2", "position in bpm system","GetRotPosY()"}, { nullptr } }; return DefineVarsFromList( vars, mode ); } //_____________________________________________________________________________ THaBPM::~THaBPM() { // Destructor. Remove variables from global list. if( fIsSetup ) RemoveVariables(); } //_____________________________________________________________________________ void THaBPM::Clear( Option_t* opt ) { // Reset per-event data. THaBeamDet::Clear(opt); fPosition.SetXYZ(0.,0.,-10000.); fDirection.SetXYZ(0.,0.,1.); for( UInt_t k=0; k<NCHAN; ++k ) { fRawSignal(k)=-1; fCorSignal(k)=-1; } fRotPos(0) = fRotPos(1) = 0.0; } //_____________________________________________________________________________ Int_t THaBPM::Decode( const THaEvData& evdata ) { // clears the event structure // loops over all modules defined in the detector map // copies raw data into local variables // performs pedestal subtraction const char* const here = "Decode()"; UInt_t nfired = 0; for (Int_t i = 0; i < fDetMap->GetSize(); i++ ){ THaDetMap::Module* d = fDetMap->GetModule( i ); for (Int_t j=0; j< evdata.GetNumChan( d->crate, d->slot ); j++) { Int_t chan = evdata.GetNextChan( d->crate, d->slot, j); if ((chan>=d->lo)&&(chan<=d->hi)) { Int_t data = evdata.GetData( d->crate, d->slot, chan, 0 ); UInt_t k = d->first + ((d->reverse) ? d->hi - chan : chan - d->lo) -1; if ((k<NCHAN)&&(fRawSignal(k)==-1)) { fRawSignal(k)= data; nfired++; } else { Warning( Here(here), "Illegal detector channel: %d", k ); } } } } if (nfired!=NCHAN) { Warning( Here(here), "Number of fired Channels out of range. " "Setting beam position to nominal values"); } else { fCorSignal=fRawSignal; fCorSignal-=fPedestals; } return 0; } //____________________________________________________ // Int_t THaBPM::Process( ) { // called by the beam apparatus // uses the pedestal subtracted signals from the antennas // to get the position in the bpm coordinate system // and uses the transformation matrix defined in the database // to transform it into the HCS // directions are not calculated, they are always set parallel to z for( UInt_t k = 0; k < NCHAN; k += 2 ) { Double_t ap = fCorSignal(k); Double_t am = fCorSignal(k + 1); if( ap + am != 0.0 ) { fRotPos(k / 2) = fCalibRot * (ap - am) / (ap + am); } else { fRotPos(k / 2) = 0.0; } } TVectorD dum(fRotPos); dum *= fRot2HCSPos; fPosition.SetXYZ( dum(0)+fOrigin(0)+fOffset(0), dum(1)+fOrigin(1)+fOffset(1), fOrigin(2) ); return 0; } //////////////////////////////////////////////////////////////////////////////// ClassImp(THaBPM)
29.903509
80
0.579642
leadmocha
3c585b17b643be42b7ea6094bbe928332ccc910a
1,993
cpp
C++
src/nbla/test/test_relu.cpp
daniel-falk/nnabla
3fe132ea52dc10521cc029a5d6ba8f565cf65ccf
[ "Apache-2.0" ]
2,792
2017-06-26T13:05:44.000Z
2022-03-28T07:55:26.000Z
src/nbla/test/test_relu.cpp
daniel-falk/nnabla
3fe132ea52dc10521cc029a5d6ba8f565cf65ccf
[ "Apache-2.0" ]
138
2017-06-27T07:04:44.000Z
2022-02-28T01:37:15.000Z
src/nbla/test/test_relu.cpp
daniel-falk/nnabla
3fe132ea52dc10521cc029a5d6ba8f565cf65ccf
[ "Apache-2.0" ]
380
2017-06-26T13:23:52.000Z
2022-03-25T16:51:30.000Z
// Copyright 2017,2018,2019,2020,2021 Sony Corporation. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // test_relu.cpp #include "gtest/gtest.h" #include <nbla/common.hpp> #include <nbla/function/relu.hpp> #include <random> namespace nbla { class ReLUTest : public ::testing::Test { public: protected: shared_ptr<Variable> in_; shared_ptr<Variable> out_; Context ctx_; dtypes dtype_; Shape_t shape_; virtual void SetUp() { // NNabla::init(); ctx_.array_class = "CpuArray"; ctx_.backend = {"cpu:float"}; dtype_ = dtypes::FLOAT; shape_ = Shape_t{2, 3, 4, 5}; in_.reset(new Variable(shape_)); out_.reset(new Variable()); std::random_device r; std::mt19937 e; std::normal_distribution<float> normal_dist(0, 1); float *data = in_->data()->cast(dtype_, ctx_)->pointer<float>(); for (int i = 0; i < in_->size(); i++) { data[i] = normal_dist(e); } } // virtual void TearDown() {} }; TEST_F(ReLUTest, Create) { shared_ptr<Function> relu = create_ReLU(ctx_, false); ASSERT_EQ(dtypes::FLOAT, relu->in_types()[0]); ASSERT_EQ(dtypes::FLOAT, relu->out_types()[0]); } TEST_F(ReLUTest, ForwardBackward) { shared_ptr<Function> relu = create_ReLU(ctx_, false); relu->setup(Variables{in_.get()}, Variables{out_.get()}); ASSERT_EQ(in_->shape(), out_->shape()); relu->forward(Variables{in_.get()}, Variables{out_.get()}); relu->backward(Variables{in_.get()}, Variables{out_.get()}, {true}, {false}); } }
29.308824
79
0.680381
daniel-falk
3c5a6b7d1058782da7dee453f54f9de563597d75
23,730
cpp
C++
src/glut/pxWindowNative.cpp
protey7/pxCore
ce09650977516833a3f892623eddba4a84aec1a3
[ "Apache-2.0" ]
null
null
null
src/glut/pxWindowNative.cpp
protey7/pxCore
ce09650977516833a3f892623eddba4a84aec1a3
[ "Apache-2.0" ]
2
2017-12-08T14:22:28.000Z
2018-02-15T03:28:31.000Z
src/glut/pxWindowNative.cpp
protey7/pxCore
ce09650977516833a3f892623eddba4a84aec1a3
[ "Apache-2.0" ]
2
2018-02-16T20:25:24.000Z
2018-07-09T17:28:46.000Z
/* pxCore Copyright 2005-2018 John Robinson 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. */ // pxWindowNativeGlut.cpp #include "../pxCore.h" #include "../pxWindow.h" #include "pxWindowNative.h" #include "../pxTimer.h" #include "../pxWindowUtil.h" #include "pxKeycodes.h" #include "pxConfigNative.h" #include <stdlib.h> #include <string.h> #include <unistd.h> #include <signal.h> #define GLUT_PX_CORE_FPS 30 #ifdef __APPLE__ #include <GLUT/glut.h> #include <OpenGL/gl.h> #include <OpenGL/glu.h> #else #if defined(PX_PLATFORM_WAYLAND_EGL) || defined(PX_PLATFORM_GENERIC_EGL) #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> #else #include <GL/glew.h> #include <GL/freeglut.h> #include <GL/gl.h> //#include <GL/glext.h> #endif //PX_PLATFORM_WAYLAND_EGL #endif using namespace std; #ifndef rtLogWarn #define rtLogWarn(...) (void)0 #endif #ifndef rtLogError #define rtLogError(...) (void)0 #endif #if 1 unsigned int frame_ms = 16; GLuint textureId1; GLuint mTextureName; static GLint u_resolution = -1; GLint u_texture = -1; GLint attr_pos = 0, attr_uv = 2; static const char *fShaderText = #if defined(PX_PLATFORM_WAYLAND_EGL) || defined(PX_PLATFORM_GENERIC_EGL) "precision mediump float;\n" #endif "uniform sampler2D s_texture;\n" "varying vec2 v_uv;\n" "void main() {\n" " vec4 textureColor = texture2D(s_texture, v_uv);\n" " gl_FragColor = vec4(textureColor.rgb,1);;\n" "}\n"; static const char *vShaderText = "uniform vec2 u_resolution;\n" "attribute vec2 pos;\n" "attribute vec2 uv;\n" "varying vec2 v_uv;\n" "void main() {\n" // map from "pixel coordinates" " vec4 zeroToOne = vec4(pos,0,1) / vec4(u_resolution, u_resolution.x, 1);\n" " vec4 zeroToTwo = zeroToOne * vec4(2.0, 2.0, 1, 1);\n" " vec4 clipSpace = zeroToTwo - vec4(1.0, 1.0, 0, 0);\n" " gl_Position = clipSpace * vec4(1, -1, 1, 1);\n" "v_uv = uv;\n" "}\n"; GLuint createShaderProgram(const char* vShaderTxt, const char* fShaderTxt) { GLuint fragShader, vertShader, program = 0; GLint stat; fragShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragShader, 1, (const char **) &fShaderTxt, NULL); glCompileShader(fragShader); glGetShaderiv(fragShader, GL_COMPILE_STATUS, &stat); if (!stat) { rtLogError("Error: fragment shader did not compile: %d", glGetError()); GLint maxLength = 0; glGetShaderiv(fragShader, GL_INFO_LOG_LENGTH, &maxLength); //The maxLength includes the NULL character std::vector<char> errorLog(maxLength); glGetShaderInfoLog(fragShader, maxLength, &maxLength, &errorLog[0]); //Provide the infolog in whatever manor you deem best. rtLogWarn("%s", &errorLog[0]); //Exit with failure. glDeleteShader(fragShader); //Don't leak the shader. exit(1); } vertShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertShader, 1, (const char **) &vShaderTxt, NULL); glCompileShader(vertShader); glGetShaderiv(vertShader, GL_COMPILE_STATUS, &stat); if (!stat) { rtLogError("vertex shader did not compile: %d", glGetError()); exit(1); } program = glCreateProgram(); glAttachShader(program, fragShader); glAttachShader(program, vertShader); glLinkProgram(program); glGetProgramiv(program, GL_LINK_STATUS, &stat); if (!stat) { char log[1000]; GLsizei len; glGetProgramInfoLog(program, 1000, &len, log); rtLogError("faild to link:%s", log); exit(1); } /* test setting attrib locations */ glBindAttribLocation(program, attr_pos, "pos"); glBindAttribLocation(program, attr_uv, "uv"); glLinkProgram(program); /* needed to put attribs into effect */ return program; } #if 0 static void drawImageTexture(float x, float y, float w, float h/*, pxBuffer& b*/) { const float verts[4][2] = { { x,y }, { x+w, y }, { x, y+h }, { x+w, y+h } }; #if 0 const float uv[4][2] = { { 0, 0 }, { b.width(), 0 }, { 0, b.height() }, { b.width(), b.height() } }; #endif { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE); glVertexAttribPointer(attr_pos, 2, GL_FLOAT, GL_FALSE, 0, verts); //glVertexAttribPointer(attr_uv, 2, GL_FLOAT, GL_FALSE, 0, uv); glEnableVertexAttribArray(attr_pos); //glEnableVertexAttribArray(attr_uv); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glDisableVertexAttribArray(attr_pos); //glDisableVertexAttribArray(attr_uv); } } #endif void doinit() { #if 1 #if !defined(__APPLE__) && !defined(PX_PLATFORM_WAYLAND_EGL) && !defined(PX_PLATFORM_GENERIC_EGL) GLenum err = glewInit(); if (err != GLEW_OK) { rtLogError("failed to initialize glew"); exit(1); // or handle the error in a nicer way } if (!GLEW_VERSION_2_1) // check that the machine supports the 2.1 API. { rtLogError("invalid glew version"); exit(1); // or handle the error in a nicer way } #endif #endif glClearColor(0, 0, 0, 1); GLuint program = createShaderProgram(vShaderText, fShaderText); u_resolution = glGetUniformLocation(program, "u_resolution"); u_texture = glGetUniformLocation(program, "s_texture"); #if 0 #if 1 // Using for RGBA texture glActiveTexture(GL_TEXTURE0); glGenTextures(1, &textureId1); glBindTexture(GL_TEXTURE_2D, textureId1); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); #if 0 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); #else glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); #endif #endif #endif glEnable(GL_BLEND); // assume non-premultiplied... glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glUseProgram(program); } #endif glutDisplay* displayRef::mDisplay = NULL; int displayRef::mRefCount = 0; vector<pxWindowNative*> pxWindowNative::mWindowVector; //bool pxWindowNative::mEventLoopTimerStarted = false; //float pxWindowNative::mEventLoopInterval = 1000.0 / (float)GLUT_PX_CORE_FPS; //timer_t pxWindowNative::mRenderTimerId; uint32_t getRawNativeKeycodeFromGlut(uint32_t key, uint32_t modifiers); //start glut callbacks pxWindowNative* pxWindowNative::getWindowFromGlutID(int id) { vector<pxWindowNative*> windowVector = pxWindow::getNativeWindows(); vector<pxWindowNative*>::iterator i; for (i = windowVector.begin(); i < windowVector.end(); i++) { pxWindowNative* w = (*i); if (w->mGlutWindowId == id) return w; } return NULL; } void pxWindowNative::onGlutReshape(int width, int height) { glViewport(0, 0, (GLint)width, (GLint)height); glUniform2f(u_resolution, width, height); pxWindowNative* w = getWindowFromGlutID(glutGetWindow()); if (w) w->onSize(width, height); } void pxWindowNative::onGlutDisplay() { pxWindowNative* w = getWindowFromGlutID(glutGetWindow()); if (w) w->drawFrame(); } void pxWindowNative::onGlutClose() { pxWindowNative* w = getWindowFromGlutID(glutGetWindow()); if (w) { unregisterWindow(w); w->onCloseRequest(); } } void pxWindowNative::onGlutTimer(int v) { #if 0 pxWindowNative* w = getWindowFromGlutID(glutGetWindow()); if (w) { w->onAnimationTimer(); glutTimerFunc(/*16*/ frame_ms, onGlutTimer, 0); } #else vector<pxWindowNative*> windowVector = pxWindow::getNativeWindows(); vector<pxWindowNative*>::iterator i; for (i = windowVector.begin(); i < windowVector.end(); i++) { pxWindowNative* w = (*i); glutSetWindow(w->mGlutWindowId); w->onAnimationTimer(); } glutTimerFunc(/*16*/ frame_ms, onGlutTimer, 0); #endif } void pxWindowNative::onGlutMouse(int button, int state, int x, int y) { unsigned long flags; if (button == GLUT_LEFT_BUTTON || button == GLUT_RIGHT_BUTTON) { if (button == GLUT_LEFT_BUTTON) flags = GLUT_LEFT_BUTTON; if (button == GLUT_RIGHT_BUTTON) flags = GLUT_RIGHT_BUTTON; pxWindowNative* w = getWindowFromGlutID(glutGetWindow()); if (w) { w->mMouseDown = (state == GLUT_DOWN); if (state == GLUT_DOWN) w->onMouseDown(x, y, flags); else { w->onMouseUp(x, y, flags); if (!w->mMouseEntered) { w->onMouseLeave(); } } } } else // some GLUT impls uses button 3,4 etc for mouse wheel if ((button == 3) || (button == 4)) // It's a wheel event { int dir = (button == 3) ? 1 : -1; pxWindowNative* w = getWindowFromGlutID(glutGetWindow()); if (w) w->onScrollWheel( dir * ((x > 0) ? 1 : -1), dir * ((y > 0) ? 1 : -1) ); } } // The second parameter gives the direction of the scroll. Values of +1 is forward, -1 is backward. void pxWindowNative::onGlutScrollWheel(int button, int dir, int x, int y) { if ((button == 3) || (button == 4)) // It's a wheel event { pxWindowNative* w = getWindowFromGlutID(glutGetWindow()); if (w) w->onScrollWheel(dir * x, dir * y); } } void pxWindowNative::onGlutMouseMotion(int x, int y) { pxWindowNative* w = getWindowFromGlutID(glutGetWindow()); if (w) w->onMouseMove(x,y); } void pxWindowNative::onGlutMousePassiveMotion(int x, int y) { pxWindowNative* w = getWindowFromGlutID(glutGetWindow()); if (w) { if (w->mMouseEntered) w->onMouseMove(x,y); } } void pxWindowNative::onGlutKeyboard(unsigned char key, int x, int y) { uint32_t unmodifiedKey = (uint32_t)key; uint32_t mappedKey = getRawNativeKeycodeFromGlut((uint32_t)key, glutGetModifiers()); uint32_t flags = 0; flags |= (glutGetModifiers() & GLUT_ACTIVE_SHIFT)?PX_MOD_SHIFT:0; flags |= (glutGetModifiers() & GLUT_ACTIVE_CTRL)?PX_MOD_CONTROL:0; flags |= (glutGetModifiers() & GLUT_ACTIVE_ALT)?PX_MOD_ALT:0; pxWindowNative* w = getWindowFromGlutID(glutGetWindow()); if (w) { // JR Did I mention Glut keyboard support is not very good w->onKeyDown(keycodeFromNative(mappedKey), flags); if (!iscntrl(unmodifiedKey)) w->onChar(unmodifiedKey); w->onKeyUp(keycodeFromNative(mappedKey), flags); } } void pxWindowNative::onGlutEntry(int state) { pxWindowNative* w = getWindowFromGlutID(glutGetWindow()); if (w) { w->mMouseEntered = (state != GLUT_LEFT); if (state == GLUT_LEFT) { if (!w->mMouseDown) // Eat here if dragging w->onMouseLeave(); } else w->onMouseEnter(); } } void pxWindowNative::onGlutKeyboardSpecial(int key, int x, int y) { int keycode = 0; uint32_t flags = 0; switch (key) { case GLUT_KEY_F1: keycode = PX_KEY_NATIVE_F1; break; case GLUT_KEY_F2: keycode = PX_KEY_NATIVE_F2; break; case GLUT_KEY_F3: keycode = PX_KEY_NATIVE_F3; break; case GLUT_KEY_F4: keycode = PX_KEY_NATIVE_F4; break; case GLUT_KEY_F5: keycode = PX_KEY_NATIVE_F5; break; case GLUT_KEY_F6: keycode = PX_KEY_NATIVE_F6; break; case GLUT_KEY_F7: keycode = PX_KEY_NATIVE_F7; break; case GLUT_KEY_F8: keycode = PX_KEY_NATIVE_F8; break; case GLUT_KEY_F9: keycode = PX_KEY_NATIVE_F9; break; case GLUT_KEY_F10: keycode = PX_KEY_NATIVE_F10; break; case GLUT_KEY_F11: keycode = PX_KEY_NATIVE_F11; break; case GLUT_KEY_F12: keycode = PX_KEY_NATIVE_F12; break; case GLUT_KEY_LEFT: keycode = PX_KEY_NATIVE_LEFT; break; case GLUT_KEY_UP: keycode = PX_KEY_NATIVE_UP; break; case GLUT_KEY_RIGHT: keycode = PX_KEY_NATIVE_RIGHT; break; case GLUT_KEY_DOWN: keycode = PX_KEY_NATIVE_DOWN; break; case GLUT_KEY_PAGE_UP: keycode = PX_KEY_NATIVE_PAGEUP; break; case GLUT_KEY_PAGE_DOWN: keycode = PX_KEY_NATIVE_PAGEDOWN; break; case GLUT_KEY_HOME: keycode = PX_KEY_NATIVE_HOME; break; case GLUT_KEY_END: keycode = PX_KEY_NATIVE_END; break; case GLUT_KEY_INSERT: keycode = PX_KEY_NATIVE_INSERT; break; case 112: // LEFT SHIFT (not defined in freeglut.h) flags |= PX_MOD_SHIFT; break; case 113: // RIGHT SHIFT (not defined in freeglut.h) flags |= PX_MOD_SHIFT; break; case 114: // CTRL (not defined in freeglut.h) flags |= PX_MOD_CONTROL; break; case 116: // ALT (not defined in freeglut.h) keycode = PX_KEY_NATIVE_ALT; break; default: printf("unknown special key: %d\n",key); } if(flags == 0) { flags |= (glutGetModifiers() & GLUT_ACTIVE_SHIFT)?PX_MOD_SHIFT:0; flags |= (glutGetModifiers() & GLUT_ACTIVE_CTRL)?PX_MOD_CONTROL:0; flags |= (glutGetModifiers() & GLUT_ACTIVE_ALT)?PX_MOD_ALT:0; } // printf("\n onGlutKeyboardSpecial() - key = %d (0x%0X) keycode = % d flags = %d PX_KEY_NATIVE_LEFT = %d\n", // key, key, keycode, flags, PX_KEY_NATIVE_LEFT); pxWindowNative* w = getWindowFromGlutID(glutGetWindow()); if (w) { // JR Did I mention Glut keyboard support is not very good w->onKeyDown(keycodeFromNative(keycode), flags); } } //end glut callbacks displayRef::displayRef() { if (mRefCount == 0) { mRefCount++; createGlutDisplay(); } else { mRefCount++; } } displayRef::~displayRef() { mRefCount--; if (mRefCount == 0) { cleanupGlutDisplay(); } } glutDisplay* displayRef::getDisplay() const { return mDisplay; } pxError displayRef::createGlutDisplay() { if (mDisplay == NULL) { mDisplay = new glutDisplay(); } int argc = 0; char **argv = NULL; glutInit(&argc, argv); return PX_OK; } void displayRef::cleanupGlutDisplay() { if (mDisplay != NULL) { delete mDisplay; } mDisplay = NULL; } bool exitFlag = false; pxWindowNative::~pxWindowNative() { } void pxWindowNative::createGlutWindow(int left, int top, int width, int height) { glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGBA /*| GLUT_DEPTH | GLUT_ALPHA*/); glutInitWindowPosition (left, top); glutInitWindowSize (width, height); mGlutWindowId = glutCreateWindow ("pxWindow"); #ifndef __APPLE__ glutSetOption(GLUT_RENDERING_CONTEXT ,GLUT_USE_CURRENT_CONTEXT ); #endif //doinit(); glClearColor(0, 0, 0, 1); } void pxWindowNative::cleanupGlutWindow() { // NOOP } pxError pxWindow::init(int left, int top, int width, int height) { glutDisplay* d = mDisplayRef.getDisplay(); if (d == NULL) { cout << "Error initializing display\n" << endl; return PX_FAIL; } else { // mLastWidth = width; // mLastHeight = height; // mResizeFlag = true; createGlutWindow(left,top,width,height); // XXX: Need to register callbacks after window is created glutDisplayFunc(onGlutDisplay); glutReshapeFunc(onGlutReshape); glutMouseFunc(onGlutMouse); glutMotionFunc(onGlutMouseMotion); glutMouseWheelFunc(onGlutScrollWheel); glutPassiveMotionFunc(onGlutMousePassiveMotion); glutKeyboardFunc(onGlutKeyboard); //#ifdef PX_USE_GLUT_ON_CLOSE glutWMCloseFunc(onGlutClose); //#endif glutSpecialFunc(onGlutKeyboardSpecial); glutEntryFunc(onGlutEntry); registerWindow(this); this->onCreate(); static bool glewInitialized = false; if (!glewInitialized) { #ifdef PX_USE_GLEW GLenum err = glewInit(); if (err != GLEW_OK) { cout << "error with glewInit()\n"; exit(1); // or handle the error in a nicer way } #endif glewInitialized = true; } } return PX_OK; } pxError pxWindow::term() { return PX_OK; } void pxWindow::invalidateRect(pxRect *r) { invalidateRectInternal(r); } // This can be improved by collecting the dirty regions and painting // when the event loop goes idle void pxWindowNative::invalidateRectInternal(pxRect *r) { drawFrame(); } bool pxWindow::visibility() { return mVisible; } void pxWindow::setVisibility(bool visible) { mVisible = visible; if (mVisible) { glutShowWindow(); } else { glutHideWindow(); } } pxError pxWindow::setAnimationFPS(uint32_t fps) { mTimerFPS = fps; frame_ms = ((1.0 / (double) mTimerFPS) * 1000.0); //mLastAnimationTime = pxMilliseconds(); return PX_OK; } void pxWindow::setTitle(const char* title) { glutSetWindowTitle(title); } pxError pxWindow::beginNativeDrawing(pxSurfaceNative& s) { //TODO return PX_OK; } pxError pxWindow::endNativeDrawing(pxSurfaceNative& s) { //TODO return PX_OK; } // pxWindowNative #if 0 void pxWindowNative::onAnimationTimerInternal() { if (mTimerFPS) { onAnimationTimer(); } } #endif // TODO this should be done better... static bool gTimerSet = false; void pxWindowNative::runEventLoop() { //glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS); glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION); exitFlag = false; if (!gTimerSet) { glutTimerFunc(32, onGlutTimer, 0); gTimerSet = true; } glutMainLoop(); } void pxWindowNative::runEventLoopOnce() { if (!gTimerSet) { glutTimerFunc(32, onGlutTimer, 0); gTimerSet = true; } // Can't do this in plain old glut #ifdef __APPLE__ glutCheckLoop(); // OSX glut extension #else glutMainLoopEvent(); // freeglut variant #endif } void pxWindowNative::exitEventLoop() { exitFlag = true; //#ifdef glutLeaveMainLoop glutLeaveMainLoop(); //#else // exit(0); //#endif } #if 0 void pxWindowNative::animateAndRender() { #if 0 static double lastAnimationTime = pxMilliseconds(); double currentAnimationTime = pxMilliseconds(); #endif drawFrame(); // double animationDelta = currentAnimationTime - lastAnimationTime; #if 0 if (mResizeFlag) { mResizeFlag = false; onSize(mLastWidth, mLastHeight); invalidateRectInternal(NULL); } #endif #if 0 if (mTimerFPS) { animationDelta = currentAnimationTime - getLastAnimationTime(); if (animationDelta > (1000/mTimerFPS)) { onAnimationTimerInternal(); setLastAnimationTime(currentAnimationTime); } } #endif } #endif #if 0 void pxWindowNative::setLastAnimationTime(double time) { mLastAnimationTime = time; } double pxWindowNative::getLastAnimationTime() { return mLastAnimationTime; } #endif void pxWindowNative::drawFrame() { #if 1 #if 0 pxSurfaceNativeDesc d; d.windowWidth = mLastWidth; d.windowHeight = mLastHeight; #endif onDraw(this); glutSwapBuffers(); #endif } void pxWindowNative::blit(pxBuffer& b, int32_t dstLeft, int32_t dstTop, int32_t dstWidth, int32_t dstHeight, int32_t srcLeft, int32_t srcTop) { #if 0 float x = dstLeft; float y = dstTop; float w = dstWidth; float h = dstHeight; const float verts[4][2] = { { x,y }, { x+w, y }, { x, y+h }, { x+w, y+h } }; const float uv[4][2] = { { 0, 0 }, { 1.0, 0 }, { 0, 1.0 }, { 1.0, 1.0 } }; { // leaky GLuint mTextureName; glActiveTexture(GL_TEXTURE0); glGenTextures(1, &mTextureName); glBindTexture(GL_TEXTURE_2D, mTextureName); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glPixelStorei(GL_UNPACK_ALIGNMENT, 4); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, b.width(), b.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, b.base()); glUniform1i(u_texture, 0); glVertexAttribPointer(attr_pos, 2, GL_FLOAT, GL_FALSE, 0, verts); glVertexAttribPointer(attr_uv, 2, GL_FLOAT, GL_FALSE, 0, uv); glEnableVertexAttribArray(attr_pos); glEnableVertexAttribArray(attr_uv); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glDisableVertexAttribArray(attr_pos); glDisableVertexAttribArray(attr_uv); } #endif } void pxWindowNative::registerWindow(pxWindowNative* p) { mWindowVector.push_back(p); } void pxWindowNative::unregisterWindow(pxWindowNative* p) { vector<pxWindowNative*>::iterator i; for (i = mWindowVector.begin(); i < mWindowVector.end(); i++) { if ((*i) == p) { mWindowVector.erase(i); return; } } } uint32_t getRawNativeKeycodeFromGlut(uint32_t key, uint32_t modifiers) { //glut doesn't support keycodes. we do some mappings here key = tolower(key); bool shiftPressed = (glutGetModifiers() & GLUT_ACTIVE_SHIFT); bool ctrlPressed = (glutGetModifiers() & GLUT_ACTIVE_CTRL); //bool altPressed = (glutGetModifiers() & GLUT_ACTIVE_ALT); // printf("\n### getRawNativeKeycodeFromGlut() - key = %d shiftPressed = %d ",key, shiftPressed); uint32_t rawKeycode = key; if (ctrlPressed) { switch (rawKeycode) { case 1: rawKeycode = 'a'; break; case 2: rawKeycode = 'b'; break; case 3: rawKeycode = 'c'; break; case 4: rawKeycode = 'd'; break; case 5: rawKeycode = 'e'; break; case 6: rawKeycode = 'f'; break; case 7: rawKeycode = 'g'; break; case 8: rawKeycode = 'h'; break; case 9: rawKeycode = 'i'; break; case 10: rawKeycode = 'j'; break; case 11: rawKeycode = 'k'; break; case 12: rawKeycode = 'l'; break; case 13: rawKeycode = 'm'; break; case 14: rawKeycode = 'n'; break; case 15: rawKeycode = 'o'; break; case 16: rawKeycode = 'p'; break; case 17: rawKeycode = 'q'; break; case 18: rawKeycode = 'r'; break; case 19: rawKeycode = 's'; break; case 20: rawKeycode = 't'; break; case 21: rawKeycode = 'u'; break; case 22: rawKeycode = 'v'; break; case 23: rawKeycode = 'w'; break; case 24: rawKeycode = 'x'; break; case 25: rawKeycode = 'y'; break; case 26: rawKeycode = 'z'; break; } } if (shiftPressed) { switch (rawKeycode) { case 33: rawKeycode = '1'; break; case 64: rawKeycode = '2'; break; case 35: rawKeycode = '3'; break; case 36: rawKeycode = '4'; break; case 37: rawKeycode = '5'; break; case 94: rawKeycode = '6'; break; case 38: rawKeycode = '7'; break; case 42: rawKeycode = '8'; break; case 40: rawKeycode = '9'; break; case 41: rawKeycode = '0'; break; case 95: rawKeycode = '-'; break; case 43: rawKeycode = '='; break; } } return rawKeycode; }
21.951896
118
0.647872
protey7
3c5af01909eacd873c1a83b59f52de3af5b128e2
3,604
cc
C++
ui/views/view_targeter.cc
domenic/mojo
53dda76fed90a47c35ed6e06baf833a0d44495b8
[ "BSD-3-Clause" ]
5
2019-05-24T01:25:34.000Z
2020-04-06T05:07:01.000Z
ui/views/view_targeter.cc
domenic/mojo
53dda76fed90a47c35ed6e06baf833a0d44495b8
[ "BSD-3-Clause" ]
null
null
null
ui/views/view_targeter.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/views/view_targeter.h" #include "ui/events/event_target.h" #include "ui/views/focus/focus_manager.h" #include "ui/views/view.h" #include "ui/views/view_targeter_delegate.h" namespace views { ViewTargeter::ViewTargeter(ViewTargeterDelegate* delegate) : delegate_(delegate) { DCHECK(delegate_); } ViewTargeter::~ViewTargeter() {} bool ViewTargeter::DoesIntersectRect(const View* target, const gfx::Rect& rect) const { return delegate_->DoesIntersectRect(target, rect); } View* ViewTargeter::TargetForRect(View* root, const gfx::Rect& rect) const { return delegate_->TargetForRect(root, rect); } ui::EventTarget* ViewTargeter::FindTargetForEvent(ui::EventTarget* root, ui::Event* event) { View* view = static_cast<View*>(root); if (event->IsKeyEvent()) return FindTargetForKeyEvent(view, *static_cast<ui::KeyEvent*>(event)); if (event->IsScrollEvent()) { return FindTargetForScrollEvent(view, *static_cast<ui::ScrollEvent*>(event)); } if (event->IsGestureEvent()) { ui::GestureEvent* gesture = event->AsGestureEvent(); View* gesture_target = FindTargetForGestureEvent(view, *gesture); root->ConvertEventToTarget(gesture_target, gesture); return gesture_target; } NOTREACHED() << "ViewTargeter does not yet support this event type."; return NULL; } ui::EventTarget* ViewTargeter::FindNextBestTarget( ui::EventTarget* previous_target, ui::Event* event) { if (!previous_target) return NULL; if (event->IsGestureEvent()) { ui::GestureEvent* gesture = event->AsGestureEvent(); ui::EventTarget* next_target = FindNextBestTargetForGestureEvent(previous_target, *gesture); previous_target->ConvertEventToTarget(next_target, gesture); return next_target; } return previous_target->GetParentTarget(); } bool ViewTargeter::SubtreeCanAcceptEvent( ui::EventTarget* target, const ui::LocatedEvent& event) const { NOTREACHED(); return false; } bool ViewTargeter::EventLocationInsideBounds( ui::EventTarget* target, const ui::LocatedEvent& event) const { NOTREACHED(); return false; } View* ViewTargeter::FindTargetForKeyEvent(View* root, const ui::KeyEvent& key) { if (root->GetFocusManager()) return root->GetFocusManager()->GetFocusedView(); return NULL; } View* ViewTargeter::FindTargetForScrollEvent(View* root, const ui::ScrollEvent& scroll) { gfx::Rect rect(scroll.location(), gfx::Size(1, 1)); return root->GetEffectiveViewTargeter()->TargetForRect(root, rect); } View* ViewTargeter::FindTargetForGestureEvent(View* root, const ui::GestureEvent& gesture) { // TODO(tdanderson): The only code path that performs targeting for gestures // uses the ViewTargeter installed on the RootView (i.e., // a RootViewTargeter). Provide a default implementation // here if we need to be able to perform gesture targeting // starting at an arbitrary node in a Views tree. NOTREACHED(); return NULL; } ui::EventTarget* ViewTargeter::FindNextBestTargetForGestureEvent( ui::EventTarget* previous_target, const ui::GestureEvent& gesture) { NOTREACHED(); return NULL; } } // namespace views
31.33913
80
0.675361
domenic
3c5db36a85222d394f0cd4ceb37fc551de360fd0
453
hpp
C++
src/engine/window/Surface.hpp
Lothav/volkano
b345091e4066727ca5cf72111453c0f6a82285a3
[ "MIT" ]
null
null
null
src/engine/window/Surface.hpp
Lothav/volkano
b345091e4066727ca5cf72111453c0f6a82285a3
[ "MIT" ]
null
null
null
src/engine/window/Surface.hpp
Lothav/volkano
b345091e4066727ca5cf72111453c0f6a82285a3
[ "MIT" ]
null
null
null
// // Created by luiz0tavio on 8/30/18. // #ifndef VOLKANO_SURFACE_HPP #define VOLKANO_SURFACE_HPP #include <cstdint> #include <vulkan/vulkan.h> namespace vkn { class Surface { private: static uint16_t width; static uint16_t height; static VkSurfaceKHR surface; public: Surface() = delete; static void init(); static void destroy(); }; } #endif //VOLKANO_SURFACE_HPP
13.727273
36
0.615894
Lothav
3c5e22d0b16e634d792c74f13155d36f1c86251d
6,273
cpp
C++
lib/VM/detail/IdentifierHashTable.cpp
exced/hermes
c53fbe3f27677d5cda2a0c5b4e79e429eb5cd9e6
[ "MIT" ]
2
2020-02-09T21:47:10.000Z
2021-07-13T09:27:33.000Z
lib/VM/detail/IdentifierHashTable.cpp
exced/hermes
c53fbe3f27677d5cda2a0c5b4e79e429eb5cd9e6
[ "MIT" ]
6
2021-03-11T07:21:46.000Z
2022-02-27T11:15:48.000Z
lib/VM/detail/IdentifierHashTable.cpp
exced/hermes
c53fbe3f27677d5cda2a0c5b4e79e429eb5cd9e6
[ "MIT" ]
2
2020-10-25T04:11:10.000Z
2020-10-25T04:11:11.000Z
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "hermes/VM/detail/IdentifierHashTable.h" #include "hermes/VM/Deserializer.h" #include "hermes/VM/Serializer.h" #include "hermes/VM/StringPrimitive.h" using namespace hermes::vm::detail; // In GCC/CLANG, method definitions can refer to ancestor namespaces of // the namespace that the class is declared in without namespace qualifiers. // This is not allowed in MSVC. #ifdef HERMESVM_SERIALIZE using hermes::vm::Deserializer; using hermes::vm::Serializer; #endif using hermes::vm::StringPrimitive; using hermes::vm::SymbolID; template <typename T> uint32_t IdentifierHashTable::lookupString( llvm::ArrayRef<T> str, uint32_t hash, bool mustBeNew) const { assert(identifierTable_ && "identifier table pointer is not initialized"); auto cap = capacity(); assert(llvm::isPowerOf2_32(cap) && "capacity must be power of 2"); assert(size_ < cap && "The hash table can never be full"); #ifdef HERMES_SLOW_DEBUG assert(hash == hashString(str) && "invalid hash"); #endif uint32_t idx = hash & (cap - 1); uint32_t base = 1; // deletedIndex tracks the index of a deleted entry found in the conflict // chain. If we could not find an entry that matches str, we would return // the deleted slot for insertion to be able to reuse deleted space. OptValue<uint32_t> deletedIndex; // The loop will always terminate as long as the hash table is not full. while (1) { if (table_.isEmpty(idx)) { // Found an empty entry, meaning that str does not exist in the table. // If deletedIndex is available, return it, otherwise return idx. return deletedIndex ? *deletedIndex : idx; } else if (table_.isDeleted(idx)) { assert( !mustBeNew && "mustBeNew should never be set if there are deleted entries"); deletedIndex = idx; } else if (!mustBeNew) { // If mustBeNew is set, we know this string does not exist in the table. // There is no need to compare. auto &lookupTableEntry = identifierTable_->getLookupTableEntry(table_.get(idx)); if (lookupTableEntry.getHash() == hash) { if (lookupTableEntry.isStringPrim()) { const StringPrimitive *strPrim = lookupTableEntry.getStringPrim(); if (strPrim->isASCII()) { if (stringRefEquals(str, strPrim->castToASCIIRef())) { return idx; } } else { if (stringRefEquals(str, strPrim->castToUTF16Ref())) { return idx; } } } else if (lookupTableEntry.isLazyASCII()) { // Lazy ASCII string. if (stringRefEquals(str, lookupTableEntry.getLazyASCIIRef())) { return idx; } } else { // UTF16 string. if (stringRefEquals(str, lookupTableEntry.getLazyUTF16Ref())) { return idx; } } } } /// Use quadratic probing to find next probe index in the hash table. /// h(k, i) = (h(k) + 1/2 * i + 1/2 * i^2) mod m. /// This guarantees the values of h(k,i) for i in [0,m-1] are all distinct. idx = (idx + base) & (cap - 1); ++base; } } // Instantiate the templated method so it can be called from other files. template uint32_t IdentifierHashTable::lookupString( llvm::ArrayRef<char> str, uint32_t hash, bool mustBeNew) const; template uint32_t IdentifierHashTable::lookupString( llvm::ArrayRef<char16_t> str, uint32_t hash, bool mustBeNew) const; uint32_t IdentifierHashTable::lookupString( const StringPrimitive *str, bool mustBeNew) const { if (str->isASCII()) { return lookupString(str->castToASCIIRef(), mustBeNew); } else { return lookupString(str->castToUTF16Ref(), mustBeNew); } } uint32_t IdentifierHashTable::lookupString( const StringPrimitive *str, uint32_t hash, bool mustBeNew) const { if (str->isASCII()) { return lookupString(str->castToASCIIRef(), hash, mustBeNew); } else { return lookupString(str->castToUTF16Ref(), hash, mustBeNew); } } void IdentifierHashTable::insert(uint32_t idx, SymbolID id) { table_.set(idx, id.unsafeGetIndex()); ++size_; ++nonEmptyEntryCount_; if (shouldGrow()) { growAndRehash(capacity() * 2); } } void IdentifierHashTable::remove(const StringPrimitive *str) { if (str->isASCII()) { remove(str->castToASCIIRef()); } else { remove(str->castToUTF16Ref()); } } void IdentifierHashTable::growAndRehash(uint32_t newCapacity) { assert(llvm::isPowerOf2_32(newCapacity) && "capacity must be power of 2"); CompactTable tmpTable(newCapacity, table_.getCurrentScale()); tmpTable.swap(table_); for (uint32_t oldIdx = 0; oldIdx < tmpTable.size(); ++oldIdx) { if (!tmpTable.isValid(oldIdx)) { continue; } // Pass true as second argument as we know this string is not in the table. uint32_t idx = 0; uint32_t oldVal = tmpTable.get(oldIdx); auto &lookupTableEntry = identifierTable_->getLookupTableEntry(oldVal); uint32_t hash = lookupTableEntry.getHash(); if (lookupTableEntry.isStringPrim()) { idx = lookupString(lookupTableEntry.getStringPrim(), hash, true); } else if (lookupTableEntry.isLazyASCII()) { idx = lookupString(lookupTableEntry.getLazyASCIIRef(), hash, true); } else if (lookupTableEntry.isLazyUTF16()) { idx = lookupString(lookupTableEntry.getLazyUTF16Ref(), hash, true); } table_.set(idx, oldVal); } nonEmptyEntryCount_ = size_; } #ifdef HERMESVM_SERIALIZE void IdentifierHashTable::serialize(Serializer &s) { // Serialize uint32_t size_{0}; s.writeInt<uint32_t>(size_); // Serialize uint32_t nonEmptyEntryCount_{0}; s.writeInt<uint32_t>(nonEmptyEntryCount_); // We don't serialize IdentifierTable *identifierTable_{}; // It is set by constructor, don't need to change. // Serialize CompactTable table_; s.serializeCompactTable(table_); } void IdentifierHashTable::deserialize(Deserializer &d) { size_ = d.readInt<uint32_t>(); nonEmptyEntryCount_ = d.readInt<uint32_t>(); d.deserializeCompactTable(table_); } #endif
32.671875
79
0.675753
exced
3c6204b4ea6f6b6004a5f14ff9f6460a02e0c21f
5,273
cc
C++
chromium/chrome/browser/plugins/plugin_installer.cc
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
chromium/chrome/browser/plugins/plugin_installer.cc
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
chromium/chrome/browser/plugins/plugin_installer.cc
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/plugins/plugin_installer.h" #include <utility> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/process/process.h" #include "base/strings/stringprintf.h" #include "chrome/browser/download/download_stats.h" #include "chrome/browser/platform_util.h" #include "chrome/browser/plugins/plugin_installer_observer.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/download_item.h" #include "content/public/browser/download_manager.h" #include "content/public/browser/download_url_parameters.h" #include "content/public/browser/web_contents.h" using content::DownloadItem; PluginInstaller::PluginInstaller() : state_(INSTALLER_STATE_IDLE), strong_observer_count_(0) { } PluginInstaller::~PluginInstaller() { } void PluginInstaller::OnDownloadUpdated(DownloadItem* download) { DownloadItem::DownloadState state = download->GetState(); switch (state) { case DownloadItem::IN_PROGRESS: return; case DownloadItem::COMPLETE: { DCHECK_EQ(INSTALLER_STATE_DOWNLOADING, state_); state_ = INSTALLER_STATE_IDLE; FOR_EACH_OBSERVER(PluginInstallerObserver, observers_, DownloadFinished()); break; } case DownloadItem::CANCELLED: { DownloadCancelled(); break; } case DownloadItem::INTERRUPTED: { content::DownloadInterruptReason reason = download->GetLastReason(); DownloadError(content::DownloadInterruptReasonToString(reason)); break; } case DownloadItem::MAX_DOWNLOAD_STATE: { NOTREACHED(); return; } } download->RemoveObserver(this); } void PluginInstaller::OnDownloadDestroyed(DownloadItem* download) { DCHECK_EQ(INSTALLER_STATE_DOWNLOADING, state_); state_ = INSTALLER_STATE_IDLE; download->RemoveObserver(this); } void PluginInstaller::AddObserver(PluginInstallerObserver* observer) { strong_observer_count_++; observers_.AddObserver(observer); } void PluginInstaller::RemoveObserver(PluginInstallerObserver* observer) { strong_observer_count_--; observers_.RemoveObserver(observer); if (strong_observer_count_ == 0) { FOR_EACH_OBSERVER(WeakPluginInstallerObserver, weak_observers_, OnlyWeakObserversLeft()); } } void PluginInstaller::AddWeakObserver(WeakPluginInstallerObserver* observer) { weak_observers_.AddObserver(observer); } void PluginInstaller::RemoveWeakObserver( WeakPluginInstallerObserver* observer) { weak_observers_.RemoveObserver(observer); } void PluginInstaller::StartInstalling(const GURL& plugin_url, content::WebContents* web_contents) { content::DownloadManager* download_manager = content::BrowserContext::GetDownloadManager( web_contents->GetBrowserContext()); StartInstallingWithDownloadManager( plugin_url, web_contents, download_manager); } void PluginInstaller::StartInstallingWithDownloadManager( const GURL& plugin_url, content::WebContents* web_contents, content::DownloadManager* download_manager) { DCHECK_EQ(INSTALLER_STATE_IDLE, state_); state_ = INSTALLER_STATE_DOWNLOADING; FOR_EACH_OBSERVER(PluginInstallerObserver, observers_, DownloadStarted()); scoped_ptr<content::DownloadUrlParameters> download_parameters( content::DownloadUrlParameters::FromWebContents(web_contents, plugin_url)); download_parameters->set_callback( base::Bind(&PluginInstaller::DownloadStarted, base::Unretained(this))); RecordDownloadSource(DOWNLOAD_INITIATED_BY_PLUGIN_INSTALLER); download_manager->DownloadUrl(std::move(download_parameters)); } void PluginInstaller::DownloadStarted( content::DownloadItem* item, content::DownloadInterruptReason interrupt_reason) { if (interrupt_reason != content::DOWNLOAD_INTERRUPT_REASON_NONE) { std::string msg = base::StringPrintf( "Error %d: %s", interrupt_reason, content::DownloadInterruptReasonToString(interrupt_reason).c_str()); DownloadError(msg); return; } item->SetOpenWhenComplete(true); item->AddObserver(this); } void PluginInstaller::OpenDownloadURL(const GURL& plugin_url, content::WebContents* web_contents) { DCHECK_EQ(INSTALLER_STATE_IDLE, state_); web_contents->OpenURL(content::OpenURLParams( plugin_url, content::Referrer(web_contents->GetURL(), blink::WebReferrerPolicyDefault), NEW_FOREGROUND_TAB, ui::PAGE_TRANSITION_TYPED, false)); FOR_EACH_OBSERVER(PluginInstallerObserver, observers_, DownloadFinished()); } void PluginInstaller::DownloadError(const std::string& msg) { DCHECK_EQ(INSTALLER_STATE_DOWNLOADING, state_); state_ = INSTALLER_STATE_IDLE; FOR_EACH_OBSERVER(PluginInstallerObserver, observers_, DownloadError(msg)); } void PluginInstaller::DownloadCancelled() { DCHECK_EQ(INSTALLER_STATE_DOWNLOADING, state_); state_ = INSTALLER_STATE_IDLE; FOR_EACH_OBSERVER(PluginInstallerObserver, observers_, DownloadCancelled()); }
34.690789
78
0.744358
wedataintelligence
3c62df3e20baca7d3405ea225b064b4f5291c0b9
5,915
cpp
C++
Engine/Source/ThirdParty/PhysX/APEX_1.4/common/src/ApexMeshHash.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Source/ThirdParty/PhysX/APEX_1.4/common/src/ApexMeshHash.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Source/ThirdParty/PhysX/APEX_1.4/common/src/ApexMeshHash.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
/* * Copyright (c) 2008-2017, NVIDIA CORPORATION. All rights reserved. * * NVIDIA CORPORATION and its licensors retain all intellectual property * and proprietary rights in and to this software, related documentation * and any modifications thereto. Any use, reproduction, disclosure or * distribution of this software and related documentation without an express * license agreement from NVIDIA CORPORATION is strictly prohibited. */ #include "ApexMeshHash.h" #include "PxBounds3.h" #include "PsSort.h" namespace nvidia { namespace apex { ApexMeshHash::ApexMeshHash() : mHashIndex(NULL) { mHashIndex = (MeshHashRoot*)PX_ALLOC(sizeof(MeshHashRoot) * HashIndexSize, PX_DEBUG_EXP("ApexMeshHash")); mTime = 1; for (uint32_t i = 0; i < HashIndexSize; i++) { mHashIndex[i].first = -1; mHashIndex[i].timeStamp = 0; } mSpacing = 0.25f; mInvSpacing = 1.0f / mSpacing; } ApexMeshHash::~ApexMeshHash() { if (mHashIndex != NULL) { PX_FREE(mHashIndex); mHashIndex = NULL; } } void ApexMeshHash::setGridSpacing(float spacing) { mSpacing = spacing; mInvSpacing = 1.0f / spacing; reset(); } void ApexMeshHash::reset() { mTime++; mEntries.clear(); } void ApexMeshHash::add(const PxBounds3& bounds, uint32_t itemIndex) { int32_t x1, y1, z1; int32_t x2, y2, z2; cellCoordOf(bounds.minimum, x1, y1, z1); cellCoordOf(bounds.maximum, x2, y2, z2); MeshHashEntry entry; entry.itemIndex = itemIndex; for (int32_t x = x1; x <= x2; x++) { for (int32_t y = y1; y <= y2; y++) { for (int32_t z = z1; z <= z2; z++) { uint32_t h = hashFunction(x, y, z); MeshHashRoot& r = mHashIndex[h]; uint32_t n = mEntries.size(); if (r.timeStamp != mTime || r.first < 0) { entry.next = -1; } else { entry.next = r.first; } r.first = (int32_t)n; r.timeStamp = mTime; mEntries.pushBack(entry); } } } } void ApexMeshHash::add(const PxVec3& pos, uint32_t itemIndex) { int x, y, z; cellCoordOf(pos, x, y, z); MeshHashEntry entry; entry.itemIndex = itemIndex; uint32_t h = hashFunction(x, y, z); MeshHashRoot& r = mHashIndex[h]; uint32_t n = mEntries.size(); if (r.timeStamp != mTime || r.first < 0) { entry.next = -1; } else { entry.next = r.first; } r.first = (int32_t)n; r.timeStamp = mTime; mEntries.pushBack(entry); } void ApexMeshHash::query(const PxBounds3& bounds, physx::Array<uint32_t>& itemIndices, int32_t maxIndices) { int32_t x1, y1, z1; int32_t x2, y2, z2; cellCoordOf(bounds.minimum, x1, y1, z1); cellCoordOf(bounds.maximum, x2, y2, z2); itemIndices.clear(); for (int32_t x = x1; x <= x2; x++) { for (int32_t y = y1; y <= y2; y++) { for (int32_t z = z1; z <= z2; z++) { uint32_t h = hashFunction(x, y, z); MeshHashRoot& r = mHashIndex[h]; if (r.timeStamp != mTime) { continue; } int32_t i = r.first; while (i >= 0) { MeshHashEntry& entry = mEntries[(uint32_t)i]; itemIndices.pushBack(entry.itemIndex); if (maxIndices >= 0 && itemIndices.size() >= (uint32_t)maxIndices) { return; } i = entry.next; } } } } } void ApexMeshHash::queryUnique(const PxBounds3& bounds, physx::Array<uint32_t>& itemIndices, int32_t maxIndices) { query(bounds, itemIndices, maxIndices); compressIndices(itemIndices); } void ApexMeshHash::query(const PxVec3& pos, physx::Array<uint32_t>& itemIndices, int32_t maxIndices) { int32_t x, y, z; cellCoordOf(pos, x, y, z); itemIndices.clear(); uint32_t h = hashFunction(x, y, z); MeshHashRoot& r = mHashIndex[h]; if (r.timeStamp != mTime) { return; } int32_t i = r.first; while (i >= 0) { MeshHashEntry& entry = mEntries[(uint32_t)i]; itemIndices.pushBack(entry.itemIndex); if (maxIndices >= 0 && itemIndices.size() >= (uint32_t)maxIndices) { return; } i = entry.next; } } void ApexMeshHash::queryUnique(const PxVec3& pos, physx::Array<uint32_t>& itemIndices, int32_t maxIndices) { query(pos, itemIndices, maxIndices); compressIndices(itemIndices); } class U32Less { public: bool operator()(uint32_t u1, uint32_t u2) const { return u1 < u2; } }; void ApexMeshHash::compressIndices(physx::Array<uint32_t>& itemIndices) { if (itemIndices.empty()) { return; } shdfnd::sort(itemIndices.begin(), itemIndices.size(), U32Less()); // mark duplicates uint32_t i = 0; while (i < itemIndices.size()) { uint32_t j = i + 1; while (j < itemIndices.size() && itemIndices[i] == itemIndices[j]) { itemIndices[j] = (uint32_t) - 1; j++; } i = j; } // remove duplicates i = 0; while (i < itemIndices.size()) { if (itemIndices[i] == (uint32_t)-1) { itemIndices.replaceWithLast(i); } else { i++; } } } int32_t ApexMeshHash::getClosestPointNr(const PxVec3* points, uint32_t numPoints, uint32_t pointStride, const PxVec3& pos) { PX_ASSERT(numPoints > 0); PxBounds3 queryBounds; queryBounds.minimum = pos; queryBounds.maximum = pos; PX_ASSERT(!queryBounds.isEmpty()); queryBounds.fattenFast(mSpacing); query(queryBounds, mTempIndices); // remove false positives due to hash collisions uint32_t next = 0; for (uint32_t i = 0; i < mTempIndices.size(); i++) { uint32_t pointNr = mTempIndices[i]; const PxVec3* p = (PxVec3*)((uint8_t*)points + (pointNr * pointStride)); if (pointNr < numPoints && queryBounds.contains(*p)) { mTempIndices[next++] = pointNr; } } mTempIndices.resize(next); bool fallBack = mTempIndices.size() == 0; uint32_t numRes = fallBack ? numPoints : mTempIndices.size(); float min2 = 0.0f; int minNr = -1; for (uint32_t j = 0; j < numRes; j++) { uint32_t k = fallBack ? j : mTempIndices[j]; const PxVec3* p = (PxVec3*)((uint8_t*)points + (k * pointStride)); float d2 = (pos - *p).magnitudeSquared(); if (minNr < 0 || d2 < min2) { min2 = d2; minNr = (int32_t)k; } } return minNr; } } } // end namespace nvidia::apex
19.848993
122
0.65224
windystrife
3c6b9e29ecbcfa8cb09c1a52a24adc71ac377dfc
507
cpp
C++
AIC/AIC'20 - Level 1 Training/Sheet #3/E.cpp
MaGnsio/CP-Problems
a7f518a20ba470f554b6d54a414b84043bf209c5
[ "Unlicense" ]
3
2020-11-01T06:31:30.000Z
2022-02-21T20:37:51.000Z
AIC/AIC'20 - Level 1 Training/Sheet #3/E.cpp
MaGnsio/CP-Problems
a7f518a20ba470f554b6d54a414b84043bf209c5
[ "Unlicense" ]
null
null
null
AIC/AIC'20 - Level 1 Training/Sheet #3/E.cpp
MaGnsio/CP-Problems
a7f518a20ba470f554b6d54a414b84043bf209c5
[ "Unlicense" ]
1
2021-05-05T18:56:31.000Z
2021-05-05T18:56:31.000Z
//https://codeforces.com/group/Rv2Qzg0DgK/contest/272491/problem/E #include <bits/stdc++.h> using namespace std; #define F first #define S second typedef long long ll; typedef long double ld; ll mod = 1e9 + 7; int main () { ios_base::sync_with_stdio (0); cin.tie (0); cout.tie (0); int n; cin >> n; vector<int> v(n); for (auto& elem : v) cin >> elem; int mi = *(min_element (v.begin (), v.end ())); int idx = distance (v.begin (), find (v.begin (), v.end (), mi)); cout << mi << " " << idx + 1; }
24.142857
66
0.617357
MaGnsio
3c721e2350479e5bd1ad28f3110b34e6313463bf
47,440
inl
C++
include/bolt/cl/detail/transform.inl
jayavanth/Bolt
ea1045126efc060c56f43eef926d65490bca7375
[ "BSL-1.0" ]
1
2016-11-29T21:03:54.000Z
2016-11-29T21:03:54.000Z
include/bolt/cl/detail/transform.inl
jayavanth/Bolt
ea1045126efc060c56f43eef926d65490bca7375
[ "BSL-1.0" ]
null
null
null
include/bolt/cl/detail/transform.inl
jayavanth/Bolt
ea1045126efc060c56f43eef926d65490bca7375
[ "BSL-1.0" ]
null
null
null
/*************************************************************************** * Copyright 2012 - 2013 Advanced Micro Devices, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ***************************************************************************/ #pragma once #if !defined( BOLT_CL_TRANSFORM_INL ) #define BOLT_CL_TRANSFORM_INL #define WAVEFRONT_SIZE 64 #define TRANSFORM_ENABLE_PROFILING 0 #include <type_traits> #ifdef ENABLE_TBB #include "bolt/btbb/transform.h" #endif #include "bolt/cl/bolt.h" #include "bolt/cl/device_vector.h" #include "bolt/cl/iterator/iterator_traits.h" namespace bolt { namespace cl { namespace detail { enum TransformTypes {transform_iType1, transform_DVInputIterator1, transform_iType2, transform_DVInputIterator2, transform_oTypeB,transform_DVOutputIteratorB, transform_BinaryFunction, transform_endB }; enum TransformUnaryTypes {transform_iType, transform_DVInputIterator, transform_oTypeU, transform_DVOutputIteratorU, transform_UnaryFunction, transform_endU }; class Transform_KernelTemplateSpecializer : public KernelTemplateSpecializer { public: Transform_KernelTemplateSpecializer() : KernelTemplateSpecializer() { addKernelName("transformTemplate"); addKernelName("transformNoBoundsCheckTemplate"); } const ::std::string operator() ( const ::std::vector< ::std::string>& binaryTransformKernels ) const { const std::string templateSpecializationString = "// Host generates this instantiation string with user-specified value type and functor\n" "template __attribute__((mangled_name("+name(0)+"Instantiated)))\n" "kernel void "+name(0)+"(\n" "global " + binaryTransformKernels[transform_iType1] + "* A_ptr,\n" + binaryTransformKernels[transform_DVInputIterator1] + " A_iter,\n" "global " + binaryTransformKernels[transform_iType2] + "* B_ptr,\n" + binaryTransformKernels[transform_DVInputIterator2] + " B_iter,\n" "global " + binaryTransformKernels[transform_oTypeB] + "* Z_ptr,\n" + binaryTransformKernels[transform_DVOutputIteratorB] + " Z_iter,\n" "const uint length,\n" "global " + binaryTransformKernels[transform_BinaryFunction] + "* userFunctor);\n\n" "// Host generates this instantiation string with user-specified value type and functor\n" "template __attribute__((mangled_name("+name(1)+"Instantiated)))\n" "kernel void "+name(1)+"(\n" "global " + binaryTransformKernels[transform_iType1] + "* A_ptr,\n" + binaryTransformKernels[transform_DVInputIterator1] + " A_iter,\n" "global " + binaryTransformKernels[transform_iType2] + "* B_ptr,\n" + binaryTransformKernels[transform_DVInputIterator2] + " B_iter,\n" "global " + binaryTransformKernels[transform_oTypeB] + "* Z_ptr,\n" + binaryTransformKernels[transform_DVOutputIteratorB] + " Z_iter,\n" "const uint length,\n" "global " + binaryTransformKernels[transform_BinaryFunction] + "* userFunctor);\n\n"; return templateSpecializationString; } }; class TransformUnary_KernelTemplateSpecializer : public KernelTemplateSpecializer { public: TransformUnary_KernelTemplateSpecializer() : KernelTemplateSpecializer() { addKernelName("unaryTransformTemplate"); addKernelName("unaryTransformNoBoundsCheckTemplate"); } const ::std::string operator() ( const ::std::vector< ::std::string>& unaryTransformKernels ) const { const std::string templateSpecializationString = "// Host generates this instantiation string with user-specified value type and functor\n" "template __attribute__((mangled_name("+name( 0 )+"Instantiated)))\n" "kernel void unaryTransformTemplate(\n" "global " + unaryTransformKernels[transform_iType] + "* A,\n" + unaryTransformKernels[transform_DVInputIterator] + " A_iter,\n" "global " + unaryTransformKernels[transform_oTypeU] + "* Z,\n" + unaryTransformKernels[transform_DVOutputIteratorU] + " Z_iter,\n" "const uint length,\n" "global " + unaryTransformKernels[transform_UnaryFunction] + "* userFunctor);\n\n" "// Host generates this instantiation string with user-specified value type and functor\n" "template __attribute__((mangled_name("+name(1)+"Instantiated)))\n" "kernel void unaryTransformNoBoundsCheckTemplate(\n" "global " + unaryTransformKernels[transform_iType] + "* A,\n" + unaryTransformKernels[transform_DVInputIterator] + " A_iter,\n" "global " + unaryTransformKernels[transform_oTypeU] + "* Z,\n" + unaryTransformKernels[transform_DVOutputIteratorU] + " Z_iter,\n" "const uint length,\n" "global " +unaryTransformKernels[transform_UnaryFunction] + "* userFunctor);\n\n"; return templateSpecializationString; } }; template<typename DVInputIterator1, typename DVInputIterator2, typename DVOutputIterator, typename BinaryFunction> void transform_enqueue( bolt::cl::control &ctl, const DVInputIterator1& first1, const DVInputIterator1& last1, const DVInputIterator2& first2, const DVOutputIterator& result, const BinaryFunction& f, const std::string& cl_code) { typedef typename std::iterator_traits<DVInputIterator1>::value_type iType1; typedef typename std::iterator_traits<DVInputIterator2>::value_type iType2; typedef typename std::iterator_traits<DVOutputIterator>::value_type oType; cl_uint distVec = static_cast< cl_uint >( first1.distance_to(last1) ); if( distVec == 0 ) return; const size_t numComputeUnits = ctl.getDevice( ).getInfo< CL_DEVICE_MAX_COMPUTE_UNITS >( ); const size_t numWorkGroupsPerComputeUnit = ctl.getWGPerComputeUnit( ); size_t numWorkGroups = numComputeUnits * numWorkGroupsPerComputeUnit; /********************************************************************************** * Type Names - used in KernelTemplateSpecializer *********************************************************************************/ std::vector<std::string> binaryTransformKernels(transform_endB); binaryTransformKernels[transform_iType1] = TypeName< iType1 >::get( ); binaryTransformKernels[transform_iType2] = TypeName< iType2 >::get( ); binaryTransformKernels[transform_DVInputIterator1] = TypeName< DVInputIterator1 >::get( ); binaryTransformKernels[transform_DVInputIterator2] = TypeName< DVInputIterator2 >::get( ); binaryTransformKernels[transform_oTypeB] = TypeName< oType >::get( ); binaryTransformKernels[transform_DVOutputIteratorB] = TypeName< DVOutputIterator >::get( ); binaryTransformKernels[transform_BinaryFunction] = TypeName< BinaryFunction >::get(); /********************************************************************************** * Type Definitions - directrly concatenated into kernel string *********************************************************************************/ // For user-defined types, the user must create a TypeName trait which returns the name of the //class - note use of TypeName<>::get to retrieve the name here. std::vector<std::string> typeDefinitions; PUSH_BACK_UNIQUE( typeDefinitions, cl_code) PUSH_BACK_UNIQUE( typeDefinitions, ClCode< iType1 >::get() ) PUSH_BACK_UNIQUE( typeDefinitions, ClCode< DVInputIterator1 >::get() ) PUSH_BACK_UNIQUE( typeDefinitions, ClCode< DVInputIterator2 >::get() ) PUSH_BACK_UNIQUE( typeDefinitions, ClCode< oType >::get() ) PUSH_BACK_UNIQUE( typeDefinitions, ClCode< DVOutputIterator >::get() ) PUSH_BACK_UNIQUE( typeDefinitions, ClCode< BinaryFunction >::get() ) /********************************************************************************** * Calculate WG Size *********************************************************************************/ cl_int l_Error = CL_SUCCESS; const size_t wgSize = WAVEFRONT_SIZE; V_OPENCL( l_Error, "Error querying kernel for CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE" ); assert( (wgSize & (wgSize-1) ) == 0 ); // The bitwise &,~ logic below requires wgSize to be a power of 2 int boundsCheck = 0; size_t wgMultiple = distVec; size_t lowerBits = ( distVec & (wgSize-1) ); if( lowerBits ) { // Bump the workitem count to the next multiple of wgSize wgMultiple &= ~lowerBits; wgMultiple += wgSize; } else { boundsCheck = 1; } if (wgMultiple/wgSize < numWorkGroups) numWorkGroups = wgMultiple/wgSize; /********************************************************************************** * Compile Options *********************************************************************************/ bool cpuDevice = ctl.getDevice().getInfo<CL_DEVICE_TYPE>() == CL_DEVICE_TYPE_CPU; //std::cout << "Device is CPU: " << (cpuDevice?"TRUE":"FALSE") << std::endl; const size_t kernel_WgSize = (cpuDevice) ? 1 : wgSize; std::string compileOptions; std::ostringstream oss; oss << " -DKERNELWORKGROUPSIZE=" << kernel_WgSize; compileOptions = oss.str(); /********************************************************************************** * Request Compiled Kernels *********************************************************************************/ Transform_KernelTemplateSpecializer ts_kts; std::vector< ::cl::Kernel > kernels = bolt::cl::getKernels( ctl, binaryTransformKernels, &ts_kts, typeDefinitions, transform_kernels, compileOptions); // kernels returned in same order as added in KernelTemplaceSpecializer constructor ALIGNED( 256 ) BinaryFunction aligned_binary( f ); control::buffPointer userFunctor = ctl.acquireBuffer( sizeof( aligned_binary ), CL_MEM_USE_HOST_PTR|CL_MEM_READ_ONLY, &aligned_binary ); typename DVInputIterator1::Payload first1_payload = first1.gpuPayload( ); typename DVInputIterator2::Payload first2_payload = first2.gpuPayload( ); typename DVOutputIterator::Payload result_payload = result.gpuPayload( ); kernels[boundsCheck].setArg( 0, first1.getContainer().getBuffer() ); kernels[boundsCheck].setArg( 1, first1.gpuPayloadSize( ),&first1_payload); kernels[boundsCheck].setArg( 2, first2.getContainer().getBuffer() ); kernels[boundsCheck].setArg( 3, first2.gpuPayloadSize( ),&first2_payload); kernels[boundsCheck].setArg( 4, result.getContainer().getBuffer() ); kernels[boundsCheck].setArg( 5, result.gpuPayloadSize( ),&result_payload); kernels[boundsCheck].setArg( 6, distVec ); kernels[boundsCheck].setArg( 7, *userFunctor); ::cl::Event transformEvent; l_Error = ctl.getCommandQueue().enqueueNDRangeKernel( kernels[boundsCheck], ::cl::NullRange, ::cl::NDRange(wgMultiple), // numWorkGroups*wgSize ::cl::NDRange(wgSize), NULL, &transformEvent ); V_OPENCL( l_Error, "enqueueNDRangeKernel() failed for transform() kernel" ); ::bolt::cl::wait(ctl, transformEvent); #if TRANSFORM_ENABLE_PROFILING if( 0 ) { cl_ulong start_time, stop_time; l_Error = transformEvent.getProfilingInfo<cl_ulong>(CL_PROFILING_COMMAND_START, &start_time); V_OPENCL( l_Error, "failed on getProfilingInfo<CL_PROFILING_COMMAND_QUEUED>()"); l_Error = transformEvent.getProfilingInfo<cl_ulong>(CL_PROFILING_COMMAND_END, &stop_time); V_OPENCL( l_Error, "failed on getProfilingInfo<CL_PROFILING_COMMAND_END>()"); size_t time = stop_time - start_time; std::cout << "Global Memory Bandwidth: "<<((distVec*(2.0*sizeof(iType1)+sizeof(oType)))/time)<<std::endl; } #endif // BOLT_ENABLE_PROFILING }; template< typename DVInputIterator, typename DVOutputIterator, typename UnaryFunction > void transform_unary_enqueue( ::bolt::cl::control &ctl, const DVInputIterator& first, const DVInputIterator& last, const DVOutputIterator& result, const UnaryFunction& f, const std::string& cl_code) { typedef typename std::iterator_traits<DVInputIterator>::value_type iType; typedef typename std::iterator_traits<DVOutputIterator>::value_type oType; cl_uint distVec = static_cast< cl_uint >( std::distance( first, last ) ); if( distVec == 0 ) return; const size_t numComputeUnits = ctl.getDevice( ).getInfo< CL_DEVICE_MAX_COMPUTE_UNITS >( ); const size_t numWorkGroupsPerComputeUnit = ctl.getWGPerComputeUnit( ); const size_t numWorkGroups = numComputeUnits * numWorkGroupsPerComputeUnit; /********************************************************************************** * Type Names - used in KernelTemplateSpecializer *********************************************************************************/ std::vector<std::string> unaryTransformKernels( transform_endU ); unaryTransformKernels[transform_iType] = TypeName< iType >::get( ); unaryTransformKernels[transform_DVInputIterator] = TypeName< DVInputIterator >::get( ); unaryTransformKernels[transform_oTypeU] = TypeName< oType >::get( ); unaryTransformKernels[transform_DVOutputIteratorU] = TypeName< DVOutputIterator >::get( ); unaryTransformKernels[transform_UnaryFunction] = TypeName< UnaryFunction >::get(); /********************************************************************************** * Type Definitions - directrly concatenated into kernel string *********************************************************************************/ std::vector<std::string> typeDefinitions; PUSH_BACK_UNIQUE( typeDefinitions, ClCode< iType >::get() ) PUSH_BACK_UNIQUE( typeDefinitions, ClCode< DVInputIterator >::get() ) PUSH_BACK_UNIQUE( typeDefinitions, ClCode< oType >::get() ) PUSH_BACK_UNIQUE( typeDefinitions, ClCode< DVOutputIterator >::get() ) PUSH_BACK_UNIQUE( typeDefinitions, ClCode< UnaryFunction >::get() ) /********************************************************************************** * Calculate WG Size *********************************************************************************/ cl_int l_Error = CL_SUCCESS; const size_t wgSize = WAVEFRONT_SIZE; int boundsCheck = 0; V_OPENCL( l_Error, "Error querying kernel for CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE" ); assert( (wgSize & (wgSize-1) ) == 0 ); // The bitwise &,~ logic below requires wgSize to be a power of 2 size_t wgMultiple = distVec; size_t lowerBits = ( distVec & (wgSize-1) ); if( lowerBits ) { // Bump the workitem count to the next multiple of wgSize wgMultiple &= ~lowerBits; wgMultiple += wgSize; } else { boundsCheck = 1; } /********************************************************************************** * Compile Options *********************************************************************************/ bool cpuDevice = ctl.getDevice().getInfo<CL_DEVICE_TYPE>() == CL_DEVICE_TYPE_CPU; //std::cout << "Device is CPU: " << (cpuDevice?"TRUE":"FALSE") << std::endl; const size_t kernel_WgSize = (cpuDevice) ? 1 : wgSize; std::string compileOptions; std::ostringstream oss; oss << " -DKERNELWORKGROUPSIZE=" << kernel_WgSize; compileOptions = oss.str(); /********************************************************************************** * Request Compiled Kernels *********************************************************************************/ TransformUnary_KernelTemplateSpecializer ts_kts; std::vector< ::cl::Kernel > kernels = bolt::cl::getKernels( ctl, unaryTransformKernels, &ts_kts, typeDefinitions, transform_kernels, compileOptions); // kernels returned in same order as added in KernelTemplaceSpecializer constructor // Create buffer wrappers so we can access the host functors, for read or writing in the kernel ALIGNED( 256 ) UnaryFunction aligned_binary( f ); control::buffPointer userFunctor = ctl.acquireBuffer( sizeof( aligned_binary ), CL_MEM_USE_HOST_PTR|CL_MEM_READ_ONLY, &aligned_binary ); typename DVInputIterator::Payload first_payload = first.gpuPayload( ); typename DVOutputIterator::Payload result_payload = result.gpuPayload( ); kernels[boundsCheck].setArg(0, first.getContainer().getBuffer() ); kernels[boundsCheck].setArg(1, first.gpuPayloadSize( ),&first_payload); kernels[boundsCheck].setArg(2, result.getContainer().getBuffer() ); kernels[boundsCheck].setArg(3, result.gpuPayloadSize( ),&result_payload); kernels[boundsCheck].setArg(4, distVec ); kernels[boundsCheck].setArg(5, *userFunctor); //k.setArg(3, numElementsPerThread ); ::cl::Event transformEvent; l_Error = ctl.getCommandQueue().enqueueNDRangeKernel( kernels[boundsCheck], ::cl::NullRange, ::cl::NDRange( wgMultiple ), // numThreads ::cl::NDRange( wgSize ), NULL, &transformEvent ); V_OPENCL( l_Error, "enqueueNDRangeKernel() failed for transform() kernel" ); ::bolt::cl::wait(ctl, transformEvent); #if TRANSFORM_ENABLE_PROFILING if( 0 ) { cl_ulong start_time, stop_time; l_Error = transformEvent.getProfilingInfo<cl_ulong>(CL_PROFILING_COMMAND_START, &start_time); V_OPENCL( l_Error, "failed on getProfilingInfo<CL_PROFILING_COMMAND_QUEUED>()"); l_Error = transformEvent.getProfilingInfo<cl_ulong>(CL_PROFILING_COMMAND_END, &stop_time); V_OPENCL( l_Error, "failed on getProfilingInfo<CL_PROFILING_COMMAND_END>()"); size_t time = stop_time - start_time; //std::cout << "Global Memory Bandwidth: "<<((distVec*(1.0*sizeof(iType)+sizeof(oType)))/time)<< std::endl; } #endif // BOLT_ENABLE_PROFILING }; /*! \brief This template function overload is used to seperate device_vector iterators from all other iterators \detail This template is called by the non-detail versions of inclusive_scan, it already assumes random access * iterators. This overload is called strictly for non-device_vector iterators */ template< typename InputIterator1, typename InputIterator2, typename OutputIterator, typename BinaryFunction > void transform_pick_iterator( bolt::cl::control &ctl, const InputIterator1& first1, const InputIterator1& last1, const InputIterator2& first2, const OutputIterator& result, const BinaryFunction& f, const std::string& user_code, std::random_access_iterator_tag, std::random_access_iterator_tag ) { typedef typename std::iterator_traits<InputIterator1>::value_type iType1; typedef typename std::iterator_traits<InputIterator2>::value_type iType2; typedef typename std::iterator_traits<OutputIterator>::value_type oType; size_t sz = std::distance( first1, last1 ); if (sz == 0) return; // Use host pointers memory since these arrays are only read once - no benefit to copying. bolt::cl::control::e_RunMode runMode = ctl.getForceRunMode(); // could be dynamic choice some day. if(runMode == bolt::cl::control::Automatic) { runMode = ctl.getDefaultPathToRun(); } #if defined(BOLT_DEBUG_LOG) BOLTLOG::CaptureLog *dblog = BOLTLOG::CaptureLog::getInstance(); #endif if( runMode == bolt::cl::control::SerialCpu ) { #if defined(BOLT_DEBUG_LOG) dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_SERIAL_CPU,"::Transform::SERIAL_CPU"); #endif std::transform( first1, last1, first2, result, f ); return; } else if( runMode == bolt::cl::control::MultiCoreCpu ) { #if defined( ENABLE_TBB ) #if defined(BOLT_DEBUG_LOG) dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_MULTICORE_CPU,"::Transform::MULTICORE_CPU"); #endif bolt::btbb::transform(first1,last1,first2,result,f); #else //std::cout << "The MultiCoreCpu version of Transform is not enabled. " << std ::endl; throw std::runtime_error( "The MultiCoreCpu version of transform is not enabled to be built! \n" ); #endif return; } else { #if defined(BOLT_DEBUG_LOG) dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_OPENCL_GPU,"::Transform::OPENCL_GPU"); #endif // Map the input iterator to a device_vector device_vector< iType1 > dvInput( first1, last1, CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY, ctl ); device_vector< iType2 > dvInput2( first2, sz, CL_MEM_USE_HOST_PTR|CL_MEM_READ_ONLY, true, ctl ); // Map the output iterator to a device_vector device_vector< oType > dvOutput( result, sz, CL_MEM_USE_HOST_PTR|CL_MEM_WRITE_ONLY, false, ctl ); transform_enqueue(ctl,dvInput.begin( ),dvInput.end( ),dvInput2.begin( ),dvOutput.begin( ),f,user_code ); // This should immediately map/unmap the buffer dvOutput.data( ); } } template< typename InputIterator1, typename InputIterator2, typename OutputIterator, typename BinaryFunction > void transform_pick_iterator( bolt::cl::control &ctl, const InputIterator1& first1, const InputIterator1& last1, const InputIterator2& fancyIter, const OutputIterator& result, const BinaryFunction& f, const std::string& user_code, std::random_access_iterator_tag, bolt::cl::fancy_iterator_tag ) { typedef typename std::iterator_traits<InputIterator1>::value_type iType1; typedef typename std::iterator_traits<InputIterator2>::value_type iType2; typedef typename std::iterator_traits<OutputIterator>::value_type oType; size_t sz = std::distance( first1, last1 ); if (sz == 0) return; // Use host pointers memory since these arrays are only read once - no benefit to copying. bolt::cl::control::e_RunMode runMode = ctl.getForceRunMode(); // could be dynamic choice some day. if(runMode == bolt::cl::control::Automatic) { runMode = ctl.getDefaultPathToRun(); } #if defined(BOLT_DEBUG_LOG) BOLTLOG::CaptureLog *dblog = BOLTLOG::CaptureLog::getInstance(); #endif if( runMode == bolt::cl::control::SerialCpu ) { #if defined(BOLT_DEBUG_LOG) dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_SERIAL_CPU,"::Transform::SERIAL_CPU"); #endif std::transform( first1, last1, fancyIter, result, f ); return; } else if( runMode == bolt::cl::control::MultiCoreCpu ) { #if defined( ENABLE_TBB ) #if defined(BOLT_DEBUG_LOG) dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_MULTICORE_CPU,"::Transform::MULTICORE_CPU"); #endif bolt::btbb::transform(first1,last1,fancyIter,result,f); #else //std::cout << "The MultiCoreCpu version of Transform is not enabled. " << std ::endl; throw std::runtime_error( "The MultiCoreCpu version of transform is not enabled to be built! \n" ); #endif return; } else { #if defined(BOLT_DEBUG_LOG) dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_OPENCL_GPU,"::Transform::OPENCL_GPU"); #endif // Use host pointers memory since these arrays are only read once - no benefit to copying. // Map the input iterator to a device_vector device_vector< iType1 > dvInput( first1, last1, CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY, ctl ); // Map the output iterator to a device_vector device_vector< oType > dvOutput( result, sz, CL_MEM_USE_HOST_PTR|CL_MEM_WRITE_ONLY, false, ctl ); transform_enqueue( ctl, dvInput.begin( ), dvInput.end( ), fancyIter, dvOutput.begin( ), f, user_code ); // This should immediately map/unmap the buffer dvOutput.data( ); } } template< typename InputIterator1, typename InputIterator2, typename OutputIterator, typename BinaryFunction > void transform_pick_iterator( bolt::cl::control &ctl, const InputIterator1& fancyIterfirst, const InputIterator1& fancyIterlast, const InputIterator2& first2, const OutputIterator& result, const BinaryFunction& f, const std::string& user_code, bolt::cl::fancy_iterator_tag, std::random_access_iterator_tag) { typedef typename std::iterator_traits<InputIterator1>::value_type iType1; typedef typename std::iterator_traits<InputIterator2>::value_type iType2; typedef typename std::iterator_traits<OutputIterator>::value_type oType; size_t sz = std::distance( fancyIterfirst, fancyIterlast ); if (sz == 0) return; // Use host pointers memory since these arrays are only read once - no benefit to copying. bolt::cl::control::e_RunMode runMode = ctl.getForceRunMode(); // could be dynamic choice some day. if(runMode == bolt::cl::control::Automatic) { runMode = ctl.getDefaultPathToRun(); } #if defined(BOLT_DEBUG_LOG) BOLTLOG::CaptureLog *dblog = BOLTLOG::CaptureLog::getInstance(); #endif if( runMode == bolt::cl::control::SerialCpu ) { #if defined(BOLT_DEBUG_LOG) dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_SERIAL_CPU,"::Transform::SERIAL_CPU"); #endif std::transform( fancyIterfirst, fancyIterlast, first2, result, f ); return; } else if( runMode == bolt::cl::control::MultiCoreCpu ) { #if defined( ENABLE_TBB ) #if defined(BOLT_DEBUG_LOG) dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_MULTICORE_CPU,"::Transform::MULTICORE_CPU"); #endif bolt::btbb::transform(fancyIterfirst,fancyIterlast,first2,result,f); #else //std::cout << "The MultiCoreCpu version of Transform is not enabled. " << std ::endl; throw std::runtime_error( "The MultiCoreCpu version of transform is not enabled to be built! \n" ); #endif return; } else { #if defined(BOLT_DEBUG_LOG) dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_OPENCL_GPU,"::Transform::OPENCL_GPU"); #endif // Use host pointers memory since these arrays are only read once - no benefit to copying. // Map the input iterator to a device_vector device_vector< iType2 > dvInput( first2, sz, CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY, true, ctl ); // Map the output iterator to a device_vector device_vector< oType > dvOutput( result, sz, CL_MEM_USE_HOST_PTR|CL_MEM_WRITE_ONLY, false, ctl ); transform_enqueue( ctl, fancyIterfirst, fancyIterlast, dvInput.begin( ), dvOutput.begin( ),f,user_code ); // This should immediately map/unmap the buffer dvOutput.data( ); } } // This template is called by the non-detail versions of inclusive_scan, it already assumes random access iterators // This is called strictly for iterators that are derived from device_vector< T >::iterator template<typename DVInputIterator1, typename DVInputIterator2, typename DVOutputIterator, typename BinaryFunction> void transform_pick_iterator( bolt::cl::control &ctl, const DVInputIterator1& first1, const DVInputIterator1& last1, const DVInputIterator2& first2, const DVOutputIterator& result, const BinaryFunction& f,const std::string& user_code, bolt::cl::device_vector_tag, bolt::cl::device_vector_tag) { typedef typename std::iterator_traits< DVInputIterator1 >::value_type iType1; typedef typename std::iterator_traits< DVInputIterator2 >::value_type iType2; typedef typename std::iterator_traits< DVOutputIterator >::value_type oType; size_t sz = std::distance( first1, last1 ); if( sz == 0 ) return; bolt::cl::control::e_RunMode runMode = ctl.getForceRunMode(); // could be dynamic choice some day. if(runMode == bolt::cl::control::Automatic) { runMode = ctl.getDefaultPathToRun(); } #if defined(BOLT_DEBUG_LOG) BOLTLOG::CaptureLog *dblog = BOLTLOG::CaptureLog::getInstance(); #endif if( runMode == bolt::cl::control::SerialCpu ) { #if defined(BOLT_DEBUG_LOG) dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_SERIAL_CPU,"::Transform::SERIAL_CPU"); #endif typename bolt::cl::device_vector< iType1 >::pointer firstPtr = first1.getContainer( ).data( ); typename bolt::cl::device_vector< iType2 >::pointer secPtr = first2.getContainer( ).data( ); typename bolt::cl::device_vector< oType >::pointer resPtr = result.getContainer( ).data( ); #if defined( _WIN32 ) std::transform( &firstPtr[ first1.m_Index ], &firstPtr[ last1.m_Index ], &secPtr[ first2.m_Index ], stdext::make_checked_array_iterator( &resPtr[ result.m_Index ], sz ), f ); #else std::transform( &firstPtr[ first1.m_Index ], &firstPtr[ last1.m_Index ], &secPtr[ first2.m_Index ], &resPtr[ result.m_Index ], f ); #endif return; } else if( runMode == bolt::cl::control::MultiCoreCpu ) { #if defined( ENABLE_TBB ) #if defined(BOLT_DEBUG_LOG) dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_MULTICORE_CPU,"::Transform::MULTICORE_CPU"); #endif typename bolt::cl::device_vector< iType1 >::pointer firstPtr = first1.getContainer( ).data( ); typename bolt::cl::device_vector< iType2 >::pointer secPtr = first2.getContainer( ).data( ); typename bolt::cl::device_vector< oType >::pointer resPtr = result.getContainer( ).data( ); bolt::btbb::transform( &firstPtr[ first1.m_Index ], &firstPtr[ last1.m_Index ], &secPtr[ first2.m_Index ],&resPtr[ result.m_Index ],f ); #else //std::cout << "The MultiCoreCpu version of Transform is not enabled. " << std ::endl; throw std::runtime_error( "The MultiCoreCpu version of transform is not enabled to be built! \n" ); #endif return; } else { #if defined(BOLT_DEBUG_LOG) dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_OPENCL_GPU,"::Transform::OPENCL_GPU"); #endif transform_enqueue( ctl, first1, last1, first2, result, f, user_code ); } } // This template is called by the non-detail versions of inclusive_scan, it already assumes random access iterators // This is called strictly for iterators that are derived from device_vector< T >::iterator template<typename DVInputIterator1, typename DVInputIterator2, typename DVOutputIterator, typename BinaryFunction> void transform_pick_iterator( bolt::cl::control &ctl,const DVInputIterator1& first1,const DVInputIterator1& last1, const DVInputIterator2& fancyIter, const DVOutputIterator& result, const BinaryFunction& f, const std::string& user_code, bolt::cl::device_vector_tag, bolt::cl::fancy_iterator_tag ) { typedef typename std::iterator_traits< DVInputIterator1 >::value_type iType1; typedef typename std::iterator_traits< DVInputIterator2 >::value_type iType2; typedef typename std::iterator_traits< DVOutputIterator >::value_type oType; size_t sz = std::distance( first1, last1 ); if( sz == 0 ) return; bolt::cl::control::e_RunMode runMode = ctl.getForceRunMode(); // could be dynamic choice some day. if(runMode == bolt::cl::control::Automatic) { runMode = ctl.getDefaultPathToRun(); } #if defined(BOLT_DEBUG_LOG) BOLTLOG::CaptureLog *dblog = BOLTLOG::CaptureLog::getInstance(); #endif if( runMode == bolt::cl::control::SerialCpu ) { #if defined(BOLT_DEBUG_LOG) dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_SERIAL_CPU,"::Transform::SERIAL_CPU"); #endif typename bolt::cl::device_vector< iType1 >::pointer firstPtr = first1.getContainer( ).data( ); typename bolt::cl::device_vector< oType >::pointer resPtr = result.getContainer( ).data( ); #if defined( _WIN32 ) std::transform( &firstPtr[ first1.m_Index ], &firstPtr[ last1.m_Index ], fancyIter, stdext::make_checked_array_iterator( &resPtr[ result.m_Index ], sz ), f ); #else std::transform( &firstPtr[ first1.m_Index ], &firstPtr[ last1.m_Index ], fancyIter, &resPtr[ result.m_Index ], f ); #endif return; } else if( runMode == bolt::cl::control::MultiCoreCpu ) { #if defined( ENABLE_TBB ) #if defined(BOLT_DEBUG_LOG) dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_MULTICORE_CPU,"::Transform::MULTICORE_CPU"); #endif typename bolt::cl::device_vector< iType1 >::pointer firstPtr = first1.getContainer( ).data( ); typename bolt::cl::device_vector< oType >::pointer resPtr = result.getContainer( ).data( ); bolt::btbb::transform( &firstPtr[ first1.m_Index ], &firstPtr[ last1.m_Index ], fancyIter, &resPtr[ result.m_Index ], f ); #else //std::cout << "The MultiCoreCpu version of Transform is not enabled. " << std ::endl; throw std::runtime_error( "The MultiCoreCpu version of transform is not enabled to be built! \n" ); #endif return; } else { #if defined(BOLT_DEBUG_LOG) dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_OPENCL_GPU,"::Transform::OPENCL_GPU"); #endif transform_enqueue( ctl, first1, last1, fancyIter, result, f, user_code ); } } /*! \brief This template function overload is used to seperate device_vector iterators from all other iterators \detail This template is called by the non-detail versions of inclusive_scan, it already assumes random access * iterators. This overload is called strictly for non-device_vector iterators */ template<typename InputIterator, typename OutputIterator, typename UnaryFunction> void transform_unary_pick_iterator( ::bolt::cl::control &ctl, const InputIterator& first, const InputIterator& last, const OutputIterator& result, const UnaryFunction& f, const std::string& user_code, std::random_access_iterator_tag ) { typedef typename std::iterator_traits<InputIterator>::value_type iType; typedef typename std::iterator_traits<OutputIterator>::value_type oType; size_t sz = (last - first); if (sz == 0) return; bolt::cl::control::e_RunMode runMode = ctl.getForceRunMode(); // could be dynamic choice some day. if(runMode == bolt::cl::control::Automatic) { runMode = ctl.getDefaultPathToRun(); } #if defined(BOLT_DEBUG_LOG) BOLTLOG::CaptureLog *dblog = BOLTLOG::CaptureLog::getInstance(); #endif if( runMode == bolt::cl::control::SerialCpu ) { #if defined(BOLT_DEBUG_LOG) dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_SERIAL_CPU,"::Transform::SERIAL_CPU"); #endif std::transform( first, last, result, f ); return; } else if( runMode == bolt::cl::control::MultiCoreCpu ) { #if defined( ENABLE_TBB ) #if defined(BOLT_DEBUG_LOG) dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_MULTICORE_CPU,"::Transform::MULTICORE_CPU"); #endif bolt::btbb::transform(first, last, result, f); #else //std::cout << "The MultiCoreCpu version of Transform is not enabled. " << std ::endl; throw std::runtime_error( "The MultiCoreCpu version of transform is not enabled to be built! \n" ); #endif return; } else { #if defined(BOLT_DEBUG_LOG) dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_OPENCL_GPU,"::Transform::OPENCL_GPU"); #endif // Use host pointers memory since these arrays are only read once - no benefit to copying. // Map the input iterator to a device_vector device_vector< iType > dvInput( first, last, CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, ctl ); // Map the output iterator to a device_vector device_vector< oType > dvOutput( result, sz, CL_MEM_USE_HOST_PTR | CL_MEM_WRITE_ONLY, false, ctl ); transform_unary_enqueue( ctl, dvInput.begin( ), dvInput.end( ), dvOutput.begin( ), f, user_code ); // This should immediately map/unmap the buffer dvOutput.data( ); } } // This template is called by the non-detail versions of inclusive_scan, it already assumes random access iterators // This is called strictly for iterators that are derived from device_vector< T >::iterator template<typename DVInputIterator, typename DVOutputIterator, typename UnaryFunction> void transform_unary_pick_iterator( ::bolt::cl::control &ctl, const DVInputIterator& first, const DVInputIterator& last, const DVOutputIterator& result, const UnaryFunction& f, const std::string& user_code, bolt::cl::device_vector_tag ) { typedef typename std::iterator_traits< DVInputIterator >::value_type iType; typedef typename std::iterator_traits< DVOutputIterator >::value_type oType; size_t sz = std::distance( first, last ); if( sz == 0 ) return; bolt::cl::control::e_RunMode runMode = ctl.getForceRunMode(); // could be dynamic choice some day. if(runMode == bolt::cl::control::Automatic) { runMode = ctl.getDefaultPathToRun(); } #if defined(BOLT_DEBUG_LOG) BOLTLOG::CaptureLog *dblog = BOLTLOG::CaptureLog::getInstance(); #endif // TBB does not have an equivalent for two input iterator std::transform if( (runMode == bolt::cl::control::SerialCpu) ) { #if defined(BOLT_DEBUG_LOG) dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_SERIAL_CPU,"::Transform::SERIAL_CPU"); #endif typename bolt::cl::device_vector< iType >::pointer firstPtr = first.getContainer( ).data( ); typename bolt::cl::device_vector< oType >::pointer resPtr = result.getContainer( ).data( ); #if defined( _WIN32 ) std::transform( &firstPtr[ first.m_Index ], &firstPtr[ last.m_Index ], stdext::make_checked_array_iterator( &resPtr[ result.m_Index ], sz ), f ); #else std::transform( &firstPtr[ first.m_Index ], &firstPtr[ last.m_Index ], &resPtr[ result.m_Index ], f ); #endif return; } else if( (runMode == bolt::cl::control::MultiCoreCpu) ) { #if defined( ENABLE_TBB ) #if defined(BOLT_DEBUG_LOG) dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_MULTICORE_CPU,"::Transform::MULTICORE_CPU"); #endif typename bolt::cl::device_vector< iType >::pointer firstPtr = first.getContainer( ).data( ); typename bolt::cl::device_vector< oType >::pointer resPtr = result.getContainer( ).data( ); bolt::btbb::transform(&firstPtr[ first.m_Index ], &firstPtr[ last.m_Index ], &resPtr[ result.m_Index ], f ); #else //std::cout << "The MultiCoreCpu version of Transform is not enabled. " << std ::endl; throw std::runtime_error("The MultiCoreCpu version of transform is not enabled to be built! \n" ); #endif return; } else { #if defined(BOLT_DEBUG_LOG) dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_OPENCL_GPU,"::Transform::OPENCL_GPU"); #endif transform_unary_enqueue( ctl, first, last, result, f, user_code ); } } template< typename InputIterator1, typename InputIterator2, typename OutputIterator, typename BinaryFunction > void transform_detect_random_access( bolt::cl::control& ctl, const InputIterator1& first1, const InputIterator1& last1, const InputIterator2& first2, const OutputIterator& result, const BinaryFunction& f, const std::string& user_code, std::random_access_iterator_tag, std::random_access_iterator_tag ) { transform_pick_iterator( ctl, first1, last1, first2, result, f, user_code, typename std::iterator_traits< InputIterator1 >::iterator_category( ), typename std::iterator_traits< InputIterator2 >::iterator_category( ) ); }; // Wrapper that uses default ::bolt::cl::control class, iterator interface template< typename InputIterator1, typename InputIterator2, typename OutputIterator, typename BinaryFunction > void transform_detect_random_access( bolt::cl::control& ctl, const InputIterator1& first1, const InputIterator1& last1, const InputIterator2& first2, const OutputIterator& result, const BinaryFunction& f,const std::string& user_code, std::input_iterator_tag, std::input_iterator_tag ) { // TODO: It should be possible to support non-random_access_iterator_tag iterators, if we copied the data // to a temporary buffer. Should we? static_assert( std::is_same< InputIterator1, std::input_iterator_tag >::value, "Bolt only supports random access iterator types" ); }; template<typename InputIterator, typename OutputIterator, typename UnaryFunction> void transform_unary_detect_random_access( ::bolt::cl::control& ctl, const InputIterator& first1, const InputIterator& last1,const OutputIterator& result, const UnaryFunction& f, const std::string& user_code, std::random_access_iterator_tag ) { transform_unary_pick_iterator( ctl, first1, last1, result, f, user_code, typename std::iterator_traits< InputIterator >::iterator_category( ) ); }; // Wrapper that uses default ::bolt::cl::control class, iterator interface template<typename InputIterator, typename OutputIterator, typename UnaryFunction> void transform_unary_detect_random_access( ::bolt::cl::control& ctl, const InputIterator& first1, const InputIterator& last1, const OutputIterator& result, const UnaryFunction& f, const std::string& user_code, std::input_iterator_tag ) { // TODO: It should be possible to support non-random_access_iterator_tag iterators, if we copied the data // to a temporary buffer. Should we? static_assert( std::is_same< InputIterator, std::input_iterator_tag >::value , "Bolt only supports random access iterator types" ); }; } //End of detail namespace // two-input transform, std:: iterator template< typename InputIterator1, typename InputIterator2, typename OutputIterator, typename BinaryFunction > void transform( bolt::cl::control& ctl, InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, OutputIterator result, BinaryFunction f, const std::string& user_code ) { detail::transform_detect_random_access( ctl, first1, last1, first2, result, f, user_code, typename std::iterator_traits< InputIterator1 >::iterator_category( ), typename std::iterator_traits< InputIterator2 >::iterator_category( ) ); } // default ::bolt::cl::control, two-input transform, std:: iterator template< typename InputIterator1, typename InputIterator2, typename OutputIterator, typename BinaryFunction > void transform( InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, OutputIterator result, BinaryFunction f, const std::string& user_code ) { detail::transform_detect_random_access( control::getDefault(), first1, last1, first2, result, f, user_code, typename std::iterator_traits< InputIterator1 >::iterator_category( ), typename std::iterator_traits< InputIterator2 >::iterator_category( ) ); } // one-input transform, std:: iterator template<typename InputIterator, typename OutputIterator, typename UnaryFunction> void transform( ::bolt::cl::control& ctl, InputIterator first1, InputIterator last1, OutputIterator result, UnaryFunction f, const std::string& user_code ) { detail::transform_unary_detect_random_access( ctl, first1, last1, result, f, user_code, typename std::iterator_traits< InputIterator >::iterator_category( ) ); } // default control, one-input transform, std:: iterator template<typename InputIterator, typename OutputIterator, typename UnaryFunction> void transform( InputIterator first1, InputIterator last1, OutputIterator result, UnaryFunction f, const std::string& user_code ) { detail::transform_unary_detect_random_access( control::getDefault(), first1, last1, result, f, user_code, typename std::iterator_traits< InputIterator >::iterator_category( ) ); } } //End of cl namespace } //End of bolt namespace #endif
48.806584
143
0.633284
jayavanth
3c72422154b573ba59da9dafa784a756a8bb89f0
898
cpp
C++
compile/libbcc/bcinfo/Wrap/wrapper_output.cpp
Keneral/aframeworks
af1d0010bfb88751837fb1afc355705bd8a9ad8b
[ "Unlicense" ]
1
2022-01-07T01:53:19.000Z
2022-01-07T01:53:19.000Z
compile/libbcc/bcinfo/Wrap/wrapper_output.cpp
Keneral/aframeworks
af1d0010bfb88751837fb1afc355705bd8a9ad8b
[ "Unlicense" ]
null
null
null
compile/libbcc/bcinfo/Wrap/wrapper_output.cpp
Keneral/aframeworks
af1d0010bfb88751837fb1afc355705bd8a9ad8b
[ "Unlicense" ]
1
2020-02-28T02:48:42.000Z
2020-02-28T02:48:42.000Z
/* * Copyright 2012, The Android Open Source Project * * 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 "bcinfo/Wrap/wrapper_output.h" bool WrapperOutput::Write(const uint8_t* buffer, size_t buffer_size) { // Default implementation that uses the byte write routine. for (size_t i = 0; i < buffer_size; ++i) { if (!Write(buffer[i])) return false; } return true; }
34.538462
75
0.726058
Keneral
3c725d7bd96bfc4cc2a748ee61fc992b5553986c
2,509
cc
C++
third_party/blink/renderer/platform/p2p/mdns_responder_adapter.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
third_party/blink/renderer/platform/p2p/mdns_responder_adapter.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
third_party/blink/renderer/platform/p2p/mdns_responder_adapter.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/platform/p2p/mdns_responder_adapter.h" #include <string> #include "jingle/glue/utils.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "net/base/ip_address.h" #include "net/base/ip_endpoint.h" #include "services/network/public/mojom/mdns_responder.mojom-blink.h" #include "third_party/blink/public/common/thread_safe_browser_interface_broker_proxy.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/renderer/platform/wtf/functional.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" #include "third_party/webrtc/rtc_base/ip_address.h" namespace blink { namespace { void OnNameCreatedForAddress( webrtc::MdnsResponderInterface::NameCreatedCallback callback, const rtc::IPAddress& addr, const String& name, bool announcement_scheduled) { // We currently ignore whether there is an announcement sent for the name. callback(addr, name.Utf8()); } void OnNameRemovedForAddress( webrtc::MdnsResponderInterface::NameRemovedCallback callback, bool removed, bool goodbye_scheduled) { // We currently ignore whether there is a goodbye sent for the name. callback(removed); } } // namespace MdnsResponderAdapter::MdnsResponderAdapter() { mojo::PendingRemote<network::mojom::blink::MdnsResponder> client; auto receiver = client.InitWithNewPipeAndPassReceiver(); shared_remote_client_ = mojo::SharedRemote<network::mojom::blink::MdnsResponder>( std::move(client)); blink::Platform::Current()->GetBrowserInterfaceBroker()->GetInterface( std::move(receiver)); } MdnsResponderAdapter::~MdnsResponderAdapter() = default; void MdnsResponderAdapter::CreateNameForAddress(const rtc::IPAddress& addr, NameCreatedCallback callback) { shared_remote_client_->CreateNameForAddress( jingle_glue::RtcIPAddressToNetIPAddress(addr), WTF::Bind(&OnNameCreatedForAddress, callback, addr)); } void MdnsResponderAdapter::RemoveNameForAddress(const rtc::IPAddress& addr, NameRemovedCallback callback) { shared_remote_client_->RemoveNameForAddress( jingle_glue::RtcIPAddressToNetIPAddress(addr), WTF::Bind(&OnNameRemovedForAddress, callback)); } } // namespace blink
35.842857
87
0.746911
sarang-apps
3c72e3f286a37d536acaa51ed811edb1aa4998aa
1,418
hpp
C++
dp/longest-common-subsequence.hpp
matumoto1234/library
a2c80516a8afe5876696c139fe0e837d8a204f69
[ "Unlicense" ]
2
2021-06-24T11:21:08.000Z
2022-03-15T05:57:25.000Z
dp/longest-common-subsequence.hpp
matumoto1234/library
a2c80516a8afe5876696c139fe0e837d8a204f69
[ "Unlicense" ]
102
2021-10-30T21:30:00.000Z
2022-03-26T18:39:47.000Z
dp/longest-common-subsequence.hpp
matumoto1234/library
a2c80516a8afe5876696c139fe0e837d8a204f69
[ "Unlicense" ]
null
null
null
#pragma once #include "./base.hpp" #include <string> #include <vector> namespace dp { // verify:EDPC_F template <typename T> struct LongestCommonSubsequence { vector<T> s, t; int h, w; vector<vector<int>> dp; LongestCommonSubsequence(vector<T> _s, vector<T> _t): s(_s), t(_t) { h = _s.size(); w = _t.size(); } LongestCommonSubsequence(string _s, string _t) { h = _s.size(), w = _t.size(); for (int i = 0; i < h; i++) s.emplace_back(_s[i]); for (int i = 0; i < w; i++) t.emplace_back(_t[i]); } int build() { dp.assign(h + 1, vector<int>(w + 1, 0)); for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { if (s[i] == t[j]) { dp[i + 1][j + 1] = max(dp[i + 1][j + 1], dp[i][j] + 1); continue; } dp[i + 1][j] = max(dp[i + 1][j], dp[i][j]); dp[i][j + 1] = max(dp[i][j + 1], dp[i][j]); } } return dp[h][w]; } vector<T> restore() { vector<T> res; int i = h, j = w; while (i > 0 and j > 0) { if (s[i - 1] == t[j - 1]) { res.emplace_back(s[i - 1]); i--; j--; continue; } if (dp[i - 1][j] > dp[i][j - 1]) i--; else j--; } reverse(res.begin(), res.end()); return res; } }; } // namespace dp
23.245902
72
0.415374
matumoto1234
3c76e16dc82dd5a00270d85ce260dcad65378378
867
hpp
C++
NWNXLib/API/Mac/API/CJoiningRestrictions.hpp
acaos/nwnxee-unified
0e4c318ede64028c1825319f39c012e168e0482c
[ "MIT" ]
1
2019-06-04T04:30:24.000Z
2019-06-04T04:30:24.000Z
NWNXLib/API/Mac/API/CJoiningRestrictions.hpp
presscad/nwnee
0f36b281524e0b7e9796bcf30f924792bf9b8a38
[ "MIT" ]
null
null
null
NWNXLib/API/Mac/API/CJoiningRestrictions.hpp
presscad/nwnee
0f36b281524e0b7e9796bcf30f924792bf9b8a38
[ "MIT" ]
1
2019-10-20T07:54:45.000Z
2019-10-20T07:54:45.000Z
#pragma once #include <cstdint> namespace NWNXLib { namespace API { struct CJoiningRestrictions { int32_t bAllowLocal; int32_t bAllowServer; int32_t bAllowVault; int32_t bFixedParties; int32_t bAllowFighter; int32_t bAllowBarbarian; int32_t bAllowRanger; int32_t bAllowPaladin; int32_t bAllowWizard; int32_t bAllowSorcerer; int32_t bAllowCleric; int32_t bAllowDruid; int32_t bAllowRogue; int32_t bAllowBard; int32_t bAllowMonk; int32_t bAllowHuman; int32_t bAllowElf; int32_t bAllowDwarf; int32_t bAllowGnome; int32_t bAllowHalfling; int32_t bAllowHalfOrc; int32_t bAllowHalfElf; int32_t nMaxPlayers; int32_t nMaxParties; int32_t nMaxItemPoints; int32_t nMaxStatTotal; int32_t nMinLevel; int32_t nMaxLevel; int32_t bAllowLocalVaultChars; }; } }
19.266667
34
0.727797
acaos
3c77efa73935544b65f3479175f705e0342d9da0
10,431
cpp
C++
Sources/src/SpecialAttack.cpp
Tifox/Grog-Knight
377a661286cda7ee3b2b2d0099641897938c2f8f
[ "Apache-2.0" ]
null
null
null
Sources/src/SpecialAttack.cpp
Tifox/Grog-Knight
377a661286cda7ee3b2b2d0099641897938c2f8f
[ "Apache-2.0" ]
null
null
null
Sources/src/SpecialAttack.cpp
Tifox/Grog-Knight
377a661286cda7ee3b2b2d0099641897938c2f8f
[ "Apache-2.0" ]
null
null
null
/** * 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. */ /** * File: SpecialMoves.cpp * Creation: 2015-06-30 09:57 * Matthieu Maudet<arkhane84@gmail.com> */ # include "SpecialAttack.hpp" # include "Characters.hpp" # include <cstdlib> //! Base constructor SpecialAttack::SpecialAttack(void) { } SpecialAttack::~SpecialAttack(void) { theSwitchboard.UnsubscribeFrom(this, "SpecialAttackEnd"); theSwitchboard.UnsubscribeFrom(this, "linkWeapon"); } SpecialAttack::SpecialAttack(Characters* charac) { std::string file; std::stringstream buffer; std::ifstream fd; Json::Reader read; Json::Value json; Json::ValueIterator i, v; std::map<std::string, Json::Value> tmp; this->character = charac; file = "Resources/Elements/SpecialAttack.json"; fd.open(file.c_str()); if (!fd.is_open()) Log::error("Can't open the file for the specialmoves class."); buffer << fd.rdbuf(); if (!read.parse(buffer, json)) Log::error("Error in json syntax :\n" + read.getFormattedErrorMessages()); for (i = json.begin(); i != json.end(); i++) { for (v = (*i).begin(); v != (*i).end(); v++) { tmp[v.key().asString()] = (*v); this->character->_attr[i.key().asString()] = tmp; } } theSwitchboard.SubscribeTo(this, "SpecialAttackEnd"); theSwitchboard.SubscribeTo(this, "linkWeapon"); } void SpecialAttack::ReceiveMessage(Message *m) { Characters *c = Game::currentGame->getHero(); if (m->GetMessageName() == "linkWeapon") { this->_left->GetBody()->SetGravityScale(0); this->_right->GetBody()->SetGravityScale(0); this->_left->GetBody()->SetLinearVelocity(b2Vec2(0,0)); this->_right->GetBody()->SetLinearVelocity(b2Vec2(0,0)); b2DistanceJointDef jointDef1; b2DistanceJointDef jointDef2; b2DistanceJointDef jointDef3; b2DistanceJointDef jointDef4; jointDef1.Initialize(c->GetBody(), this->_left->GetBody(), b2Vec2(c->GetBody()->GetWorldCenter().x, c->GetBody()->GetWorldCenter().y + 0.4), b2Vec2(this->_left->GetBody()->GetWorldCenter().x, this->_left->GetBody()->GetWorldCenter().y + 0.4)); jointDef1.collideConnected = false; jointDef2.Initialize(c->GetBody(), this->_right->GetBody(), b2Vec2(c->GetBody()->GetWorldCenter().x, c->GetBody()->GetWorldCenter().y + 0.4), b2Vec2(this->_right->GetBody()->GetWorldCenter().x, this->_right->GetBody()->GetWorldCenter().y + 0.4)); jointDef2.collideConnected = false; jointDef3.Initialize(c->GetBody(), this->_left->GetBody(), b2Vec2(c->GetBody()->GetWorldCenter().x, c->GetBody()->GetWorldCenter().y - 0.4), b2Vec2(this->_left->GetBody()->GetWorldCenter().x, this->_left->GetBody()->GetWorldCenter().y - 0.4)); jointDef3.collideConnected = false; jointDef4.Initialize(c->GetBody(), this->_right->GetBody(), b2Vec2(c->GetBody()->GetWorldCenter().x, c->GetBody()->GetWorldCenter().y - 0.4), b2Vec2(this->_right->GetBody()->GetWorldCenter().x, this->_right->GetBody()->GetWorldCenter().y - 0.4)); jointDef4.collideConnected = false; b2DistanceJoint *joint1 = (b2DistanceJoint*)theWorld.GetPhysicsWorld().CreateJoint(&jointDef1); b2DistanceJoint *joint2 = (b2DistanceJoint*)theWorld.GetPhysicsWorld().CreateJoint(&jointDef2); b2DistanceJoint *joint3 = (b2DistanceJoint*)theWorld.GetPhysicsWorld().CreateJoint(&jointDef3); b2DistanceJoint *joint4 = (b2DistanceJoint*)theWorld.GetPhysicsWorld().CreateJoint(&jointDef4); } if (m->GetMessageName() == "RapidFire") { Game::currentGame->getHero()->getWeapon()->attack(this->character); theSwitchboard.DeferredBroadcast(new Message("RapidFire"), this->character->_getAttr("rapidFire", "interval").asFloat()); } if (m->GetMessageName() == "SpecialAttackEnd") { if (this->_currentAttack == "whirlwind") { Game::currentGame->getHero()->buff.bonusSpeed = this->_previousSpeed; Game::currentGame->getHero()->_isWhirlwinding = false; c->AnimCallback("base"); c->_canAttack = true; c->_invincibility = false; this->_currentAttack = ""; } else if (this->_currentAttack == "shockwave") { this->_currentAttack = ""; } if (this->_currentAttack == "rapidFire") { Game::currentGame->getHero()->_isRapidFiring = false; theSwitchboard.UnsubscribeFrom(this, "RapidFire"); c->AnimCallback("base"); this->_currentAttack = ""; } } } void SpecialAttack::_whirlwind(void) { this->character->_setCategory("whirlwind"); Weapon *currentWeapon = Game::currentGame->getHero()->getWeapon(); Characters *hero = Game::currentGame->getHero(); if (this->character->_isAttacking == 0 && this->character->_canMove == 1 && this->character->_speAttReady == 1 /*&& currentWeapon->getType() == "Sword"*/) { this->character->_speAttReady = 0; this->character->_isWhirlwinding = true; currentWeapon->setActive(this->character->_getAttr("whirlwind", "uptime").asFloat()); this->_right = new Weapon (Game::currentGame->getHero()->_weapon, Game::currentGame->getHero(), 1); this->_left = new Weapon (Game::currentGame->getHero()->_weapon, Game::currentGame->getHero(), -1); this->_previousSpeed = hero->buff.bonusSpeed; hero->_invincibility = true; hero->buff.bonusSpeed = -(hero->_getAttr("forward", "force").asInt() / 2); hero->_canAttack = false; theSwitchboard.DeferredBroadcast(new Message("SpecialAttackEnd"), this->character->_getAttr("whirlwind", "uptime").asFloat()); theSwitchboard.DeferredBroadcast(new Message("speAttReady"), this->character->_getAttr("cooldown").asFloat()); Game::getHUD()->speAttCooldown(this->character->_getAttr("cooldown").asFloat()); hero->changeSizeTo(Vector2(hero->_getAttr("x").asFloat(), hero->_getAttr("y").asFloat())); hero->PlaySpriteAnimation(hero->_getAttr("time").asFloat(), SAT_Loop, hero->_getAttr("beginFrame").asInt(), hero->_getAttr("endFrame").asInt(), "base"); this->_currentAttack = "whirlwind"; } } void SpecialAttack::_throwWeapon(void) { this->character->_setCategory("throwWeapon"); b2Vec2 pos = this->character->GetBody()->GetWorldCenter(); Weapon *currentWeapon = this->character->getWeapon(); std::string orientation; Characters *hero = Game::currentGame->getHero(); if (this->character->_isAttacking == 0 && this->character->_canMove == 1 && this->character->_speAttReady == 1 && currentWeapon->getType() == "Spear") { this->character->_speAttReady = 0; if (hero->_latOrientation == Characters::RIGHT) { new Projectile(currentWeapon->getSprite(), 50, Vector2(pos.x, pos.y), Vector2(1, 1.5f), Vector2(0, 0), "throwSpear", -1, 0.8); } if (hero->_latOrientation == Characters::LEFT) new Projectile(currentWeapon->getSprite(), 50, Vector2(pos.x, pos.y), Vector2(-1, 1.5f), Vector2(0, 0), "throwSpear", 45, 0.8); theSwitchboard.DeferredBroadcast(new Message("speAttReady"), this->character->_getAttr("cooldown").asFloat()); Game::getHUD()->speAttCooldown(this->character->_getAttr("cooldown").asFloat()); this->_currentAttack = "throwWeapon"; } } void SpecialAttack::_shockwave(void) { this->character->_setCategory("shockwave"); Weapon *currentWeapon = Game::currentGame->getHero()->getWeapon(); Characters *hero = Game::currentGame->getHero(); if (this->character->_isAttacking == 0 && this->character->_canMove == 1 && this->character->_speAttReady == 1 && currentWeapon->getType() == "Axe") { this->character->_speAttReady = 0; this->character->_isShockWaving = true; theSwitchboard.DeferredBroadcast(new Message("speAttReady"), this->character->_getAttr("cooldown").asFloat()); int dmg = this->character->_getAttr("shockwave", "damage").asInt(); Projectile *wave = new Projectile(currentWeapon, dmg); this->_currentAttack = "shockwave"; std::string orientation; if (hero->_latOrientation == Characters::RIGHT) orientation = "right"; else if (hero->_latOrientation == Characters::LEFT) orientation = "left"; hero->changeSizeTo(Vector2(hero->_getAttr("x").asInt(), hero->_getAttr("y").asInt())); hero->PlaySpriteAnimation(hero->_getAttr("time").asFloat(), SAT_OneShot, hero->_getAttr("beginFrame_" + orientation).asInt(), hero->_getAttr("endFrame_" + orientation).asInt(), "base"); theSwitchboard.DeferredBroadcast(new Message("speAttReady"), this->character->_getAttr("cooldown").asFloat()); Game::getHUD()->speAttCooldown(this->character->_getAttr("cooldown").asFloat()); } } void SpecialAttack::_rapidFire(void) { this->character = Game::currentGame->getHero(); this->character->_setCategory("rapidFire"); Weapon *currentWeapon = Game::currentGame->getHero()->getWeapon(); Characters *hero = Game::currentGame->getHero(); std::string orientation; theSwitchboard.SubscribeTo(this, "RapidFire"); if (this->character->_isAttacking == 0 && this->character->_canMove == 1 && this->character->_speAttReady == 1 && currentWeapon->getType() == "Bow") { this->character->_speAttReady = 0; this->character->_isRapidFiring = true; if (hero->_latOrientation == Characters::RIGHT) orientation = "right"; else if (hero->_latOrientation == Characters::LEFT) orientation = "left"; hero->changeSizeTo(Vector2(hero->_getAttr("x").asInt(), hero->_getAttr("y").asInt())); hero->PlaySpriteAnimation(hero->_getAttr("time").asFloat(), SAT_Loop, hero->_getAttr("beginFrame_" + orientation).asInt(), hero->_getAttr("endFrame_" + orientation).asInt()); theSwitchboard.DeferredBroadcast(new Message("speAttReady"), this->character->_getAttr("cooldown").asFloat()); Game::getHUD()->speAttCooldown(this->character->_getAttr("cooldown").asFloat()); theSwitchboard.DeferredBroadcast(new Message("SpecialAttackEnd"), this->character->_getAttr("rapidFire", "uptime").asFloat()); theSwitchboard.DeferredBroadcast(new Message("RapidFire"), 0); this->_currentAttack = "rapidFire"; } }
45.75
157
0.705685
Tifox
3c78bcb00b7035c0bd7a9fc3c399314fd5270126
1,391
cpp
C++
src/image/color.cpp
eisbehr/c10t
c30e55613fa0203cba84cb153392a55391279551
[ "BSD-3-Clause" ]
1
2016-06-07T17:34:32.000Z
2016-06-07T17:34:32.000Z
src/image/color.cpp
eisbehr/c10t
c30e55613fa0203cba84cb153392a55391279551
[ "BSD-3-Clause" ]
null
null
null
src/image/color.cpp
eisbehr/c10t
c30e55613fa0203cba84cb153392a55391279551
[ "BSD-3-Clause" ]
null
null
null
// Distributed under the BSD License, see accompanying LICENSE.txt // (C) Copyright 2010 John-John Tedro et al. #include "image/color.hpp" #include <sstream> #include <string> uint8_t alpha_over_c(uint8_t u, uint8_t o, uint8_t ua, uint8_t oa); /** * Takes two color values and does an alpha over blending without using floats. */ inline uint8_t alpha_over_c(uint8_t ac, uint8_t aa, uint8_t bc, uint8_t ba) { return ((ac * aa) + ((0xff * (bc * ba) - aa * (bc * ba)) / 0xff)) / 0xff; } void color::blend(const color &other) { if (other.is_invisible()) return; if (other.is_opaque() || is_invisible()) { r = other.r; g = other.g; b = other.b; a = other.a; return; } r = alpha_over_c(other.r, other.a, r, a); g = alpha_over_c(other.g, other.a, g, a); b = alpha_over_c(other.b, other.a, b, a); a = a + (other.a * (0xff - a)) / 0xff; r = ((r * 0xff) / a); g = ((g * 0xff) / a); b = ((b * 0xff) / a); } // pull color down towards black void color::darken(uint8_t f) { r = std::max((int)r - ((int)r * (int)f) / 0xff, 0x0); g = std::max((int)g - ((int)g * (int)f) / 0xff, 0x0); b = std::max((int)b - ((int)b * (int)f) / 0xff, 0x0); } void color::lighten(uint8_t f) { r = std::min((int)r + ((int)r * (int)f) / 0xff, 0xff); g = std::min((int)g + ((int)g * (int)f) / 0xff, 0xff); b = std::min((int)b + ((int)b * (int)f) / 0xff, 0xff); }
28.387755
79
0.580158
eisbehr
3c7c76ccc0b9697dfeef26c9bd802a064be5c755
3,526
cpp
C++
All Project/project1.cpp
jaibae21/CPE211_S2021_UAH
9e8e5452526288699e0d7ee22ed393857233501e
[ "MIT" ]
null
null
null
All Project/project1.cpp
jaibae21/CPE211_S2021_UAH
9e8e5452526288699e0d7ee22ed393857233501e
[ "MIT" ]
null
null
null
All Project/project1.cpp
jaibae21/CPE211_S2021_UAH
9e8e5452526288699e0d7ee22ed393857233501e
[ "MIT" ]
1
2022-03-26T08:52:00.000Z
2022-03-26T08:52:00.000Z
//****************************************************************** // The following is a partial header comment block. Modify the // appropriate parts by putting in your information. Look at // the samples handed out to make any necessary additions // You may delete this line and the three above it. // Paycheck program // Ron Bowman // CPE112-02, L00 // Project due date: ##/##/## // This program computes an employee's wages for the week // If an employee works more than 40 hours they get 1.5 times // their normal pay rate for all hours over 40. //****************************************************************** // Put all preprocessor directives here // The following are the necessary header files #include <iostream> // header file for standard input output // add modification #1 here using namespace std; /* This function calculates the pay in one of two ways */ /* depending on the hours worked */ void CalcPay( float, float, float& ); // Global constant declarations const float MAX_HOURS = 40.0; // Maximum normal work hours const float OVERTIME = 1.5; // Overtime pay rate factor int main() { float payRate; // Employee's pay rate float hours; // Hours worked float wages; // Wages earned based on pay rate and hours worked. // add modification #2 here int empNum; // Employee ID number // prompt for and read in the information for an employee // information read is the employee number, their pay rate // and the number of hours they have worked for the week. cout << "Enter the employee number: "; cin >> empNum; cout << "Enter pay rate: "; cin >> payRate; cout << "Enter hours worked: "; cin >> hours; CalcPay(payRate, hours, wages); // call the function that Compute wages // output the employee information and the results // note how the output statement is broken up into multiple lines so that // the cout statement is not too long. // add modifications #3 here. This modification // adds an if statement to calculate regular and overtime pay // Modification #4 occurs here // This modification changes the cout statement as indicated in // the project handout cout << "Employee: " << empNum << endl << "Pay rate: " << payRate << endl << "Hours: " << hours << endl << "Wages: $" << wages << endl; return 0; // Indicate successful } // completion of the program //****************************************************************** //****************************************************************** // All function definitions are placed below main //****************************************************************** //****************************************************************** void CalcPay( /* in */ float payRate, // Employee's pay rate /* in */ float hours, // Hours worked /* out */ float& wages ) // Wages earned // CalcPay computes wages from the employee's pay rate // and the hours worked, taking overtime into account { if (hours > MAX_HOURS) // Is there overtime? wages = (MAX_HOURS * payRate) + // Yes (hours - MAX_HOURS) * payRate * OVERTIME; else wages = hours * payRate; // No }
41
83
0.533749
jaibae21
3c85d79c77277da0d6a478b6e02766ddbdaacd54
3,289
cpp
C++
ext/ruby_mapnik/_mapnik_symbolizer.rb.cpp
gravitystorm/Ruby-Mapnik
6e878ca914116ffc3f897cdb3bc94cd0b3c15281
[ "MIT" ]
21
2015-02-04T17:22:57.000Z
2021-12-30T22:08:47.000Z
ext/ruby_mapnik/_mapnik_symbolizer.rb.cpp
gravitystorm/Ruby-Mapnik
6e878ca914116ffc3f897cdb3bc94cd0b3c15281
[ "MIT" ]
20
2015-04-14T16:43:53.000Z
2019-10-01T16:18:50.000Z
ext/ruby_mapnik/_mapnik_symbolizer.rb.cpp
gravitystorm/Ruby-Mapnik
6e878ca914116ffc3f897cdb3bc94cd0b3c15281
[ "MIT" ]
3
2015-05-27T11:27:50.000Z
2020-09-09T09:36:24.000Z
/***************************************************************************** Copyright (C) 2011 Elliot Laster 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 "_mapnik_symbolizer.rb.h" // Rice #include <rice/Data_Type.hpp> #include <rice/Constructor.hpp> #include <rice/Class.hpp> #include <rice/Enum.hpp> // Mapnik #include <mapnik/rule.hpp> namespace { // TODO: This is just terrible... mapnik::symbolizer from_subtype(Rice::Object obj){ mapnik::symbolizer out; std::string class_name = obj.class_of().to_s().str(); if(class_name == "Mapnik::PolygonSymbolizer") { out = mapnik::symbolizer(from_ruby<mapnik::polygon_symbolizer>(obj)); } else if(class_name == "Mapnik::LineSymbolizer") { out = mapnik::symbolizer(from_ruby<mapnik::line_symbolizer>(obj)); } else if(class_name == "Mapnik::TextSymbolizer"){ out = mapnik::symbolizer(from_ruby<mapnik::text_symbolizer>(obj)); } else if(class_name == "Mapnik::LinePatternSymbolizer"){ out = mapnik::symbolizer(from_ruby<mapnik::line_pattern_symbolizer>(obj)); } else if(class_name == "Mapnik::MarkersSymbolizer"){ out = mapnik::symbolizer(from_ruby<mapnik::markers_symbolizer>(obj)); } else if(class_name == "Mapnik::PointSymbolizer") { out = mapnik::symbolizer(from_ruby<mapnik::point_symbolizer>(obj)); } else if(class_name == "Mapnik::PolygonPatternSymbolizer"){ out = mapnik::symbolizer(from_ruby<mapnik::polygon_pattern_symbolizer>(obj)); } else if(class_name == "Mapnik::RasterSymbolizer"){ out = mapnik::symbolizer(from_ruby<mapnik::raster_symbolizer>(obj)); } else if(class_name == "Mapnik::ShieldSymbolizer"){ out = mapnik::symbolizer(from_ruby<mapnik::shield_symbolizer>(obj)); } return out; } } void register_symbolizer(Rice::Module rb_mapnik){ /* @@Module_var rb_mapnik = Mapnik */ Rice::Data_Type< mapnik::symbolizer > rb_csymbolizer = Rice::define_class_under< mapnik::symbolizer >(rb_mapnik, "Symbolizer"); /* * Document-method: from_subtype * call-seq: * from_subtype(symbolizer) * @return [Mapnik::Symbolizer] */ rb_csymbolizer.define_singleton_method("from_subtype", &from_subtype, Rice::Arg("obj")); }
43.853333
129
0.697172
gravitystorm
3c8813b77a323462c1c77cf469e7e022beab5f4a
1,433
cpp
C++
startalk_ui/QuitOnCloseNotice.cpp
xuepingiw/open_source_startalk
44d962b04039f5660ec47a10313876a0754d3e72
[ "MIT" ]
34
2019-03-18T08:09:24.000Z
2022-03-15T02:03:25.000Z
startalk_ui/QuitOnCloseNotice.cpp
venliong/open_source_startalk
51fda091a932a8adea626c312692836555753a9a
[ "MIT" ]
5
2019-05-29T09:32:05.000Z
2019-08-29T03:01:33.000Z
startalk_ui/QuitOnCloseNotice.cpp
venliong/open_source_startalk
51fda091a932a8adea626c312692836555753a9a
[ "MIT" ]
32
2019-03-15T09:43:22.000Z
2021-08-10T08:26:02.000Z
#include "QuitOnCloseNotice.h" #include "CustomDefine.h" #include "Session.h" #include "SettingData.h" QuitOnCloseNotice::QuitOnCloseNotice(QWidget *parent) : LocalManDialog(parent) { ui.setupUi(this); using namespace Qt; auto remove = WindowTitleHint; auto add = FramelessWindowHint | WindowMinMaxButtonsHint; setAttribute(Qt::WA_AlwaysShowToolTips, true); setAttribute(Qt::WA_TranslucentBackground, true); overrideWindowFlags( (Qt::WindowFlags)((windowFlags() & ~remove) | add)); this->setSizeGripEnabled(false); auto titlebar = ui.titblebar; titlebar->setSizeable(false); titlebar->setMinable(false); titlebar->setWindowTitle(QStringLiteral("提示")); setWindowTitle(QStringLiteral("提示")); #ifdef QCHAT setWindowIcon(QIcon(":/Images/Deal_chat.ico")); #else setWindowIcon(QIcon(":/Images/Deal.ico")); #endif auto closeOption = [this]{ bool bMin = ui.cbMinOnClose->isChecked(); int nCloseOption = bMin?Biz::QuitOnCloseOption::QOC_IGNORE:Biz::QOC_QUIT; Biz::Session::getSettingConfig()->QuitOnClose(nCloseOption); Biz::Session::saveSettingConfig(); }; connect(titlebar, &TitlebarWidget::sgCloseOnClicked, this, &LocalManDialog::onMin); connect(titlebar, &TitlebarWidget::sgCloseOnClicked,closeOption); connect(ui.cbMinOnClose,&QCheckBox::stateChanged,closeOption); } QuitOnCloseNotice::~QuitOnCloseNotice() { }
31.152174
87
0.718772
xuepingiw
3c8949e9b3a96b2201de99d1dc955aff51025ef6
9,213
cpp
C++
src/frontend/CameraParams.cpp
lefthandwriter/Kimera-VIO
641576fd86bdecbd663b4db3cb068f49502f3a2c
[ "BSD-2-Clause" ]
1,024
2019-09-20T22:55:09.000Z
2022-03-30T13:00:14.000Z
src/frontend/CameraParams.cpp
lefthandwriter/Kimera-VIO
641576fd86bdecbd663b4db3cb068f49502f3a2c
[ "BSD-2-Clause" ]
154
2019-09-23T13:10:33.000Z
2022-03-07T02:36:52.000Z
src/frontend/CameraParams.cpp
lefthandwriter/Kimera-VIO
641576fd86bdecbd663b4db3cb068f49502f3a2c
[ "BSD-2-Clause" ]
314
2019-09-20T23:49:05.000Z
2022-03-30T06:21:38.000Z
/* ---------------------------------------------------------------------------- * Copyright 2017, Massachusetts Institute of Technology, * Cambridge, MA 02139 * All Rights Reserved * Authors: Luca Carlone, et al. (see THANKS for the full author list) * See LICENSE for the license information * -------------------------------------------------------------------------- */ /** * @file CameraParams.cpp * @brief Parameters describing a monocular camera. * @author Antoni Rosinol */ #include "kimera-vio/frontend/CameraParams.h" #include <fstream> #include <iostream> #include <gtsam/navigation/ImuBias.h> namespace VIO { bool CameraParams::parseYAML(const std::string& filepath) { YamlParser yaml_parser(filepath); yaml_parser.getYamlParam("camera_id", &camera_id_); CHECK(!camera_id_.empty()) << "Camera id cannot be empty."; VLOG(1) << "Parsing camera parameters for: " << camera_id_; // Distortion parameters. parseDistortion(yaml_parser); // Camera resolution. parseImgSize(yaml_parser, &image_size_); // Camera frame rate. parseFrameRate(yaml_parser, &frame_rate_); // Camera pose wrt body. parseBodyPoseCam(yaml_parser, &body_Pose_cam_); // Intrinsics. parseCameraIntrinsics(yaml_parser, &intrinsics_); // Convert intrinsics to cv::Mat format. convertIntrinsicsVectorToMatrix(intrinsics_, &K_); // P_ = R_rectify_ * camera_matrix_; return true; } void CameraParams::parseDistortion(const YamlParser& yaml_parser) { std::string distortion_model; yaml_parser.getYamlParam("distortion_model", &distortion_model); yaml_parser.getYamlParam("camera_model", &camera_model_); distortion_model_ = stringToDistortion(distortion_model, camera_model_); CHECK(distortion_model_ == DistortionModel::RADTAN || distortion_model_ == DistortionModel::EQUIDISTANT) << "Unsupported distortion model. Expected: radtan or equidistant."; yaml_parser.getYamlParam("distortion_coefficients", &distortion_coeff_); convertDistortionVectorToMatrix(distortion_coeff_, &distortion_coeff_mat_); } const DistortionModel CameraParams::stringToDistortion( const std::string& distortion_model, const std::string& camera_model) { std::string lower_case_distortion_model = distortion_model; std::string lower_case_camera_model = camera_model; std::transform(lower_case_distortion_model.begin(), lower_case_distortion_model.end(), lower_case_distortion_model.begin(), ::tolower); std::transform(lower_case_camera_model.begin(), lower_case_camera_model.end(), lower_case_camera_model.begin(), ::tolower); if (lower_case_camera_model == "pinhole") { if (lower_case_camera_model == std::string("none")) { return DistortionModel::NONE; } else if ((lower_case_distortion_model == std::string("plumb_bob")) || (lower_case_distortion_model == std::string("radial-tangential")) || (lower_case_distortion_model == std::string("radtan"))) { return DistortionModel::RADTAN; } else if (lower_case_distortion_model == std::string("equidistant")) { return DistortionModel::EQUIDISTANT; } else { LOG(FATAL) << "Unrecognized distortion model for pinhole camera. Valid " "pinhole " "distortion model options are 'none', 'radtan', 'equidistant'."; } } else { LOG(FATAL) << "Unrecognized camera model. Valid camera models are 'pinhole'"; } } void CameraParams::convertDistortionVectorToMatrix( const std::vector<double>& distortion_coeffs, cv::Mat* distortion_coeffs_mat) { CHECK_NOTNULL(distortion_coeffs_mat); CHECK_GE(distortion_coeffs.size(), 4u); *distortion_coeffs_mat = cv::Mat::zeros(1, distortion_coeffs.size(), CV_64F); for (int k = 0; k < distortion_coeffs_mat->cols; k++) { distortion_coeffs_mat->at<double>(0, k) = distortion_coeffs[k]; } } void CameraParams::parseImgSize(const YamlParser& yaml_parser, cv::Size* image_size) { CHECK_NOTNULL(image_size); std::vector<int> resolution; yaml_parser.getYamlParam("resolution", &resolution); CHECK_EQ(resolution.size(), 2); *image_size = cv::Size(resolution[0], resolution[1]); } void CameraParams::parseFrameRate(const YamlParser& yaml_parser, double* frame_rate) { CHECK_NOTNULL(frame_rate); int rate = 0; yaml_parser.getYamlParam("rate_hz", &rate); CHECK_GT(rate, 0u); *frame_rate = 1 / static_cast<double>(rate); } void CameraParams::parseBodyPoseCam(const YamlParser& yaml_parser, gtsam::Pose3* body_Pose_cam) { CHECK_NOTNULL(body_Pose_cam); // int n_rows = 0; // yaml_parser.getNestedYamlParam("T_BS", "rows", &n_rows); // CHECK_EQ(n_rows, 4); // int n_cols = 0; // yaml_parser.getNestedYamlParam("T_BS", "cols", &n_cols); // CHECK_EQ(n_cols, 4); std::vector<double> vector_pose; yaml_parser.getNestedYamlParam("T_BS", "data", &vector_pose); *body_Pose_cam = UtilsOpenCV::poseVectorToGtsamPose3(vector_pose); } void CameraParams::parseCameraIntrinsics(const YamlParser& yaml_parser, Intrinsics* intrinsics_) { CHECK_NOTNULL(intrinsics_); std::vector<double> intrinsics; yaml_parser.getYamlParam("intrinsics", &intrinsics); CHECK_EQ(intrinsics.size(), intrinsics_->size()); // Move elements from one to the other. std::copy_n(std::make_move_iterator(intrinsics.begin()), intrinsics_->size(), intrinsics_->begin()); } void CameraParams::convertIntrinsicsVectorToMatrix(const Intrinsics& intrinsics, cv::Mat* camera_matrix) { CHECK_NOTNULL(camera_matrix); DCHECK_EQ(intrinsics.size(), 4); *camera_matrix = cv::Mat::eye(3, 3, CV_64F); camera_matrix->at<double>(0, 0) = intrinsics[0]; camera_matrix->at<double>(1, 1) = intrinsics[1]; camera_matrix->at<double>(0, 2) = intrinsics[2]; camera_matrix->at<double>(1, 2) = intrinsics[3]; } // TODO(Toni): Check if equidistant distortion is supported as well in gtsam. // TODO(Toni): rather remove this function as it is only used in tests for // uncalibrating the keypoints.. Use instead opencv. void CameraParams::createGtsamCalibration(const cv::Mat& distortion, const Intrinsics& intrinsics, gtsam::Cal3DS2* calibration) { CHECK_NOTNULL(calibration); CHECK_GE(intrinsics.size(), 4); CHECK_GE(distortion.cols, 4); CHECK_EQ(distortion.rows, 1); *calibration = gtsam::Cal3DS2(intrinsics[0], // fx intrinsics[1], // fy 0.0, // skew intrinsics[2], // u0 intrinsics[3], // v0 distortion.at<double>(0, 0), // k1 distortion.at<double>(0, 1), // k2 distortion.at<double>(0, 2), // p1 (k3) distortion.at<double>(0, 3)); // p2 (k4) } //! Display all params. void CameraParams::print() const { std::stringstream out; PipelineParams::print(out, "Camera ID ", camera_id_, "Intrinsics: \n- fx", intrinsics_[0], "- fy", intrinsics_[1], "- cu", intrinsics_[2], "- cv", intrinsics_[3], "frame_rate_: ", frame_rate_, "image_size_: \n - width", image_size_.width, "- height", image_size_.height); LOG(INFO) << out.str(); LOG(INFO) << "- body_Pose_cam_: " << body_Pose_cam_ << '\n' << "- K: " << K_ << '\n' << "- Distortion Model:" << to_underlying(distortion_model_) << '\n' << "- Distortion Coeff:" << distortion_coeff_mat_; } //! Assert equality up to a tolerance. bool CameraParams::equals(const CameraParams& cam_par, const double& tol) const { bool areIntrinsicEqual = true; for (size_t i = 0; i < intrinsics_.size(); i++) { if (std::fabs(intrinsics_[i] - cam_par.intrinsics_[i]) > tol) { areIntrinsicEqual = false; break; } } return camera_id_ == cam_par.camera_id_ && areIntrinsicEqual && body_Pose_cam_.equals(cam_par.body_Pose_cam_, tol) && (std::fabs(frame_rate_ - cam_par.frame_rate_) < tol) && (image_size_.width == cam_par.image_size_.width) && (image_size_.height == cam_par.image_size_.height) && UtilsOpenCV::compareCvMatsUpToTol(K_, cam_par.K_) && UtilsOpenCV::compareCvMatsUpToTol(distortion_coeff_mat_, cam_par.distortion_coeff_mat_); } } // namespace VIO
38.873418
80
0.604798
lefthandwriter
3c8c7a6dbd222654ab7ac130c0b985cebb66868c
3,004
cpp
C++
Unreal/CarlaUE4/Plugins/Carla/Source/Carla/Recorder/CarlaRecorderEventAdd.cpp
adelbennaceur/carla
4d6fefe73d38f0ffaef8ffafccf71245699fc5db
[ "MIT" ]
103
2020-03-10T04:21:50.000Z
2022-03-29T13:26:57.000Z
Unreal/CarlaUE4/Plugins/Carla/Source/Carla/Recorder/CarlaRecorderEventAdd.cpp
adelbennaceur/carla
4d6fefe73d38f0ffaef8ffafccf71245699fc5db
[ "MIT" ]
12
2020-04-11T11:36:01.000Z
2021-12-09T11:35:56.000Z
Unreal/CarlaUE4/Plugins/Carla/Source/Carla/Recorder/CarlaRecorderEventAdd.cpp
adelbennaceur/carla
4d6fefe73d38f0ffaef8ffafccf71245699fc5db
[ "MIT" ]
11
2018-09-28T16:18:37.000Z
2022-01-04T06:02:05.000Z
// Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma // de Barcelona (UAB). // // This work is licensed under the terms of the MIT license. // For a copy, see <https://opensource.org/licenses/MIT>. #include "CarlaRecorder.h" #include "CarlaRecorderEventAdd.h" #include "CarlaRecorderHelpers.h" void CarlaRecorderEventAdd::Write(std::ofstream &OutFile) const { // database id WriteValue<uint32_t>(OutFile, this->DatabaseId); WriteValue<uint8_t>(OutFile, this->Type); // transform WriteFVector(OutFile, this->Location); WriteFVector(OutFile, this->Rotation); // description type WriteValue<uint32_t>(OutFile, this->Description.UId); WriteFString(OutFile, this->Description.Id); // attributes uint16_t Total = this->Description.Attributes.size(); WriteValue<uint16_t>(OutFile, Total); for (uint16_t i=0; i<Total; ++i) { // type WriteValue<uint8_t>(OutFile, this->Description.Attributes[i].Type); WriteFString(OutFile, this->Description.Attributes[i].Id); WriteFString(OutFile, this->Description.Attributes[i].Value); } } void CarlaRecorderEventAdd::Read(std::ifstream &InFile) { // database id ReadValue<uint32_t>(InFile, this->DatabaseId); // database type ReadValue<uint8_t>(InFile, this->Type); // transform ReadFVector(InFile, this->Location); ReadFVector(InFile, this->Rotation); // description type ReadValue<uint32_t>(InFile, this->Description.UId); ReadFString(InFile, this->Description.Id); // attributes uint16_t Total; ReadValue<uint16_t>(InFile, Total); this->Description.Attributes.clear(); this->Description.Attributes.reserve(Total); for (uint16_t i=0; i<Total; ++i) { CarlaRecorderActorAttribute Att; ReadValue<uint8_t>(InFile, Att.Type); ReadFString(InFile, Att.Id); ReadFString(InFile, Att.Value); this->Description.Attributes.push_back(std::move(Att)); } } //--------------------------------------------- inline void CarlaRecorderEventsAdd::Clear(void) { Events.clear(); } inline void CarlaRecorderEventsAdd::Add(const CarlaRecorderEventAdd &Event) { Events.push_back(std::move(Event)); } void CarlaRecorderEventsAdd::Write(std::ofstream &OutFile) { // write the packet id WriteValue<char>(OutFile, static_cast<char>(CarlaRecorderPacketId::EventAdd)); std::streampos PosStart = OutFile.tellp(); // write a dummy packet size uint32_t Total = 0; WriteValue<uint32_t>(OutFile, Total); // write total records Total = Events.size(); WriteValue<uint16_t>(OutFile, Total); for (uint16_t i=0; i<Total; ++i) Events[i].Write(OutFile); // write the real packet size std::streampos PosEnd = OutFile.tellp(); Total = PosEnd - PosStart - sizeof(uint32_t); OutFile.seekp(PosStart, std::ios::beg); WriteValue<uint32_t>(OutFile, Total); OutFile.seekp(PosEnd, std::ios::beg); }
28.884615
82
0.672104
adelbennaceur
3c8e8b4532acc284268d548f1ff3f7ee18b2ca90
9,545
cpp
C++
Win32.Rage/misc.cpp
010001111/Vx-Suites
6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79
[ "MIT" ]
2
2021-02-04T06:47:45.000Z
2021-07-28T10:02:10.000Z
Win32.Rage/misc.cpp
010001111/Vx-Suites
6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79
[ "MIT" ]
null
null
null
Win32.Rage/misc.cpp
010001111/Vx-Suites
6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79
[ "MIT" ]
null
null
null
#include "include.h" BOOL AntiSandBox() { char *users[] = {"sandbox", "honey", "vmware", "currentuser", "nepenthes"}; DWORD size = 128; char szUser[128]; int i; GetUserName(szUser, &size); CharLower(szUser); for (i = 0; i < (sizeof(users) / sizeof(LPTSTR)); i++) { if (strstr(szUser, users[i]) != 0) return TRUE; } return FALSE; } int Bot_Install(unsigned int Type, char FileName[MAX_PATH]) { char TempDir[MAX_PATH], CopyPath[MAX_PATH], CurrentName[MAX_PATH]; char *Word; FILE *rF, *wF; char *Buffer; switch (Type) { case 1: { //Type 1: //Copy to Program Files//Common Files//System if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PROGRAM_FILES_COMMON|CSIDL_FLAG_CREATE, NULL, 0, TempDir))) { _snprintf(CopyPath, sizeof(CopyPath), "%s\\System", TempDir); if (CreateDirectory(TempDir, NULL) == 0) { if (GetLastError() == ERROR_PATH_NOT_FOUND) { _snprintf(BotToCloneDir, sizeof(BotToCloneDir), TempDir); _snprintf(CopyPath, sizeof(CopyPath), "%s\\%s", TempDir, FileName); break; } } SetFileAttributes(CopyPath, FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM); _snprintf(BotToCloneDir, sizeof(BotToCloneDir), CopyPath); _snprintf(CopyPath, sizeof(CopyPath), "%s\\%s", CopyPath, FileName); break; } else return 0; } case 2: { //Type 2: //We install this bot into Documents and settings directory, but //because theres no function to get it, we will get temp directory //first and then strtok it into special words, then combine back GetTempPath(sizeof(TempDir), TempDir); Word = strtok(TempDir, "\\"); //If we failed, lets switch to another option if (Word == NULL) return 0; //We have pointer to "C:" in Word now so lets add it to our path _snprintf(CopyPath, sizeof(CopyPath), "%s\\", Word); //Let's get first map Word = strtok(NULL, "\\"); if (Word == NULL) return 0; _snprintf(BotToCloneDir, sizeof(BotToCloneDir), "%s%s", CopyPath, Word); _snprintf(CopyPath, sizeof(CopyPath), "%s%s\\%s", CopyPath, Word, FileName); break; } case 3: { //Type 3: //We install this bot into C:\\RECYCLER folder, //assuming that the folder exists, if not, we create it and set //hidden parameter _snprintf(TempDir, sizeof(TempDir), "C:\\RECYCLER"); if (CreateDirectory(TempDir, NULL) == 0) { if (GetLastError() == ERROR_PATH_NOT_FOUND) //Looks like theres some higher force return 0; } else SetFileAttributes(TempDir, FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM); _snprintf(BotToCloneDir, sizeof(BotToCloneDir), TempDir); _snprintf(CopyPath, sizeof(CopyPath), "%s\\%s", TempDir, FileName); break; } /* case 4: { //Type 4: //Install to %windir% (using only if type 1 & type 2 fails) GetSystemWindowsDirectory(TempDir, sizeof(TempDir)); _snprintf(BotToCloneDir, sizeof(BotToCloneDir), TempDir); _snprintf(CopyPath, sizeof(CopyPath), "%s\\%s", TempDir, FileName); break; }*/ } //Get name of our current file GetModuleFileName(0, CurrentName, sizeof(CurrentName)); #ifdef DEBUG printf("Installing to: %s\n", CopyPath); #endif rF = fopen(CurrentName, "rb"); if (rF == NULL) { #ifdef DEBUG printf("Failed to open (rb): %s\n", CurrentName); #endif return 0; } wF = fopen(CopyPath, "wb"); if (wF == NULL) { if (strstr(CurrentName, FileName) != NULL) { #ifdef DEBUG printf("File already installed!\n"); #endif _snprintf(BotToClone, sizeof(BotToClone), CopyPath); SetFileAttributes(CopyPath, FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM); return 2; } else { #ifdef DEBUG printf("Failed to open (wb): %s\n", CopyPath); #endif return 0; } } //At this point, we have both files opened, now lets start copying Buffer = (char *) malloc (1); while (fread(Buffer, 1, 1, rF) == 1) { if (fwrite(Buffer, 1, 1, wF) != 1) { #ifdef DEBUG printf("Failed to write to: %s\n", CopyPath); #endif fclose(rF); fclose(wF); return 0; } } fclose(rF); fclose(wF); SetFileAttributes(CopyPath, FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM); _snprintf(BotToClone, sizeof(BotToClone), CopyPath); #ifdef DEBUG printf("File installed to: %s\n", CopyPath); #endif return 1; } unsigned int Resolve(char *host) { struct hostent *hp; unsigned int host_ip; host_ip = inet_addr(host); if(host_ip == INADDR_NONE) { hp = gethostbyname(host); if(hp == 0) { return 0; } else host_ip = *(u_int *)(hp->h_addr); } return(host_ip); } char *GenerateLetterNick(int Len, SOCKET Sock) { char *Nick; int r, i; char Buffer[] = "abcdefghijklmnopqrstuvwxyz"; BOOL UseBuffer = TRUE; if (Len == 0) { Len = (rand()%5)+5; UseBuffer = FALSE; } Nick = (char *) malloc (Len); srand(GetTickCount()); for (i = 0; i < Len; i++) { if ((UseBuffer) && (i > 0)) { r = rand()%strlen(Buffer); Nick[i] = Buffer[r]; } else { r = rand()%26; Nick[i] = r+97; } } if (UseBuffer) { char c; if (PrivateIP(GetIP(Sock))) c = '['; else c = '['; Nick[0] = c; OSVERSIONINFO verinfo; verinfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx(&verinfo); if (verinfo.dwMajorVersion == 5 && verinfo.dwMinorVersion == 0) c = '1'; else if (verinfo.dwMajorVersion == 5 && verinfo.dwMinorVersion == 1) { if (strstr(verinfo.szCSDVersion, "2") != NULL) c = '-'; else c = '-'; } else c = '-'; Nick[1] = 'n'; Nick[2] = 'L'; Nick[3] = 'h'; Nick[4] = '-'; Nick[5] = 'V'; Nick[6] = 'N'; Nick[7] = 'C'; Nick[8] = ']'; } Nick[i] = '\0'; return Nick; } char *GenerateNumberNick(int Len) { char *Nick; int i; Nick = (char *) malloc (Len); Nick[0] = '\0'; srand(GetTickCount()); for (i = 0; i < Len; i++) { sprintf(Nick, "%s%d", Nick, rand()%10); } Nick[i] = '\0'; return Nick; } char *GetIP(SOCKET Sock) { static char IP[16]; SOCKADDR sa; int sas = sizeof(sa); memset(&sa, 0, sizeof(sa)); getsockname(Sock, &sa, &sas); sprintf(IP,"%d.%d.%d.%d",(BYTE)sa.sa_data[2], (BYTE)sa.sa_data[3], (BYTE)sa.sa_data[4], (BYTE)sa.sa_data[5]); return (IP); } int PrepareThreads() { unsigned int i; for (i = 0; i < MAX_THREADS; i++) Thread[i].Type = 0; return 1; } int AddThread(DWORD Type) { unsigned int i = 0; while (Thread[i].Type != 0) i++; if (i >= MAX_THREADS) return -1; else { Thread[i].Type = Type; return i; } } int KillThread(DWORD Type) { unsigned int i, k = 0; for (i = 0; i < MAX_THREADS; i++) { if (Thread[i].Type == Type) { TerminateThread(Thread[i].tHandle, 0); Thread[i].Type = 0; closesocket(Thread[i].Sock); k++; } } return k; } void KillAllThreads() { unsigned int i; for (i = 0; i < MAX_THREADS; i++) { if (Thread[i].tHandle != NULL) TerminateThread(Thread[i].tHandle, 0); } } int ClearThread(int i) { Thread[i].Type = 0; closesocket(Thread[i].Sock); return 1; } int CheckThread(DWORD Type) { unsigned int i, k = 0; for (i = 0; i < MAX_THREADS; i++) if (Thread[i].Type == Type) k++; return k; } BOOL checkos() { OSVERSIONINFO verinfo; verinfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx(&verinfo); if (verinfo.dwMajorVersion == 5 && verinfo.dwMinorVersion == 1 && (strstr(verinfo.szCSDVersion, "2") != NULL)) return TRUE; else return FALSE; } BOOL PrivateIP(const char *ip) { if (ip) { if (strcmp(ip, "") != 0) { char *token, ipbuf[32]; strncpy(ipbuf, ip, sizeof(ipbuf)); if ((token=strtok(ipbuf, ".")) != NULL) { int ip1 = atoi(token); if ((token=strtok(NULL, ".")) != NULL) { int ip2 = atoi(token); if ((ip1 == 10) // Class A Private Network || (ip1 == 172 && ip2 > 15 && ip2 < 32) // Class B Private Network || (ip1 == 192 && ip2 == 168)) // Class C Private Network return TRUE; } } } } return FALSE; } void Uninstall() { char buffer[1024], cmdline[MAX_PATH], botfile[MAX_PATH], batfile[MAX_PATH]; KillAllThreads(); HKEY Reg; RegCreateKeyEx(HKEY_LOCAL_MACHINE, Decode(string_autostart_location), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &Reg, NULL); RegDeleteValue(Reg, Decode(string_autostart_description)); RegCloseKey(Reg); GetTempPath(sizeof(buffer), buffer); sprintf(batfile, "%sdel.bat", buffer); HANDLE f = CreateFile(batfile, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0); if (f > (HANDLE)0) { DWORD r; sprintf(buffer,"@echo off\r\n" ":repeat\r\n" "del \"%%1\"\r\n" "if exist \"%%1\" goto repeat\r\n" "del \"%s\"", batfile); WriteFile(f, buffer, strlen(buffer), &r, NULL); CloseHandle(f); PROCESS_INFORMATION pinfo; STARTUPINFO sinfo; memset(&pinfo, 0, sizeof(pinfo)); memset(&sinfo, 0, sizeof(sinfo)); sinfo.lpTitle = ""; sinfo.cb = sizeof(sinfo); sinfo.dwFlags = STARTF_USESHOWWINDOW; sinfo.wShowWindow = SW_HIDE; GetModuleFileName(GetModuleHandle(NULL), botfile, sizeof(botfile)); if (GetFileAttributes(botfile) != INVALID_FILE_ATTRIBUTES) SetFileAttributes(botfile,FILE_ATTRIBUTE_NORMAL); sprintf(buffer, "%%comspec%% /c %s %s", batfile, botfile); ExpandEnvironmentStrings(buffer, cmdline, sizeof(cmdline)); CreateProcess(NULL, cmdline, NULL, NULL, TRUE, BELOW_NORMAL_PRIORITY_CLASS | DETACHED_PROCESS, NULL, NULL, &sinfo, &pinfo); } return; }
21.546275
139
0.62682
010001111
3c927e7c92e75a362a2b80e991a25fd2927ef931
1,209
cpp
C++
test/std/utilities/meta/meta.trans/meta.trans.cv/remove_const.pass.cpp
webrtcmirrors/chromium_llvm-project_libcxx
f759756c126dcf3f24f7636cf071a4db0f574186
[ "Apache-2.0" ]
null
null
null
test/std/utilities/meta/meta.trans/meta.trans.cv/remove_const.pass.cpp
webrtcmirrors/chromium_llvm-project_libcxx
f759756c126dcf3f24f7636cf071a4db0f574186
[ "Apache-2.0" ]
null
null
null
test/std/utilities/meta/meta.trans/meta.trans.cv/remove_const.pass.cpp
webrtcmirrors/chromium_llvm-project_libcxx
f759756c126dcf3f24f7636cf071a4db0f574186
[ "Apache-2.0" ]
null
null
null
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // type_traits // remove_const #include <type_traits> #include "test_macros.h" template <class T, class U> void test_remove_const_imp() { static_assert((std::is_same<typename std::remove_const<T>::type, U>::value), ""); #if TEST_STD_VER > 11 static_assert((std::is_same<std::remove_const_t<T>, U>::value), ""); #endif } template <class T> void test_remove_const() { test_remove_const_imp<T, T>(); test_remove_const_imp<const T, T>(); test_remove_const_imp<volatile T, volatile T>(); test_remove_const_imp<const volatile T, volatile T>(); } int main(int, char**) { test_remove_const<void>(); test_remove_const<int>(); test_remove_const<int[3]>(); test_remove_const<int&>(); test_remove_const<const int&>(); test_remove_const<int*>(); test_remove_const<const int*>(); return 0; }
25.723404
85
0.600496
webrtcmirrors
3c92ab6b4300d500a8b9f8314224a28c3b0daa40
5,638
hpp
C++
src/include/def/defrCallBacks.hpp
jinwookjungs/lefdef_parser
32829274d247c418c080328484359a750dae4cec
[ "Apache-2.0" ]
13
2019-04-21T08:09:32.000Z
2022-02-20T03:06:30.000Z
src/include/def/defrCallBacks.hpp
jinwookjungs/lefdef_parser
32829274d247c418c080328484359a750dae4cec
[ "Apache-2.0" ]
3
2019-06-06T02:40:27.000Z
2021-12-01T04:56:20.000Z
src/include/def/defrCallBacks.hpp
jinwookjungs/lefdef_parser
32829274d247c418c080328484359a750dae4cec
[ "Apache-2.0" ]
6
2016-10-21T08:39:35.000Z
2021-01-30T12:38:58.000Z
// ***************************************************************************** // ***************************************************************************** // Copyright 2013, Cadence Design Systems // // This file is part of the Cadence LEF/DEF Open Source // Distribution, Product Version 5.8. // // 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. // // For updates, support, or to become part of the LEF/DEF Community, // check www.openeda.org for details. // // $Author: dell $ // $Revision: #7 $ // $Date: 2015/01/27 $ // $State: $ // ***************************************************************************** // ***************************************************************************** #ifndef DEFRCALLBACKS_H #define DEFRCALLBACKS_H 1 #include "defiKRDefs.hpp" #include "defrReader.hpp" #include "defrReader.hpp" BEGIN_LEFDEF_PARSER_NAMESPACE class defrCallbacks { public: defrCallbacks(); static void reset(); void SetUnusedCallbacks(defrVoidCbkFnType f); defrStringCbkFnType DesignCbk; defrStringCbkFnType TechnologyCbk; defrVoidCbkFnType DesignEndCbk; defrPropCbkFnType PropCbk; defrVoidCbkFnType PropDefEndCbk; defrVoidCbkFnType PropDefStartCbk; defrStringCbkFnType ArrayNameCbk; defrStringCbkFnType FloorPlanNameCbk; defrDoubleCbkFnType UnitsCbk; defrStringCbkFnType DividerCbk; defrStringCbkFnType BusBitCbk; defrSiteCbkFnType SiteCbk; defrSiteCbkFnType CanplaceCbk; defrSiteCbkFnType CannotOccupyCbk; defrIntegerCbkFnType ComponentStartCbk; defrVoidCbkFnType ComponentEndCbk; defrComponentCbkFnType ComponentCbk; defrComponentMaskShiftLayerCbkFnType ComponentMaskShiftLayerCbk; defrIntegerCbkFnType NetStartCbk; defrVoidCbkFnType NetEndCbk; defrNetCbkFnType NetCbk; defrStringCbkFnType NetNameCbk; defrStringCbkFnType NetSubnetNameCbk; defrStringCbkFnType NetNonDefaultRuleCbk; defrNetCbkFnType NetPartialPathCbk; defrPathCbkFnType PathCbk; defrDoubleCbkFnType VersionCbk; defrStringCbkFnType VersionStrCbk; defrStringCbkFnType PinExtCbk; defrStringCbkFnType ComponentExtCbk; defrStringCbkFnType ViaExtCbk; defrStringCbkFnType NetConnectionExtCbk; defrStringCbkFnType NetExtCbk; defrStringCbkFnType GroupExtCbk; defrStringCbkFnType ScanChainExtCbk; defrStringCbkFnType IoTimingsExtCbk; defrStringCbkFnType PartitionsExtCbk; defrStringCbkFnType HistoryCbk; defrBoxCbkFnType DieAreaCbk; defrPinCapCbkFnType PinCapCbk; defrPinCbkFnType PinCbk; defrIntegerCbkFnType StartPinsCbk; defrVoidCbkFnType PinEndCbk; defrIntegerCbkFnType DefaultCapCbk; defrRowCbkFnType RowCbk; defrTrackCbkFnType TrackCbk; defrGcellGridCbkFnType GcellGridCbk; defrIntegerCbkFnType ViaStartCbk; defrVoidCbkFnType ViaEndCbk; defrViaCbkFnType ViaCbk; defrIntegerCbkFnType RegionStartCbk; defrVoidCbkFnType RegionEndCbk; defrRegionCbkFnType RegionCbk; defrIntegerCbkFnType SNetStartCbk; defrVoidCbkFnType SNetEndCbk; defrNetCbkFnType SNetCbk; defrNetCbkFnType SNetPartialPathCbk; defrNetCbkFnType SNetWireCbk; defrIntegerCbkFnType GroupsStartCbk; defrVoidCbkFnType GroupsEndCbk; defrStringCbkFnType GroupNameCbk; defrStringCbkFnType GroupMemberCbk; defrGroupCbkFnType GroupCbk; defrIntegerCbkFnType AssertionsStartCbk; defrVoidCbkFnType AssertionsEndCbk; defrAssertionCbkFnType AssertionCbk; defrIntegerCbkFnType ConstraintsStartCbk; defrVoidCbkFnType ConstraintsEndCbk; defrAssertionCbkFnType ConstraintCbk; defrIntegerCbkFnType ScanchainsStartCbk; defrVoidCbkFnType ScanchainsEndCbk; defrScanchainCbkFnType ScanchainCbk; defrIntegerCbkFnType IOTimingsStartCbk; defrVoidCbkFnType IOTimingsEndCbk; defrIOTimingCbkFnType IOTimingCbk; defrIntegerCbkFnType FPCStartCbk; defrVoidCbkFnType FPCEndCbk; defrFPCCbkFnType FPCCbk; defrIntegerCbkFnType TimingDisablesStartCbk; defrVoidCbkFnType TimingDisablesEndCbk; defrTimingDisableCbkFnType TimingDisableCbk; defrIntegerCbkFnType PartitionsStartCbk; defrVoidCbkFnType PartitionsEndCbk; defrPartitionCbkFnType PartitionCbk; defrIntegerCbkFnType PinPropStartCbk; defrVoidCbkFnType PinPropEndCbk; defrPinPropCbkFnType PinPropCbk; defrIntegerCbkFnType CaseSensitiveCbk; defrIntegerCbkFnType BlockageStartCbk; defrVoidCbkFnType BlockageEndCbk; defrBlockageCbkFnType BlockageCbk; defrIntegerCbkFnType SlotStartCbk; defrVoidCbkFnType SlotEndCbk; defrSlotCbkFnType SlotCbk; defrIntegerCbkFnType FillStartCbk; defrVoidCbkFnType FillEndCbk; defrFillCbkFnType FillCbk; defrIntegerCbkFnType NonDefaultStartCbk; defrVoidCbkFnType NonDefaultEndCbk; defrNonDefaultCbkFnType NonDefaultCbk; defrIntegerCbkFnType StylesStartCbk; defrVoidCbkFnType StylesEndCbk; defrStylesCbkFnType StylesCbk; defrStringCbkFnType ExtensionCbk; }; extern defrCallbacks *defCallbacks; END_LEFDEF_PARSER_NAMESPACE USE_LEFDEF_PARSER_NAMESPACE #endif
34.802469
80
0.745654
jinwookjungs
3c963c48ed7a3b1a6d6f30426e3a72c66a7ccea8
15,048
cpp
C++
2018/Cpp/day16/part2.cpp
tymscar/Advent-Of-Code
cd7b96b0253191e236bd704b0d8b5540fb3e8ef6
[ "MIT" ]
4
2019-12-08T08:20:53.000Z
2021-12-17T12:04:11.000Z
2018/Cpp/day16/part2.cpp
tymscar/AdventOfCode2018
9742ddb6bbbc917062baad87d6b6de75375f1ae8
[ "MIT" ]
null
null
null
2018/Cpp/day16/part2.cpp
tymscar/AdventOfCode2018
9742ddb6bbbc917062baad87d6b6de75375f1ae8
[ "MIT" ]
4
2020-12-11T22:10:24.000Z
2021-12-25T22:39:05.000Z
#include <iostream> #include <algorithm> #include <fstream> #include <vector> #include <unordered_map> #include <string> std::vector<int> eqrr (int inputOne, int inputTwo, int output, std::vector<int> registorState){ if(registorState[inputOne] == registorState[inputTwo]) registorState[output] = 1; else registorState[output] = 0; return registorState; } std::vector<int> eqri (int inputOne, int inputTwo, int output, std::vector<int> registorState){ if(registorState[inputOne] == inputTwo) registorState[output] = 1; else registorState[output] = 0; return registorState; } std::vector<int> eqir(int inputOne, int inputTwo, int output, std::vector<int> registorState){ if(inputOne == registorState[inputTwo]) registorState[output] = 1; else registorState[output] = 0; return registorState; } std::vector<int> gtrr (int inputOne, int inputTwo, int output, std::vector<int> registorState){ if(registorState[inputOne] > registorState[inputTwo]) registorState[output] = 1; else registorState[output] = 0; return registorState; } std::vector<int> gtri (int inputOne, int inputTwo, int output, std::vector<int> registorState){ if(registorState[inputOne] > inputTwo) registorState[output] = 1; else registorState[output] = 0; return registorState; } std::vector<int> gtir(int inputOne, int inputTwo, int output, std::vector<int> registorState){ if(inputOne > registorState[inputTwo]) registorState[output] = 1; else registorState[output] = 0; return registorState; } std::vector<int> seti(int inputOne, int inputTwo, int output, std::vector<int> registorState){ registorState[output] = inputOne; return registorState; } std::vector<int> setr(int inputOne, int inputTwo, int output, std::vector<int> registorState){ registorState[output] = registorState[inputOne]; return registorState; } std::vector<int> bori(int inputOne, int inputTwo, int output, std::vector<int> registorState){ registorState[output] = registorState[inputOne] | inputTwo; return registorState; } std::vector<int> borr(int inputOne, int inputTwo, int output, std::vector<int> registorState){ registorState[output] = registorState[inputOne] | registorState[inputTwo]; return registorState; } std::vector<int> bani(int inputOne, int inputTwo, int output, std::vector<int> registorState){ registorState[output] = registorState[inputOne] & inputTwo; return registorState; } std::vector<int> banr(int inputOne, int inputTwo, int output, std::vector<int> registorState){ registorState[output] = registorState[inputOne] & registorState[inputTwo]; return registorState; } std::vector<int> mulr(int inputOne, int inputTwo, int output, std::vector<int> registorState){ registorState[output] = registorState[inputOne] * registorState[inputTwo]; return registorState; } std::vector<int> muli(int inputOne, int inputTwo, int output, std::vector<int> registorState){ registorState[output] = registorState[inputOne] * inputTwo; return registorState; } std::vector<int> addr(int inputOne, int inputTwo, int output, std::vector<int> registorState){ registorState[output] = registorState[inputOne] + registorState[inputTwo]; return registorState; } std::vector<int> addi(int inputOne, int inputTwo, int output, std::vector<int> registorState){ registorState[output] = registorState[inputOne] + inputTwo; return registorState; } void execute(int opcode, int A, int B, int C, std::unordered_map<int, std::string>& opcodeToNameOfFunction, std::vector<int>& registers){ if(opcodeToNameOfFunction[opcode] == "addr"){ registers = addr(A, B, C, registers); } if(opcodeToNameOfFunction[opcode] == "addi"){ registers = addi(A, B, C, registers); } if(opcodeToNameOfFunction[opcode] == "mulr"){ registers = mulr(A, B, C, registers); } if(opcodeToNameOfFunction[opcode] == "muli"){ registers = muli(A, B, C, registers); } if(opcodeToNameOfFunction[opcode] == "banr"){ registers = banr(A, B, C, registers); } if(opcodeToNameOfFunction[opcode] == "bani"){ registers = bani(A, B, C, registers); } if(opcodeToNameOfFunction[opcode] == "borr"){ registers = borr(A, B, C, registers); } if(opcodeToNameOfFunction[opcode] == "bori"){ registers = bori(A, B, C, registers); } if(opcodeToNameOfFunction[opcode] == "setr"){ registers = setr(A, B, C, registers); } if(opcodeToNameOfFunction[opcode] == "seti"){ registers = seti(A, B, C, registers); } if(opcodeToNameOfFunction[opcode] == "gtir"){ registers = gtir(A, B, C, registers); } if(opcodeToNameOfFunction[opcode] == "gtri"){ registers = gtri(A, B, C, registers); } if(opcodeToNameOfFunction[opcode] == "gtrr"){ registers = gtrr(A, B, C, registers); } if(opcodeToNameOfFunction[opcode] == "eqir"){ registers = eqir(A, B, C, registers); } if(opcodeToNameOfFunction[opcode] == "eqri"){ registers = eqri(A, B, C, registers); } if(opcodeToNameOfFunction[opcode] == "eqrr"){ registers = eqrr(A, B, C, registers); } } int main(){ std::ifstream file; file.open("part1in.txt"); std::string input; std::unordered_map<int, std::vector<std::string> > opcodeNameList; for(int i=0;i<16;i++){ opcodeNameList[i].push_back("addr"); opcodeNameList[i].push_back("addi"); opcodeNameList[i].push_back("mulr"); opcodeNameList[i].push_back("muli"); opcodeNameList[i].push_back("banr"); opcodeNameList[i].push_back("bani"); opcodeNameList[i].push_back("borr"); opcodeNameList[i].push_back("bori"); opcodeNameList[i].push_back("setr"); opcodeNameList[i].push_back("seti"); opcodeNameList[i].push_back("gtir"); opcodeNameList[i].push_back("gtri"); opcodeNameList[i].push_back("gtrr"); opcodeNameList[i].push_back("eqir"); opcodeNameList[i].push_back("eqri"); opcodeNameList[i].push_back("eqrr"); } std::unordered_map<std::string, std::vector<int> >nameOpcodeList; for(int i=0; i<16; i++){ nameOpcodeList["addr"].push_back(i); nameOpcodeList["addi"].push_back(i); nameOpcodeList["mulr"].push_back(i); nameOpcodeList["muli"].push_back(i); nameOpcodeList["banr"].push_back(i); nameOpcodeList["bani"].push_back(i); nameOpcodeList["borr"].push_back(i); nameOpcodeList["bori"].push_back(i); nameOpcodeList["setr"].push_back(i); nameOpcodeList["seti"].push_back(i); nameOpcodeList["gtir"].push_back(i); nameOpcodeList["gtri"].push_back(i); nameOpcodeList["gtrr"].push_back(i); nameOpcodeList["eqir"].push_back(i); nameOpcodeList["eqri"].push_back(i); nameOpcodeList["eqrr"].push_back(i); } int opcodesLeft = 16; std::unordered_map<std::string, int> opcodeId; opcodeId["addr"] = -1; opcodeId["addi"] = -1; opcodeId["mulr"] = -1; opcodeId["muli"] = -1; opcodeId["banr"] = -1; opcodeId["bani"] = -1; opcodeId["borr"] = -1; opcodeId["bori"] = -1; opcodeId["setr"] = -1; opcodeId["seti"] = -1; opcodeId["gtir"] = -1; opcodeId["gtri"] = -1; opcodeId["gtrr"] = -1; opcodeId["eqir"] = -1; opcodeId["eqri"] = -1; opcodeId["eqrr"] = -1; while(file >> input){ std::vector<int> registorsOld; file >> input; registorsOld.push_back(input[1] - '0'); file >> input; registorsOld.push_back(input[0] - '0'); file >> input; registorsOld.push_back(input[0] - '0'); file >> input; registorsOld.push_back(input[0] - '0'); int opcode, A, B, C; file >> input; opcode = std::stoi(input); file >> input; A = std::stoi(input); file >> input; B = std::stoi(input); file >> input; C = std::stoi(input); file >> input; std::vector<int> registorsNew; file >> input; registorsNew.push_back(input[1] - '0'); file >> input; registorsNew.push_back(input[0] - '0'); file >> input; registorsNew.push_back(input[0] - '0'); file >> input; registorsNew.push_back(input[0] - '0'); if(addr(A, B, C, registorsOld) != registorsNew){ opcodeNameList[opcode].erase(std::remove(opcodeNameList[opcode].begin(), opcodeNameList[opcode].end(), "addr"), opcodeNameList[opcode].end()); nameOpcodeList["addr"].erase(std::remove(nameOpcodeList["addr"].begin(), nameOpcodeList["addr"].end(), opcode), nameOpcodeList["addr"].end()); } if(addi(A, B, C, registorsOld) != registorsNew){ opcodeNameList[opcode].erase(std::remove(opcodeNameList[opcode].begin(), opcodeNameList[opcode].end(), "addi"), opcodeNameList[opcode].end()); nameOpcodeList["addi"].erase(std::remove(nameOpcodeList["addi"].begin(), nameOpcodeList["addi"].end(), opcode), nameOpcodeList["addi"].end()); } if(mulr(A, B, C, registorsOld) != registorsNew){ opcodeNameList[opcode].erase(std::remove(opcodeNameList[opcode].begin(), opcodeNameList[opcode].end(), "mulr"), opcodeNameList[opcode].end()); nameOpcodeList["mulr"].erase(std::remove(nameOpcodeList["mulr"].begin(), nameOpcodeList["mulr"].end(), opcode), nameOpcodeList["mulr"].end()); } if(muli(A, B, C, registorsOld) != registorsNew){ opcodeNameList[opcode].erase(std::remove(opcodeNameList[opcode].begin(), opcodeNameList[opcode].end(), "muli"), opcodeNameList[opcode].end()); nameOpcodeList["muli"].erase(std::remove(nameOpcodeList["muli"].begin(), nameOpcodeList["muli"].end(), opcode), nameOpcodeList["muli"].end()); } if(banr(A, B, C, registorsOld) != registorsNew){ opcodeNameList[opcode].erase(std::remove(opcodeNameList[opcode].begin(), opcodeNameList[opcode].end(), "banr"), opcodeNameList[opcode].end()); nameOpcodeList["banr"].erase(std::remove(nameOpcodeList["banr"].begin(), nameOpcodeList["banr"].end(), opcode), nameOpcodeList["banr"].end()); } if(bani(A, B, C, registorsOld) != registorsNew){ opcodeNameList[opcode].erase(std::remove(opcodeNameList[opcode].begin(), opcodeNameList[opcode].end(), "bani"), opcodeNameList[opcode].end()); nameOpcodeList["bani"].erase(std::remove(nameOpcodeList["bani"].begin(), nameOpcodeList["bani"].end(), opcode), nameOpcodeList["bani"].end()); } if(borr(A, B, C, registorsOld) != registorsNew){ opcodeNameList[opcode].erase(std::remove(opcodeNameList[opcode].begin(), opcodeNameList[opcode].end(), "borr"), opcodeNameList[opcode].end()); nameOpcodeList["borr"].erase(std::remove(nameOpcodeList["borr"].begin(), nameOpcodeList["borr"].end(), opcode), nameOpcodeList["borr"].end()); } if(bori(A, B, C, registorsOld) != registorsNew){ opcodeNameList[opcode].erase(std::remove(opcodeNameList[opcode].begin(), opcodeNameList[opcode].end(), "bori"), opcodeNameList[opcode].end()); nameOpcodeList["bori"].erase(std::remove(nameOpcodeList["bori"].begin(), nameOpcodeList["bori"].end(), opcode), nameOpcodeList["bori"].end()); } if(setr(A, B, C, registorsOld) != registorsNew){ opcodeNameList[opcode].erase(std::remove(opcodeNameList[opcode].begin(), opcodeNameList[opcode].end(), "setr"), opcodeNameList[opcode].end()); nameOpcodeList["setr"].erase(std::remove(nameOpcodeList["setr"].begin(), nameOpcodeList["setr"].end(), opcode), nameOpcodeList["setr"].end()); } if(seti(A, B, C, registorsOld) != registorsNew){ opcodeNameList[opcode].erase(std::remove(opcodeNameList[opcode].begin(), opcodeNameList[opcode].end(), "seti"), opcodeNameList[opcode].end()); nameOpcodeList["seti"].erase(std::remove(nameOpcodeList["seti"].begin(), nameOpcodeList["seti"].end(), opcode), nameOpcodeList["seti"].end()); } if(gtir(A, B, C, registorsOld) != registorsNew){ opcodeNameList[opcode].erase(std::remove(opcodeNameList[opcode].begin(), opcodeNameList[opcode].end(), "gtir"), opcodeNameList[opcode].end()); nameOpcodeList["gtir"].erase(std::remove(nameOpcodeList["gtir"].begin(), nameOpcodeList["gtir"].end(), opcode), nameOpcodeList["gtir"].end()); } if(gtri(A, B, C, registorsOld) != registorsNew){ opcodeNameList[opcode].erase(std::remove(opcodeNameList[opcode].begin(), opcodeNameList[opcode].end(), "gtri"), opcodeNameList[opcode].end()); nameOpcodeList["gtri"].erase(std::remove(nameOpcodeList["gtri"].begin(), nameOpcodeList["gtri"].end(), opcode), nameOpcodeList["gtri"].end()); } if(gtrr(A, B, C, registorsOld) != registorsNew){ opcodeNameList[opcode].erase(std::remove(opcodeNameList[opcode].begin(), opcodeNameList[opcode].end(), "gtrr"), opcodeNameList[opcode].end()); nameOpcodeList["gtrr"].erase(std::remove(nameOpcodeList["gtrr"].begin(), nameOpcodeList["gtrr"].end(), opcode), nameOpcodeList["gtrr"].end()); } if(eqir(A, B, C, registorsOld) != registorsNew){ opcodeNameList[opcode].erase(std::remove(opcodeNameList[opcode].begin(), opcodeNameList[opcode].end(), "eqir"), opcodeNameList[opcode].end()); nameOpcodeList["eqir"].erase(std::remove(nameOpcodeList["eqir"].begin(), nameOpcodeList["eqir"].end(), opcode), nameOpcodeList["eqir"].end()); } if(eqri(A, B, C, registorsOld) != registorsNew){ opcodeNameList[opcode].erase(std::remove(opcodeNameList[opcode].begin(), opcodeNameList[opcode].end(), "eqri"), opcodeNameList[opcode].end()); nameOpcodeList["eqri"].erase(std::remove(nameOpcodeList["eqri"].begin(), nameOpcodeList["eqri"].end(), opcode), nameOpcodeList["eqri"].end()); } if(eqrr(A, B, C, registorsOld) != registorsNew){ opcodeNameList[opcode].erase(std::remove(opcodeNameList[opcode].begin(), opcodeNameList[opcode].end(), "eqrr"), opcodeNameList[opcode].end()); nameOpcodeList["eqrr"].erase(std::remove(nameOpcodeList["eqrr"].begin(), nameOpcodeList["eqrr"].end(), opcode), nameOpcodeList["eqrr"].end()); } } while(opcodesLeft > -10){ for(int i=0;i<16;i++){ if(opcodeNameList[i].size() == 1){ opcodeId[opcodeNameList[i][0]] = i; std::string opToRem = opcodeNameList[i][0]; for(int j=0; j<16; j++){ opcodeNameList[j].erase(std::remove(opcodeNameList[j].begin(), opcodeNameList[j].end(), opToRem), opcodeNameList[j].end()); } for(auto f: nameOpcodeList){ f.second.erase(std::remove(f.second.begin(), f.second.end(), i), f.second.end()); } opcodesLeft--; } } for(auto f: nameOpcodeList){ if(f.second.size() == 1){ opcodeId[f.first] = f.second[0]; int insToRem = f.second[0]; for(int i=0; i<16; i++){ //daca gaseste opcodeNameList[i].erase(std::remove(opcodeNameList[i].begin(), opcodeNameList[i].end(), f.first), opcodeNameList[i].end()); } for(auto g: nameOpcodeList){ //daca gaseste g.second.erase(std::remove(g.second.begin(), g.second.end(), insToRem), g.second.end()); } opcodesLeft--; } } } std::unordered_map<int, std::string> opcodeToNameOfFunction; for(int i=0; i<16; i++){ opcodeToNameOfFunction[i] = " "; } for(auto o: opcodeId){ opcodeToNameOfFunction[o.second] = o.first; } std::ifstream fileTwo; fileTwo.open("part2in.txt"); std::string inputPart2; std::vector<int> part2regs; part2regs.push_back(0); part2regs.push_back(0); part2regs.push_back(0); part2regs.push_back(0); while(fileTwo >> inputPart2){ int opcode = std::stoi(inputPart2); fileTwo >> inputPart2; int A = std::stoi(inputPart2); fileTwo >> inputPart2; int B = std::stoi(inputPart2); fileTwo >> inputPart2; int C = std::stoi(inputPart2); execute(opcode, A, B, C, opcodeToNameOfFunction, part2regs); } std::cout << part2regs[0] << std::endl; }
37.064039
145
0.692517
tymscar
3c9eb01cb5271cff67030b0ae748d7f85311c5de
2,458
cpp
C++
SurfDetect/integral.cpp
Ewenwan/RVAF
4f6dd3e3fa0ca55b43582995b8eff83c864163eb
[ "BSD-2-Clause" ]
22
2017-08-23T04:46:08.000Z
2021-11-08T08:51:59.000Z
SurfDetect/integral.cpp
Ewenwan/RVAF
4f6dd3e3fa0ca55b43582995b8eff83c864163eb
[ "BSD-2-Clause" ]
1
2017-08-23T12:31:24.000Z
2017-08-23T13:42:09.000Z
SurfDetect/integral.cpp
YangQun1/RVAF
9ee38d8158930c4a4671165f8065952c1d45fef9
[ "BSD-2-Clause" ]
12
2017-10-10T01:52:12.000Z
2020-01-05T14:02:55.000Z
/* SurfDetect // Copyright 2016 Peng Chao, (mail to:me@p-chao.com | http://p-chao.com). Build // this work with opencv > 2.3.1. The program use surf to detect feature points // and generate feature descriptor. You can also directly sample image from video // or camera, a webcamera is necessary if you run the program on camera mode. // The program can mosaic two image and draw the match point, you can see usage // and input the parameters by command line. The surf detect part referenced on // OpenSurt(https://github.com/amarburg/opencv-ffi-ext/tree/master/ext/opensurf) // project, and the core of code write by C. The test shows the program is more // efficiency than OpenSurf. Enjoy it! // Created at: 26 Aug. 2016, all rights reserved.*/ #include "common.h" namespace pc{ void computeintegral_channel(const fimg& img, fimg& ii_img){ ii_img.chns = img.chns; ii_img.cols = img.cols; ii_img.rows = img.rows; ii_img.data[0] = img.data[0]; float rs = 0.0f; for (int j = 0; j < img.cols; j++){ rs += img.data[j]; ii_img.data[j] = rs; } for (int i = 1; i < img.rows; i++){ rs = 0.0f; for (int j = 0; j < img.cols; j++){ rs += img.data[i * img.cols + j]; ii_img.data[i * ii_img.cols + j] = rs + ii_img.data[(i - 1) * img.cols + j]; } } } void compute_integral(const uimg& img, fimg& ii_img){ if (img.chns == 1){ fimg imgf; imgf.chns = img.chns; imgf.cols = img.cols; imgf.rows = img.rows; const int length = img.chns * img.cols * img.rows; imgf.data = (float*)malloc(img.chns * img.cols * img.rows * sizeof(float)); for (int i = 0; i < length; ++i){ imgf.data[i] = img.data[i] / 255.0f; } computeintegral_channel(imgf, ii_img); free(imgf.data); } else{ assert(false); } } float sumRect(const fimg& ii_img, const int row, const int col, const int rows, const int cols){ const int r1 = std::min(row, ii_img.rows) - 1; const int c1 = std::min(col, ii_img.cols) - 1; const int r2 = std::min(row + rows, ii_img.rows) - 1; const int c2 = std::min(col + cols, ii_img.cols) - 1; float value[4] = { 0 }; if (r1 >= 0 && c1 >= 0) value[0] = imgElem(ii_img, r1, c1); if (r1 >= 0 && c2 >= 0) value[1] = imgElem(ii_img, r1, c2); if (r2 >= 0 && c1 >= 0) value[2] = imgElem(ii_img, r2, c1); if (r2 >= 0 && c2 >= 0) value[3] = imgElem(ii_img, r2, c2); return std::max(0.0f, value[0] - value[1] - value[2] + value[3]); } }
32.342105
82
0.617575
Ewenwan
3ca0cdf3f18e858a2cac674378757aadfb4bf457
6,183
cpp
C++
lib/sqLITER/test/sqlitertestdataaccess.cpp
tklam/licensing-server
a583ea02fcd290dd3b0665df4b163c94302f3f0b
[ "MIT" ]
null
null
null
lib/sqLITER/test/sqlitertestdataaccess.cpp
tklam/licensing-server
a583ea02fcd290dd3b0665df4b163c94302f3f0b
[ "MIT" ]
null
null
null
lib/sqLITER/test/sqlitertestdataaccess.cpp
tklam/licensing-server
a583ea02fcd290dd3b0665df4b163c94302f3f0b
[ "MIT" ]
null
null
null
#include "sqlitertestdataaccess.h" #define TEST_FILENAME "test.db" csqlitertestdataaccess::csqlitertestdataaccess(void) { } csqlitertestdataaccess::~csqlitertestdataaccess(void) { } void csqlitertestdataaccess::setbasebath(std::string &basepath) { testpath = basepath; fullpath = testpath; fullpath.append(TEST_FILENAME); } int csqlitertestdataaccess::testtypesreturned() { //basic checks of return value types //create a table with a column of each data type. Insert row and make sure we can get it back. csqliter db; unsignedcharvector blob; //setup db.removedatabase(fullpath); //actual test if (db.createdb(fullpath) != successdb) { return(1); } db.setsql("CREATE TABLE testtypes (" "test_id INTEGER PRIMARY KEY AUTOINCREMENT, " "testint INTEGER, " "testfloat FLOAT, " "teststr TEXT, " "testblob BLOB);"); if (db.runsinglestepstatement() != successdb) { return(2); } db.setsql("INSERT INTO testtypes (" "testint, testfloat, teststr, testblob) " "VALUES (:int, :float, :str, :blob);"); blob.push_back(1); blob.push_back(2); blob.push_back(4); blob.push_back(5); db.bindint("int",5); db.bindfloat("float",3.14); db.bindstr("str", "Hello World!"); db.bindblob("blob", blob); if (db.runsinglestepstatement() != successdb) { return(3); } //now see if we get back what we put in... db.setsql("SELECT o.testint, o.testfloat, o.teststr, o.testblob FROM testtypes o;"); db.pushvaltypesout(intdbval, floatdbval, strdbval, blobdbval); if (db.runsinglestepstatement() != successdb) { return(4); } //and here's the meat of the test: see what we got back. if (db.rowdata[0].valtype != intdbval) { return(5); } if (db.rowdata[0].ival != 5) { return(6); } if (db.rowdata[1].valtype != floatdbval) { return(7); } if (db.rowdata[1].fval != 3.14) { return(8); } if (db.rowdata[2].valtype != strdbval) { return(9); } if (db.rowdata[2].sval != "Hello World!") { return(10); } blob.resize(0); if (db.rowdata[3].valtype != blobdbval) { return(11); } blob = db.rowdata[3].blob; if (blob.size() != 4) { return(12); } if (blob[0] != 1) { return(12); } if (blob[1] != 2) { return(12); } if (blob[2] != 4) { return(12); } if (blob[3] != 5) { return(12); } db.closedb(); return(0); } int csqlitertestdataaccess::testvaluesasnull() { csqliter db; //prove that nulls can be set and retrieved from any nominal data type (int, float, string, blob) //cleanup db.removedatabase(fullpath); if (db.createdb(fullpath) != successdb) { return(1); } db.setsql("CREATE TABLE testdat (" "testdat_id INTEGER PRIMARY KEY AUTOINCREMENT, " "testint INTEGER, " "testfloat FLOAT, " "teststr TEXT, " "testblob BLOB);"); if (db.runsinglestepstatement() != successdb) { return(2); } db.setsql("INSERT INTO testdat (testint, testfloat, teststr, testblob) VALUES (" ":int, :float, :str, :blob);"); db.bindnull("int"); db.bindnull("float"); db.bindnull("str"); db.bindnull("blob"); if (db.runsinglestepstatement() != successdb) { return(3); } db.setsql("SELECT o.testint, o.testfloat, o.teststr, o.testblob FROM testdat o;"); db.pushvaltypesout(intdbval, floatdbval, strdbval, blobdbval); if (db.runsinglestepstatement() != successdb) { return(4); } if (db.rowdata.size() != 4) { return(5); } if (db.rowdata[0].valtype != nulldbval) { return(5); } if (db.rowdata[1].valtype != nulldbval) { return(5); } if (db.rowdata[2].valtype != nulldbval) { return(5); } if (db.rowdata[3].valtype != nulldbval) { return(5); } db.closedb(); return(0); } int csqlitertestdataaccess::testresponsenumargserror() { csqliter db; //clean up db.removedatabase(fullpath); //now run the test if (db.createdb(fullpath) != successdb) { return(1); } db.setsql("CREATE TABLE testdat (" "testdat_id INTEGER PRIMARY KEY AUTOINCREMENT, " "testint INTEGER, " "teststr TEXT);"); if (db.runsinglestepstatement() != successdb) { return(2); } db.setsql("INSERT INTO testdat (testint, teststr) VALUES (" ":int, :str);"); db.bindint("int",3); db.bindstr("str","abcdefg"); if (db.runsinglestepstatement() != successdb) { return(3); } //this will return two values per row but we are telling it to expect only one db.setsql("SELECT o.testint, o.teststr FROM testdat o;"); db.pushvaltypesout(intdbval); if (db.runsinglestepstatement() != resultcountmismatchdberror) { return(4); } //now ask it to expect too many db.setsql("SELECT o.testint, o.teststr FROM testdat o;"); db.pushvaltypesout(intdbval, strdbval, intdbval); if (db.runsinglestepstatement() != resultcountmismatchdberror) { return(4); } //now make sure that just right actually works //now ask it to expect too many db.setsql("SELECT o.testint, o.teststr FROM testdat o;"); db.pushvaltypesout(intdbval, strdbval); if (db.runsinglestepstatement() != successdb) { return(5); } if (db.rowdata.size() != 2) { return(5); } if (db.rowdata[0].valtype != intdbval) { return(5); } if (db.rowdata[0].ival != 3) { return(5); } if (db.rowdata[1].valtype != strdbval) { return(5); } if (db.rowdata[1].sval != "abcdefg") { return(5); } db.closedb(); return(0); } int csqlitertestdataaccess::testresponseargtypeserror() { csqliter db; //clean up db.removedatabase(fullpath); //now run the test if (db.createdb(fullpath) != successdb) { return(1); } db.setsql("CREATE TABLE testdat (" "testdat_id INTEGER PRIMARY KEY AUTOINCREMENT, " "testint INTEGER, " "teststr TEXT);"); if (db.runsinglestepstatement() != successdb) { return(2); } db.setsql("INSERT INTO testdat (testint, teststr) VALUES (" ":int, :str);"); db.bindint("int",3); db.bindstr("str","abcdefg"); if (db.runsinglestepstatement() != successdb) { return(3); } db.setsql("SELECT o.testint, o.teststr FROM testdat o;"); db.pushvaltypesout(intdbval, intdbval); if (db.runsinglestepstatement() != resulttypemismatchdberror) { return(4); } db.setsql("SELECT o.testint, o.teststr FROM testdat o;"); db.pushvaltypesout(intdbval, strdbval); if (db.runsinglestepstatement() != successdb) { return(4); } db.closedb(); return(0); }
20.140065
97
0.664079
tklam
3ca577b50d33370110df1c57a236191a92213102
457
hpp
C++
include/commonpp/metric/reservoir/types.hpp
deco016/commonpp
ad03dcb6f7dc67359d898016c37a848c855c515b
[ "BSD-2-Clause" ]
32
2015-09-17T20:55:58.000Z
2022-01-24T12:00:39.000Z
include/commonpp/metric/reservoir/types.hpp
deco016/commonpp
ad03dcb6f7dc67359d898016c37a848c855c515b
[ "BSD-2-Clause" ]
7
2015-11-17T21:06:36.000Z
2018-01-30T09:45:15.000Z
include/commonpp/metric/reservoir/types.hpp
deco016/commonpp
ad03dcb6f7dc67359d898016c37a848c855c515b
[ "BSD-2-Clause" ]
11
2015-09-18T09:11:39.000Z
2019-10-06T14:53:22.000Z
/* * File: include/commonpp/metric/reservoir/types.hpp * Part of commonpp. * * Distributed under the 2-clause BSD licence (See LICENCE.TXT file at the * project root). * * Copyright (c) 2015 Thomas Sanchez. All rights reserved. * */ #pragma once namespace commonpp { namespace metric { namespace reservoir { struct WeightedReservoirTag { }; struct SimpleReservoirTag { }; } // namespace reservoir } // namespace metric } // namespace commonpp
14.741935
74
0.719912
deco016
3ca5ebca20592b48d04d484d09bf44e10da34824
8,325
cpp
C++
soccer/planning/tests/TrajectoryTest.cpp
kasohrab/robocup-software
73c92878baf960844b5a4b34c72804093f1ea459
[ "Apache-2.0" ]
null
null
null
soccer/planning/tests/TrajectoryTest.cpp
kasohrab/robocup-software
73c92878baf960844b5a4b34c72804093f1ea459
[ "Apache-2.0" ]
null
null
null
soccer/planning/tests/TrajectoryTest.cpp
kasohrab/robocup-software
73c92878baf960844b5a4b34c72804093f1ea459
[ "Apache-2.0" ]
null
null
null
#include <gtest/gtest.h> #include <rrt/planning/Path.hpp> #include "TestingUtils.hpp" #include "math.h" #include "planning/Instant.hpp" #include "planning/Trajectory.hpp" #include "planning/planner/PathTargetPlanner.hpp" #include "planning/primitives/PathSmoothing.hpp" #include "planning/primitives/RRTUtil.hpp" #include "planning/primitives/VelocityProfiling.hpp" using namespace Planning; using namespace Geometry2d; using namespace Planning::TestingUtils; TEST(Trajectory, Interpolation) { // Test the basics of the Trajectory class, including interpolation, instant // addition/insertion, and duration calculations. RJ::Time start = RJ::now(); RobotInstant start_instant = RobotInstant(Pose(0, 0, 0), Twist(1, 0, 0), start); RobotInstant mid_instant = RobotInstant(Pose(1, 1, 3), Twist(1, 0, 0), start + 1s); RobotInstant end_instant = RobotInstant(Pose(2, 0, 6), Twist(1, 0, 0), start + 1500ms); Trajectory trajectory; trajectory.AppendInstant(start_instant); trajectory.AppendInstant(mid_instant); ASSERT_EQ(*trajectory.evaluate(start), start_instant); ASSERT_EQ(*trajectory.evaluate(trajectory.end_time()), mid_instant); EXPECT_FALSE( trajectory.evaluate(trajectory.begin_time() - RJ::Seconds(1e-3s))); EXPECT_FALSE( trajectory.evaluate(trajectory.end_time() + RJ::Seconds(1e-3s))); EXPECT_FALSE(Trajectory{{}}.evaluate(RJ::Seconds(0s))); EXPECT_FALSE(Trajectory{{}}.evaluate(start)); Twist mid_twist; { RobotInstant instant = *trajectory.evaluate(start + 500ms); EXPECT_NEAR(instant.position().x(), 0.5, 1e-6); EXPECT_NEAR(instant.position().y(), 0.5, 1e-6); EXPECT_NEAR(instant.pose.heading(), 1.5, 1e-6); mid_twist = instant.velocity; } // Make sure we use the right segment. trajectory.AppendInstant(end_instant); { RobotInstant instant = *trajectory.evaluate(start + 1250ms); EXPECT_NEAR(instant.position().x(), 1.5, 1e-6); EXPECT_NEAR(instant.position().y(), 0.5, 1e-6); EXPECT_NEAR(instant.pose.heading(), 4.5, 1e-6); // Twist should be the same as halfway through the other segment, but // rescaled because this segment only lasts 500ms. EXPECT_NEAR(-mid_twist.linear().y() * 2, instant.velocity.linear().y(), 1e-6); EXPECT_NEAR(mid_twist.angular() * 2, instant.velocity.angular(), 1e-6); } EXPECT_EQ(*trajectory.evaluate(trajectory.end_time()), end_instant); EXPECT_TRUE(trajectory.CheckTime(start + 500ms)); EXPECT_FALSE(trajectory.CheckTime(start - 500ms)); EXPECT_FALSE(trajectory.CheckTime(start + 2500ms)); EXPECT_TRUE(trajectory.CheckSeconds(500ms)); EXPECT_FALSE(trajectory.CheckSeconds(-500ms)); EXPECT_FALSE(trajectory.CheckSeconds(2500ms)); EXPECT_EQ(trajectory.duration(), RJ::Seconds(end_instant.stamp - start_instant.stamp)); } TEST(Trajectory, TrajectoryCursor) { std::vector<RobotInstant> instants; RobotInstant a{Pose{{1, 1}, 1}, Twist{}, RJ::Time(1s)}; RobotInstant b{Pose{{2, 2}, 2}, Twist{}, RJ::Time(2s)}; RobotInstant c{Pose{{5, 5}, 5}, Twist{}, RJ::Time(5s)}; instants.push_back(a); instants.push_back(b); instants.push_back(c); Trajectory traj{std::move(instants)}; auto cursor = traj.cursor_begin(); ASSERT_TRUE(cursor.has_value()); EXPECT_TRUE(RobotInstant::nearly_equals(cursor.value(), a)); cursor.next_knot(); ASSERT_TRUE(cursor.has_value()); EXPECT_TRUE(RobotInstant::nearly_equals(cursor.value(), b)); cursor.advance(3s); ASSERT_TRUE(cursor.has_value()); EXPECT_TRUE(RobotInstant::nearly_equals(cursor.value(), c)); cursor.seek(c.stamp); ASSERT_TRUE(cursor.has_value()); EXPECT_TRUE(RobotInstant::nearly_equals(cursor.value(), c)); cursor.seek(b.stamp); ASSERT_TRUE(cursor.has_value()); EXPECT_TRUE(RobotInstant::nearly_equals(cursor.value(), b)); cursor.seek(a.stamp); ASSERT_TRUE(cursor.has_value()); EXPECT_TRUE(RobotInstant::nearly_equals(cursor.value(), a)); // Make sure we can advance multiple steps forwards. cursor.advance(4s); ASSERT_TRUE(cursor.has_value()); EXPECT_TRUE(RobotInstant::nearly_equals(cursor.value(), c)); cursor.seek(a.stamp); ASSERT_TRUE(cursor.has_value()); EXPECT_TRUE(RobotInstant::nearly_equals(cursor.value(), a)); cursor.advance(0.5s); cursor.advance(0.5s); ASSERT_TRUE(cursor.has_value()); EXPECT_TRUE(RobotInstant::nearly_equals(cursor.value(), b)); cursor.advance(0.5s); cursor.advance(1.5s); cursor.advance(1.0s); ASSERT_TRUE(cursor.has_value()); EXPECT_TRUE(RobotInstant::nearly_equals(cursor.value(), c)); cursor.advance(0.1s); EXPECT_FALSE(cursor.has_value()); } TEST(Trajectory, BezierPath) { std::vector<Point> points = {Point(0, 0), Point(1, 0.5), Point(1.5, 1), Point(2, 2)}; Point vi(1, 0); Point vf(0, 1); MotionConstraints constraints; constraints.maxSpeed = 3.0; constraints.maxAcceleration = 3.0; Planning::BezierPath path(points, vi, vf, constraints); for (int i = 0; i < 4; i++) { Point p; Point v; double k = 0; path.Evaluate(i / 3.0, &p, &v, &k); std::cout << p << ", " << v << std::endl; EXPECT_NEAR((p - points[i]).mag(), 0, 1e-6); if (i == 0) { EXPECT_NEAR(v.angleBetween(vi), 0, 1e-3); } if (i == 3) { EXPECT_NEAR(v.angleBetween(vf), 0, 1e-3); } } } TEST(Trajectory, SubTrajectory) { std::vector<RobotInstant> instants; RobotInstant a{Pose{{0, 0}, 0}, Twist{{1, 0}, 0}, RJ::Time(0s)}; RobotInstant b{Pose{{1, 1}, 0}, Twist{{2, 0}, 1}, RJ::Time(2s)}; RobotInstant c{Pose{{2, 0}, 0}, Twist{{1, 0}, 1}, RJ::Time(4s)}; instants.push_back(a); instants.push_back(b); instants.push_back(c); Trajectory traj{std::move(instants)}; { RJ::Time t0{1s}; RJ::Time t1{3s}; RobotInstant ab = traj.evaluate(t0).value(); RobotInstant bc = traj.evaluate(t1).value(); Trajectory sub = traj.subTrajectory(t0, t1); EXPECT_TRUE(Trajectory::nearly_equal(sub, Trajectory{{ab, b, bc}})); } { RJ::Time t0{3s}; RJ::Time t1{6s}; RobotInstant bc = traj.evaluate(t0).value(); Trajectory sub = traj.subTrajectory(t0, t1); EXPECT_TRUE(Trajectory::nearly_equal(sub, Trajectory{{bc, c}})); } { RJ::Time t0{4s}; RJ::Time t1{6s}; RobotInstant bc = traj.evaluate(t0).value(); Trajectory sub = traj.subTrajectory(t0, t1); EXPECT_TRUE(Trajectory::nearly_equal(sub, Trajectory{{c}})); } } TEST(Trajectory, SubTrajectoryEndpoints) { RobotInstant a{Pose{{0, 0}, 0}, Twist{{1, 0}, 0}, RJ::Time(0s)}; RobotInstant b{Pose{{1, 1}, 0}, Twist{{2, 0}, 1}, RJ::Time(2s)}; RobotInstant c{Pose{{2, 0}, 0}, Twist{{1, 0}, 1}, RJ::Time(4s)}; Trajectory traj{{a, b, c}}; Trajectory sub = traj.subTrajectory(RJ::Time(0s), RJ::Time(4s)); EXPECT_TRUE(Trajectory::nearly_equal(sub, Trajectory{{a, b, c}})); } TEST(Trajectory, Combining) { std::vector<RobotInstant> instants; RobotInstant a{Pose{{0, 0}, 0}, Twist{{1, 0}, 0}, RJ::Time(0s)}; RobotInstant b{Pose{{1, 1}, 0}, Twist{{2, 0}, 1}, RJ::Time(2s)}; RobotInstant c{Pose{{2, 0}, 0}, Twist{{1, 0}, 1}, RJ::Time(4s)}; Trajectory traj_1{{a, b}}; Trajectory traj_2{{b, c}}; Trajectory combined(std::move(traj_1), traj_2); EXPECT_TRUE(traj_1.empty()) << "Should have moved out of the first trajectory"; EXPECT_TRUE(Trajectory::nearly_equal(combined, Trajectory{{a, b, c}})); } TEST(Trajectory, CombiningFail) { std::vector<RobotInstant> instants; RobotInstant a{Pose{{0, 0}, 0}, Twist{{1, 0}, 0}, RJ::Time(0s)}; RobotInstant b1{Pose{{1, 1}, 0}, Twist{{2, 0}, 1}, RJ::Time(2s)}; RobotInstant b2{Pose{{1, 0.5}, 0}, Twist{{2, 0}, 1}, RJ::Time(2s)}; RobotInstant c{Pose{{2, 0}, 0}, Twist{{1, 0}, 1}, RJ::Time(4s)}; Trajectory traj_1{{a, b1}}; Trajectory traj_2{{b2, c}}; EXPECT_THROW((Trajectory{std::move(traj_1), traj_2}), std::invalid_argument); }
35.126582
80
0.634715
kasohrab
3ca8d24dcd9171cf7ae5ca2e50cfd0a576b26358
2,100
cpp
C++
functions/+Image/borderFill.cpp
kkapsner/Matlab
98d42184f78b13a4bcb586fab48ad444028163d9
[ "MIT" ]
1
2017-02-12T19:37:17.000Z
2017-02-12T19:37:17.000Z
functions/+Image/borderFill.cpp
kkapsner/Matlab
98d42184f78b13a4bcb586fab48ad444028163d9
[ "MIT" ]
3
2015-01-07T20:12:07.000Z
2018-08-22T18:26:38.000Z
functions/+Image/borderFill.cpp
kkapsner/Matlab
98d42184f78b13a4bcb586fab48ad444028163d9
[ "MIT" ]
null
null
null
#include "mex.h" #include "borderFill/List.cpp" #define idx(dx, dy) (x + dx) * h + y + dy #define check(dx, dy){\ idx = idx(dx, dy);\ if ((image[idx] == image[idx0]) && !outImage[idx]){\ outImage[idx] = 1;\ pixelList.push(x + dx, y + dy);\ }\ } /* * borderFill.cpp */ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { mxLogical *image, *outImage; mwSize w, h; borderFill::List pixelList; if (nrhs != 1){ mexErrMsgIdAndTxt( "MATLAB:borderFill:wrongInputCount", "One input (image) expected."); } /* The input must be a logical.*/ if(!mxIsLogical(prhs[0])){ mexErrMsgIdAndTxt( "MATLAB:borderFill:inputNotLogical", "Input must be a logical."); } h = mxGetM(prhs[0]); w = mxGetN(prhs[0]); image = mxGetLogicals(prhs[0]); /* Create matrix for the return argument. */ plhs[0] = mxCreateLogicalMatrix(h, w); outImage = mxGetLogicals(plhs[0]); /* first and last column */ for (int y = 0; y < h; y++){ outImage[y] = 1; pixelList.push(0, y); outImage[h * (w - 1) + y] = 1; pixelList.push(w - 1, y); } /* first and last row */ for (int x = 1; x < w - 1; x++){ outImage[x * h] = 1; pixelList.push(x, 0); outImage[x * h + h - 1] = 1; pixelList.push(x, h - 1); } while (pixelList.head){ int x = pixelList.head->x; int y = pixelList.head->y; int idx0 = idx(0, 0); int idx; pixelList.shift(); if (y > 0){ if (x > 0){ check(-1, -1); } check(0, -1); if (x < w - 1){ check(1, -1); } } if (x > 0){ check(-1, 0); } if (x < w - 1){ check(1, 0); } if (y < h - 1){ if (x > 0){ check(-1, 1); } check(0, 1); if (x < w - 1){ check(1, 1); } } } }
22.580645
57
0.439048
kkapsner
3cb2fc5dc695c437874bf7f2b28c374e3ca55c1e
4,449
cpp
C++
src/executable/plot_shasta_alignments.cpp
rlorigro/overlap_analysis
8c8753aeba40c4ba82e0c0499fc8c2f134ba7145
[ "Apache-2.0" ]
null
null
null
src/executable/plot_shasta_alignments.cpp
rlorigro/overlap_analysis
8c8753aeba40c4ba82e0c0499fc8c2f134ba7145
[ "Apache-2.0" ]
null
null
null
src/executable/plot_shasta_alignments.cpp
rlorigro/overlap_analysis
8c8753aeba40c4ba82e0c0499fc8c2f134ba7145
[ "Apache-2.0" ]
null
null
null
#include "SvgPlot.hpp" #include "boost/program_options.hpp" using boost::program_options::options_description; using boost::program_options::variables_map; using boost::program_options::bool_switch; using boost::program_options::value; #include <istream> #include <iostream> #include <functional> using std::experimental::filesystem::directory_iterator; using std::experimental::filesystem::create_directories; using std::experimental::filesystem::absolute; using std::experimental::filesystem::rename; using std::experimental::filesystem::exists; using std::experimental::filesystem::path; using std::ifstream; using std::function; class AlignmentCoordinate { public: size_t coord_a; size_t coord_b; AlignmentCoordinate()=default; }; void for_each_alignment_coordinate(path file_path, const function<void(const AlignmentCoordinate&)>& f){ ifstream file(file_path); if (not (file.good() and file.is_open())){ throw runtime_error("ERROR: file could not be read: " + file_path.string()); } string token; AlignmentCoordinate alignment_coordinate; uint64_t n_delimiters = 0; uint64_t n_lines = 0; char c; // Skip first line file.ignore(9999, '\n'); while (file.get(c)){ if (c == ',') { if (n_delimiters == 3){ alignment_coordinate.coord_a = stoi(token); } else if (n_delimiters == 4){ alignment_coordinate.coord_b = stoi(token); } token.resize(0); n_delimiters++; } else if (c == '\n'){ if (n_delimiters < 4 and n_lines > 0){ throw runtime_error( "ERROR: file provided does not contain sufficient tab delimiters to be shasta alignment: " + to_string(n_lines)); } f(alignment_coordinate); token.resize(0); n_delimiters = 0; n_lines++; } else { token += c; } } } void plot_shasta_alignment(path input_dir, path output_dir){ if (exists(output_dir)){ throw runtime_error("ERROR: output directory already exists"); } else{ create_directories(output_dir); } string type = "rect"; string color = "red"; for(auto& file_iter: directory_iterator(input_dir)){ const path& file_path = file_iter.path(); path output_path = output_dir / file_path.filename(); output_path.replace_extension(".svg"); cerr << file_path << '\n'; vector<AlignmentCoordinate> coordinates; for_each_alignment_coordinate(file_path, [&](const AlignmentCoordinate& a){ coordinates.emplace_back(a); }); size_t a_length = coordinates.back().coord_a; size_t b_length = coordinates.back().coord_b; size_t a_start = coordinates[0].coord_a; size_t b_start = coordinates[0].coord_b; cerr << a_length << ' ' << a_start << ' ' << b_length << ' ' << b_start << '\n'; SvgPlot plot(output_path, 1200, 1200, 0, a_length-a_start, 0, b_length-b_start); size_t i = 0; for (auto& item: coordinates){ plot.add_point(item.coord_a - a_start, item.coord_b - b_start, type, 20, color); if (i < 100){ cerr << item.coord_a - a_start << ' ' << item.coord_b - b_start << ' ' << item.coord_a << ' ' << item.coord_b << '\n'; } i++; } } } int main(int argc, char* argv[]){ path alignment_directory; path output_directory; options_description options("Arguments:"); options.add_options() ("input_dir", value<path>(&alignment_directory) ->required(), "Alignments TO BE EVALUATED: path of directory containing Shasta alignment details (one file per alignment)\n") ("output_dir", value<path>(&output_directory) ->required(), "Where to dump output SVG, CSV, PAF, etc") ; variables_map vm; store(parse_command_line(argc, argv, options), vm); // If help was specified, or no arguments given, provide help if (vm.count("help") || argc == 1) { cerr << options << "\n"; return 0; } notify(vm); plot_shasta_alignment( alignment_directory, output_directory); return 0; }
26.963636
134
0.595639
rlorigro
3cb3653e5985a4b3249f736b0957d7bcae5229fa
7,599
cpp
C++
benchmarks/DNN/layers/convolution/direct/unrolled_conv2/conv_layer_generator_tiramisu.cpp
akmaru/tiramisu
8ca4173547b6d12cff10575ef0dc48cf93f7f414
[ "MIT" ]
23
2017-05-03T13:06:34.000Z
2018-06-07T07:12:43.000Z
benchmarks/DNN/layers/convolution/direct/unrolled_conv2/conv_layer_generator_tiramisu.cpp
akmaru/tiramisu
8ca4173547b6d12cff10575ef0dc48cf93f7f414
[ "MIT" ]
2
2017-04-25T08:59:09.000Z
2017-05-11T16:41:55.000Z
benchmarks/DNN/layers/convolution/direct/unrolled_conv2/conv_layer_generator_tiramisu.cpp
akmaru/tiramisu
8ca4173547b6d12cff10575ef0dc48cf93f7f414
[ "MIT" ]
5
2017-02-16T14:26:40.000Z
2018-05-30T16:49:27.000Z
#include <tiramisu/tiramisu.h> #include "configure.h" using namespace tiramisu; int main(int argc, char **argv) { init("conv_tiramisu"); // ------------------------------------------------------- // Layer I // ------------------------------------------------------- var x("x", 0, N), y("y", 0, N), n("n", 0, BATCH_SIZE); var k_x("k_x", 0, K), k_y("k_y", 0, K); var fin_b("fin_b", 0, FIN_NB_BLOCKS), ffin("ffin", 0, FIN_BLOCKING); var fout_b("fout_b", 0, FOUT_NB_BLOCKS), ffout("ffout", 0, FOUT_BLOCKING); var x_pad("x_pad", 0, N + 2), y_pad("y_pad", 0, N + 2); input c_input("c_input", {n, fin_b, y_pad, x_pad, ffin}, p_float32); input filter("filter", {fout_b, fin_b, k_y, k_x, ffin, ffout}, p_float32); input bias("bias", {fout_b, ffout}, p_float32); computation conv_init("conv_init", {n, y, fout_b, x, ffout}, bias(fout_b, ffout)); view conv_out("conv_out", {n, y, fout_b, x, ffout}, p_float32); // x_bound is used to have the width dimension divisible by X_BLOCKING // in the conv computation. var x_bound("x_bound", 0, X_BOUND); var x_conclude("x_conclude", X_BOUND, N); // Compute convolution from 0 to x_bound computation conv( "conv", {n, y, fout_b, fin_b, x_bound, k_y, k_x, ffin, ffout}, conv_out(n, y, fout_b, x_bound, ffout) + filter(fout_b, fin_b, k_y, k_x, ffin, ffout) * c_input(n, fin_b, y + k_y, x_bound + k_x, ffin) ); // Compute convolution from x_bound to N computation conv_conclude( "conv_conclude", {n, y, fout_b, fin_b, k_y, k_x, ffin, ffout, x_conclude}, conv_out(n, y, fout_b, x_conclude, ffout) + filter(fout_b, fin_b, k_y, k_x, ffin, ffout) * c_input(n, fin_b, y + k_y, x_conclude + k_x, ffin) ); // ------------------------------------------------------- // Layer II // ------------------------------------------------------- // schedule for conv computation // We introduce those two computations to do register blocking computation reg_load( "reg_load", {n, y, fout_b, fin_b, x_bound, ffout}, conv_init(n, y, fout_b, x_bound, ffout) ); computation reg_store( "reg_store", {n, y, fout_b, fin_b, x_bound, ffout}, conv(n, y, fout_b, fin_b, x_bound, 0, 0, 0, ffout) ); // Split over dimension x var x_b, xx; conv.split(x_bound, X_BLOCKING, x_b, xx); conv.interchange(xx, k_y); conv.interchange(xx, k_x); conv.interchange(xx, ffin); conv.interchange(xx, ffout); reg_load.split(x_bound, X_BLOCKING, x_b, xx); reg_store.split(x_bound, X_BLOCKING, x_b, xx); reg_load.interchange(xx, ffout); reg_store.interchange(xx, ffout); // Split over dimension fout_b var fout_b_up, fout_b_low; if (FOUT_B_SPLIT_FACTOR*FOUT_BLOCKING != FOut) { conv_init.split(fout_b, FOUT_B_SPLIT_FACTOR, fout_b_up, fout_b_low); conv.split(fout_b, FOUT_B_SPLIT_FACTOR, fout_b_up, fout_b_low); reg_load.split(fout_b, FOUT_B_SPLIT_FACTOR, fout_b_up, fout_b_low); reg_store.split(fout_b, FOUT_B_SPLIT_FACTOR, fout_b_up, fout_b_low); } else { fout_b_up = y; fout_b_low = fout_b; } conv.interchange(fout_b_low, fin_b); conv.interchange(fout_b_low, x_b); conv.interchange(fout_b_low, k_y); conv.interchange(fout_b_low, k_x); conv.interchange(fout_b_low, ffin); reg_load.interchange(fout_b_low, fin_b); reg_load.interchange(fout_b_low, x_b); reg_store.interchange(fout_b_low, fin_b); reg_store.interchange(fout_b_low, x_b); // Vectorize and unroll reg_load.vectorize(ffout, FOUT_BLOCKING); conv.vectorize(ffout, FOUT_BLOCKING); reg_store.vectorize(ffout, FOUT_BLOCKING); conv.tag_unroll_level(xx); conv.tag_unroll_level(fout_b_low); reg_load.tag_unroll_level(xx); reg_load.tag_unroll_level(fout_b_low); reg_store.tag_unroll_level(xx); reg_store.tag_unroll_level(fout_b_low); // schedule for conv_conclude // This schedule is the same as conv computation computation reg_load_conclude( "reg_load_conclude", {n, y, fout_b, fin_b, ffout, x_conclude}, conv_init(n, y, fout_b, x_conclude, ffout) ); computation reg_store_conclude( "reg_store_conclude", {n, y, fout_b, fin_b, ffout, x_conclude}, conv_conclude(n, y, fout_b, fin_b, 0, 0, 0, ffout, x_conclude) ); // Split over dimension fout_b if (FOUT_B_SPLIT_FACTOR*FOUT_BLOCKING != FOut) { conv_conclude.split(fout_b, FOUT_B_SPLIT_FACTOR, fout_b_up, fout_b_low); reg_load_conclude.split(fout_b, FOUT_B_SPLIT_FACTOR, fout_b_up, fout_b_low); reg_store_conclude.split(fout_b, FOUT_B_SPLIT_FACTOR, fout_b_up, fout_b_low); } else { fout_b_up = y; fout_b_low = fout_b; } conv_conclude.interchange(fout_b_low, fin_b); conv_conclude.interchange(fout_b_low, k_y); conv_conclude.interchange(fout_b_low, k_x); conv_conclude.interchange(fout_b_low, ffin); reg_load_conclude.interchange(fout_b_low, fin_b); reg_store_conclude.interchange(fout_b_low, fin_b); // Vectorize and unroll reg_load_conclude.vectorize(ffout, FOUT_BLOCKING); conv_conclude.vectorize(ffout, FOUT_BLOCKING); reg_store_conclude.vectorize(ffout, FOUT_BLOCKING); conv_conclude.tag_unroll_level(x_conclude); conv_conclude.tag_unroll_level(fout_b_low); reg_load_conclude.tag_unroll_level(x_conclude); reg_load_conclude.tag_unroll_level(fout_b_low); reg_store_conclude.tag_unroll_level(x_conclude); reg_store_conclude.tag_unroll_level(fout_b_low); // Parallelize and order conv.tag_parallel_level(y); conv.tag_parallel_level(n); conv_init.then(reg_load, fout_b_up) .then(conv, x_b) .then(reg_store, x_b) .then(reg_load_conclude, fout_b_up) .then(conv_conclude, fin_b) .then(reg_store_conclude, fin_b); // ------------------------------------------------------- // Layer III // ------------------------------------------------------- buffer conv_buf("conv_buf", {BATCH_SIZE, FOUT_NB_BLOCKS, N, N, FOUT_BLOCKING}, p_float32, a_output); // This is where intermediate results of convolution will be stored. // We rely on the compiler to detect that this buffer can be mapped to CPU registers. buffer reg_buf("reg_buf", {FOUT_B_SPLIT_FACTOR, X_BLOCKING, FOUT_BLOCKING}, p_float32, a_temporary); conv_init.store_in(&conv_buf, {n, fout_b, y, x, ffout}); conv_out.store_in(&reg_buf, {fout_b%FOUT_B_SPLIT_FACTOR, x%X_BLOCKING, ffout}); reg_load.store_in(&reg_buf, {fout_b%FOUT_B_SPLIT_FACTOR, x_bound%X_BLOCKING, ffout}); conv.store_in(&reg_buf, {fout_b%FOUT_B_SPLIT_FACTOR, x_bound%X_BLOCKING, ffout}); reg_store.store_in(&conv_buf, {n, fout_b, y, x_bound, ffout}); reg_load_conclude.store_in(&reg_buf, {fout_b%FOUT_B_SPLIT_FACTOR, x_conclude%X_BLOCKING, ffout}); conv_conclude.store_in(&reg_buf, {fout_b%FOUT_B_SPLIT_FACTOR, x_conclude%X_BLOCKING, ffout}); reg_store_conclude.store_in(&conv_buf, {n, fout_b, y, x_conclude, ffout}); // ------------------------------------------------------- // Code Generation // ------------------------------------------------------- tiramisu::codegen({ c_input.get_buffer(), filter.get_buffer(), bias.get_buffer(), &conv_buf },"generated_conv_layer.o"); return 0; }
35.509346
149
0.627714
akmaru
3cb4849b893113fc861a211801931323b02e049a
414
cpp
C++
RemoveTypeVaArgsT.cpp
DaemonSnake/MetaProgramming
6eed2293b926e4cc856263adf2ce1e00d04f362d
[ "MIT" ]
null
null
null
RemoveTypeVaArgsT.cpp
DaemonSnake/MetaProgramming
6eed2293b926e4cc856263adf2ce1e00d04f362d
[ "MIT" ]
null
null
null
RemoveTypeVaArgsT.cpp
DaemonSnake/MetaProgramming
6eed2293b926e4cc856263adf2ce1e00d04f362d
[ "MIT" ]
null
null
null
// // test.cpp for in /home/penava_b // // Made by penava_b // Login <penava_b@epitech.net> // // Started on Wed Apr 20 23:55:00 2016 penava_b // Last update Mon Jul 11 14:23:32 2016 penava_b // #include "Mpl.hpp" using namespace MPL; template <class ...Args> class TMP {}; Unit(RemoveType) { using OLD = TMP<float, int, double, int, void>; print<OLD>(); print<RemoveInTemplateType<int, OLD>>(); }
18
49
0.657005
DaemonSnake
3cb4be1441fa63988b82083d7a154bc9e92f13f2
570
cpp
C++
Course Experiment/C Language Course Course Exp/Experiment/No.1 Experiment/1.2.1源程序改错.cpp
XJDKC/University-Code-Archive
2dd9c6edb2164540dc50db1bb94940fe53c6eba0
[ "MIT" ]
4
2019-04-01T17:33:38.000Z
2022-01-08T04:07:52.000Z
Course Experiment/C Language Course Course Exp/Experiment/No.1 Experiment/1.2.1源程序改错.cpp
XJDKC/University-Code-Archive
2dd9c6edb2164540dc50db1bb94940fe53c6eba0
[ "MIT" ]
null
null
null
Course Experiment/C Language Course Course Exp/Experiment/No.1 Experiment/1.2.1源程序改错.cpp
XJDKC/University-Code-Archive
2dd9c6edb2164540dc50db1bb94940fe53c6eba0
[ "MIT" ]
1
2021-01-06T11:04:31.000Z
2021-01-06T11:04:31.000Z
#include<stdio.h> #define PI 3.14159 int main(void) { int f; short p,k,newint; double c ,r,s; /* for task 1 */ printf("Input Fahrenheit:"); scanf("%d",&f); c = 5.0/9*(f-32); printf(" \n %d (F) = %.2f (C)\n\n ", f,c); /* for task 2 */ printf("input the radius r:"); scanf("%lf", &r); s = PI * r * r; printf("\nThe acreage is %.2lf\n\n",s); /* for task 3 */ printf("input hex int k, p :"); scanf("%hd %hd",&k,&p); newint=(p&0xff00)|((k>>8)&0xff); printf("\nnew int = %hd\n",newint); return 0; }
22.8
46
0.484211
XJDKC
3cb6b170b6cb89fd04156d5a35c905f27952ebb8
2,593
cpp
C++
homescreen/src/statusbarserver.cpp
hungsonspkt/homescreen
57d13f02f6904a95fd14a3bcaf9ea80b4176f76d
[ "Apache-2.0" ]
null
null
null
homescreen/src/statusbarserver.cpp
hungsonspkt/homescreen
57d13f02f6904a95fd14a3bcaf9ea80b4176f76d
[ "Apache-2.0" ]
null
null
null
homescreen/src/statusbarserver.cpp
hungsonspkt/homescreen
57d13f02f6904a95fd14a3bcaf9ea80b4176f76d
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2016 The Qt Company Ltd. * Copyright (C) 2016, 2017 Mentor Graphics Development (Deutschland) GmbH * * 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 "statusbarserver.h" class StatusBarServer::Private { public: Private(StatusBarServer *parent); QString texts[SupportedCount]; QString icons[SupportedCount]; }; StatusBarServer::Private::Private(StatusBarServer *parent) { icons[0] = QStringLiteral("qrc:/images/Status/HMI_Status_Wifi_NoBars-01.png"); icons[1] = QStringLiteral("qrc:/images/Status/HMI_Status_Bluetooth_Inactive-01.png"); icons[2] = QStringLiteral("qrc:/images/Status/HMI_Status_Signal_NoBars-01.png"); } StatusBarServer::StatusBarServer(QObject *parent) : QObject(parent) , d(new Private(this)) { } StatusBarServer::~StatusBarServer() { delete d; } QList<int> StatusBarServer::getAvailablePlaceholders() const { QList<int> ret; for (int i = 0; i < SupportedCount; ++i) { ret.append(i); } return ret; } QString StatusBarServer::getStatusIcon(int placeholderIndex) const { QString ret; if (-1 < placeholderIndex && placeholderIndex < SupportedCount) ret = d->icons[placeholderIndex]; return ret; } void StatusBarServer::setStatusIcon(int placeholderIndex, const QString &icon) { if (-1 < placeholderIndex && placeholderIndex < SupportedCount) { if (d->icons[placeholderIndex] == icon) return; d->icons[placeholderIndex] = icon; emit statusIconChanged(placeholderIndex, icon); } } QString StatusBarServer::getStatusText(int placeholderIndex) const { QString ret; if (-1 < placeholderIndex && placeholderIndex < SupportedCount) { ret = d->texts[placeholderIndex]; } return ret; } void StatusBarServer::setStatusText(int placeholderIndex, const QString &text) { if (-1 < placeholderIndex && placeholderIndex < SupportedCount) { if (d->texts[placeholderIndex] == text) return; d->texts[placeholderIndex] = text; emit statusTextChanged(placeholderIndex, text); } }
29.134831
89
0.70806
hungsonspkt
3cb71a962e4f3a3b6457b7da63990ad75ca6ab3d
5,490
cpp
C++
lib_ecm/components/cmp_text.cpp
OlavJDigranes/groupD
1d1fdd4ec0117162d777d0c020cbf4ae1718cf5f
[ "MIT" ]
null
null
null
lib_ecm/components/cmp_text.cpp
OlavJDigranes/groupD
1d1fdd4ec0117162d777d0c020cbf4ae1718cf5f
[ "MIT" ]
null
null
null
lib_ecm/components/cmp_text.cpp
OlavJDigranes/groupD
1d1fdd4ec0117162d777d0c020cbf4ae1718cf5f
[ "MIT" ]
null
null
null
#include "cmp_text.h" #include <system_renderer.h> #include <system_resources.h> using namespace sf; //General text component void TextComponent::update(double dt) { _text.setPosition(_parent->getPosition()); } void TextComponent::render() { Renderer::queue(&_text); } TextComponent::TextComponent(Entity* const p, const std::string& str) : Component(p), _string(str) { _text.setString(_string); _font = Resources::get<sf::Font>("ShadowsIntoLight-Regular.ttf"); _text.setFont(*_font); } void TextComponent::SetText(const std::string& str) { _string = str; _text.setString(_string); } //ESC text component void ESCTextComponent::update(double dt) { _ESCtext.setPosition(_parent->getPosition()); } void ESCTextComponent::render() { Renderer::queue(&_ESCtext); } ESCTextComponent::ESCTextComponent(Entity* const p, const std::string& str) : Component(p), _ESCstring(str) { _ESCtext.setString(_ESCstring); _ESCfont = Resources::get<sf::Font>("ShadowsIntoLight-Regular.ttf"); _ESCtext.setFont(*_ESCfont); _ESCtext.setCharacterSize(20); } void ESCTextComponent::SetText(const std::string& str) { _ESCstring = str; _ESCtext.setString(_ESCstring); } //Red Text Component void RedTextComponent::update(double dt) { _text.setPosition(_parent->getPosition()); } void RedTextComponent::render() { Renderer::queue(&_text); } RedTextComponent::RedTextComponent(Entity* const p, const std::string& str) : Component(p), _string(str) { _text.setString(_string); _text.setFillColor(Color::Red); _text.setOutlineColor(Color::White); _font = Resources::get<sf::Font>("ShadowsIntoLight-Regular.ttf"); _text.setFont(*_font); _text.setCharacterSize(40); _text.setStyle(Text::Bold); } void RedTextComponent::SetText(const std::string& str) { _string = str; _text.setString(_string); } //Green Text Component void GreenTextComponent::update(double dt) { _text.setPosition(_parent->getPosition()); } void GreenTextComponent::render() { Renderer::queue(&_text); } GreenTextComponent::GreenTextComponent(Entity* const p, const std::string& str) : Component(p), _string(str) { _text.setString(_string); _text.setFillColor(Color::Green); _text.setOutlineColor(Color::White); _font = Resources::get<sf::Font>("ShadowsIntoLight-Regular.ttf"); _text.setFont(*_font); _text.setCharacterSize(40); _text.setStyle(Text::Bold); } void GreenTextComponent::SetText(const std::string& str) { _string = str; _text.setString(_string); } //Blue Text Component void BlueTextComponent::update(double dt) { _text.setPosition(_parent->getPosition()); } void BlueTextComponent::render() { Renderer::queue(&_text); } BlueTextComponent::BlueTextComponent(Entity* const p, const std::string& str) : Component(p), _string(str) { _text.setString(_string); _text.setFillColor(Color{2,133,169,255}); _text.setOutlineColor(Color::White); _font = Resources::get<sf::Font>("ShadowsIntoLight-Regular.ttf"); _text.setFont(*_font); _text.setCharacterSize(40); _text.setStyle(Text::Bold); } void BlueTextComponent::SetText(const std::string& str) { _string = str; _text.setString(_string); } //Yellow Text Component void YellowTextComponent::update(double dt) { _text.setPosition(_parent->getPosition()); } void YellowTextComponent::render() { Renderer::queue(&_text); } YellowTextComponent::YellowTextComponent(Entity* const p, const std::string& str) : Component(p), _string(str) { _text.setString(_string); _text.setFillColor(Color::Yellow); _text.setOutlineColor(Color::White); _font = Resources::get<sf::Font>("ShadowsIntoLight-Regular.ttf"); _text.setFont(*_font); _text.setCharacterSize(40); _text.setStyle(Text::Bold); } void YellowTextComponent::SetText(const std::string& str) { _string = str; _text.setString(_string); } //Magenta Text Component void MagentaTextComponent::update(double dt) { _text.setPosition(_parent->getPosition()); } void MagentaTextComponent::render() { Renderer::queue(&_text); } MagentaTextComponent::MagentaTextComponent(Entity* const p, const std::string& str) : Component(p), _string(str) { _text.setString(_string); _text.setFillColor(Color::Magenta); _text.setOutlineColor(Color::White); _font = Resources::get<sf::Font>("ShadowsIntoLight-Regular.ttf"); _text.setFont(*_font); _text.setCharacterSize(40); _text.setStyle(Text::Bold); } void MagentaTextComponent::SetText(const std::string& str) { _string = str; _text.setString(_string); } //Cyan Text Component void CyanTextComponent::update(double dt) { _text.setPosition(_parent->getPosition()); } void CyanTextComponent::render() { Renderer::queue(&_text); } CyanTextComponent::CyanTextComponent(Entity* const p, const std::string& str) : Component(p), _string(str) { _text.setString(_string); _text.setFillColor(Color::Cyan); _text.setOutlineColor(Color::White); _font = Resources::get<sf::Font>("ShadowsIntoLight-Regular.ttf"); _text.setFont(*_font); _text.setCharacterSize(40); _text.setStyle(Text::Bold); } void CyanTextComponent::SetText(const std::string& str) { _string = str; _text.setString(_string); } //Commented lines: //_font = Resources::get<sf::Font>("RobotoMono-Regular.ttf"); //_font = Resources::get<sf::Font>("RobotoMono-Bold.ttf"); //_font = Resources::get<sf::Font>("arial.ttf");
28.010204
109
0.710383
OlavJDigranes
3cb75be46872481ade8889cd1a56a2648c33cadc
18,864
cc
C++
chrome/browser/paint_preview/paint_preview_browsertest.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
chrome/browser/paint_preview/paint_preview_browsertest.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
chrome/browser/paint_preview/paint_preview_browsertest.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2019 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 "base/base64.h" #include "base/bind.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/optional.h" #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" #include "base/unguessable_token.h" #include "build/build_config.h" #include "chrome/browser/ui/browser.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "components/paint_preview/browser/paint_preview_client.h" #include "components/paint_preview/common/file_stream.h" #include "components/paint_preview/common/mojom/paint_preview_recorder.mojom-shared.h" #include "components/paint_preview/common/proto/paint_preview.pb.h" #include "components/paint_preview/common/recording_map.h" #include "components/paint_preview/common/serialized_recording.h" #include "components/paint_preview/common/test_utils.h" #include "components/ukm/test_ukm_recorder.h" #include "content/public/browser/notification_types.h" #include "content/public/browser/render_process_host.h" #include "content/public/common/content_switches.h" #include "content/public/test/browser_test.h" #include "net/dns/mock_host_resolver.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "services/metrics/public/cpp/ukm_builders.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h" #include "third_party/skia/include/core/SkPicture.h" #include "third_party/skia/include/core/SkStream.h" #include "url/gurl.h" namespace paint_preview { class NoOpPaintPreviewRecorder : public mojom::PaintPreviewRecorder { public: NoOpPaintPreviewRecorder() = default; ~NoOpPaintPreviewRecorder() override = default; NoOpPaintPreviewRecorder(const NoOpPaintPreviewRecorder&) = delete; NoOpPaintPreviewRecorder& operator=(const NoOpPaintPreviewRecorder&) = delete; void SetRequestedClosure(base::OnceClosure requested) { requested_ = std::move(requested); } void CapturePaintPreview( mojom::PaintPreviewCaptureParamsPtr params, mojom::PaintPreviewRecorder::CapturePaintPreviewCallback callback) override { callback_ = std::move(callback); std::move(requested_).Run(); } void BindRequest(mojo::ScopedInterfaceEndpointHandle handle) { binding_.Bind(mojo::PendingAssociatedReceiver<mojom::PaintPreviewRecorder>( std::move(handle))); } private: base::OnceClosure requested_; mojom::PaintPreviewRecorder::CapturePaintPreviewCallback callback_; mojo::AssociatedReceiver<mojom::PaintPreviewRecorder> binding_{this}; }; // Test harness for a integration test of paint previews. In this test: // - Each RenderFrame has an instance of PaintPreviewRecorder attached. // - Each WebContents has an instance of PaintPreviewClient attached. // This permits end-to-end testing of the flow of paint previews. class PaintPreviewBrowserTest : public InProcessBrowserTest, public testing::WithParamInterface<RecordingPersistence> { public: PaintPreviewBrowserTest(const PaintPreviewBrowserTest&) = delete; PaintPreviewBrowserTest& operator=(const PaintPreviewBrowserTest&) = delete; protected: PaintPreviewBrowserTest() = default; ~PaintPreviewBrowserTest() override = default; void SetUp() override { ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); InProcessBrowserTest::SetUp(); } void SetUpOnMainThread() override { host_resolver()->AddRule("*", "127.0.0.1"); http_server_.ServeFilesFromSourceDirectory("content/test/data"); ASSERT_TRUE(http_server_.Start()); } void SetUpCommandLine(base::CommandLine* command_line) override { content::IsolateAllSitesForTesting(command_line); } void CreateClient() { PaintPreviewClient::CreateForWebContents(GetWebContents()); } content::WebContents* GetWebContents() { return browser()->tab_strip_model()->GetActiveWebContents(); } void LoadPage(const GURL& url) const { ui_test_utils::NavigateToURL(browser(), url); } void LoadHtml(const base::StringPiece& html) const { std::string base64_html; base::Base64Encode(html, &base64_html); GURL url(std::string("data:text/html;base64,") + base64_html); ui_test_utils::NavigateToURL(browser(), url); } PaintPreviewClient::PaintPreviewParams MakeParams() const { PaintPreviewClient::PaintPreviewParams params(GetParam()); params.inner.is_main_frame = true; params.root_dir = temp_dir_.GetPath(); params.inner.capture_links = true; params.inner.max_capture_size = 0; return params; } void OverrideInterface(NoOpPaintPreviewRecorder* service) { blink::AssociatedInterfaceProvider* remote_interfaces = GetWebContents()->GetMainFrame()->GetRemoteAssociatedInterfaces(); remote_interfaces->OverrideBinderForTesting( mojom::PaintPreviewRecorder::Name_, base::BindRepeating(&NoOpPaintPreviewRecorder::BindRequest, base::Unretained(service))); } void WaitForLoadStopWithoutSuccessCheck() { // In many cases, the load may have finished before we get here. Only wait // if the tab still has a pending navigation. auto* web_contents = GetWebContents(); if (web_contents->IsLoading()) { content::WindowedNotificationObserver load_stop_observer( content::NOTIFICATION_LOAD_STOP, content::Source<content::NavigationController>( &web_contents->GetController())); load_stop_observer.Wait(); } } // Check that |recording_map| contains the frame |frame_proto| and is a valid // SkPicture. Don't bother checking the contents as this is non-trivial and // could change. Instead check that the SkPicture can be read correctly and // has a cull rect of at least |size|. // // Consumes the recording from |recording_map|. static void EnsureSkPictureIsValid(RecordingMap* recording_map, const PaintPreviewFrameProto& frame_proto, size_t expected_subframe_count, const gfx::Size& size = gfx::Size(1, 1)) { base::ScopedAllowBlockingForTesting scoped_blocking; auto it = recording_map->find(base::UnguessableToken::Deserialize( frame_proto.embedding_token_high(), frame_proto.embedding_token_low())); ASSERT_NE(it, recording_map->end()); base::Optional<SkpResult> result = std::move(it->second).Deserialize(); ASSERT_TRUE(result.has_value()); EXPECT_NE(result->skp, nullptr); EXPECT_GE(result->skp->cullRect().width(), 0); EXPECT_GE(result->skp->cullRect().height(), 0); EXPECT_EQ(result->ctx.size(), expected_subframe_count); recording_map->erase(it); } base::ScopedTempDir temp_dir_; net::EmbeddedTestServer http_server_; net::EmbeddedTestServer http_server_different_origin_; }; IN_PROC_BROWSER_TEST_P(PaintPreviewBrowserTest, CaptureFrame) { LoadPage(http_server_.GetURL("a.com", "/cross_site_iframe_factory.html?a")); ukm::TestAutoSetUkmRecorder ukm_recorder; auto params = MakeParams(); base::RunLoop loop; CreateClient(); auto* client = PaintPreviewClient::FromWebContents(GetWebContents()); WaitForLoadStopWithoutSuccessCheck(); client->CapturePaintPreview( params, GetWebContents()->GetMainFrame(), base::BindOnce( [](base::RepeatingClosure quit, const PaintPreviewClient::PaintPreviewParams& params, base::UnguessableToken guid, mojom::PaintPreviewStatus status, std::unique_ptr<CaptureResult> result) { EXPECT_EQ(guid, params.inner.document_guid); EXPECT_EQ(status, mojom::PaintPreviewStatus::kOk); EXPECT_TRUE(result->proto.has_root_frame()); EXPECT_EQ(result->proto.subframes_size(), 0); EXPECT_EQ(result->proto.root_frame() .content_id_to_embedding_tokens_size(), 0); EXPECT_TRUE(result->proto.root_frame().is_main_frame()); { base::ScopedAllowBlockingForTesting scoped_blocking; auto pair = RecordingMapFromCaptureResult(std::move(*result)); EnsureSkPictureIsValid(&pair.first, pair.second.root_frame(), 0); } quit.Run(); }, loop.QuitClosure(), params)); loop.Run(); auto entries = ukm_recorder.GetEntriesByName( ukm::builders::PaintPreviewCapture::kEntryName); EXPECT_EQ(1u, entries.size()); } IN_PROC_BROWSER_TEST_P(PaintPreviewBrowserTest, CaptureMainFrameWithCrossProcessSubframe) { LoadPage( http_server_.GetURL("a.com", "/cross_site_iframe_factory.html?a(b)")); auto params = MakeParams(); base::RunLoop loop; CreateClient(); auto* client = PaintPreviewClient::FromWebContents(GetWebContents()); WaitForLoadStopWithoutSuccessCheck(); client->CapturePaintPreview( params, GetWebContents()->GetMainFrame(), base::BindOnce( [](base::RepeatingClosure quit, const PaintPreviewClient::PaintPreviewParams& params, base::UnguessableToken guid, mojom::PaintPreviewStatus status, std::unique_ptr<CaptureResult> result) { EXPECT_EQ(guid, params.inner.document_guid); EXPECT_EQ(status, mojom::PaintPreviewStatus::kOk); EXPECT_TRUE(result->proto.has_root_frame()); EXPECT_EQ(result->proto.subframes_size(), 1); EXPECT_EQ(result->proto.root_frame() .content_id_to_embedding_tokens_size(), 1); EXPECT_TRUE(result->proto.root_frame().is_main_frame()); EXPECT_EQ(result->proto.subframes(0) .content_id_to_embedding_tokens_size(), 0); EXPECT_FALSE(result->proto.subframes(0).is_main_frame()); { base::ScopedAllowBlockingForTesting scoped_blocking; auto pair = RecordingMapFromCaptureResult(std::move(*result)); EnsureSkPictureIsValid(&pair.first, pair.second.root_frame(), 1); EnsureSkPictureIsValid(&pair.first, pair.second.subframes(0), 0); } quit.Run(); }, loop.QuitClosure(), params)); loop.Run(); } IN_PROC_BROWSER_TEST_P(PaintPreviewBrowserTest, CaptureMainFrameWithScrollableSameProcessSubframe) { std::string html = R"(<html> <iframe srcdoc="<div style='width: 300px; height: 300px; background-color: #ff0000'> &nbsp; </div>" title="subframe" width="100px" height="100px"> </iframe> </html>)"; LoadHtml(html); auto params = MakeParams(); base::RunLoop loop; CreateClient(); auto* client = PaintPreviewClient::FromWebContents(GetWebContents()); WaitForLoadStopWithoutSuccessCheck(); client->CapturePaintPreview( params, GetWebContents()->GetMainFrame(), base::BindOnce( [](base::RepeatingClosure quit, const PaintPreviewClient::PaintPreviewParams& params, base::UnguessableToken guid, mojom::PaintPreviewStatus status, std::unique_ptr<CaptureResult> result) { EXPECT_EQ(guid, params.inner.document_guid); EXPECT_EQ(status, mojom::PaintPreviewStatus::kOk); EXPECT_TRUE(result->proto.has_root_frame()); EXPECT_EQ(result->proto.subframes_size(), 1); EXPECT_EQ(result->proto.root_frame() .content_id_to_embedding_tokens_size(), 1); EXPECT_TRUE(result->proto.root_frame().is_main_frame()); EXPECT_EQ(result->proto.subframes(0) .content_id_to_embedding_tokens_size(), 0); EXPECT_FALSE(result->proto.subframes(0).is_main_frame()); { base::ScopedAllowBlockingForTesting scoped_blocking; auto pair = RecordingMapFromCaptureResult(std::move(*result)); EnsureSkPictureIsValid(&pair.first, pair.second.root_frame(), 1); EnsureSkPictureIsValid(&pair.first, pair.second.subframes(0), 0, gfx::Size(300, 300)); } quit.Run(); }, loop.QuitClosure(), params)); loop.Run(); } IN_PROC_BROWSER_TEST_P(PaintPreviewBrowserTest, CaptureMainFrameWithNonScrollableSameProcessSubframe) { std::string html = R"(<html> <iframe srcdoc="<div style='width: 50px; height: 50px; background-color: #ff0000'> &nbsp; </div>" title="subframe" width="100px" height="100px"> </iframe> </html>)"; LoadHtml(html); auto params = MakeParams(); base::RunLoop loop; CreateClient(); auto* client = PaintPreviewClient::FromWebContents(GetWebContents()); WaitForLoadStopWithoutSuccessCheck(); client->CapturePaintPreview( params, GetWebContents()->GetMainFrame(), base::BindOnce( [](base::RepeatingClosure quit, const PaintPreviewClient::PaintPreviewParams& params, base::UnguessableToken guid, mojom::PaintPreviewStatus status, std::unique_ptr<CaptureResult> result) { EXPECT_EQ(guid, params.inner.document_guid); EXPECT_EQ(status, mojom::PaintPreviewStatus::kOk); EXPECT_TRUE(result->proto.has_root_frame()); EXPECT_EQ(result->proto.subframes_size(), 0); EXPECT_EQ(result->proto.root_frame() .content_id_to_embedding_tokens_size(), 0); EXPECT_TRUE(result->proto.root_frame().is_main_frame()); { base::ScopedAllowBlockingForTesting scoped_blocking; auto pair = RecordingMapFromCaptureResult(std::move(*result)); EnsureSkPictureIsValid(&pair.first, pair.second.root_frame(), 0); } quit.Run(); }, loop.QuitClosure(), params)); loop.Run(); } // https://crbug.com/1146573 reproduction. If a renderer crashes, // WebContentsObserver::RenderFrameDeleted. Paint preview implements this in an // observer which in turn releases the capture handle which can cause the // WebContents to be reloaded on Android where we have auto-reload. This reload // occurs *during* crash handling, leaving the frame in an invalid state and // leading to a crash when it subsequently unloaded. // This is fixed by deferring it to a PostTask. IN_PROC_BROWSER_TEST_P(PaintPreviewBrowserTest, DontReloadInRenderProcessExit) { // In the FileSystem variant of this test, blocking needs to be permitted to // allow cleanup to work during the crash. base::ScopedAllowBlockingForTesting scope; LoadPage(http_server_.GetURL("a.com", "/title1.html")); content::WebContents* web_contents = GetWebContents(); // Override remote interfaces with a no-op. base::RunLoop started_loop; NoOpPaintPreviewRecorder noop_recorder; noop_recorder.SetRequestedClosure(started_loop.QuitClosure()); OverrideInterface(&noop_recorder); CreateClient(); auto* client = PaintPreviewClient::FromWebContents(web_contents); // Do this twice to simulate conditions for crash. auto handle1 = web_contents->IncrementCapturerCount(gfx::Size(), /*stay_hidden=*/true, /*stay_awake=*/true); auto handle2 = web_contents->IncrementCapturerCount(gfx::Size(), /*stay_hidden=*/true, /*stay_awake=*/true); // A callback that causes the frame to reload and end up in an invalid state // if it is allowed to run during crash handling. base::RunLoop finished_loop; auto params = MakeParams(); bool did_run = false; client->CapturePaintPreview( params, web_contents->GetMainFrame(), // This callback is now posted so it shouldn't cause a crash. base::BindOnce( [](content::WebContents* web_contents, bool* did_run_ptr, base::ScopedClosureRunner handle1, base::ScopedClosureRunner handle2, base::UnguessableToken guid, mojom::PaintPreviewStatus status, std::unique_ptr<CaptureResult> result) { EXPECT_EQ(status, mojom::PaintPreviewStatus::kFailed); EXPECT_EQ(result, nullptr); // On Android crashed frames are marked as needing reload. web_contents->GetController().SetNeedsReload(); handle1.RunAndReset(); handle2.RunAndReset(); *did_run_ptr = true; }, web_contents, &did_run, std::move(handle1), std::move(handle2)) .Then(finished_loop.QuitClosure())); // Wait for the request to execute before crashing the renderer. Otherwise in // the FileSystem variant it is possible there will be a race during creation // of the file with the renderer crash. If this happens the callback for // `finished_loop` will not be run as no request to capture succeeded leading // to a timeout. started_loop.Run(); // Crash the renderer. content::RenderProcessHost* process = GetWebContents()->GetMainFrame()->GetProcess(); content::RenderProcessHostWatcher crash_observer( process, content::RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT); process->Shutdown(0); crash_observer.Wait(); // The browser would have crashed before the loop exited if the callback was // not posted. if (!did_run) finished_loop.Run(); // Now navigate away and ensure that the frame unloads successfully. LoadPage(http_server_.GetURL("a.com", "/title2.html")); } INSTANTIATE_TEST_SUITE_P(All, PaintPreviewBrowserTest, testing::Values(RecordingPersistence::kFileSystem, RecordingPersistence::kMemoryBuffer), PersistenceParamToString); } // namespace paint_preview
41.459341
96
0.657496
iridium-browser
3cb9f6b82085bc2d44866a0ba13ab36b65fe6494
8,248
cc
C++
ash/display/display_configuration_controller.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
ash/display/display_configuration_controller.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
ash/display/display_configuration_controller.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/display/display_configuration_controller.h" #include "ash/display/display_animator.h" #include "ash/display/display_util.h" #include "ash/display/window_tree_host_manager.h" #include "ash/rotator/screen_rotation_animator.h" #include "ash/shell.h" #include "ash/strings/grit/ash_strings.h" #include "base/time/time.h" #include "chromeos/system/devicemode.h" #include "ui/base/class_property.h" #include "ui/base/l10n/l10n_util.h" #include "ui/display/display_layout.h" #include "ui/display/manager/display_manager.h" DEFINE_UI_CLASS_PROPERTY_TYPE(ash::ScreenRotationAnimator*); namespace { // Specifies how long the display change should have been disabled // after each display change operations. // |kCycleDisplayThrottleTimeoutMs| is set to be longer to avoid // changing the settings while the system is still configurating // displays. It will be overriden by |kAfterDisplayChangeThrottleTimeoutMs| // when the display change happens, so the actual timeout is much shorter. const int64_t kAfterDisplayChangeThrottleTimeoutMs = 500; const int64_t kCycleDisplayThrottleTimeoutMs = 4000; const int64_t kSetPrimaryDisplayThrottleTimeoutMs = 500; // A property key to store the ScreenRotationAnimator of the window; Used for // screen rotation. DEFINE_OWNED_UI_CLASS_PROPERTY_KEY(ash::ScreenRotationAnimator, kScreenRotationAnimatorKey, nullptr); } // namespace namespace ash { class DisplayConfigurationController::DisplayChangeLimiter { public: DisplayChangeLimiter() : throttle_timeout_(base::Time::Now()) {} void SetThrottleTimeout(int64_t throttle_ms) { throttle_timeout_ = base::Time::Now() + base::TimeDelta::FromMilliseconds(throttle_ms); } bool IsThrottled() const { return base::Time::Now() < throttle_timeout_; } private: base::Time throttle_timeout_; DISALLOW_COPY_AND_ASSIGN(DisplayChangeLimiter); }; DisplayConfigurationController::DisplayConfigurationController( display::DisplayManager* display_manager, WindowTreeHostManager* window_tree_host_manager) : display_manager_(display_manager), window_tree_host_manager_(window_tree_host_manager), weak_ptr_factory_(this) { window_tree_host_manager_->AddObserver(this); if (chromeos::IsRunningAsSystemCompositor()) limiter_.reset(new DisplayChangeLimiter); display_animator_.reset(new DisplayAnimator()); } DisplayConfigurationController::~DisplayConfigurationController() { window_tree_host_manager_->RemoveObserver(this); } void DisplayConfigurationController::SetDisplayLayout( std::unique_ptr<display::DisplayLayout> layout) { if (display_animator_) { display_animator_->StartFadeOutAnimation( base::Bind(&DisplayConfigurationController::SetDisplayLayoutImpl, weak_ptr_factory_.GetWeakPtr(), base::Passed(&layout))); } else { SetDisplayLayoutImpl(std::move(layout)); } } void DisplayConfigurationController::SetUnifiedDesktopLayoutMatrix( const display::UnifiedDesktopLayoutMatrix& matrix) { DCHECK(display_manager_->IsInUnifiedMode()); if (display_animator_) { display_animator_->StartFadeOutAnimation(base::Bind( &DisplayConfigurationController::SetUnifiedDesktopLayoutMatrixImpl, weak_ptr_factory_.GetWeakPtr(), matrix)); } else { SetUnifiedDesktopLayoutMatrixImpl(matrix); } } void DisplayConfigurationController::SetMirrorMode(bool mirror) { if (!display_manager_->is_multi_mirroring_enabled() && display_manager_->num_connected_displays() > 2) { ShowDisplayErrorNotification( l10n_util::GetStringUTF16(IDS_ASH_DISPLAY_MIRRORING_NOT_SUPPORTED), false); return; } if (display_manager_->num_connected_displays() <= 1 || display_manager_->IsInMirrorMode() == mirror || IsLimited()) { return; } SetThrottleTimeout(kCycleDisplayThrottleTimeoutMs); if (display_animator_) { display_animator_->StartFadeOutAnimation( base::Bind(&DisplayConfigurationController::SetMirrorModeImpl, weak_ptr_factory_.GetWeakPtr(), mirror)); } else { SetMirrorModeImpl(mirror); } } void DisplayConfigurationController::SetDisplayRotation( int64_t display_id, display::Display::Rotation rotation, display::Display::RotationSource source, DisplayConfigurationController::RotationAnimation mode) { if (display_manager_->IsDisplayIdValid(display_id)) { if (GetTargetRotation(display_id) == rotation) return; ScreenRotationAnimator* screen_rotation_animator = GetScreenRotationAnimatorForDisplay(display_id); screen_rotation_animator->Rotate(rotation, source, mode); } else { display_manager_->SetDisplayRotation(display_id, rotation, source); } } display::Display::Rotation DisplayConfigurationController::GetTargetRotation( int64_t display_id) { if (!display_manager_->IsDisplayIdValid(display_id)) return display::Display::ROTATE_0; ScreenRotationAnimator* animator = GetScreenRotationAnimatorForDisplay(display_id); if (animator->IsRotating()) return animator->GetTargetRotation(); return display_manager_->GetDisplayInfo(display_id).GetActiveRotation(); } void DisplayConfigurationController::SetPrimaryDisplayId(int64_t display_id) { if (display_manager_->GetNumDisplays() <= 1 || IsLimited()) return; SetThrottleTimeout(kSetPrimaryDisplayThrottleTimeoutMs); if (display_animator_) { display_animator_->StartFadeOutAnimation( base::Bind(&DisplayConfigurationController::SetPrimaryDisplayIdImpl, weak_ptr_factory_.GetWeakPtr(), display_id)); } else { SetPrimaryDisplayIdImpl(display_id); } } void DisplayConfigurationController::OnDisplayConfigurationChanged() { // TODO(oshima): Stop all animations. SetThrottleTimeout(kAfterDisplayChangeThrottleTimeoutMs); } // Protected void DisplayConfigurationController::ResetAnimatorForTest() { if (!display_animator_) return; display_animator_.reset(); } void DisplayConfigurationController::SetScreenRotationAnimatorForTest( int64_t display_id, std::unique_ptr<ScreenRotationAnimator> animator) { aura::Window* root_window = Shell::GetRootWindowForDisplayId(display_id); root_window->SetProperty(kScreenRotationAnimatorKey, animator.release()); } // Private void DisplayConfigurationController::SetThrottleTimeout(int64_t throttle_ms) { if (limiter_) limiter_->SetThrottleTimeout(throttle_ms); } bool DisplayConfigurationController::IsLimited() { return limiter_ && limiter_->IsThrottled(); } void DisplayConfigurationController::SetDisplayLayoutImpl( std::unique_ptr<display::DisplayLayout> layout) { display_manager_->SetLayoutForCurrentDisplays(std::move(layout)); if (display_animator_) display_animator_->StartFadeInAnimation(); } void DisplayConfigurationController::SetMirrorModeImpl(bool mirror) { display_manager_->SetMirrorMode( mirror ? display::MirrorMode::kNormal : display::MirrorMode::kOff, base::nullopt); if (display_animator_) display_animator_->StartFadeInAnimation(); } void DisplayConfigurationController::SetPrimaryDisplayIdImpl( int64_t display_id) { window_tree_host_manager_->SetPrimaryDisplayId(display_id); if (display_animator_) display_animator_->StartFadeInAnimation(); } void DisplayConfigurationController::SetUnifiedDesktopLayoutMatrixImpl( const display::UnifiedDesktopLayoutMatrix& matrix) { display_manager_->SetUnifiedDesktopMatrix(matrix); if (display_animator_) display_animator_->StartFadeInAnimation(); } ScreenRotationAnimator* DisplayConfigurationController::GetScreenRotationAnimatorForDisplay( int64_t display_id) { aura::Window* root_window = Shell::GetRootWindowForDisplayId(display_id); ScreenRotationAnimator* animator = root_window->GetProperty(kScreenRotationAnimatorKey); if (!animator) { animator = new ScreenRotationAnimator(root_window); root_window->SetProperty(kScreenRotationAnimatorKey, animator); } return animator; } } // namespace ash
34.366667
78
0.771581
zipated
3cba9e6d5b3aa71faded3c8bbef606d2d265971b
3,039
c++
C++
extra/xftp/tests/test2.c++
maciek-27/Rgp
d28b5522e640e4c7b951f6861d97cbe52b0a35c9
[ "MIT" ]
null
null
null
extra/xftp/tests/test2.c++
maciek-27/Rgp
d28b5522e640e4c7b951f6861d97cbe52b0a35c9
[ "MIT" ]
null
null
null
extra/xftp/tests/test2.c++
maciek-27/Rgp
d28b5522e640e4c7b951f6861d97cbe52b0a35c9
[ "MIT" ]
null
null
null
#include <libstreamcon/sctpconnection.h++> #include <libstreamcon/databuffer.h++> #include <libstreamcon/stream.h++> #include <sys/time.h> #include <libstreamcon/sctpclient.h++> #include <libstreamcon/iofilters/tlsfilter.h++> using namespace streamcon; Mutex mutex; #define KEYFILE "client.pem" #define PASSWORD "password" #define CA_LIST "root.pem" #define CHUNK_SIZE 4096 unsigned long gettv() { struct timeval tvstart; gettimeofday(&tvstart,0); return tvstart.tv_sec; } bool bUseTls; class DataThread : public StreamThread { public: DataThread(Stream& _stream) : StreamThread(_stream) {;} unsigned long size; void Run() { char buffer[CHUNK_SIZE]; if(bUseTls) { TLSFilter* tls = new TLSFilter; stream.PushFilter(tls); tls->InitializeCTX(KEYFILE, PASSWORD, CA_LIST); tls->StartTLS(); printf("TLS Started!\n"); } printf("Thread started\n"); unsigned long t_start = gettv(); unsigned long t_last = t_start; unsigned long old_size = 0; float speed = 1.0; while(1) { size += stream.GetData(buffer, CHUNK_SIZE); if(size - old_size > (unsigned long)speed && gettv() > t_last) { speed=(size)/(gettv()-t_start);; old_size = size; t_last = gettv(); printf("%i Counter %luMB - %.2fMB/s\n", stream.GetId(), size/1024/1024, speed/1024/1024); } } } }; class TestClient : public SCTPClient { public: DataThread** threads; int nthreads; TestClient(int _nthreads) : nthreads(_nthreads){ threads = (DataThread**)malloc(sizeof(DataThread*)*nthreads); } ~TestClient() { for(int i = 0;i< nthreads;i++) delete threads[i]; free(threads); } void OnConnect(Connection& conn) throw() { std::cout << "Client is connected!\n" << std::endl; threads[0] = new DataThread(bUseTls? conn.AllocStream(1): conn.AllocStream(1)); for(int i = 1;i< nthreads;i++) { threads[i] = new DataThread(bUseTls? conn.AllocStream(i+1): conn.AllocStream(i+1)); } for(int i = 0;i<nthreads;i++) { threads[i]->Start(); } } void OnDisconnect() throw() { std::cout << "Disconnected??" << std::endl; for(int i = 0;i<5;i++) { std::cout << i << " recieved " << threads[i]->size/1024 << "KBs" << std::endl; delete threads[i]; } std::cout << "Client is disconnected!\n" << std::endl; } }; int main(int argc, char** argv) { int nstreams = 1; if(argc>1) { if(argv[1][0] == 's') { bUseTls = true; argv[1]++; // omit this char } if(argv[1][0] != 0) { nstreams = atoi(argv[1]); } } printf("Starting client with %i cuncurrent %sstreams.\n", nstreams, bUseTls?"TLS ":""); TestClient client(nstreams); while(1) { try { client.Connect(argc>2?argv[2]:"127.0.0.1", defaultPort, defaultStreams); } catch(Connection::ConnectionSevered) { std::cout << "Disconnected, retrying in 5 seconds." << std::endl; sleep(5); } catch(Connection::ConnectionRefused) { std::cout << "Refused, retrying in 5 seconds." << std::endl; sleep(5); } } return 0; }
22.021739
88
0.629483
maciek-27
3cbd1157b6c5be92bc2ea6aa85a5a88de15a339c
13,744
cpp
C++
Libs/Visualization/VTK/Core/ctkVTKConnection.cpp
lassoan/CTK
ba271a053217d26e90dee35837cd3979c3bb5b8b
[ "Apache-2.0" ]
1
2015-05-13T02:09:20.000Z
2015-05-13T02:09:20.000Z
Libs/Visualization/VTK/Core/ctkVTKConnection.cpp
medInria/CTK
00694c9f8a0da6ee28fb079902e6a8c3ec428058
[ "Apache-2.0" ]
null
null
null
Libs/Visualization/VTK/Core/ctkVTKConnection.cpp
medInria/CTK
00694c9f8a0da6ee28fb079902e6a8c3ec428058
[ "Apache-2.0" ]
1
2018-10-21T12:09:24.000Z
2018-10-21T12:09:24.000Z
/*========================================================================= Library: CTK Copyright (c) Kitware Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt 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. =========================================================================*/ // Qt includes #include <QDebug> #include <QPointer> #include <QRegExp> #include <QString> #include <QTextStream> // CTK includes #include "ctkVTKConnection.h" #include "ctkVTKConnection_p.h" // VTK includes #include <vtkObject.h> #include <vtkSmartPointer.h> #include <vtkCallbackCommand.h> //----------------------------------------------------------------------------- QString convertPointerToString(void* pointer) { QString pointerAsString; QTextStream(&pointerAsString) << pointer; return pointerAsString; } //----------------------------------------------------------------------------- // ctkVTKConnectionPrivate methods //----------------------------------------------------------------------------- ctkVTKConnectionPrivate::ctkVTKConnectionPrivate(ctkVTKConnection& object) :q_ptr(&object) { this->Callback = vtkSmartPointer<vtkCallbackCommand>::New(); this->Callback->SetCallback(ctkVTKConnectionPrivate::DoCallback); this->Callback->SetClientData(this); this->VTKObject = 0; this->QtObject = 0; this->VTKEvent = vtkCommand::NoEvent; this->Priority = 0.0; this->ConnectionType = Qt::AutoConnection; this->SlotType = ARG_UNKNOWN; this->Connected = false; this->Blocked = false; this->Id = convertPointerToString(this); this->ObserveDeletion = false; } //----------------------------------------------------------------------------- ctkVTKConnectionPrivate::~ctkVTKConnectionPrivate() { } //----------------------------------------------------------------------------- void ctkVTKConnectionPrivate::connect() { Q_Q(ctkVTKConnection); if (this->Connected) { qDebug() << "ctkVTKConnection already connected."; return; } switch (this->SlotType) { case ctkVTKConnectionPrivate::ARG_VTKOBJECT_AND_VTKOBJECT: QObject::connect(q, SIGNAL(emitExecute(vtkObject*,vtkObject*)), this->QtObject, this->QtSlot.toLatin1(), this->ConnectionType); break; case ctkVTKConnectionPrivate::ARG_VTKOBJECT_VOID_ULONG_VOID: QObject::connect(q, SIGNAL(emitExecute(vtkObject*,void*,ulong,void*)), this->QtObject, this->QtSlot.toLatin1(), this->ConnectionType); break; default: Q_ASSERT(false); qCritical() << "Failed to connect - " << "The slot (" << this->QtSlot << ") owned by " << "QObject(" << this->QtObject->objectName() << ")" << " seems to have a wrong signature."; break; } // Make a connection between this and the vtk object q->addObserver(this->VTKObject, this->VTKEvent, this->Callback, this->Priority); // If necessary, observe vtk DeleteEvent if(this->ObserveDeletion) { // don't observe it twice if (this->VTKEvent != vtkCommand::DeleteEvent) { this->VTKObject->AddObserver(vtkCommand::DeleteEvent, this->Callback); } // Remove itself from its parent when vtkObject is deleted QObject::connect(this->QtObject, SIGNAL(destroyed(QObject*)), q, SLOT(qobjectDeleted())); } this->Connected = true; } //----------------------------------------------------------------------------- void ctkVTKConnectionPrivate::disconnect() { Q_Q(ctkVTKConnection); if (!this->Connected) { return; } if (this->QtObject) { switch (this->SlotType) { case ctkVTKConnectionPrivate::ARG_VTKOBJECT_AND_VTKOBJECT: QObject::disconnect(q, SIGNAL(emitExecute(vtkObject*,vtkObject*)), this->QtObject,this->QtSlot.toLatin1().data()); break; case ctkVTKConnectionPrivate::ARG_VTKOBJECT_VOID_ULONG_VOID: QObject::disconnect(q, SIGNAL(emitExecute(vtkObject*,void*,ulong,void*)), this->QtObject, this->QtSlot.toLatin1().data()); break; default: Q_ASSERT(false); qCritical() << "Failed to disconnect - " << "The slot (" << this->QtSlot << ") owned by " << "QObject(" << this->QtObject->objectName() << ")" << " seems to have a wrong signature."; break; } } if (this->VTKObject) { q->removeObserver(this->VTKObject, this->VTKEvent, this->Callback); this->VTKObject->RemoveObservers(vtkCommand::DeleteEvent, this->Callback); } if (this->ObserveDeletion && this->QtObject) { //this->VTKObject->AddObserver(vtkCommand::DeleteEvent, this->Callback); has already been removed QObject::disconnect(this->QtObject, SIGNAL(destroyed(QObject*)), q, SIGNAL(isBroke())); } this->Connected = false; } //----------------------------------------------------------------------------- // ctkVTKConnection methods //----------------------------------------------------------------------------- ctkVTKConnection::ctkVTKConnection(QObject* _parent): Superclass(_parent) , d_ptr(new ctkVTKConnectionPrivate(*this)) { } //----------------------------------------------------------------------------- ctkVTKConnection::~ctkVTKConnection() { Q_D(ctkVTKConnection); if (d->ObserveDeletion) { this->disconnect(); } } //----------------------------------------------------------------------------- QString ctkVTKConnection::id()const { Q_D(const ctkVTKConnection); return d->Id; } //----------------------------------------------------------------------------- QObject* ctkVTKConnection::object()const { Q_D(const ctkVTKConnection); return const_cast<QObject*>(d->QtObject); } //----------------------------------------------------------------------------- QDebug operator<<(QDebug dbg, const ctkVTKConnection& connection) { const ctkVTKConnectionPrivate* d = connection.d_func(); dbg.nospace() << "ctkVTKConnection:" << &connection << endl << "Id:" << d->Id << endl << " VTKObject:" << d->VTKObject->GetClassName() << "(" << d->VTKObject << ")" << endl << " QtObject:" << d->QtObject << endl << " VTKEvent:" << d->VTKEvent << endl << " QtSlot:" << d->QtSlot << endl << " SlotType:" << d->SlotType << endl << " Priority:" << d->Priority << endl << " Connected:" << d->Connected << endl << " Blocked:" << d->Blocked; return dbg.space(); } //----------------------------------------------------------------------------- QString ctkVTKConnection::shortDescription() { Q_D(ctkVTKConnection); return ctkVTKConnection::shortDescription(d->VTKObject, d->VTKEvent, d->QtObject, d->QtSlot); } //----------------------------------------------------------------------------- QString ctkVTKConnection::shortDescription(vtkObject* vtk_obj, unsigned long vtk_event, const QObject* qt_obj, QString qt_slot) { QString ret; QTextStream ts( &ret ); ts << (vtk_obj ? vtk_obj->GetClassName() : "NULL") << " " << vtk_event << " " << qt_obj << " " << qt_slot; return ret; } //----------------------------------------------------------------------------- bool ctkVTKConnection::isValid(vtkObject* vtk_obj, unsigned long vtk_event, const QObject* qt_obj, QString qt_slot) { Q_UNUSED(vtk_event); if (!vtk_obj) { return false; } if (!qt_obj) { return false; } if (qt_slot.isEmpty()) { return false; } return true; } //----------------------------------------------------------------------------- void ctkVTKConnection::setup(vtkObject* vtk_obj, unsigned long vtk_event, const QObject* qt_obj, QString qt_slot, float priority, Qt::ConnectionType connectionType) { Q_D(ctkVTKConnection); if (!ctkVTKConnection::isValid(vtk_obj, vtk_event, qt_obj, qt_slot)) { return; } d->VTKObject = vtk_obj; d->QtObject = qt_obj; d->VTKEvent = vtk_event; d->QtSlot = qt_slot; d->Priority = priority; d->ConnectionType = connectionType; if (qt_slot.contains(QRegExp(QString("\\( ?vtkObject ?\\* ?, ?vtkObject ?\\* ?\\)")))) { d->SlotType = ctkVTKConnectionPrivate::ARG_VTKOBJECT_AND_VTKOBJECT; } else { d->SlotType = ctkVTKConnectionPrivate::ARG_VTKOBJECT_VOID_ULONG_VOID; } d->connect(); } //----------------------------------------------------------------------------- void ctkVTKConnection::setBlocked(bool block) { Q_D(ctkVTKConnection); d->Blocked = block; } //----------------------------------------------------------------------------- bool ctkVTKConnection::isBlocked()const { Q_D(const ctkVTKConnection); return d->Blocked; } //----------------------------------------------------------------------------- bool ctkVTKConnection::isEqual(vtkObject* vtk_obj, unsigned long vtk_event, const QObject* qt_obj, QString qt_slot)const { Q_D(const ctkVTKConnection); if (vtk_obj && d->VTKObject != vtk_obj) { return false; } if (vtk_event != vtkCommand::NoEvent && d->VTKEvent != vtk_event) { return false; } if (qt_obj && d->QtObject != qt_obj) { return false; } if (!qt_slot.isEmpty() && (QString(d->QtSlot).remove(' ').compare( QString(qt_slot).remove(' ')) != 0)) { return false; } return true; } //----------------------------------------------------------------------------- void ctkVTKConnectionPrivate::DoCallback(vtkObject* vtk_obj, unsigned long event, void* client_data, void* call_data) { ctkVTKConnectionPrivate* conn = reinterpret_cast<ctkVTKConnectionPrivate*>(client_data); Q_ASSERT(conn); conn->execute(vtk_obj, event, client_data, call_data); } //----------------------------------------------------------------------------- // callback from VTK to emit signal void ctkVTKConnectionPrivate::execute(vtkObject* vtk_obj, unsigned long vtk_event, void* client_data, void* call_data) { Q_Q(ctkVTKConnection); Q_ASSERT(this->Connected); if (this->Blocked) { return; } QPointer<ctkVTKConnection> connection(q); if(!this->ObserveDeletion || vtk_event != vtkCommand::DeleteEvent || this->VTKEvent == vtkCommand::DeleteEvent) { vtkObject* callDataAsVtkObject = 0; switch (this->SlotType) { case ctkVTKConnectionPrivate::ARG_VTKOBJECT_AND_VTKOBJECT: if (this->VTKEvent == vtk_event) { callDataAsVtkObject = reinterpret_cast<vtkObject*>( call_data ); if (!callDataAsVtkObject) { qCritical() << "The VTKEvent(" << this->VTKEvent<< ") triggered by vtkObject(" << this->VTKObject->GetClassName() << ") " << "doesn't return data of type vtkObject." << endl << "The slot (" << this->QtSlot << ") owned by " << "QObject(" << this->QtObject->objectName() << ")" << " may be incorrect."; } emit q->emitExecute(vtk_obj, callDataAsVtkObject); } break; case ctkVTKConnectionPrivate::ARG_VTKOBJECT_VOID_ULONG_VOID: emit q->emitExecute(vtk_obj, call_data, vtk_event, client_data); break; default: // Should never reach qCritical() << "Unknown SlotType:" << this->SlotType; return; break; } } if (!connection.isNull() && vtk_event == vtkCommand::DeleteEvent) { q->vtkObjectDeleted(); } } //----------------------------------------------------------------------------- void ctkVTKConnection::observeDeletion(bool enable) { Q_D(ctkVTKConnection); d->ObserveDeletion = enable; } //----------------------------------------------------------------------------- bool ctkVTKConnection::deletionObserved()const { Q_D(const ctkVTKConnection); return d->ObserveDeletion; } //----------------------------------------------------------------------------- void ctkVTKConnection::disconnect() { Q_D(ctkVTKConnection); d->disconnect(); } //----------------------------------------------------------------------------- void ctkVTKConnection::vtkObjectDeleted() { Q_D(ctkVTKConnection); d->VTKObject = 0; d->disconnect(); emit isBroke(); } //----------------------------------------------------------------------------- void ctkVTKConnection::qobjectDeleted() { Q_D(ctkVTKConnection); d->QtObject = 0; d->disconnect(); emit isBroke(); } //----------------------------------------------------------------------------- void ctkVTKConnection::addObserver(vtkObject* caller, unsigned long vtk_event, vtkCallbackCommand* callback, float priority) { caller->AddObserver(vtk_event, callback, priority); } //----------------------------------------------------------------------------- void ctkVTKConnection::removeObserver(vtkObject* caller, unsigned long vtk_event, vtkCallbackCommand* callback) { caller->RemoveObservers(vtk_event, callback); }
30.747204
111
0.525902
lassoan
3cbd5a684a6a6271146f5745dcb39a6e76042baa
12,275
cpp
C++
orbsvcs/Notify/MonitorControlExt/MonitorEventChannelFactory.cpp
binary42/OCI
08191bfe4899f535ff99637d019734ed044f479d
[ "MIT" ]
null
null
null
orbsvcs/Notify/MonitorControlExt/MonitorEventChannelFactory.cpp
binary42/OCI
08191bfe4899f535ff99637d019734ed044f479d
[ "MIT" ]
null
null
null
orbsvcs/Notify/MonitorControlExt/MonitorEventChannelFactory.cpp
binary42/OCI
08191bfe4899f535ff99637d019734ed044f479d
[ "MIT" ]
null
null
null
// $Id$ #include "orbsvcs/Notify/MonitorControlExt/MonitorEventChannelFactory.h" #include "orbsvcs/Notify/MonitorControlExt/NotifyMonitoringExtC.h" #include "orbsvcs/Notify/MonitorControlExt/MonitorEventChannel.h" #include "orbsvcs/Notify/MonitorControl/Dynamic_Statistic.h" #include "orbsvcs/Notify/Properties.h" #include "orbsvcs/Notify/Builder.h" #include "ace/Monitor_Point_Registry.h" #if defined (TAO_HAS_MONITOR_FRAMEWORK) && (TAO_HAS_MONITOR_FRAMEWORK == 1) TAO_BEGIN_VERSIONED_NAMESPACE_DECL // ****************************************************************** // Dynamic Statistic Classes // ****************************************************************** class EventChannels : public TAO_Dynamic_Statistic<TAO_MonitorEventChannelFactory> { public: EventChannels (TAO_MonitorEventChannelFactory* ecf, const ACE_CString& name, Monitor_Control_Types::Information_Type type, bool active) : TAO_Dynamic_Statistic<TAO_MonitorEventChannelFactory> (ecf, name.c_str (), type), active_ (active) { } virtual void update (void) { if (this->type () == Monitor_Control_Types::MC_LIST) { Monitor_Control_Types::NameList names; this->interf_->get_ecs (&names, this->active_); this->receive (names); } else { this->receive (this->interf_->get_ecs (0, this->active_)); } } private: bool active_; }; // ****************************************************************** // TAO_MonitorEventChannelFactory Methods // ****************************************************************** TAO_MonitorEventChannelFactory::TAO_MonitorEventChannelFactory ( const char* name) : name_ (name) { if (name != 0) { ACE_CString dir_name (this->name_ + "/"); ACE_CString stat_name (dir_name + NotifyMonitoringExt::ActiveEventChannelCount); EventChannels* event_channels = 0; ACE_NEW (event_channels, EventChannels (this, stat_name, Monitor_Control_Types::MC_NUMBER, true)); event_channels->add_to_registry (); event_channels->remove_ref (); this->stat_names_.push_back (stat_name); stat_name = dir_name + NotifyMonitoringExt::InactiveEventChannelCount; event_channels = 0; ACE_NEW (event_channels, EventChannels (this, stat_name, Monitor_Control_Types::MC_NUMBER, false)); event_channels->add_to_registry (); event_channels->remove_ref (); this->stat_names_.push_back (stat_name); stat_name = dir_name + NotifyMonitoringExt::ActiveEventChannelNames; event_channels = 0; ACE_NEW (event_channels, EventChannels (this, stat_name, Monitor_Control_Types::MC_LIST, true)); event_channels->add_to_registry (); event_channels->remove_ref (); this->stat_names_.push_back (stat_name); stat_name = dir_name + NotifyMonitoringExt::InactiveEventChannelNames; event_channels = 0; ACE_NEW (event_channels, EventChannels (this, stat_name, Monitor_Control_Types::MC_LIST, false)); event_channels->add_to_registry (); event_channels->remove_ref (); this->stat_names_.push_back (stat_name); stat_name = dir_name + NotifyMonitoringExt::EventChannelCreationTime; Monitor_Base* timestamp = 0; ACE_NEW (timestamp, Timestamp_Monitor (stat_name.c_str ())); ACE_Time_Value tv (ACE_OS::gettimeofday()); timestamp->receive (tv.sec () + (tv.usec () / 1000000.0)); timestamp->add_to_registry (); timestamp->remove_ref (); this->stat_names_.push_back (stat_name); Monitor_Point_Registry* instance = Monitor_Point_Registry::instance (); ACE_WRITE_GUARD (TAO_SYNCH_RW_MUTEX, guard, this->mutex_); Monitor_Base* names = instance->get (NotifyMonitoringExt::EventChannelFactoryNames); if (names == 0) { stat_name = NotifyMonitoringExt::EventChannelFactoryNames; ACE_NEW_THROW_EX (names, Monitor_Base (stat_name.c_str (), Monitor_Control_Types::MC_LIST), CORBA::NO_MEMORY ()); names->add_to_registry (); } Monitor_Control_Types::NameList list = names->get_list (); list.push_back (this->name_); names->receive (list); names->remove_ref (); } } TAO_MonitorEventChannelFactory::~TAO_MonitorEventChannelFactory (void) { Monitor_Point_Registry* instance = Monitor_Point_Registry::instance (); size_t size = this->stat_names_.size (); for (size_t i = 0; i < size; ++i) { instance->remove (this->stat_names_[i].c_str ()); } } CosNotifyChannelAdmin::EventChannel_ptr TAO_MonitorEventChannelFactory::create_named_channel ( const CosNotification::QoSProperties& initial_qos, const CosNotification::AdminProperties& initial_admin, CosNotifyChannelAdmin::ChannelID_out id, const char* name) { if (ACE_OS::strlen (name) == 0) { throw NotifyMonitoringExt::NameMapError (); } ACE_CString sname (this->name_ + "/"); sname += name; ACE_WRITE_GUARD_RETURN (TAO_SYNCH_RW_MUTEX, guard, this->mutex_, 0); // Make sure the name isn't already used. if (this->map_.find (sname) == 0) { throw NotifyMonitoringExt::NameAlreadyUsed (); } CosNotifyChannelAdmin::EventChannel_var ec = TAO_Notify_Properties::instance ()->builder ()->build_event_channel ( this, initial_qos, initial_admin, id, sname.c_str ()); if (CORBA::is_nil (ec.in ())) { return CosNotifyChannelAdmin::EventChannel::_nil (); } // Event channel creation was successful, try to bind it in our map. if (this->map_.bind (sname, id) != 0) { throw NotifyMonitoringExt::NameMapError (); } // The destructor of this object will unbind the // name from the map unless release is called. Unbinder unbinder (this->map_, sname); this->self_change (); unbinder.release (); return ec._retn (); } CosNotifyChannelAdmin::EventChannel_ptr TAO_MonitorEventChannelFactory::create_channel ( const CosNotification::QoSProperties& initial_qos, const CosNotification::AdminProperties& initial_admin, CosNotifyChannelAdmin::ChannelID_out id) { CosNotifyChannelAdmin::EventChannel_var ec = this->TAO_Notify_EventChannelFactory::create_channel (initial_qos, initial_admin, id); if (CORBA::is_nil (ec.in ())) { return CosNotifyChannelAdmin::EventChannel::_nil (); } // Make sure we can get down to the real event channel TAO_MonitorEventChannel* mec = dynamic_cast<TAO_MonitorEventChannel*> (ec->_servant ()); if (mec == 0) { throw CORBA::INTERNAL (); } // Construct the name using the new id ACE_CString sname (this->name_ + "/"); char name[64]; ACE_OS::sprintf(name, "%d", id); sname += name; ACE_WRITE_GUARD_RETURN (TAO_SYNCH_RW_MUTEX, guard, this->mutex_, 0); // Make sure the name isn't already used. if (this->map_.find (sname) == 0) throw NotifyMonitoringExt::NameAlreadyUsed (); // Event channel creation was successful, try to bind it in our map if (this->map_.bind (sname, id) != 0) { throw NotifyMonitoringExt::NameMapError (); } // Set the name and statistics on the event channel. mec->add_stats (sname.c_str ()); return ec._retn (); } void TAO_MonitorEventChannelFactory::remove (TAO_Notify_EventChannel* channel) { TAO_MonitorEventChannel* mec = dynamic_cast<TAO_MonitorEventChannel*> (channel); if (mec != 0) { ACE_WRITE_GUARD (TAO_SYNCH_RW_MUTEX, guard, this->mutex_); this->map_.unbind (mec->name ()); } this->TAO_Notify_EventChannelFactory::remove (channel); } size_t TAO_MonitorEventChannelFactory::get_suppliers ( CosNotifyChannelAdmin::ChannelID id) { size_t count = 0; CosNotifyChannelAdmin::EventChannel_var ec = this->get_event_channel (id); if (!CORBA::is_nil (ec.in ())) { CosNotifyChannelAdmin::AdminIDSeq_var supadmin_ids = ec->get_all_supplieradmins (); CORBA::ULong length = supadmin_ids->length (); for (CORBA::ULong j = 0; j < length; ++j) { CosNotifyChannelAdmin::SupplierAdmin_var admin = ec->get_supplieradmin (supadmin_ids[j]); if (!CORBA::is_nil (admin.in ())) { CosNotifyChannelAdmin::ProxyIDSeq_var proxys = admin->push_consumers (); count += proxys->length (); } } } return count; } size_t TAO_MonitorEventChannelFactory::get_consumers ( CosNotifyChannelAdmin::ChannelID id) { size_t count = 0; CosNotifyChannelAdmin::EventChannel_var ec = this->get_event_channel (id); if (!CORBA::is_nil (ec.in ())) { CosNotifyChannelAdmin::AdminIDSeq_var conadmin_ids = ec->get_all_consumeradmins (); CORBA::ULong length = conadmin_ids->length (); for (CORBA::ULong j = 0; j < length; ++j) { CosNotifyChannelAdmin::ConsumerAdmin_var admin = ec->get_consumeradmin (conadmin_ids[j]); if (!CORBA::is_nil (admin.in ())) { CosNotifyChannelAdmin::ProxyIDSeq_var proxys = admin->push_suppliers (); count += proxys->length (); } } } return count; } size_t TAO_MonitorEventChannelFactory::get_ecs ( Monitor_Control_Types::NameList* names, bool active) { size_t count = 0; CosNotifyChannelAdmin::ChannelIDSeq_var ids = this->get_all_channels (); CORBA::ULong total = ids->length (); for (CORBA::ULong i = 0; i < total; ++i) { CosNotifyChannelAdmin::ChannelID id = ids[i]; bool want_event_channel = !active; // Check for connected consumers. size_t consumers = this->get_consumers (id); if (consumers > 0) { want_event_channel = active; } if ((!active && want_event_channel) || (active && !want_event_channel)) { // Check for connected suppliers size_t suppliers = this->get_suppliers (id); if (suppliers > 0) { want_event_channel = active; } } if (want_event_channel) { count++; if (names != 0) { ACE_READ_GUARD_RETURN (TAO_SYNCH_RW_MUTEX, guard, this->mutex_, 0); Map::iterator itr (this->map_); Map::value_type* entry = 0; while (itr.next (entry)) { if (id == entry->item ()) { names->push_back (entry->key ()); } itr.advance (); } } } } return count; } // ****************************************************************** // Unbinder Helper // ****************************************************************** TAO_MonitorEventChannelFactory::Unbinder::Unbinder ( TAO_MonitorEventChannelFactory::Map& map, const ACE_CString& name) : map_ (map), name_ (name), released_ (false) { } TAO_MonitorEventChannelFactory::Unbinder::~Unbinder (void) { if (!this->released_) { this->map_.unbind (this->name_); } } void TAO_MonitorEventChannelFactory::Unbinder::release (void) { this->released_ = true; } TAO_END_VERSIONED_NAMESPACE_DECL #endif /* TAO_HAS_MONITOR_FRAMEWORK==1 */
27.834467
76
0.582811
binary42
3cbd6853c10d29c70ee6b9947316bb549c042402
411
cpp
C++
Alphabetic Patterns/alphabeticpattern56.cpp
Kajal13081/CPlusPlus-PatternHouse
257270f9b01e099f9c13f5bde39f07172f5474c0
[ "MIT" ]
4
2021-09-21T03:43:26.000Z
2022-01-07T03:07:56.000Z
Alphabetic Patterns/alphabeticpattern56.cpp
Kajal13081/CPlusPlus-PatternHouse
257270f9b01e099f9c13f5bde39f07172f5474c0
[ "MIT" ]
916
2021-09-01T15:40:24.000Z
2022-01-10T17:57:59.000Z
Alphabetic Patterns/alphabeticpattern56.cpp
Kajal13081/CPlusPlus-PatternHouse
257270f9b01e099f9c13f5bde39f07172f5474c0
[ "MIT" ]
20
2021-09-30T18:13:58.000Z
2022-01-06T09:55:36.000Z
#include<bits/stdc++.h> using namespace std; int main() { int cur_char=4; //(A+4 =E) for (int i=0;i<5;i++) { int inc=0; for (int j=i;j<i+5;j++) { inc=j; if(inc>cur_char) inc=inc-cur_char-1; //if char is > E , char is A char a = 65+inc; cout << a << " "; } cout << "\n"; } }
21.631579
82
0.372263
Kajal13081
3cbd9c86363034b011acf78b8abdb64e698e2e43
3,665
cpp
C++
mogupro/game/src/Sound/cIntroLoopableBGM.cpp
desspert/mogupro
ac39f5ec3fb670cf5044ef501951270d7d92a748
[ "MIT" ]
null
null
null
mogupro/game/src/Sound/cIntroLoopableBGM.cpp
desspert/mogupro
ac39f5ec3fb670cf5044ef501951270d7d92a748
[ "MIT" ]
null
null
null
mogupro/game/src/Sound/cIntroLoopableBGM.cpp
desspert/mogupro
ac39f5ec3fb670cf5044ef501951270d7d92a748
[ "MIT" ]
null
null
null
#include <Sound/cIntroLoopableBGM.h> #include <cinder/app/App.h> #include <Utility/cScheduler.h> namespace Sound { cIntroLoopableBGM::cIntroLoopableBGM( ) { alGenSources( 1, &source ); } cIntroLoopableBGM::~cIntroLoopableBGM( ) { if ( source != 0 ) { stop( ); alDeleteSources( 1, &source ); } if ( introId != 0 ) { alDeleteBuffers( 1, &introId ); } if ( mainId != 0 ) { alDeleteBuffers( 1, &mainId ); } } void cIntroLoopableBGM::create( char const* const rawData, size_t rawDataByte, float loopBeginSecond, float loopEndSecond ) { alGenBuffers( 1, &introId ); alBufferData ( introId, AL_FORMAT_STEREO16, rawData, calcOffset( loopBeginSecond ), 44100 ); alGenBuffers( 1, &mainId ); alBufferData ( mainId, AL_FORMAT_STEREO16, rawData + calcOffset( loopBeginSecond ), calcOffset( loopEndSecond ) - calcOffset( loopBeginSecond ), 44100 ); cinder::app::console( ) << "Sound: " << rawDataByte << std::endl; cinder::app::console( ) << "Sound: " << calcOffset( loopBeginSecond ) << std::endl; cinder::app::console( ) << "Sound: " << calcOffset( loopEndSecond ) << std::endl; cinder::app::console( ) << "Sound: " << calcOffset( loopEndSecond ) - calcOffset( loopBeginSecond ) << std::endl; this->loopBeginSecond = loopBeginSecond; } void cIntroLoopableBGM::play( ) const { alSourceQueueBuffers( source, 1, &introId ); alSourceQueueBuffers( source, 1, &mainId ); alSourcePlay( source ); time = 0.0F; introDeleted = false; } void cIntroLoopableBGM::stop( ) const { alSourceStop( source ); } void cIntroLoopableBGM::pause( ) const { alSourcePause( source ); } float cIntroLoopableBGM::getPitch() const { ALfloat value = 0.0F; alGetSourcef(source, AL_PITCH, &value); return value; } void cIntroLoopableBGM::fadeout(float fadeSecond, float target) { auto decrement = (getGain() - target) / fadeSecond; fadeHandle = Utility::cScheduler::getInstance()->applyLimitUpdate(fadeSecond, [this, decrement](float delta) { gain(getGain() - delta * decrement); }, [this] { stop(); }); } void cIntroLoopableBGM::fadein(float fadeSecond, float target) { play(); auto increment = (target) / fadeSecond; fadeHandle = Utility::cScheduler::getInstance()->applyLimitUpdate(fadeSecond, [this, increment](float delta) { gain(getGain() + delta * increment); }); } void cIntroLoopableBGM::resume() const { alSourcePlay( source ); } void cIntroLoopableBGM::gain( float const value ) const { alSourcef( source, AL_GAIN, value ); } float cIntroLoopableBGM::getGain() const { ALfloat value = 0.0F; alGetSourcef( source, AL_GAIN, &value ); return value; } void cIntroLoopableBGM::pitch( float const value ) const { alSourcef( source, AL_PITCH, value ); } bool cIntroLoopableBGM::isPlaying( ) const { ALint state; alGetSourcei( source, AL_SOURCE_STATE, &state ); return state == AL_PLAYING; } void cIntroLoopableBGM::update( float delta ) { if ( !introDeleted ) { if ( loopBeginSecond + 1.0F < time ) { alSourceUnqueueBuffers( source, 1, &introId ); auto e = alGetError( ); if ( e == AL_INVALID_VALUE ) { cinder::app::console( ) << "AL_INVALID_VALUE" << std::endl; } else if ( e == AL_INVALID_NAME ) { cinder::app::console( ) << "AL_INVALID_NAME" << std::endl; } else if ( e == AL_INVALID_OPERATION ) { cinder::app::console( ) << "AL_INVALID_OPERATION" << std::endl; } alSourcei( source, AL_LOOPING, AL_TRUE ); introDeleted = true; } } if ( isPlaying( ) ) time += delta; } size_t cIntroLoopableBGM::calcOffset( float second ) { size_t bit8_offset = second * 44100; size_t byte16_offset = bit8_offset * 2; size_t toStereo = 2; return byte16_offset * toStereo; } }
25.10274
172
0.687312
desspert
3cbf4c7b482bbf9aad85eed5762b795f1b257b79
2,020
cpp
C++
src/ui/Windows/TBMStatic.cpp
rafaelx/pwsafe
173a5c16ae2f9071efa67f628d21c30d4486effd
[ "Artistic-2.0" ]
null
null
null
src/ui/Windows/TBMStatic.cpp
rafaelx/pwsafe
173a5c16ae2f9071efa67f628d21c30d4486effd
[ "Artistic-2.0" ]
null
null
null
src/ui/Windows/TBMStatic.cpp
rafaelx/pwsafe
173a5c16ae2f9071efa67f628d21c30d4486effd
[ "Artistic-2.0" ]
null
null
null
/* * Copyright (c) 2003-2019 Rony Shapiro <ronys@pwsafe.org>. * All rights reserved. Use of the code is allowed under the * Artistic License 2.0 terms, as specified in the LICENSE file * distributed with this code, or available from * http://www.opensource.org/licenses/artistic-license-2.0.php */ // TBMStatic.cpp : implementation file // /* * Transparent Bitmap Static control */ #include "stdafx.h" #include "TBMStatic.h" #ifdef _DEBUG #undef THIS_FILE static char BASED_CODE THIS_FILE[] = __FILE__; #endif void CTBMStatic::Init(const UINT nImageID) { // Save resource IDs (Static and required image) m_nID = GetDlgCtrlID(); // Load bitmap VERIFY(m_Bitmap.Attach(::LoadImage( ::AfxFindResourceHandle(MAKEINTRESOURCE(nImageID), RT_BITMAP), MAKEINTRESOURCE(nImageID), IMAGE_BITMAP, 0, 0, (LR_DEFAULTSIZE | LR_CREATEDIBSECTION | LR_SHARED)))); const COLORREF crCOLOR_3DFACE = GetSysColor(COLOR_3DFACE); SetBitmapBackground(m_Bitmap, crCOLOR_3DFACE); SetBitmap((HBITMAP)m_Bitmap); } BEGIN_MESSAGE_MAP(CTBMStatic, CStatic) //{{AFX_MSG_MAP(CTBMStatic) //}}AFX_MSG_MAP END_MESSAGE_MAP() void CTBMStatic::SetBitmapBackground(CBitmap &bm, const COLORREF newbkgrndColour) { // Get how many pixels in the bitmap BITMAP bmInfo; bm.GetBitmap(&bmInfo); const UINT numPixels(bmInfo.bmHeight * bmInfo.bmWidth); // get a pointer to the pixels DIBSECTION ds; VERIFY(bm.GetObject(sizeof(DIBSECTION), &ds) == sizeof(DIBSECTION)); RGBTRIPLE *pixels = reinterpret_cast<RGBTRIPLE*>(ds.dsBm.bmBits); ASSERT(pixels != NULL); const RGBTRIPLE newbkgrndColourRGB = {GetBValue(newbkgrndColour), GetGValue(newbkgrndColour), GetRValue(newbkgrndColour)}; for (UINT i = 0; i < numPixels; ++i) { if (pixels[i].rgbtBlue == 192 && pixels[i].rgbtGreen == 192 && pixels[i].rgbtRed == 192) { pixels[i] = newbkgrndColourRGB; } } }
27.297297
81
0.676733
rafaelx
3cc475c5f1d5bdec62d26b69d397cbd2a528b9c2
76,727
cpp
C++
src/hpack.cpp
jonathonl/IPSuite
76dfd7913388851c6714645252b2caa3c5596dcc
[ "MIT" ]
1
2016-03-01T15:23:13.000Z
2016-03-01T15:23:13.000Z
src/hpack.cpp
jonathonl/IPSuite
76dfd7913388851c6714645252b2caa3c5596dcc
[ "MIT" ]
null
null
null
src/hpack.cpp
jonathonl/IPSuite
76dfd7913388851c6714645252b2caa3c5596dcc
[ "MIT" ]
null
null
null
#include <cmath> #include <assert.h> #include <iostream> #include "hpack.hpp" namespace std { template <> struct hash<std::pair<std::string,std::string>> { std::size_t operator()(const std::pair<std::string,std::string>& k) const { // Compute individual hash values for first, // second and third and combine them using XOR // and bit shifting: return ((std::hash<std::string>()(k.first) ^ (std::hash<std::string>()(k.second) << 1)) >> 1); } }; } namespace manifold { namespace hpack { //----------------------------------------------------------------// const std::array<std::pair<std::string,std::string>, 61> static_table{{ /* 1 */ {":authority" , "" }, /* 2 */ {":method" , "GET" }, /* 3 */ {":method" , "POST" }, /* 4 */ {":path" , "/" }, /* 5 */ {":path" , "/index.html" }, /* 6 */ {":scheme" , "http" }, /* 7 */ {":scheme" , "https" }, /* 8 */ {":status" , "200" }, /* 9 */ {":status" , "204" }, /* 10 */ {":status" , "206" }, /* 11 */ {":status" , "304" }, /* 12 */ {":status" , "400" }, /* 13 */ {":status" , "404" }, /* 14 */ {":status" , "500" }, /* 15 */ {"accept-charset" , "" }, /* 16 */ {"accept-encoding" , "gzip, deflate"}, /* 17 */ {"accept-language" , "" }, /* 18 */ {"accept-ranges" , "" }, /* 19 */ {"accept" , "" }, /* 20 */ {"access-control-allow-origin" , "" }, /* 21 */ {"age" , "" }, /* 22 */ {"allow" , "" }, /* 23 */ {"authorization" , "" }, /* 24 */ {"cache-control" , "" }, /* 25 */ {"content-disposition" , "" }, /* 26 */ {"content-encoding" , "" }, /* 27 */ {"content-language" , "" }, /* 28 */ {"content-length" , "" }, /* 29 */ {"content-location" , "" }, /* 30 */ {"content-range" , "" }, /* 31 */ {"content-type" , "" }, /* 32 */ {"cookie" , "" }, /* 33 */ {"date" , "" }, /* 34 */ {"etag" , "" }, /* 35 */ {"expect" , "" }, /* 36 */ {"expires" , "" }, /* 37 */ {"from" , "" }, /* 38 */ {"host" , "" }, /* 39 */ {"if-match" , "" }, /* 40 */ {"if-modified-since" , "" }, /* 41 */ {"if-none-match" , "" }, /* 42 */ {"if-range" , "" }, /* 43 */ {"if-unmodified-since" , "" }, /* 44 */ {"last-modified" , "" }, /* 45 */ {"link" , "" }, /* 46 */ {"location" , "" }, /* 47 */ {"max-forwards" , "" }, /* 48 */ {"proxy-authenticate" , "" }, /* 49 */ {"proxy-authorization" , "" }, /* 50 */ {"range" , "" }, /* 51 */ {"referer" , "" }, /* 52 */ {"refresh" , "" }, /* 53 */ {"retry-after" , "" }, /* 54 */ {"server" , "" }, /* 55 */ {"set-cookie" , "" }, /* 56 */ {"strict-transport-security" , "" }, /* 57 */ {"transfer-encoding" , "" }, /* 58 */ {"user-agent" , "" }, /* 59 */ {"vary" , "" }, /* 60 */ {"via" , "" }, /* 61 */ {"www-authenticate" , "" }}}; //----------------------------------------------------------------// //----------------------------------------------------------------// const std::unordered_multimap<std::string, std::size_t> static_table_reverse_lookup_map{ {":authority" , 1 }, // "" {":method" , 2 }, // "GET" {":method" , 3 }, // "POST" {":path" , 4 }, // "/" {":path" , 5 }, // "/index.html" {":scheme" , 6 }, // "http" {":scheme" , 7 }, // "https" {":status" , 8 }, // "200" {":status" , 9 }, // "204" {":status" , 10}, // "206" {":status" , 11}, // "304" {":status" , 12}, // "400" {":status" , 13}, // "404" {":status" , 14}, // "500" {"accept-charset" , 15}, // "" {"accept-encoding" , 16}, // "gzip, deflate" {"accept-language" , 17}, // "" {"accept-ranges" , 18}, // "" {"accept" , 19}, // "" {"access-control-allow-origin" , 20}, // "" {"age" , 21}, // "" {"allow" , 22}, // "" {"authorization" , 23}, // "" {"cache-control" , 24}, // "" {"content-disposition" , 25}, // "" {"content-encoding" , 26}, // "" {"content-language" , 27}, // "" {"content-length" , 28}, // "" {"content-location" , 29}, // "" {"content-range" , 30}, // "" {"content-type" , 31}, // "" {"cookie" , 32}, // "" {"date" , 33}, // "" {"etag" , 34}, // "" {"expect" , 35}, // "" {"expires" , 36}, // "" {"from" , 37}, // "" {"host" , 38}, // "" {"if-match" , 39}, // "" {"if-modified-since" , 40}, // "" {"if-none-match" , 41}, // "" {"if-range" , 42}, // "" {"if-unmodified-since" , 43}, // "" {"last-modified" , 44}, // "" {"link" , 45}, // "" {"location" , 46}, // "" {"max-forwards" , 47}, // "" {"proxy-authenticate" , 48}, // "" {"proxy-authorization" , 49}, // "" {"range" , 50}, // "" {"referer" , 51}, // "" {"refresh" , 52}, // "" {"retry-after" , 53}, // "" {"server" , 54}, // "" {"set-cookie" , 55}, // "" {"strict-transport-security" , 56}, // "" {"transfer-encoding" , 57}, // "" {"user-agent" , 58}, // "" {"vary" , 59}, // "" {"via" , 60}, // "" {"www-authenticate" , 61}}; // "" //----------------------------------------------------------------// //----------------------------------------------------------------// const std::map<huffman_code,char,huffman_code_cmp> huffman_code_tree{ /* ( 0) |11111111|11000 */ { { 0x1ff8 << (32 - 13), 13}, (char) 0 }, /* ( 1) |11111111|11111111|1011000 */ { { 0x7fffd8 << (32 - 23), 23}, (char) 1 }, /* ( 2) |11111111|11111111|11111110|0010 */ { { 0xfffffe2 << (32 - 28), 28}, (char) 2 }, /* ( 3) |11111111|11111111|11111110|0011 */ { { 0xfffffe3 << (32 - 28), 28}, (char) 3 }, /* ( 4) |11111111|11111111|11111110|0100 */ { { 0xfffffe4 << (32 - 28), 28}, (char) 4 }, /* ( 5) |11111111|11111111|11111110|0101 */ { { 0xfffffe5 << (32 - 28), 28}, (char) 5 }, /* ( 6) |11111111|11111111|11111110|0110 */ { { 0xfffffe6 << (32 - 28), 28}, (char) 6 }, /* ( 7) |11111111|11111111|11111110|0111 */ { { 0xfffffe7 << (32 - 28), 28}, (char) 7 }, /* ( 8) |11111111|11111111|11111110|1000 */ { { 0xfffffe8 << (32 - 28), 28}, (char) 8 }, /* ( 9) |11111111|11111111|11101010 */ { { 0xffffea << (32 - 24), 24}, (char) 9 }, /* ( 10) |11111111|11111111|11111111|111100 */ { { 0x3ffffffc << (32 - 30), 30}, (char) 10 }, /* ( 11) |11111111|11111111|11111110|1001 */ { { 0xfffffe9 << (32 - 28), 28}, (char) 11 }, /* ( 12) |11111111|11111111|11111110|1010 */ { { 0xfffffea << (32 - 28), 28}, (char) 12 }, /* ( 13) |11111111|11111111|11111111|111101 */ { { 0x3ffffffd << (32 - 30), 30}, (char) 13 }, /* ( 14) |11111111|11111111|11111110|1011 */ { { 0xfffffeb << (32 - 28), 28}, (char) 14 }, /* ( 15) |11111111|11111111|11111110|1100 */ { { 0xfffffec << (32 - 28), 28}, (char) 15 }, /* ( 16) |11111111|11111111|11111110|1101 */ { { 0xfffffed << (32 - 28), 28}, (char) 16 }, /* ( 17) |11111111|11111111|11111110|1110 */ { { 0xfffffee << (32 - 28), 28}, (char) 17 }, /* ( 18) |11111111|11111111|11111110|1111 */ { { 0xfffffef << (32 - 28), 28}, (char) 18 }, /* ( 19) |11111111|11111111|11111111|0000 */ { { 0xffffff0 << (32 - 28), 28}, (char) 19 }, /* ( 20) |11111111|11111111|11111111|0001 */ { { 0xffffff1 << (32 - 28), 28}, (char) 20 }, /* ( 21) |11111111|11111111|11111111|0010 */ { { 0xffffff2 << (32 - 28), 28}, (char) 21 }, /* ( 22) |11111111|11111111|11111111|111110 */ { { 0x3ffffffe << (32 - 30), 30}, (char) 22 }, /* ( 23) |11111111|11111111|11111111|0011 */ { { 0xffffff3 << (32 - 28), 28}, (char) 23 }, /* ( 24) |11111111|11111111|11111111|0100 */ { { 0xffffff4 << (32 - 28), 28}, (char) 24 }, /* ( 25) |11111111|11111111|11111111|0101 */ { { 0xffffff5 << (32 - 28), 28}, (char) 25 }, /* ( 26) |11111111|11111111|11111111|0110 */ { { 0xffffff6 << (32 - 28), 28}, (char) 26 }, /* ( 27) |11111111|11111111|11111111|0111 */ { { 0xffffff7 << (32 - 28), 28}, (char) 27 }, /* ( 28) |11111111|11111111|11111111|1000 */ { { 0xffffff8 << (32 - 28), 28}, (char) 28 }, /* ( 29) |11111111|11111111|11111111|1001 */ { { 0xffffff9 << (32 - 28), 28}, (char) 29 }, /* ( 30) |11111111|11111111|11111111|1010 */ { { 0xffffffa << (32 - 28), 28}, (char) 30 }, /* ( 31) |11111111|11111111|11111111|1011 */ { { 0xffffffb << (32 - 28), 28}, (char) 31 }, /* ' ' ( 32) |010100 */ { { 0x14 << (32 - 6), 6}, (char) 32 }, /* '!' ( 33) |11111110|00 */ { { 0x3f8 << (32 - 10), 10}, (char) 33 }, /* '"' ( 34) |11111110|01 */ { { 0x3f9 << (32 - 10), 10}, (char) 34 }, /* '#' ( 35) |11111111|1010 */ { { 0xffa << (32 - 12), 12}, (char) 35 }, /* '$' ( 36) |11111111|11001 */ { { 0x1ff9 << (32 - 13), 13}, (char) 36 }, /* '%' ( 37) |010101 */ { { 0x15 << (32 - 6), 6}, (char) 37 }, /* '&' ( 38) |11111000 */ { { 0xf8 << (32 - 8), 8}, (char) 38 }, /* ''' ( 39) |11111111|010 */ { { 0x7fa << (32 - 11), 11}, (char) 39 }, /* '(' ( 40) |11111110|10 */ { { 0x3fa << (32 - 10), 10}, (char) 40 }, /* ')' ( 41) |11111110|11 */ { { 0x3fb << (32 - 10), 10}, (char) 41 }, /* '*' ( 42) |11111001 */ { { 0xf9 << (32 - 8), 8}, (char) 42 }, /* '+' ( 43) |11111111|011 */ { { 0x7fb << (32 - 11), 11}, (char) 43 }, /* ',' ( 44) |11111010 */ { { 0xfa << (32 - 8), 8}, (char) 44 }, /* '-' ( 45) |010110 */ { { 0x16 << (32 - 6), 6}, (char) 45 }, /* '.' ( 46) |010111 */ { { 0x17 << (32 - 6), 6}, (char) 46 }, /* '/' ( 47) |011000 */ { { 0x18 << (32 - 6), 6}, (char) 47 }, /* '0' ( 48) |00000 */ { { 0x0 << (32 - 5), 5}, (char) 48 }, /* '1' ( 49) |00001 */ { { 0x1 << (32 - 5), 5}, (char) 49 }, /* '2' ( 50) |00010 */ { { 0x2 << (32 - 5), 5}, (char) 50 }, /* '3' ( 51) |011001 */ { { 0x19 << (32 - 6), 6}, (char) 51 }, /* '4' ( 52) |011010 */ { { 0x1a << (32 - 6), 6}, (char) 52 }, /* '5' ( 53) |011011 */ { { 0x1b << (32 - 6), 6}, (char) 53 }, /* '6' ( 54) |011100 */ { { 0x1c << (32 - 6), 6}, (char) 54 }, /* '7' ( 55) |011101 */ { { 0x1d << (32 - 6), 6}, (char) 55 }, /* '8' ( 56) |011110 */ { { 0x1e << (32 - 6), 6}, (char) 56 }, /* '9' ( 57) |011111 */ { { 0x1f << (32 - 6), 6}, (char) 57 }, /* ':' ( 58) |1011100 */ { { 0x5c << (32 - 7), 7}, (char) 58 }, /* ';' ( 59) |11111011 */ { { 0xfb << (32 - 8), 8}, (char) 59 }, /* '<' ( 60) |11111111|1111100 */ { { 0x7ffc << (32 - 15), 15}, (char) 60 }, /* '=' ( 61) |100000 */ { { 0x20 << (32 - 6), 6}, (char) 61 }, /* '>' ( 62) |11111111|1011 */ { { 0xffb << (32 - 12), 12}, (char) 62 }, /* '?' ( 63) |11111111|00 */ { { 0x3fc << (32 - 10), 10}, (char) 63 }, /* '@' ( 64) |11111111|11010 */ { { 0x1ffa << (32 - 13), 13}, (char) 64 }, /* 'A' ( 65) |100001 */ { { 0x21 << (32 - 6), 6}, (char) 65 }, /* 'B' ( 66) |1011101 */ { { 0x5d << (32 - 7), 7}, (char) 66 }, /* 'C' ( 67) |1011110 */ { { 0x5e << (32 - 7), 7}, (char) 67 }, /* 'D' ( 68) |1011111 */ { { 0x5f << (32 - 7), 7}, (char) 68 }, /* 'E' ( 69) |1100000 */ { { 0x60 << (32 - 7), 7}, (char) 69 }, /* 'F' ( 70) |1100001 */ { { 0x61 << (32 - 7), 7}, (char) 70 }, /* 'G' ( 71) |1100010 */ { { 0x62 << (32 - 7), 7}, (char) 71 }, /* 'H' ( 72) |1100011 */ { { 0x63 << (32 - 7), 7}, (char) 72 }, /* 'I' ( 73) |1100100 */ { { 0x64 << (32 - 7), 7}, (char) 73 }, /* 'J' ( 74) |1100101 */ { { 0x65 << (32 - 7), 7}, (char) 74 }, /* 'K' ( 75) |1100110 */ { { 0x66 << (32 - 7), 7}, (char) 75 }, /* 'L' ( 76) |1100111 */ { { 0x67 << (32 - 7), 7}, (char) 76 }, /* 'M' ( 77) |1101000 */ { { 0x68 << (32 - 7), 7}, (char) 77 }, /* 'N' ( 78) |1101001 */ { { 0x69 << (32 - 7), 7}, (char) 78 }, /* 'O' ( 79) |1101010 */ { { 0x6a << (32 - 7), 7}, (char) 79 }, /* 'P' ( 80) |1101011 */ { { 0x6b << (32 - 7), 7}, (char) 80 }, /* 'Q' ( 81) |1101100 */ { { 0x6c << (32 - 7), 7}, (char) 81 }, /* 'R' ( 82) |1101101 */ { { 0x6d << (32 - 7), 7}, (char) 82 }, /* 'S' ( 83) |1101110 */ { { 0x6e << (32 - 7), 7}, (char) 83 }, /* 'T' ( 84) |1101111 */ { { 0x6f << (32 - 7), 7}, (char) 84 }, /* 'U' ( 85) |1110000 */ { { 0x70 << (32 - 7), 7}, (char) 85 }, /* 'V' ( 86) |1110001 */ { { 0x71 << (32 - 7), 7}, (char) 86 }, /* 'W' ( 87) |1110010 */ { { 0x72 << (32 - 7), 7}, (char) 87 }, /* 'X' ( 88) |11111100 */ { { 0xfc << (32 - 8), 8}, (char) 88 }, /* 'Y' ( 89) |1110011 */ { { 0x73 << (32 - 7), 7}, (char) 89 }, /* 'Z' ( 90) |11111101 */ { { 0xfd << (32 - 8), 8}, (char) 90 }, /* '[' ( 91) |11111111|11011 */ { { 0x1ffb << (32 - 13), 13}, (char) 91 }, /* '\' ( 92) |11111111|11111110|000 */ { { 0x7fff0 << (32 - 19), 19}, (char) 92 }, /* ']' ( 93) |11111111|11100 */ { { 0x1ffc << (32 - 13), 13}, (char) 93 }, /* '^' ( 94) |11111111|111100 */ { { 0x3ffc << (32 - 14), 14}, (char) 94 }, /* '_' ( 95) |100010 */ { { 0x22 << (32 - 6), 6}, (char) 95 }, /* '`' ( 96) |11111111|1111101 */ { { 0x7ffd << (32 - 15), 15}, (char) 96 }, /* 'a' ( 97) |00011 */ { { 0x3 << (32 - 5), 5}, (char) 97 }, /* 'b' ( 98) |100011 */ { { 0x23 << (32 - 6), 6}, (char) 98 }, /* 'c' ( 99) |00100 */ { { 0x4 << (32 - 5), 5}, (char) 99 }, /* 'd' (100) |100100 */ { { 0x24 << (32 - 6), 6}, (char)100 }, /* 'e' (101) |00101 */ { { 0x5 << (32 - 5), 5}, (char)101 }, /* 'f' (102) |100101 */ { { 0x25 << (32 - 6), 6}, (char)102 }, /* 'g' (103) |100110 */ { { 0x26 << (32 - 6), 6}, (char)103 }, /* 'h' (104) |100111 */ { { 0x27 << (32 - 6), 6}, (char)104 }, /* 'i' (105) |00110 */ { { 0x6 << (32 - 5), 5}, (char)105 }, /* 'j' (106) |1110100 */ { { 0x74 << (32 - 7), 7}, (char)106 }, /* 'k' (107) |1110101 */ { { 0x75 << (32 - 7), 7}, (char)107 }, /* 'l' (108) |101000 */ { { 0x28 << (32 - 6), 6}, (char)108 }, /* 'm' (109) |101001 */ { { 0x29 << (32 - 6), 6}, (char)109 }, /* 'n' (110) |101010 */ { { 0x2a << (32 - 6), 6}, (char)110 }, /* 'o' (111) |00111 */ { { 0x7 << (32 - 5), 5}, (char)111 }, /* 'p' (112) |101011 */ { { 0x2b << (32 - 6), 6}, (char)112 }, /* 'q' (113) |1110110 */ { { 0x76 << (32 - 7), 7}, (char)113 }, /* 'r' (114) |101100 */ { { 0x2c << (32 - 6), 6}, (char)114 }, /* 's' (115) |01000 */ { { 0x8 << (32 - 5), 5}, (char)115 }, /* 't' (116) |01001 */ { { 0x9 << (32 - 5), 5}, (char)116 }, /* 'u' (117) |101101 */ { { 0x2d << (32 - 6), 6}, (char)117 }, /* 'v' (118) |1110111 */ { { 0x77 << (32 - 7), 7}, (char)118 }, /* 'w' (119) |1111000 */ { { 0x78 << (32 - 7), 7}, (char)119 }, /* 'x' (120) |1111001 */ { { 0x79 << (32 - 7), 7}, (char)120 }, /* 'y' (121) |1111010 */ { { 0x7a << (32 - 7), 7}, (char)121 }, /* 'z' (122) |1111011 */ { { 0x7b << (32 - 7), 7}, (char)122 }, /* '{' (123) |11111111|1111110 */ { { 0x7ffe << (32 - 15), 15}, (char)123 }, /* '|' (124) |11111111|100 */ { { 0x7fc << (32 - 11), 11}, (char)124 }, /* '}' (125) |11111111|111101 */ { { 0x3ffd << (32 - 14), 14}, (char)125 }, /* '~' (126) |11111111|11101 */ { { 0x1ffd << (32 - 13), 13}, (char)126 }, /* (127) |11111111|11111111|11111111|1100 */ { { 0xffffffc << (32 - 28), 28}, (char)127 }, /* (128) |11111111|11111110|0110 */ { { 0xfffe6 << (32 - 20), 20}, (char)128 }, /* (129) |11111111|11111111|010010 */ { { 0x3fffd2 << (32 - 22), 22}, (char)129 }, /* (130) |11111111|11111110|0111 */ { { 0xfffe7 << (32 - 20), 20}, (char)130 }, /* (131) |11111111|11111110|1000 */ { { 0xfffe8 << (32 - 20), 20}, (char)131 }, /* (132) |11111111|11111111|010011 */ { { 0x3fffd3 << (32 - 22), 22}, (char)132 }, /* (133) |11111111|11111111|010100 */ { { 0x3fffd4 << (32 - 22), 22}, (char)133 }, /* (134) |11111111|11111111|010101 */ { { 0x3fffd5 << (32 - 22), 22}, (char)134 }, /* (135) |11111111|11111111|1011001 */ { { 0x7fffd9 << (32 - 23), 23}, (char)135 }, /* (136) |11111111|11111111|010110 */ { { 0x3fffd6 << (32 - 22), 22}, (char)136 }, /* (137) |11111111|11111111|1011010 */ { { 0x7fffda << (32 - 23), 23}, (char)137 }, /* (138) |11111111|11111111|1011011 */ { { 0x7fffdb << (32 - 23), 23}, (char)138 }, /* (139) |11111111|11111111|1011100 */ { { 0x7fffdc << (32 - 23), 23}, (char)139 }, /* (140) |11111111|11111111|1011101 */ { { 0x7fffdd << (32 - 23), 23}, (char)140 }, /* (141) |11111111|11111111|1011110 */ { { 0x7fffde << (32 - 23), 23}, (char)141 }, /* (142) |11111111|11111111|11101011 */ { { 0xffffeb << (32 - 24), 24}, (char)142 }, /* (143) |11111111|11111111|1011111 */ { { 0x7fffdf << (32 - 23), 23}, (char)143 }, /* (144) |11111111|11111111|11101100 */ { { 0xffffec << (32 - 24), 24}, (char)144 }, /* (145) |11111111|11111111|11101101 */ { { 0xffffed << (32 - 24), 24}, (char)145 }, /* (146) |11111111|11111111|010111 */ { { 0x3fffd7 << (32 - 22), 22}, (char)146 }, /* (147) |11111111|11111111|1100000 */ { { 0x7fffe0 << (32 - 23), 23}, (char)147 }, /* (148) |11111111|11111111|11101110 */ { { 0xffffee << (32 - 24), 24}, (char)148 }, /* (149) |11111111|11111111|1100001 */ { { 0x7fffe1 << (32 - 23), 23}, (char)149 }, /* (150) |11111111|11111111|1100010 */ { { 0x7fffe2 << (32 - 23), 23}, (char)150 }, /* (151) |11111111|11111111|1100011 */ { { 0x7fffe3 << (32 - 23), 23}, (char)151 }, /* (152) |11111111|11111111|1100100 */ { { 0x7fffe4 << (32 - 23), 23}, (char)152 }, /* (153) |11111111|11111110|11100 */ { { 0x1fffdc << (32 - 21), 21}, (char)153 }, /* (154) |11111111|11111111|011000 */ { { 0x3fffd8 << (32 - 22), 22}, (char)154 }, /* (155) |11111111|11111111|1100101 */ { { 0x7fffe5 << (32 - 23), 23}, (char)155 }, /* (156) |11111111|11111111|011001 */ { { 0x3fffd9 << (32 - 22), 22}, (char)156 }, /* (157) |11111111|11111111|1100110 */ { { 0x7fffe6 << (32 - 23), 23}, (char)157 }, /* (158) |11111111|11111111|1100111 */ { { 0x7fffe7 << (32 - 23), 23}, (char)158 }, /* (159) |11111111|11111111|11101111 */ { { 0xffffef << (32 - 24), 24}, (char)159 }, /* (160) |11111111|11111111|011010 */ { { 0x3fffda << (32 - 22), 22}, (char)160 }, /* (161) |11111111|11111110|11101 */ { { 0x1fffdd << (32 - 21), 21}, (char)161 }, /* (162) |11111111|11111110|1001 */ { { 0xfffe9 << (32 - 20), 20}, (char)162 }, /* (163) |11111111|11111111|011011 */ { { 0x3fffdb << (32 - 22), 22}, (char)163 }, /* (164) |11111111|11111111|011100 */ { { 0x3fffdc << (32 - 22), 22}, (char)164 }, /* (165) |11111111|11111111|1101000 */ { { 0x7fffe8 << (32 - 23), 23}, (char)165 }, /* (166) |11111111|11111111|1101001 */ { { 0x7fffe9 << (32 - 23), 23}, (char)166 }, /* (167) |11111111|11111110|11110 */ { { 0x1fffde << (32 - 21), 21}, (char)167 }, /* (168) |11111111|11111111|1101010 */ { { 0x7fffea << (32 - 23), 23}, (char)168 }, /* (169) |11111111|11111111|011101 */ { { 0x3fffdd << (32 - 22), 22}, (char)169 }, /* (170) |11111111|11111111|011110 */ { { 0x3fffde << (32 - 22), 22}, (char)170 }, /* (171) |11111111|11111111|11110000 */ { { 0xfffff0 << (32 - 24), 24}, (char)171 }, /* (172) |11111111|11111110|11111 */ { { 0x1fffdf << (32 - 21), 21}, (char)172 }, /* (173) |11111111|11111111|011111 */ { { 0x3fffdf << (32 - 22), 22}, (char)173 }, /* (174) |11111111|11111111|1101011 */ { { 0x7fffeb << (32 - 23), 23}, (char)174 }, /* (175) |11111111|11111111|1101100 */ { { 0x7fffec << (32 - 23), 23}, (char)175 }, /* (176) |11111111|11111111|00000 */ { { 0x1fffe0 << (32 - 21), 21}, (char)176 }, /* (177) |11111111|11111111|00001 */ { { 0x1fffe1 << (32 - 21), 21}, (char)177 }, /* (178) |11111111|11111111|100000 */ { { 0x3fffe0 << (32 - 22), 22}, (char)178 }, /* (179) |11111111|11111111|00010 */ { { 0x1fffe2 << (32 - 21), 21}, (char)179 }, /* (180) |11111111|11111111|1101101 */ { { 0x7fffed << (32 - 23), 23}, (char)180 }, /* (181) |11111111|11111111|100001 */ { { 0x3fffe1 << (32 - 22), 22}, (char)181 }, /* (182) |11111111|11111111|1101110 */ { { 0x7fffee << (32 - 23), 23}, (char)182 }, /* (183) |11111111|11111111|1101111 */ { { 0x7fffef << (32 - 23), 23}, (char)183 }, /* (184) |11111111|11111110|1010 */ { { 0xfffea << (32 - 20), 20}, (char)184 }, /* (185) |11111111|11111111|100010 */ { { 0x3fffe2 << (32 - 22), 22}, (char)185 }, /* (186) |11111111|11111111|100011 */ { { 0x3fffe3 << (32 - 22), 22}, (char)186 }, /* (187) |11111111|11111111|100100 */ { { 0x3fffe4 << (32 - 22), 22}, (char)187 }, /* (188) |11111111|11111111|1110000 */ { { 0x7ffff0 << (32 - 23), 23}, (char)188 }, /* (189) |11111111|11111111|100101 */ { { 0x3fffe5 << (32 - 22), 22}, (char)189 }, /* (190) |11111111|11111111|100110 */ { { 0x3fffe6 << (32 - 22), 22}, (char)190 }, /* (191) |11111111|11111111|1110001 */ { { 0x7ffff1 << (32 - 23), 23}, (char)191 }, /* (192) |11111111|11111111|11111000|00 */ { { 0x3ffffe0 << (32 - 26), 26}, (char)192 }, /* (193) |11111111|11111111|11111000|01 */ { { 0x3ffffe1 << (32 - 26), 26}, (char)193 }, /* (194) |11111111|11111110|1011 */ { { 0xfffeb << (32 - 20), 20}, (char)194 }, /* (195) |11111111|11111110|001 */ { { 0x7fff1 << (32 - 19), 19}, (char)195 }, /* (196) |11111111|11111111|100111 */ { { 0x3fffe7 << (32 - 22), 22}, (char)196 }, /* (197) |11111111|11111111|1110010 */ { { 0x7ffff2 << (32 - 23), 23}, (char)197 }, /* (198) |11111111|11111111|101000 */ { { 0x3fffe8 << (32 - 22), 22}, (char)198 }, /* (199) |11111111|11111111|11110110|0 */ { { 0x1ffffec << (32 - 25), 25}, (char)199 }, /* (200) |11111111|11111111|11111000|10 */ { { 0x3ffffe2 << (32 - 26), 26}, (char)200 }, /* (201) |11111111|11111111|11111000|11 */ { { 0x3ffffe3 << (32 - 26), 26}, (char)201 }, /* (202) |11111111|11111111|11111001|00 */ { { 0x3ffffe4 << (32 - 26), 26}, (char)202 }, /* (203) |11111111|11111111|11111011|110 */ { { 0x7ffffde << (32 - 27), 27}, (char)203 }, /* (204) |11111111|11111111|11111011|111 */ { { 0x7ffffdf << (32 - 27), 27}, (char)204 }, /* (205) |11111111|11111111|11111001|01 */ { { 0x3ffffe5 << (32 - 26), 26}, (char)205 }, /* (206) |11111111|11111111|11110001 */ { { 0xfffff1 << (32 - 24), 24}, (char)206 }, /* (207) |11111111|11111111|11110110|1 */ { { 0x1ffffed << (32 - 25), 25}, (char)207 }, /* (208) |11111111|11111110|010 */ { { 0x7fff2 << (32 - 19), 19}, (char)208 }, /* (209) |11111111|11111111|00011 */ { { 0x1fffe3 << (32 - 21), 21}, (char)209 }, /* (210) |11111111|11111111|11111001|10 */ { { 0x3ffffe6 << (32 - 26), 26}, (char)210 }, /* (211) |11111111|11111111|11111100|000 */ { { 0x7ffffe0 << (32 - 27), 27}, (char)211 }, /* (212) |11111111|11111111|11111100|001 */ { { 0x7ffffe1 << (32 - 27), 27}, (char)212 }, /* (213) |11111111|11111111|11111001|11 */ { { 0x3ffffe7 << (32 - 26), 26}, (char)213 }, /* (214) |11111111|11111111|11111100|010 */ { { 0x7ffffe2 << (32 - 27), 27}, (char)214 }, /* (215) |11111111|11111111|11110010 */ { { 0xfffff2 << (32 - 24), 24}, (char)215 }, /* (216) |11111111|11111111|00100 */ { { 0x1fffe4 << (32 - 21), 21}, (char)216 }, /* (217) |11111111|11111111|00101 */ { { 0x1fffe5 << (32 - 21), 21}, (char)217 }, /* (218) |11111111|11111111|11111010|00 */ { { 0x3ffffe8 << (32 - 26), 26}, (char)218 }, /* (219) |11111111|11111111|11111010|01 */ { { 0x3ffffe9 << (32 - 26), 26}, (char)219 }, /* (220) |11111111|11111111|11111111|1101 */ { { 0xffffffd << (32 - 28), 28}, (char)220 }, /* (221) |11111111|11111111|11111100|011 */ { { 0x7ffffe3 << (32 - 27), 27}, (char)221 }, /* (222) |11111111|11111111|11111100|100 */ { { 0x7ffffe4 << (32 - 27), 27}, (char)222 }, /* (223) |11111111|11111111|11111100|101 */ { { 0x7ffffe5 << (32 - 27), 27}, (char)223 }, /* (224) |11111111|11111110|1100 */ { { 0xfffec << (32 - 20), 20}, (char)224 }, /* (225) |11111111|11111111|11110011 */ { { 0xfffff3 << (32 - 24), 24}, (char)225 }, /* (226) |11111111|11111110|1101 */ { { 0xfffed << (32 - 20), 20}, (char)226 }, /* (227) |11111111|11111111|00110 */ { { 0x1fffe6 << (32 - 21), 21}, (char)227 }, /* (228) |11111111|11111111|101001 */ { { 0x3fffe9 << (32 - 22), 22}, (char)228 }, /* (229) |11111111|11111111|00111 */ { { 0x1fffe7 << (32 - 21), 21}, (char)229 }, /* (230) |11111111|11111111|01000 */ { { 0x1fffe8 << (32 - 21), 21}, (char)230 }, /* (231) |11111111|11111111|1110011 */ { { 0x7ffff3 << (32 - 23), 23}, (char)231 }, /* (232) |11111111|11111111|101010 */ { { 0x3fffea << (32 - 22), 22}, (char)232 }, /* (233) |11111111|11111111|101011 */ { { 0x3fffeb << (32 - 22), 22}, (char)233 }, /* (234) |11111111|11111111|11110111|0 */ { { 0x1ffffee << (32 - 25), 25}, (char)234 }, /* (235) |11111111|11111111|11110111|1 */ { { 0x1ffffef << (32 - 25), 25}, (char)235 }, /* (236) |11111111|11111111|11110100 */ { { 0xfffff4 << (32 - 24), 24}, (char)236 }, /* (237) |11111111|11111111|11110101 */ { { 0xfffff5 << (32 - 24), 24}, (char)237 }, /* (238) |11111111|11111111|11111010|10 */ { { 0x3ffffea << (32 - 26), 26}, (char)238 }, /* (239) |11111111|11111111|1110100 */ { { 0x7ffff4 << (32 - 23), 23}, (char)239 }, /* (240) |11111111|11111111|11111010|11 */ { { 0x3ffffeb << (32 - 26), 26}, (char)240 }, /* (241) |11111111|11111111|11111100|110 */ { { 0x7ffffe6 << (32 - 27), 27}, (char)241 }, /* (242) |11111111|11111111|11111011|00 */ { { 0x3ffffec << (32 - 26), 26}, (char)242 }, /* (243) |11111111|11111111|11111011|01 */ { { 0x3ffffed << (32 - 26), 26}, (char)243 }, /* (244) |11111111|11111111|11111100|111 */ { { 0x7ffffe7 << (32 - 27), 27}, (char)244 }, /* (245) |11111111|11111111|11111101|000 */ { { 0x7ffffe8 << (32 - 27), 27}, (char)245 }, /* (246) |11111111|11111111|11111101|001 */ { { 0x7ffffe9 << (32 - 27), 27}, (char)246 }, /* (247) |11111111|11111111|11111101|010 */ { { 0x7ffffea << (32 - 27), 27}, (char)247 }, /* (248) |11111111|11111111|11111101|011 */ { { 0x7ffffeb << (32 - 27), 27}, (char)248 }, /* (249) |11111111|11111111|11111111|1110 */ { { 0xffffffe << (32 - 28), 28}, (char)249 }, /* (250) |11111111|11111111|11111101|100 */ { { 0x7ffffec << (32 - 27), 27}, (char)250 }, /* (251) |11111111|11111111|11111101|101 */ { { 0x7ffffed << (32 - 27), 27}, (char)251 }, /* (252) |11111111|11111111|11111101|110 */ { { 0x7ffffee << (32 - 27), 27}, (char)252 }, /* (253) |11111111|11111111|11111101|111 */ { { 0x7ffffef << (32 - 27), 27}, (char)253 }, /* (254) |11111111|11111111|11111110|000 */ { { 0x7fffff0 << (32 - 27), 27}, (char)254 }, /* (255) |11111111|11111111|11111011|10 */ { { 0x3ffffee << (32 - 26), 26}, (char)255 }}; //----------------------------------------------------------------// //----------------------------------------------------------------// const huffman_tree huffman_code_tree2{ /* ( 0) |11111111|11000 */ { { 0x1ff8u << (32 - 13), 13}, (char) 0 }, /* ( 1) |11111111|11111111|1011000 */ { { 0x7fffd8u << (32 - 23), 23}, (char) 1 }, /* ( 2) |11111111|11111111|11111110|0010 */ { { 0xfffffe2u << (32 - 28), 28}, (char) 2 }, /* ( 3) |11111111|11111111|11111110|0011 */ { { 0xfffffe3u << (32 - 28), 28}, (char) 3 }, /* ( 4) |11111111|11111111|11111110|0100 */ { { 0xfffffe4u << (32 - 28), 28}, (char) 4 }, /* ( 5) |11111111|11111111|11111110|0101 */ { { 0xfffffe5u << (32 - 28), 28}, (char) 5 }, /* ( 6) |11111111|11111111|11111110|0110 */ { { 0xfffffe6u << (32 - 28), 28}, (char) 6 }, /* ( 7) |11111111|11111111|11111110|0111 */ { { 0xfffffe7u << (32 - 28), 28}, (char) 7 }, /* ( 8) |11111111|11111111|11111110|1000 */ { { 0xfffffe8u << (32 - 28), 28}, (char) 8 }, /* ( 9) |11111111|11111111|11101010 */ { { 0xffffeau << (32 - 24), 24}, (char) 9 }, /* ( 10) |11111111|11111111|11111111|111100 */ { { 0x3ffffffcu << (32 - 30), 30}, (char) 10 }, /* ( 11) |11111111|11111111|11111110|1001 */ { { 0xfffffe9u << (32 - 28), 28}, (char) 11 }, /* ( 12) |11111111|11111111|11111110|1010 */ { { 0xfffffeau << (32 - 28), 28}, (char) 12 }, /* ( 13) |11111111|11111111|11111111|111101 */ { { 0x3ffffffdu << (32 - 30), 30}, (char) 13 }, /* ( 14) |11111111|11111111|11111110|1011 */ { { 0xfffffebu << (32 - 28), 28}, (char) 14 }, /* ( 15) |11111111|11111111|11111110|1100 */ { { 0xfffffecu << (32 - 28), 28}, (char) 15 }, /* ( 16) |11111111|11111111|11111110|1101 */ { { 0xfffffedu << (32 - 28), 28}, (char) 16 }, /* ( 17) |11111111|11111111|11111110|1110 */ { { 0xfffffeeu << (32 - 28), 28}, (char) 17 }, /* ( 18) |11111111|11111111|11111110|1111 */ { { 0xfffffefu << (32 - 28), 28}, (char) 18 }, /* ( 19) |11111111|11111111|11111111|0000 */ { { 0xffffff0u << (32 - 28), 28}, (char) 19 }, /* ( 20) |11111111|11111111|11111111|0001 */ { { 0xffffff1u << (32 - 28), 28}, (char) 20 }, /* ( 21) |11111111|11111111|11111111|0010 */ { { 0xffffff2u << (32 - 28), 28}, (char) 21 }, /* ( 22) |11111111|11111111|11111111|111110 */ { { 0x3ffffffeu << (32 - 30), 30}, (char) 22 }, /* ( 23) |11111111|11111111|11111111|0011 */ { { 0xffffff3u << (32 - 28), 28}, (char) 23 }, /* ( 24) |11111111|11111111|11111111|0100 */ { { 0xffffff4u << (32 - 28), 28}, (char) 24 }, /* ( 25) |11111111|11111111|11111111|0101 */ { { 0xffffff5u << (32 - 28), 28}, (char) 25 }, /* ( 26) |11111111|11111111|11111111|0110 */ { { 0xffffff6u << (32 - 28), 28}, (char) 26 }, /* ( 27) |11111111|11111111|11111111|0111 */ { { 0xffffff7u << (32 - 28), 28}, (char) 27 }, /* ( 28) |11111111|11111111|11111111|1000 */ { { 0xffffff8u << (32 - 28), 28}, (char) 28 }, /* ( 29) |11111111|11111111|11111111|1001 */ { { 0xffffff9u << (32 - 28), 28}, (char) 29 }, /* ( 30) |11111111|11111111|11111111|1010 */ { { 0xffffffau << (32 - 28), 28}, (char) 30 }, /* ( 31) |11111111|11111111|11111111|1011 */ { { 0xffffffbu << (32 - 28), 28}, (char) 31 }, /* ' ' ( 32) |010100 */ { { 0x14u << (32 - 6), 6}, (char) 32 }, /* '!' ( 33) |11111110|00 */ { { 0x3f8u << (32 - 10), 10}, (char) 33 }, /* '"' ( 34) |11111110|01 */ { { 0x3f9u << (32 - 10), 10}, (char) 34 }, /* '#' ( 35) |11111111|1010 */ { { 0xffau << (32 - 12), 12}, (char) 35 }, /* '$' ( 36) |11111111|11001 */ { { 0x1ff9u << (32 - 13), 13}, (char) 36 }, /* '%' ( 37) |010101 */ { { 0x15u << (32 - 6), 6}, (char) 37 }, /* '&' ( 38) |11111000 */ { { 0xf8u << (32 - 8), 8}, (char) 38 }, /* ''' ( 39) |11111111|010 */ { { 0x7fau << (32 - 11), 11}, (char) 39 }, /* '(' ( 40) |11111110|10 */ { { 0x3fau << (32 - 10), 10}, (char) 40 }, /* ')' ( 41) |11111110|11 */ { { 0x3fbu << (32 - 10), 10}, (char) 41 }, /* '*' ( 42) |11111001 */ { { 0xf9u << (32 - 8), 8}, (char) 42 }, /* '+' ( 43) |11111111|011 */ { { 0x7fbu << (32 - 11), 11}, (char) 43 }, /* ',' ( 44) |11111010 */ { { 0xfau << (32 - 8), 8}, (char) 44 }, /* '-' ( 45) |010110 */ { { 0x16u << (32 - 6), 6}, (char) 45 }, /* '.' ( 46) |010111 */ { { 0x17u << (32 - 6), 6}, (char) 46 }, /* '/' ( 47) |011000 */ { { 0x18u << (32 - 6), 6}, (char) 47 }, /* '0' ( 48) |00000 */ { { 0x0u << (32 - 5), 5}, (char) 48 }, /* '1' ( 49) |00001 */ { { 0x1u << (32 - 5), 5}, (char) 49 }, /* '2' ( 50) |00010 */ { { 0x2u << (32 - 5), 5}, (char) 50 }, /* '3' ( 51) |011001 */ { { 0x19u << (32 - 6), 6}, (char) 51 }, /* '4' ( 52) |011010 */ { { 0x1au << (32 - 6), 6}, (char) 52 }, /* '5' ( 53) |011011 */ { { 0x1bu << (32 - 6), 6}, (char) 53 }, /* '6' ( 54) |011100 */ { { 0x1cu << (32 - 6), 6}, (char) 54 }, /* '7' ( 55) |011101 */ { { 0x1du << (32 - 6), 6}, (char) 55 }, /* '8' ( 56) |011110 */ { { 0x1eu << (32 - 6), 6}, (char) 56 }, /* '9' ( 57) |011111 */ { { 0x1fu << (32 - 6), 6}, (char) 57 }, /* ':' ( 58) |1011100 */ { { 0x5cu << (32 - 7), 7}, (char) 58 }, /* ';' ( 59) |11111011 */ { { 0xfbu << (32 - 8), 8}, (char) 59 }, /* '<' ( 60) |11111111|1111100 */ { { 0x7ffcu << (32 - 15), 15}, (char) 60 }, /* '=' ( 61) |100000 */ { { 0x20u << (32 - 6), 6}, (char) 61 }, /* '>' ( 62) |11111111|1011 */ { { 0xffbu << (32 - 12), 12}, (char) 62 }, /* '?' ( 63) |11111111|00 */ { { 0x3fcu << (32 - 10), 10}, (char) 63 }, /* '@' ( 64) |11111111|11010 */ { { 0x1ffau << (32 - 13), 13}, (char) 64 }, /* 'A' ( 65) |100001 */ { { 0x21u << (32 - 6), 6}, (char) 65 }, /* 'B' ( 66) |1011101 */ { { 0x5du << (32 - 7), 7}, (char) 66 }, /* 'C' ( 67) |1011110 */ { { 0x5eu << (32 - 7), 7}, (char) 67 }, /* 'D' ( 68) |1011111 */ { { 0x5fu << (32 - 7), 7}, (char) 68 }, /* 'E' ( 69) |1100000 */ { { 0x60u << (32 - 7), 7}, (char) 69 }, /* 'F' ( 70) |1100001 */ { { 0x61u << (32 - 7), 7}, (char) 70 }, /* 'G' ( 71) |1100010 */ { { 0x62u << (32 - 7), 7}, (char) 71 }, /* 'H' ( 72) |1100011 */ { { 0x63u << (32 - 7), 7}, (char) 72 }, /* 'I' ( 73) |1100100 */ { { 0x64u << (32 - 7), 7}, (char) 73 }, /* 'J' ( 74) |1100101 */ { { 0x65u << (32 - 7), 7}, (char) 74 }, /* 'K' ( 75) |1100110 */ { { 0x66u << (32 - 7), 7}, (char) 75 }, /* 'L' ( 76) |1100111 */ { { 0x67u << (32 - 7), 7}, (char) 76 }, /* 'M' ( 77) |1101000 */ { { 0x68u << (32 - 7), 7}, (char) 77 }, /* 'N' ( 78) |1101001 */ { { 0x69u << (32 - 7), 7}, (char) 78 }, /* 'O' ( 79) |1101010 */ { { 0x6au << (32 - 7), 7}, (char) 79 }, /* 'P' ( 80) |1101011 */ { { 0x6bu << (32 - 7), 7}, (char) 80 }, /* 'Q' ( 81) |1101100 */ { { 0x6cu << (32 - 7), 7}, (char) 81 }, /* 'R' ( 82) |1101101 */ { { 0x6du << (32 - 7), 7}, (char) 82 }, /* 'S' ( 83) |1101110 */ { { 0x6eu << (32 - 7), 7}, (char) 83 }, /* 'T' ( 84) |1101111 */ { { 0x6fu << (32 - 7), 7}, (char) 84 }, /* 'U' ( 85) |1110000 */ { { 0x70u << (32 - 7), 7}, (char) 85 }, /* 'V' ( 86) |1110001 */ { { 0x71u << (32 - 7), 7}, (char) 86 }, /* 'W' ( 87) |1110010 */ { { 0x72u << (32 - 7), 7}, (char) 87 }, /* 'X' ( 88) |11111100 */ { { 0xfcu << (32 - 8), 8}, (char) 88 }, /* 'Y' ( 89) |1110011 */ { { 0x73u << (32 - 7), 7}, (char) 89 }, /* 'Z' ( 90) |11111101 */ { { 0xfdu << (32 - 8), 8}, (char) 90 }, /* '[' ( 91) |11111111|11011 */ { { 0x1ffbu << (32 - 13), 13}, (char) 91 }, /* '\' ( 92) |11111111|11111110|000 */ { { 0x7fff0u << (32 - 19), 19}, (char) 92 }, /* ']' ( 93) |11111111|11100 */ { { 0x1ffcu << (32 - 13), 13}, (char) 93 }, /* '^' ( 94) |11111111|111100 */ { { 0x3ffcu << (32 - 14), 14}, (char) 94 }, /* '_' ( 95) |100010 */ { { 0x22u << (32 - 6), 6}, (char) 95 }, /* '`' ( 96) |11111111|1111101 */ { { 0x7ffdu << (32 - 15), 15}, (char) 96 }, /* 'a' ( 97) |00011 */ { { 0x3u << (32 - 5), 5}, (char) 97 }, /* 'b' ( 98) |100011 */ { { 0x23u << (32 - 6), 6}, (char) 98 }, /* 'c' ( 99) |00100 */ { { 0x4u << (32 - 5), 5}, (char) 99 }, /* 'd' (100) |100100 */ { { 0x24u << (32 - 6), 6}, (char)100 }, /* 'e' (101) |00101 */ { { 0x5u << (32 - 5), 5}, (char)101 }, /* 'f' (102) |100101 */ { { 0x25u << (32 - 6), 6}, (char)102 }, /* 'g' (103) |100110 */ { { 0x26u << (32 - 6), 6}, (char)103 }, /* 'h' (104) |100111 */ { { 0x27u << (32 - 6), 6}, (char)104 }, /* 'i' (105) |00110 */ { { 0x6u << (32 - 5), 5}, (char)105 }, /* 'j' (106) |1110100 */ { { 0x74u << (32 - 7), 7}, (char)106 }, /* 'k' (107) |1110101 */ { { 0x75u << (32 - 7), 7}, (char)107 }, /* 'l' (108) |101000 */ { { 0x28u << (32 - 6), 6}, (char)108 }, /* 'm' (109) |101001 */ { { 0x29u << (32 - 6), 6}, (char)109 }, /* 'n' (110) |101010 */ { { 0x2au << (32 - 6), 6}, (char)110 }, /* 'o' (111) |00111 */ { { 0x7u << (32 - 5), 5}, (char)111 }, /* 'p' (112) |101011 */ { { 0x2bu << (32 - 6), 6}, (char)112 }, /* 'q' (113) |1110110 */ { { 0x76u << (32 - 7), 7}, (char)113 }, /* 'r' (114) |101100 */ { { 0x2cu << (32 - 6), 6}, (char)114 }, /* 's' (115) |01000 */ { { 0x8u << (32 - 5), 5}, (char)115 }, /* 't' (116) |01001 */ { { 0x9u << (32 - 5), 5}, (char)116 }, /* 'u' (117) |101101 */ { { 0x2du << (32 - 6), 6}, (char)117 }, /* 'v' (118) |1110111 */ { { 0x77u << (32 - 7), 7}, (char)118 }, /* 'w' (119) |1111000 */ { { 0x78u << (32 - 7), 7}, (char)119 }, /* 'x' (120) |1111001 */ { { 0x79u << (32 - 7), 7}, (char)120 }, /* 'y' (121) |1111010 */ { { 0x7au << (32 - 7), 7}, (char)121 }, /* 'z' (122) |1111011 */ { { 0x7bu << (32 - 7), 7}, (char)122 }, /* '{' (123) |11111111|1111110 */ { { 0x7ffeu << (32 - 15), 15}, (char)123 }, /* '|' (124) |11111111|100 */ { { 0x7fcu << (32 - 11), 11}, (char)124 }, /* '}' (125) |11111111|111101 */ { { 0x3ffdu << (32 - 14), 14}, (char)125 }, /* '~' (126) |11111111|11101 */ { { 0x1ffdu << (32 - 13), 13}, (char)126 }, /* (127) |11111111|11111111|11111111|1100 */ { { 0xffffffcu << (32 - 28), 28}, (char)127 }, /* (128) |11111111|11111110|0110 */ { { 0xfffe6u << (32 - 20), 20}, (char)128 }, /* (129) |11111111|11111111|010010 */ { { 0x3fffd2u << (32 - 22), 22}, (char)129 }, /* (130) |11111111|11111110|0111 */ { { 0xfffe7u << (32 - 20), 20}, (char)130 }, /* (131) |11111111|11111110|1000 */ { { 0xfffe8u << (32 - 20), 20}, (char)131 }, /* (132) |11111111|11111111|010011 */ { { 0x3fffd3u << (32 - 22), 22}, (char)132 }, /* (133) |11111111|11111111|010100 */ { { 0x3fffd4u << (32 - 22), 22}, (char)133 }, /* (134) |11111111|11111111|010101 */ { { 0x3fffd5u << (32 - 22), 22}, (char)134 }, /* (135) |11111111|11111111|1011001 */ { { 0x7fffd9u << (32 - 23), 23}, (char)135 }, /* (136) |11111111|11111111|010110 */ { { 0x3fffd6u << (32 - 22), 22}, (char)136 }, /* (137) |11111111|11111111|1011010 */ { { 0x7fffdau << (32 - 23), 23}, (char)137 }, /* (138) |11111111|11111111|1011011 */ { { 0x7fffdbu << (32 - 23), 23}, (char)138 }, /* (139) |11111111|11111111|1011100 */ { { 0x7fffdcu << (32 - 23), 23}, (char)139 }, /* (140) |11111111|11111111|1011101 */ { { 0x7fffddu << (32 - 23), 23}, (char)140 }, /* (141) |11111111|11111111|1011110 */ { { 0x7fffdeu << (32 - 23), 23}, (char)141 }, /* (142) |11111111|11111111|11101011 */ { { 0xffffebu << (32 - 24), 24}, (char)142 }, /* (143) |11111111|11111111|1011111 */ { { 0x7fffdfu << (32 - 23), 23}, (char)143 }, /* (144) |11111111|11111111|11101100 */ { { 0xffffecu << (32 - 24), 24}, (char)144 }, /* (145) |11111111|11111111|11101101 */ { { 0xffffedu << (32 - 24), 24}, (char)145 }, /* (146) |11111111|11111111|010111 */ { { 0x3fffd7u << (32 - 22), 22}, (char)146 }, /* (147) |11111111|11111111|1100000 */ { { 0x7fffe0u << (32 - 23), 23}, (char)147 }, /* (148) |11111111|11111111|11101110 */ { { 0xffffeeu << (32 - 24), 24}, (char)148 }, /* (149) |11111111|11111111|1100001 */ { { 0x7fffe1u << (32 - 23), 23}, (char)149 }, /* (150) |11111111|11111111|1100010 */ { { 0x7fffe2u << (32 - 23), 23}, (char)150 }, /* (151) |11111111|11111111|1100011 */ { { 0x7fffe3u << (32 - 23), 23}, (char)151 }, /* (152) |11111111|11111111|1100100 */ { { 0x7fffe4u << (32 - 23), 23}, (char)152 }, /* (153) |11111111|11111110|11100 */ { { 0x1fffdcu << (32 - 21), 21}, (char)153 }, /* (154) |11111111|11111111|011000 */ { { 0x3fffd8u << (32 - 22), 22}, (char)154 }, /* (155) |11111111|11111111|1100101 */ { { 0x7fffe5u << (32 - 23), 23}, (char)155 }, /* (156) |11111111|11111111|011001 */ { { 0x3fffd9u << (32 - 22), 22}, (char)156 }, /* (157) |11111111|11111111|1100110 */ { { 0x7fffe6u << (32 - 23), 23}, (char)157 }, /* (158) |11111111|11111111|1100111 */ { { 0x7fffe7u << (32 - 23), 23}, (char)158 }, /* (159) |11111111|11111111|11101111 */ { { 0xffffefu << (32 - 24), 24}, (char)159 }, /* (160) |11111111|11111111|011010 */ { { 0x3fffdau << (32 - 22), 22}, (char)160 }, /* (161) |11111111|11111110|11101 */ { { 0x1fffddu << (32 - 21), 21}, (char)161 }, /* (162) |11111111|11111110|1001 */ { { 0xfffe9u << (32 - 20), 20}, (char)162 }, /* (163) |11111111|11111111|011011 */ { { 0x3fffdbu << (32 - 22), 22}, (char)163 }, /* (164) |11111111|11111111|011100 */ { { 0x3fffdcu << (32 - 22), 22}, (char)164 }, /* (165) |11111111|11111111|1101000 */ { { 0x7fffe8u << (32 - 23), 23}, (char)165 }, /* (166) |11111111|11111111|1101001 */ { { 0x7fffe9u << (32 - 23), 23}, (char)166 }, /* (167) |11111111|11111110|11110 */ { { 0x1fffdeu << (32 - 21), 21}, (char)167 }, /* (168) |11111111|11111111|1101010 */ { { 0x7fffeau << (32 - 23), 23}, (char)168 }, /* (169) |11111111|11111111|011101 */ { { 0x3fffddu << (32 - 22), 22}, (char)169 }, /* (170) |11111111|11111111|011110 */ { { 0x3fffdeu << (32 - 22), 22}, (char)170 }, /* (171) |11111111|11111111|11110000 */ { { 0xfffff0u << (32 - 24), 24}, (char)171 }, /* (172) |11111111|11111110|11111 */ { { 0x1fffdfu << (32 - 21), 21}, (char)172 }, /* (173) |11111111|11111111|011111 */ { { 0x3fffdfu << (32 - 22), 22}, (char)173 }, /* (174) |11111111|11111111|1101011 */ { { 0x7fffebu << (32 - 23), 23}, (char)174 }, /* (175) |11111111|11111111|1101100 */ { { 0x7fffecu << (32 - 23), 23}, (char)175 }, /* (176) |11111111|11111111|00000 */ { { 0x1fffe0u << (32 - 21), 21}, (char)176 }, /* (177) |11111111|11111111|00001 */ { { 0x1fffe1u << (32 - 21), 21}, (char)177 }, /* (178) |11111111|11111111|100000 */ { { 0x3fffe0u << (32 - 22), 22}, (char)178 }, /* (179) |11111111|11111111|00010 */ { { 0x1fffe2u << (32 - 21), 21}, (char)179 }, /* (180) |11111111|11111111|1101101 */ { { 0x7fffedu << (32 - 23), 23}, (char)180 }, /* (181) |11111111|11111111|100001 */ { { 0x3fffe1u << (32 - 22), 22}, (char)181 }, /* (182) |11111111|11111111|1101110 */ { { 0x7fffeeu << (32 - 23), 23}, (char)182 }, /* (183) |11111111|11111111|1101111 */ { { 0x7fffefu << (32 - 23), 23}, (char)183 }, /* (184) |11111111|11111110|1010 */ { { 0xfffeau << (32 - 20), 20}, (char)184 }, /* (185) |11111111|11111111|100010 */ { { 0x3fffe2u << (32 - 22), 22}, (char)185 }, /* (186) |11111111|11111111|100011 */ { { 0x3fffe3u << (32 - 22), 22}, (char)186 }, /* (187) |11111111|11111111|100100 */ { { 0x3fffe4u << (32 - 22), 22}, (char)187 }, /* (188) |11111111|11111111|1110000 */ { { 0x7ffff0u << (32 - 23), 23}, (char)188 }, /* (189) |11111111|11111111|100101 */ { { 0x3fffe5u << (32 - 22), 22}, (char)189 }, /* (190) |11111111|11111111|100110 */ { { 0x3fffe6u << (32 - 22), 22}, (char)190 }, /* (191) |11111111|11111111|1110001 */ { { 0x7ffff1u << (32 - 23), 23}, (char)191 }, /* (192) |11111111|11111111|11111000|00 */ { { 0x3ffffe0u << (32 - 26), 26}, (char)192 }, /* (193) |11111111|11111111|11111000|01 */ { { 0x3ffffe1u << (32 - 26), 26}, (char)193 }, /* (194) |11111111|11111110|1011 */ { { 0xfffebu << (32 - 20), 20}, (char)194 }, /* (195) |11111111|11111110|001 */ { { 0x7fff1u << (32 - 19), 19}, (char)195 }, /* (196) |11111111|11111111|100111 */ { { 0x3fffe7u << (32 - 22), 22}, (char)196 }, /* (197) |11111111|11111111|1110010 */ { { 0x7ffff2u << (32 - 23), 23}, (char)197 }, /* (198) |11111111|11111111|101000 */ { { 0x3fffe8u << (32 - 22), 22}, (char)198 }, /* (199) |11111111|11111111|11110110|0 */ { { 0x1ffffecu << (32 - 25), 25}, (char)199 }, /* (200) |11111111|11111111|11111000|10 */ { { 0x3ffffe2u << (32 - 26), 26}, (char)200 }, /* (201) |11111111|11111111|11111000|11 */ { { 0x3ffffe3u << (32 - 26), 26}, (char)201 }, /* (202) |11111111|11111111|11111001|00 */ { { 0x3ffffe4u << (32 - 26), 26}, (char)202 }, /* (203) |11111111|11111111|11111011|110 */ { { 0x7ffffdeu << (32 - 27), 27}, (char)203 }, /* (204) |11111111|11111111|11111011|111 */ { { 0x7ffffdfu << (32 - 27), 27}, (char)204 }, /* (205) |11111111|11111111|11111001|01 */ { { 0x3ffffe5u << (32 - 26), 26}, (char)205 }, /* (206) |11111111|11111111|11110001 */ { { 0xfffff1u << (32 - 24), 24}, (char)206 }, /* (207) |11111111|11111111|11110110|1 */ { { 0x1ffffedu << (32 - 25), 25}, (char)207 }, /* (208) |11111111|11111110|010 */ { { 0x7fff2u << (32 - 19), 19}, (char)208 }, /* (209) |11111111|11111111|00011 */ { { 0x1fffe3u << (32 - 21), 21}, (char)209 }, /* (210) |11111111|11111111|11111001|10 */ { { 0x3ffffe6u << (32 - 26), 26}, (char)210 }, /* (211) |11111111|11111111|11111100|000 */ { { 0x7ffffe0u << (32 - 27), 27}, (char)211 }, /* (212) |11111111|11111111|11111100|001 */ { { 0x7ffffe1u << (32 - 27), 27}, (char)212 }, /* (213) |11111111|11111111|11111001|11 */ { { 0x3ffffe7u << (32 - 26), 26}, (char)213 }, /* (214) |11111111|11111111|11111100|010 */ { { 0x7ffffe2u << (32 - 27), 27}, (char)214 }, /* (215) |11111111|11111111|11110010 */ { { 0xfffff2u << (32 - 24), 24}, (char)215 }, /* (216) |11111111|11111111|00100 */ { { 0x1fffe4u << (32 - 21), 21}, (char)216 }, /* (217) |11111111|11111111|00101 */ { { 0x1fffe5u << (32 - 21), 21}, (char)217 }, /* (218) |11111111|11111111|11111010|00 */ { { 0x3ffffe8u << (32 - 26), 26}, (char)218 }, /* (219) |11111111|11111111|11111010|01 */ { { 0x3ffffe9u << (32 - 26), 26}, (char)219 }, /* (220) |11111111|11111111|11111111|1101 */ { { 0xffffffdu << (32 - 28), 28}, (char)220 }, /* (221) |11111111|11111111|11111100|011 */ { { 0x7ffffe3u << (32 - 27), 27}, (char)221 }, /* (222) |11111111|11111111|11111100|100 */ { { 0x7ffffe4u << (32 - 27), 27}, (char)222 }, /* (223) |11111111|11111111|11111100|101 */ { { 0x7ffffe5u << (32 - 27), 27}, (char)223 }, /* (224) |11111111|11111110|1100 */ { { 0xfffecu << (32 - 20), 20}, (char)224 }, /* (225) |11111111|11111111|11110011 */ { { 0xfffff3u << (32 - 24), 24}, (char)225 }, /* (226) |11111111|11111110|1101 */ { { 0xfffedu << (32 - 20), 20}, (char)226 }, /* (227) |11111111|11111111|00110 */ { { 0x1fffe6u << (32 - 21), 21}, (char)227 }, /* (228) |11111111|11111111|101001 */ { { 0x3fffe9u << (32 - 22), 22}, (char)228 }, /* (229) |11111111|11111111|00111 */ { { 0x1fffe7u << (32 - 21), 21}, (char)229 }, /* (230) |11111111|11111111|01000 */ { { 0x1fffe8u << (32 - 21), 21}, (char)230 }, /* (231) |11111111|11111111|1110011 */ { { 0x7ffff3u << (32 - 23), 23}, (char)231 }, /* (232) |11111111|11111111|101010 */ { { 0x3fffeau << (32 - 22), 22}, (char)232 }, /* (233) |11111111|11111111|101011 */ { { 0x3fffebu << (32 - 22), 22}, (char)233 }, /* (234) |11111111|11111111|11110111|0 */ { { 0x1ffffeeu << (32 - 25), 25}, (char)234 }, /* (235) |11111111|11111111|11110111|1 */ { { 0x1ffffefu << (32 - 25), 25}, (char)235 }, /* (236) |11111111|11111111|11110100 */ { { 0xfffff4u << (32 - 24), 24}, (char)236 }, /* (237) |11111111|11111111|11110101 */ { { 0xfffff5u << (32 - 24), 24}, (char)237 }, /* (238) |11111111|11111111|11111010|10 */ { { 0x3ffffeau << (32 - 26), 26}, (char)238 }, /* (239) |11111111|11111111|1110100 */ { { 0x7ffff4u << (32 - 23), 23}, (char)239 }, /* (240) |11111111|11111111|11111010|11 */ { { 0x3ffffebu << (32 - 26), 26}, (char)240 }, /* (241) |11111111|11111111|11111100|110 */ { { 0x7ffffe6u << (32 - 27), 27}, (char)241 }, /* (242) |11111111|11111111|11111011|00 */ { { 0x3ffffecu << (32 - 26), 26}, (char)242 }, /* (243) |11111111|11111111|11111011|01 */ { { 0x3ffffedu << (32 - 26), 26}, (char)243 }, /* (244) |11111111|11111111|11111100|111 */ { { 0x7ffffe7u << (32 - 27), 27}, (char)244 }, /* (245) |11111111|11111111|11111101|000 */ { { 0x7ffffe8u << (32 - 27), 27}, (char)245 }, /* (246) |11111111|11111111|11111101|001 */ { { 0x7ffffe9u << (32 - 27), 27}, (char)246 }, /* (247) |11111111|11111111|11111101|010 */ { { 0x7ffffeau << (32 - 27), 27}, (char)247 }, /* (248) |11111111|11111111|11111101|011 */ { { 0x7ffffebu << (32 - 27), 27}, (char)248 }, /* (249) |11111111|11111111|11111111|1110 */ { { 0xffffffeu << (32 - 28), 28}, (char)249 }, /* (250) |11111111|11111111|11111101|100 */ { { 0x7ffffecu << (32 - 27), 27}, (char)250 }, /* (251) |11111111|11111111|11111101|101 */ { { 0x7ffffedu << (32 - 27), 27}, (char)251 }, /* (252) |11111111|11111111|11111101|110 */ { { 0x7ffffeeu << (32 - 27), 27}, (char)252 }, /* (253) |11111111|11111111|11111101|111 */ { { 0x7ffffefu << (32 - 27), 27}, (char)253 }, /* (254) |11111111|11111111|11111110|000 */ { { 0x7fffff0u << (32 - 27), 27}, (char)254 }, /* (255) |11111111|11111111|11111011|10 */ { { 0x3ffffeeu << (32 - 26), 26}, (char)255 }}; //----------------------------------------------------------------// //----------------------------------------------------------------// void context::table_evict() { this->current_dynamic_table_size_ -= (32 + this->dynamic_table_.back().first.size() + this->dynamic_table_.back().second.size()); this->dynamic_table_.pop_back(); assert(this->dynamic_table_.size() > 0 || this->current_dynamic_table_size_ == 0); } //----------------------------------------------------------------// //----------------------------------------------------------------// void context::table_insert(const std::pair<std::string,std::string>& entry) { this->table_insert(std::pair<std::string,std::string>(entry)); } //----------------------------------------------------------------// //----------------------------------------------------------------// void context::table_insert(std::pair<std::string,std::string>&& entry) { std::size_t entry_size = 32 + entry.first.size() + entry.second.size(); while ((entry_size + this->current_dynamic_table_size_) > this->max_dynamic_table_size_ && this->dynamic_table_.size() != 0) this->table_evict(); // Entrys that are larger than max table size leave the table empty. if ((entry_size + this->current_dynamic_table_size_) <= this->max_dynamic_table_size_) { this->current_dynamic_table_size_ += entry_size; this->dynamic_table_.push_front(std::move(entry)); } } //----------------------------------------------------------------// //----------------------------------------------------------------// void encoder::encode_integer(prefix_mask prfx_mask, std::uint64_t input, std::string& output) { if (input < (std::uint8_t)prfx_mask) { output.back() |= ((std::uint8_t)prfx_mask & (std::uint8_t)input); } else { output.back() |= (std::uint8_t)prfx_mask; input = input - (std::uint8_t)prfx_mask; while (input >= 128) { output.push_back((std::uint8_t)(input % 128 + 128)); input = input / 128; } output.push_back((std::uint8_t)input); } } //----------------------------------------------------------------// //----------------------------------------------------------------// void encoder::huffman_encode(std::string::const_iterator begin, std::string::const_iterator end, std::string& output) { // std::uint8_t bits_avail_in_current_byte = 0; // // for ( std::size_t current_index = output.size(); begin != end; ++begin) // { // std::size_t ascii_code = (std::size_t)*begin; // std::pair<std::uint32_t, std::uint8_t> huff_code_pair = huffman_code_array[ascii_code]; // std::uint32_t msb_alligned = huff_code_pair.first << (32 - huff_code_pair.second); // std::size_t new_bytes_required = (huff_code_pair.second > bits_avail_in_current_byte ? (std::size_t)std::ceil(static_cast<float>(huff_code_pair.second - bits_avail_in_current_byte) / 8.0 ) : 0); // output.append(new_bytes_required, (char)0x0); // // for (std::size_t i = 0; i + current_index < output.size(); ++i) // { // output[i] = output[i] | ((msb_alligned >> ((8 * (3 - i)) + (8 - bits_avail_in_current_byte))) & 0xFF); // std::cout << std::hex << (output[i + current_index] & 0xFF) << std::dec << std::endl; // } // // if (new_bytes_required) // bits_avail_in_current_byte = (std::uint8_t)((huff_code_pair.second - bits_avail_in_current_byte) % 8); // else // bits_avail_in_current_byte -= huff_code_pair.second; // // current_index = (bits_avail_in_current_byte == 0 ? output.size() : output.size() -1); // } // // if (bits_avail_in_current_byte != 0) // { // output.back() = output.back() | (char)(0xFF >> (8 - bits_avail_in_current_byte)); // } } //----------------------------------------------------------------// //----------------------------------------------------------------// encoder::find_result encoder::find(const header_field& header_to_find) { find_result ret; auto static_table_find_range = static_table_reverse_lookup_map.equal_range(header_to_find.name); if (static_table_find_range.first != static_table_find_range.second) { ret.name_index = static_table_find_range.first->second; for( auto it = static_table_find_range.first; ret.name_and_value_index == 0 && it != static_table_find_range.second; ++it) { if (header_to_find.value == this->at(it->second).second) { ret.name_and_value_index = it->second; } } } if (ret.name_and_value_index == 0) { std::size_t current_index = static_table.size() + 1; for (auto it = this->dynamic_table_.begin(); ret.name_and_value_index == 0 && it != this->dynamic_table_.end(); ++it,++current_index) { if (it->first == header_to_find.name) { if (ret.name_index == 0) { ret.name_index = current_index; } if (it->second == header_to_find.value) { ret.name_and_value_index = current_index; } } } } return ret; }; //----------------------------------------------------------------// //----------------------------------------------------------------// void encoder::encode(const std::list<header_field>& headers, std::string& output) { // TODO: Estimate output size and reserve contiguous array in output container. while (this->table_size_updates_.size()) { output.push_back((char)0x20); this->max_dynamic_table_size_ = this->table_size_updates_.front(); encode_integer(prefix_mask::five_bit, this->max_dynamic_table_size_, output); while (this->current_dynamic_table_size_ > this->max_dynamic_table_size_) this->table_evict(); this->table_size_updates_.pop(); } for (std::list<header_field>::const_iterator header_itr= headers.begin(); header_itr != headers.end(); ++header_itr) { find_result res = this->find(*header_itr); if (res.name_and_value_index) { output.push_back((char)0x80); encode_integer(prefix_mask::seven_bit, res.name_and_value_index, output); } else { prefix_mask pfx_mask; if (header_itr->cache == cacheability::yes) { pfx_mask = prefix_mask::six_bit; output.push_back((char)0x40); this->table_insert(std::pair<std::string,std::string>(header_itr->name, header_itr->value)); } else if (header_itr->cache == cacheability::never) { pfx_mask = prefix_mask::four_bit; output.push_back((char)0); } else { pfx_mask = prefix_mask::four_bit; output.push_back((char)0x10); } if (res.name_index) { encode_integer(pfx_mask, res.name_index, output); } else { output.push_back((char)0x0); // no huffman. encode_integer(prefix_mask::seven_bit, header_itr->name.size(), output); output += header_itr->name; } output.push_back((char)0x0); // no huffman. encode_integer(prefix_mask::seven_bit, header_itr->value.size(), output); output += header_itr->value; } } } //----------------------------------------------------------------// //----------------------------------------------------------------// // TODO: Decide whether to deal with pos greather than input size. std::uint64_t decoder::decode_integer(prefix_mask prfx_mask, std::string::const_iterator& itr) { auto a = (std::uint8_t)*itr; std::uint64_t ret = (std::uint8_t)prfx_mask & *itr; if (ret == (std::uint8_t)prfx_mask) { std::uint64_t m = 0; do { ++itr; ret = ret + ((*itr & 127) * (std::uint64_t)std::pow(2,m)); m = m + 7; } while ((*itr & 128) == 128); } ++itr; return ret; } //----------------------------------------------------------------// //----------------------------------------------------------------// bool decoder::decode_string_literal(std::string::const_iterator& itr, std::string& output) { bool ret = true; bool huffman_encoded = (*itr & 0x80) != 0; std::size_t name_sz = decode_integer(prefix_mask::seven_bit, itr); if (huffman_encoded) { std::string tmp(itr, itr + name_sz); itr += name_sz; if (tmp.size() != name_sz) ret = false; else huffman_decode(tmp.begin(), tmp.end(), output); } else { output.assign(itr, itr + name_sz); itr += name_sz; if (output.size() != name_sz) ret = false; } return ret; } //----------------------------------------------------------------// //----------------------------------------------------------------// bool decoder::decode_nvp(std::size_t table_index, cacheability cache_header, std::string::const_iterator& itr, std::list<header_field>& headers) { bool ret = true; std::string n; std::string v; if (table_index) { if (table_index <= this->header_list_length()) n = this->at(table_index).first; else ret = false; } else { ret = this->decode_string_literal(itr, n); } if (ret) { ret = this->decode_string_literal(itr, v); if (ret) { if (cache_header == cacheability::yes) this->table_insert(std::pair<std::string,std::string>(n, v)); headers.emplace_back(std::move(n), std::move(v), cache_header); } } return ret; } //----------------------------------------------------------------// //----------------------------------------------------------------// void decoder::huffman_decode(std::string::const_iterator begin, std::string::const_iterator end, std::string& output) { std::uint8_t bit_pos = 7; while (begin != end) { char next; if (hpack::huffman_code_tree2.lookup(begin, end, bit_pos, next)) output.push_back(next); else break; } } //----------------------------------------------------------------// //----------------------------------------------------------------// bool decoder::decode(std::string::const_iterator itr, std::string::const_iterator end, std::list<header_field>& headers) { bool ret = true; while (ret && itr != end) { if (*itr & 0x80) { // Indexed Header Field Representation // std::uint64_t table_index = decode_integer(prefix_mask::seven_bit, itr); if (table_index && table_index <= this->header_list_length()) { const std::pair<std::string,std::string>& p = this->at(table_index); headers.emplace_back(p.first, p.second); } else ret = false; } else if ((*itr & 0xC0) == 0x40) { // Literal Header Field with Incremental Indexing // std::uint64_t table_index = decode_integer(prefix_mask::six_bit, itr); ret = this->decode_nvp(table_index, cacheability::yes, itr, headers); } else if ((*itr & 0xF0) == 0x0) { // Literal Header Field without Indexing // std::uint64_t table_index = decode_integer(prefix_mask::four_bit, itr); ret = this->decode_nvp(table_index, cacheability::no, itr, headers); } else if ((*itr & 0xF0) == 0x10) { // Literal Header Field never Indexed // std::uint64_t table_index = decode_integer(prefix_mask::four_bit, itr); ret = this->decode_nvp(table_index, cacheability::never, itr, headers); } else if ((*itr & 0xE0) == 0x20) { // Dynamic Table Size Update // std::uint64_t new_max_size = decode_integer(prefix_mask::five_bit, itr); this->max_dynamic_table_size_ = new_max_size; while (this->current_dynamic_table_size_ > this->max_dynamic_table_size_) this->table_evict(); } else { ret = false; } } return ret; } //----------------------------------------------------------------// }; }
74.132367
204
0.37855
jonathonl
3cc56bf3287b00c9261fbea80a9f7b9177dab509
10,096
cpp
C++
source/deepnetvideo/source/deepnetvideo.cpp
hyphaproject/hyphaplugins
b41b396392c5546e3c2802bfc34213c5da04fdf4
[ "MIT" ]
null
null
null
source/deepnetvideo/source/deepnetvideo.cpp
hyphaproject/hyphaplugins
b41b396392c5546e3c2802bfc34213c5da04fdf4
[ "MIT" ]
1
2017-02-18T10:51:07.000Z
2017-02-18T10:51:07.000Z
source/deepnetvideo/source/deepnetvideo.cpp
hyphaproject/hyphaplugins
b41b396392c5546e3c2802bfc34213c5da04fdf4
[ "MIT" ]
null
null
null
// Copyright (c) 2015-2016 Hypha #include "hyphaplugins/deepnetvideo/deepnetvideo.h" #include <cmath> #include <cstdlib> #include <exception> #include <fstream> #include <iostream> #include <sstream> #include <stdexcept> #include <thread> #include <vector> #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <boost/property_tree/json_parser.hpp> #include <boost/property_tree/ptree.hpp> #include <dlib/opencv.h> #include <opencv2/core/core.hpp> #include <opencv2/highgui.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/opencv.hpp> #include <Poco/ClassLibrary.h> #include <Poco/DateTime.h> #include <Poco/DateTimeFormatter.h> #include <Poco/LocalDateTime.h> #include <Poco/Timezone.h> #include <hypha/plugin/hyphaplugin.h> #include <hypha/utils/logger.h> using namespace hypha::utils; using namespace hypha::plugin; using namespace hypha::plugin::deepnetvideo; using namespace cv; using namespace cv::dnn; using namespace std; DeepNetVideo::~DeepNetVideo() {} /* Find best class for the blob (i. e. class with maximal probability) */ void getMaxClass(dnn::Blob &probBlob, int *classId, double *classProb) { Mat probMat = probBlob.matRefConst().reshape( 1, 1); // reshape the blob to 1x1000 matrix Point classNumber; minMaxLoc(probMat, NULL, classProb, NULL, &classNumber); *classId = classNumber.x; } std::vector<String> readClassNames(const char *filename = "synset_words.txt") { std::vector<String> classNames; std::ifstream fp(filename); if (!fp.is_open()) { std::cerr << "File with classes labels not found: " << filename << std::endl; throw std::runtime_error("File with classes labels not found"); } std::string name; while (!fp.eof()) { std::getline(fp, name); if (name.length()) classNames.push_back(name.substr(name.find(' ') + 1)); } fp.close(); return classNames; } void DeepNetVideo::doWork() { std::this_thread::sleep_for(std::chrono::seconds(1) / fps); try { std::thread captureT = std::thread([this] { captureCamera(); }); if (captureT.joinable()) captureT.join(); currentImage_mutex.lock(); currentImage = captureMat; currentImage_mutex.unlock(); } catch (cv::Exception &e) { Logger::error(e.what()); } catch (std::exception e) { Logger::error(e.what()); } catch (...) { Logger::error("Something terrible happened."); } std::vector<std::string> classes = classify(); Logger::info("current class: "); for (std::string className : classes) Logger::info(className); // sendMessage(className); } void DeepNetVideo::captureCamera() { if (getFilmState() == FILM) { if (filmCounter++ >= 100) setFilmState(IDLE); if (capture_mutex.try_lock()) { try { cv::Mat capt; if (capture.isOpened()) { // read five times to clear buffered old images capture.read(capt); capture.read(capt); capture.read(capt); capture.read(capt); capture.read(capt); } if (captureMat_mutex.try_lock()) { captureMat = capt.clone(); captureMat_mutex.unlock(); } capture_mutex.unlock(); } catch (cv::Exception &e) { Logger::error("Could not capture from camera"); Logger::error(e.what()); } catch (std::exception &e) { Logger::warning("Could not capture from camera"); } } } } cv::Mat DeepNetVideo::rotateMat(cv::Mat mat) { if (mat.rows < 1) return mat; cv::Point2f src_center(mat.cols / 2.0F, mat.rows / 2.0F); cv::Mat rot_mat = cv::getRotationMatrix2D(src_center, 180, 1.0); cv::warpAffine(mat, mat, rot_mat, mat.size()); return mat; } cv::Mat DeepNetVideo::fillMat(cv::Mat mat) { if (mat.rows != height) cv::vconcat(mat, cv::Mat(height - mat.rows, mat.cols, mat.type()), mat); if (mat.cols != width) cv::hconcat(mat, cv::Mat(mat.rows, width - mat.cols, mat.type()), mat); return mat; } void DeepNetVideo::setup() { if (!device.empty()) { capture.open(std::stoi(device)); capture.set(CV_CAP_PROP_FRAME_WIDTH, width); capture.set(CV_CAP_PROP_FRAME_HEIGHT, height); capture.set(CV_CAP_PROP_FPS, fps); captureMat = cv::Mat(height, width, CV_8UC3); } filmCounter = 0; filmState = FILM; loadNet(); } std::string DeepNetVideo::communicate(std::string UNUSED(message)) { return "SUCCESS"; } void DeepNetVideo::loadConfig(std::string json) { boost::property_tree::ptree pt; std::stringstream ss(json); boost::property_tree::read_json(ss, pt); if (pt.get_optional<int>("fps")) { fps = pt.get<int>("fps"); } if (pt.get_optional<int>("width")) { width = pt.get<int>("width"); } if (pt.get_optional<int>("height")) { height = pt.get<int>("height"); } if (pt.get_optional<std::string>("device")) { device = pt.get<std::string>("device"); } if (pt.get_optional<std::string>("modelTxt")) { modelTxt = pt.get<std::string>("modelTxt"); } if (pt.get_optional<std::string>("modelBin")) { modelBin = pt.get<std::string>("modelBin"); } if (pt.get_optional<std::string>("classNamesFile")) { classNamesFile = pt.get<std::string>("classNamesFile"); } } std::string DeepNetVideo::getConfig() { return "{}"; } HyphaPlugin *DeepNetVideo::getInstance(std::string id) { DeepNetVideo *instance = new DeepNetVideo(); instance->setId(id); return instance; } void DeepNetVideo::receiveMessage(std::string message) { try { boost::property_tree::ptree pt; std::stringstream ss(message); boost::property_tree::read_json(ss, pt); if (pt.get_optional<bool>("run")) { if (pt.get<bool>("run")) { setState(FILM); } else { setState(IDLE); } } } catch (std::exception &e) { Logger::error(e.what()); } } void DeepNetVideo::loadNet() { deserialize(this->modelBin) >> net >> labels; snet.subnet() = net.subnet(); } // ---------------------------------------------------------------------------------------- dlib::rectangle make_random_cropping_rect_resnet(const matrix<rgb_pixel> &img, dlib::rand &rnd) { // figure out what rectangle we want to crop from the image double mins = 0.466666666, maxs = 0.875; auto scale = mins + rnd.get_random_double() * (maxs - mins); auto size = scale * std::min(img.nr(), img.nc()); dlib::rectangle rect(size, size); // randomly shift the box around point offset(rnd.get_random_32bit_number() % (img.nc() - rect.width()), rnd.get_random_32bit_number() % (img.nr() - rect.height())); return move_rect(rect, offset); } // ---------------------------------------------------------------------------------------- void randomly_crop_images(const matrix<rgb_pixel> &img, dlib::array<matrix<rgb_pixel>> &crops, dlib::rand &rnd, long num_crops) { std::vector<chip_details> dets; for (long i = 0; i < num_crops; ++i) { auto rect = make_random_cropping_rect_resnet(img, rnd); dets.push_back(chip_details(rect, chip_dims(227, 227))); } extract_image_chips(img, dets, crops); for (auto &&img : crops) { // Also randomly flip the image if (rnd.get_random_double() > 0.5) img = fliplr(img); // And then randomly adjust the colors. apply_random_color_offset(img, rnd); } } dlib::matrix<rgb_pixel> MatToMatrix(cv::Mat mat) { dlib::matrix<rgb_pixel> result(mat.rows, mat.cols); rgb_pixel *p; for (int i = 0; i < mat.rows; i++) { p = mat.ptr<rgb_pixel>(i); for (int j = 0; j < mat.cols; j++) { result(i, j) = p[j]; } } return result; } // ---------------------------------------------------------------------------------------- std::vector<std::string> DeepNetVideo::classify() { std::vector<std::string> tags; Mat cvimg = getCurrentImage(); if (cvimg.empty()) { std::cerr << "can't get image" << std::endl; throw std::runtime_error("can't get image"); } // cv_image<bgr_pixel> cimg(img); dlib::array<matrix<rgb_pixel>> images; matrix<rgb_pixel> mimg, crop; cv::cvtColor(cvimg, cvimg, CV_BGR2RGB); mimg = MatToMatrix(cvimg); const int num_crops = 8; // Grab 16 random crops from the image. We will run all of them through the // network and average the results. randomly_crop_images(mimg, images, rnd, num_crops); // p(i) == the probability the image contains object of class i. matrix<float, 1, 1000> p = sum_rows(dlib::mat(snet(images.begin(), images.end()))) / num_crops; win.set_image(mimg); // Print the 5 most probable labels for (int k = 0; k < 1; ++k) { unsigned long predicted_label = index_of_max(p); cout << p(predicted_label) << ": " << labels[predicted_label] << endl; p(predicted_label) = 0; } return tags; } cv::Mat DeepNetVideo::getCurrentImage() { setFilmState(FILM); cv::Mat frame; currentImage_mutex.lock(); frame = currentImage.clone(); currentImage_mutex.unlock(); return frame; } DeepNetVideo::State DeepNetVideo::getState() { State state = IDLE; state_mutex.lock(); state = currentState; state_mutex.unlock(); return state; } void DeepNetVideo::setState(State state) { state_mutex.lock(); currentState = state; state_mutex.unlock(); } DeepNetVideo::State DeepNetVideo::getFilmState() { State state = IDLE; state_mutex.lock(); state = filmState; state_mutex.unlock(); return state; } void DeepNetVideo::setFilmState(State state) { state_mutex.lock(); if (filmState == IDLE && state == FILM) { filmState = FILM; if (!device.empty()) { capture.open(std::stoi(device)); capture.set(CV_CAP_PROP_FRAME_WIDTH, width); capture.set(CV_CAP_PROP_FRAME_HEIGHT, height); capture.set(CV_CAP_PROP_FPS, fps); cameras++; } } else if (filmState == FILM && state == IDLE) { filmState = IDLE; if (!device.empty()) { capture.release(); } cameras = 0; } state_mutex.unlock(); } POCO_BEGIN_MANIFEST(HyphaPlugin) POCO_EXPORT_CLASS(DeepNetVideo) POCO_END_MANIFEST
28.280112
91
0.630349
hyphaproject
3cc5e04a4bf2135ad3f0d4602ff3053dd7b68376
3,533
cpp
C++
FallingSandSurvival/IngameUI.cpp
PieKing1215/FallingSandSurvival
04e11940b5bd6bc867e880d7dd656ab32035a241
[ "BSD-3-Clause" ]
70
2020-06-06T16:13:41.000Z
2022-03-24T15:49:09.000Z
FallingSandSurvival/IngameUI.cpp
PieKing1215/FallingEverythingSurvival
e2c8a0761794c9603591a5670d08c07c7ffb3b90
[ "BSD-3-Clause" ]
13
2020-05-06T23:05:41.000Z
2022-02-21T19:47:09.000Z
FallingSandSurvival/IngameUI.cpp
PieKing1215/FallingEverythingSurvival
e2c8a0761794c9603591a5670d08c07c7ffb3b90
[ "BSD-3-Clause" ]
19
2020-09-04T02:18:16.000Z
2022-03-24T22:19:11.000Z
#include "UIs.hpp" #include "DiscordIntegration.hpp" #define timegm _mkgmtime #define BUILD_WITH_EASY_PROFILER #include <easy/profiler.h> #include "ProfilerConfig.hpp" int IngameUI::state = 0; bool IngameUI::visible = false; bool IngameUI::setup = false; void IngameUI::Setup() { } void IngameUI::Draw(Game* game) { EASY_FUNCTION(UI_PROFILER_COLOR); if(!visible) return; if(state == 0) { DrawIngame(game); } else if(state == 1) { DrawOptions(game); } } void IngameUI::DrawIngame(Game* game) { EASY_FUNCTION(UI_PROFILER_COLOR); if(!setup) { Setup(); } ImGui::SetNextWindowSize(ImVec2(400, 300)); ImGui::SetNextWindowPos(ImVec2(game->WIDTH / 2 - 200, game->HEIGHT / 2 - 250), ImGuiCond_FirstUseEver); if(!ImGui::Begin("Pause Menu", NULL, ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse)) { ImGui::End(); return; } ImGui::PushFont(ImGui::GetIO().Fonts->Fonts[1]); ImGui::SetCursorPosX(ImGui::GetWindowWidth() / 2 - ImGui::CalcTextSize("Options").x / 2); ImGui::Text("Options"); ImGui::PopFont(); ImGui::SetCursorPosY(ImGui::GetCursorPosY() + 10); int mainMenuButtonsWidth = 250; int mainMenuButtonsYOffset = 50; ImVec2 selPos; ImGui::SetCursorPos(ImVec2(200 - mainMenuButtonsWidth / 2, 25 + mainMenuButtonsYOffset * 1)); selPos = ImGui::GetCursorPos(); ImGui::PushFont(ImGui::GetIO().Fonts->Fonts[1]); ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 1.0f); if(ImGui::Button("##continue", ImVec2(mainMenuButtonsWidth, 36))) { visible = false; } ImGui::PopStyleVar(); ImGui::SetCursorPos(ImVec2(selPos.x + mainMenuButtonsWidth / 2 - ImGui::CalcTextSize("Continue").x / 2, selPos.y)); ImGui::Text("Continue"); ImGui::PopFont(); ImGui::SetCursorPos(ImVec2(200 - mainMenuButtonsWidth / 2, 25 + mainMenuButtonsYOffset * 2)); selPos = ImGui::GetCursorPos(); ImGui::PushFont(ImGui::GetIO().Fonts->Fonts[1]); ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 1.0f); if(ImGui::Button("##options", ImVec2(mainMenuButtonsWidth, 36))) { state = 1; } ImGui::PopStyleVar(); ImGui::SetCursorPos(ImVec2(selPos.x + mainMenuButtonsWidth / 2 - ImGui::CalcTextSize("Options").x / 2, selPos.y)); ImGui::Text("Options"); ImGui::PopFont(); ImGui::SetCursorPos(ImVec2(200 - mainMenuButtonsWidth / 2, 25 + mainMenuButtonsYOffset * 4)); selPos = ImGui::GetCursorPos(); ImGui::PushFont(ImGui::GetIO().Fonts->Fonts[1]); ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 1.0f); if(ImGui::Button("##quit", ImVec2(mainMenuButtonsWidth, 36))) { visible = false; game->quitToMainMenu(); } ImGui::PopStyleVar(); ImGui::SetCursorPos(ImVec2(selPos.x + mainMenuButtonsWidth / 2 - ImGui::CalcTextSize("Quit to Main Menu").x / 2, selPos.y)); ImGui::Text("Quit to Main Menu"); ImGui::PopFont(); ImGui::End(); } void IngameUI::DrawOptions(Game* game) { ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(0.11f, 0.11f, 0.11f, 0.9f)); ImGui::SetNextWindowSize(ImVec2(400, 400)); if(!ImGui::Begin("Pause Menu", NULL, ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse)) { ImGui::End(); ImGui::PopStyleColor(); return; } OptionsUI::Draw(game); ImGui::End(); ImGui::PopStyleColor(); }
31.265487
165
0.667988
PieKing1215
3cc61b71355a32cd0cd93491fbd5e80ad54be055
11,005
cc
C++
src/common/zp_conf.cc
CatKang/zeppelin
25b329d910d55465a04959e21daa92790ed7b361
[ "Apache-2.0" ]
413
2017-03-21T00:31:26.000Z
2022-03-07T12:03:25.000Z
src/common/zp_conf.cc
CatKang/zeppelin
25b329d910d55465a04959e21daa92790ed7b361
[ "Apache-2.0" ]
21
2017-05-10T14:40:46.000Z
2018-02-03T18:19:15.000Z
src/common/zp_conf.cc
CatKang/zeppelin
25b329d910d55465a04959e21daa92790ed7b361
[ "Apache-2.0" ]
92
2017-03-22T09:57:14.000Z
2022-02-10T01:20:57.000Z
#include "include/zp_conf.h" #include "include/zp_const.h" #include "slash/include/base_conf.h" static int64_t BoundaryLimit(int64_t target, int64_t floor, int64_t ceil) { target = (target < floor) ? floor : target; target = (target > ceil) ? ceil : target; return target; } ZpConf::ZpConf(const std::string& path) : conf_adaptor_(path), local_ip_("127.0.0.1"), local_port_(9999), timeout_(100), data_path_("data"), log_path_("log"), trash_path_("trash"), daemonize_(false), pid_file_(log_path_ + "/" + kZpPidFile), lock_file_(log_path_ + "/" + kZpLockFile), enable_data_delete_(true), meta_thread_num_(4), data_thread_num_(6), sync_recv_thread_num_(4), sync_send_thread_num_(4), max_background_flushes_(24), max_background_compactions_(24), binlog_remain_days_(kBinlogRemainMaxDay), binlog_remain_min_count_(kBinlogRemainMinCount), binlog_remain_max_count_(kBinlogRemainMaxCount), db_write_buffer_size_(256 * 1024), // 256KB db_max_write_buffer_(20 * 1024 * 1024), // 20MB db_target_file_size_base_(256 * 1024), // 256KB db_max_open_files_(4096), db_block_size_(16), // 16 B slowlog_slower_than_(-1), stuck_offset_dist_(kMetaOffsetStuckDist), // 100KB slowdown_delay_radio_(kSlowdownDelayRatio), // 60% migrate_count_once_(kMetaMigrateOnceCount), // 2 floyd_check_leader_us_(15000000), floyd_heartbeat_us_(6000000), floyd_append_entries_size_once_(1024000), floyd_append_entries_count_once_(128) { pthread_rwlock_init(&rwlock_, NULL); } ZpConf::~ZpConf() { pthread_rwlock_destroy(&rwlock_); } void ZpConf::Dump() const { auto iter = meta_addr_.begin(); while (iter != meta_addr_.end()) { fprintf(stderr, " Config.meta_addr : %s\n", iter->c_str()); iter++; } fprintf (stderr, " Config.local_ip : %s\n", local_ip_.c_str()); fprintf (stderr, " Config.local_port : %d\n", local_port_); fprintf (stderr, " Config.data_path : %s\n", data_path_.c_str()); fprintf (stderr, " Config.log_path : %s\n", log_path_.c_str()); fprintf (stderr, " Config.trash_path : %s\n", trash_path_.c_str()); fprintf (stderr, " Config.daemonize : %s\n", daemonize_? "true":"false"); fprintf (stderr, " Config.pid_file : %s\n", pid_file_.c_str()); fprintf (stderr, " Config.lock_file : %s\n", lock_file_.c_str()); fprintf (stderr, " Config.enable_data_delete : %s\n", enable_data_delete_ ? "true":"false"); fprintf (stderr, " Config.meta_thread_num : %d\n", meta_thread_num_); fprintf (stderr, " Config.data_thread_num : %d\n", data_thread_num_); fprintf (stderr, " Config.sync_recv_thread_num : %d\n", sync_recv_thread_num_); fprintf (stderr, " Config.sync_send_thread_num : %d\n", sync_send_thread_num_); fprintf (stderr, " Config.max_background_flushes : %d\n", max_background_flushes_); fprintf (stderr, " Config.max_background_compactions : %d\n", max_background_compactions_); fprintf (stderr, " Config.binlog_remain_days : %d\n", binlog_remain_days_); fprintf (stderr, " Config.binlog_remain_min_count : %d\n", binlog_remain_min_count_); fprintf (stderr, " Config.binlog_remain_max_count : %d\n", binlog_remain_max_count_); fprintf (stderr, " Config.db_write_buffer_size : %dKB\n", db_write_buffer_size_ / 1024); fprintf (stderr, " Config.db_max_write_buffer : %dMB\n", db_max_write_buffer_ / 1024 / 1024); fprintf (stderr, " Config.db_target_file_size_base : %dKB\n", db_target_file_size_base_ / 1024); fprintf (stderr, " Config.db_max_open_files : %d\n", db_max_open_files_); fprintf (stderr, " Config.db_block_size : %dB\n", db_block_size_); fprintf (stderr, " Config.slowlog_slower_than : %d\n", slowlog_slower_than_); fprintf (stderr, " Config.stuck_offset_dist : %dKB\n", stuck_offset_dist_ / 1024); fprintf (stderr, " Config.slowdown_delay_radio : %d%%\n", slowdown_delay_radio_); fprintf (stderr, " Config.migrate_count_once : %d\n", migrate_count_once_); fprintf (stderr, " Config.floyd_check_leader_us : %d\n", floyd_check_leader_us_); fprintf (stderr, " Config.floyd_heartbeat_us : %d\n", floyd_heartbeat_us_); fprintf (stderr, " Config.floyd_append_entries_size_once_ : %d\n", floyd_append_entries_size_once_); fprintf (stderr, " Config.floyd_append_entries_count_once_ : %d\n", floyd_append_entries_count_once_); } bool ZpConf::Rewrite() { conf_adaptor_.SetConfStr("local_ip", local_ip_); conf_adaptor_.SetConfInt("local_port", local_port_); conf_adaptor_.SetConfStr("data_path", data_path_); conf_adaptor_.SetConfStr("log_path", log_path_); conf_adaptor_.SetConfStr("trash_path", trash_path_); conf_adaptor_.SetConfBool("daemonize", daemonize_); conf_adaptor_.SetConfStrVec("meta_addr", meta_addr_); conf_adaptor_.SetConfBool("enable_data_delete", enable_data_delete_); conf_adaptor_.SetConfInt("meta_thread_num", meta_thread_num_); conf_adaptor_.SetConfInt("data_thread_num", data_thread_num_); conf_adaptor_.SetConfInt("sync_recv_thread_num", sync_recv_thread_num_); conf_adaptor_.SetConfInt("sync_send_thread_num", sync_send_thread_num_); conf_adaptor_.SetConfInt("max_background_flushes", max_background_flushes_); conf_adaptor_.SetConfInt("max_background_compactions", max_background_compactions_); conf_adaptor_.SetConfInt("binlog_remain_days", binlog_remain_days_); conf_adaptor_.SetConfInt("binlog_remain_min_count", binlog_remain_min_count_); conf_adaptor_.SetConfInt("binlog_remain_max_count", binlog_remain_max_count_); conf_adaptor_.SetConfInt("db_write_buffer_size", db_write_buffer_size_); conf_adaptor_.SetConfInt("db_max_write_buffer", db_max_write_buffer_); conf_adaptor_.SetConfInt("db_target_file_size_base", db_target_file_size_base_); conf_adaptor_.SetConfInt("db_max_open_files", db_max_open_files_); conf_adaptor_.SetConfInt("db_block_size", db_block_size_); conf_adaptor_.SetConfInt("slowlog_slower_than", slowlog_slower_than_); conf_adaptor_.SetConfInt("stuck_offset_dist", stuck_offset_dist_); conf_adaptor_.SetConfInt("slowdown_delay_radio", slowdown_delay_radio_); conf_adaptor_.SetConfInt("migrate_count_once", migrate_count_once_); conf_adaptor_.SetConfInt("floyd_check_leader_us", floyd_check_leader_us_); conf_adaptor_.SetConfInt("floyd_heartbeat_us", floyd_heartbeat_us_); conf_adaptor_.SetConfInt("floyd_append_entries_size_once", floyd_append_entries_size_once_); conf_adaptor_.SetConfInt("floyd_append_entries_count_once", floyd_append_entries_count_once_); return conf_adaptor_.WriteBack(); } int ZpConf::Load() { int res = conf_adaptor_.LoadConf(); if (res != 0) { return res; } bool ret = false; ret = conf_adaptor_.GetConfStr("local_ip", &local_ip_); ret = conf_adaptor_.GetConfInt("local_port", &local_port_); ret = conf_adaptor_.GetConfStr("data_path", &data_path_); ret = conf_adaptor_.GetConfStr("log_path", &log_path_); ret = conf_adaptor_.GetConfStr("trash_path", &trash_path_); ret = conf_adaptor_.GetConfBool("daemonize", &daemonize_); ret = conf_adaptor_.GetConfStrVec("meta_addr", &meta_addr_); ret = conf_adaptor_.GetConfBool("enable_data_delete", &enable_data_delete_); ret = conf_adaptor_.GetConfInt("meta_thread_num", &meta_thread_num_); ret = conf_adaptor_.GetConfInt("data_thread_num", &data_thread_num_); ret = conf_adaptor_.GetConfInt("sync_recv_thread_num", &sync_recv_thread_num_); ret = conf_adaptor_.GetConfInt("sync_send_thread_num", &sync_send_thread_num_); ret = conf_adaptor_.GetConfInt("max_background_flushes", &max_background_flushes_); ret = conf_adaptor_.GetConfInt("max_background_compactions", &max_background_compactions_); ret = conf_adaptor_.GetConfInt("binlog_remain_days", &binlog_remain_days_); ret = conf_adaptor_.GetConfInt("binlog_remain_min_count", &binlog_remain_min_count_); ret = conf_adaptor_.GetConfInt("binlog_remain_max_count", &binlog_remain_max_count_); ret = conf_adaptor_.GetConfInt("db_write_buffer_size", &db_write_buffer_size_); ret = conf_adaptor_.GetConfInt("db_max_write_buffer", &db_max_write_buffer_); ret = conf_adaptor_.GetConfInt("db_target_file_size_base", &db_target_file_size_base_); ret = conf_adaptor_.GetConfInt("db_max_open_files", &db_max_open_files_); ret = conf_adaptor_.GetConfInt("db_block_size", &db_block_size_); ret = conf_adaptor_.GetConfInt("slowlog_slower_than", &slowlog_slower_than_); ret = conf_adaptor_.GetConfInt("stuck_offset_dist", &stuck_offset_dist_); ret = conf_adaptor_.GetConfInt("slowdown_delay_radio", &slowdown_delay_radio_); ret = conf_adaptor_.GetConfInt("migrate_count_once", &migrate_count_once_); ret = conf_adaptor_.GetConfInt("floyd_check_leader_us", &floyd_check_leader_us_); ret = conf_adaptor_.GetConfInt("floyd_heartbeat_us", &floyd_heartbeat_us_); ret = conf_adaptor_.GetConfInt("floyd_append_entries_size_once", &floyd_append_entries_size_once_); ret = conf_adaptor_.GetConfInt("floyd_append_entries_count_once", &floyd_append_entries_count_once_); if (data_path_.back() != '/') { data_path_.append("/"); } if (log_path_.back() != '/') { log_path_.append("/"); } if (trash_path_.back() != '/') { trash_path_.append("/"); } std::string lock_path = log_path_; pid_file_ = lock_path + "pid"; lock_file_ = lock_path + "lock"; meta_thread_num_ = BoundaryLimit(meta_thread_num_, 1, 100); data_thread_num_ = BoundaryLimit(data_thread_num_, 1, 100); sync_recv_thread_num_ = BoundaryLimit(sync_recv_thread_num_, 1, 100); sync_send_thread_num_ = BoundaryLimit(sync_send_thread_num_, 1, 100); max_background_flushes_ = BoundaryLimit(max_background_flushes_, 10, 100); max_background_compactions_ = BoundaryLimit(max_background_compactions_, 10, 100); binlog_remain_days_ = BoundaryLimit(binlog_remain_days_, 0, 30); binlog_remain_min_count_ = BoundaryLimit(binlog_remain_min_count_, 10, 60); binlog_remain_max_count_ = BoundaryLimit(binlog_remain_max_count_, 10, 60); binlog_remain_min_count_ = binlog_remain_min_count_ > binlog_remain_max_count_ ? binlog_remain_max_count_ : binlog_remain_min_count_; slowlog_slower_than_ = BoundaryLimit(slowlog_slower_than_, -1, 10000000); stuck_offset_dist_ = BoundaryLimit(stuck_offset_dist_, 1, 100 * 1024 * 1024); slowdown_delay_radio_ = BoundaryLimit(slowdown_delay_radio_, 1, 100); migrate_count_once_ = BoundaryLimit(migrate_count_once_, 1, 100); db_write_buffer_size_ = BoundaryLimit(db_write_buffer_size_, 4 * 1024, 10 * 1024 * 1024); // 4M ~ 10G db_max_write_buffer_ = BoundaryLimit(db_max_write_buffer_, 1024 * 1024, 500 * 1024 * 1024); // 1G ~ 500G db_target_file_size_base_ = BoundaryLimit(db_target_file_size_base_, 4 * 1024, 10 * 1024 * 1024); // 4M ~ 10G db_block_size_ = BoundaryLimit(db_block_size_, 4, 1024 * 1024); // 14K ~ 1G return ret; }
54.480198
111
0.750204
CatKang
3cc97f66eafcd6fce27974d471ff9df22021f2e1
2,079
cxx
C++
examples/40-numcxx-pde/40-stationary-heat-fe.cxx
j-fu/numcxx
463ef36ee0744af5513e6b5b24342f5323be6ff0
[ "MIT" ]
null
null
null
examples/40-numcxx-pde/40-stationary-heat-fe.cxx
j-fu/numcxx
463ef36ee0744af5513e6b5b24342f5323be6ff0
[ "MIT" ]
null
null
null
examples/40-numcxx-pde/40-stationary-heat-fe.cxx
j-fu/numcxx
463ef36ee0744af5513e6b5b24342f5323be6ff0
[ "MIT" ]
null
null
null
/// /// \example 40-stationary-heat-fe.cxx /// /// Finite element method for stationary heat equation /// #include <cstdio> #include <iostream> #include <ctime> #include <cmath> #include <numcxx/numcxx.hxx> #include <numcxx/simplegrid.hxx> #include <numcxx/fem2d.hxx> #ifdef VTKFIG #include "numcxx/vtkfig-simplegrid.hxx" #endif #include "vtkfigFrame.h" #include "vtkfigDataSet.h" #include "vtkfigGridView.h" #include "vtkfigScalarView.h" int main(void) { numcxx::Geometry Geometry; Geometry.set_points({ {-2,0}, {0,0}, {2,0}, {2,2}, {0.5,2}, {0,1}, {-0.5,2}, {-2,2} }); Geometry.set_bfaces({ {0,1}, {1,2}, {2,3}, {3,4}, {4,5}, {5,6}, {6,7}, {7,0}, {5,1}, }); Geometry.set_bfaceregions({1,1,2,3,4,4,3,2,5}); Geometry.set_regionpoints({ {-0.5,1}, {0.5,1} }); Geometry.set_regionnumbers({1,2}); Geometry.set_regionvolumes({0.1,0.1}); numcxx::SimpleGrid grid(Geometry,"zpaAqDV"); numcxx::DArray1 bcfac(6); numcxx::DArray1 bcval(6); bcfac=0; bcval=0; bcfac(4)=fem2d::Dirichlet; bcfac(1)=fem2d::Dirichlet; bcval(4)=1.0; bcval(1)=0.0; auto nnodes=grid.npoints(); numcxx::DArray1 source(nnodes); numcxx::DArray1 kappa(nnodes); kappa=1; source=0; numcxx::DSparseMatrix SGlobal(nnodes,nnodes); numcxx::DArray1 Rhs(nnodes); numcxx::DArray1 Sol(nnodes); fem2d::assemble_heat_problem(grid,bcfac,bcval,source,kappa,SGlobal, Rhs); numcxx::DSolverUMFPACK Solver(SGlobal); Solver.update(SGlobal); Solver.solve(Sol,Rhs); #ifdef VTKFIG auto griddata=numcxx::vtkfigDataSet(grid); griddata->SetPointScalar(Sol ,"Sol"); auto frame=vtkfig::Frame::New(); frame->SetSize(800,400); frame->SetLayout(2,1); auto gridview=vtkfig::GridView::New(); gridview->SetData(griddata); frame->AddFigure(gridview,0); auto solview=vtkfig::ScalarView::New(); solview->SetData(griddata,"Sol"); frame->AddFigure(solview,1); frame->Interact(); #endif }
17.922414
75
0.619529
j-fu
3ccb6d80a8375549608877f466f71d6b9e570101
9,644
cpp
C++
f9_os/src/f9/ipc.cpp
ghsecuritylab/arm-cortex-v7-unix
cd499fa94d6ee6cd78a31387f3512d997335df52
[ "Apache-2.0" ]
null
null
null
f9_os/src/f9/ipc.cpp
ghsecuritylab/arm-cortex-v7-unix
cd499fa94d6ee6cd78a31387f3512d997335df52
[ "Apache-2.0" ]
null
null
null
f9_os/src/f9/ipc.cpp
ghsecuritylab/arm-cortex-v7-unix
cd499fa94d6ee6cd78a31387f3512d997335df52
[ "Apache-2.0" ]
1
2020-03-08T01:08:38.000Z
2020-03-08T01:08:38.000Z
/* * ipc.cpp * * Created on: May 18, 2017 * Author: Paul */ #include "ipc.hpp" #include "thread.hpp" #include "schd.hpp" #include "fpage.hpp" #include "ktimer.hpp" namespace f9 { extern tcb_t *caller; /* Imports from thread.c */ extern tcb_t *thread_map[]; extern int thread_count; static void user_ipc_error(tcb_t *thr, UE error) { /* Set ipc unsuccessful */ ipc_msg_tag_t tag(thr->ipc_read(0)); tag.flags(tag.flags() | 0x8); thr->ipc_write(0, tag.raw()); set_user_error(thr, error); } static inline void do_ipc_error(tcb_t *from, tcb_t *to, UE from_err,UE to_err,TSTATE from_state,TSTATE to_state) { user_ipc_error(from, from_err); user_ipc_error(to, to_err); from->state = from_state; to->state = to_state; } static void do_ipc(tcb_t *from, tcb_t *to) { ipc_typed_item_t typed_item; int untyped_idx, typed_idx, typed_item_idx; uint32_t typed_data; /* typed item extra word */ thread_id_t from_recv_tid; /* Clear timeout event when ipc is established. */ from->timeout_event = 0; to->timeout_event = 0; /* Copy tag of message */ ipc_msg_tag_t tag( from->ipc_read(0)); int untyped_last = tag.untyped() + 1; int typed_last = untyped_last + tag.typed(); if (typed_last > IPC_MR_COUNT) { do_ipc_error(from, to, UE::IPC_MSG_OVERFLOW | UE::IPC_PHASE_SEND, UE::IPC_MSG_OVERFLOW | UE::IPC_PHASE_RECV, TSTATE::RUNNABLE, TSTATE::RUNNABLE); return; } to->ipc_write(0, tag.raw()); /* Copy untyped words */ for (untyped_idx = 1; untyped_idx < untyped_last; ++untyped_idx) { to->ipc_write(untyped_idx, from->ipc_read(untyped_idx)); } typed_item_idx = -1; /* Copy typed words * FSM: j - number of byte */ for (typed_idx = untyped_idx; typed_idx < typed_last; ++typed_idx) { uint32_t mr_data = from->ipc_read(typed_idx); /* Write typed mr data to 'to' thread */ to->ipc_write(typed_idx, mr_data); if (typed_item_idx == -1) { /* If typed_item_idx == -1 - read typed item's tag */ typed_item = ipc_typed_item_t(mr_data); ++typed_item_idx; } else if (typed_item.header() & IPC_TI_MAP_GRANT) { #ifdef CONFIG_ENABLE_FPAGE /* MapItem / GrantItem have 1xxx in header */ int ret; typed_data = mr_data; ret = map_area(from->as, to->as, typed_item.raw() & 0xFFFFFFC0, typed_data & 0xFFFFFFC0, (typed_item.header() & IPC_TI_GRANT) ? GRANT : MAP, from->ispriviliged()); typed_item_idx = -1; if (ret < 0) { do_ipc_error(from, to, UE::IPC_ABORTED | UE::IPC_PHASE_SEND, UE::IPC_ABORTED | UE::IPC_PHASE_RECV, TSTATE::RUNNABLE, TSTATE::RUNNABLE); return; } #else panic("map grant not supported!\r\n"); #endif } /* TODO: StringItem support */ } if (!to->ctx.sp || !from->ctx.sp) { do_ipc_error(from, to, UE::IPC_ABORTED | UE::IPC_PHASE_SEND, UE::IPC_ABORTED | UE::IPC_PHASE_RECV, TSTATE::RUNNABLE, TSTATE::RUNNABLE); return; } to->utcb->sender = from->t_globalid; to->state = TSTATE::RUNNABLE; to->ipc_from = NILTHREAD; ((uint32_t *) to->ctx.sp)[REG_R0] = from->t_globalid; /* If from has receive phases, lock myself */ from_recv_tid = ((uint32_t *) from->ctx.sp)[REG_R1]; if (from_recv_tid == NILTHREAD) { from->state = TSTATE::RUNNABLE; } else { from->state = TSTATE::RECV_BLOCKED; from->ipc_from = from_recv_tid; dbg::print(dbg::DL_IPC, "IPC: %t receiving\n", from->t_globalid); } /* Dispatch communicating threads */ sched_slot_dispatch(SSI::NORMAL_THREAD, from); sched_slot_dispatch(SSI::IPC_THREAD, to); dbg::print(dbg::DL_IPC, "IPC: %t to %t\n", caller->t_globalid, to->t_globalid); } uint32_t ipc_timeout(void *data) { ktimer_event_t *event = (ktimer_event_t *) data; tcb_t *thr = (tcb_t *) event->data; if (thr->timeout_event == (uint32_t)data) { if (thr->state == TSTATE::RECV_BLOCKED) user_ipc_error(thr, UE::IPC_TIMEOUT | UE::IPC_PHASE_RECV); if (thr->state == TSTATE::SEND_BLOCKED) user_ipc_error(thr, UE::IPC_TIMEOUT | UE::IPC_PHASE_SEND); thr->state = TSTATE::RUNNABLE; thr->timeout_event = 0; } return 0; } typedef union { uint16_t raw; struct { uint32_t m : 10; uint32_t e : 5; uint32_t a : 1; } period; struct { uint32_t m : 10; uint32_t c : 1; uint32_t e : 4; uint32_t a : 1; } point; } ipc_time_t; static void sys_ipc_timeout(uint32_t timeout) { ipc_time_t t; t.raw = timeout ; /* millisec to ticks */ uint32_t ticks = (t.period.m << t.period.e) / ((1000000) / (HAL_RCC_GetHCLKFreq()/CONFIG_KTIMER_HEARTBEAT)); ktimer_event_t *kevent = ktimer_event_t::create(ticks, ipc_timeout, caller); caller->timeout_event = (uint32_t) kevent; } void sys_ipc(uint32_t *param1) { /* TODO: Checking of recv-mask */ tcb_t *to_thr = NULL; thread_id_t to_tid = param1[REG_R0], from_tid = param1[REG_R1]; uint32_t timeout = param1[REG_R2]; if (to_tid == NILTHREAD && from_tid == NILTHREAD) { caller->state = TSTATE::INACTIVE; if (timeout) sys_ipc_timeout(timeout); return; } if (to_tid != NILTHREAD) { to_thr = thread_by_globalid(to_tid); if (to_tid == TID_TO_GLOBALID(THREAD::LOG)) { user_log(caller); caller->state = TSTATE::RUNNABLE; return; } else if (to_tid == TID_TO_GLOBALID(THREAD::IRQ_REQUEST)) { #if 0 user_interrupt_config(caller); caller->state = TSTATE::RUNNABLE; #else assert(0); // no user interrupts yet, oooh signals this make sence humm #endif return; } else if ((to_thr && to_thr->state == TSTATE::RECV_BLOCKED) || to_tid == caller->t_globalid) { /* To thread who is waiting for us or sends to myself */ do_ipc(caller, to_thr); return; } else if (to_thr && to_thr->state == TSTATE::INACTIVE && GLOBALID_TO_TID(to_thr->utcb->t_pager) == GLOBALID_TO_TID(caller->t_globalid)) { if (caller->ipc_read( 0) == 0x00000005) { /* mr1: thread func, mr2: stack addr, * mr3: stack size * mr4: thread entry, mr5: thread args * thread start protocol */ memptr_t sp = caller->ipc_read( 2); size_t stack_size = caller->ipc_read(3); uint32_t regs[4]; /* r0, r1, r2, r3 */ dbg::print(dbg::DL_IPC, "IPC: %t thread start\n", to_tid); to_thr->stack_base = sp - stack_size; to_thr->stack_size = stack_size; #if 0 regs[REG_R0] = (uint32_t)&kip; #else regs[REG_R0] = 0; #endif regs[REG_R1] = (uint32_t)to_thr->utcb; regs[REG_R2] = caller->ipc_read(4); regs[REG_R3] = caller->ipc_read( 5); to_thr->init_ctx((void *) sp, (void *) caller->ipc_read(1), regs); caller->state = TSTATE::RUNNABLE; /* Start thread */ to_thr->state = TSTATE::RUNNABLE; return; } else { do_ipc(caller, to_thr); to_thr->state = TSTATE::INACTIVE; return; } } else { /* No waiting, block myself */ caller->state = TSTATE::SEND_BLOCKED; caller->utcb->intended_receiver = to_tid; dbg::print(dbg::DL_IPC, "IPC: %t sending\n", caller->t_globalid); if (timeout) sys_ipc_timeout(timeout); return; } } if (from_tid != NILTHREAD) { tcb_t *thr = nullptr; if (from_tid == ANYTHREAD) { /* Find out if there is any sending thread waiting * for caller */ for (int i = 1; i < thread_count; ++i) { thr = thread_map[i]; if (thr->state == TSTATE::SEND_BLOCKED && thr->utcb->intended_receiver == caller->t_globalid) { do_ipc(thr, caller); return; } } } else if (from_tid != TID_TO_GLOBALID(THREAD::INTERRUPT)) { thr = thread_by_globalid(from_tid); if (thr->state == TSTATE::SEND_BLOCKED && thr->utcb->intended_receiver == caller->t_globalid) { do_ipc(thr, caller); return; } } /* Only receive phases, simply lock myself */ caller->state = TSTATE::RECV_BLOCKED; caller->ipc_from = from_tid; if (from_tid == TID_TO_GLOBALID(THREAD::INTERRUPT)) { /* Threaded interrupt is ready */ #if 0 user_interrupt_handler_update(caller); #else assert(0); // no user interrupts yet, oooh signals this make sence humm #endif } if (timeout) sys_ipc_timeout(timeout); dbg::print(dbg::DL_IPC, "IPC: %t receiving\n", caller->t_globalid); return; } caller->state = TSTATE::SEND_BLOCKED; } uint32_t ipc_deliver(void *data) { thread_id_t receiver; tcb_t *from_thr = NULL, *to_thr = NULL; for (int i = 1; i < thread_count; ++i) { tcb_t *thr = thread_map[i]; switch (thr->state) { case TSTATE::RECV_BLOCKED: if (thr->ipc_from != NILTHREAD && thr->ipc_from != ANYTHREAD && thr->ipc_from != TID_TO_GLOBALID(THREAD::INTERRUPT)) { from_thr = thread_by_globalid(thr->ipc_from); /* NOTE: Must check from_thr intend to send*/ if (from_thr->state == TSTATE::SEND_BLOCKED && from_thr->utcb->intended_receiver == thr->t_globalid) do_ipc(from_thr, thr); } break; case TSTATE::SEND_BLOCKED: receiver = thr->utcb->intended_receiver; if (receiver != NILTHREAD && receiver != ANYTHREAD) { to_thr = thread_by_globalid(receiver); if (to_thr->state == TSTATE::RECV_BLOCKED) do_ipc(thr, to_thr); } break; default: break; } } return 4096; } } /* namespace f9 */
25.717333
113
0.616964
ghsecuritylab
3cce0ade454ad1af19c8bdb9f4c304f18994e4aa
577
hpp
C++
src/Components/SatteliteBody.hpp
ananace/LD45
73687658323c81e563ead4e8f36afb89cbf27232
[ "MIT" ]
null
null
null
src/Components/SatteliteBody.hpp
ananace/LD45
73687658323c81e563ead4e8f36afb89cbf27232
[ "MIT" ]
null
null
null
src/Components/SatteliteBody.hpp
ananace/LD45
73687658323c81e563ead4e8f36afb89cbf27232
[ "MIT" ]
1
2020-03-30T05:00:54.000Z
2020-03-30T05:00:54.000Z
#pragma once #include <entt/entity/fwd.hpp> namespace Components { struct SatteliteBody { entt::entity Orbiting; float Distance, Speed; float CurrentAngle; SatteliteBody() : Distance{}, Speed{}, CurrentAngle{} { } SatteliteBody(entt::entity aOrbiting, float aDistance, float aSpeed) : Orbiting(aOrbiting), Distance(aDistance), Speed(aSpeed), CurrentAngle{} { } SatteliteBody(entt::entity aOrbiting, float aDistance, float aSpeed, float aCurrentAngle) : Orbiting(aOrbiting), Distance(aDistance), Speed(aSpeed), CurrentAngle(aCurrentAngle) { } }; }
27.47619
184
0.729636
ananace
3cced1a593e29b215c4b5d63e17fbc685eba9ae6
528
cpp
C++
shared/offline_compiler/source/utilities/linux/get_path.cpp
raiyanla/compute-runtime
43433244f9d17e9c989116808757705754ddbfee
[ "MIT" ]
1
2020-04-17T05:46:04.000Z
2020-04-17T05:46:04.000Z
shared/offline_compiler/source/utilities/linux/get_path.cpp
dkjiang2018/compute-runtime
310947e6ddefc4bb9a7a268fc1ee8639155b730c
[ "MIT" ]
null
null
null
shared/offline_compiler/source/utilities/linux/get_path.cpp
dkjiang2018/compute-runtime
310947e6ddefc4bb9a7a268fc1ee8639155b730c
[ "MIT" ]
1
2020-05-25T21:57:51.000Z
2020-05-25T21:57:51.000Z
/* * Copyright (C) 2020 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include <sstream> #include <string> #include <sys/types.h> #include <unistd.h> std::string getPath() { char exepath[128] = {0}; std::stringstream ss; ss << "/proc/" << getpid() << "/exe"; if (readlink(ss.str().c_str(), exepath, 128) != -1) { std::string path = std::string(exepath); path = path.substr(0, path.find_last_of('/') + 1); return path; } else { return std::string(""); } }
21.12
58
0.558712
raiyanla
3cd0ed5b8d8c9e4a5324fb75f2189e190ff8ac36
149
hpp
C++
pagerank.hpp
gbossi/Pagerank-DOBFS
bfeb88e8778349dee66308a75d9acb2cfc7f57d0
[ "MIT" ]
3
2018-11-19T02:15:40.000Z
2021-04-10T09:40:01.000Z
pagerank.hpp
gbossi/Pagerank-DOBFS
bfeb88e8778349dee66308a75d9acb2cfc7f57d0
[ "MIT" ]
null
null
null
pagerank.hpp
gbossi/Pagerank-DOBFS
bfeb88e8778349dee66308a75d9acb2cfc7f57d0
[ "MIT" ]
1
2021-09-19T02:01:03.000Z
2021-09-19T02:01:03.000Z
#ifndef _PAGERANK_HPP_ #define _PAGERANK_HPP_ #include "graph.hpp" #include <boost/graph/page_rank.hpp> void pagerank(Graph&, double, int); #endif
16.555556
36
0.771812
gbossi
3cd1f94d974c2298039d4de584a8e42861372ace
546
cpp
C++
Data_Structures/Stacks/largest_area_hist.cpp
abhishekjha786/ds_algo
38355ca12e8ac20c4baa8baccf8ad189effaa6ae
[ "MIT" ]
11
2020-03-20T17:24:28.000Z
2022-01-08T02:43:24.000Z
Data_Structures/Stacks/largest_area_hist.cpp
abhishekjha786/ds_algo
38355ca12e8ac20c4baa8baccf8ad189effaa6ae
[ "MIT" ]
1
2021-07-25T11:24:46.000Z
2021-07-25T12:09:25.000Z
Data_Structures/Stacks/largest_area_hist.cpp
abhishekjha786/ds_algo
38355ca12e8ac20c4baa8baccf8ad189effaa6ae
[ "MIT" ]
4
2020-03-20T17:24:36.000Z
2021-12-07T19:22:59.000Z
// Given an array of integers A of size N. A represents a histogram i.e A[i] denotes height of // the ith histogram’s bar. Width of each bar is 1. // Largest Rectangle in Histogram: Example 1 // Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3]. // // | | | | | | // | | | | | // | | | // | | // | | // | // Largest Rectangle in Histogram: Example 2 // The largest rectangle is shown in the shaded area, which has area = 10 unit. // Find the area of largest rectangle in the histogram.
24.818182
94
0.611722
abhishekjha786
3cd35c24450e778221b75c946dbf8b72a7134df7
1,023
cpp
C++
Outer.Tlibc/puts.cpp
lusores/ABRViewer
64d3172651a904908589fc91276366ef3ef0489e
[ "MIT" ]
15
2017-05-15T15:52:24.000Z
2022-03-23T06:48:48.000Z
Outer.Tlibc/puts.cpp
lusores/ABRViewer
64d3172651a904908589fc91276366ef3ef0489e
[ "MIT" ]
null
null
null
Outer.Tlibc/puts.cpp
lusores/ABRViewer
64d3172651a904908589fc91276366ef3ef0489e
[ "MIT" ]
4
2017-09-07T10:55:36.000Z
2021-01-29T08:51:01.000Z
// puts.cpp // based on: // LIBCTINY - Matt Pietrek 2001 // MSDN Magazine, January 2001 // 08/12/06 (mv) #include <windows.h> #include <stdio.h> #include "libct.h" EXTERN_C int puts(const char *s) { //DWORD cbWritten; //HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE); int bw = fwrite(s, lstrlenA(s), 1, stdout); bw += fwrite("\n", 1, 1, stdout); return bw; //WriteFile(hStdOut, s, lstrlenA(s)*sizeof(char), &cbWritten, 0); //WriteFile(hStdOut, "\r\n", 2, &cbWritten, 0); //return (int)(cbWritten ? cbWritten : EOF); } EXTERN_C int _putws(const wchar_t *s) { //DWORD bw; //HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE); // _putws converts unicode to ascii before writing to stdout! char bfr[1024]; WideCharToMultiByte(CP_ACP, 0, s, -1, bfr, sizeof(bfr), 0, 0); return puts(bfr); //WriteFile(hStdOut, s, lstrlenW(s)*sizeof(wchar_t), &bw, 0); //WriteFile(hStdOut, L"\r\n", 2*sizeof(wchar_t), &bw, 0); //return (int)(bw ? bw : EOF); }
23.25
70
0.621701
lusores
3cd42c4dde6728380c810484ae70bf7e3d25ba9e
349
cpp
C++
RPi3/src/apps/botgui/botgui_main.cpp
sahibdhanjal/SLAM
f1f688253c61b27ca6acfdfb353f1d3127b53422
[ "MIT" ]
1
2020-09-20T15:03:56.000Z
2020-09-20T15:03:56.000Z
RPi3/src/apps/botgui/botgui_main.cpp
sahibdhanjal/SLAM
f1f688253c61b27ca6acfdfb353f1d3127b53422
[ "MIT" ]
null
null
null
RPi3/src/apps/botgui/botgui_main.cpp
sahibdhanjal/SLAM
f1f688253c61b27ca6acfdfb353f1d3127b53422
[ "MIT" ]
2
2019-06-29T04:21:35.000Z
2020-12-31T01:33:24.000Z
#include <apps/botgui/botgui.hpp> #include <thread> int main(int argc, char** argv) { lcm::LCM lcmInstance(MULTICAST_URL); BotGui gui(&lcmInstance, argc, argv, 1000, 800, 15); std::thread lcmThread([&]() { while(true) { lcmInstance.handleTimeout(100); } }); gui.run(); return 0; }
18.368421
56
0.558739
sahibdhanjal
3cd65db0773149765563238fdcc2b5d83f2573f5
1,186
hpp
C++
src/io/ValueReader.hpp
spraetor/amdis2
53c45c81a65752a8fafbb54f9ae6724a86639dcd
[ "MIT" ]
2
2018-07-04T16:44:04.000Z
2021-01-03T07:26:27.000Z
src/io/ValueReader.hpp
spraetor/amdis2
53c45c81a65752a8fafbb54f9ae6724a86639dcd
[ "MIT" ]
null
null
null
src/io/ValueReader.hpp
spraetor/amdis2
53c45c81a65752a8fafbb54f9ae6724a86639dcd
[ "MIT" ]
null
null
null
#pragma once #include <cstring> #include "DOFVector.hpp" #include "Mesh.hpp" namespace AMDiS { namespace io { /** \ingroup Input * * \brief * Namespace of methods which read a value file in AMDiS format and copies * the data to a DOF vector. */ namespace ValueReader { template<typename Container> void readValue(std::string /*filename*/, Mesh* /*mesh*/, Container& /*vec*/, MacroInfo* /*macroFileInfo*/) { ERROR_EXIT("ValueReader not implemented for this container type!\n"); } /// Copies the values of a value file to a DOF vector. void readValue(std::string filename, Mesh* mesh, DOFVector<double>* dofVector, MacroInfo* macroFileInfo); inline void readValue(std::string filename, Mesh* mesh, DOFVector<double>& dofVector, MacroInfo* macroFileInfo) { readValue(filename, mesh, &dofVector, macroFileInfo); } } // end namespace ValueReader } } // end namespace io, AMDiS
24.708333
78
0.546374
spraetor
3cd81ef6a18b78c954d4582e7a416f2c29046c61
1,071
cpp
C++
015_K-means_Clustering/src/main.cpp
DreamWaterFound/Codes
e7d80eb8bfd7d6f104abd18724cb4bface419233
[ "WTFPL" ]
13
2019-02-28T14:28:23.000Z
2021-12-04T04:55:19.000Z
015_K-means_Clustering/src/main.cpp
DreamWaterFound/Codes
e7d80eb8bfd7d6f104abd18724cb4bface419233
[ "WTFPL" ]
1
2019-09-07T09:00:50.000Z
2019-12-04T02:13:25.000Z
015_K-means_Clustering/src/main.cpp
DreamWaterFound/Codes
e7d80eb8bfd7d6f104abd18724cb4bface419233
[ "WTFPL" ]
1
2020-03-11T16:47:31.000Z
2020-03-11T16:47:31.000Z
#include <iostream> #include <Samples.hpp> #include <string> #include <sstream> #include "K_means.hpp" using namespace std; int main(int argc, char* argv[]) { cout<<"K-means Test."<<endl; if(argc!=4) { cout<<"Usage: "<<argv[0]<<" samples_path class_num iter_max"<<endl; cout<<"Ex: "<<argv[0]<<" ./data/my.txt 2 20"<<endl; return 0; } size_t K,N; stringstream ss(argv[2]); ss>>K; ss=stringstream(argv[3]); ss>>N; Samples sample; vector<SampleType> samples; samples=sample.getSamples(string(argv[1])); if(samples.size()==0) { cout<<"No samples loaded. Check the file "<<argv[1]<<endl; return 0; } else { cout<<"File "<<argv[1]<<" loaded complete, "<<samples.size()<<" sample points."<<endl; } K_MeansCluster cluster(K,N,sample.getRangeHeight(),sample.getRangeWidth(), 2,samples); if(cluster.isFailed()) { cout<<"Cluster Failed."<<endl; return 0; } return 0; }
16.227273
94
0.545285
DreamWaterFound
3cdab58da4e4554659c05cf219e29eb49661f564
2,023
cpp
C++
Engine/Source/Runtime/Engine/Private/Animation/AnimNode_TwoWayBlend.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
Engine/Source/Runtime/Engine/Private/Animation/AnimNode_TwoWayBlend.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
2
2015-06-21T17:38:11.000Z
2015-06-22T20:54:42.000Z
Engine/Source/Runtime/Engine/Private/Animation/AnimNode_TwoWayBlend.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #include "EnginePrivate.h" #include "Animation/AnimNode_TwoWayBlend.h" ///////////////////////////////////////////////////// // FAnimationNode_TwoWayBlend void FAnimationNode_TwoWayBlend::Initialize(const FAnimationInitializeContext& Context) { A.Initialize(Context); B.Initialize(Context); } void FAnimationNode_TwoWayBlend::CacheBones(const FAnimationCacheBonesContext& Context) { A.CacheBones(Context); B.CacheBones(Context); } void FAnimationNode_TwoWayBlend::Update(const FAnimationUpdateContext& Context) { EvaluateGraphExposedInputs.Execute(Context); const float ActualAlpha = AlphaScaleBias.ApplyTo(Alpha); if (ActualAlpha > ZERO_ANIMWEIGHT_THRESH) { if (ActualAlpha < 1.0f - ZERO_ANIMWEIGHT_THRESH) { // Blend A and B together A.Update(Context.FractionalWeight(1.0f - ActualAlpha)); B.Update(Context.FractionalWeight(ActualAlpha)); } else { // Take all of B B.Update(Context); } } else { // Take all of A A.Update(Context); } } void FAnimationNode_TwoWayBlend::Evaluate(FPoseContext& Output) { const float ActualAlpha = AlphaScaleBias.ApplyTo(Alpha); if (ActualAlpha > ZERO_ANIMWEIGHT_THRESH) { if (ActualAlpha < 1.0f - ZERO_ANIMWEIGHT_THRESH) { FPoseContext Pose1(Output); FPoseContext Pose2(Output); A.Evaluate(Pose1); B.Evaluate(Pose2); FAnimationRuntime::BlendTwoPosesTogether(Pose1.Pose, Pose2.Pose, Pose1.Curve, Pose2.Curve, (1.0f - ActualAlpha), Output.Pose, Output.Curve); } else { B.Evaluate(Output); } } else { A.Evaluate(Output); } } void FAnimationNode_TwoWayBlend::GatherDebugData(FNodeDebugData& DebugData) { const float ActualAlpha = AlphaScaleBias.ApplyTo(Alpha); FString DebugLine = DebugData.GetNodeName(this); DebugLine += FString::Printf(TEXT("(Alpha: %.1f%%)"), ActualAlpha*100); DebugData.AddDebugItem(DebugLine); A.GatherDebugData(DebugData.BranchFlow(1.f - ActualAlpha)); B.GatherDebugData(DebugData.BranchFlow(ActualAlpha)); }
24.083333
143
0.729115
PopCap
3cdaf3e549e4b46c74a65872b950438eb65b0ac3
1,254
cc
C++
src/sys/fuzzing/common/testing/module.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
5
2022-01-10T20:22:17.000Z
2022-01-21T20:14:17.000Z
src/sys/fuzzing/common/testing/module.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
2
2021-09-19T21:55:09.000Z
2021-12-19T03:34:53.000Z
src/sys/fuzzing/common/testing/module.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
1
2021-08-23T11:33:57.000Z
2021-08-23T11:33:57.000Z
// Copyright 2021 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/sys/fuzzing/common/testing/module.h" #include <lib/syslog/cpp/macros.h> #include <random> namespace fuzzing { FakeModule::FakeModule(uint32_t seed) { counters_.resize(kNumPCs, 0); pc_table_.reserve(kNumPCs); std::minstd_rand prng(seed); uintptr_t pc = prng(); for (size_t i = 0; i < kNumPCs; ++i) { pc += prng() % 512; pc_table_.emplace_back(pc, (prng() % 8) == 0); } } FakeModule::FakeModule(std::vector<ModulePC>&& pc_table) noexcept { FX_DCHECK(pc_table.size() == kNumPCs); counters_.resize(kNumPCs, 0); pc_table_ = std::move(pc_table); } FakeModule& FakeModule::operator=(FakeModule&& other) noexcept { counters_ = std::move(other.counters_); pc_table_ = std::move(other.pc_table_); return *this; } uint8_t& FakeModule::operator[](size_t index) { FX_DCHECK(index < num_pcs()); return counters_[index]; } void FakeModule::SetCoverage(const Coverage& coverage) { memset(counters(), 0, num_pcs()); for (auto x : coverage) { FX_DCHECK(x.first < num_pcs()); counters_[x.first] = x.second; } } } // namespace fuzzing
25.08
73
0.6874
allansrc
3cdb20a16e515f11cf2bb3edbdc74c1bc48f4121
8,225
cpp
C++
searchlib/src/vespa/searchlib/features/text_similarity_feature.cpp
leisureshadow/vespa
28a35b8d53cbd6dda54eb141e29b12584b297410
[ "Apache-2.0" ]
null
null
null
searchlib/src/vespa/searchlib/features/text_similarity_feature.cpp
leisureshadow/vespa
28a35b8d53cbd6dda54eb141e29b12584b297410
[ "Apache-2.0" ]
null
null
null
searchlib/src/vespa/searchlib/features/text_similarity_feature.cpp
leisureshadow/vespa
28a35b8d53cbd6dda54eb141e29b12584b297410
[ "Apache-2.0" ]
null
null
null
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "text_similarity_feature.h" #include <vespa/searchlib/fef/itermdata.h> #include <vespa/searchlib/fef/featurenamebuilder.h> namespace search::features { using CollectionType = fef::FieldInfo::CollectionType; namespace { struct Term { fef::TermFieldHandle handle; int weight; Term(fef::TermFieldHandle handle_in, int weight_in) : handle(handle_in), weight(weight_in) {} }; struct State { uint32_t field_length; uint32_t matched_terms; int sum_term_weight; uint32_t last_pos; double sum_proximity_score; uint32_t last_idx; uint32_t num_in_order; State(uint32_t length, uint32_t first_pos, int32_t first_weight, uint32_t first_idx) : field_length(length), matched_terms(1), sum_term_weight(first_weight), last_pos(first_pos), sum_proximity_score(0.0), last_idx(first_idx), num_in_order(0) {} double proximity_score(uint32_t dist) { return (dist > 8) ? 0 : (1.0 - (((dist-1)/8.0) * ((dist-1)/8.0))); } bool want_match(uint32_t pos) { return (pos > last_pos); } void addMatch(uint32_t pos, int32_t weight, uint32_t idx) { sum_proximity_score += proximity_score(pos - last_pos); num_in_order += (idx > last_idx) ? 1 : 0; last_pos = pos; last_idx = idx; ++matched_terms; sum_term_weight += weight; } void calculateScore(size_t num_query_terms, int total_term_weight, double &score_out, double &proximity_out, double &order_out, double &query_coverage_out, double &field_coverage_out) { double matches = std::min(field_length, matched_terms); if (matches < 2) { proximity_out = proximity_score(field_length); order_out = (num_query_terms == 1) ? 1.0 : 0.0; } else { proximity_out = sum_proximity_score / (matches - 1); order_out = num_in_order / (double) (matches - 1); } query_coverage_out = sum_term_weight / (double) total_term_weight; field_coverage_out = matches / (double) field_length; score_out = (0.35 * proximity_out) + (0.15 * order_out) + (0.30 * query_coverage_out) + (0.20 * field_coverage_out); } }; } // namespace search::features::<unnamed> //----------------------------------------------------------------------------- TextSimilarityExecutor::TextSimilarityExecutor(const fef::IQueryEnvironment &env, uint32_t field_id) : _handles(), _weights(), _total_term_weight(0), _queue(), _md(nullptr) { std::vector<Term> terms; for (uint32_t i = 0; i < env.getNumTerms(); ++i) { const fef::ITermData *termData = env.getTerm(i); if (termData->getWeight().percent() != 0) { // only consider query terms with contribution typedef fef::ITermFieldRangeAdapter FRA; for (FRA iter(*termData); iter.valid(); iter.next()) { const fef::ITermFieldData &tfd = iter.get(); if (tfd.getFieldId() == field_id) { int term_weight = termData->getWeight().percent(); _total_term_weight += term_weight; terms.push_back(Term(tfd.getHandle(), term_weight)); } } } } _handles.reserve(terms.size()); _weights.reserve(terms.size()); for (size_t i = 0; i < terms.size(); ++i) { _handles.push_back(terms[i].handle); _weights.push_back(terms[i].weight); } } void TextSimilarityExecutor::execute(uint32_t docId) { for (size_t i = 0; i < _handles.size(); ++i) { const fef::TermFieldMatchData *tfmd = _md->resolveTermField(_handles[i]); if (tfmd->getDocId() == docId) { Item item(i, tfmd->begin(), tfmd->end()); if (item.pos != item.end) { _queue.push(item); } } } if (_queue.empty()) { outputs().set_number(0, 0.0); outputs().set_number(1, 0.0); outputs().set_number(2, 0.0); outputs().set_number(3, 0.0); outputs().set_number(4, 0.0); return; } const Item &first = _queue.front(); State state(first.pos->getElementLen(), first.pos->getPosition(), _weights[first.idx], first.idx); _queue.pop_front(); while (!_queue.empty()) { Item &item = _queue.front(); if (state.want_match(item.pos->getPosition())) { state.addMatch(item.pos->getPosition(), _weights[item.idx], item.idx); _queue.pop_front(); } else { ++item.pos; if (item.pos == item.end) { _queue.pop_front(); } else { _queue.adjust(); } } } state.calculateScore(_handles.size(), _total_term_weight, *outputs().get_number_ptr(0), *outputs().get_number_ptr(1), *outputs().get_number_ptr(2), *outputs().get_number_ptr(3), *outputs().get_number_ptr(4)); } void TextSimilarityExecutor::handle_bind_match_data(const fef::MatchData &md) { _md = &md; } //----------------------------------------------------------------------------- const vespalib::string TextSimilarityBlueprint::score_output("score"); const vespalib::string TextSimilarityBlueprint::proximity_output("proximity"); const vespalib::string TextSimilarityBlueprint::order_output("order"); const vespalib::string TextSimilarityBlueprint::query_coverage_output("queryCoverage"); const vespalib::string TextSimilarityBlueprint::field_coverage_output("fieldCoverage"); TextSimilarityBlueprint::TextSimilarityBlueprint() : Blueprint("textSimilarity"), _field_id(fef::IllegalHandle) {} void TextSimilarityBlueprint::visitDumpFeatures(const fef::IIndexEnvironment &env, fef::IDumpFeatureVisitor &visitor) const { for (uint32_t i = 0; i < env.getNumFields(); ++i) { const fef::FieldInfo &field = *env.getField(i); if (field.type() == fef::FieldType::INDEX) { if (!field.isFilter() && field.collection() == CollectionType::SINGLE) { fef::FeatureNameBuilder fnb; fnb.baseName(getBaseName()).parameter(field.name()); visitor.visitDumpFeature(fnb.output(score_output).buildName()); visitor.visitDumpFeature(fnb.output(proximity_output).buildName()); visitor.visitDumpFeature(fnb.output(order_output).buildName()); visitor.visitDumpFeature(fnb.output(query_coverage_output).buildName()); visitor.visitDumpFeature(fnb.output(field_coverage_output).buildName()); } } } } fef::Blueprint::UP TextSimilarityBlueprint::createInstance() const { return Blueprint::UP(new TextSimilarityBlueprint()); } bool TextSimilarityBlueprint::setup(const fef::IIndexEnvironment &env, const fef::ParameterList &params) { const fef::FieldInfo *field = params[0].asField(); _field_id = field->id(); describeOutput(score_output, "default normalized combination of other outputs"); describeOutput(proximity_output, "normalized match proximity score"); describeOutput(order_output, "normalized match order score"); describeOutput(query_coverage_output, "normalized query match coverage"); describeOutput(field_coverage_output, "normalized field match coverage"); env.hintFieldAccess(field->id()); return true; } fef::FeatureExecutor & TextSimilarityBlueprint::createExecutor(const fef::IQueryEnvironment &env, vespalib::Stash &stash) const { return stash.create<TextSimilarityExecutor>(env, _field_id); } //----------------------------------------------------------------------------- }
36.71875
118
0.590517
leisureshadow
3cde63f230a04be8f62f33b544448e08f254b472
996
cpp
C++
925-long-pressed-name/925-long-pressed-name.cpp
shreydevep/DSA
688af414c1fada1b82a4b4e9506747352007c894
[ "MIT" ]
null
null
null
925-long-pressed-name/925-long-pressed-name.cpp
shreydevep/DSA
688af414c1fada1b82a4b4e9506747352007c894
[ "MIT" ]
null
null
null
925-long-pressed-name/925-long-pressed-name.cpp
shreydevep/DSA
688af414c1fada1b82a4b4e9506747352007c894
[ "MIT" ]
null
null
null
class Solution { public: vector<pair<char,int>> compress(string &s){ vector<pair<char,int>> res; int curr = 0; int i = 0; while(i < s.length()){ int cnt = 0; while(i < s.length() && i >= curr && s[curr] == s[i]){ i++; cnt++; } res.push_back({s[curr],cnt}); curr = i; } return res; } bool isLongPressedName(string name, string typed) { auto name_new = compress(name); auto typed_new = compress(typed); if(name_new.size() != typed_new.size()) return false; for(int i=0;i<name_new.size();++i){ if(name_new[i].first == typed_new[i].first){ if(name_new[i].second > typed_new[i].second){ return false; } } else{ return false; } } return true; } };
26.918919
66
0.420683
shreydevep
3cdf6e8831a9d46e590dae9f619bfa9ac48221aa
338
cc
C++
skia/ext/platform_device_linux.cc
rwatson/chromium-capsicum
b03da8e897f897c6ad2cda03ceda217b760fd528
[ "BSD-3-Clause" ]
11
2015-03-20T04:08:08.000Z
2021-11-15T15:51:36.000Z
skia/ext/platform_device_linux.cc
changbai1980/chromium
c4625eefca763df86471d798ee5a4a054b4716ae
[ "BSD-3-Clause" ]
null
null
null
skia/ext/platform_device_linux.cc
changbai1980/chromium
c4625eefca763df86471d798ee5a4a054b4716ae
[ "BSD-3-Clause" ]
1
2020-04-13T05:45:10.000Z
2020-04-13T05:45:10.000Z
// Copyright (c) 2006-2008 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 "skia/ext/platform_device_linux.h" namespace skia { PlatformDevice::PlatformDevice(const SkBitmap& bitmap) : SkDevice(bitmap) { } } // namespace skia
26
75
0.748521
rwatson