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 109 | 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 48.5k ⌀ | 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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c578dba7f0a93edf0400edcf89b7997f87186002 | 4,691 | cpp | C++ | src/core/ATN.cpp | satoshigeyuki/Centaurus | 032ffec87fc8ddb129347974d3478fd1ee5f305a | [
"MIT"
] | 3 | 2021-02-23T01:34:28.000Z | 2021-07-19T08:07:10.000Z | src/core/ATN.cpp | satoshigeyuki/Centaurus | 032ffec87fc8ddb129347974d3478fd1ee5f305a | [
"MIT"
] | null | null | null | src/core/ATN.cpp | satoshigeyuki/Centaurus | 032ffec87fc8ddb129347974d3478fd1ee5f305a | [
"MIT"
] | null | null | null | #include "ATN.hpp"
namespace Centaurus
{
template<typename TCHAR>
void ATNNode<TCHAR>::parse_literal(Stream& stream)
{
wchar_t leader = stream.get();
wchar_t ch = stream.get();
for (; ch != L'\0' && ch != leader; ch = stream.get())
{
m_literal.push_back(wide_to_target<TCHAR>(ch));
}
if (leader != ch)
throw stream.unexpected(ch);
}
template<typename TCHAR>
void ATNNode<TCHAR>::parse(Stream& stream)
{
wchar_t ch = stream.peek();
if (Identifier::is_symbol_leader(ch))
{
m_invoke.parse(stream);
m_type = ATNNodeType::Nonterminal;
}
else if (ch == L'/')
{
stream.discard();
m_nfa.parse(stream);
m_type = ATNNodeType::RegularTerminal;
}
else if (ch == L'\'' || ch == L'"')
{
parse_literal(stream);
m_type = ATNNodeType::LiteralTerminal;
}
else
{
throw stream.unexpected(ch);
}
ch = stream.skip_whitespace();
if (ch == L'{')
{
stream.discard();
ch = stream.skip_whitespace();
if (ch == L'}')
throw stream.unexpected(ch);
int id = 0;
for (; L'0' <= ch && ch <= L'9'; ch = stream.peek())
{
id = id * 10 + static_cast<int>(ch - L'0');
stream.discard();
}
ch = stream.skip_whitespace();
if (ch != L'}')
throw stream.unexpected(ch);
stream.discard();
stream.skip_whitespace();
m_localid = id;
}
}
template<typename TCHAR>
void ATNMachine<TCHAR>::parse_atom(Stream& stream)
{
int origin_state = m_nodes.size() - 1;
wchar_t ch = stream.skip_whitespace();
int anchor_state = m_nodes.size();
if (ch == L'(')
{
stream.discard();
parse_selection(stream);
ch = stream.skip_whitespace();
if (ch != L')')
throw stream.unexpected(ch);
stream.discard();
}
else
{
ATNNode<TCHAR> node(stream);
if (m_globalid > 0 && (node.type() == ATNNodeType::LiteralTerminal || node.type() == ATNNodeType::RegularTerminal))
{
m_nodes.back().add_transition(m_nodes.size());
m_nodes.emplace_back(ATNNodeType::WhiteSpace);
}
m_nodes.back().add_transition(m_nodes.size());
m_nodes.push_back(node);
}
ch = stream.skip_whitespace();
switch (ch)
{
case L'*':
add_node(m_nodes.size() - 1);
m_nodes.back().add_transition(anchor_state);
add_node(m_nodes.size() - 1);
m_nodes[origin_state].add_transition(m_nodes.size() - 1);
stream.discard();
break;
case L'+':
add_node(m_nodes.size() - 1);
m_nodes.back().add_transition(anchor_state);
stream.discard();
break;
case L'?':
add_node(m_nodes.size() - 1);
m_nodes[origin_state].add_transition(m_nodes.size() - 1);
stream.discard();
break;
}
}
template<typename TCHAR>
void ATNMachine<TCHAR>::parse_selection(Stream& stream)
{
add_node(m_nodes.size() - 1);
int priority = 0;
int origin_state = m_nodes.size() - 1;
std::vector<int> terminal_states;
for (;;)
{
terminal_states.push_back(add_node(origin_state, priority));
parse_sequence(stream);
terminal_states.back() = m_nodes.size() - 1;
wchar_t ch = stream.skip_whitespace();
if (ch == L';' || ch == L')')
{
break;
}
else if (ch == L'|')
{
stream.discard();
ch = stream.peek();
if (ch == L'>')
{
stream.discard();
priority++;
}
continue;
}
else
{
throw stream.unexpected(ch);
}
}
m_nodes.emplace_back();
int final_node = m_nodes.size() - 1;
for (int from : terminal_states)
{
m_nodes[from].add_transition(final_node);
}
}
template<typename TCHAR>
void ATNMachine<TCHAR>::parse_sequence(Stream& stream)
{
while (true)
{
wchar_t ch = stream.skip_whitespace();
if (ch == L'|' || ch == L')' || ch == L';')
return;
parse_atom(stream);
}
}
template<typename TCHAR>
void ATNMachine<TCHAR>::parse(Stream& stream)
{
wchar_t ch = stream.skip_whitespace();
if (ch != L':')
throw stream.unexpected(ch);
stream.discard();
m_nodes.emplace_back();
parse_selection(stream);
ch = stream.skip_whitespace();
if (ch != L';')
throw stream.unexpected(ch);
stream.discard();
}
template<typename TCHAR>
bool ATNMachine<TCHAR>::verify_invocations(const std::unordered_map<Identifier, ATNMachine<TCHAR> >& network) const
{
for (const auto& node : m_nodes)
{
if (node.type() == ATNNodeType::Nonterminal)
{
if (network.find(node.get_invoke()) == network.cend())
{
return false;
}
}
}
return true;
}
template class ATNMachine<char>;
template class ATNMachine<unsigned char>;
template class ATNMachine<wchar_t>;
}
| 20.307359 | 123 | 0.600938 | satoshigeyuki |
c5837d6982872fcc793d1599fc5d9d5acbddd2ef | 27,057 | cpp | C++ | src/stage/batched/host/KokkosKernels_Test_Trsm.cpp | crtrott/kokkos-kernels | 0dba50f62188eb82da35bb4fe0211c7783300903 | [
"BSD-3-Clause"
] | null | null | null | src/stage/batched/host/KokkosKernels_Test_Trsm.cpp | crtrott/kokkos-kernels | 0dba50f62188eb82da35bb4fe0211c7783300903 | [
"BSD-3-Clause"
] | null | null | null | src/stage/batched/host/KokkosKernels_Test_Trsm.cpp | crtrott/kokkos-kernels | 0dba50f62188eb82da35bb4fe0211c7783300903 | [
"BSD-3-Clause"
] | null | null | null | /// \author Kyungjoo Kim ([email protected])
#include <iomanip>
#if defined(__KOKKOSKERNELS_INTEL_MKL__)
#include "mkl.h"
#endif
#include "Kokkos_Core.hpp"
#include "impl/Kokkos_Timer.hpp"
#include "KokkosKernels_Vector.hpp"
#include "KokkosKernels_Trsm_Serial_Decl.hpp"
#include "KokkosKernels_Trsm_Serial_Impl.hpp"
namespace KokkosKernels {
namespace Test {
#define FLOP_MUL 1.0
#define FLOP_ADD 1.0
double FlopCountLower(int mm, int nn) {
double m = (double)mm; double n = (double)nn;
return (FLOP_MUL*(0.5*m*n*(n+1.0)) +
FLOP_ADD*(0.5*m*n*(n-1.0)));
}
double FlopCountUpper(int mm, int nn) {
double m = (double)mm; double n = (double)nn;
return (FLOP_MUL*(0.5*m*n*(n+1.0)) +
FLOP_ADD*(0.5*m*n*(n-1.0)));
}
template<int test, int BlkSize, int NumCols, typename DeviceSpaceType, typename VectorTagType, typename AlgoTagType>
void Trsm(const int N) {
typedef Kokkos::Schedule<Kokkos::Static> ScheduleType;
//typedef Kokkos::Schedule<Kokkos::Dynamic> ScheduleType;
switch (test) {
case 0: std::cout << "TestID = Left, Lower, NoTrans, UnitDiag\n"; break;
case 1: std::cout << "TestID = Left, Lower, NoTrans, NonUnitDiag\n"; break;
case 2: std::cout << "TestID = Right, Upper, NoTrans, UnitDiag\n"; break;
case 3: std::cout << "TestID = Right, Upper, NoTrans, NonUnitDiag\n"; break;
case 4: std::cout << "TestID = Left, Upper, NoTrans, NonUnitDiag\n"; break;
}
//constexpr int N = 100;
typedef typename VectorTagType::value_type ValueType;
constexpr int VectorLength = VectorTagType::length;
// when m == n, lower upper does not matter (unit and nonunit)
double flop = 0;
switch (test) {
case 0:
case 1:
flop = FlopCountLower(BlkSize,NumCols);
break;
case 2:
case 3:
case 4:
flop = FlopCountUpper(BlkSize,NumCols);
break;
}
flop *= (N*VectorLength);
const double tmax = 1.0e15;
typedef typename
Kokkos::Impl::is_space<DeviceSpaceType>::host_mirror_space::execution_space HostSpaceType ;
const int iter_begin = -10, iter_end = 100;
Kokkos::Impl::Timer timer;
///
/// Reference version using MKL DTRSM
///
Kokkos::View<ValueType***,Kokkos::LayoutRight,HostSpaceType> bref;
Kokkos::View<ValueType***,Kokkos::LayoutRight,HostSpaceType>
amat("amat", N*VectorLength, BlkSize, BlkSize),
bmat("bmat", N*VectorLength, BlkSize, NumCols);
Random random;
for (int k=0;k<N*VectorLength;++k) {
for (int i=0;i<BlkSize;++i)
for (int j=0;j<BlkSize;++j)
amat(k, i, j) = random.value() + 4.0*(i==j);
for (int i=0;i<BlkSize;++i)
for (int j=0;j<NumCols;++j)
bmat(k, i, j) = random.value();
}
typedef Vector<VectorTagType> VectorType;
Kokkos::View<VectorType***,Kokkos::LayoutRight,HostSpaceType>
amat_simd("amat_simd", N, BlkSize, BlkSize),
bmat_simd("bmat_simd", N, BlkSize, NumCols);
for (int k0=0;k0<N;++k0)
for (int k1=0;k1<VectorLength;++k1) {
for (int i=0;i<BlkSize;++i)
for (int j=0;j<BlkSize;++j)
amat_simd(k0, i, j)[k1] = amat(k0*VectorLength+k1, i, j);
for (int i=0;i<BlkSize;++i)
for (int j=0;j<NumCols;++j)
bmat_simd(k0, i, j)[k1] = bmat(k0*VectorLength+k1, i, j);
}
// for KNL
constexpr size_t LLC_CAPACITY = 34*1024*1024;
Flush<LLC_CAPACITY> flush;
///
/// Reference version using MKL DTRSM
///
#if defined(__KOKKOSKERNELS_INTEL_MKL__)
{
Kokkos::View<ValueType***,Kokkos::LayoutRight,HostSpaceType>
a("a", N*VectorLength, BlkSize, BlkSize),
b("b", N*VectorLength, BlkSize, NumCols);
{
double tavg = 0, tmin = tmax;
for (int iter=iter_begin;iter<iter_end;++iter) {
// flush
flush.run();
// initialize matrices
Kokkos::deep_copy(a, amat);
Kokkos::deep_copy(b, bmat);
DeviceSpaceType::fence();
timer.reset();
Kokkos::RangePolicy<DeviceSpaceType,ScheduleType> policy(0, N*VectorLength);
Kokkos::parallel_for
(policy,
KOKKOS_LAMBDA(const int k) {
auto aa = Kokkos::subview(a, k, Kokkos::ALL(), Kokkos::ALL());
auto bb = Kokkos::subview(b, k, Kokkos::ALL(), Kokkos::ALL());
switch (test) {
case 0:
cblas_dtrsm(CblasRowMajor,
CblasLeft, CblasLower, CblasNoTrans, CblasUnit,
BlkSize, NumCols,
1.0,
(double*)aa.data(), aa.stride_0(),
(double*)bb.data(), bb.stride_0());
break;
case 1:
cblas_dtrsm(CblasRowMajor,
CblasLeft, CblasLower, CblasNoTrans, CblasNonUnit,
BlkSize, NumCols,
1.0,
(double*)aa.data(), aa.stride_0(),
(double*)bb.data(), bb.stride_0());
break;
case 2:
cblas_dtrsm(CblasRowMajor,
CblasRight, CblasUpper, CblasNoTrans, CblasUnit,
BlkSize, NumCols,
1.0,
(double*)aa.data(), aa.stride_0(),
(double*)bb.data(), bb.stride_0());
break;
case 3:
cblas_dtrsm(CblasRowMajor,
CblasRight, CblasUpper, CblasNoTrans, CblasNonUnit,
BlkSize, NumCols,
1.0,
(double*)aa.data(), aa.stride_0(),
(double*)bb.data(), bb.stride_0());
break;
case 4:
cblas_dtrsm(CblasRowMajor,
CblasLeft, CblasUpper, CblasNoTrans, CblasNonUnit,
BlkSize, NumCols,
1.0,
(double*)aa.data(), aa.stride_0(),
(double*)bb.data(), bb.stride_0());
break;
}
});
DeviceSpaceType::fence();
const double t = timer.seconds();
tmin = std::min(tmin, t);
tavg += (iter >= 0)*t;
}
tavg /= iter_end;
double sum = 0;
for (int i=0;i<b.dimension(0);++i)
for (int j=0;j<b.dimension(1);++j)
for (int k=0;k<b.dimension(2);++k)
sum += std::abs(bmat(i,j,k));
std::cout << std::setw(10) << "MKL TRSM"
<< " BlkSize = " << std::setw(3) << BlkSize
<< " NumCols = " << std::setw(3) << NumCols
<< " time = " << std::scientific << tmin
<< " avg flop/s = " << (flop/tavg)
<< " max flop/s = " << (flop/tmin)
<< " sum abs(B) = " << sum
<< std::endl;
bref = b;
}
}
#if defined(__KOKKOSKERNELS_INTEL_MKL_BATCHED__)
{
Kokkos::View<ValueType***,Kokkos::LayoutRight,HostSpaceType>
a("a", N*VectorLength, BlkSize, BlkSize),
b("b", N*VectorLength, BlkSize, NumCols);
ValueType
*aa[N*VectorLength],
*bb[N*VectorLength];
for (int k=0;k<N*VectorLength;++k) {
aa[k] = &a(k, 0, 0);
bb[k] = &b(k, 0, 0);
}
{
double tavg = 0, tmin = tmax;
MKL_INT blksize[1] = { BlkSize };
MKL_INT numcols[1] = { NumCols };
MKL_INT lda[1] = { a.stride_1() };
MKL_INT ldb[1] = { b.stride_1() };
double one[1] = { 1.0 };
MKL_INT size_per_grp[1] = { N*VectorLength };
for (int iter=iter_begin;iter<iter_end;++iter) {
// flush
flush.run();
// initialize matrices
Kokkos::deep_copy(a, amat);
Kokkos::deep_copy(b, bmat);
DeviceSpaceType::fence();
timer.reset();
switch (test) {
case 0: {
CBLAS_SIDE side[1] = {CblasLeft};
CBLAS_UPLO uplo[1] = {CblasLower};
CBLAS_TRANSPOSE transA[1] = {CblasNoTrans};
CBLAS_DIAG diag[1] = {CblasUnit};
cblas_dtrsm_batch(CblasRowMajor,
side, uplo, transA, diag,
blksize, numcols,
one,
(const double**)aa, lda,
(double**)bb, ldb,
1, size_per_grp);
break;
}
case 1: {
CBLAS_SIDE side[1] = {CblasLeft};
CBLAS_UPLO uplo[1] = {CblasLower};
CBLAS_TRANSPOSE transA[1] = {CblasNoTrans};
CBLAS_DIAG diag[1] = {CblasNonUnit};
cblas_dtrsm_batch(CblasRowMajor,
side, uplo, transA, diag,
blksize, numcols,
one,
(const double**)aa, lda,
(double**)bb, ldb,
1, size_per_grp);
break;
}
case 2: {
CBLAS_SIDE side[1] = {CblasRight};
CBLAS_UPLO uplo[1] = {CblasUpper};
CBLAS_TRANSPOSE transA[1] = {CblasNoTrans};
CBLAS_DIAG diag[1] = {CblasUnit};
cblas_dtrsm_batch(CblasRowMajor,
side, uplo, transA, diag,
blksize, numcols,
one,
(const double**)aa, lda,
(double**)bb, ldb,
1, size_per_grp);
break;
}
case 3: {
CBLAS_SIDE side[1] = {CblasRight};
CBLAS_UPLO uplo[1] = {CblasUpper};
CBLAS_TRANSPOSE transA[1] = {CblasNoTrans};
CBLAS_DIAG diag[1] = {CblasNonUnit};
cblas_dtrsm_batch(CblasRowMajor,
side, uplo, transA, diag,
blksize, numcols,
one,
(const double**)aa, lda,
(double**)bb, ldb,
1, size_per_grp);
break;
}
case 4: {
CBLAS_SIDE side[1] = {CblasLeft};
CBLAS_UPLO uplo[1] = {CblasUpper};
CBLAS_TRANSPOSE transA[1] = {CblasNoTrans};
CBLAS_DIAG diag[1] = {CblasNonUnit};
cblas_dtrsm_batch(CblasRowMajor,
side, uplo, transA, diag,
blksize, numcols,
one,
(const double**)aa, lda,
(double**)bb, ldb,
1, size_per_grp);
break;
}
}
DeviceSpaceType::fence();
const double t = timer.seconds();
tmin = std::min(tmin, t);
tavg += (iter >= 0)*t;
}
tavg /= iter_end;
double diff = 0;
for (int i=0;i<bref.dimension(0);++i)
for (int j=0;j<bref.dimension(1);++j)
for (int k=0;k<bref.dimension(2);++k)
diff += std::abs(bref(i,j,k) - b(i,j,k));
std::cout << std::setw(10) << "MKL Batch"
<< " BlkSize = " << std::setw(3) << BlkSize
<< " NumCols = " << std::setw(3) << NumCols
<< " time = " << std::scientific << tmin
<< " avg flop/s = " << (flop/tavg)
<< " max flop/s = " << (flop/tmin)
<< " diff to ref = " << diff
<< std::endl;
}
}
#endif
#if defined(__KOKKOSKERNELS_INTEL_MKL_COMPACT_BATCHED__)
{
Kokkos::View<VectorType***,Kokkos::LayoutRight,HostSpaceType>
a("a", N, BlkSize, BlkSize),
b("b", N, BlkSize, NumCols);
{
double tavg = 0, tmin = tmax;
MKL_INT blksize[1] = { BlkSize };
MKL_INT numcols[1] = { NumCols };
MKL_INT lda[1] = { a.stride_1() };
MKL_INT ldb[1] = { b.stride_1() };
double one[1] = { 1.0 };
MKL_INT size_per_grp[1] = { N*VectorLength };
compact_t A_p, B_p;
A_p.layout = CblasRowMajor;
A_p.rows = blksize;
A_p.cols = blksize;
A_p.stride = lda;
A_p.group_count = 1;
A_p.size_per_group = size_per_grp;
A_p.format = VectorLength;
A_p.mat = (double*)a.data();
B_p.layout = CblasRowMajor;
B_p.rows = blksize;
B_p.cols = numcols;
B_p.stride = ldb;
B_p.group_count = 1;
B_p.size_per_group = size_per_grp;
B_p.format = VectorLength;
B_p.mat = (double*)b.data();
for (int iter=iter_begin;iter<iter_end;++iter) {
// flush
flush.run();
// initialize matrices
Kokkos::deep_copy(a, amat_simd);
Kokkos::deep_copy(b, bmat_simd);
DeviceSpaceType::fence();
timer.reset();
switch (test) {
case 0: {
CBLAS_SIDE side[1] = {CblasLeft};
CBLAS_UPLO uplo[1] = {CblasLower};
CBLAS_TRANSPOSE transA[1] = {CblasNoTrans};
CBLAS_DIAG diag[1] = {CblasUnit};
cblas_dtrsm_compute_batch(side, uplo, transA, diag,
one,
&A_p,
&B_p);
break;
}
case 1: {
CBLAS_SIDE side[1] = {CblasLeft};
CBLAS_UPLO uplo[1] = {CblasLower};
CBLAS_TRANSPOSE transA[1] = {CblasNoTrans};
CBLAS_DIAG diag[1] = {CblasNonUnit};
cblas_dtrsm_compute_batch(side, uplo, transA, diag,
one,
&A_p,
&B_p);
break;
}
case 2: {
CBLAS_SIDE side[1] = {CblasRight};
CBLAS_UPLO uplo[1] = {CblasUpper};
CBLAS_TRANSPOSE transA[1] = {CblasNoTrans};
CBLAS_DIAG diag[1] = {CblasUnit};
cblas_dtrsm_compute_batch(side, uplo, transA, diag,
one,
&A_p,
&B_p);
break;
}
case 3: {
CBLAS_SIDE side[1] = {CblasRight};
CBLAS_UPLO uplo[1] = {CblasUpper};
CBLAS_TRANSPOSE transA[1] = {CblasNoTrans};
CBLAS_DIAG diag[1] = {CblasNonUnit};
cblas_dtrsm_compute_batch(side, uplo, transA, diag,
one,
&A_p,
&B_p);
break;
}
case 4: {
CBLAS_SIDE side[1] = {CblasLeft};
CBLAS_UPLO uplo[1] = {CblasUpper};
CBLAS_TRANSPOSE transA[1] = {CblasNoTrans};
CBLAS_DIAG diag[1] = {CblasNonUnit};
cblas_dtrsm_compute_batch(side, uplo, transA, diag,
one,
&A_p,
&B_p);
break;
}
}
DeviceSpaceType::fence();
const double t = timer.seconds();
tmin = std::min(tmin, t);
tavg += (iter >= 0)*t;
}
tavg /= iter_end;
double diff = 0;
for (int i=0;i<bref.dimension(0);++i)
for (int j=0;j<bref.dimension(1);++j)
for (int k=0;k<bref.dimension(2);++k)
diff += std::abs(bref(i,j,k) - b(i/VectorLength,j,k)[i%VectorLength]);
std::cout << std::setw(10) << "MKL Cmpt"
<< " BlkSize = " << std::setw(3) << BlkSize
<< " NumCols = " << std::setw(3) << NumCols
<< " time = " << std::scientific << tmin
<< " avg flop/s = " << (flop/tavg)
<< " max flop/s = " << (flop/tmin)
<< " diff to ref = " << diff
<< std::endl;
}
}
#endif
#endif
// ///
// /// Plain version (comparable to micro BLAS version)
// ///
// {
// Kokkos::View<ValueType***,Kokkos::LayoutRight,HostSpaceType>
// a("a", N*VectorLength, BlkSize, BlkSize),
// b("b", N*VectorLength, BlkSize, NumCols);
// {
// double tavg = 0, tmin = tmax;
// for (int iter=iter_begin;iter<iter_end;++iter) {
// // flush
// flush.run();
// // initialize matrices
// Kokkos::deep_copy(a, amat);
// Kokkos::deep_copy(b, bmat);
// DeviceSpaceType::fence();
// timer.reset();
// Kokkos::RangePolicy<DeviceSpaceType,ScheduleType> policy(0, N*VectorLength);
// Kokkos::parallel_for
// (policy,
// KOKKOS_LAMBDA(const int k) {
// auto aa = Kokkos::subview(a, k, Kokkos::ALL(), Kokkos::ALL());
// auto bb = Kokkos::subview(b, k, Kokkos::ALL(), Kokkos::ALL());
// switch (test) {
// case 0:
// Serial::Trsm<Side::Left,Uplo::Lower,Trans::NoTranspose,Diag::Unit,AlgoTagType>::
// invoke(1.0, aa, bb);
// break;
// case 1:
// Serial::Trsm<Side::Left,Uplo::Lower,Trans::NoTranspose,Diag::NonUnit,AlgoTagType>::
// invoke(1.0, aa, bb);
// break;
// case 2:
// Serial::Trsm<Side::Right,Uplo::Upper,Trans::NoTranspose,Diag::Unit,AlgoTagType>::
// invoke(1.0, aa, bb);
// break;
// case 3:
// Serial::Trsm<Side::Right,Uplo::Upper,Trans::NoTranspose,Diag::NonUnit,AlgoTagType>::
// invoke(1.0, aa, bb);
// break;
// case 4:
// Serial::Trsm<Side::Left,Uplo::Upper,Trans::NoTranspose,Diag::NonUnit,AlgoTagType>::
// invoke(1.0, aa, bb);
// break;
// }
// });
// DeviceSpaceType::fence();
// const double t = timer.seconds();
// tmin = std::min(tmin, t);
// tavg += (iter >= 0)*t;
// }
// tavg /= iter_end;
// double diff = 0;
// for (int i=0;i<bref.dimension(0);++i)
// for (int j=0;j<bref.dimension(1);++j)
// for (int k=0;k<bref.dimension(2);++k)
// diff += std::abs(bref(i,j,k) - b(i,j,k));
// std::cout << std::setw(10) << "Plain"
// << " BlkSize = " << std::setw(3) << BlkSize
// << " NumCols = " << std::setw(3) << NumCols
// << " time = " << std::scientific << tmin
// << " avg flop/s = " << (flop/tavg)
// << " max flop/s = " << (flop/tmin)
// << " diff to ref = " << diff
// << std::endl;
// }
// }
///
/// SIMD with appropriate data layout
///
{
typedef Vector<VectorTagType> VectorType;
Kokkos::View<VectorType***,Kokkos::LayoutRight,HostSpaceType>
a("a", N, BlkSize, BlkSize),
b("b", N, BlkSize, NumCols);
{
double tavg = 0, tmin = tmax;
for (int iter=iter_begin;iter<iter_end;++iter) {
// flush
flush.run();
// initialize matrices
Kokkos::deep_copy(a, amat_simd);
Kokkos::deep_copy(b, bmat_simd);
DeviceSpaceType::fence();
timer.reset();
Kokkos::RangePolicy<DeviceSpaceType,ScheduleType> policy(0, N);
Kokkos::parallel_for
(policy,
KOKKOS_LAMBDA(const int k) {
auto aa = Kokkos::subview(a, k, Kokkos::ALL(), Kokkos::ALL());
auto bb = Kokkos::subview(b, k, Kokkos::ALL(), Kokkos::ALL());
switch (test) {
case 0:
Serial::Trsm<Side::Left,Uplo::Lower,Trans::NoTranspose,Diag::Unit,AlgoTagType>::
invoke(1.0, aa, bb);
break;
case 1:
Serial::Trsm<Side::Left,Uplo::Lower,Trans::NoTranspose,Diag::NonUnit,AlgoTagType>::
invoke(1.0, aa, bb);
break;
case 2:
Serial::Trsm<Side::Right,Uplo::Upper,Trans::NoTranspose,Diag::Unit,AlgoTagType>::
invoke(1.0, aa, bb);
break;
case 3:
Serial::Trsm<Side::Right,Uplo::Upper,Trans::NoTranspose,Diag::NonUnit,AlgoTagType>::
invoke(1.0, aa, bb);
break;
case 4:
Serial::Trsm<Side::Left,Uplo::Upper,Trans::NoTranspose,Diag::NonUnit,AlgoTagType>::
invoke(1.0, aa, bb);
break;
}
});
DeviceSpaceType::fence();
const double t = timer.seconds();
tmin = std::min(tmin, t);
tavg += (iter >= 0)*t;
}
tavg /= iter_end;
double diff = 0;
for (int i=0;i<bref.dimension(0);++i)
for (int j=0;j<bref.dimension(1);++j)
for (int k=0;k<bref.dimension(2);++k)
diff += std::abs(bref(i,j,k) - b(i/VectorLength,j,k)[i%VectorLength]);
std::cout << std::setw(10) << "SIMD"
<< " BlkSize = " << std::setw(3) << BlkSize
<< " NumCols = " << std::setw(3) << NumCols
<< " time = " << std::scientific << tmin
<< " avg flop/s = " << (flop/tavg)
<< " max flop/s = " << (flop/tmin)
<< " diff to ref = " << diff
<< std::endl;
}
}
std::cout << "\n\n";
}
}
}
using namespace KokkosKernels;
template<typename VectorType,
typename AlgoTagType>
void run(const int N) {
typedef Kokkos::OpenMP ExecSpace;
std::cout << "ExecSpace:: ";
if (std::is_same<ExecSpace,Kokkos::Serial>::value)
std::cout << "Kokkos::Serial " << std::endl;
else
ExecSpace::print_configuration(std::cout, false);
std::cout << "\n\n Used for Factorization \n\n";
/// Left, Lower, NoTrans, UnitDiag (used in LU factorization and LU solve)
Test::Trsm<0, 3, 3, ExecSpace,VectorType,AlgoTagType>(N);
Test::Trsm<0, 5, 5, ExecSpace,VectorType,AlgoTagType>(N);
Test::Trsm<0,10,10, ExecSpace,VectorType,AlgoTagType>(N);
Test::Trsm<0,15,15, ExecSpace,VectorType,AlgoTagType>(N);
// /// Left, Lower, NoTrans, NonUnitDiag
// Test::Trsm<1, 3, 3, ExecSpace,VectorType,AlgoTagType>(N);
// Test::Trsm<1, 5, 5, ExecSpace,VectorType,AlgoTagType>(N);
// Test::Trsm<1,10,10, ExecSpace,VectorType,AlgoTagType>(N);
// Test::Trsm<1,15,15, ExecSpace,VectorType,AlgoTagType>(N);
// /// Right, Upper, NoTrans, UnitDiag
// Test::Trsm<2, 3, 3, ExecSpace,VectorType,AlgoTagType>(N);
// Test::Trsm<2, 5, 5, ExecSpace,VectorType,AlgoTagType>(N);
// Test::Trsm<2,10,10, ExecSpace,VectorType,AlgoTagType>(N);
// Test::Trsm<2,15,15, ExecSpace,VectorType,AlgoTagType>(N);
// /// Right, Upper, NoTrans, NonUnitDiag (used in LU factorization)
// Test::Trsm<3, 3, 3, ExecSpace,VectorType,AlgoTagType>(N);
// Test::Trsm<3, 5, 5, ExecSpace,VectorType,AlgoTagType>(N);
// Test::Trsm<3,10,10, ExecSpace,VectorType,AlgoTagType>(N);
// Test::Trsm<3,15,15, ExecSpace,VectorType,AlgoTagType>(N);
// std::cout << "\n\n Used for Solve \n\n";
// /// Left, Lower, NoTrans, UnitDiag (used in LU solve)
// Test::Trsm<0, 5, 1, ExecSpace,VectorType,AlgoTagType>(N);
// Test::Trsm<0, 9, 1, ExecSpace,VectorType,AlgoTagType>(N);
// Test::Trsm<0,15, 1, ExecSpace,VectorType,AlgoTagType>(N);
// Test::Trsm<0,20, 1, ExecSpace,VectorType,AlgoTagType>(N);
// /// Left, Upper, Notrans, NonUnitDiag (user in LU solve)
// Test::Trsm<4, 5, 1, ExecSpace,VectorType,AlgoTagType>(N);
// Test::Trsm<4, 9, 1, ExecSpace,VectorType,AlgoTagType>(N);
// Test::Trsm<4,15, 1, ExecSpace,VectorType,AlgoTagType>(N);
// Test::Trsm<4,20, 1, ExecSpace,VectorType,AlgoTagType>(N);
}
int main(int argc, char *argv[]) {
Kokkos::initialize(argc, argv);
int N = 128*128;
for (int i=1;i<argc;++i) {
const std::string& token = argv[i];
if (token == std::string("-N")) N = std::atoi(argv[++i]);
}
#if defined(__AVX512F__)
constexpr int VectorLength = 8;
#elif defined(__AVX2__) || defined(__AVX__)
constexpr int VectorLength = 4;
#else
static_assert(false, "AVX is not supported");
#endif
{
std::cout << " N = " << N << std::endl;
// std::cout << "\n Testing SIMD-" << VectorLength << " and Algo::Trsm::Unblocked\n";
// run<VectorTag<SIMD<double>,VectorLength>,Algo::Trsm::Unblocked>(N/VectorLength);
// std::cout << "\n Testing AVX-" << VectorLength << " and Algo::Trsm::Unblocked\n";
// run<VectorTag<AVX<double>,VectorLength>,Algo::Trsm::Unblocked>(N/VectorLength);
// std::cout << "\n Testing SIMD-" << VectorLength << " and Algo::Trsm::Blocked\n";
// run<VectorTag<SIMD<double>,VectorLength>,Algo::Trsm::Blocked>(N/VectorLength);
std::cout << "\n Testing AVX-" << VectorLength << " and Algo::Trsm::Blocked\n";
run<VectorTag<AVX<double>,VectorLength>,Algo::Trsm::Blocked>(N/VectorLength);
// std::cout << "\n Testing AVX-" << VectorLength << " and Algo::Trsm::CompactMKL\n";
// run<VectorTag<AVX<double>,VectorLength>,Algo::Trsm::CompactMKL>(N/VectorLength);
}
Kokkos::finalize();
return 0;
}
| 36.076 | 120 | 0.465684 | crtrott |
c58fed8c8d5a08b6977399826871e6f95f7cdf70 | 5,719 | cpp | C++ | src_db/random_access_file/RandomAccessFile.cpp | alinous-core/codable-cash | 32a86a152a146c592bcfd8cc712f4e8cb38ee1a0 | [
"MIT"
] | 1 | 2020-10-15T08:24:35.000Z | 2020-10-15T08:24:35.000Z | src_db/random_access_file/RandomAccessFile.cpp | Codablecash/codablecash | 8816b69db69ff2f5da6cdb6af09b8fb21d3df1d9 | [
"MIT"
] | null | null | null | src_db/random_access_file/RandomAccessFile.cpp | Codablecash/codablecash | 8816b69db69ff2f5da6cdb6af09b8fb21d3df1d9 | [
"MIT"
] | null | null | null | /*
* RandomAccessFile.cpp
*
* Created on: 2018/04/26
* Author: iizuka
*/
#include "random_access_file/RandomAccessFile.h"
#include "base/UnicodeString.h"
#include "base_io/File.h"
#include "base_io_stream/exceptions.h"
#include "random_access_file/MMapSegments.h"
#include "random_access_file/MMapSegment.h"
#include "random_access_file/DiskCacheManager.h"
#include "base/StackRelease.h"
#include "debug/debugMacros.h"
namespace alinous {
constexpr uint64_t RandomAccessFile::PAGE_NUM_CACHE;
RandomAccessFile::RandomAccessFile(const File* file, DiskCacheManager* diskCacheManager) noexcept {
this->position = 0;
this->fileSize = 0;
this->diskCacheManager = diskCacheManager;
this->file = new File(*file);
this->segments = nullptr;
this->pageSize = Os::getSystemPageSize();
}
RandomAccessFile::RandomAccessFile(const File* file, DiskCacheManager* diskCacheManager, uint64_t pageSize) noexcept {
this->position = 0;
this->fileSize = 0;
this->diskCacheManager = diskCacheManager;
this->file = new File(*file);
this->segments = nullptr;
this->pageSize = pageSize;
}
RandomAccessFile::~RandomAccessFile() noexcept {
close();
delete this->file;
}
void RandomAccessFile::open(bool sync) {
ERROR_POINT(L"RandomAccessFile::open")
this->fd = Os::openFile2ReadWrite(this->file, sync);
if(!this->fd.isOpened()){
throw new FileOpenException(__FILE__, __LINE__);
}
this->position = 0;
this->fileSize = this->file->length();
uint64_t segmentSize = getSegmentSize();
this->segments = new MMapSegments(this->fileSize, segmentSize);
if(this->fileSize == 0){
setLength(this->pageSize * PAGE_NUM_CACHE);
}
}
void RandomAccessFile::close() noexcept {
if(!this->fd.isOpened()){
return;
}
if(this->segments != nullptr){
this->segments->clearElements(this->diskCacheManager, this->fd);
delete this->segments;
this->segments = nullptr;
}
Os::closeFileDescriptor(&this->fd);
}
int RandomAccessFile::read(uint64_t fpos, char* buff, int count) {
uint64_t segSize = getSegmentSize();
int count2Read = count;
int currentfpos = fpos;
while(count2Read > 0){
MMapSegment* seg = this->segments->getSegment(currentfpos, this->diskCacheManager, this->fd);
MMapSegmentStackRelease dec(seg);
uint64_t offset = currentfpos % segSize;
char* ptr = seg->getPtr(offset);
int cnt = seg->remains(offset);
cnt = cnt > count2Read ? count2Read : cnt;
Mem::memcpy(buff, ptr, cnt);
count2Read -= cnt;
currentfpos += cnt;
buff += cnt;
}
return count;
}
#ifdef __TEST_CPP_UNIT__
static int errorHook(){
CAUSE_ERROR_BY_RETURN(L"RandomAccessFile::write", -1)
return 0;
}
#endif
int RandomAccessFile::write(uint64_t fpos, const char* buff, int count) {
#ifdef __TEST_CPP_UNIT__
if(errorHook() < 0){
throw new FileIOException(__FILE__, __LINE__);
}
#endif
uint64_t segSize = getSegmentSize();
int count2Write = count;
int currentfpos = fpos;
while(count2Write > 0){
// check capacity
{
uint64_t currentSize = this->fileSize;
uint64_t writeEndPos = currentfpos + count2Write;
if(writeEndPos >= currentSize){
uint64_t newLength = currentSize + this->pageSize * 4;
setLength(newLength);
}
}
MMapSegment* seg = this->segments->getSegment(currentfpos, this->diskCacheManager, this->fd);
MMapSegmentStackRelease dec(seg);
uint64_t offset = currentfpos % segSize;
char* ptr = seg->getPtr(offset);
int cnt = seg->remains(offset);
cnt = cnt > count2Write ? count2Write : cnt;
Mem::memcpy(ptr, buff, cnt);
seg->setDirty(true);
count2Write -= cnt;
currentfpos += cnt;
buff += cnt;
}
return count;
}
void RandomAccessFile::sync(bool flushDisk) {
ERROR_POINT(L"RandomAccessFile::sync")
this->segments->sync(flushDisk, this->fd);
if(flushDisk){
int code = Os::syncFile(&this->fd);
if(code < 0){
throw new FileIOException(L"Failed in synchronizing file.", __FILE__, __LINE__);
}
}
}
uint64_t RandomAccessFile::getSegmentSize() const noexcept {
return this->pageSize * PAGE_NUM_CACHE;
}
void RandomAccessFile::setLength(uint64_t newLength) noexcept(false) {
if(!this->fd.isOpened()){
UnicodeString* path = this->file->getAbsolutePath();
StackRelease<UnicodeString> r_path(path);
UnicodeString msg(path);
msg.append(L" is not opened at setLength()");
throw new FileIOException(msg.towString(), __FILE__, __LINE__);
}
if(newLength <= this->fileSize){
return;
}
uint64_t newSize = newLength - this->fileSize;
const uint64_t numBlocks = newSize / this->pageSize;
const uint64_t modBytes = newSize % this->pageSize;
Os::seekFile(&this->fd, 0, Os::SeekOrigin::FROM_END);
int n;
char *tmp = new char[this->pageSize]{};
StackArrayRelease<char> t_tmp(tmp);
ERROR_POINT(L"RandomAccessFile::setLength::01")
for(int i = 0; i != numBlocks; ++i){
n = Os::write2File(&this->fd, tmp, this->pageSize);
if(n != this->pageSize){
UnicodeString* path = this->file->getAbsolutePath();
StackRelease<UnicodeString> r_path(path);
throw new FileIOException(path->towString(), __FILE__, __LINE__);
}
}
ERROR_POINT(L"RandomAccessFile::setLength::02")
n = Os::write2File(&this->fd, tmp, modBytes);
if(n != modBytes){
UnicodeString* path = this->file->getAbsolutePath();
StackRelease<UnicodeString> r_path(path);
throw new FileIOException(path->towString(), __FILE__, __LINE__);
}
this->fileSize = this->file->length();
this->segments->onResized(this->fileSize, this->fd, this->diskCacheManager);
}
MMapSegment* RandomAccessFile::getSegment(uint64_t fpos) noexcept(false) {
return this->segments->getSegment(fpos, this->diskCacheManager, this->fd);
}
bool RandomAccessFile::exists() const noexcept {
return this->file->exists();
}
} /* namespace alinous */
| 24.440171 | 118 | 0.715335 | alinous-core |
c590c230a6c90ad6494de571cb3c2919d9261094 | 2,901 | hpp | C++ | include/picture.hpp | Andrew15-5/walk-game | 550f4adeb4933fd298866cde0dd30dca11559334 | [
"MIT"
] | null | null | null | include/picture.hpp | Andrew15-5/walk-game | 550f4adeb4933fd298866cde0dd30dca11559334 | [
"MIT"
] | null | null | null | include/picture.hpp | Andrew15-5/walk-game | 550f4adeb4933fd298866cde0dd30dca11559334 | [
"MIT"
] | null | null | null | #ifndef PICTURE_HPP
#define PICTURE_HPP
#include "include/texture_functions.hpp"
#include "include/vector2.hpp"
#include "include/vector3.hpp"
#include <IL/il.h>
#include <IL/ilu.h>
class Picture {
GLuint texture_id;
Vector2 size;
Vector3 position;
GLfloat angle;
const std::string texture_path = "res/textures";
void load_texture(const std::string &path) {
ilLoadImage(path.c_str());
ILinfo image_info;
iluGetImageInfo(&image_info);
iluFlipImage();
size.x = image_info.Width;
size.y = image_info.Height;
glGenTextures(1, &texture_id);
glBindTexture(GL_TEXTURE_2D, texture_id);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8,
size.x,
size.y,
0, GL_RGB, GL_UNSIGNED_BYTE, ilGetData());
ilDeleteImage(texture_id);
}
public:
Picture(std::string texture_file_name, GLfloat x = 0, GLfloat y = 0, GLfloat z = 0) {
texture_id = ::texture_id.last + 1;
position = Vector3(x, y, z);
angle = M_PI / 2;
load_texture(texture_path + '/' + texture_file_name);
}
Vector3 get_position() { return position; }
GLuint get_texture_id() { return texture_id; }
Vector2 get_size() { return size; }
void set_angle_rad(GLfloat angle) {
this->angle = angle;
}
void set_angle_deg(GLfloat angle) {
this->angle = angle / 180 * M_PI;
}
void set_position(GLfloat x, GLfloat y, GLfloat z) {
position = Vector3(x, y, z);
}
void set_size(GLfloat width, GLfloat height) {
size = Vector2(width, height);
}
void draw() {
change_current_texture(texture_id);
glNormal3f(0.0f, 0.0f, 1.0f);
Vector3 look_vector(sin(angle),
0,
-cos(angle));
Vector3 up_vector = Vector3(0, 1, 0);
Vector3 right_vector = look_vector.cross(up_vector);
GLfloat half_length = size.x * 0.5f;
GLfloat half_height = size.y * 0.5f;
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(position.x - right_vector.x * half_length,
position.y - half_height,
position.z - right_vector.z * half_length);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(position.x + right_vector.x * half_length,
position.y - half_height,
position.z + right_vector.z * half_length);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(position.x + right_vector.x * half_length,
position.y + half_height,
position.z + right_vector.z * half_length);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(position.x - right_vector.x * half_length,
position.y + half_height,
position.z - right_vector.z * half_length);
glEnd();
if (texture_id) disable_texture();
}
};
#endif
| 28.165049 | 89 | 0.599104 | Andrew15-5 |
c590e975c9615eaa7016c5d2b80dd1a7528eefa5 | 1,254 | cpp | C++ | UnicornRender/source/Loggers.cpp | GrapefruitTechnique/R7 | 3eaa97ac63bbc1b42e4cabf97d4d12649e36f665 | [
"MIT"
] | 12 | 2017-02-18T15:17:53.000Z | 2020-02-03T16:20:33.000Z | UnicornRender/source/Loggers.cpp | GrapefruitTechnique/R7 | 3eaa97ac63bbc1b42e4cabf97d4d12649e36f665 | [
"MIT"
] | 93 | 2017-02-15T21:05:31.000Z | 2020-08-19T06:46:27.000Z | UnicornRender/source/Loggers.cpp | GrapefruitTechnique/R-7 | 3eaa97ac63bbc1b42e4cabf97d4d12649e36f665 | [
"MIT"
] | 4 | 2015-10-23T11:55:07.000Z | 2016-11-30T10:00:52.000Z | #include <unicorn/Loggers.hpp>
#include <unicorn/utility/InternalLoggers.hpp>
#include <algorithm>
#include <cassert>
namespace unicorn
{
std::array<mule::LoggerPtr, Log::size> g_loggers;
namespace
{
static std::array<char const*, Log::size> s_logger_names = {{
"unicorn"
, "unicorn_profile"
, "unicorn_input"
, "unicorn_video"
, "unicorn_vulkan"
}};
}
std::vector<std::string> Loggers::GetDefaultLoggerNames() const
{
std::vector<std::string> result;
result.reserve(Log::size);
std::transform(
s_logger_names.begin(), s_logger_names.end()
, std::back_inserter(result)
, [](char const* name) -> std::string { return std::string(name); }
);
return result;
}
Loggers::Loggers()
: mule::LoggerConfigBase(Log::size)
, mule::templates::Singleton<Loggers>()
{
}
void Loggers::InitializeLogger(uint32_t index, Settings const& settings)
{
assert(index < Log::size);
g_loggers[index] = std::make_shared<mule::Logger>(
(!settings.name.empty() ? settings.name : s_logger_names[index])
, settings.sinks.begin()
, settings.sinks.end()
);
g_loggers[index]->SetLevel(settings.level);
g_loggers[index]->SetPattern(settings.pattern);
}
}
| 19.904762 | 75 | 0.655502 | GrapefruitTechnique |
c590f4d58677b8f942caa6dbedd7c45ffd3527c0 | 15,483 | cpp | C++ | StandardTetrisMSVC2005/StandardTetrisMSVC2005/source/CPF.StandardTetris.STStrategyRogerLLimaLaurentBercotSebastienBlondeelOnePiece1996.cpp | TetrisAI/StandardTetris | b5cbe25541ceb45517472fe7feabea0c81fd55b0 | [
"MIT"
] | 7 | 2016-11-28T13:42:44.000Z | 2021-08-05T02:34:11.000Z | StandardTetrisMSVC2005/StandardTetrisMSVC2005/source/CPF.StandardTetris.STStrategyRogerLLimaLaurentBercotSebastienBlondeelOnePiece1996.cpp | PowerOlive/StandardTetris | b5cbe25541ceb45517472fe7feabea0c81fd55b0 | [
"MIT"
] | null | null | null | StandardTetrisMSVC2005/StandardTetrisMSVC2005/source/CPF.StandardTetris.STStrategyRogerLLimaLaurentBercotSebastienBlondeelOnePiece1996.cpp | PowerOlive/StandardTetris | b5cbe25541ceb45517472fe7feabea0c81fd55b0 | [
"MIT"
] | 8 | 2015-07-31T02:53:14.000Z | 2020-04-12T04:36:23.000Z | // All contents of this file written by Colin Fahey ( http://colinfahey.com )
// 2007 June 4 ; Visit web site to check for any updates to this file.
#include "CPF.StandardTetris.STStrategyRogerLLimaLaurentBercotSebastienBlondeelOnePiece1996.h"
#include "CPF.StandardTetris.STBoard.h"
#include "CPF.StandardTetris.STPiece.h"
#include <stdlib.h>
// Disable unimportant "symbol too long" error for debug builds of STL string
#pragma warning( disable : 4786 )
#include <string>
#include <vector>
using namespace std;
namespace CPF
{
namespace StandardTetris
{
string STStrategyRogerLLimaLaurentBercotSebastienBlondeelOnePiece1996::GetStrategyName ( )
{
return ((string)"Roger LLima, Laurent Bercot, Sebastien Blondeel (one-piece, 1996)");
}
// WARNING: Moves requiring rotation must wait until piece has fallen by
// at least one row!
// Perform all rotations, and then perform translations. This
// avoids the problem of getting the piece jammed on the sides
// of the board where rotation is impossible. ***
// Also, the following strategy does not take advantage of the
// possibility of using free-fall and future movements to
// slide under overhangs and fill them in.
void STStrategyRogerLLimaLaurentBercotSebastienBlondeelOnePiece1996::GetBestMoveOncePerPiece
(
STBoard & board,
STPiece & piece,
int nextPieceFlag, // 0 == no next piece available or known
int nextPieceShape, // 0 == no piece available or known
int & bestRotationDelta, // 0 or {0,1,2,3}
int & bestTranslationDelta // 0 or {...,-2,-1,0,1,2,...}
)
{
// We are given the current board, and the current piece
// configuration. Our goal is to evaluate various possible
// moves and return the best move we explored.
// Clear suggested move values to "do nothing" values.
bestRotationDelta = 0;
bestTranslationDelta = 0;
// ONE-PLY Analysis
STStrategyRogerLLimaLaurentBercotSebastienBlondeelOnePiece1996::PrivateStrategy
(
0, // Not called from parent ply; Just this one ply.
board,
piece,
bestRotationDelta, // 0 or {0,1,2,3}
bestTranslationDelta // 0 or {...,-2,-1,0,1,2,...}
);
}
float STStrategyRogerLLimaLaurentBercotSebastienBlondeelOnePiece1996::PrivateStrategy
(
int flagCalledFromParentPly, // True if called from a parent level
STBoard & board,
STPiece & piece,
int & bestRotationDelta, // 0 or {0,1,2,3}
int & bestTranslationDelta // 0 or {...,-2,-1,0,1,2,...}
)
{
// If board or piece is invalid, return.
if (0 == board.IsValid()) return(0.0f);
if (0 == piece.IsValid()) return(0.0f);
// Get dimensions of board
int width = 0;
int height = 0;
width = board.GetWidth();
height = board.GetHeight();
int currentBestTranslationDelta = 0;
int currentBestRotationDelta = 0;
float currentBestMerit = (-1.0e20f);
int currentBestPriority = 0;
int trialTranslationDelta = 0;
int trialRotationDelta = 0;
float trialMerit = 0.0f;
int trialPriority = 0;
int maxOrientations = 0;
int moveAcceptable = 0;
int count = 0;
STBoard tempBoard;
STPiece tempPiece;
maxOrientations = STPiece::GetMaxOrientations( piece.GetKind() );
for
(
trialRotationDelta = 0;
trialRotationDelta < maxOrientations;
trialRotationDelta++
)
{
// Make temporary copy of piece, and rotate the copy.
tempPiece.CopyFromPiece( piece );
for ( count = 0; count < trialRotationDelta; count++ )
{
tempPiece.Rotate();
}
// Determine the translation limits for this rotated piece.
int moveIsPossible = 0;
int minDeltaX = 0;
int maxDeltaX = 0;
board.DetermineAccessibleTranslationsForPieceOrientation
(
tempPiece,
moveIsPossible, // OUT: 0==NONE POSSIBLE
minDeltaX, // Left limit
maxDeltaX // Right limit
);
// Consider all allowed translations for the current rotation.
if (moveIsPossible)
{
for
(
trialTranslationDelta = minDeltaX;
trialTranslationDelta <= maxDeltaX;
trialTranslationDelta++
)
{
// Evaluate this move
// Copy piece to temp and rotate and translate
tempPiece.CopyFromPiece( piece );
for ( count = 0; count < trialRotationDelta; count++ )
{
tempPiece.Rotate();
}
tempPiece.Translate( trialTranslationDelta, 0 );
moveAcceptable = board.IsGoalAcceptable( tempPiece );
if (0 != moveAcceptable)
{
// Since the piece can be (not necessarily GET) at the goal
// horizontal translation and orientation, it's worth trying
// out a drop and evaluating the move.
tempBoard.CopyFromBoard( board );
int dropDistance = 0;
dropDistance = tempPiece.GetY();
tempBoard.FullDropAndAddPieceToBoard( tempPiece );
dropDistance -= tempPiece.GetY();
trialMerit =
STStrategyRogerLLimaLaurentBercotSebastienBlondeelOnePiece1996::PrivateStrategyEvaluate
(
tempBoard,
dropDistance
);
trialPriority = 0;
// Pierre Dellacherie's Move Priority
// Adding the following, taken from Pierre Dellacherie's research,
// dramatically improves the performance of Roger Espel Llima's
// algorithm -- but keep in mind that ANYTHING borrowed from
// Pierre Dellacherie's algorithm would improve an inferior
// algorithm!
/*
trialPriority += 16 * abs( temp_Piece.GetX() - TempBoard.GetPieceSpawnX() );
if (temp_Piece.GetX() < TempBoard.GetPieceSpawnX()) trialPriority -= 8;
trialPriority -= (trialRotationDelta);
*/
// If this move is better than any move considered before,
// or if this move is equally ranked but has a higher priority,
// then update this to be our best move.
if
(
(trialMerit > currentBestMerit) ||
((trialMerit == currentBestMerit) && (trialPriority > currentBestPriority))
)
{
currentBestPriority = trialPriority;
currentBestMerit = trialMerit;
currentBestTranslationDelta = trialTranslationDelta;
currentBestRotationDelta = trialRotationDelta;
}
}
}
}
}
// Commit to this move
bestTranslationDelta = currentBestTranslationDelta;
bestRotationDelta = currentBestRotationDelta;
return( currentBestMerit );
}
// The following one-ply board evaluation function is adapted from the
// "xtris" application (multi-player Tetris for the X Window system),
// created by Roger Espel Llima <[email protected]>
//
// From the "xtris" documentation:
//
// "The values for the coefficients were obtained with a genetic algorithm
// using a population of 50 sets of coefficients, calculating 18 generations
// in about 500 machine-hours distributed among 20-odd Sparc workstations.
// This resulted in an average of about 50,000 completed lines."
//
// The following people contributed "ideas for the bot's decision algorithm":
//
// Laurent Bercot <[email protected]>
// Sebastien Blondeel <[email protected]>
//
//
// The algorithm computes 6 values on the whole pile:
//
// [1] height = max height of the pieces in the pile
// [2] holes = number of holes (empty positions with a full position somewhere
// above them)
// [3] frontier = length of the frontier between all full and empty zones
// (for each empty position, add 1 for each side of the position
// that touches a border or a full position).
// [4] drop = how far down we're dropping the current brick
// [5] pit = sum of the depths of all places where a long piece ( ====== )
// would be needed.
// [6] ehole = a kind of weighted sum of holes that attempts to calculate
// how hard they are to fill.
//
// droppedPieceRow is the row where we're dropping the piece,
// which is already in the board. Note that full lines have not been
// dropped, so we need to do special tests to skip them.
float STStrategyRogerLLimaLaurentBercotSebastienBlondeelOnePiece1996::PrivateStrategyEvaluate
(
STBoard & board,
int pieceDropDistance
)
{
int coeff_f = 260;
int coeff_height = 110;
int coeff_hole = 450;
int coeff_y = 290;
int coeff_pit = 190;
int coeff_ehole = 80;
int width = 0;
int height = 0;
width = board.GetWidth();
height = board.GetHeight();
int lineCellTotal [ (1 + 20 + 200) ]; // HACK: Should be dynamic!
int lin [ (1 + 20 + 200) ]; // HACK: Should be dynamic!
int hol [ (1 + 10 + 200) * (1 + 20 + 400) ]; // HACK: Should be dynamic!
int blockedS [ (1 + 10 + 200) ]; // HACK: Should be dynamic!
// If width is greater than 200, or height is greater than 400,
// just give up. I'd rather not use malloc() for Roger's algorithm.
// Really, this algorithm needs to be repaired to avoid the use of
// memory!
if (width > 200) return(0.0f);
if (height > 400) return(0.0f);
int x = 0;
int y = 0;
// ****** NOTE: ALL ARRAYS ARE ACCESSED WITH 0 BEING FIRST ELEMENT ********
// Fill lineCellTotal[] with total cells in each row.
for ( y = 1; y <= height; y++ )
{
lineCellTotal[ (y-1) ] = 0;
for ( x = 1; x <= width; x++ )
{
if (board.GetCell( x, y ) > 0)
lineCellTotal[ (y-1) ]++;
}
}
// Clobber blocked column array
for ( x = 1; x <= width; x++ )
{
blockedS[ (x-1) ] = (-1);
}
// Clear Lin array.
for ( y = 1; y <= height; y++ )
{
lin[ (y-1) ] = 0;
}
// Embedded Holes
int eHoles = 0;
for ( y = height; y >= 1; y-- ) // Top-to-Bottom
{
for ( x = 1; x <= width; x++ )
{
if (board.GetCell( x, y ) > 0)
{
hol [ (width * (y-1)) + (x-1) ] = 0;
blockedS[ (x-1) ] = y;
}
else
{
hol [ (width * (y-1)) + (x-1) ] = 1;
if (blockedS[ (x-1) ] >= 0)
{
int y2 = 0;
y2 = blockedS[ (x-1) ];
// If this more than two rows ABOVE current row, set
// to exactly two rows above.
if (y2 > (y + 2))
{
y2 = (y + 2);
}
// Descend to current row
for ( ; y2 > y; y2-- )
{
if (board.GetCell( x, y2 ) > 0)
{
hol[ (width * (y-1)) + (x-1) ] += lin[ (y2-1) ];
}
}
}
lin[ (y-1) ] += hol[ (width * (y-1)) + (x-1) ];
eHoles += hol[ (width * (y-1)) + (x-1) ];
}
}
}
// Determine Max Height
int maxHeight = 0;
for ( x = 1; x <= width; x++ )
{
for ( y = height; y >= 1; y-- ) // Top-to-Bottom
{
// If line is complete, ignore it for Max Height purposes...
if (width == lineCellTotal[ (y-1) ])
continue;
if ( (y > maxHeight) &&
(board.GetCell( x, y ) > 0) )
{
maxHeight = y;
}
}
}
// Count buried holes
int holes = 0;
int blocked = 0;
for ( x = 1; x <= width; x++ )
{
blocked = 0;
for ( y = height; y >= 1; y-- ) // Top-to-Bottom
{
// If line is complete, skip it!
if (width == lineCellTotal[ (y-1) ])
continue;
if (board.GetCell( x, y ) > 0)
{
blocked = 1; // We encountered an occupied cell; all below is blocked
}
else
{
// All of the following is in the context of the cell ( x, y )
// being UN-occupied.
// If any upper row had an occupied cell in this column, this
// unoccupied cell is considered blocked.
if (blocked)
{
holes++; // This unoccupied cell is buried; it's a hole.
}
}
}
}
// Count Frontier
int frontier = 0;
for ( x = 1; x <= width; x++ )
{
for ( y = height; y >= 1; y-- ) // Top-to-Bottom
{
// If line is complete, skip it!
if (width == lineCellTotal[ (y-1) ])
continue;
if (0 == board.GetCell( x, y ))
{
// All of the following is in the context of the cell ( x, y )
// being UN-occupied.
// If row is not the top, and row above this one is occupied,
// then this unoccupied cell counts as a frontier.
if ( (y < height) &&
(board.GetCell( x, (y + 1) ) > 0) )
{
frontier++;
}
// If this row is not the bottom, and the row below is occupied,
// this unoccupied cell counts as a frontier.
if ( (y > 1) &&
(board.GetCell( x, (y - 1) ) > 0) )
{
frontier++;
}
// If the column is not the first, and the column to the left is
// occupied, then this unoccupied cell counts as a frontier.
// Or, if this *is* the left-most cell, it is an automatic frontier.
// (since the beyond the board is in a sense "occupied")
if ( ((x > 1) &&
(board.GetCell( x - 1, y ) > 0)) ||
(1 == x) )
{
frontier++;
}
// If the column is not the right-most, and the column to the right is
// occupied, then this unoccupied cell counts as a frontier.
// Or, if this *is* the right-most cell, it is an automatic frontier.
// (since the beyond the board is in a sense "occupied")
if ( ((x < width) &&
(board.GetCell( x + 1, y ) > 0)) ||
(width == x) )
{
frontier++;
}
}
}
}
int v = 0;
for ( x = 1; x <= width; x++ )
{
// NOTE: The following seems to descend as far as a 2-column-wide
// profile can fall for each column.
// Scan Top-to-Bottom
y = height;
while
(
// Line is not below bottom row...
(y >= 1) &&
// Cell is unoccupied or line is full...
( (0 == board.GetCell( x, y )) ||
(width == lineCellTotal[ (y-1) ]) ) &&
(
// (Not left column AND (left is empty OR line full))
((x > 1) &&
((0 == board.GetCell( x - 1, y )) ||
(width == lineCellTotal[ (y-1) ])))
|| // ...OR...
// (Not right column AND (right is empty OR line full))
((x < width) &&
((0 == board.GetCell( x + 1, y )) ||
(width == lineCellTotal[ (y-1) ]))))
)
{
y--; // Descend
}
// Count how much further we can fall just considering obstacles
// in our column.
int p = 0;
p = 0;
for ( ;
((y >= 1) && (0 == board.GetCell( x, y )));
y--, p++ ) ;
// If this is a deep well, it's worth punishing.
if (p >= 2)
{
v -= (coeff_pit * ( p - 1 ));
}
}
float rating = 0.0f;
rating = (float)(v);
rating -= (float)(coeff_f * frontier );
rating -= (float)(coeff_height * maxHeight );
rating -= (float)(coeff_hole * holes );
rating -= (float)(coeff_ehole * eHoles );
rating += (float)(coeff_y * pieceDropDistance ); // Reward drop depth!
return( rating );
}
}
}
| 24.57619 | 97 | 0.564942 | TetrisAI |
c598b41954851370883a4876885e36af02fa6e61 | 2,857 | cc | C++ | src/eic_evgen/reaction_routine.cc | sjdkay/DEMPGen | a357cfcd89978db3323435111cb1e327b191352d | [
"MIT"
] | null | null | null | src/eic_evgen/reaction_routine.cc | sjdkay/DEMPGen | a357cfcd89978db3323435111cb1e327b191352d | [
"MIT"
] | 1 | 2022-03-07T21:30:26.000Z | 2022-03-07T21:30:26.000Z | src/eic_evgen/reaction_routine.cc | sjdkay/DEMPGen | a357cfcd89978db3323435111cb1e327b191352d | [
"MIT"
] | 3 | 2022-03-07T21:19:40.000Z | 2022-03-10T15:37:25.000Z | ///*--------------------------------------------------*/
/// Reaction_routine.cc
///
/// Creator: Wenliang (Bill) Li
/// Date: Mar 12 2020
/// Email: [email protected]
///
/// Comment: Mar 12, 2020: Subroutine Exclusive_Omega_Prodoction is created
/// modeled off the Exclusive_Omega_Prodoction routine written by
/// A. Zafar
///
#include "reaction_routine.h"
#include "eic.h"
#include "particleType.h"
using namespace std;
/*--------------------------------------------------*/
/// Reaction
Reaction::Reaction(TString particle_str) {
rParticle = particle_str;
cout << "Produced particle is: " << GetParticle() << endl;
cout << "Generated process: e + p -> e' + p' + " << GetParticle() << endl;
tTime.Start();
cout << "/*--------------------------------------------------*/" << endl;
cout << "Starting setting up process" << endl;
cout << endl;
TDatime dsTime;
cout << "Start Time: " << dsTime.GetHour() << ":" << dsTime.GetMinute() << endl;
}
// SJDK 09/02/22 - New reaction where the particle and hadron are specified
Reaction::Reaction(TString particle_str, TString hadron_str) {
rParticle = particle_str;
rHadron = hadron_str;
cout << "Produced particle is: " << GetParticle() << endl;
cout << "Produced hadron is: " << GetHadron() << endl;
cout << "Generated process: e + p -> e'+ " << GetHadron() << " + " << GetParticle() << endl;
tTime.Start();
cout << "/*--------------------------------------------------*/" << endl;
cout << "Starting setting up process" << endl;
cout << endl;
TDatime dsTime;
cout << "Start Time: " << dsTime.GetHour() << ":" << dsTime.GetMinute() << endl;
}
Reaction::Reaction(){};
Reaction::~Reaction() {
// ppiOut.close();
// ppiDetails.close();
cout << endl;
cout << "Ending the process" << endl;
cout << "/*--------------------------------------------------*/" << endl;
tTime.Stop();
tTime.Print();
TDatime deTime;
cout << "End Time: " << deTime.GetHour() << ":" << deTime.GetMinute() << endl;
}
/*--------------------------------------------------*/
///
void Reaction::process_reaction() {
if (rParticle == "Pi+") {
PiPlus_Production* rr1 = new PiPlus_Production(rParticle);
rr1->process_reaction();
delete rr1;
}
else if (rParticle == "Pi0") {
// Pi0_Production* r1 = new Pi0_Production("Eta");
Pi0_Production* rr1 = new Pi0_Production(rParticle);
rr1->process_reaction();
delete rr1;
}
// 09/02/22 - SJDK - K+ production, initialises with particle and hadron specified
else if (rParticle == "K+") {
KPlus_Production* rr1 = new KPlus_Production(rParticle, rHadron);
rr1->process_reaction();
delete rr1;
}
// SJDK - 08/02/22 - Deleted large block of commented code that was below, was only there as reference?
}
| 28.57 | 105 | 0.547427 | sjdkay |
c59eec8d9e32e294c484a57dbba628de6cab8f2a | 763 | cpp | C++ | src/band_list.cpp | peterus/ESP32_WSPR | 979ba33f855141ac85dbbf7ac3606bdb06301985 | [
"MIT"
] | null | null | null | src/band_list.cpp | peterus/ESP32_WSPR | 979ba33f855141ac85dbbf7ac3606bdb06301985 | [
"MIT"
] | null | null | null | src/band_list.cpp | peterus/ESP32_WSPR | 979ba33f855141ac85dbbf7ac3606bdb06301985 | [
"MIT"
] | null | null | null | #include "band_list.h"
String BandConfig::getName() const {
return _name;
}
BandConfig::BandConfig(String const &name, ConfigBool *enable, ConfigInt *frequency) {
_name = name;
_enable = enable;
_frequency = frequency;
}
bool BandConfig::isEnabled() const {
return _enable->getValue();
}
long BandConfig::getFrequency() const {
return _frequency->getValue();
}
BandList::BandList() : _nextEntry(_frequencyList.begin()) {
}
void BandList::add(BandConfig frequency) {
_frequencyList.push_back(frequency);
_nextEntry = _frequencyList.begin();
}
BandConfig BandList::getNext() {
BandConfig value = *_nextEntry;
_nextEntry++;
if (_nextEntry == _frequencyList.end()) {
_nextEntry = _frequencyList.begin();
}
return value;
}
| 20.621622 | 86 | 0.706422 | peterus |
c5a77dc47bfd97026329f9e1dd8da605ddf730bf | 3,136 | cpp | C++ | code archive/TIOJ/1739.cpp | brianbbsu/program | c4505f2b8c0b91010e157db914a63c49638516bc | [
"MIT"
] | 4 | 2018-04-08T08:07:58.000Z | 2021-06-07T14:55:24.000Z | code archive/TIOJ/1739.cpp | brianbbsu/program | c4505f2b8c0b91010e157db914a63c49638516bc | [
"MIT"
] | null | null | null | code archive/TIOJ/1739.cpp | brianbbsu/program | c4505f2b8c0b91010e157db914a63c49638516bc | [
"MIT"
] | 1 | 2018-10-29T12:37:25.000Z | 2018-10-29T12:37:25.000Z | //{
#include<bits/stdc++.h>
using namespace std;
typedef int ll;
typedef double lf;
typedef pair<ll,ll> ii;
#define REP(i,n) for(ll i=0;i<n;i++)
#define REP1(i,n) for(ll i=1;i<=n;i++)
#define FILL(i,n) memset(i,n,sizeof i)
#define X first
#define Y second
#define SZ(_a) (int)_a.size()
#define ALL(_a) _a.begin(),_a.end()
#define pb push_back
#ifdef brian
#define debug(...) do{\
fprintf(stderr,"%s - %d (%s) = ",__PRETTY_FUNCTION__,__LINE__,#__VA_ARGS__);\
_do(__VA_ARGS__);\
}while(0)
template<typename T>void _do(T &&_x){cerr<<_x<<endl;}
template<typename T,typename ...S> void _do(T &&_x,S &&..._t){cerr<<_x<<" ,";_do(_t...);}
template<typename _a,typename _b> ostream& operator << (ostream &_s,const pair<_a,_b> &_p){return _s<<"("<<_p.X<<","<<_p.Y<<")";}
template<typename It> ostream& _OUTC(ostream &_s,It _ita,It _itb)
{
_s<<"{";
for(It _it=_ita;_it!=_itb;_it++)
{
_s<<(_it==_ita?"":",")<<*_it;
}
_s<<"}";
return _s;
}
template<typename _a> ostream &operator << (ostream &_s,vector<_a> &_c){return _OUTC(_s,ALL(_c));}
template<typename _a> ostream &operator << (ostream &_s,set<_a> &_c){return _OUTC(_s,ALL(_c));}
template<typename _a,typename _b> ostream &operator << (ostream &_s,map<_a,_b> &_c){return _OUTC(_s,ALL(_c));}
template<typename _t> void pary(_t _a,_t _b){_OUTC(cerr,_a,_b);cerr<<endl;}
#define IOS()
#else
#define debug(...)
#define pary(...)
#define endl '\n'
#define IOS() ios_base::sync_with_stdio(0);cin.tie(0);
#endif // brian
//}
#ifdef brian
int getNumQuestions(){
ll q;
cin>>q;
return q;
}
void getQuestion(int &A, int &B)
{
cin>>A>>B;
}
void answer(int ans)
{
printf("Answer: %d\n", ans);
}
#else
#include "lib1739.h"
#endif
const ll MAXn=3e5+5,MAXlg=__lg(MAXn)+2;
const ll MOD=1000000007;
const ll INF=ll(1e15);
vector<ii> _v[2 * MAXn];
int vid[MAXn][MAXlg], vit = 0;
inline vector<ii> &v(int i,int j)
{
if(vid[i][j] == 0)return _v[vid[i][j] = ++vit];
else return _v[vid[i][j]];
}
ll mp(int i, int j, int x)
{
ll t = lower_bound(ALL(v(i,j)), ii(x, -1)) - v(i,j).begin();
if(t == SZ(v(i,j)) || v(i,j)[t].X != x)return x;
else return v(i,j)[t].Y;
}
int d[MAXn], u[MAXn];
int main()
{
debug(MAXn * MAXlg);
int n, m;
scanf("%d%d", &n, &m);
REP1(i, m)scanf("%d", d + i);
REP(i, m)
{
v(i, 0).pb(ii(d[i+1], d[i+1] + 1));
v(i, 0).pb(ii(d[i+1] + 1, d[i+1]));
}
for(int j = 1;(1<<j) <= m;j++)
{
for(int i = 0;i + (1<<j) <= m;i += (1<<j))
{
ll t = i + (1<<(j-1));
for(auto &p:v(i, j-1))
{
v(i,j).pb(ii(p.X, mp(t, j-1, p.Y)));
u[p.X] = 1;
}
for(auto &p:v(t, j-1))if(!u[p.X])v(i,j).pb(p);
for(auto &p:v(i,j))u[p.X] = 0;
sort(ALL(v(i,j)));
}
}
/*ll q = getNumQuestions();
while(q--)
{
int a, b;
getQuestion(a, b);
int now = 0;
for(int j = MAXlg - 1;j >= 0;j --)if(b&(1<<j))
{
a = mp(now, j, a);
now += (1<<j);
}
answer(a);
}*/
} | 23.938931 | 129 | 0.520408 | brianbbsu |
c5ababaec40d08b3250baf901c5c3f8cbedb618d | 3,297 | hpp | C++ | Dialogs/MoveBaseDialog.hpp | joseffallman/Intrusion | a3937bcbfaaab7da0321dce3ab7d9a5fe1b350ff | [
"MIT"
] | null | null | null | Dialogs/MoveBaseDialog.hpp | joseffallman/Intrusion | a3937bcbfaaab7da0321dce3ab7d9a5fe1b350ff | [
"MIT"
] | 4 | 2019-04-21T23:30:19.000Z | 2019-05-08T21:03:25.000Z | Dialogs/MoveBaseDialog.hpp | joseffallman/Intrusion | a3937bcbfaaab7da0321dce3ab7d9a5fe1b350ff | [
"MIT"
] | 1 | 2019-03-22T08:28:07.000Z | 2019-03-22T08:28:07.000Z | /*
* Name: IntMoveBaseDialog
* Date: 2020-03-29
* Version: 1.0
* Author: Josef
*
* Description:
* The Move base dialog.
*/
class IntMoveBaseDialog : IntBaseDialog
{
onUnload = "call Intrusion_Client_MoveBaseDialog_onUnload;";
class Controls : Controls
{
class _CT_CONTROLS_GROUP
{
type = 15;
idc = -1;
style = 16;
//x = 0.5 * GUI_GRID_W + GUI_GRID_X;
//y = 2.5 * GUI_GRID_H + GUI_GRID_Y;
//w = 39.5 * GUI_GRID_W;
//h = 17.5 * GUI_GRID_H;
x = 0.5 * GUI_GRID_W + GUI_GRID_X;
y = 2.5 * GUI_GRID_H + GUI_GRID_Y;
w = 39 * GUI_GRID_W;
h = 17 * GUI_GRID_H;
shadow = 0;
onLBDrop = "call Intrusion_Client_MoveBaseDialog_OnMapDrop;";
class ScrollBar
{
color[] = {1,1,1,0.6};
colorActive[] = {1,1,1,1};
colorDisabled[] = {1,1,1,0.3};
thumb = "\A3\ui_f\data\gui\cfg\scrollbar\thumb_ca.paa";
arrowEmpty = "\A3\ui_f\data\gui\cfg\scrollbar\arrowEmpty_ca.paa";
arrowFull = "\A3\ui_f\data\gui\cfg\scrollbar\arrowFull_ca.paa";
border = "\A3\ui_f\data\gui\cfg\scrollbar\border_ca.paa";
};
class VScrollbar: ScrollBar
{
width = 0.021;
autoScrollSpeed = -1;
autoScrollDelay = 5;
autoScrollRewind = 0;
shadow = 0;
};
class HScrollbar: ScrollBar
{
height = 0.028;
shadow = 0;
};
class Controls
{
class Map : RscMapControl
{
idc = 2550;
x = 0.5 * GUI_GRID_W;
y = 2.5 * GUI_GRID_H + GUI_GRID_Y;
w = 26.5 * GUI_GRID_W;
h = 16.5 * GUI_GRID_H;
//scaleMin = 0.02;
//scaleMax = 0.02;
scaleDefault = 1; //0.02;
onMouseButtonClick = "call Intrusion_Client_MoveBaseDialog_onMapClick;";
};
class ListBox : RscListBox
{
idc = 2552;
x = 27.5 * GUI_GRID_W + GUI_GRID_X;
y = 0;
w = 11.5 * GUI_GRID_W;
h = 16 * GUI_GRID_H;
canDrag = 1;
onLBSelChanged = "call Intrusion_Client_MoveBaseDialog_OnListBoxSelectChanged;";
onLBDrag = "call Intrusion_Client_MoveBaseDialog_OnListBoxDrag;";
};
};
};
class CancelButton : Base_CancelButton
{
action = "call Intrusion_Client_MoveBaseDialog_OnCancelButtonPressed;";
};
class OKButton : Base_OkButton
{
text = "Move Base";
action = "call Intrusion_Client_MoveBaseDialog_OnOkButtonPressed;";
};
class Header : Base_Header
{
text = "Move base dialog.";
};
class Description : Base_Description
{
idc = 2553;
x = 0.5 * GUI_GRID_W + GUI_GRID_X;
y = 19.5 * GUI_GRID_H + GUI_GRID_Y;
w = 27.5 * GUI_GRID_W;
h = 5 * GUI_GRID_H;
//colorBackground[] = {1,1,1,1};
};
};
};
class ContextMenu : RscListBox
{
idc = 2560;
type = CT_LISTBOX;
style = ST_LEFT;
x = 0.5 * GUI_GRID_W;
y = 2.5 * GUI_GRID_H + GUI_GRID_Y;
w = 5 * GUI_GRID_W;
h = 5 * GUI_GRID_H;
colorSelectBackground[] = {0.6,0.6,0.6,1};
colorSelectBackground2[] = {0.2,0.2,0.2,1};
onLBSelChanged = "call Intrusion_Client_MoveBaseContextMenu_OnListBoxSelectChanged;";
};
| 24.604478 | 88 | 0.561116 | joseffallman |
c5af4925158a050a299d3431b0624c5477aec1d8 | 7,040 | cpp | C++ | NotThatGameEngine/NotThatGameEngine/GameObject.cpp | HoduRe/NotThatGameEngine | e1a6bd073fbd34f3598b2c03f8d0d82cd8540ccc | [
"MIT"
] | 1 | 2021-01-07T13:36:34.000Z | 2021-01-07T13:36:34.000Z | NotThatGameEngine/NotThatGameEngine/GameObject.cpp | HoduRe/NotThatGameEngine | e1a6bd073fbd34f3598b2c03f8d0d82cd8540ccc | [
"MIT"
] | null | null | null | NotThatGameEngine/NotThatGameEngine/GameObject.cpp | HoduRe/NotThatGameEngine | e1a6bd073fbd34f3598b2c03f8d0d82cd8540ccc | [
"MIT"
] | 1 | 2021-01-06T11:10:33.000Z | 2021-01-06T11:10:33.000Z | #include "GameObject.h"
#include "OpenGLFuncionality.h"
#include "Component.h"
#include "Transform.h"
#include "Mesh.h"
#include "Material.h"
#include "Camera.h"
#include "Animation.h"
#include "Application.h"
#include "Textures.h"
GameObject::GameObject(Application* _App, long long int _id, std::string _name, GameObject* _parent, bool _enabled, std::vector<GameObject*> children) :
name(_name), id(_id), worldTransform(), parent(_parent), childs(children), enabled(_enabled), deleteGameObject(false), idGenerator(),
mesh(nullptr), material(nullptr), transform(nullptr), camera(nullptr), App(_App) {
AddComponent(COMPONENT_TYPE::TRANSFORM, idGenerator.Int());
}
GameObject::~GameObject() {
delete mesh;
delete material;
delete transform;
delete camera;
mesh = nullptr;
material = nullptr;
transform = nullptr;
camera = nullptr;
parent = nullptr;
}
void GameObject::Update() {
if (mesh != nullptr) { mesh->SetIsAnimation(false); }
int size = childs.size();
for (int i = 0; i < size; i++) { if (childs[i]->enabled) { childs[i]->Update(); } }
}
void GameObject::PostUpdate(int focusId) {
// TODO: try implementing dirty flag ;)
if (enabled) {
transform->RecalculateTransformFromParent();
if (camera != nullptr) { camera->UpdateTransform(); }
if (animation != nullptr) { animation->PlayAnimation(); }
for (int i = childs.size() - 1; i > -1; i--) { childs[i]->PostUpdate(focusId); }
if (mesh != nullptr) {
if (material != nullptr) { OpenGLFunctionality::DrawMeshes(*mesh, worldTransform, App->texture->IsTextureRepeated(material->GetTextureName())); }
else { OpenGLFunctionality::DrawMeshes(*mesh, worldTransform, 0); }
DebugBones();
if (id == focusId) { ManageAABB(mesh->boundingBox, true); }
else { ManageAABB(mesh->boundingBox); }
if (mesh->paintNormals) { OpenGLFunctionality::DrawLines(worldTransform, mesh->DebugNormals(), mesh->debugNormals); }
}
}
CheckComponentDeletion();
}
Component* GameObject::AddComponent(COMPONENT_TYPE _type, long long int id) {
if (id == -1) { id = idGenerator.Int(); }
switch (_type) {
case COMPONENT_TYPE::TRANSFORM: if (transform == nullptr) { return transform = new Transform(id, this); } break;
case COMPONENT_TYPE::MESH: if (mesh == nullptr) { return mesh = new Mesh(id, this); } break;
case COMPONENT_TYPE::MATERIAL: if (material == nullptr) { return material = new Material(id, this); } break;
case COMPONENT_TYPE::CAMERA: if (camera == nullptr) { return camera = new Camera(id, this); } break;
case COMPONENT_TYPE::ANIMATION: if (animation == nullptr) { return animation = new Animation(id, this); } break;
default:
assert(true == false);
break;
}
return nullptr;
}
bool GameObject::AddGameObjectByParent(GameObject* newObject) {
bool ret = false;
if (newObject->parent->id == this->id) {
childs.push_back(newObject);
return true;
}
else {
int size = childs.size();
for (int i = 0; i < size; i++) {
ret = childs[i]->AddGameObjectByParent(newObject);
if (ret) { return ret; }
}
}
return false;
}
bool GameObject::CheckChildDeletionById(long long int _id) {
bool ret = false;
if (id == _id) {
SetDeleteGameObject();
return true;
}
else {
int size = childs.size();
for (int i = 0; i < size; i++) {
ret = childs[i]->CheckChildDeletionById(_id);
if (ret) { return ret; }
}
}
return false;
}
void GameObject::SetDeleteGameObject(bool deleteBool) {
deleteGameObject = deleteBool;
int size = childs.size();
for (int i = 0; i < size; i++) { childs[i]->SetDeleteGameObject(deleteBool); }
}
void GameObject::SetDeleteComponent(COMPONENT_TYPE _type) {
Component* component = GetComponent(_type);
component->deleteComponent = true;
}
void GameObject::CheckComponentDeletion() {
if (mesh != nullptr) { if (mesh->deleteComponent) { delete mesh; } }
if (material != nullptr) { if (material->deleteComponent) { delete material; } }
if (camera != nullptr) { if (camera->deleteComponent) { delete camera; } }
}
Component* GameObject::GetComponent(COMPONENT_TYPE _type) {
switch (_type) {
case COMPONENT_TYPE::TRANSFORM: return transform;
case COMPONENT_TYPE::MESH: return mesh;
case COMPONENT_TYPE::MATERIAL: return material;
case COMPONENT_TYPE::CAMERA: return camera;
case COMPONENT_TYPE::ANIMATION: return animation;
default:
assert(true == false);
break;
}
return nullptr;
}
Component* GameObject::FindGameObjectChildByComponent(long long int componentId) {
Component* ret = nullptr;
if (transform != nullptr) { if (transform->id == componentId) { return transform; } }
if (mesh != nullptr) { if (mesh->id == componentId) { return mesh; } }
if (material != nullptr) { if (material->id == componentId) { return material; } }
if (camera != nullptr) { if (camera->id == componentId) { return camera; } }
for (int i = 0; i < childs.size(); i++) {
ret = childs[i]->FindGameObjectChildByComponent(componentId);
if (ret) { return ret; }
}
return ret;
}
GameObject* GameObject::FindGameObjectChild(long long int id) {
GameObject* ret = nullptr;
for (int i = 0; i < childs.size(); i++) {
if (childs[i]->id == id) { return childs[i]; }
else {
ret = childs[i]->FindGameObjectChild(id);
if (ret) { return ret; }
}
}
return ret;
}
void GameObject::ManageAABB(AABB aabb, bool focus, bool guaranteedShow) {
if (mesh != nullptr) {
bool show = guaranteedShow || focus ? true : mesh->showBoxes;
if (show) {
OBB obb = aabb;
obb.Transform(worldTransform);
AABB newBoundingBox;
newBoundingBox.SetNegativeInfinity();
newBoundingBox.Enclose(obb);
std::vector<float> cornerVec;
for (int i = 0; i < 8; i++) {
float3 corner = newBoundingBox.CornerPoint(i);
cornerVec.push_back(corner.x);
cornerVec.push_back(corner.y);
cornerVec.push_back(corner.z);
}
if (focus) { OpenGLFunctionality::DrawBox(cornerVec, 80.0f, 0.0f, 0.0f); }
else { OpenGLFunctionality::DrawBox(cornerVec); }
}
}
}
void GameObject::DebugBones() {
AABB boneAABB;
if (mesh->showAllBones) {
for (uint i = 0; i < mesh->boneDisplayVecSize; i++) {
boneAABB.SetNegativeInfinity();
int size = mesh->vertexSize / 3;
for (int it = 0; it < size; it++) {
for (int itAux = 0; itAux < 4; itAux++) {
if (mesh->boneIDs[(it * 4) + itAux] == (int)i) {
boneAABB.Enclose(vec(mesh->vertices[it * 3], mesh->vertices[(it * 3) + 1], mesh->vertices[(it * 3) + 2]));
}
}
}
ManageAABB(boneAABB, false, true);
}
}
else {
for (uint i = 0; i < mesh->boneDisplayVecSize; i++) {
if (mesh->boneDisplayVec[i]) {
boneAABB.SetNegativeInfinity();
int size = mesh->vertexSize / 3;
for (int it = 0; it < size; it++) {
for (int itAux = 0; itAux < 4; itAux++) {
if (mesh->boneIDs[(it * 4) + itAux] == (int)i) {
boneAABB.Enclose(vec(mesh->vertices[it * 3], mesh->vertices[(it * 3) + 1], mesh->vertices[(it * 3) + 2]));
}
}
}
ManageAABB(boneAABB, false, true);
}
}
}
}
| 21.595092 | 152 | 0.65554 | HoduRe |
c5b2576542165e747bc3f04a7a127a44f73987bd | 37,332 | cpp | C++ | FireRender.Max.Plugin/parser/MaterialLoader.cpp | Vsevolod1983/RadeonProRenderMaxPlugin | d5393fd04e45dd2c77c8b17fac4e10b20df55285 | [
"Apache-2.0"
] | 6 | 2020-05-24T12:00:43.000Z | 2021-07-13T06:22:49.000Z | FireRender.Max.Plugin/parser/MaterialLoader.cpp | Vsevolod1983/RadeonProRenderMaxPlugin | d5393fd04e45dd2c77c8b17fac4e10b20df55285 | [
"Apache-2.0"
] | 4 | 2020-09-17T17:05:38.000Z | 2021-06-23T14:29:14.000Z | FireRender.Max.Plugin/parser/MaterialLoader.cpp | Vsevolod1983/RadeonProRenderMaxPlugin | d5393fd04e45dd2c77c8b17fac4e10b20df55285 | [
"Apache-2.0"
] | 8 | 2020-05-15T08:29:17.000Z | 2021-07-14T08:38:07.000Z | /**********************************************************************
Copyright 2020 Advanced Micro Devices, Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
********************************************************************/
#if 0
#include "MaterialLoader.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <map>
#include <set>
#include <string>
#include <stack>
#include <regex>
#include "Common.h"
using namespace std;
//executed RPR func and check for an error
#define CHECK_NO_ERROR(func) { \
rpr_int status = func; \
if (status != RPR_SUCCESS) \
throw std::runtime_error("Radeon ProRender error (" + std::to_string(status) + ") in " + std::string(__FILE__) + ":" + std::to_string(__LINE__)); \
}
namespace
{
const std::string kTab = " "; // default 4spaces tab for xml writer
#ifdef RPR_VERSION_MAJOR_MINOR_REVISION
const int kVersion = RPR_VERSION_MAJOR_MINOR_REVISION;
#else
const int kVersion = RPR_API_VERSION;
#endif
const std::map<int, std::string> kMaterialTypeNames{ { RPR_MATERIAL_NODE_DIFFUSE, "DIFFUSE" },
{ RPR_MATERIAL_NODE_MICROFACET, "MICROFACET" },
{ RPR_MATERIAL_NODE_REFLECTION, "REFLECTION" },
{ RPR_MATERIAL_NODE_REFRACTION, "REFRACTION" },
{ RPR_MATERIAL_NODE_MICROFACET_REFRACTION, "MICROFACET_REFRACTION" },
{ RPR_MATERIAL_NODE_TRANSPARENT, "TRANSPARENT" },
{ RPR_MATERIAL_NODE_EMISSIVE, "EMISSIVE" },
{ RPR_MATERIAL_NODE_WARD, "WARD" },
{ RPR_MATERIAL_NODE_ADD, "ADD" },
{ RPR_MATERIAL_NODE_BLEND, "BLEND" },
{ RPR_MATERIAL_NODE_ARITHMETIC, "ARITHMETIC" },
{ RPR_MATERIAL_NODE_FRESNEL, "FRESNEL" },
{ RPR_MATERIAL_NODE_NORMAL_MAP, "NORMAL_MAP" },
{ RPR_MATERIAL_NODE_IMAGE_TEXTURE, "IMAGE_TEXTURE" },
{ RPR_MATERIAL_NODE_NOISE2D_TEXTURE, "NOISE2D_TEXTURE" },
{ RPR_MATERIAL_NODE_DOT_TEXTURE, "DOT_TEXTURE" },
{ RPR_MATERIAL_NODE_GRADIENT_TEXTURE, "GRADIENT_TEXTURE" },
{ RPR_MATERIAL_NODE_CHECKER_TEXTURE, "CHECKER_TEXTURE" },
{ RPR_MATERIAL_NODE_CONSTANT_TEXTURE, "CONSTANT_TEXTURE" },
{ RPR_MATERIAL_NODE_INPUT_LOOKUP, "INPUT_LOOKUP" },
{ RPR_MATERIAL_NODE_UBERV2, "STANDARD" },
{ RPR_MATERIAL_NODE_BLEND_VALUE, "BLEND_VALUE" },
{ RPR_MATERIAL_NODE_PASSTHROUGH, "PASSTHROUGH" },
{ RPR_MATERIAL_NODE_ORENNAYAR, "ORENNAYAR" },
{ RPR_MATERIAL_NODE_FRESNEL_SCHLICK, "FRESNEL_SCHLICK" },
{ RPR_MATERIAL_NODE_DIFFUSE_REFRACTION, "DIFFUSE_REFRACTION" },
{ RPR_MATERIAL_NODE_BUMP_MAP, "BUMP_MAP" }, };
const std::map<std::string, int> kNodeTypesMap = { { "INPUT_COLOR4F", RPR_MATERIAL_NODE_INPUT_TYPE_FLOAT4 },
{ "INPUT_FLOAT1", RPR_MATERIAL_NODE_INPUT_TYPE_FLOAT4 },
{ "INPUT_UINT", RPR_MATERIAL_NODE_INPUT_TYPE_UINT },
{ "INPUT_NODE", RPR_MATERIAL_NODE_INPUT_TYPE_NODE },
{ "INPUT_TEXTURE", RPR_MATERIAL_NODE_INPUT_TYPE_IMAGE },
{ "DIFFUSE", RPR_MATERIAL_NODE_DIFFUSE },
{ "MICROFACET", RPR_MATERIAL_NODE_MICROFACET },
{ "REFLECTION", RPR_MATERIAL_NODE_REFLECTION },
{ "REFRACTION", RPR_MATERIAL_NODE_REFRACTION },
{ "MICROFACET_REFRACTION", RPR_MATERIAL_NODE_MICROFACET_REFRACTION },
{ "TRANSPARENT", RPR_MATERIAL_NODE_TRANSPARENT },
{ "EMISSIVE", RPR_MATERIAL_NODE_EMISSIVE },
{ "WARD", RPR_MATERIAL_NODE_WARD },
{ "ADD", RPR_MATERIAL_NODE_ADD },
{ "BLEND", RPR_MATERIAL_NODE_BLEND },
{ "ARITHMETIC", RPR_MATERIAL_NODE_ARITHMETIC },
{ "FRESNEL", RPR_MATERIAL_NODE_FRESNEL },
{ "NORMAL_MAP", RPR_MATERIAL_NODE_NORMAL_MAP },
{ "IMAGE_TEXTURE", RPR_MATERIAL_NODE_IMAGE_TEXTURE },
{ "NOISE2D_TEXTURE", RPR_MATERIAL_NODE_NOISE2D_TEXTURE },
{ "DOT_TEXTURE", RPR_MATERIAL_NODE_DOT_TEXTURE },
{ "GRADIENT_TEXTURE", RPR_MATERIAL_NODE_GRADIENT_TEXTURE },
{ "CHECKER_TEXTURE", RPR_MATERIAL_NODE_CHECKER_TEXTURE },
{ "CONSTANT_TEXTURE", RPR_MATERIAL_NODE_CONSTANT_TEXTURE },
{ "INPUT_LOOKUP", RPR_MATERIAL_NODE_INPUT_LOOKUP },
{ "STANDARD", RPR_MATERIAL_NODE_UBERV2 },
{ "BLEND_VALUE", RPR_MATERIAL_NODE_BLEND_VALUE },
{ "PASSTHROUGH", RPR_MATERIAL_NODE_PASSTHROUGH },
{ "ORENNAYAR", RPR_MATERIAL_NODE_ORENNAYAR },
{ "FRESNEL_SCHLICK", RPR_MATERIAL_NODE_FRESNEL_SCHLICK },
{ "DIFFUSE_REFRACTION", RPR_MATERIAL_NODE_DIFFUSE_REFRACTION },
{ "BUMP_MAP", RPR_MATERIAL_NODE_BUMP_MAP }, };
void printMaterialNode(rpr_material_node node)
{
std::cout << "__________________________________________" << std::endl;
size_t mat_name_size = 0;
CHECK_NO_ERROR(rprMaterialNodeGetInfo(node, RPR_OBJECT_NAME, 0, nullptr, &mat_name_size));
std::string mat_name;
mat_name.resize(mat_name_size - 1); // std::string contains terminator already
CHECK_NO_ERROR(rprMaterialNodeGetInfo(node, RPR_OBJECT_NAME, mat_name_size, &mat_name[0], nullptr));
rpr_int type = 0;
CHECK_NO_ERROR(rprMaterialNodeGetInfo(node, RPR_MATERIAL_NODE_TYPE, sizeof(rpr_int), &type, nullptr));
std::cout << "name " << mat_name + ", type: " << kMaterialTypeNames.at(type) << std::endl;
size_t count = 0;
CHECK_NO_ERROR(rprMaterialNodeGetInfo(node, RPR_MATERIAL_NODE_INPUT_COUNT, sizeof(size_t), &count, nullptr));
for (int i = 0; i < count; ++i)
{
size_t str_size = 0;
CHECK_NO_ERROR(rprMaterialNodeGetInputInfo(node, i, RPR_MATERIAL_NODE_INPUT_NAME_STRING, NULL, nullptr, &str_size));
char* str = new char[str_size];
CHECK_NO_ERROR(rprMaterialNodeGetInputInfo(node, i, RPR_MATERIAL_NODE_INPUT_NAME_STRING, str_size, str, nullptr));
std::cout << "\tparam: " << str << ". ";
delete[]str; str = nullptr;
std::cout << std::endl;
}
std::cout << "__________________________________________" << std::endl;
}
struct Param
{
std::string type;
std::string value;
};
struct MaterialNode
{
std::string type;
std::map<std::string, Param> params;
void* data; // RPR object
};
class XmlWriter
{
public:
XmlWriter(const std::string& file)
: m_doc(file)
, top_written(true)
{
}
~XmlWriter()
{
endDocument();
}
//write header
void startDocument()
{
m_doc << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << endl;
}
void endDocument()
{
int size = int_cast(m_nodes.size());
for (int i = 0; i < size; ++i)
{
endElement();
}
}
void startElement(const std::string& node_name)
{
// write prev node with atts
if (m_nodes.size() != 0 && top_written)
{
std::string tab = "";
for (int i = 0; i < m_nodes.size() - 1; ++i) tab += kTab;
const Node& node = m_nodes.top();
m_doc << tab << "<" << node.name << "";
for (const auto& at : node.atts)
{
m_doc << " " << at.type << "=\"" << at.value << "\""; // name = "value"
}
m_doc << ">" << endl;
}
m_nodes.push({ node_name });
top_written = true;
}
void endElement()
{
std::string tab = "";
for (int i = 0; i < m_nodes.size() - 1; ++i) tab += kTab;
const Node& node = m_nodes.top();
if (top_written)
{
const Node& node = m_nodes.top();
m_doc << tab << "<" << node.name << "";
for (const auto& at : node.atts)
{
m_doc << " " << at.type << "=\"" << at.value << "\""; // name = "value"
}
m_doc << "/>" << endl;
}
else
m_doc << tab << "</" << node.name << ">" << endl;
m_nodes.pop();
top_written = false;
}
void writeAttribute(const std::string& name, const std::string& value)
{
Node& node = m_nodes.top();
node.atts.push_back({ name, value });
}
void writeTextElement(const std::string& name, const std::string& text)
{
std::string tab = "";
for (int i = 0; i < m_nodes.size() - 1; ++i) tab += kTab;
if (m_nodes.size() != 0 && top_written)
{
const Node& node = m_nodes.top();
m_doc << tab << "<" << node.name << "";
for (const auto& at : node.atts)
{
m_doc << " " << at.type << "=\"" << at.value << "\""; // name = "value"
}
m_doc << ">" << endl;
}
tab += kTab;
// <name>text</name>
m_doc << tab << "<" << name << ">" << text << "</" << name << ">" << endl;
top_written = false;
}
private:
std::ofstream m_doc;
struct Node
{
std::string name;
std::vector<Param> atts;
};
std::stack<Node> m_nodes;
bool top_written; // true when element in top of m_nodes stack already written into xml
};
class XmlReader
{
public:
struct Node
{
std::string name;
std::string text;
std::map<string, string> atts;
bool is_closing;
Node() : name(""), text(""), is_closing(false) {};
};
XmlReader(const std::string& file) noexcept
: m_xml_text("")
, m_is_open(false)
, m_is_end(false)
, m_self_closing(false)
{
std::ifstream doc(file);
m_is_open = doc.is_open();
m_is_end = !m_is_open;
if (m_is_open)
{
m_xml_text = std::move(std::string((std::istreambuf_iterator<char>(doc)), std::istreambuf_iterator<char>()));
next();
}
}
bool isOpen() const noexcept
{
return m_is_open;
}
bool isEnd() const noexcept
{
return m_is_end;
}
bool next() noexcept
{
// root element is closed
if (!m_is_open || m_is_end)
return false;
if (m_self_closing)
{
m_self_closing = false;
Node& node = m_nodes.top();
node.is_closing = true;
return true;
}
try
{
// remove last node if it's closed
if (!m_nodes.empty() && m_nodes.top().is_closing)
m_nodes.pop();
// regex for searching XML nodes
std::regex node_reg("<[^<^>]*>");
std::smatch node_match;
m_is_end = !std::regex_search(m_xml_text, node_match, node_reg);
if (m_is_end)
return !m_is_end;
if (node_match.size() == 0)
Throw("Invalid xml: bad node");
std::string value = node_match[0];
std::regex name_reg("[^<][^>\\s/]+"); //ignoring '<' symbol
std::smatch name_match;
std::regex_search(value, name_match, name_reg);
// create new node if this is not the closing one
if (name_match.str().find('/') == std::string::npos)
m_nodes.push(Node());
Node& node = m_nodes.top();
node.name = name_match.str();
const std::string ksc_ending = "/>"; //self-closing node ending
if (value.size() > ksc_ending.size())
m_self_closing = std::equal(ksc_ending.rbegin(), ksc_ending.rend(), value.rbegin());
if (node.name.find('/') != std::string::npos)
{
node.is_closing = true;
node.name.erase(std::remove(node.name.begin(), node.name.end(), '/')); //remove closing '/'
}
std::regex att_split_reg("[\\S]+=\".*?\""); //split attributes regex string="string"
std::string attributes = name_match.suffix().str();
auto att_split_begin = std::sregex_iterator(attributes.begin(), attributes.end(), att_split_reg);
auto att_split_end = std::sregex_iterator();
// parsing attributes
for (auto i = att_split_begin; i != att_split_end; ++i)
{
std::string att = i->str();
std::regex att_reg("[^=?>\"]+");
auto att_begin = std::sregex_iterator(att.begin(), att.end(), att_reg);
auto att_end = std::sregex_iterator();
std::vector<std::string> splited_att;
splited_att.reserve(2); //should be 2 values
for (auto j = att_begin; j != att_end; ++j)
{
splited_att.push_back(j->str());
}
if (splited_att.size() == 2)
node.atts[splited_att[0]] = splited_att[1];
else // case when value = ""
node.atts[splited_att[0]] = "";
}
// cut parsed data
m_xml_text = node_match.suffix().str();
// looking for node text data
size_t pos = m_xml_text.find('<');
if (pos != std::string::npos && !m_self_closing)
{
node.text = m_xml_text.substr(0, pos);
node.text = std::regex_replace(node.text, std::regex("^[\\s]+"), ""); //removing beginning whitespaces
node.text = std::regex_replace(node.text, std::regex("[\\s]+^"), ""); //removing ending whitespaces
node.text = std::regex_replace(node.text, std::regex("[\\s]+"), " "); //replace multiple whitespaces by single space
}
}
catch (std::exception e)
{
cout << "Regex exception: " << e.what() << endl;
m_is_end = true;
}
return !m_is_end;
}
const Node& get() const
{
return m_nodes.top();
}
private:
void Throw(const std::string& msg)
{
m_is_end = true;
throw std::runtime_error(msg);
}
std::string m_xml_text;
bool m_is_open;
bool m_is_end;
bool m_self_closing;
std::stack<Node> m_nodes; //stores previoulsy open yet not closed nodes
};
rpr_material_node CreateMaterial(rpr_material_system sys, const MaterialNode& node, const std::string& name)
{
rpr_material_node mat = nullptr;
int type = kNodeTypesMap.at(node.type);
CHECK_NO_ERROR(rprMaterialSystemCreateNode(sys, type, &mat));
CHECK_NO_ERROR(rprObjectSetName(mat, name.c_str()));
return mat;
}
}
void ExportMaterials(const std::string& filename,
const std::set<rpr_material_node>& nodeList,
const std::set<rprx_material>& nodeListX ,
const std::vector<RPRX_DEFINE_PARAM_MATERIAL>& rprxParamList,
rprx_context contextX ,
std::unordered_map<rpr_image , RPR_MATERIAL_XML_EXPORT_TEXTURE_PARAM>& textureParameter,
void* closureNode, // pointer to a rpr_material_node or a rprx_material
const std::string& material_name // example : "Emissive_Fluorescent_Magenta"
)
{
XmlWriter writer(filename);
if (nodeListX.size() == 0 && nodeList.size() == 0)
{
cout << "MaterialExport error: materials input array is nullptr" << endl;
return;
}
try
{
writer.startDocument();
writer.startElement("material");
writer.writeAttribute("name", material_name);
// in case we need versioning the material XMLs... - unused for the moment.
writer.writeAttribute("version_exporter", "10");
//version of the RPR_API_VERSION used to generate this XML
std::stringstream hex_version;
hex_version << "0x" << std::hex << kVersion;
writer.writeAttribute("version_rpr", hex_version.str());
// file path as key, id - for material nodes connections
std::map<std::string, std::pair< std::string , rpr_image > > textures;
std::map<void*, std::string> objects; // <object, node_name> map
std::set<std::string> used_names; // to avoid duplicating node names
std::string closureNodeName = "";
// fill materials first
for(const auto& iNode : nodeList )
{
rpr_material_node mat = iNode;
if (objects.count(mat))
continue;
size_t name_size = 0;
CHECK_NO_ERROR(rprMaterialNodeGetInfo(mat, RPR_OBJECT_NAME, NULL, nullptr, &name_size));
std::string mat_node_name;
mat_node_name.resize(name_size - 1); // exclude extra terminator
CHECK_NO_ERROR(rprMaterialNodeGetInfo(mat, RPR_OBJECT_NAME, name_size, &mat_node_name[0], nullptr));
int postfix_id = 0;
if (mat_node_name.empty())
mat_node_name = "node" + std::to_string(postfix_id);
while (used_names.count(mat_node_name))
{
mat_node_name = "node" + std::to_string(postfix_id);
++postfix_id;
}
if ( mat == closureNode )
closureNodeName = mat_node_name;
objects[mat] = mat_node_name;
used_names.insert(mat_node_name);
}
for(const auto& iNode : nodeListX )
{
rprx_material mat = iNode;
if (objects.count(mat))
continue;
int postfix_id = 0;
std::string mat_node_name = "Uber_" + std::to_string(postfix_id);
while (used_names.count(mat_node_name))
{
mat_node_name = "Uber_" + std::to_string(postfix_id);
++postfix_id;
}
if ( mat == closureNode )
closureNodeName = mat_node_name;
objects[mat] = mat_node_name;
used_names.insert(mat_node_name);
}
// closure_node is the name of the node containing the final output of the material
writer.writeAttribute("closure_node", closureNodeName);
// look for images
for(const auto& iNode : nodeList )
{
rpr_material_node mat = iNode;
size_t input_count = 0;
CHECK_NO_ERROR(rprMaterialNodeGetInfo(mat, RPR_MATERIAL_NODE_INPUT_COUNT, sizeof(size_t), &input_count, nullptr));
for (int input_id = 0; input_id < input_count; ++input_id)
{
rpr_material_node_type input_type;
CHECK_NO_ERROR(rprMaterialNodeGetInputInfo(mat, input_id, RPR_MATERIAL_NODE_INPUT_TYPE, sizeof(input_type), &input_type, nullptr));
if (input_type != RPR_MATERIAL_NODE_INPUT_TYPE_IMAGE)
continue;
rpr_image img = nullptr;
CHECK_NO_ERROR(rprMaterialNodeGetInputInfo(mat, input_id, RPR_MATERIAL_NODE_INPUT_VALUE, sizeof(img), &img, nullptr));
if (objects.count(img)) //already mentioned
continue;
std::string img_node_name = "node0";
int postfix_id = 0;
while (used_names.count(img_node_name))
{
img_node_name = "node" + std::to_string(postfix_id);
++postfix_id;
}
objects[img] = img_node_name;
used_names.insert(img_node_name);
}
}
// optionally write description (at the moment there is no description)
writer.writeTextElement("description", "");
for(const auto& iNode : nodeList )
{
rpr_material_node node = iNode;
rpr_material_node_type type;
size_t input_count = 0;
CHECK_NO_ERROR(rprMaterialNodeGetInfo(node, RPR_MATERIAL_NODE_TYPE, sizeof(rpr_material_node_type), &type, nullptr));
CHECK_NO_ERROR(rprMaterialNodeGetInfo(node, RPR_MATERIAL_NODE_INPUT_COUNT, sizeof(size_t), &input_count, nullptr));
writer.startElement("node");
writer.writeAttribute("name", objects[node]);
writer.writeAttribute("type", kMaterialTypeNames.at(type));
for (int input_id = 0; input_id < input_count; ++input_id)
{
size_t read_count = 0;
CHECK_NO_ERROR(rprMaterialNodeGetInputInfo(node, input_id, RPR_MATERIAL_NODE_INPUT_NAME_STRING, sizeof(size_t), nullptr, &read_count));
std::vector<char> param_name(read_count, ' ');
CHECK_NO_ERROR(rprMaterialNodeGetInputInfo(node, input_id, RPR_MATERIAL_NODE_INPUT_NAME_STRING, sizeof(param_name), param_name.data(), nullptr));
std::string type = "";
std::string value = "";
rpr_material_node_type input_type;
CHECK_NO_ERROR(rprMaterialNodeGetInputInfo(node, input_id, RPR_MATERIAL_NODE_INPUT_TYPE, sizeof(input_type), &input_type, &read_count));
switch (input_type)
{
case RPR_MATERIAL_NODE_INPUT_TYPE_FLOAT4:
{
rpr_float fvalue[4] = { 0.f, 0.f, 0.f, 0.f };
CHECK_NO_ERROR(rprMaterialNodeGetInputInfo(node, input_id, RPR_MATERIAL_NODE_INPUT_VALUE, sizeof(fvalue), fvalue, nullptr));
//fvalue converted to string
std::stringstream ss;
ss << fvalue[0] << ", " <<
fvalue[1] << ", " <<
fvalue[2] << ", " <<
fvalue[3];
type = "float4";
value = ss.str();
break;
}
case RPR_MATERIAL_NODE_INPUT_TYPE_UINT:
{
rpr_int uivalue = RPR_SUCCESS;
CHECK_NO_ERROR(rprMaterialNodeGetInputInfo(node, input_id, RPR_MATERIAL_NODE_INPUT_VALUE, sizeof(uivalue), &uivalue, nullptr));
//value converted to string
type = "uint";
value = std::to_string(uivalue);
break;
}
case RPR_MATERIAL_NODE_INPUT_TYPE_NODE:
{
rpr_material_node connection = nullptr;
rpr_int res = rprMaterialNodeGetInputInfo(node, input_id, RPR_MATERIAL_NODE_INPUT_VALUE, sizeof(connection), &connection, nullptr);
CHECK_NO_ERROR(rprMaterialNodeGetInputInfo(node, input_id, RPR_MATERIAL_NODE_INPUT_VALUE, sizeof(connection), &connection, nullptr));
type = "connection";
if (!objects.count(connection) && connection)
{
throw std::runtime_error("input material node is missing");
}
value = objects[connection];
break;
}
case RPR_MATERIAL_NODE_INPUT_TYPE_IMAGE:
{
type = "connection";
rpr_image tex = nullptr;
CHECK_NO_ERROR(rprMaterialNodeGetInputInfo(node, input_id, RPR_MATERIAL_NODE_INPUT_VALUE, sizeof(tex), &tex, nullptr));
size_t name_size = 0;
CHECK_NO_ERROR(rprImageGetInfo(tex, RPR_OBJECT_NAME, NULL, nullptr, &name_size));
std::string tex_name;
tex_name.resize(name_size - 1);
CHECK_NO_ERROR(rprImageGetInfo(tex, RPR_OBJECT_NAME, name_size, &tex_name[0], nullptr));
//replace \\ by /
//so we ensure all paths are using same convention ( better for Unix )
for(int i=0; i<tex_name.length(); i++)
{
if ( tex_name[i] == '\\' )
tex_name[i] = '/';
}
// we don't want path that looks like : "H:/RPR/MatLib/MaterialLibrary/1.0 - Copy/RadeonProRMaps/Glass_Used_normal.jpg"
// all paths must look like "RadeonProRMaps/Glass_Used_normal.jpg"
// the path RadeonProRMaps/ is hard coded here for the moment .. needs to be exposed in exporter GUI if we change it ?
const std::string radeonProRMapsFolder = "/RadeonProRMaps/";
size_t pos = tex_name.find(radeonProRMapsFolder);
if ( pos != std::string::npos )
{
tex_name = tex_name.substr(pos+1);
int a=0;
}
if (!textures.count(tex_name))
{
int tex_node_id = 0;
std::string tex_node_name = objects[tex];
textures[tex_name] = std::pair<std::string , rpr_image> ( tex_node_name , tex ) ;
}
value = textures[tex_name].first;
break;
}
default:
throw std::runtime_error("unexpected material node input type " + std::to_string(input_type));
}
if (!value.empty())
{
writer.startElement("param");
writer.writeAttribute("name", param_name.data());
writer.writeAttribute("type", type);
writer.writeAttribute("value", value);
writer.endElement();
}
}
writer.endElement();
}
for(const auto& iNode : nodeListX )
{
rprx_material materialX = iNode;
writer.startElement("node");
writer.writeAttribute("name", objects[materialX]);
writer.writeAttribute("type", "UBER");
for(int iParam=0; iParam<rprxParamList.size(); iParam++)
{
std::string type = "";
std::string value = "";
rprx_parameter_type input_type = 0;
CHECK_NO_ERROR( rprxMaterialGetParameterType(contextX,materialX,rprxParamList[iParam].param,&input_type));
if ( input_type == RPRX_PARAMETER_TYPE_FLOAT4 )
{
rpr_float fvalue[4] = { 0.f, 0.f, 0.f, 0.f };
CHECK_NO_ERROR( rprxMaterialGetParameterValue(contextX,materialX,rprxParamList[iParam].param,&fvalue) );
//fvalue converted to string
std::stringstream ss;
ss << fvalue[0] << ", " <<
fvalue[1] << ", " <<
fvalue[2] << ", " <<
fvalue[3];
type = "float4";
value = ss.str();
}
else if ( input_type == RPRX_PARAMETER_TYPE_UINT )
{
rpr_int uivalue = RPR_SUCCESS;
CHECK_NO_ERROR( rprxMaterialGetParameterValue(contextX,materialX,rprxParamList[iParam].param,&uivalue));
//value converted to string
type = "uint";
value = std::to_string(uivalue);
}
else if ( input_type == RPRX_PARAMETER_TYPE_NODE )
{
rpr_material_node connection = 0;
CHECK_NO_ERROR( rprxMaterialGetParameterValue(contextX,materialX,rprxParamList[iParam].param,&connection));
if ( connection )
{
type = "connection";
if (!objects.count(connection) && connection)
{
throw std::runtime_error("input material node is missing");
}
const auto& connectName = objects.find(connection);
if ( connectName != objects.end() )
{
value = connectName->second;
}
else
{
int a=0; // ERROR ?
}
}
}
else
{
throw std::runtime_error("unexpected material nodeX input type " + std::to_string(input_type));
}
if (!value.empty())
{
writer.startElement("param");
writer.writeAttribute("name", rprxParamList[iParam].nameInXML );
writer.writeAttribute("type", type);
writer.writeAttribute("value", value);
writer.endElement();
}
}
writer.endElement();
}
for (const auto& tex : textures)
{
writer.startElement("node");
writer.writeAttribute("name", tex.second.first);
writer.writeAttribute("type", "INPUT_TEXTURE");
writer.startElement("param");
writer.writeAttribute("name", "path");
writer.writeAttribute("type", "file_path");
writer.writeAttribute("value", tex.first);
writer.endElement();
writer.startElement("param");
writer.writeAttribute("name", "gamma");
writer.writeAttribute("type", "float");
bool gammaset = false;
if ( textureParameter.find(tex.second.second) != textureParameter.end() )
{
RPR_MATERIAL_XML_EXPORT_TEXTURE_PARAM& param = textureParameter[tex.second.second];
if ( param.useGamma )
{
writer.writeAttribute("value", std::to_string(2.2f) );
gammaset = true;
}
}
else
{
int a=0;
}
if ( !gammaset )
{
writer.writeAttribute("value", std::to_string(1.0f) );
}
writer.endElement();
writer.endElement();
}
writer.endDocument();
}
catch (const std::exception& ex)
{
cout << "MaterialExport error: " << ex.what() << endl;
}
return;
}
bool ImportMaterials(const std::string& filename, rpr_context context, rpr_material_system sys, rpr_material_node** out_materials, int* out_mat_count)
{
XmlReader read(filename);
if (!read.isOpen())
{
std::cout << "Failed to open file " << filename << std::endl;
return false;
}
std::map<std::string, MaterialNode> nodes;
MaterialNode* last_node = nullptr;
std::vector<rpr_material_node> material_nodes;
std::vector<rpr_image> textures;
std::vector<std::string> tex_files;
try
{
while (!read.isEnd())
{
const XmlReader::Node& node = read.get();
if (!node.is_closing)
{
if (node.name == "node")
{
last_node = &(nodes[read.get().atts.at("name")]);
last_node->type = read.get().atts.at("type");
}
else if (node.name == "param")
{
std::string param_name = read.get().atts.at("name");
std::string param_type = read.get().atts.at("type");
std::string param_value = read.get().atts.at("value");
last_node->params[param_name] = { param_type, param_value };
}
else if (node.name == "description")
{
// at the moment we don't support a description field. easy to add:
// description = read.get().text;
}
else if (node.name == "material")
{
std::stringstream version_stream;
version_stream << std::hex << node.atts.at("version");
int version;
version_stream >> version;
if (version != kVersion)
std::cout << "Warning: Invalid API version. Expected " << hex << kVersion << "." << std::endl;
}
}
read.next();
}
// count material nodes
int count = 0;
for (auto& i : nodes)
if (i.second.type.find("INPUT") == std::string::npos)
++count;
// create nodes
for (auto& i : nodes)
{
MaterialNode& node = i.second;
if (node.type.find("INPUT") == std::string::npos)
{
material_nodes.push_back(CreateMaterial(sys, i.second, i.first));
node.data = material_nodes.back();
}
else if (node.type == "INPUT_TEXTURE")
{
rpr_image texture = nullptr;
const std::string kFilename = node.params.at("path").value;
rpr_int res = rprContextCreateImageFromFile(context, kFilename.c_str(), &texture);
// TODO: Might produce unwanted dialog box?
//^ maybe don't want to give Error messages to the user about unsupported image formats, since we support them through the plugin.
//FCHECK_CONTEXT(res, context, "rprContextCreateImageFromFile");
CHECK_NO_ERROR(res);
textures.push_back(texture);
tex_files.push_back(kFilename);
node.data = texture;
}
}
// setup material parameters
for (auto& i : nodes)
{
MaterialNode& node = i.second;
if (!node.data || node.type == "INPUT_TEXTURE") // we only need material nodes
continue;
for (auto param : node.params)
{
std::string in_input = param.first;
std::string type = param.second.type;
MaterialNode* data_node = &node;
Param* data_param = ¶m.second;
if (type == "connection")
{
data_node = &nodes.at(param.second.value); // connection node
if (data_node->type.find("INPUT") != std::string::npos && data_node->params.size() == 1)
data_param = &(data_node->params.begin()->second);
else if (!data_node->data)
{
cout << "Error: invalid connection.\n";
return false;
}
}
if (data_node->type == "INPUT_TEXTURE")
{
CHECK_NO_ERROR(rprMaterialNodeSetInputImageData(node.data, in_input.c_str(), data_node->data));
}
else if (data_param->type.find("float") != std::string::npos)
{
rpr_float fvalue[4] = { 0.f, 0.f, 0.f, 0.f };
std::string data = data_param->value;
std::replace(data.begin(), data.end(), ',', ' '); // replace comas by spaces to simplify string splitting
std::istringstream iss(data);
std::vector<std::string> tokens{ istream_iterator<std::string>{iss}, std::istream_iterator<string>{} };
int i = 0;
for (const auto& val : tokens)
{
fvalue[i] = std::stof(val);
++i;
}
CHECK_NO_ERROR(rprMaterialNodeSetInputF(node.data, in_input.c_str(), fvalue[0], fvalue[1], fvalue[2], fvalue[3]));
}
else if (data_node->type == "INPUT_UINT")
{
// not handled
rpr_uint uivalue = 0;
CHECK_NO_ERROR(rprMaterialNodeSetInputU(node.data, in_input.c_str(), uivalue));
}
else if (type == "file_path")
{
rpr_image img = nullptr;
rpr_int res = rprContextCreateImageFromFile(context, param.second.value.c_str(), &img);
// TODO: Might produce unwanted dialog box?
//^ maybe don't want to give Error messages to the user about unsupported image formats, since we support them through the plugin.
//FCHECK_CONTEXT(res, context, "rprContextCreateImageFromFile");
CHECK_NO_ERROR(res);
CHECK_NO_ERROR(rprMaterialNodeSetInputImageData(node.data, in_input.c_str(), img));
}
else if (data_node->data)
{
CHECK_NO_ERROR(rprMaterialNodeSetInputN(node.data, in_input.c_str(), data_node->data));
}
else
{
// not handled
cout << "Warning: Unknwon node type: " << data_node->type << endl;
}
}
}
// fill out buffers
if (textures.size() != tex_files.size())
{
cout << "Error: internal error." << endl;
return false;
}
if (out_materials)
{
*out_materials = new rpr_material_node[material_nodes.size()];
memcpy(*out_materials, material_nodes.data(), material_nodes.size() * sizeof(rpr_material_node));
}
if (out_mat_count)
*out_mat_count = int_cast(material_nodes.size());
}
catch (const std::exception& e)
{
cout << "MaterialImport error: " << e.what() << endl;
// Make log to Max Log
string str = e.what();
std::wstring wstr(str.begin(), str.end());
FireRender::LogErrorStringToMaxLog(wstr);
return false;
}
return true;
}
#endif
| 38.055046 | 161 | 0.545484 | Vsevolod1983 |
c5b494796a7a3f93fd5cd88bc784b6ef1ee1b00d | 1,047 | hpp | C++ | include/caffe/util/OpenCL/prelu_layer.hpp | lunochod/caffe | 209fac06cb7893da4fcae0295f5cc882c6569ce9 | [
"BSD-2-Clause"
] | 20 | 2015-06-20T18:08:42.000Z | 2018-05-27T09:28:34.000Z | include/caffe/util/OpenCL/prelu_layer.hpp | rickyHong/CaffeForOpenCL | 209fac06cb7893da4fcae0295f5cc882c6569ce9 | [
"BSD-2-Clause"
] | 3 | 2015-03-30T16:40:42.000Z | 2015-06-03T10:31:51.000Z | include/caffe/util/OpenCL/prelu_layer.hpp | rickyHong/CaffeForOpenCL | 209fac06cb7893da4fcae0295f5cc882c6569ce9 | [
"BSD-2-Clause"
] | 6 | 2015-05-09T02:06:20.000Z | 2015-10-19T07:13:47.000Z | #ifndef __OPENCL_PRELU_LAYER_HPP__
#define __OPENCL_PRELU_LAYER_HPP__
#include <CL/cl.h>
#include <glog/logging.h>
#include <caffe/util/OpenCL/OpenCLDevice.hpp>
#include <caffe/util/OpenCL/OpenCLManager.hpp>
#include <caffe/util/OpenCL/OpenCLPlatform.hpp>
#include <caffe/util/OpenCL/OpenCLSupport.hpp>
#include <iostream> // NOLINT(*)
#include <sstream> // NOLINT(*)
#include <string>
namespace caffe {
namespace OpenCL {
template<typename T> bool clPReLUForward(
const int n,
const int channels,
const int dim,
const T* in,
T* out,
const T* slope_data,
const int div_factor);
template<typename T> bool clPReLUBackward(
const int n,
const int channels,
const int dim,
const T* in_diff,
const T* in_data,
T* out_diff,
const T* slope_data,
const int div_factor);
template<typename T> bool clPReLUParamBackward(
const int n,
const T* in_diff,
const T* in_data,
T* out_diff);
} // namespace OpenCL
} // namespace caffe
#endif // __OPENCL_PRELU_LAYER_HPP__
| 21.367347 | 47 | 0.700096 | lunochod |
c5b805bf68f116642d224142956f83e1f8717ebf | 1,959 | cpp | C++ | lib/src/platform/win/shell.cpp | Voxelum/DeskGap | 9201f1197170385c53f0a2dbb45b6283b518b1c3 | [
"MIT"
] | null | null | null | lib/src/platform/win/shell.cpp | Voxelum/DeskGap | 9201f1197170385c53f0a2dbb45b6283b518b1c3 | [
"MIT"
] | 2 | 2022-03-20T13:09:11.000Z | 2022-03-30T05:07:12.000Z | lib/src/platform/win/shell.cpp | Voxelum/DeskGap | 9201f1197170385c53f0a2dbb45b6283b518b1c3 | [
"MIT"
] | 1 | 2022-03-24T01:33:56.000Z | 2022-03-24T01:33:56.000Z | #include "shell.hpp"
#include "./util/wstring_utf8.h"
#include <Windows.h>
#include <shellapi.h>
#include <shlobj.h>
#include <atlbase.h>
#include <comdef.h>
#include <filesystem>
#include <wrl/client.h>
namespace fs = std::filesystem;
bool DeskGap::Shell::OpenExternal(const std::string &urlString)
{
std::wstring wUrlString = UTF8ToWString(urlString.c_str());
return ShellExecuteW(
nullptr, L"open",
wUrlString.c_str(),
nullptr, nullptr,
SW_SHOWNORMAL) > (HINSTANCE)32;
}
bool DeskGap::Shell::ShowItemInFolder(const std::string &path)
{
// copy from electron ShowItemInFolder
Microsoft::WRL::ComPtr<IShellFolder> desktop;
HRESULT hr = SHGetDesktopFolder(desktop.GetAddressOf());
if (FAILED(hr))
return false;
fs::path full_path(path);
fs::path dir(full_path.parent_path());
ITEMIDLIST *dir_item;
hr = desktop->ParseDisplayName(NULL, NULL,
const_cast<wchar_t *>(dir.c_str()),
NULL, &dir_item, NULL);
if (FAILED(hr))
return false;
ITEMIDLIST *file_item;
hr = desktop->ParseDisplayName(
NULL, NULL, const_cast<wchar_t *>(full_path.c_str()), NULL,
&file_item, NULL);
if (FAILED(hr))
return false;
const ITEMIDLIST *highlight[] = {file_item};
hr = SHOpenFolderAndSelectItems(dir_item, std::size(highlight), highlight, NULL);
if (FAILED(hr))
{
if (hr == ERROR_FILE_NOT_FOUND)
{
// On some systems, the above call mysteriously fails with "file not
// found" even though the file is there. In these cases, ShellExecute()
// seems to work as a fallback (although it won't select the file).
ShellExecute(NULL, L"open", dir.c_str(), NULL, NULL, SW_SHOW);
}
}
CoTaskMemFree(dir_item);
CoTaskMemFree(file_item);
return true;
}
| 28.391304 | 85 | 0.61511 | Voxelum |
c5baa1014ecd4f16fbee2cd167a2760716161dc0 | 2,067 | cpp | C++ | Othuum/VishalaNetworkLib/Protocoll/Server/GameLobby.cpp | Liech/Yathsou | 95b6dda3c053bc25789cce416088e22f54a743b4 | [
"MIT"
] | 5 | 2021-04-20T17:00:41.000Z | 2022-01-18T20:16:03.000Z | Othuum/VishalaNetworkLib/Protocoll/Server/GameLobby.cpp | Liech/Yathsou | 95b6dda3c053bc25789cce416088e22f54a743b4 | [
"MIT"
] | 7 | 2021-08-22T21:30:50.000Z | 2022-01-14T16:56:34.000Z | Othuum/VishalaNetworkLib/Protocoll/Server/GameLobby.cpp | Liech/Yathsou | 95b6dda3c053bc25789cce416088e22f54a743b4 | [
"MIT"
] | null | null | null | #include "GameLobby.h"
#include "LobbyPlayer.h"
#include <iostream>
namespace Vishala {
namespace Server {
GameLobby::GameLobby(std::string name,int gameServerPort, std::string ip, size_t number, std::shared_ptr<LobbyModel> model) {
_name = name ;
_model = model ;
_number = number;
_gameServerPort = gameServerPort;
_gameServerIP = ip;
}
std::string GameLobby::getName() {
return _name;
}
size_t GameLobby::getNumber() {
return _number;
}
void GameLobby::addPlayer(std::shared_ptr<LobbyPlayer> player) {
_participators[player->getID()] = player;
sendUpdate();
}
void GameLobby::removePlayer(size_t playerID) {
auto player = _participators[playerID];
_participators.erase(playerID);
player->leaveGame();
sendUpdate();
}
void GameLobby::closeGame() {
for (auto player : _participators) {
player.second->leaveGame();
}
}
size_t GameLobby::getNumberOfPlayers() {
return _participators.size();
}
void GameLobby::sendUpdate() {
GameLobbyStateUpdate update;
update.currentPlayers.clear();
std::cout << "Send GameLobby update: " << getName()<<std::endl;
for (auto p : _participators){
GameLobbyPlayer player;
player.lobbyIdentification.name = p.second->getName();
player.lobbyIdentification.color = p.second->getColor();
player.lobbyIdentification.id = p.first;
std::cout << " " << player.lobbyIdentification.name << std::endl;
update.currentPlayers.push_back(player);
}
update.gameName = getName();
update.gameStart = _gameStarted;
update.gameServerPort = _gameServerPort;
update.gameServerIP = _gameServerIP;
for (auto p : _participators)
p.second->sendGameLobbyUpdate(update);
}
void GameLobby::startGame() {
std::cout << "GAME START" << std::endl;
_gameStarted = true;
sendUpdate();
}
}
} | 28.315068 | 129 | 0.613933 | Liech |
c5bc64a0b17db35d8fd3a28c53c5500edcd1a503 | 3,712 | cpp | C++ | dev/g++/ifsttar/wifiMapping/wifimapping/src/checkRtc.cpp | YannGarcia/repo | 0f3de24c71d942c752ada03c10861e83853fdf71 | [
"MIT"
] | null | null | null | dev/g++/ifsttar/wifiMapping/wifimapping/src/checkRtc.cpp | YannGarcia/repo | 0f3de24c71d942c752ada03c10861e83853fdf71 | [
"MIT"
] | null | null | null | dev/g++/ifsttar/wifiMapping/wifimapping/src/checkRtc.cpp | YannGarcia/repo | 0f3de24c71d942c752ada03c10861e83853fdf71 | [
"MIT"
] | 1 | 2017-01-27T12:53:50.000Z | 2017-01-27T12:53:50.000Z | /* Beaglebone check RTC result implementation
* Copyright (c) 2013 ygarcia, MIT License
*
* 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 <iomanip>
#include <sstream> // std::ostringstream
#include <cstring> // Used std::strerror, memcpy
#include <unistd.h>
#include "beagleboneCommEx.h"
#include "checkRtc.h"
#include "ipcCommon.h"
namespace wifimapping {
checkRtc::checkRtc() : _status(0x00), _timestamp(0) {
std::clog << ">>> checkRtc::checkRtc" << std::endl;
} // End of Constructor
checkRtc::~checkRtc() {
std::clog << ">>> checkRtc::~checkRtc" << std::endl;
uninitialize();
}
int checkRtc::initialize() {
std::clog << ">>> checkRtc::initialize" << std::endl;
if (_smMgr.open(RTC_SEGMENT_ID) != 0) {
std::cerr << "checkRtc::initialize: Failed to open the shared memory: " << std::strerror(errno) << std::endl;
return -1;
}
_result.clear();
return 0;
}
int checkRtc::uninitialize() {
std::clog << ">>> checkRtc::uninitialize" << std::endl;
return _smMgr.close();
}
void checkRtc::update() {
// std::clog << ">>> checkRtc::update" << std::endl;
_status = 0x00;
_timestamp = time(NULL); // Current time
/**
// Read share memory
_result.clear();
if (_smMgr.read(_result, RTC_DATA_LENGTH) != 0) {
std::cerr << "checkRtc::update: Failed to access the shared memory: " << std::strerror(errno) << std::endl;
return;
}
// Update values
_values.clear();
unsigned int nvalues = _result[0];
if (nvalues != 0) {
unsigned int offset = sizeof(unsigned char);
for (unsigned int i = 0; i < nvalues; i++) {
float value = *((float *)(_result.data() + offset));
_values.push_back(value);
offset += sizeof(float);
} // End of 'for' statement
}
*/
// std::clog << "<<< checkRtc::update: size=" << (int)_values.size() << std::endl;
} // End of method update
void checkRtc::serialize(archive & p_archive) {
// std::clog << ">>> checkRtc::serialize: " << (int)_values.size() << std::endl;
// Serialize shared memory segment identifier
p_archive.serialize(static_cast<unsigned char>(RTC_SEGMENT_ID));
// Serialize the status
p_archive.serialize(_status);
// Serialize the time stamp
p_archive.serialize(_timestamp);
} // End of method serialize
std::string & checkRtc::toString() const {
static std::string str;
std::ostringstream os;
os << "status: " << static_cast<unsigned int>(_status) << " - timestamp: " << _timestamp << std::endl;
str = os.str();
return str;
} // End of method toString
} // End of namespace wifimapping
| 32.561404 | 115 | 0.65625 | YannGarcia |
c5bcd29a0721bf8b18d5dd4d87aa3e9125bd80c8 | 3,749 | cpp | C++ | 6LinkedList/linkedListFunctions/linkedList/linkedList/main.cpp | mingyuefly/geekTimeCode | d97c5f29a429ac9cc7289ac34e049ea43fa58822 | [
"MIT"
] | 1 | 2019-05-01T04:51:14.000Z | 2019-05-01T04:51:14.000Z | 6LinkedList/linkedListFunctions/linkedList/linkedList/main.cpp | mingyuefly/geekTimeCode | d97c5f29a429ac9cc7289ac34e049ea43fa58822 | [
"MIT"
] | null | null | null | 6LinkedList/linkedListFunctions/linkedList/linkedList/main.cpp | mingyuefly/geekTimeCode | d97c5f29a429ac9cc7289ac34e049ea43fa58822 | [
"MIT"
] | null | null | null | //
// main.cpp
// linkedList
//
// Created by Gguomingyue on 2019/3/12.
// Copyright © 2019 Gmingyue. All rights reserved.
//
#include <iostream>
#include "LinkedList.h"
using namespace std;
int main(int argc, const char * argv[]) {
ListNode *head = (ListNode *)malloc(sizeof(ListNode));
head->val = 0;
ListNode *node1 = (ListNode *)malloc(sizeof(ListNode));
node1->val = 2;
head->next = node1;
ListNode *node2 = (ListNode *)malloc(sizeof(ListNode));
node2->val = 5;
node1->next = node2;
ListNode *node3 = (ListNode *)malloc(sizeof(ListNode));
node3->val = 7;
node2->next = node3;
ListNode *node4 = (ListNode *)malloc(sizeof(ListNode));
node4->val = 8;
node3->next = node4;
ListNode *node5 = (ListNode *)malloc(sizeof(ListNode));
node5->val = 13;
//node5->next = node3;
node5->next = NULL;
node4->next = node5;
//ListNode *newHead = reverseList(head);
int hasCircle = hasCycle(head);
cout << hasCircle << endl;
if (!hasCircle) {
ListNode *lHead = head;
//ListNode *lHead = newHead;
while (lHead) {
cout << lHead->val << " ";
lHead = lHead->next;
}
cout << endl;
} else {
ListNode * prtNode = findLoopStart(head);
cout << prtNode->val << endl;
}
ListNode *headt = (ListNode *)malloc(sizeof(ListNode));
headt->val = 1;
ListNode *nodet1 = (ListNode *)malloc(sizeof(ListNode));
nodet1->val = 4;
headt->next = nodet1;
ListNode *nodet2 = (ListNode *)malloc(sizeof(ListNode));
nodet2->val = 5;
nodet1->next = nodet2;
ListNode *nodet3 = (ListNode *)malloc(sizeof(ListNode));
nodet3->val = 9;
nodet2->next = nodet3;
ListNode *nodet4 = (ListNode *)malloc(sizeof(ListNode));
nodet4->val = 17;
nodet3->next = nodet4;
ListNode *nodet5 = (ListNode *)malloc(sizeof(ListNode));
nodet5->val = 21;
//node5->next = node3;
nodet5->next = NULL;
nodet4->next = nodet5;
int hasCirclet = hasCycle(headt);
cout << hasCirclet << endl;
if (!hasCirclet) {
ListNode *lHead = headt;
//ListNode *lHead = newHead;
while (lHead) {
cout << lHead->val << " ";
lHead = lHead->next;
}
cout << endl;
} else {
ListNode * prtNode = findLoopStart(headt);
cout << prtNode->val << endl;
}
ListNode *headMerge = mergeTwoLists(head, headt);
int hasCircleMerge = hasCycle(headMerge);
cout << hasCircleMerge << endl;
if (!hasCircleMerge) {
ListNode *lHead = headMerge;
//ListNode *lHead = newHead;
while (lHead) {
cout << lHead->val << " ";
lHead = lHead->next;
}
cout << endl;
} else {
ListNode * prtNode = findLoopStart(headMerge);
cout << prtNode->val << endl;
}
ListNode * middleheadMerge = middleNode(headMerge);
cout << middleheadMerge->val << endl;
ListNode *headAfterRemove = removeNthFromEnd(headMerge, 5);
int hasCircleAfterRemove = hasCycle(headAfterRemove);
cout << hasCircleAfterRemove << endl;
if (!hasCircleAfterRemove) {
ListNode *lHead = headAfterRemove;
//ListNode *lHead = newHead;
while (lHead) {
cout << lHead->val << " ";
lHead = lHead->next;
}
cout << endl;
} else {
ListNode * prtNode = findLoopStart(headAfterRemove);
cout << prtNode->val << endl;
}
ListNode * middleheadAfterRemove = middleNode(headAfterRemove);
cout << middleheadAfterRemove->val << endl;
return 0;
}
| 26.778571 | 67 | 0.561216 | mingyuefly |
c5c14cc59e7efddc4ae133c81c329968966b7f35 | 389 | hpp | C++ | cef_client/include/FunctionBinding.hpp | jarrettchisholm/glr | 79a57b12e26fe84595e833cace3528cb9c82bc20 | [
"WTFPL"
] | 11 | 2015-08-19T23:15:41.000Z | 2018-05-15T21:53:28.000Z | cef_client/include/FunctionBinding.hpp | jarrettchisholm/glr | 79a57b12e26fe84595e833cace3528cb9c82bc20 | [
"WTFPL"
] | 2 | 2015-05-21T06:37:24.000Z | 2015-05-23T05:37:16.000Z | cef_client/include/FunctionBinding.hpp | jarrettchisholm/glr | 79a57b12e26fe84595e833cace3528cb9c82bc20 | [
"WTFPL"
] | 5 | 2016-10-31T08:02:15.000Z | 2018-08-24T07:40:23.000Z | #ifndef FUNCTIONBINDING_H_
#define FUNCTIONBINDING_H_
#include <string>
#include "Macros.hpp"
namespace glr
{
namespace cef_client
{
class FunctionBinding
{
public:
FunctionBinding(std::wstring name);
virtual ~FunctionBinding();
// TODO: Get rid of macro setter and getter
GETSET(std::wstring, name_, Name)
private:
std::wstring name_;
};
}
}
#endif /* FUNCTIONBINDING_H_ */
| 12.966667 | 44 | 0.737789 | jarrettchisholm |
c5c6246b804cd4f3cf602bf3a99304183cd3ecab | 11,192 | cc | C++ | src/ui/a11y/lib/gesture_manager/recognizers/m_finger_n_tap_drag_recognizer.cc | billchen1977/fuchsia | d443f9c7b03ad317d1700c2c9457be8ed1147b86 | [
"BSD-2-Clause"
] | null | null | null | src/ui/a11y/lib/gesture_manager/recognizers/m_finger_n_tap_drag_recognizer.cc | billchen1977/fuchsia | d443f9c7b03ad317d1700c2c9457be8ed1147b86 | [
"BSD-2-Clause"
] | null | null | null | src/ui/a11y/lib/gesture_manager/recognizers/m_finger_n_tap_drag_recognizer.cc | billchen1977/fuchsia | d443f9c7b03ad317d1700c2c9457be8ed1147b86 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/ui/a11y/lib/gesture_manager/recognizers/m_finger_n_tap_drag_recognizer.h"
#include <lib/async/cpp/task.h>
#include <lib/async/default.h>
#include <lib/syslog/cpp/macros.h>
#include <set>
#include "src/lib/fxl/strings/string_printf.h"
#include "src/ui/a11y/lib/gesture_manager/gesture_util/util.h"
namespace a11y {
struct MFingerNTapDragRecognizer::Contest {
Contest(std::unique_ptr<ContestMember> contest_member)
: member(std::move(contest_member)), reject_task(member.get()), accept_task(member.get()) {}
std::unique_ptr<ContestMember> member;
// Indicates whether m fingers have been on the screen at the same time
// during the current tap.
bool tap_in_progress = false;
// Keeps the count of the number of taps detected so far, for the gesture.
uint32_t number_of_taps_detected = 0;
// Indicaes whether the recognizer has successfully accepted the gesture.
bool won = false;
// Async task used to schedule long-press timeout.
async::TaskClosureMethod<ContestMember, &ContestMember::Reject> reject_task;
// Async task to schedule delayed win for held tap.
async::TaskClosureMethod<ContestMember, &ContestMember::Accept> accept_task;
};
MFingerNTapDragRecognizer::MFingerNTapDragRecognizer(OnMFingerNTapDragCallback on_recognize,
OnMFingerNTapDragCallback on_update,
OnMFingerNTapDragCallback on_complete,
uint32_t number_of_fingers,
uint32_t number_of_taps)
: number_of_fingers_in_gesture_(number_of_fingers),
number_of_taps_in_gesture_(number_of_taps),
on_recognize_(std::move(on_recognize)),
on_update_(std::move(on_update)),
on_complete_(std::move(on_complete)) {}
MFingerNTapDragRecognizer::~MFingerNTapDragRecognizer() = default;
void MFingerNTapDragRecognizer::OnTapStarted() {
// If this tap is the last in the gesture, post a task to accept the gesture
// if the fingers are still on screen after kMinTapHoldDuration has elapsed.
// Otherwise, if this tap is NOT the last in the gesture, post a task to
// reject the gesture if the fingers have not lifted by the time kTapTimeout
// elapses.
if (contest_->number_of_taps_detected == number_of_taps_in_gesture_ - 1) {
contest_->accept_task.PostDelayed(async_get_default_dispatcher(), kMinTapHoldDuration);
} else {
contest_->reject_task.PostDelayed(async_get_default_dispatcher(), kTapTimeout);
}
}
void MFingerNTapDragRecognizer::OnExcessFingers() {
// If the gesture has already been accepted (i.e. the user has successfully
// performed n-1 taps, followed by a valid hold, but an (m+1)th finger comes
// down on screen, we should invoke the on_complete_ callback.
// In any event, the gesture is no longer valid, so we should reset the
// recognizer.
if (contest_->won) {
on_complete_(gesture_context_);
}
ResetRecognizer();
}
void MFingerNTapDragRecognizer::OnMoveEvent(
const fuchsia::ui::input::accessibility::PointerEvent& pointer_event) {
// If we've accepted the gesture, invoke on_update_. Otherwise, if the current
// tap is the last (which could become a drag), we should check if the
// fingers have already moved far enough to constitute a drag.
// If this tap is not the last, we should verify that the
// fingers are close enough to their starting locations to constitute a valid
// tap.
if (contest_->won) {
on_update_(gesture_context_);
} else if (contest_->number_of_taps_detected == number_of_taps_in_gesture_ - 1) {
if (DisplacementExceedsDragThreshold()) {
contest_->member->Accept();
return;
}
} else if (!PointerEventIsValidTap(gesture_context_, pointer_event)) {
ResetRecognizer();
}
}
void MFingerNTapDragRecognizer::OnUpEvent() {
// If we've already accepted the gesture, then we should invoke on_complete_
// and reset the recognizer once the first UP event is received (at which
// point, the drag is considered complete).
if (contest_->won) {
on_complete_(gesture_context_);
ResetRecognizer();
return;
}
// If we have counted number_of_taps_in_gesture_ - 1 complete taps, then this
// UP event must mark the end of the drag. If we have not already accepted the
// gesture at this point, we should reject.
if (contest_->number_of_taps_detected == number_of_taps_in_gesture_ - 1) {
ResetRecognizer();
return;
}
// If this UP event removed the last finger from the screen, then the most
// recent tap is complete.
if (!NumberOfFingersOnScreen(gesture_context_)) {
// If we've made it this far, we know that (1) m fingers were on screen
// simultaneously during the current single tap, and (2) The m fingers have
// now been removed, without any interceding finger DOWN events.
// Therefore, we can conclude that a complete m-finger tap has occurred.
contest_->number_of_taps_detected++;
// Mark that all m fingers were removed from the screen.
contest_->tap_in_progress = false;
// Cancel task which was scheduled for detecting single tap.
contest_->reject_task.Cancel();
// Schedule task with delay of timeout_between_taps_.
contest_->reject_task.PostDelayed(async_get_default_dispatcher(), kTimeoutBetweenTaps);
}
}
void MFingerNTapDragRecognizer::HandleEvent(
const fuchsia::ui::input::accessibility::PointerEvent& pointer_event) {
FX_DCHECK(contest_);
FX_DCHECK(pointer_event.has_pointer_id())
<< DebugName() << ": Pointer event is missing pointer id.";
const auto pointer_id = pointer_event.pointer_id();
FX_DCHECK(pointer_event.has_phase())
<< DebugName() << ": Pointer event is missing phase information.";
switch (pointer_event.phase()) {
case fuchsia::ui::input::PointerEventPhase::DOWN:
// If we receive a DOWN event when there are already m fingers on the
// screen, then either we've received a second DOWN event for one of the fingers that's
// already on the screen, or we've received a DOWN event for an (m+1)th
// finger. In either case, we should abandon the current gesture.
if (NumberOfFingersOnScreen(gesture_context_) >= number_of_fingers_in_gesture_) {
OnExcessFingers();
break;
}
// If we receive a DOWN event when there is a tap in progress, then we
// should abandon the gesture.
// NOTE: this is a distinct check from the one above, and is required to
// ensure that the number of fingers touching the screen decreases
// monotonically once the first finger is removed.
// For example,
// consider the case of finger 1 DOWN, finger 2 DOWN, finger 2 UP, finger
// 2 DOWN. Clearly, this is not a two-finger tap, but at the time of the
// second "finger 2 DOWN" event, contest->fingers_on_screen.size() would
// be 1, so the check above would pass.
if (contest_->tap_in_progress) {
ResetRecognizer();
break;
}
// If we receive successive DOWN events for the same pointer without an
// UP event, then we should abandon the current gesture.
if (FingerIsOnScreen(gesture_context_, pointer_id)) {
ResetRecognizer();
break;
}
// Initialize starting info for this new tap.
if (!InitializeStartingGestureContext(pointer_event, &gesture_context_)) {
ResetRecognizer();
break;
}
// If the total number of fingers involved in the gesture now exceeds
// number_of_fingers_in_gesture_, reject the gesture.
if (gesture_context_.starting_pointer_locations.size() > number_of_fingers_in_gesture_) {
ResetRecognizer();
break;
}
// Cancel task which would be scheduled for timeout between taps.
contest_->reject_task.Cancel();
contest_->tap_in_progress =
(NumberOfFingersOnScreen(gesture_context_) == number_of_fingers_in_gesture_);
// Only start the timeout once all m fingers are on the screen together.
if (contest_->tap_in_progress) {
OnTapStarted();
}
break;
case fuchsia::ui::input::PointerEventPhase::MOVE:
FX_DCHECK(FingerIsOnScreen(gesture_context_, pointer_id))
<< DebugName() << ": Pointer MOVE event received without preceding DOWN event.";
// Validate the pointer_event for the gesture being performed.
if (!ValidatePointerEvent(gesture_context_, pointer_event)) {
ResetRecognizer();
break;
}
UpdateGestureContext(pointer_event, true /* finger is on screen */, &gesture_context_);
OnMoveEvent(pointer_event);
break;
case fuchsia::ui::input::PointerEventPhase::UP:
FX_DCHECK(FingerIsOnScreen(gesture_context_, pointer_id))
<< DebugName() << ": Pointer UP event received without preceding DOWN event.";
// Validate pointer_event for the gesture being performed.
if (!ValidatePointerEvent(gesture_context_, pointer_event)) {
ResetRecognizer();
break;
}
UpdateGestureContext(pointer_event, false /* finger is not on screen */, &gesture_context_);
// The number of fingers on screen during a multi-finger tap should
// monotonically increase from 0 to m, and
// then monotonically decrease back to 0. If a finger is removed before
// number_of_fingers_in_gesture_ fingers are on the screen simultaneously,
// then we should reject this gesture.
if (!contest_->tap_in_progress) {
ResetRecognizer();
break;
}
OnUpEvent();
break;
default:
break;
}
}
bool MFingerNTapDragRecognizer::DisplacementExceedsDragThreshold() {
return SquareDistanceBetweenPoints(
gesture_context_.StartingCentroid(false /*use_local_coordinates*/),
gesture_context_.CurrentCentroid(false /*use_local_coordinates*/)) >=
kDragDisplacementThreshold * kDragDisplacementThreshold;
}
void MFingerNTapDragRecognizer::ResetRecognizer() {
contest_.reset();
ResetGestureContext(&gesture_context_);
}
void MFingerNTapDragRecognizer::OnWin() {
on_recognize_(gesture_context_);
if (contest_) {
contest_->won = true;
} else {
// It's possible that we don't get awarded the win until after the gesture has
// completed, in which case we also need to call the complete handler.
on_complete_(gesture_context_);
ResetRecognizer();
}
}
void MFingerNTapDragRecognizer::OnDefeat() { ResetRecognizer(); }
void MFingerNTapDragRecognizer::OnContestStarted(std::unique_ptr<ContestMember> contest_member) {
ResetRecognizer();
contest_ = std::make_unique<Contest>(std::move(contest_member));
}
std::string MFingerNTapDragRecognizer::DebugName() const {
return fxl::StringPrintf("MFingerNTapDragRecognizer(m=%d, n=%d)", number_of_fingers_in_gesture_,
number_of_taps_in_gesture_);
}
} // namespace a11y
| 39.687943 | 98 | 0.703181 | billchen1977 |
c5c796a5b36eb9ce01c779f301c5b4d4c6192dc1 | 9,705 | cpp | C++ | Mocap/src/publisher.cpp | robinzhoucmu/MLab_EXP | 4d86db9438203f51c4368e5b886def5c402955f3 | [
"Apache-2.0"
] | 2 | 2016-06-16T00:46:02.000Z | 2018-12-02T16:17:59.000Z | Mocap/src/publisher.cpp | robinzhoucmu/MLab_EXP | 4d86db9438203f51c4368e5b886def5c402955f3 | [
"Apache-2.0"
] | null | null | null | Mocap/src/publisher.cpp | robinzhoucmu/MLab_EXP | 4d86db9438203f51c4368e5b886def5c402955f3 | [
"Apache-2.0"
] | null | null | null | #include "publisher.h"
MocapPublisher::MocapPublisher(ros::NodeHandle *n) {
nodeHandle = n;
// Set as default frequency.
SetPublishFrequency(Globals::kPublishFreq);
// Without given transformation: set transformation (from robot base to mocap frame)
// as identity. Therefore mocap just return in its (unknown/uncalibrated) native
// coordinate frame.
double pose[7] = {0,0,0,1,0,0,0};
setMocapTransformation(pose);
}
MocapPublisher::~MocapPublisher() {
handle_mocap_GetMocapFrame.shutdown();
handle_mocap_SetMocapTransformation.shutdown();
}
void MocapPublisher::SetPublishFrequency(int _pub_freq_hz) {
pub_freq_hz = _pub_freq_hz;
}
void MocapPublisher::EstablishCommunications(int argc, char* argv[]) {
// Sockets Initialization.
sdCommand = -1;
sdData = -1;
// Catch ctrl-c and terminate gracefully.
signal(SIGINT, Globals::Terminate);
// Set addresses
Globals::ReadOpts(argc, argv);
// Create sockets
sdCommand = NatNet::createCommandSocket( Globals::localAddress );
sdData = NatNet::createDataSocket( Globals::localAddress );
// Ensure that the socket creation was successful
assert(sdCommand != -1);
assert(sdData != -1);
// Create Listeners with the sockets.
CreateListener();
}
void MocapPublisher::CreateListener() {
// Version number of the NatNet protocol, as reported by the server.
unsigned char natNetMajor;
unsigned char natNetMinor;
// Use this socket address to send commands to the server.
// Default NatNet command port is 1510.
struct sockaddr_in serverCommands =
NatNet::createAddress(Globals::serverAddress, NatNet::commandPort);
printf("About to start command listener\n");
// Start the CommandListener in a new thread.
commandListener = new CommandListener(sdCommand);
commandListener->start();
printf("cmd listener started. about to ping\n");
// Send a ping packet to the server so that it sends us the NatNet version
// in its response to commandListener.
NatNetPacket ping = NatNetPacket::pingPacket();
ping.send(sdCommand, serverCommands);
printf("ping sent. waiting...\n");
// Wait here for ping response to give us the NatNet version.
commandListener->getNatNetVersion(&natNetMajor, &natNetMinor);
printf("ping recieved. Major = %u, Minor = %u \n",natNetMajor,natNetMinor);
// Start up a FrameListener in a new thread.
frameListener = new FrameListener(sdData, natNetMajor, natNetMinor);
frameListener->start();
}
void MocapPublisher::ExtractPoseMsg(const MocapFrame& mframe,
Mocap::mocap_frame* msg) {
// See NatNet.h file for relevant data structures of MocapFrame.
// Extract unidenfied markers (e.g., single calibration marker).
const int num_uid_markers = mframe.unIdMarkers().size();
msg->uid_markers.markers.clear();
for (int i = 0; i < num_uid_markers; ++i) {
const Point3f& pt = mframe.unIdMarkers()[i];
geometry_msgs::Point uid_marker_pt;
uid_marker_pt.x = k_unit * pt.x;
uid_marker_pt.y = k_unit * pt.y;
uid_marker_pt.z = k_unit * pt.z;
// Transform the point.
transformPoint(&uid_marker_pt);
msg->uid_markers.markers.push_back(uid_marker_pt);
}
// Extract tracked body/ies poses and corresponding identified marker sets.
const int num_bodies = mframe.rigidBodies().size();
msg->id_marker_sets.clear();
msg->body_poses.clear();
for (int i = 0; i < num_bodies; i++) {
const RigidBody& body = mframe.rigidBodies()[i];
geometry_msgs::Pose pose;
// Copy x,y,z.
pose.position.x = k_unit * body.location().x;
pose.position.y = k_unit * body.location().y;
pose.position.z = k_unit * body.location().z;
// Copy Quaternion.
pose.orientation.x = body.orientation().qx;
pose.orientation.y = body.orientation().qy;
pose.orientation.z = body.orientation().qz;
pose.orientation.w = body.orientation().qw;
// Transform the pose.
transformPose(&pose);
msg->body_poses.push_back(pose);
msg->header.stamp = ros::Time::now();
const int marker_set_size = body.markers().size();
Mocap::marker_set id_marker_set;
for (int j = 0; j < marker_set_size; ++j) {
const Point3f& pt = body.markers()[j];
geometry_msgs::Point id_marker_pt;
id_marker_pt.x = k_unit * pt.x;
id_marker_pt.y = k_unit * pt.y;
id_marker_pt.z = k_unit * pt.z;
// Transform the point.
transformPoint(&id_marker_pt);
id_marker_set.markers.push_back(id_marker_pt);
}
msg->id_marker_sets.push_back(id_marker_set);
}
}
void MocapPublisher::PublishToTopic() {
// Set the publiser queue size.
const int kQueueSize = 100;
// Set the publishing frequency.
ros::Rate loop_rate(pub_freq_hz);
ros::Publisher mocapPub = nodeHandle->advertise<Mocap::mocap_frame>("Mocap", kQueueSize);
unsigned int rosMsgCount = 0;
Globals::run = true;
while( ros::ok() && Globals::run) {
// Try to get a new frame from the listener.
bool valid;
MocapFrame frame(frameListener->pop(&valid).first);
// Quit if the listener has no more frames.
if(!valid) {
// fprintf(stderr,"No valid frame available \n");
}
else {
// std::cout << frame << std::endl;
// Extract rigid bodies and publish to ROS.
Mocap::mocap_frame msg;
ExtractPoseMsg(frame, &msg);
//std::cout << ros::Time::now() << std::endl;
mocapPub.publish(msg);
}
// All callbacks/services will be processed here.
ros::spinOnce();
loop_rate.sleep();
rosMsgCount++;
}
printf("after ROS loop: ros::ok = %i, Globals::run = %i \n",ros::ok(),Globals::run);
// Wait for threads to finish.
frameListener->stop();
commandListener->stop();
frameListener->join();
commandListener->join();
// Epilogue (Close sockets)
close(sdData);
close(sdCommand);
// Close topic.
mocapPub.shutdown();
}
void MocapPublisher::AdvertiseServices() {
handle_mocap_GetMocapFrame =
nodeHandle->advertiseService("mocap_GetMocapFrame",
&MocapPublisher::GetMocapFrame, this);
handle_mocap_GetMocapTransformation =
nodeHandle->advertiseService("mocap_GetMocapTransformation",
&MocapPublisher::GetMocapTransformation, this);
handle_mocap_SetMocapTransformation =
nodeHandle->advertiseService("mocap_SetMocapTransformation",
&MocapPublisher::SetMocapTransformation, this);
}
bool MocapPublisher::GetMocapFrame(Mocap::mocap_GetMocapFrame::Request& req,
Mocap::mocap_GetMocapFrame::Response& res) {
double start_secs = ros::Time::now().toSec();
bool flag_tle = false;
bool flag_captured_frame = false;
while (!flag_tle && !flag_captured_frame) {
double cur_secs = ros::Time::now().toSec();
if (cur_secs - start_secs > k_max_wait) {
flag_tle = true;
}
// Try to get a new frame from the listener.
bool valid;
MocapFrame frame(frameListener->pop(&valid).first);
// Quit if the listener has no more frames.
if(!valid) {
fprintf(stderr,"No valid frame available \n");
}
else {
// Extract rigid bodies and publish to ROS.
Mocap::mocap_frame msg;
ExtractPoseMsg(frame, &msg);
res.mf = msg;
flag_captured_frame = true;
}
}
if (flag_captured_frame) {
res.msg = "OK.";
res.ret = 1;
return true;
} else {
res.msg = "Time limit exceeded.";
res.ret = 1;
return false;
}
}
bool MocapPublisher::GetMocapTransformation(Mocap::mocap_GetMocapTransformation::Request& req,
Mocap::mocap_GetMocapTransformation::Response& res) {
Vec tf_trans = tf_mocap.getTranslation();
res.x = tf_trans[0];
res.y = tf_trans[1];
res.z = tf_trans[2];
Quaternion tf_quat = tf_mocap.getQuaternion();
res.q0 = tf_quat[0];
res.qx = tf_quat[1];
res.qy = tf_quat[2];
res.qz = tf_quat[3];
res.msg = "Ok.";
res.ret = 1;
return true;
}
// TODO: the return false logic.
bool MocapPublisher::SetMocapTransformation(Mocap::mocap_SetMocapTransformation::Request& req,
Mocap::mocap_SetMocapTransformation::Response& res) {
double pose[7];
pose[0] = req.x;
pose[1] = req.y;
pose[2] = req.z;
pose[3] = req.q0;
pose[4] = req.qx;
pose[5] = req.qy;
pose[6] = req.qz;
setMocapTransformation(pose);
res.msg = "OK.";
res.ret = 1;
return true;
}
void MocapPublisher::setMocapTransformation(double pose[7]) {
tf_mocap = HomogTransf(pose);
}
void MocapPublisher::transformPoint(geometry_msgs::Point* pt) {
double p[3];
p[0] = pt->x;
p[1] = pt->y;
p[2] = pt->z;
Vec vec_p(p, 3);
vec_p = tf_mocap * vec_p;
pt->x = vec_p[0];
pt->y = vec_p[1];
pt->z = vec_p[2];
}
void MocapPublisher::transformPose(geometry_msgs::Pose* pose) {
geometry_msgs::Point& trans = pose->position;
geometry_msgs::Quaternion& quat = pose->orientation;
// Todo(Jiaji): Note q.w comes first here, in matVec q.w is the 4th element.
double tmp_pose[7] = {trans.x, trans.y, trans.z,
quat.w, quat.x, quat.y, quat.z};
HomogTransf cur_tf = HomogTransf(tmp_pose);
HomogTransf tf = tf_mocap * cur_tf;
Vec tf_trans = tf.getTranslation();
trans.x = tf_trans[0];
trans.y = tf_trans[1];
trans.z = tf_trans[2];
Quaternion tf_quat = tf.getQuaternion();
quat.x = tf_quat.x();
quat.y = tf_quat.y();
quat.z = tf_quat.z();
quat.w = tf_quat.w();
}
// Main function for the Mocap Node.
// The Mocap node is publishing Mocap frames to the Mocap Topic.
int main(int argc, char* argv[]) {
// Initialize the ROS node.
ros::init(argc, argv, "Mocap");
ros::NodeHandle node;
MocapPublisher mocap_pub(&node);
mocap_pub.EstablishCommunications(argc, argv);
mocap_pub.AdvertiseServices();
mocap_pub.PublishToTopic();
}
| 30.615142 | 95 | 0.678001 | robinzhoucmu |
c5c990ae5523ab1cf6ccf7db48a26f74d3f5afb6 | 1,222 | hpp | C++ | include/hazeRemove.hpp | norishigefukushima/OpenCP | 63090131ec975e834f85b04e84ec29b2893845b2 | [
"BSD-3-Clause"
] | 137 | 2015-03-27T07:11:19.000Z | 2022-03-30T05:58:22.000Z | include/hazeRemove.hpp | Pandinosaurus/OpenCP | a5234ed531c610d7944fa14d42f7320442ea34a1 | [
"BSD-3-Clause"
] | 2 | 2016-05-18T06:33:16.000Z | 2016-07-11T17:39:17.000Z | include/hazeRemove.hpp | Pandinosaurus/OpenCP | a5234ed531c610d7944fa14d42f7320442ea34a1 | [
"BSD-3-Clause"
] | 43 | 2015-02-20T15:34:25.000Z | 2022-01-27T14:59:37.000Z | #pragma once
#include "common.hpp"
namespace cp
{
class CP_EXPORT HazeRemove
{
cv::Size size;
cv::Mat dark;
std::vector<cv::Mat> minvalue;
cv::Mat tmap;
cv::Scalar A;
void darkChannel(cv::Mat& src, int r);
void getAtmosphericLight(cv::Mat& srcImage, double topPercent = 0.1);
void getTransmissionMap(float omega = 0.95f);
void removeHaze(cv::Mat& src, cv::Mat& trans, cv::Scalar v, cv::Mat& dest, float clip = 0.3f);
public:
HazeRemove();
~HazeRemove();
void getAtmosphericLightImage(cv::Mat& dest);
void showTransmissionMap(cv::Mat& dest, bool isPseudoColor = false);
void showDarkChannel(cv::Mat& dest, bool isPseudoColor = false);
void removeFastGlobalSmootherFilter(cv::Mat& src, cv::Mat& dest, const int r_dark, const double top_rate, const double lambda, const double sigma_color, const double lambda_attenuation, const int iteration);
void removeGuidedFilter(cv::Mat& src, cv::Mat& dest, const int r_dark, const double toprate, const int r_joint, const double e_joint);
void operator() (cv::Mat& src, cv::Mat& dest, const int r_dark, const double toprate, const int r_joint, const double e_joint);
void gui(cv::Mat& src, std::string wname = "hazeRemove");
};
} | 34.914286 | 209 | 0.713584 | norishigefukushima |
c5cbb17a63e2cba61b08f9e02c106799e95a767d | 1,276 | cpp | C++ | tests/parse/iterator_test.cpp | BastianBlokland/novus | 3b984c36855aa84d6746c14ff7e294ab7d9c1575 | [
"MIT"
] | 14 | 2020-04-14T17:00:56.000Z | 2021-08-30T08:29:26.000Z | tests/parse/iterator_test.cpp | BastianBlokland/novus | 3b984c36855aa84d6746c14ff7e294ab7d9c1575 | [
"MIT"
] | 27 | 2020-12-27T16:00:44.000Z | 2021-08-01T13:12:14.000Z | tests/parse/iterator_test.cpp | BastianBlokland/novus | 3b984c36855aa84d6746c14ff7e294ab7d9c1575 | [
"MIT"
] | 1 | 2020-05-29T18:33:37.000Z | 2020-05-29T18:33:37.000Z | #include "catch2/catch.hpp"
#include "lex/lexer.hpp"
#include "parse/parser.hpp"
#include <string>
namespace parse {
TEST_CASE("[parse] Iterating the parser", "parse") {
const std::string input = "print(1) print(x * y)";
SECTION("Range for") {
auto lexer = lex::Lexer{input.begin(), input.end()};
auto parser = parse::Parser{lexer.begin(), lexer.end()};
std::vector<NodePtr> nodes;
for (auto&& node : parser) {
nodes.push_back(std::move(node));
}
REQUIRE(nodes.size() == 2);
}
SECTION("While loop") {
auto lexer = lex::Lexer{input.begin(), input.end()};
auto parser = parse::Parser{lexer.begin(), lexer.end()};
auto i = 0;
while (parser.next() != nullptr) {
++i;
}
REQUIRE(i == 2);
}
SECTION("Iterator") {
auto lexer = lex::Lexer{input.begin(), input.end()};
auto parser = parse::Parser{lexer.begin(), lexer.end()};
auto i = 0;
auto nodeItr = parser.begin();
auto endItr = parser.end();
for (; nodeItr != endItr; ++nodeItr) {
i++;
}
REQUIRE(i == 2);
}
SECTION("ParseAll") {
auto lexer = lex::Lexer{input.begin(), input.end()};
auto vec = parseAll(lexer.begin(), lexer.end());
REQUIRE(vec.size() == 2);
}
}
} // namespace parse
| 23.2 | 60 | 0.575235 | BastianBlokland |
c5cbc32e477982145511d6a3cf13caf960799809 | 8,066 | cpp | C++ | AROGSBP/ARGOS_BP_SW/VSCODE/CameraDSLR/photo.cpp | EIDOSDATA/Argos_Main_Series | 2d6e4839afa7bd05d3b87fb530481bdf5eeac31a | [
"Unlicense"
] | null | null | null | AROGSBP/ARGOS_BP_SW/VSCODE/CameraDSLR/photo.cpp | EIDOSDATA/Argos_Main_Series | 2d6e4839afa7bd05d3b87fb530481bdf5eeac31a | [
"Unlicense"
] | null | null | null | AROGSBP/ARGOS_BP_SW/VSCODE/CameraDSLR/photo.cpp | EIDOSDATA/Argos_Main_Series | 2d6e4839afa7bd05d3b87fb530481bdf5eeac31a | [
"Unlicense"
] | null | null | null | #include "photo.h"
#include <iostream>
#include <unistd.h>
static const char* config_texts[CONFIG_TYPE]=
{
"f-number",
"shutterspeed2",
"iso",
};
int photo::threeShootWait(CameraFilePath *path, int port_num, Camera *camera, GPContext *context)
{
CameraEventType eventtype;
struct timeval start, temp;
void *eventdata = NULL;
int startflag = 0;
//NEED: wait other camera starting..
gettimeofday(&start, nullptr);
do
{
int result = gp_camera_wait_for_event(camera, 200, &eventtype, &eventdata, context);
if (result < 0)
{
perror("wait_for_event error in two shoot");
return 1;
}
switch (eventtype)
{
case GP_EVENT_TIMEOUT:
case GP_EVENT_CAPTURE_COMPLETE:
case GP_EVENT_UNKNOWN:
case GP_EVENT_FOLDER_ADDED:
break;
case GP_EVENT_FILE_ADDED:
strcpy(path->folder, ((CameraFilePath *)eventdata)->folder);
strcpy(path->name, ((CameraFilePath *)eventdata)->name);
startflag = 1;
break;
}
if(eventdata != nullptr)
{
free(eventdata);
eventdata = nullptr;
}
gettimeofday(&temp, nullptr);
} while (temp.tv_sec - start.tv_sec < 9);
if(startflag == 0)
{
std::cout << "Can't receive file added event.(cam: " << port_num << ")" << std::endl;
return 1;
}
return 0;
}
int photo::cameraClose(Camera *camera, GPContext *context)
{
if (gp_camera_exit(camera, context))
{
perror("camera exit error.\n");
return 1;
}
if (gp_camera_unref(camera))
{
perror("camera free error.\n");
return 1;
}
gp_context_unref(context);
return 0;
}
int photo::downloadFileFromCamera(CameraFile *file, const CameraFilePath *path, CameraFileType type, Camera *camera, GPContext *context)
{
int result = gp_file_clean(file); // clean file
if(result)
{
std::cout << "download_file_from_camera(file clean): " << gp_result_as_string(result) << std::endl;
return 1;
}
result = gp_camera_file_get(camera, path->folder, path->name, type, file, context); // get file
if(result)
{
const char* data;
unsigned long int size;
result = gp_file_get_data_and_size(file, &data, &size); // 사진 받기에 에러가 떳지만, 사진 내용이 있으면 저장하고 계속(??)
std::cout << "result: ," << result << " data size: " << size << std::endl; // 왠지 모르게 에러가 나지만 사진이 괜찮은 경우가 많았음(??)
if(size > 0)
{
std::cout << "file_get error but file is valid. downloading continue.." << std::endl;
return 0;
}
std::cout << "download_file_from_camera(file get): " << gp_result_as_string(result) << std::endl;
return 1;
}
return 0;
}
int photo::presetConfig(const char *name, const void *value, Config_Kind kind, CameraWidget *window, Camera *camera, GPContext *context)
{
CameraWidget* widget;
int result = gp_widget_get_child_by_name(window, name, &widget);
if (result)
{
std::cout << "wiget_get_child_by_name error. " << gp_result_as_string(result) << std::endl;
return 1;
}
if( kind == CONFIG_BY_TEXT)
{
result = gp_widget_set_value(widget, (char*)value);
if (result)
{
std::cout << "gp_widget_set_value error. " << gp_result_as_string(result) << std::endl;
return 1;
}
result = gp_camera_set_config(camera,window,context); //set config
if(result)
{
std::cout << name << "-"<< (char*)value << " config presetting error. " << gp_result_as_string(result) << std::endl;
return 1;
}
}
else if(kind == CONFIG_BY_INTEGER)
{
const char* choice;
// printf("Integer: %d\n", *(int*)value);
result = gp_widget_get_choice(widget, *(int*)value, &choice);
if(result){
std::cout << "gp_widget_get_choice error. " << gp_result_as_string(result) << std::endl;
return 1;
}
result = gp_widget_set_value(widget, (char*)choice);
if (result)
{
std::cout << "gp_widget_set_value error. " << gp_result_as_string(result) << std::endl;
return 1;
}
result = gp_camera_set_config(camera,window,context); //set config.
if(result)
{
std::cout << name << "-"<< choice << " config presetting error. " << gp_result_as_string(result) << std::endl;
return 1;
}
}
// gp_widget_unref(widget);
return 0;
}
int photo::initTextConfig(TextConfig *text_config, int config_num, int preset, CameraWidget *window)
{
text_config->name = config_texts[config_num];
int result = gp_widget_get_child_by_name(window, text_config->name, &text_config->widget);
if (result)
{
std::cout << "wiget_get_child_by_name error. " << gp_result_as_string(result) << std::endl;
return 1;
}
result = gp_widget_count_choices(text_config->widget);
if (result < 0)
{
std::cout << "wiget_count choices error. " << gp_result_as_string(result) << std::endl;
return 1;
}
text_config->n = result;
text_config->choices= (const char**)malloc(sizeof(char*)*text_config->n);
// (*choices)[result] = NULL;
const char* tmp;
for(int i=0; i<text_config->n; i++)
{
result = gp_widget_get_choice(text_config->widget,i,&tmp);
if (result)
{
std::cout << "wiget_get_choices error. " << gp_result_as_string(result) << std::endl;
break;
}
text_config->choices[i] = tmp;
}
// if (preset >= text_config->n)
// {
// std::cout << "invalid preset number" << std::endl;
// return 1;
// }
// else
// {
// result = gp_widget_set_value(text_config->widget,text_config->choices[preset]);
// if (result)
// {
// std::cout << "widget set value error: " << gp_result_as_string(result) << std::endl;
// return 1;
// }
// }
return 0;
}
int photo::portInfoListNew(GPPortInfoList **portinfolist)
{
int ret = gp_port_info_list_new(portinfolist);
if (ret < GP_OK) return ret;
ret = gp_port_info_list_load(*portinfolist);
if (ret < 0) return ret;
ret = gp_port_info_list_count(*portinfolist);
if (ret < 0) return ret;
return 0;
}
int photo::abilitiesListNew(CameraAbilitiesList **abilities, GPContext *context)
{
int ret = gp_abilities_list_new(abilities);
if (ret < GP_OK) return ret;
ret = gp_abilities_list_load(*abilities, context);
if (ret < GP_OK) return ret;
return 0;
}
int photo::openCamera(Camera **camera, const char *model, const char *port, GPContext *context, GPPortInfoList *portinfolist, CameraAbilitiesList *abilities)
{
CameraAbilities CA;
GPPortInfo GPI;
int ret = gp_camera_new(camera);
if (ret < GP_OK) return ret;
int m = gp_abilities_list_lookup_model(abilities, model);
if (m < GP_OK) return ret;
ret = gp_abilities_list_get_abilities(abilities, m, &CA);
if (ret < GP_OK) return ret;
ret = gp_camera_set_abilities(*camera, CA);
if (ret < GP_OK) return ret;
int p = gp_port_info_list_lookup_path(portinfolist, port);
switch (p)
{
case GP_ERROR_UNKNOWN_PORT:
fprintf(stderr,
"The port you specified "
"('%s') can not be found. Please "
"specify one of the ports found by "
"'gphoto2 --list-ports' and make "
"sure the spelling is correct "
"(i.e. with prefix 'serial:' or 'usb:').",
port);
break;
default:
break;
}
if (p < GP_OK) return p;
ret = gp_port_info_list_get_info(portinfolist, p, &GPI);
if (ret < GP_OK) return ret;
ret = gp_camera_set_port_info(*camera, GPI);
if (ret < GP_OK) return ret;
return GP_OK;
}
| 27.435374 | 157 | 0.5879 | EIDOSDATA |
c5d28e9f588915161d2fb455c60248ad65eb2287 | 4,453 | cc | C++ | build/X86_MESI_Two_Level/mem/protocol/L2Cache_State.cc | hoho20000000/gem5-fy | b59f6feed22896d6752331652c4d8a41a4ca4435 | [
"BSD-3-Clause"
] | null | null | null | build/X86_MESI_Two_Level/mem/protocol/L2Cache_State.cc | hoho20000000/gem5-fy | b59f6feed22896d6752331652c4d8a41a4ca4435 | [
"BSD-3-Clause"
] | 1 | 2020-08-20T05:53:30.000Z | 2020-08-20T05:53:30.000Z | build/X86_MESI_Two_Level/mem/protocol/L2Cache_State.cc | hoho20000000/gem5-fy | b59f6feed22896d6752331652c4d8a41a4ca4435 | [
"BSD-3-Clause"
] | null | null | null | /** \file L2Cache_State.hh
*
* Auto generated C++ code started by /home/hongyu/gem5-fy/src/mem/slicc/symbols/Type.py:555
*/
#include <cassert>
#include <iostream>
#include <string>
#include "base/misc.hh"
#include "mem/protocol/L2Cache_State.hh"
using namespace std;
// Code to convert the current state to an access permission
AccessPermission L2Cache_State_to_permission(const L2Cache_State& obj)
{
switch(obj) {
case L2Cache_State_NP:
return AccessPermission_Invalid;
case L2Cache_State_SS:
return AccessPermission_Read_Only;
case L2Cache_State_M:
return AccessPermission_Read_Write;
case L2Cache_State_MT:
return AccessPermission_Maybe_Stale;
case L2Cache_State_M_I:
return AccessPermission_Busy;
case L2Cache_State_MT_I:
return AccessPermission_Busy;
case L2Cache_State_MCT_I:
return AccessPermission_Busy;
case L2Cache_State_I_I:
return AccessPermission_Busy;
case L2Cache_State_S_I:
return AccessPermission_Busy;
case L2Cache_State_ISS:
return AccessPermission_Busy;
case L2Cache_State_IS:
return AccessPermission_Busy;
case L2Cache_State_IM:
return AccessPermission_Busy;
case L2Cache_State_SS_MB:
return AccessPermission_Busy;
case L2Cache_State_MT_MB:
return AccessPermission_Busy;
case L2Cache_State_MT_IIB:
return AccessPermission_Busy;
case L2Cache_State_MT_IB:
return AccessPermission_Busy;
case L2Cache_State_MT_SB:
return AccessPermission_Busy;
default:
panic("Unknown state access permission converstion for L2Cache_State");
}
}
// Code for output operator
ostream&
operator<<(ostream& out, const L2Cache_State& obj)
{
out << L2Cache_State_to_string(obj);
out << flush;
return out;
}
// Code to convert state to a string
string
L2Cache_State_to_string(const L2Cache_State& obj)
{
switch(obj) {
case L2Cache_State_NP:
return "NP";
case L2Cache_State_SS:
return "SS";
case L2Cache_State_M:
return "M";
case L2Cache_State_MT:
return "MT";
case L2Cache_State_M_I:
return "M_I";
case L2Cache_State_MT_I:
return "MT_I";
case L2Cache_State_MCT_I:
return "MCT_I";
case L2Cache_State_I_I:
return "I_I";
case L2Cache_State_S_I:
return "S_I";
case L2Cache_State_ISS:
return "ISS";
case L2Cache_State_IS:
return "IS";
case L2Cache_State_IM:
return "IM";
case L2Cache_State_SS_MB:
return "SS_MB";
case L2Cache_State_MT_MB:
return "MT_MB";
case L2Cache_State_MT_IIB:
return "MT_IIB";
case L2Cache_State_MT_IB:
return "MT_IB";
case L2Cache_State_MT_SB:
return "MT_SB";
default:
panic("Invalid range for type L2Cache_State");
}
}
// Code to convert from a string to the enumeration
L2Cache_State
string_to_L2Cache_State(const string& str)
{
if (str == "NP") {
return L2Cache_State_NP;
} else if (str == "SS") {
return L2Cache_State_SS;
} else if (str == "M") {
return L2Cache_State_M;
} else if (str == "MT") {
return L2Cache_State_MT;
} else if (str == "M_I") {
return L2Cache_State_M_I;
} else if (str == "MT_I") {
return L2Cache_State_MT_I;
} else if (str == "MCT_I") {
return L2Cache_State_MCT_I;
} else if (str == "I_I") {
return L2Cache_State_I_I;
} else if (str == "S_I") {
return L2Cache_State_S_I;
} else if (str == "ISS") {
return L2Cache_State_ISS;
} else if (str == "IS") {
return L2Cache_State_IS;
} else if (str == "IM") {
return L2Cache_State_IM;
} else if (str == "SS_MB") {
return L2Cache_State_SS_MB;
} else if (str == "MT_MB") {
return L2Cache_State_MT_MB;
} else if (str == "MT_IIB") {
return L2Cache_State_MT_IIB;
} else if (str == "MT_IB") {
return L2Cache_State_MT_IB;
} else if (str == "MT_SB") {
return L2Cache_State_MT_SB;
} else {
panic("Invalid string conversion for %s, type L2Cache_State", str);
}
}
// Code to increment an enumeration type
L2Cache_State&
operator++(L2Cache_State& e)
{
assert(e < L2Cache_State_NUM);
return e = L2Cache_State(e+1);
}
| 27.658385 | 92 | 0.642488 | hoho20000000 |
c5d835cb3603806f929d8fc2e98ab38f16792861 | 1,138 | cc | C++ | statements/ReadStmt.cc | R2333333/SCAPES | 98f8aafc1bbd279165e82a70eaa3c22eef62c892 | [
"MIT"
] | null | null | null | statements/ReadStmt.cc | R2333333/SCAPES | 98f8aafc1bbd279165e82a70eaa3c22eef62c892 | [
"MIT"
] | null | null | null | statements/ReadStmt.cc | R2333333/SCAPES | 98f8aafc1bbd279165e82a70eaa3c22eef62c892 | [
"MIT"
] | null | null | null | #include "../headerFiles/ReadStmt.h"
#include "../headerFiles/Program.h"
using namespace std;
ReadStmt::ReadStmt()
:Statement(){}
void ReadStmt::compile(QString stat){
if (checkError(stat)){
return;
}
QStringList list = stat.split(" ");
instruction = list.at(0);
operand1 = new Operand(list.at(1));
statementObj["Instruction"] = instruction;
statementObj["Operand1"] = this->getFirstOperand();
}
void ReadStmt::run(){
if(!program->getVMap()->contains(operand1->getIdent()->getName())){
QMessageBox::warning(nullptr, "Error", QString("Variable not exists yet!!!"));
}else {
int input = QInputDialog::getInt(nullptr, ("Please enter an integer"), ("Value:"));
if(program->getVMap()->value(operand1->getIdent()->getName())->getType().compare("int") == 0){
program->getVMap()->value(operand1->getIdent()->getName())->setValue(input);
}
if(program->getVMap()->value(operand1->getIdent()->getName())->getType().compare("array") == 0){
program->getVMap()->value(operand1->getIdent()->getName())->addArrElement(input);
}
}
}
| 29.179487 | 104 | 0.623023 | R2333333 |
c5d99e4135541ff66bfbb967dc53ecc3d143ed9a | 2,393 | hpp | C++ | include/UnityEngine/TestRunner/NUnitExtensions/TestResultExtensions.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/UnityEngine/TestRunner/NUnitExtensions/TestResultExtensions.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/UnityEngine/TestRunner/NUnitExtensions/TestResultExtensions.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: NUnit::Framework::Internal
namespace NUnit::Framework::Internal {
// Forward declaring type: TestResult
class TestResult;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Exception
class Exception;
}
// Forward declaring namespace: NUnit::Framework::Interfaces
namespace NUnit::Framework::Interfaces {
// Forward declaring type: ResultState
class ResultState;
}
// Completed forward declares
// Type namespace: UnityEngine.TestRunner.NUnitExtensions
namespace UnityEngine::TestRunner::NUnitExtensions {
// Size: 0x10
#pragma pack(push, 1)
// Autogenerated type: UnityEngine.TestRunner.NUnitExtensions.TestResultExtensions
// [ExtensionAttribute] Offset: FFFFFFFF
class TestResultExtensions : public ::Il2CppObject {
public:
// Creating value type constructor for type: TestResultExtensions
TestResultExtensions() noexcept {}
// static public System.Void RecordPrefixedException(NUnit.Framework.Internal.TestResult testResult, System.String prefix, System.Exception ex, NUnit.Framework.Interfaces.ResultState resultState)
// Offset: 0x1496A14
static void RecordPrefixedException(NUnit::Framework::Internal::TestResult* testResult, ::Il2CppString* prefix, System::Exception* ex, NUnit::Framework::Interfaces::ResultState* resultState);
// static public System.Void RecordPrefixedError(NUnit.Framework.Internal.TestResult testResult, System.String prefix, System.String error, NUnit.Framework.Interfaces.ResultState resultState)
// Offset: 0x1496E84
static void RecordPrefixedError(NUnit::Framework::Internal::TestResult* testResult, ::Il2CppString* prefix, ::Il2CppString* error, NUnit::Framework::Interfaces::ResultState* resultState);
}; // UnityEngine.TestRunner.NUnitExtensions.TestResultExtensions
#pragma pack(pop)
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(UnityEngine::TestRunner::NUnitExtensions::TestResultExtensions*, "UnityEngine.TestRunner.NUnitExtensions", "TestResultExtensions");
| 52.021739 | 200 | 0.752194 | darknight1050 |
c5da7565372b3c8a4fb8d54869459fddce5b60b9 | 795 | cpp | C++ | src/algorithms/kamenevs/KuniHeroVector.cpp | av-elier/fast-exponentiation-algs | 1d6393021583686372564a7ca52b09dc7013fb38 | [
"MIT"
] | 2 | 2016-10-17T20:30:05.000Z | 2020-03-24T19:52:14.000Z | src/algorithms/kamenevs/KuniHeroVector.cpp | av-elier/fast-exponentiation-algs | 1d6393021583686372564a7ca52b09dc7013fb38 | [
"MIT"
] | null | null | null | src/algorithms/kamenevs/KuniHeroVector.cpp | av-elier/fast-exponentiation-algs | 1d6393021583686372564a7ca52b09dc7013fb38 | [
"MIT"
] | null | null | null | #include "algorithms/kamenevs/KuniHeroVector.h"
#include <algorithm>
vector<string>* KuniheroVector::create_str_dicitionary(string s)
{
double p = 0;
for (int i = 0; i < s.length(); ++i)
p+=s[i] - 48;
p /= s.length();
double q = 1 - p;
Node* n = fill(k,p);
vector<string>* res = (n->get_paths());
for (int i = 0; i < res->size(); ++i)
{
(*res)[i] = (*res)[i].substr(0,(*res)[i].find_last_of("1")+1).c_str();
}
return res;
}
vector<ZZ>* KuniheroVector::create_num_dicitionary(vector<string>& strs)
{
vector<ZZ>* res = new vector<ZZ>();
for (int i = 0; i < strs.size(); ++i)
{
ZZ z;
conv(z,0);
for (int j = 0; j < strs[i].size(); ++j)
{
if (strs[i][j]=='1')
{
SetBit(z,strs[i].size() - j - 1);
}
}
res->push_back(z);
}
return res;
}
| 19.875 | 72 | 0.54717 | av-elier |
c5dfc442120aec8deaa0d3d2fb657b3bdc7f7f67 | 3,385 | cpp | C++ | pl2_assembler/main.cpp | MassiveBattlebotsFan/team-lightning-cpu | 513b92aec5b3fe185f4e9220340a23bb09561059 | [
"Unlicense"
] | 1 | 2021-09-30T19:39:55.000Z | 2021-09-30T19:39:55.000Z | pl2_assembler/main.cpp | MassiveBattlebotsFan/team-lightning-cpu | 513b92aec5b3fe185f4e9220340a23bb09561059 | [
"Unlicense"
] | null | null | null | pl2_assembler/main.cpp | MassiveBattlebotsFan/team-lightning-cpu | 513b92aec5b3fe185f4e9220340a23bb09561059 | [
"Unlicense"
] | null | null | null | #include <cstdio>
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <cstdint>
#include <cstring>
#include <map>
using namespace std;
int main(int argc, char const *argv[]) {
try{
//init logging to file
ofstream logging("pl2asm.log");
auto old_rdbuf = clog.rdbuf(); // not implemented
clog.rdbuf(logging.rdbuf());
std::map<string, uint16_t> opcodes = {};
string opcodesDb = "opcodes.db";
if(argc == 1){
cerr << "Usage: " << argv[0] << " -i source.pl2 [-v] [-d opcodes.db] [-o output.pl2c]" << endl;
return -1;
}
for(int i = 1; i < argc; i++){
if(strcmp(argv[i], "-v")==0){
clog.rdbuf(old_rdbuf);
break;
}
}
string outfile, infile;
for(int i = 1; i < argc; i++){
if(strcmp(argv[i], "-i")==0){
infile = argv[i+1];
break;
}
}
outfile = infile + 'c';
for(int i = 1; i < argc; i++){
if(strcmp(argv[i], "-o")==0){
outfile = argv[i+1];
clog << "outfile set" << endl;
}
if(strcmp(argv[i], "-d")==0){
opcodesDb = argv[i+1];
clog << "db set" << endl;
}
}
ifstream opcodesIn;
opcodesIn.open(opcodesDb);
if(!opcodesIn.is_open()){
throw("opcodes db open failed");
}
char buffer1[4096] = "", buffer2[4096] = "", buffer3[4096] = "";
stringstream parser;
clog << "Opcodes read:" << endl;
while(opcodesIn.getline(buffer1, 4096, '\n')){
parser.str("");
if(opcodesIn.fail()){
if(opcodesIn.bad()){
throw("opcodes db read stream bad");
}
if(opcodesIn.eof()){
break;
}
throw("opcodes db read loop failed");
}
parser << buffer1 << '\0';
parser.getline(buffer2, 4096, '=');
parser.getline(buffer3, 4096, '\0');
clog << buffer2 << ", " << buffer3 << endl;
opcodes[buffer3] = (uint16_t)strtol(buffer2, NULL, 16);
}
opcodesIn.close();
ifstream asmIn(infile.c_str());
if(!asmIn.is_open()){
throw("Assembly input file open failed");
}
ofstream asmOut(outfile.c_str());
if(!asmOut.is_open()){
throw("Assembled output file open failed");
}
uint16_t instrArgOut = 0x0;
uint16_t opCodeOut = 0x0;
clog << "Assembler output:" << endl;
while(asmIn.getline(buffer1, 4096, '\n')){
parser.str("");
if(asmIn.fail()){
if(asmIn.bad()){
throw("asm read stream bad");
}
throw("asm read loop failed");
}
parser << buffer1 << '\0';
parser.getline(buffer2, 4096, ':');
parser.getline(buffer3, 4096, '\0');
instrArgOut = (uint16_t)strtol(buffer3, NULL, 16);
opCodeOut = opcodes[buffer2];
clog << std::hex << std::setfill('0') << std::setw(2) << opCodeOut;
asmOut << std::hex << std::setfill('0') << std::setw(2) << opCodeOut;
clog << std::hex << std::setfill('0') << ',' << std::setw(4) << instrArgOut << ';' << endl;
asmOut << std::hex << std::setfill('0') << ',' << std::setw(4) << instrArgOut << ';';
}
asmIn.close();
asmOut.close();
return 0;
}catch(const char* error){
cerr << "Error: " << error << ", errno = " << strerror(errno) << endl;
return -1;
}catch(...){
cerr << "Unknown error. Program aborting." << endl;
return -1;
}
}
| 29.181034 | 101 | 0.52969 | MassiveBattlebotsFan |
c5dff3aade8632a6e61e52c3056107c113bcd0f2 | 3,936 | cpp | C++ | Plugins/OVRPlatformBP/Source/OVRPlatformBP/Private/OBPRequests_LanguagePack.cpp | Brain-Vision/Unreal-SharedSpaces | 262153c5c52c4e15fed5ece901e0e1c8502bb030 | [
"MIT"
] | null | null | null | Plugins/OVRPlatformBP/Source/OVRPlatformBP/Private/OBPRequests_LanguagePack.cpp | Brain-Vision/Unreal-SharedSpaces | 262153c5c52c4e15fed5ece901e0e1c8502bb030 | [
"MIT"
] | null | null | null | Plugins/OVRPlatformBP/Source/OVRPlatformBP/Private/OBPRequests_LanguagePack.cpp | Brain-Vision/Unreal-SharedSpaces | 262153c5c52c4e15fed5ece901e0e1c8502bb030 | [
"MIT"
] | null | null | null | // OVRPlatformBP plugin by InnerLoop LLC 2021
#include "OBPRequests_LanguagePack.h"
// --------------------
// Initializers
// --------------------
UOBPLanguagePack_GetCurrent::UOBPLanguagePack_GetCurrent(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
}
UOBPLanguagePack_SetCurrent::UOBPLanguagePack_SetCurrent(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
}
// --------------------
// OVR_Requests_LanguagePack.h
// --------------------
//---GetCurrent---
void UOBPLanguagePack_GetCurrent::Activate()
{
#if PLATFORM_MINOR_VERSION >= 28
auto OculusIdentityInterface = Online::GetIdentityInterface(OCULUS_SUBSYSTEM);
if (OculusIdentityInterface.IsValid())
{
ovrRequest RequestId = ovr_LanguagePack_GetCurrent();
FOnlineSubsystemOculus* OSS = static_cast<FOnlineSubsystemOculus*>(IOnlineSubsystem::Get(OCULUS_SUBSYSTEM));
OSS->AddRequestDelegate(RequestId, FOculusMessageOnCompleteDelegate::CreateLambda(
[this](ovrMessageHandle Message, bool bIsError)
{
if (bIsError)
{
OBPMessageError("LanguagePack::GetCurrent", Message);
OnFailure.Broadcast(nullptr);
}
else
{
ovrMessageType messageType = ovr_Message_GetType(Message);
if (messageType == ovrMessage_LanguagePack_GetCurrent)
{
UE_LOG(LogOVRPlatformBP, Log, TEXT("Successfully got current language pack."));
auto AssetDetails = NewObject<UOBPAssetDetails>();
AssetDetails->ovrAssetDetailsHandle = ovr_Message_GetAssetDetails(Message);
OnSuccess.Broadcast(AssetDetails);
}
else
{
UE_LOG(LogOVRPlatformBP, Log, TEXT("Failed to get current language pack."));
OnFailure.Broadcast(nullptr);
}
}
}));
}
else
{
OBPSubsystemError("LanguagePack::GetCurrent");
OnFailure.Broadcast(nullptr);
}
#else
OBPPlatformVersionError("LanguagePack::GetCurrent", "1.28");
OnFailure.Broadcast(nullptr);
#endif
}
UOBPLanguagePack_GetCurrent* UOBPLanguagePack_GetCurrent::GetCurrent(UObject* WorldContextObject)
{
return NewObject<UOBPLanguagePack_GetCurrent>();
}
//---SetCurrent---
void UOBPLanguagePack_SetCurrent::Activate()
{
#if PLATFORM_MINOR_VERSION >= 31
auto OculusIdentityInterface = Online::GetIdentityInterface(OCULUS_SUBSYSTEM);
if (OculusIdentityInterface.IsValid())
{
ovrRequest RequestId = ovr_LanguagePack_SetCurrent(TCHAR_TO_ANSI(*Tag));
FOnlineSubsystemOculus* OSS = static_cast<FOnlineSubsystemOculus*>(IOnlineSubsystem::Get(OCULUS_SUBSYSTEM));
OSS->AddRequestDelegate(RequestId, FOculusMessageOnCompleteDelegate::CreateLambda(
[this](ovrMessageHandle Message, bool bIsError)
{
if (bIsError)
{
OBPMessageError("LanguagePack::SetCurrent", Message);
OnFailure.Broadcast(FString(), FString());
}
else
{
ovrMessageType messageType = ovr_Message_GetType(Message);
if (messageType == ovrMessage_LanguagePack_SetCurrent)
{
UE_LOG(LogOVRPlatformBP, Log, TEXT("Successfully set current language pack."));
auto AssetFileDownloadResultHandle = ovr_Message_GetAssetFileDownloadResult(Message);
auto AssetID = OBPInt64ToFString(ovr_AssetFileDownloadResult_GetAssetId(AssetFileDownloadResultHandle));
auto FilePath = ovr_AssetFileDownloadResult_GetFilepath(AssetFileDownloadResultHandle);
OnSuccess.Broadcast(AssetID, FilePath);
}
else
{
UE_LOG(LogOVRPlatformBP, Log, TEXT("Failed to set current language pack."));
OnFailure.Broadcast(FString(), FString());
}
}
}));
}
else
{
OBPSubsystemError("LanguagePack::SetCurrent");
OnFailure.Broadcast(FString(), FString());
}
#else
OBPPlatformVersionError("LanguagePack::SetCurrent", "1.31");
OnFailure.Broadcast(FString(), FString());
#endif
}
UOBPLanguagePack_SetCurrent* UOBPLanguagePack_SetCurrent::SetCurrent(UObject* WorldContextObject, FString Tag)
{
auto SetCurrent = NewObject<UOBPLanguagePack_SetCurrent>();
SetCurrent->Tag = Tag;
return SetCurrent;
} | 29.818182 | 110 | 0.746697 | Brain-Vision |
c5e0fd6a70bc8bcda03a611793e213567f02d46e | 12,175 | cpp | C++ | src/ny/wayland/util.cpp | nyorain/ny | 9349a6f668a9458d3a37b76bb3cd1e5c679d16ad | [
"BSL-1.0"
] | 18 | 2015-12-14T09:04:06.000Z | 2021-11-14T20:38:17.000Z | src/ny/wayland/util.cpp | nyorain/ny | 9349a6f668a9458d3a37b76bb3cd1e5c679d16ad | [
"BSL-1.0"
] | 2 | 2015-06-26T09:26:05.000Z | 2019-04-02T09:05:12.000Z | src/ny/wayland/util.cpp | nyorain/ny | 9349a6f668a9458d3a37b76bb3cd1e5c679d16ad | [
"BSL-1.0"
] | 2 | 2017-08-23T06:04:26.000Z | 2019-11-27T01:48:02.000Z | // Copyright (c) 2015-2018 nyorain
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt
#include <ny/wayland/util.hpp>
#include <ny/wayland/appContext.hpp>
#include <ny/wayland/windowContext.hpp>
#include <ny/cursor.hpp>
#include <dlg/dlg.hpp>
#include <nytl/scope.hpp>
#include <wayland-client-protocol.h>
#include <ny/wayland/protocols/xdg-shell-v5.h>
#include <ny/wayland/protocols/xdg-shell-v6.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <iostream>
#include <cstring>
namespace ny {
namespace wayland {
namespace {
int setCloexecOrClose(int fd)
{
long flags;
if(fd == -1) goto err2;
flags = fcntl(fd, F_GETFD);
if(flags == -1) goto err1;
if(fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) goto err1;
return fd;
err1:
close(fd);
err2:
dlg_warn("fctnl failed: {}", std::strerror(errno));
return -1;
}
int createTmpfileCloexec(char *tmpname)
{
int fd;
#ifdef HAVE_MKOSTEMP
fd = mkostemp(tmpname, O_CLOEXEC);
if(fd >= 0) unlink(tmpname);
#else
fd = mkstemp(tmpname);
if(fd >= 0)
{
fd = setCloexecOrClose(fd);
unlink(tmpname);
}
#endif
return fd;
}
int osCreateAnonymousFile(off_t size)
{
static const char template1[] = "/weston-shared-XXXXXX";
const char *path;
char *name;
int fd;
path = getenv("XDG_RUNTIME_DIR");
if (!path) {
errno = ENOENT;
return -1;
}
name = (char*) malloc(strlen(path) + sizeof(template1));
if(!name) return -1;
strcpy(name, path);
strcat(name, template1);
fd = createTmpfileCloexec(name);
free(name);
if(fd < 0) return -1;
if(ftruncate(fd, size) < 0) {
close(fd);
return -1;
}
return fd;
}
} // anonymous util namespace
//shmBuffer
ShmBuffer::ShmBuffer(WaylandAppContext& ac, nytl::Vec2ui size, unsigned int stride)
: appContext_(&ac), size_(size), stride_(stride)
{
format_ = WL_SHM_FORMAT_ARGB8888;
if(!stride_) stride_ = size[0] * 4;
create();
}
ShmBuffer::~ShmBuffer()
{
destroy();
}
ShmBuffer::ShmBuffer(ShmBuffer&& other)
{
appContext_ = other.appContext_;
shmSize_ = other.shmSize_;
size_ = other.size_;
stride_ = other.stride_;
buffer_ = other.buffer_;
pool_ = other.pool_;
data_ = other.data_;
format_ = other.format_;
used_ = other.used_;
other.appContext_ = {};
other.shmSize_ = {};
other.size_ = {};
other.buffer_ = {};
other.pool_ = {};
other.data_ = {};
other.format_ = {};
other.used_ = {};
if(buffer_) wl_buffer_set_user_data(buffer_, this);
}
ShmBuffer& ShmBuffer::operator=(ShmBuffer&& other)
{
destroy();
appContext_ = other.appContext_;
shmSize_ = other.shmSize_;
size_ = other.size_;
stride_ = other.stride_;
buffer_ = other.buffer_;
pool_ = other.pool_;
data_ = other.data_;
format_ = other.format_;
used_ = other.used_;
other.appContext_ = {};
other.shmSize_ = {};
other.size_ = {};
other.buffer_ = {};
other.pool_ = {};
other.data_ = {};
other.format_ = {};
other.used_ = {};
if(buffer_) wl_buffer_set_user_data(buffer_, this);
return *this;
}
void ShmBuffer::create()
{
destroy();
if(!size_[0] || !size_[1]) throw std::runtime_error("ny::wayland::ShmBuffer invalid size");
if(!stride_) throw std::runtime_error("ny::wayland::ShmBuffer invalid stride");
auto* shm = appContext_->wlShm();
if(!shm) throw std::runtime_error("ny::wayland::ShmBuffer: appContext has no wl_shm");
auto vecSize = stride_ * size_[1];
shmSize_ = std::max(vecSize, shmSize_);
auto fd = osCreateAnonymousFile(shmSize_);
if (fd < 0) throw std::runtime_error("ny::wayland::ShmBuffer: could not create shm file");
// the fd is not needed here anymore AFTER the pool was created
// our access to the file is represented by the pool
auto fdGuard = nytl::ScopeGuard([&]{ close(fd); });
auto ptr = mmap(nullptr, shmSize_, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if(ptr == MAP_FAILED) throw std::runtime_error("ny::wayland::ShmBuffer: could not mmap file");
data_ = reinterpret_cast<std::uint8_t*>(ptr);
pool_ = wl_shm_create_pool(shm, fd, shmSize_);
buffer_ = wl_shm_pool_create_buffer(pool_, 0, size_[0], size_[1], stride_, format_);
static constexpr wl_buffer_listener listener {
memberCallback<&ShmBuffer::released>
};
wl_buffer_add_listener(buffer_, &listener, this);
}
void ShmBuffer::destroy()
{
if(buffer_) wl_buffer_destroy(buffer_);
if(pool_) wl_shm_pool_destroy(pool_);
if(data_) munmap(data_, shmSize_);
}
bool ShmBuffer::size(nytl::Vec2ui size, unsigned int stride)
{
size_ = size;
stride_ = stride;
if(!stride_) stride_ = size[0] * 4;
unsigned int vecSize = stride_ * size_[1];
if(!size_[0] || !size_[1]) throw std::runtime_error("ny::wayland::ShmBuffer invalid size");
if(!stride_) throw std::runtime_error("ny::wayland::ShmBuffer invalid stride");
if(vecSize > shmSize_) {
create();
return true;
} else {
wl_buffer_destroy(buffer_);
buffer_ = wl_shm_pool_create_buffer(pool_, 0, size_[0], size_[1], stride_, format_);
return false;
}
}
// Output
Output::Output(WaylandAppContext& ac, wl_output& outp, unsigned int id)
: appContext_(&ac), wlOutput_(&outp), globalID_(id)
{
static constexpr wl_output_listener listener {
memberCallback<&Output::geometry>,
memberCallback<&Output::mode>,
memberCallback<&Output::done>,
memberCallback<&Output::scale>
};
wl_output_add_listener(&outp, &listener, this);
}
Output::~Output()
{
if(wlOutput_) {
if(wl_output_get_version(wlOutput_) > 3) wl_output_release(wlOutput_);
else wl_output_destroy(wlOutput_);
}
}
Output::Output(Output&& other) noexcept :
appContext_(other.appContext_), wlOutput_(other.wlOutput_), globalID_(other.globalID_),
information_(other.information_)
{
other.appContext_ = {};
other.wlOutput_ = {};
if(wlOutput_) wl_output_set_user_data(wlOutput_, this);
}
Output& Output::operator=(Output&& other) noexcept
{
if(wlOutput_) wl_output_release(wlOutput_);
appContext_ = other.appContext_;
wlOutput_ = other.wlOutput_;
globalID_ = other.globalID_;
information_ = std::move(other.information_);
other.appContext_ = {};
other.wlOutput_ = {};
if(wlOutput_) wl_output_set_user_data(wlOutput_, this);
return *this;
}
void Output::geometry(wl_output*, int32_t x, int32_t y, int32_t phwidth, int32_t phheight,
int32_t subpixel, const char* make, const char* model, int32_t transform)
{
information_.make = make;
information_.model = model;
information_.transform = transform;
information_.position = {x, y};
information_.physicalSize = {static_cast<uint32_t>(phwidth), static_cast<uint32_t>(phheight)};
information_.subpixel = subpixel;
}
void Output::mode(wl_output*, uint32_t flags, int32_t width, int32_t height, int32_t refresh)
{
unsigned int urefresh = refresh;
information_.modes.push_back({{}, flags, urefresh});
information_.modes.back().size = {static_cast<uint32_t>(width), static_cast<uint32_t>(height)};
}
void Output::done(wl_output*)
{
information_.done = true;
}
void Output::scale(wl_output*, int32_t scale)
{
information_.scale = scale;
}
// util
const char* errorName(const wl_interface& interface, int error)
{
struct Error {
int code;
const char* msg;
};
static struct {
const wl_interface& interface;
std::vector<Error> errors;
} interfaces[] = {
// core protocol
{ wl_display_interface, {
{ WL_DISPLAY_ERROR_INVALID_OBJECT, "WL_DISPLAY_ERROR_INVALID_OBJECT" },
{ WL_DISPLAY_ERROR_INVALID_METHOD, "WL_DISPLAY_ERROR_INVALID_METHOD" },
{ WL_DISPLAY_ERROR_NO_MEMORY, "WL_DISPLAY_ERROR_NO_MEMORY" } }
},
{ wl_shm_interface, {
{ WL_SHM_ERROR_INVALID_FORMAT, "WL_SHM_ERROR_INVALID_FORMAT" },
{ WL_SHM_ERROR_INVALID_STRIDE, "WL_SHM_ERROR_INVALID_STRIDE" },
{ WL_SHM_ERROR_INVALID_FD, "WL_SHM_ERROR_INVALID_FD" } }
},
{ wl_data_offer_interface, {
{ WL_DATA_OFFER_ERROR_INVALID_FINISH, "WL_DATA_OFFER_ERROR_INVALID_FINISH" },
{ WL_DATA_OFFER_ERROR_INVALID_ACTION_MASK, "WL_DATA_OFFER_ERROR_INVALID_ACTION_MASK" },
{ WL_DATA_OFFER_ERROR_INVALID_ACTION, "WL_DATA_OFFER_ERROR_INVALID_ACTION" },
{ WL_DATA_OFFER_ERROR_INVALID_OFFER , "WL_DATA_OFFER_ERROR_INVALID_OFFER" } }
},
{ wl_data_source_interface, {
{ WL_DATA_SOURCE_ERROR_INVALID_ACTION_MASK, "WL_DATA_SOURCE_ERROR_INVALID_ACTION_MASK" },
{ WL_DATA_SOURCE_ERROR_INVALID_SOURCE, "WL_DATA_SOURCE_ERROR_INVALID_SOURCE" } }
},
{ wl_data_device_interface, {
{ WL_DATA_DEVICE_ERROR_ROLE, "WL_DATA_DEVICE_ERROR_ROLE" } },
},
{ wl_shell_interface, {
{ WL_SHELL_ERROR_ROLE, "WL_SHELL_ERROR_ROLE" } },
},
{ wl_surface_interface, {
{ WL_SURFACE_ERROR_INVALID_SCALE, "WL_SURFACE_ERROR_INVALID_SCALE" },
{ WL_SURFACE_ERROR_INVALID_TRANSFORM, "WL_SURFACE_ERROR_INVALID_TRANSFORM" } },
},
{ wl_shell_interface, {
{ WL_POINTER_ERROR_ROLE, "WL_POINTER_ERROR_ROLE" } },
},
{ wl_subcompositor_interface, {
{ WL_SUBCOMPOSITOR_ERROR_BAD_SURFACE, "WL_SUBCOMPOSITOR_ERROR_BAD_SURFACE" } },
},
{ wl_subsurface_interface, {
{ WL_SUBSURFACE_ERROR_BAD_SURFACE, "WL_SUBSURFACE_ERROR_BAD_SURFACE" } },
},
// xdg
// shell v5
{ xdg_shell_interface, {
{ XDG_SHELL_ERROR_ROLE, "XDG_SHELL_ERROR_ROLE" },
{ XDG_SHELL_ERROR_DEFUNCT_SURFACES, "XDG_SHELL_ERROR_DEFUNCT_SURFACES" },
{ XDG_SHELL_ERROR_NOT_THE_TOPMOST_POPUP, "XDG_SHELL_ERROR_NOT_THE_TOPMOST_POPUP" },
{ XDG_SHELL_ERROR_INVALID_POPUP_PARENT, "XDG_SHELL_ERROR_INVALID_POPUP_PARENT" } },
},
// shell v6
{ zxdg_shell_v6_interface, {
{ ZXDG_SHELL_V6_ERROR_ROLE, "ZXDG_SHELL_V6_ERROR_ROLE" },
{ ZXDG_SHELL_V6_ERROR_DEFUNCT_SURFACES, "ZXDG_SHELL_V6_ERROR_DEFUNCT_SURFACES" },
{ ZXDG_SHELL_V6_ERROR_NOT_THE_TOPMOST_POPUP,
"ZXDG_SHELL_V6_ERROR_NOT_THE_TOPMOST_POPUP" },
{ ZXDG_SHELL_V6_ERROR_INVALID_POPUP_PARENT,
"ZXDG_SHELL_V6_ERROR_INVALID_POPUP_PARENT" },
{ ZXDG_SHELL_V6_ERROR_INVALID_SURFACE_STATE,
"ZXDG_SHELL_V6_ERROR_INVALID_SURFACE_STATE" },
{ ZXDG_SHELL_V6_ERROR_INVALID_POSITIONER, "ZXDG_SHELL_V6_ERROR_INVALID_POSITIONER" } },
},
{ zxdg_positioner_v6_interface, {
{ ZXDG_POSITIONER_V6_ERROR_INVALID_INPUT, "ZXDG_POSITIONER_V6_ERROR_INVALID_INPUT"} }
},
{ zxdg_surface_v6_interface, {
{ ZXDG_SURFACE_V6_ERROR_NOT_CONSTRUCTED, "ZXDG_SURFACE_V6_ERROR_NOT_CONSTRUCTED" },
{ ZXDG_SURFACE_V6_ERROR_ALREADY_CONSTRUCTED,
"ZXDG_SURFACE_V6_ERROR_ALREADY_CONSTRUCTED" },
{ ZXDG_SURFACE_V6_ERROR_UNCONFIGURED_BUFFER,
"ZXDG_SURFACE_V6_ERROR_UNCONFIGURED_BUFFER" } }
},
{ zxdg_popup_v6_interface, {
{ ZXDG_POPUP_V6_ERROR_INVALID_GRAB, "ZXDG_POPUP_V6_ERROR_INVALID_GRAB"} }
},
};
for(auto& i : interfaces) {
if(&i.interface != &interface) {
continue;
}
for(auto& e : i.errors) {
if(e.code == error) {
return e.msg;
}
}
break;
}
return "<unknown interface error>";
}
} // namespace wayland
WindowEdge waylandToEdge(unsigned int wlEdge)
{
return static_cast<WindowEdge>(wlEdge);
}
unsigned int edgeToWayland(WindowEdge edge)
{
return static_cast<unsigned int>(edge);
}
constexpr struct FormatConversion {
ImageFormat imageFormat;
unsigned int shmFormat;
} formatConversions[] {
{ImageFormat::argb8888, WL_SHM_FORMAT_ARGB8888},
{ImageFormat::argb8888, WL_SHM_FORMAT_XRGB8888},
{ImageFormat::rgba8888, WL_SHM_FORMAT_RGBA8888},
{ImageFormat::bgra8888, WL_SHM_FORMAT_BGRA8888},
{ImageFormat::abgr8888, WL_SHM_FORMAT_ABGR8888},
{ImageFormat::bgr888, WL_SHM_FORMAT_BGR888},
{ImageFormat::rgb888, WL_SHM_FORMAT_RGB888},
};
int imageFormatToWayland(const ImageFormat& format)
{
for(auto& fc : formatConversions) if(fc.imageFormat == format) return fc.shmFormat;
return -1;
}
ImageFormat waylandToImageFormat(unsigned int shmFormat)
{
for(auto& fc : formatConversions) if(fc.shmFormat == shmFormat) return fc.imageFormat;
return ImageFormat::none;
}
unsigned int stateToWayland(ToplevelState state)
{
switch(state) {
case ToplevelState::maximized: return 1;
case ToplevelState::fullscreen: return 2;
default: return 0;
}
}
ToplevelState waylandToState(unsigned int wlState)
{
switch(wlState) {
case 1: return ToplevelState::maximized;
case 2: return ToplevelState::fullscreen;
default: return ToplevelState::unknown;
}
}
} // namespace ny
| 26.070664 | 96 | 0.733306 | nyorain |
c5e41c26b1839f262fd7709cf3963962bcad1f3c | 953 | hh | C++ | difAlgebra/DifExternal.hh | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | difAlgebra/DifExternal.hh | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | difAlgebra/DifExternal.hh | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | //--------------------------------------------------------------------------
// File and Version Information:
// $Id: DifExternal.hh 501 2010-01-14 12:46:50Z stroili $
//
// Description:
// Class Header for |DifExternal|
// Define some useful constants
//
// Environment:
// Software developed for the BaBar Detector at the SLAC B-Factory.
//
// Author List:
// A. Snyder
//
// Copyright Information:
// Copyright (C) 1996 SLAC
//
//------------------------------------------------------------------------
#ifndef DifExternal_HH
#define DifExternal_HH
#include "difAlgebra/DifNumber.hh"
#include "difAlgebra/DifVector.hh"
#include "difAlgebra/DifPoint.hh"
#include "difAlgebra/DifComplex.hh"
extern const DifNumber one;
extern const DifNumber zero;
extern const DifVector xhat;
extern const DifVector yhat;
extern const DifVector zhat;
extern const DifVector nullVec;
extern const DifPoint origin;
extern const DifComplex I;
#endif
| 19.44898 | 76 | 0.624344 | brownd1978 |
c5e6927a84897e035464382bbce98ce647ae81a9 | 395 | cpp | C++ | round1/integration/main.cpp | ymadzhunkov/codeit | a013480ef39259bd282996d7d62296f089e708f4 | [
"MIT"
] | null | null | null | round1/integration/main.cpp | ymadzhunkov/codeit | a013480ef39259bd282996d7d62296f089e708f4 | [
"MIT"
] | null | null | null | round1/integration/main.cpp | ymadzhunkov/codeit | a013480ef39259bd282996d7d62296f089e708f4 | [
"MIT"
] | null | null | null | #include "keyboard.h"
#include "answer.h"
#include "simulated_annealing.h"
#include "progress.h"
int main(int argc, char *argv[]) {
Problem problem(fopen("keyboard.in", "r"));
Progress progress(2.8);
SimulatedAnnealing sa(problem, progress);
sa.optimize(1234);
sa.getBest().write(fopen("keyboard.out", "w"), problem);
progress.report(stdout);
return EXIT_SUCCESS;
}
| 26.333333 | 60 | 0.678481 | ymadzhunkov |
c5eaeb476dc8c69d5770c7fa480e144243cd1ed7 | 1,902 | cpp | C++ | EngineGUI/FolderBrowser.cpp | openlastchaos/lastchaos-source-client | 3d88594dba7347b1bb45378136605e31f73a8555 | [
"Apache-2.0"
] | 1 | 2022-02-14T15:46:44.000Z | 2022-02-14T15:46:44.000Z | EngineGUI/FolderBrowser.cpp | openlastchaos/lastchaos-source-client | 3d88594dba7347b1bb45378136605e31f73a8555 | [
"Apache-2.0"
] | null | null | null | EngineGUI/FolderBrowser.cpp | openlastchaos/lastchaos-source-client | 3d88594dba7347b1bb45378136605e31f73a8555 | [
"Apache-2.0"
] | 2 | 2022-01-10T22:17:06.000Z | 2022-01-17T09:34:08.000Z | #include "stdh.h"
#include <shlobj.h>
static int CALLBACK BrowseCallbackProc(HWND hwnd,UINT uMsg,LPARAM lp, LPARAM pData)
{
TCHAR szDir[MAX_PATH];
switch(uMsg) {
case BFFM_INITIALIZED: {
SendMessage(hwnd,BFFM_SETSELECTION,TRUE,(LPARAM)pData);
break;
}
case BFFM_SELCHANGED: {
// enable or disable ok button if current dir is inside app path
if (SHGetPathFromIDList((LPITEMIDLIST) lp ,szDir)) {
CTFileName fnSelectedDir = (CTString)szDir + (CTString)"\\";
try {
fnSelectedDir.RemoveApplicationPath_t();
SendMessage(hwnd,BFFM_ENABLEOK ,0,TRUE);
} catch(char *) {
SendMessage(hwnd,BFFM_ENABLEOK ,0,FALSE);
}
return 0;
}
break;
}
}
return 0;
}
// Folder browse
ENGINEGUI_API BOOL CEngineGUI::BrowseForFolder(CTFileName &fnBrowsedFolder, CTString strDefaultDir, char *strWindowTitle/*="Choose folder"*/)
{
CTString fnFullRootDir = _fnmApplicationPath+strDefaultDir;
BROWSEINFO biBrowse;
memset(&biBrowse,0,sizeof(BROWSEINFO));
biBrowse.hwndOwner = AfxGetMainWnd()->m_hWnd;
biBrowse.pidlRoot = NULL;
biBrowse.pszDisplayName = NULL;
biBrowse.lpszTitle = strWindowTitle;
biBrowse.ulFlags = BIF_RETURNFSANCESTORS;
biBrowse.lpfn = BrowseCallbackProc;
biBrowse.lParam = (LPARAM)(const char*)fnFullRootDir;
// From msdn
ITEMIDLIST *pidl = SHBrowseForFolder(&biBrowse);
if(pidl!=NULL) {
char ach[MAX_PATH];
SHGetPathFromIDList(pidl, ach);
IMalloc *pm;
SHGetMalloc(&pm);
if(pm) {
pm->Free(pidl);
pm->Release();
}
CTFileName fnFullBrowsedDir = (CTString)ach + (CTString)"\\";
try {
fnFullBrowsedDir.RemoveApplicationPath_t();
fnBrowsedFolder = fnFullBrowsedDir;
return TRUE;
} catch(char *strErr) {
WarningMessage(strErr);
return FALSE;
}
} else {
return FALSE;
}
}
| 27.565217 | 141 | 0.666667 | openlastchaos |
c5eba0d073d8882945741c6aeb5c5be60c700c5e | 24,449 | cc | C++ | tests/unit/lb/test_lb_stats_comm.cc | rbuch/vt | 74c2e0cae3201dfbcbfda7644c354703ddaed6bb | [
"BSD-3-Clause"
] | 26 | 2019-11-26T08:36:15.000Z | 2022-02-15T17:13:21.000Z | tests/unit/lb/test_lb_stats_comm.cc | rbuch/vt | 74c2e0cae3201dfbcbfda7644c354703ddaed6bb | [
"BSD-3-Clause"
] | 1,215 | 2019-09-09T14:31:33.000Z | 2022-03-30T20:20:14.000Z | tests/unit/lb/test_lb_stats_comm.cc | rbuch/vt | 74c2e0cae3201dfbcbfda7644c354703ddaed6bb | [
"BSD-3-Clause"
] | 12 | 2019-09-08T00:03:05.000Z | 2022-02-23T21:28:35.000Z | /*
//@HEADER
// *****************************************************************************
//
// test_lb_stats_comm.cc
// DARMA/vt => Virtual Transport
//
// Copyright 2019-2021 National Technology & Engineering Solutions of Sandia, LLC
// (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
// Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of 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 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.
//
// Questions? Contact [email protected]
//
// *****************************************************************************
//@HEADER
*/
#include "test_parallel_harness.h"
#include <vt/transport.h>
#include <vt/utils/json/json_appender.h>
#include <vt/utils/json/json_reader.h>
#include <vt/utils/json/decompression_input_container.h>
#include <vt/utils/json/input_iterator.h>
#include <nlohmann/json.hpp>
#if vt_check_enabled(lblite)
namespace vt { namespace tests { namespace unit { namespace comm {
/**
* --------------------------------------
* Communication Record Summary
* --------------------------------------
* -------- || --------- Sender ---------
* Receiver || ColT | ObjGroup | Handler
* --------------------------------------
* ColT || R | R | R
* ObjGroup || S | S | S
* Handler || S | S | S
* --------------------------------------
*/
using TestLBStatsComm = TestParallelHarness;
using StatsData = vt::vrt::collection::balance::StatsData;
StatsData getStatsDataForPhase(vt::PhaseType phase) {
using JSONAppender = vt::util::json::Appender<std::stringstream>;
using vt::util::json::DecompressionInputContainer;
using vt::vrt::collection::balance::StatsData;
using json = nlohmann::json;
std::stringstream ss{std::ios_base::out | std::ios_base::in};
auto ap = std::make_unique<JSONAppender>("phases", std::move(ss), true);
auto j = vt::theNodeStats()->getStatsData()->toJson(phase);
ap->addElm(*j);
ss = ap->finish();
auto c = DecompressionInputContainer{
DecompressionInputContainer::AnyStreamTag{}, std::move(ss)
};
return StatsData{json::parse(c)};
}
namespace {
auto constexpr dim1 = 64;
auto constexpr num_sends = 4;
struct MyCol : vt::Collection<MyCol, vt::Index1D> { };
struct MyMsg : vt::CollectionMessage<MyCol> { double x, y, z; };
struct MyObjMsg : vt::Message { double x, y, z; };
struct ElementInfo {
using MapType = std::map<vt::Index1D, vt::elm::ElementIDStruct>;
ElementInfo() = default;
explicit ElementInfo(MapType in_map) : elms(in_map) { }
friend ElementInfo operator+(ElementInfo a1, ElementInfo const& a2) {
for (auto&& x : a2.elms) a1.elms.insert(x);
return a1;
}
template <typename SerializerT>
void serialize(SerializerT& s) {
s | elms;
}
MapType elms;
};
struct ReduceMsg : SerializeRequired<
vt::collective::ReduceTMsg<ElementInfo>, ReduceMsg
> {
using MessageParentType = SerializeRequired<
vt::collective::ReduceTMsg<ElementInfo>, ReduceMsg
>;
ReduceMsg() = default;
ReduceMsg(vt::Index1D idx, vt::elm::ElementIDStruct elm_id)
: MessageParentType(
ElementInfo{
std::map<vt::Index1D, vt::elm::ElementIDStruct>{{idx, elm_id}}
}
)
{ }
template <typename SerializerT>
void serialize(SerializerT& s) {
MessageParentType::serialize(s);
}
};
struct ColProxyMsg : vt::Message {
using ProxyType = vt::CollectionProxy<MyCol>;
ColProxyMsg(ProxyType in_proxy) : proxy(in_proxy) { }
ProxyType proxy;
};
struct ProxyMsg;
struct MyObj {
void dummyHandler(MyObjMsg* msg) {}
void simulateObjGroupColTSends(ColProxyMsg* msg);
void simulateObjGroupObjGroupSends(ProxyMsg* msg);
void simulateObjGroupHandlerSends(MyMsg* msg);
};
struct ProxyMsg : vt::CollectionMessage<MyCol> {
using ProxyType = vt::objgroup::proxy::Proxy<MyObj>;
ProxyMsg(ProxyType in_proxy) : obj_proxy(in_proxy) { }
ProxyType obj_proxy;
};
void handler2(MyMsg* msg, MyCol* col) {}
void MyObj::simulateObjGroupColTSends(ColProxyMsg* msg) {
auto proxy = msg->proxy;
auto this_node = theContext()->getNode();
auto num_nodes = theContext()->getNumNodes();
auto next = (this_node + 1) % num_nodes;
for (int i = 0; i < dim1; i++) {
vt::Index1D idx{i};
auto node = vt::theCollection()->getMappedNode(proxy, idx);
if (node == next) {
for (int j = 0; j < num_sends; j++) {
proxy(idx).template send<MyMsg, handler2>();
}
}
}
}
void MyObj::simulateObjGroupObjGroupSends(ProxyMsg* msg) {
auto obj_proxy = msg->obj_proxy;
auto this_node = theContext()->getNode();
auto num_nodes = theContext()->getNumNodes();
auto next = (this_node + 1) % num_nodes;
for (int i = 0; i < num_sends; i++) {
obj_proxy[next].template send<MyObjMsg, &MyObj::dummyHandler>();
}
}
void simulateColTColTSends(MyMsg* msg, MyCol* col) {
auto proxy = col->getCollectionProxy();
auto index = col->getIndex();
auto next = (index.x() + 1) % dim1;
for (int i = 0; i < num_sends; i++) {
proxy(next).template send<MyMsg, handler2>();
}
}
void simulateColTObjGroupSends(ProxyMsg* msg, MyCol* col) {
auto obj_proxy = msg->obj_proxy;
auto this_node = theContext()->getNode();
auto num_nodes = theContext()->getNumNodes();
auto next = (this_node + 1) % num_nodes;
for (int i = 0; i < num_sends; i++) {
obj_proxy[next].template send<MyObjMsg, &MyObj::dummyHandler>();
}
}
void bareDummyHandler(MyObjMsg* msg) {}
void simulateColTHandlerSends(MyMsg* msg, MyCol* col) {
auto this_node = theContext()->getNode();
auto num_nodes = theContext()->getNumNodes();
auto next = (this_node + 1) % num_nodes;
for (int i = 0; i < num_sends; i++) {
auto msg2 = makeMessage<MyObjMsg>();
vt::theMsg()->sendMsg<MyObjMsg, bareDummyHandler>(next, msg2);
}
}
void MyObj::simulateObjGroupHandlerSends(MyMsg* msg) {
auto this_node = theContext()->getNode();
auto num_nodes = theContext()->getNumNodes();
auto next = (this_node + 1) % num_nodes;
for (int i = 0; i < num_sends; i++) {
auto msg2 = makeMessage<MyObjMsg>();
vt::theMsg()->sendMsg<MyObjMsg, bareDummyHandler>(next, msg2);
}
}
void simulateHandlerColTSends(ColProxyMsg* msg) {
auto proxy = msg->proxy;
auto this_node = theContext()->getNode();
auto num_nodes = theContext()->getNumNodes();
auto next = (this_node + 1) % num_nodes;
for (int i = 0; i < dim1; i++) {
vt::Index1D idx{i};
auto node = vt::theCollection()->getMappedNode(proxy, idx);
if (node == next) {
for (int j = 0; j < num_sends; j++) {
proxy(idx).template send<MyMsg, handler2>();
}
}
}
}
void simulateHandlerObjGroupSends(ProxyMsg* msg) {
auto obj_proxy = msg->obj_proxy;
auto this_node = theContext()->getNode();
auto num_nodes = theContext()->getNumNodes();
auto next = (this_node + 1) % num_nodes;
for (int i = 0; i < num_sends; i++) {
obj_proxy[next].template send<MyObjMsg, &MyObj::dummyHandler>();
}
}
void simulateHandlerHandlerSends(MyMsg* msg) {
auto this_node = theContext()->getNode();
auto num_nodes = theContext()->getNumNodes();
auto next = (this_node + 1) % num_nodes;
for (int i = 0; i < num_sends; i++) {
auto msg2 = makeMessage<MyObjMsg>();
vt::theMsg()->sendMsg<MyObjMsg, bareDummyHandler>(next, msg2);
}
}
std::map<vt::Index1D, vt::elm::ElementIDStruct> all_elms;
auto idxToElmID = [](vt::Index1D i) -> vt::elm::ElementIDType {
return all_elms.find(i)->second.id;
};
void recvElementIDs(ReduceMsg* msg) { all_elms = msg->getVal().elms; }
void doReduce(MyMsg*, MyCol* col) {
auto proxy = col->getCollectionProxy();
auto index = col->getIndex();
auto cb = theCB()->makeBcast<ReduceMsg, recvElementIDs>();
auto msg = makeMessage<ReduceMsg>(index, col->getElmID());
proxy.reduce<vt::collective::PlusOp<ElementInfo>>(msg.get(), cb);
}
// ColT -> ColT, expected communication edge on receive side
TEST_F(TestLBStatsComm, test_lb_stats_comm_col_to_col_send) {
auto range = vt::Index1D{dim1};
auto proxy = vt::makeCollection<MyCol>()
.bounds(range)
.bulkInsert()
.wait();
vt::runInEpochCollective("simulateColTColTSends", [&]{
for (int i = 0; i < dim1; i++) {
if (proxy(i).tryGetLocalPtr()) {
proxy(i).invoke<MyMsg, simulateColTColTSends>();
}
}
});
vt::thePhase()->nextPhaseCollective();
vt::runInEpochCollective("doReduce", [&]{
for (int i = 0; i < dim1; i++) {
if (proxy(i).tryGetLocalPtr()) {
proxy(i).invoke<MyMsg, doReduce>();
}
}
});
vt::PhaseType phase = 0;
auto sd = getStatsDataForPhase(phase);
auto& comm = sd.node_comm_;
// Check that communication exists on the receive side as expected
for (int i = 0; i < dim1; i++) {
vt::Index1D idx{i};
auto prev_i = i-1 >= 0 ? i-1 : dim1-1;
vt::Index1D prev_idx{prev_i};
if (proxy(i).tryGetLocalPtr()) {
bool found = false;
for (auto&& x : comm) {
for (auto&& y : x.second) {
auto key = y.first;
auto vol = y.second;
if (key.to_.id == idxToElmID(idx)) {
EXPECT_TRUE(key.to_.isMigratable());
EXPECT_TRUE(key.from_.isMigratable());
EXPECT_EQ(key.from_.id, idxToElmID(prev_idx));
EXPECT_EQ(vol.bytes, sizeof(MyMsg) * num_sends);
EXPECT_EQ(vol.messages, num_sends);
found = true;
}
}
}
EXPECT_TRUE(found);
}
}
}
// ColT -> ObjGroup, expected communication edge on send side
TEST_F(TestLBStatsComm, test_lb_stats_comm_col_to_objgroup_send) {
auto range = vt::Index1D{dim1};
auto proxy = vt::makeCollection<MyCol>()
.bounds(range)
.bulkInsert()
.wait();
auto obj_proxy = vt::theObjGroup()->makeCollective<MyObj>();
vt::runInEpochCollective("simulateColTObjGroupSends", [&]{
for (int i = 0; i < dim1; i++) {
if (proxy(i).tryGetLocalPtr()) {
proxy(i).invoke<ProxyMsg, simulateColTObjGroupSends>(obj_proxy);
}
}
});
vt::thePhase()->nextPhaseCollective();
vt::runInEpochCollective("doReduce", [&]{
for (int i = 0; i < dim1; i++) {
if (proxy(i).tryGetLocalPtr()) {
proxy(i).invoke<MyMsg, doReduce>();
}
}
});
vt::PhaseType phase = 0;
auto sd = getStatsDataForPhase(phase);
auto& comm = sd.node_comm_;
auto this_node = theContext()->getNode();
auto num_nodes = theContext()->getNumNodes();
auto next = (this_node + 1) % num_nodes;
auto op = obj_proxy.getProxy();
// Check that communication exists on the send side as expected
for (int i = 0; i < dim1; i++) {
vt::Index1D idx{i};
if (proxy(i).tryGetLocalPtr()) {
bool found = false;
auto idb = vt::elm::ElmIDBits::createObjGroup(op, next).id;
for (auto&& x : comm) {
for (auto&& y : x.second) {
auto key = y.first;
auto vol = y.second;
if (key.from_.id == idxToElmID(idx) /*and key.to_.id == idb*/) {
EXPECT_TRUE(key.from_.isMigratable());
EXPECT_EQ(key.from_.id, idxToElmID(idx));
EXPECT_FALSE(key.to_.isMigratable());
EXPECT_EQ(key.to_.id, idb);
EXPECT_EQ(vol.bytes, sizeof(MyObjMsg) * num_sends);
EXPECT_EQ(vol.messages, num_sends);
found = true;
}
}
}
EXPECT_TRUE(found);
}
}
}
// ObjGroup -> ColT, expected communication edge on receive side
TEST_F(TestLBStatsComm, test_lb_stats_comm_objgroup_to_col_send) {
auto range = vt::Index1D{dim1};
auto proxy = vt::makeCollection<MyCol>()
.bounds(range)
.bulkInsert()
.wait();
auto obj_proxy = vt::theObjGroup()->makeCollective<MyObj>();
vt::runInEpochCollective("simulateObjGroupColTSends", [&]{
auto node = theContext()->getNode();
// @note: .invoke does not work here because it doesn't create the LBStats
// context!
obj_proxy(node).send<ColProxyMsg, &MyObj::simulateObjGroupColTSends>(proxy);
});
vt::thePhase()->nextPhaseCollective();
vt::runInEpochCollective("doReduce", [&]{
for (int i = 0; i < dim1; i++) {
if (proxy(i).tryGetLocalPtr()) {
proxy(i).invoke<MyMsg, doReduce>();
}
}
});
vt::PhaseType phase = 0;
auto sd = getStatsDataForPhase(phase);
auto& comm = sd.node_comm_;
auto this_node = theContext()->getNode();
auto num_nodes = theContext()->getNumNodes();
auto prev = this_node - 1 >= 0 ? this_node - 1 : num_nodes-1;
auto op = obj_proxy.getProxy();
// Check that communication exists on the receive side as expected
for (int i = 0; i < dim1; i++) {
vt::Index1D idx{i};
if (proxy(i).tryGetLocalPtr()) {
bool found = false;
for (auto&& x : comm) {
for (auto&& y : x.second) {
auto key = y.first;
auto vol = y.second;
if (key.to_.id == idxToElmID(idx)) {
EXPECT_TRUE(key.to_.isMigratable());
EXPECT_EQ(key.to_.id, idxToElmID(idx));
EXPECT_FALSE(key.from_.isMigratable());
EXPECT_EQ(key.from_.id, vt::elm::ElmIDBits::createObjGroup(op, prev).id);
EXPECT_EQ(vol.bytes, sizeof(MyMsg) * num_sends);
EXPECT_EQ(vol.messages, num_sends);
found = true;
}
}
}
EXPECT_TRUE(found);
}
}
}
// ObjGroup -> ObjGroup, expected communication edge on send side
TEST_F(TestLBStatsComm, test_lb_stats_comm_objgroup_to_objgroup_send) {
auto obj_proxy_a = vt::theObjGroup()->makeCollective<MyObj>();
auto obj_proxy_b = vt::theObjGroup()->makeCollective<MyObj>();
vt::runInEpochCollective("simulateObjGroupObjGroupSends", [&]{
auto node = theContext()->getNode();
// @note: .invoke does not work here because it doesn't create the LBStats
// context!
obj_proxy_a(node).send<ProxyMsg, &MyObj::simulateObjGroupObjGroupSends>(
obj_proxy_b
);
});
vt::thePhase()->nextPhaseCollective();
vt::PhaseType phase = 0;
auto sd = getStatsDataForPhase(phase);
auto& comm = sd.node_comm_;
auto this_node = theContext()->getNode();
auto num_nodes = theContext()->getNumNodes();
auto next = (this_node + 1) % num_nodes;
auto opa = obj_proxy_a.getProxy();
auto opb = obj_proxy_b.getProxy();
auto ida = vt::elm::ElmIDBits::createObjGroup(opa, this_node).id;
auto idb = vt::elm::ElmIDBits::createObjGroup(opb, next).id;
// Check that communication exists on the send side as expected
bool found = false;
for (auto&& x : comm) {
for (auto&& y : x.second) {
auto key = y.first;
auto vol = y.second;
if (key.from_.id == ida /*and key.to_.id == idb*/) {
EXPECT_FALSE(key.to_.isMigratable());
EXPECT_EQ(key.from_.id, ida);
EXPECT_FALSE(key.from_.isMigratable());
EXPECT_EQ(key.to_.id, idb);
EXPECT_EQ(vol.bytes, sizeof(MyObjMsg) * num_sends);
EXPECT_EQ(vol.messages, num_sends);
found = true;
}
}
}
EXPECT_TRUE(found);
}
// Handler -> ColT, expected communication edge on receive side
TEST_F(TestLBStatsComm, test_lb_stats_comm_handler_to_col_send) {
auto range = vt::Index1D{dim1};
auto proxy = vt::makeCollection<MyCol>()
.bounds(range)
.bulkInsert()
.wait();
vt::runInEpochCollective("simulateHandlerColTSends", [&]{
auto this_node = theContext()->getNode();
auto num_nodes = theContext()->getNumNodes();
auto next = (this_node + 1) % num_nodes;
auto msg = makeMessage<ColProxyMsg>(proxy);
theMsg()->sendMsg<ColProxyMsg, simulateHandlerColTSends>(next, msg);
});
vt::thePhase()->nextPhaseCollective();
vt::runInEpochCollective("doReduce", [&]{
for (int i = 0; i < dim1; i++) {
if (proxy(i).tryGetLocalPtr()) {
proxy(i).invoke<MyMsg, doReduce>();
}
}
});
vt::PhaseType phase = 0;
auto sd = getStatsDataForPhase(phase);
auto& comm = sd.node_comm_;
auto this_node = theContext()->getNode();
auto num_nodes = theContext()->getNumNodes();
auto prev = this_node - 1 >= 0 ? this_node - 1 : num_nodes-1;
// Check that communication exists on the receive side as expected
for (int i = 0; i < dim1; i++) {
vt::Index1D idx{i};
if (proxy(i).tryGetLocalPtr()) {
bool found = false;
for (auto&& x : comm) {
for (auto&& y : x.second) {
auto key = y.first;
auto vol = y.second;
if (key.to_.id == idxToElmID(idx)) {
EXPECT_TRUE(key.to_.isMigratable());
EXPECT_EQ(key.to_.id, idxToElmID(idx));
EXPECT_FALSE(key.from_.isMigratable());
EXPECT_EQ(key.from_.id, vt::elm::ElmIDBits::createBareHandler(prev).id);
EXPECT_EQ(vol.bytes, sizeof(MyMsg) * num_sends);
EXPECT_EQ(vol.messages, num_sends);
found = true;
}
}
}
EXPECT_TRUE(found);
}
}
}
// ColT -> Handler, expected communication edge on send side
TEST_F(TestLBStatsComm, test_lb_stats_comm_col_to_handler_send) {
auto range = vt::Index1D{dim1};
auto proxy = vt::makeCollection<MyCol>()
.bounds(range)
.bulkInsert()
.wait();
vt::runInEpochCollective("simulateColTHandlerSends", [&]{
for (int i = 0; i < dim1; i++) {
if (proxy(i).tryGetLocalPtr()) {
proxy(i).invoke<MyMsg, simulateColTHandlerSends>();
}
}
});
vt::thePhase()->nextPhaseCollective();
vt::runInEpochCollective("doReduce", [&]{
for (int i = 0; i < dim1; i++) {
if (proxy(i).tryGetLocalPtr()) {
proxy(i).invoke<MyMsg, doReduce>();
}
}
});
vt::PhaseType phase = 0;
auto sd = getStatsDataForPhase(phase);
auto& comm = sd.node_comm_;
auto this_node = theContext()->getNode();
auto num_nodes = theContext()->getNumNodes();
auto next = (this_node + 1) % num_nodes;
// Check that communication exists on the send side as expected
for (int i = 0; i < dim1; i++) {
vt::Index1D idx{i};
if (proxy(i).tryGetLocalPtr()) {
bool found = false;
for (auto&& x : comm) {
for (auto&& y : x.second) {
auto key = y.first;
auto vol = y.second;
fmt::print("from={}, to={}\n", key.from_, key.to_);
if (key.from_.id == idxToElmID(idx)) {
EXPECT_TRUE(key.from_.isMigratable());
EXPECT_EQ(key.from_.id, idxToElmID(idx));
EXPECT_FALSE(key.to_.isMigratable());
EXPECT_EQ(key.to_.id, vt::elm::ElmIDBits::createBareHandler(next).id);
EXPECT_EQ(vol.bytes, sizeof(MyObjMsg) * num_sends);
EXPECT_EQ(vol.messages, num_sends);
found = true;
}
}
}
EXPECT_TRUE(found);
}
}
}
// ObjGroup -> Handler, expected communication edge on send side
TEST_F(TestLBStatsComm, test_lb_stats_comm_objgroup_to_handler_send) {
auto obj_proxy_a = vt::theObjGroup()->makeCollective<MyObj>();
vt::runInEpochCollective("simulateObjGroupHandlerSends", [&]{
auto node = theContext()->getNode();
// @note: .invoke does not work here because it doesn't create the LBStats
// context!
obj_proxy_a(node).send<MyMsg, &MyObj::simulateObjGroupHandlerSends>();
});
vt::thePhase()->nextPhaseCollective();
vt::PhaseType phase = 0;
auto sd = getStatsDataForPhase(phase);
auto& comm = sd.node_comm_;
auto this_node = theContext()->getNode();
auto num_nodes = theContext()->getNumNodes();
auto next = (this_node + 1) % num_nodes;
auto opa = obj_proxy_a.getProxy();
auto ida = vt::elm::ElmIDBits::createObjGroup(opa, this_node).id;
// Check that communication exists on the send side as expected
bool found = false;
for (auto&& x : comm) {
for (auto&& y : x.second) {
auto key = y.first;
auto vol = y.second;
if (key.from_.id == ida) {
EXPECT_FALSE(key.to_.isMigratable());
EXPECT_EQ(key.to_.id, vt::elm::ElmIDBits::createBareHandler(next).id);
EXPECT_FALSE(key.from_.isMigratable());
EXPECT_EQ(vol.bytes, sizeof(MyObjMsg) * num_sends);
EXPECT_EQ(vol.messages, num_sends);
found = true;
}
}
}
EXPECT_TRUE(found);
}
// Handler -> ObjGroup, expected communication edge on send side
TEST_F(TestLBStatsComm, test_lb_stats_comm_handler_to_objgroup_send) {
auto obj_proxy_a = vt::theObjGroup()->makeCollective<MyObj>();
vt::runInEpochCollective("simulateHandlerObjGroupSends", [&]{
auto this_node = theContext()->getNode();
auto num_nodes = theContext()->getNumNodes();
auto next = (this_node + 1) % num_nodes;
auto msg = makeMessage<ProxyMsg>(obj_proxy_a);
theMsg()->sendMsg<ProxyMsg, simulateHandlerObjGroupSends>(next, msg);
});
vt::thePhase()->nextPhaseCollective();
vt::PhaseType phase = 0;
auto sd = getStatsDataForPhase(phase);
auto& comm = sd.node_comm_;
auto this_node = theContext()->getNode();
auto num_nodes = theContext()->getNumNodes();
auto next = (this_node + 1) % num_nodes;
auto opa = obj_proxy_a.getProxy();
auto ida = vt::elm::ElmIDBits::createObjGroup(opa, next).id;
// Check that communication exists on the send side as expected
bool found = false;
for (auto&& x : comm) {
for (auto&& y : x.second) {
auto key = y.first;
auto vol = y.second;
if (key.to_.id == ida) {
EXPECT_FALSE(key.to_.isMigratable());
EXPECT_EQ(key.from_.id, vt::elm::ElmIDBits::createBareHandler(this_node).id);
EXPECT_FALSE(key.from_.isMigratable());
EXPECT_EQ(vol.bytes, sizeof(MyObjMsg) * num_sends);
EXPECT_EQ(vol.messages, num_sends);
found = true;
}
}
}
EXPECT_TRUE(found);
}
// Handler -> Handler, expected communication edge on send side
TEST_F(TestLBStatsComm, test_lb_stats_comm_handler_to_handler_send) {
vt::runInEpochCollective("simulateHandlerHandlerSends", [&]{
auto this_node = theContext()->getNode();
auto num_nodes = theContext()->getNumNodes();
auto next = (this_node + 1) % num_nodes;
auto msg = makeMessage<MyMsg>();
theMsg()->sendMsg<MyMsg, simulateHandlerHandlerSends>(next, msg);
});
vt::thePhase()->nextPhaseCollective();
vt::PhaseType phase = 0;
auto sd = getStatsDataForPhase(phase);
auto& comm = sd.node_comm_;
auto this_node = theContext()->getNode();
auto num_nodes = theContext()->getNumNodes();
auto next = (this_node + 1) % num_nodes;
auto ida = vt::elm::ElmIDBits::createBareHandler(next).id;
auto idb = vt::elm::ElmIDBits::createBareHandler(this_node).id;
// Check that communication exists on the send side as expected
bool found = false;
for (auto&& x : comm) {
for (auto&& y : x.second) {
auto key = y.first;
auto vol = y.second;
if (key.to_.id == ida and key.from_.id == idb) {
EXPECT_FALSE(key.to_.isMigratable());
EXPECT_FALSE(key.from_.isMigratable());
EXPECT_GE(vol.bytes, sizeof(MyObjMsg) * num_sends);
EXPECT_GE(vol.messages, num_sends);
found = true;
}
}
}
EXPECT_TRUE(found);
}
} /* end anon namespace */
}}}} // end namespace vt::tests::unit::comm
#endif
| 32.55526 | 85 | 0.635282 | rbuch |
c5f31b69144585a176889d448ff7d494a236d747 | 821 | cpp | C++ | judges/codeforces/exercises/new_year_and_north_pole.cpp | eduardonunes2525/competitive-programming | 0f6bdc573b4d03d1ed20a2b77ec5388dca1ee47b | [
"MIT"
] | null | null | null | judges/codeforces/exercises/new_year_and_north_pole.cpp | eduardonunes2525/competitive-programming | 0f6bdc573b4d03d1ed20a2b77ec5388dca1ee47b | [
"MIT"
] | 1 | 2018-10-17T11:53:02.000Z | 2018-10-17T11:54:42.000Z | judges/codeforces/exercises/new_year_and_north_pole.cpp | eduardonunes2525/competitive-programming | 0f6bdc573b4d03d1ed20a2b77ec5388dca1ee47b | [
"MIT"
] | 1 | 2018-10-17T12:14:04.000Z | 2018-10-17T12:14:04.000Z | #include<bits/stdc++.h>
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define what_is(x) cerr << #x << " is " << x << endl
#define REP(i,a,b) for (int i = a; i <= b; i++)
#define endl "\n"
using namespace std;
using ii = pair<int, int>;
using ll = long long;
#define xmax 40000LL
#define ymax 20000LL
int main(){
IOS;
ll n; cin >> n;
ll t; string s, last;
ll y = ymax;
bool b = true;
while(n--){
cin >> t >> s;
if((y == ymax and s!="South") or (y == 0 and s!="North")) { b = false; }
if(s == "South"){
y -= t;
if(y < 0) b = false;
}
else if(s == "North"){
y += t;
if(y > ymax) b = false;
}
}
((y==ymax) and b) ? cout << "YES" << endl : cout << "NO" << endl;
return 0;
}
| 21.051282 | 80 | 0.461632 | eduardonunes2525 |
c5f60941a7a64a234edec73f2130cb22451ed8c5 | 6,796 | cc | C++ | tests/native/cxx_object.cc | Natus/natus | 4074619edd45f1bb62a5561d08a64e9960b3d9e8 | [
"MIT"
] | 1 | 2015-11-05T03:19:22.000Z | 2015-11-05T03:19:22.000Z | tests/native/cxx_object.cc | Natus/natus | 4074619edd45f1bb62a5561d08a64e9960b3d9e8 | [
"MIT"
] | null | null | null | tests/native/cxx_object.cc | Natus/natus | 4074619edd45f1bb62a5561d08a64e9960b3d9e8 | [
"MIT"
] | null | null | null | #include "test.hh"
class TestClass : public Class {
virtual Value
del(Value& obj, Value& name)
{
assert(obj.borrowCValue());
assert(name.borrowCValue());
assert(obj.isObject());
assert(name.getType() == obj.getPrivateName<size_t>("type"));
return obj.getPrivateName<Value>("retval");
}
virtual Value
get(Value& obj, Value& name)
{
assert(obj.borrowCValue());
assert(name.borrowCValue());
assert(obj.isObject());
assert(name.getType() == obj.getPrivateName<size_t>("type"));
return obj.getPrivateName<Value>("retval");
}
virtual Value
set(Value& obj, Value& name, Value& value)
{
assert(obj.borrowCValue());
assert(name.borrowCValue());
assert(value.borrowCValue());
assert(obj.isObject());
assert(name.getType() == obj.getPrivateName<size_t>("type"));
return obj.getPrivateName<Value>("retval");
}
virtual Value
enumerate(Value& obj)
{
assert(obj.borrowCValue());
assert(obj.isObject());
return obj.getPrivateName<Value>("retval");
}
virtual Value
call(Value& obj, Value& ths, Value& args)
{
assert(obj.borrowCValue());
assert(ths.borrowCValue());
assert(args.borrowCValue());
assert(obj.isObject());
assert(args.isArray());
if (strcmp(obj.getEngineName(), "v8")) // Work around a bug in v8
assert(ths.isObject() || ths.isUndefined());
if (args.get("length").to<int>() == 0)
return obj.getPrivateName<Value>("retval");
return args[0];
}
virtual Class::Hooks
getHooks()
{
return Class::HookAll;
}
};
int
doTest(Value& global)
{
assert(!global.set("x", global.newObject(new TestClass())).isException());
Value x = global.get("x");
assert(x.isObject());
//// Check for bypass
x.setPrivateName<Value>("retval", NULL); // Ensure NULL
// Number, native
assert(x.setPrivateName("type", (void*) Value::TypeNumber));
assert(!x.set(0, 17).isException());
assert(!x.get(0).isException());
assert(x.get(0).to<int>() == 17);
assert(!x.del(0).isException());
assert(x.get(0).isUndefined());
// Number, eval
assert(!global.evaluate("x[0] = 17;").isException());
assert(!global.evaluate("x[0];").isException());
assert(global.evaluate("x[0];").to<int>() == 17);
assert(!global.evaluate("delete x[0];").isException());
assert(global.evaluate("x[0];").isUndefined());
// String, native
assert(x.setPrivateName("type", (void*) Value::TypeString));
assert(!x.set("foo", 17).isException());
assert(!x.get("foo").isException());
assert(x.get("foo").to<int>() == 17);
assert(!x.del("foo").isException());
assert(x.get("foo").isUndefined());
// String, eval
assert(!global.evaluate("x['foo'] = 17;").isException());
assert(!global.evaluate("x['foo'];").isException());
assert(global.evaluate("x['foo'];").to<int>() == 17);
assert(!global.evaluate("delete x['foo'];").isException());
assert(global.evaluate("x['foo'];").isUndefined());
//// Check for exception
assert(x.setPrivateName<Value>("retval", global.newString("error").toException()));
// Number, native
assert(x.setPrivateName("type", (void*) Value::TypeNumber));
assert(x.del(0).isException());
assert(x.get(0).isException());
assert(x.set(0, 0).isException());
// Number, eval
assert(global.evaluate("delete x[0];").isException());
assert(global.evaluate("x[0];").isException());
assert(global.evaluate("x[0] = 0;").isException());
// String, native
assert(x.setPrivateName("type", (void*) Value::TypeString));
assert(x.del("foo").isException());
assert(x.get("foo").isException());
assert(x.set("foo", 0).isException());
// String, eval
assert(global.evaluate("delete x['foo'];").isException());
assert(global.evaluate("x['foo'];").isException());
assert(global.evaluate("x['foo'] = 0;").isException());
//// Check for intercept
assert(x.setPrivateName<Value>("retval", global.newBoolean(true)));
// Number, native
assert(x.setPrivateName("type", (void*) Value::TypeNumber));
assert(!x.del(0).isException());
assert(x.get(0).isBoolean());
assert(x.get(0).to<bool>());
assert(!x.set(0, 0).isException());
// Number, eval
assert(!global.evaluate("delete x[0];").isException());
assert(global.evaluate("x[0];").isBoolean());
assert(global.evaluate("x[0];").to<bool>());
assert(!global.evaluate("x[0] = 0;").isException());
// String, native
assert(x.setPrivateName("type", (void*) Value::TypeString));
assert(!x.del("foo").isException());
assert(x.get("foo").isBoolean());
assert(x.get("foo").to<bool>());
assert(!x.set("foo", 0).isException());
// String, eval
assert(!global.evaluate("delete x['foo'];").isException());
assert(global.evaluate("x['foo'];").isBoolean());
assert(global.evaluate("x['foo'];").to<bool>());
assert(!global.evaluate("x['foo'] = 0;").isException());
//// Check for successful calls
// Call from C++
Value y = global.call("x", global.newArray().push(123));
assert(!y.isException());
assert(y.isNumber());
assert(y.to<int>() == 123);
// New from C++
y = global.callNew("x", global.newArray().push(global.newObject()));
assert(!y.isException());
assert(y.isObject());
// Call from JS
y = global.evaluate("x(123);");
assert(!y.isException());
assert(y.isNumber());
assert(y.to<int>() == 123);
// New from JS
y = global.evaluate("new x({});");
assert(!y.isException());
assert(y.isObject());
//// Check for exception calls
assert(x.setPrivateName<Value>("retval", global.newString("error").toException()));
// Call from C++
y = global.call("x");
assert(y.isString());
assert(y.isException());
// New from C++
y = global.callNew("x");
assert(y.isString());
assert(y.isException());
// Call from JS
y = global.evaluate("x();");
assert(y.isString());
assert(y.isException());
// New from JS
y = global.evaluate("new x();");
assert(y.isString());
assert(y.isException());
//// Check for NULL calls
assert(x.setPrivateName<Value>("retval", NULL));
// Ensure NULL
// Call from C++
y = global.call("x");
assert(y.isUndefined());
assert(y.isException());
// New from C++
y = global.callNew("x");
assert(y.isUndefined());
assert(y.isException());
// Call from JS
y = global.evaluate("x();");
assert(y.isUndefined());
assert(y.isException());
// New from JS
y = global.evaluate("new x();");
assert(y.isUndefined());
assert(y.isException());
// Enumerate
assert(x.setPrivateName<Value>("retval", x.newArray().push(5).push(10)));
y = x.enumerate();
assert(y.isArray());
assert(y.get("length").to<int>() == 2);
assert(y.get(0).to<int>() == 5);
assert(y.get(1).to<int>() == 10);
// Cleanup
assert(!global.del("x").isException());
assert(global.get("x").isUndefined());
return 0;
}
| 31.031963 | 85 | 0.626986 | Natus |
c5f8bff9b3bc4e32bb471e125ea7b44b7e064ef4 | 12,408 | cpp | C++ | OGLFrameworkLib/volumeScene/TransferFunctionGUI.cpp | dasmysh/OGLFrameworkLib_uulm | 36fd5e65d7fb028a07f9d4f95c543f27a23a7d24 | [
"MIT"
] | null | null | null | OGLFrameworkLib/volumeScene/TransferFunctionGUI.cpp | dasmysh/OGLFrameworkLib_uulm | 36fd5e65d7fb028a07f9d4f95c543f27a23a7d24 | [
"MIT"
] | null | null | null | OGLFrameworkLib/volumeScene/TransferFunctionGUI.cpp | dasmysh/OGLFrameworkLib_uulm | 36fd5e65d7fb028a07f9d4f95c543f27a23a7d24 | [
"MIT"
] | 1 | 2019-11-14T06:24:26.000Z | 2019-11-14T06:24:26.000Z | /**
* @file TransferFunctionGUI.cpp
* @author Sebastian Maisch <[email protected]>
* @date 2015.08.24
*
* @brief Definition of the transfer function GUI.
*/
#include "TransferFunctionGUI.h"
#include "app/ApplicationBase.h"
#include "gfx/glrenderer/GLTexture.h"
#include "gfx/glrenderer/GLUniformBuffer.h"
#include <glm/gtc/matrix_transform.hpp>
#include "app/GLWindow.h"
#include "gfx/glrenderer/ScreenQuadRenderable.h"
#include <imgui.h>
#include <boost/algorithm/string/predicate.hpp>
#include <GLFW/glfw3.h>
namespace cgu {
TransferFunctionGUI::TransferFunctionGUI(const glm::vec2& boxMin, const glm::vec2& boxMax, ApplicationBase* app) :
rectMin(boxMin), rectMax(boxMax),
quad(nullptr),
quadTex(nullptr),
tfTex(nullptr),
screenAlignedProg(std::move(app->GetGPUProgramManager()->GetResource("shader/gui/tfRenderGUI.vp|shader/gui/tfRenderGUI.fp"))),
screenAlignedTextureUniform(screenAlignedProg->GetUniformLocation("guiTex")),
selection(-1),
draggingSelection(false),
lastButtonAction(0),
tfProgram(std::move(app->GetGPUProgramManager()->GetResource("shader/gui/tfPicker.vp|shader/gui/tfPicker.fp"))),
orthoUBO(new GLUniformBuffer("tfOrthoProjection", sizeof(OrthoProjectionBuffer), app->GetUBOBindingPoints())),
tfVBO(0)
{
screenAlignedProg->BindUniformBlock("tfOrthoProjection", *app->GetUBOBindingPoints());
tfProgram->BindUniformBlock("tfOrthoProjection", *app->GetUBOBindingPoints());
std::array<glm::vec2, 4> quadVerts;
quadVerts[0] = glm::vec2(0.0f);
quadVerts[1] = glm::vec2(0.0f, 1.0f);
quadVerts[2] = glm::vec2(1.0f, 0.0f);
quadVerts[3] = glm::vec2(1.0f, 1.0f);
quad.reset(new ScreenQuadRenderable(quadVerts, screenAlignedProg));
// Create default control points for TF
tf::ControlPoint p0, p1;
p0.SetColor(glm::vec3(0));
p0.SetPos(glm::vec2(0));
p1.SetColor(glm::vec3(1));
p1.SetPos(glm::vec2(1));
tf_.InsertControlPoint(p0);
tf_.InsertControlPoint(p1);
// Create texture and update it
tfTex.reset(new GLTexture(TEX_RES, TextureDescriptor(32, GL_RGBA8, GL_RGBA, GL_FLOAT)));
UpdateTexture();
// Create BG texture
std::vector<glm::vec4> texContent(TEX_RES * (TEX_RES / 2), glm::vec4(0.2f));
quadTex.reset(new GLTexture(TEX_RES, TEX_RES / 2, TextureDescriptor(32, GL_RGBA8, GL_RGBA, GL_FLOAT), texContent.data()));
UpdateTF(true);
Resize(glm::uvec2(app->GetWindow()->GetWidth(), app->GetWindow()->GetHeight()));
}
TransferFunctionGUI::~TransferFunctionGUI() = default;
void TransferFunctionGUI::Resize(const glm::uvec2& screenSize)
{
auto left = -rectMin.x / (rectMax.x - rectMin.x);
auto right = (static_cast<float>(screenSize.x) - rectMin.x) / (rectMax.x - rectMin.x);
auto bottom = (static_cast<float>(screenSize.y) - rectMin.y) / (rectMax.y - rectMin.y);
auto top = -rectMin.y / (rectMax.y - rectMin.y);
orthoBuffer.orthoMatrix = glm::ortho(left, right, bottom, top, 1.0f, -1.0f);
orthoUBO->UploadData(0, sizeof(OrthoProjectionBuffer), &orthoBuffer);
}
void TransferFunctionGUI::Draw()
{
glDisable(GL_DEPTH_TEST);
glDepthMask(GL_FALSE);
orthoUBO->BindBuffer();
screenAlignedProg->UseProgram();
quadTex->ActivateTexture(GL_TEXTURE0);
screenAlignedProg->SetUniform(screenAlignedTextureUniform, 0);
quad->Draw();// RenderGeometry();
// draw
glPointSize(0.5f * pickRadius);
tfProgram->UseProgram();
attribBind->EnableVertexAttributeArray();
// draw function
glDrawArrays(GL_LINE_STRIP, 0, static_cast<GLsizei>((tf_.points().size() + 2)));
// draw points
glDrawArrays(GL_POINTS, 1, static_cast<GLsizei>(tf_.points().size()));
// draw selection
if (selection != -1) {
glPointSize(0.8f * pickRadius);
glDrawArrays(GL_POINTS, selection + 1, static_cast<GLsizei>(1));
}
attribBind->DisableVertexAttributeArray();
glDepthMask(GL_TRUE);
glEnable(GL_DEPTH_TEST);
ImGui::SetNextWindowSize(ImVec2(rectMax.x - rectMin.x, 115), ImGuiSetCond_FirstUseEver);
ImGui::SetNextWindowPos(ImVec2(rectMin.x, rectMax.y + 10.0f), ImGuiSetCond_FirstUseEver);
ImGui::Begin("PickColor");
if (selection != -1) {
auto selectionColor = tf_.points()[selection].GetColor();
if (ImGui::ColorEdit3("Point Color", reinterpret_cast<float*>(&selectionColor))) {
tf_.points()[selection].SetColor(selectionColor);
UpdateTF();
}
}
std::array<char, 1024> tmpFilename;
auto lastPos = saveTFFilename.copy(tmpFilename.data(), 1023, 0);
tmpFilename[lastPos] = '\0';
if (ImGui::InputText("TF Filename", tmpFilename.data(), tmpFilename.size())) {
saveTFFilename = tmpFilename.data();
}
if (ImGui::Button("Save TF")) {
SaveTransferFunction();
}
if (ImGui::Button("Load TF")) {
LoadTransferFunction(saveTFFilename);
}
if (ImGui::Button("Init TF High Freq")) {
InitTF(1.0f / 16.0f);
}
if (ImGui::Button("Init TF Low Freq")) {
InitTF(1.0f / 4.0f);
}
ImGui::End();
}
void TransferFunctionGUI::LoadTransferFunction(const std::string& filename)
{
saveTFFilename = filename;
tf_.LoadFromFile(saveTFFilename + ".tf");
UpdateTF();
}
const std::string& TransferFunctionGUI::SaveTransferFunction() const
{
tf_.SaveToFile(saveTFFilename + ".tf");
return saveTFFilename;
}
bool TransferFunctionGUI::HandleMouse(int button, int action, int mods, float mouseWheelDelta, GLWindow* sender)
{
auto handled = false;
if (selection == -1) draggingSelection = false;
// if (buttonAction == 0 && !draggingSelection) return handled;
glm::vec2 screenSize(static_cast<float>(sender->GetWidth()), static_cast<float>(sender->GetHeight()));
auto pickSize = glm::vec2(pickRadius) / screenSize;
auto mouseCoords = sender->GetMousePosition();
// calculate relative points
auto relCoords = (mouseCoords - rectMin) / (rectMax - rectMin);
relCoords.y = 1.0f - relCoords.y;
// relCoords.y = glm::log((relCoords.y * (scaleBase - 1.0f)) + 1.0f) / glm::log(scaleBase);
relCoords.y = (glm::pow(scaleBase, relCoords.y) - 1.0f) / (scaleBase - 1.0f);
if (draggingSelection) {
relCoords = glm::clamp(relCoords, glm::vec2(0.0f), glm::vec2(1.0f));
// update selected point position
selection = tf_.SetPosition(selection, relCoords);
UpdateTF();
// check for drop
if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_RELEASE) draggingSelection = false;
return true;
}
const auto SEL_RAD2 = (pickRadius / (rectMax.x - rectMin.x)) * (pickRadius / (rectMax.y - rectMin.y));
if (relCoords.x >= -SEL_RAD2 && relCoords.y >= -SEL_RAD2 && relCoords.x <= 1.0f + SEL_RAD2 && relCoords.y <= 1.0f + SEL_RAD2)
{
// left click: select point or start dragging
if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) {
auto oldSelection = selection;
if (SelectPoint(relCoords, pickSize) && selection != -1 && selection == oldSelection) draggingSelection = true;
}
// right click: delete old point
if (button == GLFW_MOUSE_BUTTON_RIGHT && action == GLFW_PRESS && RemovePoint(relCoords, pickSize)) {
UpdateTF();
}
// middle click: new point
if (button == GLFW_MOUSE_BUTTON_MIDDLE && action == GLFW_PRESS && AddPoint(relCoords, pickSize)) {
UpdateTF();
}
handled = true;
}
return handled;
}
bool TransferFunctionGUI::SelectPoint(const glm::vec2& position, const glm::vec2&)
{
selection = GetControlPoint(position);
return selection != -1;
}
bool TransferFunctionGUI::AddPoint(const glm::vec2& position, const glm::vec2&)
{
auto i = GetControlPoint(position);
selection = i;
if (i == -1 && Overlap(position)) {
tf::ControlPoint p;
p.SetPos(position);
p.SetColor(glm::vec3(tf_.RGBA(p.val)));
tf_.InsertControlPoint(p);
selection = GetControlPoint(position);
draggingSelection = false;
return true;
}
draggingSelection = true;
return false;
}
bool TransferFunctionGUI::RemovePoint(const glm::vec2& position, const glm::vec2&)
{
auto i = GetControlPoint(position);
if (i > -1) {
tf_.RemoveControlPoint(i);
selection = -1;
return true;
}
return false;
}
void TransferFunctionGUI::InitTF(float freq)
{
tf_.InitWithFreqRGBA(freq / 2.0f, 1.0f - freq / 2.0f, 1.0f / ((1.0f / freq) + 1.0f), 0.1f);
UpdateTF();
}
void TransferFunctionGUI::LoadTransferFunctionFromFile(const std::string& filename)
{
if (boost::algorithm::ends_with(filename, ".tf")) saveTFFilename = filename.substr(0, filename.find_last_of("."));
else saveTFFilename = filename;
tf_.LoadFromFile(saveTFFilename + ".tf");
UpdateTF();
}
void TransferFunctionGUI::UpdateTF(bool createVAO)
{
if (createVAO) tfVBO = std::move(BufferRAII());
OGL_CALL(glBindBuffer, GL_ARRAY_BUFFER, tfVBO);
OGL_CALL(glBufferData, GL_ARRAY_BUFFER, (tf_.points().size() + 2) * sizeof(tf::ControlPoint),
nullptr, GL_DYNAMIC_DRAW);
auto tmpPoints = tf_.points();
for (auto& pt : tmpPoints) {
auto pos = pt.GetPos();
pos.y = glm::log((pos.y * (scaleBase - 1.0f)) + 1.0f) / glm::log(scaleBase);
pt.SetPos(pos);
}
tf::ControlPoint first, last;
first = tmpPoints[0];
first.SetValue(0.0f);
last = tmpPoints.back();
last.SetValue(1.0f);
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(tf::ControlPoint), &first);
glBufferSubData(GL_ARRAY_BUFFER, sizeof(tf::ControlPoint), tmpPoints.size() * sizeof(tf::ControlPoint), tmpPoints.data());
glBufferSubData(GL_ARRAY_BUFFER, (tmpPoints.size() + 1) * sizeof(tf::ControlPoint), sizeof(tf::ControlPoint), &last);
if (createVAO) {
auto loc = tfProgram->GetAttributeLocations({ "value", "color" });
attribBind = tfProgram->CreateVertexAttributeArray(tfVBO, 0);
attribBind->StartAttributeSetup();
attribBind->AddVertexAttribute(loc[0], 1, GL_FLOAT, GL_FALSE, sizeof(tf::ControlPoint), 0);
attribBind->AddVertexAttribute(loc[1], 4, GL_FLOAT, GL_FALSE, sizeof(tf::ControlPoint), sizeof(float));
attribBind->EndAttributeSetup();
} else {
attribBind->UpdateVertexAttributes();
}
UpdateTexture();
}
void TransferFunctionGUI::UpdateTexture() const
{
std::array<glm::vec4, TEX_RES> texData;
tf_.CreateTextureData(texData.data(), TEX_RES);
tfTex->SetData(texData.data());
}
// Gets an index to a control point if found within radii of mouse_pos
int TransferFunctionGUI::GetControlPoint(const glm::vec2& mouse_pos)
{
const auto SEL_RAD2 = (pickRadius / (rectMax.x - rectMin.x)) * (pickRadius / (rectMax.y - rectMin.y));
auto curSelectDist2 = SEL_RAD2 * 2.0f;
auto curSel = -1;
for (auto i = 0; i < static_cast<int>(tf_.points().size()); ++i) {
auto p = tf_.points()[i].GetPos();
// p.y = 1.f - p.y;
// glm::vec2 pos = p * (rectMax - rectMin) + rectMin;
auto d = mouse_pos - p;
auto dist2 = d.x * d.x + d.y * d.y;
if (dist2 < SEL_RAD2 && dist2 < curSelectDist2) {
curSelectDist2 = dist2;
curSel = i;
}
}
return curSel;
}
}
| 38.178462 | 134 | 0.603482 | dasmysh |
68080c70acdabd1d3e5137466c037c8d81a2acfb | 1,424 | cpp | C++ | engine/src/common/pixelboost/input/joystickManager.cpp | pixelballoon/pixelboost | 085873310050ce62493df61142b7d4393795bdc2 | [
"MIT"
] | 6 | 2015-04-21T11:30:52.000Z | 2020-04-29T00:10:04.000Z | engine/src/common/pixelboost/input/joystickManager.cpp | pixelballoon/pixelboost | 085873310050ce62493df61142b7d4393795bdc2 | [
"MIT"
] | null | null | null | engine/src/common/pixelboost/input/joystickManager.cpp | pixelballoon/pixelboost | 085873310050ce62493df61142b7d4393795bdc2 | [
"MIT"
] | null | null | null | #include "pixelboost/input/joystickManager.h"
using namespace pb;
JoystickHandler::JoystickHandler()
{
}
JoystickHandler::~JoystickHandler()
{
}
bool JoystickHandler::OnAxisChanged(int joystick, int stick, int axis, float value)
{
return false;
}
bool JoystickHandler::OnButtonDown(int joystick, int button)
{
return false;
}
bool JoystickHandler::OnButtonUp(int joystick, int button)
{
return false;
}
JoystickManager::JoystickManager()
{
}
JoystickManager::~JoystickManager()
{
}
void JoystickManager::OnAxisChanged(int joystick, int stick, int axis, float value)
{
UpdateHandlers();
for (HandlerList::iterator it = _Handlers.begin(); it != _Handlers.end(); ++it)
{
if (dynamic_cast<JoystickHandler*>(*it)->OnAxisChanged(joystick, stick, axis, value))
return;
}
}
void JoystickManager::OnButtonDown(int joystick, int button)
{
UpdateHandlers();
for (HandlerList::iterator it = _Handlers.begin(); it != _Handlers.end(); ++it)
{
if (dynamic_cast<JoystickHandler*>(*it)->OnButtonDown(joystick, button))
return;
}
}
void JoystickManager::OnButtonUp(int joystick, int button)
{
UpdateHandlers();
for (HandlerList::iterator it = _Handlers.begin(); it != _Handlers.end(); ++it)
{
if (dynamic_cast<JoystickHandler*>(*it)->OnButtonUp(joystick, button))
return;
}
}
| 19.777778 | 93 | 0.662219 | pixelballoon |
680d20a5390f605ac39b267c0f27585c472f45f7 | 1,805 | cpp | C++ | unittest/energy.cpp | thanhndv212/pinocchio | 3b4d272bf4e8a231954b71201ee7e0963c944aef | [
"BSD-2-Clause-FreeBSD"
] | 716 | 2015-03-30T16:26:45.000Z | 2022-03-30T12:26:58.000Z | unittest/energy.cpp | thanhndv212/pinocchio | 3b4d272bf4e8a231954b71201ee7e0963c944aef | [
"BSD-2-Clause-FreeBSD"
] | 1,130 | 2015-02-21T17:30:44.000Z | 2022-03-30T09:06:22.000Z | unittest/energy.cpp | thanhndv212/pinocchio | 3b4d272bf4e8a231954b71201ee7e0963c944aef | [
"BSD-2-Clause-FreeBSD"
] | 239 | 2015-02-05T14:15:14.000Z | 2022-03-14T23:51:47.000Z | //
// Copyright (c) 2016-2020 CNRS INRIA
//
#include "pinocchio/algorithm/energy.hpp"
#include "pinocchio/algorithm/crba.hpp"
#include "pinocchio/algorithm/joint-configuration.hpp"
#include "pinocchio/algorithm/center-of-mass.hpp"
#include "pinocchio/parsers/sample-models.hpp"
#include <boost/test/unit_test.hpp>
#include <boost/utility/binary.hpp>
#include <boost/test/floating_point_comparison.hpp>
BOOST_AUTO_TEST_SUITE ( BOOST_TEST_MODULE )
BOOST_AUTO_TEST_CASE(test_kinetic_energy)
{
using namespace Eigen;
using namespace pinocchio;
pinocchio::Model model;
pinocchio::buildModels::humanoidRandom(model);
pinocchio::Data data(model);
const VectorXd qmax = VectorXd::Ones(model.nq);
VectorXd q = randomConfiguration(model,-qmax,qmax);
VectorXd v = VectorXd::Ones(model.nv);
data.M.fill(0); crba(model,data,q);
data.M.triangularView<Eigen::StrictlyLower>()
= data.M.transpose().triangularView<Eigen::StrictlyLower>();
double kinetic_energy_ref = 0.5 * v.transpose() * data.M * v;
double kinetic_energy = computeKineticEnergy(model, data, q, v);
BOOST_CHECK_SMALL(kinetic_energy_ref - kinetic_energy, 1e-12);
}
BOOST_AUTO_TEST_CASE(test_potential_energy)
{
using namespace Eigen;
using namespace pinocchio;
pinocchio::Model model;
pinocchio::buildModels::humanoidRandom(model);
pinocchio::Data data(model), data_ref(model);
const VectorXd qmax = VectorXd::Ones(model.nq);
VectorXd q = randomConfiguration(model,-qmax,qmax);
double potential_energy = computePotentialEnergy(model, data, q);
centerOfMass(model,data_ref,q);
double potential_energy_ref = -data_ref.mass[0] * (data_ref.com[0].dot(model.gravity.linear()));
BOOST_CHECK_SMALL(potential_energy_ref - potential_energy, 1e-12);
}
BOOST_AUTO_TEST_SUITE_END()
| 29.112903 | 98 | 0.754017 | thanhndv212 |
680e090513b5ca735290d816d96ce46941a37677 | 1,317 | hpp | C++ | iOS/G3MiOSSDK/Commons/JSON/JSONBaseObject.hpp | AeroGlass/g3m | a21a9e70a6205f1f37046ae85dafc6e3bfaeb917 | [
"BSD-2-Clause"
] | null | null | null | iOS/G3MiOSSDK/Commons/JSON/JSONBaseObject.hpp | AeroGlass/g3m | a21a9e70a6205f1f37046ae85dafc6e3bfaeb917 | [
"BSD-2-Clause"
] | null | null | null | iOS/G3MiOSSDK/Commons/JSON/JSONBaseObject.hpp | AeroGlass/g3m | a21a9e70a6205f1f37046ae85dafc6e3bfaeb917 | [
"BSD-2-Clause"
] | null | null | null | //
// JSONBaseObject.hpp
// G3MiOSSDK
//
// Created by Oliver Koehler on 17/09/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#ifndef G3MiOSSDK_JSONBaseObject
#define G3MiOSSDK_JSONBaseObject
class JSONObject;
class JSONArray;
class JSONBoolean;
class JSONNumber;
class JSONString;
class JSONNull;
class JSONVisitor;
#include <string>
class JSONBaseObject {
public:
static JSONBaseObject* deepCopy(const JSONBaseObject* object) {
return (object == NULL) ? NULL : object->deepCopy();
}
static const std::string toString(const JSONBaseObject* object) {
return (object == NULL) ? "null" : object->toString();
}
virtual ~JSONBaseObject() {
}
virtual const JSONObject* asObject() const;
virtual const JSONArray* asArray() const;
virtual const JSONBoolean* asBoolean() const;
virtual const JSONNumber* asNumber() const;
virtual const JSONString* asString() const;
virtual const JSONNull* asNull() const;
virtual JSONBaseObject* deepCopy() const = 0;
virtual const std::string description() const = 0;
//#ifdef JAVA_CODE
// @Override
// public String toString() {
// return description();
// }
//#endif
virtual void acceptVisitor(JSONVisitor* visitor) const = 0;
virtual const std::string toString() const = 0;
};
#endif
| 20.578125 | 67 | 0.707669 | AeroGlass |
680e8a0dcdf05979bd7192591cfa4ecbf8dae8f3 | 1,626 | cpp | C++ | Client/chat.cpp | edoblette/QtChat | 154db25b97b2420a13b15993d1b4d0ee7b23c160 | [
"MIT"
] | null | null | null | Client/chat.cpp | edoblette/QtChat | 154db25b97b2420a13b15993d1b4d0ee7b23c160 | [
"MIT"
] | null | null | null | Client/chat.cpp | edoblette/QtChat | 154db25b97b2420a13b15993d1b4d0ee7b23c160 | [
"MIT"
] | null | null | null | /**
* CLIENT SIDE
* Projet Reseau
* @teacher Pablo Rauzy <[email protected]> <https://pablo.rauzy.name/teaching.html#rmpp>
*
* @autor Edgar Oblette <[email protected]>
* @collegues: Lina Tlemcem
* Nourdine ---
*
* 21/04/2019
*/
#include "ui_chat.h"
#include "eventshandler.hpp"
// ne pas remplir name, si chat public
chat::chat(QWidget *parent, EventHandler * addrEventHandler, std::string name ) :
QWidget(parent),
ui(new Ui::chat)
{
ui->setupUi(this);
pcEventHandler = addrEventHandler;
pcEventHandler->set_chat(this, name);
_destName = name;
}
chat::~chat()
{
delete ui;
}
void chat::displayMsg(std::string message){
QString qmessage = QString::fromStdString(message);
//ui->ui_messageStream->append("good !");
QPlainTextEdit *myTextEdit = ui->ui_messageStream;
myTextEdit->moveCursor (QTextCursor::End);
myTextEdit->insertPlainText(qmessage+"\n");
}
void chat::on_ui_messageSend_clicked()
{
std::string message = ui->ui_messageEdit->text().toStdString();
if(!message.empty()){
ui->ui_messageEdit->clear();
if (!_destName.empty()){ // Message prive
std::cout << "message prive" << std::endl;
pcEventHandler->SendingMessage("PRV " + _destName + " " + message);
displayMsg("Vous : " + message);
}
/* Pas implemente ici dans cette version
else { // Message public
std::cout << "message public" << std::endl;
pcEventHandler->SendingMessage("MSG " + message);
}
*/
}
}
| 27.1 | 85 | 0.599631 | edoblette |
6810b9e013996f7d618e92ad385c6ffc122fb955 | 601 | cpp | C++ | Analysis/src/AlThrust.cpp | gganis/AlphappLite | e52a184c2d39a3acdd6ff09d1d61bcfca7807460 | [
"Apache-2.0"
] | null | null | null | Analysis/src/AlThrust.cpp | gganis/AlphappLite | e52a184c2d39a3acdd6ff09d1d61bcfca7807460 | [
"Apache-2.0"
] | null | null | null | Analysis/src/AlThrust.cpp | gganis/AlphappLite | e52a184c2d39a3acdd6ff09d1d61bcfca7807460 | [
"Apache-2.0"
] | null | null | null | //////////////////////////////////////////////////////////
// implementation of the AlThrust class methods
//
// Author : M. Hoerndl
//
///////////////////////////////////////////////////////////
#include "AlThrust.h"
// default constructor : has to do something,
// since it is not created out of qvec
AlThrust::AlThrust() {}
// copy constructor :Everything is set by the QvecBase copy constructor
AlThrust::AlThrust(const AlThrust& oldT):QvecBase(oldT) {}
TVector3 AlThrust::getThrustDirection() const
{ return A4V().Vect(); }
float AlThrust::getThrustValue() const
{ return A4V().E(); }
| 24.04 | 71 | 0.572379 | gganis |
68122067b1d2352555bae044246215ae359135a8 | 3,992 | cpp | C++ | Code/Engine/GameEngine/Physics/Implementation/ClothSheetSimulator.cpp | Tekh-ops/ezEngine | d6a5887d8709f267bf8f2943ef15054e29f6d3d5 | [
"MIT"
] | 703 | 2015-03-07T15:30:40.000Z | 2022-03-30T00:12:40.000Z | Code/Engine/GameEngine/Physics/Implementation/ClothSheetSimulator.cpp | Tekh-ops/ezEngine | d6a5887d8709f267bf8f2943ef15054e29f6d3d5 | [
"MIT"
] | 233 | 2015-01-11T16:54:32.000Z | 2022-03-19T18:00:47.000Z | Code/Engine/GameEngine/Physics/Implementation/ClothSheetSimulator.cpp | Tekh-ops/ezEngine | d6a5887d8709f267bf8f2943ef15054e29f6d3d5 | [
"MIT"
] | 101 | 2016-10-28T14:05:10.000Z | 2022-03-30T19:00:59.000Z | #include <GameEngine/GameEnginePCH.h>
#include <Foundation/SimdMath/SimdConversion.h>
#include <GameEngine/Physics/ClothSheetSimulator.h>
void ezClothSimulator::SimulateCloth(const ezTime& tDiff)
{
m_leftOverTimeStep += tDiff;
constexpr ezTime tStep = ezTime::Seconds(1.0 / 60.0);
const ezSimdFloat tStepSqr = static_cast<float>(tStep.GetSeconds() * tStep.GetSeconds());
while (m_leftOverTimeStep >= tStep)
{
SimulateStep(tStepSqr, 32, m_vSegmentLength.x);
m_leftOverTimeStep -= tStep;
}
}
void ezClothSimulator::SimulateStep(const ezSimdFloat tDiffSqr, ezUInt32 uiMaxIterations, ezSimdFloat fAllowedError)
{
if (m_Nodes.GetCount() < 4)
return;
UpdateNodePositions(tDiffSqr);
// repeatedly apply the distance constraint, until the overall error is low enough
for (ezUInt32 i = 0; i < uiMaxIterations; ++i)
{
const ezSimdFloat fError = EnforceDistanceConstraint();
if (fError < fAllowedError)
return;
}
}
ezSimdFloat ezClothSimulator::EnforceDistanceConstraint()
{
ezSimdFloat fError = ezSimdFloat::Zero();
for (ezUInt32 y = 0; y < m_uiHeight; ++y)
{
for (ezUInt32 x = 0; x < m_uiWidth; ++x)
{
const ezUInt32 idx = (y * m_uiWidth) + x;
auto& n = m_Nodes[idx];
if (n.m_bFixed)
continue;
const ezSimdVec4f posThis = n.m_vPosition;
if (x > 0)
{
const ezSimdVec4f pos = m_Nodes[idx - 1].m_vPosition;
n.m_vPosition += MoveTowards(posThis, pos, 0.5f, ezSimdVec4f(-1, 0, 0), fError, m_vSegmentLength.x);
}
if (x + 1 < m_uiWidth)
{
const ezSimdVec4f pos = m_Nodes[idx + 1].m_vPosition;
n.m_vPosition += MoveTowards(posThis, pos, 0.5f, ezSimdVec4f(1, 0, 0), fError, m_vSegmentLength.x);
}
if (y > 0)
{
const ezSimdVec4f pos = m_Nodes[idx - m_uiWidth].m_vPosition;
n.m_vPosition += MoveTowards(posThis, pos, 0.5f, ezSimdVec4f(0, -1, 0), fError, m_vSegmentLength.y);
}
if (y + 1 < m_uiHeight)
{
const ezSimdVec4f pos = m_Nodes[idx + m_uiWidth].m_vPosition;
n.m_vPosition += MoveTowards(posThis, pos, 0.5f, ezSimdVec4f(0, 1, 0), fError, m_vSegmentLength.y);
}
}
}
return fError;
}
ezSimdVec4f ezClothSimulator::MoveTowards(const ezSimdVec4f posThis, const ezSimdVec4f posNext, ezSimdFloat factor, const ezSimdVec4f fallbackDir, ezSimdFloat& inout_fError, ezSimdFloat fSegLen)
{
ezSimdVec4f vDir = (posNext - posThis);
ezSimdFloat fLen = vDir.GetLength<3>();
if (fLen.IsEqual(ezSimdFloat::Zero(), 0.001f))
{
vDir = fallbackDir;
fLen = 1;
}
vDir /= fLen;
fLen -= fSegLen;
const ezSimdFloat fLocalError = fLen * factor;
vDir *= fLocalError;
// keep track of how much the rope had to be moved to fulfill the constraint
inout_fError += fLocalError.Abs();
return vDir;
}
void ezClothSimulator::UpdateNodePositions(const ezSimdFloat tDiffSqr)
{
const ezSimdFloat damping = m_fDampingFactor;
const ezSimdVec4f acceleration = ezSimdConversion::ToVec3(m_vAcceleration) * tDiffSqr;
for (auto& n : m_Nodes)
{
if (n.m_bFixed)
{
n.m_vPreviousPosition = n.m_vPosition;
}
else
{
// this (simple) logic is the so called 'Verlet integration' (+ damping)
const ezSimdVec4f previousPos = n.m_vPosition;
const ezSimdVec4f vel = (n.m_vPosition - n.m_vPreviousPosition) * damping;
// instead of using a single global acceleration, this could also use individual accelerations per node
// this would be needed to affect the rope more localized
n.m_vPosition += vel + acceleration;
n.m_vPreviousPosition = previousPos;
}
}
}
bool ezClothSimulator::HasEquilibrium(ezSimdFloat fAllowedMovement) const
{
const ezSimdFloat fErrorSqr = fAllowedMovement * fAllowedMovement;
for (const auto& n : m_Nodes)
{
if ((n.m_vPosition - n.m_vPreviousPosition).GetLengthSquared<3>() > fErrorSqr)
{
return false;
}
}
return true;
}
| 26.791946 | 194 | 0.676854 | Tekh-ops |
68135617db854f4ce233a3b6dc0df9a4087d88b5 | 2,344 | hpp | C++ | src/prx/simulation/playback/trajectory.hpp | aravindsiv/ML4KP | 064015a7545e1713cbcad3e79807b5cec0849f54 | [
"MIT"
] | 3 | 2021-05-31T11:28:03.000Z | 2021-05-31T13:49:30.000Z | src/prx/simulation/playback/trajectory.hpp | aravindsiv/ML4KP | 064015a7545e1713cbcad3e79807b5cec0849f54 | [
"MIT"
] | 1 | 2021-09-03T09:39:32.000Z | 2021-12-10T22:17:56.000Z | src/prx/simulation/playback/trajectory.hpp | aravindsiv/ML4KP | 064015a7545e1713cbcad3e79807b5cec0849f54 | [
"MIT"
] | 2 | 2021-09-03T09:17:45.000Z | 2021-10-04T15:52:58.000Z | #pragma once
#include "prx/utilities/spaces/space.hpp"
#include "prx/utilities/defs.hpp"
#include <deque>
namespace prx
{
/**
* @brief <b>A class that defines a trajectory.</b>
*
* A trajectory consists of a sequence of states.
*
* @authors Zakary Littlefield
*
*/
class trajectory_t
{
public:
typedef std::vector<space_point_t>::iterator iterator;
typedef std::vector<space_point_t>::const_iterator const_iterator;
trajectory_t(const space_t* space);
~trajectory_t();
trajectory_t(const trajectory_t& traj);
inline unsigned size() const
{
return num_states;
}
inline space_point_t operator[](unsigned index) const
{
return at(index);
}
inline space_point_t operator[](double index) const
{
return at(index);
}
inline space_point_t front() const
{
prx_assert(num_states != 0,"Trying to access the front of a trajectory with zero size.");
return states[0];
}
inline space_point_t back() const
{
prx_assert(num_states != 0,"Trying to access the back of a trajectory with zero size.");
return states[num_states - 1];
}
inline iterator begin()
{
return states.begin();
}
inline iterator end()
{
return end_iterator;
}
inline const_iterator begin() const
{
return states.begin();
}
inline const_iterator end() const
{
return const_end_iterator;
}
space_point_t at(unsigned index) const
{
prx_assert(index < num_states,"Trying to access state outside of trajectory size.");
return states[index];
}
space_point_t at(double index) const
{
return interpolate(index);
}
unsigned get_num_states() const
{
return num_states;
}
void resize(unsigned num_size);
trajectory_t& operator=(const trajectory_t& t);
trajectory_t& operator+=(const trajectory_t& t);
bool operator==(const trajectory_t& t);
bool operator!=(const trajectory_t& t);
void clear();
void copy_onto_back(space_point_t state);
void copy_onto_back(const space_t* space);
std::string print(unsigned precision=3) const;
protected:
space_point_t interpolate(double s) const;
void increase_buffer();
const space_t* state_space;
iterator end_iterator;
const_iterator const_end_iterator;
unsigned max_num_states;
unsigned num_states;
std::vector<space_point_t> states;
};
}
| 20.561404 | 92 | 0.699232 | aravindsiv |
6817374a7adaf810a5621a991bc6c6638fa695f5 | 457 | tpp | C++ | src/tp_plus_examples/src/tst_user_input.tpp | kobbled/rossum_example_ws | b705b8afab229a607c687bb9fb7dc7dac9bad87e | [
"Apache-2.0"
] | null | null | null | src/tp_plus_examples/src/tst_user_input.tpp | kobbled/rossum_example_ws | b705b8afab229a607c687bb9fb7dc7dac9bad87e | [
"Apache-2.0"
] | null | null | null | src/tp_plus_examples/src/tst_user_input.tpp | kobbled/rossum_example_ws | b705b8afab229a607c687bb9fb7dc7dac9bad87e | [
"Apache-2.0"
] | null | null | null | # Print a ascii tree with the base length
# specified by the user
# -----------------------
userclear()
usershow()
number := R[56]
number = userReadInt('enter length of ascii tree.')
i := R[46]
Dummy_1 := R[225]
Dummy_1 = number - 1
for i in (0 to Dummy_1)
Dummy_2 := R[226]
Dummy_2 = Dummy_1 - i
j := R[48]
for j in (0 to Dummy_2)
print(' ')
end
k := R[50]
for k in (0 to i)
print('* ')
end
print_line('')
end
| 15.758621 | 51 | 0.544858 | kobbled |
6817d1b46bef915ad538225b3ecabdd2f05de687 | 1,668 | cpp | C++ | src/database/overlay/SoXipMenuStyle.cpp | OpenXIP/xip-libraries | 9f0fef66038b20ff0c81c089d7dd0038e3126e40 | [
"Apache-2.0"
] | 2 | 2020-05-21T07:06:07.000Z | 2021-06-28T02:14:34.000Z | src/database/overlay/SoXipMenuStyle.cpp | OpenXIP/xip-libraries | 9f0fef66038b20ff0c81c089d7dd0038e3126e40 | [
"Apache-2.0"
] | null | null | null | src/database/overlay/SoXipMenuStyle.cpp | OpenXIP/xip-libraries | 9f0fef66038b20ff0c81c089d7dd0038e3126e40 | [
"Apache-2.0"
] | 6 | 2016-03-21T19:53:18.000Z | 2021-06-08T18:06:03.000Z | /*
Copyright (c) 2011, Siemens Corporate Research a Division of Siemens Corporation
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <Inventor/actions/SoGLRenderAction.h>
#include "SoXipMenuStyle.h"
#include "SoXipMenuStyleElement.h"
SO_NODE_SOURCE( SoXipMenuStyle );
SoXipMenuStyle::SoXipMenuStyle()
{
SO_NODE_CONSTRUCTOR( SoXipMenuStyle );
SO_NODE_ADD_FIELD( color, (0xccccccff) );
SO_NODE_ADD_FIELD( focusedColor, (0xffffaaff) );
SO_NODE_ADD_FIELD( disabledColor, (0xccccccff) );
SO_NODE_ADD_FIELD( textColor, (0, 0, 0) );
SO_NODE_ADD_FIELD( focusedTextColor, (0, 0, 0) );
SO_NODE_ADD_FIELD( disabledTextColor, (0.8, 0.8, 0.8) );
}
SoXipMenuStyle::~SoXipMenuStyle()
{
}
void
SoXipMenuStyle::initClass()
{
SO_NODE_INIT_CLASS( SoXipMenuStyle, SoNode, "Node" );
SO_ENABLE( SoGLRenderAction, SoXipMenuStyleElement );
}
void
SoXipMenuStyle::GLRender( SoGLRenderAction* action )
{
if( action->getState() )
{
SbXipMenuStyle style( color, focusedColor, disabledColor,
textColor.getValue(), focusedTextColor.getValue(), disabledTextColor.getValue() );
SoXipMenuStyleElement::set( action->getState(), this, style );
}
}
| 27.8 | 85 | 0.757794 | OpenXIP |
68194d10b70a101f39dcf8c5c984e13a327be87d | 929 | cpp | C++ | src/pdb_component/parsers/hb/source/src/vdw/ca_main.cpp | MelvinYin/Defined_Proteins | 75da20be82a47d85d27176db29580ab87d52b670 | [
"BSD-3-Clause"
] | 2 | 2021-01-05T02:55:57.000Z | 2021-04-16T15:49:08.000Z | src/pdb_component/parsers/hb/source/src/vdw/ca_main.cpp | MelvinYin/Defined_Proteins | 75da20be82a47d85d27176db29580ab87d52b670 | [
"BSD-3-Clause"
] | null | null | null | src/pdb_component/parsers/hb/source/src/vdw/ca_main.cpp | MelvinYin/Defined_Proteins | 75da20be82a47d85d27176db29580ab87d52b670 | [
"BSD-3-Clause"
] | 1 | 2021-01-05T08:12:38.000Z | 2021-01-05T08:12:38.000Z | #include "pdb_data.hpp"
#include "contact_data.hpp"
#include "contact_formatting.hpp"
int main(int argc, char *argv[])
{
if (argc<4)
{
printf("You must supply a filename to compute on, filename for contacts data, as well as the filename for residue bounds data.");
return -1;
};
// Read the structure in
string input_fname(argv[1]);
string atomcs_fname(argv[2]);
string bounds_fname(argv[3]);
FILE* fh = openFile(argv[1], "r");
if (! fh)
return -1;
AtomVector vec = parseAtomLines(fh);
fclose(fh);
// Compute contacts on it
ContactResult r = contactForAtoms(vec);
// Format distances for individual atom contacts and output it
AtomBasicsVector atomcs = formatAtomBasics(vec, r);
writeAtomBasics(atomcs_fname, atomcs);
// Write chain residues (bounds)
ChainBounds bounds = makeChainBounds(vec);
writeChainBounds(bounds_fname, bounds);
return 0;
};
| 29.967742 | 135 | 0.684607 | MelvinYin |
681d1dfa678d19cb65a83b8532d3079b9fb2d741 | 3,764 | cpp | C++ | engine/time/source/CreatureStatisticsMarkerChecker.cpp | prolog/shadow-of-the-wyrm | a1312c3e9bb74473f73c4e7639e8bd537f10b488 | [
"MIT"
] | 60 | 2019-08-21T04:08:41.000Z | 2022-03-10T13:48:04.000Z | engine/time/source/CreatureStatisticsMarkerChecker.cpp | prolog/shadow-of-the-wyrm | a1312c3e9bb74473f73c4e7639e8bd537f10b488 | [
"MIT"
] | 3 | 2021-03-18T15:11:14.000Z | 2021-10-20T12:13:07.000Z | engine/time/source/CreatureStatisticsMarkerChecker.cpp | prolog/shadow-of-the-wyrm | a1312c3e9bb74473f73c4e7639e8bd537f10b488 | [
"MIT"
] | 8 | 2019-11-16T06:29:05.000Z | 2022-01-23T17:33:43.000Z | #include "CreatureStatisticsMarkerChecker.hpp"
#include "EngineConversion.hpp"
#include "HungerCalculator.hpp"
#include "RaceManager.hpp"
#include "RNG.hpp"
#include "StatisticsMarker.hpp"
using namespace std;
const int CreatureStatisticsMarkerChecker::PASSIVE_STATISTIC_THRESHOLD = 15;
CreatureStatisticsMarkerChecker::CreatureStatisticsMarkerChecker()
: minutes_interval(9999)
{
}
CreatureStatisticsMarkerChecker::CreatureStatisticsMarkerChecker(const uint new_interval)
: minutes_interval(new_interval)
{
}
void CreatureStatisticsMarkerChecker::tick(CreaturePtr creature, TilePtr tile, const ulonglong min_this_tick, const ulonglong total_minutes_elapsed)
{
if (creature != nullptr)
{
if (total_minutes_elapsed % minutes_interval == 0)
{
check_strength_conditions(creature);
check_health_conditions(creature);
check_charisma_conditions(creature);
}
}
}
// If a creature is consistently carrying around heavy loads, it will become
// stronger.
void CreatureStatisticsMarkerChecker::check_strength_conditions(CreaturePtr creature)
{
BurdenLevel bl = BurdenLevelConverter::to_burden_level(creature);
int num_marks = 0;
if (bl == BurdenLevel::BURDEN_LEVEL_BURDENED)
{
num_marks++;
}
else if (bl == BurdenLevel::BURDEN_LEVEL_STRAINED)
{
num_marks += 2;
}
StatisticsMarker sm;
if (can_increase_passive_statistic(creature->get_strength()))
{
for (int i = 0; i < num_marks; i++)
{
sm.mark_strength(creature);
}
}
}
// If a creature maintains a good level of satiation, being neither full
// nor hungry, this will increase their overall health. Up to a point -
// otherwise, Fae would be able to get 99 Hea by just waiting around.
void CreatureStatisticsMarkerChecker::check_health_conditions(CreaturePtr creature)
{
if (creature != nullptr && can_increase_passive_statistic(creature->get_health()))
{
HungerLevel hl = HungerLevelConverter::to_hunger_level(creature->get_hunger_clock().get_hunger());
RaceManager rm;
Race* race = rm.get_race(creature->get_race_id());
// Ensure that hungerless races like the fae don't easily max out Health
// simply by existing. Hungerless races can still increase health over
// time, but at a much reduced rate.
if (race != nullptr)
{
HungerCalculator hc;
if (RNG::percent_chance(hc.calculate_pct_chance_mark_health(hl, race->get_hungerless())))
{
StatisticsMarker sm;
sm.mark_health(creature);
}
}
}
}
void CreatureStatisticsMarkerChecker::check_charisma_conditions(CreaturePtr creature)
{
Equipment& eq = creature->get_equipment();
Statistic cha = creature->get_charisma();
ItemPtr lf = eq.get_item(EquipmentWornLocation::EQUIPMENT_WORN_LEFT_FINGER);
ItemPtr rf = eq.get_item(EquipmentWornLocation::EQUIPMENT_WORN_RIGHT_FINGER);
ItemPtr neck = eq.get_item(EquipmentWornLocation::EQUIPMENT_WORN_NECK);
vector<ItemPtr> items = {lf, rf, neck};
vector<ItemType> jewelry_types = {ItemType::ITEM_TYPE_AMULET, ItemType::ITEM_TYPE_RING};
bool adorned = false;
for (ItemPtr item : items)
{
if (item != nullptr)
{
ItemType itype = item->get_type();
if (std::find(jewelry_types.begin(), jewelry_types.end(), itype) != jewelry_types.end())
{
adorned = true;
break;
}
}
}
StatisticsMarker sm;
if (can_increase_passive_statistic(cha) && adorned)
{
sm.mark_charisma(creature);
}
}
bool CreatureStatisticsMarkerChecker::can_increase_passive_statistic(const Statistic& stat)
{
bool can_increase = false;
int modifier = (stat.get_base() - stat.get_original());
if (modifier < PASSIVE_STATISTIC_THRESHOLD)
{
can_increase = true;
}
return can_increase;
} | 27.881481 | 148 | 0.729012 | prolog |
681e3bb316222511721a5a0d06ac03fe59db21d5 | 660 | hpp | C++ | ComputerInfo.hpp | Ferinko/CPPAmpRaytracer | 459d9804cadd0489eea335cf4b6ba4a1256f76dd | [
"MIT"
] | null | null | null | ComputerInfo.hpp | Ferinko/CPPAmpRaytracer | 459d9804cadd0489eea335cf4b6ba4a1256f76dd | [
"MIT"
] | null | null | null | ComputerInfo.hpp | Ferinko/CPPAmpRaytracer | 459d9804cadd0489eea335cf4b6ba4a1256f76dd | [
"MIT"
] | null | null | null | #pragma once
#include <amp.h>
#include <ostream>
namespace Smurf {
void printPCInfo(std::wostream& os) {
auto accelerators = Concurrency::accelerator::get_all();
for (auto && elem : accelerators) {
os << elem.description << std::endl;
}
}
void printRayTraceInfo(std::wostream& os) {
os << L"Resolution: " << Settings::HRes << L" * " << Settings::VRes << "\n"
<< L"Antialiasing: " << Settings::NumSamples << "\n"
<< L"Shading: " << L"Simple lights" << "\n"
<< L"Materials: " << L"Matte" << "\n"
<< std::endl;
}
} // namespace Smurf | 30 | 84 | 0.506061 | Ferinko |
6821abf0af39f37c7d40ab5361c375fe549a2445 | 2,249 | cpp | C++ | Krispy/src/Krispy/Core/OrthographicCameraController.cpp | Dallin343/GameEngine | 029de5127edb29f3372b354cf8902a29ee80d768 | [
"MIT"
] | null | null | null | Krispy/src/Krispy/Core/OrthographicCameraController.cpp | Dallin343/GameEngine | 029de5127edb29f3372b354cf8902a29ee80d768 | [
"MIT"
] | null | null | null | Krispy/src/Krispy/Core/OrthographicCameraController.cpp | Dallin343/GameEngine | 029de5127edb29f3372b354cf8902a29ee80d768 | [
"MIT"
] | null | null | null | //
// Created by dallin on 9/11/20.
//
#include "OrthographicCameraController.h"
namespace Krispy {
OrthographicCameraController::OrthographicCameraController(float aspectRatio, bool rotation)
: m_Rotation(rotation), m_AspectRatio(aspectRatio),
m_Camera(-m_AspectRatio * m_ZoomLevel, m_AspectRatio * m_ZoomLevel, -m_ZoomLevel, m_ZoomLevel) {
}
void OrthographicCameraController::OnUpdate(Timestep ts) {
if (Input::IsKeyPressed(KRISPY_KEY_D)) {
m_CameraPosition.x += m_CameraTranslationSpeed * ts;
} if (Input::IsKeyPressed(KRISPY_KEY_A)) {
m_CameraPosition.x -= m_CameraTranslationSpeed * ts;
}
if (Input::IsKeyPressed(KRISPY_KEY_W)) {
m_CameraPosition.y += m_CameraTranslationSpeed * ts;
} if (Input::IsKeyPressed(KRISPY_KEY_S)) {
m_CameraPosition.y -= m_CameraTranslationSpeed * ts;
}
if (m_Rotation) {
if (Input::IsKeyPressed(KRISPY_KEY_Q)) {
m_CameraRotation += m_CameraRotationSpeed * ts;
} if (Input::IsKeyPressed(KRISPY_KEY_E)) {
m_CameraRotation -= m_CameraRotationSpeed * ts;
}
m_Camera.SetRotation(m_CameraRotation);
}
m_Camera.SetPosition(m_CameraPosition);
m_CameraTranslationSpeed = m_ZoomLevel;
}
void OrthographicCameraController::OnEvent(Event &e) {
EventDispatcher dispatcher(e);
dispatcher.Dispatch<MouseScrolledEvent>(BIND_EVENT_FN(OnMouseScrolled));
dispatcher.Dispatch<WindowResizeEvent>(BIND_EVENT_FN(OnWindowResized));
}
bool OrthographicCameraController::OnMouseScrolled(MouseScrolledEvent &e) {
m_ZoomLevel -= e.GetYOffset() * 0.25f;
m_ZoomLevel = std::max(m_ZoomLevel, 0.25f);
m_Camera.SetProjection(-m_AspectRatio * m_ZoomLevel, m_AspectRatio * m_ZoomLevel, -m_ZoomLevel, m_ZoomLevel);
return false;
}
bool OrthographicCameraController::OnWindowResized(WindowResizeEvent &e) {
m_AspectRatio = (float) e.GetWidth() / (float) e.GetHeight();
m_Camera.SetProjection(-m_AspectRatio * m_ZoomLevel, m_AspectRatio * m_ZoomLevel, -m_ZoomLevel, m_ZoomLevel);
return false;
}
}
| 36.274194 | 117 | 0.672743 | Dallin343 |
68240349f35988ea521f53be03241ffc2a993d52 | 5,149 | cpp | C++ | ProjectEuler+/euler-0015.cpp | sarvekash/HackerRank_Solutions | 8f48e5b1a6e792a85a10d8c328cd1f5341fb16a8 | [
"Apache-2.0"
] | null | null | null | ProjectEuler+/euler-0015.cpp | sarvekash/HackerRank_Solutions | 8f48e5b1a6e792a85a10d8c328cd1f5341fb16a8 | [
"Apache-2.0"
] | null | null | null | ProjectEuler+/euler-0015.cpp | sarvekash/HackerRank_Solutions | 8f48e5b1a6e792a85a10d8c328cd1f5341fb16a8 | [
"Apache-2.0"
] | 1 | 2021-05-28T11:14:34.000Z | 2021-05-28T11:14:34.000Z | // ////////////////////////////////////////////////////////
// # Title
// Lattice paths
//
// # URL
// https://projecteuler.net/problem=15
// http://euler.stephan-brumme.com/15/
//
// # Problem
// Starting in the top left corner of a 2x2 grid, and only being able to move to the right and down,
// there are exactly 6 routes to the bottom right corner.
//
// 
//
// How many such routes are there through a 20x20 grid?
//
// # Solved by
// Stephan Brumme
// February 2017
//
// # Algorithm
// Each grid consists of ''(width+1)*(height+1)'' points. The grid in the problem statement has ''(2+1)*(2+1)=9'' points.
// I chose my coordinates to be ''[0][0]'' in the top left corner and ''[width][height]'' in the bottom right corner.
//
// For each point in a grid, the number of routes from the current point to the lower right corner
// is the sum of all routes when going right plus all routes when going down:
// ''grid[x][y] = grid[x+1][y] + grid[x][y+1];''
//
// There is a single route from the lower right corner to itself ("stay where you are"):
// ''grid[width][height] = 1;''
//
// Now I perform a breadth-first search ( https://en.wikipedia.org/wiki/Breadth-first_search ) from the lower-right corner to the upper-left corner.
// A queue named ''next'' contains the coordinates of the next points to analyze - initially it holds the point above the lower-right corner
// and the point to the left of the lower-right corner.
//
// A loop processes each point in ''next'':
// 1. If this point was already processed, skip it
// 2. If it is possible to move right then get the number of routes stored in ''grid[x+1][y]''
// 3. If it is possible to move down then get the number of routes stored in ''grid[x][y+1]''
// 4. Write the sum of step 2 and 3 to ''grid[x][y]'', potentially avoid overflow (see Hackerrank modification)
// 5. If there is a left neighbor, enqueue it in ''next''
// 6. If there is a neighbor above, enqueue it in ''next''
//
// Finally we have the result in ''grid[0][0]''.
//
// # Alternative
// I later found a posting on the internet that the result is
//
// `dfrac{(width + height)!}{width! height!}`
//
// but I'm not a math guy, I'm a programmer ...
// however, the best explanation for that formula is as follows and unfortunately, it's about bits :-) :
//
// If we take any route through the grid then a decision has to be made at each point: walk to the right or walk down.
// That's similar to a binary number where each bit can be either 0 or 1. Let's say 0 means "right" and 1 means "down".
//
// Then we have to make `width + height` decisions: exactly `width` times we have to go right and exactly `height` times we have to go down.
// In our imaginary binary number, there are `width + height` bits with `height` times 0s and `width` times 1s.
//
// All permutations of these bits are valid routes in the grid.
//
// And as turns out, there are `dfrac{(width + height)!}{width! height!}` permutations, see https://en.wikipedia.org/wiki/Permutation
//
// # Hackerrank
// The result should be printed ` mod (10^9 + 7)`
#include <vector>
#include <deque>
#include <utility>
#include <iostream>
int main()
{
unsigned int tests;
std::cin >> tests;
while (tests--)
{
unsigned int width, height;
std::cin >> width >> height;
// create a 2D array which contains the number of paths
// from the current lattice point to the lower-right corner
// there are (width + 1) * (height + 1) such points
// for the original problem, i.e. 21x21 numbers must be found
const unsigned long long Unknown = 0;
std::vector<std::vector<unsigned long long>> grid(width + 1);
for (auto& column : grid)
column.resize(height + 1, Unknown);
// one route if we are already at the goal
grid[width][height] = 1;
// enqueue the next unprocessed lattice points: left and upper neighbor of the lower-right corner
std::deque<std::pair<unsigned int, unsigned int>> next;
next.push_back(std::make_pair(width - 1, height));
next.push_back(std::make_pair(width, height - 1));
// as long as there are unprocessed points
while (!next.empty())
{
// get next point
auto current = next.front();
next.pop_front();
// I prefer names which are easier to read ...
auto x = current.first;
auto y = current.second;
// already solved ?
if (grid[x][y] != Unknown)
continue;
// sum of all path when going right plus when going down
unsigned long long routes = 0;
if (x < width) // can go right ?
routes += grid[x + 1][y];
if (y < height) // can go down ?
routes += grid[x][y + 1];
#define ORIGINAL
#ifndef ORIGINAL
routes %= 1000000007; // Hackerrank wants the result MOD 10^9 + 7
#endif
// solved number for current lattice point
grid[x][y] = routes;
// add left and upper neighbors for further processing
if (x > 0)
next.push_back(std::make_pair(x - 1, y));
if (y > 0)
next.push_back(std::make_pair(x, y - 1));
}
// we are done !
std::cout << grid[0][0] << std::endl;
}
return 0;
}
| 37.043165 | 148 | 0.646533 | sarvekash |
6825cbe7fd45c02203f82d3966e4fa4776b31e87 | 19,718 | cpp | C++ | msf_localization_ros/src/source/ros_free_model_robot_interface.cpp | Ahrovan/msf_localization | a78ba2473115234910789617e9b45262ebf1d13d | [
"BSD-3-Clause"
] | 1 | 2021-02-27T15:23:13.000Z | 2021-02-27T15:23:13.000Z | msf_localization_ros/src/source/ros_free_model_robot_interface.cpp | Ahrovan/msf_localization | a78ba2473115234910789617e9b45262ebf1d13d | [
"BSD-3-Clause"
] | null | null | null | msf_localization_ros/src/source/ros_free_model_robot_interface.cpp | Ahrovan/msf_localization | a78ba2473115234910789617e9b45262ebf1d13d | [
"BSD-3-Clause"
] | null | null | null |
#include "msf_localization_ros/ros_free_model_robot_interface.h"
#include "msf_localization_core/msfLocalization.h"
RosFreeModelRobotInterface::RosFreeModelRobotInterface(ros::NodeHandle* nh, tf::TransformBroadcaster *tf_transform_broadcaster, MsfLocalizationCore* msf_localization_core_ptr) :
RosRobotInterface(nh, tf_transform_broadcaster),
FreeModelRobotCore(msf_localization_core_ptr)
{
return;
}
RosFreeModelRobotInterface::~RosFreeModelRobotInterface()
{
return;
}
bool RosFreeModelRobotInterface::getPoseWithCovarianceByStamp(msf_localization_ros_srvs::GetPoseWithCovarianceByStamp::Request &req,
msf_localization_ros_srvs::GetPoseWithCovarianceByStamp::Response &res)
{
// Variables
TimeStamp requested_time_stamp;
TimeStamp received_time_stamp;
std::shared_ptr<StateEstimationCore> received_state;
// Fill request
requested_time_stamp=TimeStamp(req.requested_stamp.sec, req.requested_stamp.nsec);
if(!this->getMsfLocalizationCorePtr())
{
std::cout<<"Error!"<<std::endl;
return false;
}
// Do the request
int error=this->getMsfLocalizationCorePtr()->getStateByStamp(requested_time_stamp,
received_time_stamp, received_state);
// Fill response
// Success
if(error)
{
res.success=false;
return true;
}
else
{
res.success=true;
}
// Received TimeStamp
res.received_stamp=ros::Time(received_time_stamp.getSec(), received_time_stamp.getNSec());
// Received State
this->setRobotPoseWithCovarianceMsg(std::dynamic_pointer_cast<RobotStateCore>(received_state->state_component_->TheRobotStateCore), *received_state->state_component_->covarianceMatrix,
res.received_pose);
// Free state ownership
if(received_state)
received_state.reset();
// End
return true;
}
int RosFreeModelRobotInterface::readParameters()
{
// Topic names
// Pose
//
ros::param::param<std::string>("~robot_pose_with_cov_topic_name", robotPoseWithCovarianceStampedTopicName, "msf_localization/robot_pose_cov");
std::cout<<"\t robot_pose_with_cov_topic_name="<<robotPoseWithCovarianceStampedTopicName<<std::endl;
//
ros::param::param<std::string>("~robot_pose_topic_name", robotPoseStampedTopicName, "msf_localization/robot_pose");
std::cout<<"\t robot_pose_topic_name="<<robotPoseStampedTopicName<<std::endl;
//
ros::param::param<std::string>("~robot_pose_with_covariance_stamped_srv_name", robot_pose_with_covariance_stamped_srv_name_, "msf_localization/robot_pose_cov");
std::cout<<"\t robot_pose_with_covariance_stamped_srv_name="<<robot_pose_with_covariance_stamped_srv_name_<<std::endl;
// Velocities
//
ros::param::param<std::string>("~robot_velocities_stamped_topic_name", robot_velocities_stamped_topic_name_, "msf_localization/robot_velocity");
std::cout<<"\t robot_velocities_stamped_topic_name="<<robot_velocities_stamped_topic_name_<<std::endl;
//
ros::param::param<std::string>("~robot_velocities_with_covariance_stamped_topic_name", robot_velocities_with_covariance_stamped_topic_name_, "msf_localization/robot_velocity_cov");
std::cout<<"\t robot_velocities_with_covariance_stamped_topic_name="<<robot_velocities_with_covariance_stamped_topic_name_<<std::endl;
//
ros::param::param<std::string>("~robot_linear_speed_topic_name", robotLinearSpeedStampedTopicName, "msf_localization/robot_linear_speed");
std::cout<<"\t robot_linear_speed_topic_name="<<robotLinearSpeedStampedTopicName<<std::endl;
//
ros::param::param<std::string>("~robot_angular_velocity_topic_name", robotAngularVelocityStampedTopicName, "msf_localization/robot_angular_velocity");
std::cout<<"\t robot_angular_velocity_topic_name="<<robotAngularVelocityStampedTopicName<<std::endl;
// Accelerations
//
ros::param::param<std::string>("~robot_accelerations_stamped_topic_name", robot_accelerations_stamped_topic_name_, "msf_localization/robot_acceleration");
std::cout<<"\t robot_accelerations_stamped_topic_name_="<<robot_accelerations_stamped_topic_name_<<std::endl;
//
ros::param::param<std::string>("~robot_accelerations_with_covariance_stamped_topic_name", robot_accelerations_with_covariance_stamped_topic_name_, "msf_localization/robot_acceleration_cov");
std::cout<<"\t robot_accelerations_with_covariance_stamped_topic_name="<<robot_accelerations_with_covariance_stamped_topic_name_<<std::endl;
//
ros::param::param<std::string>("~robot_linear_acceleration_topic_name", robotLinearAccelerationStampedTopicName, "msf_localization/robot_linear_acceleration");
std::cout<<"\t robot_linear_acceleration_topic_name="<<robotLinearAccelerationStampedTopicName<<std::endl;
//
ros::param::param<std::string>("~robot_angular_acceleration_topic_name", robotAngularAccelerationStampedTopicName, "msf_localization/robot_angular_acceleration");
std::cout<<"\t robot_angular_acceleration_topic_name="<<robotAngularAccelerationStampedTopicName<<std::endl;
// Odometry
//
ros::param::param<std::string>("~robot_odometry_out_topic_name", robot_odometry_out_topic_name_, "msf_localization/robot_odometry");
std::cout<<"\t robot_odometry_out_topic_name="<<robot_odometry_out_topic_name_<<std::endl;
return 0;
}
int RosFreeModelRobotInterface::open()
{
// Read ROS Parameters
this->readParameters();
// Publishers
// Pose
//
robotPoseStampedPub = nh->advertise<geometry_msgs::PoseStamped>(robotPoseStampedTopicName, 1, true);
//
robotPoseWithCovarianceStampedPub = nh->advertise<geometry_msgs::PoseWithCovarianceStamped>(robotPoseWithCovarianceStampedTopicName, 1, true);
//
robot_pose_with_covariance_stamped_srv_ = nh->advertiseService(robot_pose_with_covariance_stamped_srv_name_, &RosFreeModelRobotInterface::getPoseWithCovarianceByStamp, this);
// Velocities
//
robot_velocities_stamped_pub_=nh->advertise<geometry_msgs::TwistStamped>(robot_velocities_stamped_topic_name_, 1, true);
//
robot_velocities_with_covariance_stamped_pub_=nh->advertise<geometry_msgs::TwistWithCovarianceStamped>(robot_velocities_with_covariance_stamped_topic_name_, 1, true);
//
robotLinearSpeedStampedPub = nh->advertise<geometry_msgs::Vector3Stamped>(robotLinearSpeedStampedTopicName, 1, true);
//
robotAngularVelocityStampedPub = nh->advertise<geometry_msgs::Vector3Stamped>(robotAngularVelocityStampedTopicName, 1, true);
// Accelerations
//
robot_accelerations_stamped_pub_=nh->advertise<geometry_msgs::AccelStamped>(robot_accelerations_stamped_topic_name_, 1, true);
//
robot_accelerations_with_covariance_stamped_pub_=nh->advertise<geometry_msgs::AccelWithCovarianceStamped>(robot_accelerations_with_covariance_stamped_topic_name_, 1, true);
//
robotLinearAccelerationStampedPub = nh->advertise<geometry_msgs::Vector3Stamped>(robotLinearAccelerationStampedTopicName, 1, true);
//
robotAngularAccelerationStampedPub = nh->advertise<geometry_msgs::Vector3Stamped>(robotAngularAccelerationStampedTopicName, 1, true);
// Odometry
//
robot_odometry_out_pub_=nh->advertise<nav_msgs::Odometry>(robot_odometry_out_topic_name_, 1, true);
return 0;
}
int RosFreeModelRobotInterface::setRobotPoseMsg(const std::shared_ptr<RobotStateCore>& robot_state_core,
geometry_msgs::Pose& robot_pose_msg)
{
std::shared_ptr<FreeModelRobotStateCore> TheRobotStateCore=std::static_pointer_cast<FreeModelRobotStateCore>(robot_state_core);
Eigen::Vector3d robotPosition=TheRobotStateCore->getPositionRobotWrtWorld();
Eigen::Vector4d robotAttitude=TheRobotStateCore->getAttitudeRobotWrtWorld();
// Position
robot_pose_msg.position.x=robotPosition[0];
robot_pose_msg.position.y=robotPosition[1];
robot_pose_msg.position.z=robotPosition[2];
// Attitude
robot_pose_msg.orientation.w=robotAttitude[0];
robot_pose_msg.orientation.x=robotAttitude[1];
robot_pose_msg.orientation.y=robotAttitude[2];
robot_pose_msg.orientation.z=robotAttitude[3];
return 0;
}
int RosFreeModelRobotInterface::setRobotPoseWithCovarianceMsg(const std::shared_ptr<RobotStateCore>& robot_state_core, const Eigen::MatrixXd &covariance_robot_matrix,
geometry_msgs::PoseWithCovariance& robot_pose_msg)
{
// Pose
setRobotPoseMsg(robot_state_core, robot_pose_msg.pose);
// Covariance
// TODO fix! Covariance of the attitude is not ok!
Eigen::Matrix<double, 6, 6> robotPoseCovariance;//(6,6);
robotPoseCovariance.setZero();
robotPoseCovariance.block<3,3>(0,0)=covariance_robot_matrix.block<3,3>(0,0);
robotPoseCovariance.block<3,3>(3,3)=covariance_robot_matrix.block<3,3>(9,9);
robotPoseCovariance.block<3,3>(0,3)=covariance_robot_matrix.block<3,3>(0,9);
robotPoseCovariance.block<3,3>(3,0)=covariance_robot_matrix.block<3,3>(9,0);
double robotPoseCovarianceArray[36];
Eigen::Map< Eigen::Matrix<double, 6, 6> >(robotPoseCovarianceArray, 6, 6) = robotPoseCovariance;
for(unsigned int i=0; i<36; i++)
{
robot_pose_msg.covariance[i]=robotPoseCovarianceArray[i];
}
}
int RosFreeModelRobotInterface::publish(const TimeStamp& time_stamp, const std::shared_ptr<GlobalParametersCore> &world_core, const std::shared_ptr<RobotStateCore> &robot_state_core, const Eigen::MatrixXd& covariance_robot_matrix)
{
/// tf pose robot wrt world
this->publishTfPoseRobotWrtWorld(time_stamp, world_core, robot_state_core);
/// Other publishers
// Getters
std::shared_ptr<FreeModelRobotStateCore> TheRobotStateCore=std::static_pointer_cast<FreeModelRobotStateCore>(robot_state_core);
Eigen::Vector3d robotLinearSpeed=TheRobotStateCore->getLinearSpeedRobotWrtWorld();
Eigen::Vector3d robotLinearAcceleration=TheRobotStateCore->getLinearAccelerationRobotWrtWorld();
Eigen::Vector3d robotAngularVelocity=TheRobotStateCore->getAngularVelocityRobotWrtWorld();
Eigen::Vector3d robotAngularAcceleration=TheRobotStateCore->getAngularAccelerationRobotWrtWorld();
// Fill msg
// Header
// ROBOT POSE
// Stamp
robotPoseWithCovarianceStampedMsg.header.stamp=ros::Time(time_stamp.getSec(), time_stamp.getNSec());
// Frame id
robotPoseWithCovarianceStampedMsg.header.frame_id=world_core->getWorldName();
//
robotPoseStampedMsg.header.stamp=ros::Time(time_stamp.getSec(), time_stamp.getNSec());
// Frame id
robotPoseStampedMsg.header.frame_id=world_core->getWorldName();
// Velocities
//
robot_velocities_stamped_msg_.header.stamp=ros::Time(time_stamp.getSec(), time_stamp.getNSec());
//
robot_velocities_stamped_msg_.header.frame_id=world_core->getWorldName();
//
robot_velocities_with_covariance_stamped_msg_.header.stamp=ros::Time(time_stamp.getSec(), time_stamp.getNSec());
//
robot_velocities_with_covariance_stamped_msg_.header.frame_id=world_core->getWorldName();
//
robotLinearSpeedStampedMsg.header.stamp=ros::Time(time_stamp.getSec(), time_stamp.getNSec());
// Frame id
robotLinearSpeedStampedMsg.header.frame_id=world_core->getWorldName();
//
robotAngularVelocityStampedMsg.header.stamp=ros::Time(time_stamp.getSec(), time_stamp.getNSec());
// Frame id
robotAngularVelocityStampedMsg.header.frame_id=world_core->getWorldName();
// Accelerations
//
robot_accelerations_stamped_msg_.header.stamp=ros::Time(time_stamp.getSec(), time_stamp.getNSec());
//
robot_accelerations_stamped_msg_.header.frame_id=world_core->getWorldName();
//
robot_accelerations_with_covariance_stamped_msg_.header.stamp=ros::Time(time_stamp.getSec(), time_stamp.getNSec());
//
robot_accelerations_with_covariance_stamped_msg_.header.frame_id=world_core->getWorldName();
//
robotLinearAccelerationStampedMsg.header.stamp=ros::Time(time_stamp.getSec(), time_stamp.getNSec());
// Frame id
robotLinearAccelerationStampedMsg.header.frame_id=world_core->getWorldName();
//
robotAngularAccelerationStampedMsg.header.stamp=ros::Time(time_stamp.getSec(), time_stamp.getNSec());
// Frame id
robotAngularAccelerationStampedMsg.header.frame_id=world_core->getWorldName();
/// Pose
//
this->setRobotPoseWithCovarianceMsg(robot_state_core, covariance_robot_matrix,
robotPoseWithCovarianceStampedMsg.pose);
//
this->setRobotPoseMsg(robot_state_core,
robotPoseStampedMsg.pose);
/// Velocity
geometry_msgs::Vector3 lin_vel;
lin_vel.x=robotLinearSpeed[0];
lin_vel.y=robotLinearSpeed[1];
lin_vel.z=robotLinearSpeed[2];
geometry_msgs::Vector3 ang_vel;
ang_vel.x=robotAngularVelocity[0];
ang_vel.y=robotAngularVelocity[1];
ang_vel.z=robotAngularVelocity[2];
geometry_msgs::Twist velocity;
velocity.linear=lin_vel;
velocity.angular=ang_vel;
//
robot_velocities_stamped_msg_.twist=velocity;
//
robot_velocities_with_covariance_stamped_msg_.twist.twist=velocity;
//{
Eigen::Matrix<double, 6, 6> covariance_velocity;//(6,6);
covariance_velocity.setZero();
covariance_velocity.block<3,3>(0,0)=covariance_robot_matrix.block<3,3>(3,3);
covariance_velocity.block<3,3>(3,3)=covariance_robot_matrix.block<3,3>(12,12);
covariance_velocity.block<3,3>(3,0)=covariance_robot_matrix.block<3,3>(12,3);
covariance_velocity.block<3,3>(0,3)=covariance_robot_matrix.block<3,3>(3,12);
double covariance_velocity_array[36];
Eigen::Map< Eigen::Matrix<double, 6, 6> >(covariance_velocity_array, 6, 6) = covariance_velocity;
for(unsigned int i=0; i<36; i++)
{
robot_velocities_with_covariance_stamped_msg_.twist.covariance[i]=covariance_velocity_array[i];
}
//}
//
robotLinearSpeedStampedMsg.vector=lin_vel;
//
robotAngularVelocityStampedMsg.vector=ang_vel;
/// Acceleration
geometry_msgs::Vector3 lin_acc;
lin_acc.x=robotLinearAcceleration[0];
lin_acc.y=robotLinearAcceleration[1];
lin_acc.z=robotLinearAcceleration[2];
geometry_msgs::Vector3 ang_acc;
ang_acc.x=robotAngularAcceleration[0];
ang_acc.y=robotAngularAcceleration[1];
ang_acc.z=robotAngularAcceleration[2];
geometry_msgs::Accel acceleration;
acceleration.linear=lin_acc;
acceleration.angular=ang_acc;
//
robot_accelerations_stamped_msg_.accel=acceleration;
//
robot_accelerations_with_covariance_stamped_msg_.accel.accel=acceleration;
//{
Eigen::Matrix<double, 6, 6> covariance_acceleration;//(6,6);
covariance_acceleration.setZero();
covariance_acceleration.block<3,3>(0,0)=covariance_robot_matrix.block<3,3>(6,6);
covariance_acceleration.block<3,3>(3,3)=covariance_robot_matrix.block<3,3>(15,15);
covariance_acceleration.block<3,3>(3,0)=covariance_robot_matrix.block<3,3>(15,6);
covariance_acceleration.block<3,3>(0,3)=covariance_robot_matrix.block<3,3>(6,15);
double covariance_acceleration_array[36];
Eigen::Map< Eigen::Matrix<double, 6, 6> >(covariance_acceleration_array, 6, 6) = covariance_acceleration;
for(unsigned int i=0; i<36; i++)
{
robot_accelerations_with_covariance_stamped_msg_.accel.covariance[i]=covariance_acceleration_array[i];
}
//}
//
robotLinearAccelerationStampedMsg.vector=lin_acc;
//
robotAngularAccelerationStampedMsg.vector=ang_acc;
// Odometry
robot_odometry_out_msg_.header.stamp=ros::Time(time_stamp.getSec(), time_stamp.getNSec());
robot_odometry_out_msg_.header.frame_id=world_core->getWorldName();
robot_odometry_out_msg_.child_frame_id=getRobotName();
robot_odometry_out_msg_.pose.pose=robotPoseWithCovarianceStampedMsg.pose.pose;
robot_odometry_out_msg_.pose.covariance=robotPoseWithCovarianceStampedMsg.pose.covariance;
robot_odometry_out_msg_.twist.twist=velocity;
//robot_odometry_out_msg_.twist.covariance;
//{
for(unsigned int i=0; i<36; i++)
{
robot_odometry_out_msg_.twist.covariance[i]=covariance_velocity_array[i];
}
//}
/// Publish Robot State
// Pose
if(robotPoseStampedPub.getNumSubscribers()>0)
robotPoseStampedPub.publish(robotPoseStampedMsg);
if(robotPoseWithCovarianceStampedPub.getNumSubscribers()>0)
robotPoseWithCovarianceStampedPub.publish(robotPoseWithCovarianceStampedMsg);
// Velocities
if(robot_velocities_stamped_pub_.getNumSubscribers()>0)
robot_velocities_stamped_pub_.publish(robot_velocities_stamped_msg_);
if(robot_velocities_with_covariance_stamped_pub_.getNumSubscribers()>0)
robot_velocities_with_covariance_stamped_pub_.publish(robot_velocities_with_covariance_stamped_msg_);
if(robotLinearSpeedStampedPub.getNumSubscribers()>0)
robotLinearSpeedStampedPub.publish(robotLinearSpeedStampedMsg);
if(robotAngularVelocityStampedPub.getNumSubscribers()>0)
robotAngularVelocityStampedPub.publish(robotAngularVelocityStampedMsg);
// Accelerations
if(robot_accelerations_stamped_pub_.getNumSubscribers()>0)
robot_accelerations_stamped_pub_.publish(robot_accelerations_stamped_msg_);
if(robot_accelerations_with_covariance_stamped_pub_.getNumSubscribers()>0)
robot_accelerations_with_covariance_stamped_pub_.publish(robot_accelerations_with_covariance_stamped_msg_);
if(robotLinearAccelerationStampedPub.getNumSubscribers()>0)
robotLinearAccelerationStampedPub.publish(robotLinearAccelerationStampedMsg);
if(robotAngularAccelerationStampedPub.getNumSubscribers()>0)
robotAngularAccelerationStampedPub.publish(robotAngularAccelerationStampedMsg);
// Odometry
if(robot_odometry_out_pub_.getNumSubscribers()>0)
robot_odometry_out_pub_.publish(robot_odometry_out_msg_);
// end
return 0;
}
int RosFreeModelRobotInterface::publishTfPoseRobotWrtWorld(const TimeStamp& time_stamp, const std::shared_ptr<GlobalParametersCore>& world_core, const std::shared_ptr<RobotStateCore>& robot_state_core)
{
std::shared_ptr<FreeModelRobotStateCore> TheRobotStateCore=std::dynamic_pointer_cast<FreeModelRobotStateCore>(robot_state_core);
Eigen::Vector3d robotPosition=TheRobotStateCore->getPositionRobotWrtWorld();
Eigen::Vector4d robotAttitude=TheRobotStateCore->getAttitudeRobotWrtWorld();
tf::Quaternion tf_rot(robotAttitude[1], robotAttitude[2], robotAttitude[3], robotAttitude[0]);
tf::Vector3 tf_tran(robotPosition[0], robotPosition[1], robotPosition[2]);
tf::Transform transform(tf_rot, tf_tran);
tf_transform_broadcaster_->sendTransform(tf::StampedTransform(transform, ros::Time(time_stamp.getSec(), time_stamp.getNSec()),
world_core->getWorldName(), this->getRobotName()));
return 0;
}
int RosFreeModelRobotInterface::readConfig(const pugi::xml_node &robot, std::shared_ptr<FreeModelRobotStateCore>& robot_state_core)
{
/// Imu Sensor Configs
int errorReadConfig=this->FreeModelRobotCore::readConfig(robot, robot_state_core);
if(errorReadConfig)
return errorReadConfig;
/// Ros Configs
// Name
std::string robot_name=robot.child_value("name");
this->setRobotName(robot_name);
/// Finish
// Open
this->open();
// End
return 0;
}
| 36.650558 | 230 | 0.750127 | Ahrovan |
6827daa819555eef6698af9548abe30e355a3392 | 3,953 | cpp | C++ | src/160_intersection_of_two_linked_lists.cpp | llife09/leetcode | f5bd6bc7819628b9921441d8362f62123ab881b7 | [
"MIT"
] | 1 | 2019-09-01T22:54:39.000Z | 2019-09-01T22:54:39.000Z | src/160_intersection_of_two_linked_lists.cpp | llife09/leetcode | f5bd6bc7819628b9921441d8362f62123ab881b7 | [
"MIT"
] | 6 | 2019-07-19T07:16:42.000Z | 2019-07-26T08:21:31.000Z | src/160_intersection_of_two_linked_lists.cpp | llife09/leetcode | f5bd6bc7819628b9921441d8362f62123ab881b7 | [
"MIT"
] | null | null | null |
/*
Intersection of Two Linked Lists
URL: https://leetcode.com/problems/intersection-of-two-linked-lists
Tags: ['linked-list']
___
Write a program to find the node at which the intersection of two singly
linked lists begins.
For example, the following two linked lists:
[](https://assets.leetcode.com/uploads/2018/12/13/160_statement.png)
begin to intersect at node c1.
Example 1:
[](https://assets.leetcode.com/uploads/2018/12/13/160_example_1.png)
Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA =
2, skipB = 3 Output: Reference of the node with value = 8 Input Explanation: The
intersected node 's value is 8 (note that this must not be 0 if the two lists
intersect). From the head of A, it reads as [4,1,8,4,5]. From the head of B, it
reads as [5,0,1,8,4,5]. There are 2 nodes before the intersected node in A;
There are 3 nodes before the intersected node in B.
Example 2:
[](https://assets.leetcode.com/uploads/2018/12/13/160_example_2.png)
Input: intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3,
skipB = 1 Output: Reference of the node with value = 2 Input Explanation: The
intersected node's value is 2 (note that this must not be 0 if the two lists
intersect). From the head of A, it reads as [0,9,1,2,4]. From the head of B, it
reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are
1 node before the intersected node in B.
Example 3:
[](https://assets.leetcode.com/uploads/2018/12/13/160_example_3.png)
Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB =
2 Output: null Input Explanation: From the head of A, it reads as [2,6,4]. From
the head of B, it reads as [1,5]. Since the two lists do not intersect,
intersectVal must be 0, while skipA and skipB can be arbitrary values.
Explanation: The two lists do not intersect, so return null.
Notes:
* If the two linked lists have no intersection at all, return `null`.
* The linked lists must retain their original structure after the function
returns.
* You may assume there are no cycles anywhere in the entire linked structure.
* Your code should preferably run in O(n) time and use only O(1) memory.
*/
#include "test.h"
using namespace leetcode;
namespace intersection_of_two_linked_lists {
/*
当 A 和 B 相遇时, 刚好都走完了所有的节点.
*/
inline namespace v1 {
class Solution {
public:
ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) {
if (!headA || !headB) {
return nullptr;
}
auto i = headA, j = headB;
bool aJumped = false, bJumped = false;
while (i != j) {
if (i->next) {
i = i->next;
} else {
if (aJumped) {
return nullptr;
}
i = headB;
aJumped = true;
}
if (j->next) {
j = j->next;
} else {
if (bJumped) {
return nullptr;
}
j = headA;
bJumped = true;
}
}
return i;
}
};
} // namespace v1
TEST_CASE("Intersection of Two Linked Lists") {
TEST_SOLUTION(getIntersectionNode, v1) {
ListNode a1(0);
ListNode a2(0);
ListNode a3(0);
ListNode a4(0);
ListNode a5(0);
a1.next = &a2;
a2.next = &a3;
a3.next = &a4;
a4.next = &a5;
ListNode b1(0);
ListNode b2(0);
b1.next = &b2;
b2.next = &a4;
CHECK(getIntersectionNode(&a1, &b1) == &a4);
};
}
} // namespace intersection_of_two_linked_lists
| 28.235714 | 137 | 0.620288 | llife09 |
68344879905a2fd5f125c66422f3d191d8429164 | 2,966 | cc | C++ | tests/test_ipsec.cc | ANLAB-KAIST/NBA | a093a72af32ccdc041792a01ae65a699294470cd | [
"MIT"
] | 61 | 2015-03-25T04:49:09.000Z | 2020-11-24T08:36:19.000Z | tests/test_ipsec.cc | ANLAB-KAIST/NBA | a093a72af32ccdc041792a01ae65a699294470cd | [
"MIT"
] | 32 | 2015-04-29T08:20:39.000Z | 2017-02-09T22:49:37.000Z | tests/test_ipsec.cc | ANLAB-KAIST/NBA | a093a72af32ccdc041792a01ae65a699294470cd | [
"MIT"
] | 11 | 2015-07-24T22:48:05.000Z | 2020-09-10T11:48:47.000Z | #include <cstdint>
#include <cstdlib>
#include <cstdio>
#include <unordered_map>
#ifdef USE_CUDA
#include <cuda_runtime.h>
#endif
#include <nba/framework/datablock.hh>
#include <nba/framework/datablock_shared.hh>
#include <nba/element/annotation.hh>
#include <nba/element/packet.hh>
#include <nba/element/packetbatch.hh>
#include <nba/framework/test_utils.hh>
#include <gtest/gtest.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <openssl/evp.h>
#include <openssl/err.h>
#include <openssl/aes.h>
#include <openssl/sha.h>
#include <rte_mbuf.h>
#include "../elements/ipsec/util_esp.hh"
#include "../elements/ipsec/util_ipsec_key.hh"
#include "../elements/ipsec/util_sa_entry.hh"
#ifdef USE_CUDA
#include "../elements/ipsec/IPsecAES_kernel.hh"
#include "../elements/ipsec/IPsecAuthHMACSHA1_kernel.hh"
#endif
#include "../elements/ipsec/IPsecDatablocks.hh"
/*
#require <lib/datablock.o>
#require <lib/test_utils.o>
#require "../elements/ipsec/IPsecDatablocks.o"
*/
#ifdef USE_CUDA
/*
#require "../elements/ipsec/IPsecAES_kernel.o"
#require "../elements/ipsec/IPsecAuthHMACSHA1_kernel.o"
*/
#endif
using namespace std;
using namespace nba;
#ifdef USE_CUDA
static int getNumCUDADevices() {
int count;
cudaGetDeviceCount(&count);
return count;
}
class IPsecAESCUDAMatchTest : public ::testing::TestWithParam<int> {
protected:
virtual void SetUp() {
cudaSetDevice(GetParam());
struct ipaddr_pair pair;
struct aes_sa_entry *entry;
unsigned char fake_iv[AES_BLOCK_SIZE] = {0};
aes_sa_entry_array = (struct aes_sa_entry *) malloc(sizeof(struct aes_sa_entry) * num_tunnels);
for (int i = 0; i < num_tunnels; i++) {
pair.src_addr = 0x0a000001u;
pair.dest_addr = 0x0a000000u | (i + 1);
auto result = aes_sa_table.insert(make_pair<ipaddr_pair&, int&>(pair, i));
assert(result.second == true);
entry = &aes_sa_entry_array[i];
entry->entry_idx = i;
rte_memcpy(entry->aes_key, "1234123412341234", AES_BLOCK_SIZE);
#ifdef USE_OPENSSL_EVP
EVP_CIPHER_CTX_init(&entry->evpctx);
if (EVP_EncryptInit(&entry->evpctx, EVP_aes_128_ctr(), entry->aes_key, fake_iv) != 1)
fprintf(stderr, "IPsecAES: EVP_EncryptInit() - %s\n", ERR_error_string(ERR_get_error(), NULL));
#endif
AES_set_encrypt_key((uint8_t *) entry->aes_key, 128, &entry->aes_key_t);
}
}
virtual void TearDown() {
free(aes_sa_entry_array);
cudaDeviceReset();
}
const long num_tunnels = 1024;
struct aes_sa_entry *aes_sa_entry_array;
unordered_map<struct ipaddr_pair, int> aes_sa_table;
};
TEST_P(IPsecAESCUDAMatchTest, SingleBatchWithDatablock) {
}
INSTANTIATE_TEST_CASE_P(PerDeviceIPsecAESCUDAMatchTests, IPsecAESCUDAMatchTest,
::testing::Values(0, getNumCUDADevices() - 1));
#endif
// vim: ts=8 sts=4 sw=4 et
| 29.66 | 111 | 0.683749 | ANLAB-KAIST |
683471193b0181139b491d4c60980f08955bbe39 | 11,256 | cpp | C++ | Sankore-3.1/src/domain/UBGraphicsMediaItem.cpp | eaglezzb/rsdc | cce881f6542ff206bf286cf798c8ec8da3b51d50 | [
"MIT"
] | null | null | null | Sankore-3.1/src/domain/UBGraphicsMediaItem.cpp | eaglezzb/rsdc | cce881f6542ff206bf286cf798c8ec8da3b51d50 | [
"MIT"
] | null | null | null | Sankore-3.1/src/domain/UBGraphicsMediaItem.cpp | eaglezzb/rsdc | cce881f6542ff206bf286cf798c8ec8da3b51d50 | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2010-2013 Groupement d'Intérêt Public pour l'Education Numérique en Afrique (GIP ENA)
*
* This file is part of Open-Sankoré.
*
* Open-Sankoré 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, version 3 of the License,
* with a specific linking exception for the OpenSSL project's
* "OpenSSL" library (or with modified versions of it that use the
* same license as the "OpenSSL" library).
*
* Open-Sankoré 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 Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/
#include "UBGraphicsGroupContainerItem.h"
#include "UBGraphicsMediaItem.h"
#include "UBGraphicsMediaItemDelegate.h"
#include "UBGraphicsScene.h"
#include "UBGraphicsDelegateFrame.h"
#include "document/UBDocumentProxy.h"
#include "core/UBApplication.h"
#include "board/UBBoardController.h"
#include "core/memcheck.h"
UBAudioPresentationWidget::UBAudioPresentationWidget(QWidget *parent)
: QWidget(parent)
, mBorderSize(10)
{
}
void UBAudioPresentationWidget::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
painter.fillRect(rect(), QBrush(Qt::white));
QPen borderPen;
borderPen.setWidth(2);
borderPen.setColor(QColor(Qt::black));
painter.setPen(borderPen);
painter.drawRect(0,0, width(), height());
if (QString() != mTitle)
{
painter.setPen(QPen(Qt::black));
QRect titleRect = rect();
titleRect.setX(mBorderSize);
titleRect.setY(2);
titleRect.setHeight(15);
painter.drawText(titleRect, mTitle);
}
QWidget::paintEvent(event);
}
bool UBGraphicsMediaItem::sIsMutedByDefault = false;
UBGraphicsMediaItem::UBGraphicsMediaItem(const QUrl& pMediaFileUrl, QGraphicsItem *parent)
: UBAbstractGraphicsProxyWidget(parent)
, mVideoWidget(NULL)
, mAudioWidget(NULL)
, mMuted(sIsMutedByDefault)
, mMutedByUserAction(sIsMutedByDefault)
, mMediaFileUrl(pMediaFileUrl)
, mLinkedImage(NULL)
, mInitialPos(0)
{
update();
mMediaObject = new Phonon::MediaObject(this);
QString mediaPath = pMediaFileUrl.toString();
if ("" == mediaPath)
mediaPath = pMediaFileUrl.toLocalFile();
if (mediaPath.toLower().contains("videos"))
{
mMediaType = mediaType_Video;
mAudioOutput = new Phonon::AudioOutput(Phonon::VideoCategory, this);
mMediaObject->setTickInterval(50);
mVideoWidget = new Phonon::VideoWidget(); // owned and destructed by the scene ...
Phonon::createPath(mMediaObject, mVideoWidget);
if(mVideoWidget->sizeHint() == QSize(1,1)){
mVideoWidget->resize(320,240);
}
mVideoWidget->setMinimumSize(140,26);
haveLinkedImage = true;
}
else
if (mediaPath.toLower().contains("audios"))
{
mMediaType = mediaType_Audio;
mAudioOutput = new Phonon::AudioOutput(Phonon::MusicCategory, this);
mMediaObject->setTickInterval(1000);
mAudioWidget = new UBAudioPresentationWidget();
int borderSize = 0;
UBAudioPresentationWidget* pAudioWidget = dynamic_cast<UBAudioPresentationWidget*>(mAudioWidget);
if (pAudioWidget)
{
borderSize = pAudioWidget->borderSize();
}
mAudioWidget->resize(320,26+2*borderSize); //3*border size with enabled title
mAudioWidget->setMinimumSize(150,26+borderSize);
haveLinkedImage = false;
}
Phonon::createPath(mMediaObject, mAudioOutput);
mSource = Phonon::MediaSource(pMediaFileUrl);
mMediaObject->setCurrentSource(mSource);
// we should create delegate after media objects because delegate uses his properties at creation.
setDelegate(new UBGraphicsMediaItemDelegate(this, mMediaObject));
// delegate should be created earler because we setWidget calls resize event for graphics proxy widgt.
// resize uses delegate.
if (mediaType_Video == mMediaType)
setWidget(mVideoWidget);
else
setWidget(mAudioWidget);
// media widget should be created and placed on proxy widget here.
Delegate()->init();
if (mediaType_Audio == mMediaType)
Delegate()->frame()->setOperationMode(UBGraphicsDelegateFrame::ResizingHorizontally);
else
Delegate()->frame()->setOperationMode(UBGraphicsDelegateFrame::Resizing);
setData(UBGraphicsItemData::itemLayerType, QVariant(itemLayerType::ObjectItem)); //Necessary to set if we want z value to be assigned correctly
connect(Delegate(), SIGNAL(showOnDisplayChanged(bool)), this, SLOT(showOnDisplayChanged(bool)));
connect(mMediaObject, SIGNAL(hasVideoChanged(bool)), this, SLOT(hasMediaChanged(bool)));
}
UBGraphicsMediaItem::~UBGraphicsMediaItem()
{
if (mMediaObject)
mMediaObject->stop();
}
QVariant UBGraphicsMediaItem::itemChange(GraphicsItemChange change, const QVariant &value)
{
if ((change == QGraphicsItem::ItemEnabledChange)
|| (change == QGraphicsItem::ItemSceneChange)
|| (change == QGraphicsItem::ItemVisibleChange))
{
if (mMediaObject && (!isEnabled() || !isVisible() || !scene()))
{
mMediaObject->pause();
}
}
else if (change == QGraphicsItem::ItemSceneHasChanged)
{
if (!scene())
{
mMediaObject->stop();
}
else
{
QString absoluteMediaFilename;
if(mMediaFileUrl.toLocalFile().startsWith("audios/") || mMediaFileUrl.toLocalFile().startsWith("videos/")){
absoluteMediaFilename = scene()->document()->persistencePath() + "/" + mMediaFileUrl.toLocalFile();
}
else{
absoluteMediaFilename = mMediaFileUrl.toLocalFile();
}
if (absoluteMediaFilename.length() > 0)
mMediaObject->setCurrentSource(Phonon::MediaSource(absoluteMediaFilename));
}
}
return UBAbstractGraphicsProxyWidget::itemChange(change, value);
}
void UBGraphicsMediaItem::setSourceUrl(const QUrl &pSourceUrl)
{
UBAudioPresentationWidget* pAudioWidget = dynamic_cast<UBAudioPresentationWidget*>(mAudioWidget);
if (pAudioWidget)
{
// pAudioWidget->setTitle(UBFileSystemUtils::lastPathComponent(pSourceUrl.toString()));
}
UBItem::setSourceUrl(pSourceUrl);
}
void UBGraphicsMediaItem::clearSource()
{
QString path = mediaFileUrl().toLocalFile();
//if path is absolute clean duplicated path string
if (!path.contains(UBApplication::boardController->selectedDocument()->persistencePath()))
path = UBApplication::boardController->selectedDocument()->persistencePath() + "/" + path;
if (!UBFileSystemUtils::deleteFile(path))
qDebug() << "cannot delete file: " << path;
}
void UBGraphicsMediaItem::toggleMute()
{
mMuted = !mMuted;
setMute(mMuted);
}
void UBGraphicsMediaItem::setMute(bool bMute)
{
mMuted = bMute;
mAudioOutput->setMuted(mMuted);
mMutedByUserAction = mMuted;
sIsMutedByDefault = mMuted;
}
void UBGraphicsMediaItem::hasMediaChanged(bool hasMedia)
{
if(hasMedia && mMediaObject->isSeekable())
{
Q_UNUSED(hasMedia);
mMediaObject->seek(mInitialPos);
UBGraphicsMediaItemDelegate *med = dynamic_cast<UBGraphicsMediaItemDelegate *>(Delegate());
if (med)
med->updateTicker(initialPos());
}
}
UBGraphicsScene* UBGraphicsMediaItem::scene()
{
return qobject_cast<UBGraphicsScene*>(QGraphicsItem::scene());
}
void UBGraphicsMediaItem::activeSceneChanged()
{
if (UBApplication::boardController->activeScene() != scene())
{
mMediaObject->pause();
}
}
void UBGraphicsMediaItem::showOnDisplayChanged(bool shown)
{
if (!shown)
{
mMuted = true;
mAudioOutput->setMuted(mMuted);
}
else if (!mMutedByUserAction)
{
mMuted = false;
mAudioOutput->setMuted(mMuted);
}
}
UBItem* UBGraphicsMediaItem::deepCopy() const
{
QUrl url = this->mediaFileUrl();
UBGraphicsMediaItem *copy = new UBGraphicsMediaItem(url, parentItem());
copy->setUuid(QUuid::createUuid()); // this is OK for now as long as Widgets are imutable
copyItemParameters(copy);
return copy;
}
void UBGraphicsMediaItem::copyItemParameters(UBItem *copy) const
{
UBGraphicsMediaItem *cp = dynamic_cast<UBGraphicsMediaItem*>(copy);
if (cp)
{
cp->setPos(this->pos());
cp->setTransform(this->transform());
cp->setFlag(QGraphicsItem::ItemIsMovable, true);
cp->setFlag(QGraphicsItem::ItemIsSelectable, true);
cp->setData(UBGraphicsItemData::ItemLayerType, this->data(UBGraphicsItemData::ItemLayerType));
cp->setData(UBGraphicsItemData::ItemLocked, this->data(UBGraphicsItemData::ItemLocked));
cp->setSourceUrl(this->sourceUrl());
cp->resize(this->size());
connect(UBApplication::boardController, SIGNAL(activeSceneChanged()), cp, SLOT(activeSceneChanged()));
// TODO UB 4.7 complete all members
}
}
void UBGraphicsMediaItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
if (Delegate())
{
Delegate()->mousePressEvent(event);
if (parentItem() && UBGraphicsGroupContainerItem::Type == parentItem()->type())
{
UBGraphicsGroupContainerItem *group = qgraphicsitem_cast<UBGraphicsGroupContainerItem*>(parentItem());
if (group)
{
QGraphicsItem *curItem = group->getCurrentItem();
if (curItem && this != curItem)
{
group->deselectCurrentItem();
}
group->setCurrentItem(this);
this->setSelected(true);
Delegate()->positionHandles();
}
}
}
if (parentItem() && parentItem()->type() == UBGraphicsGroupContainerItem::Type)
{
mShouldMove = false;
if (!Delegate()->mousePressEvent(event))
{
event->accept();
}
}
else
{
mShouldMove = (event->buttons() & Qt::LeftButton);
mMousePressPos = event->scenePos();
mMouseMovePos = mMousePressPos;
event->accept();
setSelected(true);
}
}
void UBGraphicsMediaItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
if(mShouldMove && (event->buttons() & Qt::LeftButton))
{
QPointF offset = event->scenePos() - mMousePressPos;
if (offset.toPoint().manhattanLength() > QApplication::startDragDistance())
{
QPointF mouseMovePos = mapFromScene(mMouseMovePos);
QPointF eventPos = mapFromScene( event->scenePos());
QPointF translation = eventPos - mouseMovePos;
translate(translation.x(), translation.y());
}
mMouseMovePos = event->scenePos();
}
event->accept();
}
| 30.016 | 147 | 0.661514 | eaglezzb |
683787adcf74d0720ef1397164780d2759656daa | 879 | cpp | C++ | Source/Flopnite/Private/FNAttributeSet.cpp | BEASTSM96/flopnite-ue4 | 76193544a6b7fe6b969864e74409b6b5a43f3d7a | [
"MIT"
] | null | null | null | Source/Flopnite/Private/FNAttributeSet.cpp | BEASTSM96/flopnite-ue4 | 76193544a6b7fe6b969864e74409b6b5a43f3d7a | [
"MIT"
] | null | null | null | Source/Flopnite/Private/FNAttributeSet.cpp | BEASTSM96/flopnite-ue4 | 76193544a6b7fe6b969864e74409b6b5a43f3d7a | [
"MIT"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "FNAttributeSet.h"
#include "Net/UnrealNetwork.h"
UFNAttributeSet::UFNAttributeSet() {
}
void UFNAttributeSet::PreAttributeChange(const FGameplayAttribute& Attribute, float& NewValue) {
Super::PreAttributeChange(Attribute, NewValue);
}
void UFNAttributeSet::PostGameplayEffectExecute(const FGameplayEffectModCallbackData& Data) {
Super::PostGameplayEffectExecute(Data);
}
void UFNAttributeSet::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const {
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
DOREPLIFETIME_CONDITION_NOTIFY(UFNAttributeSet, MoveSpeed, COND_None, REPNOTIFY_Always);
}
void UFNAttributeSet::OnRep_MoveSpeed(const FGameplayAttributeData& OldMoveSpeed)
{
GAMEPLAYATTRIBUTE_REPNOTIFY( UFNAttributeSet, MoveSpeed, OldMoveSpeed );
}
| 30.310345 | 101 | 0.829352 | BEASTSM96 |
683a085249930e046385b141a55e5d2152dd78b6 | 1,351 | cpp | C++ | PBitmapLibrary/Sample.cpp | bear1704/WindowsProgramming_Portfolio | 83f1d763c73d08b82291aa894ef246558fdf0198 | [
"Apache-2.0"
] | null | null | null | PBitmapLibrary/Sample.cpp | bear1704/WindowsProgramming_Portfolio | 83f1d763c73d08b82291aa894ef246558fdf0198 | [
"Apache-2.0"
] | null | null | null | PBitmapLibrary/Sample.cpp | bear1704/WindowsProgramming_Portfolio | 83f1d763c73d08b82291aa894ef246558fdf0198 | [
"Apache-2.0"
] | null | null | null | #include "Sample.h"
Sample::Sample()
{
}
Sample::~Sample()
{
}
bool Sample::Init()
{
object_background_bitmap_.Init();
object_background_bitmap_.Load(L"../../data/bitmap/Loading800x600.bmp");
PRectObjectStat stat;
stat.position = pPoint(0, 0);
RECT rect = { 0, 0, rectangle_client.right, rectangle_client.bottom };
stat.rect = rect;
object_background_bitmap_.Set(stat);
hero_.Init();
hero_.Load(L"../../data/bitmap/bitmap1.bmp");
PRectObjectStat stat1;
stat1.position = pPoint(100, 100);
RECT rect1 = { 90, 1 , 40, 60 };
stat1.rect = rect1;
stat1.moveSpeed = 100.0f;
hero_.Set(stat1);
character_npc_.Init();
character_npc_.Load(L"../../data/bitmap/bitmap1.bmp");
PRectObjectStat stat2;
stat2.position = pPoint(200, 200);
RECT rect2 = { 46, 62, 67, 79 };
stat2.rect = rect2;
character_npc_.Set(stat2);
//PSoundMgr::GetInstance().Play(PSoundMgr::GetInstance().Load(L"../../data/sound/onlyLove.mp3"));
return true;
}
bool Sample::Frame()
{
object_background_bitmap_.Frame();
hero_.Frame();
character_npc_.Frame();
return true;
}
bool Sample::Render()
{
object_background_bitmap_.Render();
hero_.Render();
character_npc_.Render();
return true;
}
bool Sample::Release()
{
object_background_bitmap_.Release();
hero_.Release();
character_npc_.Release();
return true;
}
PCORE_RUN(L"abcd", 0, 0, 800, 600);
| 18.506849 | 98 | 0.695781 | bear1704 |
683a4c91e23d361308f426615c06b1df1389926a | 13,848 | cpp | C++ | Engine/src/core/Quaternion.cpp | katoun/kg_engine | fdcc6ec01b191d07cedf7a8d6c274166e25401a8 | [
"Unlicense"
] | 2 | 2015-04-21T05:36:12.000Z | 2017-04-16T19:31:26.000Z | Engine/src/core/Quaternion.cpp | katoun/kg_engine | fdcc6ec01b191d07cedf7a8d6c274166e25401a8 | [
"Unlicense"
] | null | null | null | Engine/src/core/Quaternion.cpp | katoun/kg_engine | fdcc6ec01b191d07cedf7a8d6c274166e25401a8 | [
"Unlicense"
] | null | null | null | /*
-----------------------------------------------------------------------------
KG game engine (http://katoun.github.com/kg_engine) is made available under the MIT License.
Copyright (c) 2006-2013 Catalin Alexandru Nastase
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 <core/Quaternion.h>
#include <core/Math.h>
#include <core/Matrix4.h>
#include <core/Vector3d.h>
namespace core
{
quaternion::quaternion(): x(0), y(0), z(0), w(1) {}
quaternion::quaternion(const matrix4& mat)
{
(*this) = mat;
}
quaternion::quaternion(float nx, float ny, float nz)
{
set(nx, ny, nz);
}
quaternion::quaternion(float nx, float ny, float nz, float nw): x(nx), y(ny), z(nz), w(nw) {}
quaternion::quaternion(const quaternion& other): x(other.x), y(other.y), z(other.z), w(other.w) {}
quaternion::quaternion(const vector3d& axis, const float& angle)
{
fromAngleAxis(angle, axis);
}
quaternion quaternion::operator- () const
{
return quaternion(-x, -y, -z, -w);
}
quaternion& quaternion::operator=(const quaternion& other)
{
x = other.x;
y = other.y;
z = other.z;
w = other.w;
return *this;
}
quaternion& quaternion::operator=(const matrix4& m)
{
float diag = m(0, 0) + m(1, 1) + m(2, 2) + 1;
float scale = 0.0f;
if (diag > 0.0f)
{
scale = sqrt(diag) * 2.0f; // get scale from diagonal
// TODO: speed this up
x = (m(2, 1) - m(1, 2)) / scale;
y = (m(0, 2) - m(2, 0)) / scale;
z = (m(1, 0) - m(0, 1)) / scale;
w = 0.25f * scale;
}
else
{
if (m(0, 0) > m(1, 1) && m(0, 0) > m(2, 2))
{
// 1st element of diag is greatest value
// find scale according to 1st element, and double it
scale = sqrt(1.0f + m(0, 0) - m(1, 1) - m(2, 2)) * 2.0f;
// TODO: speed this up
x = 0.25f * scale;
y = (m(0, 1) + m(1, 0)) / scale;
z = (m(2, 0) + m(0, 2)) / scale;
w = (m(2, 1) - m(1, 2)) / scale;
}
else if (m(1, 1) > m(2, 2))
{
// 2nd element of diag is greatest value
// find scale according to 2nd element, and double it
scale = sqrt(1.0f + m(1, 1) - m(0, 0) - m(2, 2)) * 2.0f;
// TODO: speed this up
x = (m(0, 1) + m(1, 0)) / scale;
y = 0.25f * scale;
z = (m(1, 2) + m(2, 1)) / scale;
w = (m(0, 2) - m(2, 0)) / scale;
}
else
{
// 3rd element of diag is greatest value
// find scale according to 3rd element, and double it
scale = sqrt(1.0f + m(2, 2) - m(0, 0) - m(1, 1)) * 2.0f;
// TODO: speed this up
x = (m(0, 2) + m(2, 0)) / scale;
y = (m(1, 2) + m(2, 1)) / scale;
z = 0.25f * scale;
w = (m(1, 0) - m(0, 1)) / scale;
}
}
normalize();
return *this;
}
quaternion quaternion::operator+(const quaternion& b) const
{
return quaternion(x + b.x, y + b.y, z + b.z, w + b.w);
}
quaternion quaternion::operator-(const quaternion& b) const
{
return quaternion(x -b.x, y - b.y, z - b.z, w - b.w);
}
quaternion quaternion::operator*(const quaternion& other) const
{
quaternion tmp;
tmp.x = (w * other.x) + (x * other.w) + (y * other.z) - (z * other.y);
tmp.y = (w * other.y) + (y * other.w) + (z * other.x) - (x * other.z);
tmp.z = (w * other.z) + (z * other.w) + (x * other.y) - (y * other.x);
tmp.w = (w * other.w) - (x * other.x) - (y * other.y) - (z * other.z);
return tmp;
}
vector3d quaternion::operator*(const vector3d& v) const
{
// nVidia SDK implementation
vector3d uv, uuv;
vector3d qvec(x, y, z);
uv = qvec.crossProduct(v);
uuv = qvec.crossProduct(uv);
uv *= (2.0f * w);
uuv *= 2.0f;
return v + uv + uuv;
}
quaternion quaternion::operator*(float s) const
{
return quaternion(s*x, s*y, s*z, s*w);
}
quaternion& quaternion::operator*=(float s)
{
x *= s;
y *= s;
z *= s;
w *= s;
return *this;
}
quaternion& quaternion::operator*=(const quaternion& other)
{
*this = other * (*this);
return *this;
}
bool quaternion::operator==(const quaternion& other) const
{
return ((other.x + EPSILON > x) && (other.x - EPSILON < x) &&
(other.y + EPSILON > y) && (other.y - EPSILON < y) &&
(other.z + EPSILON > z) && (other.z - EPSILON < z) &&
(other.w + EPSILON > w) && (other.w - EPSILON < w));
}
bool quaternion::operator!=(const quaternion& other) const
{
return ((other.x + EPSILON < x) || (other.x - EPSILON > x) ||
(other.y + EPSILON < y) || (other.y - EPSILON > y) ||
(other.z + EPSILON < z) || (other.z - EPSILON > z) ||
(other.w + EPSILON < w) || (other.w - EPSILON > w));
}
void quaternion::set(float x, float y, float z, float w)
{
x = x;
y = y;
z = z;
w = w;
}
void quaternion::set(float nx, float ny, float nz)
{
float angle;
angle = nx * 0.5f;
float sr = (float)sin(angle);
float cr = (float)cos(angle);
angle = ny * 0.5f;
float sp = (float)sin(angle);
float cp = (float)cos(angle);
angle = nz * 0.5f;
float sy = (float)sin(angle);
float cy = (float)cos(angle);
float cpcy = cp * cy;
float spcy = sp * cy;
float cpsy = cp * sy;
float spsy = sp * sy; //quaternion fix by jox
x = sr * cpcy - cr * spsy;
y = cr * spcy + sr * cpsy;
z = cr * cpsy - sr * spcy;
w = cr * cpcy + sr * spsy;
normalize();
}
void quaternion::set(vector3d rot)
{
set(rot.x, rot.y, rot.z);
}
void quaternion::setDegrees(float x, float y, float z)
{
set((float)(x * DEGTORAD), (float)(y * DEGTORAD), (float)(z * DEGTORAD));
}
void quaternion::setDegrees(vector3d rot)
{
set((float)(rot.x * DEGTORAD), (float)(rot.y * DEGTORAD), (float)(rot.z * DEGTORAD));
}
void quaternion::setDegrees(const vector3d& axis, const float& angle)
{
fromAngleAxis((float)(angle * DEGTORAD), axis);
}
void quaternion::invert()
{
float fNorm = x * x + y * y + z * z + w * w;
if (fNorm > 0.0)
{
float fInvNorm = 1.0f / fNorm;
x = -x * fInvNorm;
y = -y * fInvNorm;
z = -z * fInvNorm;
w = w * fInvNorm;
}
else
{
// return an invalid result to flag the error
x = 0.0f;
y = 0.0f;
z = 0.0f;
w = 0.0f;
}
}
void quaternion::unitInvert()
{
x = -x;
y = -y;
z = -z;
}
quaternion quaternion::getInverse() const
{
float fNorm = x * x + y * y + z * z + w * w;
if (fNorm > 0.0)
{
float fInvNorm = 1.0f / fNorm;
return quaternion(-x*fInvNorm, -y*fInvNorm, -z*fInvNorm, w*fInvNorm);
}
else
{
// return an invalid result to flag the error
return quaternion(0.0, 0.0, 0.0, 0.0);
}
}
quaternion quaternion::getUnitInverse() const
{
return quaternion(-x, -y, -z);
}
quaternion& quaternion::normalize()
{
float n = x * x + y * y + z * z + w * w;
if (n == 1)
return *this;
n = 1.0f / sqrt(n);
x *= n;
y *= n;
z *= n;
w *= n;
return *this;
}
float quaternion::dotProduct(const quaternion& q2) const
{
return (x * q2.x) + (y * q2.y) + (z * q2.z) + (w * q2.w);
}
void quaternion::fromAngleAxis(const float& angle, const vector3d& axis)
{
// assert: axis is unit length
//
// The quaternion representing the rotation is
// q = cos(A/2)+sin(A/2)*(x*i+y*j+z*k)
// assert commented out since vector.normalize cant even create 100% normalized f32s
// assert(sqrt(axis.x * axis.x + axis.y * axis.y + axis.z * axis.z) == 1);
float fHalfAngle = 0.5f * angle;
float fSin = (float)sin(fHalfAngle);
w = (float)cos(fHalfAngle);
x = fSin * axis.x;
y = fSin * axis.y;
z = fSin * axis.z;
}
void quaternion::fromDegreeAxis(const float& degree, const vector3d& axis)
{
float fHalfAngle = 0.5f * (degree * DEGTORAD);
float fSin = (float)sin(fHalfAngle);
w = (float)cos(fHalfAngle);
x = fSin * axis.x;
y = fSin * axis.y;
z = fSin * axis.z;
}
void quaternion::fromAxisToAxis(const vector3d& src, const vector3d& dest, const vector3d& fallbackAxis)
{
// Based on Stan Melax's article in Game Programming Gems
// Copy, since cannot modify local
vector3d v0 = src;
vector3d v1 = dest;
v0.normalize();
v1.normalize();
float d = v0.dotProduct(v1);
// If dot == 1, vectors are the same
if (d >= 1.0f)
{
x = IDENTITY.x;
y = IDENTITY.y;
z = IDENTITY.z;
w = IDENTITY.w;
}
if (d < (1e-6f - 1.0f))
{
if (fallbackAxis != vector3d::ORIGIN_3D)
{
// rotate 180 degrees about the fallback axis
fromAngleAxis(PI, fallbackAxis);
}
else
{
// Generate an axis
vector3d axis = vector3d::UNIT_X.crossProduct(src);
if (axis.getLength() == 0) // pick another if colinear
axis = vector3d::UNIT_Y.crossProduct(src);
axis.normalize();
fromAngleAxis(PI, axis);
}
}
else
{
float s = sqrt((1+d)*2);
float invs = 1 / s;
vector3d c = v0.crossProduct(v1);
x = c.x * invs;
y = c.y * invs;
z = c.z * invs;
w = s * 0.5f;
normalize();
}
}
void quaternion::fromRotationMatrix(const matrix4& m)
{
float T = 1 + m(0, 0) + m(1, 1) + m(2, 2);
if (T > 0.00000001f)
{
float S = 0.5f / (float)sqrt(T);
x = (m(2, 1) - m(1, 2)) * S;
y = (m(0, 2) - m(2, 0)) * S;
z = (m(1, 0) - m(0, 1)) * S;
w = 0.25f / S;
}
else if (m(0, 0) > m(1, 1) && m(0, 0) > m(2, 2))
{
float S = 1.0f / (2.0f * (float)sqrt(1.0f + m(0, 0) - m(1, 1) - m(2, 2)));
x = 0.25f / S;
y = (m(1, 0) + m(0, 1)) * S;
z = (m(0, 2) + m(2, 0)) * S;
w = (m(2, 1) - m(1, 2)) * S;
}
else if (m(1, 1) > m(2, 2))
{
float S = 1.0f / (2.0f * (float)sqrt(1.0f - m(0, 0) + m(1, 1) - m(2, 2)));
x = (m(1, 0) + m(0, 1)) * S;
y = 0.25f / S;
z = (m(2, 1) + m(1, 2)) * S;
w = (m(0, 2) - m(2, 0)) * S;
}
else
{
float S = 1.0f / (2.0f * (float)sqrt(1.0f - m(0, 0) - m(1, 1) + m(2, 2)));
x = (m(0, 2) + m(2, 0)) * S;
y = (m(2, 1) + m(1, 2)) * S;
z = 0.25f / S;
w = (m(1, 0) - m(0, 1)) * S;
}
}
matrix4 quaternion::toRotationMatrix() const
{
core::matrix4 m;
m(0, 0) = 1.0f - (2.0f * y * y + 2.0f * z * z);
m(0, 1) = 2.0f * x * y - 2.0f * z * w;
m(0, 2) = 2.0f * x * z + 2.0f * y * w;
m(0, 3) = 0.0f;
m(1, 0) = 2.0f * x * y + 2.0f * z * w;
m(1, 1) = 1.0f - (2.0f * x * x + 2.0f * z * z);
m(1, 2) = 2.0f * z * y - 2.0f * x * w;
m(1, 3) = 0.0f;
m(2, 0) = 2.0f * x * z - 2.0f * y * w;
m(2, 1) = 2.0f * z * y + 2.0f * x * w;
m(2, 2) = 1.0f - (2.0f * x * x + 2.0f * y * y);
m(2, 3) = 0.0f;
m(3, 0) = 0.0f;
m(3, 1) = 0.0f;
m(3, 2) = 0.0f;
m(3, 3) = 1.0f;
return m;
}
vector3d quaternion::toEulerAngles() const
{
/* new version after euclideanspace.com by Matthias Meyer
old version had a problem where the initial quaternion
would return -0 for y value and NaN for rotation of 1.5708
around y-axis when using fromangleaxis() */
vector3d euler;
float testValue = x * y + z * w;
if (testValue > 0.499f) // north pole singularity
{
euler.y = (float)(2.0f * atan2(x, w));
euler.z = HALF_PI;
euler.x = 0.0f;
return euler;
}
if (testValue < -0.499f) // south pole singularity
{
euler.y = (float)(-2.0f * atan2(x, w));
euler.z = -HALF_PI;
euler.x = 0.0f;
return euler;
}
float sqx = x * x;
float sqy = y * y;
float sqz = z * z;
float sqw = w * w;
float unit = sqx + sqy + sqz + sqw;
euler.y = (float)atan2(2.0f * y * w - 2.0f * x * z, sqx - sqy - sqz + sqw);
euler.z = (float)asin(2.0f * testValue / unit);
euler.x = (float)atan2(2.0f * x * w - 2.0f * y * z, -sqx + sqy - sqz + sqw);
return euler;
}
vector3d quaternion::toEulerDegrees() const
{
vector3d eulerRad = toEulerAngles();
eulerRad.x *= RADTODEG;
eulerRad.y *= RADTODEG;
eulerRad.z *= RADTODEG;
return eulerRad;
}
float quaternion::getXDegrees() const
{
float eulerx;
float testValue = x * y + z * w;
if (testValue > 0.499f) // north pole singularity
{
eulerx = 0.0f;
return eulerx;
}
if (testValue < -0.499f) // south pole singularity
{
eulerx = 0.0f;
return eulerx;
}
float sqx = x * x;
float sqy = y * y;
float sqz = z * z;
float sqw = w * w;
//float unit = sqx + sqy + sqz + sqw;
eulerx = atan2(2.0f * x * w - 2.0f * y * z, -sqx + sqy - sqz + sqw);
eulerx *= RADTODEG;
return eulerx;
}
float quaternion::getYDegrees() const
{
float eulery;
float testValue = x * y + z * w;
if (testValue > 0.499f) // north pole singularity
{
eulery = (float)(2.0f * atan2(x, w));;
return eulery;
}
if (testValue < -0.499f) // south pole singularity
{
eulery = (float)(-2.0f * atan2(x, w));
return eulery;
}
float sqx = x * x;
float sqy = y * y;
float sqz = z * z;
float sqw = w * w;
//float unit = sqx + sqy + sqz + sqw;
eulery = (float)atan2(2.0f * y * w - 2.0f * x * z, sqx - sqy - sqz + sqw);
eulery *= RADTODEG;
return eulery;
}
float quaternion::getZDegrees() const
{
float eulerz;
float testValue = x * y + z * w;
if (testValue > 0.499f) // north pole singularity
{
eulerz = HALF_PI;
return eulerz;
}
if (testValue < -0.499f) // south pole singularity
{
eulerz = -HALF_PI;
return eulerz;
}
float sqx = x * x;
float sqy = y * y;
float sqz = z * z;
float sqw = w * w;
float unit = sqx + sqy + sqz + sqw;
eulerz = (float)asin(2.0f * testValue / unit);
eulerz *= RADTODEG;
return eulerz;
}
const quaternion quaternion::ZERO = quaternion(0.0f, 0.0f, 0.0f, 0.0f);
const quaternion quaternion::IDENTITY = quaternion(0.0f, 0.0f, 0.0f, 1.0f);
} // end namespace core
| 22.927152 | 104 | 0.578928 | katoun |
969821dddfb585019e6128e8689b6e60984ca4a6 | 1,297 | cpp | C++ | C++/LeetCode/0450.cpp | Nimesh-Srivastava/DSA | db33aa138f0df8ab6015d2e8ec3ddde1c6838848 | [
"MIT"
] | 4 | 2021-08-28T19:16:50.000Z | 2022-03-04T19:46:31.000Z | C++/LeetCode/0450.cpp | Nimesh-Srivastava/DSA | db33aa138f0df8ab6015d2e8ec3ddde1c6838848 | [
"MIT"
] | 8 | 2021-10-29T19:10:51.000Z | 2021-11-03T12:38:00.000Z | C++/LeetCode/0450.cpp | Nimesh-Srivastava/DSA | db33aa138f0df8ab6015d2e8ec3ddde1c6838848 | [
"MIT"
] | 4 | 2021-09-06T05:53:07.000Z | 2021-12-24T10:31:40.000Z | class Solution {
public:
int getVal(TreeNode* root){
if(!root -> right)
return root -> val;
return getVal(root -> right);
}
TreeNode* delNode(TreeNode* root, int key){
if(!root)
return NULL;
if(root -> val == key){
TreeNode* temp;
if(!root -> left && !root -> right)
return NULL;
else if(!root -> left){
temp = root -> right;
delete(root);
return temp;
}
else if(!root -> right){
temp = root -> left;
delete(root);
return temp;
}
else{
root -> val = getVal(root -> left);
root -> left = delNode(root -> left, root -> val);
return root;
}
}
root -> left = delNode(root -> left, key);
root -> right = delNode(root -> right, key);
return root;
}
TreeNode* deleteNode(TreeNode* root, int key) {
TreeNode* result = delNode(root, key);
return result;
}
};
| 23.581818 | 66 | 0.374711 | Nimesh-Srivastava |
969e602e1eb24f0be93741aa364948d7b904f31e | 413 | cpp | C++ | Leetcode/2114.cpp | prameetu/CP_codes | 41f8cfc188d2e08a8091bc5134247d05ba8a78f5 | [
"MIT"
] | null | null | null | Leetcode/2114.cpp | prameetu/CP_codes | 41f8cfc188d2e08a8091bc5134247d05ba8a78f5 | [
"MIT"
] | null | null | null | Leetcode/2114.cpp | prameetu/CP_codes | 41f8cfc188d2e08a8091bc5134247d05ba8a78f5 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
class Solution {
public:
int mostWordsFound(vector<string>& sentences) {
int ans(0);
for(auto x:sentences)
{
int curr_ans(0);
for(auto words:x)
{
if(words == ' ')
curr_ans++;
}
ans = max(ans,curr_ans);
}
return ans+1;
}
}; | 19.666667 | 51 | 0.438257 | prameetu |
969eb2ddcb0a1e56dfcd28c69e81c0c3ef5a9384 | 88,143 | hpp | C++ | utils/alias.hpp | zouxiaoliang/nerv-kubernetes-client-c | 07528948c643270fd757d38edc68da8c9628ee7a | [
"Apache-2.0"
] | null | null | null | utils/alias.hpp | zouxiaoliang/nerv-kubernetes-client-c | 07528948c643270fd757d38edc68da8c9628ee7a | [
"Apache-2.0"
] | null | null | null | utils/alias.hpp | zouxiaoliang/nerv-kubernetes-client-c | 07528948c643270fd757d38edc68da8c9628ee7a | [
"Apache-2.0"
] | null | null | null | #ifndef ALIAS_H
#define ALIAS_H
#define NS_API(type) io_k8s_api_core_##type
#define function_alias(name)
namespace nerv {
namespace k8s {
// core
namespace core {
typedef struct io_k8s_api_core_v1_namespace_t v1_namespace_t;
// io_k8s_api_core_v1_namespace_t
typedef struct io_k8s_api_core_v1_binding_t v1_binding_t;
// io_k8s_api_core_v1_binding_t
typedef struct io_k8s_api_core_v1_config_map_t v1_config_map_t;
// io_k8s_api_core_v1_config_map_t
typedef struct io_k8s_api_core_v1_endpoints_t v1_endpoints_t;
// io_k8s_api_core_v1_endpoints_t
typedef struct io_k8s_api_core_v1_event_t v1_event_t;
// io_k8s_api_core_v1_event_t
typedef struct io_k8s_api_core_v1_limit_range_t v1_limit_range_t;
// io_k8s_api_core_v1_limit_range_t
typedef struct io_k8s_api_core_v1_persistent_volume_claim_t v1_persistent_volume_claim_t;
// io_k8s_api_core_v1_persistent_volume_claim_t
typedef struct io_k8s_api_core_v1_pod_t v1_pod_t;
// io_k8s_api_core_v1_pod_t
typedef struct io_k8s_api_core_v1_pod_template_t v1_pod_template_t;
// io_k8s_api_core_v1_pod_template_t
typedef struct io_k8s_api_core_v1_replication_controller_t v1_replication_controller_t;
// io_k8s_api_core_v1_replication_controller_t
typedef struct io_k8s_api_core_v1_resource_quota_t v1_resource_quota_t;
// io_k8s_api_core_v1_resource_quota_t
typedef struct io_k8s_api_core_v1_secret_t v1_secret_t;
// io_k8s_api_core_v1_secret_t
typedef struct io_k8s_api_core_v1_service_t v1_service_t;
// io_k8s_api_core_v1_service_t
typedef struct io_k8s_api_core_v1_service_account_t v1_service_account_t;
// io_k8s_api_core_v1_service_account_t
typedef struct io_k8s_api_core_v1_node_t v1_node_t;
// io_k8s_api_core_v1_node_t
typedef struct io_k8s_api_core_v1_persistent_volume_t v1_persistent_volume_t;
// io_k8s_api_core_v1_persistent_volume_t
typedef struct io_k8s_api_core_v1_component_status_list_t v1_component_status_list_t;
// io_k8s_api_core_v1_component_status_list_t
typedef struct io_k8s_api_core_v1_config_map_list_t v1_config_map_list_t;
// io_k8s_api_core_v1_config_map_list_t
typedef struct io_k8s_api_core_v1_endpoints_list_t v1_endpoints_list_t;
// io_k8s_api_core_v1_endpoints_list_t
typedef struct io_k8s_api_core_v1_event_list_t v1_event_list_t;
// io_k8s_api_core_v1_event_list_t
typedef struct io_k8s_api_core_v1_limit_range_list_t v1_limit_range_list_t;
// io_k8s_api_core_v1_limit_range_list_t
typedef struct io_k8s_api_core_v1_namespace_list_t v1_namespace_list_t;
// io_k8s_api_core_v1_namespace_list_t
typedef struct io_k8s_api_core_v1_persistent_volume_claim_list_t v1_persistent_volume_claim_list_t;
// io_k8s_api_core_v1_persistent_volume_claim_list_t
typedef struct io_k8s_api_core_v1_pod_list_t v1_pod_list_t;
// io_k8s_api_core_v1_pod_list_t
typedef struct io_k8s_api_core_v1_pod_template_list_t v1_pod_template_list_t;
// io_k8s_api_core_v1_pod_template_list_t
typedef struct io_k8s_api_core_v1_replication_controller_list_t v1_replication_controller_list_t;
// io_k8s_api_core_v1_replication_controller_list_t
typedef struct io_k8s_api_core_v1_resource_quota_list_t v1_resource_quota_list_t;
// io_k8s_api_core_v1_resource_quota_list_t
typedef struct io_k8s_api_core_v1_secret_list_t v1_secret_list_t;
// io_k8s_api_core_v1_secret_list_t
typedef struct io_k8s_api_core_v1_service_list_t v1_service_list_t;
// io_k8s_api_core_v1_service_list_t
typedef struct io_k8s_api_core_v1_service_account_list_t v1_service_account_list_t;
// io_k8s_api_core_v1_service_account_list_t
typedef struct io_k8s_api_core_v1_node_list_t v1_node_list_t;
// io_k8s_api_core_v1_node_list_t
typedef struct io_k8s_api_core_v1_persistent_volume_list_t v1_persistent_volume_list_t;
// io_k8s_api_core_v1_persistent_volume_list_t
typedef struct io_k8s_api_core_v1_ephemeral_containers_t v1_ephemeral_containers_t;
// io_k8s_api_core_v1_ephemeral_containers_t
typedef struct io_k8s_api_core_v1_component_status_t v1_component_status_t;
// io_k8s_api_core_v1_component_status_t
typedef struct io_k8s_api_core_v1_csi_volume_source_t v1_csi_volume_source_t;
// io_k8s_api_core_v1_csi_volume_source_t
typedef struct io_k8s_api_core_v1_local_object_reference_t v1_local_object_reference_t;
// io_k8s_api_core_v1_local_object_reference_t
typedef struct io_k8s_api_core_v1_flex_persistent_volume_source_t v1_flex_persistent_volume_source_t;
// io_k8s_api_core_v1_flex_persistent_volume_source_t
typedef struct io_k8s_api_core_v1_secret_reference_t v1_secret_reference_t;
// io_k8s_api_core_v1_secret_reference_t
typedef struct io_k8s_api_core_v1_volume_device_t v1_volume_device_t;
// io_k8s_api_core_v1_volume_device_t
typedef struct io_k8s_api_core_v1_namespace_spec_t v1_namespace_spec_t;
// io_k8s_api_core_v1_namespace_spec_t
typedef struct io_k8s_api_core_v1_secret_env_source_t v1_secret_env_source_t;
// io_k8s_api_core_v1_secret_env_source_t
typedef struct io_k8s_api_core_v1_pod_security_context_t v1_pod_security_context_t;
// io_k8s_api_core_v1_pod_security_context_t
typedef struct io_k8s_api_core_v1_se_linux_options_t v1_se_linux_options_t;
// io_k8s_api_core_v1_se_linux_options_t
typedef struct io_k8s_api_core_v1_seccomp_profile_t v1_seccomp_profile_t;
// io_k8s_api_core_v1_seccomp_profile_t
typedef struct io_k8s_api_core_v1_windows_security_context_options_t v1_windows_security_context_options_t;
// io_k8s_api_core_v1_windows_security_context_options_t
typedef struct io_k8s_api_core_v1_probe_t v1_probe_t;
// io_k8s_api_core_v1_probe_t
typedef struct io_k8s_api_core_v1_exec_action_t v1_exec_action_t;
// io_k8s_api_core_v1_exec_action_t
typedef struct io_k8s_api_core_v1_http_get_action_t v1_http_get_action_t;
// io_k8s_api_core_v1_http_get_action_t
typedef struct io_k8s_api_core_v1_tcp_socket_action_t v1_tcp_socket_action_t;
// io_k8s_api_core_v1_tcp_socket_action_t
typedef struct io_k8s_api_core_v1_gce_persistent_disk_volume_source_t v1_gce_persistent_disk_volume_source_t;
// io_k8s_api_core_v1_gce_persistent_disk_volume_source_t
typedef struct io_k8s_api_core_v1_object_reference_t v1_object_reference_t;
// io_k8s_api_core_v1_object_reference_t
typedef struct io_k8s_api_core_v1_env_var_t v1_env_var_t;
// io_k8s_api_core_v1_env_var_t
typedef struct io_k8s_api_core_v1_env_var_source_t v1_env_var_source_t;
// io_k8s_api_core_v1_env_var_source_t
typedef struct io_k8s_api_core_v1_downward_api_projection_t v1_downward_api_projection_t;
// io_k8s_api_core_v1_downward_api_projection_t
typedef struct io_k8s_api_core_v1_node_config_status_t v1_node_config_status_t;
// io_k8s_api_core_v1_node_config_status_t
typedef struct io_k8s_api_core_v1_node_config_source_t v1_node_config_source_t;
// io_k8s_api_core_v1_node_config_source_t
typedef struct io_k8s_api_core_v1_persistent_volume_claim_spec_t v1_persistent_volume_claim_spec_t;
// io_k8s_api_core_v1_persistent_volume_claim_spec_t
typedef struct io_k8s_api_core_v1_persistent_volume_claim_status_t v1_persistent_volume_claim_status_t;
// io_k8s_api_core_v1_persistent_volume_claim_status_t
typedef struct io_k8s_api_core_v1_pod_template_spec_t v1_pod_template_spec_t;
// io_k8s_api_core_v1_pod_template_spec_t
typedef struct io_k8s_api_core_v1_csi_persistent_volume_source_t v1_csi_persistent_volume_source_t;
// io_k8s_api_core_v1_csi_persistent_volume_source_t
typedef struct io_k8s_api_core_v1_resource_quota_spec_t v1_resource_quota_spec_t;
// io_k8s_api_core_v1_resource_quota_spec_t
typedef struct io_k8s_api_core_v1_scope_selector_t v1_scope_selector_t;
// io_k8s_api_core_v1_scope_selector_t
typedef struct io_k8s_api_core_v1_pod_dns_config_option_t v1_pod_dns_config_option_t;
// io_k8s_api_core_v1_pod_dns_config_option_t
typedef struct io_k8s_api_core_v1_quobyte_volume_source_t v1_quobyte_volume_source_t;
// io_k8s_api_core_v1_quobyte_volume_source_t
typedef struct io_k8s_api_core_v1_service_spec_t v1_service_spec_t;
// io_k8s_api_core_v1_service_spec_t
typedef struct io_k8s_api_core_v1_service_status_t v1_service_status_t;
// io_k8s_api_core_v1_service_status_t
typedef struct io_k8s_api_core_v1_pod_dns_config_t v1_pod_dns_config_t;
// io_k8s_api_core_v1_pod_dns_config_t
typedef struct io_k8s_api_core_v1_git_repo_volume_source_t v1_git_repo_volume_source_t;
// io_k8s_api_core_v1_git_repo_volume_source_t
typedef struct io_k8s_api_core_v1_volume_t v1_volume_t;
// io_k8s_api_core_v1_volume_t
typedef struct io_k8s_api_core_v1_aws_elastic_block_store_volume_source_t v1_aws_elastic_block_store_volume_source_t;
// io_k8s_api_core_v1_aws_elastic_block_store_volume_source_t
typedef struct io_k8s_api_core_v1_azure_disk_volume_source_t v1_azure_disk_volume_source_t;
// io_k8s_api_core_v1_azure_disk_volume_source_t
typedef struct io_k8s_api_core_v1_azure_file_volume_source_t v1_azure_file_volume_source_t;
// io_k8s_api_core_v1_azure_file_volume_source_t
typedef struct io_k8s_api_core_v1_ceph_fs_volume_source_t v1_ceph_fs_volume_source_t;
// io_k8s_api_core_v1_ceph_fs_volume_source_t
typedef struct io_k8s_api_core_v1_cinder_volume_source_t v1_cinder_volume_source_t;
// io_k8s_api_core_v1_cinder_volume_source_t
typedef struct io_k8s_api_core_v1_config_map_volume_source_t v1_config_map_volume_source_t;
// io_k8s_api_core_v1_config_map_volume_source_t
typedef struct io_k8s_api_core_v1_downward_api_volume_source_t v1_downward_api_volume_source_t;
// io_k8s_api_core_v1_downward_api_volume_source_t
typedef struct io_k8s_api_core_v1_empty_dir_volume_source_t v1_empty_dir_volume_source_t;
// io_k8s_api_core_v1_empty_dir_volume_source_t
typedef struct io_k8s_api_core_v1_ephemeral_volume_source_t v1_ephemeral_volume_source_t;
// io_k8s_api_core_v1_ephemeral_volume_source_t
typedef struct io_k8s_api_core_v1_fc_volume_source_t v1_fc_volume_source_t;
// io_k8s_api_core_v1_fc_volume_source_t
typedef struct io_k8s_api_core_v1_flex_volume_source_t v1_flex_volume_source_t;
// io_k8s_api_core_v1_flex_volume_source_t
typedef struct io_k8s_api_core_v1_flocker_volume_source_t v1_flocker_volume_source_t;
// io_k8s_api_core_v1_flocker_volume_source_t
typedef struct io_k8s_api_core_v1_glusterfs_volume_source_t v1_glusterfs_volume_source_t;
// io_k8s_api_core_v1_glusterfs_volume_source_t
typedef struct io_k8s_api_core_v1_host_path_volume_source_t v1_host_path_volume_source_t;
// io_k8s_api_core_v1_host_path_volume_source_t
typedef struct io_k8s_api_core_v1_iscsi_volume_source_t v1_iscsi_volume_source_t;
// io_k8s_api_core_v1_iscsi_volume_source_t
typedef struct io_k8s_api_core_v1_nfs_volume_source_t v1_nfs_volume_source_t;
// io_k8s_api_core_v1_nfs_volume_source_t
typedef struct io_k8s_api_core_v1_persistent_volume_claim_volume_source_t v1_persistent_volume_claim_volume_source_t;
// io_k8s_api_core_v1_persistent_volume_claim_volume_source_t
typedef struct io_k8s_api_core_v1_photon_persistent_disk_volume_source_t v1_photon_persistent_disk_volume_source_t;
// io_k8s_api_core_v1_photon_persistent_disk_volume_source_t
typedef struct io_k8s_api_core_v1_portworx_volume_source_t v1_portworx_volume_source_t;
// io_k8s_api_core_v1_portworx_volume_source_t
typedef struct io_k8s_api_core_v1_projected_volume_source_t v1_projected_volume_source_t;
// io_k8s_api_core_v1_projected_volume_source_t
typedef struct io_k8s_api_core_v1_rbd_volume_source_t v1_rbd_volume_source_t;
// io_k8s_api_core_v1_rbd_volume_source_t
typedef struct io_k8s_api_core_v1_scale_io_volume_source_t v1_scale_io_volume_source_t;
// io_k8s_api_core_v1_scale_io_volume_source_t
typedef struct io_k8s_api_core_v1_secret_volume_source_t v1_secret_volume_source_t;
// io_k8s_api_core_v1_secret_volume_source_t
typedef struct io_k8s_api_core_v1_storage_os_volume_source_t v1_storage_os_volume_source_t;
// io_k8s_api_core_v1_storage_os_volume_source_t
typedef struct io_k8s_api_core_v1_vsphere_virtual_disk_volume_source_t v1_vsphere_virtual_disk_volume_source_t;
// io_k8s_api_core_v1_vsphere_virtual_disk_volume_source_t
typedef struct io_k8s_api_core_v1_config_map_key_selector_t v1_config_map_key_selector_t;
// io_k8s_api_core_v1_config_map_key_selector_t
typedef struct io_k8s_api_core_v1_object_field_selector_t v1_object_field_selector_t;
// io_k8s_api_core_v1_object_field_selector_t
typedef struct io_k8s_api_core_v1_resource_field_selector_t v1_resource_field_selector_t;
// io_k8s_api_core_v1_resource_field_selector_t
typedef struct io_k8s_api_core_v1_secret_key_selector_t v1_secret_key_selector_t;
// io_k8s_api_core_v1_secret_key_selector_t
typedef struct io_k8s_api_core_v1_weighted_pod_affinity_term_t v1_weighted_pod_affinity_term_t;
// io_k8s_api_core_v1_weighted_pod_affinity_term_t
typedef struct io_k8s_api_core_v1_pod_affinity_term_t v1_pod_affinity_term_t;
// io_k8s_api_core_v1_pod_affinity_term_t
typedef struct io_k8s_api_core_v1_node_selector_requirement_t v1_node_selector_requirement_t;
// io_k8s_api_core_v1_node_selector_requirement_t
typedef struct io_k8s_api_core_v1_namespace_status_t v1_namespace_status_t;
// io_k8s_api_core_v1_namespace_status_t
typedef struct io_k8s_api_core_v1_node_address_t v1_node_address_t;
// io_k8s_api_core_v1_node_address_t
typedef struct io_k8s_api_core_v1_endpoint_port_t v1_endpoint_port_t;
// io_k8s_api_core_v1_endpoint_port_t
typedef struct io_k8s_api_core_v1_pod_ip_t v1_pod_ip_t;
// io_k8s_api_core_v1_pod_ip_t
typedef struct io_k8s_api_core_v1_event_series_t v1_event_series_t;
// io_k8s_api_core_v1_event_series_t
typedef struct io_k8s_api_core_v1_env_from_source_t v1_env_from_source_t;
// io_k8s_api_core_v1_env_from_source_t
typedef struct io_k8s_api_core_v1_config_map_env_source_t v1_config_map_env_source_t;
// io_k8s_api_core_v1_config_map_env_source_t
typedef struct io_k8s_api_core_v1_session_affinity_config_t v1_session_affinity_config_t;
// io_k8s_api_core_v1_session_affinity_config_t
typedef struct io_k8s_api_core_v1_client_ip_config_t v1_client_ip_config_t;
// io_k8s_api_core_v1_client_ip_config_t
typedef struct io_k8s_api_core_v1_typed_local_object_reference_t v1_typed_local_object_reference_t;
// io_k8s_api_core_v1_typed_local_object_reference_t
typedef struct io_k8s_api_core_v1_endpoint_subset_t v1_endpoint_subset_t;
// io_k8s_api_core_v1_endpoint_subset_t
typedef struct io_k8s_api_core_v1_pod_anti_affinity_t v1_pod_anti_affinity_t;
// io_k8s_api_core_v1_pod_anti_affinity_t
typedef struct io_k8s_api_core_v1_persistent_volume_spec_t v1_persistent_volume_spec_t;
// io_k8s_api_core_v1_persistent_volume_spec_t
typedef struct io_k8s_api_core_v1_persistent_volume_status_t v1_persistent_volume_status_t;
// io_k8s_api_core_v1_persistent_volume_status_t
typedef struct io_k8s_api_core_v1_topology_selector_term_t v1_topology_selector_term_t;
// io_k8s_api_core_v1_topology_selector_term_t
typedef struct io_k8s_api_core_v1_event_source_t v1_event_source_t;
// io_k8s_api_core_v1_event_source_t
typedef struct io_k8s_api_core_v1_config_map_projection_t v1_config_map_projection_t;
// io_k8s_api_core_v1_config_map_projection_t
typedef struct io_k8s_api_core_v1_host_alias_t v1_host_alias_t;
// io_k8s_api_core_v1_host_alias_t
typedef struct io_k8s_api_core_v1_service_account_token_projection_t v1_service_account_token_projection_t;
// io_k8s_api_core_v1_service_account_token_projection_t
typedef struct io_k8s_api_core_v1_container_status_t v1_container_status_t;
// io_k8s_api_core_v1_container_status_t
typedef struct io_k8s_api_core_v1_container_state_t v1_container_state_t;
// io_k8s_api_core_v1_container_state_t
typedef struct io_k8s_api_core_v1_load_balancer_status_t v1_load_balancer_status_t;
// io_k8s_api_core_v1_load_balancer_status_t
typedef struct io_k8s_api_core_v1_preferred_scheduling_term_t v1_preferred_scheduling_term_t;
// io_k8s_api_core_v1_preferred_scheduling_term_t
typedef struct io_k8s_api_core_v1_node_selector_term_t v1_node_selector_term_t;
// io_k8s_api_core_v1_node_selector_term_t
typedef struct io_k8s_api_core_v1_security_context_t v1_security_context_t;
// io_k8s_api_core_v1_security_context_t
typedef struct io_k8s_api_core_v1_capabilities_t v1_capabilities_t;
// io_k8s_api_core_v1_capabilities_t
typedef struct io_k8s_api_core_v1_limit_range_item_t v1_limit_range_item_t;
// io_k8s_api_core_v1_limit_range_item_t
typedef struct io_k8s_api_core_v1_lifecycle_t v1_lifecycle_t;
// io_k8s_api_core_v1_lifecycle_t
typedef struct io_k8s_api_core_v1_handler_t v1_handler_t;
// io_k8s_api_core_v1_handler_t
typedef struct io_k8s_api_core_v1_port_status_t v1_port_status_t;
// io_k8s_api_core_v1_port_status_t
typedef struct io_k8s_api_core_v1_volume_node_affinity_t v1_volume_node_affinity_t;
// io_k8s_api_core_v1_volume_node_affinity_t
typedef struct io_k8s_api_core_v1_node_selector_t v1_node_selector_t;
// io_k8s_api_core_v1_node_selector_t
typedef struct io_k8s_api_core_v1_pod_spec_t v1_pod_spec_t;
// io_k8s_api_core_v1_pod_spec_t
typedef struct io_k8s_api_core_v1_persistent_volume_claim_template_t v1_persistent_volume_claim_template_t;
// io_k8s_api_core_v1_persistent_volume_claim_template_t
typedef struct io_k8s_api_core_v1_limit_range_spec_t v1_limit_range_spec_t;
// io_k8s_api_core_v1_limit_range_spec_t
typedef struct io_k8s_api_core_v1_http_header_t v1_http_header_t;
// io_k8s_api_core_v1_http_header_t
typedef struct io_k8s_api_core_v1_container_t v1_container_t;
// io_k8s_api_core_v1_container_t
typedef struct io_k8s_api_core_v1_resource_requirements_t v1_resource_requirements_t;
// io_k8s_api_core_v1_resource_requirements_t
typedef struct io_k8s_api_core_v1_pod_status_t v1_pod_status_t;
// io_k8s_api_core_v1_pod_status_t
typedef struct io_k8s_api_core_v1_config_map_node_config_source_t v1_config_map_node_config_source_t;
// io_k8s_api_core_v1_config_map_node_config_source_t
typedef struct io_k8s_api_core_v1_replication_controller_spec_t v1_replication_controller_spec_t;
// io_k8s_api_core_v1_replication_controller_spec_t
typedef struct io_k8s_api_core_v1_replication_controller_status_t v1_replication_controller_status_t;
// io_k8s_api_core_v1_replication_controller_status_t
typedef struct io_k8s_api_core_v1_key_to_path_t v1_key_to_path_t;
// io_k8s_api_core_v1_key_to_path_t
typedef struct io_k8s_api_core_v1_ceph_fs_persistent_volume_source_t v1_ceph_fs_persistent_volume_source_t;
// io_k8s_api_core_v1_ceph_fs_persistent_volume_source_t
typedef struct io_k8s_api_core_v1_sysctl_t v1_sysctl_t;
// io_k8s_api_core_v1_sysctl_t
typedef struct io_k8s_api_core_v1_node_spec_t v1_node_spec_t;
// io_k8s_api_core_v1_node_spec_t
typedef struct io_k8s_api_core_v1_node_status_t v1_node_status_t;
// io_k8s_api_core_v1_node_status_t
typedef struct io_k8s_api_core_v1_container_state_running_t v1_container_state_running_t;
// io_k8s_api_core_v1_container_state_running_t
typedef struct io_k8s_api_core_v1_container_state_terminated_t v1_container_state_terminated_t;
// io_k8s_api_core_v1_container_state_terminated_t
typedef struct io_k8s_api_core_v1_container_state_waiting_t v1_container_state_waiting_t;
// io_k8s_api_core_v1_container_state_waiting_t
typedef struct io_k8s_api_core_v1_iscsi_persistent_volume_source_t v1_iscsi_persistent_volume_source_t;
// io_k8s_api_core_v1_iscsi_persistent_volume_source_t
typedef struct io_k8s_api_core_v1_affinity_t v1_affinity_t;
// io_k8s_api_core_v1_affinity_t
typedef struct io_k8s_api_core_v1_node_affinity_t v1_node_affinity_t;
// io_k8s_api_core_v1_node_affinity_t
typedef struct io_k8s_api_core_v1_pod_affinity_t v1_pod_affinity_t;
// io_k8s_api_core_v1_pod_affinity_t
typedef struct io_k8s_api_core_v1_azure_file_persistent_volume_source_t v1_azure_file_persistent_volume_source_t;
// io_k8s_api_core_v1_azure_file_persistent_volume_source_t
typedef struct io_k8s_api_core_v1_local_volume_source_t v1_local_volume_source_t;
// io_k8s_api_core_v1_local_volume_source_t
typedef struct io_k8s_api_core_v1_cinder_persistent_volume_source_t v1_cinder_persistent_volume_source_t;
// io_k8s_api_core_v1_cinder_persistent_volume_source_t
typedef struct io_k8s_api_core_v1_component_condition_t v1_component_condition_t;
// io_k8s_api_core_v1_component_condition_t
typedef struct io_k8s_api_core_v1_pod_readiness_gate_t v1_pod_readiness_gate_t;
// io_k8s_api_core_v1_pod_readiness_gate_t
typedef struct io_k8s_api_core_v1_secret_projection_t v1_secret_projection_t;
// io_k8s_api_core_v1_secret_projection_t
typedef struct io_k8s_api_core_v1_persistent_volume_claim_condition_t v1_persistent_volume_claim_condition_t;
// io_k8s_api_core_v1_persistent_volume_claim_condition_t
typedef struct io_k8s_api_core_v1_toleration_t v1_toleration_t;
// io_k8s_api_core_v1_toleration_t
typedef struct io_k8s_api_core_v1_resource_quota_status_t v1_resource_quota_status_t;
// io_k8s_api_core_v1_resource_quota_status_t
typedef struct io_k8s_api_core_v1_topology_spread_constraint_t v1_topology_spread_constraint_t;
// io_k8s_api_core_v1_topology_spread_constraint_t
typedef struct io_k8s_api_core_v1_node_system_info_t v1_node_system_info_t;
// io_k8s_api_core_v1_node_system_info_t
typedef struct io_k8s_api_core_v1_taint_t v1_taint_t;
// io_k8s_api_core_v1_taint_t
typedef struct io_k8s_api_core_v1_node_condition_t v1_node_condition_t;
// io_k8s_api_core_v1_node_condition_t
typedef struct io_k8s_api_core_v1_volume_mount_t v1_volume_mount_t;
// io_k8s_api_core_v1_volume_mount_t
typedef struct io_k8s_api_core_v1_container_port_t v1_container_port_t;
// io_k8s_api_core_v1_container_port_t
typedef struct io_k8s_api_core_v1_topology_selector_label_requirement_t v1_topology_selector_label_requirement_t;
// io_k8s_api_core_v1_topology_selector_label_requirement_t
typedef struct io_k8s_api_core_v1_container_image_t v1_container_image_t;
// io_k8s_api_core_v1_container_image_t
typedef struct io_k8s_api_core_v1_rbd_persistent_volume_source_t v1_rbd_persistent_volume_source_t;
// io_k8s_api_core_v1_rbd_persistent_volume_source_t
typedef struct io_k8s_api_core_v1_endpoint_address_t v1_endpoint_address_t;
// io_k8s_api_core_v1_endpoint_address_t
typedef struct io_k8s_api_core_v1_attached_volume_t v1_attached_volume_t;
// io_k8s_api_core_v1_attached_volume_t
typedef struct io_k8s_api_core_v1_pod_condition_t v1_pod_condition_t;
// io_k8s_api_core_v1_pod_condition_t
typedef struct io_k8s_api_core_v1_load_balancer_ingress_t v1_load_balancer_ingress_t;
// io_k8s_api_core_v1_load_balancer_ingress_t
typedef struct io_k8s_api_core_v1_glusterfs_persistent_volume_source_t v1_glusterfs_persistent_volume_source_t;
// io_k8s_api_core_v1_glusterfs_persistent_volume_source_t
typedef struct io_k8s_api_core_v1_scoped_resource_selector_requirement_t v1_scoped_resource_selector_requirement_t;
// io_k8s_api_core_v1_scoped_resource_selector_requirement_t
typedef struct io_k8s_api_core_v1_node_daemon_endpoints_t v1_node_daemon_endpoints_t;
// io_k8s_api_core_v1_node_daemon_endpoints_t
typedef struct io_k8s_api_core_v1_volume_projection_t v1_volume_projection_t;
// io_k8s_api_core_v1_volume_projection_t
typedef struct io_k8s_api_core_v1_namespace_condition_t v1_namespace_condition_t;
// io_k8s_api_core_v1_namespace_condition_t
typedef struct io_k8s_api_core_v1_replication_controller_condition_t v1_replication_controller_condition_t;
// io_k8s_api_core_v1_replication_controller_condition_t
typedef struct io_k8s_api_core_v1_daemon_endpoint_t v1_daemon_endpoint_t;
// io_k8s_api_core_v1_daemon_endpoint_t
typedef struct io_k8s_api_core_v1_storage_os_persistent_volume_source_t v1_storage_os_persistent_volume_source_t;
// io_k8s_api_core_v1_storage_os_persistent_volume_source_t
typedef struct io_k8s_api_core_v1_scale_io_persistent_volume_source_t v1_scale_io_persistent_volume_source_t;
// io_k8s_api_core_v1_scale_io_persistent_volume_source_t
typedef struct io_k8s_api_core_v1_downward_api_volume_file_t v1_downward_api_volume_file_t;
// io_k8s_api_core_v1_downward_api_volume_file_t
typedef struct io_k8s_api_core_v1_ephemeral_container_t v1_ephemeral_container_t;
// io_k8s_api_core_v1_ephemeral_container_t
typedef struct io_k8s_api_core_v1_service_port_t v1_service_port_t;
// io_k8s_api_core_v1_service_port_t
}
// apimachinery
namespace apimachinery {
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_api_resource_list_t v1_api_resource_list_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_api_resource_list_t
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_status_t v1_status_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_status_t
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_watch_event_t v1_watch_event_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_watch_event_t
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_api_group_t v1_api_group_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_api_group_t
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_api_group_list_t v1_api_group_list_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_api_group_list_t
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_api_versions_t v1_api_versions_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_api_versions_t
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_object_meta_t v1_object_meta_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_object_meta_t
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_api_resource_t v1_api_resource_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_api_resource_t
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_list_meta_t v1_list_meta_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_list_meta_t
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_label_selector_t v1_label_selector_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_label_selector_t
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_status_cause_t v1_status_cause_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_status_cause_t
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_group_version_for_discovery_t v1_group_version_for_discovery_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_group_version_for_discovery_t
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_condition_t v1_condition_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_condition_t
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_label_selector_requirement_t v1_label_selector_requirement_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_label_selector_requirement_t
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_status_details_t v1_status_details_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_status_details_t
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_managed_fields_entry_t v1_managed_fields_entry_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_managed_fields_entry_t
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_server_address_by_client_cidr_t v1_server_address_by_client_cidr_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_server_address_by_client_cidr_t
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_preconditions_t v1_preconditions_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_preconditions_t
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_delete_options_t v1_delete_options_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_delete_options_t
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_owner_reference_t v1_owner_reference_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_owner_reference_t
}
// authorization
namespace authorization {
typedef struct io_k8s_api_authorization_v1_local_subject_access_review_t v1_local_subject_access_review_t;
// io_k8s_api_authorization_v1_local_subject_access_review_t
typedef struct io_k8s_api_authorization_v1_self_subject_access_review_t v1_self_subject_access_review_t;
// io_k8s_api_authorization_v1_self_subject_access_review_t
typedef struct io_k8s_api_authorization_v1_self_subject_rules_review_t v1_self_subject_rules_review_t;
// io_k8s_api_authorization_v1_self_subject_rules_review_t
typedef struct io_k8s_api_authorization_v1_subject_access_review_t v1_subject_access_review_t;
// io_k8s_api_authorization_v1_subject_access_review_t
typedef struct io_k8s_api_authorization_v1beta1_local_subject_access_review_t v1beta1_local_subject_access_review_t;
// io_k8s_api_authorization_v1beta1_local_subject_access_review_t
typedef struct io_k8s_api_authorization_v1beta1_self_subject_access_review_t v1beta1_self_subject_access_review_t;
// io_k8s_api_authorization_v1beta1_self_subject_access_review_t
typedef struct io_k8s_api_authorization_v1beta1_self_subject_rules_review_t v1beta1_self_subject_rules_review_t;
// io_k8s_api_authorization_v1beta1_self_subject_rules_review_t
typedef struct io_k8s_api_authorization_v1beta1_subject_access_review_t v1beta1_subject_access_review_t;
// io_k8s_api_authorization_v1beta1_subject_access_review_t
typedef struct io_k8s_api_authorization_v1beta1_self_subject_rules_review_spec_t v1beta1_self_subject_rules_review_spec_t;
// io_k8s_api_authorization_v1beta1_self_subject_rules_review_spec_t
typedef struct io_k8s_api_authorization_v1beta1_subject_rules_review_status_t v1beta1_subject_rules_review_status_t;
// io_k8s_api_authorization_v1beta1_subject_rules_review_status_t
typedef struct io_k8s_api_authorization_v1beta1_non_resource_attributes_t v1beta1_non_resource_attributes_t;
// io_k8s_api_authorization_v1beta1_non_resource_attributes_t
typedef struct io_k8s_api_authorization_v1_resource_attributes_t v1_resource_attributes_t;
// io_k8s_api_authorization_v1_resource_attributes_t
typedef struct io_k8s_api_authorization_v1beta1_self_subject_access_review_spec_t v1beta1_self_subject_access_review_spec_t;
// io_k8s_api_authorization_v1beta1_self_subject_access_review_spec_t
typedef struct io_k8s_api_authorization_v1beta1_subject_access_review_status_t v1beta1_subject_access_review_status_t;
// io_k8s_api_authorization_v1beta1_subject_access_review_status_t
typedef struct io_k8s_api_authorization_v1_non_resource_attributes_t v1_non_resource_attributes_t;
// io_k8s_api_authorization_v1_non_resource_attributes_t
typedef struct io_k8s_api_authorization_v1_self_subject_access_review_spec_t v1_self_subject_access_review_spec_t;
// io_k8s_api_authorization_v1_self_subject_access_review_spec_t
typedef struct io_k8s_api_authorization_v1beta1_subject_access_review_spec_t v1beta1_subject_access_review_spec_t;
// io_k8s_api_authorization_v1beta1_subject_access_review_spec_t
typedef struct io_k8s_api_authorization_v1beta1_non_resource_rule_t v1beta1_non_resource_rule_t;
// io_k8s_api_authorization_v1beta1_non_resource_rule_t
typedef struct io_k8s_api_authorization_v1_non_resource_rule_t v1_non_resource_rule_t;
// io_k8s_api_authorization_v1_non_resource_rule_t
typedef struct io_k8s_api_authorization_v1_subject_access_review_status_t v1_subject_access_review_status_t;
// io_k8s_api_authorization_v1_subject_access_review_status_t
typedef struct io_k8s_api_authorization_v1beta1_resource_attributes_t v1beta1_resource_attributes_t;
// io_k8s_api_authorization_v1beta1_resource_attributes_t
typedef struct io_k8s_api_authorization_v1_subject_access_review_spec_t v1_subject_access_review_spec_t;
// io_k8s_api_authorization_v1_subject_access_review_spec_t
typedef struct io_k8s_api_authorization_v1beta1_resource_rule_t v1beta1_resource_rule_t;
// io_k8s_api_authorization_v1beta1_resource_rule_t
typedef struct io_k8s_api_authorization_v1_self_subject_rules_review_spec_t v1_self_subject_rules_review_spec_t;
// io_k8s_api_authorization_v1_self_subject_rules_review_spec_t
typedef struct io_k8s_api_authorization_v1_subject_rules_review_status_t v1_subject_rules_review_status_t;
// io_k8s_api_authorization_v1_subject_rules_review_status_t
typedef struct io_k8s_api_authorization_v1_resource_rule_t v1_resource_rule_t;
// io_k8s_api_authorization_v1_resource_rule_t
}
// events
namespace events {
typedef struct io_k8s_api_events_v1beta1_event_t v1beta1_event_t;
// io_k8s_api_events_v1beta1_event_t
typedef struct io_k8s_api_events_v1beta1_event_list_t v1beta1_event_list_t;
// io_k8s_api_events_v1beta1_event_list_t
typedef struct io_k8s_api_events_v1beta1_event_series_t v1beta1_event_series_t;
// io_k8s_api_events_v1beta1_event_series_t
typedef struct io_k8s_api_events_v1_event_list_t v1_event_list_t;;
// io_k8s_api_events_v1_event_list_t
typedef struct io_k8s_api_events_v1_event_t v1_event_t;;
// io_k8s_api_events_v1_event_t
typedef struct io_k8s_api_events_v1_event_series_t v1_event_series_t;;
// io_k8s_api_events_v1_event_series_t
}
// node
namespace node {
typedef struct io_k8s_api_node_v1beta1_runtime_class_t v1beta1_runtime_class_t;
// io_k8s_api_node_v1beta1_runtime_class_t
typedef struct io_k8s_api_node_v1beta1_runtime_class_list_t v1beta1_runtime_class_list_t;
// io_k8s_api_node_v1beta1_runtime_class_list_t
typedef struct io_k8s_api_node_v1alpha1_runtime_class_t v1alpha1_runtime_class_t;
// io_k8s_api_node_v1alpha1_runtime_class_t
typedef struct io_k8s_api_node_v1alpha1_runtime_class_list_t v1alpha1_runtime_class_list_t;
// io_k8s_api_node_v1alpha1_runtime_class_list_t
typedef struct io_k8s_api_node_v1_runtime_class_t v1_runtime_class_t;
// io_k8s_api_node_v1_runtime_class_t
typedef struct io_k8s_api_node_v1_runtime_class_list_t v1_runtime_class_list_t;
// io_k8s_api_node_v1_runtime_class_list_t
typedef struct io_k8s_api_node_v1beta1_scheduling_t v1beta1_scheduling_t;
// io_k8s_api_node_v1beta1_scheduling_t
typedef struct io_k8s_api_node_v1alpha1_scheduling_t v1alpha1_scheduling_t;
// io_k8s_api_node_v1alpha1_scheduling_t
typedef struct io_k8s_api_node_v1_scheduling_t v1_scheduling_t;
// io_k8s_api_node_v1_scheduling_t
typedef struct io_k8s_api_node_v1_overhead_t v1_overhead_t;
// io_k8s_api_node_v1_overhead_t
typedef struct io_k8s_api_node_v1beta1_overhead_t v1beta1_overhead_t;
// io_k8s_api_node_v1beta1_overhead_t
typedef struct io_k8s_api_node_v1alpha1_runtime_class_spec_t v1alpha1_runtime_class_spec_t;
// io_k8s_api_node_v1alpha1_runtime_class_spec_t
typedef struct io_k8s_api_node_v1alpha1_overhead_t v1alpha1_overhead_t;
// io_k8s_api_node_v1alpha1_overhead_t
}
// scheduling
namespace scheduling {
typedef struct io_k8s_api_scheduling_v1_priority_class_t v1_priority_class_t;
// io_k8s_api_scheduling_v1_priority_class_t
typedef struct io_k8s_api_scheduling_v1_priority_class_list_t v1_priority_class_list_t;
// io_k8s_api_scheduling_v1_priority_class_list_t
typedef struct io_k8s_api_scheduling_v1alpha1_priority_class_t v1alpha1_priority_class_t;
// io_k8s_api_scheduling_v1alpha1_priority_class_t
typedef struct io_k8s_api_scheduling_v1alpha1_priority_class_list_t v1alpha1_priority_class_list_t;
// io_k8s_api_scheduling_v1alpha1_priority_class_list_t
typedef struct io_k8s_api_scheduling_v1beta1_priority_class_t v1beta1_priority_class_t;
// io_k8s_api_scheduling_v1beta1_priority_class_t
typedef struct io_k8s_api_scheduling_v1beta1_priority_class_list_t v1beta1_priority_class_list_t;
// io_k8s_api_scheduling_v1beta1_priority_class_list_t
}
// certificates
namespace certificates {
typedef struct io_k8s_api_certificates_v1beta1_certificate_signing_request_t v1beta1_certificate_signing_request_t;
// io_k8s_api_certificates_v1beta1_certificate_signing_request_t
typedef struct io_k8s_api_certificates_v1beta1_certificate_signing_request_list_t v1beta1_certificate_signing_request_list_t;
// io_k8s_api_certificates_v1beta1_certificate_signing_request_list_t
typedef struct io_k8s_api_certificates_v1_certificate_signing_request_t v1_certificate_signing_request_t;
// io_k8s_api_certificates_v1_certificate_signing_request_t
typedef struct io_k8s_api_certificates_v1_certificate_signing_request_list_t v1_certificate_signing_request_list_t;
// io_k8s_api_certificates_v1_certificate_signing_request_list_t
typedef struct io_k8s_api_certificates_v1_certificate_signing_request_spec_t v1_certificate_signing_request_spec_t;
// io_k8s_api_certificates_v1_certificate_signing_request_spec_t
typedef struct io_k8s_api_certificates_v1_certificate_signing_request_status_t v1_certificate_signing_request_status_t;
// io_k8s_api_certificates_v1_certificate_signing_request_status_t
typedef struct io_k8s_api_certificates_v1beta1_certificate_signing_request_spec_t v1beta1_certificate_signing_request_spec_t;
// io_k8s_api_certificates_v1beta1_certificate_signing_request_spec_t
typedef struct io_k8s_api_certificates_v1beta1_certificate_signing_request_status_t v1beta1_certificate_signing_request_status_t;
// io_k8s_api_certificates_v1beta1_certificate_signing_request_status_t
typedef struct io_k8s_api_certificates_v1_certificate_signing_request_condition_t v1_certificate_signing_request_condition_t;
// io_k8s_api_certificates_v1_certificate_signing_request_condition_t
typedef struct io_k8s_api_certificates_v1beta1_certificate_signing_request_condition_t v1beta1_certificate_signing_request_condition_t;
// io_k8s_api_certificates_v1beta1_certificate_signing_request_condition_t
}
// apiserverinternal
namespace apiserverinternal {
typedef struct io_k8s_api_apiserverinternal_v1alpha1_storage_version_t v1alpha1_storage_version_t;
// io_k8s_api_apiserverinternal_v1alpha1_storage_version_t
typedef struct io_k8s_api_apiserverinternal_v1alpha1_storage_version_list_t v1alpha1_storage_version_list_t;
// io_k8s_api_apiserverinternal_v1alpha1_storage_version_list_t
typedef struct io_k8s_api_apiserverinternal_v1alpha1_storage_version_status_t v1alpha1_storage_version_status_t;
// io_k8s_api_apiserverinternal_v1alpha1_storage_version_status_t
typedef struct io_k8s_api_apiserverinternal_v1alpha1_storage_version_condition_t v1alpha1_storage_version_condition_t;
// io_k8s_api_apiserverinternal_v1alpha1_storage_version_condition_t
typedef struct io_k8s_api_apiserverinternal_v1alpha1_server_storage_version_t v1alpha1_server_storage_version_t;
// io_k8s_api_apiserverinternal_v1alpha1_server_storage_version_t
}
// apps
namespace apps {
typedef struct io_k8s_api_apps_v1_controller_revision_t v1_controller_revision_t;
// io_k8s_api_apps_v1_controller_revision_t
typedef struct io_k8s_api_apps_v1_daemon_set_t v1_daemon_set_t;
// io_k8s_api_apps_v1_daemon_set_t
typedef struct io_k8s_api_apps_v1_deployment_t v1_deployment_t;
// io_k8s_api_apps_v1_deployment_t
typedef struct io_k8s_api_apps_v1_replica_set_t v1_replica_set_t;
// io_k8s_api_apps_v1_replica_set_t
typedef struct io_k8s_api_apps_v1_stateful_set_t v1_stateful_set_t;
// io_k8s_api_apps_v1_stateful_set_t
typedef struct io_k8s_api_apps_v1_controller_revision_list_t v1_controller_revision_list_t;
// io_k8s_api_apps_v1_controller_revision_list_t
typedef struct io_k8s_api_apps_v1_daemon_set_list_t v1_daemon_set_list_t;
// io_k8s_api_apps_v1_daemon_set_list_t
typedef struct io_k8s_api_apps_v1_deployment_list_t v1_deployment_list_t;
// io_k8s_api_apps_v1_deployment_list_t
typedef struct io_k8s_api_apps_v1_replica_set_list_t v1_replica_set_list_t;
// io_k8s_api_apps_v1_replica_set_list_t
typedef struct io_k8s_api_apps_v1_stateful_set_list_t v1_stateful_set_list_t;
// io_k8s_api_apps_v1_stateful_set_list_t
typedef struct io_k8s_api_apps_v1_stateful_set_update_strategy_t v1_stateful_set_update_strategy_t;
// io_k8s_api_apps_v1_stateful_set_update_strategy_t
typedef struct io_k8s_api_apps_v1_rolling_update_stateful_set_strategy_t v1_rolling_update_stateful_set_strategy_t;
// io_k8s_api_apps_v1_rolling_update_stateful_set_strategy_t
typedef struct io_k8s_api_apps_v1_rolling_update_daemon_set_t v1_rolling_update_daemon_set_t;
// io_k8s_api_apps_v1_rolling_update_daemon_set_t
typedef struct io_k8s_api_apps_v1_deployment_spec_t v1_deployment_spec_t;
// io_k8s_api_apps_v1_deployment_spec_t
typedef struct io_k8s_api_apps_v1_deployment_strategy_t v1_deployment_strategy_t;
// io_k8s_api_apps_v1_deployment_strategy_t
typedef struct io_k8s_api_apps_v1_deployment_status_t v1_deployment_status_t;
// io_k8s_api_apps_v1_deployment_status_t
typedef struct io_k8s_api_apps_v1_deployment_condition_t v1_deployment_condition_t;
// io_k8s_api_apps_v1_deployment_condition_t
typedef struct io_k8s_api_apps_v1_daemon_set_spec_t v1_daemon_set_spec_t;
// io_k8s_api_apps_v1_daemon_set_spec_t
typedef struct io_k8s_api_apps_v1_daemon_set_status_t v1_daemon_set_status_t;
// io_k8s_api_apps_v1_daemon_set_status_t
typedef struct io_k8s_api_apps_v1_replica_set_spec_t v1_replica_set_spec_t;
// io_k8s_api_apps_v1_replica_set_spec_t
typedef struct io_k8s_api_apps_v1_daemon_set_update_strategy_t v1_daemon_set_update_strategy_t;
// io_k8s_api_apps_v1_daemon_set_update_strategy_t
typedef struct io_k8s_api_apps_v1_replica_set_condition_t v1_replica_set_condition_t;
// io_k8s_api_apps_v1_replica_set_condition_t
typedef struct io_k8s_api_apps_v1_replica_set_status_t v1_replica_set_status_t;
// io_k8s_api_apps_v1_replica_set_status_t
typedef struct io_k8s_api_apps_v1_stateful_set_condition_t v1_stateful_set_condition_t;
// io_k8s_api_apps_v1_stateful_set_condition_t
typedef struct io_k8s_api_apps_v1_rolling_update_deployment_t v1_rolling_update_deployment_t;
// io_k8s_api_apps_v1_rolling_update_deployment_t
typedef struct io_k8s_api_apps_v1_stateful_set_spec_t v1_stateful_set_spec_t;
// io_k8s_api_apps_v1_stateful_set_spec_t
typedef struct io_k8s_api_apps_v1_stateful_set_status_t v1_stateful_set_status_t;
// io_k8s_api_apps_v1_stateful_set_status_t
typedef struct io_k8s_api_apps_v1_daemon_set_condition_t v1_daemon_set_condition_t;
// io_k8s_api_apps_v1_daemon_set_condition_t
}
// authentication
namespace authentication {
typedef struct io_k8s_api_authentication_v1_token_review_t v1_token_review_t;
// io_k8s_api_authentication_v1_token_review_t
typedef struct io_k8s_api_authentication_v1_token_request_t v1_token_request_t;
// io_k8s_api_authentication_v1_token_request_t
typedef struct io_k8s_api_authentication_v1beta1_token_review_t v1beta1_token_review_t;
// io_k8s_api_authentication_v1beta1_token_review_t
typedef struct io_k8s_api_authentication_v1_token_review_spec_t v1_token_review_spec_t;
// io_k8s_api_authentication_v1_token_review_spec_t
typedef struct io_k8s_api_authentication_v1_token_review_status_t v1_token_review_status_t;
// io_k8s_api_authentication_v1_token_review_status_t
typedef struct io_k8s_api_authentication_v1_token_request_spec_t v1_token_request_spec_t;
// io_k8s_api_authentication_v1_token_request_spec_t
typedef struct io_k8s_api_authentication_v1_bound_object_reference_t v1_bound_object_reference_t;
// io_k8s_api_authentication_v1_bound_object_reference_t
typedef struct io_k8s_api_authentication_v1_user_info_t v1_user_info_t;
// io_k8s_api_authentication_v1_user_info_t
typedef struct io_k8s_api_authentication_v1beta1_token_review_status_t v1beta1_token_review_status_t;
// io_k8s_api_authentication_v1beta1_token_review_status_t
typedef struct io_k8s_api_authentication_v1beta1_user_info_t v1beta1_user_info_t;
// io_k8s_api_authentication_v1beta1_user_info_t
typedef struct io_k8s_api_authentication_v1_token_request_status_t v1_token_request_status_t;
// io_k8s_api_authentication_v1_token_request_status_t
typedef struct io_k8s_api_authentication_v1beta1_token_review_spec_t v1beta1_token_review_spec_t;
// io_k8s_api_authentication_v1beta1_token_review_spec_t
}
// autoscaling
namespace autoscaling {
typedef struct io_k8s_api_autoscaling_v1_horizontal_pod_autoscaler_t v1_horizontal_pod_autoscaler_t;
// io_k8s_api_autoscaling_v1_horizontal_pod_autoscaler_t
typedef struct io_k8s_api_autoscaling_v1_horizontal_pod_autoscaler_list_t v1_horizontal_pod_autoscaler_list_t;
// io_k8s_api_autoscaling_v1_horizontal_pod_autoscaler_list_t
typedef struct io_k8s_api_autoscaling_v2beta2_horizontal_pod_autoscaler_t v2beta2_horizontal_pod_autoscaler_t;
// io_k8s_api_autoscaling_v2beta2_horizontal_pod_autoscaler_t
typedef struct io_k8s_api_autoscaling_v2beta2_horizontal_pod_autoscaler_list_t v2beta2_horizontal_pod_autoscaler_list_t;
// io_k8s_api_autoscaling_v2beta2_horizontal_pod_autoscaler_list_t
typedef struct io_k8s_api_autoscaling_v1_scale_t v1_scale_t;
// io_k8s_api_autoscaling_v1_scale_t
typedef struct io_k8s_api_autoscaling_v2beta1_horizontal_pod_autoscaler_t v2beta1_horizontal_pod_autoscaler_t;
// io_k8s_api_autoscaling_v2beta1_horizontal_pod_autoscaler_t
typedef struct io_k8s_api_autoscaling_v2beta1_horizontal_pod_autoscaler_list_t v2beta1_horizontal_pod_autoscaler_list_t;
// io_k8s_api_autoscaling_v2beta1_horizontal_pod_autoscaler_list_t
typedef struct io_k8s_api_autoscaling_v2beta1_metric_spec_t v2beta1_metric_spec_t;
// io_k8s_api_autoscaling_v2beta1_metric_spec_t
typedef struct io_k8s_api_autoscaling_v2beta1_container_resource_metric_source_t v2beta1_container_resource_metric_source_t;
// io_k8s_api_autoscaling_v2beta1_container_resource_metric_source_t
typedef struct io_k8s_api_autoscaling_v2beta1_external_metric_source_t v2beta1_external_metric_source_t;
// io_k8s_api_autoscaling_v2beta1_external_metric_source_t
typedef struct io_k8s_api_autoscaling_v2beta1_object_metric_source_t v2beta1_object_metric_source_t;
// io_k8s_api_autoscaling_v2beta1_object_metric_source_t
typedef struct io_k8s_api_autoscaling_v2beta1_pods_metric_source_t v2beta1_pods_metric_source_t;
// io_k8s_api_autoscaling_v2beta1_pods_metric_source_t
typedef struct io_k8s_api_autoscaling_v2beta1_resource_metric_source_t v2beta1_resource_metric_source_t;
// io_k8s_api_autoscaling_v2beta1_resource_metric_source_t
typedef struct io_k8s_api_autoscaling_v1_horizontal_pod_autoscaler_status_t v1_horizontal_pod_autoscaler_status_t;
// io_k8s_api_autoscaling_v1_horizontal_pod_autoscaler_status_t
typedef struct io_k8s_api_autoscaling_v2beta1_resource_metric_status_t v2beta1_resource_metric_status_t;
// io_k8s_api_autoscaling_v2beta1_resource_metric_status_t
typedef struct io_k8s_api_autoscaling_v2beta2_horizontal_pod_autoscaler_condition_t v2beta2_horizontal_pod_autoscaler_condition_t;
// io_k8s_api_autoscaling_v2beta2_horizontal_pod_autoscaler_condition_t
typedef struct io_k8s_api_autoscaling_v2beta1_horizontal_pod_autoscaler_condition_t v2beta1_horizontal_pod_autoscaler_condition_t;
// io_k8s_api_autoscaling_v2beta1_horizontal_pod_autoscaler_condition_t
typedef struct io_k8s_api_autoscaling_v2beta1_horizontal_pod_autoscaler_status_t v2beta1_horizontal_pod_autoscaler_status_t;
// io_k8s_api_autoscaling_v2beta1_horizontal_pod_autoscaler_status_t
typedef struct io_k8s_api_autoscaling_v2beta2_metric_identifier_t v2beta2_metric_identifier_t;
// io_k8s_api_autoscaling_v2beta2_metric_identifier_t
typedef struct io_k8s_api_autoscaling_v2beta2_object_metric_source_t v2beta2_object_metric_source_t;
// io_k8s_api_autoscaling_v2beta2_object_metric_source_t
typedef struct io_k8s_api_autoscaling_v2beta2_cross_version_object_reference_t v2beta2_cross_version_object_reference_t;
// io_k8s_api_autoscaling_v2beta2_cross_version_object_reference_t
typedef struct io_k8s_api_autoscaling_v2beta2_metric_target_t v2beta2_metric_target_t;
// io_k8s_api_autoscaling_v2beta2_metric_target_t
typedef struct io_k8s_api_autoscaling_v2beta2_horizontal_pod_autoscaler_spec_t v2beta2_horizontal_pod_autoscaler_spec_t;
// io_k8s_api_autoscaling_v2beta2_horizontal_pod_autoscaler_spec_t
typedef struct io_k8s_api_autoscaling_v2beta2_horizontal_pod_autoscaler_behavior_t v2beta2_horizontal_pod_autoscaler_behavior_t;
// io_k8s_api_autoscaling_v2beta2_horizontal_pod_autoscaler_behavior_t
typedef struct io_k8s_api_autoscaling_v2beta1_external_metric_status_t v2beta1_external_metric_status_t;
// io_k8s_api_autoscaling_v2beta1_external_metric_status_t
typedef struct io_k8s_api_autoscaling_v2beta1_cross_version_object_reference_t v2beta1_cross_version_object_reference_t;
// io_k8s_api_autoscaling_v2beta1_cross_version_object_reference_t
typedef struct io_k8s_api_autoscaling_v1_scale_spec_t v1_scale_spec_t;
// io_k8s_api_autoscaling_v1_scale_spec_t
typedef struct io_k8s_api_autoscaling_v1_scale_status_t v1_scale_status_t;
// io_k8s_api_autoscaling_v1_scale_status_t
typedef struct io_k8s_api_autoscaling_v2beta2_metric_spec_t v2beta2_metric_spec_t;
// io_k8s_api_autoscaling_v2beta2_metric_spec_t
typedef struct io_k8s_api_autoscaling_v2beta2_container_resource_metric_source_t v2beta2_container_resource_metric_source_t;
// io_k8s_api_autoscaling_v2beta2_container_resource_metric_source_t
typedef struct io_k8s_api_autoscaling_v2beta2_external_metric_source_t v2beta2_external_metric_source_t;
// io_k8s_api_autoscaling_v2beta2_external_metric_source_t
typedef struct io_k8s_api_autoscaling_v2beta2_pods_metric_source_t v2beta2_pods_metric_source_t;
// io_k8s_api_autoscaling_v2beta2_pods_metric_source_t
typedef struct io_k8s_api_autoscaling_v2beta2_resource_metric_source_t v2beta2_resource_metric_source_t;
// io_k8s_api_autoscaling_v2beta2_resource_metric_source_t
typedef struct io_k8s_api_autoscaling_v2beta2_pods_metric_status_t v2beta2_pods_metric_status_t;
// io_k8s_api_autoscaling_v2beta2_pods_metric_status_t
typedef struct io_k8s_api_autoscaling_v2beta2_metric_value_status_t v2beta2_metric_value_status_t;
// io_k8s_api_autoscaling_v2beta2_metric_value_status_t
typedef struct io_k8s_api_autoscaling_v2beta1_object_metric_status_t v2beta1_object_metric_status_t;
// io_k8s_api_autoscaling_v2beta1_object_metric_status_t
typedef struct io_k8s_api_autoscaling_v2beta1_container_resource_metric_status_t v2beta1_container_resource_metric_status_t;
// io_k8s_api_autoscaling_v2beta1_container_resource_metric_status_t
typedef struct io_k8s_api_autoscaling_v2beta1_metric_status_t v2beta1_metric_status_t;
// io_k8s_api_autoscaling_v2beta1_metric_status_t
typedef struct io_k8s_api_autoscaling_v2beta1_pods_metric_status_t v2beta1_pods_metric_status_t;
// io_k8s_api_autoscaling_v2beta1_pods_metric_status_t
typedef struct io_k8s_api_autoscaling_v2beta2_horizontal_pod_autoscaler_status_t v2beta2_horizontal_pod_autoscaler_status_t;
// io_k8s_api_autoscaling_v2beta2_horizontal_pod_autoscaler_status_t
typedef struct io_k8s_api_autoscaling_v2beta2_object_metric_status_t v2beta2_object_metric_status_t;
// io_k8s_api_autoscaling_v2beta2_object_metric_status_t
typedef struct io_k8s_api_autoscaling_v1_horizontal_pod_autoscaler_spec_t v1_horizontal_pod_autoscaler_spec_t;
// io_k8s_api_autoscaling_v1_horizontal_pod_autoscaler_spec_t
typedef struct io_k8s_api_autoscaling_v2beta1_horizontal_pod_autoscaler_spec_t v2beta1_horizontal_pod_autoscaler_spec_t;
// io_k8s_api_autoscaling_v2beta1_horizontal_pod_autoscaler_spec_t
typedef struct io_k8s_api_autoscaling_v2beta2_hpa_scaling_rules_t v2beta2_hpa_scaling_rules_t;
// io_k8s_api_autoscaling_v2beta2_hpa_scaling_rules_t
typedef struct io_k8s_api_autoscaling_v2beta2_external_metric_status_t v2beta2_external_metric_status_t;
// io_k8s_api_autoscaling_v2beta2_external_metric_status_t
typedef struct io_k8s_api_autoscaling_v1_cross_version_object_reference_t v1_cross_version_object_reference_t;
// io_k8s_api_autoscaling_v1_cross_version_object_reference_t
typedef struct io_k8s_api_autoscaling_v2beta2_container_resource_metric_status_t v2beta2_container_resource_metric_status_t;
// io_k8s_api_autoscaling_v2beta2_container_resource_metric_status_t
typedef struct io_k8s_api_autoscaling_v2beta2_resource_metric_status_t v2beta2_resource_metric_status_t;
// io_k8s_api_autoscaling_v2beta2_resource_metric_status_t
typedef struct io_k8s_api_autoscaling_v2beta2_metric_status_t v2beta2_metric_status_t;
// io_k8s_api_autoscaling_v2beta2_metric_status_t
typedef struct io_k8s_api_autoscaling_v2beta2_hpa_scaling_policy_t v2beta2_hpa_scaling_policy_t;
// io_k8s_api_autoscaling_v2beta2_hpa_scaling_policy_t
}
// batch
namespace batch {
typedef struct io_k8s_api_batch_v1_job_t v1_job_t;
// io_k8s_api_batch_v1_job_t
typedef struct io_k8s_api_batch_v1_job_list_t v1_job_list_t;
// io_k8s_api_batch_v1_job_list_t
typedef struct io_k8s_api_batch_v1beta1_cron_job_t v1beta1_cron_job_t;
// io_k8s_api_batch_v1beta1_cron_job_t
typedef struct io_k8s_api_batch_v1beta1_cron_job_list_t v1beta1_cron_job_list_t;
// io_k8s_api_batch_v1beta1_cron_job_list_t
typedef struct io_k8s_api_batch_v1_job_condition_t v1_job_condition_t;
// io_k8s_api_batch_v1_job_condition_t
typedef struct io_k8s_api_batch_v1beta1_cron_job_status_t v1beta1_cron_job_status_t;
// io_k8s_api_batch_v1beta1_cron_job_status_t
typedef struct io_k8s_api_batch_v1_job_spec_t v1_job_spec_t;
// io_k8s_api_batch_v1_job_spec_t
typedef struct io_k8s_api_batch_v1_job_status_t v1_job_status_t;
// io_k8s_api_batch_v1_job_status_t
typedef struct io_k8s_api_batch_v1beta1_cron_job_spec_t v1beta1_cron_job_spec_t;
// io_k8s_api_batch_v1beta1_cron_job_spec_t
typedef struct io_k8s_api_batch_v1beta1_job_template_spec_t v1beta1_job_template_spec_t;
// io_k8s_api_batch_v1beta1_job_template_spec_t
}
// coordination
namespace coordination {
typedef struct io_k8s_api_coordination_v1beta1_lease_t v1beta1_lease_t;
// io_k8s_api_coordination_v1beta1_lease_t
typedef struct io_k8s_api_coordination_v1beta1_lease_list_t v1beta1_lease_list_t;
// io_k8s_api_coordination_v1beta1_lease_list_t
typedef struct io_k8s_api_coordination_v1_lease_t v1_lease_t;
// io_k8s_api_coordination_v1_lease_t
typedef struct io_k8s_api_coordination_v1_lease_list_t v1_lease_list_t;
// io_k8s_api_coordination_v1_lease_list_t
typedef struct io_k8s_api_coordination_v1_lease_spec_t v1_lease_spec_t;
// io_k8s_api_coordination_v1_lease_spec_t
typedef struct io_k8s_api_coordination_v1beta1_lease_spec_t v1beta1_lease_spec_t;
// io_k8s_api_coordination_v1beta1_lease_spec_t
}
// rbac
namespace rbac {
typedef struct io_k8s_api_rbac_v1alpha1_cluster_role_t v1alpha1_cluster_role_t;
// io_k8s_api_rbac_v1alpha1_cluster_role_t
typedef struct io_k8s_api_rbac_v1alpha1_cluster_role_binding_t v1alpha1_cluster_role_binding_t;
// io_k8s_api_rbac_v1alpha1_cluster_role_binding_t
typedef struct io_k8s_api_rbac_v1alpha1_role_t v1alpha1_role_t;
// io_k8s_api_rbac_v1alpha1_role_t
typedef struct io_k8s_api_rbac_v1alpha1_role_binding_t v1alpha1_role_binding_t;
// io_k8s_api_rbac_v1alpha1_role_binding_t
typedef struct io_k8s_api_rbac_v1alpha1_cluster_role_list_t v1alpha1_cluster_role_list_t;
// io_k8s_api_rbac_v1alpha1_cluster_role_list_t
typedef struct io_k8s_api_rbac_v1alpha1_cluster_role_binding_list_t v1alpha1_cluster_role_binding_list_t;
// io_k8s_api_rbac_v1alpha1_cluster_role_binding_list_t
typedef struct io_k8s_api_rbac_v1alpha1_role_list_t v1alpha1_role_list_t;
// io_k8s_api_rbac_v1alpha1_role_list_t
typedef struct io_k8s_api_rbac_v1alpha1_role_binding_list_t v1alpha1_role_binding_list_t;
// io_k8s_api_rbac_v1alpha1_role_binding_list_t
typedef struct io_k8s_api_rbac_v1_cluster_role_t v1_cluster_role_t;
// io_k8s_api_rbac_v1_cluster_role_t
typedef struct io_k8s_api_rbac_v1_cluster_role_binding_t v1_cluster_role_binding_t;
// io_k8s_api_rbac_v1_cluster_role_binding_t
typedef struct io_k8s_api_rbac_v1_role_t v1_role_t;
// io_k8s_api_rbac_v1_role_t
typedef struct io_k8s_api_rbac_v1_role_binding_t v1_role_binding_t;
// io_k8s_api_rbac_v1_role_binding_t
typedef struct io_k8s_api_rbac_v1_cluster_role_list_t v1_cluster_role_list_t;
// io_k8s_api_rbac_v1_cluster_role_list_t
typedef struct io_k8s_api_rbac_v1_cluster_role_binding_list_t v1_cluster_role_binding_list_t;
// io_k8s_api_rbac_v1_cluster_role_binding_list_t
typedef struct io_k8s_api_rbac_v1_role_list_t v1_role_list_t;
// io_k8s_api_rbac_v1_role_list_t
typedef struct io_k8s_api_rbac_v1_role_binding_list_t v1_role_binding_list_t;
// io_k8s_api_rbac_v1_role_binding_list_t
typedef struct io_k8s_api_rbac_v1beta1_cluster_role_t v1beta1_cluster_role_t;
// io_k8s_api_rbac_v1beta1_cluster_role_t
typedef struct io_k8s_api_rbac_v1beta1_cluster_role_binding_t v1beta1_cluster_role_binding_t;
// io_k8s_api_rbac_v1beta1_cluster_role_binding_t
typedef struct io_k8s_api_rbac_v1beta1_role_t v1beta1_role_t;
// io_k8s_api_rbac_v1beta1_role_t
typedef struct io_k8s_api_rbac_v1beta1_role_binding_t v1beta1_role_binding_t;
// io_k8s_api_rbac_v1beta1_role_binding_t
typedef struct io_k8s_api_rbac_v1beta1_cluster_role_list_t v1beta1_cluster_role_list_t;
// io_k8s_api_rbac_v1beta1_cluster_role_list_t
typedef struct io_k8s_api_rbac_v1beta1_cluster_role_binding_list_t v1beta1_cluster_role_binding_list_t;
// io_k8s_api_rbac_v1beta1_cluster_role_binding_list_t
typedef struct io_k8s_api_rbac_v1beta1_role_list_t v1beta1_role_list_t;
// io_k8s_api_rbac_v1beta1_role_list_t
typedef struct io_k8s_api_rbac_v1beta1_role_binding_list_t v1beta1_role_binding_list_t;
// io_k8s_api_rbac_v1beta1_role_binding_list_t
typedef struct io_k8s_api_rbac_v1beta1_aggregation_rule_t v1beta1_aggregation_rule_t;
// io_k8s_api_rbac_v1beta1_aggregation_rule_t
typedef struct io_k8s_api_rbac_v1alpha1_role_ref_t v1alpha1_role_ref_t;
// io_k8s_api_rbac_v1alpha1_role_ref_t
typedef struct io_k8s_api_rbac_v1beta1_role_ref_t v1beta1_role_ref_t;
// io_k8s_api_rbac_v1beta1_role_ref_t
typedef struct io_k8s_api_rbac_v1_aggregation_rule_t v1_aggregation_rule_t;
// io_k8s_api_rbac_v1_aggregation_rule_t
typedef struct io_k8s_api_rbac_v1_role_ref_t v1_role_ref_t;
// io_k8s_api_rbac_v1_role_ref_t
typedef struct io_k8s_api_rbac_v1beta1_subject_t v1beta1_subject_t;
// io_k8s_api_rbac_v1beta1_subject_t
typedef struct io_k8s_api_rbac_v1alpha1_aggregation_rule_t v1alpha1_aggregation_rule_t;
// io_k8s_api_rbac_v1alpha1_aggregation_rule_t
typedef struct io_k8s_api_rbac_v1alpha1_subject_t v1alpha1_subject_t;
// io_k8s_api_rbac_v1alpha1_subject_t
typedef struct io_k8s_api_rbac_v1beta1_policy_rule_t v1beta1_policy_rule_t;
// io_k8s_api_rbac_v1beta1_policy_rule_t
typedef struct io_k8s_api_rbac_v1_subject_t v1_subject_t;
// io_k8s_api_rbac_v1_subject_t
typedef struct io_k8s_api_rbac_v1alpha1_policy_rule_t v1alpha1_policy_rule_t;
// io_k8s_api_rbac_v1alpha1_policy_rule_t
typedef struct io_k8s_api_rbac_v1_policy_rule_t v1_policy_rule_t;
// io_k8s_api_rbac_v1_policy_rule_t
}
// admissionregistration
namespace admissionregistration {
typedef struct io_k8s_api_admissionregistration_v1beta1_mutating_webhook_configuration_t v1beta1_mutating_webhook_configuration_t;
// io_k8s_api_admissionregistration_v1beta1_mutating_webhook_configuration_t
typedef struct io_k8s_api_admissionregistration_v1beta1_validating_webhook_configuration_t v1beta1_validating_webhook_configuration_t;
// io_k8s_api_admissionregistration_v1beta1_validating_webhook_configuration_t
typedef struct io_k8s_api_admissionregistration_v1beta1_mutating_webhook_configuration_list_t v1beta1_mutating_webhook_configuration_list_t;
// io_k8s_api_admissionregistration_v1beta1_mutating_webhook_configuration_list_t
typedef struct io_k8s_api_admissionregistration_v1beta1_validating_webhook_configuration_list_t v1beta1_validating_webhook_configuration_list_t;
// io_k8s_api_admissionregistration_v1beta1_validating_webhook_configuration_list_t
typedef struct io_k8s_api_admissionregistration_v1_mutating_webhook_configuration_t v1_mutating_webhook_configuration_t;
// io_k8s_api_admissionregistration_v1_mutating_webhook_configuration_t
typedef struct io_k8s_api_admissionregistration_v1_validating_webhook_configuration_t v1_validating_webhook_configuration_t;
// io_k8s_api_admissionregistration_v1_validating_webhook_configuration_t
typedef struct io_k8s_api_admissionregistration_v1_mutating_webhook_configuration_list_t v1_mutating_webhook_configuration_list_t;
// io_k8s_api_admissionregistration_v1_mutating_webhook_configuration_list_t
typedef struct io_k8s_api_admissionregistration_v1_validating_webhook_configuration_list_t v1_validating_webhook_configuration_list_t;
// io_k8s_api_admissionregistration_v1_validating_webhook_configuration_list_t
typedef struct io_k8s_api_admissionregistration_v1_webhook_client_config_t v1_webhook_client_config_t;
// io_k8s_api_admissionregistration_v1_webhook_client_config_t
typedef struct io_k8s_api_admissionregistration_v1_service_reference_t v1_service_reference_t;
// io_k8s_api_admissionregistration_v1_service_reference_t
typedef struct io_k8s_api_admissionregistration_v1beta1_validating_webhook_t v1beta1_validating_webhook_t;
// io_k8s_api_admissionregistration_v1beta1_validating_webhook_t
typedef struct io_k8s_api_admissionregistration_v1beta1_webhook_client_config_t v1beta1_webhook_client_config_t;
// io_k8s_api_admissionregistration_v1beta1_webhook_client_config_t
typedef struct io_k8s_api_admissionregistration_v1beta1_mutating_webhook_t v1beta1_mutating_webhook_t;
// io_k8s_api_admissionregistration_v1beta1_mutating_webhook_t
typedef struct io_k8s_api_admissionregistration_v1beta1_service_reference_t v1beta1_service_reference_t;
// io_k8s_api_admissionregistration_v1beta1_service_reference_t
typedef struct io_k8s_api_admissionregistration_v1_validating_webhook_t v1_validating_webhook_t;
// io_k8s_api_admissionregistration_v1_validating_webhook_t
typedef struct io_k8s_api_admissionregistration_v1_rule_with_operations_t v1_rule_with_operations_t;
// io_k8s_api_admissionregistration_v1_rule_with_operations_t
typedef struct io_k8s_api_admissionregistration_v1_mutating_webhook_t v1_mutating_webhook_t;
// io_k8s_api_admissionregistration_v1_mutating_webhook_t
typedef struct io_k8s_api_admissionregistration_v1beta1_rule_with_operations_t v1beta1_rule_with_operations_t;
// io_k8s_api_admissionregistration_v1beta1_rule_with_operations_t
}
// apiserver
namespace apiserver {
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_definition_t pkg_apis_apiextensions_v1_custom_resource_definition_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_definition_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_definition_list_t pkg_apis_apiextensions_v1_custom_resource_definition_list_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_definition_list_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_definition_t pkg_apis_apiextensions_v1beta1_custom_resource_definition_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_definition_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_definition_list_t pkg_apis_apiextensions_v1beta1_custom_resource_definition_list_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_definition_list_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_service_reference_t pkg_apis_apiextensions_v1_service_reference_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_service_reference_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_definition_spec_t pkg_apis_apiextensions_v1beta1_custom_resource_definition_spec_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_definition_spec_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_conversion_t pkg_apis_apiextensions_v1beta1_custom_resource_conversion_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_conversion_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_definition_names_t pkg_apis_apiextensions_v1beta1_custom_resource_definition_names_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_definition_names_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_subresources_t pkg_apis_apiextensions_v1beta1_custom_resource_subresources_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_subresources_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_validation_t pkg_apis_apiextensions_v1beta1_custom_resource_validation_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_validation_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_webhook_conversion_t pkg_apis_apiextensions_v1_webhook_conversion_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_webhook_conversion_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_webhook_client_config_t pkg_apis_apiextensions_v1_webhook_client_config_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_webhook_client_config_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_service_reference_t pkg_apis_apiextensions_v1beta1_service_reference_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_service_reference_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_json_schema_props_t pkg_apis_apiextensions_v1beta1_json_schema_props_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_json_schema_props_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_validation_t pkg_apis_apiextensions_v1_custom_resource_validation_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_validation_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_json_schema_props_t pkg_apis_apiextensions_v1_json_schema_props_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_json_schema_props_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_definition_version_t pkg_apis_apiextensions_v1_custom_resource_definition_version_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_definition_version_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_subresources_t pkg_apis_apiextensions_v1_custom_resource_subresources_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_subresources_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_webhook_client_config_t pkg_apis_apiextensions_v1beta1_webhook_client_config_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_webhook_client_config_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_subresource_scale_t pkg_apis_apiextensions_v1_custom_resource_subresource_scale_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_subresource_scale_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_definition_status_t pkg_apis_apiextensions_v1_custom_resource_definition_status_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_definition_status_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_definition_names_t pkg_apis_apiextensions_v1_custom_resource_definition_names_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_definition_names_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_column_definition_t pkg_apis_apiextensions_v1_custom_resource_column_definition_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_column_definition_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_external_documentation_t pkg_apis_apiextensions_v1beta1_external_documentation_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_external_documentation_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_subresource_scale_t pkg_apis_apiextensions_v1beta1_custom_resource_subresource_scale_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_subresource_scale_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_definition_version_t pkg_apis_apiextensions_v1beta1_custom_resource_definition_version_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_definition_version_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_conversion_t pkg_apis_apiextensions_v1_custom_resource_conversion_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_conversion_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_definition_condition_t pkg_apis_apiextensions_v1_custom_resource_definition_condition_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_definition_condition_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_definition_status_t pkg_apis_apiextensions_v1beta1_custom_resource_definition_status_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_definition_status_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_definition_spec_t pkg_apis_apiextensions_v1_custom_resource_definition_spec_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_definition_spec_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_external_documentation_t pkg_apis_apiextensions_v1_external_documentation_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_external_documentation_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_definition_condition_t pkg_apis_apiextensions_v1beta1_custom_resource_definition_condition_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_definition_condition_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_column_definition_t pkg_apis_apiextensions_v1beta1_custom_resource_column_definition_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_column_definition_t
}
// flowcontrol
namespace flowcontrol {
typedef struct io_k8s_api_flowcontrol_v1beta1_flow_schema_t v1beta1_flow_schema_t;
// io_k8s_api_flowcontrol_v1beta1_flow_schema_t
typedef struct io_k8s_api_flowcontrol_v1beta1_priority_level_configuration_t v1beta1_priority_level_configuration_t;
// io_k8s_api_flowcontrol_v1beta1_priority_level_configuration_t
typedef struct io_k8s_api_flowcontrol_v1beta1_flow_schema_list_t v1beta1_flow_schema_list_t;
// io_k8s_api_flowcontrol_v1beta1_flow_schema_list_t
typedef struct io_k8s_api_flowcontrol_v1beta1_priority_level_configuration_list_t v1beta1_priority_level_configuration_list_t;
// io_k8s_api_flowcontrol_v1beta1_priority_level_configuration_list_t
typedef struct io_k8s_api_flowcontrol_v1beta1_limit_response_t v1beta1_limit_response_t;
// io_k8s_api_flowcontrol_v1beta1_limit_response_t
typedef struct io_k8s_api_flowcontrol_v1beta1_queuing_configuration_t v1beta1_queuing_configuration_t;
// io_k8s_api_flowcontrol_v1beta1_queuing_configuration_t
typedef struct io_k8s_api_flowcontrol_v1beta1_non_resource_policy_rule_t v1beta1_non_resource_policy_rule_t;
// io_k8s_api_flowcontrol_v1beta1_non_resource_policy_rule_t
typedef struct io_k8s_api_flowcontrol_v1beta1_flow_schema_spec_t v1beta1_flow_schema_spec_t;
// io_k8s_api_flowcontrol_v1beta1_flow_schema_spec_t
typedef struct io_k8s_api_flowcontrol_v1beta1_flow_schema_status_t v1beta1_flow_schema_status_t;
// io_k8s_api_flowcontrol_v1beta1_flow_schema_status_t
typedef struct io_k8s_api_flowcontrol_v1beta1_priority_level_configuration_condition_t v1beta1_priority_level_configuration_condition_t;
// io_k8s_api_flowcontrol_v1beta1_priority_level_configuration_condition_t
typedef struct io_k8s_api_flowcontrol_v1beta1_service_account_subject_t v1beta1_service_account_subject_t;
// io_k8s_api_flowcontrol_v1beta1_service_account_subject_t
typedef struct io_k8s_api_flowcontrol_v1beta1_resource_policy_rule_t v1beta1_resource_policy_rule_t;
// io_k8s_api_flowcontrol_v1beta1_resource_policy_rule_t
typedef struct io_k8s_api_flowcontrol_v1beta1_group_subject_t v1beta1_group_subject_t;
// io_k8s_api_flowcontrol_v1beta1_group_subject_t
typedef struct io_k8s_api_flowcontrol_v1beta1_user_subject_t v1beta1_user_subject_t;
// io_k8s_api_flowcontrol_v1beta1_user_subject_t
typedef struct io_k8s_api_flowcontrol_v1beta1_flow_schema_condition_t v1beta1_flow_schema_condition_t;
// io_k8s_api_flowcontrol_v1beta1_flow_schema_condition_t
typedef struct io_k8s_api_flowcontrol_v1beta1_flow_distinguisher_method_t v1beta1_flow_distinguisher_method_t;
// io_k8s_api_flowcontrol_v1beta1_flow_distinguisher_method_t
typedef struct io_k8s_api_flowcontrol_v1beta1_priority_level_configuration_spec_t v1beta1_priority_level_configuration_spec_t;
// io_k8s_api_flowcontrol_v1beta1_priority_level_configuration_spec_t
typedef struct io_k8s_api_flowcontrol_v1beta1_priority_level_configuration_status_t v1beta1_priority_level_configuration_status_t;
// io_k8s_api_flowcontrol_v1beta1_priority_level_configuration_status_t
typedef struct io_k8s_api_flowcontrol_v1beta1_priority_level_configuration_reference_t v1beta1_priority_level_configuration_reference_t;
// io_k8s_api_flowcontrol_v1beta1_priority_level_configuration_reference_t
typedef struct io_k8s_api_flowcontrol_v1beta1_policy_rules_with_subjects_t v1beta1_policy_rules_with_subjects_t;
// io_k8s_api_flowcontrol_v1beta1_policy_rules_with_subjects_t
typedef struct io_k8s_api_flowcontrol_v1beta1_limited_priority_level_configuration_t v1beta1_limited_priority_level_configuration_t;
// io_k8s_api_flowcontrol_v1beta1_limited_priority_level_configuration_t
typedef struct io_k8s_api_flowcontrol_v1beta1_subject_t v1beta1_subject_t;;
// io_k8s_api_flowcontrol_v1beta1_subject_t
}
// pkg
namespace pkg {
typedef struct io_k8s_apimachinery_pkg_version_info_t version_info_t;
// io_k8s_apimachinery_pkg_version_info_t
}
// extensions
namespace extensions {
typedef struct io_k8s_api_extensions_v1beta1_ingress_t v1beta1_ingress_t;
// io_k8s_api_extensions_v1beta1_ingress_t
typedef struct io_k8s_api_extensions_v1beta1_ingress_list_t v1beta1_ingress_list_t;
// io_k8s_api_extensions_v1beta1_ingress_list_t
typedef struct io_k8s_api_extensions_v1beta1_ingress_tls_t v1beta1_ingress_tls_t;
// io_k8s_api_extensions_v1beta1_ingress_tls_t
typedef struct io_k8s_api_extensions_v1beta1_http_ingress_rule_value_t v1beta1_http_ingress_rule_value_t;
// io_k8s_api_extensions_v1beta1_http_ingress_rule_value_t
typedef struct io_k8s_api_extensions_v1beta1_http_ingress_path_t v1beta1_http_ingress_path_t;
// io_k8s_api_extensions_v1beta1_http_ingress_path_t
typedef struct io_k8s_api_extensions_v1beta1_ingress_backend_t v1beta1_ingress_backend_t;
// io_k8s_api_extensions_v1beta1_ingress_backend_t
typedef struct io_k8s_api_extensions_v1beta1_ingress_spec_t v1beta1_ingress_spec_t;
// io_k8s_api_extensions_v1beta1_ingress_spec_t
typedef struct io_k8s_api_extensions_v1beta1_ingress_rule_t v1beta1_ingress_rule_t;
// io_k8s_api_extensions_v1beta1_ingress_rule_t
typedef struct io_k8s_api_extensions_v1beta1_ingress_status_t v1beta1_ingress_status_t;
// io_k8s_api_extensions_v1beta1_ingress_status_t
}
// policy
namespace policy {
typedef struct io_k8s_api_policy_v1beta1_pod_disruption_budget_t v1beta1_pod_disruption_budget_t;
// io_k8s_api_policy_v1beta1_pod_disruption_budget_t
typedef struct io_k8s_api_policy_v1beta1_pod_security_policy_t v1beta1_pod_security_policy_t;
// io_k8s_api_policy_v1beta1_pod_security_policy_t
typedef struct io_k8s_api_policy_v1beta1_pod_disruption_budget_list_t v1beta1_pod_disruption_budget_list_t;
// io_k8s_api_policy_v1beta1_pod_disruption_budget_list_t
typedef struct io_k8s_api_policy_v1beta1_pod_security_policy_list_t v1beta1_pod_security_policy_list_t;
// io_k8s_api_policy_v1beta1_pod_security_policy_list_t
typedef struct io_k8s_api_policy_v1beta1_eviction_t v1beta1_eviction_t;
// io_k8s_api_policy_v1beta1_eviction_t
typedef struct io_k8s_api_policy_v1beta1_host_port_range_t v1beta1_host_port_range_t;
// io_k8s_api_policy_v1beta1_host_port_range_t
typedef struct io_k8s_api_policy_v1beta1_se_linux_strategy_options_t v1beta1_se_linux_strategy_options_t;
// io_k8s_api_policy_v1beta1_se_linux_strategy_options_t
typedef struct io_k8s_api_policy_v1beta1_allowed_csi_driver_t v1beta1_allowed_csi_driver_t;
// io_k8s_api_policy_v1beta1_allowed_csi_driver_t
typedef struct io_k8s_api_policy_v1beta1_runtime_class_strategy_options_t v1beta1_runtime_class_strategy_options_t;
// io_k8s_api_policy_v1beta1_runtime_class_strategy_options_t
typedef struct io_k8s_api_policy_v1beta1_pod_disruption_budget_spec_t v1beta1_pod_disruption_budget_spec_t;
// io_k8s_api_policy_v1beta1_pod_disruption_budget_spec_t
typedef struct io_k8s_api_policy_v1beta1_pod_disruption_budget_status_t v1beta1_pod_disruption_budget_status_t;
// io_k8s_api_policy_v1beta1_pod_disruption_budget_status_t
typedef struct io_k8s_api_policy_v1beta1_pod_security_policy_spec_t v1beta1_pod_security_policy_spec_t;
// io_k8s_api_policy_v1beta1_pod_security_policy_spec_t
typedef struct io_k8s_api_policy_v1beta1_fs_group_strategy_options_t v1beta1_fs_group_strategy_options_t;
// io_k8s_api_policy_v1beta1_fs_group_strategy_options_t
typedef struct io_k8s_api_policy_v1beta1_run_as_group_strategy_options_t v1beta1_run_as_group_strategy_options_t;
// io_k8s_api_policy_v1beta1_run_as_group_strategy_options_t
typedef struct io_k8s_api_policy_v1beta1_run_as_user_strategy_options_t v1beta1_run_as_user_strategy_options_t;
// io_k8s_api_policy_v1beta1_run_as_user_strategy_options_t
typedef struct io_k8s_api_policy_v1beta1_supplemental_groups_strategy_options_t v1beta1_supplemental_groups_strategy_options_t;
// io_k8s_api_policy_v1beta1_supplemental_groups_strategy_options_t
typedef struct io_k8s_api_policy_v1beta1_id_range_t v1beta1_id_range_t;
// io_k8s_api_policy_v1beta1_id_range_t
typedef struct io_k8s_api_policy_v1beta1_allowed_flex_volume_t v1beta1_allowed_flex_volume_t;
// io_k8s_api_policy_v1beta1_allowed_flex_volume_t
typedef struct io_k8s_api_policy_v1beta1_allowed_host_path_t v1beta1_allowed_host_path_t;
// io_k8s_api_policy_v1beta1_allowed_host_path_t
}
// discovery
namespace discovery {
typedef struct io_k8s_api_discovery_v1beta1_endpoint_slice_t v1beta1_endpoint_slice_t;
// io_k8s_api_discovery_v1beta1_endpoint_slice_t
typedef struct io_k8s_api_discovery_v1beta1_endpoint_slice_list_t v1beta1_endpoint_slice_list_t;
// io_k8s_api_discovery_v1beta1_endpoint_slice_list_t
typedef struct io_k8s_api_discovery_v1beta1_endpoint_t v1beta1_endpoint_t;
// io_k8s_api_discovery_v1beta1_endpoint_t
typedef struct io_k8s_api_discovery_v1beta1_endpoint_conditions_t v1beta1_endpoint_conditions_t;
// io_k8s_api_discovery_v1beta1_endpoint_conditions_t
typedef struct io_k8s_api_discovery_v1beta1_endpoint_port_t v1beta1_endpoint_port_t;
// io_k8s_api_discovery_v1beta1_endpoint_port_t
}
// storage
namespace storage {
typedef struct io_k8s_api_storage_v1beta1_csi_driver_t v1beta1_csi_driver_t;
// io_k8s_api_storage_v1beta1_csi_driver_t
typedef struct io_k8s_api_storage_v1beta1_csi_node_t v1beta1_csi_node_t;
// io_k8s_api_storage_v1beta1_csi_node_t
typedef struct io_k8s_api_storage_v1beta1_storage_class_t v1beta1_storage_class_t;
// io_k8s_api_storage_v1beta1_storage_class_t
typedef struct io_k8s_api_storage_v1beta1_volume_attachment_t v1beta1_volume_attachment_t;
// io_k8s_api_storage_v1beta1_volume_attachment_t
typedef struct io_k8s_api_storage_v1beta1_csi_driver_list_t v1beta1_csi_driver_list_t;
// io_k8s_api_storage_v1beta1_csi_driver_list_t
typedef struct io_k8s_api_storage_v1beta1_csi_node_list_t v1beta1_csi_node_list_t;
// io_k8s_api_storage_v1beta1_csi_node_list_t
typedef struct io_k8s_api_storage_v1beta1_storage_class_list_t v1beta1_storage_class_list_t;
// io_k8s_api_storage_v1beta1_storage_class_list_t
typedef struct io_k8s_api_storage_v1beta1_volume_attachment_list_t v1beta1_volume_attachment_list_t;
// io_k8s_api_storage_v1beta1_volume_attachment_list_t
typedef struct io_k8s_api_storage_v1alpha1_csi_storage_capacity_t v1alpha1_csi_storage_capacity_t;
// io_k8s_api_storage_v1alpha1_csi_storage_capacity_t
typedef struct io_k8s_api_storage_v1alpha1_volume_attachment_t v1alpha1_volume_attachment_t;
// io_k8s_api_storage_v1alpha1_volume_attachment_t
typedef struct io_k8s_api_storage_v1alpha1_csi_storage_capacity_list_t v1alpha1_csi_storage_capacity_list_t;
// io_k8s_api_storage_v1alpha1_csi_storage_capacity_list_t
typedef struct io_k8s_api_storage_v1alpha1_volume_attachment_list_t v1alpha1_volume_attachment_list_t;
// io_k8s_api_storage_v1alpha1_volume_attachment_list_t
typedef struct io_k8s_api_storage_v1_csi_driver_t v1_csi_driver_t;
// io_k8s_api_storage_v1_csi_driver_t
typedef struct io_k8s_api_storage_v1_csi_node_t v1_csi_node_t;
// io_k8s_api_storage_v1_csi_node_t
typedef struct io_k8s_api_storage_v1_storage_class_t v1_storage_class_t;
// io_k8s_api_storage_v1_storage_class_t
typedef struct io_k8s_api_storage_v1_volume_attachment_t v1_volume_attachment_t;
// io_k8s_api_storage_v1_volume_attachment_t
typedef struct io_k8s_api_storage_v1_csi_driver_list_t v1_csi_driver_list_t;
// io_k8s_api_storage_v1_csi_driver_list_t
typedef struct io_k8s_api_storage_v1_csi_node_list_t v1_csi_node_list_t;
// io_k8s_api_storage_v1_csi_node_list_t
typedef struct io_k8s_api_storage_v1_storage_class_list_t v1_storage_class_list_t;
// io_k8s_api_storage_v1_storage_class_list_t
typedef struct io_k8s_api_storage_v1_volume_attachment_list_t v1_volume_attachment_list_t;
// io_k8s_api_storage_v1_volume_attachment_list_t
typedef struct io_k8s_api_storage_v1_volume_attachment_spec_t v1_volume_attachment_spec_t;
// io_k8s_api_storage_v1_volume_attachment_spec_t
typedef struct io_k8s_api_storage_v1_volume_attachment_source_t v1_volume_attachment_source_t;
// io_k8s_api_storage_v1_volume_attachment_source_t
typedef struct io_k8s_api_storage_v1beta1_csi_driver_spec_t v1beta1_csi_driver_spec_t;
// io_k8s_api_storage_v1beta1_csi_driver_spec_t
typedef struct io_k8s_api_storage_v1beta1_volume_node_resources_t v1beta1_volume_node_resources_t;
// io_k8s_api_storage_v1beta1_volume_node_resources_t
typedef struct io_k8s_api_storage_v1beta1_volume_error_t v1beta1_volume_error_t;
// io_k8s_api_storage_v1beta1_volume_error_t
typedef struct io_k8s_api_storage_v1_csi_node_driver_t v1_csi_node_driver_t;
// io_k8s_api_storage_v1_csi_node_driver_t
typedef struct io_k8s_api_storage_v1_volume_node_resources_t v1_volume_node_resources_t;
// io_k8s_api_storage_v1_volume_node_resources_t
typedef struct io_k8s_api_storage_v1_csi_node_spec_t v1_csi_node_spec_t;
// io_k8s_api_storage_v1_csi_node_spec_t
typedef struct io_k8s_api_storage_v1_csi_driver_spec_t v1_csi_driver_spec_t;
// io_k8s_api_storage_v1_csi_driver_spec_t
typedef struct io_k8s_api_storage_v1beta1_csi_node_spec_t v1beta1_csi_node_spec_t;
// io_k8s_api_storage_v1beta1_csi_node_spec_t
typedef struct io_k8s_api_storage_v1alpha1_volume_attachment_status_t v1alpha1_volume_attachment_status_t;
// io_k8s_api_storage_v1alpha1_volume_attachment_status_t
typedef struct io_k8s_api_storage_v1alpha1_volume_error_t v1alpha1_volume_error_t;
// io_k8s_api_storage_v1alpha1_volume_error_t
typedef struct io_k8s_api_storage_v1_volume_error_t v1_volume_error_t;
// io_k8s_api_storage_v1_volume_error_t
typedef struct io_k8s_api_storage_v1beta1_volume_attachment_source_t v1beta1_volume_attachment_source_t;
// io_k8s_api_storage_v1beta1_volume_attachment_source_t
typedef struct io_k8s_api_storage_v1beta1_token_request_t v1beta1_token_request_t;
// io_k8s_api_storage_v1beta1_token_request_t
typedef struct io_k8s_api_storage_v1alpha1_volume_attachment_spec_t v1alpha1_volume_attachment_spec_t;
// io_k8s_api_storage_v1alpha1_volume_attachment_spec_t
typedef struct io_k8s_api_storage_v1_volume_attachment_status_t v1_volume_attachment_status_t;
// io_k8s_api_storage_v1_volume_attachment_status_t
typedef struct io_k8s_api_storage_v1alpha1_volume_attachment_source_t v1alpha1_volume_attachment_source_t;
// io_k8s_api_storage_v1alpha1_volume_attachment_source_t
typedef struct io_k8s_api_storage_v1beta1_csi_node_driver_t v1beta1_csi_node_driver_t;
// io_k8s_api_storage_v1beta1_csi_node_driver_t
typedef struct io_k8s_api_storage_v1beta1_volume_attachment_status_t v1beta1_volume_attachment_status_t;
// io_k8s_api_storage_v1beta1_volume_attachment_status_t
typedef struct io_k8s_api_storage_v1beta1_volume_attachment_spec_t v1beta1_volume_attachment_spec_t;
// io_k8s_api_storage_v1beta1_volume_attachment_spec_t
typedef struct io_k8s_api_storage_v1_token_request_t v1_token_request_t;;
// io_k8s_api_storage_v1_token_request_t
}
// networking
namespace networking {
typedef struct io_k8s_api_networking_v1beta1_ingress_class_t v1beta1_ingress_class_t;
// io_k8s_api_networking_v1beta1_ingress_class_t
typedef struct io_k8s_api_networking_v1beta1_ingress_class_list_t v1beta1_ingress_class_list_t;
// io_k8s_api_networking_v1beta1_ingress_class_list_t
typedef struct io_k8s_api_networking_v1_ingress_class_t v1_ingress_class_t;
// io_k8s_api_networking_v1_ingress_class_t
typedef struct io_k8s_api_networking_v1_ingress_t v1_ingress_t;
// io_k8s_api_networking_v1_ingress_t
typedef struct io_k8s_api_networking_v1_network_policy_t v1_network_policy_t;
// io_k8s_api_networking_v1_network_policy_t
typedef struct io_k8s_api_networking_v1_ingress_class_list_t v1_ingress_class_list_t;
// io_k8s_api_networking_v1_ingress_class_list_t
typedef struct io_k8s_api_networking_v1_ingress_list_t v1_ingress_list_t;
// io_k8s_api_networking_v1_ingress_list_t
typedef struct io_k8s_api_networking_v1_network_policy_list_t v1_network_policy_list_t;
// io_k8s_api_networking_v1_network_policy_list_t
typedef struct io_k8s_api_networking_v1_ingress_class_spec_t v1_ingress_class_spec_t;
// io_k8s_api_networking_v1_ingress_class_spec_t
typedef struct io_k8s_api_networking_v1_ingress_spec_t v1_ingress_spec_t;
// io_k8s_api_networking_v1_ingress_spec_t
typedef struct io_k8s_api_networking_v1_ingress_status_t v1_ingress_status_t;
// io_k8s_api_networking_v1_ingress_status_t
typedef struct io_k8s_api_networking_v1_network_policy_port_t v1_network_policy_port_t;
// io_k8s_api_networking_v1_network_policy_port_t
typedef struct io_k8s_api_networking_v1_ingress_service_backend_t v1_ingress_service_backend_t;
// io_k8s_api_networking_v1_ingress_service_backend_t
typedef struct io_k8s_api_networking_v1_service_backend_port_t v1_service_backend_port_t;
// io_k8s_api_networking_v1_service_backend_port_t
typedef struct io_k8s_api_networking_v1beta1_ingress_class_spec_t v1beta1_ingress_class_spec_t;
// io_k8s_api_networking_v1beta1_ingress_class_spec_t
typedef struct io_k8s_api_networking_v1_ingress_backend_t v1_ingress_backend_t;
// io_k8s_api_networking_v1_ingress_backend_t
typedef struct io_k8s_api_networking_v1_network_policy_peer_t v1_network_policy_peer_t;
// io_k8s_api_networking_v1_network_policy_peer_t
typedef struct io_k8s_api_networking_v1_ip_block_t v1_ip_block_t;
// io_k8s_api_networking_v1_ip_block_t
typedef struct io_k8s_api_networking_v1_network_policy_spec_t v1_network_policy_spec_t;
// io_k8s_api_networking_v1_network_policy_spec_t
typedef struct io_k8s_api_networking_v1_ingress_rule_t v1_ingress_rule_t;
// io_k8s_api_networking_v1_ingress_rule_t
typedef struct io_k8s_api_networking_v1_http_ingress_rule_value_t v1_http_ingress_rule_value_t;
// io_k8s_api_networking_v1_http_ingress_rule_value_t
typedef struct io_k8s_api_networking_v1_ingress_tls_t v1_ingress_tls_t;
// io_k8s_api_networking_v1_ingress_tls_t
typedef struct io_k8s_api_networking_v1_network_policy_egress_rule_t v1_network_policy_egress_rule_t;
// io_k8s_api_networking_v1_network_policy_egress_rule_t
typedef struct io_k8s_api_networking_v1_http_ingress_path_t v1_http_ingress_path_t;
// io_k8s_api_networking_v1_http_ingress_path_t
typedef struct io_k8s_api_networking_v1_network_policy_ingress_rule_t v1_network_policy_ingress_rule_t;
// io_k8s_api_networking_v1_network_policy_ingress_rule_t
typedef struct io_k8s_api_networking_v1beta1_ingress_backend_t v1beta1_ingress_backend_t;;
// io_k8s_api_networking_v1beta1_ingress_backend_t
typedef struct io_k8s_api_networking_v1beta1_ingress_rule_t v1beta1_ingress_rule_t;;
// io_k8s_api_networking_v1beta1_ingress_rule_t
typedef struct io_k8s_api_networking_v1beta1_ingress_status_t v1beta1_ingress_status_t;;
// io_k8s_api_networking_v1beta1_ingress_status_t
typedef struct io_k8s_api_networking_v1beta1_http_ingress_path_t v1beta1_http_ingress_path_t;;
// io_k8s_api_networking_v1beta1_http_ingress_path_t
typedef struct io_k8s_api_networking_v1beta1_ingress_spec_t v1beta1_ingress_spec_t;;
// io_k8s_api_networking_v1beta1_ingress_spec_t
typedef struct io_k8s_api_networking_v1beta1_ingress_tls_t v1beta1_ingress_tls_t;;
// io_k8s_api_networking_v1beta1_ingress_tls_t
typedef struct io_k8s_api_networking_v1beta1_ingress_t v1beta1_ingress_t;;
// io_k8s_api_networking_v1beta1_ingress_t
typedef struct io_k8s_api_networking_v1beta1_http_ingress_rule_value_t v1beta1_http_ingress_rule_value_t;;
// io_k8s_api_networking_v1beta1_http_ingress_rule_value_t
typedef struct io_k8s_api_networking_v1beta1_ingress_list_t v1beta1_ingress_list_t;;
// io_k8s_api_networking_v1beta1_ingress_list_t
}
}
}
#endif // ALIAS_H | 66.422758 | 186 | 0.935003 | zouxiaoliang |
96a3b765eb5f7343224730fff1913d50479d4139 | 1,042 | cpp | C++ | 19999/11054.cpp | rmagur1203/acmicpc | 83c4018548e42fc758b3858e8290990701e69e73 | [
"MIT"
] | null | null | null | 19999/11054.cpp | rmagur1203/acmicpc | 83c4018548e42fc758b3858e8290990701e69e73 | [
"MIT"
] | null | null | null | 19999/11054.cpp | rmagur1203/acmicpc | 83c4018548e42fc758b3858e8290990701e69e73 | [
"MIT"
] | 1 | 2022-01-11T05:03:52.000Z | 2022-01-11T05:03:52.000Z | #include <iostream>
#include <algorithm>
#define MAX 1001
using namespace std;
int arr[MAX];
int f_dp[MAX];
int b_dp[MAX];
int f_lis(int k)
{
if (k <= 0)
return 1;
if (f_dp[k] > 0)
return f_dp[k];
int mx = -1;
for (int i = k - 1; i >= 0; i--)
{
if (arr[i] < arr[k])
mx = max(mx, f_lis(i));
}
if (mx == -1)
f_dp[k] = 1;
else
f_dp[k] = mx + 1;
return f_dp[k];
}
int b_lis(int k, int n)
{
if (b_dp[k] > 0)
return b_dp[k];
int mx = -1;
for (int i = k + 1; i < n; i++)
{
if (arr[i] < arr[k])
mx = max(mx, b_lis(i, n));
}
if (mx == -1)
b_dp[k] = 1;
else
b_dp[k] = mx + 1;
return b_dp[k];
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
int mx = -1;
for (int i = 0; i < n; i++)
{
mx = max(mx, f_lis(i) + b_lis(i, n) - 1);
}
cout << mx;
} | 16.806452 | 49 | 0.415547 | rmagur1203 |
96a55515e63b554e7889792b81ca15583ee212b3 | 1,305 | cc | C++ | 445.Add-Two-Numbers-II/AddNumII.cc | stdbilly/leetcode | 752704ff99c21863bde4c929b7cc4fa18128cf39 | [
"MIT"
] | null | null | null | 445.Add-Two-Numbers-II/AddNumII.cc | stdbilly/leetcode | 752704ff99c21863bde4c929b7cc4fa18128cf39 | [
"MIT"
] | null | null | null | 445.Add-Two-Numbers-II/AddNumII.cc | stdbilly/leetcode | 752704ff99c21863bde4c929b7cc4fa18128cf39 | [
"MIT"
] | null | null | null | #include <stack>
#include "list/list.h"
using std::stack;
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
stack<int> s1, s2;
while (l1) {
s1.push(l1->val);
l1 = l1->next;
}
while (l2) {
s2.push(l2->val);
l2 = l2->next;
}
int carry = 0;
ListNode* cur = nullptr;
ListNode* pre = nullptr;
while (!s1.empty() || !s2.empty() || carry) {
int sum = carry;
if (!s1.empty()) {
sum += s1.top();
s1.pop();
}
if (!s2.empty()) {
sum += s2.top();
s2.pop();
}
carry = sum / 10;
pre = new ListNode(sum % 10);
pre->next = cur;
cur = pre;
}
return cur;
}
};
int main() {
Solution solution;
vector<int> arr1{7, 2, 4, 3};
vector<int> arr2{5, 6, 4};
ListNode* l1 = createLinkedList(arr1);
ListNode* l2 = createLinkedList(arr2);
printLinkedList(l1);
printLinkedList(l2);
ListNode* res = solution.addTwoNumbers(l1, l2);
printLinkedList(res);
destroyLinkedList(res);
destroyLinkedList(l1);
destroyLinkedList(l2);
return 0;
} | 24.166667 | 57 | 0.468966 | stdbilly |
96a713e91c76935a4ab020d15957b298d7e02cec | 1,190 | hpp | C++ | src/test/cpp/cn/edu/SUSTech/YeCanming/Judge/GTestExtensions.hpp | 2catycm/P_Algorithm_Design_and_Analysis_cpp | d1678d4db6f59a11215a8c790c2852bf9ad852dd | [
"MulanPSL-1.0"
] | null | null | null | src/test/cpp/cn/edu/SUSTech/YeCanming/Judge/GTestExtensions.hpp | 2catycm/P_Algorithm_Design_and_Analysis_cpp | d1678d4db6f59a11215a8c790c2852bf9ad852dd | [
"MulanPSL-1.0"
] | null | null | null | src/test/cpp/cn/edu/SUSTech/YeCanming/Judge/GTestExtensions.hpp | 2catycm/P_Algorithm_Design_and_Analysis_cpp | d1678d4db6f59a11215a8c790c2852bf9ad852dd | [
"MulanPSL-1.0"
] | null | null | null | #include <gtest/gtest.h>
#include <span>
#define EXPECT_MEMEQ(val1, val2, limit) \
if (0 != memcmp(val1, val2, limit)) { \
std::cout << "Expected: " << std::hex << std::uppercase << std::setfill('0'); \
for (const auto b : std::as_bytes(std::span{val1})) { \
std::cout << std::setw(2) << std::to_integer<unsigned>(b) << ' '; \
} \
std::cout << '\n'; \
std::cout << "Actually: " << std::hex << std::uppercase << std::setfill('0'); \
for (const auto b : std::as_bytes(std::span{val2})) { \
std::cout << std::setw(2) << std::to_integer<unsigned>(b) << ' '; \
} \
std::cout << '\n'; \
EXPECT_TRUE(false); \
} | 74.375 | 87 | 0.290756 | 2catycm |
96ab59e9195b9969d9f4be59ebe7ab4157bc8a37 | 2,027 | hpp | C++ | src/match.hpp | weibaohui/pipy | 14494f650fecc28410952c4c70f659f7b69b2c6a | [
"BSL-1.0"
] | null | null | null | src/match.hpp | weibaohui/pipy | 14494f650fecc28410952c4c70f659f7b69b2c6a | [
"BSL-1.0"
] | null | null | null | src/match.hpp | weibaohui/pipy | 14494f650fecc28410952c4c70f659f7b69b2c6a | [
"BSL-1.0"
] | null | null | null | /*
* Copyright (c) 2019 by flomesh.io
*
* Unless prior written consent has been obtained from the copyright
* owner, the following shall not be allowed.
*
* 1. The distribution of any source codes, header files, make files,
* or libraries of the software.
*
* 2. Disclosure of any source codes pertaining to the software to any
* additional parties.
*
* 3. Alteration or removal of any notices in or on the software or
* within the documentation included within the software.
*
* ALL SOURCE CODE AS WELL AS ALL DOCUMENTATION INCLUDED WITH THIS
* SOFTWARE IS PROVIDED IN AN “AS IS” CONDITION, WITHOUT WARRANTY OF ANY
* KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef MATCH_HPP
#define MATCH_HPP
#include "object.hpp"
#include <list>
#include <string>
#include <vector>
NS_BEGIN
//
// Match
//
class Match {
public:
Match();
Match(const std::string &path);
Match(const Match &other);
auto operator=(const Match &other) -> Match&;
bool is_root() const { return m_path.size() == 0; }
bool is_list() const { return !is_root() && m_path.back().is_array; }
bool is_map() const { return !is_root() && !m_path.back().is_array; }
auto key() const -> const std::string& { return m_path.back().key; }
bool matching() const { return m_matched == m_path.size(); }
void reset();
void process(const Object *obj);
private:
struct PathLevel {
bool is_array;
int index;
std::string key;
};
struct StackLevel {
bool is_array;
int index;
};
std::vector<PathLevel> m_path;
std::list<StackLevel> m_stack;
int m_matched = 0;
};
NS_END
#endif // MATCH_HPP
| 25.658228 | 77 | 0.693636 | weibaohui |
96bacdbe3160a6594e226f92f48e771148e930cc | 1,772 | cpp | C++ | galaxy/src/galaxy/core/Config.cpp | reworks/rework | 90508252c9a4c77e45a38e7ce63cfd99f533f42b | [
"Apache-2.0"
] | 6 | 2018-07-21T20:37:01.000Z | 2018-10-31T01:49:35.000Z | galaxy/src/galaxy/core/Config.cpp | reworks/rework | 90508252c9a4c77e45a38e7ce63cfd99f533f42b | [
"Apache-2.0"
] | null | null | null | galaxy/src/galaxy/core/Config.cpp | reworks/rework | 90508252c9a4c77e45a38e7ce63cfd99f533f42b | [
"Apache-2.0"
] | null | null | null | ///
/// Config.cpp
/// galaxy
///
/// Refer to LICENSE.txt for more details.
///
#include <fstream>
#include "Config.hpp"
namespace galaxy
{
namespace core
{
Config::Config() noexcept
: m_loaded {false}
{
m_config = "{\"config\":{}}"_json;
}
Config::Config(std::string_view file)
: m_loaded {false}
{
m_config = "{\"config\":{}}"_json;
load(file);
}
Config::~Config() noexcept
{
m_loaded = false;
m_config.clear();
}
void Config::load(std::string_view file)
{
auto path = std::filesystem::path(file);
m_path = path.string();
if (!std::filesystem::exists(path))
{
std::ofstream ofs {m_path, std::ofstream::out | std::ofstream::trunc};
if (ofs.good())
{
ofs << m_config.dump(4);
ofs.close();
}
else
{
ofs.close();
GALAXY_LOG(GALAXY_FATAL, "Failed to save config file to disk.");
}
}
else
{
std::ifstream input {m_path, std::ifstream::in};
if (!input.good())
{
input.close();
GALAXY_LOG(GALAXY_FATAL, "Failed to load config file.");
}
else
{
input >> m_config;
input.close();
m_loaded = true;
}
}
}
void Config::save()
{
if (m_loaded)
{
std::ofstream ofs {m_path, std::ofstream::out | std::ofstream::trunc};
if (ofs.good())
{
ofs << m_config.dump(4);
ofs.close();
}
else
{
ofs.close();
GALAXY_LOG(GALAXY_ERROR, "Failed to save config file to disk.");
}
}
else
{
GALAXY_LOG(GALAXY_WARNING, "Attempted to save config that was not loaded.");
}
}
bool Config::empty() noexcept
{
if (m_loaded)
{
return m_config.at("config").empty();
}
return true;
}
} // namespace core
} // namespace galaxy | 16.560748 | 80 | 0.560948 | reworks |
96c032133b7b1c4038487c6ad81795b9b18f9eee | 1,570 | cpp | C++ | src/tests/world_assertions.cpp | fairlight1337/GDAPlanner | c39d4e8fdcb0bbf18ff9e646349161853943dd5e | [
"BSD-2-Clause"
] | null | null | null | src/tests/world_assertions.cpp | fairlight1337/GDAPlanner | c39d4e8fdcb0bbf18ff9e646349161853943dd5e | [
"BSD-2-Clause"
] | null | null | null | src/tests/world_assertions.cpp | fairlight1337/GDAPlanner | c39d4e8fdcb0bbf18ff9e646349161853943dd5e | [
"BSD-2-Clause"
] | null | null | null | #include <iostream>
#include <cstdlib>
#include <string>
#include <gdaplanner/GDAPlanner.h>
using namespace gdaplanner;
int main(__attribute__((unused)) int argc, __attribute__((unused)) char** argv) {
int nReturnvalue = EXIT_FAILURE;
World::Ptr wdWorld = World::create();
Expression exA = Expression::parseSingle("(table-set table-1");
if(wdWorld->holds(exA).size() == 0) {
if(wdWorld->assertFact(exA)) {
if(wdWorld->holds(exA).size() == 1) {
wdWorld->retractFact(exA);
if(wdWorld->holds(exA).size() == 0) {
Expression exB = Expression::parseSingle("(table-set table-2");
Expression exC = Expression::parseSingle("(table-set ?a)");
if(wdWorld->assertFact(exA) && wdWorld->assertFact(exB)) {
std::vector<std::map<std::string, Expression>> vecHolds = wdWorld->holds(exC);
if(vecHolds.size() > 0) {
bool bA = false, bB = false;
for(std::map<std::string, Expression> mapHolds : vecHolds) {
if(mapHolds["?a"] == "table-1") {
bA = true;
} else if(mapHolds["?a"] == "table-2") {
bB = true;
}
}
if(bA && bB) {
wdWorld->retractFact(exA);
if(wdWorld->holds(exC).size() == 1) {
wdWorld->retractFact(exC);
if(wdWorld->holds(exC).size() == 0) {
if(wdWorld->assertFact(exA) && wdWorld->assertFact(exB)) {
wdWorld->retractFact(exC, 0, true);
if(wdWorld->holds(exC).size() == 2) {
nReturnvalue = EXIT_SUCCESS;
}
}
}
}
}
}
}
}
}
}
}
return nReturnvalue;
}
| 23.432836 | 83 | 0.576433 | fairlight1337 |
96c19a8b815f0da1e1ea7a54f5aedaf68c587d95 | 2,059 | cpp | C++ | XJ Contests/2021/1.2/T2/me.cpp | jinzhengyu1212/Clovers | 0efbb0d87b5c035e548103409c67914a1f776752 | [
"MIT"
] | null | null | null | XJ Contests/2021/1.2/T2/me.cpp | jinzhengyu1212/Clovers | 0efbb0d87b5c035e548103409c67914a1f776752 | [
"MIT"
] | null | null | null | XJ Contests/2021/1.2/T2/me.cpp | jinzhengyu1212/Clovers | 0efbb0d87b5c035e548103409c67914a1f776752 | [
"MIT"
] | null | null | null | /*
the vast starry sky,
bright for those who chase the light.
*/
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
#define mk make_pair
const int inf=(int)1e9;
const ll INF=(ll)5e18;
const int MOD=998244353;
int _abs(int x){return x<0 ? -x : x;}
int add(int x,int y){x+=y; return x>=MOD ? x-MOD : x;}
int sub(int x,int y){x-=y; return x<0 ? x+MOD : x;}
#define mul(x,y) (ll)(x)*(y)%MOD
void Add(int &x,int y){x+=y; if(x>=MOD) x-=MOD;}
void Sub(int &x,int y){x-=y; if(x<0) x+=MOD;}
void Mul(int &x,int y){x=mul(x,y);}
int qpow(int x,int y){int ret=1; while(y){if(y&1) ret=mul(ret,x); x=mul(x,x); y>>=1;} return ret;}
void checkmin(int &x,int y){if(x>y) x=y;}
void checkmax(int &x,int y){if(x<y) x=y;}
void checkmin(ll &x,ll y){if(x>y) x=y;}
void checkmax(ll &x,ll y){if(x<y) x=y;}
#define out(x) cerr<<#x<<'='<<x<<' '
#define outln(x) cerr<<#x<<'='<<x<<endl
#define sz(x) (int)(x).size()
inline int read(){
int x=0,f=1; char c=getchar();
while(c>'9'||c<'0'){if(c=='-') f=-1; c=getchar();}
while(c>='0'&&c<='9') x=(x<<1)+(x<<3)+(c^48),c=getchar();
return x*f;
}
const int N=1005;
int n,dp[N][N],match[N],a[N],top=0,vis[N],tmp[N];
void init(){
n=read(); top=0;
memset(vis,0,sizeof(vis));
for(int i=1;i<=n;i++) tmp[i]=read();
for(int i=1;i<=n;i++){
int x=read();
match[tmp[i]]=x;
}
for(int i=1;i<=n;i++){
if(vis[i]) continue;
int x=match[i],len=1; top++;
while(x!=i){
len++;
vis[x]=1;
x=match[x];
}
a[top]=len; vis[i]=1;
}
}
void solve(){
int ans=0;
for(int i=1;i<=n;i++) if(match[i]==i) ans++;
for(int l=2;l<=n;l++){
dp[l][l]=l-1;
for(int i=l+1;i<=n;i++){
dp[l][i]=max(dp[l][i-l]+l-1,dp[l][i-l-1]+l);
}
int sum=0;
for(int i=1;i<=top;i++) sum+=dp[l][a[i]];
checkmax(ans,sum);
}
printf("%d\n",ans);
}
int main()
{
int T=read();
while(T--){
init();
solve();
}
return 0;
} | 26.063291 | 98 | 0.504614 | jinzhengyu1212 |
96c43e87f29f8126f14efbbf8ceec6a03312e5c2 | 6,625 | cpp | C++ | check/TestFreezeBasis.cpp | chrhansk/HiGHS | 311aa8571925ed23c952687569dbe7207e542e0a | [
"MIT"
] | 3 | 2019-04-17T11:34:07.000Z | 2021-05-21T05:56:42.000Z | check/TestFreezeBasis.cpp | chrhansk/HiGHS | 311aa8571925ed23c952687569dbe7207e542e0a | [
"MIT"
] | 17 | 2020-03-30T19:16:59.000Z | 2020-12-15T01:01:42.000Z | check/TestFreezeBasis.cpp | chrhansk/HiGHS | 311aa8571925ed23c952687569dbe7207e542e0a | [
"MIT"
] | 1 | 2022-02-08T19:30:43.000Z | 2022-02-08T19:30:43.000Z | #include "Highs.h"
#include "catch.hpp"
const double inf = kHighsInf;
const bool dev_run = false;
const double double_equal_tolerance = 1e-5;
TEST_CASE("FreezeBasis", "[highs_test_freeze_basis]") {
std::string filename;
filename = std::string(HIGHS_DIR) + "/check/instances/avgas.mps";
Highs highs;
if (!dev_run) highs.setOptionValue("output_flag", false);
highs.readModel(filename);
const HighsLp& lp = highs.getLp();
const HighsInt num_col = lp.num_col_;
const HighsInt num_row = lp.num_row_;
const HighsInt from_col = 0;
const HighsInt to_col = num_col - 1;
const HighsInfo& info = highs.getInfo();
vector<double> original_col_lower = lp.col_lower_;
vector<double> original_col_upper = lp.col_upper_;
// Get the continuous solution and iteration count from a logical basis
highs.run();
HighsInt continuous_iteration_count = info.simplex_iteration_count;
double continuous_objective = info.objective_function_value;
// Get the integer solution to provide bound tightenings
vector<HighsVarType> integrality;
integrality.assign(num_col, HighsVarType::kInteger);
highs.changeColsIntegrality(from_col, to_col, &integrality[0]);
highs.setOptionValue("output_flag", false);
highs.run();
if (dev_run) highs.setOptionValue("output_flag", true);
vector<double> integer_solution = highs.getSolution().col_value;
vector<double> local_col_lower;
vector<double> local_col_upper;
// Now restore the original integrality and set an explicit logical
// basis to force reinversion
integrality.assign(num_col, HighsVarType::kContinuous);
highs.changeColsIntegrality(from_col, to_col, &integrality[0]);
HighsBasis basis;
for (HighsInt iCol = 0; iCol < num_col; iCol++)
basis.col_status.push_back(HighsBasisStatus::kLower);
for (HighsInt iRow = 0; iRow < num_row; iRow++)
basis.row_status.push_back(HighsBasisStatus::kBasic);
highs.setBasis(basis);
HighsInt frozen_basis_id0;
// Cannot freeze a basis when there's no INVERT
REQUIRE(highs.freezeBasis(frozen_basis_id0) == HighsStatus::kError);
// Get the basic variables to force INVERT with a logical basis
vector<HighsInt> basic_variables;
basic_variables.resize(lp.num_row_);
highs.getBasicVariables(&basic_variables[0]);
// Can freeze a basis now!
REQUIRE(highs.freezeBasis(frozen_basis_id0) == HighsStatus::kOk);
if (dev_run) {
highs.setOptionValue("output_flag", true);
highs.setOptionValue("log_dev_level", 2);
highs.setOptionValue("highs_debug_level", 3);
}
highs.run();
// highs.setOptionValue("output_flag", false);
// Now freeze the current basis and add the integer solution as lower bounds
HighsInt frozen_basis_id1;
REQUIRE(highs.freezeBasis(frozen_basis_id1) == HighsStatus::kOk);
if (dev_run) printf("\nSolving with bounds (integer solution, upper)\n");
local_col_lower = integer_solution;
local_col_upper = original_col_upper;
highs.changeColsBounds(from_col, to_col, &local_col_lower[0],
&local_col_upper[0]);
if (dev_run) highs.setOptionValue("output_flag", true);
highs.run();
// highs.setOptionValue("output_flag", false);
double semi_continuous_objective = info.objective_function_value;
// Now freeze the current basis and add the integer solution as upper bounds
HighsInt frozen_basis_id2;
REQUIRE(highs.freezeBasis(frozen_basis_id2) == HighsStatus::kOk);
if (dev_run)
printf("\nSolving with bounds (integer solution, integer solution)\n");
local_col_lower = integer_solution;
local_col_upper = integer_solution;
highs.changeColsBounds(from_col, to_col, &local_col_lower[0],
&local_col_upper[0]);
if (dev_run) highs.setOptionValue("output_flag", true);
highs.run();
// highs.setOptionValue("output_flag", false);
// Now test unfreeze
//
// Restore the upper bounds and unfreeze frozen_basis_id2 (semi-continuous
// optimal basis)
if (dev_run)
printf(
"\nSolving with bounds (integer solution, upper) after unfreezing "
"basis %d\n",
(int)frozen_basis_id2);
if (dev_run) printf("Change column bounds to (integer solution, upper)\n");
local_col_lower = integer_solution;
local_col_upper = original_col_upper;
highs.changeColsBounds(from_col, to_col, &local_col_lower[0],
&local_col_upper[0]);
if (dev_run) printf("Unfreeze basis %d\n", (int)frozen_basis_id2);
REQUIRE(highs.unfreezeBasis(frozen_basis_id2) == HighsStatus::kOk);
// Solving the LP should require no iterations
if (dev_run) highs.setOptionValue("output_flag", true);
highs.run();
// highs.setOptionValue("output_flag", false);
REQUIRE(info.simplex_iteration_count == 0);
double dl_objective =
fabs(semi_continuous_objective - info.objective_function_value);
REQUIRE(dl_objective < double_equal_tolerance);
REQUIRE(info.simplex_iteration_count == 0);
//
// Restore the lower bounds and unfreeze frozen_basis_id1 (continuous optimal
// basis)
if (dev_run)
printf("\nSolving with bounds (lower, upper) after unfreezing basis %d\n",
(int)frozen_basis_id1);
if (dev_run) printf("Change column bounds to (lower, upper)\n");
local_col_lower = original_col_lower;
local_col_upper = original_col_upper;
highs.changeColsBounds(from_col, to_col, &local_col_lower[0],
&local_col_upper[0]);
if (dev_run) printf("Unfreeze basis %d\n", (int)frozen_basis_id1);
REQUIRE(highs.unfreezeBasis(frozen_basis_id1) == HighsStatus::kOk);
// Solving the LP should require no iterations
if (dev_run) highs.setOptionValue("output_flag", true);
highs.run();
// highs.setOptionValue("output_flag", false);
dl_objective = fabs(continuous_objective - info.objective_function_value);
REQUIRE(dl_objective < double_equal_tolerance);
REQUIRE(info.simplex_iteration_count == 0);
//
// Unfreeze frozen_basis_id0
if (dev_run)
printf("\nSolving with bounds (lower, upper) after unfreezing basis %d\n",
(int)frozen_basis_id0);
if (dev_run) printf("Unfreeze basis %d\n", (int)frozen_basis_id0);
REQUIRE(highs.unfreezeBasis(frozen_basis_id0) == HighsStatus::kOk);
// Solving the LP should require the same number of iterations as before
if (dev_run) highs.setOptionValue("output_flag", true);
highs.run();
// highs.setOptionValue("output_flag", false);
dl_objective = fabs(continuous_objective - info.objective_function_value);
REQUIRE(dl_objective < double_equal_tolerance);
REQUIRE(info.simplex_iteration_count == continuous_iteration_count);
REQUIRE(highs.frozenBasisAllDataClear() == HighsStatus::kOk);
}
| 40.895062 | 79 | 0.736151 | chrhansk |
96c569ef7d41d75f7e9c2704a8fd5076345ae767 | 3,126 | cpp | C++ | Asdos/Tugas-Latihan/Tgs2_672021224.cpp | DimasAkmall/DDP | f6411aafc799378f99119dd35033047bd1bdb950 | [
"MIT"
] | null | null | null | Asdos/Tugas-Latihan/Tgs2_672021224.cpp | DimasAkmall/DDP | f6411aafc799378f99119dd35033047bd1bdb950 | [
"MIT"
] | null | null | null | Asdos/Tugas-Latihan/Tgs2_672021224.cpp | DimasAkmall/DDP | f6411aafc799378f99119dd35033047bd1bdb950 | [
"MIT"
] | null | null | null | // Dimas Akmal Widi Pradana - 672021224 - DDP F
#include <iostream>
using namespace std;
/*int main(){
int a;
cout << "masukkan a (maks 9): ";
cin >> a;
for (int k = 1; k <= 8*a+8; k++){
cout << " ";
}
for (int i = 1; i <= a-8; i++){
cout << " " << " " << " " << " " << " " << " " << " " << " " << " ";
for (int j = 1; j <= a-8; j++){
cout << "*";
}
}
cout << endl;
for (int k = 1; k <= 7*a+7; k++){
cout << " ";
}
for (int i = 1; i <= a-7; i++){
cout << " " << " " << " " << " " << " " << " " << " " << " ";
for (int j = 1; j <= a-7; j++){
cout << "*";
}
}
cout << endl;
for (int k = 1; k <= 6*a+6; k++){
cout << " ";
}
for (int i = 1; i <= a-6; i++){
cout << " " << " " << " " << " " << " " << " " << " ";
for (int j = 1; j <= a-6; j++){
cout << "*";
}
}
cout << endl;
for (int k = 1; k <= 5*a+5; k++){
cout << " ";
}
for (int i = 1; i <= a-5; i++){
cout << " " << " " << " " << " " << " " << " ";
for (int j = 1; j <= a-5; j++){
cout << "*";
}
}
cout << endl;
for (int k = 1; k <= 4*a+4; k++){
cout << " ";
}
for (int i = 1; i <= a-4; i++){
cout << " " << " " << " " << " " << " ";
for (int j = 1; j <= a-4; j++){
cout << "*";
}
}
cout << endl;
for (int k = 1; k <= 3*a+3; k++){
cout << " ";
}
for (int i = 1; i <= a-3; i++){
cout << " " << " " << " " << " ";
for (int j = 1; j <= a-3; j++){
cout << "*";
}
}
cout << endl;
for (int k = 1; k <= 2*a+2; k++){
cout << " ";
}
for (int i = 1; i <= a-2; i++){
cout << " " << " " << " ";
for (int j = 1; j <= a-2; j++){
cout << "*";
}
}
cout << endl;
for (int k = 1; k <= 1*a+1; k++){
cout << " ";
}
for (int i = 1; i <= a-1; i++){
cout << " " << " ";
for (int j = 1; j <= a-1; j++){
cout << "*";
}
}
cout << endl;
for (int i = 1; i <= a; i++){
cout << " ";
for (int h = 1; h <= a; h++){
cout << "*";
}
}
cout << endl;
//Maaf kak masih bingung hehe..
return 0;
}*/
// pembetulan from rio a.
int main(){
int tinggi;
int baris, jeda, invers, berundak;
cout << "Tingginya (Maks 8): ";
cin >> tinggi;
for(baris=1;baris<=tinggi;baris++){
for(jeda=1;jeda<=tinggi;jeda++){
for(invers=tinggi-baris;invers>0;invers--){
cout << " ";
}
for(berundak=baris;berundak>0;berundak--) {
if(tinggi<jeda+baris){
cout << "*";
}
else{
cout << " ";
}
}
cout << " ";
}
cout << endl;
}
return 0;
} | 22.328571 | 76 | 0.27991 | DimasAkmall |
96c946d267f9328e957d6c1dece07f6b38182e56 | 2,870 | cpp | C++ | QtCef/QtCef/main.cpp | fuyanzhi1234/DevelopQt | f4590cca8cde5e8b38ee19d97ea82c43257ec1b3 | [
"MIT"
] | null | null | null | QtCef/QtCef/main.cpp | fuyanzhi1234/DevelopQt | f4590cca8cde5e8b38ee19d97ea82c43257ec1b3 | [
"MIT"
] | null | null | null | QtCef/QtCef/main.cpp | fuyanzhi1234/DevelopQt | f4590cca8cde5e8b38ee19d97ea82c43257ec1b3 | [
"MIT"
] | null | null | null | #include "qtcef.h"
#include <QApplication>
#include <qt_windows.h>
#include "include/base/cef_scoped_ptr.h"
#include "include/cef_command_line.h"
#include "include/cef_sandbox_win.h"
#include "cefsimple/simple_app.h"
#include "include/cef_sandbox_win.h"
#include <QMessageBox>
#include "cefsimple/simple_handler.h"
bool IsSubprocess(int & argc, char ** argv)
{
std::vector<std::string> argVector(argv, argv + argc);
for (auto i = 0; i < argc; ++i) {
if (argVector[i].find("--type") != std::string::npos) {
return true;
}
}
return false;
}
int RunCefSubprocess(int & argc, char ** argv)
{
CefMainArgs cefMainArgs(GetModuleHandle(nullptr));
return CefExecuteProcess(cefMainArgs, nullptr, nullptr);
}
int main(int argc, char *argv[])
{
if (IsSubprocess(argc, argv)) {
// QMessageBox::about(NULL, "1", "2");
return RunCefSubprocess(argc, argv);
}
// argc = 2;
// argv[1] = "--ppapi-flash-path=plugins\\pepflashplayer.dll";
QApplication a(argc, argv);
// Enable High-DPI support on Windows 7 or newer.
CefEnableHighDPISupport();
void* sandbox_info = NULL;
#if defined(CEF_USE_SANDBOX)
// Manage the life span of the sandbox information object. This is necessary
// for sandbox support on Windows. See cef_sandbox_win.h for complete details.
CefScopedSandboxInfo scoped_sandbox;
sandbox_info = scoped_sandbox.sandbox_info();
#endif
HINSTANCE hInstance = (HINSTANCE)GetModuleHandle(NULL);
// Provide CEF with command-line arguments.
CefMainArgs main_args(hInstance);
// SimpleApp implements application-level callbacks. It will create the first
// browser instance in OnContextInitialized() after CEF has initialized.
// QMessageBox::about(NULL, "main", "1");
CefRefPtr<SimpleApp> app(new SimpleApp());
// CEF applications have multiple sub-processes (render, plugin, GPU, etc)
// that share the same executable. This function checks the command-line and,
// if this is a sub-process, executes the appropriate logic.
// QMessageBox::about(NULL, "main", "2");
// int exit_code = CefExecuteProcess(main_args, app.get(), sandbox_info);
// // The sub-process has completed so return here.
// QMessageBox::about(NULL, "main", QString("%1").arg(exit_code));
//
// if (exit_code >= 0) {
// QMessageBox::about(NULL, "main", "3");
// return 0;
// }
// QMessageBox::about(NULL, "main", "4");
// Specify CEF global settings here.
CefSettings settings;
#if !defined(CEF_USE_SANDBOX)
settings.no_sandbox = true;
#endif
settings.multi_threaded_message_loop = true;
settings.remote_debugging_port = 2012;
// settings.single_process = true;
// Initialize CEF.
CefInitialize(main_args, settings, app.get(), sandbox_info);
QtCef w;
w.show();
int result = a.exec();
// Shut down CEF.
#ifndef _DEBUG
CefShutdown();
#endif // _DEBUG
return result;
}
| 28.7 | 79 | 0.7 | fuyanzhi1234 |
96cbd824a9526d5c62a48c4144d4fefaa6bda4c5 | 2,786 | cpp | C++ | cpp/virtual/virtual3.cpp | stdbilly/CS_Note | a8a87e135a525d53c283a4c70fb942c9ca59a758 | [
"MIT"
] | 2 | 2020-12-09T09:55:51.000Z | 2021-01-08T11:38:22.000Z | cpp/virtual/virtual3.cpp | stdbilly/CS_Note | a8a87e135a525d53c283a4c70fb942c9ca59a758 | [
"MIT"
] | null | null | null | cpp/virtual/virtual3.cpp | stdbilly/CS_Note | a8a87e135a525d53c283a4c70fb942c9ca59a758 | [
"MIT"
] | null | null | null | #pragma vtordisp(off)
#include <iostream>
using std::cout;
using std::endl;
class Base1 {
public:
Base1() : _iBase1(10) {}
virtual void f() { cout << "Base1::f()" << endl; }
virtual void g() { cout << "Base1::g()" << endl; }
virtual void h() { cout << "Base1::h()" << endl; }
private:
int _iBase1;
};
class Base2 {
public:
Base2() : _iBase2(100) {}
virtual void f() { cout << "Base2::f()" << endl; }
virtual void g() { cout << "Base2::g()" << endl; }
virtual void h() { cout << "Base2::h()" << endl; }
private:
int _iBase2;
};
class Base3 {
public:
Base3() : _iBase3(1000) {}
virtual void f() { cout << "Base3::f()" << endl; }
virtual void g() { cout << "Base3::g()" << endl; }
virtual void h() { cout << "Base3::h()" << endl; }
private:
int _iBase3;
};
/*
32位系统下
测试三:多重继承(带虚函数)
1. 每个基类都有自己的虚函数表
2. 派生类如果有自己的虚函数,会被加入到第一个虚函数表之中
3. 内存布局中, 其基类的布局按照基类被声明时的顺序进行排列
4. 派生类会覆盖基类的虚函数,只有第一个虚函数表中存放的是
真实的被覆盖的函数的地址;其它的虚函数表中存放的并不是真实的
对应的虚函数的地址,而只是一条跳转指令
1>class Derived size(28):
1> +---
1> 0 | +--- (base class Base1)
1> 0 | | {vfptr}
1> 4 | | _iBase1
1> | +---
1> 8 | +--- (base class Base2)
1> 8 | | {vfptr}
1>12 | | _iBase2
1> | +---
1>16 | +--- (base class Base3)
1>16 | | {vfptr}
1>20 | | _iBase3
1> | +---
1>24 | _iDerived
1> +---
1>Derived::$vftable@Base1@:
1> | &Derived_meta
1> | 0
1> 0 | &Derived::f
1> 1 | &Base1::g
1> 2 | &Base1::h
1> 3 | &Derived::g1
1>Derived::$vftable@Base2@:
1> | -8
1> 0 | &thunk: this-=8; goto Derived::f 跳转指令
1> 1 | &Base2::g
1> 2 | &Base2::h
1>
1>Derived::$vftable@Base3@:
1> | -16
1> 0 | &thunk: this-=16; goto Derived::f 跳转指令
1> 1 | &Base3::g
1> 2 | &Base3::h
*/
/*
虚继承Base1
1>class Derived size(32):
1> +---
1> 0 | +--- (base class Base2)
1> 0 | | {vfptr}
1> 4 | | _iBase2
1> | +---
1> 8 | +--- (base class Base3)
1> 8 | | {vfptr}
1>12 | | _iBase3
1> | +---
1>16 | {vbptr} ==> 谁虚继承的基类,该虚基指针就跟着谁
1>20 | _iDerived
1> +---
1> +--- (virtual base Base1)
1>24 | {vfptr}
1>28 | _iBase1
1> +---
*/
class Derived : virtual public Base1, public Base2, public Base3 {
public:
Derived() : _iDerived(10000) {}
void f() { cout << "Derived::f()" << endl; }
virtual void g1() { cout << "Derived::g1()" << endl; }
private:
int _iDerived;
};
int main(void) {
Derived d;
Base2* pBase2 = &d;
Base3* pBase3 = &d;
Derived* pDerived = &d;
pBase2->f();
cout << "sizeof(d) = " << sizeof(d) << endl;
cout << "&Derived = " << &d << endl; // 这三个地址值是不一样的
cout << "pBase2 = " << pBase2 << endl; //
cout << "pBase3 = " << pBase3 << endl; //
return 0;
}
| 19.9 | 67 | 0.507897 | stdbilly |
96cd0fc938ada87d2f809727cb36a2627b0279a3 | 316 | cpp | C++ | src/converter/ExporterOne.cpp | rfrolov/otus_homework_05 | 15e20fb0261c037e4eaaa972734248eb50aba646 | [
"MIT"
] | null | null | null | src/converter/ExporterOne.cpp | rfrolov/otus_homework_05 | 15e20fb0261c037e4eaaa972734248eb50aba646 | [
"MIT"
] | null | null | null | src/converter/ExporterOne.cpp | rfrolov/otus_homework_05 | 15e20fb0261c037e4eaaa972734248eb50aba646 | [
"MIT"
] | null | null | null | #include "../primitives/IPrimitive.h"
#include "../utils/utils.h"
#include "ExporterOne.h"
bool ExporterOne::do_convert(data_t &data) {
if (!fs_.is_open()) { return false; }
fs_ << data.size() << std::endl;
for (auto &serialised_data : data) {
fs_ << serialised_data;
}
return true;
} | 21.066667 | 44 | 0.617089 | rfrolov |
96d3eff9d1a8e3eb52b0ba299d150bd95f8692b9 | 15,716 | cpp | C++ | Math Test/src/mat4_test.cpp | gerrygoo/graficas | 443832dc6820c0a93c8291831109e3248f57f9b0 | [
"MIT"
] | null | null | null | Math Test/src/mat4_test.cpp | gerrygoo/graficas | 443832dc6820c0a93c8291831109e3248f57f9b0 | [
"MIT"
] | null | null | null | Math Test/src/mat4_test.cpp | gerrygoo/graficas | 443832dc6820c0a93c8291831109e3248f57f9b0 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "CppUnitTest.h"
#include <cmath>
#include <limits>
#include <locale>
#include <codecvt>
#include "vec4.h"
#include "mat4.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace Microsoft
{
namespace VisualStudio
{
namespace CppUnitTestFramework
{
template<>
static std::wstring ToString<cgmath::vec4>(const cgmath::vec4& v)
{
return L"(" + std::to_wstring(v.x) + L", " + std::to_wstring(v.y) + L", " + std::to_wstring(v.z) + L", " + std::to_wstring(v.w) + L")";
}
template<>
static std::wstring ToString<cgmath::mat4>(const cgmath::mat4& m)
{
std::stringstream ss;
ss << m;
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
std::wstring wide = converter.from_bytes(ss.rdbuf()->str());
return wide;
}
}
}
}
namespace MathTest
{
TEST_CLASS(mat4_test)
{
public:
TEST_METHOD(ConstructorTest)
{
cgmath::mat4 a;
Assert::AreEqual(0.0f, a[0][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, a[0][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, a[0][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, a[0][3], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, a[1][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, a[1][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, a[1][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, a[1][3], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, a[2][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, a[2][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, a[2][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, a[2][3], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, a[3][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, a[3][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, a[3][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, a[3][3], std::numeric_limits<float>::epsilon());
cgmath::mat4 b(1.0f);
Assert::AreEqual(1.0f, b[0][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, b[0][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, b[0][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, b[0][3], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, b[1][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(1.0f, b[1][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, b[1][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, b[1][3], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, b[2][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, b[2][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(1.0f, b[2][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, b[2][3], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, b[3][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, b[3][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, b[3][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(1.0f, b[3][3], std::numeric_limits<float>::epsilon());
cgmath::mat4 c(-7.0f);
Assert::AreEqual(-7.0f, c[0][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, c[0][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, c[0][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, c[0][3], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, c[1][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(-7.0f, c[1][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, c[1][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, c[1][3], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, c[2][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, c[2][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(-7.0f, c[2][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, c[2][3], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, c[3][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, c[3][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, c[3][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(-7.0f, c[3][3], std::numeric_limits<float>::epsilon());
cgmath::vec4 col1(0.0f, 1.0f, 2.0f, 3.0f);
cgmath::vec4 col2(4.0f, 5.0f, 6.0f, 7.0f);
cgmath::vec4 col3(8.0f, 9.0f, 10.0f, 11.0f);
cgmath::vec4 col4(12.0f, 13.0f, 14.0f, 15.0f);
cgmath::mat4 d(col1, col2, col3, col4);
for (auto& col : { 0, 1, 2, 3 })
for (auto& row : { 0, 1, 2, 3 })
Assert::AreEqual(col * 4.0f + row, d[col][row], std::numeric_limits<float>::epsilon());
}
TEST_METHOD(IndexTest)
{
cgmath::vec4 col1(0.0f, 1.0f, 2.0f, 3.0f);
cgmath::vec4 col2(4.0f, 5.0f, 6.0f, 7.0f);
cgmath::vec4 col3(8.0f, 9.0f, 10.0f, 11.0f);
cgmath::vec4 col4(12.0f, 13.0f, 14.0f, 15.0f);
cgmath::mat4 a(col1, col2, col3, col4);
for (auto& col : { 0, 1, 2, 3 })
for (auto& row : { 0, 1, 2, 3 })
Assert::AreEqual(col * 4.0f + row, a[col][row], std::numeric_limits<float>::epsilon());
a[0][0] = 1.0f + 22.0f; a[1][0] -= 2.0f; a[2][0] = 7.0f * 3.0f; a[3][0] = 1.0f + 22.0f;
a[0][1] = 22.0f - 3.0f; a[1][1] += 11.0f; a[2][1] *= 3.0f; a[3][1] = 22.0f - 3.0f;
a[0][2] = 18.0f; a[1][2] = 6.0f / 3.0f; a[2][2] /= 3.0f; a[3][2] = 18.0f;
a[0][3] = 17.0f; a[1][3] = 9.0f / 3.0f; a[2][3] /= 3.0f; a[3][3] = 38.0f;
Assert::AreEqual(1.0f + 22.0f, a[0][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(22.0f - 3.0f, a[0][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(18.0f, a[0][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(17.0f, a[0][3], std::numeric_limits<float>::epsilon());
Assert::AreEqual(4.0f - 2.0f, a[1][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(5.0f + 11.0f, a[1][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(6.0f / 3.0f, a[1][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(9.0f / 3.0f, a[1][3], std::numeric_limits<float>::epsilon());
Assert::AreEqual(7.0f * 3.0f, a[2][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(9.0f * 3.0f, a[2][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(10.0f / 3.0f, a[2][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(11.0f / 3.0f, a[2][3], std::numeric_limits<float>::epsilon());
Assert::AreEqual(1.0f + 22.0f, a[3][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(22.0f - 3.0f, a[3][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(18.0f, a[3][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(38.0f, a[3][3], std::numeric_limits<float>::epsilon());
}
TEST_METHOD(EqualityTest)
{
cgmath::mat4 a;
cgmath::mat4 b;
Assert::IsTrue(a == b);
cgmath::vec4 col1(1.0f, 2.0f, 3.0f, 1.0f);
cgmath::vec4 col2(4.0f, 5.0f, 6.0f, -2.0f);
cgmath::vec4 col3(7.0f, 8.0f, 9.0f, 3.0f);
cgmath::vec4 col4(7.0f, 8.0f, 9.0f, -4.0f);
cgmath::mat4 c(col1, col2, col3, col4);
Assert::IsTrue(a == b);
Assert::IsFalse(a == c);
Assert::IsFalse(b == c);
cgmath::mat4 d(-col1, col2, -col3, col4);
Assert::IsTrue(a == b);
Assert::IsFalse(a == c);
Assert::IsFalse(a == d);
Assert::IsFalse(b == c);
Assert::IsFalse(b == d);
Assert::IsFalse(c == d);
cgmath::mat4 e;
e[0] = col1;
e[1] = col2;
e[2] = col3;
e[3] = col4;
Assert::IsTrue(a == b);
Assert::IsFalse(a == c);
Assert::IsFalse(a == d);
Assert::IsFalse(a == e);
Assert::IsFalse(b == c);
Assert::IsFalse(b == d);
Assert::IsFalse(b == e);
Assert::IsFalse(c == d);
Assert::IsTrue(c == e);
Assert::IsFalse(d == e);
}
TEST_METHOD(InverseTest)
{
cgmath::mat4 a;
for (auto& i : { 0, 1, 2, 3 })
for (auto& j : { 0, 1, 2, 3 })
Assert::IsTrue(std::isnan(cgmath::mat4::inverse(a)[i][j]));
cgmath::mat4 b(1.0f);
Assert::AreEqual<cgmath::mat4>(b, cgmath::mat4::inverse(b));
cgmath::mat4 c(2.0f);
cgmath::mat4 d(0.5f);
Assert::AreEqual<cgmath::mat4>(d, cgmath::mat4::inverse(c));
cgmath::vec4 col1(1.0f, 4.0f, -7.0f, 1.0f);
cgmath::vec4 col2(2.0f, -5.0f, 8.0f, -2.0f);
cgmath::vec4 col3(3.0f, 6.0f, -9.0f, 3.0f);
cgmath::vec4 col4(4.0f, -7.0f, 10.0f, 1.0f);
cgmath::mat4 e(col1, col2, col3, col4);
cgmath::mat4 f = cgmath::mat4::inverse(e);
Assert::AreEqual(1.0f / 8.0f, f[0][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(1.0f / 4.0f, f[0][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(1.0f / 8.0f, f[0][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, f[0][3], std::numeric_limits<float>::epsilon());
Assert::AreEqual(-23.0f / 20.0f, f[1][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(3.0f / 10.0f, f[1][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(43.0f / 60.0f, f[1][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(-2.0f / 5.0f, f[1][3], std::numeric_limits<float>::epsilon());
Assert::AreEqual(-33.0f / 40.0f, f[2][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(3.0f / 20.0f, f[2][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(53.0f / 120.0f, f[2][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(-1.0f / 5.0f, f[2][3], std::numeric_limits<float>::epsilon());
Assert::AreEqual(-3.0f / 10.0f, f[3][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(-2.0f / 5.0f, f[3][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(1.0f / 10.0f, f[3][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(1.0f / 5.0f, f[3][3], std::numeric_limits<float>::epsilon());
}
TEST_METHOD(StreamExtraction)
{
std::stringstream ss1;
cgmath::mat4 a;
ss1 << a;
std::string matstring1 = ss1.rdbuf()->str();
Assert::AreEqual<std::string>("0 0 0 0\n0 0 0 0\n0 0 0 0\n0 0 0 0", matstring1);
std::stringstream ss2;
cgmath::vec4 col1(1.0f, 2.0f, 3.0f, 4.0f);
cgmath::vec4 col2(5.0f, 6.0f, 7.0f, 8.0f);
cgmath::vec4 col3(9.0f, 10.0f, 11.0f, 12.0f);
cgmath::vec4 col4(13.0f, 14.0f, 15.0f, 16.0f);
cgmath::mat4 b(col1, col2, col3, col4);
ss2 << b;
std::string vecstring2 = ss2.rdbuf()->str();
Assert::AreEqual<std::string>("1 5 9 13\n2 6 10 14\n3 7 11 15\n4 8 12 16", vecstring2);
}
TEST_METHOD(Mat4xVec4)
{
cgmath::vec4 v1(3.0f, 6.0f, 4.0f, -2.0f);
cgmath::mat4 m(1.0f);
Assert::AreEqual<cgmath::vec4>(v1, m * v1);
m[0][0] *= 3.0f;
m[1][1] *= 3.0f;
m[2][2] *= 3.0f;
m[3][3] *= 3.0f;
Assert::AreEqual<cgmath::vec4>(v1 * 3.0f, m * v1);
cgmath::vec4 v2(2.0f, -40.0f, 1.0f, 1.0f);
m[2][0] = v2.x;
m[2][1] = v2.y;
m[2][2] = v2.z;
m[3][3] = v2.w;
Assert::AreEqual<cgmath::vec4>(cgmath::vec4(17.0f, -142.0f, 4.0f, -2.0f), m * v1);
cgmath::vec4 v3(-3.0f, 0.0f, 8.0f, 1.0f);
m[1][0] = -2.0f;
m[0][1] = -3.0f;
m[0][2] = -7.0f;
Assert::AreEqual<cgmath::vec4>(cgmath::vec4(7.0f, -311.0f, 29.0f, 1.0f), m * v3);
cgmath::vec4 v4;
Assert::AreEqual<cgmath::vec4>(cgmath::vec4(), m * v4);
cgmath::mat4 m2;
Assert::AreEqual<cgmath::vec4>(v4, m2 * v2);
v4[0] = 1.0f;
v4[1] = 0.0f;
v4[2] = 1.0f;
m2[0][0] = cos(3.14159f); m2[1][0] = -sin(3.14159f); m2[2][0] = 0.0f; m2[3][0] = 0.0f;
m2[0][1] = sin(3.14159f); m2[1][1] = cos(3.14159f); m2[2][1] = 0.0f; m2[3][1] = 0.0f;
m2[0][2] = 0.0f; m2[1][2] = 0.0f; m2[2][2] = 1.0f; m2[3][2] = 0.0f;
m2[0][3] = 0.0f; m2[1][3] = 0.0f; m2[2][3] = 0.0f; m2[3][3] = 1.0f;
Assert::AreEqual(-1.0f, (m2 * v4).x, std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, (m2 * v4).y, 0.00001f);
Assert::AreEqual(1.0f, (m2 * v4).z, std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, (m2 * v4).w, std::numeric_limits<float>::epsilon());
}
TEST_METHOD(Mat4xMat4)
{
cgmath::mat4 m1;
cgmath::mat4 m2(1.0f);
Assert::AreEqual<cgmath::mat4>(m1, m1 * m2);
Assert::AreNotEqual<cgmath::mat4>(m2, m2 * m1);
m1[0][0] = 1.0f; m1[1][0] = 2.0f; m1[2][0] = 3.0f; m1[3][0] = 4.0f;
m1[0][1] = 5.0f; m1[1][1] = 6.0f; m1[2][1] = 7.0f; m1[3][1] = 8.0f;
m1[0][2] = 9.0f; m1[1][2] = 10.0f; m1[2][2] = 11.0f; m1[3][2] = 12.0f;
m1[0][3] = 13.0f; m1[1][3] = 14.0f; m1[2][3] = 15.0f; m1[3][3] = 16.0f;
m2[0][0] = -1.0f; m2[1][0] = -2.0f; m2[2][0] = -3.0f; m2[3][0] = -4.0f;
m2[0][1] = -5.0f; m2[1][1] = -6.0f; m2[2][1] = -7.0f; m2[3][1] = -8.0f;
m2[0][2] = -9.0f; m2[1][2] = -10.0f; m2[2][2] = -11.0f; m2[3][2] = -12.0f;
m2[0][3] = -13.0f; m2[1][3] = -14.0f; m2[2][3] = -15.0f; m2[3][3] = -16.0f;
cgmath::mat4 r;
r[0][0] = -90.0f; r[1][0] = -100.0f; r[2][0] = -110.0f; r[3][0] = -120.0f;
r[0][1] = -202.0f; r[1][1] = -228.0f; r[2][1] = -254.0f; r[3][1] = -280.0f;
r[0][2] = -314.0f; r[1][2] = -356.0f; r[2][2] = -398.0f; r[3][2] = -440.0f;
r[0][3] = -426.0f; r[1][3] = -484.0f; r[2][3] = -542.0f; r[3][3] = -600.0f;
Assert::AreEqual<cgmath::mat4>(r, m1 * m2);
m1[0][0] = 1.0f; m1[1][0] = 2.0f; m1[2][0] = 3.0f; m1[3][0] = 4.0f;
m1[0][1] = 5.0f; m1[1][1] = 6.0f; m1[2][1] = 7.0f; m1[3][1] = 8.0f;
m1[0][2] = 9.0f; m1[1][2] = 10.0f; m1[2][2] = 11.0f; m1[3][2] = 12.0f;
m1[0][3] = 13.0f; m1[1][3] = 14.0f; m1[2][3] = 15.0f; m1[3][3] = 16.0f;
m2[0][0] = 17.0f; m2[1][0] = 18.0f; m2[2][0] = 19.0f; m2[3][0] = 20.0f;
m2[0][1] = 21.0f; m2[1][1] = 22.0f; m2[2][1] = 23.0f; m2[3][1] = 24.0f;
m2[0][2] = 25.0f; m2[1][2] = 26.0f; m2[2][2] = 27.0f; m2[3][2] = 28.0f;
m2[0][3] = 29.0f; m2[1][3] = 30.0f; m2[2][3] = 31.0f; m2[3][3] = 32.0f;
r[0][0] = 250.0f; r[1][0] = 260.0f; r[2][0] = 270.0f; r[3][0] = 280.0f;
r[0][1] = 618.0f; r[1][1] = 644.0f; r[2][1] = 670.0f; r[3][1] = 696.0f;
r[0][2] = 986.0f; r[1][2] = 1028.0f; r[2][2] = 1070.0f; r[3][2] = 1112.0f;
r[0][3] = 1354.0f; r[1][3] = 1412.0f; r[2][3] = 1470.0f; r[3][3] = 1528.0f;
Assert::AreEqual<cgmath::mat4>(r, m1 * m2);
Assert::AreNotEqual<cgmath::mat4>(r, m2 * m1);
r[0][0] = 538.0f; r[1][0] = 612.0f; r[2][0] = 686.0f; r[3][0] = 760.0f;
r[0][1] = 650.0f; r[1][1] = 740.0f; r[2][1] = 830.0f; r[3][1] = 920.0f;
r[0][2] = 762.0f; r[1][2] = 868.0f; r[2][2] = 974.0f; r[3][2] = 1080.0f;
r[0][3] = 874.0f; r[1][3] = 996.0f; r[2][3] = 1118.0f; r[3][3] = 1240.0f;
Assert::AreEqual<cgmath::mat4>(r, m2 * m1);
cgmath::vec4 v(2.0f, 0.0f, -1.0f, 1.0f);
float pi = 3.1415926535897932384626433832795f;
m1[0][0] = cos(pi); m1[1][0] = -sin(pi); m1[2][0] = 0.0f; m1[3][0] = 0.0f;
m1[0][1] = sin(pi); m1[1][1] = cos(pi); m1[2][1] = 0.0f; m1[3][1] = 0.0f;
m1[0][2] = 0.0f; m1[1][2] = 0.0f; m1[2][2] = 1.0f; m1[3][2] = 0.0f;
m1[0][3] = 0.0f; m1[1][3] = 0.0f; m1[2][3] = 0.0f; m1[3][3] = 1.0f;
m2[0][0] = cos(pi); m2[1][0] = -sin(pi); m2[2][0] = 0.0f; m2[3][0] = 0.0f;
m2[0][1] = sin(pi); m2[1][1] = cos(pi); m2[2][1] = 0.0f; m2[3][1] = 0.0f;
m2[0][2] = 0.0f; m2[1][2] = 0.0f; m2[2][2] = 1.0f; m2[3][2] = 0.0f;
m2[0][3] = 0.0f; m2[1][3] = 0.0f; m2[2][3] = 0.0f; m2[3][3] = 1.0f;
cgmath::vec4 res = m1 * m2 * v;
Assert::AreEqual(2.0f, v.x, std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, v.y, 0.000001f);
Assert::AreEqual(-1.0f, v.z, std::numeric_limits<float>::epsilon());
Assert::AreEqual(1.0f, v.w, std::numeric_limits<float>::epsilon());
}
};
} | 44.39548 | 139 | 0.570247 | gerrygoo |
96d4391bfa03cc3db1052b74bd3bd6a7aa9bce5b | 903 | cpp | C++ | selection_sort/main.cpp | sangkyunyoon/learn_algorithms_cpp | 1bfafd37f4f80f6fa7fd9f843e77ddce631f6acb | [
"MIT"
] | null | null | null | selection_sort/main.cpp | sangkyunyoon/learn_algorithms_cpp | 1bfafd37f4f80f6fa7fd9f843e77ddce631f6acb | [
"MIT"
] | null | null | null | selection_sort/main.cpp | sangkyunyoon/learn_algorithms_cpp | 1bfafd37f4f80f6fa7fd9f843e77ddce631f6acb | [
"MIT"
] | null | null | null | //
// Created by Sangkyun Yoon on 3/12/21.
//
#include <iostream>
int main() {
int min, index, temp;
int arr[10] = {1, 10, 5, 8, 7, 6, 4, 3, 2, 9};
//정렬을 해야하는 수 만큼 루프를 돈다.
for (int i = 0; i < 10; ++i) {
//항상 최소값은 가장 큰수보다 큰 값으로 매번 초기화 되어야 한다.
min = 9999;
//정렬 대상을 최소값과 하나씩 비교하면서 정렬되지 않은 대상에서 최소값을 찾는다. 값과 위치 정보 획득
for (int j = i; j < 10; ++j) {
if(min > arr[j]) {
min = arr[j];
index = j;
}
}
//i번째 위치의 값과 최소값을 스왑한다.
temp = arr[i];
arr[i] = arr[index];
arr[index] = temp;
std::cout << i << ": ";
for (int k = 0; k < 10; ++k) {
std::cout << arr[k] << " ";
}
std::cout << std::endl;
}
//배열의 수 만큼 루프를 돌면서 값을 출력한다.
for (int k = 0; k < 10; ++k) {
std::cout << arr[k] << " ";
}
return 0;
} | 23.153846 | 66 | 0.399779 | sangkyunyoon |
96d5e00f80e2249b7da56aef2b6fe0b20657d7c4 | 8,702 | cc | C++ | src/benchmark/sorting_bench.cc | calvincaulfield/lib_calvin | cecf2d8b9cc7b6a4e7f269d0e94e0b80774fc30b | [
"Apache-2.0"
] | null | null | null | src/benchmark/sorting_bench.cc | calvincaulfield/lib_calvin | cecf2d8b9cc7b6a4e7f269d0e94e0b80774fc30b | [
"Apache-2.0"
] | null | null | null | src/benchmark/sorting_bench.cc | calvincaulfield/lib_calvin | cecf2d8b9cc7b6a4e7f269d0e94e0b80774fc30b | [
"Apache-2.0"
] | null | null | null | #include <utility>
#include <vector>
#include <string>
#include "sorting_bench.h"
#include "sort.h"
#include "sort_test.h"
#include "pdqsort.h"
#include "bench.h"
#include "random.h"
#include "in_place_merge_sort.h"
#include "intro_sort_parallel.h"
#include "merge_sort_parallel.h"
#include "boost/sort/sort.hpp"
std::vector<lib_calvin_benchmark::sorting::Algorithm>
lib_calvin_benchmark::sorting::getBenchAlgorithms() {
using namespace lib_calvin_benchmark::sorting;
return {
STD_SORT,
LIB_CALVIN_QSORT,
//ORLP_PDQSORT,
BOOST_PDQSORT,
LIB_CALVIN_BLOCK_QSORT,
STD_STABLE_SORT,
BOOST_SPINSORT,
LIB_CALVIN_MERGESORT,
//LIB_CALVIN_STABLE_BLOCK_QSORT, // weak to all equal
BOOST_FLAT_STABLE_SORT,
LIB_CALVIN_IN_PLACE_MERGESORT,
//LIB_CALVIN_HEAPSORT,
BOOST_BLOCK_INDIRECT_SORT,
LIB_CALVIN_BLOCK_QSORT_PARALLEL,
LIB_CALVIN_BLOCK_QSORT_PARALLEL_ADVANCED,
BOOST_SAMPLE_SORT_PARALLEL,
LIB_CALVIN_MERGESORT_PARALLEL
};
}
std::vector<std::string>
lib_calvin_benchmark::sorting::getAlgorithmNamesAndTags(Algorithm algo) {
switch (algo) {
case STD_SORT:
return { "std::sort", "in-place" };
case STD_STABLE_SORT:
return { "std::stable_sort", "stable" };
case ORLP_PDQSORT:
return { "orlp::pdqsort", "in-place" };
case BOOST_SPINSORT:
return { "boost::spinsort", "stable" };
case BOOST_FLAT_STABLE_SORT:
return { "boost::flat_stable_sort", "stable", "in-place" };
case BOOST_PDQSORT:
return { "boost::pdqsort", "in-place" };
case LIB_CALVIN_QSORT:
return { "lib_calvin::qsort", "in-place" };
case LIB_CALVIN_BLOCK_QSORT:
return { "lib_calvin::block_qsort", "in-place" };
case LIB_CALVIN_MERGESORT:
return { "lib_calvin::mergesort", "stable" };
case LIB_CALVIN_STABLE_BLOCK_QSORT:
return { "lib_calvin::stable_block_qsort", "stable" };
case LIB_CALVIN_IN_PLACE_MERGESORT:
return { "lib_calvin::inplace_mergesort", "stable", "in-place" };
case LIB_CALVIN_HEAPSORT:
return { "lib_calvin::heapsort", "in-place" };
case BOOST_BLOCK_INDIRECT_SORT:
return { "boost::block_indirect_sort_parallel", "in-place", "parallel" };
case BOOST_SAMPLE_SORT_PARALLEL:
return { "boost::sample_sort_parallel", "stable", "parallel" };
case LIB_CALVIN_BLOCK_QSORT_PARALLEL:
return { "lib_calvin::block_qsort_parallel", "parallel", "in-place" };
case LIB_CALVIN_BLOCK_QSORT_PARALLEL_ADVANCED:
return { "lib_calvin::block_qsort_parallel+", "parallel", "in-place" };
case LIB_CALVIN_MERGESORT_PARALLEL:
return { "lib_calvin::mergesort_parallel", "stable", "parallel" };
default:
return { "getAlgorithmName error!" };
}
}
std::string
lib_calvin_benchmark::sorting::getTitle(size_t num) {
return category + " " + lib_calvin_benchmark::getSizeString(benchTestSize[num]) +
" " + benchTitleSuffix;
}
std::string
lib_calvin_benchmark::sorting::getPatternString(InputPattern pattern) {
switch (pattern) {
case RANDOM_ORDER:
return "Random array";
case SORTED_90_PERCENT:
return "Nearly sorted (10% randomized)";
case SORTED:
return "Sorted";
case ALL_EQUAL:
return "All equal";
default:
return "Error";
}
}
template <typename T>
std::string
lib_calvin_benchmark::sorting::getSubCategory(InputPattern pattern) {
return T::to_string() + " / " + getPatternString(pattern);
}
std::vector<std::vector<std::string>>
lib_calvin_benchmark::sorting::getAlgorithmNamesAndTagsVector(std::vector<Algorithm> algorithms) {
using namespace std;
vector<vector<string>> algorithmNamesAndTags = {};
std::for_each(algorithms.begin(), algorithms.end(),
[&algorithmNamesAndTags](Algorithm algo) {
algorithmNamesAndTags.push_back(getAlgorithmNamesAndTags(algo)); });
return algorithmNamesAndTags;
}
void lib_calvin_benchmark::sorting::sortBench() {
sortBench(RANDOM_ORDER);
//sortBench(SORTED);
sortBench(ALL_EQUAL);
}
void lib_calvin_benchmark::sorting::sortBench(InputPattern pattern) {
std::cout << "Size : " << benchTestSize.size() << "\n\n\n";
currentInputPattern = pattern;
for (size_t i = 0; i < benchTestSize.size(); i++) {
std::cout << "Doing : " << i << "\n\n\n";
sortBench<object_16>(i);
sortBench<object_32>(i);
sortBench<object_64>(i);
sortBench<object_vector>(i);
}
}
template <typename T>
void lib_calvin_benchmark::sorting::sortBench(size_t num) {
using namespace std;
using namespace lib_calvin_sort;
string category = "Sorting";
string comment = "";
string unit = "M/s (higher is better)";
vector<string> testCases = { "comparison sorting" };
auto algorithms = getBenchAlgorithms();
vector<vector<double>> results;
for (auto algorithm : algorithms) {
results.push_back(
{ sortBenchSub<T>(algorithm, benchTestSize[num], benchNumIter[num]) });
}
lib_calvin_benchmark::save_bench(category, getSubCategory<T>(currentInputPattern), getTitle(num), comment,
getAlgorithmNamesAndTagsVector(algorithms),
results, testCases, unit, benchOrder[num]);
}
template <typename T>
double lib_calvin_benchmark::sorting::sortBenchSub(
Algorithm algo, size_t testSize, size_t numIter) {
using namespace lib_calvin_sort;
using std::less;
std::cout << "Now benchmarking: " << testSize << " " << "object size: " << sizeof(T) <<
" " << getSubCategory<T>(currentInputPattern) <<
" " << getAlgorithmNamesAndTags(algo)[0] << "\n";
switch (algo) {
case STD_SORT:
return sortBenchSub2(std::sort<T *, less<T>>, testSize, numIter);
case STD_STABLE_SORT:
return sortBenchSub2(std::stable_sort<T *, less<T>>, testSize, numIter);
case ORLP_PDQSORT:
return sortBenchSub2(pdqsort_branchless<T *, less<T>>, testSize, numIter);
case BOOST_SPINSORT:
return sortBenchSub2(boost::sort::spinsort<T *, less<T>>, testSize, numIter);
case BOOST_FLAT_STABLE_SORT:
return sortBenchSub2(boost::sort::flat_stable_sort<T *, less<T>>, testSize, numIter);
case BOOST_PDQSORT:
return sortBenchSub2(boost::sort::pdqsort_branchless<T *, less<T>>, testSize, numIter);
case LIB_CALVIN_QSORT:
return sortBenchSub2(introSort<T *, less<T>>, testSize, numIter);
case LIB_CALVIN_BLOCK_QSORT:
return sortBenchSub2(blockIntroSort<T *, less<T>>, testSize, numIter);
case LIB_CALVIN_MERGESORT:
return sortBenchSub2(mergeSort2<T *, less<T>>, testSize, numIter);
case LIB_CALVIN_STABLE_BLOCK_QSORT:
return sortBenchSub2(stableBlockIntroSort<T *, less<T>>, testSize, numIter);
case LIB_CALVIN_IN_PLACE_MERGESORT:
return sortBenchSub2(inPlaceMergeSort2<T *, less<T>>, testSize, numIter);
case LIB_CALVIN_HEAPSORT:
return sortBenchSub2(heapSort<T *, less<T>>, testSize, numIter);
case BOOST_SAMPLE_SORT_PARALLEL:
return sortBenchSub2(boost::sort::sample_sort<T *, less<T>>, testSize, numIter);
case BOOST_BLOCK_INDIRECT_SORT:
return sortBenchSub2(boost::sort::block_indirect_sort<T *, less<T>>, testSize, numIter);
case LIB_CALVIN_BLOCK_QSORT_PARALLEL:
return sortBenchSub2(introSortParallel<T *, less<T>>, testSize, numIter);
case LIB_CALVIN_BLOCK_QSORT_PARALLEL_ADVANCED:
return sortBenchSub2(introSortParallelAdvanced2<T *, less<T>>, testSize, numIter);
case LIB_CALVIN_MERGESORT_PARALLEL:
return sortBenchSub2(mergeSortParallel<T *, less<T>>, testSize, numIter);
default:
cout << "sortBenchSub error!";
exit(0);
}
}
template <typename T>
double
lib_calvin_benchmark::sorting::sortBenchSub2(void(*sorter)(T *first, T *last, std::less<T>),
size_t testSize, size_t numIter) {
using namespace lib_calvin_sort;
lib_calvin::stopwatch watch;
lib_calvin::random_number_generator gen;
T *testSet = static_cast<T *>(operator new(sizeof(T) * testSize));
double min = 1000000;
for (int i = 0; i < numIter; i++) {
if (currentInputPattern == RANDOM_ORDER) {
for (int j = 0; j < testSize; j++) {
new (testSet + j) T(j);
}
std::shuffle(testSet, testSet + testSize, std::mt19937_64(std::random_device()()));
} else if (currentInputPattern == SORTED_90_PERCENT) {
for (int j = 0; j < testSize; j++) {
if (i % 10 == 0) {
new (testSet + j) T(gen() % testSize);
} else {
new (testSet + j) T(j);
}
}
} else if (currentInputPattern == SORTED) {
for (int j = 0; j < testSize; j++) {
new (testSet + j) T(j);
}
} else if (currentInputPattern == ALL_EQUAL) {
for (int j = 0; j < testSize; j++) {
new (testSet + j) T(0);
}
} else {
cout << "sortBenchSub2 error!";
exit(0);
}
double time = 0;
bool isCorrect = true;
bool isStable = true;
sortTest(sorter, testSet, testSet + testSize, "", time, isCorrect, isStable, std::less<T>());
for (int j = 0; j < testSize; j++) {
testSet[j].~T();
}
if (time < min) {
min = time;
}
}
operator delete(testSet);
return testSize * std::log(testSize) / min / 1000 / 1000;
}
| 30.006897 | 107 | 0.714319 | calvincaulfield |
96d86fcf63579188b7a89f507b9ad824af9fab33 | 22,730 | cpp | C++ | NPlan/NPlan/view/NProjectResourceView.cpp | Avens666/NPlan | 726411b053ded26ce6c1b8c280c994d4c1bac71a | [
"Apache-2.0"
] | 16 | 2018-08-30T11:27:14.000Z | 2021-12-17T02:05:45.000Z | NPlan/NPlan/view/NProjectResourceView.cpp | Avens666/NPlan | 726411b053ded26ce6c1b8c280c994d4c1bac71a | [
"Apache-2.0"
] | null | null | null | NPlan/NPlan/view/NProjectResourceView.cpp | Avens666/NPlan | 726411b053ded26ce6c1b8c280c994d4c1bac71a | [
"Apache-2.0"
] | 14 | 2018-08-30T12:13:56.000Z | 2021-02-06T11:07:44.000Z | // File: NProjectResourceView.cpp
// Copyright: Copyright(C) 2013-2017 Wuhan KOTEI Informatics Co., Ltd. All rights reserved.
// Website: http://www.nuiengine.com
// Description: This code is part of NPlan Project (Powered by NUI Engine)
// Comments:
// Rev: 1
// Created: 2018/8/27
// Last edit: 2015/8/28
// Author: Chen Zhi and his team
// E-mail: [email protected]
// License: APACHE V2.0 (see license file)
#include "NProjectResourceView.h"
#include "../manager/KStringManager.h"
#include "../manager/KProjectManager.h"
extern int g_iScreenWidth; // 屏幕宽度
extern int g_iScreenHeight; // 屏幕高度
NProjectResourceView::NProjectResourceView(CNProjectData* pProjectData)
{
m_down_x=m_down_y=0;
m_p_originalProjData = pProjectData;
if (pProjectData->getTaskBoardItems().size()==0)
{
CNProjectTaskBoardItem board1;
board1.setName(_T("Todo"));
board1.setId(0);
pProjectData->m_taskboard.addBoardItem( board1 );
CNProjectTaskBoardItem board2;
board2.setName(_T("In Process"));
board2.setId(1);
pProjectData->m_taskboard.addBoardItem( board2 );
CNProjectTaskBoardItem board3;
board3.setName(_T("Verify"));
board3.setId(2);
pProjectData->m_taskboard.addBoardItem( board3 );
CNProjectTaskBoardItem board4;
board4.setName(_T("Done"));
board4.setId(3);
pProjectData->m_taskboard.addBoardItem( board4 );
//CNProjectTask task;
//
//task.setStartTime( _T("not a valid time "));
//task.setEndTime( _T( "not a valid time "));
//m_p_originalProjData->addTask( task);
}
m_projectData= *pProjectData;
m_globalResource=*(getProjectManager()->getGlobalResource());
m_down_title = false;
}
NProjectResourceView::~NProjectResourceView( void )
{
}
void NProjectResourceView::initCtrl()
{
kn_int i_btn_w = 100;
kn_int i_btn_h = 40;
int iSlideWidth = 15;
int iGridRow = 3;
int i_grid_col = 6;
int i_width = 700; //窗口高度
int i_height = 480; //窗口宽度
int i_title_height = 38; //标题栏高度
int i_text_width = 65; //文本宽度;
int i_text_x = 20; //文本框left坐标
int i_edit_height = 32; //编辑框高度;
int i_name_edit_width = 598; //项目名称编辑框宽度
int i_pm_edit_width = 500; //项目经理编辑框宽度
int i_start_edit_width = 300; //起始时间编辑框宽度
int i_end_edit_width = 300; //结束时间编辑框宽度
int i_pool_height = 300; //资源池查看框的高度
int i_view_y = 0;
//初始化背景
K9PatchImageDrawable_PTR p_tsk_bg = K9PatchImageDrawable_PTR(new K9PatchImageDrawable(
getSurfaceManager()->GetSurface(_T("./resource/resource_bg.9.png")),true));
m_group_project = KViewGroup_PTR(new KViewGroup);
m_group_project->Create(RERect::MakeXYWH((g_iScreenWidth-i_width)/2,(g_iScreenHeight-i_height)/2,i_width,i_height));
m_group_project->addDrawable(p_tsk_bg);
AddView(m_group_project);
//初始化标题
m_text_title = KTextView_PTR(new KTextView);
m_text_title->SetText(getStringManager()->GetStringByID(_T("project_info")));
m_text_title->setTextAlign(REPaint::kLeft_Align);
m_text_title->SetTextColor(RE_ColorWHITE,RE_ColorWHITE,RE_ColorWHITE,RE_ColorWHITE);
m_text_title->SetFontSize(18);
m_text_title->Create(20,4,i_width - 46,i_title_height);
m_group_project->AddView(m_text_title);
m_text_title->enableMessage(false);
i_view_y = 4 + i_title_height + 15;
//project name and edit
m_text_name = KTextView_PTR(new KTextView);
m_text_name->SetText(getStringManager()->GetStringByID(_T("name")));
m_text_name->setTextAlign(REPaint::kLeft_Align);
m_text_name->SetTextColor(0xff666666,0xff666666,0xff666666,0xff666666);
m_text_name->SetFontSize(14);
m_text_name->Create(i_text_x,i_view_y,i_text_width,i_edit_height);
m_text_name->enableMessage(false);
m_group_project->AddView(m_text_name);
m_edit_name = KEditView_PTR( new KEditView);
K9PatchImageDrawable_PTR p_name = K9PatchImageDrawable_PTR(new K9PatchImageDrawable(
getSurfaceManager()->GetSurface(_T("./resource/public_resource_text.9.png")),true));
p_name->SetRect(RERect::MakeWH(i_name_edit_width,i_edit_height));
K9PatchImageDrawable_PTR p_name_a = K9PatchImageDrawable_PTR(new K9PatchImageDrawable(
getSurfaceManager()->GetSurface(_T("./resource/public_resource_text_a.9.png")),true));
p_name_a->SetRect(RERect::MakeWH(i_name_edit_width,i_edit_height));
m_edit_name->Create(m_text_name->GetRect().right(),i_view_y,i_name_edit_width,i_edit_height);
m_edit_name->Init(5,5,RE_ColorBLACK);
m_edit_name->SetTextColor(0xff444444,0xff444444,0xff444444,0xff444444);;
m_edit_name->setBKDrawable(p_name);
m_edit_name->setFocusDrawable(p_name_a);
m_edit_name->SetCrossIndex(0);
m_edit_name->setTextOff(2,2);
m_edit_name->setCrossOff(4);
m_edit_name->SetText(m_projectData.getName());
m_group_project->AddView(m_edit_name);
i_view_y += i_edit_height+15;
//start and end time
if (!m_projectData.getProBeginTime().is_not_a_date_time())
{
m_text_time_start = KTextView_PTR( new KTextView);
m_text_time_start->SetText(getStringManager()->GetStringByID(_T("task_resource_time_start"))+ _T(" ") + to_iso_extended_wstring(m_projectData.getProBeginTime().date()) );
m_text_time_start->setTextAlign(REPaint::kLeft_Align);
m_text_time_start->SetTextColor(0xff666666,0xff666666,0xff666666,0xff666666);
m_text_time_start->SetFontSize(14);
m_text_time_start->Create(i_text_x,i_view_y,(i_text_width+i_start_edit_width)/2,i_edit_height);
m_text_time_start->enableMessage(false);
m_group_project->AddView(m_text_time_start);
m_text_time_end = KTextView_PTR(new KTextView);
m_text_time_end->SetText(getStringManager()->GetStringByID(_T("task_resource_time_end")) + _T(" ") + to_iso_extended_wstring(m_projectData.getProEndTime().date()) );
m_text_time_end->setTextAlign(REPaint::kLeft_Align);
m_text_time_end->SetTextColor(0xff666666,0xff666666,0xff666666,0xff666666);
m_text_time_end->SetFontSize(14);
m_text_time_end->Create(m_text_time_start->GetRect().right(), i_view_y,(i_text_width+i_end_edit_width)/2,i_edit_height);
m_text_time_end->enableMessage(false);
m_group_project->AddView(m_text_time_end);
i_view_y += i_edit_height+15;
}
//project manager name and edit
m_text_pm =KTextView_PTR( new KTextView);
m_text_pm->SetText(getStringManager()->GetStringByID(_T("task_owner")));
m_text_pm->setTextAlign(REPaint::kLeft_Align);
m_text_pm->SetTextColor(0xff666666,0xff666666,0xff666666,0xff666666);
m_text_pm->SetFontSize(14);
m_text_pm->Create(i_text_x, i_view_y,i_text_width,i_edit_height);
m_text_pm->enableMessage(false);
m_group_project->AddView(m_text_pm);
m_edit_pm = KEditView_PTR(new KEditView);
K9PatchImageDrawable_PTR p_manager_name = K9PatchImageDrawable_PTR(new K9PatchImageDrawable(
getSurfaceManager()->GetSurface(_T("./resource/public_resource_text.9.png")),true));
K9PatchImageDrawable_PTR p_manager_name_a = K9PatchImageDrawable_PTR(new K9PatchImageDrawable(
getSurfaceManager()->GetSurface(_T("./resource/public_resource_text_a.9.png")),true));
p_manager_name->SetRect(RERect::MakeWH((i_pm_edit_width - i_text_width)/2,i_edit_height));
p_manager_name_a->SetRect(RERect::MakeWH((i_pm_edit_width - i_text_width)/2,i_edit_height));
m_edit_pm->Create(m_text_pm->GetRect().right(), i_view_y,(i_pm_edit_width - i_text_width)/2,i_edit_height);
m_edit_pm->Init(5,5,RE_ColorBLACK);
m_edit_pm->SetTextColor(0xff444444,0xff444444,0xff444444,0xff444444);;
m_edit_pm->setBKDrawable(p_manager_name);
m_edit_pm->setFocusDrawable(p_manager_name_a);
m_edit_pm->SetCrossIndex(0);
m_edit_pm->setTextOff(2,2);
m_edit_pm->setCrossOff(4);
m_edit_pm->SetText(m_projectData.getLeader());
m_edit_pm->setReadonly(true);
i_view_y += i_edit_height+15;
p_pmedit_active = K9PatchImageDrawable_PTR(
new K9PatchImageDrawable(getSurfaceManager()->GetSurface(_T("./resource/member_bg_a.9.png")),true));
p_pmedit_active->SetRect(RERect::MakeXYWH(0,0,m_edit_pm->GetRect().width(),m_edit_pm->GetRect().height()));
p_pmedit_active->SetShow(FALSE);
m_edit_pm->addDrawable(p_pmedit_active);
m_group_project->AddView(m_edit_pm);
//resource management
//resource text
m_text_resource = KTextView_PTR( new KTextView);
m_text_resource->SetText(getStringManager()->GetStringByID(_T("project_res")));
m_text_resource->setTextAlign(REPaint::kLeft_Align);
m_text_resource->SetTextColor(0xff666666,0xff666666,0xff666666,0xff666666);
m_text_resource->SetFontSize(14);
m_text_resource->Create(i_text_x, i_view_y,i_text_width*4,i_edit_height);
m_text_resource->enableMessage(false);
m_group_project->AddView(m_text_resource);
i_view_y += i_edit_height+2;
//add people button
KImgButtonView_PTR p_btn_add;
m_group_project->createImgViewHelper(&p_btn_add,
_T("./resource/btn_add_n.png")
, _T("./resource/btn_add_n.png"),
_T("./resource/btn_add_a.png"),
m_edit_name->GetRect().right()-30, m_text_resource->GetRect().top() + 5);
p_btn_add->m_clicked_signal.connect(this,&NProjectResourceView::onBtnAdd);
//project resource pool
/** 添加一个用于滑动的人员*/
m_p_drag_view = NDragStaffView_PTR( new NDragStaffView(_T(""),(res_type)0,0) );
m_p_drag_view->SetTextColor(0xFF555555,0xFF555555,0xFF555555,0xFF555555);
m_p_drag_view->setOpacity(0X88);
m_p_drag_view->SetShow(FALSE);
AddView(m_p_drag_view);
m_grou_resource = KViewGroup_PTR(new KViewGroup);
K9PatchImageDrawable_PTR draw_resource = K9PatchImageDrawable_PTR(new K9PatchImageDrawable(
getSurfaceManager()->GetSurface(_T("./resource/public_resource_people_bg.9.png")),true));
draw_resource->SetRect(RERect::MakeWH(i_width - 46,i_pool_height));
m_grou_resource->Create(23, i_view_y,i_width - 46,i_pool_height);
m_grou_resource->addDrawable(draw_resource);
m_group_project->AddView(m_grou_resource);
RERect rect;
rect.setXYWH(10,2,draw_resource->GetRect().width() - 20,draw_resource->GetRect().height() - 4);
//gridview
m_view_satff_grid = NGridView_PTR( new NGridView((rect.width()-20) / i_grid_col,rect.height() / iGridRow,rect) );
m_view_satff_grid->Create(rect);
m_view_satff_grid->m_sign_GridItemDClicked.connect(this,&NProjectResourceView::onResourceDClick);
m_grou_resource->AddView(m_view_satff_grid);
//init project resource pool
int count = m_projectData.getResourcePool().getCount();
int leaderID = m_projectData.getResourceIdByName(m_projectData.getLeader().c_str());
for (int i = 0 ; i < count; i++)
{
CNProjectResource * tempRes = m_projectData.getResourcePool().getResByIndex(i);
NStaffView_PTR pView = NStaffView_PTR( new NStaffView( tempRes->getName() ,tempRes->getType(),tempRes->getId()) );
pView->SetTextColor(0xff444444,0xff444444,0xff444444,0xff444444);
pView->m_sign_down.connect(this,&NProjectResourceView::onDownMem);
pView->setLeader(leaderID == tempRes->getId());
m_view_satff_grid->AddView(pView);
}
//初始化游标
KSlideView_PTR p_slide = KSlideView_PTR(new KSlideView() );
K9PatchImageDrawable_PTR normal = K9PatchImageDrawable_PTR(
new K9PatchImageDrawable(getSurfaceManager()->GetSurface(_T("./resource/list_silder_bk.9.png")),true));
p_slide->setBKDrawable(normal);
normal = K9PatchImageDrawable_PTR(
new K9PatchImageDrawable(getSurfaceManager()->GetSurface(_T("./resource/list_silder_cursor.9.png")),true));
p_slide->setIconDrawable(normal);
p_slide->Create( RERect::MakeXYWH( m_view_satff_grid->GetRect().width()-8,10,18,m_view_satff_grid->GetRect().height() - 20));
p_slide->init(PROCESS_Vertical);
p_slide->showBK(TRUE);
m_view_satff_grid->BindSlide(p_slide);
m_grou_resource->AddView(p_slide);
//取消
KImgButtonView_PTR p_btn_ok;
m_group_project->createImgView9PatchHelper(&p_btn_ok,
_T("./resource/btn_ok_n.9.png"),
_T("./resource/btn_ok_a.9.png"),
_T("./resource/btn_ok_n.9.png"),
i_width - 23 - i_btn_w, m_grou_resource->GetRect().bottom()+13, i_btn_w, i_btn_h);
p_btn_ok->SetText(getStringManager()->GetStringByID(_T("ok")));
p_btn_ok->SetFontSize(14);
p_btn_ok->setStateChangeEnable(true);
p_btn_ok->SetTextColor(RE_ColorWHITE,RE_ColorWHITE,0xfffff000,RE_ColorWHITE);
p_btn_ok->SetTextBound(RERect::MakeXYWH(8,10,80,24));
p_btn_ok->setTextAlign(REPaint::kCenter_Align);
p_btn_ok->m_clicked_signal.connect(this,&NProjectResourceView::onBtnOk);
//ȷ��
KImgButtonView_PTR p_btn_cancel;
m_group_project->createImgView9PatchHelper(&p_btn_cancel,
_T("./resource/btn_cancel_n.9.png"),
_T("./resource/btn_cancel_a.9.png"),
_T("./resource/btn_cancel_n.9.png"),
p_btn_ok->GetRect().left()- 15 - i_btn_w, m_grou_resource->GetRect().bottom()+13, i_btn_w, i_btn_h);
p_btn_cancel->SetText(getStringManager()->GetStringByID(_T("cancel")));
p_btn_cancel->SetFontSize(14);
p_btn_cancel->setStateChangeEnable(true);
p_btn_cancel->SetTextColor(RE_ColorWHITE,RE_ColorWHITE,0xfffff000,RE_ColorWHITE);
p_btn_cancel->SetTextBound(RERect::MakeXYWH(8,10,80,24));
p_btn_cancel->setTextAlign(REPaint::kCenter_Align);
p_btn_cancel->m_clicked_signal.connect(this,&NProjectResourceView::onBtnCancle);
p_tsk_bg->SetRect(RERect::MakeWH(i_width,p_btn_ok->GetRect().bottom() + 30));
m_group_project->changeViewLayerTop(m_grou_resource);
m_group_project->m_sign_down.connect(this,&NProjectResourceView::onDown);
m_group_project->m_sign_move.connect(this,&NProjectResourceView::onMove);
m_group_project->m_sign_up.connect(this,&NProjectResourceView::onUp);
//�˳�
m_group_project->createImgViewHelper(&m_p_btn_exit,
_T("./resource/btn_delete_n.png")
,_T("./resource/btn_delete_a.png"),
_T("./resource/btn_delete_f.png"),
i_width - 45,3);
m_p_btn_exit->m_clicked_signal.connect(this,&NProjectResourceView::onBtnCancle);
}
/**
* 确定
*/
void NProjectResourceView::onBtnOk(KView_PTR p)
{
if (m_edit_name->getText().size()==0)
{
MessageBox(GetScreen()->getWnd(), getStringManager()->GetStringByID(_T("prj_name_error")).c_str(),getStringManager()->GetStringByID(_T("error")).c_str(), MB_OK);
return;
}
m_projectData.setName(m_edit_name->getText().c_str());
m_projectData.setLeader(m_edit_pm->getText());
m_p_originalProjData->setResourcePool(m_projectData.getResourcePool());
m_p_originalProjData->setName(m_edit_name->getText().c_str());
m_p_originalProjData->setLeader(m_edit_pm->getText());
endModal(KN_REUSLT_OK,TRUE);
if (m_p_originalProjData->getFileName().empty())
{
kn_string filePath = _T("project/");
filePath+=m_edit_name->getText();
filePath+=_T(".nprj");
m_p_originalProjData->setFileName(filePath);
if (NO_ERROR!=m_p_originalProjData->savePrjFile())
{
MessageBox(GetScreen()->getWnd(), getStringManager()->GetStringByID(_T("create_file_fail")).c_str(),getStringManager()->GetStringByID(_T("error")).c_str(), MB_OK);
}
}
}
/**
* 取消
*/
void NProjectResourceView::onBtnCancle(KView_PTR p)
{
endModal(KN_REUSLT_CANCLE,TRUE);
}
void NProjectResourceView::onBtnAdd( KView_PTR p )
{
vector<CNProjectResource> vec_project_member = m_projectData.getResourcePool().getResources();
vector<NMemberMsg> vec_project_mem;
CNProjectTask_LST* taskList=m_projectData.getpManTasks();
for (vector<CNProjectResource>::iterator itr = vec_project_member.begin();
itr != vec_project_member.end() ; ++itr)
{
NMemberMsg member = NMemberMsg(*itr);
for (CNProjectTask_LST::iterator taskIter=taskList->begin();taskIter!=taskList->end();taskIter++)
{
if (taskIter->getLeaderName()==itr->getName())
{
member.b_update=false;
}
}
vec_project_mem.push_back(member);
}
vector<CNProjectResource> vec_global_member =m_globalResource.getResources();
vector<NMemberMsg> vec_global_mem;
for (vector<CNProjectResource>::iterator itr = vec_global_member.begin();
itr != vec_global_member.end() ; ++itr)
{
vec_global_mem.push_back(NMemberMsg(*itr));
}
NMemberSourceView_PTR m_p_mem = NMemberSourceView_PTR( new NMemberSourceView(vec_global_mem, vec_project_mem) );
m_p_mem->Create(0,0,g_iScreenWidth,g_iScreenHeight);
m_p_mem->initCtrl();
m_p_mem->m_sign_btn_ok.connect(this,&NProjectResourceView::UpdateResourceGrid);
AddView(m_p_mem);
m_p_mem->doModal();
}
void NProjectResourceView::UpdateResourceGrid(vector<NMemberMsg>& v )
{
m_view_satff_grid->resetCursorPos();
for (int i = m_view_satff_grid->getViewCount() - 1; i >= 0 ; i--)
{
m_view_satff_grid->AddViewToDel(m_view_satff_grid->getViewByIndex(i));
m_view_satff_grid->eraseView(m_view_satff_grid->getViewByIndex(i));
}
std::vector <CNProjectResource > NewResources;
int offset =0;
bool leaderStillExist=false;
//OutputDebugString(_T("UpdateResourceGrid : "));
for (vector<NMemberMsg>::iterator it = v.begin();
it != v.end() ; it++)
{
NStaffView_PTR pView = NStaffView_PTR( new NStaffView((*it)) );
pView->SetTextColor(0xFF555555,0xFF555555,0xFF555555,0xFF555555);
m_view_satff_grid->AddView(pView);
pView->setCanLeader(true);
pView->m_sign_down.connect(this,&NProjectResourceView::onDownMem);
if (m_edit_pm->getText()==pView->GetName())
{
pView->setLeader(true);
leaderStillExist=true;
}
//OutputDebugString(it->str_name.c_str());
}
if (leaderStillExist==false)
{
m_edit_pm->SetText(_T(""));
}
//OutputDebugString(_T("\n"));
TranslateMemberListToResouceList(v,m_projectData.getResourcePool(),m_globalResource);
}
void NProjectResourceView::TranslateMemberListToResouceList(vector<NMemberMsg>& vecMemeber,CNProjectResourcePool& originalResourcePool, CNProjectResourcePool& extraResourcePool )
{
std::vector <CNProjectResource > NewResources;
int offset =0;
//OutputDebugString(_T("TranslateMemberListToResouceList : "));
for (vector<NMemberMsg>::iterator it = vecMemeber.begin();
it != vecMemeber.end() ; it++)
{
//OutputDebugString(it->str_name.c_str());
// CNProjectResource* pFoundResource = originalResourcePool.getResourceByID(it->id);
// if (pFoundResource!=NULL && pFoundResource->getName()==it->str_name)
// {
// CNProjectResource tempResource(*pFoundResource);
// NewResources.push_back(tempResource);
// }
// else
// {
// pFoundResource= extraResourcePool.getResourceByID(it->id);
// if (pFoundResource!=NULL)
// {
// CNProjectResource tempResource(*pFoundResource);
// tempResource.setId(offset + m_projectData.getResourcePool().getLargestResId());
// offset++;
// NewResources.push_back(tempResource);
// }
// }
CNProjectResource* pFoundResource=NULL;
int resourceID=originalResourcePool.findResourceID(it->str_name.c_str());
//not in original pool
if (resourceID == -1)
{
resourceID = originalResourcePool.getLargestResId();
pFoundResource = extraResourcePool.getResourceByID(it->id);
if (pFoundResource!=NULL)
{
CNProjectResource tempResource(*pFoundResource);
tempResource.setId(offset + m_projectData.getResourcePool().getLargestResId());
offset++;
NewResources.push_back(tempResource);
}
}
//in original pool
else
{
pFoundResource = originalResourcePool.getResourceByID(resourceID);
if (pFoundResource!=NULL)
{
CNProjectResource tempResource(*pFoundResource);
NewResources.push_back(tempResource);
}
}
}
//OutputDebugString(_T("\n"));
originalResourcePool.setResources(NewResources);
}
void NProjectResourceView::MergeResourceByName(CNProjectResourcePool& dstPool, CNProjectResourcePool&srcPool)
{
vector<CNProjectResource> srcResourceVector = srcPool.getResources();
for (vector<CNProjectResource>::iterator iter =srcResourceVector.begin();iter!=srcResourceVector.end();iter++)
{
if(-1 == dstPool.findResourceID(iter->getName().c_str()))
{
if (dstPool.checkResourceByID(iter->getId()))
{
iter->setId(dstPool.getLargestResId());
}
dstPool.addResource(*iter);
}
}
}
/**
* 标题移动相关
*/
void NProjectResourceView::onDown( kn_int iScreenX, kn_int iScreenY, KMessageMouse* pMsg )
{
iScreenX -= m_group_project->GetRect().left();
iScreenY -= m_group_project->GetRect().top();
if (m_text_title->isPointInView(iScreenX,iScreenY))
{
m_down_title = true;
m_down_x = iScreenX;
m_down_y = iScreenY;
}
}
/**
* 标题移动相关
*/
void NProjectResourceView::onMove( kn_int iScreenX, kn_int iScreenY, KMessageMouse* pMsg )
{
if (m_down_title)
{
m_group_project->SetPosition(iScreenX - m_down_x ,iScreenY - m_down_y );
InvalidateView(true);
}
}
/**
* 标题移动相关
*/
void NProjectResourceView::onUp( kn_int iScreenX, kn_int iScreenY, KMessageMouse* pMsg )
{
m_down_title = false;
}
void NProjectResourceView::onResourceDClick( KView_PTR view )
{
NStaffView_PTR staff = VIEW_PTR(NStaffView) (view);
if (staff==NULL)
{
return;
}
m_edit_pm->SetText(staff->GetName());
}
/**
* 拖拽一个成员到负责人窗口
*/
void NProjectResourceView::onDownMem(kn_int x, kn_int y,KMessageMouse* msg)
{
NStaffView_PTR pView = VIEW_PTR(NStaffView)(msg->m_p_view);
kn_string str ;
//������û������ ��������ק cxc 2014-5-5
//if (pView->getCanUpdate())
{
pView->GetName(str);
m_p_drag_view->SetResourceType(pView->GetResourceType());
m_p_drag_view->SetName(str);
m_p_drag_view->OnDown(x,y,msg);
}
}
void NProjectResourceView::OnMemDrag(KMessageDrag* msg)
{
kn_int ix,iy,lx,ly;
ix = msg->m_pos_x;
iy = msg->m_pos_y;
KView_PTR p = msg->m_p_drag_view;
m_edit_pm->GetScreenXY(lx,ly);
if (ix > lx && ix < lx + m_edit_pm->GetRect().width()&&
iy > ly && iy < ly + m_edit_pm->GetRect().height())
{
ix -= lx;
iy -= ly;
p_pmedit_active->SetShow(true);
}
else
{
p_pmedit_active->SetShow(false);
}
}
void NProjectResourceView::OnMemDragEnd(KMessageDrag* msg)
{
kn_int ix,iy,lx,ly;
ix = msg->m_pos_x;
iy = msg->m_pos_y;
KView_PTR p = msg->m_p_drag_view;
m_edit_pm->GetScreenXY(lx,ly);
if (ix > lx && ix < lx + m_edit_pm->GetRect().width()&&
iy > ly && iy < ly + m_edit_pm->GetRect().height())
{
ix -= lx;
iy -= ly;
m_edit_pm->SetText((VIEW_PTR(NStaffView)(p))->GetName());
p_pmedit_active->SetShow(FALSE);
for (int i = 0; i < m_view_satff_grid->getViewCount() ; i++)
{
NStaffView_PTR pview = VIEW_PTR(NStaffView)(m_view_satff_grid->getViewByIndex(i));
pview->setLeader(pview->getMsg() == (VIEW_PTR(NStaffView)(p))->getMsg());
}
m_view_satff_grid->InvalidateView();
}
InvalidateView();
}
void NProjectResourceView::onDragDirect( KMessageDrag* msg )
{
if (msg)
{
if (msg->m_drag_type == TASK_GROUP_DRAG_UP)
{
OnMemDragEnd(msg);
}
if (msg->m_drag_type == TASK_GROUP_DRAG)
{
OnMemDrag(msg);
}
}
}
| 35.682889 | 180 | 0.729916 | Avens666 |
96dbaa699af4505593828a33675e95e9fd705c74 | 12,955 | cpp | C++ | src/cli/test/test_CLI.cpp | pozsa/sarus | 5117a0da8d2171c4bf9ebc6835e0dd6b73812930 | [
"BSD-3-Clause"
] | null | null | null | src/cli/test/test_CLI.cpp | pozsa/sarus | 5117a0da8d2171c4bf9ebc6835e0dd6b73812930 | [
"BSD-3-Clause"
] | null | null | null | src/cli/test/test_CLI.cpp | pozsa/sarus | 5117a0da8d2171c4bf9ebc6835e0dd6b73812930 | [
"BSD-3-Clause"
] | null | null | null | /*
* Sarus
*
* Copyright (c) 2018-2020, ETH Zurich. All rights reserved.
*
* Please, refer to the LICENSE file in the root directory.
* SPDX-License-Identifier: BSD-3-Clause
*
*/
#include <memory>
#include <boost/filesystem.hpp>
#include "common/Utility.hpp"
#include "common/Config.hpp"
#include "common/CLIArguments.hpp"
#include "cli/CommandObjectsFactory.hpp"
#include "cli/CLI.hpp"
#include "cli/CommandHelp.hpp"
#include "cli/CommandHelpOfCommand.hpp"
#include "cli/CommandImages.hpp"
#include "cli/CommandLoad.hpp"
#include "cli/CommandPull.hpp"
#include "cli/CommandRmi.hpp"
#include "cli/CommandRun.hpp"
#include "cli/CommandSshKeygen.hpp"
#include "cli/CommandVersion.hpp"
#include "runtime/Mount.hpp"
#include "test_utility/config.hpp"
#include "test_utility/unittest_main_function.hpp"
using namespace sarus;
TEST_GROUP(CLITestGroup) {
};
std::unique_ptr<cli::Command> generateCommandFromCLIArguments(const common::CLIArguments& args) {
auto cli = cli::CLI{};
auto configRAII = test_utility::config::makeConfig();
return cli.parseCommandLine(args, configRAII.config);
}
template<class ExpectedDynamicType>
void checkCommandDynamicType(const cli::Command& command) {
CHECK(dynamic_cast<const ExpectedDynamicType*>(&command) != nullptr);
}
TEST(CLITestGroup, LogLevel) {
auto& logger = common::Logger::getInstance();
generateCommandFromCLIArguments({"sarus"});
CHECK(logger.getLevel() == common::LogLevel::WARN);
generateCommandFromCLIArguments({"sarus", "--verbose"});
CHECK(logger.getLevel() == common::LogLevel::INFO);
generateCommandFromCLIArguments({"sarus", "--debug"});
CHECK(logger.getLevel() == common::LogLevel::DEBUG);
}
TEST(CLITestGroup, CommandTypes) {
auto command = generateCommandFromCLIArguments({"sarus"});
checkCommandDynamicType<cli::CommandHelp>(*command);
command = generateCommandFromCLIArguments({"sarus", "help"});
checkCommandDynamicType<cli::CommandHelp>(*command);
command = generateCommandFromCLIArguments({"sarus", "--help"});
checkCommandDynamicType<cli::CommandHelp>(*command);
command = generateCommandFromCLIArguments({"sarus", "help", "pull"});
checkCommandDynamicType<cli::CommandHelpOfCommand>(*command);
command = generateCommandFromCLIArguments({"sarus", "images"});
checkCommandDynamicType<cli::CommandImages>(*command);
command = generateCommandFromCLIArguments({"sarus", "load", "archive.tar", "image"});
checkCommandDynamicType<cli::CommandLoad>(*command);
command = generateCommandFromCLIArguments({"sarus", "pull", "image"});
checkCommandDynamicType<cli::CommandPull>(*command);
command = generateCommandFromCLIArguments({"sarus", "rmi", "image"});
checkCommandDynamicType<cli::CommandRmi>(*command);
command = generateCommandFromCLIArguments({"sarus", "run", "image"});
checkCommandDynamicType<cli::CommandRun>(*command);
command = generateCommandFromCLIArguments({"sarus", "ssh-keygen"});
checkCommandDynamicType<cli::CommandSshKeygen>(*command);
command = generateCommandFromCLIArguments({"sarus", "version"});
checkCommandDynamicType<cli::CommandVersion>(*command);
command = generateCommandFromCLIArguments({"sarus", "--version"});
checkCommandDynamicType<cli::CommandVersion>(*command);
}
TEST(CLITestGroup, UnrecognizedGlobalOptions) {
CHECK_THROWS(common::Error, generateCommandFromCLIArguments({"sarus", "--mpi", "run"}));
CHECK_THROWS(common::Error, generateCommandFromCLIArguments({"sarus", "---run"}));
}
std::shared_ptr<common::Config> generateConfig(const common::CLIArguments& args) {
auto commandName = args.argv()[0];
auto configRAII = test_utility::config::makeConfig();
auto factory = cli::CommandObjectsFactory{};
auto command = factory.makeCommandObject(commandName, args, configRAII.config);
return configRAII.config;
}
TEST(CLITestGroup, generated_config_for_CommandLoad) {
// centralized repo
{
auto conf = generateConfig(
{"load", "--centralized-repository", "archive.tar", "library/image:tag"});
auto expectedArchivePath = boost::filesystem::absolute("archive.tar");
CHECK_EQUAL(conf->directories.tempFromCLI.empty(), true);
CHECK_EQUAL(conf->useCentralizedRepository, true);
CHECK_EQUAL(conf->archivePath.string(), expectedArchivePath.string());
CHECK_EQUAL(conf->imageID.server, std::string{"load"});
CHECK_EQUAL(conf->imageID.repositoryNamespace, std::string{"library"});
CHECK_EQUAL(conf->imageID.image, std::string{"image"});
CHECK_EQUAL(conf->imageID.tag, std::string{"tag"});
}
// temp dir
{
auto conf = generateConfig(
{"load", "--temp-dir=/custom-temp-dir", "archive.tar", "library/image:tag"});
auto expectedArchivePath = boost::filesystem::absolute("archive.tar");
CHECK_EQUAL(conf->directories.temp.string(), std::string{"/custom-temp-dir"});
CHECK_EQUAL(conf->useCentralizedRepository, false);
CHECK_EQUAL(conf->archivePath.string(), expectedArchivePath.string());
CHECK_EQUAL(conf->imageID.server, std::string{"load"});
CHECK_EQUAL(conf->imageID.repositoryNamespace, std::string{"library"});
CHECK_EQUAL(conf->imageID.image, std::string{"image"});
CHECK_EQUAL(conf->imageID.tag, std::string{"tag"});
}
}
TEST(CLITestGroup, generated_config_for_CommandPull) {
// defaults
{
auto conf = generateConfig({"pull", "ubuntu"});
CHECK(conf->directories.tempFromCLI.empty() == true);
CHECK(conf->useCentralizedRepository == false);
CHECK(conf->imageID.server == "index.docker.io");
CHECK(conf->imageID.repositoryNamespace == "library");
CHECK(conf->imageID.image == "ubuntu");
CHECK(conf->imageID.tag == "latest");
}
// centralized repo
{
auto conf = generateConfig({"pull", "--centralized-repository", "ubuntu"});
CHECK(conf->directories.tempFromCLI.empty() == true);
CHECK(conf->useCentralizedRepository == true);
CHECK(conf->imageID.server == "index.docker.io");
CHECK(conf->imageID.repositoryNamespace == "library");
CHECK(conf->imageID.image == "ubuntu");
CHECK(conf->imageID.tag == "latest");
}
// temp-dir option and custom server
{
auto conf = generateConfig(
{"pull",
"--temp-dir=/custom-temp-dir",
"my.own.server:5000/user/image:tag"});
CHECK(conf->directories.temp.string() == "/custom-temp-dir");
CHECK(conf->imageID.server == "my.own.server:5000");
CHECK(conf->imageID.repositoryNamespace == "user");
CHECK(conf->imageID.image == "image");
CHECK(conf->imageID.tag == "tag");
}
}
TEST(CLITestGroup, generated_config_for_CommandRmi) {
// defaults
{
auto conf = generateConfig({"rmi", "ubuntu"});
CHECK_EQUAL(conf->useCentralizedRepository, false);
CHECK_EQUAL(conf->imageID.server, std::string{"index.docker.io"});
CHECK_EQUAL(conf->imageID.repositoryNamespace, std::string{"library"});
CHECK_EQUAL(conf->imageID.image, std::string{"ubuntu"});
CHECK_EQUAL(conf->imageID.tag, std::string{"latest"});
}
// centralized repo
{
auto conf = generateConfig({"rmi", "--centralized-repository", "ubuntu"});
CHECK_EQUAL(conf->useCentralizedRepository, true);
CHECK_EQUAL(conf->imageID.server, std::string{"index.docker.io"});
CHECK_EQUAL(conf->imageID.repositoryNamespace, std::string{"library"});
CHECK_EQUAL(conf->imageID.image, std::string{"ubuntu"});
CHECK_EQUAL(conf->imageID.tag, std::string{"latest"});
}
}
TEST(CLITestGroup, generated_config_for_CommandRun) {
// empty values
{
auto conf = generateConfig({"run", "image"});
CHECK_EQUAL(conf->imageID.server, std::string{"index.docker.io"});
CHECK_EQUAL(conf->imageID.repositoryNamespace, std::string{"library"});
CHECK_EQUAL(conf->imageID.image, std::string{"image"});
CHECK_EQUAL(conf->imageID.tag, std::string{"latest"});
CHECK_EQUAL(conf->useCentralizedRepository, false);
CHECK_EQUAL(conf->commandRun.addInitProcess, false);
CHECK_EQUAL(conf->commandRun.mounts.size(), 1); // 1 site mount + 0 user mount
CHECK_EQUAL(conf->commandRun.useMPI, false);
CHECK_EQUAL(conf->commandRun.enableGlibcReplacement, 0);
CHECK_EQUAL(conf->commandRun.enableSSH, false);
CHECK_EQUAL(conf->commandRun.allocatePseudoTTY, false);
CHECK(conf->commandRun.execArgs.argc() == 0);
}
// centralized repository
{
auto conf = generateConfig({"run", "--centralized-repository", "image"});
CHECK_EQUAL(conf->useCentralizedRepository, true);
}
// entrypoint
{
auto conf = generateConfig({"run", "--entrypoint", "myprogram", "image"});
CHECK_EQUAL(conf->commandRun.entrypoint->argc(), 1);
CHECK_EQUAL(conf->commandRun.entrypoint->argv()[0], std::string{"myprogram"});
conf = generateConfig({"run", "--entrypoint", "myprogram --option", "image"});
CHECK_EQUAL(conf->commandRun.entrypoint->argc(), 2);
CHECK_EQUAL(conf->commandRun.entrypoint->argv()[0], std::string{"myprogram"});
CHECK_EQUAL(conf->commandRun.entrypoint->argv()[1], std::string{"--option"});
}
// init
{
auto conf = generateConfig({"run", "--init", "image"});
CHECK_EQUAL(conf->commandRun.addInitProcess, true);
}
// mount
{
auto conf = generateConfig({"run", "--mount",
"type=bind,source=/source,destination=/destination",
"image"});
CHECK_EQUAL(conf->commandRun.mounts.size(), 2); // 1 site mount + 1 user mount
}
// mpi
{
auto conf = generateConfig({"run", "--mpi", "image"});
CHECK_EQUAL(conf->commandRun.useMPI, true);
conf = generateConfig({"run", "-m", "image"});
CHECK_EQUAL(conf->commandRun.useMPI, true);
}
// ssh
{
auto conf = generateConfig({"run", "--ssh", "image"});
CHECK_EQUAL(conf->commandRun.enableSSH, true);
}
// tty
{
auto conf = generateConfig({"run", "--tty", "image"});
CHECK_EQUAL(conf->commandRun.allocatePseudoTTY, true);
conf = generateConfig({"run", "-t", "image"});
CHECK_EQUAL(conf->commandRun.allocatePseudoTTY, true);
}
// workdir
{
// long option with whitespace
auto conf = generateConfig({"run", "--workdir", "/workdir", "image"});
CHECK_EQUAL(conf->commandRun.workdir->string(), std::string{"/workdir"});
// short option with whitespace
conf = generateConfig({"run", "-w", "/workdir", "image"});
CHECK_EQUAL(conf->commandRun.workdir->string(), std::string{"/workdir"});
}
// sticky short options
{
auto conf = generateConfig({"run", "-mt", "image"});
CHECK_EQUAL(conf->commandRun.useMPI, true);
CHECK_EQUAL(conf->commandRun.allocatePseudoTTY, true);
}
// options as application arguments (for images with an entrypoint)
{
auto conf = generateConfig({"run", "image", "--option0", "--option1", "-q"});
CHECK(conf->commandRun.execArgs.argc() == 3);
CHECK_EQUAL(conf->commandRun.execArgs.argv()[0], std::string{"--option0"});
CHECK_EQUAL(conf->commandRun.execArgs.argv()[1], std::string{"--option1"});
CHECK_EQUAL(conf->commandRun.execArgs.argv()[2], std::string{"-q"});
}
// combined test
{
auto conf = generateConfig({"run",
"--workdir=/workdir",
"--mpi",
"--glibc",
"--mount=type=bind,source=/source,destination=/destination",
"ubuntu", "bash", "-c", "ls /dev |grep nvidia"});
CHECK_EQUAL(conf->commandRun.workdir->string(), std::string{"/workdir"});
CHECK_EQUAL(conf->commandRun.useMPI, true);
CHECK_EQUAL(conf->commandRun.enableGlibcReplacement, true);
CHECK_EQUAL(conf->commandRun.mounts.size(), 2); // 1 site mount + 1 user mount
CHECK_EQUAL(conf->imageID.server, std::string{"index.docker.io"});
CHECK_EQUAL(conf->imageID.repositoryNamespace, std::string{"library"});
CHECK_EQUAL(conf->imageID.image, std::string{"ubuntu"});
CHECK_EQUAL(conf->imageID.tag, std::string{"latest"});
CHECK(conf->commandRun.execArgs.argc() == 3);
CHECK_EQUAL(conf->commandRun.execArgs.argv()[0], std::string{"bash"});
CHECK_EQUAL(conf->commandRun.execArgs.argv()[1], std::string{"-c"});
CHECK_EQUAL(conf->commandRun.execArgs.argv()[2], std::string{"ls /dev |grep nvidia"});
}
}
SARUS_UNITTEST_MAIN_FUNCTION();
| 41.790323 | 97 | 0.647009 | pozsa |
96e0cf58acfe50d0693960d3dfd0ad346cd27ee5 | 3,599 | cpp | C++ | Base/PLCore/src/File/FileSearchAndroid.cpp | ktotheoz/pixellight | 43a661e762034054b47766d7e38d94baf22d2038 | [
"MIT"
] | 83 | 2015-01-08T15:06:14.000Z | 2021-07-20T17:07:00.000Z | Base/PLCore/src/File/FileSearchAndroid.cpp | PixelLightFoundation/pixellight | 43a661e762034054b47766d7e38d94baf22d2038 | [
"MIT"
] | 27 | 2019-06-18T06:46:07.000Z | 2020-02-02T11:11:28.000Z | Base/PLCore/src/File/FileSearchAndroid.cpp | naetherm/PixelLight | d7666f5b49020334cbb5debbee11030f34cced56 | [
"MIT"
] | 40 | 2015-02-25T18:24:34.000Z | 2021-03-06T09:01:48.000Z | /*********************************************************\
* File: FileSearchAndroid.cpp *
*
* Copyright (C) 2002-2013 The PixelLight Team (http://www.pixellight.org/)
*
* This file is part of PixelLight.
*
* 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.
\*********************************************************/
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include <stdio.h> // For e.g. "off_t"
#include <stdint.h> // For e.g. "size_t"
#include <android/asset_manager.h>
#include "PLCore/System/SystemAndroid.h"
#include "PLCore/File/FileSearchAndroid.h"
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
namespace PLCore {
//[-------------------------------------------------------]
//[ Private functions ]
//[-------------------------------------------------------]
/**
* @brief
* Constructor
*/
FileSearchAndroid::FileSearchAndroid(const String &sPath, const FileAccess *pAccess) : FileSearchImpl(pAccess),
m_pAAssetDir(nullptr),
m_sPath(sPath),
m_pszNextFilename(nullptr)
{
// Get the Android asset manager instance
AAssetManager *pAAssetManager = SystemAndroid::GetAssetManager();
if (pAAssetManager) {
// Start search
m_pAAssetDir = AAssetManager_openDir(pAAssetManager, (m_sPath.GetFormat() == String::ASCII) ? m_sPath.GetASCII() : m_sPath.GetUTF8());
if (m_pAAssetDir) {
// Something has been found
m_pszNextFilename = AAssetDir_getNextFileName(m_pAAssetDir);
}
}
}
/**
* @brief
* Destructor
*/
FileSearchAndroid::~FileSearchAndroid()
{
// Close the search
if (m_pAAssetDir)
AAssetDir_close(m_pAAssetDir);
}
//[-------------------------------------------------------]
//[ Private virtual FileSearchImpl functions ]
//[-------------------------------------------------------]
bool FileSearchAndroid::HasNextFile()
{
return (m_pszNextFilename != nullptr);
}
String FileSearchAndroid::GetNextFile()
{
if (m_pszNextFilename) {
m_sFilename = m_pszNextFilename;
m_pszNextFilename = AAssetDir_getNextFileName(m_pAAssetDir);
return m_sFilename;
} else {
return "";
}
}
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // PLCore
| 35.633663 | 136 | 0.548486 | ktotheoz |
96e4f68f9e2d37940d54a68cce1ac7d4c0426ac7 | 3,844 | cpp | C++ | Model/ModelGrid.cpp | robbor78/OpenGLTetris3D | b388cbdc2eda9fcc9a073f8aa857b0912819e695 | [
"Apache-2.0"
] | null | null | null | Model/ModelGrid.cpp | robbor78/OpenGLTetris3D | b388cbdc2eda9fcc9a073f8aa857b0912819e695 | [
"Apache-2.0"
] | null | null | null | Model/ModelGrid.cpp | robbor78/OpenGLTetris3D | b388cbdc2eda9fcc9a073f8aa857b0912819e695 | [
"Apache-2.0"
] | null | null | null | /*
* ModelGrid.cpp
*
* Created on: 22 Dec 2013
* Author: bert
*/
#include "ModelGrid.h"
namespace Tetris3D {
ModelGrid::ModelGrid(OpenGLProgram* program) :
AbstractModelPiece(program) {
well = 0;
vbo = -1;
}
ModelGrid::~ModelGrid() {
program = 0;
well = 0;
glBindBuffer(GL_ARRAY_BUFFER, 0);
glDeleteBuffers(1, &vbo);
}
void ModelGrid::GenerateBuffers() {
std::vector<float> grid;
MakeGrid(grid);
GenerateArrayBuffer(vbo, grid);
}
void ModelGrid::InitBuffers() {
glBindBuffer(GL_ARRAY_BUFFER, vbo);
AbstractModelPiece::InitBuffers();
}
void ModelGrid::DrawBuffers() {
int size = 0;
glGetBufferParameteriv(GL_ARRAY_BUFFER, GL_BUFFER_SIZE, &size);
glDrawArrays(GL_LINES, 0, size / sizeof(VertexStructure));
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void ModelGrid::MakeGrid(std::vector<float> &cs) {
cs.clear();
unsigned int maxCol = well->GetCol();
unsigned int maxRow = well->GetRow();
unsigned int maxDep = well->GetDep();
for (unsigned int row = 0; row <= maxRow; row++) {
float xStart = xOffset;
float y = -(float) (row * sideLength) + yOffset;
float xEnd = (float) (maxCol * sideLength) + xOffset;
float zStart = 0.0; //sideLength * maxDep;
PushIntoVector(cs, new float[3] { xStart, y, zStart }, new float[3] { 0.0, 0.0, -1.0 }, new float[4] { 1.0, 1.0,
0.0, 1.0 });
PushIntoVector(cs, new float[3] { xEnd, y, zStart }, new float[3] { 0.0, 0.0, -1.0 }, new float[4] { 1.0, 1.0, 0.0,
1.0 });
float zEnd = sideLength * maxDep;
PushIntoVector(cs, new float[3] { xStart, y, zStart }, new float[3] { 0.0, 0.0, -1.0 }, new float[4] { 1.0, 1.0,
0.0, 1.0 });
PushIntoVector(cs, new float[3] { xStart, y, zEnd }, new float[3] { 0.0, 0.0, -1.0 }, new float[4] { 1.0, 1.0, 0.0,
1.0 });
PushIntoVector(cs, new float[3] { xEnd, y, zStart }, new float[3] { 0.0, 0.0, -1.0 }, new float[4] { 1.0, 1.0, 0.0,
1.0 });
PushIntoVector(cs, new float[3] { xEnd, y, zEnd }, new float[3] { 0.0, 0.0, -1.0 }, new float[4] { 1.0, 1.0, 0.0,
1.0 });
}
for (unsigned int col = 0; col <= maxCol; col++) {
float yStart = yOffset;
float yEnd = -(float) (maxRow * sideLength) + yOffset;
float x = (float) (col * sideLength) + xOffset;
float zStart = 0.0;
float zEnd = sideLength * maxDep;
PushIntoVector(cs, new float[3] { x, yStart, zStart }, new float[3] { 0.0, 0.0, -1.0 }, new float[4] { 1.0, 0.0, 1.0, 1.0 });
PushIntoVector(cs, new float[3] { x, yEnd, zStart }, new float[3] { 0.0, 0.0, -1.0 }, new float[4] { 1.0, 0.0, 1.0, 1.0 });
PushIntoVector(cs, new float[3] { x, yEnd, zStart }, new float[3] { 0.0, 0.0, -1.0 }, new float[4] { 1.0, 1.0, 0.0,
1.0 });
PushIntoVector(cs, new float[3] { x, yEnd, zEnd }, new float[3] { 0.0, 0.0, -1.0 }, new float[4] { 1.0, 1.0, 0.0,
1.0 });
}
for (unsigned int dep = 1; dep <= maxDep; dep++) {
float z = dep * sideLength;
float xStart = xOffset;
float xEnd = (float) (maxCol * sideLength) + xOffset;
float yStart = 14.0;
float yEnd = -(float) (maxRow * sideLength) + yOffset;
PushIntoVector(cs, new float[3] { xStart, yStart, z }, new float[3] { 0.0, 0.0, -1.0 }, new float[4] { 1.0, 1.0,
0.0, 1.0 });
PushIntoVector(cs, new float[3] { xStart, yEnd, z }, new float[3] { 0.0, 0.0, -1.0 }, new float[4] { 1.0, 1.0, 0.0,
1.0 });
PushIntoVector(cs, new float[3] { xEnd, yStart, z }, new float[3] { 0.0, 0.0, -1.0 }, new float[4] { 1.0, 1.0, 0.0,
1.0 });
PushIntoVector(cs, new float[3] { xEnd, yEnd, z }, new float[3] { 0.0, 0.0, -1.0 }, new float[4] { 1.0, 1.0, 0.0,
1.0 });
PushIntoVector(cs, new float[3] { xStart, yEnd, z }, new float[3] { 0.0, 0.0, -1.0 }, new float[4] { 1.0, 1.0, 0.0,
1.0 });
PushIntoVector(cs, new float[3] { xEnd, yEnd, z }, new float[3] { 0.0, 0.0, -1.0 }, new float[4] { 1.0, 1.0, 0.0,
1.0 });
}
}
} /* namespace Tetris3D */
| 30.752 | 127 | 0.588189 | robbor78 |
96e7bbcce9ad7f8b0208c8cd243525d9f87d612d | 404 | hpp | C++ | src/arithmetic.hpp | UtopiaLang/src | be8904f978f3ea0d92afb72895cc2bb052cf4107 | [
"Unlicense"
] | 7 | 2021-03-01T17:24:45.000Z | 2021-10-01T02:28:25.000Z | src/arithmetic.hpp | UtopiaLang/Utopia | be8904f978f3ea0d92afb72895cc2bb052cf4107 | [
"Unlicense"
] | 6 | 2021-02-27T18:25:45.000Z | 2021-09-10T21:27:39.000Z | src/arithmetic.hpp | UtopiaLang/src | be8904f978f3ea0d92afb72895cc2bb052cf4107 | [
"Unlicense"
] | null | null | null | #pragma once
namespace Utopia
{
using arithmetic_func_t = long long(*)(const long long, const long long);
long long arithmetic_plus(const long long left, const long long right);
long long arithmetic_minus(const long long left, const long long right);
long long arithmetic_multiply(const long long left, const long long right);
long long arithmetic_divide(const long long left, long long right);
}
| 33.666667 | 76 | 0.779703 | UtopiaLang |
96e8e95e2fad0184250fd1bdeebe56d670ac8932 | 6,795 | cc | C++ | selfdrive/can/dbc_out/cadillac_ct6_chassis.cc | ziggysnorkel/openpilot | 695859fb49976c2ef0a6a4a73d30d5cef2ad1945 | [
"MIT"
] | 1 | 2021-03-05T18:09:52.000Z | 2021-03-05T18:09:52.000Z | selfdrive/can/dbc_out/cadillac_ct6_chassis.cc | ziggysnorkel/openpilot | 695859fb49976c2ef0a6a4a73d30d5cef2ad1945 | [
"MIT"
] | null | null | null | selfdrive/can/dbc_out/cadillac_ct6_chassis.cc | ziggysnorkel/openpilot | 695859fb49976c2ef0a6a4a73d30d5cef2ad1945 | [
"MIT"
] | null | null | null | #include <cstdint>
#include "common.h"
namespace {
const Signal sigs_338[] = {
{
.name = "LKASteeringCmd",
.b1 = 2,
.b2 = 14,
.bo = 48,
.is_signed = true,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LKASteeringCmdActive",
.b1 = 0,
.b2 = 1,
.bo = 63,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LKASVehicleSpeed",
.b1 = 19,
.b2 = 13,
.bo = 32,
.is_signed = false,
.factor = 0.22,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "SetMe1",
.b1 = 18,
.b2 = 1,
.bo = 45,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "RollingCounter",
.b1 = 16,
.b2 = 2,
.bo = 46,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LKASteeringCmdChecksum",
.b1 = 38,
.b2 = 10,
.bo = 16,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LKASMode",
.b1 = 35,
.b2 = 2,
.bo = 27,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_340[] = {
{
.name = "LKASteeringCmd",
.b1 = 2,
.b2 = 14,
.bo = 48,
.is_signed = true,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LKASteeringCmdActive",
.b1 = 0,
.b2 = 1,
.bo = 63,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LKASVehicleSpeed",
.b1 = 19,
.b2 = 13,
.bo = 32,
.is_signed = false,
.factor = 0.22,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "SetMe1",
.b1 = 18,
.b2 = 1,
.bo = 45,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "RollingCounter",
.b1 = 16,
.b2 = 2,
.bo = 46,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LKASteeringCmdChecksum",
.b1 = 38,
.b2 = 10,
.bo = 16,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "LKASteeringCmdActive2",
.b1 = 36,
.b2 = 1,
.bo = 27,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_368[] = {
{
.name = "FrictionBrakePressure",
.b1 = 16,
.b2 = 16,
.bo = 32,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_560[] = {
{
.name = "Regen",
.b1 = 6,
.b2 = 10,
.bo = 48,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_789[] = {
{
.name = "FrictionBrakeCmd",
.b1 = 4,
.b2 = 12,
.bo = 48,
.is_signed = true,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FrictionBrakeMode",
.b1 = 0,
.b2 = 4,
.bo = 60,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "FrictionBrakeChecksum",
.b1 = 16,
.b2 = 16,
.bo = 32,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "RollingCounter",
.b1 = 34,
.b2 = 6,
.bo = 24,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Signal sigs_823[] = {
{
.name = "SteeringWheelCmd",
.b1 = 16,
.b2 = 16,
.bo = 32,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "RollingCounter",
.b1 = 36,
.b2 = 2,
.bo = 26,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
{
.name = "SteeringWheelChecksum",
.b1 = 40,
.b2 = 16,
.bo = 8,
.is_signed = false,
.factor = 1,
.offset = 0,
.is_little_endian = false,
.type = SignalType::DEFAULT,
},
};
const Msg msgs[] = {
{
.name = "ASCMLKASteeringCmd",
.address = 0x152,
.size = 6,
.num_sigs = ARRAYSIZE(sigs_338),
.sigs = sigs_338,
},
{
.name = "ASCMBLKASteeringCmd",
.address = 0x154,
.size = 6,
.num_sigs = ARRAYSIZE(sigs_340),
.sigs = sigs_340,
},
{
.name = "EBCMFrictionBrakeStatus",
.address = 0x170,
.size = 8,
.num_sigs = ARRAYSIZE(sigs_368),
.sigs = sigs_368,
},
{
.name = "EBCMRegen",
.address = 0x230,
.size = 6,
.num_sigs = ARRAYSIZE(sigs_560),
.sigs = sigs_560,
},
{
.name = "EBCMFrictionBrakeCmd",
.address = 0x315,
.size = 5,
.num_sigs = ARRAYSIZE(sigs_789),
.sigs = sigs_789,
},
{
.name = "PACMParkAssitCmd",
.address = 0x337,
.size = 7,
.num_sigs = ARRAYSIZE(sigs_823),
.sigs = sigs_823,
},
};
const Val vals[] = {
{
.name = "LKASteeringCmdActive",
.address = 0x152,
.def_val = "1 ACTIVE 0 INACTIVE",
.sigs = sigs_338,
},
{
.name = "LKASMode",
.address = 0x152,
.def_val = "2 SUPERCRUISE 1 LKAS 0 INACTIVE",
.sigs = sigs_338,
},
};
}
const DBC cadillac_ct6_chassis = {
.name = "cadillac_ct6_chassis",
.num_msgs = ARRAYSIZE(msgs),
.msgs = msgs,
.vals = vals,
.num_vals = ARRAYSIZE(vals),
};
dbc_init(cadillac_ct6_chassis) | 19.810496 | 51 | 0.474467 | ziggysnorkel |
96eb5448be918c54a3a35b49c7a9d9632a0e59d7 | 26,330 | cpp | C++ | test/test_manifest_tsv.cpp | rkimballn1/aeon-merged | 062136993c0f326c95caaddf6118a84789e206b1 | [
"MIT",
"BSL-1.0",
"Apache-2.0",
"BSD-3-Clause"
] | 63 | 2016-08-14T07:19:45.000Z | 2021-09-21T15:57:08.000Z | test/test_manifest_tsv.cpp | NervanaSystems/aeon | a63b9f8d75311b8d9e9b0be58a066e749aeb81d4 | [
"MIT",
"BSL-1.0",
"Apache-2.0",
"BSD-3-Clause"
] | 64 | 2016-08-08T18:35:19.000Z | 2022-03-11T23:43:51.000Z | test/test_manifest_tsv.cpp | rkimballn1/aeon-merged | 062136993c0f326c95caaddf6118a84789e206b1 | [
"MIT",
"BSL-1.0",
"Apache-2.0",
"BSD-3-Clause"
] | 44 | 2016-08-10T01:20:52.000Z | 2020-07-01T19:47:48.000Z | /*******************************************************************************
* Copyright 2016-2018 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#include <fcntl.h>
#include <unistd.h>
#include <sys/time.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <stdexcept>
#include <memory>
#include <chrono>
#include "gtest/gtest.h"
#include "manifest_file.hpp"
#include "manifest_builder.hpp"
#include "util.hpp"
#include "file_util.hpp"
#include "manifest_file.hpp"
#include "crc.hpp"
#include "file_util.hpp"
#include "block_loader_file.hpp"
#include "base64.hpp"
#include "gen_image.hpp"
#include "loader.hpp"
using namespace std;
using namespace nervana;
static string test_data_directory = file_util::path_join(string(CURDIR), "test_data");
TEST(manifest, constructor)
{
manifest_builder mm;
auto& ms = mm.sizes({0, 0}).record_count(0).create();
nervana::manifest_file manifest0(ms, false);
}
TEST(manifest, no_file)
{
ASSERT_THROW(nervana::manifest_file manifest0("/tmp/jsdkfjsjkfdjaskdfj_doesnt_exist", false),
std::runtime_error);
}
TEST(manifest, version_eq)
{
manifest_builder mm;
auto& ms = mm.sizes({0, 0}).record_count(0).create();
nervana::manifest_file manifest1(ms, false);
nervana::manifest_file manifest2(ms, false);
ASSERT_EQ(manifest1.version(), manifest2.version());
}
TEST(manifest, parse_file_doesnt_exist)
{
manifest_builder mm;
auto& ms = mm.sizes({0, 0}).record_count(0).create();
nervana::manifest_file manifest0(ms, false);
ASSERT_EQ(manifest0.record_count(), 0);
}
TEST(manifest, parse_file)
{
manifest_builder mm;
auto& ms = mm.sizes({0, 0}).record_count(2).create();
nervana::manifest_file manifest0(ms, false);
ASSERT_EQ(manifest0.record_count(), 2);
}
TEST(manifest, no_shuffle)
{
manifest_builder mm1;
auto& ms1 = mm1.sizes({4, 4}).record_count(20).create();
nervana::manifest_file manifest1(ms1, false);
manifest_builder mm2;
auto& ms2 = mm2.sizes({4, 4}).record_count(20).create();
nervana::manifest_file manifest2(ms2, false);
ASSERT_EQ(1, manifest1.block_count());
ASSERT_EQ(1, manifest2.block_count());
auto& m1_block = *manifest1.next();
auto& m2_block = *manifest2.next();
ASSERT_EQ(manifest1.record_count(), manifest2.record_count());
ASSERT_EQ(2, manifest1.elements_per_record());
for (int i = 0; i < manifest1.record_count(); i++)
{
ASSERT_EQ(m1_block[i][0], m2_block[i][0]);
ASSERT_EQ(m1_block[i][1], m2_block[i][1]);
}
}
namespace {
void test_multinode_manifest(bool shuffle)
{
const uint32_t record_count = 17;
const uint32_t batch_size = 3;
const uint32_t node_count = 2;
manifest_builder mm1;
auto& ms1 = mm1.sizes({4, 4}).record_count(record_count).create();
nervana::manifest_file manifest(ms1, shuffle, "", 1.0f, 5000, 1234, 0, 0, batch_size);
manifest_builder mmn1;
auto& msn1 = mmn1.sizes({4, 4}).record_count(record_count).create();
nervana::manifest_file manifest_node1(msn1, shuffle, "", 1.0f, 5000, 1234, 0, 2, batch_size);
manifest_builder mmn2;
auto& msn2 = mmn2.sizes({4, 4}).record_count(record_count).create();
nervana::manifest_file manifest_node2(msn2, shuffle, "", 1.0f, 5000, 1234, 1, 2, batch_size);
ASSERT_EQ(1, manifest_node1.block_count());
ASSERT_EQ(1, manifest_node2.block_count());
ASSERT_EQ(8, manifest_node1.record_count());
ASSERT_EQ(8, manifest_node2.record_count());
ASSERT_EQ(2, manifest_node1.elements_per_record());
ASSERT_EQ(2, manifest_node2.elements_per_record());
auto record_count_node = (manifest.record_count() / node_count) * node_count;
uint32_t batches = ((record_count_node / node_count) / batch_size) * node_count;
for (int i = 0; i < batches; i++)
{
for (int j = 0; j < batch_size; j++)
{
uint32_t src_index = i * batch_size + j;
uint32_t dst_index = ( i / node_count ) * batch_size + j;
if ( i % node_count == 0)
{
ASSERT_EQ(manifest[src_index][0], manifest_node1[dst_index][0]);
ASSERT_EQ(manifest[src_index][1], manifest_node1[dst_index][1]);
}
else
{
ASSERT_EQ(manifest[src_index][0], manifest_node2[dst_index][0]);
ASSERT_EQ(manifest[src_index][1], manifest_node2[dst_index][1]);
}
}
}
auto remain = record_count_node - batches * batch_size;
for (int i = 0; i < remain; i++)
{
uint32_t src_index = batches * batch_size + i;
uint32_t dst_index = batches * batch_size / node_count + i % node_count;
if ( i / node_count == 0)
{
ASSERT_EQ(manifest[src_index][0], manifest_node1[dst_index][0]);
ASSERT_EQ(manifest[src_index][1], manifest_node1[dst_index][1]);
}
else
{
ASSERT_EQ(manifest[src_index][0], manifest_node2[dst_index][0]);
ASSERT_EQ(manifest[src_index][1], manifest_node2[dst_index][1]);
}
}
auto block = manifest.next();
auto block_node1 = manifest_node1.next();
auto block_node2 = manifest_node2.next();
manifest.reset();
manifest_node1.reset();
manifest_node2.reset();
block = manifest.next();
block_node1 = manifest_node1.next();
block_node2 = manifest_node2.next();
}
}
TEST(manifest, no_shuffle_multinode)
{
test_multinode_manifest(false);
}
TEST(manifest, shuffle_multinode)
{
test_multinode_manifest(true);
}
TEST(manifest, shuffle)
{
manifest_builder mm1;
auto& ms1 = mm1.sizes({4, 4}).record_count(20).create();
nervana::manifest_file manifest1(ms1, false);
manifest_builder mm2;
auto& ms2 = mm2.sizes({4, 4}).record_count(20).create();
nervana::manifest_file manifest2(ms2, true);
bool different = false;
ASSERT_EQ(1, manifest1.block_count());
ASSERT_EQ(1, manifest2.block_count());
auto& m1_block = *manifest1.next();
auto& m2_block = *manifest2.next();
ASSERT_EQ(manifest1.record_count(), manifest2.record_count());
for (int i = 0; i < manifest1.record_count(); i++)
{
if (m1_block[i][0] != m2_block[i][0])
{
different = true;
}
}
ASSERT_EQ(different, true);
}
TEST(manifest, non_paired_manifests)
{
{
manifest_builder mm;
auto& ms = mm.sizes({4, 4, 4}).record_count(20).create();
nervana::manifest_file manifest1(ms, false);
ASSERT_EQ(manifest1.record_count(), 20);
}
{
manifest_builder mm;
auto& ms = mm.sizes({4}).record_count(20).create();
nervana::manifest_file manifest1(ms, false);
ASSERT_EQ(manifest1.record_count(), 20);
}
}
TEST(manifest, root_path)
{
string manifest_file = "tmp_manifest.tsv";
{
ofstream f(manifest_file);
f << "@FILE\tFILE\n";
for (int i = 0; i < 10; i++)
{
f << "/t1/image" << i << ".png" << manifest_file::get_delimiter();
f << "/t1/target" << i << ".txt\n";
}
f.close();
nervana::manifest_file manifest(manifest_file, false);
ASSERT_EQ(1, manifest.block_count());
auto& block = *manifest.next();
for (int i = 0; i < manifest.record_count(); i++)
{
const vector<string>& x = block[i];
ASSERT_EQ(2, x.size());
stringstream ss;
ss << "/t1/image" << i << ".png";
EXPECT_STREQ(x[0].c_str(), ss.str().c_str());
ss.str("");
ss << "/t1/target" << i << ".txt";
EXPECT_STREQ(x[1].c_str(), ss.str().c_str());
}
}
{
ofstream f(manifest_file);
f << "@FILE\tFILE\n";
for (int i = 0; i < 10; i++)
{
f << "/t1/image" << i << ".png" << manifest_file::get_delimiter();
f << "/t1/target" << i << ".txt\n";
}
f.close();
nervana::manifest_file manifest(manifest_file, false, "/x1");
ASSERT_EQ(1, manifest.block_count());
auto& block = *manifest.next();
for (int i = 0; i < manifest.record_count(); i++)
{
const vector<string>& x = block[i];
ASSERT_EQ(2, x.size());
stringstream ss;
ss << "/t1/image" << i << ".png";
EXPECT_STREQ(x[0].c_str(), ss.str().c_str());
ss.str("");
ss << "/t1/target" << i << ".txt";
EXPECT_STREQ(x[1].c_str(), ss.str().c_str());
}
}
{
ofstream f(manifest_file);
f << "@FILE\tFILE\n";
for (int i = 0; i < 10; i++)
{
f << "t1/image" << i << ".png" << manifest_file::get_delimiter();
f << "t1/target" << i << ".txt\n";
}
f.close();
nervana::manifest_file manifest(manifest_file, false, "/x1");
ASSERT_EQ(1, manifest.block_count());
auto& block = *manifest.next();
for (int i = 0; i < manifest.record_count(); i++)
{
const vector<string>& x = block[i];
ASSERT_EQ(2, x.size());
stringstream ss;
ss << "/x1/t1/image" << i << ".png";
EXPECT_STREQ(x[0].c_str(), ss.str().c_str());
ss.str("");
ss << "/x1/t1/target" << i << ".txt";
EXPECT_STREQ(x[1].c_str(), ss.str().c_str());
}
}
remove(manifest_file.c_str());
}
TEST(manifest, crc)
{
const string input = "123456789";
uint32_t expected = 0xe3069283;
uint32_t actual = 0;
CryptoPP::CRC32C crc;
crc.Update((const uint8_t*)input.data(), input.size());
crc.TruncatedFinal((uint8_t*)&actual, sizeof(actual));
EXPECT_EQ(expected, actual);
}
TEST(manifest, file_implicit)
{
vector<string> image_files = {"flowers.jpg", "img_2112_70.jpg"};
vector<string> target_files = {"1.txt", "2.txt"};
stringstream ss;
for (int count = 0; count < 32; count++)
{
for (int i = 0; i < image_files.size(); i++)
{
ss << image_files[i] << "\t" << target_files[i] << "\n";
}
}
size_t block_size = 16;
EXPECT_THROW(manifest_file(ss, false, test_data_directory, 1.0, block_size),
std::invalid_argument);
}
TEST(manifest, wrong_elements_number)
{
string image_file = "flowers.jpg";
stringstream ss;
ss << "@FILE"
<< "\t"
<< "FILE"
<< "\n";
ss << image_file << "\n";
size_t block_size = 1;
EXPECT_THROW(manifest_file manifest(ss, false, test_data_directory, 1.0, block_size),
std::runtime_error);
}
TEST(manifest, changing_elements_number)
{
string image_file = "flowers.jpg";
string target_file = "1.txt";
stringstream ss;
ss << "@FILE"
<< "\t"
<< "FILE"
<< "\n";
ss << image_file << "\t" << target_file << "\n";
ss << image_file << "\n";
size_t block_size = 2;
EXPECT_THROW(manifest_file manifest(ss, false, test_data_directory, 1.0, block_size),
std::runtime_error);
}
TEST(manifest, file_explicit)
{
vector<string> image_files = {"flowers.jpg", "img_2112_70.jpg"};
vector<string> target_files = {"1.txt", "2.txt"};
stringstream ss;
ss << "@FILE"
<< "\t"
<< "FILE"
<< "\n";
for (int count = 0; count < 32; count++)
{
for (int i = 0; i < image_files.size(); i++)
{
ss << image_files[i] << "\t" << target_files[i] << "\n";
}
}
size_t block_size = 16;
auto manifest = make_shared<manifest_file>(ss, false, test_data_directory, 1.0, block_size);
auto types = manifest->get_element_types();
ASSERT_EQ(2, types.size());
EXPECT_EQ(manifest::element_t::FILE, types[0]);
EXPECT_EQ(manifest::element_t::FILE, types[1]);
block_loader_file bload{manifest, block_size};
for (int i = 0; i < 2; i++)
{
encoded_record_list* buffer = bload.filler();
ASSERT_NE(nullptr, buffer);
ASSERT_EQ(block_size, buffer->size());
for (int j = 0; j < buffer->size(); j++)
{
encoded_record record = buffer->record(j);
auto idata = record.element(0);
auto tdata = record.element(1);
string target{tdata.data(), tdata.size()};
int value = stod(target);
EXPECT_EQ(j % 2 + 1, value);
}
}
}
string make_target_data(size_t index)
{
stringstream tmp;
tmp << "target_number" << index++;
return tmp.str();
}
TEST(manifest, binary)
{
vector<string> image_files = {"flowers.jpg", "img_2112_70.jpg"};
stringstream ss;
size_t index = 0;
ss << "@FILE"
<< "\t"
<< "BINARY"
<< "\n";
for (int count = 0; count < 32; count++)
{
for (int i = 0; i < image_files.size(); i++)
{
vector<char> str = string2vector(make_target_data(index++));
auto data_string = base64::encode(str);
ss << image_files[i] << "\t" << vector2string(data_string) << "\n";
}
}
size_t block_size = 16;
auto manifest = make_shared<manifest_file>(ss, false, test_data_directory, 1.0, block_size);
auto types = manifest->get_element_types();
ASSERT_EQ(2, types.size());
EXPECT_EQ(manifest::element_t::FILE, types[0]);
EXPECT_EQ(manifest::element_t::BINARY, types[1]);
block_loader_file block_loader{manifest, block_size};
index = 0;
for (int i = 0; i < 2; i++)
{
encoded_record_list* buffer = block_loader.filler();
ASSERT_NE(nullptr, buffer);
ASSERT_EQ(block_size, buffer->size());
for (int j = 0; j < buffer->size(); j++)
{
encoded_record record = buffer->record(j);
auto idata = record.element(0);
auto tdata = record.element(1);
string str = vector2string(tdata);
string expected = make_target_data(index);
index = (index + 1) % manifest->record_count();
EXPECT_STREQ(expected.c_str(), str.c_str());
}
}
}
TEST(manifest, string)
{
vector<string> image_files = {"flowers.jpg", "img_2112_70.jpg"};
stringstream ss;
size_t index = 0;
ss << "@FILE"
<< "\t"
<< "STRING"
<< "\n";
for (int count = 0; count < 32; count++)
{
for (int i = 0; i < image_files.size(); i++)
{
string str = make_target_data(index++);
ss << image_files[i] << "\t" << str << "\n";
}
}
size_t block_size = 16;
auto manifest = make_shared<manifest_file>(ss, false, test_data_directory, 1.0, block_size);
// for (auto data : manifest)
// {
// INFO << data[0] << ", " << data[1];
// }
auto types = manifest->get_element_types();
ASSERT_EQ(2, types.size());
EXPECT_EQ(manifest::element_t::FILE, types[0]);
EXPECT_EQ(manifest::element_t::STRING, types[1]);
block_loader_file block_loader{manifest, block_size};
index = 0;
for (int i = 0; i < 2; i++)
{
encoded_record_list* buffer = block_loader.filler();
ASSERT_NE(nullptr, buffer);
ASSERT_EQ(block_size, buffer->size());
for (int j = 0; j < buffer->size(); j++)
{
encoded_record record = buffer->record(j);
auto idata = record.element(0);
auto tdata = record.element(1);
string str = vector2string(tdata);
string expected = make_target_data(index);
index = (index + 1) % manifest->record_count();
EXPECT_STREQ(expected.c_str(), str.c_str());
}
}
}
TEST(manifest, ascii_int)
{
vector<string> image_files = {"flowers.jpg", "img_2112_70.jpg"};
stringstream ss;
size_t index = 0;
ss << "@FILE"
<< "\t"
<< "ASCII_INT"
<< "\n";
for (int count = 0; count < 32; count++)
{
for (int i = 0; i < image_files.size(); i++)
{
ss << image_files[i] << "\t" << count * 2 + i << "\n";
}
}
size_t block_size = 16;
auto manifest = make_shared<manifest_file>(ss, false, test_data_directory, 1.0, block_size);
auto types = manifest->get_element_types();
ASSERT_EQ(2, types.size());
EXPECT_EQ(manifest::element_t::FILE, types[0]);
EXPECT_EQ(manifest::element_t::ASCII_INT, types[1]);
block_loader_file block_loader{manifest, block_size};
index = 0;
for (int i = 0; i < 2; i++)
{
encoded_record_list* buffer = block_loader.filler();
ASSERT_NE(nullptr, buffer);
ASSERT_EQ(block_size, buffer->size());
for (int j = 0; j < buffer->size(); j++)
{
encoded_record record = buffer->record(j);
auto idata = record.element(0);
int32_t tdata = unpack<int32_t>(record.element(1).data());
EXPECT_EQ(tdata, index);
index++;
}
}
}
TEST(manifest, ascii_float)
{
vector<string> image_files = {"flowers.jpg", "img_2112_70.jpg"};
stringstream ss;
size_t index = 0;
ss << "@FILE"
<< "\t"
<< "ASCII_FLOAT"
<< "\n";
for (int count = 0; count < 32; count++)
{
for (int i = 0; i < image_files.size(); i++)
{
ss << image_files[i] << "\t" << (float)(count * 2 + i) / 10. << "\n";
}
}
size_t block_size = 16;
auto manifest = make_shared<manifest_file>(ss, false, test_data_directory, 1.0, block_size);
auto types = manifest->get_element_types();
ASSERT_EQ(2, types.size());
EXPECT_EQ(manifest::element_t::FILE, types[0]);
EXPECT_EQ(manifest::element_t::ASCII_FLOAT, types[1]);
block_loader_file block_loader{manifest, block_size};
index = 0;
for (int i = 0; i < 2; i++)
{
encoded_record_list* buffer = block_loader.filler();
ASSERT_NE(nullptr, buffer);
ASSERT_EQ(block_size, buffer->size());
for (int j = 0; j < buffer->size(); j++)
{
encoded_record record = buffer->record(j);
auto idata = record.element(0);
float tdata = unpack<float>(record.element(1).data());
float expected = (float)index / 10.;
EXPECT_EQ(tdata, expected);
index++;
}
}
}
extern string test_cache_directory;
class manifest_manager
{
public:
manifest_manager(const string& source_dir, size_t count, int rows, int cols)
{
test_root = source_dir;
source_directory = file_util::make_temp_directory(source_dir);
manifest_filename = file_util::path_join(source_directory, "manifest.tsv");
file_list.push_back(manifest_filename);
ofstream mfile(manifest_filename);
mfile << "@FILE\tFILE\n";
for (size_t i = 0; i < count; i++)
{
cv::Mat image = embedded_id_image::generate_image(rows, cols, i);
string number = to_string(i);
string image_filename =
file_util::path_join(source_directory, "image" + number + ".png");
string target_filename =
file_util::path_join(source_directory, "target" + number + ".txt");
// cout << image_filename << ", " << target_filename << endl;
file_list.push_back(image_filename);
file_list.push_back(target_filename);
cv::imwrite(image_filename, image);
ofstream tfile(target_filename);
tfile << i;
mfile << image_filename << manifest_file::get_delimiter();
mfile << target_filename << "\n";
}
}
const string& manifest_file() const { return manifest_filename; }
~manifest_manager() { file_util::remove_directory(test_root); }
private:
string test_root;
string manifest_filename;
string source_directory;
vector<string> file_list;
};
TEST(manifest, manifest_shuffle)
{
const uint32_t seed = 1234;
const size_t block_size = 4;
const float subset_fraction = 1.0;
string source_dir = file_util::make_temp_directory(test_cache_directory);
manifest_manager manifest_builder{source_dir, 10, 25, 25};
string manifest_root;
nervana::manifest_file manifest1{
manifest_builder.manifest_file(), true, manifest_root, subset_fraction, block_size, seed};
nervana::manifest_file manifest2{
manifest_builder.manifest_file(), false, manifest_root, subset_fraction, block_size, seed};
EXPECT_EQ(manifest1.get_crc(), manifest2.get_crc());
}
TEST(manifest, manifest_shuffle_repeatable)
{
const uint32_t seed = 1234;
const size_t block_size = 4;
const float subset_fraction = 1.0;
string source_dir = file_util::make_temp_directory(test_cache_directory);
manifest_manager manifest_builder{source_dir, 10, 25, 25};
string manifest_root;
nervana::manifest_file manifest1{
manifest_builder.manifest_file(), true, manifest_root, subset_fraction, block_size, seed};
nervana::manifest_file manifest2{
manifest_builder.manifest_file(), true, manifest_root, subset_fraction, block_size, seed};
EXPECT_EQ(manifest1.get_crc(), manifest2.get_crc());
}
TEST(manifest, subset_fraction)
{
string source_dir = file_util::make_temp_directory(test_cache_directory);
manifest_manager manifest_builder{source_dir, 1000, 25, 25};
uint32_t manifest1_crc;
uint32_t manifest2_crc;
const uint32_t seed = 1234;
float subset_fraction = 0.01;
int block_size = 4;
bool shuffle_manifest = true;
string manifest_root;
{
auto manifest = make_shared<nervana::manifest_file>(manifest_builder.manifest_file(),
shuffle_manifest,
manifest_root,
subset_fraction,
block_size,
seed);
ASSERT_NE(nullptr, manifest);
manifest1_crc = manifest->get_crc();
}
{
auto manifest = make_shared<nervana::manifest_file>(manifest_builder.manifest_file(),
shuffle_manifest,
manifest_root,
subset_fraction,
block_size,
seed);
ASSERT_NE(nullptr, manifest);
manifest2_crc = manifest->get_crc();
}
EXPECT_EQ(manifest1_crc, manifest2_crc);
}
TEST(manifest, crc_root_dir)
{
stringstream ss;
ss << manifest_file::get_metadata_char();
ss << manifest_file::get_file_type_id() << manifest_file::get_delimiter()
<< manifest_file::get_string_type_id() << "\n";
for (size_t i = 0; i < 100; i++)
{
ss << "relative/path/image" << i << ".jpg" << manifest_file::get_delimiter() << i << "\n";
}
uint32_t manifest1_crc;
uint32_t manifest2_crc;
float subset_fraction = 1.0;
int block_size = 4;
bool shuffle_manifest = false;
{
stringstream tmp{ss.str()};
string manifest_root = "/root1/";
auto manifest = make_shared<nervana::manifest_file>(
tmp, shuffle_manifest, manifest_root, subset_fraction, block_size);
ASSERT_NE(nullptr, manifest);
manifest1_crc = manifest->get_crc();
}
{
stringstream tmp{ss.str()};
string manifest_root = "/root2/";
auto manifest = make_shared<nervana::manifest_file>(
tmp, shuffle_manifest, manifest_root, subset_fraction, block_size);
ASSERT_NE(nullptr, manifest);
manifest2_crc = manifest->get_crc();
}
EXPECT_EQ(manifest1_crc, manifest2_crc);
}
TEST(manifest, comma)
{
string manifest_file = "tmp_manifest.tsv";
{
int height = 224;
int width = 224;
size_t batch_size = 128;
nlohmann::json image_config = {
{"type", "image"}, {"height", height}, {"width", width}, {"channel_major", false}};
nlohmann::json label_config = {{"type", "label"}, {"binary", false}};
nlohmann::json config = {{"manifest_filename", manifest_file},
{"batch_size", batch_size},
{"iteration_mode", "INFINITE"},
{"etl", {image_config, label_config}}};
loader_factory factory;
EXPECT_THROW(factory.get_loader(config), std::runtime_error);
}
}
| 32.070646 | 100 | 0.558033 | rkimballn1 |
96f6c44ea96b4a9d526f8476396dfd1d359e8e9d | 3,758 | hpp | C++ | gtfo/algorithm/search_n.hpp | TMorozovsky/Generic_Tools_for_Frequent_Operations | bbc6804e1259f53a84375316cddeb9b648359c28 | [
"MIT"
] | 1 | 2016-01-09T09:57:55.000Z | 2016-01-09T09:57:55.000Z | gtfo/algorithm/search_n.hpp | TMorozovsky/Generic_Tools_for_Frequent_Operations | bbc6804e1259f53a84375316cddeb9b648359c28 | [
"MIT"
] | null | null | null | gtfo/algorithm/search_n.hpp | TMorozovsky/Generic_Tools_for_Frequent_Operations | bbc6804e1259f53a84375316cddeb9b648359c28 | [
"MIT"
] | null | null | null | #ifndef GTFO_FILE_INCLUDED_ALGORITHM_SEARCH_N_HPP
#define GTFO_FILE_INCLUDED_ALGORITHM_SEARCH_N_HPP
/*
* Defines the following overloads:
* search_n(ForwardIterator, ForwardIterator, Size, const Value &);
* search_n(ForwardIterator, ForwardIterator, Size, const Value &, BinaryPredicate);
* search_n(Range, Size, const Value &);
* search_n(Range, Size, const Value &, BinaryPredicate);
*/
#include <algorithm>
#include "gtfo/_impl/utility.hpp"
#include "gtfo/_impl/type_traits/are_comparable_op_eq.hpp"
#include "gtfo/_impl/type_traits/are_comparable_pred.hpp"
#include "gtfo/_impl/type_traits/result_of_dereferencing.hpp"
#include "gtfo/_impl/type_traits/iterator_of_range.hpp"
namespace gtfo
{
#define GTFO_RESULT_OF_SEARCH_N(ForwardIterator, Value) \
typename _tt::enable_if \
< \
_tt::are_comparable_op_eq \
< \
typename _tt::result_of_dereferencing< ForwardIterator >::type, \
Value \
>::value, \
ForwardIterator \
>::type
#define GTFO_RESULT_OF_SEARCH_N_PRED(ForwardIterator, Value, BinaryPredicate) \
typename _tt::enable_if \
< \
_tt::are_comparable_pred \
< \
BinaryPredicate, \
typename _tt::result_of_dereferencing< ForwardIterator >::type, \
Value \
>::value, \
ForwardIterator \
>::type
template<typename ForwardIterator, typename Size, typename Value>
inline
GTFO_RESULT_OF_SEARCH_N(ForwardIterator,
Value)
search_n(ForwardIterator _it_begin,
ForwardIterator _it_end,
Size _count,
const Value & _value)
{
return ::std::search_n(::gtfo::move(_it_begin),
::gtfo::move(_it_end),
::gtfo::move(_count),
_value);
}
template<typename ForwardIterator, typename Size, typename Value, typename BinaryPredicate>
inline
ForwardIterator
search_n(ForwardIterator _it_begin,
ForwardIterator _it_end,
Size _count,
const Value & _value,
BinaryPredicate _pred)
{
return ::std::search_n(::gtfo::move(_it_begin),
::gtfo::move(_it_end),
::gtfo::move(_count),
_value,
::gtfo::move(_pred));
}
template<typename Range, typename Size, typename Value>
inline
typename _tt::iterator_of_range< Range >::type
search_n(Range && _range,
Size _count,
const Value & _value)
{
return ::std::search_n(begin(_range),
end(_range),
::gtfo::move(_count),
_value);
}
template<typename Range, typename Size, typename Value, typename BinaryPredicate>
inline
GTFO_RESULT_OF_SEARCH_N_PRED(typename _tt::iterator_of_range< Range >::type,
Value,
BinaryPredicate)
search_n(Range && _range,
Size _count,
const Value & _value,
BinaryPredicate _pred)
{
return ::std::search_n(begin(_range),
end(_range),
::gtfo::move(_count),
_value,
::gtfo::move(_pred));
}
#undef GTFO_RESULT_OF_SEARCH_N_PRED
#undef GTFO_RESULT_OF_SEARCH_N
}
#endif // GTFO_FILE_INCLUDED_ALGORITHM_SEARCH_N_HPP
| 33.553571 | 97 | 0.552155 | TMorozovsky |
96fab864cfa6183c048e07f09223ff4be016dfb0 | 3,191 | cpp | C++ | src/mfx/ControlledParam.cpp | mikelange49/pedalevite | a81bd8a6119c5920995ec91b9f70e11e9379580e | [
"WTFPL"
] | 69 | 2017-01-17T13:17:31.000Z | 2022-03-01T14:56:32.000Z | src/mfx/ControlledParam.cpp | mikelange49/pedalevite | a81bd8a6119c5920995ec91b9f70e11e9379580e | [
"WTFPL"
] | 1 | 2020-11-03T14:52:45.000Z | 2020-12-01T20:31:15.000Z | src/mfx/ControlledParam.cpp | mikelange49/pedalevite | a81bd8a6119c5920995ec91b9f70e11e9379580e | [
"WTFPL"
] | 8 | 2017-02-08T13:30:42.000Z | 2021-12-09T08:43:09.000Z | /*****************************************************************************
ControlledParam.cpp
Author: Laurent de Soras, 2016
--- Legal stuff ---
This program is free software. It comes without any warranty, to
the extent permitted by applicable law. You can redistribute it
and/or modify it under the terms of the Do What The Fuck You Want
To Public License, Version 2, as published by Sam Hocevar. See
http://sam.zoy.org/wtfpl/COPYING for more details.
*Tab=3***********************************************************************/
#if defined (_MSC_VER)
#pragma warning (1 : 4130 4223 4705 4706)
#pragma warning (4 : 4355 4786 4800)
#endif
/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
#include "fstb/fnc.h"
#include "mfx/ControlledParam.h"
#include "mfx/CtrlUnit.h"
#include "mfx/PluginPool.h"
#include "mfx/ProcessingContext.h"
#include <cassert>
namespace mfx
{
/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
ControlledParam::ControlledParam (const ParamCoord ¶m)
: _param (param)
, _ctrl_list ()
{
// Nothing
}
const ParamCoord & ControlledParam::use_coord () const
{
return _param;
}
ControlledParam::CtrlUnitList & ControlledParam::use_unit_list ()
{
return _ctrl_list;
}
const ControlledParam::CtrlUnitList & ControlledParam::use_unit_list () const
{
return _ctrl_list;
}
// For parameters with relative sources
void ControlledParam::update_internal_val(float val_nrm)
{
assert (! _ctrl_list.empty () && _ctrl_list [0]->_abs_flag);
CtrlUnit & unit = *_ctrl_list [0];
unit.update_internal_val (val_nrm);
}
// Controller absolute values should have been updated beforehand
// Parameter value in the plug-in pool is updated if there is an absolute controler.
float ControlledParam::compute_final_val (PluginPool &pi_pool) const
{
PluginPool::PluginDetails & details =
pi_pool.use_plugin (_param._plugin_id);
float val = 0;
int beg = 0;
const int index = _param._param_index;
if ( ! _ctrl_list.empty ()
&& _ctrl_list [0]->_abs_flag)
{
CtrlUnit & unit = *_ctrl_list [0];
// If the modification comes from the audio thread (controller),
// we calculate the new value and update the reference.
if (details._param_update_from_audio [index])
{
val = unit.evaluate (0);
details._param_arr [index] = fstb::limit (val, 0.f, 1.f);
}
// Otherwise, we get the value from the reference.
else
{
val = details._param_arr [index];
if (unit._source.is_relative ())
{
// Forces internal value for relative sources
unit.update_internal_val (val);
}
}
beg = 1;
}
else
{
val = details._param_arr [index];
}
for (int m = beg; m < int (_ctrl_list.size ()); ++m)
{
const CtrlUnit & unit = *_ctrl_list [m];
val = unit.evaluate (val);
}
val = fstb::limit (val, 0.f, 1.f);
return val;
}
/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
} // namespace mfx
/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
| 20.856209 | 84 | 0.579442 | mikelange49 |
96fcd45b14a5c76cdefc0fec95107889abdad464 | 429 | cpp | C++ | Pbinfo/Prime.cpp | Al3x76/cpp | 08a0977d777e63e0d36d87fcdea777de154697b7 | [
"MIT"
] | 7 | 2019-01-06T19:10:14.000Z | 2021-10-16T06:41:23.000Z | Pbinfo/Prime.cpp | Al3x76/cpp | 08a0977d777e63e0d36d87fcdea777de154697b7 | [
"MIT"
] | null | null | null | Pbinfo/Prime.cpp | Al3x76/cpp | 08a0977d777e63e0d36d87fcdea777de154697b7 | [
"MIT"
] | 6 | 2019-01-06T19:17:30.000Z | 2020-02-12T22:29:17.000Z | #include <fstream>
using namespace std;
ifstream cin("prime.in");
ofstream cout("prime.out");
bool prim(int n){
if(n==0 || n==1) return 0;
if(n==2) return 1;
if(n%2==0) return 0;
for(int d=3; d*d<=n; d=d+2)
if(n%d==0) return 0;
return 1;
}
int main()
{
int n, a[1000];
cin>>n;
for(int i=1; i<=n; i++){
cin>>a[i];
if(prim(a[i])) cout<<a[i]<<" ";
}
return 0;
} | 14.793103 | 39 | 0.482517 | Al3x76 |
8c102b026fa270923c5e1b5b590a34376b49cedd | 8,748 | cc | C++ | src/s3_cmds/zgw_s3_completemultiupload.cc | baotiao/zeppelin-gateway | bff8d8e160422322e306dfc1dc1768b29001a8c0 | [
"Apache-2.0"
] | 20 | 2017-05-04T00:49:55.000Z | 2022-03-27T10:06:02.000Z | src/s3_cmds/zgw_s3_completemultiupload.cc | baotiao/zeppelin-gateway | bff8d8e160422322e306dfc1dc1768b29001a8c0 | [
"Apache-2.0"
] | null | null | null | src/s3_cmds/zgw_s3_completemultiupload.cc | baotiao/zeppelin-gateway | bff8d8e160422322e306dfc1dc1768b29001a8c0 | [
"Apache-2.0"
] | 16 | 2017-04-11T08:10:04.000Z | 2020-06-16T02:49:48.000Z | #include "src/s3_cmds/zgw_s3_object.h"
#include <algorithm>
#include "slash/include/env.h"
#include "src/s3_cmds/zgw_s3_xml.h"
#include "src/zgw_utils.h"
bool CompleteMultiUploadCmd::DoInitial() {
http_request_xml_.clear();
http_response_xml_.clear();
received_parts_info_.clear();
upload_id_ = query_params_.at("uploadId");
md5_ctx_.Init();
request_id_ = md5(bucket_name_ +
object_name_ +
upload_id_ +
std::to_string(slash::NowMicros()));
if (!TryAuth()) {
DLOG(INFO) << request_id_ << " " <<
"CompleteMultiUpload(DoInitial) - Auth failed: " << client_ip_port_;
g_zgw_monitor->AddAuthFailed();
return false;
}
DLOG(INFO) << request_id_ << " " <<
"CompleteMultiUpload(DoInitial) - " << bucket_name_ << "/" << object_name_ <<
", uploadId: " << upload_id_;
return true;
}
void CompleteMultiUploadCmd::DoReceiveBody(const char* data, size_t data_size) {
http_request_xml_.append(data, data_size);
}
bool CompleteMultiUploadCmd::ParseReqXml() {
S3XmlDoc doc;
if (!doc.ParseFromString(http_request_xml_)) {
return false;
}
S3XmlNode root;
if (!doc.FindFirstNode("CompleteMultipartUpload", &root)) {
return false;
}
S3XmlNode node;
if (!root.FindFirstNode("Part", &node)) {
return false;
}
do {
S3XmlNode part_num, etag;
if (!node.FindFirstNode("PartNumber", &part_num) ||
!node.FindFirstNode("ETag", &etag)) {
return false;
}
// Trim quote of etag
std::string etag_s = etag.value();
if (!etag_s.empty() && etag_s.at(0) == '"') {
etag_s.assign(etag_s.substr(1, 32));
}
received_parts_info_.push_back(std::make_pair(part_num.value(), etag_s));
} while (node.NextSibling());
return true;
}
void CompleteMultiUploadCmd::DoAndResponse(pink::HTTPResponse* resp) {
if (http_ret_code_ == 200) {
if (!ParseReqXml()) {
http_ret_code_ = 400;
GenerateErrorXml(kMalformedXML);
}
std::string virtual_bucket = "__TMPB" + upload_id_ +
bucket_name_ + "|" + object_name_;
std::string new_data_blocks;
uint64_t data_size = 0;
std::vector<zgwstore::Object> stored_parts;
DLOG(INFO) << request_id_ << " " <<
"CompleteMultiUpload(DoAndResponse) - virtual_bucket: " << virtual_bucket;
Status s = store_->Lock();
if (s.ok()) {
DLOG(INFO) << request_id_ << " " <<
"CompleteMultiUpload(DoAndResponse) - Lock success";
if (http_ret_code_ == 200) {
s = store_->ListObjects(user_name_, virtual_bucket, &stored_parts);
if (!s.ok()) {
if (s.ToString().find("Bucket Doesn't Belong To This User") !=
std::string::npos) {
http_ret_code_ = 404;
GenerateErrorXml(kNoSuchUpload, upload_id_);
} else {
http_ret_code_ = 500;
LOG(ERROR) << request_id_ << " " <<
"CompleteMultiUpload(DoAndResponse) - ListVirtObjects " <<
virtual_bucket << "error: " << s.ToString();
}
} else {
// Complete multiupload
if (received_parts_info_.size() != stored_parts.size()) {
http_ret_code_ = 400;
GenerateErrorXml(kInvalidPart);
} else {
// sort stored parts
std::sort(stored_parts.begin(), stored_parts.end(),
[](const zgwstore::Object& a, const zgwstore::Object& b) {
return std::atoi(a.object_name.c_str()) <
std::atoi(b.object_name.c_str());
});
for (size_t i = 0 ; i < received_parts_info_.size(); i++) {
bool found_part = false;
for (auto& stored_part : stored_parts) {
if (received_parts_info_[i].first == stored_part.object_name) {
found_part = true;
break;
}
}
if (!found_part) {
http_ret_code_ = 400;
GenerateErrorXml(kInvalidPart);
break;
}
if (received_parts_info_[i].first != stored_parts[i].object_name) {
http_ret_code_ = 400;
GenerateErrorXml(kInvalidPartOrder);
break;
}
if (received_parts_info_[i].second != stored_parts[i].etag) {
http_ret_code_ = 400;
GenerateErrorXml(kInvalidPart);
break;
}
md5_ctx_.Update(stored_parts[i].etag);
data_size += stored_parts[i].size;
// AddMultiBlockSet
// Add sort sign
char buf[100];
sprintf(buf, "%05d", std::atoi(stored_parts[i].object_name.c_str()));
s = store_->AddMultiBlockSet(bucket_name_, object_name_, upload_id_,
std::string(buf) + stored_parts[i].data_block);
if (!s.ok()) {
http_ret_code_ = 500;
LOG(ERROR) << request_id_ << " " <<
"CompleteMultiUpload(DoAndResponse) - AddMultiBlockSet" <<
virtual_bucket << "/" << stored_parts[i].object_name << " " <<
upload_id_ << " error: " << s.ToString();
}
}
}
}
}
if (http_ret_code_ == 200) {
// Initial new_object_
new_object_.bucket_name = bucket_name_;
new_object_.object_name = object_name_;
new_object_.etag = md5_ctx_.ToString() + "-" +
std::to_string(stored_parts.size());
new_object_.size = data_size;
new_object_.owner = user_name_;
new_object_.last_modified = slash::NowMicros();
new_object_.storage_class = 0; // Unused
new_object_.acl = "FULL_CONTROL";
new_object_.upload_id = upload_id_;
new_object_.data_block = upload_id_ + bucket_name_ + "|" + object_name_;
// Write meta
Status s = store_->AddObject(new_object_, false);
if (!s.ok()) {
http_ret_code_ = 500;
LOG(ERROR) << request_id_ << " " <<
"CompleteMultiUpload(DoAndResponse) - AddObject " << bucket_name_ <<
"/" << object_name_ << "error: " << s.ToString();
} else {
DLOG(INFO) << request_id_ << " " <<
"CompleteMultiUpload(DoAndResponse) - AddObject " << bucket_name_ <<
"/" << object_name_ << "success, cleaning...";
for (auto& p : stored_parts) {
s = store_->DeleteObject(user_name_, virtual_bucket, p.object_name, false, false);
if (s.IsIOError()) {
http_ret_code_ = 500;
LOG(ERROR) << request_id_ << " " <<
"CompleteMultiUpload(DoAndResponse) - DeleteVirtObject " <<
virtual_bucket << "/" << p.object_name << " error: " << s.ToString();
}
}
if (http_ret_code_ == 200) {
s = store_->DeleteBucket(user_name_, virtual_bucket, false);
if (s.IsIOError()) {
http_ret_code_ = 500;
LOG(ERROR) << request_id_ << " " <<
"CompleteMultiUpload(DoAndResponse) - DeleteVirtBucket " <<
virtual_bucket << " error: " << s.ToString();
}
}
}
}
s = store_->UnLock();
}
if (!s.ok()) {
http_ret_code_ = 500;
LOG(ERROR) << request_id_ << " " <<
"CompleteMultiUpload(DoAndResponse) - Lock or Unlock error:" <<
s.ToString();
}
DLOG(INFO) << request_id_ << " " <<
"CompleteMultiUpload(DoAndResponse) - UnLock success";
if (http_ret_code_ == 200) {
DLOG(INFO) << "CompleteMultiUpload(DoAndResponse) - Clean OK";
// Build response XML
GenerateRespXml();
}
}
g_zgw_monitor->AddApiRequest(kCompleteMultiUpload, http_ret_code_);
resp->SetStatusCode(http_ret_code_);
resp->SetContentLength(http_response_xml_.size());
}
void CompleteMultiUploadCmd::GenerateRespXml() {
S3XmlDoc doc("CompleteMultipartUploadResult");
doc.AppendToRoot(doc.AllocateNode("Bucket", bucket_name_));
doc.AppendToRoot(doc.AllocateNode("Key", object_name_));
doc.AppendToRoot(doc.AllocateNode("ETag", "\"" + new_object_.etag + "\""));
doc.ToString(&http_response_xml_);
}
int CompleteMultiUploadCmd::DoResponseBody(char* buf, size_t max_size) {
if (max_size < http_response_xml_.size()) {
memcpy(buf, http_response_xml_.data(), max_size);
http_response_xml_.assign(http_response_xml_.substr(max_size));
} else {
memcpy(buf, http_response_xml_.data(), http_response_xml_.size());
}
return std::min(max_size, http_response_xml_.size());
}
| 36 | 94 | 0.569845 | baotiao |
8c147229939933595fc2b15fa4eadcc02734e81b | 5,164 | cpp | C++ | engine/samples/ModelLoading/src/MainState.cpp | Arthapz/StormKit | 7c8dead874734d04b97776287b25bf2ebe9be617 | [
"MIT"
] | 17 | 2019-02-12T14:40:06.000Z | 2021-12-21T12:54:17.000Z | engine/samples/ModelLoading/src/MainState.cpp | Arthapz/StormKit | 7c8dead874734d04b97776287b25bf2ebe9be617 | [
"MIT"
] | null | null | null | engine/samples/ModelLoading/src/MainState.cpp | Arthapz/StormKit | 7c8dead874734d04b97776287b25bf2ebe9be617 | [
"MIT"
] | 2 | 2019-02-21T10:07:42.000Z | 2020-05-08T19:49:10.000Z | #include "MainState.hpp"
#include "Log.hpp"
/////////// - StormKit::entities - ///////////
#include <storm/entities/MessageBus.hpp>
/////////// - StormKit::render - ///////////
#include <storm/render/core/Device.hpp>
#include <storm/render/core/PhysicalDevice.hpp>
#include <storm/render/core/Surface.hpp>
/////////// - StormKit::window - ///////////
#include <storm/window/Keyboard.hpp>
#include <storm/window/Mouse.hpp>
#include <storm/window/Window.hpp>
/////////// - StormKit::engine - ///////////
#include <storm/engine/Engine.hpp>
#include <storm/engine/NameComponent.hpp>
#include <storm/engine/render/DrawableComponent.hpp>
#include <storm/engine/render/MaterialComponent.hpp>
#include <storm/engine/render/TransformComponent.hpp>
#include <storm/engine/render/3D/FPSCamera.hpp>
#include <storm/engine/render/3D/Model.hpp>
#include <storm/engine/render/3D/PbrMesh.hpp>
#include <storm/engine/render/3D/PbrRenderSystem.hpp>
using namespace storm;
static constexpr auto ROTATE_ANGLE = 5.f;
class RotationSystem: public entities::System {
public:
explicit RotationSystem(entities::EntityManager &manager)
: System { manager, 1, { engine::TransformComponent::TYPE } } {}
~RotationSystem() override = default;
RotationSystem(RotationSystem &&) noexcept = default;
RotationSystem &operator=(RotationSystem &&) noexcept = default;
void update(core::Secondf delta) override {
for (auto e : m_entities) {
auto &transform_component = m_manager->getComponent<engine::TransformComponent>(e);
transform_component.transform.rotateRoll(ROTATE_ANGLE * delta.count());
}
}
protected:
void onMessageReceived(const entities::Message &message) override {}
};
////////////////////////////////////////
////////////////////////////////////////
MainState::MainState(core::StateManager &owner, engine::Engine &engine, window::Window &window)
: State { owner, engine }, m_window { window },
m_keyboard { window.createKeyboardPtr() }, m_mouse { window.createMousePtr() } {
m_mouse->setPositionOnWindow(
core::Position2i { window.size().width / 2, window.size().height / 2 });
const auto extent = State::engine().surface().extent();
m_render_system = &m_world.addSystem<engine::PbrRenderSystem>(State::engine());
m_world.addSystem<RotationSystem>();
m_camera = engine::FPSCamera::allocateOwned(extent);
m_camera->setPosition({ 0.f, 0.f, -3.f });
m_render_system->setCamera(*m_camera);
m_model = engine::Model::allocateOwned(engine, EXAMPLES_DATA_DIR "models/Sword.glb");
auto mesh = m_model->createMesh();
auto e = m_world.makeEntity();
auto &name_component = m_world.addComponent<engine::NameComponent>(e);
name_component.name = "MyMesh";
auto &drawable_component = m_world.addComponent<engine::DrawableComponent>(e);
drawable_component.drawable = std::move(mesh);
m_world.addComponent<engine::TransformComponent>(e);
enableCamera();
}
////////////////////////////////////////
////////////////////////////////////////
MainState::~MainState() = default;
////////////////////////////////////////
////////////////////////////////////////
MainState::MainState(MainState &&) noexcept = default;
////////////////////////////////////////
////////////////////////////////////////
MainState &MainState::operator=(MainState &&) noexcept = default;
////////////////////////////////////////
////////////////////////////////////////
void MainState::update(core::Secondf delta) {
if (m_camera_enabled) {
auto inputs = engine::FPSCamera::Inputs {
.up = m_keyboard->isKeyPressed(window::Key::Z),
.down = m_keyboard->isKeyPressed(window::Key::S),
.right = m_keyboard->isKeyPressed(window::Key::D),
.left = m_keyboard->isKeyPressed(window::Key::Q),
};
const auto extent = core::Extenti { State::engine().surface().extent() };
const auto position = [&inputs, &extent, this]() {
auto position = m_mouse->getPositionOnWindow();
if (position->x <= 5 || position->x > (extent.width - 5)) {
position->x = extent.width / 2;
inputs.mouse_ignore = true;
}
if (position->y <= 5 || position->y > (extent.height - 5)) {
position->y = extent.height / 2;
inputs.mouse_ignore = true;
}
m_mouse->setPositionOnWindow(position);
return position;
}();
inputs.mouse_updated = true;
inputs.x_mouse = static_cast<float>(position->x);
inputs.y_mouse = static_cast<float>(position->y);
m_camera->feedInputs(inputs);
m_camera->update(delta);
}
auto &frame = engine().beginFrame();
m_world.step(delta);
m_render_system->render(frame);
engine().endFrame();
}
void MainState::enableCamera() noexcept {
m_window.get().lockMouse();
m_camera_enabled = true;
}
void MainState::disableCamera() noexcept {
m_window.get().unlockMouse();
m_camera_enabled = false;
}
| 33.532468 | 95 | 0.595275 | Arthapz |
22c49f58b40dfb1128231c78099a753b486200b9 | 1,143 | cpp | C++ | atreyu/main.cpp | AiRT-Software/ocs | 2d6056a1260ac9ac75cfd507fb1a77db3b26298a | [
"BSD-4-Clause"
] | 1 | 2019-02-07T12:24:51.000Z | 2019-02-07T12:24:51.000Z | atreyu/main.cpp | AiRT-Software/ocs | 2d6056a1260ac9ac75cfd507fb1a77db3b26298a | [
"BSD-4-Clause"
] | null | null | null | atreyu/main.cpp | AiRT-Software/ocs | 2d6056a1260ac9ac75cfd507fb1a77db3b26298a | [
"BSD-4-Clause"
] | 1 | 2020-07-06T10:33:10.000Z | 2020-07-06T10:33:10.000Z |
/*
AiRT Software
http://www.airt.eu
This project has received funding from the European Union's Horizon 2020 research
and innovation programme under grant agreement No 732433.
Copyright Universitat Politecnica de Valencia 2017-2018.
All rights reserved.
Instituto de Automática e Informática Industrial (ai2)
http://www.ai2.upv.es
Contact: Paco Abad ([email protected])
*/
#include <log.h>
#include "server.h"
#include "globalSettings.h"
using namespace airt;
int main(int argc, char **argv)
{
Log::setFile("atreyu.log");
// Remove for final release
Log::setOutputToConsole(true);
//
for (int i = 1; i < argc; i++)
{
std::string opt(argv[i]);
if (opt == "-l" && (i + 1 < argc))
{
Log::setFile(argv[++i]);
}
else if (opt == "-i" && (i + 1 < argc))
{
GlobalSettings::setIniFile(argv[++i]);
}
else if (opt == "-h" || opt == "--help")
{
std::cerr << argv[0] << " [-l logfile] [-i initfile] [-h]\n";
return -2;
}
}
Server server;
server.run();
return 0;
}
| 19.372881 | 81 | 0.55818 | AiRT-Software |
22c557929df89e8dc17f778d87fdd7bcc1010935 | 289 | cpp | C++ | tsc/src/SkyObject/Earth.cpp | jbangelo/tsc | 3251f81a27c7dbee043736e0f579f5d2a9e991a1 | [
"MIT"
] | 1 | 2016-11-29T01:31:26.000Z | 2016-11-29T01:31:26.000Z | tsc/src/SkyObject/Earth.cpp | jbangelo/tsc | 3251f81a27c7dbee043736e0f579f5d2a9e991a1 | [
"MIT"
] | null | null | null | tsc/src/SkyObject/Earth.cpp | jbangelo/tsc | 3251f81a27c7dbee043736e0f579f5d2a9e991a1 | [
"MIT"
] | null | null | null | /*
* Earth.cpp
*
* Created on: Nov 21, 2015
* Author: ben
*/
#include "SkyObject/Earth.h"
using tsc::SkyObject::Earth;
using tsc::Utils::IDataStorage;
Earth::Earth(IDataStorage& dataStorage) :
Planet(EARTH, dataStorage, *this)
{
_isEarth = true;
}
Earth::~Earth()
{
}
| 11.56 | 41 | 0.640138 | jbangelo |
22c60e356e68db2412b1696f5d97877bcf0148df | 9,831 | cpp | C++ | trace_server/3rd/qwt/qwt_spline_cardinal.cpp | mojmir-svoboda/DbgToolkit | 590887987d0856032be906068a3103b6ce31d21c | [
"MIT"
] | null | null | null | trace_server/3rd/qwt/qwt_spline_cardinal.cpp | mojmir-svoboda/DbgToolkit | 590887987d0856032be906068a3103b6ce31d21c | [
"MIT"
] | null | null | null | trace_server/3rd/qwt/qwt_spline_cardinal.cpp | mojmir-svoboda/DbgToolkit | 590887987d0856032be906068a3103b6ce31d21c | [
"MIT"
] | null | null | null | /* -*- mode: C++ ; c-file-style: "stroustrup" -*- *****************************
* Qwt Widget Library
* Copyright (C) 1997 Josef Wilgen
* Copyright (C) 2002 Uwe Rathmann
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the Qwt License, Version 1.0
*****************************************************************************/
#include "qwt_spline_cardinal.h"
namespace QwtSplineCardinalG1P
{
class PathStore
{
public:
inline void init( int )
{
}
inline void start( const QPointF &p0 )
{
path.moveTo( p0 );
}
inline void addCubic( const QPointF &cp1,
const QPointF &cp2, const QPointF &p2 )
{
path.cubicTo( cp1, cp2, p2 );
}
QPainterPath path;
};
class ControlPointsStore
{
public:
inline ControlPointsStore():
d_cp( NULL )
{
}
inline void init( int size )
{
controlPoints.resize( size );
d_cp = controlPoints.data();
}
inline void start( const QPointF & )
{
}
inline void addCubic( const QPointF &cp1,
const QPointF &cp2, const QPointF & )
{
QLineF &l = *d_cp++;
l.setPoints( cp1, cp2 );
}
QVector<QLineF> controlPoints;
private:
QLineF* d_cp;
};
}
static inline QwtSplineCardinalG1::Tension qwtTension(
double d13, double d23, double d24,
const QPointF &p1, const QPointF &p2,
const QPointF &p3, const QPointF &p4 )
{
const bool b1 = ( d13 / 3.0 ) < d23;
const bool b2 = ( d24 / 3.0 ) < d23;
QwtSplineCardinalG1::Tension tension;
if ( b1 & b2 )
{
tension.t1 = ( p1 != p2 ) ? ( 1.0 / 3.0 ) : ( 2.0 / 3.0 );
tension.t2 = ( p3 != p4 ) ? ( 1.0 / 3.0 ) : ( 2.0 / 3.0 );
}
else
{
tension.t1 = d23 / ( b1 ? d24 : d13 );
tension.t2 = d23 / ( b2 ? d13 : d24 );
}
return tension;
}
template< class Param >
static inline QVector<QwtSplineCardinalG1::Tension> qwtTensions(
const QPolygonF &points, bool isClosed, Param param )
{
const int size = points.size();
QVector<QwtSplineCardinalG1::Tension> tensions2( isClosed ? size : size - 1 );
const QPointF *p = points.constData();
QwtSplineCardinalG1::Tension *t = tensions2.data();
const QPointF &p0 = isClosed ? p[size-1] : p[0];
double d13 = param(p[0], p[2]);
t[0] = qwtTension( param(p0, p[1]), param(p[0], p[1]),
d13, p0, p[0], p[1], p[2] );
for ( int i = 1; i < size - 2; i++ )
{
const double d23 = param( p[i], p[i+1] );
const double d24 = param( p[i], p[i+2] );
t[i] = qwtTension( d13, d23, d24, p[i-1], p[i], p[i+1], p[i+2] );
d13 = d24;
}
const QPointF &pn = isClosed ? p[0] : p[size-1];
const double d24 = param( p[size-2], pn );
t[size-2] = qwtTension( d13, param( p[size-2], p[size-1] ), d24,
p[size - 3], p[size - 2], p[size - 1], pn );
if ( isClosed )
{
const double d34 = param( p[size-1], p[0] );
const double d35 = param( p[size-1], p[1] );
t[size-1] = qwtTension( d24, d34, d35, p[size-2], p[size-1], p[0], p[1] );
}
return tensions2;
}
template< class SplineStore >
static SplineStore qwtSplinePathG1(
const QwtSplineCardinalG1 *spline, const QPolygonF &points )
{
const int size = points.size();
const int numTensions = spline->isClosing() ? size : size - 1;
const QVector<QwtSplineCardinalG1::Tension> tensions2 = spline->tensions( points );
if ( tensions2.size() != numTensions )
return SplineStore();
const QPointF *p = points.constData();
const QwtSplineCardinalG1::Tension *t = tensions2.constData();
SplineStore store;
store.init( numTensions );
store.start( p[0] );
const QPointF &p0 = spline->isClosing() ? p[size-1] : p[0];
QPointF vec1 = ( p[1] - p0 ) * 0.5;
for ( int i = 0; i < size - 2; i++ )
{
const QPointF vec2 = ( p[i+2] - p[i] ) * 0.5;
store.addCubic( p[i] + vec1 * t[i].t1,
p[i+1] - vec2 * t[i].t2, p[i+1] );
vec1 = vec2;
}
const QPointF &pn = spline->isClosing() ? p[0] : p[size-1];
const QPointF vec2 = 0.5 * ( pn - p[size - 2] );
store.addCubic( p[size - 2] + vec1 * t[size-2].t1,
p[size - 1] - vec2 * t[size-2].t2, p[size - 1] );
if ( spline->isClosing() )
{
const QPointF vec3 = 0.5 * ( p[1] - p[size-1] );
store.addCubic( p[size-1] + vec2 * t[size-1].t1,
p[0] - vec3 * t[size-1].t2, p[0] );
}
return store;
}
template< class SplineStore, class Param >
static SplineStore qwtSplinePathPleasing( const QPolygonF &points,
bool isClosed, Param param )
{
const int size = points.size();
const QPointF *p = points.constData();
SplineStore store;
store.init( isClosed ? size : size - 1 );
store.start( p[0] );
const QPointF &p0 = isClosed ? p[size-1] : p[0];
double d13 = param(p[0], p[2]);
const QwtSplineCardinalG1::Tension t0 = qwtTension(
param(p0, p[1]), param(p[0], p[1]), d13, p0, p[0], p[1], p[2] );
const QPointF vec0 = ( p[1] - p0 ) * 0.5;
QPointF vec1 = ( p[2] - p[0] ) * 0.5;
store.addCubic( p[0] + vec0 * t0.t1, p[1] - vec1 * t0.t2, p[1] );
for ( int i = 1; i < size - 2; i++ )
{
const double d23 = param(p[i], p[i+1]);
const double d24 = param(p[i], p[i+2]);
const QPointF vec2 = ( p[i+2] - p[i] ) * 0.5;
const QwtSplineCardinalG1::Tension t =
qwtTension( d13, d23, d24, p[i-1], p[i], p[i+1], p[i+2] );
store.addCubic( p[i] + vec1 * t.t1, p[i+1] - vec2 * t.t2, p[i+1] );
d13 = d24;
vec1 = vec2;
}
const QPointF &pn = isClosed ? p[0] : p[size-1];
const double d24 = param( p[size-2], pn );
const QwtSplineCardinalG1::Tension tn = qwtTension(
d13, param( p[size-2], p[size-1] ), d24, p[size-3], p[size-2], p[size-1], pn );
const QPointF vec2 = 0.5 * ( pn - p[size-2] );
store.addCubic( p[size-2] + vec1 * tn.t1, p[size-1] - vec2 * tn.t2, p[size-1] );
if ( isClosed )
{
const double d34 = param( p[size-1], p[0] );
const double d35 = param( p[size-1], p[1] );
const QPointF vec3 = 0.5 * ( p[1] - p[size-1] );
const QwtSplineCardinalG1::Tension tn =
qwtTension( d24, d34, d35, p[size-2], p[size-1], p[0], p[1] );
store.addCubic( p[size-1] + vec2 * tn.t1, p[0] - vec3 * tn.t2, p[0] );
}
return store;
}
QwtSplineCardinalG1::QwtSplineCardinalG1()
{
}
QwtSplineCardinalG1::~QwtSplineCardinalG1()
{
}
QVector<QLineF> QwtSplineCardinalG1::bezierControlPointsP(
const QPolygonF &points ) const
{
using namespace QwtSplineCardinalG1P;
const ControlPointsStore store =
qwtSplinePathG1<ControlPointsStore>( this, points );
return store.controlPoints;
}
QPainterPath QwtSplineCardinalG1::pathP( const QPolygonF &points ) const
{
using namespace QwtSplineCardinalG1P;
PathStore store = qwtSplinePathG1<PathStore>( this, points );
if ( isClosing() )
store.path.closeSubpath();
return store.path;
}
QwtSplinePleasing::QwtSplinePleasing()
{
}
QwtSplinePleasing::~QwtSplinePleasing()
{
}
QPainterPath QwtSplinePleasing::pathP( const QPolygonF &points ) const
{
const int size = points.size();
if ( size <= 2 )
return QwtSplineCardinalG1::pathP( points );
using namespace QwtSplineCardinalG1P;
PathStore store;
switch( parametrization()->type() )
{
case QwtSplineParameter::ParameterX:
{
store = qwtSplinePathPleasing<PathStore>( points,
isClosing(), QwtSplineParameter::paramX() );
break;
}
case QwtSplineParameter::ParameterUniform:
{
store = qwtSplinePathPleasing<PathStore>( points,
isClosing(), QwtSplineParameter::paramUniform() );
break;
}
case QwtSplineParameter::ParameterChordal:
{
store = qwtSplinePathPleasing<PathStore>( points,
isClosing(), QwtSplineParameter::paramChordal() );
break;
}
default:
{
store = qwtSplinePathPleasing<PathStore>( points,
isClosing(), QwtSplineParameter::param( parametrization() ) );
}
}
if ( isClosing() )
store.path.closeSubpath();
return store.path;
}
QVector<QLineF> QwtSplinePleasing::bezierControlPointsP(
const QPolygonF &points ) const
{
return QwtSplineCardinalG1::bezierControlPointsP( points );
}
QVector<QwtSplineCardinalG1::Tension>
QwtSplinePleasing::tensions( const QPolygonF &points ) const
{
QVector<Tension> tensions2;
if ( points.size() <= 2 )
return tensions2;
switch( parametrization()->type() )
{
case QwtSplineParameter::ParameterX:
{
tensions2 = qwtTensions( points,
isClosing(), QwtSplineParameter::paramX() );
break;
}
case QwtSplineParameter::ParameterUniform:
{
tensions2 = qwtTensions( points,
isClosing(), QwtSplineParameter::paramUniform() );
break;
}
case QwtSplineParameter::ParameterChordal:
{
tensions2 = qwtTensions( points,
isClosing(), QwtSplineParameter::paramChordal() );
break;
}
default:
{
tensions2 = qwtTensions( points,
isClosing(), QwtSplineParameter::param( parametrization() ) );
}
}
return tensions2;
}
| 27.157459 | 87 | 0.551521 | mojmir-svoboda |
22c62abcae296cc143d5e364ae8c021641d9991e | 982 | cpp | C++ | Shared/Src/Shin/Vertex/TextureVertex.cpp | sindharta/vulkan-sandbox | 45ef4be936273723b0d8f84a7396293016e4254b | [
"Apache-2.0"
] | null | null | null | Shared/Src/Shin/Vertex/TextureVertex.cpp | sindharta/vulkan-sandbox | 45ef4be936273723b0d8f84a7396293016e4254b | [
"Apache-2.0"
] | null | null | null | Shared/Src/Shin/Vertex/TextureVertex.cpp | sindharta/vulkan-sandbox | 45ef4be936273723b0d8f84a7396293016e4254b | [
"Apache-2.0"
] | 1 | 2021-06-15T06:15:24.000Z | 2021-06-15T06:15:24.000Z | #include "TextureVertex.h"
//---------------------------------------------------------------------------------------------------------------------
const VkVertexInputBindingDescription* TextureVertex::GetBindingDescription() {
static VkVertexInputBindingDescription bindingDescription = {
0, sizeof(TextureVertex), VK_VERTEX_INPUT_RATE_VERTEX
};
return &bindingDescription;
}
//---------------------------------------------------------------------------------------------------------------------
const std::vector<VkVertexInputAttributeDescription>* TextureVertex::GetAttributeDescriptions() {
static std::vector<VkVertexInputAttributeDescription> attributeDescriptions{
{ 0, 0, VK_FORMAT_R32G32_SFLOAT, offsetof(TextureVertex, Pos) },
{ 1, 0, VK_FORMAT_R32G32B32_SFLOAT, offsetof(TextureVertex, Color) },
{ 2, 0, VK_FORMAT_R32G32_SFLOAT, offsetof(TextureVertex, TexCoord) },
};
return &attributeDescriptions;
}
| 39.28 | 119 | 0.564155 | sindharta |
22c7cbbf15e6ff0d998153c996df2a85b8060ed5 | 2,202 | cpp | C++ | source/parser/interp.cpp | zhiayang/peirce-alpha | 49931a234ba173ed7ea4bdcca9949f28d64d7b4f | [
"Apache-2.0"
] | 1 | 2021-05-03T22:51:13.000Z | 2021-05-03T22:51:13.000Z | source/parser/interp.cpp | zhiayang/peirce-alpha | 49931a234ba173ed7ea4bdcca9949f28d64d7b4f | [
"Apache-2.0"
] | 1 | 2021-05-03T22:52:59.000Z | 2021-05-10T15:31:26.000Z | source/parser/interp.cpp | zhiayang/peirce-alpha | 49931a234ba173ed7ea4bdcca9949f28d64d7b4f | [
"Apache-2.0"
] | null | null | null | // interp.cpp
// Copyright (c) 2021, zhiayang
// Licensed under the Apache License Version 2.0.
#include "ast.h"
namespace ast
{
Expr* Var::evaluate(const std::unordered_map<std::string, bool>& syms) const
{
if(auto it = syms.find(this->name); it != syms.end())
return new Lit(it->second);
return new Var(this->name);
}
Expr* Lit::evaluate(const std::unordered_map<std::string, bool>& syms) const
{
return new Lit(this->value);
}
Expr* Not::evaluate(const std::unordered_map<std::string, bool>& syms) const
{
auto ee = this->e->evaluate(syms);
if(auto elit = dynamic_cast<Lit*>(ee); elit != nullptr)
{
auto v = elit->value;
delete ee;
return new Lit(!v);
}
// check if the inside is a not -- eliminate the double negation
if(auto enot = dynamic_cast<Not*>(ee); enot)
return enot->e;
return new Not(ee);
}
Expr* And::evaluate(const std::unordered_map<std::string, bool>& syms) const
{
auto ll = this->left->evaluate(syms);
if(auto llit = dynamic_cast<Lit*>(ll); llit != nullptr)
{
if(llit->value)
{
delete ll;
return this->right->evaluate(syms);
}
else
{
return new Lit(false);
}
}
auto rr = this->right->evaluate(syms);
if(auto rlit = dynamic_cast<Lit*>(rr); rlit != nullptr)
{
if(rlit->value)
{
delete rr;
return ll;
}
else
{
delete ll;
return new Lit(false);
}
}
return new And(ll, rr);
}
// these 3 don't need to be evaluated, since we'll use transform()
// to reduce everything to ands and nots.
Expr* Or::evaluate(const std::unordered_map<std::string, bool>& syms) const
{
return nullptr;
}
Expr* Implies::evaluate(const std::unordered_map<std::string, bool>& syms) const
{
return nullptr;
}
Expr* BidirImplies::evaluate(const std::unordered_map<std::string, bool>& syms) const
{
return nullptr;
}
Expr::~Expr() { }
Var::~Var() { }
Lit::~Lit() { }
And::~And() { delete this->left; delete this->right; }
Not::~Not() { delete this->e; }
Or::~Or() { delete this->left; delete this->right; }
Implies::~Implies() { delete this->left; delete this->right; }
BidirImplies::~BidirImplies() { delete this->left; delete this->right; }
}
| 22.02 | 86 | 0.631698 | zhiayang |
22c857a309705824486a47aba5a2571c3bc1f99d | 748 | cpp | C++ | Algorithms/LC/cpp/0520 Detect Capital/LC0520.cpp | tjzhym/LeetCode-solution | 06bd35bae619caaf8153b81849dae9dcc7bc9491 | [
"MIT"
] | null | null | null | Algorithms/LC/cpp/0520 Detect Capital/LC0520.cpp | tjzhym/LeetCode-solution | 06bd35bae619caaf8153b81849dae9dcc7bc9491 | [
"MIT"
] | null | null | null | Algorithms/LC/cpp/0520 Detect Capital/LC0520.cpp | tjzhym/LeetCode-solution | 06bd35bae619caaf8153b81849dae9dcc7bc9491 | [
"MIT"
] | null | null | null | // Problem : https://leetcode.com/problems/detect-capital/
// Solution: https://github.com/tjzhym/LeetCode-solution
// Author : zhym (tjzhym)
// Date : 2021-11-13
#include <string>
using namespace std;
class Solution {
public:
bool detectCapitalUse(string word) {
if (islower(word[0]) && word.size() > 1 && isupper(word[1])) {
return false;
}
int isCapital = 0; // isupper function return int
if (word.size() > 2) {
isCapital = isupper(word[1]);
}
for (int index = 2; index < word.size(); ++index) {
if (isupper(word[index]) != isCapital) {
return false;
}
}
return true;
}
};
// Traverse | 22.666667 | 70 | 0.529412 | tjzhym |
22d1eb53c0a65998647ccedf5f8eed35fadb14c4 | 10,789 | hpp | C++ | src/Evolution/Systems/Cce/OptionTags.hpp | desperadoshi/spectre | b61c12dce108a98a875a1e9476e5630bea634119 | [
"MIT"
] | null | null | null | src/Evolution/Systems/Cce/OptionTags.hpp | desperadoshi/spectre | b61c12dce108a98a875a1e9476e5630bea634119 | [
"MIT"
] | null | null | null | src/Evolution/Systems/Cce/OptionTags.hpp | desperadoshi/spectre | b61c12dce108a98a875a1e9476e5630bea634119 | [
"MIT"
] | null | null | null | // Distributed under the MIT License.
// See LICENSE.txt for details.
#pragma once
#include <cstddef>
#include <limits>
#include "DataStructures/DataBox/Tag.hpp"
#include "Evolution/Systems/Cce/Initialize/InitializeJ.hpp"
#include "Evolution/Systems/Cce/InterfaceManagers/GhInterfaceManager.hpp"
#include "Evolution/Systems/Cce/InterfaceManagers/GhLockstep.hpp"
#include "Evolution/Systems/Cce/ReadBoundaryDataH5.hpp"
#include "NumericalAlgorithms/Interpolation/SpanInterpolator.hpp"
#include "Options/Options.hpp"
namespace Cce {
namespace OptionTags {
/// %Option group
struct Cce {
static constexpr OptionString help = {"Options for the Cce evolution system"};
};
/// %Option group
struct Filtering {
static constexpr OptionString help = {"Options for the filtering in Cce"};
using group = Cce;
};
struct LMax {
using type = size_t;
static constexpr OptionString help{
"Maximum l value for spin-weighted spherical harmonics"};
using group = Cce;
};
struct FilterLMax {
using type = size_t;
static constexpr OptionString help{"l mode cutoff for angular filtering"};
using group = Filtering;
};
struct RadialFilterAlpha {
using type = double;
static constexpr OptionString help{
"alpha parameter in exponential radial filter"};
using group = Filtering;
};
struct RadialFilterHalfPower {
using type = size_t;
static constexpr OptionString help{
"Half-power of the exponential radial filter argument"};
using group = Filtering;
};
struct ObservationLMax {
using type = size_t;
static constexpr OptionString help{"Maximum l value for swsh output"};
using group = Cce;
};
struct NumberOfRadialPoints {
using type = size_t;
static constexpr OptionString help{
"Number of radial grid points in the spherical domain"};
using group = Cce;
};
struct ExtractionRadius {
using type = double;
static constexpr OptionString help{"Extraction radius from the GH system."};
using group = Cce;
};
struct EndTime {
using type = double;
static constexpr OptionString help{"End time for the Cce Evolution."};
static double default_value() noexcept {
return std::numeric_limits<double>::infinity();
}
using group = Cce;
};
struct StartTime {
using type = double;
static constexpr OptionString help{
"Cce Start time (default to earliest possible time)."};
static double default_value() noexcept {
return -std::numeric_limits<double>::infinity();
}
using group = Cce;
};
struct TargetStepSize {
using type = double;
static constexpr OptionString help{"Target time step size for Cce Evolution"};
using group = Cce;
};
struct BoundaryDataFilename {
using type = std::string;
static constexpr OptionString help{
"H5 file to read the wordltube data from."};
using group = Cce;
};
struct H5LookaheadTimes {
using type = size_t;
static constexpr OptionString help{
"Number of times steps from the h5 to cache each read."};
static size_t default_value() noexcept { return 200; }
using group = Cce;
};
struct H5Interpolator {
using type = std::unique_ptr<intrp::SpanInterpolator>;
static constexpr OptionString help{
"The interpolator for imported h5 worldtube data."};
using group = Cce;
};
struct GhInterfaceManager {
using type = std::unique_ptr<InterfaceManagers::GhInterfaceManager>;
static constexpr OptionString help{
"Class to manage worldtube data from a GH system."};
using group = Cce;
};
struct ScriInterpolationOrder {
static std::string name() noexcept { return "ScriInterpOrder"; }
using type = size_t;
static constexpr OptionString help{"Order of time interpolation at scri+."};
static size_t default_value() noexcept { return 5; }
using group = Cce;
};
struct ScriOutputDensity {
using type = size_t;
static constexpr OptionString help{
"Number of scri output points per timestep."};
static size_t default_value() noexcept { return 1; }
using group = Cce;
};
struct InitializeJ {
using type = std::unique_ptr<::Cce::InitializeJ::InitializeJ>;
static constexpr OptionString help{
"The initialization for the first hypersurface for J"};
using group = Cce;
};
} // namespace OptionTags
namespace InitializationTags {
/// An initialization tag that constructs a `WorldtubeDataManager` from options
struct H5WorldtubeBoundaryDataManager : db::SimpleTag {
using type = WorldtubeDataManager;
using option_tags =
tmpl::list<OptionTags::LMax, OptionTags::BoundaryDataFilename,
OptionTags::H5LookaheadTimes, OptionTags::H5Interpolator>;
static constexpr bool pass_metavariables = false;
static WorldtubeDataManager create_from_options(
const size_t l_max, const std::string& filename,
const size_t number_of_lookahead_times,
const std::unique_ptr<intrp::SpanInterpolator>& interpolator) noexcept {
return WorldtubeDataManager{
std::make_unique<SpecWorldtubeH5BufferUpdater>(filename), l_max,
number_of_lookahead_times, interpolator->get_clone()};
}
};
struct ScriInterpolationOrder : db::SimpleTag {
using type = size_t;
using option_tags = tmpl::list<OptionTags::ScriInterpolationOrder>;
static constexpr bool pass_metavariables = false;
static size_t create_from_options(
const size_t scri_plus_interpolation_order) noexcept {
return scri_plus_interpolation_order;
}
};
struct TargetStepSize : db::SimpleTag {
using type = double;
using option_tags = tmpl::list<OptionTags::TargetStepSize>;
static constexpr bool pass_metavariables = false;
static double create_from_options(const double target_step_size) noexcept {
return target_step_size;
}
};
struct ExtractionRadius : db::SimpleTag {
using type = double;
using option_tags = tmpl::list<OptionTags::ExtractionRadius>;
template <typename Metavariables>
static double create_from_options(const double extraction_radius) noexcept {
return extraction_radius;
}
};
struct ScriOutputDensity : db::SimpleTag {
using type = size_t;
using option_tags = tmpl::list<OptionTags::ScriOutputDensity>;
static constexpr bool pass_metavariables = false;
static size_t create_from_options(const size_t scri_output_density) noexcept {
return scri_output_density;
}
};
} // namespace InitializationTags
namespace Tags {
struct LMax : db::SimpleTag, Spectral::Swsh::Tags::LMaxBase {
using type = size_t;
using option_tags = tmpl::list<OptionTags::LMax>;
static constexpr bool pass_metavariables = false;
static size_t create_from_options(const size_t l_max) noexcept {
return l_max;
}
};
struct NumberOfRadialPoints : db::SimpleTag,
Spectral::Swsh::Tags::NumberOfRadialPointsBase {
using type = size_t;
using option_tags = tmpl::list<OptionTags::NumberOfRadialPoints>;
static constexpr bool pass_metavariables = false;
static size_t create_from_options(
const size_t number_of_radial_points) noexcept {
return number_of_radial_points;
}
};
struct ObservationLMax : db::SimpleTag {
using type = size_t;
using option_tags = tmpl::list<OptionTags::ObservationLMax>;
static constexpr bool pass_metavariables = false;
static size_t create_from_options(const size_t observation_l_max) noexcept {
return observation_l_max;
}
};
struct FilterLMax : db::SimpleTag {
using type = size_t;
using option_tags = tmpl::list<OptionTags::FilterLMax>;
static constexpr bool pass_metavariables = false;
static size_t create_from_options(const size_t filter_l_max) noexcept {
return filter_l_max;
}
};
struct RadialFilterAlpha : db::SimpleTag {
using type = double;
using option_tags = tmpl::list<OptionTags::RadialFilterAlpha>;
static constexpr bool pass_metavariables = false;
static double create_from_options(const double radial_filter_alpha) noexcept {
return radial_filter_alpha;
}
};
struct RadialFilterHalfPower : db::SimpleTag {
using type = size_t;
using option_tags = tmpl::list<OptionTags::RadialFilterHalfPower>;
static constexpr bool pass_metavariables = false;
static size_t create_from_options(
const size_t radial_filter_half_power) noexcept {
return radial_filter_half_power;
}
};
struct StartTime : db::SimpleTag {
using type = double;
using option_tags =
tmpl::list<OptionTags::StartTime, OptionTags::BoundaryDataFilename>;
static constexpr bool pass_metavariables = false;
static double create_from_options(double start_time,
const std::string& filename) noexcept {
if (start_time == -std::numeric_limits<double>::infinity()) {
SpecWorldtubeH5BufferUpdater h5_boundary_updater{filename};
const auto& time_buffer = h5_boundary_updater.get_time_buffer();
start_time = time_buffer[0];
}
return start_time;
}
};
/// \brief Represents the final time of a bounded CCE evolution, determined
/// either from option specification or from the file
///
/// \details If the option `OptionTags::EndTime` is set to
/// `std::numeric_limits<double>::%infinity()`, this will find the end time from
/// the provided H5 file. If `OptionTags::EndTime` takes any other value, it
/// will be used directly as the end time for the CCE evolution instead.
struct EndTime : db::SimpleTag {
using type = double;
using option_tags =
tmpl::list<OptionTags::EndTime, OptionTags::BoundaryDataFilename>;
static constexpr bool pass_metavariables = false;
static double create_from_options(double end_time,
const std::string& filename) {
if (end_time == std::numeric_limits<double>::infinity()) {
SpecWorldtubeH5BufferUpdater h5_boundary_updater{filename};
const auto& time_buffer = h5_boundary_updater.get_time_buffer();
end_time = time_buffer[time_buffer.size() - 1];
}
return end_time;
}
};
struct GhInterfaceManager : db::SimpleTag {
using type = std::unique_ptr<InterfaceManagers::GhInterfaceManager>;
using option_tags = tmpl::list<OptionTags::GhInterfaceManager>;
template <typename Metavariables>
static std::unique_ptr<InterfaceManagers::GhInterfaceManager>
create_from_options(
const std::unique_ptr<InterfaceManagers::GhInterfaceManager>&
interface_manager) noexcept {
return interface_manager->get_clone();
}
};
struct InitializeJ : db::SimpleTag {
using type = std::unique_ptr<::Cce::InitializeJ::InitializeJ>;
using option_tags = tmpl::list<OptionTags::InitializeJ>;
static constexpr bool pass_metavariables = false;
static std::unique_ptr<::Cce::InitializeJ::InitializeJ> create_from_options(
const std::unique_ptr<::Cce::InitializeJ::InitializeJ>&
initialize_j) noexcept {
return initialize_j->get_clone();
}
};
} // namespace Tags
} // namespace Cce
| 30.91404 | 80 | 0.736769 | desperadoshi |
22d2f10d921c9f1cd7ca1c6742ea221a46a9fb3d | 2,809 | cc | C++ | graph-tool-2.27/src/graph/topology/graph_similarity.cc | Znigneering/CSCI-3154 | bc318efc73d2a80025b98f5b3e4f7e4819e952e4 | [
"MIT"
] | null | null | null | graph-tool-2.27/src/graph/topology/graph_similarity.cc | Znigneering/CSCI-3154 | bc318efc73d2a80025b98f5b3e4f7e4819e952e4 | [
"MIT"
] | null | null | null | graph-tool-2.27/src/graph/topology/graph_similarity.cc | Znigneering/CSCI-3154 | bc318efc73d2a80025b98f5b3e4f7e4819e952e4 | [
"MIT"
] | null | null | null | // graph-tool -- a general graph modification and manipulation thingy
//
// Copyright (C) 2006-2018 Tiago de Paula Peixoto <[email protected]>
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#include "graph_python_interface.hh"
#include "graph.hh"
#include "graph_filtering.hh"
#include "graph_properties.hh"
#include "graph_selectors.hh"
#include "graph_similarity.hh"
using namespace std;
using namespace boost;
using namespace graph_tool;
template <class Type, class Index>
auto uncheck(boost::unchecked_vector_property_map<Type,Index>, boost::any p)
{
return boost::any_cast<boost::checked_vector_property_map<Type,Index>>(p).get_unchecked();
}
template <class T>
auto&& uncheck(T&&, boost::any p)
{
return boost::any_cast<T>(p);
}
typedef UnityPropertyMap<size_t,GraphInterface::edge_t> ecmap_t;
typedef boost::mpl::push_back<edge_scalar_properties, ecmap_t>::type
weight_props_t;
python::object similarity(GraphInterface& gi1, GraphInterface& gi2,
boost::any weight1, boost::any weight2,
boost::any label1, boost::any label2, double norm,
bool asym)
{
if (weight1.empty())
weight1 = ecmap_t();
if (weight2.empty())
weight2 = ecmap_t();
python::object s;
gt_dispatch<>()
([&](const auto& g1, const auto& g2, auto ew1, auto l1)
{
auto l2 = uncheck(l1, label2);
auto ew2 = uncheck(ew1, weight2);
auto ret = get_similarity(g1, g2, ew1, ew2, l1, l2, asym, norm);
s = python::object(ret);
},
all_graph_views(),
all_graph_views(),
weight_props_t(),
vertex_scalar_properties())
(gi1.get_graph_view(), gi2.get_graph_view(), weight1, label1);
return s;
}
python::object similarity_fast(GraphInterface& gi1, GraphInterface& gi2,
boost::any weight1, boost::any weight2,
boost::any label1, boost::any label2,
double norm, bool asym);
void export_similarity()
{
python::def("similarity", &similarity);
python::def("similarity_fast", &similarity_fast);
};
| 33.440476 | 94 | 0.655037 | Znigneering |
22d39c9953c594931b7016a1f9ca7edcfb004c79 | 717 | cpp | C++ | cc150/2.1.cpp | WIZARD-CXY/pl | 22b7f5d81804f4e333d3cff6433364ba1a0ac7ef | [
"Apache-2.0"
] | 1 | 2016-01-20T08:26:34.000Z | 2016-01-20T08:26:34.000Z | cc150/2.1.cpp | WIZARD-CXY/pl | 22b7f5d81804f4e333d3cff6433364ba1a0ac7ef | [
"Apache-2.0"
] | 1 | 2015-10-21T05:38:17.000Z | 2015-11-02T07:42:55.000Z | cc150/2.1.cpp | WIZARD-CXY/pl | 22b7f5d81804f4e333d3cff6433364ba1a0ac7ef | [
"Apache-2.0"
] | null | null | null | #include <iostream>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int v):val(v),next(NULL){}
};
void deleteDup(ListNode *head){
if(head==NULL){
return;
}
ListNode *cur=head;
while(cur){
ListNode *run=cur;
while(run->next){
if(run->next->val==cur->val){
//delete run->next;
ListNode *temp=run->next;
run->next=run->next->next;
delete temp;
}else{
run=run->next;
}
}
cur=cur->next;
}
}
int main(){
ListNode *a= new ListNode(1);
a->next= new ListNode(2);
a->next->next= new ListNode(1);
a->next->next->next= new ListNode(2);
a->next->next->next->next= new ListNode(1);
deleteDup(a);
while(a){
cout<<a->val<<endl;
a=a->next;
}
} | 15.586957 | 44 | 0.6053 | WIZARD-CXY |
22d70eeca2ffd57dcd8d43633cb8f6a6d6b810d7 | 1,604 | cpp | C++ | Applied/CCore/src/AbstFileToMem.cpp | SergeyStrukov/CCore-4-xx | 5faeadd50a24a7dbe18ffff8efe5f49212588637 | [
"BSL-1.0"
] | null | null | null | Applied/CCore/src/AbstFileToMem.cpp | SergeyStrukov/CCore-4-xx | 5faeadd50a24a7dbe18ffff8efe5f49212588637 | [
"BSL-1.0"
] | null | null | null | Applied/CCore/src/AbstFileToMem.cpp | SergeyStrukov/CCore-4-xx | 5faeadd50a24a7dbe18ffff8efe5f49212588637 | [
"BSL-1.0"
] | null | null | null | /* AbstFileToMem.cpp */
//----------------------------------------------------------------------------------------
//
// Project: CCore 4.01
//
// Tag: Applied
//
// License: Boost Software License - Version 1.0 - August 17th, 2003
//
// see http://www.boost.org/LICENSE_1_0.txt or the local copy
//
// Copyright (c) 2020 Sergey Strukov. All rights reserved.
//
//----------------------------------------------------------------------------------------
#include <CCore/inc/AbstFileToMem.h>
#include <CCore/inc/Exception.h>
namespace CCore {
/* class AbstFileToMem */
AbstFileToMem::AbstFileToMem(AbstFileToRead file,StrLen file_name,ulen max_len)
{
file->open(file_name);
ScopeGuard guard( [&] () { file->close(); } );
auto file_len=file->getLen();
if( file_len>max_len )
{
Printf(Exception,"CCore::AbstFileToMem::AbstFileToMem(...,#.q;,max_len=#;) : file is too long #;",file_name,max_len,file_len);
}
ulen len=(ulen)file_len;
file->read_all(0,alloc(len),len);
}
/* class PartAbstFileToMem */
PartAbstFileToMem::PartAbstFileToMem(AbstFileToRead file_,StrLen file_name,ulen buf_len)
: file(file_),
buf(buf_len),
off(0)
{
file->open(file_name);
file_len=file->getLen();
}
PartAbstFileToMem::~PartAbstFileToMem()
{
file->close();
}
PtrLen<const uint8> PartAbstFileToMem::pump()
{
uint8 *ptr=buf.getPtr();
ulen len=buf.getLen();
FilePosType delta=file_len-off;
if( !delta ) return Empty;
if( delta<len ) len=(ulen)delta;
file->read_all(off,ptr,len);
off+=len;
return Range(ptr,len);
}
} // namespace CCore
| 20.303797 | 131 | 0.591022 | SergeyStrukov |
22d9b729ef4dbfb5a190fb699a03d6e75c3bf331 | 131 | hxx | C++ | src/Providers/UNIXProviders/RangeOfIPAddresses/UNIX_RangeOfIPAddresses_STUB.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | 1 | 2020-10-12T09:00:09.000Z | 2020-10-12T09:00:09.000Z | src/Providers/UNIXProviders/RangeOfIPAddresses/UNIX_RangeOfIPAddresses_STUB.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | null | null | null | src/Providers/UNIXProviders/RangeOfIPAddresses/UNIX_RangeOfIPAddresses_STUB.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | null | null | null | #ifdef PEGASUS_OS_STUB
#ifndef __UNIX_RANGEOFIPADDRESSES_PRIVATE_H
#define __UNIX_RANGEOFIPADDRESSES_PRIVATE_H
#endif
#endif
| 10.916667 | 43 | 0.854962 | brunolauze |
22dd38870431ad1cab052d3fa095b8f60f7aaf24 | 480 | cpp | C++ | URI/2143-the-return-of-radar.cpp | SusmoySenGupta/online-judge-solutions | 8735a1bc71a05dc46255664c3ec6f47f042bfa6c | [
"MIT"
] | null | null | null | URI/2143-the-return-of-radar.cpp | SusmoySenGupta/online-judge-solutions | 8735a1bc71a05dc46255664c3ec6f47f042bfa6c | [
"MIT"
] | null | null | null | URI/2143-the-return-of-radar.cpp | SusmoySenGupta/online-judge-solutions | 8735a1bc71a05dc46255664c3ec6f47f042bfa6c | [
"MIT"
] | null | null | null | /*
problem no: 2143
problem name: The Return of Radar
problem link: https://www.urionlinejudge.com.br/judge/en/problems/view/2143
author: Susmoy Sen Gupta
Status: __Solved__
Solved at: 6/24/21, 12:35:28 AM
*/
#include <iostream>
using namespace std;
int main()
{
int t, x;
while(1)
{
cin >> t;
if(t == 0) break;
while(t--)
{
cin >> x;
x % 2 == 0 ? cout << (x * 2) - 2 : cout << (x*2) - 1;
cout << endl;
}
}
return 0;
}
| 12.631579 | 76 | 0.547917 | SusmoySenGupta |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.