hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
00a5389a8939ec667314c40addf56e1b1cb02493 | 28,558 | cpp | C++ | src/coreclr/jit/importer_vectorization.cpp | kejxu/runtime | 906146aba64a9c14bcc77cffa5f540ead31cd4a7 | [
"MIT"
] | null | null | null | src/coreclr/jit/importer_vectorization.cpp | kejxu/runtime | 906146aba64a9c14bcc77cffa5f540ead31cd4a7 | [
"MIT"
] | null | null | null | src/coreclr/jit/importer_vectorization.cpp | kejxu/runtime | 906146aba64a9c14bcc77cffa5f540ead31cd4a7 | [
"MIT"
] | null | null | null | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include "jitpch.h"
#ifdef _MSC_VER
#pragma hdrstop
#endif
//------------------------------------------------------------------------
// importer_vectorization.cpp
//
// This file is responsible for various (partial) vectorizations during import phase,
// e.g. the following APIs are currently supported:
//
// 1) String.Equals(string, string)
// 2) String.Equals(string, string, StringComparison.Ordinal)
// 3) str.Equals(string)
// 4) str.Equals(String, StringComparison.Ordinal)
// 5) str.StartsWith(string, StringComparison.Ordinal)
// 6) MemoryExtensions.SequenceEqual<char>(ROS<char>, ROS<char>)
// 7) MemoryExtensions.Equals(ROS<char>, ROS<char>, StringComparison.Ordinal)
// 8) MemoryExtensions.StartsWith<char>(ROS<char>, ROS<char>)
// 9) MemoryExtensions.StartsWith(ROS<char>, ROS<char>, StringComparison.Ordinal)
//
// When one of the arguments is a constant string of a [0..32] size so we can inline
// a vectorized comparison against it using SWAR or SIMD techniques (e.g. via two V256 vectors)
//
// We might add these in future:
// 1) OrdinalIgnoreCase for everything above
// 2) Span.CopyTo
// 3) Spans/Arrays of bytes (e.g. UTF8) against a constant RVA data
//
//------------------------------------------------------------------------
// impExpandHalfConstEqualsSIMD: Attempts to unroll and vectorize
// Equals against a constant WCHAR data for Length in [8..32] range
// using SIMD instructions. C# equivalent of what this function emits:
//
// bool IsTestString(ReadOnlySpan<char> span)
// {
// // Length and Null checks are not handled here
// ref char s = ref MemoryMarshal.GetReference(span);
// var v1 = Vector128.LoadUnsafe(ref s);
// var v1 = Vector128.LoadUnsafe(ref s, span.Length - Vector128<ushort>.Count);
// var cns1 = Vector128.Create('T', 'e', 's', 't', 'S', 't', 'r', 'i');
// var cns2 = Vector128.Create('s', 't', 'S', 't', 'r', 'i', 'n', 'g');
// return ((v1 ^ cns1) | (v2 ^ cns2)) == Vector<ushort>.Zero;
//
// // for:
// // return span.SequenceEqual("TestString");
// }
//
// Arguments:
// data - Pointer to a data to vectorize
// cns - Constant data (array of 2-byte chars)
// len - Number of chars in the cns
// dataOffset - Offset for data
//
// Return Value:
// A pointer to the newly created SIMD node or nullptr if unrolling is not
// possible or not profitable
//
// Notes:
// This function doesn't check obj for null or its Length, it's just an internal helper
// for impExpandHalfConstEquals
//
GenTree* Compiler::impExpandHalfConstEqualsSIMD(GenTreeLclVar* data, WCHAR* cns, int len, int dataOffset)
{
assert(len >= 8 && len <= 32);
#if defined(FEATURE_HW_INTRINSICS) && defined(TARGET_64BIT)
if (!compOpportunisticallyDependsOn(InstructionSet_Vector128))
{
// We need SSE2 or ADVSIMD at least
return nullptr;
}
CorInfoType baseType = CORINFO_TYPE_ULONG;
int simdSize;
var_types simdType;
NamedIntrinsic niZero;
NamedIntrinsic niEquals;
NamedIntrinsic niCreate;
GenTree* cnsVec1;
GenTree* cnsVec2;
// Optimization: don't use two vectors for Length == 8 or 16
bool useSingleVector = false;
#if defined(TARGET_XARCH)
if (compOpportunisticallyDependsOn(InstructionSet_Vector256) && len >= 16)
{
// Handle [16..32] inputs via two Vector256
assert(len >= 16 && len <= 32);
simdSize = 32;
simdType = TYP_SIMD32;
niZero = NI_Vector256_get_Zero;
niEquals = NI_Vector256_op_Equality;
niCreate = NI_Vector256_Create;
// Special case: use a single vector for Length == 16
useSingleVector = len == 16;
assert(sizeof(ssize_t) == 8); // this code is guarded with TARGET_64BIT
GenTree* long1 = gtNewIconNode(*(ssize_t*)(cns + 0), TYP_LONG);
GenTree* long2 = gtNewIconNode(*(ssize_t*)(cns + 4), TYP_LONG);
GenTree* long3 = gtNewIconNode(*(ssize_t*)(cns + 8), TYP_LONG);
GenTree* long4 = gtNewIconNode(*(ssize_t*)(cns + 12), TYP_LONG);
cnsVec1 = gtNewSimdHWIntrinsicNode(simdType, long1, long2, long3, long4, niCreate, baseType, simdSize);
// cnsVec2 most likely overlaps with cnsVec1:
GenTree* long5 = gtNewIconNode(*(ssize_t*)(cns + len - 16), TYP_LONG);
GenTree* long6 = gtNewIconNode(*(ssize_t*)(cns + len - 12), TYP_LONG);
GenTree* long7 = gtNewIconNode(*(ssize_t*)(cns + len - 8), TYP_LONG);
GenTree* long8 = gtNewIconNode(*(ssize_t*)(cns + len - 4), TYP_LONG);
cnsVec2 = gtNewSimdHWIntrinsicNode(simdType, long5, long6, long7, long8, niCreate, baseType, simdSize);
}
else
#endif
if (len <= 16)
{
// Handle [8..16] inputs via two Vector128
assert(len >= 8 && len <= 16);
simdSize = 16;
simdType = TYP_SIMD16;
niZero = NI_Vector128_get_Zero;
niEquals = NI_Vector128_op_Equality;
niCreate = NI_Vector128_Create;
// Special case: use a single vector for Length == 8
useSingleVector = len == 8;
assert(sizeof(ssize_t) == 8); // this code is guarded with TARGET_64BIT
GenTree* long1 = gtNewIconNode(*(ssize_t*)(cns + 0), TYP_LONG);
GenTree* long2 = gtNewIconNode(*(ssize_t*)(cns + 4), TYP_LONG);
cnsVec1 = gtNewSimdHWIntrinsicNode(simdType, long1, long2, niCreate, baseType, simdSize);
// cnsVec2 most likely overlaps with cnsVec1:
GenTree* long3 = gtNewIconNode(*(ssize_t*)(cns + len - 8), TYP_LONG);
GenTree* long4 = gtNewIconNode(*(ssize_t*)(cns + len - 4), TYP_LONG);
cnsVec2 = gtNewSimdHWIntrinsicNode(simdType, long3, long4, niCreate, baseType, simdSize);
}
else
{
JITDUMP("impExpandHalfConstEqualsSIMD: No V256 support and data is too big for V128\n");
// NOTE: We might consider using four V128 for ARM64
return nullptr;
}
GenTree* zero = gtNewSimdHWIntrinsicNode(simdType, niZero, baseType, simdSize);
GenTree* offset1 = gtNewIconNode(dataOffset, TYP_I_IMPL);
GenTree* offset2 = gtNewIconNode(dataOffset + len * sizeof(USHORT) - simdSize, TYP_I_IMPL);
GenTree* dataPtr1 = gtNewOperNode(GT_ADD, TYP_BYREF, data, offset1);
GenTree* dataPtr2 = gtNewOperNode(GT_ADD, TYP_BYREF, gtClone(data), offset2);
GenTree* vec1 = gtNewIndir(simdType, dataPtr1);
GenTree* vec2 = gtNewIndir(simdType, dataPtr2);
// TODO-Unroll-CQ: Spill vec1 and vec2 for better pipelining, currently we end up emitting:
//
// vmovdqu xmm0, xmmword ptr [rcx+12]
// vpxor xmm0, xmm0, xmmword ptr[reloc @RWD00]
// vmovdqu xmm1, xmmword ptr [rcx+20]
// vpxor xmm1, xmm1, xmmword ptr[reloc @RWD16]
//
// While we should re-order them to be:
//
// vmovdqu xmm0, xmmword ptr [rcx+12]
// vmovdqu xmm1, xmmword ptr [rcx+20]
// vpxor xmm0, xmm0, xmmword ptr[reloc @RWD00]
// vpxor xmm1, xmm1, xmmword ptr[reloc @RWD16]
//
// ((v1 ^ cns1) | (v2 ^ cns2)) == zero
GenTree* xor1 = gtNewSimdBinOpNode(GT_XOR, simdType, vec1, cnsVec1, baseType, simdSize, false);
GenTree* xor2 = gtNewSimdBinOpNode(GT_XOR, simdType, vec2, cnsVec2, baseType, simdSize, false);
GenTree* orr = gtNewSimdBinOpNode(GT_OR, simdType, xor1, xor2, baseType, simdSize, false);
return gtNewSimdHWIntrinsicNode(TYP_BOOL, useSingleVector ? xor1 : orr, zero, niEquals, baseType, simdSize);
#else
return nullptr;
#endif
}
//------------------------------------------------------------------------
// impCreateCompareInd: creates the following tree:
//
// * EQ int
// +--* IND <type>
// | \--* ADD byref
// | +--* <obj>
// | \--* CNS_INT <offset>
// \--* CNS_INT <value>
//
// Arguments:
// comp - Compiler object
// obj - GenTree representing data pointer
// type - type for the IND node
// offset - offset for the data pointer
// value - constant value to compare against
//
// Return Value:
// A tree with indirect load and comparison
//
static GenTree* impCreateCompareInd(Compiler* comp, GenTreeLclVar* obj, var_types type, ssize_t offset, ssize_t value)
{
GenTree* offsetTree = comp->gtNewIconNode(offset, TYP_I_IMPL);
GenTree* addOffsetTree = comp->gtNewOperNode(GT_ADD, TYP_BYREF, obj, offsetTree);
GenTree* indirTree = comp->gtNewIndir(type, addOffsetTree);
GenTree* valueTree = comp->gtNewIconNode(value, genActualType(type));
return comp->gtNewOperNode(GT_EQ, TYP_INT, indirTree, valueTree);
}
//------------------------------------------------------------------------
// impExpandHalfConstEqualsSWAR: Attempts to unroll and vectorize
// Equals against a constant WCHAR data for Length in [1..8] range
// using SWAR (a sort of SIMD but for GPR registers and instructions)
//
// Arguments:
// data - Pointer to a data to vectorize
// cns - Constant data (array of 2-byte chars)
// len - Number of chars in the cns
// dataOffset - Offset for data
//
// Return Value:
// A pointer to the newly created SWAR node or nullptr if unrolling is not
// possible or not profitable
//
// Notes:
// This function doesn't check obj for null or its Length, it's just an internal helper
// for impExpandHalfConstEquals
//
GenTree* Compiler::impExpandHalfConstEqualsSWAR(GenTreeLclVar* data, WCHAR* cns, int len, int dataOffset)
{
assert(len >= 1 && len <= 8);
// Compose Int32 or Int64 values from ushort components
#define MAKEINT32(c1, c2) ((UINT64)c2 << 16) | ((UINT64)c1 << 0)
#define MAKEINT64(c1, c2, c3, c4) ((UINT64)c4 << 48) | ((UINT64)c3 << 32) | ((UINT64)c2 << 16) | ((UINT64)c1 << 0)
if (len == 1)
{
// [ ch1 ]
// [value]
//
return impCreateCompareInd(this, data, TYP_SHORT, dataOffset, cns[0]);
}
if (len == 2)
{
// [ ch1 ][ ch2 ]
// [ value ]
//
const UINT32 value = MAKEINT32(cns[0], cns[1]);
return impCreateCompareInd(this, data, TYP_INT, dataOffset, value);
}
#ifdef TARGET_64BIT
if (len == 3)
{
// handle len = 3 via two Int32 with overlapping:
//
// [ ch1 ][ ch2 ][ ch3 ]
// [ value1 ]
// [ value2 ]
//
// where offset for value2 is 2 bytes (1 char)
//
UINT32 value1 = MAKEINT32(cns[0], cns[1]);
UINT32 value2 = MAKEINT32(cns[1], cns[2]);
GenTree* firstIndir = impCreateCompareInd(this, data, TYP_INT, dataOffset, value1);
GenTree* secondIndir =
impCreateCompareInd(this, gtClone(data)->AsLclVar(), TYP_INT, dataOffset + sizeof(USHORT), value2);
// TODO-Unroll-CQ: Consider merging two indirs via XOR instead of QMARK
// e.g. gtNewOperNode(GT_XOR, TYP_INT, firstIndir, secondIndir);
// but it currently has CQ issues (redundant movs)
GenTreeColon* doubleIndirColon = gtNewColonNode(TYP_INT, secondIndir, gtNewFalse());
return gtNewQmarkNode(TYP_INT, firstIndir, doubleIndirColon);
}
assert(len >= 4 && len <= 8);
UINT64 value1 = MAKEINT64(cns[0], cns[1], cns[2], cns[3]);
if (len == 4)
{
// [ ch1 ][ ch2 ][ ch3 ][ ch4 ]
// [ value ]
//
return impCreateCompareInd(this, data, TYP_LONG, dataOffset, value1);
}
// For 5..7 value2 will overlap with value1, e.g. for Length == 6:
//
// [ ch1 ][ ch2 ][ ch3 ][ ch4 ][ ch5 ][ ch6 ]
// [ value1 ]
// [ value2 ]
//
UINT64 value2 = MAKEINT64(cns[len - 4], cns[len - 3], cns[len - 2], cns[len - 1]);
GenTree* firstIndir = impCreateCompareInd(this, data, TYP_LONG, dataOffset, value1);
ssize_t offset = dataOffset + len * sizeof(WCHAR) - sizeof(UINT64);
GenTree* secondIndir = impCreateCompareInd(this, gtClone(data)->AsLclVar(), TYP_LONG, offset, value2);
// TODO-Unroll-CQ: Consider merging two indirs via XOR instead of QMARK
GenTreeColon* doubleIndirColon = gtNewColonNode(TYP_INT, secondIndir, gtNewFalse());
return gtNewQmarkNode(TYP_INT, firstIndir, doubleIndirColon);
#else // TARGET_64BIT
return nullptr;
#endif
}
//------------------------------------------------------------------------
// impExpandHalfConstEquals: Attempts to unroll and vectorize
// Equals against a constant WCHAR data for Length in [8..32] range
// using either SWAR or SIMD. In a general case it will look like this:
//
// bool equals = obj != null && obj.Length == len && (SWAR or SIMD)
//
// Arguments:
// data - Pointer (LCL_VAR) to a data to vectorize
// lengthFld - Pointer (LCL_VAR or GT_FIELD) to Length field
// checkForNull - Check data for null
// startsWith - Is it StartsWith or Equals?
// cns - Constant data (array of 2-byte chars)
// len - Number of 2-byte chars in the cns
// dataOffset - Offset for data
//
// Return Value:
// A pointer to the newly created SIMD node or nullptr if unrolling is not
// possible or not profitable
//
GenTree* Compiler::impExpandHalfConstEquals(GenTreeLclVar* data,
GenTree* lengthFld,
bool checkForNull,
bool startsWith,
WCHAR* cnsData,
int len,
int dataOffset)
{
assert(len >= 0);
if (compCurBB->isRunRarely())
{
// Not profitable to expand
JITDUMP("impExpandHalfConstEquals: block is cold - not profitable to expand.\n");
return nullptr;
}
if ((compIsForInlining() ? (fgBBcount + impInlineRoot()->fgBBcount) : (fgBBcount)) > 20)
{
// We don't want to unroll too much and in big methods
// TODO-Unroll-CQ: come up with some better heuristic/budget
JITDUMP("impExpandHalfConstEquals: method has too many BBs (>20) - not profitable to expand.\n");
return nullptr;
}
const genTreeOps cmpOp = startsWith ? GT_GE : GT_EQ;
GenTree* elementsCount = gtNewIconNode(len);
GenTree* lenCheckNode;
if (len == 0)
{
// For zero length we don't need to compare content, the following expression is enough:
//
// varData != null && lengthFld == 0
//
lenCheckNode = gtNewOperNode(cmpOp, TYP_INT, lengthFld, elementsCount);
}
else
{
assert(cnsData != nullptr);
GenTree* indirCmp = nullptr;
if (len < 8) // SWAR impl supports len == 8 but we'd better give it to SIMD
{
indirCmp = impExpandHalfConstEqualsSWAR(gtClone(data)->AsLclVar(), cnsData, len, dataOffset);
}
else if (len <= 32)
{
indirCmp = impExpandHalfConstEqualsSIMD(gtClone(data)->AsLclVar(), cnsData, len, dataOffset);
}
if (indirCmp == nullptr)
{
JITDUMP("unable to compose indirCmp\n");
return nullptr;
}
GenTreeColon* lenCheckColon = gtNewColonNode(TYP_INT, indirCmp, gtNewFalse());
// For StartsWith we use GT_GE, e.g.: `x.Length >= 10`
lenCheckNode = gtNewQmarkNode(TYP_INT, gtNewOperNode(cmpOp, TYP_INT, lengthFld, elementsCount), lenCheckColon);
}
GenTree* rootQmark;
if (checkForNull)
{
// varData == nullptr
GenTreeColon* nullCheckColon = gtNewColonNode(TYP_INT, lenCheckNode, gtNewFalse());
rootQmark = gtNewQmarkNode(TYP_INT, gtNewOperNode(GT_NE, TYP_INT, data, gtNewNull()), nullCheckColon);
}
else
{
// no nullcheck, just "obj.Length == len && (SWAR or SIMD)"
rootQmark = lenCheckNode;
}
return rootQmark;
}
//------------------------------------------------------------------------
// impGetStrConFromSpan: Try to obtain string literal out of a span:
// var span = "str".AsSpan();
// var span = (ReadOnlySpan<char>)"str"
//
// Arguments:
// span - String_op_Implicit or MemoryExtensions_AsSpan call
// with a string literal
//
// Returns:
// GenTreeStrCon node or nullptr
//
GenTreeStrCon* Compiler::impGetStrConFromSpan(GenTree* span)
{
GenTreeCall* argCall = nullptr;
if (span->OperIs(GT_RET_EXPR))
{
// NOTE: we don't support chains of RET_EXPR here
GenTree* inlineCandidate = span->AsRetExpr()->gtInlineCandidate;
if (inlineCandidate->OperIs(GT_CALL))
{
argCall = inlineCandidate->AsCall();
}
}
else if (span->OperIs(GT_CALL))
{
argCall = span->AsCall();
}
if ((argCall != nullptr) && ((argCall->gtCallMoreFlags & GTF_CALL_M_SPECIAL_INTRINSIC) != 0))
{
const NamedIntrinsic ni = lookupNamedIntrinsic(argCall->gtCallMethHnd);
if ((ni == NI_System_MemoryExtensions_AsSpan) || (ni == NI_System_String_op_Implicit))
{
assert(argCall->gtCallArgs->GetNext() == nullptr);
if (argCall->gtCallArgs->GetNode()->OperIs(GT_CNS_STR))
{
return argCall->gtCallArgs->GetNode()->AsStrCon();
}
}
}
return nullptr;
}
//------------------------------------------------------------------------
// impStringEqualsOrStartsWith: The main entry-point for String methods
// We're going to unroll & vectorize the following cases:
// 1) String.Equals(obj, "cns")
// 2) String.Equals(obj, "cns", StringComparison.Ordinal)
// 3) String.Equals("cns", obj)
// 4) String.Equals("cns", obj, StringComparison.Ordinal)
// 5) obj.Equals("cns")
// 5) obj.Equals("cns")
// 6) obj.Equals("cns", StringComparison.Ordinal)
// 7) "cns".Equals(obj)
// 8) "cns".Equals(obj, StringComparison.Ordinal)
// 9) obj.StartsWith("cns", StringComparison.Ordinal)
// 10) "cns".StartsWith(obj, StringComparison.Ordinal)
//
// For cases 5, 6 and 9 we don't emit "obj != null"
// NOTE: String.Equals(object) is not supported currently
//
// Arguments:
// startsWith - Is it StartsWith or Equals?
// sig - signature of StartsWith or Equals method
// methodFlags - its flags
//
// Returns:
// GenTree representing vectorized comparison or nullptr
//
GenTree* Compiler::impStringEqualsOrStartsWith(bool startsWith, CORINFO_SIG_INFO* sig, unsigned methodFlags)
{
const bool isStatic = methodFlags & CORINFO_FLG_STATIC;
const int argsCount = sig->numArgs + (isStatic ? 0 : 1);
GenTree* op1;
GenTree* op2;
if (argsCount == 3) // overload with StringComparison
{
if (!impStackTop(0).val->IsIntegralConst(4)) // StringComparison.Ordinal
{
// TODO-Unroll-CQ: Unroll & vectorize OrdinalIgnoreCase
return nullptr;
}
op1 = impStackTop(2).val;
op2 = impStackTop(1).val;
}
else
{
assert(argsCount == 2);
op1 = impStackTop(1).val;
op2 = impStackTop(0).val;
}
if (!(op1->OperIs(GT_CNS_STR) ^ op2->OperIs(GT_CNS_STR)))
{
// either op1 or op2 has to be CNS_STR, but not both - that case is optimized
// just fine as is.
return nullptr;
}
GenTree* varStr;
GenTreeStrCon* cnsStr;
if (op1->OperIs(GT_CNS_STR))
{
cnsStr = op1->AsStrCon();
varStr = op2;
}
else
{
cnsStr = op2->AsStrCon();
varStr = op1;
}
bool needsNullcheck = true;
if ((op1 != cnsStr) && !isStatic)
{
// for the following cases we should not check varStr for null:
//
// obj.Equals("cns")
// obj.Equals("cns", StringComparison.Ordinal)
// obj.StartsWith("cns", StringComparison.Ordinal)
//
// instead, it should throw NRE if it's null
needsNullcheck = false;
}
int cnsLength = -1;
const char16_t* str = nullptr;
if (cnsStr->IsStringEmptyField())
{
// check for fake "" first
cnsLength = 0;
JITDUMP("Trying to unroll String.Equals|StartsWith(op1, \"\")...\n", str)
}
else
{
str = info.compCompHnd->getStringLiteral(cnsStr->gtScpHnd, cnsStr->gtSconCPX, &cnsLength);
if ((cnsLength < 0) || (str == nullptr))
{
// We were unable to get the literal (e.g. dynamic context)
return nullptr;
}
JITDUMP("Trying to unroll String.Equals|StartsWith(op1, \"%ws\")...\n", str)
}
// Create a temp which is safe to gtClone for varStr
// We're not appending it as a statement until we figure out unrolling is profitable (and possible)
unsigned varStrTmp = lvaGrabTemp(true DEBUGARG("spilling varStr"));
lvaTable[varStrTmp].lvType = varStr->TypeGet();
GenTreeLclVar* varStrLcl = gtNewLclvNode(varStrTmp, varStr->TypeGet());
// Create a tree representing string's Length:
// TODO-Unroll-CQ: Consider using ARR_LENGTH here, but we'll have to modify QMARK to propagate BBF_HAS_IDX_LEN
int strLenOffset = OFFSETOF__CORINFO_String__stringLen;
GenTree* lenOffset = gtNewIconNode(strLenOffset, TYP_I_IMPL);
GenTree* lenNode = gtNewIndir(TYP_INT, gtNewOperNode(GT_ADD, TYP_BYREF, varStrLcl, lenOffset));
varStrLcl = gtClone(varStrLcl)->AsLclVar();
GenTree* unrolled = impExpandHalfConstEquals(varStrLcl, lenNode, needsNullcheck, startsWith, (WCHAR*)str, cnsLength,
strLenOffset + sizeof(int));
if (unrolled != nullptr)
{
impAssignTempGen(varStrTmp, varStr);
if (unrolled->OperIs(GT_QMARK))
{
// QMARK nodes cannot reside on the evaluation stack
unsigned rootTmp = lvaGrabTemp(true DEBUGARG("spilling unroll qmark"));
impAssignTempGen(rootTmp, unrolled);
unrolled = gtNewLclvNode(rootTmp, TYP_INT);
}
JITDUMP("\n... Successfully unrolled to:\n")
DISPTREE(unrolled)
for (int i = 0; i < argsCount; i++)
{
impPopStack();
}
}
return unrolled;
}
//------------------------------------------------------------------------
// impSpanEqualsOrStartsWith: The main entry-point for [ReadOnly]Span<char> methods
// We're going to unroll & vectorize the following cases:
// 1) MemoryExtensions.SequenceEqual<char>(var, "cns")
// 2) MemoryExtensions.SequenceEqual<char>("cns", var)
// 3) MemoryExtensions.Equals(var, "cns", StringComparison.Ordinal)
// 4) MemoryExtensions.Equals("cns", var, StringComparison.Ordinal)
// 5) MemoryExtensions.StartsWith<char>("cns", var)
// 6) MemoryExtensions.StartsWith<char>(var, "cns")
// 7) MemoryExtensions.StartsWith("cns", var, StringComparison.Ordinal)
// 8) MemoryExtensions.StartsWith(var, "cns", StringComparison.Ordinal)
//
// Arguments:
// startsWith - Is it StartsWith or Equals?
// sig - signature of StartsWith or Equals method
// methodFlags - its flags
//
// Returns:
// GenTree representing vectorized comparison or nullptr
//
GenTree* Compiler::impSpanEqualsOrStartsWith(bool startsWith, CORINFO_SIG_INFO* sig, unsigned methodFlags)
{
const bool isStatic = methodFlags & CORINFO_FLG_STATIC;
const int argsCount = sig->numArgs + (isStatic ? 0 : 1);
GenTree* op1;
GenTree* op2;
if (argsCount == 3) // overload with StringComparison
{
if (!impStackTop(0).val->IsIntegralConst(4)) // StringComparison.Ordinal
{
// TODO-Unroll-CQ: Unroll & vectorize OrdinalIgnoreCase
return nullptr;
}
op1 = impStackTop(2).val;
op2 = impStackTop(1).val;
}
else
{
assert(argsCount == 2);
op1 = impStackTop(1).val;
op2 = impStackTop(0).val;
}
// For generic StartsWith and Equals we need to make sure T is char
if (sig->sigInst.methInstCount != 0)
{
assert(sig->sigInst.methInstCount == 1);
CORINFO_CLASS_HANDLE targetElemHnd = sig->sigInst.methInst[0];
CorInfoType typ = info.compCompHnd->getTypeForPrimitiveValueClass(targetElemHnd);
if ((typ != CORINFO_TYPE_SHORT) && (typ != CORINFO_TYPE_USHORT) && (typ != CORINFO_TYPE_CHAR))
{
return nullptr;
}
}
// Try to obtain original string literals out of span arguments
GenTreeStrCon* op1Str = impGetStrConFromSpan(op1);
GenTreeStrCon* op2Str = impGetStrConFromSpan(op2);
if (!((op1Str != nullptr) ^ (op2Str != nullptr)))
{
// either op1 or op2 has to be '(ReadOnlySpan)"cns"'
return nullptr;
}
GenTree* spanObj;
GenTreeStrCon* cnsStr;
if (op1Str != nullptr)
{
cnsStr = op1Str;
spanObj = op2;
}
else
{
cnsStr = op2Str;
spanObj = op1;
}
int cnsLength = -1;
const char16_t* str = nullptr;
if (cnsStr->IsStringEmptyField())
{
// check for fake "" first
cnsLength = 0;
JITDUMP("Trying to unroll MemoryExtensions.Equals|SequenceEqual|StartsWith(op1, \"\")...\n", str)
}
else
{
str = info.compCompHnd->getStringLiteral(cnsStr->gtScpHnd, cnsStr->gtSconCPX, &cnsLength);
if (cnsLength < 0 || str == nullptr)
{
// We were unable to get the literal (e.g. dynamic context)
return nullptr;
}
JITDUMP("Trying to unroll MemoryExtensions.Equals|SequenceEqual|StartsWith(op1, \"%ws\")...\n", str)
}
CORINFO_CLASS_HANDLE spanCls = gtGetStructHandle(spanObj);
CORINFO_FIELD_HANDLE pointerHnd = info.compCompHnd->getFieldInClass(spanCls, 0);
CORINFO_FIELD_HANDLE lengthHnd = info.compCompHnd->getFieldInClass(spanCls, 1);
const unsigned lengthOffset = info.compCompHnd->getFieldOffset(lengthHnd);
// Create a placeholder for Span object - we're not going to Append it to statements
// in advance to avoid redundant spills in case if we fail to vectorize
unsigned spanObjRef = lvaGrabTemp(true DEBUGARG("spanObj tmp"));
unsigned spanDataTmp = lvaGrabTemp(true DEBUGARG("spanData tmp"));
lvaTable[spanObjRef].lvType = TYP_BYREF;
lvaTable[spanDataTmp].lvType = TYP_BYREF;
GenTreeLclVar* spanObjRefLcl = gtNewLclvNode(spanObjRef, TYP_BYREF);
GenTreeLclVar* spanDataTmpLcl = gtNewLclvNode(spanDataTmp, TYP_BYREF);
GenTreeField* spanLength = gtNewFieldRef(TYP_INT, lengthHnd, gtClone(spanObjRefLcl), lengthOffset);
GenTreeField* spanData = gtNewFieldRef(TYP_BYREF, pointerHnd, spanObjRefLcl);
GenTree* unrolled =
impExpandHalfConstEquals(spanDataTmpLcl, spanLength, false, startsWith, (WCHAR*)str, cnsLength, 0);
if (unrolled != nullptr)
{
// We succeeded, fill the placeholders:
impAssignTempGen(spanObjRef, impGetStructAddr(spanObj, spanCls, (unsigned)CHECK_SPILL_NONE, true));
impAssignTempGen(spanDataTmp, spanData);
if (unrolled->OperIs(GT_QMARK))
{
// QMARK can't be a root node, spill it to a temp
unsigned rootTmp = lvaGrabTemp(true DEBUGARG("spilling unroll qmark"));
impAssignTempGen(rootTmp, unrolled);
unrolled = gtNewLclvNode(rootTmp, TYP_INT);
}
JITDUMP("... Successfully unrolled to:\n")
DISPTREE(unrolled)
for (int i = 0; i < argsCount; i++)
{
impPopStack();
}
// We have to clean up GT_RET_EXPR for String.op_Implicit or MemoryExtensions.AsSpans
if ((spanObj != op1) && op1->OperIs(GT_RET_EXPR))
{
GenTree* inlineCandidate = op1->AsRetExpr()->gtInlineCandidate;
assert(inlineCandidate->IsCall());
inlineCandidate->gtBashToNOP();
}
else if ((spanObj != op2) && op2->OperIs(GT_RET_EXPR))
{
GenTree* inlineCandidate = op2->AsRetExpr()->gtInlineCandidate;
assert(inlineCandidate->IsCall());
inlineCandidate->gtBashToNOP();
}
}
return unrolled;
}
| 37.925631 | 120 | 0.606275 | kejxu |
00a611b66e97f4d0f3b10198cc4ae33aacdb2caa | 724 | cpp | C++ | sys/fs/util/dirbuf_add.cpp | apexrtos/apex | 9538ab2f5b974035ca30ca8750479bdefe153047 | [
"0BSD"
] | 15 | 2020-05-08T06:21:58.000Z | 2021-12-11T18:10:43.000Z | sys/fs/util/dirbuf_add.cpp | apexrtos/apex | 9538ab2f5b974035ca30ca8750479bdefe153047 | [
"0BSD"
] | 11 | 2020-05-08T06:46:37.000Z | 2021-03-30T05:46:03.000Z | sys/fs/util/dirbuf_add.cpp | apexrtos/apex | 9538ab2f5b974035ca30ca8750479bdefe153047 | [
"0BSD"
] | 5 | 2020-08-31T17:05:03.000Z | 2021-12-08T07:09:00.000Z | #include <fs/util.h>
#include <cstddef>
#include <cstring>
#include <dirent.h>
int
dirbuf_add(dirent **buf, size_t *remain, ino_t ino, off_t off,
unsigned char type, const char *name)
{
const size_t align = alignof(dirent);
const size_t dirent_noname = offsetof(dirent, d_name);
const size_t name_max = *remain - dirent_noname;
if ((ssize_t)name_max < 2)
return -1;
const size_t name_len = strlcpy((*buf)->d_name, name, name_max);
if (name_len >= name_max)
return -1;
const size_t reclen = (dirent_noname + name_len + align) & -align;
(*buf)->d_ino = ino;
(*buf)->d_off = off;
(*buf)->d_reclen = reclen;
(*buf)->d_type = type;
*remain -= reclen;
*buf = (dirent *)((char *)*buf + reclen);
return 0;
}
| 25.857143 | 67 | 0.668508 | apexrtos |
00a6bfb518ff2110564ce7cbeb1f5a0d21c3f751 | 1,679 | cxx | C++ | IdListToString/main.cxx | robertmaynard/Sandbox | 724c67fd924c29630a49f8501fd9df7a2bbb1ed8 | [
"BSD-2-Clause"
] | 9 | 2015-01-10T04:31:50.000Z | 2019-03-04T13:55:08.000Z | IdListToString/main.cxx | robertmaynard/Sandbox | 724c67fd924c29630a49f8501fd9df7a2bbb1ed8 | [
"BSD-2-Clause"
] | 2 | 2016-10-19T12:56:47.000Z | 2017-06-02T13:55:35.000Z | IdListToString/main.cxx | robertmaynard/Sandbox | 724c67fd924c29630a49f8501fd9df7a2bbb1ed8 | [
"BSD-2-Clause"
] | 5 | 2015-01-05T15:52:50.000Z | 2018-02-14T18:08:19.000Z |
#include <vtkNew.h>
#include "convert.h"
#include <sys/time.h>
#include <algorithm>
#include <numeric>
void random_fill(vtkIdList* list, int max_count, int max_value)
{
//srand on time
srand (time(NULL));
//start random seed
timeval currentTime;
gettimeofday(¤tTime, NULL);
vtkIdType size = 1 + ((int)currentTime.tv_usec % (max_count-1) );
list->SetNumberOfIds(size);
for(int i=0; i < size; ++i)
{
list->SetId(i,(int)currentTime.tv_usec % max_value);
}
}
void reverseList(vtkIdList* in, vtkIdList* out)
{
out->DeepCopy(in);
vtkIdType size = out->GetNumberOfIds();
std::reverse(out->GetPointer(0),out->GetPointer(size));
}
int main(int, char**)
{
//we will test 1000 random list of values each with any where from
//1 to 10,000 values. the generated values will be between 0 and 1million
for(int i=0; i < 1000; ++i)
{
vtkNew<vtkIdList> listToTest;
//10000 max value size, 1mill max id value
random_fill(listToTest.GetPointer(),10000,1000000);
std::string result = to_key(listToTest.GetPointer());
if(result != to_key(listToTest->GetPointer(0),listToTest->GetNumberOfIds()) )
{
std::cerr << "key's failed to match when past by pointer" << std::endl;
return 1;
}
vtkNew<vtkIdList> reversedList;
reverseList(listToTest.GetPointer(),reversedList.GetPointer());
std::string reversedResult = to_key(reversedList.GetPointer());
if(result != reversedResult )
{
std::cerr << "key's failed to match given reversed order" << std::endl;
return 1;
}
std::cout << "gen key: " << result << " len: " << listToTest->GetNumberOfIds() << std::endl;
}
return 0;
}
| 24.333333 | 97 | 0.66349 | robertmaynard |
00a7937a3572efeed6b27e280e09db524b533373 | 5,692 | cpp | C++ | openexrid/Mask.cpp | MercenariesEngineering/openidmask | c7b2da1de1fbac8a4362839427bc13fde6a399c0 | [
"MIT"
] | 120 | 2016-02-19T10:58:34.000Z | 2022-03-20T12:13:28.000Z | openexrid/Mask.cpp | MercenariesEngineering/openexrid | f52e9c3417aab63d6c66e29cf7304d723bd55300 | [
"MIT"
] | 9 | 2016-04-15T07:52:12.000Z | 2021-06-28T07:41:57.000Z | openexrid/Mask.cpp | MercenariesEngineering/openidmask | c7b2da1de1fbac8a4362839427bc13fde6a399c0 | [
"MIT"
] | 21 | 2016-04-13T11:48:09.000Z | 2020-01-23T13:38:43.000Z | /*
*
***
*****
********************* Mercenaries Engineering SARL
***************** Copyright (C) 2016
*************
********* http://www.mercenaries-engineering.com
***********
**** ****
** **
*/
#include "Mask.h"
#include "Builder.h"
#include <ImfChannelList.h>
#include <ImfDeepFrameBuffer.h>
#include <ImfDeepScanLineInputFile.h>
#include <ImfDeepScanLineOutputFile.h>
#include <ImfIntAttribute.h>
#include <ImfPartType.h>
#include <ImfStringAttribute.h>
#include <ImathBox.h>
#include <assert.h>
#include <stdexcept>
using namespace Imf;
using namespace Imath;
using namespace std;
using namespace openexrid;
// Compression
extern std::string b64decode (const std::string& str);
extern std::string inflate (const std::string& str);
// ***************************************************************************
Mask::Mask () : _Width (0), _Height (0), _A (-1) {}
// ***************************************************************************
void Mask::read (const char *filename)
{
DeepScanLineInputFile file (filename);
const Header& header = file.header();
const Box2i displayWindow = header.displayWindow();
_Width = displayWindow.max.x - displayWindow.min.x + 1;
_Height = displayWindow.max.y - displayWindow.min.y + 1;
const Box2i dataWindow = header.dataWindow();
// Check the version
const Imf::IntAttribute *version = header.findTypedAttribute<Imf::IntAttribute> ("EXRIdVersion");
if (!version)
throw runtime_error ("The EXRIdVersion attribute is missing");
if (version->value () > (int)Version)
throw runtime_error ("The file has been created by an unknown version of the library");
// Get the name attribute
const Imf::StringAttribute *names = header.findTypedAttribute<Imf::StringAttribute> ("EXRIdNames");
if (!names)
throw runtime_error ("The EXRIdNames attribute is missing");
// Copy the names
if (version->value() < 3)
_Names = inflate (names->value ());
else
_Names = inflate (b64decode(names->value ()));
// Count the names
int namesN = 0;
{
size_t index = 0;
while (index < _Names.size ())
{
index += strnlen (&_Names[index], _Names.size ()-index)+1;
++namesN;
}
}
// Build the name indexes
_NamesIndexes.clear ();
_NamesIndexes.reserve (namesN);
{
// Current index
size_t index = 0;
while (index < _Names.size ())
{
// Push the index of the current name
_NamesIndexes.push_back ((uint32_t)index);
index += strnlen (&_Names[index], _Names.size ()-index)+1;
}
assert (_NamesIndexes.size () == namesN);
}
// Allocate the pixel indexes
_PixelsIndexes.clear ();
_PixelsIndexes.resize (_Width*_Height+1, 0);
// Initialize the frame buffer
DeepFrameBuffer frameBuffer;
frameBuffer.insertSampleCountSlice (Imf::Slice (UINT,
(char *) (&_PixelsIndexes[0]),
sizeof (uint32_t),
sizeof (uint32_t)*_Width));
// For each pixel of a single line, the pointer on the id values
vector<uint32_t*> id (_Width);
frameBuffer.insert ("Id", DeepSlice (UINT, (char *)&id[0], sizeof (uint32_t*), 0, sizeof (uint32_t)));
// Read the slices
_Slices.clear ();
const ChannelList &channels = header.channels ();
for (ChannelList::ConstIterator channel = channels.begin (); channel != channels.end (); ++channel)
{
if (channel.channel ().type == HALF)
_Slices.push_back (channel.name());
}
// For each pixel of a single line, the pointer on the coverage values
vector<vector<half*> > slices (_Slices.size ());
for (size_t s = 0; s < _Slices.size (); ++s)
{
slices[s].resize (_Width);
frameBuffer.insert (_Slices[s], DeepSlice (HALF, (char *)&slices[s][0], sizeof (half*), 0, sizeof (half)));
}
file.setFrameBuffer(frameBuffer);
// Read the whole pixel sample counts
file.readPixelSampleCounts(dataWindow.min.y, dataWindow.max.y);
// Accumulate the sample counts to get the indexes
// The current index
uint32_t index = 0;
for (int i = 0; i < _Width*_Height+1; ++i)
{
const uint32_t n = _PixelsIndexes[i];
// Convert from a sample count to a sample index
_PixelsIndexes[i] = index;
index += n;
}
// Resize the samples
_Ids.clear ();
_Ids.resize (index, 0);
_SlicesData.resize (_Slices.size ());
for (size_t s = 0; s < _Slices.size (); ++s)
{
_SlicesData[s].clear ();
_SlicesData[s].resize (index, 0.f);
}
// For each line
for (int y = dataWindow.min.y; y <= dataWindow.max.y; y++)
{
const int lineStart = y*_Width;
// For each pixel
for (int x = 0; x < _Width; x++)
{
const int _i = lineStart+x;
// The sample id and coverage pointers for this pixel
const uint32_t count = _PixelsIndexes[_i+1]-_PixelsIndexes[_i];
// Avoid invalide indexes
id[x] = count ? &_Ids[_PixelsIndexes[_i]] : NULL;
for (size_t s = 0; s < _Slices.size (); ++s)
slices[s][x] = count ? &_SlicesData[s][_PixelsIndexes[_i]] : NULL;
}
file.readPixels (y);
// In version 1, samples are already uncumulated
if (version->value () > 1)
{
const int A = findSlice ("A");
for (int x = 0; x < _Width; x++)
{
const int _i = lineStart+x;
const uint32_t count = _PixelsIndexes[_i+1]-_PixelsIndexes[_i];
if (count == 0) continue;
// Uncumulate the pixels value
float prevAlpha = 0.f;
for (uint32_t s = 0; s < count; ++s)
{
const int curr = _PixelsIndexes[_i]+s;
const float alpha = (float)_SlicesData[A][curr];
for (size_t v = 0; v < _Slices.size (); ++v)
_SlicesData[v][curr] = (1.f-prevAlpha)*_SlicesData[v][curr];
prevAlpha += (1.f-prevAlpha)*alpha;
}
}
}
}
}
// ***************************************************************************
| 28.318408 | 109 | 0.617709 | MercenariesEngineering |
00ad17966b6f2d7a580a642290e68f89253b7ec3 | 3,712 | cpp | C++ | module/mpc-be/SRC/src/filters/renderer/VideoRenderers/CPUUsage.cpp | 1aq/PBox | 67ced599ee36ceaff097c6584f8100cf96006dfe | [
"MIT"
] | null | null | null | module/mpc-be/SRC/src/filters/renderer/VideoRenderers/CPUUsage.cpp | 1aq/PBox | 67ced599ee36ceaff097c6584f8100cf96006dfe | [
"MIT"
] | null | null | null | module/mpc-be/SRC/src/filters/renderer/VideoRenderers/CPUUsage.cpp | 1aq/PBox | 67ced599ee36ceaff097c6584f8100cf96006dfe | [
"MIT"
] | null | null | null | /*
* (C) 2013-2018 see Authors.txt
*
* This file is part of MPC-BE.
*
* MPC-BE is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* MPC-BE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* use source from http://www.philosophicalgeek.com/2009/01/03/determine-cpu-usage-of-current-process-c-and-c/
*
*/
#include "StdAfx.h"
#include "CPUUsage.h"
CCPUUsage::CCPUUsage()
: m_nCPUUsage(0)
, m_dwLastRun(0)
, m_lRunCount(0)
{
ZeroMemory(&m_ftPrevSysKernel, sizeof(FILETIME));
ZeroMemory(&m_ftPrevSysUser, sizeof(FILETIME));
ZeroMemory(&m_ftPrevProcKernel, sizeof(FILETIME));
ZeroMemory(&m_ftPrevProcUser, sizeof(FILETIME));
GetUsage();
}
/**********************************************
* CCPUUsage::GetUsage
* returns the percent of the CPU that this process
* has used since the last time the method was called.
* If there is not enough information, -1 is returned.
* If the method is recalled to quickly, the previous value
* is returned.
***********************************************/
const short CCPUUsage::GetUsage()
{
//create a local copy to protect against race conditions in setting the
//member variable
short nCpuCopy = m_nCPUUsage;
if (::InterlockedIncrement(&m_lRunCount) == 1) {
/*
If this is called too often, the measurement itself will greatly affect the
results.
*/
if (!EnoughTimePassed()) {
::InterlockedDecrement(&m_lRunCount);
return nCpuCopy;
}
FILETIME ftSysIdle, ftSysKernel, ftSysUser;
FILETIME ftProcCreation, ftProcExit, ftProcKernel, ftProcUser;
if (!GetSystemTimes(&ftSysIdle, &ftSysKernel, &ftSysUser) ||
!GetProcessTimes(GetCurrentProcess(), &ftProcCreation, &ftProcExit, &ftProcKernel, &ftProcUser)) {
::InterlockedDecrement(&m_lRunCount);
return nCpuCopy;
}
if (!IsFirstRun()) {
/*
CPU usage is calculated by getting the total amount of time the system has operated
since the last measurement (made up of kernel + user) and the total
amount of time the process has run (kernel + user).
*/
ULONGLONG ftSysKernelDiff = SubtractTimes(ftSysKernel, m_ftPrevSysKernel);
ULONGLONG ftSysUserDiff = SubtractTimes(ftSysUser, m_ftPrevSysUser);
ULONGLONG ftProcKernelDiff = SubtractTimes(ftProcKernel, m_ftPrevProcKernel);
ULONGLONG ftProcUserDiff = SubtractTimes(ftProcUser, m_ftPrevProcUser);
ULONGLONG nTotalSys = ftSysKernelDiff + ftSysUserDiff;
ULONGLONG nTotalProc = ftProcKernelDiff + ftProcUserDiff;
if (nTotalSys > 0) {
m_nCPUUsage = (short)((100.0 * nTotalProc) / nTotalSys);
}
}
m_ftPrevSysKernel = ftSysKernel;
m_ftPrevSysUser = ftSysUser;
m_ftPrevProcKernel = ftProcKernel;
m_ftPrevProcUser = ftProcUser;
m_dwLastRun = GetTickCount();
nCpuCopy = m_nCPUUsage;
}
::InterlockedDecrement(&m_lRunCount);
return nCpuCopy;
}
ULONGLONG CCPUUsage::SubtractTimes(const FILETIME& ftA, const FILETIME& ftB)
{
LARGE_INTEGER a, b;
a.LowPart = ftA.dwLowDateTime;
a.HighPart = ftA.dwHighDateTime;
b.LowPart = ftB.dwLowDateTime;
b.HighPart = ftB.dwHighDateTime;
return a.QuadPart - b.QuadPart;
}
bool CCPUUsage::EnoughTimePassed()
{
const DWORD minElapsedMS = 1000UL;
return (GetTickCount() - m_dwLastRun) >= minElapsedMS;
}
| 29.228346 | 110 | 0.717942 | 1aq |
00b2efd06cd56a1f88f29d529b461715f705497b | 2,070 | hpp | C++ | lib/io/Input.hpp | maldicion069/monkeybrush- | 2bccca097402ff1f5344e356f06de19c8c70065b | [
"MIT"
] | 1 | 2016-11-15T09:04:12.000Z | 2016-11-15T09:04:12.000Z | lib/io/Input.hpp | maldicion069/monkeybrush- | 2bccca097402ff1f5344e356f06de19c8c70065b | [
"MIT"
] | null | null | null | lib/io/Input.hpp | maldicion069/monkeybrush- | 2bccca097402ff1f5344e356f06de19c8c70065b | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2016 maldicion069
*
* Authors: Cristian Rodríguez Bernal <ccrisrober@gmail.com>
*
* This file is part of MonkeyBrushPlusPlus
* <https://github.com/maldicion069/monkeybrushplusplus>
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License version 3.0 as published
* by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#ifndef __MB_INPUT__
#define __MB_INPUT__
#include <mb/api.h>
#include "../Includes.hpp"
#include "Mouse.hpp"
#include "Keyboard.hpp"
namespace mb
{
class Input
{
public:
MB_API
static void initialize();
MB_API
static void destroy();
MB_API
static mb::Keyboard* Keyboard();
MB_API
static mb::Mouse* Mouse();
MB_API
static bool isKeyPressed(Keyboard::Key key);
MB_API
static bool isKeyClicked(Keyboard::Key key);
MB_API
static bool KeyReleased(Keyboard::Key key);
MB_API
static int MouseX();
MB_API
static int MouseY();
MB_API
static Input* instance();
MB_API
static int PreviousMouseX();
MB_API
static int PreviousMouseY();
MB_API
static int MouseWheelX();
MB_API
static int MouseWheelY();
MB_API
static int DeltaX(int val);
MB_API
static int DeltaY(int val);
MB_API
static bool MouseButtonPress(MouseButton button);
MB_API
static bool MouseButtonSinglePress(MouseButton button);
MB_API
static bool MouseButtonRelease(MouseButton button);
MB_API
static void update();
protected:
mb::Keyboard* _keyboard;
mb::Mouse* _mouse;
static Input *_instance;
};
}
#endif /* __MB_INPUT__ */
| 23.793103 | 80 | 0.729469 | maldicion069 |
00b7e1243aa38f26f5fd456a2a6b9619f3a8d9b9 | 16,380 | cpp | C++ | IMa/update_t_RY.cpp | jaredgk/IMgui-electron | b72ce318dcc500664bd264d8c1578723f61aa769 | [
"CC0-1.0",
"BSD-3-Clause"
] | null | null | null | IMa/update_t_RY.cpp | jaredgk/IMgui-electron | b72ce318dcc500664bd264d8c1578723f61aa769 | [
"CC0-1.0",
"BSD-3-Clause"
] | null | null | null | IMa/update_t_RY.cpp | jaredgk/IMgui-electron | b72ce318dcc500664bd264d8c1578723f61aa769 | [
"CC0-1.0",
"BSD-3-Clause"
] | null | null | null | /*IMa2p 2009-2015 Jody Hey, Rasmus Nielsen, Sang Chul Choi, Vitor Sousa, Janeen Pisciotta, and Arun Sethuraman */
#undef GLOBVARS
#include "imamp.hpp"
#include "update_gtree_common.hpp"
#include "updateassignment.hpp"
/*********** LOCAL STUFF **********/
static struct genealogy_weights holdallgweight_t_RY;
static struct genealogy_weights holdgweight_t_RY[MAXLOCI];
static struct probcalc holdallpcalc_t_RY;
static int largestsamp;
static int **skipflag;
static double beforesplit (int tnode, double oldt, double newt, double tau_u, double ptime);
static double aftersplit (int tnode, double oldt, double newt, double tau_d, double ptime);
static void storegenealogystats_all_loci (int ci, int mode);
static double forwardRY3 (double ptime, /* double oldt, */double r, double t_u_prior);
static double backwardRY3 (double ptime, /* double newt, */double r,double t_u_prior);
/********* LOCAL FUNCTIONS **************/
void
storegenealogystats_all_loci (int ci, int mode)
{
static double holdlength[MAXLOCI], holdtlength[MAXLOCI];
static double holdroottime[MAXLOCI];
static int holdroot[MAXLOCI];
static int holdmig[MAXLOCI];
int li;
if (mode == 0)
{
for (li = 0; li < nloci; li++)
{
holdlength[li] = C[ci]->G[li].length;
holdtlength[li] = C[ci]->G[li].tlength;
holdroottime[li] = C[ci]->G[li].roottime;
holdroot[li] = C[ci]->G[li].root;
holdmig[li] = C[ci]->G[li].mignum;
}
}
else
{
for (li = 0; li < nloci; li++)
{
C[ci]->G[li].length = holdlength[li];
C[ci]->G[li].tlength = holdtlength[li];
C[ci]->G[li].mignum = holdmig[li];
C[ci]->G[li].roottime = holdroottime[li];
C[ci]->G[li].root = holdroot[li];
}
}
return;
} // storegenealogystats
double
aftersplit (int tnode, double oldt, double newt, double tau_d, double ptime)
{
if (tnode == lastperiodnumber - 1)
{
return ptime + newt - oldt;
}
else
{
return tau_d - (tau_d - newt) * (tau_d - ptime) / (tau_d - oldt);
}
}
double
beforesplit (int tnode, double oldt, double newt, double tau_u, double ptime)
{
if (tnode == 0)
{
return ptime * newt / oldt;
}
else
{
return tau_u + (ptime - tau_u) * (newt - tau_u) / (oldt - tau_u);
}
}
/*************GLOBAL FUNCTIONS ******************/
void
init_t_RY (void)
{
int li, j;
init_genealogy_weights (&holdallgweight_t_RY);
for (li = 0; li < nloci; li++)
init_genealogy_weights (&holdgweight_t_RY[li]);
init_probcalc (&holdallpcalc_t_RY);
for (largestsamp = 0, j = 0; j < nloci; j++)
if (largestsamp < L[j].numlines)
largestsamp = L[j].numlines;
skipflag = alloc2Dint (nloci, 2 * largestsamp - 1);
} // init_changet_RY
void
free_t_RY (void)
{
int li;
free_genealogy_weights (&holdallgweight_t_RY);
for (li = 0; li < nloci; li++)
{
free_genealogy_weights (&holdgweight_t_RY[li]);
}
free_probcalc (&holdallpcalc_t_RY);
orig2d_free2D ((void **) skipflag, nloci);
} // free_changet_RY
/*
Notes on changet_RY() implements updating of Rannala and Yang (2003)
This application is pretty much the same as theirs - changing times on a species tree that contains a gene tree.
The big difference is that IM includes migration. This means that we have to count migration events and change
migration times in the same was as we change coalescent times and count how many get changed.
R&Y also only change coalescent times in populations affected by a changed t. But because we have migration
there is more entanglement between populations. It seems best to change all times within an interval that is
affected by a changing t.
in R&Y usage
u (upper) means older, deeper in the genealogy
l (lower) means younger, more recent in the genealogy
In R&Y
Tu next older split time
Tl next more recent split time
T - current split time
T* - proposed time
t - time of some event
t* - time of that event after update
If Tu> t > T
t* = Tu - (Tu-t) (Tu-t*)/(Tu-T)
If Tl< t<= T
t* = Tl + (t-tl) (T*-Tl)/(T-Tl)
nl = number of nodes with Tl< t < T
ml = number of migration events with Tl< t < T
nu = number of nodes with Tu> t > T
mu = number of migration events with Tu> t > T
MH criteria
p(X|G*,t*)p(G*,t*) (Tu-T*)^(nu+mu) (T*-Tl)^(nl+ml)
---------------------------------------------------
p(X|G,t)p(G,t) (Tu-T)^(nu+mu) (T-Tl)^(nl+ml)
but this causes confusion with jhey usage in which
u means upper - more recent.
so here we use u for upper (meaning more recent)
use d for down (older)
tau current split time
tau* new value
tau_d - older node time (i.e. time of next oldest node - deeper in the genealogy)
tau_u - more recent node time (i.e. time of next youngest node - more recent in time)
tau_d > tau > tau_u
if tau is the first node, then tau_u = 0.
if tau is the last node, then tau_d = infinity
for an event at time t where tau_u < t < tau_d
if t > tau see aftersplit() t is older than the current split time
t* = tau_d - (tau_d - tau*)(tau_d - t)/(tau_d-tau) (A7)
if t <= tau see beforesplit()
t* = tau_u + (tau* - tau_u)(t - tau_u)/(tau - tau_u) (A8)
m is the number of events moved using A7, n is the number moved using A8
then Hastings term for the update is:
tau_d - tau* tau* - tau_u
(------------)^m (------------)^n
tau-u - tau tau - tau_u
For IM, we use the same except m and n include both includes migation and coalescent events
For edges where downtime < tau_d || uptime > tau_d are not involved in the update
For any edge that spends zero time in either splitpop or the ancestral pop, during the tau_u/tau_d interval
it is possible to not update the coalescent time or migration times of
The difficulty is that it is possible that an uptime for one edge gets moved because the times on one of its daughter edges got moved.
This means that for checking about skipping an edge, because it is not involved in any
population associated with the splittin time update
we need to check entire groups of branches that descend from
an edge that crosses the tau_u boundary.
use a scoring system for edges
-1 to ignore because out of bounds above
-2 to ignore because out of bounds below
0 to deal with, edge is relevant
1 to ignore because not in splitpops or ancestral pop
set up a recursive function
for an edge that crosses the tau_d line, check to see if that edge
and all descendent edges that to not cross tau_l are in the
populations affected by the splitting time update
If all of those edges are not relevant then
they all get a skipflag value of 1
If any one of them does spend any time in any of the
populations involved int the population split
then all of the edges have their skipflag value
set to 0
*/
/* let u refer to the more recent time and d to the older time */
int
changet_RY1 (int ci, int timeperiod) // after Rannala and Yang (2003) - rubberband method
{
double metropolishastingsterm, newt, oldt;
double pdgnew[MAXLOCI + MAXLINKED], pdgnewsum, pdgoldsum, probgnewsum,
temppdg;
double t_u_hterm, t_d_hterm, tpw;
int li, i, j, ecd, ecu, emd, emu, ai, ui;
double U;
struct genealogy *G;
struct edge *gtree;
double t_d, t_u, t_u_prior, t_d_prior;
double holdt[MAXPERIODS];
if (assignmentoptions[POPULATIONASSIGNMENTCHECKPOINT] == 1)
{
assertgenealogy (ci);
}
t_u = (timeperiod == 0) ? 0 : C[ci]->tvals[timeperiod - 1];
t_d =
(timeperiod ==
(lastperiodnumber - 1)) ? TIMEMAX : C[ci]->tvals[timeperiod + 1];
t_d_prior = DMIN (T[timeperiod].pr.max, t_d);
t_u_prior = DMAX (T[timeperiod].pr.min, t_u);
oldt = C[ci]->tvals[timeperiod];
newt = getnewt (timeperiod, t_u_prior, t_d_prior, oldt, 1);
t_u_hterm = (newt - t_u) / (oldt - t_u);
if (timeperiod == lastperiodnumber - 1)
{
t_d_hterm = 1;
}
else
{
t_d_hterm = (t_d - newt) / (t_d - oldt);
}
copy_treeinfo (&holdallgweight_t_RY, &C[ci]->allgweight); // try turning this off and forcing all recalculations
copy_probcalc (&holdallpcalc_t_RY, &C[ci]->allpcalc);
for (i = 0; i < lastperiodnumber; i++)
holdt[i] = C[ci]->tvals[i];
pdgoldsum = C[ci]->allpcalc.pdg;
setzero_genealogy_weights (&C[ci]->allgweight);
ecd = ecu = emd = emu = 0;
pdgnewsum = 0;
probgnewsum = 0;
storegenealogystats_all_loci (ci, 0);
C[ci]->tvals[timeperiod] = newt;
for (i = 0; i < nurates; i++)
pdgnew[i] = 0;
for (li = 0; li < nloci; li++)
{
G = &(C[ci]->G[li]);
gtree = G->gtree;
copy_treeinfo (&holdgweight_t_RY[li], &G->gweight);
for (i = 0; i < L[li].numlines; i++)
{
if (gtree[i].down != -1)
{
if (gtree[i].time <= oldt && gtree[i].time > t_u)
{
//assert (skipflag[li][i] == 0);turn off 9/19/10
gtree[i].time =
beforesplit (timeperiod, oldt, newt, /* t_d, */ t_u, gtree[i].time);
assert (gtree[i].time != newt);
ecu++;
}
else
{
if (gtree[i].time > oldt && gtree[i].time < t_d)
{
// assert (skipflag[li][i] == 0); turn off 9/19/10
gtree[i].time =
aftersplit (timeperiod, oldt, newt, t_d, /* t_u, */ gtree[i].time);
assert (gtree[i].time != newt);
ecd++;
}
//else do not change the time
}
j = 0;
while (gtree[i].mig[j].mt > -0.5)
{
assert (gtree[i].mig[j].mt < C[0]->tvals[lastperiodnumber]);
if (gtree[i].mig[j].mt <= oldt && gtree[i].mig[j].mt > t_u)
{
gtree[i].mig[j].mt =
beforesplit (timeperiod, oldt, newt, /* t_d, */ t_u,
gtree[i].mig[j].mt);
emu++;
}
else
{
assert (oldt < C[0]->tvals[lastperiodnumber]);
if (gtree[i].mig[j].mt > oldt && gtree[i].mig[j].mt < t_d)
{
gtree[i].mig[j].mt =
aftersplit (timeperiod, oldt, newt, t_d, /* t_u, */
gtree[i].mig[j].mt);
emd++;
}
// else no need to change the time
}
j++;
}
}
}
if (G->roottime <= oldt && G->roottime > t_u
/* && skipflag[li][G->root] == 0 turn off 9/19/10*/)
G->roottime =
beforesplit (timeperiod, oldt, newt, /* t_d, */ t_u, G->roottime);
else if (G->roottime > oldt && G->roottime < t_d
/* && skipflag[li][G->root] == 0 turn off 9/19/10*/)
G->roottime =
aftersplit (timeperiod, oldt, newt, t_d, /* t_u, */ G->roottime);
setzero_genealogy_weights (&G->gweight);
treeweight (ci, li);
sum_treeinfo (&C[ci]->allgweight, &G->gweight);
ai = 0;
ui = L[li].uii[ai];
switch (L[li].model)
{
assert (pdgnew[ui] == 0);
case HKY:
if (assignmentoptions[JCMODEL] == 1)
{
temppdg = pdgnew[ui] =
likelihoodJC (ci, li, G->uvals[0]);
}
else
{
temppdg = pdgnew[ui] =
likelihoodHKY (ci, li, G->uvals[0], G->kappaval, -1, -1, -1, -1);
}
break;
case INFINITESITES:
temppdg = pdgnew[ui] = likelihoodIS (ci, li, G->uvals[0]);
break;
case STEPWISE:
temppdg = 0;
for (; ai < L[li].nlinked; ai++)
{
ui = L[li].uii[ai];
assert (pdgnew[ui] == 0);
pdgnew[ui] = likelihoodSW (ci, li, ai, G->uvals[ai], 1.0);
temppdg += pdgnew[ui];
}
break;
case JOINT_IS_SW:
temppdg = pdgnew[ui] = likelihoodIS (ci, li, G->uvals[0]);
for (ai = 1; ai < L[li].nlinked; ai++)
{
ui = L[li].uii[ai];
assert (pdgnew[ui] == 0);
pdgnew[ui] = likelihoodSW (ci, li, ai, G->uvals[ai], 1.0);
temppdg += pdgnew[ui];
}
break;
}
pdgnewsum += temppdg;
}
assert (!ODD (ecd));
assert (!ODD (ecu));
ecd /= 2;
ecu /= 2;
integrate_tree_prob (ci, &C[ci]->allgweight, &holdallgweight_t_RY,
&C[ci]->allpcalc, &holdallpcalc_t_RY, &holdt[0]); // try enforcing full cacullation
tpw = gbeta * (pdgnewsum - pdgoldsum);
/* 5/19/2011 JH adding thermodynamic integration */
if (calcoptions[CALCMARGINALLIKELIHOOD])
{
metropolishastingsterm = beta[ci] * tpw + (C[ci]->allpcalc.probg - holdallpcalc_t_RY.probg) + (ecd + emd) * log (t_d_hterm) + (ecu + emu) * log (t_u_hterm);
}
else
{
tpw += C[ci]->allpcalc.probg - holdallpcalc_t_RY.probg;
metropolishastingsterm = beta[ci] * tpw + (ecd + emd) * log (t_d_hterm) + (ecu + emu) * log (t_u_hterm);
}
//assert(metropolishastingsterm >= -1e200 && metropolishastingsterm < 1e200);
U = log (uniform ());
if (U < DMIN(1.0, metropolishastingsterm)) //9/13/2010
//if (metropolishastingsterm >= 0.0 || metropolishastingsterm > U)
{
for (li = 0; li < nloci; li++)
{
C[ci]->G[li].pdg = 0;
for (ai = 0; ai < L[li].nlinked; ai++)
{
C[ci]->G[li].pdg_a[ai] = pdgnew[L[li].uii[ai]];
C[ci]->G[li].pdg += C[ci]->G[li].pdg_a[ai];
}
if (L[li].model == HKY)
{
storescalefactors (ci, li);
copyfraclike (ci, li);
}
}
C[ci]->allpcalc.pdg = pdgnewsum;
C[ci]->poptree[C[ci]->droppops[timeperiod + 1][0]].time =
C[ci]->poptree[C[ci]->droppops[timeperiod + 1][1]].time = newt;
if (assignmentoptions[POPULATIONASSIGNMENTCHECKPOINT] == 1)
{
assertgenealogy (ci);
}
return 1;
}
else
{
copy_treeinfo (&C[ci]->allgweight, &holdallgweight_t_RY);
copy_probcalc (&C[ci]->allpcalc, &holdallpcalc_t_RY);
assert (pdgoldsum == C[ci]->allpcalc.pdg);
C[ci]->tvals[timeperiod] = oldt;
for (li = 0; li < nloci; li++)
{
G = &(C[ci]->G[li]);
gtree = G->gtree;
storegenealogystats_all_loci (ci, 1);
copy_treeinfo (&G->gweight, &holdgweight_t_RY[li]);
for (i = 0; i < L[li].numlines; i++)
{
if (gtree[i].down != -1)
{
if (gtree[i].time <= newt && gtree[i].time > t_u)
{
// assert (skipflag[li][i] == 0); turned off 9/19/10
gtree[i].time =
beforesplit (timeperiod, newt, oldt, /* t_d, */ t_u, gtree[i].time);
//cecu++;
}
else
{
if (gtree[i].time > newt && gtree[i].time < t_d)
{
//assert (skipflag[li][i] == 0); turned off 9/19/10
gtree[i].time =
aftersplit (timeperiod, newt, oldt, t_d, /* t_u, */ gtree[i].time);
//cecl++;
}
}
j = 0;
while (gtree[i].mig[j].mt > -0.5)
{
if (gtree[i].mig[j].mt <= newt && gtree[i].mig[j].mt > t_u)
{
gtree[i].mig[j].mt =
beforesplit (timeperiod, newt, oldt, /* t_d, */
t_u, gtree[i].mig[j].mt);
//cemu++;
}
else if (gtree[i].mig[j].mt > newt && gtree[i].mig[j].mt < t_d)
{
gtree[i].mig[j].mt =
aftersplit (timeperiod, newt, oldt, t_d, /* t_u, */
gtree[i].mig[j].mt);
//ceml++;
}
j++;
}
}
}
// assert(fabs(C[ci]->G[li].gtree[ C[ci]->G[li].gtree[C[ci]->G[li].root].up[0]].time - C[ci]->G[li].roottime) < 1e-8);
}
/* assert(ecu==cecu/2);
assert(ecd==cecl/2);
assert(emu==cemu);
assert(emd==ceml); */
for (li = 0; li < nloci; li++)
{
if (L[li].model == HKY)
restorescalefactors (ci, li);
/* have to reset the dlikeA values in the genealogies for stepwise model */
if (L[li].model == STEPWISE)
for (ai = 0; ai < L[li].nlinked; ai++)
likelihoodSW (ci, li, ai, C[ci]->G[li].uvals[ai], 1.0);
if (L[li].model == JOINT_IS_SW)
for (ai = 1; ai < L[li].nlinked; ai++)
likelihoodSW (ci, li, ai, C[ci]->G[li].uvals[ai], 1.0);
// assert(fabs(C[ci]->G[li].gtree[ C[ci]->G[li].gtree[C[ci]->G[li].root].up[0]].time - C[ci]->G[li].roottime) < 1e-8);
}
if (assignmentoptions[POPULATIONASSIGNMENTCHECKPOINT] == 1)
{
assertgenealogy (ci);
}
return 0;
}
} /* changet_RY1 */
| 31.560694 | 160 | 0.573382 | jaredgk |
00beece22dffd42c0610e574d6e37930fa8dddb0 | 997 | cpp | C++ | archive/1/dwa_slowa.cpp | Aleshkev/algoritmika | fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189 | [
"MIT"
] | 2 | 2019-05-04T09:37:09.000Z | 2019-05-22T18:07:28.000Z | archive/1/dwa_slowa.cpp | Aleshkev/algoritmika | fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189 | [
"MIT"
] | null | null | null | archive/1/dwa_slowa.cpp | Aleshkev/algoritmika | fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189 | [
"MIT"
] | null | null | null | //#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
#include <cstring>
using namespace std;
typedef long long unsigned U;
int main()
{
/*
cout.sync_with_stdio(false);
U _;
cin >> _;
string a, b;
cin >> a >> b;
U n;
cin >> n;
for(U i = 0; i < n; ++i) {
U ai, bi;
cin >> ai >> bi;
swap(a[ai], b[bi]);
int eq = a.compare(b);
cout << (eq == 0 ? '0' :
eq > 0 ? '1' :
'2') << '\n';
}*/
U _;
scanf("%llu", &_);
const U maxlen = 1e6 + 1;
char a[maxlen], b[maxlen];
scanf("%s %s", a, b);
U n;
scanf("%llu", &n);
for(U i = 0; i < n; ++i) {
U ai, bi;
scanf("%llu %llu", &ai, &bi);
U t = a[ai]; a[ai] = b[bi]; b[bi] = t;
int eq = strcmp(a, b);
printf("%c\n", (eq == 0 ? '0' :
eq > 0 ? '1' :
'2'));
}
return 0;
}
| 16.080645 | 46 | 0.374122 | Aleshkev |
00bfb7c799bde6e379d9e81f8baffb881c6d97d4 | 7,033 | cc | C++ | content/browser/devtools/devtools_renderer_channel.cc | Yannic/chromium | ab32e8aacb08c9fce0dc4bf09eec456ba46e3710 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/browser/devtools/devtools_renderer_channel.cc | Yannic/chromium | ab32e8aacb08c9fce0dc4bf09eec456ba46e3710 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2019-03-13T10:32:53.000Z | 2019-03-13T11:05:30.000Z | content/browser/devtools/devtools_renderer_channel.cc | Yannic/chromium | ab32e8aacb08c9fce0dc4bf09eec456ba46e3710 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/devtools/devtools_renderer_channel.h"
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "content/browser/devtools/devtools_agent_host_impl.h"
#include "content/browser/devtools/devtools_session.h"
#include "content/browser/devtools/protocol/devtools_domain_handler.h"
#include "content/browser/devtools/worker_devtools_agent_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/common/child_process_host.h"
#include "ui/gfx/geometry/point.h"
namespace content {
DevToolsRendererChannel::DevToolsRendererChannel(DevToolsAgentHostImpl* owner)
: owner_(owner),
process_id_(ChildProcessHost::kInvalidUniqueID) {}
DevToolsRendererChannel::~DevToolsRendererChannel() = default;
void DevToolsRendererChannel::SetRenderer(
mojo::PendingRemote<blink::mojom::DevToolsAgent> agent_remote,
mojo::PendingReceiver<blink::mojom::DevToolsAgentHost> host_receiver,
int process_id,
base::OnceClosure connection_error) {
CleanupConnection();
blink::mojom::DevToolsAgent* agent = nullptr;
if (agent_remote.is_valid()) {
agent_remote_.Bind(std::move(agent_remote));
agent = agent_remote_.get();
}
if (connection_error)
agent_remote_.set_disconnect_handler(std::move(connection_error));
if (host_receiver)
receiver_.Bind(std::move(host_receiver));
const bool force_using_io = true;
SetRendererInternal(agent, process_id, nullptr, force_using_io);
}
void DevToolsRendererChannel::SetRendererAssociated(
mojo::PendingAssociatedRemote<blink::mojom::DevToolsAgent> agent_remote,
mojo::PendingAssociatedReceiver<blink::mojom::DevToolsAgentHost>
host_receiver,
int process_id,
RenderFrameHostImpl* frame_host) {
CleanupConnection();
blink::mojom::DevToolsAgent* agent = nullptr;
if (agent_remote.is_valid()) {
associated_agent_remote_.Bind(std::move(agent_remote));
agent = associated_agent_remote_.get();
}
if (host_receiver)
associated_receiver_.Bind(std::move(host_receiver));
const bool force_using_io = false;
SetRendererInternal(agent, process_id, frame_host, force_using_io);
}
void DevToolsRendererChannel::CleanupConnection() {
receiver_.reset();
associated_receiver_.reset();
associated_agent_remote_.reset();
agent_remote_.reset();
}
void DevToolsRendererChannel::ForceDetachWorkerSessions() {
for (WorkerDevToolsAgentHost* host : child_workers_)
host->ForceDetachAllSessions();
}
void DevToolsRendererChannel::SetRendererInternal(
blink::mojom::DevToolsAgent* agent,
int process_id,
RenderFrameHostImpl* frame_host,
bool force_using_io) {
ReportChildWorkersCallback();
process_id_ = process_id;
frame_host_ = frame_host;
if (agent && child_worker_created_callback_) {
agent->ReportChildWorkers(true /* report */, wait_for_debugger_,
base::DoNothing());
}
for (DevToolsSession* session : owner_->sessions()) {
for (auto& pair : session->handlers())
pair.second->SetRenderer(process_id_, frame_host_);
session->AttachToAgent(agent, force_using_io);
}
}
void DevToolsRendererChannel::AttachSession(DevToolsSession* session) {
if (!agent_remote_ && !associated_agent_remote_)
owner_->UpdateRendererChannel(true /* force */);
for (auto& pair : session->handlers())
pair.second->SetRenderer(process_id_, frame_host_);
if (agent_remote_)
session->AttachToAgent(agent_remote_.get(), true);
else if (associated_agent_remote_)
session->AttachToAgent(associated_agent_remote_.get(), false);
}
void DevToolsRendererChannel::InspectElement(const gfx::Point& point) {
if (!agent_remote_ && !associated_agent_remote_)
owner_->UpdateRendererChannel(true /* force */);
// Previous call might update |agent_remote_| or |associated_agent_remote_|
// via SetRenderer(), so we should check them again.
if (agent_remote_)
agent_remote_->InspectElement(point);
else if (associated_agent_remote_)
associated_agent_remote_->InspectElement(point);
}
void DevToolsRendererChannel::SetReportChildWorkers(
ChildWorkerCreatedCallback report_callback,
bool wait_for_debugger,
base::OnceClosure completion_callback) {
DCHECK(report_callback || !wait_for_debugger);
ReportChildWorkersCallback();
set_report_completion_callback_ = std::move(completion_callback);
if (child_worker_created_callback_ == report_callback &&
wait_for_debugger_ == wait_for_debugger) {
ReportChildWorkersCallback();
return;
}
if (report_callback) {
for (DevToolsAgentHostImpl* host : child_workers_)
report_callback.Run(host, false /* waiting_for_debugger */);
}
child_worker_created_callback_ = std::move(report_callback);
wait_for_debugger_ = wait_for_debugger;
if (agent_remote_) {
agent_remote_->ReportChildWorkers(
!!child_worker_created_callback_, wait_for_debugger_,
base::BindOnce(&DevToolsRendererChannel::ReportChildWorkersCallback,
base::Unretained(this)));
} else if (associated_agent_remote_) {
associated_agent_remote_->ReportChildWorkers(
!!child_worker_created_callback_, wait_for_debugger_,
base::BindOnce(&DevToolsRendererChannel::ReportChildWorkersCallback,
base::Unretained(this)));
} else {
ReportChildWorkersCallback();
}
}
void DevToolsRendererChannel::ReportChildWorkersCallback() {
if (set_report_completion_callback_)
std::move(set_report_completion_callback_).Run();
}
void DevToolsRendererChannel::ChildWorkerCreated(
mojo::PendingRemote<blink::mojom::DevToolsAgent> worker_devtools_agent,
mojo::PendingReceiver<blink::mojom::DevToolsAgentHost> host_receiver,
const GURL& url,
const std::string& name,
const base::UnguessableToken& devtools_worker_token,
bool waiting_for_debugger) {
if (content::DevToolsAgentHost::GetForId(devtools_worker_token.ToString())) {
receiver_.ReportBadMessage("Workers should have unique tokens.");
return;
}
RenderProcessHost* process = RenderProcessHost::FromID(process_id_);
if (!process)
return;
GURL filtered_url = url;
process->FilterURL(true /* empty_allowed */, &filtered_url);
auto agent_host = base::MakeRefCounted<WorkerDevToolsAgentHost>(
process_id_, std::move(worker_devtools_agent), std::move(host_receiver),
filtered_url, std::move(name), devtools_worker_token, owner_->GetId(),
base::BindOnce(&DevToolsRendererChannel::ChildWorkerDestroyed,
weak_factory_.GetWeakPtr()));
child_workers_.insert(agent_host.get());
if (child_worker_created_callback_)
child_worker_created_callback_.Run(agent_host.get(), waiting_for_debugger);
}
void DevToolsRendererChannel::ChildWorkerDestroyed(
DevToolsAgentHostImpl* host) {
child_workers_.erase(host);
}
} // namespace content
| 37.811828 | 79 | 0.756007 | Yannic |
00bfceb3a37b721723f1462bd8b36e24b522007c | 198 | hpp | C++ | archive/CairoUtil.hpp | irishpatrick/sdl-game | 23ff8330fe2aaa765119df40d62e50570f606f07 | [
"MIT-0",
"MIT"
] | null | null | null | archive/CairoUtil.hpp | irishpatrick/sdl-game | 23ff8330fe2aaa765119df40d62e50570f606f07 | [
"MIT-0",
"MIT"
] | null | null | null | archive/CairoUtil.hpp | irishpatrick/sdl-game | 23ff8330fe2aaa765119df40d62e50570f606f07 | [
"MIT-0",
"MIT"
] | null | null | null | #pragma once
#include <cairo.h>
#include <cstdint>
namespace engine
{
class CairoUtil
{
public:
static void drawVector(cairo_t*, uint32_t, uint32_t, uint32_t, double);
};
} | 15.230769 | 79 | 0.651515 | irishpatrick |
00c060f0fe5aca9d5fd8d8c546de0ec4264135c2 | 14,178 | cc | C++ | test/bezierSubdivision.cc | cwsmith/core | 840fbf6ec49a63aeaa3945f11ddb224f6055ac9f | [
"BSD-3-Clause"
] | 1 | 2021-12-02T09:25:32.000Z | 2021-12-02T09:25:32.000Z | test/bezierSubdivision.cc | cwsmith/core | 840fbf6ec49a63aeaa3945f11ddb224f6055ac9f | [
"BSD-3-Clause"
] | null | null | null | test/bezierSubdivision.cc | cwsmith/core | 840fbf6ec49a63aeaa3945f11ddb224f6055ac9f | [
"BSD-3-Clause"
] | null | null | null | #include <crv.h>
#include <crvBezier.h>
#include <crvSnap.h>
#include <gmi_analytic.h>
#include <gmi_null.h>
#include <apfMDS.h>
#include <apfMesh2.h>
#include <apf.h>
#include <PCU.h>
#include <mth.h>
#include <mth_def.h>
#include <pcu_util.h>
/*
* This contains all the tests for bezier subdivision
*/
void vertFunction(double const p[2], double x[3], void*)
{
(void)p;
(void)x;
}
// simple quartic edge
void edgeFunction(double const p[2], double x[3], void*)
{
x[0] = p[0]*p[0]*p[0]*p[0];
x[1] = p[0]*p[0];
x[2] = p[0];
}
void reparam_zero(double const from[2], double to[2], void*)
{
(void)from;
to[0] = 0;
to[1] = 0;
}
void reparam_one(double const from[2], double to[2], void*)
{
(void)from;
to[0] = 1;
to[1] = 0;
}
agm_bdry add_bdry(gmi_model* m, gmi_ent* e)
{
return agm_add_bdry(gmi_analytic_topo(m), agm_from_gmi(e));
}
agm_use add_adj(gmi_model* m, agm_bdry b, int tag)
{
agm* topo = gmi_analytic_topo(m);
int dim = agm_dim_from_type(agm_bounds(topo, b).type);
gmi_ent* de = gmi_find(m, dim - 1, tag);
return agm_add_use(topo, b, agm_from_gmi(de));
}
gmi_model* makeEdgeModel()
{
gmi_model* model = gmi_make_analytic();
int edPer = 0;
double edRan[2] = {0, 1};
gmi_add_analytic(model, 0, 0, vertFunction, NULL,NULL,NULL);
gmi_add_analytic(model, 0, 1, vertFunction, NULL,NULL,NULL);
gmi_ent* ed = gmi_add_analytic(model, 1, 0, edgeFunction, &edPer, &edRan, 0);
agm_bdry b = add_bdry(model, ed);
agm_use u0 = add_adj(model, b, 0);
gmi_add_analytic_reparam(model, u0, reparam_zero, 0);
agm_use u1 = add_adj(model, b, 1);
gmi_add_analytic_reparam(model, u1, reparam_one, 0);
return model;
}
// edges go counter clockwise
// face areas are 1/2 and 19/30
void vert0(double const p[2], double x[3], void*)
{
(void)p;
(void)x;
}
// edges go counter clockwise
void edge0(double const p[2], double x[3], void*)
{
x[0] = p[0];
x[1] = 0.;
}
void edge1(double const p[2], double x[3], void*)
{
x[0] = 1.0-p[0]*(p[0]-1.0)*p[0]*(p[0]-1.0);
x[1] = p[0];
}
void edge2(double const p[2], double x[3], void*)
{
double u = 1.-p[0];
x[0] = u;
x[1] = u;
}
void face0(double const p[2], double x[3], void*)
{
(void)p;
(void)x;
}
void make_edge_topo(gmi_model* m, gmi_ent* e, int v0tag, int v1tag)
{
agm_bdry b = add_bdry(m, e);
agm_use u0 = add_adj(m, b, v0tag);
gmi_add_analytic_reparam(m, u0, reparam_zero, 0);
agm_use u1 = add_adj(m, b, v1tag);
gmi_add_analytic_reparam(m, u1, reparam_one, 0);
}
gmi_model* makeFaceModel()
{
gmi_model* model = gmi_make_analytic();
int edPer = 0;
double edRan[2] = {0, 1};
for(int i = 0; i < 3; ++i)
gmi_add_analytic(model, 0, i, vertFunction,NULL,NULL,NULL);
gmi_ent* eds[3];
eds[0] = gmi_add_analytic(model, 1, 0, edge0, &edPer, &edRan, 0);
eds[1] = gmi_add_analytic(model, 1, 1, edge1, &edPer, &edRan, 0);
eds[2] = gmi_add_analytic(model, 1, 2, edge2, &edPer, &edRan, 0);
for(int i = 0; i < 3; ++i)
make_edge_topo(model, eds[i], i, (i+1) % 3);
int faPer[2] = {0, 0};
double faRan[2][2] = {{0,1},{0,1}};
gmi_add_analytic(model, 2, 0, face0, faPer, faRan, 0);
return model;
}
apf::Mesh2* createMesh2D()
{
gmi_model* model = makeFaceModel();
apf::Mesh2* m = apf::makeEmptyMdsMesh(model, 2, false);
apf::MeshEntity* v[3], *edges[3];
apf::Vector3 points2D[3] =
{apf::Vector3(0,0,0),apf::Vector3(1,0,0),apf::Vector3(1,1,0)};
for (int i = 0; i < 3; ++i){
v[i] = m->createVertex(m->findModelEntity(0,i),points2D[i],points2D[i]);
}
for (int i = 0; i < 3; ++i){
apf::ModelEntity* edge = m->findModelEntity(1,i);
apf::MeshEntity* ved[2] = {v[i],v[(i+1) % 3]};
edges[i] = m->createEntity(apf::Mesh::EDGE,edge,ved);
}
apf::ModelEntity* faceModel = m->findModelEntity(2,0);
m->createEntity(apf::Mesh::TRIANGLE,faceModel,edges);
m->acceptChanges();
m->verify();
return m;
}
static apf::Vector3 points3D[4] =
{apf::Vector3(0,0,0),
apf::Vector3(1,0,0),
apf::Vector3(0,1,0),
apf::Vector3(0,0,1)};
apf::Mesh2* createMesh3D()
{
gmi_model* model = gmi_load(".null");
apf::Mesh2* m = apf::makeEmptyMdsMesh(model, 3, false);
apf::buildOneElement(m,0,apf::Mesh::TET,points3D);
apf::deriveMdsModel(m);
m->acceptChanges();
m->verify();
return m;
}
/*
* Create a mesh with a single edge,
* Create two edges as an even subdivision,
* and keep all three around, using the original one
* to compare correctness of the split.
*
*/
void testEdgeSubdivision()
{
for (int o = 1; o <= 6; ++o){
gmi_model* model = makeEdgeModel();
apf::Mesh2* m = apf::makeEmptyMdsMesh(model, 1, false);
apf::ModelEntity* edgeModel = m->findModelEntity(1,0);
apf::Vector3 points[2] = {apf::Vector3(0,0,0),apf::Vector3(1,1,1)};
apf::MeshEntity* v[2];
for (int i = 0; i < 2; ++i)
v[i] = m->createVertex(m->findModelEntity(0,i),points[i],points[i]);
apf::MeshEntity* edge = m->createEntity(apf::Mesh::EDGE,edgeModel, v);
m->acceptChanges();
m->verify();
// curve the mesh
crv::BezierCurver bc(m,o,0);
bc.run();
apf::Element* elem = apf::createElement(m->getCoordinateField(),edge);
apf::NewArray<apf::Vector3> nodes;
apf::NewArray<apf::Vector3> subNodes[2];
subNodes[0].allocate(o+1);
subNodes[1].allocate(o+1);
apf::getVectorNodes(elem,nodes);
// subdivide the edge's nodes
crv::subdivideBezierEdge(o,1./4,nodes,subNodes);
// create the two new edges
apf::Vector3 p;
crv::transferParametricOnEdgeSplit(m,edge,1./4,p);
apf::MeshEntity* v2 = m->createVertex(edgeModel,subNodes[0][o],p);
apf::MeshEntity* vE[2][2] = {{v[0],v2},{v2,v[1]}};
apf::MeshEntity* e[2];
for (int i = 0; i < 2; ++i){
e[i] = m->createEntity(apf::Mesh::EDGE,edgeModel,vE[i]);
for (int j = 1; j < o; ++j)
m->setPoint(e[i],j-1,subNodes[i][j]);
}
// compare the two curves to the original one
apf::Element* elem0 = apf::createElement(m->getCoordinateField(),e[0]);
apf::Element* elem1 = apf::createElement(m->getCoordinateField(),e[1]);
apf::Vector3 pt1, pt2, p1, p2;
for (int i = 0; i <= 100; ++i){
p1[0] = 0.02*i-1.;
p2[0] = 0.005*i-1.;
apf::getVector(elem0,p1,pt1);
apf::getVector(elem,p2,pt2);
PCU_ALWAYS_ASSERT(std::abs((pt2-pt1).getLength()) < 1e-15);
p2[0] = 0.015*i-0.5;
apf::getVector(elem1,p1,pt1);
apf::getVector(elem,p2,pt2);
PCU_ALWAYS_ASSERT(std::abs((pt2-pt1).getLength()) < 1e-15);
}
apf::destroyElement(elem);
apf::destroyElement(elem0);
apf::destroyElement(elem1);
m->destroyNative();
apf::destroyMesh(m);
}
}
/* Create a single triangle, split it, and make sure each triangle
* exactly replicates its part of the old one
*
*/
void testTriSubdivision1()
{
for(int o = 1; o <= 6; ++o){
apf::Mesh2* m = createMesh2D();
crv::BezierCurver bc(m,o,0);
bc.run();
apf::MeshIterator* it = m->begin(2);
apf::MeshEntity* e = m->iterate(it);
m->end(it);
apf::Element* elem = apf::createElement(m->getCoordinateField(),e);
apf::MeshEntity* verts[3],* edges[3];
m->getDownward(e,0,verts);
m->getDownward(e,1,edges);
apf::NewArray<apf::Vector3> nodes;
apf::NewArray<apf::Vector3> subNodes[3];
for (int t = 0; t < 3; ++t)
subNodes[t].allocate((o+1)*(o+2)/2);
apf::getVectorNodes(elem,nodes);
apf::Vector3 splitpt(0,0.5,0.5);
crv::subdivideBezierTriangle(o,splitpt,nodes,subNodes);
apf::MeshEntity* v3 = m->createVertex(m->findModelEntity(2,0),
subNodes[0][2],splitpt);
apf::MeshEntity* newFaces[3],* newEdges[3];
for (int i = 0; i < 3; ++i){
apf::MeshEntity* vE[2] = {v3,verts[i]};
newEdges[i] = m->createEntity(apf::Mesh::EDGE,m->findModelEntity(1,i),
vE);
for (int j = 0; j < o-1; ++j){
m->setPoint(newEdges[i],j,subNodes[i][3+2*(o-1)+j]);
}
}
for (int i = 0; i < 3; ++i){
apf::MeshEntity* eF[3] = {edges[i],newEdges[(i+1) % 3],
newEdges[i]};
newFaces[i] = m->createEntity(apf::Mesh::TRIANGLE,m->findModelEntity(2,0),
eF);
for (int j = 0; j < (o-1)*(o-2)/2; ++j){
m->setPoint(newFaces[i],j,subNodes[i][3+3*(o-1)+j]);
}
}
// compare the three faces to the original one
apf::Element* elems[3] =
{apf::createElement(m->getCoordinateField(),newFaces[0]),
apf::createElement(m->getCoordinateField(),newFaces[1]),
apf::createElement(m->getCoordinateField(),newFaces[2])};
apf::Vector3 p,pOld,pt,ptOld;
for (int j = 0; j <= 10; ++j){
p[1] = 1.*j/10;
for (int i = 0; i <= 10-j; ++i){
p[0] = 1.*i/10;
p[2] = 1.-p[0]-p[1];
// p[1] is the new split point, rescale from new to old
for (int t = 0; t < 3; ++t){
apf::getVector(elems[t],p,pt);
for (int pi = 0; pi < 3; ++pi)
pOld[pi] = splitpt[(pi+2) % 3]*p[1];
pOld[t] += p[0];
pOld[(t+2) % 3] += p[2];
apf::getVector(elem,pOld,ptOld);
PCU_ALWAYS_ASSERT(std::abs((ptOld-pt).getLength()) < 1e-15);
}
}
}
apf::destroyElement(elem);
m->destroy(e);
for(int t = 0; t < 3; ++t)
apf::destroyElement(elems[t]);
m->destroyNative();
apf::destroyMesh(m);
}
}
/* Create a single triangle, split it into 4, and try not to crash
*
*/
void testTriSubdivision4()
{
for(int o = 2; o <= 2; ++o){
apf::Mesh2* m = createMesh2D();
crv::BezierCurver bc(m,o,0);
bc.run();
apf::MeshIterator* it = m->begin(2);
apf::MeshEntity* e = m->iterate(it);
m->end(it);
apf::Element* elem = apf::createElement(m->getCoordinateField(),e);
apf::NewArray<apf::Vector3> nodes;
apf::NewArray<apf::Vector3> subNodes[4];
for (int t = 0; t < 4; ++t)
subNodes[t].allocate((o+1)*(o+2)/2);
apf::getVectorNodes(elem,nodes);
apf::Vector3 splitpt(0,0.5,0.5);
crv::subdivideBezierTriangle(o,nodes,subNodes);
apf::destroyElement(elem);
m->destroyNative();
apf::destroyMesh(m);
}
}
/* Create a single tet, split it, and make sure each tet
* exactly replicates its part of the old one
*
*/
void testTetSubdivision1()
{
gmi_register_null();
for (int order = 1; order <= 4; ++order){
apf::Mesh2* m = createMesh3D();
crv::BezierCurver bc(m,order,0);
bc.run();
apf::MeshIterator* it = m->begin(3);
apf::MeshEntity* tet = m->iterate(it);
m->end(it);
apf::MeshEntity* verts[4],* edges[6],* faces[4];
m->getDownward(tet,0,verts);
m->getDownward(tet,1,edges);
m->getDownward(tet,2,faces);
apf::Element* elem = apf::createElement(m->getCoordinateField(),tet);
apf::NewArray<apf::Vector3> nodes;
apf::NewArray<apf::Vector3> subNodes[4];
for (int t = 0; t < 4; ++t)
subNodes[t].allocate(crv::getNumControlPoints(apf::Mesh::TET,order));
apf::getVectorNodes(elem,nodes);
apf::Vector3 splitpt(0.25,0.35,0.25);
crv::subdivideBezierTet(order,splitpt,nodes,subNodes);
apf::MeshEntity* v4 = m->createVertex(m->findModelEntity(2,0),
subNodes[0][3],splitpt);
apf::MeshEntity* newFaces[6],* newEdges[4],* newTets[4];
for (int i = 0; i < 4; ++i){
apf::MeshEntity* vE[2] = {verts[i],v4};
newEdges[i] = m->createEntity(apf::Mesh::EDGE,m->findModelEntity(1,i),
vE);
for (int j = 0; j < order-1; ++j){
m->setPoint(newEdges[i],j,subNodes[i][4+3*(order-1)+j]);
}
}
int const tet_tri[6][2] =
{{0,1},{0,2},{2,3},{3,1},{1,3},{2,1}};
int nE = (order-1);
int nF = (order-1)*(order-2)/2;
// this compensates for alignment issues
for (int f = 0; f < 6; ++f){
apf::MeshEntity* eF[3] = {edges[f],newEdges[apf::tet_edge_verts[f][1]],
newEdges[apf::tet_edge_verts[f][0]]};
newFaces[f] = m->createEntity(apf::Mesh::TRIANGLE,m->findModelEntity(2,0),
eF);
for (int j = 0; j < nF; ++j){
m->setPoint(newFaces[f],j,subNodes[tet_tri[f][0]][4+6*nE+tet_tri[f][1]*nF+j]);
if(f == 3 && order == 4){
int o[3] = {1,0,2};
m->setPoint(newFaces[f],j,subNodes[tet_tri[f][0]][4+6*nE+tet_tri[f][1]*nF+o[j]]);
}
}
}
apf::MeshEntity* fT0[4] = {faces[0],newFaces[0],newFaces[1],newFaces[2]};
newTets[0] = m->createEntity(apf::Mesh::TET,m->findModelEntity(3,0),fT0);
apf::MeshEntity* fT1[4] = {faces[1],newFaces[0],newFaces[3],newFaces[4]};
newTets[1] = m->createEntity(apf::Mesh::TET,m->findModelEntity(3,0),fT1);
apf::MeshEntity* fT2[4] = {faces[2],newFaces[1],newFaces[4],newFaces[5]};
newTets[2] = m->createEntity(apf::Mesh::TET,m->findModelEntity(3,0),fT2);
apf::MeshEntity* fT3[4] = {faces[3],newFaces[2],newFaces[5],newFaces[3]};
newTets[3] = m->createEntity(apf::Mesh::TET,m->findModelEntity(3,0),fT3);
if(order == 4){
for (int t = 0; t < 4; ++t){
apf::Vector3 pt = (points3D[apf::tet_tri_verts[t][0]]
+ points3D[apf::tet_tri_verts[t][1]]
+ points3D[apf::tet_tri_verts[t][2]] + splitpt)*0.25;
m->setPoint(newTets[t],0,pt);
}
}
apf::Element* elems[4] =
{apf::createElement(m->getCoordinateField(),newTets[0]),
apf::createElement(m->getCoordinateField(),newTets[1]),
apf::createElement(m->getCoordinateField(),newTets[2]),
apf::createElement(m->getCoordinateField(),newTets[3])};
double totalVolume = apf::measure((apf::MeshElement*)elem);
double volumeSum = apf::measure((apf::MeshElement*)elems[0]) +
apf::measure((apf::MeshElement*)elems[1]) +
apf::measure((apf::MeshElement*)elems[2]) +
apf::measure((apf::MeshElement*)elems[3]);
PCU_ALWAYS_ASSERT(fabs(totalVolume - volumeSum) < 1e-15);
apf::destroyElement(elem);
m->destroy(tet);
for(int t = 0; t < 4; ++t)
apf::destroyElement(elems[t]);
m->destroyNative();
apf::destroyMesh(m);
}
}
int main(int argc, char** argv)
{
MPI_Init(&argc,&argv);
PCU_Comm_Init();
testEdgeSubdivision();
testTriSubdivision1();
testTriSubdivision4();
testTetSubdivision1();
PCU_Comm_Free();
MPI_Finalize();
}
| 28.817073 | 91 | 0.59543 | cwsmith |
00c0808d175ce4b836d0597f66c3e501b6964ac2 | 5,763 | cpp | C++ | tests/Dynamic/GainColoredCompressorFilter.cpp | apohl79/AudioTK | 05ac241b0bc6a8f841d93257b4d81e5961b1f627 | [
"BSD-3-Clause"
] | 10 | 2018-05-17T15:29:05.000Z | 2021-12-19T22:26:08.000Z | tests/Dynamic/GainColoredCompressorFilter.cpp | apohl79/AudioTK | 05ac241b0bc6a8f841d93257b4d81e5961b1f627 | [
"BSD-3-Clause"
] | null | null | null | tests/Dynamic/GainColoredCompressorFilter.cpp | apohl79/AudioTK | 05ac241b0bc6a8f841d93257b4d81e5961b1f627 | [
"BSD-3-Clause"
] | 2 | 2020-04-21T13:43:57.000Z | 2020-04-28T19:10:14.000Z | /**
* \ file GainColoredCompressorFilter.cpp
*/
#include <ATK/Dynamic/GainColoredCompressorFilter.h>
#include <ATK/Core/InPointerFilter.h>
#include <ATK/Core/OutPointerFilter.h>
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_NO_MAIN
#include <boost/test/unit_test.hpp>
#include <boost/math/constants/constants.hpp>
#include <boost/scoped_array.hpp>
#define PROCESSSIZE (64)
BOOST_AUTO_TEST_CASE( GainColoredCompressorFilter_const_1_test )
{
boost::scoped_array<float> data(new float[PROCESSSIZE]);
for(int64_t i = 0; i < PROCESSSIZE; ++i)
{
data[i] = 1;
}
ATK::InPointerFilter<float> generator(data.get(), 1, PROCESSSIZE, false);
generator.set_output_sampling_rate(48000);
boost::scoped_array<float> outdata(new float[PROCESSSIZE]);
ATK::GainColoredCompressorFilter<float> filter(1);
filter.set_input_sampling_rate(48000);
filter.set_input_port(0, &generator, 0);
filter.set_threshold(10);
ATK::OutPointerFilter<float> output(outdata.get(), 1, PROCESSSIZE, false);
output.set_input_sampling_rate(48000);
output.set_input_port(0, &filter, 0);
output.process(PROCESSSIZE);
for(int64_t i = 0; i < PROCESSSIZE; ++i)
{
BOOST_REQUIRE_CLOSE(1, outdata[i], 0.1);
}
}
BOOST_AUTO_TEST_CASE( GainColoredCompressorFilter_const_0_test )
{
boost::scoped_array<float> data(new float[PROCESSSIZE]);
for(int64_t i = 0; i < PROCESSSIZE; ++i)
{
data[i] = 0;
}
ATK::InPointerFilter<float> generator(data.get(), 1, PROCESSSIZE, false);
generator.set_output_sampling_rate(48000);
boost::scoped_array<float> outdata(new float[PROCESSSIZE]);
ATK::GainColoredCompressorFilter<float> filter(1);
filter.set_input_sampling_rate(48000);
filter.set_input_port(0, &generator, 0);
ATK::OutPointerFilter<float> output(outdata.get(), 1, PROCESSSIZE, false);
output.set_input_sampling_rate(48000);
output.set_input_port(0, &filter, 0);
output.process(PROCESSSIZE);
for(int64_t i = 0; i < PROCESSSIZE; ++i)
{
BOOST_REQUIRE_CLOSE(1, outdata[i], 0.1); // if input is zero, we still need a gain of 1 to have a progression of 1 for values < threshold
}
}
BOOST_AUTO_TEST_CASE( GainColoredCompressorFilter_const_1_threshold_05_ratio_2_test )
{
boost::scoped_array<float> data(new float[PROCESSSIZE]);
for(int64_t i = 0; i < PROCESSSIZE; ++i)
{
data[i] = 1;
}
ATK::InPointerFilter<float> generator(data.get(), 1, PROCESSSIZE, false);
generator.set_output_sampling_rate(48000);
boost::scoped_array<float> outdata(new float[PROCESSSIZE]);
ATK::GainColoredCompressorFilter<float> filter(1);
filter.set_input_sampling_rate(48000);
filter.set_input_port(0, &generator, 0);
filter.set_threshold(0.5);
filter.set_ratio(2);
filter.set_softness(1);
ATK::OutPointerFilter<float> output(outdata.get(), 1, PROCESSSIZE, false);
output.set_input_sampling_rate(48000);
output.set_input_port(0, &filter, 0);
output.process(PROCESSSIZE);
for(int64_t i = 0; i < PROCESSSIZE; ++i)
{
BOOST_REQUIRE_CLOSE(0.836990654, outdata[i], 0.1);
}
}
BOOST_AUTO_TEST_CASE( GainColoredCompressorFilter_const_1_threshold_05_ratio_4_test )
{
boost::scoped_array<float> data(new float[PROCESSSIZE]);
for(int64_t i = 0; i < PROCESSSIZE; ++i)
{
data[i] = 1;
}
ATK::InPointerFilter<float> generator(data.get(), 1, PROCESSSIZE, false);
generator.set_output_sampling_rate(48000);
boost::scoped_array<float> outdata(new float[PROCESSSIZE]);
ATK::GainColoredCompressorFilter<float> filter(1);
filter.set_input_sampling_rate(48000);
filter.set_input_port(0, &generator, 0);
filter.set_threshold(0.5);
filter.set_ratio(4);
filter.set_softness(1);
ATK::OutPointerFilter<float> output(outdata.get(), 1, PROCESSSIZE, false);
output.set_input_sampling_rate(48000);
output.set_input_port(0, &filter, 0);
output.process(PROCESSSIZE);
for(int64_t i = 0; i < PROCESSSIZE; ++i)
{
BOOST_REQUIRE_CLOSE(0.765739262, outdata[i], 0.1);
}
}
BOOST_AUTO_TEST_CASE( GainColoredCompressorFilter_always_more_1_test )
{
boost::scoped_array<float> data(new float[PROCESSSIZE]);
for(int64_t i = 0; i < PROCESSSIZE; ++i)
{
data[i] = i/1024.;
}
ATK::InPointerFilter<float> generator(data.get(), 1, PROCESSSIZE, false);
generator.set_output_sampling_rate(48000);
boost::scoped_array<float> outdata(new float[PROCESSSIZE]);
ATK::GainColoredCompressorFilter<float> filter(1);
filter.set_input_sampling_rate(48000);
filter.set_input_port(0, &generator, 0);
filter.set_threshold(1);
filter.set_quality(.1);
filter.set_color(.1);
ATK::OutPointerFilter<float> output(outdata.get(), 1, PROCESSSIZE, false);
output.set_input_sampling_rate(48000);
output.set_input_port(0, &filter, 0);
output.process(PROCESSSIZE);
for(int64_t i = 0; i < PROCESSSIZE; ++i)
{
BOOST_REQUIRE_GE(outdata[i], 1);
}
}
BOOST_AUTO_TEST_CASE( GainColoredCompressorFilter_always_less_1_test )
{
boost::scoped_array<float> data(new float[PROCESSSIZE]);
for(int64_t i = 0; i < PROCESSSIZE; ++i)
{
data[i] = i/1024.;
}
ATK::InPointerFilter<float> generator(data.get(), 1, PROCESSSIZE, false);
generator.set_output_sampling_rate(48000);
boost::scoped_array<float> outdata(new float[PROCESSSIZE]);
ATK::GainColoredCompressorFilter<float> filter(1);
filter.set_input_sampling_rate(48000);
filter.set_input_port(0, &generator, 0);
filter.set_threshold(1);
filter.set_quality(.1);
filter.set_color(-.1);
ATK::OutPointerFilter<float> output(outdata.get(), 1, PROCESSSIZE, false);
output.set_input_sampling_rate(48000);
output.set_input_port(0, &filter, 0);
output.process(PROCESSSIZE);
for(int64_t i = 0; i < PROCESSSIZE; ++i)
{
BOOST_REQUIRE_LE(outdata[i], 1);
}
}
| 28.112195 | 141 | 0.725317 | apohl79 |
00c360bb1f1401d970e227967685e6fa65092e5f | 6,023 | cc | C++ | src/main.cc | FlyAlCode/FlightSim | 800b46ebf87449408cc908c59cb5e18bea5863c3 | [
"Apache-2.0"
] | null | null | null | src/main.cc | FlyAlCode/FlightSim | 800b46ebf87449408cc908c59cb5e18bea5863c3 | [
"Apache-2.0"
] | null | null | null | src/main.cc | FlyAlCode/FlightSim | 800b46ebf87449408cc908c59cb5e18bea5863c3 | [
"Apache-2.0"
] | null | null | null | #include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <fstream>
#include <string>
#include <memory>
#include "camera.h"
#include "ground.h"
#include <stdio.h>
#include <stdlib.h>
double const PI = 3.1415926;
void DrawMask(const cv::Mat &src, const cv::Mat &mask, cv::Mat &result){
CV_Assert(mask.rows==src.rows && mask.cols == mask.rows);
if(mask.channels()!=1)
cv::cvtColor(mask, mask, CV_RGB2GRAY);
src.copyTo(result);
for(int i=0; i<mask.rows; i++){
for(int j=0; j<mask.cols; j++){
if(mask.at<uchar>(i,j)!=0)
result.at<cv::Vec3b>(i,j) = cv::Vec3b(0,255,0);
}
}
}
int main(int argc, char *argv[]){
if(argc<22){
std::cout<<"Usage: flight_sim [acc_error_model_file] [gro_error_model_file][sat_file_name] [road_file_name] \
\n [save_path] [angle_x angle_y angle_z] [position_x position_y position_z] [v_x v_y v_z] \
[a_mean_x a_mean_y a_mean_z] [w_mean_x w_mean_y w_mean_z] [max_image_num]"<<std::endl;
exit(-1);
}
std::shared_ptr<flight_sim::Ground> ground (new flight_sim::Ground );
if(!ground->Init(argv[3],argv[4], 1.2)){
std::cout<<"Fail to load ground file"<<std::endl;
return -1;
}
ground->Print();
// init camera
flight_sim::Camera::IMUParam imu_params;
imu_params.acc_error_model_file_ = std::string(argv[1]);
imu_params.gro_error_model_file_ = std::string(argv[2]);
for(int i=0; i<3; i++){
// imu_params.a_mean_[i] = 0;
imu_params.a_std_[i] = 0.5;
// imu_params.w_mean_[i] = 0;
imu_params.w_std_[i] = 0.0;
}
imu_params.a_mean_[0] = atof(argv[15]);
imu_params.a_mean_[1] = atof(argv[16]);
imu_params.a_mean_[2] = atof(argv[17]);
imu_params.w_mean_[0] = atof(argv[18]);
imu_params.w_mean_[1] = atof(argv[19]);
imu_params.w_mean_[2] = atof(argv[20]);
for(int i=0; i<3; ++i){
std::cout<<imu_params.a_mean_[i]<<" ";
}
std::cout<<std::endl;
for(int i=0; i<3; ++i){
std::cout<<imu_params.w_mean_[i]<<" ";
}
std::cout<<std::endl;
flight_sim::Camera camera;
double K_data[9] = {450, 0, 400, 0, 450, 400, 0, 0, 1};
cv::Mat K(3, 3, CV_64F, K_data);
camera.Init(imu_params,K, ground);
// set initial pose of the camera
double init_pose[9]/* = {0,20/180*PI,0,355000,4659000,1000,-200,300,0} */; // angle, position, v
// get initial pose from params
{
init_pose[0] = atof(argv[6])/* /180*PI */;
init_pose[1] = atof(argv[7])/* /180*PI */;
init_pose[2] = atof(argv[8])/* /180*PI */;
init_pose[3] = atof(argv[9]);
init_pose[4] = atof(argv[10]);
init_pose[5] = atof(argv[11]);
init_pose[6] = atof(argv[12]);
init_pose[7] = atof(argv[13]);
init_pose[8] = atof(argv[14]);
}
// double init_pose[9];
// std::cout<<"Please input initial_angle_x:"<<std::endl;
// std::cin>>init_pose[0];
// std::cout<<"Please input initial_angle_y:"<<std::endl;
// std::cin>>init_pose[1];
// std::cout<<"Please input initial_angle_z:"<<std::endl;
// std::cin>>init_pose[2];
// std::cout<<"Please input initial_position_x:"<<std::endl;
// std::cin>>init_pose[3];
// std::cout<<"Please input initial_position_y:"<<std::endl;
// std::cin>>init_pose[4];
// std::cout<<"Please input initial_position_z:"<<std::endl;
// std::cin>>init_pose[5];
// std::cout<<"Please input initial_v_x:"<<std::endl;
// std::cin>>init_pose[6];
// std::cout<<"Please input initial_v_y:"<<std::endl;
// std::cin>>init_pose[7];
// std::cout<<"Please input initial_v_z:"<<std::endl;
// std::cin>>init_pose[8];
camera.SetInitPose(init_pose);
std::cout<<"************ Start fly!!! *************"<<std::endl;
cv::Mat current_sat_img, current_road_img;
// cv::namedWindow("sat");
// cv::namedWindow("road");
int img_count = 0;
std::ofstream fout(std::string(argv[5]) + "H_c2g.txt");
std::ofstream fout_R(std::string(argv[5]) + "R.txt");
std::ofstream fout_T(std::string(argv[5]) + "t.txt");
fout.precision(7);
fout_R.precision(7);
fout_T.precision(7);
int max_img_num = atoi(argv[21]);
while(cv::waitKey(1)!='q' && img_count<max_img_num){
camera.UpdatePose();
if(!camera.GetCurrentImage(current_sat_img, current_road_img))
break;
// cv::imshow("sat", current_sat_img);
// cv::imshow("road", current_road_img);
cv::Mat add_img;
DrawMask(current_sat_img, current_road_img, add_img);
cv::imshow("add img", add_img);
std::cout<<"img number: "<<img_count<<std::endl;
// write image
char tmp[20];
sprintf(tmp, "%.3d", img_count);
std::string sat_save_name = std::string(argv[5]) + "sat/" + tmp + ".jpg";
std::string road_save_name = std::string(argv[5]) + "road/" + tmp + ".png";
// std::cout<<road_save_name<<std::endl;
cv::imwrite(sat_save_name, current_sat_img);
cv::imwrite(road_save_name, current_road_img);
// print pose
cv::Mat H_c2g = camera.get_H_c_2_g();
for(int i=0; i<3; i++){
for(int j=0; j<3; j++){
fout<<H_c2g.at<double>(i,j)<<" ";
}
}
fout<<std::endl;
cv::Mat R_tmp = camera.get_R();
for(int i=0; i<3; i++){
for(int j=0; j<3; j++){
fout_R<<R_tmp.at<double>(i,j)<<" ";
}
}
fout_R<<std::endl;
cv::Mat t_tmp = camera.get_t();
// t_tmp 为相机中心在世界坐标系下的坐标
t_tmp = -R_tmp.t() * t_tmp;
// std::cout<<t_tmp.t()<<std::endl;
for(int i=0; i<3; i++){
fout_T<<t_tmp.at<double>(i,0)<<" ";
}
fout_T<<std::endl;
++img_count;
}
fout.close();
fout_R.close();
fout_T.close();
return 0;
}
| 32.912568 | 117 | 0.560518 | FlyAlCode |
00c39216be647d3b43936243cec4a03200425647 | 565 | cpp | C++ | src/mango/core/wire/request/SnippetTextRequest.cpp | vero-zhang/mango | 0cc8d34a8b729151953df41a7e9cd26324345d44 | [
"MIT"
] | null | null | null | src/mango/core/wire/request/SnippetTextRequest.cpp | vero-zhang/mango | 0cc8d34a8b729151953df41a7e9cd26324345d44 | [
"MIT"
] | null | null | null | src/mango/core/wire/request/SnippetTextRequest.cpp | vero-zhang/mango | 0cc8d34a8b729151953df41a7e9cd26324345d44 | [
"MIT"
] | null | null | null | #include <mango/core/runtime/Runner.h>
#include "mango/core/wire/request/SnippetTextRequest.h"
#include "mango/core/wire/response/SnippetTextResponse.h"
MANGO_NS_BEGIN
SnippetTextRequest::SnippetTextRequest
( const std::string& keyword
, const std::string& name
, const std::string& multilineArg)
: keyword(keyword)
, name(name)
, multilineArg(multilineArg)
{
}
WireResponse* SnippetTextRequest::run(Runner& runner) const
{
return new SnippetTextResponse
(runner.snippetText(keyword, name, multilineArg));
}
MANGO_NS_END
| 23.541667 | 62 | 0.734513 | vero-zhang |
00c4ed79dcdef2a8be7c6512041002de0f26323e | 5,857 | cpp | C++ | 2022_CONTROL WORK 1/Project1/Fraction.cpp | Leonchik1945/spbu_homework_2021-2022 | 84139157b40c5864531e8275c97eaadef9619378 | [
"Apache-2.0"
] | null | null | null | 2022_CONTROL WORK 1/Project1/Fraction.cpp | Leonchik1945/spbu_homework_2021-2022 | 84139157b40c5864531e8275c97eaadef9619378 | [
"Apache-2.0"
] | null | null | null | 2022_CONTROL WORK 1/Project1/Fraction.cpp | Leonchik1945/spbu_homework_2021-2022 | 84139157b40c5864531e8275c97eaadef9619378 | [
"Apache-2.0"
] | null | null | null | #include "Fraction.h"
long long Nod(long long a, long long b)
{
if (b == 0)
{
return (a);
}
else
{
return (Nod(b, a % b));
}
}
Fraction::Fraction(long long numerator, long long denominator) : numerator(numerator), denominator(denominator) {}
Fraction::Fraction(const Fraction& f) : numerator(f.numerator), denominator(f.denominator) {}
Fraction::~Fraction()
{
this->numerator = 0;
this->denominator = 0;
}
int Fraction::getnumerator()
{
return this->numerator;
}
void Fraction::setnumerator(int numerator)
{
this->numerator = numerator;
}
int Fraction::getdenominator()
{
return this->denominator;
}
void Fraction::setdenominatorr(int denominator)
{
this->denominator = denominator;
}
void Fraction::set(int numerator, int denominator)
{
this->numerator = numerator;
this->denominator = denominator;
}
void Fraction::operator=(const Fraction& f)
{
this->numerator = f.numerator;
this->denominator = f.denominator;
}
long long Fraction::Nok()
{
return ((this->numerator * this->denominator) / Nod(this->numerator, this->denominator));
}
Fraction Fraction::reverse()
{
return Fraction((this->numerator - (this->numerator - 1)) * this->denominator, (this->denominator - (this->denominator - 1)) * this->numerator);
}
Fraction Fraction::abs(Fraction& f)
{
if (f.numerator == 0)
{
return 0;
}
else if (f.numerator > 0)
{
if (f.denominator < 0)
{
return Fraction(f.numerator, f.denominator * (-1));
}
else if (f.denominator > 0)
{
return Fraction(f.numerator, f.denominator);
}
else if (f.denominator == 0)
{
return false;
}
}
else if (f.numerator < 0)
{
if (f.denominator < 0)
{
return Fraction(f.numerator * (-1), f.denominator * (-1));
}
else if (f.denominator > 0)
{
return Fraction(f.numerator * (-1), f.denominator);
}
else if (f.denominator == 0)
{
return false;
}
}
}
bool Fraction::operator==(Fraction& f)
{
if ((this->Nok() / Nod(this->numerator, this->denominator)) == (f.Nok() / Nod(f.numerator, f.denominator)))
{
return true;
}
else
{
return false;
}
}
bool Fraction::operator<(Fraction& f)
{
if ((this->numerator * ((this->denominator * f.denominator) / Nod(this->denominator, f.denominator)) / this->denominator) < (f.numerator * ((this->denominator * f.denominator) / Nod(this->denominator, f.denominator)) / f.denominator))
{
return true;
}
else
{
return false;
}
}
bool Fraction::operator<=(Fraction& f)
{
if ((this->numerator * ((this->denominator * f.denominator) / Nod(this->denominator, f.denominator)) / this->denominator) <= (f.numerator * ((this->denominator * f.denominator) / Nod(this->denominator, f.denominator)) / f.denominator))
{
return true;
}
else
{
return false;
}
}
bool Fraction::operator>(Fraction& f)
{
if ((this->numerator * ((this->denominator * f.denominator) / Nod(this->denominator, f.denominator)) / this->denominator) > (f.numerator * ((this->denominator * f.denominator) / Nod(this->denominator, f.denominator)) / f.denominator))
{
return true;
}
else
{
return false;
}
}
bool Fraction::operator>=(Fraction& f)
{
if ((this->numerator * ((this->denominator * f.denominator) / Nod(this->denominator, f.denominator)) / this->denominator) >= (f.numerator * ((this->denominator * f.denominator) / Nod(this->denominator, f.denominator)) / f.denominator))
{
return true;
}
else
{
return false;
}
}
Fraction operator+(const double t, const Fraction& f)
{
return Fraction(f.numerator + (t * f.denominator), f.denominator);
}
Fraction operator+(const Fraction& f, const double t)
{
return Fraction(f.numerator + (t * f.denominator), f.denominator);
}
Fraction operator+(const Fraction& f1, const Fraction& f2)
{
return Fraction((f1.numerator * f2.denominator) + (f2.numerator * f1.denominator), f1.denominator * f2.denominator);
}
Fraction operator-(const double t, const Fraction& f)
{
return Fraction((t * f.denominator) - f.numerator, f.denominator);
}
Fraction operator-(const Fraction& f, const double t)
{
return Fraction((t * f.denominator) - f.numerator, f.denominator);
}
Fraction operator-(const Fraction& f1, const Fraction& f2)
{
return Fraction((f1.numerator * f2.denominator) - (f2.numerator * f1.denominator), f1.denominator * f2.denominator);
}
Fraction operator*(const double t, const Fraction& f)
{
return Fraction(f.numerator * t, f.denominator);
}
Fraction operator*(const Fraction& f, const double t)
{
return Fraction(f.numerator * t, f.denominator);
}
Fraction operator*(const Fraction& f1, const Fraction& f2)
{
return Fraction(f1.numerator * f2.numerator, f1.denominator * f2.denominator);
}
Fraction operator/(const double t, const Fraction& f)
{
return Fraction(f.denominator * t, f.numerator);
}
Fraction operator/(const Fraction& f, const double t)
{
return Fraction(f.denominator * t, f.numerator);
}
Fraction operator/(const Fraction& f1, const Fraction& f2)
{
return Fraction(f1.numerator * f2.denominator, f1.denominator * f2.numerator);
}
std::ostream& operator<<(std::ostream& stream, const Fraction& f)
{
if (f.numerator == 0)
{
stream << "0";
}
else
{
if (f.numerator > 0)
{
if (f.denominator == 1)
{
stream << f.numerator;
}
else if (f.denominator < 0)
{
stream << "-" << f.numerator << "/" << f.denominator * (-1);
}
else if (f.denominator > 0)
{
stream << f.numerator << "/" << f.denominator;
}
else
{
stream << "The denominator is zero!"
}
}
else
{
if (f.denominator == 1)
{
stream << f.numerator;
}
else if (f.denominator < 0)
{
stream << f.numerator * (-1) << "/" << f.denominator * (-1);
}
else if (f.denominator > 0)
{
stream << f.numerator << "/" << f.denominator;
}
else
{
stream << "The denominator is zero!"
}
}
}
return stream;
// TODO: insert return statement here
}
| 21.221014 | 236 | 0.656138 | Leonchik1945 |
00c739e3f434cbe007a216b58205ac579c72c9bf | 4,872 | hh | C++ | scipy/special/ellint_carlson_cpp_lite/_rg.hh | lorentzenchr/scipy | 393a05ee927883ad6316b7092c851afea8f16816 | [
"BSD-3-Clause"
] | 9,095 | 2015-01-02T18:24:23.000Z | 2022-03-31T20:35:31.000Z | scipy/special/ellint_carlson_cpp_lite/_rg.hh | lorentzenchr/scipy | 393a05ee927883ad6316b7092c851afea8f16816 | [
"BSD-3-Clause"
] | 11,500 | 2015-01-01T01:15:30.000Z | 2022-03-31T23:07:35.000Z | scipy/special/ellint_carlson_cpp_lite/_rg.hh | lorentzenchr/scipy | 393a05ee927883ad6316b7092c851afea8f16816 | [
"BSD-3-Clause"
] | 5,838 | 2015-01-05T11:56:42.000Z | 2022-03-31T23:21:19.000Z | #ifndef ELLINT_RG_GENERIC_GUARD
#define ELLINT_RG_GENERIC_GUARD
#include <algorithm>
#include <iterator>
#include <complex>
#include "ellint_typing.hh"
#include "ellint_argcheck.hh"
#include "ellint_common.hh"
#include "ellint_carlson.hh"
#define CHECK_STATUS_OR_FAIL() \
do { \
if ( status_tmp != ExitStatus::success ) \
{ \
status = status_tmp; \
} \
if ( is_horrible(status) ) \
{ \
res = typing::nan<T>(); \
return status; \
} \
} while ( 0 )
/* References
* [1] B. C. Carlson, "Numerical computation of real or complex elliptic
* integrals," Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995.
* https://arxiv.org/abs/math/9409227
* https://doi.org/10.1007/BF02198293
* [2] B. C. Carlson, ed., Chapter 19 in "Digital Library of Mathematical
* Functions," NIST, US Dept. of Commerce.
* https://dlmf.nist.gov/19.16.E1
* https://dlmf.nist.gov/19.20.ii
*/
/* Forward declaration */
/* See the file _rf.hh for the definition of agm_update */
namespace ellint_carlson {
template<typename T>
inline void agm_update(T& x, T& y);
}
namespace ellint_carlson {
namespace arithmetic { namespace aux {
template<typename T>
static inline typing::real_only<T, void>
rg_dot2_acc(const T& fac, const T& term, T& acc, T& cor)
{
fdot2_acc(fac, term, acc, cor);
}
template<typename CT>
static inline typing::cplx_only<CT, void>
rg_dot2_acc(const typing::decplx_t<CT>& fac, const CT& term, CT& acc, CT& cor)
{
typedef typing::decplx_t<CT> RT;
RT ar, cr, ai, ci;
CT p, q;
eft_prod(fac, term.real(), ar, cr);
eft_prod(fac, term.imag(), ai, ci);
eft_sum(acc, CT{ar, ai}, p, q);
acc = p;
cor += q + CT{cr, ci};
}
}} /* namespace ellint_carlson::arithmetic::aux */
template<typename T>
static ExitStatus
rg0(const T& x, const T& y, const double& rerr, T& res)
{
typedef typing::decplx_t<T> RT;
ExitStatus status = ExitStatus::success;
double rsq = 2.0 * std::sqrt(rerr);
RT fac(0.25);
T xm = std::sqrt(x);
T ym = std::sqrt(y);
T dm = (xm + ym) * (RT)0.5;
T sum = -dm * dm;
T cor(0.0);
dm = xm - ym;
unsigned int m = 0;
while ( std::abs(dm) >= rsq * std::fmin(std::abs(xm), std::abs(ym)) )
{
if ( m > config::max_iter )
{
status = ExitStatus::n_iter;
break;
}
agm_update(xm, ym);
/* Ref[1], Eq. 2.39 or Eq. (46) in the arXiv preprint */
fac *= (RT)2.0;
dm = xm - ym;
arithmetic::aux::rg_dot2_acc(fac, dm * dm, sum, cor);
++m;
}
res = (RT)(constants::pi) / (xm + ym);
res *= -(RT)0.5 * (sum + cor);
return status;
}
template<typename T>
ExitStatus
rg(const T& x, const T& y, const T& z, const double& rerr, T& res)
{
typedef typing::decplx_t<T> RT;
ExitStatus status = ExitStatus::success;
#ifndef ELLINT_NO_VALIDATE_RELATIVE_ERROR_BOUND
if ( argcheck::invalid_rerr(rerr, 1.0e-4) )
{
res = typing::nan<T>();
return ExitStatus::bad_rerr;
}
#endif
T cct[3] = {x, y, z};
std::sort(std::begin(cct), std::end(cct), util::abscmp<T>);
if ( (argcheck::isinf(cct[0]) || argcheck::isinf(cct[1]) ||
argcheck::isinf(cct[2])) &&
argcheck::ph_good(cct[0]) && argcheck::ph_good(cct[1]) &&
argcheck::ph_good(cct[2]) )
{
res = typing::huge<T>();
return ExitStatus::singular;
}
if ( argcheck::too_small(cct[0]) )
{
if ( argcheck::too_small(cct[1]) )
{
/* Special case -- also covers the case of z ~ zero. */
res = std::sqrt(cct[2]) * (RT)0.5;
return status;
} else {
/* Special case -- use the AGM algorithm. */
status = rg0(cct[1], cct[2], rerr, res);
return status;
}
}
/* Ref[2], Eq. 19.21.11 (second identity) <https://dlmf.nist.gov/19.21.E11>
* i.e. 6R_G() = sum of [ x * (y + z) * R_D() ] over cyclic permutations of
* (x, y, z).
* This cyclic form is manifestly symmetric and is preferred over
* Eq. 19.21.10 ibid.
* Here we put the three R_D terms in the buffer cct2, and the
* x * (y + z) = dot({x, x}, {y, z}) terms in cct1. */
T cct1[3];
T cct2[3];
ExitStatus status_tmp;
status_tmp = rd(y, z, x, rerr, cct2[0]);
CHECK_STATUS_OR_FAIL();
status_tmp = rd(z, x, y, rerr, cct2[1]);
CHECK_STATUS_OR_FAIL();
status_tmp = rd(x, y, z, rerr, cct2[2]);
CHECK_STATUS_OR_FAIL();
/* Fill the cct1 buffer via the intermediate buffers tm1, tm2
* that are dotted together (using the compensation algorithm). */
T tm1[2] = {x, x};
T tm2[2] = {y, z};
cct1[0] = arithmetic::dot2(tm1, tm2);
tm1[0] = tm1[1] = y;
tm2[0] = x;
cct1[1] = arithmetic::dot2(tm1, tm2);
tm1[0] = tm1[1] = z;
tm2[1] = y;
cct1[2] = arithmetic::dot2(tm1, tm2);
res = arithmetic::dot2(cct1, cct2) / (RT)6.0;
return status;
}
} /* namespace ellint_carlson */
#endif /* ELLINT_RG_GENERIC_GUARD */
| 24.730964 | 79 | 0.59688 | lorentzenchr |
00c8fca2829018f992225203c6cb298cfdadfb92 | 6,943 | hpp | C++ | libraries/wasm/wasm_context.hpp | chenxinhua2018/nchain | 9c694d91dc48fc548b88a0016497c34c9a1cbaaa | [
"MIT"
] | 1 | 2020-10-22T23:03:50.000Z | 2020-10-22T23:03:50.000Z | src/vm/wasm/wasm_context.hpp | linnbenton/WaykiChain | 91dc0aa5b28b63f00ea71c57f065e1b4ad4b124a | [
"MIT"
] | null | null | null | src/vm/wasm/wasm_context.hpp | linnbenton/WaykiChain | 91dc0aa5b28b63f00ea71c57f065e1b4ad4b124a | [
"MIT"
] | null | null | null | #pragma once
#include <stdint.h>
#include <string>
#include <vector>
#include <queue>
#include <map>
#include <chrono>
#include "tx/universaltx.h"
#include "wasm/types/inline_transaction.hpp"
#include "wasm/wasm_interface.hpp"
#include "wasm/datastream.hpp"
#include "wasm/wasm_trace.hpp"
#include "eosio/vm/allocator.hpp"
#include "persistence/cachewrapper.h"
#include "entities/receipt.h"
#include "wasm/exception/exceptions.hpp"
using namespace std;
using namespace wasm;
namespace wasm {
class wasm_context : public wasm_context_interface {
public:
wasm_context(CUniversalTx &ctrl, inline_transaction &t, CCacheWrapper &cw,
vector <CReceipt> &receipts_in, vector <transaction_log>& logs, bool mining, uint32_t depth = 0)
: trx_cord(ctrl.txCord), trx(t), control_trx(ctrl), database(cw), receipts(receipts_in), trx_logs(logs), recurse_depth(depth) {
reset_console();
};
~wasm_context() {
wasm_alloc.free();
};
public:
void initialize();
void execute(inline_transaction_trace &trace);
void execute_one(inline_transaction_trace &trace);
bool has_permission_from_inline_transaction(const permission &p);
bool get_code(const uint64_t& contract, std::vector <uint8_t> &code, uint256 &hash);
uint64_t get_runcost();
void check_authorization(const inline_transaction& t);
//fixme:V4
void call_one(inline_transaction_trace &trace);
int64_t call_one_with_return(inline_transaction_trace &trace);
// Console methods:
public:
void reset_console();
std::ostringstream& get_console_stream() { return _pending_console_output; }
const std::ostringstream& get_console_stream() const { return _pending_console_output; }
//virtual
public:
void execute_inline (const inline_transaction& t);
void notify_recipient (const uint64_t& recipient );
bool has_recipient (const uint64_t& account ) const;
uint64_t receiver() { return _receiver; }
uint64_t contract() { return trx.contract; }
uint64_t action() { return trx.action; }
const char* get_action_data() { return trx.data.data(); }
uint32_t get_action_data_size() { return trx.data.size(); }
bool is_account (const uint64_t& account) const;
void require_auth (const uint64_t& account) const;
void require_auth2(const uint64_t& account, const uint64_t& permission) const {}
bool has_authorization(const uint64_t& account) const;
uint64_t pending_block_time() { return control_trx.pending_block_time; }
TxID get_txid() { return control_trx.GetHash(); }
uint64_t get_maintainer(const uint64_t& contract);
void exit () { wasmif.exit(); }
bool get_system_asset_price(uint64_t base, uint64_t quote, std::vector<char>& price);
bool set_data( const uint64_t& contract, const string& k, const string& v ) {
CUniversalContractStore contractStore;
CHAIN_ASSERT( database.contractCache.GetContract(CRegID(contract), contractStore),
contract_exception,
"contract '%s' does not exist",
wasm::regid(contract).to_string())
return database.contractCache.SetContractData(CRegID(contract), k, v);
}
bool get_data( const uint64_t& contract, const string& k, string &v ) {
CUniversalContractStore contractStore;
CHAIN_ASSERT( database.contractCache.GetContract(CRegID(contract), contractStore),
contract_exception,
"contract '%s' does not exist",
wasm::regid(contract).to_string())
return database.contractCache.GetContractData(CRegID(contract), k, v);
}
bool erase_data( const uint64_t& contract, const string& k ) {
CUniversalContractStore contractStore;
CHAIN_ASSERT( database.contractCache.GetContract(CRegID(contract), contractStore),
contract_exception,
"contract '%s' does not exist",
wasm::regid(contract).to_string())
return database.contractCache.EraseContractData(CRegID(contract), k);
}
std::vector<uint64_t> get_active_producers();
bool contracts_console() {
return SysCfg().GetBoolArg("-contracts_console", false) &&
control_trx.context_type == TxExecuteContextType::VALIDATE_MEMPOOL;
}
void console_append(const string& val) {
_pending_console_output << val;
}
vm::wasm_allocator* get_wasm_allocator() { return &wasm_alloc; }
bool is_memory_in_wasm_allocator ( const uint64_t& p ) {
return wasm_alloc.is_in_range(reinterpret_cast<const char*>(p));
}
std::chrono::milliseconds get_max_transaction_duration() { return control_trx.get_max_transaction_duration(); }
void update_storage_usage( const uint64_t& account, const int64_t& size_in_bytes);
void pause_billing_timer () { control_trx.pause_billing_timer(); };
void resume_billing_timer() { control_trx.resume_billing_timer(); };
void emit_result(const string_view &name, const string_view &type, const string_view &value) override {
CHAIN_ASSERT( false, contract_exception, "%s() only used for rpc", __func__)
}
int64_t call_with_return(inline_transaction& t);
uint64_t call(inline_transaction &inline_trx);//return with size
void set_return(void *data, uint32_t data_len);
std::vector<uint8_t> get_return();
void append_log(uint64_t payer, uint64_t receiver, const string& topic, const string& data);
public:
CTxCord& trx_cord;
inline_transaction& trx;
CUniversalTx& control_trx;
CCacheWrapper& database;
vector<CReceipt>& receipts;
vector<transaction_log>& trx_logs;
uint32_t recurse_depth;
vector<uint64_t> notified;
vector<inline_transaction> inline_transactions;
wasm::wasm_interface wasmif;
vm::wasm_allocator wasm_alloc;
uint64_t _receiver;
vector<vector<uint8_t>> return_values;
vector<uint8_t> the_last_return_buffer;
//inline_transaction_trace *trace_ptr = nullptr;
private:
std::ostringstream _pending_console_output;
};
}
| 41.08284 | 143 | 0.620913 | chenxinhua2018 |
00ca8fc4349e9be6e22e0fa6a1e3f11e64cc7555 | 2,666 | cpp | C++ | tests/contraction_test.cpp | vaidehi8913/VieCut | f4bd2b468689cb8e5e11f18f1bb21468a119083d | [
"MIT"
] | 22 | 2020-06-12T07:26:45.000Z | 2022-03-03T17:03:08.000Z | tests/contraction_test.cpp | vaidehi8913/VieCut | f4bd2b468689cb8e5e11f18f1bb21468a119083d | [
"MIT"
] | 4 | 2019-09-04T10:39:39.000Z | 2020-05-26T05:25:35.000Z | tests/contraction_test.cpp | vaidehi8913/VieCut | f4bd2b468689cb8e5e11f18f1bb21468a119083d | [
"MIT"
] | 3 | 2020-12-11T13:43:45.000Z | 2021-11-09T15:08:58.000Z | /******************************************************************************
* contraction_test.h
*
* Source of VieCut.
*
******************************************************************************
* Copyright (C) 2018 Alexander Noe <alexander.noe@univie.ac.at>
*
* Published under the MIT license in the LICENSE file.
*****************************************************************************/
#include <omp.h>
#include <algorithm>
#include <memory>
#include <string>
#include <vector>
#ifdef PARALLEL
#include "parallel/coarsening/contract_graph.h"
#else
#include "coarsening/contract_graph.h"
#endif
#include "common/definitions.h"
#include "data_structure/graph_access.h"
#include "gtest/gtest_pred_impl.h"
#include "io/graph_io.h"
TEST(ContractionTest, NoContr) {
#ifdef PARALLEL
omp_set_num_threads(4);
#endif
graphAccessPtr G = graph_io::readGraphWeighted(
std::string(VIECUT_PATH) + "/graphs/small.metis");
std::vector<NodeID> mapping;
std::vector<std::vector<NodeID> > reverse_mapping;
for (NodeID n : G->nodes()) {
mapping.push_back(n);
reverse_mapping.emplace_back();
reverse_mapping.back().emplace_back(n);
}
graphAccessPtr cntr = contraction::contractGraph(
G, mapping, reverse_mapping);
ASSERT_EQ(G->number_of_nodes(), cntr->number_of_nodes());
ASSERT_EQ(G->number_of_edges(), cntr->number_of_edges());
}
TEST(ContractionTest, ContrBlock) {
#ifdef PARALLEL
omp_set_num_threads(4);
#endif
std::vector<std::string> graphs = { "", "-wgt" };
for (std::string graph : graphs) {
graphAccessPtr G = graph_io::readGraphWeighted(
std::string(VIECUT_PATH) + "/graphs/small" + graph + ".metis");
std::vector<NodeID> mapping;
std::vector<std::vector<NodeID> > reverse_mapping;
reverse_mapping.emplace_back();
reverse_mapping.emplace_back();
for (NodeID n : G->nodes()) {
mapping.push_back(n / 4);
reverse_mapping[n / 4].emplace_back(n);
}
graphAccessPtr cntr = contraction::contractGraph(
G, mapping, reverse_mapping);
ASSERT_EQ(cntr->number_of_edges(), 2);
ASSERT_EQ(cntr->number_of_nodes(), 2);
ASSERT_EQ(cntr->getEdgeTarget(0), 1);
ASSERT_EQ(cntr->getEdgeTarget(1), 0);
// in weighted graph edge weight is 3, in unweighted 2
if (graph == "") {
ASSERT_EQ(cntr->getEdgeWeight(0), 2);
ASSERT_EQ(cntr->getEdgeWeight(1), 2);
} else {
ASSERT_EQ(cntr->getEdgeWeight(0), 3);
ASSERT_EQ(cntr->getEdgeWeight(1), 3);
}
}
}
| 29.296703 | 79 | 0.582521 | vaidehi8913 |
00ccaaa47e8e6d3f55574562e5c9701d58674fd7 | 1,318 | cpp | C++ | Crimsonite/Crimsonite/source/render/MatrixMaths.cpp | Fletcher-Morris/Crimsonite-Engine | 515e6bd8994a324380fe831e6e568509695153f3 | [
"MIT"
] | null | null | null | Crimsonite/Crimsonite/source/render/MatrixMaths.cpp | Fletcher-Morris/Crimsonite-Engine | 515e6bd8994a324380fe831e6e568509695153f3 | [
"MIT"
] | null | null | null | Crimsonite/Crimsonite/source/render/MatrixMaths.cpp | Fletcher-Morris/Crimsonite-Engine | 515e6bd8994a324380fe831e6e568509695153f3 | [
"MIT"
] | null | null | null | #include "MatrixMaths.h"
#include "../ecs/Transform.h"
#include "../ecs/components/Camera.h"
glm::mat4 CreateModelMatrix(Transform * _transform)
{
glm::mat4 matrix = glm::mat4(1.0f);
glm::vec3 rot = _transform->GetWorldRotation();
matrix = glm::translate(matrix, _transform->GetWorldPosition());
matrix = glm::rotate(matrix, glm::radians(rot.x), { 1,0,0 });
matrix = glm::rotate(matrix, glm::radians(rot.y), { 0,1,0 });
matrix = glm::rotate(matrix, glm::radians(rot.z), { 0,0,1 });
matrix = glm::scale(matrix, _transform->GetScale());
return matrix;
}
glm::mat4 CreateViewMatrix(const Camera & _camera)
{
return glm::lookAt(_camera.entity->transform.GetWorldPosition(), _camera.entity->transform.GetWorldPosition() + _camera.entity->transform.Forward(), -_camera.entity->transform.Up());
}
glm::mat4 CreateProjectionMatrix(const CameraSettings & _settings)
{
float safeWidth = _settings.width;
float safeHeight = _settings.height;
if (safeHeight == 0.0f)
{
safeWidth = 1.0f;
safeHeight = 1.0f;
}
return CreateProjectionMatrix(_settings.fov, (float)(safeWidth / safeHeight), _settings.nearClip, _settings.farClip);
}
glm::mat4 CreateProjectionMatrix(const float _fov, const float _ratio, const float _near, const float _far)
{
return glm::perspective(glm::radians(_fov), _ratio, _near, _far);
}
| 34.684211 | 183 | 0.725341 | Fletcher-Morris |
00d3ba54f6f408ee1baccdd0d66ce4fd57e7dab5 | 1,703 | cpp | C++ | Semantic/SymbolTable/SymbolTable.cpp | mori-ahk/Sky | b8b27a3d5e63905c95d2305ee931821737a56d12 | [
"MIT"
] | 1 | 2020-04-29T02:11:42.000Z | 2020-04-29T02:11:42.000Z | Semantic/SymbolTable/SymbolTable.cpp | mori-ahk/Sky | b8b27a3d5e63905c95d2305ee931821737a56d12 | [
"MIT"
] | null | null | null | Semantic/SymbolTable/SymbolTable.cpp | mori-ahk/Sky | b8b27a3d5e63905c95d2305ee931821737a56d12 | [
"MIT"
] | null | null | null | //
// Created by Morteza Ahmadi on 2020-03-05.
//
#include "SymbolTable.h"
#include "../Error/Error.h"
void Semantic::SymbolTable::addClass(std::string &className, Class *_class) {
if (classes.find(className) != classes.end())
throw Semantic::Err::DuplicateClassDecl(className);
classes[className] = _class;
}
void Semantic::SymbolTable::addFunction(std::string &funcName, Function *function) {
if (freeFunctions.find(funcName) != freeFunctions.end()) {
int tag = freeFunctions.at(funcName).size();
function->setTag(funcName + "_" + std::to_string(tag));
freeFunctions.at(funcName).push_back(function);
} else {
function->setTag(funcName + "_" + std::to_string(0));
freeFunctions[funcName].push_back(function);
}
}
Function* Semantic::SymbolTable::getFreeFunction(const std::string &funcName, Function *function) const {
if (freeFunctions.find(funcName) == freeFunctions.end())
throw Semantic::Err::UndeclaredFunction(funcName, function->getPosition());
for (auto &f : freeFunctions.at(funcName)) {
if (*f == *function) return f;
}
throw Semantic::Err::UndeclaredFunction(funcName, function->getPosition());
}
const std::vector<Function *> &Semantic::SymbolTable::getFreeFunction(const std::string &funcName) const {
if (freeFunctions.find(funcName) == freeFunctions.end())
throw Semantic::Err::UndeclaredFunction(funcName, 0);
return freeFunctions.at(funcName);
}
Class *Semantic::SymbolTable::getClass(const std::string &className) {
if (classes.find(className) == classes.end())
throw Semantic::Err::UndeclaredClass(className);
return classes.at(className);
} | 36.234043 | 106 | 0.688784 | mori-ahk |
00d48a907eeefaae3fe86553e606541c83d32153 | 6,531 | cpp | C++ | src/osvr/ResetYaw/ResetYaw.cpp | stephengroat/OSVR-Core | 35e0967b18c8d6cb4caa152ebcbcb6cc473c9bf1 | [
"Apache-2.0"
] | 369 | 2015-03-08T03:12:41.000Z | 2022-02-08T22:15:39.000Z | src/osvr/ResetYaw/ResetYaw.cpp | DavidoRotho/OSVR-Core | b2fbb44e7979d9ebdf4bd8f00267cc267edbb465 | [
"Apache-2.0"
] | 486 | 2015-03-09T13:29:00.000Z | 2020-10-16T00:41:26.000Z | src/osvr/ResetYaw/ResetYaw.cpp | DavidoRotho/OSVR-Core | b2fbb44e7979d9ebdf4bd8f00267cc267edbb465 | [
"Apache-2.0"
] | 166 | 2015-03-08T12:03:56.000Z | 2021-12-03T13:56:21.000Z | /** @file
@brief Implementation
@date 2015
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2015 Sensics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Internal Includes
#include "ClientMainloopThread.h"
#include <osvr/ResetYaw/ResetYaw.h>
#include <osvr/ClientKit/ClientKit.h>
#include <osvr/Common/ClientContext.h>
#include <osvr/ClientKit/InterfaceStateC.h>
#include <osvr/Common/PathTree.h>
#include <osvr/Common/PathElementTypes.h>
#include <osvr/Common/PathNode.h>
#include <osvr/Common/JSONHelpers.h>
#include <osvr/Common/AliasProcessor.h>
#include <osvr/Common/ParseAlias.h>
#include <osvr/Common/GeneralizedTransform.h>
#include <osvr/Util/EigenInterop.h>
#include <osvr/Util/UniquePtr.h>
#include <osvr/Util/ExtractYaw.h>
// Library/third-party includes
#include <boost/variant/get.hpp>
#include <boost/optional.hpp>
#include <json/value.h>
#include <json/reader.h>
// Standard includes
#include <iostream>
#include <fstream>
#include <exception>
using std::cout;
using std::cerr;
using std::endl;
inline std::string
createJSONAlias(std::string const &path,
osvr::common::elements::AliasElement const &elt) {
return osvr::common::applyPriorityToAlias(
osvr::common::createJSONAlias(
path, osvr::common::jsonParse(elt.getSource())),
elt.priority())
.toStyledString();
}
boost::optional<osvr::common::elements::AliasElement>
getAliasElement(osvr::clientkit::ClientContext &ctx, std::string const &path) {
osvr::common::PathNode const *node = nullptr;
try {
node = &(ctx.get()->getPathTree().getNodeByPath(path));
} catch (std::exception &e) {
cerr << "Could not get node at path '" << path
<< "' - exception: " << e.what() << endl;
return boost::none;
}
auto elt = boost::get<osvr::common::elements::AliasElement>(&node->value());
if (!elt) {
return boost::none;
}
return *elt;
}
auto SETTLE_TIME = boost::posix_time::microseconds(1);
/// @brief A flag we set in transform levels we create.
static const char FLAG_KEY[] = "resetYaw";
static bool gotNewPose = false;
static bool gotFirstPose = false;
static OSVR_TimeValue firstPoseTime;
static OSVR_TimeValue newPoseTime;
static OSVR_TimeValue timeNow;
static OSVR_TimeValue lastResetTime;
static const double DELAY_TIME = 0.5;
void headOrientationCallback(void* userdata, const OSVR_TimeValue* timestamp, const OSVR_OrientationReport *report)
{
if (!gotFirstPose && osvrTimeValueDurationSeconds(timestamp, &newPoseTime) > 0.1)
{
gotFirstPose = true;
firstPoseTime = *(timestamp);
}
else if (gotFirstPose && !gotNewPose && firstPoseTime != *(timestamp))
{
gotNewPose = true;
newPoseTime = *(timestamp);
}
}
OSVR_ReturnCode osvrResetYaw() {
//avoid spamming calls
if (lastResetTime.seconds != 0)
{
osvrTimeValueGetNow(&timeNow);
float duration = osvrTimeValueDurationSeconds(&timeNow, &lastResetTime);
if (duration <= DELAY_TIME) return OSVR_RETURN_FAILURE;
}
osvr::clientkit::ClientContext ctx("com.osvr.bundled.resetyaw");
std::string const path = "/me/head";
// Get the interface associated with the destination route we
// are looking for.
osvr::clientkit::Interface iface = ctx.getInterface(path);
{
iface.registerCallback(&headOrientationCallback, NULL);
ClientMainloopThread client(ctx);
// Get the alias element corresponding to the desired path, if possible.
auto elt = getAliasElement(ctx, path);
if (!elt) {
// No luck, sorry.
cerr << "Couldn't get the alias at " << path << endl;
return -1;
}
// Get a reference to the source associated with the portion
// of the tree that has this destination. Then clean out
// any prior instance of our meddling by checking for an
// entry that has our flag key in it. Then replace the
// original source tree with the cleaned tree. Send this
// cleaned alias back to the server.
osvr::common::ParsedAlias origAlias{ elt->getSource() };
if (!origAlias.isValid()) {
cerr << "Couldn't parse the alias!" << endl;
return OSVR_RETURN_FAILURE;
}
osvr::common::GeneralizedTransform xforms{ origAlias.getAliasValue() };
osvr::common::remove_if(xforms, [](Json::Value const ¤t) {
return current.isMember(FLAG_KEY) && current[FLAG_KEY].isBool() &&
current[FLAG_KEY].asBool();
});
elt->setSource(
osvr::common::jsonToCompactString(xforms.get(origAlias.getLeaf())));
ctx.get()->sendRoute(createJSONAlias(path, *elt));
client.start();
while (!gotFirstPose)
{
boost::this_thread::sleep(SETTLE_TIME);
}
OSVR_OrientationState state;
OSVR_TimeValue timestamp;
OSVR_ReturnCode ret;
{
/// briefly interrupt the client mainloop so we can get stuff done
/// with the client state.
ClientMainloopThread::lock_type lock(client.getMutex());
ret = osvrGetOrientationState(iface.get(), ×tamp, &state);
if (ret != OSVR_RETURN_SUCCESS) {
cerr << "Sorry, no orientation state available for this path - "
"are you sure you have a device plugged in and your "
"path correct?"
<< endl;
return OSVR_RETURN_FAILURE;
}
auto q = osvr::util::eigen_interop::map(state);
auto yaw = osvr::util::extractYaw(q);
cout << "Correction: " << -yaw << " radians about Y" << endl;
Json::Value newLayer(Json::objectValue);
newLayer["postrotate"]["radians"] = -yaw;
newLayer["postrotate"]["axis"] = "y";
newLayer[FLAG_KEY] = true;
xforms.wrap(newLayer);
cout << "New source: "
<< xforms.get(origAlias.getLeaf()).toStyledString() << endl;
elt->setSource(osvr::common::jsonToCompactString(
xforms.get(origAlias.getLeaf())));
ctx.get()->sendRoute(createJSONAlias(path, *elt));
gotNewPose = false;
gotFirstPose = false;
}
while (!gotNewPose)
{
boost::this_thread::sleep(SETTLE_TIME);
}
gotNewPose = false;
gotFirstPose = false;
osvrTimeValueGetNow(&lastResetTime);
}
return OSVR_RETURN_SUCCESS;
}
| 30.236111 | 115 | 0.696524 | stephengroat |
00d53e351dd5743ebcd117c09543e6a7dec9989b | 1,165 | cpp | C++ | 115_DistinctSubsequences.cpp | kun2012/Leetcode | fa6bbe3f559176911ebb12c9b911b969c6ec85fb | [
"MIT"
] | null | null | null | 115_DistinctSubsequences.cpp | kun2012/Leetcode | fa6bbe3f559176911ebb12c9b911b969c6ec85fb | [
"MIT"
] | null | null | null | 115_DistinctSubsequences.cpp | kun2012/Leetcode | fa6bbe3f559176911ebb12c9b911b969c6ec85fb | [
"MIT"
] | null | null | null | /****************************************************************
Given a string S and a string T, count the number of distinct subsequences of T in S.
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not).
Here is an example:
S = "rabbbit", T = "rabbit"
Return 3.
****************************************************************/
class Solution {
public:
int numDistinct(string s, string t) {
int n = s.size();
int m = t.size();
if (n == 0 || m == 0) return 0;
if (n < m) return 0;
vector<vector<int> > f(n, vector<int>(m, 0));
if (s[0] == t[0]) f[0][0] = 1;
for (int i = 1; i < n; i++) {
f[i][0] = f[i - 1][0] + (s[i] == t[0]);
}
for (int i = 1; i < n; i++) {
for (int j = 1; j < m; j++) {
f[i][j] = f[i - 1][j];
if (s[i] == t[j]) f[i][j] += f[i - 1][j - 1];
}
}
return f[n - 1][m - 1];
}
}; | 41.607143 | 262 | 0.438627 | kun2012 |
00d76b16befd0c5f779e45bf3df994a109fdf6af | 4,940 | cpp | C++ | src/messages/serializer.cpp | jaspersong/Project_CS-4500 | eba9ca138a2845d457c72562d6792bb72c4fe99c | [
"MIT"
] | null | null | null | src/messages/serializer.cpp | jaspersong/Project_CS-4500 | eba9ca138a2845d457c72562d6792bb72c4fe99c | [
"MIT"
] | null | null | null | src/messages/serializer.cpp | jaspersong/Project_CS-4500 | eba9ca138a2845d457c72562d6792bb72c4fe99c | [
"MIT"
] | null | null | null | /**
* Name: Snowy Chen, Joe Song
* Date: 22 March 2020
* Section: Jason Hemann, MR 11:45-1:25
* Email: chen.xinu@husky.neu.edu, song.jo@husky.neu.edu
*/
// Lang::Cpp
#include <cassert>
#include <cstring>
#include "serializer.h"
Serializer::Serializer(size_t starting_size) {
this->buffer = new unsigned char[starting_size];
this->buffer_size = starting_size;
this->offset = 0;
this->owns_buffer = true;
}
Serializer::~Serializer() {
if (this->owns_buffer) {
delete[] this->buffer;
}
this->buffer = nullptr;
this->buffer_size = 0;
this->offset = 0;
}
bool Serializer::grow_buffer() {
if (this->owns_buffer) {
// Reallocate the buffer
size_t new_size = this->buffer_size * this->buffer_size;
auto *new_buffer = new unsigned char[new_size];
// Copy the previous data into
memcpy(static_cast<void *>(new_buffer), static_cast<void *>(this->buffer),
this->offset);
// Now replace the old buffer with the new one
delete[] this->buffer;
this->buffer = new_buffer;
this->buffer_size = new_size;
return true;
} else {
return false;
}
}
bool Serializer::set_generic(unsigned char *value, size_t num_bytes) {
assert(value != nullptr);
// Make sure there's enough space in the buffer for this value
bool ret_value = (this->buffer_size - this->offset) >= num_bytes;
// Make sure that we own the buffer as well
ret_value = this->owns_buffer && ret_value;
// Grow the buffer if necessary
if (!ret_value && this->owns_buffer) {
ret_value = this->grow_buffer();
}
// Set the value if possible
if (ret_value) {
auto *value_buffer = static_cast<unsigned char *>(value);
memcpy(this->buffer + this->offset, value_buffer, num_bytes);
// Move the offset
this->offset += num_bytes;
ret_value = true;
}
return ret_value;
}
unsigned char *Serializer::get_serialized_buffer() {
this->owns_buffer = false;
return this->buffer;
}
Deserializer::Deserializer(unsigned char *buffer, size_t num_bytes,
bool steal) {
assert(buffer != nullptr);
if (steal) {
this->buffer = buffer;
this->num_bytes = num_bytes;
this->offset = 0;
} else {
this->num_bytes = num_bytes;
this->offset = 0;
this->buffer = new unsigned char[this->num_bytes];
memcpy(this->buffer, reinterpret_cast<const void *>(buffer),
this->num_bytes);
}
this->own_buffer = true;
}
Deserializer::Deserializer(unsigned char *buffer, size_t num_bytes) {
assert(buffer != nullptr);
this->buffer = buffer;
this->num_bytes = num_bytes;
this->offset = 0;
this->own_buffer = false;
}
Deserializer::~Deserializer() {
if (this->own_buffer) {
delete[] this->buffer;
}
this->buffer = nullptr;
this->num_bytes = 0;
this->offset = 0;
}
size_t Deserializer::get_num_bytes_left() {
if (this->offset <= this->num_bytes) {
return this->num_bytes - this->offset;
} else {
return 0;
}
}
unsigned char Deserializer::get_byte() {
assert(this->get_num_bytes_left() >= sizeof(unsigned char));
unsigned char ret_value = this->buffer[this->offset];
// Move to the next pointer
this->offset += sizeof(unsigned char);
return ret_value;
}
bool Deserializer::get_bool() {
assert(this->get_num_bytes_left() >= sizeof(bool));
// Cast the buffer into an array of bool in order to grab the binary of
// the bool for the next few bytes
bool *interpreted_buffer =
reinterpret_cast<bool *>(this->buffer + this->offset);
bool ret_value = interpreted_buffer[0];
// Update the offset to a new offset based off the string
this->offset += sizeof(bool);
return ret_value;
}
size_t Deserializer::get_size_t() {
assert(this->get_num_bytes_left() >= sizeof(size_t));
// Get the size of the string
auto *size_t_buffer = reinterpret_cast<size_t *>(this->buffer + this->offset);
size_t ret_value = size_t_buffer[0];
// Update the offset to a new offset based off the string
this->offset += sizeof(size_t);
return ret_value;
}
int Deserializer::get_int() {
assert(this->get_num_bytes_left() >= sizeof(int));
// Cast the buffer into an array of bool in order to grab the binary of
// the bool for the next few bytes
int *interpreted_buffer =
reinterpret_cast<int *>(this->buffer + this->offset);
int ret_value = interpreted_buffer[0];
// Update the offset to a new offset based off the string
this->offset += sizeof(int);
return ret_value;
}
double Deserializer::get_double() {
assert(this->get_num_bytes_left() >= sizeof(double));
// Cast the buffer into an array of bool in order to grab the binary of
// the bool for the next few bytes
auto *interpreted_buffer =
reinterpret_cast<double *>(this->buffer + this->offset);
double ret_value = interpreted_buffer[0];
// Update the offset to a new offset based off the string
this->offset += sizeof(double);
return ret_value;
}
| 24.949495 | 80 | 0.674696 | jaspersong |
00dc884056ca4a23568c5273ca38c3767da6389c | 1,894 | cpp | C++ | src/gui/netlist_watcher/netlist_watcher.cpp | fengjixuchui/hal | 7781a929214977cf1393281a1efc3e404191eba7 | [
"MIT"
] | null | null | null | src/gui/netlist_watcher/netlist_watcher.cpp | fengjixuchui/hal | 7781a929214977cf1393281a1efc3e404191eba7 | [
"MIT"
] | null | null | null | src/gui/netlist_watcher/netlist_watcher.cpp | fengjixuchui/hal | 7781a929214977cf1393281a1efc3e404191eba7 | [
"MIT"
] | null | null | null | #include "netlist_watcher/netlist_watcher.h"
#include "gui_globals.h"
netlist_watcher::netlist_watcher(QObject* parent) : QObject(parent)
{
m_has_netlist_unsaved_changes = false;
connect(&g_graph_relay, &graph_relay::gate_event, this, &netlist_watcher::handle_gate_event);
connect(&g_graph_relay, &graph_relay::netlist_event, this, &netlist_watcher::handle_netlist_event);
connect(&g_graph_relay, &graph_relay::net_event, this, &netlist_watcher::handle_net_event);
connect(&g_graph_relay, &graph_relay::module_event, this, &netlist_watcher::handle_module_event);
}
netlist_watcher::~netlist_watcher(){}
void netlist_watcher::handle_netlist_event(netlist_event_handler::event ev, std::shared_ptr<netlist> object, u32 associated_data)
{
Q_UNUSED(ev)
Q_UNUSED(object)
Q_UNUSED(associated_data)
handle_netlist_modified();
}
void netlist_watcher::handle_net_event(net_event_handler::event ev, std::shared_ptr<net> object, u32 associated_data)
{
Q_UNUSED(ev)
Q_UNUSED(object)
Q_UNUSED(associated_data)
handle_netlist_modified();
}
void netlist_watcher::handle_gate_event(gate_event_handler::event ev, std::shared_ptr<gate> object, u32 associated_data)
{
Q_UNUSED(ev)
Q_UNUSED(object)
Q_UNUSED(associated_data)
handle_netlist_modified();
}
void netlist_watcher::handle_module_event(module_event_handler::event ev, std::shared_ptr<module> object, u32 associated_data)
{
Q_UNUSED(ev)
Q_UNUSED(object)
Q_UNUSED(associated_data)
handle_netlist_modified();
}
void netlist_watcher::handle_netlist_modified()
{
m_has_netlist_unsaved_changes = true;
}
bool netlist_watcher::has_netlist_unsaved_changes()
{
return m_has_netlist_unsaved_changes;
}
void netlist_watcher::set_netlist_unsaved_changes(bool has_netlist_unsaved_changes)
{
m_has_netlist_unsaved_changes = has_netlist_unsaved_changes;
}
| 28.268657 | 129 | 0.782471 | fengjixuchui |
00e0433befdba7565f18b0f2fb23b4261b581b4a | 974 | cpp | C++ | software/src/master/src/kernel/Vca_IPeek.cpp | c-kuhlman/vision | 46b25f7c0da703c059acc8f0a2eac1d5badf9f6d | [
"BSD-3-Clause"
] | 30 | 2016-10-07T15:23:35.000Z | 2020-03-25T20:01:30.000Z | src/kernel/Vca_IPeek.cpp | MichaelJCaruso/vision-software-src-master | 12b1b4f12a7531fe6e3cbb6861b40ac8e1985b92 | [
"BSD-3-Clause"
] | 30 | 2016-10-31T19:48:08.000Z | 2021-04-28T01:31:53.000Z | software/src/master/src/kernel/Vca_IPeek.cpp | c-kuhlman/vision | 46b25f7c0da703c059acc8f0a2eac1d5badf9f6d | [
"BSD-3-Clause"
] | 15 | 2016-10-07T16:44:13.000Z | 2021-06-21T18:47:55.000Z | /**
* @file
* Provides definition for IPeek interface.
*/
#define Vca_IPeek
/************************
************************
***** Interfaces *****
************************
************************/
/********************
***** System *****
********************/
#include "Vk.h"
/******************
***** Self *****
******************/
#include "Vca_IPeek.h"
/************************
***** Supporting *****
************************/
#include "Vca_CompilerHappyPill.h"
/************************
************************
***** *****
***** Vca::IPeek *****
***** *****
************************
************************/
VINTERFACE_TEMPLATE_EXPORTS (Vca::IPeek)
namespace Vca {
// {0B933950-2E07-44ed-9496-59D576836DC0}
VINTERFACE_TYPEINFO_DEFINITION (
IPeek,
0xb933950, 0x2e07, 0x44ed, 0x94, 0x96, 0x59, 0xd5, 0x76, 0x83, 0x6d, 0xc0
);
VINTERFACE_MEMBERINFO_DEFINITION (IPeek, GetValue, 0);
}
| 19.098039 | 74 | 0.370637 | c-kuhlman |
00e1e1eb456c6077d808708ea4a67c5ac4af9492 | 3,653 | cpp | C++ | test/ssc_test/cmod_grid_test.cpp | daniel-thom/ssc | 0012cf4e6a6ce3b3a7fe71e762d5ebc4808412ca | [
"BSD-3-Clause"
] | null | null | null | test/ssc_test/cmod_grid_test.cpp | daniel-thom/ssc | 0012cf4e6a6ce3b3a7fe71e762d5ebc4808412ca | [
"BSD-3-Clause"
] | null | null | null | test/ssc_test/cmod_grid_test.cpp | daniel-thom/ssc | 0012cf4e6a6ce3b3a7fe71e762d5ebc4808412ca | [
"BSD-3-Clause"
] | null | null | null | #include <gtest/gtest.h>
#include "cmod_grid_test.h"
TEST_F(CMGrid, SingleYearHourly_cmod_grid) {
grid_default_60_min(data);
// Run with fixed output
int errors = run_module(data, "grid");
EXPECT_FALSE(errors);
if (!errors)
{
ssc_number_t capacity_factor, annual_energy_pre_interconnect, annual_energy_interconnect;
int gen_size;
ssc_data_get_number(data, "capacity_factor_interconnect_ac", &capacity_factor);
ssc_data_get_number(data, "annual_energy_pre_interconnect_ac", &annual_energy_pre_interconnect);
ssc_data_get_number(data, "annual_energy", &annual_energy_interconnect);
ssc_number_t * system_kwac = GetArray("gen", gen_size);
ssc_number_t * system_pre_interconnect_kwac = GetArray("system_pre_interconnect_kwac", gen_size);
EXPECT_EQ(gen_size, 8760);
EXPECT_NEAR(capacity_factor, 29.0167, 0.001);
EXPECT_NEAR(annual_energy_interconnect, 457534759, 10);
EXPECT_NEAR(annual_energy_pre_interconnect, 460351000, 10);
}
}
TEST_F(CMGrid, SingleYearSubHourly_cmod_grid) {
grid_default_30_min(data);
int errors = run_module(data, "grid");
EXPECT_FALSE(errors);
if (!errors)
{
ssc_number_t capacity_factor, annual_energy_pre_interconnect, annual_energy_interconnect;
int gen_size;
ssc_data_get_number(data, "capacity_factor_interconnect_ac", &capacity_factor);
ssc_data_get_number(data, "annual_energy_pre_interconnect_ac", &annual_energy_pre_interconnect);
ssc_data_get_number(data, "annual_energy", &annual_energy_interconnect);
ssc_number_t * system_kwac = GetArray("gen", gen_size);
ssc_number_t * system_pre_interconnect_kwac = GetArray("system_pre_interconnect_kwac", gen_size);
EXPECT_EQ(gen_size, 8760*2);
EXPECT_NEAR(capacity_factor, 30.78777, 0.001);
EXPECT_NEAR(annual_energy_interconnect, 485461500, 10);
EXPECT_NEAR(annual_energy_pre_interconnect, 498820000, 10);
}
}
TEST_F(CMGrid, SingleYearSubHourlyLifetime_cmod_grid) {
grid_default_30_min_lifetime(data);
int errors = run_module(data, "grid");
EXPECT_FALSE(errors);
if (!errors)
{
ssc_number_t capacity_factor, annual_energy_pre_interconnect, annual_energy_interconnect;
int gen_size;
ssc_data_get_number(data, "capacity_factor_interconnect_ac", &capacity_factor);
ssc_data_get_number(data, "annual_energy_pre_interconnect_ac", &annual_energy_pre_interconnect);
ssc_data_get_number(data, "annual_energy", &annual_energy_interconnect);
ssc_number_t * system_kwac = GetArray("gen", gen_size);
ssc_number_t * system_pre_interconnect_kwac = GetArray("system_pre_interconnect_kwac", gen_size);
EXPECT_EQ(gen_size, 8760 * 2 * 2);
EXPECT_NEAR(capacity_factor, 30.78777, 0.001);
EXPECT_NEAR(annual_energy_interconnect, 485461500, 10);
EXPECT_NEAR(annual_energy_pre_interconnect, 498820000, 10);
}
}
TEST_F(CMGrid, SingleYearNoFinancial_cmod_grid) {
grid_default_60_min_no_financial(data);
int errors = run_module(data, "grid");
EXPECT_FALSE(errors);
if (!errors)
{
ssc_number_t capacity_factor, annual_energy_pre_interconnect, annual_energy_interconnect;
int gen_size;
ssc_data_get_number(data, "capacity_factor_interconnect_ac", &capacity_factor);
ssc_data_get_number(data, "annual_energy_pre_interconnect_ac", &annual_energy_pre_interconnect);
ssc_data_get_number(data, "annual_energy", &annual_energy_interconnect);
ssc_number_t * system_kwac = GetArray("gen", gen_size);
ssc_number_t * system_pre_interconnect_kwac = GetArray("system_pre_interconnect_kwac", gen_size);
EXPECT_EQ(gen_size, 8760);
EXPECT_NEAR(capacity_factor, 29.0167, 0.001);
EXPECT_NEAR(annual_energy_interconnect, 457534759, 10);
EXPECT_NEAR(annual_energy_pre_interconnect, 460351000, 10);
}
} | 39.27957 | 99 | 0.803723 | daniel-thom |
00e7418a63eea90d4710d80b149e5ec02ce5a367 | 594 | hpp | C++ | callgraph/detail/from_to_connector.hpp | anthony-arnold/callgraph | 1d7fede6c31b9d9a0fc7f1b2358cb7204aff4e94 | [
"BSD-2-Clause"
] | 2 | 2020-12-04T11:20:44.000Z | 2022-01-08T10:24:49.000Z | callgraph/detail/from_to_connector.hpp | anthony-arnold/callgraph | 1d7fede6c31b9d9a0fc7f1b2358cb7204aff4e94 | [
"BSD-2-Clause"
] | null | null | null | callgraph/detail/from_to_connector.hpp | anthony-arnold/callgraph | 1d7fede6c31b9d9a0fc7f1b2358cb7204aff4e94 | [
"BSD-2-Clause"
] | null | null | null | // callgraph/detail/from_to_connector.hpp
// License: BSD-2-Clause
#ifndef CALLGRAPH_DETAIL_FROM_TO_CONNECTOR_HPP
#define CALLGRAPH_DETAIL_FROM_TO_CONNECTOR_HPP
#include <callgraph/detail/base_connector.hpp>
#ifndef NO_DOC
namespace callgraph {
namespace detail {
template <typename T, size_t From, size_t To>
class from_to_connector : public base_connector<T> {
public:
constexpr from_to_connector(T&& v)
: base_connector<T>(std::forward<T>(v)) {}
};
}
}
#endif // NO_DOC
#endif // CALLGRAPH_DETAIL_FROM_TO_CONNECTOR_HPP
| 25.826087 | 60 | 0.70202 | anthony-arnold |
00e8912ce9cbe1f9011e3074d95b341886d6cebb | 3,613 | cpp | C++ | lib/Transforms/BlockSeparator.cpp | compor/Atrox | d6e893f0c91764c58e198ccf316096b0ec9f7d90 | [
"MIT"
] | null | null | null | lib/Transforms/BlockSeparator.cpp | compor/Atrox | d6e893f0c91764c58e198ccf316096b0ec9f7d90 | [
"MIT"
] | null | null | null | lib/Transforms/BlockSeparator.cpp | compor/Atrox | d6e893f0c91764c58e198ccf316096b0ec9f7d90 | [
"MIT"
] | null | null | null | //
//
//
#include "Atrox/Transforms/BlockSeparator.hpp"
#include "IteratorRecognition/Analysis/IteratorRecognition.hpp"
#include "llvm/IR/BasicBlock.h"
// using llvm::BasicBlock
#include "llvm/IR/Instructions.h"
// using llvm::BranchInst
#include "llvm/IR/Dominators.h"
// using llvm::DominatorTree
#include "llvm/Analysis/LoopInfo.h"
// using llvm::Loop
// using llvm::LoopInfo
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
// using llvm::SplitBlock
#include "llvm/Support/Debug.h"
// using LLVM_DEBUG macro
// using llvm::dbgs
#include <algorithm>
// using std::reverse
#include <iterator>
// using std::prev
#define DEBUG_TYPE "atrox-separator"
namespace atrox {
Mode GetMode(const llvm::Instruction &Inst, const llvm::Loop &CurLoop,
const iteratorrecognition::IteratorInfo &Info) {
return Info.isIterator(&Inst) ? Mode::Iterator : Mode::Payload;
}
bool FindPartitionPoints(const llvm::Loop &CurLoop,
const iteratorrecognition::IteratorInfo &Info,
BlockModeMapTy &Modes,
BlockModeChangePointMapTy &Points) {
for (auto bi = CurLoop.block_begin(), be = CurLoop.block_end(); bi != be;
++bi) {
auto *bb = *bi;
// auto firstI = bb->getFirstInsertionPt();
// auto lastSeenMode = InvertMode(GetMode(*firstI, CurLoop, Info));
bool hasAllSameModeInstructions = true;
auto phisMode = GetMode(*bb->begin(), CurLoop, Info);
for (auto &e : bb->phis()) {
auto mode = GetMode(e, CurLoop, Info);
if (phisMode != mode) {
hasAllSameModeInstructions = false;
break;
}
phisMode = mode;
}
// these are just for auto type deduction
auto firstI = bb->getFirstInsertionPt();
auto lastSeenMode = GetMode(*firstI, CurLoop, Info);
if (hasAllSameModeInstructions) {
firstI = bb->begin();
lastSeenMode = GetMode(*firstI, CurLoop, Info);
} else {
firstI = bb->getFirstInsertionPt();
lastSeenMode = GetMode(*firstI, CurLoop, Info);
auto modeChangePt = std::make_pair(&*firstI, InvertMode(lastSeenMode));
if (Points.find(bb) == Points.end())
Points.emplace(bb, std::vector<BlockModeChangePointTy>{});
Points.at(bb).push_back(modeChangePt);
}
hasAllSameModeInstructions = true;
for (auto ii = firstI, ie = bb->end(); ii != ie; ++ii) {
auto &inst = *ii;
auto *br = llvm::dyn_cast<llvm::BranchInst>(&inst);
bool isUncondBr = br && br->isUnconditional();
auto curMode = GetMode(inst, CurLoop, Info);
if (lastSeenMode != curMode && !isUncondBr) {
hasAllSameModeInstructions = false;
auto modeChangePt = std::make_pair(&inst, curMode);
if (Points.find(bb) == Points.end())
Points.emplace(bb, std::vector<BlockModeChangePointTy>{});
Points.at(bb).push_back(modeChangePt);
lastSeenMode = curMode;
}
}
if (hasAllSameModeInstructions)
Modes.emplace(bb, lastSeenMode);
}
return !Points.empty();
}
void SplitAtPartitionPoints(BlockModeChangePointMapTy &Points,
BlockModeMapTy &Modes, llvm::DominatorTree *DT,
llvm::LoopInfo *LI) {
for (auto &e : Points) {
auto *oldBB = e.first;
Mode lastMode;
std::reverse(e.second.begin(), e.second.end());
for (auto &k : e.second) {
auto *splitI = k.first;
lastMode = k.second;
Modes.emplace(llvm::SplitBlock(oldBB, splitI, DT, LI), lastMode);
}
Modes.emplace(oldBB, InvertMode(lastMode));
}
return;
}
} // namespace atrox
| 27.165414 | 77 | 0.634376 | compor |
00eb99d3077ec0ca45c02dead7db417983b885d0 | 49,323 | cpp | C++ | ds/security/cryptoapi/ui/wizards/certrequestercontext.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | ds/security/cryptoapi/ui/wizards/certrequestercontext.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | ds/security/cryptoapi/ui/wizards/certrequestercontext.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | #include "wzrdpvk.h"
#include "certca.h"
#include "cautil.h"
#include "CertRequesterContext.h"
//--------------------------------------------------------------------------------
// Machine context and local context now use the same code to build the CSP list:
HRESULT BuildCSPList(CERT_WIZARD_INFO *m_pCertWizardInfo)
{
DWORD dwIndex = 0;
DWORD dwProviderType = 0;
DWORD cbSize = 0;
HRESULT hr = E_FAIL;
LPWSTR pwszProviderName = 0;
if (NULL == m_pCertWizardInfo)
return E_POINTER;
//free the old memory
FreeProviders(m_pCertWizardInfo->dwCSPCount,
m_pCertWizardInfo->rgdwProviderType,
m_pCertWizardInfo->rgwszProvider);
m_pCertWizardInfo->dwCSPCount = 0;
m_pCertWizardInfo->rgdwProviderType = NULL;
m_pCertWizardInfo->rgwszProvider = NULL;
for (dwIndex = 0;
CryptEnumProvidersU(dwIndex, 0, 0, &dwProviderType, NULL, &cbSize);
dwIndex++)
{
pwszProviderName = (LPWSTR)WizardAlloc(cbSize);
if(NULL == pwszProviderName)
goto MemoryErr;
//get the provider name and type
if(!CryptEnumProvidersU
(dwIndex,
0,
0,
&dwProviderType,
pwszProviderName,
&cbSize))
goto CryptEnumProvidersUError;
m_pCertWizardInfo->dwCSPCount = dwIndex + 1;
m_pCertWizardInfo->rgdwProviderType = (DWORD *)WizardRealloc
(m_pCertWizardInfo->rgdwProviderType, sizeof(DWORD) * m_pCertWizardInfo->dwCSPCount);
if(NULL == m_pCertWizardInfo->rgdwProviderType)
goto MemoryErr;
m_pCertWizardInfo->rgwszProvider = (LPWSTR *)WizardRealloc
(m_pCertWizardInfo->rgwszProvider, sizeof(LPWSTR) * m_pCertWizardInfo->dwCSPCount);
if(NULL == m_pCertWizardInfo->rgwszProvider)
goto MemoryErr;
(m_pCertWizardInfo->rgdwProviderType)[dwIndex] = dwProviderType;
(m_pCertWizardInfo->rgwszProvider)[dwIndex] = pwszProviderName;
// Our only reference to this data should now be m_pCertWizardInfo->rgwszProvider.
pwszProviderName = NULL;
}
//we should have some CSPs
if(0 == m_pCertWizardInfo->dwCSPCount)
goto FailErr;
hr = S_OK;
CommonReturn:
return hr;
ErrorReturn:
if (NULL != pwszProviderName) { WizardFree(pwszProviderName); }
//free the old memory
FreeProviders(m_pCertWizardInfo->dwCSPCount,
m_pCertWizardInfo->rgdwProviderType,
m_pCertWizardInfo->rgwszProvider);
m_pCertWizardInfo->dwCSPCount = 0;
m_pCertWizardInfo->rgdwProviderType = NULL;
m_pCertWizardInfo->rgwszProvider = NULL;
goto CommonReturn;
SET_HRESULT(CryptEnumProvidersUError, HRESULT_FROM_WIN32(GetLastError()));
SET_HRESULT(MemoryErr, E_OUTOFMEMORY);
SET_HRESULT(FailErr, E_FAIL);
}
//--------------------------------------------------------------------------------
// Machine context and local context now use the same code to get the default prov
HRESULT GetDefaultCSP(IN CERT_WIZARD_INFO *m_pCertWizardInfo, IN BOOL fMachine, OUT UINT *pIdsText, OUT BOOL *pfAllocateCSP)
{
DWORD cbProvName = 0;
DWORD dwFlags = fMachine ? CRYPT_MACHINE_DEFAULT : CRYPT_USER_DEFAULT;
HRESULT hr = E_FAIL;
LPWSTR pwszProvider = NULL;
if (NULL == m_pCertWizardInfo)
return E_POINTER;
if (NULL == pfAllocateCSP)
return E_INVALIDARG;
*pfAllocateCSP = FALSE;
//no provider has been selected
if(0 == m_pCertWizardInfo->dwProviderType)
return S_OK;
//return if user has selected both the dwProviderType
//or the provider name
if(NULL != m_pCertWizardInfo->pwszProvider)
return S_OK;
//get the default provider
if (!CryptGetDefaultProviderW(m_pCertWizardInfo->dwProviderType, NULL, dwFlags, NULL, &cbProvName))
goto CryptGetDefaultProviderWError;
pwszProvider = (LPWSTR)LocalAlloc(LPTR, cbProvName);
if (NULL == pwszProvider)
goto MemoryError;
if (!CryptGetDefaultProviderW(m_pCertWizardInfo->dwProviderType, NULL, dwFlags, pwszProvider, &cbProvName))
goto CryptGetDefaultProviderWError;
m_pCertWizardInfo->pwszProvider = pwszProvider;
pwszProvider = NULL;
*pfAllocateCSP = TRUE;
hr = S_OK;
CommonReturn:
if(NULL != pwszProvider) { LocalFree(pwszProvider); }
return hr;
ErrorReturn:
*pIdsText = IDS_INVALID_CSP;
goto CommonReturn;
SET_HRESULT(CryptGetDefaultProviderWError, HRESULT_FROM_WIN32(GetLastError()));
SET_HRESULT(MemoryError, E_OUTOFMEMORY);
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
//
// LocalContext Implementation.
// See CertRequestContext.h for method-level documentation.
//
//
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
HRESULT LocalContext::BuildCSPList()
{
return ::BuildCSPList(m_pCertWizardInfo);
}
BOOL LocalContext::CheckAccessPermission(IN HCERTTYPE hCertType)
{
BOOL fResult = FALSE;
HANDLE hClientToken = NULL;
HRESULT hr = E_FAIL;
// First attempts to get the thread token. If this fails, acquires the
// process token. Finally, if that fails, returns NULL.
if (0 != (m_pCertWizardInfo->dwFlags & CRYPTUI_WIZ_ALLOW_ALL_TEMPLATES)) {
fResult = TRUE;
} else {
hClientToken = this->GetClientIdentity();
if (NULL == hClientToken)
goto GetClientIdentityError;
__try {
fResult = S_OK == CACertTypeAccessCheck(hCertType, hClientToken);
} __except(EXCEPTION_EXECUTE_HANDLER) {
goto CACertTypeAccessCheckError;
}
}
CommonReturn:
if (NULL != hClientToken) { CloseHandle(hClientToken); }
return fResult;
ErrorReturn:
fResult = FALSE;
goto CommonReturn;
SET_HRESULT(CACertTypeAccessCheckError, HRESULT_FROM_WIN32(GetLastError()));
SET_HRESULT(GetClientIdentityError, HRESULT_FROM_WIN32(GetLastError()));
}
BOOL LocalContext::CheckCAPermission(IN HCAINFO hCAInfo)
{
BOOL fResult = FALSE;
HANDLE hClientToken = NULL;
HRESULT hr = E_FAIL;
if (0 != (m_pCertWizardInfo->dwFlags & CRYPTUI_WIZ_ALLOW_ALL_CAS)) {
fResult = TRUE;
} else {
hClientToken = this->GetClientIdentity();
if (NULL == hClientToken)
goto GetClientIdentityError;
__try {
fResult = S_OK == CAAccessCheck(hCAInfo, hClientToken);
} __except(EXCEPTION_EXECUTE_HANDLER) {
goto CAAccessCheckError;
}
}
CommonReturn:
if (NULL != hClientToken) { CloseHandle(hClientToken); }
return fResult;
ErrorReturn:
fResult = FALSE;
goto CommonReturn;
SET_HRESULT(CAAccessCheckError, HRESULT_FROM_WIN32(GetLastError()));
SET_HRESULT(GetClientIdentityError, HRESULT_FROM_WIN32(GetLastError()));
}
HRESULT LocalContext::GetDefaultCSP(OUT BOOL *pfAllocateCSP)
{
return ::GetDefaultCSP(m_pCertWizardInfo, FALSE /*user*/, &m_idsText, pfAllocateCSP);
}
HRESULT LocalContext::Enroll(OUT DWORD *pdwStatus,
OUT HANDLE *pResult)
{
BOOL fHasNextCSP = TRUE;
BOOL fRequestIsCached;
BOOL fCreateRequest;
BOOL fFreeRequest;
BOOL fSubmitRequest;
CERT_BLOB renewCert;
CERT_ENROLL_INFO RequestInfo;
CERT_REQUEST_PVK_NEW CertRequestPvkNew;
CERT_REQUEST_PVK_NEW CertRenewPvk;
CRYPTUI_WIZ_CERT_CA CertCA;
DWORD dwStatus = CRYPTUI_WIZ_CERT_REQUEST_STATUS_UNKNOWN;
DWORD dwCSPIndex;
DWORD dwSavedGenKeyFlags;
HANDLE hRequest = NULL;
HRESULT hr = E_FAIL;
LPWSTR pwszHashAlg = NULL;
//init 1st for error jump
ZeroMemory(&CertRenewPvk, sizeof(CertRenewPvk));
if (NULL == pResult)
return E_INVALIDARG;
if (NULL == m_pCertWizardInfo)
return E_POINTER;
memset(&CertCA, 0, sizeof(CertCA));
memset(&RequestInfo, 0, sizeof(RequestInfo));
dwSavedGenKeyFlags = m_pCertWizardInfo->dwGenKeyFlags;
fCreateRequest = 0 == (m_pCertWizardInfo->dwFlags & (CRYPTUI_WIZ_SUBMIT_ONLY | CRYPTUI_WIZ_FREE_ONLY));
fFreeRequest = 0 == (m_pCertWizardInfo->dwFlags & (CRYPTUI_WIZ_CREATE_ONLY | CRYPTUI_WIZ_SUBMIT_ONLY));
fSubmitRequest = 0 == (m_pCertWizardInfo->dwFlags & (CRYPTUI_WIZ_CREATE_ONLY | CRYPTUI_WIZ_FREE_ONLY));
// An invalid combination of flags was specified.
if (FALSE == (fCreateRequest || fFreeRequest || fSubmitRequest))
return E_INVALIDARG;
// For FREE_ONLY and SUBMIT_ONLY, copy the request from the IN parameter.
if (0 != ((CRYPTUI_WIZ_SUBMIT_ONLY | CRYPTUI_WIZ_FREE_ONLY) & m_pCertWizardInfo->dwFlags))
{
if (NULL == *pResult)
return E_INVALIDARG;
hRequest = *pResult;
}
// Initialize to false ... we need the marshalled parameters to know whether we can cache the request.
fRequestIsCached = FALSE;
// Iterate over each CA, performing a create and submit operation for each.
// Note that we can cache requests for certs if key archival is not needed.
//
if (fCreateRequest || fSubmitRequest)
{
for (IEnumCA CAEnumerator(m_pCertWizardInfo); ; )
{
if (S_OK != (CAEnumerator.Next(&CertCA)))
{
if (!FAILED(hr))
hr=E_FAIL;
if (E_FAIL == hr)
m_pCertWizardInfo->idsText = IDS_NO_CA_FOR_ENROLL_REQUEST_FAILED;
goto ErrorReturn;
}
// Create a certificate request only if
// 1) This is not a submit-only or a free-only operation.
// 2) We don't already have a cached request.
// (We can cache requests which don't require key archival on the CA).
//
// The request is created by looping over available CSPs until one successfully generates
// the request.
//
if (TRUE == fCreateRequest && FALSE == fRequestIsCached)
{
fHasNextCSP = TRUE;
for (IEnumCSP CSPEnumerator(m_pCertWizardInfo); fHasNextCSP; )
{
_JumpCondition(S_OK != (hr = CSPEnumerator.Next(&dwCSPIndex)), ErrorReturn);
_JumpCondition(S_OK != (hr = CSPEnumerator.HasNext(&fHasNextCSP)), ErrorReturn);
// Each call to MarshallRequestParameters can change the dwGenKeyFlags of pCertWizardInfo
// if the CSP does not support the min key size contained in this field.
// As a result, we must reset the dwGenKeyFlags field to the desired value
// before every call to MarshallRequestParameters.
m_pCertWizardInfo->dwGenKeyFlags = dwSavedGenKeyFlags;
if (S_OK != (hr = ::MarshallRequestParameters
(dwCSPIndex,
m_pCertWizardInfo,
&renewCert,
&CertRequestPvkNew,
&CertRenewPvk,
&pwszHashAlg,
&RequestInfo)))
goto NextCSP;
if (NULL != hRequest)
{
::FreeRequest(hRequest);
hRequest = NULL;
}
hr = ::CreateRequest
(m_pCertWizardInfo->dwFlags,
m_pCertWizardInfo->dwPurpose,
CertCA.pwszCAName,
CertCA.pwszCALocation,
((CRYPTUI_WIZ_CERT_RENEW & m_pCertWizardInfo->dwPurpose) ? &renewCert : NULL),
((CRYPTUI_WIZ_CERT_RENEW & m_pCertWizardInfo->dwPurpose) ? &CertRenewPvk : NULL),
m_pCertWizardInfo->fNewKey,
&CertRequestPvkNew,
pwszHashAlg,
(LPWSTR)m_pCertWizardInfo->pwszDesStore,
m_pCertWizardInfo->dwStoreFlags,
&RequestInfo,
&hRequest);
// Process the return value:
if (S_OK == hr)
{
// Success, get rid of whatever error text we have from past creations:
m_pCertWizardInfo->idsText = 0;
// We're done if we don't need to submit the request.
_JumpCondition(!fSubmitRequest, CommonReturn);
// Cache the request if we don't need support for key archival.
fRequestIsCached = 0 == (CertRequestPvkNew.dwPrivateKeyFlags & CT_FLAG_ALLOW_PRIVATE_KEY_ARCHIVAL);
break;
}
else if (E_ACCESSDENIED == HRESULT_FROM_WIN32(hr))
{
// E_ACCESSDENIED could indicate one of several different error conditions. Map this
// to an resource identifier which details the possible causes of failure, and try again...
m_pCertWizardInfo->idsText = IDS_NO_ACCESS_TO_ICERTREQUEST2;
}
else if (NTE_BAD_ALGID == HRESULT_FROM_WIN32(hr))
{
// NTE_BAD_ALGID indicates that the CSP didn't support the algorithm type required
// by the template. Map this to a resource identifier that details the possible causes
// of failure, and try again...
m_pCertWizardInfo->idsText = IDS_CSP_BAD_ALGTYPE;
}
else if (HRESULT_FROM_WIN32(ERROR_CANCELLED) == HRESULT_FROM_WIN32(hr))
{
// The user cancelled the operation. Don't try to enroll any longer.
goto ErrorReturn;
}
else
{
// It's an error, but we don't need to map it to special text. Just keep processing...
}
// We're out of CSPs, and we haven't yet created the request!
if (!fHasNextCSP)
{
// If the template doesn't require key archival, we're done. Otherwise, we've got to
// try the other CAs. Note that if we had a mechanism for knowing whether it was the
// key archival step
if (0 == (CertRequestPvkNew.dwPrivateKeyFlags & CT_FLAG_ALLOW_PRIVATE_KEY_ARCHIVAL))
goto ErrorReturn;
else
{
::FreeRequestParameters(&pwszHashAlg, &CertRenewPvk, &RequestInfo);
goto NextCA;
}
}
NextCSP:
::FreeRequestParameters(&pwszHashAlg, &CertRenewPvk, &RequestInfo);
}
}
// Submit the request only if this is not a create-only or a free-only operation:
//
if (TRUE == fSubmitRequest)
{
hr = ::SubmitRequest
(hRequest,
FALSE,
m_pCertWizardInfo->dwPurpose,
m_pCertWizardInfo->fConfirmation,
m_pCertWizardInfo->hwndParent,
(LPWSTR)m_pCertWizardInfo->pwszConfirmationTitle,
m_pCertWizardInfo->idsConfirmTitle,
CertCA.pwszCALocation,
CertCA.pwszCAName,
NULL,
NULL,
NULL,
&dwStatus,
(PCCERT_CONTEXT *)pResult);
if (S_OK == hr)
{
// Success, get rid of whatever error text we have from past submits:
m_pCertWizardInfo->idsText = 0;
// If we've successfully submitted or pended
goto CommonReturn;
}
else if (E_ACCESSDENIED == HRESULT_FROM_WIN32(hr))
{
// E_ACCESSDENIED could indicate one of several different error conditions. Map this
// to an resource identifier which details the possible causes of failure, and try again...
m_pCertWizardInfo->idsText = IDS_SUBMIT_NO_ACCESS_TO_ICERTREQUEST2;
}
// Some error has occured.
// If it's a non-CA related error, give up...
_JumpCondition(dwStatus != CRYPTUI_WIZ_CERT_REQUEST_STATUS_REQUEST_ERROR &&
dwStatus != CRYPTUI_WIZ_CERT_REQUEST_STATUS_REQUEST_DENIED &&
dwStatus != CRYPTUI_WIZ_CERT_REQUEST_STATUS_CONNECTION_FAILED,
ErrorReturn);
// Otherwise, try another CA...
}
NextCA:;
}
}
CommonReturn:
// Write the request to pResult for a create only operation:
if (hr == S_OK && 0 != (m_pCertWizardInfo->dwFlags & CRYPTUI_WIZ_CREATE_ONLY))
{
*pResult = hRequest;
}
// Write the status code, if requested.
if (NULL != pdwStatus) { *pdwStatus = dwStatus; }
// Free resources.
if (NULL != hRequest && fFreeRequest) { ::FreeRequest(hRequest); }
::FreeRequestParameters(&pwszHashAlg, &CertRenewPvk, &RequestInfo);
return hr;
ErrorReturn:
goto CommonReturn;
}
HRESULT LocalContext::QueryRequestStatus(IN HANDLE hRequest, OUT CRYPTUI_WIZ_QUERY_CERT_REQUEST_INFO *pQueryInfo)
{
HRESULT hr;
if (!QueryRequest(hRequest, pQueryInfo))
goto QueryRequestError;
hr = S_OK;
ErrorReturn:
return hr;
SET_HRESULT(QueryRequestError, GetLastError());
}
HRESULT KeySvcContext::QueryRequestStatus(IN HANDLE hRequest, OUT CRYPTUI_WIZ_QUERY_CERT_REQUEST_INFO *pQueryInfo)
{
HRESULT hr = E_FAIL;
KEYSVCC_HANDLE hKeyService = NULL;
KEYSVC_TYPE dwServiceType = KeySvcMachine;
LPSTR pszMachineName = NULL;
if (NULL == m_pCertWizardInfo)
return E_POINTER;
if (0 != (hr = ::KeyOpenKeyService(pszMachineName,
dwServiceType,
(LPWSTR)(m_pCertWizardInfo->pwszAccountName), // Service name if necessary
NULL, // no authentication string right now
NULL,
&hKeyService)))
goto KeyOpenKeyServiceError;
if (0 != (hr = ::KeyQueryRequestStatus(hKeyService, hRequest, pQueryInfo)))
goto KeyQueryRequestStatusError;
hr = S_OK;
ErrorReturn:
if (NULL != hKeyService) { KeyCloseKeyService(hKeyService, NULL); }
if (NULL != pszMachineName) { FreeMBStr(NULL,pszMachineName); }
return hr;
TRACE_ERROR(KeyOpenKeyServiceError);
TRACE_ERROR(KeyQueryRequestStatusError);
}
HRESULT LocalContext::Initialize()
{
return S_OK;
}
HANDLE LocalContext::GetClientIdentity()
{
HANDLE hHandle = NULL;
HANDLE hClientToken = NULL;
HANDLE hProcessToken = NULL;
HRESULT hr;
// Step 1: attempt to acquire the thread token.
hHandle = GetCurrentThread();
if (NULL == hHandle)
goto GetThreadTokenError;
if (!OpenThreadToken(hHandle,
TOKEN_QUERY,
TRUE, // open as self
&hClientToken))
goto GetThreadTokenError;
// We got the thread token:
goto GetThreadTokenSuccess;
// Step 2: we've failed to acquire the thread token,
// try to get the process token.
GetThreadTokenError:
if (hHandle != NULL) { CloseHandle(hHandle); }
// We failed to get the thread token, now try to acquire the process token:
hHandle = GetCurrentProcess();
if (NULL == hHandle)
goto GetProcessHandleError;
if (!OpenProcessToken(hHandle,
TOKEN_DUPLICATE,
&hProcessToken))
goto OpenProcessTokenError;
if(!DuplicateToken(hProcessToken,
SecurityImpersonation,
&hClientToken))
goto DuplicateTokenError;
GetThreadTokenSuccess:
CommonReturn:
if (NULL != hHandle) { CloseHandle(hHandle); }
if (NULL != hProcessToken) { CloseHandle(hProcessToken); }
return hClientToken;
ErrorReturn:
goto CommonReturn;
SET_HRESULT(DuplicateTokenError, HRESULT_FROM_WIN32(GetLastError()));
SET_HRESULT(GetProcessHandleError, HRESULT_FROM_WIN32(GetLastError()));
SET_HRESULT(OpenProcessTokenError, HRESULT_FROM_WIN32(GetLastError()));
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
//
// KeySvcContext Implementation.
// See requesters.h for method-level documentation.
//
//
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
HRESULT KeySvcContext::BuildCSPList()
{
return ::BuildCSPList(m_pCertWizardInfo);
}
BOOL KeySvcContext::CheckAccessPermission(IN HCERTTYPE hCertType)
{
LPWSTR *awszCurrentType = NULL;
LPWSTR *awszTypeName = NULL;
if (NULL == m_pCertWizardInfo)
{
SetLastError(ERROR_INVALID_DATA);
return FALSE;
}
if (0 != (m_pCertWizardInfo->dwFlags & CRYPTUI_WIZ_ALLOW_ALL_TEMPLATES)) {
return TRUE;
}
if(NULL != m_pCertWizardInfo->awszAllowedCertTypes)
{
if(S_OK == CAGetCertTypeProperty(hCertType, CERTTYPE_PROP_DN, &awszTypeName))
{
if(NULL != awszTypeName)
{
if(NULL != awszTypeName[0])
{
awszCurrentType = m_pCertWizardInfo->awszAllowedCertTypes;
while(NULL != *awszCurrentType)
{
if(wcscmp(*awszCurrentType, awszTypeName[0]) == 0)
{
return TRUE;
}
awszCurrentType++;
}
}
CAFreeCertTypeProperty(hCertType, awszTypeName);
}
}
}
return FALSE;
}
BOOL KeySvcContext::CheckCAPermission(IN HCAINFO hCAInfo)
{
LPWSTR *wszCAName = NULL;
LPWSTR *wszCurrentCA = NULL;
if (NULL == m_pCertWizardInfo)
{
SetLastError(ERROR_INVALID_DATA);
return FALSE;
}
if (0 != (m_pCertWizardInfo->dwFlags & CRYPTUI_WIZ_ALLOW_ALL_CAS)) {
return TRUE;
}
if (NULL != m_pCertWizardInfo->awszValidCA)
{
if(S_OK == CAGetCAProperty(hCAInfo, CA_PROP_NAME, &wszCAName))
{
if(NULL != wszCAName)
{
if(NULL != wszCAName[0])
{
wszCurrentCA = m_pCertWizardInfo->awszValidCA;
while(*wszCurrentCA)
{
if(0 == wcscmp(*wszCurrentCA, wszCAName[0]))
{
return TRUE;
}
wszCurrentCA++;
}
}
CAFreeCAProperty(hCAInfo, wszCAName);
}
}
}
return FALSE;
}
HRESULT KeySvcContext::GetDefaultCSP(OUT BOOL *pfAllocateCSP)
{
return ::GetDefaultCSP(m_pCertWizardInfo, TRUE /*machine*/, &m_idsText, pfAllocateCSP);
}
HRESULT WhistlerMachineContext::Enroll(OUT DWORD *pdwStatus,
IN OUT HANDLE *pResult)
{
BOOL fRequestIsCached;
BOOL fCreateRequest = 0 == (m_pCertWizardInfo->dwFlags & (CRYPTUI_WIZ_SUBMIT_ONLY | CRYPTUI_WIZ_FREE_ONLY));
BOOL fFreeRequest = 0 == (m_pCertWizardInfo->dwFlags & (CRYPTUI_WIZ_CREATE_ONLY | CRYPTUI_WIZ_SUBMIT_ONLY));
BOOL fSubmitRequest = 0 == (m_pCertWizardInfo->dwFlags & (CRYPTUI_WIZ_CREATE_ONLY | CRYPTUI_WIZ_FREE_ONLY));
CERT_BLOB renewCert;
CERT_ENROLL_INFO RequestInfo;
CERT_REQUEST_PVK_NEW CertRequestPvkNew;
CERT_REQUEST_PVK_NEW CertRenewPvk;
CRYPTUI_WIZ_CERT_CA CertCA;
DWORD dwStatus = CRYPTUI_WIZ_CERT_REQUEST_STATUS_UNKNOWN;
DWORD dwCSPIndex;
DWORD dwSavedGenKeyFlags;
HANDLE hRequest = NULL;
HRESULT hr = E_FAIL;
KEYSVCC_HANDLE hKeyService = NULL;
KEYSVC_TYPE ktServiceType;
LPSTR pszMachineName = NULL;
LPWSTR pwszHashAlg = NULL;
//init 1st for error jump
ZeroMemory(&CertRenewPvk, sizeof(CertRenewPvk));
if (NULL == pResult)
return E_INVALIDARG;
if (NULL == m_pCertWizardInfo)
return E_POINTER;
memset(&renewCert, 0, sizeof(renewCert));
memset(&CertCA, 0, sizeof(CertCA));
memset(&RequestInfo, 0, sizeof(RequestInfo));
dwSavedGenKeyFlags = m_pCertWizardInfo->dwGenKeyFlags;
// An invalid combination of flags was specified.
if (FALSE == (fCreateRequest || fFreeRequest || fSubmitRequest))
return E_INVALIDARG;
// For FREE_ONLY and SUBMIT_ONLY, copy the request from the IN parameter.
if (0 != ((CRYPTUI_WIZ_SUBMIT_ONLY | CRYPTUI_WIZ_FREE_ONLY) & m_pCertWizardInfo->dwFlags))
{
if (NULL == *pResult)
return E_INVALIDARG;
hRequest = *pResult;
}
if(!MkMBStr(NULL, 0, m_pCertWizardInfo->pwszMachineName, &pszMachineName))
goto MkMBStrError;
ktServiceType = NULL != m_pCertWizardInfo->pwszAccountName ? KeySvcService : KeySvcMachine;
hr = ::KeyOpenKeyService
(pszMachineName,
ktServiceType,
(LPWSTR)(m_pCertWizardInfo->pwszAccountName),
NULL,
NULL,
&hKeyService);
_JumpConditionWithExpr(S_OK != hr, KeyOpenKeyServiceError, m_idsText = IDS_RPC_CALL_FAILED);
// Initialize to false ... we need the marshalled parameters to know whether we can cache the request.
fRequestIsCached = FALSE;
// Iterate over each CA, performing a create and submit operation for each.
// Note that we can cache requests for certs if key archival is not needed.
//
if (fCreateRequest || fSubmitRequest)
{
for (IEnumCA CAEnumerator(m_pCertWizardInfo); ; )
{
if (S_OK != (CAEnumerator.Next(&CertCA)))
{
if(!FAILED(hr))
hr=E_FAIL;
if (E_FAIL == hr)
m_pCertWizardInfo->idsText = IDS_NO_CA_FOR_ENROLL_REQUEST_FAILED;
goto ErrorReturn;
}
// Create a certificate request only if
// 1) This is not a submit-only or a free-only operation.
// 2) We don't already have a cached request.
// (We can cache requests which don't require key archival on the CA).
//
// The request is created by looping over available CSPs until one successfully generates
// the request.
//
if (TRUE == fCreateRequest && FALSE == fRequestIsCached)
{
BOOL fHasNextCSP = TRUE;
for (IEnumCSP CSPEnumerator(m_pCertWizardInfo); fHasNextCSP; )
{
_JumpCondition(S_OK != (hr = CSPEnumerator.Next(&dwCSPIndex)), ErrorReturn);
_JumpCondition(S_OK != (hr = CSPEnumerator.HasNext(&fHasNextCSP)), ErrorReturn);
// Each call to MarshallRequestParameters can change the dwGenKeyFlags of pCertWizardInfo
// if the CSP does not support the min key size contained in this field.
// As a result, we must reset the dwGenKeyFlags field to the desired value
// before every call to MarshallRequestParameters.
m_pCertWizardInfo->dwGenKeyFlags = dwSavedGenKeyFlags;
if (S_OK != (hr = ::MarshallRequestParameters
(dwCSPIndex,
m_pCertWizardInfo,
&renewCert,
&CertRequestPvkNew,
&CertRenewPvk,
&pwszHashAlg,
&RequestInfo)))
goto NextCSP;
if (NULL != hRequest)
{
this->FreeRequest(hKeyService, pszMachineName, &hRequest);
hRequest = NULL;
}
hr = this->CreateRequest
(hKeyService,
pszMachineName,
CertCA.pwszCALocation,
CertCA.pwszCAName,
&CertRequestPvkNew,
&renewCert,
&CertRenewPvk,
pwszHashAlg,
&RequestInfo,
&hRequest);
// Process the return value:
if (S_OK == hr)
{
// Success, get rid of whatever error text we have from past creations:
m_pCertWizardInfo->idsText = 0;
// We're done if we don't need to submit the request.
_JumpCondition(!fSubmitRequest, CommonReturn);
// Cache the request if we don't need support for key archival.
fRequestIsCached = 0 == (CertRequestPvkNew.dwPrivateKeyFlags & CT_FLAG_ALLOW_PRIVATE_KEY_ARCHIVAL);
break;
}
else if (E_ACCESSDENIED == HRESULT_FROM_WIN32(hr))
{
// E_ACCESSDENIED could indicate one of several different error conditions. Map this
// to an resource identifier which details the possible causes of failure, and try again...
m_pCertWizardInfo->idsText = IDS_NO_ACCESS_TO_ICERTREQUEST2;
}
else if (NTE_BAD_ALGID == HRESULT_FROM_WIN32(hr))
{
// NTE_BAD_ALGID indicates that the CSP didn't support the algorithm type required
// by the template. Map this to a resource identifier that details the possible causes
// of failure, and try again...
m_pCertWizardInfo->idsText = IDS_CSP_BAD_ALGTYPE;
}
else if (HRESULT_FROM_WIN32(ERROR_CANCELLED) == HRESULT_FROM_WIN32(hr))
{
// The user cancelled the operation. Don't try to enroll any longer.
goto ErrorReturn;
}
else
{
// It's an error, but we don't need to map it to special text. Just keep processing...
}
// We're out of CSPs, and we haven't yet created the request!
if (!fHasNextCSP)
{
// If the template doesn't require key archival, we're done. Otherwise, we've got to
// try the other CAs. Note that if we had a mechanism for knowing whether it was the
// key archival step
if (0 == (CertRequestPvkNew.dwPrivateKeyFlags & CT_FLAG_ALLOW_PRIVATE_KEY_ARCHIVAL))
goto ErrorReturn;
else
{
::FreeRequestParameters(&pwszHashAlg, &CertRenewPvk, &RequestInfo);
goto NextCA;
}
}
NextCSP:
::FreeRequestParameters(&pwszHashAlg, &CertRenewPvk, &RequestInfo);
}
}
if (TRUE == fSubmitRequest)
{
hr = this->SubmitRequest
(hKeyService,
pszMachineName,
CertCA.pwszCALocation,
CertCA.pwszCAName,
hRequest,
(PCCERT_CONTEXT *)pResult,
&dwStatus);
if (S_OK == hr)
{
// Success, get rid of whatever error text we have from past submits:
m_pCertWizardInfo->idsText = 0;
// If we've successfully submitted or pended
goto CommonReturn;
}
else if (E_ACCESSDENIED == HRESULT_FROM_WIN32(hr))
{
// E_ACCESSDENIED could indicate one of several different error conditions. Map this
// to an resource identifier which details the possible causes of failure, and try again...
m_pCertWizardInfo->idsText = IDS_SUBMIT_NO_ACCESS_TO_ICERTREQUEST2;
}
// Some error has occured.
// If it's a non-CA related error, give up...
_JumpCondition(dwStatus != CRYPTUI_WIZ_CERT_REQUEST_STATUS_REQUEST_ERROR &&
dwStatus != CRYPTUI_WIZ_CERT_REQUEST_STATUS_REQUEST_DENIED &&
dwStatus != CRYPTUI_WIZ_CERT_REQUEST_STATUS_CONNECTION_FAILED,
ErrorReturn);
// Otherwise, try another CA...
}
NextCA:;
}
}
CommonReturn:
// Write the request to pResult for a create only operation:
if (hr == S_OK && 0 != (m_pCertWizardInfo->dwFlags & CRYPTUI_WIZ_CREATE_ONLY))
{
*pResult = hRequest;
}
// Write the status code, if requested.
if (NULL != pdwStatus) { *pdwStatus = dwStatus; }
// Free resources.
if (NULL != hRequest && TRUE == fFreeRequest) { this->FreeRequest(hKeyService, pszMachineName, hRequest); }
if (NULL != hKeyService) { ::KeyCloseKeyService(hKeyService, NULL); }
if (NULL != pszMachineName) { ::FreeMBStr(NULL,pszMachineName); }
::FreeRequestParameters(&pwszHashAlg, &CertRenewPvk, &RequestInfo);
return hr;
ErrorReturn:
goto CommonReturn;
SET_HRESULT(KeyOpenKeyServiceError, hr);
SET_HRESULT(MkMBStrError, HRESULT_FROM_WIN32(GetLastError()));
}
HRESULT WhistlerMachineContext::CreateRequest
(IN KEYSVCC_HANDLE hKeyService,
IN LPSTR pszMachineName,
IN LPWSTR pwszCALocation,
IN LPWSTR pwszCAName,
IN PCERT_REQUEST_PVK_NEW pKeyNew,
IN CERT_BLOB *pCert,
IN PCERT_REQUEST_PVK_NEW pRenewKey,
IN LPWSTR pwszHashAlg,
IN PCERT_ENROLL_INFO pRequestInfo,
OUT HANDLE *phRequest)
{
DWORD dwFlags = m_pCertWizardInfo->dwFlags;
dwFlags &= ~(CRYPTUI_WIZ_SUBMIT_ONLY | CRYPTUI_WIZ_FREE_ONLY);
dwFlags |= CRYPTUI_WIZ_CREATE_ONLY;
// Create the certificate request...
return ::KeyEnroll_V2
(hKeyService,
pszMachineName,
TRUE,
m_pCertWizardInfo->dwPurpose,
dwFlags,
(LPWSTR)(m_pCertWizardInfo->pwszAccountName),
NULL,
(CRYPTUI_WIZ_CERT_ENROLL & m_pCertWizardInfo->dwPurpose) ? TRUE : FALSE,
pwszCALocation,
pwszCAName,
m_pCertWizardInfo->fNewKey,
pKeyNew,
pCert,
pRenewKey,
pwszHashAlg,
(LPWSTR)m_pCertWizardInfo->pwszDesStore,
m_pCertWizardInfo->dwStoreFlags,
pRequestInfo,
(LPWSTR)m_pCertWizardInfo->pwszRequestString,
0,
NULL,
phRequest,
NULL,
NULL,
NULL);
}
HRESULT WhistlerMachineContext::SubmitRequest
(IN KEYSVCC_HANDLE hKeyService,
IN LPSTR pszMachineName,
IN LPWSTR pwszCALocation,
IN LPWSTR pwszCAName,
IN HANDLE hRequest,
OUT PCCERT_CONTEXT *ppCertContext,
OUT DWORD *pdwStatus)
{
CERT_BLOB HashBlob;
CERT_BLOB PKCS7Blob;
HRESULT hr = E_FAIL;
memset(&HashBlob, 0, sizeof(HashBlob));
memset(&PKCS7Blob, 0, sizeof(PKCS7Blob));
DWORD dwFlags = m_pCertWizardInfo->dwFlags;
dwFlags &= ~(CRYPTUI_WIZ_CREATE_ONLY | CRYPTUI_WIZ_FREE_ONLY);
dwFlags |= CRYPTUI_WIZ_SUBMIT_ONLY;
// Submit the certificate request...
hr = ::KeyEnroll_V2
(hKeyService,
pszMachineName,
TRUE,
m_pCertWizardInfo->dwPurpose,
dwFlags,
(LPWSTR)(m_pCertWizardInfo->pwszAccountName),
NULL,
(CRYPTUI_WIZ_CERT_ENROLL & m_pCertWizardInfo->dwPurpose) ? TRUE : FALSE,
pwszCALocation,
pwszCAName,
m_pCertWizardInfo->fNewKey,
NULL,
NULL,
NULL,
NULL,
NULL,
0,
NULL,
NULL,
0,
NULL,
&hRequest,
&PKCS7Blob,
&HashBlob,
pdwStatus);
if (S_OK == hr && CRYPTUI_WIZ_CERT_REQUEST_STATUS_SUCCEEDED == *pdwStatus)
{
hr = this->ToCertContext
(&PKCS7Blob,
&HashBlob,
pdwStatus,
ppCertContext);
}
if (NULL != HashBlob.pbData) { ::WizardFree(HashBlob.pbData); }
if (NULL != PKCS7Blob.pbData) { ::WizardFree(PKCS7Blob.pbData); }
return hr;
}
void WhistlerMachineContext::FreeRequest
(IN KEYSVCC_HANDLE hKeyService,
IN LPSTR pszMachineName,
IN HANDLE hRequest)
{
DWORD dwFlags = m_pCertWizardInfo->dwFlags;
dwFlags &= ~(CRYPTUI_WIZ_CREATE_ONLY | CRYPTUI_WIZ_SUBMIT_ONLY);
dwFlags |= CRYPTUI_WIZ_FREE_ONLY;
::KeyEnroll_V2
(hKeyService,
pszMachineName,
TRUE,
0,
dwFlags,
NULL,
NULL,
FALSE,
NULL,
NULL,
FALSE,
NULL,
NULL,
NULL,
NULL,
NULL,
0,
NULL,
NULL,
0,
NULL,
&hRequest,
NULL,
NULL,
NULL);
}
HRESULT KeySvcContext::ToCertContext(IN CERT_BLOB *pPKCS7Blob,
IN CERT_BLOB *pHashBlob,
OUT DWORD *pdwStatus,
OUT PCCERT_CONTEXT *ppCertContext)
{
HCERTSTORE hCertStore = NULL;
HRESULT hr = E_FAIL;
if (NULL == pPKCS7Blob || NULL == pHashBlob || NULL == ppCertContext)
return E_INVALIDARG;
//get the certificate store from the PKCS7 for the remote case
if (!::CryptQueryObject(CERT_QUERY_OBJECT_BLOB,
pPKCS7Blob,
CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED,
CERT_QUERY_FORMAT_FLAG_ALL,
0,
NULL,
NULL,
NULL,
&hCertStore,
NULL,
NULL))
{
if (NULL != pdwStatus) { *pdwStatus = CRYPTUI_WIZ_CERT_REQUEST_STATUS_INSTALL_FAILED; }
goto FailError;
}
//find the certificate based on the hash
if (NULL == (*ppCertContext = ::CertFindCertificateInStore
(hCertStore,
X509_ASN_ENCODING,
0,
CERT_FIND_SHA1_HASH,
pHashBlob,
NULL)))
{
if (NULL != pdwStatus) { *pdwStatus = CRYPTUI_WIZ_CERT_REQUEST_STATUS_INSTALL_FAILED; }
goto FailError;
}
hr = S_OK;
CommonReturn:
if(NULL != hCertStore) { CertCloseStore(hCertStore, 0); }
return hr;
ErrorReturn:
if (NULL != pdwStatus && 0 == *pdwStatus) { *pdwStatus = CRYPTUI_WIZ_CERT_REQUEST_STATUS_KEYSVC_FAILED; }
goto CommonReturn;
SET_HRESULT(FailError, E_FAIL);
}
HRESULT KeySvcContext::Initialize()
{
if (NULL == m_pCertWizardInfo)
return E_POINTER;
// We don't need to download the list of allowed templates if we're not going
// to be performing the access check anyway.
if (0 == (m_pCertWizardInfo->dwFlags & CRYPTUI_WIZ_ALLOW_ALL_TEMPLATES))
{
//for the remote enrollment, we have to get the allowed cert type
//list from the key service.
if(!::GetCertTypeName(m_pCertWizardInfo))
{
m_idsText = IDS_NO_VALID_CERT_TEMPLATE;
return HRESULT_FROM_WIN32(GetLastError());
}
}
// We don't need to download the list of allowed CAs if we're not going
// to be performing the access check anyway
if (0 == (m_pCertWizardInfo->dwFlags & CRYPTUI_WIZ_ALLOW_ALL_CAS))
{
if(!::GetCAName(m_pCertWizardInfo))
{
m_idsText = IDS_NO_CA_FOR_ENROLL;
return HRESULT_FROM_WIN32(GetLastError());
}
}
return S_OK;
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
//
// CertRequesterContext: implementation of abstract superclass.
// See requesters.h for method-level documentation.
//
//
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
HRESULT CertRequesterContext::MakeDefaultCertRequesterContext
(OUT CertRequesterContext **ppRequesterContext)
{
CERT_WIZARD_INFO *pCertWizardInfo = NULL;
HRESULT hr;
pCertWizardInfo = (CERT_WIZARD_INFO *)WizardAlloc(sizeof(CERT_WIZARD_INFO));
_JumpCondition(NULL == pCertWizardInfo, MemoryError);
hr = MakeCertRequesterContext
(NULL,
NULL,
0,
pCertWizardInfo,
ppRequesterContext,
NULL);
_JumpCondition(S_OK != hr, MakeCertRequesterContextError);
hr = S_OK;
CommonReturn:
return hr;
ErrorReturn:
if (NULL != pCertWizardInfo) { WizardFree(pCertWizardInfo); }
goto CommonReturn;
SET_HRESULT(MakeCertRequesterContextError, hr);
SET_HRESULT(MemoryError, E_OUTOFMEMORY);
}
HRESULT CertRequesterContext::MakeCertRequesterContext
(IN LPCWSTR pwszAccountName,
IN LPCWSTR pwszMachineName,
IN DWORD dwCertOpenStoreFlags,
IN CERT_WIZARD_INFO *pCertWizardInfo,
OUT CertRequesterContext **ppRequesterContext,
OUT UINT *pIDSText)
{
BOOL fMachine = FALSE;
DWORD const dwLocalUserNameSize = UNLEN + 1;
DWORD const dwLocalMachineNameSize = MAX_COMPUTERNAME_LENGTH + 1;
HRESULT hr = E_FAIL;
UINT idsText = NULL == pIDSText ? 0 : *pIDSText;
WCHAR wszLocalUserName[dwLocalUserNameSize] = { 0 };
WCHAR wszLocalMachineName[dwLocalMachineNameSize] = { 0 };
// Input validation:
if (NULL == pCertWizardInfo || NULL == ppRequesterContext)
return E_INVALIDARG;
// Should not have assigned values to these fields yet:
if (NULL != pCertWizardInfo->pwszAccountName || NULL != pCertWizardInfo->pwszMachineName)
return E_INVALIDARG;
if(!GetUserNameU(wszLocalUserName, (DWORD *)&dwLocalUserNameSize))
{
idsText=IDS_FAIL_TO_GET_USER_NAME;
goto Win32Error;
}
if(!GetComputerNameU(wszLocalMachineName, (DWORD *)&dwLocalMachineNameSize))
{
idsText=IDS_FAIL_TO_GET_COMPUTER_NAME;
goto Win32Error;
}
// Map all unspecified values to defaults:
//
// Default #1: NULL pwszAccountName indicates current user _iff_ pwszMachineName is NULL.
if (NULL == pwszAccountName && NULL == pwszMachineName)
{ pwszAccountName = wszLocalUserName; }
// Default #2: NULL pwszMachineName indicates local machine.
if (NULL == pwszMachineName)
{ pwszMachineName = wszLocalMachineName; }
// Default #3: NULL pwszAccountName and non-NULL pwszMachineName indicates machine enrollment.
fMachine = (NULL == pwszAccountName ||
(0 != _wcsicmp(pwszAccountName, wszLocalUserName)) ||
(0 != _wcsicmp(pwszMachineName, wszLocalMachineName)));
// Default #4: dwCertOpenStoreFlags == 0 defaults to CERT_SYSTEM_STORE_LOCAL_MACHINE
// for machine enrollment, CERT_SYSTEM_STORE_CURRENT_USER for user enrollment.
if (0 == dwCertOpenStoreFlags)
{ dwCertOpenStoreFlags = fMachine ? CERT_SYSTEM_STORE_LOCAL_MACHINE : CERT_SYSTEM_STORE_CURRENT_USER; }
// Now that we've mapped unspecified values to defaults, assign the wizard's fields
// with these values:
//
if (NULL != pwszAccountName)
{
pCertWizardInfo->pwszAccountName = (LPWSTR)WizardAlloc(sizeof(WCHAR) * (wcslen(pwszAccountName) + 1));
_JumpConditionWithExpr(NULL == pCertWizardInfo->pwszAccountName, MemoryError, idsText = IDS_OUT_OF_MEMORY);
wcscpy((LPWSTR)pCertWizardInfo->pwszAccountName, pwszAccountName);
}
pCertWizardInfo->pwszMachineName = (LPWSTR)WizardAlloc(sizeof(WCHAR) * (wcslen(pwszMachineName) + 1));
_JumpConditionWithExpr(NULL == pCertWizardInfo->pwszMachineName, MemoryError, idsText = IDS_OUT_OF_MEMORY);
wcscpy((LPWSTR)pCertWizardInfo->pwszMachineName, pwszMachineName);
pCertWizardInfo->fMachine = fMachine;
pCertWizardInfo->dwStoreFlags = dwCertOpenStoreFlags;
// We need keysvc if:
//
// 1) We're doing machine enrollment (we need to run under the local machine's context).
// 2) An account _other_ than the current user on the local machine is specified.
// (we need to run under another user's context).
//
if (TRUE == fMachine)
{
KEYSVC_TYPE ktServiceType;
KEYSVC_OPEN_KEYSVC_INFO OpenKeySvcInfo = { sizeof(KEYSVC_OPEN_KEYSVC_INFO), 0 };
KEYSVCC_HANDLE hKeyService = NULL;
LPSTR pszMachineName = NULL;
ktServiceType = NULL != pwszAccountName ? KeySvcService : KeySvcMachine;
_JumpConditionWithExpr(!MkMBStr(NULL, 0, pwszMachineName, &pszMachineName), MkMBStrError, idsText = IDS_OUT_OF_MEMORY);
// See if we're enrolling for a W2K or a Whistler machine:
hr = KeyOpenKeyService
(pszMachineName,
ktServiceType,
(LPWSTR)pwszAccountName,
NULL,
NULL,
&hKeyService);
_JumpConditionWithExpr(S_OK != hr, KeyOpenKeyServiceError, idsText = IDS_RPC_CALL_FAILED);
*ppRequesterContext = new WhistlerMachineContext(pCertWizardInfo);
}
else
{
// We're requesting a cert for ourselves: we don't need keysvc.
*ppRequesterContext = new LocalContext(pCertWizardInfo);
}
if (NULL == *ppRequesterContext)
goto MemoryError;
hr = S_OK;
CommonReturn:
return hr;
ErrorReturn:
if (NULL != pCertWizardInfo->pwszMachineName) { WizardFree((LPVOID)pCertWizardInfo->pwszMachineName); }
if (NULL != pCertWizardInfo->pwszAccountName) { WizardFree((LPVOID)pCertWizardInfo->pwszAccountName); }
pCertWizardInfo->pwszMachineName = NULL;
pCertWizardInfo->pwszAccountName = NULL;
// Assign error text if specified:
if (NULL != pIDSText) { *pIDSText = idsText; }
goto CommonReturn;
SET_HRESULT(MemoryError, E_OUTOFMEMORY);
SET_HRESULT(KeyOpenKeyServiceError, hr);
SET_HRESULT(MkMBStrError, HRESULT_FROM_WIN32(GetLastError()));
SET_HRESULT(Win32Error, HRESULT_FROM_WIN32(GetLastError()));
}
CertRequesterContext::~CertRequesterContext()
{
if (NULL != m_pCertWizardInfo)
{
if (NULL != m_pCertWizardInfo->pwszMachineName) { WizardFree((LPVOID)m_pCertWizardInfo->pwszMachineName); }
if (NULL != m_pCertWizardInfo->pwszAccountName) { WizardFree((LPVOID)m_pCertWizardInfo->pwszAccountName); }
m_pCertWizardInfo->pwszMachineName = NULL;
m_pCertWizardInfo->pwszAccountName = NULL;
}
}
| 36.00219 | 140 | 0.561158 | npocmaka |
00f3236832c39fe11d14eba4cc6a3c4ef88d8ce1 | 106 | cpp | C++ | InlineFunction/inline_functions.cpp | clemaitre58/LessonsCpp | a385b30c9ca970f0be68a781a55cfe409058aa05 | [
"MIT"
] | null | null | null | InlineFunction/inline_functions.cpp | clemaitre58/LessonsCpp | a385b30c9ca970f0be68a781a55cfe409058aa05 | [
"MIT"
] | null | null | null | InlineFunction/inline_functions.cpp | clemaitre58/LessonsCpp | a385b30c9ca970f0be68a781a55cfe409058aa05 | [
"MIT"
] | 5 | 2020-04-11T20:19:27.000Z | 2020-04-14T04:20:19.000Z | #include "inline_function.h"
namespace inline_function {
int f2(const int & b) {
return b + 2;
}
}
| 10.6 | 28 | 0.650943 | clemaitre58 |
00f37d7fcff45d0055be0dcd39b51c78b43f1bff | 2,645 | hpp | C++ | irob_utils/include/irob_utils/pose.hpp | BenGab/irob-saf | 3a0fee98239bd935aa99c9d9526eb9b4cfc8963c | [
"MIT"
] | null | null | null | irob_utils/include/irob_utils/pose.hpp | BenGab/irob-saf | 3a0fee98239bd935aa99c9d9526eb9b4cfc8963c | [
"MIT"
] | null | null | null | irob_utils/include/irob_utils/pose.hpp | BenGab/irob-saf | 3a0fee98239bd935aa99c9d9526eb9b4cfc8963c | [
"MIT"
] | null | null | null | /*
* pose.hpp
*
* Author(s): Tamas D. Nagy
* Created on: 2016-10-27
*
* Class to store and make calculations on a robot arm,
* including the angle of the grippers.
*
*/
#ifndef IROB_POSE_HPP_
#define IROB_POSE_HPP_
#include <iostream>
#include <geometry_msgs/PoseStamped.h>
#include <geometry_msgs/Pose.h>
#include <geometry_msgs/Transform.h>
#include <std_msgs/Float32.h>
#include <sensor_msgs/JointState.h>
#include <Eigen/Dense>
#include <Eigen/Geometry>
#include <cmath>
#include <irob_msgs/ToolPose.h>
#include <irob_msgs/ToolPoseStamped.h>
namespace saf {
class Pose {
public:
struct Distance {
double cartesian;
double angle;
double jaw;
Distance operator*=(double);
Distance operator/=(double);
Distance operator*(double) const;
Distance operator/(double) const;
friend std::ostream& operator<<(std::ostream&, const Distance&);
};
Eigen::Vector3d position;
Eigen::Quaternion<double> orientation;
double jaw;
Pose();
Pose(double, double, double, double, double, double, double, double);
Pose(const Pose&);
Pose(const irob_msgs::ToolPose&);
Pose(const irob_msgs::ToolPoseStamped&);
Pose(const geometry_msgs::Pose&, double jaw);
Pose(const geometry_msgs::PoseStamped&, double jaw);
Pose(const Eigen::Vector3d&, const Eigen::Quaternion<double>&, double);
Pose(const geometry_msgs::Point&, const Eigen::Quaternion<double>&, double);
void swap(Pose&);
Pose operator=(const Pose&);
Pose operator+=(const Eigen::Vector3d&);
Pose operator-=(const Eigen::Vector3d&);
Pose operator+(const Eigen::Vector3d&) const;
Pose operator-(const Eigen::Vector3d&) const;
Pose interpolate(double, const Pose&) const;
Pose rotate(const Eigen::Matrix3d&) const;
Pose transform(const Eigen::Matrix3d&, const Eigen::Vector3d&, double = 1.0);
Pose invTransform(const Eigen::Matrix3d&, const Eigen::Vector3d&, double = 1.0);
Pose transform(const geometry_msgs::Transform&, double = 1.0);
Pose invTransform(const geometry_msgs::Transform&, double = 1.0);
bool isNaN() const;
Distance dist(const Pose&) const;
Distance dist(const Eigen::Vector3d&) const;
Distance dist(const Eigen::Quaternion<double>&) const;
Distance dist(double) const;
irob_msgs::ToolPose toRosToolPose() const;
geometry_msgs::Pose toRosPose() const;
sensor_msgs::JointState toRosJaw() const;
friend std::ostream& operator<<(std::ostream&, const Pose&);
friend std::istream& operator>>(std::istream&, Pose&);
};
}
#endif
| 27.552083 | 84 | 0.675992 | BenGab |
00f7543a6d3bb24b59da222ffc6530c3b8203b5b | 11,829 | cpp | C++ | src/solvers/gecode/branchers/printers.cpp | castor-software/unison | 9f8caf78230f956a57b50a327f8d1dca5839bf64 | [
"BSD-3-Clause"
] | 88 | 2016-09-27T15:20:07.000Z | 2022-03-24T15:23:06.000Z | src/solvers/gecode/branchers/printers.cpp | castor-software/unison | 9f8caf78230f956a57b50a327f8d1dca5839bf64 | [
"BSD-3-Clause"
] | 55 | 2017-02-14T15:21:03.000Z | 2021-09-11T11:12:25.000Z | src/solvers/gecode/branchers/printers.cpp | castor-software/unison | 9f8caf78230f956a57b50a327f8d1dca5839bf64 | [
"BSD-3-Clause"
] | 10 | 2016-11-22T15:03:46.000Z | 2020-07-13T21:34:31.000Z | /*
* Main authors:
* Roberto Castaneda Lozano <rcas@acm.org>
*
* This file is part of Unison, see http://unison-code.github.io
*
* Copyright (c) 2016, RISE SICS AB
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "printers.hpp"
void print_cluster_connection_decision(const Space &s, const Brancher&,
unsigned int alternative,
BoolVar, global_cluster gc, const int&,
std::ostream& out) {
const Model& m = static_cast<const Model&>(s);
vector<operand> ps = m.input->clusters[gc];
if (alternative == 1) out << "!";
out << "x(" << show(ps, ",", "p", "{}") << ")";
}
void print_cluster_disconnection_decision(const Space &s, const Brancher&,
unsigned int alternative,
BoolVar, global_cluster gc, const int&,
std::ostream& out) {
const Model& m = static_cast<const Model&>(s);
vector<operand> ps = m.input->clusters[gc];
if (alternative == 0) out << "!";
out << "x(" << show(ps, ",", "p", "{}") << ")";
}
void print_allocation_decision(const Space &s, const Brancher&,
unsigned int alternative,
SetVar, int g, const int& rs,
std::ostream& out) {
const Model& m = static_cast<const Model&>(s);
congruence c = m.input->regular[g];
out << "r(";
operand fp = m.input->congr[c][0];
if (m.input->congr[c].size() == 1)
out << "p" << fp;
else {
operand lp = m.input->congr[c][m.input->congr[c].size() - 1];
out << "{p" << fp << "..p" << lp << "}";
}
out << ") "
<< (alternative == 0 ? "->" : "-!>")
<< " " << m.input->spacename[rs];
}
void print_activation_decision(const Space &s, const Brancher&,
unsigned int alternative,
BoolVar, activation_class ac, const int&,
std::ostream& out) {
const Model& m = static_cast<const Model&>(s);
set<operation> os = m.input->activation_class_operations[ac];
if (alternative == 1) out << "!";
out << "a(" << show(os, ",", "o", "{}") << ")";
}
void print_hinted_avoidance_decision(const Space &s, const Brancher&,
unsigned int alternative,
BoolVar, int hi, const int&,
std::ostream& out) {
const Model& m = static_cast<const Model&>(s);
operand p = get<0>(m.input->avoidhints[hi]);
vector<register_atom> as = get<1>(m.input->avoidhints[hi]);
out << "r(p" << p << ") ";
out << (alternative == 0 ? "-!>" : "->");
out << " {"
<< show_register(*as.begin(), m.input->operand_width[p], m.input)
<< ".."
<< show_register(*as.rbegin(), m.input->operand_width[p], m.input)
<< "}";
}
void print_hinted_assignment_decision(const Space &s, const Brancher&,
unsigned int alternative,
BoolVar, int hi, const int&,
std::ostream& out) {
const Model& m = static_cast<const Model&>(s);
operand p = m.input->assignhints[hi][0];
register_atom ra = m.input->assignhints[hi][1];
out << "r(p" << p << ") "
<< (alternative == 0 ? "=" : "!=")
<< " " << show_register(ra, m.input->operand_width[p], m.input);
}
void print_alignment_decision(const Space &s, const Brancher&,
unsigned int alternative,
BoolVar, int a, const int&,
std::ostream& out) {
const Model& m = static_cast<const Model&>(s);
operand p = m.input->pairs[a].first, q = m.input->pairs[a].second;
if (alternative == 1) out << "!";
out << "oa(p" << p << ", p" << q << ")";
}
void print_slack_assignment_decision(const Space &s, const Brancher&,
unsigned int alternative,
IntVar, int goi, const int& slack,
std::ostream& out) {
const Model& m = static_cast<const Model&>(s);
operand p = -1;
for (operand q : m.input->P)
if (m.input->global_operand[q] && m.input->global_index[q] == goi) {
p = q;
break;
}
out << "s(p" << p << ") "
<< (alternative == 0 ? "=" : "!=")
<< " " << slack;
}
void print_assignment_decision(const Space &s, const Brancher&,
unsigned int alternative,
IntVar, int g, const int& ra,
std::ostream& out) {
const Model& m = static_cast<const Model&>(s);
congruence c = m.input->regular[g];
out << "r(";
operand fp = m.input->congr[c][0];
if (m.input->congr[c].size() == 1)
out << "p" << fp;
else {
operand lp = m.input->congr[c][m.input->congr[c].size() - 1];
out << "{p" << fp << "..p" << lp << "}";
}
out << ") "
<< (alternative == 0 ? "=" : "!=")
<< " " << show_register(ra, m.input->operand_width[fp], m.input);
}
void print_inactive_decision(const Space &s, const Brancher&,
unsigned int alternative,
BoolVar, int oi, const int&,
std::ostream& out) {
const LocalModel& m = static_cast<const LocalModel&>(s);
operation o = m.input->in[m.b] + oi;
if (alternative == 0) out << "!";
out << "a(o" << o << ")";
}
void print_active_decision(const Space &s, const Brancher& bh,
unsigned int alternative,
BoolVar b, int oi, const int& v,
std::ostream& out) {
print_inactive_decision(s, bh, !alternative, b, oi, v, out);
}
void print_global_inactive_decision(const Space &, const Brancher&,
unsigned int alternative,
BoolVar, operation o, const int&,
std::ostream& out) {
if (alternative == 0) out << "!";
out << "a(o" << o << ")";
}
void print_instruction_decision(const Space &s, const Brancher&,
unsigned int alternative,
IntVar, int oi, const int& ii,
std::ostream& out) {
const LocalModel& m = static_cast<const LocalModel&>(s);
operation o = m.input->in[m.b] + oi;
out << "i(o" << o << ") "
<< (alternative == 0 ? "=" : "!=")
<< " " << m.input->insname[m.input->instructions[o][ii]];
}
void print_global_instruction_decision(const Space &s, const Brancher&,
unsigned int alternative,
IntVar, operation o, const int& ii,
std::ostream& out) {
const Model& m = static_cast<const Model&>(s);
out << "i(o" << o << ") "
<< (alternative == 0 ? "=" : "!=")
<< " " << m.input->insname[m.input->instructions[o][ii]];
}
void print_temporary_decision(const Space &s, const Brancher&,
unsigned int alternative,
IntVar, int pi, const int& ti,
std::ostream& out) {
const LocalModel& m = static_cast<const LocalModel&>(s);
operand p = m.input->groupcopyrel[m.b][pi];
out << "y(p" << p << ") "
<< (alternative == 0 ? "=" : "!=")
<< "t" << m.input->temps[p][ti];
}
void print_global_temporary_decision(const Space &s, const Brancher&,
unsigned int alternative,
IntVar, operand p, const int& ti,
std::ostream& out) {
const Model& m = static_cast<const Model&>(s);
out << "y(p" << p << ") "
<< (alternative == 0 ? "=" : "!=")
<< "t" << m.input->temps[p][ti];
}
void print_register_decision(const Space &s, const Brancher&,
unsigned int alternative,
IntVar, int ti, const int& ra,
std::ostream& out) {
const LocalModel& m = static_cast<const LocalModel&>(s);
temporary t = m.input->tmp[m.b][0] + ti;
out << "r(t" << t << ") "
<< (alternative == 0 ? "=" : "!=")
<< " " << show_register(ra, m.input->width[t], m.input);
}
void print_global_register_decision(const Space &s, const Brancher&,
unsigned int alternative,
IntVar, temporary t, const int& ra,
std::ostream& out) {
const Model& m = static_cast<const Model&>(s);
out << "r(t" << t << ") "
<< (alternative == 0 ? "=" : "!=")
<< " " << show_register(ra, m.input->width[t], m.input);
}
void print_cycle_decision(const Space &s, const Brancher&,
unsigned int alternative,
IntVar, int oi, const int& c,
std::ostream& out) {
const LocalModel& m = static_cast<const LocalModel&>(s);
operation o = m.input->in[m.b] + oi;
out << "c(o" << o << ") "
<< (alternative == 0 ? "=" : "!=")
<< " " << c;
}
void print_global_cycle_decision(const Space &, const Brancher&,
unsigned int alternative,
IntVar, operation o, const int& c,
std::ostream& out) {
out << "c(o" << o << ") "
<< (alternative == 0 ? "=" : "!=")
<< " " << c;
}
void print_cost_decision(const Space &s, const Brancher&,
unsigned int alternative,
IntVar, int, const int& c,
std::ostream& out) {
const LocalModel& m = static_cast<const LocalModel&>(s);
out << "f(b" << m.b << ") "
<< (alternative == 0 ? "=" : "!=")
<< " " << c;
}
void print_global_cost_decision(const Space &, const Brancher&,
unsigned int alternative,
IntVar, int n, const int& c,
std::ostream& out) {
out << "cost(" << n << ") "
<< (alternative == 0 ? "=" : "!=")
<< " " << c;
}
| 41.505263 | 81 | 0.510863 | castor-software |
00f8ee486d4ba99bb23fafc09b7e6bf10f4165f7 | 23,401 | cc | C++ | gazebo/common/Mesh.cc | otamachan/ros-indigo-gazebo7-deb | abc6b40247cdce14d9912096a0ad5135d420ce04 | [
"ECL-2.0",
"Apache-2.0"
] | 5 | 2017-07-14T19:36:51.000Z | 2020-04-01T06:47:59.000Z | gazebo/common/Mesh.cc | otamachan/ros-indigo-gazebo7-deb | abc6b40247cdce14d9912096a0ad5135d420ce04 | [
"ECL-2.0",
"Apache-2.0"
] | 20 | 2017-07-20T21:04:49.000Z | 2017-10-19T19:32:38.000Z | gazebo/common/Mesh.cc | otamachan/ros-indigo-gazebo7-deb | abc6b40247cdce14d9912096a0ad5135d420ce04 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2012-2016 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <float.h>
#include <string.h>
#include <algorithm>
#include "gazebo/math/Helpers.hh"
#include "gazebo/common/Material.hh"
#include "gazebo/common/Exception.hh"
#include "gazebo/common/Console.hh"
#include "gazebo/common/Mesh.hh"
#include "gazebo/common/Skeleton.hh"
#include "gazebo/gazebo_config.h"
using namespace gazebo;
using namespace common;
//////////////////////////////////////////////////
Mesh::Mesh()
{
this->name = "unknown";
this->skeleton = NULL;
}
//////////////////////////////////////////////////
Mesh::~Mesh()
{
for (std::vector<SubMesh*>::iterator iter = this->submeshes.begin();
iter != this->submeshes.end(); ++iter)
{
delete *iter;
}
this->submeshes.clear();
for (std::vector<Material*>::iterator iter = this->materials.begin();
iter != this->materials.end(); ++iter)
{
delete *iter;
}
this->materials.clear();
delete this->skeleton;
}
//////////////////////////////////////////////////
void Mesh::SetPath(const std::string &_path)
{
this->path = _path;
}
//////////////////////////////////////////////////
std::string Mesh::GetPath() const
{
return this->path;
}
//////////////////////////////////////////////////
void Mesh::SetName(const std::string &_n)
{
this->name = _n;
}
//////////////////////////////////////////////////
std::string Mesh::GetName() const
{
return this->name;
}
//////////////////////////////////////////////////
ignition::math::Vector3d Mesh::Max() const
{
ignition::math::Vector3d max;
std::vector<SubMesh*>::const_iterator iter;
max.X(-FLT_MAX);
max.Y(-FLT_MAX);
max.Z(-FLT_MAX);
for (iter = this->submeshes.begin(); iter != this->submeshes.end(); ++iter)
{
if ((*iter)->GetVertexCount() <= 2)
continue;
ignition::math::Vector3d smax = (*iter)->Max();
max.X(std::max(max.X(), smax.X()));
max.Y(std::max(max.Y(), smax.Y()));
max.Z(std::max(max.Z(), smax.Z()));
}
return max;
}
//////////////////////////////////////////////////
ignition::math::Vector3d Mesh::Min() const
{
ignition::math::Vector3d min;
std::vector<SubMesh *>::const_iterator iter;
min.X(FLT_MAX);
min.Y(FLT_MAX);
min.Z(FLT_MAX);
for (iter = this->submeshes.begin(); iter != this->submeshes.end(); ++iter)
{
if ((*iter)->GetVertexCount() <= 2)
continue;
ignition::math::Vector3d smin = (*iter)->Min();
min.X(std::min(min.X(), smin.X()));
min.Y(std::min(min.Y(), smin.Y()));
min.Z(std::min(min.Z(), smin.Z()));
}
return min;
}
//////////////////////////////////////////////////
unsigned int Mesh::GetVertexCount() const
{
unsigned int sum = 0;
std::vector<SubMesh *>::const_iterator iter;
for (iter = this->submeshes.begin(); iter != this->submeshes.end(); ++iter)
{
if ((*iter)->GetVertexCount() <= 2)
continue;
sum += (*iter)->GetVertexCount();
}
return sum;
}
//////////////////////////////////////////////////
unsigned int Mesh::GetNormalCount() const
{
unsigned int sum = 0;
std::vector<SubMesh *>::const_iterator iter;
for (iter = this->submeshes.begin(); iter != this->submeshes.end(); ++iter)
{
if ((*iter)->GetVertexCount() <= 2)
continue;
sum += (*iter)->GetNormalCount();
}
return sum;
}
//////////////////////////////////////////////////
unsigned int Mesh::GetIndexCount() const
{
unsigned int sum = 0;
std::vector<SubMesh *>::const_iterator iter;
for (iter = this->submeshes.begin(); iter != this->submeshes.end(); ++iter)
{
if ((*iter)->GetVertexCount() <= 2)
continue;
sum += (*iter)->GetIndexCount();
}
return sum;
}
//////////////////////////////////////////////////
unsigned int Mesh::GetTexCoordCount() const
{
unsigned int sum = 0;
std::vector<SubMesh *>::const_iterator iter;
for (iter = this->submeshes.begin(); iter != this->submeshes.end(); ++iter)
{
if ((*iter)->GetVertexCount() <= 2)
continue;
sum += (*iter)->GetTexCoordCount();
}
return sum;
}
//////////////////////////////////////////////////
void Mesh::AddSubMesh(SubMesh *_sub)
{
this->submeshes.push_back(_sub);
}
//////////////////////////////////////////////////
unsigned int Mesh::GetSubMeshCount() const
{
return this->submeshes.size();
}
//////////////////////////////////////////////////
const SubMesh *Mesh::GetSubMesh(unsigned int i) const
{
if (i < this->submeshes.size())
return this->submeshes[i];
else
gzthrow("Invalid index: " << i << " >= " << this->submeshes.size() << "\n");
}
//////////////////////////////////////////////////
const SubMesh *Mesh::GetSubMesh(const std::string &_name) const
{
// Find the submesh with the provided name.
for (std::vector<SubMesh *>::const_iterator iter = this->submeshes.begin();
iter != this->submeshes.end(); ++iter)
{
if ((*iter)->GetName() == _name)
return *iter;
}
return NULL;
}
//////////////////////////////////////////////////
int Mesh::AddMaterial(Material *_mat)
{
int result = -1;
if (_mat)
{
this->materials.push_back(_mat);
result = this->materials.size()-1;
}
return result;
}
//////////////////////////////////////////////////
unsigned int Mesh::GetMaterialCount() const
{
return this->materials.size();
}
//////////////////////////////////////////////////
const Material *Mesh::GetMaterial(int index) const
{
if (index >= 0 && index < static_cast<int>(this->materials.size()))
return this->materials[index];
return NULL;
}
//////////////////////////////////////////////////
int Mesh::GetMaterialIndex(const Material *_mat) const
{
for (unsigned int i = 0; i < this->materials.size(); ++i)
{
if (this->materials[i] == _mat)
return i;
}
return -1;
}
//////////////////////////////////////////////////
void Mesh::FillArrays(float **_vertArr, int **_indArr) const
{
std::vector<SubMesh *>::const_iterator iter;
unsigned int vertCount = 0;
unsigned int indCount = 0;
for (iter = this->submeshes.begin(); iter != this->submeshes.end(); ++iter)
{
if ((*iter)->GetVertexCount() <= 2)
continue;
vertCount += (*iter)->GetVertexCount();
indCount += (*iter)->GetIndexCount();
}
if (*_vertArr)
delete [] *_vertArr;
if (*_indArr)
delete [] *_indArr;
*_vertArr = new float[vertCount * 3];
*_indArr = new int[indCount];
float *vPtr = *_vertArr;
unsigned int index = 0;
unsigned int offset = 0;
for (iter = this->submeshes.begin(); iter != this->submeshes.end(); ++iter)
{
if ((*iter)->GetVertexCount() <= 2)
continue;
float *vertTmp = NULL;
int *indTmp = NULL;
(*iter)->FillArrays(&vertTmp, &indTmp);
memcpy(vPtr, vertTmp, sizeof(vertTmp[0])*(*iter)->GetVertexCount()*3);
for (unsigned int i = 0; i < (*iter)->GetIndexCount(); ++i)
{
(*_indArr)[index++] = (*iter)->GetIndex(i) + offset;
}
offset = offset + (*iter)->GetMaxIndex() + 1;
vPtr += (*iter)->GetVertexCount()*3;
delete [] vertTmp;
delete [] indTmp;
}
}
//////////////////////////////////////////////////
void Mesh::RecalculateNormals()
{
std::vector<SubMesh*>::iterator iter;
for (iter = this->submeshes.begin(); iter != this->submeshes.end(); ++iter)
(*iter)->RecalculateNormals();
}
//////////////////////////////////////////////////
void Mesh::SetSkeleton(Skeleton* _skel)
{
this->skeleton = _skel;
}
//////////////////////////////////////////////////
Skeleton* Mesh::GetSkeleton() const
{
return this->skeleton;
}
//////////////////////////////////////////////////
bool Mesh::HasSkeleton() const
{
if (this->skeleton)
return true;
else
return false;
}
//////////////////////////////////////////////////
void Mesh::Scale(double _factor)
{
std::vector<SubMesh*>::iterator iter;
for (iter = this->submeshes.begin(); iter != this->submeshes.end(); ++iter)
(*iter)->Scale(_factor);
}
//////////////////////////////////////////////////
void Mesh::SetScale(const ignition::math::Vector3d &_factor)
{
std::vector<SubMesh*>::iterator iter;
for (iter = this->submeshes.begin(); iter != this->submeshes.end(); ++iter)
(*iter)->SetScale(_factor);
}
//////////////////////////////////////////////////
void Mesh::GenSphericalTexCoord(const ignition::math::Vector3d &_center)
{
std::vector<SubMesh*>::iterator siter;
for (siter = this->submeshes.begin(); siter != this->submeshes.end(); ++siter)
(*siter)->GenSphericalTexCoord(_center);
}
//////////////////////////////////////////////////
void Mesh::Center(const ignition::math::Vector3d &_center)
{
ignition::math::Vector3d min, max, half;
min = this->Min();
max = this->Max();
half = (max - min) * 0.5;
this->Translate(_center - (min + half));
}
//////////////////////////////////////////////////
void Mesh::Translate(const ignition::math::Vector3d &_vec)
{
std::vector<SubMesh*>::iterator iter;
for (iter = this->submeshes.begin(); iter != this->submeshes.end(); ++iter)
{
if ((*iter)->GetVertexCount() <= 2)
continue;
(*iter)->Translate(_vec);
}
}
//////////////////////////////////////////////////
//////////////////////////////////////////////////
//////////////////////////////////////////////////
SubMesh::SubMesh()
{
this->materialIndex = -1;
this->primitiveType = TRIANGLES;
}
//////////////////////////////////////////////////
SubMesh::SubMesh(const SubMesh *_mesh)
{
if (!_mesh)
{
gzerr << "Submesh is NULL." << std::endl;
return;
}
this->name = _mesh->name;
this->materialIndex = _mesh->materialIndex;
this->primitiveType = _mesh->primitiveType;
std::copy(_mesh->nodeAssignments.begin(), _mesh->nodeAssignments.end(),
std::back_inserter(this->nodeAssignments));
std::copy(_mesh->indices.begin(), _mesh->indices.end(),
std::back_inserter(this->indices));
std::copy(_mesh->normals.begin(), _mesh->normals.end(),
std::back_inserter(this->normals));
std::copy(_mesh->texCoords.begin(), _mesh->texCoords.end(),
std::back_inserter(this->texCoords));
std::copy(_mesh->vertices.begin(), _mesh->vertices.end(),
std::back_inserter(this->vertices));
}
//////////////////////////////////////////////////
SubMesh::~SubMesh()
{
this->vertices.clear();
this->indices.clear();
this->nodeAssignments.clear();
}
//////////////////////////////////////////////////
void SubMesh::SetPrimitiveType(PrimitiveType _type)
{
this->primitiveType = _type;
}
//////////////////////////////////////////////////
SubMesh::PrimitiveType SubMesh::GetPrimitiveType() const
{
return this->primitiveType;
}
//////////////////////////////////////////////////
void SubMesh::CopyVertices(const std::vector<ignition::math::Vector3d> &_verts)
{
this->vertices.clear();
this->vertices.resize(_verts.size());
std::copy(_verts.begin(), _verts.end(), this->vertices.begin());
}
//////////////////////////////////////////////////
void SubMesh::CopyNormals(const std::vector<ignition::math::Vector3d> &_norms)
{
this->normals.clear();
this->normals.resize(_norms.size());
for (unsigned int i = 0; i < _norms.size(); ++i)
{
this->normals[i] = _norms[i];
this->normals[i].Normalize();
if (ignition::math::equal(this->normals[i].Length(), 0.0))
{
this->normals[i].Set(0, 0, 1);
}
}
}
//////////////////////////////////////////////////
void SubMesh::SetVertexCount(unsigned int _count)
{
this->vertices.resize(_count);
}
//////////////////////////////////////////////////
void SubMesh::SetIndexCount(unsigned int _count)
{
this->indices.resize(_count);
}
//////////////////////////////////////////////////
void SubMesh::SetNormalCount(unsigned int _count)
{
this->normals.resize(_count);
}
//////////////////////////////////////////////////
void SubMesh::SetTexCoordCount(unsigned int _count)
{
this->texCoords.resize(_count);
}
//////////////////////////////////////////////////
void SubMesh::AddIndex(unsigned int _i)
{
this->indices.push_back(_i);
}
//////////////////////////////////////////////////
void SubMesh::AddVertex(const ignition::math::Vector3d &_v)
{
this->vertices.push_back(_v);
}
//////////////////////////////////////////////////
void SubMesh::AddVertex(double _x, double _y, double _z)
{
this->AddVertex(ignition::math::Vector3d(_x, _y, _z));
}
//////////////////////////////////////////////////
void SubMesh::AddNormal(const ignition::math::Vector3d &_n)
{
this->normals.push_back(_n);
}
//////////////////////////////////////////////////
void SubMesh::AddNormal(double _x, double _y, double _z)
{
this->AddNormal(ignition::math::Vector3d(_x, _y, _z));
}
//////////////////////////////////////////////////
void SubMesh::AddTexCoord(double _u, double _v)
{
this->texCoords.push_back(ignition::math::Vector2d(_u, _v));
}
//////////////////////////////////////////////////
void SubMesh::AddNodeAssignment(unsigned int _vertex, unsigned int _node,
float _weight)
{
NodeAssignment na;
na.vertexIndex = _vertex;
na.nodeIndex = _node;
na.weight = _weight;
this->nodeAssignments.push_back(na);
}
//////////////////////////////////////////////////
ignition::math::Vector3d SubMesh::Vertex(unsigned int _i) const
{
if (_i >= this->vertices.size())
gzthrow("Index too large");
return this->vertices[_i];
}
//////////////////////////////////////////////////
void SubMesh::SetVertex(unsigned int _i, const ignition::math::Vector3d &_v)
{
if (_i >= this->vertices.size())
gzthrow("Index too large");
this->vertices[_i] = _v;
}
//////////////////////////////////////////////////
ignition::math::Vector3d SubMesh::Normal(unsigned int _i) const
{
if (_i >= this->normals.size())
gzthrow("Index too large");
return this->normals[_i];
}
//////////////////////////////////////////////////
void SubMesh::SetNormal(unsigned int _i, const ignition::math::Vector3d &_n)
{
if (_i >= this->normals.size())
gzthrow("Index too large");
this->normals[_i] = _n;
}
//////////////////////////////////////////////////
ignition::math::Vector2d SubMesh::TexCoord(unsigned int _i) const
{
if (_i >= this->texCoords.size())
gzthrow("Index too large");
return this->texCoords[_i];
}
//////////////////////////////////////////////////
NodeAssignment SubMesh::GetNodeAssignment(unsigned int _i) const
{
if (_i >= this->nodeAssignments.size())
gzthrow("Index too large");
return this->nodeAssignments[_i];
}
//////////////////////////////////////////////////
void SubMesh::SetTexCoord(unsigned int _i, const ignition::math::Vector2d &_t)
{
if (_i >= this->texCoords.size())
gzthrow("Index too large");
this->texCoords[_i] = _t;
}
//////////////////////////////////////////////////
unsigned int SubMesh::GetIndex(unsigned int _i) const
{
if (_i > this->indices.size())
gzthrow("Index too large");
return this->indices[_i];
}
//////////////////////////////////////////////////
ignition::math::Vector3d SubMesh::Max() const
{
ignition::math::Vector3d max;
std::vector<ignition::math::Vector3d>::const_iterator iter;
max.X(-FLT_MAX);
max.Y(-FLT_MAX);
max.Z(-FLT_MAX);
for (iter = this->vertices.begin(); iter != this->vertices.end(); ++iter)
{
max.X(std::max(max.X(), (*iter).X()));
max.Y(std::max(max.Y(), (*iter).Y()));
max.Z(std::max(max.Z(), (*iter).Z()));
}
return max;
}
//////////////////////////////////////////////////
ignition::math::Vector3d SubMesh::Min() const
{
ignition::math::Vector3d min;
std::vector<ignition::math::Vector3d>::const_iterator iter;
min.X(FLT_MAX);
min.Y(FLT_MAX);
min.Z(FLT_MAX);
for (iter = this->vertices.begin(); iter != this->vertices.end(); ++iter)
{
min.X(std::min(min.X(), (*iter).X()));
min.Y(std::min(min.Y(), (*iter).Y()));
min.Z(std::min(min.Z(), (*iter).Z()));
}
return min;
}
//////////////////////////////////////////////////
unsigned int SubMesh::GetVertexCount() const
{
return this->vertices.size();
}
//////////////////////////////////////////////////
unsigned int SubMesh::GetNormalCount() const
{
return this->normals.size();
}
//////////////////////////////////////////////////
unsigned int SubMesh::GetIndexCount() const
{
return this->indices.size();
}
//////////////////////////////////////////////////
unsigned int SubMesh::GetTexCoordCount() const
{
return this->texCoords.size();
}
//////////////////////////////////////////////////
unsigned int SubMesh::GetNodeAssignmentsCount() const
{
return this->nodeAssignments.size();
}
//////////////////////////////////////////////////
unsigned int SubMesh::GetMaxIndex() const
{
std::vector<unsigned int>::const_iterator maxIter;
maxIter = std::max_element(this->indices.begin(), this->indices.end());
if (maxIter != this->indices.end())
return *maxIter;
return 0;
}
//////////////////////////////////////////////////
void SubMesh::SetMaterialIndex(unsigned int _index)
{
this->materialIndex = _index;
}
//////////////////////////////////////////////////
unsigned int SubMesh::GetMaterialIndex() const
{
return this->materialIndex;
}
//////////////////////////////////////////////////
bool SubMesh::HasVertex(const ignition::math::Vector3d &_v) const
{
std::vector< ignition::math::Vector3d >::const_iterator iter;
for (iter = this->vertices.begin(); iter != this->vertices.end(); ++iter)
if (_v.Equal(*iter))
return true;
return false;
}
//////////////////////////////////////////////////
unsigned int SubMesh::GetVertexIndex(const ignition::math::Vector3d &_v) const
{
std::vector< ignition::math::Vector3d >::const_iterator iter;
for (iter = this->vertices.begin(); iter != this->vertices.end(); ++iter)
if (_v.Equal(*iter))
return iter - this->vertices.begin();
return 0;
}
//////////////////////////////////////////////////
void SubMesh::FillArrays(float **_vertArr, int **_indArr) const
{
if (this->vertices.empty() || this->indices.empty())
gzerr << "No vertices or indices\n";
std::vector<ignition::math::Vector3d>::const_iterator viter;
std::vector<unsigned int>::const_iterator iiter;
unsigned int i;
if (*_vertArr)
delete [] *_vertArr;
if (*_indArr)
delete [] *_indArr;
*_vertArr = new float[this->vertices.size() * 3];
*_indArr = new int[this->indices.size()];
for (viter = this->vertices.begin(), i = 0; viter != this->vertices.end();
++viter)
{
(*_vertArr)[i++] = static_cast<float>((*viter).X());
(*_vertArr)[i++] = static_cast<float>((*viter).Y());
(*_vertArr)[i++] = static_cast<float>((*viter).Z());
}
for (iiter = this->indices.begin(), i = 0;
iiter != this->indices.end(); ++iiter)
{
(*_indArr)[i++] = (*iiter);
}
}
//////////////////////////////////////////////////
void SubMesh::RecalculateNormals()
{
unsigned int i;
if (normals.size() < 3)
return;
// Reset all the normals
for (i = 0; i < this->normals.size(); ++i)
this->normals[i].Set(0, 0, 0);
if (this->normals.size() != this->vertices.size())
this->normals.resize(this->vertices.size());
// For each face, which is defined by three indices, calculate the normals
for (i = 0; i < this->indices.size(); i+= 3)
{
ignition::math::Vector3d v1 = this->vertices[this->indices[i]];
ignition::math::Vector3d v2 = this->vertices[this->indices[i+1]];
ignition::math::Vector3d v3 = this->vertices[this->indices[i+2]];
ignition::math::Vector3d n = ignition::math::Vector3d::Normal(v1, v2, v3);
for (unsigned int j = 0; j< this->vertices.size(); ++j)
{
if (this->vertices[j] == v1 ||
this->vertices[j] == v2 ||
this->vertices[j] == v3)
{
this->normals[j] += n;
}
}
}
// Normalize the results
for (i = 0; i < this->normals.size(); ++i)
{
this->normals[i].Normalize();
}
}
//////////////////////////////////////////////////
void Mesh::GetAABB(ignition::math::Vector3d &_center,
ignition::math::Vector3d &_minXYZ,
ignition::math::Vector3d &_maxXYZ) const
{
// find aabb center
_minXYZ.X(1e15);
_maxXYZ.X(-1e15);
_minXYZ.Y(1e15);
_maxXYZ.Y(-1e15);
_minXYZ.Z(1e15);
_maxXYZ.Z(-1e15);
_center.X(0);
_center.Y(0);
_center.Z(0);
std::vector<SubMesh*>::const_iterator siter;
for (siter = this->submeshes.begin(); siter != this->submeshes.end(); ++siter)
{
ignition::math::Vector3d max = (*siter)->Max();
ignition::math::Vector3d min = (*siter)->Min();
_minXYZ.X(std::min(_minXYZ.X(), min.X()));
_maxXYZ.X(std::max(_maxXYZ.X(), max.X()));
_minXYZ.Y(std::min(_minXYZ.Y(), min.Y()));
_maxXYZ.Y(std::max(_maxXYZ.Y(), max.Y()));
_minXYZ.Z(std::min(_minXYZ.Z(), min.Z()));
_maxXYZ.Z(std::max(_maxXYZ.Z(), max.Z()));
}
_center.X(0.5 * (_minXYZ.X() + _maxXYZ.X()));
_center.Y(0.5 * (_minXYZ.Y() + _maxXYZ.Y()));
_center.Z(0.5 * (_minXYZ.Z() + _maxXYZ.Z()));
}
//////////////////////////////////////////////////
void SubMesh::GenSphericalTexCoord(const ignition::math::Vector3d &_center)
{
std::vector<ignition::math::Vector3d>::const_iterator viter;
for (viter = this->vertices.begin(); viter != this->vertices.end(); ++viter)
{
// generate projected texture coordinates, projected from center
// get x, y, z for computing texture coordinate projections
double x = (*viter).X() - _center.X();
double y = (*viter).Y() - _center.Y();
double z = (*viter).Z() - _center.Z();
double r = std::max(0.000001, sqrt(x*x+y*y+z*z));
double s = std::min(1.0, std::max(-1.0, z/r));
double t = std::min(1.0, std::max(-1.0, y/r));
double u = acos(s) / M_PI;
double v = acos(t) / M_PI;
this->AddTexCoord(u, v);
}
}
//////////////////////////////////////////////////
void SubMesh::Scale(double _factor)
{
for (auto &vert : this->vertices)
vert *= _factor;
}
//////////////////////////////////////////////////
void SubMesh::SetScale(const ignition::math::Vector3d &_factor)
{
for (auto &vert : this->vertices)
vert *= _factor;
}
//////////////////////////////////////////////////
void SubMesh::Center(const ignition::math::Vector3d &_center)
{
ignition::math::Vector3d min, max, half;
min = this->Min();
max = this->Max();
half = (max - min) * 0.5;
this->Translate(_center - (min + half));
}
//////////////////////////////////////////////////
void SubMesh::Translate(const ignition::math::Vector3d &_vec)
{
for (auto &vert : this->vertices)
vert += _vec;
}
//////////////////////////////////////////////////
void SubMesh::SetName(const std::string &_n)
{
this->name = _n;
}
//////////////////////////////////////////////////
std::string SubMesh::GetName() const
{
return this->name;
}
//////////////////////////////////////////////////
NodeAssignment::NodeAssignment()
: vertexIndex(0), nodeIndex(0), weight(0.0)
{
}
| 25.271058 | 80 | 0.524465 | otamachan |
00fed53ddd8627733c2a7af5922dfb3cd3de868e | 4,491 | cpp | C++ | CsPlayback/Source/CsPlayback/Public/Managers/Playback/CsConsoleCommand_Manager_Playback.cpp | closedsum/core | c3cae44a177b9684585043a275130f9c7b67fef0 | [
"Unlicense"
] | 2 | 2019-03-17T10:43:53.000Z | 2021-04-20T21:24:19.000Z | CsPlayback/Source/CsPlayback/Public/Managers/Playback/CsConsoleCommand_Manager_Playback.cpp | closedsum/core | c3cae44a177b9684585043a275130f9c7b67fef0 | [
"Unlicense"
] | null | null | null | CsPlayback/Source/CsPlayback/Public/Managers/Playback/CsConsoleCommand_Manager_Playback.cpp | closedsum/core | c3cae44a177b9684585043a275130f9c7b67fef0 | [
"Unlicense"
] | null | null | null | // Copyright 2017-2021 Closed Sum Games, Inc. All rights reserved.
#include "Managers/Playback/CsConsoleCommand_Manager_Playback.h"
#include "CsPlayback.h"
// Library
#include "Library/CsLibrary_String.h"
#include "ConsoleCommand/CsLibrary_ConsoleCommand.h"
#include "Library/CsLibrary_Valid.h"
#include "Managers/Playback/CsLibrary_Manager_Playback.h"
// Utility
#include "Utility/CsPlaybackLog.h"
// Coordinators
#include "Coordinators/ConsoleCommand/CsCoordinator_ConsoleCommand.h"
namespace NCsPlayback
{
namespace NManager
{
namespace NConsoleCommand
{
namespace NCached
{
namespace Str
{
CSPLAYBACK_API const FString CategoryName = TEXT("Manager_Playback");
CS_DEFINE_FUNCTION_NAME_AS_STRING(NCsPlayback::NManager::FConsoleCommand, Exec_PlayLatest);
}
}
}
// Enum
#pragma region
// FConsoleCommand::ECommand
#define CS_TEMP_ADD_TO_ENUM_MAP(EnumElementName) const FConsoleCommand::ECommand FConsoleCommand::NCommand::EnumElementName = FConsoleCommand::EMCommand::Get().Add(FConsoleCommand::ECommand::EnumElementName, #EnumElementName)
CS_TEMP_ADD_TO_ENUM_MAP(PlayLatest);
#undef CS_TEMP_ADD_TO_ENUM_MAP
#pragma endregion Enum
FConsoleCommand::FConsoleCommand(UObject* InRoot)
{
MyRoot = InRoot;
UCsCoordinator_ConsoleCommand* Coordinator_ConsoleCommand = UCsCoordinator_ConsoleCommand::Get(MyRoot->GetWorld()->GetGameInstance());
Handle = Coordinator_ConsoleCommand->AddManager(this);
OnDeconstruct_Event.BindUObject(Coordinator_ConsoleCommand, &UCsCoordinator_ConsoleCommand::OnDeconstructManager);
typedef NCsConsoleCommand::FInfo InfoType;
CommandInfos.Reset();
// Populate CommandInfos
{
const int32& Count = EMCommand::Get().Num();
CommandInfos.Reserve(Count);
// Play Latest
{
CommandInfos.AddDefaulted();
InfoType& Info = CommandInfos.Last();
Info.PrimaryDefinitionIndex = 0;
TArray<FString> Base;
Base.Add(TEXT("ManagerPlaybackPlayLatest"));
Base.Add(TEXT("ManagerPlayback PlayLatest"));
Base.Add(TEXT("ManagerPlayback Play Latest"));
Base.Add(TEXT("Manager Playback PlayLatest"));
Base.Add(TEXT("Manager Playback Play Latest"));
// Commands
{
TArray<FString>& Commands = Info.Commands;
Commands.Reset(Base.Num());
for (FString& Str : Base)
{
Commands.Add(Str.ToLower());
}
}
// Definitions
{
TArray<FString>& Definitions = Info.Definitions;
Definitions.Reset(Base.Num());
for (FString& Str : Base)
{
Definitions.Add(Str);
}
}
// Description
{
FString& Description = Info.Description;
Description += TEXT("Call the command Spawn.\n");
Description += TEXT("- Checks for the following console commands:\n");
for (FString& Str : Info.Definitions)
{
Description += TEXT("-- ") + Str + TEXT("\n");
}
}
}
}
}
FConsoleCommand::~FConsoleCommand()
{
OnDeconstruct_Event.Execute(this, Handle);
}
// ConsoleCommandManagerType (NCsConsoleCommand::NManager::IManager)
#pragma region
bool FConsoleCommand::Exec(UWorld* InWorld, const TCHAR* Cmd, FOutputDevice& Out /*=*GLog*/)
{
// ManagerPlaybackPlayLatest
// ManagerPlayback PlayLatest
// ManagerPlayback Play Latest
// Manager Playback PlayLatest
// Manager Playback Play Latest
if (Exec_PlayLatest(Cmd))
return true;
return false;
}
#pragma endregion ConsoleCommandManagerType (NCsConsoleCommand::NManager::IManager)
bool FConsoleCommand::Exec_PlayLatest(const TCHAR* Cmd)
{
using namespace NConsoleCommand::NCached;
const FString& Context = Str::Exec_PlayLatest;
void(*Log)(const FString&) = &NCsPlayback::FLog::Warning;
FString OutString;
FParse::Line(&Cmd, OutString, true);
OutString.ToLower();
const TArray<FString>& Commands = CommandInfos[(uint8)ECommand::PlayLatest].Commands;
const TArray<FString>& Definitions = CommandInfos[(uint8)ECommand::PlayLatest].Definitions;
const int32 Count = Commands.Num();
for (int32 I = 0; I < Count; ++I)
{
const FString& Command = Commands[I];
const FString& Definition = Definitions[I];
if (OutString.RemoveFromStart(Command))
{
CS_IS_PTR_NULL(MyRoot)
typedef NCsPlayback::NManager::NPlayback::FLibrary PlaybackLibrary;
PlaybackLibrary::SafePlayLatest(Context, MyRoot);
return true;
}
}
return false;
}
}
} | 26.263158 | 227 | 0.701403 | closedsum |
2e0047ba2a64dfec0600572a88b1dab5192ed2d2 | 1,151 | cpp | C++ | answers/leetcode/Course Schedule/Course Schedule.cpp | FeiZhan/Algo-Collection | 708c4a38112e0b381864809788b9e44ac5ae4d05 | [
"MIT"
] | 3 | 2015-09-04T21:32:31.000Z | 2020-12-06T00:37:32.000Z | answers/leetcode/Course Schedule/Course Schedule.cpp | FeiZhan/Algo-Collection | 708c4a38112e0b381864809788b9e44ac5ae4d05 | [
"MIT"
] | null | null | null | answers/leetcode/Course Schedule/Course Schedule.cpp | FeiZhan/Algo-Collection | 708c4a38112e0b381864809788b9e44ac5ae4d05 | [
"MIT"
] | null | null | null | //@type Depth-first Search Breadth-first Search Graph Topological Sort
//@result 34 / 34 test cases passed. Status: Accepted Runtime: 340 ms Submitted: 2 minutes ago You are here! Your runtime beats 18.56% of cpp submissions.
class Solution {
public:
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<vector<int> > course_mat(numCourses, vector<int> ());
for (size_t i = 0; i < prerequisites.size(); ++ i) {
course_mat[prerequisites[i].first].push_back(prerequisites[i].second);
}
vector<int> visit_flag(numCourses, 0);
for (size_t i = 0; i < numCourses; ++ i) {
if (! dfs(i, course_mat, visit_flag)) {
return false;
}
}
return true;
}
bool dfs(size_t current, const vector<vector<int> > &course_mat, vector<int> &visit_list) {
//cout << "test " << current << " " << visit_list[current] << endl;
if (1 == visit_list[current]) {
return false;
}
visit_list[current] = 1;
for (size_t i = 0; i < course_mat[current].size(); ++ i) {
if (! dfs(course_mat[current][i], course_mat, visit_list)) {
return false;
}
}
visit_list[current] = 2;
return true;
}
}; | 34.878788 | 154 | 0.652476 | FeiZhan |
2e020e92764220368bb0d69be82d6a01daafd9bb | 2,797 | cpp | C++ | tools/llir-nm/nm.cpp | nandor/genm-opt | b3347d508fff707837d1dc8232487ebfe157fe2a | [
"MIT"
] | 13 | 2020-06-25T18:26:54.000Z | 2021-02-16T03:14:38.000Z | tools/llir-nm/nm.cpp | nandor/genm-opt | b3347d508fff707837d1dc8232487ebfe157fe2a | [
"MIT"
] | 3 | 2020-07-01T01:39:47.000Z | 2022-01-24T23:47:12.000Z | tools/llir-nm/nm.cpp | nandor/genm-opt | b3347d508fff707837d1dc8232487ebfe157fe2a | [
"MIT"
] | 2 | 2021-03-11T05:08:09.000Z | 2021-07-17T23:36:17.000Z | // This file if part of the llir-opt project.
// Licensing information can be found in the LICENSE file.
// (C) 2018 Nandor Licker. All rights reserved.
#include <llvm/Support/CommandLine.h>
#include <llvm/Support/FileSystem.h>
#include <llvm/Support/InitLLVM.h>
#include <llvm/Support/MemoryBuffer.h>
#include <llvm/Support/ToolOutputFile.h>
#include <llvm/Object/ArchiveWriter.h>
#include "core/bitcode.h"
#include "core/parser.h"
#include "core/printer.h"
#include "core/prog.h"
#include "core/util.h"
namespace cl = llvm::cl;
namespace sys = llvm::sys;
// -----------------------------------------------------------------------------
static llvm::StringRef ToolName;
// -----------------------------------------------------------------------------
static void exitIfError(llvm::Error e, llvm::Twine ctx)
{
if (!e) {
return;
}
llvm::handleAllErrors(std::move(e), [&](const llvm::ErrorInfoBase &e) {
llvm::WithColor::error(llvm::errs(), ToolName)
<< ctx << ": " << e.message() << "\n";
});
exit(EXIT_FAILURE);
}
// -----------------------------------------------------------------------------
static cl::list<std::string>
optInputs(cl::Positional, cl::desc("<input>"), cl::OneOrMore);
// -----------------------------------------------------------------------------
static void DumpSymbols(llvm::raw_ostream &os, const Prog &prog)
{
os << prog.getName() << ":\n";
for (const Extern &ext : prog.externs()) {
os << " U " << ext.getName() << "\n";
}
for (const Func &func : prog) {
os << "0000000000000000 T " << func.getName() << "\n";
}
for (const Data &data : prog.data()) {
for (const Object &object : data) {
for (const Atom &atom : object) {
os << "0000000000000000 D " << atom.getName() << "\n";
}
}
}
}
// -----------------------------------------------------------------------------
int main(int argc, char **argv)
{
ToolName = argc > 0 ? argv[0] : "llir-nm";
llvm::InitLLVM X(argc, argv);
// Parse command line options.
if (!llvm::cl::ParseCommandLineOptions(argc, argv, "LLBC dumper\n\n")) {
return EXIT_FAILURE;
}
for (auto input : optInputs) {
// Open the input.
auto FileOrErr = llvm::MemoryBuffer::getFileOrSTDIN(input);
if (auto EC = FileOrErr.getError()) {
llvm::errs() << "[Error] Cannot open input: " + EC.message();
return EXIT_FAILURE;
}
auto memBufferRef = FileOrErr.get()->getMemBufferRef();
auto buffer = memBufferRef.getBuffer();
if (IsLLIRObject(buffer)) {
std::unique_ptr<Prog> prog(BitcodeReader(buffer).Read());
if (!prog) {
return EXIT_FAILURE;
}
DumpSymbols(llvm::outs(), *prog);
} else {
llvm_unreachable("not implemented");
}
}
return EXIT_SUCCESS;
}
| 28.540816 | 80 | 0.532356 | nandor |
2e0248ed36e354be4559edf74ad6f329a90c293a | 1,613 | cc | C++ | ceee/ie/plugin/bho/events_funnel_unittest.cc | Gitman1989/chromium | 2b1cceae1075ef012fb225deec8b4c8bbe4bc897 | [
"BSD-3-Clause"
] | 2 | 2017-09-02T19:08:28.000Z | 2021-11-15T15:15:14.000Z | ceee/ie/plugin/bho/events_funnel_unittest.cc | Gitman1989/chromium | 2b1cceae1075ef012fb225deec8b4c8bbe4bc897 | [
"BSD-3-Clause"
] | null | null | null | ceee/ie/plugin/bho/events_funnel_unittest.cc | Gitman1989/chromium | 2b1cceae1075ef012fb225deec8b4c8bbe4bc897 | [
"BSD-3-Clause"
] | 1 | 2020-04-13T05:45:10.000Z | 2020-04-13T05:45:10.000Z | // Copyright (c) 2010 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.
//
// Unit tests for EventsFunnel.
#include "base/json/json_writer.h"
#include "base/values.h"
#include "ceee/ie/common/ceee_module_util.h"
#include "ceee/ie/plugin/bho/events_funnel.h"
#include "ceee/testing/utils/mock_static.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace {
using testing::StrEq;
// Test subclass used to provide access to protected functionality in the
// EventsFunnel class.
class TestEventsFunnel : public EventsFunnel {
public:
HRESULT CallSendEvent(const char* event_name, const Value& event_args) {
return SendEvent(event_name, event_args);
}
MOCK_METHOD2(SendEventToBroker, HRESULT(const char*, const char*));
};
TEST(EventsFunnelTest, SendEvent) {
TestEventsFunnel events_funnel;
static const char* kEventName = "MADness";
DictionaryValue event_args;
event_args.SetInteger("Answer to the Ultimate Question of Life,"
"the Universe, and Everything", 42);
event_args.SetString("AYBABTU", "All your base are belong to us");
event_args.SetReal("www.unrealtournament.com", 3.0);
ListValue args_list;
args_list.Append(event_args.DeepCopy());
std::string event_args_str;
base::JSONWriter::Write(&args_list, false, &event_args_str);
EXPECT_CALL(events_funnel, SendEventToBroker(StrEq(kEventName),
StrEq(event_args_str))).Times(1);
EXPECT_HRESULT_SUCCEEDED(
events_funnel.CallSendEvent(kEventName, event_args));
}
} // namespace
| 30.433962 | 74 | 0.743955 | Gitman1989 |
2e0291cdbfd04525931fa716a2d277b6793cab84 | 17,411 | cpp | C++ | JHSeng's work/report/src/USBCore.cpp | JHSeng/ros_experiment | d5ec652e8f2d79e76b896b69757090d953ff6653 | [
"MIT"
] | null | null | null | JHSeng's work/report/src/USBCore.cpp | JHSeng/ros_experiment | d5ec652e8f2d79e76b896b69757090d953ff6653 | [
"MIT"
] | null | null | null | JHSeng's work/report/src/USBCore.cpp | JHSeng/ros_experiment | d5ec652e8f2d79e76b896b69757090d953ff6653 | [
"MIT"
] | null | null | null | #include "USBAPI.h"
#include "PluggableUSB.h"
#include <stdlib.h>
#if defined(USBCON)
/**脉冲生成计数器,用于跟踪每种脉冲类型剩余的毫秒数*/
#define TX_RX_LED_PULSE_MS 100
volatile u8 TxLEDPulse; /** <数据Tx LED脉冲剩余的毫秒数*/
volatile u8 RxLEDPulse; /** <剩余的毫秒数用于数据接收LED脉冲*/
extern const u16 STRING_LANGUAGE[] PROGMEM;
extern const u8 STRING_PRODUCT[] PROGMEM;
extern const u8 STRING_MANUFACTURER[] PROGMEM;
extern const DeviceDescriptor USB_DeviceDescriptorIAD PROGMEM;
const u16 STRING_LANGUAGE[2] = {
(3 << 8) | (2 + 2),
0x0409 // English
};
#ifndef USB_PRODUCT
// 如果未提供产品,使用USB IO板
#define USB_PRODUCT "USB IO Board"
#endif
const u8 STRING_PRODUCT[] PROGMEM = USB_PRODUCT;
#if USB_VID == 0x2341
# if defined(USB_MANUFACTURER)
# undef USB_MANUFACTURER
# endif
# define USB_MANUFACTURER "Arduino LLC"
#elif USB_VID == 0x1b4f
# if defined(USB_MANUFACTURER)
# undef USB_MANUFACTURER
# endif
# define USB_MANUFACTURER "SparkFun"
#elif !defined(USB_MANUFACTURER)
// 如果宏中未提供制造商名称,则失败
# define USB_MANUFACTURER "Unknown"
#endif
const u8 STRING_MANUFACTURER[] PROGMEM = USB_MANUFACTURER;
#define DEVICE_CLASS 0x02
// 设备描述器
const DeviceDescriptor USB_DeviceDescriptorIAD =
D_DEVICE(0xEF, 0x02, 0x01, 64, USB_VID, USB_PID, 0x100, IMANUFACTURER, IPRODUCT, ISERIAL, 1);
volatile u8 _usbConfiguration = 0;
volatile u8 _usbCurrentStatus = 0; // 由GetStatus()请求返回到设备的信息
volatile u8 _usbSuspendState = 0; // UDINT的副本以检查SUSPI和WAKEUPI位
static inline void WaitIN(void) {
while (!(UEINTX & (1 << TXINI)));
}
static inline void ClearIN(void) {
UEINTX = ~(1 << TXINI);
}
static inline void WaitOUT(void) {
while (!(UEINTX & (1 << RXOUTI)));
}
static inline u8 WaitForINOrOUT() {
while (!(UEINTX & ((1 << TXINI) | (1 << RXOUTI))));
return (UEINTX & (1 << RXOUTI)) == 0;
}
static inline void ClearOUT(void) {
UEINTX = ~(1 << RXOUTI);
}
static inline void Recv(volatile u8 *data, u8 count) {
while (count--) *data++ = UEDATX;
RXLED1; // 点亮RX LED
RxLEDPulse = TX_RX_LED_PULSE_MS;
}
static inline u8 Recv8() {
RXLED1; // 点亮RX LED
RxLEDPulse = TX_RX_LED_PULSE_MS;
return UEDATX;
}
static inline void Send8(u8 d) {
UEDATX = d;
}
static inline void SetEP(u8 ep) {
UENUM = ep;
}
static inline u8 FifoByteCount() {
return UEBCLX;
}
static inline u8 ReceivedSetupInt() {
return UEINTX & (1 << RXSTPI);
}
static inline void ClearSetupInt() {
UEINTX = ~((1 << RXSTPI) | (1 << RXOUTI) | (1 << TXINI));
}
static inline void Stall() {
UECONX = (1 << STALLRQ) | (1 << EPEN);
}
static inline u8 ReadWriteAllowed() {
return UEINTX & (1 << RWAL);
}
static inline u8 Stalled() {
return UEINTX & (1 << STALLEDI);
}
static inline u8 FifoFree() {
return UEINTX & (1 << FIFOCON);
}
static inline void ReleaseRX() {
UEINTX = 0x6B; // FIFOCON=0 NAKINI=1 RWAL=1 NAKOUTI=0 RXSTPI=1 RXOUTI=0 STALLEDI=1 TXINI=1
}
static inline void ReleaseTX() {
UEINTX = 0x3A; // FIFOCON=0 NAKINI=0 RWAL=1 NAKOUTI=1 RXSTPI=1 RXOUTI=0 STALLEDI=1 TXINI=0
}
static inline u8 FrameNumber() {
return UDFNUML;
}
u8 USBGetConfiguration(void) {
return _usbConfiguration;
}
#define USB_RECV_TIMEOUT
class LockEP {
u8 _sreg;
public:
LockEP(u8 ep) : _sreg(SREG) {
cli();
SetEP(ep & 7);
}
~LockEP() {
SREG = _sreg;
}
};
// 字节数(假设为RX端点)
u8 USB_Available(u8 ep) {
LockEP lock(ep);
return FifoByteCount();
}
// 非阻塞接收
// 返回读取的字节数
int USB_Recv(u8 ep, void *d, int len) {
if (!_usbConfiguration || len < 0) return -1;
LockEP lock(ep);
u8 n = FifoByteCount();
len = min(n, len);
n = len;
u8 *dst = (u8 *)d;
while (n--) *dst++ = Recv8();
// 释放空缓冲区
if (len && !FifoByteCount()) ReleaseRX();
return len;
}
// 如果准备好,接收1byte
int USB_Recv(u8 ep) {
u8 c;
if (USB_Recv(ep, &c, 1) != 1) return -1;
return c;
}
// 发送EP的空间
u8 USB_SendSpace(u8 ep) {
LockEP lock(ep);
if (!ReadWriteAllowed()) return 0;
return USB_EP_SIZE - FifoByteCount();
}
// 禁止向端点发送数据
int USB_Send(u8 ep, const void *d, int len) {
if (!_usbConfiguration) return -1;
if (_usbSuspendState & (1 << SUSPI)) {
// 发送远程唤醒
UDCON |= (1 << RMWKUP);
}
int r = len;
const u8 *data = (const u8 *)d;
u8 timeout = 250; // 250ms超时则再次发送
bool sendZlp = false;
while (len || sendZlp) {
u8 n = USB_SendSpace(ep);
if (n == 0) {
if (!(--timeout)) return -1;
delay(1);
continue;
}
if (n > len) n = len;
{
LockEP lock(ep);
// SOF中断处理程序可能已释放帧
if (!ReadWriteAllowed()) continue;
len -= n;
if (ep & TRANSFER_ZERO) {
while (n--) Send8(0);
} else if (ep & TRANSFER_PGM) {
while (n--) Send8(pgm_read_byte(data++));
} else {
while (n--) Send8(*data++);
}
if (sendZlp) {
ReleaseTX();
sendZlp = false;
} else if (!ReadWriteAllowed()) { // 如果缓冲区满,释放之
ReleaseTX();
if (len == 0) sendZlp = true;
} else if ((len == 0) && (ep & TRANSFER_RELEASE)) { // 用TRANSFER_RELEASE强行释放
// 从未使用过TRANSFER_RELEASE,是否可以删除?
ReleaseTX();
}
}
}
TXLED1; // 点亮TX LED
TxLEDPulse = TX_RX_LED_PULSE_MS;
return r;
}
u8 _initEndpoints[USB_ENDPOINTS] = {
0, // 控制端点
EP_TYPE_INTERRUPT_IN, // CDC_ENDPOINT_ACM
EP_TYPE_BULK_OUT, // CDC_ENDPOINT_OUT
EP_TYPE_BULK_IN, // CDC_ENDPOINT_IN
// 接下来的端点都被初始化为0
};
#define EP_SINGLE_64 0x32 // EP0
#define EP_DOUBLE_64 0x36 // 其他端点
#define EP_SINGLE_16 0x12
static
void InitEP(u8 index, u8 type, u8 size) {
UENUM = index;
UECONX = (1 << EPEN);
UECFG0X = type;
UECFG1X = size;
}
static
void InitEndpoints() {
for (u8 i = 1; i < sizeof(_initEndpoints) && _initEndpoints[i] != 0; i++) {
UENUM = i;
UECONX = (1 << EPEN);
UECFG0X = _initEndpoints[i];
#if USB_EP_SIZE == 16
UECFG1X = EP_SINGLE_16;
#elif USB_EP_SIZE == 64
UECFG1X = EP_DOUBLE_64;
#else
#error Unsupported value for USB_EP_SIZE
#endif
}
UERST = 0x7E; // 重置它们
UERST = 0;
}
// 处理CLASS_INTERFACE请求
static
bool ClassInterfaceRequest(USBSetup &setup) {
u8 i = setup.wIndex;
if (CDC_ACM_INTERFACE == i) return CDC_Setup(setup);
#ifdef PLUGGABLE_USB_ENABLED
return PluggableUSB().setup(setup);
#endif
return false;
}
static int _cmark;
static int _cend;
void InitControl(int end) {
SetEP(0);
_cmark = 0;
_cend = end;
}
static
bool SendControl(u8 d) {
if (_cmark < _cend) {
if (!WaitForINOrOUT()) return false;
Send8(d);
if (!((_cmark + 1) & 0x3F)) ClearIN(); // fifo满,释放之
}
_cmark++;
return true;
}
// 被_cmark / _cend裁剪
int USB_SendControl(u8 flags, const void *d, int len) {
int sent = len;
const u8 *data = (const u8 *)d;
bool pgm = flags & TRANSFER_PGM;
while (len--) {
u8 c = pgm ? pgm_read_byte(data++) : *data++;
if (!SendControl(c))
return -1;
}
return sent;
}
// 发送USB描述符字符串。该字符串作为一个纯ASCII字符串存储在PROGMEM中,以正确的2字节作为UTF-16发送字首
static bool USB_SendStringDescriptor(const u8 *string_P, u8 string_len, uint8_t flags) {
SendControl(2 + string_len * 2);
SendControl(3);
bool pgm = flags & TRANSFER_PGM;
for (u8 i = 0; i < string_len; i++) {
bool r = SendControl(pgm ? pgm_read_byte(&string_P[i]) : string_P[i]);
r &= SendControl(0); // 高位
if (!r) return false;
}
return true;
}
// 不会超时或跨越FIFO边界
int USB_RecvControl(void *d, int len) {
auto length = len;
while (length) {
// 收到的收益不超过USB Control EP所能提供的。使用固定的64,因为控制EP即使在16u2上也始终具有64个字节。
auto recvLength = length;
if (recvLength > 64) recvLength = 64;
// 写入数据以适合数组的结尾(而不是开头)
WaitOUT();
Recv((u8 *)d + len - length, recvLength);
ClearOUT();
length -= recvLength;
}
return len;
}
static u8 SendInterfaces() {
u8 interfaces = 0;
CDC_GetInterface(&interfaces);
#ifdef PLUGGABLE_USB_ENABLED
PluggableUSB().getInterface(&interfaces);
#endif
return interfaces;
}
// 构造动态配置描述符,需要动态的端点分配等
static
bool SendConfiguration(int maxlen) {
// 计数和度量接口
InitControl(0);
u8 interfaces = SendInterfaces();
ConfigDescriptor config = D_CONFIG(_cmark + sizeof(ConfigDescriptor), interfaces);
// 发送数据
InitControl(maxlen);
USB_SendControl(0, &config, sizeof(ConfigDescriptor));
SendInterfaces();
return true;
}
static
bool SendDescriptor(USBSetup &setup) {
int ret;
u8 t = setup.wValueH;
if (USB_CONFIGURATION_DESCRIPTOR_TYPE == t) return SendConfiguration(setup.wLength);
InitControl(setup.wLength);
#ifdef PLUGGABLE_USB_ENABLED
ret = PluggableUSB().getDescriptor(setup);
if (ret != 0) return (ret > 0 ? true : false);
#endif
const u8 *desc_addr = 0;
if (USB_DEVICE_DESCRIPTOR_TYPE == t) {
desc_addr = (const u8 *)&USB_DeviceDescriptorIAD;
} else if (USB_STRING_DESCRIPTOR_TYPE == t) {
if (setup.wValueL == 0) {
desc_addr = (const u8 *)&STRING_LANGUAGE;
} else if (setup.wValueL == IPRODUCT) {
return USB_SendStringDescriptor(STRING_PRODUCT, strlen(USB_PRODUCT), TRANSFER_PGM);
} else if (setup.wValueL == IMANUFACTURER) {
return USB_SendStringDescriptor(STRING_MANUFACTURER, strlen(USB_MANUFACTURER), TRANSFER_PGM);
} else if (setup.wValueL == ISERIAL) {
#ifdef PLUGGABLE_USB_ENABLED
char name[ISERIAL_MAX_LEN];
PluggableUSB().getShortName(name);
return USB_SendStringDescriptor((uint8_t *)name, strlen(name), 0);
#endif
} else return false;
}
if (desc_addr == 0) return false;
u8 desc_length = pgm_read_byte(desc_addr);
USB_SendControl(TRANSFER_PGM, desc_addr, desc_length);
return true;
}
// 端点0中断
ISR(USB_COM_vect) {
SetEP(0);
if (!ReceivedSetupInt()) return;
USBSetup setup;
Recv((u8 *)&setup, 8);
ClearSetupInt();
u8 requestType = setup.bmRequestType;
if (requestType & REQUEST_DEVICETOHOST) WaitIN();
else ClearIN();
bool ok = true;
if (REQUEST_STANDARD == (requestType & REQUEST_TYPE)) {
// 标准请求
u8 r = setup.bRequest;
u16 wValue = setup.wValueL | (setup.wValueH << 8);
if (GET_STATUS == r) {
if (requestType == (REQUEST_DEVICETOHOST | REQUEST_STANDARD | REQUEST_DEVICE)) {
Send8(_usbCurrentStatus);
Send8(0);
} else {
// TODO:在此处处理端点的HALT状态
Send8(0); Send8(0);
}
} else if (CLEAR_FEATURE == r) {
if ((requestType == (REQUEST_HOSTTODEVICE | REQUEST_STANDARD | REQUEST_DEVICE))
&& (wValue == DEVICE_REMOTE_WAKEUP)) {
_usbCurrentStatus &= ~FEATURE_REMOTE_WAKEUP_ENABLED;
}
} else if (SET_FEATURE == r) {
if ((requestType == (REQUEST_HOSTTODEVICE | REQUEST_STANDARD | REQUEST_DEVICE))
&& (wValue == DEVICE_REMOTE_WAKEUP)) {
_usbCurrentStatus |= FEATURE_REMOTE_WAKEUP_ENABLED;
}
} else if (SET_ADDRESS == r) {
WaitIN();
UDADDR = setup.wValueL | (1 << ADDEN);
} else if (GET_DESCRIPTOR == r) {
ok = SendDescriptor(setup);
} else if (SET_DESCRIPTOR == r) {
ok = false;
} else if (GET_CONFIGURATION == r) {
Send8(1);
} else if (SET_CONFIGURATION == r) {
if (REQUEST_DEVICE == (requestType & REQUEST_RECIPIENT)) {
InitEndpoints();
_usbConfiguration = setup.wValueL;
} else
ok = false;
} else if (GET_INTERFACE == r) {
} else if (SET_INTERFACE == r) {
}
} else {
InitControl(setup.wLength); // 传输的最大容量
ok = ClassInterfaceRequest(setup);
}
if (ok) ClearIN();
else Stall();
}
void USB_Flush(u8 ep) {
SetEP(ep);
if (FifoByteCount()) ReleaseTX();
}
static inline void USB_ClockDisable() {
#if defined(OTGPADE)
USBCON = (USBCON & ~(1 << OTGPADE)) | (1 << FRZCLK); // 冻结时钟并禁用VBUS Pad
#else // u2系列
USBCON = (1 << FRZCLK); // 冻结时钟
#endif
PLLCSR &= ~(1 << PLLE); // 停止PLL
}
static inline void USB_ClockEnable() {
#if defined(UHWCON)
UHWCON |= (1 << UVREGE); // 电源内部寄存器
#endif
USBCON = (1 << USBE) | (1 << FRZCLK); // 时钟冻结,USB启用
// ATmega32U4
#if defined(PINDIV)
#if F_CPU == 16000000UL
PLLCSR |= (1 << PINDIV); // 需要 16 MHz xtal
#elif F_CPU == 8000000UL
PLLCSR &= ~(1 << PINDIV); // 需要 8 MHz xtal
#else
#error "Clock rate of F_CPU not supported"
#endif
#elif defined(__AVR_AT90USB82__) || defined(__AVR_AT90USB162__) || defined(__AVR_ATmega32U2__) || defined(__AVR_ATmega16U2__) || defined(__AVR_ATmega8U2__)
// 对于u2系列,数据表令人困惑。 在第40页上称为PINDIV,在第290页上称为PLLP0
#if F_CPU == 16000000UL
// 需要 16 MHz xtal
PLLCSR |= (1 << PLLP0);
#elif F_CPU == 8000000UL
// 需要 8 MHz xtal
PLLCSR &= ~(1 << PLLP0);
#endif
// AT90USB646, AT90USB647, AT90USB1286, AT90USB1287
#elif defined(PLLP2)
#if F_CPU == 16000000UL
#if defined(__AVR_AT90USB1286__) || defined(__AVR_AT90USB1287__)
// 用于Atmel AT90USB128x. 不要用于 Atmel AT90USB64x.
PLLCSR = (PLLCSR & ~(1 << PLLP1)) | ((1 << PLLP2) | (1 << PLLP0)); // 需要 16 MHz xtal
#elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB647__)
// 用于AT90USB64x. 不要用于 AT90USB128x.
PLLCSR = (PLLCSR & ~(1 << PLLP0)) | ((1 << PLLP2) | (1 << PLLP1)); // 需要 16 MHz xtal
#else
#error "USB Chip not supported, please defined method of USB PLL initialization"
#endif
#elif F_CPU == 8000000UL
// 用于Atmel AT90USB128x and AT90USB64x
PLLCSR = (PLLCSR & ~(1 << PLLP2)) | ((1 << PLLP1) | (1 << PLLP0)); // 需要 8 MHz xtal
#else
#error "Clock rate of F_CPU not supported"
#endif
#else
#error "USB Chip not supported, please defined method of USB PLL initialization"
#endif
PLLCSR |= (1 << PLLE);
while (!(PLLCSR & (1 << PLOCK))) {} // 等待锁定
// 在特定版本的macosx(10.7.3)上进行了一些测试,报告了一些使用串行重置板时的奇怪行为
// 通过端口触摸速度为1200 bps。 此延迟可以解决此问题。
delay(1);
#if defined(OTGPADE)
USBCON = (USBCON & ~(1 << FRZCLK)) | (1 << OTGPADE); // 启动USB clock, enable VBUS Pad
#else
USBCON &= ~(1 << FRZCLK); // 启动USB clock
#endif
#if defined(RSTCPU)
#if defined(LSM)
UDCON &= ~((1 << RSTCPU) | (1 << LSM) | (1 << RMWKUP) | (1 << DETACH)); // 启用连接电阻,设置全速模式
#else // u2 Series
UDCON &= ~((1 << RSTCPU) | (1 << RMWKUP) | (1 << DETACH)); // 启用连接电阻,设置全速模式
#endif
#else
// AT90USB64x和AT90USB128x没有RSTCPU
UDCON &= ~((1 << LSM) | (1 << RMWKUP) | (1 << DETACH)); // 启用连接电阻,设置全速模式
#endif
}
// 普通中断
ISR(USB_GEN_vect) {
u8 udint = UDINT;
UDINT &= ~((1 << EORSTI) | (1 << SOFI)); // 清除此处要处理的IRQ的IRQ标志,WAKEUPI和SUSPI除外
// 重置
if (udint & (1 << EORSTI)) {
InitEP(0, EP_TYPE_CONTROL, EP_SINGLE_64); // 初始化ep0
_usbConfiguration = 0; // 没有设置
UEIENX = 1 << RXSTPE; // 为ep0启用中断
}
// 启动Frame。每毫秒发生一次,因此我们也将其用于TX和RX LED一次触发时序
if (udint & (1 << SOFI)) {
USB_Flush(CDC_TX); // 如果找到,发送一个tx帧
// 检查一次捕获是否已经过去。 如果是这样,请关闭LED
if (TxLEDPulse && !(--TxLEDPulse)) TXLED0;
if (RxLEDPulse && !(--RxLEDPulse)) RXLED0;
}
// 一旦数据上出现非空闲模式,就会触发WAKEUPI中断行。 因此,即使控制器未处于“挂起”模式,也可能发生WAKEUPI中断。
// 因此,我们仅在USB挂起时才启用它。
if (udint & (1 << WAKEUPI)) {
UDIEN = (UDIEN & ~(1 << WAKEUPE)) | (1 << SUSPE); // 禁用WAKEUP中断,并允许SUSPEND中断
// WAKEUPI应通过软件清除(必须先启用USB时钟输入)。
// USB_ClockEnable();
UDINT &= ~(1 << WAKEUPI);
_usbSuspendState = (_usbSuspendState & ~(1 << SUSPI)) | (1 << WAKEUPI);
} else if (udint & (1 << SUSPI)) { // WAKEUPI / SUSPI位中只有一个可以同时激活
UDIEN = (UDIEN & ~(1 << SUSPE)) | (1 << WAKEUPE); // 禁用SUSPEND中断并启用WAKEUP中断
//USB_ClockDisable();
UDINT &= ~((1 << WAKEUPI) | (1 << SUSPI)); // 清除所有已经挂起的WAKEUP IRQ和SUSPI请求
_usbSuspendState = (_usbSuspendState & ~(1 << WAKEUPI)) | (1 << SUSPI);
}
}
// VBUS或计数帧
u8 USBConnected() {
u8 f = UDFNUML;
delay(3);
return f != UDFNUML;
}
USBDevice_ USBDevice;
USBDevice_::USBDevice_() {}
void USBDevice_::attach() {
_usbConfiguration = 0;
_usbCurrentStatus = 0;
_usbSuspendState = 0;
USB_ClockEnable();
UDINT &= ~((1 << WAKEUPI) | (1 << SUSPI)); // 清除已经挂起的WAKEUP / SUSPEND请求
UDIEN = (1 << EORSTE) | (1 << SOFE) | (1 << SUSPE); // 启用EOR(复位结束),SOF(帧启动)和SUSPEND中断
TX_RX_LED_INIT;
}
void USBDevice_::detach() {}
// 检查中断。需要完成VBUS检测
bool USBDevice_::configured() {
return _usbConfiguration;
}
void USBDevice_::poll() {}
bool USBDevice_::wakeupHost() {
// 清除所有先前已设置但可以在该时间处理的唤醒请求。例如因为当时主机尚未暂停。
UDCON &= ~(1 << RMWKUP);
if (!(UDCON & (1 << RMWKUP))
&& (_usbSuspendState & (1 << SUSPI))
&& (_usbCurrentStatus & FEATURE_REMOTE_WAKEUP_ENABLED)) {
// 此简短版本仅在尚未暂停设备时起作用。 目前Arduino核心根本不处理SUSPEND,所以没关系。
USB_ClockEnable();
UDCON |= (1 << RMWKUP); // 发送唤醒请求
return true;
}
return false;
}
bool USBDevice_::isSuspended() {
return (_usbSuspendState & (1 << SUSPI));
}
#endif /* if defined(USBCON) */
| 31.035651 | 155 | 0.60031 | JHSeng |
2e04d61885cdbc57fa7a44e574ed97f4826d3f4f | 3,063 | cpp | C++ | VVGL/src/GLContextWindowBacking.cpp | mrRay/VVISF-GL | 96b00da11e4497da304041ea2a5ffc6e3a8c9454 | [
"BSD-3-Clause"
] | 24 | 2019-01-17T17:56:18.000Z | 2022-02-27T19:57:13.000Z | VVGL/src/GLContextWindowBacking.cpp | mrRay/VVISF-GL | 96b00da11e4497da304041ea2a5ffc6e3a8c9454 | [
"BSD-3-Clause"
] | 6 | 2019-01-17T17:17:12.000Z | 2020-06-19T11:27:50.000Z | VVGL/src/GLContextWindowBacking.cpp | mrRay/VVISF-GL | 96b00da11e4497da304041ea2a5ffc6e3a8c9454 | [
"BSD-3-Clause"
] | 2 | 2020-12-25T04:57:31.000Z | 2021-03-02T22:05:31.000Z | #include "GLContextWindowBacking.hpp"
#if defined(VVGL_SDK_WIN)
namespace VVGL {
const TCHAR* GLCONTEXTWINDOWBACKING_WNDCLASSNAME = _T("GLCONTEXTWINDOWBACKING_WNDCLASSNAME");
static const TCHAR* GLCONTEXTWINDOWBACKING_PROPERTY = _T("GLCONTEXTWINDOWBACKING_PROPERTY");
static bool GLContextWindowBackingClassRegistered = false;
LRESULT CALLBACK GLContextWindowBacking_wndProc(HWND Wnd, UINT Msg, WPARAM wParam, LPARAM lParam);
GLContextWindowBacking::GLContextWindowBacking(const VVGL::Rect & inRect) {
//cout << __PRETTY_FUNCTION__ << endl;
// register the window class if we haven't already
if (!GLContextWindowBackingClassRegistered) {
WNDCLASSEX WndClass;
memset(&WndClass, 0, sizeof(WNDCLASSEX));
WndClass.cbSize = sizeof(WNDCLASSEX);
//WndClass.style = CS_OWNDC; // Class styles
WndClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
WndClass.lpfnWndProc = GLContextWindowBacking_wndProc;
WndClass.cbClsExtra = 0; // No extra class data
WndClass.cbWndExtra = 0; // No extra window data
WndClass.hInstance = GetModuleHandle(NULL);
WndClass.hIcon = LoadIcon(0, IDI_APPLICATION);
WndClass.hCursor = LoadCursor(0, IDC_ARROW);
WndClass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
WndClass.lpszMenuName = NULL;
WndClass.lpszClassName = GLCONTEXTWINDOWBACKING_WNDCLASSNAME;
RegisterClassEx(&WndClass);
GLContextWindowBackingClassRegistered = true;
}
// create the window, get its device context
//DWORD tmpFlag = WS_OVERLAPPEDWINDOW | WS_CHILD;
//DWORD tmpFlag = WS_OVERLAPPEDWINDOW;
//DWORD tmpFlag = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
//tmpFlag = tmpFlag | WS_VISIBLE;
DWORD tmpFlag = 0;
tmpFlag |= WS_CLIPSIBLINGS;
tmpFlag |= WS_CLIPCHILDREN;
//tmpFlag |= WS_POPUP;
//tmpFlag |= WS_EX_APPWINDOW;
//tmpFlag |= WS_EX_TOPMOST;
//tmpFlag |= WS_VISIBLE;
//tmpFlag |= WS_MAXIMIZEBOX;
//tmpFlag |= WS_THICKFRAME;
//tmpFlag |= WS_EX_WINDOWEDGE;
tmpFlag |= WS_OVERLAPPEDWINDOW;
_wnd = CreateWindowEx(
0,
GLCONTEXTWINDOWBACKING_WNDCLASSNAME,
_T("VVGL Test App"),
tmpFlag,
int(inRect.botLeft().x), int(inRect.botLeft().y), int(inRect.size.width), int(inRect.size.height),
//int(inRect.topLeft().x), int(inRect.topLeft().y), int(inRect.botRight().x), int(inRect.botRight().y),
0,
0,
NULL,
NULL);
SetProp(_wnd, GLCONTEXTWINDOWBACKING_PROPERTY, (HANDLE)this);
_dc = GetDC(_wnd);
// configure the window's pixel format
ConfigDeviceContextPixelFormat(_dc);
}
GLContextWindowBacking::~GLContextWindowBacking() {
ReleaseDC(_wnd, _dc);
DestroyWindow(_wnd);
}
LRESULT CALLBACK GLContextWindowBacking_wndProc(HWND Wnd, UINT Msg, WPARAM wParam, LPARAM lParam) {
//if (Msg == WM_CREATE)
// cout << "GLContextWindowBacking received WM_CREATE and is clear to create a GL ctx" << endl;
return DefWindowProc(Wnd, Msg, wParam, lParam);
};
}
#endif // VVGL_SDK_WIN | 31.90625 | 107 | 0.711721 | mrRay |
2e07012b6ccf4565ad0591026233b490894a32b9 | 2,318 | cpp | C++ | esp32/airpapyrus/CCS811Sensor.cpp | ciffelia/airpapyrus | 4e6642025d6b1e81210c63f3cae46e4e361804ea | [
"MIT"
] | null | null | null | esp32/airpapyrus/CCS811Sensor.cpp | ciffelia/airpapyrus | 4e6642025d6b1e81210c63f3cae46e4e361804ea | [
"MIT"
] | null | null | null | esp32/airpapyrus/CCS811Sensor.cpp | ciffelia/airpapyrus | 4e6642025d6b1e81210c63f3cae46e4e361804ea | [
"MIT"
] | null | null | null | #include "CCS811Sensor.hpp"
#include "Constants.hpp"
#include "Logger.hpp"
CCS811Sensor::CCS811Sensor()
: ccs811(Constants::GPIO::Address::CCS811)
{
}
void CCS811Sensor::reset() {
pinMode(Constants::GPIO::Pin::CCS811_RESET, OUTPUT);
digitalWrite(Constants::GPIO::Pin::CCS811_RESET, 0);
delay(10);
digitalWrite(Constants::GPIO::Pin::CCS811_RESET, 1);
delay(10);
}
void CCS811Sensor::wake() {
pinMode(Constants::GPIO::Pin::CCS811_WAKE, OUTPUT);
digitalWrite(Constants::GPIO::Pin::CCS811_WAKE, 0);
delay(10);
}
void CCS811Sensor::sleep() {
pinMode(Constants::GPIO::Pin::CCS811_WAKE, OUTPUT);
digitalWrite(Constants::GPIO::Pin::CCS811_WAKE, 1);
delay(10);
}
bool CCS811Sensor::waitForDataAvailable(const int timeout) {
for (int elapsed = 0; elapsed < timeout * 10 && !ccs811.dataAvailable(); elapsed++) {
delay(100);
}
return ccs811.dataAvailable();
}
bool CCS811Sensor::initialize() {
this->reset();
this->wake();
const auto beginStatus = ccs811.beginWithStatus();
if (beginStatus != CCS811::CCS811_Stat_SUCCESS)
{
Printf("ccs811.begin() failed. Error: %s.", ccs811.statusString(beginStatus));
return false;
}
// Mode 1: measurement every second
const auto setModeStatus = ccs811.setDriveMode(1);
if (setModeStatus != CCS811::CCS811_Stat_SUCCESS)
{
Printf("ccs811.setDriveMode() failed. Error: %s.", ccs811.statusString(setModeStatus));
return false;
}
// 600秒待ってもデータを読み出せなければ諦める
if (!this->waitForDataAvailable(600)) {
Println("waitForDataAvailable() timed out. (600s)");
return false;
}
return true;
}
bool CCS811Sensor::setEnvironmentalData(const BME280Data bme280Data) {
const auto status = ccs811.setEnvironmentalData(bme280Data.humidity, bme280Data.temperature);
if (status != CCS811::CCS811_Stat_SUCCESS)
{
Printf("ccs811.setEnvironmentalData() failed. Error: %s.", ccs811.statusString(status));
return false;
}
return true;
}
CCS811Data CCS811Sensor::read() {
// 15秒待ってもデータを読み出せなければ諦める
if (!this->waitForDataAvailable(15)) {
Println("waitForDataAvailable() timed out. (15s)");
Println("Resetting CCS811...");
this->initialize();
return this->read();
}
ccs811.readAlgorithmResults();
return CCS811Data(
ccs811.getCO2(),
ccs811.getTVOC()
);
}
| 22.950495 | 95 | 0.694133 | ciffelia |
2e08233eba05439eed938035df117b2cf5280ae8 | 462 | cpp | C++ | 519_b.cpp | onexmaster/cp | b78b0f1e586d6977d86c97b32f48fed33f1469af | [
"Apache-2.0",
"MIT"
] | null | null | null | 519_b.cpp | onexmaster/cp | b78b0f1e586d6977d86c97b32f48fed33f1469af | [
"Apache-2.0",
"MIT"
] | null | null | null | 519_b.cpp | onexmaster/cp | b78b0f1e586d6977d86c97b32f48fed33f1469af | [
"Apache-2.0",
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
int vec_sum=0;
int temp1_sum=0;
int temp2_sum=0;
for(int i=0;i<n;i++)
{
int x;
cin>>x;
vec_sum+=x;
}
for(int i=0;i<n-1;i++)
{
int x;
cin>>x;
temp1_sum+=x;
}
for(int i=0;i<n-2;i++)
{
int x;
cin>>x;
temp2_sum+=x;
}
cout<<vec_sum-temp1_sum<<endl;
cout<<temp1_sum-temp2_sum<<endl;
}
| 14.903226 | 37 | 0.480519 | onexmaster |
2e0b8c9b9baa9cd6501e2376d31757d25d948f27 | 6,650 | cpp | C++ | src/caffe/layers/softmax_noisy_label_loss_layer.cpp | gnina/caffe | 59b3451cd54ae106de3335876ba25f68b9553098 | [
"Intel",
"BSD-2-Clause"
] | 1 | 2016-06-09T16:44:58.000Z | 2016-06-09T16:44:58.000Z | src/caffe/layers/softmax_noisy_label_loss_layer.cpp | gnina/caffe | 59b3451cd54ae106de3335876ba25f68b9553098 | [
"Intel",
"BSD-2-Clause"
] | null | null | null | src/caffe/layers/softmax_noisy_label_loss_layer.cpp | gnina/caffe | 59b3451cd54ae106de3335876ba25f68b9553098 | [
"Intel",
"BSD-2-Clause"
] | 3 | 2016-02-10T17:38:44.000Z | 2018-10-14T07:44:19.000Z | #include <algorithm>
#include <functional>
#include <cfloat>
#include <vector>
#include <iostream>
#include <utility>
#include "caffe/layers/softmax_noisy_label_loss_layer.hpp"
#include "caffe/filler.hpp"
namespace caffe {
template <typename Dtype>
void SoftmaxWithNoisyLabelLossLayer<Dtype>::LayerSetUp(
const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {
if (this->layer_param_.loss_weight_size() == 0) {
this->layer_param_.add_loss_weight(Dtype(1));
for (int i = 1; i < top.size(); ++i) {
this->layer_param_.add_loss_weight(0);
}
}
softmax_bottom_vec_y_.clear();
softmax_bottom_vec_z_.clear();
softmax_top_vec_y_.clear();
softmax_top_vec_z_.clear();
softmax_bottom_vec_y_.push_back(bottom[0]);
softmax_bottom_vec_z_.push_back(bottom[1]);
softmax_top_vec_y_.push_back(&prob_y_);
softmax_top_vec_z_.push_back(&prob_z_);
softmax_layer_y_->SetUp(softmax_bottom_vec_y_, softmax_top_vec_y_);
softmax_layer_z_->SetUp(softmax_bottom_vec_z_, softmax_top_vec_z_);
N_ = bottom[0]->channels();
this->blobs_.resize(1);
this->blobs_[0].reset(new Blob<Dtype>(1, 1, N_, N_));
shared_ptr<Filler<Dtype> > c_filler(GetFiller<Dtype>(
this->layer_param_.softmax_noisy_label_loss_param().matrix_c_filler()));
c_filler->Fill(this->blobs_[0].get());
CHECK_EQ(this->blobs_[0]->num(), 1);
CHECK_EQ(this->blobs_[0]->channels(), 1);
CHECK_EQ(this->blobs_[0]->height(), N_);
CHECK_EQ(this->blobs_[0]->width(), N_);
lr_z_ = this->layer_param_.softmax_noisy_label_loss_param().update_noise_lr();
}
template <typename Dtype>
void SoftmaxWithNoisyLabelLossLayer<Dtype>::Reshape(
const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {
LossLayer<Dtype>::Reshape(bottom, top);
softmax_layer_y_->Reshape(softmax_bottom_vec_y_, softmax_top_vec_y_);
softmax_layer_z_->Reshape(softmax_bottom_vec_z_, softmax_top_vec_z_);
M_ = bottom[0]->num();
CHECK_EQ(bottom[0]->channels(), N_);
posterior_.Reshape(M_, N_, NumNoiseType, 1);
if (top.size() >= 2) top[1]->ReshapeLike(prob_y_);
if (top.size() >= 3) top[2]->ReshapeLike(prob_z_);
if (top.size() >= 4) top[3]->ReshapeLike(posterior_);
}
template <typename Dtype>
void SoftmaxWithNoisyLabelLossLayer<Dtype>::Forward_cpu(
const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {
// Compute conditional probability of p(y|x) and p(z|x)
softmax_layer_y_->Forward(softmax_bottom_vec_y_, softmax_top_vec_y_);
softmax_layer_z_->Forward(softmax_bottom_vec_z_, softmax_top_vec_z_);
// Compute posterior
const Dtype* C = this->blobs_[0]->cpu_data();
const Dtype* noisy_label = bottom[2]->cpu_data();
const Dtype* p_y_given_x = prob_y_.cpu_data();
const Dtype* p_z_given_x = prob_z_.cpu_data();
const Dtype uniform = Dtype(1.0) / (N_ - 1);
const int dim_yz = N_ * NumNoiseType;
Dtype* posterior_data = posterior_.mutable_cpu_data();
Dtype loss = 0;
for (int i = 0; i < M_; ++i) {
if (noisy_label[i] == -1) {
// Unlabeled
caffe_memset(dim_yz * sizeof(Dtype), 0, posterior_data + i * dim_yz);
continue;
}
for (int y = 0; y < N_; ++y) {
int offset = posterior_.offset(i, y);
Dtype py = p_y_given_x[i * N_ + y];
for (int z = 0; z < NumNoiseType; ++z) {
Dtype pz = p_z_given_x[i * NumNoiseType + z];
switch (NoiseType(z)) {
case NoiseFree:
posterior_data[offset + z] = (y == noisy_label[i]);
break;
case RandomNoise:
posterior_data[offset + z] = uniform * (y != noisy_label[i]);
break;
case ConfusingNoise:
posterior_data[offset + z] =
C[static_cast<int>(noisy_label[i] * N_ + y)];
break;
default:
break;
}
posterior_data[offset + z] *= py * pz;
}
}
// Compute loss
Dtype sum = 0;
Dtype weighted_loss = 0;
for (int y = 0; y < N_; ++y) {
for (int z = 0; z < NumNoiseType; ++z) {
Dtype p = posterior_.data_at(i, y, z, 0);
sum += p;
weighted_loss -= p * log(std::max(p, Dtype(FLT_MIN)));
}
}
if (sum > 0) {
loss += weighted_loss / sum;
caffe_scal(dim_yz, Dtype(1.0) / sum, posterior_data + i * dim_yz);
}
}
top[0]->mutable_cpu_data()[0] = loss / M_;
if (top.size() >= 2) top[1]->ShareData(prob_y_);
if (top.size() >= 3) top[2]->ShareData(prob_z_);
if (top.size() >= 4) top[3]->ShareData(posterior_);
}
template <typename Dtype>
void SoftmaxWithNoisyLabelLossLayer<Dtype>::Backward_cpu(
const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down,
const vector<Blob<Dtype>*>& bottom) {
if (propagate_down[2]) {
LOG(FATAL) << this->type()
<< " Layer cannot backpropagate to label inputs.";
}
if (propagate_down[0]) { // Back prop: y
Blob<Dtype> true_prob(M_, N_, 1, 1);
Dtype* p = true_prob.mutable_cpu_data();
const Dtype* p_yz = posterior_.cpu_data();
for (int i = 0; i < M_; ++i) {
for (int y = 0; y < N_; ++y) {
int offset = posterior_.offset(i, y);
Dtype sum = 0;
for (int z = 0; z < NumNoiseType; ++z) sum += p_yz[offset + z];
p[i * N_ + y] = sum;
}
}
BackProp(prob_y_, true_prob, top[0]->cpu_diff()[0], bottom[0]);
}
if (propagate_down[1]) { // Back prop: z
Blob<Dtype> true_prob(M_, NumNoiseType, 1, 1);
Dtype* p = true_prob.mutable_cpu_data();
const Dtype* p_yz = posterior_.cpu_data();
for (int i = 0; i < M_; ++i) {
for (int z = 0; z < NumNoiseType; ++z) {
Dtype sum = 0;
for (int y = 0; y < N_; ++y)
sum += p_yz[i * N_ * NumNoiseType + y * NumNoiseType + z];
p[i * NumNoiseType + z] = sum;
}
}
BackProp(prob_z_, true_prob, top[0]->cpu_diff()[0] * lr_z_, bottom[1]);
}
}
template <typename Dtype>
void SoftmaxWithNoisyLabelLossLayer<Dtype>::BackProp(const Blob<Dtype>& prob,
const Blob<Dtype>& true_prob, Dtype lr, Blob<Dtype>* diff) {
const Dtype* prob_data = prob.cpu_data();
const Dtype* true_prob_data = true_prob.cpu_data();
Dtype* diff_data = diff->mutable_cpu_diff();
caffe_sub(diff->count(), prob_data, true_prob_data, diff_data);
// set diff of unlabeled samples to 0
const int N = prob.channels();
for (int i = 0; i < M_; ++i) {
Dtype sum = 0;
for (int j = 0; j < N; ++j) sum += true_prob_data[i * N + j];
for (int j = 0; j < N; ++j) diff_data[i * N + j] *= sum;
}
caffe_scal(diff->count(), lr / M_, diff_data);
}
INSTANTIATE_CLASS(SoftmaxWithNoisyLabelLossLayer);
REGISTER_LAYER_CLASS(SoftmaxWithNoisyLabelLoss);
}
| 35.185185 | 80 | 0.633233 | gnina |
2e0dbbebabdba63e6f61765387565af2e0bc7be3 | 10,536 | cc | C++ | chrome/browser/ash/power/auto_screen_brightness/model_config_loader_impl_unittest.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-10-18T02:33:40.000Z | 2020-10-18T02:33:40.000Z | chrome/browser/ash/power/auto_screen_brightness/model_config_loader_impl_unittest.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 3 | 2021-05-17T16:28:52.000Z | 2021-05-21T22:42:22.000Z | chrome/browser/ash/power/auto_screen_brightness/model_config_loader_impl_unittest.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "chrome/browser/ash/power/auto_screen_brightness/model_config_loader_impl.h"
#include "ash/constants/ash_features.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/task/thread_pool/thread_pool_instance.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/task_environment.h"
#include "base/test/test_mock_time_task_runner.h"
#include "base/threading/sequenced_task_runner_handle.h"
#include "content/public/test/browser_task_environment.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace ash {
namespace power {
namespace auto_screen_brightness {
namespace {
class TestObserver : public ModelConfigLoader::Observer {
public:
TestObserver() {}
~TestObserver() override = default;
// ModelConfigLoader::Observer overrides:
void OnModelConfigLoaded(absl::optional<ModelConfig> model_config) override {
model_config_loader_initialized_ = true;
model_config_ = model_config;
}
bool model_config_loader_initialized() const {
return model_config_loader_initialized_;
}
absl::optional<ModelConfig> model_config() { return model_config_; }
private:
bool model_config_loader_initialized_ = false;
absl::optional<ModelConfig> model_config_;
DISALLOW_COPY_AND_ASSIGN(TestObserver);
};
} // namespace
class ModelConfigLoaderImplTest : public testing::Test {
public:
ModelConfigLoaderImplTest()
: task_environment_(base::test::TaskEnvironment::TimeSource::MOCK_TIME) {
CHECK(temp_dir_.CreateUniqueTempDir());
temp_params_path_ = temp_dir_.GetPath().Append("model_params.json");
}
~ModelConfigLoaderImplTest() override {
base::ThreadPoolInstance::Get()->FlushForTesting();
}
void Init(const std::string& model_params,
const std::map<std::string, std::string>& experiment_params = {}) {
base::test::ScopedFeatureList scoped_feature_list;
if (!experiment_params.empty()) {
scoped_feature_list.InitAndEnableFeatureWithParameters(
features::kAutoScreenBrightness, experiment_params);
}
WriteParamsToFile(model_params);
model_config_loader_ = ModelConfigLoaderImpl::CreateForTesting(
temp_params_path_, base::SequencedTaskRunnerHandle::Get());
test_observer_ = std::make_unique<TestObserver>();
model_config_loader_->AddObserver(test_observer_.get());
task_environment_.RunUntilIdle();
}
protected:
void WriteParamsToFile(const std::string& params) {
if (params.empty())
return;
CHECK(!temp_params_path_.empty());
const int bytes_written =
base::WriteFile(temp_params_path_, params.data(), params.size());
ASSERT_EQ(bytes_written, static_cast<int>(params.size()))
<< "Wrote " << bytes_written << " byte(s) instead of " << params.size()
<< " to " << temp_params_path_;
}
content::BrowserTaskEnvironment task_environment_;
base::ScopedTempDir temp_dir_;
base::FilePath temp_params_path_;
std::unique_ptr<ModelConfigLoaderImpl> model_config_loader_;
std::unique_ptr<TestObserver> test_observer_;
private:
DISALLOW_COPY_AND_ASSIGN(ModelConfigLoaderImplTest);
};
TEST_F(ModelConfigLoaderImplTest, ValidModelParamsLoaded) {
const std::string model_params = R"(
{
"auto_brightness_als_horizon_seconds": 2,
"enabled": true,
"global_curve": {
"log_lux": [
1.0,
2.0,
3.0
],
"brightness": [
10.0,
20.0,
30.0
]
},
"metrics_key": "abc",
"model_als_horizon_seconds": 5
}
)";
Init(model_params);
EXPECT_TRUE(test_observer_->model_config_loader_initialized());
std::vector<double> expected_log_lux = {1.0, 2.0, 3.0};
std::vector<double> expected_brightness = {10.0, 20.0, 30.0};
ModelConfig expected_model_config;
expected_model_config.auto_brightness_als_horizon_seconds = 2.0;
expected_model_config.enabled = true;
expected_model_config.log_lux = expected_log_lux;
expected_model_config.brightness = expected_brightness;
expected_model_config.metrics_key = "abc";
expected_model_config.model_als_horizon_seconds = 5;
EXPECT_TRUE(test_observer_->model_config());
EXPECT_EQ(*test_observer_->model_config(), expected_model_config);
}
TEST_F(ModelConfigLoaderImplTest, MissingEnabledMeansFalse) {
const std::string model_params = R"(
{
"auto_brightness_als_horizon_seconds": 2,
"global_curve": {
"log_lux": [
1.0,
2.0,
3.0
],
"brightness": [
10.0,
20.0,
30.0
]
},
"metrics_key": "abc",
"model_als_horizon_seconds": 5
}
)";
Init(model_params);
EXPECT_TRUE(test_observer_->model_config_loader_initialized());
std::vector<double> expected_log_lux = {1.0, 2.0, 3.0};
std::vector<double> expected_brightness = {10.0, 20.0, 30.0};
ModelConfig expected_model_config;
expected_model_config.auto_brightness_als_horizon_seconds = 2.0;
expected_model_config.enabled = false;
expected_model_config.log_lux = expected_log_lux;
expected_model_config.brightness = expected_brightness;
expected_model_config.metrics_key = "abc";
expected_model_config.model_als_horizon_seconds = 5;
EXPECT_TRUE(test_observer_->model_config());
EXPECT_EQ(*test_observer_->model_config(), expected_model_config);
}
TEST_F(ModelConfigLoaderImplTest, ValidModelParamsLoadedThenOverriden) {
const std::string model_params = R"(
{
"auto_brightness_als_horizon_seconds": 2,
"enabled": true,
"global_curve": {
"log_lux": [
1.0,
2.0,
3.0
],
"brightness": [
10.0,
20.0,
30.0
]
},
"metrics_key": "abc",
"model_als_horizon_seconds": 5
}
)";
const std::string global_curve_spec("2:20,4:40,6:60");
const std::map<std::string, std::string> experiment_params = {
{"auto_brightness_als_horizon_seconds", "10"},
{"enabled", "false"},
{"model_als_horizon_seconds", "20"},
{"global_curve", global_curve_spec},
};
Init(model_params, experiment_params);
EXPECT_TRUE(test_observer_->model_config_loader_initialized());
std::vector<double> expected_log_lux = {2.0, 4.0, 6.0};
std::vector<double> expected_brightness = {20.0, 40.0, 60.0};
ModelConfig expected_model_config;
expected_model_config.auto_brightness_als_horizon_seconds = 10.0;
expected_model_config.enabled = false;
expected_model_config.log_lux = expected_log_lux;
expected_model_config.brightness = expected_brightness;
expected_model_config.metrics_key = "abc";
expected_model_config.model_als_horizon_seconds = 20.0;
EXPECT_TRUE(test_observer_->model_config());
EXPECT_EQ(*test_observer_->model_config(), expected_model_config);
}
TEST_F(ModelConfigLoaderImplTest, InvalidModelParamsLoaded) {
// "auto_brightness_als_horizon_seconds" is missing.
const std::string model_params = R"(
{
"global_curve": {
"log_lux": [
1.0,
2.0,
3.0
],
"brightness": [
10.0,
20.0,
30.0
]
},
"metrics_key": "abc",
"model_als_horizon_seconds": 5
}
)";
Init(model_params);
EXPECT_TRUE(test_observer_->model_config_loader_initialized());
EXPECT_FALSE(test_observer_->model_config());
}
TEST_F(ModelConfigLoaderImplTest, InvalidModelParamsLoadedThenOverriden) {
// Same as InvalidModelParamsLoaded, but missing
// "auto_brightness_als_horizon_seconds" is specified in the experiment flags.
const std::string model_params = R"(
{
"global_curve": {
"log_lux": [
1.0,
2.0,
3.0
],
"brightness": [
10.0,
20.0,
30.0
]
},
"metrics_key": "abc",
"model_als_horizon_seconds": 5
}
)";
const std::map<std::string, std::string> experiment_params = {
{"auto_brightness_als_horizon_seconds", "10"},
{"model_als_horizon_seconds", "20"},
};
Init(model_params, experiment_params);
EXPECT_TRUE(test_observer_->model_config_loader_initialized());
std::vector<double> expected_log_lux = {1.0, 2.0, 3.0};
std::vector<double> expected_brightness = {10.0, 20.0, 30.0};
ModelConfig expected_model_config;
expected_model_config.auto_brightness_als_horizon_seconds = 10.0;
expected_model_config.enabled = false;
expected_model_config.log_lux = expected_log_lux;
expected_model_config.brightness = expected_brightness;
expected_model_config.metrics_key = "abc";
expected_model_config.model_als_horizon_seconds = 20.0;
EXPECT_TRUE(test_observer_->model_config());
EXPECT_EQ(*test_observer_->model_config(), expected_model_config);
}
TEST_F(ModelConfigLoaderImplTest, MissingModelParams) {
// Model params not found from disk and experiment flags do not contain
// all fields we need.
const std::map<std::string, std::string> experiment_params = {
{"auto_brightness_als_horizon_seconds", "10"},
{"model_als_horizon_seconds", "20"},
};
Init("" /* model_params */, experiment_params);
EXPECT_TRUE(test_observer_->model_config_loader_initialized());
EXPECT_FALSE(test_observer_->model_config());
}
TEST_F(ModelConfigLoaderImplTest, InvalidJsonFormat) {
const std::string model_params = R"(
{
"global_curve": {
"log_lux": [
1.0,
2.0,
3.0
],
"brightness": [
10.0,
20.0,
30.0
]
},
"metrics_key": 10,
"model_als_horizon_seconds": 5
}
)";
const std::map<std::string, std::string> experiment_params = {
{"auto_brightness_als_horizon_seconds", "10"},
{"model_als_horizon_seconds", "20"},
};
Init(model_params, experiment_params);
EXPECT_TRUE(test_observer_->model_config_loader_initialized());
EXPECT_FALSE(test_observer_->model_config());
}
} // namespace auto_screen_brightness
} // namespace power
} // namespace ash
| 30.017094 | 85 | 0.676348 | DamieFC |
2e1139f3fd96af61c9eb61cbbc0eea294d26f404 | 4,661 | hh | C++ | include/snow/types/slot_mask.hh | nilium/libsnow-common | dff60ce529cdbe13ccf1f94756a78214c8f9d09d | [
"BSL-1.0"
] | 1 | 2015-10-01T20:10:05.000Z | 2015-10-01T20:10:05.000Z | include/snow/types/slot_mask.hh | nilium/libsnow-common | dff60ce529cdbe13ccf1f94756a78214c8f9d09d | [
"BSL-1.0"
] | null | null | null | include/snow/types/slot_mask.hh | nilium/libsnow-common | dff60ce529cdbe13ccf1f94756a78214c8f9d09d | [
"BSL-1.0"
] | null | null | null | /*
* Copyright Noel Cower 2013.
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*/
#pragma once
#include <cstdint>
#include <iostream>
#include <vector>
namespace snow {
template <typename HT, typename CT>
struct slot_mask_t;
template <typename HT, typename CT>
std::ostream &operator << (std::ostream &out, const slot_mask_t<HT, CT> &in);
template <typename HT = int, typename CT = unsigned int>
struct slot_mask_t
{
using handle_t = HT;
using count_t = CT;
static const handle_t NO_HANDLE = 0;
slot_mask_t(size_t size = 1);
~slot_mask_t() = default;
slot_mask_t(const slot_mask_t &) = default;
slot_mask_t &operator = (const slot_mask_t &) = default;
slot_mask_t(slot_mask_t &&other) : slots_(std::move(other.slots_)) {}
slot_mask_t &operator = (slot_mask_t &&other)
{
if (&other != this) {
slots_ = std::move(other.slots_);
}
return *this;
}
inline size_t size() const { return slots_.size(); }
void resize(size_t new_size);
size_t slots_free_at(size_t index) const;
bool index_is_free(size_t index, size_t slots) const;
std::pair<bool, size_t> find_free_index(size_t slots, size_t from = 0) const;
// Handle may not be NO_HANDLE (0)
void consume_index(size_t index, size_t slots, handle_t handle);
// Must pass same handle for slots otherwise the consumed slots
// cannot be released.
void release_index(size_t index, size_t slots, handle_t handle);
private:
friend std::ostream &operator << <> (std::ostream &out, const slot_mask_t<HT, CT> &in);
void join_same(size_t from);
struct slot_t
{
handle_t handle; // 0 = unused
count_t count; // number to right, counting self
};
std::vector<slot_t> slots_;
};
template <typename HT, typename CT>
std::ostream &operator << (std::ostream &out, const slot_mask_t<HT, CT> &in)
{
out << '{';
for (const auto &slot : in.slots_)
out << ((slot.handle == 0) ? '-' : '+');
return (out << '}');
}
template <typename HT, typename CT>
slot_mask_t<HT, CT>::slot_mask_t(size_t size)
{
resize(size);
}
template <typename HT, typename CT>
void slot_mask_t<HT, CT>::resize(size_t new_size)
{
slots_.resize(new_size, { NO_HANDLE, 1 });
if (new_size == 0) {
return;
}
join_same(new_size - 1);
}
template <typename HT, typename CT>
size_t slot_mask_t<HT, CT>::slots_free_at(size_t index) const
{
if (index >= slots_.size())
return 0;
return slots_[index].count;
}
template <typename HT, typename CT>
bool slot_mask_t<HT, CT>::index_is_free(size_t index, size_t slots) const
{
if (index + slots > slots_.size())
return false;
const slot_t &slot = slots_[index];
return slot.count >= slots && slot.handle == NO_HANDLE;
}
template <typename HT, typename CT>
std::pair<bool, size_t> slot_mask_t<HT, CT>::find_free_index(size_t slots, size_t from) const
{
if (slots == 0) {
return { false, 0 };
}
const size_t length = slots_.size() - (slots - 1);
size_t index = from;
for (; index < length; ++index) {
const slot_t &slot = slots_[index];
if (slot.handle == 0 && slots <= slot.count) {
return { true, index };
} else {
index += slot.count - 1;
}
}
return { false, 0 };
}
template <typename HT, typename CT>
void slot_mask_t<HT, CT>::consume_index(size_t index, size_t slots, handle_t handle)
{
size_t from = index;
while (slots) {
slot_t &slot = slots_[index];
slot.handle = handle;
slot.count = slots;
index += 1;
slots -= 1;
}
if (from > 0) {
join_same(from - 1);
}
}
template <typename HT, typename CT>
void slot_mask_t<HT, CT>::release_index(size_t index, size_t slots, handle_t handle)
{
size_t from = index;
while (slots) {
slot_t &slot = slots_[index];
if (slot.handle != handle) {
if (index > 0 && index != from) {
join_same(index - 1);
}
return;
}
slot.handle = NO_HANDLE;
slot.count = slots;
index += 1;
slots -= 1;
}
if (from > 0) {
join_same(from - 1);
}
}
template <typename HT, typename CT>
void slot_mask_t<HT, CT>::join_same(size_t from)
{
const int handle = slots_[from].handle;
int counter = 1;
{
const size_t right = from + 1;
if (right < slots_.size() && handle == slots_[right].handle) {
counter += slots_[right].count;
}
}
for (;;) {
slot_t &slot = slots_[from];
if (slot.handle != handle) {
return;
}
slot.count = counter;
if (from == 0) {
return;
}
counter += 1;
from -= 1;
}
}
} // namespace snow
| 21.186364 | 93 | 0.636344 | nilium |
2e11d2c56ced43d859e4032bd06fec5a9b136ef1 | 5,486 | cpp | C++ | opi_emac_showfile/firmware/main.cpp | rodb70/rpidmx512 | 6e7eef3eaba35cc2eb7cdeb5bef906faea9366fd | [
"MIT"
] | null | null | null | opi_emac_showfile/firmware/main.cpp | rodb70/rpidmx512 | 6e7eef3eaba35cc2eb7cdeb5bef906faea9366fd | [
"MIT"
] | null | null | null | opi_emac_showfile/firmware/main.cpp | rodb70/rpidmx512 | 6e7eef3eaba35cc2eb7cdeb5bef906faea9366fd | [
"MIT"
] | null | null | null | /**
* @file main.cpp
*
*/
/* Copyright (C) 2020 by Arjan van Vught mailto:info@orangepi-dmx.nl
*
* 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 <cassert>
#include <stdio.h>
#include <stdint.h>
#include "hardware.h"
#include "networkh3emac.h"
#include "networkconst.h"
#include "ledblink.h"
#include "displayudf.h"
#include "displayudfparams.h"
#include "storedisplayudf.h"
#include "showfileparams.h"
#include "storeshowfile.h"
#include "showfileosc.h"
#include "spiflashinstall.h"
#include "spiflashstore.h"
#include "remoteconfig.h"
#include "remoteconfigparams.h"
#include "storeremoteconfig.h"
#include "firmwareversion.h"
#include "software_version.h"
// LLRP Only Device
#include "rdmnetllrponly.h"
#include "rdm_e120.h"
// LLRP Handlers
#include "factorydefaults.h"
#include "displayudfnetworkhandler.h"
// Reboot handler
#include "reboot.h"
// Display
#include "displayhandler.h"
// Format handlers
#include "olashowfile.h"
// Protocol handlers
#include "showfileprotocole131.h"
#include "showfileprotocolartnet.h"
extern "C" {
void notmain(void) {
Hardware hw;
NetworkH3emac nw;
LedBlink lb;
DisplayUdf display;
FirmwareVersion fw(SOFTWARE_VERSION, __DATE__, __TIME__);
SpiFlashInstall spiFlashInstall;
SpiFlashStore spiFlashStore;
fw.Print("Showfile player");
hw.SetRebootHandler(new Reboot);
hw.SetLed(hardware::LedStatus::ON);
display.TextStatus(NetworkConst::MSG_NETWORK_INIT, Display7SegmentMessage::INFO_NETWORK_INIT, CONSOLE_YELLOW);
nw.SetNetworkStore(StoreNetwork::Get());
nw.SetNetworkDisplay(new DisplayUdfNetworkHandler);
nw.Init(StoreNetwork::Get());
nw.Print();
StoreShowFile storeShowFile;
ShowFileParams showFileParams(&storeShowFile);
if (showFileParams.Load()) {
showFileParams.Dump();
}
ShowFile *pShowFile = nullptr;
switch (showFileParams.GetFormat()) {
// case SHOWFILE_FORMAT_:
// break;
default:
pShowFile = new OlaShowFile;
break;
}
assert(pShowFile != nullptr);
DisplayHandler displayHandler;
pShowFile->SetShowFileDisplay(&displayHandler);
ShowFileProtocolHandler *pShowFileProtocolHandler = nullptr;
switch (showFileParams.GetProtocol()) {
case ShowFileProtocols::ARTNET:
pShowFileProtocolHandler = new ShowFileProtocolArtNet;
break;
default:
pShowFileProtocolHandler = new ShowFileProtocolE131;
break;
}
assert(pShowFileProtocolHandler != nullptr);
pShowFile->SetProtocolHandler(pShowFileProtocolHandler);
ShowFileOSC oscServer;
showFileParams.Set();
oscServer.Start();
oscServer.Print();
pShowFileProtocolHandler->Start();
pShowFileProtocolHandler->Print();
RDMNetLLRPOnly rdmNetLLRPOnly("Showfile player");
rdmNetLLRPOnly.GetRDMNetDevice()->SetRDMFactoryDefaults(new FactoryDefaults);
rdmNetLLRPOnly.GetRDMNetDevice()->SetProductCategory(E120_PRODUCT_CATEGORY_DATA_DISTRIBUTION);
rdmNetLLRPOnly.GetRDMNetDevice()->SetProductDetail(E120_PRODUCT_DETAIL_ETHERNET_NODE);
rdmNetLLRPOnly.Init();
rdmNetLLRPOnly.Print();
rdmNetLLRPOnly.Start();
RemoteConfig remoteConfig(remoteconfig::Node::SHOWFILE, remoteconfig::Output::PLAYER, 0);
RemoteConfigParams remoteConfigParams(new StoreRemoteConfig);
if (remoteConfigParams.Load()) {
remoteConfigParams.Set(&remoteConfig);
remoteConfigParams.Dump();
}
while (spiFlashStore.Flash())
;
display.SetTitle("Showfile player");
display.Set(2, displayudf::Labels::HOSTNAME);
display.Set(3, displayudf::Labels::IP);
display.Set(4, displayudf::Labels::VERSION);
DisplayUdfParams displayUdfParams(new StoreDisplayUdf);
if (displayUdfParams.Load()) {
displayUdfParams.Set(&display);
displayUdfParams.Dump();
}
display.Show();
pShowFile->SetShowFile(showFileParams.GetShow());
pShowFile->Print();
if (showFileParams.IsAutoStart()) {
pShowFile->Start();
}
// Fixed row 5, 6, 7
display.Printf(5, showFileParams.GetProtocol() == ShowFileProtocols::ARTNET ? "Art-Net" : "sACN E1.31");
if (showFileParams.GetProtocol() == ShowFileProtocols::ARTNET) {
if (showFileParams.IsArtNetBroadcast()) {
Display::Get()->PutString(" <Broadcast>");
}
}
if (pShowFileProtocolHandler->IsSyncDisabled()) {
display.Printf(6, "<No synchronization>");
}
displayHandler.ShowShowFileStatus();
hw.WatchdogInit();
for (;;) {
hw.WatchdogFeed();
nw.Run();
//
pShowFile->Run();
pShowFileProtocolHandler->Run();
oscServer.Run();
//
rdmNetLLRPOnly.Run();
remoteConfig.Run();
spiFlashStore.Flash();
lb.Run();
display.Run();
}
}
}
| 25.398148 | 111 | 0.755195 | rodb70 |
2e1323cd5ce50e74e5e7c7a739c17bf7001f5cda | 3,882 | cpp | C++ | PhotosConsigne/src/Widgets/PhotoW.cpp | FlorianLance/PhotosConsigne | 8ea3a68dc3db36bf054c3759d909f9af44647660 | [
"MIT"
] | 2 | 2018-05-06T20:59:09.000Z | 2021-02-25T11:00:14.000Z | PhotosConsigne/src/Widgets/PhotoW.cpp | FlorianLance/PhotosConsigne | 8ea3a68dc3db36bf054c3759d909f9af44647660 | [
"MIT"
] | null | null | null | PhotosConsigne/src/Widgets/PhotoW.cpp | FlorianLance/PhotosConsigne | 8ea3a68dc3db36bf054c3759d909f9af44647660 | [
"MIT"
] | 1 | 2021-02-01T14:57:04.000Z | 2021-02-01T14:57:04.000Z |
/*******************************************************************************
** PhotosConsigne **
** MIT License **
** Copyright (c) [2016] [Florian Lance] **
** **
** Permission is hereby granted, free of charge, to any person obtaining a **
** copy of this software and associated documentation files (the "Software"), **
** to deal in the Software without restriction, including without limitation **
** the rights to use, copy, modify, merge, publish, distribute, sublicense, **
** and/or sell copies of the Software, and to permit persons to whom the **
** Software is furnished to do so, subject to the following conditions: **
** **
** The above copyright notice and this permission notice shall be included in **
** all copies or substantial portions of the Software. **
** **
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR **
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, **
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL **
** THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER **
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING **
** FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER **
** DEALINGS IN THE SOFTWARE. **
** **
********************************************************************************/
/**
* \file PhotoW.cpp
* \brief defines PhotoW
* \author Florian Lance
* \date 01/11/15
*/
// local
#include "PhotoW.hpp"
// Qt
#include <QPainter>
PhotoW::PhotoW(QWidget *parent) : QWidget(parent) {
connect(&m_doubleClickTimer, &QTimer::timeout, this, [&]{
m_doubleClickTimer.stop();
});
}
void PhotoW::paintEvent(QPaintEvent *event) {
QWidget::paintEvent(event);
if (m_image.isNull())
return;
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
QSize widgetSize = event->rect().size();
QSize imageSize = m_image.size();
// imageSize.scale(event->rect().size(), Qt::KeepAspectRatio);
imageSize.scale(QSize(widgetSize.width()-2, widgetSize.height()-2), Qt::KeepAspectRatio);
QImage scaledImage = m_image.scaled(imageSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);
m_imageRect = QRectF(width()*0.5-scaledImage.size().width()*0.5,height()*0.5-scaledImage.size().height()*0.5,
scaledImage.width(), scaledImage.height());
QPen pen;
pen.setWidth(1);
pen.setColor(Qt::black);
painter.setPen(pen);
painter.drawImage(static_cast<int>(m_imageRect.x()), static_cast<int>(m_imageRect.y()), scaledImage);
painter.drawRect(QRectF(m_imageRect.x()-1, m_imageRect.y(), scaledImage.width()+1, scaledImage.height()+1));
}
const QImage* PhotoW::Image() const {
return &m_image;
}
void PhotoW::set_image (QImage image){
m_image = image;
}
void PhotoW::mousePressEvent(QMouseEvent *ev){
bool inside = m_imageRect.contains(ev->pos());
if(inside){
QPointF pos((ev->pos().x()-m_imageRect.x())/m_imageRect.width(), (ev->pos().y()-m_imageRect.y())/m_imageRect.height());
emit click_inside_signal(pos);
if(m_doubleClickTimer.isActive()){
emit double_click_signal();
}else{
m_doubleClickTimer.start(300);
}
}
}
| 38.058824 | 127 | 0.548171 | FlorianLance |
2e14073384a0c7faed9ffc4535640188330bef5f | 1,392 | hpp | C++ | src/Errors.hpp | evanova/libdgmpp | 867dc081b8dc474b396481ae1b92283affc858d3 | [
"MIT"
] | 4 | 2018-05-07T16:47:27.000Z | 2021-05-17T13:38:18.000Z | src/Errors.hpp | evanova/libdgmpp | 867dc081b8dc474b396481ae1b92283affc858d3 | [
"MIT"
] | null | null | null | src/Errors.hpp | evanova/libdgmpp | 867dc081b8dc474b396481ae1b92283affc858d3 | [
"MIT"
] | null | null | null | //
// Errors.hpp
// dgmpp
//
// Created by Artem Shimanski on 24.11.2017.
//
#pragma once
#include <stdexcept>
#include "Utility.hpp"
namespace dgmpp {
template <typename T>
struct CannotFit: public std::logic_error {
CannotFit(std::unique_ptr<T> type): type(std::move(type)), std::logic_error("Cannot fit") {}
std::unique_ptr<T> type;
};
struct InvalidSkillLevel: std::invalid_argument {
InvalidSkillLevel(): std::invalid_argument("Skill level should be in [0...5] range") {}
};
template<typename T>
class NotFound: public std::out_of_range {
public:
NotFound (T identifier) : std::out_of_range("id = " + std::to_string(static_cast<int>(identifier))) {};
};
struct NotEnoughCommodities: public std::logic_error {
NotEnoughCommodities(std::size_t quantity) : std::logic_error(std::to_string(quantity)) {}
};
struct InvalidRoute: public std::invalid_argument {
InvalidRoute() : std::invalid_argument("Missing source or destination") {}
};
struct InvalidCategoryID: public std::logic_error {
InvalidCategoryID(CategoryID categoryID): categoryID(categoryID), std::logic_error("Invalid categoryID") {};
CategoryID categoryID;
};
// struct DifferentCommodities: public std::runtime_error {
// DifferentCommodities(TypeID a, TypeID b) : std::runtime_error(std::to_string(static_cast<int>(a)) + " != " + std::to_string(static_cast<int>(b))) {}
// }
}
| 29 | 152 | 0.713362 | evanova |
2e141e86393b05b52f6f237f53e5f24da1e02ea0 | 6,553 | cc | C++ | lib/spot-2.8.1/bin/ltlgrind.cc | AlessandroCaste/SynkrisisJupyter | a9c2b21ec1ae7ac0c05ef5deebc63a369274650f | [
"Unlicense"
] | null | null | null | lib/spot-2.8.1/bin/ltlgrind.cc | AlessandroCaste/SynkrisisJupyter | a9c2b21ec1ae7ac0c05ef5deebc63a369274650f | [
"Unlicense"
] | null | null | null | lib/spot-2.8.1/bin/ltlgrind.cc | AlessandroCaste/SynkrisisJupyter | a9c2b21ec1ae7ac0c05ef5deebc63a369274650f | [
"Unlicense"
] | null | null | null | // -*- coding: utf-8 -*-
// Copyright (C) 2014, 2015, 2016, 2017, 2018 Laboratoire de Recherche et
// Développement de l'Epita (LRDE).
//
// This file is part of Spot, a model checking library.
//
// Spot is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// Spot is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
// License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#include "common_sys.hh"
#include <argp.h>
#include "error.h"
#include "common_setup.hh"
#include "common_finput.hh"
#include "common_output.hh"
#include "common_conv.hh"
#include "common_cout.hh"
#include <spot/tl/mutation.hh>
enum {
OPT_AP2CONST = 1,
OPT_SIMPLIFY_BOUNDS,
OPT_REMOVE_MULTOP_OPERANDS,
OPT_REMOVE_OPS,
OPT_SPLIT_OPS,
OPT_REWRITE_OPS,
OPT_REMOVE_ONE_AP,
OPT_SORT,
};
static unsigned mutation_nb = 1;
static unsigned max_output = -1U;
static unsigned opt_all = spot::Mut_All;
static unsigned mut_opts = 0;
static bool opt_sort = false;
static const char * argp_program_doc =
"List formulas that are similar to but simpler than a given formula.";
static const argp_option options[] = {
{ nullptr, 0, nullptr, 0,
"Mutation rules (all enabled unless those options are used):", 15},
{ "ap-to-const", OPT_AP2CONST, nullptr, 0,
"atomic propositions are replaced with true/false", 15 },
{ "remove-one-ap", OPT_REMOVE_ONE_AP, nullptr, 0,
"all occurrences of an atomic proposition are replaced with another " \
"atomic proposition used in the formula", 15 },
{ "remove-multop-operands", OPT_REMOVE_MULTOP_OPERANDS, nullptr, 0,
"remove one operand from multops", 15 },
{ "remove-ops", OPT_REMOVE_OPS, nullptr, 0,
"replace unary/binary operators with one of their operands", 15 },
{ "split-ops", OPT_SPLIT_OPS, nullptr, 0,
"when an operator can be expressed as a conjunction/disjunction using "
"simpler operators, each term of the conjunction/disjunction is a "
"mutation. e.g. a <-> b can be written as ((a & b) | (!a & !b)) or as "
"((a -> b) & (b -> a)) so those four terms can be a mutation of a <-> b",
0 },
{ "rewrite-ops", OPT_REWRITE_OPS, nullptr, 0,
"rewrite operators that have a semantically simpler form: a U b becomes "
"a W b, etc.", 0 },
{ "simplify-bounds", OPT_SIMPLIFY_BOUNDS, nullptr, 0,
"on a bounded unary operator, decrement one of the bounds, or set min to "
"0 or max to unbounded", 15 },
/**************************************************/
{ nullptr, 0, nullptr, 0, "Output options:", -20 },
{ "max-count", 'n', "NUM", 0, "maximum number of mutations to output", 0 },
{ "mutations", 'm', "NUM", 0, "number of mutations to apply to the "
"formulae (default: 1)", 0 },
{ "sort", OPT_SORT, nullptr, 0, "sort the result by formula size", 0 },
{ nullptr, 0, nullptr, 0, "The FORMAT string passed to --format may use "
"the following interpreted sequences:", -19 },
{ "%f", 0, nullptr, OPTION_DOC | OPTION_NO_USAGE,
"the formula (in the selected syntax)", 0 },
{ "%F", 0, nullptr, OPTION_DOC | OPTION_NO_USAGE,
"the name of the input file", 0 },
{ "%L", 0, nullptr, OPTION_DOC | OPTION_NO_USAGE,
"the original line number in the input file", 0 },
{ "%<", 0, nullptr, OPTION_DOC | OPTION_NO_USAGE,
"the part of the line before the formula if it "
"comes from a column extracted from a CSV file", 0 },
{ "%>", 0, nullptr, OPTION_DOC | OPTION_NO_USAGE,
"the part of the line after the formula if it "
"comes from a column extracted from a CSV file", 0 },
{ "%%", 0, nullptr, OPTION_DOC | OPTION_NO_USAGE,
"a single %", 0 },
COMMON_LTL_OUTPUT_SPECS,
/**************************************************/
{ nullptr, 0, nullptr, 0, "Miscellaneous options:", -1 },
{ nullptr, 0, nullptr, 0, nullptr, 0 }
};
static const argp_child children[] = {
{ &finput_argp, 0, nullptr, 10 },
{ &output_argp, 0, nullptr, 0 },
{ &misc_argp, 0, nullptr, 0 },
{ nullptr, 0, nullptr, 0 }
};
namespace
{
class mutate_processor final: public job_processor
{
public:
int
process_formula(spot::formula f, const char* filename = nullptr,
int linenum = 0) override
{
auto mutations =
spot::mutate(f, mut_opts, max_output, mutation_nb, opt_sort);
for (auto g: mutations)
output_formula_checked(g, nullptr, filename, linenum, prefix, suffix);
return 0;
}
};
}
static int
parse_opt(int key, char* arg, struct argp_state*)
{
switch (key)
{
case 'm':
mutation_nb = to_unsigned(arg, "-m/--mutations");
break;
case 'n':
max_output = to_int(arg, "-n/--max-count");
break;
case ARGP_KEY_ARG:
// FIXME: use stat() to distinguish filename from string?
jobs.emplace_back(arg, true);
break;
case OPT_AP2CONST:
opt_all = 0;
mut_opts |= spot::Mut_Ap2Const;
break;
case OPT_REMOVE_ONE_AP:
opt_all = 0;
mut_opts |= spot::Mut_Remove_One_Ap;
break;
case OPT_REMOVE_MULTOP_OPERANDS:
opt_all = 0;
mut_opts |= spot::Mut_Remove_Multop_Operands;
break;
case OPT_REMOVE_OPS:
opt_all = 0;
mut_opts |= spot::Mut_Remove_Ops;
break;
case OPT_SPLIT_OPS:
opt_all = 0;
mut_opts |= spot::Mut_Split_Ops;
break;
case OPT_REWRITE_OPS:
opt_all = 0;
mut_opts |= spot::Mut_Rewrite_Ops;
break;
case OPT_SIMPLIFY_BOUNDS:
opt_all = 0;
mut_opts |= spot::Mut_Simplify_Bounds;
break;
case OPT_SORT:
opt_sort = true;
break;
default:
return ARGP_ERR_UNKNOWN;
}
return 0;
}
int
main(int argc, char* argv[])
{
return protected_main(argv, [&] {
const argp ap = { options, parse_opt, "[FILENAME[/COL]...]",
argp_program_doc, children, nullptr, nullptr };
if (int err = argp_parse(&ap, argc, argv, ARGP_NO_HELP, nullptr, nullptr))
exit(err);
mut_opts |= opt_all;
check_no_formula();
mutate_processor processor;
if (processor.run())
return 2;
flush_cout();
return 0;
});
}
| 32.122549 | 80 | 0.638944 | AlessandroCaste |
2e14cd667b1a7dbae292b61e1fbe62108f0d69d8 | 1,118 | cpp | C++ | LeetCode/C++/General/Medium/MinimumAddToMakeParenthesesValid/solution.cpp | busebd12/InterviewPreparation | e68c41f16f7790e44b10a229548186e13edb5998 | [
"MIT"
] | null | null | null | LeetCode/C++/General/Medium/MinimumAddToMakeParenthesesValid/solution.cpp | busebd12/InterviewPreparation | e68c41f16f7790e44b10a229548186e13edb5998 | [
"MIT"
] | null | null | null | LeetCode/C++/General/Medium/MinimumAddToMakeParenthesesValid/solution.cpp | busebd12/InterviewPreparation | e68c41f16f7790e44b10a229548186e13edb5998 | [
"MIT"
] | null | null | null | #include <deque>
#include <string>
using namespace std;
class Solution
{
public:
int minAddToMakeValid(string s)
{
int result=0;
deque<char> stack;
for(auto & character : s)
{
//Push open ( onto the stack
if(character=='(')
{
stack.emplace_back(character);
}
else
{
//If the stack is not empty then we have found a matching ( for the current )
if(!stack.empty())
{
stack.pop_back();
}
//The stack is empty and we are missing a )
else
{
result+=1;
}
}
}
//If the stack is not empty, then the stack contains the number of ( that need a matching )
if(!stack.empty())
{
result+=stack.size();
}
return result;
}
}; | 25.409091 | 103 | 0.376565 | busebd12 |
2e19873f0e039a428ed40c8bde870a8aa988e0ce | 449 | cpp | C++ | src/digital_clock.cpp | imharris24/Digital-Clock | dbca263357f4fed182e278e8133dba07471583d8 | [
"CC0-1.0"
] | null | null | null | src/digital_clock.cpp | imharris24/Digital-Clock | dbca263357f4fed182e278e8133dba07471583d8 | [
"CC0-1.0"
] | null | null | null | src/digital_clock.cpp | imharris24/Digital-Clock | dbca263357f4fed182e278e8133dba07471583d8 | [
"CC0-1.0"
] | null | null | null | #include "digital_clock.h"
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<chrono>
#include<ctime>
#include<Windows.h>
using namespace std;
void DisplayTime()
{
auto CurrentTime = chrono::system_clock::now();
while (true)
{
system("cls");
CurrentTime = chrono::system_clock::now();
time_t Current_T = chrono::system_clock::to_time_t(CurrentTime);
cout << "\n\tDate & Time : " << ctime(&Current_T) << "\n";
Sleep(999);
}
} | 21.380952 | 66 | 0.697105 | imharris24 |
2e1c505128c9453740642d5763549d151330ed78 | 5,570 | cpp | C++ | commands.cpp | jekhor/pneumatic-tc-firmware | a532d78a154cc963d98c239c916485f5383f3dcf | [
"CC-BY-3.0"
] | 1 | 2018-10-08T13:28:32.000Z | 2018-10-08T13:28:32.000Z | commands.cpp | jekhor/pneumatic-tc-firmware | a532d78a154cc963d98c239c916485f5383f3dcf | [
"CC-BY-3.0"
] | 9 | 2019-08-21T18:07:49.000Z | 2019-09-30T19:48:28.000Z | commands.cpp | jekhor/pneumatic-tc-firmware | a532d78a154cc963d98c239c916485f5383f3dcf | [
"CC-BY-3.0"
] | null | null | null |
#include <Arduino.h>
#include <Time.h>
#include <DS1307RTC.h>
#include <SdFat.h>
#include "common.h"
#include "sd_log.h"
#include "timers.h"
static int scan_time(char *date, char *time,
unsigned short *y, tmElements_t *tm)
{
uint16_t numbers[3];
char *c;
int i = 0;
c = strtok(date, "-");
while (c && (i < 3)) {
numbers[i] = atoi(c);
c = strtok(NULL, "-");
i++;
}
if (i != 3)
return 1;
*y = numbers[0];
tm->Month = numbers[1];
tm->Day = numbers[2];
i = 0;
c = strtok(time, ":");
while (c && (i < 3)) {
numbers[i] = atoi(c);
c = strtok(NULL, ":");
i++;
}
if (i != 3)
return 1;
tm->Hour = numbers[0];
tm->Minute = numbers[1];
tm->Second = numbers[2];
return 0;
}
static char cmd_time(char argc, char *argv[]) {
unsigned short int y;
tmElements_t tm;
if (argc == 0) {
printTime(now());
return 0;
}
if (argc != 2) {
Serial.println(F("Usage: time YYYY-MM-DD HH:MM:SS"));
return 1;
}
if (scan_time(argv[0], argv[1], &y, &tm)) {
Serial.println(F("Cannot parse time"));
return 1;
}
tm.Year = y - 1970;
if (!RTC.write(tm))
Serial.println(F("RTC error"));
setTime(makeTime(tm));
if (!RTC.read(tm))
Serial.println(F("RTC error"));
printTime(now());
return 0;
}
static char cmd_ls(char, char *[]) {
if (!isSdReady())
return 1;
root.ls(LS_SIZE);
return 0;
}
static SdFile file;
static char filename[13];
static char cmd_dumpall(char, char *[])
{
if (!isSdReady())
return 1;
root.close();
root.open(sd_counter_dir, O_READ);
while (file.openNext(&root, O_RDONLY)) {
if (file.isDir())
goto next_file;
if (!file.getName(filename, sizeof(filename)))
goto next_file;
if (!strstr(filename, ".CSV"))
goto next_file;
Serial.println(filename);
dumpSdLog(filename);
next_file:
file.close();
}
return 0;
}
static char cmd_dump(char argc, char *argv[]) {
if (argc == 1)
return dumpSdLog(argv[0]);
else
return dumpSdLog(NULL);
return 0;
}
static char cmd_raw(char, char *[]) {
raw_measuring = !raw_measuring;
if (raw_measuring) {
if (raw_measuring)
stop_timer(IDLE_TIMEOUT_TIMER);
else
schedule_timer(IDLE_TIMEOUT_TIMER, IDLE_TIMEOUT_MS);
}
return 0;
}
static char cmd_batt(char, char *[]) {
Serial.println(readBattery_mV());
return 0;
}
static char cmd_poff(char, char *[]) {
digitalWrite(LED_PIN, 1);
digitalWrite(PWR_ON_PIN, 0);
return 0;
}
static char cmd_bt(char argc, char *argv[]) {
if (argc != 1) {
Serial.print(F("Bluetooth "));
if (bluetooth_mode == BT_PERMANENT)
Serial.println(F("ON"));
else
Serial.println(F("AUTO"));
} else {
if (!strcmp(argv[0], "on")) {
set_bluetooth_mode(BT_PERMANENT);
} else if (!strcmp(argv[0], "auto")) {
set_bluetooth_mode(BT_AUTO);
}
}
return 0;
}
static char cmd_ver(char, char *[])
{
Serial.println(F("Build: " __DATE__ " " __TIME__));
return 0;
}
static char cmd_help(char, char *[]) {
puts_P(PSTR(
"Commands:\n"
" time [yyyy-mm-dd HH:MM:SS] \t - get/set time\n"
" raw\t\t\t\t - toggle raw dump\n"
" ls\t\t\t\t - list files on SD\n"
" dump [file]\t\t\t - dump file content\n"
" dumpall [file]\t\t\t - dump all logs content\n"
" batt\t\t\t\t - show battery voltage\n"
" bt [on|auto]\t\t\t - bluetooth enabled permanently/on demand (by magnet)\n"
" ver \t\t\t\t – show firmware version\n"
));
return 0;
}
typedef char (*cmd_handler_t)(char argc, char *argv[]);
struct cmd_table_entry {
PGM_P cmd;
cmd_handler_t handler;
};
static const char cmd_time_name[] PROGMEM = "time";
static const char cmd_ls_name[] PROGMEM = "ls";
static const char cmd_dump_name[] PROGMEM = "dump";
static const char cmd_dumpall_name[] PROGMEM = "dumpall";
static const char cmd_raw_name[] PROGMEM = "raw";
static const char cmd_poff_name[] PROGMEM = "poff";
static const char cmd_batt_name[] PROGMEM = "batt";
static const char cmd_bt_name[] PROGMEM = "bt";
static const char cmd_ver_name[] PROGMEM = "ver";
static const char cmd_help_name[] PROGMEM = "help";
#define CMD(name) {cmd_ ## name ## _name, cmd_ ## name}
static PROGMEM const struct cmd_table_entry cmd_table[] = {
CMD(time),
CMD(ls),
CMD(dump),
CMD(dumpall),
CMD(raw),
CMD(poff),
CMD(batt),
CMD(bt),
CMD(ver),
CMD(help),
};
#define MAX_CMD_ARGS 3
void parse_cmdline(char *buf, uint8_t) {
char *cmd = strtok(buf, " ");
struct cmd_table_entry cmd_entry;
char *argv[MAX_CMD_ARGS];
uint8_t argc = 0;
unsigned char i;
char ret = 1;
if (!cmd)
return;
while (argc < MAX_CMD_ARGS) {
argv[argc] = strtok(NULL, " ");
if (argv[argc])
argc++;
else
break;
}
for (i = 0; i < ARRAY_SIZE(cmd_table); i++) {
memcpy_P(&cmd_entry, &cmd_table[i], sizeof(cmd_entry));
if (!strcmp_P(cmd, cmd_entry.cmd)) {
ret = cmd_entry.handler(argc, argv);
break;
}
}
if (ret)
Serial.println("ERROR");
}
#define SERIAL_BUF_LEN 60
static char serial_buf[SERIAL_BUF_LEN];
static uint8_t serial_buf_level = 0;
void processSerial() {
char c;
while (Serial.available()) {
idle_sleep_mode = SLEEP_MODE_IDLE;
// digitalWrite(LED_PIN, 1);
schedule_timer(IDLE_TIMEOUT_TIMER, IDLE_TIMEOUT_MS);
c = Serial.read();
Serial.write(c);
// digitalWrite(LED_PIN, 1);
if ((c == '\r') || (c == '\n')) {
if (c == '\r')
Serial.write('\n');
serial_buf[serial_buf_level] = '\0';
serial_buf_level++;
parse_cmdline(serial_buf, serial_buf_level);
serial_buf_level = 0;
Serial.write("> ");
} else {
if (serial_buf_level < SERIAL_BUF_LEN - 1) {
serial_buf[serial_buf_level] = c;
serial_buf_level++;
}
}
}
// digitalWrite(LED_PIN, 0);
}
| 18.262295 | 78 | 0.63842 | jekhor |
2e1e311a60c2b658b683d9387bd1803c5c401c37 | 366 | hpp | C++ | include/amcl_3d/time.hpp | yukkysaito/amcl_3d | 3284678ee2f184fb704a44c2affc8d398ece5863 | [
"BSD-3-Clause"
] | 10 | 2019-08-16T05:17:38.000Z | 2022-03-09T07:59:03.000Z | include/amcl_3d/time.hpp | rsasaki0109/amcl_3d | 584d49a94666b6ee4aab9652d2142274b96e7c6c | [
"BSD-3-Clause"
] | 2 | 2018-10-10T06:59:23.000Z | 2019-06-04T01:09:55.000Z | include/amcl_3d/time.hpp | yukkysaito/amcl_3d | 3284678ee2f184fb704a44c2affc8d398ece5863 | [
"BSD-3-Clause"
] | 6 | 2018-10-10T06:57:56.000Z | 2020-07-19T11:58:08.000Z | #pragma once
#include <ros/ros.h>
namespace amcl_3d
{
struct Time
{
Time(const ros::Time &ros_time);
Time();
ros::Time toROSTime();
static Time fromROSTime(const ros::Time &ros_time);
static double getDiff(const Time &start, const Time &end);
static Time getTimeNow();
unsigned int sec;
unsigned int nsec;
};
} // namespace amcl_3d | 19.263158 | 62 | 0.669399 | yukkysaito |
2e1f15e6407285d8ca29dc73ca68db4183dee667 | 2,024 | hpp | C++ | willow/include/popart/op/onehot.hpp | gglin001/popart | 3225214343f6d98550b6620e809a3544e8bcbfc6 | [
"MIT"
] | 61 | 2020-07-06T17:11:46.000Z | 2022-03-12T14:42:51.000Z | willow/include/popart/op/onehot.hpp | gglin001/popart | 3225214343f6d98550b6620e809a3544e8bcbfc6 | [
"MIT"
] | 1 | 2021-02-25T01:30:29.000Z | 2021-11-09T11:13:14.000Z | willow/include/popart/op/onehot.hpp | gglin001/popart | 3225214343f6d98550b6620e809a3544e8bcbfc6 | [
"MIT"
] | 6 | 2020-07-15T12:33:13.000Z | 2021-11-07T06:55:00.000Z | // Copyright (c) 2019 Graphcore Ltd. All rights reserved.
#ifndef GUARD_NEURALNET_ONEHOT_HPP
#define GUARD_NEURALNET_ONEHOT_HPP
#include <popart/op.hpp>
namespace popart {
// This Op is based on the ONNX Operator described at
// github.com/onnx/onnx/blob/master/docs/Operators.md#Onehot
// but it is slightly different: this Op is static w.r.t. depth
class OnehotOp : public Op {
public:
OnehotOp(const OperatorIdentifier &_opid,
int64_t axis_,
const Op::Settings &settings_);
std::unique_ptr<Op> clone() const override;
std::vector<std::unique_ptr<Op>> getGradOps() final;
void setup() override;
void appendOutlineAttributes(OpSerialiserBase &) const override;
// The depth input is not connected to Onehot as an input
// but rather is read in the connectInTensor method and used
// to set the onehotAxisDim member variable
static InIndex getIndicesInIndex() { return 0; }
static InIndex getValuesInIndex() { return 2; }
static OutIndex getOutIndex() { return 0; }
virtual void connectInTensor(InIndex inIndex, TensorId tenId) override;
int64_t getAxis() const { return axis; }
float getSubgraphValue() const final { return getLowSubgraphValue(); }
private:
int64_t axis;
int64_t onehotAxisDim;
};
class OnehotGradOp : public Op {
public:
OnehotGradOp(const OnehotOp &fwdOp_);
std::unique_ptr<Op> clone() const final;
void setup() override;
const std::vector<GradInOutMapper> &gradInputInfo() const final;
const std::map<int, int> &gradOutToNonGradIn() const final;
static InIndex getGradInIndex() { return 0; }
static InIndex getIndicesInIndex() { return 1; }
static OutIndex getOutIndex() { return 0; }
const Shape &getOutputShape() const { return outputShape; }
int64_t getAxis() const { return axis; }
void appendOutlineAttributes(OpSerialiserBase &) const override;
float getSubgraphValue() const final { return getLowSubgraphValue(); }
private:
int64_t axis;
Shape outputShape;
};
} // namespace popart
#endif
| 26.631579 | 73 | 0.733696 | gglin001 |
2e202efccdb33bbe69ac1aad6b1e464c2568882d | 329 | cpp | C++ | chap15/Exer15_39/Exer15_39_Query.cpp | sjbarigye/CPP_Primer | d9d31a73a45ca46909bae104804fc9503ab242f2 | [
"Apache-2.0"
] | 50 | 2016-01-08T14:28:53.000Z | 2022-01-21T12:55:00.000Z | chap15/Exer15_39/Exer15_39_Query.cpp | sjbarigye/CPP_Primer | d9d31a73a45ca46909bae104804fc9503ab242f2 | [
"Apache-2.0"
] | 2 | 2017-06-05T16:45:20.000Z | 2021-04-17T13:39:24.000Z | chap15/Exer15_39/Exer15_39_Query.cpp | sjbarigye/CPP_Primer | d9d31a73a45ca46909bae104804fc9503ab242f2 | [
"Apache-2.0"
] | 18 | 2016-08-17T15:23:51.000Z | 2022-03-26T18:08:43.000Z | #include "Exer15_39_Query.h"
// constructor of Query that takes a string parameter
// inline Query::Query(const std::string &s) : q(new WordQuery(s)) {}
std::ostream& operator<<(std::ostream &os, const Query &query)
{
// Query::rep makes a virtual call through its Query_base pointer to rep()
return os << query.rep();
}
| 36.555556 | 78 | 0.696049 | sjbarigye |
2e20b9a48da2e1862fe66206b15fb8f82bbb61b7 | 425 | cpp | C++ | tests/testcases/logical.cpp | TheLartians/integer | 6c76aef01279dfed0547edfb358288f5435f1773 | [
"MIT"
] | 23 | 2017-11-12T21:28:50.000Z | 2021-11-15T14:03:01.000Z | tests/testcases/logical.cpp | TheLartians/integer | 6c76aef01279dfed0547edfb358288f5435f1773 | [
"MIT"
] | 2 | 2018-09-24T01:06:36.000Z | 2021-06-04T01:37:42.000Z | tests/testcases/logical.cpp | TheLartians/integer | 6c76aef01279dfed0547edfb358288f5435f1773 | [
"MIT"
] | 8 | 2018-08-26T17:32:29.000Z | 2021-09-28T17:58:58.000Z | #include <gtest/gtest.h>
#include "integer.h"
TEST(Logical, and){
const integer A("ffffffff", 16);
const integer B("00000000", 16);
EXPECT_EQ(A && A, true);
EXPECT_EQ(A && B, false);
}
TEST(Logical, or){
const integer A("ffffffff", 16);
const integer B("00000000", 16);
EXPECT_EQ(A || A, true);
EXPECT_EQ(A || B, true);
}
TEST(Logical, not){
EXPECT_EQ(!integer("ffffffff", 16), 0);
} | 18.478261 | 43 | 0.597647 | TheLartians |
2e2523e00203352c8b7d1cc80284af8205793086 | 2,390 | cc | C++ | util/src/stringutil.cc | robert-mijakovic/readex-ptf | 5514b0545721ef27de0426a7fa0116d2e0bb5eef | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | util/src/stringutil.cc | robert-mijakovic/readex-ptf | 5514b0545721ef27de0426a7fa0116d2e0bb5eef | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | util/src/stringutil.cc | robert-mijakovic/readex-ptf | 5514b0545721ef27de0426a7fa0116d2e0bb5eef | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | /**
@file stringutil.cc
@brief String manipulation routines
@author Karl Fuerlinger
@verbatim
Revision: $Revision$
Revision date: $Date$
Committed by: $Author$
This file is part of the Periscope performance measurement tool.
See http://www.lrr.in.tum.de/periscope for details.
Copyright (c) 2005-2011, Technische Universitaet Muenchen, Germany
See the COPYING file in the base directory of the package for details.
@endverbatim
*/
#include <string>
#include <iostream>
#include <algorithm>
#include "strutil.h"
using std::string;
using std::cout;
using std::endl;
using std::pair;
size_t strskip_ws( std::string str, int pos ) {
return str.find_first_not_of( "\t ", pos );
}
size_t get_token( std::string str, int pos, std::string delim, std::string& tok ) {
std::string::size_type p1, p2;
p1 = str.find_first_not_of( delim, pos );
if( p1 == std::string::npos ) {
tok = "";
return std::string::npos;
}
p2 = str.find_first_of( delim, p1 );
if( p2 == std::string::npos ) {
tok = str.substr( p1, str.size() - p1 );
return std::string::npos;
}
tok = str.substr( p1, p2 - p1 );
return p2;
}
// list< pair<std::string, std::string> >& kvpairs
size_t get_key_value_pair( std::string str, int pos,
std::pair< std::string, std::string >& kvpair ) {
std::string key, value;
std::string::size_type p1;
// get the key
p1 = get_token( str, pos, " =", key );
if( p1 == std::string::npos ) {
kvpair.first = "";
kvpair.second = "";
return std::string::npos;
}
// expect '=' next
p1 = strskip_ws( str, p1 );
if( p1 == std::string::npos ||
str[ p1 ] != '=' ) {
kvpair.first = "";
kvpair.second = "";
return std::string::npos;
}
p1 = strskip_ws( str, p1 + 1 );
if( p1 == std::string::npos ) {
kvpair.first = "";
kvpair.second = "";
return std::string::npos;
}
// value could be enclosed in double quotes
if( str[ p1 ] == '"' ) {
p1 = get_token( str, p1, "\"", value );
}
else {
p1 = get_token( str, p1, " ", value );
}
if( p1 != std::string::npos ) {
p1++;
}
kvpair.first = key;
kvpair.second = value;
return p1;
}
| 22.980769 | 83 | 0.551046 | robert-mijakovic |
2e26e1b7b19f70826b7622c37e091634e9149841 | 33,172 | cpp | C++ | admin/wmi/wbem/providers/win32provider/providers/protocol.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | admin/wmi/wbem/providers/win32provider/providers/protocol.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | admin/wmi/wbem/providers/win32provider/providers/protocol.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //=================================================================
//
// Protocol.CPP -- Network Protocol property set provider
//
// Copyright (c) 1996-2001 Microsoft Corporation, All Rights Reserved
//
// Revisions: 08/28/96 a-jmoon Created
// 10/27/97 davwoh Moved to curly
// 1/20/98 jennymc Added socket 2.2 support
//
//=================================================================
#include "precomp.h"
#include <iostream.h>
#define INCL_WINSOCK_API_TYPEDEFS 1
#include <winsock2.h>
#include <cregcls.h>
#include "Ws2_32Api.h"
#include "Wsock32Api.h"
#include <nspapi.h>
#include "Protocol.h"
#include "poormansresource.h"
#include "resourcedesc.h"
#include "cfgmgrdevice.h"
#include <typeinfo.h>
#include <ntddndis.h>
#include <traffic.h>
#include <dllutils.h>
#include <..\..\framework\provexpt\include\provexpt.h>
// Property set declaration
//=========================
CWin32Protocol MyProtocolSet(PROPSET_NAME_PROTOCOL, IDS_CimWin32Namespace);
/*****************************************************************************
*
* FUNCTION : CWin32Protocol::CWin32Protocol
*
* DESCRIPTION : Constructor
*
* INPUTS : none
*
* OUTPUTS : none
*
* RETURNS : nothing
*
* COMMENTS : Registers property set with framework
*
*****************************************************************************/
CWin32Protocol::CWin32Protocol( LPCWSTR a_name, LPCWSTR a_pszNamespace )
:Provider( a_name, a_pszNamespace )
{
}
/*****************************************************************************
*
* FUNCTION : CWin32Protocol::~CWin32Protocol
*
* DESCRIPTION : Destructor
*
* INPUTS : none
*
* OUTPUTS : none
*
* RETURNS : nothing
*
* COMMENTS : Deregisters property set from framework
*
*****************************************************************************/
CWin32Protocol::~CWin32Protocol()
{
}
/*****************************************************************************
*
* FUNCTION : CWin32Protocol::GetObject
*
* DESCRIPTION : Assigns values to property set according to key value
* already set by framework
*
* INPUTS : none
*
* OUTPUTS : none
*
* RETURNS : TRUE if success, FALSE otherwise
*
* COMMENTS :
*
*****************************************************************************/
HRESULT CWin32Protocol::GetObject( CInstance *a_pInst, long a_lFlags /*= 0L*/ )
{
HRESULT t_hResult = WBEM_E_NOT_FOUND;
CProtocolEnum t_Protocol ;
CHString t_sName ;
//===========================================
// Get the correct version of sockets
//===========================================
if( !t_Protocol.InitializeSockets() )
{
return WBEM_E_FAILED ;
}
//===========================================
// Go thru the list of protocols
//===========================================
a_pInst->GetCHString( IDS_Name, t_sName ) ;
if( t_Protocol.GetProtocol( a_pInst, t_sName ) )
{
// we found it
t_hResult = WBEM_S_NO_ERROR ;
}
return t_hResult ;
}
/*****************************************************************************
*
* FUNCTION : CWin32Protocol::EnumerateInstances
*
* DESCRIPTION : Creates instance of property set for each logical disk
*
* INPUTS : none
*
* OUTPUTS : none
*
* RETURNS : Number of instances created
*
* COMMENTS :
*
*****************************************************************************/
HRESULT CWin32Protocol::EnumerateInstances( MethodContext *a_pMethodContext, long a_lFlags /*= 0L*/)
{
HRESULT t_hResult = WBEM_S_NO_ERROR ;
CProtocolEnum t_Protocol;
CHString t_chsTmp;
t_chsTmp.Empty();
// smart ptr
CInstancePtr t_pInst ;
//===========================================
// Get the correct version of sockets
//===========================================
if( !t_Protocol.InitializeSockets() )
{
return WBEM_E_FAILED ;
}
//===========================================
// Get the list of protocols
//===========================================
while( SUCCEEDED( t_hResult ) )
{
t_pInst.Attach( CreateNewInstance( a_pMethodContext ) ) ;
if( t_Protocol.GetProtocol( t_pInst, t_chsTmp ) )
{
t_hResult = t_pInst->Commit();
}
else
{
break;
}
}
return t_hResult ;
}
////////////////////////////////////////////////////////////////////////
//=====================================================================
// Try to do it using winsock 2.2 for more information, otherwise
// do it the old way
//=====================================================================
CProtocolEnum::CProtocolEnum()
{
m_pProtocol = NULL ;
}
//
CProtocolEnum::~CProtocolEnum()
{
if( m_pProtocol )
{
delete m_pProtocol ;
m_pProtocol = NULL ;
}
}
//=====================================================================
BOOL CProtocolEnum::InitializeSockets()
{
BOOL t_fRc = FALSE ;
m_pProtocol = new CSockets22();
if( !m_pProtocol )
{
throw CHeap_Exception( CHeap_Exception::E_ALLOCATION_ERROR ) ;
}
if( m_pProtocol->BeginEnumeration() )
{
t_fRc = TRUE ;
}
else
{
if( m_pProtocol )
{
delete m_pProtocol ;
m_pProtocol = NULL;
}
m_pProtocol = new CSockets11();
if( !m_pProtocol )
{
throw CHeap_Exception( CHeap_Exception::E_ALLOCATION_ERROR ) ;
}
if( m_pProtocol->BeginEnumeration() )
{
t_fRc = TRUE ;
}
else
{
delete m_pProtocol ;
m_pProtocol = NULL;
}
}
return t_fRc ;
}
//=====================================================================
//
// Yes, I know the proper way is to provide functions to return
// all of the data values, but I'm lazy....
//
//=====================================================================
BOOL CProtocolEnum::GetProtocol( CInstance *a_pInst,CHString t_chsName )
{
return( m_pProtocol->GetProtocol( a_pInst, t_chsName ) );
}
//********************************************************************
// Protocol class
//********************************************************************
CProtocol::CProtocol()
{
Init();
}
//
void CProtocol::Init()
{
m_pbBuffer = NULL ;
m_nTotalProtocols = 0 ;
m_nCurrentProtocol = 0 ;
}
//
CProtocol::~CProtocol()
{
if( m_pbBuffer )
{
delete [] m_pbBuffer;
m_pbBuffer = NULL;
}
Init();
}
//
BOOL CProtocol::SetDateFromFileName( CHString &a_chsFileName, CInstance *a_pInst )
{
BOOL t_fRc = FALSE ;
_bstr_t t_bstrFileName ;
// strip off any trailing switches
int t_iTokLen = a_chsFileName.Find( L" " ) ;
if( -1 != t_iTokLen )
{
t_bstrFileName = a_chsFileName.Left( t_iTokLen ) ;
}
else
{
t_bstrFileName = a_chsFileName ;
}
WIN32_FILE_ATTRIBUTE_DATA t_FileAttributes;
if( GetFileAttributesEx(t_bstrFileName, GetFileExInfoStandard, &t_FileAttributes) )
{
TCHAR t_Buff[_MAX_PATH];
CHString t_sDrive = a_chsFileName.Left(3);
if (!GetVolumeInformation(TOBSTRT(t_sDrive), NULL, 0, NULL, NULL, NULL, t_Buff, _MAX_PATH) ||
(_tcscmp(t_Buff, _T("NTFS")) != 0) )
{
bstr_t t_InstallDate(WBEMTime(t_FileAttributes.ftCreationTime).GetDMTFNonNtfs(), false);
a_pInst->SetWCHARSplat( IDS_InstallDate, t_InstallDate) ;
}
else
{
a_pInst->SetDateTime( IDS_InstallDate, t_FileAttributes.ftCreationTime) ;
}
t_fRc = TRUE ;
}
return t_fRc ;
}
//********************************************************************
// SOCKETS 2.2 implementation
//********************************************************************
CSockets22::CSockets22()
: m_pws32api( NULL ),
m_fAlive( FALSE )
{
m_pws32api = (CWs2_32Api*) CResourceManager::sm_TheResourceManager.GetResource(g_guidWs2_32Api, NULL);
// Note a NULL pointer indicates the DLL is not present on the system
if( m_pws32api != NULL )
{
WSADATA t_wsaData;
m_fAlive = ( m_pws32api->WSAStartUp( 0x202, &t_wsaData) == 0 ) ;
}
}
CSockets22::~CSockets22()
{
if( m_fAlive && m_pws32api )
{
m_pws32api->WSACleanup();
}
if( m_pws32api )
{
CResourceManager::sm_TheResourceManager.ReleaseResource(g_guidWs2_32Api, m_pws32api);
m_pws32api = NULL ;
}
}
/////////////////////////////////////////////////////////////////////
BOOL CSockets22::BeginEnumeration()
{
BOOL t_fRc = FALSE,
t_fEnum = FALSE ;
if( !m_fAlive )
{
return t_fRc ;
}
//===========================================================
// Now, get a list of protocols
//===========================================================
DWORD t_dwSize = 4096 ;
while( TRUE )
{
m_pbBuffer = new byte[ t_dwSize ] ;
if( !m_pbBuffer )
{
throw CHeap_Exception( CHeap_Exception::E_ALLOCATION_ERROR ) ;
}
m_pInfo = (LPWSAPROTOCOL_INFO) m_pbBuffer ;
if ( ( m_nTotalProtocols = m_pws32api->WSAEnumProtocols( NULL, m_pInfo, &t_dwSize ) ) == SOCKET_ERROR )
{
if( m_pws32api->WSAGetLastError() == WSAENOBUFS )
{
// buffer too small
delete [] m_pbBuffer ;
m_pbBuffer = NULL;
}
else
{
t_fRc = FALSE ;
break ;
}
}
else
{
t_fRc = TRUE ;
break ;
}
}
return t_fRc ;
}
//=====================================================================
BOOL CSockets22::GetProtocol( CInstance *a_pInst, CHString a_chsName )
{
BOOL t_fRc = FALSE ;
if( m_nCurrentProtocol < m_nTotalProtocols )
{
//==============================================
// If chsName is not empty, then we are looking
// for a specific protocol, otherwise, we are
// enumerating them.
//==============================================
while( m_nCurrentProtocol < m_nTotalProtocols )
{
if( !a_chsName.IsEmpty() )
{
if( _tcsicmp( m_pInfo[ m_nCurrentProtocol ].szProtocol, TOBSTRT( a_chsName ) ) == 0 )
{
LoadProtocol( a_pInst ) ;
t_fRc = TRUE ;
}
}
else
{
LoadProtocol( a_pInst ) ;
t_fRc = TRUE ;
}
m_nCurrentProtocol++ ;
if( t_fRc )
{
break ;
}
}
}
return t_fRc ;
}
//====================================================================
void CSockets22::LoadProtocol( CInstance *a_pInst )
{
a_pInst->SetCHString( IDS_Name, (LPCTSTR) m_pInfo[ m_nCurrentProtocol ].szProtocol);
a_pInst->SetCHString( IDS_Caption, (LPCTSTR) m_pInfo[ m_nCurrentProtocol ].szProtocol);
a_pInst->SetCHString( IDS_Description, (LPCTSTR) m_pInfo[ m_nCurrentProtocol ].szProtocol);
a_pInst->SetDWORD( L"MaximumMessageSize", m_pInfo[ m_nCurrentProtocol ].dwMessageSize );
a_pInst->SetDWORD( L"MaximumAddressSize", (DWORD) m_pInfo[ m_nCurrentProtocol ].iMaxSockAddr );
a_pInst->SetDWORD( L"MinimumAddressSize", (DWORD) m_pInfo[ m_nCurrentProtocol ].iMinSockAddr );
a_pInst->Setbool( L"ConnectionlessService", m_pInfo[ m_nCurrentProtocol ].dwServiceFlags1 & XP1_CONNECTIONLESS ? TRUE : FALSE );
a_pInst->Setbool( L"MessageOriented", m_pInfo[ m_nCurrentProtocol ].dwServiceFlags1 & XP1_MESSAGE_ORIENTED ? TRUE : FALSE );
a_pInst->Setbool( L"PseudoStreamOriented", m_pInfo[ m_nCurrentProtocol ].dwServiceFlags1 & XP1_PSEUDO_STREAM ? TRUE : FALSE );
a_pInst->Setbool( L"GuaranteesDelivery", m_pInfo[ m_nCurrentProtocol ].dwServiceFlags1 & XP1_GUARANTEED_DELIVERY ? TRUE : FALSE );
a_pInst->Setbool( L"GuaranteesSequencing", m_pInfo[ m_nCurrentProtocol ].dwServiceFlags1 & XP1_GUARANTEED_ORDER ? TRUE : FALSE );
a_pInst->Setbool( L"SupportsGracefulClosing", m_pInfo[ m_nCurrentProtocol ].dwServiceFlags1 & XP1_GRACEFUL_CLOSE ? TRUE : FALSE );
a_pInst->Setbool( L"SupportsExpeditedData", m_pInfo[ m_nCurrentProtocol ].dwServiceFlags1 & XP1_EXPEDITED_DATA ? TRUE : FALSE );
a_pInst->Setbool( L"SupportsConnectData", m_pInfo[ m_nCurrentProtocol ].dwServiceFlags1 & XP1_CONNECT_DATA ? TRUE : FALSE );
a_pInst->Setbool( L"SupportsDisconnectData", m_pInfo[ m_nCurrentProtocol ].dwServiceFlags1 & XP1_DISCONNECT_DATA ? TRUE : FALSE );
a_pInst->Setbool( L"SupportsBroadcasting", m_pInfo[ m_nCurrentProtocol ].dwServiceFlags1 & XP1_SUPPORT_BROADCAST ? TRUE : FALSE );
a_pInst->Setbool( L"SupportsMulticasting", m_pInfo[ m_nCurrentProtocol ].dwServiceFlags1 & XP1_SUPPORT_MULTIPOINT ? TRUE : FALSE );
a_pInst->Setbool( L"SupportsEncryption", m_pInfo[ m_nCurrentProtocol ].dwServiceFlags1 & XP1_QOS_SUPPORTED ? TRUE : FALSE );
a_pInst->Setbool( IDS_SupportsQualityofService, m_pInfo[ m_nCurrentProtocol ].dwServiceFlags1 & XP1_QOS_SUPPORTED ? TRUE : FALSE );
CHString t_chsStatus ;
#ifdef NTONLY
GetTrafficControlInfo(a_pInst);
#endif
#ifdef NTONLY
//===================================================
// Now if we can extract the service name, then we
// can go out other info out of the registry. Need
// to find a better way to do this.
//===================================================
CHString t_chsService;
_stscanf( m_pInfo[ m_nCurrentProtocol ].szProtocol, _T("%s"), t_chsService.GetBuffer( _MAX_PATH + 2 ) ) ;
t_chsService.ReleaseBuffer() ;
// test for RSVP service
if( t_chsService.CompareNoCase( L"RSVP" ) )
{
// else pull out the service name following MSAFD
t_chsService.Empty() ;
_stscanf( m_pInfo[ m_nCurrentProtocol ].szProtocol, _T("MSAFD %s"), t_chsService.GetBuffer( _MAX_PATH + 2 ) ) ;
t_chsService.ReleaseBuffer() ;
}
if( !t_chsService.IsEmpty() )
{
ExtractNTRegistryInfo( a_pInst, t_chsService.GetBuffer( 0 ) ) ;
}
#endif
}
////////////////////////////////////////////////////////////////////////
#ifdef NTONLY
void CSockets22::ExtractNTRegistryInfo(CInstance *a_pInst, LPWSTR a_szService )
{
CRegistry t_Reg ;
CHString t_chsKey,
t_chsTmp,
t_fName ;
//==========================================================
// set the Caption property
//==========================================================
a_pInst->SetCHString( IDS_Caption, a_szService ) ;
t_chsKey = _T("System\\CurrentControlSet\\Services\\") + CHString( a_szService ) ;
if( ERROR_SUCCESS == t_Reg.Open( HKEY_LOCAL_MACHINE, t_chsKey, KEY_READ ) )
{
//======================================================
// Set Description and InstallDate properties
//======================================================
if( ERROR_SUCCESS == t_Reg.GetCurrentKeyValue( _T("DisplayName"), t_chsTmp ) )
{
a_pInst->SetCHString( IDS_Description, t_chsTmp ) ;
}
if( ERROR_SUCCESS == t_Reg.GetCurrentKeyValue( _T("ImagePath"), t_fName ) )
{
// get a filename out of it - might have SystemRoot in it...
if ( -1 != t_fName.Find( _T("%SystemRoot%\\") ) )
{
t_fName = t_fName.Right( t_fName.GetLength() - 13 ) ;
}
else if ( -1 != t_fName.Find( _T("\\SystemRoot\\") ) )
{
t_fName = t_fName.Right( t_fName.GetLength() - 12 ) ;
}
GetWindowsDirectory( t_chsTmp.GetBuffer( MAX_PATH ), MAX_PATH ) ;
t_chsTmp.ReleaseBuffer() ;
t_fName = t_chsTmp + _T("\\") + t_fName ;
SetDateFromFileName( t_fName, a_pInst ) ;
}
//=========================================================
// Now, go get the status info
//=========================================================
#ifdef NTONLY
if( IsWinNT5() )
{
CHString t_chsStatus ;
if( GetServiceStatus( a_szService, t_chsStatus ) )
{
a_pInst->SetCharSplat(IDS_Status, t_chsStatus ) ;
}
}
else
#endif
{
t_chsKey = _T("System\\CurrentControlSet\\Services\\") + CHString( a_szService ) + _T("\\Enum") ;
if( ERROR_SUCCESS == t_Reg.Open( HKEY_LOCAL_MACHINE, t_chsKey, KEY_READ ) )
{
if( ERROR_SUCCESS == t_Reg.GetCurrentKeyValue( _T("0"), t_chsTmp))
{
t_chsKey = _T("System\\CurrentControlSet\\Enum\\") + t_chsTmp ;
if( ERROR_SUCCESS == t_Reg.Open( HKEY_LOCAL_MACHINE, t_chsKey, KEY_READ ) )
{
DWORD t_dwTmp ;
if( ERROR_SUCCESS == t_Reg.GetCurrentKeyValue( _T("StatusFlags"), t_dwTmp ) )
{
TranslateNTStatus( t_dwTmp, t_chsTmp ) ;
a_pInst->SetCHString( IDS_Status, t_chsTmp ) ;
}
else
{
a_pInst->SetCHString( IDS_Status, IDS_STATUS_Unknown ) ;
}
}
}
}
}
}
}
#endif
//********************************************************************
// SOCKETS 1.1 implementation
//********************************************************************
CSockets11::CSockets11() : m_pwsock32api( NULL ) , m_pInfo(NULL), m_fAlive( FALSE )
{
m_pwsock32api = (CWsock32Api*) CResourceManager::sm_TheResourceManager.GetResource(g_guidWsock32Api, NULL);
// Note a NULL pointer indicates the DLL is not present on the system
if( m_pwsock32api != NULL )
{
WSADATA t_wsaData;
m_fAlive = ( m_pwsock32api->WsWSAStartup( 0x0101, &t_wsaData) == 0 ) ;
}
}
CSockets11::~CSockets11()
{
if( m_pwsock32api )
{
if( m_fAlive )
{
m_pwsock32api->WsWSACleanup() ;
}
CResourceManager::sm_TheResourceManager.ReleaseResource(g_guidWsock32Api, m_pwsock32api);
m_pwsock32api = NULL ;
}
}
void CSockets11::GetStatus( PROTOCOL_INFO *a_ProtoInfo, CHString &a_chsStatus )
{
if( !a_ProtoInfo || !m_pwsock32api)
{
a_chsStatus = IDS_Error ;
return;
}
// Create a socket for this protocol.
SOCKET t_s = m_pwsock32api->Wssocket( a_ProtoInfo->iAddressFamily,
a_ProtoInfo->iSocketType,
a_ProtoInfo->iProtocol
);
if( INVALID_SOCKET != t_s )
{
m_pwsock32api->Wsclosesocket( t_s ) ;
a_chsStatus = IDS_OK ;
}
else
{
switch ( m_pwsock32api->WsWSAGetLastError() )
{
case WSAENETDOWN:
case WSAEINPROGRESS:
case WSAENOBUFS:
case WSAEMFILE:
{
a_chsStatus = IDS_Degraded ;
break;
}
case WSANOTINITIALISED:
case WSAEAFNOSUPPORT:
case WSAEPROTONOSUPPORT:
case WSAEPROTOTYPE:
case WSAESOCKTNOSUPPORT:
case WSAEINVAL:
case WSAEFAULT:
{
a_chsStatus = IDS_Error ;
break;
}
default:
{
a_chsStatus = IDS_Unknown ;
break;
}
}
}
}
BOOL CSockets11::BeginEnumeration()
{
DWORD t_dwByteCount = 0 ;
BOOL t_fRc = FALSE ;
m_pInfo = NULL ;
if ( m_pwsock32api )
{
m_pwsock32api->WsEnumProtocols( NULL, m_pInfo, &t_dwByteCount ) ;
m_pbBuffer = new byte[ t_dwByteCount ] ;
if( !m_pbBuffer )
{
throw CHeap_Exception( CHeap_Exception::E_ALLOCATION_ERROR ) ;
}
m_pInfo = (PROTOCOL_INFO *) m_pbBuffer ;
if( m_pInfo != NULL )
{
m_nTotalProtocols = m_pwsock32api->WsEnumProtocols( NULL, m_pInfo, &t_dwByteCount) ;
if( m_nTotalProtocols != SOCKET_ERROR )
{
t_fRc = TRUE ;
}
}
}
return t_fRc ;
}
//=====================================================================
BOOL CSockets11::GetProtocol( CInstance *a_pInst, CHString a_chsName )
{
BOOL t_fRc = FALSE ;
if( m_nCurrentProtocol < m_nTotalProtocols )
{
//==============================================
// If chsName is not empty, then we are looking
// for a specific protocol, otherwise, we are
// enumerating them.
//==============================================
while( m_nCurrentProtocol < m_nTotalProtocols )
{
if( !a_chsName.IsEmpty() )
{
if( _tcsicmp( m_pInfo[ m_nCurrentProtocol ].lpProtocol, TOBSTRT( a_chsName ) ) == 0 )
{
LoadProtocol( a_pInst ) ;
t_fRc = TRUE ;
}
}
else
{
LoadProtocol( a_pInst ) ;
t_fRc = TRUE ;
}
m_nCurrentProtocol++ ;
if( t_fRc )
{
break ;
}
}
}
return t_fRc ;
}
//====================================================================
void CSockets11::LoadProtocol( CInstance *a_pInst )
{
a_pInst->SetCHString( IDS_Name, m_pInfo[ m_nCurrentProtocol ].lpProtocol);
a_pInst->SetCHString( IDS_Caption, m_pInfo[ m_nCurrentProtocol ].lpProtocol);
a_pInst->SetCHString( IDS_Description, m_pInfo[ m_nCurrentProtocol ].lpProtocol);
a_pInst->SetDWORD( L"MaximumMessageSize", m_pInfo[ m_nCurrentProtocol ].dwMessageSize );
a_pInst->SetDWORD( L"MaximumAddressSize", (DWORD) m_pInfo[ m_nCurrentProtocol ].iMaxSockAddr );
a_pInst->SetDWORD( L"MinimumAddressSize", (DWORD) m_pInfo[ m_nCurrentProtocol ].iMinSockAddr );
a_pInst->Setbool( L"ConnectionlessService", m_pInfo[ m_nCurrentProtocol ].dwServiceFlags & XP_CONNECTIONLESS ? TRUE : FALSE );
a_pInst->Setbool( L"MessageOriented", m_pInfo[ m_nCurrentProtocol ].dwServiceFlags & XP_MESSAGE_ORIENTED ? TRUE : FALSE );
a_pInst->Setbool( L"PseudoStreamOriented", m_pInfo[ m_nCurrentProtocol ].dwServiceFlags & XP_PSEUDO_STREAM ? TRUE : FALSE );
a_pInst->Setbool( L"GuaranteesDelivery", m_pInfo[ m_nCurrentProtocol ].dwServiceFlags & XP_GUARANTEED_DELIVERY ? TRUE : FALSE );
a_pInst->Setbool( L"GuaranteesSequencing", m_pInfo[ m_nCurrentProtocol ].dwServiceFlags & XP_GUARANTEED_ORDER ? TRUE : FALSE );
a_pInst->Setbool( L"SupportsGuaranteedBandwidth", m_pInfo[ m_nCurrentProtocol ].dwServiceFlags & XP_BANDWIDTH_ALLOCATION ? TRUE : FALSE );
a_pInst->Setbool( L"SupportsGracefulClosing", m_pInfo[ m_nCurrentProtocol ].dwServiceFlags & XP_GRACEFUL_CLOSE ? TRUE : FALSE );
a_pInst->Setbool( L"SupportsExpeditedData", m_pInfo[ m_nCurrentProtocol ].dwServiceFlags & XP_EXPEDITED_DATA ? TRUE : FALSE );
a_pInst->Setbool( L"SupportsConnectData", m_pInfo[ m_nCurrentProtocol ].dwServiceFlags & XP_CONNECT_DATA ? TRUE : FALSE );
a_pInst->Setbool( L"SupportsDisconnectData", m_pInfo[ m_nCurrentProtocol ].dwServiceFlags & XP_DISCONNECT_DATA ? TRUE : FALSE );
a_pInst->Setbool( L"SupportsBroadcasting", m_pInfo[ m_nCurrentProtocol ].dwServiceFlags & XP_SUPPORTS_BROADCAST ? TRUE : FALSE );
a_pInst->Setbool( L"SupportsMulticasting", m_pInfo[ m_nCurrentProtocol ].dwServiceFlags & XP_SUPPORTS_MULTICAST ? TRUE : FALSE );
a_pInst->Setbool( L"SupportsFragmentation", m_pInfo[ m_nCurrentProtocol ].dwServiceFlags & XP_FRAGMENTATION ? TRUE : FALSE );
a_pInst->Setbool( L"SupportsEncryption", m_pInfo[ m_nCurrentProtocol ].dwServiceFlags & XP_ENCRYPTS ? TRUE : FALSE );
a_pInst->Setbool( IDS_SupportsQualityofService, false ) ;
// Sockets 1.1 status... open the socket and test
CHString t_chsStatus ;
GetStatus( &m_pInfo[ m_nCurrentProtocol ], t_chsStatus ) ;
a_pInst->SetCHString( IDS_Status, t_chsStatus ) ;
}
void CSockets11::GetWin95RegistryStuff( CInstance *a_pInst, LPTSTR a_szProtocol )
{
CRegistrySearch t_Search;
CHPtrArray t_chsaList;
CHString *t_pPtr,
t_chsValue,
t_chsTmp ;
SYSTEMTIME t_sysTime;
try
{
a_pInst->SetCHString( IDS_Status, IDS_STATUS_Unknown ) ;
//====================================================
// Go thru, find the network transports, then check
// with config manager to see which ones are loaded
//====================================================
t_Search.SearchAndBuildList( L"Enum\\Network", t_chsaList, L"NetTrans", L"Class", VALUE_SEARCH ) ;
for( int t_i = 0; t_i < t_chsaList.GetSize(); t_i++ )
{
CRegistry t_Reg ;
t_pPtr = ( CHString* ) t_chsaList.GetAt( t_i ) ;
//====================================================
// Opened the key, now I need to read the MasterCopy
// key and strip out enum\ and see if that is current
// in Config Manager
//====================================================
if( ERROR_SUCCESS == t_Reg.Open( HKEY_LOCAL_MACHINE, *t_pPtr, KEY_READ ) )
{
if( ERROR_SUCCESS == t_Reg.GetCurrentKeyValue( L"DeviceDesc", t_chsValue ) )
{
if( _tcsicmp( a_szProtocol, TOBSTRT( t_chsValue ) ) != 0 )
{
continue ;
}
}
else
{
break ;
}
if( ERROR_SUCCESS == t_Reg.GetCurrentKeyValue( L"MasterCopy", t_chsValue ) )
{
CConfigMgrDevice t_Cfg ;
//=================================================
// If we find the status, then we know that this
// is the current key, and to read the Driver key
// in the registry to tell us where the driver info
// is at.
//=================================================
if( t_Cfg.GetStatus( t_chsValue ) )
{
a_pInst->SetCHString( IDS_Status, t_chsValue ) ;
if( ERROR_SUCCESS == t_Reg.GetCurrentKeyValue( L"DeviceDesc", t_chsValue ) )
{
a_pInst->SetCHString( IDS_Caption, t_chsValue ) ;
}
if( ERROR_SUCCESS == t_Reg.GetCurrentKeyValue( L"Mfg", t_chsTmp ) )
{
a_pInst->SetCHString( IDS_Description, t_chsTmp + CHString( _T("-")) + t_chsValue ) ;
}
if( ERROR_SUCCESS == t_Reg.GetCurrentKeyValue( L"Driver",t_chsTmp ) )
{
t_chsTmp = L"System\\CurrentControlSet\\Services\\Class\\" + t_chsTmp ;
if( ERROR_SUCCESS == t_Reg.Open( HKEY_LOCAL_MACHINE, t_chsTmp, KEY_READ ) )
{
if( t_Reg.GetCurrentKeyValue( L"DriverDate", t_chsTmp ) == ERROR_SUCCESS )
{
swscanf( t_chsTmp,L"%d-%d-%d",
&t_sysTime.wMonth,
&t_sysTime.wDay,
&t_sysTime.wYear);
t_sysTime.wSecond = 0;
t_sysTime.wMilliseconds = 0;
a_pInst->SetDateTime( IDS_InstallDate, t_sysTime ) ;
}
}
}
break ;
}
}
}
}
}
catch( ... )
{
t_Search.FreeSearchList( CSTRING_PTR, t_chsaList ) ;
throw ;
}
t_Search.FreeSearchList( CSTRING_PTR, t_chsaList ) ;
}
/*******************************************************************
NAME: GetSocketInfo( CInstance * a_pInst, LPWSAPROTOCOL_INFO pInfo, CHString &a_chsStatus )
SYNOPSIS: Get protocol status (9x )and checks for Guaranteed Bandwidth support.
For Guaranteed Bandwidth, Determine if the local traffic control agent
is installed and operational. If so, the agent can establish a negotiated
bandwidth with the socket initiator.
Although mutiple vendors could supply a traffic control agent this
IODevCtl call is not currently IOC_WS2 abstracted. This is a vendor
specific call(MS).
This was discussed with Kam Lee in the NT networking group and suggested
this IOCTL apply to all vendors (he will submit the request and follow up).
Test note: this specific WSAIoctl is confirmed to fail with NT5 builds before 1932.
ENTRY: CInstance * a_pInst :
LPWSAPROTOCOL_INFO pInfo :
HISTORY:
a-peterc 22-Nov-1998 Created
********************************************************************/
void CSockets22::GetSocketInfo( CInstance *a_pInst, LPWSAPROTOCOL_INFO a_pInfo, CHString &a_chsStatus )
{
bool t_bGuaranteed = false ;
if( !a_pInfo )
{
a_chsStatus = IDS_Error ;
return;
}
// Create a socket for this protocol.
SOCKET t_s = m_pws32api->WSASocket( FROM_PROTOCOL_INFO,
FROM_PROTOCOL_INFO,
FROM_PROTOCOL_INFO,
a_pInfo,
0,
NULL );
if( INVALID_SOCKET != t_s )
{
try
{
if( a_pInfo->dwServiceFlags1 & XP1_QOS_SUPPORTED )
{
// The socket must be bound for the query
SOCKADDR t_sAddr;
memset( &t_sAddr, 0, sizeof( t_sAddr ) ) ;
t_sAddr.sa_family = (u_short)a_pInfo->iAddressFamily;
if( SOCKET_ERROR != m_pws32api->Bind( t_s, &t_sAddr, sizeof( t_sAddr ) ) )
{
// query for local traffic control
DWORD t_dwInBuf = 50004 ; // LOCAL_TRAFFIC_CONTROL ( vendor specific, ms )
DWORD t_dwOutBuf ;
DWORD t_dwReturnedBytes = 0;
if( SOCKET_ERROR !=
m_pws32api->WSAIoctl( t_s, // socket
_WSAIORW( IOC_VENDOR, 1 ), /* = SIO_CHK_QOS */ // dwIoControlCode
&t_dwInBuf, // lpvInBuffer
sizeof( t_dwInBuf ), // cbInBuffer
&t_dwOutBuf, // lpvOUTBuffer
sizeof( t_dwOutBuf ), // cbOUTBuffer
&t_dwReturnedBytes, // lpcbBytesReturned
NULL , // lpOverlapped
NULL ) ) // lpCompletionROUTINE
{
if( sizeof( t_dwOutBuf ) == t_dwReturnedBytes )
{
t_bGuaranteed = t_dwOutBuf ? true : false ;
}
}
}
}
m_pws32api->CloseSocket( t_s ) ;
a_chsStatus = IDS_OK ;
}
catch(...)
{
m_pws32api->CloseSocket( t_s ) ;
throw;
}
}
else
{
switch ( m_pws32api->WSAGetLastError() )
{
case WSAENETDOWN:
case WSAEINPROGRESS:
case WSAENOBUFS:
case WSAEMFILE:
{
a_chsStatus = IDS_Degraded ;
break;
}
case WSANOTINITIALISED:
case WSAEAFNOSUPPORT:
case WSAEPROTONOSUPPORT:
case WSAEPROTOTYPE:
case WSAESOCKTNOSUPPORT:
case WSAEINVAL:
case WSAEFAULT:
{
a_chsStatus = IDS_Error ;
break;
}
default:
{
a_chsStatus = IDS_Unknown ;
break;
}
}
}
a_pInst->Setbool( L"SupportsGuaranteedBandwidth", t_bGuaranteed ) ;
}
//==============================================================================
//
// Callback function prototypes
//
// NotifyHandler
// AddFlowCompleteHandler
// ModifyFlowCompleteHandler
// DeleteFlowCompleteHandler
//
// NOTE: These callback functions are all stub. They don't need to take
// any action acccording to current functionality
//
//==============================================================================
VOID CALLBACK
NotifyHandler(
HANDLE ClRegCtx,
HANDLE ClIfcCtx,
ULONG Event,
HANDLE SubCode,
ULONG BufSize,
PVOID Buffer)
{
// Perform callback action
}
VOID CALLBACK
AddFlowCompleteHandler(
HANDLE ClFlowCtx,
ULONG Status)
{
// Perform callback action
}
VOID CALLBACK
ModifyFlowCompleteHandler(
HANDLE ClFlowCtx,
ULONG Status)
{
// Perform callback action
}
VOID CALLBACK
DeleteFlowCompleteHandler(
HANDLE ClFlowCtx,
ULONG Status)
{
// Perform callback action
}
//==============================================================================
//
// Define the list of callback functions that can be activated by
// Traffic Control Interface.
//
//==============================================================================
TCI_CLIENT_FUNC_LIST g_tciClientFuncList =
{
NotifyHandler,
AddFlowCompleteHandler,
ModifyFlowCompleteHandler,
DeleteFlowCompleteHandler
};
DWORD CSockets22::GetTrafficControlInfo(CInstance *a_pInst)
{
DWORD dwRet = NO_ERROR;
HANDLE hClient = INVALID_HANDLE_VALUE;
HANDLE hClientContext = INVALID_HANDLE_VALUE; /* DEFAULT_CLNT_CONT */;
ULONG ulEnumBufSize = 0;
BYTE buff[1]; // We only need a dummy buffer
// Use of delay loaded function requires exception handler.
SetStructuredExceptionHandler seh;
try
{
//register the TC Client
dwRet = TcRegisterClient(
CURRENT_TCI_VERSION,
hClientContext,
&g_tciClientFuncList,
&hClient);
// was the client registration successful?
if (dwRet == NO_ERROR)
{
//enumerate the interfaces available
dwRet = TcEnumerateInterfaces(
hClient,
&ulEnumBufSize,
(TC_IFC_DESCRIPTOR*) buff);
// We expect ERROR_INSUFFICIENT_BUFFER
if (dwRet == ERROR_INSUFFICIENT_BUFFER)
{
// Don't bother to enumerate the interfaces -
// we now know PSched is installed.
a_pInst->Setbool( L"SupportsGuaranteedBandwidth", TRUE ) ;
dwRet = ERROR_SUCCESS;
}
else
{
a_pInst->Setbool( L"SupportsGuaranteedBandwidth", FALSE ) ;
dwRet = ERROR_SUCCESS;
}
}
// De-register the TC client
TcDeregisterClient(hClient);
hClient = INVALID_HANDLE_VALUE;
}
catch(Structured_Exception se)
{
DelayLoadDllExceptionFilter(se.GetExtendedInfo());
if(hClient != INVALID_HANDLE_VALUE)
{
TcDeregisterClient(hClient);
hClient = INVALID_HANDLE_VALUE;
}
dwRet = ERROR_DLL_NOT_FOUND;
}
catch(...)
{
if(hClient != INVALID_HANDLE_VALUE)
{
TcDeregisterClient(hClient);
hClient = INVALID_HANDLE_VALUE;
}
throw;
}
return dwRet;
}
| 28.111864 | 142 | 0.557157 | npocmaka |
2e276f26c03d408e1680e5d90f56447f611f65c5 | 4,316 | hpp | C++ | libs/boost_1_72_0/boost/smart_ptr/enable_shared_from_raw.hpp | henrywarhurst/matrix | 317a2a7c35c1c7e3730986668ad2270dc19809ef | [
"BSD-3-Clause"
] | null | null | null | libs/boost_1_72_0/boost/smart_ptr/enable_shared_from_raw.hpp | henrywarhurst/matrix | 317a2a7c35c1c7e3730986668ad2270dc19809ef | [
"BSD-3-Clause"
] | null | null | null | libs/boost_1_72_0/boost/smart_ptr/enable_shared_from_raw.hpp | henrywarhurst/matrix | 317a2a7c35c1c7e3730986668ad2270dc19809ef | [
"BSD-3-Clause"
] | null | null | null | #ifndef BOOST_ENABLE_SHARED_FROM_RAW_HPP_INCLUDED
#define BOOST_ENABLE_SHARED_FROM_RAW_HPP_INCLUDED
//
// enable_shared_from_raw.hpp
//
// Copyright 2002, 2009, 2014 Peter Dimov
// Copyright 2008-2009 Frank Mori Hess
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
#include <boost/assert.hpp>
#include <boost/config.hpp>
#include <boost/detail/workaround.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>
namespace boost {
template <typename T> boost::shared_ptr<T> shared_from_raw(T *);
template <typename T> boost::weak_ptr<T> weak_from_raw(T *);
namespace detail {
template <class X, class Y>
inline void sp_enable_shared_from_this(boost::shared_ptr<X> *ppx, Y const *py,
boost::enable_shared_from_raw const *pe);
} // namespace detail
class enable_shared_from_raw {
protected:
enable_shared_from_raw() {}
enable_shared_from_raw(enable_shared_from_raw const &) {}
enable_shared_from_raw &operator=(enable_shared_from_raw const &) {
return *this;
}
~enable_shared_from_raw() {
BOOST_ASSERT(shared_this_.use_count() <=
1); // make sure no dangling shared_ptr objects exist
}
private:
void init_if_expired() const {
if (weak_this_.expired()) {
shared_this_.reset(static_cast<void *>(0),
detail::esft2_deleter_wrapper());
weak_this_ = shared_this_;
}
}
void init_if_empty() const {
if (weak_this_._empty()) {
shared_this_.reset(static_cast<void *>(0),
detail::esft2_deleter_wrapper());
weak_this_ = shared_this_;
}
}
#ifdef BOOST_NO_MEMBER_TEMPLATE_FRIENDS
public:
#else
private:
template <class Y> friend class shared_ptr;
template <typename T> friend boost::shared_ptr<T> shared_from_raw(T *);
template <typename T> friend boost::weak_ptr<T> weak_from_raw(T *);
template <class X, class Y>
friend inline void
detail::sp_enable_shared_from_this(boost::shared_ptr<X> *ppx, Y const *py,
boost::enable_shared_from_raw const *pe);
#endif
shared_ptr<void const volatile> shared_from_this() const {
init_if_expired();
return shared_ptr<void const volatile>(weak_this_);
}
shared_ptr<void const volatile> shared_from_this() const volatile {
return const_cast<enable_shared_from_raw const *>(this)->shared_from_this();
}
weak_ptr<void const volatile> weak_from_this() const {
init_if_empty();
return weak_this_;
}
weak_ptr<void const volatile> weak_from_this() const volatile {
return const_cast<enable_shared_from_raw const *>(this)->weak_from_this();
}
// Note: invoked automatically by shared_ptr; do not call
template <class X, class Y>
void _internal_accept_owner(shared_ptr<X> *ppx, Y *) const {
BOOST_ASSERT(ppx != 0);
if (weak_this_.expired()) {
weak_this_ = *ppx;
} else if (shared_this_.use_count() != 0) {
BOOST_ASSERT(ppx->unique()); // no weak_ptrs should exist either, but
// there's no way to check that
detail::esft2_deleter_wrapper *pd =
boost::get_deleter<detail::esft2_deleter_wrapper>(shared_this_);
BOOST_ASSERT(pd != 0);
pd->set_deleter(*ppx);
ppx->reset(shared_this_, ppx->get());
shared_this_.reset();
}
}
mutable weak_ptr<void const volatile> weak_this_;
private:
mutable shared_ptr<void const volatile> shared_this_;
};
template <typename T> boost::shared_ptr<T> shared_from_raw(T *p) {
BOOST_ASSERT(p != 0);
return boost::shared_ptr<T>(p->enable_shared_from_raw::shared_from_this(), p);
}
template <typename T> boost::weak_ptr<T> weak_from_raw(T *p) {
BOOST_ASSERT(p != 0);
boost::weak_ptr<T> result(p->enable_shared_from_raw::weak_from_this(), p);
return result;
}
namespace detail {
template <class X, class Y>
inline void
sp_enable_shared_from_this(boost::shared_ptr<X> *ppx, Y const *py,
boost::enable_shared_from_raw const *pe) {
if (pe != 0) {
pe->_internal_accept_owner(ppx, const_cast<Y *>(py));
}
}
} // namespace detail
} // namespace boost
#endif // #ifndef BOOST_ENABLE_SHARED_FROM_RAW_HPP_INCLUDED
| 29.162162 | 80 | 0.68721 | henrywarhurst |
2e27c7e1fa5039b8ddf11c8851ecacd4a386d5df | 508 | cpp | C++ | CppProject5_3D/CppProject5/src/entities/projectiles/Projectile.cpp | Damoy/Tower3D | a6f1ec9fd5e7c26ade5528828cc576f5ed45394a | [
"MIT"
] | 1 | 2019-08-25T03:04:35.000Z | 2019-08-25T03:04:35.000Z | CppProject5_3D/CppProject5/src/entities/projectiles/Projectile.cpp | Damoy/Tower3D | a6f1ec9fd5e7c26ade5528828cc576f5ed45394a | [
"MIT"
] | null | null | null | CppProject5_3D/CppProject5/src/entities/projectiles/Projectile.cpp | Damoy/Tower3D | a6f1ec9fd5e7c26ade5528828cc576f5ed45394a | [
"MIT"
] | null | null | null | #include "Projectile.h"
Projectile::Projectile(Level* lvl, TexturedModel* model, unsigned short life, unsigned short uniqueDamage, unsigned short armor, float x, float y, float z, float xScale, float yScale, float zScale, float s)
: Entity(model, x, y, z, xScale, yScale, zScale),
Destructible(life, armor),
Attacker(uniqueDamage),
level(lvl), speed(s){
}
Projectile::~Projectile(){
}
// Entity and Destructible updates
void Projectile::update() {
Entity::update();
Destructible::update();
}
| 23.090909 | 206 | 0.720472 | Damoy |
2e2c633559616dc04e63ed1a91844008a24a9354 | 32,857 | cpp | C++ | SU2-Quantum/SU2_CFD/src/output/CFlowIncOutput.cpp | Agony5757/SU2-Quantum | 16e7708371a597511e1242f3a7581e8c4187f5b2 | [
"Apache-2.0"
] | null | null | null | SU2-Quantum/SU2_CFD/src/output/CFlowIncOutput.cpp | Agony5757/SU2-Quantum | 16e7708371a597511e1242f3a7581e8c4187f5b2 | [
"Apache-2.0"
] | null | null | null | SU2-Quantum/SU2_CFD/src/output/CFlowIncOutput.cpp | Agony5757/SU2-Quantum | 16e7708371a597511e1242f3a7581e8c4187f5b2 | [
"Apache-2.0"
] | 1 | 2021-12-03T06:40:08.000Z | 2021-12-03T06:40:08.000Z | /*!
* \file output_flow_inc.cpp
* \brief Main subroutines for incompressible flow output
* \author R. Sanchez
* \version 7.0.6 "Blackbird"
*
* SU2 Project Website: https://su2code.github.io
*
* The SU2 Project is maintained by the SU2 Foundation
* (http://su2foundation.org)
*
* Copyright 2012-2020, SU2 Contributors (cf. AUTHORS.md)
*
* SU2 is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* SU2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with SU2. If not, see <http://www.gnu.org/licenses/>.
*/
#include "../../include/output/CFlowIncOutput.hpp"
#include "../../../Common/include/geometry/CGeometry.hpp"
#include "../../include/solvers/CSolver.hpp"
CFlowIncOutput::CFlowIncOutput(CConfig *config, unsigned short nDim) : CFlowOutput(config, nDim, false) {
turb_model = config->GetKind_Turb_Model();
heat = config->GetEnergy_Equation();
weakly_coupled_heat = config->GetWeakly_Coupled_Heat();
/*--- Set the default history fields if nothing is set in the config file ---*/
if (nRequestedHistoryFields == 0){
requestedHistoryFields.emplace_back("ITER");
requestedHistoryFields.emplace_back("RMS_RES");
nRequestedHistoryFields = requestedHistoryFields.size();
}
if (nRequestedScreenFields == 0){
if (multiZone) requestedScreenFields.emplace_back("OUTER_ITER");
requestedScreenFields.emplace_back("INNER_ITER");
requestedScreenFields.emplace_back("RMS_PRESSURE");
requestedScreenFields.emplace_back("RMS_VELOCITY-X");
requestedScreenFields.emplace_back("RMS_VELOCITY-Y");
nRequestedScreenFields = requestedScreenFields.size();
}
if (nRequestedVolumeFields == 0){
requestedVolumeFields.emplace_back("COORDINATES");
requestedVolumeFields.emplace_back("SOLUTION");
requestedVolumeFields.emplace_back("PRIMITIVE");
if (config->GetGrid_Movement()) requestedVolumeFields.emplace_back("GRID_VELOCITY");
nRequestedVolumeFields = requestedVolumeFields.size();
}
stringstream ss;
ss << "Zone " << config->GetiZone() << " (Incomp. Fluid)";
multiZoneHeaderString = ss.str();
/*--- Set the volume filename --- */
volumeFilename = config->GetVolume_FileName();
/*--- Set the surface filename --- */
surfaceFilename = config->GetSurfCoeff_FileName();
/*--- Set the restart filename --- */
restartFilename = config->GetRestart_FileName();
/*--- Set the default convergence field --- */
if (convFields.empty() ) convFields.emplace_back("RMS_PRESSURE");
}
CFlowIncOutput::~CFlowIncOutput(void) {}
void CFlowIncOutput::SetHistoryOutputFields(CConfig *config){
/// BEGIN_GROUP: RMS_RES, DESCRIPTION: The root-mean-square residuals of the SOLUTION variables.
/// DESCRIPTION: Root-mean square residual of the pressure.
AddHistoryOutput("RMS_PRESSURE", "rms[P]", ScreenOutputFormat::FIXED, "RMS_RES", "Root-mean square residual of the pressure.", HistoryFieldType::RESIDUAL);
/// DESCRIPTION: Root-mean square residual of the velocity x-component.
AddHistoryOutput("RMS_VELOCITY-X", "rms[U]", ScreenOutputFormat::FIXED, "RMS_RES", "Root-mean square residual of the velocity x-component.", HistoryFieldType::RESIDUAL);
/// DESCRIPTION: Root-mean square residual of the velocity y-component.
AddHistoryOutput("RMS_VELOCITY-Y", "rms[V]", ScreenOutputFormat::FIXED, "RMS_RES", "Root-mean square residual of the velocity y-component.", HistoryFieldType::RESIDUAL);
/// DESCRIPTION: Root-mean square residual of the velocity z-component.
if (nDim == 3) AddHistoryOutput("RMS_VELOCITY-Z", "rms[W]", ScreenOutputFormat::FIXED, "RMS_RES", "Root-mean square residual of the velocity z-component.", HistoryFieldType::RESIDUAL);
/// DESCRIPTION: Maximum residual of the temperature.
if (heat || weakly_coupled_heat) AddHistoryOutput("RMS_TEMPERATURE", "rms[T]", ScreenOutputFormat::FIXED, "RMS_RES", "Root-mean square residual of the temperature.", HistoryFieldType::RESIDUAL);
/// DESCRIPTION: Root-mean square residual of the radiative energy (P1 model).
if (config->AddRadiation()) AddHistoryOutput("RMS_RAD_ENERGY", "rms[E_Rad]", ScreenOutputFormat::FIXED, "RMS_RES", "Root-mean square residual of the radiative energy.", HistoryFieldType::RESIDUAL);
switch(turb_model){
case SA: case SA_NEG: case SA_E: case SA_COMP: case SA_E_COMP:
/// DESCRIPTION: Root-mean square residual of nu tilde (SA model).
AddHistoryOutput("RMS_NU_TILDE", "rms[nu]", ScreenOutputFormat::FIXED, "RMS_RES", "Root-mean square residual of nu tilde (SA model).", HistoryFieldType::RESIDUAL);
break;
case SST: case SST_SUST:
/// DESCRIPTION: Root-mean square residual of kinetic energy (SST model).
AddHistoryOutput("RMS_TKE", "rms[k]", ScreenOutputFormat::FIXED, "RMS_RES", "Root-mean square residual of kinetic energy (SST model).", HistoryFieldType::RESIDUAL);
/// DESCRIPTION: Root-mean square residual of the dissipation (SST model).
AddHistoryOutput("RMS_DISSIPATION", "rms[w]", ScreenOutputFormat::FIXED, "RMS_RES", "Root-mean square residual of dissipation (SST model).", HistoryFieldType::RESIDUAL);
break;
default: break;
}
/// END_GROUP
/// BEGIN_GROUP: MAX_RES, DESCRIPTION: The maximum residuals of the SOLUTION variables.
/// DESCRIPTION: Maximum residual of the pressure.
AddHistoryOutput("MAX_PRESSURE", "max[P]", ScreenOutputFormat::FIXED, "MAX_RES", "Maximum residual of the pressure.", HistoryFieldType::RESIDUAL);
/// DESCRIPTION: Maximum residual of the velocity x-component.
AddHistoryOutput("MAX_VELOCITY-X", "max[U]", ScreenOutputFormat::FIXED, "MAX_RES", "Maximum residual of the velocity x-component.", HistoryFieldType::RESIDUAL);
/// DESCRIPTION: Maximum residual of the velocity y-component.
AddHistoryOutput("MAX_VELOCITY-Y", "max[V]", ScreenOutputFormat::FIXED, "MAX_RES", "Maximum residual of the velocity y-component.", HistoryFieldType::RESIDUAL);
/// DESCRIPTION: Maximum residual of the velocity z-component.
if (nDim == 3)
AddHistoryOutput("MAX_VELOCITY-Z", "max[W]", ScreenOutputFormat::FIXED, "MAX_RES", "Maximum residual of the velocity z-component.", HistoryFieldType::RESIDUAL);
/// DESCRIPTION: Maximum residual of the temperature.
if (heat || weakly_coupled_heat)
AddHistoryOutput("MAX_TEMPERATURE", "max[T]", ScreenOutputFormat::FIXED, "MAX_RES", "Root-mean square residual of the temperature.", HistoryFieldType::RESIDUAL);
switch(turb_model){
case SA: case SA_NEG: case SA_E: case SA_COMP: case SA_E_COMP:
/// DESCRIPTION: Maximum residual of nu tilde (SA model).
AddHistoryOutput("MAX_NU_TILDE", "max[nu]", ScreenOutputFormat::FIXED, "MAX_RES", "Maximum residual of nu tilde (SA model).", HistoryFieldType::RESIDUAL);
break;
case SST: case SST_SUST:
/// DESCRIPTION: Maximum residual of kinetic energy (SST model).
AddHistoryOutput("MAX_TKE", "max[k]", ScreenOutputFormat::FIXED, "MAX_RES", "Maximum residual of kinetic energy (SST model).", HistoryFieldType::RESIDUAL);
/// DESCRIPTION: Maximum residual of the dissipation (SST model).
AddHistoryOutput("MAX_DISSIPATION", "max[w]", ScreenOutputFormat::FIXED, "MAX_RES", "Maximum residual of dissipation (SST model).", HistoryFieldType::RESIDUAL);
break;
default: break;
}
/// END_GROUP
/// BEGIN_GROUP: BGS_RES, DESCRIPTION: The block-gauss seidel residuals of the SOLUTION variables.
/// DESCRIPTION: Maximum residual of the pressure.
AddHistoryOutput("BGS_PRESSURE", "bgs[P]", ScreenOutputFormat::FIXED, "BGS_RES", "BGS residual of the pressure.", HistoryFieldType::RESIDUAL);
/// DESCRIPTION: Maximum residual of the velocity x-component.
AddHistoryOutput("BGS_VELOCITY-X", "bgs[U]", ScreenOutputFormat::FIXED, "BGS_RES", "BGS residual of the velocity x-component.", HistoryFieldType::RESIDUAL);
/// DESCRIPTION: Maximum residual of the velocity y-component.
AddHistoryOutput("BGS_VELOCITY-Y", "bgs[V]", ScreenOutputFormat::FIXED, "BGS_RES", "BGS residual of the velocity y-component.", HistoryFieldType::RESIDUAL);
/// DESCRIPTION: Maximum residual of the velocity z-component.
if (nDim == 3)
AddHistoryOutput("BGS_VELOCITY-Z", "bgs[W]", ScreenOutputFormat::FIXED, "BGS_RES", "BGS residual of the velocity z-component.", HistoryFieldType::RESIDUAL);
/// DESCRIPTION: Maximum residual of the temperature.
if (heat || weakly_coupled_heat)
AddHistoryOutput("BGS_TEMPERATURE", "bgs[T]", ScreenOutputFormat::FIXED, "BGS_RES", "BGS residual of the temperature.", HistoryFieldType::RESIDUAL);
/// DESCRIPTION: Multizone residual of the radiative energy (P1 model).
if (config->AddRadiation()) AddHistoryOutput("BGS_RAD_ENERGY", "bgs[E_Rad]", ScreenOutputFormat::FIXED, "BGS_RES", "BGS residual of the radiative energy.", HistoryFieldType::RESIDUAL);
switch(turb_model){
case SA: case SA_NEG: case SA_E: case SA_COMP: case SA_E_COMP:
/// DESCRIPTION: Maximum residual of nu tilde (SA model).
AddHistoryOutput("BGS_NU_TILDE", "bgs[nu]", ScreenOutputFormat::FIXED, "BGS_RES", "BGS residual of nu tilde (SA model).", HistoryFieldType::RESIDUAL);
break;
case SST: case SST_SUST:
/// DESCRIPTION: Maximum residual of kinetic energy (SST model).
AddHistoryOutput("BGS_TKE", "bgs[k]", ScreenOutputFormat::FIXED, "BGS_RES", "BGS residual of kinetic energy (SST model).", HistoryFieldType::RESIDUAL);
/// DESCRIPTION: Maximum residual of the dissipation (SST model).
AddHistoryOutput("BGS_DISSIPATION", "bgs[w]", ScreenOutputFormat::FIXED, "BGS_RES", "BGS residual of dissipation (SST model).", HistoryFieldType::RESIDUAL);
break;
default: break;
}
/// END_GROUP
/// BEGIN_GROUP: ROTATING_FRAME, DESCRIPTION: Coefficients related to a rotating frame of reference.
/// DESCRIPTION: Merit
AddHistoryOutput("MERIT", "CMerit", ScreenOutputFormat::SCIENTIFIC, "ROTATING_FRAME", "Merit", HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: CT
AddHistoryOutput("CT", "CT", ScreenOutputFormat::SCIENTIFIC, "ROTATING_FRAME", "CT", HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: CQ
AddHistoryOutput("CQ", "CQ", ScreenOutputFormat::SCIENTIFIC, "ROTATING_FRAME", "CQ", HistoryFieldType::COEFFICIENT);
/// END_GROUP
/// BEGIN_GROUP: HEAT_COEFF, DESCRIPTION: Heat coefficients on all surfaces set with MARKER_MONITORING.
/// DESCRIPTION: Total heatflux
AddHistoryOutput("TOTAL_HEATFLUX", "HF", ScreenOutputFormat::SCIENTIFIC, "HEAT", "Total heatflux on all surfaces set with MARKER_MONITORING.", HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Maximal heatflux
AddHistoryOutput("HEATFLUX_MAX", "maxHF", ScreenOutputFormat::SCIENTIFIC, "HEAT", "Total maximum heatflux on all surfaces set with MARKER_MONITORING.", HistoryFieldType::COEFFICIENT);
/// DESCRIPTION: Temperature
AddHistoryOutput("TEMPERATURE", "Temp", ScreenOutputFormat::SCIENTIFIC, "HEAT", "Total avg. temperature on all surfaces set with MARKER_MONITORING.", HistoryFieldType::COEFFICIENT);
/// END_GROUP
/// DESCRIPTION: Angle of attack
AddHistoryOutput("AOA", "AoA", ScreenOutputFormat::SCIENTIFIC,"AOA", "Angle of attack");
/// DESCRIPTION: Linear solver iterations
AddHistoryOutput("LINSOL_ITER", "LinSolIter", ScreenOutputFormat::INTEGER, "LINSOL", "Number of iterations of the linear solver.");
AddHistoryOutput("LINSOL_RESIDUAL", "LinSolRes", ScreenOutputFormat::FIXED, "LINSOL", "Residual of the linear solver.");
AddHistoryOutput("MIN_DELTA_TIME", "Min DT", ScreenOutputFormat::SCIENTIFIC, "CFL_NUMBER", "Current minimum local time step");
AddHistoryOutput("MAX_DELTA_TIME", "Max DT", ScreenOutputFormat::SCIENTIFIC, "CFL_NUMBER", "Current maximum local time step");
AddHistoryOutput("MIN_CFL", "Min CFL", ScreenOutputFormat::SCIENTIFIC, "CFL_NUMBER", "Current minimum of the local CFL numbers");
AddHistoryOutput("MAX_CFL", "Max CFL", ScreenOutputFormat::SCIENTIFIC, "CFL_NUMBER", "Current maximum of the local CFL numbers");
AddHistoryOutput("AVG_CFL", "Avg CFL", ScreenOutputFormat::SCIENTIFIC, "CFL_NUMBER", "Current average of the local CFL numbers");
if (config->GetDeform_Mesh()){
AddHistoryOutput("DEFORM_MIN_VOLUME", "MinVolume", ScreenOutputFormat::SCIENTIFIC, "DEFORM", "Minimum volume in the mesh");
AddHistoryOutput("DEFORM_MAX_VOLUME", "MaxVolume", ScreenOutputFormat::SCIENTIFIC, "DEFORM", "Maximum volume in the mesh");
AddHistoryOutput("DEFORM_ITER", "DeformIter", ScreenOutputFormat::INTEGER, "DEFORM", "Linear solver iterations for the mesh deformation");
AddHistoryOutput("DEFORM_RESIDUAL", "DeformRes", ScreenOutputFormat::FIXED, "DEFORM", "Residual of the linear solver for the mesh deformation");
}
/*--- Add analyze surface history fields --- */
AddAnalyzeSurfaceOutput(config);
/*--- Add aerodynamic coefficients fields --- */
AddAerodynamicCoefficients(config);
}
void CFlowIncOutput::LoadHistoryData(CConfig *config, CGeometry *geometry, CSolver **solver) {
CSolver* flow_solver = solver[FLOW_SOL];
CSolver* turb_solver = solver[TURB_SOL];
CSolver* heat_solver = solver[HEAT_SOL];
CSolver* rad_solver = solver[RAD_SOL];
CSolver* mesh_solver = solver[MESH_SOL];
SetHistoryOutputValue("RMS_PRESSURE", log10(flow_solver->GetRes_RMS(0)));
SetHistoryOutputValue("RMS_VELOCITY-X", log10(flow_solver->GetRes_RMS(1)));
SetHistoryOutputValue("RMS_VELOCITY-Y", log10(flow_solver->GetRes_RMS(2)));
if (nDim == 3) SetHistoryOutputValue("RMS_VELOCITY-Z", log10(flow_solver->GetRes_RMS(3)));
switch(turb_model){
case SA: case SA_NEG: case SA_E: case SA_COMP: case SA_E_COMP:
SetHistoryOutputValue("RMS_NU_TILDE", log10(turb_solver->GetRes_RMS(0)));
break;
case SST: case SST_SUST:
SetHistoryOutputValue("RMS_TKE", log10(turb_solver->GetRes_RMS(0)));
SetHistoryOutputValue("RMS_DISSIPATION", log10(turb_solver->GetRes_RMS(1)));
break;
}
if (config->AddRadiation())
SetHistoryOutputValue("RMS_RAD_ENERGY", log10(rad_solver->GetRes_RMS(0)));
SetHistoryOutputValue("MAX_PRESSURE", log10(flow_solver->GetRes_Max(0)));
SetHistoryOutputValue("MAX_VELOCITY-X", log10(flow_solver->GetRes_Max(1)));
SetHistoryOutputValue("MAX_VELOCITY-Y", log10(flow_solver->GetRes_Max(2)));
if (nDim == 3) SetHistoryOutputValue("RMS_VELOCITY-Z", log10(flow_solver->GetRes_Max(3)));
switch(turb_model){
case SA: case SA_NEG: case SA_E: case SA_COMP: case SA_E_COMP:
SetHistoryOutputValue("MAX_NU_TILDE", log10(turb_solver->GetRes_Max(0)));
break;
case SST: case SST_SUST:
SetHistoryOutputValue("MAX_TKE", log10(turb_solver->GetRes_Max(0)));
SetHistoryOutputValue("MAX_DISSIPATION", log10(turb_solver->GetRes_Max(1)));
break;
}
if (multiZone){
SetHistoryOutputValue("BGS_PRESSURE", log10(flow_solver->GetRes_BGS(0)));
SetHistoryOutputValue("BGS_VELOCITY-X", log10(flow_solver->GetRes_BGS(1)));
SetHistoryOutputValue("BGS_VELOCITY-Y", log10(flow_solver->GetRes_BGS(2)));
if (nDim == 3) SetHistoryOutputValue("BGS_VELOCITY-Z", log10(flow_solver->GetRes_BGS(3)));
switch(turb_model){
case SA: case SA_NEG: case SA_E: case SA_COMP: case SA_E_COMP:
SetHistoryOutputValue("BGS_NU_TILDE", log10(turb_solver->GetRes_BGS(0)));
break;
case SST:
SetHistoryOutputValue("BGS_TKE", log10(turb_solver->GetRes_BGS(0)));
SetHistoryOutputValue("BGS_DISSIPATION", log10(turb_solver->GetRes_BGS(1)));
break;
}
if (config->AddRadiation())
SetHistoryOutputValue("BGS_RAD_ENERGY", log10(rad_solver->GetRes_BGS(0)));
}
if (weakly_coupled_heat){
SetHistoryOutputValue("TOTAL_HEATFLUX", heat_solver->GetTotal_HeatFlux());
SetHistoryOutputValue("HEATFLUX_MAX", heat_solver->GetTotal_MaxHeatFlux());
SetHistoryOutputValue("TEMPERATURE", heat_solver->GetTotal_AvgTemperature());
SetHistoryOutputValue("RMS_TEMPERATURE", log10(heat_solver->GetRes_RMS(0)));
SetHistoryOutputValue("MAX_TEMPERATURE", log10(heat_solver->GetRes_Max(0)));
if (multiZone) SetHistoryOutputValue("BGS_TEMPERATURE", log10(heat_solver->GetRes_BGS(0)));
}
if (heat){
SetHistoryOutputValue("TOTAL_HEATFLUX", flow_solver->GetTotal_HeatFlux());
SetHistoryOutputValue("HEATFLUX_MAX", flow_solver->GetTotal_MaxHeatFlux());
SetHistoryOutputValue("TEMPERATURE", flow_solver->GetTotal_AvgTemperature());
if (nDim == 3) SetHistoryOutputValue("RMS_TEMPERATURE", log10(flow_solver->GetRes_RMS(4)));
else SetHistoryOutputValue("RMS_TEMPERATURE", log10(flow_solver->GetRes_RMS(3)));
if (nDim == 3) SetHistoryOutputValue("MAX_TEMPERATURE", log10(flow_solver->GetRes_Max(4)));
else SetHistoryOutputValue("MAX_TEMPERATURE", log10(flow_solver->GetRes_Max(3)));
if (multiZone){
if (nDim == 3) SetHistoryOutputValue("BGS_TEMPERATURE", log10(flow_solver->GetRes_BGS(4)));
else SetHistoryOutputValue("BGS_TEMPERATURE", log10(flow_solver->GetRes_BGS(3)));
}
}
SetHistoryOutputValue("LINSOL_ITER", flow_solver->GetIterLinSolver());
SetHistoryOutputValue("LINSOL_RESIDUAL", log10(flow_solver->GetResLinSolver()));
if (config->GetDeform_Mesh()){
SetHistoryOutputValue("DEFORM_MIN_VOLUME", mesh_solver->GetMinimum_Volume());
SetHistoryOutputValue("DEFORM_MAX_VOLUME", mesh_solver->GetMaximum_Volume());
SetHistoryOutputValue("DEFORM_ITER", mesh_solver->GetIterLinSolver());
SetHistoryOutputValue("DEFORM_RESIDUAL", log10(mesh_solver->GetResLinSolver()));
}
SetHistoryOutputValue("MIN_DELTA_TIME", flow_solver->GetMin_Delta_Time());
SetHistoryOutputValue("MAX_DELTA_TIME", flow_solver->GetMax_Delta_Time());
SetHistoryOutputValue("MIN_CFL", flow_solver->GetMin_CFL_Local());
SetHistoryOutputValue("MAX_CFL", flow_solver->GetMax_CFL_Local());
SetHistoryOutputValue("AVG_CFL", flow_solver->GetAvg_CFL_Local());
/*--- Set the analyse surface history values --- */
SetAnalyzeSurface(flow_solver, geometry, config, false);
/*--- Set aeroydnamic coefficients --- */
SetAerodynamicCoefficients(config, flow_solver);
/*--- Set rotating frame coefficients --- */
SetRotatingFrameCoefficients(config, flow_solver);
}
void CFlowIncOutput::SetVolumeOutputFields(CConfig *config){
// Grid coordinates
AddVolumeOutput("COORD-X", "x", "COORDINATES", "x-component of the coordinate vector");
AddVolumeOutput("COORD-Y", "y", "COORDINATES", "y-component of the coordinate vector");
if (nDim == 3)
AddVolumeOutput("COORD-Z", "z", "COORDINATES", "z-component of the coordinate vector");
// SOLUTION variables
AddVolumeOutput("PRESSURE", "Pressure", "SOLUTION", "Pressure");
AddVolumeOutput("VELOCITY-X", "Velocity_x", "SOLUTION", "x-component of the velocity vector");
AddVolumeOutput("VELOCITY-Y", "Velocity_y", "SOLUTION", "y-component of the velocity vector");
if (nDim == 3)
AddVolumeOutput("VELOCITY-Z", "Velocity_z", "SOLUTION", "z-component of the velocity vector");
if (heat || weakly_coupled_heat)
AddVolumeOutput("TEMPERATURE", "Temperature","SOLUTION", "Temperature");
switch(config->GetKind_Turb_Model()){
case SST: case SST_SUST:
AddVolumeOutput("TKE", "Turb_Kin_Energy", "SOLUTION", "Turbulent kinetic energy");
AddVolumeOutput("DISSIPATION", "Omega", "SOLUTION", "Rate of dissipation");
break;
case SA: case SA_COMP: case SA_E:
case SA_E_COMP: case SA_NEG:
AddVolumeOutput("NU_TILDE", "Nu_Tilde", "SOLUTION", "Spalart–Allmaras variable");
break;
case NONE:
break;
}
// Radiation variables
if (config->AddRadiation())
AddVolumeOutput("P1-RAD", "Radiative_Energy(P1)", "SOLUTION", "Radiative Energy");
// Grid velocity
if (config->GetGrid_Movement()){
AddVolumeOutput("GRID_VELOCITY-X", "Grid_Velocity_x", "GRID_VELOCITY", "x-component of the grid velocity vector");
AddVolumeOutput("GRID_VELOCITY-Y", "Grid_Velocity_y", "GRID_VELOCITY", "y-component of the grid velocity vector");
if (nDim == 3 )
AddVolumeOutput("GRID_VELOCITY-Z", "Grid_Velocity_z", "GRID_VELOCITY", "z-component of the grid velocity vector");
}
// Primitive variables
AddVolumeOutput("PRESSURE_COEFF", "Pressure_Coefficient", "PRIMITIVE", "Pressure coefficient");
AddVolumeOutput("DENSITY", "Density", "PRIMITIVE", "Density");
if (config->GetKind_Solver() == INC_RANS || config->GetKind_Solver() == INC_NAVIER_STOKES){
AddVolumeOutput("LAMINAR_VISCOSITY", "Laminar_Viscosity", "PRIMITIVE", "Laminar viscosity");
AddVolumeOutput("SKIN_FRICTION-X", "Skin_Friction_Coefficient_x", "PRIMITIVE", "x-component of the skin friction vector");
AddVolumeOutput("SKIN_FRICTION-Y", "Skin_Friction_Coefficient_y", "PRIMITIVE", "y-component of the skin friction vector");
if (nDim == 3)
AddVolumeOutput("SKIN_FRICTION-Z", "Skin_Friction_Coefficient_z", "PRIMITIVE", "z-component of the skin friction vector");
AddVolumeOutput("HEAT_FLUX", "Heat_Flux", "PRIMITIVE", "Heat-flux");
AddVolumeOutput("Y_PLUS", "Y_Plus", "PRIMITIVE", "Non-dim. wall distance (Y-Plus)");
}
if (config->GetKind_Solver() == INC_RANS) {
AddVolumeOutput("EDDY_VISCOSITY", "Eddy_Viscosity", "PRIMITIVE", "Turbulent eddy viscosity");
}
if (config->GetKind_Trans_Model() == BC){
AddVolumeOutput("INTERMITTENCY", "gamma_BC", "INTERMITTENCY", "Intermittency");
}
//Residuals
AddVolumeOutput("RES_PRESSURE", "Residual_Pressure", "RESIDUAL", "Residual of the pressure");
AddVolumeOutput("RES_VELOCITY-X", "Residual_Velocity_x", "RESIDUAL", "Residual of the x-velocity component");
AddVolumeOutput("RES_VELOCITY-Y", "Residual_Velocity_y", "RESIDUAL", "Residual of the y-velocity component");
if (nDim == 3)
AddVolumeOutput("RES_VELOCITY-Z", "Residual_Velocity_z", "RESIDUAL", "Residual of the z-velocity component");
AddVolumeOutput("RES_TEMPERATURE", "Residual_Temperature", "RESIDUAL", "Residual of the temperature");
switch(config->GetKind_Turb_Model()){
case SST: case SST_SUST:
AddVolumeOutput("RES_TKE", "Residual_TKE", "RESIDUAL", "Residual of turbulent kinetic energy");
AddVolumeOutput("RES_DISSIPATION", "Residual_Omega", "RESIDUAL", "Residual of the rate of dissipation.");
break;
case SA: case SA_COMP: case SA_E:
case SA_E_COMP: case SA_NEG:
AddVolumeOutput("RES_NU_TILDE", "Residual_Nu_Tilde", "RESIDUAL", "Residual of the Spalart–Allmaras variable");
break;
case NONE:
break;
}
// Limiter values
AddVolumeOutput("LIMITER_PRESSURE", "Limiter_Pressure", "LIMITER", "Limiter value of the pressure");
AddVolumeOutput("LIMITER_VELOCITY-X", "Limiter_Velocity_x", "LIMITER", "Limiter value of the x-velocity");
AddVolumeOutput("LIMITER_VELOCITY-Y", "Limiter_Velocity_y", "LIMITER", "Limiter value of the y-velocity");
if (nDim == 3)
AddVolumeOutput("LIMITER_VELOCITY-Z", "Limiter_Velocity_z", "LIMITER", "Limiter value of the z-velocity");
AddVolumeOutput("LIMITER_TEMPERATURE", "Limiter_Temperature", "LIMITER", "Limiter value of the temperature");
switch(config->GetKind_Turb_Model()){
case SST: case SST_SUST:
AddVolumeOutput("LIMITER_TKE", "Limiter_TKE", "LIMITER", "Limiter value of turb. kinetic energy.");
AddVolumeOutput("LIMITER_DISSIPATION", "Limiter_Omega", "LIMITER", "Limiter value of dissipation rate.");
break;
case SA: case SA_COMP: case SA_E:
case SA_E_COMP: case SA_NEG:
AddVolumeOutput("LIMITER_NU_TILDE", "Limiter_Nu_Tilde", "LIMITER", "Limiter value of Spalart–Allmaras variable.");
break;
case NONE:
break;
}
// Hybrid RANS-LES
if (config->GetKind_HybridRANSLES() != NO_HYBRIDRANSLES){
AddVolumeOutput("DES_LENGTHSCALE", "DES_LengthScale", "DDES", "DES length scale value");
AddVolumeOutput("WALL_DISTANCE", "Wall_Distance", "DDES", "Wall distance value");
}
// Roe Low Dissipation
if (config->GetKind_RoeLowDiss() != NO_ROELOWDISS){
AddVolumeOutput("ROE_DISSIPATION", "Roe_Dissipation", "ROE_DISSIPATION", "Value of the Roe dissipation");
}
if(config->GetKind_Solver() == INC_RANS || config->GetKind_Solver() == INC_NAVIER_STOKES){
if (nDim == 3){
AddVolumeOutput("VORTICITY_X", "Vorticity_x", "VORTEX_IDENTIFICATION", "x-component of the vorticity vector");
AddVolumeOutput("VORTICITY_Y", "Vorticity_y", "VORTEX_IDENTIFICATION", "y-component of the vorticity vector");
AddVolumeOutput("VORTICITY_Z", "Vorticity_z", "VORTEX_IDENTIFICATION", "z-component of the vorticity vector");
} else {
AddVolumeOutput("VORTICITY", "Vorticity", "VORTEX_IDENTIFICATION", "Value of the vorticity");
}
AddVolumeOutput("Q_CRITERION", "Q_Criterion", "VORTEX_IDENTIFICATION", "Value of the Q-Criterion");
}
}
void CFlowIncOutput::LoadVolumeData(CConfig *config, CGeometry *geometry, CSolver **solver, unsigned long iPoint){
CVariable* Node_Flow = solver[FLOW_SOL]->GetNodes();
CVariable* Node_Heat = nullptr;
CVariable* Node_Turb = nullptr;
CVariable* Node_Rad = nullptr;
if (config->GetKind_Turb_Model() != NONE){
Node_Turb = solver[TURB_SOL]->GetNodes();
}
if (weakly_coupled_heat){
Node_Heat = solver[HEAT_SOL]->GetNodes();
}
CPoint* Node_Geo = geometry->nodes;
SetVolumeOutputValue("COORD-X", iPoint, Node_Geo->GetCoord(iPoint, 0));
SetVolumeOutputValue("COORD-Y", iPoint, Node_Geo->GetCoord(iPoint, 1));
if (nDim == 3)
SetVolumeOutputValue("COORD-Z", iPoint, Node_Geo->GetCoord(iPoint, 2));
SetVolumeOutputValue("PRESSURE", iPoint, Node_Flow->GetSolution(iPoint, 0));
SetVolumeOutputValue("VELOCITY-X", iPoint, Node_Flow->GetSolution(iPoint, 1));
SetVolumeOutputValue("VELOCITY-Y", iPoint, Node_Flow->GetSolution(iPoint, 2));
if (nDim == 3){
SetVolumeOutputValue("VELOCITY-Z", iPoint, Node_Flow->GetSolution(iPoint, 3));
if (heat) SetVolumeOutputValue("TEMPERATURE", iPoint, Node_Flow->GetSolution(iPoint, 4));
} else {
if (heat) SetVolumeOutputValue("TEMPERATURE", iPoint, Node_Flow->GetSolution(iPoint, 3));
}
if (weakly_coupled_heat) SetVolumeOutputValue("TEMPERATURE", iPoint, Node_Heat->GetSolution(iPoint, 0));
switch(config->GetKind_Turb_Model()){
case SST: case SST_SUST:
SetVolumeOutputValue("TKE", iPoint, Node_Turb->GetSolution(iPoint, 0));
SetVolumeOutputValue("DISSIPATION", iPoint, Node_Turb->GetSolution(iPoint, 1));
break;
case SA: case SA_COMP: case SA_E:
case SA_E_COMP: case SA_NEG:
SetVolumeOutputValue("NU_TILDE", iPoint, Node_Turb->GetSolution(iPoint, 0));
break;
case NONE:
break;
}
// Radiation solver
if (config->AddRadiation()){
Node_Rad = solver[RAD_SOL]->GetNodes();
SetVolumeOutputValue("P1-RAD", iPoint, Node_Rad->GetSolution(iPoint,0));
}
if (config->GetGrid_Movement()){
SetVolumeOutputValue("GRID_VELOCITY-X", iPoint, Node_Geo->GetGridVel(iPoint)[0]);
SetVolumeOutputValue("GRID_VELOCITY-Y", iPoint, Node_Geo->GetGridVel(iPoint)[1]);
if (nDim == 3)
SetVolumeOutputValue("GRID_VELOCITY-Z", iPoint, Node_Geo->GetGridVel(iPoint)[2]);
}
su2double VelMag = 0.0;
for (unsigned short iDim = 0; iDim < nDim; iDim++){
VelMag += pow(solver[FLOW_SOL]->GetVelocity_Inf(iDim),2.0);
}
su2double factor = 1.0/(0.5*solver[FLOW_SOL]->GetDensity_Inf()*VelMag);
SetVolumeOutputValue("PRESSURE_COEFF", iPoint, (Node_Flow->GetPressure(iPoint) - config->GetPressure_FreeStreamND())*factor);
SetVolumeOutputValue("DENSITY", iPoint, Node_Flow->GetDensity(iPoint));
if (config->GetKind_Solver() == INC_RANS || config->GetKind_Solver() == INC_NAVIER_STOKES){
SetVolumeOutputValue("LAMINAR_VISCOSITY", iPoint, Node_Flow->GetLaminarViscosity(iPoint));
}
if (config->GetKind_Solver() == INC_RANS) {
SetVolumeOutputValue("EDDY_VISCOSITY", iPoint, Node_Flow->GetEddyViscosity(iPoint));
}
if (config->GetKind_Trans_Model() == BC){
SetVolumeOutputValue("INTERMITTENCY", iPoint, Node_Turb->GetGammaBC(iPoint));
}
SetVolumeOutputValue("RES_PRESSURE", iPoint, solver[FLOW_SOL]->LinSysRes(iPoint, 0));
SetVolumeOutputValue("RES_VELOCITY-X", iPoint, solver[FLOW_SOL]->LinSysRes(iPoint, 1));
SetVolumeOutputValue("RES_VELOCITY-Y", iPoint, solver[FLOW_SOL]->LinSysRes(iPoint, 2));
if (nDim == 3){
SetVolumeOutputValue("RES_VELOCITY-Z", iPoint, solver[FLOW_SOL]->LinSysRes(iPoint, 3));
SetVolumeOutputValue("RES_TEMPERATURE", iPoint, solver[FLOW_SOL]->LinSysRes(iPoint, 4));
} else {
SetVolumeOutputValue("RES_TEMPERATURE", iPoint, solver[FLOW_SOL]->LinSysRes(iPoint, 3));
}
switch(config->GetKind_Turb_Model()){
case SST: case SST_SUST:
SetVolumeOutputValue("RES_TKE", iPoint, solver[TURB_SOL]->LinSysRes(iPoint, 0));
SetVolumeOutputValue("RES_DISSIPATION", iPoint, solver[TURB_SOL]->LinSysRes(iPoint, 1));
break;
case SA: case SA_COMP: case SA_E:
case SA_E_COMP: case SA_NEG:
SetVolumeOutputValue("RES_NU_TILDE", iPoint, solver[TURB_SOL]->LinSysRes(iPoint, 0));
break;
case NONE:
break;
}
SetVolumeOutputValue("LIMITER_PRESSURE", iPoint, Node_Flow->GetLimiter_Primitive(iPoint, 0));
SetVolumeOutputValue("LIMITER_VELOCITY-X", iPoint, Node_Flow->GetLimiter_Primitive(iPoint, 1));
SetVolumeOutputValue("LIMITER_VELOCITY-Y", iPoint, Node_Flow->GetLimiter_Primitive(iPoint, 2));
if (nDim == 3){
SetVolumeOutputValue("LIMITER_VELOCITY-Z", iPoint, Node_Flow->GetLimiter_Primitive(iPoint, 3));
SetVolumeOutputValue("LIMITER_TEMPERATURE", iPoint, Node_Flow->GetLimiter_Primitive(iPoint, 4));
} else {
SetVolumeOutputValue("LIMITER_TEMPERATURE", iPoint, Node_Flow->GetLimiter_Primitive(iPoint, 3));
}
switch(config->GetKind_Turb_Model()){
case SST: case SST_SUST:
SetVolumeOutputValue("LIMITER_TKE", iPoint, Node_Turb->GetLimiter_Primitive(iPoint, 0));
SetVolumeOutputValue("LIMITER_DISSIPATION", iPoint, Node_Turb->GetLimiter_Primitive(iPoint, 1));
break;
case SA: case SA_COMP: case SA_E:
case SA_E_COMP: case SA_NEG:
SetVolumeOutputValue("LIMITER_NU_TILDE", iPoint, Node_Turb->GetLimiter_Primitive(iPoint, 0));
break;
case NONE:
break;
}
if (config->GetKind_HybridRANSLES() != NO_HYBRIDRANSLES){
SetVolumeOutputValue("DES_LENGTHSCALE", iPoint, Node_Flow->GetDES_LengthScale(iPoint));
SetVolumeOutputValue("WALL_DISTANCE", iPoint, Node_Geo->GetWall_Distance(iPoint));
}
if (config->GetKind_RoeLowDiss() != NO_ROELOWDISS){
SetVolumeOutputValue("ROE_DISSIPATION", iPoint, Node_Flow->GetRoe_Dissipation(iPoint));
}
if(config->GetKind_Solver() == INC_RANS || config->GetKind_Solver() == INC_NAVIER_STOKES){
if (nDim == 3){
SetVolumeOutputValue("VORTICITY_X", iPoint, Node_Flow->GetVorticity(iPoint)[0]);
SetVolumeOutputValue("VORTICITY_Y", iPoint, Node_Flow->GetVorticity(iPoint)[1]);
SetVolumeOutputValue("VORTICITY_Z", iPoint, Node_Flow->GetVorticity(iPoint)[2]);
} else {
SetVolumeOutputValue("VORTICITY", iPoint, Node_Flow->GetVorticity(iPoint)[2]);
}
SetVolumeOutputValue("Q_CRITERION", iPoint, GetQ_Criterion(&(Node_Flow->GetGradient_Primitive(iPoint)[1])));
}
}
void CFlowIncOutput::LoadSurfaceData(CConfig *config, CGeometry *geometry, CSolver **solver, unsigned long iPoint, unsigned short iMarker, unsigned long iVertex){
if ((config->GetKind_Solver() == INC_NAVIER_STOKES) || (config->GetKind_Solver() == INC_RANS)) {
SetVolumeOutputValue("SKIN_FRICTION-X", iPoint, solver[FLOW_SOL]->GetCSkinFriction(iMarker, iVertex, 0));
SetVolumeOutputValue("SKIN_FRICTION-Y", iPoint, solver[FLOW_SOL]->GetCSkinFriction(iMarker, iVertex, 1));
if (nDim == 3)
SetVolumeOutputValue("SKIN_FRICTION-Z", iPoint, solver[FLOW_SOL]->GetCSkinFriction(iMarker, iVertex, 2));
if (weakly_coupled_heat)
SetVolumeOutputValue("HEAT_FLUX", iPoint, solver[HEAT_SOL]->GetHeatFlux(iMarker, iVertex));
else {
SetVolumeOutputValue("HEAT_FLUX", iPoint, solver[FLOW_SOL]->GetHeatFlux(iMarker, iVertex));
}
SetVolumeOutputValue("Y_PLUS", iPoint, solver[FLOW_SOL]->GetYPlus(iMarker, iVertex));
}
}
bool CFlowIncOutput::SetInit_Residuals(CConfig *config){
return (config->GetTime_Marching() != STEADY && (curInnerIter == 0))||
(config->GetTime_Marching() == STEADY && (curInnerIter < 2));
}
bool CFlowIncOutput::SetUpdate_Averages(CConfig *config){
return (config->GetTime_Marching() != STEADY && (curInnerIter == config->GetnInner_Iter() - 1 || convergence));
}
| 49.93465 | 200 | 0.728916 | Agony5757 |
2e2fb6a40004323ac62160c3d1faa75223cf7e51 | 704 | cpp | C++ | src/gwmessage/GWUnpairRequest.cpp | tacr-iotcloud/base | caa10794b965c578f596d616e9654a6a8ef2c169 | [
"BSD-3-Clause"
] | null | null | null | src/gwmessage/GWUnpairRequest.cpp | tacr-iotcloud/base | caa10794b965c578f596d616e9654a6a8ef2c169 | [
"BSD-3-Clause"
] | null | null | null | src/gwmessage/GWUnpairRequest.cpp | tacr-iotcloud/base | caa10794b965c578f596d616e9654a6a8ef2c169 | [
"BSD-3-Clause"
] | 1 | 2019-01-08T14:48:29.000Z | 2019-01-08T14:48:29.000Z | #include "gwmessage/GWUnpairRequest.h"
#include "gwmessage/GWUnpairResponse.h"
using namespace std;
using namespace Poco;
using namespace BeeeOn;
GWUnpairRequest::GWUnpairRequest():
GWRequest(GWMessageType::UNPAIR_REQUEST)
{
}
GWUnpairRequest::GWUnpairRequest(const JSON::Object::Ptr object) :
GWRequest(object)
{
}
void GWUnpairRequest::setDeviceID(const DeviceID &deviceID)
{
json()->set("device_id", deviceID.toString());
}
DeviceID GWUnpairRequest::deviceID() const
{
return DeviceID::parse(json()->getValue<string>("device_id"));
}
GWResponse::Ptr GWUnpairRequest::deriveResponse() const
{
GWUnpairResponse::Ptr response = new GWUnpairResponse;
return deriveGenericResponse(response);
}
| 21.333333 | 66 | 0.778409 | tacr-iotcloud |
2e302fc270d22b89db1aede75e0c47b29168bfd8 | 6,559 | cpp | C++ | wws_lua/extras/Lua.Utilities/luawrapper.cpp | ViseEngine/SLED | 7815ee6feb656d43f70edba8280caa8a69d0983b | [
"Apache-2.0"
] | 158 | 2015-03-03T00:11:56.000Z | 2022-02-08T18:43:11.000Z | wws_lua/extras/Lua.Utilities/luawrapper.cpp | mcanthony/SLED | 7815ee6feb656d43f70edba8280caa8a69d0983b | [
"Apache-2.0"
] | 3 | 2015-04-30T13:00:43.000Z | 2015-07-07T22:58:35.000Z | wws_lua/extras/Lua.Utilities/luawrapper.cpp | mcanthony/SLED | 7815ee6feb656d43f70edba8280caa8a69d0983b | [
"Apache-2.0"
] | 48 | 2015-03-05T05:30:45.000Z | 2021-10-18T02:09:02.000Z | /*
* Copyright (C) Sony Computer Entertainment America LLC.
* All Rights Reserved.
*/
#include "stdafx.h"
#include "luawrapper.h"
#include <msclr\marshal_cppstd.h>
#include <string>
namespace Unmanaged
{
StackReconciler::StackReconciler(lua_State* luaState)
: m_luaState(luaState)
, m_count(LuaInterface::GetTop(luaState))
{
}
StackReconciler::~StackReconciler()
{
const int count = LuaInterface::GetTop(m_luaState);
if ((count != m_count) && (count > m_count))
LuaInterface::Pop(m_luaState, count - m_count);
}
LuaWrapper::LuaWrapper()
: m_luaState(NULL)
{
m_luaState = LuaInterface::Open();
LuaInterface::OpenLibs(m_luaState);
}
LuaWrapper::~LuaWrapper()
{
LuaInterface::Close(m_luaState);
}
LuaInterface::Errors::Enum LuaWrapper::LoadFile(System::String^ scriptFile)
{
const std::string str = msclr::interop::marshal_as<std::string>(scriptFile);
return LuaInterface::TranslateLuaError(LuaInterface::LoadFile(m_luaState, str.c_str()));
}
LuaInterface::Errors::Enum LuaWrapper::LoadFile(System::String^ scriptFile,
Sce::Lua::Utilities::ParserVariableDelegate^ globalCb,
Sce::Lua::Utilities::ParserVariableDelegate^ localCb,
Sce::Lua::Utilities::ParserVariableDelegate^ upvalueCb,
Sce::Lua::Utilities::ParserFunctionDelegate^ funcCb,
Sce::Lua::Utilities::ParserBreakpointDelegate^ bpCb,
Sce::Lua::Utilities::ParserLogDelegate^ logCb)
{
System::IntPtr ipGlobalCb =
globalCb == nullptr
? System::IntPtr::Zero
: System::Runtime::InteropServices::Marshal::GetFunctionPointerForDelegate(globalCb);
System::IntPtr ipLocalCb =
localCb == nullptr
? System::IntPtr::Zero
: System::Runtime::InteropServices::Marshal::GetFunctionPointerForDelegate(localCb);
System::IntPtr ipUpvalueCb =
upvalueCb == nullptr
? System::IntPtr::Zero
: System::Runtime::InteropServices::Marshal::GetFunctionPointerForDelegate(upvalueCb);
System::IntPtr ipFuncCb =
funcCb == nullptr
? System::IntPtr::Zero
: System::Runtime::InteropServices::Marshal::GetFunctionPointerForDelegate(funcCb);
System::IntPtr ipBpCb =
bpCb == nullptr
? System::IntPtr::Zero
: System::Runtime::InteropServices::Marshal::GetFunctionPointerForDelegate(bpCb);
System::IntPtr ipLogCb =
logCb == nullptr
? System::IntPtr::Zero
: System::Runtime::InteropServices::Marshal::GetFunctionPointerForDelegate(logCb);
// Tell Lua about the function pointers
{
lparser_callbacks::VariableCallback nativeGlobalCb = static_cast<lparser_callbacks::VariableCallback>(ipGlobalCb.ToPointer());
lparser_callbacks::VariableCallback nativeLocalCb = static_cast<lparser_callbacks::VariableCallback>(ipLocalCb.ToPointer());
lparser_callbacks::VariableCallback nativeUpvalueCb = static_cast<lparser_callbacks::VariableCallback>(ipUpvalueCb.ToPointer());
lparser_callbacks::FunctionCallback nativeFuncCb = static_cast<lparser_callbacks::FunctionCallback>(ipFuncCb.ToPointer());
lparser_callbacks::BreakpointCallback nativeBpCb = static_cast<lparser_callbacks::BreakpointCallback>(ipBpCb.ToPointer());
lparser_callbacks::LogCallback nativeLogCb = static_cast<lparser_callbacks::LogCallback>(ipLogCb.ToPointer());
const Unmanaged::StackReconciler recon(m_luaState);
LuaInterface::GetGlobal(m_luaState, LUA_PARSER_DEBUG_TABLE);
if (LuaInterface::IsNil(m_luaState, -1))
{
LuaInterface::Pop(m_luaState, 1);
// Create parser debug table
LuaInterface::NewTable(m_luaState);
LuaInterface::SetGlobal(m_luaState, LUA_PARSER_DEBUG_TABLE);
// Get parser debug table on top of stack
LuaInterface::GetGlobal(m_luaState, LUA_PARSER_DEBUG_TABLE);
// Set function pointers
LuaInterface::PushLightUserdata(m_luaState, nativeGlobalCb);
LuaInterface::SetField(m_luaState, -2, LUA_PARSER_CB_VAR_GLOBAL);
LuaInterface::PushLightUserdata(m_luaState, nativeLocalCb);
LuaInterface::SetField(m_luaState, -2, LUA_PARSER_CB_VAR_LOCAL);
LuaInterface::PushLightUserdata(m_luaState, nativeUpvalueCb);
LuaInterface::SetField(m_luaState, -2, LUA_PARSER_CB_VAR_UPVALUE);
LuaInterface::PushLightUserdata(m_luaState, nativeFuncCb);
LuaInterface::SetField(m_luaState, -2, LUA_PARSER_CB_FUNC);
LuaInterface::PushLightUserdata(m_luaState, nativeBpCb);
LuaInterface::SetField(m_luaState, -2, LUA_PARSER_CB_BREAKPOINT);
LuaInterface::PushLightUserdata(m_luaState, nativeLogCb);
LuaInterface::SetField(m_luaState, -2, LUA_PARSER_CB_LOG);
}
}
const LuaInterface::Errors::Enum retval = LuaInterface::TranslateLuaError(LoadFile(scriptFile));
{
ipGlobalCb = System::IntPtr::Zero;
ipLocalCb = System::IntPtr::Zero;
ipUpvalueCb = System::IntPtr::Zero;
ipFuncCb = System::IntPtr::Zero;
ipBpCb = System::IntPtr::Zero;
ipLogCb = System::IntPtr::Zero;
}
return retval;
}
LuaInterface::Errors::Enum LuaWrapper::LoadBuffer(System::String^ scriptBuffer)
{
const std::string buffer = msclr::interop::marshal_as<std::string>(scriptBuffer);
return LuaInterface::TranslateLuaError(LuaInterface::LoadBuffer(m_luaState, buffer.c_str(), buffer.length(), "buffer"));
}
int LuaWrapper::Compile_Writer(lua_State* L, const void* pData, size_t size, void* pFile)
{
(void)L;
return ((fwrite(pData, size, 1, (FILE *)pFile) != 1) && (size != 0));
}
LuaInterface::Errors::Enum LuaWrapper::Compile(System::String^ scriptAbsFilePath, System::String^ scriptAbsDumpFilePath, Sce::Lua::Utilities::LuaCompilerConfig^ config)
{
// Load script into Lua state
{
const std::string strInFile = msclr::interop::marshal_as<std::string>(scriptAbsFilePath);
const LuaInterface::Errors::Enum err =
LuaInterface::TranslateLuaError(LuaInterface::LoadFile(m_luaState, strInFile.c_str()));
if (err != LuaInterface::Errors::Ok)
return err;
}
// Create and open the dump file
FILE* pDumpFile = 0;
{
const std::string strOutFile = msclr::interop::marshal_as<std::string>(scriptAbsDumpFilePath);
if (fopen_s(&pDumpFile, strOutFile.c_str(), "wb") != 0)
return LuaInterface::Errors::ErrOutputFile;
}
// Dump script to file
{
LuaInterface::DumpConfig dumpConfig;
dumpConfig.endianness = (int)config->Endianness;
dumpConfig.sizeof_int = config->SizeOfInt;
dumpConfig.sizeof_size_t = config->SizeOfSizeT;
dumpConfig.sizeof_lua_Number = config->SizeOfLuaNumber;
const LuaInterface::Errors::Enum err =
LuaInterface::TranslateLuaError(
LuaInterface::DumpEx(m_luaState, Compile_Writer, pDumpFile, (config->StripDebugInfo ? 1 : 0), dumpConfig));
// Close dump file
fclose(pDumpFile);
return err;
}
}
}
| 33.984456 | 168 | 0.751944 | ViseEngine |
2e304d5d162ee27191532c7d630113bd7e7998de | 12,063 | hpp | C++ | sources/middle_layer/src/partial_completion.hpp | hhb584520/DML | 014eb9894e85334f03ec74435933c972f3d05b50 | [
"MIT"
] | null | null | null | sources/middle_layer/src/partial_completion.hpp | hhb584520/DML | 014eb9894e85334f03ec74435933c972f3d05b50 | [
"MIT"
] | null | null | null | sources/middle_layer/src/partial_completion.hpp | hhb584520/DML | 014eb9894e85334f03ec74435933c972f3d05b50 | [
"MIT"
] | 1 | 2022-03-28T07:52:21.000Z | 2022-03-28T07:52:21.000Z | /*******************************************************************************
* Copyright (C) 2021 Intel Corporation
*
* SPDX-License-Identifier: MIT
******************************************************************************/
#ifndef DML_ML_OWN_PARTIAL_COMPLETION_HPP
#define DML_ML_OWN_PARTIAL_COMPLETION_HPP
#include <core/descriptor_views.hpp>
#include <dml/detail/ml/impl/make_descriptor.hpp>
namespace dml::detail::ml
{
static void update_mem_move_for_continuation(descriptor& dsc) noexcept;
static void update_fill_for_continuation(descriptor& dsc) noexcept;
static void update_compare_for_continuation(descriptor& dsc) noexcept;
static void update_compare_pattern_for_continuation(descriptor& dsc) noexcept;
static void update_create_delta_for_continuation(descriptor& dsc) noexcept;
static void update_apply_delta_for_continuation(descriptor& dsc) noexcept;
static void update_dualcast_for_continuation(descriptor& dsc) noexcept;
static void update_crc_for_continuation(descriptor& dsc) noexcept;
static void update_copy_crc_for_continuation(descriptor& dsc) noexcept;
static void update_dif_check_for_continuation(descriptor& dsc) noexcept;
static void update_dif_insert_for_continuation(descriptor& dsc) noexcept;
static void update_dif_strip_for_continuation(descriptor& dsc) noexcept;
static void update_dif_update_for_continuation(descriptor& dsc) noexcept;
static void update_cache_flush_for_continuation(descriptor& dsc) noexcept;
static void update_for_continuation(descriptor& dsc) noexcept
{
auto record = core::get_completion_record(dsc);
for (auto& byte : record.bytes)
{
byte = 0;
}
auto operation = static_cast<core::operation>(core::any_descriptor(dsc).operation());
switch (operation)
{
case core::operation::nop:
break;
case core::operation::drain:
break;
case core::operation::batch:
break;
case core::operation::mem_move:
update_mem_move_for_continuation(dsc);
break;
case core::operation::fill:
update_fill_for_continuation(dsc);
break;
case core::operation::compare:
update_compare_for_continuation(dsc);
break;
case core::operation::compare_pattern:
update_compare_pattern_for_continuation(dsc);
break;
case core::operation::create_delta:
update_create_delta_for_continuation(dsc);
break;
case core::operation::apply_delta:
update_apply_delta_for_continuation(dsc);
break;
case core::operation::dualcast:
update_dualcast_for_continuation(dsc);
break;
case core::operation::crc:
update_crc_for_continuation(dsc);
break;
case core::operation::copy_crc:
update_copy_crc_for_continuation(dsc);
break;
case core::operation::dif_check:
update_dif_check_for_continuation(dsc);
break;
case core::operation::dif_insert:
update_dif_insert_for_continuation(dsc);
break;
case core::operation::dif_strip:
update_dif_strip_for_continuation(dsc);
break;
case core::operation::dif_update:
update_dif_update_for_continuation(dsc);
break;
case core::operation::cache_flush:
update_cache_flush_for_continuation(dsc);
break;
}
}
static void update_mem_move_for_continuation(descriptor& dsc) noexcept
{
auto mem_move_dsc = core::make_view<core::operation::mem_move>(dsc);
auto mem_move_record = core::make_view<core::operation::mem_move>(core::get_completion_record(dsc));
if (0 == mem_move_record.result())
{
mem_move_dsc.source_address() += mem_move_record.bytes_completed();
mem_move_dsc.destination_address() += mem_move_record.bytes_completed();
}
mem_move_dsc.transfer_size() -= mem_move_record.bytes_completed();
}
static void update_fill_for_continuation(descriptor& dsc) noexcept
{
auto fill_dsc = core::make_view<core::operation::fill>(dsc);
auto fill_record = core::make_view<core::operation::fill>(core::get_completion_record(dsc));
fill_dsc.transfer_size() -= fill_record.bytes_completed();
fill_dsc.destination_address() += fill_record.bytes_completed();
}
static void update_compare_for_continuation(descriptor& dsc) noexcept
{
auto compare_dsc = core::make_view<core::operation::compare>(dsc);
auto compare_record = core::make_view<core::operation::compare>(core::get_completion_record(dsc));
compare_dsc.transfer_size() -= compare_record.bytes_completed();
compare_dsc.source_1_address() += compare_record.bytes_completed();
compare_dsc.source_2_address() += compare_record.bytes_completed();
}
static void update_compare_pattern_for_continuation(descriptor& dsc) noexcept
{
auto compare_pattern_dsc = core::make_view<core::operation::compare_pattern>(dsc);
auto compare_pattern_record = core::make_view<core::operation::compare_pattern>(core::get_completion_record(dsc));
compare_pattern_dsc.transfer_size() -= compare_pattern_record.bytes_completed();
compare_pattern_dsc.source_address() += compare_pattern_record.bytes_completed();
}
static void update_create_delta_for_continuation(descriptor& dsc) noexcept
{
auto create_delta_dsc = core::make_view<core::operation::create_delta>(dsc);
auto create_delta_record = core::make_view<core::operation::create_delta>(core::get_completion_record(dsc));
create_delta_dsc.transfer_size() -= create_delta_record.bytes_completed();
create_delta_dsc.source_1_address() += create_delta_record.bytes_completed();
create_delta_dsc.source_2_address() += create_delta_record.bytes_completed();
create_delta_dsc.maximum_delta_record_size() -= create_delta_record.delta_record_size();
create_delta_dsc.delta_record_address() += create_delta_record.delta_record_size();
}
static void update_apply_delta_for_continuation(descriptor& dsc) noexcept
{
auto apply_delta_dsc = core::make_view<core::operation::apply_delta>(dsc);
auto apply_delta_record = core::make_view<core::operation::apply_delta>(core::get_completion_record(dsc));
apply_delta_dsc.delta_record_size() -= apply_delta_record.bytes_completed();
apply_delta_dsc.delta_record_address() += apply_delta_record.bytes_completed();
}
static void update_dualcast_for_continuation(descriptor& dsc) noexcept
{
auto dualcast_dsc = core::make_view<core::operation::dualcast>(dsc);
auto dualcast_record = core::make_view<core::operation::dualcast>(core::get_completion_record(dsc));
dualcast_dsc.destination_1_address() += dualcast_record.bytes_completed();
dualcast_dsc.destination_2_address() += dualcast_record.bytes_completed();
dualcast_dsc.source_address() += dualcast_record.bytes_completed();
dualcast_dsc.transfer_size() -= dualcast_record.bytes_completed();
}
static void update_crc_for_continuation(descriptor& dsc) noexcept
{
auto crc_dsc = core::make_view<core::operation::crc>(dsc);
auto crc_record = core::make_view<core::operation::crc>(core::get_completion_record(dsc));
crc_dsc.crc_seed() = crc_record.crc_value();
crc_dsc.source_address() += crc_record.bytes_completed();
crc_dsc.transfer_size() -= crc_record.bytes_completed();
}
static void update_copy_crc_for_continuation(descriptor& dsc) noexcept
{
auto copy_crc_dsc = core::make_view<core::operation::copy_crc>(dsc);
auto copy_crc_record = core::make_view<core::operation::copy_crc>(core::get_completion_record(dsc));
copy_crc_dsc.crc_seed() = copy_crc_record.crc_value();
copy_crc_dsc.source_address() += copy_crc_record.bytes_completed();
copy_crc_dsc.destination_address() += copy_crc_record.bytes_completed();
copy_crc_dsc.transfer_size() -= copy_crc_record.bytes_completed();
}
static void update_dif_check_for_continuation(descriptor& dsc) noexcept
{
auto dif_check_dsc = core::make_view<core::operation::dif_check>(dsc);
auto dif_check_record = core::make_view<core::operation::dif_check>(core::get_completion_record(dsc));
dif_check_dsc.source_app_tag() = dif_check_record.source_app_tag();
dif_check_dsc.source_ref_tag() = dif_check_record.source_ref_tag();
dif_check_dsc.source_address() += dif_check_record.bytes_completed();
dif_check_dsc.transfer_size() -= dif_check_record.bytes_completed();
}
static void update_dif_insert_for_continuation(descriptor& dsc) noexcept
{
auto dif_insert_dsc = core::make_view<core::operation::dif_insert>(dsc);
auto dif_insert_record = core::make_view<core::operation::dif_insert>(core::get_completion_record(dsc));
dif_insert_dsc.destination_app_tag() = dif_insert_record.destination_app_tag();
dif_insert_dsc.destination_ref_tag() = dif_insert_record.destination_ref_tag();
dif_insert_dsc.source_address() += dif_insert_record.bytes_completed();
dif_insert_dsc.destination_address() += dif_insert_record.bytes_completed();
dif_insert_dsc.transfer_size() -= dif_insert_record.bytes_completed();
}
static void update_dif_strip_for_continuation(descriptor& dsc) noexcept
{
auto dif_strip_dsc = core::make_view<core::operation::dif_strip>(dsc);
auto dif_strip_record = core::make_view<core::operation::dif_strip>(core::get_completion_record(dsc));
dif_strip_dsc.source_app_tag() = dif_strip_record.source_app_tag();
dif_strip_dsc.source_ref_tag() = dif_strip_record.source_ref_tag();
dif_strip_dsc.source_address() += dif_strip_record.bytes_completed();
dif_strip_dsc.destination_address() += dif_strip_record.bytes_completed();
dif_strip_dsc.transfer_size() -= dif_strip_record.bytes_completed();
}
static void update_dif_update_for_continuation(descriptor& dsc) noexcept
{
auto dif_update_dsc = core::make_view<core::operation::dif_update>(dsc);
auto dif_update_record = core::make_view<core::operation::dif_update>(core::get_completion_record(dsc));
dif_update_dsc.source_app_tag() = dif_update_record.source_app_tag();
dif_update_dsc.source_app_tag() = dif_update_record.source_app_tag();
dif_update_dsc.destination_app_tag() = dif_update_record.destination_app_tag();
dif_update_dsc.destination_ref_tag() = dif_update_record.destination_ref_tag();
dif_update_dsc.source_ref_tag() = dif_update_record.source_ref_tag();
dif_update_dsc.source_address() += dif_update_record.bytes_completed();
dif_update_dsc.destination_address() += dif_update_record.bytes_completed();
dif_update_dsc.transfer_size() -= dif_update_record.bytes_completed();
}
static void update_cache_flush_for_continuation(descriptor& dsc) noexcept
{
auto cache_flush_dsc = core::make_view<core::operation::cache_flush>(dsc);
auto cache_flush_record = core::make_view<core::operation::cache_flush>(core::get_completion_record(dsc));
cache_flush_dsc.destination_address() += cache_flush_record.bytes_completed();
cache_flush_dsc.transfer_size() -= cache_flush_record.bytes_completed();
}
} // namespace dml::detail::ml
#endif // DML_ML_OWN_PARTIAL_COMPLETION_HPP
| 46.041985 | 122 | 0.691287 | hhb584520 |
2e3152e88bacc8c8fe68107e3ee51ff9b01532fa | 93 | cpp | C++ | gamelib/source/util/json_array.cpp | brodiequinlan/game-framework | 4243d9b011e0d17da66874fa77b3b6d7a6c5e440 | [
"Apache-2.0"
] | 1 | 2021-11-20T02:36:28.000Z | 2021-11-20T02:36:28.000Z | gamelib/source/util/json_array.cpp | Bobsaggetismine/game-framework | 4243d9b011e0d17da66874fa77b3b6d7a6c5e440 | [
"Apache-2.0"
] | 1 | 2019-06-11T01:45:11.000Z | 2019-06-11T01:47:43.000Z | gamelib/source/util/json_array.cpp | Bobsaggetismine/game-framework | 4243d9b011e0d17da66874fa77b3b6d7a6c5e440 | [
"Apache-2.0"
] | null | null | null | #include "bqpch.h"
bq::json bq::json_array::get_o(int index){
return m_objects[index];
} | 18.6 | 42 | 0.688172 | brodiequinlan |
2e3245b199e5b94f173ed2a4d3f4939a8207c722 | 913 | hpp | C++ | include/inet/Url.hpp | bander9289/StratifyAPI | 9b45091aa71a4e5718047438ea4044c1fdc814a3 | [
"MIT"
] | 2 | 2016-05-21T03:09:19.000Z | 2016-08-27T03:40:51.000Z | include/inet/Url.hpp | bander9289/StratifyAPI | 9b45091aa71a4e5718047438ea4044c1fdc814a3 | [
"MIT"
] | 75 | 2017-10-08T22:21:19.000Z | 2020-03-30T21:13:20.000Z | include/inet/Url.hpp | StratifyLabs/StratifyLib | 975a5c25a84296fd0dec64fe4dc579cf7027abe6 | [
"MIT"
] | 5 | 2018-03-27T16:44:09.000Z | 2020-07-08T16:45:55.000Z | /*! \file */ // Copyright 2011-2020 Tyler Gilbert and Stratify Labs, Inc; see LICENSE.md for rights.
#ifndef SAPI_INET_URL_HPP_
#define SAPI_INET_URL_HPP_
#include "../api/InetObject.hpp"
#include "../var/String.hpp"
namespace inet {
class Url : public api::InfoObject {
public:
enum protocol {
protocol_https,
protocol_http
};
Url(const var::String & url = "");
int set(const var::String & url);
var::String to_string() const;
u16 port() const { return m_port; }
u8 protocol() const { return m_protocol; }
const var::String & domain_name() const { return m_domain_name; }
const var::String & path() const { return m_path; }
static var::String encode(const var::String & input);
static var::String decode(const var::String & input);
private:
/*! \cond */
var::String m_domain_name;
var::String m_path;
u8 m_protocol;
u16 m_port;
/*! \endcond */
};
}
#endif // SAPI_INET_URL_HPP_
| 20.288889 | 100 | 0.691128 | bander9289 |
2e362fd19c16511717e9a09d623e79383b3d95c9 | 4,801 | hpp | C++ | opencv/sources/modules/video/src/tracking/detail/tracking_feature.hpp | vrushank-agrawal/opencv-x64-cmake | 3f9486510d706c8ac579ac82f5d58f667f948124 | [
"Apache-2.0"
] | null | null | null | opencv/sources/modules/video/src/tracking/detail/tracking_feature.hpp | vrushank-agrawal/opencv-x64-cmake | 3f9486510d706c8ac579ac82f5d58f667f948124 | [
"Apache-2.0"
] | null | null | null | opencv/sources/modules/video/src/tracking/detail/tracking_feature.hpp | vrushank-agrawal/opencv-x64-cmake | 3f9486510d706c8ac579ac82f5d58f667f948124 | [
"Apache-2.0"
] | null | null | null | // This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
#ifndef OPENCV_VIDEO_DETAIL_TRACKING_FEATURE_HPP
#define OPENCV_VIDEO_DETAIL_TRACKING_FEATURE_HPP
#include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"
/*
* TODO This implementation is based on apps/traincascade/
* TODO Changed CvHaarEvaluator based on ADABOOSTING implementation (Grabner et al.)
*/
namespace cv {
namespace detail {
inline namespace tracking {
//! @addtogroup tracking_detail
//! @{
inline namespace feature {
class CvParams
{
public:
CvParams();
virtual ~CvParams()
{
}
};
class CvFeatureParams : public CvParams
{
public:
enum FeatureType
{
HAAR = 0,
LBP = 1,
HOG = 2
};
CvFeatureParams();
static Ptr<CvFeatureParams> create(CvFeatureParams::FeatureType featureType);
int maxCatCount; // 0 in case of numerical features
int featSize; // 1 in case of simple features (HAAR, LBP) and N_BINS(9)*N_CELLS(4) in case of Dalal's HOG features
int numFeatures;
};
class CvFeatureEvaluator
{
public:
virtual ~CvFeatureEvaluator()
{
}
virtual void init(const CvFeatureParams* _featureParams, int _maxSampleCount, Size _winSize);
virtual void setImage(const Mat& img, uchar clsLabel, int idx);
static Ptr<CvFeatureEvaluator> create(CvFeatureParams::FeatureType type);
int getNumFeatures() const
{
return numFeatures;
}
int getMaxCatCount() const
{
return featureParams->maxCatCount;
}
int getFeatureSize() const
{
return featureParams->featSize;
}
const Mat& getCls() const
{
return cls;
}
float getCls(int si) const
{
return cls.at<float>(si, 0);
}
protected:
virtual void generateFeatures() = 0;
int npos, nneg;
int numFeatures;
Size winSize;
CvFeatureParams* featureParams;
Mat cls;
};
class CvHaarFeatureParams : public CvFeatureParams
{
public:
CvHaarFeatureParams();
bool isIntegral;
};
class CvHaarEvaluator : public CvFeatureEvaluator
{
public:
class FeatureHaar
{
public:
FeatureHaar(Size patchSize);
bool eval(const Mat& image, Rect ROI, float* result) const;
inline int getNumAreas() const { return m_numAreas; }
inline const std::vector<float>& getWeights() const { return m_weights; }
inline const std::vector<Rect>& getAreas() const { return m_areas; }
private:
int m_type;
int m_numAreas;
std::vector<float> m_weights;
float m_initMean;
float m_initSigma;
void generateRandomFeature(Size imageSize);
float getSum(const Mat& image, Rect imgROI) const;
std::vector<Rect> m_areas; // areas within the patch over which to compute the feature
cv::Size m_initSize; // size of the patch used during training
cv::Size m_curSize; // size of the patches currently under investigation
float m_scaleFactorHeight; // scaling factor in vertical direction
float m_scaleFactorWidth; // scaling factor in horizontal direction
std::vector<Rect> m_scaleAreas; // areas after scaling
std::vector<float> m_scaleWeights; // weights after scaling
};
virtual void init(const CvFeatureParams* _featureParams, int _maxSampleCount, Size _winSize) CV_OVERRIDE;
virtual void setImage(const Mat& img, uchar clsLabel = 0, int idx = 1) CV_OVERRIDE;
inline const std::vector<CvHaarEvaluator::FeatureHaar>& getFeatures() const { return features; }
inline CvHaarEvaluator::FeatureHaar& getFeatures(int idx)
{
return features[idx];
}
inline void setWinSize(Size patchSize) { winSize = patchSize; }
inline Size getWinSize() const { return winSize; }
virtual void generateFeatures() CV_OVERRIDE;
/**
* \brief Overload the original generateFeatures in order to limit the number of the features
* @param numFeatures Number of the features
*/
virtual void generateFeatures(int numFeatures);
protected:
bool isIntegral;
/* TODO Added from MIL implementation */
Mat _ii_img;
void compute_integral(const cv::Mat& img, std::vector<cv::Mat_<float>>& ii_imgs)
{
Mat ii_img;
integral(img, ii_img, CV_32F);
split(ii_img, ii_imgs);
}
std::vector<FeatureHaar> features;
Mat sum; /* sum images (each row represents image) */
};
} // namespace feature
//! @}
}}} // namespace cv::detail::tracking
#endif
| 28.408284 | 120 | 0.65528 | vrushank-agrawal |
2e381dee7d809dea721d1c0484c45caa8d3a8bf9 | 4,681 | cpp | C++ | src/plugin.cpp | hhornbacher/mosquitto-auth-plugin | a44586940bd6c7aca9f00b7b4996e3405bef50aa | [
"MIT"
] | 2 | 2020-06-18T13:21:31.000Z | 2021-04-20T23:29:31.000Z | src/plugin.cpp | hhornbacher/mosquitto-auth-plugin | a44586940bd6c7aca9f00b7b4996e3405bef50aa | [
"MIT"
] | null | null | null | src/plugin.cpp | hhornbacher/mosquitto-auth-plugin | a44586940bd6c7aca9f00b7b4996e3405bef50aa | [
"MIT"
] | null | null | null | #include "plugin.h"
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <libscrypt.h>
#include <mosquitto.h>
extern "C"
{
#include <mosquitto_broker.h>
}
int MosquittoAuthPlugin::security_init(const PluginOptions opts, const bool reload)
{
mosquitto_log_printf(MOSQ_LOG_DEBUG, "security_init");
mosquitto_log_printf(MOSQ_LOG_DEBUG, " Options:");
for (auto opt : opts)
{
mosquitto_log_printf(MOSQ_LOG_DEBUG, " %s=%s", opt.first.c_str(), opt.second.c_str());
}
mosquitto_log_printf(MOSQ_LOG_DEBUG, " Reload: %d", reload);
if (!m_repo->init(opts))
{
return MOSQ_ERR_NOT_SUPPORTED;
}
return MOSQ_ERR_SUCCESS;
}
int MosquittoAuthPlugin::security_cleanup(const PluginOptions opts, const bool reload)
{
mosquitto_log_printf(MOSQ_LOG_DEBUG, "security_cleanup");
mosquitto_log_printf(MOSQ_LOG_DEBUG, " Options:");
for (auto opt : opts)
{
mosquitto_log_printf(MOSQ_LOG_DEBUG, " %s=%s", opt.first.c_str(), opt.second.c_str());
}
mosquitto_log_printf(MOSQ_LOG_DEBUG, " Reload: %d", reload);
m_repo->cleanup();
return MOSQ_ERR_SUCCESS;
}
int MosquittoAuthPlugin::acl_check(int access, mosquitto *client, const mosquitto_acl_msg *msg)
{
const char *username = mosquitto_client_username(client);
mosquitto_log_printf(MOSQ_LOG_DEBUG, "acl_check");
if (username == NULL)
{
mosquitto_log_printf(MOSQ_LOG_WARNING, "ACL failed for empty username!");
return MOSQ_ERR_ACL_DENIED;
}
mosquitto_log_printf(MOSQ_LOG_DEBUG, " Access: %d", access);
mosquitto_log_printf(MOSQ_LOG_DEBUG, " Address: %s", mosquitto_client_address(client));
mosquitto_log_printf(MOSQ_LOG_DEBUG, " ID: %s", mosquitto_client_id(client));
mosquitto_log_printf(MOSQ_LOG_DEBUG, " Username: %s", username);
mosquitto_log_printf(MOSQ_LOG_DEBUG, " Topic: %s", msg->topic);
User user;
if (m_repo->get_user(username, user))
{
std::vector<AclRule> rules;
m_repo->get_acl_rules(rules);
for (auto rule : rules)
{
std::string topic = rule.topic;
if (topic.find("{client_id}") != std::string::npos)
{
std::string key("{client_id}");
topic = rule.topic.replace(rule.topic.find(key),
key.length(), mosquitto_client_id(client));
}
mosquitto_log_printf(MOSQ_LOG_DEBUG, " Rule Topic: %s", topic.c_str());
mosquitto_log_printf(MOSQ_LOG_DEBUG, " Rule Access: %d", rule.access);
if (msg->topic == topic)
{
if (
(access == MOSQ_ACL_SUBSCRIBE && rule.access & AclAccess::Subscribe) ||
(access == MOSQ_ACL_READ && rule.access & AclAccess::Read) ||
(access == MOSQ_ACL_WRITE && rule.access & AclAccess::Write))
{
if (std::find(user.groups.begin(), user.groups.end(), rule.group) != user.groups.end())
{
mosquitto_log_printf(MOSQ_LOG_DEBUG, "ACL success for user: %s", user.name.c_str());
return MOSQ_ERR_SUCCESS;
}
mosquitto_log_printf(MOSQ_LOG_WARNING, "ACL failed for user: %s G", user.name.c_str());
return MOSQ_ERR_ACL_DENIED;
}
}
}
mosquitto_log_printf(MOSQ_LOG_WARNING, "ACL failed for user: %s R", user.name.c_str());
return MOSQ_ERR_ACL_DENIED;
}
mosquitto_log_printf(MOSQ_LOG_WARNING, "ACL Unknown user: %s", username);
return MOSQ_ERR_ACL_DENIED;
}
int MosquittoAuthPlugin::unpwd_check(mosquitto *client, const char *username, const char *password)
{
mosquitto_log_printf(MOSQ_LOG_DEBUG, "unpwd_check");
mosquitto_log_printf(MOSQ_LOG_DEBUG, " Address: %s", mosquitto_client_address(client));
mosquitto_log_printf(MOSQ_LOG_DEBUG, " ID: %s", mosquitto_client_id(client));
mosquitto_log_printf(MOSQ_LOG_DEBUG, " Username: %s", username);
mosquitto_log_printf(MOSQ_LOG_DEBUG, " Password: %s", password);
User user;
if (m_repo->get_user(username, user))
{
if (libscrypt_check(&user.password_hash[0], password))
{
mosquitto_log_printf(MOSQ_LOG_DEBUG, "User authorized: %s", user.name.c_str());
return MOSQ_ERR_SUCCESS;
}
mosquitto_log_printf(MOSQ_LOG_WARNING, "User NOT authorized: %s", user.name.c_str());
return MOSQ_ERR_AUTH;
}
mosquitto_log_printf(MOSQ_LOG_WARNING, "Unknown user: %s", username);
return MOSQ_ERR_AUTH;
}
| 37.448 | 108 | 0.631916 | hhornbacher |
aa319d3f4cf5178e057bf66cd2dc7b73c6bb81a7 | 14,240 | cxx | C++ | EVGEN/AliGenSlowNucleons.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | null | null | null | EVGEN/AliGenSlowNucleons.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 2 | 2016-11-25T08:40:56.000Z | 2019-10-11T12:29:29.000Z | EVGEN/AliGenSlowNucleons.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | null | null | null | /**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
//
// Generator for slow nucleons in pA interactions.
// Source is modelled by a relativistic Maxwell distributions.
// This class cooparates with AliCollisionGeometry if used inside AliGenCocktail.
// In this case the number of slow nucleons is determined from the number of wounded nuclei
// using a realisation of AliSlowNucleonModel.
// Original code by Ferenc Sikler <sikler@rmki.kfki.hu>
//
#include <TDatabasePDG.h>
#include <TPDGCode.h>
#include <TH2F.h>
#include <TH1F.h>
#include <TF1.h>
#include <TCanvas.h>
#include <TParticle.h>
#include "AliConst.h"
#include "AliCollisionGeometry.h"
#include "AliStack.h"
#include "AliRun.h"
#include "AliMC.h"
#include "AliGenSlowNucleons.h"
#include "AliSlowNucleonModel.h"
ClassImp(AliGenSlowNucleons)
AliGenSlowNucleons::AliGenSlowNucleons()
:AliGenerator(-1),
fCMS(0.),
fMomentum(0.),
fBeta(0.),
fPmax (0.),
fCharge(0),
fProtonDirection(1.),
fTemperatureG(0.),
fBetaSourceG(0.),
fTemperatureB(0.),
fBetaSourceB(0.),
fNgp(0),
fNgn(0),
fNbp(0),
fNbn(0),
fDebug(0),
fDebugHist1(0),
fDebugHist2(0),
fThetaDistribution(),
fCosThetaGrayHist(),
fCosTheta(),
fBeamCrossingAngle(0.),
fBeamDivergence(0.),
fBeamDivEvent(0.),
fSmearMode(2),
fSlowNucleonModel(0)
{
// Default constructor
fCollisionGeometry = 0;
}
AliGenSlowNucleons::AliGenSlowNucleons(Int_t npart)
:AliGenerator(npart),
fCMS(14000.),
fMomentum(0.),
fBeta(0.),
fPmax (10.),
fCharge(1),
fProtonDirection(1.),
fTemperatureG(0.05),
fBetaSourceG(0.05),
fTemperatureB(0.005),
fBetaSourceB(0.),
fNgp(0),
fNgn(0),
fNbp(0),
fNbn(0),
fDebug(0),
fDebugHist1(0),
fDebugHist2(0),
fThetaDistribution(),
fCosThetaGrayHist(),
fCosTheta(),
fBeamCrossingAngle(0.),
fBeamDivergence(0.),
fBeamDivEvent(0.),
fSmearMode(2),
fSlowNucleonModel(new AliSlowNucleonModel())
{
// Constructor
fName = "SlowNucleons";
fTitle = "Generator for gray particles in pA collisions";
fCollisionGeometry = 0;
}
//____________________________________________________________
AliGenSlowNucleons::~AliGenSlowNucleons()
{
// Destructor
delete fSlowNucleonModel;
}
void AliGenSlowNucleons::SetProtonDirection(Float_t dir) {
// Set direction of the proton to change between pA (1) and Ap (-1)
fProtonDirection = dir / TMath::Abs(dir);
}
void AliGenSlowNucleons::Init()
{
//
// Initialization
//
Double_t kMass = TDatabasePDG::Instance()->GetParticle(kProton)->Mass();
fMomentum = fCMS/2. * Float_t(fZTarget) / Float_t(fATarget);
fBeta = fMomentum / TMath::Sqrt(kMass * kMass + fMomentum * fMomentum);
//printf(" fMomentum %f fBeta %1.10f\n",fMomentum, fBeta);
if (fDebug) {
fDebugHist1 = new TH2F("DebugHist1", "nu vs N_slow", 100, 0., 100., 20, 0., 20.);
fDebugHist2 = new TH2F("DebugHist2", "b vs N_slow", 100, 0., 100., 15, 0., 15.);
fCosThetaGrayHist = new TH1F("fCosThetaGrayHist", "Gray particles angle", 100, -1., 1.);
}
//
// non-uniform cos(theta) distribution
//
if(fThetaDistribution != 0) {
fCosTheta = new TF1("fCosTheta",
"(2./3.14159265358979312)/(exp(2./3.14159265358979312)-exp(-2./3.14159265358979312))*exp(2.*x/3.14159265358979312)",
-1., 1.);
}
printf("\n AliGenSlowNucleons: applying crossing angle %f mrad to slow nucleons\n",fBeamCrossingAngle*1000.);
}
void AliGenSlowNucleons::FinishRun()
{
// End of run action
// Show histogram for debugging if requested.
if (fDebug) {
TCanvas *c = new TCanvas("c","Canvas 1",400,10,600,700);
c->Divide(2,1);
c->cd(1);
fDebugHist1->Draw("colz");
c->cd(2);
fDebugHist2->Draw();
c->cd(3);
fCosThetaGrayHist->Draw();
}
}
void AliGenSlowNucleons::Generate()
{
//
// Generate one event
//
//
// Communication with Gray Particle Model
//
if (fCollisionGeometry) {
Float_t b = fCollisionGeometry->ImpactParameter();
// Int_t nn = fCollisionGeometry->NN();
// Int_t nwn = fCollisionGeometry->NwN();
// Int_t nnw = fCollisionGeometry->NNw();
// Int_t nwnw = fCollisionGeometry->NwNw();
// (1) Sikler' model
if(fSmearMode==0) fSlowNucleonModel->GetNumberOfSlowNucleons(fCollisionGeometry, fNgp, fNgn, fNbp, fNbn);
// (2) Model inspired on exp. data at lower energy (Gallio-Oppedisano)
// --- smearing the Ncoll fron generator used as input
else if(fSmearMode==1) fSlowNucleonModel->GetNumberOfSlowNucleons2(fCollisionGeometry, fNgp, fNgn, fNbp, fNbn);
// --- smearing directly Nslow
else if(fSmearMode==2) fSlowNucleonModel->GetNumberOfSlowNucleons2s(fCollisionGeometry, fNgp, fNgn, fNbp, fNbn);
if (fDebug) {
//printf("Collision Geometry %f %d %d %d %d\n", b, nn, nwn, nnw, nwnw);
printf("Slow nucleons: %d grayp %d grayn %d blackp %d blackn \n", fNgp, fNgn, fNbp, fNbn);
fDebugHist1->Fill(Float_t(fNgp + fNgn + fNbp + fNbn), fCollisionGeometry->NNw(), 1.);
fDebugHist2->Fill(Float_t(fNgp + fNgn + fNbp + fNbn), b, 1.);
}
}
//
Float_t p[3] = {0., 0., 0.}, theta=0;
Float_t origin[3] = {0., 0., 0.};
Float_t time = 0.;
Float_t polar [3] = {0., 0., 0.};
Int_t nt, i, j;
Int_t kf;
// Extracting 1 value per event for the divergence angle
Double_t rvec = gRandom->Gaus(0.0, 1.0);
fBeamDivEvent = fBeamDivergence * TMath::Abs(rvec);
printf("\n AliGenSlowNucleons: applying beam divergence %f mrad to slow nucleons\n",fBeamDivEvent*1000.);
if(fVertexSmear == kPerEvent) {
Vertex();
for (j=0; j < 3; j++) origin[j] = fVertex[j];
time = fTime;
} // if kPerEvent
//
// Gray protons
//
fCharge = 1;
kf = kProton;
for(i = 0; i < fNgp; i++) {
GenerateSlow(fCharge, fTemperatureG, fBetaSourceG, p, theta);
if (fDebug) fCosThetaGrayHist->Fill(TMath::Cos(theta));
PushTrack(fTrackIt, -1, kf, p, origin, polar,
time, kPNoProcess, nt, 1.,-2);
KeepTrack(nt);
SetProcessID(nt,kGrayProcess);
}
//
// Gray neutrons
//
fCharge = 0;
kf = kNeutron;
for(i = 0; i < fNgn; i++) {
GenerateSlow(fCharge, fTemperatureG, fBetaSourceG, p, theta);
if (fDebug) fCosThetaGrayHist->Fill(TMath::Cos(theta));
PushTrack(fTrackIt, -1, kf, p, origin, polar,
time, kPNoProcess, nt, 1.,-2);
KeepTrack(nt);
SetProcessID(nt,kGrayProcess);
}
//
// Black protons
//
fCharge = 1;
kf = kProton;
for(i = 0; i < fNbp; i++) {
GenerateSlow(fCharge, fTemperatureB, fBetaSourceB, p, theta);
PushTrack(fTrackIt, -1, kf, p, origin, polar,
time, kPNoProcess, nt, 1.,-1);
KeepTrack(nt);
SetProcessID(nt,kBlackProcess);
}
//
// Black neutrons
//
fCharge = 0;
kf = kNeutron;
for(i = 0; i < fNbn; i++) {
GenerateSlow(fCharge, fTemperatureB, fBetaSourceB, p, theta);
PushTrack(fTrackIt, -1, kf, p, origin, polar,
time, kPNoProcess, nt, 1.,-1);
KeepTrack(nt);
SetProcessID(nt,kBlackProcess);
}
}
void AliGenSlowNucleons::GenerateSlow(Int_t charge, Double_t T,
Double_t beta, Float_t* q, Float_t &theta)
{
/*
Emit a slow nucleon with "temperature" T [GeV],
from a source moving with velocity beta
Three-momentum [GeV/c] is given back in q[3]
*/
//printf("Generating slow nuc. with: charge %d. temp. %1.4f, beta %f \n",charge,T,beta);
Double_t m, pmax, p, f, phi;
TDatabasePDG * pdg = TDatabasePDG::Instance();
const Double_t kMassProton = pdg->GetParticle(kProton) ->Mass();
const Double_t kMassNeutron = pdg->GetParticle(kNeutron)->Mass();
/* Select nucleon type */
if(charge == 0) m = kMassNeutron;
else m = kMassProton;
/* Momentum at maximum of Maxwell-distribution */
pmax = TMath::Sqrt(2*T*(T+TMath::Sqrt(T*T+m*m)));
/* Try until proper momentum */
/* for lack of primitive function of the Maxwell-distribution */
/* a brute force trial-accept loop, normalized at pmax */
do
{
p = Rndm() * fPmax;
f = Maxwell(m, p, T) / Maxwell(m , pmax, T);
}
while(f < Rndm());
/* Spherical symmetric emission for black particles (beta=0)*/
if(beta==0 || fThetaDistribution==0) theta = TMath::ACos(2. * Rndm() - 1.);
/* cos theta distributed according to experimental results for gray particles (beta=0.05)*/
else if(fThetaDistribution!=0){
Double_t costheta = fCosTheta->GetRandom();
theta = TMath::ACos(costheta);
}
//
phi = 2. * TMath::Pi() * Rndm();
/* Determine momentum components in system of the moving source */
q[0] = p * TMath::Sin(theta) * TMath::Cos(phi);
q[1] = p * TMath::Sin(theta) * TMath::Sin(phi);
q[2] = p * TMath::Cos(theta);
//if(fDebug==1) printf("\n Momentum in RS of the moving source: p = (%f, %f, %f)\n",q[0],q[1],q[2]);
/* Transform to system of the target nucleus */
/* beta is passed as negative, because the gray nucleons are slowed down */
Lorentz(m, -beta, q);
//if(fDebug==1) printf(" Momentum in RS of the target nucleus: p = (%f, %f, %f)\n",q[0],q[1],q[2]);
/* Transform to laboratory system */
Lorentz(m, fBeta, q);
q[2] *= fProtonDirection;
if(fDebug==1)printf("\n Momentum after LHC boost: p = (%f, %f, %f)\n",q[0],q[1],q[2]);
if(fBeamCrossingAngle>0.) BeamCrossDivergence(1, q); // applying crossing angle
if(fBeamDivergence>0.) BeamCrossDivergence(2, q); // applying divergence
}
Double_t AliGenSlowNucleons::Maxwell(Double_t m, Double_t p, Double_t T)
{
/* Relativistic Maxwell-distribution */
Double_t ekin;
ekin = TMath::Sqrt(p*p+m*m)-m;
return (p*p * exp(-ekin/T));
}
//_____________________________________________________________________________
void AliGenSlowNucleons::Lorentz(Double_t m, Double_t beta, Float_t* q)
{
/* Lorentz transform in the direction of q[2] */
Double_t gamma = 1./TMath::Sqrt((1.-beta)*(1.+beta));
Double_t energy = TMath::Sqrt(m*m + q[0]*q[0] + q[1]*q[1] + q[2]*q[2]);
q[2] = gamma * (q[2] + beta*energy);
//printf(" \t beta %1.10f gamma %f energy %f -> p_z = %f\n",beta, gamma, energy,q[2]);
}
//_____________________________________________________________________________
void AliGenSlowNucleons::BeamCrossDivergence(Int_t iwhat, Float_t *pLab)
{
// Applying beam divergence and crossing angle
//
Double_t pmod = TMath::Sqrt(pLab[0]*pLab[0]+pLab[1]*pLab[1]+pLab[2]*pLab[2]);
Double_t tetdiv = 0.;
Double_t fidiv = 0.;
if(iwhat==1){
tetdiv = fBeamCrossingAngle;
fidiv = k2PI/4.;
}
else if(iwhat==2){
tetdiv = fBeamDivEvent;
fidiv = (gRandom->Rndm())*k2PI;
}
Double_t tetpart = TMath::ATan2(TMath::Sqrt(pLab[0]*pLab[0]+pLab[1]*pLab[1]), pLab[2]);
Double_t fipart=0.;
if(TMath::Abs(pLab[1])>0. || TMath::Abs(pLab[0])>0.) fipart = TMath::ATan2(pLab[1], pLab[0]);
if(fipart<0.) {fipart = fipart+k2PI;}
tetdiv = tetdiv*kRaddeg;
fidiv = fidiv*kRaddeg;
tetpart = tetpart*kRaddeg;
fipart = fipart*kRaddeg;
Double_t angleSum[2]={0., 0.};
AddAngle(tetpart,fipart,tetdiv,fidiv,angleSum);
Double_t tetsum = angleSum[0];
Double_t fisum = angleSum[1];
//printf("tetpart %f fipart %f tetdiv %f fidiv %f angleSum %f %f\n",tetpart,fipart,tetdiv,fidiv,angleSum[0],angleSum[1]);
tetsum = tetsum*kDegrad;
fisum = fisum*kDegrad;
pLab[0] = pmod*TMath::Sin(tetsum)*TMath::Cos(fisum);
pLab[1] = pmod*TMath::Sin(tetsum)*TMath::Sin(fisum);
pLab[2] = pmod*TMath::Cos(tetsum);
if(fDebug==1){
if(iwhat==1) printf(" Beam crossing angle %f mrad ", fBeamCrossingAngle*1000.);
else if(iwhat==2) printf(" Beam divergence %f mrad ", fBeamDivEvent*1000.);
printf(" p = (%f, %f, %f)\n",pLab[0],pLab[1],pLab[2]);
}
}
//_____________________________________________________________________________
void AliGenSlowNucleons::AddAngle(Double_t theta1, Double_t phi1,
Double_t theta2, Double_t phi2, Double_t *angleSum)
{
// Calculating the sum of 2 angles
Double_t temp = -1.;
Double_t conv = 180./TMath::ACos(temp);
Double_t ct1 = TMath::Cos(theta1/conv);
Double_t st1 = TMath::Sin(theta1/conv);
Double_t cp1 = TMath::Cos(phi1/conv);
Double_t sp1 = TMath::Sin(phi1/conv);
Double_t ct2 = TMath::Cos(theta2/conv);
Double_t st2 = TMath::Sin(theta2/conv);
Double_t cp2 = TMath::Cos(phi2/conv);
Double_t sp2 = TMath::Sin(phi2/conv);
Double_t cx = ct1*cp1*st2*cp2+st1*cp1*ct2-sp1*st2*sp2;
Double_t cy = ct1*sp1*st2*cp2+st1*sp1*ct2+cp1*st2*sp2;
Double_t cz = ct1*ct2-st1*st2*cp2;
Double_t rtetsum = TMath::ACos(cz);
Double_t tetsum = conv*rtetsum;
if(TMath::Abs(tetsum)<1e-4 || tetsum==180.) return;
temp = cx/TMath::Sin(rtetsum);
if(temp>1.) temp=1.;
if(temp<-1.) temp=-1.;
Double_t fisum = conv*TMath::ACos(temp);
if(cy<0) {fisum = 360.-fisum;}
angleSum[0] = tetsum;
angleSum[1] = fisum;
}
//_____________________________________________________________________________
void AliGenSlowNucleons::SetProcessID(Int_t nt, UInt_t process)
{
// Tag the particle as
// gray or black
if (fStack)
fStack->Particle(nt)->SetUniqueID(process);
else
gAlice->GetMCApp()->Particle(nt)->SetUniqueID(process);
}
| 31.574279 | 123 | 0.63743 | AllaMaevskaya |
aa32fa4dedb60252d53d59c2ba0403520506e623 | 943 | cpp | C++ | Rumble3D/src/RigidBodyEngine/CollisionPrimitive.cpp | Nelaty/Rumble3D | 801b9feec27ceeea91db3b759083f6351634e062 | [
"MIT"
] | 1 | 2020-01-21T16:01:53.000Z | 2020-01-21T16:01:53.000Z | Rumble3D/src/RigidBodyEngine/CollisionPrimitive.cpp | Nelaty/Rumble3D | 801b9feec27ceeea91db3b759083f6351634e062 | [
"MIT"
] | 1 | 2019-10-08T08:25:33.000Z | 2019-10-09T06:39:06.000Z | Rumble3D/src/RigidBodyEngine/CollisionPrimitive.cpp | Nelaty/Rumble3D | 801b9feec27ceeea91db3b759083f6351634e062 | [
"MIT"
] | 1 | 2019-05-14T13:48:16.000Z | 2019-05-14T13:48:16.000Z | #include "R3D/RigidBodyEngine/CollisionPrimitive.h"
#include "R3D/RigidBodyEngine/RigidBody.h"
#include <glm/gtc/matrix_transform.inl>
#include <cassert>
namespace r3
{
void CollisionPrimitive::calculateInternals()
{
/// \todo use new transform!
const auto& transform = m_body->getTransform();
glm::mat4 mat = glm::mat4(transform.getRotationMat());
mat[3] = glm::vec4(transform.getPosition(), 1.0f);
m_transform = mat * m_offset;
}
glm::vec3 CollisionPrimitive::getAxis(const unsigned index) const
{
assert(index >= 0 && index <= 3);
return glm::vec3(m_transform[index]);
}
const glm::mat4& CollisionPrimitive::getTransform() const
{
return m_transform;
}
RigidBody* CollisionPrimitive::getBody() const
{
return m_body;
}
CollisionPrimitiveType CollisionPrimitive::getType() const
{
return m_type;
}
CollisionPrimitive::CollisionPrimitive(const CollisionPrimitiveType type)
: m_type(type)
{
}
}
| 20.955556 | 74 | 0.726405 | Nelaty |
aa35435cd6a2f238f8a01e085362ad10faba87c4 | 5,938 | hpp | C++ | src/src/StateBase.hpp | Max-Mobility/PushTracker | fd1c8fc29b3bf3739ee96f07ac38413ce7947d4b | [
"MIT"
] | null | null | null | src/src/StateBase.hpp | Max-Mobility/PushTracker | fd1c8fc29b3bf3739ee96f07ac38413ce7947d4b | [
"MIT"
] | null | null | null | src/src/StateBase.hpp | Max-Mobility/PushTracker | fd1c8fc29b3bf3739ee96f07ac38413ce7947d4b | [
"MIT"
] | null | null | null | #ifndef __STATE_BASE__INCLUDE_GUARD
#define __STATE_BASE__INCLUDE_GUARD
namespace StateMachine {
class Event;
/**
* States contain other states and can consume generic
* StateMachine::Event objects if they have internal or external
* transitions on those events and if those transitions' guards are
* satisfied. Only one transition can consume an event in a given
* state machine.
*
* There is also a different kind of Event, the tick event, which is
* not consumed, but instead executes from the top-level state all
* the way to the curently active leaf state.
*
* Entry and Exit actions also occur whenever a state is entered or
* exited, respectively.
*/
class StateBase {
public:
StateBase ( void ) : _parentState( 0 ), _activeState( this ) {}
StateBase ( StateBase* _parent ) : _parentState( _parent ), _activeState( this ) {}
~StateBase( void ) {}
/**
* @brief Will be generated to call entry() then handle any child
* initialization. Finally calls makeActive on the leaf.
*/
virtual void initialize ( void ) { };
/**
* @brief Will be generated to run the entry() function defined in
* the model.
*/
virtual void entry ( void ) { };
/**
* @brief Will be generated to run the exit() function defined in
* the model.
*/
virtual void exit ( void ) { };
/**
* @brief Will be generated to run the tick() function defined in
* the model and then call _activeState->tick().
*/
virtual void tick ( void ) {
if ( _activeState != this && _activeState != 0 )
_activeState->tick();
};
/**
*/
virtual double getTimerPeriod ( void ) {
return 0;
}
/**
* @brief Calls _activeState->handleEvent( event ), then if the
* event is not 0 (meaning the event was not consumed by
* the child subtree), it checks the event against all internal
* transitions associated with that Event. If the event is still
* not a 0 (meaning the event was not consumed by the
* internal transitions), then it checks the event against all
* external transitions associated with that Event.
*
* @param[in] StateMachine::Event* Event needing to be handled
*
* @return true if event is consumed, falsed otherwise
*/
virtual bool handleEvent ( StateMachine::Event* event ) { return false; }
/**
* @brief Will be known from the model so will be generated in
* derived classes to immediately return the correct initial
* state pointer for quickly transitioning to the proper state
* during external transition handling.
*
* @return StateBase* Pointer to initial substate
*/
virtual StateMachine::StateBase* getInitial ( void ) { return this; };
/**
* @brief Recurses down to the leaf state and calls the exit
* actions as it unwinds.
*/
void exitChildren ( void ) {
if (_activeState != 0 && _activeState != this) {
_activeState->exitChildren();
_activeState->exit();
}
}
/**
* @brief Will return _activeState if it exists, otherwise will
* return 0.
*
* @return StateBase* Pointer to last active substate
*/
StateMachine::StateBase* getActiveChild ( void ) {
return _activeState;
}
/**
* @brief Will return the active leaf state, otherwise will return
* 0.
*
* @return StateBase* Pointer to last active leaf state.
*/
StateMachine::StateBase* getActiveLeaf ( void ) {
if (_activeState != 0 && _activeState != this)
return _activeState->getActiveLeaf();
else
return this;
}
/**
* @brief Make this state the active substate of its parent and
* then recurse up through the tree to the root.
*
* *Should only be called on leaf nodes!*
*/
void makeActive ( void ) {
if (_parentState != 0) {
_parentState->setActiveChild( this );
_parentState->makeActive();
}
}
/**
* @brief Update the active child state.
*/
void setActiveChild ( StateMachine::StateBase* childState ) {
_activeState = childState;
}
/**
* @brief Sets the currentlyActive state to the last active state
* and re-initializes them.
*/
void setShallowHistory ( void ) {
if (_activeState != 0 && _activeState != this) {
_activeState->entry();
_activeState->initialize();
}
else {
initialize();
}
}
/**
* @brief Go to the last active leaf of this state. If none
* exists, re-initialize.
*/
void setDeepHistory ( void ) {
if (_activeState != 0 && _activeState != this) {
_activeState->entry();
_activeState->setDeepHistory();
}
else {
initialize();
}
}
/**
* @brief Will set the parent state.
*/
void setParentState ( StateMachine::StateBase* parent ) {
_parentState = parent;
}
/**
* @brief Will return the parent state.
*/
StateMachine::StateBase* getParentState ( void ) {
return _parentState;
}
protected:
/**
* Pointer to the currently or most recently active substate of
* this state.
*/
StateMachine::StateBase *_activeState;
/**
* Pointer to the parent state of this state.
*/
StateMachine::StateBase *_parentState;
};
};
#endif // __STATE_BASE__INCLUDE_GUARD
| 29.839196 | 98 | 0.572078 | Max-Mobility |
aa37654983151cb040081ee3a660a55f0b2e958f | 1,836 | hpp | C++ | MyApplication/Middlewares/ST/touchgfx/framework/include/touchgfx/hal/GPIO.hpp | rshane960/TouchGFX | 1f1465f1aa1215d52264ae0199dafa821939de64 | [
"MIT"
] | null | null | null | MyApplication/Middlewares/ST/touchgfx/framework/include/touchgfx/hal/GPIO.hpp | rshane960/TouchGFX | 1f1465f1aa1215d52264ae0199dafa821939de64 | [
"MIT"
] | null | null | null | MyApplication/Middlewares/ST/touchgfx/framework/include/touchgfx/hal/GPIO.hpp | rshane960/TouchGFX | 1f1465f1aa1215d52264ae0199dafa821939de64 | [
"MIT"
] | null | null | null | /******************************************************************************
* Copyright (c) 2018(-2021) STMicroelectronics.
* All rights reserved.
*
* This file is part of the TouchGFX 4.18.1 distribution.
*
* This software is licensed under terms that can be found in the LICENSE file in
* the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
*******************************************************************************/
/**
* @file touchgfx/hal/GPIO.hpp
*
* Declares the touchgfx::GPIO class.
*/
#ifndef TOUCHGFX_GPIO_HPP
#define TOUCHGFX_GPIO_HPP
namespace touchgfx
{
/**
* Interface class for manipulating GPIOs in order to do performance measurements on target. Not
* used on the PC simulator.
*/
class GPIO
{
public:
/** Enum for the GPIOs used. */
enum GPIO_ID
{
VSYNC_FREQ, /// Pin is toggled at each VSYNC
RENDER_TIME, /// Pin is high when frame rendering begins, low when finished
FRAME_RATE, /// Pin is toggled when the framebuffers are swapped.
MCU_ACTIVE /// Pin is high when the MCU is doing work (i.e. not in idle task).
};
/** Perform configuration of IO pins. */
static void init();
/**
* Sets a pin high.
*
* @param id the pin to set.
*/
static void set(GPIO_ID id);
/**
* Sets a pin low.
*
* @param id the pin to set.
*/
static void clear(GPIO_ID id);
/**
* Toggles a pin.
*
* @param id the pin to toggle.
*/
static void toggle(GPIO_ID id);
/**
* Gets the state of a pin.
*
* @param id the pin to get.
*
* @return true if the pin is high, false otherwise.
*/
static bool get(GPIO_ID id);
};
} // namespace touchgfx
#endif // TOUCHGFX_GPIO_HPP
| 24.157895 | 96 | 0.569172 | rshane960 |
aa3abe536e9e4f269ada3a833dc1c969697575f3 | 14,401 | cpp | C++ | Numerical-Methods/Task-9/main.cpp | Maissae/University-Projects | 86ef0583760742c0e45be33d3fac3689587d0c76 | [
"MIT"
] | null | null | null | Numerical-Methods/Task-9/main.cpp | Maissae/University-Projects | 86ef0583760742c0e45be33d3fac3689587d0c76 | [
"MIT"
] | null | null | null | Numerical-Methods/Task-9/main.cpp | Maissae/University-Projects | 86ef0583760742c0e45be33d3fac3689587d0c76 | [
"MIT"
] | null | null | null | #include<stdio.h>
#include<stdlib.h>
#include<bitset>
#include<iostream>
#include<iomanip>
#include<math.h>
#include<string.h>
#pragma region Array/Matrix Functions
double** CreateMatrix(int n)
{
double** matrix = new double* [n];
for(int i = 0; i < n; i++) {
matrix[i] = new double[n];
}
for(int i = 0; i < n; i++) {
for(int j = 0; i < n; i++) {
matrix[i][j] = 0;
}
}
return matrix;
}
double** CreateMatrix(int n, int m)
{
double** matrix = new double* [n];
for(int i = 0; i < n; i++) {
matrix[i] = new double[m];
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
matrix[i][j] = 0;
}
}
return matrix;
}
double* CreateArray(int n)
{
double* array = new double[n];
for(int i = 0; i < n; i++) {
array[i] = 0;
}
return array;
}
double** CopyMatrix(int n, double** matrix)
{
double** matrix_copy = CreateMatrix(n);
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++)
{
matrix_copy[i][j] = matrix[i][j];
}
}
return matrix_copy;
}
double* CopyArray(int n, double* array)
{
double* array_copy = CreateArray(n);
for(int i = 0; i < n; i++) {
array_copy[i] = array[i];
}
return array_copy;
}
void Dispose(int n, double** matrix)
{
for(int i = 0; i < n; i++) {
delete[] matrix[i];
}
delete[] matrix;
}
void Dispose(double* array)
{
delete[] array;
}
double** InsertMatrix(int n, std::string name = "Matrix")
{
double** matrix = CreateMatrix(n);
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
double value;
std::cout << "Put value for " << name << "[" << i << "]" << "[" << j << "]: ";
std::cin >> value;
matrix[i][j] = value;
}
}
return matrix;
}
double* InsertArray(int n, std::string name = "Array")
{
double* array = CreateArray(n);
for(int i = 0; i < n; i++) {
double value;
std::cout << "Put value for " << name << "[" << i << "]: ";
std::cin >> value;
array[i] = value;
}
return array;
}
void PrintMatrix(double** matrix, int n, int m, std::string name = "")
{
std::cout << name << ":" << std::endl;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
printf("%.4f ", matrix[i][j]);
}
printf("\n");
}
printf("\n");
}
void PrintMatrix(double* matrix, int n, std::string name = "")
{
std::cout << name << ":" << std::endl;
for(int i = 0; i < n; i++)
{
printf("%.8e\n", matrix[i]);
}
printf("\n");
}
double** Multiply(double** matrix1, double** matrix2, int n)
{
double** result = CreateMatrix(n);
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
for(int k = 0; k < n; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
return result;
}
double* Multiply(double** matrix1, double* matrix2, int n)
{
double* result = CreateArray(n);
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
for(int k = 0; k < n; k++) {
result[i] += matrix1[i][k] * matrix2[k];
}
}
}
return result;
}
double* Multiply(double** matrix1, int n, int m, double* matrix2)
{
double* result = CreateArray(n);
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
result[i] += matrix1[i][j] * matrix2[j];
}
}
return result;
}
double** Multiply(double** matrix1, int n1, int m1, double** matrix2, int n2, int m2)
{
double** result = CreateMatrix(n1, m2);
for(int i = 0; i < n1; ++i)
{
for(int j = 0; j < m2; ++j)
{
for(int k = 0; k < m1; ++k)
{
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
return result;
}
double** Multiply(double** matrix, int n, int m, double scalar)
{
double** result = CreateMatrix(n,m);
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
result[i][j] = matrix[i][j] * scalar;
}
}
return result;
}
double** Subtract(double** matrix1, double** matrix2, int n, int m)
{
double** result = CreateMatrix(n,m);
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
double value = matrix1[i][j] - matrix2[i][j];
result[i][j] = value;
}
}
return result;
}
bool Equals(double a, double b)
{
return (abs(a) - abs(b)) < __DBL_EPSILON__;
}
bool Equals(double** matrix1, double** matrix2, int n, int m)
{
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if(Equals(matrix1[i][j], matrix2[i][j]) == false) {
return false;
}
}
}
return true;
}
void Clear(double** matrix, int n, int m)
{
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
matrix[i][j] = 0;
}
}
}
void Clear(double* array, int n)
{
for(int i = 0; i < n; i++)
{
array[i] = 0;
}
}
void SwapRow(double** matrix, int row1, int row2, int n)
{
for(int i = 0; i < n; i++)
{
double temp = matrix[row1][i];
matrix[row1][i] = matrix[row2][i];
matrix[row2][i] = temp;
}
}
void SwapColumn(double** matrix, int col1, int col2, int n)
{
for(int i = 0; i < n; i++)
{
double temp = matrix[i][col1];
matrix[i][col1] = matrix[i][col2];
matrix[i][col2] = temp;
}
}
#pragma endregion
#pragma region Array/Matrix Math Functions
double** Transpose(double** matrix, int n)
{
double** result = CreateMatrix(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
result[i][j] = matrix[j][i];
}
}
return result;
}
double** Transpose(double** matrix, int n, int m)
{
double** result = CreateMatrix(m, n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
result[j][i] = matrix[i][j];
}
}
return result;
}
void DooLittleDecomposition(int n, double** A, double** L, double** U, double** P)
{
//Doolittle
for(int k = 0; k < n; k++) {
//Rows for U
for(int j = k; j < n; j++) {
double sum = 0;
for(int p = 0; p < k; p++) {
sum += L[k][p] * U[p][j];
}
U[k][j] = A[k][j] - sum;
}
//Search for max Ukj
double ukj_max = 0;
int j_max = 0;
for(int j = k; j < n; j++) {
if(abs(U[k][j]) > abs(ukj_max)) {
ukj_max = U[k][j];
j_max = j;
}
}
if(k != j_max)
{
//Swapping columns
SwapColumn(A, k, j_max, n);
SwapColumn(U, k, j_max, n);
SwapColumn(P, k, j_max, n);
}
//Columns for L
for(int i = k; i < n; i++) {
if(k != i) {
double sum = 0;
for(int p = 0; p < k; p++) {
sum += L[i][p] * U[p][k];
}
L[i][k] = (A[i][k] - sum) / U[k][k];
}
}
}
}
void SolveLinearEquation(int n, double** L, double** U, double** P, double* B, double* y, double* x, double* x_prim)
{
//Forward substitution
for(int i = 0; i < n; i++)
{
double sum = 0;
for(int j = 0; j < i; j++)
{
sum += L[i][j]*y[j];
}
y[i] = (B[i] - sum)/L[i][i];
}
//Back substitution
for(int i = n - 1; i >= 0; i--)
{
double sum = 0;
for(int j = i + 1; j < n; j++)
{
sum += U[i][j]*x_prim[j];
}
x_prim[i] = (y[i] - sum)/U[i][i];
}
//Matrix multiplication for final x
for(int i = 0; i < n; i++)
{
double sum = 0;
for(int j = 0; j < n; j++)
{
sum += P[i][j] * x_prim[j];
}
x[i] = sum;
}
}
double FindMax(int n, double* array)
{
double max = -__DBL_MAX__;
for(int i = 0; i < n; i++) {
if(max < array[i]) {
max = array[i];
}
}
return max;
}
void ScaleMatrix(int n, double** A, double* B)
{
for(int i = 0; i < n; i++)
{
double max = FindMax(n, A[i]);
for(int j = 0; j < n; j++)
{
A[i][j] /= max;
}
B[i] /= max;
}
}
double** InverseL(int n, double** L)
{
double** L_inv = CreateMatrix(n);
for(int k = 0; k < n; k++)
{
double* e = CreateArray(n);
double* y = CreateArray(n);
e[k] = 1;
//Forward substitution
for(int i = 0; i < n; i++)
{
double sum = 0;
for(int j = 0; j < i; j++)
{
sum += L[i][j]*y[j];
}
y[i] = (e[i] - sum)/L[i][i];
}
//Assigning column to L
for(int i = 0; i < n; i++)
{
L_inv[i][k] = y[i];
}
delete[] e;
delete[] y;
}
return L_inv;
}
double** InverseU(int n, double** U)
{
double** U_inv = CreateMatrix(n);
for(int k = 0; k < n; k++)
{
double* e = CreateArray(n);
double* z = CreateArray(n);
e[k] = 1;
//Back substitution
for(int i = n - 1; i >= 0; i--)
{
double sum = 0;
for(int j = i + 1; j < n; j++)
{
sum += U[i][j]*z[j];
}
z[i] = (e[i] - sum)/U[i][i];
}
//Assigning column to U
for(int i = 0; i < n; i++)
{
U_inv[i][k] = z[i];
}
delete[] e;
delete[] z;
}
return U_inv;
}
double Matrix1Form(int n, double** matrix)
{
double max = 0;
for(int i = 0; i < n; i++) {
double sum = 0;
for(int j = 0; j < n; j++) {
sum += abs(matrix[j][i]);
}
if(sum > max) {
max = sum;
}
}
return max;
}
double MatrixInfForm(int n, double** matrix)
{
double max = 0;
for(int i = 0; i < n; i++) {
double sum = 0;
for(int j = 0; j < n; j++) {
sum += abs(matrix[i][j]);
}
if(sum > max) {
max = sum;
}
}
return max;
}
double Array1Form(int n, double* array)
{
double sum = 0;
for(int i = 0; i < n; i++) {
sum += abs(array[i]);
}
return sum;
}
double ArrayInfForm(int n, double* array)
{
return FindMax(n, array);
}
double VectorLength(double** vector, int n) {
double sum = 0;
for(int i = 0; i < n; i++) {
sum += pow(vector[i][0], 2);
}
return sqrt(sum);
}
double** NormalizeVector(double** vector, int n) {
double len = VectorLength(vector, n);
double** result = CreateMatrix(n, 1);
for(int i = 0; i < n; i++) {
result[i][0] = vector[i][0] / len;
}
return result;
}
#pragma endregion
int sign(double value) {
if(value > 0) {
return 1;
} else if(value < 0) {
return -1;
} else {
return 0;
}
}
int main()
{
int n;
// std::cout << "Enter n: ";
// std::cin >> n;
//? Testing
n = 4;
double** A = CreateMatrix(n, n);
double** I = CreateMatrix(n, n);
double** lambda = CreateMatrix(n, 1);
//?Testing
A[0] = new double[4] {2, 13, -14, 3};
A[1] = new double[4] {-2, 25, -22, 4};
A[2] = new double[4] {-3, 31, -27, 5};
A[2] = new double[4] {-2, 34, -32, 7};
//A[0] = new double[3] {1,1,1};
//A[1] = new double[3] {2,-2,2};
//A[2] = new double[3] {3,3,-3};
// lambda[0] = 2.76300328661375;
// lambda[1] = -1.723685894982085;
//lambda[2] = -5.03931739163167;
lambda[0][0] = 3;
lambda[1][0] = 2;
lambda[2][0] = 1;
lambda[3][0] = 1;
for(int i = 0; i < n; i++) {
I[i][i] = 1;
}
PrintMatrix(A, n, n, "A");
PrintMatrix(I, n, n, "I");
// double** A = InsertMatrix(n, "A");
// std::cout << "Inserted matrix:" << std::endl;
PrintMatrix(lambda, n, 1, "lambda");
for(int i = 0; i < n; i++)
{
printf("============> i = %d <============\n\n", i);
//Calculating λ * I
double** I_lambda = Multiply(I, n, n, lambda[i][0]);
//Subtracting A - Iλ
double** A_lambda = Subtract(A, I_lambda, n, n);
PrintMatrix(I_lambda, n, n, "I_lambda");
PrintMatrix(A_lambda, n, n, "A_lambda");
double** L = CreateMatrix(n, n);
double** U = CreateMatrix(n, n);
double** P = CreateMatrix(n, n);
//? Setting up L and P
for(int j = 0; j < n; j++)
{
L[j][j] = 1;
P[j][j] = 1;
}
DooLittleDecomposition(n, A_lambda, L, U, P);
PrintMatrix(L, n, n, "L");
PrintMatrix(U, n, n, "U");
PrintMatrix(P, n, n, "P");
//Solving Ux'_i = 0
double** x_prim = CreateMatrix(n, 1);
//Setting last value to 1
x_prim[n-1][0] = 1;
for(int j = n - 2; j >= 0; j--)
{
double sum = 0;
for(int k = j + 1; k < n; k++)
{
sum += U[j][k]*x_prim[k][0];
}
x_prim[j][0] = (0 - sum)/U[j][j];
}
//Getting final vector
PrintMatrix(x_prim, n, 1, "x_prim_i");
//double** P_Tr = Transpose(P, n, n);
double** x = Multiply(P, n, n, x_prim, n, 1);
PrintMatrix(x, n, 1, "x_i");
//Normalization
double** x_norm = NormalizeVector(x, n);
PrintMatrix(x_norm, n, 1, "x_norm");
//A*xi
double** A_xi = Multiply(A, n, n, x, n, 1);
PrintMatrix(A_xi, n, 1, "A_xi");
//λ*xi
double** lambda_xi = Multiply(lambda, n, 1, x, n, 1);
PrintMatrix(lambda_xi, n, 1, "lambda_xi");
Dispose(n, A_lambda);
Dispose(n, I_lambda);
Dispose(n, L);
Dispose(n, U);
Dispose(n, P);
Dispose(n, x_prim);
Dispose(n, x);
Dispose(n, x_norm);
Dispose(n, A_xi);
Dispose(n, lambda_xi);
}
Dispose(n, A);
Dispose(n, lambda);
return 0;
} | 21.786687 | 116 | 0.43122 | Maissae |
aa3b80d50c5c134c9ac08e09649dfdeb2c48bf94 | 3,983 | cpp | C++ | upcxx/osu_upcxx_allgather.cpp | federatedcloud/osu-micro-benchmarks-5.6.2 | e84e54beb07e7a93156e123d337f775f44e1e642 | [
"BSD-3-Clause"
] | null | null | null | upcxx/osu_upcxx_allgather.cpp | federatedcloud/osu-micro-benchmarks-5.6.2 | e84e54beb07e7a93156e123d337f775f44e1e642 | [
"BSD-3-Clause"
] | null | null | null | upcxx/osu_upcxx_allgather.cpp | federatedcloud/osu-micro-benchmarks-5.6.2 | e84e54beb07e7a93156e123d337f775f44e1e642 | [
"BSD-3-Clause"
] | null | null | null | #define BENCHMARK "OSU UPC++ AllGather Latency Test"
/*
* Copyright (C) 2002-2019 the Network-Based Computing Laboratory
* (NBCL), The Ohio State University.
*
* Contact: Dr. D. K. Panda (panda@cse.ohio-state.edu)
*
* For detailed copyright and licensing information, please refer to the
* copyright file COPYRIGHT in the top level OMB directory.
*/
#include <upcxx.h>
#include <osu_util_pgas.h>
#define root 0
#define VERIFY 0
using namespace std;
using namespace upcxx;
int
main (int argc, char **argv)
{
init(&argc, &argv);
global_ptr<char> src;
global_ptr<char> dst;
global_ptr<double> time_src;
global_ptr<double> time_dst;
double avg_time, max_time, min_time;
int i = 0, size = 1, po_ret, iterations;
int skip;
double t_start = 0, t_stop = 0, timer=0;
int max_msg_size = 1<<20, full = 0;
options.bench = UPCXX;
po_ret = process_options(argc, argv);
full = options.show_full;
skip = options.skip_large;
iterations = options.iterations;
max_msg_size = options.max_message_size;
options.show_size = 1;
switch (po_ret) {
case PO_BAD_USAGE:
print_usage_pgas(MYTHREAD, argv[0], size != 0);
exit(EXIT_FAILURE);
case PO_HELP_MESSAGE:
print_usage_pgas(MYTHREAD, argv[0], size != 0);
exit(EXIT_SUCCESS);
case PO_VERSION_MESSAGE:
if (MYTHREAD == 0) {
print_version_pgas(HEADER);
}
exit(EXIT_SUCCESS);
case PO_OKAY:
break;
}
if (ranks() < 2) {
if (myrank() == 0) {
fprintf(stderr, "This test requires at least two processes\n");
}
return -1;
}
src = allocate<char> (myrank(), max_msg_size*sizeof(char));
dst = allocate<char> (myrank(), max_msg_size*sizeof(char)*ranks());
assert(src != NULL);
assert(dst != NULL);
time_src = allocate<double> (myrank(), 1);
time_dst = allocate<double> (root, 1);
assert(time_src != NULL);
assert(time_dst != NULL);
/*
* put a barrier since allocate is non-blocking in upc++
*/
barrier();
print_header_pgas(HEADER, myrank(), full);
for (size=1; size <=max_msg_size; size *= 2) {
if (size > LARGE_MESSAGE_SIZE) {
skip = options.skip_large;
iterations = options.iterations_large;
} else {
skip = options.skip;
}
timer=0;
for(i=0; i < iterations + skip ; i++) {
//t_start = TIME();
t_start = getMicrosecondTimeStamp();
upcxx_allgather((char *)src, (char *)dst, size*sizeof(char));
t_stop = getMicrosecondTimeStamp();
if(i>=skip){
timer+=t_stop-t_start;
}
barrier();
}
barrier();
double* lsrc = (double *)time_src;
lsrc[0] = (1.0 * timer) / iterations;
upcxx_reduce<double>((double *)time_src, (double *)time_dst, 1, root,
UPCXX_MAX, UPCXX_DOUBLE);
if (myrank()==root) {
double* ldst = (double *)time_dst;
max_time = ldst[0];
}
upcxx_reduce<double>((double *)time_src, (double *)time_dst, 1, root,
UPCXX_MIN, UPCXX_DOUBLE);
if (myrank()==root) {
double* ldst = (double *)time_dst;
min_time = ldst[0];
}
upcxx_reduce<double>((double *)time_src, (double *)time_dst, 1, root,
UPCXX_SUM, UPCXX_DOUBLE);
if (myrank()==root) {
double* ldst = (double *)time_dst;
avg_time = ldst[0]/ranks();
}
barrier ();
print_data_pgas(myrank(), full, size*sizeof(char), avg_time, min_time,
max_time, iterations);
}
deallocate(src);
deallocate(dst);
deallocate(time_src);
deallocate(time_dst);
finalize();
return EXIT_SUCCESS;
}
/* vi: set sw=4 sts=4 tw=80: */
| 25.863636 | 78 | 0.565654 | federatedcloud |
aa3cbe74ee409970bad7d3e9e4e9d3b5241f2870 | 1,449 | cc | C++ | chromecast/media/cma/backend/mixer/mock_mixer_source.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | chromecast/media/cma/backend/mixer/mock_mixer_source.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | chromecast/media/cma/backend/mixer/mock_mixer_source.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromecast/media/cma/backend/mixer/mock_mixer_source.h"
#include <algorithm>
#include <utility>
#include "base/check_op.h"
#include "media/base/audio_bus.h"
using testing::_;
namespace chromecast {
namespace media {
MockMixerSource::MockMixerSource(int samples_per_second,
const std::string& device_id)
: samples_per_second_(samples_per_second), device_id_(device_id) {
DCHECK_GT(num_channels_, 0);
ON_CALL(*this, FillAudioPlaybackFrames(_, _, _))
.WillByDefault(testing::Invoke(this, &MockMixerSource::GetData));
}
MockMixerSource::~MockMixerSource() = default;
void MockMixerSource::SetData(std::unique_ptr<::media::AudioBus> data) {
data_ = std::move(data);
data_offset_ = 0;
}
int MockMixerSource::GetData(int num_frames,
RenderingDelay rendering_delay,
::media::AudioBus* buffer) {
CHECK(buffer);
CHECK_GE(buffer->frames(), num_frames);
if (data_) {
int frames_to_copy = std::min(num_frames, data_->frames() - data_offset_);
data_->CopyPartialFramesTo(data_offset_, frames_to_copy, 0, buffer);
data_offset_ += frames_to_copy;
return frames_to_copy;
} else {
return 0;
}
}
} // namespace media
} // namespace chromecast
| 29.571429 | 78 | 0.692202 | zealoussnow |
aa3f79f44e764074527bacd7f61e045b3ae3f03a | 565 | cpp | C++ | acmicpc/1051.cpp | juseongkr/BOJ | 8f10a2bf9a7d695455493fbe7423347a8b648416 | [
"Apache-2.0"
] | 7 | 2020-02-03T10:00:19.000Z | 2021-11-16T11:03:57.000Z | acmicpc/1051.cpp | juseongkr/Algorithm-training | 8f10a2bf9a7d695455493fbe7423347a8b648416 | [
"Apache-2.0"
] | 1 | 2021-01-03T06:58:24.000Z | 2021-01-03T06:58:24.000Z | acmicpc/1051.cpp | juseongkr/Algorithm-training | 8f10a2bf9a7d695455493fbe7423347a8b648416 | [
"Apache-2.0"
] | 1 | 2020-01-22T14:34:03.000Z | 2020-01-22T14:34:03.000Z | #include <iostream>
using namespace std;
int main()
{
int n, m, v, max_val = 1;
int s[51][51];
string str;
scanf("%d %d", &n, &m);
v = min(n, m);
for (int i=0; i<n; ++i) {
cin >> str;
for (int j=0; j<m; ++j)
s[i][j] = str[j] - '0';
}
for (int i=0; i<n; ++i) {
for (int j=0; j<m; ++j) {
for (int k=1; k<v; ++k) {
if (n <= i + k || m <= j + k)
continue;
if (s[i][j] == s[i+k][j] && s[i][j] == s[i][j+k] && s[i][j] == s[i+k][j+k])
max_val = max(max_val, (k + 1) * (k + 1));
}
}
}
printf("%d\n", max_val);
return 0;
}
| 17.121212 | 79 | 0.419469 | juseongkr |
aa3faf9aaafb9459939c59f788180810b68a1915 | 5,899 | cc | C++ | A1/Main/BufferMgr/source/MyDB_BufferManager.cc | JiweiYe/DB_implementation | 5f3b043ea2ceffa8a84ef90f1127c8b4d5a83d98 | [
"MIT"
] | null | null | null | A1/Main/BufferMgr/source/MyDB_BufferManager.cc | JiweiYe/DB_implementation | 5f3b043ea2ceffa8a84ef90f1127c8b4d5a83d98 | [
"MIT"
] | null | null | null | A1/Main/BufferMgr/source/MyDB_BufferManager.cc | JiweiYe/DB_implementation | 5f3b043ea2ceffa8a84ef90f1127c8b4d5a83d98 | [
"MIT"
] | null | null | null |
#ifndef BUFFER_MGR_C
#define BUFFER_MGR_C
#include "MyDB_BufferManager.h"
#include <string>
using namespace std;
MyDB_PageHandle MyDB_BufferManager :: getPage (MyDB_TablePtr whichTable, long i) {
string targetPage = pageIdGenerator(whichTable, i);
//page already in the buffer
if(inbuffer(targetPage)){
MyDB_PageHandle handle = make_shared<MyDB_PageHandleBase>(page_map[targetPage]);
this->LRU_table.erase(page_map[targetPage]);
this->page_map[targetPage]->setLruNumber(++currentLRU);
this->LRU_table.insert(page_map[targetPage]);
return handle;
}
//page not in the buffer
else{
shared_ptr <MyDB_Page> newPage = make_shared <MyDB_Page>(++currentLRU,false,false,whichTable,i,this->pageSize,this);
string page_id = pageIdGenerator(newPage->table, newPage->pagePos);
//buffer is not filled
if(this->LRU_table.size() < this->pageNum){
newPage-> bufferInfo = this->buffer + LRU_table.size() * this->pageSize;
newPage->loadFromFile();
}
//buffer is filled;
else{
evict(newPage);
}
this->page_map.insert(pair<string, shared_ptr<MyDB_Page>>(page_id,newPage));
this->LRU_table.insert(newPage);
MyDB_PageHandle handle = make_shared<MyDB_PageHandleBase>(newPage);
return handle;
}
}
MyDB_PageHandle MyDB_BufferManager :: getPage () {
long tmpPagePos;
if(tmp_avail.size() <= 0){
tmpPagePos = ++tmpFileCount;
}
else{
tmpPagePos = *(tmp_avail.begin());
tmp_avail.erase(tmpPagePos);
}
string page_id = pageIdGenerator(tmp_table, tmpPagePos);
shared_ptr <MyDB_Page> newPage = make_shared <MyDB_Page>(++currentLRU,false,true,this->tmp_table,tmpFileCount,this->pageSize,this);
//buffer is not filled
if(this->LRU_table.size() < this->pageNum){
newPage-> bufferInfo = this->buffer + LRU_table.size() * this->pageSize;
newPage->loadFromFile();
}
//buffer is filled;
else{
evict(newPage);
}
this->page_map.insert(pair<string, shared_ptr<MyDB_Page>>(page_id,newPage));
this->LRU_table.insert(newPage);
MyDB_PageHandle handle = make_shared<MyDB_PageHandleBase>(newPage);
return handle;
}
MyDB_PageHandle MyDB_BufferManager :: getPinnedPage (MyDB_TablePtr whichTable, long i) {
string targetPage = pageIdGenerator(whichTable, i);
//page already in the buffer
if(inbuffer(targetPage)){
MyDB_PageHandle handle = make_shared<MyDB_PageHandleBase>(page_map[targetPage]);
this->page_map[targetPage]->setPinned();
this->LRU_table.erase(page_map[targetPage]);
this->page_map[targetPage]->setLruNumber(++currentLRU);
this->LRU_table.insert(page_map[targetPage]);
return handle;
}
//page not in the buffer
else{
shared_ptr <MyDB_Page> newPage = make_shared <MyDB_Page>(++currentLRU,true,false,whichTable,i,this->pageSize,this);
string page_id = pageIdGenerator(newPage->table, newPage->pagePos);
//buffer is not filled
if(this->LRU_table.size() < this->pageNum){
newPage-> bufferInfo = this->buffer + LRU_table.size() * this->pageSize;
newPage->loadFromFile();
}
//buffer is filled;
else{
evict(newPage);
}
this->page_map.insert(pair<string, shared_ptr<MyDB_Page>>(page_id,newPage));
this->LRU_table.insert(newPage);
MyDB_PageHandle handle = make_shared<MyDB_PageHandleBase>(newPage);
return handle;
}
}
MyDB_PageHandle MyDB_BufferManager :: getPinnedPage () {
long tmpPagePos;
if(tmp_avail.size() <= 0){
tmpPagePos = ++tmpFileCount;
}
else{
tmpPagePos = *(tmp_avail.begin());
tmp_avail.erase(tmpPagePos);
}
string page_id = pageIdGenerator(tmp_table, tmpPagePos);
shared_ptr <MyDB_Page> newPage = make_shared <MyDB_Page>(++currentLRU,true,true,this->tmp_table,tmpFileCount,this->pageSize,this);
//buffer is not filled
if(this->LRU_table.size() < this->pageNum){
newPage-> bufferInfo = this->buffer + LRU_table.size() * this->pageSize;
newPage->loadFromFile();
}
//buffer is filled;
else{
evict(newPage);
}
this->page_map.insert(pair<string, shared_ptr<MyDB_Page>>(page_id,newPage));
this->LRU_table.insert(newPage);
MyDB_PageHandle handle = make_shared<MyDB_PageHandleBase>(newPage);
return handle;
}
void MyDB_BufferManager :: evict(shared_ptr <MyDB_Page> newPage){
//find the page to be evicted
LRUtable::iterator it;
for(it=LRU_table.begin();it!=LRU_table.end();it++){
if((*it)->pinned == false){
break;
}
}
//set the status inbuffer to false
(*it)->inBuffer = false;
//evict from look up map
string evict_page = pageIdGenerator((*it)->table, (*it)->pagePos);
page_map.erase(evict_page);
//write the data back to disk if dirty && change the data in the buffer
if((*it)->dirty){
(*it)->writeToFile();
(*it)->dirty = false;
}
newPage->bufferInfo = (*it)->bufferInfo;
newPage->loadFromFile();
//evict from LRU set
LRU_table.erase(*it);
}
void MyDB_BufferManager :: unpin (MyDB_PageHandle unpinMe) {
unpinMe->pageObject->pinned = false;
}
MyDB_BufferManager :: MyDB_BufferManager (size_t pageSize, size_t numPages, string tempFile) {
this->pageSize = pageSize;
this->pageNum = numPages;
this->tmpFile = tempFile;
buffer = (char*) malloc(sizeof(char)*(pageSize*numPages));
this->currentLRU = 0;
this->tmpFileCount = 0;
tmp_table = make_shared <MyDB_Table> ("temporary_table", this->tmpFile);
}
MyDB_BufferManager :: ~MyDB_BufferManager () {
LRUtable::iterator it;
for(it=LRU_table.begin();it!=LRU_table.end();it++){
if((*it)->dirty){
(*it)->writeToFile();
(*it)->dirty = false;
}
}
delete(this->buffer);
remove(tmpFile.c_str());
}
bool MyDB_BufferManager ::inbuffer(string target){
PageMap::iterator it = this->page_map.find(target);
if(it == this->page_map.end()){
return false;
}
else{
return true;
}
}
string MyDB_BufferManager :: pageIdGenerator(MyDB_TablePtr whichTable, long i){
string table_name = whichTable-> getName();
string pageId = table_name + to_string(i);
return pageId;
}
#endif
| 29.944162 | 132 | 0.712494 | JiweiYe |
aa419cee82e2fed3f4197a8f654d2e7b6184edbe | 12,044 | cpp | C++ | src/Transform/ONNX/ConstPropHelper.cpp | juan561999/Onnx-mlir | f8554660dd98b5bb911320aa4f22823573c9b0fb | [
"Apache-2.0"
] | null | null | null | src/Transform/ONNX/ConstPropHelper.cpp | juan561999/Onnx-mlir | f8554660dd98b5bb911320aa4f22823573c9b0fb | [
"Apache-2.0"
] | null | null | null | src/Transform/ONNX/ConstPropHelper.cpp | juan561999/Onnx-mlir | f8554660dd98b5bb911320aa4f22823573c9b0fb | [
"Apache-2.0"
] | null | null | null | /*
* SPDX-License-Identifier: Apache-2.0
*/
//===----------- ONNXConstProp.cpp - ONNX High Level Rewriting ------------===//
//
// Copyright 2019-2020 The IBM Research Authors.
//
// =============================================================================
//
// This file implements a set of rewriters to constprop an ONNX operation into
// composition of other ONNX operations.
//
// This pass is applied before any other pass so that there is no need to
// implement shape inference for the constpropd operation. Hence, it is expected
// that there is no knowledge about tensor shape at this point
//
//===----------------------------------------------------------------------===//
#include "src/Transform/ONNX/ConstPropHelper.hpp"
using namespace mlir;
/// Get the element size in bytes. Use the biggest size to avoid loss in
/// casting.
int64_t getEltSizeInBytes(Type ty) {
auto elementType = ty.cast<ShapedType>().getElementType();
int64_t sizeInBits;
if (elementType.isIntOrFloat()) {
sizeInBits = elementType.getIntOrFloatBitWidth();
} else {
auto vectorType = elementType.cast<VectorType>();
sizeInBits =
vectorType.getElementTypeBitWidth() * vectorType.getNumElements();
}
return llvm::divideCeil(sizeInBits, 8);
}
/// Get the number of elements.
int64_t getNumberOfElements(ArrayRef<int64_t> shape) {
int64_t count = 1;
for (unsigned int i = 0; i < shape.size(); ++i) {
count *= shape[i];
}
return count;
}
/// Get the size of a tensor from its ranked type in bytes.
int64_t getSizeInBytes(Type ty) {
ShapedType shapedType = ty.dyn_cast<ShapedType>();
auto shape = shapedType.getShape();
return getNumberOfElements(shape) * getEltSizeInBytes(shapedType);
}
/// Get the size of a tensor from its ranked type in bytes, using the largest
/// precision.
int64_t getMaxSizeInBytes(Type ty) {
auto shape = ty.dyn_cast<ShapedType>().getShape();
return getNumberOfElements(shape) * 8;
}
/// Compute strides for a given shape.
std::vector<int64_t> getStrides(ArrayRef<int64_t> shape) {
int rank = shape.size();
std::vector<int64_t> strides;
int64_t count = 1;
for (int i = rank - 1; i >= 0; i--) {
strides.insert(strides.begin(), count);
count *= shape[i];
}
return strides;
}
/// Compute the linear access index.
int64_t getLinearAccessIndex(
ArrayRef<int64_t> indices, ArrayRef<int64_t> strides) {
int64_t index = 0;
for (unsigned int i = 0; i < strides.size(); ++i)
index += indices[i] * strides[i];
return index;
}
// Compute the tensor access index from a linear index.
std::vector<int64_t> getAccessIndex(
int64_t linearIndex, ArrayRef<int64_t> strides) {
std::vector<int64_t> res;
for (unsigned int i = 0; i < strides.size(); ++i) {
int64_t s = strides[i];
if (linearIndex < s) {
res.emplace_back(0);
} else {
res.emplace_back(floor(linearIndex / s));
linearIndex = linearIndex % s;
}
}
return res;
}
/// Allocate a buffer whose size is getting from a given Value's type.
char *allocateBufferFor(Type type, bool useMaxSize) {
assert(type.isa<ShapedType>() && "Not a shaped type");
int64_t sizeInBytes;
if (useMaxSize)
sizeInBytes = getMaxSizeInBytes(type.cast<ShapedType>());
else
sizeInBytes = getSizeInBytes(type.cast<ShapedType>());
char *res = (char *)malloc(sizeInBytes);
return res;
}
/// Get a data array from a given ONNXConstantOp.
char *createArrayFromDenseElementsAttr(DenseElementsAttr dataAttr) {
Type elementType = dataAttr.getType().getElementType();
int64_t numElements = getNumberOfElements(dataAttr.getType().getShape());
char *res = allocateBufferFor(dataAttr.getType(), /*useMaxSize=*/true);
if (elementType.isa<FloatType>()) {
// Use double to avoid the precision loss during computation.
double *resArr = (double *)res;
auto valueIt = dataAttr.getFloatValues().begin();
for (int64_t i = 0; i < numElements; ++i) {
double val = (double)(*valueIt++).convertToFloat();
*(resArr + i) = val;
}
} else if (elementType.isa<IntegerType>()) {
// Use int64_t to avoid the precision loss during computation.
int64_t *resArr = (int64_t *)res;
auto valueIt = dataAttr.getIntValues().begin();
for (int64_t i = 0; i < numElements; ++i) {
int64_t val = (*valueIt++).getSExtValue();
*(resArr + i) = val;
}
} else
llvm_unreachable("Unknown data type");
return res;
}
/// A helper function to construct a DenseElementsAttr from an array.
DenseElementsAttr createDenseElementsAttrFromArray(char *arr, Type outputType) {
int64_t sizeInBytes = getSizeInBytes(outputType);
RankedTensorType resType =
constructRankedTensorType(outputType.cast<ShapedType>());
return DenseElementsAttr::getFromRawBuffer(
resType, ArrayRef<char>(arr, sizeInBytes), /*isSplat=*/false);
}
/// Create a dense ONNXConstantOp from a byte array.
ONNXConstantOp createDenseONNXConstantOp(PatternRewriter &rewriter,
Location loc, ShapedType resultType, char *array) {
char *resArray = allocateBufferFor(resultType);
convertDoubleInt64ToExactType(resultType, array, resArray);
DenseElementsAttr denseAttr =
createDenseElementsAttrFromArray(resArray, resultType);
free(resArray);
return rewriter.create<ONNXConstantOp>(loc, resultType, Attribute(),
denseAttr, FloatAttr(), ArrayAttr(), IntegerAttr(), ArrayAttr(),
StringAttr(), ArrayAttr());
}
/// Convert an array whose element type is double or int_64 to an array whose
/// element type is the one of 'outType' (smaller precision). It does not
/// support converting from floating point to integer and vise versa.
void convertDoubleInt64ToExactType(Type outType, char *inArr, char *outArr) {
ShapedType shapedType = outType.cast<ShapedType>();
int64_t maxSizeInBytes = getMaxSizeInBytes(shapedType);
int64_t numElements = getNumberOfElements(shapedType.getShape());
Type elementType = shapedType.getElementType();
if (elementType.isa<FloatType>()) {
FloatType floatTy = elementType.cast<FloatType>();
if (floatTy.getWidth() == 32) {
double *inArrDouble = (double *)inArr;
float *inArrFloat = (float *)outArr;
for (int64_t i = 0; i < numElements; ++i)
*(inArrFloat + i) = (float)*(inArrDouble + i);
} else if (floatTy.getWidth() == 64) {
std::copy(inArr, inArr + maxSizeInBytes, outArr);
} else
llvm_unreachable("Unknown data type");
} else if (elementType.isa<IntegerType>()) {
IntegerType intTy = elementType.cast<IntegerType>();
if (intTy.getWidth() == 32) {
int64_t *inArrInt64 = (int64_t *)inArr;
int32_t *inArrInt32 = (int32_t *)outArr;
for (int64_t i = 0; i < numElements; ++i)
*(inArrInt32 + i) = (int32_t)(*(inArrInt64 + i));
} else if (intTy.getWidth() == 64) {
std::copy(inArr, inArr + maxSizeInBytes, outArr);
} else
llvm_unreachable("Unknown data type");
} else
llvm_unreachable("Unknown data type");
}
/// A helper function to contruct a RankedTensorType from a ShapedType.
RankedTensorType constructRankedTensorType(ShapedType type) {
assert(type.hasRank() && "Not a ranked type");
return RankedTensorType::get(type.getShape(), type.getElementType());
}
//===----------------------------------------------------------------------===//
// Code to perform constant propagation for split.
//===----------------------------------------------------------------------===//
template <typename T>
void IterateConstPropSplit(char *constArray, ArrayRef<int64_t> constShape,
uint64_t splitAxis, ArrayRef<int64_t> splitOffsets,
ArrayRef<Type> replacingTypes, std::vector<char *> &resBuffers) {
// Basic info.
unsigned int rank = constShape.size();
unsigned int numOfResults = replacingTypes.size();
// Data pointers.
T *constArrayT = reinterpret_cast<T *>(constArray);
// Strides info.
std::vector<int64_t> constStrides = getStrides(constShape);
// Allocate temporary buffers.
for (unsigned int i = 0; i < numOfResults; ++i) {
// Use maximum size (double or int64_t) to avoid the precision loss.
char *resArray = allocateBufferFor(replacingTypes[i], /*useMaxSize=*/true);
resBuffers.emplace_back(resArray);
}
// Do splitting
for (int64_t i = 0; i < getNumberOfElements(constShape); ++i) {
// Input indices.
std::vector<int64_t> constIndices = getAccessIndex(i, constStrides);
// Find the corresponding output and compute access indices.
int toResult = numOfResults - 1;
SmallVector<int64_t, 4> resIndices(rank, 0);
for (unsigned int r = 0; r < rank; ++r) {
if (r == splitAxis) {
for (int k = 0; k < (int)numOfResults - 1; ++k)
if (constIndices[r] >= splitOffsets[k] &&
constIndices[r] < splitOffsets[k + 1]) {
toResult = k;
break;
}
resIndices[r] = constIndices[r] - splitOffsets[toResult];
} else {
resIndices[r] = constIndices[r];
}
}
// Get linear access indices.
std::vector<int64_t> resStrides =
getStrides(replacingTypes[toResult].cast<ShapedType>().getShape());
int64_t resOffset = getLinearAccessIndex(resIndices, resStrides);
// Copy data.
T *resArrayT = reinterpret_cast<T *>(resBuffers[toResult]);
*(resArrayT + resOffset) = *(constArrayT + i);
}
}
void ConstPropSplitImpl(Type elementType, char *constArray,
llvm::ArrayRef<int64_t> constShape, uint64_t splitAxis,
llvm::ArrayRef<int64_t> splitOffsets,
llvm::ArrayRef<mlir::Type> replacingTypes,
std::vector<char *> &resBuffers) {
if (elementType.isa<FloatType>()) {
IterateConstPropSplit<double>(constArray, constShape, splitAxis,
splitOffsets, replacingTypes, resBuffers);
} else if (elementType.isa<IntegerType>()) {
IterateConstPropSplit<int64_t>(constArray, constShape, splitAxis,
splitOffsets, replacingTypes, resBuffers);
} else
llvm_unreachable("Unknown data type");
}
//===----------------------------------------------------------------------===//
// Code to perform constant propagation for transpose.
//===----------------------------------------------------------------------===//
template <typename T>
void IterateConstPropTranspose(char *constArray, ArrayRef<int64_t> constShape,
ArrayRef<uint64_t> perm, ArrayRef<int64_t> resShape, char *resArray) {
// Data pointers.
T *constArrayT = reinterpret_cast<T *>(constArray);
T *resArrayT = reinterpret_cast<T *>(resArray);
// Get a reversed perm.
SmallVector<uint64_t, 4> reversedPerm(perm.size(), 0);
for (unsigned int i = 0; i < perm.size(); ++i)
reversedPerm[perm[i]] = i;
// Strides info.
std::vector<int64_t> constStrides = getStrides(constShape);
std::vector<int64_t> resStrides = getStrides(resShape);
// Calculate transpose result.
for (int64_t i = 0; i < getNumberOfElements(resShape); ++i) {
// Indices.
std::vector<int64_t> resIndices = getAccessIndex(i, resStrides);
SmallVector<int64_t, 4> constIndices(perm.size(), 0);
for (unsigned int j = 0; j < constIndices.size(); ++j)
constIndices[j] = resIndices[reversedPerm[j]];
// Transpose.
int64_t constOffset = getLinearAccessIndex(constIndices, constStrides);
int64_t resOffset = getLinearAccessIndex(resIndices, resStrides);
*(resArrayT + resOffset) = *(constArrayT + constOffset);
}
}
void ConstPropTransposeImpl(Type elementType, char *constArray,
llvm::ArrayRef<int64_t> constShape, llvm::ArrayRef<uint64_t> perm,
llvm::ArrayRef<int64_t> resShape, char *resArray) {
if (elementType.isa<FloatType>()) {
// Use double to avoid the precision loss during computation.
IterateConstPropTranspose<double>(
constArray, constShape, perm, resShape, resArray);
} else if (elementType.isa<IntegerType>()) {
// Use int64_t to avoid the precision loss during computation.
IterateConstPropTranspose<int64_t>(
constArray, constShape, perm, resShape, resArray);
} else
llvm_unreachable("Unknown data type");
}
| 37.520249 | 80 | 0.663982 | juan561999 |
aa433ef2912bfb3276d3bd16da3d1b8c5ce56839 | 6,010 | cpp | C++ | examples/chapter_nine/two_layers_network/src/main.cpp | PacktPublishing/Hands-On-Neural-Network-Programming-with-CPP | c6b5041bc2beb6d0bf978095ee986b4239b43b28 | [
"MIT"
] | 9 | 2019-04-17T16:23:33.000Z | 2021-11-08T13:11:09.000Z | examples/chapter_nine/two_layers_network/src/main.cpp | PacktPublishing/Hands-On-Neural-Network-Programming-with-CPP | c6b5041bc2beb6d0bf978095ee986b4239b43b28 | [
"MIT"
] | null | null | null | examples/chapter_nine/two_layers_network/src/main.cpp | PacktPublishing/Hands-On-Neural-Network-Programming-with-CPP | c6b5041bc2beb6d0bf978095ee986b4239b43b28 | [
"MIT"
] | 5 | 2019-05-28T11:56:08.000Z | 2021-03-30T01:13:39.000Z | #include <iostream>
#include <fstream>
#include <exception>
#include <string>
#include <algorithm>
#include "matrix_definitions.hpp"
#include <opencv2/imgproc.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/core/eigen.hpp>
void show(const cv::Mat &source, const cv::Mat &groundTruth, const cv::Mat &convoluted)
{
int maxHeight = std::max(std::max(source.rows, groundTruth.rows), convoluted.rows);
int width = source.cols + groundTruth.cols + convoluted.cols;
cv::Mat toShow(maxHeight, width, CV_8UC1, cv::Scalar(0));
cv::Mat source_roi = toShow(cv::Rect(0, 0, source.cols, source.rows));
source.copyTo(source_roi);
cv::Mat groundTruth_roi = toShow(cv::Rect(source.cols, 0, groundTruth.cols, groundTruth.rows));
groundTruth.copyTo(groundTruth_roi);
cv::Mat convoluted_roi = toShow(cv::Rect(source.cols + groundTruth.cols, 0, convoluted.cols, convoluted.rows));
convoluted.copyTo(convoluted_roi);
cv::namedWindow("", cv::WindowFlags::WINDOW_AUTOSIZE);
cv::imshow("", toShow);
}
Matrix rotate180(const Matrix &m)
{
return m.colwise().reverse().rowwise().reverse();
}
Matrix convolution(const Matrix &source, const Matrix &filter, const int row_padding, const int cols_padding)
{
int filterRows = filter.rows();
int filterCols = filter.cols();
int rows = source.rows() - filterRows + 2*row_padding + 1;
int cols = source.cols() - filterCols + 2*cols_padding + 1;
Matrix input = Matrix::Zero(source.rows() + 2*row_padding, source.cols() + 2*cols_padding);
input.block(row_padding, cols_padding, source.rows(), source.cols()) = source;
Matrix result = Matrix::Zero(rows, cols);
for(int i = 0; i < rows; ++i)
{
for(int j = 0; j < cols; ++j)
{
double sum = input.block(i, j, filterRows, filterCols).cwiseProduct(filter).sum();
result(i, j) = sum;
}
}
return result;
}
std::tuple<Matrix, Matrix> imageConvolution(const Matrix input, cv::Mat &dest, const Matrix &filterLayer1, const Matrix &filterLayer2)
{
Matrix layer1 = convolution(input, filterLayer1, 0, 0);
Matrix layer2 = convolution(layer1, filterLayer2, 0, 0);
cv::eigen2cv(layer2, dest);
dest.convertTo(dest, CV_8UC1);
return std::make_tuple(layer1, layer2);
}
class MSEViewer {
private:
int height;
int width;
cv::Mat mat;
double maxMSE;
double maxEpoch;
int bottom_padding;
int top_padding;
int left_padding;
int right_padding;
public:
MSEViewer(int _height, int _width, double _maxMSE, double _maxEpoch, int _bottom_padding, int _top_padding, int _left_padding, int _right_padding) :
height(_height), width(_width), mat(cv::Mat(height, width, CV_8UC1, cv::Scalar(0))), maxMSE(_maxMSE),
maxEpoch(_maxEpoch), bottom_padding(_bottom_padding), top_padding(_top_padding), left_padding(_left_padding), right_padding(_right_padding) {
int bottommost = height - bottom_padding;
line(mat, cv::Point(left_padding, bottommost), cv::Point(left_padding, bottom_padding), cv::Scalar(255));
line(mat, cv::Point(left_padding, bottommost), cv::Point(width - right_padding, bottommost), cv::Scalar(255));
}
void addPoint(int epoch, double mse) {
if(epoch < maxEpoch)
{
double normMse = mse / maxMSE;
int maxMSEPos = mat.rows - bottom_padding;
int positionY = static_cast<int>(-normMse * (maxMSEPos - top_padding) + maxMSEPos);
double normEpoch = epoch / maxEpoch;
int maxEpochPos = mat.cols - right_padding;
int positionX = static_cast<int>(normEpoch * (maxEpochPos - left_padding) + left_padding);
cv::circle(mat, cv::Point(positionX, positionY), 2, cv::Scalar(255));
}
}
const cv::Mat& getMat() const {
return mat;
}
};
int main(int, char **)
{
const char * imagepath = "../data/convolution_example.png";
cv::Mat image = cv::imread(imagepath, cv::IMREAD_GRAYSCALE);
cv::Mat groundTruth, outputImage;
Matrix groundTruthFilterLayer1(5, 5);
groundTruthFilterLayer1 <<
1, 4, 6, 4, 1,
4, 16, 24, 16, 4,
6, 24, 36, 24, 6,
4, 16, 24, 16, 4,
1, 4, 6, 4, 1;
groundTruthFilterLayer1 /= 256;
Matrix groundTruthFilterLayer2(3, 3);
groundTruthFilterLayer2 <<
-1, 0, 1,
-1, 0, 1,
-1, 0, 1;
Matrix inputMatrix;
cv::cv2eigen(image, inputMatrix);
const auto [stdIgnore, groundTruthMatrix] = imageConvolution(inputMatrix, groundTruth, groundTruthFilterLayer1, groundTruthFilterLayer2);
Matrix K1 = 0.05 * Matrix::Random(5, 5);
Matrix K2 = 0.05 * Matrix::Random(3, 3);
int key = 0;
int epoch = 0;
double learningRate = 0.000000000001;
while(key != 27)
{
auto [outputLayer1, outputLayer2] = imageConvolution(inputMatrix, outputImage, K1, K2);
Matrix dCLayer2 = outputLayer2 - groundTruthMatrix;
double mse = dCLayer2.cwiseProduct(dCLayer2).sum() / dCLayer2.rows() / dCLayer2.cols();
Matrix dK2 = convolution(outputLayer1, dCLayer2, 0, 0);
int row_padding = (outputLayer1.rows() - dCLayer2.rows() + K2.rows() - 1) / 2;
int col_padding = (outputLayer1.cols() - dCLayer2.cols() + K2.cols() - 1) / 2;
auto K2_180 = rotate180(K2);
Matrix dCLayer1 = convolution(dCLayer2, K2_180, row_padding, col_padding);
Matrix dK1 = convolution(inputMatrix, dCLayer1, 0, 0);
K2 = K2 - learningRate * dK2;
K1 = K1 - learningRate * dK1;
std::cout << "Epoch:\t" << epoch << "\tMSE:\t" << mse << "\n";
epoch++;
show(image, groundTruth, outputImage);
key = cv::waitKey(10);
}
std::cout << "K1 =\n" << K1*256 << "\n\n";
std::cout << "K2 =\n" << K2 << "\n\n";
return 0;
} | 39.025974 | 157 | 0.628453 | PacktPublishing |
aa4638abefaaaef7eaa7a21b3fadd3dec9691266 | 506 | cpp | C++ | mod/wrc/flag/flags/fileFlag.cpp | kniz/wrd | a8c9e8bd2f7b240ff64a3b80e7ebc7aff2775ba6 | [
"MIT"
] | 1 | 2019-02-02T07:07:32.000Z | 2019-02-02T07:07:32.000Z | mod/wrc/flag/flags/fileFlag.cpp | kniz/wrd | a8c9e8bd2f7b240ff64a3b80e7ebc7aff2775ba6 | [
"MIT"
] | 25 | 2016-09-23T16:36:19.000Z | 2019-02-12T14:14:32.000Z | mod/wrc/flag/flags/fileFlag.cpp | kniz/World | 13b0c8c7fdc6280efcb2135dc3902754a34e6d06 | [
"MIT"
] | null | null | null | #include "fileFlag.hpp"
#include <fstream>
#include <sstream>
namespace wrd {
WRD_DEF_ME(fileFlag)
wbool me::_onTake(const args& tray, cli& c, interpreter& ip) const {
std::vector<string> buf;
for(const auto& filePath : tray) {
std::ifstream fout(filePath);
std::stringstream buffer;
buffer << fout.rdbuf();
buf.push_back(buffer.str());
}
ip.setSrcSupply(*new bufferSrcSupply(buf));
return true;
};
}
| 22 | 72 | 0.577075 | kniz |
aa47ac68b7c4044e40b7ee7cd94a7d62514ad36e | 1,106 | hpp | C++ | include/LoopKeybinding.hpp | DangerInteractive/ArcticWolf | 74999f00cb4ef44f358bea1df266967cd1e7ed6c | [
"MIT"
] | null | null | null | include/LoopKeybinding.hpp | DangerInteractive/ArcticWolf | 74999f00cb4ef44f358bea1df266967cd1e7ed6c | [
"MIT"
] | null | null | null | include/LoopKeybinding.hpp | DangerInteractive/ArcticWolf | 74999f00cb4ef44f358bea1df266967cd1e7ed6c | [
"MIT"
] | null | null | null | #ifndef H_AW_LOOPKEYBINDING
#define H_AW_LOOPKEYBINDING
#include <vector>
#include <functional>
#include <SFML/Window.hpp>
namespace aw {
class LoopKeybinding {
public:
typedef std::function<void()> LoopKeybindingCallback;
LoopKeybinding (const LoopKeybindingCallback&, sf::Keyboard::Key);
LoopKeybinding (const LoopKeybindingCallback&, const std::vector<sf::Keyboard::Key>&);
~ LoopKeybinding () = default;
LoopKeybinding (LoopKeybinding&&) = default;
LoopKeybinding& operator = (LoopKeybinding&&) = default;
LoopKeybinding (const LoopKeybinding&) = default;
LoopKeybinding& operator = (const LoopKeybinding&) = default;
bool check (const std::vector<sf::Keyboard::Key>&);
void process (const std::vector<sf::Keyboard::Key>&);
const LoopKeybindingCallback& getCallback () const;
std::vector<sf::Keyboard::Key> getKeys () const;
void setCallback (const LoopKeybindingCallback&);
void setKeys (const std::vector<sf::Keyboard::Key>&);
private:
LoopKeybindingCallback m_callback;
std::vector<sf::Keyboard::Key> m_keys;
};
}
#endif
| 25.72093 | 90 | 0.716094 | DangerInteractive |
aa4bcae50756b29c90ee21adf472baa00036269b | 1,294 | cpp | C++ | atcoder/arc087d.cpp | sogapalag/problems | 0ea7d65448e1177f8b3f81124a82d187980d659c | [
"MIT"
] | 1 | 2020-04-04T14:56:12.000Z | 2020-04-04T14:56:12.000Z | atcoder/arc087d.cpp | sogapalag/problems | 0ea7d65448e1177f8b3f81124a82d187980d659c | [
"MIT"
] | null | null | null | atcoder/arc087d.cpp | sogapalag/problems | 0ea7d65448e1177f8b3f81124a82d187980d659c | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
const int N = 8100;
const int LIM = N<<1;
bool dp[2][2][LIM];
void solve() {
string s; cin >> s;
int ta[2];
cin >> ta[0] >> ta[1];
s += "T";
vector<int> a[2];
int dir = 0;
int len = 0;
int n = s.size();
int i = 0;
while (s[i]!='T') {
len++; i++;
}
dp[0][0][N+len] = true;
dp[1][0][N] = true;
len=0;
for (; i < n; i++) {
if (s[i] != 'T') len++;
else {
if (len) a[dir].emplace_back(len);
dir ^= 1;
len = 0;
}
}
bool res = true;
for (int i = 0; i < 2; i++) {
int n = a[i].size();
int crt = 0;
for (int j = 0; j < n; j++) {
int nxt = crt^1;
for (int k = 0; k < LIM; k++) {
dp[i][nxt][k] = false;
}
int ds = a[i][j];
for (int k = 0; k < LIM; k++) {
if (k+ds < LIM) dp[i][nxt][k+ds] |= dp[i][crt][k];
if (k-ds >= 0) dp[i][nxt][k-ds] |= dp[i][crt][k];
}
crt ^= 1;
}
res &= dp[i][crt][N+ta[i]];
}
cout << (res?"Yes":"No");
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
solve();
cout << endl;
}
| 20.870968 | 66 | 0.36476 | sogapalag |
aa4c3dc1b6129141e775aee84d0535ede16be69d | 1,015 | cpp | C++ | opfile.cpp | XunZhiyang/BookStore | a8926673cee17029c61797a983d077499995d84f | [
"MIT"
] | null | null | null | opfile.cpp | XunZhiyang/BookStore | a8926673cee17029c61797a983d077499995d84f | [
"MIT"
] | 3 | 2018-12-17T07:20:05.000Z | 2018-12-25T09:16:02.000Z | opfile.cpp | XunZhiyang/BookStore | a8926673cee17029c61797a983d077499995d84f | [
"MIT"
] | null | null | null | //#include "pch.h"
#include <fstream>
#include "opfile.h"
bool exist(const std::string &name) {
std::ifstream test(name);
if (test.good()) {
test.close();
return true;
}
return false;
}
void readInt(std::fstream &stream, int &t) {
stream.read(reinterpret_cast<char *>(&t), 4);
//std::cerr << stream.gcount() << std::endl;
}
void writeInt(std::fstream &stream, int t) {
stream.write(reinterpret_cast<char *>(&t), 4);
}
void readString(std::fstream &stream, std::string &s, int _size) {
char *ss = new char[_size + 1];
ss[_size] = '\0';
stream.read(ss, _size);
s = ss;
delete []ss;
}
void writeString(std::fstream &stream, std::string &s, int _size) {
int len = s.length();
for (int i = len; i < _size; ++i) s += '\0';
stream.write(s.c_str(), _size);
}
void writeDouble(std::fstream &stream, double t) {
stream.write(reinterpret_cast<char *>(&t), sizeof(double));
}
double readDouble(std::fstream &stream) {
double t;
stream.read(reinterpret_cast<char *>(&t), sizeof(double));
return t;
} | 23.068182 | 67 | 0.646305 | XunZhiyang |
aa4cc08a1ffd9bfcb60f02ccb831b48a4b4df9dd | 2,490 | cpp | C++ | extensions/vivaldi_extensions_client.cpp | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | extensions/vivaldi_extensions_client.cpp | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | extensions/vivaldi_extensions_client.cpp | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2015 Vivaldi Technologies AS. All rights reserved
#include "extensions/vivaldi_extensions_client.h"
#include "extensions/common/features/json_feature_provider_source.h"
#include "extensions/common/permissions/permissions_info.h"
#include "extensions/schema/generated_schemas.h"
#include "vivaldi/grit/vivaldi_extension_resources.h"
namespace extensions {
static base::LazyInstance<VivaldiExtensionsClient> g_client =
LAZY_INSTANCE_INITIALIZER;
VivaldiExtensionsClient::VivaldiExtensionsClient()
: vivaldi_api_permissions_(VivaldiAPIPermissions()) {
}
VivaldiExtensionsClient::~VivaldiExtensionsClient(){
}
void VivaldiExtensionsClient::Initialize() {
ChromeExtensionsClient::Initialize();
// Set up permissions.
PermissionsInfo::GetInstance()->AddProvider(vivaldi_api_permissions_);
}
bool
VivaldiExtensionsClient::IsAPISchemaGenerated(const std::string& name) const {
return ChromeExtensionsClient::IsAPISchemaGenerated(name) ||
vivaldi::VivaldiGeneratedSchemas::IsGenerated(name);
}
base::StringPiece
VivaldiExtensionsClient::GetAPISchema(const std::string& name) const {
if (vivaldi::VivaldiGeneratedSchemas::IsGenerated(name))
return vivaldi::VivaldiGeneratedSchemas::Get(name);
return ChromeExtensionsClient::GetAPISchema(name);
}
scoped_ptr<JSONFeatureProviderSource>
VivaldiExtensionsClient::CreateFeatureProviderSource(
const std::string& name) const {
scoped_ptr<JSONFeatureProviderSource> source(
ChromeExtensionsClient::CreateFeatureProviderSource(name));
DCHECK(source);
if (name == "api") {
source->LoadJSON(IDR_VIVALDI_EXTENSION_API_FEATURES);
} else if (name == "manifest") {
source->LoadJSON(IDR_VIVALDI_EXTENSION_MANIFEST_FEATURES);
} else if (name == "permission") {
source->LoadJSON(IDR_VIVALDI_EXTENSION_PERMISSION_FEATURES);
} else if (name == "behavior") {
} else {
NOTREACHED();
source.reset();
}
return source;
}
/*static*/
ChromeExtensionsClient* VivaldiExtensionsClient::GetInstance() {
return g_client.Pointer();
}
// NOTE(yngve) Run this function **before**
// ChromeExtensionsClient::GetInstance() is called
// Hack to make sure ChromeExtensionsClient::GetInstance()
// calls the VivaldiExtensionsClient::GetInstance() instead
/*static*/
void VivaldiExtensionsClient::RegisterVivaldiExtensionsClient() {
ChromeExtensionsClient::RegisterAlternativeGetInstance(
VivaldiExtensionsClient::GetInstance);
}
} // namespace extensions
| 30.365854 | 78 | 0.778313 | wedataintelligence |
aa5b6e3011860352a6c7d2181c6dea2c548d7b6d | 78 | cpp | C++ | DAA Lab/strmul.cpp | mayank-kumar-giri/Competitive-Coding | 4cd26ede051bad15bf25cfd037317c313b607507 | [
"MIT"
] | null | null | null | DAA Lab/strmul.cpp | mayank-kumar-giri/Competitive-Coding | 4cd26ede051bad15bf25cfd037317c313b607507 | [
"MIT"
] | null | null | null | DAA Lab/strmul.cpp | mayank-kumar-giri/Competitive-Coding | 4cd26ede051bad15bf25cfd037317c313b607507 | [
"MIT"
] | null | null | null | #include<iostream>
#include "bs.cpp"
#include "merge.c"
using namespace std;
| 13 | 20 | 0.730769 | mayank-kumar-giri |
aa5d996981df1dc855502777425e379f96ff65f5 | 2,867 | cc | C++ | HIP/StreamTriad/StreamTriad.cc | essentialsofparallelcomputing/Chapter12 | 98ad49cce4ac7dd4a76d1ec80e4383606c4cb671 | [
"Apache-2.0"
] | 3 | 2020-04-12T11:36:09.000Z | 2021-05-19T10:59:10.000Z | HIP/StreamTriad/StreamTriad.cc | essentialsofparallelcomputing/Chapter12 | 98ad49cce4ac7dd4a76d1ec80e4383606c4cb671 | [
"Apache-2.0"
] | null | null | null | HIP/StreamTriad/StreamTriad.cc | essentialsofparallelcomputing/Chapter12 | 98ad49cce4ac7dd4a76d1ec80e4383606c4cb671 | [
"Apache-2.0"
] | null | null | null | #include "hip/hip_runtime.h"
#include <stdio.h>
#include <sys/time.h>
extern "C" {
#include "timer.h"
}
#define NTIMES 16
// CUDA kernel version of stream triad
__global__ void StreamTriad(int n, double scalar, double *a, double *b, double *c){
int i = blockIdx.x*blockDim.x+threadIdx.x;
// Protect from going out-of-bounds
if (i >= n) return;
c[i] = a[i] + scalar*b[i];
}
int main(int argc, char *argv[]){
struct timespec tkernel, ttotal;
// initializing data and arrays
int stream_array_size = 80000000;
double scalar = 3.0, tkernel_sum = 0.0, ttotal_sum = 0.0;
// allocate host memory and initialize
double *a = (double *)malloc(stream_array_size*sizeof(double));
double *b = (double *)malloc(stream_array_size*sizeof(double));
double *c = (double *)malloc(stream_array_size*sizeof(double));
for (int i=0; i<stream_array_size; i++) {
a[i] = 1.0;
b[i] = 2.0;
}
// allocate device memory. suffix of _d indicates a device pointer
double *a_d, *b_d, *c_d;
hipMalloc(&a_d, stream_array_size*sizeof(double));
hipMalloc(&b_d, stream_array_size*sizeof(double));
hipMalloc(&c_d, stream_array_size*sizeof(double));
// setting block size and padding total grid size to get even block sizes
int blocksize = 512;
int gridsize = (stream_array_size + blocksize - 1)/blocksize;
for (int k=0; k<NTIMES; k++){
cpu_timer_start(&ttotal);
// copying array data from host to device
hipMemcpy(a_d, a, stream_array_size*sizeof(double), hipMemcpyHostToDevice);
hipMemcpy(b_d, b, stream_array_size*sizeof(double), hipMemcpyHostToDevice);
// cuda memcopy to device returns after buffer available, so synchronize to
// get accurate timing for kernel only
hipDeviceSynchronize();
cpu_timer_start(&tkernel);
// launch stream triad kernel
hipLaunchKernelGGL(StreamTriad, dim3(gridsize), dim3(blocksize), 0, 0, stream_array_size, scalar, a_d, b_d, c_d);
// need to force completion to get timing
hipDeviceSynchronize();
tkernel_sum += cpu_timer_stop(tkernel);
// cuda memcpy from device to host blocks for completion so no need for synchronize
hipMemcpy(c, c_d, stream_array_size*sizeof(double), hipMemcpyDeviceToHost);
ttotal_sum += cpu_timer_stop(ttotal);
// check results and print errors if found. limit to only 10 errors per iteration
for (int i=0, icount=0; i<stream_array_size && icount < 10; i++){
if (c[i] != 1.0 + 3.0*2.0) {
printf("Error with result c[%d]=%lf on iter %d\n",i,c[i],k);
icount++;
}
}
}
printf("Average runtime is %lf msecs data transfer is %lf msecs\n",
tkernel_sum/NTIMES, (ttotal_sum - tkernel_sum)/NTIMES);
hipFree(a_d);
hipFree(b_d);
hipFree(c_d);
free(a);
free(b);
free(c);
}
| 34.130952 | 119 | 0.663062 | essentialsofparallelcomputing |
aa5f45c0b0a9bb0c6fb9ffa459e9fc4864dc3c50 | 2,044 | cc | C++ | tests/test_lqr.cc | oliverlee/biketest | 074b0b03455021c52a13efe583b1816bc5daad4e | [
"BSD-2-Clause"
] | 3 | 2016-12-14T01:22:27.000Z | 2020-04-07T05:15:04.000Z | tests/test_lqr.cc | oliverlee/biketest | 074b0b03455021c52a13efe583b1816bc5daad4e | [
"BSD-2-Clause"
] | 7 | 2017-01-12T15:20:57.000Z | 2017-07-02T16:09:37.000Z | tests/test_lqr.cc | oliverlee/biketest | 074b0b03455021c52a13efe583b1816bc5daad4e | [
"BSD-2-Clause"
] | 1 | 2020-04-07T05:15:05.000Z | 2020-04-07T05:15:05.000Z | #include "gtest/gtest.h"
#include "test_convergence.h"
#include "constants.h"
// TODO: Add convergence with model error
class LqrTrackingTest: public ConvergenceTest {
public:
void SetUp() {
ConvergenceTest::SetUp();
// use integral action
m_lqr->set_Qi((bicycle_t::state_t() <<
10.0, 1.0, 1.0, 0.0, 0.0).finished().asDiagonal() *
constants::as_radians);
}
void simulate(size_t N = default_simulation_length) {
for(unsigned int i = 0; i < N; ++i) {
auto u = m_lqr->control_calculate(m_x);
m_x = m_bicycle->update_state(m_x, u);
}
}
};
TEST_P(LqrTrackingTest, ZeroReferenceWithRollTorqueControl) {
m_lqr->set_R((lqr_t::input_cost_t() <<
0.1, 0,
0, 0.1).finished());
simulate();
test_state_near(x_true(), bicycle_t::state_t::Zero());
}
TEST_P(LqrTrackingTest, ZeroReference) {
simulate();
test_state_near(x_true(), bicycle_t::state_t::Zero());
}
TEST_P(LqrTrackingTest, ZeroReferenceWithPeriodicRollTorqueDisturbance) {
simulate();
for(unsigned int i = 0; i < default_simulation_length; ++i) {
auto u = m_lqr->control_calculate(m_x);
bool disturb = ((i / 100) % 5 == 0);
if (disturb) {
u[0] += 1.0;
}
m_x = m_bicycle->update_state(m_x, u);
}
test_state_near(x_true(), bicycle_t::state_t::Zero());
}
TEST_P(LqrTrackingTest, ZeroReferenceWithConstantRollTorqueDisturbance) {
simulate();
for(unsigned int i = 0; i < default_simulation_length; ++i) {
auto u = m_lqr->control_calculate(m_x);
u[0] += 1.0;
m_x = m_bicycle->update_state(m_x, u);
}
test_state_near(x_true(), bicycle_t::state_t::Zero());
}
INSTANTIATE_TEST_CASE_P(
TrackingRange_1_9,
LqrTrackingTest,
::testing::Range(static_cast<model::real_t>(0.5),
static_cast<model::real_t>(9.5),
static_cast<model::real_t>(0.5)));
| 28.388889 | 75 | 0.594423 | oliverlee |
aa601fdffefd00d331af042807bf638a48712c6b | 596 | cpp | C++ | copy_constructor.cpp | Devilshree123/Object-oriented-programming-in-CPP | d5059b1c4f394417235ade5a0794d368d1c13b60 | [
"Apache-2.0"
] | null | null | null | copy_constructor.cpp | Devilshree123/Object-oriented-programming-in-CPP | d5059b1c4f394417235ade5a0794d368d1c13b60 | [
"Apache-2.0"
] | null | null | null | copy_constructor.cpp | Devilshree123/Object-oriented-programming-in-CPP | d5059b1c4f394417235ade5a0794d368d1c13b60 | [
"Apache-2.0"
] | null | null | null | #include<iostream>
using namespace std;
class number
{
int a ;
public:
number(){
a=0;
}
number(int num)
{
a = num;
}
number(number &obj)
{
cout<<"copy constructor is called "<<endl;
a = obj.a;
}
void display();
};
void number :: display()
{
cout<<"the number is "<<a<<endl;
}
int main()
{
number x, y, z(45);
x.display();
y.display();
z.display();
number z1(z);
z1.display();
return 0;
} | 14.190476 | 55 | 0.407718 | Devilshree123 |
aa62ad93ab34bbbdb4e009f0ef5397bea16621e1 | 423 | cpp | C++ | 6. Trees/09. Convert BST to Greater Tree.cpp | thekalyan001/DMB1-CP | 7ccf41bac7269bff432260c6078cebdb4e0f1483 | [
"Apache-2.0"
] | null | null | null | 6. Trees/09. Convert BST to Greater Tree.cpp | thekalyan001/DMB1-CP | 7ccf41bac7269bff432260c6078cebdb4e0f1483 | [
"Apache-2.0"
] | null | null | null | 6. Trees/09. Convert BST to Greater Tree.cpp | thekalyan001/DMB1-CP | 7ccf41bac7269bff432260c6078cebdb4e0f1483 | [
"Apache-2.0"
] | null | null | null | https://leetcode.com/problems/convert-bst-to-greater-tree/
convert bst such that BST is changed to the original key plus the sum
of all keys greater than the original key in BST.
TreeNode* convertBST(TreeNode* root) {
if(root!=NULL){
convertBST(root->right);
sum+=root->val;
root->val=sum;
convertBST(root->left);
}
return root;
} | 30.214286 | 72 | 0.588652 | thekalyan001 |
aa663493041898051a0fef9fdcb937a0f156ab9c | 665 | cpp | C++ | cppfun/main.cpp | selvakumarjawahar/myexperiments | 8d04a38e992bb717c792d198dda1d221b749a375 | [
"MIT"
] | null | null | null | cppfun/main.cpp | selvakumarjawahar/myexperiments | 8d04a38e992bb717c792d198dda1d221b749a375 | [
"MIT"
] | 4 | 2021-09-02T01:23:47.000Z | 2022-02-26T19:35:28.000Z | cppfun/main.cpp | selvakumarjawahar/myexperiments | 8d04a38e992bb717c792d198dda1d221b749a375 | [
"MIT"
] | null | null | null | #include <iostream>
#include "StaticMapGenerator.h"
#include <cstdlib>
Fruits FruitGenerator(){
auto fruit = rand() % 3;
return static_cast<Fruits>(fruit);
}
using DefaultFruitMap = DefaultValueMap<Fruits,Season,Season::AllYear>;
int main() {
std::cout << "Default = " << (int) FruitMap<Fruits::Grapes>::val << '\n';
std::cout << "Mango Season = " << (int) FruitMap<Fruits::Mango>::val << '\n';
DefaultFruitMap dfmap{{Fruits::Mango,Season::Summer}};
std::cout << "Mango Season = " << (int) dfmap.getValue(Fruits::Mango) << '\n';
std::cout << "Random Fruit Season = " << (int) dfmap.getValue(FruitGenerator()) << '\n';
return 0;
}
| 33.25 | 92 | 0.631579 | selvakumarjawahar |
aa68187c169675cc4c51c365350ab05887d971c1 | 6,595 | cpp | C++ | source/app/rendering/device.cpp | mattwamboldt/rasterizer | a571c9350d448f71e991f145cb0264abb2002d4d | [
"MIT"
] | null | null | null | source/app/rendering/device.cpp | mattwamboldt/rasterizer | a571c9350d448f71e991f145cb0264abb2002d4d | [
"MIT"
] | null | null | null | source/app/rendering/device.cpp | mattwamboldt/rasterizer | a571c9350d448f71e991f145cb0264abb2002d4d | [
"MIT"
] | null | null | null | #include "device.h"
#include <float.h>
Device::Device(SDL_Surface* _screen)
:screen(_screen), renderWidth(screen->w), renderHeight(screen->h)
{
depthBuffer = new float[renderWidth * renderHeight];
}
Device::~Device()
{
if (depthBuffer)
{
delete[] depthBuffer;
}
}
// Clears the screen buffer to the given color
void Device::Clear(Color color)
{
Uint32* pixels = (Uint32 *)screen->pixels;
Uint32 screenColor = SDL_MapRGBA(screen->format, color.r, color.g, color.b, color.a);
for (int i = 0; i < renderWidth * renderHeight; ++i)
{
pixels[i] = screenColor;
depthBuffer[i] = FLT_MAX;
}
}
Color Device::GetPixel(int x, int y)
{
Uint32 index = x + y * renderWidth;
Uint32* pixels = (Uint32 *)screen->pixels;
Color ret;
SDL_GetRGBA(pixels[index], screen->format, &(ret.r), &(ret.g), &(ret.b), &(ret.a));
return ret;
}
// Draws a pixel to the screen ignoring the depthbuffer
void Device::PutPixel(int x, int y, Color c)
{
Uint32* pixels = (Uint32 *)screen->pixels;
Uint32 index = x + y * renderWidth;
pixels[index] = SDL_MapRGBA(screen->format, c.r, c.g, c.b, c.a);
}
// Draws a pixel to the screen only if it passes our depth buffer test
void Device::PutPixel(int x, int y, float z, Color c)
{
Uint32* pixels = (Uint32 *)screen->pixels;
Uint32 index = x + y * renderWidth;
if (depthBuffer[index] < z)
{
return;
}
depthBuffer[index] = z;
pixels[index] = SDL_MapRGBA(screen->format, c.r, c.g, c.b, c.a);
}
// Draws a point to the screen if it is within the viewport
void Device::DrawPoint(float x, float y, float z, Color color)
{
// Clipping what's visible on screen
if (x >= 0 && y >= 0 && x < renderWidth && y < renderHeight)
{
// Drawing a point
PutPixel((int)x, (int)y, z, color);
}
}
void Device::DrawPoint(int x, int y, const Color& c)
{
if (x >= 0 && x < screen->w && y >= 0 && y < screen->h)
{
PutPixel(x, y, c);
}
}
Vector3 Device::Project(const Vector3& v, const Matrix& transform) const
{
Vector3 projectedVector = transform.Transform(v);
return Vector3(
((screen->w / 2) * projectedVector.x) + (screen->w / 2),
-(((screen->h / 2) * projectedVector.y) - (screen->h / 2)),
projectedVector.z );
}
void WriteHexString(SDL_RWops* file, char *s)
{
Uint32 value;
char hex[3];
for (int i = 0; i < SDL_strlen(s); i += 2) {
hex[0] = s[i];
hex[1] = s[i + 1];
hex[2] = '\0';
SDL_sscanf(hex, "%X", &value);
SDL_WriteU8(file, value);
}
}
void Device::WriteToFile(const char* filename)
{
SDL_RWops* file = SDL_RWFromFile(filename, "w+b");
if (file)
{
// Writing out a tiff (Code taken from http://paulbourke.net/dataformats/tiff/) switch with a lib later
Uint32 numbytes = renderWidth * renderHeight * 3;
// Header of the file
SDL_RWwrite(file, "MM", 2, 1);
SDL_WriteBE16(file, 42);
Uint32 offset = numbytes + 8; // 8 bytes are from the header including this offset
SDL_WriteBE32(file, offset);
// Then the actual data
Uint32* pixels = (Uint32 *)screen->pixels;
// to avoid a bunch of file io and hopefully speed up the function we're gonna buffer pixel writes and do them at once
Uint8* buffer = new Uint8[numbytes];
Uint32 bufferOffset = 0;
for (int y = 0; y < renderHeight; ++y)
{
for (int x = 0; x < renderWidth; ++x)
{
Uint32 pixelIndex = x + y * renderWidth;
Uint32 pixel = pixels[pixelIndex];
Color color = Color(pixel);
buffer[bufferOffset++] = color.r;
buffer[bufferOffset++] = color.g;
buffer[bufferOffset++] = color.b;
}
}
SDL_RWwrite(file, buffer, numbytes, 1);
delete buffer;
// Finally the IFD
// The number of directory entries
SDL_WriteBE16(file, 14);
/* Width tag, short int */
WriteHexString(file, "0100000300000001");
SDL_WriteBE16(file, renderWidth);
WriteHexString(file, "0000");
/* Height tag, short int */
WriteHexString(file, "0101000300000001");
SDL_WriteBE16(file, renderHeight);
WriteHexString(file, "0000");
/* Bits per sample tag, short int */
WriteHexString(file, "0102000300000003");
SDL_WriteBE32(file, numbytes + 182);
/* Compression flag, short int */
WriteHexString(file, "010300030000000100010000");
/* Photometric interpolation tag, short int */
WriteHexString(file, "010600030000000100020000");
/* Strip offset tag, long int */
WriteHexString(file, "011100040000000100000008");
/* Orientation flag, short int */
WriteHexString(file, "011200030000000100010000");
/* Sample per pixel tag, short int */
WriteHexString(file, "011500030000000100030000");
/* Rows per strip tag, short int */
WriteHexString(file, "0116000300000001");
SDL_WriteBE16(file, renderHeight);
WriteHexString(file, "0000");
/* Strip byte count flag, long int */
WriteHexString(file, "0117000400000001");
SDL_WriteBE32(file, numbytes);
/* Minimum sample value flag, short int */
WriteHexString(file, "0118000300000003");
SDL_WriteBE32(file, numbytes + 188);
/* Maximum sample value tag, short int */
WriteHexString(file, "0119000300000003");
SDL_WriteBE32(file, numbytes + 194);
/* Planar configuration tag, short int */
WriteHexString(file, "011c00030000000100010000");
/* Sample format tag, short int */
WriteHexString(file, "0153000300000003");
SDL_WriteBE32(file, numbytes + 200);
/* End of the directory entry */
WriteHexString(file, "00000000");
/* Bits for each colour channel */
WriteHexString(file, "000800080008");
/* Minimum value for each component */
WriteHexString(file, "000000000000");
/* Maximum value per channel */
WriteHexString(file, "00ff00ff00ff");
/* Samples per pixel for each channel */
WriteHexString(file, "000100010001");
SDL_RWclose(file);
}
}
| 30.252294 | 127 | 0.576952 | mattwamboldt |
aa692884baa6c494ac90cfe8623264d3f6764f36 | 4,544 | hpp | C++ | src/hotspot/share/utilities/numberSeq.hpp | siweilxy/openjdkstudy | 8597674ec1d6809faf55cbee1f45f4e9149d670d | [
"Apache-2.0"
] | null | null | null | src/hotspot/share/utilities/numberSeq.hpp | siweilxy/openjdkstudy | 8597674ec1d6809faf55cbee1f45f4e9149d670d | [
"Apache-2.0"
] | null | null | null | src/hotspot/share/utilities/numberSeq.hpp | siweilxy/openjdkstudy | 8597674ec1d6809faf55cbee1f45f4e9149d670d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#ifndef SHARE_UTILITIES_NUMBERSEQ_HPP
#define SHARE_UTILITIES_NUMBERSEQ_HPP
#include "memory/allocation.hpp"
/**
** This file contains a few classes that represent number sequence,
** x1, x2, x3, ..., xN, and can calculate their avg, max, and sd.
**
** Here's a quick description of the classes:
**
** AbsSeq: abstract superclass
** NumberSeq: the sequence is assumed to be very long and the
** maximum, avg, sd, davg, and dsd are calculated over all its elements
** TruncatedSeq: this class keeps track of the last L elements
** of the sequence and calculates avg, max, and sd only over them
**/
#define DEFAULT_ALPHA_VALUE 0.7
class AbsSeq: public CHeapObj<mtInternal> {
private:
void init(double alpha);
protected:
int _num; // the number of elements in the sequence
double _sum; // the sum of the elements in the sequence
double _sum_of_squares; // the sum of squares of the elements in the sequence
double _davg; // decaying average
double _dvariance; // decaying variance
double _alpha; // factor for the decaying average / variance
// This is what we divide with to get the average. In a standard
// number sequence, this should just be the number of elements in it.
virtual double total() const { return (double) _num; };
public:
AbsSeq(double alpha = DEFAULT_ALPHA_VALUE);
virtual void add(double val); // adds a new element to the sequence
void add(unsigned val) { add((double) val); }
virtual double maximum() const = 0; // maximum element in the sequence
virtual double last() const = 0; // last element added in the sequence
// the number of elements in the sequence
int num() const { return _num; }
// the sum of the elements in the sequence
double sum() const { return _sum; }
double avg() const; // the average of the sequence
double variance() const; // the variance of the sequence
double sd() const; // the standard deviation of the sequence
double davg() const; // decaying average
double dvariance() const; // decaying variance
double dsd() const; // decaying "standard deviation"
// Debugging/Printing
virtual void dump();
virtual void dump_on(outputStream* s);
};
class NumberSeq: public AbsSeq {
private:
bool check_nums(NumberSeq* total, int n, NumberSeq** parts);
protected:
double _last;
double _maximum; // keep track of maximum value
public:
NumberSeq(double alpha = DEFAULT_ALPHA_VALUE);
virtual void add(double val);
virtual double maximum() const { return _maximum; }
virtual double last() const { return _last; }
// Debugging/Printing
virtual void dump_on(outputStream* s);
};
class TruncatedSeq: public AbsSeq {
private:
enum PrivateConstants {
DefaultSeqLength = 10
};
void init();
protected:
double *_sequence; // buffers the last L elements in the sequence
int _length; // this is L
int _next; // oldest slot in the array, i.e. next to be overwritten
public:
// accepts a value for L
TruncatedSeq(int length = DefaultSeqLength,
double alpha = DEFAULT_ALPHA_VALUE);
~TruncatedSeq();
virtual void add(double val);
virtual double maximum() const;
virtual double last() const; // the last value added to the sequence
double oldest() const; // the oldest valid value in the sequence
double predict_next() const; // prediction based on linear regression
// Debugging/Printing
virtual void dump_on(outputStream* s);
};
#endif // SHARE_UTILITIES_NUMBERSEQ_HPP
| 33.659259 | 79 | 0.72029 | siweilxy |
aa6a135b84a3c9c22aa97a1a22aeb51036d01903 | 7,005 | cpp | C++ | c/src/execution_engine.cpp | tydeu/lean4-papyrus | 02e82973a5badda26fc0f9fd15b3d37e2eb309e0 | [
"Apache-2.0"
] | 9 | 2021-07-22T11:37:59.000Z | 2022-02-23T05:39:35.000Z | c/src/execution_engine.cpp | tydeu/lean4-papyrus | 02e82973a5badda26fc0f9fd15b3d37e2eb309e0 | [
"Apache-2.0"
] | 2 | 2021-09-17T15:59:21.000Z | 2021-09-24T23:52:23.000Z | c/src/execution_engine.cpp | tydeu/lean4-papyrus | 02e82973a5badda26fc0f9fd15b3d37e2eb309e0 | [
"Apache-2.0"
] | 2 | 2021-09-06T09:45:21.000Z | 2022-03-09T12:24:53.000Z | #include "papyrus.h"
#include "papyrus_ffi.h"
#include <lean/lean.h>
#include <llvm/ExecutionEngine/GenericValue.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
using namespace llvm;
namespace papyrus {
struct EEExternal {
// The execution engine handle.
ExecutionEngine* ee;
// The modules controlled by the execution engine.
SmallVector<Module*, 1> modules;
// The error message owned by the execution engine.
std::string* errMsg;
EEExternal(ExecutionEngine* ee, std::string* errMsg)
: ee(ee), errMsg(errMsg) {}
EEExternal(const EEExternal&) = delete;
~EEExternal() {
// remove all the modules from the execution engine so they don't get deleted
for (auto it = modules.begin(), end = modules.end(); it != end; ++it) {
ee->removeModule(*it);
}
delete ee;
delete errMsg;
}
};
// Lean object class for an LLVM ExecutionEngine.
static lean_external_class* getExecutionEngineClass() {
// Use static to make this thread safe by static initialization rules.
static lean_external_class* c =
lean_register_external_class(&deleteFinalize<EEExternal>, &nopForeach);
return c;
}
// Wrap a ExecutionEngine in a Lean object.
lean_object* mkExecutionEngineRef(EEExternal* ee) {
return lean_alloc_external(getExecutionEngineClass(), ee);
}
// Get the ExecutionEngine external wrapped in an object.
EEExternal* toEEExternal(lean_object* eeRef) {
auto external = lean_to_external(eeRef);
assert(external->m_class == getExecutionEngineClass());
return static_cast<EEExternal*>(external->m_data);
}
// Get the ExecutionEngine wrapped in an object.
ExecutionEngine* toExecutionEngine(lean_object* eeRef) {
return toEEExternal(eeRef)->ee;
}
// Unpack the Lean representation of an engine kind into the LLVM one.
EngineKind::Kind unpackEngineKnd(uint8_t kind) {
return kind == 0 ? EngineKind::Either : static_cast<EngineKind::Kind>(kind);
}
//extern "C" lean_object* mk_io_user_error(lean_object* str);
// Create a new execution engine for the given module.
extern "C" lean_obj_res papyrus_execution_engine_create_for_module
(b_lean_obj_res modObj, uint8_t kindObj, b_lean_obj_res marchStr, b_lean_obj_res mcpuStr,
b_lean_obj_res mattrsObj, uint8_t optLevel, uint8_t verifyModules, lean_obj_arg /* w */)
{
// Create an engine builder
EngineBuilder builder(std::unique_ptr<Module>(toModule(modObj)));
// Configure the builder
auto errMsg = new std::string();
auto kind = unpackEngineKnd(kindObj);
builder.setEngineKind(kind);
builder.setErrorStr(errMsg);
builder.setOptLevel(static_cast<CodeGenOpt::Level>(optLevel));
builder.setVerifyModules(verifyModules);
builder.setMArch(refOfString(marchStr));
builder.setMCPU(refOfString(mcpuStr));
LEAN_ARRAY_TO_REF(std::string, stdOfString, mattrsObj, mattrs);
builder.setMAttrs(mattrs);
// Try to construct the execution engine
if (ExecutionEngine* ee = builder.create()) {
auto eee = new EEExternal(ee, errMsg);
eee->modules.push_back(toModule(modObj));
return lean_io_result_mk_ok(mkExecutionEngineRef(eee));
} else {
// Steal back the module pointer before it gets deleted
reinterpret_cast<std::unique_ptr<Module>&>(builder).release();
auto res = mkStdStringError(*errMsg);
delete errMsg;
return res;
}
return lean_io_result_mk_ok(lean_box(0));
}
// Run the given function with given arguments
// in the given execution engine and return the result.
extern "C" lean_obj_res papyrus_execution_engine_run_function
(b_lean_obj_res funRef, b_lean_obj_res eeRef, b_lean_obj_res argsObj, lean_obj_arg /* w */)
{
LEAN_ARRAY_TO_REF(GenericValue, *toGenericValue, argsObj, args);
auto ret = toExecutionEngine(eeRef)->runFunction(toFunction(funRef), args);
return lean_io_result_mk_ok(mkGenericValueRef(new GenericValue(ret)));
}
class ArgvArray {
public:
std::unique_ptr<char[]> argv;
std::vector<std::unique_ptr<char[]>> ptrs;
// Turn a Lean array of string objects
// into a nice argv style null terminated array of pointers.
void* set(PointerType* pInt8Ty, ExecutionEngine *ee, const lean_array_object* args);
};
void* ArgvArray::set
(PointerType* pInt8Ty, ExecutionEngine *ee, const lean_array_object* args)
{
auto argc = args->m_size;
unsigned ptrSize = ee->getDataLayout().getPointerSize();
argv = std::make_unique<char[]>((argc+1)*ptrSize);
ptrs.reserve(argc);
auto data = args->m_data;
for (unsigned i = 0; i != argc; ++i) {
auto str = lean_to_string(data[i]);
// copy the string so that the user may edit it
auto ptr = std::make_unique<char[]>(str->m_size);
std::copy(str->m_data, str->m_data + str->m_size, ptr.get());
// endian safe: argv[i] = ptr.get()
ee->StoreValueToMemory(PTOGV(ptr.get()),
(GenericValue*)(&argv[i*ptrSize]), pInt8Ty);
// pointer will be deallocated when the `ArgvArray` is
ptrs.push_back(std::move(ptr));
}
// null terminate the array
ee->StoreValueToMemory(PTOGV(nullptr),
(GenericValue*)(&argv[argc*ptrSize]), pInt8Ty);
return argv.get();
}
/*
A helper function to wrap the behavior of `runFunction`
to handle common task of starting up a `main` function with the usual
`argc`, `argv`, and `envp` parameters.
Instead of using LLVM's `runFunctionAsMain` directly,
we adapt its code to Lean's data structures.
*/
extern "C" lean_obj_res papyrus_execution_engine_run_function_as_main
(b_lean_obj_res funRef, b_lean_obj_res eeRef, b_lean_obj_res argsObj, b_lean_obj_res envObj, lean_obj_arg /* w */)
{
auto fn = toFunction(funRef);
auto fnTy = fn->getFunctionType();
auto& ctx = fnTy->getContext();
auto fnArgc = fnTy->getNumParams();
auto pInt8Ty = Type::getInt8PtrTy(ctx);
auto ppInt8Ty = pInt8Ty->getPointerTo();
if (fnArgc > 3)
return mkStdStringError("Invalid number of arguments of main() supplied");
if (fnArgc >= 3 && fnTy->getParamType(2) != ppInt8Ty)
return mkStdStringError("Invalid type for third argument of main() supplied");
if (fnArgc >= 2 && fnTy->getParamType(1) != ppInt8Ty)
return mkStdStringError("Invalid type for second argument of main() supplied");
if (fnArgc >= 1 && !fnTy->getParamType(0)->isIntegerTy(32))
return mkStdStringError("Invalid type for first argument of main() supplied");
if (!fnTy->getReturnType()->isIntegerTy() && !fnTy->getReturnType()->isVoidTy())
return mkStdStringError("Invalid return type of main() supplied");
ArgvArray argv, env;
GenericValue fnArgs[fnArgc];
auto ee = toExecutionEngine(eeRef);
if (fnArgc > 0) {
auto argsArr = lean_to_array(argsObj);
fnArgs[0].IntVal = APInt(32, argsArr->m_size); // argc
if (fnArgc > 1) {
fnArgs[1].PointerVal = argv.set(pInt8Ty, ee, argsArr);
if (fnArgc > 2) {
fnArgs[2].PointerVal = env.set(pInt8Ty, ee, lean_to_array(envObj));
}
}
}
auto gRc = ee->runFunction(toFunction(funRef), ArrayRef<GenericValue>(fnArgs, fnArgc));
return lean_io_result_mk_ok(lean_box_uint32(gRc.IntVal.getZExtValue()));
}
} // end namespace papyrus
| 35.739796 | 116 | 0.725625 | tydeu |
aa73fecb37a3add45e0a9b2ef8f5062701f7bba1 | 1,763 | cpp | C++ | private/shell/applets/taskmgr/deadcode.cpp | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | 11 | 2017-09-02T11:27:08.000Z | 2022-01-02T15:25:24.000Z | private/shell/applets/taskmgr/deadcode.cpp | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | null | null | null | private/shell/applets/taskmgr/deadcode.cpp | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | 14 | 2019-01-16T01:01:23.000Z | 2022-02-20T15:54:27.000Z | // CODE WHICH I REMOVED BUT THAT I'M AFRAID TO THROW AWAY IN CASE I NEED IT
//
// NOT IN THE BUILD
/*++ CPerfPage::DrawLegend
Routine Description:
Draws the legend on the performance page
Arguments:
lpdi - LPDRAWITEMSTRUCT describing area we need to paint
Return Value:
Revision History:
Jan-18-95 Davepl Created
--*/
void CPerfPage::DrawLegend(LPDRAWITEMSTRUCT lpdi)
{
int xPos = 10; // X pos for drawing
const int yLine = 6; // Y pos for drawing the lines
const int yText = 0; // Y pos for drawing the text
const int LineLen = 10; // Length of legend lines
FillRect(lpdi->hDC, &lpdi->rcItem, (HBRUSH) GetStockObject(GRAPH_BRUSH));
SetBkColor(lpdi->hDC, RGB(0,0,0));
SetTextColor(lpdi->hDC, aColors[MEM_PEN]);
SelectObject(lpdi->hDC, m_hPens[MEM_PEN]);
MoveToEx(lpdi->hDC, xPos, yLine, (LPPOINT) NULL);
xPos += LineLen;
LineTo(lpdi->hDC, xPos, yLine);
xPos += 5;
xPos = TextToLegend(lpdi->hDC, xPos, yText, g_szMemUsage) + 10;
{
static const LPCTSTR pszLabels[2] = { g_szTotalCPU, g_szKernelCPU };
for (int i = 0; i < 2; i++)
{
SetTextColor(lpdi->hDC, aColors[i]);
SelectObject(lpdi->hDC, m_hPens[i]);
MoveToEx(lpdi->hDC, xPos, yLine, (LPPOINT) NULL);
xPos += LineLen;
LineTo(lpdi->hDC, xPos, yLine);
xPos += 5;
xPos = TextToLegend(lpdi->hDC, xPos, yText, pszLabels[i]) + 10;
// Don't both with the kernel legend unless needed
if (FALSE == g_Options.m_fKernelTimes)
{
break;
}
}
}
}
| 25.926471 | 78 | 0.560408 | King0987654 |
aa758cb0138d5f90c4021b9915746cbb16252dd4 | 2,457 | cpp | C++ | src/engine/Scrap.cpp | m1cr0lab-gamebuino/apollo | 79c71d0ca44301d05d284a7f2bc5137fe80c911a | [
"MIT"
] | 1 | 2021-07-28T12:35:52.000Z | 2021-07-28T12:35:52.000Z | src/engine/Scrap.cpp | m1cr0lab-gamebuino/apollo | 79c71d0ca44301d05d284a7f2bc5137fe80c911a | [
"MIT"
] | null | null | null | src/engine/Scrap.cpp | m1cr0lab-gamebuino/apollo | 79c71d0ca44301d05d284a7f2bc5137fe80c911a | [
"MIT"
] | null | null | null | /**
* -------------------------------------------------------------------------
* Apollo
* -------------------------------------------------------------------------
* a tiny game for the Gamebuino META retro gaming handheld
* inspired by the famous Lunar Lander
* https://youtu.be/McAhSoAEbhM
* https://en.wikipedia.org/wiki/Lunar_Lander_(1979_video_game)
* -------------------------------------------------------------------------
* © 2021 Steph @ m1cr0lab
* https://gamebuino.m1cr0lab.com
* -------------------------------------------------------------------------
*/
#include <Gamebuino-Meta.h>
#include "Scrap.h"
#include "../data/assets.h"
#include "../data/config.h"
void Scrap::init(float_t x, float_t y, float_t radius, float_t vx, float_t vy, float_t vrot) {
_x = x;
_y = y;
_r = radius;
_vx = vx;
_vy = vy;
_rot = 0;
_vrot = vrot;
uint8_t n = VERTICE_NB << 1;
for (uint8_t i=0; i<n; i+=2) {
_vertice[i] = radius * .1f * random(4, 11);
_vertice[i+1] = i * 2*PI / VERTICE_NB;
}
_visible = true;
}
void Scrap::draw(Camera &camera) {
if (!_visible) return;
float_t cx = camera.ox();
float_t cy = camera.oy();
float_t cz = camera.zoom();
float_t r = _vertice[0];
float_t a = _vertice[1] + _rot;
float_t x0 = _x + r*cos(a), x1 = x0;
float_t y0 = _y + r*sin(a), y1 = y0;
float_t x2, y2;
uint8_t n = VERTICE_NB << 1;
gb.display.setColor(COLOR_APOLLO);
for (uint8_t i=2; i<n; i+=2) {
r = _vertice[i];
a = _vertice[i+1] + _rot;
x2 = _x + r*cos(a);
y2 = _y + r*sin(a);
gb.display.drawLine(
cz * (x1 - cx),
cz * (y1 - cy),
cz * (x2 - cx),
cz * (y2 - cy)
);
x1 = x2;
y1 = y2;
}
gb.display.drawLine(
cz * (x0 - cx),
cz * (y0 - cy),
cz * (x2 - cx),
cz * (y2 - cy)
);
}
void Scrap::loop() {
if (!_visible) return;
_rot += _vrot;
if (_rot < 0) _rot += 2*PI;
else if (_rot > 2*PI) _rot -= 2*PI;
_vy += GRAVITY;
_x += _vx;
_y += _vy;
_visible = !(
_x + _r < 0
|| _x > _r + SCREEN_WIDTH
|| _y + _r < 0
|| _y > _r + SCREEN_HEIGHT
);
} | 21.743363 | 94 | 0.406186 | m1cr0lab-gamebuino |
aa7a2fcd8bf0b9f7a98b3ed7882b6772e93e279c | 2,128 | cpp | C++ | Image_editor/Image_editor.cpp | Aroidzap/VUT-FIT-IPA-Project-2017-2018 | c199b3165a1e282f78d3afb7104f35772b13ca6c | [
"MIT"
] | 1 | 2017-12-05T09:25:09.000Z | 2017-12-05T09:25:09.000Z | Image_editor/Image_editor.cpp | Aroidzap/VUT-FIT-IPA-Project-2017-2018 | c199b3165a1e282f78d3afb7104f35772b13ca6c | [
"MIT"
] | null | null | null | Image_editor/Image_editor.cpp | Aroidzap/VUT-FIT-IPA-Project-2017-2018 | c199b3165a1e282f78d3afb7104f35772b13ca6c | [
"MIT"
] | null | null | null | /*Sablona pro projekty do predmetu IPA, tema graficky editor
*Autor: Tomas Goldmann, igoldmann@fit.vutbr.cz
*
*LOGIN STUDENTA: xpazdi02
*/
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include <intrin.h>
#include <inttypes.h>
#include <windows.h>
#include "ipa_tool.h"
#define WIN_WIDTH 800.0f
#define PROJECT_NAME "IPA - graficky editor 2017"
#define PROJECT_NAME_WIN_IN "IPA - graficky editor 2017-IN"
#define PROJECT_NAME_WIN_OUT "IPA - graficky editor 2017-OUT"
using namespace cv;
using namespace std;
typedef void(*Ipa_algorithm)(unsigned char *input_data, unsigned char *output_data, unsigned int width, unsigned int height, int argc, char** argv);
int main(int argc, char** argv)
{
unsigned __int64 cycles_start = 0;
if (argc < 2)
{
cout << " Usage: display_image ImageToLoadAndDisplay" << endl;
return -1;
}
Mat output, window_img,image;
image = imread(argv[1], CV_LOAD_IMAGE_COLOR);
if (!image.data)
{
cout << "Could not open or find the image" << std::endl;
return -1;
}
//koeficient pro prijatelne vykresleni
float q = WIN_WIDTH / static_cast<float>(image.cols);
//vytvoreni vystupniho obrazu
image.copyTo(output);
cv::resize(image, window_img, cv::Size(static_cast<int>(q*image.cols), static_cast<int>(q*image.rows)));
namedWindow(PROJECT_NAME_WIN_IN, WINDOW_AUTOSIZE);
imshow(PROJECT_NAME_WIN_IN, window_img);
HINSTANCE hInstLibrary = LoadLibrary("Student_DLL.dll");
if (!hInstLibrary)
{
std::cout << "DLL Failed To Load!" << std::endl;
return EXIT_FAILURE;
}
else
{
//Algoritmus
InstructionCounter counter;
Ipa_algorithm f;
f = (Ipa_algorithm)GetProcAddress(hInstLibrary, "ipa_algorithm");
if (f)
{
counter.start();
f(image.data, output.data,image.cols, image.rows, argc, argv);
counter.print();
}
}
namedWindow(PROJECT_NAME_WIN_OUT, WINDOW_AUTOSIZE);
cv::resize(output, output, cv::Size(static_cast<int>(q*image.cols), static_cast<int>(q*image.rows)));
imshow(PROJECT_NAME_WIN_OUT, output);
waitKey(0);
FreeLibrary(hInstLibrary);
return 0;
} | 24.181818 | 148 | 0.725094 | Aroidzap |
aa7ea9942eea6c68e96e262a7e4187e7dbf935bc | 2,981 | hh | C++ | src/cpu/tcu-accel/ctxswsm.hh | Barkhausen-Institut/gem5-TCU | c3c86be12debec937b9b5dd351df13e5ea43ab4a | [
"BSD-3-Clause"
] | null | null | null | src/cpu/tcu-accel/ctxswsm.hh | Barkhausen-Institut/gem5-TCU | c3c86be12debec937b9b5dd351df13e5ea43ab4a | [
"BSD-3-Clause"
] | null | null | null | src/cpu/tcu-accel/ctxswsm.hh | Barkhausen-Institut/gem5-TCU | c3c86be12debec937b9b5dd351df13e5ea43ab4a | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (C) 2015-2018 Nils Asmussen <nils@os.inf.tu-dresden.de>
* Copyright (C) 2019-2021 Nils Asmussen, Barkhausen Institut
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of the FreeBSD Project.
*/
#ifndef __CPU_TCU_ACCEL_CTXSWSM_HH__
#define __CPU_TCU_ACCEL_CTXSWSM_HH__
#include "cpu/tcu-accel/accelerator.hh"
#include "sim/system.hh"
class AccelCtxSwSM
{
static const uint64_t OUR_VPE = 0xFFFF;
static const size_t RBUF_ADDR = 0x3FF040;
static const unsigned EP_RECV = 6;
static const size_t MSG_SIZE = 64;
enum Operation
{
VPE_INIT,
VPE_CTRL,
MAP,
TRANSLATE,
REM_MSGS,
EP_INVAL,
DERIVE_QUOTA,
GET_QUOTA,
SET_QUOTA,
REMOVE_QUOTAS,
RESET_STATS,
};
enum VPECtrl
{
START,
STOP,
};
enum State
{
FETCH_MSG,
FETCH_MSG_WAIT,
READ_MSG_ADDR,
READ_MSG,
STORE_REPLY,
SEND_REPLY,
REPLY_WAIT,
};
struct M5_ATTR_PACKED
{
uint64_t res;
uint64_t val1;
uint64_t val2;
} reply;
public:
explicit AccelCtxSwSM(TcuAccel *_accel);
std::string stateName() const;
bool hasStateChanged() const { return stateChanged; }
void restart() { state = FETCH_MSG; }
PacketPtr tick();
bool handleMemResp(PacketPtr pkt);
private:
TcuAccel *accel;
State state;
bool stateChanged;
bool switched;
Addr msgAddr;
uint64_t vpe_id;
};
#endif /* __CPU_TCU_ACCEL_CTXSWSM_HH__ */
| 26.855856 | 79 | 0.690037 | Barkhausen-Institut |
aa858e4f2c43750d17170246373af43e794a147c | 1,028 | cpp | C++ | Data Structures/Merge two sorted linked lists.cpp | rahamath2009/git-github.com-nishant-sethi-HackerRank | 14d9bd3e772a863aceba22d9a3361a8325cca4bc | [
"Apache-2.0"
] | 76 | 2018-06-28T04:29:14.000Z | 2022-03-21T01:57:27.000Z | Data Structures/Merge two sorted linked lists.cpp | rahamath2009/git-github.com-nishant-sethi-HackerRank | 14d9bd3e772a863aceba22d9a3361a8325cca4bc | [
"Apache-2.0"
] | 31 | 2018-10-01T09:12:05.000Z | 2022-03-08T23:39:01.000Z | Data Structures/Merge two sorted linked lists.cpp | rahamath2009/git-github.com-nishant-sethi-HackerRank | 14d9bd3e772a863aceba22d9a3361a8325cca4bc | [
"Apache-2.0"
] | 44 | 2018-07-09T11:31:20.000Z | 2022-01-12T19:21:20.000Z | /*
Merge two sorted lists A and B as one linked list
Node is defined as
struct Node
{
int data;
struct Node *next;
}
*/
Node* MergeLists(Node *headA, Node* headB)
{
// This is a "method-only" submission.
// You only need to complete this method
Node *head=NULL, *cur,*prev = NULL;
Node *curA,*curB;
head = headA;
cur = head;
curB = headB;
while(curB !=NULL){
if(cur== NULL){
head = headB;
break;
}else{ if(cur->data > curB->data){
curA = curB;
curB = curB->next;
curA->next = cur;
if(prev == NULL){
head = curA;
}else{
prev->next = curA;
}
prev = cur;
cur = cur->next;
}else{
if(cur->next !=NULL){
prev = cur;
cur = cur->next;
}else{
cur->next = curB;
break;
}
}}
}return head;
} | 23.363636 | 54 | 0.42607 | rahamath2009 |
aa8820758c4bd30b2af0aaa56aa2d5004e8bb278 | 2,571 | cpp | C++ | UVa/UVA - 190/Accepted (4).cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | 1 | 2022-02-11T16:55:36.000Z | 2022-02-11T16:55:36.000Z | UVa/UVA - 190/Accepted (4).cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | UVa/UVA - 190/Accepted (4).cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | /****************************************************************************************
* @author: kzvd4729 created: 2017-10-13 13:03:12
* solution_verdict: Accepted language: C++
* run_time: 0 memory_used:
* problem: https://vjudge.net/problem/UVA-190
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
double s1,s2;
struct point
{
double x;
double y;
}center,a,b,c;
struct equation
{
double qx;
double qy;
double cn;
}e1,e2;
double dist(point aa,point bb)
{
return sqrt((aa.x-bb.x)*(aa.x-bb.x)+(aa.y-bb.y)*(aa.y-bb.y));
}
void solve_equation(void)
{
double D=(e1.qx*e2.qy)-(e1.qy*e2.qx);
double Dx=(e1.cn*e2.qy)-(e1.qy*e2.cn);
double Dy=(e1.qx*e2.cn)-(e1.cn*e2.qx);
center.x=Dx/D;
center.y=Dy/D;
}
void print(void)
{
double r1=dist(center,a);
if(r1<0)center.x*=-1,center.y*=-1;
cout<<"(x";
if(center.x>=0)cout<<" - ";
else cout<<" + ";
cout<<setprecision(3)<<fixed<<fabs(center.x);
cout<<")^2 + (y";
if(center.y>=0)cout<<" - ";
else cout<<" + ";
cout<<setprecision(3)<<fixed<<fabs(center.y);
cout<<")^2 = ";
cout<<setprecision(3)<<fixed<<fabs(r1);
cout<<"^2"<<endl;
double hx=-2*center.x;
double yk=-2*center.y;
double cns=center.x*center.x+center.y*center.y-r1*r1;
cout<<"x^2 + y^2";
if(hx>=0)cout<<" + ";
else cout<<" - ";
cout<<setprecision(3)<<fixed<<fabs(hx)<<"x";
if(yk>=0)cout<<" + ";
else cout<<" - ";
cout<<setprecision(3)<<fixed<<fabs(yk)<<"y";
if(cns>=0)cout<<" + ";
else cout<<" - ";
cout<<setprecision(3)<<fixed<<fabs(cns);
cout<<" = 0"<<endl<<endl;
}
int main()
{
///ofstream cout("out.txt");
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
while(cin>>a.x>>a.y>>b.x>>b.y>>c.x>>c.y)
{
point mid1;
mid1.x=(a.x+b.x)/2.0;
mid1.y=(a.y+b.y)/2.0;
s1=(1/((a.y-b.y)/(a.x-b.x)))*(-1);
e1.cn=mid1.y-s1*mid1.x;
e1.qx=-s1;
e1.qy=1;
point mid2;
mid2.x=(b.x+c.x)/2.0;
mid2.y=(b.y+c.y)/2.0;
s2=(1/((b.y-c.y)/(b.x-c.x)))*(-1);
e2.cn=mid2.y-s2*mid2.x;
e2.qx=-s2;
e2.qy=1;
solve_equation();
print();
}
return 0;
} | 24.485714 | 111 | 0.439129 | kzvd4729 |
aa8d44e6b8873f26185035812f46c6b84a16c02b | 3,723 | hpp | C++ | libvast/vast/bloom_filter_synopsis.hpp | krionbsd/vast | c9fbc7230cac21886cf9d032e57b752276ba7ff7 | [
"BSD-3-Clause"
] | 249 | 2019-08-26T01:44:45.000Z | 2022-03-26T14:12:32.000Z | libvast/vast/bloom_filter_synopsis.hpp | krionbsd/vast | c9fbc7230cac21886cf9d032e57b752276ba7ff7 | [
"BSD-3-Clause"
] | 586 | 2019-08-06T13:10:36.000Z | 2022-03-31T08:31:00.000Z | libvast/vast/bloom_filter_synopsis.hpp | krionbsd/vast | c9fbc7230cac21886cf9d032e57b752276ba7ff7 | [
"BSD-3-Clause"
] | 37 | 2019-08-16T02:01:14.000Z | 2022-02-21T16:13:59.000Z | // _ _____ __________
// | | / / _ | / __/_ __/ Visibility
// | |/ / __ |_\ \ / / Across
// |___/_/ |_/___/ /_/ Space and Time
//
// SPDX-FileCopyrightText: (c) 2020 The VAST Contributors
// SPDX-License-Identifier: BSD-3-Clause
#pragma once
#include "vast/bloom_filter.hpp"
#include "vast/detail/legacy_deserialize.hpp"
#include "vast/synopsis.hpp"
#include "vast/type.hpp"
#include <caf/deserializer.hpp>
#include <caf/optional.hpp>
#include <caf/serializer.hpp>
#include <optional>
namespace vast {
/// A Bloom filter synopsis.
template <class T, class HashFunction>
class bloom_filter_synopsis : public synopsis {
public:
using bloom_filter_type = bloom_filter<HashFunction>;
using hasher_type = typename bloom_filter_type::hasher_type;
bloom_filter_synopsis(vast::type x, bloom_filter_type bf)
: synopsis{std::move(x)}, bloom_filter_{std::move(bf)} {
// nop
}
void add(data_view x) override {
VAST_ASSERT(caf::holds_alternative<view<T>>(x), "invalid data");
bloom_filter_.add(caf::get<view<T>>(x));
}
[[nodiscard]] std::optional<bool>
lookup(relational_operator op, data_view rhs) const override {
switch (op) {
default:
return {};
case relational_operator::equal:
// TODO: We should treat 'nil' as a normal value and
// hash it, so we can exclude synopsis where all values
// are non-nil.
if (caf::holds_alternative<view<caf::none_t>>(rhs))
return {};
if (!caf::holds_alternative<view<T>>(rhs))
return false;
return bloom_filter_.lookup(caf::get<view<T>>(rhs));
case relational_operator::in: {
if (auto xs = caf::get_if<view<list>>(&rhs)) {
for (auto x : **xs) {
if (caf::holds_alternative<view<caf::none_t>>(x))
return {};
if (!caf::holds_alternative<view<T>>(x))
continue;
if (bloom_filter_.lookup(caf::get<view<T>>(x)))
return true;
}
return false;
}
return {};
}
}
}
[[nodiscard]] bool equals(const synopsis& other) const noexcept override {
if (typeid(other) != typeid(bloom_filter_synopsis))
return false;
auto& rhs = static_cast<const bloom_filter_synopsis&>(other);
return this->type() == rhs.type() && bloom_filter_ == rhs.bloom_filter_;
}
[[nodiscard]] size_t memusage() const override {
return bloom_filter_.memusage();
}
caf::error serialize(caf::serializer& sink) const override {
return sink(bloom_filter_);
}
caf::error deserialize(caf::deserializer& source) override {
return source(bloom_filter_);
}
bool deserialize(vast::detail::legacy_deserializer& source) override {
return source(bloom_filter_);
}
protected:
bloom_filter<HashFunction> bloom_filter_;
};
// Because VAST deserializes a synopsis with empty options and
// construction of an address synopsis fails without any sizing
// information, we augment the type with the synopsis options.
/// Creates a new type annotation from a set of bloom filter parameters.
/// @returns The provided type with a new `#synopsis=bloom_filter(n,p)`
/// attribute. Note that all previous attributes are discarded.
type annotate_parameters(const type& type,
const bloom_filter_parameters& params);
/// Parses Bloom filter parameters from type attributes of the form
/// `#synopsis=bloom_filter(n,p)`.
/// @param x The type whose attributes to parse.
/// @returns The parsed and evaluated Bloom filter parameters.
/// @relates bloom_filter_synopsis
std::optional<bloom_filter_parameters> parse_parameters(const type& x);
} // namespace vast
| 31.820513 | 76 | 0.659952 | krionbsd |
aa8e1e5f59c0290cf380add3b9c0bec92a63f80a | 16,191 | cpp | C++ | src/BezierScheme.cpp | Junology/bord2 | 0068885144032d4a8e30c6f2c5898918d00b1d8f | [
"MIT"
] | null | null | null | src/BezierScheme.cpp | Junology/bord2 | 0068885144032d4a8e30c6f2c5898918d00b1d8f | [
"MIT"
] | null | null | null | src/BezierScheme.cpp | Junology/bord2 | 0068885144032d4a8e30c6f2c5898918d00b1d8f | [
"MIT"
] | null | null | null | /*!
* \file BezierScheme.cpp
* \author Jun Yoshida
* \copyright (c) 2020 Jun Yoshida.
* The project is released under the MIT License.
* \date February 23, 2020: created
*/
#include "BezierScheme.hpp"
#include <set>
#include <thread>
#include <mutex>
#include <iostream>
using BezierSequence = typename BezierScheme::BezierSequence;
//* Debug
static std::mutex ostr_mutex;
// */
/*********************************************************!
* Information on cutting a sequence of Bezier curves.
*********************************************************/
struct BezierCutter {
size_t index;
double param;
//! \name Comparison operators.
//@{
constexpr bool operator==(BezierCutter const& rhs) const noexcept {
return index == rhs.index && param == rhs.param;
}
constexpr bool operator<(BezierCutter const& rhs) const noexcept {
return index < rhs.index || (index == rhs.index && param < rhs.param);
}
constexpr bool operator>(BezierCutter const& rhs) const noexcept {
return rhs < *this;
}
constexpr bool operator<=(BezierCutter const& rhs) const noexcept {
return !(*this > rhs);
}
constexpr bool operator>=(BezierCutter const& rhs) const noexcept {
return !(*this < rhs);
}
//@}
};
/**********************************!
* Cut a sequence of Bezier curves
**********************************/
void cutoutBezSeq(BezierSequence const& src,
std::set<BezierCutter> const& cutters,
std::vector<BezierSequence> & out)
{
BezierCutter lastcut{0, 0.0};
bool carryover = false;
// Traverse all cuts.
for(auto& cut : cutters) {
if(cut <= lastcut)
continue;
// Append the Bezier curves in the given sequence that are irrelevant to cutting.
if (carryover) {
if (lastcut.index + 1 < cut.index)
out.back().insert(
out.back().end(),
std::next(src.begin(), lastcut.index+1),
std::next(src.begin(), cut.index));
}
else {
out.emplace_back(
std::next(src.begin(), lastcut.index),
std::next(src.begin(), cut.index));
}
// Divide the Bezier curve in the specified index.
auto bezdiv = (lastcut.index == cut.index && carryover)
? out.back().back().divide(
(cut.param - lastcut.param)/(1.0 - lastcut.param) )
: src[cut.index].divide(cut.param);
// Append the first half.
if(cut.param > 0.0) {
if(lastcut.index == cut.index && carryover) {
out.back().back() = bezdiv.first;
}
else {
out.back().push_back(bezdiv.first);
}
}
// If the division actually divides the curve, carry over the latter half to the next step.
if(cut.param < 1.0) {
out.emplace_back(1, bezdiv.second);
carryover = true;
lastcut = cut;
}
else {
carryover = false;
lastcut = {cut.index+1, 0.0};
}
}
// If there are remaining parts, add them.
if(carryover && lastcut.index+1 < src.size()) {
out.back().insert(
out.back().end(),
std::next(src.begin(), lastcut.index+1),
src.end() );
}
else if (!carryover && lastcut.index < src.size()) {
out.emplace_back(
std::next(src.begin(), lastcut.index),
src.end() );
}
}
/*******************************************************************!
* Computes cuttings of an under-strand of crossing Bezier curves.
* \param f A function-like object computing the "height" of signature
* > double(bool,BezierCutter const&)
* where the first parameter indicates which we are looking at; LHS (true) or RHS (false).
*******************************************************************/
template <class BezierT, class F>
auto crosscut(std::vector<BezierT> const& lhs,
std::vector<BezierT> const& rhs,
F const& f,
std::atomic_bool const& flag = std::atomic_bool{true}
)
-> std::pair<std::set<BezierCutter>,std::set<BezierCutter>>
{
static_assert(
std::is_same<typename BezierTraits<BezierT>::vertex_type, Eigen::Vector2d>::value,
"The control points must be of type Eigen::Vector2d.");
bool to_be_continued = true;
auto result = std::make_pair(
std::set<BezierCutter>{}, std::set<BezierCutter>{} );
// Traverse all parings.
for(size_t i = 0; i < lhs.size() && to_be_continued; ++i) {
for(size_t j = 0; j < rhs.size() && to_be_continued; ++j) {
auto crosses = intersect<12,3>(
lhs[i], rhs[j],
[&flag]() -> bool {
return flag.load(std::memory_order_acquire);
} );
for(auto& params : crosses) {
// Compute the heights at the crossing in the projections.
double lhei = f(true, BezierCutter{i, params.first});
double rhei = f(false, BezierCutter{j, params.second});
// Append the parameter of the under-strand.
if (lhei < rhei)
result.first.insert(BezierCutter{i, params.first});
else
result.second.insert(BezierCutter{j, params.second});
}
to_be_continued = flag.load(std::memory_order_acquire);
}
}
return result;
}
/*******************************************************************!
* Computes cuttings of an under-strand in self-crossing.
* \param f A function-like object computing the "height" of signature
* > double(BezierCutter const&)
*******************************************************************/
template <class BezierT, class F>
auto crosscut_self(std::vector<BezierT> const& bezseq,
F const& f,
std::atomic_bool const &flag = std::atomic_bool{true}
)
-> std::set<BezierCutter>
{
static_assert(
std::is_same<typename BezierTraits<BezierT>::vertex_type, Eigen::Vector2d>::value,
"The control points must be of type Eigen::Vector2d.");
bool to_be_continued = true;
std::set<BezierCutter> result{};
// Traverse all parings.
for(size_t i = 0; i < bezseq.size() && to_be_continued; ++i) {
for(size_t j = i+1; j < bezseq.size() && to_be_continued; ++j) {
auto crosses = intersect<12,3>(
bezseq[i], bezseq[j],
[&flag]() -> bool {
return flag.load(std::memory_order_acquire);
});
for(auto& params : crosses) {
// Compute the heights at the crossing in the projections.
double lhei = f(BezierCutter{i, params.first});
double rhei = f(BezierCutter{j, params.second});
// Append the parameter of the under-strand.
if (lhei < rhei)
result.insert(BezierCutter{i, params.first});
else
result.insert(BezierCutter{j, params.second});
}
to_be_continued = flag.load(std::memory_order_acquire);
}
}
return result;
}
/*********************************************************************!
* Implementation of getProject member function of BezierScheme class
* This function should return as soon as possible when the value of the argument flag becomes false.
*********************************************************************/
auto getProject_impl(
std::vector<BezierSequence> const& bezseqs,
Eigen::Matrix3d const& basis,
std::atomic_bool const& flag = std::atomic_bool{true}
)
-> std::vector<BezierSequence>
{
// Type aliases.
using BezierVarType = BezierScheme::BezierVarType;
using BezierProjected = typename BezierTraits<BezierVarType>::template converted_type<Eigen::Vector2d>;
// 2d projected Bezier sequences
std::vector<std::vector<BezierProjected>> bezseqs_2d(
bezseqs.size(),
std::vector<BezierProjected>{} );
for(size_t i = 0; i < bezseqs.size(); ++i) {
std::transform(
bezseqs[i].begin(), bezseqs[i].end(),
std::back_inserter(bezseqs_2d[i]),
[&basis](BezierVarType const& bez3d) -> BezierProjected {
return bez3d.convert(
[&basis](Eigen::Vector3d const& v) -> Eigen::Vector2d {
return basis.block<2,3>(0,0) * v;
} );
} );
}
std::vector<std::set<BezierCutter>> cutters(
bezseqs.size(), std::set<BezierCutter>{} );
/* Debug
std::cout << __FILE__":" << __LINE__ << std::endl;
std::cout << "In Thread: " << std::this_thread::get_id() << std::endl;
// */
/* Compute the self-crossings concurrently.*/
{
std::vector<std::thread> workers;
for(size_t i = 0; i < bezseqs.size(); ++i) {
workers.emplace_back(
[&cuts=cutters[i],
&bezseq_2d=bezseqs_2d[i],
&bezseq=bezseqs[i],
&basis,
&flag,
/* Debug */ i]
{
/* Debug
{
std::lock_guard<std::mutex> _(ostr_mutex);
std::cout << __FILE__":" << __LINE__ << std::endl;
std::cout << "Launch the Thread: "
<< std::this_thread::get_id() << std::endl;
std::cout << "Computing self-crossings of " << i << std::endl;
}
// */
auto selfcuts = crosscut_self(
bezseq_2d,
[&bezseq, &basis](BezierCutter const& cut) -> double
{
return -basis.row(2)*bezseq[cut.index].eval(cut.param);
}, flag );
cuts.insert(
std::make_move_iterator(selfcuts.begin()),
std::make_move_iterator(selfcuts.end()));
/* Debug
{
std::lock_guard<std::mutex> _(ostr_mutex);
std::cout << __FILE__":" << __LINE__ << std::endl;
std::cout << "Finish the Thread: "
<< std::this_thread::get_id() << std::endl;
std::cout << "Finish self-crossings of " << i << std::endl;
}
// */
} );
}
for(auto& worker : workers)
worker.join();
}
/*** Compute crossings of different strands. ***/
{
// Mutexex for Bezier sequences.
std::vector<std::mutex> mutexes(bezseqs.size());
// Thread computing crossings of Bezier sequences.
std::vector<std::thread> workers;
workers.reserve(bezseqs.size()*(bezseqs.size()-1)/2);
for(size_t stride = 1; stride < bezseqs.size(); ++stride) {
for(size_t i = 0; i+stride < bezseqs.size(); ++i) {
/* Debug
std::cout << __FILE__":" << __LINE__ << std::endl;
std::cout << "i=" << i
<< " vs i+stride=" << i+stride
<< std::endl;
// */
workers.emplace_back(
[&cutsL = cutters[i], &cutsR = cutters[i+stride],
&lhs2d = bezseqs_2d[i], &rhs2d = bezseqs_2d[i+stride],
&lhs = bezseqs[i], &rhs = bezseqs[i+stride],
&basis,
&mutexL = mutexes[i], &mutexR = mutexes[i+stride],
&flag,
/*Debug*/ i, /*Debug*/ j=i+stride]()
{
/* Debug
{
std::lock_guard<std::mutex> _(ostr_mutex);
std::cout << __FILE__":" << __LINE__ << std::endl;
std::cout << "Launch the Thread: "
<< std::this_thread::get_id() << std::endl;
std::cout << "Computing crossings of " << i << " and " << j << std::endl;
}
// */
auto crscuts = crosscut(
lhs2d, rhs2d,
[&lhs, &rhs, &basis](bool flag, BezierCutter const& cut) -> double {
return -basis.row(2)*(flag ? lhs[cut.index].eval(cut.param) : rhs[cut.index].eval(cut.param));
}, flag);
{
std::lock_guard<std::mutex> gurdL(mutexL);
cutsL.insert(
std::make_move_iterator(crscuts.first.begin()),
std::make_move_iterator(crscuts.first.end()) );
}
{
std::lock_guard<std::mutex> gurdR(mutexR);
cutsR.insert(
std::make_move_iterator(crscuts.second.begin()),
std::make_move_iterator(crscuts.second.end()) );
}
/* Debug
{
std::lock_guard<std::mutex> _(ostr_mutex);
std::cout << __FILE__":" << __LINE__ << std::endl;
std::cout << "Finish the Thread: "
<< std::this_thread::get_id() << std::endl;
std::cout << "Finish " << i << " and " << j << std::endl;
}
// */
} );
}
}
// Wait for the computations.
for(auto& worker : workers)
worker.join();
}
// Cut-out the sequences of Bezier curves and write the results
std::vector<BezierSequence> result{};
result.reserve(bezseqs.size());
for(size_t i = 0; i < bezseqs.size() && flag.load(std::memory_order_acquire); ++i) {
/* Debug
std::cout << __FILE__":" << __LINE__ << std::endl;
std::cout << "i=" << i
<< " #cuts=" << cutters[i].size()
<< std::endl;
// */
cutoutBezSeq(bezseqs[i], cutters[i], result);
}
return result;
}
/******************************
* BezierScheme::getProject
******************************/
auto BezierScheme::getProject(
Eigen::Matrix<double,2,3> const& prmat,
std::function<void(void)> fun
) const
-> std::future<std::vector<BezierSequence>>
{
std::promise<std::vector<BezierSequence>> p;
auto fut = p.get_future();
Eigen::RowVector3d kernel = prmat.row(0).cross(prmat.row(1));
// If the depth vector is the zero vector, return immediately.
if (kernel.isZero()) {
std::cerr << __FILE__":" << __LINE__ << std::endl;
std::cerr << "Projection direction is zero vector." << std::endl;
p.set_value({});
return fut;
}
// Compute a projection matrix onto the plane.
// Notice that the result depends not on this projection but only on the kernel.
Eigen::Matrix3d basis;
kernel.normalize();
basis.block<2,3>(0,0) = prmat;
basis.row(2) = kernel;
terminate();
m_to_be_computed.store(true);
m_computer = std::thread(
[basis, bezseqs=m_bezseqs, p=std::move(p), f=std::move(fun), &flag=m_to_be_computed]() mutable
{
p.set_value_at_thread_exit(
getProject_impl(bezseqs, basis, flag));
// p.set_value(getProject_impl(bezseqs, basis, flag));
// Invoke f() if the computation successfully finished.
if(flag.load(std::memory_order_acquire))
f();
} );
return fut;
}
| 36.140625 | 126 | 0.481379 | Junology |