blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 905
values | visit_date
timestamp[us]date 2015-08-09 11:21:18
2023-09-06 10:45:07
| revision_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-17 19:19:19
| committer_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-06 06:22:19
| github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-07 00:51:45
2023-09-14 21:58:39
⌀ | gha_created_at
timestamp[us]date 2008-03-27 23:40:48
2023-08-21 23:17:38
⌀ | gha_language
stringclasses 141
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 115
values | content
stringlengths 3
10.4M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
158
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e5e22fd662ca1304482157a5260fd7e1b3dc4f0e | 0540feb2f5a29ab8d42951fb03a0056addc6f392 | /src/3rd/Simd/SimdAvx512fNeural.cpp | 670d6a20079c5b85503836f81ce10d7025203a0c | [
"MIT"
] | permissive | ShamanWolffire/AntiDupl | 0ebe37edbb8a16543fe8b53a3d938960b109e9a5 | 6cab96338dc3b273ede0e9d1e90280a6afbdd889 | refs/heads/master | 2021-04-28T15:28:23.055990 | 2018-01-17T06:57:25 | 2018-01-17T06:57:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 158,835 | cpp | /*
* Simd Library (http://ermig1979.github.io/Simd).
*
* Copyright (c) 2011-2017 Yermalayeu Ihar.
*
* 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 "Simd/SimdMemory.h"
#include "Simd/SimdStore.h"
#include "Simd/SimdExtract.h"
#include "Simd/SimdStream.h"
#include "Simd/SimdNeural.h"
#include "Simd/SimdAvx2.h"
namespace Simd
{
#ifdef SIMD_AVX512F_ENABLE
namespace Avx512f
{
template <bool align, bool mask> SIMD_INLINE void NeuralProductSum(const float * a, const float * b, size_t offset, __m512 & sum, __mmask16 m = -1)
{
__m512 _a = Load<align, mask>(a + offset, m);
__m512 _b = Load<align, mask>(b + offset, m);
sum = _mm512_fmadd_ps(_a, _b, sum);
}
template <bool align> SIMD_INLINE void NeuralProductSum(const float * a, const float * b, size_t size, float * sum)
{
if (align)
assert(Aligned(a) && Aligned(b));
size_t partialAlignedSize = AlignLo(size, F);
size_t fullAlignedSize = AlignLo(size, QF);
size_t i = 0;
__m512 sum0 = _mm512_setzero_ps();
if (fullAlignedSize)
{
__m512 sum1 = _mm512_setzero_ps();
__m512 sum2 = _mm512_setzero_ps();
__m512 sum3 = _mm512_setzero_ps();
for (; i < fullAlignedSize; i += QF)
{
NeuralProductSum<align, false>(a, b, i + F * 0, sum0);
NeuralProductSum<align, false>(a, b, i + F * 1, sum1);
NeuralProductSum<align, false>(a, b, i + F * 2, sum2);
NeuralProductSum<align, false>(a, b, i + F * 3, sum3);
}
sum0 = _mm512_add_ps(_mm512_add_ps(sum0, sum1), _mm512_add_ps(sum2, sum3));
}
for (; i < partialAlignedSize; i += F)
NeuralProductSum<align, false>(a, b, i, sum0);
if (i < size)
{
__mmask16 tailMask = __mmask16(-1) >> (F + i - size);
NeuralProductSum<align, true>(a, b, i, sum0, tailMask);
}
*sum = ExtractSum(sum0);
}
void NeuralProductSum(const float * a, const float * b, size_t size, float * sum)
{
if (Aligned(a) && Aligned(b))
NeuralProductSum<true>(a, b, size, sum);
else
NeuralProductSum<false>(a, b, size, sum);
}
template <bool align, bool mask> SIMD_INLINE void AddMultiplied(const float * src, const __m512 & value, float * dst, __mmask16 m = -1)
{
__m512 _src = Load<align, mask>(src, m);
__m512 _dst = Load<align, mask>(dst, m);
Store<align, mask>(dst, _mm512_fmadd_ps(value, _src, _dst), m);
}
template <bool align> SIMD_INLINE void AddMultiplied(const float * src, size_t aligned, size_t partial, size_t full, float value, float * dst)
{
size_t i = 0;
__m512 _value = _mm512_set1_ps(value);
for (; i < aligned; i += QF)
{
AddMultiplied<align, false>(src + i + F * 0, _value, dst + i + F * 0);
AddMultiplied<align, false>(src + i + F * 1, _value, dst + i + F * 1);
AddMultiplied<align, false>(src + i + F * 2, _value, dst + i + F * 2);
AddMultiplied<align, false>(src + i + F * 3, _value, dst + i + F * 3);
}
for (; i < partial; i += F)
AddMultiplied<align, false>(src + i, _value, dst + i);
if (i < full)
{
__mmask16 tailMask = __mmask16(-1) >> (F + i - full);
AddMultiplied<align, true>(src + i, _value, dst + i, tailMask);
}
}
void NeuralAddVectorMultipliedByValue(const float * src, size_t size, const float * value, float * dst)
{
size_t aligned = AlignLo(size, QF);
size_t partial = AlignLo(size, F);
if (Aligned(src) && Aligned(dst))
AddMultiplied<true>(src, aligned, partial, size, *value, dst);
else
AddMultiplied<false>(src, aligned, partial, size, *value, dst);
}
template <bool align, bool mask> SIMD_INLINE void AddVector(const float * src, float * dst, __mmask16 m = -1)
{
__m512 _src = Load<align, mask>(src, m);
__m512 _dst = Load<align, mask>(dst, m);
Store<align, mask>(dst, _mm512_add_ps(_src, _dst), m);
}
template <bool align> SIMD_INLINE void AddVector(const float * src, size_t aligned, size_t partial, size_t full, float * dst)
{
size_t i = 0;
for (; i < aligned; i += QF)
{
AddVector<align, false>(src + i + F * 0, dst + i + F * 0);
AddVector<align, false>(src + i + F * 1, dst + i + F * 1);
AddVector<align, false>(src + i + F * 2, dst + i + F * 2);
AddVector<align, false>(src + i + F * 3, dst + i + F * 3);
}
for (; i < partial; i += F)
AddVector<align, false>(src + i, dst + i);
if (i < full)
{
__mmask16 tailMask = __mmask16(-1) >> (F + i - full);
AddVector<align, true>(src + i, dst + i, tailMask);
}
}
void NeuralAddVector(const float * src, size_t size, float * dst)
{
size_t aligned = AlignLo(size, QF);
size_t partial = AlignLo(size, F);
if (Aligned(src) && Aligned(dst))
AddVector<true>(src, aligned, partial, size, dst);
else
AddVector<false>(src, aligned, partial, size, dst);
}
template <bool align, bool mask> SIMD_INLINE void AddValue(const __m512 & value, float * dst, __mmask16 m = -1)
{
__m512 _dst = Load<align, mask>(dst, m);
Store<align, mask>(dst, _mm512_add_ps(_dst, value), m);
}
template <bool align> SIMD_INLINE void AddValue(const float * value, float * dst, size_t aligned, size_t partial, size_t full)
{
size_t i = 0;
__m512 _value = _mm512_set1_ps(value[0]);
for (; i < aligned; i += QF)
{
AddValue<align, false>(_value, dst + i + F * 0);
AddValue<align, false>(_value, dst + i + F * 1);
AddValue<align, false>(_value, dst + i + F * 2);
AddValue<align, false>(_value, dst + i + F * 3);
}
for (; i < partial; i += F)
AddValue<align, false>(_value, dst + i);
if (i < full)
{
__mmask16 tailMask = __mmask16(-1) >> (F + i - full);
AddValue<align, true>(_value, dst + i, tailMask);
}
}
void NeuralAddValue(const float * value, float * dst, size_t size)
{
size_t aligned = AlignLo(size, QF);
size_t partial = AlignLo(size, F);
if (Aligned(dst))
AddValue<true>(value, dst, aligned, partial, size);
else
AddValue<false>(value, dst, aligned, partial, size);
}
class ExpEstimator
{
__m512i _exponent, _mantissa, _127;
__m512 _1_0, _0_5, _min, _max, _exp0, _exp1, _exp2, _exp3, _exp4, _exp5, _k;
void Init(float k)
{
_exponent = _mm512_set1_epi32(0x7F800000);
_mantissa = _mm512_set1_epi32(0x007FFFFF);
_127 = _mm512_set1_epi32(127);
_1_0 = _mm512_set1_ps(1.0f);
_0_5 = _mm512_set1_ps(0.5f);
_min = _mm512_set1_ps(-126.99999f);
_max = _mm512_set1_ps(129.00000f);
_exp0 = _mm512_set1_ps(9.9999994e-1f);
_exp1 = _mm512_set1_ps(6.9315308e-1f);
_exp2 = _mm512_set1_ps(2.4015361e-1f);
_exp3 = _mm512_set1_ps(5.5826318e-2f);
_exp4 = _mm512_set1_ps(8.9893397e-3f);
_exp5 = _mm512_set1_ps(1.8775767e-3f);
_k = _mm512_set1_ps(k / 0.69314718056f);
}
SIMD_INLINE __m512 Poly5(__m512 x)
{
__m512 p = _exp5;
p = _mm512_fmadd_ps(x, p, _exp4);
p = _mm512_fmadd_ps(x, p, _exp3);
p = _mm512_fmadd_ps(x, p, _exp2);
p = _mm512_fmadd_ps(x, p, _exp1);
p = _mm512_fmadd_ps(x, p, _exp0);
return p;
}
SIMD_INLINE __m512 Exp2(__m512 x)
{
x = _mm512_max_ps(_mm512_min_ps(x, _max), _min);
__m512i ipart = _mm512_cvtps_epi32(_mm512_sub_ps(x, _0_5));
__m512 fpart = _mm512_sub_ps(x, _mm512_cvtepi32_ps(ipart));
__m512 expipart = _mm512_castsi512_ps(_mm512_slli_epi32(_mm512_add_epi32(ipart, _127), 23));
__m512 expfpart = Poly5(fpart);
return _mm512_mul_ps(expipart, expfpart);
}
SIMD_INLINE __m512 Sigmoid(__m512 value)
{
__m512 exp = Exp2(_mm512_mul_ps(_k, value));
return _mm512_div_ps(_1_0, _mm512_add_ps(_1_0, exp));
}
template<bool align> void Sigmoid(const float * src, size_t size, const float * slope, float * dst)
{
if (align)
assert(Aligned(src) && Aligned(dst));
Init(-slope[0]);
size_t alignedSize = AlignLo(size, F);
size_t i = 0;
for (; i < alignedSize; i += F)
Avx512f::Store<align>(dst + i, Sigmoid(Avx512f::Load<align>(src + i)));
for (; i < size; ++i)
dst[i] = Base::Sigmoid(src[i] * slope[0]);
}
SIMD_INLINE __m512 Tanh(__m512 value)
{
__m512 exp = Exp2(_mm512_mul_ps(_k, value));
return _mm512_div_ps(_mm512_sub_ps(_1_0, exp), _mm512_add_ps(_1_0, exp));
}
template<bool align> void Tanh(const float * src, size_t size, const float * slope, float * dst)
{
if (align)
assert(Aligned(src) && Aligned(dst));
Init(-2.0f*slope[0]);
size_t alignedSize = AlignLo(size, F);
size_t i = 0;
for (; i < alignedSize; i += F)
Avx512f::Store<align>(dst + i, Tanh(Avx512f::Load<align>(src + i)));
for (; i < size; ++i)
dst[i] = Base::Tanh(src[i] * slope[0]);
}
public:
void Sigmoid(const float * src, size_t size, const float * slope, float * dst)
{
if (Aligned(src) && Aligned(dst))
Sigmoid<true>(src, size, slope, dst);
else
Sigmoid<false>(src, size, slope, dst);
}
void Tanh(const float * src, size_t size, const float * slope, float * dst)
{
if (Aligned(src) && Aligned(dst))
Tanh<true>(src, size, slope, dst);
else
Tanh<false>(src, size, slope, dst);
}
};
void NeuralSigmoid(const float * src, size_t size, const float * slope, float * dst)
{
ExpEstimator estimator;
estimator.Sigmoid(src, size, slope, dst);
}
void NeuralTanh(const float * src, size_t size, const float * slope, float * dst)
{
ExpEstimator estimator;
estimator.Tanh(src, size, slope, dst);
}
template <bool align, bool mask> SIMD_INLINE void NeuralRoughSigmoid(const float * src, const __m512 & _0, const __m512 & _1,
const __m512 & a, const __m512 & b, const __m512 & slope, float * dst, __mmask16 m = -1)
{
__m512 _src = Load<align, mask>(src, m);
__m512 x = AndNot(_0, _mm512_mul_ps(_src, slope));
__m512 x2 = _mm512_mul_ps(x, x);
__m512 x4 = _mm512_mul_ps(x2, x2);
__m512 series = _mm512_add_ps(_mm512_fmadd_ps(x2, a, _1), _mm512_fmadd_ps(x4, b, x));
__m512 exp = _mm512_mask_blend_ps(_mm512_cmp_ps_mask(_src, _0, _CMP_GT_OS), series, Rcp14(series));
__m512 sigmoid = Rcp14(_mm512_add_ps(_1, exp));
Store<align, mask>(dst, sigmoid, m);
}
template <bool align> SIMD_INLINE void NeuralRoughSigmoid(const float * src, size_t size, const float * slope, float * dst)
{
__m512 _slope = _mm512_set1_ps(*slope);
__m512 _0 = _mm512_set1_ps(-0.0f);
__m512 _1 = _mm512_set1_ps(1.0f);
__m512 _a = _mm512_set1_ps(0.5417f);
__m512 _b = _mm512_set1_ps(0.1460f);
size_t i = 0;
size_t partialAlignedSize = Simd::AlignLo(size, F);
size_t fullAlignedSize = Simd::AlignLo(size, QF);
for (; i < fullAlignedSize; i += QF)
{
NeuralRoughSigmoid<align, false>(src + i + 0 * F, _0, _1, _a, _b, _slope, dst + i + 0 * F);
NeuralRoughSigmoid<align, false>(src + i + 1 * F, _0, _1, _a, _b, _slope, dst + i + 1 * F);
NeuralRoughSigmoid<align, false>(src + i + 2 * F, _0, _1, _a, _b, _slope, dst + i + 2 * F);
NeuralRoughSigmoid<align, false>(src + i + 3 * F, _0, _1, _a, _b, _slope, dst + i + 3 * F);
}
for (; i < partialAlignedSize; i += F)
NeuralRoughSigmoid<align, false>(src + i, _0, _1, _a, _b, _slope, dst + i);
if (i < size)
{
__mmask16 tailMask = __mmask16(-1) >> (F + i - size);
NeuralRoughSigmoid<align, true>(src + i, _0, _1, _a, _b, _slope, dst + i, tailMask);
}
}
void NeuralRoughSigmoid(const float * src, size_t size, const float * slope, float * dst)
{
if (Aligned(src) && Aligned(dst))
NeuralRoughSigmoid<true>(src, size, slope, dst);
else
NeuralRoughSigmoid<false>(src, size, slope, dst);
}
template <bool align, bool mask> SIMD_INLINE void NeuralRoughSigmoid2(const float * src, const __m512 & k,
const __m512 & _1, const __m512 & _05, float * dst, __mmask16 m = -1)
{
__m512 _src = Load<align, mask>(src, m);
__m512 e1 = _mm512_max_ps(_05, _mm512_fmadd_ps(_src, k, _1));
__m512 e2 = _mm512_mul_ps(e1, e1);
__m512 e4 = _mm512_mul_ps(e2, e2);
__m512 e8 = _mm512_mul_ps(e4, e4);
__m512 e16 = _mm512_mul_ps(e8, e8);
__m512 e32 = _mm512_mul_ps(e16, e16);
__m512 e64 = _mm512_mul_ps(e32, e32);
__m512 sigmoid = Rcp14(_mm512_fmadd_ps(e64, e64, _1));
Store<align, mask>(dst, sigmoid, m);
}
template <bool align> SIMD_INLINE void NeuralRoughSigmoid2(const float * src, size_t size, const float * slope, float * dst)
{
size_t partialAlignedSize = Simd::AlignLo(size, F);
size_t fullAlignedSize = Simd::AlignLo(size, QF);
__m512 _k = _mm512_set1_ps(-(*slope)*0.0078125f);
__m512 _1 = _mm512_set1_ps(1.0f);
__m512 _05 = _mm512_set1_ps(0.5f);
size_t i = 0;
for (; i < fullAlignedSize; i += QF)
{
NeuralRoughSigmoid2<align, true>(src + i + 0 * F, _k, _1, _05, dst + i + 0 * F);
NeuralRoughSigmoid2<align, true>(src + i + 1 * F, _k, _1, _05, dst + i + 1 * F);
NeuralRoughSigmoid2<align, true>(src + i + 2 * F, _k, _1, _05, dst + i + 2 * F);
NeuralRoughSigmoid2<align, true>(src + i + 3 * F, _k, _1, _05, dst + i + 3 * F);
}
for (; i < partialAlignedSize; i += F)
NeuralRoughSigmoid2<align, true>(src + i, _k, _1, _05, dst + i);
if (i < size)
{
__mmask16 tailMask = __mmask16(-1) >> (F + i - size);
NeuralRoughSigmoid2<align, true>(src + i, _k, _1, _05, dst + i, tailMask);
}
}
void NeuralRoughSigmoid2(const float * src, size_t size, const float * slope, float * dst)
{
if (Aligned(src) && Aligned(dst))
NeuralRoughSigmoid2<true>(src, size, slope, dst);
else
NeuralRoughSigmoid2<false>(src, size, slope, dst);
}
template <bool align, bool mask> SIMD_INLINE void NeuralDerivativeSigmoid(const float * src, const __m512 & _1, const __m512 & slope, float * dst, __mmask16 m = -1)
{
__m512 _src = Load<align, mask>(src, m);
__m512 _dst = Load<align, mask>(dst, m);
Store<align, mask>(dst, _mm512_mul_ps(_mm512_mul_ps(_dst, slope), _mm512_mul_ps(_mm512_sub_ps(_1, _src), _src)), m);
}
template <bool align> SIMD_INLINE void NeuralDerivativeSigmoid(const float * src, size_t size, const float * slope, float * dst)
{
size_t partialAlignedSize = Simd::AlignLo(size, F);
size_t fullAlignedSize = Simd::AlignLo(size, QF);
__m512 _1 = _mm512_set1_ps(1.0f);
__m512 _slope = _mm512_set1_ps(*slope);
size_t i = 0;
for (; i < fullAlignedSize; i += QF)
{
NeuralDerivativeSigmoid<align, true>(src + i + 0 * F, _1, _slope, dst + i + 0 * F);
NeuralDerivativeSigmoid<align, true>(src + i + 1 * F, _1, _slope, dst + i + 1 * F);
NeuralDerivativeSigmoid<align, true>(src + i + 2 * F, _1, _slope, dst + i + 2 * F);
NeuralDerivativeSigmoid<align, true>(src + i + 3 * F, _1, _slope, dst + i + 3 * F);
}
for (; i < partialAlignedSize; i += F)
NeuralDerivativeSigmoid<align, true>(src + i, _1, _slope, dst + i);
if (i < size)
{
__mmask16 tailMask = __mmask16(-1) >> (F + i - size);
NeuralDerivativeSigmoid<align, true>(src + i, _1, _slope, dst + i, tailMask);
}
}
void NeuralDerivativeSigmoid(const float * src, size_t size, const float * slope, float * dst)
{
if (Aligned(src) && Aligned(dst))
NeuralDerivativeSigmoid<true>(src, size, slope, dst);
else
NeuralDerivativeSigmoid<false>(src, size, slope, dst);
}
template <bool align, bool mask> SIMD_INLINE void NeuralRoughTanh(const float * src, const __m512 & _0, const __m512 & _1,
const __m512 & a, const __m512 & b, const __m512 & slope, float * dst, __mmask16 m = -1)
{
__m512 _src = Load<align, mask>(src, m);
__m512 x = AndNot(_0, _mm512_mul_ps(_src, slope));
__m512 x2 = _mm512_mul_ps(x, x);
__m512 x4 = _mm512_mul_ps(x2, x2);
__m512 pe = _mm512_add_ps(_mm512_fmadd_ps(x2, a, _1), _mm512_fmadd_ps(x4, b, x));
__m512 ne = Rcp14(pe);
__m512 absTanh = _mm512_mul_ps(_mm512_sub_ps(pe, ne), Rcp14(_mm512_add_ps(pe, ne)));
__m512 tanh = Xor(absTanh, AndMaskZ(_0, _0, _mm512_cmp_ps_mask(_0, _src, _CMP_GT_OS)));
Store<align, mask>(dst, tanh, m);
}
template <bool align> SIMD_INLINE void NeuralRoughTanh(const float * src, size_t size, const float * slope, float * dst)
{
__m512 _slope = _mm512_set1_ps(*slope);
__m512 _0 = _mm512_set1_ps(-0.0f);
__m512 _1 = _mm512_set1_ps(1.0f);
__m512 _a = _mm512_set1_ps(0.5658f);
__m512 _b = _mm512_set1_ps(0.1430f);
size_t i = 0;
size_t partialAlignedSize = Simd::AlignLo(size, F);
size_t fullAlignedSize = Simd::AlignLo(size, QF);
for (; i < fullAlignedSize; i += QF)
{
NeuralRoughTanh<align, false>(src + i + 0 * F, _0, _1, _a, _b, _slope, dst + i + 0 * F);
NeuralRoughTanh<align, false>(src + i + 1 * F, _0, _1, _a, _b, _slope, dst + i + 1 * F);
NeuralRoughTanh<align, false>(src + i + 2 * F, _0, _1, _a, _b, _slope, dst + i + 2 * F);
NeuralRoughTanh<align, false>(src + i + 3 * F, _0, _1, _a, _b, _slope, dst + i + 3 * F);
}
for (; i < partialAlignedSize; i += F)
NeuralRoughTanh<align, false>(src + i, _0, _1, _a, _b, _slope, dst + i);
if (i < size)
{
__mmask16 tailMask = __mmask16(-1) >> (F + i - size);
NeuralRoughTanh<align, true>(src + i, _0, _1, _a, _b, _slope, dst + i, tailMask);
}
}
void NeuralRoughTanh(const float * src, size_t size, const float * slope, float * dst)
{
if (Aligned(src) && Aligned(dst))
NeuralRoughTanh<true>(src, size, slope, dst);
else
NeuralRoughTanh<false>(src, size, slope, dst);
}
template <bool align, bool mask> SIMD_INLINE void NeuralDerivativeTanh(const float * src, const __m512 & _1, const __m512 & slope, float * dst, __mmask16 m = -1)
{
__m512 _src = Load<align, mask>(src, m);
__m512 _dst = Load<align, mask>(dst, m);
Store<align, mask>(dst, _mm512_mul_ps(_mm512_mul_ps(_dst, slope), _mm512_sub_ps(_1, _mm512_mul_ps(_src, _src))), m);
}
template <bool align> SIMD_INLINE void NeuralDerivativeTanh(const float * src, size_t size, const float * slope, float * dst)
{
size_t partialAlignedSize = Simd::AlignLo(size, F);
size_t fullAlignedSize = Simd::AlignLo(size, QF);
__m512 _1 = _mm512_set1_ps(1.0f);
__m512 _slope = _mm512_set1_ps(*slope);
size_t i = 0;
for (; i < fullAlignedSize; i += QF)
{
NeuralDerivativeTanh<align, true>(src + i + 0 * F, _1, _slope, dst + i + 0 * F);
NeuralDerivativeTanh<align, true>(src + i + 1 * F, _1, _slope, dst + i + 1 * F);
NeuralDerivativeTanh<align, true>(src + i + 2 * F, _1, _slope, dst + i + 2 * F);
NeuralDerivativeTanh<align, true>(src + i + 3 * F, _1, _slope, dst + i + 3 * F);
}
for (; i < partialAlignedSize; i += F)
NeuralDerivativeTanh<align, true>(src + i, _1, _slope, dst + i);
if (i < size)
{
__mmask16 tailMask = __mmask16(-1) >> (F + i - size);
NeuralDerivativeTanh<align, true>(src + i, _1, _slope, dst + i, tailMask);
}
}
void NeuralDerivativeTanh(const float * src, size_t size, const float * slope, float * dst)
{
if (Aligned(src) && Aligned(dst))
NeuralDerivativeTanh<true>(src, size, slope, dst);
else
NeuralDerivativeTanh<false>(src, size, slope, dst);
}
template <bool align, bool mask> SIMD_INLINE void NeuralRelu(const float * src, const __m512 & slope, float * dst, __mmask16 m = -1)
{
__m512 _src = Load<align, mask>(src, m);
Store<align, mask>(dst, _mm512_max_ps(_mm512_mul_ps(slope, _src), _src), m);
}
template <bool align> SIMD_INLINE void NeuralRelu(const float * src, size_t size, const float * slope, float * dst)
{
assert(slope[0] >= 0.0f && slope[0] <= 1.0f);
size_t partialAlignedSize = Simd::AlignLo(size, F);
size_t fullAlignedSize = Simd::AlignLo(size, QF);
size_t i = 0;
if (slope[0] == 0)
{
__m512 _0 = _mm512_set1_ps(0.0f);
for (; i < fullAlignedSize; i += QF)
{
Store<align>(dst + i + 0 * F, _mm512_max_ps(_0, Load<align>(src + i + 0 * F)));
Store<align>(dst + i + 1 * F, _mm512_max_ps(_0, Load<align>(src + i + 1 * F)));
Store<align>(dst + i + 2 * F, _mm512_max_ps(_0, Load<align>(src + i + 2 * F)));
Store<align>(dst + i + 3 * F, _mm512_max_ps(_0, Load<align>(src + i + 3 * F)));
}
for (; i < partialAlignedSize; i += F)
Store<align>(dst + i, _mm512_max_ps(_0, Load<align>(src + i)));
if (i < size)
{
__mmask16 tailMask = __mmask16(-1) >> (F + i - size);
__m512 _src = Load<align, true>(src + i, tailMask);
Store<align, true>(dst + i, _mm512_max_ps(_0, _src), tailMask);
}
}
else
{
__m512 _slope = _mm512_set1_ps(*slope);
for (; i < fullAlignedSize; i += QF)
{
NeuralRelu<align, true>(src + i + 0 * F, _slope, dst + i + 0 * F);
NeuralRelu<align, true>(src + i + 1 * F, _slope, dst + i + 1 * F);
NeuralRelu<align, true>(src + i + 2 * F, _slope, dst + i + 2 * F);
NeuralRelu<align, true>(src + i + 3 * F, _slope, dst + i + 3 * F);
}
for (; i < partialAlignedSize; i += F)
NeuralRelu<align, true>(src + i, _slope, dst + i);
if (i < size)
{
__mmask16 tailMask = __mmask16(-1) >> (F + i - size);
NeuralRelu<align, true>(src + i, _slope, dst + i, tailMask);
}
}
}
void NeuralRelu(const float * src, size_t size, const float * slope, float * dst)
{
if (Aligned(src) && Aligned(dst))
NeuralRelu<true>(src, size, slope, dst);
else
NeuralRelu<false>(src, size, slope, dst);
}
template <bool align, bool mask> SIMD_INLINE void NeuralDerivativeRelu(const float * src, const __m512 & _0, const __m512 & _1, const __m512 & slope, float * dst, __mmask16 m = -1)
{
__m512 _src = Load<align, mask>(src, m);
__mmask16 positive = _mm512_cmp_ps_mask(_src, _0, _CMP_GT_OS);
__m512 _dst = Load<align, mask>(dst, m);
Store<align, mask>(dst, _mm512_mul_ps(_mm512_mask_blend_ps(positive, slope, _1), _dst), m);
}
template <bool align> SIMD_INLINE void NeuralDerivativeRelu(const float * src, size_t size, const float * slope, float * dst)
{
__m512 _0 = _mm512_set1_ps(0.0f);
__m512 _1 = _mm512_set1_ps(1.0f);
__m512 _slope = _mm512_set1_ps(slope[0]);
size_t partialAlignedSize = Simd::AlignLo(size, F);
size_t fullAlignedSize = Simd::AlignLo(size, QF);
size_t i = 0;
for (; i < fullAlignedSize; i += QF)
{
NeuralDerivativeRelu<align, true>(src + i + 0 * F, _0, _1, _slope, dst + i + 0 * F);
NeuralDerivativeRelu<align, true>(src + i + 1 * F, _0, _1, _slope, dst + i + 1 * F);
NeuralDerivativeRelu<align, true>(src + i + 2 * F, _0, _1, _slope, dst + i + 2 * F);
NeuralDerivativeRelu<align, true>(src + i + 3 * F, _0, _1, _slope, dst + i + 3 * F);
}
for (; i < partialAlignedSize; i += F)
NeuralDerivativeRelu<align, true>(src + i, _0, _1, _slope, dst + i);
if (i < size)
{
__mmask16 tailMask = __mmask16(-1) >> (F + i - size);
NeuralDerivativeRelu<align, true>(src + i, _0, _1, _slope, dst + i, tailMask);
}
}
void NeuralDerivativeRelu(const float * src, size_t size, const float * slope, float * dst)
{
if (Aligned(src) && Aligned(dst))
NeuralDerivativeRelu<true>(src, size, slope, dst);
else
NeuralDerivativeRelu<false>(src, size, slope, dst);
}
class PowEstimator
{
__m512i _exponent, _mantissa, _127;
__m512 _1_0, _0_5;
void Init()
{
_exponent = _mm512_set1_epi32(0x7F800000);
_mantissa = _mm512_set1_epi32(0x007FFFFF);
_127 = _mm512_set1_epi32(127);
_1_0 = _mm512_set1_ps(1.0f);
_0_5 = _mm512_set1_ps(0.5f);
}
SIMD_INLINE __m512 Poly5(__m512 x, float a, float b, float c, float d, float e, float f)
{
__m512 p = _mm512_set1_ps(f);
p = _mm512_fmadd_ps(x, p, _mm512_set1_ps(e));
p = _mm512_fmadd_ps(x, p, _mm512_set1_ps(d));
p = _mm512_fmadd_ps(x, p, _mm512_set1_ps(c));
p = _mm512_fmadd_ps(x, p, _mm512_set1_ps(b));
p = _mm512_fmadd_ps(x, p, _mm512_set1_ps(a));
return p;
}
SIMD_INLINE __m512 Exp2(__m512 x)
{
x = _mm512_max_ps(_mm512_min_ps(x, _mm512_set1_ps(129.00000f)), _mm512_set1_ps(-126.99999f));
__m512i ipart = _mm512_cvtps_epi32(_mm512_sub_ps(x, _0_5));
__m512 fpart = _mm512_sub_ps(x, _mm512_cvtepi32_ps(ipart));
__m512 expipart = _mm512_castsi512_ps(_mm512_slli_epi32(_mm512_add_epi32(ipart, _mm512_set1_epi32(127)), 23));
__m512 expfpart = Poly5(fpart, 9.9999994e-1f, 6.9315308e-1f, 2.4015361e-1f, 5.5826318e-2f, 8.9893397e-3f, 1.8775767e-3f);
return _mm512_mul_ps(expipart, expfpart);
}
SIMD_INLINE __m512 Log2(__m512 x)
{
__m512i i = _mm512_castps_si512(x);
__m512 e = _mm512_cvtepi32_ps(_mm512_sub_epi32(_mm512_srli_epi32(_mm512_and_si512(i, _exponent), 23), _127));
__m512 m = _mm512_or_ps(_mm512_castsi512_ps(_mm512_and_si512(i, _mantissa)), _1_0);
__m512 p = Poly5(m, 3.1157899f, -3.3241990f, 2.5988452f, -1.2315303f, 3.1821337e-1f, -3.4436006e-2f);
return _mm512_fmadd_ps(p, _mm512_sub_ps(m, _1_0), e);
}
SIMD_INLINE __m512 Pow(__m512 basis, __m512 exponent)
{
return Exp2(_mm512_mul_ps(Log2(basis), exponent));
}
template<bool align> void Run(const float * src, size_t size, const float * exponent, float * dst)
{
if (align)
assert(Aligned(src) && Aligned(dst));
float e = exponent[0];
size_t alignedSize = AlignLo(size, F);
__m512 _e = _mm512_set1_ps(e);
size_t i = 0;
for (; i < alignedSize; i += F)
Store<align>(dst + i, Pow(Load<align>(src + i), _e));
for (; i < size; ++i)
dst[i] = Base::Pow(src[i], e);
}
public:
void Run(const float * src, size_t size, const float * exponent, float * dst)
{
Init();
if (Aligned(src) && Aligned(dst))
Run<true>(src, size, exponent, dst);
else
Run<false>(src, size, exponent, dst);
}
};
void NeuralPow(const float * src, size_t size, const float * exponent, float * dst)
{
#if defined(_MSC_VER) && _MSC_VER <= 1912
Avx2::NeuralPow(src, size, exponent, dst);
#else
PowEstimator estimator;
estimator.Run(src, size, exponent, dst);
#endif
}
template <bool align, bool mask> SIMD_INLINE void NeuralUpdateWeights(const float * x, const __m512 & a, const __m512 & b, float * d, float * w, __mmask16 m)
{
__m512 _x = Load<align, mask>(x, m);
__m512 _d = Load<align, mask>(d, m);
_d = _mm512_fmadd_ps(a, _d, _mm512_mul_ps(b, _x));
Store<align, mask>(d, _d, m);
__m512 _w = Load<align, mask>(w, m);
Store<align, mask>(w, _mm512_add_ps(_w, _d), m);
}
template <bool align, bool mask> SIMD_INLINE void NeuralUpdateWeights(const float * x, size_t offset, const __m512 & a, const __m512 & b, float * d, float * w, __mmask16 m = -1)
{
NeuralUpdateWeights<align, mask>(x + offset, a, b, d + offset, w + offset, m);
}
template <bool align> SIMD_INLINE void NeuralUpdateWeights(const float * x, size_t size, const float & a, const float & b, float * d, float * w)
{
if (align)
assert(Aligned(x) && Aligned(d) && Aligned(w));
__m512 _a = _mm512_set1_ps(a);
__m512 _b = _mm512_set1_ps(b);
size_t partialAlignedSize = AlignLo(size, F);
size_t fullAlignedSize = AlignLo(size, QF);
size_t i = 0;
for (; i < fullAlignedSize; i += QF)
{
NeuralUpdateWeights<align, false>(x, i + F * 0, _a, _b, d, w);
NeuralUpdateWeights<align, false>(x, i + F * 1, _a, _b, d, w);
NeuralUpdateWeights<align, false>(x, i + F * 2, _a, _b, d, w);
NeuralUpdateWeights<align, false>(x, i + F * 3, _a, _b, d, w);
}
for (; i < partialAlignedSize; i += F)
NeuralUpdateWeights<align, false>(x, i, _a, _b, d, w);
if (i < size)
{
__mmask16 tailMask = __mmask16(-1) >> (F + i - size);
NeuralUpdateWeights<align, true>(x, i, _a, _b, d, w, tailMask);
}
}
void NeuralUpdateWeights(const float * x, size_t size, const float * a, const float * b, float * d, float * w)
{
if (Aligned(x) && Aligned(d) && Aligned(w))
NeuralUpdateWeights<true>(x, size, *a, *b, d, w);
else
NeuralUpdateWeights<false>(x, size, *a, *b, d, w);
}
template <bool align, bool mask> SIMD_INLINE void AdaptiveGradientUpdate(const float * delta, const __m512 & norm, const __m512 & alpha, const __m512 & epsilon, float * gradient, float * weight, __mmask16 m)
{
__m512 _delta = Load<align, mask>(delta, m);
__m512 d = _mm512_mul_ps(_delta, norm);
__m512 _gradient = Load<align, mask>(gradient, m);
_gradient = _mm512_fmadd_ps(d, d, _gradient);
Store<align, mask>(gradient, _gradient, m);
__m512 _weight = Load<align, mask>(weight, m);
Store<align, mask>(weight, _mm512_sub_ps(_weight, _mm512_mul_ps(_mm512_mul_ps(alpha, d), Rsqrt14(_mm512_add_ps(_gradient, epsilon)))), m);
}
template <bool align, bool mask> SIMD_INLINE void AdaptiveGradientUpdate(const float * delta, size_t offset, const __m512 & norm, const __m512 & alpha, const __m512 & epsilon, float * gradient, float * weight, __mmask16 m = -1)
{
AdaptiveGradientUpdate<align, mask>(delta + offset, norm, alpha, epsilon, gradient + offset, weight + offset, m);
}
template <bool align> void NeuralAdaptiveGradientUpdate(const float * delta, size_t size, size_t batch, const float * alpha, const float * epsilon, float * gradient, float * weight)
{
if (align)
assert(Aligned(delta) && Aligned(gradient) && Aligned(weight));
const float norm = (float)(1.0 / batch);
__m512 _norm = _mm512_set1_ps(norm);
__m512 _alpha = _mm512_set1_ps(*alpha);
__m512 _epsilon = _mm512_set1_ps(*epsilon);
size_t partialAlignedSize = AlignLo(size, F);
size_t fullAlignedSize = AlignLo(size, QF);
size_t i = 0;
for (; i < fullAlignedSize; i += QF)
{
AdaptiveGradientUpdate<align, false>(delta, i + F * 0, _norm, _alpha, _epsilon, gradient, weight);
AdaptiveGradientUpdate<align, false>(delta, i + F * 1, _norm, _alpha, _epsilon, gradient, weight);
AdaptiveGradientUpdate<align, false>(delta, i + F * 2, _norm, _alpha, _epsilon, gradient, weight);
AdaptiveGradientUpdate<align, false>(delta, i + F * 3, _norm, _alpha, _epsilon, gradient, weight);
}
for (; i < partialAlignedSize; i += F)
AdaptiveGradientUpdate<align, false>(delta, i, _norm, _alpha, _epsilon, gradient, weight);
if (i < size)
{
__mmask16 tailMask = __mmask16(-1) >> (F + i - size);
AdaptiveGradientUpdate<align, true>(delta, i, _norm, _alpha, _epsilon, gradient, weight, tailMask);
}
}
void NeuralAdaptiveGradientUpdate(const float * delta, size_t size, size_t batch, const float * alpha, const float * epsilon, float * gradient, float * weight)
{
if (Aligned(delta) && Aligned(gradient) && Aligned(weight))
NeuralAdaptiveGradientUpdate<true>(delta, size, batch, alpha, epsilon, gradient, weight);
else
NeuralAdaptiveGradientUpdate<false>(delta, size, batch, alpha, epsilon, gradient, weight);
}
template <size_t size> SIMD_INLINE void LoadWeightsForward(const float * src, __m512 * dst)
{
for (size_t i = 0; i < size; ++i)
dst[i] = _mm512_set1_ps(src[i]);
}
template <size_t size> SIMD_INLINE void LoadWeightsBackward(const float * src, __m512 * dst)
{
for (size_t i = 0; i < size; ++i)
dst[i] = _mm512_set1_ps(src[size - i - 1]);
}
namespace
{
template<int count> struct Buffer
{
Buffer(size_t width)
{
_size = width * sizeof(float);
size_t stride = AlignHi(width + 2 * (count - 1), F);
size_t full = count*stride * sizeof(float);
_ptr = Allocate(full);
memset(_ptr, 0, full);
rows[0] = (float*)_ptr;
for (size_t i = 1; i < count; ++i)
rows[i] = rows[i - 1] + stride;
}
void Update(const float * src)
{
float * tmp = rows[0];
if (src == NULL)
memset(tmp + count - 1, 0, _size);
else
memcpy(tmp + count - 1, src, _size);
for (size_t i = 0; i < count - 1; ++i)
rows[i] = rows[i + 1];
rows[count - 1] = tmp;
}
~Buffer()
{
Free(_ptr);
}
float * rows[count];
private:
size_t _size;
void * _ptr;
};
}
template<size_t coreX, size_t coreY> struct Convolution
{
template<bool align, bool mask> static SIMD_INLINE __m512 Forward(const float * src, size_t stride, const __m512 * weights, __mmask16 m = -1);
template<bool align, bool mask> static SIMD_INLINE __m512 Backward(const Buffer<coreX> & buffer, size_t offset, const __m512 * weights, __mmask16 m = -1);
template <bool align, bool mask> static SIMD_INLINE void Sum1x1(const float * src0, size_t srcStride, const float * dst0, __m512 * sums, __mmask16 m = -1);
template <bool align, bool mask> static SIMD_INLINE void Sum2x1(const float * src0, size_t srcStride, const float * dst0, size_t dstStride, __m512 * sums, __mmask16 m = -1);
template <bool align, bool mask> static SIMD_INLINE void Sum1x2(const float * src0, size_t srcStride, const float * dst0, __m512 * sums);
template <bool align, bool mask> static SIMD_INLINE void Sum2x2(const float * src0, size_t srcStride, const float * dst0, size_t dstStride, __m512 * sums);
};
template<> struct Convolution<2, 2>
{
template <bool align, bool mask> static SIMD_INLINE __m512 RowConvolution(const float * src, const __m512 * weights, __mmask16 m = -1)
{
__m512 src0 = Load<align, mask>(src, m);
__m512 src1 = Load<false, mask>(src + 1, m);
return _mm512_fmadd_ps(src0, weights[0], _mm512_mul_ps(src1, weights[1]));
}
template<bool align, bool mask> static SIMD_INLINE __m512 Forward(const float * src, size_t stride, const __m512 * weights, __mmask16 m = -1)
{
__m512 row0 = RowConvolution<align, mask>(src, weights, m);
__m512 row1 = RowConvolution<align, mask>(src + stride, weights + 2, m);
return _mm512_add_ps(row0, row1);
}
template<bool align, bool mask> static SIMD_INLINE __m512 Backward(const Buffer<2> & buffer, size_t offset, const __m512 * weights, __mmask16 m = -1)
{
__m512 row0 = RowConvolution<align, mask>(buffer.rows[0] + offset, weights + 0, m);
__m512 row1 = RowConvolution<align, mask>(buffer.rows[1] + offset, weights + 2, m);
return _mm512_add_ps(row0, row1);
}
template <bool align, bool mask> static SIMD_INLINE void Sum1x1(const float * src0, size_t srcStride, const float * dst0, __m512 * sums, __mmask16 m = -1)
{
const float * src1 = src0 + srcStride;
__m512 dst00 = Load<align, mask>(dst0, m);
sums[0] = _mm512_fmadd_ps(dst00, (Load<align, mask>(src0 + 0, m)), sums[0]);
sums[1] = _mm512_fmadd_ps(dst00, (Load<false, mask>(src0 + 1, m)), sums[1]);
sums[2] = _mm512_fmadd_ps(dst00, (Load<align, mask>(src1 + 0, m)), sums[2]);
sums[3] = _mm512_fmadd_ps(dst00, (Load<false, mask>(src1 + 1, m)), sums[3]);
}
template <bool align, bool mask> static SIMD_INLINE void Sum2x1(const float * src0, size_t srcStride, const float * dst0, size_t dstStride, __m512 * sums, __mmask16 m = -1)
{
const float * src1 = src0 + srcStride;
const float * src2 = src1 + srcStride;
const float * dst1 = dst0 + dstStride;
__m512 dst00 = Load<align, mask>(dst0, m);
__m512 src00 = Load<align, mask>(src0, m);
__m512 src01 = Load<false, mask>(src0 + 1, m);
__m512 src10 = Load<align, mask>(src1, m);
__m512 src11 = Load<false, mask>(src1 + 1, m);
sums[0] = _mm512_fmadd_ps(dst00, src00, sums[0]);
sums[1] = _mm512_fmadd_ps(dst00, src01, sums[1]);
sums[2] = _mm512_fmadd_ps(dst00, src10, sums[2]);
sums[3] = _mm512_fmadd_ps(dst00, src11, sums[3]);
__m512 dst10 = Load<align, mask>(dst1, m);
__m512 src20 = Load<align, mask>(src2, m);
__m512 src21 = Load<false, mask>(src2 + 1, m);
sums[0] = _mm512_fmadd_ps(dst10, src10, sums[0]);
sums[1] = _mm512_fmadd_ps(dst10, src11, sums[1]);
sums[2] = _mm512_fmadd_ps(dst10, src20, sums[2]);
sums[3] = _mm512_fmadd_ps(dst10, src21, sums[3]);
}
template <bool align> static SIMD_INLINE void Sum1x2(const float * src0, size_t srcStride, const float * dst0, __m512 * sums)
{
const float * src1 = src0 + srcStride;
__m512 dst00 = Load<align>(dst0);
__m512 src00 = Load<align>(src0);
__m512 src01 = Load<align>(src0 + F);
__m512 src10 = Load<align>(src1);
__m512 src11 = Load<align>(src1 + F);
sums[0] = _mm512_fmadd_ps(dst00, src00, sums[0]);
sums[1] = _mm512_fmadd_ps(dst00, Alignr<1>(src00, src01), sums[1]);
sums[2] = _mm512_fmadd_ps(dst00, src10, sums[2]);
sums[3] = _mm512_fmadd_ps(dst00, Alignr<1>(src10, src11), sums[3]);
__m512 dst10 = Load<align>(dst0 + F);
__m512 src02 = Load<false>(src0 + F + 1);
__m512 src12 = Load<false>(src1 + F + 1);
sums[0] = _mm512_fmadd_ps(dst10, src01, sums[0]);
sums[1] = _mm512_fmadd_ps(dst10, src02, sums[1]);
sums[2] = _mm512_fmadd_ps(dst10, src11, sums[2]);
sums[3] = _mm512_fmadd_ps(dst10, src12, sums[3]);
}
template <bool align> static SIMD_INLINE void Sum2x2(const float * src0, size_t srcStride, const float * dst0, size_t dstStride, __m512 * sums)
{
const float * src1 = src0 + srcStride;
const float * src2 = src1 + srcStride;
const float * dst1 = dst0 + dstStride;
__m512 dst00 = Load<align>(dst0);
__m512 src000 = Load<align>(src0);
__m512 src010 = Load<align>(src0 + F);
__m512 src100 = Load<align>(src1);
__m512 src110 = Load<align>(src1 + F);
__m512 src101 = Alignr<1>(src100, src110);
sums[0] = _mm512_fmadd_ps(dst00, src000, sums[0]);
sums[1] = _mm512_fmadd_ps(dst00, Alignr<1>(src000, src010), sums[1]);
sums[2] = _mm512_fmadd_ps(dst00, src100, sums[2]);
sums[3] = _mm512_fmadd_ps(dst00, src101, sums[3]);
__m512 dst01 = Load<align>(dst0 + F);
__m512 src011 = Load<false>(src0 + F + 1);
__m512 src111 = Load<false>(src1 + F + 1);
sums[0] = _mm512_fmadd_ps(dst01, src010, sums[0]);
sums[1] = _mm512_fmadd_ps(dst01, src011, sums[1]);
sums[2] = _mm512_fmadd_ps(dst01, src110, sums[2]);
sums[3] = _mm512_fmadd_ps(dst01, src111, sums[3]);
__m512 dst10 = Load<align>(dst1);
__m512 src200 = Load<align>(src2);
__m512 src210 = Load<align>(src2 + F);
sums[0] = _mm512_fmadd_ps(dst10, src100, sums[0]);
sums[1] = _mm512_fmadd_ps(dst10, src101, sums[1]);
sums[2] = _mm512_fmadd_ps(dst10, src200, sums[2]);
sums[3] = _mm512_fmadd_ps(dst10, Alignr<1>(src200, src210), sums[3]);
__m512 dst11 = Load<align>(dst1 + F);
__m512 src211 = Load<false>(src2 + F + 1);
sums[0] = _mm512_fmadd_ps(dst11, src110, sums[0]);
sums[1] = _mm512_fmadd_ps(dst11, src111, sums[1]);
sums[2] = _mm512_fmadd_ps(dst11, src210, sums[2]);
sums[3] = _mm512_fmadd_ps(dst11, src211, sums[3]);
}
};
template<> struct Convolution<3, 3>
{
template <bool align, bool mask> static SIMD_INLINE __m512 RowConvolution(const float * src, const __m512 * weights, __mmask16 m = -1)
{
__m512 src0 = Load<align, mask>(src, m);
__m512 src1 = Load<false, mask>(src + 1, m);
__m512 src2 = Load<false, mask>(src + 2, m);
return _mm512_fmadd_ps(src0, weights[0], _mm512_fmadd_ps(src1, weights[1], _mm512_mul_ps(src2, weights[2])));
}
template<bool align, bool mask> static SIMD_INLINE __m512 Forward(const float * src, size_t stride, const __m512 * weights, __mmask16 m = -1)
{
__m512 row0 = RowConvolution<align, mask>(src, weights, m);
__m512 row1 = RowConvolution<align, mask>(src + stride, weights + 3, m);
__m512 row2 = RowConvolution<align, mask>(src + 2 * stride, weights + 6, m);
return _mm512_add_ps(_mm512_add_ps(row0, row1), row2);
}
template<bool align, bool mask> static SIMD_INLINE __m512 Backward(const Buffer<3> & buffer, size_t offset, const __m512 * weights, __mmask16 m = -1)
{
__m512 row0 = RowConvolution<align, mask>(buffer.rows[0] + offset, weights + 0, m);
__m512 row1 = RowConvolution<align, mask>(buffer.rows[1] + offset, weights + 3, m);
__m512 row2 = RowConvolution<align, mask>(buffer.rows[2] + offset, weights + 6, m);
return _mm512_add_ps(_mm512_add_ps(row0, row1), row2);
}
template <bool align, bool mask> static SIMD_INLINE void Sum1x1(const float * src0, size_t srcStride, const float * dst0, __m512 * sums, __mmask16 m = -1)
{
const float * src1 = src0 + srcStride;
const float * src2 = src1 + srcStride;
__m512 dst00 = Load<align, mask>(dst0, m);
__m512 src00 = Load<align>(src0);
__m512 src0f = Load<align>(src0 + F);
sums[0] = _mm512_fmadd_ps(dst00, (Alignr<0, mask>(src00, src0f, m)), sums[0]);
sums[1] = _mm512_fmadd_ps(dst00, (Alignr<1, mask>(src00, src0f, m)), sums[1]);
sums[2] = _mm512_fmadd_ps(dst00, (Alignr<2, mask>(src00, src0f, m)), sums[2]);
__m512 src10 = Load<align>(src1);
__m512 src1f = Load<align>(src1 + F);
sums[3] = _mm512_fmadd_ps(dst00, (Alignr<0, mask>(src10, src1f, m)), sums[3]);
sums[4] = _mm512_fmadd_ps(dst00, (Alignr<1, mask>(src10, src1f, m)), sums[4]);
sums[5] = _mm512_fmadd_ps(dst00, (Alignr<2, mask>(src10, src1f, m)), sums[5]);
__m512 src20 = Load<align>(src2);
__m512 src2f = Load<align>(src2 + F);
sums[6] = _mm512_fmadd_ps(dst00, (Alignr<0, mask>(src20, src2f, m)), sums[6]);
sums[7] = _mm512_fmadd_ps(dst00, (Alignr<1, mask>(src20, src2f, m)), sums[7]);
sums[8] = _mm512_fmadd_ps(dst00, (Alignr<2, mask>(src20, src2f, m)), sums[8]);
}
template <bool align, bool mask> static SIMD_INLINE void Sum2x1(const float * src0, size_t srcStride, const float * dst0, size_t dstStride, __m512 * sums, __mmask16 m = -1)
{
const float * dst1 = dst0 + dstStride;
const float * src1 = src0 + srcStride;
const float * src2 = src1 + srcStride;
const float * src3 = src2 + srcStride;
__m512 dst00 = Load<align, mask>(dst0, m);
__m512 src00 = Load<align>(src0);
__m512 src0f = Load<align>(src0 + F);
sums[0] = _mm512_fmadd_ps(dst00, (Alignr<0, mask>(src00, src0f, m)), sums[0]);
sums[1] = _mm512_fmadd_ps(dst00, (Alignr<1, mask>(src00, src0f, m)), sums[1]);
sums[2] = _mm512_fmadd_ps(dst00, (Alignr<2, mask>(src00, src0f, m)), sums[2]);
__m512 dst10 = Load<align, mask>(dst1, m);
__m512 src10 = Load<align>(src1);
__m512 src1f = Load<align>(src1 + F);
sums[0] = _mm512_fmadd_ps(dst10, Mask<mask>(src10, m), sums[0]);
sums[3] = _mm512_fmadd_ps(dst00, Mask<mask>(src10, m), sums[3]);
__m512 src11 = Alignr<1, mask>(src10, src1f, m);
sums[1] = _mm512_fmadd_ps(dst10, src11, sums[1]);
sums[4] = _mm512_fmadd_ps(dst00, src11, sums[4]);
__m512 src12 = Alignr<2, mask>(src10, src1f, m);
sums[2] = _mm512_fmadd_ps(dst10, src12, sums[2]);
sums[5] = _mm512_fmadd_ps(dst00, src12, sums[5]);
__m512 src20 = Load<align>(src2);
__m512 src2f = Load<align>(src2 + F);
sums[3] = _mm512_fmadd_ps(dst10, Mask<mask>(src20, m), sums[3]);
sums[6] = _mm512_fmadd_ps(dst00, Mask<mask>(src20, m), sums[6]);
__m512 src21 = Alignr<1, mask>(src20, src2f, m);
sums[4] = _mm512_fmadd_ps(dst10, src21, sums[4]);
sums[7] = _mm512_fmadd_ps(dst00, src21, sums[7]);
__m512 src22 = Alignr<2, mask>(src20, src2f, m);
sums[5] = _mm512_fmadd_ps(dst10, src22, sums[5]);
sums[8] = _mm512_fmadd_ps(dst00, src22, sums[8]);
__m512 src30 = Load<align>(src3);
__m512 src3f = Load<align>(src3 + F);
sums[6] = _mm512_fmadd_ps(dst10, (Alignr<0, mask>(src30, src3f, m)), sums[6]);
sums[7] = _mm512_fmadd_ps(dst10, (Alignr<1, mask>(src30, src3f, m)), sums[7]);
sums[8] = _mm512_fmadd_ps(dst10, (Alignr<2, mask>(src30, src3f, m)), sums[8]);
}
};
template<> struct Convolution<4, 4>
{
template <bool align, bool mask> static SIMD_INLINE __m512 RowConvolution(const float * src, const __m512 * weights, __mmask16 m = -1)
{
__m512 src0 = Load<align>(src);
__m512 srcf = Load<align>(src + F);
__m512 sum0 = _mm512_fmadd_ps(Alignr<0>(src0, srcf), weights[0], _mm512_mul_ps(Alignr<1>(src0, srcf), weights[1]));
__m512 sum1 = _mm512_fmadd_ps(Alignr<2>(src0, srcf), weights[2], _mm512_mul_ps(Alignr<3>(src0, srcf), weights[3]));
return _mm512_add_ps(sum0, sum1);
}
template<bool align, bool mask> static SIMD_INLINE __m512 Forward(const float * src, size_t stride, const __m512 * weights, __mmask16 m = -1)
{
__m512 row0 = RowConvolution<align, mask>(src, weights, m);
__m512 row1 = RowConvolution<align, mask>(src + stride, weights + 4, m);
__m512 row2 = RowConvolution<align, mask>(src + 2 * stride, weights + 8, m);
__m512 row3 = RowConvolution<align, mask>(src + 3 * stride, weights + 12, m);
return _mm512_add_ps(_mm512_add_ps(row0, row1), _mm512_add_ps(row2, row3));
}
template<bool align, bool mask> static SIMD_INLINE __m512 Backward(const Buffer<4> & buffer, size_t offset, const __m512 * weights, __mmask16 m = -1)
{
__m512 row0 = RowConvolution<align, mask>(buffer.rows[0] + offset, weights + 0, m);
__m512 row1 = RowConvolution<align, mask>(buffer.rows[1] + offset, weights + 4, m);
__m512 row2 = RowConvolution<align, mask>(buffer.rows[2] + offset, weights + 8, m);
__m512 row3 = RowConvolution<align, mask>(buffer.rows[3] + offset, weights + 12, m);
return _mm512_add_ps(_mm512_add_ps(row0, row1), _mm512_add_ps(row2, row3));
}
template <bool align, bool mask> static SIMD_INLINE void Sum1x1(const float * src0, size_t srcStride, const float * dst0, __m512 * sums, __mmask16 m = -1)
{
const float * src1 = src0 + srcStride;
const float * src2 = src1 + srcStride;
const float * src3 = src2 + srcStride;
__m512 dst00 = Load<align, mask>(dst0, m);
__m512 src00 = Load<align>(src0);
__m512 src0f = Load<align>(src0 + F);
sums[0] = _mm512_fmadd_ps(dst00, (Alignr<0, mask>(src00, src0f, m)), sums[0]);
sums[1] = _mm512_fmadd_ps(dst00, (Alignr<1, mask>(src00, src0f, m)), sums[1]);
sums[2] = _mm512_fmadd_ps(dst00, (Alignr<2, mask>(src00, src0f, m)), sums[2]);
sums[3] = _mm512_fmadd_ps(dst00, (Alignr<3, mask>(src00, src0f, m)), sums[3]);
__m512 src10 = Load<align>(src1);
__m512 src1f = Load<align>(src1 + F);
sums[4] = _mm512_fmadd_ps(dst00, (Alignr<0, mask>(src10, src1f, m)), sums[4]);
sums[5] = _mm512_fmadd_ps(dst00, (Alignr<1, mask>(src10, src1f, m)), sums[5]);
sums[6] = _mm512_fmadd_ps(dst00, (Alignr<2, mask>(src10, src1f, m)), sums[6]);
sums[7] = _mm512_fmadd_ps(dst00, (Alignr<3, mask>(src10, src1f, m)), sums[7]);
__m512 src20 = Load<align>(src2);
__m512 src2f = Load<align>(src2 + F);
sums[8] = _mm512_fmadd_ps(dst00, (Alignr<0, mask>(src20, src2f, m)), sums[8]);
sums[9] = _mm512_fmadd_ps(dst00, (Alignr<1, mask>(src20, src2f, m)), sums[9]);
sums[10] = _mm512_fmadd_ps(dst00, (Alignr<2, mask>(src20, src2f, m)), sums[10]);
sums[11] = _mm512_fmadd_ps(dst00, (Alignr<3, mask>(src20, src2f, m)), sums[11]);
__m512 src30 = Load<align>(src3);
__m512 src3f = Load<align>(src3 + F);
sums[12] = _mm512_fmadd_ps(dst00, (Alignr<0, mask>(src30, src3f, m)), sums[12]);
sums[13] = _mm512_fmadd_ps(dst00, (Alignr<1, mask>(src30, src3f, m)), sums[13]);
sums[14] = _mm512_fmadd_ps(dst00, (Alignr<2, mask>(src30, src3f, m)), sums[14]);
sums[15] = _mm512_fmadd_ps(dst00, (Alignr<3, mask>(src30, src3f, m)), sums[15]);
}
template <bool align, bool mask> static SIMD_INLINE void Sum2x1(const float * src0, size_t srcStride, const float * dst0, size_t dstStride, __m512 * sums, __mmask16 m = -1)
{
const float * dst1 = dst0 + dstStride;
const float * src1 = src0 + srcStride;
const float * src2 = src1 + srcStride;
const float * src3 = src2 + srcStride;
const float * src4 = src3 + srcStride;
__m512 dst00 = Load<align, mask>(dst0, m);
__m512 src00 = Load<align>(src0);
__m512 src0f = Load<align>(src0 + F);
sums[0] = _mm512_fmadd_ps(dst00, (Alignr<0, mask>(src00, src0f, m)), sums[0]);
sums[1] = _mm512_fmadd_ps(dst00, (Alignr<1, mask>(src00, src0f, m)), sums[1]);
sums[2] = _mm512_fmadd_ps(dst00, (Alignr<2, mask>(src00, src0f, m)), sums[2]);
sums[3] = _mm512_fmadd_ps(dst00, (Alignr<3, mask>(src00, src0f, m)), sums[3]);
__m512 dst10 = Load<align, mask>(dst1, m);
__m512 src10 = Load<align>(src1);
__m512 src1f = Load<align>(src1 + F);
sums[0] = _mm512_fmadd_ps(dst10, Mask<mask>(src10, m), sums[0]);
sums[4] = _mm512_fmadd_ps(dst00, Mask<mask>(src10, m), sums[4]);
__m512 src11 = Alignr<1, mask>(src10, src1f, m);
sums[1] = _mm512_fmadd_ps(dst10, src11, sums[1]);
sums[5] = _mm512_fmadd_ps(dst00, src11, sums[5]);
__m512 src12 = Alignr<2, mask>(src10, src1f, m);
sums[2] = _mm512_fmadd_ps(dst10, src12, sums[2]);
sums[6] = _mm512_fmadd_ps(dst00, src12, sums[6]);
__m512 src13 = Alignr<3, mask>(src10, src1f, m);
sums[3] = _mm512_fmadd_ps(dst10, src13, sums[3]);
sums[7] = _mm512_fmadd_ps(dst00, src13, sums[7]);
__m512 src20 = Load<align>(src2);
__m512 src2f = Load<align>(src2 + F);
sums[4] = _mm512_fmadd_ps(dst10, Mask<mask>(src20, m), sums[4]);
sums[8] = _mm512_fmadd_ps(dst00, Mask<mask>(src20, m), sums[8]);
__m512 src21 = Alignr<1, mask>(src20, src2f, m);
sums[5] = _mm512_fmadd_ps(dst10, src21, sums[5]);
sums[9] = _mm512_fmadd_ps(dst00, src21, sums[9]);
__m512 src22 = Alignr<2, mask>(src20, src2f, m);
sums[6] = _mm512_fmadd_ps(dst10, src22, sums[6]);
sums[10] = _mm512_fmadd_ps(dst00, src22, sums[10]);
__m512 src23 = Alignr<3, mask>(src20, src2f, m);
sums[7] = _mm512_fmadd_ps(dst10, src23, sums[7]);
sums[11] = _mm512_fmadd_ps(dst00, src23, sums[11]);
__m512 src30 = Load<align>(src3);
__m512 src3f = Load<align>(src3 + F);
sums[8] = _mm512_fmadd_ps(dst10, Mask<mask>(src30, m), sums[8]);
sums[12] = _mm512_fmadd_ps(dst00, Mask<mask>(src30, m), sums[12]);
__m512 src31 = Alignr<1, mask>(src30, src3f, m);
sums[9] = _mm512_fmadd_ps(dst10, src31, sums[9]);
sums[13] = _mm512_fmadd_ps(dst00, src31, sums[13]);
__m512 src32 = Alignr<2, mask>(src30, src3f, m);
sums[10] = _mm512_fmadd_ps(dst10, src32, sums[10]);
sums[14] = _mm512_fmadd_ps(dst00, src32, sums[14]);
__m512 src33 = Alignr<3, mask>(src30, src3f, m);
sums[11] = _mm512_fmadd_ps(dst10, src33, sums[11]);
sums[15] = _mm512_fmadd_ps(dst00, src33, sums[15]);
__m512 src40 = Load<align>(src4);
__m512 src4f = Load<align>(src4 + F);
sums[12] = _mm512_fmadd_ps(dst10, (Alignr<0, mask>(src40, src4f, m)), sums[12]);
sums[13] = _mm512_fmadd_ps(dst10, (Alignr<1, mask>(src40, src4f, m)), sums[13]);
sums[14] = _mm512_fmadd_ps(dst10, (Alignr<2, mask>(src40, src4f, m)), sums[14]);
sums[15] = _mm512_fmadd_ps(dst10, (Alignr<3, mask>(src40, src4f, m)), sums[15]);
}
};
template<> struct Convolution<5, 5>
{
template <bool align, bool mask> static SIMD_INLINE __m512 RowConvolution(const float * src, const __m512 * weights, __mmask16 m = -1)
{
__m512 src0 = Load<align>(src);
__m512 srcf = Load<align>(src + F);
__m512 sum0 = _mm512_fmadd_ps(Alignr<0>(src0, srcf), weights[0], _mm512_mul_ps(Alignr<1>(src0, srcf), weights[1]));
__m512 sum1 = _mm512_fmadd_ps(Alignr<2>(src0, srcf), weights[2], _mm512_mul_ps(Alignr<3>(src0, srcf), weights[3]));
return _mm512_fmadd_ps(Alignr<4>(src0, srcf), weights[4], _mm512_add_ps(sum0, sum1));
}
template<bool align, bool mask> static SIMD_INLINE __m512 Forward(const float * src, size_t stride, const __m512 * weights, __mmask16 m = -1)
{
return _mm512_add_ps((RowConvolution<align, mask>(src, weights, m)),
_mm512_add_ps(_mm512_add_ps((RowConvolution<align, mask>(src + stride, weights + 5, m)),
(RowConvolution<align, mask>(src + 2 * stride, weights + 10, m))),
_mm512_add_ps((RowConvolution<align, mask>(src + 3 * stride, weights + 15, m)),
(RowConvolution<align, mask>(src + 4 * stride, weights + 20, m)))));
}
template<bool align, bool mask> static SIMD_INLINE __m512 Backward(const Buffer<5> & buffer, size_t offset, const __m512 * weights, __mmask16 m = -1)
{
return _mm512_add_ps((RowConvolution<align, mask>(buffer.rows[0] + offset, weights, m)),
_mm512_add_ps(_mm512_add_ps((RowConvolution<align, mask>(buffer.rows[1] + offset, weights + 5, m)),
(RowConvolution<align, mask>(buffer.rows[2] + offset, weights + 10, m))),
_mm512_add_ps((RowConvolution<align, mask>(buffer.rows[3] + offset, weights + 15, m)),
(RowConvolution<align, mask>(buffer.rows[4] + offset, weights + 20, m)))));
}
template <bool align, bool mask> static SIMD_INLINE void Sum1x1(const float * src0, size_t srcStride, const float * dst0, __m512 * sums, __mmask16 m = -1)
{
const float * src1 = src0 + srcStride;
const float * src2 = src1 + srcStride;
const float * src3 = src2 + srcStride;
const float * src4 = src3 + srcStride;
__m512 dst00 = Load<align, mask>(dst0, m);
__m512 src00 = Load<align>(src0);
__m512 src0f = Load<align>(src0 + F);
sums[0] = _mm512_fmadd_ps(dst00, (Alignr<0, mask>(src00, src0f, m)), sums[0]);
sums[1] = _mm512_fmadd_ps(dst00, (Alignr<1, mask>(src00, src0f, m)), sums[1]);
sums[2] = _mm512_fmadd_ps(dst00, (Alignr<2, mask>(src00, src0f, m)), sums[2]);
sums[3] = _mm512_fmadd_ps(dst00, (Alignr<3, mask>(src00, src0f, m)), sums[3]);
sums[4] = _mm512_fmadd_ps(dst00, (Alignr<4, mask>(src00, src0f, m)), sums[4]);
__m512 src10 = Load<align>(src1);
__m512 src1f = Load<align>(src1 + F);
sums[5] = _mm512_fmadd_ps(dst00, (Alignr<0, mask>(src10, src1f, m)), sums[5]);
sums[6] = _mm512_fmadd_ps(dst00, (Alignr<1, mask>(src10, src1f, m)), sums[6]);
sums[7] = _mm512_fmadd_ps(dst00, (Alignr<2, mask>(src10, src1f, m)), sums[7]);
sums[8] = _mm512_fmadd_ps(dst00, (Alignr<3, mask>(src10, src1f, m)), sums[8]);
sums[9] = _mm512_fmadd_ps(dst00, (Alignr<4, mask>(src10, src1f, m)), sums[9]);
__m512 src20 = Load<align>(src2);
__m512 src2f = Load<align>(src2 + F);
sums[10] = _mm512_fmadd_ps(dst00, (Alignr<0, mask>(src20, src2f, m)), sums[10]);
sums[11] = _mm512_fmadd_ps(dst00, (Alignr<1, mask>(src20, src2f, m)), sums[11]);
sums[12] = _mm512_fmadd_ps(dst00, (Alignr<2, mask>(src20, src2f, m)), sums[12]);
sums[13] = _mm512_fmadd_ps(dst00, (Alignr<3, mask>(src20, src2f, m)), sums[13]);
sums[14] = _mm512_fmadd_ps(dst00, (Alignr<4, mask>(src20, src2f, m)), sums[14]);
__m512 src30 = Load<align>(src3);
__m512 src3f = Load<align>(src3 + F);
sums[15] = _mm512_fmadd_ps(dst00, (Alignr<0, mask>(src30, src3f, m)), sums[15]);
sums[16] = _mm512_fmadd_ps(dst00, (Alignr<1, mask>(src30, src3f, m)), sums[16]);
sums[17] = _mm512_fmadd_ps(dst00, (Alignr<2, mask>(src30, src3f, m)), sums[17]);
sums[18] = _mm512_fmadd_ps(dst00, (Alignr<3, mask>(src30, src3f, m)), sums[18]);
sums[19] = _mm512_fmadd_ps(dst00, (Alignr<4, mask>(src30, src3f, m)), sums[19]);
__m512 src40 = Load<align>(src4);
__m512 src4f = Load<align>(src4 + F);
sums[20] = _mm512_fmadd_ps(dst00, (Alignr<0, mask>(src40, src4f, m)), sums[20]);
sums[21] = _mm512_fmadd_ps(dst00, (Alignr<1, mask>(src40, src4f, m)), sums[21]);
sums[22] = _mm512_fmadd_ps(dst00, (Alignr<2, mask>(src40, src4f, m)), sums[22]);
sums[23] = _mm512_fmadd_ps(dst00, (Alignr<3, mask>(src40, src4f, m)), sums[23]);
sums[24] = _mm512_fmadd_ps(dst00, (Alignr<4, mask>(src40, src4f, m)), sums[24]);
}
template <bool align, bool mask> static SIMD_INLINE void SumRow1(const float * src, const __m512 & dst, __m512 * sums, __mmask16 m)
{
__m512 src0 = Load<align>(src + 0);
__m512 srcf = Load<align>(src + F);
sums[0] = _mm512_fmadd_ps(dst, (Alignr<0, mask>(src0, srcf, m)), sums[0]);
sums[1] = _mm512_fmadd_ps(dst, (Alignr<1, mask>(src0, srcf, m)), sums[1]);
sums[2] = _mm512_fmadd_ps(dst, (Alignr<2, mask>(src0, srcf, m)), sums[2]);
sums[3] = _mm512_fmadd_ps(dst, (Alignr<3, mask>(src0, srcf, m)), sums[3]);
sums[4] = _mm512_fmadd_ps(dst, (Alignr<4, mask>(src0, srcf, m)), sums[4]);
}
template <bool align, bool mask> static SIMD_INLINE void SumRow2(const float * src, const __m512 & dst0, const __m512 & dst1, __m512 * sums, __mmask16 m)
{
__m512 src0 = Load<align>(src + 0);
__m512 srcf = Load<align>(src + F);
sums[0] = _mm512_fmadd_ps(dst1, Mask<mask>(src0, m), sums[0]);
sums[5] = _mm512_fmadd_ps(dst0, Mask<mask>(src0, m), sums[5]);
__m512 src1 = Alignr<1, mask>(src0, srcf, m);
sums[1] = _mm512_fmadd_ps(dst1, src1, sums[1]);
sums[6] = _mm512_fmadd_ps(dst0, src1, sums[6]);
__m512 src2 = Alignr<2, mask>(src0, srcf, m);
sums[2] = _mm512_fmadd_ps(dst1, src2, sums[2]);
sums[7] = _mm512_fmadd_ps(dst0, src2, sums[7]);
__m512 src3 = Alignr<3, mask>(src0, srcf, m);
sums[3] = _mm512_fmadd_ps(dst1, src3, sums[3]);
sums[8] = _mm512_fmadd_ps(dst0, src3, sums[8]);
__m512 src4 = Alignr<4, mask>(src0, srcf, m);
sums[4] = _mm512_fmadd_ps(dst1, src4, sums[4]);
sums[9] = _mm512_fmadd_ps(dst0, src4, sums[9]);
}
template <bool align, bool mask> static SIMD_INLINE void Sum2x1(const float * src, size_t srcStride, const float * dst, size_t dstStride, __m512 * sums, __mmask16 m = -1)
{
__m512 dst0 = Load<align, mask>(dst, m);
SumRow1<align, mask>(src, dst0, sums + 0, m);
__m512 dst1 = Load<align, mask>(dst + dstStride, m);
SumRow2<align, mask>(src + srcStride, dst0, dst1, sums + 0, m);
SumRow2<align, mask>(src + 2 * srcStride, dst0, dst1, sums + 5, m);
SumRow2<align, mask>(src + 3 * srcStride, dst0, dst1, sums + 10, m);
SumRow2<align, mask>(src + 4 * srcStride, dst0, dst1, sums + 15, m);
SumRow1<align, mask>(src + 5 * srcStride, dst1, sums + 20, m);
}
};
template <bool align, size_t coreX, size_t coreY> void NeuralAddConvolutionForward(const float * src, size_t srcStride, size_t width, size_t height, const float * weights, float * dst, size_t dstStride)
{
size_t alignedWidth = AlignLo(width, F);
__mmask16 tailMask = __mmask16(-1) >> (F + alignedWidth - width);
__m512 _weights[coreX*coreY];
LoadWeightsForward<coreX*coreY>(weights, _weights);
for (size_t row = 0; row < height; ++row)
{
size_t col = 0;
for (; col < alignedWidth; col += F)
{
__m512 sum = Convolution<coreX, coreY>::template Forward<align, false>(src + col, srcStride, _weights);
__m512 _dst = Load<align>(dst + col);
Store<align>(dst + col, _mm512_add_ps(_dst, sum));
}
if (col < width)
{
__m512 sum = Convolution<coreX, coreY>::template Forward<align, true>(src + col, srcStride, _weights);
__m512 _dst = Load<align, true>(dst + col, tailMask);
Store<align, true>(dst + col, _mm512_add_ps(_dst, sum), tailMask);
}
src += srcStride;
dst += dstStride;
}
}
void NeuralAddConvolution2x2Forward(const float * src, size_t srcStride, size_t width, size_t height, const float * weights, float * dst, size_t dstStride)
{
if (Aligned(src) && Aligned(srcStride, F) && Aligned(dst) && Aligned(dstStride, F))
NeuralAddConvolutionForward<true, 2, 2>(src, srcStride, width, height, weights, dst, dstStride);
else
NeuralAddConvolutionForward<false, 2, 2>(src, srcStride, width, height, weights, dst, dstStride);
}
void NeuralAddConvolution3x3Forward(const float * src, size_t srcStride, size_t width, size_t height, const float * weights, float * dst, size_t dstStride)
{
if (Aligned(src) && Aligned(srcStride, F) && Aligned(dst) && Aligned(dstStride, F))
NeuralAddConvolutionForward<true, 3, 3>(src, srcStride, width, height, weights, dst, dstStride);
else
NeuralAddConvolutionForward<false, 3, 3>(src, srcStride, width, height, weights, dst, dstStride);
}
void NeuralAddConvolution4x4Forward(const float * src, size_t srcStride, size_t width, size_t height, const float * weights, float * dst, size_t dstStride)
{
if (Aligned(src) && Aligned(srcStride, F) && Aligned(dst) && Aligned(dstStride, F))
NeuralAddConvolutionForward<true, 4, 4>(src, srcStride, width, height, weights, dst, dstStride);
else
NeuralAddConvolutionForward<false, 4, 4>(src, srcStride, width, height, weights, dst, dstStride);
}
void NeuralAddConvolution5x5Forward(const float * src, size_t srcStride, size_t width, size_t height, const float * weights, float * dst, size_t dstStride)
{
if (Aligned(src) && Aligned(srcStride, F) && Aligned(dst) && Aligned(dstStride, F))
NeuralAddConvolutionForward<true, 5, 5>(src, srcStride, width, height, weights, dst, dstStride);
else
NeuralAddConvolutionForward<false, 5, 5>(src, srcStride, width, height, weights, dst, dstStride);
}
template<bool condition> struct If
{
template<bool align> static SIMD_INLINE void AddMultiplied(const float * src, size_t aligned, size_t partial, size_t full, float value, float * dst)
{
Avx512f::AddMultiplied<align>(src, aligned, partial, full, value, dst);
}
};
template<> struct If<false>
{
template<bool align> static SIMD_INLINE void AddMultiplied(const float * src, size_t aligned, size_t partial, size_t full, float value, float * dst)
{
}
};
template <bool align, size_t coreX, size_t coreY> void NeuralAddConvolutionBackwardSmall(const float * src, size_t srcStride, size_t width, size_t height, const float * weights, float * dst, size_t dstStride)
{
size_t aligned = AlignLo(width, QF);
size_t partial = AlignLo(width, F);
for (size_t row = 0; row < height; ++row)
{
for (size_t dy = 0; dy < coreY; ++dy)
{
const float * w = weights + dy * coreX;
float * d = dst + dy*dstStride;
If < 0 < coreX > ::template AddMultiplied<align>(src, aligned, partial, width, w[0], d + 0);
If < 1 < coreX > ::template AddMultiplied<false>(src, aligned, partial, width, w[1], d + 1);
If < 2 < coreX > ::template AddMultiplied<false>(src, aligned, partial, width, w[2], d + 2);
If < 3 < coreX > ::template AddMultiplied<false>(src, aligned, partial, width, w[3], d + 3);
If < 4 < coreX > ::template AddMultiplied<false>(src, aligned, partial, width, w[4], d + 4);
}
src += srcStride;
dst += dstStride;
}
}
template <bool align, size_t coreX, size_t coreY> void NeuralAddConvolutionBackwardLarge(const float * src, size_t srcStride, size_t width, size_t height, const float * weights, float * dst, size_t dstStride)
{
Buffer<coreX> buffer(width);
height += coreY - 1;
width += coreX - 1;
size_t alignedWidth = AlignLo(width, F);
__mmask16 tailMask = __mmask16(-1) >> (F + alignedWidth - width);
__m512 _weights[coreX*coreY];
LoadWeightsBackward<coreX*coreY>(weights, _weights);
for (size_t row = 0; row < height; ++row)
{
buffer.Update(row <= height - coreY ? src : NULL);
size_t col = 0;
for (; col < alignedWidth; col += F)
{
__m512 sum = Convolution<coreX, coreY>::template Backward<align, false>(buffer, col, _weights);
__m512 _dst = Load<align>(dst + col);
Store<align>(dst + col, _mm512_add_ps(_dst, sum));
}
if (col < width)
{
__m512 sum = Convolution<coreX, coreY>::template Backward<false, true>(buffer, col, _weights, tailMask);
__m512 _dst = Load<align, true>(dst + col, tailMask);
Store<align, true>(dst + col, _mm512_add_ps(_dst, sum), tailMask);
}
src += srcStride;
dst += dstStride;
}
}
template <bool align, size_t coreX, size_t coreY> void NeuralAddConvolutionBackward(const float * src, size_t srcStride, size_t width, size_t height, const float * weights, float * dst, size_t dstStride)
{
if (width*height < 1024)
NeuralAddConvolutionBackwardSmall<align, coreX, coreY>(src, srcStride, width, height, weights, dst, dstStride);
else
NeuralAddConvolutionBackwardLarge<align, coreX, coreY>(src, srcStride, width, height, weights, dst, dstStride);
}
void NeuralAddConvolution2x2Backward(const float * src, size_t srcStride, size_t width, size_t height, const float * weights, float * dst, size_t dstStride)
{
if (Aligned(src) && Aligned(srcStride, F) && Aligned(dst) && Aligned(dstStride, F))
NeuralAddConvolutionBackward<true, 2, 2>(src, srcStride, width, height, weights, dst, dstStride);
else
NeuralAddConvolutionBackward<false, 2, 2>(src, srcStride, width, height, weights, dst, dstStride);
}
void NeuralAddConvolution3x3Backward(const float * src, size_t srcStride, size_t width, size_t height, const float * weights, float * dst, size_t dstStride)
{
if (Aligned(src) && Aligned(srcStride, F) && Aligned(dst) && Aligned(dstStride, F))
NeuralAddConvolutionBackward<true, 3, 3>(src, srcStride, width, height, weights, dst, dstStride);
else
NeuralAddConvolutionBackward<false, 3, 3>(src, srcStride, width, height, weights, dst, dstStride);
}
void NeuralAddConvolution4x4Backward(const float * src, size_t srcStride, size_t width, size_t height, const float * weights, float * dst, size_t dstStride)
{
if (Aligned(src) && Aligned(srcStride, F) && Aligned(dst) && Aligned(dstStride, F))
NeuralAddConvolutionBackward<true, 4, 4>(src, srcStride, width, height, weights, dst, dstStride);
else
NeuralAddConvolutionBackward<false, 4, 4>(src, srcStride, width, height, weights, dst, dstStride);
}
void NeuralAddConvolution5x5Backward(const float * src, size_t srcStride, size_t width, size_t height, const float * weights, float * dst, size_t dstStride)
{
if (Aligned(src) && Aligned(srcStride, F) && Aligned(dst) && Aligned(dstStride, F))
NeuralAddConvolutionBackward<true, 5, 5>(src, srcStride, width, height, weights, dst, dstStride);
else
NeuralAddConvolutionBackward<false, 5, 5>(src, srcStride, width, height, weights, dst, dstStride);
}
SIMD_INLINE __m128 PartialSum(const __m512 & src)
{
__m128 lo = _mm_add_ps(_mm512_extractf32x4_ps(src, 0), _mm512_extractf32x4_ps(src, 1));
__m128 hi = _mm_add_ps(_mm512_extractf32x4_ps(src, 2), _mm512_extractf32x4_ps(src, 3));
return _mm_add_ps(lo, hi);
}
SIMD_INLINE void Add4ExtractedSums(const __m512 * src, float * dst)
{
__m128 s0 = PartialSum(src[0]);
__m128 s1 = PartialSum(src[1]);
__m128 s2 = PartialSum(src[2]);
__m128 s3 = PartialSum(src[3]);
__m128 sums = _mm_hadd_ps(_mm_hadd_ps(s0, s1), _mm_hadd_ps(s2, s3));
_mm_storeu_ps(dst, _mm_add_ps(_mm_loadu_ps(dst), sums));
}
template <bool align, size_t coreX, size_t coreY> SIMD_INLINE void NeuralAddConvolutionSum1x1(const float * src, size_t srcStride, const float * dst, size_t dstStride, size_t width, size_t height, float * sums)
{
size_t alignedWidth = Simd::AlignLo(width, F);
__mmask16 tailMask = __mmask16(-1) >> (F + alignedWidth - width);
__m512 _sums[coreX*coreY];
memset(_sums, 0, sizeof(_sums));
size_t row = 0;
for (; row < height; ++row)
{
size_t col = 0;
for (; col < alignedWidth; col += F)
Convolution<coreX, coreY>::template Sum1x1<align, false>(src + col, srcStride, dst + col, _sums);
if (col < width)
Convolution<coreX, coreY>::template Sum1x1<align, true>(src + col, srcStride, dst + col, _sums, tailMask);
src += srcStride;
dst += dstStride;
}
size_t i = 0, n = Simd::AlignLo(coreX*coreY, 4);
#ifndef _MSC_VER
for (; i < n; i += 4)
Add4ExtractedSums(_sums + i, sums + i);
#endif
for (; i < coreX*coreY; ++i)
sums[i] += ExtractSum(_sums[i]);
}
template <bool align, size_t coreX, size_t coreY> SIMD_INLINE void NeuralAddConvolutionSum2x1(const float * src, size_t srcStride, const float * dst, size_t dstStride, size_t width, size_t height, float * sums)
{
size_t alignedHeight = Simd::AlignLo(height, 2);
size_t alignedWidth = Simd::AlignLo(width, F);
__mmask16 tailMask = __mmask16(-1) >> (F + alignedWidth - width);
__m512 _sums[coreX*coreY];
memset(_sums, 0, sizeof(_sums));
size_t row = 0;
for (; row < alignedHeight; row += 2)
{
size_t col = 0;
for (; col < alignedWidth; col += F)
Convolution<coreX, coreY>::template Sum2x1<align, false>(src + col, srcStride, dst + col, dstStride, _sums);
if (col < width)
Convolution<coreX, coreY>::template Sum2x1<align, true>(src + col, srcStride, dst + col, dstStride, _sums, tailMask);
src += 2 * srcStride;
dst += 2 * dstStride;
}
for (; row < height; ++row)
{
size_t col = 0;
for (; col < alignedWidth; col += F)
Convolution<coreX, coreY>::template Sum1x1<align, false>(src + col, srcStride, dst + col, _sums);
if (col < width)
Convolution<coreX, coreY>::template Sum1x1<align, true>(src + col, srcStride, dst + col, _sums, tailMask);
src += srcStride;
dst += dstStride;
}
size_t i = 0, n = Simd::AlignLo(coreX*coreY, 4);
#ifndef _MSC_VER
for (; i < n; i += 4)
Add4ExtractedSums(_sums + i, sums + i);
#endif
for (; i < coreX*coreY; ++i)
sums[i] += ExtractSum(_sums[i]);
}
template <bool align, size_t coreX, size_t coreY> SIMD_INLINE void NeuralAddConvolutionSum2x2(const float * src, size_t srcStride, const float * dst, size_t dstStride, size_t width, size_t height, float * sums)
{
size_t alignedHeight = Simd::AlignLo(height, 2);
size_t fullAlignedWidth = Simd::AlignLo(width - 1, DF);
size_t partialAlignedWidth = Simd::AlignLo(width, F);
__mmask16 tailMask = __mmask16(-1) >> (F + partialAlignedWidth - width);
__m512 _sums[coreX*coreY];
memset(_sums, 0, sizeof(_sums));
size_t row = 0;
for (; row < alignedHeight; row += 2)
{
size_t col = 0;
for (; col < fullAlignedWidth; col += DF)
Convolution<coreX, coreY>::template Sum2x2<align>(src + col, srcStride, dst + col, dstStride, _sums);
for (; col < partialAlignedWidth; col += F)
Convolution<coreX, coreY>::template Sum2x1<align, false>(src + col, srcStride, dst + col, dstStride, _sums);
if (col < width)
Convolution<coreX, coreY>::template Sum2x1<align, true>(src + col, srcStride, dst + col, dstStride, _sums, tailMask);
src += 2 * srcStride;
dst += 2 * dstStride;
}
for (; row < height; ++row)
{
size_t col = 0;
for (; col < fullAlignedWidth; col += DF)
Convolution<coreX, coreY>::template Sum1x2<align>(src + col, srcStride, dst + col, _sums);
for (; col < partialAlignedWidth; col += F)
Convolution<coreX, coreY>::template Sum1x1<align, false>(src + col, srcStride, dst + col, _sums);
if (col < width)
Convolution<coreX, coreY>::template Sum1x1<align, true>(src + col, srcStride, dst + col, _sums, tailMask);
src += srcStride;
dst += dstStride;
}
size_t i = 0, n = Simd::AlignLo(coreX*coreY, 4);
#ifndef _MSC_VER
for (; i < n; i += 4)
Add4ExtractedSums(_sums + i, sums + i);
#endif
for (; i < coreX*coreY; ++i)
sums[i] += ExtractSum(_sums[i]);
}
void NeuralAddConvolution2x2Sum(const float * src, size_t srcStride, const float * dst, size_t dstStride, size_t width, size_t height, float * sums)
{
if (Aligned(src) && Aligned(srcStride, F) && Aligned(dst) && Aligned(dstStride, F))
NeuralAddConvolutionSum2x2<true, 2, 2>(src, srcStride, dst, dstStride, width, height, sums);
else
NeuralAddConvolutionSum2x2<false, 2, 2>(src, srcStride, dst, dstStride, width, height, sums);
}
void NeuralAddConvolution3x3Sum(const float * src, size_t srcStride, const float * dst, size_t dstStride, size_t width, size_t height, float * sums)
{
if (Aligned(src) && Aligned(srcStride, F) && Aligned(dst) && Aligned(dstStride, F))
NeuralAddConvolutionSum2x1<true, 3, 3>(src, srcStride, dst, dstStride, width, height, sums);
else
NeuralAddConvolutionSum2x1<false, 3, 3>(src, srcStride, dst, dstStride, width, height, sums);
}
void NeuralAddConvolution4x4Sum(const float * src, size_t srcStride, const float * dst, size_t dstStride, size_t width, size_t height, float * sums)
{
if (Aligned(src) && Aligned(srcStride, F) && Aligned(dst) && Aligned(dstStride, F))
NeuralAddConvolutionSum2x1<true, 4, 4>(src, srcStride, dst, dstStride, width, height, sums);
else
NeuralAddConvolutionSum2x1<false, 4, 4>(src, srcStride, dst, dstStride, width, height, sums);
}
void NeuralAddConvolution5x5Sum(const float * src, size_t srcStride, const float * dst, size_t dstStride, size_t width, size_t height, float * sums)
{
if (Aligned(src) && Aligned(srcStride, F) && Aligned(dst) && Aligned(dstStride, F))
NeuralAddConvolutionSum2x1<true, 5, 5>(src, srcStride, dst, dstStride, width, height, sums);
else
NeuralAddConvolutionSum2x1<false, 5, 5>(src, srcStride, dst, dstStride, width, height, sums);
}
template <bool align> SIMD_INLINE __m512 Pooling1x1Max3x1Body(const float * src)
{
return _mm512_max_ps(_mm512_max_ps(Load<false>(src - 1), Load<align>(src)), Load<false>(src + 1));
}
template <bool align> SIMD_INLINE void Pooling1x1Max3x3Body(const float * src, size_t stride, float * dst)
{
__m512 src0 = Pooling1x1Max3x1Body<align>(src - stride);
__m512 src1 = Pooling1x1Max3x1Body<align>(src);
__m512 src2 = Pooling1x1Max3x1Body<align>(src + stride);
Store<align>(dst, _mm512_max_ps(_mm512_max_ps(src0, src1), src2));
}
template <bool align> SIMD_INLINE void Pooling1x1Max3x2Body(const float * src, size_t stride, float * dst)
{
__m512 src0 = Pooling1x1Max3x1Body<align>(src);
__m512 src1 = Pooling1x1Max3x1Body<align>(src + stride);
Store<align>(dst, _mm512_max_ps(src0, src1));
}
__m512i K32_PERMUTE_NOSE = SIMD_MM512_SETR_EPI32(0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14);
template <bool align> SIMD_INLINE __m512 Pooling1x1Max3x1Nose(const float * src)
{
__m512 src1 = Load<align>(src);
__m512 src0 = _mm512_permutexvar_ps(K32_PERMUTE_NOSE, src1);
__m512 src2 = Load<false>(src + 1);
return _mm512_max_ps(_mm512_max_ps(src0, src1), src2);
}
template <bool align> SIMD_INLINE void Pooling1x1Max3x3Nose(const float * src, size_t stride, float * dst)
{
__m512 src0 = Pooling1x1Max3x1Nose<align>(src - stride);
__m512 src1 = Pooling1x1Max3x1Nose<align>(src);
__m512 src2 = Pooling1x1Max3x1Nose<align>(src + stride);
Store<align>(dst, _mm512_max_ps(_mm512_max_ps(src0, src1), src2));
}
template <bool align> SIMD_INLINE void Pooling1x1Max3x2Nose(const float * src, size_t stride, float * dst)
{
__m512 src0 = Pooling1x1Max3x1Nose<align>(src);
__m512 src1 = Pooling1x1Max3x1Nose<align>(src + stride);
Store<align>(dst, _mm512_max_ps(src0, src1));
}
__m512i K32_PERMUTE_TAIL = SIMD_MM512_SETR_EPI32(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 15);
template <bool align> SIMD_INLINE __m512 Pooling1x1Max3x1Tail(const float * src)
{
__m512 src0 = Load<false>(src - 1);
__m512 src1 = Load<align>(src);
__m512 src2 = _mm512_permutexvar_ps(K32_PERMUTE_TAIL, src1);
return _mm512_max_ps(_mm512_max_ps(src0, src1), src2);
}
template <bool align> SIMD_INLINE void Pooling1x1Max3x3Tail(const float * src, size_t stride, float * dst)
{
__m512 src0 = Pooling1x1Max3x1Tail<align>(src - stride);
__m512 src1 = Pooling1x1Max3x1Tail<align>(src);
__m512 src2 = Pooling1x1Max3x1Tail<align>(src + stride);
Store<align>(dst, _mm512_max_ps(_mm512_max_ps(src0, src1), src2));
}
template <bool align> SIMD_INLINE void Pooling1x1Max3x2Tail(const float * src, size_t stride, float * dst)
{
__m512 src0 = Pooling1x1Max3x1Tail<align>(src);
__m512 src1 = Pooling1x1Max3x1Tail<align>(src + stride);
Store<align>(dst, _mm512_max_ps(src0, src1));
}
template <bool align> void NeuralPooling1x1Max3x3(const float * src, size_t srcStride, size_t width, size_t height, float * dst, size_t dstStride)
{
assert(width > F && height > 1);
size_t alignedWidth = AlignHi(width, F) - F;
height -= 1;
Pooling1x1Max3x2Nose<align>(src, srcStride, dst);
for (size_t col = F; col < alignedWidth; col += F)
Pooling1x1Max3x2Body<align>(src + col, srcStride, dst + col);
Pooling1x1Max3x2Tail<false>(src + width - F, srcStride, dst + width - F);
for (size_t row = 1; row < height; ++row)
{
src += srcStride;
dst += dstStride;
Pooling1x1Max3x3Nose<align>(src, srcStride, dst);
for (size_t col = F; col < alignedWidth; col += F)
Pooling1x1Max3x3Body<align>(src + col, srcStride, dst + col);
Pooling1x1Max3x3Tail<false>(src + width - F, srcStride, dst + width - F);
}
dst += dstStride;
Pooling1x1Max3x2Nose<align>(src, srcStride, dst);
for (size_t col = F; col < alignedWidth; col += F)
Pooling1x1Max3x2Body<align>(src + col, srcStride, dst + col);
Pooling1x1Max3x2Tail<false>(src + width - F, srcStride, dst + width - F);
}
void NeuralPooling1x1Max3x3(const float * src, size_t srcStride, size_t width, size_t height, float * dst, size_t dstStride)
{
if (Aligned(src) && Aligned(srcStride, F) && Aligned(dst) && Aligned(dstStride, F))
NeuralPooling1x1Max3x3<true>(src, srcStride, width, height, dst, dstStride);
else
NeuralPooling1x1Max3x3<false>(src, srcStride, width, height, dst, dstStride);
}
__m512i K32_PERMUTE_2_0 = SIMD_MM512_SETR_EPI32(0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30);
__m512i K32_PERMUTE_2_1 = SIMD_MM512_SETR_EPI32(1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31);
__m512i K32_PERMUTE_2_2 = SIMD_MM512_SETR_EPI32(2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 0);
template <bool align> SIMD_INLINE __m512 Pooling2x2Max2x2(const float * src, size_t stride)
{
__m512 lo = _mm512_max_ps(Load<align>(src + 0), Load<align>(src + stride + 0));
__m512 hi = _mm512_max_ps(Load<align>(src + F), Load<align>(src + stride + F));
__m512 _lo = _mm512_shuffle_f32x4(lo, hi, 0x88);
__m512 _hi = _mm512_shuffle_f32x4(lo, hi, 0xDD);
return _mm512_max_ps(_mm512_shuffle_ps(_lo, _hi, 0x88), _mm512_shuffle_ps(_lo, _hi, 0xDD));
}
template <bool align> SIMD_INLINE __m512 Pooling2x2Max2(const float * src)
{
__m512 lo = Load<align>(src + 0);
__m512 hi = Load<align>(src + F);
__m512 _lo = _mm512_shuffle_f32x4(lo, hi, 0x88);
__m512 _hi = _mm512_shuffle_f32x4(lo, hi, 0xDD);
return _mm512_max_ps(_mm512_shuffle_ps(_lo, _hi, 0x88), _mm512_shuffle_ps(_lo, _hi, 0xDD));
}
template <bool align> void NeuralPooling2x2Max2x2(const float * src, size_t srcStride, size_t width, size_t height, float * dst, size_t dstStride)
{
size_t heightEven = Simd::AlignLo(height, 2);
size_t widthEven = Simd::AlignLo(width, 2);
size_t alignedWidth = AlignLo(width, DF);
for (size_t row = 0; row < heightEven; row += 2)
{
for (size_t col = 0; col < alignedWidth; col += DF)
Store<align>(dst + (col >> 1), Pooling2x2Max2x2<align>(src + col, srcStride));
if (widthEven - alignedWidth)
{
size_t col = widthEven - DF;
Store<false>(dst + (col >> 1), Pooling2x2Max2x2<false>(src + col, srcStride));
}
if (width - widthEven)
dst[widthEven >> 1] = Simd::Max(src[widthEven], src[widthEven + srcStride]);
src += 2 * srcStride;
dst += dstStride;
}
if (height - heightEven)
{
for (size_t col = 0; col < alignedWidth; col += DF)
Store<align>(dst + (col >> 1), Pooling2x2Max2<align>(src + col));
if (widthEven - alignedWidth)
{
size_t col = widthEven - DF;
Store<false>(dst + (col >> 1), Pooling2x2Max2<false>(src + col));
}
if (width - widthEven)
dst[widthEven >> 1] = src[widthEven];
}
}
void NeuralPooling2x2Max2x2(const float * src, size_t srcStride, size_t width, size_t height, float * dst, size_t dstStride)
{
if (Aligned(src) && Aligned(srcStride, F) && Aligned(dst) && Aligned(dstStride, F))
NeuralPooling2x2Max2x2<true>(src, srcStride, width, height, dst, dstStride);
else
NeuralPooling2x2Max2x2<false>(src, srcStride, width, height, dst, dstStride);
}
template <bool align> SIMD_INLINE __m512 Pooling2x2Max1x3(const float * src, size_t stride)
{
return _mm512_max_ps(_mm512_max_ps(Load<align>(src), Load<align>(src + stride)), Load<align>(src + 2 * stride));
}
template <bool align> SIMD_INLINE __m512 Pooling2x2Max3x3(const float * src, size_t stride)
{
__m512 s0 = Pooling2x2Max1x3<align>(src + 0, stride);
__m512 sf = Pooling2x2Max1x3<align>(src + F, stride);
__m512 p0 = _mm512_permutex2var_ps(s0, K32_PERMUTE_2_0, sf);
__m512 p1 = _mm512_permutex2var_ps(s0, K32_PERMUTE_2_1, sf);
__m512 p2 = _mm512_permutex2var_ps(s0, K32_PERMUTE_2_2, sf);
return _mm512_max_ps(_mm512_max_ps(p0, p1), p2);
}
template <bool align> SIMD_INLINE __m512 Pooling2x2Max1x2(const float * src, size_t stride)
{
return _mm512_max_ps(Load<align>(src), Load<align>(src + stride));
}
template <bool align> SIMD_INLINE __m512 Pooling2x2Max3x2(const float * src, size_t stride)
{
__m512 s0 = Pooling2x2Max1x2<align>(src + 0, stride);
__m512 sf = Pooling2x2Max1x2<align>(src + F, stride);
__m512 p0 = _mm512_permutex2var_ps(s0, K32_PERMUTE_2_0, sf);
__m512 p1 = _mm512_permutex2var_ps(s0, K32_PERMUTE_2_1, sf);
__m512 p2 = _mm512_permutex2var_ps(s0, K32_PERMUTE_2_2, sf);
return _mm512_max_ps(_mm512_max_ps(p0, p1), p2);
}
template <bool align> void NeuralPooling2x2Max3x3(const float * src, size_t srcStride, size_t width, size_t height, float * dst, size_t dstStride)
{
height -= 1;
width -= 1;
size_t heightEven = Simd::AlignLo(height, 2);
size_t widthEven = Simd::AlignLo(width, 2);
size_t step = DF - 2;
size_t alignedWidth = width / step*step;
for (size_t row = 0; row < heightEven; row += 2)
{
for (size_t col = 0; col < alignedWidth; col += step)
Store<false, true>(dst + (col >> 1), Pooling2x2Max3x3<false>(src + col, srcStride), __mmask16(0x7FFF));
if (widthEven - alignedWidth)
{
size_t col = widthEven - step;
Store<false, true>(dst + (col >> 1), Pooling2x2Max3x3<false>(src + col, srcStride), __mmask16(0x7FFF));
}
if (width - widthEven)
Sse::Max2x3s(src + widthEven, srcStride, dst + (widthEven >> 1));
src += 2 * srcStride;
dst += dstStride;
}
if (height - heightEven)
{
for (size_t col = 0; col < alignedWidth; col += step)
Store<false, true>(dst + (col >> 1), Pooling2x2Max3x2<false>(src + col, srcStride), __mmask16(0x7FFF));
if (widthEven - alignedWidth)
{
size_t col = widthEven - step;
Store<false, true>(dst + (col >> 1), Pooling2x2Max3x2<false>(src + col, srcStride), __mmask16(0x7FFF));
}
if (width - widthEven)
Sse::Max2x2s(src + widthEven, srcStride, dst + (widthEven >> 1));
}
}
void NeuralPooling2x2Max3x3(const float * src, size_t srcStride, size_t width, size_t height, float * dst, size_t dstStride)
{
if (Aligned(src) && Aligned(srcStride, F) && Aligned(dst) && Aligned(dstStride, F))
NeuralPooling2x2Max3x3<true>(src, srcStride, width, height, dst, dstStride);
else
NeuralPooling2x2Max3x3<false>(src, srcStride, width, height, dst, dstStride);
}
namespace Ncf
{
namespace Ver0
{
void PrepareB(const float * src, size_t srcWidth, size_t srcHeight, size_t srcDepth, size_t kernelX, size_t kernelY,
size_t padX, size_t padY, size_t strideX, size_t strideY, size_t dilationX, size_t dilationY, size_t dstWidth, size_t dstHeight, float * dst)
{
const size_t K = kernelX*kernelY*srcDepth, N = dstHeight*dstWidth;
if (dilationX*dilationY*strideX*strideY != 1)
{
for (size_t dstRow = 0; dstRow < dstHeight; ++dstRow)
{
size_t srcRow0 = dstRow*strideY - padY;
for (size_t dstCol = 0; dstCol < dstWidth; ++dstCol)
{
size_t srcCol0 = dstCol*strideX - padX;
for (size_t channel = 0; channel < srcDepth; ++channel)
{
for (size_t kernelRow = 0; kernelRow < kernelY; ++kernelRow)
{
size_t srcRow = srcRow0 + kernelRow*dilationY;
if (srcRow < srcHeight)
{
const float * psrc = src + (channel*srcHeight + srcRow)*srcWidth;
for (size_t kernelCol = 0; kernelCol < kernelX; ++kernelCol)
{
size_t srcCol = srcCol0 + kernelCol*dilationX;
if (srcCol < srcWidth)
*(dst++) = psrc[srcCol];
else
*(dst++) = 0;
}
}
else
{
for (size_t kernelCol = 0; kernelCol < kernelX; ++kernelCol)
*(dst++) = 0;
}
}
}
}
}
}
else if (kernelX*kernelY != 1)
{
for (size_t dstRow = 0; dstRow < dstHeight; ++dstRow)
{
size_t srcRow0 = dstRow - padY;
for (size_t dstCol = 0; dstCol < dstWidth; ++dstCol)
{
size_t srcCol0 = dstCol - padX;
for (size_t channel = 0; channel < srcDepth; ++channel)
{
for (size_t kernelRow = 0; kernelRow < kernelY; ++kernelRow)
{
size_t srcRow = srcRow0 + kernelRow;
if (srcRow < srcHeight)
{
const float * psrc = src + (channel*srcHeight + srcRow)*srcWidth;
for (size_t kernelCol = 0; kernelCol < kernelX; ++kernelCol)
{
size_t srcCol = srcCol0 + kernelCol;
if (srcCol < srcWidth)
*(dst++) = psrc[srcCol];
else
*(dst++) = 0;
}
}
else
{
for (size_t kernelCol = 0; kernelCol < kernelX; ++kernelCol)
*(dst++) = 0;
}
}
}
}
}
}
else
{
for (size_t i = 0; i < N; ++i)
{
for (size_t k = 0; k < K; ++k)
*(dst++) = src[k*N + i];
}
}
}
template <bool align> static SIMD_INLINE void Kernel1x4x16(const __m512 & a, size_t K, const float * b, __m512 * sums)
{
sums[0] = _mm512_fmadd_ps(a, Load<align>(b + 0 * K), sums[0]);
sums[1] = _mm512_fmadd_ps(a, Load<align>(b + 1 * K), sums[1]);
sums[2] = _mm512_fmadd_ps(a, Load<align>(b + 2 * K), sums[2]);
sums[3] = _mm512_fmadd_ps(a, Load<align>(b + 3 * K), sums[3]);
}
template <bool align> static SIMD_INLINE void Kernel1x1x16(const __m512 & a, const float * b, __m512 & sum)
{
sum = _mm512_fmadd_ps(a, Load<align>(b), sum);
}
SIMD_INLINE void Add4ExtractedSums(const __m512 * src, float * dst)
{
__m512 sum02 = _mm512_add_ps(_mm512_unpacklo_ps(src[0], src[2]), _mm512_unpackhi_ps(src[0], src[2]));
__m512 sum13 = _mm512_add_ps(_mm512_unpacklo_ps(src[1], src[3]), _mm512_unpackhi_ps(src[1], src[3]));
__m512 sum512 = _mm512_add_ps(_mm512_unpacklo_ps(sum02, sum13), _mm512_unpackhi_ps(sum02, sum13));
__m128 sum128 = _mm_add_ps(_mm_add_ps(_mm512_extractf32x4_ps(sum512, 0), _mm512_extractf32x4_ps(sum512, 1)),
_mm_add_ps(_mm512_extractf32x4_ps(sum512, 2), _mm512_extractf32x4_ps(sum512, 3)));
_mm_storeu_ps(dst, _mm_add_ps(_mm_loadu_ps(dst), sum128));
}
template <bool align> static SIMD_INLINE void Kernel4x4x16(const __m512 * a, size_t K, const float * b, __m512 * sums)
{
__m512 b0 = Load<align>(b + 0 * K);
sums[0x0] = _mm512_fmadd_ps(a[0], b0, sums[0x0]);
sums[0x4] = _mm512_fmadd_ps(a[1], b0, sums[0x4]);
sums[0x8] = _mm512_fmadd_ps(a[2], b0, sums[0x8]);
sums[0xC] = _mm512_fmadd_ps(a[3], b0, sums[0xC]);
__m512 b1 = Load<align>(b + 1 * K);
sums[0x1] = _mm512_fmadd_ps(a[0], b1, sums[0x1]);
sums[0x5] = _mm512_fmadd_ps(a[1], b1, sums[0x5]);
sums[0x9] = _mm512_fmadd_ps(a[2], b1, sums[0x9]);
sums[0xD] = _mm512_fmadd_ps(a[3], b1, sums[0xD]);
__m512 b2 = Load<align>(b + 2 * K);
sums[0x2] = _mm512_fmadd_ps(a[0], b2, sums[0x2]);
sums[0x6] = _mm512_fmadd_ps(a[1], b2, sums[0x6]);
sums[0xA] = _mm512_fmadd_ps(a[2], b2, sums[0xA]);
sums[0xE] = _mm512_fmadd_ps(a[3], b2, sums[0xE]);
__m512 b3 = Load<align>(b + 3 * K);
sums[0x3] = _mm512_fmadd_ps(a[0], b3, sums[0x3]);
sums[0x7] = _mm512_fmadd_ps(a[1], b3, sums[0x7]);
sums[0xB] = _mm512_fmadd_ps(a[2], b3, sums[0xB]);
sums[0xF] = _mm512_fmadd_ps(a[3], b3, sums[0xF]);
}
template <bool align> static SIMD_INLINE void Kernel4x1x16(const __m512 * a, const float * b, __m512 * sums)
{
__m512 b0 = Load<align>(b);
sums[0] = _mm512_fmadd_ps(a[0], b0, sums[0]);
sums[1] = _mm512_fmadd_ps(a[1], b0, sums[1]);
sums[2] = _mm512_fmadd_ps(a[2], b0, sums[2]);
sums[3] = _mm512_fmadd_ps(a[3], b0, sums[3]);
}
template <bool align> static SIMD_INLINE void Kernel3x4x16(const __m512 * a, size_t K, const float * b, __m512 * sums)
{
__m512 _b;
_b = Load<align>(b + 0 * K);
sums[0x0] = _mm512_fmadd_ps(a[0], _b, sums[0x0]);
sums[0x4] = _mm512_fmadd_ps(a[1], _b, sums[0x4]);
sums[0x8] = _mm512_fmadd_ps(a[2], _b, sums[0x8]);
_b = Load<align>(b + 1 * K);
sums[0x1] = _mm512_fmadd_ps(a[0], _b, sums[0x1]);
sums[0x5] = _mm512_fmadd_ps(a[1], _b, sums[0x5]);
sums[0x9] = _mm512_fmadd_ps(a[2], _b, sums[0x9]);
_b = Load<align>(b + 2 * K);
sums[0x2] = _mm512_fmadd_ps(a[0], _b, sums[0x2]);
sums[0x6] = _mm512_fmadd_ps(a[1], _b, sums[0x6]);
sums[0xA] = _mm512_fmadd_ps(a[2], _b, sums[0xA]);
_b = Load<align>(b + 3 * K);
sums[0x3] = _mm512_fmadd_ps(a[0], _b, sums[0x3]);
sums[0x7] = _mm512_fmadd_ps(a[1], _b, sums[0x7]);
sums[0xB] = _mm512_fmadd_ps(a[2], _b, sums[0xB]);
}
template <bool align> static SIMD_INLINE void Kernel3x1x16(const __m512 * a, const float * b, __m512 * sums)
{
__m512 _b = Load<align>(b);
sums[0x0] = _mm512_fmadd_ps(a[0], _b, sums[0x0]);
sums[0x1] = _mm512_fmadd_ps(a[1], _b, sums[0x1]);
sums[0x2] = _mm512_fmadd_ps(a[2], _b, sums[0x2]);
}
template <bool align, bool mask> static SIMD_INLINE void Load4(const float * p, __m512 * a, size_t step, __mmask16 tail = -1)
{
a[0] = Load<align, mask>(p + 0 * step, tail);
a[1] = Load<align, mask>(p + 1 * step, tail);
a[2] = Load<align, mask>(p + 2 * step, tail);
a[3] = Load<align, mask>(p + 3 * step, tail);
}
template <bool align, bool mask> static SIMD_INLINE void Load3(const float * p, __m512 * a, size_t step, __mmask16 tail = -1)
{
a[0] = Load<align, mask>(p + 0 * step, tail);
a[1] = Load<align, mask>(p + 1 * step, tail);
a[2] = Load<align, mask>(p + 2 * step, tail);
}
template <bool align> void Execute(size_t M, size_t N, size_t K, const float * a, const float * b, float * c)
{
size_t M3 = M / 3 * 3;
size_t M4 = Simd::AlignLo(M, 4);
size_t N4 = Simd::AlignLo(N, 4);
size_t K16 = Simd::AlignLo(K, 16);
__mmask16 tailMask = TailMask16(K - K16);
size_t i = 0;
#if SIMD_ZMM_COUNT == 32
for (; i < M4; i += 4)
{
const float * pa = a + i*K;
float * pc = c + i*N;
size_t j = 0;
register __m512 _a[4];
for (; j < N4; j += 4)
{
const float * pb = b + j*K;
register __m512 sums[16] = {
_mm512_setzero_ps(), _mm512_setzero_ps(), _mm512_setzero_ps(), _mm512_setzero_ps(),
_mm512_setzero_ps(), _mm512_setzero_ps(), _mm512_setzero_ps(), _mm512_setzero_ps(),
_mm512_setzero_ps(), _mm512_setzero_ps(), _mm512_setzero_ps(), _mm512_setzero_ps(),
_mm512_setzero_ps(), _mm512_setzero_ps(), _mm512_setzero_ps(), _mm512_setzero_ps() };
size_t k = 0;
for (; k < K16; k += 16)
{
Load4<false, false>(pa + k, _a, K);
Kernel4x4x16<align>(_a, K, pb + k, sums);
}
if (k < K)
{
Load4<false, true>(pa + k, _a, K, tailMask);
Kernel4x4x16<false>(_a, K, pb + k, sums);
}
Add4ExtractedSums(sums + 0x0, pc + 0 * N + j);
Add4ExtractedSums(sums + 0x4, pc + 1 * N + j);
Add4ExtractedSums(sums + 0x8, pc + 2 * N + j);
Add4ExtractedSums(sums + 0xC, pc + 3 * N + j);
}
for (; j < N; ++j)
{
const float * pb = b + j*K;
register __m512 sums[4] = { _mm512_setzero_ps(), _mm512_setzero_ps(), _mm512_setzero_ps(), _mm512_setzero_ps() };
size_t k = 0;
for (; k < K16; k += 16)
{
Load4<false, false>(pa + k, _a, K);
Kernel4x1x16<align>(_a, pb + k, sums);
}
if (k < K)
{
Load4<false, true>(pa + k, _a, K, tailMask);
Kernel4x1x16<false>(_a, pb + k, sums);
}
pc[0 * N + j] += ExtractSum(sums[0]);
pc[1 * N + j] += ExtractSum(sums[1]);
pc[2 * N + j] += ExtractSum(sums[2]);
pc[3 * N + j] += ExtractSum(sums[3]);
}
}
#endif
for (; i < M3; i += 3)
{
const float * pa = a + i*K;
float * pc = c + i*N;
size_t j = 0;
register __m512 _a[3];
for (; j < N4; j += 4)
{
const float * pb = b + j*K;
register __m512 sums[12] = {
_mm512_setzero_ps(), _mm512_setzero_ps(), _mm512_setzero_ps(), _mm512_setzero_ps(),
_mm512_setzero_ps(), _mm512_setzero_ps(), _mm512_setzero_ps(), _mm512_setzero_ps(),
_mm512_setzero_ps(), _mm512_setzero_ps(), _mm512_setzero_ps(), _mm512_setzero_ps() };
size_t k = 0;
for (; k < K16; k += 16)
{
Load3<false, false>(pa + k, _a, K);
Kernel3x4x16<align>(_a, K, pb + k, sums);
}
if (k < K)
{
Load3<false, true>(pa + k, _a, K, tailMask);
Kernel3x4x16<false>(_a, K, pb + k, sums);
}
Add4ExtractedSums(sums + 0x0, pc + 0 * N + j);
Add4ExtractedSums(sums + 0x4, pc + 1 * N + j);
Add4ExtractedSums(sums + 0x8, pc + 2 * N + j);
}
for (; j < N; ++j)
{
const float * pb = b + j*K;
register __m512 sums[3] = { _mm512_setzero_ps(), _mm512_setzero_ps(), _mm512_setzero_ps() };
size_t k = 0;
for (; k < K16; k += 16)
{
Load3<false, false>(pa + k, _a, K);
Kernel3x1x16<align>(_a, pb + k, sums);
}
if (k < K)
{
Load3<false, true>(pa + k, _a, K, tailMask);
Kernel3x1x16<false>(_a, pb + k, sums);
}
pc[0 * N + j] += ExtractSum(sums[0]);
pc[1 * N + j] += ExtractSum(sums[1]);
pc[2 * N + j] += ExtractSum(sums[2]);
}
}
for (; i < M; ++i)
{
const float * pa = a + i*K;
float * pc = c + i*N;
size_t j = 0;
for (; j < N4; j += 4)
{
const float * pb = b + j*K;
register __m512 sums[4] = { _mm512_setzero_ps(), _mm512_setzero_ps(), _mm512_setzero_ps(), _mm512_setzero_ps() };
size_t k = 0;
for (; k < K16; k += 16)
{
register __m512 _a = Load<false>(pa + k);
Kernel1x4x16<align>(_a, K, pb + k, sums);
}
if (k < K)
{
register __m512 _a = Load<false, true>(pa + k, tailMask);
Kernel1x4x16<false>(_a, K, pb + k, sums);
}
Add4ExtractedSums(sums + 0, pc + j);
}
for (; j < N; ++j)
{
const float * pb = b + j*K;
register __m512 sum = _mm512_setzero_ps();
size_t k = 0;
for (; k < K16; k += 16)
{
register __m512 _a = Load<false>(pa + k);
Kernel1x1x16<align>(_a, pb + k, sum);
}
if (k < K)
{
register __m512 _a = Load<false, true>(pa + k, tailMask);
Kernel1x1x16<false>(_a, pb + k, sum);
}
pc[j] += ExtractSum(sum);
}
}
}
void Execute(size_t M, size_t N, size_t K, const float * a, const float * b, float * c)
{
if (Aligned(K, F))
Execute<true>(M, N, K, a, b, c);
else
Execute<false>(M, N, K, a, b, c);
}
}
namespace Ver1
{
void PrepareA(const float * src, size_t M, size_t K, size_t cell, float * dst)
{
size_t K4 = AlignLo(K, 4), K8 = AlignLo(K, 8);
for (size_t i = 0; i < M; i += cell)
{
size_t n = Simd::Min(cell, M - i), k = 0;
if (cell == 4 && n == 4)
{
for (; k < K8; k += 8)
{
const float * ps = src + k;
__m256 s0 = Avx::Load<false>(ps + 0 * K);
__m256 s1 = Avx::Load<false>(ps + 1 * K);
__m256 s2 = Avx::Load<false>(ps + 2 * K);
__m256 s3 = Avx::Load<false>(ps + 3 * K);
__m256 s00 = _mm256_unpacklo_ps(s0, s2);
__m256 s01 = _mm256_unpacklo_ps(s1, s3);
__m256 s10 = _mm256_unpackhi_ps(s0, s2);
__m256 s11 = _mm256_unpackhi_ps(s1, s3);
__m256 d0 = _mm256_unpacklo_ps(s00, s01);
__m256 d1 = _mm256_unpackhi_ps(s00, s01);
__m256 d2 = _mm256_unpacklo_ps(s10, s11);
__m256 d3 = _mm256_unpackhi_ps(s10, s11);
Avx::Store<false>(dst + 0, _mm256_permute2f128_ps(d0, d1, 0x20));
Avx::Store<false>(dst + 8, _mm256_permute2f128_ps(d2, d3, 0x20));
Avx::Store<false>(dst + 16, _mm256_permute2f128_ps(d0, d1, 0x31));
Avx::Store<false>(dst + 24, _mm256_permute2f128_ps(d2, d3, 0x31));
dst += 32;
}
for (; k < K4; k += 4)
{
const float * ps = src + k;
__m128 s0 = Sse::Load<false>(ps + 0 * K);
__m128 s1 = Sse::Load<false>(ps + 1 * K);
__m128 s2 = Sse::Load<false>(ps + 2 * K);
__m128 s3 = Sse::Load<false>(ps + 3 * K);
__m128 s00 = _mm_unpacklo_ps(s0, s2);
__m128 s01 = _mm_unpacklo_ps(s1, s3);
__m128 s10 = _mm_unpackhi_ps(s0, s2);
__m128 s11 = _mm_unpackhi_ps(s1, s3);
Sse::Store<false>(dst + 0, _mm_unpacklo_ps(s00, s01));
Sse::Store<false>(dst + 4, _mm_unpackhi_ps(s00, s01));
Sse::Store<false>(dst + 8, _mm_unpacklo_ps(s10, s11));
Sse::Store<false>(dst + 12, _mm_unpackhi_ps(s10, s11));
dst += 16;
}
}
for (; k < K; ++k)
{
for (size_t c = 0; c < n; ++c)
*(dst++) = src[c*K + k];
}
src += cell*K;
}
}
void PrepareB(const float * src, size_t srcWidth, size_t srcHeight, size_t srcDepth, size_t kernelX, size_t kernelY, size_t padX, size_t padY,
size_t strideX, size_t strideY, size_t dilationX, size_t dilationY, size_t dstWidth, size_t dstHeight, size_t cell, float * tmp, float * dst)
{
const size_t K = kernelX*kernelY*srcDepth, N = dstHeight*dstWidth;
if (kernelX*kernelY != 1)
{
float * dst = tmp;
size_t channelSize = srcHeight * srcWidth;
if (dilationX*dilationY*strideX*strideY != 1)
{
for (size_t channel = 0, k = 0; channel < srcDepth; ++channel, src += channelSize)
{
for (size_t kernelRow = 0; kernelRow < kernelY; ++kernelRow)
{
for (size_t kernelCol = 0; kernelCol < kernelX; ++kernelCol, ++k)
{
size_t srcRow = kernelRow*dilationY - padY;
for (size_t dstRow = 0; dstRow < dstHeight; ++dstRow)
{
if (srcRow < srcHeight)
{
size_t srcCol = kernelCol*dilationX - padX;
for (size_t dstCol = 0; dstCol < dstWidth; ++dstCol)
{
if (srcCol < srcWidth)
*(dst++) = src[srcRow*srcWidth + srcCol];
else
*(dst++) = 0;
srcCol += strideX;
}
}
else
{
for (size_t dstCol = 0; dstCol < dstWidth; ++dstCol)
*(dst++) = 0;
}
srcRow += strideY;
}
}
}
}
}
else
{
const size_t bodySize = dstWidth - padX * 2;
for (size_t channel = 0, k = 0; channel < srcDepth; ++channel, src += channelSize)
{
for (size_t kernelRow = 0; kernelRow < kernelY; ++kernelRow)
{
for (size_t kernelCol = 0; kernelCol < kernelX; ++kernelCol, ++k)
{
size_t srcRow = kernelRow - padY;
for (size_t dstRow = 0; dstRow < dstHeight; ++dstRow, ++srcRow)
{
if (srcRow < srcHeight)
{
size_t srcCol = kernelCol - padX, dstCol = 0;
const float * psrc = src + srcRow*srcWidth;
for (; dstCol < padX; ++dstCol, ++srcCol)
{
if (srcCol < srcWidth)
*(dst++) = psrc[srcCol];
else
*(dst++) = 0;
}
memcpy(dst, psrc + srcCol, bodySize * 4);
dst += bodySize;
dstCol += bodySize;
srcCol += bodySize;
for (; dstCol < dstWidth; ++dstCol, ++srcCol)
{
if (srcCol < srcWidth)
*(dst++) = psrc[srcCol];
else
*(dst++) = 0;
}
}
else
{
memset(dst, 0, dstWidth * 4);
dst += dstWidth;
}
}
}
}
}
}
src = tmp;
}
if (cell == 32)
{
for (size_t j = 0; j < N; j += cell)
{
size_t n = Simd::Min(cell, N - j);
if (n == cell)
{
for (size_t k = 0; k < K; ++k)
{
const float * psrc = src + k*N;
Store<false>(dst + 0, Load<false>(psrc + 0));
Store<false>(dst + F, Load<false>(psrc + F));
dst += 32;
}
}
else
{
for (size_t k = 0; k < K; ++k)
{
const float * psrc = src + k*N;
size_t c = 0;
for (; c < n; ++c)
*(dst++) = *(psrc++);
for (; c < cell; ++c)
*(dst++) = 0;
}
}
src += cell;
}
}
else if (cell == 16)
{
for (size_t j = 0; j < N; j += cell)
{
size_t n = Simd::Min(cell, N - j);
if (n == cell)
{
for (size_t k = 0; k < K; ++k)
{
const float * psrc = src + k*N;
Store<false>(dst, Load<false>(psrc));
dst += 16;
}
}
else
{
for (size_t k = 0; k < K; ++k)
{
const float * psrc = src + k*N;
size_t c = 0;
for (; c < n; ++c)
*(dst++) = *(psrc++);
for (; c < cell; ++c)
*(dst++) = 0;
}
}
src += cell;
}
}
else
{
for (size_t j = 0; j < N; j += cell)
{
size_t n = Simd::Min(cell, N - j);
for (size_t k = 0; k < K; ++k)
{
const float * psrc = src + k*N;
size_t c = 0;
for (; c < n; ++c)
*(dst++) = *(psrc++);
for (; c < cell; ++c)
*(dst++) = 0;
}
src += cell;
}
}
}
SIMD_INLINE void AddSum(__m512 sum, float * dst)
{
_mm512_storeu_ps(dst, _mm512_add_ps(_mm512_loadu_ps(dst), sum));
}
template<bool mask> SIMD_INLINE void AddSum(__m512 sum, float * dst, __mmask16 tail = -1)
{
Store<false, mask>(dst, _mm512_add_ps((Load<false, mask>(dst, tail)), sum), tail);
}
template<bool mask> SIMD_INLINE void AddSums16(const __m512 * sums, size_t size, float * dst, size_t stride, __mmask16 tail = -1)
{
for (size_t i = 0; i < size; ++i, dst += stride)
AddSum<mask>(sums[i], dst, tail);
}
template <bool align, bool mask> SIMD_INLINE void KernelMx16(size_t N, size_t K, const float * a, const float * b, float * c, size_t m, __mmask16 tail = -1)
{
__m512 sums[4] = { _mm512_setzero_ps(), _mm512_setzero_ps(), _mm512_setzero_ps(), _mm512_setzero_ps() };
for (size_t k = 0; k < K; ++k)
{
__m512 b0 = Load<align>(b);
for (size_t s = 0; s < m; ++s)
{
__m512 a0 = _mm512_set1_ps(a[s]);
sums[s] = _mm512_fmadd_ps(b0, a0, sums[s]);
}
b += 16;
a += m;
}
AddSums16<mask>(sums, m, c, N, tail);
}
template <bool align, bool mask> SIMD_INLINE void Kernel4x16(size_t N, size_t K, const float * a, const float * b, float * c, __mmask16 tail = -1)
{
__m512 sums[4] = { _mm512_setzero_ps(), _mm512_setzero_ps(), _mm512_setzero_ps(), _mm512_setzero_ps() };
for (size_t k = 0; k < K; ++k)
{
__m512 b0 = Load<align>(b);
__m512 a0 = _mm512_set1_ps(a[0]);
sums[0] = _mm512_fmadd_ps(b0, a0, sums[0]);
__m512 a1 = _mm512_set1_ps(a[1]);
sums[1] = _mm512_fmadd_ps(b0, a1, sums[1]);
__m512 a2 = _mm512_set1_ps(a[2]);
sums[2] = _mm512_fmadd_ps(b0, a2, sums[2]);
__m512 a3 = _mm512_set1_ps(a[3]);
sums[3] = _mm512_fmadd_ps(b0, a3, sums[3]);
b += 16;
a += 4;
}
AddSums16<mask>(sums, 4, c, N, tail);
}
template <bool align> void Execute4x16(size_t M, size_t N, size_t K, const float * a, const float * b, float * c)
{
size_t M4 = Simd::AlignLo(M, 4);
size_t N16 = Simd::AlignLo(N, 16);
__mmask16 tailMask = TailMask16(N - N16);
size_t i = 0;
for (; i < M4; i += 4)
{
size_t j = 0;
for (; j < N16; j += 16)
Kernel4x16<align, false>(N, K, a + i*K, b + j*K, c + i*N + j);
if (j < N)
Kernel4x16<align, true>(N, K, a + i*K, b + j*K, c + i*N + j, tailMask);
}
if (i < M)
{
size_t j = 0;
for (; j < N16; j += 16)
KernelMx16<align, false>(N, K, a + i*K, b + j*K, c + i*N + j, M - M4);
if (j < N)
KernelMx16<align, true>(N, K, a + i*K, b + j*K, c + i*N + j, M - M4, tailMask);
}
}
template<bool mask> SIMD_INLINE void AddSums32(const __m512 * sums, size_t size, float * dst, size_t stride, const __mmask16 * tails)
{
for (size_t i = 0; i < size; ++i, dst += stride)
{
AddSum<mask>(sums[i + 0], dst + 00, tails[0]);
AddSum<mask>(sums[i + 4], dst + 16, tails[1]);
}
}
template <bool align, bool mask> SIMD_INLINE void KernelMx32(size_t N, size_t K, const float * a, const float * b, float * c, size_t m, const __mmask16 * tails)
{
__m512 sums[8] = { _mm512_setzero_ps(), _mm512_setzero_ps(), _mm512_setzero_ps(), _mm512_setzero_ps(),
_mm512_setzero_ps(), _mm512_setzero_ps(), _mm512_setzero_ps(), _mm512_setzero_ps() };
for (size_t k = 0; k < K; ++k)
{
__m512 b0 = Load<align>(b + 00);
__m512 b1 = Load<align>(b + 16);
for (size_t s = 0; s < m; ++s)
{
__m512 a0 = _mm512_set1_ps(a[s]);
sums[s + 0] = _mm512_fmadd_ps(b0, a0, sums[s + 0]);
sums[s + 4] = _mm512_fmadd_ps(b1, a0, sums[s + 4]);
}
b += 32;
a += m;
}
AddSums32<mask>(sums, m, c, N, tails);
}
void Kernel4x32(size_t N, size_t K, const float * a, const float * b, float * c)
{
register __m512 _a, b0, b1, c00, c01, c10, c11, c20, c21, c30, c31;
c00 = _mm512_setzero_ps();
c01 = _mm512_setzero_ps();
c10 = _mm512_setzero_ps();
c11 = _mm512_setzero_ps();
c20 = _mm512_setzero_ps();
c21 = _mm512_setzero_ps();
c30 = _mm512_setzero_ps();
c31 = _mm512_setzero_ps();
for (size_t k = 0; k < K; ++k)
{
b0 = _mm512_loadu_ps(b + 0 * F);
b1 = _mm512_loadu_ps(b + 1 * F);
_a = _mm512_set1_ps(a[0]);
c00 = _mm512_fmadd_ps(b0, _a, c00);
c01 = _mm512_fmadd_ps(b1, _a, c01);
_a = _mm512_set1_ps(a[1]);
c10 = _mm512_fmadd_ps(b0, _a, c10);
c11 = _mm512_fmadd_ps(b1, _a, c11);
_a = _mm512_set1_ps(a[2]);
c20 = _mm512_fmadd_ps(b0, _a, c20);
c21 = _mm512_fmadd_ps(b1, _a, c21);
_a = _mm512_set1_ps(a[3]);
c30 = _mm512_fmadd_ps(b0, _a, c30);
c31 = _mm512_fmadd_ps(b1, _a, c31);
b += 32;
a += 4;
}
AddSum(c00, c + 0 * F);
AddSum(c01, c + 1 * F);
c += N;
AddSum(c10, c + 0 * F);
AddSum(c11, c + 1 * F);
c += N;
AddSum(c20, c + 0 * F);
AddSum(c21, c + 1 * F);
c += N;
AddSum(c30, c + 0 * F);
AddSum(c31, c + 1 * F);
}
template <bool align> void Execute4x32(size_t M, size_t N, size_t K, const float * a, const float * b, float * c)
{
size_t M4 = Simd::AlignLo(M, 4);
size_t N32 = Simd::AlignLo(N, 32);
__mmask16 tailMasks[2];
for (size_t i = 0; i < 2; ++i)
tailMasks[i] = TailMask16(N - N32 - F*i);
size_t i = 0;
for (; i < M4; i += 4)
{
size_t j = 0;
for (; j < N32; j += 32)
Kernel4x32(N, K, a + i * K, b + j * K, c + i * N + j);
if (j < N)
KernelMx32<align, true>(N, K, a + i*K, b + j*K, c + i*N + j, 4, tailMasks);
}
if (i < M)
{
size_t j = 0;
for (; j < N32; j += 32)
KernelMx32<align, false>(N, K, a + i*K, b + j*K, c + i*N + j, M - M4, tailMasks);
if (j < N)
KernelMx32<align, true>(N, K, a + i*K, b + j*K, c + i*N + j, M - M4, tailMasks);
}
}
void Execute(size_t M, size_t N, size_t K, const float * a, const float * b, float * c, size_t cellA, size_t cellB)
{
if (cellA == 4)
{
if (cellB == 16)
Execute4x16<false>(M, N, K, a, b, c);
if (cellB == 32)
Execute4x32<false>(M, N, K, a, b, c);
}
}
}
namespace Ver2
{
void PrepareB(const float * src, size_t srcWidth, size_t srcHeight, size_t srcDepth, size_t padX, size_t padY, float * dst, size_t dstWidth, size_t dstHeight)
{
for (size_t channel = 0; channel < srcDepth; ++channel)
{
const float * s = src;
float * d = dst;
memset(d, 0, padY*dstWidth * 4);
d += padY*dstWidth;
for (size_t row = padY; row < dstHeight - padY; ++row)
{
memset(d, 0, padX * 4);
memcpy(d + padX, s, srcWidth * 4);
memset(d + padX + srcWidth, 0, padX * 4);
d += dstWidth;
s += srcWidth;
}
memset(d, 0, padY*dstWidth * 4);
src += srcWidth*srcHeight;
dst += dstWidth*dstHeight;
}
}
template <bool align, size_t kernelX, size_t kernelY> void AddConvolution8x8(const float * src, size_t srcWidth, size_t srcHeight, size_t srcDepth,
const float * weight, float * dst, size_t dstDepth)
{
__m256 _weight[kernelX*kernelY];
for (size_t dstChannel = 0; dstChannel < dstDepth; ++dstChannel)
{
__m256 _dst[8];
float * pdst = dst;
for (size_t row = 0; row < 8; ++row, pdst += 8)
_dst[row] = Avx::Load<align>(pdst);
if (kernelY < 4)
{
for (size_t srcChannel = 0; srcChannel < srcDepth; ++srcChannel)
{
const float * psrc = src + srcWidth*srcHeight*srcChannel;
Avx2::LoadWeightsForward<kernelX*kernelY>(weight, _weight);
for (size_t row = 0; row < 8; ++row)
{
_dst[row] = _mm256_add_ps(_dst[row], Avx2::Convolution<kernelX, kernelY>::template Forward<align>(psrc, srcWidth, _weight));
psrc += srcWidth;
}
weight += kernelX*kernelY;
}
}
else
{
for (size_t srcChannel = 0; srcChannel < srcDepth; ++srcChannel)
{
const float * psrc = src + srcWidth*srcHeight*srcChannel;
for (size_t dy = 0; dy < kernelY; dy++)
{
const float * ps = psrc + dy*srcWidth;
Avx2::LoadWeightsForward<kernelX>(weight, _weight);
for (size_t row = 0; row < 8; ++row)
{
_dst[row] = _mm256_add_ps(_dst[row], Avx2::Convolution<kernelX, kernelY>::template RowConvolution<align>(ps, _weight));
ps += srcWidth;
}
weight += kernelX;
}
}
}
for (size_t row = 0; row < 8; ++row, dst += 8)
Avx::Store<align>(dst, _dst[row]);
}
}
template <bool align, size_t kernelX, size_t kernelY> void AddConvolution16x16(const float * src, size_t srcWidth, size_t srcHeight, size_t srcDepth,
const float * weight, float * dst, size_t dstDepth)
{
__m512 _weight[kernelX*kernelY];
for (size_t dstChannel = 0; dstChannel < dstDepth; ++dstChannel)
{
__m512 _dst[16];
float * pdst = dst;
for (size_t row = 0; row < 16; ++row, pdst += 16)
_dst[row] = Load<align>(pdst);
if (kernelY < 4)
{
for (size_t srcChannel = 0; srcChannel < srcDepth; ++srcChannel)
{
const float * psrc = src + srcWidth*srcHeight*srcChannel;
LoadWeightsForward<kernelX*kernelY>(weight, _weight);
for (size_t row = 0; row < 16; ++row)
{
_dst[row] = _mm512_add_ps(_dst[row], (Convolution<kernelX, kernelY>::template Forward<align, false>(psrc, srcWidth, _weight)));
psrc += srcWidth;
}
weight += kernelX*kernelY;
}
}
else
{
for (size_t srcChannel = 0; srcChannel < srcDepth; ++srcChannel)
{
const float * psrc = src + srcWidth*srcHeight*srcChannel;
for (size_t dy = 0; dy < kernelY; dy++)
{
const float * ps = psrc + dy*srcWidth;
LoadWeightsForward<kernelX>(weight, _weight);
for (size_t row = 0; row < 16; ++row)
{
_dst[row] = _mm512_add_ps(_dst[row], (Convolution<kernelX, kernelY>::template RowConvolution<align, false>(ps, _weight)));
ps += srcWidth;
}
weight += kernelX;
}
}
}
for (size_t row = 0; row < 16; ++row, dst += 16)
Store<align>(dst, _dst[row]);
}
}
template <bool align, size_t kernelX, size_t kernelY> void AddConvolution(const float * src, size_t srcWidth, size_t srcHeight, size_t srcDepth,
const float * weight, float * dst, size_t dstWidth, size_t dstHeight, size_t dstDepth)
{
if (dstWidth == 8 && dstHeight == 8)
{
AddConvolution8x8<align, kernelX, kernelY>(src, srcWidth, srcHeight, srcDepth, weight, dst, dstDepth);
return;
}
if (dstWidth == 16 && dstHeight == 16)
{
AddConvolution16x16<align, kernelX, kernelY>(src, srcWidth, srcHeight, srcDepth, weight, dst, dstDepth);
return;
}
size_t alignedWidth = AlignLo(dstWidth, F);
__mmask16 tailMask = TailMask16(dstWidth - alignedWidth);
__m512 _weight[kernelX*kernelY];
for (size_t dstChannel = 0; dstChannel < dstDepth; ++dstChannel)
{
for (size_t srcChannel = 0; srcChannel < srcDepth; ++srcChannel)
{
const float * psrc = src + srcWidth*srcHeight*srcChannel;
const float * pweight = weight + (dstChannel*srcDepth + srcChannel)*kernelX*kernelY;
float * pdst = dst + dstWidth*dstHeight*dstChannel;
LoadWeightsForward<kernelX*kernelY>(pweight, _weight);
for (size_t row = 0; row < dstHeight; ++row)
{
size_t col = 0;
for (; col < alignedWidth; col += F)
{
__m512 _dst = Load<align>(pdst + col);
_dst = _mm512_add_ps(_dst, (Convolution<kernelX, kernelY>::template Forward<align, false>(psrc + col, srcWidth, _weight)));
Store<align>(pdst + col, _dst);
}
if (col < dstWidth)
{
__m512 _dst = Load<align, true>(pdst + col, tailMask);
_dst = _mm512_add_ps(_dst, (Convolution<kernelX, kernelY>::template Forward<align, true>(psrc + col, srcWidth, _weight, tailMask)));
Store<align, true>(pdst + col, _dst, tailMask);
}
psrc += srcWidth;
pdst += dstWidth;
}
}
}
}
void Execute(const float * src, size_t srcWidth, size_t srcHeight, size_t srcDepth,
const float * weight, size_t kernelX, size_t kernelY, float * dst, size_t dstWidth, size_t dstHeight, size_t dstDepth)
{
assert(kernelX == kernelY);
if (kernelX == 2)
AddConvolution<false, 2, 2>(src, srcWidth, srcHeight, srcDepth, weight, dst, dstWidth, dstHeight, dstDepth);
else if (kernelX == 3)
AddConvolution<false, 3, 3>(src, srcWidth, srcHeight, srcDepth, weight, dst, dstWidth, dstHeight, dstDepth);
else if (kernelX == 4)
AddConvolution<false, 4, 4>(src, srcWidth, srcHeight, srcDepth, weight, dst, dstWidth, dstHeight, dstDepth);
else if (kernelX == 5)
AddConvolution<false, 5, 5>(src, srcWidth, srcHeight, srcDepth, weight, dst, dstWidth, dstHeight, dstDepth);
else
assert(0);
}
bool Preferable(size_t srcDepth, size_t kernelX, size_t kernelY, size_t strideX, size_t strideY, size_t dilationX, size_t dilationY, size_t dstWidth, size_t dstHeight, size_t dstDepth)
{
if (kernelX == kernelY && kernelX >= 2 && kernelX <= 5 && strideX*strideY*dilationX*dilationY == 1)
{
if (dstWidth*dstHeight*kernelX*kernelY >= 8 * 8 * 3 * 3)
return true;
}
return false;
}
}
struct Opt
{
enum Alg
{
None,
Ver0,
Ver1,
Ver2,
} alg;
size_t sizeA;
size_t sizeB;
size_t sizeT;
size_t cellA;
size_t cellB;
size_t M, N, K;
size_t strideB;
size_t paddedW;
size_t paddedH;
Opt(size_t srcWidth, size_t srcHeight, size_t srcDepth, size_t kernelX, size_t kernelY, size_t padX, size_t padY, size_t strideX, size_t strideY, size_t dilationX, size_t dilationY, size_t dstWidth, size_t dstHeight, size_t dstDepth)
{
alg = None;
sizeA = 0;
sizeB = 0;
sizeT = 0;
cellA = 1;
cellB = 1;
M = dstDepth;
N = dstHeight*dstWidth;
K = kernelX*kernelY*srcDepth;
if (dstWidth*dstHeight / kernelX <= 1000)
alg = Ver0;
else
alg = Ver1;
if (Ver2::Preferable(srcDepth, kernelX, kernelY, strideX, strideY, dilationX, dilationY, dstWidth, dstHeight, dstDepth))
alg = Ver2;
switch (alg)
{
case Ver0:
sizeB = N*K;
break;
case Ver1:
cellA = 4;
cellB = 32;
sizeA = M*K;
strideB = Simd::AlignHi(N, cellB);
sizeB = strideB*K;
if (kernelX*kernelY > 1)
sizeT = sizeB;
break;
case Ver2:
if (padX > 0 || padY > 0)
{
paddedW = Simd::AlignHi(srcWidth + 2 * padX, F);
paddedH = srcHeight + 2 * padY;
sizeB = paddedW*paddedH*srcDepth;
}
else
{
paddedW = srcWidth;
paddedH = srcHeight;
}
break;
default:
assert(0);
break;
}
}
};
struct Data
{
float * a;
float * b;
float * t;
Data(size_t sizeA, size_t sizeB, size_t sizeT, void * externalData, size_t * externalSize)
: a(0)
, b(0)
, _data(0)
{
sizeA = AlignHi(sizeA, F);
sizeB = AlignHi(sizeB, F);
sizeT = AlignHi(sizeT, F);
size_t size = (sizeA + sizeB + sizeT) * sizeof(float);
if (size == 0)
return;
if (externalData != AlignHi(externalData, SIMD_ALIGN))
size += SIMD_ALIGN;
float * data = NULL;
if (externalData == NULL || externalSize == NULL || *externalSize < size)
{
_data = Simd::Allocate(size);
if (externalSize)
*externalSize = size;
data = (float*)_data;
}
else
data = (float*)AlignHi(externalData, SIMD_ALIGN);
if (sizeA)
a = data;
if (sizeB)
b = data + sizeA;
if (sizeT)
t = data + sizeA + sizeB;
}
~Data()
{
if (_data)
Simd::Free(_data);
}
private:
void * _data;
};
}
void NeuralConvolutionForward(const float * src, size_t srcWidth, size_t srcHeight, size_t srcDepth,
const float * weight, size_t kernelX, size_t kernelY, size_t padX, size_t padY, size_t strideX, size_t strideY, size_t dilationX, size_t dilationY,
void * buffer, size_t * size, float * dst, size_t dstWidth, size_t dstHeight, size_t dstDepth, int add)
{
using namespace Ncf;
assert(dstWidth == (srcWidth + 2 * padX - (dilationX * (kernelX - 1) + 1)) / strideX + 1);
assert(dstHeight == (srcHeight + 2 * padY - (dilationY * (kernelY - 1) + 1)) / strideY + 1);
if (!add)
memset(dst, 0, dstWidth*dstHeight*dstDepth * sizeof(float));
Opt opt(srcWidth, srcHeight, srcDepth, kernelX, kernelY, padX, padY, strideX, strideY, dilationX, dilationY, dstWidth, dstHeight, dstDepth);
Data data(opt.sizeA, opt.sizeB, opt.sizeT, buffer, size);
if (opt.sizeA)
{
switch (opt.alg)
{
case Opt::Ver1: Ver1::PrepareA(weight, opt.M, opt.K, opt.cellA, data.a);
default:
break;
}
}
else
data.a = (float*)weight;
if (opt.sizeB)
{
switch (opt.alg)
{
case Opt::Ver0: Ver0::PrepareB(src, srcWidth, srcHeight, srcDepth, kernelX, kernelY, padX, padY, strideX, strideY, dilationX, dilationY, dstWidth, dstHeight, data.b); break;
case Opt::Ver1: Ver1::PrepareB(src, srcWidth, srcHeight, srcDepth, kernelX, kernelY, padX, padY, strideX, strideY, dilationX, dilationY, dstWidth, dstHeight, opt.cellB, data.t, data.b); break;
case Opt::Ver2: Ver2::PrepareB(src, srcWidth, srcHeight, srcDepth, padX, padY, data.b, opt.paddedW, opt.paddedH); break;
default: break;
}
}
else
data.b = (float*)src;
switch (opt.alg)
{
case Opt::Ver0: Ver0::Execute(opt.M, opt.N, opt.K, data.a, data.b, dst); break;
case Opt::Ver1: Ver1::Execute(opt.M, opt.N, opt.K, data.a, data.b, dst, opt.cellA, opt.cellB); break;
case Opt::Ver2: Ver2::Execute(data.b, opt.paddedW, opt.paddedH, srcDepth, weight, kernelX, kernelY, dst, dstWidth, dstHeight, dstDepth); break;
default: break;
}
}
}
#endif// SIMD_AVX512F_ENABLE
}
| [
"[email protected]"
] | |
08de55d65eb702ced050fbe4d27941a5315971a3 | e44c564fc38cbb13ee12ea58f21420691339f700 | /exponencial.cpp | dc3baaceab5c80ce6ac43132fed8d4f21facf415 | [] | no_license | dabarono/16-agosto | eb82dbffbdb725e3af54466c2b49d650c2b514eb | 720f86e1adfaba7fd675debf57c7072642c4771a | refs/heads/master | 2021-06-21T07:34:36.896379 | 2017-08-16T16:04:46 | 2017-08-16T16:04:46 | 100,507,764 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 706 | cpp | #include<iostream>
#include<cmath>
int fa(int k){
if (k<=0){
return 1;
}
else {
double g=1;
double j=1;
for(j;j<=k;j=j+1){
g=g*j;
}
return g;
}
}
double ea(double x, int n){
double h=0;
int k;
for(k=0;k<n;k=k+1){
h=h+pow(-x,k)/fa(k);
}
return h;
}
double es(double x, int n){
double f=1;
int i;
double a_0=1;
for(i=0;i<n;i=i+1){
a_0=a_0*(-x)/(i+1);
f=f+a_0;
}
return f;
}
int main(void){
std::cout.precision(16); std::cout.setf(std::ios::scientific);
double x=10;
int l=1;
for(l;l<=200;l=l+1){
std::cout<<l<<" "<<ea(x,l)<<" "<<es(x,l)<<" "<<exp(-x)<<" "<<fabs(exp(-x)-es(x,l))/exp(-x) <<std::endl;
}
return 0;
}
| [
"[email protected]"
] | |
73313302008edb2b1e8e29b69c5258b57023c584 | c8bbccd8ec055e72ef9589a8814cd5b3dc474c05 | /shocktube/openfoam3/0.0016/phi | 500a6c9afb10a2a87ab93349e3fb5f1f56dd2d8c | [] | no_license | samtx/adv-fluids | f221253be7290a0b04a50b6fbaa9f30efc181e28 | 8baf7a4f12ed3d5bc24418fa685a9dd2c72aee61 | refs/heads/master | 2021-01-21T06:38:16.914084 | 2017-05-06T20:49:27 | 2017-05-06T20:49:27 | 82,866,684 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,650 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 4.1 |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class surfaceScalarField;
location "0.0016";
object phi;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [1 0 -1 0 0 0 0];
internalField nonuniform List<scalar>
999
(
-3.31184e-11
-3.76374e-11
-3.68914e-11
-3.25713e-11
-3.16049e-11
-3.78364e-11
-3.50724e-11
-3.16334e-11
-2.467e-11
-2.43716e-11
-2.61338e-11
-3.17115e-11
-3.20384e-11
-3.41416e-11
-2.8372e-11
-2.30571e-11
-2.42864e-11
-3.26779e-11
-3.1541e-11
-2.81517e-11
-1.9952e-11
-1.57527e-11
-8.05045e-12
-7.31148e-12
-1.39337e-11
-1.83107e-11
-1.7188e-11
-1.97034e-11
-1.60298e-11
-2.13731e-11
-1.94973e-11
-2.40945e-11
-2.08686e-11
-2.58709e-11
-1.96039e-11
-1.38982e-11
-1.13403e-11
-1.44667e-11
-1.44524e-11
-9.60654e-12
-4.37694e-12
-7.10543e-13
-3.03402e-12
-5.40723e-12
-1.60583e-12
5.32907e-13
1.25056e-12
-1.75504e-12
3.87956e-12
3.62377e-12
1.03455e-11
9.86233e-12
3.99325e-12
9.37916e-13
-1.71241e-12
1.28608e-12
1.42109e-13
1.68399e-12
2.84928e-12
5.74119e-12
5.68434e-14
-3.8014e-12
-1.20437e-11
-1.40545e-11
-1.99734e-11
-1.76499e-11
-1.37845e-11
-7.13385e-12
-5.54223e-12
-8.1144e-12
-9.12337e-12
-1.80691e-11
-1.19798e-11
-3.49587e-12
-4.4551e-12
1.79767e-12
7.08411e-12
1.11129e-11
1.17524e-11
1.50777e-11
6.76437e-12
8.2494e-12
1.53761e-11
1.67404e-11
2.00302e-11
2.35616e-11
2.46985e-11
1.81757e-11
2.19273e-11
1.66338e-11
2.46487e-11
2.22755e-11
1.64846e-11
2.42224e-11
2.65103e-11
2.56009e-11
2.45493e-11
1.75575e-11
1.16955e-11
1.45164e-11
1.93339e-11
2.12381e-11
2.00231e-11
1.60014e-11
1.14824e-11
9.64206e-12
9.72022e-12
1.69535e-11
2.22684e-11
2.80735e-11
2.43077e-11
2.14229e-11
1.41611e-11
1.12621e-11
1.43601e-11
8.96705e-12
3.43903e-12
9.19442e-12
1.32303e-11
1.67617e-11
1.47935e-11
8.98126e-12
6.79279e-12
1.20792e-13
-5.22959e-12
-8.05045e-12
-2.94875e-12
-2.8848e-12
4.9738e-14
3.12639e-13
-1.84741e-13
3.23297e-12
1.02887e-11
1.59446e-11
2.47908e-11
2.74269e-11
2.56648e-11
2.82299e-11
2.45279e-11
1.79412e-11
1.28111e-11
7.26175e-12
6.84963e-12
7.71649e-12
6.672e-12
2.49401e-12
1.7053e-13
4.9738e-12
-2.25242e-12
-8.36309e-12
-6.61515e-12
-1.01466e-11
-1.81473e-11
-1.51914e-11
-1.49996e-11
-2.05205e-11
-2.3249e-11
-1.50351e-11
-9.2939e-12
-9.96891e-12
-6.04672e-12
-1.10347e-11
-1.43672e-11
-9.85523e-12
-1.65556e-12
-1.39266e-12
7.88702e-13
2.17426e-12
4.07141e-12
2.16005e-12
-2.55795e-12
-8.98837e-12
-9.2939e-12
-6.35936e-12
-3.41061e-12
-9.74154e-12
-2.224e-12
1.5703e-12
-3.91509e-12
-9.57812e-12
-9.78417e-12
-1.98952e-12
6.20304e-12
1.085e-11
1.15321e-11
1.10987e-11
9.08784e-12
1.37916e-11
1.70317e-11
2.08757e-11
1.65628e-11
1.29745e-11
1.10916e-11
8.70415e-12
7.58149e-12
1.86873e-12
2.01084e-12
1.02673e-11
7.93676e-12
8.32756e-12
6.12488e-12
6.807e-12
1.20934e-11
6.70042e-12
5.3717e-12
3.70193e-12
8.44125e-12
9.43601e-12
1.38556e-11
1.41327e-11
9.9547e-12
1.00613e-11
1.9412e-11
1.79128e-11
1.99307e-11
1.97673e-11
1.59162e-11
1.19016e-11
7.61702e-12
8.26361e-12
9.40048e-12
7.83018e-12
9.18732e-12
1.1795e-11
1.20011e-11
1.11555e-11
9.17311e-12
1.03242e-11
6.53699e-13
-2.27374e-13
-1.28608e-12
7.43228e-12
6.19593e-12
-8.45546e-13
3.78719e-12
1.93268e-12
-1.28608e-12
2.12452e-12
-1.46372e-12
-3.28981e-12
2.77112e-13
-2.66454e-12
-7.90834e-12
-1.02247e-11
-8.02913e-12
-6.07514e-12
-3.68061e-12
2.40874e-12
1.11555e-12
-1.81899e-12
1.51346e-12
1.52056e-12
-4.24905e-12
-8.66862e-12
-9.19442e-12
-9.22284e-12
-1.20579e-11
-7.53175e-12
-7.70228e-12
-9.46443e-12
-3.95772e-12
-8.36309e-12
-5.06617e-12
1.13687e-12
3.28271e-12
3.2685e-12
3.29692e-12
3.78009e-12
7.65965e-12
9.59233e-12
2.70717e-12
-2.06057e-12
-4.70379e-12
2.89191e-12
1.1056e-11
4.76774e-12
9.72022e-12
8.45546e-12
4.25615e-12
8.95994e-12
4.37694e-12
2.42295e-12
3.63087e-12
5.42855e-12
1.37987e-11
1.66054e-11
9.96181e-12
1.27045e-11
9.90497e-12
8.71836e-12
1.28395e-11
1.11058e-11
1.14539e-11
1.30171e-11
1.5504e-11
1.53975e-11
9.91918e-12
4.81037e-12
5.34328e-12
1.04734e-11
8.65441e-12
1.77636e-13
1.38556e-12
2.86349e-12
2.95586e-12
1.50635e-12
-2.56506e-12
-4.68248e-12
1.85452e-12
2.03926e-12
4.52616e-12
-3.20455e-12
-4.76064e-12
-1.27187e-12
7.24754e-13
1.59162e-12
2.13163e-14
0
0
1.44951e-12
1.62714e-12
-1.62714e-12
-1.44951e-12
-1.21503e-12
-1.37845e-12
1.39977e-12
1.20082e-12
-9.73444e-13
1.45661e-12
4.1851e-12
2.31637e-12
4.61853e-12
3.29692e-12
-2.25242e-12
-3.5385e-12
1.23634e-12
-3.93641e-12
-4.25615e-12
-4.24905e-12
2.13163e-13
1.62714e-12
0
1.79057e-12
2.41585e-12
1.00187e-12
-4.54747e-12
6.53699e-13
3.60956e-12
-1.1724e-12
-3.38218e-12
-2.71427e-12
-2.224e-12
-1.8332e-12
6.03961e-12
1.41256e-11
1.0175e-11
4.03588e-12
-3.62377e-12
-4.81037e-12
3.0056e-12
9.9476e-13
-3.16192e-12
-4.12825e-12
-3.87246e-12
2.76401e-12
8.87468e-12
7.65965e-12
1.75504e-12
1.91847e-12
4.0572e-12
3.21876e-12
-9.59233e-13
-5.96856e-12
-8.73968e-13
4.46931e-12
1.21503e-12
-6.37357e-12
-1.2804e-11
-7.96518e-12
-4.73221e-12
-3.16902e-12
-2.01794e-12
2.28084e-12
3.85114e-12
4.1922e-13
1.39266e-12
1.21503e-12
3.24718e-12
1.26477e-12
2.62901e-12
3.82272e-12
4.46221e-12
7.60281e-12
1.54188e-12
1.33582e-12
1.78346e-12
3.19744e-13
1.01039e-11
3.68843e-11
1.25674e-10
3.79337e-10
1.11862e-09
3.2242e-09
9.10924e-09
2.53078e-08
6.92044e-08
1.86337e-07
4.93981e-07
1.28904e-06
3.31e-06
8.36055e-06
2.07643e-05
5.06867e-05
0.000121553
0.000286238
0.000661533
0.00149967
0.00333275
0.0072558
0.0154645
0.0322415
0.0656978
0.130717
0.253683
0.479638
0.882294
1.57663
2.73218
4.58243
7.42134
11.5716
17.2907
24.5281
33.0246
42.6173
53.1343
64.3756
76.1433
88.2598
100.577
112.976
125.366
137.677
149.856
161.863
173.669
185.25
196.587
207.668
218.482
229.02
239.276
249.245
258.924
268.31
277.401
286.194
294.69
302.888
310.786
318.385
325.683
332.682
339.379
345.774
351.867
357.658
363.137
368.33
373.171
377.781
381.962
385.959
389.568
392.781
395.925
398.429
400.85
402.976
404.524
406.061
407.284
408.035
408.717
409.286
409.532
409.591
409.725
409.763
409.73
409.657
409.622
409.599
409.578
409.501
409.401
409.365
409.337
409.28
409.244
409.224
409.207
409.169
409.139
409.122
409.099
409.055
409.022
408.991
408.955
408.915
408.884
408.846
408.775
408.7
408.647
408.608
408.576
408.51
408.312
408.092
407.968
407.942
407.98
408.388
408.773
408.887
408.249
401.384
374.86
343.333
319.222
301.457
289.095
281.552
277.53
275.246
273.695
273.009
272.979
273.259
273.251
272.925
272.893
273.31
273.468
273.105
272.85
273.027
273.426
273.399
272.862
272.804
273.248
273.441
272.937
272.707
272.815
273.242
273.14
272.567
272.515
272.791
273.075
272.391
272.178
272.22
272.526
272.568
271.52
271.405
271.497
271.992
271.252
270.034
270.012
270.387
271.076
268.047
267.208
267.193
267.426
267.743
258.81
242.82
215.781
82.5868
25.6388
6.45661
1.54341
0.364225
0.0856943
0.0201451
0.00473378
0.00111203
0.00026118
6.1333e-05
1.44007e-05
3.38068e-06
7.93505e-07
1.86216e-07
4.36922e-08
1.02494e-08
2.40382e-09
5.64036e-10
1.329e-10
3.1358e-11
6.942e-12
1.51701e-12
5.57776e-13
-1.41398e-12
-1.82965e-12
-1.44773e-12
-8.11795e-13
4.74287e-13
2.26308e-12
1.45128e-12
1.6005e-12
2.75335e-13
-2.14939e-13
-6.34159e-13
-1.0516e-12
-5.66658e-13
-5.43565e-13
7.69163e-13
1.33937e-12
2.84217e-13
1.55254e-12
-1.82965e-13
-2.24532e-12
-4.70735e-13
-5.82645e-13
-4.31655e-13
-1.5099e-13
-6.34159e-13
-2.91323e-13
-2.02505e-13
4.28102e-13
3.9968e-13
-1.77636e-14
1.58451e-12
-3.55271e-14
-1.15818e-12
-9.82325e-13
-2.28084e-12
-1.9007e-13
1.65201e-12
1.25056e-12
1.23279e-12
5.68434e-13
-1.33227e-13
-5.56e-13
-5.45342e-13
-1.72484e-12
-1.84919e-12
-4.81393e-13
-2.59348e-13
-2.27551e-12
-2.04992e-12
-1.26121e-12
-4.29878e-13
-3.39284e-13
-3.81917e-13
1.13687e-13
-1.26299e-12
-5.56e-13
8.40217e-13
1.71418e-12
9.5568e-13
-1.08358e-13
6.21725e-13
8.49099e-13
2.49223e-12
2.04992e-12
3.83693e-13
-1.91847e-13
3.55271e-15
-2.8777e-13
-3.89022e-13
2.30926e-13
-1.13687e-12
-1.87228e-12
-1.01075e-12
-1.10134e-13
-1.24523e-12
-1.38733e-12
-7.69163e-13
-3.58824e-13
-9.32587e-13
4.90274e-13
7.63833e-13
5.68434e-13
1.98952e-13
-3.09086e-13
-6.21725e-13
1.05338e-12
1.76748e-12
2.12275e-12
2.4194e-12
1.06226e-12
1.06226e-12
7.99361e-13
7.19425e-13
6.75016e-13
1.89893e-12
1.56142e-12
4.44089e-14
1.09601e-12
1.78524e-12
1.46372e-12
1.28253e-12
7.81597e-13
2.06057e-13
-6.64357e-13
-8.0469e-13
-6.55476e-13
-4.1922e-13
-2.94875e-13
-4.9738e-13
-7.01661e-13
-2.43361e-13
-4.52971e-13
1.12266e-12
-1.77636e-14
-2.2915e-13
3.44613e-13
-6.76792e-13
-1.44773e-12
-2.63967e-12
-2.49933e-12
-9.84102e-13
-2.24887e-12
-9.29035e-13
9.05942e-14
1.25056e-12
2.73026e-12
6.30607e-13
-7.92255e-13
4.583e-13
5.04485e-13
-1.23812e-12
-1.35003e-13
-9.96536e-13
-6.16396e-13
8.75744e-13
2.90612e-12
2.33591e-12
2.96119e-12
2.07834e-12
4.17444e-13
-8.45546e-13
-1.97176e-13
-1.10134e-13
-1.44951e-12
-1.16707e-12
7.63833e-13
-3.35731e-13
-3.28626e-13
5.15143e-13
-2.71783e-13
-1.8705e-12
-3.32889e-12
-2.71427e-12
-1.09779e-12
-8.36664e-13
-2.66454e-14
-9.34364e-13
-2.36078e-12
-3.33955e-12
-2.46558e-12
-1.72129e-12
-1.23279e-12
-5.32907e-15
-9.30811e-13
-2.54019e-13
3.49942e-13
7.63833e-14
6.83897e-13
1.15641e-12
1.31095e-12
7.10543e-14
-2.61124e-13
-1.4424e-12
-8.27782e-13
-5.18696e-13
-5.70211e-13
-8.59757e-13
1.86517e-13
-1.7053e-13
-1.36957e-12
-1.03384e-12
1.23457e-12
6.07514e-13
6.03961e-13
1.56675e-12
1.79945e-12
2.22933e-12
1.79412e-12
1.37668e-12
8.52651e-14
-5.68434e-13
3.8014e-13
1.35536e-12
1.95044e-12
1.12976e-12
-5.79092e-13
6.89226e-13
1.08002e-12
1.28608e-12
2.359e-12
6.80345e-13
1.32161e-12
1.4726e-12
4.90274e-13
2.11564e-12
2.61657e-12
1.25944e-12
5.73763e-13
1.5099e-13
-1.0818e-12
-2.79599e-12
-2.57394e-12
-1.12266e-12
-2.3519e-12
-1.7959e-12
-2.15117e-12
-1.55786e-12
-7.54952e-13
-1.14397e-12
-1.06049e-12
-1.07825e-12
-1.82254e-12
-2.224e-12
-3.55094e-12
-4.05365e-12
-2.54019e-12
-2.15294e-12
-1.9007e-13
1.26121e-12
5.73763e-13
1.92379e-12
1.83853e-12
1.9611e-12
2.1938e-12
1.51701e-12
-3.92575e-13
-4.90274e-13
-2.46914e-13
-5.93303e-13
1.66978e-13
-2.13163e-14
1.35358e-12
2.56684e-12
9.48575e-13
2.16716e-12
7.51399e-13
-8.73968e-13
-1.89182e-12
-1.03384e-12
-1.72662e-12
-8.29559e-13
3.33955e-13
-3.51719e-13
-1.11022e-12
-4.33431e-13
-1.81188e-12
-3.7268e-12
-3.55449e-12
-4.21529e-12
-4.75531e-12
-4.64695e-12
-2.10676e-12
-1.82609e-12
-3.63976e-12
-3.6966e-12
-4.11404e-12
-4.02878e-12
-4.09983e-12
-3.61666e-12
-2.87237e-12
-2.32347e-12
-7.83373e-13
-6.30607e-13
-1.16707e-12
-1.06404e-12
8.01137e-13
2.46558e-12
1.58984e-12
-2.16716e-13
-6.53699e-13
3.87246e-13
8.68638e-13
-3.30402e-13
1.68576e-12
1.65024e-12
1.62537e-12
3.96128e-12
5.11768e-12
4.59188e-12
3.02691e-12
1.61471e-12
1.25233e-12
2.13873e-12
1.70708e-12
2.11209e-12
1.73905e-12
1.83853e-12
3.56515e-12
4.06253e-12
4.16378e-12
4.26503e-12
3.94884e-12
3.31113e-12
3.63087e-12
2.79066e-12
1.39444e-12
1.82609e-12
-3.73035e-14
-7.40741e-13
-8.13571e-13
-1.72662e-12
-9.32587e-13
1.77636e-14
-1.19016e-13
-5.68434e-13
1.41576e-12
2.10676e-12
2.96652e-12
2.75335e-12
2.8475e-12
1.22569e-12
1.36957e-12
1.71241e-12
1.92379e-12
5.79092e-13
1.22569e-13
4.28102e-13
7.83373e-13
-1.13687e-13
-1.55254e-12
-1.68754e-13
7.70939e-13
-1.24878e-12
-6.05738e-13
-9.14824e-13
-5.00933e-13
2.78888e-13
0
0
0
0
1.77636e-15
-1.19016e-13
9.59233e-13
1.63602e-12
3.94351e-13
5.15143e-13
-2.04281e-13
1.27898e-13
-3.01981e-13
3.19744e-14
4.26326e-14
-7.28306e-13
-3.33955e-13
5.73763e-13
8.43769e-13
5.20473e-13
-1.55786e-12
-9.92983e-13
-7.74492e-13
-6.83897e-13
1.54543e-13
2.4869e-14
5.15143e-14
3.51719e-13
1.0818e-12
2.02505e-12
3.22053e-12
3.07843e-12
4.63807e-12
4.33076e-12
4.14602e-12
4.64873e-12
5.10347e-12
7.28306e-12
8.75922e-12
9.18021e-12
7.88347e-12
8.64198e-12
7.8515e-12
6.80167e-12
7.84617e-12
8.59579e-12
9.03988e-12
1.01092e-11
1.11964e-11
1.17613e-11
1.0365e-11
1.1859e-11
)
;
boundaryField
{
sides
{
type calculated;
value nonuniform List<scalar> 2(1.16489e-11 3.29047e-11);
}
empty
{
type empty;
value nonuniform 0();
}
}
// ************************************************************************* //
| [
"[email protected]"
] | ||
0cfd98233140feeb84e7669c0862b71e23775c37 | 5b41e312db8aeb5532ba59498c93e2ec1dccd4ff | /Tools/Simulator/Simulator/CLogWriterWrapper.h | 2859c867d1e72b539f1fb27d0410e6f1543415b0 | [] | no_license | frankilfrancis/KPO_HMI_vs17 | 10d96c6cb4aebffb83254e6ca38fe6d1033eba79 | de49aa55eccd8a7abc165f6057088a28426a1ceb | refs/heads/master | 2020-04-15T16:40:14.366351 | 2019-11-14T15:33:25 | 2019-11-14T15:33:25 | 164,845,188 | 0 | 1 | null | null | null | null | ISO-8859-3 | C++ | false | false | 1,865 | h | // Copyright 2009 SMS - Siemag AG
#ifndef _CLogWriterWrapper_H_
#define _CLogWriterWrapper_H_
//--------------------------------------------------------
#include "CStdConverter.h"
#include "CLogWriter.h"
//--------------------------------------------------------
#include <string>
//--------------------------------------------------------
//using namespace simulator;
using namespace System;
using namespace Diagnostics;
//--------------------------------------------------------
//-------------------------------------------
// Name: CLogWriterWrapper.h
// Descr: Wrapper fuer die Klasse CLogWriter.h
// Date:
// Autor: Emeljanov Alexander
//--------------------------------------------
public ref class CLogWriterWrapper
{
public:
enum class MessTyp {Info,Warning,Error};
static CLogWriterWrapper^ getLogWriterWrapper();
void setPath(String^ path);
void WriteMessage(MessTyp typ,String^ message,String^ file,String^ function,int line,StackTrace^ stTrace,int stDepth);
void setSettings(int size,bool info,bool warning,bool error);
void removeNeedlessLogFiles();
void ReadSettingsFromIniFile();
~CLogWriterWrapper();
protected:
CLogWriterWrapper();
private:
static CLogWriterWrapper^ LogWriterWrapper=nullptr;
CLogWriter* writer;
};
//// Vergleichsklasse Kriterium 'Wohnort'
//private __gc class DateComparer : IComparer
//{
// public int Compare(Object* x, object* y)
// {
// // prüfen auf null-Übergabe
// if(x == null && y == null) return 0;
// if(x == null) return 1;
// if(y == null) return 1;
// // Typüberprüfung
//
//
//
//
// if(x.GetType() != y.GetType())
// throw new ArgumentException("Ungültiger Vergleich");
// // Vergleich
// return ((Person)x).Wohnort.CompareTo(((Person)y).Wohnort);
// }
//};
#endif
| [
"[email protected]"
] | |
2141e0615319baac902130dcb1c2047e9f2bd70a | b1fed0cf607483a8c51df377d6278d186be95007 | /tags/Rel_1_3_4/adfs/listener.cpp | 890ac27ddec9defb66fad7b2d6bba624f242bd2e | [] | no_license | svn2github/cpp-sp | eab0e52ce521ae696ba02d815d7da02481c4e24d | 9c0bfdae80f3c60860b36f15698f241f1e3d933f | refs/heads/master | 2020-06-06T03:24:19.620256 | 2015-01-20T00:27:14 | 2015-01-20T00:27:14 | 19,316,247 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,853 | cpp | /*
* Copyright 2001-2005 Internet2
*
* 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.
*/
/*
* listener.cpp -- implementation of IListener functional methods that includes ADFS support
*
* Scott Cantor
* 10/10/05
*
*/
#include "internal.h"
#include <xercesc/framework/MemBufInputSource.hpp>
using namespace std;
using namespace saml;
using namespace shibboleth;
using namespace shibtarget;
using namespace adfs;
using namespace adfs::logging;
namespace {
class ADFSListener : public virtual IListener
{
public:
ADFSListener(const DOMElement* e) : log(&Category::getInstance(ADFS_LOGCAT".Listener")) {}
~ADFSListener() {}
bool create(ShibSocket& s) const {return true;}
bool bind(ShibSocket& s, bool force=false) const {return true;}
bool connect(ShibSocket& s) const {return true;}
bool close(ShibSocket& s) const {return true;}
bool accept(ShibSocket& listener, ShibSocket& s) const {return true;}
void sessionNew(
const IApplication* application,
int supported_profiles,
const char* recipient,
const char* packet,
const char* ip,
std::string& target,
std::string& cookie,
std::string& provider_id
) const;
void sessionGet(
const IApplication* application,
const char* cookie,
const char* ip,
ISessionCacheEntry** pentry
) const;
void sessionEnd(
const IApplication* application,
const char* cookie
) const;
void ping(int& i) const;
private:
Category* log;
};
}
IPlugIn* ADFSListenerFactory(const DOMElement* e)
{
return new ADFSListener(e);
}
void ADFSListener::sessionNew(
const IApplication* app,
int supported_profiles,
const char* recipient,
const char* packet,
const char* ip,
string& target,
string& cookie,
string& provider_id
) const
{
#ifdef _DEBUG
saml::NDC ndc("sessionNew");
#endif
log->debug("creating session for %s", ip);
log->debug("recipient: %s", recipient);
log->debug("application: %s", app->getId());
auto_ptr_XMLCh wrecipient(recipient);
// Access the application config. It's already locked behind us.
ShibTargetConfig& stc=ShibTargetConfig::getConfig();
IConfig* conf=stc.getINI();
bool checkIPAddress=true;
const IPropertySet* props=app->getPropertySet("Sessions");
if (props) {
pair<bool,bool> pcheck=props->getBool("checkAddress");
if (pcheck.first)
checkIPAddress = pcheck.second;
}
pair<bool,bool> checkReplay=pair<bool,bool>(false,false);
props=app->getPropertySet("Sessions");
if (props)
checkReplay=props->getBool("checkReplay");
const IRoleDescriptor* role=NULL;
Metadata m(app->getMetadataProviders());
bool bADFS = false;
SAMLBrowserProfile::BrowserProfileResponse bpr;
// For now, just branch off to handle ADFS inline, I'll wrap all this up later.
if (supported_profiles & ADFS_SSO) {
log->debug("executing ADFS profile...");
CgiParse parser(packet,strlen(packet));
const char* param=parser.get_value("wa");
if (param && !strcmp(param,"wsignin1.0")) {
bADFS=true;
param=parser.get_value("wresult");
if (!param)
throw FatalProfileException("ADFS profile required wresult parameter not found");
log->debug("decoded ADFS Token response:\n%s",param);
// wresult should carry an wst:RequestSecurityTokenResponse message so we parse it manually
DOMDocument* rdoc=NULL;
try {
saml::XML::Parser p;
static const XMLCh systemId[]={chLatin_W, chLatin_S, chDash, chLatin_T, chLatin_r, chLatin_u, chLatin_s, chLatin_t, chNull};
MemBufInputSource membufsrc(reinterpret_cast<const XMLByte*>(param),strlen(param),systemId,false);
Wrapper4InputSource dsrc(&membufsrc,false);
rdoc=p.parse(dsrc);
// Process the wrapper and extract the assertion.
if (saml::XML::isElementNamed(rdoc->getDocumentElement(),adfs::XML::WSTRUST_NS,ADFS_L(RequestSecurityTokenResponse))) {
DOMElement* e=
saml::XML::getFirstChildElement(rdoc->getDocumentElement(),adfs::XML::WSTRUST_NS,ADFS_L(RequestedSecurityToken));
if (e) {
e=saml::XML::getFirstChildElement(e,saml::XML::SAML_NS,L(Assertion));
if (e) {
// Wrap the assertion DOM in a dummy samlp:Response for subsequent processing.
// We have to manually create the Response DOM first in order to avoid
// corrupting the namespace declarations in the Assertion.
static const XMLCh One[]={chDigit_1, chNull};
static const XMLCh dummyID[] = {chLatin_A, chLatin_D, chLatin_F, chLatin_S, chNull};
static const XMLCh samlp_Success[]=
{ chLatin_s, chLatin_a, chLatin_m, chLatin_l, chLatin_p, chColon,
chLatin_S, chLatin_u, chLatin_c, chLatin_c, chLatin_e, chLatin_s, chLatin_s, chNull };
DOMElement* rdom=rdoc->createElementNS(saml::XML::SAMLP_NS,L(Response));
rdom->setAttributeNS(saml::XML::XMLNS_NS,L_QNAME(xmlns,samlp),saml::XML::SAMLP_NS);
rdom->setAttributeNS(saml::XML::XMLNS_NS,L(xmlns),saml::XML::SAMLP_NS);
rdom->setAttributeNS(NULL,L(MajorVersion),One);
rdom->setAttributeNS(NULL,L(MinorVersion),One);
rdom->setAttributeNS(NULL,L(ResponseID),dummyID);
SAMLDateTime issued(time(NULL));
issued.parseDateTime();
rdom->setAttributeNS(NULL,L(IssueInstant),issued.getRawData());
DOMElement* status=rdoc->createElementNS(saml::XML::SAMLP_NS,L(Status));
rdom->appendChild(status);
DOMElement* code=rdoc->createElementNS(saml::XML::SAMLP_NS,L(StatusCode));
code->setAttributeNS(NULL,L(Value),samlp_Success);
status->appendChild(code);
rdom->appendChild(e); // append the assertion
auto_ptr<SAMLResponse> response(new SAMLResponse(rdom));
response->setDocument(rdoc); // give the Document to the response object
// root the response in the document so the signature will verify
rdoc->replaceChild(response->toDOM(rdoc,false),rdoc->getDocumentElement());
rdoc=NULL;
// Try and map to metadata.
SAMLAssertion* assertion=response->getAssertions().next();
const IEntityDescriptor* provider=m.lookup(assertion->getIssuer());
if (provider)
role=provider->getIDPSSODescriptor(adfs::XML::WSFED_NS);
if (!role) {
MetadataException ex("unable to locate role-specific metadata for identity provider.");
annotateException(&ex,provider); // throws it
}
try {
// Check over the assertion.
SAMLAuthenticationStatement* authnStatement=checkAssertionProfile(assertion);
if (!checkReplay.first || checkReplay.second) {
auto_ptr_char id(assertion->getId());
string key(id.get());
key="P_" + key;
if (!conf->getReplayCache()->check(key.c_str(),assertion->getNotOnOrAfter()->getEpoch()))
throw ReplayedAssertionException(string("Rejecting replayed assertion ID (") + id.get() + ")");
}
// Check signature.
log->debug("passing signed ADFS assertion to trust layer");
Trust t(app->getTrustProviders());
if (!t.validate(*assertion,role)) {
log->error("unable to verify signed ADFS assertion");
throw TrustException("unable to verify signed authentication assertion");
}
log->info("verified digital signature over ADFS assertion");
// Now dummy up the SAML profile response wrapper.
param=parser.get_value("wctx");
if (param)
bpr.TARGET=param;
bpr.profile=SAMLBrowserProfile::Post; // not really, but...
bpr.response=response.release();
bpr.assertion=assertion;
bpr.authnStatement=authnStatement;
}
catch (SAMLException& ex) {
annotateException(&ex,role); // throws it
}
}
}
}
if (rdoc) {
rdoc->release();
rdoc=NULL;
}
}
catch(...) {
if (rdoc) rdoc->release();
throw;
}
}
if (bADFS && !bpr.response)
throw FatalProfileException("ADFS profile was indicated, but processing was unsuccesful");
}
// If ADFS wasn't used, proceed to SAML processing up until we reach a common point.
int minorVersion = 1;
try {
if (!bADFS) {
int allowed = 0;
if (supported_profiles & SAML11_POST || supported_profiles & SAML10_POST)
allowed |= SAMLBrowserProfile::Post;
if (supported_profiles & SAML11_ARTIFACT || supported_profiles & SAML10_ARTIFACT)
allowed |= SAMLBrowserProfile::Artifact;
minorVersion=(supported_profiles & SAML11_ARTIFACT || supported_profiles & SAML11_POST) ? 1 : 0;
auto_ptr<SAMLBrowserProfile::ArtifactMapper> artifactMapper(app->getArtifactMapper());
// Try and run the profile.
log->debug("executing browser profile...");
bpr=app->getBrowserProfile()->receive(
packet,
wrecipient.get(),
allowed,
(!checkReplay.first || checkReplay.second) ? conf->getReplayCache() : NULL,
artifactMapper.get(),
minorVersion
);
// Blow it away to clear any locks that might be held.
delete artifactMapper.release();
// Try and map to metadata (again).
// Once the metadata layer is in the SAML core, the repetition should be fixed.
const IEntityDescriptor* provider=m.lookup(bpr.assertion->getIssuer());
if (!provider && bpr.authnStatement->getSubject()->getNameIdentifier() &&
bpr.authnStatement->getSubject()->getNameIdentifier()->getNameQualifier())
provider=m.lookup(bpr.authnStatement->getSubject()->getNameIdentifier()->getNameQualifier());
if (provider) {
const IIDPSSODescriptor* IDP=provider->getIDPSSODescriptor(
minorVersion==1 ? saml::XML::SAML11_PROTOCOL_ENUM : saml::XML::SAML10_PROTOCOL_ENUM
);
role=IDP;
}
// This isn't likely, since the profile must have found a role.
if (!role) {
MetadataException ex("Unable to locate role-specific metadata for identity provider.");
annotateException(&ex,provider); // throws it
}
}
// At this point, we link back up and do the same work for ADFS and SAML.
// Maybe verify the origin address....
if (checkIPAddress) {
log->debug("verifying client address");
// Verify the client address exists
const XMLCh* wip = bpr.authnStatement->getSubjectIP();
if (wip && *wip) {
// Verify the client address matches authentication
auto_ptr_char this_ip(wip);
if (strcmp(ip, this_ip.get())) {
FatalProfileException ex(
SESSION_E_ADDRESSMISMATCH,
"Your client's current address ($1) differs from the one used when you authenticated "
"to your identity provider. To correct this problem, you may need to bypass a proxy server. "
"Please contact your local support staff or help desk for assistance.",
params(1,ip)
);
annotateException(&ex,role); // throws it
}
}
}
// Verify condition(s) on authentication assertion.
// Attribute assertions get filtered later by the AAP.
Iterator<SAMLCondition*> conditions=bpr.assertion->getConditions();
while (conditions.hasNext()) {
SAMLCondition* cond=conditions.next();
const SAMLAudienceRestrictionCondition* ac=dynamic_cast<const SAMLAudienceRestrictionCondition*>(cond);
if (!ac) {
ostringstream os;
os << *cond;
log->error("Unrecognized Condition in authentication assertion (%s), tossing it.",os.str().c_str());
FatalProfileException ex("unable to create session due to unrecognized condition in authentication assertion.");
annotateException(&ex,role); // throws it
}
else if (!ac->eval(app->getAudiences())) {
ostringstream os;
os << *ac;
log->error("Unacceptable AudienceRestrictionCondition in authentication assertion (%s), tossing it.",os.str().c_str());
FatalProfileException ex("unable to create session due to unacceptable AudienceRestrictionCondition in authentication assertion.");
annotateException(&ex,role); // throws it
}
}
}
catch (SAMLException&) {
bpr.clear();
throw;
}
catch (...) {
log->error("caught unknown exception");
bpr.clear();
#ifdef _DEBUG
throw;
#else
SAMLException e("An unexpected error occurred while creating your session.");
annotateException(&e,role);
#endif
}
// It passes all our tests -- create a new session.
// Are attributes present?
bool attributesPushed=false;
Iterator<SAMLAssertion*> assertions=bpr.response->getAssertions();
while (!attributesPushed && assertions.hasNext()) {
Iterator<SAMLStatement*> statements=assertions.next()->getStatements();
while (!attributesPushed && statements.hasNext()) {
if (dynamic_cast<SAMLAttributeStatement*>(statements.next()))
attributesPushed=true;
}
}
auto_ptr_char oname(role->getEntityDescriptor()->getId());
auto_ptr_char hname(bpr.authnStatement->getSubject()->getNameIdentifier()->getName());
try {
// Create a new session key.
cookie = conf->getSessionCache()->generateKey();
// Insert into cache.
auto_ptr<SAMLAuthenticationStatement> as(static_cast<SAMLAuthenticationStatement*>(bpr.authnStatement->clone()));
conf->getSessionCache()->insert(
cookie.c_str(),
app,
ip,
(bADFS ? ADFS_SSO :
((bpr.profile==SAMLBrowserProfile::Post) ?
(minorVersion==1 ? SAML11_POST : SAML10_POST) : (minorVersion==1 ? SAML11_ARTIFACT : SAML10_ARTIFACT))),
oname.get(),
as.get(),
(attributesPushed ? bpr.response : NULL),
role
);
as.release(); // owned by cache now
}
catch (SAMLException&) {
bpr.clear();
throw;
}
catch (...) {
log->error("caught unknown exception");
bpr.clear();
#ifdef _DEBUG
throw;
#else
SAMLException e("An unexpected error occurred while creating your session.");
annotateException(&e,role);
#endif
}
target = bpr.TARGET;
provider_id = oname.get();
// Maybe delete the response...
if (!attributesPushed)
bpr.clear();
log->debug("new session id: %s", cookie.c_str());
// Transaction Logging
FixedContextCategory tranLog(SHIBTRAN_LOGCAT);
tranLog.infoStream() <<
"New session (ID: " <<
cookie <<
") with (applicationId: " <<
app->getId() <<
") for principal from (IdP: " <<
provider_id <<
") at (ClientAddress: " <<
ip <<
") with (NameIdentifier: " <<
hname.get() <<
")";
//stc.releaseTransactionLog();
}
void ADFSListener::sessionGet(
const IApplication* app,
const char* cookie,
const char* ip,
ISessionCacheEntry** pentry
) const
{
g_MemoryListener->sessionGet(app,cookie,ip,pentry);
}
void ADFSListener::sessionEnd(
const IApplication* application,
const char* cookie
) const
{
g_MemoryListener->sessionEnd(application,cookie);
}
void ADFSListener::ping(int& i) const
{
g_MemoryListener->ping(i);
}
| [
"cantor@cb58f699-b61c-0410-a6fe-9272a202ed29"
] | cantor@cb58f699-b61c-0410-a6fe-9272a202ed29 |
3ddb718a332188d620443e10dcef4f693e82104a | 48530aaa54b22e5fa131e620dfe4f4b52d176011 | /src/skse64/skaar_skse_plugin/SkaarSpecialInventoryCrafting.h | d09745fcbe17e90630526979a2f4327c994c947c | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | clayne/sse_character_export | 3d3b05e1fab98c4b64b414bacf6cb11bb541d34d | 04b5a650f4392f5cb03f1fcd9146938307f221a7 | refs/heads/master | 2022-12-24T18:52:05.844331 | 2020-10-06T05:24:11 | 2020-10-06T05:24:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 990 | h | #include "skse/PapyrusNativeFunctions.h"
#include "skse/GameReferences.h"
#include "skse/GameExtraData.h"
namespace SkaarSpecialInventoryCrafting {
// Add all the contents from a source container to a destination container, leaving the source container untouched
void SkaarAddItemsFromContainerToContainer(StaticFunctionTag *base, TESObjectREFR* pSourceContainerRef, TESObjectREFR* pDestContainerRef, UInt32 typeID);
// Any item and its count of items in the given container will be removed from the other container, leaving the first container untouched
void SkaarRemoveItemsInContainerFromContainer(StaticFunctionTag *base, TESObjectREFR* pInContainerRef, TESObjectREFR* pFromContainerRef, UInt32 typeID);
// Helper functions
// Test if a given EntryData is already in a given EntryDataList
bool SkaarEntryDataListContainsEntryData(ExtraContainerChanges::EntryDataList *entryDataList, ExtraContainerChanges::EntryData *entry);
bool RegisterFuncs(VMClassRegistry* registry);
}
| [
"[email protected]"
] | |
406db367c87bf4123a17ab4ea1ffa7af4013f025 | d6805c8ab206ea1cdffe3cd507a6ffb03e1d7c65 | /KernelEvolve/src/Graphics/GraphicsSimulation.cpp | bde5564e99b2055c6568922b20825ab0fe0a38f9 | [] | no_license | Hegodi/Evolve | c91193ba84c5ef4b735b449b2e6b70babbf1e900 | 389e5e99a8621cd4495c54a2bf23a399adc3a58c | refs/heads/main | 2023-03-19T03:38:13.734536 | 2021-03-14T10:10:16 | 2021-03-14T10:10:16 | 347,599,251 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,473 | cpp |
#include <vector>
#include <string>
#include "GraphicsSimulation.h"
bool CGraphicsSimulation::OnUserUpdate(float fElapsedTime)
{
m_world->Update();
m_offsetTarget = m_world->GetCenter() * m_scale;
m_offset = Vector2D<float>::Lerp(m_offset, m_offsetTarget, 0.01f);
CheckUserInput();
Render();
return true;
}
void CGraphicsSimulation::CheckUserInput()
{
if (GetKey(olc::Key::K1).bPressed)
{
m_scale = ScreenHeight() / m_world->GetSize();
}
else if (GetKey(olc::Key::K2).bPressed)
{
m_scale = 2.0 * ScreenHeight() / m_world->GetSize();
}
else if (GetKey(olc::Key::K3).bPressed)
{
m_scale = 4.0 * ScreenHeight() / m_world->GetSize();
}
else if (GetKey(olc::Key::N).bPressed)
{
m_indexNodeSelected = (m_indexNodeSelected + 1) % m_world->GetNumberNodes();
m_nodeSelected = m_world->GetNode(m_indexNodeSelected);
}
else if (GetKey(olc::Key::S).bPressed)
{
m_indexSpringSelected = (m_indexSpringSelected + 1) % m_world->GetNumberSrings();
m_springSelected = m_world->GetSpring(m_indexSpringSelected);
}
}
void CGraphicsSimulation::Render()
{
Clear(olc::BLACK);
RenderBackground();
RenderWorldInfo();
if (m_world == nullptr)
{
return;
}
std::vector<CNode*> const& nodes = m_world->GetNodes();
for (CNode* const node : nodes)
{
olc::Pixel color = olc::RED;
if (node == m_nodeSelected)
{
color = olc::YELLOW;
}
Vec2f pos = node->GetPos() * m_scale;
FixGraphicPosition(pos);
FillCircle(pos.x, pos.y, node->GetRadius() * m_scale, color);
}
std::vector<CSpring*> const& springs = m_world->GetSprings();
for (CSpring* const spring : springs)
{
olc::Pixel color = olc::RED;
Vec2f pos1 = spring->GetPosStart() * m_scale;
FixGraphicPosition(pos1);
Vec2f pos2 = spring->GetPosEnd() * m_scale;
FixGraphicPosition(pos2);
if (spring == m_springSelected)
{
color = olc::YELLOW;
}
else
{
if (typeid(*spring) == typeid(CSpringActive))
{
color = olc::GREEN;
}
else if (typeid(*spring) == typeid(CSpringPasive))
{
color = olc::RED;
}
}
DrawLine(pos1.x, pos1.y, pos2.x, pos2.y, color);
}
Vec2f center = m_world->GetCenter();
static char buffer[128];
sprintf_s(buffer, "Pos: %.2f, %.2f", center.x, center.y);
DrawString(5, ScreenHeight() - 10, buffer);
}
void CGraphicsSimulation::RenderBackground()
{
float lenght = ScreenHeight();
float deltaX = 10.0f * m_scale;
int indCenter = (int)(m_offset.x / deltaX);
for (int i = -8; i < 8; i++)
{
float x = (indCenter + i) * deltaX;
Vec2f pos1;
pos1.x = x;
pos1.y = 0.0f;
Vec2f pos2;
pos2.x = x;
pos2.y = lenght;
FixGraphicPosition(pos1);
FixGraphicPosition(pos2);
DrawLine(pos1.x, pos1.y, pos2.x, pos2.y, olc::GREY);
Vec2f posText;
posText.x = x - 10;
posText.y = -30;
FixGraphicPosition(posText);
std::string textNumber = std::to_string((int)(x / m_scale));
DrawString(posText.x, posText.y, textNumber, olc::GREY);
}
Vec2f pos;
FixGraphicPosition(pos);
FillRect(0.0, pos.y, ScreenWidth(), 10, olc::WHITE);
float time = m_world->GetTime();
std::string textTime = std::to_string(time);
DrawString(ScreenWidth() - 100, 10, textTime, olc::GREY);
}
void CGraphicsSimulation::RenderWorldInfo()
{
if (m_nodeSelected != nullptr)
{
std::string text;
text = "Node " + std::to_string(m_indexNodeSelected);
DrawString(5, 5, text);
text = "Radius " + std::to_string(m_nodeSelected->GetRadius());
DrawString(5, 15, text);
text = "Elastic Coef. " + std::to_string(m_nodeSelected->GetElasticCoefficient());
DrawString(5, 35, text);
text = "Friction Coef. " + std::to_string(m_nodeSelected->GetFrictionCoefficient());
DrawString(5, 45, text);
}
if (m_springSelected != nullptr)
{
std::string text;
text = "Spring " + std::to_string(m_indexSpringSelected);
DrawString(5, 70, text);
text = "Spring Constant " + std::to_string(m_springSelected->GetSpringConstant());
DrawString(5, 80, text);
text = "Length " + std::to_string(m_springSelected->GetLength());
DrawString(5, 90, text);
if (CSpringActive const* springActive = dynamic_cast<CSpringActive const*>(m_springSelected))
{
text = "Delta Length " + std::to_string(springActive->GetDeltaLengthFactor());
DrawString(5, 100, text);
text = "Period " + std::to_string(springActive->GetPeriod());
DrawString(5, 110, text);
}
}
}
void CGraphicsSimulation::FixGraphicPosition(Vec2f& pos)
{
pos.y = 0.8f * ScreenHeight() - pos.y;
pos.x += ScreenWidth() * 0.5f;
pos.x -= m_offset.x;
}
| [
"[email protected]"
] | |
a48b1a8826f689005407bdca656aee50a2060f45 | a56252fda5c9e42eff04792c6e16e413ad51ba1a | /resources/home/dnanexus/root/include/TSpectrum2Transform.h | 5672590941180f54725f8cff566a4ac3b246a0f2 | [
"LGPL-2.1-or-later",
"LGPL-2.1-only",
"Apache-2.0"
] | permissive | edawson/parliament2 | 4231e692565dbecf99d09148e75c00750e6797c4 | 2632aa3484ef64c9539c4885026b705b737f6d1e | refs/heads/master | 2021-06-21T23:13:29.482239 | 2020-12-07T21:10:08 | 2020-12-07T21:10:08 | 150,246,745 | 0 | 0 | Apache-2.0 | 2019-09-11T03:22:55 | 2018-09-25T10:21:03 | Python | UTF-8 | C++ | false | false | 4,253 | h | // @(#)root/spectrum:$Id$
// Author: Miroslav Morhac 25/09/06
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT_TSpectrum2Transform
#define ROOT_TSpectrum2Transform
#include "TNamed.h"
class TSpectrum2Transform : public TObject {
protected:
Int_t fSizeX; ///< x length of transformed data
Int_t fSizeY; ///< y length of transformed data
Int_t fTransformType; ///< type of transformation (Haar, Walsh, Cosine, Sine, Fourier, Hartley, Fourier-Walsh, Fourier-Haar, Walsh-Haar, Cosine-Walsh, Cosine-Haar, Sine-Walsh, Sine-Haar)
Int_t fDegree; ///< degree of mixed transform, applies only for Fourier-Walsh, Fourier-Haar, Walsh-Haar, Cosine-Walsh, Cosine-Haar, Sine-Walsh, Sine-Haar transforms
Int_t fDirection; ///< forward or inverse transform
Int_t fXmin; ///< first channel x of filtered or enhanced region
Int_t fXmax; ///< last channel x of filtered or enhanced region
Int_t fYmin; ///< first channel y of filtered or enhanced region
Int_t fYmax; ///< last channel y of filtered or enhanced region
Double_t fFilterCoeff; ///< value set in the filtered region
Double_t fEnhanceCoeff; ///< multiplication coefficient applied in enhanced region;
public:
enum {
kTransformHaar =0,
kTransformWalsh =1,
kTransformCos =2,
kTransformSin =3,
kTransformFourier =4,
kTransformHartley =5,
kTransformFourierWalsh =6,
kTransformFourierHaar =7,
kTransformWalshHaar =8,
kTransformCosWalsh =9,
kTransformCosHaar =10,
kTransformSinWalsh =11,
kTransformSinHaar =12,
kTransformForward =0,
kTransformInverse =1
};
TSpectrum2Transform();
TSpectrum2Transform(Int_t sizeX, Int_t sizeY);
virtual ~TSpectrum2Transform();
protected:
void BitReverse(Double_t *working_space,Int_t num);
void BitReverseHaar(Double_t *working_space,Int_t shift,Int_t num,Int_t start);
void FourCos2(Double_t **working_matrix,Double_t *working_vector,Int_t numx,Int_t numy,Int_t direction,Int_t type);
void Fourier(Double_t *working_space,Int_t num,Int_t hartley,Int_t direction,Int_t zt_clear);
void General2(Double_t **working_matrix,Double_t *working_vector,Int_t numx,Int_t numy,Int_t direction,Int_t type,Int_t degree);
Int_t GeneralExe(Double_t *working_space,Int_t zt_clear,Int_t num,Int_t degree,Int_t type);
Int_t GeneralInv(Double_t *working_space,Int_t num,Int_t degree,Int_t type);
void Haar(Double_t *working_space,Int_t num,Int_t direction);
void HaarWalsh2(Double_t **working_matrix,Double_t *working_vector,Int_t numx,Int_t numy,Int_t direction,Int_t type);
void Walsh(Double_t *working_space,Int_t num);
public:
void Enhance(const Double_t **fSource, Double_t **fDest);
void FilterZonal(const Double_t **fSource, Double_t **fDest);
void SetDirection(Int_t direction);
void SetEnhanceCoeff(Double_t enhanceCoeff);
void SetFilterCoeff(Double_t filterCoeff);
void SetRegion(Int_t xmin, Int_t xmax, Int_t ymin, Int_t ymax);
void SetTransformType(Int_t transType, Int_t degree);
void Transform(const Double_t **fSource, Double_t **fDest);
ClassDef(TSpectrum2Transform,1) //Spectrum2 Transformer, it calculates classic orthogonal 2D transforms
};
#endif
| [
"[email protected]"
] | |
c1cd202b3ea1a702937a5da54312cb1c03fca9dd | 33cdd5ccd542e647b72972b634203b20277852eb | /Css343Lab4/RentalShop.cpp | 7a4a310df27ef8308f48cf154581e89c4d7b1745 | [
"MIT"
] | permissive | Whompithian/css343-project4 | 1430e7ab3551f84921b9edac3e7c549c92b0b445 | b527c4a35126c0be41bf0a2c0d70d1a2d986b164 | refs/heads/main | 2023-07-20T08:50:18.728804 | 2016-06-09T05:08:27 | 2016-06-09T05:08:27 | 60,750,946 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,715 | cpp | /*
* @file RentalShop.cpp
* @brief This class represents a shop that rents items to customers. It is a
* type of business that deals with material goods, so it has a
* merchandise inventory. A rental shop may have an expected number of
* unique items it will hold in inventory and may have a set limit on
* the number of each item it will carry.
* @author Brendan Sweeney, SID 1161836
* @date March 9, 2012
*/
#include "RentalShop.h"
RentalShop::RentalShop(const string& newName, int customerBase,
int idealStock = 47, int maxQty = 10) :
Business(newName, customerBase), stock(idealStock, maxQty)
{
} // end Constructor
RentalShop::~RentalShop()
{
} // end Destructor
int RentalShop::getItemQty(void) const
{
return stock.getItemQty();
} // end getItemQty()
bool RentalShop::setItemQty(int stockSize)
{
stock.setItemQty(stockSize);
} // end setItemQty(int)
int RentalShop::getMaxQty(void) const
{
return stock.getMaxQty();
} // end getMaxQty()
bool RentalShop::setMaxQty(int newQty)
{
return stock.setMaxQty(newQty);
} // end setMaxQty(int)
bool RentalShop::addItem(const Merch *newItem)
{
return stock.addItem(newItem);
} // end addItem(Merch*)
bool RentalShop::updateItem(const Merch *item)
{
return stock.updateItem(item);
} // end updateItem(Merch*)
bool RentalShop::removeItem(const Merch *item)
{
return stock.removeItem(item);
} // end removeItem(Merch*)
bool RentalShop::retrieveItem(Merch *& target) const
{
return stock.retrieveItem(target);
} // end findItem(Merch*&)
void RentalShop::showInventory(void) const
{
stock.displayInventory();
} // end showInventory()
| [
"[email protected]"
] | |
c78429712b9834f130547109629aba07baf17f15 | fb6e1b288e76b34903b5d79262e5942148f1b188 | /TestCapi/Test_CDistributedQueue.cpp | 817727b9462e664c3af46283487703c68eaba5ad | [] | no_license | zhangnju/capi | 2fee06bb32b4871ca79dc062115a8dacf6b3febf | bc64605c18e47b90dd2f69ff9d1d622e3a89d6a1 | refs/heads/master | 2020-03-18T01:31:13.212222 | 2018-05-20T11:52:06 | 2018-05-20T11:52:06 | 134,145,645 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,236 | cpp | /*
* Copyright (c) 2006-2008
* Author: Weiming Zhou
*
* Permission to use, copy, modify, distribute and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies and
* that both that copyright notice and this permission notice appear
* in supporting documentation.
*/
#include <windows.h>
#include <stdio.h>
#include <omp.h>
#include "TestApi.h"
#include "CLocalQueue.h"
#include "CStealQueue.h"
#include "CQueuePool.h"
#include "CDistributedQueue.h"
void TestCase_CDistributedQueue_Constructor1(void);
void TestCase_CDistributedQueue_Constructor2(void);
void TestCase_CDistributedQueue_Pop(void);
void TestCase_CDistributedQueue_Push(void);
void Test_CDistributedQueue()
{
TestCase_Add(TestCase_CDistributedQueue_Constructor1);
TestCase_Add(TestCase_CDistributedQueue_Constructor2);
TestCase_Add(TestCase_CDistributedQueue_Pop);
TestCase_Add(TestCase_CDistributedQueue_Push);
}
REGISTER_TESTFUNC(Test_CDistributedQueue)
void TestCase_CDistributedQueue_Constructor1(void)
{
#if 0
CStealQueue<int> Q(4);
int nSize;
int nCore = omp_get_num_procs();
nSize = DEFAULT_STEALQUEUE_RESERVED_SIZE+nCore;
assertTrue(nSize == Q.m_uMaxSize);
assertTrue(Q.m_uHead == 0 && Q.m_uTail == 0);
assertTrue(Q.m_lSize == 0 && Q.m_uFullSize == nCore);
assertTrue(Q.IsEmpty());
assertFalse(Q.IsFull());
#endif
}
void TestCase_CDistributedQueue_Constructor2(void)
{
#if 0
CStealQueue<int> Q(8);
int nSize;
int nCore = omp_get_num_procs();
nSize = DEFAULT_STEALQUEUE_RESERVED_SIZE+nCore;
assertTrue(8 == Q.m_uMaxSize);
assertTrue(Q.m_uHead == 0 && Q.m_uTail == 0);
assertTrue(Q.m_lSize == 0 && Q.m_uFullSize == 8-DEFAULT_STEALQUEUE_RESERVED_SIZE);
assertTrue(Q.IsEmpty());
assertFalse(Q.IsFull());
#endif
}
void TestCase_CDistributedQueue_Pop(void)
{
CDistributedQueue<int, CLocalQueue<int>, CQueuePool<int, CStealQueue<int>>> dque;
dque.Create(16, 0, 16, 0);
int x = 10;
dque.EnQueue(x);
x = 15;
dque.EnQueue(x);
x = 20;
dque.EnQueue(x);
int a;
dque.DeQueue(a);
assertTrue(a==10);
dque.DeQueue(a);
assertTrue(a==15);
dque.DeQueue(a);
assertTrue(a==20);
x = 121;
dque.PushToSharedQueue(x);
dque.DeQueue(a);
assertTrue(a==121);
int ret = dque.DeQueue(a);
assertTrue(ret == CAPI_FAILED && a == 121);
x = 90;
dque.PushToLocalQueue(x);
dque.DeQueue(a);
assertTrue(a==90);
}
void TestCase_CDistributedQueue_Push(void)
{
CDistributedQueue<int, CLocalQueue<int>, CStealQueue<int>> dque;
dque.Create(16, 0, 16, 0);
int x = 10;
dque.EnQueue(x);
x = 15;
dque.EnQueue(x);
x = 20;
dque.EnQueue(x);
int a;
dque.DeQueue(a);
assertTrue(a==10);
dque.DeQueue(a);
assertTrue(a==15);
dque.DeQueue(a);
assertTrue(a==20);
x = 121;
dque.PushToSharedQueue(x);
dque.DeQueue(a);
assertTrue(a==121);
int ret = dque.DeQueue(a);
assertTrue(ret == CAPI_FAILED && a == 121);
x = 90;
dque.PushToLocalQueue(x);
dque.DeQueue(a);
assertTrue(a==90);
}
| [
"[email protected]"
] | |
9eb95ec7d28b4d90750b6ae188044a503c1ee66e | 303ab321bfc10a2d7f9c15f2db1bef6c4a41785c | /Release/moc_advancemonitordlg.cpp | 25f07011ce379ba4371c05a2bc55cd7a84691a10 | [] | no_license | webstorage119/RemoteControl-1 | f27304d8ad870344a2cb618b786f269e5c54d2b7 | 65466940a50da547069e6e2078f5b312714d3e57 | refs/heads/master | 2023-07-05T17:50:26.331178 | 2015-08-17T12:15:19 | 2015-08-17T12:15:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,735 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'advancemonitordlg.h'
**
** Created: Tue Jun 30 23:22:06 2015
** by: The Qt Meta Object Compiler version 63 (Qt 4.8.4)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../advancemonitordlg.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'advancemonitordlg.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 63
#error "This file was generated using the moc from 4.8.4. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_AdvanceMonitorDlg[] = {
// content:
6, // revision
0, // classname
0, 0, // classinfo
5, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: signature, parameters, type, tag, flags
31, 19, 18, 18, 0x08,
92, 87, 18, 18, 0x08,
140, 87, 18, 18, 0x08,
187, 18, 18, 18, 0x08,
220, 18, 18, 18, 0x08,
0 // eod
};
static const char qt_meta_stringdata_AdvanceMonitorDlg[] = {
"AdvanceMonitorDlg\0\0item,column\0"
"onTrAdvanceFileMonitorItemClicked(QTreeWidgetItem*,int)\0"
"item\0onTbUsbPlugRecordItemClicked(QTableWidgetItem*)\0"
"onTbUsbDirItemDoubleClicked(QTableWidgetItem*)\0"
"onBtnCleanMonitorRecordClicked()\0"
"onBtnCancelMonitorClicked()\0"
};
void AdvanceMonitorDlg::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
Q_ASSERT(staticMetaObject.cast(_o));
AdvanceMonitorDlg *_t = static_cast<AdvanceMonitorDlg *>(_o);
switch (_id) {
case 0: _t->onTrAdvanceFileMonitorItemClicked((*reinterpret_cast< QTreeWidgetItem*(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break;
case 1: _t->onTbUsbPlugRecordItemClicked((*reinterpret_cast< QTableWidgetItem*(*)>(_a[1]))); break;
case 2: _t->onTbUsbDirItemDoubleClicked((*reinterpret_cast< QTableWidgetItem*(*)>(_a[1]))); break;
case 3: _t->onBtnCleanMonitorRecordClicked(); break;
case 4: _t->onBtnCancelMonitorClicked(); break;
default: ;
}
}
}
const QMetaObjectExtraData AdvanceMonitorDlg::staticMetaObjectExtraData = {
0, qt_static_metacall
};
const QMetaObject AdvanceMonitorDlg::staticMetaObject = {
{ &QWidget::staticMetaObject, qt_meta_stringdata_AdvanceMonitorDlg,
qt_meta_data_AdvanceMonitorDlg, &staticMetaObjectExtraData }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &AdvanceMonitorDlg::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *AdvanceMonitorDlg::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *AdvanceMonitorDlg::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_AdvanceMonitorDlg))
return static_cast<void*>(const_cast< AdvanceMonitorDlg*>(this));
return QWidget::qt_metacast(_clname);
}
int AdvanceMonitorDlg::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 5)
qt_static_metacall(this, _c, _id, _a);
_id -= 5;
}
return _id;
}
QT_END_MOC_NAMESPACE
| [
"[email protected]"
] | |
51c97ca4b96c9a03e972aa839d1f30ff737250f7 | 6fe7aae8ade04b2093a196adaa6822346f0d9e5b | /tests/ft_strlcpy_test.cpp | bbb23b5f13a726ed7fe45b17cd3b5f680c5ed806 | [] | no_license | brhaka/libftTester | d95e004b04fb33dc252330cb89e90d277bb54eca | 96a8e715e2063f322a0a6de4d1c0ab1edc18f655 | refs/heads/master | 2023-03-19T18:57:33.860128 | 2021-02-24T09:50:42 | 2021-02-24T09:50:42 | 340,689,119 | 1 | 0 | null | 2021-02-20T15:38:36 | 2021-02-20T15:38:35 | null | UTF-8 | C++ | false | false | 1,375 | cpp | extern "C"
{
#define new tripouille
#include "libft.h"
#undef new
}
#include "sigsegv.hpp"
#include "check.hpp"
#include "leaks.hpp"
#include <string.h>
int iTest = 1;
int main(void)
{
signal(SIGSEGV, sigsegv);
title("ft_strlcpy\t: ")
char src[] = "coucou";
char dest[10]; memset(dest, 'A', 10);
/* 1 */ check(ft_strlcpy(dest, src, 0) == strlen(src) && dest[0] == 'A'); showLeaks();
/* 2 */ check(ft_strlcpy(dest, src, 1) == strlen(src) && dest[0] == 0 && dest[1] == 'A'); showLeaks();
/* 3 */ check(ft_strlcpy(dest, src, 2) == strlen(src) && dest[0] == 'c' && dest[1] == 0 && dest[2] == 'A'); showLeaks();
/* 4 */ check(ft_strlcpy(dest, src, -1) == strlen(src) && !strcmp(src, dest) && dest[strlen(src) + 1] == 'A'); showLeaks(); memset(dest, 'A', 10);
/* 5 */ check(ft_strlcpy(dest, src, 6) == strlen(src) && !memcmp(src, dest, 5) && dest[5] == 0); showLeaks(); memset(dest, 'A', 10);
/* 6 */ check(ft_strlcpy(dest, src, 7) == strlen(src) && !memcmp(src, dest, 7)); showLeaks(); memset(dest, 'A', 10);
/* 7 */ check(ft_strlcpy(dest, src, 8) == strlen(src) && !memcmp(src, dest, 7)); showLeaks(); memset(dest, 'A', 10);
/* 8 */ check(ft_strlcpy(dest, "", 42) == 0 && !memcmp("", dest, 1)); showLeaks(); memset(dest, 0, 10);
/* 9 */ check(ft_strlcpy(dest, "1", 0) == 1 && dest[0] == 0); showLeaks(); memset(dest, 'A', 10);
write(1, "\n", 1);
return (0);
} | [
"[email protected]"
] | |
3cb42927185699b9cbcd3b12a550426e106e6c8c | 83bacfbdb7ad17cbc2fc897b3460de1a6726a3b1 | /third_party/skia/gm/aaxfermodes.cpp | 378f2bb0884b44bef226a6edd7544384583c7ea0 | [
"Apache-2.0",
"BSD-3-Clause"
] | permissive | cool2528/miniblink49 | d909e39012f2c5d8ab658dc2a8b314ad0050d8ea | 7f646289d8074f098cf1244adc87b95e34ab87a8 | refs/heads/master | 2020-06-05T03:18:43.211372 | 2019-06-01T08:57:37 | 2019-06-01T08:59:56 | 192,294,645 | 2 | 0 | Apache-2.0 | 2019-06-17T07:16:28 | 2019-06-17T07:16:27 | null | UTF-8 | C++ | false | false | 10,160 | cpp |
/*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkArithmeticMode.h"
#include "SkShader.h"
#include "SkXfermode.h"
enum {
kXfermodeCount = SkXfermode::kLastMode + 2, // All xfermodes plus arithmetic mode.
kShapeSize = 22,
kShapeSpacing = 36,
kShapeTypeSpacing = 4 * kShapeSpacing / 3,
kPaintSpacing = 3 * kShapeTypeSpacing,
kLabelSpacing = 3 * kShapeSize,
kMargin = kShapeSpacing / 2,
kXfermodeTypeSpacing = kLabelSpacing + 2 * kPaintSpacing + kShapeTypeSpacing,
kTitleSpacing = 3 * kShapeSpacing / 4,
kSubtitleSpacing = 5 * kShapeSpacing / 8
};
static const SkColor kBGColor = SkColorSetARGB(200, 210, 184, 135);
static const SkColor kShapeColors[2] = {
SkColorSetARGB(130, 255, 0, 128), // input color unknown
SkColorSetARGB(255, 0, 255, 255) // input color opaque
};
enum Shape {
kSquare_Shape,
kDiamond_Shape,
kOval_Shape,
kLast_Shape = kOval_Shape
};
namespace skiagm {
/**
* Verifies AA works properly on all Xfermodes, including arithmetic, with both opaque and unknown
* src colors.
*/
class AAXfermodesGM : public GM {
public:
AAXfermodesGM() {}
protected:
enum DrawingPass {
kCheckerboard_Pass,
kBackground_Pass,
kShape_Pass
};
SkString onShortName() override {
return SkString("aaxfermodes");
}
SkISize onISize() override {
return SkISize::Make(2 * kMargin + 2 * kXfermodeTypeSpacing -
(kXfermodeTypeSpacing - (kLabelSpacing + 2 * kPaintSpacing)),
2 * kMargin + kTitleSpacing + kSubtitleSpacing +
(1 + SkXfermode::kLastCoeffMode) * kShapeSpacing);
}
void onOnceBeforeDraw() override {
fLabelPaint.setAntiAlias(true);
sk_tool_utils::set_portable_typeface_always(&fLabelPaint);
fLabelPaint.setTextSize(5 * kShapeSize/8);
fLabelPaint.setSubpixelText(true);
static const SkScalar radius = -1.4f * kShapeSize/2;
SkPoint pts[4] = {
{-radius, 0},
{0, -1.33f * radius},
{radius, 0},
{0, 1.33f * radius}
};
fPath.moveTo(pts[0]);
fPath.quadTo(pts[1], pts[2]);
fPath.quadTo(pts[3], pts[0]);
}
void draw_pass(SkCanvas* canvas, DrawingPass drawingPass) {
SkRect clipRect =
{ -kShapeSize*11/16, -kShapeSize*11/16, kShapeSize*11/16, kShapeSize*11/16 };
canvas->save();
if (kCheckerboard_Pass == drawingPass) {
canvas->translate(kMargin, kMargin);
}
canvas->translate(0, kTitleSpacing);
for (size_t xfermodeSet = 0; xfermodeSet < 2; xfermodeSet++) {
size_t firstMode = (SkXfermode::kLastCoeffMode + 1) * xfermodeSet;
canvas->save();
if (kShape_Pass == drawingPass) {
fLabelPaint.setTextAlign(SkPaint::kCenter_Align);
canvas->drawText("Src Unknown", sizeof("Src Unknown") - 1,
kLabelSpacing + kShapeSpacing / 2 + kShapeTypeSpacing,
kSubtitleSpacing / 2 + fLabelPaint.getTextSize() / 3, fLabelPaint);
canvas->drawText("Src Opaque", sizeof("Src Opaque") - 1,
kLabelSpacing + kShapeSpacing / 2 + kShapeTypeSpacing + kPaintSpacing,
kSubtitleSpacing / 2 + fLabelPaint.getTextSize() / 3, fLabelPaint);
}
canvas->translate(0, kSubtitleSpacing + kShapeSpacing/2);
for (size_t m = 0; m <= SkXfermode::kLastCoeffMode; m++) {
SkXfermode::Mode mode = static_cast<SkXfermode::Mode>(firstMode + m);
canvas->save();
if (kShape_Pass == drawingPass) {
this->drawModeName(canvas, mode);
}
canvas->translate(kLabelSpacing + kShapeSpacing/2, 0);
for (size_t colorIdx = 0; colorIdx < SK_ARRAY_COUNT(kShapeColors); colorIdx++) {
SkPaint paint;
this->setupShapePaint(canvas, kShapeColors[colorIdx], mode, &paint);
SkASSERT(colorIdx == 0 || 255 == paint.getAlpha());
canvas->save();
for (size_t shapeIdx = 0; shapeIdx <= kLast_Shape; shapeIdx++) {
if (kShape_Pass != drawingPass) {
canvas->save();
canvas->clipRect(clipRect);
if (kCheckerboard_Pass == drawingPass) {
sk_tool_utils::draw_checkerboard(canvas, 0xffffffff, 0xffc6c3c6,
10);
} else {
SkASSERT(kBackground_Pass == drawingPass);
canvas->drawColor(kBGColor, SkXfermode::kSrc_Mode);
}
canvas->restore();
} else {
this->drawShape(canvas, static_cast<Shape>(shapeIdx), paint, mode);
}
canvas->translate(kShapeTypeSpacing, 0);
}
canvas->restore();
canvas->translate(kPaintSpacing, 0);
}
canvas->restore();
canvas->translate(0, kShapeSpacing);
}
canvas->restore();
canvas->translate(kXfermodeTypeSpacing, 0);
}
canvas->restore();
}
void onDraw(SkCanvas* canvas) override {
draw_pass(canvas, kCheckerboard_Pass);
canvas->saveLayer(NULL, NULL);
canvas->translate(kMargin, kMargin);
draw_pass(canvas, kBackground_Pass);
SkPaint titlePaint(fLabelPaint);
titlePaint.setTextSize(9 * titlePaint.getTextSize() / 8);
titlePaint.setFakeBoldText(true);
titlePaint.setTextAlign(SkPaint::kCenter_Align);
canvas->drawText("Porter Duff", sizeof("Porter Duff") - 1,
kLabelSpacing + 3 * kShapeTypeSpacing,
kTitleSpacing / 2 + titlePaint.getTextSize() / 3, titlePaint);
canvas->drawText("Advanced", sizeof("Advanced") - 1,
kXfermodeTypeSpacing + kLabelSpacing + 3 * kShapeTypeSpacing,
kTitleSpacing / 2 + titlePaint.getTextSize() / 3, titlePaint);
draw_pass(canvas, kShape_Pass);
canvas->restore();
}
void drawModeName(SkCanvas* canvas, SkXfermode::Mode mode) {
const char* modeName = mode <= SkXfermode::kLastMode ? SkXfermode::ModeName(mode)
: "Arithmetic";
fLabelPaint.setTextAlign(SkPaint::kRight_Align);
canvas->drawText(modeName, strlen(modeName), kLabelSpacing - kShapeSize / 4,
fLabelPaint.getTextSize() / 3, fLabelPaint);
}
void setupShapePaint(SkCanvas* canvas, GrColor color, SkXfermode::Mode mode, SkPaint* paint) {
paint->setColor(color);
if (mode == SkXfermode::kPlus_Mode) {
// Check for overflow, otherwise we might get confusing AA artifacts.
int maxSum = SkTMax(SkTMax(SkColorGetA(kBGColor) + SkColorGetA(color),
SkColorGetR(kBGColor) + SkColorGetR(color)),
SkTMax(SkColorGetG(kBGColor) + SkColorGetG(color),
SkColorGetB(kBGColor) + SkColorGetB(color)));
if (maxSum > 255) {
SkPaint dimPaint;
dimPaint.setAntiAlias(false);
dimPaint.setXfermode(SkXfermode::Create(SkXfermode::kDstIn_Mode));
if (255 != paint->getAlpha()) {
// Dim the src and dst colors.
dimPaint.setARGB(255 * 255 / maxSum, 0, 0, 0);
paint->setAlpha(255 * paint->getAlpha() / maxSum);
} else {
// Just clear the dst, we need to preserve the paint's opacity.
dimPaint.setARGB(0, 0, 0, 0);
}
canvas->drawRectCoords(-kShapeSpacing/2, -kShapeSpacing/2,
kShapeSpacing/2 + 2 * kShapeTypeSpacing,
kShapeSpacing/2, dimPaint);
}
}
}
void drawShape(SkCanvas* canvas, Shape shape, const SkPaint& paint, SkXfermode::Mode mode) {
SkPaint shapePaint(paint);
shapePaint.setAntiAlias(kSquare_Shape != shape);
SkAutoTUnref<SkXfermode> xfermode;
if (mode <= SkXfermode::kLastMode) {
xfermode.reset(SkXfermode::Create(mode));
} else {
xfermode.reset(SkArithmeticMode::Create(+1.0f, +0.25f, -0.5f, +0.1f));
}
shapePaint.setXfermode(xfermode);
switch (shape) {
case kSquare_Shape:
canvas->drawRectCoords(-kShapeSize/2, -kShapeSize/2, kShapeSize/2, kShapeSize/2,
shapePaint);
break;
case kDiamond_Shape:
canvas->save();
canvas->rotate(45);
canvas->drawRectCoords(-kShapeSize/2, -kShapeSize/2, kShapeSize/2, kShapeSize/2,
shapePaint);
canvas->restore();
break;
case kOval_Shape:
canvas->save();
canvas->rotate(static_cast<SkScalar>((511 * mode + 257) % 360));
canvas->drawPath(fPath, shapePaint);
canvas->restore();
break;
default:
SkFAIL("Invalid shape.");
}
}
private:
SkPaint fLabelPaint;
SkPath fPath;
typedef GM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static GM* MyFactory(void*) { return new AAXfermodesGM; }
static GMRegistry reg(MyFactory);
}
| [
"[email protected]"
] | |
0b8479073a38c7da584f28785b9bbfe08403cd50 | 03b5b626962b6c62fc3215154b44bbc663a44cf6 | /src/instruction/FLD.h | 5342591b272d0d8721be1d735a5fdc572a099d9c | [] | no_license | haochenprophet/iwant | 8b1f9df8ee428148549253ce1c5d821ece0a4b4c | 1c9bd95280216ee8cd7892a10a7355f03d77d340 | refs/heads/master | 2023-06-09T11:10:27.232304 | 2023-05-31T02:41:18 | 2023-05-31T02:41:18 | 67,756,957 | 17 | 5 | null | 2018-08-11T16:37:37 | 2016-09-09T02:08:46 | C++ | UTF-8 | C++ | false | false | 201 | h | #ifndef FLD_H
#define FLD_H
#include "../object.h"
namespace n_FLD {
class CFLD :public Object
{
public:
CFLD();
~CFLD();
int my_init(void *p=nullptr);
};
}
using namespace n_FLD;
#endif
| [
"[email protected]"
] | |
b0f67ea01c19d1176ba1926a6bc14ceb2aa4d9cc | 6bac0a0b94a73eb3f52d978caf4665b2fa1062c7 | /source/player.h | 6229007f2d65252477c30efb5fc79f76f26e9878 | [] | no_license | Corosauce/AI_TestBed | a843be16aea121dae14706c196420f855873b9e6 | 8ae61b78faf7c55735f7c7fa1a00028c951ca8c7 | refs/heads/master | 2021-01-10T20:52:41.812296 | 2012-01-30T20:56:11 | 2012-01-30T20:56:11 | 3,308,728 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 285 | h | #ifndef PLAYER_H
#define PLAYER_H
#include "sprite.h"
struct mouseData {
long button;
long relx;
long rely;
long x;
long y;
};
class player: public sprite {
public:
player();
void InitPlayer ();
int test;
int DoMoves();
bool keys[323];
mouseData mouse;
};
#endif | [
"[email protected]"
] | |
341b035292c0486dcae0c37308178defa8af1966 | 0611b1cc08b15d329057595365359947c20fcd59 | /acwing/课/搜索/染色法.cpp | a4ee6a3bfbb8162343f6b8cdc71ff0f7213fc7aa | [] | no_license | Lan-ce-lot/overflow | c9a7167edaeeaa1f9f1e92624726b1d964289798 | ae76120e328a5a2991eb6ef7f1ae5e279374e15c | refs/heads/master | 2023-04-08T04:24:49.614146 | 2021-04-25T05:33:06 | 2021-04-25T05:33:06 | 279,082,035 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,205 | cpp | /*************************************************************************
> FileName:
> Author: Lance
> Mail: [email protected]
> Date: 9102.1.8
> Description:
************************************************************************/
//#include <bits/stdc++.h>
//#pragma comment(linker, "/STACK:102400000,102400000")//add_stack
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <sstream>
#include <vector>
#include <cstdio>
#include <bitset>
#include <string>
#include <cmath>
#include <deque>
#include <queue>
#include <stack>
#include <map>
#include <set>
using namespace std;
typedef long long ll;
typedef pair<int, int> PII;
const double pi = acos(-1.0);
const double eps = 1e-6;
const int mod = 1e9 + 7;
#define debug(a) cout << "*" << a << "*" << endl
const int INF = 0x3f3f3f3f;//int2147483647//ll9e18//unsigned ll 1e19
const int maxn = 1000005;
//sacnf("%lf") printf("%f")
ll read()
{
ll x = 0,f = 1;
char ch = getchar();
while (ch < '0' || ch > '9')
{
if (ch == '-')
f = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9')
{
x = x * 10 + ch - '0';
ch = getchar();
}
return x * f;
}
int t, n, m, color[maxn];
vector <int> G[maxn];
bool vis[maxn];
bool dfs(int u, int c)
{
color[u] = c;
for (int i = 0; i < G[u].size(); i++)
{
int j = G[u][i];
if (color[j] == -1)//未被染且不能符合条件
{
if (!dfs(j, !c)) return 0;
}
else if (color[j] == c) return 0;//已被染且相邻相同
}
return 1;
}
void solve()
{
cin >> n >> m;
for (int i = 0; i < m; i++)
{
int a, b;
cin >> a >> b;
G[a].push_back(b);
G[b].push_back(a);
}
memset(color, -1, sizeof color);
bool flag = 1;
for (int i = 1; i <= n; i++)
{
if (color[i] == -1)
{
if (!dfs(i, 0))
{
flag = 0;
break;
}
}
}
if (flag)
puts("Yes");
else
puts("No");
}
int main()
{
// freopen("F:/Overflow/in.txt","r",stdin);
// ios::sync_with_stdio(false);
solve();
return 0;
}
| [
"[email protected]"
] | |
3e25cb3c362831a5b25baa4525e9641850e52381 | 62f80a9c302a24ac1e9b5300cb2dabd425fa2cce | /SettingManager.h | 3ab01f327f0d24d1163e35dd8cdf4a0bcfd22b03 | [] | no_license | FlorianByl/AnalyseurPort | 491b58d60e4a2ed189b33a09e9c68fad0bb54650 | 47d9441773326366d4e2d24a7a7f8766b2a92fe1 | refs/heads/master | 2020-06-28T21:02:52.150744 | 2016-11-22T12:34:26 | 2016-11-22T12:34:26 | 74,470,198 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 151 | h | #ifndef _SETMAN_
#define _SETMAN_
#include <iostream>
class SettingManager
{
private:
/* data */
public:
SettingManager ();
};
#endif
| [
"[email protected]"
] | |
61b10865550d8dd5fd849d717994c053b79f124a | e1f3493a98ef150afbb37e4becd09cfb6b52330a | /lib/interpreter/engine/provider.cpp | e6b6a12672bd3d715924327b03fe4917333d17bd | [
"CC0-1.0",
"BSD-3-Clause",
"Apache-2.0"
] | permissive | sshyran/SSVM | 13738e3855d3719c2a722546a265736bf4844f3d | ff8c3dca9347468c3275dd8c3e233721e8d862c4 | refs/heads/master | 2023-04-07T10:40:30.634450 | 2020-09-25T07:06:37 | 2020-09-25T07:36:23 | 299,383,559 | 0 | 0 | null | 2023-04-04T01:08:50 | 2020-09-28T17:30:33 | null | UTF-8 | C++ | false | false | 645 | cpp | // SPDX-License-Identifier: Apache-2.0
#include "interpreter/engine/provider.h"
namespace SSVM {
namespace Interpreter {
/// Getter for next instruction. See "include/interpreter/engine/provider.h".
const AST::Instruction *InstrProvider::getNextInstr() {
/// Instruction sequence vector is empty.
if (Iters.size() == 0) {
return nullptr;
}
/// Instruction sequence executed to end.
if (Iters.back().Curr == Iters.back().End) {
return nullptr;
}
/// Get instruction.
const AST::Instruction *Instr = (*Iters.back().Curr).get();
(Iters.back().Curr)++;
return Instr;
}
} // namespace Interpreter
} // namespace SSVM
| [
"[email protected]"
] | |
76c2cd1e4764b3ec8c7753880fdca5529d06422b | 7eacf8b6bcbb464d23ae2a7bfe887c600fe63fa2 | /GLFWProject/SpriteSheet.cpp | d7efd35b445cb31bafcab35d854728d7d203c3f9 | [
"BSD-3-Clause"
] | permissive | HenryLoo/GLFWProject | e7f3186fc4e940ddab0ce0c1c5567258be59223b | 0b0f21779df452ca0e498ac141320944d5df0c16 | refs/heads/master | 2022-11-25T22:07:47.729468 | 2020-07-30T23:19:16 | 2020-07-30T23:19:16 | 183,114,850 | 1 | 0 | null | 2020-07-30T23:07:40 | 2019-04-24T00:17:26 | C++ | UTF-8 | C++ | false | false | 1,117 | cpp | #include "SpriteSheet.h"
#include "GameComponent.h"
SpriteSheet::SpriteSheet(GLuint id, GLint width, GLint height, GLint numChannels,
const std::unordered_map<std::string, SpriteSet> &sprites,
std::string name) :
Texture(id, width, height, numChannels), m_sprites(sprites),
m_name(name)
{
}
SpriteSheet::SpriteSheet(GLuint id, GLint width, GLint height, GLint numChannels,
std::string name) :
Texture(id, width, height, numChannels), m_name(name)
{
}
bool SpriteSheet::setSprite(const std::string &label,
GameComponent::Sprite &output) const
{
auto it{ m_sprites.find(label) };
if (it != m_sprites.end())
{
// Animation was found, so set it and reset the frame.
output.currentSprite = it->second;
output.currentFrame = 0;
output.currentFrameTime = 0;
return true;
}
return false;
}
bool SpriteSheet::getSprite(const std::string &label, SpriteSet &sprite) const
{
auto it{ m_sprites.find(label) };
if (it != m_sprites.end())
{
// Animation was found.
sprite = it->second;
return true;
}
return false;
}
const std::string &SpriteSheet::getName() const
{
return m_name;
} | [
"[email protected]"
] | |
e5a85714a495ea62ce9d410406a1a3644cdb635a | a542d7d423ce0966d59ec760987dddd6fa9767d2 | /androidUSBSample/linux/AdkEcho.cpp | 476262e60d1f4c486b0356cc77caaf6484bbe0f0 | [] | no_license | kotemaru/kotemaru | 05dc18271ca7a85af41d4fe0a8154b3809bbd83e | 0e886150a15c49abfcdec354d36d57a58061dcd0 | refs/heads/master | 2020-05-28T14:01:07.615419 | 2015-04-10T07:07:54 | 2015-04-10T07:07:54 | 33,769,860 | 5 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,175 | cpp | /**
Android USB connection sample.
@Author kotemru.org
@Licence apache/2.0
*/
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <string.h>
#include "AOA/AOA.h"
// USB Connector opend.
AOA acc("kotemaru.org",
"AdkSample",
"Sample for ADK",
"1.0",
"http://blog.kotemaru.org/androidUSBSample",
"000000000000001") ;
/**
* Disconnect USB innterrupt aborted.
*/
void signal_callback_handler(int signum)
{
fprintf(stderr, "\ninterrupt %d\n",signum);
acc.disconnect();
exit(0);
}
static void error(char *msg, int rc) {
fprintf(stderr,"Error(%d,%s): %s\n",rc,strerror(errno),msg);
acc.disconnect();
exit(0);
}
int main(int argc, char *argv[])
{
signal(SIGINT, signal_callback_handler);
signal(SIGTERM, signal_callback_handler);
unsigned char buff[1024];
acc.connect(100);
// Echo back.
while (1) {
int len = acc.read(buff, sizeof(buff), 1000000);
if (len < 0) error("acc.read",len);
buff[len+1] = '\0';
printf("USB>%s\n", buff);
for (int i=0; i<len; i++) buff[i] = buff[i] - 0x20;
acc.write(buff, len, 1000);
}
}
| [
"[email protected]@007fbaa9-8b8e-5bb4-69cf-ca3c05551f93"
] | [email protected]@007fbaa9-8b8e-5bb4-69cf-ca3c05551f93 |
ff18d07823c86a2408eab03381c0929e8f922904 | 664b5e8e92b44eecc14e60390152bdaee864b70a | /framework/src/gui/widgets/edit/dwtextlayoutengine.h | 717066f16889d5ff59b8059ad0090d29cb1b4a7f | [] | no_license | JerryZhou/Raccoon | a44f178ec47e3eb8181d05e6ca870d02c75477e8 | f8da3ddf82f0e5d2918d890eafbff77a61025d1e | refs/heads/master | 2016-09-05T20:24:23.866920 | 2013-10-25T08:14:53 | 2013-10-25T08:14:53 | 8,606,064 | 8 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 2,281 | h | #pragma once
#include "dwgui/dwrttiobject.h"
#include "dwcore/dwvector.h"
#include "dwcore/dwrect.h"
#include "dwgui/dwcharformat.h"
//------------------------------------------------------------------------------
class DwTextDocument;
class DwTextCursor;
// ONLY SUPPORT THE ONE LINE LAYOUT
//------------------------------------------------------------------------------
class DW_GUI_EXPORT DwTextLayoutEngine : public DwRttiObject
{
DW_DECLARE_CLASS(DwTextLayoutEngine);
public:
enum LayoutCache { Content = 0x01, Cursor = 0x02, Select = 0x04, ALL = 0xFFFF, };
DwTextLayoutEngine();
virtual ~DwTextLayoutEngine();
// invalidate the cache
virtual bool invalidateLayoutCache(int c);
// the text content
virtual bool layout(DwTextDocument * doc, const DwRectF &rect, DwVector<DwString>& strs, DwVector<DwRectF> &rects, DwVector<DwCharFormat*> &format) const;
// the flash cursor
virtual bool layout(DwTextDocument * doc, const DwRectF &rect, DwPointF &from, DwPointF &to) const;
// the select rect
virtual bool layout(DwTextDocument * doc, const DwRectF &rect, DwVector<DwRectF> &rects) const;
// calcute the num of char from begin to p, int rect
virtual int numOfPrintChar(DwTextDocument * doc, const DwRectF &rect, const DwPointF &p) const;
// calcute the text content rect
virtual bool contentRect(DwTextDocument * doc, const DwRectF &rect, DwRectF & textRect);
// add a character
virtual bool onAdd(DwTextDocument * doc, const DwRectF &rect, DwRichChar *c, int pos = -1);
// remove a character
virtual bool onDel(DwTextDocument * doc, const DwRectF &rect, DwRichChar *c, int pos = -1);
// set the org conetnt rect
void setOrgContentRect(const DwRectF &r);
// the org content rect
DwRectF orgContentRect() const;
protected:
// caculate the cursor point
virtual bool layoutCursor(DwTextDocument * doc, const DwRectF &rect, const DwTextCursor& cursor, DwPointF &from, DwPointF &to) const;
// set the flag of cache
void setCacheValidate(LayoutCache, bool b = true);
// require the cached
bool isCachedValidate(LayoutCache) const;
DwRectF m_orgContentRect;
int m_validateCache;
};// end of DwTextLayoutEngine
DW_REGISTER_CLASS(DwTextLayoutEngine); | [
"[email protected]"
] | |
2d84d7470db141e5f874f53ba575154c95ba1ca6 | 1b7daae23b2bd3baa72cf9711be00699dc387db3 | /src/qt/bitcoingui.h | ff0fd95648b5c2c09db7e788f442906545309a03 | [
"MIT"
] | permissive | hotion/BitCoinCppChinese | f48894beff6e652031f18b58181592af1168ed40 | 76f64ad8cee5b6c5671b3629f39e7ae4ef84be0a | refs/heads/master | 2020-04-18T06:33:11.575445 | 2019-01-24T02:02:27 | 2019-01-24T02:02:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,353 | h |
//此源码被清华学神尹成大魔王专业翻译分析并修改
//尹成QQ77025077
//尹成微信18510341407
//尹成所在QQ群721929980
//尹成邮箱 [email protected]
//尹成毕业于清华大学,微软区块链领域全球最有价值专家
//https://mvp.microsoft.com/zh-cn/PublicProfile/4033620
//版权所有(c)2011-2019比特币核心开发者
//根据MIT软件许可证分发,请参见随附的
//文件复制或http://www.opensource.org/licenses/mit-license.php。
#ifndef BITCOIN_QT_BITCOINGUI_H
#define BITCOIN_QT_BITCOINGUI_H
#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif
#include <qt/optionsdialog.h>
#include <amount.h>
#include <QLabel>
#include <QMainWindow>
#include <QMap>
#include <QPoint>
#include <QSystemTrayIcon>
#ifdef Q_OS_MAC
#include <qt/macos_appnap.h>
#endif
#include <memory>
class ClientModel;
class NetworkStyle;
class Notificator;
class OptionsModel;
class PlatformStyle;
class RPCConsole;
class SendCoinsRecipient;
class UnitDisplayStatusBarControl;
class WalletController;
class WalletFrame;
class WalletModel;
class HelpMessageDialog;
class ModalOverlay;
namespace interfaces {
class Handler;
class Node;
}
QT_BEGIN_NAMESPACE
class QAction;
class QComboBox;
class QMenu;
class QProgressBar;
class QProgressDialog;
QT_END_NAMESPACE
namespace GUIUtil {
class ClickableLabel;
class ClickableProgressBar;
}
/*
比特币GUI主类。此类表示比特币用户界面的主窗口。它与客户机和
钱包模型,为用户提供当前核心状态的最新视图。
**/
class BitcoinGUI : public QMainWindow
{
Q_OBJECT
public:
static const std::string DEFAULT_UIPLATFORM;
explicit BitcoinGUI(interfaces::Node& node, const PlatformStyle *platformStyle, const NetworkStyle *networkStyle, QWidget *parent = nullptr);
~BitcoinGUI();
/*设置客户端模型。
客户机模型代表了与P2P网络通信的核心部分,并且与钱包无关。
**/
void setClientModel(ClientModel *clientModel);
#ifdef ENABLE_WALLET
void setWalletController(WalletController* wallet_controller);
#endif
#ifdef ENABLE_WALLET
/*设置钱包模型。
钱包模型代表比特币钱包,提供对交易列表、通讯簿和发送的访问。
功能。
**/
void addWallet(WalletModel* walletModel);
void removeWallet(WalletModel* walletModel);
void removeAllWallets();
#endif //允许钱包
bool enableWallet = false;
/*获取托盘图标状态。
有些系统没有“系统托盘”或“通知区域”可用。
**/
bool hasTrayIcon() const { return trayIcon; }
protected:
void changeEvent(QEvent *e);
void closeEvent(QCloseEvent *event);
void showEvent(QShowEvent *event);
void dragEnterEvent(QDragEnterEvent *event);
void dropEvent(QDropEvent *event);
bool eventFilter(QObject *object, QEvent *event);
private:
interfaces::Node& m_node;
WalletController* m_wallet_controller{nullptr};
std::unique_ptr<interfaces::Handler> m_handler_message_box;
std::unique_ptr<interfaces::Handler> m_handler_question;
ClientModel* clientModel = nullptr;
WalletFrame* walletFrame = nullptr;
UnitDisplayStatusBarControl* unitDisplayControl = nullptr;
QLabel* labelWalletEncryptionIcon = nullptr;
QLabel* labelWalletHDStatusIcon = nullptr;
GUIUtil::ClickableLabel* labelProxyIcon = nullptr;
GUIUtil::ClickableLabel* connectionsControl = nullptr;
GUIUtil::ClickableLabel* labelBlocksIcon = nullptr;
QLabel* progressBarLabel = nullptr;
GUIUtil::ClickableProgressBar* progressBar = nullptr;
QProgressDialog* progressDialog = nullptr;
QMenuBar* appMenuBar = nullptr;
QToolBar* appToolBar = nullptr;
QAction* overviewAction = nullptr;
QAction* historyAction = nullptr;
QAction* quitAction = nullptr;
QAction* sendCoinsAction = nullptr;
QAction* sendCoinsMenuAction = nullptr;
QAction* usedSendingAddressesAction = nullptr;
QAction* usedReceivingAddressesAction = nullptr;
QAction* signMessageAction = nullptr;
QAction* verifyMessageAction = nullptr;
QAction* aboutAction = nullptr;
QAction* receiveCoinsAction = nullptr;
QAction* receiveCoinsMenuAction = nullptr;
QAction* optionsAction = nullptr;
QAction* toggleHideAction = nullptr;
QAction* encryptWalletAction = nullptr;
QAction* backupWalletAction = nullptr;
QAction* changePassphraseAction = nullptr;
QAction* aboutQtAction = nullptr;
QAction* openRPCConsoleAction = nullptr;
QAction* openAction = nullptr;
QAction* showHelpMessageAction = nullptr;
QAction* m_wallet_selector_label_action = nullptr;
QAction* m_wallet_selector_action = nullptr;
QLabel *m_wallet_selector_label = nullptr;
QComboBox* m_wallet_selector = nullptr;
QSystemTrayIcon* trayIcon = nullptr;
const std::unique_ptr<QMenu> trayIconMenu;
Notificator* notificator = nullptr;
RPCConsole* rpcConsole = nullptr;
HelpMessageDialog* helpMessageDialog = nullptr;
ModalOverlay* modalOverlay = nullptr;
#ifdef Q_OS_MAC
CAppNapInhibitor* m_app_nap_inhibitor = nullptr;
#endif
/*跟踪以前的块数,以检测进度*/
int prevBlocks = 0;
int spinnerFrame = 0;
const PlatformStyle *platformStyle;
const NetworkStyle* const m_network_style;
/*创建主UI操作。*/
void createActions();
/*创建菜单栏和子菜单。*/
void createMenuBar();
/*创建工具栏*/
void createToolBars();
/*创建系统托盘图标和通知*/
void createTrayIcon();
/*创建系统托盘菜单(或设置停靠菜单)*/
void createTrayIconMenu();
/*启用或禁用所有与钱包相关的操作*/
void setWalletActionsEnabled(bool enabled);
/*将核心信号连接到GUI客户端*/
void subscribeToCoreSignals();
/*从GUI客户端断开核心信号*/
void unsubscribeFromCoreSignals();
/*使用模型中的最新网络信息更新用户界面。*/
void updateNetworkState();
void updateHeadersSyncProgressLabel();
/*打开指定选项卡索引上的选项对话框*/
void openOptionsDialogWithTab(OptionsDialog::Tab tab);
Q_SIGNALS:
/*输入或拖动到GUI时引发的信号*/
void receivedURI(const QString &uri);
/*显示RPC控制台时引发的信号*/
void consoleShown(RPCConsole* console);
public Q_SLOTS:
/*设置用户界面中显示的连接数*/
void setNumConnections(int count);
/*设置用户界面中显示的网络状态*/
void setNetworkActive(bool networkActive);
/*设置用户界面中显示的块数和最后一个块日期*/
void setNumBlocks(int count, const QDateTime& blockDate, double nVerificationProgress, bool headers);
/*从核心网络或事务处理代码通知用户事件。
@param[in]标题消息框/通知标题
@param[in]消息显示的文本
@param[in]样式形式和样式定义(图标和使用的按钮-仅用于消息框的按钮)
@请参见cclientuiinterface::messageboxflags
@param[in]ret指向bool的指针,该bool将被修改为是否单击了OK(仅限模式)
**/
void message(const QString &title, const QString &message, unsigned int style, bool *ret = nullptr);
#ifdef ENABLE_WALLET
void setCurrentWallet(WalletModel* wallet_model);
void setCurrentWalletBySelectorIndex(int index);
/*根据当前选定的钱包设置用户界面状态指示器。
**/
void updateWalletStatus();
private:
/*设置加密状态,如用户界面所示。
@param[in]状态当前加密状态
@参见walletmodel::encryptionstatus
**/
void setEncryptionStatus(int status);
/*设置HD启用状态,如用户界面所示。
@param[in]hd启用当前hd启用状态
@参见walletmodel::encryptionstatus
**/
void setHDStatus(bool privkeyDisabled, int hdEnabled);
public Q_SLOTS:
bool handlePaymentRequest(const SendCoinsRecipient& recipient);
/*显示新事务的传入事务通知。*/
void incomingTransaction(const QString& date, int unit, const CAmount& amount, const QString& type, const QString& address, const QString& label, const QString& walletName);
#endif //允许钱包
private:
/*设置代理启用图标,如用户界面中所示。*/
void updateProxyIcon();
void updateWindowTitle();
public Q_SLOTS:
#ifdef ENABLE_WALLET
/*切换到概述(主页)页*/
void gotoOverviewPage();
/*切换到历史记录(事务)页*/
void gotoHistoryPage();
/*切换到接收硬币页面*/
void gotoReceiveCoinsPage();
/*切换到发送硬币页面*/
void gotoSendCoinsPage(QString addr = "");
/*显示签名/验证消息对话框并切换到签名消息选项卡*/
void gotoSignMessageTab(QString addr = "");
/*显示签名/验证消息对话框并切换到验证消息选项卡*/
void gotoVerifyMessageTab(QString addr = "");
/*显示打开的对话框*/
void openClicked();
#endif //允许钱包
/*显示配置对话框*/
void optionsClicked();
/*显示关于对话框*/
void aboutClicked();
/*显示调试窗口*/
void showDebugWindow();
/*显示调试窗口并将焦点设置到控制台*/
void showDebugWindowActivateConsole();
/*显示帮助消息对话框*/
void showHelpMessageClicked();
#ifndef Q_OS_MAC
/*已单击句柄托盘图标*/
void trayIconActivated(QSystemTrayIcon::ActivationReason reason);
#else
/*已单击处理MacOS Dock图标*/
void macosDockIconActivated();
#endif
/*隐藏时显示窗口,最小化时取消最小化,隐藏时上升,或隐藏时显示,并且ftoggleHidden为真*/
void showNormalIfMinimized() { showNormalIfMinimized(false); }
void showNormalIfMinimized(bool fToggleHidden);
/*只需调用showNormalIFMinimized(true)在slot()宏中使用*/
void toggleHidden();
/*由计时器调用以检查是否已设置shutdownrequested()。*/
void detectShutdown();
/*显示进度对话框,例如用于VerifyChain*/
void showProgress(const QString &title, int nProgress);
/*当在选项中更改hidetrayicon设置时,隐藏或显示相应的图标。*/
void setTrayIconVisible(bool);
void showModalOverlay();
};
class UnitDisplayStatusBarControl : public QLabel
{
Q_OBJECT
public:
explicit UnitDisplayStatusBarControl(const PlatformStyle *platformStyle);
/*让控件知道选项模型(及其信号)*/
void setOptionsModel(OptionsModel *optionsModel);
protected:
/*以便它响应左键单击*/
void mousePressEvent(QMouseEvent *event);
private:
OptionsModel *optionsModel;
QMenu* menu;
/*按鼠标坐标显示带有显示单位选项的上下文菜单*/
void onDisplayUnitsClicked(const QPoint& point);
/*创建上下文菜单及其操作,并连接鼠标事件的所有相关信号。*/
void createContextMenu();
private Q_SLOTS:
/*当选项“Model”上的显示单位发生更改时,它将刷新状态栏上控件的显示文本。*/
void updateDisplayUnit(int newUnits);
/*通知基础选项Model更新其当前显示单元。*/
void onMenuSelection(QAction* action);
};
#endif //比特币qt
| [
"openaichain"
] | openaichain |
f3bd6837f3d7e63414817e5a96d21a9adce47357 | 3692382ccf9cbfd5a48c2eead2315738325c6d5c | /Sources/LmUser.cpp | e0129f3db144a3f71225fcad9d2bc10329f9d747 | [] | no_license | ludomuse/cocos-sources | fdb5f93a5c8f681ad2973526258b7ab5e388d19b | dd5fd8b006114de9251724f6bb9c80e3ba0d1603 | refs/heads/master | 2021-01-10T07:36:49.166230 | 2015-10-08T14:41:49 | 2015-10-08T14:41:49 | 43,686,286 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 359 | cpp | /*
* LmUser.cpp
*
* Created on: 9 sept. 2015
* Author: IHMTEKDev4
*/
#include "../Include/LmUser.h"
LmUser::LmUser()
{
//primitive type
m_iScore = 0;
m_bMale = true;
//pointer
m_pUserName = nullptr;
m_pUserTabletName = nullptr;
m_bParent=nullptr;
}
LmUser::~LmUser()
{
}
void LmUser::addToScore(int points)
{
m_iScore += points;
}
| [
"[email protected]"
] | |
1db43227cb54fb1d0a0b43e7ff22b382cd468d9e | ebeade2609e56126da910684fd41085b85f981d3 | /Src/MarchingCubesGenerateConstantBufferVS.h | 147d76af65c5b138d01ec558f21c0b4a5b8105f2 | [] | no_license | patrickjamescarr/DirectX_Engine | 3364e3d68dffd9365cc781d1246038f242ad4044 | bf98fcb8708658e462eaa00e8e5f5c03a035cf49 | refs/heads/main | 2023-08-15T17:52:27.860256 | 2021-10-08T12:18:11 | 2021-10-08T12:18:11 | 345,572,176 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 704 | h | #pragma once
#include "Bindable.h"
#include "VertexConstantBuffer.h"
class MarchingCubesGenerateConstantBufferVS :
public Bindable
{
private:
// Buffer to store the cube variables
// x val contains cube scale
// y val contains cube dimentions
struct CubeBufferType
{
DirectX::XMFLOAT4 cubeVariables;
};
public:
MarchingCubesGenerateConstantBufferVS(DX::DeviceResources& deviceResources, const int* dimention, const float* scale, UINT slot = 0);
void Bind(DX::DeviceResources& deviceResources) noexcept override;
private:
std::unique_ptr<VertexConstantBuffer<CubeBufferType>> m_vertexConstantBuffer;
const float* m_scale;
const int* m_dimention;
}; | [
"[email protected]"
] | |
d55cf65872b480fbef7667b7227600ca89dc73b8 | 636394fc4967123179dd2dc935f437e735c6d38a | /export/windows/obj/include/openfl/utils/_Object/Object_Impl_.h | bd37b2c5edfd6aa5032dfa93a2e2eb8e695b90dd | [
"MIT"
] | permissive | arturspon/zombie-killer | 865e6ef3bdb47408f9bfea9016f61bf19b2559c7 | 07848c5006916e9079537a3d703ffe3740afaa5a | refs/heads/master | 2021-07-18T16:44:26.556092 | 2019-05-04T13:56:08 | 2019-05-04T13:56:08 | 181,805,463 | 0 | 1 | MIT | 2021-07-16T23:18:46 | 2019-04-17T02:50:10 | C++ | UTF-8 | C++ | false | true | 2,851 | h | // Generated by Haxe 4.0.0-rc.2+77068e10c
#ifndef INCLUDED_openfl_utils__Object_Object_Impl_
#define INCLUDED_openfl_utils__Object_Object_Impl_
#ifndef HXCPP_H
#include <hxcpp.h>
#endif
HX_DECLARE_CLASS3(openfl,utils,_Object,Object_Impl_)
namespace openfl{
namespace utils{
namespace _Object{
class HXCPP_CLASS_ATTRIBUTES Object_Impl__obj : public hx::Object
{
public:
typedef hx::Object super;
typedef Object_Impl__obj OBJ_;
Object_Impl__obj();
public:
enum { _hx_ClassId = 0x1e136e60 };
void __construct();
inline void *operator new(size_t inSize, bool inContainer=false,const char *inName="openfl.utils._Object.Object_Impl_")
{ return hx::Object::operator new(inSize,inContainer,inName); }
inline void *operator new(size_t inSize, int extra)
{ return hx::Object::operator new(inSize+extra,false,"openfl.utils._Object.Object_Impl_"); }
hx::ObjectPtr< Object_Impl__obj > __new() {
hx::ObjectPtr< Object_Impl__obj > __this = new Object_Impl__obj();
__this->__construct();
return __this;
}
static hx::ObjectPtr< Object_Impl__obj > __alloc(hx::Ctx *_hx_ctx) {
Object_Impl__obj *__this = (Object_Impl__obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(Object_Impl__obj), false, "openfl.utils._Object.Object_Impl_"));
*(void **)__this = Object_Impl__obj::_hx_vtable;
return __this;
}
static void * _hx_vtable;
static Dynamic __CreateEmpty();
static Dynamic __Create(hx::DynamicArray inArgs);
//~Object_Impl__obj();
HX_DO_RTTI_ALL;
static bool __GetStatic(const ::String &inString, Dynamic &outValue, hx::PropertyAccess inCallProp);
static void __register();
bool _hx_isInstanceOf(int inClassId);
::String __ToString() const { return HX_("Object_Impl_",bf,20,11,ba); }
static void __boot();
static ::Dynamic __meta__;
static ::Dynamic _new();
static ::Dynamic _new_dyn();
static bool hasOwnProperty( ::Dynamic this1,::String name);
static ::Dynamic hasOwnProperty_dyn();
static bool isPrototypeOf( ::Dynamic this1,hx::Class theClass);
static ::Dynamic isPrototypeOf_dyn();
static ::Dynamic iterator( ::Dynamic this1);
static ::Dynamic iterator_dyn();
static bool propertyIsEnumerable( ::Dynamic this1,::String name);
static ::Dynamic propertyIsEnumerable_dyn();
static ::String toLocaleString( ::Dynamic this1);
static ::Dynamic toLocaleString_dyn();
static ::String toString( ::Dynamic this1);
static ::Dynamic toString_dyn();
static ::Dynamic valueOf( ::Dynamic this1);
static ::Dynamic valueOf_dyn();
static ::Dynamic __get( ::Dynamic this1,::String key);
static ::Dynamic __get_dyn();
static ::Dynamic __set( ::Dynamic this1,::String key, ::Dynamic value);
static ::Dynamic __set_dyn();
};
} // end namespace openfl
} // end namespace utils
} // end namespace _Object
#endif /* INCLUDED_openfl_utils__Object_Object_Impl_ */
| [
"[email protected]"
] | |
ae8d4ba32ead01ca2f11dbfbc118050e97acc5df | 06d59d8a0f8065283b1903bcb2d530a397ecde14 | /node/src/node/app.cpp | da90a687cd127b686352f8d520b428315728c1d3 | [] | no_license | Alukardd/cocaine-plugins | d2c8b353e4f5c4a7865cdfe830a7b4d29d67cbb1 | 5609c49600fe5fc9b9033b06bb184884c52455cb | refs/heads/master | 2020-12-11T03:21:43.161559 | 2015-10-09T08:48:24 | 2015-10-09T08:48:24 | 44,396,547 | 0 | 0 | null | 2015-10-16T16:14:27 | 2015-10-16T16:14:27 | null | UTF-8 | C++ | false | false | 16,482 | cpp | #include "cocaine/detail/service/node/app.hpp"
#include "cocaine/api/isolate.hpp"
#include "cocaine/context.hpp"
#include "cocaine/errors.hpp"
#include "cocaine/idl/node.hpp"
#include "cocaine/locked_ptr.hpp"
#include "cocaine/rpc/actor.hpp"
#include "cocaine/rpc/actor_unix.hpp"
#include "cocaine/traits/dynamic.hpp"
#include "cocaine/detail/service/node/dispatch/client.hpp"
#include "cocaine/detail/service/node/dispatch/handshaker.hpp"
#include "cocaine/detail/service/node/dispatch/hostess.hpp"
#include "cocaine/detail/service/node/manifest.hpp"
#include "cocaine/detail/service/node/overseer.hpp"
#include "cocaine/detail/service/node/profile.hpp"
namespace ph = std::placeholders;
using namespace cocaine;
using namespace cocaine::service;
using namespace cocaine::service::node;
struct overseer_proxy_t {
std::shared_ptr<overseer_t> o;
explicit
overseer_proxy_t(std::shared_ptr<overseer_t> o):
o(std::move(o))
{}
};
// While the client is connected it's okay, balance on numbers depending on received.
class control_slot_t:
public io::basic_slot<io::app::control>
{
struct controlling_slot_t:
public io::basic_slot<io::app::control>::dispatch_type
{
typedef io::basic_slot<io::app::control>::dispatch_type super;
typedef io::event_traits<io::app::control>::dispatch_type dispatch_type;
typedef io::protocol<dispatch_type>::scope protocol;
control_slot_t* p;
controlling_slot_t(control_slot_t* p_):
super("controlling"),
p(p_)
{
on<protocol::chunk>([&](int size) {
if (auto overseer = p->overseer.lock()) {
overseer->o->keep_alive(size);
}
});
p->locked.store(true);
}
~controlling_slot_t() {
p->locked.store(false);
}
virtual
void
discard(const std::error_code&) const {
COCAINE_LOG_DEBUG(p->log, "client has been disappeared, assuming direct control");
if (auto overseer = p->overseer.lock()) {
overseer->o->keep_alive(0);
}
}
};
typedef std::shared_ptr<const io::basic_slot<io::app::control>::dispatch_type> result_type;
const std::unique_ptr<logging::log_t> log;
std::atomic<bool> locked;
std::weak_ptr<overseer_proxy_t> overseer;
public:
control_slot_t(std::shared_ptr<overseer_proxy_t> overseer_, std::unique_ptr<logging::log_t> log_):
log(std::move(log_)),
locked(false),
overseer(overseer_)
{
COCAINE_LOG_DEBUG(log, "control slot has been created");
}
~control_slot_t() {
COCAINE_LOG_DEBUG(log, "control slot has been destroyed");
}
boost::optional<result_type>
operator()(tuple_type&& args, upstream_type&& upstream) {
typedef io::protocol<io::event_traits<io::app::control>::upstream_type>::scope protocol;
const auto dispatch = tuple::invoke(std::move(args), [&]() -> result_type {
if (locked) {
upstream.send<protocol::error>(std::make_error_code(std::errc::resource_unavailable_try_again));
return nullptr;
}
return std::make_shared<controlling_slot_t>(this);
});
return boost::make_optional(dispatch);
}
};
/// App dispatch, manages incoming enqueue requests. Adds them to the queue.
///
/// \note lives until at least one connection left after actor has been destroyed.
class app_dispatch_t:
public dispatch<io::app_tag>
{
typedef io::streaming_slot<io::app::enqueue> slot_type;
const std::unique_ptr<logging::log_t> log;
// Yes, weak pointer here indicates about application destruction.
std::weak_ptr<overseer_proxy_t> overseer;
public:
app_dispatch_t(context_t& context, const std::string& name, std::shared_ptr<overseer_proxy_t> overseer_) :
dispatch<io::app_tag>(name),
log(context.log(format("%s/dispatch", name))),
overseer(overseer_)
{
on<io::app::enqueue>(std::make_shared<slot_type>(
std::bind(&app_dispatch_t::on_enqueue, this, ph::_1, ph::_2, ph::_3)
));
on<io::app::info>(std::bind(&app_dispatch_t::on_info, this));
on<io::app::control>(std::make_shared<control_slot_t>(overseer_, context.log(format("%s/control", name))));
}
~app_dispatch_t() {
COCAINE_LOG_DEBUG(log, "app dispatch has been destroyed");
}
private:
std::shared_ptr<const slot_type::dispatch_type>
on_enqueue(slot_type::upstream_type&& upstream , const std::string& event, const std::string& id) {
COCAINE_LOG_DEBUG(log, "processing enqueue '%s' event", event);
typedef io::protocol<io::event_traits<io::app::enqueue>::dispatch_type>::scope protocol;
try {
if (auto overseer = this->overseer.lock()) {
if (id.empty()) {
return overseer->o->enqueue(upstream, event, boost::none);
} else {
return overseer->o->enqueue(upstream, event, service::node::slave::id_t(id));
}
} else {
// We shouldn't close the connection here, because there possibly can be events
// processing.
throw std::system_error(std::make_error_code(std::errc::broken_pipe), "the application has been stopped");
}
} catch (const std::system_error& err) {
COCAINE_LOG_ERROR(log, "unable to enqueue '%s' event: %s", event, err.what());
upstream.send<protocol::error>(err.code(), err.what());
}
return std::make_shared<client_rpc_dispatch_t>(name());
}
dynamic_t
on_info() const {
if (auto overseer = this->overseer.lock()) {
// TODO: Forward flags.
io::node::info::flags_t flags;
flags = static_cast<io::node::info::flags_t>(
io::node::info::overseer_report);
return overseer->o->info(flags);
}
throw std::system_error(std::make_error_code(std::errc::broken_pipe), "the application has been stopped");
}
};
/// \note originally there was `boost::variant`, but in 1.46 it has no idea about move-only types.
namespace state {
class base_t {
public:
virtual
~base_t() {}
virtual
bool
stopped() noexcept {
return false;
}
virtual
dynamic_t::object_t
info(io::node::info::flags_t flags) const = 0;
};
/// The application is stopped either normally or abnormally.
class stopped_t:
public base_t
{
std::error_code ec;
public:
stopped_t() noexcept {}
explicit
stopped_t(std::error_code ec) noexcept:
ec(std::move(ec))
{}
virtual
bool
stopped() noexcept {
return true;
}
virtual
dynamic_t::object_t
info(io::node::info::flags_t) const {
dynamic_t::object_t info;
info["state"] = ec ? std::string("broken") : "stopped";
info["error"] = ec.value();
info["cause"] = ec ? ec.message() : "manually stopped";
return info;
}
};
/// The application is currently spooling.
class spooling_t:
public base_t
{
std::shared_ptr<api::isolate_t> isolate;
std::unique_ptr<api::cancellation_t> spooler;
public:
template<class F>
spooling_t(context_t& context,
asio::io_service& loop,
const manifest_t& manifest,
const profile_t& profile,
const logging::log_t* log,
F handler)
{
isolate = context.get<api::isolate_t>(
profile.isolate.type,
context,
loop,
manifest.name,
profile.isolate.args
);
try {
// NOTE: Regardless of whether the asynchronous operation completes immediately or not,
// the handler will not be invoked from within this call. Invocation of the handler
// will be performed in a manner equivalent to using `boost::asio::io_service::post()`.
spooler = isolate->async_spool(handler);
} catch (const std::system_error& err) {
COCAINE_LOG_ERROR(log, "uncaught spool exception: [%d] %s", err.code().value(), err.code().message());
handler(err.code());
} catch (const std::exception& err) {
COCAINE_LOG_ERROR(log, "uncaught spool exception: %s", err.what());
handler(error::uncaught_spool_error);
}
}
~spooling_t() {
if (spooler) {
spooler->cancel();
}
}
virtual
dynamic_t::object_t
info(io::node::info::flags_t) const {
dynamic_t::object_t info;
info["state"] = "spooling";
return info;
}
};
/// The application has been published and currently running.
class running_t:
public base_t
{
const logging::log_t* log;
context_t& context;
std::string name;
std::unique_ptr<unix_actor_t> engine;
std::shared_ptr<overseer_proxy_t> overseer;
public:
running_t(context_t& context_,
const manifest_t& manifest,
const profile_t& profile,
const logging::log_t* log,
std::shared_ptr<asio::io_service> loop):
log(log),
context(context_),
name(manifest.name)
{
// Create the Overseer - slave spawner/despawner plus the event queue dispatcher.
overseer = std::make_shared<overseer_proxy_t>(
std::make_shared<overseer_t>(context, manifest, profile, loop)
);
// Create a TCP server and publish it.
COCAINE_LOG_DEBUG(log, "publishing application service with the context");
context.insert(manifest.name, std::make_unique<actor_t>(
context,
std::make_shared<asio::io_service>(),
std::make_unique<app_dispatch_t>(context, manifest.name, overseer)
));
// Create an unix actor and bind to {manifest->name}.{pid} unix-socket.
COCAINE_LOG_DEBUG(log, "publishing worker service with the context");
engine.reset(new unix_actor_t(
context,
manifest.endpoint,
std::bind(&overseer_t::prototype, overseer->o),
[](io::dispatch_ptr_t handshaker, std::shared_ptr<session_t> session) {
std::static_pointer_cast<const handshaker_t>(handshaker)->bind(session);
},
std::make_shared<asio::io_service>(),
std::make_unique<hostess_t>(manifest.name)
));
engine->run();
}
~running_t() {
COCAINE_LOG_DEBUG(log, "removing application service from the context");
try {
// NOTE: It can throw if someone has removed the service from the context, it's valid.
//
// Moreover if the context was unable to bootstrap itself it removes all services from
// the service list (including child services). It can be that this app has been removed
// earlier during bootstrap failure.
context.remove(name);
} catch (const std::exception& err) {
COCAINE_LOG_WARNING(log, "unable to remove application service from the context: %s", err.what());
}
engine->terminate();
overseer->o->cancel();
}
virtual
dynamic_t::object_t
info(io::node::info::flags_t flags) const {
dynamic_t::object_t info;
if (is_overseer_report_required(flags)) {
info = overseer->o->info(flags);
} else {
info["uptime"] = overseer->o->uptime().count();
}
info["state"] = "running";
return info;
}
private:
static
bool
is_overseer_report_required(io::node::info::flags_t flags) {
return flags & io::node::info::overseer_report;
}
};
} // namespace state
class cocaine::service::node::app_state_t:
public std::enable_shared_from_this<app_state_t>
{
const std::unique_ptr<logging::log_t> log;
context_t& context;
typedef std::unique_ptr<state::base_t> state_type;
synchronized<state_type> state;
/// Node start request's deferred.
cocaine::deferred<void> deferred;
// Configuration.
const manifest_t manifest_;
const profile_t profile;
std::shared_ptr<asio::io_service> loop;
std::unique_ptr<asio::io_service::work> work;
boost::thread thread;
public:
app_state_t(context_t& context,
manifest_t manifest_,
profile_t profile_,
cocaine::deferred<void> deferred_):
log(context.log(format("%s/app", manifest_.name))),
context(context),
state(new state::stopped_t),
deferred(std::move(deferred_)),
manifest_(std::move(manifest_)),
profile(std::move(profile_)),
loop(std::make_shared<asio::io_service>()),
work(std::make_unique<asio::io_service::work>(*loop))
{
COCAINE_LOG_DEBUG(log, "application has initialized its internal state");
thread = boost::thread([=] {
loop->run();
});
}
~app_state_t() {
COCAINE_LOG_DEBUG(log, "application is destroying its internal state");
work.reset();
thread.join();
COCAINE_LOG_DEBUG(log, "application has destroyed its internal state");
}
const manifest_t&
manifest() const noexcept {
return manifest_;
}
dynamic_t
info(io::node::info::flags_t flags) const {
return (*state.synchronize())->info(flags);
}
void
spool() {
state.apply([&](state_type& state) {
if (!state->stopped()) {
throw std::logic_error("invalid state");
}
COCAINE_LOG_DEBUG(log, "app is spooling");
state.reset(new state::spooling_t(
context,
*loop,
manifest(),
profile,
log.get(),
std::bind(&app_state_t::on_spool, shared_from_this(), ph::_1)
));
});
}
void
cancel(std::error_code ec) {
state.synchronize()->reset(new state::stopped_t(std::move(ec)));
}
private:
void
on_spool(const std::error_code& ec) {
if (ec) {
COCAINE_LOG_ERROR(log, "unable to spool app - [%d] %s", ec.value(), ec.message());
loop->dispatch(std::bind(&app_state_t::cancel, shared_from_this(), ec));
// Attempt to finish node service's request.
try {
deferred.abort(ec, ec.message());
} catch (const std::exception&) {
// Ignore if the client has been disconnected.
}
} else {
// Dispatch the completion handler to be sure it will be called in a I/O thread to
// avoid possible deadlocks.
loop->dispatch(std::bind(&app_state_t::publish, shared_from_this()));
}
}
void
publish() {
std::error_code ec;
try {
state.synchronize()->reset(
new state::running_t(context, manifest(), profile, log.get(), loop)
);
} catch (const std::system_error& err) {
COCAINE_LOG_ERROR(log, "unable to publish app: [%d] %s", err.code().value(), err.code().message());
ec = err.code();
} catch (const std::exception& err) {
COCAINE_LOG_ERROR(log, "unable to publish app: %s", err.what());
ec = error::uncaught_publish_error;
}
// Attempt to finish node service's request.
try {
if (ec) {
cancel(ec);
deferred.abort(ec, ec.message());
} else {
deferred.close();
}
} catch (const std::exception&) {
// Ignore if the client has been disconnected.
}
}
};
app_t::app_t(context_t& context,
const std::string& manifest,
const std::string& profile,
cocaine::deferred<void> deferred):
state(std::make_shared<app_state_t>(context, manifest_t(context, manifest), profile_t(context, profile), deferred))
{
state->spool();
}
app_t::~app_t() {
state->cancel(std::error_code());
}
std::string
app_t::name() const {
return state->manifest().name;
}
dynamic_t
app_t::info(io::node::info::flags_t flags) const {
return state->info(flags);
}
| [
"[email protected]"
] | |
c30431f9fa2cf9362a45a69860edfcaa107bda60 | ec1b2269bb146495c1bf097becc371ebe49501ed | /vm_op.cpp | a34a8ed67972391f7c1c9314345f5414c3efe585 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | yang123vc/rusalka-vm | 5423ac83b85a3716a68a13dad36e63b3de5733d5 | 6fbfd2a8ef7f190539a323f983272844680dc0ac | refs/heads/master | 2020-07-02T16:00:50.525390 | 2014-12-15T07:41:44 | 2014-12-15T07:41:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 579 | cpp | /*
* Copyright Noel Cower 2014.
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*/
#include "vm_op.h"
#include "vm_unit.h"
vm_opcode vm_op::opcode() const
{
return unit.instructions[ip].opcode;
}
vm_value vm_op::operator [] (int64_t index) const
{
int32_t argv_base = unit.instructions[ip].arg_pointer;
return unit.instruction_argv[argv_base + index];
}
uint64_t vm_op::litflag() const
{
return unit.instructions[ip].litflag;
}
| [
"[email protected]"
] | |
022e90d2390f166adcb2f2db1cd3e58da7cdd611 | 716da7c52fa7fa81e0013c33061b6c43a92957de | /Lexer.cpp | 97925c734f88136bdc29b5954f4da018daeb0bcc | [] | no_license | TamirKar/ProjOne | 2188e75b70ef2cbe6920b7ecba451537525a8800 | 72f438966e6e2e1b45797f6c949fb63814bc5877 | refs/heads/master | 2020-04-13T16:23:33.788159 | 2018-12-27T17:22:39 | 2018-12-27T17:22:39 | 163,319,849 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,536 | cpp |
#include <sstream>
#include "Lexer.h"
#include <algorithm>
#include "StringUtilis.h"
/**
* Lexer
* @param fileName fileName
* @return vector<vector<string>>
*/
vector<vector<string>> Lexer::GetFileLines(const char *fileName) {
vector<vector<string>> vec;
string line;
ifstream infile;
infile.open(fileName);
//lines are splitted by /n and then added to a vector of strings.
while (!infile.eof()) {
getline(infile, line);
if (line.size() != 0) {
//remove additional '\' for the bind command
if (line.find("bind") != std::string::npos) {
line = StringUtilis::CharRemoverStr(line, '\"');
}
//add spaces for equal operator.
if (line.find('=') != std::string::npos
&& !(line.find("==") != std::string::npos
|| line.find("!=") != std::string::npos
|| line.find(">=") != std::string::npos
|| line.find("<=") != std::string::npos)) {
int i = line.find("=");
string str1 = line.substr(0, i);
string str2 = line.substr(i+1, line.size());
line = str1 + " = " + str2;
}
//remove any ','
line = StringUtilis::CharRemoverStr(line, ',');
//remove spaces and add to vector.
vector<string> v = StringUtilis::CharRemover(line, ' ');
vec.push_back(v);
}
}
infile.close();
return vec;
}
| [
"[email protected]"
] | |
832c9a7b0ea44c50d3726150b8218ca329c45d61 | bcb569fb7eefce77ef4f31bca0cfa73029298ae0 | /banco/GameServer/trunk/src/admin/GetFreePlayer.cpp | 62926f39f4e5f0d774c27bf5433f48818f1b5758 | [] | no_license | xubingyue/GP | e3b3f69b3d412057933ca32e61a57005ab19df80 | 7b0e7b48c1389e39aafb83a7337723400f18ada5 | refs/heads/master | 2020-09-15T01:32:03.539712 | 2018-07-18T10:46:19 | 2018-07-18T10:46:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 477 | cpp | #include "GetFreePlayer.h"
#include "ProtocolServerId.h"
#include "Room.h"
#include "Logger.h"
#include "ProcessManager.h"
int GetFreePlayer::doRequest(CDLSocketHandler* clientHandler, InputPacket* inputPacket,Context* pt )
{
short cmd = inputPacket->GetCmdType();
if(Room::getInstance()->getStatus()==-1)
{
return sendErrorMsg(clientHandler, cmd, 0, -1, "room.Status=-1, Server Wait For Stop") ;
}
return 0;
}
REGISTER_PROCESS(ADMIN_GET_FREE_PLAYER, GetFreePlayer)
| [
"[email protected]"
] | |
0f824835246cbc2a416398943bcaad3389295496 | 6cc1bd836cf5951770a77bf47f63afe127e39738 | /common/humanmachineinterface.cpp | 76bd805b7c1ec11f66b6e008c982d17bb5ef6118 | [] | no_license | jm-szlendak/scada_server | 32f08d34de1233dfb4936ce3b222121316463845 | 58a8a7ff25744402e41dff7405ccfe1d3eb4fe23 | refs/heads/master | 2021-05-28T18:53:15.527263 | 2015-05-22T22:03:03 | 2015-05-22T22:03:03 | 33,886,698 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,802 | cpp | #include "humanmachineinterface.h"
HumanMachineInterface::HumanMachineInterface()
{
}
HumanMachineInterface::~HumanMachineInterface()
{
}
bool HumanMachineInterface::initReceived(Packet *init)
{
this->uuid = init->getDeviceID();
QList<QString>* brief = init->getBriefData();
QList<double>* numeric = init->getNumericData();
if(brief->size() == 6)
{
name = brief->at(1);
factoryData = brief->at(3);
hmiBrief = brief->at(5);
return true;
}
return false;
}
bool HumanMachineInterface::dataReceived(Packet *data)
{
}
bool HumanMachineInterface::settingsReceived(Packet *settings)
{
if(settings->getNumericData()->empty())
return false;
foreach(double data, *(settings->getNumericData()))
{
wishList.append((deviceState_enum)data);
}
return true;
}
Packet HumanMachineInterface::getDataPacket()
{
}
Packet HumanMachineInterface::getInitPacket()
{
Packet packet;
packet.setPacketID(Packet::HMI_INIT);
packet.setDeviceID(this->uuid);
packet.addBriefData("name");
packet.addBriefData(name);
packet.addBriefData("factory_data");
packet.addBriefData(factoryData);
packet.addBriefData("hmi_brief");
packet.addBriefData(hmiBrief);
return packet;
}
Packet HumanMachineInterface::getSettingsPacket()
{
Packet packet;
packet.setPacketID(Packet::SETTINGS);
packet.setDeviceID(this->uuid);
foreach(int element, wishList)
{
packet.addNumericData(double(element));
}
return packet;
}
bool HumanMachineInterface::appendToWishlist(ScadaDevice* device)
{
for(size_t i; i<wishList.size();i++)
{
if(wishList[i]==device->getUUID())
return false;
}
wishList.append(device->getUUID());
return true;
}
| [
"[email protected]"
] | |
8ed67822228e2eb8d8800dc57c2d706c5c38f8d5 | 2aea9d967d8aa8ab1feba960edd9dd90975ebf33 | /parameterized actives/Parameterized Actives Approach/Instances/obr/lerDiretorioVetor.cpp | 7532f84a1d61773467c4de5090e5cb9faf822e20 | [
"MIT"
] | permissive | lcad9/job-shop-schedule-galib | a284518546ab3e92701d747fefa71a321b6fd629 | 66609581ff24c65aa4a165c08089e34ddcc803f3 | refs/heads/master | 2021-03-02T09:41:51.820553 | 2020-03-29T14:39:45 | 2020-03-29T14:39:45 | 245,856,773 | 1 | 1 | MIT | 2020-03-28T20:55:56 | 2020-03-08T17:22:10 | C | ISO-8859-1 | C++ | false | false | 2,721 | cpp | // ************************************************************
// Exemplo de leitura de uma instância de problemas especificos para job shop scheduling
// Este programa lê um arquivo texto e imprime o seu
// conteudo na tela.
// ************************************************************
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#include <vector>
#include <iostream>
#include <dirent.h>
using namespace std;
int main()
{
FILE *arq;
vector<int> maq;
vector<int> T;
char Linha[100];
char *result;
char *pch;
//////////////////////////////////////////////////////////////////////////////////////
//***********************Fim tratamento de excessões*********************************/
/////////////////////////////////////////////////////////////////////////////////////
//arq = fopen(diretorio[p-1].c_str(), "rt");
arq = fopen("orb03", "rt");
//i = 1;
int cont = 0; //Conta o número de linhas
while (!feof(arq))
{
// Lê uma linha (inclusive com o '\n')
result = fgets(Linha, 100, arq); // o 'fgets' lê até 99 caracteres ou até o '\n'
///Lê-se a partir da linha 3, por causa dos formatos
if(cont > 3){
if (result){
pch = strtok(Linha, " ");//Armazena o conteúdo da linha
while(pch != NULL)
{
maq.push_back(atoi(pch) + 1);//Armazena o número da máquina +1
pch = strtok(NULL, " ");
T.push_back(atoi(pch)); //Armazena o número do tempo
pch = strtok(NULL, " ");
}
}
}
cont++;
}
fclose(arq); //Fecha arquivo da instância do problema
int m = maq[0];
int t = T[0];
cout << m << " x " << t; //Demostra tamanho da instância do problema
int JT[m][t];//Matriz onde será armazenado o tempo, separado por máquina
for(int i = 0; i < m; i++)
for(int j = 0; j < t; j++){
JT[i][j] = T[(j + 1) + (i * t) ];
}
//////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
/*
** A partir daqui é somente exibição do conteúdo
*/
cout << "\n\n";
cout << "Maquina: ";
maq.erase(maq.begin());
T.erase(T.begin());
for(std::vector<int>::iterator it = maq.begin(); it != maq.end(); ++it)
cout << ' ' << *it;
cout << "\n\n";
cout << "Job: ";
for(std::vector<int>::iterator it = T.begin(); it != T.end(); ++it)
cout << ' ' << *it;
cout << "\n";
for(int i = 0; i < m; i++){
for(int j = 0; j < t; j++){
cout << JT[i][j];
cout << " ";
}
cout << "\n";
}
system("pause");
return 0;
}
| [
"[email protected]"
] | |
1ea8646f934e71cd917042fe46095a12ab86993d | 68b468b17d096e23c944b7009d5d9a10d3957dae | /src/bp/template_lib/tagescl.h | d34263e7c86b17fff681b5df7b28712071c90e6d | [
"MIT"
] | permissive | aniket-de/scarab | 5ff5bde9b2518d7390d49630afdaddba2c6adda3 | 43fa882cfef710e8984aa6a14fccb72453c84080 | refs/heads/master | 2021-02-05T19:23:42.885477 | 2020-09-27T18:51:22 | 2020-09-27T18:51:22 | 243,822,527 | 0 | 0 | MIT | 2020-09-27T18:51:23 | 2020-02-28T17:52:14 | C | UTF-8 | C++ | false | false | 11,353 | h | /* Copyright 2020 HPS/SAFARI Research Groups
*
* 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 "statistical_corrector.h"
#include "tage.h"
#include "tagescl_configs.h"
#include "utils.h"
template <class CONFIG>
struct Tage_SC_L_Prediction_Info {
Tage_Prediction_Info<typename CONFIG::TAGE> tage;
Loop_Prediction_Info<typename CONFIG::LOOP> loop;
bool tage_or_loop_prediction;
SC_Prediction_Info sc;
bool final_prediction;
};
/* Interface functions:
*
* warmup() a wrapper for updating predictor state during the warmup phase of a
* simulation.
*
* predict_and_update() a wrapper for consecutive simultaneous prediction and
* update that implement the idealistic algorithms without considering pipeline
* requirements. (same as Championship Branch Prediction Interface)
*/
template <class CONFIG>
class Tage_SC_L {
public:
Tage_SC_L(int max_in_flight_branches) :
tage_(random_number_gen_, max_in_flight_branches),
statistical_corrector_(), loop_predictor_(random_number_gen_),
loop_predictor_beneficial_(-1),
prediction_info_buffer_(max_in_flight_branches) {}
// Gets a new branch_id for a new in-flight branch. The id remains valid
// until
// the branch is retired or flushed. The class internally maintains metadata
// for each in-flight branch. The rest of the public functions in this class
// need the id of a branch to work on.
int64_t get_new_branch_id() {
int64_t branch_id = prediction_info_buffer_.allocate_back();
auto& prediction_info = prediction_info_buffer_[branch_id];
Tage<typename CONFIG::TAGE>::build_empty_prediction(&prediction_info.tage);
Loop_Predictor<typename CONFIG::LOOP>::build_empty_prediction(
&prediction_info.loop);
return branch_id;
}
// It uses the speculative state of the predictor to generate a prediction.
// Should be called before update_speculative_state.
bool get_prediction(int64_t branch_id, uint64_t br_pc);
// It updates the speculative state (e.g. to insert history bits in Tage's
// global history register). For conditional branches, it should be called
// after get_prediction() in the front-end of a pipeline. For unconditional
// branches, it should be the only function called in the front-end.
void update_speculative_state(int64_t branch_id, uint64_t br_pc,
Branch_Type br_type, bool branch_dir,
uint64_t br_target);
// Invokes the default update algorithm for updating the predictor state.
// Can
// be called either at the end of execute or retire. Note that even though
// updating at the end of execute is speculative, committing the state
// cannot
// be undone.
void commit_state(int64_t branch_id, uint64_t br_pc, Branch_Type br_type,
bool resolve_dir);
// Updates predictor states that are critical for algorithm correctness.
// Thus, should always be called in the retire state and after
// commit_state()
// is called. branch_id is invalidated and should not be used anymore.
void commit_state_at_retire(int64_t branch_id, uint64_t br_pc,
Branch_Type br_type, bool resolve_dir,
uint64_t br_target);
// Flushes the branch and all branches that came after it and repairs the
// speculative state of the predictor. It invalidated all branch_id of
// flushed
// branches.
void flush_branch_and_repair_state(int64_t branch_id, uint64_t br_pc,
Branch_Type br_type, bool resolve_dir,
uint64_t br_target);
private:
Random_Number_Generator random_number_gen_;
Tage<typename CONFIG::TAGE> tage_;
Statistical_Corrector<CONFIG> statistical_corrector_;
Loop_Predictor<typename CONFIG::LOOP> loop_predictor_;
// Counter for choosing between Tage and Loop Predictor.
Saturating_Counter<CONFIG::CONFIDENCE_COUNTER_WIDTH, true>
loop_predictor_beneficial_;
// Used for remembering necessary information gathered during prediction
// that
// are needed for update.
Circular_Buffer<Tage_SC_L_Prediction_Info<CONFIG>> prediction_info_buffer_;
};
template <class CONFIG>
bool Tage_SC_L<CONFIG>::get_prediction(int64_t branch_id, uint64_t br_pc) {
auto& prediction_info = prediction_info_buffer_[branch_id];
// First, use Tage to make a prediction.
tage_.get_prediction(br_pc, &prediction_info.tage);
prediction_info.tage_or_loop_prediction = prediction_info.tage.prediction;
if(CONFIG::USE_LOOP_PREDICTOR) {
// Then, look up the loop predictor and override Tage's prediction if
// the
// loop predictor is found to be beneficial.
loop_predictor_.get_prediction(br_pc, &prediction_info.loop);
if(loop_predictor_beneficial_.get() >= 0 && prediction_info.loop.valid) {
prediction_info.tage_or_loop_prediction = prediction_info.loop.prediction;
}
}
if(!CONFIG::USE_SC) {
prediction_info.final_prediction = prediction_info.tage_or_loop_prediction;
} else {
statistical_corrector_.get_prediction(
br_pc, prediction_info.tage, prediction_info.tage_or_loop_prediction,
&prediction_info.sc);
prediction_info.final_prediction = prediction_info.sc.prediction;
}
return prediction_info.final_prediction;
}
template <class CONFIG>
void Tage_SC_L<CONFIG>::commit_state(int64_t branch_id, uint64_t br_pc,
Branch_Type br_type, bool resolve_dir) {
if(!br_type.is_conditional) {
return;
}
auto& prediction_info = prediction_info_buffer_[branch_id];
if(CONFIG::USE_SC) {
statistical_corrector_.commit_state(
br_pc, resolve_dir, prediction_info.tage, prediction_info.sc,
prediction_info.tage_or_loop_prediction);
}
if(CONFIG::USE_LOOP_PREDICTOR) {
if(prediction_info.loop.valid) {
if(prediction_info.final_prediction != prediction_info.loop.prediction) {
loop_predictor_beneficial_.update(resolve_dir ==
prediction_info.loop.prediction);
}
}
loop_predictor_.commit_state(
br_pc, resolve_dir, prediction_info.loop,
prediction_info.final_prediction != resolve_dir,
prediction_info.tage.prediction);
loop_predictor_.commit_state_at_retire(
br_pc, resolve_dir, prediction_info.loop,
prediction_info.final_prediction != resolve_dir,
prediction_info.tage.prediction);
}
tage_.commit_state(br_pc, resolve_dir, prediction_info.tage,
prediction_info.final_prediction);
}
template <class CONFIG>
void Tage_SC_L<CONFIG>::flush_branch_and_repair_state(int64_t branch_id,
uint64_t br_pc,
Branch_Type br_type,
bool resolve_dir,
uint64_t br_target) {
// First iterate over all flushed branches from youngest to oldest and call
// local recovery functions.
for(int64_t id = prediction_info_buffer_.back_id(); id >= branch_id; --id) {
auto& prediction_info = prediction_info_buffer_[id];
tage_.local_recover_speculative_state(prediction_info.tage);
if(CONFIG::USE_LOOP_PREDICTOR) {
loop_predictor_.local_recover_speculative_state(prediction_info.loop);
}
if(CONFIG::USE_SC) {
statistical_corrector_.local_recover_speculative_state(
br_pc, prediction_info.sc);
}
}
prediction_info_buffer_.deallocate_after(branch_id);
// Now call global recovery functions.
auto& prediction_info = prediction_info_buffer_[branch_id];
tage_.global_recover_speculative_state(prediction_info.tage);
if(CONFIG::USE_LOOP_PREDICTOR) {
loop_predictor_.global_recover_speculative_state(prediction_info.loop);
}
if(CONFIG::USE_SC) {
statistical_corrector_.global_recover_speculative_state(prediction_info.sc);
}
// Finally, update the speculative histories again using the resolved
// direction of the branch.
tage_.update_speculative_state(br_pc, br_target, br_type, resolve_dir,
&prediction_info.tage);
if(CONFIG::USE_LOOP_PREDICTOR) {
loop_predictor_.update_speculative_state(prediction_info.loop);
}
if(CONFIG::USE_SC) {
statistical_corrector_.update_speculative_state(
br_pc, resolve_dir, br_target, br_type, &prediction_info.sc);
}
}
template <class CONFIG>
void Tage_SC_L<CONFIG>::commit_state_at_retire(int64_t branch_id,
uint64_t br_pc,
Branch_Type br_type,
bool resolve_dir,
uint64_t br_target) {
auto& prediction_info = prediction_info_buffer_[branch_id];
// if (CONFIG::USE_LOOP_PREDICTOR) {
// loop_predictor_.commit_state_at_retire(
// br_pc, resolve_dir, prediction_info.loop,
// prediction_info.final_prediction != resolve_dir,
// prediction_info.tage.prediction);
//}
tage_.commit_state_at_retire(prediction_info.tage);
if(CONFIG::USE_SC) {
statistical_corrector_.commit_state_at_retire();
}
prediction_info_buffer_.deallocate_front(branch_id);
}
template <class CONFIG>
void Tage_SC_L<CONFIG>::update_speculative_state(int64_t branch_id,
uint64_t br_pc,
Branch_Type br_type,
bool branch_dir,
uint64_t br_target) {
auto& prediction_info = prediction_info_buffer_[branch_id];
tage_.update_speculative_state(br_pc, br_target, br_type, branch_dir,
&prediction_info.tage);
if(CONFIG::USE_LOOP_PREDICTOR) {
loop_predictor_.update_speculative_state(prediction_info.loop);
}
if(CONFIG::USE_SC) {
statistical_corrector_.update_speculative_state(
br_pc, branch_dir, br_target, br_type, &prediction_info.sc);
}
}
| [
"[email protected]"
] | |
df892e0335f24d023055d00a7ea5bc517a519126 | 8924ec2a09ac595b30322f1638e2fc0d32c2ab4d | /Arduino/src/led_tester.cpp | 7e1c8af9958a04e90eeae06e2080677ed192eb2c | [] | no_license | Art2Geek/LEDController | 1a04889a83c37a5cf2d09b694cef8bf8756eb322 | caf211522873decf8d48f0c40f5b7c7d5a6ec99b | refs/heads/master | 2023-01-02T16:15:23.281761 | 2020-10-26T10:33:04 | 2020-10-26T10:33:04 | 307,081,595 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 871 | cpp | #include <Arduino.h>
#include <Adafruit_NeoPixel.h>
#define NUMPIXELS 16
#define LED_PIN 8
#define RED_PIN A0
#define GREEN_PIN A1
#define BLUE_PIN A2
byte redVal, greenVal, blueVal;
Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUMPIXELS, LED_PIN, NEO_GRB + NEO_KHZ800);
void setup() {
Serial.begin(9600);
strip.begin();
strip.setBrightness(100);
strip.show();
}
void loop() {
strip.clear();
redVal = map(analogRead(RED_PIN), 0, 1024, 0, 255);
greenVal = map(analogRead(GREEN_PIN), 0, 1024, 0, 255);
blueVal = map(analogRead(BLUE_PIN), 0, 1024, 0, 255);
strip.fill(strip.Color(redVal, greenVal, blueVal), 0, NUMPIXELS);
//strip.fill(strip.Color(redVal, greenVal, blueVal), 0, 1);
//strip.fill(strip.Color(255, 0, 0), 3, 1);
//strip.fill(strip.Color(0, 255, 0), 4, 1);
//strip.fill(strip.Color(0, 0, 255), 5, 1);
strip.show();
}
| [
"[email protected]"
] | |
59cf412f7866ddc101dd738b97d09d475329924a | 461473dbd2713ff19eed84e21b40438ef0512763 | /examples_openvdb/00_sample/main.cpp | ab70dde73d6e50d72789aa5d4a4404fb0199c291 | [
"MIT"
] | permissive | nobuyuki83/delfem2 | 7211c7eb3c59293c4bc92d285600d6404952dea8 | 104f3deb80e7501b3dd5eea0456d10c4e5095753 | refs/heads/master | 2022-11-13T21:46:13.926755 | 2022-11-06T06:38:04 | 2022-11-06T06:38:04 | 140,655,906 | 194 | 21 | MIT | 2022-11-06T06:38:06 | 2018-07-12T03:25:11 | C++ | UTF-8 | C++ | false | false | 722 | cpp | #include "openvdb/openvdb.h"
#include <openvdb/tools/LevelSetSphere.h>
// https://www.openvdb.org/documentation/doxygen/codeExamples.html#sAllocatingGrids
int main()
{
openvdb::initialize();
// Create a FloatGrid and populate it with a narrow-band
// signed distance field of a sphere.
openvdb::FloatGrid::Ptr grid =
openvdb::tools::createLevelSetSphere<openvdb::FloatGrid>(
50.0, openvdb::Vec3f(1.5, 2, 3),
0.5, 4.0);
// Associate some metadata with the grid.
grid->insertMeta("radius", openvdb::FloatMetadata(50.0));
// Name the grid "density".
grid->setName("density");
// Create a VDB file object and write out the grid.
openvdb::io::File("mygrids.vdb").write({grid});
} | [
"[email protected]"
] | |
722805d7223067f8c9db5ebfffe9848704bed21c | 17dd7156681d104c038a06c1f1d0f5a7102179b7 | /SFMLFallingSand/ButtonBase.h | afdcc97cfdfc3285f72b814018ba3e535d6d7855 | [] | no_license | ShahroozGh/SFMLFallingSand | 3d84af822a0e265ced38191523cbf6e2c9359cc9 | fffa485e426ccac1b40807c553a84c69f34551b0 | refs/heads/master | 2021-01-01T05:04:02.243396 | 2016-05-06T00:25:03 | 2016-05-06T00:25:03 | 57,453,329 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 605 | h | #pragma once
#include <SFML\Graphics.hpp>
class ButtonBase
{
public:
ButtonBase();
~ButtonBase();
void draw(sf::RenderWindow &targetWindow);
bool checkIfClicked(sf::Vector2f mouseCoords);
void setPosition(sf::Vector2f pos);
void setSize(sf::Vector2f newSize);
void setColor(sf::Color color);
void setSelectedColor(sf::Color color);
void setSelected(bool select);
sf::Vector2f getSize();
private:
sf::Vector2f position;
sf::Vector2f size;
sf::RectangleShape buttonRect;
sf::RectangleShape buttonBorder;
sf::Color buttonColor, selectedColor;
sf::Rect<float> hitBox;
bool selected;
};
| [
"[email protected]"
] | |
64c6e35bbb8047d64a4eb92835a4688e6904e240 | 52a3c93c38bef127eaee4420f36a89d929a321c5 | /SDK/SoT_BP_cls_shop_bsp_01_a_classes.hpp | 44198427182a15a9c5c8b926b00194a1060b4f81 | [] | no_license | RDTCREW/SoT-SDK_2_0_7_reserv | 8e921275508d09e5f81b10f9a43e47597223cb35 | db6a5fc4cdb9348ddfda88121ebe809047aa404a | refs/heads/master | 2020-07-24T17:18:40.537329 | 2019-09-11T18:53:58 | 2019-09-11T18:53:58 | 207,991,316 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,801 | hpp | #pragma once
// Sea of Thieves (2.0) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "SoT_BP_cls_shop_bsp_01_a_structs.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass BP_cls_shop_bsp_01_a.BP_cls_shop_bsp_01_a_C
// 0x0218 (0x06C0 - 0x04A8)
class ABP_cls_shop_bsp_01_a_C : public AActor
{
public:
class UStaticMeshComponent* bsp_cls_shop_dressing_01_b; // 0x04A8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UBoxComponent* Collision_02; // 0x04B0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UBoxComponent* Collision_01; // 0x04B8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* bsp_cls_shop_dressing_01_a; // 0x04C0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class USpotLightComponent* SpotLight8; // 0x04C8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class USpotLightComponent* SpotLight7; // 0x04D0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UChildActorComponent* BP_IslandVanityChest; // 0x04D8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* StaticMesh7; // 0x04E0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UChildActorComponent* BP_IslandStorageBarrel_Outpost3; // 0x04E8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UChildActorComponent* BP_IslandStorageBarrel_Outpost2; // 0x04F0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UChildActorComponent* BP_IslandStorageBarrel_Outpost1; // 0x04F8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UChildActorComponent* BP_IslandClothingChest; // 0x0500(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UChildActorComponent* ChildActor1; // 0x0508(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UChildActorComponent* ChildActor; // 0x0510(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UChildActorComponent* wsp_bottle_burner; // 0x0518(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* NoRain_Volume5; // 0x0520(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* NoRain_Volume4; // 0x0528(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* NoRain_Volume3; // 0x0530(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* NoRain_Volume2; // 0x0538(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* NoRain_Volume; // 0x0540(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class USpotLightComponent* SpotLight6; // 0x0548(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class USpotLightComponent* SpotLight5; // 0x0550(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class USpotLightComponent* SpotLight4; // 0x0558(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class USpotLightComponent* SpotLight3; // 0x0560(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class USpotLightComponent* SpotLight2; // 0x0568(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class USpotLightComponent* SpotLight1; // 0x0570(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class USpotLightComponent* SpotLight; // 0x0578(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UPointLightComponent* PointLight; // 0x0580(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UPostProcessComponent* PostProcess; // 0x0588(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UBoxComponent* Box; // 0x0590(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UChildActorComponent* AudioSpace; // 0x0598(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* StaticMesh14; // 0x05A0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* cmn_moneybag_01_a; // 0x05A8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* StaticMesh13; // 0x05B0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* StaticMesh12; // 0x05B8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* StaticMesh11; // 0x05C0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* StaticMesh10; // 0x05C8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* StaticMesh9; // 0x05D0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* StaticMesh8; // 0x05D8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* cmn_barrel_debris_02_a; // 0x05E0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* cmn_barrel_debris_03_a; // 0x05E8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* cmn_barrel_debris_01_a; // 0x05F0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* bld_shop_drapes_02_a; // 0x05F8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* bld_cls_shop_hanging_cloth_03_a; // 0x0600(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* bld_enc_shop_rug_01_a; // 0x0608(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* bld_cls_shop_hanging_rope_01_a; // 0x0610(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* bld_cls_shop_hanging_cloth_02_a; // 0x0618(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* bld_cls_shp_dye_pot_lid_01_c; // 0x0620(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* bld_cls_shp_dye_pot_lid_01_b; // 0x0628(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* bld_cls_shp_dye_pot_01_c; // 0x0630(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* bld_cls_shp_dye_pot_01_b; // 0x0638(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* bld_shop_drapes_01_a; // 0x0640(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* bld_shop_rug_01_a; // 0x0648(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* bld_shop_table_01_a; // 0x0650(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* bld_cls_shp_sign_01_a; // 0x0658(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* bld_cls_shp_porch_mat_01_a; // 0x0660(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* bld_cls_shp_stairs_01_a; // 0x0668(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* bld_cls_shop_door_01_a; // 0x0670(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* bld_cls_shop_window_01_a2; // 0x0678(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* bld_cls_shop_window_01_a1; // 0x0680(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* bld_cls_shop_window_01_a; // 0x0688(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* bld_cls_shp_clothes_lines_01_a; // 0x0690(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* bld_cls_shp_hanging_cloth_01_a; // 0x0698(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* bld_cls_shp_side_roof_01_a; // 0x06A0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* bld_cls_shp_main_roof_01_a; // 0x06A8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UStaticMeshComponent* bld_cls_shop_01_a; // 0x06B0(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
class USceneComponent* DefaultSceneRoot; // 0x06B8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData)
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>(_xor_("BlueprintGeneratedClass BP_cls_shop_bsp_01_a.BP_cls_shop_bsp_01_a_C"));
return ptr;
}
void UserConstructionScript();
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
b92579705c8ee6eebbec6a6d427267d208d6156d | b9ab0973a86955a0ac264d03e764934db4d88025 | /src/entities/Belt.cpp | 03ea152513ff4053b65743cf29bb159ef636c13d | [] | no_license | swarzzy/factory-game | b7ef7d76b8b34e1adb7cc4c1e7ba3666cb0daa50 | 8229ce1cd5025a9ea6c79fd837795b6ebf4505de | refs/heads/master | 2022-12-11T03:16:49.346513 | 2020-07-05T16:15:36 | 2020-07-05T16:15:36 | 262,098,096 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,422 | cpp | #include "Belt.h"
void SerializeBeltTrait(BeltTrait* trait, BinaryBlob* out) {
WriteField(out, &trait->direction);
WriteField(out, &trait->items);
WriteField(out, &trait->itemPositions);
WriteField(out, &trait->itemTurnDirections);
WriteField(out, &trait->extractTimeout);
}
void DeserializeBeltTrait(BeltTrait* trait, EntitySerializedData data) {
ReadField(&data, &trait->direction);
ReadField(&data, &trait->items);
ReadField(&data, &trait->itemPositions);
ReadField(&data, &trait->itemTurnDirections);
ReadField(&data, &trait->extractTimeout);
trait->InsertItem = BeltInsertItem;
trait->GrabItem = BeltGrabItem;
}
void OrientBelt(Belt* belt) {
i32 directions[4] {};
auto world = GetWorld();
ForEachEntityNeighbor(world, belt->p, [&](auto block, auto dir) {
if (block.entity) {
// TODO: Actually use trait
auto neighborBelt = FindEntityTrait<BeltTrait>(block.entity);
if (neighborBelt) {
if (neighborBelt->direction == dir || Dir::Opposite(neighborBelt->direction) == dir) {
belt->belt.direction = neighborBelt->direction;
return;
} else {
belt->belt.direction = dir;
return;
}
}
}
});
i32 max = -1;
i32 maxIndex = -1;
for (usize i = 0; i < array_count(directions); i++) {
if (directions[i] == max) {
maxIndex = -1;
break;
}
if (directions[i] > max) {
max = directions[i];
maxIndex = i;
}
}
if (maxIndex != -1) {
belt->belt.direction = (Direction)directions[maxIndex];
}
}
Entity* CreateBelt(GameWorld* world, WorldPos p) {
Belt* belt = AddBlockEntity<Belt>(world, p.block);
if (belt) {
belt->type = EntityType::Belt;
belt->dirtyNeighborhood = true;
belt->belt.direction = Direction::North;
belt->belt.InsertItem = BeltInsertItem;
belt->belt.GrabItem = BeltGrabItem;
OrientBelt(belt);
}
return belt;
}
void BeltDelete(Entity* entity, GameWorld* world) {
}
void BeltDropPickup(Entity* entity, GameWorld* world, WorldPos p) {
auto belt = (Belt*)entity;
auto pickup = CreatePickup(p, (u32)Item::Belt, 1);
for (usize i = 0; i < array_count(belt->belt.items); i++) {
if (belt->belt.items[i] != 0) {
auto pickup = CreatePickup(p, belt->belt.items[i], 1);
}
}
}
void BeltRotate(Belt* belt, void* _data) {
auto data = (EntityRotateData*)_data;
belt->belt.direction = Dir::RotateYCW(belt->belt.direction);
PostEntityNeighborhoodUpdate(belt->world, belt);
}
void BeltUpdateAndRender(Belt* belt, void* _data) {
auto data = (EntityUpdateAndRenderData*)_data;
if (belt->dirtyNeighborhood) {
//OrientBelt(belt);
belt->dirtyNeighborhood = false;
}
auto trait = &belt->belt;
bool lateClearLastItemSlot = false;
for (usize i = 0; i < BeltTrait::Capacity; i++) {
if (trait->items[i] != 0) {
f32 max = (i + 1) * (1.0f / array_count(trait->items));
f32 maxPrev = (i) * (1.0f / array_count(trait->items));
trait->itemPositions[i] = trait->itemPositions[i] + data->deltaTime * BeltTrait::Speed;
if (trait->itemHorzPositions[i] != 0.0f) {
trait->itemHorzPositions[i] -= data->deltaTime * BeltTrait::HorzSpeed;
if (trait->itemHorzPositions[i] < 0.0f) {
trait->itemHorzPositions[i] = 0.0f;
}
}
if (trait->itemPositions[i] > max) {
bool passedForward = false;
if (i < BeltTrait::Capacity - 1) {
if (trait->items[i + 1] == 0) {
trait->itemPositions[i + 1] = trait->itemPositions[i];
trait->items[i + 1] = trait->items[i];
trait->items[i] = 0;
i++;
} else {
trait->itemPositions[i] = max;
}
} else {
auto to = belt->p + Dir::ToIV3(trait->direction);
auto toEntity = GetBlockEntity(belt->world, to);
if (toEntity) {
auto toBelt = FindEntityTrait<BeltTrait>(toEntity);
if (toBelt) {
assert(toBelt->InsertItem);
bool passed = toBelt->InsertItem(toEntity, trait->direction, trait->items[i], trait->itemPositions[i]);
if (passed) {
passedForward = true;
if (belt->generation > toEntity->generation) {
trait->items[BeltTrait::LastSlot] = 0;
} else {
lateClearLastItemSlot = true;
}
}
}
}
}
if (!passedForward) {
trait->itemPositions[i] = max;
}
}
}
}
auto context = GetContext();
RenderCommandDrawMesh command {};
command.transform = Translate(WorldPos::Relative(data->camera->targetWorldPosition, WorldPos::Make(belt->p))) * M4x4(RotateY(Dir::AngleDegY(Direction::North, belt->belt.direction)));
command.mesh = context->beltStraightMesh;
command.material = &context->beltMaterial;
Push(data->group, &command);
for (usize i = 0; i < BeltTrait::Capacity; i++) {
if (belt->belt.items[i] != 0) {
// TODO: Cache align and scale
auto info = GetItemInfo(belt->belt.items[i]);
v3 dir = V3(Dir::ToIV3(belt->belt.direction));
v3 horzDir = V3(Dir::ToIV3(belt->belt.itemTurnDirections[i]));
v3 itemBegin = V3(Dir::ToIV3(Dir::Opposite(belt->belt.direction))) * 0.5f;
v3 itemOffset = itemBegin + dir * belt->belt.itemPositions[i] - V3(0.0f, info->beltAlign, 0.0f) + horzDir * belt->belt.itemHorzPositions[i] * 0.5f;
RenderCommandDrawMesh command {};
command.transform = Translate(WorldPos::Relative(data->camera->targetWorldPosition, WorldPos::Make(belt->p, itemOffset))) * Scale(V3(info->beltScale));
command.mesh = info->mesh;
command.material = info->material;
Push(data->group, &command);
}
}
if (lateClearLastItemSlot) {
belt->belt.items[BeltTrait::Capacity - 1] = 0;
}
}
void BeltBehavior(Entity* entity, EntityBehaviorInvoke reason, void* data) {
auto belt = (Belt*)entity;
switch (reason) {
case EntityBehaviorInvoke::UpdateAndRender: { BeltUpdateAndRender(belt, data); } break;
case EntityBehaviorInvoke::Rotate: { BeltRotate(belt, data); } break;
default: {} break;
}
}
bool BeltInsertItem(Entity* entity, Direction dir, u32 itemID, f32 callerItemPos) {
bool result = false;
auto belt = (Belt*)entity;
u32 index = U32::Max;
f32 horzPos = 0.0f;
Direction turnDir = dir;
if (dir == belt->belt.direction) {
if (belt->belt.items[BeltTrait::FirstSlot] == 0) {
index = BeltTrait::FirstSlot;
}
} else if (dir != Dir::Opposite(belt->belt.direction)) {
u32 midSlot = BeltTrait::Capacity / 2 + 1;
if (belt->belt.items[midSlot] == 0) {
index = midSlot;
horzPos = 1.0f;
turnDir = Dir::Opposite(dir);
}
}
if (index != U32::Max) {
belt->belt.items[index] = itemID;
belt->belt.itemPositions[index] = callerItemPos - 1.0f + (index * (1.0f / BeltTrait::Capacity));
belt->belt.itemHorzPositions[index] = horzPos;
belt->belt.itemTurnDirections[index] = turnDir;
result = true;
}
return result;
}
u32 BeltGrabItem(Entity* entity, Direction dir) {
u32 result = 0;
auto belt = (Belt*)entity;
if (belt->belt.direction == dir) {
if (belt->belt.items[BeltTrait::LastSlot] && belt->belt.itemPositions[BeltTrait::LastSlot] == 1.0f) {
result = belt->belt.items[BeltTrait::LastSlot];
belt->belt.items[BeltTrait::LastSlot] = 0;
}
}
return result;
}
| [
"[email protected]"
] | |
feeed1043317b9e5af86fee7561a17b6b28af927 | e6559df51c2a14256962c3757073a491ea66de7c | /URI/1746 - Dividindo os Nomes.cpp | f7962bb4d58a14bac241d4d999badfccabb38bee | [] | no_license | Maycon708/Maratona | c30eaedc3ee39d69582b0ed1a60f31ad8d666d43 | b6d07582544c230e67c23a20e1a1be99d4b47576 | refs/heads/master | 2020-04-25T23:37:53.992330 | 2019-02-28T17:10:25 | 2019-02-28T17:10:25 | 143,191,679 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,912 | cpp | #include <bits/stdc++.h>
#define INF 200*18+10
#define rep(i, a, b) for(int i = int(a); i < int(b); i++)
#define pb push_back
#define debug(x) cout << #x << " = " << x << endl;
#define debug2(x,y) cout << #x << " = " << x << " --- " << #y << " = " << y << "\n";
#define debugM( x, l, c ) { rep( i, 0, l ){ rep( j, 0, c ) cout << x[i][j] << " "; printf("\n");}}
#define all(S) (S).begin(), (S).end()
#define F first
#define S second
#define mk make_pair
#define N 25000
#define FOR(i,a,b) rep(i,a,b+1)
#define SET(c,v) memset(c, v, sizeof c);
using namespace std;
typedef long long int ll;
typedef pair <ll, ll> ii;
const int MAX = 200*18+10;
int sig[MAX][30], cnt, freq[MAX];
int R[MAX], down[MAX];
int pd[MAX][100];
void init(){
cnt = 1;
memset( freq, 0, sizeof freq );
memset( sig, -1, sizeof sig );
memset( pd, -1, sizeof pd );
}
void add( char* s ){
int t = strlen(s), x = 0;
rep( i, 0, t ){
int c = s[i] - 'A';
if( sig[x][c] == -1 ) sig[x][c] = cnt++;
x = sig[x][c];
freq[x]++;
}
}
void calc(){
for( int i = 0; i < cnt; i++ ){
int last = -1;
for( int j = 26; j >= 0; j-- ){
if( sig[i][j] != -1 ){
R[sig[i][j]] = last;
last = sig[i][j];
}
}
down[i] = last;
}
}
int solve( int x, int st, int d ){
int &ans = pd[x][st];
if( ans == -1 ){
ans = INF;
for( int i = 0; i <= min( st, freq[x] ); i++ ){
if( R[x] == -1 && i != st ) continue;
int cur = 0;
if( i == 1 ) cur += d;
if( freq[x] - i == 1 ) cur += d;
if( R[x] != -1 ) cur += solve( R[x], st-i, d );
if( down[x] != -1 ){
cur += solve(down[x], i, d+1);
if( i == 1 ) cur -= d+1;
if( freq[x] - i == 1 ) cur -= d+1;
}
ans = min( ans, cur );
}
}
return ans;
}
int main(){
int n;
char s[20];
while( scanf("%d", &n ) != EOF ){
init();
rep( i, 0, 2*n ){
scanf("%s", s );
add(s);
}
calc();
printf("%d\n", n * solve( down[0], n, 1 ));
}
}
| [
"[email protected]"
] | |
35d3ec7656754e02679f3fd7d9bb5330876edc09 | 556d4d27c1f7ae415c1c7d4497e53295cc87c5fa | /sketch_oct10a.ino | ee4a13c8e9910b596d9cc6badab6ecc957081594 | [] | no_license | prankapo/PESMO | 7970111cc134c60101bf6ba1e8c7975914d53af4 | 1bbebfbde6871d67a10c47c2011cc9679e5e8181 | refs/heads/main | 2023-07-10T07:54:28.065151 | 2020-10-11T17:26:55 | 2020-10-11T17:26:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 878 | ino | float voltage1, voltage2;
void setup() {
pinMode(5, OUTPUT);
}
void loop() {
if (digitalRead(5) == HIGH){
_delay_us(100);
if(digitalRead(5) == HIGH){
Serial.begin(9600); //fastest frequency
Serial.println("START SAMPLING");
while(1){
voltage1 = (5.0 * analogRead(A0))/1024.0;
voltage2 = (5.0 * analogRead(A1))/1024.0;
Serial.print("CH1 ");
Serial.print(voltage1);
Serial.print(" CH2 ");
Serial.print(voltage2);
Serial.print("\n");
_delay_us(40);
if(digitalRead(5) == LOW){
_delay_us(100);
if(digitalRead(5) == LOW){
Serial.println("\nSTOP SAMPLING");
break;
}
}
}
}
}
}
| [
"[email protected]"
] | |
b0cc6de7c8fc6b2e48ae9dcbf958725dee28acce | cc7661edca4d5fb2fc226bd6605a533f50a2fb63 | /Assembly-CSharp-firstpass/MegaWireConnectionHelper.h | bb8dd3e3a6d7f309f5c70ca5bbbe1cf630706e2c | [
"MIT"
] | permissive | g91/Rust-C-SDK | 698e5b573285d5793250099b59f5453c3c4599eb | d1cce1133191263cba5583c43a8d42d8d65c21b0 | refs/heads/master | 2020-03-27T05:49:01.747456 | 2017-08-23T09:07:35 | 2017-08-23T09:07:35 | 146,053,940 | 1 | 0 | null | 2018-08-25T01:13:44 | 2018-08-25T01:13:44 | null | UTF-8 | C++ | false | false | 324 | h | #pragma once
#include "..\UnityEngine\List.h"
namespace rust
{
class MegaWireConnectionHelper : public MonoBehaviour // 0x18
{
public:
UnityEngine::List<MegaWireConnectionDef>* connections; // 0x18 (size: 0x8, flags: 0x6, type: 0x15)
bool showgizmo; // 0x20 (size: 0x1, flags: 0x6, type: 0x2)
}; // size = 0x28
}
| [
"[email protected]"
] | |
e6b17c05ec9e17b6bd330cf4114d8edfdcdd165b | 7d8e2f95ba14fe322be3f299f30fe1bcf33b576f | /util.cpp | 40cd3ce20bdc07e586ab81961121cbd89a8497a9 | [
"MIT"
] | permissive | milot-mirdita/gotoh | 90103c6dfa7751197f01818a3da55776f3aeb4af | 072eead3670d4c7cde6f8851f46f7e37df893fcc | refs/heads/master | 2020-04-10T15:28:03.758674 | 2013-10-04T23:33:20 | 2013-10-04T23:33:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 593 | cpp | //
// util.cpp
// AlgoUmMilotZuZerstoeren
//
// Created by Martin Steinegger on 23.10.12.
// Copyright (c) 2012 -. All rights reserved.
//
#include "util.h"
#include <iostream>
#include <sstream>
std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
std::stringstream ss(s);
std::string item;
while(std::getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
return split(s, delim, elems);
} | [
"[email protected]"
] | |
01bffc5a7bce9113a3b7f796c017815213faee6b | 6631bfe0702681a61ded05c2e0cc33c1d4f15c31 | /debugwindow.cpp | e1a17eafb784ce03756357826da5c833a932c03a | [] | no_license | J-Lin1996/Audio-Streaming-Service | 28f4f39d4ac9040131661e117ad08f5a576fd81f | aa416afd76661f98d05f9a8a0ae615a444be176b | refs/heads/master | 2021-06-17T22:43:56.535190 | 2017-04-12T15:42:29 | 2017-04-12T15:42:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,408 | cpp | #pragma comment(lib, "ws2_32.lib")
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include "debugwindow.h"
#include "ui_debugwindow.h"
#include "songstreamer.h"
#include "utilities.h"
#include <thread>
#include <QFileDialog>
#include "client.h"
#include "server.h"
DebugWindow *DebugWindow::instance = nullptr;
DebugWindow *DebugWindow::get() {
if (instance == nullptr) {
instance = new DebugWindow();
}
return instance;
}
DebugWindow::DebugWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::DebugWindow)
{
ui->setupUi(this);
QWidget::setWindowTitle("Debug Window");
}
DebugWindow::~DebugWindow()
{
delete ui;
}
void DebugWindow::printToDebugLog(QString msg) {
ui->TB_DebugLog->append(msg);
}
void DebugWindow::logd(QString msg) {
QMetaObject::invokeMethod(this, "printToDebugLog", Q_ARG(QString, msg));
}
void DebugWindow::printToPacketInLog(QString msg) {
ui->TB_PacketIn->moveCursor(QTextCursor::End);
ui->TB_PacketIn->insertPlainText(msg);
}
void DebugWindow::logpi(QString msg) {
QMetaObject::invokeMethod(this, "printToPacketInLog", Q_ARG(QString, msg));
}
void DebugWindow::printToPacketOutLog(QString msg) {
ui->TB_PacketOut->moveCursor(QTextCursor::End);
ui->TB_PacketOut->insertPlainText(msg);
}
void DebugWindow::logpo(QString msg) {
QMetaObject::invokeMethod(this, "printToPacketOutLog", Q_ARG(QString, msg));
}
| [
"[email protected]"
] | |
d8df9eb426d124f82e23503220ee65bb2f7599a4 | 19194c2f2c07ab3537f994acfbf6b34ea9b55ae7 | /android-32/android/icu/util/CurrencyAmount.hpp | 4272323251338224be05444285b24e7a380a05ff | [
"GPL-3.0-only"
] | permissive | YJBeetle/QtAndroidAPI | e372609e9db0f96602da31b8417c9f5972315cae | ace3f0ea2678967393b5eb8e4edba7fa2ca6a50c | refs/heads/Qt6 | 2023-08-05T03:14:11.842336 | 2023-07-24T08:35:31 | 2023-07-24T08:35:31 | 249,539,770 | 19 | 4 | Apache-2.0 | 2022-03-14T12:15:32 | 2020-03-23T20:42:54 | C++ | UTF-8 | C++ | false | false | 1,532 | hpp | #pragma once
#include "./Currency.def.hpp"
#include "../../../java/lang/Number.def.hpp"
#include "../../../java/util/Currency.def.hpp"
#include "./CurrencyAmount.def.hpp"
namespace android::icu::util
{
// Fields
// Constructors
inline CurrencyAmount::CurrencyAmount(jdouble arg0, android::icu::util::Currency arg1)
: android::icu::util::Measure(
"android.icu.util.CurrencyAmount",
"(DLandroid/icu/util/Currency;)V",
arg0,
arg1.object()
) {}
inline CurrencyAmount::CurrencyAmount(jdouble arg0, java::util::Currency arg1)
: android::icu::util::Measure(
"android.icu.util.CurrencyAmount",
"(DLjava/util/Currency;)V",
arg0,
arg1.object()
) {}
inline CurrencyAmount::CurrencyAmount(java::lang::Number arg0, android::icu::util::Currency arg1)
: android::icu::util::Measure(
"android.icu.util.CurrencyAmount",
"(Ljava/lang/Number;Landroid/icu/util/Currency;)V",
arg0.object(),
arg1.object()
) {}
inline CurrencyAmount::CurrencyAmount(java::lang::Number arg0, java::util::Currency arg1)
: android::icu::util::Measure(
"android.icu.util.CurrencyAmount",
"(Ljava/lang/Number;Ljava/util/Currency;)V",
arg0.object(),
arg1.object()
) {}
// Methods
inline android::icu::util::Currency CurrencyAmount::getCurrency() const
{
return callObjectMethod(
"getCurrency",
"()Landroid/icu/util/Currency;"
);
}
} // namespace android::icu::util
// Base class headers
#include "./Measure.hpp"
#ifdef QT_ANDROID_API_AUTOUSE
using namespace android::icu::util;
#endif
| [
"[email protected]"
] | |
b2671334c9b3ee854149078dfcd93225f82530ab | 2c773208ff665a3bc99d1a4ddff6e4d473767626 | /SteelDetect/canny2.h | 04b11b80fdc85950cd4a9c408af146f22bf75b40 | [] | no_license | ChanceMi/EdgeDetect | 6b43845c48c0f622983fbdde6ad1589160199e1c | d8d8af5fbcc5b77e34ef031f29bbd0a5924ed2eb | refs/heads/master | 2016-09-05T08:53:51.031358 | 2015-04-09T09:22:24 | 2015-04-09T09:22:24 | 33,300,131 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,559 | h | #include <opencv2/opencv.hpp>
#include <vector>
#include <math.h>
/*
1)用3x3高斯滤波器进行滤波,消除噪声;
2)针对每一个像素,计算横向与纵向两方向的微分近似,以得到像素的梯度大小和方向;
3)对梯度进行"非极大抑制"(非局部最大值置0);
4)对梯度取两次阈值;
5)对边缘进行连接;
*/
void Canny(unsigned char *pUnchImage, int nWidth, int nHeight, double sigma,
double dRatioLow, double dRatioHigh, unsigned char *pUnchEdge);
void GaussianSmooth(unsigned char *pUnchImg, int nWidth, int nHeight,
double sigma, unsigned char * pUnchSmthdImg);
void DirGrad(unsigned char *pUnchSmthdImg, int nWidth, int nHeight,
int *pnGradX , int *pnGradY);
void GradMagnitude(int *pnGradX, int *pnGradY, int nWidth, int nHeight, int *pnMag);
void NonmaxSuppress(int *pnMag, int *pnGradX, int *pnGradY, int nWidth,
int nHeight, unsigned char *pUnchRst);
void Hysteresis(int *pnMag, int nWidth, int nHeight, double dRatioLow,
double dRatioHigh, unsigned char *pUnchEdge);
void EstimateThreshold(int *pnMag, int nWidth, int nHeight, int *pnThdHigh,int *pnThdLow,
unsigned char * pUnchEdge, double dRatioHigh, double dRationLow);
void MakeGauss(double sigma, double **pdKernel, int *pnWindowSize);
void TraceEdge (int y, int x, int nLowThd, unsigned char *pUnchEdge, int *pnMag, int nWidth);
void TraceEdge2(int y, int x, int nLowThd, unsigned char *pUnchEdge, int *pnMag, int nWidth);
cv::Mat clArrayToCvImage(uchar* output, int resultWidth, int resultHeight); | [
"[email protected]"
] | |
b032196627135d510c0f85cbc3765819ef5e55d6 | eb16dbfe97a18f4cea92ab63a67c106736a428b3 | /Code/astar_search/miscFunction.cpp | 2e0d23dd6029a6074861fe86d05262426067fe09 | [] | no_license | kevinktlin/astar_search | 1377e80a7bf6891cc5ea50cf5961a1403a3a8c3d | dd15be8c1bc07ed069c76976092aa79bcea14301 | refs/heads/master | 2021-01-19T19:08:40.103195 | 2017-04-01T03:19:01 | 2017-04-01T03:19:01 | 86,646,645 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 743 | cpp | /*
* miscFunction.cpp
*
* Created on: Mar 30, 2017
* Author: kingo
*/
#include <ostream>
#include "miscFunction.h"
#include "miscType.h"
std::ostream& operator<<(std::ostream& os, const Location& loc) {
return os << '(' << loc.x << ',' << loc.y << ')';
}
bool operator==(const Location& lhs, const Location& rhs) {
return (lhs.x == rhs.x && lhs.y == rhs.y);
}
bool operator!=(const Location& lhs, const Location& rhs) {
return (lhs.x != rhs.x || lhs.y != rhs.y);
}
bool operator>(const priorityElement& lhs, const priorityElement& rhs) {
return lhs.priority > rhs.priority;
}
bool operator<(const priorityElement& lhs, const priorityElement& rhs) {
return lhs.priority < rhs.priority;
}
| [
"[email protected]"
] | |
bba13458df05a0d6c5ec81b8ef850225477a8b48 | 341612fd3fe8162b7f96a523dcfd8be197e04312 | /Logic_Game/Logic_Game/Editor.hpp | a74bcea88805194bd197184c46c0b42ecf30ff91 | [] | no_license | Miklakapi/Logic_Game | f45f3a0aac8851d6f15adb2762ac1d2c9313ef0c | 421b9e4152b2e3148873b78b38f1017269190543 | refs/heads/master | 2022-05-28T02:52:17.612643 | 2022-03-22T21:59:23 | 2022-03-22T21:59:23 | 169,990,507 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 720 | hpp | #pragma once
#include <SFML\Window.hpp>
#include <SFML\System.hpp>
#include <SFML\Graphics.hpp>
#include <string>
#include <fstream>
#include "LaserReceiver.hpp"
#include "ShootingBlock.hpp"
#include "LaserMachine.hpp"
#include "Mirror.hpp"
#include "Screen.hpp"
#include "VectorConverter.hpp"
#include "Play.hpp"
using namespace sf;
using namespace std;
class Editor{
public:
enum Type {
None,
Exit
};
private:
Clock delayClock;
Screen::Stage stage;
Screen* screen;
RectangleShape stageCounter;
Texture counterTexture;
bool start;
bool stop;
Screen::Click clickType;
void save();
public:
Editor();
Type run(RenderWindow& window);
void draw(RenderWindow& window);
~Editor();
}; | [
"[email protected]"
] | |
66efbe6bc996ebddc93f8e111e1f637d889097be | b0cfb4fd27bdc751c11bc294d8a76023872da1b9 | /rectangle.h | 6d2ca93c088c60ed385a8137d84e4ef8cf8e3440 | [] | no_license | manzala/Shape-Inheritance | 5858111556ace636343b3d895cc60e9f78322e28 | ddc51edbc6deca644217589d4f1859080e6661d2 | refs/heads/master | 2021-06-14T00:02:21.770020 | 2017-03-22T17:20:19 | 2017-03-22T17:20:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 385 | h | #ifndef RECTANGLE_H
#define RECTANGLE_H
#include "shape.h"
#include "circle.h"
#include "quadrilateral.h"
#include <iostream>
using namespace std;
class rectangle : public quadrilateral {
public:
void rectangle::draw();
double CalArea(double, double);
bool isSquare(int, int);
//bool getisSquare();
rectangle(string, string, int, int);
private:
};
#endif | [
"[email protected]"
] | |
51d26397c2ee8d2b2503a00584967cf2991101ce | 83bacfbdb7ad17cbc2fc897b3460de1a6726a3b1 | /third_party/skia/tools/skpdiff/SkDifferentPixelsMetric.h | 1f39b3552e8e959544a417a534d6a5007ee1c699 | [
"BSD-3-Clause",
"Apache-2.0"
] | permissive | cool2528/miniblink49 | d909e39012f2c5d8ab658dc2a8b314ad0050d8ea | 7f646289d8074f098cf1244adc87b95e34ab87a8 | refs/heads/master | 2020-06-05T03:18:43.211372 | 2019-06-01T08:57:37 | 2019-06-01T08:59:56 | 192,294,645 | 2 | 0 | Apache-2.0 | 2019-06-17T07:16:28 | 2019-06-17T07:16:27 | null | UTF-8 | C++ | false | false | 1,092 | h | /*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SkDifferentPixelsMetric_DEFINED
#define SkDifferentPixelsMetric_DEFINED
#include "SkTDArray.h"
#if SK_SUPPORT_OPENCL
#include "SkCLImageDiffer.h"
#else
#include "SkImageDiffer.h"
#endif
/**
* A differ that measures the percentage of different corresponding pixels. If the two images are
* not the same size or have no pixels, the result will always be zero.
*/
class SkDifferentPixelsMetric :
#if SK_SUPPORT_OPENCL
public SkCLImageDiffer {
#else
public SkImageDiffer {
#endif
public:
const char* getName() const override;
virtual bool diff(SkBitmap* baseline, SkBitmap* test,
const BitmapsToCreate& bitmapsToCreate,
Result* result) const override;
protected:
#if SK_SUPPORT_OPENCL
bool onInit() override;
#endif
private:
#if SK_SUPPORT_OPENCL
cl_kernel fKernel;
typedef SkCLImageDiffer INHERITED;
#else
typedef SkImageDiffer INHERITED;
#endif
};
#endif
| [
"[email protected]"
] | |
8a155aaa6c46feca608f81113895ac1acaf6193d | bb9b83b2526d3ff8a932a1992885a3fac7ee064d | /src/modules/osg/generated_code/NodeVisitor.pypp.hpp | a056a8b0005ef75c767b4e31b21165addf25b12e | [] | no_license | JaneliaSciComp/osgpyplusplus | 4ceb65237772fe6686ddc0805b8c77d7b4b61b40 | a5ae3f69c7e9101a32d8cc95fe680dab292f75ac | refs/heads/master | 2021-01-10T19:12:31.756663 | 2015-09-09T19:10:16 | 2015-09-09T19:10:16 | 23,578,052 | 20 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 211 | hpp | // This file has been generated by Py++.
#ifndef NodeVisitor_hpp__pyplusplus_wrapper
#define NodeVisitor_hpp__pyplusplus_wrapper
void register_NodeVisitor_class();
#endif//NodeVisitor_hpp__pyplusplus_wrapper
| [
"[email protected]"
] | |
b7b4b348d129b1452a78796aa88301ab77eb2eb4 | 0bbf24ce561dc5bff0cc9b99cf145cd4215442c8 | /source/game/common/flowstates/TrainerCardOverworldFlowState.h | 1e0c12a607fd7793174fab154915435f7de3046c | [] | no_license | AlexKoukoulas2074245K/ProjectRetro | 90b5e0d53d577ce386e24a9fa7847970f301c01c | 363f7f9841ca1a4757d297c86f89ce5a1abe6288 | refs/heads/master | 2020-05-01T19:19:45.284877 | 2019-12-22T17:44:15 | 2019-12-22T17:44:15 | 177,645,852 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,985 | h | //
// TrainerCardOverworldFlowState.h
// ProjectRetro
//
// Created by Alex Koukoulas on 29/10/2019.
//
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
#ifndef TrainerCardOverworldFlowState_h
#define TrainerCardOverworldFlowState_h
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
#include "BaseOverworldFlowState.h"
#include "../GameConstants.h"
#include "../utils/MathUtils.h"
#include "../utils/StringUtils.h"
#include "../../ECS.h"
#include <vector>
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
class TrainerCardOverworldFlowState final: public BaseOverworldFlowState
{
public:
TrainerCardOverworldFlowState(ecs::World&);
void VUpdate(const float dt) override;
private:
void CreateBackground();
void CreateInfoTextbox();
void CreateEmblems();
void DestroyBackground();
void DestroyInfoTextbox();
void DestroyEmblems();
static const std::string TRAINER_BACKGROUND_SPRITE_MODEL_FILE_NAME;
static const std::string TRAINER_BACKGROUND_TEXTURE_FILE_NAME;
static const std::string ENCOUNTER_SPRITE_MODEL_NAME;
static const std::string ENCOUNTER_SPRITE_ANIMATION_NAME;
static const std::string ENCOUNTER_SPRITE_SHADER_NAME;
static const std::string EMBLEMS_ATLAS_FILE_NAME;
static const glm::vec3 BACKGROUND_POSITION;
static const glm::vec3 BACKGROUND_SCALE;
static const glm::vec3 TRAINER_CARD_BACKGROUND_POSITION;
static const glm::vec3 TRAINER_CARD_BACKGROUND_SCALE;
static const glm::vec3 INFO_TEXTBOX_POSITION;
static const glm::vec3 EMBLEM_SPRITE_SCALE;
static const glm::vec3 EMBLEM_SPRITE_ORIGIN_POSITION;
static const int INFO_TEXTBOX_COLS;
static const int INFO_TEXTBOX_ROWS;
static const int EMBLEM_ATALS_COLS;
static const int EMBLEM_ATALS_ROWS;
static const float EMBLEMS_HOR_DISTANCE;
static const float EMBLEMS_VER_DISTANCE;
std::vector<ecs::EntityId> mEmblemEntityIds;
ecs::EntityId mBackgroundCoverEntityId;
ecs::EntityId mInfoTextboxEntityId;
ecs::EntityId mTrainerCardBackgroundEntityId;
};
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
#endif /* TrainerCardOverworldFlowState_h */
| [
"[email protected]"
] | |
2ee92b74b29fab53d5922947c11c08620c8a6fb6 | 73ee941896043f9b3e2ab40028d24ddd202f695f | /external/chromium_org/chrome/browser/media_galleries/fileapi/itunes_finder_win_browsertest.cc | 9aeb450ab98f84264741462b7aa7712062738226 | [
"BSD-3-Clause"
] | permissive | CyFI-Lab-Public/RetroScope | d441ea28b33aceeb9888c330a54b033cd7d48b05 | 276b5b03d63f49235db74f2c501057abb9e79d89 | refs/heads/master | 2022-04-08T23:11:44.482107 | 2016-09-22T20:15:43 | 2016-09-22T20:15:43 | 58,890,600 | 5 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 5,942 | cc | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/base64.h"
#include "base/base_paths_win.h"
#include "base/bind.h"
#include "base/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/strings/stringprintf.h"
#include "base/test/scoped_path_override.h"
#include "chrome/browser/media_galleries/fileapi/itunes_finder_win.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/base/in_process_browser_test.h"
namespace itunes {
namespace {
std::string EncodePath(const base::FilePath& path) {
std::string input(reinterpret_cast<const char*>(path.value().data()),
path.value().size()*2);
std::string result;
base::Base64Encode(input, &result);
return result;
}
void TouchFile(const base::FilePath& file) {
ASSERT_EQ(1, file_util::WriteFile(file, " ", 1));
}
class ITunesFinderWinTest : public InProcessBrowserTest {
public:
ITunesFinderWinTest() : test_finder_callback_called_(false) {}
virtual ~ITunesFinderWinTest() {}
virtual void SetUp() OVERRIDE {
ASSERT_TRUE(app_data_dir_.CreateUniqueTempDir());
ASSERT_TRUE(music_dir_.CreateUniqueTempDir());
app_data_dir_override_.reset(
new base::ScopedPathOverride(base::DIR_APP_DATA, app_data_dir()));
music_dir_override_.reset(
new base::ScopedPathOverride(chrome::DIR_USER_MUSIC, music_dir()));
InProcessBrowserTest::SetUp();
}
const base::FilePath& app_data_dir() {
return app_data_dir_.path();
}
const base::FilePath& music_dir() {
return music_dir_.path();
}
void WritePrefFile(const std::string& data) {
base::FilePath pref_dir =
app_data_dir().AppendASCII("Apple Computer").AppendASCII("iTunes");
ASSERT_TRUE(file_util::CreateDirectory(pref_dir));
ASSERT_EQ(data.size(),
file_util::WriteFile(pref_dir.AppendASCII("iTunesPrefs.xml"),
data.data(), data.size()));
}
void TouchDefault() {
base::FilePath default_dir = music_dir().AppendASCII("iTunes");
ASSERT_TRUE(file_util::CreateDirectory(default_dir));
TouchFile(default_dir.AppendASCII("iTunes Music Library.xml"));
}
void TestFindITunesLibrary() {
test_finder_callback_called_ = false;
result_.clear();
base::RunLoop loop;
ITunesFinder::FindITunesLibrary(
base::Bind(&ITunesFinderWinTest::TestFinderCallback,
base::Unretained(this),
loop.QuitClosure()));
loop.Run();
}
bool EmptyResult() const {
return result_.empty();
}
bool test_finder_callback_called() const {
return test_finder_callback_called_;
}
private:
void TestFinderCallback(const base::Closure& quit_closure,
const std::string& result) {
test_finder_callback_called_ = true;
result_ = result;
quit_closure.Run();
}
scoped_ptr<base::ScopedPathOverride> app_data_dir_override_;
scoped_ptr<base::ScopedPathOverride> music_dir_override_;
base::ScopedTempDir app_data_dir_;
base::ScopedTempDir music_dir_;
bool test_finder_callback_called_;
std::string result_;
DISALLOW_COPY_AND_ASSIGN(ITunesFinderWinTest);
};
IN_PROC_BROWSER_TEST_F(ITunesFinderWinTest, NotFound) {
TestFindITunesLibrary();
EXPECT_TRUE(test_finder_callback_called());
EXPECT_TRUE(EmptyResult());
}
IN_PROC_BROWSER_TEST_F(ITunesFinderWinTest, DefaultLocation) {
TouchDefault();
TestFindITunesLibrary();
EXPECT_TRUE(test_finder_callback_called());
EXPECT_FALSE(EmptyResult());
}
IN_PROC_BROWSER_TEST_F(ITunesFinderWinTest, CustomLocation) {
base::FilePath library_xml = music_dir().AppendASCII("library.xml");
TouchFile(library_xml);
std::string xml = base::StringPrintf(
"<plist>"
" <dict>"
" <key>User Preferences</key>"
" <dict>"
" <key>iTunes Library XML Location:1</key>"
" <data>%s</data>"
" </dict>"
" </dict>"
"</plist>", EncodePath(library_xml).c_str());
WritePrefFile(xml);
TestFindITunesLibrary();
EXPECT_TRUE(test_finder_callback_called());
EXPECT_FALSE(EmptyResult());
}
IN_PROC_BROWSER_TEST_F(ITunesFinderWinTest, BadCustomLocation) {
// Missing file.
base::FilePath library_xml = music_dir().AppendASCII("library.xml");
std::string xml = base::StringPrintf(
"<plist>"
" <dict>"
" <key>User Preferences</key>"
" <dict>"
" <key>iTunes Library XML Location:1</key>"
" <data>%s</data>"
" </dict>"
" </dict>"
"</plist>", EncodePath(library_xml).c_str());
WritePrefFile(xml);
TestFindITunesLibrary();
EXPECT_TRUE(test_finder_callback_called());
EXPECT_TRUE(EmptyResult());
TouchFile(library_xml);
// User Preferences dictionary at the wrong level.
xml = base::StringPrintf(
"<plist>"
" <key>User Preferences</key>"
" <dict>"
" <key>iTunes Library XML Location:1</key>"
" <data>%s</data>"
" </dict>"
"</plist>", EncodePath(library_xml).c_str());
WritePrefFile(xml);
TestFindITunesLibrary();
EXPECT_TRUE(test_finder_callback_called());
EXPECT_TRUE(EmptyResult());
// Library location at the wrong scope.
xml = base::StringPrintf(
"<plist>"
" <dict>"
" <key>User Preferences</key>"
" <dict/>"
" <key>iTunes Library XML Location:1</key>"
" <data>%s</data>"
" </dict>"
"</plist>", EncodePath(library_xml).c_str());
WritePrefFile(xml);
TestFindITunesLibrary();
EXPECT_TRUE(test_finder_callback_called());
EXPECT_TRUE(EmptyResult());
}
} // namespace
} // namespace itunes
| [
"[email protected]"
] | |
15e48a93c779332db3cd50739bed1a353863a4ef | ac1c9fbc1f1019efb19d0a8f3a088e8889f1e83c | /out/release/gen/media/capture/mojom/video_capture.mojom-blink.h | 8dbc8c7e68be5b6b5160c9e29ffdac8e31c8d929 | [
"BSD-3-Clause"
] | permissive | xueqiya/chromium_src | 5d20b4d3a2a0251c063a7fb9952195cda6d29e34 | d4aa7a8f0e07cfaa448fcad8c12b29242a615103 | refs/heads/main | 2022-07-30T03:15:14.818330 | 2021-01-16T16:47:22 | 2021-01-16T16:47:22 | 330,115,551 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,086 | h | // media/capture/mojom/video_capture.mojom-blink.h is auto generated by mojom_bindings_generator.py, do not edit
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef MEDIA_CAPTURE_MOJOM_VIDEO_CAPTURE_MOJOM_BLINK_H_
#define MEDIA_CAPTURE_MOJOM_VIDEO_CAPTURE_MOJOM_BLINK_H_
#include <stdint.h>
#include <limits>
#include <type_traits>
#include <utility>
#include "base/callback.h"
#include "base/macros.h"
#include "base/optional.h"
#include "mojo/public/cpp/bindings/mojo_buildflags.h"
#if BUILDFLAG(MOJO_TRACE_ENABLED)
#include "base/trace_event/trace_event.h"
#endif
#include "mojo/public/cpp/bindings/clone_traits.h"
#include "mojo/public/cpp/bindings/equals_traits.h"
#include "mojo/public/cpp/bindings/lib/serialization.h"
#include "mojo/public/cpp/bindings/struct_ptr.h"
#include "mojo/public/cpp/bindings/struct_traits.h"
#include "mojo/public/cpp/bindings/union_traits.h"
#include "media/capture/mojom/video_capture.mojom-shared.h"
#include "media/capture/mojom/video_capture.mojom-blink-forward.h"
#include "media/capture/mojom/video_capture_types.mojom-blink-forward.h"
#include "ui/gfx/geometry/mojom/geometry.mojom-blink-forward.h"
#include "mojo/public/mojom/base/unguessable_token.mojom-blink-forward.h"
#include "mojo/public/cpp/bindings/lib/wtf_clone_equals_util.h"
#include "mojo/public/cpp/bindings/lib/wtf_hash_util.h"
#include "third_party/blink/renderer/platform/wtf/hash_functions.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "mojo/public/cpp/bindings/associated_interface_ptr.h"
#include "mojo/public/cpp/bindings/associated_interface_ptr_info.h"
#include "mojo/public/cpp/bindings/associated_interface_request.h"
#include "mojo/public/cpp/bindings/interface_ptr.h"
#include "mojo/public/cpp/bindings/interface_request.h"
#include "mojo/public/cpp/bindings/lib/control_message_handler.h"
#include "mojo/public/cpp/bindings/raw_ptr_impl_ref_traits.h"
#include "mojo/public/cpp/bindings/thread_safe_interface_ptr.h"
#include "third_party/blink/public/platform/web_common.h"
namespace WTF {
struct media_mojom_internal_VideoCaptureState_DataHashFn {
static unsigned GetHash(const ::media::mojom::VideoCaptureState& value) {
using utype = std::underlying_type<::media::mojom::VideoCaptureState>::type;
return DefaultHash<utype>::Hash().GetHash(static_cast<utype>(value));
}
static bool Equal(const ::media::mojom::VideoCaptureState& left, const ::media::mojom::VideoCaptureState& right) {
return left == right;
}
static const bool safe_to_compare_to_empty_or_deleted = true;
};
template <>
struct HashTraits<::media::mojom::VideoCaptureState>
: public GenericHashTraits<::media::mojom::VideoCaptureState> {
static_assert(true,
"-1000000 is a reserved enum value");
static_assert(true,
"-1000001 is a reserved enum value");
static const bool hasIsEmptyValueFunction = true;
static bool IsEmptyValue(const ::media::mojom::VideoCaptureState& value) {
return value == static_cast<::media::mojom::VideoCaptureState>(-1000000);
}
static void ConstructDeletedValue(::media::mojom::VideoCaptureState& slot, bool) {
slot = static_cast<::media::mojom::VideoCaptureState>(-1000001);
}
static bool IsDeletedValue(const ::media::mojom::VideoCaptureState& value) {
return value == static_cast<::media::mojom::VideoCaptureState>(-1000001);
}
};
} // namespace WTF
namespace media {
namespace mojom {
namespace blink {
class VideoCaptureObserverProxy;
template <typename ImplRefTraits>
class VideoCaptureObserverStub;
class VideoCaptureObserverRequestValidator;
class BLINK_PLATFORM_EXPORT VideoCaptureObserver
: public VideoCaptureObserverInterfaceBase {
public:
static const char Name_[];
static constexpr uint32_t Version_ = 0;
static constexpr bool PassesAssociatedKinds_ = false;
static constexpr bool HasSyncMethods_ = false;
using Base_ = VideoCaptureObserverInterfaceBase;
using Proxy_ = VideoCaptureObserverProxy;
template <typename ImplRefTraits>
using Stub_ = VideoCaptureObserverStub<ImplRefTraits>;
using RequestValidator_ = VideoCaptureObserverRequestValidator;
using ResponseValidator_ = mojo::PassThroughFilter;
enum MethodMinVersions : uint32_t {
kOnStateChangedMinVersion = 0,
kOnNewBufferMinVersion = 0,
kOnBufferReadyMinVersion = 0,
kOnBufferDestroyedMinVersion = 0,
};
virtual ~VideoCaptureObserver() {}
virtual void OnStateChanged(VideoCaptureState state) = 0;
virtual void OnNewBuffer(int32_t buffer_id, ::media::mojom::blink::VideoBufferHandlePtr buffer_handle) = 0;
virtual void OnBufferReady(int32_t buffer_id, ::media::mojom::blink::VideoFrameInfoPtr info) = 0;
virtual void OnBufferDestroyed(int32_t buffer_id) = 0;
};
class VideoCaptureHostProxy;
template <typename ImplRefTraits>
class VideoCaptureHostStub;
class VideoCaptureHostRequestValidator;
class VideoCaptureHostResponseValidator;
class BLINK_PLATFORM_EXPORT VideoCaptureHost
: public VideoCaptureHostInterfaceBase {
public:
static const char Name_[];
static constexpr uint32_t Version_ = 0;
static constexpr bool PassesAssociatedKinds_ = false;
static constexpr bool HasSyncMethods_ = false;
using Base_ = VideoCaptureHostInterfaceBase;
using Proxy_ = VideoCaptureHostProxy;
template <typename ImplRefTraits>
using Stub_ = VideoCaptureHostStub<ImplRefTraits>;
using RequestValidator_ = VideoCaptureHostRequestValidator;
using ResponseValidator_ = VideoCaptureHostResponseValidator;
enum MethodMinVersions : uint32_t {
kStartMinVersion = 0,
kStopMinVersion = 0,
kPauseMinVersion = 0,
kResumeMinVersion = 0,
kRequestRefreshFrameMinVersion = 0,
kReleaseBufferMinVersion = 0,
kGetDeviceSupportedFormatsMinVersion = 0,
kGetDeviceFormatsInUseMinVersion = 0,
kOnFrameDroppedMinVersion = 0,
kOnLogMinVersion = 0,
};
virtual ~VideoCaptureHost() {}
virtual void Start(const ::base::UnguessableToken& device_id, const ::base::UnguessableToken& session_id, const ::media::VideoCaptureParams& params, mojo::PendingRemote<VideoCaptureObserver> observer) = 0;
virtual void Stop(const ::base::UnguessableToken& device_id) = 0;
virtual void Pause(const ::base::UnguessableToken& device_id) = 0;
virtual void Resume(const ::base::UnguessableToken& device_id, const ::base::UnguessableToken& session_id, const ::media::VideoCaptureParams& params) = 0;
virtual void RequestRefreshFrame(const ::base::UnguessableToken& device_id) = 0;
virtual void ReleaseBuffer(const ::base::UnguessableToken& device_id, int32_t buffer_id, double consumer_resource_utilization) = 0;
using GetDeviceSupportedFormatsCallback = base::OnceCallback<void(const WTF::Vector<::media::VideoCaptureFormat>&)>;
virtual void GetDeviceSupportedFormats(const ::base::UnguessableToken& device_id, const ::base::UnguessableToken& session_id, GetDeviceSupportedFormatsCallback callback) = 0;
using GetDeviceFormatsInUseCallback = base::OnceCallback<void(const WTF::Vector<::media::VideoCaptureFormat>&)>;
virtual void GetDeviceFormatsInUse(const ::base::UnguessableToken& device_id, const ::base::UnguessableToken& session_id, GetDeviceFormatsInUseCallback callback) = 0;
virtual void OnFrameDropped(const ::base::UnguessableToken& device_id, ::media::VideoCaptureFrameDropReason reason) = 0;
virtual void OnLog(const ::base::UnguessableToken& device_id, const WTF::String& message) = 0;
};
class BLINK_PLATFORM_EXPORT VideoCaptureObserverProxy
: public VideoCaptureObserver {
public:
using InterfaceType = VideoCaptureObserver;
explicit VideoCaptureObserverProxy(mojo::MessageReceiverWithResponder* receiver);
void OnStateChanged(VideoCaptureState state) final;
void OnNewBuffer(int32_t buffer_id, ::media::mojom::blink::VideoBufferHandlePtr buffer_handle) final;
void OnBufferReady(int32_t buffer_id, ::media::mojom::blink::VideoFrameInfoPtr info) final;
void OnBufferDestroyed(int32_t buffer_id) final;
private:
mojo::MessageReceiverWithResponder* receiver_;
};
class BLINK_PLATFORM_EXPORT VideoCaptureHostProxy
: public VideoCaptureHost {
public:
using InterfaceType = VideoCaptureHost;
explicit VideoCaptureHostProxy(mojo::MessageReceiverWithResponder* receiver);
void Start(const ::base::UnguessableToken& device_id, const ::base::UnguessableToken& session_id, const ::media::VideoCaptureParams& params, mojo::PendingRemote<VideoCaptureObserver> observer) final;
void Stop(const ::base::UnguessableToken& device_id) final;
void Pause(const ::base::UnguessableToken& device_id) final;
void Resume(const ::base::UnguessableToken& device_id, const ::base::UnguessableToken& session_id, const ::media::VideoCaptureParams& params) final;
void RequestRefreshFrame(const ::base::UnguessableToken& device_id) final;
void ReleaseBuffer(const ::base::UnguessableToken& device_id, int32_t buffer_id, double consumer_resource_utilization) final;
void GetDeviceSupportedFormats(const ::base::UnguessableToken& device_id, const ::base::UnguessableToken& session_id, GetDeviceSupportedFormatsCallback callback) final;
void GetDeviceFormatsInUse(const ::base::UnguessableToken& device_id, const ::base::UnguessableToken& session_id, GetDeviceFormatsInUseCallback callback) final;
void OnFrameDropped(const ::base::UnguessableToken& device_id, ::media::VideoCaptureFrameDropReason reason) final;
void OnLog(const ::base::UnguessableToken& device_id, const WTF::String& message) final;
private:
mojo::MessageReceiverWithResponder* receiver_;
};
class BLINK_PLATFORM_EXPORT VideoCaptureObserverStubDispatch {
public:
static bool Accept(VideoCaptureObserver* impl, mojo::Message* message);
static bool AcceptWithResponder(
VideoCaptureObserver* impl,
mojo::Message* message,
std::unique_ptr<mojo::MessageReceiverWithStatus> responder);
};
template <typename ImplRefTraits =
mojo::RawPtrImplRefTraits<VideoCaptureObserver>>
class VideoCaptureObserverStub
: public mojo::MessageReceiverWithResponderStatus {
public:
using ImplPointerType = typename ImplRefTraits::PointerType;
VideoCaptureObserverStub() {}
~VideoCaptureObserverStub() override {}
void set_sink(ImplPointerType sink) { sink_ = std::move(sink); }
ImplPointerType& sink() { return sink_; }
bool Accept(mojo::Message* message) override {
if (ImplRefTraits::IsNull(sink_))
return false;
return VideoCaptureObserverStubDispatch::Accept(
ImplRefTraits::GetRawPointer(&sink_), message);
}
bool AcceptWithResponder(
mojo::Message* message,
std::unique_ptr<mojo::MessageReceiverWithStatus> responder) override {
if (ImplRefTraits::IsNull(sink_))
return false;
return VideoCaptureObserverStubDispatch::AcceptWithResponder(
ImplRefTraits::GetRawPointer(&sink_), message, std::move(responder));
}
private:
ImplPointerType sink_;
};
class BLINK_PLATFORM_EXPORT VideoCaptureHostStubDispatch {
public:
static bool Accept(VideoCaptureHost* impl, mojo::Message* message);
static bool AcceptWithResponder(
VideoCaptureHost* impl,
mojo::Message* message,
std::unique_ptr<mojo::MessageReceiverWithStatus> responder);
};
template <typename ImplRefTraits =
mojo::RawPtrImplRefTraits<VideoCaptureHost>>
class VideoCaptureHostStub
: public mojo::MessageReceiverWithResponderStatus {
public:
using ImplPointerType = typename ImplRefTraits::PointerType;
VideoCaptureHostStub() {}
~VideoCaptureHostStub() override {}
void set_sink(ImplPointerType sink) { sink_ = std::move(sink); }
ImplPointerType& sink() { return sink_; }
bool Accept(mojo::Message* message) override {
if (ImplRefTraits::IsNull(sink_))
return false;
return VideoCaptureHostStubDispatch::Accept(
ImplRefTraits::GetRawPointer(&sink_), message);
}
bool AcceptWithResponder(
mojo::Message* message,
std::unique_ptr<mojo::MessageReceiverWithStatus> responder) override {
if (ImplRefTraits::IsNull(sink_))
return false;
return VideoCaptureHostStubDispatch::AcceptWithResponder(
ImplRefTraits::GetRawPointer(&sink_), message, std::move(responder));
}
private:
ImplPointerType sink_;
};
class BLINK_PLATFORM_EXPORT VideoCaptureObserverRequestValidator : public mojo::MessageReceiver {
public:
bool Accept(mojo::Message* message) override;
};
class BLINK_PLATFORM_EXPORT VideoCaptureHostRequestValidator : public mojo::MessageReceiver {
public:
bool Accept(mojo::Message* message) override;
};
class BLINK_PLATFORM_EXPORT VideoCaptureHostResponseValidator : public mojo::MessageReceiver {
public:
bool Accept(mojo::Message* message) override;
};
} // namespace blink
} // namespace mojom
} // namespace media
namespace mojo {
} // namespace mojo
#endif // MEDIA_CAPTURE_MOJOM_VIDEO_CAPTURE_MOJOM_BLINK_H_ | [
"[email protected]"
] | |
215d1d817d572696f071d847b16a086ab89e34ad | 125f1a9c87eb76d88adec4f17d483bd52ec3c60a | /galaxysv/samples/ModernCpp/multithreading/SyncQueue.hpp | b6b1d5a0cd08e9c886b16f2da655f85be6f48006 | [] | no_license | dongdong-2009/CppProjects | 339dc7e8b99686caa070cb534f3c37acbdebb2d9 | 2d8335a91e28d771e64ee3565809b39d0dca6883 | refs/heads/master | 2021-07-23T09:19:07.044408 | 2017-11-02T07:50:23 | 2017-11-02T07:50:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,789 | hpp | /*
* SyncQueue.hpp
*
* Created on: Apr 8, 2015
* Author: dinglinhui
*/
#ifndef SYNCQUEUE_HPP_
#define SYNCQUEUE_HPP_
#include <list>
#include <mutex>
#include <thread>
#include <condition_variable>
#include <iostream>
namespace cplusplus {
template<typename T>
class SyncQueue {
public:
SyncQueue(int maxSize) :
m_maxSize(maxSize), m_needStop(false) {
}
void Put(const T&x) {
Add(x);
}
void Put(T&&x) {
Add(std::forward<T>(x));
}
void Take(std::list<T>& list) {
std::unique_lock<std::mutex> locker(m_mutex);
m_notEmpty.wait(locker, [this] {return m_needStop || NotEmpty();});
if (m_needStop)
return;
list = std::move(m_queue);
m_notFull.notify_one();
}
void Take(T& t) {
std::unique_lock<std::mutex> locker(m_mutex);
m_notEmpty.wait(locker, [this] {return m_needStop || NotEmpty();});
if (m_needStop)
return;
t = m_queue.front();
m_queue.pop_front();
m_notFull.notify_one();
}
void Stop() {
{
std::lock_guard<std::mutex> locker(m_mutex);
m_needStop = true;
}
m_notFull.notify_all();
m_notEmpty.notify_all();
}
bool Empty() {
std::lock_guard<std::mutex> locker(m_mutex);
return m_queue.empty();
}
bool Full() {
std::lock_guard<std::mutex> locker(m_mutex);
return m_queue.size() == m_maxSize;
}
size_t Size() {
std::lock_guard<std::mutex> locker(m_mutex);
return m_queue.size();
}
int Count() {
return m_queue.size();
}
private:
bool NotFull() const {
bool full = m_queue.size() >= m_maxSize;
if (full)
cout << "full, waiting,thread id: " << this_thread::get_id() << endl;
return !full;
}
bool NotEmpty() const {
bool empty = m_queue.empty();
if (empty)
cout << "empty,waiting,thread id: " << this_thread::get_id() << endl;
return !empty;
}
template<typename F>
void Add(F&&x) {
std::unique_lock<std::mutex> locker(m_mutex);
m_notFull.wait(locker, [this] {return m_needStop || NotFull();});
if (m_needStop)
return;
m_queue.push_back(std::forward<F>(x));
m_notEmpty.notify_one();
}
private:
std::list<T> m_queue; //缓冲区
std::mutex m_mutex; //互斥量和条件变量结合起来使用
std::condition_variable m_notEmpty; //不为空的条件变量
std::condition_variable m_notFull; //没有满的条件变量
int m_maxSize; //同步队列最大的size
bool m_needStop; //停止的标志
};
} //namespace cplusplus
#endif /* SYNCQUEUE_HPP_ */
| [
"[email protected]"
] | |
1b31ef65a529fa4e8bba0477823d45b72c5d8b63 | 6b40e9dccf2edc767c44df3acd9b626fcd586b4d | /NT/sdktools/verifier/cmdline.cpp | 7736029aab32db1a42d410136615016247311e41 | [] | no_license | jjzhang166/WinNT5_src_20201004 | 712894fcf94fb82c49e5cd09d719da00740e0436 | b2db264153b80fbb91ef5fc9f57b387e223dbfc2 | refs/heads/Win2K3 | 2023-08-12T01:31:59.670176 | 2021-10-14T15:14:37 | 2021-10-14T15:14:37 | 586,134,273 | 1 | 0 | null | 2023-01-07T03:47:45 | 2023-01-07T03:47:44 | null | UTF-8 | C++ | false | false | 24,494 | cpp | //
// Driver Verifier UI
// Copyright (c) Microsoft Corporation, 1999
//
//
//
// module: CmdLine.cpp
// author: DMihai
// created: 11/1/00
//
// Description:
//
#include "stdafx.h"
#include "verifier.h"
#include "CmdLine.h"
#include "VrfUtil.h"
#include "VGlobal.h"
/////////////////////////////////////////////////////////////////////////////
//
// Execute command line
//
DWORD CmdLineExecute( INT argc, TCHAR *argv[] )
{
BOOL bFoundCmdLineSwitch;
BOOL bHaveNewFlags;
BOOL bHaveNewDrivers;
BOOL bHaveVolatile;
BOOL bVolatileAddDriver;
BOOL bHaveDisk;
DWORD dwExitCode;
DWORD dwNewFlags;
INT_PTR nDrivers;
INT_PTR nCrtDriver;
CStringArray astrNewDrivers;
CString strAllDrivers;
dwExitCode = EXIT_CODE_SUCCESS;
//
// See if the user asked for help
//
bFoundCmdLineSwitch = CmdLineExecuteIfHelp( argc,
argv );
if( TRUE == bFoundCmdLineSwitch )
{
//
// We are done printing out the help strings
//
goto Done;
}
//
// See if the user asked to reset all the existing verifier settings
//
bFoundCmdLineSwitch = CmdLineFindResetSwitch( argc,
argv );
if( TRUE == bFoundCmdLineSwitch )
{
if( VrfDeleteAllVerifierSettings() )
{
if( FALSE != g_bSettingsSaved )
{
//
// Had some non-void verifier settings before
//
dwExitCode = EXIT_CODE_REBOOT_NEEDED;
VrfMesssageFromResource( IDS_REBOOT );
}
else
{
//
// Nothing has changed
//
dwExitCode = EXIT_CODE_SUCCESS;
VrfMesssageFromResource( IDS_NO_SETTINGS_WERE_CHANGED );
}
}
else
{
dwExitCode = EXIT_CODE_ERROR;
}
goto Done;
//
// We are deleting the settings
//
}
//
// See if we need to start logging statistics
//
bFoundCmdLineSwitch = CmdLineExecuteIfLog( argc,
argv );
if( TRUE == bFoundCmdLineSwitch )
{
//
// We are done logging
//
goto Done;
}
//
// See if the user asked to dump the current statistics
// to the console
//
bFoundCmdLineSwitch = CmdLineExecuteIfQuery( argc,
argv );
if( TRUE == bFoundCmdLineSwitch )
{
//
// We are done with the query
//
goto Done;
}
//
// See if the user asked to dump the current registry settings
//
bFoundCmdLineSwitch = CmdLineExecuteIfQuerySettings( argc,
argv );
if( TRUE == bFoundCmdLineSwitch )
{
//
// We are done with the settings query
//
goto Done;
}
//
// Get the new flags, drivers and volatile
// if they have been specified
//
bHaveNewFlags = FALSE;
bHaveNewDrivers = FALSE;
bHaveVolatile = FALSE;
bHaveDisk = FALSE;
CmdLineGetFlagsDriversVolatileDisk(
argc,
argv,
dwNewFlags,
bHaveNewFlags,
astrNewDrivers,
bHaveNewDrivers,
bHaveVolatile,
bVolatileAddDriver,
bHaveDisk);
//
// Enable or disable the disk verifier for all disks.
//
g_NewVerifierSettings.m_aDiskData.SetVerifyAllDisks( bHaveDisk );
g_NewVerifierSettings.m_aDiskData.SaveNewSettings();
if( FALSE != bHaveNewFlags || FALSE != bHaveNewDrivers )
{
//
// Some new drivers, disks and/or flags have been specified.
//
if( FALSE != bHaveVolatile )
{
if( FALSE != bHaveNewFlags || FALSE != bHaveNewDrivers )
{
//
// Have new volative settings
//
if( bHaveNewFlags )
{
VrfSetNewFlagsVolatile( dwNewFlags );
}
else
{
if( astrNewDrivers.GetSize() > 0 )
{
//
// Have some new drivers to add or remove
// from the verify list
//
if( bVolatileAddDriver )
{
//
// Add some drivers
//
VrfAddDriversVolatile( astrNewDrivers );
}
else
{
//
// Remove some drivers
//
VrfRemoveDriversVolatile( astrNewDrivers );
}
}
}
}
}
else
{
//
// Have new persistent settings (registry)
//
//
// Try to get the old settings
//
VrtLoadCurrentRegistrySettings( g_bAllDriversVerified,
g_astrVerifyDriverNamesRegistry,
g_dwVerifierFlagsRegistry );
if( bHaveNewDrivers )
{
//
// Concat all the new driver names in only one string,
// separated with spaces
//
nDrivers = astrNewDrivers.GetSize();
for( nCrtDriver = 0; nCrtDriver < nDrivers; nCrtDriver += 1 )
{
if( strAllDrivers.GetLength() > 0 )
{
strAllDrivers += _T( ' ' );
}
strAllDrivers += astrNewDrivers.ElementAt( nCrtDriver );
}
}
//
// If:
//
// - we are switching to "all drivers verified" OR
// - we are switching to a new set of drivers to be verified OR
// - we are switching to other verifier flags
//
if( ( bHaveNewDrivers &&
strAllDrivers.CompareNoCase( _T( "*" ) ) == 0 &&
TRUE != g_bAllDriversVerified ) ||
( bHaveNewDrivers &&
strAllDrivers.CompareNoCase( _T( "*" ) ) != 0 &&
VrfIsDriversSetDifferent( strAllDrivers, g_astrVerifyDriverNamesRegistry ) ) ||
( bHaveNewFlags && dwNewFlags != g_dwVerifierFlagsRegistry ) )
{
//
// These are different settings from what we had before
//
VrfWriteVerifierSettings( bHaveNewDrivers,
strAllDrivers,
bHaveNewFlags,
dwNewFlags );
}
}
}
if( g_bSettingsSaved )
{
VrfMesssageFromResource( IDS_NEW_SETTINGS );
g_OldDiskData = g_NewVerifierSettings.m_aDiskData;
VrfDumpRegistrySettingsToConsole();
_putts( _T("\n" ) );
VrfMesssageFromResource( IDS_REBOOT );
}
else
{
VrfMesssageFromResource( IDS_NO_SETTINGS_WERE_CHANGED );
}
Done:
return dwExitCode;
}
/////////////////////////////////////////////////////////////////////////////
//
// See if the user asked for help and print out the help strings
//
BOOL CmdLineExecuteIfHelp( INT argc,
TCHAR *argv[] )
{
BOOL bPrintedHelp;
TCHAR szCmdLineSwitch[ 64 ];
bPrintedHelp = FALSE;
VERIFY( VrfLoadString( IDS_HELP_CMDLINE_SWITCH,
szCmdLineSwitch,
ARRAY_LENGTH( szCmdLineSwitch ) ) );
//
// Search for help switch in the command line
//
if( argc == 2 && _tcsicmp( argv[ 1 ], szCmdLineSwitch) == 0)
{
CmdLinePrintHelpInformation();
bPrintedHelp = TRUE;
}
return bPrintedHelp;
}
/////////////////////////////////////////////////////////////////////////////
VOID CmdLinePrintHelpInformation()
{
VrfTPrintfResourceFormat( IDS_HELP_LINE1, VER_PRODUCTVERSION_STR );
puts( VER_LEGALCOPYRIGHT_STR );
VrfPrintStringFromResources( IDS_HELP_LINE3 );
VrfPrintStringFromResources( IDS_HELP_LINE4 );
VrfPrintStringFromResources( IDS_HELP_LINE5 );
VrfPrintStringFromResources( IDS_HELP_LINE6 );
VrfPrintStringFromResources( IDS_HELP_LINE7 );
VrfPrintStringFromResources( IDS_HELP_LINE8 );
VrfPrintStringFromResources( IDS_HELP_LINE9 );
VrfPrintStringFromResources( IDS_HELP_LINE10 );
VrfPrintStringFromResources( IDS_HELP_LINE11 );
VrfPrintStringFromResources( IDS_HELP_LINE12 );
VrfPrintStringFromResources( IDS_HELP_LINE13 );
VrfPrintStringFromResources( IDS_HELP_LINE14 );
VrfPrintStringFromResources( IDS_HELP_LINE15 );
VrfPrintStringFromResources( IDS_HELP_LINE16 );
VrfPrintStringFromResources( IDS_HELP_LINE17 );
VrfPrintStringFromResources( IDS_HELP_LINE18 );
VrfPrintStringFromResources( IDS_HELP_LINE19 );
VrfPrintStringFromResources( IDS_HELP_LINE20 );
VrfPrintStringFromResources( IDS_HELP_LINE21 );
VrfPrintStringFromResources( IDS_HELP_LINE22 );
VrfPrintStringFromResources( IDS_HELP_LINE23 );
VrfPrintStringFromResources( IDS_HELP_LINE24 );
VrfPrintStringFromResources( IDS_HELP_LINE25 );
VrfPrintStringFromResources( IDS_HELP_LINE26 );
VrfPrintStringFromResources( IDS_HELP_LINE27 );
VrfPrintStringFromResources( IDS_HELP_LINE28 );
VrfPrintStringFromResources( IDS_HELP_LINE29 );
VrfPrintStringFromResources( IDS_HELP_LINE30 );
VrfPrintStringFromResources( IDS_HELP_LINE31 );
}
/////////////////////////////////////////////////////////////////////////////
//
// See if the user asked to reset all the existing verifier settings
//
BOOL CmdLineFindResetSwitch( INT argc,
TCHAR *argv[] )
{
BOOL bFound;
TCHAR szCmdLineOption[ 64 ];
bFound = FALSE;
if( 2 == argc )
{
VERIFY( VrfLoadString( IDS_RESET_CMDLINE_SWITCH,
szCmdLineOption,
ARRAY_LENGTH( szCmdLineOption ) ) );
bFound = ( _tcsicmp( argv[ 1 ], szCmdLineOption) == 0 );
}
return bFound;
}
/////////////////////////////////////////////////////////////////////////////
//
// See if we need to start logging statistics
//
BOOL CmdLineExecuteIfLog( INT argc,
TCHAR *argv[] )
{
INT nCrtArg;
BOOL bStartLogging;
LPCTSTR szLogFileName;
DWORD dwLogMillisec;
FILE *file;
TCHAR szLogCmdLineOption[ 64 ];
TCHAR szIntervalCmdLineOption[ 64 ];
bStartLogging = FALSE;
szLogFileName = NULL;
if( argc < 2 )
{
//
// Need at least /log LOG_FILE_NAME IN THE CMD LINE
//
goto Done;
}
//
// Default log period - 30 sec
//
dwLogMillisec = 30000;
VERIFY( VrfLoadString( IDS_LOG_CMDLINE_SWITCH,
szLogCmdLineOption,
ARRAY_LENGTH( szLogCmdLineOption ) ) );
VERIFY( VrfLoadString( IDS_INTERVAL_CMDLINE_SWITCH,
szIntervalCmdLineOption,
ARRAY_LENGTH( szIntervalCmdLineOption ) ) );
for( nCrtArg = 1; nCrtArg < argc - 1; nCrtArg += 1 )
{
if( _tcsicmp( argv[ nCrtArg ], szLogCmdLineOption) == 0 )
{
//
// Start logging
//
bStartLogging = TRUE;
szLogFileName = argv[ nCrtArg + 1 ];
}
else
{
if( _tcsicmp( argv[ nCrtArg ], szIntervalCmdLineOption) == 0 )
{
//
// Logging period
//
dwLogMillisec = _ttoi( argv[ nCrtArg + 1 ] ) * 1000;
}
}
}
if( TRUE == bStartLogging )
{
ASSERT( szLogFileName != NULL );
while( TRUE )
{
//
// Open the file
//
file = _tfopen( szLogFileName, TEXT("a+") );
if( file == NULL )
{
//
// print a error message
//
VrfTPrintfResourceFormat(
IDS_CANT_APPEND_FILE,
szLogFileName );
break;
}
//
// Dump current information
//
if( ! VrfDumpStateToFile ( file ) )
{
//
// Insufficient disk space ?
//
VrfTPrintfResourceFormat(
IDS_CANT_WRITE_FILE,
szLogFileName );
}
fflush( file );
VrfFTPrintf(
file,
TEXT("\n\n") );
//
// Close the file
//
fclose( file );
//
// Sleep
//
Sleep( dwLogMillisec );
}
}
Done:
return bStartLogging;
}
/////////////////////////////////////////////////////////////////////////////
//
// See if we need to dump the statistics to the console
//
BOOL CmdLineExecuteIfQuery( INT argc,
TCHAR *argv[] )
{
BOOL bFoundCmdLineSwitch;
TCHAR szCmdLineSwitch[ 64 ];
bFoundCmdLineSwitch = FALSE;
VERIFY( VrfLoadString( IDS_QUERY_CMDLINE_SWITCH,
szCmdLineSwitch,
ARRAY_LENGTH( szCmdLineSwitch ) ) );
//
// Search for our switch in the command line
//
if( argc == 2 && _tcsicmp( argv[1], szCmdLineSwitch) == 0)
{
bFoundCmdLineSwitch = TRUE;
VrfDumpStateToFile( stdout );
}
return bFoundCmdLineSwitch;
}
/////////////////////////////////////////////////////////////////////////////
//
// See if we need to dump the statistics to the console
//
BOOL CmdLineExecuteIfQuerySettings( INT argc,
TCHAR *argv[] )
{
BOOL bFoundCmdLineSwitch;
TCHAR szCmdLineSwitch[ 64 ];
bFoundCmdLineSwitch = FALSE;
VERIFY( VrfLoadString( IDS_QUERYSETT_CMDLINE_SWITCH,
szCmdLineSwitch,
ARRAY_LENGTH( szCmdLineSwitch ) ) );
//
// Search for our switch in the command line
//
if( argc == 2 && _tcsicmp( argv[1], szCmdLineSwitch) == 0)
{
bFoundCmdLineSwitch = TRUE;
VrfDumpRegistrySettingsToConsole();
}
return bFoundCmdLineSwitch;
}
/////////////////////////////////////////////////////////////////////////////
//
// Get the new flags, drivers and volatile
// if they have been specified
//
VOID CmdLineGetFlagsDriversVolatileDisk( INT argc,
TCHAR *argv[],
DWORD &dwNewFlags,
BOOL &bHaveNewFlags,
CStringArray &astrNewDrivers,
BOOL &bHaveNewDrivers,
BOOL &bHaveVolatile,
BOOL &bVolatileAddDriver,
BOOL &bHaveDisk)
{
INT nCrtArg;
NTSTATUS Status;
UNICODE_STRING ustrFlags;
TCHAR szFlagsCmdLineOption[ 64 ];
TCHAR szDiskCmdLineOption[ 64 ];
TCHAR szAllCmdLineOption[ 64 ];
TCHAR szVolatileCmdLineOption[ 64 ];
TCHAR szDriversCmdLineOption[ 64 ];
TCHAR szAddDriversCmdLineOption[ 64 ];
TCHAR szRemoveDriversCmdLineOption[ 64 ];
TCHAR szStandardCmdLineOption[ 64 ];
#ifndef UNICODE
//
// ANSI
//
INT nNameLength;
LPWSTR szUnicodeName;
#endif //#ifndef UNICODE
astrNewDrivers.RemoveAll();
bHaveNewFlags = FALSE;
bHaveNewDrivers = FALSE;
bHaveVolatile = FALSE;
bHaveDisk = FALSE;
//
// Load the switches from the resources
//
VERIFY( VrfLoadString( IDS_FLAGS_CMDLINE_SWITCH,
szFlagsCmdLineOption,
ARRAY_LENGTH( szFlagsCmdLineOption ) ) );
VERIFY( VrfLoadString( IDS_DISK_CMDLINE_SWITCH,
szDiskCmdLineOption,
ARRAY_LENGTH( szDiskCmdLineOption ) ) );
VERIFY( VrfLoadString( IDS_ALL_CMDLINE_SWITCH,
szAllCmdLineOption,
ARRAY_LENGTH( szAllCmdLineOption ) ) );
VERIFY( VrfLoadString( IDS_DONTREBOOT_CMDLINE_SWITCH,
szVolatileCmdLineOption,
ARRAY_LENGTH( szVolatileCmdLineOption ) ) );
VERIFY( VrfLoadString( IDS_DRIVER_CMDLINE_SWITCH,
szDriversCmdLineOption,
ARRAY_LENGTH( szDriversCmdLineOption ) ) );
VERIFY( VrfLoadString( IDS_ADDDRIVER_CMDLINE_SWITCH,
szAddDriversCmdLineOption,
ARRAY_LENGTH( szAddDriversCmdLineOption ) ) );
VERIFY( VrfLoadString( IDS_REMOVEDRIVER_CMDLINE_SWITCH,
szRemoveDriversCmdLineOption,
ARRAY_LENGTH( szRemoveDriversCmdLineOption ) ) );
VERIFY( VrfLoadString( IDS_STANDARD_CMDLINE_SWITCH,
szStandardCmdLineOption,
ARRAY_LENGTH( szStandardCmdLineOption ) ) );
//
// Parse all the cmd line arguments, looking for ours
//
for( nCrtArg = 1; nCrtArg < argc; nCrtArg += 1 )
{
if( _tcsicmp( argv[ nCrtArg ], szFlagsCmdLineOption) == 0 )
{
if( nCrtArg < argc - 1 )
{
//
// Not the last cmd line arg - look for the flags next
//
#ifdef UNICODE
//
// UNICODE
//
RtlInitUnicodeString( &ustrFlags,
argv[ nCrtArg + 1 ] );
#else
//
// ANSI
//
nNameLength = strlen( argv[ nCrtArg + 1 ] );
szUnicodeName = new WCHAR[ nNameLength + 1 ];
if( NULL == szUnicodeName )
{
VrfErrorResourceFormat( IDS_NOT_ENOUGH_MEMORY );
goto DoneWithFlags;
}
MultiByteToWideChar( CP_ACP,
0,
argv[ nCrtArg + 1 ],
-1,
szUnicodeName,
nNameLength + 1 );
RtlInitUnicodeString( &ustrFlags,
szUnicodeName );
#endif
Status = RtlUnicodeStringToInteger( &ustrFlags,
0,
&dwNewFlags );
if( NT_SUCCESS( Status ) )
{
bHaveNewFlags = TRUE;
}
#ifndef UNICODE
//
// ANSI
//
ASSERT( NULL != szUnicodeName );
delete [] szUnicodeName;
szUnicodeName = NULL;
DoneWithFlags:
NOTHING;
#endif
}
}
else if( _tcsicmp( argv[ nCrtArg ], szDiskCmdLineOption) == 0 )
{
//
// Verify all disks.
//
bHaveVolatile = FALSE;
bHaveDisk = TRUE;
}
else if( _tcsicmp( argv[ nCrtArg ], szAllCmdLineOption) == 0 )
{
//
// Verify all drivers.
//
bHaveVolatile = FALSE;
astrNewDrivers.Add( _T( '*' ) );
bHaveNewDrivers = TRUE;
}
else if( _tcsicmp( argv[ nCrtArg ], szStandardCmdLineOption) == 0 )
{
//
// Standard verifier flags.
//
dwNewFlags = VrfGetStandardFlags();
bHaveNewFlags = TRUE;
}
else if( _tcsicmp( argv[ nCrtArg ], szVolatileCmdLineOption) == 0 )
{
//
// Volatile
//
bHaveVolatile = TRUE;
}
else if( _tcsicmp( argv[ nCrtArg ], szDriversCmdLineOption) == 0 )
{
//
// /Driver
//
bHaveVolatile = FALSE;
CmdLineGetDriversFromArgv( argc,
argv,
nCrtArg + 1,
astrNewDrivers,
bHaveNewDrivers );
//
// All done - all the rest of argumentshave been driver names
//
break;
}
else if( bHaveVolatile && _tcsicmp( argv[ nCrtArg ], szAddDriversCmdLineOption) == 0 )
{
//
// /adddriver
//
bVolatileAddDriver = TRUE;
CmdLineGetDriversFromArgv( argc,
argv,
nCrtArg + 1,
astrNewDrivers,
bHaveNewDrivers );
//
// All done - all the rest of argumentshave been driver names
//
break;
}
else if( bHaveVolatile && _tcsicmp( argv[ nCrtArg ], szRemoveDriversCmdLineOption) == 0 )
{
//
// /removedriver
//
bVolatileAddDriver = FALSE;
CmdLineGetDriversFromArgv( argc,
argv,
nCrtArg + 1,
astrNewDrivers,
bHaveNewDrivers );
//
// All done - all the rest of arguments have been driver names
//
break;
}
}
//
// If we have new drivers look if they are miniports
//
if( bHaveNewDrivers )
{
VrfAddMiniports( astrNewDrivers );
}
}
/////////////////////////////////////////////////////////////////////////////
//
// Everything that follows after /driver, /adddriver, /removedriver
// should be driver names. Extract these from the command line
//
VOID CmdLineGetDriversFromArgv( INT argc,
TCHAR *argv[],
INT nFirstDriverArgIndex,
CStringArray &astrNewDrivers,
BOOL &bHaveNewDrivers )
{
INT nDriverArg;
bHaveNewDrivers = FALSE;
astrNewDrivers.RemoveAll();
//
// Everything in the command line from here on should be driver names
//
for( nDriverArg = nFirstDriverArgIndex; nDriverArg < argc; nDriverArg += 1 )
{
astrNewDrivers.Add( argv[ nDriverArg ] );
}
bHaveNewDrivers = ( astrNewDrivers.GetSize() > 0 );
}
| [
"[email protected]"
] | |
5fba0046207c49ddbc93bbba6b1fb45c8778934e | b967295eb531575eb39ef0b2f0d83c4297808fd8 | /packages/eigen-eigen-323c052e1731/doc/examples/Tutorial_ReductionsVisitorsBroadcasting_visitors.cpp | 6618630c7d1ffa977dfc9b21f998608adba331d6 | [
"MPL-2.0",
"Minpack",
"LGPL-2.1-only",
"BSD-3-Clause",
"GPL-3.0-only",
"LGPL-2.0-or-later",
"LGPL-2.1-or-later",
"Apache-2.0"
] | permissive | ai-techsystems/dnnc-operators | de9dc196db343003b6f3506dc0e502d59df2689f | 55e682c0318091c4ee87a8e67134a31042c393e1 | refs/heads/master | 2020-07-02T16:08:37.965213 | 2019-08-29T14:38:52 | 2019-08-29T14:38:52 | 201,582,638 | 5 | 7 | Apache-2.0 | 2019-09-06T18:31:19 | 2019-08-10T05:06:16 | C++ | UTF-8 | C++ | false | false | 557 | cpp | #include <iostream>
#include <Eigen/Dense>
using namespace std;
using namespace Eigen;
int main()
{
Eigen::MatrixXf m(2,2);
m << 1, 2,
3, 4;
//get location of maximum
MatrixXf::Index maxRow, maxCol;
float max = m.maxCoeff(&maxRow, &maxCol);
//get location of minimum
MatrixXf::Index minRow, minCol;
float min = m.minCoeff(&minRow, &minCol);
cout << "Max: " << max << ", at: " <<
maxRow << "," << maxCol << endl;
cout << "Min: " << min << ", at: " <<
minRow << "," << minCol << endl;
}
| [
"[email protected]"
] | |
19f815caaaab27bd7e82406ba525930121eddd24 | d1caf0c064786a878a292fe12bf457a1fb50df25 | /CommNavigationObjects/smartsoft/src/CommNavigationObjects/CommCorridorNavigationPoseRequestEventState.hh | 1220b3b766e1f423a7b5f31de6b3fbbdfe31a853 | [
"BSD-3-Clause"
] | permissive | Servicerobotics-Ulm/DomainModelsRepositories | 8dc395bf62fe386564ba56d8b52f7e5ee90f8d5e | f4d83111d435510a79f69acb78f14a23d2af5539 | refs/heads/master | 2022-05-19T00:55:15.782791 | 2022-05-04T16:14:21 | 2022-05-04T16:14:21 | 122,947,911 | 0 | 8 | BSD-3-Clause | 2021-02-10T11:54:39 | 2018-02-26T09:44:24 | C++ | UTF-8 | C++ | false | false | 2,391 | hh | //--------------------------------------------------------------------------
// Code generated by the SmartSoft MDSD Toolchain
// The SmartSoft Toolchain has been developed by:
//
// Service Robotics Research Center
// University of Applied Sciences Ulm
// Prittwitzstr. 10
// 89075 Ulm (Germany)
//
// Information about the SmartSoft MDSD Toolchain is available at:
// www.servicerobotik-ulm.de
//
// This file is generated once. Modify this file to your needs.
// If you want the toolchain to re-generate this file, please
// delete it before running the code generator.
//--------------------------------------------------------------------------
#ifndef COMMNAVIGATIONOBJECTS_COMMCORRIDORNAVIGATIONPOSEREQUESTEVENTSTATE_H_
#define COMMNAVIGATIONOBJECTS_COMMCORRIDORNAVIGATIONPOSEREQUESTEVENTSTATE_H_
#include "CommNavigationObjects/CommCorridorNavigationPoseRequestEventStateCore.hh"
namespace CommNavigationObjects {
class CommCorridorNavigationPoseRequestEventState : public CommCorridorNavigationPoseRequestEventStateCore {
public:
// default constructors
CommCorridorNavigationPoseRequestEventState();
/**
* Constructor to set all values.
* NOTE that you have to keep this constructor consistent with the model!
* Use at your own choice.
*
* The preferred way to set values for initialization is:
* CommRepository::MyCommObject obj;
* obj.setX(1).setY(2).setZ(3)...;
*/
// CommCorridorNavigationPoseRequestEventState(const CommNavigationObjects::NodeRequestAnserType &newState);
CommCorridorNavigationPoseRequestEventState(const CommCorridorNavigationPoseRequestEventStateCore &commCorridorNavigationPoseRequestEventState);
CommCorridorNavigationPoseRequestEventState(const DATATYPE &commCorridorNavigationPoseRequestEventState);
virtual ~CommCorridorNavigationPoseRequestEventState();
// use framework specific getter and setter methods from core (base) class
using CommCorridorNavigationPoseRequestEventStateCore::get;
using CommCorridorNavigationPoseRequestEventStateCore::set;
//
// feel free to add customized methods here
//
};
inline std::ostream &operator<<(std::ostream &os, const CommCorridorNavigationPoseRequestEventState &co)
{
co.to_ostream(os);
return os;
}
} /* namespace CommNavigationObjects */
#endif /* COMMNAVIGATIONOBJECTS_COMMCORRIDORNAVIGATIONPOSEREQUESTEVENTSTATE_H_ */
| [
"[email protected]"
] | |
274a2601db4f1b55986013144a71b54316ac426f | 1c08c04bb2e21d6c255adc71ba3f3a3bf12c2e13 | /MagLua/ModuleSelect.h | 5538e28b8ee142c90474ddd47c14ae248b005e88 | [] | no_license | denkisdeng/maglua | 0e0b9faeee92b266c4b0aa8aca82dda4e8f49d58 | 48a26a7bced05ae8d840a06afc6f0b3a686133b6 | refs/heads/master | 2020-03-24T22:40:43.935202 | 2016-08-02T00:37:23 | 2016-08-02T00:37:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 385 | h | #ifndef MODULESELECT_H
#define MODULESELECT_H
#include <QDialog>
#include <QtGui>
namespace Ui {
class ModuleSelect;
}
class ModuleSelect : public QDialog
{
Q_OBJECT
public:
explicit ModuleSelect(QWidget *parent = 0);
~ModuleSelect();
QStringList mods;
public slots:
void add();
void remove();
private:
Ui::ModuleSelect *ui;
};
#endif // MODULESELECT_H
| [
"[email protected]"
] | |
5a1d257dda109287c0919cf0839d1eea24c6cbe8 | de3008b1532421bf9ea53bbdd3256f853cf13e51 | /T2K/T2K Practice Task/0.4.1/Python/nd280/ND__TReconPerformanceEvalModule.h | 2ffc0a83b6b94588e79043aecbecfb30353860ac | [] | no_license | BenjaminTMilnes/UOWFourthYearProjectOriginal | e0eef7c5f2cf65c8fb0bb12f029132709cdc1afb | d617af7751228cb18d85293e74f1eaf5279b2c8d | refs/heads/master | 2021-08-24T12:29:50.316743 | 2017-12-09T21:26:16 | 2017-12-09T21:26:16 | 113,700,704 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,614 | h | //////////////////////////////////////////////////////////
// This class has been generated by TFile::MakeProject
// (Wed Nov 21 16:59:10 2012 by ROOT version 5.32/00)
// from the StreamerInfo in file /storage/epp2/phseaj/exercise/prod5_analysis.root
//////////////////////////////////////////////////////////
#ifndef ND__TReconPerformanceEvalModule_h
#define ND__TReconPerformanceEvalModule_h
namespace ND {
class TReconPerformanceEvalModule;
} // end of namespace.
#include "ND__TAnalysisReconModuleBase.h"
#include "TClonesArray.h"
#include "Riostream.h"
#include <map>
#include "TObject.h"
#include <string>
#include "TLorentzVector.h"
#include "TVector3.h"
#include "ND__TReconPerformanceEvalModule.h"
namespace ND {
class TReconPerformanceEvalModule : public ND::TAnalysisReconModuleBase {
public:
// Nested classes forward declaration.
class TGlobalReconObject;
class TGlobalTruthInfo;
public:
// Nested classes declaration.
class TGlobalTruthInfo : public TObject {
public:
// Nested classes declaration.
public:
// Data Members.
bool SetOK; //
double Momentum; /// < Momentum of the true trajectory
TVector3 Direction; /// < Direction of the true trajectory
double Charge; /// < Charge of the trajectory
TLorentzVector Position; /// < Initial position of the trajectory
double Efficiency; /// < Efficiency of this truth matching
double Purity; /// < Purity of this truth matching
TGlobalTruthInfo();
TGlobalTruthInfo(const TGlobalTruthInfo & );
virtual ~TGlobalTruthInfo();
ClassDef(TGlobalTruthInfo,2); // Generated by MakeProject.
};
class TGlobalReconObject : public TObject {
public:
// Nested classes declaration.
public:
// Data Members.
bool SetOK; //
Int_t NConstituents; //
map<string,int>* NModuleConstituents; //
string SubdetectorString; //
string StatusString; //
TClonesArray* GlobalNodes; //
Int_t NGlobalNodes; //
Int_t NGlobalNodesSaved; //
double Momentum; //
TLorentzVector Position; //
TVector3 Direction; //
double Charge; //
double Quality; //
int NDOF; //
string ParticleID; //
double PIDWeight; //
TClonesArray* MatchingChi2Info; //
int NMatchingChi2Info; //
ND::TReconPerformanceEvalModule::TGlobalTruthInfo Truth; //
TClonesArray* Constituents; //
TClonesArray* DownToTrackerConstituents; //
Int_t NDownToTrackerConstituents; //
TGlobalReconObject();
TGlobalReconObject(const TGlobalReconObject & );
virtual ~TGlobalReconObject();
ClassDef(TGlobalReconObject,2); // Generated by MakeProject.
};
public:
// Data Members.
Int_t fNGlobalReconObjects; //
TClonesArray* fGlobalReconObjects; //
std::vector<std::pair<std::string,int> > fHitInfo; //
bool fSaveAllGlobalNodes; //
TReconPerformanceEvalModule();
TReconPerformanceEvalModule(const TReconPerformanceEvalModule & );
virtual ~TReconPerformanceEvalModule();
ClassDef(TReconPerformanceEvalModule,2); // Generated by MakeProject.
};
} // namespace
#endif
| [
"[email protected]"
] | |
1a1c3745952fad4503d95a44730b7d59be6b7ec7 | 2b666b00b3d27e0ede6d94109a79d82d5eb4f654 | /toyjvm/utilities/javautils.h | 88ce60f4665e6ae6e70193dde2843b06267844a5 | [] | no_license | lemononse/ToyJVM | 3e2062e22cb383b2146867ee733f9bd61987ecd1 | a64fe96f5cce5366221c0a130323f48d5e9d5d9d | refs/heads/master | 2021-09-14T09:13:32.783927 | 2018-05-11T04:45:56 | 2018-05-11T04:45:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 367 | h | //
// Created by cyhone on 18-4-23.
//
#ifndef TOYJVM_JAVAUTILS_H
#define TOYJVM_JAVAUTILS_H
#include <string>
namespace jvm {
std::string getPackageName(const std::string &class_name);
std::string descriptorToClassName(const std::string& descriptor);
std::string classNameToDescriptor(const std::string& descriptor);
}
#endif //TOYJVM_JAVA_UTILS_H
| [
"[email protected]"
] | |
84a5c0559fd03774275f8685511588d01ecfea76 | 7fb149b31b9321fc14396dad040fabf7e6e6eb52 | /build/tmp/expandedArchives/hal-cpp-2019.2.1-sources.zip_9dcb46c9ade4c7c133c75a9dc6ab4149/sim/mockdata/DIOData.cpp | ea66de328f776847f180487fa032db9d1d4fa7be | [
"BSD-3-Clause"
] | permissive | FRCTeam5458DigitalMinds/Axon | 4feb4e7cc1a50d93d77c204dbf6cca863850ba3f | af571142de3f9d6589252c89537210015a1a26a0 | refs/heads/master | 2020-04-18T20:14:50.004225 | 2019-10-30T03:05:29 | 2019-10-30T03:05:29 | 167,732,922 | 3 | 0 | BSD-3-Clause | 2019-03-11T01:25:14 | 2019-01-26T20:00:28 | C++ | UTF-8 | C++ | false | false | 1,810 | cpp | /*----------------------------------------------------------------------------*/
/* Copyright (c) 2017-2018 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#include "../PortsInternal.h"
#include "DIODataInternal.h"
using namespace hal;
namespace hal {
namespace init {
void InitializeDIOData() {
static DIOData sdd[kNumDigitalChannels];
::hal::SimDIOData = sdd;
}
} // namespace init
} // namespace hal
DIOData* hal::SimDIOData;
void DIOData::ResetData() {
initialized.Reset(false);
value.Reset(true);
pulseLength.Reset(0.0);
isInput.Reset(true);
filterIndex.Reset(-1);
}
extern "C" {
void HALSIM_ResetDIOData(int32_t index) { SimDIOData[index].ResetData(); }
#define DEFINE_CAPI(TYPE, CAPINAME, LOWERNAME) \
HAL_SIMDATAVALUE_DEFINE_CAPI(TYPE, HALSIM, DIO##CAPINAME, SimDIOData, \
LOWERNAME)
DEFINE_CAPI(HAL_Bool, Initialized, initialized)
DEFINE_CAPI(HAL_Bool, Value, value)
DEFINE_CAPI(double, PulseLength, pulseLength)
DEFINE_CAPI(HAL_Bool, IsInput, isInput)
DEFINE_CAPI(int32_t, FilterIndex, filterIndex)
#define REGISTER(NAME) \
SimDIOData[index].NAME.RegisterCallback(callback, param, initialNotify)
void HALSIM_RegisterDIOAllCallbacks(int32_t index, HAL_NotifyCallback callback,
void* param, HAL_Bool initialNotify) {
REGISTER(initialized);
REGISTER(value);
REGISTER(pulseLength);
REGISTER(isInput);
REGISTER(filterIndex);
}
} // extern "C"
| [
"[email protected]"
] | |
c55a5a095765fea75ef58a3d2e60c19465a29314 | b19d8a737ac7c5debb4bf914df7b10add6e030b2 | /laser-radar-arduino/laser-radar-arduino.ino | f6baf11ff7782b2d30a2f27448f30ce7d3ec35be | [] | no_license | CalebJ2/laser-radar | 10f4cb24a5e66cc18d4d8dc8b97c7408eca2f3ea | 2f2053a2d0101cb0f1b4d05037fdeb202cefd0e5 | refs/heads/master | 2020-11-24T20:36:17.360962 | 2019-12-16T08:26:34 | 2019-12-16T08:26:34 | 228,332,401 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,511 | ino | /* This example shows how to get single-shot range
measurements from the VL53L0X. The sensor can optionally be
configured with different ranging profiles, as described in
the VL53L0X API user manual, to get better performance for
a certain application. This code is based on the four
"SingleRanging" examples in the VL53L0X API.
The range readings are in units of mm. */
#include <Wire.h>
#include <VL53L0X.h>
#include<Servo.h>
long duration;
int distance;
int servoAngle = 15;
bool servoInc = true;
long startMil;
Servo servo;
VL53L0X sensor;
// Uncomment this line to use long range mode. This
// increases the sensitivity of the sensor and extends its
// potential range, but increases the likelihood of getting
// an inaccurate reading because of reflections from objects
// other than the intended target. It works best in dark
// conditions.
//#define LONG_RANGE
// Uncomment ONE of these two lines to get
// - higher speed at the cost of lower accuracy OR
// - higher accuracy at the cost of lower speed
//#define HIGH_SPEED
//#define HIGH_ACCURACY
void setup()
{
startMil = millis();
pinMode(13, OUTPUT);
digitalWrite(13, HIGH); // power for sensor
Serial.begin(9600);
while (!Serial) { } // wait for serial port to connect. Needed for Leonardo
Wire.begin();
sensor.init();
sensor.setTimeout(500);
servo.attach(9);
#if defined LONG_RANGE
// lower the return signal rate limit (default is 0.25 MCPS)
sensor.setSignalRateLimit(0.1);
// increase laser pulse periods (defaults are 14 and 10 PCLKs)
sensor.setVcselPulsePeriod(VL53L0X::VcselPeriodPreRange, 18);
sensor.setVcselPulsePeriod(VL53L0X::VcselPeriodFinalRange, 14);
#endif
#if defined HIGH_SPEED
// reduce timing budget to 20 ms (default is about 33 ms)
sensor.setMeasurementTimingBudget(20000);
#elif defined HIGH_ACCURACY
// increase timing budget to 200 ms
sensor.setMeasurementTimingBudget(200000);
#endif
}
void loop()
{
//Serial.print(sensor.readRangeSingleMillimeters()); // max 8190
if (sensor.timeoutOccurred()) { Serial.print("TIMEOUT"); }
if (servoAngle < 15 || servoAngle > 165) { servoInc = !servoInc; }
servoAngle += servoInc ? 1 : -1;
servo.write(servoAngle);
distance=sensor.readRangeSingleMillimeters();
Serial.print(servoAngle);
Serial.print(",");
Serial.print(distance);
Serial.print(".");
delayAtLeast(50);
}
void delayAtLeast(int mil) {
int diff = constrain(millis()-startMil, 0, mil);
delay(mil - diff);
startMil = millis();
}
| [
"[email protected]"
] | |
813d34fd8244945280e1fa78e7aebff3f1baad41 | c64b52ee275e7e69e6c10c6b11398e6297e1a7cf | /Md1View.h | 988e3e5858f7f0ca3fb811984b85489b4c10067b | [] | no_license | jhkim16/Middle | e1bc9a9e4f4103698f8be694f5644ac47805783b | 2fd21ca2e0e920093d7df51a7dbb523800cf829d | refs/heads/master | 2020-08-14T15:37:41.481418 | 2019-10-15T03:14:43 | 2019-10-15T03:14:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,259 | h |
// Md1View.h: CMd1View 클래스의 인터페이스
//
#pragma once
class CMd1View : public CView
{
protected: // serialization에서만 만들어집니다.
CMd1View() noexcept;
DECLARE_DYNCREATE(CMd1View)
// 특성입니다.
public:
CMd1Doc* GetDocument() const;
// 작업입니다.
public:
CPoint pnt;
COLORREF col;
int size;
// 재정의입니다.
public:
virtual void OnDraw(CDC* pDC); // 이 뷰를 그리기 위해 재정의되었습니다.
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);
// 구현입니다.
public:
virtual ~CMd1View();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
// 생성된 메시지 맵 함수
protected:
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
afx_msg void OnSize1();
afx_msg void OnSize16();
afx_msg void OnSize32();
afx_msg void OnMenuColor();
};
#ifndef _DEBUG // Md1View.cpp의 디버그 버전
inline CMd1Doc* CMd1View::GetDocument() const
{ return reinterpret_cast<CMd1Doc*>(m_pDocument); }
#endif
| [
"[email protected]"
] | |
7dd3e209f064b678a39e2cc195a76a496c97ef4e | adbc979313cbc1f0d42c79ac4206d42a8adb3234 | /Source Code/李沿橙 2017-10-5/competition/source/192.168.0.81_株洲二中 薛宇翔/forest.cpp | e5581a8e037967ff63298a2a9d9232baeb08fe76 | [] | no_license | UnnamedOrange/Contests | a7982c21e575d1342d28c57681a3c98f8afda6c0 | d593d56921d2cde0c473b3abedb419bef4cf3ba4 | refs/heads/master | 2018-10-22T02:26:51.952067 | 2018-07-21T09:32:29 | 2018-07-21T09:32:29 | 112,301,400 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 518 | cpp | #include<bits/stdc++.h>
using namespace std;
int read()
{
int x=0,y=1;char c=getchar();
while(c>'9'||c<'0'){if(c=='-')y=-1;c=getchar();}
while(c>='0'&&c<='9'){x=x*10+c-'0';c=getchar();}
return x*y;
}
int n,num[100007],l[100007][2];
int main()
{
freopen("forest.in","r",stdin);
freopen("forest.out","w",stdout);
n=read();
for(int i=1;i<=n;i++)num[i]=read();
for(int i=1;i<n;i++)l[i][0]=read(),l[i][1]=read();
for(int i=1;i<n;i++){
int a=read();
}
cout<<"6"<<endl<<"9"<<endl<<"6"<<endl;
return 0;
}
| [
"[email protected]"
] | |
ba552327d282228f62cb55d3f7a89abd2079bb38 | dec4ef167e1ce49062645cbf036be324ea677b5e | /SDK/PUBG_Motorbike_Seat_Passenger_classes.hpp | f465279428792dc16e14b10f27e7c1394ef47ff6 | [] | no_license | qrluc/pubg-sdk-3.7.19.5 | 519746887fa2204f27f5c16354049a8527367bfb | 583559ee1fb428e8ba76398486c281099e92e011 | refs/heads/master | 2021-04-15T06:40:38.144620 | 2018-03-26T00:55:36 | 2018-03-26T00:55:36 | 126,754,368 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 717 | hpp | #pragma once
// PlayerUnknown's Battlegrounds (3.5.7.7) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "PUBG_Motorbike_Seat_Passenger_structs.hpp"
namespace PUBG
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass Motorbike_Seat_Passenger.Motorbike_Seat_Passenger_C
// 0x0000 (0x0464 - 0x0464)
class AMotorbike_Seat_Passenger_C : public AVehicleSeatBase_Moto_C
{
public:
static UClass* StaticClass()
{
static UClass* ptr = nullptr;
if (!ptr) ptr = UObject::FindClass(0xef668803);
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
918068a92be4d04e750863a43f353f52324c5404 | 407bf25050a51b87ad802854192e7bf0a976cca0 | /main/wireless/UdpClient.hpp | 2c4dfbf0b37f7e10c8381e6c0895a0731bb84a4d | [] | no_license | jpan127/esp32-mp3-player | ebebc6ba14152a5c758e39dd2e89024af9a423b5 | 89ff5c8004686b389533f0f5f382bb70323409b7 | refs/heads/master | 2021-08-30T19:22:06.921684 | 2017-12-19T05:16:42 | 2017-12-19T05:16:42 | 114,721,443 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 520 | hpp | #pragma once
#include "UdpSocket.hpp"
#include "WifiStation.hpp"
#include "utilities.h"
#include "credentials.hpp" // Saved ssid and password
#include <freertos/event_groups.h>
class UdpClient : public WifiStation
{
public:
UdpClient(port_t Port);
// Initialize wifi
void Initialize();
// Initializes socket
void InitializeSocket();
// Send packet
void SendPacket(char *packet, int packet_length, port_t port, char *server_ip);
private:
UdpSocket mClientSocket;
}; | [
"[email protected]"
] | |
8ed76867331377f5755b00c95d6bfb4e35905b25 | 39a2c7f286dada6e10405ac1286bfaf8bc3f9510 | /SemanaCasiFinal/frmAgregarNodo.h | a343f8b5896410019e64c846d4297d62b0b82838 | [] | no_license | aldahir123/fafayfa | 18c5fe80de2a6dd06a8a7af8594b5edaa9220808 | 596d94ca9c12c23c79ff46e8a3485df9003a5be5 | refs/heads/master | 2020-11-24T08:10:21.660492 | 2019-12-14T15:32:36 | 2019-12-14T15:32:36 | 228,044,572 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 12,309 | h | #pragma once
namespace SemanaCasiFinal {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
/// <summary>
/// Resumen de frmAgregarNodo
/// </summary>
public ref class frmAgregarNodo : public System::Windows::Forms::Form
{
public:
frmAgregarNodo(void)
{
InitializeComponent();
//
//TODO: agregar código de constructor aquí
//
}
protected:
/// <summary>
/// Limpiar los recursos que se estén utilizando.
/// </summary>
~frmAgregarNodo()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Label^ label1;
protected:
private: System::Windows::Forms::TextBox^ txtNodo;
private: System::Windows::Forms::Label^ label2;
private: System::Windows::Forms::Label^ label3;
private: System::Windows::Forms::TextBox^ txtPesoIzq;
private: System::Windows::Forms::TextBox^ txtPesoDer;
private: System::Windows::Forms::TextBox^ txtNodoDer;
private: System::Windows::Forms::TextBox^ txtNodoIzq;
private: System::Windows::Forms::Label^ label4;
private: System::Windows::Forms::Label^ label5;
private: System::Windows::Forms::Button^ btnInsertar;
private: System::Windows::Forms::Button^ btnAsignar;
private: System::Windows::Forms::Button^ btnCalcular;
private: System::Windows::Forms::DataGridView^ dgvLista;
private: System::Windows::Forms::DataGridViewTextBoxColumn^ colNodo;
private: System::Windows::Forms::DataGridViewTextBoxColumn^ colPI;
private: System::Windows::Forms::DataGridViewTextBoxColumn^ colPD;
private: System::Windows::Forms::DataGridViewTextBoxColumn^ colNodos;
private: System::Windows::Forms::ContextMenuStrip^ contextMenuStrip1;
private: System::ComponentModel::IContainer^ components;
private:
/// <summary>
/// Variable del diseñador requerida.
/// </summary>
#pragma region Windows Form Designer generated code
/// <summary>
/// Método necesario para admitir el Diseñador. No se puede modificar
/// el contenido del método con el editor de código.
/// </summary>
void InitializeComponent(void)
{
this->components = (gcnew System::ComponentModel::Container());
this->label1 = (gcnew System::Windows::Forms::Label());
this->txtNodo = (gcnew System::Windows::Forms::TextBox());
this->label2 = (gcnew System::Windows::Forms::Label());
this->label3 = (gcnew System::Windows::Forms::Label());
this->txtPesoIzq = (gcnew System::Windows::Forms::TextBox());
this->txtPesoDer = (gcnew System::Windows::Forms::TextBox());
this->txtNodoDer = (gcnew System::Windows::Forms::TextBox());
this->txtNodoIzq = (gcnew System::Windows::Forms::TextBox());
this->label4 = (gcnew System::Windows::Forms::Label());
this->label5 = (gcnew System::Windows::Forms::Label());
this->btnInsertar = (gcnew System::Windows::Forms::Button());
this->btnAsignar = (gcnew System::Windows::Forms::Button());
this->btnCalcular = (gcnew System::Windows::Forms::Button());
this->dgvLista = (gcnew System::Windows::Forms::DataGridView());
this->colNodo = (gcnew System::Windows::Forms::DataGridViewTextBoxColumn());
this->colPI = (gcnew System::Windows::Forms::DataGridViewTextBoxColumn());
this->colPD = (gcnew System::Windows::Forms::DataGridViewTextBoxColumn());
this->colNodos = (gcnew System::Windows::Forms::DataGridViewTextBoxColumn());
this->contextMenuStrip1 = (gcnew System::Windows::Forms::ContextMenuStrip(this->components));
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->dgvLista))->BeginInit();
this->SuspendLayout();
//
// label1
//
this->label1->AutoSize = true;
this->label1->Location = System::Drawing::Point(25, 22);
this->label1->Name = L"label1";
this->label1->Size = System::Drawing::Size(33, 13);
this->label1->TabIndex = 0;
this->label1->Text = L"Nodo";
//
// txtNodo
//
this->txtNodo->Location = System::Drawing::Point(64, 19);
this->txtNodo->Name = L"txtNodo";
this->txtNodo->Size = System::Drawing::Size(100, 20);
this->txtNodo->TabIndex = 1;
//
// label2
//
this->label2->AutoSize = true;
this->label2->Location = System::Drawing::Point(25, 65);
this->label2->Name = L"label2";
this->label2->Size = System::Drawing::Size(23, 13);
this->label2->TabIndex = 2;
this->label2->Text = L"P.I.";
//
// label3
//
this->label3->AutoSize = true;
this->label3->Location = System::Drawing::Point(136, 65);
this->label3->Name = L"label3";
this->label3->Size = System::Drawing::Size(28, 13);
this->label3->TabIndex = 3;
this->label3->Text = L"P.D.";
//
// txtPesoIzq
//
this->txtPesoIzq->Location = System::Drawing::Point(54, 62);
this->txtPesoIzq->Name = L"txtPesoIzq";
this->txtPesoIzq->Size = System::Drawing::Size(60, 20);
this->txtPesoIzq->TabIndex = 4;
//
// txtPesoDer
//
this->txtPesoDer->Location = System::Drawing::Point(170, 62);
this->txtPesoDer->Name = L"txtPesoDer";
this->txtPesoDer->Size = System::Drawing::Size(60, 20);
this->txtPesoDer->TabIndex = 5;
//
// txtNodoDer
//
this->txtNodoDer->Location = System::Drawing::Point(170, 99);
this->txtNodoDer->Name = L"txtNodoDer";
this->txtNodoDer->Size = System::Drawing::Size(60, 20);
this->txtNodoDer->TabIndex = 9;
//
// txtNodoIzq
//
this->txtNodoIzq->Location = System::Drawing::Point(54, 99);
this->txtNodoIzq->Name = L"txtNodoIzq";
this->txtNodoIzq->Size = System::Drawing::Size(60, 20);
this->txtNodoIzq->TabIndex = 8;
//
// label4
//
this->label4->AutoSize = true;
this->label4->Location = System::Drawing::Point(136, 102);
this->label4->Name = L"label4";
this->label4->Size = System::Drawing::Size(29, 13);
this->label4->TabIndex = 7;
this->label4->Text = L"N.D.";
//
// label5
//
this->label5->AutoSize = true;
this->label5->Location = System::Drawing::Point(25, 102);
this->label5->Name = L"label5";
this->label5->Size = System::Drawing::Size(24, 13);
this->label5->TabIndex = 6;
this->label5->Text = L"N.I.";
//
// btnInsertar
//
this->btnInsertar->Location = System::Drawing::Point(439, 13);
this->btnInsertar->Name = L"btnInsertar";
this->btnInsertar->Size = System::Drawing::Size(75, 23);
this->btnInsertar->TabIndex = 10;
this->btnInsertar->Text = L"Insertar";
this->btnInsertar->UseVisualStyleBackColor = true;
this->btnInsertar->Click += gcnew System::EventHandler(this, &frmAgregarNodo::btnInsertar_Click);
//
// btnAsignar
//
this->btnAsignar->Location = System::Drawing::Point(439, 56);
this->btnAsignar->Name = L"btnAsignar";
this->btnAsignar->Size = System::Drawing::Size(75, 23);
this->btnAsignar->TabIndex = 11;
this->btnAsignar->Text = L"Asignar";
this->btnAsignar->UseVisualStyleBackColor = true;
this->btnAsignar->Click += gcnew System::EventHandler(this, &frmAgregarNodo::btnAsignar_Click);
//
// btnCalcular
//
this->btnCalcular->Location = System::Drawing::Point(439, 99);
this->btnCalcular->Name = L"btnCalcular";
this->btnCalcular->Size = System::Drawing::Size(75, 23);
this->btnCalcular->TabIndex = 12;
this->btnCalcular->Text = L"Calcular";
this->btnCalcular->UseVisualStyleBackColor = true;
this->btnCalcular->Click += gcnew System::EventHandler(this, &frmAgregarNodo::btnCalcular_Click);
//
// dgvLista
//
this->dgvLista->AllowUserToAddRows = false;
this->dgvLista->AllowUserToDeleteRows = false;
this->dgvLista->ColumnHeadersHeightSizeMode = System::Windows::Forms::DataGridViewColumnHeadersHeightSizeMode::AutoSize;
this->dgvLista->Columns->AddRange(gcnew cli::array< System::Windows::Forms::DataGridViewColumn^ >(4) {
this->colNodo, this->colPI,
this->colPD, this->colNodos
});
this->dgvLista->Location = System::Drawing::Point(12, 238);
this->dgvLista->Name = L"dgvLista";
this->dgvLista->ReadOnly = true;
this->dgvLista->Size = System::Drawing::Size(502, 269);
this->dgvLista->TabIndex = 13;
//
// colNodo
//
this->colNodo->HeaderText = L"Nodo";
this->colNodo->Name = L"colNodo";
this->colNodo->ReadOnly = true;
//
// colPI
//
this->colPI->HeaderText = L"P.I.";
this->colPI->Name = L"colPI";
this->colPI->ReadOnly = true;
//
// colPD
//
this->colPD->HeaderText = L"P.D.";
this->colPD->Name = L"colPD";
this->colPD->ReadOnly = true;
//
// colNodos
//
this->colNodos->HeaderText = L"Nodos";
this->colNodos->Name = L"colNodos";
this->colNodos->ReadOnly = true;
//
// contextMenuStrip1
//
this->contextMenuStrip1->Name = L"contextMenuStrip1";
this->contextMenuStrip1->Size = System::Drawing::Size(153, 26);
//
// frmAgregarNodo
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(528, 519);
this->Controls->Add(this->dgvLista);
this->Controls->Add(this->btnCalcular);
this->Controls->Add(this->btnAsignar);
this->Controls->Add(this->btnInsertar);
this->Controls->Add(this->txtNodoDer);
this->Controls->Add(this->txtNodoIzq);
this->Controls->Add(this->label4);
this->Controls->Add(this->label5);
this->Controls->Add(this->txtPesoDer);
this->Controls->Add(this->txtPesoIzq);
this->Controls->Add(this->label3);
this->Controls->Add(this->label2);
this->Controls->Add(this->txtNodo);
this->Controls->Add(this->label1);
this->Name = L"frmAgregarNodo";
this->Text = L"frmAgregarNodo";
this->Load += gcnew System::EventHandler(this, &frmAgregarNodo::frmAgregarNodo_Load);
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->dgvLista))->EndInit();
this->ResumeLayout(false);
this->PerformLayout();
}
char *StringToChar(System::Windows::Forms::TextBox^ textBox) {
String^ val = textBox->Text;
IntPtr ptrToNativeString = Marshal::StringToHGlobalAnsi(val);
char* r = static_cast<char*>(ptrToNativeString.ToPointer());
return r;
}
char *StringToChar(String^ val) {
IntPtr ptrToNativeString = Marshal::StringToHGlobalAnsi(val);
char* r = static_cast<char*>(ptrToNativeString.ToPointer());
return r;
}
#pragma endregion
private: System::Void btnInsertar_Click(System::Object^ sender, System::EventArgs^ e) {
int pesoI = Convert::ToInt32(txtPesoIzq->Text);
int pesoD = Convert::ToInt32(txtPesoDer->Text);
insertarNodo(StringToChar(txtNodo), pesoI, pesoD);
MostrarLista();
}
private: void MostrarLista(){
dgvLista->Rows->Clear();
for (int i = 0; i < cn; i++){
nodoGrafo *nodo = Nodos[i];
String ^ nodosID = "";
if (nodo->izq != NULL && nodo->der){
nodosID = gcnew String(nodo->izq->dato) + "," + gcnew String(nodo->der->dato);
}
dgvLista->Rows->Add(
gcnew String(nodo->dato),
gcnew String(nodo->pi + ""),
gcnew String(nodo->pd + ""),
nodosID
);
}
}
private: System::Void btnAsignar_Click(System::Object^ sender, System::EventArgs^ e) {
if (cn >= 2){
asignarNodo(StringToChar(txtNodo), StringToChar(txtNodoIzq), StringToChar(txtNodoDer));
MostrarLista();
}
else{
MessageBox::Show("Al menos debe haber 3 nodos para asignar");
}
}
private: System::Void frmAgregarNodo_Load(System::Object^ sender, System::EventArgs^ e) {
this->txtPesoDer->KeyPress += gcnew System::Windows::Forms::KeyPressEventHandler(txtPermitirSoloNumeros);
this->txtPesoIzq->KeyPress += gcnew System::Windows::Forms::KeyPressEventHandler(txtPermitirSoloNumeros);
/*
insertarNodo("A", 1, 1);
insertarNodo("B", 1, 1);
insertarNodo("C", 1, 1);
insertarNodo("D", 1, 1);
insertarNodo("E", 1, 1);
asignarNodo("A", "C", "B");
asignarNodo("B", "C", "E");
asignarNodo("C", "E", "D");
asignarNodo("D", "C", "E");
asignarNodo("E", "A", "D");
MostrarLista();*/
}
private: System::Void btnCalcular_Click(System::Object^ sender, System::EventArgs^ e) {
calcularCamino("A", "E");
}
};
}
| [
"[email protected]"
] | |
d4a4bcc42d8f757d2c080a8e7e579fa87e38be2f | c712c82341b30aad4678f6fbc758d6d20bd84c37 | /CAC_Source_1.7884/DangerAliasFace.cpp | d8db155582cfef8dd9005f13143a31fe1ed1c021 | [] | no_license | governmentbg/EPEP_2019_d2 | ab547c729021e1d625181e264bdf287703dcb46c | 5e68240f15805c485505438b27de12bab56df91e | refs/heads/master | 2022-12-26T10:00:41.766991 | 2020-09-28T13:55:30 | 2020-09-28T13:55:30 | 292,803,726 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 380 | cpp | //{{TDangerAliasFace Implementation}}
TDangerAliasFace::TDangerAliasFace(TWindow* parent, int resourceId, const char *name, long tSubject, long flags)
:
TLongAliasFace(parent, resourceId, name, DangerSubject, NULL, flags), subject(tSubject)
{
}
void TDangerAliasFace::Criteria(msql &m, TGroup *group)
{
DangerSubject->subject = subject;
TLongAliasFace::Criteria(m, group);
}
| [
"[email protected]"
] | |
2ab69c67b625c0a9bb7f023f32ee4cc6331178c9 | 6fb44155767dc405f74eef2111307ee0248e28c0 | /src/LxElfCmd.cpp | cb71d9572c9c67f7289352216b4183dd3b75b9a3 | [
"MIT",
"ISC"
] | permissive | emagii/ielftool | e1938e8cf043f65c48522515038032176ee6556c | 3d3729f2d4777063c1255dcb20766097551a811c | refs/heads/main | 2023-03-18T17:35:18.799250 | 2021-03-09T09:03:04 | 2021-03-09T09:04:09 | 345,926,139 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,396 | cpp | ///////////////////////////////// -*- C++ -*- /////////////////////////////////
/*
* Copyright 2007-2017 IAR Systems AB.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/* $Rev: 57699 $ */
// Base class used for transforming an elf file
#include "LxElfCmd.h"
#include "LxElfException.h"
LxElfCmdOffset::
LxElfCmdOffset()
: mOffset(0), mIsNegative(false)
{}
LxElfCmdOffset::
LxElfCmdOffset(uint64_t offs)
: mOffset(offs), mIsNegative(false)
{}
LxElfCmdOffset::
LxElfCmdOffset(int64_t offs)
: mOffset(offs >= 0 ? offs : 0-offs), mIsNegative(offs >= 0 ? false : true)
{}
void LxElfCmdOffset::
SetOffset(uint64_t offs)
{
mOffset = offs;
mIsNegative = false;
}
void LxElfCmdOffset::
SetNegativeOffset(uint64_t offs)
{
mOffset = offs;
mIsNegative = true;
}
template<typename T>
uint64_t LxElfCmdOffset::
ModifyX(uint64_t addr64) const
{
T addr = static_cast<T>(addr64);
T tmp;
if (mIsNegative)
{
tmp = static_cast<T>(addr - mOffset);
if (tmp > addr)
// wrap around
throw LxOffsetException(addr, mOffset, mIsNegative);
}
else
{
tmp = static_cast<T>(addr + mOffset);
if (tmp < addr)
// wrap around
throw LxOffsetException(addr, mOffset, mIsNegative);
}
return tmp;
}
uint64_t LxElfCmdOffset::
Modify(uint64_t addr, bool is64bit) const
{
if (is64bit)
return ModifyX<uint64_t>(addr);
else
return ModifyX<uint32_t>(static_cast<uint32_t>(addr));
}
uint64_t LxElfCmdOffset::
GetOffset() const
{
return mOffset;
}
bool LxElfCmdOffset::
IsNegative() const
{
return mIsNegative;
}
uint32_t
LxCheck32(uint64_t x)
{
uint32_t res = static_cast<uint32_t>(x);
if (res != x)
throw LxSaveException();
return res;
} | [
"[email protected]"
] | |
f2e8f26f2192e7f2fd2feedfb57b83e88d10552b | 79551a5f231849cc333d58d385215d3309897e79 | /gvle2.simulating.shape/src/openglwidget.h | 4647ea6bf969dc16b25c77561c47b321a6dd0071 | [] | no_license | Chabrier/plugins | 986157496ef21ce17804d551ba91220496ea467e | 228c580c9f208ab8d38a17c7ef4eb79fc3126f0f | refs/heads/master | 2016-08-04T13:44:03.032988 | 2015-09-22T13:14:21 | 2015-09-22T13:16:06 | 17,205,898 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,262 | h | /*
* This file is part of VLE, a framework for multi-modeling, simulation
* and analysis of complex dynamical systems.
* http://www.vle-project.org
*
* Copyright (c) 2014 INRA
*
*/
#ifndef OPENGLWIDGET_H
#define OPENGLWIDGET_H
#include <GL/glew.h>
#include <QGLWidget>
#include "shapeobject.h"
class OpenGLWidget
: public QGLWidget
{
Q_OBJECT
public:
typedef struct vertext_s {
float x;
float y;
float z;
float s;
float t;
} vertex_t;
class cObjectDef {
public:
QColor color;
ShapeObject *shape;
vertex_t *vertices;
};
protected:
int textureMax;
int vertexMax;
int indexMax;
QList<cObjectDef *> mObjects;
QString objectText;
ShapeObject::Box bounds;
private:
bool mIsInit;
public:
explicit OpenGLWidget(QWidget *parent = 0);
~OpenGLWidget();
void addShape(ShapeObject *shape);
void setObjectColor(int n, QColor c);
protected:
virtual void initializeGL();
virtual void resizeGL(int width, int height);
virtual void paintGL();
void buildObject(cObjectDef *obj);
signals:
public slots:
};
#endif // OPENGLWIDGET_H
| [
"[email protected]"
] | |
ddc866c029287c00797383bd08d05230f111af49 | 3c51ef0b38122070472f88b0f01cff019f8278e4 | /Product/GWar/Src/Scene/GWarScene_Battle.cpp | e7022ed38a93ac4365089e1e444fa23c994f9ca7 | [] | no_license | TwinkleStar/TGame | cdd35d2f4ec460207ed57bd67102e9657935a269 | d1cd460602dcaf24a7e3a9658e022b2babfd1dc2 | refs/heads/master | 2020-05-29T13:10:05.029315 | 2013-01-08T13:27:52 | 2013-01-08T13:27:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,307 | cpp |
#include "GWarScene_Battle.h"
#include "TGame.h"
CGWarScene_Battle::CGWarScene_Battle(ITGameSystem* pSys)
:CTGScene(pSys)
{
m_pTex = NULL;
m_nFrame = 0;
m_nPosY = 0;
}
CGWarScene_Battle::~CGWarScene_Battle()
{
}
int MoveTGRect(TGRect* pRt , int nMoveX , int nMoveY)
{
if(pRt)
{
pRt->left += nMoveX;
pRt->right += nMoveX;
pRt->top += nMoveY;
pRt->bottom += nMoveY;
return 1;
}
return 0;
}
int CGWarScene_Battle::Begin()
{
m_pSys->LoadTGGLTexture("ani3.png" , &m_pTex);
m_dwTick = 0;
return TGAME_OK;
}
int CGWarScene_Battle::OnProcess(unsigned int tick)
{
if(tick - m_dwTick > 100)
{
m_dwTick = tick;
m_nFrame++;
m_nPosY +=2;
if(m_nFrame >3)
m_nFrame = 0;
}
return TGAME_OK;
}
int CGWarScene_Battle::Draw(ITGameCanvas* pTGCanvas)
{
if(pTGCanvas)
{
TGRect rc;
rc.left = 30;
rc.right = 60;
rc.top = 30 + m_nPosY;
rc.bottom = 60 + m_nPosY;
TGRect rcSrc;
rcSrc.left = 0;
rcSrc.right = 32;
rcSrc.top = 0;
rcSrc.bottom = 32;
int arrFrameIndex[4] = {0,1,2,1};
if(arrFrameIndex[m_nFrame])
{
MoveTGRect(&rcSrc , 32 * arrFrameIndex[m_nFrame],0);
}
pTGCanvas->TGC_DrawImage(m_pTex , &rc , &rcSrc);
pTGCanvas->TGC_DrawRect(0xFFFF0000 , 1.0f , &rc);
}
return TGAME_OK;
}
int CGWarScene_Battle::End()
{
return TGAME_OK;
}
| [
"[email protected]"
] | |
0966059b7f590dbff8e4c6e360ff46442b87c29b | 4c83329d01247b91457b387e9d0fb0fe673950f4 | /src/test/bloom_tests.cpp | 1edaa79cbba3b0df4d540f0ade35a505be36557b | [
"MIT"
] | permissive | LordSoylent/ICHIBA | 31e10885bb8a6a7c4166195b685837419b77e804 | e57f796cac3c8d7f93702c8d7009f5499c831aa2 | refs/heads/master | 2020-04-24T01:39:37.223596 | 2019-01-31T12:05:02 | 2019-01-31T12:05:02 | 171,607,220 | 2 | 0 | MIT | 2019-02-20T05:30:38 | 2019-02-20T05:30:38 | null | UTF-8 | C++ | false | false | 51,841 | cpp | // Copyright (c) 2012-2013 The Bitcoin Core developers
// Copyright (c) 2017 The IchibaCoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "bloom.h"
#include "base58.h"
#include "clientversion.h"
#include "key.h"
#include "merkleblock.h"
#include "serialize.h"
#include "streams.h"
#include "uint256.h"
#include "util.h"
#include "utilstrencodings.h"
#include <vector>
#include <boost/test/unit_test.hpp>
#include <boost/tuple/tuple.hpp>
using namespace std;
using namespace boost::tuples;
BOOST_AUTO_TEST_SUITE(bloom_tests)
BOOST_AUTO_TEST_CASE(bloom_create_insert_serialize)
{
CBloomFilter filter(3, 0.01, 0, BLOOM_UPDATE_ALL);
filter.insert(ParseHex("99108ad8ed9bb6274d3980bab5a85c048f0950c8"));
BOOST_CHECK_MESSAGE( filter.contains(ParseHex("99108ad8ed9bb6274d3980bab5a85c048f0950c8")), "BloomFilter doesn't contain just-inserted object!");
// One bit different in first byte
BOOST_CHECK_MESSAGE(!filter.contains(ParseHex("19108ad8ed9bb6274d3980bab5a85c048f0950c8")), "BloomFilter contains something it shouldn't!");
filter.insert(ParseHex("b5a2c786d9ef4658287ced5914b37a1b4aa32eee"));
BOOST_CHECK_MESSAGE(filter.contains(ParseHex("b5a2c786d9ef4658287ced5914b37a1b4aa32eee")), "BloomFilter doesn't contain just-inserted object (2)!");
filter.insert(ParseHex("b9300670b4c5366e95b2699e8b18bc75e5f729c5"));
BOOST_CHECK_MESSAGE(filter.contains(ParseHex("b9300670b4c5366e95b2699e8b18bc75e5f729c5")), "BloomFilter doesn't contain just-inserted object (3)!");
CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
filter.Serialize(stream, SER_NETWORK, PROTOCOL_VERSION);
vector<unsigned char> vch = ParseHex("03614e9b050000000000000001");
vector<char> expected(vch.size());
for (unsigned int i = 0; i < vch.size(); i++)
expected[i] = (char)vch[i];
BOOST_CHECK_EQUAL_COLLECTIONS(stream.begin(), stream.end(), expected.begin(), expected.end());
BOOST_CHECK_MESSAGE( filter.contains(ParseHex("99108ad8ed9bb6274d3980bab5a85c048f0950c8")), "BloomFilter doesn't contain just-inserted object!");
filter.clear();
BOOST_CHECK_MESSAGE( !filter.contains(ParseHex("99108ad8ed9bb6274d3980bab5a85c048f0950c8")), "BloomFilter should be empty!");
}
BOOST_AUTO_TEST_CASE(bloom_create_insert_serialize_with_tweak)
{
// Same test as bloom_create_insert_serialize, but we add a nTweak of 100
CBloomFilter filter(3, 0.01, 2147483649UL, BLOOM_UPDATE_ALL);
filter.insert(ParseHex("99108ad8ed9bb6274d3980bab5a85c048f0950c8"));
BOOST_CHECK_MESSAGE( filter.contains(ParseHex("99108ad8ed9bb6274d3980bab5a85c048f0950c8")), "BloomFilter doesn't contain just-inserted object!");
// One bit different in first byte
BOOST_CHECK_MESSAGE(!filter.contains(ParseHex("19108ad8ed9bb6274d3980bab5a85c048f0950c8")), "BloomFilter contains something it shouldn't!");
filter.insert(ParseHex("b5a2c786d9ef4658287ced5914b37a1b4aa32eee"));
BOOST_CHECK_MESSAGE(filter.contains(ParseHex("b5a2c786d9ef4658287ced5914b37a1b4aa32eee")), "BloomFilter doesn't contain just-inserted object (2)!");
filter.insert(ParseHex("b9300670b4c5366e95b2699e8b18bc75e5f729c5"));
BOOST_CHECK_MESSAGE(filter.contains(ParseHex("b9300670b4c5366e95b2699e8b18bc75e5f729c5")), "BloomFilter doesn't contain just-inserted object (3)!");
CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
filter.Serialize(stream, SER_NETWORK, PROTOCOL_VERSION);
vector<unsigned char> vch = ParseHex("03ce4299050000000100008001");
vector<char> expected(vch.size());
for (unsigned int i = 0; i < vch.size(); i++)
expected[i] = (char)vch[i];
BOOST_CHECK_EQUAL_COLLECTIONS(stream.begin(), stream.end(), expected.begin(), expected.end());
}
BOOST_AUTO_TEST_CASE(bloom_create_insert_key)
{
string strSecret = string("5Kg1gnAjaLfKiwhhPpGS3QfRg2m6awQvaj98JCZBZQ5SuS2F15C");
CBitcoinSecret vchSecret;
BOOST_CHECK(vchSecret.SetString(strSecret));
CKey key = vchSecret.GetKey();
CPubKey pubkey = key.GetPubKey();
vector<unsigned char> vchPubKey(pubkey.begin(), pubkey.end());
CBloomFilter filter(2, 0.001, 0, BLOOM_UPDATE_ALL);
filter.insert(vchPubKey);
uint160 hash = pubkey.GetID();
filter.insert(vector<unsigned char>(hash.begin(), hash.end()));
CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
filter.Serialize(stream, SER_NETWORK, PROTOCOL_VERSION);
vector<unsigned char> vch = ParseHex("038fc16b080000000000000001");
vector<char> expected(vch.size());
for (unsigned int i = 0; i < vch.size(); i++)
expected[i] = (char)vch[i];
BOOST_CHECK_EQUAL_COLLECTIONS(stream.begin(), stream.end(), expected.begin(), expected.end());
}
BOOST_AUTO_TEST_CASE(bloom_match)
{
// Random real transaction (b4749f017444b051c44dfd2720e88f314ff94f3dd6d56d40ef65854fcd7fff6b)
CTransaction tx;
CDataStream stream(ParseHex("01000000010b26e9b7735eb6aabdf358bab62f9816a21ba9ebdb719d5299e88607d722c190000000008b4830450220070aca44506c5cef3a16ed519d7c3c39f8aab192c4e1c90d065f37b8a4af6141022100a8e160b856c2d43d27d8fba71e5aef6405b8643ac4cb7cb3c462aced7f14711a0141046d11fee51b0e60666d5049a9101a72741df480b96ee26488a4d3466b95c9a40ac5eeef87e10a5cd336c19a84565f80fa6c547957b7700ff4dfbdefe76036c339ffffffff021bff3d11000000001976a91404943fdd508053c75000106d3bc6e2754dbcff1988ac2f15de00000000001976a914a266436d2965547608b9e15d9032a7b9d64fa43188ac00000000"), SER_DISK, CLIENT_VERSION);
stream >> tx;
// and one which spends it (e2769b09e784f32f62ef849763d4f45b98e07ba658647343b915ff832b110436)
unsigned char ch[] = {0x01, 0x00, 0x00, 0x00, 0x01, 0x6b, 0xff, 0x7f, 0xcd, 0x4f, 0x85, 0x65, 0xef, 0x40, 0x6d, 0xd5, 0xd6, 0x3d, 0x4f, 0xf9, 0x4f, 0x31, 0x8f, 0xe8, 0x20, 0x27, 0xfd, 0x4d, 0xc4, 0x51, 0xb0, 0x44, 0x74, 0x01, 0x9f, 0x74, 0xb4, 0x00, 0x00, 0x00, 0x00, 0x8c, 0x49, 0x30, 0x46, 0x02, 0x21, 0x00, 0xda, 0x0d, 0xc6, 0xae, 0xce, 0xfe, 0x1e, 0x06, 0xef, 0xdf, 0x05, 0x77, 0x37, 0x57, 0xde, 0xb1, 0x68, 0x82, 0x09, 0x30, 0xe3, 0xb0, 0xd0, 0x3f, 0x46, 0xf5, 0xfc, 0xf1, 0x50, 0xbf, 0x99, 0x0c, 0x02, 0x21, 0x00, 0xd2, 0x5b, 0x5c, 0x87, 0x04, 0x00, 0x76, 0xe4, 0xf2, 0x53, 0xf8, 0x26, 0x2e, 0x76, 0x3e, 0x2d, 0xd5, 0x1e, 0x7f, 0xf0, 0xbe, 0x15, 0x77, 0x27, 0xc4, 0xbc, 0x42, 0x80, 0x7f, 0x17, 0xbd, 0x39, 0x01, 0x41, 0x04, 0xe6, 0xc2, 0x6e, 0xf6, 0x7d, 0xc6, 0x10, 0xd2, 0xcd, 0x19, 0x24, 0x84, 0x78, 0x9a, 0x6c, 0xf9, 0xae, 0xa9, 0x93, 0x0b, 0x94, 0x4b, 0x7e, 0x2d, 0xb5, 0x34, 0x2b, 0x9d, 0x9e, 0x5b, 0x9f, 0xf7, 0x9a, 0xff, 0x9a, 0x2e, 0xe1, 0x97, 0x8d, 0xd7, 0xfd, 0x01, 0xdf, 0xc5, 0x22, 0xee, 0x02, 0x28, 0x3d, 0x3b, 0x06, 0xa9, 0xd0, 0x3a, 0xcf, 0x80, 0x96, 0x96, 0x8d, 0x7d, 0xbb, 0x0f, 0x91, 0x78, 0xff, 0xff, 0xff, 0xff, 0x02, 0x8b, 0xa7, 0x94, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x19, 0x76, 0xa9, 0x14, 0xba, 0xde, 0xec, 0xfd, 0xef, 0x05, 0x07, 0x24, 0x7f, 0xc8, 0xf7, 0x42, 0x41, 0xd7, 0x3b, 0xc0, 0x39, 0x97, 0x2d, 0x7b, 0x88, 0xac, 0x40, 0x94, 0xa8, 0x02, 0x00, 0x00, 0x00, 0x00, 0x19, 0x76, 0xa9, 0x14, 0xc1, 0x09, 0x32, 0x48, 0x3f, 0xec, 0x93, 0xed, 0x51, 0xf5, 0xfe, 0x95, 0xe7, 0x25, 0x59, 0xf2, 0xcc, 0x70, 0x43, 0xf9, 0x88, 0xac, 0x00, 0x00, 0x00, 0x00, 0x00};
vector<unsigned char> vch(ch, ch + sizeof(ch) -1);
CDataStream spendStream(vch, SER_DISK, CLIENT_VERSION);
CTransaction spendingTx;
spendStream >> spendingTx;
CBloomFilter filter(10, 0.000001, 0, BLOOM_UPDATE_ALL);
filter.insert(uint256("0xb4749f017444b051c44dfd2720e88f314ff94f3dd6d56d40ef65854fcd7fff6b"));
BOOST_CHECK_MESSAGE(filter.IsRelevantAndUpdate(tx), "Simple Bloom filter didn't match tx hash");
filter = CBloomFilter(10, 0.000001, 0, BLOOM_UPDATE_ALL);
// byte-reversed tx hash
filter.insert(ParseHex("6bff7fcd4f8565ef406dd5d63d4ff94f318fe82027fd4dc451b04474019f74b4"));
BOOST_CHECK_MESSAGE(filter.IsRelevantAndUpdate(tx), "Simple Bloom filter didn't match manually serialized tx hash");
filter = CBloomFilter(10, 0.000001, 0, BLOOM_UPDATE_ALL);
filter.insert(ParseHex("30450220070aca44506c5cef3a16ed519d7c3c39f8aab192c4e1c90d065f37b8a4af6141022100a8e160b856c2d43d27d8fba71e5aef6405b8643ac4cb7cb3c462aced7f14711a01"));
BOOST_CHECK_MESSAGE(filter.IsRelevantAndUpdate(tx), "Simple Bloom filter didn't match input signature");
filter = CBloomFilter(10, 0.000001, 0, BLOOM_UPDATE_ALL);
filter.insert(ParseHex("046d11fee51b0e60666d5049a9101a72741df480b96ee26488a4d3466b95c9a40ac5eeef87e10a5cd336c19a84565f80fa6c547957b7700ff4dfbdefe76036c339"));
BOOST_CHECK_MESSAGE(filter.IsRelevantAndUpdate(tx), "Simple Bloom filter didn't match input pub key");
filter = CBloomFilter(10, 0.000001, 0, BLOOM_UPDATE_ALL);
filter.insert(ParseHex("04943fdd508053c75000106d3bc6e2754dbcff19"));
BOOST_CHECK_MESSAGE(filter.IsRelevantAndUpdate(tx), "Simple Bloom filter didn't match output address");
BOOST_CHECK_MESSAGE(filter.IsRelevantAndUpdate(spendingTx), "Simple Bloom filter didn't add output");
filter = CBloomFilter(10, 0.000001, 0, BLOOM_UPDATE_ALL);
filter.insert(ParseHex("a266436d2965547608b9e15d9032a7b9d64fa431"));
BOOST_CHECK_MESSAGE(filter.IsRelevantAndUpdate(tx), "Simple Bloom filter didn't match output address");
filter = CBloomFilter(10, 0.000001, 0, BLOOM_UPDATE_ALL);
filter.insert(COutPoint(uint256("0x90c122d70786e899529d71dbeba91ba216982fb6ba58f3bdaab65e73b7e9260b"), 0));
BOOST_CHECK_MESSAGE(filter.IsRelevantAndUpdate(tx), "Simple Bloom filter didn't match COutPoint");
filter = CBloomFilter(10, 0.000001, 0, BLOOM_UPDATE_ALL);
COutPoint prevOutPoint(uint256("0x90c122d70786e899529d71dbeba91ba216982fb6ba58f3bdaab65e73b7e9260b"), 0);
{
vector<unsigned char> data(32 + sizeof(unsigned int));
memcpy(&data[0], prevOutPoint.hash.begin(), 32);
memcpy(&data[32], &prevOutPoint.n, sizeof(unsigned int));
filter.insert(data);
}
BOOST_CHECK_MESSAGE(filter.IsRelevantAndUpdate(tx), "Simple Bloom filter didn't match manually serialized COutPoint");
filter = CBloomFilter(10, 0.000001, 0, BLOOM_UPDATE_ALL);
filter.insert(uint256("00000009e784f32f62ef849763d4f45b98e07ba658647343b915ff832b110436"));
BOOST_CHECK_MESSAGE(!filter.IsRelevantAndUpdate(tx), "Simple Bloom filter matched random tx hash");
filter = CBloomFilter(10, 0.000001, 0, BLOOM_UPDATE_ALL);
filter.insert(ParseHex("0000006d2965547608b9e15d9032a7b9d64fa431"));
BOOST_CHECK_MESSAGE(!filter.IsRelevantAndUpdate(tx), "Simple Bloom filter matched random address");
filter = CBloomFilter(10, 0.000001, 0, BLOOM_UPDATE_ALL);
filter.insert(COutPoint(uint256("0x90c122d70786e899529d71dbeba91ba216982fb6ba58f3bdaab65e73b7e9260b"), 1));
BOOST_CHECK_MESSAGE(!filter.IsRelevantAndUpdate(tx), "Simple Bloom filter matched COutPoint for an output we didn't care about");
filter = CBloomFilter(10, 0.000001, 0, BLOOM_UPDATE_ALL);
filter.insert(COutPoint(uint256("0x000000d70786e899529d71dbeba91ba216982fb6ba58f3bdaab65e73b7e9260b"), 0));
BOOST_CHECK_MESSAGE(!filter.IsRelevantAndUpdate(tx), "Simple Bloom filter matched COutPoint for an output we didn't care about");
}
BOOST_AUTO_TEST_CASE(merkle_block_1)
{
// Random real block (0000000000013b8ab2cd513b0261a14096412195a72a0c4827d229dcc7e0f7af)
// With 9 txes
CBlock block;
CDataStream stream(ParseHex("0100000090f0a9f110702f808219ebea1173056042a714bad51b916cb6800000000000005275289558f51c9966699404ae2294730c3c9f9bda53523ce50e9b95e558da2fdb261b4d4c86041b1ab1bf930901000000010000000000000000000000000000000000000000000000000000000000000000ffffffff07044c86041b0146ffffffff0100f2052a01000000434104e18f7afbe4721580e81e8414fc8c24d7cfacf254bb5c7b949450c3e997c2dc1242487a8169507b631eb3771f2b425483fb13102c4eb5d858eef260fe70fbfae0ac00000000010000000196608ccbafa16abada902780da4dc35dafd7af05fa0da08cf833575f8cf9e836000000004a493046022100dab24889213caf43ae6adc41cf1c9396c08240c199f5225acf45416330fd7dbd022100fe37900e0644bf574493a07fc5edba06dbc07c311b947520c2d514bc5725dcb401ffffffff0100f2052a010000001976a914f15d1921f52e4007b146dfa60f369ed2fc393ce288ac000000000100000001fb766c1288458c2bafcfec81e48b24d98ec706de6b8af7c4e3c29419bfacb56d000000008c493046022100f268ba165ce0ad2e6d93f089cfcd3785de5c963bb5ea6b8c1b23f1ce3e517b9f022100da7c0f21adc6c401887f2bfd1922f11d76159cbc597fbd756a23dcbb00f4d7290141042b4e8625a96127826915a5b109852636ad0da753c9e1d5606a50480cd0c40f1f8b8d898235e571fe9357d9ec842bc4bba1827daaf4de06d71844d0057707966affffffff0280969800000000001976a9146963907531db72d0ed1a0cfb471ccb63923446f388ac80d6e34c000000001976a914f0688ba1c0d1ce182c7af6741e02658c7d4dfcd388ac000000000100000002c40297f730dd7b5a99567eb8d27b78758f607507c52292d02d4031895b52f2ff010000008b483045022100f7edfd4b0aac404e5bab4fd3889e0c6c41aa8d0e6fa122316f68eddd0a65013902205b09cc8b2d56e1cd1f7f2fafd60a129ed94504c4ac7bdc67b56fe67512658b3e014104732012cb962afa90d31b25d8fb0e32c94e513ab7a17805c14ca4c3423e18b4fb5d0e676841733cb83abaf975845c9f6f2a8097b7d04f4908b18368d6fc2d68ecffffffffca5065ff9617cbcba45eb23726df6498a9b9cafed4f54cbab9d227b0035ddefb000000008a473044022068010362a13c7f9919fa832b2dee4e788f61f6f5d344a7c2a0da6ae740605658022006d1af525b9a14a35c003b78b72bd59738cd676f845d1ff3fc25049e01003614014104732012cb962afa90d31b25d8fb0e32c94e513ab7a17805c14ca4c3423e18b4fb5d0e676841733cb83abaf975845c9f6f2a8097b7d04f4908b18368d6fc2d68ecffffffff01001ec4110200000043410469ab4181eceb28985b9b4e895c13fa5e68d85761b7eee311db5addef76fa8621865134a221bd01f28ec9999ee3e021e60766e9d1f3458c115fb28650605f11c9ac000000000100000001cdaf2f758e91c514655e2dc50633d1e4c84989f8aa90a0dbc883f0d23ed5c2fa010000008b48304502207ab51be6f12a1962ba0aaaf24a20e0b69b27a94fac5adf45aa7d2d18ffd9236102210086ae728b370e5329eead9accd880d0cb070aea0c96255fae6c4f1ddcce1fd56e014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffff02404b4c00000000001976a9142b6ba7c9d796b75eef7942fc9288edd37c32f5c388ac002d3101000000001976a9141befba0cdc1ad56529371864d9f6cb042faa06b588ac000000000100000001b4a47603e71b61bc3326efd90111bf02d2f549b067f4c4a8fa183b57a0f800cb010000008a4730440220177c37f9a505c3f1a1f0ce2da777c339bd8339ffa02c7cb41f0a5804f473c9230220585b25a2ee80eb59292e52b987dad92acb0c64eced92ed9ee105ad153cdb12d001410443bd44f683467e549dae7d20d1d79cbdb6df985c6e9c029c8d0c6cb46cc1a4d3cf7923c5021b27f7a0b562ada113bc85d5fda5a1b41e87fe6e8802817cf69996ffffffff0280651406000000001976a9145505614859643ab7b547cd7f1f5e7e2a12322d3788ac00aa0271000000001976a914ea4720a7a52fc166c55ff2298e07baf70ae67e1b88ac00000000010000000586c62cd602d219bb60edb14a3e204de0705176f9022fe49a538054fb14abb49e010000008c493046022100f2bc2aba2534becbdf062eb993853a42bbbc282083d0daf9b4b585bd401aa8c9022100b1d7fd7ee0b95600db8535bbf331b19eed8d961f7a8e54159c53675d5f69df8c014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffff03ad0e58ccdac3df9dc28a218bcf6f1997b0a93306faaa4b3a28ae83447b2179010000008b483045022100be12b2937179da88599e27bb31c3525097a07cdb52422d165b3ca2f2020ffcf702200971b51f853a53d644ebae9ec8f3512e442b1bcb6c315a5b491d119d10624c83014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffff2acfcab629bbc8685792603762c921580030ba144af553d271716a95089e107b010000008b483045022100fa579a840ac258871365dd48cd7552f96c8eea69bd00d84f05b283a0dab311e102207e3c0ee9234814cfbb1b659b83671618f45abc1326b9edcc77d552a4f2a805c0014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffffdcdc6023bbc9944a658ddc588e61eacb737ddf0a3cd24f113b5a8634c517fcd2000000008b4830450221008d6df731df5d32267954bd7d2dda2302b74c6c2a6aa5c0ca64ecbabc1af03c75022010e55c571d65da7701ae2da1956c442df81bbf076cdbac25133f99d98a9ed34c014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffffe15557cd5ce258f479dfd6dc6514edf6d7ed5b21fcfa4a038fd69f06b83ac76e010000008b483045022023b3e0ab071eb11de2eb1cc3a67261b866f86bf6867d4558165f7c8c8aca2d86022100dc6e1f53a91de3efe8f63512850811f26284b62f850c70ca73ed5de8771fb451014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffff01404b4c00000000001976a9142b6ba7c9d796b75eef7942fc9288edd37c32f5c388ac00000000010000000166d7577163c932b4f9690ca6a80b6e4eb001f0a2fa9023df5595602aae96ed8d000000008a4730440220262b42546302dfb654a229cefc86432b89628ff259dc87edd1154535b16a67e102207b4634c020a97c3e7bbd0d4d19da6aa2269ad9dded4026e896b213d73ca4b63f014104979b82d02226b3a4597523845754d44f13639e3bf2df5e82c6aab2bdc79687368b01b1ab8b19875ae3c90d661a3d0a33161dab29934edeb36aa01976be3baf8affffffff02404b4c00000000001976a9144854e695a02af0aeacb823ccbc272134561e0a1688ac40420f00000000001976a914abee93376d6b37b5c2940655a6fcaf1c8e74237988ac0000000001000000014e3f8ef2e91349a9059cb4f01e54ab2597c1387161d3da89919f7ea6acdbb371010000008c49304602210081f3183471a5ca22307c0800226f3ef9c353069e0773ac76bb580654d56aa523022100d4c56465bdc069060846f4fbf2f6b20520b2a80b08b168b31e66ddb9c694e240014104976c79848e18251612f8940875b2b08d06e6dc73b9840e8860c066b7e87432c477e9a59a453e71e6d76d5fe34058b800a098fc1740ce3012e8fc8a00c96af966ffffffff02c0e1e400000000001976a9144134e75a6fcb6042034aab5e18570cf1f844f54788ac404b4c00000000001976a9142b6ba7c9d796b75eef7942fc9288edd37c32f5c388ac00000000"), SER_NETWORK, PROTOCOL_VERSION);
stream >> block;
CBloomFilter filter(10, 0.000001, 0, BLOOM_UPDATE_ALL);
// Match the last transaction
filter.insert(uint256("0x74d681e0e03bafa802c8aa084379aa98d9fcd632ddc2ed9782b586ec87451f20"));
CMerkleBlock merkleBlock(block, filter);
BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash());
BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 1);
pair<unsigned int, uint256> pair = merkleBlock.vMatchedTxn[0];
BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == uint256("0x74d681e0e03bafa802c8aa084379aa98d9fcd632ddc2ed9782b586ec87451f20"));
BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 8);
vector<uint256> vMatched;
BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched) == block.hashMerkleRoot);
BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size());
for (unsigned int i = 0; i < vMatched.size(); i++)
BOOST_CHECK(vMatched[i] == merkleBlock.vMatchedTxn[i].second);
// Also match the 8th transaction
filter.insert(uint256("0xdd1fd2a6fc16404faf339881a90adbde7f4f728691ac62e8f168809cdfae1053"));
merkleBlock = CMerkleBlock(block, filter);
BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash());
BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 2);
BOOST_CHECK(merkleBlock.vMatchedTxn[1] == pair);
BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == uint256("0xdd1fd2a6fc16404faf339881a90adbde7f4f728691ac62e8f168809cdfae1053"));
BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 7);
BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched) == block.hashMerkleRoot);
BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size());
for (unsigned int i = 0; i < vMatched.size(); i++)
BOOST_CHECK(vMatched[i] == merkleBlock.vMatchedTxn[i].second);
}
BOOST_AUTO_TEST_CASE(merkle_block_2)
{
// Random real block (000000005a4ded781e667e06ceefafb71410b511fe0d5adc3e5a27ecbec34ae6)
// With 4 txes
CBlock block;
CDataStream stream(ParseHex("0100000075616236cc2126035fadb38deb65b9102cc2c41c09cdf29fc051906800000000fe7d5e12ef0ff901f6050211249919b1c0653771832b3a80c66cea42847f0ae1d4d26e49ffff001d00f0a4410401000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0804ffff001d029105ffffffff0100f2052a010000004341046d8709a041d34357697dfcb30a9d05900a6294078012bf3bb09c6f9b525f1d16d5503d7905db1ada9501446ea00728668fc5719aa80be2fdfc8a858a4dbdd4fbac00000000010000000255605dc6f5c3dc148b6da58442b0b2cd422be385eab2ebea4119ee9c268d28350000000049483045022100aa46504baa86df8a33b1192b1b9367b4d729dc41e389f2c04f3e5c7f0559aae702205e82253a54bf5c4f65b7428551554b2045167d6d206dfe6a2e198127d3f7df1501ffffffff55605dc6f5c3dc148b6da58442b0b2cd422be385eab2ebea4119ee9c268d2835010000004847304402202329484c35fa9d6bb32a55a70c0982f606ce0e3634b69006138683bcd12cbb6602200c28feb1e2555c3210f1dddb299738b4ff8bbe9667b68cb8764b5ac17b7adf0001ffffffff0200e1f505000000004341046a0765b5865641ce08dd39690aade26dfbf5511430ca428a3089261361cef170e3929a68aee3d8d4848b0c5111b0a37b82b86ad559fd2a745b44d8e8d9dfdc0cac00180d8f000000004341044a656f065871a353f216ca26cef8dde2f03e8c16202d2e8ad769f02032cb86a5eb5e56842e92e19141d60a01928f8dd2c875a390f67c1f6c94cfc617c0ea45afac0000000001000000025f9a06d3acdceb56be1bfeaa3e8a25e62d182fa24fefe899d1c17f1dad4c2028000000004847304402205d6058484157235b06028c30736c15613a28bdb768ee628094ca8b0030d4d6eb0220328789c9a2ec27ddaec0ad5ef58efded42e6ea17c2e1ce838f3d6913f5e95db601ffffffff5f9a06d3acdceb56be1bfeaa3e8a25e62d182fa24fefe899d1c17f1dad4c2028010000004a493046022100c45af050d3cea806cedd0ab22520c53ebe63b987b8954146cdca42487b84bdd6022100b9b027716a6b59e640da50a864d6dd8a0ef24c76ce62391fa3eabaf4d2886d2d01ffffffff0200e1f505000000004341046a0765b5865641ce08dd39690aade26dfbf5511430ca428a3089261361cef170e3929a68aee3d8d4848b0c5111b0a37b82b86ad559fd2a745b44d8e8d9dfdc0cac00180d8f000000004341046a0765b5865641ce08dd39690aade26dfbf5511430ca428a3089261361cef170e3929a68aee3d8d4848b0c5111b0a37b82b86ad559fd2a745b44d8e8d9dfdc0cac000000000100000002e2274e5fea1bf29d963914bd301aa63b64daaf8a3e88f119b5046ca5738a0f6b0000000048473044022016e7a727a061ea2254a6c358376aaa617ac537eb836c77d646ebda4c748aac8b0220192ce28bf9f2c06a6467e6531e27648d2b3e2e2bae85159c9242939840295ba501ffffffffe2274e5fea1bf29d963914bd301aa63b64daaf8a3e88f119b5046ca5738a0f6b010000004a493046022100b7a1a755588d4190118936e15cd217d133b0e4a53c3c15924010d5648d8925c9022100aaef031874db2114f2d869ac2de4ae53908fbfea5b2b1862e181626bb9005c9f01ffffffff0200e1f505000000004341044a656f065871a353f216ca26cef8dde2f03e8c16202d2e8ad769f02032cb86a5eb5e56842e92e19141d60a01928f8dd2c875a390f67c1f6c94cfc617c0ea45afac00180d8f000000004341046a0765b5865641ce08dd39690aade26dfbf5511430ca428a3089261361cef170e3929a68aee3d8d4848b0c5111b0a37b82b86ad559fd2a745b44d8e8d9dfdc0cac00000000"), SER_NETWORK, PROTOCOL_VERSION);
stream >> block;
CBloomFilter filter(10, 0.000001, 0, BLOOM_UPDATE_ALL);
// Match the first transaction
filter.insert(uint256("0xe980fe9f792d014e73b95203dc1335c5f9ce19ac537a419e6df5b47aecb93b70"));
CMerkleBlock merkleBlock(block, filter);
BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash());
BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 1);
pair<unsigned int, uint256> pair = merkleBlock.vMatchedTxn[0];
BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == uint256("0xe980fe9f792d014e73b95203dc1335c5f9ce19ac537a419e6df5b47aecb93b70"));
BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 0);
vector<uint256> vMatched;
BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched) == block.hashMerkleRoot);
BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size());
for (unsigned int i = 0; i < vMatched.size(); i++)
BOOST_CHECK(vMatched[i] == merkleBlock.vMatchedTxn[i].second);
// Match an output from the second transaction (the pubkey for address 1DZTzaBHUDM7T3QvUKBz4qXMRpkg8jsfB5)
// This should match the third transaction because it spends the output matched
// It also matches the fourth transaction, which spends to the pubkey again
filter.insert(ParseHex("044a656f065871a353f216ca26cef8dde2f03e8c16202d2e8ad769f02032cb86a5eb5e56842e92e19141d60a01928f8dd2c875a390f67c1f6c94cfc617c0ea45af"));
merkleBlock = CMerkleBlock(block, filter);
BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash());
BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 4);
BOOST_CHECK(pair == merkleBlock.vMatchedTxn[0]);
BOOST_CHECK(merkleBlock.vMatchedTxn[1].second == uint256("0x28204cad1d7fc1d199e8ef4fa22f182de6258a3eaafe1bbe56ebdcacd3069a5f"));
BOOST_CHECK(merkleBlock.vMatchedTxn[1].first == 1);
BOOST_CHECK(merkleBlock.vMatchedTxn[2].second == uint256("0x6b0f8a73a56c04b519f1883e8aafda643ba61a30bd1439969df21bea5f4e27e2"));
BOOST_CHECK(merkleBlock.vMatchedTxn[2].first == 2);
BOOST_CHECK(merkleBlock.vMatchedTxn[3].second == uint256("0x3c1d7e82342158e4109df2e0b6348b6e84e403d8b4046d7007763ace63cddb23"));
BOOST_CHECK(merkleBlock.vMatchedTxn[3].first == 3);
BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched) == block.hashMerkleRoot);
BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size());
for (unsigned int i = 0; i < vMatched.size(); i++)
BOOST_CHECK(vMatched[i] == merkleBlock.vMatchedTxn[i].second);
}
BOOST_AUTO_TEST_CASE(merkle_block_2_with_update_none)
{
// Random real block (000000005a4ded781e667e06ceefafb71410b511fe0d5adc3e5a27ecbec34ae6)
// With 4 txes
CBlock block;
CDataStream stream(ParseHex("0100000075616236cc2126035fadb38deb65b9102cc2c41c09cdf29fc051906800000000fe7d5e12ef0ff901f6050211249919b1c0653771832b3a80c66cea42847f0ae1d4d26e49ffff001d00f0a4410401000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0804ffff001d029105ffffffff0100f2052a010000004341046d8709a041d34357697dfcb30a9d05900a6294078012bf3bb09c6f9b525f1d16d5503d7905db1ada9501446ea00728668fc5719aa80be2fdfc8a858a4dbdd4fbac00000000010000000255605dc6f5c3dc148b6da58442b0b2cd422be385eab2ebea4119ee9c268d28350000000049483045022100aa46504baa86df8a33b1192b1b9367b4d729dc41e389f2c04f3e5c7f0559aae702205e82253a54bf5c4f65b7428551554b2045167d6d206dfe6a2e198127d3f7df1501ffffffff55605dc6f5c3dc148b6da58442b0b2cd422be385eab2ebea4119ee9c268d2835010000004847304402202329484c35fa9d6bb32a55a70c0982f606ce0e3634b69006138683bcd12cbb6602200c28feb1e2555c3210f1dddb299738b4ff8bbe9667b68cb8764b5ac17b7adf0001ffffffff0200e1f505000000004341046a0765b5865641ce08dd39690aade26dfbf5511430ca428a3089261361cef170e3929a68aee3d8d4848b0c5111b0a37b82b86ad559fd2a745b44d8e8d9dfdc0cac00180d8f000000004341044a656f065871a353f216ca26cef8dde2f03e8c16202d2e8ad769f02032cb86a5eb5e56842e92e19141d60a01928f8dd2c875a390f67c1f6c94cfc617c0ea45afac0000000001000000025f9a06d3acdceb56be1bfeaa3e8a25e62d182fa24fefe899d1c17f1dad4c2028000000004847304402205d6058484157235b06028c30736c15613a28bdb768ee628094ca8b0030d4d6eb0220328789c9a2ec27ddaec0ad5ef58efded42e6ea17c2e1ce838f3d6913f5e95db601ffffffff5f9a06d3acdceb56be1bfeaa3e8a25e62d182fa24fefe899d1c17f1dad4c2028010000004a493046022100c45af050d3cea806cedd0ab22520c53ebe63b987b8954146cdca42487b84bdd6022100b9b027716a6b59e640da50a864d6dd8a0ef24c76ce62391fa3eabaf4d2886d2d01ffffffff0200e1f505000000004341046a0765b5865641ce08dd39690aade26dfbf5511430ca428a3089261361cef170e3929a68aee3d8d4848b0c5111b0a37b82b86ad559fd2a745b44d8e8d9dfdc0cac00180d8f000000004341046a0765b5865641ce08dd39690aade26dfbf5511430ca428a3089261361cef170e3929a68aee3d8d4848b0c5111b0a37b82b86ad559fd2a745b44d8e8d9dfdc0cac000000000100000002e2274e5fea1bf29d963914bd301aa63b64daaf8a3e88f119b5046ca5738a0f6b0000000048473044022016e7a727a061ea2254a6c358376aaa617ac537eb836c77d646ebda4c748aac8b0220192ce28bf9f2c06a6467e6531e27648d2b3e2e2bae85159c9242939840295ba501ffffffffe2274e5fea1bf29d963914bd301aa63b64daaf8a3e88f119b5046ca5738a0f6b010000004a493046022100b7a1a755588d4190118936e15cd217d133b0e4a53c3c15924010d5648d8925c9022100aaef031874db2114f2d869ac2de4ae53908fbfea5b2b1862e181626bb9005c9f01ffffffff0200e1f505000000004341044a656f065871a353f216ca26cef8dde2f03e8c16202d2e8ad769f02032cb86a5eb5e56842e92e19141d60a01928f8dd2c875a390f67c1f6c94cfc617c0ea45afac00180d8f000000004341046a0765b5865641ce08dd39690aade26dfbf5511430ca428a3089261361cef170e3929a68aee3d8d4848b0c5111b0a37b82b86ad559fd2a745b44d8e8d9dfdc0cac00000000"), SER_NETWORK, PROTOCOL_VERSION);
stream >> block;
CBloomFilter filter(10, 0.000001, 0, BLOOM_UPDATE_NONE);
// Match the first transaction
filter.insert(uint256("0xe980fe9f792d014e73b95203dc1335c5f9ce19ac537a419e6df5b47aecb93b70"));
CMerkleBlock merkleBlock(block, filter);
BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash());
BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 1);
pair<unsigned int, uint256> pair = merkleBlock.vMatchedTxn[0];
BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == uint256("0xe980fe9f792d014e73b95203dc1335c5f9ce19ac537a419e6df5b47aecb93b70"));
BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 0);
vector<uint256> vMatched;
BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched) == block.hashMerkleRoot);
BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size());
for (unsigned int i = 0; i < vMatched.size(); i++)
BOOST_CHECK(vMatched[i] == merkleBlock.vMatchedTxn[i].second);
// Match an output from the second transaction (the pubkey for address 1DZTzaBHUDM7T3QvUKBz4qXMRpkg8jsfB5)
// This should not match the third transaction though it spends the output matched
// It will match the fourth transaction, which has another pay-to-pubkey output to the same address
filter.insert(ParseHex("044a656f065871a353f216ca26cef8dde2f03e8c16202d2e8ad769f02032cb86a5eb5e56842e92e19141d60a01928f8dd2c875a390f67c1f6c94cfc617c0ea45af"));
merkleBlock = CMerkleBlock(block, filter);
BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash());
BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 3);
BOOST_CHECK(pair == merkleBlock.vMatchedTxn[0]);
BOOST_CHECK(merkleBlock.vMatchedTxn[1].second == uint256("0x28204cad1d7fc1d199e8ef4fa22f182de6258a3eaafe1bbe56ebdcacd3069a5f"));
BOOST_CHECK(merkleBlock.vMatchedTxn[1].first == 1);
BOOST_CHECK(merkleBlock.vMatchedTxn[2].second == uint256("0x3c1d7e82342158e4109df2e0b6348b6e84e403d8b4046d7007763ace63cddb23"));
BOOST_CHECK(merkleBlock.vMatchedTxn[2].first == 3);
BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched) == block.hashMerkleRoot);
BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size());
for (unsigned int i = 0; i < vMatched.size(); i++)
BOOST_CHECK(vMatched[i] == merkleBlock.vMatchedTxn[i].second);
}
BOOST_AUTO_TEST_CASE(merkle_block_3_and_serialize)
{
// Random real block (000000000000dab0130bbcc991d3d7ae6b81aa6f50a798888dfe62337458dc45)
// With one tx
CBlock block;
CDataStream stream(ParseHex("0100000079cda856b143d9db2c1caff01d1aecc8630d30625d10e8b4b8b0000000000000b50cc069d6a3e33e3ff84a5c41d9d3febe7c770fdcc96b2c3ff60abe184f196367291b4d4c86041b8fa45d630101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff08044c86041b020a02ffffffff0100f2052a01000000434104ecd3229b0571c3be876feaac0442a9f13c5a572742927af1dc623353ecf8c202225f64868137a18cdd85cbbb4c74fbccfd4f49639cf1bdc94a5672bb15ad5d4cac00000000"), SER_NETWORK, PROTOCOL_VERSION);
stream >> block;
CBloomFilter filter(10, 0.000001, 0, BLOOM_UPDATE_ALL);
// Match the only transaction
filter.insert(uint256("0x63194f18be0af63f2c6bc9dc0f777cbefed3d9415c4af83f3ee3a3d669c00cb5"));
CMerkleBlock merkleBlock(block, filter);
BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash());
BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 1);
BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == uint256("0x63194f18be0af63f2c6bc9dc0f777cbefed3d9415c4af83f3ee3a3d669c00cb5"));
BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 0);
vector<uint256> vMatched;
BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched) == block.hashMerkleRoot);
BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size());
for (unsigned int i = 0; i < vMatched.size(); i++)
BOOST_CHECK(vMatched[i] == merkleBlock.vMatchedTxn[i].second);
CDataStream merkleStream(SER_NETWORK, PROTOCOL_VERSION);
merkleStream << merkleBlock;
vector<unsigned char> vch = ParseHex("0100000079cda856b143d9db2c1caff01d1aecc8630d30625d10e8b4b8b0000000000000b50cc069d6a3e33e3ff84a5c41d9d3febe7c770fdcc96b2c3ff60abe184f196367291b4d4c86041b8fa45d630100000001b50cc069d6a3e33e3ff84a5c41d9d3febe7c770fdcc96b2c3ff60abe184f19630101");
vector<char> expected(vch.size());
for (unsigned int i = 0; i < vch.size(); i++)
expected[i] = (char)vch[i];
BOOST_CHECK_EQUAL_COLLECTIONS(expected.begin(), expected.end(), merkleStream.begin(), merkleStream.end());
}
BOOST_AUTO_TEST_CASE(merkle_block_4)
{
// Random real block (000000000000b731f2eef9e8c63173adfb07e41bd53eb0ef0a6b720d6cb6dea4)
// With 7 txes
CBlock block;
CDataStream stream(ParseHex("0100000082bb869cf3a793432a66e826e05a6fc37469f8efb7421dc880670100000000007f16c5962e8bd963659c793ce370d95f093bc7e367117b3c30c1f8fdd0d9728776381b4d4c86041b554b85290701000000010000000000000000000000000000000000000000000000000000000000000000ffffffff07044c86041b0136ffffffff0100f2052a01000000434104eaafc2314def4ca98ac970241bcab022b9c1e1f4ea423a20f134c876f2c01ec0f0dd5b2e86e7168cefe0d81113c3807420ce13ad1357231a2252247d97a46a91ac000000000100000001bcad20a6a29827d1424f08989255120bf7f3e9e3cdaaa6bb31b0737fe048724300000000494830450220356e834b046cadc0f8ebb5a8a017b02de59c86305403dad52cd77b55af062ea10221009253cd6c119d4729b77c978e1e2aa19f5ea6e0e52b3f16e32fa608cd5bab753901ffffffff02008d380c010000001976a9142b4b8072ecbba129b6453c63e129e643207249ca88ac0065cd1d000000001976a9141b8dd13b994bcfc787b32aeadf58ccb3615cbd5488ac000000000100000003fdacf9b3eb077412e7a968d2e4f11b9a9dee312d666187ed77ee7d26af16cb0b000000008c493046022100ea1608e70911ca0de5af51ba57ad23b9a51db8d28f82c53563c56a05c20f5a87022100a8bdc8b4a8acc8634c6b420410150775eb7f2474f5615f7fccd65af30f310fbf01410465fdf49e29b06b9a1582287b6279014f834edc317695d125ef623c1cc3aaece245bd69fcad7508666e9c74a49dc9056d5fc14338ef38118dc4afae5fe2c585caffffffff309e1913634ecb50f3c4f83e96e70b2df071b497b8973a3e75429df397b5af83000000004948304502202bdb79c596a9ffc24e96f4386199aba386e9bc7b6071516e2b51dda942b3a1ed022100c53a857e76b724fc14d45311eac5019650d415c3abb5428f3aae16d8e69bec2301ffffffff2089e33491695080c9edc18a428f7d834db5b6d372df13ce2b1b0e0cbcb1e6c10000000049483045022100d4ce67c5896ee251c810ac1ff9ceccd328b497c8f553ab6e08431e7d40bad6b5022033119c0c2b7d792d31f1187779c7bd95aefd93d90a715586d73801d9b47471c601ffffffff0100714460030000001976a914c7b55141d097ea5df7a0ed330cf794376e53ec8d88ac0000000001000000045bf0e214aa4069a3e792ecee1e1bf0c1d397cde8dd08138f4b72a00681743447000000008b48304502200c45de8c4f3e2c1821f2fc878cba97b1e6f8807d94930713aa1c86a67b9bf1e40221008581abfef2e30f957815fc89978423746b2086375ca8ecf359c85c2a5b7c88ad01410462bb73f76ca0994fcb8b4271e6fb7561f5c0f9ca0cf6485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018ffd6238f4d87270efb1d3ae37079b794a92d7ec95ffffffffd669f7d7958d40fc59d2253d88e0f248e29b599c80bbcec344a83dda5f9aa72c000000008a473044022078124c8beeaa825f9e0b30bff96e564dd859432f2d0cb3b72d3d5d93d38d7e930220691d233b6c0f995be5acb03d70a7f7a65b6bc9bdd426260f38a1346669507a3601410462bb73f76ca0994fcb8b4271e6fb7561f5c0f9ca0cf6485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018ffd6238f4d87270efb1d3ae37079b794a92d7ec95fffffffff878af0d93f5229a68166cf051fd372bb7a537232946e0a46f53636b4dafdaa4000000008c493046022100c717d1714551663f69c3c5759bdbb3a0fcd3fab023abc0e522fe6440de35d8290221008d9cbe25bffc44af2b18e81c58eb37293fd7fe1c2e7b46fc37ee8c96c50ab1e201410462bb73f76ca0994fcb8b4271e6fb7561f5c0f9ca0cf6485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018ffd6238f4d87270efb1d3ae37079b794a92d7ec95ffffffff27f2b668859cd7f2f894aa0fd2d9e60963bcd07c88973f425f999b8cbfd7a1e2000000008c493046022100e00847147cbf517bcc2f502f3ddc6d284358d102ed20d47a8aa788a62f0db780022100d17b2d6fa84dcaf1c95d88d7e7c30385aecf415588d749afd3ec81f6022cecd701410462bb73f76ca0994fcb8b4271e6fb7561f5c0f9ca0cf6485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018ffd6238f4d87270efb1d3ae37079b794a92d7ec95ffffffff0100c817a8040000001976a914b6efd80d99179f4f4ff6f4dd0a007d018c385d2188ac000000000100000001834537b2f1ce8ef9373a258e10545ce5a50b758df616cd4356e0032554ebd3c4000000008b483045022100e68f422dd7c34fdce11eeb4509ddae38201773dd62f284e8aa9d96f85099d0b002202243bd399ff96b649a0fad05fa759d6a882f0af8c90cf7632c2840c29070aec20141045e58067e815c2f464c6a2a15f987758374203895710c2d452442e28496ff38ba8f5fd901dc20e29e88477167fe4fc299bf818fd0d9e1632d467b2a3d9503b1aaffffffff0280d7e636030000001976a914f34c3e10eb387efe872acb614c89e78bfca7815d88ac404b4c00000000001976a914a84e272933aaf87e1715d7786c51dfaeb5b65a6f88ac00000000010000000143ac81c8e6f6ef307dfe17f3d906d999e23e0189fda838c5510d850927e03ae7000000008c4930460221009c87c344760a64cb8ae6685a3eec2c1ac1bed5b88c87de51acd0e124f266c16602210082d07c037359c3a257b5c63ebd90f5a5edf97b2ac1c434b08ca998839f346dd40141040ba7e521fa7946d12edbb1d1e95a15c34bd4398195e86433c92b431cd315f455fe30032ede69cad9d1e1ed6c3c4ec0dbfced53438c625462afb792dcb098544bffffffff0240420f00000000001976a9144676d1b820d63ec272f1900d59d43bc6463d96f888ac40420f00000000001976a914648d04341d00d7968b3405c034adc38d4d8fb9bd88ac00000000010000000248cc917501ea5c55f4a8d2009c0567c40cfe037c2e71af017d0a452ff705e3f1000000008b483045022100bf5fdc86dc5f08a5d5c8e43a8c9d5b1ed8c65562e280007b52b133021acd9acc02205e325d613e555f772802bf413d36ba807892ed1a690a77811d3033b3de226e0a01410429fa713b124484cb2bd7b5557b2c0b9df7b2b1fee61825eadc5ae6c37a9920d38bfccdc7dc3cb0c47d7b173dbc9db8d37db0a33ae487982c59c6f8606e9d1791ffffffff41ed70551dd7e841883ab8f0b16bf04176b7d1480e4f0af9f3d4c3595768d068000000008b4830450221008513ad65187b903aed1102d1d0c47688127658c51106753fed0151ce9c16b80902201432b9ebcb87bd04ceb2de66035fbbaf4bf8b00d1cfe41f1a1f7338f9ad79d210141049d4cf80125bf50be1709f718c07ad15d0fc612b7da1f5570dddc35f2a352f0f27c978b06820edca9ef982c35fda2d255afba340068c5035552368bc7200c1488ffffffff0100093d00000000001976a9148edb68822f1ad580b043c7b3df2e400f8699eb4888ac00000000"), SER_NETWORK, PROTOCOL_VERSION);
stream >> block;
CBloomFilter filter(10, 0.000001, 0, BLOOM_UPDATE_ALL);
// Match the last transaction
filter.insert(uint256("0x0a2a92f0bda4727d0a13eaddf4dd9ac6b5c61a1429e6b2b818f19b15df0ac154"));
CMerkleBlock merkleBlock(block, filter);
BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash());
BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 1);
pair<unsigned int, uint256> pair = merkleBlock.vMatchedTxn[0];
BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == uint256("0x0a2a92f0bda4727d0a13eaddf4dd9ac6b5c61a1429e6b2b818f19b15df0ac154"));
BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 6);
vector<uint256> vMatched;
BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched) == block.hashMerkleRoot);
BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size());
for (unsigned int i = 0; i < vMatched.size(); i++)
BOOST_CHECK(vMatched[i] == merkleBlock.vMatchedTxn[i].second);
// Also match the 4th transaction
filter.insert(uint256("0x02981fa052f0481dbc5868f4fc2166035a10f27a03cfd2de67326471df5bc041"));
merkleBlock = CMerkleBlock(block, filter);
BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash());
BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 2);
BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == uint256("0x02981fa052f0481dbc5868f4fc2166035a10f27a03cfd2de67326471df5bc041"));
BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 3);
BOOST_CHECK(merkleBlock.vMatchedTxn[1] == pair);
BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched) == block.hashMerkleRoot);
BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size());
for (unsigned int i = 0; i < vMatched.size(); i++)
BOOST_CHECK(vMatched[i] == merkleBlock.vMatchedTxn[i].second);
}
BOOST_AUTO_TEST_CASE(merkle_block_4_test_p2pubkey_only)
{
// Random real block (000000000000b731f2eef9e8c63173adfb07e41bd53eb0ef0a6b720d6cb6dea4)
// With 7 txes
CBlock block;
CDataStream stream(ParseHex("0100000082bb869cf3a793432a66e826e05a6fc37469f8efb7421dc880670100000000007f16c5962e8bd963659c793ce370d95f093bc7e367117b3c30c1f8fdd0d9728776381b4d4c86041b554b85290701000000010000000000000000000000000000000000000000000000000000000000000000ffffffff07044c86041b0136ffffffff0100f2052a01000000434104eaafc2314def4ca98ac970241bcab022b9c1e1f4ea423a20f134c876f2c01ec0f0dd5b2e86e7168cefe0d81113c3807420ce13ad1357231a2252247d97a46a91ac000000000100000001bcad20a6a29827d1424f08989255120bf7f3e9e3cdaaa6bb31b0737fe048724300000000494830450220356e834b046cadc0f8ebb5a8a017b02de59c86305403dad52cd77b55af062ea10221009253cd6c119d4729b77c978e1e2aa19f5ea6e0e52b3f16e32fa608cd5bab753901ffffffff02008d380c010000001976a9142b4b8072ecbba129b6453c63e129e643207249ca88ac0065cd1d000000001976a9141b8dd13b994bcfc787b32aeadf58ccb3615cbd5488ac000000000100000003fdacf9b3eb077412e7a968d2e4f11b9a9dee312d666187ed77ee7d26af16cb0b000000008c493046022100ea1608e70911ca0de5af51ba57ad23b9a51db8d28f82c53563c56a05c20f5a87022100a8bdc8b4a8acc8634c6b420410150775eb7f2474f5615f7fccd65af30f310fbf01410465fdf49e29b06b9a1582287b6279014f834edc317695d125ef623c1cc3aaece245bd69fcad7508666e9c74a49dc9056d5fc14338ef38118dc4afae5fe2c585caffffffff309e1913634ecb50f3c4f83e96e70b2df071b497b8973a3e75429df397b5af83000000004948304502202bdb79c596a9ffc24e96f4386199aba386e9bc7b6071516e2b51dda942b3a1ed022100c53a857e76b724fc14d45311eac5019650d415c3abb5428f3aae16d8e69bec2301ffffffff2089e33491695080c9edc18a428f7d834db5b6d372df13ce2b1b0e0cbcb1e6c10000000049483045022100d4ce67c5896ee251c810ac1ff9ceccd328b497c8f553ab6e08431e7d40bad6b5022033119c0c2b7d792d31f1187779c7bd95aefd93d90a715586d73801d9b47471c601ffffffff0100714460030000001976a914c7b55141d097ea5df7a0ed330cf794376e53ec8d88ac0000000001000000045bf0e214aa4069a3e792ecee1e1bf0c1d397cde8dd08138f4b72a00681743447000000008b48304502200c45de8c4f3e2c1821f2fc878cba97b1e6f8807d94930713aa1c86a67b9bf1e40221008581abfef2e30f957815fc89978423746b2086375ca8ecf359c85c2a5b7c88ad01410462bb73f76ca0994fcb8b4271e6fb7561f5c0f9ca0cf6485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018ffd6238f4d87270efb1d3ae37079b794a92d7ec95ffffffffd669f7d7958d40fc59d2253d88e0f248e29b599c80bbcec344a83dda5f9aa72c000000008a473044022078124c8beeaa825f9e0b30bff96e564dd859432f2d0cb3b72d3d5d93d38d7e930220691d233b6c0f995be5acb03d70a7f7a65b6bc9bdd426260f38a1346669507a3601410462bb73f76ca0994fcb8b4271e6fb7561f5c0f9ca0cf6485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018ffd6238f4d87270efb1d3ae37079b794a92d7ec95fffffffff878af0d93f5229a68166cf051fd372bb7a537232946e0a46f53636b4dafdaa4000000008c493046022100c717d1714551663f69c3c5759bdbb3a0fcd3fab023abc0e522fe6440de35d8290221008d9cbe25bffc44af2b18e81c58eb37293fd7fe1c2e7b46fc37ee8c96c50ab1e201410462bb73f76ca0994fcb8b4271e6fb7561f5c0f9ca0cf6485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018ffd6238f4d87270efb1d3ae37079b794a92d7ec95ffffffff27f2b668859cd7f2f894aa0fd2d9e60963bcd07c88973f425f999b8cbfd7a1e2000000008c493046022100e00847147cbf517bcc2f502f3ddc6d284358d102ed20d47a8aa788a62f0db780022100d17b2d6fa84dcaf1c95d88d7e7c30385aecf415588d749afd3ec81f6022cecd701410462bb73f76ca0994fcb8b4271e6fb7561f5c0f9ca0cf6485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018ffd6238f4d87270efb1d3ae37079b794a92d7ec95ffffffff0100c817a8040000001976a914b6efd80d99179f4f4ff6f4dd0a007d018c385d2188ac000000000100000001834537b2f1ce8ef9373a258e10545ce5a50b758df616cd4356e0032554ebd3c4000000008b483045022100e68f422dd7c34fdce11eeb4509ddae38201773dd62f284e8aa9d96f85099d0b002202243bd399ff96b649a0fad05fa759d6a882f0af8c90cf7632c2840c29070aec20141045e58067e815c2f464c6a2a15f987758374203895710c2d452442e28496ff38ba8f5fd901dc20e29e88477167fe4fc299bf818fd0d9e1632d467b2a3d9503b1aaffffffff0280d7e636030000001976a914f34c3e10eb387efe872acb614c89e78bfca7815d88ac404b4c00000000001976a914a84e272933aaf87e1715d7786c51dfaeb5b65a6f88ac00000000010000000143ac81c8e6f6ef307dfe17f3d906d999e23e0189fda838c5510d850927e03ae7000000008c4930460221009c87c344760a64cb8ae6685a3eec2c1ac1bed5b88c87de51acd0e124f266c16602210082d07c037359c3a257b5c63ebd90f5a5edf97b2ac1c434b08ca998839f346dd40141040ba7e521fa7946d12edbb1d1e95a15c34bd4398195e86433c92b431cd315f455fe30032ede69cad9d1e1ed6c3c4ec0dbfced53438c625462afb792dcb098544bffffffff0240420f00000000001976a9144676d1b820d63ec272f1900d59d43bc6463d96f888ac40420f00000000001976a914648d04341d00d7968b3405c034adc38d4d8fb9bd88ac00000000010000000248cc917501ea5c55f4a8d2009c0567c40cfe037c2e71af017d0a452ff705e3f1000000008b483045022100bf5fdc86dc5f08a5d5c8e43a8c9d5b1ed8c65562e280007b52b133021acd9acc02205e325d613e555f772802bf413d36ba807892ed1a690a77811d3033b3de226e0a01410429fa713b124484cb2bd7b5557b2c0b9df7b2b1fee61825eadc5ae6c37a9920d38bfccdc7dc3cb0c47d7b173dbc9db8d37db0a33ae487982c59c6f8606e9d1791ffffffff41ed70551dd7e841883ab8f0b16bf04176b7d1480e4f0af9f3d4c3595768d068000000008b4830450221008513ad65187b903aed1102d1d0c47688127658c51106753fed0151ce9c16b80902201432b9ebcb87bd04ceb2de66035fbbaf4bf8b00d1cfe41f1a1f7338f9ad79d210141049d4cf80125bf50be1709f718c07ad15d0fc612b7da1f5570dddc35f2a352f0f27c978b06820edca9ef982c35fda2d255afba340068c5035552368bc7200c1488ffffffff0100093d00000000001976a9148edb68822f1ad580b043c7b3df2e400f8699eb4888ac00000000"), SER_NETWORK, PROTOCOL_VERSION);
stream >> block;
CBloomFilter filter(10, 0.000001, 0, BLOOM_UPDATE_P2PUBKEY_ONLY);
// Match the generation pubkey
filter.insert(ParseHex("04eaafc2314def4ca98ac970241bcab022b9c1e1f4ea423a20f134c876f2c01ec0f0dd5b2e86e7168cefe0d81113c3807420ce13ad1357231a2252247d97a46a91"));
// ...and the output address of the 4th transaction
filter.insert(ParseHex("b6efd80d99179f4f4ff6f4dd0a007d018c385d21"));
CMerkleBlock merkleBlock(block, filter);
BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash());
// We should match the generation outpoint
BOOST_CHECK(filter.contains(COutPoint(uint256("0x147caa76786596590baa4e98f5d9f48b86c7765e489f7a6ff3360fe5c674360b"), 0)));
// ... but not the 4th transaction's output (its not pay-2-pubkey)
BOOST_CHECK(!filter.contains(COutPoint(uint256("0x02981fa052f0481dbc5868f4fc2166035a10f27a03cfd2de67326471df5bc041"), 0)));
}
BOOST_AUTO_TEST_CASE(merkle_block_4_test_update_none)
{
// Random real block (000000000000b731f2eef9e8c63173adfb07e41bd53eb0ef0a6b720d6cb6dea4)
// With 7 txes
CBlock block;
CDataStream stream(ParseHex("0100000082bb869cf3a793432a66e826e05a6fc37469f8efb7421dc880670100000000007f16c5962e8bd963659c793ce370d95f093bc7e367117b3c30c1f8fdd0d9728776381b4d4c86041b554b85290701000000010000000000000000000000000000000000000000000000000000000000000000ffffffff07044c86041b0136ffffffff0100f2052a01000000434104eaafc2314def4ca98ac970241bcab022b9c1e1f4ea423a20f134c876f2c01ec0f0dd5b2e86e7168cefe0d81113c3807420ce13ad1357231a2252247d97a46a91ac000000000100000001bcad20a6a29827d1424f08989255120bf7f3e9e3cdaaa6bb31b0737fe048724300000000494830450220356e834b046cadc0f8ebb5a8a017b02de59c86305403dad52cd77b55af062ea10221009253cd6c119d4729b77c978e1e2aa19f5ea6e0e52b3f16e32fa608cd5bab753901ffffffff02008d380c010000001976a9142b4b8072ecbba129b6453c63e129e643207249ca88ac0065cd1d000000001976a9141b8dd13b994bcfc787b32aeadf58ccb3615cbd5488ac000000000100000003fdacf9b3eb077412e7a968d2e4f11b9a9dee312d666187ed77ee7d26af16cb0b000000008c493046022100ea1608e70911ca0de5af51ba57ad23b9a51db8d28f82c53563c56a05c20f5a87022100a8bdc8b4a8acc8634c6b420410150775eb7f2474f5615f7fccd65af30f310fbf01410465fdf49e29b06b9a1582287b6279014f834edc317695d125ef623c1cc3aaece245bd69fcad7508666e9c74a49dc9056d5fc14338ef38118dc4afae5fe2c585caffffffff309e1913634ecb50f3c4f83e96e70b2df071b497b8973a3e75429df397b5af83000000004948304502202bdb79c596a9ffc24e96f4386199aba386e9bc7b6071516e2b51dda942b3a1ed022100c53a857e76b724fc14d45311eac5019650d415c3abb5428f3aae16d8e69bec2301ffffffff2089e33491695080c9edc18a428f7d834db5b6d372df13ce2b1b0e0cbcb1e6c10000000049483045022100d4ce67c5896ee251c810ac1ff9ceccd328b497c8f553ab6e08431e7d40bad6b5022033119c0c2b7d792d31f1187779c7bd95aefd93d90a715586d73801d9b47471c601ffffffff0100714460030000001976a914c7b55141d097ea5df7a0ed330cf794376e53ec8d88ac0000000001000000045bf0e214aa4069a3e792ecee1e1bf0c1d397cde8dd08138f4b72a00681743447000000008b48304502200c45de8c4f3e2c1821f2fc878cba97b1e6f8807d94930713aa1c86a67b9bf1e40221008581abfef2e30f957815fc89978423746b2086375ca8ecf359c85c2a5b7c88ad01410462bb73f76ca0994fcb8b4271e6fb7561f5c0f9ca0cf6485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018ffd6238f4d87270efb1d3ae37079b794a92d7ec95ffffffffd669f7d7958d40fc59d2253d88e0f248e29b599c80bbcec344a83dda5f9aa72c000000008a473044022078124c8beeaa825f9e0b30bff96e564dd859432f2d0cb3b72d3d5d93d38d7e930220691d233b6c0f995be5acb03d70a7f7a65b6bc9bdd426260f38a1346669507a3601410462bb73f76ca0994fcb8b4271e6fb7561f5c0f9ca0cf6485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018ffd6238f4d87270efb1d3ae37079b794a92d7ec95fffffffff878af0d93f5229a68166cf051fd372bb7a537232946e0a46f53636b4dafdaa4000000008c493046022100c717d1714551663f69c3c5759bdbb3a0fcd3fab023abc0e522fe6440de35d8290221008d9cbe25bffc44af2b18e81c58eb37293fd7fe1c2e7b46fc37ee8c96c50ab1e201410462bb73f76ca0994fcb8b4271e6fb7561f5c0f9ca0cf6485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018ffd6238f4d87270efb1d3ae37079b794a92d7ec95ffffffff27f2b668859cd7f2f894aa0fd2d9e60963bcd07c88973f425f999b8cbfd7a1e2000000008c493046022100e00847147cbf517bcc2f502f3ddc6d284358d102ed20d47a8aa788a62f0db780022100d17b2d6fa84dcaf1c95d88d7e7c30385aecf415588d749afd3ec81f6022cecd701410462bb73f76ca0994fcb8b4271e6fb7561f5c0f9ca0cf6485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018ffd6238f4d87270efb1d3ae37079b794a92d7ec95ffffffff0100c817a8040000001976a914b6efd80d99179f4f4ff6f4dd0a007d018c385d2188ac000000000100000001834537b2f1ce8ef9373a258e10545ce5a50b758df616cd4356e0032554ebd3c4000000008b483045022100e68f422dd7c34fdce11eeb4509ddae38201773dd62f284e8aa9d96f85099d0b002202243bd399ff96b649a0fad05fa759d6a882f0af8c90cf7632c2840c29070aec20141045e58067e815c2f464c6a2a15f987758374203895710c2d452442e28496ff38ba8f5fd901dc20e29e88477167fe4fc299bf818fd0d9e1632d467b2a3d9503b1aaffffffff0280d7e636030000001976a914f34c3e10eb387efe872acb614c89e78bfca7815d88ac404b4c00000000001976a914a84e272933aaf87e1715d7786c51dfaeb5b65a6f88ac00000000010000000143ac81c8e6f6ef307dfe17f3d906d999e23e0189fda838c5510d850927e03ae7000000008c4930460221009c87c344760a64cb8ae6685a3eec2c1ac1bed5b88c87de51acd0e124f266c16602210082d07c037359c3a257b5c63ebd90f5a5edf97b2ac1c434b08ca998839f346dd40141040ba7e521fa7946d12edbb1d1e95a15c34bd4398195e86433c92b431cd315f455fe30032ede69cad9d1e1ed6c3c4ec0dbfced53438c625462afb792dcb098544bffffffff0240420f00000000001976a9144676d1b820d63ec272f1900d59d43bc6463d96f888ac40420f00000000001976a914648d04341d00d7968b3405c034adc38d4d8fb9bd88ac00000000010000000248cc917501ea5c55f4a8d2009c0567c40cfe037c2e71af017d0a452ff705e3f1000000008b483045022100bf5fdc86dc5f08a5d5c8e43a8c9d5b1ed8c65562e280007b52b133021acd9acc02205e325d613e555f772802bf413d36ba807892ed1a690a77811d3033b3de226e0a01410429fa713b124484cb2bd7b5557b2c0b9df7b2b1fee61825eadc5ae6c37a9920d38bfccdc7dc3cb0c47d7b173dbc9db8d37db0a33ae487982c59c6f8606e9d1791ffffffff41ed70551dd7e841883ab8f0b16bf04176b7d1480e4f0af9f3d4c3595768d068000000008b4830450221008513ad65187b903aed1102d1d0c47688127658c51106753fed0151ce9c16b80902201432b9ebcb87bd04ceb2de66035fbbaf4bf8b00d1cfe41f1a1f7338f9ad79d210141049d4cf80125bf50be1709f718c07ad15d0fc612b7da1f5570dddc35f2a352f0f27c978b06820edca9ef982c35fda2d255afba340068c5035552368bc7200c1488ffffffff0100093d00000000001976a9148edb68822f1ad580b043c7b3df2e400f8699eb4888ac00000000"), SER_NETWORK, PROTOCOL_VERSION);
stream >> block;
CBloomFilter filter(10, 0.000001, 0, BLOOM_UPDATE_NONE);
// Match the generation pubkey
filter.insert(ParseHex("04eaafc2314def4ca98ac970241bcab022b9c1e1f4ea423a20f134c876f2c01ec0f0dd5b2e86e7168cefe0d81113c3807420ce13ad1357231a2252247d97a46a91"));
// ...and the output address of the 4th transaction
filter.insert(ParseHex("b6efd80d99179f4f4ff6f4dd0a007d018c385d21"));
CMerkleBlock merkleBlock(block, filter);
BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash());
// We shouldn't match any outpoints (UPDATE_NONE)
BOOST_CHECK(!filter.contains(COutPoint(uint256("0x147caa76786596590baa4e98f5d9f48b86c7765e489f7a6ff3360fe5c674360b"), 0)));
BOOST_CHECK(!filter.contains(COutPoint(uint256("0x02981fa052f0481dbc5868f4fc2166035a10f27a03cfd2de67326471df5bc041"), 0)));
}
BOOST_AUTO_TEST_SUITE_END()
| [
"[email protected]"
] | |
48b631ed85685e64a314e4292ef8cfcaceabc024 | 6730e217faa36488f706f6ff4a997de550180b29 | /Tool/MyForm.cpp | 7ddefb0d51e0951f12114feea02418b001c8759e | [] | no_license | gameMedia/DirectX9_2D-Dungreed | 338ab671c341ce499b694f8e7b152c07ce4eca7f | fdfb3c5bebe0f7d269ea6787c03293443425e5c3 | refs/heads/master | 2023-08-21T12:37:00.079679 | 2021-10-10T09:40:30 | 2021-10-10T09:40:30 | 415,541,860 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 2,162 | cpp | // MyForm.cpp : 구현 파일입니다.
//
#include "stdafx.h"
#include "Tool.h"
#include "MyForm.h"
// CMyForm
IMPLEMENT_DYNCREATE(CMyForm, CFormView)
CMyForm::CMyForm()
: CFormView(IDD_MYFORM)
{
}
CMyForm::~CMyForm()
{
}
void CMyForm::DoDataExchange(CDataExchange* pDX)
{
CFormView::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CMyForm, CFormView)
ON_BN_CLICKED(IDC_BUTTON1, &CMyForm::OnBnClickedUnitTool)
ON_BN_CLICKED(IDC_BUTTON6, &CMyForm::OnBnClickedMapTool)
ON_BN_CLICKED(IDC_BUTTON7, &CMyForm::OnBnClickedPopUp)
ON_BN_CLICKED(IDC_BUTTON8, &CMyForm::OnBnClickedPathExtract)
END_MESSAGE_MAP()
// CMyForm 진단입니다.
#ifdef _DEBUG
void CMyForm::AssertValid() const
{
CFormView::AssertValid();
}
#ifndef _WIN32_WCE
void CMyForm::Dump(CDumpContext& dc) const
{
CFormView::Dump(dc);
}
#endif
#endif //_DEBUG
// CMyForm 메시지 처리기입니다.
void CMyForm::OnInitialUpdate()
{
CFormView::OnInitialUpdate();
// TODO: 여기에 특수화된 코드를 추가 및/또는 기본 클래스를 호출합니다.
m_Font.CreatePointFont(200, L"궁서");
GetDlgItem(IDC_BUTTON1)->SetFont(&m_Font);
GetDlgItem(IDC_BUTTON6)->SetFont(&m_Font);
GetDlgItem(IDC_BUTTON7)->SetFont(&m_Font);
GetDlgItem(IDC_BUTTON8)->SetFont(&m_Font);
if(nullptr == m_UnitTool.GetSafeHwnd())
m_UnitTool.Create(IDD_UNITTOOL);
if (nullptr == m_MapTool.GetSafeHwnd())
m_MapTool.Create(IDD_MAPTOOL);
if (nullptr == m_PopUp.GetSafeHwnd())
m_PopUp.Create(IDD_POPUP);
if (nullptr == m_PathExtract.GetSafeHwnd())
m_PathExtract.Create(IDD_PATHEXTRACT);
}
void CMyForm::OnBnClickedUnitTool()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
m_UnitTool.ShowWindow(SW_SHOW);
}
void CMyForm::OnBnClickedMapTool()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
m_MapTool.ShowWindow(SW_SHOW);
}
void CMyForm::OnBnClickedPopUp()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
m_PopUp.ShowWindow(SW_SHOW);
}
void CMyForm::OnBnClickedPathExtract()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
m_PathExtract.ShowWindow(SW_SHOW);
}
| [
"[email protected]"
] | |
ccc7022d2cc960dac1732cbae92f3f11c47b6592 | 631af35a3422941848dd308f73f000c02367c6de | /src/.old/2017.02.08_original_from_mwinde/Lbl_Mirror.cc | 7dcdf32d3f7181fafb12228f25a4a500697ee7f7 | [] | no_license | davitkalantaryan/pitz-laserbeamline | 14bacba04a7cbdde142abea4ecb85d22aa801ce2 | 600116d4f8011cf247f077f7b6c003e13f252b76 | refs/heads/master | 2023-01-20T08:09:17.195511 | 2020-12-04T14:37:49 | 2020-12-04T14:37:49 | 81,306,920 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 644 | cc | #include "Lbl_Mirror.h"
int EqFctLbl_Mirror::mirrorConf_done = 0;
EqFctLbl_Mirror::EqFctLbl_Mirror() :
EqFctLbl_XYDevice()
//??,mirrorConstB("MIRROR.CONST.B half of diameter", this)
{
if (!mirrorConf_done) {
//??list_append();
mirrorConf_done = 1;
}
};
smStatus EqFctLbl_Mirror::PerformSeletedCmd(int val) {
smStatus stat = 0;
int baseCmd = val & cmdMask_baseCmds;
switch(baseCmd) {
case cmd_zeroPosition:
pendingCommand |= cmdS_X_fine; // force additional fine-tuning
default: ; // not a command special to EqFctLbl_Mirror
}
stat = EqFctLbl_XYDevice::PerformSeletedCmd(val);
return stat;
}
| [
"[email protected]"
] | |
b593437d3f77dfdeb5648d66c44b9d77c70f2450 | b2646000cf8064bbddd1f609ec05f1f0038c29cf | /Rapsberry/catkin_ws/install/include/simulator/simulator_lightRequest.h | f14f73e5ec82b861de33aac8c8c7f7e543c76ab5 | [] | no_license | Oscaryanezgomez/R2D2- | 2fc27a4b1979ed11341066a914840eb9204e18e6 | cc93663f5e815659a9f5f742ba71c6a8d41f7b64 | refs/heads/master | 2020-07-25T16:34:21.203034 | 2019-09-17T17:34:39 | 2019-09-17T17:34:39 | 208,356,674 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,150 | h | // Generated by gencpp from file simulator/simulator_lightRequest.msg
// DO NOT EDIT!
#ifndef SIMULATOR_MESSAGE_SIMULATOR_LIGHTREQUEST_H
#define SIMULATOR_MESSAGE_SIMULATOR_LIGHTREQUEST_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>
namespace simulator
{
template <class ContainerAllocator>
struct simulator_lightRequest_
{
typedef simulator_lightRequest_<ContainerAllocator> Type;
simulator_lightRequest_()
: req(0) {
}
simulator_lightRequest_(const ContainerAllocator& _alloc)
: req(0) {
(void)_alloc;
}
typedef int32_t _req_type;
_req_type req;
typedef boost::shared_ptr< ::simulator::simulator_lightRequest_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::simulator::simulator_lightRequest_<ContainerAllocator> const> ConstPtr;
}; // struct simulator_lightRequest_
typedef ::simulator::simulator_lightRequest_<std::allocator<void> > simulator_lightRequest;
typedef boost::shared_ptr< ::simulator::simulator_lightRequest > simulator_lightRequestPtr;
typedef boost::shared_ptr< ::simulator::simulator_lightRequest const> simulator_lightRequestConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::simulator::simulator_lightRequest_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::simulator::simulator_lightRequest_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace simulator
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False}
// {'std_msgs': ['/opt/ros/indigo/share/std_msgs/cmake/../msg'], 'simulator': ['/home/diego/catkin_ws/src/simulator/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< ::simulator::simulator_lightRequest_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::simulator::simulator_lightRequest_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::simulator::simulator_lightRequest_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::simulator::simulator_lightRequest_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::simulator::simulator_lightRequest_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::simulator::simulator_lightRequest_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::simulator::simulator_lightRequest_<ContainerAllocator> >
{
static const char* value()
{
return "688ec893d5ff2cccc11b9bc8bc41109b";
}
static const char* value(const ::simulator::simulator_lightRequest_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0x688ec893d5ff2cccULL;
static const uint64_t static_value2 = 0xc11b9bc8bc41109bULL;
};
template<class ContainerAllocator>
struct DataType< ::simulator::simulator_lightRequest_<ContainerAllocator> >
{
static const char* value()
{
return "simulator/simulator_lightRequest";
}
static const char* value(const ::simulator::simulator_lightRequest_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::simulator::simulator_lightRequest_<ContainerAllocator> >
{
static const char* value()
{
return "int32 req\n\
";
}
static const char* value(const ::simulator::simulator_lightRequest_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::simulator::simulator_lightRequest_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.req);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct simulator_lightRequest_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::simulator::simulator_lightRequest_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::simulator::simulator_lightRequest_<ContainerAllocator>& v)
{
s << indent << "req: ";
Printer<int32_t>::stream(s, indent + " ", v.req);
}
};
} // namespace message_operations
} // namespace ros
#endif // SIMULATOR_MESSAGE_SIMULATOR_LIGHTREQUEST_H
| [
"[email protected]"
] | |
f74fe85d123c04b55509cd68f86479e1a3219d60 | 38763b01d06c87ff1164877f57fc22d0da2927e4 | /src/imageb_player/frmSettings.h | 8cd10104b309ab943321ecd2a362d40b6da65c74 | [] | no_license | JPSGoncalves/ImageB | 48b31b83bb1c032394c14e1df5ed90e2a285a521 | 135ccb9847f9e3394f2391417885d753a5b3a930 | refs/heads/master | 2023-03-17T03:57:10.299812 | 2011-07-20T16:59:41 | 2011-07-20T16:59:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 930 | h | #ifndef frmSettings_H
#define frmSettings_H
#include "ui_frmSettings.h"
#include "imgproc/imageproc.h"
#include "imgproc/imageb.h"
#include "imgproc/setupsinal.h"
//! global variable for signal setup options
extern SetupSinal signal_setup;
//! global variable to signal acquisition information
extern Acquisition aq;
using namespace std;
//! A class to control form frmSAFSAFT
/*!
this class provides an interface to process RF data from Michigan University dataset.
*/
class frmSettings : public QWidget, private Ui::frmSettings
{
Q_OBJECT
public:
frmSettings(QWidget *parent = 0);
private:
//! class for image processing
ImageProc imgproc;
//! matrix data from RF signal
Matrix rfdata;
//! Signal configuration setup
SetupSinal ssetup;
private slots:
void botCloseClicked();
void botCancelClicked();
signals:
;
};
#endif
| [
"[email protected]"
] | |
4223d3bd989b979b7afbc119cabd00c8a1e6fee1 | 8232ac568fdeca25a379445f49a3b27d6f9e4fd2 | /trash/vesperia/lib/gnuplot.h | 4d84f2280251f2bf82d3395a0307b4d2be080231 | [] | no_license | espin-tolosa/vesperia | 8fcd51ce43830fd6015f14acc4d0992b821bd69c | b7982f5847504c0ea480ed370efcc3a35016a5da | refs/heads/master | 2022-04-22T05:30:08.998050 | 2020-04-17T14:48:41 | 2020-04-17T14:48:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,034 | h | #ifndef GNUPLOT_H_INCLUDED
#define GNUPLOT_H_INCLUDED
//*t/tfin;
//360*t/tfin;
ofstream outFile_ofstream; //create an object type ofstream called outFile_ofstream
ofstream gnuPlot_ofstream;
ofstream outCell_ofstream;
ofstream outXPC4_ofstream;
ofstream outXPC8_ofstream;
ofstream outOCT1_ofstream;
ofstream outOCT2_ofstream;
ofstream outOCT3_ofstream;
ofstream outOCT4_ofstream;
string outputGNUFile = "temp/gnu.data";
string outputFileName = "temp/data.msh";
string outputFileCell = "temp/cell.msh";
string outputFileXPC4 = "temp/xpC4.msh";
string outputFileXPC8 = "temp/xpC8.msh";
string outputFileOCT1 = "temp/oct1.msh";
string outputFileOCT2 = "temp/oct2.msh";
string outputFileOCT3 = "temp/oct3.msh";
string outputFileOCT4 = "temp/oct4.msh";
gnuPlot_ofstream.open(outputGNUFile .c_str()); //C++03 or below: .c_str()
outFile_ofstream.open(outputFileName.c_str());
outCell_ofstream.open(outputFileCell.c_str());
outXPC4_ofstream.open(outputFileXPC4.c_str());
outXPC8_ofstream.open(outputFileXPC8.c_str());
outOCT1_ofstream.open(outputFileOCT1.c_str());
outOCT2_ofstream.open(outputFileOCT2.c_str());
outOCT3_ofstream.open(outputFileOCT3.c_str());
outOCT4_ofstream.open(outputFileOCT4.c_str());
// outFile_fstream.open(outFile_fstream, ios::out); //Error in the compiler by now
if(gnuPlot_ofstream.is_open())
{
gnuPlot_ofstream<<"#!/usr/bin/gnuplot -persist"<<std::endl;
gnuPlot_ofstream<<"set xrange [-2:2]"<<std::endl;
gnuPlot_ofstream<<"set yrange [-2:2]"<<std::endl;
gnuPlot_ofstream<<"set zrange [-5:5]"<<std::endl;
// gnuPlot_ofstream<<"set view equal xyz"<<std::endl;
gnuPlot_ofstream<<"set xlabel 'x-axis'"<<std::endl;
gnuPlot_ofstream<<"set ylabel 'y-axis'"<<std::endl;
gnuPlot_ofstream<<"set zlabel 'ts: "<<t<<"/"<<MyCube.Total_Cell_Divided<<"'"<<std::endl;
gnuPlot_ofstream<<"set grid"<<std::endl;
gnuPlot_ofstream<<"set hidden3d"<<std::endl;
gnuPlot_ofstream<<"set term png"<<std::endl;
gnuPlot_ofstream<<"set style line 1 lc rgb \"gray\""<<std::endl;
gnuPlot_ofstream<<"set style line 2 lc rgb \"red\""<<std::endl;
gnuPlot_ofstream<<"set view "<<VIEW_ROTX<<", "<<VIEW_ROTZ<<", 1, 1"<<std::endl;
gnuPlot_ofstream<<"set object 1 rectangle from screen 0,0 to screen 1,1 fillcolor rgb\"gray\""<<endl;
// gnuPlot_ofstream<<"set term png"<<std::endl;
gnuPlot_ofstream<<"set output \"printem."<<t+100<<".png\""<<std::endl;
gnuPlot_ofstream<<"splot 'temp/data.msh'using 1:2:3 lc 1,\\"<<std::endl;
gnuPlot_ofstream<<" 'temp/cell.msh'using 1:2:3 notitle lc 1 with lines,\\"<<std::endl;
gnuPlot_ofstream<<" 'temp/oct1.msh'using 1:2:3 notitle lc 2 with lines,\\"<<std::endl;
gnuPlot_ofstream<<" 'temp/oct2.msh'using 1:2:3 notitle lc 2 with lines,\\"<<std::endl;
gnuPlot_ofstream<<" 'temp/oct3.msh'using 1:2:3 notitle lc 2 with lines,\\"<<std::endl;
gnuPlot_ofstream<<" 'temp/oct4.msh'using 1:2:3 notitle lc 2 with lines,\\"<<std::endl;
gnuPlot_ofstream<<" 'temp/xpC8.msh'using 1:2:3 notitle lc 2 with lines\n"<<std::endl;
// gnuPlot_ofstream<<"replot"<<std::endl;
// gnuPlot_ofstream<<"set term x11"<<std::endl;
// gnuPlot_ofstream<<"exit"<<std::endl;
gnuPlot_ofstream.close();
}
if(outFile_ofstream.is_open())
{
// for(int i=0;i<MyCube.Log_Verts();i++)
// {
// outFile_ofstream<<MyCube.Mesh[i]<<std::endl;
// }
outFile_ofstream.close();
}
if(outCell_ofstream.is_open())
{
for(int j=0; j<MyCube.Log_Cells_Max(); j++)
{
MyCube.loadVertexId(j);
MyCube.loadCellEdges();
for(int i=0;i<12;i++)
{
outCell_ofstream<<*MyCube.Edge_i[i]<<endl;
outCell_ofstream<<*MyCube.Edge_j[i]<<endl;
// cout<<"SALIDA DE MALLA:"<<*MyCube.Edge_i[i]<<endl;
outCell_ofstream<<"\n\n"<<endl;
}
}
outCell_ofstream.close();
}
if(outOCT1_ofstream.is_open())
{
for(int j=0; j<Octree1->Log_Cells_Max(); j++)
{
Octree1->loadVertexId(j);
Octree1->loadCellEdges();
for(int i=0;i<12;i++)
{
// outOCT1_ofstream<<Octree1->Cell_Centroids[j]<<std::endl;
outOCT1_ofstream<<*Octree1->Edge_i[i]<<endl;
outOCT1_ofstream<<*Octree1->Edge_j[i]<<endl;
// cout<<"SALIDA DE MALLA:"<<*MyCube.Edge_i[i]<<endl;
outOCT1_ofstream<<"\n\n"<<endl;
}
}
outOCT1_ofstream.close();
}
if(outOCT2_ofstream.is_open())
{
for(int j=0; j<Octree2->Log_Cells_Max(); j++)
{
Octree2->loadVertexId(j);
Octree2->loadCellEdges();
for(int i=0;i<12;i++)
{
// outOCT1_ofstream<<Octree1->Cell_Centroids[j]<<std::endl;
outOCT2_ofstream<<*Octree2->Edge_i[i]<<endl;
outOCT2_ofstream<<*Octree2->Edge_j[i]<<endl;
// cout<<"SALIDA DE MALLA:"<<*MyCube.Edge_i[i]<<endl;
outOCT2_ofstream<<"\n\n"<<endl;
}
}
outOCT2_ofstream.close();
}
if(outOCT3_ofstream.is_open())
{
for(int j=0; j<Octree3->Log_Cells_Max(); j++)
{
Octree3->loadVertexId(j);
Octree3->loadCellEdges();
for(int i=0;i<12;i++)
{
// outOCT1_ofstream<<Octree1->Cell_Centroids[j]<<std::endl;
outOCT3_ofstream<<*Octree3->Edge_i[i]<<endl;
outOCT3_ofstream<<*Octree3->Edge_j[i]<<endl;
// cout<<"SALIDA DE MALLA:"<<*MyCube.Edge_i[i]<<endl;
outOCT3_ofstream<<"\n\n"<<endl;
}
}
outOCT3_ofstream.close();
}
if(outOCT4_ofstream.is_open())
{
for(int j=0; j<Octree4->Log_Cells_Max(); j++)
{
Octree4->loadVertexId(j);
Octree4->loadCellEdges();
for(int i=0;i<12;i++)
{
// outOCT1_ofstream<<Octree1->Cell_Centroids[j]<<std::endl;
outOCT4_ofstream<<*Octree4->Edge_i[i]<<endl;
outOCT4_ofstream<<*Octree4->Edge_j[i]<<endl;
// cout<<"SALIDA DE MALLA:"<<*MyCube.Edge_i[i]<<endl;
outOCT4_ofstream<<"\n\n"<<endl;
}
}
outOCT4_ofstream.close();
}
if(outXPC8_ofstream.is_open())
{
for(int j=0; j<number_of_points; j++)
{
outXPC8_ofstream<<point[j]<<std::endl;
//MyCube.Centroids[j]<<std::endl;
}
outXPC8_ofstream.close();
}
if(outXPC4_ofstream.is_open())
{
// for(int i=1;i<13;i++)
// {
// outXPC4_ofstream<<MyCube.Centroids[i]<<std::endl;
// }
outXPC4_ofstream.close();
}
else
{
cout<<"Could not create file: "<<outputFileName<<std::endl;
}
//std::cout<<"DISTANCE OF CENTROID TO VERTEX: "<<MyCube.Centroids[0];
#endif // GNUPLOT_H_INCLUDED
| [
"[email protected]"
] | |
6662e4208503c34f5b2ec95ddb7476191b387f5c | 84b7fe34b67839a2f08da10857a678a10042e181 | /scene_projections/ofxBox2D/src/ofxBox2d.cpp | 6f472624035b1d579ac4f1c0572165e85f90b718 | [] | no_license | jbloit/sound2graphics2sound | 5fcd6b91badb70635620ad415f620c91d17468a0 | 06f60c75b45f7be186cfa55fcb228c695bdf5d28 | refs/heads/master | 2021-01-16T19:09:18.899999 | 2014-10-13T07:52:18 | 2014-10-13T07:52:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,596 | cpp | #include "ofxBox2d.h"
// ------------------------------------------------------
ofxBox2d::ofxBox2d() {
enableContactEvents = false;
world = NULL;
m_bomb = NULL;
#ifdef TARGET_OPENGLES
// touch grabbing
for( int i=0; i<OF_MAX_TOUCH_JOINTS; i++ )
touchJoints[ i ] = NULL;
for( int i=0; i<OF_MAX_TOUCH_JOINTS; i++ )
touchBodies[ i ] = NULL;
#else
// mouse grabbing
mouseJoint = NULL;
mouseBody = NULL;
#endif
ground = NULL;
mainBody = NULL;
}
// ------------------------------------------------------
ofxBox2d::~ofxBox2d() {
#ifdef TARGET_OPENGLES
// destroy touch grabbing bodies
for(int i=0; i<OF_MAX_TOUCH_JOINTS; i++) {
if(touchBodies[i]) {
if(world) world->DestroyBody(touchBodies[i]);
}
}
#else
// destroy mouse grabbing body
if(mouseBody) {
if(world) world->DestroyBody(mouseBody);
}
#endif
if(world) {
for (b2Body* f = world->GetBodyList(); f; f = f->GetNext()) {
world->DestroyBody(f);
}
for (b2Joint* f = world->GetJointList(); f; f = f->GetNext()) {
world->DestroyJoint(f);
}
/*
// This is not safe...
delete world;
world = NULL;*/
}
}
// ------------------------------------------------------ init
void ofxBox2d::init() {
// settings
bHasContactListener = false;
bCheckBounds = false;
bEnableGrabbing = true;
scale = OFX_BOX2D_SCALE;
doSleep = true;
// gravity
gravity.set(0, 5.0f);
setFPS(30.0);
velocityIterations = 40;
positionIterations = 20;
#ifdef TARGET_OPENGLES
// touch grabbing
for( int i=0; i<OF_MAX_TOUCH_JOINTS; i++ )
touchJoints[ i ] = NULL;
for( int i=0; i<OF_MAX_TOUCH_JOINTS; i++ )
touchBodies[ i ] = NULL;
#else
// mouse grabbing
mouseJoint = NULL;
mouseBody = NULL;
#endif
// ground/bounds
// debug drawer
debugRender.setScale(scale);
debugRender.SetFlags(1);
//worldAABB.lowerBound.Set(-100.0f, -100.0f);
//worldAABB.upperBound.Set(100.0f, 100.0f);
delete world;
world = NULL;
world = new b2World(b2Vec2(gravity.x, gravity.y));
world->SetAllowSleeping(doSleep);
//world->SetDebugDraw(&debugRender);
if(ground!=NULL) {
world->DestroyBody(ground);
ground = NULL;
}
ofLog(OF_LOG_NOTICE, "ofxBox2d:: - world created -");
}
// ------------------------------------------------------ enable events
void ofxBox2d::enableEvents() {
if(world!=NULL) {
world->SetContactListener(this);
}
}
// ------------------------------------------------------ disable events
void ofxBox2d::disableEvents() {
if(world!=NULL) {
world->SetContactListener(NULL);
}
}
// ------------------------------------------------------ grab shapes
void ofxBox2d::setContactListener(ofxBox2dContactListener * listener) {
if(world != NULL) {
bHasContactListener = true;
world->SetContactListener(listener);
}
else {
ofLog(OF_LOG_WARNING, "ofxBox2d:: - world not inited -");
}
}
// ------------------------------------------------------ grab shapes Events
void ofxBox2d::registerGrabbing() {
#ifdef TARGET_OPENGLES
ofAddListener(ofEvents().touchDown, this, &ofxBox2d::touchDown);
ofAddListener(ofEvents().touchMoved, this, &ofxBox2d::touchMoved);
ofAddListener(ofEvents().touchUp, this, &ofxBox2d::touchUp);
#else
ofAddListener(ofEvents().mousePressed, this, &ofxBox2d::mousePressed);
ofAddListener(ofEvents().mouseDragged, this, &ofxBox2d::mouseDragged);
ofAddListener(ofEvents().mouseReleased, this, &ofxBox2d::mouseReleased);
#endif
}
#ifdef TARGET_OPENGLES
void ofxBox2d::touchDown(ofTouchEventArgs &touch) {
grabShapeDown(touch.x, touch.y, touch.id);
}
void ofxBox2d::touchMoved(ofTouchEventArgs &touch) {
grabShapeDragged(touch.x, touch.y, touch.id);
}
void ofxBox2d::touchUp(ofTouchEventArgs &touch) {
grabShapeUp(touch.x, touch.y, touch.id);
}
#else
void ofxBox2d::mousePressed(ofMouseEventArgs &e) {
grabShapeDown(e.x, e.y);
}
void ofxBox2d::mouseDragged(ofMouseEventArgs &e) {
grabShapeDragged(e.x, e.y);
}
void ofxBox2d::mouseReleased(ofMouseEventArgs &e) {
grabShapeUp(e.x, e.y);
}
#endif
// ------------------------------------------------------
void ofxBox2d::grabShapeDown(float x, float y, int id) {
if(world == NULL) {
ofLog(OF_LOG_WARNING, "ofxBox2d:: - Need a world, call init first! -");
return;
}
if(bEnableGrabbing) {
b2Vec2 p(x/OFX_BOX2D_SCALE, y/OFX_BOX2D_SCALE);
#ifdef TARGET_OPENGLES
if(id >= 0 && id < OF_MAX_TOUCH_JOINTS)
{
if(touchJoints[id] != NULL)
return;
if( touchBodies[id] == NULL) {
b2BodyDef bd;
touchBodies[id] = world->CreateBody(&bd);
}
}
else
return; // invalid mouse / touch id.
#else
if (mouseJoint != NULL) {
return;
}
if(mouseBody == NULL) {
b2BodyDef bd;
mouseBody = world->CreateBody(&bd);
}
#endif
// Make a small box.
b2AABB aabb;
b2Vec2 d;
d.Set(0.001f, 0.001f);
aabb.lowerBound = p - d;
aabb.upperBound = p + d;
// Query the world for overlapping shapes.
QueryCallback callback(p);
world->QueryAABB(&callback, aabb);
if (callback.m_fixture) {
b2Body* body = callback.m_fixture->GetBody();
b2MouseJointDef md;
md.bodyB = body;
md.target = p;
md.maxForce = 1000.0f * body->GetMass();
#ifdef TARGET_OPENGLES
md.bodyA = touchBodies[id];
touchJoints[id] = (b2MouseJoint*)world->CreateJoint(&md);
#else
md.bodyA = mouseBody;
mouseJoint = (b2MouseJoint*)world->CreateJoint(&md);
#endif
body->SetAwake(true);
}
}
}
// ------------------------------------------------------
void ofxBox2d::grabShapeUp(float x, float y, int id) {
#ifdef TARGET_OPENGLES
if(id >= 0 && id < OF_MAX_TOUCH_JOINTS) {
if(touchJoints[id] && bEnableGrabbing){
if(world == NULL) {
ofLog(OF_LOG_WARNING, "ofxBox2d:: - Need a world, call init first! -");
return;
}
world->DestroyJoint(touchJoints[id]);
touchJoints[id] = NULL;
}
}
#else
if(mouseJoint && bEnableGrabbing) {
if(world == NULL) {
ofLog(OF_LOG_WARNING, "ofxBox2d:: - Need a world, call init first! -");
return;
}
world->DestroyJoint(mouseJoint);
mouseJoint = NULL;
}
#endif
}
// ------------------------------------------------------
void ofxBox2d::grabShapeDragged(float x, float y, int id) {
b2Vec2 p(x/OFX_BOX2D_SCALE, y/OFX_BOX2D_SCALE);
#ifdef TARGET_OPENGLES
if(id >= 0 && id < OF_MAX_TOUCH_JOINTS) {
if (touchJoints[id] && bEnableGrabbing)
touchJoints[id]->SetTarget(p);
}
#else
if (mouseJoint && bEnableGrabbing)
mouseJoint->SetTarget(p);
#endif
}
// ------------------------------------------------------
int ofxBox2d::getBodyCount() {
if(world)
return world->GetBodyCount();
return 0;
}
// ------------------------------------------------------
int ofxBox2d::getJointCount() {
if(world)
return world->GetJointCount();
return 0;
}
// ------------------------------------------------------ wake up
void ofxBox2d::wakeupShapes() {
if(world == NULL) {
ofLog(OF_LOG_WARNING, "ofxBox2d:: - Need a world, call init first! -");
return;
}
b2Body* bodies = world->GetBodyList();
while(bodies) {
b2Body* b = bodies;
if(b) {
if( !b->IsAwake() ) b->SetAwake(true);
}
bodies = bodies->GetNext();
}
}
// ------------------------------------------------------ set gravity
void ofxBox2d::setGravity(ofPoint pt) {
setGravity(pt.x, pt.y);
}
void ofxBox2d::setGravity(float x, float y) {
if(world == NULL) {
ofLog(OF_LOG_WARNING, "ofxBox2d:: - Need a world, call init first! -");
return;
}
world->SetGravity(b2Vec2(x, y));
wakeupShapes();
}
ofPoint ofxBox2d::getGravity() {
if(world == NULL) {
ofLog(OF_LOG_WARNING, "ofxBox2d:: - Need a world, call init first! -");
return ofPoint();
}
return ofPoint(world->GetGravity().x, world->GetGravity().y);
}
// ------------------------------------------------------ set bounds
void ofxBox2d::setBounds(ofPoint lowBounds, ofPoint upBounds) {
//TODO: still need to work on this...
}
// ------------------------------------------------------ create Ground
void ofxBox2d::createGround(float x1, float y1, float x2, float y2) {
if(world == NULL) {
ofLog(OF_LOG_WARNING, "ofxBox2d:: - Need a world, call init first! -");
return;
}
if(ground!=NULL) world->DestroyBody(ground);
b2BodyDef bd;
ground = world->CreateBody(&bd);
b2EdgeShape shape;
shape.Set(b2Vec2(x1/OFX_BOX2D_SCALE, y1/OFX_BOX2D_SCALE), b2Vec2(x2/OFX_BOX2D_SCALE, y2/OFX_BOX2D_SCALE));
ground->CreateFixture(&shape, 0.0f);
}
// ------------------------------------------------------ create Ground
void ofxBox2d::createGround(const ofPoint & p1, const ofPoint & p2) {
createGround(p1.x, p1.y, p2.x, p2.y);
}
// ------------------------------------------------------ create bounds
void ofxBox2d::createBounds(ofRectangle rec) {
createBounds(rec.x, rec.y, rec.width, rec.height);
}
// ------------------------------------------------------ create bounds
void ofxBox2d::createBounds(float x, float y, float w, float h) {
if(world == NULL) {
ofLog(OF_LOG_WARNING, "ofxBox2d:: - Need a world, call init first! -");
return;
}
if(ground!=NULL) world->DestroyBody(ground);
b2BodyDef bd;
bd.position.Set(0, 0);
ground = world->CreateBody(&bd);
b2EdgeShape shape;
ofRectangle rec(x/OFX_BOX2D_SCALE, y/OFX_BOX2D_SCALE, w/OFX_BOX2D_SCALE, h/OFX_BOX2D_SCALE);
//right wall
shape.Set(b2Vec2(rec.x+rec.width, rec.y), b2Vec2(rec.x+rec.width, rec.y+rec.height));
ground->CreateFixture(&shape, 0.0f);
//left wall
shape.Set(b2Vec2(rec.x, rec.y), b2Vec2(rec.x, rec.y+rec.height));
ground->CreateFixture(&shape, 0.0f);
// top wall
shape.Set(b2Vec2(rec.x, rec.y), b2Vec2(rec.x+rec.width, rec.y));
ground->CreateFixture(&shape, 0.0f);
// bottom wall
shape.Set(b2Vec2(rec.x, rec.y+rec.height), b2Vec2(rec.x+rec.width, rec.y+rec.height));
ground->CreateFixture(&shape, 0.0f);
// add custom user data
ground->SetUserData(new BoundsData());
BoundsData * myBoundsData = (BoundsData*) ground->GetUserData();
}
// ------------------------------------------------------ check if shapes are out of bounds
void ofxBox2d::checkBounds(bool b) {
bCheckBounds = b;
}
// ------------------------------------------------------
void ofxBox2d::setIterations(int velocityTimes, int positionTimes) {
velocityIterations = velocityTimes;
positionIterations = positionTimes;
}
// ------------------------------------------------------
void ofxBox2d::update() {
if(world == NULL) {
ofLog(OF_LOG_WARNING, "ofxBox2d:: - Need a world, call init first! -");
return;
}
// destroy the object if we are out of the bounds
if(bCheckBounds) {
/*
float top = 0;
float bottom = ofGetHeight();
float right = ofGetWidth();
float left = 0;
b2Body* node = world->GetBodyList();
while(node) {
b2Body* b = node;
node = node->GetNext();
b2Vec2 p = b->GetPosition();
ofxBox2dBaseShape* base = (ofxBox2dBaseShape*)b->GetUserData();
if(base) {
//printf("dead:%i\n", base->dead);
if(p.y*OFX_BOX2D_SCALE > bottom) {
base->dead = true;
world->DestroyBody(b);
}
if(p.y*OFX_BOX2D_SCALE < top) {
base->dead = true;
world->DestroyBody(b);
}
if(p.x*OFX_BOX2D_SCALE > right) {
base->dead = true;
world->DestroyBody(b);
}
if(p.x*OFX_BOX2D_SCALE < left) {
base->dead = true;
world->DestroyBody(b);
}
*/
}
float timeStep = (1.0f / fps);
world->Step(timeStep, velocityIterations, positionIterations);
//world->Validate();
}
// ------------------------------------------------------
void ofxBox2d::drawGround() {
if(ground == NULL) return;
const b2Transform& xf = ground->GetTransform();
for (b2Fixture* f = ground->GetFixtureList(); f; f = f->GetNext()) {
b2EdgeShape* edge = (b2EdgeShape*)f->GetShape();
if(edge) {
ofNoFill();
ofSetColor(120, 0, 120);
ofLine(worldPtToscreenPt(edge->m_vertex0), worldPtToscreenPt(edge->m_vertex1));
}
}
}
// ------------------------------------------------------
void ofxBox2d::draw() {
drawGround();
}
| [
"[email protected]"
] | |
9f3c5898afad1e481507a4972516c7b9ad2a3250 | d1a04ef0dd0fa41b0e6d84f66fb14c2b3a7d1771 | /honeybee_proj/HBH/syn/systemc/honeybee_fcmp_32nfYi.h | 89b2d08fd7c09bb52f0237981896f5c111d6b1a7 | [
"MIT"
] | permissive | AnthonyKenny98/HoneyBee | 927f9d74bfaa4c3f2707e11c6de81d4db37cc73b | 5b1859fe8c50cb5bd709f53780c4e5ce7160b987 | refs/heads/master | 2021-01-08T05:33:05.584975 | 2020-04-15T22:55:15 | 2020-04-15T22:55:15 | 241,922,569 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,234 | h | // ==============================================================
// Vivado(TM) HLS - High-Level Synthesis from C, C++ and SystemC v2019.2 (64-bit)
// Copyright 1986-2019 Xilinx, Inc. All Rights Reserved.
// ==============================================================
#ifndef __honeybee_fcmp_32nfYi__HH__
#define __honeybee_fcmp_32nfYi__HH__
#include "ACMP_fcmp.h"
#include <systemc>
template<
int ID,
int NUM_STAGE,
int din0_WIDTH,
int din1_WIDTH,
int dout_WIDTH>
SC_MODULE(honeybee_fcmp_32nfYi) {
sc_core::sc_in_clk clk;
sc_core::sc_in<sc_dt::sc_logic> reset;
sc_core::sc_in<sc_dt::sc_logic> ce;
sc_core::sc_in< sc_dt::sc_lv<din0_WIDTH> > din0;
sc_core::sc_in< sc_dt::sc_lv<din1_WIDTH> > din1;
sc_core::sc_in< sc_dt::sc_lv<5> > opcode;
sc_core::sc_out< sc_dt::sc_lv<dout_WIDTH> > dout;
ACMP_fcmp<ID, 2, din0_WIDTH, din1_WIDTH, dout_WIDTH> ACMP_fcmp_U;
SC_CTOR(honeybee_fcmp_32nfYi): ACMP_fcmp_U ("ACMP_fcmp_U") {
ACMP_fcmp_U.clk(clk);
ACMP_fcmp_U.reset(reset);
ACMP_fcmp_U.ce(ce);
ACMP_fcmp_U.din0(din0);
ACMP_fcmp_U.din1(din1);
ACMP_fcmp_U.dout(dout);
ACMP_fcmp_U.opcode(opcode);
}
};
#endif //
| [
"[email protected]"
] | |
e963402bd145667e631e95a51a715faa5083ee89 | 6485cd7f1cc389e8f70ddcf3857dcde448b91406 | /FastSimulation/Tracking/plugins/SimTrackIdProducer.h | f96e4d35d1d1f0a84dee1ede2f8e85550247b20f | [] | no_license | GLP90/cmssw | 4e3a83993ff0672612326df328c4344fedacf192 | 83151f6f1086270a53346945e2da73f332e5298a | refs/heads/CMSSW_7_5_X | 2020-12-30T21:53:51.630020 | 2015-05-20T09:52:38 | 2015-05-20T09:52:38 | 35,955,829 | 2 | 0 | null | 2016-03-02T14:31:21 | 2015-05-20T15:13:27 | C++ | UTF-8 | C++ | false | false | 987 | h | #ifndef FastSimulation_Tracking_SimTrackIdProducer_h
#define FastSimulation_Tracking_SimTrackIdProducer_h
#include "FWCore/Framework/interface/stream/EDProducer.h"
#include "FWCore/Utilities/interface/InputTag.h"
#include "DataFormats/Common/interface/ValueMap.h"
#include "DataFormats/TrackReco/interface/Track.h"
#include <vector>
#include <string>
namespace edm {
class ParameterSet;
class Event;
class EventSetup;
}
class SimTrackIdProducer : public edm::stream::EDProducer <>
{
public:
explicit SimTrackIdProducer(const edm::ParameterSet& conf);
virtual ~SimTrackIdProducer() {}
virtual void produce(edm::Event& e, const edm::EventSetup& es) override;
private:
// consumes
edm::EDGetTokenT<reco::TrackCollection> trackToken;
double maxChi2_;
std::vector< edm::EDGetTokenT<edm::ValueMap<int> > > overrideTrkQuals_;
bool filterTracks_ = false;
reco::TrackBase::TrackQuality trackQuality_;
};
#endif
| [
"[email protected]"
] | |
80e0656ccbb6c8a6cf72291b3949f265a5261e11 | 9e272210463dd47a66e0c359ebb47a3088dffd07 | /Arduino示例程序中文翻译/24 MC猜数字(6)- 完成制作/Lesson24_3/Lesson24_3.ino | c7682acb8b075204bf33d4dcb73b7ce99a0811e2 | [] | no_license | Noroom569/Arduino | 8a5fe0c28fa885e4af1edacc6f5a7174bdd991bd | e8bd3d2f962d6dcf2025129f006d640e70b0909e | refs/heads/master | 2023-08-31T17:26:23.676849 | 2021-09-22T15:02:15 | 2021-09-22T15:02:15 | 409,244,657 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,374 | ino | /*
24 MC猜数字 - 5 完成制作 - 3
每次按键后闪动随机图案,最后停留在一个数字上面
此版本已基本实现猜数字游戏装置功能。
*/
int myNumber;
void setup() {
pinMode(2, INPUT_PULLUP);
Serial.begin(9600);
int pinNumber = 3;
while(pinNumber <= 9){
pinMode(pinNumber, OUTPUT);
pinNumber = pinNumber + 1;
}
randomSeed(analogRead(A0));
}
// the loop function runs over and over again forever
void loop() {
if (!digitalRead(2)){
myNumber = getRandomNumber(0, 10);
}
displayNumber(myNumber);
}
int getRandomNumber(int minNumber, int maxNumber){
int randomNumber;
int i;
while(i < 15){
i = i + 1;
randomNumber = random(minNumber,maxNumber);
//displayNumber(randomNumber);
displayRandom();
delay(100);
displayClear();
delay(100);
Serial.print("i = ");
Serial.println(i);
Serial.print("randomNumber = ");
Serial.println(randomNumber);
Serial.println("");
}
return randomNumber;
}
void displayNumber(int ledNumber){
switch(ledNumber){
case 1: //显示1
digitalWrite(4, HIGH);
digitalWrite(7, HIGH);
break;
case 2: //显示2
digitalWrite(3, HIGH);
digitalWrite(4, HIGH);
digitalWrite(5, HIGH);
digitalWrite(8, HIGH);
digitalWrite(9, HIGH);
break;
case 3: //显示3
digitalWrite(3, HIGH);
digitalWrite(4, HIGH);
digitalWrite(5, HIGH);
digitalWrite(7, HIGH);
digitalWrite(8, HIGH);
break;
case 4: //显示4
digitalWrite(4, HIGH);
digitalWrite(5, HIGH);
digitalWrite(6, HIGH);
digitalWrite(7, HIGH);
break;
case 5: //显示5
digitalWrite(3, HIGH);
digitalWrite(5, HIGH);
digitalWrite(6, HIGH);
digitalWrite(7, HIGH);
digitalWrite(8, HIGH);
break;
case 6: //显示6
digitalWrite(3, HIGH);
digitalWrite(5, HIGH);
digitalWrite(6, HIGH);
digitalWrite(7, HIGH);
digitalWrite(8, HIGH);
digitalWrite(9, HIGH);
break;
case 7: //显示7
digitalWrite(3, HIGH);
digitalWrite(4, HIGH);
digitalWrite(7, HIGH);
break;
case 8: //显示8
digitalWrite(3, HIGH);
digitalWrite(4, HIGH);
digitalWrite(5, HIGH);
digitalWrite(6, HIGH);
digitalWrite(7, HIGH);
digitalWrite(8, HIGH);
digitalWrite(9, HIGH);
break;
case 9: //显示9
digitalWrite(3, HIGH);
digitalWrite(4, HIGH);
digitalWrite(5, HIGH);
digitalWrite(6, HIGH);
digitalWrite(7, HIGH);
digitalWrite(8, HIGH);
break;
case 0: //显示默认
digitalWrite(3, HIGH);
digitalWrite(4, HIGH);
digitalWrite(6, HIGH);
digitalWrite(7, HIGH);
digitalWrite(8, HIGH);
digitalWrite(9, HIGH);
break;
default:
digitalWrite(4, HIGH);
digitalWrite(5, HIGH);
digitalWrite(7, HIGH);
digitalWrite(8, HIGH);
digitalWrite(9, HIGH);
}
}
void displayClear(){
digitalWrite(3, LOW);
digitalWrite(4, LOW);
digitalWrite(5, LOW);
digitalWrite(6, LOW);
digitalWrite(7, LOW);
digitalWrite(8, LOW);
digitalWrite(9, LOW);
}
void displayRandom(){
int randomPin = random(3,9);
digitalWrite(randomPin, HIGH);
}
| [
"[email protected]"
] | |
9144e3688155fcb537a9ead3bf441b28ce6be8b5 | 5470644b5f0834b9646649da365c96101a2f9b2a | /Sources/Elastos/LibCore/src/org/apache/harmony/security/pkcs7/CSignerInfo.cpp | 6dd3d568d9b8c13985f91ba9b7e9022e9c351298 | [] | no_license | dothithuy/ElastosRDK5_0 | 42372da3c749170581b5ee9b3884f4a27ae81608 | 2cf231e9f09f8b3b8bcacb11080b4a87d047833f | refs/heads/master | 2021-05-13T15:02:22.363934 | 2015-05-25T01:54:38 | 2015-05-25T01:54:38 | 116,755,452 | 1 | 0 | null | 2018-01-09T02:33:06 | 2018-01-09T02:33:06 | null | UTF-8 | C++ | false | false | 9,998 | cpp |
#include "CSignerInfo.h"
#include <cmdef.h>
#include <elastos/StringBuilder.h>
using Elastos::Core::StringBuilder;
using Org::Apache::Harmony::Security::X501::CName;
namespace Org {
namespace Apache {
namespace Harmony {
namespace Security {
namespace Pkcs7 {
CAR_INTERFACE_IMPL(CSignerInfo::ASN1SequenceDerived1, IASN1Sequence)
CAR_INTERFACE_IMPL(CSignerInfo::ASN1SequenceDerived2, IASN1Sequence)
ASN1SEQUENCE_METHODS_IMPL(CSignerInfo::ASN1SequenceDerived1, ASN1Sequence)
ASN1SEQUENCE_METHODS_IMPL(CSignerInfo::ASN1SequenceDerived2, ASN1Sequence)
ECode CSignerInfo::ASN1SequenceDerived1::GetValues(
/* [in] */ IInterface* object,
/* [in] */ ArrayOf<IInterface*>* values)
{
AutoPtr<IInterface> tmp;
AutoPtr<IArrayOf> issAndSerial = IArrayOf::Probe(object);
issAndSerial->Get(0, (IInterface**)&tmp);
values->Set(0, tmp);
tmp = NULL;
issAndSerial->Get(1, (IInterface**)&tmp);
values->Set(1, tmp);
return NOERROR;
}
ECode CSignerInfo::ASN1SequenceDerived1::GetDecodedObject(
/* [in] */ IBerInputStream* bis,
/* [out] */ IInterface** object)
{
return ASN1Sequence::GetDecodedObject(bis, object);
}
CSignerInfo::ASN1SequenceDerived1::ASN1SequenceDerived1(
/* [in] */ ArrayOf<IASN1Type *>* type)
{
ASN1Sequence::Init(type);
}
ECode CSignerInfo::ASN1SequenceDerived2::GetValues(
/* [in] */ IInterface* object,
/* [in] */ ArrayOf<IInterface*>* values)
{
AutoPtr<CSignerInfo> si = object;
AutoPtr<ArrayOf<Byte> > bytes = ArrayOf<Byte>::Alloc(1);
(*bytes)[0] = (Byte)si->mVersion;
AutoPtr<IArrayOf> arr;
CArrayOf::New(EIID_IByte, 1, (IArrayOf**)&arr);
AutoPtr<IByte> bt;
CByte::New((*bytes)[0], (IByte**)&bt);
arr->Put(0, bt.Get());
values->Set(0, arr.Get());
arr = NULL;
CArrayOf::New(EIID_IInterface, 2, (IArrayOf**)&arr);
String str;
si->mIssuer->GetName(&str);
AutoPtr<IName> name;
CName::New(str, (IName**)&name);
arr->Set(0, name.Get());
bytes = NULL;
FAIL_RETURN(si->mSerialNumber->ToByteArray((ArrayOf<Byte>**)&bytes))
AutoPtr<IArrayOf> arrTmp;
CArrayOf::New(EIID_IInterface, 2, (IArrayOf**)&arrTmp);
for (Int32 i = 0; i < bytes->GetLength(); i++) {
AutoPtr<IByte> bt;
CByte::New((*bytes)[i], (IByte**)&bt);
arrTmp->Put(i, bt.Get());
}
arr->Set(1, arrTmp.Get());
FAIL_RETURN(values->Set(1, arr.Get()))
values->Set(2, si->mDigestAlgorithm.Get());
values->Set(3, si->mAuthenticatedAttributes.Get());
values->Set(4, si->mDigestEncryptionAlgorithm.Get());
values->Set(5, si->mEncryptedDigest.Get());
values->Set(6, si->mUnauthenticatedAttributes.Get());
return NOERROR;
}
ECode CSignerInfo::ASN1SequenceDerived2::GetDecodedObject(
/* [in] */ IBerInputStream* bis,
/* [out] */ IInterface** object)
{
AutoPtr<IInterface> content;
bis->GetContent((IInterface**)&content);
AutoPtr<IArrayOf> values = IArrayOf::Probe(content);
Int32 arg1;
AutoPtr<IASN1IntegerHelper> asn1IntHelper;
CASN1IntegerHelper::AcquireSingleton((IASN1IntegerHelper**)&asn1IntHelper);
AutoPtr<IInterface> val0;
values->Get(0, (IInterface**)&val0);
asn1IntHelper->ToIntValue(val0, &arg1);
val0 = NULL;
values->Get(1, (IInterface**)&val0);
Int32 size;
IArrayOf::Probe(val0)->GetSize(&size);
AutoPtr<ArrayOf<IInterface*> > arg2 = ArrayOf<IInterface*>::Alloc(size);
for (Int32 i = 0; i < size; i++) {
AutoPtr<IInterface> elem;
IArrayOf::Probe(val0)->Get(i, (IInterface**)&elem);
arg2->Set(i, elem);
}
val0 = NULL;
values->Get(2, (IInterface**)&val0);
AutoPtr<IAlgorithmIdentifier> arg3 = IAlgorithmIdentifier::Probe(val0);
val0 = NULL;
values->Get(3, (IInterface**)&val0);
AutoPtr<IAuthenticatedAttributes> arg4 = IAuthenticatedAttributes::Probe(val0);
val0 = NULL;
values->Get(4, (IInterface**)&val0);
AutoPtr<IAlgorithmIdentifier> arg5 = IAlgorithmIdentifier::Probe(val0);
val0 = NULL;
values->Get(5, (IInterface**)&val0);
IArrayOf::Probe(val0)->GetSize(&size);
AutoPtr<ArrayOf<Byte> > arg6 = ArrayOf<Byte>::Alloc(size);
for (Int32 i = 0; i < size; i++) {
AutoPtr<IInterface> elem;
IArrayOf::Probe(val0)->Get(i, (IInterface**)&elem);
Byte bt;
IByte::Probe(elem)->GetValue(&bt);
(*arg6)[i] = bt;
}
val0 = NULL;
values->Get(6, (IInterface**)&val0);
AutoPtr<IList> arg7 = IList::Probe(val0);
*object = new CSignerInfo(arg1, arg2, arg3, arg4, arg5, arg6, arg7);
INTERFACE_ADDREF(*object);
return NOERROR;
}
CSignerInfo::ASN1SequenceDerived2::ASN1SequenceDerived2(
/* [in] */ ArrayOf<IASN1Type *>* type)
{
ASN1Sequence::Init(type);
}
static AutoPtr<IASN1Sequence> ISSUER_AND_SERIAL_NUMBER;
static AutoPtr<IASN1Sequence> ASN1 = InitStatic();
AutoPtr<IASN1Sequence> CSignerInfo::InitStatic()
{
AutoPtr<IASN1Sequence> ret;
AutoPtr<ArrayOf<IASN1Type*> > argForISN = ArrayOf<IASN1Type*>::Alloc(2);
argForISN->Set(0, CName::ASN1.Get());
AutoPtr<IASN1IntegerHelper> hlp;
CASN1IntegerHelper::AcquireSingleton((IASN1IntegerHelper**)&hlp);
AutoPtr<IASN1Integer> asn1Int;
hlp->GetInstance((IASN1Integer**)&asn1Int);
argForISN->Set(1, asn1Int.Get());
ISSUER_AND_SERIAL_NUMBER = new ASN1SequenceDerived1(argForISN);
AutoPtr<ArrayOf<IASN1Type*> > argForASN1 = ArrayOf<IASN1Type*>::Alloc(7);
argForASN1->Set(0, asn1Int.Get());
argForASN1->Set(1, ISSUER_AND_SERIAL_NUMBER.Get());
argForASN1->Set(2, CAlgorithmIdentifier::ASN1.Get());
AutoPtr<IASN1Implicit> tmp;
CASN1Implicit::New(0, CAuthenticatedAttributes::ASN1.Get(), (IASN1Implicit**)&tmp);
argForASN1->Set(3, tmp.Get());
argForASN1->Set(4, CAlgorithmIdentifier::ASN1.Get());
AutoPtr<IASN1OctetStringHelper> aosh;
AutoPtr<IASN1OctetString> aos;
CASN1OctetStringHelper::AcquireSingleton((IASN1OctetStringHelper**)&aosh);
aosh->GetInstance((IASN1OctetString**)&aos);
argForASN1->Set(5, aos.Get());
AutoPtr<IASN1SetOf> aso;
CASN1SetOf::New(CAttributeTypeAndValue::ASN1.Get(), (IASN1SetOf**)&aso);
tmp = NULL;
CASN1Implicit::New(1, aso.Get(), (IASN1Implicit**)&tmp);
argForASN1->Set(6, tmp.Get());
ret = new ASN1SequenceDerived2(argForASN1);
return ret;
}
CSignerInfo::CSignerInfo()
{}
CSignerInfo::CSignerInfo(
/* [in] */ Int32 version,
/* [in] */ ArrayOf<IInterface*>* issuerAndSerialNumber,
/* [in] */ IAlgorithmIdentifier* digestAlgorithm,
/* [in] */ IAuthenticatedAttributes* authenticatedAttributes,
/* [in] */ IAlgorithmIdentifier* digestEncryptionAlgorithm,
/* [in] */ ArrayOf<Byte>* encryptedDigest,
/* [in] */ IList* unauthenticatedAttributes)
{
mVersion = version;
IName::Probe((*issuerAndSerialNumber)[0])->GetX500Principal((IX500Principal**)&mIssuer);
AutoPtr<IASN1IntegerHelper> helper;
CASN1IntegerHelper::AcquireSingleton((IASN1IntegerHelper**)&helper);
helper->ToBigIntegerValue((*issuerAndSerialNumber)[1], (IBigInteger**)&mSerialNumber);
mDigestAlgorithm = digestAlgorithm;
mAuthenticatedAttributes = authenticatedAttributes;
mDigestEncryptionAlgorithm = digestEncryptionAlgorithm;
mEncryptedDigest = encryptedDigest;
mUnauthenticatedAttributes = unauthenticatedAttributes;
}
ECode CSignerInfo::GetIssuer(
/* [out] */ IX500Principal** issuer)
{
VALIDATE_NOT_NULL(issuer)
*issuer = mIssuer;
INTERFACE_ADDREF(*issuer);
return NOERROR;
}
ECode CSignerInfo::GetSerialNumber(
/* [out] */ IBigInteger** serialNumber)
{
VALIDATE_NOT_NULL(serialNumber)
*serialNumber = mSerialNumber;
INTERFACE_ADDREF(*serialNumber)
return NOERROR;
}
ECode CSignerInfo::GetDigestAlgorithm(
/* [out] */ String* algorithm)
{
return mDigestAlgorithm->GetAlgorithm(algorithm);
}
ECode CSignerInfo::GetDigestEncryptionAlgorithm(
/* [out] */ String* digestEncryptionAlgorithm)
{
return mDigestEncryptionAlgorithm->GetAlgorithm(digestEncryptionAlgorithm);
}
ECode CSignerInfo::GetAuthenticatedAttributes(
/* [out] */ IList** authenticatedAttributes)
{
if (mAuthenticatedAttributes == NULL) {
return NOERROR;
}
return mAuthenticatedAttributes->GetAttributes(authenticatedAttributes);
}
ECode CSignerInfo::GetEncodedAuthenticatedAttributes(
/* [out, callee] */ ArrayOf<Byte>** encodedAuthenticatedAttributes)
{
if (mAuthenticatedAttributes == NULL) {
return NOERROR;
}
return mAuthenticatedAttributes->GetEncoded(encodedAuthenticatedAttributes);
}
ECode CSignerInfo::GetEncryptedDigest(
/* [out, callee] */ ArrayOf<Byte>** encryptedDigest)
{
VALIDATE_NOT_NULL(encryptedDigest)
*encryptedDigest = mEncryptedDigest;
INTERFACE_ADDREF(*encryptedDigest)
return NOERROR;
}
ECode CSignerInfo::ToString(
/* [out] */ String* ret)
{
StringBuilder res();
res.AppendCStr("-- SignerInfo:");
res.AppendCStr("\n version : ");
res.AppendInt32(mVersion);
res.AppendCStr("\nissuerAndSerialNumber: ");
res.AppendObject(mIssuer.Get());
res.AppendCStr(" ");
res.AppendObject(mSerialNumber.Get());
res.AppendCStr("\ndigestAlgorithm: ");
String str;
mDigestAlgorithm->ToString(&str);
res.AppendString(str);
res.AppendCStr("\nauthenticatedAttributes: ");
if (mAuthenticatedAttributes != NULL) {
mAuthenticatedAttributes->ToString(&str);
res.AppendString(str);
}
res.AppendCStr("\ndigestEncryptionAlgorithm: ");
mDigestEncryptionAlgorithm->ToString(&str);
res.AppendString(str);
res.AppendCStr("\nunauthenticatedAttributes: ");
if (mUnauthenticatedAttributes != NULL) {
mUnauthenticatedAttributes->ToString(&str);
res.AppendString(str);
}
res.AppendCStr("\n-- SignerInfo End\n");
return res.ToString(ret);
}
} // namespace Pkcs7
} // namespace Security
} // namespace Harmony
} // namespace Apache
} // namespace Org
| [
"[email protected]"
] | |
4f13c3625c279abf3320e2bb57c63e9604cab66d | 76543bb0e041f2d759ebbb79c386db5b46a4b3ab | /CvGameCoreDLL_Expansion2/CvEspionageClasses.h | 21b59b0f0535b3dc91d7d7654bd8b42528b4bbba | [] | no_license | mcymsb/Community-Patch-DLL | 25cd6d3a848d47df648adbacf4a8066baa4ae092 | 2d126a605761a9ed53a3e5e6aa6f128d54ec91a0 | refs/heads/master | 2023-04-24T19:03:57.392452 | 2021-05-14T18:19:18 | 2021-05-14T18:19:18 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 15,662 | h | /* -------------------------------------------------------------------------------------------------------
© 1991-2012 Take-Two Interactive Software and its subsidiaries. Developed by Firaxis Games.
Sid Meier's Civilization V, Civ, Civilization, 2K Games, Firaxis Games, Take-Two Interactive Software
and their respective logos are all trademarks of Take-Two interactive Software, Inc.
All other marks and trademarks are the property of their respective owners.
All rights reserved.
------------------------------------------------------------------------------------------------------- */
#pragma once
#ifndef CIV5_ESPIONAGE_CLASSES_H
#define CIV5_ESPIONAGE_CLASSES_H
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// CLASS: CvEspionageSpy
//! \brief All the information about a spy
//
//! Key Attributes:
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
enum CvSpyRank
{
SPY_RANK_RECRUIT,
SPY_RANK_AGENT,
SPY_RANK_SPECIAL_AGENT,
NUM_SPY_RANKS
};
enum CvEspionageType
{
NO_ESPIONAGE_TYPE,
ESPIONAGE_TYPE_KILL,
ESPIONAGE_TYPE_IDENTIFY,
ESPIONAGE_TYPE_DETECT,
NUM_ESPIONAGE_TYPES
};
enum CvSpyState
{
SPY_STATE_UNASSIGNED,
SPY_STATE_TRAVELLING,
SPY_STATE_SURVEILLANCE,
SPY_STATE_GATHERING_INTEL,
SPY_STATE_RIG_ELECTION,
SPY_STATE_COUNTER_INTEL,
SPY_STATE_MAKING_INTRODUCTIONS,
SPY_STATE_SCHMOOZE,
SPY_STATE_DEAD,
#if defined(MOD_API_ESPIONAGE)
SPY_STATE_TERMINATED,
SPY_STATE_BUILDING_NETWORK,
#endif
NUM_SPY_STATES
};
enum CvSpyResult // what was the result of the last spy action
{
SPY_RESULT_UNDETECTED, // spy was not detected
SPY_RESULT_DETECTED, // a spy was detected in the city, but the defensive player can't tell which player
SPY_RESULT_IDENTIFIED, // a spy was detected and identified in the city
SPY_RESULT_KILLED, // a spy was detected, identified, and killed in the city
#if defined(MOD_API_ESPIONAGE)
SPY_RESULT_ELIMINATED, // a spy was detected, identified, and killed in the city, in such an embarrassing way that another spy won't be recruited!
#endif
NUM_SPY_RESULTS
};
enum CvIntrigueType // What intrigue was uncovered?
{
INTRIGUE_TYPE_DECEPTION, // A civ is lying to another civ
INTRIGUE_TYPE_BUILDING_ARMY, // A civ is amassing an army
INTRIGUE_TYPE_BUILDING_AMPHIBIOUS_ARMY, // A civ is amassing an army to attack over the water
INTRIGUE_TYPE_ARMY_SNEAK_ATTACK, // A civ is sending an army toward another civ
INTRIGUE_TYPE_AMPHIBIOUS_SNEAK_ATTACK, // a civ is sending a land invasion across the water toward another civ
INTRIGUE_TYPE_CONSTRUCTING_WONDER, // A civ is constructing a wonder
NUM_INTRIGUE_TYPES
};
class CvEspionageSpy
{
public:
CvEspionageSpy();
const char* GetSpyName(CvPlayer* pPlayer);
#if defined(MOD_API_ESPIONAGE)
void SetSpyState(PlayerTypes eSpyOwner, int iSpyIndex, CvSpyState eSpyState);
#endif
void SetSpyFocus(CityEventChoiceTypes m_eSpyFocus);
// Public data
int m_iName;
CvString m_sName;
int m_iCityX;
int m_iCityY;
CvSpyRank m_eRank;
int GetSpyRank(PlayerTypes eSpyOwner) const;
CvSpyState m_eSpyState;
int m_iReviveCounter; // after killed, counter to reincarnate a spy
bool m_bIsDiplomat;
bool m_bEvaluateReassignment; // used by the AI. Flag to indicate if the spy should be evaluated to be reassigned
#if defined(MOD_API_ESPIONAGE)
bool m_bPassive;
#endif
CityEventChoiceTypes m_eSpyFocus; // focus type for events- events are classified.
int m_iPotentialAtStart;
};
FDataStream& operator>>(FDataStream&, CvEspionageSpy&);
FDataStream& operator<<(FDataStream&, const CvEspionageSpy&);
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// CLASS: CvPlayerEspionage
//! \brief All the information about espionage relating to this player
//
//! Key Attributes:
//! - Core data in this class is a list of CvEspionageSpies
//! - This object is created inside the CvPlayer object and accessed through CvPlayer
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#if defined(MOD_BALANCE_CORE)
struct ScoreCityEntry
{
CvCity* m_pCity;
int m_iScore;
bool m_bDiplomat;
};
struct ScoreCityEntryHighEval
{
bool operator()(ScoreCityEntry const& a, ScoreCityEntry const& b) const
{
return a.m_iScore > b.m_iScore;
}
};
struct ScoreCityEntryLowEval
{
bool operator()(ScoreCityEntry const& a, ScoreCityEntry const& b) const
{
return a.m_iScore < b.m_iScore;
}
};
struct SpyNotificationMessage
{
int m_iCityX;
int m_iCityY;
PlayerTypes m_eAttackingPlayer;
int m_iSpyResult;
TechTypes m_eStolenTech;
};
struct IntrigueNotificationMessage
{
PlayerTypes m_eDiscoveringPlayer;
PlayerTypes m_eSourcePlayer;
PlayerTypes m_eTargetPlayer;
BuildingTypes m_eBuilding;
ProjectTypes m_eProject;
int m_iIntrigueType;
int m_iTurnNum;
int m_iCityX;
int m_iCityY;
CvString m_strSpyName;
int iSpyID;
bool m_bShared;
};
typedef vector<CvEspionageSpy> SpyList;
typedef vector<TechTypes> TechList;
typedef vector<TechList> PlayerTechList;
typedef vector<int> NumTechsToStealList;
typedef vector<int> NumGWToStealList;
typedef vector<int> NumSpyActionsDone;
typedef vector<int> MaxTechCost;
class CvPlayerEspionage
{
public:
CvPlayerEspionage(void);
~CvPlayerEspionage(void);
void Init(CvPlayer* pPlayer);
void Uninit(void);
void Reset(void);
// Functions invoked each player turn
void DoTurn(void);
void CreateSpy(void);
void ProcessSpy(uint uiSpyIndex);
#if defined(MOD_BALANCE_CORE_SPIES)
void ProcessSpyFocus();
void TriggerSpyFocusSetup(CvCity* pCity, int uiSpyIndex);
bool DoSpyFocusEvent(uint uiSpyIndex);
CvSpyResult ProcessSpyFocusResult(PlayerTypes ePlayer, CvCity* pCity, int uiSpyIndex, CityEventChoiceTypes eEventChoice, bool bDefer = false);
void CreateSpyChoiceEvent(CityEventTypes eEvent, CvCity* pCity, int uiSpyIndex);
void DoSpyFocusLevelUp(uint uiSpyIndex, int iChance);
CvString GetEventHelpText(CityEventTypes eEvent, int uiSpyIndex);
CvWeightedVector<int>GetRandomActionEventPool(CvCity* pCity);
//Tooltips
CvString GetSpyInfo(uint uiSpyIndex, bool bNoBasic, CvCity* pCity = NULL);
CvString GetSpyChanceAtCity(CvCity* pCity, uint uiSpyIndex, bool bNoBasic);
CvString GetCityPotentialInfo(CvCity* pCity, bool bNoBasic);
int GetDefenseChance(CvEspionageType eEspionage, CvCity* pCity, CityEventChoiceTypes eEventChoice = NO_EVENT_CHOICE_CITY, bool bPreview = false);
CvSpyResult GetSpyRollResult(CvCity* pCity, CityEventChoiceTypes eEventChoice = NO_EVENT_CHOICE_CITY);
#endif
void UncoverIntrigue(uint uiSpyIndex);
#if defined(MOD_BALANCE_CORE)
void GetRandomIntrigue(CvCity* pCity, uint uiSpyIndex);
#endif
void GetNextSpyName(CvEspionageSpy* pSpy);
bool IsSpyInCity(uint uiSpyIndex);
CvCity* GetCityWithSpy(uint uiSpyIndex);
CvEspionageSpy* GetSpyByID(uint uiSpyIndex);
int GetSpyIndexInCity(CvCity* pCity);
bool CanEverMoveSpyTo(CvCity* pCity);
bool CanMoveSpyTo(CvCity* pCity, uint uiSpyIndex, bool bAsDiplomat);
bool MoveSpyTo(CvCity* pCity, uint uiSpyIndex, bool bAsDiplomat);
bool ExtractSpyFromCity(uint uiSpyIndex);
void LevelUpSpy(uint uiSpyIndex);
#if defined(MOD_API_ESPIONAGE)
void SetPassive(uint uiSpyIndex, bool bPassive);
void SetOutcome(uint uiSpyIndex, uint uiSpyResult, bool bAffectsDiplomacy = true);
#endif
void UpdateSpies();
void UpdateCity(CvCity* pCity);
int CalcPerTurn(int iSpyState, CvCity* pCity, int iSpyIndex, bool bGlobalCheck = false, bool bFirstTime = false);
int CalcRequired(int iSpyState, CvCity* pCity, int iSpyIndex, bool bGlobalCheck = false);
int GetSpyPower(CvCity* pCity, int iSpyIndex);
int GetSpyResistance(CvCity* pCity, bool bConsiderPotentialSpy = false);
const char* GetSpyRankName(int iRank) const;
bool HasEstablishedSurveillance(uint uiSpyIndex);
bool HasEstablishedSurveillanceInCity(CvCity* pCity);
bool IsAnySurveillanceEstablished(PlayerTypes eTargetPlayer);
bool IsDiplomat (uint uiSpyIndex);
bool IsSchmoozing (uint uiSpyIndex);
bool IsAnySchmoozing (CvCity* pCity);
bool CanStageCoup(uint uiSpyIndex);
bool CanStageCoup(CvCity* pCity);
int GetCoupChanceOfSuccess(uint uiSpyIndex);
int GetTheoreticalChanceOfCoup(CvCity* pCity);
bool AttemptCoup(uint uiSpyIndex);
int GetTurnsUntilStateComplete(uint uiSpyIndex);
int GetPercentOfStateComplete(uint uiSpyIndex);
int GetNumSpies(void);
int GetNumAliveSpies(void);
int GetNumAssignedSpies(void);
int GetNumUnassignedSpies(void);
void BuildStealableTechList(PlayerTypes ePlayer);
bool IsTechStealable(PlayerTypes ePlayer, TechTypes eTech);
int GetNumTechsToSteal(PlayerTypes ePlayer);
int GetNumSpyActionsDone(PlayerTypes ePlayer);
bool IsMyDiplomatVisitingThem(PlayerTypes ePlayer, bool bIncludeTravelling = false);
bool IsOtherDiplomatVisitingMe(PlayerTypes ePlayer);
void AddSpyMessage(int iCityX, int iCityY, PlayerTypes ePlayer, int iSpyResult, TechTypes eStolenTech, int iGreatWorkIndex = -1);
void ProcessSpyMessages(void);
void AddIntrigueMessage(PlayerTypes eDiscoveringPlayer, PlayerTypes eSourcePlayer, PlayerTypes eTargetPlayer, BuildingTypes eBuilding, ProjectTypes eProject, CvIntrigueType eIntrigueType, uint uiSpyIndex, CvCity* pCity, bool bShowNotification);
Localization::String GetIntrigueMessage(uint uiIndex);
bool HasRecentIntrigueAbout(PlayerTypes eTargetPlayer);
IntrigueNotificationMessage* GetRecentIntrigueInfo(PlayerTypes eTargetPlayer);
bool HasSharedIntrigue(PlayerTypes eTargetPlayer, PlayerTypes eSourcePlayer, CvIntrigueType eIntrigueType);
bool HasSharedIntrigue(PlayerTypes eTargetPlayer, PlayerTypes eSourcePlayer);
int MarkRecentIntrigueAsShared(PlayerTypes eTargetPlayer, PlayerTypes eSourcePlayer, CvIntrigueType eIntrigueType);
bool HasSharedIntrigueAboutMe(PlayerTypes eFromPlayer);
CvString GetLogFileName(void) const;
void LogEspionageMsg(CvString& strMsg);
SpyList m_aSpyList;
std::vector<int> m_aiSpyListNameOrder;
int m_iSpyListNameOrderIndex;
PlayerTechList m_aaPlayerStealableTechList;
NumTechsToStealList m_aiNumTechsToStealList;
std::vector<SpyNotificationMessage> m_aSpyNotificationMessages; // cleared every turn after displayed for the player
std::vector<IntrigueNotificationMessage> m_aIntrigueNotificationMessages; // cleared only between games
NumSpyActionsDone m_aiNumSpyActionsDone;
#endif
private:
CvPlayer* m_pPlayer;
};
FDataStream& operator>>(FDataStream&, CvPlayerEspionage&);
FDataStream& operator<<(FDataStream&, const CvPlayerEspionage&);
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// CLASS: CvCityEspionage
//! \brief All the information about espionage relating to this player
//
//! Key Attributes:
//! - Core data in this class is the progress various civs have made on doing
//! espionage in the city
//! - This object is created inside the CvCity object and accessed through CvCity
//! - This may be deprecated!
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
typedef Firaxis::Array<int, MAX_MAJOR_CIVS> SpyAssignmentList;
typedef Firaxis::Array<int, MAX_MAJOR_CIVS> SpyAmountProgressList;
typedef Firaxis::Array<int, MAX_MAJOR_CIVS> SpyRateProgressList;
typedef Firaxis::Array<int, MAX_MAJOR_CIVS> SpyGoalProgressList;
typedef Firaxis::Array<int, MAX_MAJOR_CIVS> LastProgressList;
typedef Firaxis::Array<int, MAX_MAJOR_CIVS> SpyResultList;
typedef Firaxis::Array<int, MAX_MAJOR_CIVS> LastPotentialList;
typedef Firaxis::Array<int, MAX_MAJOR_CIVS> NumTimesCityRobbedList;
typedef Firaxis::Array<int, MAX_MAJOR_CIVS> CityPendingEventsList;
class CvCityEspionage
{
public:
CvCityEspionage(void);
~CvCityEspionage(void);
void Init(CvCity* pCity);
void Uninit(void);
void Reset(void);
void SetActivity(PlayerTypes ePlayer, int iAmount, int iRate, int iGoal);
void Process(PlayerTypes ePlayer);
bool HasReachedGoal(PlayerTypes ePlayer);
void ResetProgress(PlayerTypes ePlayer);
void SetLastProgress(PlayerTypes ePlayer, int iProgress);
void SetLastPotential(PlayerTypes ePlayer, int iPotential);
void SetLastBasePotential(PlayerTypes ePlayer, int iPotential);
#if defined(MOD_EVENTS_ESPIONAGE)
void SetSpyResult(PlayerTypes eSpyOwner, int iSpyIndex, int iResult);
#else
void SetSpyResulttsp(PlayerTypes ePlayer, int iResult);
#endif
bool HasPendingEvents(PlayerTypes ePlayer) const;
bool HasCounterSpy();
CvCity* m_pCity;
SpyAssignmentList m_aiSpyAssignment;
SpyAmountProgressList m_aiAmount; // how much has been collected so far
SpyRateProgressList m_aiRate; // how much per turn
SpyGoalProgressList m_aiGoal; // how many we need
LastProgressList m_aiLastProgress; // the last progress we got from this city. This is recalculated when transitioning between surveillance and stealing a tech and while stealing techs
LastPotentialList m_aiLastPotential; // the last potential we calculated from this city taking into account the spy stealing
LastPotentialList m_aiLastBasePotential; // the last potential we calculated from this city without taking into account the spy
SpyResultList m_aiResult; // what was the spy result this turn
NumTimesCityRobbedList m_aiNumTimesCityRobbed; // how many times has this city had a tech stolen from it?
CityPendingEventsList m_aiPendingEventsForPlayer;
};
FDataStream& operator>>(FDataStream&, CvCityEspionage&);
FDataStream& operator<<(FDataStream&, const CvCityEspionage&);
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// CLASS: CvEspionageAI
//! \brief The player-level AI for espionage
//
//! Key Attributes:
//! - Object is in the player class
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
typedef vector<int> EspionageAIOutOfTechTurnList;
typedef vector<int> EspionageAILastTurns;
typedef vector<int> EspionageAICount;
typedef vector<CvCity*> EspionageCityList;
class CvEspionageAI
{
public:
// check to see if the countdown clock is started
enum {
PLAN_DEFEND_CS_FOR_WIN,
PLAN_ATTACK_CS_TO_PREVENT_DEFEAT,
PLAN_COLLECT_VOTES,
PLAN_PLAY_NORMAL
};
CvEspionageAI(void);
~CvEspionageAI(void);
void Init(CvPlayer* pPlayer);
void Uninit(void);
void Reset(void);
void DoTurn(void);
void StealTechnology(void);
void UpdateCivOutOfTechTurn(void);
void AttemptCoups(void);
std::vector<ScoreCityEntry> BuildDiplomatCityList();
std::vector<ScoreCityEntry> BuildOffenseCityList();
std::vector<ScoreCityEntry> BuildDefenseCityList();
std::vector<ScoreCityEntry> BuildMinorCityList();
int GetCityStatePlan(PlayerTypes* peThreatPlayer = NULL);
void EvaluateSpiesAssignedToTargetPlayer(PlayerTypes ePlayer);
void EvaluateUnassignedSpies(void);
void EvaluateDefensiveSpies(void);
void EvaluateDiplomatSpies(void);
CvPlayer* m_pPlayer;
EspionageAIOutOfTechTurnList m_aiCivOutOfTechTurn; // when a civ has run out of techs to steal relative to us
EspionageAICount m_aiNumSpiesCaught; // how many spies we caught
EspionageAICount m_aiNumSpiesKilled; // how many spies we killed
EspionageAICount m_aiNumSpiesDied; // how many spies we controlled that were killed
EspionageAILastTurns m_aiTurnLastSpyCaught; // last turn we caught a spy
EspionageAILastTurns m_aiTurnLastSpyKilled; // last turn we killed a spy
EspionageAILastTurns m_aiTurnLastSpyDied; // last turn one of our spies was killed
bool m_bUNCountdownStarted; // has the UN countdown started
int m_iTurnEspionageStarted; // what turn espionage started
};
FDataStream& operator>>(FDataStream&, CvEspionageAI&);
FDataStream& operator<<(FDataStream&, const CvEspionageAI&);
#endif //CIV5_ESPIONAGE_CLASSES_H | [
"[email protected]"
] | |
7cdbfe186bf57b55bff6330fe5fb6ce59b381043 | e9f3aed4d520b7a2634ae6bd9467a5504dbbdfa2 | /cc/IPCC_ObserverIF.hpp | 9c49dada00ecb64f0a0c88d32f73779129c864f8 | [] | no_license | tfoerch/LMP | 4b7e50f72796e96f8c40691c3cfab1c5c64f2ca9 | b82e2665778e6d984f166ba2242add0f78cf4857 | refs/heads/master | 2021-01-01T03:48:57.646358 | 2018-12-18T22:01:17 | 2018-12-18T22:01:17 | 58,702,868 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,643 | hpp | #ifndef LIBS_IPCC_OBSERVERIF_HPP_
#define LIBS_IPCC_OBSERVERIF_HPP_
/*
* IPCC_ObserverIF.hpp
*
* Created on: 11.03.2015
* Author: tom
*/
#include "base/ProtocolTypes.hpp" // for DWORD
namespace lmp
{
namespace cc
{
class IpccApplicationIF;
namespace appl
{
class State;
class Event;
class Action;
class IpccObserverIF
{
public:
inline void notifyTransition(
const IpccApplicationIF& ipcc,
const appl::State& sourceState,
const appl::Event& event,
const appl::State& targetState,
const appl::Action& action)
{ do_notifyTransition(ipcc, sourceState, event, targetState, action); }
inline void notifyPeerIpccDiscovered(
const IpccApplicationIF& ipcc,
lmp::DWORD remoteNodeId,
lmp::DWORD remoteCCId)
{ do_notifyPeerIpccDiscovered(ipcc, remoteNodeId, remoteCCId); }
virtual ~IpccObserverIF(){}
private:
virtual void do_notifyTransition(
const IpccApplicationIF& ipcc,
const appl::State& sourceState,
const appl::Event& event,
const appl::State& targetState,
const appl::Action& action) = 0;
virtual void do_notifyPeerIpccDiscovered(
const IpccApplicationIF& ipcc,
lmp::DWORD remoteNodeId,
lmp::DWORD remoteCCId) = 0;
};
} // namespace appl
} // namespace cc
} // namespace lmp
#endif /* LIBS_IPCC_OBSERVERIF_HPP_ */
| [
"[email protected]"
] | |
3a69778f9eb81e024158161e4bd3f0418e129f8f | d26a96ee43f9ab6e05df09e561fae65d9d303b2a | /Homework/HW 6/MovieTree.cpp | 0ed78b074c475f58ed9175e157db1248f74986b7 | [] | no_license | johnkeller101/CSCI-2270 | 0964f31cccae6e13a79122c2478b3526c4a9590f | 61c6b5bdc767c62a263374fdf1e3b3c107bbfe10 | refs/heads/master | 2021-08-11T12:32:50.487556 | 2017-11-13T17:54:55 | 2017-11-13T17:54:55 | 107,299,186 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,010 | cpp | #include "MovieTree.hpp"
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
using namespace std;
MovieTree::MovieTree() {
// constructor
root = NULL;
}
MovieTree::~MovieTree() {
// deconstructor
deleteAll(root);
}
void MovieTree::printMovieInventory() {
printMovieHelper(root);
}
void MovieTree::printMovieHelper(MovieNode *tree){
// We are using a helper function so we can properly do recursion
if(tree != NULL){
if(tree->leftChild != NULL){
// node has left child
printMovieHelper(tree->leftChild);
}
cout << "Movie: " << tree->title << " " << tree->quantity << endl;
if(tree->rightChild != NULL){
// node has right child
printMovieHelper(tree->rightChild);
}
}
}
void MovieTree::addMovieNode(int ranking, std::string title, int releaseYear, int quantity){
MovieNode *newNode = new MovieNode(ranking, title, releaseYear, quantity);
if(root == NULL){
// No movies exist in the tree
root = newNode;
// That's it!
} else {
// Movies do exist in the tree
MovieNode *tempNode = root;
while(tempNode != NULL){
// Let's iterate through the tree until we find the correct spot to add the movie
if(title.compare(tempNode->title) < 0){
// LEFT CHILD TEST
if(tempNode->leftChild != NULL){
// Node has left child, so we need to set that as the new temp
tempNode = tempNode->leftChild;
} else {
// node does not have left child
tempNode->leftChild = newNode;
newNode->parent = tempNode;
tempNode = NULL;
}
} else {
// RIGHT CHILD TEST
if(tempNode->rightChild != NULL){
// node has right child
tempNode = tempNode->rightChild;
} else {
// node does not have right child
tempNode->rightChild = newNode;
newNode->parent = tempNode;
tempNode = NULL;
}
}
}
}
}
void MovieTree::findMovie(std::string title){
// This method goes through the whole tree in order to find the matching node with title matching the search title
MovieNode *returnNode = root;
while(returnNode != NULL){
if(title.compare(returnNode->title) < 0){
// move onto left child
returnNode = returnNode->leftChild;
} else if (title.compare(returnNode->title) > 0){
// move onto right child
returnNode = returnNode->rightChild;
} else {
// it's a match!
cout << "Movie Info:" << endl;
cout << "===========" << endl;
cout << "Ranking:" << returnNode->ranking << endl;
cout << "Title:" << returnNode->title << endl;
cout << "Year:" << returnNode->year << endl;
cout << "Quantity:" << returnNode->quantity << endl;
return;
}
}
// no movie found after going through the tree
cout << "Movie not found." << endl;
return;
}
MovieNode* MovieTree::search(MovieNode* node, string title){
if(node != NULL){
if(title < node->title && node->leftChild != NULL){
return search(node->leftChild, title);
} else if (title > node->title && node->rightChild != NULL){
return search(node->rightChild, title);
} else if (title == node->title){
return node;
} else {
}
}
return NULL;
}
void MovieTree::rentMovie(std::string title){
// this item simply removes one from the quantity of a specified movie
MovieNode *returnNode = search(root,title);
if(returnNode == NULL){
// no movie was found
cout << "Movie not found." << endl;
} else {
returnNode->quantity = returnNode->quantity - 1;
cout << "Movie has been rented." << endl;
cout << "Movie Info:" << endl;
cout << "===========" << endl;
cout << "Ranking:" << returnNode->ranking << endl;
cout << "Title:" << returnNode->title << endl;
cout << "Year:" << returnNode->year << endl;
cout << "Quantity:" << returnNode->quantity << endl;
if(returnNode->quantity <= 0){
deleteMovie(returnNode->title);
}
}
}
// HELPER FUNCTION TO DELETE MOVIES RECURSIVLY
MovieNode* MovieTree::max(MovieNode* tree){
if(tree == NULL){
return NULL;
}
while(tree->rightChild != NULL){
tree = tree->rightChild;
}
return tree;
}
MovieNode* MovieTree::min(MovieNode* tree){
if(tree->leftChild != NULL){
return min(tree->leftChild);
} else {
return tree;
}
}
void MovieTree::deleteAll(MovieNode* tree){
if(tree != NULL){
deleteAll(tree->leftChild);
deleteAll(tree->rightChild);
delete tree;
tree = NULL;
}
}
void MovieTree::deleteMovie(std::string title){
MovieNode* target = search(root, title);
// test if the tree is empty
if(target == NULL){
cout << "Movie not found." << endl;
return;
}
// Now, for the actual tests
if(target->leftChild != NULL){
// CASE 1: Target has one child
string maxLeftTitle = max(target->leftChild)->title;
int maxLeftRanking = max(target->leftChild)->ranking;
int maxLeftYear = max(target->leftChild)->year;
int maxLeftQuantity = max(target->leftChild)->quantity;
MovieNode* maxNodeLeft = max(target->leftChild);
if(maxNodeLeft->leftChild != NULL){
// maxNodeLeft has a LEFT child
maxNodeLeft->leftChild->parent = maxNodeLeft->parent;
if(maxNodeLeft->parent->title > maxNodeLeft->title){
// maxNodeLeft is a left child to its parent
maxNodeLeft->parent->leftChild = maxNodeLeft->leftChild;
} else {
// maxNodeLeft is a right child to its parent
maxNodeLeft->parent->rightChild = maxNodeLeft->leftChild;
}
} else {
// maxNodeLeft has NO child
if(maxNodeLeft->parent->title > maxNodeLeft->title){
maxNodeLeft->parent->leftChild = NULL;
} else {
maxNodeLeft->parent->rightChild = NULL;
}
}
delete maxNodeLeft;
target->title = maxLeftTitle;
target->ranking = maxLeftRanking;
target->year = maxLeftYear;
target->quantity = maxLeftQuantity;
} else if(target->rightChild != NULL){
// target has a RIGHT child
string minRightTitle = max(target->rightChild)->title;
int minRightRanking = max(target->rightChild)->ranking;
int minRightYear = max(target->rightChild)->year;
int minRightQuantity = max(target->rightChild)->quantity;
MovieNode* minRightNode = min(target->rightChild);
if(minRightNode->rightChild != NULL){
minRightNode->rightChild->parent = minRightNode->parent;
if(minRightNode->parent->title > minRightNode->title){
minRightNode->parent->leftChild = minRightNode->rightChild;
} else {
minRightNode->parent->rightChild = minRightNode->rightChild;
}
} else {
if(minRightNode->parent->title > minRightNode->title){
minRightNode->parent->leftChild = NULL;
} else {
minRightNode->parent->rightChild = NULL;
}
}
delete minRightNode;
target->title = minRightTitle;
target->ranking = minRightRanking;
target->year = minRightYear;
target->quantity = minRightQuantity;
} else if(target->parent != NULL) {
// Target for deletion has NO children, but has a parent
if(target->parent->title > target->title){
target->parent->leftChild = NULL;
} else {
target->parent->rightChild = NULL;
}
delete target;
} else {
// target for deletion is root
delete root;
root = NULL;
}
}
int count(MovieNode* tree){
if(tree != NULL){
return(count(tree->leftChild) + count(tree->rightChild)) + 1;
} else {
// tree os empty
return 0;
}
}
void MovieTree::countMovies(){
// counts all movies in the tree
cout << "Count = " << count(root) << endl;
}
int main(int argc, char const *argv[]) {
// Main has to load all the stuff from the test file
// read all movie data line by line, creating a MovieNode for each movie.
// Insert each node into the Binary Search Tree ordered alphabetically by movie title
// NOTE: the data should be added to the tree in the order that it is read in
// First, let's import all the data from the text file
MovieTree tree;
ifstream ifile;
// Movie Information is in a file and the name of the file is passed in as a command-line argument. An example file is on the website HW5-Movies.txt.
// argv[1] = "HW5-Movies.txt";
// ifile.open(argv[1]);
// string line;
// while(getline(ifile,line)){
// // for each line in the text file
// // we need to split up the data by commas
// string ranking, title, year, quantity;
// istringstream ss(line);
// string temp;
// int i = 1;
// while(getline(ss,temp,',')){
// if(i==1){
// ranking = temp;
// } else if(i==2){
// title = temp;
// } else if(i==3){
// year = temp;
// } else {
// quantity = temp;
// }
// i++;
// }
// // cout << title << endl;
// tree.addMovieNode(stoi(ranking), title, stoi(year), stoi(quantity));
// }
string addMovies[8] = {"Man on Wire","Hands on a Hardbody","Dogtown and Z-Boys","Dancin' Outlaw","Jiro Dreams of Sushi","Enron: The Smartest Guys in the Room", "Bowling for Columbine", "Taxi to the Dark Side"};
for (int i = 0; i < 8; i++) {
tree.addMovieNode(2, addMovies[i], 1990, i);
}
tree.printMovieInventory();
string deleteMovies[3] = {"Jiro Dreams of Sushi","Man on Wire","Dancin' Outlaw"};
for (int i = 0; i < 3; i++){
cout << "-----------------------------------" << endl;
cout << "deleting " << deleteMovies[i] << endl;
tree.deleteMovie(deleteMovies[i]);
cout << "new inventory: " << endl;
tree.printMovieInventory();
}
// HANDLE INPUTS
// int input = 0;
// while(input != 4){
// cout << "======Main Menu======" << endl;
// cout << "1. Find a movie" << endl;
// cout << "2. Rent a movie" << endl;
// cout << "3. Print the inventory" << endl;
// cout << "4. Quit" << endl;
// string inputString;
// getline(cin, inputString);
// input = stoi(inputString);
// if(input == 1){
// // user wants to find a movie
// string movieToFind;
// cout << "Enter title:" << endl;
// getline(cin, movieToFind);
// tree.findMovie(movieToFind);
// } else if(input == 2){
// // user wants to rent a movie
// string movieToRent;
// cout << "Enter title:" << endl;
// getline(cin, movieToRent);
// tree.rentMovie(movieToRent);
// } else if(input == 3){
// // user wants to print the inventory
// tree.printMovieInventory();
// }
// }
// cout << "Goodbye!" << endl;
}
| [
"[email protected]"
] | |
2f5a3344618ab89b46fa79109bf6522a8f72053a | 2c27dd8c10e5450dd638eb52a11428f8fc389f6f | /0-Distribution.d/0-Distribution.d/Adafruit_QSPI/Adafruit_QSPI_S25FL1.cpp | ad53db04fa684c104c00326379375e8a8a0e8347 | [
"MIT"
] | permissive | wa1tnr/yaffa_samD51-exp | 30a7908b396ca9364bf0b1b19e0c446b7779b00f | 555f0e0bbba5c453366960d16573d368065f62f3 | refs/heads/master | 2020-07-14T07:24:03.474141 | 2019-08-30T04:36:10 | 2019-08-30T04:36:10 | 205,272,617 | 0 | 0 | MIT | 2019-08-30T04:44:40 | 2019-08-30T00:18:48 | C | UTF-8 | C++ | false | false | 2,385 | cpp | /*
* Adafruit_QSPI_S25FL1.cpp
*
* Created on: Jan 2, 2018
* Author: deanm
*/
#include "Adafruit_QSPI_S25FL1.h"
enum {
S25FL1_READ_STATUS_2 = 0,
S25FL1_READ_STATUS_3,
S25FL1_WRITE_ENABLE_STATUS,
};
/**************************************************************************/
/*!
@brief additional commands specific to the S25FL1 flash device
*/
/**************************************************************************/
static const QSPIInstr cmdSetS25FL1[] = {
//read status 2
{ 0x35, false, QSPI_ADDRLEN_24_BITS, QSPI_OPCODE_LEN_NONE, QSPI_IO_FORMAT_SINGLE, (QSPI_OPTION_INSTREN | QSPI_OPTION_DATAEN | QSPI_OPTION_ADDREN), QSPI_READ, 0 },
//read status 3
{ 0x33, false, QSPI_ADDRLEN_24_BITS, QSPI_OPCODE_LEN_NONE, QSPI_IO_FORMAT_SINGLE, (QSPI_OPTION_INSTREN | QSPI_OPTION_DATAEN | QSPI_OPTION_ADDREN), QSPI_READ, 0 },
//write enable status
{ 0x50, false, QSPI_ADDRLEN_NONE, QSPI_OPCODE_LEN_NONE, QSPI_IO_FORMAT_SINGLE, (QSPI_OPTION_INSTREN), QSPI_READ, 0 },
};
/**************************************************************************/
/*!
@brief begin the QSPI peripheral and enable quad mode on the flash device.
@returns true if the peripheral was initialized and the device could be identified, false otherwise.
*/
/**************************************************************************/
bool Adafruit_QSPI_S25FL1::begin()
{
Adafruit_QSPI_Generic::begin();
//enable quad
writeStatus(0x00, 0x06, 0x70);
uint8_t s2;
QSPI0.runInstruction(&cmdSetS25FL1[S25FL1_READ_STATUS_2], 0, NULL, &s2, 1);
return (s2 == 0x06);
}
/**************************************************************************/
/*!
@brief write to the device-specific status registers s1, s2, s3
@param s1 the value to write to the status register s1
@param s2 the value to write to the status register s2
@param s3 the value to write to the status register s3
*/
/**************************************************************************/
void Adafruit_QSPI_S25FL1::writeStatus(byte s1, byte s2, byte s3)
{
uint8_t c[] = {s1, s2, s3};
uint8_t dummy;
QSPI0.runInstruction(&cmdSetGeneric[ADAFRUIT_QSPI_GENERIC_CMD_WRITE_ENABLE], 0, NULL, &dummy, 1);
QSPI0.runInstruction(&cmdSetS25FL1[S25FL1_WRITE_ENABLE_STATUS], 0, NULL, &dummy, 1);
QSPI0.runInstruction(&cmdSetGeneric[ADAFRUIT_QSPI_GENERIC_CMD_WRITE_STATUS], 0, c, NULL, 3);
}
| [
"[email protected]"
] | |
009162c91c9b23151d2d531b440cc58f9ce0acea | c646555e3f2ffdf72d56ca9e3b454975520553fc | /x11wrapper.h | 45a161ad713f5d25ff0b88c09eb810c641385c55 | [] | no_license | markthumes/x11wrapper | a5eb184a64a60a0ef347dfa73ff4cbd39f7c54ff | 5b08043ac3a5c0d0e45a0a4bb47abc12b603029b | refs/heads/master | 2023-08-16T00:54:45.767494 | 2021-10-12T21:36:51 | 2021-10-12T21:36:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,029 | h | #include <X11/Xlib.h>
#include <X11/extensions/Xdbe.h>
#include <inttypes.h>
#include <limits.h>
#include <unistd.h>
class X11{
public:
class Point : public XPoint {
public:
Point(){};
Point(short _x, short _y);
Point(const Point &p);
Point random( short xMax = SHRT_MAX, short yMax = SHRT_MAX );
};
class Line{
public:
Line(){};
Line( Point _a, Point _b );
Line( const Line& l );
Point a, b;
};
class Color{
public:
Color(){};
Color(float r, float g, float b);
Color(const Color &c );
XColor getColor(){ return m_color; }
void setReferenceDisplay( Display* d){ m_display = d; }
private:
static Display* m_display;
XColor m_color;
};
public:
X11( const char* name = "New Window", int w = 100, int h = 100 );
void open();
void close();
int getWidth() { return m_attrib.width; }
int getHeight() { return m_attrib.height; }
Window getWindow() { return m_window; }
Display* getDisplay(){ return m_display; }
bool isOpen() { return m_open; }
Point getCenter() { return Point(m_attrib.width/2, m_attrib.height/2); }
//**************** Drawing and Updating ****************//
void drawLines ( Color c, Line* l, int count = 1, int width = 1 );
void drawLine ( Color c, Line l, int width = 1 );
void drawPoints( Color c, Point* p, int count = 1, int size = 1 );
void drawPoint ( Color c, Point p, int size = 1 );
void refresh( float timeSeconds = 0.0 );
void setWindowName( const char* name );
void setBackground( Color c );
void setDoubleBuffered( bool mode = true );
/* Swap using DBE (Double Buffer Extension) [front, back]
*
*
*/
XID buffer[2]; //XID buffer name,
void swapBuffers();
void getAttributes();
protected:
void drawToBuffer();
void readFromBuffer();
//private:
uint8_t m_bufferCounter;
const char* m_windowName;
bool m_open;
bool m_doubleBuffered;
Display* m_display;
Window m_window;
XdbeBackBuffer m_backBuffer;
XWindowAttributes m_attrib;
};
| [
"markthumes"
] | markthumes |
be2dab32697d0b96aac906222f7f8cb7e662c47a | 3ff1fe3888e34cd3576d91319bf0f08ca955940f | /waf/src/v20180125/model/TargetEntity.cpp | a23d9e202b0ea91db9ccd35e491963d36bcda32d | [
"Apache-2.0"
] | permissive | TencentCloud/tencentcloud-sdk-cpp | 9f5df8220eaaf72f7eaee07b2ede94f89313651f | 42a76b812b81d1b52ec6a217fafc8faa135e06ca | refs/heads/master | 2023-08-30T03:22:45.269556 | 2023-08-30T00:45:39 | 2023-08-30T00:45:39 | 188,991,963 | 55 | 37 | Apache-2.0 | 2023-08-17T03:13:20 | 2019-05-28T08:56:08 | C++ | UTF-8 | C++ | false | false | 3,059 | cpp | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/waf/v20180125/model/TargetEntity.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Waf::V20180125::Model;
using namespace std;
TargetEntity::TargetEntity() :
m_instanceIdHasBeenSet(false),
m_domainHasBeenSet(false)
{
}
CoreInternalOutcome TargetEntity::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("InstanceId") && !value["InstanceId"].IsNull())
{
if (!value["InstanceId"].IsString())
{
return CoreInternalOutcome(Core::Error("response `TargetEntity.InstanceId` IsString=false incorrectly").SetRequestId(requestId));
}
m_instanceId = string(value["InstanceId"].GetString());
m_instanceIdHasBeenSet = true;
}
if (value.HasMember("Domain") && !value["Domain"].IsNull())
{
if (!value["Domain"].IsString())
{
return CoreInternalOutcome(Core::Error("response `TargetEntity.Domain` IsString=false incorrectly").SetRequestId(requestId));
}
m_domain = string(value["Domain"].GetString());
m_domainHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void TargetEntity::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_instanceIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "InstanceId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_instanceId.c_str(), allocator).Move(), allocator);
}
if (m_domainHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Domain";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_domain.c_str(), allocator).Move(), allocator);
}
}
string TargetEntity::GetInstanceId() const
{
return m_instanceId;
}
void TargetEntity::SetInstanceId(const string& _instanceId)
{
m_instanceId = _instanceId;
m_instanceIdHasBeenSet = true;
}
bool TargetEntity::InstanceIdHasBeenSet() const
{
return m_instanceIdHasBeenSet;
}
string TargetEntity::GetDomain() const
{
return m_domain;
}
void TargetEntity::SetDomain(const string& _domain)
{
m_domain = _domain;
m_domainHasBeenSet = true;
}
bool TargetEntity::DomainHasBeenSet() const
{
return m_domainHasBeenSet;
}
| [
"[email protected]"
] | |
cc2d192994ad8ea29b5a3772b73b2840ff8d8fb6 | 7a28c52137f6cac9ea5341ba5854a567ea0f83cd | /Plugins/BrainWeb/Source/BrainWeb/Private/Graph/Editor/Style/Colors_BrainWeb.h | ee56349f408f3c2d421d1395c0d7bb491e185186 | [] | no_license | rupee990/BrainWeb | 4c4cc481a7988550f55b16a207dfa5a30932f78f | 93134ab9a6edb60c022225209efad17aa25c486e | refs/heads/master | 2023-02-06T13:41:29.159616 | 2023-02-01T06:23:45 | 2023-02-01T06:23:45 | 251,450,482 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 628 | h | #pragma once
#include "CoreMinimal.h"
namespace BrainWebColors
{
namespace NodeBody
{
const FLinearColor Default(0.1f, 0.1f, 0.1f);
const FLinearColor Root(0.5f, 0.5f, 0.5f, 0.1f);
const FLinearColor Error(1.0f, 0.0f, 0.0f);
}
namespace NodeBorder
{
const FLinearColor HighlightAbortRange0(0.0f, 0.22f, 0.4f);
}
namespace Pin
{
const FLinearColor Diff(0.9f, 0.2f, 0.15f);
const FLinearColor Hover(1.0f, 0.7f, 0.0f);
const FLinearColor Default(0.02f, 0.02f, 0.02f);
const FLinearColor SingleNode(0.02f, 0.02f, 0.02f);
}
namespace Connection
{
const FLinearColor Default(1.0f, 1.0f, 1.0f);
}
}
| [
"[email protected]"
] | |
12dd90908aa41498a935312dd698f34e93ad3b01 | 54afb09bc98c1814135e412c0b7ffa95716b7001 | /include/dll/transform/binarize_layer_impl.hpp | 12f3595f377e78e7dca6c6df4712cf415573cb9d | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | praveenmunagapati/dll | aaf900166b0fe1935e64fc065da431ed83de50a4 | 05cd2e8b4b1d4ebbe6acd322b2ae3216b91e520a | refs/heads/master | 2021-05-07T08:10:27.732261 | 2017-10-17T16:33:48 | 2017-10-17T16:33:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,087 | hpp | //=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
#include "dll/base_traits.hpp"
#include "dll/transform/transform_layer.hpp"
namespace dll {
/*!
* \brief Simple thresholding binarize layer
*
* Note: This is only supported at the beginning of the network, no
* backpropagation is possible for now.
*/
template <typename Desc>
struct binarize_layer_impl : transform_layer<binarize_layer_impl<Desc>> {
using desc = Desc; ///< The descriptor type
using base_type = transform_layer<binarize_layer_impl<Desc>>; ///< The base type
using this_type = binarize_layer_impl<Desc>; ///< This layer's type
using layer_t = this_type; ///< This layer's type
using dyn_layer_t = typename desc::dyn_layer_t; ///< The dynamic version of this layer
static constexpr size_t Threshold = desc::T;
binarize_layer_impl() = default;
/*!
* \brief Returns a string representation of the layer
*/
static std::string to_short_string(std::string pre = "") {
cpp_unused(pre);
return "Binarize";
}
/*!
* \brief Apply the layer to the batch of input
* \param output The batch of output
* \param input The batch of input to apply the layer to
*/
template <typename Input, typename Output>
static void forward_batch(Output& output, const Input& input) {
output = input;
for (auto& value : output) {
value = value > Threshold ? 1 : 0;
}
}
/*!
* \brief Adapt the errors, called before backpropagation of the errors.
*
* This must be used by layers that have both an activation fnction and a non-linearity.
*
* \param context the training context
*/
template<typename C>
void adapt_errors(C& context) const {
cpp_unused(context);
}
/*!
* \brief Backpropagate the errors to the previous layers
* \param output The ETL expression into which write the output
* \param context The training context
*/
template<typename H, typename C>
void backward_batch(H&& output, C& context) const {
cpp_unused(output);
cpp_unused(context);
}
/*!
* \brief Compute the gradients for this layer, if any
* \param context The trainng context
*/
template<typename C>
void compute_gradients(C& context) const {
cpp_unused(context);
}
};
//Allow odr-use of the constexpr static members
template <typename Desc>
const size_t binarize_layer_impl<Desc>::Threshold;
// Declare the traits for the layer
template<typename Desc>
struct layer_base_traits<binarize_layer_impl<Desc>> {
static constexpr bool is_neural = false; ///< Indicates if the layer is a neural layer
static constexpr bool is_dense = false; ///< Indicates if the layer is dense
static constexpr bool is_conv = false; ///< Indicates if the layer is convolutional
static constexpr bool is_deconv = false; ///< Indicates if the layer is deconvolutional
static constexpr bool is_standard = false; ///< Indicates if the layer is standard
static constexpr bool is_rbm = false; ///< Indicates if the layer is RBM
static constexpr bool is_pooling = false; ///< Indicates if the layer is a pooling layer
static constexpr bool is_unpooling = false; ///< Indicates if the layer is an unpooling laye
static constexpr bool is_transform = true; ///< Indicates if the layer is a transform layer
static constexpr bool is_dynamic = false; ///< Indicates if the layer is dynamic
static constexpr bool pretrain_last = false; ///< Indicates if the layer is dynamic
static constexpr bool sgd_supported = true; ///< Indicates if the layer is supported by SGD
};
/*!
* \brief Specialization of sgd_context for binarize_layer_impl
*/
template <typename DBN, typename Desc, size_t L>
struct sgd_context<DBN, binarize_layer_impl<Desc>, L> {
using layer_t = binarize_layer_impl<Desc>; ///< The current layer type
using previous_layer = typename DBN::template layer_type<L - 1>; ///< The previous layer type
using previous_context = sgd_context<DBN, previous_layer, L - 1>; ///< The previous layer's context
using inputs_t = decltype(std::declval<previous_context>().output); ///< The type of inputs
inputs_t input; ///< A batch of input
inputs_t output; ///< A batch of output
inputs_t errors; ///< A batch of errors
sgd_context(const layer_t& /*layer*/){}
};
/*!
* \brief Specialization of cg_context for binarize_layer_impl
*/
template <typename Desc>
struct cg_context<binarize_layer_impl<Desc>> {
using rbm_t = binarize_layer_impl<Desc>;
using weight = double; ///< The data type for this layer
static constexpr bool is_trained = false;
static constexpr size_t num_visible = 1;
static constexpr size_t num_hidden = 1;
etl::fast_matrix<weight, 1, 1> gr_w_incs;
etl::fast_vector<weight, 1> gr_b_incs;
etl::fast_matrix<weight, 1, 1> gr_w_best;
etl::fast_vector<weight, 1> gr_b_best;
etl::fast_matrix<weight, 1, 1> gr_w_best_incs;
etl::fast_vector<weight, 1> gr_b_best_incs;
etl::fast_matrix<weight, 1, 1> gr_w_df0;
etl::fast_vector<weight, 1> gr_b_df0;
etl::fast_matrix<weight, 1, 1> gr_w_df3;
etl::fast_vector<weight, 1> gr_b_df3;
etl::fast_matrix<weight, 1, 1> gr_w_s;
etl::fast_vector<weight, 1> gr_b_s;
etl::fast_matrix<weight, 1, 1> gr_w_tmp;
etl::fast_vector<weight, 1> gr_b_tmp;
std::vector<etl::dyn_vector<weight>> gr_probs_a;
std::vector<etl::dyn_vector<weight>> gr_probs_s;
};
} //end of dll namespace
| [
"[email protected]"
] | |
efd69b47d5e9396a6a28e95da1ac46505c799069 | 3fad9690c2a2ae223ea36e74d1ef9dd2e27e4305 | /code.cpp | 3315ef3867632c7b9dc0d22e2f702dc870a620ba | [] | no_license | ankurloonia/minor | 63c368f6317405b021ea3c70541b71f8e3eeb2ee | 30f3c9ac0f773099cfda4520a71767c851b962b6 | refs/heads/master | 2021-01-19T14:12:40.438113 | 2015-06-15T01:06:13 | 2015-06-15T01:06:13 | 14,837,761 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,615 | cpp | #include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/nonfree/features2d.hpp"
#include <gtk/gtk.h>
#include <iostream>
#include <stdio.h>
#include <strings.h>
#include <GL/glut.h>
#include <string.h>
#include <math.h>
#define WIDTH 600
#define HEIGHT 600
using namespace std;
using namespace cv;
Mat frame;
void detect( Mat frame );
void result();
int match(Mat);
void drawText(char,float,float);
void drawSector(float,float,int);
void drawPie(float,int);
void checkPie(float,int);
void myDisplay();
void abc();
int k=0;
float eye_x1,eye_y1,eye_x2,eye_y2,mouth_x1,mouth_y1,mouth_x2,mouth_y2,nose_x1,nose_y1,nose_x2,nose_y2;
//Radius of circle
float radius=0.4;
//Different Colors to be used in pie chart
float Colors[7][3]={{1.0,0.0,0.0},{0.0,1.0,0.0},{0.0,0.0,1.0},{1.0,1.0,0.0},{1.0,0.0,1.0},{0.0,1.0,1.0},{1.0,1.0,1.0}};
//length of color array
int numColors=7;
//Data in % example : A=20%,B=35%,C=15%,D=25%,E=5% so that sum = 100%
float data[7];
//length of data array
int n=7;
//text coordinates is equal to number of pie i.e = n
float text[50][2];
RNG rng(12345);
static void open_dialog(GtkWidget* buton, gpointer window)
{
GtkWidget *dialog;
dialog=gtk_file_chooser_dialog_new("Choose a Image",GTK_WINDOW(window),GTK_FILE_CHOOSER_ACTION_OPEN,GTK_STOCK_OK,
GTK_RESPONSE_OK,GTK_STOCK_CANCEL,GTK_RESPONSE_CANCEL,NULL);
gtk_widget_show_all(dialog);
gint resp=gtk_dialog_run(GTK_DIALOG(dialog));
if(resp==GTK_RESPONSE_OK)
{
g_print("%s\n",gtk_file_chooser_get_uri(GTK_FILE_CHOOSER(dialog))+7);
Mat frame=imread(gtk_file_chooser_get_uri(GTK_FILE_CHOOSER(dialog))+7, CV_LOAD_IMAGE_COLOR);
gtk_widget_destroy(dialog);
detect( frame );
}
else
{
g_print("You pressed cancel\n");
gtk_widget_destroy(dialog);
}
}
int main(int argc, char* argv[], char ** argg)
{
//GTK+2.0 INITIALIZATION
gtk_init(&argc,&argv);
memset(text,0.0,5);
glutInit( &argc, argg);
glutInitDisplayMode( GLUT_DOUBLE| GLUT_RGB);
glutInitWindowPosition( 100, 100);
glutInitWindowSize(WIDTH,HEIGHT);
GtkWidget *window,*button,*vbox;
vbox=gtk_vbox_new(0,0);
window=gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_widget_set_size_request(window, 400, 300);
gtk_window_set_resizable (GTK_WINDOW(window), FALSE);
g_signal_connect(window,"delete_event",G_CALLBACK(gtk_main_quit),NULL);
button=gtk_button_new_with_label("Select Image");
g_signal_connect(button,"clicked",G_CALLBACK(open_dialog),window);
gtk_container_add(GTK_CONTAINER(window),vbox);
gtk_box_pack_start(GTK_BOX(vbox),button,0,0,0);
gtk_widget_set_size_request(button,30,30);
gtk_widget_show_all(window);
gtk_main();
return 0;
}
void detect( Mat frame )
{
String face_cascade_name = "/home/ankur/Desktop/opencv-2.4.6.1/data/haarcascades/haarcascade_frontalface_alt.xml";
String eyes_cascade_name = "/home/ankur/Desktop/opencv-2.4.6.1/data/haarcascades/haarcascade_mcs_eyepair_big.xml";
String mouth_cascade_name = "/home/ankur/Desktop/opencv-2.4.6.1/data/haarcascades/haarcascade_mcs_mouth.xml";
String nose_cascade_name = "/home/ankur/Desktop/opencv-2.4.6.1/data/haarcascades/haarcascade_mcs_nose.xml";
CascadeClassifier face_cascade;
CascadeClassifier eyes_cascade;
CascadeClassifier mouth_cascade;
CascadeClassifier nose_cascade;
std::vector<Rect> faces;
std::vector<Rect> eyes;
std::vector<Rect> mouth;
std::vector<Rect> nose;
Mat frame_gray;
int mo;
//-- 1. Load the cascades
face_cascade.load( face_cascade_name );
eyes_cascade.load( eyes_cascade_name );
mouth_cascade.load( mouth_cascade_name );
nose_cascade.load( nose_cascade_name );
cvtColor( frame, frame_gray, CV_BGR2GRAY );
equalizeHist( frame_gray, frame_gray );
//-- Detect faces
face_cascade.detectMultiScale( frame_gray, faces, 1.1, 2, 0|CV_HAAR_SCALE_IMAGE, Size(30, 30) );
for( size_t i = 0; i < faces.size(); i++ )
{
Point pt1( faces[i].x + faces[i].width, faces[i].y + faces[i].height );
Point pt2( faces[i].x, faces[i].y);
//rectangle(frame,pt1,pt2,cvScalar(0,255,0,0),1,8,0);
Mat faceROI = frame_gray( faces[i] );
//-- In each face, detect eyes
eyes_cascade.detectMultiScale( faceROI, eyes, 1.1, 2, 0 |CV_HAAR_SCALE_IMAGE, Size(30, 30) );
for( size_t j = 0; j < eyes.size(); j++ )
{
Point pt3( faces[i].x + eyes[j].x + eyes[j].width, faces[i].y + eyes[j].y + eyes[j].height );
Point pt4(faces[i].x + eyes[j].x, faces[i].y + eyes[j].y );
//rectangle(frame,pt3,pt4,cvScalar(0,0,255,0),1,8,0);
}
eye_x1=faces[0].x + eyes[0].x + eyes[0].width;
eye_y1=faces[0].y + eyes[0].y + eyes[0].height;
eye_x2=faces[0].x + eyes[0].x;
eye_y2=faces[0].y + eyes[0].y;
nose_cascade.detectMultiScale( faceROI, nose, 1.1, 2, 0 |CV_HAAR_SCALE_IMAGE, Size(30, 30) );
for( size_t j = 0; j < nose.size(); j++ )
{
if((faces[i].x +nose[j].x + nose[j].width)<eye_x1 && (faces[i].y + nose[j].y + nose[j].height)>eye_y1)
if((faces[i].x +nose[j].x)>eye_x2)
{
Point pt7(faces[i].x +nose[j].x + nose[j].width,faces[i].y + nose[j].y + nose[j].height );
Point pt8(faces[i].x +nose[j].x,faces[i].y+nose[j].y );
//rectangle(frame,pt7,pt8,cvScalar(255,255,0,0),1,8,0);
mo=j;
}
}
nose_x1=faces[0].x + nose[mo].x + nose[mo].width;
nose_y1=faces[0].y + nose[mo].y + nose[mo].height;
nose_x2=faces[0].x + nose[mo].x;
nose_y2=faces[0].y + nose[mo].y;
mouth_cascade.detectMultiScale( faceROI, mouth, 1.1, 2, 0 |CV_HAAR_SCALE_IMAGE, Size(30, 30) );
for( size_t j = 0; j < mouth.size(); j++ )
{
if((faces[i].x +mouth[j].x + mouth[j].width)<eye_x1 && (faces[i].x +mouth[j].x)>eye_x2)
{
if((faces[i].y + mouth[j].y + mouth[j].height)>(faces[i].y+nose[mo].y +nose[mo].height))
{
Point pt5(faces[i].x +mouth[j].x + mouth[j].width,faces[i].y + mouth[j].y + mouth[j].height );
Point pt6(faces[i].x +mouth[j].x,faces[i].y + mouth[j].y );
//rectangle(frame,pt5,pt6,cvScalar(0,255,0,0),1,8,0);
mo=j;
}
}
}
mouth_x1=faces[0].x + mouth[mo].x + mouth[mo].width;
mouth_y1=faces[0].y + mouth[mo].y + mouth[mo].height;
mouth_x2=faces[0].x + mouth[mo].x;
mouth_y2=faces[0].y + mouth[mo].y;
}
//-- Show what you got
//cout<<"("<<eye_x1<<","<<eye_y1<<")\n"<<"("<<eye_x2<<","<<eye_y2<<")\n";
//imshow("Voila",frame);
imwrite("/home/ankur/Desktop/data/new.jpg",frame);
abc();
}
void abc()
{
char read[50][80];
FILE *p;
int j=0;
p=fopen("abc.txt","r+");
while(!feof(p))
{
fscanf(p,"%s\n",read[j]);
Mat img_1 = imread(read[j], CV_LOAD_IMAGE_GRAYSCALE );
if(j>=0 && j<=7)
{
match(img_1);
}
else if(j>=9 && j<=15)
{
eye_x1=mouth_x1;
eye_x2=mouth_x2;
eye_y1=mouth_y1;
eye_y2=mouth_y2;
match(img_1);
}
else if(j>=17 && j<=23)
{
eye_x1=nose_x1;
eye_x2=nose_x2;
eye_y1=nose_y1;
eye_y2=nose_y2;
match(img_1);
}
j++;
}
fclose(p);
result();
}
void result()
{
int i=0;
float sum=0;
while(i<n)
sum=sum+data[i++];
while(i>=0){
data[i]=(data[i]/sum)*100;i--;}
cout<<data[0]<<"% Kind-hearted, friendly and approachable individual\n"; //Prominent Eyes
cout<<data[1]<<"% Energetic\n"; //Protruding Eyes
cout<<data[2]<<"% Powerful ability to concentrate\n"; //Closed Set Eyes
cout<<data[3]<<"% Gregarious & Impulsive\n"; //Round Shaped Eyes
cout<<data[4]<<"% Open-minded,with endless intellectual curiosity\n"; //Big Eyes
cout<<data[5]<<"% Perfectionist and attentive person\n"; //Small Eyes
cout<<data[6]<<"% Flair for shifting paradigms & creative imagination\n"; //Roving and unsteady Eyes
glutCreateWindow( "Testing");
glClearColor(0.0,0.0,0.0,1.0);
glutDisplayFunc(myDisplay);
glutMainLoop();
}
int match(Mat img_1)
{
int i=0,j=0;
Mat img_2 = imread( "/home/ankur/Desktop/data/new.jpg", CV_LOAD_IMAGE_GRAYSCALE );
if( !img_1.data || !img_2.data )
{ std::cout<< " --(!) Error reading images " << std::endl; return -1; }
//-- Step 1: Detect the keypoints using SURF Detector
int minHessian = 400;
float good=0,total=0;
SurfFeatureDetector detector( minHessian );
std::vector<KeyPoint> keypoints_1, keypoints_2;
detector.detect( img_1, keypoints_1 );
detector.detect( img_2, keypoints_2 );
//-- Step 2: Calculate descriptors (feature vectors)
SurfDescriptorExtractor extractor;
Mat descriptors_1, descriptors_2;
extractor.compute( img_1, keypoints_1, descriptors_1 );
extractor.compute( img_2, keypoints_2, descriptors_2 );
//-- Step 3: Matching descriptor vectors using FLANN matcher
FlannBasedMatcher matcher;
std::vector< DMatch > matches;
matcher.match( descriptors_1, descriptors_2, matches );
double max_dist = 0; double min_dist = 100;
//-- Quick calculation of max and min distances between keypoints
for( int i = 0; i < descriptors_1.rows; i++ )
{ double dist = matches[i].distance;
if( dist < min_dist ) min_dist = dist;
if( dist > max_dist ) max_dist = dist;
}
// printf("-- Max dist : %f \n", max_dist );
// printf("-- Min dist : %f \n", min_dist );
//-- Draw only "good" matches (i.e. whose distance is less than 2*min_dist )
//-- PS.- radiusMatch can also be used here.
std::vector< DMatch > good_matches;
for( int i = 0; i < descriptors_1.rows; i++ )
{
if( matches[i].distance <= 2*min_dist )
{
good_matches.push_back( matches[i]);
}
}
//-- Draw only "good" matches
Mat img_matches;
drawMatches( img_1, keypoints_1, img_2, keypoints_2,
good_matches, img_matches, Scalar::all(-1), Scalar::all(-1),
vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS );
//-- Show detected matches
float x,y;
//imshow( "Good Matches", img_matches );
for( int i = 0; i < (int)good_matches.size(); i++ )
{
x= keypoints_2[good_matches[i].queryIdx].pt.x;
y= keypoints_2[good_matches[i].queryIdx].pt.y;
total++;
if(y<eye_y1 && y>eye_y2)
if(x<eye_x1 && x>eye_x2)
good++;
// cout<<"("<<x<<","<<y<<")\n";
//printf( "-- Good Match [%d] Keypoint 1: %d -- Keypoint 2: %d \n", i, good_matches[i].queryIdx, good_matches[i].trainIdx );
}
data[k++]=(good/total)*100;
//cout<<(good/total)*100<<"% matching\n";
//cout<<"("<<eye_x1<<","<<eye_y1<<")\n"<<"("<<eye_x2<<","<<eye_y2<<")\n";
return 0;
}
//Draw Text Material
void drawText(char *str,float x,float y)
{
int i;
int len=strlen(str);
glColor3f(1.0,1.0,1.0);
glRasterPos2f(x,y);
for(i=0;i<len;i++)
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_10,str[i]);
}
//Draw data representation matrix
/*void drawData(float *data,int z)
{
int l;
char string[50];
char integer[10];
drawText("Data : Value (in %)",-0.9,0.95);
for(int i=0;i<z;i++)
{
string[0]=65+i;
string[1]=' ';
string[2]=':';
string[3]=' ';
string[4]='\0';
itoa(data[i],integer,10);
l=strlen(integer);
strcat(string,integer);
drawText(string,-0.9,0.9-(i*0.05));
}
}*/
//Draw a sector
void drawSector(float start,float end,int id)
{
float angle,st;
float tx,ty;
glBegin(GL_TRIANGLE_FAN);
glColor3f(Colors[id][0],Colors[id][1],Colors[id][2]);
glVertex2d(0,0);
angle=end-start;
st=start*(3.14/180);
for(int i=0;i<=100;i++)
{
float const t = ((3.14/180.0)*angle)*(float)i/100.0;
glVertex2d(sin(st+t)*radius,cos(st+t)*radius);
if(i==50)
{
tx=(radius+0.1)*sin(st+t);
ty=(radius+0.1)*cos(st+t);
text[id][0]=tx;
text[id][1]=ty;
}
}
glEnd();
}
void drawPie(float *arr,int z)
{
float angle1=90.0;
float angle2;
int id;
char txt[2];
for(int i=0;i<z;i++)
{
txt[0]=i+65;
txt[1]='\0';
if(i>numColors)
id=i%numColors;
else
id=i;
angle2=(arr[i]/100.0)*360.0+angle1;
drawSector(angle1,angle2,id);
angle1=angle2;
drawText(txt,text[i][0],text[i][1]);
}
}
void checkPie(float *data,int n)
{
float total=0.0;
int i=0;
for(i=0;i<n;i++)
{
total=total+data[i];
}
if(total>99.00 && total<101.00)
{
data[i]=data[i]+100.00-total;
}
else
{
printf("\nWarning!!!Incomplete data %f ",total);
exit(1);
}
}
void myDisplay()
{
glClear( GL_COLOR_BUFFER_BIT);
checkPie(data,n);
drawPie(data,n);
//drawData(data,n);
glutSwapBuffers();
glutPostRedisplay();
glFlush();
}
| [
"[email protected]"
] | |
61e93fc95e3b043a9ee2418d09c54047558e5044 | 84173c56d1fd47e81bbfde6eeaa108d8378922ce | /llvm/tools/clang/lib/CodeGen/EHScopeStack.h | e92a7bba4b4d505ca10d4d2d5c44409b467b6503 | [
"MIT",
"NCSA"
] | permissive | gbeauchesne/cm-compiler | 3c8840e4c9959f9bd604e955c2a447b5c9583ee9 | dd211eea3a2f2e27e1014ee05a94535ae78031a9 | refs/heads/master | 2023-08-04T03:54:49.660141 | 2018-05-17T13:45:44 | 2018-05-17T17:28:01 | 126,233,617 | 0 | 0 | null | 2018-03-21T20:00:30 | 2018-03-21T20:00:30 | null | UTF-8 | C++ | false | false | 17,039 | h | //===-- EHScopeStack.h - Stack for cleanup IR generation --------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// These classes should be the minimum interface required for other parts of
// CodeGen to emit cleanups. The implementation is in CGCleanup.cpp and other
// implemenentation details that are not widely needed are in CGCleanup.h.
//
//===----------------------------------------------------------------------===//
#ifndef CLANG_CODEGEN_EHSCOPESTACK_H
#define CLANG_CODEGEN_EHSCOPESTACK_H
#include "clang/Basic/LLVM.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Value.h"
namespace clang {
namespace CodeGen {
class CodeGenFunction;
/// A branch fixup. These are required when emitting a goto to a
/// label which hasn't been emitted yet. The goto is optimistically
/// emitted as a branch to the basic block for the label, and (if it
/// occurs in a scope with non-trivial cleanups) a fixup is added to
/// the innermost cleanup. When a (normal) cleanup is popped, any
/// unresolved fixups in that scope are threaded through the cleanup.
struct BranchFixup {
/// The block containing the terminator which needs to be modified
/// into a switch if this fixup is resolved into the current scope.
/// If null, LatestBranch points directly to the destination.
llvm::BasicBlock *OptimisticBranchBlock;
/// The ultimate destination of the branch.
///
/// This can be set to null to indicate that this fixup was
/// successfully resolved.
llvm::BasicBlock *Destination;
/// The destination index value.
unsigned DestinationIndex;
/// The initial branch of the fixup.
llvm::BranchInst *InitialBranch;
};
template <class T> struct InvariantValue {
typedef T type;
typedef T saved_type;
static bool needsSaving(type value) { return false; }
static saved_type save(CodeGenFunction &CGF, type value) { return value; }
static type restore(CodeGenFunction &CGF, saved_type value) { return value; }
};
/// A metaprogramming class for ensuring that a value will dominate an
/// arbitrary position in a function.
template <class T> struct DominatingValue : InvariantValue<T> {};
template <class T, bool mightBeInstruction =
std::is_base_of<llvm::Value, T>::value &&
!std::is_base_of<llvm::Constant, T>::value &&
!std::is_base_of<llvm::BasicBlock, T>::value>
struct DominatingPointer;
template <class T> struct DominatingPointer<T,false> : InvariantValue<T*> {};
// template <class T> struct DominatingPointer<T,true> at end of file
template <class T> struct DominatingValue<T*> : DominatingPointer<T> {};
enum CleanupKind : unsigned {
EHCleanup = 0x1,
NormalCleanup = 0x2,
NormalAndEHCleanup = EHCleanup | NormalCleanup,
InactiveCleanup = 0x4,
InactiveEHCleanup = EHCleanup | InactiveCleanup,
InactiveNormalCleanup = NormalCleanup | InactiveCleanup,
InactiveNormalAndEHCleanup = NormalAndEHCleanup | InactiveCleanup
};
/// A stack of scopes which respond to exceptions, including cleanups
/// and catch blocks.
class EHScopeStack {
public:
/// A saved depth on the scope stack. This is necessary because
/// pushing scopes onto the stack invalidates iterators.
class stable_iterator {
friend class EHScopeStack;
/// Offset from StartOfData to EndOfBuffer.
ptrdiff_t Size;
stable_iterator(ptrdiff_t Size) : Size(Size) {}
public:
static stable_iterator invalid() { return stable_iterator(-1); }
stable_iterator() : Size(-1) {}
bool isValid() const { return Size >= 0; }
/// Returns true if this scope encloses I.
/// Returns false if I is invalid.
/// This scope must be valid.
bool encloses(stable_iterator I) const { return Size <= I.Size; }
/// Returns true if this scope strictly encloses I: that is,
/// if it encloses I and is not I.
/// Returns false is I is invalid.
/// This scope must be valid.
bool strictlyEncloses(stable_iterator I) const { return Size < I.Size; }
friend bool operator==(stable_iterator A, stable_iterator B) {
return A.Size == B.Size;
}
friend bool operator!=(stable_iterator A, stable_iterator B) {
return A.Size != B.Size;
}
};
/// Information for lazily generating a cleanup. Subclasses must be
/// POD-like: cleanups will not be destructed, and they will be
/// allocated on the cleanup stack and freely copied and moved
/// around.
///
/// Cleanup implementations should generally be declared in an
/// anonymous namespace.
class Cleanup {
// Anchor the construction vtable.
virtual void anchor();
public:
/// Generation flags.
class Flags {
enum {
F_IsForEH = 0x1,
F_IsNormalCleanupKind = 0x2,
F_IsEHCleanupKind = 0x4
};
unsigned flags;
public:
Flags() : flags(0) {}
/// isForEH - true if the current emission is for an EH cleanup.
bool isForEHCleanup() const { return flags & F_IsForEH; }
bool isForNormalCleanup() const { return !isForEHCleanup(); }
void setIsForEHCleanup() { flags |= F_IsForEH; }
bool isNormalCleanupKind() const { return flags & F_IsNormalCleanupKind; }
void setIsNormalCleanupKind() { flags |= F_IsNormalCleanupKind; }
/// isEHCleanupKind - true if the cleanup was pushed as an EH
/// cleanup.
bool isEHCleanupKind() const { return flags & F_IsEHCleanupKind; }
void setIsEHCleanupKind() { flags |= F_IsEHCleanupKind; }
};
// Provide a virtual destructor to suppress a very common warning
// that unfortunately cannot be suppressed without this. Cleanups
// should not rely on this destructor ever being called.
virtual ~Cleanup() {}
/// Emit the cleanup. For normal cleanups, this is run in the
/// same EH context as when the cleanup was pushed, i.e. the
/// immediately-enclosing context of the cleanup scope. For
/// EH cleanups, this is run in a terminate context.
///
// \param flags cleanup kind.
virtual void Emit(CodeGenFunction &CGF, Flags flags) = 0;
};
/// ConditionalCleanupN stores the saved form of its N parameters,
/// then restores them and performs the cleanup.
template <class T, class A0>
class ConditionalCleanup1 : public Cleanup {
typedef typename DominatingValue<A0>::saved_type A0_saved;
A0_saved a0_saved;
void Emit(CodeGenFunction &CGF, Flags flags) override {
A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved);
T(a0).Emit(CGF, flags);
}
public:
ConditionalCleanup1(A0_saved a0)
: a0_saved(a0) {}
};
template <class T, class A0, class A1>
class ConditionalCleanup2 : public Cleanup {
typedef typename DominatingValue<A0>::saved_type A0_saved;
typedef typename DominatingValue<A1>::saved_type A1_saved;
A0_saved a0_saved;
A1_saved a1_saved;
void Emit(CodeGenFunction &CGF, Flags flags) override {
A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved);
A1 a1 = DominatingValue<A1>::restore(CGF, a1_saved);
T(a0, a1).Emit(CGF, flags);
}
public:
ConditionalCleanup2(A0_saved a0, A1_saved a1)
: a0_saved(a0), a1_saved(a1) {}
};
template <class T, class A0, class A1, class A2>
class ConditionalCleanup3 : public Cleanup {
typedef typename DominatingValue<A0>::saved_type A0_saved;
typedef typename DominatingValue<A1>::saved_type A1_saved;
typedef typename DominatingValue<A2>::saved_type A2_saved;
A0_saved a0_saved;
A1_saved a1_saved;
A2_saved a2_saved;
void Emit(CodeGenFunction &CGF, Flags flags) override {
A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved);
A1 a1 = DominatingValue<A1>::restore(CGF, a1_saved);
A2 a2 = DominatingValue<A2>::restore(CGF, a2_saved);
T(a0, a1, a2).Emit(CGF, flags);
}
public:
ConditionalCleanup3(A0_saved a0, A1_saved a1, A2_saved a2)
: a0_saved(a0), a1_saved(a1), a2_saved(a2) {}
};
template <class T, class A0, class A1, class A2, class A3>
class ConditionalCleanup4 : public Cleanup {
typedef typename DominatingValue<A0>::saved_type A0_saved;
typedef typename DominatingValue<A1>::saved_type A1_saved;
typedef typename DominatingValue<A2>::saved_type A2_saved;
typedef typename DominatingValue<A3>::saved_type A3_saved;
A0_saved a0_saved;
A1_saved a1_saved;
A2_saved a2_saved;
A3_saved a3_saved;
void Emit(CodeGenFunction &CGF, Flags flags) override {
A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved);
A1 a1 = DominatingValue<A1>::restore(CGF, a1_saved);
A2 a2 = DominatingValue<A2>::restore(CGF, a2_saved);
A3 a3 = DominatingValue<A3>::restore(CGF, a3_saved);
T(a0, a1, a2, a3).Emit(CGF, flags);
}
public:
ConditionalCleanup4(A0_saved a0, A1_saved a1, A2_saved a2, A3_saved a3)
: a0_saved(a0), a1_saved(a1), a2_saved(a2), a3_saved(a3) {}
};
private:
// The implementation for this class is in CGException.h and
// CGException.cpp; the definition is here because it's used as a
// member of CodeGenFunction.
/// The start of the scope-stack buffer, i.e. the allocated pointer
/// for the buffer. All of these pointers are either simultaneously
/// null or simultaneously valid.
char *StartOfBuffer;
/// The end of the buffer.
char *EndOfBuffer;
/// The first valid entry in the buffer.
char *StartOfData;
/// The innermost normal cleanup on the stack.
stable_iterator InnermostNormalCleanup;
/// The innermost EH scope on the stack.
stable_iterator InnermostEHScope;
/// The current set of branch fixups. A branch fixup is a jump to
/// an as-yet unemitted label, i.e. a label for which we don't yet
/// know the EH stack depth. Whenever we pop a cleanup, we have
/// to thread all the current branch fixups through it.
///
/// Fixups are recorded as the Use of the respective branch or
/// switch statement. The use points to the final destination.
/// When popping out of a cleanup, these uses are threaded through
/// the cleanup and adjusted to point to the new cleanup.
///
/// Note that branches are allowed to jump into protected scopes
/// in certain situations; e.g. the following code is legal:
/// struct A { ~A(); }; // trivial ctor, non-trivial dtor
/// goto foo;
/// A a;
/// foo:
/// bar();
SmallVector<BranchFixup, 8> BranchFixups;
char *allocate(size_t Size);
void *pushCleanup(CleanupKind K, size_t DataSize);
public:
EHScopeStack() : StartOfBuffer(nullptr), EndOfBuffer(nullptr),
StartOfData(nullptr), InnermostNormalCleanup(stable_end()),
InnermostEHScope(stable_end()) {}
~EHScopeStack() { delete[] StartOfBuffer; }
// Variadic templates would make this not terrible.
/// Push a lazily-created cleanup on the stack.
template <class T>
void pushCleanup(CleanupKind Kind) {
void *Buffer = pushCleanup(Kind, sizeof(T));
Cleanup *Obj = new(Buffer) T();
(void) Obj;
}
/// Push a lazily-created cleanup on the stack.
template <class T, class A0>
void pushCleanup(CleanupKind Kind, A0 a0) {
void *Buffer = pushCleanup(Kind, sizeof(T));
Cleanup *Obj = new(Buffer) T(a0);
(void) Obj;
}
/// Push a lazily-created cleanup on the stack.
template <class T, class A0, class A1>
void pushCleanup(CleanupKind Kind, A0 a0, A1 a1) {
void *Buffer = pushCleanup(Kind, sizeof(T));
Cleanup *Obj = new(Buffer) T(a0, a1);
(void) Obj;
}
/// Push a lazily-created cleanup on the stack.
template <class T, class A0, class A1, class A2>
void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2) {
void *Buffer = pushCleanup(Kind, sizeof(T));
Cleanup *Obj = new(Buffer) T(a0, a1, a2);
(void) Obj;
}
/// Push a lazily-created cleanup on the stack.
template <class T, class A0, class A1, class A2, class A3>
void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3) {
void *Buffer = pushCleanup(Kind, sizeof(T));
Cleanup *Obj = new(Buffer) T(a0, a1, a2, a3);
(void) Obj;
}
/// Push a lazily-created cleanup on the stack.
template <class T, class A0, class A1, class A2, class A3, class A4>
void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) {
void *Buffer = pushCleanup(Kind, sizeof(T));
Cleanup *Obj = new(Buffer) T(a0, a1, a2, a3, a4);
(void) Obj;
}
// Feel free to add more variants of the following:
/// Push a cleanup with non-constant storage requirements on the
/// stack. The cleanup type must provide an additional static method:
/// static size_t getExtraSize(size_t);
/// The argument to this method will be the value N, which will also
/// be passed as the first argument to the constructor.
///
/// The data stored in the extra storage must obey the same
/// restrictions as normal cleanup member data.
///
/// The pointer returned from this method is valid until the cleanup
/// stack is modified.
template <class T, class A0, class A1, class A2>
T *pushCleanupWithExtra(CleanupKind Kind, size_t N, A0 a0, A1 a1, A2 a2) {
void *Buffer = pushCleanup(Kind, sizeof(T) + T::getExtraSize(N));
return new (Buffer) T(N, a0, a1, a2);
}
void pushCopyOfCleanup(CleanupKind Kind, const void *Cleanup, size_t Size) {
void *Buffer = pushCleanup(Kind, Size);
std::memcpy(Buffer, Cleanup, Size);
}
/// Pops a cleanup scope off the stack. This is private to CGCleanup.cpp.
void popCleanup();
/// Push a set of catch handlers on the stack. The catch is
/// uninitialized and will need to have the given number of handlers
/// set on it.
class EHCatchScope *pushCatch(unsigned NumHandlers);
/// Pops a catch scope off the stack. This is private to CGException.cpp.
void popCatch();
/// Push an exceptions filter on the stack.
class EHFilterScope *pushFilter(unsigned NumFilters);
/// Pops an exceptions filter off the stack.
void popFilter();
/// Push a terminate handler on the stack.
void pushTerminate();
/// Pops a terminate handler off the stack.
void popTerminate();
/// Determines whether the exception-scopes stack is empty.
bool empty() const { return StartOfData == EndOfBuffer; }
bool requiresLandingPad() const {
return InnermostEHScope != stable_end();
}
/// Determines whether there are any normal cleanups on the stack.
bool hasNormalCleanups() const {
return InnermostNormalCleanup != stable_end();
}
/// Returns the innermost normal cleanup on the stack, or
/// stable_end() if there are no normal cleanups.
stable_iterator getInnermostNormalCleanup() const {
return InnermostNormalCleanup;
}
stable_iterator getInnermostActiveNormalCleanup() const;
stable_iterator getInnermostEHScope() const {
return InnermostEHScope;
}
stable_iterator getInnermostActiveEHScope() const;
/// An unstable reference to a scope-stack depth. Invalidated by
/// pushes but not pops.
class iterator;
/// Returns an iterator pointing to the innermost EH scope.
iterator begin() const;
/// Returns an iterator pointing to the outermost EH scope.
iterator end() const;
/// Create a stable reference to the top of the EH stack. The
/// returned reference is valid until that scope is popped off the
/// stack.
stable_iterator stable_begin() const {
return stable_iterator(EndOfBuffer - StartOfData);
}
/// Create a stable reference to the bottom of the EH stack.
static stable_iterator stable_end() {
return stable_iterator(0);
}
/// Translates an iterator into a stable_iterator.
stable_iterator stabilize(iterator it) const;
/// Turn a stable reference to a scope depth into a unstable pointer
/// to the EH stack.
iterator find(stable_iterator save) const;
/// Removes the cleanup pointed to by the given stable_iterator.
void removeCleanup(stable_iterator save);
/// Add a branch fixup to the current cleanup scope.
BranchFixup &addBranchFixup() {
assert(hasNormalCleanups() && "adding fixup in scope without cleanups");
BranchFixups.push_back(BranchFixup());
return BranchFixups.back();
}
unsigned getNumBranchFixups() const { return BranchFixups.size(); }
BranchFixup &getBranchFixup(unsigned I) {
assert(I < getNumBranchFixups());
return BranchFixups[I];
}
/// Pops lazily-removed fixups from the end of the list. This
/// should only be called by procedures which have just popped a
/// cleanup or resolved one or more fixups.
void popNullFixups();
/// Clears the branch-fixups list. This should only be called by
/// ResolveAllBranchFixups.
void clearFixups() { BranchFixups.clear(); }
};
} // namespace CodeGen
} // namespace clang
#endif
| [
"[email protected]"
] | |
4dd4ad1817d3be772cb5f88c81d99aedf4df88a9 | 869cefe6ea1acb40e347f5430278b1204984b565 | /src/DiscreteOpt/DiscreteModel.cpp | 1a3670387249641cc2d20d0bc22175b66cdac50b | [] | no_license | muschellij2/FSL6.0.0 | c68ed91e8c2777fcf07d994d7ab288a75e448fd1 | 3c3dd651066ee189bc8c290f744ca48cb3d1f156 | refs/heads/master | 2020-04-27T01:04:04.915711 | 2019-03-05T14:57:48 | 2019-03-05T14:57:48 | 173,954,388 | 9 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 19,459 | cpp | /* DiscreteModel.cpp
Emma Robinson, FMRIB Image Analysis Group
Copyright (C) 2012 University of Oxford */
/* Part of FSL - FMRIB's Software Library
http://www.fmrib.ox.ac.uk/fsl
[email protected]
Developed at FMRIB (Oxford Centre for Functional Magnetic Resonance
Imaging of the Brain), Department of Clinical Neurology, Oxford
University, Oxford, UK
LICENCE
FMRIB Software Library, Release 5.0 (c) 2012, The University of
Oxford (the "Software")
The Software remains the property of the University of Oxford ("the
University").
The Software is distributed "AS IS" under this Licence solely for
non-commercial use in the hope that it will be useful, but in order
that the University as a charitable foundation protects its assets for
the benefit of its educational and research purposes, the University
makes clear that no condition is made or to be implied, nor is any
warranty given or to be implied, as to the accuracy of the Software,
or that it will be suitable for any particular purpose or for use
under any specific conditions. Furthermore, the University disclaims
all responsibility for the use which is made of the Software. It
further disclaims any liability for the outcomes arising from using
the Software.
The Licensee agrees to indemnify the University and hold the
University harmless from and against any and all claims, damages and
liabilities asserted by third parties (including claims for
negligence) which arise directly or indirectly from the use of the
Software or the sale of any products based on the Software.
No part of the Software may be reproduced, modified, transmitted or
transferred in any form or by any means, electronic or mechanical,
without the express permission of the University. The permission of
the University is not required if the said reproduction, modification,
transmission or transference is done without financial return, the
conditions of this Licence are imposed upon the receiver of the
product, and all original and amended source code is included in any
transmitted product. You may be held legally responsible for any
copyright infringement that is caused or encouraged by your failure to
abide by these terms and conditions.
You are not permitted under this Licence to use this Software
commercially. Use for which any financial return is received shall be
defined as commercial use, and includes (1) integration of all or part
of the source code or the Software into a product for sale or license
by or on behalf of Licensee to third parties or (2) use of the
Software or any derivative of it for research with the final aim of
developing software products for sale or license to a third party or
(3) use of the Software or any derivative of it for research with the
final aim of developing non-software products for sale or license to a
third party, or (4) use of the Software to provide any service to an
external organisation for which payment is received. If you are
interested in using the Software commercially, please contact Oxford
University Innovation ("OUI"), the technology transfer company of the
University, to negotiate a licence. Contact details are:
[email protected] quoting reference DE/9564. */
#include "DiscreteModel.h"
#include <algorithm>
#include <iostream>
namespace DISCRETEOPT{
void sort_nodeids(int *nodes, int length){
std::vector<int> myvector (nodes, nodes+length);
std::sort(myvector.begin(), myvector.begin()+length);
for(unsigned int i=0;i<myvector.size();i++)
nodes[i] =myvector[i];
}
//===
//====================================================================================================================//
//====================================================================================================================//
void DiscreteModel::resetLabeling()
{
if(labeling) std::fill(labeling,labeling+m_num_nodes,0);
}
//====================================================================================================================//
void DiscreteModel::initLabeling()
{
if(m_num_nodes)
{
if(labeling) delete[] labeling;
labeling = new int[m_num_nodes];
resetLabeling();
}
}
//====================================================================================================================//
void DiscreteModel::printLabeling()
{
std::cout << "Labeling: ";
for(int i = 0; i < m_num_nodes; ++i)
std::cout << labeling[i] << " ";
std::cout << std::endl;
}
//====================================================================================================================//
void SRegDiscreteModel::set_parameters(myparam PAR){
myparam::iterator it;
it=PAR.find("lambda");m_lambda=boost::get<float>(it->second);
it=PAR.find("CPres");m_CPres=boost::get<int>(it->second);
it=PAR.find("SGres");m_SGres=boost::get<int>(it->second);
it=PAR.find("simmeasure");m_simmeasure=boost::get<int>(it->second);
it=PAR.find("regularisermode");m_regoption=boost::get<int>(it->second);
it=PAR.find("multivariate");m_multivariate=boost::get<bool>(it->second);
it=PAR.find("verbosity");m_verbosity=boost::get<bool>(it->second);
it=PAR.find("outdir");m_outdir=boost::get<string>(it->second);
it=PAR.find("TriLikelihood");m_triclique=boost::get<bool>(it->second);
it=PAR.find("numthreads");_numthreads=boost::get<int>(it->second);
it=PAR.find("quartet");_estquartet=boost::get<bool>(it->second);
if(m_regoption==1) _pairwise=true;
}
void SRegDiscreteModel::Initialize(const newmesh &CONTROLGRID){
ColumnVector vMAXmvd;
double MVDmax=0.0;
MVD=0;
double tot=0;
double dist=0;
Pt CP;
m_CPgrid=CONTROLGRID;
/////////////// SET LOW RES DEFORMATION GRID & INITIALISE ASSOCIATED MRF PARAMS /////////////////////////
m_num_nodes=m_CPgrid.nvertices(); m_num_pairs=0;
initLabeling();
//////////////////////// CALCULATE (MEAN) VERTEX SEPARATIONS FOR EACH VERTEX
vMAXmvd.ReSize(m_CPgrid.nvertices()); vMAXmvd=0;
for (int k=0;k<m_CPgrid.nvertices();k++){
CP=m_CPgrid.get_coord(k);
for (vector<int>::const_iterator it=m_CPgrid.nbegin(k);it !=m_CPgrid.nend(k);it++){
dist= 2*RAD*asin((CP-m_CPgrid.get_coord(*it)).norm()/(2*RAD));
MVD+=(CP-m_CPgrid.get_coord(*it)).norm();
tot++;
if(dist > vMAXmvd(k+1))
vMAXmvd(k+1)=dist;
if(vMAXmvd(k+1)>MVDmax) MVDmax=vMAXmvd(k+1);
}
}
MVD/=tot;
m_maxs_dist=0.4*Calculate_MaxVD(m_CPgrid);
////////////////// INITIALIZE COSTFCT ///////////////////
if(costfct.get()){
costfct->set_meshes(m_TARGET,m_SOURCE,m_CPgrid);
costfct->set_spacings(vMAXmvd,MVDmax);
}
else {throw DISCRETEOPTHOCRException("Discrete Model:: You have not initialised the discrete costfunction before initialising the model");}
m_iter=1;
}
void SRegDiscreteModel::initialize_cost_function(const bool &MV, const int & sim, myparam &P){
//////////////////////// CREATE COST FUNCTION //////////////////////
if(MV){
if(m_triclique)
costfct=boost::shared_ptr<SRegDiscreteCostFunction>(new HOMultivariateNonLinearSRegDiscreteCostFunction());
else
costfct=boost::shared_ptr<SRegDiscreteCostFunction>(new MultivariateNonLinearSRegDiscreteCostFunction()); // choose CF based on choice of method of calculation of the data term
}
else if (sim==4) {throw DISCRETEOPTHOCRException("DiscreteModel ERROR:: alpha MI not in this version of MSM yet");} //costfct=boost::shared_ptr<SRegDiscreteCostFunction>(new alphaMINonLinearSRegDiscreteCostFunction());
else{
if(m_triclique)
costfct=boost::shared_ptr<SRegDiscreteCostFunction>(new HOUnivariateNonLinearSRegDiscreteCostFunction());
else
costfct=boost::shared_ptr<SRegDiscreteCostFunction>(new UnivariateNonLinearSRegDiscreteCostFunction());}
costfct->set_parameters(P);
}
void SRegDiscreteModel::Initialize_sampling_grid(){
//////////////////////// LABELS USING HIGHER RES GRID //////////////////////
m_samplinggrid.make_mesh_from_icosa(m_SGres); true_rescale(m_samplinggrid,RAD);
////// find the first centroid with 6 neighbours
for(int i=0;i<m_samplinggrid.nvertices();i++){
if(m_samplinggrid.get_total_neighbours(i)==6){
m_centroid=i;
break;
}
}
label_sampling_grid(m_centroid,m_maxs_dist,m_samplinggrid);
}
void SRegDiscreteModel::label_sampling_grid(const int & centroid, const double & dist, NEWMESH::newmesh &Grid)
{
m_samples.clear(); m_barycentres.clear();
vector<int> getneighbours;
vector<int> newneighbours;
int label;
Pt centre=Grid.get_coord(centroid);
Pt sample;
ColumnVector found(Grid.nvertices()),found_tr(Grid.ntriangles());
found=0;found_tr=0;
getneighbours.push_back(centroid);
m_samples.push_back(centre);
m_barycentres.push_back(centre);
label=1;
//// searches for neighbours of the cnetroid that are within the max sampling distance
while(getneighbours.size()>0){
for(unsigned int i=0;i< getneighbours.size();i++){
for(vector<int>::const_iterator j=Grid.nbegin(getneighbours[i]); j!=Grid.nend(getneighbours[i]);j++){
sample=Grid.get_coord(*j);
if((sample-centre).norm()<=dist && (found(*j+1)==0) && *j!=centroid){
m_samples.push_back(Grid.get_coord(*j)); /// pt-centroid equals deformation vector
newneighbours.push_back(*j);
found(*j+1)=1;
}
}
for(vector<int>::const_iterator j=Grid.tIDbegin(getneighbours[i]); j!=Grid.tIDend(getneighbours[i]);j++){
NEWMESH::Pt v1 = Grid.get_triangle_vertex(*j,0), v2 = Grid.get_triangle_vertex(*j,1), v3 = Grid.get_triangle_vertex(*j,2);
Pt bary((v1.X+v2.X+v3.X)/3,(v1.Y+v2.Y+v3.Y)/3,(v1.Z+v2.Z+v3.Z)/3);
bary.normalize(); bary=bary*RAD;
if((bary-centre).norm()<=dist && (bary-centre).norm()> 0 && found_tr(*j+1)==0){
for(unsigned int k=0;k<m_barycentres.size();k++){
if(abs(1-(((bary-centre)|(m_barycentres[k]-centre))/((bary-centre).norm()*(m_barycentres[k]-centre).norm()))) < 1e-2){ found_tr(*j+1)=1;}
}
if(!found_tr(*j+1)){m_barycentres.push_back(bary); Grid.set_pvalue(Grid.get_triangle_vertexID(*j,0),label);
label++;}
found_tr(*j+1)=1;
}
}
}
getneighbours=newneighbours;
newneighbours.clear();
}
}
void NonLinearSRegDiscreteModel::estimate_pairs(){
int pair=0;
for(int i=0;i<m_CPgrid.nvertices();i++){ /// estimate the total number of edge pairs ////
m_num_pairs+=m_CPgrid.get_total_neighbours(i);
}
m_num_pairs/=2;
pairs = new int [m_num_pairs*2];
for(int i=0;i<m_CPgrid.nvertices();i++){
for(vector<int>::const_iterator j=m_CPgrid.nbegin(i); j!=m_CPgrid.nend(i);j++){
if(*j>i){
int node_ids[2] = { i, *j};
sort_nodeids(node_ids,2);
pairs[2*pair]=node_ids[0];
pairs[2*pair+1]=node_ids[1];
pair++;
}
}
}
}
void NonLinearSRegDiscreteModel::estimate_triplets(){
m_num_triplets=m_CPgrid.ntriangles();
triplets = new int [m_num_triplets*3];
for(int i=0;i<m_CPgrid.ntriangles();i++){
int node_ids[3] = {m_CPgrid.get_triangle_vertexID(i,0),m_CPgrid.get_triangle_vertexID(i,1), m_CPgrid.get_triangle_vertexID(i,2)};
sort_nodeids(node_ids,3);
triplets[3*i]=node_ids[0];
triplets[3*i+1]=node_ids[1];
triplets[3*i+2]=node_ids[2];
}
}
void NonLinearSRegDiscreteModel::Initialize(const newmesh &CONTROLGRID){
SRegDiscreteModel::Initialize(CONTROLGRID);
if(_pairwise){
//////////////////////// GET PAIRS //////////////
estimate_pairs();
}
else{
/////////////////////////// INITIALIZE TRIPLETS /////////////////////
estimate_triplets();
}
/////////////////// CALCULATE FIXED GRID SPACINGS////////
double MVDinput=Calculate_MVD(m_TARGET); /// estimate spacing of data grid from first vertex
/// INITIALIAZE LABEL GRID/////////
Initialize_sampling_grid();
get_rotations(m_ROT); /// enables rotation of sampling grid onto every CP
//////////// INITIALIZE NEIGHBOURHOODS ////////////////
m_inputrel=boost::shared_ptr<RELATIONS >(new RELATIONS (m_SOURCE,m_TARGET,1.5*asin(MVDinput/RAD)));
}
void NonLinearSRegDiscreteModel::get_rotations(vector<Matrix> &ROT){ /// rotates sampling grid to each control point
Matrix R,R2,R_n,R_n2,R_diff;
Pt ci,CP,CP_n;
ROT.clear();
ci=m_samplinggrid.get_coord(m_centroid);
for (int k=0;k<m_CPgrid.nvertices();k++){
CP=m_CPgrid.get_coord(k);
//// rotate sampling points to overlap with control point
R=estimate_rotation_matrix(ci,CP);
ROT.push_back(R);
}
}
void NonLinearSRegDiscreteModel::setupCostFunction()
{
resetLabeling(); // initialise label array to zero
////// use geodesic distances ////////
costfct->reset_CPgrid(m_CPgrid);
if(m_iter==1){
costfct->initialize_regulariser();
m_cp_neighbourhood=boost::shared_ptr<RELATIONS >(new RELATIONS (m_SOURCE,m_CPgrid,3*asin(MVD/RAD)));
m_cp_neighbourhood->update_RELATIONS(m_SOURCE);
costfct->set_relations(m_cp_neighbourhood,m_inputrel);
}
costfct->reset_anatomical(m_outdir,m_iter);
get_rotations(m_ROT); /// instead of recalulating the source->CP neighbours, these are now constant (as source is moving with CPgrid) we we just need to recalculate the rotations of the label grid to the cp vertices
if(m_debug){
char filename[1000];
sprintf(filename,"%sSOURCE-%d.surf",m_outdir.c_str(),m_iter); m_SOURCE.save(filename);
sprintf(filename,"%sSOURCE-%d.func",m_outdir.c_str(),m_iter); m_SOURCE.save(filename);
if(m_iter==1){sprintf(filename,"%sTARGET.surf",m_outdir.c_str()); m_TARGET.save(filename); }
sprintf(filename,"%sCPgrid-%d.surf",m_outdir.c_str(),m_iter); m_CPgrid.save(filename);
}
//////////// set samples (labels vary from iter to iter ) ///////////////
if(m_iter%2==0) m_labels=m_samples;
else m_labels=m_barycentres;
m_num_labels=m_labels.size();
costfct->set_labels(m_labels,m_ROT);
if(m_verbosity)cout << " initialize cost function " << m_iter << endl;
costfct->initialize(m_num_nodes,m_num_labels,m_num_pairs,m_num_triplets);
costfct->get_source_data();
if(_pairwise) costfct->setPairs(pairs);
else costfct->setTriplets(triplets);
m_iter++;
}
void NonLinearSRegDiscreteModel::applyLabeling(int *dlabels){
if(dlabels){
for (int i=0;i<m_CPgrid.nvertices();i++){
//// rotate sampling points to overlap with control point
//// transform grid point to new position given by label
Pt newpt=m_ROT[i]*m_labels[dlabels[i]];
m_CPgrid.set_coord(i,newpt);
}
}
}
void MetricDistortionDiscreteModel::Initialize(const newmesh &CONTROLGRID){
m_CPgrid=CONTROLGRID;
m_num_nodes=m_CPgrid.nvertices();
m_maxs_dist=0.4*Calculate_MaxVD(m_CPgrid);
initLabeling();
/////////////////////////// INITIALIZE TRIPLETS /////////////////////
estimate_triplets();
Initialize_sampling_grid();
get_rotations(m_ROT); /// enables rotation of sampling grid onto every CP
m_iter=1;
}
void MetricDistortionDiscreteModel::setupCostFunction()
{
resetLabeling(); // initialise label array to zero
////// use geodesic distances ////////
costfct->reset_CPgrid(m_CPgrid);
get_rotations(m_ROT); /// instead of recalulating the source->CP neighbours, these are now constant (as source is moving with CPgrid) we we just need to recalculate the rotations of the label grid to the cp vertices
//////////// set samples (labels vary from iter to iter ) ///////////////
if(m_iter%2==0) m_labels=m_samples;
else m_labels=m_barycentres;
m_num_labels=m_labels.size();
costfct->set_labels(m_labels,m_ROT);
if(m_verbosity)cout << " initialize cost function " << m_iter << endl;
costfct->initialize(m_num_nodes,m_num_labels,m_num_pairs,m_num_triplets);
m_iter++;
}
void GroupSegmentationModel::Initialize(){
if (m_num_subjects ==0){throw DISCRETEOPTHOCRException("Group segmentation Model:: DATA has not been set");}
m_num_nodes=m_SOURCE.nvertices()*m_num_subjects;
///////// INIT LABELLING
m_num_labels=2;
initLabeling();
// GET TRIPLETS: for intra subject edges ////////
m_num_triplets=m_num_subjects*m_SOURCE.ntriangles();
triplets = new int [m_num_triplets*3];
int triplet=0;
for(int num=0;num<m_num_subjects;num++){
for(int i=0;i<m_SOURCE.ntriangles();i++){
if(triplet>=m_num_triplets){ cout << i << " too many triplets " << triplet << "num " << num << endl; exit(1);}
triplets[3*triplet]=m_SOURCE.nvertices()*num + m_SOURCE.get_triangle_vertexID(i,0);
triplets[3*triplet+1]=m_SOURCE.nvertices()*num + m_SOURCE.get_triangle_vertexID(i,1);
triplets[3*triplet+2]=m_SOURCE.nvertices()*num + m_SOURCE.get_triangle_vertexID(i,2);
triplet++;
}
}
/////////////////// CALCULATE FIXED GRID SPACINGS////////
double MVDmax= Calculate_MaxVD(m_SOURCE); /// estimate spacing of data grid from first vertex
//////////// INITIALIZE NEIGHBOURHOODS ////////////////
m_neighbourhood=boost::shared_ptr<RELATIONS >(new RELATIONS (m_SOURCE,m_SOURCE,3*asin(MVDmax/RAD)));
m_neighbourhood->update_RELATIONS(m_SOURCE);
//////////////////////// GET PAIRS //////////////
int pair=0;
m_num_pairs=(m_num_subjects-1)*m_count*m_SOURCE.nvertices(); // iterates through ALL intra subjects pairs (for all subjects) and then ALL inter subject pairs
pairs = new int [m_num_pairs*2];
for (int i=1;i<=m_SOURCE.nvertices();i++){
for (int j=1;j<=m_count;j++){
if(m_neighbourhood->Nrows(i)<m_count) {throw DISCRETEOPTHOCRException("Group segmentation Model:: m_neighbourhood is not big enough");}
for(int num=1;num<m_num_subjects;num++){
if(pair>=m_num_pairs){ cout << i << " too many pairs " << pair << " m_count " << m_count << endl; exit(1);}
pairs[2*pair]=(i-1);
pairs[2*pair+1]=m_SOURCE.nvertices()*num+((*m_neighbourhood)(j,i)-1);
pair++;
}
}
}
}
void GroupSegmentationModel::setupCostFunction()
{
resetLabeling(); // initialise label array to zero
costfct->set_relations(m_neighbourhood);
if(m_verbosity)cout << " initialize segmentation cost function " << endl;
costfct->initialize(m_num_nodes,m_num_labels,m_num_pairs,m_num_triplets);
if(m_verbosity) cout << " numpoints " << m_num_nodes << " m_num_labels " << m_num_labels << " m_num_pairs " << m_num_pairs << endl;
}
void GroupSegmentationModel::applyLabeling(int *dlabels){
SEGMENTATION.ReSize(m_num_subjects,m_SOURCE.nvertices());
if(dlabels){
for(int num=0;num< m_num_subjects;num++){
for (int i=0;i<m_SOURCE.nvertices();i++){
SEGMENTATION(num+1,i+1)=dlabels[num*m_SOURCE.nvertices()+i];
}
}
}
}
}
| [
"[email protected]"
] | |
89319be666e9d759219c4938c7534f924a1e43b1 | 2de8f5ba729a846f8ad5630272dd5b1f3b7b6e44 | /src/OLDCore/Cpackets/CGUseBonusPoint.h | 77cd2e08354b72f42dfa895ff390c749f15255dd | [] | no_license | najosky/darkeden-v2-serverfiles | dc0f90381404953e3716bf71320a619eb10c3825 | 6e0015f5b8b658697228128543ea145a1fc4c559 | refs/heads/master | 2021-10-09T13:01:42.843224 | 2018-12-24T15:01:52 | 2018-12-24T15:01:52 | null | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 2,913 | h | //////////////////////////////////////////////////////////////////////
//
// Filename : CGUseBonusPoint.h
// Written By : crazydog
// Description : vampire가 bonus point를 사용한다.
//
//////////////////////////////////////////////////////////////////////
#ifndef __CG_USE_BONUS_POINT_H__
#define __CG_USE_BONUS_POINT_H__
// include files
#include "Types.h"
#include "Exception.h"
#include "Packet.h"
#include "PacketFactory.h"
#define INC_INT 0
#define INC_STR 1
#define INC_DEX 2
//////////////////////////////////////////////////////////////////////
//
// class CGUseBonusPoint;
//
//////////////////////////////////////////////////////////////////////
class CGUseBonusPoint : public Packet {
public:
// constructor
CGUseBonusPoint() throw();
// destructor
~CGUseBonusPoint() throw();
public:
// 입력스트림(버퍼)으로부터 데이타를 읽어서 패킷을 초기화한다.
void read(SocketInputStream & iStream) throw(ProtocolException, Error);
// 출력스트림(버퍼)으로 패킷의 바이너리 이미지를 보낸다.
void write(SocketOutputStream & oStream) const throw(ProtocolException, Error);
// execute packet's handler
void execute(Player* pPlayer) throw(ProtocolException, Error);
// get packet id
PacketID_t getPacketID() const throw() { return PACKET_CG_USE_BONUS_POINT; }
// get packet's body size
PacketSize_t getPacketSize() const throw() { return szBYTE; }
// get packet name
string getPacketName() const throw() { return "CGUseBonusPoint"; }
// get/set which
BYTE getWhich() const throw() { return m_Which;}
void setWhich(BYTE w) throw() { m_Which = w;}
// get packet's debug string
string toString() const throw();
private :
// which
BYTE m_Which;
};
//////////////////////////////////////////////////////////////////////
//
// class CGUseBonusPointFactory;
//
// Factory for CGUseBonusPoint
//
//////////////////////////////////////////////////////////////////////
class CGUseBonusPointFactory : public PacketFactory {
public:
// constructor
CGUseBonusPointFactory() throw() {}
// destructor
virtual ~CGUseBonusPointFactory() throw() {}
public:
// create packet
Packet* createPacket() throw() { return new CGUseBonusPoint(); }
// get packet name
string getPacketName() const throw() { return "CGUseBonusPoint"; }
// get packet id
PacketID_t getPacketID() const throw() { return Packet::PACKET_CG_USE_BONUS_POINT; }
// get Packet Max Size
PacketSize_t getPacketMaxSize() const throw() { return szBYTE; }
};
//////////////////////////////////////////////////////////////////////
//
// class CGUseBonusPointHandler;
//
//////////////////////////////////////////////////////////////////////
class CGUseBonusPointHandler {
public:
// execute packet's handler
static void execute(CGUseBonusPoint* pCGUseBonusPoint, Player* pPlayer) throw(Error);
};
#endif
| [
"[email protected]"
] | |
453bfc8935ab8da9f7bfeb2bdcf6d214ddda0f15 | ed997b3a8723cc9e77787c1d868f9300b0097473 | /boost/test/utils/basic_cstring/bcs_char_traits.hpp | 81227fe14bf1c75cd5493d55dd797174ce7c15a4 | [
"BSL-1.0"
] | permissive | juslee/boost-svn | 7ddb99e2046e5153e7cb5680575588a9aa8c79b2 | 6d5a03c1f5ed3e2b23bd0f3ad98d13ff33d4dcbb | refs/heads/master | 2023-04-13T11:00:16.289416 | 2012-11-16T11:14:39 | 2012-11-16T11:14:39 | 6,734,455 | 0 | 0 | BSL-1.0 | 2023-04-03T23:13:08 | 2012-11-17T11:21:17 | C++ | UTF-8 | C++ | false | false | 4,304 | hpp | // (C) Copyright Gennadiy Rozental 2004-2012.
// 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)
// See http://www.boost.org/libs/test for the library home page.
//
// File : $RCSfile$
//
// Version : $Revision$
//
// Description : generic char traits class; wraps std::char_traits
// ***************************************************************************
#ifndef BOOST_TEST_BCS_CHAR_TRAITS_HPP_071894GER
#define BOOST_TEST_BCS_CHAR_TRAITS_HPP_071894GER
// Boost
#include <boost/config.hpp>
#include <boost/detail/workaround.hpp>
#include <boost/test/detail/config.hpp>
#include <boost/type_traits/add_const.hpp>
// STL
#include <string> // std::char_traits
#include <cstddef> // std::size_t
#include <boost/test/detail/suppress_warnings.hpp>
//____________________________________________________________________________//
namespace boost {
namespace unit_test {
namespace ut_detail {
template<typename CharT> struct bcs_base_char { typedef CharT type; };
template<> struct bcs_base_char<char const> { typedef char type; };
template<> struct bcs_base_char<unsigned char> { typedef char type; };
#if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x551))
template<> struct bcs_base_char<unsigned char const> { typedef char type; };
#endif
template<> struct bcs_base_char<wchar_t const> { typedef wchar_t type; };
// ************************************************************************** //
// ************** bcs_char_traits ************** //
// ************************************************************************** //
template<typename CharT>
struct bcs_char_traits_impl
{
#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
typedef CharT const const_char;
#else
typedef typename boost::add_const<CharT>::type const_char;
#endif
static bool eq( CharT c1, CharT c2 )
{
return c1 == c2;
}
static bool lt( CharT c1, CharT c2 )
{
return c1 < c2;
}
static int compare( const_char* cstr1, const_char* cstr2, std::size_t n )
{
while( n > 0 ) {
if( !eq( *cstr1, *cstr2 ) )
return lt( *cstr1, *cstr2 ) ? -1 : 1;
++cstr1;
++cstr2;
--n;
}
return 0;
}
static std::size_t length( const_char* cstr )
{
const_char null_char = CharT();
const_char* ptr = cstr;
while( !eq( *ptr, null_char ) )
++ptr;
return ptr - cstr;
}
static const_char* find( const_char* s, std::size_t n, CharT c )
{
while( n > 0 ) {
if( eq( *s, c ) )
return s;
++s;
--n;
}
return 0;
}
};
#ifdef BOOST_CLASSIC_IOSTREAMS
template<typename CharT>
struct char_traits_with_find : std::string_char_traits<CharT> {
static CharT const* find( CharT const* s, std::size_t n, CharT c )
{
while( n > 0 ) {
if( eq( *s, c ) )
return s;
++s;
--n;
}
return 0;
}
};
template<> struct bcs_char_traits_impl<char> : char_traits_with_find<char> {};
template<> struct bcs_char_traits_impl<wchar_t> : char_traits_with_find<wchar_t> {};
#else
template<> struct bcs_char_traits_impl<char> : std::char_traits<char> {};
template<> struct bcs_char_traits_impl<wchar_t> : std::char_traits<wchar_t> {};
#endif
template<typename CharT>
class bcs_char_traits : public bcs_char_traits_impl<CharT> {
typedef typename ut_detail::bcs_base_char<CharT>::type the_base_char;
public:
#ifdef BOOST_CLASSIC_IOSTREAMS
typedef std::basic_string<the_base_char, std::string_char_traits<the_base_char> > std_string;
#else
typedef std::basic_string<the_base_char, std::char_traits<the_base_char> > std_string;
#endif
};
} // namespace ut_detail
} // namespace unit_test
} // namespace boost
//____________________________________________________________________________//
#include <boost/test/detail/enable_warnings.hpp>
#endif // BOOST_TEST_BCS_CHAR_TRAITS_HPP_071894GER
| [
"rogeeff@b8fc166d-592f-0410-95f2-cb63ce0dd405"
] | rogeeff@b8fc166d-592f-0410-95f2-cb63ce0dd405 |
50304af7e03aa96bf92d01c669313d6980928583 | 65fb98fc0dd146c6143d37a69a4e77560b031f37 | /Self-Driving_Car_part_1/Project_25_EKF/CarND-Extended-Kalman-Filter-Project-master/src/tools.cpp | f774d7d781aeda28cfa15a2570e8acba81c0c71b | [] | no_license | jack239/udacity_CarND | 7b1e0e68fd5901237a92f9b861c3b5faae4a3eb8 | 2dd9008b9f64d4f12bbe61bff5ecbfb33292104d | refs/heads/main | 2023-07-11T04:54:56.909996 | 2021-08-23T13:47:18 | 2021-08-23T13:47:27 | 391,993,976 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,996 | cpp | #include "tools.h"
#include <iostream>
namespace Tools {
Eigen::VectorXd CalculateRMSE(
const std::vector<Eigen::VectorXd> &estimations,
const std::vector<Eigen::VectorXd> &ground_truth
) {
Eigen::VectorXd rmse(4);
rmse.setZero();
for (int i=0; i < estimations.size(); ++i) {
Eigen::VectorXd delta = estimations[i] - ground_truth[i];
delta = delta.array() * delta.array();
rmse += delta;
}
rmse /= estimations.size();
return rmse.array().sqrt();
}
Eigen::MatrixXd CalculateJacobian(const Eigen::VectorXd& x_state) {
Eigen::MatrixXd Hj(3,4);
Hj.setZero();
// recover state parameters
float px = x_state(0);
float py = x_state(1);
float vx = x_state(2);
float vy = x_state(3);
float p_norm = std::hypot(px, py);
float p_norm2 = p_norm * p_norm;
float p_norm3 = p_norm * p_norm2;
if (p_norm > 1e-5) {
Hj(0, 0) = Hj(2, 2) = px / p_norm;
Hj(0, 1) = Hj(2, 3) = py / p_norm;
Hj(1, 0) = - py / p_norm2;
Hj(1, 1) = px / p_norm2;
float hj3 = (py * vx - px * vy) / p_norm3;
Hj(2, 0) = py * hj3;
Hj(2, 1) = -px * hj3;
}
return Hj;
}
Eigen::Vector2d PolarToCartesian(const Eigen::VectorXd& polar) {
return Eigen::Vector2d{
std::cos(polar[1]),
std::sin(polar[1])
} * polar[0];
}
Eigen::VectorXd CartesianToPolar(const Eigen::VectorXd& cart) {
double norm = Eigen::Vector2d{cart[0], cart[1]}.norm();
Eigen::VectorXd result;
result = Eigen::VectorXd(3);
result.setZero(3);
if (norm > 1e-6) {
double r3 = (cart[0] * cart[2] + cart[1] * cart[3]) / norm;
double angle = std::atan2(cart[1], cart[0]);
result << norm, angle, r3;
}
return result;
}
double normalizeAngle(double angle) {
double result = std::fmod(angle, 2 * M_PI);
if (result > M_PI) {
result -= 2 * M_PI;
} else if (result < -M_PI) {
result += 2 * M_PI;
}
return result;
}
}
| [
"[email protected]"
] | |
47c649f583c75275bc0a8e448eff4b3a83e0674a | 775acebaa6559bb12365c930330a62365afb0d98 | /source/public/interfaces/text/IEndnoteReferenceData.h | 4fddf4c2e3ce445739837f08ea62950091d334ff | [] | no_license | Al-ain-Developers/indesing_plugin | 3d22c32d3d547fa3a4b1fc469498de57643e9ee3 | 36a09796b390e28afea25456b5d61597b20de850 | refs/heads/main | 2023-08-14T13:34:47.867890 | 2021-10-05T07:57:35 | 2021-10-05T07:57:35 | 339,970,603 | 1 | 1 | null | 2021-10-05T07:57:36 | 2021-02-18T07:33:40 | C++ | UTF-8 | C++ | false | false | 1,633 | h | //========================================================================================
//
// $File: //depot/devtech/16.0.x/plugin/source/public/interfaces/text/IEndnoteReferenceData.h $
//
// Owner: shagupta
//
// $Author: pmbuilder $
//
// $DateTime: 2020/11/06 13:08:29 $
//
// $Revision: #2 $
//
// $Change: 1088580 $
//
// ADOBE CONFIDENTIAL
//
// Copyright 2017 Adobe
// All Rights Reserved.
//
// NOTICE: Adobe permits you to use, modify, and distribute this file in
// accordance with the terms of the Adobe license agreement accompanying
// it. If you have received this file from a source other than Adobe,
// then your use, modification, or distribution of it requires the prior
// written permission of Adobe.
//
//========================================================================================
#pragma once
#include "IPMUnknown.h"
#include "IEndnoteTextRangeData.h"
#include "TextID.h"
/** This interface is used to access the endnote text details from an endnote reference.
@ingroup text_layout
*/
class IEndnoteReferenceData : public IPMUnknown
{
public:
enum { kDefaultIID = IID_IENDNOTEREFERENCEDATA};
/** INTERNAL USE: Set the UIDRef of the kEndnoteTextRangeBoss associated with the endnote.
*/
virtual void SetEndnoteReferenceData(UIDRef endnoteRef) = 0;
/** Get the reference counted IEndnoteTextRangeData pointer associated with the endnote text.
*/
virtual IEndnoteTextRangeData* QueryEndnoteReference() const = 0;
/** Get the UIDRef of the kEndnoteTextRangeBoss associated with the endnote
*/
virtual UIDRef GetEndnoteRef() const = 0;
};
| [
"[email protected]"
] | |
87680760494868184c1a37b424f38dc29746a1bd | f13d58b82ab70b42ff017432272e4e9fc3d8d99a | /online-judge/HDU/HDU 2501.cpp | a548b3e39ea04b59b0a697edd4c2ab8c0f09a465 | [] | no_license | WEGFan/Algorithm-Contest-Code | 3586d6edba03165a9e243a10566fedcc6bcf1315 | a5b53605c0ec7161d12d48335171763a2ddf12b0 | refs/heads/master | 2020-11-26T10:33:02.807386 | 2019-12-19T12:05:17 | 2019-12-19T12:05:17 | 229,043,842 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 303 | cpp | #include <iostream>
using namespace std;
int main()
{
int a[35] = {1, 3, 5};
for (int i = 3; i < 35; i++)
{
a[i] = 2 * a[i - 2] + a[i - 1];
}
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
cout << a[n - 1] << endl;
}
return 0;
}
| [
"[email protected]"
] | |
606a35a2b6de27fa2439a120bf079b3a7e3627cb | f81124e4a52878ceeb3e4b85afca44431ce68af2 | /re20_1/processor18/25/U | 166125cfbc4de47c4a16bea0e19ec34ac1657789 | [] | no_license | chaseguy15/coe-of2 | 7f47a72987638e60fd7491ee1310ee6a153a5c10 | dc09e8d5f172489eaa32610e08e1ee7fc665068c | refs/heads/master | 2023-03-29T16:59:14.421456 | 2021-04-06T23:26:52 | 2021-04-06T23:26:52 | 355,040,336 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,612 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 7
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volVectorField;
location "25";
object U;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 1 -1 0 0 0 0];
internalField nonuniform List<vector>
36
(
(1.16755 0.393997 -2.63662e-20)
(1.16403 0.350358 -2.28652e-21)
(1.15746 0.309401 -6.38456e-21)
(1.08407 0.49158 -9.16384e-20)
(1.111 0.455516 3.69761e-21)
(0.842297 0.50091 9.35685e-20)
(0.96512 0.533141 2.61461e-20)
(0.586857 0.426679 -3.16724e-20)
(0.786687 0.532707 -1.54754e-20)
(0.243852 0.215494 -9.01081e-20)
(0.534605 0.450583 -5.82855e-20)
(0.215387 0.224547 4.60828e-20)
(0.182657 0.223805 1.0932e-19)
(0.182657 -0.223805 8.23429e-20)
(0.215387 -0.224547 -3.47239e-20)
(0.243852 -0.215494 -1.12907e-19)
(0.534605 -0.450583 3.63518e-20)
(0.586857 -0.426679 5.36048e-20)
(0.786687 -0.532707 -1.61097e-20)
(0.842297 -0.50091 -6.19869e-20)
(0.96512 -0.533141 -2.61461e-20)
(1.08407 -0.49158 9.16384e-20)
(1.111 -0.455516 -3.69761e-21)
(1.16755 -0.393997 2.63662e-20)
(1.16403 -0.350358 2.28651e-21)
(1.15746 -0.309401 6.38457e-21)
(1.17626 0.217067 7.09161e-22)
(1.16641 0.182154 3.06198e-21)
(1.15969 0.15139 -5.46698e-21)
(1.15318 0.127011 1.63419e-21)
(1.14669 0.10582 -4.51433e-21)
(1.14059 0.0874417 7.03474e-21)
(1.17626 -0.217067 -7.09159e-22)
(1.16641 -0.182154 -3.06198e-21)
(1.15969 -0.15139 5.46698e-21)
(1.15318 -0.127011 -1.63419e-21)
)
;
boundaryField
{
inlet
{
type uniformFixedValue;
uniformValue constant (1 0 0);
value nonuniform 0();
}
outlet
{
type pressureInletOutletVelocity;
value nonuniform 0();
}
cylinder
{
type fixedValue;
value uniform (0 0 0);
}
top
{
type symmetryPlane;
}
bottom
{
type symmetryPlane;
}
defaultFaces
{
type empty;
}
procBoundary18to16
{
type processor;
value nonuniform List<vector>
12
(
(1.118 0.359185 2.27029e-20)
(1.11559 0.315349 -8.57837e-20)
(1.118 -0.359185 -2.27029e-20)
(1.11559 -0.315349 8.57837e-20)
(1.1476 0.220811 5.56559e-21)
(1.1447 0.186591 -1.17579e-21)
(1.14248 0.155425 2.191e-21)
(1.13884 0.130409 -4.52616e-21)
(1.13442 0.108678 -1.77083e-20)
(1.1476 -0.220811 -5.56559e-21)
(1.1447 -0.186591 1.17579e-21)
(1.14248 -0.155425 -2.19099e-21)
)
;
}
procBoundary18to17
{
type processor;
value nonuniform List<vector>
30
(
(1.11828 0.407811 -5.59061e-20)
(1.15053 0.272488 7.36757e-21)
(1.02662 0.513139 1.36811e-20)
(1.11828 0.407811 -5.59061e-20)
(1.05364 0.467264 -3.80916e-20)
(1.02662 0.513139 1.36811e-20)
(0.901065 0.552474 -1.85534e-20)
(0.901065 0.552474 -1.85534e-20)
(0.719363 0.54733 -9.02867e-20)
(0.719363 0.54733 -9.02867e-20)
(0.472964 0.457506 -1.37063e-19)
(0.472964 0.457506 -1.37063e-19)
(0.406089 0.44619 -4.67721e-20)
(0.14809 0.212642 7.01334e-19)
(0.14809 -0.212642 -2.06852e-19)
(0.406089 -0.44619 2.2322e-19)
(0.472964 -0.457506 -3.9375e-20)
(0.472964 -0.457506 -3.9375e-20)
(0.719363 -0.54733 -4.22329e-20)
(0.719363 -0.54733 -4.22329e-20)
(0.901065 -0.552474 1.85534e-20)
(0.901065 -0.552474 1.85534e-20)
(1.02662 -0.513139 -1.36811e-20)
(1.02662 -0.513139 -1.36811e-20)
(1.05364 -0.467264 3.80916e-20)
(1.11828 -0.407811 5.59061e-20)
(1.11828 -0.407811 5.59061e-20)
(1.15053 -0.272488 -7.36757e-21)
(1.12979 0.0897667 5.62566e-21)
(1.13884 -0.130409 1.19744e-21)
)
;
}
procBoundary18to19
{
type processor;
value nonuniform List<vector>
28
(
(1.20578 0.335434 1.11909e-20)
(1.19648 0.298382 -7.51042e-21)
(1.1859 0.264368 5.26767e-21)
(1.13011 0.457993 -1.40068e-19)
(1.16098 0.43357 -3.10809e-20)
(1.16098 0.43357 -3.10809e-20)
(0.882289 0.454304 9.227e-20)
(1.01701 0.498743 -4.72244e-20)
(1.01701 0.498743 -4.72244e-20)
(0.62602 0.387999 -9.10926e-21)
(0.62602 0.387999 -9.10926e-21)
(0.265956 0.197903 1.04298e-19)
(0.265956 0.197903 1.04298e-19)
(0.265956 -0.197903 4.08953e-20)
(0.265956 -0.197903 4.08953e-20)
(0.62602 -0.387999 -5.9926e-21)
(0.62602 -0.387999 -5.9926e-21)
(0.882289 -0.454304 -2.35005e-19)
(1.01701 -0.498743 3.53021e-20)
(1.01701 -0.498743 3.53021e-20)
(1.13011 -0.457993 -6.93044e-20)
(1.16098 -0.43357 3.10809e-20)
(1.16098 -0.43357 3.10809e-20)
(1.20578 -0.335434 -1.11909e-20)
(1.19648 -0.298382 7.51043e-21)
(1.1859 -0.264368 -5.26767e-21)
(1.13509 0.0711014 6.6627e-21)
(1.14669 -0.10582 2.9485e-21)
)
;
}
procBoundary18to20
{
type processor;
value nonuniform List<vector>
12
(
(1.2102 0.37249 2.09601e-23)
(1.2102 -0.37249 -2.0961e-23)
(1.20384 0.210544 2.24778e-21)
(1.18768 0.176178 -5.45079e-23)
(1.17678 0.146574 -6.21962e-22)
(1.16733 0.123091 -3.31538e-22)
(1.15886 0.102589 1.43373e-21)
(1.15132 0.084877 -1.67395e-21)
(1.20384 -0.210544 -2.24778e-21)
(1.18768 -0.176178 5.45078e-23)
(1.17678 -0.146574 2.31935e-22)
(1.16733 -0.123091 7.24374e-22)
)
;
}
}
// ************************************************************************* //
| [
"chaseguy15"
] | chaseguy15 |
|
9656c8f2ad4b38add03ef5f9be267c26602d88d6 | 6a9c9988b3f0299381961be7d677dca9b6aa4e20 | /Code/Most Visited Sector in a Circular Track.cpp | 32fb1250fd48981dc261a12b6ab4d7b66b37310a | [] | no_license | siddiqui-zeeshan/Leetcode | d703d551a509339b3d952bb51bae9f73dd31f891 | 94cdfff5fa67f98e915d36aa0bc1db500d589dd3 | refs/heads/master | 2022-12-17T19:34:08.094485 | 2020-09-16T10:43:10 | 2020-09-16T10:43:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 773 | cpp | class Solution {
public:
vector<int> mostVisited(int n, vector<int>& rounds) {
vector<int> ans(n + 1, 0);
int m = rounds.size();
for(int i = 0; i < m; i++)
{
rounds[i]--;
}
for(int i = 0; i < m - 1; i++)
{
for(int j = rounds[i]; j != rounds[i + 1]; j = (j + 1) % n)
{
ans[j]++;
}
}
ans[rounds[m - 1]]++;
int maximum = 0;
for(auto i : ans)
{
//cout<<i<<" ";
maximum = max(maximum, i);
}
vector<int> res ;
for(int i = 0; i < ans.size(); i++)
{
if(ans[i] == maximum)
res.push_back(i + 1);
}
return res;
}
};
| [
"[email protected]"
] | |
161c226127656517eb8ffe39a5cc925c78fac2f6 | 18e0e1e3af22f36cb990c81de5e40517419fef31 | /nvvs/plugin_src/contextcreate/ContextCreate.cpp | 762968ffc2c7658078e511998f1359c160cc2442 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | f2hkop/DCGM | 56f369f21057177cfce0456ca63161297fd139f1 | 904e1600e5924ef60ac5256d492d0b7f6a7244bc | refs/heads/master | 2023-03-01T01:28:34.433334 | 2021-02-03T18:11:43 | 2021-02-03T18:11:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,700 | cpp | /*
* Copyright (c) 2021, NVIDIA CORPORATION. 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 <sstream>
#include "ContextCreate.h"
#include "ContextCreatePlugin.h"
#include "PluginStrings.h"
#include "dcgm_agent.h"
#include "dcgm_structs.h"
ContextCreate::ContextCreate(TestParameters *testParameters, Plugin *plugin, dcgmHandle_t handle)
: m_plugin(plugin)
, m_testParameters(testParameters)
, m_device()
, m_dcgmRecorder(0)
, m_dcgmHandle(handle)
, m_dcgmGroup()
{}
ContextCreate::~ContextCreate()
{}
bool ContextCreate::GpusAreNonExclusive()
{
dcgmConfig_t current[DCGM_GROUP_MAX_ENTITIES];
unsigned int actualSize = 0;
dcgmReturn_t ret = m_dcgmGroup.GetConfig(current, DCGM_GROUP_MAX_ENTITIES, actualSize);
if (ret != DCGM_ST_OK)
{
std::string err = m_dcgmHandle.RetToString(ret);
m_plugin->AddInfo(err);
PRINT_DEBUG("%s", "%s", err.c_str());
return false;
}
for (unsigned int i = 0; i < actualSize; i++)
{
if (current[i].computeMode == DCGM_CONFIG_COMPUTEMODE_PROHIBITED)
{
std::stringstream err;
err << "GPU " << current[i].gpuId << " is in prohibited mode, so we must skip this test.";
m_plugin->AddInfo(err.str());
PRINT_DEBUG("%s", "%s", err.str().c_str());
return false;
}
else if (current[i].computeMode == DCGM_CONFIG_COMPUTEMODE_EXCLUSIVE_PROCESS)
{
std::stringstream err;
err << "GPU " << current[i].gpuId << " is in exclusive mode, so we must skip this test.";
m_plugin->AddInfo(err.str());
PRINT_DEBUG("%s", "%s", err.str().c_str());
return false;
}
}
return true;
}
std::string ContextCreate::Init(const dcgmDiagPluginGpuList_t &gpuList)
{
std::vector<unsigned int> gpuVec;
for (size_t i = 0; i < gpuList.numGpus; i++)
{
ContextCreateDevice *ccd = 0;
try
{
ccd = new ContextCreateDevice(
gpuList.gpus[i].gpuId, gpuList.gpus[i].attributes.identifiers.pciBusId, m_plugin, m_dcgmHandle);
}
catch (DcgmError &d)
{
if (ccd)
{
delete ccd;
}
m_plugin->AddError(d);
return d.GetMessage();
}
catch (std::runtime_error &re)
{
if (ccd)
{
delete ccd;
}
DcgmError d;
DCGM_ERROR_FORMAT_MESSAGE(DCGM_FR_INTERNAL, d, re.what());
return d.GetMessage();
}
m_device.push_back(ccd);
gpuVec.push_back(gpuList.gpus[i].gpuId);
}
dcgmReturn_t ret = m_dcgmGroup.Init(m_dcgmHandle.GetHandle(), "context_create_group", gpuVec);
if (ret != DCGM_ST_OK)
{
return m_dcgmHandle.RetToString(ret);
}
return "";
}
void ContextCreate::Cleanup()
{
for (size_t i = 0; i < m_device.size(); i++)
{
delete m_device[i];
}
m_device.clear();
// Cleanup the group first because it needs a handle to take care of itself
m_dcgmGroup.Cleanup();
m_dcgmHandle.Cleanup();
}
int ContextCreate::CanCreateContext()
{
int created = CTX_CREATED;
CUresult cuSt;
std::stringstream err;
std::string error;
for (size_t i = 0; i < m_device.size(); i++)
{
cuSt = cuCtxCreate(&m_device[i]->cuContext, 0, m_device[i]->cuDevice);
if (cuSt == CUDA_SUCCESS)
{
cuCtxDestroy(m_device[i]->cuContext);
continue;
}
else if (cuSt == CUDA_ERROR_UNKNOWN)
{
err << "GPU " << m_device[i]->gpuId << " is in prohibted mode; skipping test.";
m_plugin->AddInfo(err.str());
PRINT_DEBUG("%s", "%s", err.str().c_str());
created |= CTX_SKIP;
}
else
{
const char *errStr;
cuGetErrorString(cuSt, &errStr);
DcgmError d;
DCGM_ERROR_FORMAT_MESSAGE(DCGM_FR_CUDA_CONTEXT, d, m_device[i]->gpuId, errStr);
m_plugin->AddErrorForGpu(m_device[i]->gpuId, d);
PRINT_DEBUG("%s", "%s", error.c_str());
created |= CTX_FAIL;
}
}
return created;
}
int ContextCreate::Run(const dcgmDiagPluginGpuList_t &gpuList)
{
std::string error = Init(gpuList);
if (error.size() != 0)
{
PRINT_ERROR("%s", "%s", error.c_str());
return CONTEXT_CREATE_FAIL;
}
int rc = CanCreateContext();
if ((rc & CTX_FAIL) != 0)
{
// cuCtxCreate() only gives us a special error for prohibited mode, not exclusive, so check
// the GPU mode here.
if (GpusAreNonExclusive() == false)
{
// Test should be skipped
return CONTEXT_CREATE_SKIP;
}
else
return CONTEXT_CREATE_FAIL;
}
else if (rc)
{
if (m_testParameters->GetString(CTXCREATE_IGNORE_EXCLUSIVE) == "True")
return CONTEXT_CREATE_FAIL;
else
return CONTEXT_CREATE_SKIP;
}
return CONTEXT_CREATE_PASS;
}
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.