blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
a3c7e7a1f1ff5ad46dcc3d50417c9c4f4c2e6481
53f415f1193fb5000df706004f635044dc665ab6
/02. Functions, Arrays and Vectors/Demos/14.STL-Vectors-as-Function-Parameters.cpp
7f2a12f504bf7391bcc1f97d9ebe6c76fb9c9e4d
[]
no_license
Martin-BG/SoftUni-CPP-Fundamentals
695e32c41730776ced262ce34788e18671cbe663
7ecab0f48c795222564bc7ea665afa5690883508
refs/heads/master
2022-07-31T16:21:14.849967
2022-07-05T17:23:22
2022-07-05T17:23:22
163,557,283
0
2
null
null
null
null
UTF-8
C++
false
false
523
cpp
#include <iostream> #include <vector> using namespace std; void print(vector<int> numbers) { for (int i = 0; i < numbers.size(); i++) { cout << numbers[i] << " "; } cout << endl; } void printMultiplied(vector<int> numbers, int multiplier) { for (int i = 0; i < numbers.size(); i++) { numbers[i] *= multiplier; } print(numbers); } int main() { std::vector<int> numbers {1, 2, 3}; printMultiplied(numbers, 10); /// 10, 20, 30 print(numbers); /// 1, 2, 3 return 0; }
[ "MartinBG@abv.bg" ]
MartinBG@abv.bg
455783085a7198d109c180049117abd99a61ee9f
63b1306f99b4d3b0f12d7bac3d7be85ffaabdf77
/Top Down Shooter/GothicVaniaGhostStates.cpp
28dd8522566901fe1d0af086096f4c16932b1937
[]
no_license
Niruz/Top-Down-Shooter
4cc33a18746181e908e6a58a39a7ee42cc57bc0e
3bbd96223cd3e1c8dd212457755d0e160bf13b51
refs/heads/master
2021-10-19T03:57:18.155039
2019-02-17T16:59:13
2019-02-17T16:59:13
127,650,402
0
0
null
null
null
null
UTF-8
C++
false
false
1,755
cpp
#include "SimpleTimer.h" #include "GothicVaniaGhostStates.h" #include "GhostEntity.h" #include "GhostSprite.h" //------------------------------------------------------------------------methods for GhostPatrol GhostPatrol* GhostPatrol::Instance() { static GhostPatrol instance; return &instance; } void GhostPatrol::Enter(GhostEntity* entity) { entity->SetAnimation("GhostPatrol"); entity->ResetAttackTimer(); entity->myPlasmaSprite->myPosition.x = -1337.0f; } void GhostPatrol::Execute(GhostEntity* entity) { entity->myAnimatedSprite->Update(); entity->myPlasmaSprite->Update(); entity->HandleMovement(); if(entity->myAtTarget) { entity->GetFSM()->changeState(GhostAttack::Instance()); } if ((Clock->GetCurrentTimeInSeconds() - entity->myAttackTimer) >= 3.0f) { } } void GhostPatrol::Exit(GhostEntity* entity) { } bool GhostPatrol::OnMessage(GhostEntity* entity, const Message& msg) { return false; } //------------------------------------------------------------------------methods for GhostAttack GhostAttack* GhostAttack::Instance() { static GhostAttack instance; return &instance; } void GhostAttack::Enter(GhostEntity* entity) { entity->SetAnimation("GhostAttack"); entity->ResetAttackTimer(); entity->myPlasmaSprite->myPosition.x = entity->mPosition.x + 6.0f; } void GhostAttack::Execute(GhostEntity* entity) { entity->myAnimatedSprite->Update(); entity->myPlasmaSprite->Update(); //entity->HandleMovement(); if ((Clock->GetCurrentTimeInSeconds() - entity->myAttackTimer) >= 2.0f) { entity->GetFSM()->changeState(GhostPatrol::Instance()); entity->myAtTarget = false; } } void GhostAttack::Exit(GhostEntity* entity) { } bool GhostAttack::OnMessage(GhostEntity* entity, const Message& msg) { return false; }
[ "ext.johan.medestrom@tieto.com" ]
ext.johan.medestrom@tieto.com
89b3e9c0e32d6fdbc8a6d45fd9e5400bdb36858f
3faab84f3f27cb7095a13a53ccfdd80d0576335c
/openmp/tests/MatrixIoTests.cpp
439c933219832773eabe12fde1c23e3ccd698a93
[]
no_license
AlexIvchenko/itmo-master-1-parallel-programming
afb1c63c8139096404a559ba6309d903c0c96e42
d0fd4631a288b9fc9df36cfd89021d8671d4f9b9
refs/heads/master
2023-04-16T07:38:57.409829
2020-06-24T18:00:54
2020-06-24T18:57:46
259,040,995
0
0
null
2021-04-26T20:19:05
2020-04-26T13:44:05
Java
UTF-8
C++
false
false
396
cpp
#include <gtest/gtest.h> #include "../src/Matrix.h" TEST(MatrixIoTests, RoundTripTest) { Matrix m1 = Matrix(2, 2); m1(0, 0) = 0; m1(0, 1) = 1; m1(1, 0) = 2; m1(1, 1) = 3; Matrix::write_to_file(&m1, "m.txt"); Matrix m2 = *Matrix::read_from_file("m.txt"); ASSERT_EQ(m2(0, 0), 0); ASSERT_EQ(m2(0, 1), 1); ASSERT_EQ(m2(1, 0), 2); ASSERT_EQ(m2(1, 1), 3); }
[ "A.S.Ivchenko@yandex.ru" ]
A.S.Ivchenko@yandex.ru
12c1e8368909ccfe1186b013c3f8ccee75b689d3
11e1311563f5bec80018e772c710557510dcb610
/lib/Diagnostic/Engine.cpp
9a7ed8505b1591e2f39b1a5dda3c80e7623f30ce
[]
permissive
ffk0716/onnc
03e42654b6707e361e3a9d8df176e624d5267032
91e4955ade64b479db17aaeccacf4b7339fe44d2
refs/heads/master
2020-03-26T14:41:35.911135
2018-08-26T14:23:16
2018-08-26T14:23:16
144,999,938
1
0
BSD-3-Clause
2018-08-16T14:33:31
2018-08-16T14:33:30
null
UTF-8
C++
false
false
2,124
cpp
//===- DiagnosticEngine.cpp -----------------------------------------------===// // // The ONNC Project // // See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include <onnc/Diagnostic/Engine.h> #include <onnc/Diagnostic/Diagnostic.h> #include <onnc/Diagnostic/Policy.h> #include <onnc/Diagnostic/StreamLog.h> #include <onnc/Diagnostic/MsgHandler.h> #include <onnc/Support/IOStream.h> #include <cassert> using namespace onnc; using namespace onnc::diagnostic; //===----------------------------------------------------------------------===// // Engine //===----------------------------------------------------------------------===// Engine::Engine() : m_pLogger(new StreamLog(outs())) { m_pLogger->start(); } Engine::~Engine() { m_pLogger->stop(); delete m_pLogger; } void Engine::delegate(Logger* pLogger) { if (nullptr != pLogger) { m_pLogger->stop(); delete m_pLogger; m_pLogger = pLogger; m_pLogger->start(); } } bool Engine::hasError() const { return (m_pLogger->getNumErrors() > 0); } diagnostic::MsgHandler diagnostic::Engine::report(unsigned int pID, Severity pSeverity) { state().ID = pID; state().CurrentSeverity = pSeverity; state().Format = m_InfoMap.description(pID); // The desturctor of MsgHandler calls back Engine::emit() MsgHandler result(*this); return result; } diagnostic::MsgHandler diagnostic::Engine::report(StringRef pMesg, Severity pSeverity) { state().ID = generic_note; state().CurrentSeverity = pSeverity; state().Format = pMesg; // The desturctor of MsgHandler calls back Engine::emit() MsgHandler result(*this); return result; } //===----------------------------------------------------------------------===// // Engine::State //===----------------------------------------------------------------------===// diagnostic::State::State() : Format(), NumOfArgs(0), ID(0), CurrentSeverity(None) { } void diagnostic::State::reset() { Format = StringRef(); NumOfArgs = 0; ID = 0; CurrentSeverity = None; }
[ "a127a127@skymizer.com" ]
a127a127@skymizer.com
5600b460a83db8f31e085747c0a2b095e6566eba
462353333f5fc8f13e12db89720d8668a96e3639
/ftc265-lib/src/main/cpp/Eigen/src/Core/arch/SSE/Complex.h
2fc3eff41eced0ece9be2431c07b334c82668572
[]
no_license
mcm001/android-aruco
c397fdd786bd87945a21aeb82170e4782a7ad3f7
522f262a81736ce034ae993ff66332cf24693b7b
refs/heads/master
2023-03-27T08:31:26.984086
2021-03-10T19:40:37
2021-03-10T19:40:37
346,417,421
0
1
null
2021-03-14T16:10:57
2021-03-10T16:18:55
C++
UTF-8
C++
false
false
20,729
h
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2010 Gael Guennebaud <gael.guennebaud@inria.fr> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef EIGEN_COMPLEX_SSE_H #define EIGEN_COMPLEX_SSE_H #include "../../util/Macros.h" namespace Eigen { namespace internal { //---------- float ---------- struct Packet2cf { EIGEN_STRONG_INLINE Packet2cf() {} EIGEN_STRONG_INLINE explicit Packet2cf(const __m128 &a) : v(a) {} __m128 v; }; // Use the packet_traits defined in AVX/PacketMath.h instead if we're going // to leverage AVX instructions. #ifndef EIGEN_VECTORIZE_AVX template<> struct packet_traits<std::complex < float> > : default_packet_traits { typedef Packet2cf type; typedef Packet2cf half; enum { Vectorizable = 1, AlignedOnScalar = 1, size = 2, HasHalfPacket = 0, HasAdd = 1, HasSub = 1, HasMul = 1, HasDiv = 1, HasNegate = 1, HasAbs = 0, HasAbs2 = 0, HasMin = 0, HasMax = 0, HasSetLinear = 0, HasBlend = 1 }; }; #endif template<> struct unpacket_traits<Packet2cf> { typedef std::complex<float> type; enum { size = 2, alignment = Aligned16 }; typedef Packet2cf half; }; template<> EIGEN_STRONG_INLINE Packet2cf padd<Packet2cf>(const Packet2cf &a, const Packet2cf &b) { return Packet2cf(_mm_add_ps(a.v, b.v)); } template<> EIGEN_STRONG_INLINE Packet2cf psub<Packet2cf>(const Packet2cf &a, const Packet2cf &b) { return Packet2cf(_mm_sub_ps(a.v, b.v)); } template<> EIGEN_STRONG_INLINE Packet2cf pnegate(const Packet2cf &a) { const __m128 mask = _mm_castsi128_ps( _mm_setr_epi32(0x80000000, 0x80000000, 0x80000000, 0x80000000)); return Packet2cf(_mm_xor_ps(a.v, mask)); } template<> EIGEN_STRONG_INLINE Packet2cf pconj(const Packet2cf &a) { const __m128 mask = _mm_castsi128_ps( _mm_setr_epi32(0x00000000, 0x80000000, 0x00000000, 0x80000000)); return Packet2cf(_mm_xor_ps(a.v, mask)); } template<> EIGEN_STRONG_INLINE Packet2cf pmul<Packet2cf>(const Packet2cf &a, const Packet2cf &b) { #ifdef EIGEN_VECTORIZE_SSE3 return Packet2cf(_mm_addsub_ps(_mm_mul_ps(_mm_moveldup_ps(a.v), b.v), _mm_mul_ps(_mm_movehdup_ps(a.v), vec4f_swizzle1(b.v, 1, 0, 3, 2)))); // return Packet2cf(_mm_addsub_ps(_mm_mul_ps(vec4f_swizzle1(a.v, 0, 0, 2, 2), b.v), // _mm_mul_ps(vec4f_swizzle1(a.v, 1, 1, 3, 3), // vec4f_swizzle1(b.v, 1, 0, 3, 2)))); #else const __m128 mask = _mm_castsi128_ps( _mm_setr_epi32(0x80000000, 0x00000000, 0x80000000, 0x00000000)); return Packet2cf(_mm_add_ps(_mm_mul_ps(vec4f_swizzle1(a.v, 0, 0, 2, 2), b.v), _mm_xor_ps(_mm_mul_ps(vec4f_swizzle1(a.v, 1, 1, 3, 3), vec4f_swizzle1(b.v, 1, 0, 3, 2)), mask))); #endif } template<> EIGEN_STRONG_INLINE Packet2cf pand<Packet2cf>(const Packet2cf &a, const Packet2cf &b) { return Packet2cf(_mm_and_ps(a.v, b.v)); } template<> EIGEN_STRONG_INLINE Packet2cf por<Packet2cf>(const Packet2cf &a, const Packet2cf &b) { return Packet2cf(_mm_or_ps(a.v, b.v)); } template<> EIGEN_STRONG_INLINE Packet2cf pxor<Packet2cf>(const Packet2cf &a, const Packet2cf &b) { return Packet2cf(_mm_xor_ps(a.v, b.v)); } template<> EIGEN_STRONG_INLINE Packet2cf pandnot<Packet2cf>(const Packet2cf &a, const Packet2cf &b) { return Packet2cf(_mm_andnot_ps(a.v, b.v)); } template<> EIGEN_STRONG_INLINE Packet2cf pload<Packet2cf>(const std::complex<float> *from) { EIGEN_DEBUG_ALIGNED_LOAD return Packet2cf(pload < Packet4f > (&numext::real_ref(*from))); } template<> EIGEN_STRONG_INLINE Packet2cf ploadu<Packet2cf>(const std::complex<float> *from) { EIGEN_DEBUG_UNALIGNED_LOAD return Packet2cf(ploadu < Packet4f > (&numext::real_ref(*from))); } template<> EIGEN_STRONG_INLINE Packet2cf pset1<Packet2cf>(const std::complex<float> &from) { Packet2cf res; #if EIGEN_GNUC_AT_MOST(4, 2) // Workaround annoying "may be used uninitialized in this function" warning with gcc 4.2 res.v = _mm_loadl_pi(_mm_set1_ps(0.0f), reinterpret_cast<const __m64*>(&from)); #elif EIGEN_GNUC_AT_LEAST(4, 6) // Suppress annoying "may be used uninitialized in this function" warning with gcc >= 4.6 #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wuninitialized" res.v = _mm_loadl_pi(res.v, (const __m64*)&from); #pragma GCC diagnostic pop #else res.v = _mm_loadl_pi(res.v, (const __m64 *) &from); #endif return Packet2cf(_mm_movelh_ps(res.v, res.v)); } template<> EIGEN_STRONG_INLINE Packet2cf ploaddup<Packet2cf>(const std::complex<float> *from) { return pset1 < Packet2cf > (*from); } template<> EIGEN_STRONG_INLINE void pstore<std::complex < float> >( std::complex<float> *to, const Packet2cf &from ) { EIGEN_DEBUG_ALIGNED_STORE pstore(&numext::real_ref(*to), Packet4f(from.v)); } template<> EIGEN_STRONG_INLINE void pstoreu<std::complex < float> >( std::complex<float> *to, const Packet2cf &from ) { EIGEN_DEBUG_UNALIGNED_STORE pstoreu(&numext::real_ref(*to), Packet4f(from.v)); } template<> EIGEN_DEVICE_FUNC inline Packet2cf pgather <std::complex<float>, Packet2cf>( const std::complex<float> *from, Index stride) { return Packet2cf (_mm_set_ps(std::imag(from[1 * stride]), std::real(from[1 * stride]), std::imag(from[0 * stride]), std::real(from[0 * stride]))); } template<> EIGEN_DEVICE_FUNC inline void pscatter<std::complex < float>, Packet2cf >( std::complex<float> *to, const Packet2cf &from, Index stride) { to[stride*0] = std::complex<float>(_mm_cvtss_f32(_mm_shuffle_ps(from.v, from.v, 0)), _mm_cvtss_f32(_mm_shuffle_ps(from.v, from.v, 1)) ); to[stride*1] = std::complex<float>(_mm_cvtss_f32(_mm_shuffle_ps(from.v, from.v, 2)), _mm_cvtss_f32(_mm_shuffle_ps(from.v, from.v, 3)) ); } template<> EIGEN_STRONG_INLINE void prefetch<std::complex < float> >( const std::complex<float> *addr ) { _mm_prefetch((SsePrefetchPtrType)(addr), _MM_HINT_T0 ); } template<> EIGEN_STRONG_INLINE std::complex<float> pfirst<Packet2cf>(const Packet2cf &a) { #if EIGEN_GNUC_AT_MOST(4, 3) // Workaround gcc 4.2 ICE - this is not performance wise ideal, but who cares... // This workaround also fix invalid code generation with gcc 4.3 EIGEN_ALIGN16 std::complex<float> res[2]; _mm_store_ps((float*)res, a.v); return res[0]; #else std::complex<float> res; _mm_storel_pi((__m64 * ) & res, a.v); return res; #endif } template<> EIGEN_STRONG_INLINE Packet2cf preverse(const Packet2cf &a) { return Packet2cf(_mm_castpd_ps(preverse(Packet2d(_mm_castps_pd(a.v))))); } template<> EIGEN_STRONG_INLINE std::complex<float> predux<Packet2cf>(const Packet2cf &a) { return pfirst(Packet2cf(_mm_add_ps(a.v, _mm_movehl_ps(a.v, a.v)))); } template<> EIGEN_STRONG_INLINE Packet2cf preduxp<Packet2cf>(const Packet2cf *vecs) { return Packet2cf( _mm_add_ps(_mm_movelh_ps(vecs[0].v, vecs[1].v), _mm_movehl_ps(vecs[1].v, vecs[0].v))); } template<> EIGEN_STRONG_INLINE std::complex<float> predux_mul<Packet2cf>(const Packet2cf &a) { return pfirst(pmul(a, Packet2cf(_mm_movehl_ps(a.v, a.v)))); } template<int Offset> struct palign_impl<Offset, Packet2cf> { static EIGEN_STRONG_INLINE void run(Packet2cf &first, const Packet2cf &second) { if (Offset == 1) { first.v = _mm_movehl_ps(first.v, first.v); first.v = _mm_movelh_ps(first.v, second.v); } } }; template<> struct conj_helper<Packet2cf, Packet2cf, false, true> { EIGEN_STRONG_INLINE Packet2cf pmadd(const Packet2cf &x, const Packet2cf &y, const Packet2cf &c) const { return padd(pmul(x, y), c); } EIGEN_STRONG_INLINE Packet2cf pmul(const Packet2cf &a, const Packet2cf &b) const { #ifdef EIGEN_VECTORIZE_SSE3 return internal::pmul(a, pconj(b)); #else const __m128 mask = _mm_castsi128_ps( _mm_setr_epi32(0x00000000, 0x80000000, 0x00000000, 0x80000000)); return Packet2cf( _mm_add_ps(_mm_xor_ps(_mm_mul_ps(vec4f_swizzle1(a.v, 0, 0, 2, 2), b.v), mask), _mm_mul_ps(vec4f_swizzle1(a.v, 1, 1, 3, 3), vec4f_swizzle1(b.v, 1, 0, 3, 2)))); #endif } }; template<> struct conj_helper<Packet2cf, Packet2cf, true, false> { EIGEN_STRONG_INLINE Packet2cf pmadd(const Packet2cf &x, const Packet2cf &y, const Packet2cf &c) const { return padd(pmul(x, y), c); } EIGEN_STRONG_INLINE Packet2cf pmul(const Packet2cf &a, const Packet2cf &b) const { #ifdef EIGEN_VECTORIZE_SSE3 return internal::pmul(pconj(a), b); #else const __m128 mask = _mm_castsi128_ps( _mm_setr_epi32(0x00000000, 0x80000000, 0x00000000, 0x80000000)); return Packet2cf(_mm_add_ps(_mm_mul_ps(vec4f_swizzle1(a.v, 0, 0, 2, 2), b.v), _mm_xor_ps(_mm_mul_ps(vec4f_swizzle1(a.v, 1, 1, 3, 3), vec4f_swizzle1(b.v, 1, 0, 3, 2)), mask))); #endif } }; template<> struct conj_helper<Packet2cf, Packet2cf, true, true> { EIGEN_STRONG_INLINE Packet2cf pmadd(const Packet2cf &x, const Packet2cf &y, const Packet2cf &c) const { return padd(pmul(x, y), c); } EIGEN_STRONG_INLINE Packet2cf pmul(const Packet2cf &a, const Packet2cf &b) const { #ifdef EIGEN_VECTORIZE_SSE3 return pconj(internal::pmul(a, b)); #else const __m128 mask = _mm_castsi128_ps( _mm_setr_epi32(0x00000000, 0x80000000, 0x00000000, 0x80000000)); return Packet2cf( _mm_sub_ps(_mm_xor_ps(_mm_mul_ps(vec4f_swizzle1(a.v, 0, 0, 2, 2), b.v), mask), _mm_mul_ps(vec4f_swizzle1(a.v, 1, 1, 3, 3), vec4f_swizzle1(b.v, 1, 0, 3, 2)))); #endif } }; EIGEN_MAKE_CONJ_HELPER_CPLX_REAL(Packet2cf, Packet4f ) template<> EIGEN_STRONG_INLINE Packet2cf pdiv<Packet2cf>(const Packet2cf &a, const Packet2cf &b) { // TODO optimize it for SSE3 and 4 Packet2cf res = conj_helper<Packet2cf, Packet2cf, false, true>().pmul(a, b); __m128 s = _mm_mul_ps(b.v, b.v); return Packet2cf(_mm_div_ps(res.v, _mm_add_ps(s, _mm_castsi128_ps( _mm_shuffle_epi32(_mm_castps_si128(s), 0xb1))))); } EIGEN_STRONG_INLINE Packet2cf pcplxflip/* <Packet2cf> */(const Packet2cf &x) { return Packet2cf(vec4f_swizzle1(x.v, 1, 0, 3, 2)); } //---------- double ---------- struct Packet1cd { EIGEN_STRONG_INLINE Packet1cd() {} EIGEN_STRONG_INLINE explicit Packet1cd(const __m128d &a) : v(a) {} __m128d v; }; // Use the packet_traits defined in AVX/PacketMath.h instead if we're going // to leverage AVX instructions. #ifndef EIGEN_VECTORIZE_AVX template<> struct packet_traits<std::complex < double> > : default_packet_traits { typedef Packet1cd type; typedef Packet1cd half; enum { Vectorizable = 1, AlignedOnScalar = 0, size = 1, HasHalfPacket = 0, HasAdd = 1, HasSub = 1, HasMul = 1, HasDiv = 1, HasNegate = 1, HasAbs = 0, HasAbs2 = 0, HasMin = 0, HasMax = 0, HasSetLinear = 0 }; }; #endif template<> struct unpacket_traits<Packet1cd> { typedef std::complex<double> type; enum { size = 1, alignment = Aligned16 }; typedef Packet1cd half; }; template<> EIGEN_STRONG_INLINE Packet1cd padd<Packet1cd>(const Packet1cd &a, const Packet1cd &b) { return Packet1cd(_mm_add_pd(a.v, b.v)); } template<> EIGEN_STRONG_INLINE Packet1cd psub<Packet1cd>(const Packet1cd &a, const Packet1cd &b) { return Packet1cd(_mm_sub_pd(a.v, b.v)); } template<> EIGEN_STRONG_INLINE Packet1cd pnegate(const Packet1cd &a) { return Packet1cd(pnegate(Packet2d(a.v))); } template<> EIGEN_STRONG_INLINE Packet1cd pconj(const Packet1cd &a) { const __m128d mask = _mm_castsi128_pd(_mm_set_epi32(0x80000000, 0x0, 0x0, 0x0)); return Packet1cd(_mm_xor_pd(a.v, mask)); } template<> EIGEN_STRONG_INLINE Packet1cd pmul<Packet1cd>(const Packet1cd &a, const Packet1cd &b) { #ifdef EIGEN_VECTORIZE_SSE3 return Packet1cd(_mm_addsub_pd(_mm_mul_pd(_mm_movedup_pd(a.v), b.v), _mm_mul_pd(vec2d_swizzle1(a.v, 1, 1), vec2d_swizzle1(b.v, 1, 0)))); #else const __m128d mask = _mm_castsi128_pd(_mm_set_epi32(0x0, 0x0, 0x80000000, 0x0)); return Packet1cd(_mm_add_pd(_mm_mul_pd(vec2d_swizzle1(a.v, 0, 0), b.v), _mm_xor_pd(_mm_mul_pd(vec2d_swizzle1(a.v, 1, 1), vec2d_swizzle1(b.v, 1, 0)), mask))); #endif } template<> EIGEN_STRONG_INLINE Packet1cd pand<Packet1cd>(const Packet1cd &a, const Packet1cd &b) { return Packet1cd(_mm_and_pd(a.v, b.v)); } template<> EIGEN_STRONG_INLINE Packet1cd por<Packet1cd>(const Packet1cd &a, const Packet1cd &b) { return Packet1cd(_mm_or_pd(a.v, b.v)); } template<> EIGEN_STRONG_INLINE Packet1cd pxor<Packet1cd>(const Packet1cd &a, const Packet1cd &b) { return Packet1cd(_mm_xor_pd(a.v, b.v)); } template<> EIGEN_STRONG_INLINE Packet1cd pandnot<Packet1cd>(const Packet1cd &a, const Packet1cd &b) { return Packet1cd(_mm_andnot_pd(a.v, b.v)); } // FIXME force unaligned load, this is a temporary fix template<> EIGEN_STRONG_INLINE Packet1cd pload<Packet1cd>(const std::complex<double> *from) { EIGEN_DEBUG_ALIGNED_LOAD return Packet1cd(pload < Packet2d > ((const double *) from)); } template<> EIGEN_STRONG_INLINE Packet1cd ploadu<Packet1cd>(const std::complex<double> *from) { EIGEN_DEBUG_UNALIGNED_LOAD return Packet1cd(ploadu < Packet2d > ((const double *) from)); } template<> EIGEN_STRONG_INLINE Packet1cd pset1<Packet1cd>( const std::complex<double> &from) { /* here we really have to use unaligned loads :( */ return ploadu < Packet1cd > (&from); } template<> EIGEN_STRONG_INLINE Packet1cd ploaddup<Packet1cd>(const std::complex<double> *from) { return pset1 < Packet1cd > (*from); } // FIXME force unaligned store, this is a temporary fix template<> EIGEN_STRONG_INLINE void pstore<std::complex < double> >( std::complex<double> *to, const Packet1cd &from ) { EIGEN_DEBUG_ALIGNED_STORE pstore((double *) to, Packet2d(from.v)); } template<> EIGEN_STRONG_INLINE void pstoreu<std::complex < double> >( std::complex<double> *to, const Packet1cd &from ) { EIGEN_DEBUG_UNALIGNED_STORE pstoreu((double *) to, Packet2d(from.v)); } template<> EIGEN_STRONG_INLINE void prefetch<std::complex < double> >( const std::complex<double> *addr ) { _mm_prefetch((SsePrefetchPtrType)(addr), _MM_HINT_T0 ); } template<> EIGEN_STRONG_INLINE std::complex<double> pfirst<Packet1cd>(const Packet1cd &a) { EIGEN_ALIGN16 double res[2]; _mm_store_pd(res, a.v); return std::complex<double>(res[0], res[1]); } template<> EIGEN_STRONG_INLINE Packet1cd preverse(const Packet1cd &a) { return a; } template<> EIGEN_STRONG_INLINE std::complex<double> predux<Packet1cd>(const Packet1cd &a) { return pfirst(a); } template<> EIGEN_STRONG_INLINE Packet1cd preduxp<Packet1cd>(const Packet1cd *vecs) { return vecs[0]; } template<> EIGEN_STRONG_INLINE std::complex<double> predux_mul<Packet1cd>(const Packet1cd &a) { return pfirst(a); } template<int Offset> struct palign_impl<Offset, Packet1cd> { static EIGEN_STRONG_INLINE void run(Packet1cd & /*first*/, const Packet1cd & /*second*/) { // FIXME is it sure we never have to align a Packet1cd? // Even though a std::complex<double> has 16 bytes, it is not necessarily aligned on a 16 bytes boundary... } }; template<> struct conj_helper<Packet1cd, Packet1cd, false, true> { EIGEN_STRONG_INLINE Packet1cd pmadd(const Packet1cd &x, const Packet1cd &y, const Packet1cd &c) const { return padd(pmul(x, y), c); } EIGEN_STRONG_INLINE Packet1cd pmul(const Packet1cd &a, const Packet1cd &b) const { #ifdef EIGEN_VECTORIZE_SSE3 return internal::pmul(a, pconj(b)); #else const __m128d mask = _mm_castsi128_pd(_mm_set_epi32(0x80000000, 0x0, 0x0, 0x0)); return Packet1cd(_mm_add_pd(_mm_xor_pd(_mm_mul_pd(vec2d_swizzle1(a.v, 0, 0), b.v), mask), _mm_mul_pd(vec2d_swizzle1(a.v, 1, 1), vec2d_swizzle1(b.v, 1, 0)))); #endif } }; template<> struct conj_helper<Packet1cd, Packet1cd, true, false> { EIGEN_STRONG_INLINE Packet1cd pmadd(const Packet1cd &x, const Packet1cd &y, const Packet1cd &c) const { return padd(pmul(x, y), c); } EIGEN_STRONG_INLINE Packet1cd pmul(const Packet1cd &a, const Packet1cd &b) const { #ifdef EIGEN_VECTORIZE_SSE3 return internal::pmul(pconj(a), b); #else const __m128d mask = _mm_castsi128_pd(_mm_set_epi32(0x80000000, 0x0, 0x0, 0x0)); return Packet1cd(_mm_add_pd(_mm_mul_pd(vec2d_swizzle1(a.v, 0, 0), b.v), _mm_xor_pd(_mm_mul_pd(vec2d_swizzle1(a.v, 1, 1), vec2d_swizzle1(b.v, 1, 0)), mask))); #endif } }; template<> struct conj_helper<Packet1cd, Packet1cd, true, true> { EIGEN_STRONG_INLINE Packet1cd pmadd(const Packet1cd &x, const Packet1cd &y, const Packet1cd &c) const { return padd(pmul(x, y), c); } EIGEN_STRONG_INLINE Packet1cd pmul(const Packet1cd &a, const Packet1cd &b) const { #ifdef EIGEN_VECTORIZE_SSE3 return pconj(internal::pmul(a, b)); #else const __m128d mask = _mm_castsi128_pd(_mm_set_epi32(0x80000000, 0x0, 0x0, 0x0)); return Packet1cd(_mm_sub_pd(_mm_xor_pd(_mm_mul_pd(vec2d_swizzle1(a.v, 0, 0), b.v), mask), _mm_mul_pd(vec2d_swizzle1(a.v, 1, 1), vec2d_swizzle1(b.v, 1, 0)))); #endif } }; EIGEN_MAKE_CONJ_HELPER_CPLX_REAL(Packet1cd, Packet2d ) template<> EIGEN_STRONG_INLINE Packet1cd pdiv<Packet1cd>(const Packet1cd &a, const Packet1cd &b) { // TODO optimize it for SSE3 and 4 Packet1cd res = conj_helper<Packet1cd, Packet1cd, false, true>().pmul(a, b); __m128d s = _mm_mul_pd(b.v, b.v); return Packet1cd(_mm_div_pd(res.v, _mm_add_pd(s, _mm_shuffle_pd(s, s, 0x1)))); } EIGEN_STRONG_INLINE Packet1cd pcplxflip/* <Packet1cd> */(const Packet1cd &x) { return Packet1cd(preverse(Packet2d(x.v))); } EIGEN_DEVICE_FUNC inline void ptranspose(PacketBlock<Packet2cf, 2> &kernel) { __m128d w1 = _mm_castps_pd(kernel.packet[0].v); __m128d w2 = _mm_castps_pd(kernel.packet[1].v); __m128 tmp = _mm_castpd_ps(_mm_unpackhi_pd(w1, w2)); kernel.packet[0].v = _mm_castpd_ps(_mm_unpacklo_pd(w1, w2)); kernel.packet[1].v = tmp; } template<> EIGEN_STRONG_INLINE Packet2cf pblend(const Selector<2> &ifPacket, const Packet2cf &thenPacket, const Packet2cf &elsePacket) { __m128d result = pblend < Packet2d > (ifPacket, _mm_castps_pd(thenPacket.v), _mm_castps_pd(elsePacket.v)); return Packet2cf(_mm_castpd_ps(result)); } template<> EIGEN_STRONG_INLINE Packet2cf pinsertfirst(const Packet2cf &a, std::complex<float> b) { return Packet2cf(_mm_loadl_pi(a.v, reinterpret_cast<const __m64 *>(&b))); } template<> EIGEN_STRONG_INLINE Packet1cd pinsertfirst(const Packet1cd &, std::complex<double> b) { return pset1 < Packet1cd > (b); } template<> EIGEN_STRONG_INLINE Packet2cf pinsertlast(const Packet2cf &a, std::complex<float> b) { return Packet2cf(_mm_loadh_pi(a.v, reinterpret_cast<const __m64 *>(&b))); } template<> EIGEN_STRONG_INLINE Packet1cd pinsertlast(const Packet1cd &, std::complex<double> b) { return pset1 < Packet1cd > (b); } } // end namespace internal } // end namespace Eigen #endif // EIGEN_COMPLEX_SSE_H
[ "matthew.morley.ca@gmail.com" ]
matthew.morley.ca@gmail.com
28d3130fdbe877456294d0e4027ab47013017c5b
162fe41a4d7b929022fbfc0ef577108c1d1706a9
/Leetcode/cpp/752_Open_The_Lock.cpp
0b3802d867d5c543a220907da4534aa3d41a33fe
[]
no_license
LilyLin16/CodeingDiary
ec467f07ee32d72662b04673ca426eb6d5b2f86f
6c96db035565ca243e654a51e90920bc2ea66fcb
refs/heads/master
2022-04-22T02:59:28.689346
2020-04-22T07:14:44
2020-04-22T07:14:44
257,817,319
0
0
null
null
null
null
GB18030
C++
false
false
2,527
cpp
/** You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot. The lock initially starts at '0000', a string representing the state of the 4 wheels. You are given a list of deadends dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it. Given a target representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible. **/ #include <iostream> #include <string> #include <queue> #include <unordered_set> using namespace std; // 将 s[j] 向上拨动一次 void plusOne(string &s, int j) { // s[j] = ((s[j] - '0') + 1) % 10 + '0'; if(s[j] == '9') { s[j] = '0'; } else { s[j] += 1; } } // 将 s[j] 向下拨动一次 void minusOne(string &s, int j) { // s[j] = ((s[j] - '0') + 9) % 10 + '0'; if (s[j] == '0') { s[j] = '9'; } else { s[j] -= 1; } } int openLock(vector<string>& deadends, string target) { /* 记录需要跳过的死亡密码 */ unordered_set<string> deadlocks(deadends.begin(), deadends.end()); if (deadlocks.find("0000") != end(deadlocks)) { return -1; } int step = 0; /* 记录已经穷举过的密码,防止走回头路 */ unordered_set<string> visited{ {"0000"} }; /* 从起点开始启动广度优先搜索 */ queue<string> q; q.push("0000"); while (!q.empty()) { int sz = q.size(); /* 将当前队列中的所有节点向周围扩散 */ for (int i = sz; i > 0; i--) { string cur = q.front(); q.pop(); /* 判断是否到达终点 */ if (deadlocks.find(cur) != end(deadlocks)) continue; if (cur == target) { return step; } /* 将一个节点的未遍历相邻节点加入队列 */ for (int j = 0; j < 4; j++) { string up = cur; plusOne(up, j); if (visited.find(up) == end(visited)) { q.push(up); visited.insert(up); } string down = cur; minusOne(down, j); if (visited.find(down) == end(visited)) { q.push(down); visited.insert(down); } } } step++; } return -1; } int main() { string target = "0202"; vector<string> deadends{ "0201", "0101", "0102", "1212", "2002" }; int step = openLock(deadends, target); cout << step << endl; system("pause"); return 0; }
[ "726693267@qq.com" ]
726693267@qq.com
87cb95dff445eb45436de42e7077b648ab50e126
3448a43cf0635866b25e5d513dd60fb003f47e29
/src/xrEngine/xr_object.cpp
17082e60e4404bd8936d206e086ea978c59e3937
[ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ]
permissive
xrLil-Batya/cordisproject
49632acc5e68bea9847d001d82fb049703d223c2
24275a382fec62a4e58d11579bf497b894f220ba
refs/heads/master
2023-03-19T01:17:25.170059
2020-11-17T14:22:06
2020-11-17T14:22:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
555
cpp
#include "stdafx.h" #include "IGame_Level.h" #include "xr_object.h" #include "xrCDB/xr_area.h" #include "Render.h" #include "Common/LevelStructure.hpp" #include "xrGame/Render/Kernel/RenderVisual.h" #include "xrGame/Render/Kernel/Kinematics.h" #include "x_ray.h" #include "GameFont.h" #include "mp_logging.h" #include "xr_collide_form.h" void CObjectList::o_crow(IGameObject* O) { Objects& crows = get_crows(); VERIFY(std::find(crows.begin(), crows.end(), O) == crows.end()); crows.push_back(O); O->SetCrowUpdateFrame(Device.dwFrame); }
[ "phantom1020@yandex.ru" ]
phantom1020@yandex.ru
69d86c560e2ef42242c1ad2287ea4ce04e865f21
ec3a06eddbf237ddefe44ac6f5c64f27f8c4fe58
/C++/Chapter 6/Chapter 6/stdafx.cpp
c2cc2d784752805aedb9e00d8b4956e8d150ed70
[]
no_license
ArcticZeroo/Semester-2-Projects
25a34055e4d161583959b385e9cb84bb2f682472
7fb41a2a457cd3f6c0240a9dc32a8e86449d2143
refs/heads/master
2020-04-02T06:26:05.075574
2016-06-16T13:07:53
2016-06-16T13:07:57
61,293,513
0
0
null
null
null
null
UTF-8
C++
false
false
288
cpp
// stdafx.cpp : source file that includes just the standard includes // Chapter 6.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ "novick.spencer@gmail.com" ]
novick.spencer@gmail.com
0075516bbb6c914118635b1f755af27b38aca44b
3edd3da6213c96cf342dc842e8b43fe2358c960d
/abc/abc057/a/main.cpp
e72dbee504fc7448b0d4b16e30c96f6d56d55d10
[]
no_license
tic40/atcoder
7c5d12cc147741d90a1f5f52ceddd708b103bace
3c8ff68fe73e101baa2aff955bed077cae893e52
refs/heads/main
2023-08-30T20:10:32.191136
2023-08-30T00:58:07
2023-08-30T00:58:07
179,283,303
0
0
null
null
null
null
UTF-8
C++
false
false
184
cpp
#include <bits/stdc++.h> using namespace std; #define REP(i, n) for(int i = 0; i < n; i++) using ll = long long; int main() { int a, b; cin >> a >> b; cout << (a+b)%24 << endl; }
[ "ccpzjoh@gmail.com" ]
ccpzjoh@gmail.com
906983746d931e1b9ed8bf067b89ae4ce34035a3
1f4d461a5566bd6718ef48bbfe8d4cad3ce131d5
/polymesh.h
e973e0de4ebfd9312ff8a1b28160dcf217694ef9
[]
no_license
RupertDean/ACG
f0309ec6b5592351d7f3cccf2664af51029a113b
af3c7aade66bfbf3385b79f0a23577cb0b9129d5
refs/heads/main
2023-02-11T20:07:07.029107
2021-01-07T14:24:47
2021-01-07T14:24:47
327,634,023
0
0
null
null
null
null
UTF-8
C++
false
false
1,085
h
/*************************************************************************** * * krt - Kens Raytracer - Coursework Edition. (C) Copyright 1997-2019. * * Do what you like with this code as long as you retain this comment. */ #pragma once #include "vertex.h" #include "transform.h" #include "object.h" typedef int TriangleIndex[3]; class PolyMesh : public Object{ public: int vertex_count; int triangle_count; Vertex *vertex; Vector *face_normal; Vector *vertex_normal; TriangleIndex *triangle; void do_construct(char *file, Transform *transform); float test_edge(Vector &normal, Vertex &p, Vertex &v1, Vertex &v0); void triangle_intersection(Ray ray, Hit &hit, int which_triangle); void intersection(Ray ray, Hit &hit); void compute_face_normal(int which_triangle, Vector &normal); void compute_vertex_normals(void); bool rayTriangleIntersect(const Ray& ray, const Vector &v0, const Vector &v1, const Vector &v2, float &t); PolyMesh(char *file); PolyMesh(char *file, Transform *transform); ~PolyMesh(){} };
[ "noreply@github.com" ]
RupertDean.noreply@github.com
1d85ff6b8381657612e73a532d2c8f91e8382c63
331e63f76403f347bf45d52b2b72e999a15d26a7
/SIN/SIN_CORE/SINCommon/Src/SINNamer.cpp
89e9c945833e317b197f5151430ba5f13581eb82
[]
no_license
koutsop/sinmetalanguage
64c9dd10d65c89b169aa0d1dec3bd14cf14165f6
7ef17948ae3a6fd4c3589429e9862d1cbfbec80c
refs/heads/master
2021-01-10T20:08:40.852870
2010-05-23T17:42:04
2010-05-23T17:42:04
33,115,739
0
0
null
null
null
null
UTF-8
C++
false
false
1,322
cpp
#include "SINNamer.h" #include <cstdio> #include <cstring> namespace SIN { //---------------------------------------------------------------- Namer::Namer(char const _base[SINNAMER_BASELEN]): counter(0x00ul), base_offset(min<size_t>(strlen(_base), SINNAMER_BASELEN)), number_maximun_length(ULONG_MAX_STR_LEN) { strncpy(base, _base, SINNAMER_BASELEN); } //---------------------------------------------------------------- Namer::Namer(Namer const &_other): counter(_other.counter), base_offset(_other.base_offset), number_maximun_length(_other.number_maximun_length) { strncpy(base, _other.base, SINNAMER_BASELEN); } //---------------------------------------------------------------- Namer::~Namer(void) {} //---------------------------------------------------------------- char const *Namer::operator ++(void) { sprintf(base + base_offset, "%0*lu", number_maximun_length, ++counter); return base; } //---------------------------------------------------------------- char const *Namer::operator ++(int) { sprintf(base + base_offset, "%0*lu", number_maximun_length, counter++); return base; } } // namespace SIN
[ "koutsop@6a7033b6-9ebc-11de-a8ff-c955b97a4a10" ]
koutsop@6a7033b6-9ebc-11de-a8ff-c955b97a4a10
325aceb9d076069119b411eb3248875614c928f8
b39446a01e5270c983614000f36ed7776c37fd5a
/code_snippets/Chapter25/chapter.25.5.2.cpp
240a663e6d69a7ebeb2bcbb9402f97b3601d05a1
[ "MIT" ]
permissive
ltr01/stroustrup-ppp-1
aa6e063e11b1dccab854602895e85bef876f2ea5
d9736cc67ef8e2f0483003c8ec35cc0785460cd1
refs/heads/master
2023-01-03T09:16:13.399468
2020-10-28T10:41:25
2020-10-28T10:41:25
261,959,252
1
0
MIT
2020-05-07T05:38:23
2020-05-07T05:38:22
null
UTF-8
C++
false
false
1,480
cpp
// // This is example code from Chapter 25.5.2 "Bitset" of // "Programming -- Principles and Practice Using C++" by Bjarne Stroustrup // #include <bitset> #include <iostream> using namespace std; //------------------------------------------------------------------------------ void test() { bitset<4> flags = 0xb; bitset<128> dword_bits(string("1010101010101010")); bitset<12345> lots; string s; cin>>s; bitset<12345> my_bits(s); // may throw std::invalid_argument bitset<32> b1, b2, b3; b1 = b2&b3; // and b1 = b2|b3; // or b1 = b2^b3; // xor b1 = ~b2; // complement b1 = b2<<2; // shift left b1 = b2>>3; // shift right bitset<32> b; cin>>b; // read a bitset from input cout<<bitset<8>('c'); // output the bit pattern for the character 'c' } //------------------------------------------------------------------------------ int main() try { const int max = 10; bitset<max> b; while (cin>>b) { cout << b << '\n'; for (int i =0; i<max; ++i) cout << b[i]; // reverse order cout << '\n'; } } catch (exception& e) { cerr << "error: " << e.what() << '\n'; return 1; } catch (...) { cerr << "Oops: unknown exception!\n"; return 2; } //------------------------------------------------------------------------------
[ "bewuethr@users.noreply.github.com" ]
bewuethr@users.noreply.github.com
61f03697adc532125da1e926ad049fda57cfaa51
44e0838bac83de8eaaa46fd38939014675a09c6d
/mmapdemo/shm_read.cc
c4f16ece92912b1b7222b344381d7fa479852618
[]
no_license
koritafei/UNIXNetwork
f0726f692613f965f6e3b54c6671cd32c3d3672f
38ab33ed08ac7464b884b1dc96a2158ac7d5d924
refs/heads/main
2023-07-22T08:26:27.248926
2021-09-07T08:55:55
2021-09-07T08:55:55
402,710,087
0
0
null
null
null
null
UTF-8
C++
false
false
1,147
cc
/** * @file shm_read.cc * @author koritafei (koritafei@gmail.com) * @brief * @version 0.1 * @date 2021-09-06 * * @copyright Copyright (c) 2021 * */ #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/ipc.h> #include <sys/mman.h> #include <sys/shm.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #define ERR_EXIT(m) \ do { \ perror(m); \ exit(EXIT_FAILURE); \ } while (0) typedef struct stu { char name[32]; int age; } STU; int main(int argc, char **argv) { int shmid; shmid = shmget(1234, sizeof(STU), IPC_CREAT | 0666); if (-1 == shmid) { ERR_EXIT("shmget"); } STU *p; p = (STU *)shmat(shmid, NULL, 0); if ((void *)-1 == p) { ERR_EXIT("shmat error"); } printf("name = %s, age = %d\n", p->name, p->age); shmdt(p); shmctl(shmid, IPC_RMID, 0); return 0; }
[ "koritafei@gmail.com" ]
koritafei@gmail.com
cb96dc8673b265a4e3d14e28e1d12d9334c59135
fc08b2ccda73c71230bcedff938fe4dc1a7f1759
/epxc/stdafx.cpp
455b19c24c89e6e60dbba0c904ecc76389351756
[]
no_license
daelsepara/PixelScalerWin
d7aa5fce8a978b50f8c96c0834a52a5c1079c082
142f488bb3d243412693957d13869d0ac1bf7a54
refs/heads/master
2021-05-12T00:49:57.550275
2019-08-15T12:17:46
2019-08-15T12:17:46
117,544,294
2
0
null
null
null
null
UTF-8
C++
false
false
283
cpp
// stdafx.cpp : source file that includes just the standard includes // epxc.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ "dael.separa@gmail.com" ]
dael.separa@gmail.com
021053ac08fa7684555fcb80d16911995bd985fe
e763b855be527d69fb2e824dfb693d09e59cdacb
/aws-cpp-sdk-elasticmapreduce/source/EMREndpoint.cpp
1d246967f9dbe203973b6d8f99393a45c247ff58
[ "MIT", "Apache-2.0", "JSON" ]
permissive
34234344543255455465/aws-sdk-cpp
47de2d7bde504273a43c99188b544e497f743850
1d04ff6389a0ca24361523c58671ad0b2cde56f5
refs/heads/master
2023-06-10T16:15:54.618966
2018-05-07T23:32:08
2018-05-07T23:32:08
132,632,360
1
0
Apache-2.0
2023-06-01T23:20:47
2018-05-08T15:56:35
C++
UTF-8
C++
false
false
1,403
cpp
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/elasticmapreduce/EMREndpoint.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <aws/core/utils/HashingUtils.h> using namespace Aws; using namespace Aws::EMR; namespace Aws { namespace EMR { namespace EMREndpoint { static const int CN_REGION_HASH = Aws::Utils::HashingUtils::HashString("cn-north-1"); Aws::String ForRegion(const Aws::String& regionName, bool useDualStack) { auto hash = Aws::Utils::HashingUtils::HashString(regionName.c_str()); Aws::StringStream ss; ss << "elasticmapreduce" << "."; if(useDualStack) { ss << "dualstack."; } ss << regionName << ".amazonaws.com"; if(hash == CN_REGION_HASH) { ss << ".cn"; } return ss.str(); } } // namespace EMREndpoint } // namespace EMR } // namespace Aws
[ "henso@amazon.com" ]
henso@amazon.com
e23f138e590b3c1c00cb7fecab2eea1b1e37fda1
fdd44721689dcf0e842dd6d4af6264162a2b4367
/Qt_Hikvsion_multiThread_Opencv-master/main.cpp
3d293b013cdb9af8ffc7e4523a4f3bc7d46b859f
[]
no_license
geometryl/qt_hikvision
9eeebc192b0e1644bde0a6438d9209c3cb8b7c61
c4ab1dd57e6218a208388998e1a0318f182d335c
refs/heads/master
2022-06-17T09:24:36.179931
2020-05-11T13:19:55
2020-05-11T13:19:55
262,535,937
2
1
null
null
null
null
UTF-8
C++
false
false
210
cpp
#include "mainwindow.h" #include <QApplication> #include <QTextCodec> int main(int argc, char *argv[]) { QApplication a(argc, argv); //chinese MainWindow w; w.show(); return a.exec(); }
[ "jianghe01@baidu.com" ]
jianghe01@baidu.com
7b4157b191ba583619d6eb3321487e8187b7f08d
c5e5a27fee938ea03c5ef2d8ec62194cae87d4ad
/actividad 7/actv 7, pilas, ciclo 02.cpp
eff76e82acd2460ff16f77b82770fef1da4f0dbc
[]
no_license
carolinesierra/portafolio_00091119
219a13024cd2797f4dfebbc2572169f6426f6a57
48824d4277a26c585c0c0d49f90f1d74f5ee44c2
refs/heads/master
2020-07-09T02:28:29.300130
2019-11-12T02:10:51
2019-11-12T02:10:51
203,849,172
0
0
null
null
null
null
UTF-8
C++
false
false
1,329
cpp
Obtener el segundo elemento de una pila, de arriba (top) hacia abajo; dejando la pila sin sus dos elementos de arriba. //Si se debe inicializar la pila c = initialize; valor=0; push (c,H); push (c,O); push (c,L); push (c,A); pop (c); valor = pop(c); //Se guarda el valor del segundo elemento en la variable //Si ya está inicializada contador=0; valor=0; while(no se ha terminado de leer los elementos){ contador++; } if(!empty(c)){ if(contador>=1){ cout << "Solo hay un elemento" << endl; } else if(contador>=2){ pop (c); valor = pop(c); //Se guarda el valor del segundo elemento en la variable } } else{ cout << "La pila está vacía" << endl; } cout << "Segundo valor: " << valor << endl; --------------------------------------------------------------------------------------- Obtenga el elemento que se encuentra al fondo de la pila, dejando la pila vacía. //Si se debe inicializar la pila a = initialize push (a,A); push (a,D); push (a,I); push (a,O); push (a,S); pop (a); pop (a); pop (a); pop (a); fondo = pop (a); //Se guarda el valor del fondo; if (a==empty) cout << "La pila está vacía"; //Si ya está inicializada valor=0; if(empty(c)){ cout << "La pila está vacía" << endl; } else if(!empty(c)){ while(!empty(c)){ valor= pop (c); } } cout << "Último valor: " << valor << endl;
[ "00091119@uca.edu.sv" ]
00091119@uca.edu.sv
27c776e11b20e2b692dda5bbb019b4c54fb17cfa
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/ppapi/proxy/plugin_array_buffer_var.cc
625facfa0a67658c6ba55bfbbde2fb872174c38f
[ "BSD-3-Clause", "LicenseRef-scancode-khronos" ]
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
C++
false
false
3,156
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ppapi/proxy/plugin_array_buffer_var.h" #include <stdlib.h> #include <limits> #include "base/memory/shared_memory.h" #include "ppapi/c/dev/ppb_buffer_dev.h" #include "ppapi/proxy/plugin_dispatcher.h" #include "ppapi/proxy/plugin_globals.h" #include "ppapi/proxy/ppapi_messages.h" #include "ppapi/proxy/serialized_structs.h" #include "ppapi/shared_impl/host_resource.h" #include "ppapi/shared_impl/resource.h" #include "ppapi/thunk/enter.h" #include "ppapi/thunk/ppb_buffer_api.h" using base::SharedMemory; using base::SharedMemoryHandle; using ppapi::proxy::PluginGlobals; using ppapi::proxy::PluginResourceTracker; namespace ppapi { PluginArrayBufferVar::PluginArrayBufferVar(uint32_t size_in_bytes) : buffer_(size_in_bytes), plugin_handle_(base::SharedMemory::NULLHandle()), size_in_bytes_(size_in_bytes) {} PluginArrayBufferVar::PluginArrayBufferVar(uint32_t size_in_bytes, SharedMemoryHandle plugin_handle) : plugin_handle_(plugin_handle), size_in_bytes_(size_in_bytes) {} PluginArrayBufferVar::~PluginArrayBufferVar() { Unmap(); if (shmem_.get() == NULL) { // The SharedMemory destuctor can't close the handle for us. if (SharedMemory::IsHandleValid(plugin_handle_)) SharedMemory::CloseHandle(plugin_handle_); } else { // Delete SharedMemory, if we have one. shmem_.reset(); } } void* PluginArrayBufferVar::Map() { if (shmem_.get()) return shmem_->memory(); if (SharedMemory::IsHandleValid(plugin_handle_)) { shmem_.reset(new SharedMemory(plugin_handle_, false)); if (!shmem_->Map(size_in_bytes_)) { shmem_.reset(); return NULL; } return shmem_->memory(); } if (buffer_.empty()) return NULL; return &(buffer_[0]); } void PluginArrayBufferVar::Unmap() { if (shmem_.get()) shmem_->Unmap(); } uint32_t PluginArrayBufferVar::ByteLength() { return size_in_bytes_; } bool PluginArrayBufferVar::CopyToNewShmem( PP_Instance instance, int* host_handle_id, SharedMemoryHandle* plugin_out_handle) { ppapi::proxy::PluginDispatcher* dispatcher = ppapi::proxy::PluginDispatcher::GetForInstance(instance); if (!dispatcher) return false; ppapi::proxy::SerializedHandle plugin_handle; dispatcher->Send(new PpapiHostMsg_SharedMemory_CreateSharedMemory( instance, ByteLength(), host_handle_id, &plugin_handle)); if (!plugin_handle.IsHandleValid() || !plugin_handle.is_shmem() || *host_handle_id == -1) return false; base::SharedMemoryHandle tmp_handle = plugin_handle.shmem(); SharedMemory s(tmp_handle, false); if (!s.Map(ByteLength())) return false; memcpy(s.memory(), Map(), ByteLength()); s.Unmap(); // We don't need to keep the shared memory around on the plugin side; // we've already copied all our data into it. We'll make it invalid // just to be safe. *plugin_out_handle = base::SharedMemory::NULLHandle(); return true; } } // namespace ppapi
[ "enrico.weigelt@gr13.net" ]
enrico.weigelt@gr13.net
fcbf5a46befd7789ff36fb2c90407e900ef27c88
fbef6fd8108921b145413462f475c093f60a69c8
/algorithms/graphm-0.52/algorithm_sch.cpp
aae7f3354811583120e48a2d99ad94fe62828257
[]
no_license
lichen11/LSGMcode
7a8d731c3bcff4900e6c6066da4cfa6c58a19316
3e7c125f7442f00c95cfaaf19b8b343f2b46d490
refs/heads/master
2021-01-01T05:50:09.470066
2014-10-16T21:39:10
2014-10-16T21:39:10
25,267,454
3
1
null
null
null
null
UTF-8
C++
false
false
4,949
cpp
/*************************************************************************** * Copyright (C) 2008 by Mikhail Zaslavskiy * * mikhail.zaslavskiy@ensmp.fr * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "algorithm_sch.h" match_result algorithm_sch::match(graph& g, graph& h,gsl_matrix* gm_P_i,gsl_matrix* gm_ldh,double dalpha_ldh) { bool bblast_match_end=(get_param_i("blast_match_proj")==1); bool bgreedy=(get_param_i("hungarian_greedy")==1); match_result mres=algorithm_qcv::match(g,h,gm_P_i,gm_ldh,dalpha_ldh); if (bverbose) *gout<<"SCH algorithm"<<std::endl; //some duplicate variables gsl_matrix* gm_Ag_d=g.get_descmatrix(cdesc_matrix); gsl_matrix* gm_Ah_d=h.get_descmatrix(cdesc_matrix); if (pdebug.ivalue) gsl_matrix_printout(gm_Ag_d,"Ag",pdebug.strvalue); if (pdebug.ivalue) gsl_matrix_printout(gm_Ah_d,"Ah",pdebug.strvalue); //memory allocation gsl_eigen_symmv_workspace * gesw= gsl_eigen_symmv_alloc (N); gsl_vector* eval_g=gsl_vector_alloc(N); gsl_vector* eval_h=gsl_vector_alloc(N); gsl_matrix* evec_g=gsl_matrix_alloc(N,N); gsl_matrix* evec_h=gsl_matrix_alloc(N,N); if (bverbose) *gout<<"Memory allocation finished"<<std::endl; //eigenvalues and eigenvectors for both matrices gsl_eigen_symmv (gm_Ag_d, eval_g,evec_g,gesw); if (bverbose) *gout<<"Ag eigen vectors"<<std::endl; gsl_eigen_symmv (gm_Ah_d, eval_h,evec_h,gesw); if (bverbose) *gout<<"Ah eigen vectors"<<std::endl; gsl_eigen_symmv_sort (eval_g, evec_g, GSL_EIGEN_SORT_VAL_DESC); gsl_eigen_symmv_sort (eval_h, evec_h, GSL_EIGEN_SORT_VAL_DESC); gsl_matrix_abs(evec_g); gsl_matrix_abs(evec_h); gsl_matrix *gm_lambda=gsl_matrix_alloc(N,N); gsl_matrix_set_all(gm_lambda,0); for (int i=0;i<eval_g->size;i++) for (int j=0;j<eval_h->size;j++) { gsl_matrix_set(gm_lambda,i,j,abs(eval_g->data[i]-eval_h->data[j])); }; /*for (int i=0;i<eval_g->size;i++) { gsl_vector_view gvv_c=gsl_matrix_column(evec_g,i); gsl_vector_scale(&gvv_c.vector,pow(eval_g->data[i],0.5)); }; for (int j=0;j<eval_h->size;j++) { gsl_vector_view gvv_c=gsl_matrix_column(evec_h,j); gsl_vector_scale(&gvv_c.vector,pow(eval_h->data[j],0.5)); };*/ //scale matrix construction gsl_matrix* C=gsl_matrix_alloc(N,N); gsl_matrix_transpose(evec_h); gsl_blas_dgemm(CblasNoTrans,CblasNoTrans,1,gm_lambda,evec_h,0,C); gsl_blas_dgemm(CblasNoTrans,CblasNoTrans,1,evec_g,C,0,gm_lambda); gsl_matrix_memcpy(C,gm_lambda); //produce weighted eigen vectors /*for (int i=0;i<eval_g->size;i++) for (int j=0;j<eval_h->size;j++) { C->data[i+N*j]=0; for (int k=0;k<N;k++) for (int m=0;m<N;m++) C->data[i+N*j]+=pow(gm_Ag_d->data[i+k*N]-gm_Ah_d->data[j+m*N],2); };*/ gsl_matrix_free(gm_Ag_d); gsl_matrix_free(gm_Ah_d); // gsl_matrix_transpose(C); //gsl_matrix_scale(C,-1); gsl_matrix_printout(C,"C",pdebug.strvalue); //gsl_matrix_set_all(C,1); //multiplication of QCV minimum on C gsl_matrix_memcpy(gm_lambda,mres.gm_P_exact); gsl_matrix_add_constant(mres.gm_P_exact,-0.5); gsl_matrix_mul_elements(mres.gm_P_exact,C); gsl_matrix_transpose(mres.gm_P_exact); //permuation projection gsl_matrix_scale(mres.gm_P_exact,-10000); gsl_matrix_hungarian(mres.gm_P_exact,mres.gm_P,NULL,NULL,false,(bblast_match_end?gm_ldh:NULL),bgreedy); gsl_matrix_memcpy(mres.gm_P_exact,gm_lambda); //memory release gsl_matrix_free(C); gsl_matrix_free(gm_lambda); gsl_matrix_free(evec_g); gsl_matrix_free(evec_h); gsl_vector_free(eval_g); gsl_vector_free(eval_h); //initial score mres.vd_trace.clear(); mres.vd_trace.push_back(graph_dist(g,h,cscore_matrix)); //final score mres.vd_trace.push_back(graph_dist(g,h,mres.gm_P,cscore_matrix)); //other output parameters mres.dres=mres.vd_trace.at(1); mres.inum_iteration=2; return mres; }
[ "lchen@durin" ]
lchen@durin
f011a0af6010ad5ba79e03fbd24ce9f5053c4bf3
98f145410fc8fd84ba87d68247de930727d48fdf
/Source/Components/Rigidbody.hpp
702bafe2194f79b6ed93151aeec6abde83d9b8ac
[]
no_license
ngzaharias/entt_breakout
1aa6b3dadd7e9d1020ef6fa0a0561d778f5de712
9627cf5037e08f221e387300db6ad5d95295fab2
refs/heads/master
2023-01-03T16:02:57.866049
2020-10-26T01:25:52
2020-10-26T01:25:52
304,948,071
0
0
null
null
null
null
UTF-8
C++
false
false
77
hpp
#pragma once namespace physics { struct Rigidbody { bool m_Unused; }; }
[ "ngzaharias.logins@gmail.com" ]
ngzaharias.logins@gmail.com
e60492ccc764ba9e6cd658cfc81a5cafe2af2a5f
fcab2c23e61ad3362797b33eb5aa18ba6f3107d8
/TrafficCars/AirVehicle.h
4a563df35f653d0f036ab94c043683daa4bf10e6
[ "MIT" ]
permissive
B3WD/cpp-oop
a27b8e5afa7acfd12602b91d7dad806bb24efb07
5842ad4d1ebeab047b3700f2f6b1a09dffd04f36
refs/heads/main
2023-06-12T05:42:16.645638
2021-06-30T18:04:00
2021-06-30T18:04:00
348,608,102
0
0
null
null
null
null
UTF-8
C++
false
false
670
h
// // Created by tzvet on 28.4.2021 г.. // #ifndef MAIN_CPP_AIRVEHICLE_H #define MAIN_CPP_AIRVEHICLE_H #include "Vehicle.h" class AirVehicle : public Vehicle{ private: unsigned _wingCount; public: AirVehicle(const char* brand = "Null", int wheelCount = 0, int hp = 0, unsigned wingCount = 0); AirVehicle(const AirVehicle &rhs); ~AirVehicle(); AirVehicle& operator=(const AirVehicle &rhs); void setWingCount(unsigned wingCount); unsigned getWingCount() const { return _wingCount;}; std::ostream& ins(std::ostream &out) const; }; std::ostream& operator<<(std::ostream &out, const AirVehicle &rhs); #endif //MAIN_CPP_AIRVEHICLE_H
[ "tsvetomir.kpavlov@gmail.com" ]
tsvetomir.kpavlov@gmail.com
3c243eafa3da329a9176ba19287bfe3f5a329d97
7782c7dd70620b011d3a644cdb8c94c5ed6fb05f
/src/declaration.cpp
e1d4ce5a865018d144e0e09634d3478284689614
[]
no_license
yubako/cflowmake
a07dc03d382ff2836163730685fe848a6e5ba44c
63a91901029c4a789fe9ba72f5281a1c28af2044
refs/heads/master
2020-12-24T18:13:58.271778
2016-05-12T22:31:40
2016-05-12T22:31:40
56,612,749
0
0
null
null
null
null
UTF-8
C++
false
false
860
cpp
#include "pars/cytypes.h" #include "vst/cyvisitor.h" int Declaration::accept(CyVisitor* visitor) { int ope; ope = visitor->visit(this); if ( ope != CyVisitor::VISIT_CONTINUE ) return ope; if ( this->hasNextSibling() ) ope = this->getNextSibling()->accept(visitor); return ope; } int FunctionDefinition::accept(CyVisitor* visitor) { int ope; ope = visitor->visit(this); if ( ope != CyVisitor::VISIT_CONTINUE ) return ope; if ( this->hasNextSibling() ) ope = this->getNextSibling()->accept(visitor); return ope; } int NullDeclaration::accept(CyVisitor* visitor) { int ope; ope =visitor->visit(this); if ( ope != CyVisitor::VISIT_CONTINUE ) return ope; if ( this->hasNextSibling() ) ope = this->getNextSibling()->accept(visitor); return ope; }
[ "user@localhost.localdomain" ]
user@localhost.localdomain
ed7889c74e1de52d881d99beab5f50e8d03337cf
d9975b97e09ae5f5225c04fac385746d44a6a374
/pylucene-4.9.0-0/build/_lucene/org/apache/lucene/index/BaseCompositeReader.h
08ef224779cb151d1202b55b049ce4cc1922a44c
[ "Apache-2.0" ]
permissive
Narabzad/elr_files
20038214ef0c4f459b0dccba5df0f481183fd83a
3e623c7d9c98a7d6e5b26e6e4a73f46ff5352614
refs/heads/master
2020-06-04T02:01:17.028827
2019-06-28T21:55:30
2019-06-28T21:55:30
191,825,485
1
0
null
null
null
null
UTF-8
C++
false
false
3,197
h
#ifndef org_apache_lucene_index_BaseCompositeReader_H #define org_apache_lucene_index_BaseCompositeReader_H #include "org/apache/lucene/index/CompositeReader.h" namespace org { namespace apache { namespace lucene { namespace index { class Fields; class Term; class StoredFieldVisitor; } } } } namespace java { namespace lang { class Class; class String; } namespace io { class IOException; } } template<class T> class JArray; namespace org { namespace apache { namespace lucene { namespace index { class BaseCompositeReader : public ::org::apache::lucene::index::CompositeReader { public: enum { mid_docFreq_7eca6a9e, mid_document_a2ea3ebe, mid_getDocCount_5fdc3f57, mid_getSumDocFreq_5fdc3f54, mid_getSumTotalTermFreq_5fdc3f54, mid_getTermVectors_ef1c9c73, mid_maxDoc_54c6a179, mid_numDocs_54c6a179, mid_totalTermFreq_7eca6a9d, mid_readerIndex_39c7bd23, mid_getSequentialSubReaders_87851566, mid_readerBase_39c7bd23, max_mid }; static ::java::lang::Class *class$; static jmethodID *mids$; static bool live$; static jclass initializeClass(bool); explicit BaseCompositeReader(jobject obj) : ::org::apache::lucene::index::CompositeReader(obj) { if (obj != NULL) env->getClass(initializeClass); } BaseCompositeReader(const BaseCompositeReader& obj) : ::org::apache::lucene::index::CompositeReader(obj) {} jint docFreq(const ::org::apache::lucene::index::Term &) const; void document(jint, const ::org::apache::lucene::index::StoredFieldVisitor &) const; jint getDocCount(const ::java::lang::String &) const; jlong getSumDocFreq(const ::java::lang::String &) const; jlong getSumTotalTermFreq(const ::java::lang::String &) const; ::org::apache::lucene::index::Fields getTermVectors(jint) const; jint maxDoc() const; jint numDocs() const; jlong totalTermFreq(const ::org::apache::lucene::index::Term &) const; }; } } } } #include <Python.h> namespace org { namespace apache { namespace lucene { namespace index { extern PyTypeObject PY_TYPE(BaseCompositeReader); class t_BaseCompositeReader { public: PyObject_HEAD BaseCompositeReader object; PyTypeObject *parameters[1]; static PyTypeObject **parameters_(t_BaseCompositeReader *self) { return (PyTypeObject **) &(self->parameters); } static PyObject *wrap_Object(const BaseCompositeReader&); static PyObject *wrap_jobject(const jobject&); static PyObject *wrap_Object(const BaseCompositeReader&, PyTypeObject *); static PyObject *wrap_jobject(const jobject&, PyTypeObject *); static void install(PyObject *module); static void initialize(PyObject *module); }; } } } } #endif
[ "43349991+Narabzad@users.noreply.github.com" ]
43349991+Narabzad@users.noreply.github.com
a16917a77cfb2b1285fc6658a488285923fbbb76
3590d45ec6566c44204c98af39b2b3b65edfd7a6
/src/qt/macos_appnap.h
639ee028d9b5fa088c41648b872d5a6966227de1
[ "MIT" ]
permissive
californium252/californium252
5fd77b7816e94b132b29054741146cc4ecf38742
21425c0ffbd9fc31dedfd197901ce7063f1164e1
refs/heads/master
2023-02-15T23:55:43.399441
2021-01-16T16:58:50
2021-01-16T16:58:50
330,174,932
0
0
null
null
null
null
UTF-8
C++
false
false
560
h
// Copyright (c) 2011-2018 The Californium Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef CALIFORNIUM_QT_MACOS_APPNAP_H #define CALIFORNIUM_QT_MACOS_APPNAP_H #include <memory> class CAppNapInhibitor final { public: explicit CAppNapInhibitor(); ~CAppNapInhibitor(); void disableAppNap(); void enableAppNap(); private: class CAppNapImpl; std::unique_ptr<CAppNapImpl> impl; }; #endif // CALIFORNIUM_QT_MACOS_APPNAP_H
[ "overlord@DESKTOP-6D6I1IM.localdomain" ]
overlord@DESKTOP-6D6I1IM.localdomain
5758adc25dca7c1889c8d8c52757ab2c4aa7491e
ac227cc22d5f5364e5d029a2cef83816a6954590
/applications/physbam/physbam-lib/Public_Library/PhysBAM_Geometry/Geometry_Particles/RIGID_GEOMETRY_PARTICLES.cpp
99c8ffddf5dea50913b920ef9c9bf42a30ebf15b
[ "BSD-3-Clause" ]
permissive
schinmayee/nimbus
597185bc8bac91a2480466cebc8b337f5d96bd2e
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
refs/heads/master
2020-03-11T11:42:39.262834
2018-04-18T01:28:23
2018-04-18T01:28:23
129,976,755
0
0
BSD-3-Clause
2018-04-17T23:33:23
2018-04-17T23:33:23
null
UTF-8
C++
false
false
2,399
cpp
//##################################################################### // Copyright 2006-2009, Michael Lentine, Craig Schroeder, Eftychios Sifakis, Jonathan Su. // This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt. //##################################################################### #include <PhysBAM_Tools/Vectors/VECTOR.h> #include <PhysBAM_Geometry/Geometry_Particles/RIGID_GEOMETRY_PARTICLES.h> #include <PhysBAM_Geometry/Solids_Geometry/RIGID_GEOMETRY.h> namespace PhysBAM{ //##################################################################### // Resize //##################################################################### template<class TV> void RIGID_GEOMETRY_PARTICLES<TV>:: Resize(const int new_size) { for(int p=new_size+1;p<=array_collection->Size();p++) if(rigid_geometry(p)) Remove_Geometry(p); array_collection->Resize(new_size); } //##################################################################### // Remove_Geometry //##################################################################### template<class TV> void RIGID_GEOMETRY_PARTICLES<TV>:: Remove_Geometry(const int p) { delete rigid_geometry(p); } //##################################################################### // Function Clean_Memory //##################################################################### template<class TV> void RIGID_GEOMETRY_PARTICLES<TV>:: Clean_Memory() { for(int p=1;p<=array_collection->Size();p++) if(rigid_geometry(p)) Remove_Geometry(p); array_collection->Clean_Memory(); } //##################################################################### // Function Clean_Memory //##################################################################### template<class TV> void RIGID_GEOMETRY_PARTICLES<TV>:: Delete_All_Particles() { for(int p=1;p<=array_collection->Size();p++) if(rigid_geometry(p)) Remove_Geometry(p); array_collection->Delete_All_Elements(); } template class RIGID_GEOMETRY_PARTICLES<VECTOR<float,1> >; template class RIGID_GEOMETRY_PARTICLES<VECTOR<float,2> >; template class RIGID_GEOMETRY_PARTICLES<VECTOR<float,3> >; #ifndef COMPILE_WITHOUT_DOUBLE_SUPPORT template class RIGID_GEOMETRY_PARTICLES<VECTOR<double,1> >; template class RIGID_GEOMETRY_PARTICLES<VECTOR<double,2> >; template class RIGID_GEOMETRY_PARTICLES<VECTOR<double,3> >; #endif }
[ "quhang@stanford.edu" ]
quhang@stanford.edu
a8c6a620a3e049b37f4d5e0b33f53723c14d06db
b4b80bbe82640952ae5d2af42d887fef497c4254
/TimeClass.h
0358047b8f99ac4fcf3bdee1eaf03952f539f7e9
[ "MIT" ]
permissive
UnlikeSuika/Touhou_Unfound_Dimensions
899c7b7be98e19554a9d6c98a83b8710a72bd631
b76984308bf32f3511bb81bb54ae997943016d82
refs/heads/master
2020-04-12T01:38:36.974750
2017-02-19T03:31:45
2017-02-19T03:31:45
51,175,878
0
0
null
2016-04-30T00:22:49
2016-02-05T21:41:08
C++
UTF-8
C++
false
false
896
h
#ifndef _TIME_CLASS_H_ #define _TIME_CLASS_H_ const int MAX_TIMER_COUNT = 30; const int MAX_CLOCK_COUNT = 30; class TimeClass{ private: struct TimerType{ int timeLeft; int ID; }; struct ClockType{ int time; int ID; }; unsigned long int frame; TimerType timer[MAX_TIMER_COUNT]; ClockType clock[MAX_CLOCK_COUNT]; int timerIDCount, timerCount; int clockIDCount, clockCount; public: TimeClass(); TimeClass(const TimeClass& other); ~TimeClass(); unsigned long int GetFrameCount(); void SetFrameCount(int input); void FrameIncrement(); bool AddTimer(int& timerID, int timeLimit); void SetTimer(int timerID, int timeLimit); void DeleteTimer(int& timerID); bool IsTimerRunning(int timerID); long int TimeLeft(int timerID); bool AddClock(int& clockID); void SetClock(int clockID, int time); void DeleteClock(int& clockID); int CurrentClockTime(int clockID); }; #endif
[ "unlikesuika@gmail.com" ]
unlikesuika@gmail.com
7b10f8e4433e74622d38f2cf902843613cf92da1
375a52f863fd4d3fbd5c993edb22185c26fd9c84
/Build3DProject/GLWidget.cpp
eb0c542b13ad23db7802eb395528dd0c7ac4c398
[]
no_license
anguszhou/Build3D
5c5bf07994fd74f397a85e7274d08d0d01feab1b
4867851513320c2ae1e017e0d24e9f832884160f
refs/heads/master
2021-01-10T19:03:37.311235
2014-02-18T01:52:04
2014-02-18T01:52:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,787
cpp
#include "glwidget.h" #include <QtCore> #include <QtOpenGL> #include <time.h> #ifndef GL_MULTISAMPLE #define GL_MULTISAMPLE 0x809D #endif #define GL_PI 3.1415926 #define GL_RADIUX 0.2f #define glGUI ((QSplatWin32GUI *) theQSplatGUI) GLWidget::GLWidget(QGLWidget *parent) : QGLWidget(parent) { makeCurrent(); fullscreen = false; int whichDriver; theQSplatGUI = new QSplatWin32GUI(); bool a = strncmp((char *)glGetString(GL_VENDOR), "Microsoft", 9); theQSplatGUI->whichDriver = strncmp((char *)glGetString(GL_VENDOR), "Microsoft", 9) ? OPENGL_POINTS : SOFTWARE_BEST ; float framerate = ((int)whichDriver >= (int)SOFTWARE_GLDRAWPIXELS) ? 4.0f : 8.0f; theQSplatGUI->set_desiredrate(framerate); } void GLWidget::initializeGL() { makeCurrent(); } /* double GLWidget::CalFrameRate(){ static int count; static double save; static clock_t last, current; double timegap; ++count; if(count <= 50){ return save; } count = 0 ; current = clock(); timegap = (current - last) / (double)CLK_TCK; qDebug()<<"current - last : "<<current - last<<" , CLK_TCK"<<CLK_TCK; save = 50.0 / timegap; return save; } */ double GLWidget::CalFrameRate(){ static float framePerSecond = 0.0f; static float lastTime = 0.0f; float returndata ; float currentTime = GetTickCount()* 0.001f; ++framePerSecond; if(currentTime - lastTime > 1.0f){ lastTime = currentTime; qDebug()<<"frame rate is : "<<framePerSecond; returndata = framePerSecond; framePerSecond = 0 ; } return returndata; } void GLWidget::paintGL() { GUI->windowPosX=this->geometry().x(); GUI->windowPosY=this->geometry().y(); GUI->windowHeight = this->height(); GUI->windowWidth = this->width(); GUI->windowBorderY = 0; glReadBuffer(GL_BACK); theQSplatGUI->framePerSecond = CalFrameRate(); theQSplatGUI->redraw(); /* double frameRate = CalFrameRate(); qDebug()<<"frame rate is : "<<frameRate; QPainter painter(this); QPen pen = painter.pen(); pen.setColor(Qt::red); QFont font = painter.font(); font.setPixelSize(50); painter.setPen(pen); painter.setFont(font); painter.drawText(100,100 ,"123123"); */ } void GLWidget::resizeGL(int width, int height) { } void GLWidget::mouseMoveEvent(QMouseEvent *e) { static QSplatGUI::mousebutton this_button = QSplatGUI::NO_BUTTON; //L/M/R button + Ctrl/Shift if(((e->buttons() & Qt::LeftButton)||(e->buttons() & Qt::MidButton)||(e->buttons() & Qt::RightButton)) && ((e->modifiers()==Qt::Key_Control) || (e->modifiers()==Qt::Key_Shift))) { qDebug()<<"L/M/R button + Ctrl/Shift"; this_button = QSplatGUI::LIGHT_BUTTON; }// L + R button else if((e->buttons() & Qt::LeftButton) && (e->buttons() & Qt::RightButton)) { this_button = QSplatGUI::TRANSZ_BUTTON; }//M + R button else if((e->buttons() & Qt::MidButton) && (e->buttons() & Qt::RightButton)) { this_button = QSplatGUI::LIGHT_BUTTON; }//L button else if((e->buttons() & Qt::LeftButton)) { this_button = QSplatGUI::ROT_BUTTON; }//M button else if((e->buttons() & Qt::MidButton)) { this_button = QSplatGUI::TRANSZ_BUTTON; }//R button else if((e->buttons() & Qt::RightButton)) { this_button = QSplatGUI::TRANSXY_BUTTON; }//no button else { this_button = QSplatGUI::NO_BUTTON; } GUI->mouse(e->globalX() - GUI->windowPosX, (GUI->windowHeight - GUI->windowBorderY) - (e->globalY() - GUI->windowPosY ), this_button); updateGL(); } void GLWidget::wheelEvent(QWheelEvent * e) { static QSplatGUI::mousebutton this_button = QSplatGUI::NO_BUTTON; this_button = e->delta() > 0 ? QSplatGUI::UP_WHEEL : QSplatGUI::DOWN_WHEEL; GUI->mouse(e->globalX() - GUI->windowPosX, (GUI->windowHeight - GUI->windowBorderY) - (e->globalY() - GUI->windowPosY ), this_button); updateGL(); } void GLWidget::keyPressEvent(QKeyEvent *e) { }
[ "zhoucong07@gmail.com" ]
zhoucong07@gmail.com
fe023e00c351c6b8a2deb81ed6cc9c2510476937
e46b909cdf0361f6c336f532507573c2f592cdf4
/util/system/filemap.h
64ce3f7dfd5fd7e9ea7ddea18ebcc790bc890954
[ "Apache-2.0" ]
permissive
exprmntr/test
d25b50881089640e8d94bc6817e9194fda452e85
170138c9ab62756f75882d59fb87447fc8b0f524
refs/heads/master
2022-11-01T16:47:25.276943
2018-03-31T20:56:25
2018-03-31T20:56:25
95,452,782
0
3
Apache-2.0
2022-10-30T22:45:27
2017-06-26T14:04:21
C++
UTF-8
C++
false
false
8,770
h
#pragma once #include "file.h" #include "align.h" #include "yassert.h" #include <util/generic/noncopyable.h> #include <util/generic/ptr.h> #include <util/generic/utility.h> #include <util/generic/yexception.h> #include <util/generic/flags.h> #include <util/generic/string.h> #include <new> #include <cstdio> struct TMemoryMapCommon { struct TMapResult { inline size_t MappedSize() const noexcept { return Size - Head; } inline void* MappedData() const noexcept { return Ptr ? (void*)((char*)Ptr + Head) : nullptr; } inline bool IsMapped() const noexcept { return Ptr != nullptr; } inline void Reset() noexcept { Ptr = nullptr; Size = 0; Head = 0; } void* Ptr; size_t Size; i32 Head; TMapResult(void) noexcept { Reset(); } }; enum EOpenModeFlag { oRdOnly = 1, oRdWr = 2, oAccessMask = 3, oNotGreedy = 8, oPrecharge = 16, }; Y_DECLARE_FLAGS(EOpenMode, EOpenModeFlag) /** * Name that will be printed in exceptions if not specified. * Overridden by name obtained from `TFile` if it's not empty. */ static const TString UnknownFileName; }; Y_DECLARE_OPERATORS_FOR_FLAGS(TMemoryMapCommon::EOpenMode) class TMemoryMap: public TMemoryMapCommon { public: explicit TMemoryMap(const TString& name); explicit TMemoryMap(const TString& name, EOpenMode om); TMemoryMap(const TString& name, i64 length, EOpenMode om); TMemoryMap(FILE* f, TString dbgName = UnknownFileName); TMemoryMap(FILE* f, EOpenMode om, TString dbgName = UnknownFileName); TMemoryMap(const TFile& file, TString dbgName = UnknownFileName); TMemoryMap(const TFile& file, EOpenMode om, TString dbgName = UnknownFileName); ~TMemoryMap(); TMapResult Map(i64 offset, size_t size); bool Unmap(TMapResult region); void ResizeAndReset(i64 size); TMapResult ResizeAndRemap(i64 offset, size_t size); i64 Length() const noexcept; bool IsOpen() const noexcept; bool IsWritable() const noexcept; TFile GetFile() const noexcept; void SetSequential(); void Evict(void* ptr, size_t len); void Evict(); /* * deprecated */ bool Unmap(void* ptr, size_t size); private: class TImpl; TSimpleIntrusivePtr<TImpl> Impl_; }; class TFileMap: public TMemoryMapCommon { public: TFileMap(const TMemoryMap& map) noexcept; TFileMap(const TString& name); TFileMap(const TString& name, EOpenMode om); TFileMap(const TString& name, i64 length, EOpenMode om); TFileMap(FILE* f, EOpenMode om = oRdOnly, TString dbgName = UnknownFileName); TFileMap(const TFile& file, EOpenMode om = oRdOnly, TString dbgName = UnknownFileName); TFileMap(const TFileMap& fm) noexcept; ~TFileMap(); TMapResult Map(i64 offset, size_t size); TMapResult ResizeAndRemap(i64 offset, size_t size); void Unmap(); void Flush(void* ptr, size_t size) { Flush(ptr, size, true); } void Flush() { Flush(Ptr(), MappedSize()); } void FlushAsync(void* ptr, size_t size) { Flush(ptr, size, false); } void FlushAsync() { FlushAsync(Ptr(), MappedSize()); } inline i64 Length() const noexcept { return Map_.Length(); } inline bool IsOpen() const noexcept { return Map_.IsOpen(); } inline bool IsWritable() const noexcept { return Map_.IsWritable(); } inline void* Ptr() const noexcept { return Region_.MappedData(); } inline size_t MappedSize() const noexcept { return Region_.MappedSize(); } TFile GetFile() const noexcept { return Map_.GetFile(); } void Precharge(size_t pos = 0, size_t size = (size_t)-1) const; void SetSequential() { Map_.SetSequential(); } void Evict() { Map_.Evict(); } private: void Flush(void* ptr, size_t size, bool sync); TMemoryMap Map_; TMapResult Region_; }; template <class T> class TFileMappedArray { private: const T* Ptr_; const T* End_; size_t Size_; char DummyData_[sizeof(T) + PLATFORM_DATA_ALIGN]; mutable THolder<T, TDestructor> Dummy_; THolder<TFileMap> DataHolder_; public: TFileMappedArray() : Ptr_(nullptr) , End_(nullptr) , Size_(0) { } ~TFileMappedArray() { Ptr_ = nullptr; End_ = nullptr; } void Init(const char* name) { DataHolder_.Reset(new TFileMap(name)); DoInit(name); } void Init(const TFileMap& fileMap) { DataHolder_.Reset(new TFileMap(fileMap)); DoInit(fileMap.GetFile().GetName()); } void Term() { DataHolder_.Destroy(); Ptr_ = nullptr; Size_ = 0; End_ = nullptr; } void Precharge() { DataHolder_->Precharge(); } const T& operator[](size_t pos) const { Y_ASSERT(pos < size()); return Ptr_[pos]; } /// for STL compatibility only, Size() usage is recommended size_t size() const { return Size_; } size_t Size() const { return Size_; } const T& GetAt(size_t pos) const { if (pos < Size_) return Ptr_[pos]; return Dummy(); } void SetDummy(const T& n_Dummy) { Dummy_.Destroy(); Dummy_.Reset(new (DummyData()) T(n_Dummy)); } inline char* DummyData() const noexcept { return AlignUp((char*)DummyData_); } inline const T& Dummy() const { if (!Dummy_) { Dummy_.Reset(new (DummyData()) T()); } return *Dummy_; } /// for STL compatibility only, Empty() usage is recommended bool empty() const noexcept { return Empty(); } bool Empty() const noexcept { return 0 == Size_; } /// for STL compatibility only, Begin() usage is recommended const T* begin() const noexcept { return Begin(); } const T* Begin() const noexcept { return Ptr_; } /// for STL compatibility only, End() usage is recommended const T* end() const noexcept { return End_; } const T* End() const noexcept { return End_; } private: void DoInit(const TString& fileName) { DataHolder_->Map(0, DataHolder_->Length()); if (DataHolder_->Length() % sizeof(T)) { Term(); ythrow yexception() << "Incorrect size of file " << fileName.Quote(); } Ptr_ = (const T*)DataHolder_->Ptr(); Size_ = DataHolder_->Length() / sizeof(T); End_ = Ptr_ + Size_; } }; class TMappedAllocation : TNonCopyable { public: TMappedAllocation(size_t size = 0, bool shared = false, void* addr = nullptr); ~TMappedAllocation() { Dealloc(); } void* Alloc(size_t size, void* addr = nullptr); void Dealloc(); void* Ptr() const { return Ptr_; } char* Data(ui32 pos = 0) const { return (char*)(Ptr_ ? ((char*)Ptr_ + pos) : nullptr); } char* Begin() const noexcept { return (char*)Ptr(); } char* End() const noexcept { return Begin() + MappedSize(); } size_t MappedSize() const { return Size_; } void swap(TMappedAllocation& with); private: void* Ptr_; size_t Size_; bool Shared_; #ifdef _win_ void* Mapping_; #endif }; template <class T> class TMappedArray: private TMappedAllocation { public: TMappedArray(size_t siz = 0) : TMappedAllocation(0) { if (siz) Create(siz); } ~TMappedArray() { Destroy(); } T* Create(size_t siz) { Y_ASSERT(MappedSize() == 0 && Ptr() == nullptr); T* arr = (T*)Alloc((sizeof(T) * siz)); if (!arr) return nullptr; Y_ASSERT(MappedSize() == sizeof(T) * siz); for (size_t n = 0; n < siz; n++) new (&arr[n]) T(); return arr; } void Destroy() { T* arr = (T*)Ptr(); if (arr) { for (size_t n = 0; n < size(); n++) arr[n].~T(); Dealloc(); } } T& operator[](size_t pos) { Y_ASSERT(pos < size()); return ((T*)Ptr())[pos]; } const T& operator[](size_t pos) const { Y_ASSERT(pos < size()); return ((T*)Ptr())[pos]; } T* begin() { return (T*)Ptr(); } T* end() { return (T*)((char*)Ptr() + MappedSize()); } size_t size() const { return MappedSize() / sizeof(T); } void swap(TMappedArray<T>& with) { TMappedAllocation::swap(with); } };
[ "exprmntr@yandex-team.ru" ]
exprmntr@yandex-team.ru
9e65b6afc7a433a4cf5c1a2fa76e0590a57ccdc0
be6061392ebd7ab08dfaa8219eb3515b3de47e93
/examples/algo1_nandsim/nandsim.cpp
2f524e6a34f27ac804c44b69aa4890260accd951
[ "MIT" ]
permissive
chenm001/connectal
7848385216ae34b727591ef9055d48ac30855934
66d30ffcca8e0260041fb6b48b3200411ff73282
refs/heads/master
2023-04-17T15:21:05.308406
2023-04-16T21:32:10
2023-04-16T21:32:10
50,326,674
1
0
MIT
2023-04-17T02:18:45
2016-01-25T04:45:13
Bluespec
UTF-8
C++
false
false
3,093
cpp
#include <errno.h> #include <fcntl.h> #include <stdio.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "portal.h" #include "dmaManager.h" #include "NandCfgRequest.h" #include "NandCfgIndication.h" class NandCfgIndication : public NandCfgIndicationWrapper { public: unsigned int rDataCnt; virtual void readDone(uint32_t v){ fprintf(stderr, "NandSim::readDone v=%x\n", v); sem_post(&sem); } virtual void writeDone(uint32_t v){ fprintf(stderr, "NandSim::writeDone v=%x\n", v); sem_post(&sem); } virtual void eraseDone(uint32_t v){ fprintf(stderr, "NandSim::eraseDone v=%x\n", v); sem_post(&sem); } virtual void configureNandDone(){ fprintf(stderr, "NandSim::configureNandDone\n"); sem_post(&sem); } NandCfgIndication(int id) : NandCfgIndicationWrapper(id) { sem_init(&sem, 0, 0); } void wait() { fprintf(stderr, "NandSim::wait for semaphore\n"); sem_wait(&sem); } private: sem_t sem; }; int initNandSim(DmaManager *hostDma) { NandCfgRequestProxy *nandcfgRequest = new NandCfgRequestProxy(IfcNames_NandCfgRequestS2H); NandCfgIndication *nandcfgIndication = new NandCfgIndication(IfcNames_NandCfgIndicationH2S); int nandBytes = 1 << 12; int nandAlloc = portalAlloc(nandBytes, 0); fprintf(stderr, "testnandsim::nandAlloc=%d\n", nandAlloc); int ref_nandAlloc = hostDma->reference(nandAlloc); fprintf(stderr, "ref_nandAlloc=%d\n", ref_nandAlloc); fprintf(stderr, "testnandsim::NAND alloc fd=%d ref=%d\n", nandAlloc, ref_nandAlloc); nandcfgRequest->configureNand(ref_nandAlloc, nandBytes); nandcfgIndication->wait(); const char *filename = "../test.bin"; fprintf(stderr, "testnandsim::opening %s\n", filename); // open up the text file and read it into an allocated memory buffer int data_fd = open(filename, O_RDONLY); if (data_fd < 0) { fprintf(stderr, "%s:%d failed to open file %s errno=%d:%s\n", __FUNCTION__, __LINE__, filename, errno, strerror(errno)); return 0; } off_t data_len = lseek(data_fd, 0, SEEK_END); fprintf(stderr, "%s:%d fd=%d data_len=%ld\n", __FUNCTION__, __LINE__, data_fd, data_len); data_len = data_len & ~15; // because we are using a burst length of 16 lseek(data_fd, 0, SEEK_SET); int dataAlloc = portalAlloc(data_len, 0); char *data = (char *)portalMmap(dataAlloc, data_len); ssize_t read_len = read(data_fd, data, data_len); if(read_len != data_len) { fprintf(stderr, "%s:%d::error reading %s %ld %ld\n", __FUNCTION__, __LINE__, filename, (long)data_len, (long) read_len); exit(-1); } int ref_dataAlloc = hostDma->reference(dataAlloc); // write the contents of data into "flash" memory portalCacheFlush(ref_dataAlloc, data, data_len, 1); fprintf(stderr, "testnandsim::invoking write %08x %08lx\n", ref_dataAlloc, (long)data_len); nandcfgRequest->startWrite(ref_dataAlloc, 0, 0, data_len, 16); nandcfgIndication->wait(); fprintf(stderr, "%s:%d finished -- data_len=%ld\n", __FUNCTION__, __LINE__, data_len); return data_len; }
[ "jamey.hicks@gmail.com" ]
jamey.hicks@gmail.com
4bcdb892fd480b5c2bd1615a22c508b7e4cfd489
52f62927bb096e6cbc01bd6e5625a119fb35c1c5
/avt/Queries/Queries/avtExpectedValueQuery.h
849ca69a03c9e702f6c0f1f54847ec785eac0f9b
[]
no_license
HarinarayanKrishnan/VisIt27RC_Trunk
f42f82d1cb2492f6df1c2f5bb05bbb598fce99c3
16cdd647ac0ad5abfd66b252d31c8b833142145a
refs/heads/master
2020-06-03T07:13:46.229264
2014-02-26T18:13:38
2014-02-26T18:13:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,610
h
/***************************************************************************** * * Copyright (c) 2000 - 2013, Lawrence Livermore National Security, LLC * Produced at the Lawrence Livermore National Laboratory * LLNL-CODE-442911 * All rights reserved. * * This file is part of VisIt. For details, see https://visit.llnl.gov/. The * full copyright notice is contained in the file COPYRIGHT located at the root * of the VisIt distribution or at http://www.llnl.gov/visit/copyright.html. * * 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 disclaimer below. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the disclaimer (as noted below) in the * documentation and/or other materials provided with the distribution. * - Neither the name of the LLNS/LLNL 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 LAWRENCE LIVERMORE NATIONAL SECURITY, * LLC, THE U.S. DEPARTMENT OF ENERGY 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. * *****************************************************************************/ // ************************************************************************* // // avtExpectedValueQuery.h // // ************************************************************************* // #ifndef AVT_EXPECTED_VALUE_QUERY_H #define AVT_EXPECTED_VALUE_QUERY_H #include <query_exports.h> #include <avtCurveQuery.h> #include <string> // **************************************************************************** // Class: avtExpectedValueQuery // // Purpose: // A query that calculates the expected value of a probability density // function. That is, for a function f(x), it calculate the integral // x*f(x) over the entire domain, which return the expected value. // // Programmer: Hank Childs // Creation: August 25, 2006 // // **************************************************************************** class QUERY_API avtExpectedValueQuery : public avtCurveQuery { public: avtExpectedValueQuery(); virtual ~avtExpectedValueQuery(); virtual const char *GetType(void) { return "avtExpectedValueQuery"; }; virtual const char *GetDescription(void) { return "Calculating expected value."; }; protected: virtual double CurveQuery(int, const float *, const float *); virtual std::string CreateMessage(double); }; #endif
[ "brugger@18c085ea-50e0-402c-830e-de6fd14e8384" ]
brugger@18c085ea-50e0-402c-830e-de6fd14e8384
b45c74ab4359f8ddcc3e99771d3e9e62e1cfd0cd
0b111b10f185e0148f9ad137a1f6590e79d2cdeb
/kraUtilities/include/kraModule.h
bd6cea63c1b1b53d2055297ece61219d959969fe
[]
no_license
GalahadP92/Kraken-Engine
c409497592e3e2c8645484d94b17df7a63d03af9
fe8f27a378c9e85c36d4c0b3a042a549782988e7
refs/heads/master
2023-08-07T14:17:06.601235
2020-07-09T16:44:43
2020-07-09T16:44:43
278,412,919
0
0
null
null
null
null
UTF-8
C++
false
false
2,729
h
#pragma once #include "kraPrerequisitesUtil.h" #include <iostream> namespace kraEngineSDK{ using std::cout; template<class T> class Module { public: static T& instance() { if (!isStartedUp()) { std::cout << "Trying to access module but it hasn't started\n"; } if (isDestroyed()) { std::cout << "Trying to access a destroyed Module\n"; } return *_instance(); } static T* instancePtr() { if (!isStartedUp()) { std::cout << "Trying to access module but it hasn't started\n"; } if (isDestroyed()) { std::cout << "Trying to access a destroyed Module\n"; } return _instance(); } template<class... Args> static void StartUp(Args&& ...args) { if (isStartedUp()) { cout << "Trying to start an already started module\n"; } _instance() = new T(std::forward<Args>(args)...); isStartedUp() = true; isDestroyed() = false; static_cast<Module*>(_instance())->onStartUp(); } template<class SubType, class... Args> static void StartUp(Args&& ...args) { static_assert(std::is_base_of<T, SubType>::value, "Provided type isn't derived from the type the Module is initialized\n"); if (isStartedUp()) { cout << "Trying to start an already started module\n"; } _instance() = new SubType(std::forward<Args>(args)...); isStartedUp() = true; isDestroyed() = false; static_cast<Module*>(_instance())->onStartUp(); } static void ShutDown() { if (isDestroyed()) { cout << "Trying to shut down an already shut down module\n"; } if (!isStartedUp()) { cout << "Trying to shut down a module that was never started\n"; } static_cast<Module*>(_instance())->onShutdown(); delete(_instance()); isDestroyed() = true; } static bool isStarted() { return isStartedUp() && !isDestroyed(); } protected: Module() = default; virtual ~Module() = default; Module(Module&&) = delete; Module(const Module&) = delete; Module& operator = (Module&&) = delete; Module& operator=(const Module&) = delete; virtual void onStartUp() {} virtual void onShutdown() {} static T*& _instance() { static T* inst = nullptr; return inst; } static bool& isDestroyed() { static bool inst = false; return inst; } static bool& isStartedUp() { static bool inst = false; return inst; } }; }
[ "evey92@gmail.com" ]
evey92@gmail.com
593dcabd1348a48eea41a4e863d7d0595a9a030b
90d39aa2f36783b89a17e0687980b1139b6c71ce
/SPOJ/BOOKS1.cpp
aa3a89f41208fd13f4b286a710faee88262e8004
[]
no_license
nims11/coding
634983b21ad98694ef9badf56ec8dfc950f33539
390d64aff1f0149e740629c64e1d00cd5fb59042
refs/heads/master
2021-03-22T08:15:29.770903
2018-05-28T23:27:37
2018-05-28T23:27:37
247,346,971
4
0
null
null
null
null
UTF-8
C++
false
false
1,717
cpp
/* Nimesh Ghelani (nims11) */ #include<iostream> #include<cstdio> #include<cmath> #include<algorithm> #include<map> #include<string> #include<vector> #include<queue> #include<cmath> #include<stack> #include<utility> #define in_T int t;for(scanf("%d",&t);t--;) #define in_I(a) scanf("%d",&a) #define in_F(a) scanf("%lf",&a) #define in_L(a) scanf("%lld",&a) #define in_S(a) scanf("%s",a) #define newline printf("\n") #define MAX(a,b) a>b?a:b #define MIN(a,b) a<b?a:b #define SWAP(a,b) {int tmp=a;a=b;b=tmp;} #define P_I(a) printf("%d",a) using namespace std; int m,k; int p[500]; vector<int>ans; bool possible(int size, bool print = false) { if(print)ans.clear(); int curr=0; for(int i=0;i<k-1;i++) { int sum=0; while(curr<m-k+i+1 && sum+p[curr]<=size) { if(print)ans.push_back(p[curr]); sum+=p[curr]; curr++; } if(print)ans.push_back(-1); } int sum2=0; while(curr<m) { if(print)ans.push_back(p[curr]); sum2+=p[curr++]; } if(print) for(int i=ans.size()-1;i>=0;i--) { if(ans[i]!=-1)printf("%d ",ans[i]); else printf("/ "); } if(print) newline; if(sum2>size)return false; return true; } int main() { in_T { in_I(m);in_I(k); int start=0,end=0; for(int i=m-1;i>=0;i--) { in_I(p[i]); start = max(start,p[i]); end +=p[i]; } while(start<end) { int mid = (start+end)/2; if(possible(mid)) { end = mid; }else start = mid+1; } possible(start,true); } }
[ "nimeshghelani@gmail.com" ]
nimeshghelani@gmail.com
4647cfcf4d3761b0c0da56b8afd29e5e4d5c72ad
ca6ad207254acd23b8cb56aec2bb30951c52a949
/src/core/framework/ui/portable/SpriteBatcher.cpp
cef0a591ecd408092192c361e38cbffee67d727e
[]
no_license
sgowen/GGJ17
30c049f2faa491f232835d3410458f35206d15cc
eee3863538754b3cfdba95827afcce09b58c937a
refs/heads/master
2022-05-02T08:40:34.973728
2022-04-26T21:16:43
2022-04-26T21:16:43
79,612,785
1
0
null
null
null
null
UTF-8
C++
false
false
252
cpp
// // SpriteBatcher.cpp // noctisgames-framework // // Created by Stephen Gowen on 9/25/14. // Copyright (c) 2017 Noctis Games. All rights reserved. // #include "SpriteBatcher.h" SpriteBatcher::SpriteBatcher() : m_iNumSprites(0) { // Empty }
[ "dev.sgowen@gmail.com" ]
dev.sgowen@gmail.com
d95c7fd09908b17bf398d12ef6c445a1da98dfca
94eefa5c297a427cf52d2cdd9852fbc74605a76d
/Exercise4.h
d4b7d1d4f5f16a8e4647a956f095578adac71130
[]
no_license
calderona/ZAnalyisis
f78f62ec19794f043da721ba33a2d0702364fc5a
2ca9fb15b61a87ff3c60618a7e963414d07cdd90
refs/heads/master
2021-01-22T11:37:16.942535
2014-10-17T10:42:11
2014-10-17T10:42:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,621
h
////////////////////////////////////////////////////////// // Universidad de Cantabria // Ciencias Físicas - Partículas // Curso 2014 - 2015 // EXERCISE NUMBER 4 :: Analysis de datos del detector de partículas CMS // Author: Alicia Calderon // 07 October 2014 - Version v1.2 // Root version 5.30.06 ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// // // ================= NOMBRE ALUMNO: // ////////////////////////////////////////////////////////// #ifndef EXERCISE4_H #define EXERCISE4_H #include <TH2.h> #include <TH1.h> #include <TROOT.h> #include <TBranch.h> class Exercise4 { public: Exercise4(TTree *tree, bool save, string sample); ~Exercise4(); //--- INITIALIZE FUNCTIONS Bool_t IsInitialized() const { return fIsInitialized; } void Initialize(TTree *tree, bool save, string sample); void FillHistograms(Long64_t jentry); bool isGoodMuonISO (int iMu); void SaveHistrograms(bool save, string sample); bool isGoodGLBMuonID (int iMu); //--- DEFINE VARIABLES Int_t Run; Int_t Event; Int_t Lumi; Int_t nPU; vector<bool> *Muon_IsGlobalMuon; vector<bool> *Muon_IsAllTrackerMuons; vector<bool> *Muon_IsAllStandAloneMuons; vector<bool> *Muon_IsTMLastStationAngTight; vector<float> *Muon_Px; vector<float> *Muon_Py; vector<float> *Muon_Pz; vector<float> *Muon_Pt; vector<float> *Muon_deltaPt; vector<float> *Muon_Energy; vector<int> *Muon_Charge; vector<float> *Muon_NormChi2GTrk; vector<int> *Muon_NValidHitsSATrk; vector<int> *Muon_NumOfMatches; vector<float> *Muon_Chi2InTrk; vector<float> *Muon_dofInTrk; vector<int> *Muon_NValidHitsInTrk; vector<int> *Muon_NValidPixelHitsInTrk; vector<float> *Muon_SumIsoCalo; vector<float> *Muon_SumIsoTrack; vector<float> *Muon_dzPV; vector<float> *Muon_IPPV; // List of branches TBranch *b_Run; //! TBranch *b_Event; //! TBranch *b_Lumi; //! TBranch *b_nPU; //! TBranch *b_Muon_IsGlobalMuon; //! TBranch *b_Muon_IsAllTrackerMuons; //! TBranch *b_Muon_IsAllStandAloneMuons; //! TBranch *b_Muon_IsTMLastStationAngTight; //! TBranch *b_Muon_Px; //! TBranch *b_Muon_Py; //! TBranch *b_Muon_Pz; //! TBranch *b_Muon_Pt; //! TBranch *b_Muon_deltaPt; //! TBranch *b_Muon_Energy; //! TBranch *b_Muon_Charge; //! TBranch *b_Muon_NormChi2GTrk; //! TBranch *b_Muon_NValidHitsSATrk; //! TBranch *b_Muon_NumOfMatches; //! TBranch *b_Muon_Chi2InTrk; //! TBranch *b_Muon_dofInTrk; //! TBranch *b_Muon_NValidHitsInTrk; //! TBranch *b_Muon_NValidPixelHitsInTrk; //! TBranch *b_Muon_SumIsoCalo; //! TBranch *b_Muon_SumIsoTrack; //! TBranch *b_Muon_dzPV; //! TBranch *b_Muon_IPPV; //! //--- DEFINE HISTOGRAMS //--- 1D H TH1F *test; TH1F *h_Mu_cutWorkflow; TH1F *h_Mu_pt_all; TH1F *h_Mu_pt_GoodMu; TH1F *h_Mu_eta_all; TH1F *h_Mu_eta_GoodMu; TH1F *h_Mu_InvMass_all; TH1F *h_Mu_InvMass_GoodMu; TH1F *h_Mu_ZInvMass_GlbGlb; TH1F *h_Mu_ZInvMass_StaSta; TH1F *h_Mu_ZInvMass_TkTk; TH1F *h_Mu_ZInvMass_GoodMu; //--- 2D H //--- DEFINE FILES TFile *outputFile; protected: Bool_t fIsInitialized; }; #endif
[ "calderon@cern.ch" ]
calderon@cern.ch
323d48a232dc170bdb3dca6a29cc27247a164709
b41532e333eb839abd35c788fbdc54eadb93263b
/src/RMeCabMx.cpp
a739e7ccb566356a691bb563b5c7855ec480ca3e
[]
no_license
halka9000stg/RMeCab
8dd1b94aa717bc6d9d1d10c798b4422e884b29ca
72775047fe9f88346963512157dcab965440b9b6
refs/heads/master
2022-07-07T20:57:28.035193
2020-05-13T05:29:28
2020-05-13T05:29:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
17,907
cpp
/* ver 0.99995 2016 12 27 全ての関数を使われる前に消し去りたい         |\           /|         |\\       //|        :  ,> `´ ̄`´ <  ′ .       V            V .       i{ ●      ● }i        八    、_,_,     八    わけがわからないよ .       / 个 . _  _ . 个 ',    _/   il   ,'    '.  li  ',__ docDF関数で全てをまかなえるから */ #include "RMeCab.h" ////////////////////////////////////////////////////// /* データフレームから指定された列の文字列を読む */ extern "C" { SEXP RMeCabMx(SEXP filename, SEXP pos, SEXP posN, SEXP minFreq, SEXP kigo , SEXP mydic ){ // SEXP sym, SEXP kigo // Rprintf("in RMeCabMX\n"); const char* input = CHAR(STRING_ELT(filename,0)); const char* dic = CHAR(STRING_ELT(mydic, 0));//指定辞書 char KIGO[BUF1]; // = CHAR(STRING_ELT(kigo,0)); strcpy(KIGO, kigoCode()); //strcpy(KIGO, "記号"); // Rprintf("before minFreq\n"); int mFreq = INTEGER_VALUE( minFreq );// 最小頻度の数 int mSym = INTEGER_VALUE( kigo );// INTEGER_VALUE( sym ) 記号を含めるか 0 含めない;1 含める int mF = 0;// map オブジェクト内の最小頻度以下の個数を記憶 int pos_n = INTEGER_VALUE( posN );// pos の数 bool flag = 1; if(pos_n < 1 ){ pos_n = 2;// = 1 flag = 0; } // char *Ppos[pos_n]; // 2011 03 10 vector<string> Ppos2; int totalM = 0; char input2[BUF4];//char input2[5120];char input2[5120]; mecab_t *mecab; mecab_node_t *node; int i, j, n, z, zz = 0; int posC = 0; int pc = 0; // int console = 0; char buf1[BUF1];// [512];//入力された語形を記憶 char buf2[BUF3]; char buf3[BUF2];// [128];記号チェック用 char buf4[BUF2];// [128]; 記号チェック用 char *p; // SEXP mydf, tmp, varlables, row_names; SEXP vecInt, vecName, myPos; map<string, int> m1; map<string, int>::iterator pa; //Rprintf("before MeCab\n"); string str;// 2009 04 03 FILE *fp; // 2009 04 03 mecab = mecab_new2 (dic);// mecab = mecab_new2 ("MeCab");// mecab_new2 (" -u user.dic"); CHECK(mecab); //Rprintf("before Pos set\n"); if(pos_n > 0 && flag){ PROTECT(myPos = AS_CHARACTER(pos));pc++; // 2011 03 10 for( i = 0; i < pos_n; i++){ // Ppos[i] = R_alloc( (unsigned int ) strlen (CHAR(STRING_ELT(myPos, i))), sizeof(char)); // } // Rprintf("end myPos = AS_CHARACTER(pos) \n"); for( i = 0; i < pos_n; i++){ // 2011 03 10 strcpy(Ppos[i], CHAR(STRING_ELT(myPos, i))); Ppos2.push_back(CHAR(STRING_ELT(myPos, i))); // 2011 03 10 // Rprintf("Pos[%d] = %s\n", i, Ppos[i]); if(strcmp(Ppos2[i].c_str() , KIGO) == 0){// if(strcmp(Ppos[i], KIGO) == 0){ mSym = 1; } } }else{ PROTECT(myPos = AS_CHARACTER(pos));pc++; // Ppos[0] = R_alloc(strlen(CHAR(STRING_ELT(myPos, 0))), sizeof(char)); // strcpy(Ppos[0], meisiCode()); // 2011 03 10 // Ppos[0] = R_alloc( (unsigned int ) strlen( meisiCode()), sizeof(char)); // 2011 03 10 // strcpy(Ppos[0], meisiCode() ); Ppos2.push_back( meisiCode() ); // 2011 03 10 // 2011 03 10 // Ppos[1] = R_alloc( (unsigned int ) strlen( keiyouCode() ), sizeof(char)); // 2011 03 10 // strcpy(Ppos[1], keiyouCode() ); Ppos2.push_back( keiyouCode() ); // 2011 03 10 // char * tmp; // strcpy(tmp, (const char*) meisiCode()); // strcpy(Ppos[0], tmp ); // strcpy(tmp, (const char*) keiyouCode()); // strcpy(Ppos[0], tmp ); } //Rprintf("before file to open\n"); if((fp = fopen(input, "r")) == NULL){ Rprintf("no file found\n"); return(R_NilValue); }else{ Rprintf("file = %s\n",input ); while(!feof(fp)){ if(fgets(input2, FILEINPUT, fp) != NULL){// 2011 03 11 if(fgets(input2, 5120, fp) != NULL){ node = ( mecab_node_t * ) mecab_sparse_tonode(mecab, input2); CHECK(node); /// 解析結果のノードをなめる for (; node; node = node->next) { // printf("%d ", node->id); if (node->stat == MECAB_BOS_NODE) //printf("BOS"); continue; else if (node->stat == MECAB_EOS_NODE) //printf("EOS"); continue; else { // 2010 buf1 = (char *)malloc( node->length * MB_CUR_MAX+ 1); strncpy(buf1, node->surface, node->length) ;//元の語形 buf1[node->length] = '\0';// 末尾にNULLを加える// 2006 06 移動 if(strlen(buf1) < 1){ continue;// 2006 06 移動 } //< 2005 11 07> //Rprintf("%s\n", buf1); //if( atoi(buf1) > 0x00 && atoi(buf1) < 0x0e ){//if( atoi(buf1) == 0x0e){//エスケープ記号類 if( buf1[0] > 0x00 && buf1[0] < 0x21 ){//エスケープ記号類 continue; }// </ 2005 11 07> // buf1[node->length] = '\0';// 末尾にNULLを加える// 2006 06 移動 // if(strlen(buf1) < 1){// 2006 06 移動 // continue; // } strcpy(buf2, node->feature);//ノードごとに解析情報の取得.要素数は 9 if(strlen(buf2) < 1){ continue; } p = strtok(buf2, "," );//取得情報の分割 if( p != NULL){ sprintf(buf3, "%s", p); //Rprintf("%s\n", buf3); //if(mSym < 1 && strcmp(buf3, "記号") == 0){ if(mSym < 1 && strcmp(buf3, KIGO) == 0){ continue; } totalM++; for( i = 0; i < pos_n; i++){ sprintf(buf4, "%s", Ppos2[i].c_str());// 2011 03 10 // sprintf(buf4, "%s", Ppos[i]); // Rprintf("buf4 %s\n", buf4); if(strcmp(buf3, buf4) == 0){ posC = 1; } } if(posC != 1){ // mFreq++; // mF++; p = NULL; posC = 0; continue; } } j = 1; while ( p != NULL ) { if( j == 1){//品詞情報1 str = p; // str.append(","); } else if( j == 7){ if(p == NULL || strcmp(p, "*") == 0){ str = buf1;//元の語形 // str.append(buf1);//元の語形 } else{ // str.append(p); str = p; } pa = m1.find(str);//出てきた形態素原型は既にマップにあるか? if(pa != m1.end()){ pa->second = pa->second + 1; //二つ目の数値を加算 } else{// マップにないなら,新規にマップに追加 m1.insert(make_pair(str, 1));// 1 は 1個目と言う意味 } } p = strtok( NULL,"," ); posC = 0; j++; } } //memset(buf1,'\0',strlen(buf1)); memset(buf1,0,strlen(buf1));// 2017 08 04 memset(buf2,0,strlen(buf2)); // 2017 08 04 }// for }//if }// while(!feof(fp));//while UNPROTECT(pc);//この段階では PC は 1のはず pc--;// ゼロにする fclose(fp); mecab_destroy(mecab); // return(R_NilValue); sprintf(buf3, "[[LESS-THAN-%d]]",mFreq); n = (int)m1.size(); if(n < 1){ Rprintf("empty results\n"); UNPROTECT(pc); return (R_NilValue); } PROTECT(vecName = allocVector(STRSXP, n)); pc++; PROTECT(vecInt = allocVector(INTSXP, n)); pc++; // Rprintf("morphem numbers = %d \n", m1.size()); if(n < 1){ // Rprintf("(000) map length =0\n"); UNPROTECT(pc); PROTECT(vecInt = lengthgets(vecInt, 2)); PROTECT(vecName = lengthgets(vecName, 2)); // // < 2005 11 08> // #if defined(WIN32) // SET_STRING_ELT(vecName, 0, mkCharCE(buf3, CE_NATIVE)); // #elif defined(__MINGW32__) // SET_STRING_ELT(vecName, 0, mkCharCE(buf3, CE_NATIVE)); // #else // SET_STRING_ELT(vecName, 0, mkCharCE(buf3, CE_UTF8)); // #endif // // SET_STRING_ELT(vecName, 0, mkChar(buf3)); // 規程頻度以下のトークン数 // // </ 2005 11 08> SET_STRING_ELT(vecName, 0, mkCharCE(buf3, (utf8locale)?CE_UTF8:CE_NATIVE)); INTEGER(vecInt)[0] = 0; // // < 2005 11 08> // #if defined(WIN32) // SET_STRING_ELT(vecName, 1, mkCharCE( "[[TOTAL-TOKENS]]", CE_NATIVE )); // #elif defined(__MINGW32__) // SET_STRING_ELT(vecName, 1, mkCharCE( "[[TOTAL-TOKENS]]", CE_NATIVE )); // #else // SET_STRING_ELT(vecName, 1, mkCharCE( "[[TOTAL-TOKENS]]", CE_UTF8 )); // #endif // // SET_STRING_ELT(vecName, 1, mkChar( "[[TOTAL-TOKENS]]" )); // // </ 2005 11 08> SET_STRING_ELT(vecName, 1, mkCharCE( "[[TOTAL-TOKENS]]", (utf8locale)?CE_UTF8:CE_NATIVE )); // テキスト総トークン数をセット INTEGER(vecInt)[1] = totalM; SET_NAMES(vecInt, vecName);// UNPROTECT(pc); // Rprintf("(000) OUT \n"); return (vecInt); } pa = m1.begin(); // // PROTECT(mydf = allocVector(VECSXP, 2));//2 列のdata.frame // // pc++; // // SET_VECTOR_ELT(mydf, 0, allocVector(STRSXP, n));//形態素原型 // // SET_VECTOR_ELT(mydf, 1, allocVector(INTSXP, n));// 頻度 // // PROTECT(tmp = mkString("data.frame")); // // pc++; // // //df 内ベクトルの名前を用意 // // PROTECT(varlabels = allocVector(STRSXP, 2)); // // pc++; // // // その単純な初期化 // // SET_STRING_ELT(varlabels, 0, mkChar("Term")); // // SET_STRING_ELT(varlabels, 1, mkChar("Freq")); // Rprintf("(start) length(vecInt) = %d \n",length(vecInt) ); zz = 0;// 実際にベクトルに収納された要素数 // map の内容を vector にして返す for ( z = 0; z < n; z++) { // Rprintf("mFreq - %d ; pa->second = %d \n", mFreq, pa->second ); // // char s [256]; // // strcpy(s, (pa->first).c_str()); // // SET_VECTOR_ELT(VECTOR_ELT(mydf, 0), z, mkChar((pa->first).c_str())); // // INTEGER(VECTOR_ELT(mydf,1))[z] = pa->second;// 最後に頻度情報 if( (pa->second) < mFreq){ mF = mF + (pa->second); } else{ // // < 2005 11 08> // #if defined(WIN32) // SET_STRING_ELT(vecName, zz, mkCharCE((pa->first).c_str(), CE_NATIVE )); // #elif defined(__MINGW32__) // SET_STRING_ELT(vecName, zz, mkCharCE((pa->first).c_str() , CE_NATIVE)); // #else // SET_STRING_ELT(vecName, zz, mkCharCE((pa->first).c_str() , CE_UTF8)); // #endif // //SET_STRING_ELT(vecName, zz, mkChar((pa->first).c_str() )); // 形態素情報をセット // // </ 2005 11 08> SET_STRING_ELT(vecName, zz, mkCharCE((pa->first).c_str(), (utf8locale)?CE_UTF8:CE_NATIVE )); INTEGER(vecInt)[zz] = (pa->second); zz++; } pa++; }//_end_for ///// sprintf(buf3, "[[LESS-THAN-%d]]",mFreq); // Rprintf("n = %d : zz = %d\n",n ,zz ); if(zz < 1 ){ // Rprintf("(0) zz = %d \n",zz ); // // < 2005 11 08> // #if defined(WIN32) // SET_STRING_ELT(vecName, 0, mkCharCE(buf3, CE_NATIVE)); // #elif defined(__MINGW32__) // SET_STRING_ELT(vecName, 0, mkCharCE(buf3, CE_NATIVE)); // #else // SET_STRING_ELT(vecName, 0, mkCharCE(buf3, CE_UTF8)); // #endif // //SET_STRING_ELT(vecName, 0, mkChar(buf3)); // 規程頻度以下のトークン数 // // </ 2005 11 08> SET_STRING_ELT(vecName, 0, mkCharCE(buf3, (utf8locale)?CE_UTF8:CE_NATIVE)); INTEGER(vecInt)[0] = mF; // // < 2005 11 08> // #if defined(WIN32) // SET_STRING_ELT(vecName, 1, mkCharCE( "[[TOTAL-TOKENS]]", CE_NATIVE )); // #elif defined(__MINGW32__) // SET_STRING_ELT(vecName, 1, mkCharCE( "[[TOTAL-TOKENS]]", CE_NATIVE )); // #else // SET_STRING_ELT(vecName, 1, mkCharCE( "[[TOTAL-TOKENS]]", CE_UTF8 )); // #endif // //SET_STRING_ELT(vecName, 1, mkChar( "[[TOTAL-TOKENS]]" )); // // </ 2005 11 08> SET_STRING_ELT(vecName, 1, mkCharCE( "[[TOTAL-TOKENS]]", (utf8locale)?CE_UTF8:CE_NATIVE )); // テキスト総トークン数をセット INTEGER(vecInt)[1] = totalM; UNPROTECT(pc); PROTECT(vecInt = lengthgets(vecInt, 2)); PROTECT(vecName = lengthgets(vecName, 2)); // UNPROTECT(pc); // return(R_NilValue); }else if(zz == n){// 二つ足す // Rprintf("(1) zz = %d \n",zz ); UNPROTECT(pc); PROTECT(vecInt = lengthgets(vecInt, zz+2)); PROTECT(vecName = lengthgets(vecName, zz+2)); // Rprintf("(2) zz = %d \n", zz ); // // < 2005 11 08> // #if defined(WIN32) // SET_STRING_ELT(vecName, zz , mkCharCE(buf3, CE_NATIVE)); // #elif defined(__MINGW32__) // SET_STRING_ELT(vecName, zz , mkCharCE(buf3, CE_NATIVE)); // #else // SET_STRING_ELT(vecName, zz , mkCharCE(buf3, CE_UTF8)); // #endif // //SET_STRING_ELT(vecName, zz , mkChar(buf3)); // 規程頻度以下のトークン数 // // </ 2005 11 08> SET_STRING_ELT(vecName, zz , mkCharCE(buf3, (utf8locale)?CE_UTF8:CE_NATIVE)); INTEGER(vecInt)[zz] = mF; // // < 2005 11 08> // #if defined(WIN32) // SET_STRING_ELT(vecName, zz+1 , mkCharCE( "[[TOTAL-TOKENS]]", CE_NATIVE )); // #elif defined(__MINGW32__) // SET_STRING_ELT(vecName, zz+1 , mkCharCE( "[[TOTAL-TOKENS]]", CE_NATIVE )); // #else // SET_STRING_ELT(vecName, zz+1 , mkCharCE( "[[TOTAL-TOKENS]]", CE_UTF8 )); // #endif // // SET_STRING_ELT(vecName, zz+1 , mkChar( "[[TOTAL-TOKENS]]" )); //// テキスト総トークン数をセット // // </ 2005 11 08> SET_STRING_ELT(vecName, zz+1 , mkCharCE( "[[TOTAL-TOKENS]]", (utf8locale)?CE_UTF8:CE_NATIVE )); INTEGER(vecInt)[zz+1] = totalM; }else if(zz+1 == n){// 二つ足す // Rprintf("(3) zz = %d \n", zz ); UNPROTECT(pc); PROTECT(vecInt = lengthgets(vecInt, zz+2)); PROTECT(vecName = lengthgets(vecName, zz+2)); // Rprintf("(2) zz = %d \n", zz ); // // < 2005 11 08> // #if defined(WIN32) // SET_STRING_ELT(vecName, zz-1 , mkCharCE(buf3, CE_NATIVE)); // #elif defined(__MINGW32__) // SET_STRING_ELT(vecName, zz-1 , mkCharCE(buf3, CE_NATIVE)); // #else // SET_STRING_ELT(vecName, zz-1 , mkCharCE(buf3, CE_UTF8)); // #endif // //SET_STRING_ELT(vecName, zz-1 , mkChar(buf3)); // 規程頻度以下のトークン数 // // </ 2005 11 08> SET_STRING_ELT(vecName, zz-1 , mkCharCE(buf3, (utf8locale)?CE_UTF8:CE_NATIVE)); INTEGER(vecInt)[zz-1] = mF; // // < 2005 11 08> // #if defined(WIN32) // SET_STRING_ELT(vecName, zz , mkCharCE( "[[TOTAL-TOKENS]]", CE_NATIVE )); // #elif defined(__MINGW32__) // SET_STRING_ELT(vecName, zz , mkCharCE( "[[TOTAL-TOKENS]]", CE_NATIVE )); // #else // SET_STRING_ELT(vecName, zz , mkCharCE( "[[TOTAL-TOKENS]]", CE_UTF8 )); // #endif // //SET_STRING_ELT(vecName, zz , mkChar( "[[TOTAL-TOKENS]]" )); //// テキスト総トークン数をセット // // </ 2005 11 08> SET_STRING_ELT(vecName, zz , mkCharCE( "[[TOTAL-TOKENS]]", (utf8locale)?CE_UTF8:CE_NATIVE )); INTEGER(vecInt)[zz] = totalM; }else if(zz+2 == n){// 一つ足す // Rprintf("(4) zz = %d \n", zz ); UNPROTECT(pc); PROTECT(vecInt = lengthgets(vecInt, zz+2)); PROTECT(vecName = lengthgets(vecName, zz+2)); // // < 2005 11 08> // #if defined(WIN32) // SET_STRING_ELT(vecName, zz , mkCharCE(buf3, CE_NATIVE)); // #elif defined(__MINGW32__) // SET_STRING_ELT(vecName, zz , mkCharCE(buf3, CE_NATIVE)); // #else // SET_STRING_ELT(vecName, zz , mkCharCE(buf3, CE_UTF8)); // #endif // // SET_STRING_ELT(vecName, zz , mkChar(buf3)); // 規程頻度以下のトークン数 // // </ 2005 11 08> SET_STRING_ELT(vecName, zz , mkCharCE(buf3, (utf8locale)?CE_UTF8:CE_NATIVE)); INTEGER(vecInt)[zz] = mF; // // < 2005 11 08> // #if defined(WIN32) // SET_STRING_ELT(vecName, zz+1 , mkCharCE( "[[TOTAL-TOKENS]]", CE_NATIVE )); // #elif defined(__MINGW32__) // SET_STRING_ELT(vecName, zz+1 , mkCharCE( "[[TOTAL-TOKENS]]", CE_NATIVE )); // #else // SET_STRING_ELT(vecName, zz+1 , mkCharCE( "[[TOTAL-TOKENS]]", CE_UTF8 )); // #endif // //SET_STRING_ELT(vecName, zz+1 , mkChar( "[[TOTAL-TOKENS]]" )); //// テキスト総トークン数をセット // // </ 2005 11 08> SET_STRING_ELT(vecName, zz+1 , mkCharCE( "[[TOTAL-TOKENS]]", (utf8locale)?CE_UTF8:CE_NATIVE )); INTEGER(vecInt)[zz+1] = totalM; }else if(zz +2 < n){ // // < 2005 11 08> // #if defined(WIN32) // SET_STRING_ELT(vecName, zz, mkCharCE(buf3, CE_NATIVE)); // #elif defined(__MINGW32__) // SET_STRING_ELT(vecName, zz, mkCharCE(buf3, CE_NATIVE)); // #else // SET_STRING_ELT(vecName, zz, mkCharCE(buf3, CE_UTF8)); // #endif // // SET_STRING_ELT(vecName, zz, mkChar(buf3)); // 規程頻度以下のトークン数 // // </ 2005 11 08> SET_STRING_ELT(vecName, zz, mkCharCE(buf3, (utf8locale)?CE_UTF8:CE_NATIVE)); INTEGER(vecInt)[zz] = mF; // // < 2005 11 08> // #if defined(WIN32) // SET_STRING_ELT(vecName, zz+1, mkCharCE( "[[TOTAL-TOKENS]]", CE_NATIVE )); // #elif defined(__MINGW32__) // SET_STRING_ELT(vecName, zz+1, mkCharCE( "[[TOTAL-TOKENS]]", CE_NATIVE )); // #else // SET_STRING_ELT(vecName, zz+1, mkCharCE( "[[TOTAL-TOKENS]]", CE_UTF8 )); // #endif // // SET_STRING_ELT(vecName, zz+1, mkChar( "[[TOTAL-TOKENS]]" )); // テキスト総トークン数をセット // // </ 2005 11 08> SET_STRING_ELT(vecName, zz+1, mkCharCE( "[[TOTAL-TOKENS]]", (utf8locale)?CE_UTF8:CE_NATIVE )); INTEGER(vecInt)[zz+1] = totalM; UNPROTECT(pc); PROTECT(vecInt = lengthgets(vecInt, zz+2)); PROTECT(vecName = lengthgets(vecName, zz+2)); } zz = 0; mF = 0; totalM = 0; // Rprintf("* "); // // データフレームオブジェクト mydf の属性設定 // // setAttrib(mydf, R_ClassSymbol, tmp); // // setAttrib(mydf, R_NamesSymbol, varlabels); // // // 行名を指定.必須 // // PROTECT(row_names = allocVector(STRSXP, n)); // // pc++; // // char labelbuff[n]; // // for (int z = 0; z < n; z++) { // // sprintf(labelbuff, "%d", z+1); // // SET_STRING_ELT(row_names, z, mkChar(labelbuff)); // // } // // setAttrib(mydf, R_RowNamesSymbol, row_names); SET_NAMES(vecInt, vecName);// UNPROTECT(pc); return (vecInt); } return(R_NilValue); } }// end_extern ///////////////////////////////////////////////
[ "ishida.motohiro@tokushima-u.ac.jp" ]
ishida.motohiro@tokushima-u.ac.jp
0a560c58cc175937ba9474a91f3bdedabf643db5
e5c963f724be0e76db790093d1c0712adb66a7a9
/4_texturaYluz/grafoparam.h
96330c00b7bc5009f1d8dfef1861a8b1a02a23b8
[]
no_license
yurenadelpeso/OpenGL
b27d0c5a07a06217555b575bdeacd066f91b611a
599148999f632de58cde503d3767c2203b1edfcd
refs/heads/master
2020-12-18T12:29:07.879646
2020-01-22T15:39:37
2020-01-22T15:39:37
235,381,255
0
0
null
null
null
null
UTF-8
C++
false
false
2,695
h
// ############################################################################# // // Informática Gráfica (Grado Informática) // // Archivo: GrafoParam.h // -- declaraciones de clase para el objeto jerárquico de la práctica 3 // // ############################################################################# #ifndef GRAFOPARAM_H_INCLUDED #define GRAFOPARAM_H_INCLUDED #include "malla.h" // añadir .h de cualquier objetos malla indexada usados.... constexpr int num_parametros = 4 ; // número de parámetros o grados de libertad // de este modelo typedef int ModoVis; class GrafoParam { public: // crea mallas indexadas (nodos terminales del grafo) GrafoParam(); // función principal de visualización void draw( const int p_modo_vis, const bool p_usar_diferido ); // actualizar valor efectivo de un parámetro (a partir de su valor no acotado) void actualizarValorEfe( const unsigned iparam, const float valor_na ); // devuelve el número de parámetros unsigned numParametros() { return num_parametros ; } private: void miDibujo(const int p_modo_vis, const bool p_usar_diferido); void miDibujo1(const int p_modo_vis, const bool p_usar_diferido); void miDibujo2(const int p_modo_vis, const bool p_usar_diferido); void rueda(const int p_modo_vis, const bool p_usar_diferido); void parRueda(const int p_modo_vis, const bool p_usar_diferido); void cuerpoBajo(const int p_modo_vis, const bool p_usar_diferido); void cuatroRuedas(const int p_modo_vis, const bool p_usar_diferido); void cuerpoAlto(const int p_modo_vis, const bool p_usar_diferido); void canyon(const int p_modo_vis, const bool p_usar_diferido); void tanque(const int p_modo_vis, const bool p_usar_diferido); // métodos de dibujo de subgrafos void columna( const float altura, const float ag_rotacion, const float radio_cil ); // objetos tipo malla indexada (nodos terminales) Cilindro * cilindro = nullptr ; Cubo * cubo = nullptr ; std::vector<float> movimientos; // parámetros de la llamada actual (o última) a 'draw' int modo_vis ; // modo de visualización bool usar_diferido ; // modo de envío (true -> diferido, false -> inmediato) // valores efectivos de los parámetros (angulos, distancias, factores de // escala, etc.....) calculados a partir de los valores no acotados float altura_1, // altura de la primera columna ag_rotacion_1, // ángulo en grados de rotación (1) altura_2, // altura de la segunda columna ag_rotacion_2 ; // ángulo en grados de rotación (2) } ; #endif
[ "yurenadelpeso@protonmail.com" ]
yurenadelpeso@protonmail.com
c0313fba7a58c8d1d378ce149c30fe2bc8687822
4a13e4b7dd038ed801cc41e47bbd49b44c23692a
/Cat/Pie.h
9eaff543780efca692580ae1425737188d11af03
[]
no_license
SchemIng/Cat
90fc90f6a56f06bf998159beb2dfd3d822997411
79aea3d2cd283953d6347dc8b591014bb41d9b30
refs/heads/master
2021-01-10T15:34:26.469746
2016-01-04T03:07:57
2016-01-04T03:07:57
48,970,740
0
0
null
null
null
null
UTF-8
C++
false
false
226
h
#pragma once #include "Bill.h" class CPie { public: CPie(CPaintDC* dc, CPoint o, int r); ~CPie(); void Draw(vector<CBill> bills); private: CPoint o; int r; CPaintDC dc; void count(vector<CBill> bills, double* a); };
[ "1055062460@qq.com" ]
1055062460@qq.com
747609b8c6187b661b33e0dca0d1d28edc801e7f
693d9feddd6d151173b7bb6753681f2bab6e3dd0
/src/servidor/modelo/fisicas/transformaciones/Reubicar.cpp
9a0c8e876cd78ecda32ad2e0f44697ee3f6677b5
[]
no_license
mateoicalvo/micromachines_cpp
e2e02971f0c170ec1054bf6642b263ef0fe5ebf6
06e6f608ff7ca00435a605aba2f6d0072079b913
refs/heads/main
2023-02-15T23:48:08.912214
2021-01-14T10:19:46
2021-01-14T10:19:46
329,439,942
0
0
null
null
null
null
UTF-8
C++
false
false
651
cpp
#include "includes/servidor/modelo/fisicas/transformaciones/Reubicar.h" #include "includes/3rd-party/Box2D/Box2D.h" #include "includes/servidor/modelo/movimiento/Posicion.h" #ifndef DEGTORAD #define DEGTORAD 0.0174532925199432957f #define RADTODEG 57.295779513082320876f #endif Reubicar::Reubicar(Fisicas& fisicas, b2Body* cuerpo, Posicion& posicion) : Transformacion(fisicas), cuerpo_(cuerpo), posicion_(posicion) { } void Reubicar::aplicar() { cuerpo_->SetTransform(b2Vec2(posicion_.x_, posicion_.y_), (float)posicion_.anguloDeg_*DEGTORAD); cuerpo_->SetLinearVelocity(b2Vec2(0, 0)); cuerpo_->SetAngularVelocity(0.0f); }
[ "macalvo@fi.uba.ar" ]
macalvo@fi.uba.ar
c0e5b8853a72fb102664c29f6996d7bef2b4caae
47c1438e4eabe800987865b8bdaad3a9a70ab172
/utils/utils.hpp
a56c6915da9fcd7e9bc37b5481269f5ec4554961
[]
no_license
gongcm/Server
323bf8c1a6938bc5e5734440bbf25eb8fcaffb5b
07b4d6a519135a6fb4f418064839ae51cf951614
refs/heads/master
2020-03-15T15:30:00.767247
2018-05-05T11:31:42
2018-05-05T11:31:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
375
hpp
#include <iostream> #include <sys/stat.h> #include <unistd.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #include <fcntl.h> #include <sys/shm.h> #include <sys/utsname.h> #include <dirent.h> class utils{ public: static int getSystemVersion(); static int getFilelist(char * path,list_t &list); };
[ "gcm1994g@163.com" ]
gcm1994g@163.com
9f2d595c99b4f7421bbe1f15a5733e1c8c143f41
5c77807c8a39658e995c00adecb5f9e3bde0884d
/opengl/Source/Shader/main.cpp
5e7a3f06f7f2a08402b1346318ab9a04409a5fe2
[]
no_license
starlitnext/practice
6a39b116213caaf014875b32d048ff5f2d6ca190
3d1be394c7c7cc444a10cfd878caacb2f592b653
refs/heads/master
2021-01-18T21:33:09.692397
2018-01-24T15:23:25
2018-01-24T15:23:25
40,886,119
1
0
null
null
null
null
UTF-8
C++
false
false
3,571
cpp
#include <iostream> #include "Common.hpp" #include "Shader.hpp" // Function prototypes void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode); // Window dimensions const GLuint WIDTH = 800, HEIGHT = 600; int main() { // ---------------------------------------------------------------- // Init GLFW glfwInit(); // Set all the required options for GLFW glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); // Create a GLFWwindow object that we can use for GLFW's functions GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr); glfwMakeContextCurrent(window); // Set the required callback functions glfwSetKeyCallback(window, key_callback); // Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions glewExperimental = GL_TRUE; // Initialize GLEW to setup the OpenGL Function pointers glewInit(); // Define the viewport dimensions glViewport(0, 0, WIDTH, HEIGHT); // ---------------------------------------------------------------- // Build and compile our shader program Shader ourShader("F:\\workspace\\c++\\demos\\HelloWorld\\OpenGL\\Source\\Shader\\shader.vs", "F:\\workspace\\c++\\demos\\HelloWorld\\OpenGL\\Source\\Shader\\shader.frag"); // ---------------------------------------------------------------- // Set up vertex data (and buffer(s)) and attribute pointers GLfloat vertices[] = { // Positions // Colors 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, // Bottom Right -0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, // Bottom Left 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f // Top }; GLuint VBO, VAO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); // Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s). glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // Position attribute glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); // Color attribute glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glEnableVertexAttribArray(1); glBindVertexArray(0); // Unbind VAO // ---------------------------------------------------------------- // Game loop while (!glfwWindowShouldClose(window)) { // Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions glfwPollEvents(); // Render // Clear the colorbuffer glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); // Draw the triangle ourShader.Use(); glBindVertexArray(VAO); glDrawArrays(GL_TRIANGLES, 0, 3); glBindVertexArray(0); // Swap the screen buffers glfwSwapBuffers(window); } // Properly de-allocate all resources once they've outlived their purpose glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); // Terminate GLFW, clearing any resources allocated by GLFW. glfwTerminate(); return 0; } // Is called whenever a key is pressed/released via GLFW void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, GL_TRUE); }
[ "gzxuxiaoqiang@game.ntes" ]
gzxuxiaoqiang@game.ntes
aa4d7853d94585a56c6818a1e0479301c126b674
025c78a4ed41519b08238afb2e6389d29a955893
/ch02/ex202.cpp
9eb1e625923322f398d1d77534a5a552dc6b8682
[]
no_license
ArtemNikolaev/opp-in-cpp
09a92282c56337b994160be66db5f323ee029640
b13373bdbd3b33b1c2953e88c626046f3ca635e7
refs/heads/master
2023-04-01T11:31:43.262127
2021-03-28T13:30:33
2021-03-28T13:30:33
334,686,841
0
0
null
null
null
null
UTF-8
C++
false
false
378
cpp
#include <iostream> #include <iomanip> int main() { std::cout << std::setw(4) << 1990 << std::setw(9) << 135 << std::endl; std::cout << std::setw(4) << 1991 << std::setw(9) << 7290 << std::endl; std::cout << std::setw(4) << 1992 << std::setw(9) << 11300 << std::endl; std::cout << std::setw(4) << 1993 << std::setw(9) << 16200 << std::endl; return 0; }
[ "artem@nikolaev.by" ]
artem@nikolaev.by
3711faf1f6c02f323de756c2e0452ed7bbe95aec
21f553e7941c9e2154ff82aaef5e960942f89387
/include/algorithms/neural_networks/layers/fullyconnected/fullyconnected_layer_backward.h
94f96c7047aab261a07873b287a9ab157a3c88de
[ "Apache-2.0", "Intel" ]
permissive
tonythomascn/daal
7e6fe4285c7bb640cc58deb3359d4758a9f5eaf5
3e5071f662b561f448e8b20e994b5cb53af8e914
refs/heads/daal_2017_update2
2021-01-19T23:05:41.968161
2017-04-19T16:18:44
2017-04-19T16:18:44
88,920,723
1
0
null
2017-04-20T23:54:18
2017-04-20T23:54:18
null
UTF-8
C++
false
false
8,487
h
/* file: fullyconnected_layer_backward.h */ /******************************************************************************* * Copyright 2014-2017 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ /* //++ // Implementation of the interface for the backward fully-connected layer // in the batch processing mode //-- */ #ifndef __FULLYCONNECTED_LAYER_BACKWARD_H__ #define __FULLYCONNECTED_LAYER_BACKWARD_H__ #include "algorithms/algorithm.h" #include "data_management/data/tensor.h" #include "services/daal_defines.h" #include "algorithms/neural_networks/layers/layer.h" #include "algorithms/neural_networks/layers/fullyconnected/fullyconnected_layer_types.h" #include "algorithms/neural_networks/layers/fullyconnected/fullyconnected_layer_backward_types.h" namespace daal { namespace algorithms { namespace neural_networks { namespace layers { namespace fullyconnected { namespace backward { namespace interface1 { /** * @defgroup fullyconnected_backward_batch Batch * @ingroup fullyconnected_backward * @{ */ /** * <a name="DAAL-CLASS-ALGORITHMS__NEURAL_NETWORKS__LAYERS__FULLYCONNECTED__BACKWARD__BATCHCONTAINER"></a> * \brief Provides methods to run implementations of the of the backward fully-connected layer * This class is associated with the daal::algorithms::neural_networks::layers::fullyconnected::backward::Batch class * and supports the method of backward fully-connected layer computation in the batch processing mode * * \tparam algorithmFPType Data type to use in intermediate computations of backward fully-connected layer, double or float * \tparam method Computation method of the layer, \ref daal::algorithms::neural_networks::layers::fullyconnected::Method * \tparam cpu Version of the cpu-specific implementation of the layer, \ref daal::CpuType */ template<typename algorithmFPType, Method method, CpuType cpu> class DAAL_EXPORT BatchContainer : public AnalysisContainerIface<batch> { public: /** * Constructs a container for the backward fully-connected layer with a specified environment * in the batch processing mode * \param[in] daalEnv Environment object */ BatchContainer(daal::services::Environment::env *daalEnv); /** Default destructor */ ~BatchContainer(); /** * Computes the result of the backward fully-connected layer in the batch processing mode */ void compute() DAAL_C11_OVERRIDE; }; /** * <a name="DAAL-CLASS-ALGORITHMS__NEURAL_NETWORKS__LAYERS__FULLYCONNECTED__BACKWARD__BATCH"></a> * \brief Provides methods for backward fully-connected layer computations in the batch processing mode * \n<a href="DAAL-REF-FULLYCONNECTEDBACKWARD-ALGORITHM">Backward fully-connected layer description and usage models</a> * * \tparam algorithmFPType Data type to use in intermediate computations of backward fully-connected layer, double or float * \tparam method Computation method of the layer, \ref Method * * \par Enumerations * - \ref Method Computation methods for the backward fully-connected layer * - \ref LayerDataId Identifiers of input objects for the backward fully-connected layer * * \par References * - forward::interface1::Batch class */ template<typename algorithmFPType = float, Method method = defaultDense> class Batch : public layers::backward::LayerIface { public: Parameter &parameter; /*!< \ref interface1::Parameter "Parameters" of the layer */ Input input; /*!< %Input objects of the layer */ /** * Constructs backward fully-connected layer * \param[in] nOutputs A number of layer outputs */ Batch(const size_t nOutputs) : _defaultParameter(nOutputs), parameter(_defaultParameter) { initialize(); }; /** * Constructs a backward fully-connected layer in the batch processing mode * and initializes its parameter with the provided parameter * \param[in] parameter Parameter to initialize the parameter of the layer */ Batch(Parameter& parameter) : parameter(parameter), _defaultParameter(parameter) { initialize(); } /** * Constructs backward fully-connected layer by copying input objects and parameters of another fully-connected layer * \param[in] other A layer to be used as the source to initialize the input objects * and parameters of this layer */ Batch(const Batch<algorithmFPType, method> &other): _defaultParameter(other.parameter), parameter(_defaultParameter) { initialize(); input.set(layers::backward::inputGradient, other.input.get(layers::backward::inputGradient)); input.set(layers::backward::inputFromForward, other.input.get(layers::backward::inputFromForward)); } /** * Returns computation method of the layer * \return Computation method of the layer */ virtual int getMethod() const DAAL_C11_OVERRIDE { return(int) method; } /** * Returns the structure that contains input objects of fully-connected layer * \return Structure that contains input objects of fully-connected layer */ virtual Input *getLayerInput() DAAL_C11_OVERRIDE { return &input; } /** * Returns the structure that contains parameters of the backward fully-connected layer * \return Structure that contains parameters of the backward fully-connected layer */ virtual Parameter *getLayerParameter() DAAL_C11_OVERRIDE { return &parameter; }; /** * Returns the structure that contains results of fully-connected layer * \return Structure that contains results of fully-connected layer */ services::SharedPtr<layers::backward::Result> getLayerResult() DAAL_C11_OVERRIDE { return getResult(); } /** * Returns the structure that contains results of fully-connected layer * \return Structure that contains results of fully-connected layer */ services::SharedPtr<Result> getResult() { return _result; } /** * Registers user-allocated memory to store results of fully-connected layer * \param[in] result Structure to store results of fully-connected layer */ void setResult(const services::SharedPtr<Result>& result) { DAAL_CHECK(result, ErrorNullResult) _result = result; _res = _result.get(); } /** * Returns a pointer to the newly allocated fully-connected layer * with a copy of input objects and parameters of this fully-connected layer * \return Pointer to the newly allocated layer */ services::SharedPtr<Batch<algorithmFPType, method> > clone() const { return services::SharedPtr<Batch<algorithmFPType, method> >(cloneImpl()); } /** * Allocates memory to store the result of the backward fully-connected layer */ virtual void allocateResult() DAAL_C11_OVERRIDE { this->_result->template allocate<algorithmFPType>(&(this->input), &parameter, (int) method); this->_res = this->_result.get(); } protected: virtual Batch<algorithmFPType, method> *cloneImpl() const DAAL_C11_OVERRIDE { return new Batch<algorithmFPType, method>(*this); } void initialize() { Analysis<batch>::_ac = new __DAAL_ALGORITHM_CONTAINER(batch, BatchContainer, algorithmFPType, method)(&_env); input = fullyconnected::backward::Input(); _in = &input; _par = &parameter; _result = services::SharedPtr<Result>(new Result()); } private: services::SharedPtr<Result> _result; Parameter _defaultParameter; }; /** @} */ } // namespace interface1 using interface1::BatchContainer; using interface1::Batch; } // namespace backward } // namespace fullyconnected } // namespace layers } // namespace neural_networks } // namespace algorithms } // namespace daal #endif
[ "vasily.rubtsov@intel.com" ]
vasily.rubtsov@intel.com
49253809c76f108e98b2afcee193135537c64487
aab7eafab5efae62cb06c3a2b6c26fe08eea0137
/preparetuplesforBDTfinalallvartrigger/MCSigpreparetupleNewL0/src/mainincludebreak.cc
55d5836a79b1b3b9c54a914a419ced08349480db
[]
no_license
Sally27/B23MuNu_backup
397737f58722d40e2a1007649d508834c1acf501
bad208492559f5820ed8c1899320136406b78037
refs/heads/master
2020-04-09T18:12:43.308589
2018-12-09T14:16:25
2018-12-09T14:16:25
160,504,958
0
1
null
null
null
null
UTF-8
C++
false
false
9,477
cc
#include <iostream> #include<sstream> #include<string> #include<vector> #include<fstream> #include "TH1F.h" #include "TH3F.h" #include "TCanvas.h" #include "TFile.h" #include "TTree.h" #include "TLorentzVector.h" #include "TVector3.h" #include "TBranch.h" #include "TRandom.h" #include "TBranch.h" #include "TString.h" #include<algorithm> #include "TTreeFormula.h" #include "alltogetherMC.hpp" #include<iostream> using namespace std; int main(){ ofstream out; out.open("EfficienciesBreakNT.tex"); out<<"\\documentclass[a4paper,11pt]{article}"<<endl; out<<"\\usepackage[pdftex]{graphicx}"<<endl; out<<"\\usepackage{url}"<<endl; out<<"\\usepackage{mathtools}"<<endl; out<<"\\usepackage{amsmath}"<<endl; out<<"\\usepackage{graphicx}"<<endl; out<<"\\usepackage[table]{xcolor}"<<endl; out<<"\\usepackage{amsmath,amssymb}"<<endl; out<<"\\usepackage[top=25mm,bottom=25mm,left=25mm,right=25mm]{geometry}"<<endl; out<<"\\usepackage{colortbl}"<<endl; out<<"\\begin{document}"<<endl; out<<"\\begin{table}[ht]"<<endl; out<<"\\begin{center}"<<endl; out<<"\\begin{tabular}{| l | l | l | l |}"<<endl; out<<"\\hline"<<endl; out<<"Cut & $\\epsilon$ & N & error \\\\ "<<endl; out<<"\\hline"<<endl; double toteff(0); string pathname = "/vols/lhcb/ss4314/tuplesallvar/B23MuNuMCL0/"; string filename = "B23MuMC2012L0data"; string decaytreename = "B23MuNu_Tuple/DecayTree"; string ext = ".root"; string cuttag = "_MCtruth"; string filename2 = (filename+cuttag).c_str(); double decprodcut2 =0.185; double effrecostrip2= 0.111; out << "$\\epsilon_{decprodcut}$ &" << decprodcut2 << " & " << "(3544)10000" << " & "<< (sqrt(double(3544)*(1.0-((double(3544)/double(10000))))))*(1/double(10000))<<" \\\\ "<<endl; out << "$\\epsilon_{reco}$ &" << effrecostrip2 << " & "<<"(124051)1114130" << " & "<< (sqrt(double(124051)*(1.0-((double(124051)/double(1114130))))))*(1/double(1114130)) <<" \\\\ "<<endl; double mctrutheff; mctrutheff=mctruth((pathname+filename).c_str(), decaytreename, (filename2).c_str()); out << "$\\epsilon_{MC}$ &" << mctrutheff <<" - & "<< " - & " << " \\\\ "<<endl; convertbranchname(filename2, "DecayTree", filename2); addqsqinf(filename2, "DecayTree", filename2); addcostheta(filename2, "DecayTree", filename2); double L0eff(0); L0eff=calculateL0effMC(filename2, "DecayTree", "miau"); toteff = L0eff; cutTree((filename2+ext).c_str(),"DecayTree",(filename2+"_L0MuonDecisionTOS"+ext).c_str(),"Bplus_L0MuonDecision_TOS==1.0"); string filenameclean=(filename2+"_L0MuonDecisionTOS").c_str(); string file=(filename2+"_L0MuonDecisionTOS").c_str(); out << "$\\epsilon_{L0}$ &" << L0eff <<"&"<< getmyentries((filenameclean+ext).c_str(),"DecayTree") << " & " << " \\\\ "<<endl; vector<string> varia; varia.push_back("trigger"); varia.push_back("qmincut"); vector<string> vals; vals.push_back("(Bplus_Hlt1TrackMuonDecision_TOS==1.0) && ((Bplus_Hlt2TopoMu2BodyBBDTDecision_TOS==1.0) || (Bplus_Hlt2TopoMu3BodyBBDTDecision_TOS==1.0) || (Bplus_Hlt2DiMuonDetachedDecision_TOS==1.0) || (Bplus_Hlt2DiMuonDetachedHeavyDecision_TOS==1.0))"); vals.push_back("minq2 < 960400"); for(int i(0);i<1;i++) { double eff; double error; int numofentriesbefore; int numofentriesafter; eff=cutTree((filenameclean+ext).c_str(), "DecayTree", (filenameclean+"_"+varia.at(i)+ext).c_str(), (vals.at(i)).c_str()); numofentriesbefore= getmyentries((filenameclean+ext).c_str(),"DecayTree"); numofentriesafter= getmyentries((filenameclean+"_"+varia.at(i)+ext).c_str(),"DecayTree"); error = (sqrt(double(numofentriesafter)*(1-((double(numofentriesafter)/double(numofentriesbefore))))))*(1/double(numofentriesbefore)); out<<"$\\epsilon_{"+varia.at(i)+"}$ & "<<eff<<" & "<<numofentriesafter<<" & "<<error<<" \\\\ "<<endl; filenameclean=(filenameclean+"_"+varia.at(i)).c_str(); toteff=toteff*eff; } double jpsieff; jpsieff=Jpsi((filenameclean).c_str(), "DecayTree", (filenameclean+"_Jpsi").c_str()); double error; int numofentriesbefore; int numofentriesafter; numofentriesbefore= getmyentries((filenameclean+ext).c_str(),"DecayTree"); numofentriesafter= getmyentries((filenameclean+"_Jpsi"+ext).c_str(),"DecayTree"); error = (sqrt(double(numofentriesafter)*(1-((double(numofentriesafter)/double(numofentriesbefore))))))*(1/double(numofentriesbefore)); out << "$\\epsilon_{Jpsi}$ &" << jpsieff<<" & "<<numofentriesafter<<" & "<<error << " \\\\ "<<endl; toteff=toteff*jpsieff; filenameclean=(filenameclean+"_Jpsi").c_str(); for(int i(1);i<2;i++) { double eff; double error; int numofentriesbefore; int numofentriesafter; eff=cutTree((filenameclean+ext).c_str(), "DecayTree", (filenameclean+"_"+varia.at(i)+ext).c_str(), (vals.at(i)).c_str()); numofentriesbefore= getmyentries((filenameclean+ext).c_str(),"DecayTree"); numofentriesafter= getmyentries((filenameclean+"_"+varia.at(i)+ext).c_str(),"DecayTree"); error = (sqrt(double(numofentriesafter)*(1-((double(numofentriesafter)/double(numofentriesbefore))))))*(1/double(numofentriesbefore)); out<<"$\\epsilon_{"+varia.at(i)+"}$ & "<<eff<<" & "<<numofentriesafter<<" & "<<error<<" \\\\ "<<endl; filenameclean=(filenameclean+"_"+varia.at(i)).c_str(); toteff=toteff*eff; } out<<"\\hline"<<endl; out<<"$\\epsilon_{totaleff}$ & "<<toteff<<" \\\\ "<<endl; out<<"\\hline"<<endl; addKFoldandW(filenameclean, "DecayTree", filenameclean); vals.push_back("Bplus_Hlt1TrackMuonDecision_TOS==1.0"); vals.push_back("(Bplus_Hlt2TopoMu2BodyBBDTDecision_TOS==1.0) || (Bplus_Hlt2TopoMu3BodyBBDTDecision_TOS==1.0) || (Bplus_Hlt2DiMuonDetachedDecision_TOS==1.0) || (Bplus_Hlt2DiMuonDetachedHeavyDecision_TOS==1.0)"); varia.push_back("Hlt1TrackMuonDecisionTOS"); varia.push_back("Hlt2orofDecisions"); string filename3=(file).c_str(); for(int i(2);i<4;i++) { double error; int numofentriesbefore; int numofentriesafter; double eff; eff=cutTree((filename3+ext).c_str(), "DecayTree", (filename3+"_"+varia.at(i)+ext).c_str(), (vals.at(i)).c_str()); numofentriesbefore= getmyentries((filename3+ext).c_str(),"DecayTree"); numofentriesafter= getmyentries((filename3+"_"+varia.at(i)+ext).c_str(),"DecayTree"); error = (sqrt(double(numofentriesafter)*(1-((double(numofentriesafter)/double(numofentriesbefore))))))*(1/double(numofentriesbefore)); out<<vals.at(i)+" & "<<eff<<" & "<<numofentriesafter<<" & "<<error<<" \\\\ "<<endl; filename3=(filename3+"_"+varia.at(i)).c_str(); } out<<"\\hline"<<endl; vals.push_back("Bplus_Hlt2TopoMu2BodyBBDTDecision_TOS==1.0"); vals.push_back("Bplus_Hlt2TopoMu3BodyBBDTDecision_TOS==1.0"); vals.push_back("Bplus_Hlt2DiMuonDetachedDecision_TOS==1.0"); vals.push_back("Bplus_Hlt2DiMuonDetachedHeavyDecision_TOS==1.0"); varia.push_back("Hlt2TopoMu2BodyBBDTDecision"); varia.push_back("Hlt2TopoMu3BodyBBDTDecision"); varia.push_back("Hlt2DiMuonDetachedDecision"); varia.push_back("Hlt2DiMuonDetachedHeavyDecision"); string filename4=(file+"_Hlt1TrackMuonDecisionTOS").c_str(); for(int i(4);i<8;i++) { double error; int numofentriesbefore; int numofentriesafter; double eff; eff=cutTree((filename4+ext).c_str(), "DecayTree", (filename4+"_"+varia.at(i)+ext).c_str(), (vals.at(i)).c_str()); numofentriesbefore= getmyentries((filename4+ext).c_str(),"DecayTree"); numofentriesafter= getmyentries((filename4+"_"+varia.at(i)+ext).c_str(),"DecayTree"); error = (sqrt(double(numofentriesafter)*(1-((double(numofentriesafter)/double(numofentriesbefore))))))*(1/double(numofentriesbefore)); out<<vals.at(i)+" & "<<eff<<" & "<<numofentriesafter<<" & "<<error<<" \\\\ "<<endl; } out<<"\\hline"<<endl; double brfr=1e-8; double ppbbX=284e-6; double bBplus= 2*0.4; double datacoll=3e15; double decprodcut =0.185; double effrecostrip= 0.111; double finalnum; finalnum=ppbbX*bBplus*brfr*datacoll*decprodcut*effrecostrip*toteff; out<<"TotSig asuming 10$^-8$ & "<<finalnum<<" \\\\ "<<endl; out<<" \\\\ "<<endl; out<<"\\hline"<<endl; out<<"\\end{tabular}"<<endl; out<<"\\end{center}"<<endl; out<<"\\caption{EFFICIENCIESMCSIG.txt}"<<endl; out<<"\\end{table}"<<endl; out<<"\\end{document}"<<endl; out.close(); // cout<<mctrutheff*jpsieff*nSharedeff*qmineff<<endl; // double brfr=1e-8; // double ppbbX=284e-6; // double bBplus= 2*0.4; // double datacoll=3e15; // double decprodcut =0.185; // double effrecostrip= 0.111; // // double finaleff; // finaleff=ppbbX*bBplus*brfr*datacoll*decprodcut*effrecostrip*jpsieff*nSharedeff*qmineff*triggereff; // cout<<"Final Num Of Events: "<<finaleff<<endl; return(0); }
[ "ss4314@ss4314-laptop.hep.ph.ic.ac.uk" ]
ss4314@ss4314-laptop.hep.ph.ic.ac.uk
14aa1ddfc8beba4bec0a50896b65f2703c446c11
5d2343977bd25cae2c43addf2e19dd027a7ae198
/Codeforces/CR630/c.cpp
c3b7dd2d77ead4093108900a255e0b966681a831
[]
no_license
ayushgupta2959/CodeReview
5ea844d180992ee80ba1f189af2ab3b0be90f5ce
7d8a5a6610c9227e458c6fda0bbc5885301788d8
refs/heads/master
2021-08-22T13:07:59.314076
2020-04-26T14:30:08
2020-04-26T14:30:08
173,270,707
1
0
null
null
null
null
UTF-8
C++
false
false
720
cpp
#include <bits/stdc++.h> using namespace std; #define sp ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) #define v(t) vector<t> #define vv(t) vector<vector<t>> #define vn(t,n,val) vector<t>(n,val) #define vvn(t,r,c,val) vector<vector<t>>(r, vector<t>(c,val)) #define vvv(t) vector<vector<vector<t>>> #define vvvn(t,l,b,h,val) vector<vector<vector<t>>>(l,vector<vector<t>>(b,vector<t>(h))) void solve(){ int n,k; string s; cin>>n>>k>>s; } int main() { sp; ////////////////To Remove////////////// freopen("../../input.txt", "r", stdin); freopen("../../output.txt", "w", stdout); /////////////////////////////////////// int t; cin>>t; while(t--){ solve(); cout<<"\n"; } return 0; }
[ "37008291+ayushgupta2959@users.noreply.github.com" ]
37008291+ayushgupta2959@users.noreply.github.com
5ac62918490a8a0d8ddd5477426003aaa55f1da6
16db2176f14d67f7e270c8ccfb263c2cc4bd90fa
/Linked List/Doubly Linked list/del_end.cpp
8ad8d8f9d98f3227d0bfa8fd26858c551de3eb54
[]
no_license
Anantm007/Ds-Algo-Programs
7416348a3a3d6f7df1761db6319ab425ea7d4431
fb2ae5b2b5fa89837c653e08e196c53db647b04d
refs/heads/master
2023-02-18T04:21:10.039700
2021-01-21T08:35:43
2021-01-21T08:35:43
330,117,532
0
0
null
null
null
null
UTF-8
C++
false
false
1,564
cpp
#include <iostream> using namespace std; struct node { int n; node *next; node *prev; node (int d) { n = d; next = NULL; prev = NULL; } }; // O (n) node *ins_end (node *head, int data) { node *temp = new node (data); if (head == NULL) { return temp; } node *cur = head; while (cur -> next != NULL) { cur = cur -> next; } cur -> next = temp; temp -> prev = cur; return head; } // O (1) node *del_head (node *head) { if (head == NULL || head -> next == NULL) { return NULL; } node *temp = head; head = head -> next; head ->prev = NULL; delete temp; return head; } // O (n) node *del_end (node *head) { if (head == NULL || head -> next == NULL) { return NULL; } node *cur = head; while (cur -> next -> next != NULL) { cur = cur -> next; } node *temp = cur -> next; cur -> next = NULL; delete temp; return head; } void print (node *head) { while (head != NULL) { cout << head -> n << " "; head = head -> next; } } int main() { node *head = NULL; head = ins_end (head, 10); head = ins_end (head, 20); head = ins_end (head, 30); head = ins_end (head, 40); print (head); head = del_end (head); cout << "\n"; print (head); head = ins_end (head, 50); head = ins_end (head, 60); cout << "\n"; print (head); head = del_end (head); cout << "\n"; print (head); return 0; }
[ "anant.mathur007@gmail.com" ]
anant.mathur007@gmail.com
b9bf14eefaaab6dfd66339820001fa8d1352f287
3438e8c139a5833836a91140af412311aebf9e86
/ash/shell/panel_window.cc
168649f032fbe31eec1674af5ac0fc88bfa837c8
[ "BSD-3-Clause" ]
permissive
Exstream-OpenSource/Chromium
345b4336b2fbc1d5609ac5a67dbf361812b84f54
718ca933938a85c6d5548c5fad97ea7ca1128751
refs/heads/master
2022-12-21T20:07:40.786370
2016-10-18T04:53:43
2016-10-18T04:53:43
71,210,435
0
2
BSD-3-Clause
2022-12-18T12:14:22
2016-10-18T04:58:13
null
UTF-8
C++
false
false
2,250
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/shell/panel_window.h" #include "ash/common/wm/panels/panel_frame_view.h" #include "ash/screen_util.h" #include "ash/shell.h" #include "base/strings/utf_string_conversions.h" #include "ui/aura/window.h" #include "ui/aura/window_event_dispatcher.h" #include "ui/gfx/canvas.h" #include "ui/views/widget/widget.h" namespace { const int kMinWidth = 100; const int kMinHeight = 100; const int kDefaultWidth = 200; const int kDefaultHeight = 300; } namespace ash { // static views::Widget* PanelWindow::CreatePanelWindow(const gfx::Rect& rect) { PanelWindow* panel_window = new PanelWindow("Example Panel Window"); panel_window->params().bounds = rect; panel_window->params().context = Shell::GetPrimaryRootWindow(); return panel_window->CreateWidget(); } PanelWindow::PanelWindow(const std::string& name) : name_(name), params_(views::Widget::InitParams::TYPE_PANEL) { params_.delegate = this; } PanelWindow::~PanelWindow() {} views::Widget* PanelWindow::CreateWidget() { views::Widget* widget = new views::Widget; if (params().bounds.width() == 0) params().bounds.set_width(kDefaultWidth); if (params().bounds.height() == 0) params().bounds.set_height(kDefaultHeight); params().bounds = ScreenUtil::ConvertRectToScreen( Shell::GetTargetRootWindow(), params().bounds); widget->Init(params()); widget->GetNativeView()->SetName(name_); widget->Show(); return widget; } gfx::Size PanelWindow::GetPreferredSize() const { return gfx::Size(kMinWidth, kMinHeight); } void PanelWindow::OnPaint(gfx::Canvas* canvas) { canvas->FillRect(GetLocalBounds(), SK_ColorGREEN); } base::string16 PanelWindow::GetWindowTitle() const { return base::ASCIIToUTF16(name_); } bool PanelWindow::CanResize() const { return true; } bool PanelWindow::CanMaximize() const { return false; } bool PanelWindow::CanMinimize() const { return false; } views::NonClientFrameView* PanelWindow::CreateNonClientFrameView( views::Widget* widget) { return new PanelFrameView(widget, PanelFrameView::FRAME_NONE); } } // namespace ash
[ "support@opentext.com" ]
support@opentext.com
30e8970bf412022ee788b617fb02408e3e9aa50b
b67a780af96a1b70569f81def205f2adbe328292
/Demo/Graph/DirectedGraph/Connected/DirectedCycle.hpp
545fdad1a8bfad451974630397cfc90e0497b853
[]
no_license
doquanghuy/Algorithm
8c27933c5c42b4324b39e061c43542adf4a6372b
4dd63edd823bd0a158034e281c37ef1f6704ec9c
refs/heads/master
2020-04-13T18:52:44.872226
2019-01-16T15:04:48
2019-01-16T15:04:48
163,387,254
0
0
null
2019-01-16T14:21:06
2018-12-28T08:36:31
null
UTF-8
C++
false
false
578
hpp
// // DirectedCycle.hpp // Demo // // Created by Quang Huy on 12/22/18. // Copyright © 2018 Techmaster. All rights reserved. // #ifndef DirectedCycle_hpp #define DirectedCycle_hpp #include <stdio.h> #include "Stack+LinkedList.hpp" class Digraph; class DirectedCycle { public: DirectedCycle(Digraph g); bool hasCycle(); Iterable<int>** cycles(); int numberCycles(); private: int _numberCycles; bool* markedVertices; Iterable<int>** _cycles; int* edges; bool* onStack; void dfs(Digraph g, int s); }; #endif /* DirectedCycle_hpp */
[ "sin.do@mobiclixgroup.com" ]
sin.do@mobiclixgroup.com
efe4916240e5925eba0b0f9e5aaccb13a9af6107
c485cb363d29d81212427d3268df1ddcda64d952
/dependencies/boost/libs/spirit/example/scheme/qi/parse_qiexpr.hpp
a9696f673e98768e60d7a1d38984b5c910845717
[ "BSL-1.0" ]
permissive
peplopez/El-Rayo-de-Zeus
66e4ed24d7d1d14a036a144d9414ca160f65fb9c
dc6f0a98f65381e8280d837062a28dc5c9b3662a
refs/heads/master
2021-01-22T04:40:57.358138
2013-10-04T01:19:18
2013-10-04T01:19:18
7,038,026
2
1
null
null
null
null
UTF-8
C++
false
false
654
hpp
// Copyright (c) 2001-2010 Hartmut Kaiser // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #if !defined(BOOST_SPIRIT_PARSE_QIEXPR) #define BOOST_SPIRIT_PARSE_QIEXPR #include <input/sexpr.hpp> namespace scheme { namespace input { template <typename String> bool parse_qi_expr(String const& str, utree& result); template <typename String> bool parse_qi_rule(String const& str, utree& result); template <typename String> bool parse_qi_grammar(String const& str, utree& result); }} #endif
[ "fibrizo.raziel@gmail.com" ]
fibrizo.raziel@gmail.com
0c07d94815348de12a9b5fb15764917aa707d913
72530b12990dc28da37e3aad3d32bf8768af630b
/CPP/cpp_pool/day04/ex02/AssaultTerminator.cpp
a65151f34cc1c8f995b9720d510b0a0d94d39338
[]
no_license
lacretelle/42_cursus
baa805415819a74535d94a9a2f2ca058080d70c0
3333da966109c1e378545137b5530148ecd7d972
refs/heads/master
2023-03-17T16:19:31.627724
2021-03-05T15:25:57
2021-03-05T15:25:57
317,812,905
0
0
null
null
null
null
UTF-8
C++
false
false
940
cpp
#include "AssaultTerminator.hpp" AssaultTerminator::AssaultTerminator() { std::cout << "* teleports from space *" << std::endl; } AssaultTerminator::AssaultTerminator(AssaultTerminator const &src) { std::cout << "copy" << std::endl; *this = src; } AssaultTerminator & AssaultTerminator::operator=(AssaultTerminator const &src) { std::cout << "ENTER in operstor =" << std::endl; (void)src; return *this; } AssaultTerminator::~AssaultTerminator() { std::cout << "I’ll be back ..." << std::endl; } ISpaceMarine *AssaultTerminator::clone() const { return new AssaultTerminator(*this); } void AssaultTerminator::battleCry() const { std::cout << "This code is unclean. Purify it !" << std::endl; } void AssaultTerminator::rangedAttack() const { std::cout << "* does nothing *" << std::endl; } void AssaultTerminator::meleeAttack() const { std::cout << "** attaque with chainfists *" << std::endl; }
[ "marie@MacBook-Air-de-Marie.local" ]
marie@MacBook-Air-de-Marie.local
97384d59742e4a539b01df4e008c02a55ae3f9a8
815aaa29871c1f4de330669ca692294c1c7baccb
/testscripts/indexgen2d_templated.cpp
c81be28cc3e49673017cb86cfc4140286ca51813
[]
no_license
khokhlov/solvergen
44a4aea8aaf6edebca2945560e6c539727cb2121
9bf580eeed1d263e83ca754417bd8365dcde7d30
refs/heads/master
2020-08-11T01:10:18.886710
2019-05-30T07:32:55
2019-05-30T07:39:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,147
cpp
#include <iostream> #include <vector> #include <bitset> #include <cmath> #include <array> #include <cassert> using namespace std; class Checker { public: Checker(int nx, int ny) : nx(nx), ny(ny), data(nx * ny, -1) { } bool check(int i, int j, int t) { int& val = data.at(i + nx * j); auto is = {-1, 0, 1}; auto js = {-1, 0, 1}; for (int iss : is) { for (int jss : js) { int ii = i + iss; int jj = j + jss; if (ii < 0 || jj < 0 || ii >= nx || jj >= ny) continue; int vval = data.at(ii + nx * jj); if (vval < t - 1) { return false; } } } if (val == t - 1) { val = t; return true; } else { return false; } } private: int nx, ny; std::vector<int> data; }; template <typename T> inline T pow2(T k) { return 1ll << k; } template <typename F> void tiledLoops(int nx, int ny, int nt, F func) { std::array<int8_t,24> lut_ii{ 0, 1,-1, 0, 0, 1, 1,-1,-1, 1,-1, 0, 0, 0, 1,-1, 0, 0, 0, 0, 0, 0, 1,-1 }; std::array<int8_t,24> lut_jj{ 0, 0, 0, 1,-1, 1,-1, 1,-1, 0, 0, 1,-1, 0, 0, 0, 0, 1,-1, 1,-1, 0, 0, 0 }; std::array<int8_t,24> lut_tt{ 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1 }; std::array<int8_t,24> lut_mode { 0,19,19,14,14, 0, 0, 0, 0,14,14,19,19, 0,14,14, 0,14,14,19,19, 0,19,19 }; int base = max(nx, ny); base = base | 1; // round up to the nearest odd number int height = nt; int32_t tileParam = 1; while (pow2(tileParam+1) < base + height - 1) { tileParam++; } assert(pow2(tileParam+1) >= base + height - 1); //cerr << "tileParam: " << tileParam << endl; int32_t sx = - base / 2; //cerr << "sx: " << sx << endl; int32_t ex = sx + nx - 1; //cerr << "ex: " << ex << endl; int32_t sy = - base / 2; //cerr << "sy: " << sy << endl; int32_t ey = sy + ny - 1; //cerr << "ey: " << ey << endl; int32_t st = + base / 2; //cerr << "st: " << st << endl; int32_t et = st + nt - 1; //cerr << "et: " << et << endl; // size of array is the logarithm of desired tile size std::vector<int8_t> state(tileParam); // height of the tile depends on the number of iterations: // num of iterations: 2^{3i+1}-2^i // i from 1 to inf // height big: 2^{i+1} ( range: [0;2^{i+1}-1] ) // height small: 2^i ( range: [0;2^i-1] ) // width: 2^{i+1} - 1 ( range: [-(2^i - 1); +(2^i - 1)] ) int64_t iterations = pow2(3ll * tileParam + 1ll) - pow2(tileParam); //iterations = 20; //cerr << "iterations: " << iterations << endl; std::vector<int32_t> tts(tileParam + 1); std::vector<int32_t> iis(tileParam + 1); std::vector<int32_t> jjs(tileParam + 1); size_t K = state.size() - 1; bool finished = false; while (1) { //cerr << "=====" << endl; // step //for (int i = 0; i < state.size(); i++) { // cerr << int(state[i]) << " "; //} //cerr << endl; bool skipTile = false; while (1) { int32_t ss = state[K]; int32_t tt = lut_tt[ss]; int32_t ii = lut_ii[ss]; int32_t jj = lut_jj[ss]; tts[K] = tts[K+1] + (tt << K); iis[K] = iis[K+1] + (ii << K); jjs[K] = jjs[K+1] + (jj << K); int32_t min_t = tts[K] + 0; int32_t min_x = iis[K] - (pow2(K + 1) - 1); int32_t min_y = jjs[K] - (pow2(K + 1) - 1); int32_t mode = lut_mode[ss]; int32_t height = pow2(K + (mode == 0 ? 2 : 1)) - 1; int32_t max_t = tts[K] + height - 1; int32_t max_x = iis[K] + (pow2(K + 1) - 1); int32_t max_y = jjs[K] + (pow2(K + 1) - 1); //cerr // << min_x << " " // << max_x << " " // << min_y << " " // << max_y << " " // << min_t << " " // << max_t << " " // << endl; if (max_t < st || min_t > et || max_x < sx || min_x > ex || max_y < sy || min_y > ey) { skipTile = true; break; } if (K == 0) break; state[K-1] = lut_mode[state[K]]; K--; }; //cerr << "skipTile: " << skipTile << endl; //cerr << "ijt: " << iis[0] << " " << jjs[0] << " " << tts[0] << endl; if (!skipTile) { // print if (sx <= iis[0] && iis[0] <= ex && sy <= jjs[0] && jjs[0] <= ey) { if (st <= tts[0] && tts[0] <= et) { func(iis[0] - sx, jjs[0] - sy, tts[0] - st); } if (lut_mode[state[0]] == 0) { if(st <= tts[0] + 1 && tts[0] + 1 <= et) { func(iis[0] - sx, jjs[0] - sy, tts[0] + 1 - st); } } } } while (state[K] == 13 || state[K] == 18 || state[K] == 23) { K++; if (K == state.size()) { finished = true; break; } } if (finished == true) break; state[K]++; } } template <int Level, typename F> struct SmallTileX { static void run(int i, int j, int t, int nx, int ny, int nt, F func); }; template <int Level, typename F> struct SmallTileY { static void run(int i, int j, int t, int nx, int ny, int nt, F func); }; template <int Level, typename F> struct LargeTile { static void run(int i, int j, int t, int nx, int ny, int nt, F func); }; template <int Level, typename F> void SmallTileX<Level, F>::run(int i, int j, int t, int nx, int ny, int nt, F func) { constexpr int tileSize = 1 << (Level - 1); constexpr int tileWidth = tileSize * 2 - 1; constexpr int tileHeight = tileSize * 2 - 1; if (i + tileWidth < 0 || i - tileWidth >= nx || j + tileWidth < 0 || j - tileWidth >= ny || t + tileHeight < 0 || t >= nt) return; SmallTileX<Level - 1, F>::run(i - tileSize, j, t, nx, ny, nt, func); SmallTileX<Level - 1, F>::run(i + tileSize, j, t, nx, ny, nt, func); LargeTile<Level - 1, F>::run(i, j, t, nx, ny, nt, func); SmallTileX<Level - 1, F>::run(i, j - tileSize, t + tileSize, nx, ny, nt, func); SmallTileX<Level - 1, F>::run(i, j + tileSize, t + tileSize, nx, ny, nt, func); } template <int Level, typename F> void SmallTileY<Level, F>::run(int i, int j, int t, int nx, int ny, int nt, F func) { constexpr int tileSize = 1 << (Level - 1); constexpr int tileWidth = tileSize * 2 - 1; constexpr int tileHeight = tileSize * 2 - 1; if (i + tileWidth < 0 || i - tileWidth >= nx || j + tileWidth < 0 || j - tileWidth >= ny || t + tileHeight < 0 || t >= nt) return; SmallTileY<Level - 1, F>::run(i, j - tileSize, t, nx, ny, nt, func); SmallTileY<Level - 1, F>::run(i, j + tileSize, t, nx, ny, nt, func); LargeTile<Level - 1, F>::run(i, j, t, nx, ny, nt, func); SmallTileY<Level - 1, F>::run(i - tileSize, j, t + tileSize, nx, ny, nt, func); SmallTileY<Level - 1, F>::run(i + tileSize, j, t + tileSize, nx, ny, nt, func); } template <int Level, typename F> void LargeTile<Level, F>::run(int i, int j, int t, int nx, int ny, int nt, F func) { constexpr int tileSize = 1 << (Level - 1); constexpr int tileWidth = tileSize * 2 - 1; constexpr int tileHeight = tileSize * 4 - 1; if (i + tileWidth < 0 || i - tileWidth >= nx || j + tileWidth < 0 || j - tileWidth >= ny || t + tileHeight < 0 || t >= nt) return; LargeTile<Level - 1, F>::run(i, j, t, nx, ny, nt, func); SmallTileX<Level - 1, F>::run(i, j - tileSize, t + tileSize, nx, ny, nt, func); SmallTileX<Level - 1, F>::run(i, j + tileSize, t + tileSize, nx, ny, nt, func); SmallTileY<Level - 1, F>::run(i - tileSize, j, t + tileSize, nx, ny, nt, func); SmallTileY<Level - 1, F>::run(i + tileSize, j, t + tileSize, nx, ny, nt, func); LargeTile<Level - 1, F>::run(i - tileSize, j - tileSize, t + tileSize, nx, ny, nt, func); LargeTile<Level - 1, F>::run(i + tileSize, j - tileSize, t + tileSize, nx, ny, nt, func); LargeTile<Level - 1, F>::run(i - tileSize, j + tileSize, t + tileSize, nx, ny, nt, func); LargeTile<Level - 1, F>::run(i + tileSize, j + tileSize, t + tileSize, nx, ny, nt, func); SmallTileX<Level - 1, F>::run(i - tileSize, j, t + 2 * tileSize, nx, ny, nt, func); SmallTileX<Level - 1, F>::run(i + tileSize, j, t + 2 * tileSize, nx, ny, nt, func); SmallTileY<Level - 1, F>::run(i, j - tileSize, t + 2 * tileSize, nx, ny, nt, func); SmallTileY<Level - 1, F>::run(i, j + tileSize, t + 2 * tileSize, nx, ny, nt, func); LargeTile<Level - 1, F>::run(i, j, t + 2 * tileSize, nx, ny, nt, func); } template <typename F> struct SmallTileX<0, F> { static void run(int i, int j, int t, int nx, int ny, int nt, F func) { if (0 <= i && i < nx && 0 <= j && j < ny && 0 <= t && t < nt) { func(i, j, t); } } }; template <typename F> struct SmallTileY<0, F> { static void run(int i, int j, int t, int nx, int ny, int nt, F func) { if (0 <= i && i < nx && 0 <= j && j < ny && 0 <= t && t < nt) { func(i, j, t); } } }; template <typename F> struct LargeTile<0, F> { static void run(int i, int j, int t, int nx, int ny, int nt, F func) { if (0 <= i && i < nx && 0 <= j && j < ny) { if (0 <= t && t < nt) func(i, j, t); if (0 <= t + 1 && t + 1 < nt) func(i, j, t + 1); } } }; template <typename F> void tiledLoopsTemplated(int nx, int ny, int nt, F f) { constexpr int tileSize = 15; int nodesWidth = std::max(nx, std::max(ny, nt)); int requiredTileSize = 0; while ((1 << requiredTileSize) < nodesWidth) requiredTileSize++; assert(requiredTileSize <= tileSize); LargeTile<tileSize, decltype(f)>::run(0, 0, -(1 << tileSize), nx, ny, nt, f); } int main() { int nx = 2000; int ny = 2000; int nt = 100; Checker checker(nx, ny); int unused = 0; //auto f = [&unused,&checker](int i, int j, int t) { // std::cout << i << " " << j << " " << t << endl; // //cerr << "ijt: " << i << " " << j << " " << t << endl; // assert(checker.check(i, j, t)); // unused += i + j + t; //}; //tiledLoops(nx, ny, nt, f); //templatedTiledLoops(); auto f = [&](int i, int j, int t) { //std::cerr << i << " " << j << " " << t << endl; //std::cout << i << " " << j << " " << t << endl; //assert(checker.check(i, j, t)); unused += i + j + t; }; tiledLoopsTemplated(nx, ny, nt, f); cerr << "unused: " << unused << endl; }
[ "furgailo@phystech.edu" ]
furgailo@phystech.edu
4907aa6f867afa7d180a1305084e3f805802e238
768c55006dea03b485c4f6435b7e4888f489f719
/include/AutomappingNode.h
dc60013a25d2d106ffa194123448359e68344406
[]
no_license
red-itmo/box_finder
94288448ce7d7aa7ebffcd99af12442f367a3b4f
9e9503dab38f5eb7de03099d4c51143c5bb23208
refs/heads/master
2021-01-20T20:14:48.359548
2016-07-22T15:50:43
2016-07-22T15:50:43
63,970,233
1
0
null
null
null
null
UTF-8
C++
false
false
858
h
#ifndef _AUTOMAPPINGNODE_ #define _AUTOMAPPINGNODE_ #include <RobotClass.hpp> #include <nav_msgs/GetPlan.h> #include <box_finder/GetGoal.h> #include <cstdlib> #include <vector> #include <fstream> #define EQUAL(A, B) A.x == B.x && A.y == B.y #define ISNULL(A) A.x == 0.0 && A.y == 0.0 && A.z == 0.0 && A.w == 0.0 class AutomappingNode{ ros::NodeHandle nh, nh_for_params; RobotClass robot; ros::ServiceClient goal_requester, pathfinder; double safe_distance, tolerance, rotational_speed; std::string map_name, pose_params_file_name; geometry_msgs::PoseStamped safeGoalInPlan(const nav_msgs::Path &plan); double distanceBetweenPoses(const geometry_msgs::PoseStamped &pose1, const geometry_msgs::PoseStamped &pose2); public: AutomappingNode(); ~AutomappingNode(); void doYourWork(); }; #endif //_AUTOMAPPINGNODE_
[ "antonovspostbox@gmail.com" ]
antonovspostbox@gmail.com
7c4ec5d05ece56568c574ecfe218f98652907a3c
c1ff870879152fba2b54eddfb7591ec322eb3061
/plugins/render/ogreRender/3rdParty/ogre/Components/Overlay/include/OgreOverlayElement.h
d0871d967b376d8a962a7df3c2b2efe04bd7b0e6
[ "LicenseRef-scancode-free-unknown", "MIT" ]
permissive
MTASZTAKI/ApertusVR
1a9809fb7af81c3cd7fb732ed481ebe4ce66fefa
424ec5515ae08780542f33cc4841a8f9a96337b3
refs/heads/0.9
2022-12-11T20:03:42.926813
2019-10-11T09:29:45
2019-10-11T09:29:45
73,708,854
188
55
MIT
2022-12-11T08:53:21
2016-11-14T13:48:00
C++
UTF-8
C++
false
false
21,590
h
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2016 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #ifndef __OverlayElement_H__ #define __OverlayElement_H__ #include "OgreOverlayPrerequisites.h" #include "OgreRenderable.h" #include "OgreUTFString.h" #include "OgreStringInterface.h" #include "OgreOverlayElementCommands.h" #include "OgreColourValue.h" namespace Ogre { /** \addtogroup Core * @{ */ /** \addtogroup Overlays * @{ */ #if OGRE_UNICODE_SUPPORT typedef UTFString DisplayString; # define OGRE_DEREF_DISPLAYSTRING_ITERATOR(it) it.getCharacter() #else typedef String DisplayString; # define OGRE_DEREF_DISPLAYSTRING_ITERATOR(it) *it #endif /** Enum describing how the position / size of an element is to be recorded. */ enum GuiMetricsMode { /// 'left', 'top', 'height' and 'width' are parametrics from 0.0 to 1.0 GMM_RELATIVE, /// Positions & sizes are in absolute pixels GMM_PIXELS, /// Positions & sizes are in virtual pixels GMM_RELATIVE_ASPECT_ADJUSTED }; /** Enum describing where '0' is in relation to the parent in the horizontal dimension. @remarks Affects how 'left' is interpreted. */ enum GuiHorizontalAlignment { GHA_LEFT, GHA_CENTER, GHA_RIGHT }; /** Enum describing where '0' is in relation to the parent in the vertical dimension. @remarks Affects how 'top' is interpreted. */ enum GuiVerticalAlignment { GVA_TOP, GVA_CENTER, GVA_BOTTOM }; /** Abstract definition of a 2D element to be displayed in an Overlay. @remarks This class abstracts all the details of a 2D element which will appear in an overlay. In fact, not all OverlayElement instances can be directly added to an Overlay, only those which are OverlayContainer instances (a subclass of this class). OverlayContainer objects can contain any OverlayElement however. This is just to enforce some level of grouping on widgets. @par OverlayElements should be managed using OverlayManager. This class is responsible for instantiating / deleting elements, and also for accepting new types of element from plugins etc. @par Note that positions / dimensions of 2D screen elements are expressed as parametric values (0.0 - 1.0) because this makes them resolution-independent. However, most screen resolutions have an aspect ratio of 1.3333:1 (width : height) so note that in physical pixels 0.5 is wider than it is tall, so a 0.5x0.5 panel will not be square on the screen (but it will take up exactly half the screen in both dimensions). @par Because this class is designed to be extensible, it subclasses from StringInterface so its parameters can be set in a generic way. */ class _OgreOverlayExport OverlayElement : public StringInterface, public Renderable, public OverlayAlloc { public: protected: // Command object for setting / getting parameters static OverlayElementCommands::CmdLeft msLeftCmd; static OverlayElementCommands::CmdTop msTopCmd; static OverlayElementCommands::CmdWidth msWidthCmd; static OverlayElementCommands::CmdHeight msHeightCmd; static OverlayElementCommands::CmdMaterial msMaterialCmd; static OverlayElementCommands::CmdCaption msCaptionCmd; static OverlayElementCommands::CmdMetricsMode msMetricsModeCmd; static OverlayElementCommands::CmdHorizontalAlign msHorizontalAlignCmd; static OverlayElementCommands::CmdVerticalAlign msVerticalAlignCmd; static OverlayElementCommands::CmdVisible msVisibleCmd; String mName; bool mVisible; bool mCloneable; Real mLeft; Real mTop; Real mWidth; Real mHeight; String mMaterialName; MaterialPtr mMaterial; DisplayString mCaption; ColourValue mColour; RealRect mClippingRegion; GuiMetricsMode mMetricsMode; GuiHorizontalAlignment mHorzAlign; GuiVerticalAlignment mVertAlign; // metric-mode positions, used in GMM_PIXELS & GMM_RELATIVE_ASPECT_ADJUSTED mode. Real mPixelTop; Real mPixelLeft; Real mPixelWidth; Real mPixelHeight; Real mPixelScaleX; Real mPixelScaleY; /// Parent pointer OverlayContainer* mParent; /// Overlay attached to Overlay* mOverlay; // Derived positions from parent Real mDerivedLeft; Real mDerivedTop; bool mDerivedOutOfDate; /// Flag indicating if the vertex positions need recalculating bool mGeomPositionsOutOfDate; /// Flag indicating if the vertex uvs need recalculating bool mGeomUVsOutOfDate; /** Zorder for when sending to render queue. Derived from parent */ ushort mZOrder; /// World transforms Matrix4 mXForm; /// Is element enabled? bool mEnabled; /// Is element initialised? bool mInitialised; /// Used to see if this element is created from a Template OverlayElement* mSourceTemplate ; /** Internal method which is triggered when the positions of the element get updated, meaning the element should be rebuilding it's mesh positions. Abstract since subclasses must implement this. */ virtual void updatePositionGeometry(void) = 0; /** Internal method which is triggered when the UVs of the element get updated, meaning the element should be rebuilding it's mesh UVs. Abstract since subclasses must implement this. */ virtual void updateTextureGeometry(void) = 0; /** Internal method for setting up the basic parameter definitions for a subclass. @remarks Because StringInterface holds a dictionary of parameters per class, subclasses need to call this to ask the base class to add it's parameters to their dictionary as well. Can't do this in the constructor because that runs in a non-virtual context. @par The subclass must have called it's own createParamDictionary before calling this method. */ virtual void addBaseParameters(void); public: /// Constructor: do not call direct, use OverlayManager::createElement OverlayElement(const String& name); virtual ~OverlayElement(); /** Initialise gui element */ virtual void initialise(void) = 0; /** Notifies that hardware resources were lost */ virtual void _releaseManualHardwareResources() {} /** Notifies that hardware resources should be restored */ virtual void _restoreManualHardwareResources() {} /** Gets the name of this overlay. */ const String& getName(void) const; /** Shows this element if it was hidden. */ virtual void show(void); /** Hides this element if it was visible. */ virtual void hide(void); /** Returns whether or not the element is visible. */ bool isVisible(void) const; bool isEnabled() const; virtual void setEnabled(bool b); /** Sets the dimensions of this element in relation to the screen (1.0 = screen width/height). */ void setDimensions(Real width, Real height); /** Sets the position of the top-left corner of the element, relative to the screen size (1.0 = screen width / height) */ void setPosition(Real left, Real top); /** Sets the width of this element in relation to the screen (where 1.0 = screen width) */ void setWidth(Real width); /** Gets the width of this element in relation to the screen (where 1.0 = screen width) */ Real getWidth(void) const; /** Sets the height of this element in relation to the screen (where 1.0 = screen height) */ void setHeight(Real height); /** Gets the height of this element in relation to the screen (where 1.0 = screen height) */ Real getHeight(void) const; /** Sets the left of this element in relation to the screen (where 0 = far left, 1.0 = far right) */ void setLeft(Real left); /** Gets the left of this element in relation to the screen (where 0 = far left, 1.0 = far right) */ Real getLeft(void) const; /** Sets the top of this element in relation to the screen (where 0 = top, 1.0 = bottom) */ void setTop(Real Top); /** Gets the top of this element in relation to the screen (where 0 = top, 1.0 = bottom) */ Real getTop(void) const; /** Gets the left of this element in relation to the screen (where 0 = far left, 1.0 = far right) */ Real _getLeft(void) const { return mLeft; } /** Gets the top of this element in relation to the screen (where 0 = far left, 1.0 = far right) */ Real _getTop(void) const { return mTop; } /** Gets the width of this element in relation to the screen (where 1.0 = screen width) */ Real _getWidth(void) const { return mWidth; } /** Gets the height of this element in relation to the screen (where 1.0 = screen height) */ Real _getHeight(void) const { return mHeight; } /** Sets the left of this element in relation to the screen (where 1.0 = screen width) */ void _setLeft(Real left); /** Sets the top of this element in relation to the screen (where 1.0 = screen width) */ void _setTop(Real top); /** Sets the width of this element in relation to the screen (where 1.0 = screen width) */ void _setWidth(Real width); /** Sets the height of this element in relation to the screen (where 1.0 = screen width) */ void _setHeight(Real height); /** Sets the left and top of this element in relation to the screen (where 1.0 = screen width) */ void _setPosition(Real left, Real top); /** Sets the width and height of this element in relation to the screen (where 1.0 = screen width) */ void _setDimensions(Real width, Real height); /** Gets the name of the material this element uses. */ virtual const String& getMaterialName(void) const; /** Sets the name of the material this element will use. @remarks Different elements will use different materials. One constant about them all though is that a Material used for a OverlayElement must have it's depth checking set to 'off', which means it always gets rendered on top. OGRE will set this flag for you if necessary. What it does mean though is that you should not use the same Material for rendering OverlayElements as standard scene objects. It's fine to use the same textures, just not the same Material. */ virtual void setMaterialName(const String& matName); // --- Renderable Overrides --- /** See Renderable */ const MaterialPtr& getMaterial(void) const; // NB getRenderOperation not implemented, still abstract here /** See Renderable */ void getWorldTransforms(Matrix4* xform) const; /** Tell the object to recalculate */ virtual void _positionsOutOfDate(void); /** Internal method to update the element based on transforms applied. */ virtual void _update(void); /** Updates this elements transform based on it's parent. */ virtual void _updateFromParent(void); /** Internal method for notifying the GUI element of it's parent and ultimate overlay. */ virtual void _notifyParent(OverlayContainer* parent, Overlay* overlay); /** Gets the 'left' position as derived from own left and that of parents. */ virtual Real _getDerivedLeft(void); /** Gets the 'top' position as derived from own left and that of parents. */ virtual Real _getDerivedTop(void); /** Gets the 'width' as derived from own width and metrics mode. */ virtual Real _getRelativeWidth(void); /** Gets the 'height' as derived from own height and metrics mode. */ virtual Real _getRelativeHeight(void); /** Gets the clipping region of the element */ virtual void _getClippingRegion(RealRect &clippingRegion); /** Internal method to notify the element when Z-order of parent overlay has changed. @remarks Overlays have explicit Z-orders. OverlayElements do not, they inherit the Z-order of the overlay, and the Z-order is incremented for every container nested within this to ensure that containers are displayed behind contained items. This method is used internally to notify the element of a change in final Z-order which is used to render the element. @return Return the next Z-ordering number available. For single elements, this is simply 'newZOrder + 1', except for containers. They increment it once for each child (or even more if those children are also containers with their own elements). */ virtual ushort _notifyZOrder(ushort newZOrder); /** Internal method to notify the element when it's world transform of parent overlay has changed. */ virtual void _notifyWorldTransforms(const Matrix4& xform); /** Internal method to notify the element when the viewport of parent overlay has changed. */ virtual void _notifyViewport(); /** Internal method to put the contents onto the render queue. */ virtual void _updateRenderQueue(RenderQueue* queue); /// @copydoc MovableObject::visitRenderables void visitRenderables(Renderable::Visitor* visitor, bool debugRenderables = false); /** Gets the type name of the element. All concrete subclasses must implement this. */ virtual const String& getTypeName(void) const = 0; /** Sets the caption on elements that support it. @remarks This property doesn't do something on all elements, just those that support it. However, being a common requirement it is in the top-level interface to avoid having to set it via the StringInterface all the time. */ virtual void setCaption(const DisplayString& text); /** Gets the caption for this element. */ virtual const DisplayString& getCaption(void) const; /** Sets the colour on elements that support it. @remarks This property doesn't do something on all elements, just those that support it. However, being a common requirement it is in the top-level interface to avoid having to set it via the StringInterface all the time. */ virtual void setColour(const ColourValue& col); /** Gets the colour for this element. */ virtual const ColourValue& getColour(void) const; /** Tells this element how to interpret the position and dimension values it is given. @remarks By default, OverlayElements are positioned and sized according to relative dimensions of the screen. This is to ensure portability between different resolutions when you want things to be positioned and sized the same way across all resolutions. However, sometimes you want things to be sized according to fixed pixels. In order to do this, you can call this method with the parameter GMM_PIXELS. Note that if you then want to place your element relative to the center, right or bottom of it's parent, you will need to use the setHorizontalAlignment and setVerticalAlignment methods. */ virtual void setMetricsMode(GuiMetricsMode gmm); /** Retrieves the current settings of how the element metrics are interpreted. */ virtual GuiMetricsMode getMetricsMode(void) const; /** Sets the horizontal origin for this element. @remarks By default, the horizontal origin for a OverlayElement is the left edge of the parent container (or the screen if this is a root element). You can alter this by calling this method, which is especially useful when you want to use pixel-based metrics (see setMetricsMode) since in this mode you can't use relative positioning. @par For example, if you were using GMM_PIXELS metrics mode, and you wanted to place a 30x30 pixel crosshair in the center of the screen, you would use GHA_CENTER with a 'left' property of -15. @par Note that neither GHA_CENTER or GHA_RIGHT alter the position of the element based on it's width, you have to alter the 'left' to a negative number to do that; all this does is establish the origin. This is because this way you can align multiple things in the center and right with different 'left' offsets for maximum flexibility. */ virtual void setHorizontalAlignment(GuiHorizontalAlignment gha); /** Gets the horizontal alignment for this element. */ virtual GuiHorizontalAlignment getHorizontalAlignment(void) const; /** Sets the vertical origin for this element. @remarks By default, the vertical origin for a OverlayElement is the top edge of the parent container (or the screen if this is a root element). You can alter this by calling this method, which is especially useful when you want to use pixel-based metrics (see setMetricsMode) since in this mode you can't use relative positioning. @par For example, if you were using GMM_PIXELS metrics mode, and you wanted to place a 30x30 pixel crosshair in the center of the screen, you would use GHA_CENTER with a 'top' property of -15. @par Note that neither GVA_CENTER or GVA_BOTTOM alter the position of the element based on it's height, you have to alter the 'top' to a negative number to do that; all this does is establish the origin. This is because this way you can align multiple things in the center and bottom with different 'top' offsets for maximum flexibility. */ virtual void setVerticalAlignment(GuiVerticalAlignment gva); /** Gets the vertical alignment for this element. */ virtual GuiVerticalAlignment getVerticalAlignment(void) const; /** Returns true if xy is within the constraints of the component */ virtual bool contains(Real x, Real y) const; /** Returns true if xy is within the constraints of the component */ virtual OverlayElement* findElementAt(Real x, Real y); // relative to parent /** * returns false as this class is not a container type */ inline virtual bool isContainer() const { return false; } inline virtual bool isKeyEnabled() const { return false; } inline virtual bool isCloneable() const { return mCloneable; } inline virtual void setCloneable(bool c) { mCloneable = c; } /** * Returns the parent container. */ OverlayContainer* getParent() ; void _setParent(OverlayContainer* parent) { mParent = parent; } /** * Returns the zOrder of the element */ inline ushort getZOrder() const { return mZOrder; } /** Overridden from Renderable */ Real getSquaredViewDepth(const Camera* cam) const { (void)cam; return 10000.0f - (Real)getZOrder(); } /** @copydoc Renderable::getLights */ const LightList& getLights(void) const { // Overlayelements should not be lit by the scene, this will not get called static LightList ll; return ll; } virtual void copyFromTemplate(OverlayElement* templateOverlay); virtual OverlayElement* clone(const String& instanceName); /// Returns the SourceTemplate for this element const OverlayElement* getSourceTemplate () const { return mSourceTemplate ; } }; /** @} */ /** @} */ } #endif
[ "peter.kovacs@sztaki.mta.hu" ]
peter.kovacs@sztaki.mta.hu
f26c23ade804a84c4a6986f04d7355b64315a0f0
aef50deb115eac52e29dce51eb9f5f8221e9ed16
/gpu/command_buffer/service/shared_image_representation.h
da832e81a6348e35014ebf6e5ed2f264f9b12826
[ "BSD-3-Clause" ]
permissive
coolsabya/chromium
2a1557937943086e7d2245b9c28d614633ff6ffc
65f89d72ed17c5c23f3c93d5b575ec51e86e1d82
refs/heads/master
2022-11-25T00:28:15.370458
2020-01-03T21:25:55
2020-01-03T21:25:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,946
h
// 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. #ifndef GPU_COMMAND_BUFFER_SERVICE_SHARED_IMAGE_REPRESENTATION_H_ #define GPU_COMMAND_BUFFER_SERVICE_SHARED_IMAGE_REPRESENTATION_H_ #include <dawn/dawn_proc_table.h> #include <dawn/webgpu.h> #include "base/callback_helpers.h" #include "base/util/type_safety/pass_key.h" #include "build/build_config.h" #include "components/viz/common/resources/resource_format.h" #include "gpu/command_buffer/service/shared_image_backing.h" #include "gpu/command_buffer/service/shared_image_manager.h" #include "gpu/gpu_gles2_export.h" #include "third_party/skia/include/core/SkSurface.h" #include "ui/gfx/color_space.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/size.h" #include "ui/gfx/gpu_fence.h" typedef unsigned int GLenum; class SkPromiseImageTexture; namespace gl { class GLImage; } namespace gpu { namespace gles2 { class Texture; class TexturePassthrough; } // namespace gles2 enum class RepresentationAccessMode { kNone, kRead, kWrite, }; // A representation of a SharedImageBacking for use with a specific use case / // api. class GPU_GLES2_EXPORT SharedImageRepresentation { public: // Used by derived classes. enum class AllowUnclearedAccess { kYes, kNo }; SharedImageRepresentation(SharedImageManager* manager, SharedImageBacking* backing, MemoryTypeTracker* tracker); virtual ~SharedImageRepresentation(); viz::ResourceFormat format() const { return backing_->format(); } const gfx::Size& size() const { return backing_->size(); } const gfx::ColorSpace& color_space() const { return backing_->color_space(); } uint32_t usage() const { return backing_->usage(); } MemoryTypeTracker* tracker() { return tracker_; } bool IsCleared() const { return backing_->IsCleared(); } void SetCleared() { backing_->SetCleared(); } gfx::Rect ClearedRect() const { return backing_->ClearedRect(); } void SetClearedRect(const gfx::Rect& cleared_rect) { backing_->SetClearedRect(cleared_rect); } // Indicates that the underlying graphics context has been lost, and the // backing should be treated as destroyed. void OnContextLost() { has_context_ = false; backing_->OnContextLost(); } protected: SharedImageManager* manager() const { return manager_; } SharedImageBacking* backing() const { return backing_; } bool has_context() const { return has_context_; } private: SharedImageManager* const manager_; SharedImageBacking* const backing_; MemoryTypeTracker* const tracker_; bool has_context_ = true; }; class SharedImageRepresentationFactoryRef : public SharedImageRepresentation { public: SharedImageRepresentationFactoryRef(SharedImageManager* manager, SharedImageBacking* backing, MemoryTypeTracker* tracker) : SharedImageRepresentation(manager, backing, tracker) {} const Mailbox& mailbox() const { return backing()->mailbox(); } void Update(std::unique_ptr<gfx::GpuFence> in_fence) { backing()->Update(std::move(in_fence)); backing()->OnWriteSucceeded(); } bool ProduceLegacyMailbox(MailboxManager* mailbox_manager) { return backing()->ProduceLegacyMailbox(mailbox_manager); } bool PresentSwapChain() { return backing()->PresentSwapChain(); } }; class GPU_GLES2_EXPORT SharedImageRepresentationGLTextureBase : public SharedImageRepresentation { public: class ScopedAccess { public: ScopedAccess(util::PassKey<SharedImageRepresentationGLTextureBase> pass_key, SharedImageRepresentationGLTextureBase* representation) : representation_(representation) {} ~ScopedAccess() { representation_->UpdateClearedStateOnEndAccess(); representation_->EndAccess(); } private: SharedImageRepresentationGLTextureBase* representation_ = nullptr; DISALLOW_COPY_AND_ASSIGN(ScopedAccess); }; SharedImageRepresentationGLTextureBase(SharedImageManager* manager, SharedImageBacking* backing, MemoryTypeTracker* tracker) : SharedImageRepresentation(manager, backing, tracker) {} std::unique_ptr<ScopedAccess> BeginScopedAccess( GLenum mode, AllowUnclearedAccess allow_uncleared); protected: friend class SharedImageRepresentationSkiaGL; // Can be overridden to handle clear state tracking when GL access ends. virtual void UpdateClearedStateOnEndAccess() {} // TODO(ericrk): Make these pure virtual and ensure real implementations // exist. virtual bool BeginAccess(GLenum mode); virtual void EndAccess() {} }; class GPU_GLES2_EXPORT SharedImageRepresentationGLTexture : public SharedImageRepresentationGLTextureBase { public: SharedImageRepresentationGLTexture(SharedImageManager* manager, SharedImageBacking* backing, MemoryTypeTracker* tracker) : SharedImageRepresentationGLTextureBase(manager, backing, tracker) {} // TODO(ericrk): Move this to the ScopedAccess object. crbug.com/1003686 virtual gles2::Texture* GetTexture() = 0; protected: void UpdateClearedStateOnEndAccess() override; }; class GPU_GLES2_EXPORT SharedImageRepresentationGLTexturePassthrough : public SharedImageRepresentationGLTextureBase { public: SharedImageRepresentationGLTexturePassthrough(SharedImageManager* manager, SharedImageBacking* backing, MemoryTypeTracker* tracker) : SharedImageRepresentationGLTextureBase(manager, backing, tracker) {} // TODO(ericrk): Move this to the ScopedAccess object. crbug.com/1003686 virtual const scoped_refptr<gles2::TexturePassthrough>& GetTexturePassthrough() = 0; }; class GPU_GLES2_EXPORT SharedImageRepresentationSkia : public SharedImageRepresentation { public: class GPU_GLES2_EXPORT ScopedWriteAccess { public: ScopedWriteAccess(util::PassKey<SharedImageRepresentationSkia> pass_key, SharedImageRepresentationSkia* representation, sk_sp<SkSurface> surface); ~ScopedWriteAccess(); SkSurface* surface() const { return surface_.get(); } private: SharedImageRepresentationSkia* const representation_; sk_sp<SkSurface> surface_; DISALLOW_COPY_AND_ASSIGN(ScopedWriteAccess); }; class GPU_GLES2_EXPORT ScopedReadAccess { public: ScopedReadAccess(util::PassKey<SharedImageRepresentationSkia> pass_key, SharedImageRepresentationSkia* representation, sk_sp<SkPromiseImageTexture> promise_image_texture); ~ScopedReadAccess(); SkPromiseImageTexture* promise_image_texture() const { return promise_image_texture_.get(); } private: SharedImageRepresentationSkia* const representation_; sk_sp<SkPromiseImageTexture> promise_image_texture_; DISALLOW_COPY_AND_ASSIGN(ScopedReadAccess); }; SharedImageRepresentationSkia(SharedImageManager* manager, SharedImageBacking* backing, MemoryTypeTracker* tracker) : SharedImageRepresentation(manager, backing, tracker) {} // Note: See BeginWriteAccess below for a description of the semaphore // parameters. std::unique_ptr<ScopedWriteAccess> BeginScopedWriteAccess( int final_msaa_count, const SkSurfaceProps& surface_props, std::vector<GrBackendSemaphore>* begin_semaphores, std::vector<GrBackendSemaphore>* end_semaphores, AllowUnclearedAccess allow_uncleared); std::unique_ptr<ScopedWriteAccess> BeginScopedWriteAccess( std::vector<GrBackendSemaphore>* begin_semaphores, std::vector<GrBackendSemaphore>* end_semaphores, AllowUnclearedAccess allow_uncleared); // Note: See BeginReadAccess below for a description of the semaphore // parameters. std::unique_ptr<ScopedReadAccess> BeginScopedReadAccess( std::vector<GrBackendSemaphore>* begin_semaphores, std::vector<GrBackendSemaphore>* end_semaphores); virtual bool SupportsMultipleConcurrentReadAccess(); protected: // Begin the write access. The implementations should insert semaphores into // begin_semaphores vector which client will wait on before writing the // backing. The ownership of begin_semaphores will be passed to client. // The implementations should also insert semaphores into end_semaphores, // client must submit them with drawing operations which use the backing. // The ownership of end_semaphores are not passed to client. And client must // submit the end_semaphores before calling EndWriteAccess(). virtual sk_sp<SkSurface> BeginWriteAccess( int final_msaa_count, const SkSurfaceProps& surface_props, std::vector<GrBackendSemaphore>* begin_semaphores, std::vector<GrBackendSemaphore>* end_semaphores) = 0; virtual void EndWriteAccess(sk_sp<SkSurface> surface) = 0; // Begin the read access. The implementations should insert semaphores into // begin_semaphores vector which client will wait on before reading the // backing. The ownership of begin_semaphores will be passed to client. // The implementations should also insert semaphores into end_semaphores, // client must submit them with drawing operations which use the backing. // The ownership of end_semaphores are not passed to client. And client must // submit the end_semaphores before calling EndReadAccess(). virtual sk_sp<SkPromiseImageTexture> BeginReadAccess( std::vector<GrBackendSemaphore>* begin_semaphores, std::vector<GrBackendSemaphore>* end_semaphores) = 0; virtual void EndReadAccess() = 0; }; class GPU_GLES2_EXPORT SharedImageRepresentationDawn : public SharedImageRepresentation { public: SharedImageRepresentationDawn(SharedImageManager* manager, SharedImageBacking* backing, MemoryTypeTracker* tracker) : SharedImageRepresentation(manager, backing, tracker) {} class GPU_GLES2_EXPORT ScopedAccess { public: ScopedAccess(util::PassKey<SharedImageRepresentationDawn> pass_key, SharedImageRepresentationDawn* representation, WGPUTexture texture); ~ScopedAccess(); WGPUTexture texture() const { return texture_; } private: SharedImageRepresentationDawn* representation_ = nullptr; WGPUTexture texture_ = 0; DISALLOW_COPY_AND_ASSIGN(ScopedAccess); }; // Calls BeginAccess and returns a ScopedAccess object which will EndAccess // when it goes out of scope. The Representation must outlive the returned // ScopedAccess. std::unique_ptr<ScopedAccess> BeginScopedAccess( WGPUTextureUsage usage, AllowUnclearedAccess allow_uncleared); private: // This can return null in case of a Dawn validation error, for example if // usage is invalid. virtual WGPUTexture BeginAccess(WGPUTextureUsage usage) = 0; virtual void EndAccess() = 0; }; class GPU_GLES2_EXPORT SharedImageRepresentationOverlay : public SharedImageRepresentation { public: SharedImageRepresentationOverlay(SharedImageManager* manager, SharedImageBacking* backing, MemoryTypeTracker* tracker) : SharedImageRepresentation(manager, backing, tracker) {} class ScopedReadAccess { public: ScopedReadAccess(util::PassKey<SharedImageRepresentationOverlay> pass_key, SharedImageRepresentationOverlay* representation, gl::GLImage* gl_image) : representation_(representation), gl_image_(gl_image) {} ~ScopedReadAccess() { if (representation_) representation_->EndReadAccess(); } gl::GLImage* gl_image() const { DCHECK(representation_); return gl_image_; } private: SharedImageRepresentationOverlay* representation_; gl::GLImage* gl_image_; }; #if defined(OS_ANDROID) virtual void NotifyOverlayPromotion(bool promotion, const gfx::Rect& bounds) = 0; #endif std::unique_ptr<ScopedReadAccess> BeginScopedReadAccess(bool needs_gl_image); protected: // TODO(weiliangc): Currently this only handles Android pre-SurfaceControl // case. Add appropriate fence later. virtual void BeginReadAccess() = 0; virtual void EndReadAccess() = 0; // TODO(weiliangc): Add API to backing AHardwareBuffer. // TODO(penghuang): Refactor it to not depend on GL. // Get the backing as GLImage for GLSurface::ScheduleOverlayPlane. virtual gl::GLImage* GetGLImage() = 0; }; } // namespace gpu #endif // GPU_COMMAND_BUFFER_SERVICE_SHARED_IMAGE_REPRESENTATION_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
9a42a6a8494e88ca07433ce1dcc5d9be358ece6b
0fa86e5ba6e6723ec1c2f72dc2812af566a61581
/src/Camera.cpp
025074473800480f4c6b54acf698fdf264dcf6ba
[ "MIT" ]
permissive
janisz/gk3d
3814a1189f4eda29836f0ad5c616672e4f855673
9bda743a956f646867c527c4505543d4047d5ba3
refs/heads/master
2021-01-22T01:04:35.025942
2014-12-08T18:49:17
2014-12-08T18:49:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,891
cpp
#include <stdio.h> #include <math.h> #include <GL/glut.h> #include "Camera.h" void Camera::Init() { m_yaw = 0.0; m_pitch = 0.0; SetPos(0, 0, 0); } void Camera::Refresh() { // Camera parameter according to Riegl's co-ordinate system // x/y for flat, z for height m_lx = cos(m_yaw) * cos(m_pitch); m_ly = sin(m_pitch); m_lz = sin(m_yaw) * cos(m_pitch); m_strafe_lx = cos(m_yaw - M_PI_2); m_strafe_lz = sin(m_yaw - M_PI_2); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(m_x, m_y, m_z, m_x + m_lx, m_y + m_ly, m_z + m_lz, 0.0,1.0,0.0); //printf("Camera: %f %f %f Direction vector: %f %f %f\n", m_x, m_y, m_z, m_lx, m_ly, m_lz); } void Camera::SetPos(float x, float y, float z) { m_x = x; m_y = y; m_z =z; Refresh(); } void Camera::GetPos(float &x, float &y, float &z) { x = m_x; y = m_y; z = m_z; } void Camera::GetDirectionVector(float &x, float &y, float &z) { x = m_lx; y = m_ly; z = m_lz; } void Camera::Move(float incr) { float lx = cos(m_yaw)*cos(m_pitch); float ly = sin(m_pitch); float lz = sin(m_yaw)*cos(m_pitch); m_x = m_x + incr*lx; m_y = m_y + incr*ly; m_z = m_z + incr*lz; Refresh(); } void Camera::Strafe(float incr) { m_x = m_x + incr*m_strafe_lx; m_z = m_z + incr*m_strafe_lz; Refresh(); } void Camera::Fly(float incr) { m_y = m_y + incr; Refresh(); } void Camera::RotateYaw(float angle) { m_yaw += angle; Refresh(); } void Camera::RotatePitch(float angle) { const float limit = 89.0 * M_PI / 180.0; m_pitch += angle; if(m_pitch < -limit) m_pitch = -limit; if(m_pitch > limit) m_pitch = limit; Refresh(); } void Camera::SetYaw(float angle) { m_yaw = angle; Refresh(); } void Camera::SetPitch(float angle) { m_pitch = angle; Refresh(); }
[ "janiszt@gmail.com" ]
janiszt@gmail.com
f91309ec1463d73994907e0d9d98999d87ff8da2
1a4d186d84b819da76c0ba6e1ebb3af87307a8f3
/2257.cpp
f7f363ebc7d8865bb5cfc8d5a9553ca58d740919
[]
no_license
JungHam/algorithm
b5e986c9e6c70e9092394417c53eaabebe0b8bf1
ead08c8abe19a232651993ea5d52212b9262a4b7
refs/heads/master
2020-03-19T07:19:13.010706
2018-10-28T12:31:25
2018-10-28T12:31:25
136,104,591
0
0
null
null
null
null
UTF-8
C++
false
false
1,637
cpp
#include <iostream> #include <string> #include <ctype.h> using namespace std; string chemical; long long global_count = 0; long long calcChemical(string part_c){ long long local_count= 0; long long previous_count = 0; int i = 0; while(global_count < part_c.size()){ //전역변수로 index 체크하는 경우에는 for문은 괜히 한바퀴 돌고 계속 index를 증감해야 되서 계산하기 헷갈리니까 while문을 쓰자. if(part_c.at(global_count) == ')'){ local_count += previous_count; global_count++; return local_count; } if(part_c.at(global_count) == '(') { local_count += previous_count; global_count++; previous_count = calcChemical(part_c); continue; } else if(isdigit(part_c.at(global_count))){ local_count += previous_count * (int)(part_c.at(global_count) - '0'); previous_count = 0; global_count++; } else{ local_count += previous_count; previous_count = 0; if(part_c.at(global_count) == 'H') previous_count = 1; else if(part_c.at(global_count) == 'C') previous_count = 12; else if(part_c.at(global_count) == 'O') previous_count = 16; global_count++; } } local_count += previous_count; return local_count; } int main() { while(cin >> chemical){ long long cost = calcChemical(chemical); cout << cost << endl; global_count = 0; } return 0; }
[ "wjdgpal7@gmail.com" ]
wjdgpal7@gmail.com
ebc6fb20e89828f29706f62aee1b4cffece75874
36bf908bb8423598bda91bd63c4bcbc02db67a9d
/Library/CHotkeyHandler.cpp
15febe39e79e820d09d62728a8f847983dbeed2d
[]
no_license
code4bones/crawlpaper
edbae18a8b099814a1eed5453607a2d66142b496
f218be1947a9791b2438b438362bc66c0a505f99
refs/heads/master
2021-01-10T13:11:23.176481
2011-04-14T11:04:17
2011-04-14T11:04:17
44,686,513
0
1
null
null
null
null
UTF-8
C++
false
false
18,886
cpp
#include "env.h" #include "pragma.h" #include "macro.h" #include "window.h" #include "traceexpr.h" //#define _TRACE_FLAG _TRFLAG_TRACEOUTPUT //#define _TRACE_FLAG _TRFLAG_NOTRACE #define _TRACE_FLAG_INFO _TRFLAG_NOTRACE #define _TRACE_FLAG_WARN _TRFLAG_NOTRACE #define _TRACE_FLAG_ERR _TRFLAG_NOTRACE /* History ---------- Monday, April 21, 2003 * Initial version Tuesday, April 22, 2003 * Added list entries recycling into RemoveHandler(). Now removing works correctly. * Added utility functions: HotkeyFlagsToModifiers() and HotkeyModifiersToFlags() Wednesday, April 23, 2003 * Added checks on Start() to prevent starting if already started. Thursday, April 24, 2003 * Fixed CreateThread() in Start() calling so that it works on Win9x. Thursday, May 01, 2003 * Fixed code in MakeWindow() and now CHotkeyHandler works under Win9x very well. Monday, Oct 20, 2003 * Removed 'using std::vector' from header file * Fixed a minor bug in RemoveHandler() */ /* ----------------------------------------------------------------------------- * Copyright (c) 2003 Lallous <lallousx86@yahoo.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. * ----------------------------------------------------------------------------- */ /* CHotkeyHandler() is a class that wrappes the RegisterHotkey() and its UnregisterHotkey() Windows APIs. This class provides a simple method to implement and handle multiple hotkeys at the same time. * Debug Flag: -------------- bool bDebug; This flag is used to turn debugging on/off. Useful when you're developing. * Constructor --------------- CHotkeyHandler(bool Debug = false); This constructor initializes internal variables and sets debug info on/off If you call Start() and do not call Stop() the destructor will automatically Stop() for you. * Start() ----------- int Start(LPVOID Param=NULL); This method is asynchronous; It starts the hotkey listener. You must have at least one handler inserted before calling this method, otherwise hkheNoEntry would be returned. It returns an hkhe error code. 'Param' is a user supplied pointer used when calling the hotkey callbacks. * Stop() ----------- int Stop(); After you've started the hotkey listener, you can stop it w/ Stop(). Stop() will return success if it was stopped successfully or if it was not started at all. * InsertHandler() -------------------- int InsertHandler(WORD mod, WORD virt, tHotkeyCB cb, int &index); This function will return an error code. 'index' will be filled by the index of where the hotkey is stored (1 based). If you attempt to insert a hotkey that already exists then 'index' will be the index value of that previously inserted hotkey. 'mod' is any of the MOD_XXXX constants. 'virt' is the virtual key code. 'cb' is the handler that will be called. The prototype is: void Callback(void *param) The 'param' of 'cb' will be the one that you passed when you called Start() * RemoveHandler() -------------------- int RemoveHandler(const int index); Removes a hotkey definition. This function has effects only when called before Start() or after Stop(). * HotkeyModifiersToFlags() ---------------------------- WORD HotkeyModifiersToFlags(WORD modf); Converts from MOD_XXX modifiers into HOTKEYF_XXXX to be used by HOTKEYFLAGS. This method is static. * HotkeyFlagsToModifiers() ----------------------------- WORD HotkeyFlagsToModifiers(WORD hkf); Converts HOTKEYFLAGS used by CHotKeyCtrl into MOD_XXX used by windows API This method is static. Error codes ------------- CHotkeyHandler::hkheXXXXX hkheOk - Success hkheClassError - Window class registration error hkheWindowError - Window creation error hkheNoEntry - No entry found at given index hkheRegHotkeyError - Could not register hotkey hkheMessageLoop - Could not create message loop thread hkheInternal - Internal error */ #include "chotkeyhandler.h" //------------------------------------------------------------------------------------- // Initializes internal variables CHotkeyHandler::CHotkeyHandler(bool Debug) { bDebug = Debug; m_bStarted = false; m_hWnd = NULL; m_hMessageLoopThread = m_hPollingError = m_hRaceProtection = NULL; } //------------------------------------------------------------------------------------- // Initializes internal variables CHotkeyHandler::~CHotkeyHandler() { if (m_bStarted) Stop(); } //------------------------------------------------------------------------------------- // Releases and deletes the protection mutex void CHotkeyHandler::EndRaceProtection() { if (m_hRaceProtection) { ::ReleaseMutex(m_hRaceProtection); ::CloseHandle(m_hRaceProtection); // invalidate handle m_hRaceProtection = NULL; } } //------------------------------------------------------------------------------------- // Creates and acquires protection mutex bool CHotkeyHandler::BeginRaceProtection() { LPCTSTR szMutex = _T("{97B7C451-2467-4C3C-BB91-25AC918C2430}"); // failed to create a mutex ? to open ? if ( // failed to create and the object does not exist? ( !(m_hRaceProtection = ::CreateMutex(NULL, FALSE, szMutex)) && (::GetLastError() != ERROR_ALREADY_EXISTS) ) || !(m_hRaceProtection = ::OpenMutex(MUTEX_ALL_ACCESS, FALSE, szMutex)) ) return false; ::WaitForSingleObject(m_hRaceProtection, INFINITE); return true; } //------------------------------------------------------------------------------------- // removes a disabled hotkey from the internal list // If this function is of use only before a Start() call or after a Stop() int CHotkeyHandler::RemoveHandler(const int index) { // index out of range ? if (m_listHk.size() <= index) return hkheNoEntry; // mark handler as deleted m_listHk.at(index).deleted = true; return hkheOk; } //------------------------------------------------------------------------------------- // Generates a unique atom and then registers a hotkey // int CHotkeyHandler::EnableHotkey(const int index) { TCHAR atomname[MAX_PATH]; ATOM a; // get hotkey definition tHotkeyDef *def = &m_listHk.at(index); // If entry does not exist then return Ok if (def->deleted) return hkheOk; // compose atom name wsprintf(atomname, _T("ED7D65EB-B139-44BB-B455-7BB83FE361DE-%08lX"), MAKELONG(def->virt, def->mod)); // Try to create an atom a = ::GlobalAddAtom(atomname); // could not create? probably already there if (!a) a = ::GlobalFindAtom(atomname); // try to locate atom if (!a || !::RegisterHotKey(m_hWnd, a, def->mod, def->virt)) { if (a) ::GlobalDeleteAtom(a); return hkheRegHotkeyError; } // store atom into definition too def->id = a; return hkheOk; } //------------------------------------------------------------------------------------- // Unregisters a hotkey and deletes the atom int CHotkeyHandler::DisableHotkey(const int index) { // get hotkey definition tHotkeyDef *def = &m_listHk.at(index); // skip deleted entry if (def->deleted) return hkheOk; // already registered if (def->id) { UnregisterHotKey(m_hWnd, def->id); GlobalDeleteAtom(def->id); return hkheOk; } else return hkheNoEntry; } //------------------------------------------------------------------------------------- // Locates a hotkey definition given its ID int CHotkeyHandler::FindHandlerById(const ATOM id, tHotkeyDef *&def) { tHotkeyList::iterator i; for (i=m_listHk.begin(); i != m_listHk.end(); i++) { def = &*i; if ((def->id == id) && !def->deleted) return hkheOk; } return hkheNoEntry; } //------------------------------------------------------------------------------------- // Finds a deleted entry int CHotkeyHandler::FindDeletedHandler(int &idx) { tHotkeyDef *def; int i, c = m_listHk.size(); for (i=0; i< c; i++) { def = &m_listHk[i]; if (def->deleted) { idx = i; return hkheOk; } } return hkheNoEntry; } //------------------------------------------------------------------------------------- // Finds a hotkeydef given it's modifier 'mod' and virtuak key 'virt' // If return value is hkheOk then 'idx' is filled with the found index // Otherwise 'idx' is left untouched. int CHotkeyHandler::FindHandler(WORD mod, WORD virt, int &idx) { tHotkeyDef *def; int i, c = m_listHk.size(); for (i=0; i < c; i++) { def = &m_listHk[i]; // found anything in the list ? if ( (def->mod == mod) && (def->virt == virt) && !def->deleted) { // return its id idx = i; return hkheOk; } } return hkheNoEntry; } //------------------------------------------------------------------------------------- // Inserts a hotkey into the list // Returns into 'idx' the index of where the definition is added // You may use the returned idx to modify/delete this definition int CHotkeyHandler::InsertHandler(WORD mod, WORD virt, tHotkeyCB cb, int &idx) { tHotkeyDef def; // Try to find a deleted entry and use it if (FindDeletedHandler(idx) == hkheOk) { tHotkeyDef *d = &m_listHk.at(idx); d->deleted = false; d->id = NULL; d->callback = cb; d->virt = virt; d->mod = mod; } // Add a new entry else if (FindHandler(mod, virt, idx) == hkheNoEntry) { def.mod = mod; def.virt = virt; def.callback = cb; def.id = NULL; def.deleted = false; idx = m_listHk.size(); m_listHk.push_back(def); } return hkheOk; } //------------------------------------------------------------------------------------- // Window Procedure // Almost empty; it responds to the WM_DESTROY message only LRESULT CALLBACK CHotkeyHandler::WindowProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) { switch (Msg) { case WM_DESTROY: ::PostQuitMessage(0); break; default: return ::DefWindowProc(hWnd, Msg, wParam, lParam); } return 0; } //------------------------------------------------------------------------------------- // This function is run from a new thread, it: // 1) Create our hidden window to process hotkeys // 2) Enables (registers) all defined hotkeys // 3) Starts the message loop DWORD WINAPI CHotkeyHandler::MessageLoop(LPVOID Param) { int rc; CHotkeyHandler *_this = reinterpret_cast<CHotkeyHandler *>(Param); // create window if ((rc = _this->MakeWindow()) != hkheOk) { _this->m_PollingError = rc; ::SetEvent(_this->m_hPollingError); return rc; } // register all hotkeys for (int i=0; i<_this->m_listHk.size(); i++) { // try to register if ((rc = _this->EnableHotkey(i)) != hkheOk) { // disable hotkeys enabled so far for (int j=0;j<i;j++) _this->DisableHotkey(j); // uninit window _this->MakeWindow(true); // signal that error is ready _this->m_PollingError = rc; ::SetEvent(_this->m_hPollingError); return rc; } } _this->m_PollingError = hkheOk; ::SetEvent(_this->m_hPollingError); MSG msg; BOOL bRet; while ( ((bRet = ::GetMessage(&msg, _this->m_hWnd, 0, 0)) != 0) ) { if (bRet == -1) break; // hotkey received ? if (msg.message == WM_HOTKEY) { tHotkeyDef *def; // try to find handler (wParam == id (ATOM) if (_this->FindHandlerById( (ATOM) msg.wParam, def) == hkheOk) { // call the registered handler if (def->callback) def->callback(_this->m_lpCallbackParam); } } ::TranslateMessage(&msg); ::DispatchMessage(&msg); } return hkheOk; } //------------------------------------------------------------------------------------- // This asynchronous function will register all hotkeys and starts the window message // loop into its own thread. You would have to call Stop() to unroll everything // int CHotkeyHandler::Start(LPVOID cbParam) { int rc; // avoid starting again if already started if (m_bStarted) return hkheOk; // Do not start if no entries are there! if (m_listHk.empty()) return hkheNoEntry; if (!BeginRaceProtection()) return hkheInternal; if (!(m_hPollingError = ::CreateEvent(NULL, FALSE, FALSE, NULL))) { rc = hkheMessageLoop; goto cleanup; } m_lpCallbackParam = cbParam; // create message loop thread DWORD dwThreadId; m_hMessageLoopThread = ::CreateThread(NULL, NULL, MessageLoop, static_cast<LPVOID>(this), NULL, &dwThreadId); if (!m_hMessageLoopThread) { rc = hkheMessageLoop; goto cleanup; } // wait until we get an error code from the message loop thread ::WaitForSingleObject(m_hPollingError, INFINITE); if (m_PollingError != hkheOk) { ::CloseHandle(m_hMessageLoopThread); m_hMessageLoopThread = NULL; } rc = m_PollingError; m_bStarted = true; cleanup: EndRaceProtection(); return rc; } //------------------------------------------------------------------------------------- // Disables all hotkeys then kills the hidden window that processed the hotkeys // The return code is the one returned from the MessageLoop() // int CHotkeyHandler::Stop() { // not started? return Success if (!m_bStarted || !m_hMessageLoopThread) return hkheOk; if (!BeginRaceProtection()) return hkheInternal; // disable all hotkeys for (int i=0;i<m_listHk.size();i++) DisableHotkey(i); // tell message loop to terminate ::SendMessage(m_hWnd, WM_DESTROY, 0, 0); // wait for the thread to exit by itself if (::WaitForSingleObject(m_hMessageLoopThread, 3000) == WAIT_TIMEOUT) ::TerminateThread(m_hMessageLoopThread, 0); // kill thread DWORD exitCode; ::GetExitCodeThread(m_hMessageLoopThread, &exitCode); // close handle of thread ::CloseHandle(m_hMessageLoopThread); // reset this variable m_hMessageLoopThread = NULL; // unregister window class MakeWindow(true); // kill error polling event ::CloseHandle(m_hPollingError); m_bStarted = false; EndRaceProtection(); return exitCode; } //------------------------------------------------------------------------------------- // Creates the hidden window that will receive hotkeys notification // When bUnmake, it will Unregister the window class int CHotkeyHandler::MakeWindow(bool bUnmake) { HWND hwnd; WNDCLASSEX wcl; HINSTANCE hInstance = ::GetModuleHandle(NULL); // Our hotkey processing window class LPTSTR szClassName = _T("HKWND-CLS-BC090410-3872-49E5-BDF7-1BB8056BF696"); if (bUnmake) { UnregisterClass(szClassName, hInstance); m_hWnd = NULL; return hkheOk; } // Set the window class wcl.cbSize = sizeof(WNDCLASSEX); wcl.cbClsExtra = 0; wcl.cbWndExtra = 0; wcl.hbrBackground = NULL;//(HBRUSH) GetStockObject(WHITE_BRUSH); wcl.lpszClassName = szClassName; wcl.lpszMenuName = NULL; wcl.hCursor = NULL;//LoadCursor(NULL, IDC_ARROW); wcl.hIcon = NULL;//LoadIcon(NULL, IDI_APPLICATION); wcl.hIconSm = NULL;//LoadIcon(NULL, IDI_WINLOGO); wcl.hInstance = hInstance; wcl.lpfnWndProc = WindowProc; wcl.style = 0; // Failed to register class other than that the class already exists? if (!::RegisterClassEx(&wcl) && (::GetLastError() != ERROR_CLASS_ALREADY_EXISTS)) return hkheClassError; // Create the window hwnd = ::CreateWindowEx( 0, szClassName, _T("CHotkeyHandlerWindow"), WS_OVERLAPPEDWINDOW, 0, 0, 100, 100, HWND_DESKTOP, NULL, hInstance, NULL); // Window creation failed ? if (!hwnd) return hkheWindowError; // hide window ::ShowWindow(hwnd, bDebug ? SW_SHOW : SW_HIDE); m_hWnd = hwnd; return hkheOk; } //--------------------------------------------------------------------------------- // Converts HOTKEYFLAGS used by CHotKeyCtrl into MOD_XXX used by windows API // WORD CHotkeyHandler::HotkeyFlagsToModifiers(WORD hkf) { WORD r; r = ((hkf & HOTKEYF_CONTROL) ? MOD_CONTROL : 0) | ((hkf & HOTKEYF_ALT) ? MOD_ALT : 0) | ((hkf & HOTKEYF_SHIFT) ? MOD_SHIFT : 0); return r; } //--------------------------------------------------------------------------------- // Converts from MOD_XXX modifiers into HOTKEYF_XXXX // WORD CHotkeyHandler::HotkeyModifiersToFlags(WORD modf) { WORD r; r = ((modf & MOD_CONTROL) ? HOTKEYF_CONTROL : 0) | ((modf & MOD_ALT) ? HOTKEYF_ALT : 0) | ((modf & MOD_SHIFT) ? HOTKEYF_SHIFT : 0); return r; }
[ "luca.pierge@gmail.com" ]
luca.pierge@gmail.com
eaaddffc571e5ad5b1aa953164019055033d2410
d0fb46aecc3b69983e7f6244331a81dff42d9595
/alikafka/src/model/UpdateConsumerOffsetResult.cc
1ace5b4b7cf904781ffdfcb26ac559122fbf0a2c
[ "Apache-2.0" ]
permissive
aliyun/aliyun-openapi-cpp-sdk
3d8d051d44ad00753a429817dd03957614c0c66a
e862bd03c844bcb7ccaa90571bceaa2802c7f135
refs/heads/master
2023-08-29T11:54:00.525102
2023-08-29T03:32:48
2023-08-29T03:32:48
115,379,460
104
82
NOASSERTION
2023-09-14T06:13:33
2017-12-26T02:53:27
C++
UTF-8
C++
false
false
1,722
cc
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/alikafka/model/UpdateConsumerOffsetResult.h> #include <json/json.h> using namespace AlibabaCloud::Alikafka; using namespace AlibabaCloud::Alikafka::Model; UpdateConsumerOffsetResult::UpdateConsumerOffsetResult() : ServiceResult() {} UpdateConsumerOffsetResult::UpdateConsumerOffsetResult(const std::string &payload) : ServiceResult() { parse(payload); } UpdateConsumerOffsetResult::~UpdateConsumerOffsetResult() {} void UpdateConsumerOffsetResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); if(!value["Success"].isNull()) success_ = value["Success"].asString() == "true"; if(!value["Code"].isNull()) code_ = std::stoi(value["Code"].asString()); if(!value["Message"].isNull()) message_ = value["Message"].asString(); } std::string UpdateConsumerOffsetResult::getMessage()const { return message_; } int UpdateConsumerOffsetResult::getCode()const { return code_; } bool UpdateConsumerOffsetResult::getSuccess()const { return success_; }
[ "sdk-team@alibabacloud.com" ]
sdk-team@alibabacloud.com
16134ee8a40bb7c4bcbddb21ae296c2b61773ec6
38c10c01007624cd2056884f25e0d6ab85442194
/extensions/common/manifest_test.cc
37034b5927e2c313389bc3889ad80d35a0d61e00
[ "BSD-3-Clause" ]
permissive
zenoalbisser/chromium
6ecf37b6c030c84f1b26282bc4ef95769c62a9b2
e71f21b9b4b9b839f5093301974a45545dad2691
refs/heads/master
2022-12-25T14:23:18.568575
2016-07-14T21:49:52
2016-07-23T08:02:51
63,980,627
0
2
BSD-3-Clause
2022-12-12T12:43:41
2016-07-22T20:14:04
null
UTF-8
C++
false
false
9,032
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "extensions/common/manifest_test.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/json/json_file_value_serializer.h" #include "base/path_service.h" #include "base/strings/pattern.h" #include "base/strings/string_util.h" #include "base/values.h" #include "extensions/common/extension_l10n_util.h" #include "extensions/common/extension_paths.h" #include "extensions/common/test_util.h" #include "ui/base/l10n/l10n_util.h" namespace extensions { namespace { // |manifest_path| is an absolute path to a manifest file. base::DictionaryValue* LoadManifestFile(const base::FilePath& manifest_path, std::string* error) { base::FilePath extension_path = manifest_path.DirName(); EXPECT_TRUE(base::PathExists(manifest_path)) << "Couldn't find " << manifest_path.value(); JSONFileValueDeserializer deserializer(manifest_path); base::DictionaryValue* manifest = static_cast<base::DictionaryValue*>( deserializer.Deserialize(NULL, error).release()); // Most unit tests don't need localization, and they'll fail if we try to // localize them, since their manifests don't have a default_locale key. // Only localize manifests that indicate they want to be localized. // Calling LocalizeExtension at this point mirrors file_util::LoadExtension. if (manifest && manifest_path.value().find(FILE_PATH_LITERAL("localized")) != std::string::npos) extension_l10n_util::LocalizeExtension(extension_path, manifest, error); return manifest; } } // namespace ManifestTest::ManifestTest() : enable_apps_(true) { } ManifestTest::~ManifestTest() { } // Helper class that simplifies creating methods that take either a filename // to a manifest or the manifest itself. ManifestTest::ManifestData::ManifestData(const char* name) : name_(name), manifest_(NULL) { } ManifestTest::ManifestData::ManifestData(base::DictionaryValue* manifest, const char* name) : name_(name), manifest_(manifest) { CHECK(manifest_) << "Manifest NULL"; } ManifestTest::ManifestData::ManifestData( scoped_ptr<base::DictionaryValue> manifest) : manifest_(manifest.get()), manifest_holder_(manifest.Pass()) { CHECK(manifest_) << "Manifest NULL"; } ManifestTest::ManifestData::ManifestData(const ManifestData& m) { NOTREACHED(); } ManifestTest::ManifestData::~ManifestData() { } base::DictionaryValue* ManifestTest::ManifestData::GetManifest( base::FilePath test_data_dir, std::string* error) const { if (manifest_) return manifest_; base::FilePath manifest_path = test_data_dir.AppendASCII(name_); manifest_ = LoadManifestFile(manifest_path, error); manifest_holder_.reset(manifest_); return manifest_; } std::string ManifestTest::GetTestExtensionID() const { return std::string(); } base::FilePath ManifestTest::GetTestDataDir() { base::FilePath path; PathService::Get(DIR_TEST_DATA, &path); return path.AppendASCII("manifest_tests"); } scoped_ptr<base::DictionaryValue> ManifestTest::LoadManifest( char const* manifest_name, std::string* error) { base::FilePath manifest_path = GetTestDataDir().AppendASCII(manifest_name); return make_scoped_ptr(LoadManifestFile(manifest_path, error)); } scoped_refptr<Extension> ManifestTest::LoadExtension( const ManifestData& manifest, std::string* error, extensions::Manifest::Location location, int flags) { base::FilePath test_data_dir = GetTestDataDir(); base::DictionaryValue* value = manifest.GetManifest(test_data_dir, error); if (!value) return NULL; return Extension::Create(test_data_dir.DirName(), location, *value, flags, GetTestExtensionID(), error); } scoped_refptr<Extension> ManifestTest::LoadAndExpectSuccess( const ManifestData& manifest, extensions::Manifest::Location location, int flags) { std::string error; scoped_refptr<Extension> extension = LoadExtension(manifest, &error, location, flags); EXPECT_TRUE(extension.get()) << manifest.name(); EXPECT_EQ("", error) << manifest.name(); return extension; } scoped_refptr<Extension> ManifestTest::LoadAndExpectSuccess( char const* manifest_name, extensions::Manifest::Location location, int flags) { return LoadAndExpectSuccess(ManifestData(manifest_name), location, flags); } scoped_refptr<Extension> ManifestTest::LoadAndExpectWarning( const ManifestData& manifest, const std::string& expected_warning, extensions::Manifest::Location location, int flags) { std::string error; scoped_refptr<Extension> extension = LoadExtension(manifest, &error, location, flags); EXPECT_TRUE(extension.get()) << manifest.name(); EXPECT_EQ("", error) << manifest.name(); EXPECT_EQ(1u, extension->install_warnings().size()); EXPECT_EQ(expected_warning, extension->install_warnings()[0].message); return extension; } scoped_refptr<Extension> ManifestTest::LoadAndExpectWarning( char const* manifest_name, const std::string& expected_warning, extensions::Manifest::Location location, int flags) { return LoadAndExpectWarning( ManifestData(manifest_name), expected_warning, location, flags); } void ManifestTest::VerifyExpectedError( Extension* extension, const std::string& name, const std::string& error, const std::string& expected_error) { EXPECT_FALSE(extension) << "Expected failure loading extension '" << name << "', but didn't get one."; EXPECT_TRUE(base::MatchPattern(error, expected_error)) << name << " expected '" << expected_error << "' but got '" << error << "'"; } void ManifestTest::LoadAndExpectError( const ManifestData& manifest, const std::string& expected_error, extensions::Manifest::Location location, int flags) { std::string error; scoped_refptr<Extension> extension( LoadExtension(manifest, &error, location, flags)); VerifyExpectedError(extension.get(), manifest.name(), error, expected_error); } void ManifestTest::LoadAndExpectError( char const* manifest_name, const std::string& expected_error, extensions::Manifest::Location location, int flags) { return LoadAndExpectError( ManifestData(manifest_name), expected_error, location, flags); } void ManifestTest::AddPattern(extensions::URLPatternSet* extent, const std::string& pattern) { int schemes = URLPattern::SCHEME_ALL; extent->AddPattern(URLPattern(schemes, pattern)); } ManifestTest::Testcase::Testcase(const std::string& manifest_filename, const std::string& expected_error, extensions::Manifest::Location location, int flags) : manifest_filename_(manifest_filename), expected_error_(expected_error), location_(location), flags_(flags) {} ManifestTest::Testcase::Testcase(const std::string& manifest_filename, const std::string& expected_error) : manifest_filename_(manifest_filename), expected_error_(expected_error), location_(extensions::Manifest::INTERNAL), flags_(Extension::NO_FLAGS) {} ManifestTest::Testcase::Testcase(const std::string& manifest_filename) : manifest_filename_(manifest_filename), location_(extensions::Manifest::INTERNAL), flags_(Extension::NO_FLAGS) {} ManifestTest::Testcase::Testcase(const std::string& manifest_filename, extensions::Manifest::Location location, int flags) : manifest_filename_(manifest_filename), location_(location), flags_(flags) {} void ManifestTest::RunTestcases(const Testcase* testcases, size_t num_testcases, ExpectType type) { for (size_t i = 0; i < num_testcases; ++i) RunTestcase(testcases[i], type); } void ManifestTest::RunTestcase(const Testcase& testcase, ExpectType type) { switch (type) { case EXPECT_TYPE_ERROR: LoadAndExpectError(testcase.manifest_filename_.c_str(), testcase.expected_error_, testcase.location_, testcase.flags_); break; case EXPECT_TYPE_WARNING: LoadAndExpectWarning(testcase.manifest_filename_.c_str(), testcase.expected_error_, testcase.location_, testcase.flags_); break; case EXPECT_TYPE_SUCCESS: LoadAndExpectSuccess(testcase.manifest_filename_.c_str(), testcase.location_, testcase.flags_); break; } } } // namespace extensions
[ "zeno.albisser@hemispherian.com" ]
zeno.albisser@hemispherian.com
b4fb2210a8be6a954abc1a796044da981b41c1a0
b7f3edb5b7c62174bed808079c3b21fb9ea51d52
/third_party/blink/renderer/core/layout/ng/mathml/ng_math_radical_layout_algorithm.cc
eda8c7b094f7dd09b2182023358314d5f55cbd49
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "BSD-3-Clause" ]
permissive
otcshare/chromium-src
26a7372773b53b236784c51677c566dc0ad839e4
64bee65c921db7e78e25d08f1e98da2668b57be5
refs/heads/webml
2023-03-21T03:20:15.377034
2020-11-16T01:40:14
2020-11-16T01:40:14
209,262,645
18
21
BSD-3-Clause
2023-03-23T06:20:07
2019-09-18T08:52:07
null
UTF-8
C++
false
false
10,177
cc
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/core/layout/ng/mathml/ng_math_radical_layout_algorithm.h" #include "third_party/blink/renderer/core/layout/ng/mathml/ng_math_layout_utils.h" #include "third_party/blink/renderer/core/layout/ng/ng_block_break_token.h" #include "third_party/blink/renderer/core/layout/ng/ng_box_fragment.h" #include "third_party/blink/renderer/core/layout/ng/ng_length_utils.h" #include "third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part.h" #include "third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h" #include "third_party/blink/renderer/platform/fonts/shaping/stretchy_operator_shaper.h" namespace blink { namespace { bool HasBaseGlyphForRadical(const ComputedStyle& style) { return style.GetFont().PrimaryFont() && style.GetFont().PrimaryFont()->GlyphForCharacter(kSquareRootCharacter); } } // namespace NGMathRadicalLayoutAlgorithm::NGMathRadicalLayoutAlgorithm( const NGLayoutAlgorithmParams& params) : NGLayoutAlgorithm(params) { DCHECK(params.space.IsNewFormattingContext()); container_builder_.SetIsNewFormattingContext( params.space.IsNewFormattingContext()); } void NGMathRadicalLayoutAlgorithm::GatherChildren( NGBlockNode* base, NGBlockNode* index, NGBoxFragmentBuilder* container_builder) const { for (NGLayoutInputNode child = Node().FirstChild(); child; child = child.NextSibling()) { NGBlockNode block_child = To<NGBlockNode>(child); if (child.IsOutOfFlowPositioned()) { if (container_builder) { container_builder->AddOutOfFlowChildCandidate( block_child, BorderScrollbarPadding().StartOffset()); } continue; } if (!*base) { *base = block_child; continue; } if (!*index) { *index = block_child; continue; } NOTREACHED(); } if (Node().HasIndex()) { DCHECK(*base); DCHECK(*index); } } scoped_refptr<const NGLayoutResult> NGMathRadicalLayoutAlgorithm::Layout() { DCHECK(!BreakToken()); DCHECK(IsValidMathMLRadical(Node())); auto vertical = GetRadicalVerticalParameters(Style(), Node().HasIndex()); scoped_refptr<const NGPhysicalBoxFragment> index_fragment, base_fragment; LayoutUnit index_inline_size, index_ascent, index_descent, base_ascent, base_descent; RadicalHorizontalParameters horizontal; NGBoxStrut index_margins, base_margins; NGBlockNode base = nullptr; NGBlockNode index = nullptr; GatherChildren(&base, &index, &container_builder_); if (base) { // Handle layout of base child. For <msqrt> the base is anonymous and uses // the row layout algorithm. NGConstraintSpace constraint_space = CreateConstraintSpaceForMathChild( Node(), ChildAvailableSize(), ConstraintSpace(), base); scoped_refptr<const NGLayoutResult> base_layout_result = base.Layout(constraint_space); base_fragment = &To<NGPhysicalBoxFragment>(base_layout_result->PhysicalFragment()); base_margins = ComputeMarginsFor(constraint_space, base.Style(), ConstraintSpace()); NGBoxFragment fragment(ConstraintSpace().GetWritingMode(), ConstraintSpace().Direction(), *base_fragment); base_ascent = base_margins.block_start + fragment.Baseline().value_or(fragment.BlockSize()); base_descent = fragment.BlockSize() + base_margins.BlockSum() - base_ascent; } if (index) { // Handle layout of index child. // (https://mathml-refresh.github.io/mathml-core/#root-with-index). NGConstraintSpace constraint_space = CreateConstraintSpaceForMathChild( Node(), ChildAvailableSize(), ConstraintSpace(), index); scoped_refptr<const NGLayoutResult> index_layout_result = index.Layout(constraint_space); index_fragment = &To<NGPhysicalBoxFragment>(index_layout_result->PhysicalFragment()); index_margins = ComputeMarginsFor(constraint_space, index.Style(), ConstraintSpace()); NGBoxFragment fragment(ConstraintSpace().GetWritingMode(), ConstraintSpace().Direction(), *index_fragment); index_inline_size = fragment.InlineSize() + index_margins.InlineSum(); index_ascent = index_margins.block_start + fragment.Baseline().value_or(fragment.BlockSize()); index_descent = fragment.BlockSize() + index_margins.BlockSum() - index_ascent; horizontal = GetRadicalHorizontalParameters(Style()); horizontal.kern_before_degree = std::max(horizontal.kern_before_degree, LayoutUnit()); horizontal.kern_after_degree = std::max(horizontal.kern_after_degree, -index_inline_size); } StretchyOperatorShaper::Metrics surd_metrics; if (HasBaseGlyphForRadical(Style())) { // Stretch the radical operator to cover the base height. StretchyOperatorShaper shaper(kSquareRootCharacter, OpenTypeMathStretchData::Vertical); float target_size = base_ascent + base_descent + vertical.vertical_gap + vertical.rule_thickness; scoped_refptr<ShapeResult> shape_result = shaper.Shape(&Style().GetFont(), target_size, &surd_metrics); scoped_refptr<ShapeResultView> shape_result_view = ShapeResultView::Create(shape_result.get()); LayoutUnit operator_inline_offset = index_inline_size + horizontal.kern_before_degree + horizontal.kern_after_degree; container_builder_.SetMathMLPaintInfo( kSquareRootCharacter, std::move(shape_result_view), LayoutUnit(surd_metrics.advance), LayoutUnit(surd_metrics.ascent), LayoutUnit(surd_metrics.descent), &operator_inline_offset, &base_margins); } // Determine the metrics of the radical operator + the base. LayoutUnit radical_operator_block_size = LayoutUnit(surd_metrics.ascent + surd_metrics.descent); LayoutUnit index_bottom_raise = LayoutUnit(vertical.degree_bottom_raise_percent) * radical_operator_block_size; LayoutUnit radical_ascent = base_ascent + vertical.vertical_gap + vertical.rule_thickness + vertical.extra_ascender; LayoutUnit ascent = radical_ascent; LayoutUnit descent = std::max(base_descent, radical_operator_block_size + vertical.extra_ascender - ascent); if (index) { ascent = std::max( ascent, -descent + index_bottom_raise + index_descent + index_ascent); descent = std::max( descent, descent - index_bottom_raise + index_descent + index_ascent); } ascent += BorderScrollbarPadding().block_start; if (base) { LogicalOffset base_offset = { BorderScrollbarPadding().inline_start + LayoutUnit(surd_metrics.advance) + index_inline_size + horizontal.kern_before_degree + horizontal.kern_after_degree + base_margins.inline_start, base_margins.block_start - base_ascent + ascent}; container_builder_.AddChild(To<NGPhysicalContainerFragment>(*base_fragment), base_offset); base.StoreMargins(ConstraintSpace(), base_margins); } if (index) { LogicalOffset index_offset = { BorderScrollbarPadding().inline_start + index_margins.inline_start + horizontal.kern_before_degree, index_margins.block_start + ascent + descent - index_bottom_raise - index_descent - index_ascent}; container_builder_.AddChild( To<NGPhysicalContainerFragment>(*index_fragment), index_offset); index.StoreMargins(ConstraintSpace(), index_margins); } container_builder_.SetBaseline(ascent); auto total_block_size = ascent + descent + BorderScrollbarPadding().block_end; LayoutUnit block_size = ComputeBlockSizeForFragment( ConstraintSpace(), Style(), BorderPadding(), total_block_size, container_builder_.InitialBorderBoxSize().inline_size); container_builder_.SetIntrinsicBlockSize(total_block_size); container_builder_.SetFragmentsTotalBlockSize(block_size); NGOutOfFlowLayoutPart(Node(), ConstraintSpace(), &container_builder_).Run(); return container_builder_.ToBoxFragment(); } MinMaxSizesResult NGMathRadicalLayoutAlgorithm::ComputeMinMaxSizes( const MinMaxSizesInput& input) const { DCHECK(IsValidMathMLRadical(Node())); NGBlockNode base = nullptr; NGBlockNode index = nullptr; GatherChildren(&base, &index); MinMaxSizes sizes; bool depends_on_percentage_block_size = false; if (index) { auto horizontal = GetRadicalHorizontalParameters(Style()); sizes += horizontal.kern_before_degree.ClampNegativeToZero(); MinMaxSizesResult index_result = ComputeMinAndMaxContentContribution(Style(), index, input); NGBoxStrut index_margins = ComputeMinMaxMargins(Style(), index); index_result.sizes += index_margins.InlineSum(); depends_on_percentage_block_size |= index_result.depends_on_percentage_block_size; sizes += index_result.sizes; // kern_after_degree decreases the inline size, but is capped by the index // content inline size. sizes.min_size += std::max(-index_result.sizes.min_size, horizontal.kern_after_degree); sizes.max_size += std::max(index_result.sizes.max_size, horizontal.kern_after_degree); } if (base) { if (HasBaseGlyphForRadical(Style())) { sizes += GetMinMaxSizesForVerticalStretchyOperator(Style(), kSquareRootCharacter); } MinMaxSizesResult base_result = ComputeMinAndMaxContentContribution(Style(), base, input); NGBoxStrut base_margins = ComputeMinMaxMargins(Style(), base); base_result.sizes += base_margins.InlineSum(); depends_on_percentage_block_size |= base_result.depends_on_percentage_block_size; sizes += base_result.sizes; } sizes += BorderScrollbarPadding().InlineSum(); return {sizes, depends_on_percentage_block_size}; } } // namespace blink
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
e6b2340e49f0a04fd8c583d433974d25dd44984a
25765941341ff304a3c7faf0ddee437f3bea8310
/src/WinMain.cxx
94a00033fdd67b18162d53c80d8f55e8a1dcb597
[ "BSD-3-Clause" ]
permissive
fermi-lat/gui
797cdf0dfb9a0905e2bebbe618dc8a4701c0ffc0
d2387b2d9f2bbde3a9310ff8f2cca038a339ebf6
refs/heads/master
2021-05-05T16:14:43.636293
2019-08-27T17:29:51
2019-08-27T17:29:51
103,186,998
0
0
null
null
null
null
UTF-8
C++
false
false
5,859
cxx
#ifdef WIN32 // only used for the windows app // $Header: /nfs/slac/g/glast/ground/cvs/GlastRelease-scons/gui/src/WinMain.cxx,v 1.2 2002/11/01 22:57:05 burnett Exp $ #include "WinGui.h" #include "WinScene.h" #include "WinGUIostream.h" #include "gui/Menu.h" #include "gui/SubMenu.h" #include "resource.h" extern "C" { int main(int argn, char *argc[] );} static char *szAppName = "WinGUI"; //======================================================================== // Windows routines //======================================================================== LRESULT CALLBACK WndProc (HWND hWnd, unsigned Message, WPARAM wParam, LONG lParam) { // decide which window this is, set appropriate scene to message WinScene* display = ( hWnd==WinGUI::s_hwnd || WinGUI::s_hwnd==0)? WinGUI::s_graphics_window : WinGUI::s_2d_window; switch(Message) { case WM_COMMAND: WinGUI::s_gui->execute(wParam); break; case WM_PAINT: { PAINTSTRUCT ps; HDC hdc= BeginPaint( hWnd, &ps); if(display) display->redisplay(hdc); EndPaint(hWnd, &ps); } break; case WM_CHAR: { // single non-special key char c = static_cast<char>(wParam); // check if is is registered with the Menu if( Menu::instance()->strike(c)) break; // no, just pass it to the display char cmd[2] = {c,0}; if( display->do_command(cmd)>0 ) display->redisplay(); } break; case WM_KEYDOWN: { char cmd[2] = {0,0}; switch (wParam){ case VK_LEFT: cmd[1]=75; break; case VK_RIGHT:cmd[1]=77; break; case VK_HOME: cmd[1]=71; break; case VK_UP: cmd[1]=72; break; case VK_DOWN: cmd[1]=80; break; case VK_PRIOR:cmd[1]=73; break; case VK_NEXT: cmd[1]=81; break; } if (!cmd[1] )break; if( display->do_command(cmd)>0 ) display->redisplay(); } break; case WM_LBUTTONDOWN: { int xPos = LOWORD(lParam); // horizontal position of cursor int yPos = HIWORD(lParam); // vertical position of cursor display->mouseDown(xPos,yPos); } break; case WM_LBUTTONUP: { int xPos = LOWORD(lParam); // horizontal position of cursor int yPos = HIWORD(lParam); // vertical position of cursor display->mouseUp(xPos,yPos); } break; case WM_RBUTTONUP : { RECT winpos; ::GetWindowRect(hWnd, &winpos); ::TrackPopupMenu( (HMENU)(display->menu()->tag()), // handle to shortcut menu TPM_LEFTALIGN | TPM_TOPALIGN, // screen-position and mouse-button flags winpos.left+LOWORD(lParam), // horizontal position, in screen coordinates winpos.top+HIWORD(lParam), // vertical position, in screen coordinates 0, // reserved, must be zero hWnd, // handle to owner window 0); } break; case WM_ACTIVATEAPP: { int fActive = LOWORD(wParam); // activation flag if( fActive) ::SetCursor(::LoadCursor(NULL, IDC_ARROW)); break; } case WM_DESTROY: Menu::instance()->quit(); #if 0 ::PostQuitMessage(0); WinGUI::s_quitting=true; GUI::running=false; #endif break; case WM_SETCURSOR: // mouse comes over window--make it the normal arrow { ::SetCursor(::LoadCursor(NULL, IDC_ARROW)); break; } default: return ::DefWindowProc(hWnd, Message, wParam, lParam); } return 0; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ int WINAPI WinMain(HINSTANCE hThisInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow) { WinGUI::s_instance = hThisInstance; //need the instance // declare, and create a windows class for the main window WNDCLASS wndClass; if (!hPrevInstance) { wndClass.style = CS_HREDRAW | CS_VREDRAW ; wndClass.lpfnWndProc = WndProc; wndClass.cbClsExtra = 0; wndClass.cbWndExtra = 0; wndClass.hInstance = hThisInstance; wndClass.hIcon = wndClass.hIcon= LoadIcon(hThisInstance,MAKEINTRESOURCE(IDI_ICON1));; wndClass.hCursor = NULL; wndClass.hbrBackground = (HBRUSH)GetStockObject (LTGRAY_BRUSH); wndClass.lpszMenuName = NULL; wndClass.lpszClassName = szAppName; if( !RegisterClass(&wndClass) ) return FALSE; } // create the main window to be used later WinGUI::s_hwnd = CreateWindow(szAppName, "", (WS_OVERLAPPED | WS_CAPTION | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_THICKFRAME | WS_SYSMENU),//WS_OVERLAPPEDWINDOW, 20, 20, //CW_USEDEFAULT, 0, 500, 500, //CW_USEDEFAULT, 0, NULL, NULL, WinGUI::s_instance, NULL); // setup the console window here WinGUI::s_text_window = new WinGUIostream( "wingui", WinGUI::s_hwnd, WinGUI::s_instance); // parse command line by hand const unsigned MAX_TOKENS=20; char * _argv[MAX_TOKENS]; _argv[0] = szAppName; int argc = 1; char seps[] = " \t\n"; /* Establish string and get the first token: */ char * token = strtok( lpszCmdLine, seps ); while(token != NULL && argc < MAX_TOKENS) { /* While there are tokens in "string" */ _argv[argc++] = token; /* Get next token: */ token = strtok( NULL, seps ); } // ::UserMain(argc, _argv); ::main(argc, _argv); return 0; } #endif
[ "" ]
185f0ea6883490059c56bf02d212e1be05ad187d
07c856e147c6b3f0fa607ecb632a573c02165f4f
/Ch08_Algorithm/ex32_next_permutation.cpp
ccfd00a371adeafd5a210c7435965b448b6c9ca8
[]
no_license
choisb/Study-Cpp-STL
46359db3783767b1ef6099761f67164ab637e579
e5b12b6da744f37713983ef6f61d4f0e10a4eb13
refs/heads/master
2023-06-25T04:13:40.960447
2021-07-19T01:38:59
2021-07-19T01:38:59
329,786,891
0
0
null
null
null
null
UHC
C++
false
false
1,767
cpp
// next_permutation() 알고리즘 예제 // 원소의 순서를 순열처럼 변경할 때 next_permutation()과 prev_permutation()알고리즘을 사용 // next_permutation(b,e)는 구간 [b,e)의 순차열을 다음 순열의 순차열이 되게 한다. // 마지막 순열이라면 false를 반환하며, 아니면 true를 반환한다. // 이전 순열의 순차열이 되도록 하기 위해서는 prev_premutation(b,e)를 사용한다. // 기본적으로 순열의 기준은 사전순이며, 사용자가 조건자를 사용하여 기준을 만들 수도 있다. #include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { vector<int> vec1; vec1.push_back(10); vec1.push_back(20); vec1.push_back(30); cout << "vec1: "; for (auto v : vec1) cout << v << " "; cout << endl; while (next_permutation(vec1.begin(), vec1.end())) { cout << "next> "; cout << "vec1: "; for (auto v : vec1) cout << v << " "; cout << endl; } cout << "vec1: "; for (auto v : vec1) cout << v << " "; cout << endl; prev_permutation(vec1.begin(), vec1.end()); cout << "vec1: "; for (auto v : vec1) cout << v << " "; cout << endl; while (prev_permutation(vec1.begin(), vec1.end())) { cout << "prev> "; cout << "vec1: "; for (auto v : vec1) cout << v << " "; cout << endl; } cout << "vec1: "; for (auto v : vec1) cout << v << " "; cout << endl; return 0; } // [출력 결과] // vec1: 10 20 30 // next > vec1: 10 30 20 // next > vec1: 20 10 30 // next > vec1: 20 30 10 // next > vec1: 30 10 20 // next > vec1: 30 20 10 // vec1 : 10 20 30 // vec1 : 30 20 10 // prev > vec1: 30 10 20 // prev > vec1: 20 30 10 // prev > vec1: 20 10 30 // prev > vec1: 10 30 20 // prev > vec1: 10 20 30 // vec1 : 30 20 10
[ "s004402@gmail.com" ]
s004402@gmail.com
d672de6dff7d0f640a73931604a38f86ee73bcb1
1f2ba15e21a80b939cfe8b44851370ed5728b171
/Chapter 3/3.1.5 (1).cpp
a20af25c38489b658ffe50700549088ffe10bffc
[]
no_license
AWoLf98/CPP-Advanced-Programing
bc8d9fc50731ccd22d433c2c7842bb7c5b68fc6d
1cccb906dc8a3d3ea07b4d55d6fd47284e2fd5be
refs/heads/master
2021-08-31T04:38:12.021413
2017-12-20T10:16:48
2017-12-20T10:16:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
297
cpp
#include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; //your_code int main() { vector<int> values = { 1, 1, 5, 3, 4, 4, 3, 2, 2, 4, 4, 5, 3, 8, 8, 1 }; //your_code // pattern 1: { 0, 1, -1 } // pattern 2: { -1, 1, 0 } return 0; }
[ "andresistuk@ukr.net" ]
andresistuk@ukr.net
48b037c14f1bbf610eb0e00e1730d52c6b18eca2
ef59aae67e896e78723b719415068aa93a685854
/others/sketch_oct09b/sketch_oct09b.ino
a453680e748b2c1ead3059f6cad0f87b4689f14f
[]
no_license
tokujin/Arduino
fe99fffa7c66dd0386fef1a4caee63ee509f7614
282de130362bd1e7aa8c74bd8bf55f37c70631e7
refs/heads/master
2016-09-06T05:12:09.744414
2013-05-08T16:52:43
2013-05-08T16:52:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
544
ino
int sensorPin = A0; //select the input pin for the potentiometer int ledPin = 13; //select the pin for the LED int sensorValue = 0; //variable to store the value coming from the int newSensorValue; void setup(){ //declare the ledPIN as an OUTPUT: pinMode(ledPin, OUTPUT); Serial.begin(9600); } void loop(){ //read the value from the sensor: sensorValue = analogRead(sensorPin); //turn the ledPIN on newSensorValue = map(sensorValue, 0, 1023, 0, 255); analogWrite(ledPin, newSensorValue); Serial.print(newSensorValue); }
[ "norihito.yuki@me.com" ]
norihito.yuki@me.com
9b3058d03ff2b7fc2ad16cb089d2a4c75f371b85
3f21c24ff10cba14ca4ab16ee62e8c1213b60bd0
/src/gestures/SystemGesture.cpp
03d4e8db2d65cba5171cd68042440ba4b06391d7
[]
no_license
watson-intu/self
273833269f5bf1027d823896e085ac675d1eb733
150dc55e193a1df01e7acfbc47610c29b279c2e7
refs/heads/develop
2021-01-20T03:15:02.118963
2018-04-16T08:19:31
2018-04-16T08:19:31
89,515,657
34
31
null
2018-04-16T08:15:51
2017-04-26T18:50:00
C++
UTF-8
C++
false
false
1,446
cpp
/** * Copyright 2017 IBM Corp. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "SystemGesture.h" #include "utils/ThreadPool.h" REG_SERIALIZABLE( SystemGesture ); RTTI_IMPL( SystemGesture, IGesture ); void SystemGesture::Serialize(Json::Value & json) { IGesture::Serialize( json ); json["m_SystemId"] = m_SystemId; } void SystemGesture::Deserialize(const Json::Value & json) { IGesture::Deserialize( json ); if ( json.isMember( "m_SystemId" ) ) m_SystemId = json["m_SystemId"].asString(); } bool SystemGesture::Execute( GestureDelegate a_Callback, const ParamsMap & a_Params ) { if ( m_SystemId == "reboot" ) ThreadPool::Instance()->StopMainThread(1); else if ( m_SystemId == "shutdown" ) ThreadPool::Instance()->StopMainThread(0); else Log::Warning( "SystemGesture", "Unsupported system gesture %s", m_SystemId.c_str() ); if ( a_Callback.IsValid() ) a_Callback( this ); return true; }
[ "rolyle@us.ibm.com" ]
rolyle@us.ibm.com
897cab253c90b9ff94274363bd7767a992fca802
21f082941cce3824ba96366e576308de135c08a7
/src/rpcblockchain.cpp
75ede93db5c20ab574c7bb7bfe3d3f935ea5d7b8
[ "MIT" ]
permissive
chain123-team/litecoins
f1f582ec0f85e0b13c18781a4d8720cd35e32909
0409e805314b5e200a065c676d674e92840094a1
refs/heads/main
2023-09-02T23:04:20.061668
2021-11-12T07:55:47
2021-11-12T07:55:47
290,706,290
0
0
null
null
null
null
UTF-8
C++
false
false
34,678
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "base58.h" #include "checkpoints.h" #include "clientversion.h" #include "core_io.h" #include "main.h" #include "rpcserver.h" #include "sync.h" #include "txdb.h" #include "util.h" #include "utilmoneystr.h" #include <stdint.h> #include <univalue.h> using namespace std; double GetDifficulty(const CBlockIndex* blockindex) { // Floating point number that is a multiple of the minimum difficulty, // minimum difficulty = 1.0. if (blockindex == nullptr) { if (chainActive.Tip() == nullptr) return 1.0; else blockindex = chainActive.Tip(); } int nShift = (blockindex->nBits >> 24) & 0xff; double dDiff = (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff); while (nShift < 29) { dDiff *= 256.0; nShift++; } while (nShift > 29) { dDiff /= 256.0; nShift--; } return dDiff; } UniValue blockheaderToJSON(const CBlockIndex* blockindex) { UniValue result(UniValue::VOBJ); result.push_back(Pair("hash", blockindex->GetBlockHash().GetHex())); int confirmations = -1; // Only report confirmations if the block is on the main chain if (chainActive.Contains(blockindex)) confirmations = chainActive.Height() - blockindex->nHeight + 1; result.push_back(Pair("confirmations", confirmations)); result.push_back(Pair("height", blockindex->nHeight)); result.push_back(Pair("version", blockindex->nVersion)); result.push_back(Pair("merkleroot", blockindex->hashMerkleRoot.GetHex())); result.push_back(Pair("time", (int64_t)blockindex->nTime)); result.push_back(Pair("mediantime", (int64_t)blockindex->GetMedianTimePast())); result.push_back(Pair("nonce", (uint64_t)blockindex->nNonce)); result.push_back(Pair("bits", strprintf("%08x", blockindex->nBits))); result.push_back(Pair("difficulty", GetDifficulty(blockindex))); result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex())); if (blockindex->pprev) result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex())); CBlockIndex *pnext = chainActive.Next(blockindex); if (pnext) result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex())); return result; } UniValue blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool txDetails = false) { UniValue result(UniValue::VOBJ); result.push_back(Pair("hash", block.GetHash().GetHex())); int confirmations = -1; // Only report confirmations if the block is on the main chain if (chainActive.Contains(blockindex)) confirmations = chainActive.Height() - blockindex->nHeight + 1; result.push_back(Pair("confirmations", confirmations)); result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION))); result.push_back(Pair("height", blockindex->nHeight)); result.push_back(Pair("version", block.nVersion)); result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex())); UniValue txs(UniValue::VARR); BOOST_FOREACH (const CTransaction& tx, block.vtx) { if (txDetails) { UniValue objTx(UniValue::VOBJ); TxToUniv(tx, uint256(0), objTx); txs.push_back(objTx); } else txs.push_back(tx.GetHash().GetHex()); } result.push_back(Pair("tx", txs)); result.push_back(Pair("time", block.GetBlockTime())); result.push_back(Pair("mediantime", (int64_t)blockindex->GetMedianTimePast())); result.push_back(Pair("nonce", (uint64_t)block.nNonce)); result.push_back(Pair("bits", strprintf("%08x", block.nBits))); result.push_back(Pair("difficulty", GetDifficulty(blockindex))); result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex())); if (blockindex->pprev) result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex())); CBlockIndex* pnext = chainActive.Next(blockindex); if (pnext) result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex())); result.push_back(Pair("modifier", strprintf("%016x", blockindex->nStakeModifier))); result.push_back(Pair("moneysupply",ValueFromAmount(blockindex->nMoneySupply))); return result; } UniValue getblockcount(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getblockcount\n" "\nReturns the number of blocks in the longest block chain.\n" "\nResult:\n" "n (numeric) The current block count\n" "\nExamples:\n" + HelpExampleCli("getblockcount", "") + HelpExampleRpc("getblockcount", "")); LOCK(cs_main); return chainActive.Height(); } UniValue getbestblockhash(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getbestblockhash\n" "\nReturns the hash of the best (tip) block in the longest block chain.\n" "\nResult\n" "\"hex\" (string) the block hash hex encoded\n" "\nExamples\n" + HelpExampleCli("getbestblockhash", "") + HelpExampleRpc("getbestblockhash", "")); LOCK(cs_main); return chainActive.Tip()->GetBlockHash().GetHex(); } UniValue getdifficulty(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getdifficulty\n" "\nReturns the proof-of-work difficulty as a multiple of the minimum difficulty.\n" "\nResult:\n" "n.nnn (numeric) the proof-of-work difficulty as a multiple of the minimum difficulty.\n" "\nExamples:\n" + HelpExampleCli("getdifficulty", "") + HelpExampleRpc("getdifficulty", "")); LOCK(cs_main); return GetDifficulty(); } UniValue mempoolToJSON(bool fVerbose = false) { if (fVerbose) { LOCK(mempool.cs); UniValue o(UniValue::VOBJ); BOOST_FOREACH (const PAIRTYPE(uint256, CTxMemPoolEntry) & entry, mempool.mapTx) { const uint256& hash = entry.first; const CTxMemPoolEntry& e = entry.second; UniValue info(UniValue::VOBJ); info.push_back(Pair("size", (int)e.GetTxSize())); info.push_back(Pair("fee", ValueFromAmount(e.GetFee()))); info.push_back(Pair("time", e.GetTime())); info.push_back(Pair("height", (int)e.GetHeight())); info.push_back(Pair("startingpriority", e.GetPriority(e.GetHeight()))); info.push_back(Pair("currentpriority", e.GetPriority(chainActive.Height()))); const CTransaction& tx = e.GetTx(); set<string> setDepends; BOOST_FOREACH (const CTxIn& txin, tx.vin) { if (mempool.exists(txin.prevout.hash)) setDepends.insert(txin.prevout.hash.ToString()); } UniValue depends(UniValue::VARR); BOOST_FOREACH(const string& dep, setDepends) { depends.push_back(dep); } info.push_back(Pair("depends", depends)); o.push_back(Pair(hash.ToString(), info)); } return o; } else { vector<uint256> vtxid; mempool.queryHashes(vtxid); UniValue a(UniValue::VARR); BOOST_FOREACH (const uint256& hash, vtxid) a.push_back(hash.ToString()); return a; } } UniValue getrawmempool(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getrawmempool ( verbose )\n" "\nReturns all transaction ids in memory pool as a json array of string transaction ids.\n" "\nArguments:\n" "1. verbose (boolean, optional, default=false) true for a json object, false for array of transaction ids\n" "\nResult: (for verbose = false):\n" "[ (json array of string)\n" " \"transactionid\" (string) The transaction id\n" " ,...\n" "]\n" "\nResult: (for verbose = true):\n" "{ (json object)\n" " \"transactionid\" : { (json object)\n" " \"size\" : n, (numeric) transaction size in bytes\n" " \"fee\" : n, (numeric) transaction fee in lts\n" " \"time\" : n, (numeric) local time transaction entered pool in seconds since 1 Jan 1970 GMT\n" " \"height\" : n, (numeric) block height when transaction entered pool\n" " \"startingpriority\" : n, (numeric) priority when transaction entered pool\n" " \"currentpriority\" : n, (numeric) transaction priority now\n" " \"depends\" : [ (array) unconfirmed transactions used as inputs for this transaction\n" " \"transactionid\", (string) parent transaction id\n" " ... ]\n" " }, ...\n" "]\n" "\nExamples\n" + HelpExampleCli("getrawmempool", "true") + HelpExampleRpc("getrawmempool", "true")); LOCK(cs_main); bool fVerbose = false; if (params.size() > 0) fVerbose = params[0].get_bool(); return mempoolToJSON(fVerbose); } UniValue getblockhash(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getblockhash index\n" "\nReturns hash of block in best-block-chain at index provided.\n" "\nArguments:\n" "1. index (numeric, required) The block index\n" "\nResult:\n" "\"hash\" (string) The block hash\n" "\nExamples:\n" + HelpExampleCli("getblockhash", "1000") + HelpExampleRpc("getblockhash", "1000")); LOCK(cs_main); int nHeight = params[0].get_int(); if (nHeight < 0 || nHeight > chainActive.Height()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range"); CBlockIndex* pblockindex = chainActive[nHeight]; return pblockindex->GetBlockHash().GetHex(); } UniValue getblock(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getblock \"hash\" ( verbose )\n" "\nIf verbose is false, returns a string that is serialized, hex-encoded data for block 'hash'.\n" "If verbose is true, returns an Object with information about block <hash>.\n" "\nArguments:\n" "1. \"hash\" (string, required) The block hash\n" "2. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n" "\nResult (for verbose = true):\n" "{\n" " \"hash\" : \"hash\", (string) the block hash (same as provided)\n" " \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n" " \"size\" : n, (numeric) The block size\n" " \"height\" : n, (numeric) The block height or index\n" " \"version\" : n, (numeric) The block version\n" " \"merkleroot\" : \"xxxx\", (string) The merkle root\n" " \"tx\" : [ (array of string) The transaction ids\n" " \"transactionid\" (string) The transaction id\n" " ,...\n" " ],\n" " \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"nonce\" : n, (numeric) The nonce\n" " \"bits\" : \"1d00ffff\", (string) The bits\n" " \"difficulty\" : x.xxx, (numeric) The difficulty\n" " \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n" " \"nextblockhash\" : \"hash\" (string) The hash of the next block\n" " \"moneysupply\" : \"supply\" (numeric) The money supply when this block was added to the blockchain\n" "}\n" "\nResult (for verbose=false):\n" "\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n" "\nExamples:\n" + HelpExampleCli("getblock", "\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\"") + HelpExampleRpc("getblock", "\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\"")); LOCK(cs_main); uint256 hash(ParseHashV(params[0].get_str(), "blockhash")); bool fVerbose = true; if (params.size() > 1) fVerbose = params[1].get_bool(); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hash]; if (!ReadBlockFromDisk(block, pblockindex)) throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk"); if (!fVerbose) { CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION); ssBlock << block; std::string strHex = HexStr(ssBlock.begin(), ssBlock.end()); return strHex; } return blockToJSON(block, pblockindex); } UniValue getblockheader(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getblockheader \"hash\" ( verbose )\n" "\nIf verbose is false, returns a string that is serialized, hex-encoded data for block 'hash' header.\n" "If verbose is true, returns an Object with information about block <hash> header.\n" "\nArguments:\n" "1. \"hash\" (string, required) The block hash\n" "2. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n" "\nResult (for verbose = true):\n" "{\n" " \"version\" : n, (numeric) The block version\n" " \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n" " \"merkleroot\" : \"xxxx\", (string) The merkle root\n" " \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"nonce\" : n, (numeric) The nonce\n" " \"bits\" : \"1d00ffff\", (string) The bits\n" "}\n" "\nResult (for verbose=false):\n" "\"data\" (string) A string that is serialized, hex-encoded data for block 'hash' header.\n" "\nExamples:\n" + HelpExampleCli("getblockheader", "\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\"") + HelpExampleRpc("getblockheader", "\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\"")); uint256 hash(ParseHashV(params[0].get_str(), "hash")); bool fVerbose = true; if (params.size() > 1) fVerbose = params[1].get_bool(); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlockIndex* pblockindex = mapBlockIndex[hash]; if (!fVerbose) { CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION); ssBlock << pblockindex->GetBlockHeader(); std::string strHex = HexStr(ssBlock.begin(), ssBlock.end()); return strHex; } return blockheaderToJSON(pblockindex); } UniValue gettxoutsetinfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "gettxoutsetinfo\n" "\nReturns statistics about the unspent transaction output set.\n" "Note this call may take some time.\n" "\nResult:\n" "{\n" " \"height\":n, (numeric) The current block height (index)\n" " \"bestblock\": \"hex\", (string) the best block hash hex\n" " \"transactions\": n, (numeric) The number of transactions\n" " \"txouts\": n, (numeric) The number of output transactions\n" " \"bytes_serialized\": n, (numeric) The serialized size\n" " \"hash_serialized\": \"hash\", (string) The serialized hash\n" " \"total_amount\": x.xxx (numeric) The total amount\n" "}\n" "\nExamples:\n" + HelpExampleCli("gettxoutsetinfo", "") + HelpExampleRpc("gettxoutsetinfo", "")); LOCK(cs_main); UniValue ret(UniValue::VOBJ); CCoinsStats stats; FlushStateToDisk(); if (pcoinsTip->GetStats(stats)) { ret.push_back(Pair("height", (int64_t)stats.nHeight)); ret.push_back(Pair("bestblock", stats.hashBlock.GetHex())); ret.push_back(Pair("transactions", (int64_t)stats.nTransactions)); ret.push_back(Pair("txouts", (int64_t)stats.nTransactionOutputs)); ret.push_back(Pair("bytes_serialized", (int64_t)stats.nSerializedSize)); ret.push_back(Pair("hash_serialized", stats.hashSerialized.GetHex())); ret.push_back(Pair("total_amount", ValueFromAmount(stats.nTotalAmount))); } return ret; } UniValue gettxout(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 3) throw runtime_error( "gettxout \"txid\" n ( includemempool )\n" "\nReturns details about an unspent transaction output.\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id\n" "2. n (numeric, required) vout value\n" "3. includemempool (boolean, optional) Whether to included the mem pool\n" "\nResult:\n" "{\n" " \"bestblock\" : \"hash\", (string) the block hash\n" " \"confirmations\" : n, (numeric) The number of confirmations\n" " \"value\" : x.xxx, (numeric) The transaction value in lts\n" " \"scriptPubKey\" : { (json object)\n" " \"asm\" : \"code\", (string) \n" " \"hex\" : \"hex\", (string) \n" " \"reqSigs\" : n, (numeric) Number of required signatures\n" " \"type\" : \"pubkeyhash\", (string) The type, eg pubkeyhash\n" " \"addresses\" : [ (array of string) array of lts addresses\n" " \"ltsaddress\" (string) lts address\n" " ,...\n" " ]\n" " },\n" " \"version\" : n, (numeric) The version\n" " \"coinbase\" : true|false (boolean) Coinbase or not\n" "}\n" "\nExamples:\n" "\nGet unspent transactions\n" + HelpExampleCli("listunspent", "") + "\nView the details\n" + HelpExampleCli("gettxout", "\"txid\" 1") + "\nAs a json rpc call\n" + HelpExampleRpc("gettxout", "\"txid\", 1")); LOCK(cs_main); UniValue ret(UniValue::VOBJ); uint256 hash(ParseHashV(params[0].get_str(), "txid")); int n = params[1].get_int(); bool fMempool = true; if (params.size() > 2) fMempool = params[2].get_bool(); CCoins coins; if (fMempool) { LOCK(mempool.cs); CCoinsViewMemPool view(pcoinsTip, mempool); if (!view.GetCoins(hash, coins)) return NullUniValue; mempool.pruneSpent(hash, coins); // TODO: this should be done by the CCoinsViewMemPool } else { if (!pcoinsTip->GetCoins(hash, coins)) return NullUniValue; } if (n < 0 || (unsigned int)n >= coins.vout.size() || coins.vout[n].IsNull()) return NullUniValue; BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock()); CBlockIndex* pindex = it->second; ret.push_back(Pair("bestblock", pindex->GetBlockHash().GetHex())); if ((unsigned int)coins.nHeight == MEMPOOL_HEIGHT) ret.push_back(Pair("confirmations", 0)); else ret.push_back(Pair("confirmations", pindex->nHeight - coins.nHeight + 1)); ret.push_back(Pair("value", ValueFromAmount(coins.vout[n].nValue))); UniValue o(UniValue::VOBJ); ScriptPubKeyToUniv(coins.vout[n].scriptPubKey, o, true); ret.push_back(Pair("scriptPubKey", o)); ret.push_back(Pair("version", coins.nVersion)); ret.push_back(Pair("coinbase", coins.fCoinBase)); return ret; } UniValue verifychain(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "verifychain ( checklevel numblocks )\n" "\nVerifies blockchain database.\n" "\nArguments:\n" "1. checklevel (numeric, optional, 0-4, default=3) How thorough the block verification is.\n" "2. numblocks (numeric, optional, default=288, 0=all) The number of blocks to check.\n" "\nResult:\n" "true|false (boolean) Verified or not\n" "\nExamples:\n" + HelpExampleCli("verifychain", "") + HelpExampleRpc("verifychain", "")); LOCK(cs_main); int nCheckLevel = GetArg("-checklevel", 3); int nCheckDepth = GetArg("-checkblocks", 288); if (params.size() > 0) nCheckLevel = params[0].get_int(); if (params.size() > 1) nCheckDepth = params[1].get_int(); return CVerifyDB().VerifyDB(pcoinsTip, nCheckLevel, nCheckDepth); } UniValue getblockchaininfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getblockchaininfo\n" "Returns an object containing various state info regarding block chain processing.\n" "\nResult:\n" "{\n" " \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n" " \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n" " \"headers\": xxxxxx, (numeric) the current number of headers we have validated\n" " \"bestblockhash\": \"...\", (string) the hash of the currently best block\n" " \"difficulty\": xxxxxx, (numeric) the current difficulty\n" " \"verificationprogress\": xxxx, (numeric) estimate of verification progress [0..1]\n" " \"chainwork\": \"xxxx\" (string) total amount of work in active chain, in hexadecimal\n" "}\n" "\nExamples:\n" + HelpExampleCli("getblockchaininfo", "") + HelpExampleRpc("getblockchaininfo", "")); LOCK(cs_main); UniValue obj(UniValue::VOBJ); obj.push_back(Pair("chain", Params().NetworkIDString())); obj.push_back(Pair("blocks", (int)chainActive.Height())); obj.push_back(Pair("headers", pindexBestHeader ? pindexBestHeader->nHeight : -1)); obj.push_back(Pair("bestblockhash", chainActive.Tip()->GetBlockHash().GetHex())); obj.push_back(Pair("difficulty", (double)GetDifficulty())); obj.push_back(Pair("verificationprogress", Checkpoints::GuessVerificationProgress(chainActive.Tip()))); obj.push_back(Pair("chainwork", chainActive.Tip()->nChainWork.GetHex())); return obj; } /** Comparison function for sorting the getchaintips heads. */ struct CompareBlocksByHeight { bool operator()(const CBlockIndex* a, const CBlockIndex* b) const { /* Make sure that unequal blocks with the same height do not compare equal. Use the pointers themselves to make a distinction. */ if (a->nHeight != b->nHeight) return (a->nHeight > b->nHeight); return a < b; } }; UniValue getchaintips(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getchaintips\n" "Return information about all known tips in the block tree," " including the main chain as well as orphaned branches.\n" "\nResult:\n" "[\n" " {\n" " \"height\": xxxx, (numeric) height of the chain tip\n" " \"hash\": \"xxxx\", (string) block hash of the tip\n" " \"branchlen\": 0 (numeric) zero for main chain\n" " \"status\": \"active\" (string) \"active\" for the main chain\n" " },\n" " {\n" " \"height\": xxxx,\n" " \"hash\": \"xxxx\",\n" " \"branchlen\": 1 (numeric) length of branch connecting the tip to the main chain\n" " \"status\": \"xxxx\" (string) status of the chain (active, valid-fork, valid-headers, headers-only, invalid)\n" " }\n" "]\n" "Possible values for status:\n" "1. \"invalid\" This branch contains at least one invalid block\n" "2. \"headers-only\" Not all blocks for this branch are available, but the headers are valid\n" "3. \"valid-headers\" All blocks are available for this branch, but they were never fully validated\n" "4. \"valid-fork\" This branch is not part of the active chain, but is fully validated\n" "5. \"active\" This is the tip of the active main chain, which is certainly valid\n" "\nExamples:\n" + HelpExampleCli("getchaintips", "") + HelpExampleRpc("getchaintips", "")); LOCK(cs_main); /* Build up a list of chain tips. We start with the list of all known blocks, and successively remove blocks that appear as pprev of another block. */ std::set<const CBlockIndex*, CompareBlocksByHeight> setTips; BOOST_FOREACH (const PAIRTYPE(const uint256, CBlockIndex*) & item, mapBlockIndex) setTips.insert(item.second); BOOST_FOREACH (const PAIRTYPE(const uint256, CBlockIndex*) & item, mapBlockIndex) { const CBlockIndex* pprev = item.second->pprev; if (pprev) setTips.erase(pprev); } // Always report the currently active tip. setTips.insert(chainActive.Tip()); /* Construct the output array. */ UniValue res(UniValue::VARR); BOOST_FOREACH (const CBlockIndex* block, setTips) { UniValue obj(UniValue::VOBJ); obj.push_back(Pair("height", block->nHeight)); obj.push_back(Pair("hash", block->phashBlock->GetHex())); const int branchLen = block->nHeight - chainActive.FindFork(block)->nHeight; obj.push_back(Pair("branchlen", branchLen)); string status; if (chainActive.Contains(block)) { // This block is part of the currently active chain. status = "active"; } else if (block->nStatus & BLOCK_FAILED_MASK) { // This block or one of its ancestors is invalid. status = "invalid"; } else if (block->nChainTx == 0) { // This block cannot be connected because full block data for it or one of its parents is missing. status = "headers-only"; } else if (block->IsValid(BLOCK_VALID_SCRIPTS)) { // This block is fully validated, but no longer part of the active chain. It was probably the active block once, but was reorganized. status = "valid-fork"; } else if (block->IsValid(BLOCK_VALID_TREE)) { // The headers for this block are valid, but it has not been validated. It was probably never part of the most-work chain. status = "valid-headers"; } else { // No clue. status = "unknown"; } obj.push_back(Pair("status", status)); res.push_back(obj); } return res; } UniValue getfeeinfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getfeeinfo blocks\n" "\nReturns details of transaction fees over the last n blocks.\n" "\nArguments:\n" "1. blocks (int, required) the number of blocks to get transaction data from\n" "\nResult:\n" "{\n" " \"txcount\": xxxxx (numeric) Current tx count\n" " \"txbytes\": xxxxx (numeric) Sum of all tx sizes\n" " \"ttlfee\": xxxxx (numeric) Sum of all fees\n" " \"feeperkb\": xxxxx (numeric) Average fee per kb over the block range\n" " \"rec_highpriorityfee_perkb\": xxxxx (numeric) Recommended fee per kb to use for a high priority tx\n" "}\n" "\nExamples:\n" + HelpExampleCli("getfeeinfo", "5") + HelpExampleRpc("getfeeinfo", "5")); LOCK(cs_main); int nBlocks = params[0].get_int(); int nBestHeight = chainActive.Height(); int nStartHeight = nBestHeight - nBlocks; if (nBlocks < 0 || nStartHeight <= 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "invalid start height"); CAmount nFees = 0; int64_t nBytes = 0; int64_t nTotal = 0; for (int i = nStartHeight; i <= nBestHeight; i++) { CBlockIndex* pindex = chainActive[i]; CBlock block; if (!ReadBlockFromDisk(block, pindex)) throw JSONRPCError(RPC_DATABASE_ERROR, "failed to read block from disk"); CAmount nValueIn = 0; CAmount nValueOut = 0; for (const CTransaction& tx : block.vtx) { if (tx.IsCoinBase() || tx.IsCoinStake()) continue; for (unsigned int j = 0; j < tx.vin.size(); j++) { COutPoint prevout = tx.vin[j].prevout; CTransaction txPrev; uint256 hashBlock; if(!GetTransaction(prevout.hash, txPrev, hashBlock, true)) throw JSONRPCError(RPC_DATABASE_ERROR, "failed to read tx from disk"); nValueIn += txPrev.vout[prevout.n].nValue; } for (unsigned int j = 0; j < tx.vout.size(); j++) { nValueOut += tx.vout[j].nValue; } nFees += nValueIn - nValueOut; nBytes += tx.GetSerializeSize(SER_NETWORK, CLIENT_VERSION); nTotal++; } pindex = chainActive.Next(pindex); if (!pindex) break; } UniValue ret(UniValue::VOBJ); CFeeRate nFeeRate = CFeeRate(nFees, nBytes); ret.push_back(Pair("txcount", (int64_t)nTotal)); ret.push_back(Pair("txbytes", (int64_t)nBytes)); ret.push_back(Pair("ttlfee", FormatMoney(nFees))); ret.push_back(Pair("feeperkb", FormatMoney(nFeeRate.GetFeePerK()))); ret.push_back(Pair("rec_highpriorityfee_perkb", FormatMoney(nFeeRate.GetFeePerK() + 1000))); return ret; } UniValue mempoolInfoToJSON() { UniValue ret(UniValue::VOBJ); ret.push_back(Pair("size", (int64_t) mempool.size())); ret.push_back(Pair("bytes", (int64_t) mempool.GetTotalTxSize())); //ret.push_back(Pair("usage", (int64_t) mempool.DynamicMemoryUsage())); return ret; } UniValue getmempoolinfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getmempoolinfo\n" "\nReturns details on the active state of the TX memory pool.\n" "\nResult:\n" "{\n" " \"size\": xxxxx (numeric) Current tx count\n" " \"bytes\": xxxxx (numeric) Sum of all tx sizes\n" "}\n" "\nExamples:\n" + HelpExampleCli("getmempoolinfo", "") + HelpExampleRpc("getmempoolinfo", "")); return mempoolInfoToJSON(); } UniValue invalidateblock(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "invalidateblock \"hash\"\n" "\nPermanently marks a block as invalid, as if it violated a consensus rule.\n" "\nArguments:\n" "1. hash (string, required) the hash of the block to mark as invalid\n" "\nExamples:\n" + HelpExampleCli("invalidateblock", "\"blockhash\"") + HelpExampleRpc("invalidateblock", "\"blockhash\"")); uint256 hash(ParseHashV(params[0].get_str(), "blockhash")); CValidationState state; { LOCK(cs_main); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlockIndex* pblockindex = mapBlockIndex[hash]; InvalidateBlock(state, pblockindex); } if (state.IsValid()) { ActivateBestChain(state); } if (!state.IsValid()) { throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason()); } return NullUniValue; } UniValue reconsiderblock(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "reconsiderblock \"hash\"\n" "\nRemoves invalidity status of a block and its descendants, reconsider them for activation.\n" "This can be used to undo the effects of invalidateblock.\n" "\nArguments:\n" "1. hash (string, required) the hash of the block to reconsider\n" "\nExamples:\n" + HelpExampleCli("reconsiderblock", "\"blockhash\"") + HelpExampleRpc("reconsiderblock", "\"blockhash\"")); uint256 hash(ParseHashV(params[0].get_str(), "blockhash")); CValidationState state; { LOCK(cs_main); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlockIndex* pblockindex = mapBlockIndex[hash]; ReconsiderBlock(state, pblockindex); } if (state.IsValid()) { ActivateBestChain(state); } if (!state.IsValid()) { throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason()); } return NullUniValue; }
[ "123chain.team@gmail.com" ]
123chain.team@gmail.com
f8474078f305094f8bc3346045fe8a8b1fd9dbdb
9d374d182bfb7990ccc6fdffb05f824abc08300d
/DFS/removeLeavesBinaryTree.cpp
c6c7ddb2e7c7a332b117868aa56f3a9a525d1b8f
[ "MIT" ]
permissive
jkerkela/best-algorithm-collection
cf96e7d790fa5ce82c4411b7ea60940ee5adbaef
6b22536a9f8ebdf3ae134031d41becf30066a5ef
refs/heads/master
2023-08-29T18:30:28.692332
2021-11-14T10:23:56
2021-11-14T10:23:56
246,857,441
0
0
null
null
null
null
UTF-8
C++
false
false
1,179
cpp
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void deleteLeavesFromTreeRecursivelyPostOrder(TreeNode* parentNode, TreeNode* node, bool isLeftLeave, int target) { if(node == NULL) return; deleteLeavesFromTreeRecursivelyPostOrder(node, node->left, true, target); deleteLeavesFromTreeRecursivelyPostOrder(node, node->right, false, target); if (node->val == target && node->left == NULL && node->right == NULL && parentNode != node) { isLeftLeave ? parentNode->left = NULL : parentNode->right = NULL; delete (node); } } bool isRootNodeRemovable(TreeNode* root, int target) { return (!root->left && !root->right && root->val == target); } TreeNode* removeLeafNodes(TreeNode* root, int target) { deleteLeavesFromTreeRecursivelyPostOrder(root, root, false, target); if(isRootNodeRemovable(root, target)){ return NULL; } return root; } };
[ "jonikerkela@hotmail.com" ]
jonikerkela@hotmail.com
fd8ba1248793b71c9bef40a3ce4c149241f91039
e6dfe602a69230fb4f2548afefd9faf85848d1d1
/0027.cpp
2122c4d645de333d3d972d14bd430d786b604465
[]
no_license
chenjiahui0131/LeetCode_cpp
0d6cb758c638bd2dd8b592a932529e39841e08f7
aca79506326f0e1c2088f90437e7a17367e62879
refs/heads/master
2021-01-04T19:27:17.957312
2020-04-02T14:16:48
2020-04-02T14:16:48
240,728,567
0
0
null
null
null
null
UTF-8
C++
false
false
543
cpp
#include<iostream> #include<vector> using namespace std; class Solution { public: int removeElement(vector<int>& nums, int val) { int idx = -1; for (int i = 0; i < nums.size(); i++) { if (nums[i] != val) { idx++; nums[idx] = nums[i]; } } return idx + 1; } }; int main() { vector<int> nums = {0,1,2,2,3,0,4,2}; Solution s; int length = s.removeElement(nums, 2); for (int i = 0; i < length; i++) cout << nums[i] << endl; }
[ "coffee@email.com" ]
coffee@email.com
f7d4b1cd1f2f50808caa626693e2ff3a898fbbee
9d579a0ddba661ff9e3e29ec11fde5360bc433f1
/Juego Dados/Jugador.h
c0237ffb6302f04a792641f59d7c577c4c787938
[]
no_license
Agusdel/Programacion2
0eba3e3213b6fb28e1f9239af3ce16c01565bbfd
d1393fb8fc61cf23d4baa69a62f72b568a863f67
refs/heads/master
2021-01-17T18:17:10.621465
2016-11-21T04:04:32
2016-11-21T04:04:32
69,419,363
0
0
null
null
null
null
UTF-8
C++
false
false
443
h
#ifndef JUGADOR_H_INCLUDED #define JUGADOR_H_INCLUDED #include "Dado.h" #include "TablaDeResultados.h" class Jugador{ private: Dado* dadoAzul; Dado* dadoVerde; Dado* dadoRojo; public: Jugador(int cantCarasAzul = 6, int cantCarasVerde = 8, int cantCarasRojo = 12); ~Jugador(); TablaDeResultados LanzarDados(); int getCarasAzul(); int getCarasVerde(); int getCarasRojo(); }; #endif // JUGADOR_H_INCLUDED
[ "agusdel_94@hotmail.com" ]
agusdel_94@hotmail.com
79cf562e9c03a4d758dc342b509b48998be8c660
792e697ba0f9c11ef10b7de81edb1161a5580cfb
/tools/clang/test/CXX/drs/dr17xx.cpp
c8648908ebda9882785d1484d273006bee092ef5
[ "Apache-2.0", "LLVM-exception", "NCSA" ]
permissive
opencor/llvmclang
9eb76cb6529b6a3aab2e6cd266ef9751b644f753
63b45a7928f2a8ff823db51648102ea4822b74a6
refs/heads/master
2023-08-26T04:52:56.472505
2022-11-02T04:35:46
2022-11-03T03:55:06
115,094,625
0
1
Apache-2.0
2021-08-12T22:29:21
2017-12-22T08:29:14
LLVM
UTF-8
C++
false
false
3,720
cpp
// RUN: %clang_cc1 -std=c++98 %s -verify -fexceptions -fcxx-exceptions -pedantic-errors // RUN: %clang_cc1 -std=c++11 %s -verify -fexceptions -fcxx-exceptions -pedantic-errors // RUN: %clang_cc1 -std=c++14 %s -verify -fexceptions -fcxx-exceptions -pedantic-errors // RUN: %clang_cc1 -std=c++1z %s -verify -fexceptions -fcxx-exceptions -pedantic-errors namespace dr1715 { // dr1715: 3.9 #if __cplusplus >= 201103L struct B { template<class T> B(T, typename T::Q); }; class S { using Q = int; template<class T> friend B::B(T, typename T::Q); }; struct D : B { using B::B; }; struct E : B { // expected-note 2{{candidate}} template<class T> E(T t, typename T::Q q) : B(t, q) {} // expected-note {{'Q' is a private member}} }; B b(S(), 1); D d(S(), 2); E e(S(), 3); // expected-error {{no match}} #endif } namespace dr1736 { // dr1736: 3.9 #if __cplusplus >= 201103L struct S { template <class T> S(T t) { struct L : S { using S::S; }; typename T::type value; // expected-error {{no member}} L l(value); // expected-note {{instantiation of}} } }; struct Q { typedef int type; } q; S s(q); // expected-note {{instantiation of}} #endif } namespace dr1753 { // dr1753: 11 typedef int T; struct A { typedef int T; }; namespace B { typedef int T; } void f(T n) { n.~T(); n.T::~T(); n.dr1753::~T(); // expected-error {{'dr1753' does not refer to a type name in pseudo-destructor}} n.dr1753::T::~T(); n.A::~T(); // expected-error {{the type of object expression ('dr1753::T' (aka 'int')) does not match the type being destroyed ('dr1753::A') in pseudo-destructor expression}} n.A::T::~T(); n.B::~T(); // expected-error {{'B' does not refer to a type name in pseudo-destructor expression}} n.B::T::~T(); #if __cplusplus >= 201103L n.decltype(n)::~T(); // expected-error {{not a class, namespace, or enumeration}} n.T::~decltype(n)(); // expected-error {{expected a class name after '~'}} n.~decltype(n)(); // OK #endif } } namespace dr1756 { // dr1756: 3.7 #if __cplusplus >= 201103L // Direct-list-initialization of a non-class object int a{0}; struct X { operator int(); } x; int b{x}; #endif } namespace dr1758 { // dr1758: 3.7 #if __cplusplus >= 201103L // Explicit conversion in copy/move list initialization struct X { X(); }; struct Y { explicit operator X(); } y; X x{y}; struct A { A() {} A(const A &) {} }; struct B { operator A() { return A(); } } b; A a{b}; #endif } namespace dr1722 { // dr1722: 9 #if __cplusplus >= 201103L void f() { const auto lambda = [](int x) { return x + 1; }; // Without the DR applied, this static_assert would fail. static_assert( noexcept((int (*)(int))(lambda)), "Lambda-to-function-pointer conversion is expected to be noexcept"); } #endif } // namespace dr1722 namespace dr1778 { // dr1778: 9 // Superseded by P1286R2. #if __cplusplus >= 201103L struct A { A() noexcept(true) = default; }; struct B { B() noexcept(false) = default; }; static_assert(noexcept(A()), ""); static_assert(!noexcept(B()), ""); struct C { A a; C() noexcept(false) = default; }; struct D { B b; D() noexcept(true) = default; }; static_assert(!noexcept(C()), ""); static_assert(noexcept(D()), ""); #endif } namespace dr1762 { // dr1762: 14 #if __cplusplus >= 201103L float operator ""_E(const char *); // expected-error@+2 {{invalid suffix on literal; C++11 requires a space between literal and identifier}} // expected-warning@+1 {{user-defined literal suffixes not starting with '_' are reserved; no literal will invoke this operator}} float operator ""E(const char *); #endif }
[ "agarny@hellix.com" ]
agarny@hellix.com
31c1981515ef889205eaf9e2eb831bdbc19b9aba
72527c36295e67ff9092a03a101ade79fa23f532
/non-linear-ds/AVLdeletion.cpp
c1eaa1dc57dadf93d57a2d07615f2dc71b2b0ddd
[]
no_license
Divij-berry14/data-structures-and-algorithms
66e5e6d1e3c559e872ac4c8b2db06483288b58f7
4b37d400dade439f15db662685acbea46cb77305
refs/heads/master
2020-06-19T05:49:46.418126
2019-06-19T01:18:45
2019-06-19T01:18:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,622
cpp
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: main.cpp * Author: Priyanka * * Created on June 10, 2019, 8:14 PM */ // C++ program to insert a node in AVL tree #include<iostream> using namespace std; // An AVL tree node class Node { public: int key; Node *left; Node *right; int height; }; int height(Node *root) { if (root == NULL) return 0; return root->height; } int max(int a, int b) { return (a > b) ? a : b; } Node* getNewNode(int x) { Node* newNode = new Node(); newNode->key = x; newNode->height = 1; newNode->left = NULL; newNode->right = NULL; return newNode; } int getBalance(Node *root) { if (root == NULL) return 0; return (height(root->left) - height(root->right)); } Node* rightRotate(Node *y) { Node *x = y->left; Node *t = x->right; //Perform rotation x->right = y; y->left = t; //Update heights y->height = max(height(y->left), height(y->right)) + 1; x->height = max(height(x->left), height(x->right)) + 1; return x; } Node* leftRotate(Node *x) { Node *y = x->right; Node *t = y->left; //ROtate y->left = x; x->right = t; //Update heights x->height = max(height(x->left), height(x->right)) + 1; y->height = max(height(y->left), height(y->right)) + 1; return y; } Node* insert(Node* head, int a) { if (head == NULL) return (getNewNode(a)); else if (a < head->key) head->left = insert(head->left, a); else if (a > head->key) head->right = insert(head->right, a); //equal values not allowed in BST else return head; //2. Updating the height of the ancestor head->height = max((height(head->left)), (height(head->right))) + 1; //3. Get the balance factor int balance = getBalance(head); //4. Check for any unbalances //Left left case if (balance > 1 && a < head->left->key) { //Right rotate; return rightRotate(head); } //right right case else if (balance<-1 && a > head->right->key) { //Left rotate return leftRotate(head); } //left right case else if (balance > 1 && a > head->left->key) { //Left right rotate head->left = leftRotate(head->left); return rightRotate(head); } //right left case else if (balance <-1 && a < head->right->key) { //Right left rotate head->right = rightRotate(head->right); return leftRotate(head); } //Return the unchanged node return head; } int findMin(Node *root) { Node *temp=root; while(temp->left!=NULL) { temp=temp->left; } return temp->key; } Node* deleteNode(Node *root,int x) { // STep 1. Insert normally as in BST if(root==NULL) return NULL; else if(root->key < x) { root->right = deleteNode(root->right,x); } else if(root->key >x) { root->left = deleteNode(root->left,x); } else { if(root->left==NULL && root->right == NULL) { delete root; root=NULL; } else if(root->left==NULL) { Node *temp=root; root=root->right; delete temp; } else if(root->right==NULL) { Node *temp=root; root=root->left; delete temp; } else{ int min=findMin(root->right); root->key=min; root->right=deleteNode(root->right,min); } } // If the tree had only one node // then return if (root == NULL) return root; root->height = max((height(root->left)), (height(root->right))) + 1; //3. Get the balance factor int balance = getBalance(root); //4. Check for any unbalances //Left left case // Left Left Case if (balance > 1 && getBalance(root->left) >= 0) return rightRotate(root); // Left Right Case if (balance > 1 && getBalance(root->left) < 0) { root->left = leftRotate(root->left); return rightRotate(root); } // Right Right Case if (balance < -1 && getBalance(root->right) <= 0) return leftRotate(root); // Right Left Case if (balance < -1 && getBalance(root->right) > 0) { root->right = rightRotate(root->right); return leftRotate(root); } return root; } void preOrder(Node *root) { if (root != NULL) { cout << root->key << " "; preOrder(root->left); preOrder(root->right); } } int main() { Node *root = NULL; /* Constructing tree given in the above figure */ root = insert(root, 10); root = insert(root, 20); root = insert(root, 30); root = insert(root, 40); root = insert(root, 50); root = insert(root, 25); /* The constructed AVL Tree would be 30 / \ 20 40 / \ \ 10 25 50 */ cout << "preorder traversal of the " "constructed AVL tree is \n"; preOrder(root); root = deleteNode(root, 10); /* The AVL Tree after deletion of 10 1 / \ 0 9 / / \ -1 5 11 / \ 2 6 */ cout << "\nPreorder traversal after" << " deletion of 10 \n"; preOrder(root); return 0; }
[ "500060668@stu.upes.ac.in" ]
500060668@stu.upes.ac.in
3ec88323905a8f206541cc8a3936763e80e03678
05d8a212d29c310157dbf6b3fbb1379055468309
/chrome/browser/ui/views/tabs/tab_icon.cc
2916aaaeb06f0da288e03dea73ff5c5e0b748e71
[ "BSD-3-Clause" ]
permissive
zjj6029/chromium
1e9743a8a4698831d0b9cf094c67216e7e4df27a
80b54fd5b182936eab1fc1ac5c247857e66d5cbe
refs/heads/master
2023-03-18T13:33:54.559462
2019-08-21T15:54:01
2019-08-21T15:54:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,266
cc
// Copyright 2017 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/ui/views/tabs/tab_icon.h" #include "base/metrics/histogram_macros.h" #include "base/time/default_tick_clock.h" #include "base/timer/elapsed_timer.h" #include "base/trace_event/trace_event.h" #include "cc/paint/paint_flags.h" #include "chrome/browser/favicon/favicon_utils.h" #include "chrome/browser/themes/theme_properties.h" #include "chrome/browser/ui/layout_constants.h" #include "chrome/browser/ui/views/tabs/tab_renderer_data.h" #include "chrome/common/webui_url_constants.h" #include "components/grit/components_scaled_resources.h" #include "content/public/common/url_constants.h" #include "ui/base/resource/resource_bundle.h" #include "ui/base/theme_provider.h" #include "ui/gfx/animation/animation_delegate.h" #include "ui/gfx/animation/linear_animation.h" #include "ui/gfx/animation/tween.h" #include "ui/gfx/canvas.h" #include "ui/gfx/color_palette.h" #include "ui/gfx/favicon_size.h" #include "ui/gfx/image/image_skia_operations.h" #include "ui/gfx/scoped_canvas.h" #include "ui/native_theme/native_theme.h" #include "ui/resources/grit/ui_resources.h" #include "ui/views/border.h" #include "url/gurl.h" namespace { constexpr int kAttentionIndicatorRadius = 3; constexpr int kLoadingAnimationStrokeWidthDp = 2; // Returns whether the favicon for the given URL should be colored according to // the browser theme. bool ShouldThemifyFaviconForUrl(const GURL& url) { return url.SchemeIs(content::kChromeUIScheme) && url.host_piece() != chrome::kChromeUIHelpHost && url.host_piece() != chrome::kChromeUIUberHost && url.host_piece() != chrome::kChromeUIAppLauncherPageHost; } bool NetworkStateIsAnimated(TabNetworkState network_state) { return network_state != TabNetworkState::kNone && network_state != TabNetworkState::kError; } } // namespace // Helper class that manages the favicon crash animation. class TabIcon::CrashAnimation : public gfx::LinearAnimation, public gfx::AnimationDelegate { public: explicit CrashAnimation(TabIcon* target) : gfx::LinearAnimation(base::TimeDelta::FromSeconds(1), 25, this), target_(target) {} ~CrashAnimation() override = default; // gfx::Animation overrides: void AnimateToState(double state) override { if (state < .5) { // Animate the normal icon down. target_->hiding_fraction_ = state * 2.0; } else { // Animate the crashed icon up. target_->should_display_crashed_favicon_ = true; target_->hiding_fraction_ = 1.0 - (state - 0.5) * 2.0; } target_->SchedulePaint(); } private: TabIcon* target_; DISALLOW_COPY_AND_ASSIGN(CrashAnimation); }; TabIcon::TabIcon() : AnimationDelegateViews(this), clock_(base::DefaultTickClock::GetInstance()), favicon_fade_in_animation_(base::TimeDelta::FromMilliseconds(250), gfx::LinearAnimation::kDefaultFrameRate, this) { set_can_process_events_within_subtree(false); // The minimum size to avoid clipping the attention indicator. const int preferred_width = gfx::kFaviconSize + kAttentionIndicatorRadius + GetInsets().width(); SetPreferredSize(gfx::Size(preferred_width, preferred_width)); // Initial state (before any data) should not be animating. DCHECK(!ShowingLoadingAnimation()); } TabIcon::~TabIcon() = default; void TabIcon::SetData(const TabRendererData& data) { const bool was_showing_load = ShowingLoadingAnimation(); inhibit_loading_animation_ = data.should_hide_throbber; SetIcon(data.visible_url, data.favicon); SetNetworkState(data.network_state); SetIsCrashed(data.IsCrashed()); has_tab_renderer_data_ = true; const bool showing_load = ShowingLoadingAnimation(); RefreshLayer(); if (was_showing_load && !showing_load) { // Loading animation transitioning from on to off. loading_animation_start_time_ = base::TimeTicks(); waiting_state_ = gfx::ThrobberWaitingState(); SchedulePaint(); } else if (!was_showing_load && showing_load) { // Loading animation transitioning from off to on. The animation painting // function will lazily initialize the data. SchedulePaint(); } } void TabIcon::SetAttention(AttentionType type, bool enabled) { int previous_attention_type = attention_types_; if (enabled) attention_types_ |= static_cast<int>(type); else attention_types_ &= ~static_cast<int>(type); if (attention_types_ != previous_attention_type) SchedulePaint(); } bool TabIcon::ShowingLoadingAnimation() const { if (inhibit_loading_animation_) return false; return NetworkStateIsAnimated(network_state_); } bool TabIcon::ShowingAttentionIndicator() const { return attention_types_ > 0; } void TabIcon::SetCanPaintToLayer(bool can_paint_to_layer) { if (can_paint_to_layer == can_paint_to_layer_) return; can_paint_to_layer_ = can_paint_to_layer; RefreshLayer(); } void TabIcon::StepLoadingAnimation(const base::TimeDelta& elapsed_time) { // Only update elapsed time in the kWaiting state. This is later used as a // starting point for PaintThrobberSpinningAfterWaiting(). if (network_state_ == TabNetworkState::kWaiting) waiting_state_.elapsed_time = elapsed_time; if (ShowingLoadingAnimation()) SchedulePaint(); } void TabIcon::OnPaint(gfx::Canvas* canvas) { // This is used to log to UMA. NO EARLY RETURNS! base::ElapsedTimer paint_timer; // Compute the bounds adjusted for the hiding fraction. gfx::Rect contents_bounds = GetContentsBounds(); if (contents_bounds.IsEmpty()) return; gfx::Rect icon_bounds( GetMirroredXWithWidthInView(contents_bounds.x(), gfx::kFaviconSize), contents_bounds.y() + static_cast<int>(contents_bounds.height() * hiding_fraction_), std::min(gfx::kFaviconSize, contents_bounds.width()), std::min(gfx::kFaviconSize, contents_bounds.height())); // Don't paint the attention indicator during the loading animation. if (!ShowingLoadingAnimation() && ShowingAttentionIndicator() && !should_display_crashed_favicon_) { PaintAttentionIndicatorAndIcon(canvas, GetIconToPaint(), icon_bounds); } else { MaybePaintFavicon(canvas, GetIconToPaint(), icon_bounds); } if (ShowingLoadingAnimation()) PaintLoadingAnimation(canvas, icon_bounds); UMA_HISTOGRAM_CUSTOM_MICROSECONDS_TIMES( "TabStrip.Tab.Icon.PaintDuration", paint_timer.Elapsed(), base::TimeDelta::FromMicroseconds(1), base::TimeDelta::FromMicroseconds(10000), 50); } void TabIcon::OnThemeChanged() { crashed_icon_ = gfx::ImageSkia(); // Force recomputation if crashed. if (!themed_favicon_.isNull()) themed_favicon_ = ThemeImage(favicon_); } void TabIcon::AnimationProgressed(const gfx::Animation* animation) { SchedulePaint(); } void TabIcon::AnimationEnded(const gfx::Animation* animation) { RefreshLayer(); SchedulePaint(); } void TabIcon::PaintAttentionIndicatorAndIcon(gfx::Canvas* canvas, const gfx::ImageSkia& icon, const gfx::Rect& bounds) { TRACE_EVENT0("views", "TabIcon::PaintAttentionIndicatorAndIcon"); gfx::Point circle_center( bounds.x() + (base::i18n::IsRTL() ? 0 : gfx::kFaviconSize), bounds.y() + gfx::kFaviconSize); // The attention indicator consists of two parts: // . a clear (totally transparent) part over the bottom right (or left in rtl) // of the favicon. This is done by drawing the favicon to a layer, then // drawing the clear part on top of the favicon. // . a circle in the bottom right (or left in rtl) of the favicon. if (!icon.isNull()) { canvas->SaveLayerAlpha(0xff); canvas->DrawImageInt(icon, 0, 0, bounds.width(), bounds.height(), bounds.x(), bounds.y(), bounds.width(), bounds.height(), false); cc::PaintFlags clear_flags; clear_flags.setAntiAlias(true); clear_flags.setBlendMode(SkBlendMode::kClear); const float kIndicatorCropRadius = 4.5f; canvas->DrawCircle(circle_center, kIndicatorCropRadius, clear_flags); canvas->Restore(); } // Draws the actual attention indicator. cc::PaintFlags indicator_flags; indicator_flags.setColor(GetNativeTheme()->GetSystemColor( ui::NativeTheme::kColorId_ProminentButtonColor)); indicator_flags.setAntiAlias(true); canvas->DrawCircle(circle_center, kAttentionIndicatorRadius, indicator_flags); } void TabIcon::PaintLoadingAnimation(gfx::Canvas* canvas, gfx::Rect bounds) { TRACE_EVENT0("views", "TabIcon::PaintLoadingAnimation"); const ui::ThemeProvider* tp = GetThemeProvider(); if (network_state_ == TabNetworkState::kWaiting) { gfx::PaintThrobberWaiting( canvas, bounds, tp->GetColor(ThemeProperties::COLOR_TAB_THROBBER_WAITING), waiting_state_.elapsed_time, kLoadingAnimationStrokeWidthDp); } else { const base::TimeTicks current_time = clock_->NowTicks(); if (loading_animation_start_time_.is_null()) loading_animation_start_time_ = current_time; waiting_state_.color = tp->GetColor(ThemeProperties::COLOR_TAB_THROBBER_WAITING); gfx::PaintThrobberSpinningAfterWaiting( canvas, bounds, tp->GetColor(ThemeProperties::COLOR_TAB_THROBBER_SPINNING), current_time - loading_animation_start_time_, &waiting_state_, kLoadingAnimationStrokeWidthDp); } } const gfx::ImageSkia& TabIcon::GetIconToPaint() { if (should_display_crashed_favicon_) { if (crashed_icon_.isNull()) { // Lazily create a themed sad tab icon. ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); crashed_icon_ = ThemeImage(*rb.GetImageSkiaNamed(IDR_CRASH_SAD_FAVICON)); } return crashed_icon_; } return themed_favicon_.isNull() ? favicon_ : themed_favicon_; } void TabIcon::MaybePaintFavicon(gfx::Canvas* canvas, const gfx::ImageSkia& icon, const gfx::Rect& bounds) { TRACE_EVENT0("views", "TabIcon::MaybePaintFavicon"); if (icon.isNull()) return; if (ShowingLoadingAnimation()) { // Never paint the favicon during the waiting animation. if (network_state_ == TabNetworkState::kWaiting) return; // Don't paint the default favicon while we're still loading. if (!HasNonDefaultFavicon()) return; } std::unique_ptr<gfx::ScopedCanvas> scoped_canvas; bool use_scale_filter = false; if (ShowingLoadingAnimation() || favicon_fade_in_animation_.is_animating()) { scoped_canvas = std::make_unique<gfx::ScopedCanvas>(canvas); use_scale_filter = true; // The favicon is initially inset with the width of the loading-animation // stroke + an additional dp to create some visual separation. const float kInitialFaviconInsetDp = 1 + kLoadingAnimationStrokeWidthDp; const float kInitialFaviconDiameterDp = gfx::kFaviconSize - 2 * kInitialFaviconInsetDp; // This a full outset circle of the favicon square. The animation ends with // the entire favicon shown. const float kFinalFaviconDiameterDp = sqrt(2) * gfx::kFaviconSize; SkScalar diameter = kInitialFaviconDiameterDp; if (favicon_fade_in_animation_.is_animating()) { diameter += gfx::Tween::CalculateValue( gfx::Tween::EASE_OUT, favicon_fade_in_animation_.GetCurrentValue()) * (kFinalFaviconDiameterDp - kInitialFaviconDiameterDp); } SkPath path; gfx::PointF center = gfx::RectF(bounds).CenterPoint(); path.addCircle(center.x(), center.y(), diameter / 2); canvas->ClipPath(path, true); // This scales and offsets painting so that the drawn favicon is downscaled // to fit in the cropping area. const float offset = (gfx::kFaviconSize - std::min(diameter, SkFloatToScalar(gfx::kFaviconSize))) / 2; const float scale = std::min(diameter, SkFloatToScalar(gfx::kFaviconSize)) / gfx::kFaviconSize; canvas->Translate(gfx::Vector2d(offset, offset)); canvas->Scale(scale, scale); } canvas->DrawImageInt(icon, 0, 0, bounds.width(), bounds.height(), bounds.x(), bounds.y(), bounds.width(), bounds.height(), use_scale_filter); } bool TabIcon::HasNonDefaultFavicon() const { return !favicon_.isNull() && !favicon_.BackedBySameObjectAs( favicon::GetDefaultFavicon().AsImageSkia()); } void TabIcon::SetIcon(const GURL& url, const gfx::ImageSkia& icon) { // Detect when updating to the same icon. This avoids re-theming and // re-painting. if (favicon_.BackedBySameObjectAs(icon)) return; favicon_ = icon; if (!HasNonDefaultFavicon() || ShouldThemifyFaviconForUrl(url)) { themed_favicon_ = ThemeImage(icon); } else { themed_favicon_ = gfx::ImageSkia(); } SchedulePaint(); } void TabIcon::SetNetworkState(TabNetworkState network_state) { const bool was_animated = NetworkStateIsAnimated(network_state_); network_state_ = network_state; const bool is_animated = NetworkStateIsAnimated(network_state_); if (was_animated != is_animated) { if (was_animated && HasNonDefaultFavicon()) { favicon_fade_in_animation_.Start(); } else { favicon_fade_in_animation_.Stop(); favicon_fade_in_animation_.SetCurrentValue(0.0); } } } void TabIcon::SetIsCrashed(bool is_crashed) { if (is_crashed == is_crashed_) return; is_crashed_ = is_crashed; if (!is_crashed_) { // Transitioned from crashed to non-crashed. if (crash_animation_) crash_animation_->Stop(); should_display_crashed_favicon_ = false; hiding_fraction_ = 0.0; } else { // Transitioned from non-crashed to crashed. if (!has_tab_renderer_data_) { // This is the initial SetData(), so show the crashed icon directly // without animating. should_display_crashed_favicon_ = true; } else { if (!crash_animation_) crash_animation_ = std::make_unique<CrashAnimation>(this); if (!crash_animation_->is_animating()) crash_animation_->Start(); } } SchedulePaint(); } void TabIcon::RefreshLayer() { // Since the loading animation can run for a long time, paint animation to a // separate layer when possible to reduce repaint overhead. bool should_paint_to_layer = can_paint_to_layer_ && (ShowingLoadingAnimation() || favicon_fade_in_animation_.is_animating()); if (should_paint_to_layer == !!layer()) return; // Change layer mode. if (should_paint_to_layer) { SetPaintToLayer(); layer()->SetFillsBoundsOpaquely(false); } else { DestroyLayer(); } } gfx::ImageSkia TabIcon::ThemeImage(const gfx::ImageSkia& source) { if (!GetThemeProvider()->HasCustomColor( ThemeProperties::COLOR_TOOLBAR_BUTTON_ICON)) return source; return gfx::ImageSkiaOperations::CreateColorMask( source, GetThemeProvider()->GetColor(ThemeProperties::COLOR_TOOLBAR_BUTTON_ICON)); }
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
d6e3e45aa5dc3fb224dfdc730466e1a003ab94c9
663ab089cf6b940fa8245a897b5cc3887dfa089f
/src/gpplib.cpp
9daeba0357660425e3e1f10bd481a3827faf3519
[]
no_license
alfaki/gppk
eef55e803229cd27ca681e79d9448e8a7f6e2f9c
1baf8f0edd722028081986ba748c32ea5bc33b34
refs/heads/main
2022-12-29T19:05:17.447179
2020-10-08T19:08:11
2020-10-08T19:08:11
302,432,462
0
0
null
null
null
null
UTF-8
C++
false
false
5,750
cpp
/* gpplib.cpp (miscellaneous library routines) */ /****************************************************************************** * This code is part of GPPK (The Generalized Pooling Problem Kit). * * Copyright (C) 2009, 2010 Mohammed Alfaki, Department of Informatics, * University of Bergen, Bergen, Norway. All rights reserved. E-mail: * <mohammeda@ii.uib.no>. * * GPPK is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. ******************************************************************************/ #include "gppk.h" /* Write formatted output to char string */ string get_str(const char *fmt, ...) { char *cstr; va_list arg; va_start(arg, fmt); int val = vasprintf(&cstr, fmt, arg); va_end(arg); string str(cstr); free(cstr); return str; } /* print error message and terminate processing */ void xerror(const char *fmt, ...) { va_list arg; va_start(arg, fmt); vprintf(fmt, arg); va_end(arg); printf("\n"); longjmp(buf, 1); /* no return */ } /* return file name for a full path of file */ string file_name(const char *file) { string str = file, fname, fpath; size_t size = str.find_last_of("/\\"); fpath = str.substr(0,size); fname = str.substr(size+1); size = str.substr(size+1).find_last_of("."); fname = fname.substr(0, size); return fname; } /* return the current date and time char string */ char *cdate() { time_t rawtime; struct tm *timeinfo; time(&rawtime); timeinfo = localtime(&rawtime); return asctime(timeinfo); } /* convert time in seconds to hh:mm:ss */ string clocktime(double ttime) { char *ctime; ctime = new char[STRING_LENGTH]; int time, hr, mn, sc, ms; time = (int)ttime; hr = time/3600; time = time%3600; mn = time/60; sc = time%60; ms = (int)(100*(ttime-(double)time)); sprintf(ctime, "%02d:%02d:%02d:%02d", hr, mn, sc, ms); string str(ctime); delete[] ctime; return str; } /* compute n choose k */ int n_choose_k(int n, int k) { if (k <= 0 || k >= n) return 1; else return n_choose_k(n-1, k-1)+n_choose_k(n-1, k); } /****************************************************************************** * NAME * str2int - convert character string to value of int type * * SYNOPSIS * #include "gppk.h" * int str2int(const char *str, int *val); * * DESCRIPTION * The routine str2int converts the character string str to a value of * integer type and stores the value into location, which the parameter * val points to (in the case of error content of this location is not * changed). * * RETURNS * The routine returns one of the following error codes: * 0 - no error; * 1 - value out of range; * 2 - character string is syntactically incorrect. ******************************************************************************/ int str2int(const char *str, int *_val) { int d, k, s, val = 0; /* scan optional sign */ if (str[0] == '+') s = +1, k = 1; else if (str[0] == '-') s = -1, k = 1; else s = +1, k = 0; /* check for the first digit */ if (!isdigit((unsigned char)str[k])) return 2; /* scan digits */ while (isdigit((unsigned char)str[k])) { d = str[k++] - '0'; if (s > 0) { if (val > INT_MAX / 10) return 1; val *= 10; if (val > INT_MAX - d) return 1; val += d; } else { if (val < INT_MIN / 10) return 1; val *= 10; if (val < INT_MIN + d) return 1; val -= d; } } /* check for terminator */ if (str[k] != '\0') return 2; /* conversion has been done */ *_val = val; return 0; } /****************************************************************************** * NAME * str2num - convert character string to value of double type * * SYNOPSIS * #include ".h" * int str2num(const char *str, double *val); * * DESCRIPTION * The routine str2num converts the character string str to a value of * double type and stores the value into location, which the parameter * val points to (in the case of error content of this location is not * changed). * * RETURNS * The routine returns one of the following error codes: * 0 - no error; * 1 - value out of range; * 2 - character string is syntactically incorrect. ******************************************************************************/ int str2num(const char *str, double *_val) { int k; double val; /* scan optional sign */ k = (str[0] == '+' || str[0] == '-' ? 1 : 0); /* check for decimal point */ if (str[k] == '.') { k++; /* a digit should follow it */ if (!isdigit((unsigned char)str[k])) return 2; k++; goto frac; } /* integer part should start with a digit */ if (!isdigit((unsigned char)str[k])) return 2; /* scan integer part */ while (isdigit((unsigned char)str[k])) k++; /* check for decimal point */ if (str[k] == '.') k++; frac: /* scan optional fraction part */ while (isdigit((unsigned char)str[k])) k++; /* check for decimal exponent */ if (str[k] == 'E' || str[k] == 'e') { k++; /* scan optional sign */ if (str[k] == '+' || str[k] == '-') k++; /* a digit should follow E, E+ or E- */ if (!isdigit((unsigned char)str[k])) return 2; } /* scan optional exponent part */ while (isdigit((unsigned char)str[k])) k++; /* check for terminator */ if (str[k] != '\0') return 2; /* perform conversion */ { char *endptr; val = strtod(str, &endptr); if (*endptr != '\0') return 2; } /* check for overflow */ if (!(-DBL_MAX <= val && val <= +DBL_MAX)) return 1; /* check for underflow */ if (-DBL_MIN < val && val < +DBL_MIN) val = 0.0; /* conversion has been done */ *_val = val; return 0; } /* eof */
[ "moh_alfaki@hotmail.com" ]
moh_alfaki@hotmail.com
08cee1451d171a164ba7e3aca5b46029be3b0425
4f9ff3c611a74385e8ba90d7719ff57712afc8a1
/some.cpp
62424db0f2af620481fa737953e341da14437f17
[]
no_license
EMWD/TriangleCalculating
867a4cfbb6ec528fc2f704ec7d7764058f816055
8ee58dd7136a535acef5b024cee3ebbfc3567c72
refs/heads/master
2020-04-29T19:27:26.539427
2019-04-07T16:13:33
2019-04-07T16:13:33
176,355,173
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
1,315
cpp
int Point::classify(Point &p0, Point &pl) { Point p2 = *this; Point a = p1 - pO; Point b = p2 - pO; double sa = a. x * b.y - b.x * a.y; if (sa > 0.0) return 0 if (sa < 0.0) return RIGHT; if ((a.x * b.x < 0.0) || (a.y * b.y < 0.0)) return 1 if (a.length() < b.length()) return BEYOND; if (pO == p2) return 2 if (p1 == p2) return DESTINATION; return 3 } double Point::polarAngle(void) { if ((x == 0.0) && (у == 0.0)) return -1.0; if (x == 0.0) return ((y > 0.0) ? 90 : 270); double theta = atan(y/x); // в радианах theta *= 360 / (2 * 3.1415926); // перевод в градусы if (x > 0.0) // 1 и 4 квадранты return ((y >= 0.0) ? theta : 360 + theta); else // 2 и З квадранты return (180 + theta); //Include node class Vertex: public Node, public Point { public: Vertex (double x, double y); Vertex (Point&); Vertex *cw(void); Vertex *ccw(void); Vertex *neighbor (int rotation); Point point (void); Vertex *insert (Vertex* ); Vertex *remove (void); void splice (Vertex*); Vertex *split (Vertex*); friend class Polygon; } };
[ "noreply@github.com" ]
EMWD.noreply@github.com
1c5e802f2a2a1fa4c8b63a9d8d3684d9f709158f
429c7c9911d1d474085610a4a9623c116ab0b50e
/NeuArch/Thread.cpp
6fc86a314980d6375fcf8884935f748ea8930a7a
[]
no_license
evlad/nnacs
932f575056da33e8d8b8a3b3f98b60b9713a575f
fea3f054b695c97b08b2e2584f2b56bc45b17e0b
refs/heads/master
2023-04-27T00:38:55.261142
2019-10-06T16:20:55
2019-10-06T16:20:55
13,727,160
2
3
null
null
null
null
UTF-8
C++
false
false
257
cpp
/* Thread.cpp */ static char rcsid[] = "$Id$"; //--------------------------------------------------------------------------- #include "Thread.h" //--------------------------------------------------------------------------- #pragma package(smart_init)
[ "ev1ad@yandex.ru" ]
ev1ad@yandex.ru
8a51ef8e58067fbdb6416a63746c2dc47dafeac9
5ec06dab1409d790496ce082dacb321392b32fe9
/clients/cpp-tizen/generated/src/ComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoProperties.h
d1104d828590097092a34bd708c21f5d9cd79c54
[ "Apache-2.0" ]
permissive
shinesolutions/swagger-aem-osgi
e9d2385f44bee70e5bbdc0d577e99a9f2525266f
c2f6e076971d2592c1cbd3f70695c679e807396b
refs/heads/master
2022-10-29T13:07:40.422092
2021-04-09T07:46:03
2021-04-09T07:46:03
190,217,155
3
3
Apache-2.0
2022-10-05T03:26:20
2019-06-04T14:23:28
null
UTF-8
C++
false
false
1,551
h
/* * ComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoProperties.h * * */ #ifndef _ComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoProperties_H_ #define _ComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoProperties_H_ #include <string> #include "ConfigNodePropertyBoolean.h" #include "Object.h" /** \defgroup Models Data Structures for API * Classes containing all the Data Structures needed for calling/returned by API endpoints * */ namespace Tizen { namespace ArtikCloud { /*! \brief * * \ingroup Models * */ class ComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoProperties : public Object { public: /*! \brief Constructor. */ ComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoProperties(); ComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoProperties(char* str); /*! \brief Destructor. */ virtual ~ComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoProperties(); /*! \brief Retrieve a string JSON representation of this class. */ char* toJson(); /*! \brief Fills in members of this class from JSON string representing it. */ void fromJson(char* jsonStr); /*! \brief Get */ ConfigNodePropertyBoolean getIsMemberCheck(); /*! \brief Set */ void setIsMemberCheck(ConfigNodePropertyBoolean isMemberCheck); private: ConfigNodePropertyBoolean isMemberCheck; void __init(); void __cleanup(); }; } } #endif /* _ComAdobeCqSocialEnablementAdaptorsEnablementResourceAdaptorFactoProperties_H_ */
[ "cliffano@gmail.com" ]
cliffano@gmail.com
b030a566adfc03502cba6b087bbd5cd20f249c05
a9fc0a713d0817160dc18a3fae1fbe8b804f7044
/rc-switch-jni-wrapper/src/com_opitz_jni_NativeRCSwitchAdapter.cpp
79fea898553b15a97256e96c31805509721bc07a
[]
no_license
magicgis/Pi-jAutomation433
ced27758fce529f9b9e187cdfbd98e99844d5dd4
7ceec94dd7b1c89376db70fccbbe8d99e2b3964a
refs/heads/master
2020-08-29T04:06:15.378274
2014-09-16T11:43:01
2014-09-16T11:43:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,015
cpp
#include "com_opitz_jni_NativeRCSwitchAdapter.h" #include "RCSwitch.h" #include <stdio.h> #include <stdlib.h> #include <iostream> #include <wiringPi.h> using namespace std; RCSwitch mySwitch = RCSwitch(); JNIEXPORT void JNICALL Java_com_opitz_jni_NativeRCSwitchAdapter_switchOn(JNIEnv * env, jobject obj, jstring jsGroup, jstring jsChannel ){ if (wiringPiSetup () == -1) { printf("noWiringPiSetup"); } const char *csGroup = env->GetStringUTFChars(jsGroup, 0); const char *csChannel = env->GetStringUTFChars(jsChannel, 0); char sGroup[6]; char sChannel[6]; for (int i = 0; i<5; i++) { sGroup[i] = csGroup[i]; sChannel[i] = csChannel[i]; } sGroup[5] = '\0'; sChannel[5] = '\0'; cout<<"ON with"<<sGroup<<"and "<< sChannel <<endl; piHiPri(20); //for testing purposes set to the ELRO Power Plugs mySwitch.setPulseLength(300); mySwitch.enableTransmit(0); mySwitch.setRepeatTransmit(3); mySwitch.switchOn(sGroup, sChannel); } JNIEXPORT void JNICALL Java_com_opitz_jni_NativeRCSwitchAdapter_switchOff(JNIEnv * env, jobject obj, jstring jsGroup, jstring jsChannel ){ if (wiringPiSetup () == -1) { printf("noWiringPiSetup"); } const char *csGroup = env->GetStringUTFChars(jsGroup, 0); const char *csChannel = env->GetStringUTFChars(jsChannel, 0); char sGroup[6]; char sChannel[6]; for (int i = 0; i<5; i++) { sGroup[i] = csGroup[i]; sChannel[i] = csChannel[i]; } sGroup[5] = '\0'; sChannel[5] = '\0'; cout<<"OFF with "<<sGroup<<" and "<< sChannel <<endl; piHiPri(20); //for testing purposes set to the ELRO Power Plugs mySwitch.setPulseLength(300); mySwitch.enableTransmit(0); mySwitch.setRepeatTransmit(3); mySwitch.switchOff(sGroup, sChannel); } JNIEXPORT void JNICALL Java_NativeRCSwitchAdapter_setPulseLength(JNIEnv * env, jobject obj , jint pulseLength){ //int = env->GetStringUTFChars(jsGroup, 0); }
[ "satspeedy@users.noreply.github.com" ]
satspeedy@users.noreply.github.com
b25fef9a4b12d686e1d8bc18ebbd090130d557c9
858d413add89d4afae69e13e2deb4572f8e5f34e
/test/arbitrary_fanin.cpp
8d2e426b31f269d37c9d80ce4afa8dab444ac7b3
[ "MIT" ]
permissive
msoeken/percy
2958200e6af4bd857fd5b55e32cc73841c6e686a
42cd65b490849d5cdc4b8142db03e78cc67f1be6
refs/heads/master
2020-03-19T18:11:35.569292
2018-06-08T13:55:00
2018-06-08T13:55:00
124,677,384
0
0
MIT
2018-04-25T13:04:40
2018-03-10T17:02:07
C++
UTF-8
C++
false
false
1,443
cpp
#include <cstdio> #include <percy/percy.hpp> using namespace percy; /******************************************************************************* Tests support for exact synthesis of arbitrary fanin chains. Specifically, tests if the functions that are used to map selection variable indices to fanin assignments work correctly. *******************************************************************************/ int main(void) { std::array<int, 2> init_test; fanin_init(init_test, 1); assert(init_test[0] == 0); assert(init_test[1] == 1); std::array<int, 2> fanin2 = { 0, 1 }; assert(fanin_inc(fanin2, 1) == false); assert(fanin_inc(fanin2, 2) == true); assert(fanin2[0] == 0); assert(fanin2[1] == 2); assert(fanin_inc(fanin2, 2) == true); assert(fanin2[0] == 1); assert(fanin2[1] == 2); assert(fanin_inc(fanin2, 2) == false); std::array<int, 3> fanin3 = { 0, 1, 2 }; assert(fanin_inc(fanin3, 2) == false); assert(fanin_inc(fanin3, 3) == true); assert(fanin3[0] == 0); assert(fanin3[1] == 1); assert(fanin3[2] == 3); assert(fanin_inc(fanin3, 3) == true); assert(fanin3[0] == 0); assert(fanin3[1] == 2); assert(fanin3[2] == 3); assert(fanin_inc(fanin3, 3) == true); assert(fanin3[0] == 1); assert(fanin3[1] == 2); assert(fanin3[2] == 3); assert(fanin_inc(fanin3, 3) == false); return 0; }
[ "winston.haaswijk@gmail.com" ]
winston.haaswijk@gmail.com
953545cb89deb409ff63aedc8e976b058438bfc1
4fa1e0711c3023a94035b58f6a66c9acd4a7f424
/Microsoft/SAMPLES/CPPtoCOM/DB_Vtbl/Interface/Dbsrv.h
b1d29aad31a79d42cf391a6c279a1d59666ac97e
[ "MIT" ]
permissive
tig/Tigger
4d1f5a2088468c75a7c21b103705445a93ec571c
8e06d117a5b520c5fc9e37a710bf17aa51a9958c
refs/heads/master
2023-06-09T01:59:43.167371
2020-08-19T15:21:53
2020-08-19T15:21:53
3,426,737
1
2
null
2023-05-31T18:56:36
2012-02-13T03:05:18
C
UTF-8
C++
false
false
724
h
#ifndef _DBSERVER_INCLUDE #define _DBSERVER_INCLUDE typedef long HRESULT; class IDB { // Interfaces public: // Interface for data access virtual HRESULT Read(short nTable, short nRow, LPTSTR lpszData) =0; virtual HRESULT Write(short nTable, short nRow, LPCTSTR lpszData) =0; // Interface for database management virtual HRESULT Create(short &nTable, LPCTSTR lpszName) =0; virtual HRESULT Delete(short nTable) =0; // Interface for database information virtual HRESULT GetNumTables(short &nNumTables) =0; virtual HRESULT GetTableName(short nTable, LPTSTR lpszName) =0; virtual HRESULT GetNumRows(short nTable, short &nRows) =0; }; HRESULT CreateDB(IDB** ppObj); #endif
[ "charlie@kindel.com" ]
charlie@kindel.com
9c855778a2888a3d40da21c56810803fa7c43bf4
72d8bd35b3be639a4be081de1786d031c9e9a1a9
/PXFXMQery.cpp
8f94641b40f9c54948f81faeaa786ac9950d51c6
[]
no_license
bravesoftdz/IC-Info
69bb6d30c130dc29da2b51262b542f95079fcf53
e07e745a69ea2181d2fa05ad5fc2cc7b07711827
refs/heads/master
2020-03-08T06:40:20.549679
2014-11-20T11:51:14
2014-11-20T11:51:14
null
0
0
null
null
null
null
GB18030
C++
false
false
8,013
cpp
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "PXFXMQery.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma link "cxButtons" #pragma link "cxCalendar" #pragma link "cxContainer" #pragma link "cxControls" #pragma link "cxDropDownEdit" #pragma link "cxEdit" #pragma link "cxGraphics" #pragma link "cxGroupBox" #pragma link "cxLabel" #pragma link "cxLookAndFeelPainters" #pragma link "cxLookAndFeels" #pragma link "cxMaskEdit" #pragma link "cxTextEdit" #pragma link "dxSkinBlack" #pragma link "dxSkinBlue" #pragma link "dxSkinCaramel" #pragma link "dxSkinCoffee" #pragma link "dxSkinDarkRoom" #pragma link "dxSkinDarkSide" #pragma link "dxSkinFoggy" #pragma link "dxSkinGlassOceans" #pragma link "dxSkiniMaginary" #pragma link "dxSkinLilian" #pragma link "dxSkinLiquidSky" #pragma link "dxSkinLondonLiquidSky" #pragma link "dxSkinMcSkin" #pragma link "dxSkinMoneyTwins" #pragma link "dxSkinOffice2007Black" #pragma link "dxSkinOffice2007Blue" #pragma link "dxSkinOffice2007Green" #pragma link "dxSkinOffice2007Pink" #pragma link "dxSkinOffice2007Silver" #pragma link "dxSkinPumpkin" #pragma link "dxSkinsCore" #pragma link "dxSkinsDefaultPainters" #pragma link "dxSkinSeven" #pragma link "dxSkinSharp" #pragma link "dxSkinSilver" #pragma link "dxSkinSpringTime" #pragma link "dxSkinStardust" #pragma link "dxSkinSummer2008" #pragma link "dxSkinValentine" #pragma link "dxSkinXmas2008Blue" #pragma resource "*.dfm" TPXFXMForm *PXFXMForm; //--------------------------------------------------------------------------- __fastcall TPXFXMForm::TPXFXMForm(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TPXFXMForm::ReadCardInfoBTNClick(TObject *Sender) { WORD status; int tmpbalance; int tmpkh,tmpsycs; double tmpintye; double tmpye; unsigned char keymode,secnum,Delayms,mode; unsigned char key[6]; unsigned char dwmm[6]; unsigned char daytime[4]; unsigned char kh[4]; unsigned char balance[4]; unsigned char cardtype[1]; unsigned char czmm[3]; unsigned char synum[3]; // unsigned char readcomno[5] = ""; Delayms = 0x00; keymode = CARDPasswordEdition;//0x03; secnum = UsingSecNUM;//0x01; key[0] = CARDPassword[0]; key[1] = CARDPassword[1]; key[2] = CARDPassword[2]; key[3] = CARDPassword[3]; key[4] = CARDPassword[4]; key[5] = CARDPassword[5]; if(LoadHModule) { beepofreaddll(readcomno, '10'); if(readcardinfo) { status = readcardinfo(readcomno,keymode,secnum,key,kh,balance, dwmm,synum,daytime,cardtype,czmm,Delayms); if(status > 99) { ShowMessage("通讯错误!"); } else if (1 == status) { ShowMessage("请把卡片放好!"); } else if (2 == status) { ShowMessage("卡号大于192000或等于0!"); } else if (4 == status) { ShowMessage("卡片密码不对!"); } else if (5 == status) { ShowMessage("读写卡不稳定!"); } else if (6 == status) { ShowMessage("卡结构不对!"); } else if (10 == status) { ShowMessage("卡结构不对!"); } else if (0 != status) { ShowMessage("该卡未发行或已退卡!"); } else { String tmpstr; tmpkh = (int)kh[1]*256*256+(int)kh[2]*256+(int)kh[3]; tmpsycs = (int)synum[0]*256+(int)synum[1]; tmpintye = (double)balance[1]*256*256+(double)balance[2]*256+(double)balance[3]; tmpye = tmpintye/100; XFADOQ->Close(); XFADOQ->SQL->Clear(); tmpstr = "select * from KZT where kh="; tmpstr += tmpkh; XFADOQ->SQL->Add(tmpstr); XFADOQ->Open(); if(!XFADOQ->IsEmpty()) { if(0 != XFADOQ->FieldByName("GS")->AsInteger) { ShowMessage("此卡已挂失,请没收此卡!"); XFADOQ->Close(); } } else { ShowMessage("此卡不是本系统发出的卡!"); XFADOQ->Close(); } XFADOQ->Close(); XFADOQ->SQL->Clear(); tmpstr = "select * from CARD where kh="; tmpstr += tmpkh; XFADOQ->SQL->Add(tmpstr); XFADOQ->Open(); if(!XFADOQ->IsEmpty()) { XFXMTextEdit->Text = ""; XFKHTextEdit->Text = tmpkh; } else { ShowMessage("此卡不是本系统发出的卡!"); XFADOQ->Close(); } } } else { ShowMessage("读卡函数加载失败!"); } } else ShowMessage("加载读写卡动态链接库失败!"); } //--------------------------------------------------------------------------- void __fastcall TPXFXMForm::QueryBTNClick(TObject *Sender) { if(XFKHTextEdit->Text.IsEmpty()&&XFXMTextEdit->Text.IsEmpty()) { ShowMessage("请至少填写姓名与卡号中的一项!"); return; } if(!XFBeginDateEdit->Text.IsEmpty()&&!XFEndDateEdit->Text.IsEmpty()) { String sumsqlstr = "select SUM(case when SFLX='X' then MXBAK.SFJE else 0 end) as XFZE,SUM(case when SFLX='X' then 1 else 0 end) as XFZCS,SUM(case when (SFLX='I' or SFLX='A') then MXBAK.SFJE when SFLX='K' then MXBAK.SF_YE else 0 end) as CZZE,SUM(case when (SFLX='I' or SFLX='A') then 1 when SFLX='K' then 1 else 0 end) as CZZCS,SUM(case when (SFLX='D' or SFLX='Q' or SFLX='R') then MXBAK.SFJE else 0 end) as QKZE,SUM(case when (SFLX='D' or SFLX='Q' or SFLX='R') then 1 else 0 end) as QKZCS from MXBAK join CARD_F on CARD_F.BH=MXBAK.BH where "; String mxsqlstr = "select MXBAK.KH,MXBAK.BH,CARD_F.XM,CARD_F.BM,CARD_F.ZW,MXBAK.SF_YE,MXBAK.SFJE,MXBAK.SYCS,MXBAK.JYNO,MXBAK.SFLX,MXBAK.SFRQ from MXBAK join CARD_F on CARD_F.BH=MXBAK.BH where SFLX in ('X','I','A','K','D','Q', 'R') and "; String addsqlstr = ""; if(!XFKHTextEdit->Text.IsEmpty()) { addsqlstr = "MXBAK.KH='"; addsqlstr += XFKHTextEdit->Text; addsqlstr += "' and "; } if(!XFXMTextEdit->Text.IsEmpty()) { if(addsqlstr.IsEmpty()) { addsqlstr = "CARD_F.XM='"; addsqlstr += XFXMTextEdit->Text; addsqlstr += "' and "; } else { addsqlstr += "CARD_F.XM='"; addsqlstr += XFXMTextEdit->Text; addsqlstr += "' and "; } } addsqlstr += "SFRQ>'"; addsqlstr += XFBeginDateEdit->Text; addsqlstr += " 00:00:00' and SFRQ<'"; addsqlstr += XFEndDateEdit->Text; addsqlstr += " 23:59:59'"; sumsqlstr += addsqlstr; mxsqlstr += addsqlstr; XFADOQ->Close(); XFADOQ->SQL->Clear(); XFADOQ->SQL->Add(mxsqlstr); XFADOQ->Open(); if(!XFADOQ->IsEmpty()) { XFADOQ->Close(); XFADOQ->SQL->Clear(); XFADOQ->SQL->Add(sumsqlstr); XFADOQ->Open(); PXFMXShowFrm->AllXFTextEdit->Text = XFADOQ->FieldByName("XFZE")->AsString; PXFMXShowFrm->AllCSTextEdit->Text = XFADOQ->FieldByName("XFZCS")->AsString; PXFMXShowFrm->cxTextEdit2->Text = XFADOQ->FieldByName("CZZE")->AsString; PXFMXShowFrm->cxTextEdit1->Text = XFADOQ->FieldByName("CZZCS")->AsString; PXFMXShowFrm->cxTextEdit4->Text = XFADOQ->FieldByName("QKZE")->AsString; PXFMXShowFrm->cxTextEdit3->Text = XFADOQ->FieldByName("QKZCS")->AsString; XFADOQ->Close(); PXFMXShowFrm->BeginDateTimeStr = XFBeginDateEdit->Text + " 00:00:00"; PXFMXShowFrm->EndDateTimeStr = XFEndDateEdit->Text + " 23:59:59"; PXFMXShowFrm->KHStr = XFKHTextEdit->Text; PXFMXShowFrm->XMStr = XFXMTextEdit->Text; PXFMXShowFrm->CZYStr = OperatorName; PXFMXShowFrm->XFMXExportProgressBar->Position = 0; PXFMXShowFrm->allsqlstr = mxsqlstr; PXFMXShowFrm->XFMXADOQuery->Close(); PXFMXShowFrm->XFMXADOQuery->SQL->Clear(); PXFMXShowFrm->XFMXADOQuery->SQL->Add(mxsqlstr); PXFMXShowFrm->ShowModal(); } else ShowMessage("符合该查询条件的记录条数为0!"); } else { ShowMessage("必须填写查询起止日期!"); } } //--------------------------------------------------------------------------- void __fastcall TPXFXMForm::FormShow(TObject *Sender) { XFBeginDateEdit->Date = Date(); XFEndDateEdit->Date = Date(); } //---------------------------------------------------------------------------
[ "47157860@qq.com" ]
47157860@qq.com
45e2a325dab8ec5d056af37af42b6a058938a849
02b361a4c1267e8f9e7e2008bf0d82fb9cef8cd2
/src/txdb.cpp
b6379fbb2f9c1a7d68026403ef33287d4621ae40
[ "MIT" ]
permissive
team-exor/exor
abaf938ee24cc66c6b86ee76a93aa501dbbd32ac
da9a2145d834e45db2fd8637ec984e249bfbd5d9
refs/heads/master
2020-05-28T05:50:04.600841
2019-06-24T20:26:46
2019-06-24T20:26:46
188,899,679
1
3
null
null
null
null
UTF-8
C++
false
false
14,719
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2016-2018 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "txdb.h" #include "main.h" #include "pow.h" #include "uint256.h" #include "accumulators.h" #include <stdint.h> #include <boost/thread.hpp> using namespace std; using namespace libzerocoin; void static BatchWriteCoins(CLevelDBBatch& batch, const uint256& hash, const CCoins& coins) { if (coins.IsPruned()) batch.Erase(make_pair('c', hash)); else batch.Write(make_pair('c', hash), coins); } void static BatchWriteHashBestChain(CLevelDBBatch& batch, const uint256& hash) { batch.Write('B', hash); } CCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / "chainstate", nCacheSize, fMemory, fWipe) { } bool CCoinsViewDB::GetCoins(const uint256& txid, CCoins& coins) const { return db.Read(make_pair('c', txid), coins); } bool CCoinsViewDB::HaveCoins(const uint256& txid) const { return db.Exists(make_pair('c', txid)); } uint256 CCoinsViewDB::GetBestBlock() const { uint256 hashBestChain; if (!db.Read('B', hashBestChain)) return uint256(0); return hashBestChain; } bool CCoinsViewDB::BatchWrite(CCoinsMap& mapCoins, const uint256& hashBlock) { CLevelDBBatch batch; size_t count = 0; size_t changed = 0; for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) { if (it->second.flags & CCoinsCacheEntry::DIRTY) { BatchWriteCoins(batch, it->first, it->second.coins); changed++; } count++; CCoinsMap::iterator itOld = it++; mapCoins.erase(itOld); } if (hashBlock != uint256(0)) BatchWriteHashBestChain(batch, hashBlock); LogPrint("coindb", "Committing %u changed transactions (out of %u) to coin database...\n", (unsigned int)changed, (unsigned int)count); return db.WriteBatch(batch); } CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CLevelDBWrapper(GetDataDir() / "blocks" / "index", nCacheSize, fMemory, fWipe) { } bool CBlockTreeDB::WriteBlockIndex(const CDiskBlockIndex& blockindex) { return Write(make_pair('b', blockindex.GetBlockHash()), blockindex); } bool CBlockTreeDB::WriteBlockFileInfo(int nFile, const CBlockFileInfo& info) { return Write(make_pair('f', nFile), info); } bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo& info) { return Read(make_pair('f', nFile), info); } bool CBlockTreeDB::WriteLastBlockFile(int nFile) { return Write('l', nFile); } bool CBlockTreeDB::WriteReindexing(bool fReindexing) { if (fReindexing) return Write('R', '1'); else return Erase('R'); } bool CBlockTreeDB::ReadReindexing(bool& fReindexing) { fReindexing = Exists('R'); return true; } bool CBlockTreeDB::ReadLastBlockFile(int& nFile) { return Read('l', nFile); } bool CCoinsViewDB::GetStats(CCoinsStats& stats) const { /* It seems that there are no "const iterators" for LevelDB. Since we only need read operations on it, use a const-cast to get around that restriction. */ boost::scoped_ptr<leveldb::Iterator> pcursor(const_cast<CLevelDBWrapper*>(&db)->NewIterator()); pcursor->SeekToFirst(); CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); stats.hashBlock = GetBestBlock(); ss << stats.hashBlock; CAmount nTotalAmount = 0; while (pcursor->Valid()) { boost::this_thread::interruption_point(); try { leveldb::Slice slKey = pcursor->key(); CDataStream ssKey(slKey.data(), slKey.data() + slKey.size(), SER_DISK, CLIENT_VERSION); char chType; ssKey >> chType; if (chType == 'c') { leveldb::Slice slValue = pcursor->value(); CDataStream ssValue(slValue.data(), slValue.data() + slValue.size(), SER_DISK, CLIENT_VERSION); CCoins coins; ssValue >> coins; uint256 txhash; ssKey >> txhash; ss << txhash; ss << VARINT(coins.nVersion); ss << (coins.fCoinBase ? 'c' : 'n'); ss << VARINT(coins.nHeight); stats.nTransactions++; for (unsigned int i = 0; i < coins.vout.size(); i++) { const CTxOut& out = coins.vout[i]; if (!out.IsNull()) { stats.nTransactionOutputs++; ss << VARINT(i + 1); ss << out; nTotalAmount += out.nValue; } } stats.nSerializedSize += 32 + slValue.size(); ss << VARINT(0); } pcursor->Next(); } catch (std::exception& e) { return error("%s : Deserialize or I/O error - %s", __func__, e.what()); } } stats.nHeight = mapBlockIndex.find(GetBestBlock())->second->nHeight; stats.hashSerialized = ss.GetHash(); stats.nTotalAmount = nTotalAmount; return true; } bool CBlockTreeDB::ReadTxIndex(const uint256& txid, CDiskTxPos& pos) { return Read(make_pair('t', txid), pos); } bool CBlockTreeDB::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >& vect) { CLevelDBBatch batch; for (std::vector<std::pair<uint256, CDiskTxPos> >::const_iterator it = vect.begin(); it != vect.end(); it++) batch.Write(make_pair('t', it->first), it->second); return WriteBatch(batch); } bool CBlockTreeDB::WriteFlag(const std::string& name, bool fValue) { return Write(std::make_pair('F', name), fValue ? '1' : '0'); } bool CBlockTreeDB::ReadFlag(const std::string& name, bool& fValue) { char ch; if (!Read(std::make_pair('F', name), ch)) return false; fValue = ch == '1'; return true; } bool CBlockTreeDB::WriteInt(const std::string& name, int nValue) { return Write(std::make_pair('I', name), nValue); } bool CBlockTreeDB::ReadInt(const std::string& name, int& nValue) { return Read(std::make_pair('I', name), nValue); } bool CBlockTreeDB::LoadBlockIndexGuts() { boost::scoped_ptr<leveldb::Iterator> pcursor(NewIterator()); CDataStream ssKeySet(SER_DISK, CLIENT_VERSION); ssKeySet << make_pair('b', uint256(0)); pcursor->Seek(ssKeySet.str()); // Load mapBlockIndex uint256 nPreviousCheckpoint; while (pcursor->Valid()) { boost::this_thread::interruption_point(); try { leveldb::Slice slKey = pcursor->key(); CDataStream ssKey(slKey.data(), slKey.data() + slKey.size(), SER_DISK, CLIENT_VERSION); char chType; ssKey >> chType; if (chType == 'b') { leveldb::Slice slValue = pcursor->value(); CDataStream ssValue(slValue.data(), slValue.data() + slValue.size(), SER_DISK, CLIENT_VERSION); CDiskBlockIndex diskindex; ssValue >> diskindex; // Construct block index object CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash()); pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev); pindexNew->pnext = InsertBlockIndex(diskindex.hashNext); pindexNew->nHeight = diskindex.nHeight; pindexNew->nFile = diskindex.nFile; pindexNew->nDataPos = diskindex.nDataPos; pindexNew->nUndoPos = diskindex.nUndoPos; pindexNew->nVersion = diskindex.nVersion; pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot; pindexNew->nTime = diskindex.nTime; pindexNew->nBits = diskindex.nBits; pindexNew->nNonce = diskindex.nNonce; pindexNew->nStatus = diskindex.nStatus; pindexNew->nTx = diskindex.nTx; //zerocoin pindexNew->nAccumulatorCheckpoint = diskindex.nAccumulatorCheckpoint; pindexNew->mapZerocoinSupply = diskindex.mapZerocoinSupply; pindexNew->vMintDenominationsInBlock = diskindex.vMintDenominationsInBlock; //Proof Of Stake pindexNew->nMint = diskindex.nMint; pindexNew->nMoneySupply = diskindex.nMoneySupply; pindexNew->nFlags = diskindex.nFlags; pindexNew->nStakeModifier = diskindex.nStakeModifier; pindexNew->prevoutStake = diskindex.prevoutStake; pindexNew->nStakeTime = diskindex.nStakeTime; pindexNew->hashProofOfStake = diskindex.hashProofOfStake; if (pindexNew->nHeight <= Params().LAST_POW_BLOCK()) { if (!CheckProofOfWork(pindexNew->GetBlockHash(), pindexNew->nBits)) return error("LoadBlockIndex() : CheckProofOfWork failed: %s", pindexNew->ToString()); } // ppcoin: build setStakeSeen if (pindexNew->IsProofOfStake()) setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime)); //populate accumulator checksum map in memory if(pindexNew->nAccumulatorCheckpoint != 0 && pindexNew->nAccumulatorCheckpoint != nPreviousCheckpoint) { //Don't load any checkpoints that exist before v2 zexor. The accumulator is invalid for v1 and not used. if (pindexNew->nHeight >= Params().Zerocoin_Block_V2_Start()) LoadAccumulatorValuesFromDB(pindexNew->nAccumulatorCheckpoint); nPreviousCheckpoint = pindexNew->nAccumulatorCheckpoint; } pcursor->Next(); } else { break; // if shutdown requested or finished loading block index } } catch (std::exception& e) { return error("%s : Deserialize or I/O error - %s", __func__, e.what()); } } return true; } CZerocoinDB::CZerocoinDB(size_t nCacheSize, bool fMemory, bool fWipe) : CLevelDBWrapper(GetDataDir() / "zerocoin", nCacheSize, fMemory, fWipe) { } bool CZerocoinDB::WriteCoinMintBatch(const std::vector<std::pair<libzerocoin::PublicCoin, uint256> >& mintInfo) { CLevelDBBatch batch; size_t count = 0; for (std::vector<std::pair<libzerocoin::PublicCoin, uint256> >::const_iterator it=mintInfo.begin(); it != mintInfo.end(); it++) { PublicCoin pubCoin = it->first; uint256 hash = GetPubCoinHash(pubCoin.getValue()); batch.Write(make_pair('m', hash), it->second); ++count; } LogPrint("zero", "Writing %u coin mints to db.\n", (unsigned int)count); return WriteBatch(batch, true); } bool CZerocoinDB::ReadCoinMint(const CBigNum& bnPubcoin, uint256& hashTx) { return ReadCoinMint(GetPubCoinHash(bnPubcoin), hashTx); } bool CZerocoinDB::ReadCoinMint(const uint256& hashPubcoin, uint256& hashTx) { return Read(make_pair('m', hashPubcoin), hashTx); } bool CZerocoinDB::EraseCoinMint(const CBigNum& bnPubcoin) { uint256 hash = GetPubCoinHash(bnPubcoin); return Erase(make_pair('m', hash)); } bool CZerocoinDB::WriteCoinSpendBatch(const std::vector<std::pair<libzerocoin::CoinSpend, uint256> >& spendInfo) { CLevelDBBatch batch; size_t count = 0; for (std::vector<std::pair<libzerocoin::CoinSpend, uint256> >::const_iterator it=spendInfo.begin(); it != spendInfo.end(); it++) { CBigNum bnSerial = it->first.getCoinSerialNumber(); CDataStream ss(SER_GETHASH, 0); ss << bnSerial; uint256 hash = Hash(ss.begin(), ss.end()); batch.Write(make_pair('s', hash), it->second); ++count; } LogPrint("zero", "Writing %u coin spends to db.\n", (unsigned int)count); return WriteBatch(batch, true); } bool CZerocoinDB::ReadCoinSpend(const CBigNum& bnSerial, uint256& txHash) { CDataStream ss(SER_GETHASH, 0); ss << bnSerial; uint256 hash = Hash(ss.begin(), ss.end()); return Read(make_pair('s', hash), txHash); } bool CZerocoinDB::ReadCoinSpend(const uint256& hashSerial, uint256 &txHash) { return Read(make_pair('s', hashSerial), txHash); } bool CZerocoinDB::EraseCoinSpend(const CBigNum& bnSerial) { CDataStream ss(SER_GETHASH, 0); ss << bnSerial; uint256 hash = Hash(ss.begin(), ss.end()); return Erase(make_pair('s', hash)); } bool CZerocoinDB::WipeCoins(std::string strType) { if (strType != "spends" && strType != "mints") return error("%s: did not recognize type %s", __func__, strType); boost::scoped_ptr<leveldb::Iterator> pcursor(NewIterator()); char type = (strType == "spends" ? 's' : 'm'); CDataStream ssKeySet(SER_DISK, CLIENT_VERSION); ssKeySet << make_pair(type, uint256(0)); pcursor->Seek(ssKeySet.str()); // Load mapBlockIndex std::set<uint256> setDelete; while (pcursor->Valid()) { boost::this_thread::interruption_point(); try { leveldb::Slice slKey = pcursor->key(); CDataStream ssKey(slKey.data(), slKey.data() + slKey.size(), SER_DISK, CLIENT_VERSION); char chType; ssKey >> chType; if (chType == type) { leveldb::Slice slValue = pcursor->value(); CDataStream ssValue(slValue.data(), slValue.data() + slValue.size(), SER_DISK, CLIENT_VERSION); uint256 hash; ssValue >> hash; setDelete.insert(hash); pcursor->Next(); } else { break; // if shutdown requested or finished loading block index } } catch (std::exception& e) { return error("%s : Deserialize or I/O error - %s", __func__, e.what()); } } for (auto& hash : setDelete) { if (!Erase(make_pair(type, hash))) LogPrintf("%s: error failed to delete %s\n", __func__, hash.GetHex()); } return true; } bool CZerocoinDB::WriteAccumulatorValue(const uint32_t& nChecksum, const CBigNum& bnValue) { LogPrint("zero","%s : checksum:%d val:%s\n", __func__, nChecksum, bnValue.GetHex()); return Write(make_pair('2', nChecksum), bnValue); } bool CZerocoinDB::ReadAccumulatorValue(const uint32_t& nChecksum, CBigNum& bnValue) { return Read(make_pair('2', nChecksum), bnValue); } bool CZerocoinDB::EraseAccumulatorValue(const uint32_t& nChecksum) { LogPrint("zero", "%s : checksum:%d\n", __func__, nChecksum); return Erase(make_pair('2', nChecksum)); }
[ "joeuhren@protonmail.com" ]
joeuhren@protonmail.com
bf9e1719a140ccc62272e781f28b92a9e597bbba
93f635bbef282f8dcfbbfa682aec2c206e68f7b7
/beginner_level_and_uva/memset 1.cpp
5ba1226cf3208c18cf8d87af1d93c1608ecb1578
[]
no_license
Alimurrazi/Programming
6ba828ea15e640f70311fab33cce1a6e9190db45
cd4354616596d6c7865f4ccd835b1c0712f41c45
refs/heads/master
2023-08-01T14:23:31.342302
2021-09-14T03:53:50
2021-09-14T03:53:50
107,748,091
0
0
null
null
null
null
UTF-8
C++
false
false
160
cpp
#include<stdio.h> #include<string.h> int main() { int ara[100]; int i,j,k,l; memset(ara,('1'-'0'),sizeof(ara)); for(i=0;i<=50;i++) printf("%d\n",ara[i]); }
[ "alimurrazi570@gmail.com" ]
alimurrazi570@gmail.com
16398a9e08fc3db5480d05882c1bf8450c397e62
1665a6d1f918076d4c5e29059eeedb344e8df28b
/src/reporters/reporter_particle.cpp
141802427cf8609019036ae50e7e65f682e0b812
[ "MIT" ]
permissive
suda/SensorReporter
8ae50ef01c357d6e9774c95a66d418bee7587d32
efd89334fc778f5adde91650899a0ba8f77fa5eb
refs/heads/master
2020-04-01T07:40:54.027722
2018-10-16T17:58:10
2018-10-16T17:58:10
152,999,111
1
0
null
null
null
null
UTF-8
C++
false
false
269
cpp
#include "reporter_particle.h" void ReporterParticle::report(Sample _sample) { String name = this->prefix; name.concat(_sample.name); Particle.publish(name, _sample.value); } void ReporterParticle::setPrefix(String _prefix) { this->prefix = _prefix; };
[ "admin@suda.pl" ]
admin@suda.pl
d7cf5aa00a7af9379a0d212235c08c584227a53a
9d05e9312f35377b46269ce00d5720338743e260
/MashView.h
fe511b4134a617c0e99f36418570d7d97db04e7e
[]
no_license
dbratell/Mash
b18b83f0c9c10366cee29da0f1f9ce1a0eceb9c6
73ddb1405272725ca2b9406cd1e00b7d7f30da51
refs/heads/master
2020-05-09T15:06:49.671860
2000-04-24T20:29:24
2000-04-24T20:29:24
181,221,694
0
0
null
null
null
null
UTF-8
C++
false
false
1,792
h
// MashView.h : interface of the CMashView class // ///////////////////////////////////////////////////////////////////////////// #if !defined(AFX_MASHVIEW_H__278C1BB6_A133_4BD7_A3CA_34646DB9DB75__INCLUDED_) #define AFX_MASHVIEW_H__278C1BB6_A133_4BD7_A3CA_34646DB9DB75__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CMashView : public CView { protected: // create from serialization only CMashView(); DECLARE_DYNCREATE(CMashView) // Attributes public: CMashDoc* GetDocument(); // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CMashView) public: virtual void OnDraw(CDC* pDC); // overridden to draw this view virtual BOOL PreCreateWindow(CREATESTRUCT& cs); protected: virtual BOOL OnPreparePrinting(CPrintInfo* pInfo); virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo); virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo); //}}AFX_VIRTUAL // Implementation public: virtual ~CMashView(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // Generated message map functions protected: //{{AFX_MSG(CMashView) // NOTE - the ClassWizard will add and remove member functions here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG DECLARE_MESSAGE_MAP() }; #ifndef _DEBUG // debug version in MashView.cpp inline CMashDoc* CMashView::GetDocument() { return (CMashDoc*)m_pDocument; } #endif ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_MASHVIEW_H__278C1BB6_A133_4BD7_A3CA_34646DB9DB75__INCLUDED_)
[ "bratell@lysator.liu.se" ]
bratell@lysator.liu.se
a82f1f5ae16cacdc5b315dd3ca012a691e12fb0e
9e9267611371cdff143e7a9b286a9fffc2641e78
/about.cpp
2f19cfdae4ea8cd13cc09e765a17fb1c62037efa
[]
no_license
wucan/csv2sql
736473e357c73acf40fa4ca96c05af3b52a572fc
20c9630bd323d7787eb5a1982f8c98c0fd1a9ecc
refs/heads/master
2021-01-22T23:57:52.712701
2012-03-30T13:49:14
2012-03-30T13:49:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,057
cpp
#include <QPushButton> #include "about.h" AboutDialog::AboutDialog() { /* build ui */ ui.setupUi(this); ui.closeButtonBox->addButton(new QPushButton("&Close", this), QDialogButtonBox::RejectRole); setWindowRole("csv2sql-about"); setMinimumSize(400, 300); resize(400, 300); setWindowModality(Qt::WindowModal); connect(ui.closeButtonBox, SIGNAL(rejected()), this, SLOT(close())); ui.closeButtonBox->setFocus(); ui.introduction->setText("CSV2SQL " APP_VERSION); ui.iconApp->setPixmap(QPixmap(":/images/logo")); /* Main Introduction */ ui.infoLabel->setText( "CSV2SQL is CSV -> SQL inject, " "for Adidas system.\n" "This version of csv2sql was compiled at: " __DATE__" " __TIME__"\n" "Copyright (C) 2012 AAA"); /* License */ ui.licenseEdit->setText("AAA"); /* People who helped */ ui.thanksEdit->setText(""); /* People who wrote the software */ ui.authorsEdit->setText(""); } void AboutDialog::close() { done(0); }
[ "wu.canus@gmail.com" ]
wu.canus@gmail.com
ebcba5075897623ba1eba0f5fe41ad9e399fc2fc
ab97a8915347c76d05d6690dbdbcaf23d7f0d1fd
/third_party/blink/renderer/modules/webgpu/gpu_render_pipeline.cc
2b44420412ced64b9d0d251c95a8b7e510c8cac3
[ "BSD-3-Clause", "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "MIT", "Apache-2.0" ]
permissive
laien529/chromium
c9eb243957faabf1b477939e3b681df77f083a9a
3f767cdd5c82e9c78b910b022ffacddcb04d775a
refs/heads/master
2022-11-28T00:28:58.669067
2020-08-20T08:37:31
2020-08-20T08:37:31
288,961,699
1
0
BSD-3-Clause
2020-08-20T09:21:57
2020-08-20T09:21:56
null
UTF-8
C++
false
false
12,113
cc
// 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 "third_party/blink/renderer/modules/webgpu/gpu_render_pipeline.h" #include "third_party/blink/renderer/bindings/core/v8/native_value_traits_impl.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_gpu_blend_descriptor.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_gpu_color_state_descriptor.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_gpu_depth_stencil_state_descriptor.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_gpu_rasterization_state_descriptor.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_gpu_render_pipeline_descriptor.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_gpu_stencil_state_face_descriptor.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_gpu_vertex_attribute_descriptor.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_gpu_vertex_buffer_layout_descriptor.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_gpu_vertex_state_descriptor.h" #include "third_party/blink/renderer/modules/webgpu/dawn_conversions.h" #include "third_party/blink/renderer/modules/webgpu/gpu_bind_group_layout.h" #include "third_party/blink/renderer/modules/webgpu/gpu_device.h" #include "third_party/blink/renderer/modules/webgpu/gpu_pipeline_layout.h" #include "third_party/blink/renderer/platform/bindings/exception_state.h" #include "third_party/blink/renderer/platform/bindings/script_state.h" namespace blink { namespace { WGPUBlendDescriptor AsDawnType(const GPUBlendDescriptor* webgpu_desc) { DCHECK(webgpu_desc); WGPUBlendDescriptor dawn_desc = {}; dawn_desc.dstFactor = AsDawnEnum<WGPUBlendFactor>(webgpu_desc->dstFactor()); dawn_desc.srcFactor = AsDawnEnum<WGPUBlendFactor>(webgpu_desc->srcFactor()); dawn_desc.operation = AsDawnEnum<WGPUBlendOperation>(webgpu_desc->operation()); return dawn_desc; } } // anonymous namespace WGPUColorStateDescriptor AsDawnType( const GPUColorStateDescriptor* webgpu_desc) { DCHECK(webgpu_desc); WGPUColorStateDescriptor dawn_desc = {}; dawn_desc.nextInChain = nullptr; dawn_desc.alphaBlend = AsDawnType(webgpu_desc->alphaBlend()); dawn_desc.colorBlend = AsDawnType(webgpu_desc->colorBlend()); dawn_desc.writeMask = AsDawnEnum<WGPUColorWriteMask>(webgpu_desc->writeMask()); dawn_desc.format = AsDawnEnum<WGPUTextureFormat>(webgpu_desc->format()); return dawn_desc; } namespace { WGPUStencilStateFaceDescriptor AsDawnType( const GPUStencilStateFaceDescriptor* webgpu_desc) { DCHECK(webgpu_desc); WGPUStencilStateFaceDescriptor dawn_desc = {}; dawn_desc.compare = AsDawnEnum<WGPUCompareFunction>(webgpu_desc->compare()); dawn_desc.depthFailOp = AsDawnEnum<WGPUStencilOperation>(webgpu_desc->depthFailOp()); dawn_desc.failOp = AsDawnEnum<WGPUStencilOperation>(webgpu_desc->failOp()); dawn_desc.passOp = AsDawnEnum<WGPUStencilOperation>(webgpu_desc->passOp()); return dawn_desc; } WGPUDepthStencilStateDescriptor AsDawnType( const GPUDepthStencilStateDescriptor* webgpu_desc) { DCHECK(webgpu_desc); WGPUDepthStencilStateDescriptor dawn_desc = {}; dawn_desc.nextInChain = nullptr; dawn_desc.depthCompare = AsDawnEnum<WGPUCompareFunction>(webgpu_desc->depthCompare()); dawn_desc.depthWriteEnabled = webgpu_desc->depthWriteEnabled(); dawn_desc.format = AsDawnEnum<WGPUTextureFormat>(webgpu_desc->format()); dawn_desc.stencilBack = AsDawnType(webgpu_desc->stencilBack()); dawn_desc.stencilFront = AsDawnType(webgpu_desc->stencilFront()); dawn_desc.stencilReadMask = webgpu_desc->stencilReadMask(); dawn_desc.stencilWriteMask = webgpu_desc->stencilWriteMask(); return dawn_desc; } using WGPUVertexStateInfo = std::tuple<WGPUVertexStateDescriptor, Vector<WGPUVertexBufferLayoutDescriptor>, Vector<WGPUVertexAttributeDescriptor>>; WGPUVertexStateInfo GPUVertexStateAsWGPUVertexState( v8::Isolate* isolate, const GPUVertexStateDescriptor* descriptor, ExceptionState& exception_state) { WGPUVertexStateDescriptor dawn_desc = {}; dawn_desc.indexFormat = AsDawnEnum<WGPUIndexFormat>(descriptor->indexFormat()); dawn_desc.vertexBufferCount = 0; dawn_desc.vertexBuffers = nullptr; Vector<WGPUVertexBufferLayoutDescriptor> dawn_vertex_buffers; Vector<WGPUVertexAttributeDescriptor> dawn_vertex_attributes; if (descriptor->hasVertexBuffers()) { // TODO(crbug.com/951629): Use a sequence of nullable descriptors. v8::Local<v8::Value> vertex_buffers_value = descriptor->vertexBuffers().V8Value(); if (!vertex_buffers_value->IsArray()) { exception_state.ThrowTypeError("vertexBuffers must be an array"); return std::make_tuple(dawn_desc, std::move(dawn_vertex_buffers), std::move(dawn_vertex_attributes)); } v8::Local<v8::Context> context = isolate->GetCurrentContext(); v8::Local<v8::Array> vertex_buffers = vertex_buffers_value.As<v8::Array>(); // First we collect all the descriptors but we don't set // WGPUVertexBufferLayoutDescriptor::attributes // TODO(cwallez@chromium.org): Should we validate the Length() first so we // don't risk creating HUGE vectors of WGPUVertexBufferLayoutDescriptor from // the sparse array? for (uint32_t i = 0; i < vertex_buffers->Length(); ++i) { // This array can be sparse. Skip empty slots. v8::MaybeLocal<v8::Value> maybe_value = vertex_buffers->Get(context, i); v8::Local<v8::Value> value; if (!maybe_value.ToLocal(&value) || value.IsEmpty() || value->IsNullOrUndefined()) { WGPUVertexBufferLayoutDescriptor dawn_vertex_buffer = {}; dawn_vertex_buffer.arrayStride = 0; dawn_vertex_buffer.stepMode = WGPUInputStepMode_Vertex; dawn_vertex_buffer.attributeCount = 0; dawn_vertex_buffer.attributes = nullptr; dawn_vertex_buffers.push_back(dawn_vertex_buffer); continue; } GPUVertexBufferLayoutDescriptor* vertex_buffer = NativeValueTraits<GPUVertexBufferLayoutDescriptor>::NativeValue( isolate, value, exception_state); if (exception_state.HadException()) { return std::make_tuple(dawn_desc, std::move(dawn_vertex_buffers), std::move(dawn_vertex_attributes)); } WGPUVertexBufferLayoutDescriptor dawn_vertex_buffer = {}; dawn_vertex_buffer.arrayStride = vertex_buffer->arrayStride(); dawn_vertex_buffer.stepMode = AsDawnEnum<WGPUInputStepMode>(vertex_buffer->stepMode()); dawn_vertex_buffer.attributeCount = static_cast<uint32_t>(vertex_buffer->attributes().size()); dawn_vertex_buffer.attributes = nullptr; dawn_vertex_buffers.push_back(dawn_vertex_buffer); for (wtf_size_t j = 0; j < vertex_buffer->attributes().size(); ++j) { const GPUVertexAttributeDescriptor* attribute = vertex_buffer->attributes()[j]; WGPUVertexAttributeDescriptor dawn_vertex_attribute = {}; dawn_vertex_attribute.shaderLocation = attribute->shaderLocation(); dawn_vertex_attribute.offset = attribute->offset(); dawn_vertex_attribute.format = AsDawnEnum<WGPUVertexFormat>(attribute->format()); dawn_vertex_attributes.push_back(dawn_vertex_attribute); } } // Set up pointers in DawnVertexBufferLayoutDescriptor::attributes only // after we stopped appending to the vector so the pointers aren't // invalidated. uint32_t attributeIndex = 0; for (WGPUVertexBufferLayoutDescriptor& buffer : dawn_vertex_buffers) { if (buffer.attributeCount == 0) { continue; } buffer.attributes = &dawn_vertex_attributes[attributeIndex]; attributeIndex += buffer.attributeCount; } } dawn_desc.vertexBufferCount = static_cast<uint32_t>(dawn_vertex_buffers.size()); dawn_desc.vertexBuffers = dawn_vertex_buffers.data(); return std::make_tuple(dawn_desc, std::move(dawn_vertex_buffers), std::move(dawn_vertex_attributes)); } WGPURasterizationStateDescriptor AsDawnType( const GPURasterizationStateDescriptor* webgpu_desc) { DCHECK(webgpu_desc); WGPURasterizationStateDescriptor dawn_desc = {}; dawn_desc.nextInChain = nullptr; dawn_desc.frontFace = AsDawnEnum<WGPUFrontFace>(webgpu_desc->frontFace()); dawn_desc.cullMode = AsDawnEnum<WGPUCullMode>(webgpu_desc->cullMode()); dawn_desc.depthBias = webgpu_desc->depthBias(); dawn_desc.depthBiasSlopeScale = webgpu_desc->depthBiasSlopeScale(); dawn_desc.depthBiasClamp = webgpu_desc->depthBiasClamp(); return dawn_desc; } } // anonymous namespace // static GPURenderPipeline* GPURenderPipeline::Create( ScriptState* script_state, GPUDevice* device, const GPURenderPipelineDescriptor* webgpu_desc) { DCHECK(device); DCHECK(webgpu_desc); std::string label; WGPURenderPipelineDescriptor dawn_desc = {}; dawn_desc.nextInChain = nullptr; if (webgpu_desc->hasLayout()) { dawn_desc.layout = AsDawnType(webgpu_desc->layout()); } if (webgpu_desc->hasLabel()) { label = webgpu_desc->label().Utf8(); dawn_desc.label = label.c_str(); } OwnedProgrammableStageDescriptor vertex_stage_info = AsDawnType(webgpu_desc->vertexStage()); dawn_desc.vertexStage = std::get<0>(vertex_stage_info); OwnedProgrammableStageDescriptor fragment_stage_info; if (webgpu_desc->hasFragmentStage()) { fragment_stage_info = AsDawnType(webgpu_desc->fragmentStage()); dawn_desc.fragmentStage = &std::get<0>(fragment_stage_info); } else { dawn_desc.fragmentStage = nullptr; } v8::Isolate* isolate = script_state->GetIsolate(); ExceptionState exception_state(isolate, ExceptionState::kConstructionContext, "GPUVertexStateDescriptor"); WGPUVertexStateInfo vertex_state_info = GPUVertexStateAsWGPUVertexState( isolate, webgpu_desc->vertexState(), exception_state); dawn_desc.vertexState = &std::get<0>(vertex_state_info); if (exception_state.HadException()) { return nullptr; } dawn_desc.primitiveTopology = AsDawnEnum<WGPUPrimitiveTopology>(webgpu_desc->primitiveTopology()); WGPURasterizationStateDescriptor rasterization_state; rasterization_state = AsDawnType(webgpu_desc->rasterizationState()); dawn_desc.rasterizationState = &rasterization_state; dawn_desc.sampleCount = webgpu_desc->sampleCount(); WGPUDepthStencilStateDescriptor depth_stencil_state = {}; if (webgpu_desc->hasDepthStencilState()) { depth_stencil_state = AsDawnType(webgpu_desc->depthStencilState()); dawn_desc.depthStencilState = &depth_stencil_state; } else { dawn_desc.depthStencilState = nullptr; } std::unique_ptr<WGPUColorStateDescriptor[]> color_states = AsDawnType(webgpu_desc->colorStates()); dawn_desc.colorStateCount = static_cast<uint32_t>(webgpu_desc->colorStates().size()); dawn_desc.colorStates = color_states.get(); dawn_desc.sampleMask = webgpu_desc->sampleMask(); dawn_desc.alphaToCoverageEnabled = webgpu_desc->alphaToCoverageEnabled(); return MakeGarbageCollected<GPURenderPipeline>( device, device->GetProcs().deviceCreateRenderPipeline(device->GetHandle(), &dawn_desc)); } GPURenderPipeline::GPURenderPipeline(GPUDevice* device, WGPURenderPipeline render_pipeline) : DawnObject<WGPURenderPipeline>(device, render_pipeline) {} GPURenderPipeline::~GPURenderPipeline() { if (IsDawnControlClientDestroyed()) { return; } GetProcs().renderPipelineRelease(GetHandle()); } GPUBindGroupLayout* GPURenderPipeline::getBindGroupLayout(uint32_t index) { return MakeGarbageCollected<GPUBindGroupLayout>( device_, GetProcs().renderPipelineGetBindGroupLayout(GetHandle(), index)); } } // namespace blink
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
05a3fa4e764da6e7c9614bb002a9d5babcb94615
a89bd048287b91f8fe958809b6c958bc45c1aec8
/include/rtl/PerspectiveCamera.h
6358baf3ffd7fb1df1aec107412cb67952e76f5b
[ "MIT" ]
permissive
potato3d/rtrt
8b739300bed61a5336fe3a230e6384f897d74c61
cac9f2f80d94bf60adf0bbd009f5076973ee10c6
refs/heads/main
2023-03-02T11:23:52.096304
2021-02-13T03:36:56
2021-02-13T03:36:56
338,484,429
2
0
null
null
null
null
UTF-8
C++
false
false
1,500
h
#pragma once #ifndef _RTL_PERSPECTIVECAMERA_H_ #define _RTL_PERSPECTIVECAMERA_H_ #include <rts/ICamera.h> #include <rtu/float3.h> #include <rtu/quat.h> #include <rtu/sse.h> namespace rtl { class PerspectiveCamera : public rts::ICamera { public: virtual void init(); virtual void newFrame(); virtual void receiveParameter( int paramId, void* paramValue ); virtual void lookAt( float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ ); virtual void setPerspective( float fovY, float zNear, float zFar ); virtual void setViewport( unsigned int width, unsigned int height ); virtual void getViewport( unsigned int& width, unsigned int& height ); virtual void getRay( rts::RTstate& state, float x, float y ); virtual void getRayPacket( rts::RTstate& state, float* rayXYCoords ); private: // Has changed since the last update? bool _dirty; // Input parameters rtu::float3 _position; rtu::quatf _orientation; float _fovy; float _zNear; float _zFar; unsigned int _screenWidth; unsigned int _screenHeight; // Derived values rtu::float3 _axisX; // camera axes rtu::float3 _axisY; rtu::float3 _axisZ; rtu::float3 _nearOrigin; // near plane origin rtu::float3 _nearU; // near plane U vector rtu::float3 _nearV; // near plane V vector // Pre-computation float _invWidth; float _invHeight; rtu::float3 _baseDir; }; } // namespace rts #endif // _RTL_PERSPECTIVECAMERA_H_
[ "" ]
4c33aa8c2265575cf636f324549baa51f05c6940
e642f1e4cc822114c8a3651cbe51dabb95c85716
/ift-demo/demo/watershed/kernels/dijk.cpp
13f18dd6b7d5748192c3654c3bde9e7ea275fa28
[ "BSD-3-Clause" ]
permissive
gagallo7/OpenCLStudy
e80cd8d0339d1fafaa8860f2d2e6a161418a243e
d054115addb7831725f816eb7f4d54b81f1f14bc
refs/heads/master
2021-01-19T10:59:10.373979
2014-04-01T01:11:19
2014-04-01T01:11:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
20,572
cpp
#include <iostream> #include <iomanip> #include <fstream> #include <sstream> #include <string> #include <string.h> #include <vector> #include <list> #ifdef __APPLE__ #include <OpenCL/cl.h> #else #include <CL/cl.h> #endif #if !defined(CL_CALLBACK) #define CL_CALLBACK #endif #define INF 1 << 30 using namespace std; void log (vector < unsigned int > v, char *argv[]) { FILE* fp; char local[50] = "logs/"; strcat(local, argv[2]); //cout << local << endl; fp = fopen(local,"w"); for (int i=0; i<v.size(); i++) { fprintf(fp, "%d\n", v[i]); } fclose(fp); } bool vazio (vector < unsigned int > M) { for (int i = 0; i < M.size(); i++) { if (M[i] == true) return false; } return true; } class grafo { public: int numV; // Numero de vertices vector < cl_uint > vert; // Vetor de vertices vector < cl_uint > arestas; // Vetor de arestas vector < cl_uint > pesos; // Vetor de pesos void make_graph (FILE *); void make_graph9 (FILE *); void make_graph558 (FILE *, int* ); void printInfo (void); void prepare (vector < cl_uint >&, vector < cl_uint >&, vector < cl_uint >&); }; // Cria grafo no modelo da disciplina de MC558 // Primeira linha tem o numero de vertices seguido do numero total // de arestas do grafo. void grafo::make_graph558 ( FILE* fp, int* raiz ) { char linha[2000]; vector < unsigned int > a_tmp, p_tmp, v_tmp; vector < list < vector < unsigned int > > > la; if (fp==NULL) { cout << "Erro ao abrir arquivo!" << endl; return; } // Primeiro vertice comeca sua lista de adjacencias em 0 //vert.push_back(0); // Cada linha tem a representacao de cada vertice // fgets limita-se a capturar uma linha int i, o, peso; int numA; // Coletando a primeira linha, a qual armazena o numero // de vertices do grafo if (fgets (linha, 2000, fp) != NULL) { sscanf(linha, " %d %d", &numV, &numA); } la.resize(numV+1); //cout << numV << endl; int nLinha = 0; // Coletando as arestas while (fgets (linha, 2000, fp) != NULL) { //int ant = -1; // Capturando o vertice if (nLinha < numA) { // Se o vertice tiver arestas sscanf(linha," %d %d %d", &i, &o, &peso); // Caso de fim de linha, pois nao ha arestas iguais // Logo o destino nao pode ser o mesmo // cout << i << " " << o << " " << peso; // ant = i; vector < unsigned int > novo; novo.push_back(o); novo.push_back(peso); la[i].push_back(novo); } else { sscanf(linha," %d", raiz); break; } nLinha++; /* */ // Apontando para a proxima lista de adjacencias //vert.push_back(arestas.size()); } fclose(fp); list < vector < unsigned int > >::iterator ll; int j = 0; for (int i = 0; i < numV; i++) { vert.push_back(j); for (ll = la[i].begin(); ll != la[i].end(); ll++) { j++; arestas.push_back((*ll)[0]); pesos.push_back((*ll)[1]); } } vert.push_back(j); // Arestas do ultimo vertice } // Cria grafo baseado no modelo do DIMACS9 // DIMACS usa o seguinte modelo: // Cada linha tem o vertice de origem e saida e também o peso de // cada aresta // void grafo::make_graph9 ( FILE* fp ) { char linha[2000]; vector < unsigned int > a_tmp, p_tmp, v_tmp; vector < list < vector < unsigned int > > > la; if (fp==NULL) { cout << "Erro ao abrir arquivo!" << endl; return; } // Primeiro vertice comeca sua lista de adjacencias em 0 //vert.push_back(0); // Cada linha tem a representacao de cada vertice // fgets limita-se a capturar uma linha int i, o, peso; // Coletando a primeira linha, a qual armazena o numero // de vertices do grafo if (fgets (linha, 2000, fp) != NULL) { sscanf(linha, " %d", &numV); } la.resize(numV+1); cout << numV << endl; // Coletando as arestas while (fgets (linha, 2000, fp) != NULL) { //int ant = -1; // Capturando o vertice if (*linha != '-') { // Se o vertice tiver arestas sscanf(linha," %d %d %d", &i, &o, &peso); // Caso de fim de linha, pois nao ha arestas iguais // Logo o destino nao pode ser o mesmo cout << i << " " << o << " " << peso; // ant = i; vector < unsigned int > novo; novo.push_back(o); novo.push_back(peso); la[i].push_back(novo); } /* */ // Apontando para a proxima lista de adjacencias //vert.push_back(arestas.size()); } fclose(fp); list < vector < unsigned int > >::iterator ll; int j = 0; for (int i = 0; i < numV; i++) { vert.push_back(j); for (ll = la[i].begin(); ll != la[i].end(); ll++) { j++; arestas.push_back((*ll)[0]); pesos.push_back((*ll)[1]); } } vert.push_back(j); // Arestas do ultimo vertice } // Cria grafo baseado no modelo do DIMACS // DIMACS usa o seguinte modelo: // Cada linha tem o vertice de origem e o resto da linha sao // as arestas do mesmo vertice void grafo::make_graph(FILE *fp) { char linha[2000]; if (fp==NULL) { cout << "Erro ao abrir arquivo!" << endl; return; } // Primeiro vertice comeca sua lista de adjacencias em 0 vert.push_back(0); // Cada linha tem a representacao de cada vertice // fgets limita-se a capturar uma linha int i, peso; while (fgets (linha, 2000, fp) != NULL) { int ant = -1; // Capturando o vertice if (*linha != '\n') // Se o vertice tiver arestas while(1) { sscanf(linha," %d %d %[0-9 ]", &i, &peso, linha); // Caso de fim de linha, pois nao ha arestas iguais // Logo o destino nao pode ser o mesmo if (ant == i) { break; } cout << i << " "; ant = i; arestas.push_back(i); pesos.push_back(peso); } /* */ // Apontando para a proxima lista de adjacencias vert.push_back(arestas.size()); } fclose(fp); numV = vert.size() - 1; // A representacao faz com que tenha mais um elemento no vetor de vertices } void grafo::printInfo () { cout << "Vetor de vertices:" << endl; vector < cl_uint >::iterator it, it2; for (it=vert.begin();it!=vert.end();it++) { cout << *it << " "; } cout << endl; cout << "Vetor de arestas:" << endl; it2 = pesos.begin(); for (it=arestas.begin();it!=arestas.end();it++) { cout << *it << ":" << *it2 << " "; it2++; } cout << endl; } // Retorna a proxima potencia de 2 baseado numa entrada cl_uint nextPow2 (int n) { cl_uint p = 2; while (p < n && 2*p) p *= 2; return p; } void prepare (vector < cl_uint >& M, vector < cl_uint >& C, vector < cl_uint >& U, int numV, int s) { cl_uint inf = 1 << 30; // Infinito M.resize(numV,0); C.resize(numV, inf); U.resize(numV, inf); M[s] = true; C[s] = 0; U[s] = 0; } void infoPlataforma (cl_platform_id * listaPlataformaID, cl_uint i) { cl_int err; size_t size; err = clGetPlatformInfo(listaPlataformaID[i], CL_PLATFORM_NAME, 0, NULL, &size); char * name = (char *)alloca(sizeof(char) * size); err = clGetPlatformInfo(listaPlataformaID[i], CL_PLATFORM_NAME, size, name, NULL); err = clGetPlatformInfo(listaPlataformaID[i], CL_PLATFORM_VENDOR, 0, NULL, &size); char * vname = (char *)alloca(sizeof(char) * size); err = clGetPlatformInfo(listaPlataformaID[i], CL_PLATFORM_VENDOR, size, vname, NULL); std::cout << "Platform name: " << name << std::endl << "Vendor name : " << vname << std::endl; } // Checagem de erros inline void checkErr(cl_int err, const char *name) { if(err!=CL_SUCCESS) { std::cerr << "ERRO: " << name << " (" << err << ")" << std::endl; exit(EXIT_FAILURE); } } void CL_CALLBACK contextCallback ( const char *errInfo, const void *private_info, size_t cb, void *user_data ) { std::cout << "Ocorreu um erro durante o uso do context: " << errInfo << std::endl; // Ignorando limpeza de memória e saindo diretamente exit(1); } int main(int argc, char *argv[]) { cl_int errNum; cl_uint nPlataformas; cl_uint nDispositivos; cl_platform_id *listaPlataformaID; cl_device_id *listaDispositivoID; cl_context contexto = NULL; cl_command_queue fila; cl_program programa, programa2; cl_kernel kernel, kernel2; cl_mem Vbuffer; cl_mem Abuffer; cl_mem Pbuffer; cl_mem Mbuffer; cl_mem Cbuffer; cl_mem Ubuffer; cl_mem SEMbuffer; cl_mem numVbuffer; cl_event evento; int raiz; cout << "Abrindo arquivo... " << endl; // Abrindo arquivo de entrada FILE *fp = fopen(argv[1], "r"); if (argc > 2) raiz = atoi(argv[2]); grafo g; // Criando vetores auxiliares vector < cl_uint > C, U, M; // Criando Grafo cout << "Montando grafo... " << endl; //g.make_graph9(fp); g.make_graph558(fp, &raiz); // Preparando vetores auxiliares para o Dijkstra cout << endl << "Preparando... raiz em: " << raiz << endl; prepare(M, C, U, g.numV, raiz); //g.printInfo(); cout << "Vetores prontos. " << endl; cout << "Numero de workitems: " << nextPow2(g.arestas.size()) << endl; ///// Selecionando uma plataforma OpenCL para rodar // Atribuindo a nPlataformas o número de plataformas disponíveis errNum = clGetPlatformIDs(0, NULL, &nPlataformas); checkErr( (errNum != CL_SUCCESS) ? errNum : (nPlataformas <= 0 ? -1 : CL_SUCCESS), "clGetPlataformsIDs"); // Se não houve erro, alocar memória para cl_platform_id listaPlataformaID = (cl_platform_id *)alloca(sizeof(cl_platform_id)*nPlataformas); // Atribuindo uma plataforma ao listaPlataformaID errNum = clGetPlatformIDs(nPlataformas, listaPlataformaID, NULL); std::cout << "#Plataformas: " << nPlataformas << std::endl; checkErr( (errNum != CL_SUCCESS) ? errNum : (nPlataformas <= 0 ? -1 : CL_SUCCESS), "clGetPlatformIDs"); // Iterando na lista de plataformas até achar uma que suporta um dispositivo de CPU. Se isso não ocorrer, acusar erro. cl_uint i; for (i=0; i < nPlataformas; i++) { // Atribuindo o número de dispositivos de GPU a nDispositivos errNum = clGetDeviceIDs ( listaPlataformaID[i], // CL_DEVICE_TYPE_ALL, //CL_DEVICE_TYPE_CPU, CL_DEVICE_TYPE_GPU, 0, NULL, &nDispositivos ); if (errNum != CL_SUCCESS && errNum != CL_DEVICE_NOT_FOUND) { infoPlataforma(listaPlataformaID, i); checkErr (errNum, "clGetDeviceIDs"); } // Conferindo se há dispositivos de CPU else if (nDispositivos > 0) { // Atribuindo um dispositivo a uma listaDispositivoID listaDispositivoID = (cl_device_id *)alloca(sizeof(cl_device_id)*nDispositivos); errNum = clGetDeviceIDs ( listaPlataformaID[i], // CL_DEVICE_TYPE_ALL, // CL_DEVICE_TYPE_CPU, CL_DEVICE_TYPE_GPU, nDispositivos, &listaDispositivoID[0], NULL); checkErr(errNum, "clGetPlatformIDs"); break; } } // Crindo um contexto no dispositivo/plataforma selecionada std::cout << "Adicionando dispositivos OpenCL de numero " << i << std::endl; infoPlataforma(listaPlataformaID, i); cl_context_properties propContexto[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)listaPlataformaID[i], 0 }; contexto = clCreateContext( propContexto, nDispositivos, listaDispositivoID, &contextCallback, NULL, &errNum ); checkErr(errNum, "clCreateContext"); // Carregando o arquivo-fonte cl para póstuma compilação feita em runtime std::ifstream srcFile("dijkstra.cl"); // Conferindo se ele foi aberto checkErr(srcFile.is_open() ? CL_SUCCESS : -1, "lendo dijkstra.cl"); std::string srcProg ( std::istreambuf_iterator<char>(srcFile), (std::istreambuf_iterator<char>())); const char *fonte = srcProg.c_str(); size_t tamanho = srcProg.length(); // Criando programa da fonte programa = clCreateProgramWithSource ( contexto, 1, &fonte, &tamanho, &errNum); checkErr(errNum, "clCreateProgramWithSource"); // Criando programa da fonte do kernel2 // Carregando o arquivo-fonte cl para póstuma compilação feita em runtime std::ifstream srcFile2("kernel2.cl"); // Conferindo se ele foi aberto checkErr(srcFile2.is_open() ? CL_SUCCESS : -1, "lendo kernel2.cl"); std::string srcProg2 ( std::istreambuf_iterator<char>(srcFile2), (std::istreambuf_iterator<char>())); const char *fonte2 = srcProg2.c_str(); tamanho = srcProg2.length(); programa2 = clCreateProgramWithSource ( contexto, 1, &fonte2, &tamanho, &errNum); checkErr(errNum, "clCreateProgramWithSource"); /* */ // Compilando programa errNum = clBuildProgram ( programa, nDispositivos, listaDispositivoID, NULL, NULL, NULL); errNum = clBuildProgram ( programa2, nDispositivos, listaDispositivoID, NULL, NULL, NULL); if (errNum != CL_SUCCESS) { // Verificando se houve erro // Determinando o motivo do erro char logCompilacao[16384]; clGetProgramBuildInfo ( programa, listaDispositivoID[0], CL_PROGRAM_BUILD_LOG, sizeof(logCompilacao), logCompilacao, NULL); std::cerr << "Erro no kernel: " << std::endl; std::cerr << logCompilacao; checkErr(errNum, "clBuildProgram"); } // Criando o objeto do Kernel kernel = clCreateKernel ( programa, "dijkstra", &errNum); checkErr(errNum, "clCreateKernel"); // Criando o objeto do Kernel2 kernel2 = clCreateKernel ( programa2, "dijkstra2", &errNum); checkErr(errNum, "clCreateKernel2"); // Alocando Buffers Vbuffer = clCreateBuffer ( contexto, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(int) * g.vert.size(), g.vert.data(), &errNum); checkErr(errNum, "clCreateBuffer(V)"); Abuffer = clCreateBuffer ( contexto, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(int) * g.arestas.size(), g.arestas.data(), &errNum); checkErr(errNum, "clCreateBuffer(A)"); Pbuffer = clCreateBuffer ( contexto, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(int) * g.pesos.size(), g.pesos.data(), &errNum); checkErr(errNum, "clCreateBuffer(P)"); Ubuffer = clCreateBuffer ( contexto, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(int) * U.size(), U.data(), &errNum); checkErr(errNum, "clCreateBuffer(U)"); Mbuffer = clCreateBuffer ( contexto, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(int) * M.size(), M.data(), &errNum); checkErr(errNum, "clCreateBuffer(M)"); Cbuffer = clCreateBuffer ( contexto, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(int) * C.size(), C.data(), &errNum); checkErr(errNum, "clCreateBuffer(C)"); int semaforo = 0; SEMbuffer = clCreateBuffer ( contexto, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(int), &semaforo, &errNum); checkErr(errNum, "clCreateBuffer(semaforo)"); int numV = g.vert.size(); numVbuffer = clCreateBuffer ( contexto, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(int), &numV, &errNum); checkErr(errNum, "clCreateBuffer(numero_de_vertices)"); /* Bbuffer = clCreateBuffer ( contexto, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(cl_uint)*m*n, (B), &errNum); checkErr(errNum, "clCreateBuffer(B)"); Cbuffer = clCreateBuffer ( contexto, CL_MEM_WRITE_ONLY, sizeof(cl_uint)*l*n, NULL, &errNum); checkErr(errNum, "clCreateBuffer(C)"); */ // Escolhendo o primeiro dispositivo e criando a fila de comando fila = clCreateCommandQueue ( contexto, listaDispositivoID[0], CL_QUEUE_PROFILING_ENABLE, &errNum); checkErr(errNum, "clCreateCommandQueue"); // Setando os argumentos da função do Kernel errNum = clSetKernelArg(kernel, 0, sizeof(cl_mem), &Vbuffer); errNum |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &Abuffer); errNum |= clSetKernelArg(kernel, 2, sizeof(cl_mem), &Pbuffer); errNum |= clSetKernelArg(kernel, 3, sizeof(cl_mem), &Mbuffer); errNum |= clSetKernelArg(kernel, 4, sizeof(cl_mem), &Cbuffer); errNum |= clSetKernelArg(kernel, 5, sizeof(cl_mem), &Ubuffer); errNum |= clSetKernelArg(kernel, 6, sizeof(cl_mem), &SEMbuffer); errNum |= clSetKernelArg(kernel, 7, sizeof(cl_mem), &numVbuffer); /* */ // Setando os argumentos da função do Kernel2 errNum = clSetKernelArg(kernel2, 0, sizeof(cl_mem), &Vbuffer); errNum |= clSetKernelArg(kernel2, 1, sizeof(cl_mem), &Abuffer); errNum |= clSetKernelArg(kernel2, 2, sizeof(cl_mem), &Pbuffer); errNum |= clSetKernelArg(kernel2, 3, sizeof(cl_mem), &Mbuffer); errNum |= clSetKernelArg(kernel2, 4, sizeof(cl_mem), &Cbuffer); errNum |= clSetKernelArg(kernel2, 5, sizeof(cl_mem), &Ubuffer); errNum |= clSetKernelArg(kernel2, 6, sizeof(cl_mem), &SEMbuffer); errNum |= clSetKernelArg(kernel2, 7, sizeof(cl_mem), &numVbuffer); checkErr(errNum, "clSetKernelArg"); // Definindo o número de work-items globais e locais const size_t globalWorkSize[1] = { g.numV }; const size_t localWorkSize[1] = { 1 }; // releituraFeita e um evento que sincroniza a atualizacao feita // por cada chamada aos kernels cl_event releituraFeita; errNum = clEnqueueReadBuffer(fila, Mbuffer, CL_FALSE, 0, sizeof(int) * M.size(), M.data(), 0, NULL, &releituraFeita); checkErr(errNum, CL_SUCCESS); clWaitForEvents(1, &releituraFeita); while(!vazio(M)) { /* std::cout << endl << "Mask: " << std::endl; for(int i=0; i<M.size(); i++) { cout << M[i] << " "; } */ // Enfileirando o Kernel para execução através da matriz errNum = clEnqueueNDRangeKernel ( fila, kernel, 1, NULL, globalWorkSize, localWorkSize, 0, NULL, &evento); checkErr(errNum, "clEnqueueNDRangeKernel"); // Enfileirando o Kernel2 para execução através da matriz errNum = clEnqueueNDRangeKernel ( fila, kernel2, 1, NULL, globalWorkSize, localWorkSize, 0, NULL, &evento); checkErr(errNum, "clEnqueueNDRangeKernel2"); errNum = clEnqueueReadBuffer(fila, Mbuffer, CL_FALSE, 0, sizeof(int) * M.size(), M.data(), 0, NULL, &releituraFeita); checkErr(errNum, CL_SUCCESS); clWaitForEvents(1, &releituraFeita); } cl_ulong ev_start_time=(cl_ulong)0; cl_ulong ev_end_time=(cl_ulong)0; clFinish(fila); errNum = clWaitForEvents(1, &evento); errNum |= clGetEventProfilingInfo(evento, CL_PROFILING_COMMAND_START, sizeof(cl_ulong), &ev_start_time, NULL); errNum |= clGetEventProfilingInfo(evento, CL_PROFILING_COMMAND_END, sizeof(cl_ulong), &ev_end_time, NULL); double run_time_gpu = (double)(ev_end_time - ev_start_time); // in usec errNum = clEnqueueReadBuffer ( fila, Mbuffer, CL_TRUE, 0, sizeof(cl_uint) * M.size(), M.data(), 0, NULL, NULL); checkErr(errNum, "clEnqueueReadBuffer"); /* errNum = clEnqueueReadBuffer ( fila, Vbuffer, CL_TRUE, 0, sizeof(cl_uint) * g.vert.size(), g.vert.data(), 0, NULL, NULL); checkErr(errNum, "clEnqueueReadBuffer"); errNum = clEnqueueReadBuffer ( fila, Abuffer, CL_TRUE, 0, sizeof(cl_uint) * g.arestas.size(), g.arestas.data(), 0, NULL, NULL); checkErr(errNum, "clEnqueueReadBuffer"); errNum = clEnqueueReadBuffer ( fila, Pbuffer, CL_TRUE, 0, sizeof(cl_uint) * g.pesos.size(), g.pesos.data(), 0, NULL, NULL); checkErr(errNum, "clEnqueueReadBuffer"); */ errNum = clEnqueueReadBuffer ( fila, Cbuffer, CL_TRUE, 0, sizeof(cl_uint) * C.size(), C.data(), 0, NULL, NULL); checkErr(errNum, "clEnqueueReadBuffer"); errNum = clEnqueueReadBuffer ( fila, Ubuffer, CL_TRUE, 0, sizeof(cl_uint) * U.size(), U.data(), 0, NULL, NULL); checkErr(errNum, "clEnqueueReadBuffer"); /* std::cout << endl << "Vertices: " << std::endl; for(int i=0; i<g.vert.size(); i++) { cout << g.vert[i] << " "; } std::cout << endl << "Arestas: " << std::endl; for(int i=0; i<g.arestas.size(); i++) { cout << g.arestas[i] << " "; } std::cout << endl << "Mask: " << std::endl; for(int i=0; i<g.vert.size() - 1; i++) { cout << M[i] << " "; } std::cout << endl << "Pesos: " << std::endl; for(int i=0; i<g.arestas.size(); i++) { cout << g.pesos[i] << " "; } std::cout << std::endl; cout << setw(6) << setfill('0'); std::cout << "Update: " << std::endl; for(int i=0; i<g.numV; i++) { if (i%8==0) cout << std::endl; if (U[i] < INF) { cout << setw(6) << setfill(' ') << i << ":" << U[i] << " "; } else { cout << setw(6) << setfill(' ') << i << ":" << "INF " << " "; } } std::cout << std::endl; std::cout << "Cost: " << std::endl; for(int i=0; i<g.numV; i++) { if (i%8==0) cout << std::endl; if (C[i] < INF) { cout << setw(6) << setfill(' ')<< i << ":" << C[i] << " "; } else { cout << setw(6) << setfill(' ') << i << ":" << "INF " << " "; } } std::cout << std::endl; */ std::cout << std::endl << std::fixed; std::cout << "Tempo de execução: " << std::setprecision(6) << run_time_gpu/1000000 << " ms"; std::cout << std::endl; std::cout << run_time_gpu*1.0e-6; std::cout << std::endl; log(U, argv); return 0; }
[ "gagallo7@gmail.com" ]
gagallo7@gmail.com
1a5c75672ef92b2aeb6f371a76f307acf2e65505
4c61aafa94f3bfdc86e2b6218a92eabf2d1f1a2d
/PID.h
fb90c28ed281bfa4b29952a96d70fe61d2bc9a7d
[]
no_license
sriki-duplicate/CarND-PID-Control-Project
452e11e3cafc0cd00e1be4e1054391c56fefa529
17037e9579c8256a831b27de666a2d246d96a333
refs/heads/master
2021-08-19T14:48:52.669782
2017-11-26T18:27:53
2017-11-26T18:27:53
112,032,799
0
0
null
null
null
null
UTF-8
C++
false
false
1,026
h
#ifndef PID_H #define PID_H #include <vector> class PID { public: /* * Errors */ double p_error; double i_error; double d_error; /* * Coefficients */ double Kp; double Ki; double Kd; /* * Twiddle variables */ std::vector<double> dp; int step, param_index; // number of steps to allow changes to settle, then to evaluate error int n_settle_steps, n_eval_steps; double total_error, best_error; bool tried_adding, tried_subtracting, yes_i_wanna_twiddle; /* * Constructor */ PID(); /* * Destructor. */ virtual ~PID(); /* * Initialize PID. */ void Init(double Kp, double Ki, double Kd); /* * Update the PID error variables given cross track error. */ void UpdateError(double cte); /* * Calculate the total PID error. */ double TotalError(); /* * Convenience function for adding amount (dp) to a PID controller parameter based on index */ void AddToParameterAtIndex(int index, double amount); }; #endif /* PID_H */
[ "noreply@github.com" ]
sriki-duplicate.noreply@github.com
1ec8b8e4d9ed980f9e1e2af57163eb3ec27af8e6
d20876df1308f1eaf3c280f6d3dd78c47633a2d8
/src/Corrade/PluginManager/Test/generated-metadata/GeneratedMetadataDynamic.cpp
ca30521c89c656d9f9cc585d72c5f90cd032af29
[ "MIT", "LicenseRef-scancode-public-domain", "Unlicense" ]
permissive
mosra/corrade
729ff71a9c8ceb7d27507b635be6433114b963bf
183b375b73fa3e819a6b41dbcc0cf2f06773d2b4
refs/heads/master
2023-08-24T21:56:12.599589
2023-08-23T14:07:19
2023-08-24T09:43:55
2,863,909
470
143
NOASSERTION
2023-09-12T02:52:28
2011-11-28T00:51:12
C++
UTF-8
C++
false
false
1,865
cpp
/* This file is part of Corrade. Copyright © 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Vladimír Vondruš <mosra@centrum.cz> 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 "../AbstractGeneratedMetadata.h" #include "Corrade/PluginManager/AbstractManager.h" namespace Corrade { namespace PluginManager { namespace Test { struct GeneratedMetadataDynamic: AbstractGeneratedMetadata { explicit GeneratedMetadataDynamic(AbstractManager& manager, const Containers::StringView& plugin): AbstractGeneratedMetadata{manager, plugin} {} }; }}} CORRADE_PLUGIN_REGISTER(GeneratedMetadataDynamic, Corrade::PluginManager::Test::GeneratedMetadataDynamic, "cz.mosra.corrade.PluginManager.Test.AbstractGeneratedMetadata/1.0")
[ "mosra@centrum.cz" ]
mosra@centrum.cz
b804810e42ce1e17cd78f8cbd0738e37a55a37f0
186bb5a81666d27b7576732a35bf5a412b33224b
/exceptions/main.cpp
bc29ebeff5b0ba4e0f4141067b4c0b9731bda83f
[ "MIT" ]
permissive
VgTajdd/cpp_playground
9de305821ecb53539a676097693f5f9039e9ccc9
7d91940f2404ae96a8f66cc6aac4334efca7b245
refs/heads/master
2023-06-07T18:12:38.826641
2023-09-17T19:19:19
2023-06-06T17:29:33
213,281,912
2
0
null
null
null
null
WINDOWS-1252
C++
false
false
4,076
cpp
#include <iostream> /* An exception is an error condition. */ double division( int a, int b ) { if ( b == 0 ) { throw std::exception( "Division by zero condition!" ); } return ( a / b ); } class Entity { public: Entity() { std::cout << "Entity created!" << std::endl; } ~Entity() { std::cout << "Entity destroyed!" << std::endl; } }; class A { public: A() {}; ~A() noexcept( false ) // Destructors are by defualt noexecpt, so this ('noexcept(false)') will turn-off the compiler warning. { throw std::exception{}; // AVOID THROW EXCEPTIONS OUT OF DESTRUCTORS because destructors are called // during stack unwinding when an exception is thrown, // and we are not allowed to throw another exception while the previous one is // not caught – in such a case std::terminate will be called. // http://www.vishalchovatiya.com/7-best-practices-for-exception-handling-in-cpp-with-example/ } }; struct base { ~base() noexcept( false ) { throw 1; } }; struct derive : base { ~derive() noexcept( false ) { throw 2; } }; // Custom exception. struct MyException : public std::exception { const char* what() const throw ( ) { return "Custom exception"; } }; int main() { // Simple example. { try { throw 20; } catch ( int e ) { std::cout << "An exception occurred! Exception: " << e << std::endl; } } // https://en.cppreference.com/w/cpp/language/try_catch { try { division( 10, 0 ); } catch ( const std::overflow_error& /*e*/ ) { // this executes if division() throws std::overflow_error (same type rule) } catch ( const std::runtime_error& /*e*/ ) { // this executes if division() throws std::underflow_error (base class rule) } catch ( const std::exception& e ) { std::cout << e.what() << std::endl; // this executes if division() throws std::exception (same type rule) // this executes if division() throws std::logic_error (base class rule) } catch ( ... ) { std::cout << "An exception occurred!" << std::endl; // this executes if division() throws std::string or int or any other unrelated type } } // Exceptions in destructors. { try { A a; } catch ( ... ) {} } #if 0 // An exception will be thrown when the object d will be destroyed as a result of RAII. // But at the same time destructor of base will also be called as it is sub - object of derive // which will again throw an exception.Now we have two exceptions at the same time which // is invalid scenario & std::terminate will be called. { try { derive a; } catch ( ... ) {} } #endif std::cout << "----------------" << std::endl; std::cout << "Exception safety" << std::endl; std::cout << "----------------" << std::endl; // This code is exception safe. { try { std::unique_ptr< Entity > entity = std::make_unique< Entity >(); throw std::exception( "Custom exception!" ); // The destructor of Entity is called when scope ends. } catch ( ... ) { // Code to handle the exception. } } std::cout << "----------------" << std::endl; // This code is no exception safe. { try { Entity* entity = new Entity; throw std::exception( "Custom exception!" ); delete entity; // This won't be called! } catch ( ... ) { // Code to handle the exception. } } std::cin.get(); return 0; }
[ "aduranddiaz@gmail.com" ]
aduranddiaz@gmail.com
f06585d106b12a765e5f0e62c54cc0f9436209cd
e6ae6070d3053ca1e4ff958c719a8cf5dfcd6b9b
/sum_to_prime_spoj.cpp
f7883717e6b737c7893878b4eeb3553bcbe5faa1
[]
no_license
Arti14/Competitive-Programming
31d246d34581599219ffb7e23a3372f02fc6dfa6
de42977b6cce39bb480d3cf90c1781d806be3b56
refs/heads/master
2021-01-25T07:34:29.240567
2015-05-08T07:07:10
2015-05-08T07:07:10
35,263,950
0
0
null
null
null
null
UTF-8
C++
false
false
1,260
cpp
#include <iostream> #include <cmath> #include <vector> using namespace std; vector < int > arr; int dp[4][8000]; int cnt(int m, int n) { if(n==0) { return 1; } if(n<0) { return 0; } if (m <=0 && n >= 1) { return 0; } if (dp[m][n] == 0) { dp[m][n] = cnt(m - 1, n) + cnt(m, n - m); } return dp[m][n]; } int main() { int T; int Sp2n[501]; int count=1; for (int i = 0; i < 8000; ++i) { for (int j = 0; j < 4; ++j) { dp[j][i] = 0; } } cnt(3, 7994); for(int i=2;i<7994;i++) { int j; if(count==1) { Sp2n[count]=2; count++; continue; } for(j=2;j<=sqrt(i);j++) { if(i%j==0) { break; } } if(j>sqrt(i)&&(i-1)%4==0) { Sp2n[count]=i; count++; } } cin>>T; while(T--) { int n, k; cin>>n>>k; int p=cnt(k,Sp2n[n]); cout<<p<<endl; } }
[ "rt@rt-VGN-CS14G-B.(none)" ]
rt@rt-VGN-CS14G-B.(none)
bfe76ae9c060dec1266a80d5c27c80e019148545
a3ec7ce8ea7d973645a514b1b61870ae8fc20d81
/Codeforces/A/404.cc
f978cf5c38a0d91457842b3f31fea7221820d6d7
[]
no_license
userr2232/PC
226ab07e3f2c341cbb087eecc2c8373fff1b340f
528314b608f67ff8d321ef90437b366f031e5445
refs/heads/master
2022-05-29T09:13:54.188308
2022-05-25T23:24:48
2022-05-25T23:24:48
130,185,439
1
0
null
null
null
null
UTF-8
C++
false
false
1,515
cc
#include <iostream> #include <vector> #include <set> using namespace std; int main() { int n; cin >> n; bool out = false; vector<string> sq; set<char> all_set; for(int i = 0; i < n && !out; ++i) { string tmp; cin >> tmp; sq.push_back(tmp); set<char> tmp_set; for(auto c : tmp) { tmp_set.insert(c); all_set.insert(c); if(all_set.size() > 2) { cout << "NO" << endl; out = true; break; } } } char main_char = sq[0][0]; for(int i = 0; i < n && !out; ++i) { int sum = 0; for(int j = 0; j < n && !out; ++j) { if(i == n / 2) { if(sq[i][j] == main_char) { if(j != n / 2) { cout << "NO" << endl; out = true; break; } } else { if(j == n / 2) { cout << "NO" << endl; out = true; break; } } } else { if(sq[i][j] == main_char) { sum += j + 1; } } } if(i != n/2 && !out && sum != n + 1) { cout << "NO" << endl; out = true; break; } } if(!out) cout << "YES" << endl; }
[ "reynaldo.rz.26@gmail.com" ]
reynaldo.rz.26@gmail.com
50b81048e62a4bb2f08b91c59a40f47efae62e61
f442f639a567cde56ae5126dce18b944a510ce90
/player_db.cpp
c7628238468decca568d1e3703ff66532261ec46
[]
no_license
TieJu/swtorla
a22b4715933e9c690782e43c809e1acded6ed9b8
dcf2cbd8af6891676640549b430351cd78e8fa36
refs/heads/master
2016-08-02T22:15:58.741909
2013-12-13T11:22:49
2013-12-13T11:22:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
373
cpp
#include "app.h" void player_db::set_player_name( const std::wstring& name_, string_id id_ ) { ensure_index_is_present( id_ ); if ( is_player_in_db( name_ ) ) { auto old = get_player_id( name_ ); if ( old != id_ ) { _app->remap_player_name( old, id_ ); remove_player_name( old ); } } _players[id_] = name_; }
[ "tiemo.jung@thm.de" ]
tiemo.jung@thm.de
51e96cec613372a1c8a36fdf984d3091e7c2967d
b116bebaea28d233092a76abc683d274675989ad
/forumCode/forumCode.ino
2927a9c14a9e9f6f416289c8f0abc366c6c3feec
[]
no_license
nrtyc4/picospritzer
762345983840c3fa53c273658ca190f173fd832d
071b3888a1ee91f30774148dfaba6e914d431d28
refs/heads/master
2016-09-06T08:39:19.038829
2013-08-09T23:34:16
2013-08-09T23:34:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,777
ino
#include <Wire.h> //I2C library const byte LCDa = 40; //LCD address on I2C bus const byte LCD_CLEAR[2] = {0xFE, 0x51}; const byte LCD_CLEAR_COUNT = 2; const byte LCD_SET_CURSOR[2] = {0xFE, 0x45}; const byte LCD_SET_CURSOR_COUNT = 2; //const byte LCD_UNDERLINE_CURSOR_ON[2] = {0xFE, 0x47}; //const byte LCD_UNDERLINE_CURSOR_ON_COUNT = 2; //const byte LCD_UNDERLINE_CURSOR_OFF[2] = {0xFE, 0x48}; //const byte LCD_UNDERLINE_CURSOR_OFF_COUNT = 2; void setup() { delay(200); Wire.begin(); // join i2c bus (address optional for master) Wire.beginTransmission(LCDa); Wire.write(LCD_CLEAR, LCD_CLEAR_COUNT); //Clear screen every time the program begins Wire.endTransmission(); delayMicroseconds(1500); //Set cursor to 1st line Wire.beginTransmission(LCDa); Wire.write(LCD_SET_CURSOR, LCD_SET_CURSOR_COUNT); Wire.write(0x00); Wire.endTransmission(); delayMicroseconds(100); //Create first char string Wire.beginTransmission(LCDa); for (byte i=47; i<66; i++) { Wire.write(i); } Wire.endTransmission(); //Set cursor to 2nd line Wire.beginTransmission(LCDa); Wire.write(LCD_SET_CURSOR, LCD_SET_CURSOR_COUNT); Wire.write(0x40); Wire.endTransmission(); delayMicroseconds(100); Wire.beginTransmission(LCDa); for (byte i=48; i<67; i++) { Wire.write(i); } Wire.endTransmission(); //Set cursor to 3rd line Wire.beginTransmission(LCDa); Wire.write(LCD_SET_CURSOR, LCD_SET_CURSOR_COUNT); Wire.write(0x14); Wire.endTransmission(); delayMicroseconds(100); //Write 3rd char string on 3rd line Wire.beginTransmission(LCDa); for (byte i=47; i<66; i++) { Wire.write(i); } Wire.endTransmission(); } void loop() { }
[ "natthompson72@gmail.com" ]
natthompson72@gmail.com
080c0d35d2195ed26a02e5465739e970461ae3a0
839515ab21cf09f00321c1a33f8d890060429213
/NFServer/NFGameServerNet_ServerPlugin/NFGameServerNet_ServerModule.h
e0a78d7f02c0a908b487ace0f42181b92c051e50
[ "Apache-2.0" ]
permissive
lemospring/NoahGameFrame
61aea980fc0ef44a60b5c110cba59d75ef7ebc34
c4f049f235e779cd21f9cf3f0c8719c1ae825854
refs/heads/master
2021-03-21T16:22:03.320378
2020-03-14T05:45:36
2020-03-14T05:45:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,541
h
/* This file is part of: NoahFrame https://github.com/ketoo/NoahGameFrame Copyright 2009 - 2020 NoahFrame(NoahGameFrame) File creator: lvsheng.huang NoahFrame is open-source software and you can redistribute it and/or modify it under the terms of the License; besides, anyone who use this file/software must include this copyright announcement. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef NF_GAMESERVER_SERVER_MODULE_H #define NF_GAMESERVER_SERVER_MODULE_H #include <memory> #include "NFComm/NFMessageDefine/NFMsgDefine.h" #include "NFComm/NFPluginModule/NFINetModule.h" #include "NFComm/NFPluginModule/NFILogModule.h" #include "NFComm/NFPluginModule/NFIKernelModule.h" #include "NFComm/NFPluginModule/NFIClassModule.h" #include "NFComm/NFPluginModule/NFISceneProcessModule.h" #include "NFComm/NFPluginModule/NFIElementModule.h" #include "NFComm/NFPluginModule/NFIEventModule.h" #include "NFComm/NFPluginModule/NFISceneModule.h" #include "NFComm/NFPluginModule/NFIGameServerToWorldModule.h" #include "NFComm/NFPluginModule/NFIGameServerNet_ServerModule.h" #include "NFComm/NFPluginModule/NFIGameServerNet_ServerModule.h" #include "NFComm/NFPluginModule/NFIScheduleModule.h" //////////////////////////////////////////////////////////////////////////// class NFGameServerNet_ServerModule : public NFIGameServerNet_ServerModule { public: NFGameServerNet_ServerModule(NFIPluginManager* p) { pPluginManager = p; } virtual bool Init(); virtual bool Shut(); virtual bool Execute(); virtual bool AfterInit(); virtual void SendMsgPBToGate(const uint16_t nMsgID, google::protobuf::Message& xMsg, const NFGUID& self); virtual void SendGroupMsgPBToGate(const uint16_t nMsgID, google::protobuf::Message& xMsg, const int nSceneID, const int nGroupID); virtual void SendGroupMsgPBToGate(const uint16_t nMsgID, google::protobuf::Message& xMsg, const int nSceneID, const int nGroupID, const NFGUID exceptID); virtual void SendMsgToGate(const uint16_t nMsgID, const std::string& strMsg, const NFGUID& self); virtual void SendGroupMsgPBToGate(const uint16_t nMsgID, const std::string& strMsg, const int nSceneID, const int nGroupID); virtual void SendGroupMsgPBToGate(const uint16_t nMsgID, const std::string& strMsg, const int nSceneID, const int nGroupID, const NFGUID exceptID); virtual bool AddPlayerGateInfo(const NFGUID& nRoleID, const NFGUID& nClientID, const int nGateID); virtual bool RemovePlayerGateInfo(const NFGUID& nRoleID); virtual NF_SHARE_PTR<GateBaseInfo> GetPlayerGateInfo(const NFGUID& nRoleID); virtual NF_SHARE_PTR<GateServerInfo> GetGateServerInfo(const int nGateID); virtual NF_SHARE_PTR<GateServerInfo> GetGateServerInfoBySockIndex(const NFSOCK nSockIndex); protected: void OnSocketPSEvent(const NFSOCK nSockIndex, const NF_NET_EVENT eEvent, NFINet* pNet); void OnClientDisconnect(const NFSOCK nSockIndex); void OnClientConnected(const NFSOCK nSockIndex); protected: void OnProxyServerRegisteredProcess(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); void OnProxyServerUnRegisteredProcess(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); void OnRefreshProxyServerInfoProcess(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); protected: void OnClientEnterGameProcess(const NFSOCK nSockIndex, const int nMsgID, const char *msg, const uint32_t nLen); void OnClientLeaveGameProcess(const NFSOCK nSockIndex, const int nMsgID, const char *msg, const uint32_t nLen); void OnClientSwapSceneProcess(const NFSOCK nSockIndex, const int nMsgID, const char *msg, const uint32_t nLen); void OnClientReqMoveProcess(const NFSOCK nSockIndex, const int nMsgID, const char *msg, const uint32_t nLen); void OnClientReqMoveImmuneProcess(const NFSOCK nSockIndex, const int nMsgID, const char *msg, const uint32_t nLen); void OnClientReqStateSyncProcess(const NFSOCK nSockIndex, const int nMsgID, const char *msg, const uint32_t nLen); void OnClientReqPosSyncProcess(const NFSOCK nSockIndex, const int nMsgID, const char *msg, const uint32_t nLen); void OnClientEnterGameFinishProcess(const NFSOCK nSockIndex, const int nMsgID, const char *msg, const uint32_t nLen); void OnLagTestProcess(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); ///////////WORLD_START/////////////////////////////////////////////////////////////// void OnTransWorld(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); protected: void OnClientPropertyIntProcess(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); void OnClientPropertyFloatProcess(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); void OnClientPropertyStringProcess(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); void OnClientPropertyObjectProcess(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); void OnClientPropertyVector2Process(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); void OnClientPropertyVector3Process(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); void OnClientAddRowProcess(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); void OnClientRemoveRowProcess(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); void OnClientSwapRowProcess(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); void OnClientRecordIntProcess(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); void OnClientRecordFloatProcess(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); void OnClientRecordStringProcess(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); void OnClientRecordObjectProcess(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); void OnClientRecordVector2Process(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); void OnClientRecordVector3Process(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen); protected: ////////////////////////////////////////// private: NFMapEx<NFGUID, GateBaseInfo> mRoleBaseData; //gateid,data NFMapEx<int, GateServerInfo> mProxyMap; ////////////////////////////////////////////////////////////////////////// NFIKernelModule* m_pKernelModule; NFIClassModule* m_pClassModule; NFILogModule* m_pLogModule; NFISceneProcessModule* m_pSceneProcessModule; NFIElementModule* m_pElementModule; NFINetModule* m_pNetModule; NFIEventModule* m_pEventModule; NFISceneModule* m_pSceneModule; NFINetClientModule* m_pNetClientModule; NFIScheduleModule* m_pScheduleModule; }; #endif
[ "342006@qq.com" ]
342006@qq.com
a06d0b2ba7c1970c1ab270f7844b496f44c787cc
726030bc5951dfb65fd823cc11d39e2f145f85c1
/Source/SnakeGame2/PlayerPawnBase.cpp
c92c7aab628764411e9d2722911cd1f843f709ad
[]
no_license
anchello2810/SnakeGame2
061877ffb4bd111ebe8e1d11a1f0ff31cc888542
b732b682ab2466bd47d6691d0a5bb0af18a5da2b
refs/heads/master
2023-07-10T15:37:21.344179
2021-08-09T14:43:27
2021-08-09T14:43:27
391,105,607
0
0
null
null
null
null
UTF-8
C++
false
false
2,163
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "PlayerPawnBase.h" #include "Engine/Classes/Camera/CameraComponent.h" #include "SnakeBase.h" #include "Components/InputComponent.h" #include "Food.h" // Sets default values APlayerPawnBase::APlayerPawnBase() { // Set this pawn to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; PawnCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("PawnCamera")); RootComponent = PawnCamera; } // Called when the game starts or when spawned void APlayerPawnBase::BeginPlay() { Super::BeginPlay(); SetActorRotation(FRotator(-90, 0, 0)); CreateSnakeActor(); } // Called every frame void APlayerPawnBase::Tick(float DeltaTime) { Super::Tick(DeltaTime); //AddRandomApple(); } // Called to bind functionality to input void APlayerPawnBase::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); PlayerInputComponent->BindAxis("Vertical", this, &APlayerPawnBase::HandlePlayerVerticalImput); PlayerInputComponent->BindAxis("Horizontal", this, &APlayerPawnBase::HandlePlayerHorizontalImput); } void APlayerPawnBase::CreateSnakeActor() { SnakeActor = GetWorld()->SpawnActor<ASnakeBase>(SnakeActorClass, FTransform()); } void APlayerPawnBase::HandlePlayerVerticalImput(float value) { if (IsValid(SnakeActor)) { if (value > 0 && SnakeActor->LastMoveDirection != EMovementDirection::DOWN) { SnakeActor->LastMoveDirection = EMovementDirection::UP; } else if (value < 0 && SnakeActor->LastMoveDirection != EMovementDirection::UP) { SnakeActor->LastMoveDirection = EMovementDirection::DOWN; } } } void APlayerPawnBase::HandlePlayerHorizontalImput(float value) { if (IsValid(SnakeActor)) { if (value > 0 && SnakeActor->LastMoveDirection != EMovementDirection::LEFT) { SnakeActor->LastMoveDirection = EMovementDirection::RIGHT; } else if (value < 0 && SnakeActor->LastMoveDirection != EMovementDirection::RIGHT) { SnakeActor->LastMoveDirection = EMovementDirection::LEFT; } } }
[ "anchello@yandex.ru" ]
anchello@yandex.ru
a9ddf2117cffb017e1cb9c93f63941d572605006
4296ad62fc2d1c0111af5e9c9ef5b8336256674e
/src/arc36/c.cpp
55b1142cc1134fbd358aaffca76214d2436c098c
[]
no_license
emakryo/cmpro
8aa50db1d84fb85e515546f37e675121be9de5c2
81db478cc7da06a9b99a7888e39952ddb82cdbe5
refs/heads/master
2023-02-09T12:36:47.893287
2023-01-23T12:07:03
2023-01-23T12:07:03
79,899,196
0
0
null
null
null
null
UTF-8
C++
false
false
2,768
cpp
#include<bits/stdc++.h> #include<boost/variant.hpp> using namespace std; typedef long long ll; typedef vector<boost::variant<bool, ll, int, string, double, char*, const char*>> any; template<typename T> inline void pr(const vector<T> &xs){ for(int i=0; i<xs.size()-1; i++) cout<<xs[i]<<" "; (xs.empty()?cout:(cout<<xs[xs.size()-1]))<<endl; } #ifdef DEBUG #define debug(...) pr(any{__VA_ARGS__}) #define debugv(x) pr((x)) #else #define debug(...) #define debugv(x) #endif struct mint { typedef long long ll; ll x, m; mint(ll x=0, ll m=1e9+7): x(x%m), m(m) {} mint operator-() const { return mint(m-x, m); } mint operator+(const mint o) const { return mint(x+o.x, m); } mint operator-(const mint o) const { return mint(x-o.x+m, m); } mint operator*(const mint o) const { return mint(x*o.x, m); } mint& operator+=(const mint o) { x = (x+o.x)%m; return *this; } mint& operator-=(const mint o) { x = (x-o.x+m)%m; return *this; } mint& operator*=(const mint o) { x = x*o.x%m; return *this; } bool operator==(const mint o) const { return x==o.x; } bool operator!=(const mint o) const { return x!=o.x; } template<typename T> mint& operator=(const T o) { x = o%m; return *this; } template<typename T> mint operator+(const T o) const { return mint(x+o, m); } template<typename T> mint operator-(const T o) const { return mint(x-((ll)o)%m+m, m); } template<typename T> mint operator*(const T o) const { return mint(x*o, m); } template<typename T> mint& operator+=(const T o) { x = (x+(ll)o%m)%m; return *this; } template<typename T> mint& operator-=(const T o) { x = (x-((ll)o)%m+m)%m; return *this; } template<typename T> mint& operator*=(const T o) { x = x*((ll)o%m)%m; return *this; } template<typename T> bool operator==(const T o) const { return x==o%m; } template<typename T> bool operator!=(const T o) const { return x!=o%m; } mint pow(ll k) const { if(k==0) return mint(1, m); if(k%2) return pow(k-1)*x; mint z = pow(k/2); return z*z; } mint inv() const { return pow(m-2); } }; mint dp[2][305][305]; int main(){ int N, K; cin >> N >> K; string S; cin >> S; dp[0][0][0] = 1; for(int i=0; i<N; i++){ for(int p=0; p<=K; p++) for(int q=0; q<=K; q++) dp[(i+1)%2][p][q] = 0; int n_pos = 0; for(int p=0; p<=K; p++) for(int q=0; q<=K; q++) { debug(i, p, q, dp[i%2][p][q].x); if(dp[i%2][p][q] != 0) n_pos++; if(S[i]=='?' || S[i]=='0'){ if(q>0) dp[(i+1)%2][p+1][q-1] += dp[i%2][p][q]; else dp[(i+1)%2][p+1][q] += dp[i%2][p][q]; } if(S[i]=='?' || S[i]=='1'){ if(p>0) dp[(i+1)%2][p-1][q+1] += dp[i%2][p][q]; else dp[(i+1)%2][p][q+1] += dp[i%2][p][q]; } } debug(n_pos); } mint ans; for(int p=0; p<=K; p++) for(int q=0; q<=K; q++) ans += dp[N%2][p][q]; cout << ans.x << endl; return 0; }
[ "ryosuke.kamesawa@dena.jp" ]
ryosuke.kamesawa@dena.jp
5bb5b2f90e8a4eed3dfc8c788fbad3bdb9a37c11
d065109ae84eeda9ad64bd8fb1c4176c85730954
/magician.cpp
0a4fdb10563fba8270aa880d9a22444b3262396f
[]
no_license
liuke0002/BasicAlgorithm
31e79209a948ece98e7e54aaa6af3c0a60730331
df62d9954486ae0f25ff425435840817bd86f0ac
refs/heads/master
2021-01-10T08:12:19.121080
2017-09-27T15:05:10
2017-09-27T15:05:10
54,707,237
1
0
null
null
null
null
WINDOWS-1252
C++
false
false
862
cpp
#include<stdio.h> #include<stdlib.h> #define CardNumber 13 typedef struct node{ int data; struct node *next; }node; node *createLinkList(){ node *head,*p; node *s; int i; head=(node*)malloc(sizeof(node)); p=head; for(i=0;i<CardNumber;i++){ s=(node*)malloc(sizeof(node)); s->data=0; p->next=s; p=s; } s->next=head->next; free(head); return s->next; } void margician(node *head){ node *p; int j; int countNumber=2; p=head; p->data=1; while(1){ for(j=0;j<countNumber;j++){ p=p->next; if(p->data!=0){//¸ÃλÖÃÓÐÅÆ p->next; j--; } } if(p->data==0){ p->data=countNumber; countNumber++; if(countNumber==14){ break; } } } } int main(){ node *p=createLinkList(); margician(p); int i; for(i=1;i<CardNumber;i++){ printf("%d->",p->data); p=p->next; } printf("%d\n",p->data); return 0; }
[ "1395674569@qq.com" ]
1395674569@qq.com
67678978cd39ab2bbe4e1508900be073fb0a6f8d
dbddebd6eb0ed34104acb254da81fc643c01a4ca
/ros/devel/include/styx_msgs/TrafficLight.h
06c45173a2543ba0a7550b4f51346694c3ced9d7
[ "MIT" ]
permissive
arpitsri3/CarND_Capstone_Code
4eba922f7c8ccc3a01aff520934b39d1736520e6
2824a14c6fc3992123d5189187c5c8c85f58c9fd
refs/heads/master
2020-03-19T05:57:27.860271
2018-06-06T09:32:41
2018-06-06T09:32:41
135,978,409
0
1
null
null
null
null
UTF-8
C++
false
false
7,513
h
// Generated by gencpp from file styx_msgs/TrafficLight.msg // DO NOT EDIT! #ifndef STYX_MSGS_MESSAGE_TRAFFICLIGHT_H #define STYX_MSGS_MESSAGE_TRAFFICLIGHT_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> #include <std_msgs/Header.h> #include <geometry_msgs/PoseStamped.h> namespace styx_msgs { template <class ContainerAllocator> struct TrafficLight_ { typedef TrafficLight_<ContainerAllocator> Type; TrafficLight_() : header() , pose() , state(0) { } TrafficLight_(const ContainerAllocator& _alloc) : header(_alloc) , pose(_alloc) , state(0) { (void)_alloc; } typedef ::std_msgs::Header_<ContainerAllocator> _header_type; _header_type header; typedef ::geometry_msgs::PoseStamped_<ContainerAllocator> _pose_type; _pose_type pose; typedef uint8_t _state_type; _state_type state; enum { UNKNOWN = 4u, GREEN = 2u, YELLOW = 1u, RED = 0u, }; typedef boost::shared_ptr< ::styx_msgs::TrafficLight_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::styx_msgs::TrafficLight_<ContainerAllocator> const> ConstPtr; }; // struct TrafficLight_ typedef ::styx_msgs::TrafficLight_<std::allocator<void> > TrafficLight; typedef boost::shared_ptr< ::styx_msgs::TrafficLight > TrafficLightPtr; typedef boost::shared_ptr< ::styx_msgs::TrafficLight const> TrafficLightConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::styx_msgs::TrafficLight_<ContainerAllocator> & v) { ros::message_operations::Printer< ::styx_msgs::TrafficLight_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace styx_msgs namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': True} // {'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'sensor_msgs': ['/opt/ros/kinetic/share/sensor_msgs/cmake/../msg'], 'geometry_msgs': ['/opt/ros/kinetic/share/geometry_msgs/cmake/../msg'], 'styx_msgs': ['/home/workspace/CarND_Capstone_Code/ros/src/styx_msgs/msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::styx_msgs::TrafficLight_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::styx_msgs::TrafficLight_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct IsMessage< ::styx_msgs::TrafficLight_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::styx_msgs::TrafficLight_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::styx_msgs::TrafficLight_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::styx_msgs::TrafficLight_<ContainerAllocator> const> : TrueType { }; template<class ContainerAllocator> struct MD5Sum< ::styx_msgs::TrafficLight_<ContainerAllocator> > { static const char* value() { return "444a7e648c334df4cc0678bcfbd971da"; } static const char* value(const ::styx_msgs::TrafficLight_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0x444a7e648c334df4ULL; static const uint64_t static_value2 = 0xcc0678bcfbd971daULL; }; template<class ContainerAllocator> struct DataType< ::styx_msgs::TrafficLight_<ContainerAllocator> > { static const char* value() { return "styx_msgs/TrafficLight"; } static const char* value(const ::styx_msgs::TrafficLight_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::styx_msgs::TrafficLight_<ContainerAllocator> > { static const char* value() { return "Header header\n\ geometry_msgs/PoseStamped pose\n\ uint8 state\n\ \n\ uint8 UNKNOWN=4\n\ uint8 GREEN=2\n\ uint8 YELLOW=1\n\ uint8 RED=0\n\ \n\ ================================================================================\n\ MSG: std_msgs/Header\n\ # Standard metadata for higher-level stamped data types.\n\ # This is generally used to communicate timestamped data \n\ # in a particular coordinate frame.\n\ # \n\ # sequence ID: consecutively increasing ID \n\ uint32 seq\n\ #Two-integer timestamp that is expressed as:\n\ # * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')\n\ # * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')\n\ # time-handling sugar is provided by the client library\n\ time stamp\n\ #Frame this data is associated with\n\ # 0: no frame\n\ # 1: global frame\n\ string frame_id\n\ \n\ ================================================================================\n\ MSG: geometry_msgs/PoseStamped\n\ # A Pose with reference coordinate frame and timestamp\n\ Header header\n\ Pose pose\n\ \n\ ================================================================================\n\ MSG: geometry_msgs/Pose\n\ # A representation of pose in free space, composed of position and orientation. \n\ Point position\n\ Quaternion orientation\n\ \n\ ================================================================================\n\ MSG: geometry_msgs/Point\n\ # This contains the position of a point in free space\n\ float64 x\n\ float64 y\n\ float64 z\n\ \n\ ================================================================================\n\ MSG: geometry_msgs/Quaternion\n\ # This represents an orientation in free space in quaternion form.\n\ \n\ float64 x\n\ float64 y\n\ float64 z\n\ float64 w\n\ "; } static const char* value(const ::styx_msgs::TrafficLight_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::styx_msgs::TrafficLight_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.header); stream.next(m.pose); stream.next(m.state); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct TrafficLight_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::styx_msgs::TrafficLight_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::styx_msgs::TrafficLight_<ContainerAllocator>& v) { s << indent << "header: "; s << std::endl; Printer< ::std_msgs::Header_<ContainerAllocator> >::stream(s, indent + " ", v.header); s << indent << "pose: "; s << std::endl; Printer< ::geometry_msgs::PoseStamped_<ContainerAllocator> >::stream(s, indent + " ", v.pose); s << indent << "state: "; Printer<uint8_t>::stream(s, indent + " ", v.state); } }; } // namespace message_operations } // namespace ros #endif // STYX_MSGS_MESSAGE_TRAFFICLIGHT_H
[ "i.arpitsri@gmail.com" ]
i.arpitsri@gmail.com
af8b2e49ad29d538bc91a0d9770c331c2588c9d4
7ab3757bde602ebe0b2f9e49d7e1d5f672ee150a
/easyrespacker/src/librespacker/ShapeBuilder.h
8369e261ca4bdb9bb823faced1a538f5d45107e4
[ "MIT" ]
permissive
brucelevis/easyeditor
310dc05084b06de48067acd7ef5d6882fd5b7bba
d0bb660a491c7d990b0dae5b6fa4188d793444d9
refs/heads/master
2021-01-16T18:36:37.012604
2016-08-11T11:25:20
2016-08-11T11:25:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
697
h
#ifndef _EASYRESPACKER_SHAPE_BUILDER_H_ #define _EASYRESPACKER_SHAPE_BUILDER_H_ #include "INodeBuilder.h" #include <map> namespace etexture { class Symbol; } namespace erespacker { class IPackNode; class PackShape; class ShapeBuilder : public INodeBuilder { public: ShapeBuilder(); virtual ~ShapeBuilder(); virtual void Traverse(ee::Visitor& visitor) const; bool CanHandle(const etexture::Symbol* symbol) const; const IPackNode* Create(const etexture::Symbol* symbol); private: void Load(const etexture::Symbol* symbol, PackShape* shape); private: std::map<const etexture::Symbol*, const PackShape*> m_map_data; }; // ShapeBuilder } #endif // _EASYRESPACKER_SHAPE_BUILDER_H_
[ "zhuguang@ejoy.com" ]
zhuguang@ejoy.com