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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
83601c01f2b2ad2f336a61e9a1f658cfbb6aa0b5
| 2,932
|
cpp
|
C++
|
src/Widgets/MenuLabelLayer.cpp
|
huntermalm/Layers
|
1f2f6eabe3be8dfbc60d682ca47543f7807a0bbf
|
[
"MIT"
] | null | null | null |
src/Widgets/MenuLabelLayer.cpp
|
huntermalm/Layers
|
1f2f6eabe3be8dfbc60d682ca47543f7807a0bbf
|
[
"MIT"
] | null | null | null |
src/Widgets/MenuLabelLayer.cpp
|
huntermalm/Layers
|
1f2f6eabe3be8dfbc60d682ca47543f7807a0bbf
|
[
"MIT"
] | null | null | null |
#include "../../include/AttributeWidgets.h"
#include "../../include/MenuLabelLayer.h"
using Layers::Button;
using Layers::Label;
using Layers::Menu;
using Layers::MenuLabelLayer;
MenuLabelLayer::MenuLabelLayer(Menu* menu, QWidget* parent) :
m_icon_button{ new Button(new Graphic(*menu->icon), false) },
m_text_label{ new Label(menu->name) },
Widget(parent)
{
init_attributes();
init_child_themeable_reference_list();
set_name("menu_label_layer");
set_icon(new Graphic(":/svgs/mll_icon.svg", QSize(20, 6)));
m_back_button->set_name("back_button");
m_back_button->set_proper_name("Back Button");
m_back_button->set_padding(11, 13, 6, 14);
m_icon_button->set_name("icon_button");
m_icon_button->set_proper_name("Menu Icon");
m_icon_button->set_padding(6, 11, 11, 11);
m_icon_button->disable_graphic_hover_color();
m_text_label->setAttribute(Qt::WA_TransparentForMouseEvents);
m_text_label->set_name("text_label");
m_text_label->set_proper_name("Text Label");
m_text_label->set_font_size(16);
m_text_label->set_padding(0, 8, 0, 0);
m_stretch_widget->setAttribute(Qt::WA_TransparentForMouseEvents);
setup_layout();
}
void MenuLabelLayer::init_attributes()
{
a_fill.set_value(QColor("#e6e6e6"));
a_corner_radius_tl.set_value(10);
a_corner_radius_tr.set_value(10);
a_corner_radius_bl.set_value(10);
a_corner_radius_br.set_value(10);
m_stretch_widget->a_fill.set_disabled();
}
void MenuLabelLayer::init_child_themeable_reference_list()
{
add_child_themeable_reference(m_back_button);
add_child_themeable_reference(m_icon_button);
add_child_themeable_reference(m_text_label);
}
void MenuLabelLayer::replace_all_attributes_with(MenuLabelLayer* mll)
{
Widget::replace_all_attributes_with(mll);
if (m_back_button) m_back_button->replace_all_attributes_with(mll->m_back_button);
if (m_icon_button) m_icon_button->replace_all_attributes_with(mll->m_icon_button);
if (m_text_label) m_text_label->replace_all_attributes_with(mll->m_text_label);
}
void MenuLabelLayer::shrink()
{
m_back_button->hide();
m_text_label->hide();
m_icon_button->set_padding(21, 11, 21, 11);
m_stretch_widget->hide();
setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum);
}
void MenuLabelLayer::expand()
{
m_back_button->show();
m_text_label->show();
m_icon_button->set_padding(6, 11, 11, 11);
m_stretch_widget->show();
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
}
Button* MenuLabelLayer::back_button() const
{
return m_back_button;
}
Button* MenuLabelLayer::icon_button() const
{
return m_icon_button;
}
Label* MenuLabelLayer::text_label() const
{
return m_text_label;
}
void MenuLabelLayer::setup_layout()
{
main_layout->setContentsMargins(0, 0, 0, 0);
main_layout->setSpacing(0);
main_layout->addWidget(m_back_button);
main_layout->addWidget(m_icon_button);
main_layout->addWidget(m_text_label);
main_layout->addWidget(m_stretch_widget);
setLayout(main_layout);
}
| 25.059829
| 83
| 0.778308
|
huntermalm
|
8361d646c42d5cba23f5149221933b967d7fa604
| 765
|
hpp
|
C++
|
swizzle/ast/nodes/DefaultStringValue.hpp
|
SenorAgosto/Swizzle
|
52c221de9fa293b0006f07a41b140d2afcc1a9ed
|
[
"BSD-4-Clause"
] | null | null | null |
swizzle/ast/nodes/DefaultStringValue.hpp
|
SenorAgosto/Swizzle
|
52c221de9fa293b0006f07a41b140d2afcc1a9ed
|
[
"BSD-4-Clause"
] | null | null | null |
swizzle/ast/nodes/DefaultStringValue.hpp
|
SenorAgosto/Swizzle
|
52c221de9fa293b0006f07a41b140d2afcc1a9ed
|
[
"BSD-4-Clause"
] | null | null | null |
#pragma once
#include <swizzle/ast/Node.hpp>
#include <swizzle/lexer/TokenInfo.hpp>
#include <cstddef>
#include <string>
namespace swizzle { namespace ast {
class VisitorInterface;
}}
namespace swizzle { namespace ast { namespace nodes {
class DefaultStringValue : public Node
{
public:
DefaultStringValue(const lexer::TokenInfo& value, const std::string& underlyingType, const std::ptrdiff_t length);
const lexer::TokenInfo& value() const;
const std::string& underlying() const;
std::ptrdiff_t length() const;
void accept(VisitorInterface& visitor) override;
private:
const lexer::TokenInfo value_;
const std::string underlying_;
const std::ptrdiff_t length_;
};
}}}
| 23.90625
| 122
| 0.677124
|
SenorAgosto
|
836cea669f660d9e2cd9553b4da0e0f5715a5af3
| 638
|
cpp
|
C++
|
347-top-k-frequent-elements/347-top-k-frequent-elements.cpp
|
champmaniac/LeetCode
|
65810e0123e0ceaefb76d0a223436d1525dac0d4
|
[
"MIT"
] | 1
|
2022-02-27T09:01:07.000Z
|
2022-02-27T09:01:07.000Z
|
347-top-k-frequent-elements/347-top-k-frequent-elements.cpp
|
champmaniac/LeetCode
|
65810e0123e0ceaefb76d0a223436d1525dac0d4
|
[
"MIT"
] | null | null | null |
347-top-k-frequent-elements/347-top-k-frequent-elements.cpp
|
champmaniac/LeetCode
|
65810e0123e0ceaefb76d0a223436d1525dac0d4
|
[
"MIT"
] | null | null | null |
class Solution { // TC O(n)
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int,int> mp;
int n = nums.size();
for(int i=0;i<n;i++){
mp[nums[i]]++;
}
vector<vector<int>> buckets(n);
for(auto it = mp.begin();it!=mp.end();it++){
buckets[it->second-1].push_back(it->first);
}
vector<int> sorted;
for(int i=0;i<n;i++){
sorted.insert(sorted.end(),buckets[i].begin(),buckets[i].end());
}
vector<int> ans(sorted.rbegin(),sorted.rbegin()+k);
return ans;
}
};
| 31.9
| 76
| 0.484326
|
champmaniac
|
836ec9798f6f8c8f2658f67f1a524c7a17cf03a0
| 33,287
|
cc
|
C++
|
src/rocblas_wrappers.cc
|
G-Ragghianti/blaspp
|
7650db32e9fc4c69bd10388c2dee8865cfcfa36f
|
[
"BSD-3-Clause"
] | null | null | null |
src/rocblas_wrappers.cc
|
G-Ragghianti/blaspp
|
7650db32e9fc4c69bd10388c2dee8865cfcfa36f
|
[
"BSD-3-Clause"
] | null | null | null |
src/rocblas_wrappers.cc
|
G-Ragghianti/blaspp
|
7650db32e9fc4c69bd10388c2dee8865cfcfa36f
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright (c) 2017-2021, University of Tennessee. All rights reserved.
// SPDX-License-Identifier: BSD-3-Clause
// This program is free software: you can redistribute it and/or modify it under
// the terms of the BSD 3-Clause license. See the accompanying LICENSE file.
#include "blas/device.hh"
#ifdef BLAS_HAVE_ROCBLAS
#ifdef __HIP_PLATFORM_NVCC__
#warning Compiling with rocBLAS on NVCC mode... This is an odd configuration. (Consider using NVCC only)
#endif
namespace blas {
namespace device {
// -----------------------------------------------------------------------------
/// @return the corresponding device trans constant
rocblas_operation op2rocblas(blas::Op trans)
{
switch (trans) {
case Op::NoTrans: return rocblas_operation_none; break;
case Op::Trans: return rocblas_operation_transpose; break;
case Op::ConjTrans: return rocblas_operation_conjugate_transpose; break;
default: throw blas::Error( "unknown op" );
}
}
// -----------------------------------------------------------------------------
/// @return the corresponding device diag constant
rocblas_diagonal diag2rocblas(blas::Diag diag)
{
switch (diag) {
case Diag::Unit: return rocblas_diagonal_unit; break;
case Diag::NonUnit: return rocblas_diagonal_non_unit; break;
default: throw blas::Error( "unknown diag" );
}
}
// -----------------------------------------------------------------------------
/// @return the corresponding device uplo constant
rocblas_fill uplo2rocblas(blas::Uplo uplo)
{
switch (uplo) {
case Uplo::Upper: return rocblas_fill_upper; break;
case Uplo::Lower: return rocblas_fill_lower; break;
case Uplo::General: return rocblas_fill_full; break;
default: throw blas::Error( "unknown uplo" );
}
}
// -----------------------------------------------------------------------------
/// @return the corresponding device side constant
rocblas_side side2rocblas(blas::Side side)
{
switch (side) {
case Side::Left: return rocblas_side_left; break;
case Side::Right: return rocblas_side_right; break;
default: throw blas::Error( "unknown side" );
}
}
// =============================================================================
// Level 1 BLAS - Device Interfaces
// -----------------------------------------------------------------------------
// swap
// -----------------------------------------------------------------------------
// sswap
void sswap(
blas::Queue& queue,
device_blas_int n,
float *dx, device_blas_int incdx,
float *dy, device_blas_int incdy)
{
blas_dev_call(
rocblas_sswap(
queue.handle(),
n,
dx, incdx,
dy, incdy) );
}
// -----------------------------------------------------------------------------
// dswap
void dswap(
blas::Queue& queue,
device_blas_int n,
double *dx, device_blas_int incdx,
double *dy, device_blas_int incdy)
{
blas_dev_call(
rocblas_dswap(
queue.handle(),
n,
dx, incdx,
dy, incdy) );
}
// -----------------------------------------------------------------------------
// cswap
void cswap(
blas::Queue& queue,
device_blas_int n,
std::complex<float> *dx, device_blas_int incdx,
std::complex<float> *dy, device_blas_int incdy)
{
blas_dev_call(
rocblas_cswap(
queue.handle(),
n,
(rocblas_float_complex*) dx, incdx,
(rocblas_float_complex*) dy, incdy) );
}
// -----------------------------------------------------------------------------
// zswap
void zswap(
blas::Queue& queue,
device_blas_int n,
std::complex<double> *dx, device_blas_int incdx,
std::complex<double> *dy, device_blas_int incdy)
{
blas_dev_call(
rocblas_zswap(
queue.handle(),
n,
(rocblas_double_complex*) dx, incdx,
(rocblas_double_complex*) dy, incdy) );
}
// =============================================================================
// Level 2 BLAS - Device Interfaces
// -----------------------------------------------------------------------------
// =============================================================================
// Level 3 BLAS - Device Interfaces
// -----------------------------------------------------------------------------
// gemm
// -----------------------------------------------------------------------------
// sgemm
void sgemm(
blas::Queue& queue,
blas::Op transA, blas::Op transB,
device_blas_int m, device_blas_int n, device_blas_int k,
float alpha,
float const *dA, device_blas_int ldda,
float const *dB, device_blas_int lddb,
float beta,
float *dC, device_blas_int lddc)
{
blas_dev_call(
rocblas_sgemm(
queue.handle(),
op2rocblas(transA), op2rocblas(transB),
m, n, k,
&alpha, dA, ldda,
dB, lddb,
&beta, dC, lddc ) );
}
// -----------------------------------------------------------------------------
// dgemm
void dgemm(
blas::Queue& queue,
blas::Op transA, blas::Op transB,
device_blas_int m, device_blas_int n, device_blas_int k,
double alpha,
double const *dA, device_blas_int ldda,
double const *dB, device_blas_int lddb,
double beta,
double *dC, device_blas_int lddc)
{
blas_dev_call(
rocblas_dgemm(
queue.handle(),
op2rocblas(transA), op2rocblas(transB),
m, n, k,
&alpha, dA, ldda,
dB, lddb,
&beta, dC, lddc ) );
}
// -----------------------------------------------------------------------------
// cgemm
void cgemm(
blas::Queue& queue,
blas::Op transA, blas::Op transB,
device_blas_int m, device_blas_int n, device_blas_int k,
std::complex<float> alpha,
std::complex<float> const *dA, device_blas_int ldda,
std::complex<float> const *dB, device_blas_int lddb,
std::complex<float> beta,
std::complex<float> *dC, device_blas_int lddc)
{
blas_dev_call(
rocblas_cgemm(
queue.handle(),
op2rocblas(transA), op2rocblas(transB),
m, n, k,
(rocblas_float_complex*) &alpha,
(rocblas_float_complex*) dA, ldda,
(rocblas_float_complex*) dB, lddb,
(rocblas_float_complex*) &beta,
(rocblas_float_complex*) dC, lddc ) );
}
// -----------------------------------------------------------------------------
// zgemm
void zgemm(
blas::Queue& queue,
blas::Op transA, blas::Op transB,
device_blas_int m, device_blas_int n, device_blas_int k,
std::complex<double> alpha,
std::complex<double> const *dA, device_blas_int ldda,
std::complex<double> const *dB, device_blas_int lddb,
std::complex<double> beta,
std::complex<double> *dC, device_blas_int lddc)
{
blas_dev_call(
rocblas_zgemm(
queue.handle(),
op2rocblas(transA), op2rocblas(transB),
m, n, k,
(rocblas_double_complex*) &alpha,
(rocblas_double_complex*) dA, ldda,
(rocblas_double_complex*) dB, lddb,
(rocblas_double_complex*) &beta,
(rocblas_double_complex*) dC, lddc ) );
}
// -----------------------------------------------------------------------------
// trsm
// -----------------------------------------------------------------------------
// strsm
void strsm(
blas::Queue& queue,
blas::Side side, blas::Uplo uplo, blas::Op trans, blas::Diag diag,
device_blas_int m, device_blas_int n,
float alpha,
float const *dA, device_blas_int ldda,
float *dB, device_blas_int lddb)
{
blas_dev_call(
rocblas_strsm(
queue.handle(),
side2rocblas(side), uplo2rocblas(uplo), op2rocblas(trans), diag2rocblas(diag),
m, n,
&alpha,
dA, ldda,
dB, lddb ) );
}
// -----------------------------------------------------------------------------
// dtrsm
void dtrsm(
blas::Queue& queue,
blas::Side side, blas::Uplo uplo, blas::Op trans, blas::Diag diag,
device_blas_int m, device_blas_int n,
double alpha,
double const *dA, device_blas_int ldda,
double *dB, device_blas_int lddb)
{
blas_dev_call(
rocblas_dtrsm(
queue.handle(),
side2rocblas(side), uplo2rocblas(uplo), op2rocblas(trans), diag2rocblas(diag),
m, n,
&alpha,
dA, ldda,
dB, lddb ) );
}
// -----------------------------------------------------------------------------
// ctrsm
void ctrsm(
blas::Queue& queue,
blas::Side side, blas::Uplo uplo, blas::Op trans, blas::Diag diag,
device_blas_int m, device_blas_int n,
std::complex<float> alpha,
std::complex<float> const *dA, device_blas_int ldda,
std::complex<float> *dB, device_blas_int lddb)
{
blas_dev_call(
rocblas_ctrsm(
queue.handle(),
side2rocblas(side), uplo2rocblas(uplo), op2rocblas(trans), diag2rocblas(diag),
m, n,
(rocblas_float_complex*) &alpha,
(rocblas_float_complex*) dA, ldda,
(rocblas_float_complex*) dB, lddb ) );
}
// -----------------------------------------------------------------------------
// ztrsm
void ztrsm(
blas::Queue& queue,
blas::Side side, blas::Uplo uplo, blas::Op trans, blas::Diag diag,
device_blas_int m, device_blas_int n,
std::complex<double> alpha,
std::complex<double> const *dA, device_blas_int ldda,
std::complex<double> *dB, device_blas_int lddb)
{
blas_dev_call(
rocblas_ztrsm(
queue.handle(),
side2rocblas(side), uplo2rocblas(uplo), op2rocblas(trans), diag2rocblas(diag),
m, n,
(rocblas_double_complex*) &alpha,
(rocblas_double_complex*) dA, ldda,
(rocblas_double_complex*) dB, lddb ) );
}
// -----------------------------------------------------------------------------
// trmm
// -----------------------------------------------------------------------------
// strmm
void strmm(
blas::Queue& queue,
blas::Side side, blas::Uplo uplo, blas::Op trans, blas::Diag diag,
device_blas_int m, device_blas_int n,
float alpha,
float const *dA, device_blas_int ldda,
float *dB, device_blas_int lddb)
{
blas_dev_call(
rocblas_strmm(
queue.handle(),
side2rocblas(side), uplo2rocblas(uplo), op2rocblas(trans), diag2rocblas(diag),
m, n,
&alpha,
dA, ldda,
dB, lddb ) );
}
// -----------------------------------------------------------------------------
// dtrmm
void dtrmm(
blas::Queue& queue,
blas::Side side, blas::Uplo uplo, blas::Op trans, blas::Diag diag,
device_blas_int m, device_blas_int n,
double alpha,
double const *dA, device_blas_int ldda,
double *dB, device_blas_int lddb)
{
blas_dev_call(
rocblas_dtrmm(
queue.handle(),
side2rocblas(side), uplo2rocblas(uplo), op2rocblas(trans), diag2rocblas(diag),
m, n,
&alpha,
dA, ldda,
dB, lddb ) );
}
// -----------------------------------------------------------------------------
// ctrmm
void ctrmm(
blas::Queue& queue,
blas::Side side, blas::Uplo uplo, blas::Op trans, blas::Diag diag,
device_blas_int m, device_blas_int n,
std::complex<float> alpha,
std::complex<float> const *dA, device_blas_int ldda,
std::complex<float> *dB, device_blas_int lddb)
{
blas_dev_call(
rocblas_ctrmm(
queue.handle(),
side2rocblas(side), uplo2rocblas(uplo), op2rocblas(trans), diag2rocblas(diag),
m, n,
(rocblas_float_complex*) &alpha,
(rocblas_float_complex*) dA, ldda,
(rocblas_float_complex*) dB, lddb ) );
}
// -----------------------------------------------------------------------------
// ztrmm
void ztrmm(
blas::Queue& queue,
blas::Side side, blas::Uplo uplo, blas::Op trans, blas::Diag diag,
device_blas_int m, device_blas_int n,
std::complex<double> alpha,
std::complex<double> const *dA, device_blas_int ldda,
std::complex<double> *dB, device_blas_int lddb)
{
blas_dev_call(
rocblas_ztrmm(
queue.handle(),
side2rocblas(side), uplo2rocblas(uplo), op2rocblas(trans), diag2rocblas(diag),
m, n,
(rocblas_double_complex*) &alpha,
(rocblas_double_complex*) dA, ldda,
(rocblas_double_complex*) dB, lddb ) );
}
// -----------------------------------------------------------------------------
// hemm
// -----------------------------------------------------------------------------
// chemm
void chemm(
blas::Queue& queue,
blas::Side side, blas::Uplo uplo,
device_blas_int m, device_blas_int n,
std::complex<float> alpha,
std::complex<float> const *dA, device_blas_int ldda,
std::complex<float> const *dB, device_blas_int lddb,
std::complex<float> beta,
std::complex<float>* dC, device_blas_int lddc)
{
blas_dev_call(
rocblas_chemm(
queue.handle(),
side2rocblas(side), uplo2rocblas(uplo),
m, n,
(rocblas_float_complex*) &alpha,
(rocblas_float_complex*) dA, ldda,
(rocblas_float_complex*) dB, lddb,
(rocblas_float_complex*) &beta,
(rocblas_float_complex*) dC, lddc ) );
}
// -----------------------------------------------------------------------------
// zhemm
void zhemm(
blas::Queue& queue,
blas::Side side, blas::Uplo uplo,
device_blas_int m, device_blas_int n,
std::complex<double> alpha,
std::complex<double> const *dA, device_blas_int ldda,
std::complex<double> const *dB, device_blas_int lddb,
std::complex<double> beta,
std::complex<double>* dC, device_blas_int lddc)
{
blas_dev_call(
rocblas_zhemm(
queue.handle(),
side2rocblas(side), uplo2rocblas(uplo),
m, n,
(rocblas_double_complex*) &alpha,
(rocblas_double_complex*) dA, ldda,
(rocblas_double_complex*) dB, lddb,
(rocblas_double_complex*) &beta,
(rocblas_double_complex*) dC, lddc ) );
}
// -----------------------------------------------------------------------------
// symm
// -----------------------------------------------------------------------------
// ssymm
void ssymm(
blas::Queue& queue,
blas::Side side, blas::Uplo uplo,
device_blas_int m, device_blas_int n,
float alpha,
float const *dA, device_blas_int ldda,
float const *dB, device_blas_int lddb,
float beta,
float* dC, device_blas_int lddc)
{
blas_dev_call(
rocblas_ssymm(
queue.handle(),
side2rocblas(side), uplo2rocblas(uplo),
m, n,
&alpha, dA, ldda,
dB, lddb,
&beta, dC, lddc ) );
}
// -----------------------------------------------------------------------------
// dsymm
void dsymm(
blas::Queue& queue,
blas::Side side, blas::Uplo uplo,
device_blas_int m, device_blas_int n,
double alpha,
double const *dA, device_blas_int ldda,
double const *dB, device_blas_int lddb,
double beta,
double* dC, device_blas_int lddc)
{
blas_dev_call(
rocblas_dsymm(
queue.handle(),
side2rocblas(side), uplo2rocblas(uplo),
m, n,
&alpha, dA, ldda,
dB, lddb,
&beta, dC, lddc ) );
}
// -----------------------------------------------------------------------------
// csymm
void csymm(
blas::Queue& queue,
blas::Side side, blas::Uplo uplo,
device_blas_int m, device_blas_int n,
std::complex<float> alpha,
std::complex<float> const *dA, device_blas_int ldda,
std::complex<float> const *dB, device_blas_int lddb,
std::complex<float> beta,
std::complex<float>* dC, device_blas_int lddc)
{
blas_dev_call(
rocblas_csymm(
queue.handle(),
side2rocblas(side), uplo2rocblas(uplo),
m, n,
(rocblas_float_complex*) &alpha,
(rocblas_float_complex*) dA, ldda,
(rocblas_float_complex*) dB, lddb,
(rocblas_float_complex*) &beta,
(rocblas_float_complex*) dC, lddc ) );
}
// -----------------------------------------------------------------------------
// zsymm
void zsymm(
blas::Queue& queue,
blas::Side side, blas::Uplo uplo,
device_blas_int m, device_blas_int n,
std::complex<double> alpha,
std::complex<double> const *dA, device_blas_int ldda,
std::complex<double> const *dB, device_blas_int lddb,
std::complex<double> beta,
std::complex<double>* dC, device_blas_int lddc)
{
blas_dev_call(
rocblas_zsymm(
queue.handle(),
side2rocblas(side), uplo2rocblas(uplo),
m, n,
(rocblas_double_complex*) &alpha,
(rocblas_double_complex*) dA, ldda,
(rocblas_double_complex*) dB, lddb,
(rocblas_double_complex*) &beta,
(rocblas_double_complex*) dC, lddc ) );
}
// -----------------------------------------------------------------------------
// herk
// -----------------------------------------------------------------------------
// cherk
void cherk(
blas::Queue& queue,
blas::Uplo uplo, blas::Op trans,
device_blas_int n, device_blas_int k,
float alpha,
std::complex<float> const *dA, device_blas_int ldda,
float beta,
std::complex<float>* dC, device_blas_int lddc)
{
blas_dev_call(
rocblas_cherk(
queue.handle(),
uplo2rocblas(uplo), op2rocblas(trans),
n, k,
&alpha, (rocblas_float_complex*) dA, ldda,
&beta, (rocblas_float_complex*) dC, lddc ) );
}
// -----------------------------------------------------------------------------
// zherk
void zherk(
blas::Queue& queue,
blas::Uplo uplo, blas::Op trans,
device_blas_int n, device_blas_int k,
double alpha,
std::complex<double> const *dA, device_blas_int ldda,
double beta,
std::complex<double>* dC, device_blas_int lddc)
{
blas_dev_call(
rocblas_zherk(
queue.handle(),
uplo2rocblas(uplo), op2rocblas(trans),
n, k,
&alpha, (rocblas_double_complex*) dA, ldda,
&beta, (rocblas_double_complex*) dC, lddc ) );
}
// -----------------------------------------------------------------------------
// syrk
// -----------------------------------------------------------------------------
// ssyrk
void ssyrk(
blas::Queue& queue,
blas::Uplo uplo, blas::Op trans,
device_blas_int n, device_blas_int k,
float alpha,
float const *dA, device_blas_int ldda,
float beta,
float* dC, device_blas_int lddc)
{
// rocblas doesn't accept ConjTrans.
if (trans == Op::ConjTrans)
trans = Op::Trans;
blas_dev_call(
rocblas_ssyrk(
queue.handle(),
uplo2rocblas(uplo), op2rocblas(trans),
n, k,
&alpha, dA, ldda,
&beta, dC, lddc ) );
}
// -----------------------------------------------------------------------------
// dsyrk
void dsyrk(
blas::Queue& queue,
blas::Uplo uplo, blas::Op trans,
device_blas_int n, device_blas_int k,
double alpha,
double const *dA, device_blas_int ldda,
double beta,
double* dC, device_blas_int lddc)
{
// rocblas doesn't accept ConjTrans.
if (trans == Op::ConjTrans)
trans = Op::Trans;
blas_dev_call(
rocblas_dsyrk(
queue.handle(),
uplo2rocblas(uplo), op2rocblas(trans),
n, k,
&alpha, dA, ldda,
&beta, dC, lddc ) );
}
// -----------------------------------------------------------------------------
// csyrk
void csyrk(
blas::Queue& queue,
blas::Uplo uplo, blas::Op trans,
device_blas_int n, device_blas_int k,
std::complex<float> alpha,
std::complex<float> const *dA, device_blas_int ldda,
std::complex<float> beta,
std::complex<float>* dC, device_blas_int lddc)
{
blas_dev_call(
rocblas_csyrk(
queue.handle(),
uplo2rocblas(uplo), op2rocblas(trans),
n, k,
(rocblas_float_complex*) &alpha,
(rocblas_float_complex*) dA, ldda,
(rocblas_float_complex*) &beta,
(rocblas_float_complex*) dC, lddc ) );
}
// -----------------------------------------------------------------------------
// zsyrk
void zsyrk(
blas::Queue& queue,
blas::Uplo uplo, blas::Op trans,
device_blas_int n, device_blas_int k,
std::complex<double> alpha,
std::complex<double> const *dA, device_blas_int ldda,
std::complex<double> beta,
std::complex<double>* dC, device_blas_int lddc)
{
blas_dev_call(
rocblas_zsyrk(
queue.handle(),
uplo2rocblas(uplo), op2rocblas(trans),
n, k,
(rocblas_double_complex*) &alpha,
(rocblas_double_complex*) dA, ldda,
(rocblas_double_complex*) &beta,
(rocblas_double_complex*) dC, lddc ) );
}
// -----------------------------------------------------------------------------
// her2k
// -----------------------------------------------------------------------------
// cher2k
void cher2k(
blas::Queue& queue,
blas::Uplo uplo, blas::Op trans,
device_blas_int n, device_blas_int k,
std::complex<float> alpha,
std::complex<float> const *dA, device_blas_int ldda,
std::complex<float> const *dB, device_blas_int lddb,
float beta,
std::complex<float>* dC, device_blas_int lddc)
{
blas_dev_call(
rocblas_cher2k(
queue.handle(),
uplo2rocblas(uplo), op2rocblas(trans),
n, k,
(rocblas_float_complex*) &alpha,
(rocblas_float_complex*) dA, ldda,
(rocblas_float_complex*) dB, lddb,
&beta,
(rocblas_float_complex*) dC, lddc ) );
}
// -----------------------------------------------------------------------------
// zher2k
void zher2k(
blas::Queue& queue,
blas::Uplo uplo, blas::Op trans,
device_blas_int n, device_blas_int k,
std::complex<double> alpha,
std::complex<double> const *dA, device_blas_int ldda,
std::complex<double> const *dB, device_blas_int lddb,
double beta,
std::complex<double>* dC, device_blas_int lddc)
{
blas_dev_call(
rocblas_zher2k(
queue.handle(),
uplo2rocblas(uplo), op2rocblas(trans),
n, k,
(rocblas_double_complex*) &alpha,
(rocblas_double_complex*) dA, ldda,
(rocblas_double_complex*) dB, lddb,
&beta,
(rocblas_double_complex*) dC, lddc ) );
}
// -----------------------------------------------------------------------------
// syr2k
// -----------------------------------------------------------------------------
// ssyr2k
void ssyr2k(
blas::Queue& queue,
blas::Uplo uplo, blas::Op trans,
device_blas_int n, device_blas_int k,
float alpha,
float const *dA, device_blas_int ldda,
float const *dB, device_blas_int lddb,
float beta,
float* dC, device_blas_int lddc)
{
// rocblas doesn't accept ConjTrans.
if (trans == Op::ConjTrans)
trans = Op::Trans;
blas_dev_call(
rocblas_ssyr2k(
queue.handle(),
uplo2rocblas(uplo), op2rocblas(trans),
n, k,
&alpha, dA, ldda,
dB, lddb,
&beta, dC, lddc ) );
}
// -----------------------------------------------------------------------------
// dsyr2k
void dsyr2k(
blas::Queue& queue,
blas::Uplo uplo, blas::Op trans,
device_blas_int n, device_blas_int k,
double alpha,
double const *dA, device_blas_int ldda,
double const *dB, device_blas_int lddb,
double beta,
double* dC, device_blas_int lddc)
{
// rocblas doesn't accept ConjTrans.
if (trans == Op::ConjTrans)
trans = Op::Trans;
blas_dev_call(
rocblas_dsyr2k(
queue.handle(),
uplo2rocblas(uplo), op2rocblas(trans),
n, k,
&alpha, dA, ldda,
dB, lddb,
&beta, dC, lddc ) );
}
// -----------------------------------------------------------------------------
// csyr2k
void csyr2k(
blas::Queue& queue,
blas::Uplo uplo, blas::Op trans,
device_blas_int n, device_blas_int k,
std::complex<float> alpha,
std::complex<float> const *dA, device_blas_int ldda,
std::complex<float> const *dB, device_blas_int lddb,
std::complex<float> beta,
std::complex<float>* dC, device_blas_int lddc)
{
blas_dev_call(
rocblas_csyr2k(
queue.handle(),
uplo2rocblas(uplo), op2rocblas(trans),
n, k,
(rocblas_float_complex*) &alpha,
(rocblas_float_complex*) dA, ldda,
(rocblas_float_complex*) dB, lddb,
(rocblas_float_complex*) &beta,
(rocblas_float_complex*) dC, lddc ) );
}
// -----------------------------------------------------------------------------
// zsyr2k
void zsyr2k(
blas::Queue& queue,
blas::Uplo uplo, blas::Op trans,
device_blas_int n, device_blas_int k,
std::complex<double> alpha,
std::complex<double> const *dA, device_blas_int ldda,
std::complex<double> const *dB, device_blas_int lddb,
std::complex<double> beta,
std::complex<double>* dC, device_blas_int lddc)
{
blas_dev_call(
rocblas_zsyr2k(
queue.handle(),
uplo2rocblas(uplo), op2rocblas(trans),
n, k,
(rocblas_double_complex*) &alpha,
(rocblas_double_complex*) dA, ldda,
(rocblas_double_complex*) dB, lddb,
(rocblas_double_complex*) &beta,
(rocblas_double_complex*) dC, lddc ) );
}
// -----------------------------------------------------------------------------
// batch gemm
// -----------------------------------------------------------------------------
// batch sgemm
void batch_sgemm(
blas::Queue& queue,
blas::Op transA, blas::Op transB,
device_blas_int m, device_blas_int n, device_blas_int k,
float alpha,
float const * const * dAarray, device_blas_int ldda,
float const * const * dBarray, device_blas_int lddb,
float beta,
float** dCarray, device_blas_int lddc,
device_blas_int batch_size)
{
blas_dev_call(
rocblas_sgemm_batched(
queue.handle(),
op2rocblas(transA), op2rocblas(transB),
m, n, k,
&alpha,
(float const**) dAarray, ldda,
(float const**) dBarray, lddb,
&beta,
dCarray, lddc,
batch_size ) );
}
// -----------------------------------------------------------------------------
// batch dgemm
void batch_dgemm(
blas::Queue& queue,
blas::Op transA, blas::Op transB,
device_blas_int m, device_blas_int n, device_blas_int k,
double alpha,
double const * const * dAarray, device_blas_int ldda,
double const * const * dBarray, device_blas_int lddb,
double beta,
double** dCarray, device_blas_int lddc,
device_blas_int batch_size)
{
blas_dev_call(
rocblas_dgemm_batched(
queue.handle(),
op2rocblas(transA), op2rocblas(transB),
m, n, k,
&alpha,
(double const**) dAarray, ldda,
(double const**) dBarray, lddb,
&beta,
dCarray, lddc,
batch_size ) );
}
// -----------------------------------------------------------------------------
// batch cgemm
void batch_cgemm(
blas::Queue& queue,
blas::Op transA, blas::Op transB,
device_blas_int m, device_blas_int n, device_blas_int k,
std::complex<float> alpha,
std::complex<float> const * const * dAarray, device_blas_int ldda,
std::complex<float> const * const * dBarray, device_blas_int lddb,
std::complex<float> beta,
std::complex<float>** dCarray, device_blas_int lddc,
device_blas_int batch_size)
{
blas_dev_call(
rocblas_cgemm_batched(
queue.handle(),
op2rocblas(transA), op2rocblas(transB),
m, n, k,
(rocblas_float_complex*) &alpha,
(rocblas_float_complex const**) dAarray, ldda,
(rocblas_float_complex const**) dBarray, lddb,
(rocblas_float_complex*) &beta,
(rocblas_float_complex**) dCarray, lddc,
batch_size ) );
}
// -----------------------------------------------------------------------------
// batch zgemm
void batch_zgemm(
blas::Queue& queue,
blas::Op transA, blas::Op transB,
device_blas_int m, device_blas_int n, device_blas_int k,
std::complex<double> alpha,
std::complex<double> const * const * dAarray, device_blas_int ldda,
std::complex<double> const * const * dBarray, device_blas_int lddb,
std::complex<double> beta,
std::complex<double>** dCarray, device_blas_int lddc,
device_blas_int batch_size)
{
blas_dev_call(
rocblas_zgemm_batched(
queue.handle(),
op2rocblas(transA), op2rocblas(transB),
m, n, k,
(rocblas_double_complex*) &alpha,
(rocblas_double_complex const**) dAarray, ldda,
(rocblas_double_complex const**) dBarray, lddb,
(rocblas_double_complex*) &beta,
(rocblas_double_complex**) dCarray, lddc,
batch_size ) );
}
// -----------------------------------------------------------------------------
// batch strsm
void batch_strsm(
blas::Queue& queue,
blas::Side side, blas::Uplo uplo, blas::Op trans, blas::Diag diag,
device_blas_int m, device_blas_int n,
float alpha,
float const * const * dAarray, device_blas_int ldda,
float const * const * dBarray, device_blas_int lddb,
device_blas_int batch_size)
{
blas_dev_call(
rocblas_strsm_batched(
queue.handle(),
side2rocblas(side), uplo2rocblas(uplo), op2rocblas(trans), diag2rocblas(diag),
m, n,
&alpha,
(float const**) dAarray, ldda,
(float**) dBarray, lddb,
batch_size ) );
}
// -----------------------------------------------------------------------------
// batch dtrsm
void batch_dtrsm(
blas::Queue& queue,
blas::Side side, blas::Uplo uplo, blas::Op trans, blas::Diag diag,
device_blas_int m, device_blas_int n,
double alpha,
double const * const * dAarray, device_blas_int ldda,
double const * const * dBarray, device_blas_int lddb,
device_blas_int batch_size)
{
blas_dev_call(
rocblas_dtrsm_batched(
queue.handle(),
side2rocblas(side), uplo2rocblas(uplo), op2rocblas(trans), diag2rocblas(diag),
m, n,
&alpha,
(double const**) dAarray, ldda,
(double**) dBarray, lddb,
batch_size ) );
}
// -----------------------------------------------------------------------------
// batch ctrsm
void batch_ctrsm(
blas::Queue& queue,
blas::Side side, blas::Uplo uplo, blas::Op trans, blas::Diag diag,
device_blas_int m, device_blas_int n,
std::complex<float> alpha,
std::complex<float> const * const * dAarray, device_blas_int ldda,
std::complex<float> const * const * dBarray, device_blas_int lddb,
device_blas_int batch_size)
{
blas_dev_call(
rocblas_ctrsm_batched(
queue.handle(),
side2rocblas(side), uplo2rocblas(uplo), op2rocblas(trans), diag2rocblas(diag),
m, n,
(rocblas_float_complex*) &alpha,
(rocblas_float_complex const**) dAarray, ldda,
(rocblas_float_complex**) dBarray, lddb,
batch_size ) );
}
// -----------------------------------------------------------------------------
// batch ztrsm
void batch_ztrsm(
blas::Queue& queue,
blas::Side side, blas::Uplo uplo, blas::Op trans, blas::Diag diag,
device_blas_int m, device_blas_int n,
std::complex<double> alpha,
std::complex<double> const * const * dAarray, device_blas_int ldda,
std::complex<double> const * const * dBarray, device_blas_int lddb,
device_blas_int batch_size)
{
blas_dev_call(
rocblas_ztrsm_batched(
queue.handle(),
side2rocblas(side), uplo2rocblas(uplo), op2rocblas(trans), diag2rocblas(diag),
m, n,
(rocblas_double_complex*) &alpha,
(rocblas_double_complex const**) dAarray, ldda,
(rocblas_double_complex**) dBarray, lddb,
batch_size ) );
}
} // namespace device
} // namespace blas
#endif // BLAS_HAVE_ROCBLAS
| 32.475122
| 108
| 0.513654
|
G-Ragghianti
|
83757500261ff583fa5227a73296280c4eb83929
| 2,469
|
hpp
|
C++
|
Sources/AGEngine/Render/GeometryManagement/DebugDrawManager.hpp
|
Another-Game-Engine/AGE
|
d5d9e98235198fe580a43007914f515437635830
|
[
"MIT"
] | 47
|
2015-03-29T09:44:25.000Z
|
2020-11-30T10:05:56.000Z
|
Sources/AGEngine/Render/GeometryManagement/DebugDrawManager.hpp
|
Another-Game-Engine/AGE
|
d5d9e98235198fe580a43007914f515437635830
|
[
"MIT"
] | 313
|
2015-01-01T18:16:30.000Z
|
2015-11-30T07:54:07.000Z
|
Sources/AGEngine/Render/GeometryManagement/DebugDrawManager.hpp
|
Another-Game-Engine/AGE
|
d5d9e98235198fe580a43007914f515437635830
|
[
"MIT"
] | 9
|
2015-06-07T13:21:54.000Z
|
2020-08-25T09:50:07.000Z
|
#pragma once
#include <vector>
#include <glm/glm.hpp>
#include <Utils/Spinlock.hpp>
#include <Utils/Dependency.hpp>
#include <Utils/Containers/PODVector.hpp>
namespace AGE
{
class PaintingManager;
class Painter;
class DebugDrawManager : public Dependency < DebugDrawManager >
{
public:
struct SimpleVec2
{
float x, y;
};
struct SimpleVec3
{
float x, y, z;
};
inline void lock() { _mutex.lock(); }
inline void unlock() { _mutex.unlock(); }
// IMPORTANT LOCK IT AND UNLOCKIT
void draw3dQuad(SimpleVec3 &&_a, SimpleVec3 &&_b, SimpleVec3 &&_c, SimpleVec3 &&_d, SimpleVec3 &&_color, bool _depthTest);
// IMPORTANT LOCK IT AND UNLOCKIT
void draw3DLine(SimpleVec3 &&_start, SimpleVec3 &&_startColor, SimpleVec3 &&_end, SimpleVec3 &&_endColor, bool _depthTest);
// IMPORTANT LOCK IT AND UNLOCKIT
void draw2DQuad(SimpleVec2 &&_a, SimpleVec2 &&_b, SimpleVec2 &&_c, SimpleVec2 &&_d, SimpleVec3 &&_color);
// IMPORTANT LOCK IT AND UNLOCKIT
void draw2DLine(SimpleVec2 &&_start, SimpleVec2 &&_end, SimpleVec3 &&_color);
// IMPORTANT LOCK IT AND UNLOCKIT
void draw3dQuad(const glm::vec3 &_a, const glm::vec3 &_b, const glm::vec3 &_c, const glm::vec3 &_d, const glm::vec3 &_color, bool _depthTest);
// IMPORTANT LOCK IT AND UNLOCKIT
void draw3DLine(const glm::vec3 &_start, const glm::vec3 &_startColor, const glm::vec3 &_end, const glm::vec3 &_endColor, bool _depthTest);
// IMPORTANT LOCK IT AND UNLOCKIT
void draw2DQuad(const glm::vec2 &_a, const glm::vec2 &_b, const glm::vec2 &_c, const glm::vec2 &_d, const glm::vec3 &_color);
// IMPORTANT LOCK IT AND UNLOCKIT
void draw2DLine(const glm::vec2 &_start, const glm::vec2 &_end, const glm::vec3 &_color);
void renderBegin(std::shared_ptr<PaintingManager> paintingManager);
void renderEnd();
private:
// Debug Drawings
// 2D lines
PODVector<SimpleVec2> _debug2DlinesPoints;
PODVector<SimpleVec3> _debug2DlinesColor;
PODVector<SimpleVec3> _debug3DlinesPoints;
PODVector<SimpleVec3> _debug3DlinesColor;
// 3D lines with depth test
PODVector<SimpleVec3> _debug3DlinesPointsDepth;
PODVector<SimpleVec3> _debug3DlinesColorDepth;
PODVector<unsigned int> indices2DLines;
PODVector<unsigned int> indices3DLines;
PODVector<unsigned int> indices3DLinesDepth;
SpinLock _mutex;
std::shared_ptr<Painter> _line2DPainter = nullptr;
std::shared_ptr<Painter> _line3DPainter = nullptr;
std::shared_ptr<Painter> _line3DPainterDepth = nullptr;
};
}
| 35.782609
| 144
| 0.738356
|
Another-Game-Engine
|
83782b69bfe531b044dd9673434c8eda50bae513
| 717
|
cxx
|
C++
|
test/t634.cxx
|
paulwratt/cin-5.34.00
|
036a8202f11a4a0e29ccb10d3c02f304584cda95
|
[
"MIT"
] | 10
|
2018-03-26T07:41:44.000Z
|
2021-11-06T08:33:24.000Z
|
test/t634.cxx
|
paulwratt/cin-5.34.00
|
036a8202f11a4a0e29ccb10d3c02f304584cda95
|
[
"MIT"
] | null | null | null |
test/t634.cxx
|
paulwratt/cin-5.34.00
|
036a8202f11a4a0e29ccb10d3c02f304584cda95
|
[
"MIT"
] | 1
|
2020-11-17T03:17:00.000Z
|
2020-11-17T03:17:00.000Z
|
/* -*- C++ -*- */
/*************************************************************************
* Copyright(c) 1995~2005 Masaharu Goto (root-cint@cern.ch)
*
* For the licensing terms see the file COPYING
*
************************************************************************/
#include <stdio.h>
class TA {
public:
void Bugged(const double x) const; };
void TA::Bugged(const double x) const {
printf("x:%f\n",x);
if (x<15 ) return;
if (x>80 ) return;
int i = 0; // Removing this line solve the problem
printf("OK x:%f\n",x); // This line is never reached
}
void bug() {
TA a;
int i;
for (i=0;i<10;i++) a.Bugged(i*10);
}
int main() {
bug();
return 0;
}
| 23.129032
| 74
| 0.440725
|
paulwratt
|
837a6e6ec3d184dc4b8aa05c80758d6043750930
| 685
|
hpp
|
C++
|
src/Cl/ClTools.hpp
|
Jino42/stf
|
f10ddaf4eb0a7ba94e6f9bb7d6b2191ca3a0b3db
|
[
"Unlicense"
] | null | null | null |
src/Cl/ClTools.hpp
|
Jino42/stf
|
f10ddaf4eb0a7ba94e6f9bb7d6b2191ca3a0b3db
|
[
"Unlicense"
] | null | null | null |
src/Cl/ClTools.hpp
|
Jino42/stf
|
f10ddaf4eb0a7ba94e6f9bb7d6b2191ca3a0b3db
|
[
"Unlicense"
] | null | null | null |
#pragma once
#include <NTL.hpp>
#include <iostream>
#include <Cl/ClContext.hpp>
#include <Cl/ClError.hpp>
namespace ClTools {
template <typename T>
void printIntArrayGpu(cl::Buffer &buffer, size_t length,
std::string const &name, void (*print)(T*)) {
ClError err;
cl::CommandQueue queue(ClContext::Get().context, ClContext::Get().deviceDefault);
T *arrayCpu = new T[length];
err.err = queue.enqueueReadBuffer(buffer, CL_TRUE, 0, sizeof(T) * length, arrayCpu);
err.clCheckError();
queue.finish();
std::cout << "start [" << name << "]" << std::endl;
for (int i = 0; i < length; i++)
print(&arrayCpu[i]);
std::cout << "end [" << name << "]" << std::endl;
}
};
| 29.782609
| 86
| 0.642336
|
Jino42
|
837a852ea239c42c7f4a655106d388572b67417b
| 8,486
|
cpp
|
C++
|
src/opengl/renderer.cpp
|
lahoising/MobRend
|
c804a0cfebd06818a5cbf1747c2337ea134c11d7
|
[
"MIT"
] | null | null | null |
src/opengl/renderer.cpp
|
lahoising/MobRend
|
c804a0cfebd06818a5cbf1747c2337ea134c11d7
|
[
"MIT"
] | null | null | null |
src/opengl/renderer.cpp
|
lahoising/MobRend
|
c804a0cfebd06818a5cbf1747c2337ea134c11d7
|
[
"MIT"
] | null | null | null |
#ifdef MOBREND_GL_RENDERING
#include <glad/glad.h>
#include <glm/glm.hpp>
#ifdef MOBREND_GLFW_WINDOW
#include <mobrend/glfw/window.h>
#endif
#include "mr_logger.h"
#include <mobrend/opengl/renderer.h>
#include <mobrend/gui.h>
#include <mobrend/application.h>
#include <mobrend/model.h>
#include <mobrend/mesh.h>
#include <assimp/Importer.hpp>
namespace mr
{
struct Renderer::gui_init_info_s
{
char glVersion[16];
};
#ifndef NDEBUG
static void GLAPIENTRY GlErrorMessageCallback( GLenum source,
GLenum type,
GLuint id,
GLenum severity,
GLsizei length,
const GLchar* message,
const void* userParam )
{
const char *msg = "OpenGL error 0x%x (severity 0x%x): %s";
if(type == GL_DEBUG_TYPE_ERROR)
{
mrerr(msg, type, severity, message);
}
else
{
mrwarn(msg, type, severity, message);
}
}
#endif
GlRenderer::GlRenderer()
{
#ifdef MOBREND_GLFW_WINDOW
gladLoadGLLoader((GLADloadproc)glfwGetProcAddress);
#endif
#ifndef NDEBUG
mrlog("enable gl debug output");
glEnable(GL_DEBUG_OUTPUT);
glDebugMessageCallback(GlErrorMessageCallback, 0);
#endif
glEnable(GL_DEPTH_TEST);
glClearColor(0.23f, 0.23f, 0.23f, 1.0f);
}
GlRenderer::~GlRenderer()
{
}
void GlRenderer::Clear()
{
glClear(GL_COLOR_BUFFER_BIT);
}
void GlRenderer::SetViewport(int x, int y, int width, int height)
{
glViewport(x, y, width, height);
}
void GlRenderer::OnRenderBegin()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
}
void GlRenderer::OnRenderEnd()
{
}
void GlRenderer::Render(Renderer::Command &cmd)
{
switch (cmd.renderObjectType)
{
case RenderObjectType::RENDER_OBJECT_MESH:
{
const IndexBuffer *indexBuffer = cmd.mesh->GetIndexBuffer();
cmd.mesh->GetVertexBuffer()->Bind();
indexBuffer->Bind();
glDrawElements(
GlRenderer::GetTopology(cmd.topologyType),
indexBuffer->GetElementCount(),
GL_UNSIGNED_INT, nullptr
);
}
break;
case RenderObjectType::RENDER_OBJECT_MODEL:
cmd.renderObjectType = RenderObjectType::RENDER_OBJECT_MESH;
for(auto &mesh : cmd.model->GetMeshes())
{
cmd.mesh = mesh;
this->Render(cmd);
}
break;
default:
mrwarn("Render cmd was called with no render object type");
break;
}
}
void GlRenderer::EnableRenderPass(RenderPassMask renderPassMask, bool enable)
{
void (*fn)(GLenum) = enable? glEnable : glDisable;
if(renderPassMask & RENDER_PASS_DEPTH)
{
fn( GlRenderer::GetRenderPass(RENDER_PASS_DEPTH) );
}
if(renderPassMask & RENDER_PASS_STENCIL)
{
fn( GlRenderer::GetRenderPass(RENDER_PASS_STENCIL) );
}
if(renderPassMask & RENDER_PASS_BLEND)
{
fn( GlRenderer::GetRenderPass(RENDER_PASS_BLEND) );
}
if(renderPassMask & RENDER_PASS_CULLING)
{
fn( GlRenderer::GetRenderPass(RENDER_PASS_CULLING) );
}
}
void GlRenderer::EnableFeatures(RendererFeatureMask mask, bool enable)
{
void (*fn)(GLenum) = enable? glEnable : glDisable;
if(mask & RENDERER_FEATURE_SHADER_POINT_SIZE)
{
fn( GlRenderer::GetRendererFeature(RENDERER_FEATURE_SHADER_POINT_SIZE) );
}
}
void GlRenderer::SetDepthTestFn(RenderPassFn fn)
{
glDepthFunc( GlRenderer::GetRenderPassFn(fn) );
}
void GlRenderer::SetDepthMask(bool writeable)
{
glDepthMask(writeable? GL_TRUE : GL_FALSE);
}
void GlRenderer::SetStencilTestFn(RenderPassFn fn, int refValue, unsigned int mask)
{
glStencilFunc(
GlRenderer::GetRenderPassFn(fn),
refValue, mask
);
}
void GlRenderer::SetBlendFn(BlendFn srcFactor, BlendFn dstFactor)
{
glBlendFunc(
GlRenderer::GetBlendFn(srcFactor),
GlRenderer::GetBlendFn(dstFactor)
);
}
void GlRenderer::SetStencilTestAction(
StencilAction stencilFailAction,
StencilAction depthFailAction,
StencilAction bothPass)
{
glStencilOp(
GlRenderer::GetStencilAction(stencilFailAction),
GlRenderer::GetStencilAction(depthFailAction),
GlRenderer::GetStencilAction(bothPass)
);
}
void GlRenderer::SetStencilMask(uint32_t mask)
{
glStencilMask((unsigned int)mask);
}
void GlRenderer::SetCullFace(CullFace cullFace)
{
glCullFace( GlRenderer::GetCullFace(cullFace) );
}
void GlRenderer::SetFrontFaceWinding(FrontFaceWinding winding)
{
glFrontFace( GlRenderer::GetWinding(winding) );
}
struct Renderer::gui_init_info_s *GlRenderer::GetGuiInitInfo()
{
auto *guiInfo = (Renderer::gui_init_info_s*)malloc(sizeof(Renderer::gui_init_info_s));
strcpy(guiInfo->glVersion, "#version 410");
return guiInfo;
}
void GlRenderer::DeleteGuiInitInfo(Renderer::gui_init_info_s *info)
{
delete(info);
}
GLenum GlRenderer::GetTopology(TopologyType type)
{
switch (type)
{
case TopologyType::TOPOLOGY_TRIANGLES: return GL_TRIANGLES;
case TopologyType::TOPOLOGY_WIREFRAME: return GL_LINE_STRIP;
case TopologyType::TOPOLOGY_POINTS: return GL_POINTS;
default: throw "Unsupported topology type";
}
}
GLenum GlRenderer::GetRendererFeature(RendererFeature feature)
{
switch (feature)
{
case RENDERER_FEATURE_SHADER_POINT_SIZE: return GL_PROGRAM_POINT_SIZE;
default: return 0;
}
}
GLenum GlRenderer::GetRenderPass(RenderPass pass)
{
switch (pass)
{
case RENDER_PASS_DEPTH: return GL_DEPTH_TEST;
case RENDER_PASS_STENCIL: return GL_STENCIL_TEST;
case RENDER_PASS_BLEND: return GL_BLEND;
case RENDER_PASS_CULLING: return GL_CULL_FACE;
default: return 0;
}
}
GLenum GlRenderer::GetRenderPassFn(RenderPassFn fn)
{
switch (fn)
{
case RENDER_PASS_FN_ALWAYS: return GL_ALWAYS;
case RENDER_PASS_FN_NEVER: return GL_NEVER;
case RENDER_PASS_FN_LESS: return GL_LESS;
case RENDER_PASS_FN_EQUAL: return GL_EQUAL;
case RENDER_PASS_FN_LESS_OR_EQUEAL: return GL_LEQUAL;
case RENDER_PASS_FN_GREATER: return GL_GREATER;
case RENDER_PASS_FN_NOT_EQUAL: return GL_NOTEQUAL;
case RENDER_PASS_FN_GREATER_OR_EQUAL: return GL_GEQUAL;
default: throw "Render pass function not supporter";
}
}
GLenum GlRenderer::GetStencilAction(StencilAction action)
{
switch (action)
{
case STENCIL_ACTION_KEEP: return GL_KEEP;
case STENCIL_ACTION_ZERO: return GL_ZERO;
case STENCIL_ACTION_REPLACE: return GL_REPLACE;
case STENCIL_ACTION_INCREASE: return GL_INCR;
case STENCIL_ACTION_INCREASE_WRAP: return GL_INCR_WRAP;
case STENCIL_ACTION_DECREASE: return GL_DECR;
case STENCIL_ACTION_DECREASE_WRAP: return GL_DECR_WRAP;
case STENCIL_ACTION_INVERT: return GL_INVERT;
default: throw "Unknown stencil action";
}
}
GLenum GlRenderer::GetBlendFn(BlendFn fn)
{
switch(fn)
{
case BLEND_FN_ZERO: return GL_ZERO;
case BLEND_FN_ONE: return GL_ONE;
case BLEND_FN_SRC_COLOR: return GL_SRC_COLOR;
case BLEND_FN_ONE_MINUS_SRC_COLOR: return GL_ONE_MINUS_SRC_COLOR;
case BLEND_FN_DST_COLOR: return GL_DST_COLOR;
case BLEND_FN_ONE_MINUS_DST_COLOR: return GL_ONE_MINUS_DST_COLOR;
case BLEND_FN_SRC_ALPHA: return GL_SRC_ALPHA;
case BLEND_FN_ONE_MINUS_SRC_ALPHA: return GL_ONE_MINUS_SRC_ALPHA;
case BLEND_FN_DST_ALPHA: return GL_DST_ALPHA;
case BLEND_FN_ONE_MINUS_DST_ALPHA: return GL_ONE_MINUS_DST_ALPHA;
case BLEND_FN_CONSTANT_COLOR: return GL_CONSTANT_COLOR;
case BLEND_FN_ONE_MINUS_CONSTANT_COLOR: return GL_ONE_MINUS_CONSTANT_COLOR;
case BLEND_FN_CONSTANT_ALPHA: return GL_CONSTANT_ALPHA;
case BLEND_FN_ONE_MINUS_CONSTANT_ALPHA: return GL_ONE_MINUS_CONSTANT_ALPHA;
default: throw "Unknown blend fn";
}
}
GLenum GlRenderer::GetCullFace(CullFace cullFace)
{
switch (cullFace)
{
case CULL_FACE_FRONT: return GL_FRONT;
case CULL_FACE_BACK: return GL_BACK;
case CULL_FACE_FRONT_AND_BACK: return GL_FRONT_AND_BACK;
default: throw "Unknown cull face";
}
}
GLenum GlRenderer::GetWinding(FrontFaceWinding winding)
{
switch (winding)
{
case FF_WINDING_CCW: return GL_CCW;
case FF_WINDING_CW: return GL_CW;
default: throw "Unknown winding";
}
}
} // namespace mr
#endif
| 25.871951
| 90
| 0.699387
|
lahoising
|
837ac01c040c638ad3aad26de9c78fdf6b41408d
| 8,369
|
cpp
|
C++
|
src/TactileSwitch.cpp
|
IGB-Germany/TactileSwitch
|
0b7a2be6841daed6027ee6e640fc39411a11e3a3
|
[
"Unlicense"
] | null | null | null |
src/TactileSwitch.cpp
|
IGB-Germany/TactileSwitch
|
0b7a2be6841daed6027ee6e640fc39411a11e3a3
|
[
"Unlicense"
] | null | null | null |
src/TactileSwitch.cpp
|
IGB-Germany/TactileSwitch
|
0b7a2be6841daed6027ee6e640fc39411a11e3a3
|
[
"Unlicense"
] | null | null | null |
//tactile switch class
#include "TactileSwitch.h"
//Constructor
TactileSwitch::TactileSwitch(uint8_t pin, uint8_t number, uint8_t mode, bool enablePullUp):
_number(number),
_pin(pin),
_mode(mode),
_enablePullUp(enablePullUp),
_event (NO_EVENT),
_message (NO_MESSAGE),
_state (START),
_previousState(START),
_clicks(0),
_timePressed(0),
_timeReleased(0),
_multiClickFeature(true),
_readTime(0),
_durationDebouncePressed(DURATION_DEBOUNCE_PRESSED),
_durationDebounceReleased(DURATION_DEBOUNCE_RELEASED)
{
//Configuration of switch
if (_mode) //HIGH
{
//Signal from HIGH(released) to LOW(pressed)
pinMode(_pin, INPUT);
digitalWrite(_pin, LOW);
}
else //LOW
{
//Signal from LOW(released) to HIGH(pressed)
//to do optional INPUT_PULLUP
pinMode(_pin, INPUT_PULLUP);
//digitalWrite(_pin, HIGH);
}
}
//get number of switch
uint8_t TactileSwitch::getNumber() const
{
return _number;
}
//set number of switch
void TactileSwitch::setNumber(uint8_t number)
{
_number = number;
}
//get message of switch like NO_MESSAGE, POLLING_LONG, BOUNCING_PRESSED, BOUNCING_RELEASED
TactileSwitch::event_t TactileSwitch::getEvent() const
{
return _event;
}
TactileSwitch::message_t TactileSwitch::getMessage() const
{
return _message;
}
//get current state
uint8_t TactileSwitch::getState(void)
{
//read and print state
if (_state == START || _previousState != _state)
{
Serial.print(F("_state: "));
Serial.println(_state);
}
_previousState = _state; //save state
return _state;
}
//get number of clicks
int8_t TactileSwitch::getClicks(void) const
{
return _clicks;
}
//read switch
void TactileSwitch::readSwitch(void)
{
//get current state
getState();
//get time between polling switch
if (millis() - _readTime >= DURATION_POLLING) _message = POLLING_SLOW;
else _message = NO_MESSAGE;
//save last read time
_readTime = millis();
//initalize
//The button was clicked 102 times consecutively in quick succession.
if (_state == START)//0
{
_clicks = 0;
_event = NO_EVENT;
_message = NO_MESSAGE;
_state = AWAIT_PRESS;
}
//1
else if (_state == AWAIT_PRESS)
{
_clicks = 0;
_event = NO_EVENT;
_message = NO_MESSAGE;
//read pin
//if switch is pressed
//save _timePressed
//and change to _state to DEBOUNCE_PRESS
if (digitalRead(_pin) == _mode) //falling flank HIGH to LOW
{
//save time
_timePressed = millis();
//change state
_state = DEBOUNCE_PRESS;
}
//else switch is not pressed
else
{
//wait
}
}
//2
else if (_state == DEBOUNCE_PRESS)
{
//read pin
//if switch is still pressed down
//wait
if (digitalRead(_pin) == _mode)
{
//and wait until DURATION_DEBOUNCE_PRESS has elapsed
if ((millis() - _timePressed) > DURATION_DEBOUNCE_PRESSED)
{
_state = AWAIT_RELEASE;
_message = NO_MESSAGE;
}
}
//if switch is not pressed long enough -> go back
else
{
_state = AWAIT_PRESS;
_message = BOUNCING_PRESSED;
}
}
//3
else if (_state == AWAIT_RELEASE)
{
//initalize if back from Bouncing
_message = NO_MESSAGE;
//read _pin
//if released
//save _timeReleased
//and change to _state = DEBOUNCE_RELEASE
if (digitalRead(_pin) != _mode)
{
//save state change time
_timeReleased = millis();
_state = DEBOUNCE_RELEASE;
//only one loop count and than next state
//does not work if bouncing
//clicks++;
}
//if still pressed and time elapsed -> LONG PRESS
else
{
if ((millis() - _timePressed) > DURATION_LONG_PRESS)
{
_event = HOLD_LONG;
_state = LONG_PRESS;
//save clicks before waiting
_clicks = -1;
}
else //<= DURATION_LONG_PRESS
{
//wait
}
}
}
//4
else if (_state == DEBOUNCE_RELEASE)
{
//read pin
//if released long enough
//change to _state = AWAIT_MULTI_PRESS
if (digitalRead(_pin) != _mode) //still released ?
{
//Serial.println(F("released"));
//wait long enough
if ((millis() - _timeReleased) > DURATION_DEBOUNCE_RELEASED)
{
//increase clicks
_clicks ++;
_state = AWAIT_MULTI_PRESS;
}
else
{
//wait
}
}
//not released long enough go back
else
{
_state = AWAIT_RELEASE;
_message = BOUNCING_RELEASED;
}
}
//5
else if (_state == AWAIT_MULTI_PRESS)
{
//time not elapsed ?
//_multiClickFeature enabled ?
//read pin
//if pressed Multiclick
if ((millis() - _timeReleased) < DURATION_MULTI_CLICK && _multiClickFeature)
{
//Next click - Multiclick start
if (digitalRead(_pin) == _mode) //LOW
{
//save state change time
_timePressed = millis();
//change _state
_state = DEBOUNCE_PRESS;
//increades clicks
//_clicks += 1; //does not work correct here if bouncing
}
//wait
else
{
}
}
//End of _multiClickTime
else
{
//end of state machine loop
//back to start
_state = AWAIT_PRESS;
if (_clicks == 1)_event = CLICK;
else if (_clicks > 1 ) _event = MULTI_CLICK;
else _event = NO_EVENT;
}
}
//6
else if (_state == LONG_PRESS)
{
//read _pin
if (digitalRead(_pin) != _mode) //if released
{
//save time since released
_timeReleased = millis();
//go to debounce
_state = DEBOUNCE_RELEASE_LONG;
}
else //still pressed
{
//wait long enough
if ((millis() - _timePressed) > DURATION_VERY_LONG_PRESS)
{
//go to next state
_state = VERY_LONG_PRESS;
_event = HOLD_VERY_LONG;
}
//stay in this state
else
{
//inversed logic; reset clicks here
_event = NO_EVENT;
_message = NO_MESSAGE;
_clicks = 0;
}
}
}
//7
else if (_state == DEBOUNCE_RELEASE_LONG)
{
//open: measure first _pin or wait _debounceReleaseTime + _eventTime
//Solution: best way first check if switch is still pressed than start timer.
//if switch not released go back instantly
//means switch ha to be released for an amount of time or we jump back to previous state
//still released ?
if (digitalRead(_pin) != _mode)
{
//wait long enough
if ((millis() - _timeReleased) > DURATION_DEBOUNCE_RELEASED)
{
_event = RELEASED_HOLD_LONG;
//go to next state
_state = AWAIT_PRESS;
}
}
//not released go back
else
{
_state = LONG_PRESS;
_message = BOUNCING_RELEASED;
}
}
//8
else if (_state == VERY_LONG_PRESS)
{
//read _pin
if (digitalRead(_pin) != _mode) //if released
{
//save time since released
_timeReleased = millis();
//go to debounce
_state = DEBOUNCE_RELEASE_VERY_LONG;
}
else //still pressed
{
//turned logic; reset clicks here
_event = NO_EVENT;
_clicks = 0;
}
}
//9
else if (_state == DEBOUNCE_RELEASE_VERY_LONG)
{
//still released ?
if (digitalRead(_pin) != _mode)
{
//wait long enough
if ((millis() - _timeReleased) > DURATION_DEBOUNCE_RELEASED)
{
_event = RELEASED_HOLD_VERY_LONG;
//go to next state
_state = AWAIT_PRESS;
}
}
//not released go back
else
{
_state = VERY_LONG_PRESS;
_message = BOUNCING_RELEASED;
}
}
//Unknown _state
else
{
_state = START;
_event = NO_EVENT;
_clicks = 0;
_message = NO_MESSAGE;
}
}
//enable MULTI_CLICK feature default true
void TactileSwitch::setMultiClickFeature(bool enable)
{
_multiClickFeature = enable;
}
//sets the debounce time (in milliseconds) if pressed [default: DURATION_DEBOUNCE_PRESSED = 20]
void TactileSwitch::setDurationDebouncePressed(uint8_t durationDebouncePressed)
{
_durationDebouncePressed = durationDebouncePressed;
}
//sets the debounce time (in milliseconds) if released [default: DURATION_DEBOUNCE_RELEASED = 50].
void TactileSwitch::setDurationDebounceReleased(uint8_t durationDebounceReleased)
{
_durationDebounceReleased = durationDebounceReleased;
}
| 21.908377
| 98
| 0.623491
|
IGB-Germany
|
837b253adc810aeced2b1deff350f0f92a3a50ec
| 168
|
cpp
|
C++
|
tests/map/map_delete_inside_data.cpp
|
ye-luo/openmp-target
|
f042e9d255b521e07ca32fe08799e736d4b1c70c
|
[
"BSD-3-Clause"
] | 5
|
2020-02-14T03:32:58.000Z
|
2021-06-21T18:13:02.000Z
|
tests/map/map_delete_inside_data.cpp
|
ye-luo/openmp-target
|
f042e9d255b521e07ca32fe08799e736d4b1c70c
|
[
"BSD-3-Clause"
] | 1
|
2020-02-24T01:48:06.000Z
|
2020-02-24T01:48:57.000Z
|
tests/map/map_delete_inside_data.cpp
|
ye-luo/openmp-target
|
f042e9d255b521e07ca32fe08799e736d4b1c70c
|
[
"BSD-3-Clause"
] | 4
|
2020-05-20T16:04:10.000Z
|
2021-06-22T20:06:39.000Z
|
int main()
{
int a[100];
#pragma omp target enter data map(alloc:a)
#pragma omp target data map(alloc:a)
{
#pragma omp target exit data map(delete:a)
}
}
| 16.8
| 46
| 0.642857
|
ye-luo
|
8388bd49bc0e8b718d88f392bed4a1565d602fba
| 853
|
hpp
|
C++
|
include/LightBulb/LightBulbPrec.hpp
|
domin1101/ANNHelper
|
50acb5746d6dad6777532e4c7da4983a7683efe0
|
[
"Zlib"
] | 5
|
2016-02-04T06:14:42.000Z
|
2017-02-06T02:21:43.000Z
|
include/LightBulb/LightBulbPrec.hpp
|
domin1101/ANNHelper
|
50acb5746d6dad6777532e4c7da4983a7683efe0
|
[
"Zlib"
] | 41
|
2015-04-15T21:05:45.000Z
|
2015-07-09T12:59:02.000Z
|
include/LightBulb/LightBulbPrec.hpp
|
domin1101/LightBulb
|
50acb5746d6dad6777532e4c7da4983a7683efe0
|
[
"Zlib"
] | null | null | null |
#include <map>
#include <vector>
#include <mutex>
#include <stdexcept>
#include <random>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <string>
#include <memory>
#include <cmath>
#include <thread>
#include <Eigen/Dense>
#include <viennacl/vector.hpp>
#include <viennacl/scalar.hpp>
#include <viennacl/matrix.hpp>
#include <cereal/cereal.hpp>
#include <cereal/types/polymorphic.hpp>
#include <cereal/types/vector.hpp>
#include <cereal/access.hpp>
#include <cereal/types/utility.hpp>
#include <cereal/types/base_class.hpp>
#include <cereal/archives/xml.hpp>
#include <cereal/archives/portable_binary.hpp>
#include <cereal/archives/json.hpp>
#include "IO/UseParentSerialization.hpp"
#include "IO/TemplateDeclaration.hpp"
#include "LinearAlgebra/Vector.hpp"
#include "LinearAlgebra/Matrix.hpp"
#include "LinearAlgebra/Scalar.hpp"
| 24.371429
| 46
| 0.770223
|
domin1101
|
8393e9f57e79eed22781243ed944b64484ed065b
| 4,628
|
hpp
|
C++
|
cpp/include/algorithm/string/shunting_yard.hpp
|
rohithv999/ProAlgos-Cpp
|
36dcb1706e464bdbabfb949ac194b4db12aead3d
|
[
"MIT"
] | 222
|
2020-05-12T23:33:21.000Z
|
2022-03-31T16:57:43.000Z
|
cpp/include/algorithm/string/shunting_yard.hpp
|
rohithv999/ProAlgos-Cpp
|
36dcb1706e464bdbabfb949ac194b4db12aead3d
|
[
"MIT"
] | 93
|
2020-05-07T21:08:41.000Z
|
2022-03-28T00:40:04.000Z
|
cpp/include/algorithm/string/shunting_yard.hpp
|
rohithv999/ProAlgos-Cpp
|
36dcb1706e464bdbabfb949ac194b4db12aead3d
|
[
"MIT"
] | 95
|
2020-05-07T22:22:11.000Z
|
2022-02-01T08:39:25.000Z
|
/*
Shunting Yard
----------------------------------------------
Converting an infix arithmetic string to a post-fix one, A.K.A. Reverse Polish Notation.
This implementation does not implement functions and solely focuses on simple arithmetic of consisting of [-,+,*,/,^]
Time complexity
---------------
O(N*M*P) where N is the size of input vector, i.e. equations,
M is the size of the greatest string in the vector,
and P is maximum number of operators in the string
Space complexity
----------------
O(N+P) = O(N) : where N is the size of input vector, i.e. equations,
and P is maximum number of operators in the string, i.e. stack operations.
*/
#ifndef SHUNTING_YARD_HPP
#define SHUNTING_YARD_HPP
#include <iostream>
#include <vector>
#include <string>
#include <stack>
#include <unordered_map>
#include <algorithm>
using std::string;
class OperatorOperations {
public:
static std::vector<std::string> to_reverse_polish(const std::vector<std::string> &);
static std::unordered_map<char, int> operator_precedence;
static std::unordered_map<char, std::string> operator_association;
};
std::unordered_map<char, int> OperatorOperations::operator_precedence{{'-', 2},
{'+', 2},
{'*', 3},
{'/', 3},
{'^', 4}};
std::unordered_map<char, std::string> OperatorOperations::operator_association{{'-', "left"},
{'+', "left"},
{'*', "left"},
{'/', "left"},
{'^', "right"}};
std::vector<std::string> OperatorOperations::to_reverse_polish(const std::vector<std::string> &equations) {
string equation;
string temporary_string;
std::vector<string> postfixed_equations;
postfixed_equations.reserve(equations.size());
std::stack<char> operators;
for (int i = 0; i <= (int) equations.size() - 1; i++) {
equation = equations[i];
temporary_string = "";
for (int j = 0; j <= (int) equation.length() - 1; j++) {
if (isalnum(equation[j])) {
temporary_string.push_back(equation[j]);
} else if (isblank(equation[j])) {
// do nothing
} else if (equation[j] != '(' && equation[j] != ')' &&
operator_precedence.find(equation[j]) == operator_precedence.end()) {
temporary_string.push_back(equation[j]);
} else {
if (equation[j] == '(') {
operators.push(equation[j]);
} else {
if (equation[j] == ')') {
while (operators.top() != '(') {
temporary_string.push_back(operators.top());
operators.pop();
}
operators.pop();
} else {
if (operators.empty()) {
operators.push(equation[j]);
} else {
while (!operators.empty() && (operators.top() != '(') &&
(OperatorOperations::operator_precedence[operators.top()] >
OperatorOperations::operator_precedence[equation[j]] ||
(OperatorOperations::operator_precedence[operators.top()] ==
OperatorOperations::operator_precedence[equation[j]] &&
OperatorOperations::operator_association[operators.top()] == "left"))) {
temporary_string.push_back(operators.top());
operators.pop();
}
operators.push(equation[j]);
}
}
}
}
}
while (!operators.empty()) {
temporary_string.push_back(operators.top());
operators.pop();
}
postfixed_equations.push_back(temporary_string);
}
return postfixed_equations;
}
#endif // SHUNTING_YARD_HPP
| 43.660377
| 121
| 0.455056
|
rohithv999
|
8b505136a95f188eaf7cfa753f70eb4b5647d720
| 1,530
|
cpp
|
C++
|
Projects/WebAthl/RulesSet.cpp
|
darianbridge/WebAthl
|
daf916b169983375022a39645419f79c7f3cbfed
|
[
"Apache-2.0"
] | null | null | null |
Projects/WebAthl/RulesSet.cpp
|
darianbridge/WebAthl
|
daf916b169983375022a39645419f79c7f3cbfed
|
[
"Apache-2.0"
] | null | null | null |
Projects/WebAthl/RulesSet.cpp
|
darianbridge/WebAthl
|
daf916b169983375022a39645419f79c7f3cbfed
|
[
"Apache-2.0"
] | 1
|
2021-07-05T10:10:21.000Z
|
2021-07-05T10:10:21.000Z
|
// RulesSet.cpp : implementation file
//
#include "stdafx.h"
#include "CSV.h"
#include "StringStream.h"
#include "RecordsetEx.h"
#include "RulesSet.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CRulesSet
IMPLEMENT_DYNAMIC(CRulesSet, CRecordsetEx)
CRulesSet::CRulesSet(CDatabase* pdb)
: CRecordsetEx(pdb)
{
//{{AFX_FIELD_INIT(CRulesSet)
m_SeriesID = 0;
m_RuleTypeID = 0;
m_RuleSubTypeID = 0;
m_RuleID = 0;
m_Law = 0;
m_nFields = 5;
//}}AFX_FIELD_INIT
m_nDefaultType = dynaset;
m_strIdentityColumn = _T("RuleID");
m_nIdentityColumn = &m_RuleID;
}
CString CRulesSet::GetDefaultConnect()
{
return _T("");
}
CString CRulesSet::GetDefaultSQL()
{
return _T("[Rules]");
}
void CRulesSet::DoFieldExchange(CFieldExchange* pFX)
{
//{{AFX_FIELD_MAP(CRulesSet)
pFX->SetFieldType(CFieldExchange::outputColumn);
RFX_Long(pFX, _T("[Rules].[SeriesID]"), m_SeriesID);
RFX_Long(pFX, _T("[Rules].[RuleTypeID]"), m_RuleTypeID);
RFX_Long(pFX, _T("[Rules].[RuleSubTypeID]"), m_RuleSubTypeID);
RFX_Long(pFX, _T("[Rules].[RuleID]"), m_RuleID);
RFX_Long(pFX, _T("[Rules].[Law]"), m_Law);
//}}AFX_FIELD_MAP
}
/////////////////////////////////////////////////////////////////////////////
// CRulesSet diagnostics
#ifdef _DEBUG
void CRulesSet::AssertValid() const
{
CRecordsetEx::AssertValid();
}
void CRulesSet::Dump(CDumpContext& dc) const
{
CRecordsetEx::Dump(dc);
}
#endif //_DEBUG
| 19.87013
| 77
| 0.642484
|
darianbridge
|
8b50cc1989ffefa5f1f50117c5d1f727a433be43
| 15,691
|
cpp
|
C++
|
source/write.cpp
|
luciebakels/StarPopMaker
|
2556d1531af15360f1f72d8539987aec3d6cc906
|
[
"BSD-3-Clause"
] | null | null | null |
source/write.cpp
|
luciebakels/StarPopMaker
|
2556d1531af15360f1f72d8539987aec3d6cc906
|
[
"BSD-3-Clause"
] | null | null | null |
source/write.cpp
|
luciebakels/StarPopMaker
|
2556d1531af15360f1f72d8539987aec3d6cc906
|
[
"BSD-3-Clause"
] | null | null | null |
#include <iostream>
#include <fstream>
#include <array>
#include <vector>
#include <algorithm>
#include <cstdint>
#include <cmath>
#include <sstream>
#include <random>
#include "proto.h"
#include "allvars.h"
#include "mpi.h"
void writeVector(std::vector<std::vector<double>> outputvector, std::string fileName, char x){
std::ofstream myfile;
if(x == 'w')
myfile.open(fileName, std::ofstream::out | std::ofstream::trunc);
else if(x == 'a')
myfile.open(fileName, std::ios_base::app);
for(int j = 0; j < outputvector[0].size(); j++){
for(int i = 0; i < outputvector.size(); i++){
myfile << outputvector[i][j];
if(i == outputvector.size()-1)
myfile << "\n";
else
myfile << "\t";
}
}
myfile.close();
}
void AllParticles::writeStarDataToTxt(){
std::ofstream myfile;
myfile.open("Stars.txt", std::ofstream::out | std::ofstream::trunc);
myfile << "x\ty\tz\tm\n";
for(int i = 0; i < m_star.size(); i++){
myfile << m_star[i].Pos() << m_star[i].getMass();
myfile << "\n";
}
myfile.close();
}
void AllParticles::writePositionsToTxt(int t){
std::ofstream myfile, myfilestar;
myfile.open("Positions/ParticlePositionsIon_" + std::to_string(t) + ".txt", std::ofstream::out | std::ofstream::trunc);
myfile << "x\ty\tz\tH\tHI\tHe\tHeI\tHeII\tT\n";
for(int i = 0; i < m_gas.size(); i++){
myfile << m_gas[i].Pos() << m_gas[i].speciesFrac() << m_gas[i].temperature();
myfile << "\n";
}
myfile.close();
myfilestar.open("Positions/StarPositions_" + std::to_string(t) + ".txt", std::ofstream::out | std::ofstream::trunc);
myfilestar << "\txstar\tystar\tzstar\n";
for(int i = 0; i < m_star.size(); i++){
myfilestar << m_star[i].Pos();
myfilestar << "\n";
}
myfilestar.close();
}
void AllParticles::printStars(){
for(int i = 0; i < m_star.size(); i++){
std::cout << "StarID: " << m_star[i].ID() << "\t" << m_star[i].Pos() << "\t Active: " << m_star[i].Active() << "\n";
}
}
void AllParticles::printGas(){
for(int i = 0; i < m_gas.size(); i++){
std::cout << "GasID: " << m_gas[i].ID() << "\t" << m_gas[i].Pos();
std::cout << "\t Ionized: " << m_gas[i].ionized() << " ";
std::cout << "\n";
}
}
void AllParticles::writeStarSpectra(std::string fileName){ //Mass, luminosity, lumion, Nion, acclumMol, acclumDiff, acclumInt, acclumCor
double deltaMass{((*All).MaximumMass - (*All).MinimumMass)/(*All).MassBins};
double mass{(*All).MinimumMass};
std::ofstream massfile;
massfile.open(fileName, std::ofstream::out | std::ofstream::trunc);
while(mass < (*All).MaximumMass){
Star startijdelijk(0, 0, 0, mass);
startijdelijk.assignProperties();
startijdelijk.assignIonPhotonsLum(13.6, 300);
massfile << mass << "\t" << startijdelijk.luminosity() << "\t" << startijdelijk.ionluminosity() << "\t"
<< startijdelijk.ionN();
if(mass >= 8.0){
startijdelijk.accretionLuminosity(getGasProperties(GASTYPE_MOLECULARCLOUD));
massfile << "\t" << startijdelijk.accluminosity();
startijdelijk.accretionLuminosity(getGasProperties(GASTYPE_DIFFUSECLOUD));
massfile << "\t" << startijdelijk.accluminosity();
startijdelijk.accretionLuminosity(getGasProperties(GASTYPE_INTERCLOUDMEDIUM));
massfile << "\t" << startijdelijk.accluminosity();
startijdelijk.accretionLuminosity(getGasProperties(GASTYPE_CORONALGAS));
massfile << "\t" << startijdelijk.accluminosity();
}
else{
massfile << "\t" << 0.0 << "\t" << 0.0 << "\t" << 0.0 << "\t" << 0.0;
}
massfile << "\n";
mass += deltaMass;
}
massfile.close();
}
void AllParticles::writeStarPhotons(std::string fileName){
double deltaMass{((*All).MaximumMass - (*All).MinimumMass)/(*All).MassBins};
double mass{(*All).MinimumMass}, energy{m_E[0]}, energynew{0};
std::ofstream starphotons;
starphotons.open(fileName, std::ofstream::out | std::ofstream::trunc);
while(mass < (*All).MaximumMass){
energy = m_E[0];
Star startijdelijk(0, 0, 0, mass);
startijdelijk.assignProperties();
starphotons << mass << "\t";
for(int i = 0; i < m_E.size(); i++){
if(i==(m_E.size()-1)){
if(mass< 0.5)
starphotons << 0.0;
else{
startijdelijk.assignIonPhotonsLum(energy, m_E[i]);
starphotons << startijdelijk.ionN();
}
}
else{
energynew = m_E[i+1] - (m_E[i+1]-energy)/2.0;
if( mass < 0.5){
starphotons << 0.0 << "\t";
energy = energynew;
}
else{
startijdelijk.assignIonPhotonsLum(energy, energynew);
energy = energynew;
starphotons << startijdelijk.ionN() << "\t";
}
}
}
starphotons << "\n";
mass += deltaMass;
}
starphotons.close();
}
void AllParticles::writeMasses(){
std::ofstream masses;
masses.open("AllHMXBMasses.txt", std::ofstream::out | std::ofstream::trunc);
masses << "Mass\tRemnantMass\tCompanionMass\tTemperature\tLuminosity\tIonLuminosity\n";
for(int i = 0; i < m_star.size(); i++){
if (m_star[i].type() == Star::TYPE_HMXB){
masses << m_star[i].getMass() << "\t" << m_star[i].getMassRemnant() << "\t" << m_star[i].massCompanion() << "\t" <<
m_star[i].temperature() << "\t" << m_star[i].HMXBluminosity() << "\t" << m_star[i].HMXBIonluminosity()<< "\n";
}
}
masses.close();
}
void AllParticles::writeStarPhotonsPerGasType(){
double deltaMass{((*All).MaximumMass - (*All).MinimumMass)/(*All).MassBins};
double mass{(*All).MinimumMass}, energy{m_E[0]}, energynew{0};
std::ofstream starphotM, starphotD, starphotI, starphotC;
starphotM.open("StarPhotonsM" + std::to_string(ThisTask) + ".txt", std::ofstream::out | std::ofstream::trunc);
starphotD.open("StarPhotonsD" + std::to_string(ThisTask) + ".txt", std::ofstream::out | std::ofstream::trunc);
starphotI.open("StarPhotonsI" + std::to_string(ThisTask) + ".txt", std::ofstream::out | std::ofstream::trunc);
starphotC.open("StarPhotonsC" + std::to_string(ThisTask) + ".txt", std::ofstream::out | std::ofstream::trunc);
while(mass < (*All).MaximumMass){
energy = m_E[0];
Star startijdelijk(0, 0, 0, mass);
startijdelijk.assignProperties();
std::vector<double> starphot(m_E.size()), starphotlost(m_E.size());
starphotM << mass;
starphotD << mass;
starphotI << mass;
starphotC << mass;
for(int i = 0; i < m_E.size(); i++){
if(i==(m_E.size()-1)){
if( mass < 0.5)
starphot[i] = 0.0;
else{
startijdelijk.assignIonPhotonsLum(energy, m_E[i]);
starphot[i] = startijdelijk.ionN();
}
}
else{
energynew = m_E[i+1] - (m_E[i+1]-energy)/2.0;
if( mass < 0.5){
starphot[i] = 0.0;
energy = energynew;
}
else{
startijdelijk.assignIonPhotonsLum(energy, energynew);
energy = energynew;
starphot[i] = startijdelijk.ionN();
}
}
}
starphotlost = lostPhotons(getGasProperties(GASTYPE_MOLECULARCLOUD), starphot, m_numStar);
for(int i = 0; i < m_E.size(); i++)
starphotM << "\t" << starphotlost[i];
starphotlost = lostPhotons(getGasProperties(GASTYPE_DIFFUSECLOUD), starphot, m_numStar);
for(int i = 0; i < m_E.size(); i++)
starphotD << "\t" << starphotlost[i];
starphotlost = lostPhotons(getGasProperties(GASTYPE_INTERCLOUDMEDIUM), starphot, m_numStar);
for(int i = 0; i < m_E.size(); i++)
starphotI << "\t" << starphotlost[i];
starphotlost = lostPhotons(getGasProperties(GASTYPE_CORONALGAS), starphot, m_numStar);
for(int i = 0; i < m_E.size(); i++)
starphotC << "\t" << starphotlost[i];
starphotM << "\n";
starphotD << "\n";
starphotI << "\n";
starphotC << "\n";
mass += deltaMass;
}
starphotM.close();
starphotD.close();
starphotI.close();
starphotC.close();
}
void AllParticles::addPopFiles(){
std::ofstream numfile, lumfile, massfile;
std::ofstream starmasses;
std::ofstream hmxb("HMXB.txt");
std::ofstream bh("BH.txt");
std::ofstream ns("NS.txt");
int length{static_cast<int>((*All).TotalTime/(*All).TimeStep)};
double *Time = new double[length]();
double *NewMass = new double[length]();
double *Mass = new double[length]();
double *StarMass = new double[length]();
double *HMXBMass = new double[length]();
double *LMXBMass = new double[length]();
double *BHMass = new double[length]();
double *WDMass = new double[length]();
double *SNMass = new double[length]();
double *NSMass = new double[length]();
double *Stars = new double[length]();
double *HMXBs = new double[length]();
double *LMXBs = new double[length]();
double *BH = new double[length]();
double *NS = new double[length]();
double *WD = new double[length]();
double *SN = new double[length]();
double *LumStars = new double[length]();
double *LumStars8 = new double[length]();
double *LumStarsIon = new double[length]();
double *NionStars = new double[length]();
double *LumHMXBs = new double[length]();
double *LumHMXBsIon = new double[length]();
double *NionHMXBs = new double[length]();
double *LumBH = new double[length]();
double *LumNS = new double[length]();
double *LumWD = new double[length]();
//double *Masses = new double[length]();
//double *Number = new double[length]();
for(int i = 0; i < NTask; i++){
std::ifstream f2("HMXB_" + std::to_string(i) + ".txt");
std::ifstream f3("BH_" + std::to_string(i) + ".txt");
std::ifstream f4("NS_" + std::to_string(i) + ".txt");
std::string weg;
if(i > 0){
getline(f2, weg);
getline(f3, weg);
getline(f4, weg);
}
hmxb << f2.rdbuf();
bh << f3.rdbuf();
ns << f4.rdbuf();
remove(("HMXB_" + std::to_string(i) + ".txt").c_str());
remove(("BH_" + std::to_string(i) + ".txt").c_str());
remove(("NS_" + std::to_string(i) + ".txt").c_str());
}
//Adding up the StarData files
numfile.open("NumData.txt", std::ofstream::out | std::ofstream::trunc);
lumfile.open("LumData.txt", std::ofstream::out | std::ofstream::trunc);
massfile.open("MassData.txt", std::ofstream::out | std::ofstream::trunc);
//starmasses.open("StarMass.txt", std::ofstream::out | std::ofstream::trunc);
for(int i = 0; i < NTask; i++){
double tijdelijk;
std::ifstream infile1("NumData_" + std::to_string(i) + ".txt");
for(int j = 0; j < length; j++){
std::string strInput1;
if(j == 0){
getline(infile1, strInput1);
if(i == 0)
numfile << strInput1 << "\n";
}
else{
infile1 >> Time[j-1];
infile1 >> tijdelijk;
Stars[j-1] += tijdelijk;
infile1 >> tijdelijk;
HMXBs[j-1] += tijdelijk;
infile1 >> tijdelijk;
LMXBs[j-1] += tijdelijk;
infile1 >> tijdelijk;
BH[j-1] += tijdelijk;
infile1 >> tijdelijk;
NS[j-1] += tijdelijk;
infile1 >> tijdelijk;
WD[j-1] += tijdelijk;
infile1 >> tijdelijk;
SN[j-1] += tijdelijk;
}
}
remove(("NumData_" + std::to_string(i) + ".txt").c_str());
std::ifstream infile2("LumData_" + std::to_string(i) + ".txt");
for(int j = 0; j < length; j++){
std::string strInput2;
if(j == 0){
getline(infile2, strInput2);
if(i == 0)
lumfile << strInput2 << "\n";
}
else{
infile2 >> Time[j-1];
infile2 >> tijdelijk;
LumStars[j-1] += tijdelijk;
infile2 >> tijdelijk;
LumStars8[j-1] += tijdelijk;
infile2 >> tijdelijk;
LumHMXBs[j-1] += tijdelijk;
infile2 >> tijdelijk;
LumBH[j-1] += tijdelijk;
infile2 >> tijdelijk;
LumNS[j-1] += tijdelijk;
infile2 >> tijdelijk;
LumWD[j-1] += tijdelijk;
infile2 >> tijdelijk;
LumStarsIon[j-1] += tijdelijk;
infile2 >> tijdelijk;
NionStars[j-1] += tijdelijk;
infile2 >> tijdelijk;
LumHMXBsIon[j-1] += tijdelijk;
infile2 >> tijdelijk;
NionHMXBs[j-1] += tijdelijk;
}
}
remove(("LumData_" + std::to_string(i) + ".txt").c_str());
std::ifstream infile3("MassData_" + std::to_string(i) + ".txt");
for(int j = 0; j < length; j++){
std::string strInput3;
if(j == 0){
getline(infile3, strInput3);
if(i == 0)
massfile << strInput3 << "\n";
}
else{
infile3 >> Time[j-1];
infile3 >> tijdelijk;
NewMass[j-1] += tijdelijk;
infile3 >> tijdelijk;
Mass[j-1] += tijdelijk;
infile3 >> tijdelijk;
StarMass[j-1] += tijdelijk;
infile3 >> tijdelijk;
HMXBMass[j-1] += tijdelijk;
infile3 >> tijdelijk;
LMXBMass[j-1] += tijdelijk;
infile3 >> tijdelijk;
BHMass[j-1] += tijdelijk;
infile3 >> tijdelijk;
NSMass[j-1] += tijdelijk;
infile3 >> tijdelijk;
WDMass[j-1] += tijdelijk;
infile3 >> tijdelijk;
SNMass[j-1] += tijdelijk;
}
}
remove(("MassData_" + std::to_string(i) + ".txt").c_str());
}
/*
for(int i = 0; i < NTask; i++){
double tijdelijk;
std::ifstream massin("AllStarMasses_" + std::to_string(i) + ".txt");
for(int j = 0; j < length; j++){
std::string strInput2;
if(j == 0){
getline(massin, strInput2);
if(i == 0)
starmasses << strInput2 << "\n";
}
else{
massin >> Masses[j-1];
massin >> tijdelijk;
Number[j-1] += tijdelijk;
}
}
remove(("AllStarMasses_" + std::to_string(i) + ".txt").c_str());
}
*/
for(int i = 0; i < length - 1; i++){
numfile << Time[i] << "\t" << Stars[i] << "\t" << HMXBs[i] << "\t" << LMXBs[i] << "\t"
<< BH[i] << "\t" << NS[i] << "\t" << WD[i] << "\t" << SN[i] << "\n";
}
numfile.close();
for(int i = 0; i < length - 1; i++){
lumfile << Time[i] << "\t" << LumStars[i] << "\t" << LumStars8[i] << "\t" << LumHMXBs[i] << "\t" << LumBH[i] << "\t"
<< LumNS[i] << "\t" << LumWD[i] << "\t" << LumStarsIon[i] << "\t" << NionStars[i] << "\t" << LumHMXBsIon[i] << "\t"
<< NionHMXBs[i] << "\n";
}
lumfile.close();
for(int i = 0; i < length - 1; i++){
massfile << Time[i] << "\t" << NewMass[i] << "\t" << Mass[i] << "\t" << StarMass[i] << "\t" << HMXBMass[i] << "\t"
<< LMXBMass[i] << "\t" << BHMass[i] << "\t" << NSMass[i] << "\t" << WDMass[i] << "\t" << SNMass[i] << "\n";
}
massfile.close();
delete[] Time;
delete[] NewMass;
delete[] Mass;
delete[] StarMass;
delete[] Stars;
delete[] HMXBs;
delete[] LMXBs;
delete[] BH;
delete[] NS;
delete[] WD;
delete[] SN;
delete[] HMXBMass;
delete[] LMXBMass;
delete[] BHMass;
delete[] NSMass;
delete[] WDMass;
delete[] SNMass;
delete[] NSMass;
delete[] LumStars;
delete[] LumStars8;
delete[] LumStarsIon;
delete[] NionStars;
delete[] LumHMXBs;
delete[] LumHMXBsIon;
delete[] NionHMXBs;
delete[] LumBH;
delete[] LumNS;
//delete[] Masses;
//delete[] Number;
}
| 35.024554
| 136
| 0.551463
|
luciebakels
|
8b514529904372469c8cb3e6428ab6efb43371d5
| 1,470
|
cpp
|
C++
|
src/loginserver/server/protocal/msgcpp.cpp
|
mage-game/metagame-xm-server
|
193b67389262803fe0eae742800b1e878b5b3087
|
[
"MIT"
] | 3
|
2021-12-16T13:57:28.000Z
|
2022-03-26T07:50:08.000Z
|
src/loginserver/server/protocal/msgcpp.cpp
|
mage-game/metagame-xm-server
|
193b67389262803fe0eae742800b1e878b5b3087
|
[
"MIT"
] | null | null | null |
src/loginserver/server/protocal/msgcpp.cpp
|
mage-game/metagame-xm-server
|
193b67389262803fe0eae742800b1e878b5b3087
|
[
"MIT"
] | 1
|
2022-03-26T07:50:11.000Z
|
2022-03-26T07:50:11.000Z
|
#include "servercommon/userprotocal/msgheader.h"
#include "servercommon/userprotocal/loginmsgcode.h"
#include "msglogin.h"
#include "msgregister.h"
namespace Protocol
{
CSLogin::CSLogin():header(MT_NEW_LOGIN_REQ_CS){}
SCRoleList::SCRoleList():header(MT_ROLE_LIST_SC){}
CSRoleReq::CSRoleReq():header(MT_NEW_ROLE_REQ_CS){}
SCLoginAck::SCLoginAck():header(MT_LOGIN_ACK_SC){}
SCGetThreadAck::SCGetThreadAck():header(MT_GET_THREAD_ACK_SC){}
CSPassAntiWallow::CSPassAntiWallow():header(MT_ANTI_WALLOW_CS){}
CSPassAntiWallowEx::CSPassAntiWallowEx():header(MT_ANTI_WALLOW_EX_CS){}
SCAntiWallowRet::SCAntiWallowRet():header(MT_ANTI_WALLOW_EX_RET_SC){}
SCAccountKeyError::SCAccountKeyError():header(MT_ACCOUNT_KEY_ERROR_SC){}
SCMergeRoleList::SCMergeRoleList():header(MT_MERGE_ROLE_LIST_SC){}
SCProfNumInfo::SCProfNumInfo() : header(MT_PROF_NUM_INFO_SC) {}
SCLHeartBeat::SCLHeartBeat() : header(MT_L_HEARTBEAT_SC) {}
CSCreateRole::CSCreateRole():header(MT_CREATE_ROLE_REQ_CS){}
SCCreateRoleAck::SCCreateRoleAck():header(MT_CREATE_ROLE_ACK_SC){}
CSDestroyRole::CSDestroyRole():header(MT_DESTROY_ROLE_REQ_CS){}
SCDestroyRoleAck::SCDestroyRoleAck():header(MT_DESTROY_ROLE_ACK_SC){}
CSGetThreadInfo::CSGetThreadInfo():header(MT_GET_TREAD_CS){}
CSChangePlatName::CSChangePlatName():header(MT_CHANGE_PLATNAME_REQ_CS) {}
SCChangePlatNameAck::SCChangePlatNameAck():header(MT_CHANGE_PLATNAME_ACK_SC) {}
CSLHeartBeat::CSLHeartBeat():header(MT_L_HEARTBEAT_CS){};
}
| 43.235294
| 80
| 0.817007
|
mage-game
|
8b58c243dbee99b83a3fc229d6075c3697765a90
| 2,994
|
hpp
|
C++
|
libraries/include/TRG.hpp
|
JoyM1K1/o3-sigma-model-TRG
|
2bbb5db3f5ea523e4dfb8a0b469e303abd9e563b
|
[
"MIT"
] | null | null | null |
libraries/include/TRG.hpp
|
JoyM1K1/o3-sigma-model-TRG
|
2bbb5db3f5ea523e4dfb8a0b469e303abd9e563b
|
[
"MIT"
] | null | null | null |
libraries/include/TRG.hpp
|
JoyM1K1/o3-sigma-model-TRG
|
2bbb5db3f5ea523e4dfb8a0b469e303abd9e563b
|
[
"MIT"
] | null | null | null |
#ifndef O3_SIGMA_MODEL_TRG_HPP
#define O3_SIGMA_MODEL_TRG_HPP
#include "tensor.hpp"
#include "impure_tensor.hpp"
#define MAX_IMT_NUM 6
namespace TRG {
class Unitary_S {
public:
double *array{nullptr};
int D_cut{0};
Unitary_S() = default;
explicit Unitary_S(int D_cut);
~Unitary_S();
};
class Tensor : public BaseTensor {
public:
std::pair<Unitary_S *, Unitary_S *> S{std::make_pair(nullptr, nullptr)};
Tensor() : BaseTensor() {};
explicit Tensor(int D_cut) : BaseTensor(D_cut) {};
Tensor(int D, int D_max) : BaseTensor(D, D_max) {};
Tensor(int Di, int Dj, int Dk, int Dl) : BaseTensor(Di, Dj, Dk, Dl) {};
Tensor(int Di, int Dj, int Dk, int Dl, int D_max) : BaseTensor(Di, Dj, Dk, Dl, D_max) {};
~Tensor();
Tensor &operator=(const Tensor &rhs);
};
class ImpureTensor : public BaseImpureTensor<Tensor> {
public:
ImpureTensor() : BaseImpureTensor<Tensor>() {};
explicit ImpureTensor(int D) : BaseImpureTensor<Tensor>(D) {};
ImpureTensor(int D, int D_max) : BaseImpureTensor<Tensor>(D, D_max) {};
ImpureTensor(int Di, int Dj, int Dk, int Dl) : BaseImpureTensor<Tensor>(Di, Dj, Dk, Dl) {};
ImpureTensor(int Di, int Dj, int Dk, int Dl, int D_max) : BaseImpureTensor<Tensor>(Di, Dj, Dk, Dl, D_max) {};
ImpureTensor(int d, BaseImpureTensor<Tensor> &T) : BaseImpureTensor<Tensor>(d, T) {};
explicit ImpureTensor(BaseImpureTensor<Tensor> &rhs) : BaseImpureTensor<Tensor>(rhs) {};
};
void SVD(Tensor &T, bool is_default, bool is_odd_times);
void contraction(Tensor &T, Tensor &T1, Tensor &T2, Tensor &T3, Tensor &T4);
void initialize_spherical_harmonics(Tensor &T1, Tensor &T2, const int &D, const int &D_cut, const double &beta, const int &l_max);
void initialize_gauss_quadrature(Tensor &T1, Tensor &T2, const int &D, const int &D_cut, const double &beta, const int &n_node);
void
initialize_spherical_harmonics_with_impure(Tensor &T1, Tensor &T2, ImpureTensor (&IMTs)[MAX_IMT_NUM], const int &D, const int &D_cut, const double &beta, const int &l_max, const int &merge_point);
void
initialize_gauss_quadrature_with_impure(Tensor &T1, Tensor &T2, ImpureTensor (&IMTs)[MAX_IMT_NUM], const int &D, const int &D_cut, const double &beta, const int &n_node, const int &merge_point);
void allocate_tensor(Tensor &T, const int &D, const int &D_cut);
namespace renormalization {
double partition(Tensor &T1, Tensor &T2, long long int *orders, const int &n, const int &normalize_factor);
void
two_point(Tensor &T1, Tensor &T2, ImpureTensor (&IMTs)[MAX_IMT_NUM], long long *orders, const int &N, const int &n, const int &merge_point, const int &normalize_factor);
void trace(Tensor &T, ImpureTensor &IMT, const long long *orders, const int &normalize_factor, double *res);
}
}
#endif //O3_SIGMA_MODEL_TRG_HPP
| 35.223529
| 200
| 0.663661
|
JoyM1K1
|
8b599406e69a9e3ef7e8e5aa1549aa2b976d5efc
| 1,292
|
cpp
|
C++
|
lyngvi.cpp
|
TuliMyrskyTaivas/Lyngvi
|
c96a4c06b743e64cb83045f3fdb4d9271f184dca
|
[
"MIT"
] | null | null | null |
lyngvi.cpp
|
TuliMyrskyTaivas/Lyngvi
|
c96a4c06b743e64cb83045f3fdb4d9271f184dca
|
[
"MIT"
] | null | null | null |
lyngvi.cpp
|
TuliMyrskyTaivas/Lyngvi
|
c96a4c06b743e64cb83045f3fdb4d9271f184dca
|
[
"MIT"
] | null | null | null |
//////////////////////////////////////////////////////////////////////////
/// file: lyngvi.cpp
///
/// summary: Declares the interface of Lyngvi library
//////////////////////////////////////////////////////////////////////////
#include <stdexcept>
#include <memory>
#include "lyngvi.h"
#include "engine.h"
namespace lyngvi
{
static std::unique_ptr<Engine> engine;
//////////////////////////////////////////////////////////////////////////
void Initialize(cstr locDir)
{
if (engine)
throw std::logic_error("lyngvi was already initialized");
engine.reset(new Engine(locDir));
}
//////////////////////////////////////////////////////////////////////////
void LoadModule(cstr name)
{
if (!engine)
throw std::logic_error("lyngvi is not initialized");
engine->LoadModule(name);
}
//////////////////////////////////////////////////////////////////////////
void EnableLogging(LogCallback cb, LogLevel what)
{
if (!engine)
throw std::logic_error("lyngvi is not initialized");
engine->EnableLogging(cb, what);
}
//////////////////////////////////////////////////////////////////////////
cstr GetText(cstr const module, cstr text)
{
if (!engine)
throw std::logic_error("lyngvi is not initialized");
return engine->GetTranslation(module, text);
}
} // namespace lyngvi
| 23.925926
| 74
| 0.466718
|
TuliMyrskyTaivas
|
8b65c0eb676f25db20525f00c9a024266ebbf283
| 328
|
inl
|
C++
|
shared/test/unit_test/helpers/test_debug_variables.inl
|
troels/compute-runtime
|
3269e719a3ee7bcd97c50ec2cfe78fc8674adec0
|
[
"Intel",
"MIT"
] | 778
|
2017-09-29T20:02:43.000Z
|
2022-03-31T15:35:28.000Z
|
shared/test/unit_test/helpers/test_debug_variables.inl
|
troels/compute-runtime
|
3269e719a3ee7bcd97c50ec2cfe78fc8674adec0
|
[
"Intel",
"MIT"
] | 478
|
2018-01-26T16:06:45.000Z
|
2022-03-30T10:19:10.000Z
|
shared/test/unit_test/helpers/test_debug_variables.inl
|
troels/compute-runtime
|
3269e719a3ee7bcd97c50ec2cfe78fc8674adec0
|
[
"Intel",
"MIT"
] | 215
|
2018-01-30T08:39:32.000Z
|
2022-03-29T11:08:51.000Z
|
/*
* Copyright (C) 2018-2021 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
DECLARE_DEBUG_VARIABLE(std::string, StringTestKey, "DefaultTestValue", "TestDescription")
DECLARE_DEBUG_VARIABLE(int32_t, IntTestKey, 1234, "TestDescription")
DECLARE_DEBUG_VARIABLE(int32_t, IntTestKeyHex, 0xDEADBEEF, "TestDescription")
| 29.818182
| 89
| 0.786585
|
troels
|
8b69da557790d2e4735301bcc84805eeacc179ca
| 343
|
hpp
|
C++
|
include/graphics/SkyboxRenderableHandle.hpp
|
icebreakersentertainment/ice_engine
|
52a8313bc266c053366bdf554b5dc27a54ddcb25
|
[
"MIT"
] | null | null | null |
include/graphics/SkyboxRenderableHandle.hpp
|
icebreakersentertainment/ice_engine
|
52a8313bc266c053366bdf554b5dc27a54ddcb25
|
[
"MIT"
] | null | null | null |
include/graphics/SkyboxRenderableHandle.hpp
|
icebreakersentertainment/ice_engine
|
52a8313bc266c053366bdf554b5dc27a54ddcb25
|
[
"MIT"
] | 1
|
2019-06-11T03:41:48.000Z
|
2019-06-11T03:41:48.000Z
|
#ifndef SKYBOX_RENDERABLE_HANDLE_H_
#define SKYBOX_RENDERABLE_HANDLE_H_
#include "handles/Handle.hpp"
namespace ice_engine
{
namespace graphics
{
class SkyboxRenderableHandle : public handles::Handle<SkyboxRenderableHandle>
{
public:
using handles::Handle<SkyboxRenderableHandle>::Handle;
};
}
}
#endif /* SKYBOX_RENDERABLE_HANDLE_H_ */
| 16.333333
| 77
| 0.80758
|
icebreakersentertainment
|
8b703848037ac226361563e2b14a884961f63faa
| 20,078
|
hpp
|
C++
|
Source/GRChomboCore/ChomboParameters.hpp
|
Scientistwang/GRChombo_Zipeng
|
cd7aeb9ce0d67422e769b9c2072afafb0b9a2659
|
[
"BSD-3-Clause"
] | null | null | null |
Source/GRChomboCore/ChomboParameters.hpp
|
Scientistwang/GRChombo_Zipeng
|
cd7aeb9ce0d67422e769b9c2072afafb0b9a2659
|
[
"BSD-3-Clause"
] | null | null | null |
Source/GRChomboCore/ChomboParameters.hpp
|
Scientistwang/GRChombo_Zipeng
|
cd7aeb9ce0d67422e769b9c2072afafb0b9a2659
|
[
"BSD-3-Clause"
] | null | null | null |
/* GRChombo
* Copyright 2012 The GRChombo collaboration.
* Please refer to LICENSE in GRChombo's root directory.
*/
#ifndef CHOMBOPARAMETERS_HPP_
#define CHOMBOPARAMETERS_HPP_
// General includes
#include "BoundaryConditions.hpp"
#include "GRParmParse.hpp"
#include "UserVariables.hpp"
#include "VariableType.hpp"
#include <algorithm>
class ChomboParameters
{
public:
ChomboParameters(GRParmParse &pp) { read_params(pp); }
void read_params(GRParmParse &pp)
{
pp.load("verbosity", verbosity, 0);
// Grid setup
pp.load("regrid_threshold", regrid_threshold, 0.5);
pp.load("num_ghosts", num_ghosts, 3);
pp.load("tag_buffer_size", tag_buffer_size, 3);
pp.load("dt_multiplier", dt_multiplier, 0.25);
pp.load("fill_ratio", fill_ratio, 0.7);
// Periodicity and boundaries
pp.load("isPeriodic", isPeriodic, {true, true, true});
read_boundary_params(pp);
// Setup the grid size
std::array<int, CH_SPACEDIM> Ni_full;
std::array<int, CH_SPACEDIM> Ni;
ivN = IntVect::Unit;
// cannot contain both
if ((pp.contains("N_full") && pp.contains("N")))
MayDay::Error("Please only provide 'N' or 'N_full', not both");
int N_full = -1;
int N = -1;
if (pp.contains("N_full"))
pp.load("N_full", N_full);
else if (pp.contains("N"))
pp.load("N", N);
// read all options (N, N_full, Ni_full and Ni) and then choose
// accordingly
FOR1(dir)
{
std::string name = ("N" + std::to_string(dir + 1));
std::string name_full = ("N" + std::to_string(dir + 1) + "_full");
Ni_full[dir] = -1;
Ni[dir] = -1;
// only one of them exists - this passes if none of the 4 exist, but
// that is asserted below
if (!((N_full > 0 || N > 0) && !pp.contains(name.c_str()) &&
!pp.contains(name_full.c_str())) &&
!((N_full < 0 && N < 0) && !(pp.contains(name.c_str()) &&
pp.contains(name_full.c_str()))))
MayDay::Error("Please provide 'N' or 'N_full' or a set of "
"'N1/N1_full', 'N2/N2_full', 'N3/N3_full'");
if (N_full < 0 && N < 0)
{
if (pp.contains(name_full.c_str()))
pp.load(name_full.c_str(), Ni_full[dir]);
else
pp.load(name.c_str(), Ni[dir]);
}
if (N < 0 && N_full < 0 && Ni[dir] < 0 &&
Ni_full[dir] < 0) // sanity check
MayDay::Error("Please provide 'N' or 'N_full' or a set of "
"'N1/N1_full', 'N2/N2_full', 'N3/N3_full'");
if (N_full > 0)
Ni_full[dir] = N_full;
else if (N > 0)
Ni[dir] = N;
if (Ni[dir] > 0)
{
if (boundary_params.lo_boundary[dir] ==
BoundaryConditions::REFLECTIVE_BC ||
boundary_params.hi_boundary[dir] ==
BoundaryConditions::REFLECTIVE_BC)
Ni_full[dir] = Ni[dir] * 2;
else
Ni_full[dir] = Ni[dir];
}
else
{
if (boundary_params.lo_boundary[dir] ==
BoundaryConditions::REFLECTIVE_BC ||
boundary_params.hi_boundary[dir] ==
BoundaryConditions::REFLECTIVE_BC)
{
if (Ni_full[dir] % 2 != 0) // Ni_full is even
MayDay::Error("N's should be even when applying "
"reflective boundary conditions");
Ni[dir] = Ni_full[dir] / 2;
}
else
Ni[dir] = Ni_full[dir];
}
ivN[dir] = Ni[dir] - 1;
}
int max_N_full = *std::max_element(Ni_full.begin(), Ni_full.end());
int max_N = ivN.max() + 1;
// Grid L
// cannot contain both
if ((pp.contains("L_full") && pp.contains("L")))
MayDay::Error("Please only provide 'L' or 'L_full', not both");
double L_full = -1.;
if (pp.contains("L_full"))
pp.load("L_full", L_full);
else
pp.load("L", L, 1.0);
if (L_full > 0.)
// necessary for some reflective BC cases, as 'L' is the
// length of the longest side of the box
L = (L_full * max_N) / max_N_full;
coarsest_dx = L / max_N;
// extraction params
dx.fill(coarsest_dx);
origin.fill(coarsest_dx / 2.0);
// Grid center
// now that L is surely set, get center
pp.load("center", center,
{0.5 * Ni[0] * coarsest_dx, 0.5 * Ni[1] * coarsest_dx,
0.5 * Ni[2] * coarsest_dx}); // default to center
FOR1(idir)
{
if ((boundary_params.lo_boundary[idir] ==
BoundaryConditions::REFLECTIVE_BC) &&
(boundary_params.hi_boundary[idir] !=
BoundaryConditions::REFLECTIVE_BC))
center[idir] = 0.;
else if ((boundary_params.hi_boundary[idir] ==
BoundaryConditions::REFLECTIVE_BC) &&
(boundary_params.lo_boundary[idir] !=
BoundaryConditions::REFLECTIVE_BC))
center[idir] = coarsest_dx * Ni[idir];
}
pout() << "Center has been set to: ";
FOR1(idir) { pout() << center[idir] << " "; }
pout() << endl;
// Misc
pp.load("ignore_checkpoint_name_mismatch",
ignore_checkpoint_name_mismatch, false);
pp.load("max_level", max_level, 0);
// the reference ratio is hard coded to 2 on all levels
// in principle it can be set to other values, but this is
// not recommended since we do not test GRChombo with other
// refinement ratios - use other values at your own risk
ref_ratios.resize(max_level + 1);
ref_ratios.assign(2);
// read in frequency of regrid on each levels, needs
// max_level + 1 entries (although never regrids on max_level+1)
pp.getarr("regrid_interval", regrid_interval, 0, max_level + 1);
// time stepping outputs and regrid data
pp.load("checkpoint_interval", checkpoint_interval, 1);
pp.load("chk_prefix", checkpoint_prefix);
pp.load("plot_interval", plot_interval, 0);
pp.load("plot_prefix", plot_prefix);
pp.load("stop_time", stop_time, 1.0);
pp.load("max_steps", max_steps, 1000000);
pp.load("write_plot_ghosts", write_plot_ghosts, false);
// load vars to write to plot files
load_vars_to_vector(pp, "plot_vars", "num_plot_vars", plot_vars,
num_plot_vars);
// alias the weird chombo names to something more descriptive
// for these box params, and default to some reasonable values
if (pp.contains("max_grid_size"))
{
pp.load("max_grid_size", max_grid_size);
}
else
{
pp.load("max_box_size", max_grid_size, 64);
}
if (pp.contains("block_factor"))
{
pp.load("block_factor", block_factor);
}
else
{
pp.load("min_box_size", block_factor, 8);
}
// Chombo already has an error for this, but when applying symmetric BC
// this may help the user figure the problem more easily (e.g. N_full=48
// with block_factor=16 seems fine, but with symmetric BC it's not, as
// the box will use N=24)
FOR1(dir)
{
if (Ni[dir] % block_factor != 0)
{
if (boundary_params.lo_boundary[dir] ==
BoundaryConditions::REFLECTIVE_BC ||
boundary_params.hi_boundary[dir] ==
BoundaryConditions::REFLECTIVE_BC)
{
MayDay::Error(
("N" + std::to_string(dir + 1) + " (or half of N" +
std::to_string(dir + 1) +
"_full) should be a multiple of block_factor.")
.c_str());
}
else
MayDay::Error(("N" + std::to_string(dir + 1) +
" should be a multiple of block_factor")
.c_str());
}
}
}
// read in of the boundary conditions - this is quite long
// so kept separate for readability
void read_boundary_params(GRParmParse &pp)
{
// default to static BCs if unspecified in params
int bc = BoundaryConditions::STATIC_BC;
pp.load("hi_boundary", boundary_params.hi_boundary, {bc, bc, bc});
pp.load("lo_boundary", boundary_params.lo_boundary, {bc, bc, bc});
// set defaults, then override them where appropriate
boundary_params.vars_parity.fill(BoundaryConditions::EVEN);
boundary_params.vars_asymptotic_values.fill(0.0);
boundary_params.is_periodic.fill(true);
boundary_params.extrapolation_order = 0;
nonperiodic_boundaries_exist = false;
boundary_solution_enforced = false;
boundary_params.mixed_bc_extrapolating_vars.clear();
boundary_params.mixed_bc_sommerfeld_vars.clear();
FOR1(idir)
{
if (isPeriodic[idir] == false)
{
nonperiodic_boundaries_exist = true;
boundary_params.is_periodic[idir] = false;
// read in relevent params - note that no defaults are set so as
// to force the user to specify them where the relevant BCs are
// selected
if ((boundary_params.hi_boundary[idir] ==
BoundaryConditions::REFLECTIVE_BC) ||
(boundary_params.lo_boundary[idir] ==
BoundaryConditions::REFLECTIVE_BC))
{
boundary_solution_enforced = true;
pp.load("vars_parity", boundary_params.vars_parity);
}
if ((boundary_params.hi_boundary[idir] ==
BoundaryConditions::EXTRAPOLATING_BC) ||
(boundary_params.lo_boundary[idir] ==
BoundaryConditions::EXTRAPOLATING_BC) ||
(boundary_params.hi_boundary[idir] ==
BoundaryConditions::MIXED_BC) ||
(boundary_params.lo_boundary[idir] ==
BoundaryConditions::MIXED_BC))
{
boundary_solution_enforced = true;
pp.load("extrapolation_order",
boundary_params.extrapolation_order, 1);
}
if ((boundary_params.hi_boundary[idir] ==
BoundaryConditions::SOMMERFELD_BC) ||
(boundary_params.lo_boundary[idir] ==
BoundaryConditions::SOMMERFELD_BC) ||
(boundary_params.hi_boundary[idir] ==
BoundaryConditions::MIXED_BC) ||
(boundary_params.lo_boundary[idir] ==
BoundaryConditions::MIXED_BC))
{
int num_values = -1;
std::vector<std::pair<int, VariableType>>
nonzero_asymptotic_vars;
load_vars_to_vector(pp, "nonzero_asymptotic_vars",
"num_nonzero_asymptotic_vars",
nonzero_asymptotic_vars, num_values);
const double default_value = 0.0;
load_values_to_array(pp, "nonzero_asymptotic_values",
nonzero_asymptotic_vars,
boundary_params.vars_asymptotic_values,
default_value);
// for backwards compatibility, but above method should
// be preferred in future
if (num_values == -1)
{
pp.load("vars_asymptotic_values",
boundary_params.vars_asymptotic_values);
}
}
if ((boundary_params.hi_boundary[idir] ==
BoundaryConditions::MIXED_BC) ||
(boundary_params.lo_boundary[idir] ==
BoundaryConditions::MIXED_BC))
{
// only read in these params once, even if specified in
// several directions. They must be the same for all.
if (boundary_params.mixed_bc_extrapolating_vars.size() == 0)
{
// if not yet done, read in the mixed conditions
int num_extrapolating_vars = 0;
std::vector<std::pair<int, VariableType>>
extrapolating_vars;
load_vars_to_vector(
pp, "extrapolating_vars", "num_extrapolating_vars",
extrapolating_vars, num_extrapolating_vars);
for (int icomp = 0; icomp < NUM_VARS; icomp++)
{
bool is_extrapolating = false;
// if the variable is not in extrapolating vars, it
// is assumed to be sommerfeld by default
for (int icomp2 = 0;
icomp2 < extrapolating_vars.size(); icomp2++)
{
if (icomp == extrapolating_vars[icomp2].first)
{
// should be an evolution variable
CH_assert(
extrapolating_vars[icomp2].second ==
VariableType::evolution);
boundary_params.mixed_bc_extrapolating_vars
.push_back(icomp);
is_extrapolating = true;
}
}
if (!is_extrapolating)
{
boundary_params.mixed_bc_sommerfeld_vars
.push_back(icomp);
}
}
}
}
}
}
// write out boundary conditions where non periodic - useful for debug
if (nonperiodic_boundaries_exist)
{
BoundaryConditions::write_boundary_conditions(boundary_params);
}
}
// function to create a vector of enums of vars by reading in their
// names as strings from the params file and converting it to the enums
void load_vars_to_vector(
GRParmParse &pp, const char *a_vars_vector_string,
const char *a_vector_size_string,
std::vector<std::pair<int, VariableType>> &a_vars_vector,
int &a_vars_vector_size)
{
int num_values;
pp.load(a_vector_size_string, num_values, -1);
// only set a_vars_vector and a_var_vector_size if a_vector_size_string
// found
if (num_values >= 0)
{
std::vector<std::string> var_names(num_values, "");
pp.load(a_vars_vector_string, var_names, num_values, var_names);
for (std::string var_name : var_names)
{
// first assume plot_var is a normal evolution var
int var = UserVariables::variable_name_to_enum(var_name);
VariableType var_type = VariableType::evolution;
if (var < 0)
{
// if not an evolution var check if it's a diagnostic var
var = DiagnosticVariables::variable_name_to_enum(var_name);
if (var < 0)
{
// it's neither :(
pout() << "Variable with name " << var_name
<< " not found." << endl;
}
else
{
var_type = VariableType::diagnostic;
}
}
if (var >= 0)
{
a_vars_vector.emplace_back(var, var_type);
}
}
// overwrites read in value if entries have been ignored
a_vars_vector_size = a_vars_vector.size();
}
}
// where one has read in a subset of variables with some feature
// this reads in a set of associated values and assigns it into a full
// array of all NUM_VARS vars (setting other values to a default value)
template <class T>
void load_values_to_array(
GRParmParse &pp, const char *a_values_vector_string,
const std::vector<std::pair<int, VariableType>> &a_vars_vector,
std::array<double, NUM_VARS> &a_values_array, const T a_default_value)
{
// how many values do I need to get?
int num_values = a_vars_vector.size();
// make a container for them, and load
std::vector<T> vars_values(num_values, a_default_value);
pp.load(a_values_vector_string, vars_values, num_values, vars_values);
// populate the values_array for the NUM_VARS values with those read in
a_values_array.fill(a_default_value);
for (int i = 0; i < num_values; i++)
{
int icomp = a_vars_vector[i].first;
CH_assert(a_vars_vector[i].second == VariableType::evolution);
a_values_array[icomp] = vars_values[i];
}
}
// General parameters
int verbosity;
double L; // Physical sidelength of the grid
std::array<double, CH_SPACEDIM> center; // grid center
IntVect ivN; // The number of grid cells in each dimension
double coarsest_dx; // The coarsest resolution
int max_level; // the max number of regriddings to do
int num_ghosts; // must be at least 3 for KO dissipation
int tag_buffer_size; // Amount the tagged region is grown by
Vector<int> ref_ratios; // ref ratios between levels
Vector<int> regrid_interval; // steps between regrid at each level
int max_steps;
bool ignore_checkpoint_name_mismatch; // ignore mismatch of variable names
// between restart file and program
double dt_multiplier, stop_time; // The Courant factor and stop time
int checkpoint_interval, plot_interval; // Steps between outputs
int max_grid_size, block_factor; // max and min box sizes
double fill_ratio; // determines how fussy the regridding is about tags
std::string checkpoint_prefix, plot_prefix; // naming of files
bool write_plot_ghosts;
int num_plot_vars;
std::vector<std::pair<int, VariableType>>
plot_vars; // vars to write to plot file
std::array<double, CH_SPACEDIM> origin,
dx; // location of coarsest origin and dx
// Boundary conditions
std::array<bool, CH_SPACEDIM> isPeriodic; // periodicity
BoundaryConditions::params_t boundary_params; // set boundaries in each dir
bool nonperiodic_boundaries_exist;
bool boundary_solution_enforced;
// For tagging
double regrid_threshold;
};
#endif /* CHOMBOPARAMETERS_HPP_ */
| 42.269474
| 80
| 0.519275
|
Scientistwang
|
8b729a8666035d79368fb48b4f40bdbea30151d9
| 1,218
|
hpp
|
C++
|
FileFormats/Bif/Bif_Friendly.hpp
|
xloss/NWNFileFormats
|
0b3fd4fba416bcdb79f4d898a40a4107234ceea0
|
[
"WTFPL"
] | 9
|
2018-03-02T17:03:43.000Z
|
2021-09-02T13:26:04.000Z
|
FileFormats/Bif/Bif_Friendly.hpp
|
xloss/NWNFileFormats
|
0b3fd4fba416bcdb79f4d898a40a4107234ceea0
|
[
"WTFPL"
] | 8
|
2018-03-04T09:20:46.000Z
|
2020-12-06T04:28:33.000Z
|
FileFormats/Bif/Bif_Friendly.hpp
|
xloss/NWNFileFormats
|
0b3fd4fba416bcdb79f4d898a40a4107234ceea0
|
[
"WTFPL"
] | 8
|
2018-03-04T09:18:49.000Z
|
2020-12-01T01:15:41.000Z
|
#pragma once
#include "FileFormats/Bif/Bif_Raw.hpp"
#include <memory>
#include <optional>
#include <unordered_map>
namespace FileFormats::Bif::Friendly {
struct BifResource
{
// The actual ID listed in the BIF.
std::uint32_t m_ResId;
// The resource type.
Resource::ResourceType m_ResType;
// The underlying data for this resource.
std::unique_ptr<DataBlock> m_DataBlock;
};
// This is a user friendly wrapper around the Bif data.
// NOTE: We ignore the fixed resource table as it is not implemented per the spec.
class Bif
{
public:
// This constructs a friendly BIF from a raw BIF.
Bif(Raw::Bif const& rawBif);
// This constructs a friendly BIF from a raw BIF whose ownership has been passed to us.
// If ownership of the Bif is passed to us, we construct streamed resources, thus lowering
// the memory usage significantly.
Bif(Raw::Bif&& rawBif);
using BifResourceMap = std::unordered_map<std::uint32_t, BifResource>;
BifResourceMap const& GetResources() const;
private:
std::optional<Raw::Bif> m_RawBif;
void ConstructInternal(Raw::Bif const& rawBif);
// This maps between ID -> { BifResource }
BifResourceMap m_Resources;
};
}
| 24.857143
| 94
| 0.707718
|
xloss
|
8b76c86372c3b9cdedba64fe695ade9dccf143a6
| 8,164
|
cpp
|
C++
|
src/imr_cases.cpp
|
joshia5/ayj-omega_h
|
8b65215013df29af066fa076261ba897d64a72c2
|
[
"BSD-2-Clause-FreeBSD"
] | 44
|
2019-01-23T03:37:18.000Z
|
2021-08-24T02:20:29.000Z
|
src/imr_cases.cpp
|
joshia5/ayj-omega_h
|
8b65215013df29af066fa076261ba897d64a72c2
|
[
"BSD-2-Clause-FreeBSD"
] | 67
|
2019-01-29T15:35:42.000Z
|
2021-08-17T20:42:40.000Z
|
src/imr_cases.cpp
|
joshia5/ayj-omega_h
|
8b65215013df29af066fa076261ba897d64a72c2
|
[
"BSD-2-Clause-FreeBSD"
] | 29
|
2019-01-14T21:33:32.000Z
|
2021-08-10T11:35:24.000Z
|
#include "Omega_h_adapt.hpp"
#include "Omega_h_file.hpp"
#include "Omega_h_for.hpp"
#include "Omega_h_laplace.hpp"
#include "Omega_h_map.hpp"
#include "Omega_h_mesh.hpp"
#include "Omega_h_metric.hpp"
#include "Omega_h_timer.hpp"
#include "Omega_h_vector.hpp"
#include <iostream>
#include <set>
using namespace Omega_h;
struct Case {
virtual ~Case();
virtual const char* file_name() const = 0;
virtual std::vector<I32> objects() const = 0;
virtual Int time_steps() const = 0;
virtual Reals motion(Mesh* m, Int step, I32 object, LOs ov2v) const = 0;
};
Case::~Case() {}
struct TranslateBall : public Case {
~TranslateBall() override;
virtual const char* file_name() const override { return "ball_in_cube.msh"; }
virtual std::vector<I32> objects() const override {
return std::vector<I32>({72});
}
virtual Int time_steps() const override { return 12; }
virtual Reals motion(Mesh* m, Int step, I32 object, LOs ov2v) const override {
(void)m;
(void)step;
(void)object;
return static_motion(ov2v);
}
static Reals static_motion(LOs ov2v) {
auto out = Write<Real>(ov2v.size() * 3);
auto f = OMEGA_H_LAMBDA(LO ov) {
set_vector<3>(out, ov, vector_3(0.02, 0, 0));
};
parallel_for(ov2v.size(), f);
return out;
}
};
TranslateBall::~TranslateBall() {}
struct RotateBall : public Case {
~RotateBall() override;
virtual const char* file_name() const override { return "ball_in_cube.msh"; }
virtual std::vector<I32> objects() const override {
return std::vector<I32>({72});
}
virtual Int time_steps() const override { return 16; }
virtual Reals motion(Mesh* m, Int step, I32 object, LOs ov2v) const override {
(void)step;
(void)object;
return static_motion(m, ov2v);
}
static Reals static_motion(Mesh* m, LOs ov2v) {
auto coords = m->coords();
auto out = Write<Real>(ov2v.size() * 3);
auto rot = rotate(PI / 16, vector_3(0, 0, 1));
auto f = OMEGA_H_LAMBDA(LO ov) {
auto v = ov2v[ov];
auto x = get_vector<3>(coords, v);
auto mid = vector_3(.5, .5, 0);
x = x - mid;
auto x2 = rot * x;
auto w = x2 - x;
set_vector<3>(out, ov, w);
};
parallel_for(ov2v.size(), f);
return out;
}
};
RotateBall::~RotateBall() {}
struct CollideBalls : public Case {
~CollideBalls() override;
virtual const char* file_name() const override { return "balls_in_box.msh"; }
virtual std::vector<I32> objects() const override {
return std::vector<I32>({72, 110});
}
virtual Int time_steps() const override { return 12; }
virtual Reals motion(Mesh* m, Int step, I32 object, LOs ov2v) const override {
(void)m;
(void)step;
return static_motion(object, ov2v);
}
static Reals static_motion(I32 object, LOs ov2v) {
auto out = Write<Real>(ov2v.size() * 3);
auto f = OMEGA_H_LAMBDA(LO ov) {
if (object == 72) {
set_vector<3>(out, ov, vector_3(0, 0, 0.02));
} else {
set_vector<3>(out, ov, vector_3(0, 0, -0.02));
}
};
parallel_for(ov2v.size(), f);
return out;
}
};
CollideBalls::~CollideBalls() {}
struct CylinderTube : public Case {
~CylinderTube() override;
virtual const char* file_name() const override {
return "cylinder_thru_tube.msh";
}
virtual std::vector<I32> objects() const override {
return std::vector<I32>({73});
}
virtual Int time_steps() const override { return 12; }
virtual Reals motion(Mesh* m, Int step, I32 object, LOs ov2v) const override {
(void)m;
(void)step;
(void)object;
return static_motion(ov2v);
}
static Reals static_motion(LOs ov2v) {
auto out = Write<Real>(ov2v.size() * 3);
auto f = OMEGA_H_LAMBDA(LO ov) {
set_vector<3>(out, ov, vector_3(0, 0, 0.02));
};
parallel_for(ov2v.size(), f);
return out;
}
};
CylinderTube::~CylinderTube() {}
struct TwinRotor : public Case {
std::set<I32> assembly0;
std::set<I32> assembly1;
TwinRotor() : assembly0({66, 98, 126}), assembly1({254, 253, 252}) {}
~TwinRotor() override;
virtual const char* file_name() const override { return "twin_rotor.msh"; }
virtual std::vector<I32> objects() const override {
std::vector<I32> out;
out.insert(out.end(), assembly0.begin(), assembly0.end());
out.insert(out.end(), assembly1.begin(), assembly1.end());
return out;
}
virtual Int time_steps() const override { return 16; }
virtual Reals motion(Mesh* m, Int step, I32 object, LOs ov2v) const override {
(void)step;
Vector<3> center;
Real dir;
if (assembly0.count(object)) {
center = vector_3(-.25, 0, 0);
dir = 1.0;
} else if (assembly1.count(object)) {
center = vector_3(.25, 0, 0);
dir = -1.0;
} else {
Omega_h_fail("object %d not in either assembly\n", object);
}
return static_motion(m, ov2v, center, dir);
}
static Reals static_motion(Mesh* m, LOs ov2v, Vector<3> center, Real dir) {
auto coords = m->coords();
auto out = Write<Real>(ov2v.size() * 3);
auto rm = rotate(dir * PI / 32, vector_3(0, 0, 1));
auto f = OMEGA_H_LAMBDA(LO ov) {
auto v = ov2v[ov];
auto x = get_vector<3>(coords, v);
set_vector(out, ov, ((rm * (x - center)) + center) - x);
};
parallel_for(ov2v.size(), f);
return out;
}
};
TwinRotor::~TwinRotor() {}
static void run_case(Library* lib, Case const& c, Int niters) {
if (niters == -1) {
niters = c.time_steps();
} else {
OMEGA_H_CHECK(niters >= 0);
if (niters > c.time_steps()) {
std::cerr << "warning: requesting " << niters
<< " time steps but the case is designed for " << c.time_steps()
<< '\n';
}
}
auto world = lib->world();
auto mesh = gmsh::read(c.file_name(), world);
mesh.set_parting(OMEGA_H_GHOSTED);
{
auto metrics = get_implied_isos(&mesh);
mesh.add_tag(VERT, "metric", 1, metrics);
}
vtk::Writer writer("out", &mesh);
writer.write();
Now t0 = now();
for (Int step = 0; step < niters; ++step) {
mesh.set_parting(OMEGA_H_GHOSTED);
auto objs = c.objects();
auto motion_w = Write<Real>(mesh.nverts() * mesh.dim(), 0.0);
for (auto obj : objs) {
auto verts_on_obj =
mark_class_closure(&mesh, Omega_h::VERT, mesh.dim(), obj);
auto ov2v = collect_marked(verts_on_obj);
auto obj_motion = c.motion(&mesh, step, obj, ov2v);
map_into(obj_motion, ov2v, motion_w, mesh.dim());
}
auto motion = Reals(motion_w);
motion = solve_laplacian(&mesh, motion, mesh.dim(), 1e-2);
mesh.add_tag(VERT, "warp", mesh.dim(), motion);
// auto metrics = mesh.get_array<Real>(VERT, "metric");
// auto lengths = lengths_from_isos(metrics);
// lengths = solve_laplacian(&mesh, lengths, 1, 1e-2);
// metrics = isos_from_lengths(lengths);
// mesh.set_tag(VERT, "metric", metrics);
auto opts = AdaptOpts(&mesh);
opts.max_length_allowed = opts.max_length_desired * 2.0;
int warp_step = 0;
while (warp_to_limit(&mesh, opts)) {
if (world->rank() == 0) {
std::cout << "WARP STEP " << warp_step << " OF TIME STEP " << step
<< '\n';
}
adapt(&mesh, opts);
++warp_step;
}
writer.write();
}
Now t1 = now();
if (world->rank() == 0) {
std::cout << "case took " << (t1 - t0) << " seconds to run\n";
}
}
int main(int argc, char** argv) {
auto lib = Library(&argc, &argv);
std::string name;
Int niters = -1;
for (int i = 1; i < argc; ++i) {
std::string arg = argv[i];
if (arg == "--niters") {
if (i == argc - 1) Omega_h_fail("--niters needs an argument\n");
++i;
niters = atoi(argv[i]);
} else {
name = arg;
}
}
if (name == "translate_ball")
run_case(&lib, TranslateBall(), niters);
else if (name == "rotate_ball")
run_case(&lib, RotateBall(), niters);
else if (name == "collide_balls")
run_case(&lib, CollideBalls(), niters);
else if (name == "cylinder_thru_tube")
run_case(&lib, CylinderTube(), niters);
else if (name == "twin_rotor")
run_case(&lib, TwinRotor(), niters);
else
Omega_h_fail("unknown case \"%s\"", argv[1]);
}
| 30.462687
| 80
| 0.612567
|
joshia5
|
8b774c0add9a33601f14e172337d31db83134d88
| 13,525
|
hpp
|
C++
|
src/johnson.hpp
|
kubohiroya/APSP-in-parallel
|
c1f94d29f85129b6eaf3cbdf0c376939b7af3282
|
[
"MIT"
] | null | null | null |
src/johnson.hpp
|
kubohiroya/APSP-in-parallel
|
c1f94d29f85129b6eaf3cbdf0c376939b7af3282
|
[
"MIT"
] | null | null | null |
src/johnson.hpp
|
kubohiroya/APSP-in-parallel
|
c1f94d29f85129b6eaf3cbdf0c376939b7af3282
|
[
"MIT"
] | null | null | null |
#pragma once
#include <iostream> // cerr
#include <random> // mt19937_64, uniform_x_distribution
#include <vector>
#include <boost/config.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <iostream>
#include "inf.hpp"
#include "getInf.hpp"
#include "util.hpp"
using namespace boost;
template<typename Number> using Graph = adjacency_list<listS, vecS, directedS, no_property, property<edge_weight_t, Number>>;
template<typename Number> using Vertex = typename graph_traits<Graph<Number>>::vertex_descriptor;
typedef std::pair<int, int> Edge;
template<typename Number>
struct graph_t {
int V;
int E;
Edge *edge_array;
Number *weights;
};
#ifdef CUDA
template<typename Number>
struct graph_cuda_t {
int V;
int E;
Edge *edge_array;
Number *weights;
int *starts;
};
#endif
template<typename Number> size_t init_random_adjacency_matrix(Number *adjacencyMatrix, const int n, const double p, const unsigned long seed) {
static const Number inf = getInf<Number>();
static std::uniform_real_distribution<double> flip(0, 1);
static std::uniform_real_distribution<double> choose_weight(1, 100);
std::mt19937_64 rand_engine(seed);
size_t e = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j) {
adjacencyMatrix[i * n + j] = 0;
} else if (flip(rand_engine) < p) {
adjacencyMatrix[i * n + j] = choose_weight(rand_engine);
e++;
} else {
adjacencyMatrix[i * n + j] = inf;
}
}
}
return e;
}
template<typename Number> size_t count_edges(const Number *adjacencyMatrix, const int n) {
static const Number inf = getInf<Number>();
size_t e = 0;
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (int i = 0; i < n * n; i++) {
Number weight = adjacencyMatrix[i];
if (weight != 0 && weight != inf) {
#ifdef _OPENMP
#pragma omp atomic
#endif
e++;
}
}
return e;
}
template<typename Number> graph_t<Number> * init_graph(const Number *adjacencyMatrix, const int n) {
static const Number inf = getInf<Number>();
size_t e = count_edges<Number>(adjacencyMatrix, n);
Edge *edge_array = new Edge[e];
Number *weights = new Number[e];
int ei = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (adjacencyMatrix[i * n + j] != 0 && adjacencyMatrix[i * n + j] != inf) {
#ifdef _OPENMP
#pragma omp critical (init_graph)
#endif
{
edge_array[ei] = Edge(i, j);
weights[ei] = adjacencyMatrix[i * n + j];
ei++;
}
}
}
}
graph_t<Number> *gr = new graph_t<Number>;
gr->V = n;
gr->E = e;
gr->edge_array = edge_array;
gr->weights = weights;
return gr;
}
template<typename Number> graph_t<Number> * init_random_graph(const int n, const double p, const unsigned long seed) {
static const Number inf = getInf<Number>();
Number *adjacencyMatrix = new Number[n * n];
size_t e = init_random_adjacency_matrix<Number>(adjacencyMatrix, n, p, seed);
graph_t<Number> * gr = init_graph<Number>(adjacencyMatrix, n, e);
delete[] adjacencyMatrix;
return gr;
}
template<typename Number> void free_graph(const graph_t<Number> *g) {
delete[] g->edge_array;
delete[] g->weights;
delete g;
}
#ifdef CUDA
template<typename Number> graph_cuda_t<Number> * init_graph_cuda(const Number *adjacencyMatrix, const int n) {
static const Number inf = getInf<Number>();
size_t e = count_edges<Number>(adjacencyMatrix, n);
Edge *edge_array = new Edge[e];
Number *weights = new Number[e];
int* starts = new int[n + 1]; // Starting point for each edge
int ei = 0;
for (int i = 0; i < n; i++) {
starts[i] = ei;
for (int j = 0; j < n; j++) {
if (adjacencyMatrix[i * n + j] != 0 && adjacencyMatrix[i * n + j] != inf) {
#ifdef _OPENMP
#pragma omp critical (init_graph_cuda)
#endif
{
edge_array[ei] = Edge(i, j);
weights[ei] = adjacencyMatrix[i * n + j];
ei++;
}
}
}
}
starts[n] = ei; // One extra
graph_cuda_t<Number> *gr = new graph_cuda_t<Number>;
gr->V = n;
gr->E = e;
gr->edge_array = edge_array;
gr->weights = weights;
gr->starts = starts;
return gr;
}
template<typename Number> graph_cuda_t<Number> * johnson_cuda_random_init(const int n, const double p, const unsigned long seed) {
static const Number inf = getInf<Number>();
Number* adjacencyMatrix = new Number[n * n];
int e = init_random_adjacency_matrix<Number>(adjacencyMatrix, n, p, seed);
graph_cuda_t<Number> *gr = init_graph_cuda<Number>(adjacencyMatrix, n);
delete[] adjacencyMatrix;
return gr;
}
template<typename Number> void free_graph_cuda(const graph_cuda_t<Number> * g) {
delete[] g->edge_array;
delete[] g->weights;
delete[] g->starts;
delete g;
}
template<typename Number> void johnson_cuda(graph_cuda_t<Number> *gr, Number *distanceMatrix);
template<typename Number> void johnson_successor_cuda(graph_cuda_t<Number> *gr, Number *distanceMatrix, int *successorMatrix);
#endif
template<typename Number> inline bool bellman_ford(const graph_t<Number> *gr, Number *dist, int src) {
static const Number inf = getInf<Number>();
int v = gr->V;
int e = gr->E;
Edge *edges = gr->edge_array;
Number *weights = gr->weights;
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (int i = 0; i < v; i++) {
dist[i] = inf;
}
dist[src] = 0;
for (int i = 1; i <= v - 1; i++) {
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (int j = 0; j < e; j++) {
int u = std::get<0>(edges[j]);
int v = std::get<1>(edges[j]);
Number new_dist = weights[j] + dist[u];
if (dist[u] != inf && new_dist < dist[v])
dist[v] = new_dist;
}
}
bool no_neg_cycle = true;
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (int i = 0; i < e; i++) {
int u = std::get<0>(edges[i]);
int v = std::get<1>(edges[i]);
Number weight = weights[i];
if (dist[u] != inf && dist[u] + weight < dist[v])
no_neg_cycle = false;
}
return no_neg_cycle;
}
template<typename Number> void johnson_parallel(const graph_t<Number> *gr, Number *distanceMatrix) {
static const Number inf = getInf<Number>();
int v = gr->V;
// Make new graph for Bellman-Ford
// First, a new node q is added to the graph, connected by zero-weight edges
// to each of the other nodes.
graph_t<Number> *bf_graph = new graph_t<Number>;
bf_graph->V = v + 1;
bf_graph->E = gr->E + v;
bf_graph->edge_array = new Edge[bf_graph->E];
bf_graph->weights = new Number[bf_graph->E];
std::memcpy(bf_graph->edge_array, gr->edge_array, gr->E * sizeof(Edge));
std::memcpy(bf_graph->weights, gr->weights, gr->E * sizeof(Number));
std::memset(&bf_graph->weights[gr->E], 0, v * sizeof(Number));
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (int e = 0; e < v; e++) {
bf_graph->edge_array[e + gr->E] = Edge(v, e);
}
// Second, the Bellman–Ford algorithm is used, starting from the new vertex q,
// to find for each vertex v the minimum weight h(v) of a path from q to v. If
// this step detects a negative cycle, the algorithm is terminated.
// TODO Can run parallel version?
Number *h = new Number[bf_graph->V];
bool r = bellman_ford<Number>(bf_graph, h, v);
if (!r) {
std::cerr << "\nNegative Cycles Detected! Terminating Early\n";
exit(1);
}
// Next the edges of the original graph are reweighted using the values computed
// by the Bellman–Ford algorithm: an edge from u to v, having length
// w(u,v), is given the new length w(u,v) + h(u) − h(v).
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (int e = 0; e < gr->E; e++) {
int u = std::get<0>(gr->edge_array[e]);
int v = std::get<1>(gr->edge_array[e]);
gr->weights[e] = gr->weights[e] + h[u] - h[v];
}
Graph<Number> G(gr->edge_array, gr->edge_array + gr->E, gr->weights, v);
#ifdef _OPENMP
#pragma omp parallel for schedule(dynamic)
#endif
for (int s = 0; s < v; s++) {
std::vector <Vertex<Number>> p(num_vertices(G));
std::vector<Number> d(num_vertices(G));
dijkstra_shortest_paths(G, s, distance_map(&d[0]).distance_inf(inf));
for (int vi = 0; vi < v; vi++) {
int i = s * v + vi;
distanceMatrix[i] = d[vi] + h[vi] - h[s];
}
}
delete[] h;
free_graph<Number>(bf_graph);
}
template<typename Number> void johnson_parallel(const graph_t<Number> *gr, Number *distanceMatrix, int *successorMatrix) {
static const Number inf = getInf<Number>();
int v = gr->V;
// Make new graph for Bellman-Ford
// First, a new node q is added to the graph, connected by zero-weight edges
// to each of the other nodes.
graph_t<Number> *bf_graph = new graph_t<Number>;
bf_graph->V = v + 1;
bf_graph->E = gr->E + v;
bf_graph->edge_array = new Edge[bf_graph->E];
bf_graph->weights = new Number[bf_graph->E];
std::memcpy(bf_graph->edge_array, gr->edge_array, gr->E * sizeof(Edge));
std::memcpy(bf_graph->weights, gr->weights, gr->E * sizeof(Number));
std::memset(&bf_graph->weights[gr->E], 0, v * sizeof(Number));
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (int e = 0; e < v; e++) {
bf_graph->edge_array[e + gr->E] = Edge(v, e);
}
// Second, the Bellman–Ford algorithm is used, starting from the new vertex q,
// to find for each vertex v the minimum weight h(v) of a path from q to v. If
// this step detects a negative cycle, the algorithm is terminated.
// TODO Can run parallel version?
Number *h = new Number[bf_graph->V];
bool r = bellman_ford<Number>(bf_graph, h, v);
if (!r) {
std::cerr << "\nNegative Cycles Detected! Terminating Early\n";
exit(1);
}
// Next the edges of the original graph are reweighted using the values computed
// by the Bellman–Ford algorithm: an edge from u to v, having length
// w(u,v), is given the new length w(u,v) + h(u) − h(v).
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (int e = 0; e < gr->E; e++) {
int u = std::get<0>(gr->edge_array[e]);
int v = std::get<1>(gr->edge_array[e]);
gr->weights[e] = gr->weights[e] + h[u] - h[v];
}
Graph<Number> G(gr->edge_array, gr->edge_array + gr->E, gr->weights, v);
#ifdef _OPENMP
#pragma omp parallel for schedule(dynamic)
#endif
for (int s = 0; s < v; s++) {
std::vector <Vertex<Number>> p(num_vertices(G));
std::vector<Number> d(num_vertices(G));
dijkstra_shortest_paths(G, s, distance_map(&d[0]).predecessor_map(&p[0]).distance_inf(inf));
for (int vi = 0; vi < v; vi++) {
int i = s * v + vi;
distanceMatrix[i] = d[vi] + h[vi] - h[s];
successorMatrix[vi * v + s] = p[vi];
}
}
delete[] h;
free_graph<Number>(bf_graph);
}
template<typename Number> void johnson_parallel_matrix(const Number *adjacencyMatrix, Number **distanceMatrix, const int n) {
*distanceMatrix = (Number *) malloc(sizeof(Number) * n * n);
memcpy(*distanceMatrix, adjacencyMatrix, sizeof(Number) * n * n);
#ifdef CUDA
graph_cuda_t<Number> *cuda_gr = init_graph_cuda<Number>(adjacencyMatrix, n);
johnson_cuda<Number>(cuda_gr, *distanceMatrix);
free_graph_cuda<Number>(cuda_gr);
#else
const graph_t<Number> *gr = init_graph<Number>(adjacencyMatrix, n);
johnson_parallel<Number>(gr, *distanceMatrix);
delete gr;
#endif
}
template<typename Number> void johnson_parallel_matrix(const Number *adjacencyMatrix, Number **distanceMatrix, int **successorMatrix, const int n) {
*distanceMatrix = (Number *) malloc(sizeof(Number) * n * n);
*successorMatrix = (int *) malloc(sizeof(int) * n * n);
memcpy(*distanceMatrix, adjacencyMatrix, sizeof(Number) * n * n);
#ifdef CUDA
graph_cuda_t<Number> *cuda_gr = init_graph_cuda<Number>(adjacencyMatrix, n);
johnson_successor_cuda<Number>(cuda_gr, *distanceMatrix, *successorMatrix);
free_graph_cuda<Number>(cuda_gr);
#else
const graph_t<Number> *gr = init_graph<Number>(adjacencyMatrix, n);
johnson_parallel<Number>(gr, *distanceMatrix, *successorMatrix);
delete gr;
#endif
}
template<typename Number> void free_johnson_parallel_matrix(Number **distanceMatrix) {
free(*distanceMatrix);
}
template<typename Number> void free_johnson_parallel_matrix(Number **distanceMatrix, int **successorMatrix) {
free(*distanceMatrix);
free(*successorMatrix);
}
extern "C" void johnson_parallel_matrix_double(const double *adjacencyMatrix, double **distanceMatrix, const int n);
extern "C" void free_johnson_parallel_matrix_double(double **distanceMatrix);
extern "C" void johnson_parallel_matrix_float(const float *adjacencyMatrix, float **distanceMatrix, const int n);
extern "C" void free_johnson_parallel_matrix_float(float **distanceMatrix);
extern "C" void johnson_parallel_matrix_int(const int *adjacencyMatrix, int **distanceMatrix, const int n);
extern "C" void free_johnson_parallel_matrix_int(int **distanceMatrix);
extern "C" void johnson_parallel_matrix_successor_double(const double *adjacencyMatrix, double **distanceMatrix, int **successorMatrix, const int n);
extern "C" void free_johnson_parallel_matrix_successor_double(double **distanceMatrix, int **successorMatrix);
extern "C" void johnson_parallel_matrix_successor_float(const float *adjacencyMatrix, float **distanceMatrix, int **successorMatrix, const int n);
extern "C" void free_johnson_parallel_matrix_successor_float(float **distanceMatrix, int **successorMatrix);
extern "C" void johnson_parallel_matrix_successor_int(const int *adjacencyMatrix, int **distanceMatrix, int **successorMatrix, const int n);
extern "C" void free_johnson_parallel_matrix_successor_int(int **distanceMatrix, int **successorMatrix);
| 33.395062
| 149
| 0.673124
|
kubohiroya
|
8b779ac421ec7687e81830da41830e8286f7cd7c
| 975
|
cpp
|
C++
|
.LHP/.Lop11/.T.Minh/DENDUONG/DENDUONG/DENDUONG.cpp
|
sxweetlollipop2912/MaCode
|
661d77a2096e4d772fda2b6a7f80c84113b2cde9
|
[
"MIT"
] | null | null | null |
.LHP/.Lop11/.T.Minh/DENDUONG/DENDUONG/DENDUONG.cpp
|
sxweetlollipop2912/MaCode
|
661d77a2096e4d772fda2b6a7f80c84113b2cde9
|
[
"MIT"
] | null | null | null |
.LHP/.Lop11/.T.Minh/DENDUONG/DENDUONG/DENDUONG.cpp
|
sxweetlollipop2912/MaCode
|
661d77a2096e4d772fda2b6a7f80c84113b2cde9
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <iomanip>
#define maxN 100002
//#define maxA 1000000001
typedef long maxn;
typedef double maxa;
const maxa eps = 1e-9;
maxn n;
maxa L, a[maxN];
void Prepare() {
std::cin >> n >> L;
for (maxn i = 0; i < n; i++) std::cin >> a[i];
std::sort(a, a + n);
}
bool Check(const maxa D) {
maxa cur = 0;
for (maxn i = 0; i < n; i++) {
maxa tmp = std::min(cur, a[i]) + D;
if (tmp - eps > a[i]) cur = std::max(cur, tmp);
else return 0;
}
if (cur - eps > L) return 1; else return 0;
}
void Process() {
maxa l = 0, r = L;
for (maxn i = 0; i < 150 && r - l > eps; i++) {
maxa m = (l + r) / (maxa)2;
if (!Check(m)) l = m;
else r = m;
}
std::cout << std::fixed; std::cout << std::setprecision(2);
std::cout << l;
}
int main() {
//freopen("denduong.inp", "r", stdin);
//freopen("denduong.out", "w", stdout);
std::ios_base::sync_with_stdio(0);
std::cin.tie(0);
Prepare();
Process();
}
| 17.105263
| 60
| 0.558974
|
sxweetlollipop2912
|
8b8077c8d386d1e10fd0b8782c798594e88ba042
| 1,632
|
hpp
|
C++
|
include/ctre/actions/asserts.inc.hpp
|
XRay3D/compile-time-regular-expressions
|
57573365db1256de316acb46109674853d967bb4
|
[
"Apache-2.0"
] | 2,261
|
2017-10-11T11:30:02.000Z
|
2022-03-31T14:19:55.000Z
|
include/ctre/actions/asserts.inc.hpp
|
XRay3D/compile-time-regular-expressions
|
57573365db1256de316acb46109674853d967bb4
|
[
"Apache-2.0"
] | 221
|
2017-10-11T15:42:32.000Z
|
2022-03-26T12:18:16.000Z
|
include/ctre/actions/asserts.inc.hpp
|
XRay3D/compile-time-regular-expressions
|
57573365db1256de316acb46109674853d967bb4
|
[
"Apache-2.0"
] | 140
|
2017-10-11T17:25:56.000Z
|
2022-03-23T01:06:57.000Z
|
#ifndef CTRE__ACTIONS__ASSERTS__HPP
#define CTRE__ACTIONS__ASSERTS__HPP
// push_assert_begin
template <auto V, typename... Ts, typename Parameters> static constexpr auto apply(pcre::push_assert_begin, ctll::term<V>, pcre_context<ctll::list<Ts...>, Parameters> subject) {
return pcre_context{ctll::push_front(assert_line_begin(), subject.stack), subject.parameters};
}
// push_assert_end
template <auto V, typename... Ts, typename Parameters> static constexpr auto apply(pcre::push_assert_end, ctll::term<V>, pcre_context<ctll::list<Ts...>, Parameters> subject) {
return pcre_context{ctll::push_front(assert_line_end(), subject.stack), subject.parameters};
}
// push_assert_begin
template <auto V, typename... Ts, typename Parameters> static constexpr auto apply(pcre::push_assert_subject_begin, ctll::term<V>, pcre_context<ctll::list<Ts...>, Parameters> subject) {
return pcre_context{ctll::push_front(assert_subject_begin(), subject.stack), subject.parameters};
}
// push_assert_subject_end
template <auto V, typename... Ts, typename Parameters> static constexpr auto apply(pcre::push_assert_subject_end, ctll::term<V>, pcre_context<ctll::list<Ts...>, Parameters> subject) {
return pcre_context{ctll::push_front(assert_subject_end(), subject.stack), subject.parameters};
}
// push_assert_subject_end_with_lineend
template <auto V, typename... Ts, typename Parameters> static constexpr auto apply(pcre::push_assert_subject_end_with_lineend, ctll::term<V>, pcre_context<ctll::list<Ts...>, Parameters> subject) {
return pcre_context{ctll::push_front(assert_subject_end_line(), subject.stack), subject.parameters};
}
#endif
| 54.4
| 196
| 0.783088
|
XRay3D
|
8b860c32c5c145df12787bf1b3dde86342e929bc
| 23,061
|
cpp
|
C++
|
src/DataWidgets/Data/nObjectTypeEditor.cpp
|
Vladimir-Lin/QtDataWidgets
|
67372e2a807d47082d3130d16857476d7020facc
|
[
"MIT"
] | null | null | null |
src/DataWidgets/Data/nObjectTypeEditor.cpp
|
Vladimir-Lin/QtDataWidgets
|
67372e2a807d47082d3130d16857476d7020facc
|
[
"MIT"
] | null | null | null |
src/DataWidgets/Data/nObjectTypeEditor.cpp
|
Vladimir-Lin/QtDataWidgets
|
67372e2a807d47082d3130d16857476d7020facc
|
[
"MIT"
] | null | null | null |
#include <datawidgets.h>
N::ObjectTypeEditor:: ObjectTypeEditor ( QWidget * parent , Plan * p )
: TreeWidget ( parent , p )
{
WidgetClass ;
Configure ( ) ;
}
N::ObjectTypeEditor::~ObjectTypeEditor (void)
{
}
QSize N::ObjectTypeEditor::SuitableSize(void)
{
QSize s = size() ;
CUIDs w = columnWidths() ;
int t = 0 ;
if (w.count()<=0) return s ;
for (int i=0;i<w.count();i++) {
t += w[i] ;
} ;
s . setWidth ( t ) ;
return s ;
}
void N::ObjectTypeEditor::Configure(void)
{
NewTreeWidgetItem ( head ) ;
head -> setText ( 0 , tr("Type") ) ;
head -> setText ( 1 , tr("Name") ) ;
head -> setText ( 2 , tr("Enumeration") ) ;
head -> setText ( 3 , tr("Statistics") ) ;
head -> setText ( 4 , "" ) ;
////////////////////////////////////////////////////////////
setWindowTitle ( tr("Object types") ) ;
setDragDropMode ( NoDragDrop ) ;
setRootIsDecorated ( false ) ;
setAlternatingRowColors ( true ) ;
setSelectionMode ( SingleSelection ) ;
setColumnCount ( 5 ) ;
setColumnHidden ( 3 , true ) ;
setHorizontalScrollBarPolicy ( Qt::ScrollBarAsNeeded ) ;
setVerticalScrollBarPolicy ( Qt::ScrollBarAsNeeded ) ;
assignHeaderItems ( head ) ;
plan -> setFont ( this ) ;
MountClicked ( 2 ) ;
MountClicked ( 9 ) ;
////////////////////////////////////////////////////////////
if (!plan->Booleans["Desktop"]) {
allowGesture = true ;
grabGesture ( Qt::TapAndHoldGesture ) ;
grabGesture ( Qt::PanGesture ) ;
} ;
}
void N::ObjectTypeEditor::List(void)
{
start ( 1001 ) ;
}
void N::ObjectTypeEditor::AllTypes(void)
{
blockSignals ( true ) ;
clear ( ) ;
emit OnBusy ( ) ;
EnterSQL(SC,plan->sql) ;
UUIDs Uuids = SC.Uuids(PlanTable(Types),"type","order by id asc") ;
SUID uuid ;
QString Q ;
foreach (uuid,Uuids) {
QString name = GetName(SC,uuid) ;
QString Enum ;
int flags ;
Q = SC.sql.SelectFrom("flags",PlanTable(Types) ,
QString("where type = %1").arg(uuid) ) ;
if (SC.Fetch(Q)) flags = SC . Int ( 0 ) ;
Q = SC.sql.SelectFrom("value",PlanTable(Variables) ,
"where uuid = :UUID and name = :NAME" ) ;
SC.Prepare ( Q ) ;
SC.Bind ( "uuid" , uuid ) ;
SC.Bind ( "name" , "Enumeration" ) ;
if (SC.Exec() && SC.Next()) Enum = SC.String(0) ;
NewTreeWidgetItem ( item ) ;
item->setCheckState(0,IsMask(flags,1) ? Qt::Checked : Qt::Unchecked ) ;
item->setData (0,Qt::UserRole ,uuid ) ;
item->setTextAlignment (0,Qt::AlignRight|Qt::AlignVCenter) ;
item->setText (0,QString::number(uuid) ) ;
item->setText (1,name ) ;
item->setText (2,Enum ) ;
addTopLevelItem ( item ) ;
} ;
LeaveSQL(SC,plan->sql) ;
blockSignals ( false ) ;
emit AutoFit ( ) ;
emit GoRelax ( ) ;
Alert ( Done ) ;
}
void N::ObjectTypeEditor::doubleClicked (QTreeWidgetItem * item,int column)
{
switch (column) {
case 1 :
setLineEdit (
item,column ,
SIGNAL(editingFinished()) ,
SLOT (nameChanged ()) ) ;
break ;
case 2 :
setLineEdit (
item,column ,
SIGNAL(editingFinished()) ,
SLOT (enumChanged ()) ) ;
break ;
} ;
}
void N::ObjectTypeEditor::stateChanged (QTreeWidgetItem * item,int column)
{
if (column!=0) return ;
bool checked = (item->checkState(0)==Qt::Checked) ;
SUID uuid = nTreeUuid ( item , 0 ) ;
int flags = 0 ;
if (checked) flags = 1 ;
EnterSQL ( SC , plan->sql ) ;
QString Q ;
Q = SC.sql.Update(PlanTable(Types) ,
QString("where type = :TYPE"),1,"flags") ;
SC . Prepare ( Q ) ;
SC . Bind ( "type" , uuid ) ;
SC . Bind ( "flags" , flags ) ;
SC . Exec ( ) ;
LeaveSQL ( SC , plan->sql ) ;
Alert ( Done ) ;
if (checked) {
plan->Talk(15,tr("Enable object type" )) ;
} else {
plan->Talk(15,tr("Disable object type")) ;
} ;
}
void N::ObjectTypeEditor::removeOldItem(void)
{
nDropOut ( IsNull(ItemEditing) ) ;
removeItemWidget (ItemEditing,ItemColumn) ;
ItemEditing = NULL ;
ItemWidget = NULL ;
ItemColumn = -1 ;
if (!plan->Booleans["Desktop"]) {
allowGesture = true ;
} ;
}
void N::ObjectTypeEditor::nameChanged(void)
{
nDropOut ( IsNull(ItemEditing) ) ;
nDropOut ( IsNull(ItemWidget ) ) ;
QLineEdit * line = Casting(QLineEdit,ItemWidget) ;
SUID uuid = nTreeUuid(ItemEditing,0) ;
if (NotNull(line)) {
QString name = line->text() ;
EnterSQL ( SC , plan->sql ) ;
QString Q ;
Q = SC.sql.SelectFrom("id",PlanTable(Names) ,
QString("where uuid = %1 and language = %2")
.arg(uuid )
.arg(vLanguageId) ) ;
if (SC.Fetch(Q)) {
Q = SC.NameUpdate(PlanTable(Names),"name") ;
} else {
Q = SC.NameSyntax(PlanTable(Names)) ;
} ;
if (SC.insertName(Q,uuid,vLanguageId,name)) {
ItemEditing -> setText ( 1 , name ) ;
Alert ( Done ) ;
} else {
Alert ( Error ) ;
} ;
LeaveSQL ( SC , plan->sql ) ;
} ;
removeOldItem ( ) ;
}
void N::ObjectTypeEditor::enumChanged(void)
{
nDropOut ( IsNull(ItemEditing) ) ;
nDropOut ( IsNull(ItemWidget ) ) ;
QLineEdit * line = Casting(QLineEdit,ItemWidget) ;
SUID uuid = nTreeUuid(ItemEditing,0) ;
if (NotNull(line)) {
QString name = line->text() ;
EnterSQL ( SC , plan->sql ) ;
QString Q ;
Q = SC.sql.DeleteFrom(PlanTable(Variables) ,
QString("where uuid = %1 "
"and name = `Enumeration`" )
.arg(uuid) ) ;
SC . Query ( Q ) ;
Q = SC.sql.InsertInto(PlanTable(Variables) ,
2,"uuid","name") ;
SC . Prepare ( Q ) ;
SC . Bind ( "uuid" , uuid ) ;
SC . Bind ( "name" , "Enumeration" ) ;
SC . Exec ( ) ;
Q = SC.sql.Update(PlanTable(Variables) ,
"where uuid = :UUID and name = :NAME" ,
1 , "value" ) ;
SC . Prepare ( Q ) ;
SC . Bind ( "uuid" , uuid ) ;
SC . Bind ( "name" , "Enumeration" ) ;
SC . Bind ( "value" , name ) ;
SC . Exec ( ) ;
ItemEditing -> setText ( ItemColumn , name ) ;
LeaveSQL ( SC , plan->sql ) ;
Alert ( Done ) ;
} ;
removeOldItem ( ) ;
}
bool N::ObjectTypeEditor::FocusIn(void)
{
nKickOut ( IsNull(plan) , true ) ;
DisableAllActions ( ) ;
AssignAction ( Label , windowTitle ( ) ) ;
AssignAction ( Refresh , tr("Refresh types") ) ;
LinkAction ( Refresh , List ( ) ) ;
LinkAction ( Copy , CopyToClipboard ( ) ) ;
return true ;
}
bool N::ObjectTypeEditor::Menu(QPoint pos)
{
nScopedMenu ( mm , this ) ;
QAction * aa ;
QMenu * ms ;
QMenu * ma ;
QMenu * me ;
mm.add(101,tr("Refresh" )) ;
mm.add(102,tr("Statistics" )) ;
mm.addSeparator() ;
mm.add(103,tr("Export C++ enumeration" )) ;
mm.add(104,tr("Display C++ enumeration")) ;
mm.addSeparator() ;
mm.add(105,tr("Export names to file" )) ;
mm.addSeparator() ;
ms = mm . addMenu ( tr ("Sorting" ) ) ;
ma = mm . addMenu ( tr ("Adjustments" ) ) ;
me = mm . addMenu ( tr ("Selection" ) ) ;
SortingMenu ( mm , ms ) ;
AdjustMenu ( mm , ma ) ;
SelectionsMenu ( mm , me ) ;
mm.setFont(plan) ;
if (plan->Booleans["Desktop"]) {
pos = QCursor::pos() ;
} else {
pos = mapToGlobal ( pos ) ;
} ;
aa = mm.exec(pos) ;
if (!plan->Booleans["Desktop"]) {
allowGesture = true ;
} ;
if (IsNull ( aa)) return true ;
if (RunSorting (mm,aa)) return true ;
if (RunAdjustment(mm,aa)) return true ;
if (RunSelections(mm,aa)) return true ;
QSize s ;
switch (mm[aa]) {
case 101 :
List ( ) ;
break ;
case 102 :
setColumnHidden(3,false) ;
nFullLoop(i,columnCount()) {
resizeColumnToContents ( i ) ;
} ;
nFullLoop(i,topLevelItemCount()) {
QTreeWidgetItem * item ;
item = topLevelItem ( i ) ;
item -> setText ( 3 , "" ) ;
} ;
DoProcessEvents ;
update ( ) ;
s = SuitableSize() ;
resize ( s ) ;
DoProcessEvents ;
repaint ( ) ;
emit Adjustment ( this , s ) ;
DoProcessEvents ;
start ( 1002 ) ;
break ;
case 103 :
ExportCpp ( ) ;
break ;
case 104 :
DisplayCpp ( ) ;
break ;
case 105 :
ExportNames ( ) ;
break ;
} ;
return true ;
}
void N::ObjectTypeEditor::AllItems(void)
{
plan->Talk(tr("Counting object items, please wait for a moment.")) ;
emit OnBusy ( ) ;
QMap<SUID,QTreeWidgetItem *> ITEMs ;
QTreeWidgetItem * EndItem = NULL ;
for (int i=0;i<topLevelItemCount();i++) {
QTreeWidgetItem * item = topLevelItem ( i ) ;
SUID uuid = nTreeUuid ( item , 0 ) ;
ITEMs [uuid] = item ;
if (IsNull(EndItem)) {
if (item->checkState(0)==Qt::Unchecked) EndItem = item ;
} ;
} ;
int Total = 0 ;
SqlConnection SC(plan->sql) ;
if (SC.open("nObjectTypeEditor","run")) {
QString Q ;
Q = SC.sql.SelectFrom("type,count(*)",PlanTable(MajorUuid) ,
"group by type order by type asc" ) ;
SqlLoopNow ( SC , Q ) ;
SUID type = SC . Uuid ( 0 ) ;
int count = SC . Int ( 1 ) ;
Total += count ;
if (ITEMs.contains(type)) {
ITEMs[type]->setTextAlignment(3,Qt::AlignRight |
Qt::AlignVCenter ) ;
ITEMs[type]->setText(3,QString::number(count)) ;
} ;
SqlLoopErr ( SC , Q ) ;
SqlLoopEnd ( SC , Q ) ;
SC.close() ;
} ;
SC.remove() ;
if (NotNull(EndItem)) {
EndItem->setText(3,QString::number(Total)) ;
} ;
emit GoRelax ( ) ;
Alert ( Done ) ;
}
void N::ObjectTypeEditor::DisplayCpp(void)
{
QByteArray Data ;
ExportCpp ( Data , "ObjectTypes" ) ;
if (Data.size()<=0) return ;
emit CppEnumeration ( Data ) ;
}
void N::ObjectTypeEditor::ExportCpp(void)
{
QString filename = QFileDialog::getSaveFileName (
this ,
tr("Export C++ enumeration") ,
plan->Temporary("") ,
tr("C++ (*.h *.c *.hpp *.cpp *.cc *.c++)") ) ;
if (filename.length()<=0) return ;
ExportCpp(filename,"ObjectTypes") ;
}
void N::ObjectTypeEditor::ExportCpp(QString filename,QString EnumName)
{
QByteArray Data ;
ExportCpp ( Data , EnumName ) ;
if (Data.size()<=0) return ;
File::toFile ( filename , Data ) ;
}
void N::ObjectTypeEditor::ExportCpp(QByteArray & Data,QString EnumName)
{
QStringList lists ;
QStringList enums ;
QString Enum ;
ZMAPs IDs ;
int MaxEnum = 0 ;
int MaxLine = 0 ;
int Count = 0 ;
QString Space ( " " ) ;
QString Line ;
Data . clear ( ) ;
////////////////////////////////////////////////
for (int i=0;i<topLevelItemCount();i++) {
QTreeWidgetItem * item ;
item = topLevelItem(i) ;
if (IsMask(item->checkState(0),Qt::Checked)) {
Enum = item->text(2) ;
enums << Enum ;
IDs [ Enum ] = nTreeUuid(item,0) ;
if (Enum.length()>MaxEnum) {
MaxEnum = Enum.length() ;
} ;
} ;
} ;
////////////////////////////////////////////////
MaxLine = MaxEnum + 9 ;
Count = 5 + EnumName.length() ;
Line = "enum " ;
Line += EnumName ;
Line += Space.repeated(MaxLine-Count) ;
Line += "{" ;
lists << Line ;
////////////////////////////////////////////////
int TE = 0 ;
for (int i=0;i<enums.count();i++) {
int Value ;
QString V ;
Enum = enums [ i ] ;
Value = IDs [ Enum ] ;
V = QString::number(Value) ;
Line = " " ;
Line += Enum ;
if (MaxEnum>Enum.length()) {
int L = Enum.length() ;
Line += Space.repeated(MaxEnum-L) ;
} ;
Line += " = " ;
if (V.length()<3) {
int L = V.length() ;
Line += Space.repeated(3-L) ;
} ;
Line += V ;
Line += " ," ;
lists << Line ;
if (Value>=TE) TE = Value + 1 ;
} ;
////////////////////////////////////////////////
Line = " TypesEnd" ;
Line += Space.repeated(MaxEnum-8) ;
Line += " = " ;
Line += QString::number(TE) ;
lists << Line ;
////////////////////////////////////////////////
Line = "}" ;
Line += Space.repeated(MaxLine-1) ;
Line += ";" ;
lists << Line ;
////////////////////////////////////////////////
Enum = lists . join ("\r\n") ;
Data . append ( Enum.toUtf8() ) ;
}
void N::ObjectTypeEditor::ExportNames(void)
{
QString filename = QFileDialog::getSaveFileName (
this ,
tr("Export names into file") ,
plan->Temporary("") ,
tr("Plain text file(*.txt)") ) ;
nDropOut ( filename.length() <= 0 ) ;
/////////////////////////////////////////////////////
QStringList L ;
for (int i=0;i<topLevelItemCount();i++) {
QTreeWidgetItem * it = topLevelItem(i) ;
L << it->text(1) ;
} ;
nDropOut ( L.count() <= 0 ) ;
/////////////////////////////////////////////////////
QString M = L.join("\r\n") ;
QByteArray B = M.toUtf8() ;
QFile F(filename) ;
if (F.open(QIODevice::WriteOnly)) {
F . write ( B ) ;
F . close ( ) ;
Alert ( Done ) ;
} else {
Alert ( Error ) ;
} ;
}
void N::ObjectTypeEditor::run(int Type,ThreadData * data)
{ Q_UNUSED ( data ) ;
switch (Type) {
case 1001 :
AllTypes ( ) ;
break ;
case 1002 :
AllItems ( ) ;
break ;
} ;
}
| 47.646694
| 77
| 0.300854
|
Vladimir-Lin
|
8b8a6c123be6c6f5d3cee43461199f2e18752218
| 1,413
|
cpp
|
C++
|
aws-cpp-sdk-appstream/source/model/DescribeApplicationsRequest.cpp
|
perfectrecall/aws-sdk-cpp
|
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
|
[
"Apache-2.0"
] | 1
|
2022-02-10T08:06:54.000Z
|
2022-02-10T08:06:54.000Z
|
aws-cpp-sdk-appstream/source/model/DescribeApplicationsRequest.cpp
|
perfectrecall/aws-sdk-cpp
|
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
|
[
"Apache-2.0"
] | 1
|
2021-10-14T16:57:00.000Z
|
2021-10-18T10:47:24.000Z
|
aws-cpp-sdk-appstream/source/model/DescribeApplicationsRequest.cpp
|
ravindra-wagh/aws-sdk-cpp
|
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
|
[
"Apache-2.0"
] | 1
|
2021-11-09T11:58:03.000Z
|
2021-11-09T11:58:03.000Z
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/appstream/model/DescribeApplicationsRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::AppStream::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
DescribeApplicationsRequest::DescribeApplicationsRequest() :
m_arnsHasBeenSet(false),
m_nextTokenHasBeenSet(false),
m_maxResults(0),
m_maxResultsHasBeenSet(false)
{
}
Aws::String DescribeApplicationsRequest::SerializePayload() const
{
JsonValue payload;
if(m_arnsHasBeenSet)
{
Array<JsonValue> arnsJsonList(m_arns.size());
for(unsigned arnsIndex = 0; arnsIndex < arnsJsonList.GetLength(); ++arnsIndex)
{
arnsJsonList[arnsIndex].AsString(m_arns[arnsIndex]);
}
payload.WithArray("Arns", std::move(arnsJsonList));
}
if(m_nextTokenHasBeenSet)
{
payload.WithString("NextToken", m_nextToken);
}
if(m_maxResultsHasBeenSet)
{
payload.WithInteger("MaxResults", m_maxResults);
}
return payload.View().WriteReadable();
}
Aws::Http::HeaderValueCollection DescribeApplicationsRequest::GetRequestSpecificHeaders() const
{
Aws::Http::HeaderValueCollection headers;
headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "PhotonAdminProxyService.DescribeApplications"));
return headers;
}
| 22.078125
| 109
| 0.743808
|
perfectrecall
|
8b92d8d406ffd29b8a7087335782d3cc237b5b36
| 1,844
|
cpp
|
C++
|
sdk/engine/source/graphics/resources/PointLightManager.cpp
|
NcStudios/NcEngine
|
ce04eca00211b50188d80e59604bfa67bb9c15b6
|
[
"MIT"
] | null | null | null |
sdk/engine/source/graphics/resources/PointLightManager.cpp
|
NcStudios/NcEngine
|
ce04eca00211b50188d80e59604bfa67bb9c15b6
|
[
"MIT"
] | 3
|
2022-03-26T15:14:43.000Z
|
2022-03-27T16:12:53.000Z
|
sdk/engine/source/graphics/resources/PointLightManager.cpp
|
NcStudios/NcEngine
|
ce04eca00211b50188d80e59604bfa67bb9c15b6
|
[
"MIT"
] | null | null | null |
#include "PointLightManager.h"
#include "graphics/Initializers.h"
namespace nc::graphics
{
PointLightManager::PointLightManager(uint32_t bindingSlot, GpuAllocator* allocator, ShaderDescriptorSets* descriptors, uint32_t maxPointLights)
: m_pointLightsArrayBuffer{nullptr},
m_descriptors{descriptors},
m_allocator{allocator},
m_maxPointLights{maxPointLights},
m_bindingSlot{bindingSlot}
{
Initialize();
}
PointLightManager::~PointLightManager() noexcept
{
m_pointLightsArrayBuffer->Clear();
}
void PointLightManager::Initialize()
{
const auto bufferSize = static_cast<uint32_t>(sizeof(PointLightInfo) * m_maxPointLights);
if (m_pointLightsArrayBuffer == nullptr)
{
m_pointLightsArrayBuffer = std::make_unique<WriteableBuffer<nc::PointLightInfo>>(m_allocator, bufferSize);
}
m_descriptors->RegisterDescriptor
(
m_bindingSlot,
BindFrequency::per_frame,
1,
vk::DescriptorType::eStorageBuffer,
vk::ShaderStageFlagBits::eFragment | vk::ShaderStageFlagBits::eVertex,
vk::DescriptorBindingFlagBitsEXT()
);
m_descriptors->UpdateBuffer
(
BindFrequency::per_frame,
m_pointLightsArrayBuffer->GetBuffer(),
bufferSize,
1,
vk::DescriptorType::eStorageBuffer,
m_bindingSlot
);
}
void PointLightManager::Update(const std::vector<PointLightInfo>& data)
{
m_pointLightsArrayBuffer->Map(data, [](PointLightInfo& info)
{
info.isInitialized = false;
});
}
void PointLightManager::Reset()
{
// // m_pointLightsArrayBuffer.Clear();
Initialize();
}
}
| 28.8125
| 147
| 0.624187
|
NcStudios
|
8ba1a3a3455e72d71abf445034918dd521622d67
| 1,612
|
cpp
|
C++
|
libgramtools/submods/combine_jvcfs.cpp
|
bricoletc/gramtools
|
1ce06178b7b26f42d72e47d3d7b8a7a606e6f256
|
[
"MIT"
] | null | null | null |
libgramtools/submods/combine_jvcfs.cpp
|
bricoletc/gramtools
|
1ce06178b7b26f42d72e47d3d7b8a7a606e6f256
|
[
"MIT"
] | null | null | null |
libgramtools/submods/combine_jvcfs.cpp
|
bricoletc/gramtools
|
1ce06178b7b26f42d72e47d3d7b8a7a606e6f256
|
[
"MIT"
] | null | null | null |
/**
* @file Combine JSON genotyped files into one
*/
#include <filesystem>
#include <fstream>
#include <iostream>
#include <nlohmann/json.hpp>
#include "genotype/infer/output_specs/json_prg_spec.hpp"
namespace fs = std::filesystem;
using JSON = nlohmann::json;
using namespace gram::json;
void usage(const char* argv[]) {
std::cout << "Usage: " << argv[0] << " fofn fout" << std::endl;
std::cout << "\t fofn: file of file names of the JSON files to combine"
<< std::endl;
std::cout << "\t fout: name of output combined JSON file" << std::endl;
exit(1);
}
int main(int argc, const char* argv[]) {
if (argc != 3) usage(argv);
fs::path fofn(argv[1]);
if (!fs::exists(fofn)) {
std::cout << fofn << " not found.";
usage(argv);
} else if (fs::is_empty(fofn)) {
std::cout << fofn << " is empty.";
usage(argv);
}
std::ofstream fout(argv[2]);
if (!fout.good()) {
std::cout << "Error: could not open " << argv[2] << std::endl;
usage(argv);
}
std::ifstream fin(fofn);
std::string next_file;
JSON next_json;
Json_Prg combined_json;
bool first{true};
while (std::getline(fin, next_file)) {
std::ifstream next_istream(next_file);
if (!next_istream.good()) {
std::cout << "Error: Could not open JSON file " << next_file << std::endl;
exit(1);
}
next_json.clear();
next_istream >> next_json;
if (first) {
combined_json.set_prg(next_json);
first = false;
}
else {
Json_Prg next_prg(next_json);
combined_json.combine_with(next_prg);
}
}
fout << combined_json.get_prg();
}
| 24.424242
| 80
| 0.610422
|
bricoletc
|
8ba8aad3360054857ba0e077576d68a23b8c8514
| 31,765
|
cpp
|
C++
|
SHC/SmartHandController/Catalog.cpp
|
Zarfab/DobsonGoto
|
51b7811e105358465e054f6cfdd5b531cf9b5e24
|
[
"MIT"
] | 1
|
2021-12-20T09:40:20.000Z
|
2021-12-20T09:40:20.000Z
|
SHC/SmartHandController/Catalog.cpp
|
Zarfab/DobsonGoto
|
51b7811e105358465e054f6cfdd5b531cf9b5e24
|
[
"MIT"
] | 1
|
2021-12-20T09:42:15.000Z
|
2021-12-21T08:31:51.000Z
|
SHC/SmartHandController/Catalog.cpp
|
Zarfab/DobsonGoto
|
51b7811e105358465e054f6cfdd5b531cf9b5e24
|
[
"MIT"
] | null | null | null |
#include <Arduino.h>
#include <math.h>
#include "Constants.h"
#include "Locales.h"
#include "Config.h"
#include "Locale.h"
#include "Pinmap.h"
#include "Catalog.h"
#include "CatalogTypes.h"
#include "CatalogConfig.h"
// --------------------------------------------------------------------------------
// Catalog Manager
// initialization
void CatMgr::setLat(double lat) {
_lat=lat;
if (lat<9999) {
_cosLat=cos(lat/Rad);
_sinLat=sin(lat/Rad);
}
}
// Set Local Sidereal Time, and number of milliseconds
void CatMgr::setLstT0(double lstT0) {
_lstT0=lstT0;
_lstMillisT0=millis();
}
// Set last Tele RA/Dec
void CatMgr::setLastTeleEqu(double RA, double Dec) {
_lastTeleRA=RA;
_lastTeleDec=Dec;
}
bool CatMgr::isInitialized() {
return ((_lat<9999) && (_lstT0!=0));
}
// Get Local Sidereal Time, converted from hours to degrees
double CatMgr::lstDegs() {
return (lstHours()*15.0);
}
// Get Local Sidereal Time, in hours, and adjust for time inside the menus
double CatMgr::lstHours() {
double msSinceT0=(unsigned long)(millis()-_lstMillisT0);
// Convert from Solar to Sidereal
double siderealSecondsSinceT0=(msSinceT0/1000.0)*1.00277778;
return _lstT0+siderealSecondsSinceT0/3600.0;
}
// number of catalogs available
int CatMgr::numCatalogs() {
for (int i=0; i<MaxCatalogs; i++) {
if (catalog[i].NumObjects==0) return i;
}
return 32;
}
gen_star_t* _genStarCatalog = NULL;
gen_star_vcomp_t* _genStarVCompCatalog = NULL;
dbl_star_t* _dblStarCatalog = NULL;
dbl_star_comp_t* _dblStarCompCatalog = NULL;
var_star_t* _varStarCatalog = NULL;
var_star_comp_t* _varStarCompCatalog = NULL;
dso_t* _dsoCatalog = NULL;
dso_comp_t* _dsoCompCatalog = NULL;
dso_vcomp_t* _dsoVCompCatalog = NULL;
// handle catalog selection (0..n)
void CatMgr::select(int number) {
_genStarCatalog =NULL;
_genStarVCompCatalog =NULL;
_dblStarCatalog =NULL;
_dsoCatalog =NULL;
_dsoCompCatalog =NULL;
_dsoVCompCatalog =NULL;
if ((number<0) || (number>=numCatalogs())) number=-1; // invalid catalog?
_selected=number;
if (_selected>=0) {
if (catalog[_selected].CatalogType==CAT_GEN_STAR) _genStarCatalog =(gen_star_t*)catalog[_selected].Objects; else
if (catalog[_selected].CatalogType==CAT_GEN_STAR_VCOMP) _genStarVCompCatalog=(gen_star_vcomp_t*)catalog[_selected].Objects; else
if (catalog[_selected].CatalogType==CAT_DBL_STAR) _dblStarCatalog =(dbl_star_t*)catalog[_selected].Objects; else
if (catalog[_selected].CatalogType==CAT_DBL_STAR_COMP) _dblStarCompCatalog =(dbl_star_comp_t*)catalog[_selected].Objects; else
if (catalog[_selected].CatalogType==CAT_VAR_STAR) _varStarCatalog =(var_star_t*)catalog[_selected].Objects; else
if (catalog[_selected].CatalogType==CAT_VAR_STAR_COMP) _varStarCompCatalog =(var_star_comp_t*)catalog[_selected].Objects; else
if (catalog[_selected].CatalogType==CAT_DSO) _dsoCatalog =(dso_t*)catalog[_selected].Objects; else
if (catalog[_selected].CatalogType==CAT_DSO_COMP) _dsoCompCatalog =(dso_comp_t*)catalog[_selected].Objects; else
if (catalog[_selected].CatalogType==CAT_DSO_VCOMP) _dsoVCompCatalog =(dso_vcomp_t*)catalog[_selected].Objects; else _selected=-1;
}
}
// Get active catalog type
CAT_TYPES CatMgr::catalogType() {
return catalog[_selected].CatalogType;
}
// check so see if there's a double star catalog present
bool CatMgr::hasDblStarCatalog() {
for (int i=0; i<MaxCatalogs; i++) {
if (catalog[i].CatalogType==CAT_DBL_STAR) return true;
if (catalog[i].CatalogType==CAT_DBL_STAR_COMP) return true;
if (catalog[i].CatalogType==CAT_NONE) break;
}
return false;
}
// check so see if theres a variable star catalog present
bool CatMgr::hasVarStarCatalog() {
for (int i=0; i<MaxCatalogs; i++) {
if (catalog[i].CatalogType==CAT_VAR_STAR) return true;
if (catalog[i].CatalogType==CAT_NONE) break;
}
return false;
}
// check to see if the primaryId() was moved to the prefix
bool CatMgr::hasPrimaryIdInPrefix() {
const char *s=catalog[_selected].Prefix;
return strstr(s,";");
}
bool CatMgr::isStarCatalog() {
return (catalogType()==CAT_GEN_STAR) || (catalogType()==CAT_GEN_STAR_VCOMP) ||
(catalogType()==CAT_DBL_STAR) || (catalogType()==CAT_DBL_STAR_COMP) ||
(catalogType()==CAT_VAR_STAR) || (catalogType()==CAT_VAR_STAR_COMP);
}
bool CatMgr::isDblStarCatalog() {
if (catalogType()==CAT_DBL_STAR) return true;
if (catalogType()==CAT_DBL_STAR_COMP) return true;
return false;
}
bool CatMgr::isVarStarCatalog() {
if (catalogType()==CAT_VAR_STAR) return true;
if (catalogType()==CAT_VAR_STAR_COMP) return true;
return false;
}
bool CatMgr::isDsoCatalog() {
return (catalogType()==CAT_DSO) || (catalogType()==CAT_DSO_COMP) || (catalogType()==CAT_DSO_VCOMP);
}
// Get active catalog title
const char* CatMgr::catalogTitle() {
if (_selected<0) return "";
char *subMenu=strstr(catalog[_selected].Title,">");
if (subMenu) {
return &subMenu[1];
} else return catalog[_selected].Title;
return catalog[_selected].Title;
}
// Get active catalog submenu
const char* CatMgr::catalogSubMenu() {
if (_selected<0) return "";
static char thisSubMenu[16];
strcpy(thisSubMenu,catalog[_selected].Title);
char *subMenu=strstr(thisSubMenu,">");
if (subMenu) {
subMenu[0]=0;
return thisSubMenu;
} else return "";
}
// Get active catalog prefix
const char* CatMgr::catalogPrefix() {
if (_selected<0) return "";
const char *s=catalog[_selected].Prefix;
// array type prefix?
if (strstr(s,";")) {
const char *s1;
long p=primaryId();
if (p>=0) {
s1=getElementFromString(s,p);
if (strlen(s1)>0) return s1; else {
s1=getElementFromString(s,0);
static char s2[24];
sprintf(s2,"%s%ld",s1,p);
return s2;
}
} else return "?";
} else return s;
}
// catalog filtering
void CatMgr::filtersClear() {
_fm=FM_NONE;
}
void CatMgr::filterAdd(int fm) {
_fm|=fm;
}
void CatMgr::filterAdd(int fm, int param) {
_fm|=fm;
if (fm&FM_CONSTELLATION) _fm_con=param;
if (fm&FM_BY_MAG) {
if (param==0) _fm_mag_limit=10.0; else
if (param==1) _fm_mag_limit=12.0; else
if (param==2) _fm_mag_limit=13.0; else
if (param==3) _fm_mag_limit=14.0; else
if (param==4) _fm_mag_limit=15.0; else
if (param==5) _fm_mag_limit=16.0; else
if (param==6) _fm_mag_limit=17.0; else _fm_mag_limit=100.0;
}
if (fm&FM_NEARBY) {
if (param==0) _fm_nearby_dist=1.0; else
if (param==1) _fm_nearby_dist=5.0; else
if (param==2) _fm_nearby_dist=10.0; else
if (param==3) _fm_nearby_dist=15.0; else _fm_nearby_dist=9999.0;
}
if (fm&FM_OBJ_TYPE) _fm_obj_type=param;
if (fm&FM_DBL_MIN_SEP) {
if (param==0) _fm_dbl_min=0.2; else
if (param==1) _fm_dbl_min=0.5; else
if (param==2) _fm_dbl_min=1.0; else
if (param==3) _fm_dbl_min=1.5; else
if (param==4) _fm_dbl_min=2.0; else
if (param==5) _fm_dbl_min=3.0; else
if (param==6) _fm_dbl_min=5.0; else
if (param==7) _fm_dbl_min=10.0; else
if (param==8) _fm_dbl_min=20.0; else
if (param==9) _fm_dbl_min=50.0; else _fm_dbl_min=0.0;
}
if (fm&FM_DBL_MAX_SEP) {
if (param==0) _fm_dbl_max=0.5; else
if (param==1) _fm_dbl_max=1.0; else
if (param==2) _fm_dbl_max=1.5; else
if (param==3) _fm_dbl_max=2.0; else
if (param==4) _fm_dbl_max=3.0; else
if (param==5) _fm_dbl_max=5.0; else
if (param==6) _fm_dbl_max=10.0; else
if (param==7) _fm_dbl_max=20.0; else
if (param==8) _fm_dbl_max=50.0; else
if (param==9) _fm_dbl_max=100.0; else _fm_dbl_max=0.0;
}
if (fm&FM_VAR_MAX_PER) {
if (param==0) _fm_var_max=0.5; else
if (param==1) _fm_var_max=1.0; else
if (param==2) _fm_var_max=2.0; else
if (param==3) _fm_var_max=5.0; else
if (param==4) _fm_var_max=10.0; else
if (param==5) _fm_var_max=20.0; else
if (param==6) _fm_var_max=50.0; else
if (param==7) _fm_var_max=100.0; else _fm_var_max=0.0; }
}
// checks to see if the currently selected catalog has an active filter
bool CatMgr::hasActiveFilter() {
if (!isInitialized()) return false;
if (_fm==FM_NONE) return false;
//if (_fm & FM_ABOVE_HORIZON) return true; // doesn't apply to this indication
if (_fm & FM_CONSTELLATION) return true;
if (isDsoCatalog() && (_fm & FM_OBJ_TYPE)) return true;
if (_fm & FM_BY_MAG) return true;
if (_fm & FM_NEARBY) return true;
if (isDblStarCatalog() && (_fm & FM_DBL_MAX_SEP)) return true;
if (isDblStarCatalog() && (_fm & FM_DBL_MIN_SEP)) return true;
if (isVarStarCatalog() && (_fm & FM_VAR_MAX_PER)) return true;
return false;
}
// checks to see if the currently selected object is filtered (returns true if filtered out)
bool CatMgr::isFiltered() {
if (!isInitialized()) return false;
if (_fm == FM_NONE) return false;
if (_fm & FM_CONSTELLATION) { if (constellation()!=_fm_con) return true; }
if (_fm & FM_OBJ_TYPE) { if (isDsoCatalog() && (objectType()!=_fm_obj_type)) return true; }
if (_fm & FM_BY_MAG) { if (magnitude()>=_fm_mag_limit) return true; }
if (_fm & FM_NEARBY) { if (DistFromEqu(_lastTeleRA,_lastTeleDec)>=_fm_nearby_dist) return true; }
if (_fm & FM_DBL_MAX_SEP) { if (isDblStarCatalog() && ((separation()>_fm_dbl_max) || (separation()<0))) return true; }
if (_fm & FM_DBL_MIN_SEP) { if (isDblStarCatalog() && ((separation()<_fm_dbl_min) || (separation()<0))) return true; }
if (_fm & FM_VAR_MAX_PER) { if (isVarStarCatalog() && ((period() >_fm_var_max) || (period() <0))) return true; }
if (_fm & FM_ABOVE_HORIZON) { if (alt()<0.0) return true; }
if (_fm & FM_ALIGN_ALL_SKY) {
if (magnitude()>3.0) return true; // maximum magnitude 3.0
if (alt()<10.0) return true; // minimum 10 degrees altitude
if (abs(dec())>80.0) return true; // minimum 10 degrees from the pole (for accuracy)
}
return false;
}
// select catalog record
bool CatMgr::setIndex(long index) {
if (_selected<0) return false;
catalog[_selected].Index=index;
decIndex();
return incIndex();
}
long CatMgr::getIndex() {
return catalog[_selected].Index;
}
long CatMgr::getMaxIndex() {
return catalog[_selected].NumObjects-1;
}
bool CatMgr::incIndex() {
long i=getMaxIndex()+1;
do {
i--;
catalog[_selected].Index++;
if (catalog[_selected].Index>getMaxIndex()) catalog[_selected].Index=0;
} while (isFiltered() && (i>0));
if (isFiltered()) return false; else return true;
}
bool CatMgr::decIndex() {
long i=getMaxIndex()+1;
do {
i--;
catalog[_selected].Index--;
if (catalog[_selected].Index<0) catalog[_selected].Index=getMaxIndex();
} while (isFiltered() && (i>0));
if (isFiltered()) return false; else return true;
}
// get catalog contents
// RA, converted from hours to degrees
double CatMgr::ra() {
return rah()*15.0;
}
// RA in hours
double CatMgr::rah() {
if (_selected<0) return 0;
if (catalogType()==CAT_GEN_STAR) return _genStarCatalog[catalog[_selected].Index].RA; else
if (catalogType()==CAT_GEN_STAR_VCOMP) return _genStarVCompCatalog[catalog[_selected].Index].RA/2730.6666666666666; else
if (catalogType()==CAT_DBL_STAR) return _dblStarCatalog[catalog[_selected].Index].RA; else
if (catalogType()==CAT_DBL_STAR_COMP) return _dblStarCompCatalog[catalog[_selected].Index].RA/2730.6666666666666; else
if (catalogType()==CAT_VAR_STAR) return _varStarCatalog[catalog[_selected].Index].RA; else
if (catalogType()==CAT_VAR_STAR_COMP) return _varStarCompCatalog[catalog[_selected].Index].RA/2730.6666666666666; else
if (catalogType()==CAT_DSO) return _dsoCatalog[catalog[_selected].Index].RA; else
if (catalogType()==CAT_DSO_COMP) return _dsoCompCatalog[catalog[_selected].Index].RA/2730.6666666666666; else
if (catalogType()==CAT_DSO_VCOMP) return _dsoVCompCatalog[catalog[_selected].Index].RA/2730.6666666666666; else return 0;
}
// HA in degrees
double CatMgr::ha() {
if (!isInitialized()) return 0;
double h=(lstDegs()-ra());
while (h>180.0) h-=360.0;
while (h<-180.0) h+=360.0;
return h;
}
// Get RA of an object, in hours, minutes, seconds
void CatMgr::raHMS(uint8_t &h, uint8_t &m, uint8_t &s) {
double f=rah();
double h1,m1,s1;
h1=floor(f);
m1=(f-h1)*60;
s1=(m1-floor(m1))*60.0;
h = (int)h1;
m = (int)m1;
s = (int)s1;
}
// Dec in degrees
double CatMgr::dec() {
if (catalogType()==CAT_GEN_STAR) return _genStarCatalog[catalog[_selected].Index].DE; else
if (catalogType()==CAT_GEN_STAR_VCOMP) return _genStarVCompCatalog[catalog[_selected].Index].DE/364.07777777777777; else
if (catalogType()==CAT_DBL_STAR) return _dblStarCatalog[catalog[_selected].Index].DE; else
if (catalogType()==CAT_DBL_STAR_COMP) return _dblStarCompCatalog[catalog[_selected].Index].DE/364.07777777777777; else
if (catalogType()==CAT_VAR_STAR) return _varStarCatalog[catalog[_selected].Index].DE; else
if (catalogType()==CAT_VAR_STAR_COMP) return _varStarCompCatalog[catalog[_selected].Index].DE/364.07777777777777; else
if (catalogType()==CAT_DSO) return _dsoCatalog[catalog[_selected].Index].DE; else
if (catalogType()==CAT_DSO_COMP) return _dsoCompCatalog[catalog[_selected].Index].DE/364.07777777777777; else
if (catalogType()==CAT_DSO_VCOMP) return _dsoVCompCatalog[catalog[_selected].Index].DE/364.07777777777777; else return 0;
}
// Declination as degrees, minutes, seconds
void CatMgr::decDMS(short& d, uint8_t& m, uint8_t& s) {
double f=dec();
double d1, m1, s1;
int sign=1; if (f<0) sign=-1;
f=f*sign;
d1=floor(f);
m1=(f-d1)*60;
s1=(m1-floor(m1))*60.0;
d = (int)d1*sign;
m = (int)m1;
s = (int)s1;
}
// Epoch for catalog
int CatMgr::epoch() {
if (_selected<0) return -1;
return catalog[_selected].Epoch;
}
// Alt in degrees
double CatMgr::alt() {
double a;
EquToAlt(ra(),dec(),&a);
return a;
}
// Declination as degrees, minutes, seconds
void CatMgr::altDMS(short &d, uint8_t &m, uint8_t &s) {
double f=alt();
double d1, m1, s1;
int sign=1; if (f<0) sign=-1;
f=f*sign;
d1=floor(f);
m1=(f-d1)*60;
s1=(m1-floor(m1))*60.0;
d = (int)d1*sign;
m = (int)m1;
s = (int)s1;
}
// Azm in degrees
double CatMgr::azm() {
double a,z;
EquToHor(ra(),dec(),&a,&z);
return z;
}
// Get Azm of an object, in degrees, minutes, seconds
void CatMgr::azmDMS(short &d, uint8_t &m, uint8_t &s) {
double f=azm();
double d1,m1,s1;
d1=floor(f);
m1=(f-d1)*60;
s1=(m1-floor(m1))*60.0;
d = (int)d1;
m = (int)m1;
s = (int)s1;
}
// apply refraction, this converts from the "Topocentric" to "Observed" place for higher accuracy, RA in hours Dec in degrees
void CatMgr::topocentricToObservedPlace(float *RA, float *Dec) {
if (isInitialized()) {
double Alt,Azm;
double r=*RA*15.0;
double d=*Dec;
EquToHor(r,d,&Alt,&Azm);
Alt = Alt+TrueRefrac(Alt) / 60.0;
HorToEqu(Alt,Azm,&r,&d);
*RA=r/15.0; *Dec=d;
}
}
// Period of variable star, in days
// -2 = irregular, -1 = unknown
float CatMgr::period() {
if (_selected<0) return -1;
float p;
if (catalogType()==CAT_VAR_STAR) p=_varStarCatalog[catalog[_selected].Index].Period; else
if (catalogType()==CAT_VAR_STAR_COMP) p=_varStarCatalog[catalog[_selected].Index].Period; else return -1;
// Period 0.00 to 9.99 days (0 to 999) period 10.0 to 3186.6 days (1000 to 32766), 32766 = Irregular, 32767 = Unknown
if ((p>=0) && (p<=999)) return p/100.0; else
if ((p>999) && (p<=32765)) return (p-900)/10.0; else
if (p==32766) return -2; else return -1;
}
// Position angle of double star, in degrees
// -1 = Unknown
int CatMgr::positionAngle() {
if (_selected<0) return -1;
int p;
if (catalogType()==CAT_DBL_STAR) p=_dblStarCatalog[catalog[_selected].Index].PA; else
if (catalogType()==CAT_DBL_STAR_COMP) p=_dblStarCompCatalog[catalog[_selected].Index].PA; else return -1;
// Position angle 0 to 360 degrees, 361 = Unknown
if (p==361) return -1; else return p;
}
// Separation of double star, in arc-seconds
// -1 = Unknown
float CatMgr::separation() {
if (_selected<0) return -1;
float s;
if (catalogType()==CAT_DBL_STAR) s=_dblStarCatalog[catalog[_selected].Index].Sep/10.0; else
if (catalogType()==CAT_DBL_STAR_COMP) s=_dblStarCompCatalog[catalog[_selected].Index].Sep/10.0; else return -1;
// Seperation 0 to 999.8 (0 to 9998) arc-seconds, 9999=unknown
if (abs(s-999.9)<0.01) return -1; else return s;
}
// Magnitude of an object
// 99.9 = Unknown
float CatMgr::magnitude() {
if (_selected<0) return 99.9;
if (catalogType()==CAT_GEN_STAR) return _genStarCatalog[catalog[_selected].Index].Mag/100.0; else
if (catalogType()==CAT_GEN_STAR_VCOMP) { int m=_genStarVCompCatalog[catalog[_selected].Index].Mag; if (m==255) return 99.9; else return (m/10.0)-2.5; } else
if (catalogType()==CAT_DBL_STAR) return _dblStarCatalog[catalog[_selected].Index].Mag/100.0; else
if (catalogType()==CAT_DBL_STAR_COMP) { int m=_dblStarCompCatalog[catalog[_selected].Index].Mag; if (m==255) return 99.9; else return (m/10.0)-2.5; } else
if (catalogType()==CAT_VAR_STAR) return _varStarCatalog[catalog[_selected].Index].Mag/100.0; else
if (catalogType()==CAT_VAR_STAR_COMP) { int m=_varStarCompCatalog[catalog[_selected].Index].Mag; if (m==255) return 99.9; else return (m/10.0)-2.5; } else
if (catalogType()==CAT_DSO) return _dsoCatalog[catalog[_selected].Index].Mag/100.0; else
if (catalogType()==CAT_DSO_COMP) { int m=_dsoCompCatalog[catalog[_selected].Index].Mag; if (m==255) return 99.9; else return (m/10.0)-2.5; } else
if (catalogType()==CAT_DSO_VCOMP) { int m=_dsoVCompCatalog[catalog[_selected].Index].Mag; if (m==255) return 99.9; else return (m/10.0)-2.5; } else return 99.9;
}
// Secondary magnitude of an star. For double stars this is the magnitude of the secondary. For variables this is the minimum brightness.
// 99.9 = Unknown
float CatMgr::magnitude2() {
if (_selected<0) return 99.9;
if (catalogType()==CAT_DBL_STAR) return _dblStarCatalog[catalog[_selected].Index].Mag2/100.0; else
if (catalogType()==CAT_DBL_STAR_COMP) { int m=_dblStarCompCatalog[catalog[_selected].Index].Mag2; if (m==255) return 99.9; else return (m/10.0)-2.5; } else
if (catalogType()==CAT_VAR_STAR) return _varStarCatalog[catalog[_selected].Index].Mag2/100.0; else
if (catalogType()==CAT_VAR_STAR_COMP) { int m=_varStarCompCatalog[catalog[_selected].Index].Mag2; if (m==255) return 99.9; else return (m/10.0)-2.5; } return 99.9;
}
// Constellation number
// 89 = Unknown
byte CatMgr::constellation() {
if (_selected<0) return 89;
if (catalogType()==CAT_GEN_STAR) return _genStarCatalog[catalog[_selected].Index].Cons; else
if (catalogType()==CAT_GEN_STAR_VCOMP) return _genStarVCompCatalog[catalog[_selected].Index].Cons; else
if (catalogType()==CAT_DBL_STAR) return _dblStarCatalog[catalog[_selected].Index].Cons; else
if (catalogType()==CAT_DBL_STAR_COMP) return _dblStarCompCatalog[catalog[_selected].Index].Cons; else
if (catalogType()==CAT_VAR_STAR) return _varStarCatalog[catalog[_selected].Index].Cons; else
if (catalogType()==CAT_VAR_STAR_COMP) return _varStarCompCatalog[catalog[_selected].Index].Cons; else
if (catalogType()==CAT_DSO) return _dsoCatalog[catalog[_selected].Index].Cons; else
if (catalogType()==CAT_DSO_COMP) return _dsoCompCatalog[catalog[_selected].Index].Cons; else
if (catalogType()==CAT_DSO_VCOMP) return _dsoVCompCatalog[catalog[_selected].Index].Cons; else return 89;
}
// Constellation string
const char* CatMgr::constellationStr() {
return Txt_Constellations[constellation()];
}
// Constellation string, from constellation number
const char* CatMgr::constellationCodeToStr(int code) {
if ((code>=0) && (code<=87)) return Txt_Constellations[code]; else return "";
}
// Object type code
byte CatMgr::objectType() {
if (_selected<0) return -1;
if (catalogType()==CAT_GEN_STAR) return 2; else
if (catalogType()==CAT_GEN_STAR_VCOMP) return 2; else
if (catalogType()==CAT_DBL_STAR) return 2; else
if (catalogType()==CAT_DBL_STAR_COMP) return 2; else
if (catalogType()==CAT_VAR_STAR) return 2; else
if (catalogType()==CAT_VAR_STAR_COMP) return 2; else
if (catalogType()==CAT_DSO) return _dsoCatalog[catalog[_selected].Index].Obj_type; else
if (catalogType()==CAT_DSO_COMP) return _dsoCompCatalog[catalog[_selected].Index].Obj_type; else
if (catalogType()==CAT_DSO_VCOMP) return _dsoVCompCatalog[catalog[_selected].Index].Obj_type; else return -1;
}
// Object type string
const char* CatMgr::objectTypeStr() {
int t=objectType();
if ((t>=0) && (t<=20)) return Txt_Object_Type[t]; else return "";
}
// Object Type string, from code number
const char* CatMgr::objectTypeCodeToStr(int code) {
if ((code>=0) && (code<=20)) return Txt_Object_Type[code]; else return "";
}
// Object name code (encoded by Has_name.) Returns -1 if the object doesn't have a name code.
long CatMgr::objectName() {
if (_selected<0) return -1;
// does it have a name? if not just return
if (catalogType()==CAT_GEN_STAR) { if (!_genStarCatalog[catalog[_selected].Index].Has_name) return -1; } else
if (catalogType()==CAT_GEN_STAR_VCOMP) { if (!_genStarVCompCatalog[catalog[_selected].Index].Has_name) return -1; } else
if (catalogType()==CAT_DBL_STAR) { if (!_dblStarCatalog[catalog[_selected].Index].Has_name) return -1; } else
if (catalogType()==CAT_DBL_STAR_COMP) { if (!_dblStarCompCatalog[catalog[_selected].Index].Has_name) return -1; } else
if (catalogType()==CAT_VAR_STAR) { if (!_varStarCatalog[catalog[_selected].Index].Has_name) return -1; } else
if (catalogType()==CAT_VAR_STAR_COMP) { if (!_varStarCompCatalog[catalog[_selected].Index].Has_name) return -1; } else
if (catalogType()==CAT_DSO) { if (!_dsoCatalog[catalog[_selected].Index].Has_name) return -1; } else
if (catalogType()==CAT_DSO_COMP) { if (!_dsoCompCatalog[catalog[_selected].Index].Has_name) return -1; } else
if (catalogType()==CAT_DSO_VCOMP) { if (!_dsoVCompCatalog[catalog[_selected].Index].Has_name) return -1; } else return -1;
// find the code
long result=-1;
long j=catalog[_selected].Index;
if (j>getMaxIndex()) j=-1;
if (j<0) return -1;
if (catalogType()==CAT_GEN_STAR) { for (long i=0; i<=j; i++) { if (_genStarCatalog[i].Has_name) result++; } } else
if (catalogType()==CAT_GEN_STAR_VCOMP) { for (long i=0; i<=j; i++) { if (_genStarVCompCatalog[i].Has_name) result++; } } else
if (catalogType()==CAT_DBL_STAR) { for (long i=0; i<=j; i++) { if (_dblStarCatalog[i].Has_name) result++; } } else
if (catalogType()==CAT_DBL_STAR_COMP) { for (long i=0; i<=j; i++) { if (_dblStarCompCatalog[i].Has_name) result++; } } else
if (catalogType()==CAT_VAR_STAR) { for (long i=0; i<=j; i++) { if (_varStarCatalog[i].Has_name) result++; } } else
if (catalogType()==CAT_VAR_STAR_COMP) { for (long i=0; i<=j; i++) { if (_varStarCompCatalog[i].Has_name) result++; } } else
if (catalogType()==CAT_DSO) { for (long i=0; i<=j; i++) { if (_dsoCatalog[i].Has_name) result++; } } else
if (catalogType()==CAT_DSO_COMP) { for (long i=0; i<=j; i++) { if (_dsoCompCatalog[i].Has_name) result++; } } else
if (catalogType()==CAT_DSO_VCOMP) { for (long i=0; i<=j; i++) { if (_dsoVCompCatalog[i].Has_name) result++; } } else return -1;
return result;
}
// Object name type string
const char* CatMgr::objectNameStr() {
if (_selected<0) return "";
long elementNum=objectName();
if (elementNum>=0) return getElementFromString(catalog[_selected].ObjectNames,elementNum); else return "";
}
// Object Id
long CatMgr::primaryId() {
long id=-1;
if (_selected<0) return -1;
if (catalogType()==CAT_GEN_STAR) id=_genStarCatalog[catalog[_selected].Index].Obj_id; else
if (catalogType()==CAT_GEN_STAR_VCOMP) id= catalog[_selected].Index+1; else
if (catalogType()==CAT_DBL_STAR) id=_dblStarCatalog[catalog[_selected].Index].Obj_id; else
if (catalogType()==CAT_DBL_STAR_COMP) id=_dblStarCompCatalog[catalog[_selected].Index].Obj_id; else
if (catalogType()==CAT_VAR_STAR) id=_varStarCatalog[catalog[_selected].Index].Obj_id; else
if (catalogType()==CAT_VAR_STAR_COMP) id=_varStarCompCatalog[catalog[_selected].Index].Obj_id; else
if (catalogType()==CAT_DSO) id=_dsoCatalog[catalog[_selected].Index].Obj_id; else
if (catalogType()==CAT_DSO_COMP) id=_dsoCompCatalog[catalog[_selected].Index].Obj_id; else
if (catalogType()==CAT_DSO_VCOMP) id=catalog[_selected].Index+1; else return -1;
if (id<1) return -1;
return id;
}
// Object note code (encoded by Has_note.) Returns -1 if the object doesn't have a note code.
long CatMgr::subId() {
if (_selected<0) return -1;
// does it have a note? if not just return
if (catalogType()==CAT_GEN_STAR) { if (!_genStarCatalog[catalog[_selected].Index].Has_subId) return -1; } else
if (catalogType()==CAT_GEN_STAR_VCOMP) { if (!_genStarVCompCatalog[catalog[_selected].Index].Has_subId) return -1; } else
if (catalogType()==CAT_DBL_STAR) { if (!_dblStarCatalog[catalog[_selected].Index].Has_subId) return -1; } else
if (catalogType()==CAT_DBL_STAR_COMP) { if (!_dblStarCompCatalog[catalog[_selected].Index].Has_subId) return -1; } else
if (catalogType()==CAT_VAR_STAR) { if (!_varStarCatalog[catalog[_selected].Index].Has_subId) return -1; } else
if (catalogType()==CAT_VAR_STAR_COMP) { if (!_varStarCompCatalog[catalog[_selected].Index].Has_subId) return -1; } else
if (catalogType()==CAT_DSO) { if (!_dsoCatalog[catalog[_selected].Index].Has_subId) return -1; } else
if (catalogType()==CAT_DSO_COMP) { if (!_dsoCompCatalog[catalog[_selected].Index].Has_subId) return -1; } else
if (catalogType()==CAT_DSO_VCOMP) { if (!_dsoVCompCatalog[catalog[_selected].Index].Has_subId) return -1; } else return -1;
// find the code
long result=-1;
long j=catalog[_selected].Index;
if (j>getMaxIndex()) j=-1;
if (j<0) return -1;
if (catalogType()==CAT_GEN_STAR) { for (long i=0; i<=j; i++) { if (_genStarCatalog[i].Has_subId) result++; } } else
if (catalogType()==CAT_GEN_STAR_VCOMP) { for (long i=0; i<=j; i++) { if (_genStarVCompCatalog[i].Has_subId) result++; } } else
if (catalogType()==CAT_DBL_STAR) { for (long i=0; i<=j; i++) { if (_dblStarCatalog[i].Has_subId) result++; } } else
if (catalogType()==CAT_DBL_STAR_COMP) { for (long i=0; i<=j; i++) { if (_dblStarCompCatalog[i].Has_subId) result++; } } else
if (catalogType()==CAT_VAR_STAR) { for (long i=0; i<=j; i++) { if (_varStarCatalog[i].Has_subId) result++; } } else
if (catalogType()==CAT_VAR_STAR_COMP) { for (long i=0; i<=j; i++) { if (_varStarCompCatalog[i].Has_subId) result++; } } else
if (catalogType()==CAT_DSO) { for (long i=0; i<=j; i++) { if (_dsoCatalog[i].Has_subId) result++; } } else
if (catalogType()==CAT_DSO_COMP) { for (long i=0; i<=j; i++) { if (_dsoCompCatalog[i].Has_subId) result++; } } else
if (catalogType()==CAT_DSO_VCOMP) { for (long i=0; i<=j; i++) { if (_dsoVCompCatalog[i].Has_subId) result++; } } else return -1;
return result;
}
// Object note string
const char* CatMgr::subIdStr() {
if (_selected<0) return "";
long elementNum=subId();
if (elementNum>=0) return getElementFromString(catalog[_selected].ObjectSubIds,elementNum); else return "";
}
// For Bayer designated Stars 0 = Alp, etc. to 23. For Fleemstead designated Stars 25 = '1', etc.
int CatMgr::bayerFlam() {
if (_selected<0) return -1;
int bf=24;
if (catalogType()==CAT_GEN_STAR) bf=_genStarCatalog[catalog[_selected].Index].BayerFlam; else
if (catalogType()==CAT_GEN_STAR_VCOMP) bf=_genStarVCompCatalog[catalog[_selected].Index].BayerFlam; else
if (catalogType()==CAT_DBL_STAR) bf=_dblStarCatalog[catalog[_selected].Index].BayerFlam; else
if (catalogType()==CAT_DBL_STAR_COMP) bf=_dblStarCompCatalog[catalog[_selected].Index].BayerFlam; else
if (catalogType()==CAT_VAR_STAR) bf=_varStarCatalog[catalog[_selected].Index].BayerFlam; else
if (catalogType()==CAT_VAR_STAR_COMP) bf=_varStarCompCatalog[catalog[_selected].Index].BayerFlam; else return -1;
if (bf==24) return -1; else return bf;
}
// For Bayer designated Stars return greek letter or Flamsteed designated stars return number
const char* CatMgr::bayerFlamStr() {
if (_selected<0) return "";
static char bfStr[3]="";
int bfNum=bayerFlam();
if ((bfNum>=0) && (bfNum<24)) {
sprintf(bfStr,"%d",bfNum);
return bfStr;
} else
if (bfNum>24) {
sprintf(bfStr,"%d",bfNum-24);
return bfStr;
} else
return "";
}
// support functions
// returns elementNum 'th element from the comma delimited string where the 0th element is the first etc.
const char* CatMgr::getElementFromString(const char *data, long elementNum) {
static char result[40] = "";
// find the string start index
bool found=false;
long j=0;
long n=elementNum;
long len=strlen(data);
for (long i=0; i<len; i++) {
if (n==0) { j=i; found=true; break; }
if (data[i]==';') { n--; }
}
// return the string
if (found) {
long k=0;
for (long i=j; i<len; i++) {
result[k++]=data[i];
if (result[k-1]==';') { result[k-1]=0; break; }
if (i==len-1) { result[k]=0; break; }
}
return result;
} else return "";
}
// angular distance from current Equ coords, in degrees
double CatMgr::DistFromEqu(double RA, double Dec) {
RA=RA/Rad; Dec=Dec/Rad;
return acos( sin(dec()/Rad)*sin(Dec) + cos(dec()/Rad)*cos(Dec)*cos(ra()/Rad - RA))*Rad;
}
// convert an HA to RA, in degrees
double CatMgr::HAToRA(double HA) {
return (lstDegs()-HA);
}
// convert equatorial coordinates to horizon, in degrees
void CatMgr::EquToHor(double RA, double Dec, double *Alt, double *Azm) {
double HA=lstDegs()-RA;
while (HA<0.0) HA=HA+360.0;
while (HA>=360.0) HA=HA-360.0;
HA =HA/Rad;
Dec=Dec/Rad;
double SinAlt = (sin(Dec) * _sinLat) + (cos(Dec) * _cosLat * cos(HA));
*Alt = asin(SinAlt);
double t1=sin(HA);
double t2=cos(HA)*_sinLat-tan(Dec)*_cosLat;
*Azm=atan2(t1,t2)*Rad;
*Azm=*Azm+180.0;
*Alt = *Alt*Rad;
}
// convert equatorial coordinates to horizon, in degrees
void CatMgr::EquToAlt(double RA, double Dec, double *Alt) {
double HA=lstDegs()-RA;
while (HA<0.0) HA=HA+360.0;
while (HA>=360.0) HA=HA-360.0;
HA =HA/Rad;
Dec=Dec/Rad;
double SinAlt = (sin(Dec) * _sinLat) + (cos(Dec) * _cosLat * cos(HA));
*Alt = asin(SinAlt);
*Alt = *Alt*Rad;
}
// convert horizon coordinates to equatorial, in degrees
void CatMgr::HorToEqu(double Alt, double Azm, double *RA, double *Dec) {
while (Azm<0) Azm=Azm+360.0;
while (Azm>=360.0) Azm=Azm-360.0;
Alt = Alt/Rad;
Azm = Azm/Rad;
double SinDec = (sin(Alt) * _sinLat) + (cos(Alt) * _cosLat * cos(Azm));
*Dec = asin(SinDec);
double t1=sin(Azm);
double t2=cos(Azm)*_sinLat-tan(Alt)*_cosLat;
double HA=atan2(t1,t2)*Rad;
HA=HA+180.0;
*Dec = *Dec*Rad;
while (HA<0.0) HA=HA+360.0;
while (HA>=360.0) HA=HA-360.0;
*RA=(lstDegs()-HA);
}
// returns the amount of refraction (in arcminutes) at the given true altitude (degrees), pressure (millibars), and temperature (celsius)
double CatMgr::TrueRefrac(double Alt, double Pressure, double Temperature) {
double TPC=(Pressure/1010.0) * (283.0/(273.0+Temperature));
double r=( ( 1.02*cot( (Alt+(10.3/(Alt+5.11)))/Rad ) ) ) * TPC; if (r<0.0) r=0.0;
return r;
}
double CatMgr::cot(double n) {
return 1.0/tan(n);
}
CatMgr cat_mgr;
| 39.905779
| 167
| 0.67672
|
Zarfab
|
8bae1e41ca23b4a31d54bdef6f8b78adebc70d22
| 9,234
|
cpp
|
C++
|
Source/UMod/Game/UModHUD.cpp
|
StoneLineDevTeam/UMod
|
e57e41b95d8cdcc4479965453ac86e5116178795
|
[
"BSD-4-Clause"
] | 21
|
2015-09-03T13:17:55.000Z
|
2022-03-28T15:55:42.000Z
|
Source/UMod/Game/UModHUD.cpp
|
StoneLineDevTeam/UMod
|
e57e41b95d8cdcc4479965453ac86e5116178795
|
[
"BSD-4-Clause"
] | 24
|
2015-09-19T18:03:30.000Z
|
2018-12-21T10:53:01.000Z
|
Source/UMod/Game/UModHUD.cpp
|
StoneLineDevTeam/UMod
|
e57e41b95d8cdcc4479965453ac86e5116178795
|
[
"BSD-4-Clause"
] | 17
|
2015-09-03T13:18:04.000Z
|
2021-11-24T02:14:11.000Z
|
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#include "UMod.h"
#include "UModHUD.h"
#include "Engine/Canvas.h"
#include "TextureResource.h"
#include "CanvasItem.h"
#include "Renderer/Render2D.h"
#include "Player/UModCharacter.h"
#include "Player/UModController.h"
#include "UModGameInstance.h"
const FColor Back = FColor(50, 50, 50, 255);
const FColor DarkGrey = FColor(0, 0, 0, 255);
const FColor Black = FColor(0, 0, 0, 255);
const FColor White = FColor(255, 255, 255, 255);
const FColor Red = FColor(55, 0, 0, 255);
const FColor Green = FColor(0, 255, 0, 255);
const FColor Yellow = FColor(255, 255, 0, 255);
const FColor AmmoCol = FColor(255, 180, 0, 255);
struct Button {
FString text;
uint8 id;
Button(uint8 i, FString t) {
text = t;
id = i;
}
};
const Button* Buttons[16] = {
new Button(0, FString("Back to game")),
new Button(1, FString("Disconnect"))
};
AUModHUD::AUModHUD(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)
{
UUModAssetsManager::PrecacheAssets.AddDynamic(this, &AUModHUD::Precache);
}
void AUModHUD::Precache()
{
CrosshairTex = URender2D::LoadTexture("Internal:Textures/FirstPersonCrosshair");
HUDFont = URender2D::LoadFont("UMod:FederationRegular", 32);
}
void AUModHUD::BeginPlay()
{
Super::BeginPlay();
Game = Cast<UUModGameInstance>(GetGameInstance());
PlyCtrl = Cast<AUModController>(GetOwningPlayerController());
PlyCtrl->OnMouseClick.AddDynamic(this, &AUModHUD::HandleMouseClick);
UE_LOG(UMod_Game, Log, TEXT("[DEBUG]BeginPlay called for HUD"));
}
FVector2D AUModHUD::ScreenSize()
{
FVector2D ScrSize = FVector2D(GEngine->GameViewport->Viewport->GetSizeXY());
return ScrSize;
}
bool IsMouseInRect(float msPosX, float msPosY, float x, float y, float w, float h)
{
if (msPosX >= x && msPosX <= (x + w)) {
if (msPosY >= y && msPosY <= (y + h)) {
return true;
}
}
return false;
}
void AUModHUD::OnButtonClick(uint8 id)
{
switch (id) {
case 0:
PlyCtrl->ExitIngameMenu();
break;
case 1:
Game->Disconnect(FString("You disconnected !"));
}
}
void AUModHUD::HandleMouseClick(float x, float y)
{
FVector2D size = ScreenSize();
for (int i = 0; i < 16; i++) {
const Button* but = Buttons[i];
if (but != NULL) {
if (FVUIUtils::IsMouseInRect(size.X / 2 - 256, 200 + i * 70, 512, 64)) {
OnButtonClick(but->id);
}
}
}
}
void AUModHUD::DrawIngameMenu()
{
FVector2D size = ScreenSize();
float msPosX;
float msPosY;
PlyCtrl->GetMousePosition(msPosX, msPosY);
URender2D::SetColor(DarkGrey);
URender2D::SetFontScale(1, 1);
URender2D::DrawText("UMod - " + Game->GetGameMode(), size.X / 2, 100, TEXT_ALIGN_CENTER);
for (int i = 0; i < 16; i++) {
const Button* but = Buttons[i];
if (but != NULL) {
if (FVUIUtils::IsMouseInRect(size.X / 2 - 256, 200 + i * 70, 512, 64)) {
URender2D::SetColor(FColor(200, 200, 200, 200));
URender2D::DrawRect(size.X / 2 - 256, 200 + i * 70, 512, 64);
} else {
URender2D::SetColor(FColor(133, 133, 133, 200));
URender2D::DrawRect(size.X / 2 - 256, 200 + i * 70, 512, 64);
}
URender2D::SetColor(White);
URender2D::DrawText(but->text, size.X / 2 - 256, 200 + i * 70 + 10, TEXT_ALIGN_LEFT);
}
}
}
void AUModHUD::DrawPlayerStats()
{
FVector2D size = ScreenSize();
//Variables
uint32 Health = PlyCtrl->NativePlayer->GetHealth();
uint32 MaxHealth = PlyCtrl->NativePlayer->GetMaxHealth();
int Armor = 45; //Why !? There is no armor feature planned, if you want armor feature tell me.
URender2D::SetColor(Back);
URender2D::DrawRect(5, (size.Y / 7 * 6) - 5, size.X / 4.5, size.Y / 7);
float BoxSizeX = size.X / 4.5;
float BoxSizeY = size.Y / 7;
URender2D::SetFontScale(0.5, 0.5);
URender2D::SetColor(White);
URender2D::DrawText("Health : " + FString::FromInt(Health), 10, (size.Y / 7 * 6) + 5, TEXT_ALIGN_LEFT);
URender2D::SetColor(DarkGrey);
URender2D::DrawRect(10, ((size.Y / 7 * 6) - 5) + (size.Y / 6 / 3) - 4 * 2, BoxSizeX - 10, size.Y / 7 / 5.8);
URender2D::SetColor(White);
URender2D::DrawText("Armor : " + FString::FromInt(Armor), 10, (size.Y / 7 * 6) + (BoxSizeY / 2), TEXT_ALIGN_LEFT);
URender2D::SetColor(DarkGrey);
URender2D::DrawRect(10, ((size.Y / 7 * 6) - 5) + (BoxSizeY / 4 * 3), BoxSizeX - 10, (size.Y / 7 / 5.8));
if (Health >= MaxHealth / 2 && Health <= 100) {
URender2D::SetColor(Green);
URender2D::DrawRect(10, ((size.Y / 7 * 6) - 5) + (size.Y / 6 / 3) - 4 * 2, (BoxSizeX - 10) / MaxHealth * Health, size.Y / 7 / 5.8);
} else if (Health > 20 && Health < 50) {
URender2D::SetColor(Yellow);
URender2D::DrawRect(10, ((size.Y / 7 * 6) - 5) + (size.Y / 6 / 3) - 4 * 2, (BoxSizeX - 10) / MaxHealth * Health, size.Y / 7 / 5.8);
} else if (Health <= 20) {
URender2D::SetColor(Red);
URender2D::DrawRect(10, ((size.Y / 7 * 6) - 5) + (size.Y / 6 / 3) - 4 * 2, (BoxSizeX - 10) / MaxHealth * Health, size.Y / 7 / 5.8);
}
if (Armor > 100) { //Not planned, if you realy want armor management, then tell me.
URender2D::SetColor(Green);
URender2D::DrawRect(10, ((size.Y / 7 * 6) - 5) + (BoxSizeY / 4 * 3), BoxSizeX - 10, (size.Y / 7 / 5.8));
} else if (Armor >= 50 && Armor <= 100) {
URender2D::SetColor(Green);
URender2D::DrawRect(10, ((size.Y / 7 * 6) - 5) + (BoxSizeY / 4 * 3), (BoxSizeX - 10) / 100 * Armor, (size.Y / 7 / 5.8));
} else if (Armor > 20 && Armor < 50) {
URender2D::SetColor(Yellow);
URender2D::DrawRect(10, ((size.Y / 7 * 6) - 5) + (BoxSizeY / 4 * 3), (BoxSizeX - 10) / 100 * Armor, (size.Y / 7 / 5.8));
} else if (Armor <= 20) {
URender2D::SetColor(Red);
URender2D::DrawRect(10, ((size.Y / 7 * 6) - 5) + (BoxSizeY / 4 * 3), (BoxSizeX - 10) / 100 * Armor, (size.Y / 7 / 5.8));
}
}
void AUModHUD::DrawWeaponStats()
{
FVector2D size = ScreenSize();
//Ammo and Weapon HUD
AWeaponBase *base = PlyCtrl->NativePlayer->GetActiveWeapon();
if (base != NULL) {
int Ammo = base->GetPrimaryAmmo();
int MaxAmmo = base->GetPrimaryClipSize();
int ReloadAmmo = PlyCtrl->NativePlayer->GetRemainingAmmo(base->GetPrimaryAmmoType());
FString WeaponName = base->GetNiceName();
float AmmoSizeX = size.X / 4.5;
float AmmoSizeY = size.Y / 9;
float AmmoPerc = 0;
if (MaxAmmo > 0) {
AmmoPerc = (Ammo * 100 / MaxAmmo * 100) / 100;
}
URender2D::SetColor(Back);
URender2D::DrawRect((size.X / 4.5 *3.5) - 5, (size.Y / 9 * 8) - 5, size.X / 4.5, size.Y / 9);
URender2D::SetColor(White);
URender2D::DrawText(WeaponName, size.X / 4.5 *3.5, (size.Y / 9 * 8), TEXT_ALIGN_LEFT);
URender2D::SetColor(DarkGrey);
URender2D::DrawRect((size.X / 4.5 *3.5), (size.Y / 9 * 8) - 5 + AmmoSizeY / 2, AmmoSizeX - 10, AmmoSizeY / 3);
URender2D::SetColor(AmmoCol);
URender2D::DrawRect((size.X / 4.5 *3.5), (size.Y / 9 * 8) - 5 + AmmoSizeY / 2, ((AmmoSizeX - 10) / 100) * AmmoPerc, AmmoSizeY / 3);
URender2D::SetColor(White);
URender2D::DrawText(FString::FromInt(Ammo) + FString(" | ") + FString::FromInt(ReloadAmmo), size.X / 4.5 *3.5, (size.Y / 9 * 8) + AmmoSizeY / 2, TEXT_ALIGN_LEFT);
}
}
void AUModHUD::DrawWeaponSwitch()
{
FVector2D size = ScreenSize();
//Weapon switch
for (int i = 0; i < 16; i++) {
AWeaponBase *b = PlyCtrl->NativePlayer->GetWeapons()[i];
if (b != NULL) {
URender2D::SetColor(FColor(0, 0, 0, 200));
URender2D::DrawRect(size.X / 2 - (64 * 8) + i * 64, 10, 64, 64);
URender2D::SetColor(White);
URender2D::SetFontScale(0.2, 0.2);
URender2D::DrawText(b->GetNiceName(), size.X / 2 - (64 * 8) + i * 64, 10, TEXT_ALIGN_LEFT);
}
}
}
void AUModHUD::DrawUnderwaterHUD()
{
}
void AUModHUD::MainHUDRender()
{
const FVector2D Center(Canvas->ClipX * 0.5f, Canvas->ClipY * 0.5f);
const FVector2D CrosshairDrawPosition((Center.X - (16)), (Center.Y - (16)));
URender2D::SetTexture(CrosshairTex);
URender2D::SetColor(FColor::White);
URender2D::DrawRect(CrosshairDrawPosition.X, CrosshairDrawPosition.Y, 32, 32);
URender2D::ResetTexture();
FVector2D size = ScreenSize();
URender2D::SetColor(FColor::Red);
URender2D::SetFontScale(0.3, 0.3);
/*if (PlyCtrl->Player == NULL || PlyCtrl->Player->PlayerState == NULL) {
URender2D::DrawText("THIS CLIENT IS ERRORED", 16, 16, TEXT_ALIGN_LEFT);
} else {
FString txt = PlyCtrl->Player->PlayerState->PlayerName;
URender2D::DrawText("Playing as " + txt, 16, 16, TEXT_ALIGN_LEFT);
}*/
FConnectionStats stats = Game->GetConnectionInfo();
if (stats.ConnectionProblem) {
URender2D::SetColor(FColor(255, 0, 0, 128));
URender2D::DrawRect(0, 256, 256, 128);
URender2D::SetColor(FColor::Black);
URender2D::DrawText("WARNING : Connection problem !", 10, 266, TEXT_ALIGN_LEFT);
URender2D::DrawText("Disconnect in " + FString::SanitizeFloat(stats.SecsBeforeDisconnect), 10, 286, TEXT_ALIGN_LEFT);
}
//Health and Armor Box
//Yeah localPlyCL is sometimes null thanks to buggy engine !!
if (PlyCtrl->NativePlayer != NULL) {
DrawPlayerStats();
DrawWeaponStats();
DrawWeaponSwitch();
}
if (PlyCtrl->IsOnIngameMenu()) {
DrawIngameMenu();
}
}
void AUModHUD::DrawHUD()
{
UMOD_STAT(RENDERHUD);
if (Game == NULL || PlyCtrl == NULL) { return; }
Super::DrawHUD();
URender2D::SetContext(Canvas);
Game->Lua->RunScriptFunctionZeroParam(ETableType::GAMEMODE, 0, "DrawHUD");
URender2D::SetFont(HUDFont);
MainHUDRender();
URender2D::ExitContext();
}
| 32.286713
| 164
| 0.651614
|
StoneLineDevTeam
|
8baf823a8b4b357d2864b416a55be5c97654bc3d
| 3,974
|
cpp
|
C++
|
performance/module_perform.cpp
|
opensource000/cnblogs
|
31eaee01e150072f26ac50d43a740143016588ea
|
[
"Apache-2.0"
] | 3
|
2017-08-30T07:12:28.000Z
|
2017-08-30T07:12:33.000Z
|
performance/module_perform.cpp
|
opensource000/cnblogs
|
31eaee01e150072f26ac50d43a740143016588ea
|
[
"Apache-2.0"
] | null | null | null |
performance/module_perform.cpp
|
opensource000/cnblogs
|
31eaee01e150072f26ac50d43a740143016588ea
|
[
"Apache-2.0"
] | 1
|
2019-04-18T02:37:20.000Z
|
2019-04-18T02:37:20.000Z
|
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/time.h>
#include <string>
#include <vector>
#include <stdint.h>
#define rdtscll_64(val) do {\
unsigned int __a,__d; \
__asm__ __volatile__("rdtsc" : "=a" (__a), "=d" (__d)); \
(val) = (((unsigned long long)__d)<<32) | (__a); \
} while(0);
class CTscStat
{
public:
CTscStat(const std::string& sCallerName)
: m_sCallerName(sCallerName)
{
rdtscll_64(m_start);
rdtscll_64(m_lastcall);
}
~CTscStat()
{
uint64_t end;
rdtscll_64(end);
uint64_t totalConsumeTsc = end - m_start;
printf("TscStat---TOTAL:func=[%s] tsc_cost=[%lu]\n", m_sCallerName.c_str(), totalConsumeTsc);
}
void AddCall(const std::string& sCall)
{
AddCall(sCall, GetTscSub());
}
private:
void AddCall(const std::string& sCallerName, uint64_t consumeTsc)
{
printf("TscStat---SubCall:func=[%s] sub_func=[%s] tsc_cost=[%lu]\n",
m_sCallerName.c_str(), sCallerName.c_str(), consumeTsc);
rdtscll_64(m_lastcall);
}
uint64_t GetTscSub()
{
uint64_t now;
rdtscll_64(now);
return now - m_lastcall;
}
private:
struct SCall
{
std::string sCallerName;
uint64_t consumeTsc;
};
private:
std::string m_sCallerName; // 统计接口
std::vector<SCall> m_vecCall; // 请求列表
uint64_t m_start; // 开始TSC
uint64_t m_lastcall; // 上次TSC
};
#define TSC_START(sCn) CTscStat oTscS(sCn);
#define TSC_APICALL(API) \
do { \
oTscS.AddCall(API); \
} while(0)
class CTimeStat
{
public:
CTimeStat(const std::string& sCallerName)
: m_sCallerName(sCallerName)
{
gettimeofday(&m_start, 0);
gettimeofday(&m_lastcall, 0);
}
~CTimeStat()
{
struct timeval end;
struct timeval subresult;
gettimeofday(&end, 0);
timersub(&end, &m_start, &subresult);
uint32_t dwTotalConsumeTime = subresult.tv_sec * 1000 + subresult.tv_usec / 1000;
printf("TimeStat---TOTAL:func=[%s] time_cost=[%u]\n", m_sCallerName.c_str(), dwTotalConsumeTime);
}
void AddCall(const std::string& sCall)
{
AddCall(sCall, GetTimeSub());
}
private:
void AddCall(const std::string& sCallerName, uint32_t dwConsumeTime)
{
printf("TimeStat---SubCall:func=[%s] sub_func=[%s] time_cost=[%u]\n",
m_sCallerName.c_str(), sCallerName.c_str(), dwConsumeTime);
gettimeofday(&m_lastcall, 0);
}
uint32_t GetTimeSub()
{
struct timeval now;
struct timeval subresult;
gettimeofday(&now, 0);
timersub(&now, &m_lastcall, &subresult);
return subresult.tv_sec * 1000 + subresult.tv_usec / 1000;
}
private:
struct SCall
{
std::string sCallerName;
uint32_t dwConsumeTime;
};
private:
std::string m_sCallerName; // 统计接口
std::vector<SCall> m_vecCall; // 请求列表
struct timeval m_start; // 开始时间
struct timeval m_lastcall; // 上次请求时间
};
#define TS_START(sCn) CTimeStat oTimeS(sCn);
#define TS_APICALL(API) \
do { \
oTimeS.AddCall(API); \
} while(0)
void funcA()
{
usleep(1000); // 1ms
}
void funcB()
{
usleep(100000); // 100ms
}
void funcC()
{
sleep(1); // 1s
}
void TestTsc()
{
TSC_START("TestTsc");
funcA();
TSC_APICALL("funcA");
funcB();
TSC_APICALL("funcB");
funcC();
TSC_APICALL("funcC");
}
void TestTime()
{
TS_START("TestTsc");
funcA();
TS_APICALL("funcA");
funcB();
TS_APICALL("funcB");
funcC();
TS_APICALL("funcC");
}
int main(int argc, char** argv)
{
////////// tsc ///////////
TestTsc();
///////// time ///////////
TestTime();
return 0;
}
| 20.806283
| 105
| 0.571213
|
opensource000
|
8bb2d7c04293c72e5b7569de8ac67feb2b3820b4
| 3,616
|
cc
|
C++
|
src/connector/native/ui_mac.cc
|
morethanyouknowltd/Lockpick
|
bfba2b91aabda88951f3ddf7aa564d040d2bb209
|
[
"MIT"
] | 1
|
2021-11-25T02:11:13.000Z
|
2021-11-25T02:11:13.000Z
|
src/connector/native/ui_mac.cc
|
morethanyouknowltd/Lockpick
|
bfba2b91aabda88951f3ddf7aa564d040d2bb209
|
[
"MIT"
] | 4
|
2021-04-24T11:28:38.000Z
|
2021-05-26T18:03:34.000Z
|
src/connector/native/ui_mac.cc
|
morethanyouknowltd/Lockpick
|
bfba2b91aabda88951f3ddf7aa564d040d2bb209
|
[
"MIT"
] | null | null | null |
#include "ui.h"
#include "string.h"
#include "rect.h"
#include <CoreGraphics/CoreGraphics.h>
ImageDeets::ImageDeets(CGImageRef latestImage, WindowInfo frame) {
this->frame = frame;
this->imageRef = latestImage;
CGDataProviderRef provider = CGImageGetDataProvider(latestImage);
imageData = CGDataProviderCopyData(provider);
bytesPerRow = CGImageGetBytesPerRow(latestImage);
bytesPerPixel = CGImageGetBitsPerPixel(latestImage) / 8;
info = CGImageGetBitmapInfo(latestImage);
width = frame.frame.w;
height = frame.frame.h;
maxInclOffset = getPixelOffset(XYPoint{width - 1, height - 1});
};
ImageDeets::~ImageDeets() {
CFRelease(imageRef);
CFRelease(imageData);
};
MWColor ImageDeets::colorAt(XYPoint point) {
size_t offset = getPixelOffset(point);
if (offset >= maxInclOffset) {
std::cout << "Offset outside range";
return MWColor{0, 0, 0};
}
const UInt8* dataPtr = CFDataGetBytePtr(imageData);
// int alpha = dataPtr[offset + 3],
int red = dataPtr[offset + 2],
green = dataPtr[offset + 1],
blue = dataPtr[offset + 0];
return MWColor{red, green, blue};
};
ImageDeets* BitwigWindow::updateScreenshot() {
auto newFrame = getFrame();
if (newFrame.frame.w == 0 && newFrame.frame.h == 0) {
std::cout << "Couldn't find window, can't update screenshot";
return latestImageDeets;
}
lastBWFrame = newFrame;
if (latestImageDeets != nullptr) {
delete latestImageDeets;
}
// std::cout << "updating screenshot" << std::endl;
auto image = CGWindowListCreateImage(
CGRectNull,
kCGWindowListOptionIncludingWindow,
this->lastBWFrame.windowId,
kCGWindowImageBoundsIgnoreFraming | kCGWindowImageNominalResolution
);
latestImageDeets = new ImageDeets(image, lastBWFrame);
return latestImageDeets;
};
WindowInfo BitwigWindow::getFrame() {
// Go through all on screen windows, find BW, get its frame
CFArrayRef array = CGWindowListCopyWindowInfo(kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements, kCGNullWindowID);
CFIndex count = CFArrayGetCount(array);
for (CFIndex i = 0; i < count; i++) {
CFDictionaryRef dict = (CFDictionaryRef)CFArrayGetValueAtIndex(array, i);
auto str = CFStringToString((CFStringRef)CFDictionaryGetValue(dict, kCGWindowOwnerName));
if (str == "Bitwig Studio") {
CGRect windowRect;
CGRectMakeWithDictionaryRepresentation((CFDictionaryRef)(CFDictionaryGetValue(dict, kCGWindowBounds)), &windowRect);
if (windowRect.size.height < 100) {
// Bitwig opens a separate window for its tooltips, ignore this window
// TODO Revisit better way of only getting the main window
continue;
}
CGWindowID windowId;
CFNumberGetValue((CFNumberRef)CFDictionaryGetValue(dict, kCGWindowNumber), kCGWindowIDCFNumberType, &windowId);
CFRelease(array);
return WindowInfo{
windowId,
MWRect({
(int)windowRect.origin.x,
(int)windowRect.origin.y,
(int)windowRect.size.width,
(int)windowRect.size.height
})
};
}
}
CFRelease(array);
return WindowInfo{
1,
MWRect{0, 0, 0, 0}
};
};
Napi::Value BitwigWindow::UpdateFrame(const Napi::CallbackInfo &info) {
auto env = info.Env();
this->lastBWFrame = getFrame();
return Napi::Value();
}
| 35.45098
| 138
| 0.643252
|
morethanyouknowltd
|
8bb838cd162bee3c52b0c45f6c566e51e8ec49db
| 968
|
cc
|
C++
|
GeeksForGeeks/Easy/SubStringRepetition.cc
|
ChakreshSinghUC/CPPCodes
|
d82a3f467303566afbfcc927b660b0f7bf7c0432
|
[
"MIT"
] | null | null | null |
GeeksForGeeks/Easy/SubStringRepetition.cc
|
ChakreshSinghUC/CPPCodes
|
d82a3f467303566afbfcc927b660b0f7bf7c0432
|
[
"MIT"
] | null | null | null |
GeeksForGeeks/Easy/SubStringRepetition.cc
|
ChakreshSinghUC/CPPCodes
|
d82a3f467303566afbfcc927b660b0f7bf7c0432
|
[
"MIT"
] | null | null | null |
//Check is a string is a concatenation of some of its substring
#include <iostream>
#include <string>
using namespace std;
bool checkSubStr(int len, string s1, int factor)
{
bool r;
string temp;
string s;
string::iterator itr;
int index;
for (index = 0, itr = s1.begin(); index < len; itr++, index++)
{
s = s + *itr;
}
temp = s;
for (index = 0; index < factor - 1; index++)
{
temp = temp + s;
}
s = temp;
if (s == s1)
r = true;
else
r = false;
return r;
}
int main()
{
string s1 = "absabsabs";
// int t;
bool result;
// cin >> t;
// while (t--)
// {
if (!s1.empty())
{
for (int i = 1; i <= s1.length(); i++)
{
if (s1.length() % i == 0)
{
result = checkSubStr(i, s1, s1.length() / i);
cout << result << endl;
}
}
}
// }
return -1;
}
| 17.925926
| 66
| 0.443182
|
ChakreshSinghUC
|
8bbc07b59f50bafbbfc8e9770234bcc1e6cbf895
| 837
|
hpp
|
C++
|
events/gamepad_hat_event.hpp
|
MrTAB/aabGameEngine
|
dc51c6e443bf087ca10e14e6884e4dfa6caef4a8
|
[
"MIT"
] | null | null | null |
events/gamepad_hat_event.hpp
|
MrTAB/aabGameEngine
|
dc51c6e443bf087ca10e14e6884e4dfa6caef4a8
|
[
"MIT"
] | null | null | null |
events/gamepad_hat_event.hpp
|
MrTAB/aabGameEngine
|
dc51c6e443bf087ca10e14e6884e4dfa6caef4a8
|
[
"MIT"
] | null | null | null |
/**
*
* gamepad_hat_event.hpp
*
**/
#if !defined(AAB_EVENTS_GAMEPAD_HAT_EVENT_CLASS)
#define AAB_EVENTS_GAMEPAD_HAT_EVENT_CLASS
#include"event.hpp"
#include"internal_event.hpp"
#include"imports.hpp"
#include"../input/hat_position.hpp"
namespace aab {
namespace events{
class GamepadHatEvent : public Event
{
public:
typedef aab::types::Smart <GamepadHatEvent>::Ptr Ptr;
typedef aab::input::HatPosition HatPosition;
private:
int id;
unsigned char hat;
HatPosition value;
public:
explicit GamepadHatEvent (InternalEvent e);
virtual ~GamepadHatEvent () throw ();
int getGamePadId () const;
int getHatId () const;
HatPosition getHatPosition () const;
static EventType getClassEventType ();
};
} // events
} // aab
#endif // AAB_EVENTS_GAMEPAD_HAT_EVENT_CLASS
| 17.081633
| 55
| 0.701314
|
MrTAB
|
8bc08710c5006b7ff0339538008ae0dac04136dc
| 1,952
|
cpp
|
C++
|
aws-cpp-sdk-devops-guru/source/model/AnomalyStatus.cpp
|
perfectrecall/aws-sdk-cpp
|
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
|
[
"Apache-2.0"
] | 1
|
2022-02-10T08:06:54.000Z
|
2022-02-10T08:06:54.000Z
|
aws-cpp-sdk-devops-guru/source/model/AnomalyStatus.cpp
|
perfectrecall/aws-sdk-cpp
|
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
|
[
"Apache-2.0"
] | 1
|
2021-10-14T16:57:00.000Z
|
2021-10-18T10:47:24.000Z
|
aws-cpp-sdk-devops-guru/source/model/AnomalyStatus.cpp
|
ravindra-wagh/aws-sdk-cpp
|
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
|
[
"Apache-2.0"
] | 1
|
2021-11-09T11:58:03.000Z
|
2021-11-09T11:58:03.000Z
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/devops-guru/model/AnomalyStatus.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>
using namespace Aws::Utils;
namespace Aws
{
namespace DevOpsGuru
{
namespace Model
{
namespace AnomalyStatusMapper
{
static const int ONGOING_HASH = HashingUtils::HashString("ONGOING");
static const int CLOSED_HASH = HashingUtils::HashString("CLOSED");
AnomalyStatus GetAnomalyStatusForName(const Aws::String& name)
{
int hashCode = HashingUtils::HashString(name.c_str());
if (hashCode == ONGOING_HASH)
{
return AnomalyStatus::ONGOING;
}
else if (hashCode == CLOSED_HASH)
{
return AnomalyStatus::CLOSED;
}
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
overflowContainer->StoreOverflow(hashCode, name);
return static_cast<AnomalyStatus>(hashCode);
}
return AnomalyStatus::NOT_SET;
}
Aws::String GetNameForAnomalyStatus(AnomalyStatus enumValue)
{
switch(enumValue)
{
case AnomalyStatus::ONGOING:
return "ONGOING";
case AnomalyStatus::CLOSED:
return "CLOSED";
default:
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
}
return {};
}
}
} // namespace AnomalyStatusMapper
} // namespace Model
} // namespace DevOpsGuru
} // namespace Aws
| 27.492958
| 92
| 0.610143
|
perfectrecall
|
8bc41b3f3f57ff6f530f5771537685ea2706a38e
| 3,905
|
hpp
|
C++
|
include/armnnTestUtils/MockBackend.hpp
|
Srivathsav-max/armnn-clone
|
af2daa6526623c91ee97f7141be4d1b07de92a48
|
[
"MIT"
] | 1
|
2022-03-31T18:21:59.000Z
|
2022-03-31T18:21:59.000Z
|
include/armnnTestUtils/MockBackend.hpp
|
Elm8116/armnn
|
e571cde8411803aec545b1070ed677e481f46f3f
|
[
"MIT"
] | null | null | null |
include/armnnTestUtils/MockBackend.hpp
|
Elm8116/armnn
|
e571cde8411803aec545b1070ed677e481f46f3f
|
[
"MIT"
] | null | null | null |
//
// Copyright © 2022 Arm Ltd and Contributors. All rights reserved.
// SPDX-License-Identifier: MIT
//
#pragma once
#include <armnn/backends/IBackendInternal.hpp>
#include <armnn/backends/MemCopyWorkload.hpp>
#include <armnnTestUtils/MockTensorHandle.hpp>
namespace armnn
{
// A bare bones Mock backend to enable unit testing of simple tensor manipulation features.
class MockBackend : public IBackendInternal
{
public:
MockBackend() = default;
~MockBackend() = default;
static const BackendId& GetIdStatic();
const BackendId& GetId() const override
{
return GetIdStatic();
}
IBackendInternal::IWorkloadFactoryPtr
CreateWorkloadFactory(const IBackendInternal::IMemoryManagerSharedPtr& memoryManager = nullptr) const override
{
IgnoreUnused(memoryManager);
return nullptr;
}
IBackendInternal::ILayerSupportSharedPtr GetLayerSupport() const override
{
return nullptr;
};
};
class MockWorkloadFactory : public IWorkloadFactory
{
public:
explicit MockWorkloadFactory(const std::shared_ptr<MockMemoryManager>& memoryManager);
MockWorkloadFactory();
~MockWorkloadFactory()
{}
const BackendId& GetBackendId() const override;
bool SupportsSubTensors() const override
{
return false;
}
ARMNN_DEPRECATED_MSG("Use ITensorHandleFactory::CreateSubTensorHandle instead")
std::unique_ptr<ITensorHandle> CreateSubTensorHandle(ITensorHandle&,
TensorShape const&,
unsigned int const*) const override
{
return nullptr;
}
ARMNN_DEPRECATED_MSG("Use ITensorHandleFactory::CreateTensorHandle instead")
std::unique_ptr<ITensorHandle> CreateTensorHandle(const TensorInfo& tensorInfo,
const bool IsMemoryManaged = true) const override
{
IgnoreUnused(IsMemoryManaged);
return std::make_unique<MockTensorHandle>(tensorInfo, m_MemoryManager);
};
ARMNN_DEPRECATED_MSG("Use ITensorHandleFactory::CreateTensorHandle instead")
std::unique_ptr<ITensorHandle> CreateTensorHandle(const TensorInfo& tensorInfo,
DataLayout dataLayout,
const bool IsMemoryManaged = true) const override
{
IgnoreUnused(dataLayout, IsMemoryManaged);
return std::make_unique<MockTensorHandle>(tensorInfo, static_cast<unsigned int>(MemorySource::Malloc));
};
ARMNN_DEPRECATED_MSG_REMOVAL_DATE(
"Use ABI stable "
"CreateWorkload(LayerType, const QueueDescriptor&, const WorkloadInfo& info) instead.",
"22.11")
std::unique_ptr<IWorkload> CreateInput(const InputQueueDescriptor& descriptor,
const WorkloadInfo& info) const override
{
if (info.m_InputTensorInfos.empty())
{
throw InvalidArgumentException("MockWorkloadFactory::CreateInput: Input cannot be zero length");
}
if (info.m_OutputTensorInfos.empty())
{
throw InvalidArgumentException("MockWorkloadFactory::CreateInput: Output cannot be zero length");
}
if (info.m_InputTensorInfos[0].GetNumBytes() != info.m_OutputTensorInfos[0].GetNumBytes())
{
throw InvalidArgumentException(
"MockWorkloadFactory::CreateInput: data input and output differ in byte count.");
}
return std::make_unique<CopyMemGenericWorkload>(descriptor, info);
};
std::unique_ptr<IWorkload>
CreateWorkload(LayerType type, const QueueDescriptor& descriptor, const WorkloadInfo& info) const override;
private:
mutable std::shared_ptr<MockMemoryManager> m_MemoryManager;
};
} // namespace armnn
| 33.663793
| 118
| 0.660435
|
Srivathsav-max
|
8bd1556b376d79c61e0d75c7397741fb7a5d7c60
| 657
|
cpp
|
C++
|
Engine_Source/Source/Insight/Core/Log.cpp
|
GCourtney27/DirectX11RenderingEngine
|
ebbe470b697c6e5ab98502c0be4163500d91641a
|
[
"Apache-2.0"
] | 2
|
2021-01-29T08:03:01.000Z
|
2021-04-10T19:18:54.000Z
|
Engine_Source/Source/Insight/Core/Log.cpp
|
GCourtney27/DirectX11RenderingEngine
|
ebbe470b697c6e5ab98502c0be4163500d91641a
|
[
"Apache-2.0"
] | 3
|
2020-06-04T23:37:07.000Z
|
2020-06-04T23:39:04.000Z
|
Engine_Source/Source/Insight/Core/Log.cpp
|
GCourtney27/DirectX11RenderingEngine
|
ebbe470b697c6e5ab98502c0be4163500d91641a
|
[
"Apache-2.0"
] | 1
|
2020-09-07T07:20:11.000Z
|
2020-09-07T07:20:11.000Z
|
#include <Engine_pch.h>
#include "Log.h"
#include "spdlog/sinks/stdout_color_sinks.h"
namespace Insight {
namespace Debug {
std::shared_ptr<spdlog::logger> Logger::s_CoreLogger;
std::shared_ptr<spdlog::logger> Logger::s_ClientLogger;
#if defined IE_DEBUG && defined (IE_PLATFORM_BUILD_WIN32)
ConsoleWindow Logger::m_ConsoleWindow;
#endif
bool Logger::Init()
{
spdlog::set_pattern("%^[%T] %n: %v%$");
s_CoreLogger = spdlog::stdout_color_mt("Insight");
s_CoreLogger->set_level(spdlog::level::trace);
s_ClientLogger = spdlog::stdout_color_mt("App");
s_ClientLogger->set_level(spdlog::level::trace);
return true;
}
}
}
| 20.53125
| 57
| 0.712329
|
GCourtney27
|
8bd3c0d4d3ab847a6182ba73a369289a949364e3
| 22,000
|
cpp
|
C++
|
src/api/client/Blockchain.cpp
|
nopdotcom/opentxs
|
140428ba8f1bd4c09654ebf0a1c1725f396efa8b
|
[
"MIT"
] | null | null | null |
src/api/client/Blockchain.cpp
|
nopdotcom/opentxs
|
140428ba8f1bd4c09654ebf0a1c1725f396efa8b
|
[
"MIT"
] | null | null | null |
src/api/client/Blockchain.cpp
|
nopdotcom/opentxs
|
140428ba8f1bd4c09654ebf0a1c1725f396efa8b
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2018 The Open-Transactions developers
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "stdafx.hpp"
#include "Internal.hpp"
#if OT_CRYPTO_SUPPORTED_KEY_HD
#include "opentxs/api/client/Activity.hpp"
#include "opentxs/api/client/Blockchain.hpp"
#include "opentxs/api/storage/Storage.hpp"
#include "opentxs/api/crypto/Crypto.hpp"
#include "opentxs/api/crypto/Encode.hpp"
#include "opentxs/api/crypto/Hash.hpp"
#include "opentxs/api/Core.hpp"
#include "opentxs/api/HDSeed.hpp"
#include "opentxs/api/Wallet.hpp"
#include "opentxs/core/Data.hpp"
#include "opentxs/core/Identifier.hpp"
#include "opentxs/core/Log.hpp"
#include "opentxs/core/String.hpp"
#include "opentxs/crypto/key/Asymmetric.hpp"
#if OT_CRYPTO_SUPPORTED_KEY_SECP256K1
#include "opentxs/crypto/key/Secp256k1.hpp"
#endif
#include "opentxs/crypto/Bip32.hpp"
#include <map>
#include <mutex>
#include <set>
#include "Blockchain.hpp"
#define LOCK_ACCOUNT() \
Lock mapLock(lock_); \
auto& accountMutex = account_lock_[accountID]; \
mapLock.unlock(); \
Lock accountLock(accountMutex);
#define LOCK_NYM() \
Lock mapLock(lock_); \
auto& nymMutex = nym_lock_[nymID]; \
mapLock.unlock(); \
Lock nymLock(nymMutex);
#define MAX_INDEX 2147483648
#define BLOCKCHAIN_VERSION 1
#define ACCOUNT_VERSION 1
#define PATH_VERSION 1
#define COMPRESSED_PUBKEY_SIZE 33
#define BITCOIN_PUBKEY_HASH 0x0
#define BITCOIN_TESTNET_HASH 0x6f
#define LITECOIN_PUBKEY_HASH 0x30
#define DOGECOIN_PUBKEY_HASH 0x1e
#define DASH_PUBKEY_HASH 0x4c
#define OT_METHOD "opentxs::Blockchain::"
namespace opentxs
{
api::client::Blockchain* Factory::Blockchain(
const api::Core& api,
const api::client::Activity& activity)
{
return new api::client::implementation::Blockchain(api, activity);
}
} // namespace opentxs
namespace opentxs::api::client::implementation
{
Blockchain::Blockchain(
const api::Core& api,
const api::client::Activity& activity)
: api_(api)
, activity_(activity)
, lock_()
, nym_lock_()
, account_lock_()
{
// WARNING: do not access api_.Wallet() during construction
}
std::shared_ptr<proto::Bip44Account> Blockchain::Account(
const Identifier& nymID,
const Identifier& accountID) const
{
LOCK_ACCOUNT()
const std::string sNymID = nymID.str();
const std::string sAccountID = accountID.str();
auto account = load_account(accountLock, sNymID, sAccountID);
if (false == bool(account)) {
otErr << OT_METHOD << __FUNCTION__ << ": Account does not exist."
<< std::endl;
}
return account;
}
std::set<OTIdentifier> Blockchain::AccountList(
const Identifier& nymID,
const proto::ContactItemType type) const
{
std::set<OTIdentifier> output;
auto list = api_.Storage().BlockchainAccountList(nymID.str(), type);
for (const auto& accountID : list) {
// output.emplace(String(accountID.c_str()));
output.emplace(Identifier::Factory(accountID));
}
return output;
}
proto::Bip44Address& Blockchain::add_address(
const std::uint32_t index,
proto::Bip44Account& account,
const BIP44Chain chain) const
{
OT_ASSERT(MAX_INDEX >= index);
account.set_revision(account.revision() + 1);
if (chain) {
account.set_internalindex(index + 1);
return *account.add_internaladdress();
} else {
account.set_externalindex(index + 1);
return *account.add_externaladdress();
}
}
std::uint8_t Blockchain::address_prefix(const proto::ContactItemType type) const
{
switch (type) {
case proto::CITEMTYPE_BCH:
case proto::CITEMTYPE_BTC: {
return BITCOIN_PUBKEY_HASH;
}
case proto::CITEMTYPE_LTC: {
return LITECOIN_PUBKEY_HASH;
}
case proto::CITEMTYPE_DOGE: {
return DOGECOIN_PUBKEY_HASH;
}
case proto::CITEMTYPE_DASH: {
return DASH_PUBKEY_HASH;
}
case proto::CITEMTYPE_TNBCH:
case proto::CITEMTYPE_TNBTC:
case proto::CITEMTYPE_TNXRP:
case proto::CITEMTYPE_TNLTC:
case proto::CITEMTYPE_TNXEM:
case proto::CITEMTYPE_TNDASH:
case proto::CITEMTYPE_TNMAID:
case proto::CITEMTYPE_TNLSK:
case proto::CITEMTYPE_TNDOGE:
case proto::CITEMTYPE_TNXMR:
case proto::CITEMTYPE_TNWAVES:
case proto::CITEMTYPE_TNNXT:
case proto::CITEMTYPE_TNSC:
case proto::CITEMTYPE_TNSTEEM: {
return BITCOIN_TESTNET_HASH;
}
default: {
OT_FAIL;
}
}
return 0x0;
}
std::unique_ptr<proto::Bip44Address> Blockchain::AllocateAddress(
const Identifier& nymID,
const Identifier& accountID,
const std::string& label,
const BIP44Chain chain) const
{
LOCK_ACCOUNT()
const std::string sNymID = nymID.str();
const std::string sAccountID = accountID.str();
std::unique_ptr<proto::Bip44Address> output{nullptr};
auto account = load_account(accountLock, sNymID, sAccountID);
if (false == bool(account)) {
otErr << OT_METHOD << __FUNCTION__ << ": Account does not exist."
<< std::endl;
return output;
}
const auto& type = account->type();
const auto index =
chain ? account->internalindex() : account->externalindex();
if (MAX_INDEX == index) {
otErr << OT_METHOD << __FUNCTION__ << ": Account is full." << std::endl;
return output;
}
auto& newAddress = add_address(index, *account, chain);
newAddress.set_version(BLOCKCHAIN_VERSION);
newAddress.set_index(index);
newAddress.set_address(calculate_address(*account, chain, index));
OT_ASSERT(false == newAddress.address().empty());
otErr << OT_METHOD << __FUNCTION__ << ": Address " << newAddress.address()
<< " allocated." << std::endl;
newAddress.set_label(label);
const auto saved = api_.Storage().Store(sNymID, type, *account);
if (false == saved) {
otErr << OT_METHOD << __FUNCTION__ << ": Failed to save account."
<< std::endl;
return output;
}
output.reset(new proto::Bip44Address(newAddress));
return output;
}
bool Blockchain::AssignAddress(
const Identifier& nymID,
const Identifier& accountID,
const std::uint32_t index,
const Identifier& contactID,
const BIP44Chain chain) const
{
LOCK_ACCOUNT()
const std::string sNymID = nymID.str();
const std::string sAccountID = accountID.str();
const std::string sContactID = contactID.str();
auto account = load_account(accountLock, sNymID, sAccountID);
if (false == bool(account)) {
otErr << OT_METHOD << __FUNCTION__ << ": Account does not exist."
<< std::endl;
return false;
}
const auto& type = account->type();
const auto allocatedIndex =
chain ? account->internalindex() : account->externalindex();
if (index > allocatedIndex) {
otErr << OT_METHOD << __FUNCTION__
<< ": Address has not been allocated." << std::endl;
return false;
}
auto& address = find_address(index, chain, *account);
const auto& existing = address.contact();
if (false == existing.empty()) {
move_transactions(nymID, address, existing, sContactID);
}
address.set_contact(sContactID);
account->set_revision(account->revision() + 1);
// check: does the activity thread exist between nym and contact?
bool threadExists = false;
const auto threadList = api_.Storage().ThreadList(sNymID, false);
for (const auto it : threadList) {
const auto& id = it.first;
if (id == sContactID) { threadExists = true; }
}
if (threadExists) {
// check: does every incoming transaction exist as an activity
std::shared_ptr<proto::StorageThread> thread =
activity_.Thread(nymID, contactID);
OT_ASSERT(thread);
for (const std::string& txID : address.incoming()) {
bool exists = false;
for (const auto activity : thread->item())
if (txID.compare(activity.id()) == 0) exists = true;
// add: transaction to the thread
if (!exists) {
activity_.AddBlockchainTransaction(
nymID,
contactID,
StorageBox::INCOMINGBLOCKCHAIN,
*Transaction(txID));
}
}
} else {
// create the thread and add the transactions
for (const auto txID : address.incoming()) {
activity_.AddBlockchainTransaction(
nymID,
contactID,
StorageBox::INCOMINGBLOCKCHAIN,
*Transaction(txID));
}
}
return api_.Storage().Store(sNymID, type, *account);
}
Bip44Type Blockchain::bip44_type(const proto::ContactItemType type) const
{
switch (type) {
case proto::CITEMTYPE_BTC: {
return Bip44Type::BITCOIN;
}
case proto::CITEMTYPE_LTC: {
return Bip44Type::LITECOIN;
}
case proto::CITEMTYPE_DOGE: {
return Bip44Type::DOGECOIN;
}
case proto::CITEMTYPE_DASH: {
return Bip44Type::DASH;
}
case proto::CITEMTYPE_BCH: {
return Bip44Type::BITCOINCASH;
}
case proto::CITEMTYPE_TNBCH:
case proto::CITEMTYPE_TNBTC:
case proto::CITEMTYPE_TNXRP:
case proto::CITEMTYPE_TNLTC:
case proto::CITEMTYPE_TNXEM:
case proto::CITEMTYPE_TNDASH:
case proto::CITEMTYPE_TNMAID:
case proto::CITEMTYPE_TNLSK:
case proto::CITEMTYPE_TNDOGE:
case proto::CITEMTYPE_TNXMR:
case proto::CITEMTYPE_TNWAVES:
case proto::CITEMTYPE_TNNXT:
case proto::CITEMTYPE_TNSC:
case proto::CITEMTYPE_TNSTEEM: {
return Bip44Type::TESTNET;
}
default: {
OT_FAIL;
}
}
return {};
}
std::string Blockchain::calculate_address(
const proto::Bip44Account& account,
const BIP44Chain chain,
const std::uint32_t index) const
{
const auto& path = account.path();
auto fingerprint = path.root();
auto serialized = api_.Seeds().AccountChildKey(path, chain, index);
if (false == bool(serialized)) {
otErr << OT_METHOD << __FUNCTION__ << ": Unable to derive key."
<< std::endl;
return {};
}
const auto key{opentxs::crypto::key::Asymmetric::Factory(*serialized)};
const opentxs::crypto::key::Secp256k1* ecKey{
dynamic_cast<const opentxs::crypto::key::Secp256k1*>(&key.get())};
if (false == bool(key.get())) {
otErr << OT_METHOD << __FUNCTION__ << ": Unable to instantiate key."
<< std::endl;
return {};
}
if (nullptr == ecKey) {
otErr << OT_METHOD << __FUNCTION__ << ": Incorrect key type."
<< std::endl;
return {};
}
auto pubkey = Data::Factory();
if (false == ecKey->GetPublicKey(pubkey)) {
otErr << OT_METHOD << __FUNCTION__ << ": Unable to extract public key."
<< std::endl;
return {};
}
if (COMPRESSED_PUBKEY_SIZE != pubkey->size()) {
otErr << OT_METHOD << __FUNCTION__ << ": Incorrect pubkey size ("
<< pubkey->size() << ")." << std::endl;
return {};
}
auto sha256 = Data::Factory();
auto ripemd160 = Data::Factory();
auto pubkeyHash = Data::Factory();
if (!api_.Crypto().Hash().Digest(proto::HASHTYPE_SHA256, pubkey, sha256)) {
otErr << OT_METHOD << __FUNCTION__ << ": Unable to calculate sha256."
<< std::endl;
return {};
}
if (!api_.Crypto().Hash().Digest(
proto::HASHTYPE_RIMEMD160, sha256, pubkeyHash)) {
otErr << OT_METHOD << __FUNCTION__ << ": Unable to calculate rimemd160."
<< std::endl;
return {};
}
const auto prefix = address_prefix(account.type());
auto preimage = Data::Factory(&prefix, sizeof(prefix));
OT_ASSERT(1 == preimage->size());
preimage += pubkeyHash;
OT_ASSERT(21 == preimage->size());
return api_.Crypto().Encode().IdentifierEncode(preimage);
}
proto::Bip44Address& Blockchain::find_address(
const std::uint32_t index,
const BIP44Chain chain,
proto::Bip44Account& account) const
{
// TODO: determine if we can prove the addresses were inserted in index
// order. Then we don't need to do a linear search here.
// Perhaps opentxs-proto should fail validation for improperly sorted
// Bip44Accounts
if (chain) {
for (auto& address : *account.mutable_internaladdress()) {
if (address.index() == index) { return address; }
}
} else {
for (auto& address : *account.mutable_externaladdress()) {
if (address.index() == index) { return address; }
}
}
OT_FAIL;
}
void Blockchain::init_path(
const std::string& root,
const proto::ContactItemType chain,
const std::uint32_t account,
const BlockchainAccountType standard,
proto::HDPath& path) const
{
path.set_version(PATH_VERSION);
path.set_root(root);
switch (standard) {
case BlockchainAccountType::BIP32: {
path.add_child(
account | static_cast<std::uint32_t>(Bip32Child::HARDENED));
} break;
case BlockchainAccountType::BIP44: {
path.add_child(
static_cast<std::uint32_t>(Bip43Purpose::HDWALLET) |
static_cast<std::uint32_t>(Bip32Child::HARDENED));
path.add_child(
static_cast<std::uint32_t>(bip44_type(chain)) |
static_cast<std::uint32_t>(Bip32Child::HARDENED));
path.add_child(account);
} break;
default: {
OT_FAIL;
}
}
}
std::shared_ptr<proto::Bip44Account> Blockchain::load_account(
const Lock&,
const std::string& nymID,
const std::string& accountID) const
{
std::shared_ptr<proto::Bip44Account> account{nullptr};
api_.Storage().Load(nymID, accountID, account);
return account;
}
std::unique_ptr<proto::Bip44Address> Blockchain::LoadAddress(
const Identifier& nymID,
const Identifier& accountID,
const std::uint32_t index,
const BIP44Chain chain) const
{
LOCK_ACCOUNT()
std::unique_ptr<proto::Bip44Address> output{};
const std::string sNymID = nymID.str();
const std::string sAccountID = accountID.str();
auto account = load_account(accountLock, sNymID, sAccountID);
if (false == bool(account)) {
otErr << OT_METHOD << __FUNCTION__ << ": Account does not exist."
<< std::endl;
return output;
}
const auto allocatedIndex =
chain ? account->internalindex() : account->externalindex();
if (index > allocatedIndex) {
otErr << OT_METHOD << __FUNCTION__
<< ": Address has not been allocated." << std::endl;
return output;
}
auto& address = find_address(index, chain, *account);
output.reset(new proto::Bip44Address(address));
return output;
}
bool Blockchain::move_transactions(
const Identifier& nymID,
const proto::Bip44Address& address,
const std::string& fromContact,
const std::string& toContact) const
{
bool output{true};
for (const auto& txid : address.incoming()) {
output &= activity_.MoveIncomingBlockchainTransaction(
nymID,
Identifier::Factory(fromContact),
Identifier::Factory(toContact),
txid);
}
return output;
}
OTIdentifier Blockchain::NewAccount(
const Identifier& nymID,
const BlockchainAccountType standard,
const proto::ContactItemType type) const
{
LOCK_NYM()
const std::string sNymID = nymID.str();
auto existing = api_.Storage().BlockchainAccountList(sNymID, type);
if (0 < existing.size()) {
otErr << OT_METHOD << __FUNCTION__ << ": Account already exists."
<< std::endl;
return Identifier::Factory(*existing.begin());
}
auto nym = api_.Wallet().Nym(nymID);
if (false == bool(nym)) {
otErr << OT_METHOD << __FUNCTION__ << ": Nym does not exist."
<< std::endl;
return Identifier::Factory();
}
proto::HDPath nymPath{};
if (false == nym->Path(nymPath)) {
otErr << OT_METHOD << __FUNCTION__ << ": No nym path." << std::endl;
return Identifier::Factory();
}
if (0 == nymPath.root().size()) {
otErr << OT_METHOD << __FUNCTION__ << ": Missing root." << std::endl;
return Identifier::Factory();
}
if (2 > nymPath.child().size()) {
otErr << OT_METHOD << __FUNCTION__ << ": Invalid path." << std::endl;
return Identifier::Factory();
}
proto::HDPath accountPath{};
init_path(
nymPath.root(),
type,
nymPath.child(1) | static_cast<std::uint32_t>(Bip32Child::HARDENED),
standard,
accountPath);
const auto accountID = Identifier::Factory(type, accountPath);
Lock accountLock(account_lock_[accountID]);
proto::Bip44Account account{};
account.set_version(ACCOUNT_VERSION);
account.set_id(accountID->str());
account.set_type(type);
account.set_revision(0);
*account.mutable_path() = accountPath;
account.set_internalindex(0);
account.set_externalindex(0);
account.clear_internaladdress();
account.clear_externaladdress();
const bool saved = api_.Storage().Store(sNymID, type, account);
if (saved) { return accountID; }
otErr << OT_METHOD << __FUNCTION__ << ": Failed to save account."
<< std::endl;
return Identifier::Factory();
}
bool Blockchain::StoreIncoming(
const Identifier& nymID,
const Identifier& accountID,
const std::uint32_t index,
const BIP44Chain chain,
const proto::BlockchainTransaction& transaction) const
{
LOCK_ACCOUNT()
const std::string sNymID = nymID.str();
const std::string sAccountID = accountID.str();
auto account = load_account(accountLock, sNymID, sAccountID);
if (false == bool(account)) {
otErr << OT_METHOD << __FUNCTION__ << ": Account does not exist."
<< std::endl;
return false;
}
const auto allocatedIndex =
chain ? account->internalindex() : account->externalindex();
if (index > allocatedIndex) {
otErr << OT_METHOD << __FUNCTION__
<< ": Address has not been allocated." << std::endl;
return false;
}
auto& address = find_address(index, chain, *account);
bool exists = false;
for (const auto& txid : address.incoming()) {
if (txid == transaction.txid()) {
exists = true;
break;
}
}
if (false == exists) { address.add_incoming(transaction.txid()); }
auto saved = api_.Storage().Store(sNymID, account->type(), *account);
if (false == saved) {
otErr << OT_METHOD << __FUNCTION__ << ": Failed to save account."
<< std::endl;
return false;
}
saved = api_.Storage().Store(transaction);
if (false == saved) {
otErr << OT_METHOD << __FUNCTION__ << ": Failed to save transaction."
<< std::endl;
return false;
}
if (address.contact().empty()) { return true; }
const auto contactID = Identifier::Factory(address.contact());
return activity_.AddBlockchainTransaction(
nymID, contactID, StorageBox::INCOMINGBLOCKCHAIN, transaction);
}
bool Blockchain::StoreOutgoing(
const Identifier& senderNymID,
const Identifier& accountID,
const Identifier& recipientContactID,
const proto::BlockchainTransaction& transaction) const
{
LOCK_ACCOUNT()
const std::string sNymID = senderNymID.str();
const std::string sAccountID = accountID.str();
auto account = load_account(accountLock, sNymID, sAccountID);
if (false == bool(account)) {
otErr << OT_METHOD << __FUNCTION__ << ": Account does not exist."
<< std::endl;
return false;
}
const auto& txid = transaction.txid();
account->add_outgoing(txid);
auto saved = api_.Storage().Store(sNymID, account->type(), *account);
if (false == saved) {
otErr << OT_METHOD << __FUNCTION__ << ": Failed to save account."
<< std::endl;
return false;
}
saved = api_.Storage().Store(transaction);
if (false == saved) {
otErr << OT_METHOD << __FUNCTION__ << ": Failed to save transaction."
<< std::endl;
return false;
}
if (recipientContactID.empty()) { return true; }
return activity_.AddBlockchainTransaction(
senderNymID,
recipientContactID,
StorageBox::OUTGOINGBLOCKCHAIN,
transaction);
}
std::shared_ptr<proto::BlockchainTransaction> Blockchain::Transaction(
const std::string& txid) const
{
std::shared_ptr<proto::BlockchainTransaction> output;
if (false == api_.Storage().Load(txid, output, false)) {
otErr << OT_METHOD << __FUNCTION__ << ": Failed to load transaction."
<< std::endl;
}
return output;
}
} // namespace opentxs::api::client::implementation
#endif // OT_CRYPTO_SUPPORTED_KEY_HD
| 28.608583
| 80
| 0.610227
|
nopdotcom
|
8bd675a9aaf2799e379644e5f34f65e05c62abe8
| 405
|
cpp
|
C++
|
URI/2867-digits.cpp
|
SusmoySenGupta/online-judge-solutions
|
8735a1bc71a05dc46255664c3ec6f47f042bfa6c
|
[
"MIT"
] | null | null | null |
URI/2867-digits.cpp
|
SusmoySenGupta/online-judge-solutions
|
8735a1bc71a05dc46255664c3ec6f47f042bfa6c
|
[
"MIT"
] | null | null | null |
URI/2867-digits.cpp
|
SusmoySenGupta/online-judge-solutions
|
8735a1bc71a05dc46255664c3ec6f47f042bfa6c
|
[
"MIT"
] | null | null | null |
/*
problem no: 2867
problem name: Digits
problem link: https://www.urionlinejudge.com.br/judge/en/problems/view/2867
author: Susmoy Sen Gupta
Status: __Solved__
Solved at: 6/22/21, 6:39:09 PM
*/
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int t, x, y;
cin >> t;
while(t--)
{
cin >> x >> y;
cout << (int)( y * log10(x) ) + 1 << endl;
}
return 0;
}
| 13.5
| 76
| 0.604938
|
SusmoySenGupta
|
8bd7a66b2aa3b8c8842762561616bdcc1f11a644
| 886
|
cpp
|
C++
|
examples/text/ascii-table.hybrid.cpp
|
alf-p-steinbach/cppx-core-language
|
930351fe0df65e231e8e91998f1c94d345938107
|
[
"MIT"
] | 3
|
2020-05-24T16:29:42.000Z
|
2021-09-10T13:33:15.000Z
|
examples/text/ascii-table.hybrid.cpp
|
alf-p-steinbach/cppx-core-language
|
930351fe0df65e231e8e91998f1c94d345938107
|
[
"MIT"
] | null | null | null |
examples/text/ascii-table.hybrid.cpp
|
alf-p-steinbach/cppx-core-language
|
930351fe0df65e231e8e91998f1c94d345938107
|
[
"MIT"
] | null | null | null |
#include <cppx-core-language/ascii/all.hpp>
#include <iomanip> // std::setw
#include <iostream>
auto main()
-> int
{
using std::cout, std::endl, std::left, std::setw;
using cppx::hex_digit;
namespace ascii = cppx::ascii;
const auto field = setw( 4 );
// Column headers.
cout << field << "";
for( int i = 0; i < 16; ++i ) { cout << field << hex_digit( i ); }
cout << endl;
cout << endl; // Spacer line to make the header row stand out as such.
// Main table with a row header column to the left.
for( int y = 0; y < 8; ++y ) {
cout << field << hex_digit( y );
for( int x = 0; x < 16; ++x ) {
const int code = 16*y + x;
const auto ch = char( ascii::is_noncontrol( code )? code: ascii::del );
cout << field << ch;
}
cout << endl;
}
}
| 28.580645
| 88
| 0.506772
|
alf-p-steinbach
|
8bd7b64d646c0c836d6951b653007b1f33e31674
| 1,235
|
cc
|
C++
|
src/client/human/human.cc
|
TheBenPerson/Game
|
824b2240e95529b735b4d8055a541c77102bb5dc
|
[
"MIT"
] | null | null | null |
src/client/human/human.cc
|
TheBenPerson/Game
|
824b2240e95529b735b4d8055a541c77102bb5dc
|
[
"MIT"
] | null | null | null |
src/client/human/human.cc
|
TheBenPerson/Game
|
824b2240e95529b735b4d8055a541c77102bb5dc
|
[
"MIT"
] | null | null | null |
#include <math.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "gfx.hh"
#include "human.hh"
#include "world.hh"
GFX::texture tex;
static void create(uint8_t *data);
extern "C" {
bool init() {
Entity::regEnt("human", &create);
tex = GFX::loadTexture("villager_f.png");
return true;
}
void cleanup() {
// todo: unreg ent?
GFX::freeTexture(&tex);
}
}
Human::Human(uint8_t *data): Entity(data) {
// todo: unsafe?
name = strdup((char*) data + SIZE_TENTITY);
}
Human::~Human() {
free(name);
}
void Human::draw() {
Entity::draw();
Point pvel = vel;
pvel.rot(World::rot);
direction dir = UP;
if (vel) {
if (fabsf(pvel.x) > fabsf(pvel.y)) {
if (pvel.x < 0) dir = LEFT;
else dir = RIGHT;
} else {
if (pvel.y < 0) dir = DOWN;
else dir = UP;
}
} else dir = lastDir;
Point tdim = {3, 4};
Point frame;
if (vel) frame.x = GFX::frame / 10;
else frame.x = 1;
frame.y = dir;
GFX::drawSprite(tex, &pos, &dim, -World::rot, &tdim, &frame);
Point text = {0, dim.y / 2};
text.y += .2f;
text.rot(-World::rot);
text += pos;
GFX::drawText(name, &text, .4f, true, -World::rot);
lastDir = dir;
}
void create(uint8_t *data) {
new Human(data);
}
| 12.474747
| 62
| 0.584615
|
TheBenPerson
|
8bd7c14e4aad14ff4b3d9fb4002978b6347b0b02
| 87
|
cpp
|
C++
|
VulkanEngine/code/cystring.cpp
|
schecko/VulkanEngine
|
88bc893311c18db81beca66a15f51fce52d064f1
|
[
"MIT"
] | null | null | null |
VulkanEngine/code/cystring.cpp
|
schecko/VulkanEngine
|
88bc893311c18db81beca66a15f51fce52d064f1
|
[
"MIT"
] | null | null | null |
VulkanEngine/code/cystring.cpp
|
schecko/VulkanEngine
|
88bc893311c18db81beca66a15f51fce52d064f1
|
[
"MIT"
] | null | null | null |
#include "cystring.h"
namespace Cy
{
String operator+(String s1, String s2)
{
}
}
| 8.7
| 39
| 0.655172
|
schecko
|
8bd7f6cf7b64e57cf2e1328d6aa92fe575294744
| 847
|
cpp
|
C++
|
sensor/temperature.cpp
|
yan9a/rpi
|
eef334c8b61b5e32e7cf57e38f47236b8f483bfb
|
[
"MIT"
] | 2
|
2019-07-02T06:27:25.000Z
|
2022-02-24T16:50:42.000Z
|
sensor/temperature.cpp
|
yan9a/rpi
|
eef334c8b61b5e32e7cf57e38f47236b8f483bfb
|
[
"MIT"
] | null | null | null |
sensor/temperature.cpp
|
yan9a/rpi
|
eef334c8b61b5e32e7cf57e38f47236b8f483bfb
|
[
"MIT"
] | 1
|
2021-12-25T11:52:03.000Z
|
2021-12-25T11:52:03.000Z
|
#include <stdio.h>
#include <unistd.h>
#include "ce_spi.h"
using namespace std;
int main()
{
CE_SPI tsensor;
tsensor.Begin();
int n;
float v, t;
for(int i=0;i<10;i++){
tsensor.tx[0]=0x01;//Send start bit - 0000 0001
tsensor.tx[1]=0x80;//read channel 0 - | s/~d | d2 d1 d0 | x x x x |
// b7= single/~differential = 1 for single ended
// d2 d1 d0 = 0 for channel 0
tsensor.tx[2]=0x00; // don't care = x x x x x x x x
tsensor.Transfer(3);
//printf("%02X %02X \n",(unsigned char)tsensor.rx[1], (unsigned char)tsensor.rx[2]);
n = tsensor.rx[1]<<8 | tsensor.rx[2];
n&=0x03FF;//mask out invalid bits
v = 3.3*float(n)/ 1023;//using 3.3 Vref
t = (float(n)*3.3 - 511.5) / 10.23;
printf("n= %d v=%f t=%f\n",n,v,t);
usleep(1000000);
}
return 0;
}
| 29.206897
| 86
| 0.548996
|
yan9a
|
8bd919484fab1e1ecc7095de4b788278555b8a2e
| 3,587
|
hpp
|
C++
|
src/glfw/vk/soVkGLFWSurface.hpp
|
BenSolus/vulkan-engine
|
04a7114b7f9b2617cf6b5133e71190b1f48c0575
|
[
"MIT"
] | null | null | null |
src/glfw/vk/soVkGLFWSurface.hpp
|
BenSolus/vulkan-engine
|
04a7114b7f9b2617cf6b5133e71190b1f48c0575
|
[
"MIT"
] | null | null | null |
src/glfw/vk/soVkGLFWSurface.hpp
|
BenSolus/vulkan-engine
|
04a7114b7f9b2617cf6b5133e71190b1f48c0575
|
[
"MIT"
] | null | null | null |
/*
* Copyright (C) 2017-2018 by Bennet Carstensen
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
/**
* @file soVkGLFWSurface.hpp
* @author Bennet Carstensen
* @date 2018
* @copyright Copyright (c) 2017-2018 Bennet Carstensen
*
* 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 "soGLFWBaseSurface.hpp"
#include "soVulkanSurface.hpp"
namespace so {
namespace vk {
class
GLFWSurface : public base::Surface
{
public:
GLFWSurface();
explicit GLFWSurface(VkInstance const instance);
GLFWSurface(GLFWSurface const& other) = delete;
GLFWSurface(GLFWSurface&& other) = delete;
~GLFWSurface() noexcept;
GLFWSurface&
operator=(GLFWSurface const& other) = delete;
GLFWSurface&
operator=(GLFWSurface&& other) noexcept;
return_t
getInstanceExtensions(char const*** extensions, size_type* count) const;
return_t
createWindow(std::string const& title,
size_type const width,
size_type const height);
return_t
createSurface(VkInstance instance);
inline VkSurfaceKHR getVkSurfaceKHR() const { return mSurface; }
private:
VkSurfaceKHR mSurface;
VkInstance mInstance;
void
deleteMembers();
}; // GLFWSurface
} // namespace vk
} // namespace so
| 34.825243
| 79
| 0.68581
|
BenSolus
|
8bdc31d0ef68ae02e16281e4c5a8bf65c6f35f9e
| 1,248
|
cpp
|
C++
|
engine/Engine.cpp
|
shenchi/gllab
|
5d8fe33cd763d5fe5033da106b715751ae2e87ef
|
[
"MIT"
] | null | null | null |
engine/Engine.cpp
|
shenchi/gllab
|
5d8fe33cd763d5fe5033da106b715751ae2e87ef
|
[
"MIT"
] | null | null | null |
engine/Engine.cpp
|
shenchi/gllab
|
5d8fe33cd763d5fe5033da106b715751ae2e87ef
|
[
"MIT"
] | null | null | null |
#include "Engine.hpp"
EngineBase::~EngineBase() {
}
void EngineBase::run(int w, int h) {
if (!glfwInit())
return;
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
m_window = glfwCreateWindow(w, h, "GLLab", NULL, NULL);
if (!m_window) {
glfwTerminate();
return;
}
glfwMakeContextCurrent(m_window);
m_timer = new Timer();
if (!onInit()) {
glfwTerminate();
return;
}
glfwSwapInterval(0); // turn off vsync
float lastTime = m_timer->elapsed();
float nowTime = 0.0f;
int frameCount = 0;
float delta = 0.0f;
float totalDelta = 0.0f;
while (!glfwWindowShouldClose(m_window)) {
nowTime = m_timer->elapsed();
delta = nowTime - lastTime;
lastTime = nowTime;
onFrame(delta);
glfwSwapBuffers(m_window);
frameCount++;
totalDelta += delta;
if (totalDelta > 1.0f) {
totalDelta -= 1.0f;
printf("frame rate: %d\n", frameCount);
frameCount = 0;
}
glfwPollEvents();
}
onRelease();
delete m_timer;
glfwTerminate();
}
bool Engine::onInit() {
return false;
}
void Engine::onFrame(float dt) {
}
void Engine::onRelease() {
}
| 16.864865
| 63
| 0.684295
|
shenchi
|
8bdd8b6c0ae5f801651e5825fad97524ec28b936
| 130
|
hpp
|
C++
|
5.FIRMWARE/arch/x86_64/mach/include/mach.hpp
|
xivisi/MachineLearning
|
a213e18dfeb7b22ea4ea555696e4d7e7dddd16f1
|
[
"Apache-2.0"
] | null | null | null |
5.FIRMWARE/arch/x86_64/mach/include/mach.hpp
|
xivisi/MachineLearning
|
a213e18dfeb7b22ea4ea555696e4d7e7dddd16f1
|
[
"Apache-2.0"
] | null | null | null |
5.FIRMWARE/arch/x86_64/mach/include/mach.hpp
|
xivisi/MachineLearning
|
a213e18dfeb7b22ea4ea555696e4d7e7dddd16f1
|
[
"Apache-2.0"
] | null | null | null |
/*
文件: mach.hpp
作者: Li Yong
电邮: xivisi@126.com
时间: 2018年9月11日
*/
#ifndef MACH_HPP_
#define MACH_HPP_
#endif /* MACH_HPP_ */
| 8.125
| 22
| 0.669231
|
xivisi
|
8bddfd0cca46132af90dc57da322de32c3b976e4
| 2,244
|
cpp
|
C++
|
LinkList/p1list.cpp
|
imsanjayK/DataStructure
|
89ac5dc625d53653ea477071289c363024725ada
|
[
"Unlicense"
] | null | null | null |
LinkList/p1list.cpp
|
imsanjayK/DataStructure
|
89ac5dc625d53653ea477071289c363024725ada
|
[
"Unlicense"
] | null | null | null |
LinkList/p1list.cpp
|
imsanjayK/DataStructure
|
89ac5dc625d53653ea477071289c363024725ada
|
[
"Unlicense"
] | null | null | null |
#include <iostream>
#include <cstdlib>
using namespace std;
typedef struct list
{
int data;
struct list *next;
} linkList;
linkList *start;
void push(int value)
{
linkList *newNode = new linkList;
if (newNode == NULL)
{
cout << "start NUll";
}
else
{
newNode->data = value;
newNode->next = start;
start = newNode;
}
}
void pushBack(int value)
{
linkList *newNode = new linkList;
linkList *temp;
if (newNode == NULL)
{
cout << "start NUll";
}
else
{
newNode->data = value;
if (start == NULL)
{
newNode->next = NULL;
start = newNode;
}
else
{
temp = start;
while (temp->next != NULL)
{
// preNode = temp ;
temp = temp->next;
}
temp->next = newNode;
newNode->next = NULL;
}
}
}
void display()
{
linkList *temp;
if (start == NULL)
{
cout << "empty";
return;
}
temp = start;
while (temp)
{
cout << temp->data << endl;
temp = temp->next;
}
}
void deleteAtEnd()
{
linkList *newNode;
linkList *temp;
if (start == NULL)
{
cout << "list empty";
}
else
{
temp = start;
while (temp->next != NULL)
{
newNode = temp;
temp = temp->next;
}
newNode->next = NULL;
free(temp);
}
}
void deleteAtBegin()
{
linkList *temp;
if (start == NULL)
{
cout << "list empty";
}
else
{
temp = start;
start = temp->next;
free(temp);
}
}
int main()
{
system("cls");
cout << "main" << endl;
push(11);
push(27);
push(23);
push(23);
push(23);
push(40);
push(99);
pushBack(99);
display();
cout << "-----------------" << endl;
deleteAtBegin();
display();
cout << "-----------------" << endl;
deleteAtEnd();
//cout << maxRepeat();
display();
return 0;
}
| 17.809524
| 41
| 0.414884
|
imsanjayK
|
8bdfd552b3997f3a34651a386df174551d9e3397
| 445
|
cpp
|
C++
|
Exercicios1/matriz.cpp
|
leandro-araujo-silva/Aprendendo-Cpp
|
09c5eb038ca62f46a694c4386b6d9e1e7d2cb8fc
|
[
"MIT"
] | null | null | null |
Exercicios1/matriz.cpp
|
leandro-araujo-silva/Aprendendo-Cpp
|
09c5eb038ca62f46a694c4386b6d9e1e7d2cb8fc
|
[
"MIT"
] | null | null | null |
Exercicios1/matriz.cpp
|
leandro-araujo-silva/Aprendendo-Cpp
|
09c5eb038ca62f46a694c4386b6d9e1e7d2cb8fc
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int main() {
int matriz[2][3];
cout << "Digite os valores da matriz:\n";
for(int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
cout << "Matriz[" << i << "][" << j << "] = ";
cin >> matriz[i][j];
}
}
for(int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
cout << "Matriz[" << i << "][" << j << "] = " << matriz[i][j] << endl;
}
}
return 0;
}
| 18.541667
| 76
| 0.395506
|
leandro-araujo-silva
|
8be03b2b7842e06885e63d6b260c38a228788528
| 2,700
|
cpp
|
C++
|
doc-src/samples/close-error.cpp
|
lsilvest/crpcut
|
e9d694fb04599b72ebdcf6fea7d6ad598807ff41
|
[
"BSD-2-Clause"
] | 1
|
2019-04-09T12:48:41.000Z
|
2019-04-09T12:48:41.000Z
|
doc-src/samples/close-error.cpp
|
lsilvest/crpcut
|
e9d694fb04599b72ebdcf6fea7d6ad598807ff41
|
[
"BSD-2-Clause"
] | 2
|
2020-05-06T16:22:07.000Z
|
2020-05-07T04:02:41.000Z
|
doc-src/samples/close-error.cpp
|
lsilvest/crpcut
|
e9d694fb04599b72ebdcf6fea7d6ad598807ff41
|
[
"BSD-2-Clause"
] | 1
|
2019-04-10T12:47:11.000Z
|
2019-04-10T12:47:11.000Z
|
/*
* Copyright 2009 Bjorn Fahller <bjorn@fahller.se>
* All rights reserved
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <crpcut.hpp>
extern "C"
{
#include <unistd.h>
}
class raw_dump
{
public:
raw_dump(const char *filename) : fd(::open(filename, O_CREAT | O_EXCL))
{
if (fd < 0) throw std::exception("fail");
}
~raw_dump()
{
int rv = ::close(fd);
if (rv < 0) throw std::exception("close");
}
void dump(const void *buffer, size_t len)
{
const char *p = static_cast<const char*>(buffer);
size_t bytes_written = 0;
while (bytes_written < len)
{
int rv = ::write(fd, p + bytes_written, len - bytes_written);
if (rv < 0) throw std::exception("write");
if (rv == 0) return;
bytes_written+= rv;
}
}
private:
raw_dump(const raw_dump&);
raw_dump& operator=(const raw_dump&);
int fd;
};
namespace original {
CRPCUT_WRAP_FUNC(libc, close, int, (int fd), (fd));
}
int *set_errno = 0;
int close(int fd)
{
int rv = original::close(fd);
return set_errno ? *set_errno : rv;
}
template <const char *(&fname)>
struct cleaner
{
~cleaner() { ::unlink(&fname); }
};
const char *filename = "dump";
TEST(failed_close, cleaner<filename>)
{
(void)read_data("/dev/zero");
}
TEST(wrapped_with_wrong_expectations)
{
expected_filename = "/dev/random";
(void)read_data("/dev/zero");
}
int main(int argc, char *argv[])
{
return crpcut::run(argc, argv);
}
| 27.272727
| 77
| 0.692963
|
lsilvest
|
8be2b2a326e5be01b5f5d2fdfad31b9ea867d030
| 1,103
|
hpp
|
C++
|
Kernel/Threads/Scheduler.hpp
|
asynts/picoos
|
5197f86ce1902fc6572cecd10f97ca68109f2f86
|
[
"MIT"
] | 1
|
2021-08-24T05:59:32.000Z
|
2021-08-24T05:59:32.000Z
|
Kernel/Threads/Scheduler.hpp
|
asynts/picoos
|
5197f86ce1902fc6572cecd10f97ca68109f2f86
|
[
"MIT"
] | 3
|
2021-03-31T15:36:01.000Z
|
2021-04-19T14:17:44.000Z
|
Kernel/Threads/Scheduler.hpp
|
asynts/picoos
|
5197f86ce1902fc6572cecd10f97ca68109f2f86
|
[
"MIT"
] | null | null | null |
#pragma once
#include <Std/Singleton.hpp>
#include <Std/Vector.hpp>
#include <Std/CircularQueue.hpp>
#include <Kernel/Forward.hpp>
#include <Kernel/Threads/Thread.hpp>
#include <Kernel/SystemHandler.hpp>
#include <Kernel/PageAllocator.hpp>
namespace Kernel
{
constexpr bool debug_scheduler = false;
constexpr bool scheduler_slow = false;
class Scheduler : public Singleton<Scheduler> {
public:
Thread* active_thread_if_avaliable()
{
return m_active_thread;
}
Thread& active()
{
VERIFY(m_active_thread != nullptr);
return *m_active_thread;
}
Thread& schedule();
void add_thread(RefPtr<Thread> thread)
{
m_queued_threads.enqueue(thread);
}
void loop();
void trigger();
bool m_enabled = false;
CircularQueue<RefPtr<Thread>, 16> m_queued_threads;
private:
RefPtr<Thread> m_default_thread;
RefPtr<Thread> m_active_thread = nullptr;
friend Singleton<Scheduler>;
Scheduler();
};
}
| 20.811321
| 59
| 0.618314
|
asynts
|
8be9d39fc4b9b10782990946969a98776321be2d
| 97
|
cpp
|
C++
|
src/entdlr/parser/grammar/generated/flatbuffers/FlatBuffersParserVisitor.cpp
|
tstraus/entdlr
|
d38f16c545873cde2d2e9a892cff6bf1f7ce803f
|
[
"MIT"
] | null | null | null |
src/entdlr/parser/grammar/generated/flatbuffers/FlatBuffersParserVisitor.cpp
|
tstraus/entdlr
|
d38f16c545873cde2d2e9a892cff6bf1f7ce803f
|
[
"MIT"
] | null | null | null |
src/entdlr/parser/grammar/generated/flatbuffers/FlatBuffersParserVisitor.cpp
|
tstraus/entdlr
|
d38f16c545873cde2d2e9a892cff6bf1f7ce803f
|
[
"MIT"
] | null | null | null |
// Generated from FlatBuffersParser.g4 by ANTLR 4.9.3
#include "FlatBuffersParserVisitor.h"
| 12.125
| 53
| 0.762887
|
tstraus
|
8bef420924809a920949881929bec91863062bde
| 2,809
|
cc
|
C++
|
source/src/Objects/Track.cc
|
rete/Baboon
|
e5b2cfe6b9e5b5a41c2c68feda84b8df109eb086
|
[
"FSFAP"
] | null | null | null |
source/src/Objects/Track.cc
|
rete/Baboon
|
e5b2cfe6b9e5b5a41c2c68feda84b8df109eb086
|
[
"FSFAP"
] | null | null | null |
source/src/Objects/Track.cc
|
rete/Baboon
|
e5b2cfe6b9e5b5a41c2c68feda84b8df109eb086
|
[
"FSFAP"
] | null | null | null |
/// \file Track.cc
/*
*
* Track.cc source template generated by fclass
* Creation date : lun. avr. 29 2013
* Copyright (c) CNRS , IPNL
*
* All Right Reserved.
* Use and copying of these libraries and preparation of derivative works
* based upon these libraries are permitted. Any copy of these libraries
* must include this copyright notice.
*
* @author : rete
*/
#include "Objects/Track.hh"
using namespace std;
namespace baboon {
Track::Track()
: HitCompositeObject(),
TypedObject("Track") {
}
Track::~Track() {
}
TrackExtremities Track::GetExtremities() {
TrackExtremities extrem;
bool firstIt = true;
CaloHit *caloHitFirst = 0;
CaloHit *caloHitSecond = 0;
for(unsigned int i=0 ; i<caloHitCollection->size() ; i++) {
CaloHit *caloHit1 = caloHitCollection->at(i);
ThreeVector vec1 = caloHit1->GetPosition();
for(unsigned int j=0 ; j<caloHitCollection->size() ; j++) {
if( i == j ) continue;
CaloHit *caloHit2 = caloHitCollection->at(j);
ThreeVector vec2 = caloHit2->GetPosition();
if(firstIt) {
caloHitFirst = caloHit1;
caloHitSecond = caloHit2;
// extrem = make_pair( hit1 , hit2 );
firstIt = false;
continue;
}
// compare the distance between the two hits with the current minimum distance (in extrem)
if( (caloHit1->GetPosition() - caloHit2->GetPosition()).mag()
> (caloHitFirst->GetPosition() - caloHitSecond->GetPosition()).mag() ) {
caloHitFirst = caloHit1;
caloHitSecond = caloHit2;
}
}
}
extrem = make_pair( caloHitFirst , caloHitSecond );
return extrem;
}
std::vector<ThreeVector> Track::GetPositions() const {
std::vector<ThreeVector> vecCol;
for( unsigned int i=0 ; i<caloHitCollection->size() ; i++ ) {
vecCol.push_back( caloHitCollection->at(i)->GetPosition() );
}
return vecCol;
}
std::vector<ThreeVector> Track::GetIJKs() const {
std::vector<ThreeVector> ijks;
for( unsigned int i=0 ; i<caloHitCollection->size() ; i++ ) {
ThreeVector ijk( caloHitCollection->at(i)->GetIJK().at(0) , caloHitCollection->at(i)->GetIJK().at(1) , caloHitCollection->at(i)->GetIJK().at(2) );
ijks.push_back( ijk );
}
return ijks;
}
Return Track::SortHits() {
if( caloHitCollection->size() <= 1 )
return BABOON_SUCCESS("Sort one element or an empty list is easy...");
int i = 0;
int j = 0;
CaloHit *caloHit = 0;
for( j=1 ; j<caloHitCollection->size() ; j++ ) {
i = j-1;
while( caloHitCollection->at(j)->GetIJK().at(2) < caloHitCollection->at(i)->GetIJK().at(2) ) {
caloHit = caloHitCollection->at(i);
caloHitCollection->at(i) = caloHitCollection->at(j);
caloHitCollection->at(j) = caloHit;
i=i-1;
j=j-1;
if( i<0 ) break;
}
}
return BABOON_SUCCESS();
}
} // namespace
| 21.775194
| 149
| 0.644001
|
rete
|
8bef6194c19b70ad60f1b2599f56eb0f4cac1469
| 368
|
cpp
|
C++
|
src/stationchat/RegistrarNode.cpp
|
seefo/swg-stationapi
|
ae46b8a6177ea800b0dde00630051a19876cffae
|
[
"MIT"
] | null | null | null |
src/stationchat/RegistrarNode.cpp
|
seefo/swg-stationapi
|
ae46b8a6177ea800b0dde00630051a19876cffae
|
[
"MIT"
] | null | null | null |
src/stationchat/RegistrarNode.cpp
|
seefo/swg-stationapi
|
ae46b8a6177ea800b0dde00630051a19876cffae
|
[
"MIT"
] | 1
|
2022-03-09T23:57:59.000Z
|
2022-03-09T23:57:59.000Z
|
#include "RegistrarNode.hpp"
#include "StationChatConfig.hpp"
RegistrarNode::RegistrarNode(StationChatConfig& config)
: Node(this, config.registrarAddress, config.registrarPort, config.bindToIp)
, config_{config} {}
RegistrarNode::~RegistrarNode() {}
StationChatConfig& RegistrarNode::GetConfig() {
return config_;
}
void RegistrarNode::OnTick() {}
| 20.444444
| 80
| 0.75
|
seefo
|
8bf1eae24c25e7ec00c0d87aee060a990b1fc908
| 5,038
|
cpp
|
C++
|
include/types/operator.cpp
|
nathanmullenax83/rhizome
|
e7410341fdc4d38ab5aaecc55c94d3ac6efd51da
|
[
"MIT"
] | 1
|
2020-07-11T14:53:38.000Z
|
2020-07-11T14:53:38.000Z
|
include/types/operator.cpp
|
nathanmullenax83/rhizome
|
e7410341fdc4d38ab5aaecc55c94d3ac6efd51da
|
[
"MIT"
] | 1
|
2020-07-04T16:45:49.000Z
|
2020-07-04T16:45:49.000Z
|
include/types/operator.cpp
|
nathanmullenax83/rhizome
|
e7410341fdc4d38ab5aaecc55c94d3ac6efd51da
|
[
"MIT"
] | null | null | null |
#include "operator.hpp"
#include <cwctype>
#include <string>
#include <codecvt>
#include <locale>
namespace rhizome {
namespace types {
Thing * unit_dummy() {
throw runtime_error(" is not a unit operator.");
}
Thing * unary_dummy(Thing *a) {
(void)a;
throw runtime_error(" is not a unary operator.");
}
Thing * binary_dummy(Thing* a, Thing *b) {
(void)a; (void)b;
throw runtime_error(" is not a binary operator.");
}
Thing * nary_dummy( Tuple *t ) {
(void)t;
throw runtime_error(" is not an n-ary operator.");
}
// this is private--exclusively for cloning.
Operator::Operator() {
}
Operator::Operator( wstring op, UnitFunction apply )
: op({op}), unit_f(apply), unary_f(unary_dummy), binary_f(binary_dummy), nary_f(nary_dummy)
{
t = NONFIX;
arity_from = arity_to = 0;
}
// unary pre- or post- fix.
Operator::Operator( wstring op, UnaryFunction apply, OperatorType t )
: op({op}), unit_f(unit_dummy), unary_f(apply), binary_f(binary_dummy), nary_f(nary_dummy)
{
// consider ++p and ++++p
assert( t!=INFIX ); // as that just doesn't make any sense.
this->t = t;
// if it's a prefix operator, then it should be right to left.
// if it's postfix, then it has to be left to right
associativity = (t==POSTFIX? LEFT_TO_RIGHT : RIGHT_TO_LEFT); // ought to do it.
arity_from = arity_to = 1;
}
// binary infix (left or right associative)
Operator::Operator( wstring op, BinaryFunction apply, OperatorAssociativity assoc )
: op({op}), unit_f(unit_dummy), unary_f(unary_dummy), binary_f(apply), nary_f(nary_dummy)
{
t = INFIX;
associativity = assoc;
arity_from = arity_to = 2;
}
// n-ary pre- or post- fix.
Operator::Operator( wstring op, NAryFunction apply, OperatorType t)
: op({op}), t(t), unit_f(unit_dummy), unary_f(unary_dummy), binary_f(binary_dummy), nary_f(apply)
{
arity_from = 0;
arity_to = SIZE_MAX;
}
/// Sigh. Ternary, etc.
Operator::Operator( vector<wstring> ops, size_t arity, NAryFunction apply, OperatorType t)
: op(ops), t(t), unit_f(unit_dummy), unary_f(unary_dummy), binary_f(binary_dummy), nary_f(apply)
{
arity_from = arity_to = arity;
}
void Operator::serialize_to( size_t level, std::ostream &out ) const {
(void)level;
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
out << rhizome_type() << " ";
if(arity_from != arity_to ) {
if( arity_to==SIZE_MAX ) {
out << arity_from << "," << "∞" << "-compound";
} else {
out << arity_from << "," << arity_to << "-compound";
}
} else {
if( arity_from==2 ) {
out << "binary";
} else if( arity_from==1 ) {
out << "unary";
} else if( arity_from==0 ) {
out << "unit";
} else if( arity_from==3 ) {
out << "ternary";
} else {
out << arity_from << "-ary";
}
}
out << " ";
switch(t) {
case PREFIX: out << "prefix "; break;
case INFIX: out << "infix subex "; break;
case POSTFIX: out << "postfix "; break;
case NONFIX: break;
}
for(auto i=op.begin(); i!=op.end(); i++ ) {
wstring w = *i;
out << converter.to_bytes(w);
if( (i+1)!=op.end() ) {
out << " subex ";
}
}
if( t!=NONFIX ) {
out << " subex";
}
out << " ⏹";
}
string
Operator::rhizome_type() const {
return "Operator";
}
Thing *
Operator::clone() const {
Operator *p = new Operator();
p->arity_from = arity_from;
p->arity_to = arity_to;
p->associativity = associativity;
p->op = op;
p->t = t;
return p;
}
bool
Operator::has_interface( string const &w ) {
return (w==rhizome_type()||w=="Thing");
}
Thing *
Operator::invoke( Thing *context, string const &method, Thing *arg ) {
(void)arg; (void)context;
if(method=="`"||method=="eval") {
}
throw runtime_error("Not implemented.");
}
}
}
| 31.685535
| 106
| 0.467844
|
nathanmullenax83
|
8bf2b14218141d2e155dcbc81bf7bb714c6d429c
| 1,119
|
cpp
|
C++
|
source/msynth/msynth/ui/dialog/MRecordDialog.cpp
|
MRoc/MSynth
|
3eb5c6cf0ad6a3d12f555ebca5fbe84c1b255829
|
[
"MIT"
] | 1
|
2022-01-30T07:40:31.000Z
|
2022-01-30T07:40:31.000Z
|
source/msynth/msynth/ui/dialog/MRecordDialog.cpp
|
MRoc/MSynth
|
3eb5c6cf0ad6a3d12f555ebca5fbe84c1b255829
|
[
"MIT"
] | null | null | null |
source/msynth/msynth/ui/dialog/MRecordDialog.cpp
|
MRoc/MSynth
|
3eb5c6cf0ad6a3d12f555ebca5fbe84c1b255829
|
[
"MIT"
] | null | null | null |
#include "MRecordDialog.h"
MRecordDialog::MRecordDialog()
{
MSaxTreeDocument doc;
doc.parseResource( "resource/xml/recorddialog.xml" );
load( doc.getRoot() );
ivMode = RENDER;
}
MRecordDialog::~MRecordDialog()
{
}
MRecordDialog::DlgResult MRecordDialog::onDlgCommand( unsigned int id )
{
switch( id )
{
case IDC_RADIO1:
{
ivMode = RENDER;
MToggleButton* lrToggle = (MToggleButton*) MWndNamespace::getObjNS( this, "left2right" );
if( lrToggle )
lrToggle->setValue( false );
}
break;
case IDC_RADIO2:
{
ivMode = STREAMING;
MToggleButton* lrSession = (MToggleButton*) MWndNamespace::getObjNS( this, "session" );
if( lrSession )
lrSession->setValue( true );
}
break;
case IDOK: return MDialog::DlgResult::OK; break;
case IDCANCEL: return MDialog::DlgResult::CANCEL; break;
}
return MDialog::DlgResult::CANCEL;
}
void MRecordDialog::onInit()
{
MToggleButton* lrToggle = (MToggleButton*) MWndNamespace::getObjNS( this, "left2right" );
if( lrToggle )
lrToggle->setValue( true );
}
void MRecordDialog::onDestroy()
{
}
| 21.941176
| 93
| 0.670241
|
MRoc
|
8bf741dd5065ee7451bb49fe66b7956ef21a68b3
| 197
|
cpp
|
C++
|
30-app/viewdll/source/ctrlapp3.cpp
|
RealCrond/view
|
0a5f0b5d6e57d0d91f8b254ec9f3075e5185a34d
|
[
"MIT"
] | 1
|
2020-03-27T09:37:18.000Z
|
2020-03-27T09:37:18.000Z
|
30-app/viewdll/source/ctrlapp3.cpp
|
RealCrond/view
|
0a5f0b5d6e57d0d91f8b254ec9f3075e5185a34d
|
[
"MIT"
] | null | null | null |
30-app/viewdll/source/ctrlapp3.cpp
|
RealCrond/view
|
0a5f0b5d6e57d0d91f8b254ec9f3075e5185a34d
|
[
"MIT"
] | null | null | null |
#include "stdafx.h"
#include "ctrlapp3.h"
CCtrlApp3::CCtrlApp3()
{
}
CCtrlApp3::~CCtrlApp3()
{
}
BEGIN_MSG_MAP(CCtrlApp3)
//REG_MSG(emFistEventId, CCtrlApp1::OnCameraSelectCmd)
END_MSG_MAP()
| 11.588235
| 55
| 0.736041
|
RealCrond
|
8bf9baa09612c9b6ba0e39b5c17e1a12a80dc66e
| 740
|
cpp
|
C++
|
src/0039.cpp
|
shuihan0555/LeetCode-Solutions-in-Cpp17
|
8bb69fc546486c5e73839431204927626601dd18
|
[
"MIT"
] | null | null | null |
src/0039.cpp
|
shuihan0555/LeetCode-Solutions-in-Cpp17
|
8bb69fc546486c5e73839431204927626601dd18
|
[
"MIT"
] | null | null | null |
src/0039.cpp
|
shuihan0555/LeetCode-Solutions-in-Cpp17
|
8bb69fc546486c5e73839431204927626601dd18
|
[
"MIT"
] | null | null | null |
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> res;
vector<int> tmp;
dfs(res, tmp, candidates, 0, target);
return res;
}
void dfs(vector<vector<int>>& res, vector<int>& tmp, vector<int>& candidates, int n, int target)
{
if (!target)
{
res.emplace_back(tmp);
return;
}
for (int i = n; i < size(candidates); ++i)
{
if (target - candidates[i] >= 0)
{
tmp.emplace_back(candidates[i]);
dfs(res, tmp, candidates, i, target - candidates[i]);
tmp.pop_back();
}
}
}
};
| 27.407407
| 100
| 0.486486
|
shuihan0555
|
8bfa7858a0e5e4cac2701e40fee0b7790b94f730
| 14,133
|
hpp
|
C++
|
src/align_bench_seqan.hpp
|
rrahn/align_bench
|
eed206e113f2aa1a2ef7a2441f19e56ecafa23fc
|
[
"BSD-3-Clause"
] | 2
|
2017-03-08T05:35:46.000Z
|
2019-08-21T16:09:18.000Z
|
src/align_bench_seqan.hpp
|
rrahn/align_bench
|
eed206e113f2aa1a2ef7a2441f19e56ecafa23fc
|
[
"BSD-3-Clause"
] | null | null | null |
src/align_bench_seqan.hpp
|
rrahn/align_bench
|
eed206e113f2aa1a2ef7a2441f19e56ecafa23fc
|
[
"BSD-3-Clause"
] | null | null | null |
// ==========================================================================
// SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2018, Knut Reinert, FU Berlin
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN 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.
//
// ==========================================================================
// Author: Rene Rahn <rene.rahn@fu-berlin.de>
// ==========================================================================
#ifndef ALIGN_BENCH_SEQAN_HPP
#define ALIGN_BENCH_SEQAN_HPP
#include <seqan/basic.h>
#include <seqan/align_parallel.h>
#include "benchmark_executor.hpp"
using namespace seqan;
template <typename TGapsH, typename TGapsV>
inline void writeAlignment(AlignBenchOptions const & options,
TGapsH const & gapsH,
TGapsV const & gapsV)
{
auto printGaps = [&](auto & stream)
{
for (unsigned i = 0; i < length(gapsH); ++i)
{
stream << "Alignment no. " << i << std::endl;
stream << "Score: " << options.stats.scores[i] << std::endl;
stream << gapsH[i] << std::endl;
stream << gapsV[i] << std::endl;
}
};
if (options.alignOut == "stdout")
{
printGaps(std::cout);
return;
}
std::ofstream alignOut;
alignOut.open(options.alignOut.c_str());
if (!alignOut.good())
{
std::cerr << "Could not open file << " << options.alignOut.c_str() << ">>!" << std::endl;
return;
}
printGaps(alignOut);
alignOut.close();
}
template <typename TStream, typename TResultVec>
inline void writeScores_(TStream & stream,
TResultVec const & vec)
{
std::for_each(std::begin(vec), std::end(vec), [&](auto & sc) { stream << sc << ",\n"; });
stream << "\n";
}
inline void writeScores(AlignBenchOptions const & options)
{
if (options.alignOut == "stdout")
{
writeScores_(std::cout, options.stats.scores);
} else
{
std::ofstream alignOut;
alignOut.open(options.alignOut.c_str());
if (!alignOut.good())
{
std::cerr << "Could not open file << " << options.alignOut.c_str() << ">>!" << std::endl;
return;
}
writeScores_(alignOut, options.stats.scores);
}
}
#if defined(ALIGN_BENCH_TRACE)
template <typename TExecPolicy,
typename TSet1,
typename TSet2,
typename TScore>
inline void
BenchmarkExecutor::runAlignmentTrace(AlignBenchOptions & options,
TExecPolicy const & execPolicy,
TSet1 & set1,
TSet2 & set2,
TScore const & scoreMat)
{
options.stats.isBanded = "no";
using TSeqH = typename Value<TSet1>::Type;
using TSeqV = typename Value<TSet2>::Type;
StringSet<Gaps<TSeqH>> gapsSet1;
StringSet<Gaps<TSeqV>> gapsSet2;
auto fillGaps = [](auto & gaps, auto & sequences)
{
resize(gaps, length(sequences), Exact{});
for (unsigned i = 0; i < length(sequences); ++i)
{
assignSource(gaps[i], sequences[i]);
}
};
fillGaps(gapsSet1, set1);
fillGaps(gapsSet2, set2);
switch (options.method)
{
case AlignMethod::GLOBAL:
{
resize(options.stats.scores, length(gapsSet1), Exact());
start(mTimer);
auto res = globalAlignment(execPolicy, gapsSet1, gapsSet2, scoreMat);
stop(mTimer);
seqan::arrayMoveForward(begin(res, Standard()), end(res, Standard()), begin(options.stats.scores, Standard()));
break;
}
case AlignMethod::LOCAL:
{
resize(options.stats.scores, length(gapsSet1), Exact());
start(mTimer);
auto res = localAlignment(execPolicy, gapsSet1, gapsSet2, scoreMat);
stop(mTimer);
seqan::arrayMoveForward(begin(res, Standard()), end(res, Standard()), begin(options.stats.scores, Standard()));
break;
}
case AlignMethod::SEMIGLOBAL:
{
resize(options.stats.scores, length(gapsSet1), Exact());
start(mTimer);
auto res = globalAlignment(execPolicy, gapsSet1, gapsSet2, scoreMat, AlignConfig<true, false, false, true>{});
stop(mTimer);
seqan::arrayMoveForward(begin(res, Standard()), end(res, Standard()), begin(options.stats.scores, Standard()));
break;
}
case AlignMethod::OVERLAP:
{
resize(options.stats.scores, length(gapsSet1), Exact());
start(mTimer);
auto res = globalAlignment(execPolicy, gapsSet1, gapsSet2, scoreMat, AlignConfig<true, true, true, true>{});
stop(mTimer);
seqan::arrayMoveForward(begin(res, Standard()), end(res, Standard()), begin(options.stats.scores, Standard()));
break;
}
}
writeAlignment(options, gapsSet1, gapsSet2);
}
template <typename TExecPolicy,
typename TSet1,
typename TSet2,
typename TScore>
inline void
BenchmarkExecutor::runAlignmentBandedTrace(AlignBenchOptions & options,
TExecPolicy const & execPolicy,
TSet1 & set1,
TSet2 & set2,
TScore const & scoreMat)
{
options.stats.isBanded = "yes";
using TSeqH = typename Value<TSet1>::Type;
using TSeqV = typename Value<TSet2>::Type;
StringSet<Gaps<TSeqH>> gapsSet1;
StringSet<Gaps<TSeqV>> gapsSet2;
auto fillGaps = [](auto & gaps, auto & sequences)
{
resize(gaps, length(sequences), Exact{});
for (unsigned i = 0; i < length(sequences); ++i)
{
assignSource(gaps[i], sequences[i]);
}
};
fillGaps(gapsSet1, set1);
fillGaps(gapsSet2, set2);
switch (options.method)
{
case AlignMethod::GLOBAL:
{
resize(options.stats.scores, length(gapsSet1), Exact());
start(mTimer);
auto res = globalAlignment(execPolicy, gapsSet1, gapsSet2, scoreMat, options.lower, options.upper);
stop(mTimer);
seqan::arrayMoveForward(begin(res, Standard()), end(res, Standard()), begin(options.stats.scores, Standard()));
break;
}
case AlignMethod::LOCAL:
{
resize(options.stats.scores, length(gapsSet1), Exact());
start(mTimer);
auto res = localAlignment(execPolicy, gapsSet1, gapsSet2, scoreMat, options.lower, options.upper);
stop(mTimer);
seqan::arrayMoveForward(begin(res, Standard()), end(res, Standard()), begin(options.stats.scores, Standard()));
break;
}
case AlignMethod::SEMIGLOBAL:
{
resize(options.stats.scores, length(gapsSet1), Exact());
start(mTimer);
auto res = globalAlignment(execPolicy, gapsSet1, gapsSet2, scoreMat, AlignConfig<true, false, false, true>{}, options.lower, options.upper);
stop(mTimer);
seqan::arrayMoveForward(begin(res, Standard()), end(res, Standard()), begin(options.stats.scores, Standard()));
break;
}
case AlignMethod::OVERLAP:
{
resize(options.stats.scores, length(gapsSet1), Exact());
start(mTimer);
auto res = globalAlignment(execPolicy, gapsSet1, gapsSet2, scoreMat, AlignConfig<true, true, true, true>{}, options.lower, options.upper);
stop(mTimer);
seqan::arrayMoveForward(begin(res, Standard()), end(res, Standard()), begin(options.stats.scores, Standard()));
break;
}
}
writeAlignment(options, gapsSet1, gapsSet2);
}
#else // ALIGN_BENCH_TRACE
template <typename TExecPolicy,
typename TSet1,
typename TSet2,
typename TScore>
inline void
BenchmarkExecutor::runAlignment(AlignBenchOptions & options,
TExecPolicy const & execPolicy,
TSet1 & set1,
TSet2 & set2,
TScore const & scoreMat)
{
options.stats.isBanded = "no";
switch (options.method)
{
case AlignMethod::GLOBAL:
{
resize(options.stats.scores, length(set1), Exact());
start(mTimer);
auto res = globalAlignmentScore(execPolicy, set1, set2, scoreMat);
stop(mTimer);
seqan::arrayMoveForward(begin(res, Standard()), end(res, Standard()), begin(options.stats.scores, Standard()));
break;
}
case AlignMethod::LOCAL:
{
resize(options.stats.scores, length(set1), Exact());
start(mTimer);
auto res = localAlignmentScore(execPolicy, set1, set2, scoreMat);
stop(mTimer);
seqan::arrayMoveForward(begin(res, Standard()), end(res, Standard()), begin(options.stats.scores, Standard()));
break;
}
case AlignMethod::SEMIGLOBAL:
{
resize(options.stats.scores, length(set1), Exact());
start(mTimer);
auto res = globalAlignmentScore(execPolicy, set1, set2, scoreMat, AlignConfig<true, false, false, true>{});
stop(mTimer);
seqan::arrayMoveForward(begin(res, Standard()), end(res, Standard()), begin(options.stats.scores, Standard()));
break;
}
case AlignMethod::OVERLAP:
{
resize(options.stats.scores, length(set1), Exact());
start(mTimer);
auto res = globalAlignmentScore(execPolicy, set1, set2, scoreMat, AlignConfig<true, true, true, true>{});
stop(mTimer);
seqan::arrayMoveForward(begin(res, Standard()), end(res, Standard()), begin(options.stats.scores, Standard()));
break;
}
}
writeScores(options);
}
#if defined(ALIGN_BENCH_BANDED)
template <typename TExecPolicy,
typename TSet1,
typename TSet2,
typename TScore>
inline void
BenchmarkExecutor::runAlignmentBanded(AlignBenchOptions & options,
TExecPolicy const & execPolicy,
TSet1 const & set1,
TSet2 const & set2,
TScore const & scoreMat)
{
options.stats.isBanded = "yes";
switch (options.method)
{
case AlignMethod::GLOBAL:
{
resize(options.stats.scores, length(set1), Exact());
start(mTimer);
auto res = globalAlignmentScore(execPolicy, set1, set2, scoreMat, options.lower, options.upper);
stop(mTimer);
seqan::arrayMoveForward(begin(res, Standard()), end(res, Standard()), begin(options.stats.scores, Standard()));
break;
}
case AlignMethod::LOCAL:
{
resize(options.stats.scores, length(set1), Exact());
start(mTimer);
auto res = localAlignmentScore(execPolicy, set1, set2, scoreMat, options.lower, options.upper);
stop(mTimer);
seqan::arrayMoveForward(begin(res, Standard()), end(res, Standard()), begin(options.stats.scores, Standard()));
break;
}
case AlignMethod::SEMIGLOBAL:
{
resize(options.stats.scores, length(set1), Exact());
start(mTimer);
auto res = globalAlignmentScore(execPolicy, set1, set2, scoreMat, AlignConfig<true, false, false, true>{}, options.lower, options.upper);
stop(mTimer);
seqan::arrayMoveForward(begin(res, Standard()), end(res, Standard()), begin(options.stats.scores, Standard()));
break;
}
case AlignMethod::OVERLAP:
{
resize(options.stats.scores, length(set1), Exact());
start(mTimer);
auto res = globalAlignmentScore(execPolicy, set1, set2, scoreMat, AlignConfig<true, true, true, true>{}, options.lower, options.upper);
stop(mTimer);
seqan::arrayMoveForward(begin(res, Standard()), end(res, Standard()), begin(options.stats.scores, Standard()));
break;
}
}
writeScores(options);
}
#endif // ALIGN_BENCH_BANDED
#endif // ALIGN_BENCH_TRACE
#endif // ALIGN_BENCH_SEQAN_HPP
| 39.477654
| 152
| 0.574117
|
rrahn
|
8bfbdf50008464649c64cc0191c62685f48c9948
| 5,334
|
cc
|
C++
|
ProbTools/ConsistencySet.cc
|
brownd1978/FastSim
|
05f590d72d8e7f71856fd833114a38b84fc7fd48
|
[
"Apache-2.0"
] | null | null | null |
ProbTools/ConsistencySet.cc
|
brownd1978/FastSim
|
05f590d72d8e7f71856fd833114a38b84fc7fd48
|
[
"Apache-2.0"
] | null | null | null |
ProbTools/ConsistencySet.cc
|
brownd1978/FastSim
|
05f590d72d8e7f71856fd833114a38b84fc7fd48
|
[
"Apache-2.0"
] | null | null | null |
//--------------------------------------------------------------------------
// File and Version Information:
// $Id: ConsistencySet.cc 704 2010-11-10 15:23:36Z stroili $
//
// Description:
// Class ConsistencySet -- see header
//
// Environment:
// Software developed for the BaBar Detector at the SLAC B-Factory.
//
// Author List:
// Yury Kolomensky 05/02/98
//
// Copyright (C) 1998 Caltech
//
//------------------------------------------------------------------------
#include "BaBar/BaBar.hh"
//-----------------------
// This Class's Header --
//-----------------------
#include "ProbTools/ConsistencySet.hh"
#include "BbrStdUtils/String.hh"
#include <algorithm>
//-------------
// C Headers --
//-------------
extern "C" {
#include <assert.h>
}
//---------------
// C++ Headers --
//---------------
#include <iostream>
#include <iomanip>
using std::endl;
using std::ostream;
using std::setw;
//----------------
// Constructors --
//----------------
ConsistencySet::ConsistencySet()
{
}
ConsistencySet::ConsistencySet(const ConsistencySet& other) :
_consistencyList(other._consistencyList), _labelList(other._labelList)
{
}
//--------------
// Destructor --
//--------------
ConsistencySet::~ConsistencySet()
{
}
//-------------
// Methods --
//-------------
size_t
ConsistencySet::nParents() const
{
return _labelList.size();
}
const Consistency*
ConsistencySet::getConsistency(size_t index) const
{
if (index >= _consistencyList.size()) return 0;
return &_consistencyList[index];
}
const Consistency*
ConsistencySet::getLabelConsistency(const char* label) const
{
size_t index = 0;
if (0 != label) {
std::string d(label);
babar::String::transformToLower(d);
if (!getLabelIndex_(d, index)) return 0;
}
return getConsistency(index);
}
const char*
ConsistencySet::getLabel(size_t index) const
{
if (index >= _labelList.size()) return 0;
return _labelList[index].c_str();
}
double
ConsistencySet::worstSignificance() const
{
size_t index = 0;
if (!worstSignificanceIndex_(index)) return 0.;
const Consistency* cons = getConsistency(index);
assert(cons != 0);
return cons->significanceLevel();
}
const char*
ConsistencySet::worstSignificanceLabel() const
{
size_t index = 0;
if (!worstSignificanceIndex_(index)) return 0;
return getLabel(index);
}
ConsistencySet*
ConsistencySet::overlap(const ConsistencySet& other) const
{
ConsistencySet* result = 0;
for (size_t i = 0; i < this->nParents(); i++) {
if (0 != other.getLabelConsistency(this->getLabel(i))) {
if (0 == result) {
result = new ConsistencySet;
}
result->add(this->getLabel(i), *(this->getConsistency(i)));
}
}
return result;
}
//-------------
// Operators --
//-------------
ConsistencySet&
ConsistencySet::operator=(const ConsistencySet& rhs)
{
if (this != &rhs) {
_consistencyList = rhs._consistencyList;
_labelList = rhs._labelList;
}
return *this;
}
bool
ConsistencySet::operator==(const ConsistencySet& rhs) const
{
bool retval = false;
// just in case
if (this != &rhs) {
if (this->nParents() == rhs.nParents()) {
retval = true;
for (size_t i = 0; i < nParents(); i++) {
// order is not guaranteed to be the same even for equal objects
if (0 == rhs.getLabelConsistency(this->getLabel(i))) {
retval = false;
return retval;
}
}
}
}
return retval;
}
bool
ConsistencySet::operator!=(const ConsistencySet& rhs) const
{
return !(*this == rhs);
}
//-------------
// Selectors --
//-------------
//-------------
// Modifiers --
//-------------
void
ConsistencySet::reset()
{
_consistencyList.clear();
_labelList.clear();
}
bool
ConsistencySet::add(const char* label, const Consistency& c)
{
bool retval = false;
// some idiot-proofing
if (0 != label) {
std::string d(label);
babar::String::transformToLower(d);
// test for overlaps
size_t index;
if (!getLabelIndex_(d, index)) {
_labelList.push_back(d);
_consistencyList.push_back(c);
retval = true;
}
}
return retval;
}
bool
ConsistencySet::combine(const ConsistencySet& other)
{
bool retval = true;
for (size_t i = 0; i < other.nParents(); i++) {
retval = retval && add(other.getLabel(i), *(other.getConsistency(i)));
}
return retval;
}
//
// Internal protected functions
//
bool
ConsistencySet::getLabelIndex_(const std::string& dLower, size_t& index) const
{
bool retval = false;
std::vector<std::string>::const_iterator iter = _labelList.begin();
index = 0;
while (iter != _labelList.end()) {
if (*iter == dLower) {
retval = true;
break;
}
index++;
++iter;
}
return retval;
}
bool
ConsistencySet::worstSignificanceIndex_(size_t& index) const
{
double worst(999.);
const Consistency* cons = 0;
size_t i = 0;
while ((cons = getConsistency(i))) {
double value = cons->significanceLevel();
if (value < worst) {
index = i;
worst = value;
}
i++;
}
return worst <= 1.;
}
void
ConsistencySet::print(ostream& os) const
{
os << nParents() << " parents:" << endl;
for (size_t i = 0; i < nParents(); i++) {
os << setw(3) << i;
os << setw(10) << _labelList[i] << " : ";
_consistencyList[i].print(os);
}
}
| 18.982206
| 78
| 0.587364
|
brownd1978
|
8bfe4b52ee3158d0b972817b2cb94736f6c76e16
| 2,238
|
cpp
|
C++
|
src/timer.cpp
|
ekera/qunundrum
|
deeed6779a5b0e69df9245024225b8a552c2179c
|
[
"MIT"
] | 4
|
2020-12-09T10:57:05.000Z
|
2021-12-27T15:44:47.000Z
|
src/timer.cpp
|
ekera/qunundrum
|
deeed6779a5b0e69df9245024225b8a552c2179c
|
[
"MIT"
] | null | null | null |
src/timer.cpp
|
ekera/qunundrum
|
deeed6779a5b0e69df9245024225b8a552c2179c
|
[
"MIT"
] | null | null | null |
/*!
* \file timer.cpp
* \ingroup timer
*
* \brief The definition of functions for manipulating timers and collecting
* timing statistics.
*/
#include "timer.h"
#include <stdint.h>
#include <string.h>
#include <time.h>
void timer_start(
Timer * const timer)
{
clock_gettime(CLOCK_MONOTONIC_RAW, &(timer->start));
memcpy(&(timer->stop), &(timer->start), sizeof(struct timespec));
}
uint64_t timer_stop(
Timer * const timer)
{
clock_gettime(CLOCK_MONOTONIC_RAW, &(timer->stop));
int64_t delta;
delta = (int64_t)(timer->stop.tv_sec) -
(int64_t)(timer->start.tv_sec);
delta *= 1000 * 1000; /* compensate for us resolution */
delta += ((int64_t)(timer->stop.tv_nsec) -
(int64_t)(timer->start.tv_nsec)) / 1000; /* reduce ns to us */
if (delta < 0) {
delta = 0;
}
return (uint64_t)delta;
}
void timer_statistics_init(
Timer_Statistics * const statistics)
{
timer_statistics_reset(statistics);
}
void timer_statistics_reset(
Timer_Statistics * const statistics)
{
statistics->min = (uint64_t)(-1);
statistics->max = 0;
statistics->sum = 0;
statistics->count = 0;
}
void timer_statistics_insert(
Timer_Statistics * const statistics,
const uint64_t t)
{
if (statistics->min > t) {
statistics->min = t;
}
if (statistics->max < t) {
statistics->max = t;
}
statistics->sum += t;
statistics->count += 1;
}
void timer_statistics_export(
uint64_t * const min,
uint64_t * const max,
uint64_t * const sum,
uint32_t * const count,
double * const avg,
const Timer_Statistics * const statistics)
{
if (NULL != min) {
if (statistics->count == 0) {
(*min) = 0;
} else {
(*min) = statistics->min;
}
}
if (NULL != max) {
if (statistics->count == 0) {
(*max) = 0;
} else {
(*max) = statistics->max;
}
}
if (NULL != sum) {
if (statistics->count == 0) {
(*sum) = 0;
} else {
(*sum) = statistics->sum;
}
}
if (NULL != count) {
(*count) = statistics->count;
}
if (NULL != avg) {
if (statistics->count == 0) {
(*avg) = 0;
} else {
(*avg) = ((double)statistics->sum) / ((double)statistics->count);
}
}
}
| 18.806723
| 78
| 0.592493
|
ekera
|
bdd70b22c8427bd1b6a3dd13583f9f723a739e46
| 282
|
cc
|
C++
|
src/mob/friendly/Zeus.cc
|
kallentu/pathos
|
1914edbccc98baef79d98fb065119230072ac40d
|
[
"MIT"
] | 7
|
2019-05-09T15:38:55.000Z
|
2021-12-07T03:13:29.000Z
|
src/mob/friendly/Zeus.cc
|
kallentu/pathos
|
1914edbccc98baef79d98fb065119230072ac40d
|
[
"MIT"
] | 1
|
2019-06-20T03:01:18.000Z
|
2019-06-20T03:01:18.000Z
|
src/mob/friendly/Zeus.cc
|
kallentu/pathos
|
1914edbccc98baef79d98fb065119230072ac40d
|
[
"MIT"
] | null | null | null |
#include "mob/friendly/Zeus.h"
#include "request/TalkRequest.h"
#include <memory>
using namespace Pathos;
std::unique_ptr<TalkRequest> Zeus::beTalkedToBy(Player &p) {
(void)p;
return std::make_unique<TalkRequest>(
"When you need me, lightning will be by your side.");
}
| 23.5
| 60
| 0.719858
|
kallentu
|
bdd7c99e4f0dfd095d69105db7b52ef047def2b6
| 406
|
cpp
|
C++
|
directfire_github/trunk/gameui/menuscene.cpp
|
zhwsh00/DirectFire-android
|
10c757e1be0b25dee951f9ba3a0e1f6d5c04a938
|
[
"MIT"
] | 1
|
2015-08-12T04:05:33.000Z
|
2015-08-12T04:05:33.000Z
|
directfire_github/trunk/gameui/menuscene.cpp
|
zhwsh00/DirectFire-android
|
10c757e1be0b25dee951f9ba3a0e1f6d5c04a938
|
[
"MIT"
] | null | null | null |
directfire_github/trunk/gameui/menuscene.cpp
|
zhwsh00/DirectFire-android
|
10c757e1be0b25dee951f9ba3a0e1f6d5c04a938
|
[
"MIT"
] | null | null | null |
#include "menuscene.h"
#include "mainmenulayer.h"
#include "gamecore/serverinterface.h"
MenuScene::MenuScene()
{
ServerInterface::getInstance();
}
MenuScene::~MenuScene()
{
}
bool MenuScene::init()
{
bool ret = false;
do {
CC_BREAK_IF(!CCScene::init());
this->addChild(MainMenuLayer::create());
ret = true;
} while (0);
return ret;
}
| 16.24
| 49
| 0.583744
|
zhwsh00
|
bdd93f5b4e5df56b2800daa79defddf4def0946e
| 19,004
|
cpp
|
C++
|
Lab-7/CS20B1127_Inheritance.cpp
|
Hitesh1309/OOPS-Lab-Submissions
|
d5bc462686e328760ca6091c8fe3dcc514b98dd9
|
[
"MIT"
] | null | null | null |
Lab-7/CS20B1127_Inheritance.cpp
|
Hitesh1309/OOPS-Lab-Submissions
|
d5bc462686e328760ca6091c8fe3dcc514b98dd9
|
[
"MIT"
] | null | null | null |
Lab-7/CS20B1127_Inheritance.cpp
|
Hitesh1309/OOPS-Lab-Submissions
|
d5bc462686e328760ca6091c8fe3dcc514b98dd9
|
[
"MIT"
] | null | null | null |
//CS20B1127
//Hitesh Gupta
//Program for Inheritance.
// NOTE : The credit and debit in checking account using option 2 and 3 respectively are done without cutting the transaction fee.
#include <iostream>
using namespace std;
// Class for storing linked list of Saving Accounts.
class SavingsLL
{
public:
int value1;
double value2;
double value3;
SavingsLL *snext;
};
// Class for storing linked list of Checking Accounts.
class CheckingLL
{
public:
int value1;
double value2;
double value3;
CheckingLL *cnext;
};
// Base Class Account
class Account
{
public:
int accNum;
double accBal;
// Default constructor.
Account()
{
accNum = 0;
accBal = 0.0;
}
// Parameterised constructor.
Account(int temp ,double bal)
{
accNum = temp;
if(bal >= 0.0)
this->accBal = bal;
else
{
this->accBal = 0.0;
cout << "The initial balance is invalid." << endl;
}
}
// Function to credit amount.
void credit(double amount)
{
if(amount <= 0)
{
cout << "The amount is invalid." << endl;
}
else
{
accBal = accBal + amount;
}
}
// Boolean function to debit amount and return whether the amount is debited or not.
bool debit(double amount)
{
if(amount <= 0)
{
cout << "The amount is invalid." << endl;
return false;
}
else if(amount > accBal)
{
cout << "Debit amount exceeded account balance." << endl;
return false;
}
else
{
accBal = accBal - amount;
return true;
}
}
// Function to return the balance.
double getBal()
{
return this->accBal;
}
};
// Derived class for saving accounts.
class SavingsAccount : public Account
{
public:
double intRate;
// Default constructor.
SavingsAccount()
{
intRate = 0.0;
}
// Parameterised constructor.
SavingsAccount(int temp, double bal , double rate):Account(temp,bal)
{
if(rate >= 0.0)
{
intRate = rate;
}
else
{
cout << "The initial interest rate is invalid." << endl;
intRate = 0.0;
}
}
// Function to return the interest amount.
double calculate_interest( )
{
return getBal()*(intRate/100);
}
};
// Derived class for checking accounts.
class CheckingAccount : public Account
{
public:
double tranFee;
// Default constructor.
CheckingAccount()
{
tranFee = 0.0;
}
// Parameterised constructor.
CheckingAccount(int temp, double bal, double fee):Account(temp,bal)
{
if(fee >= 0.0)
{
tranFee = fee;
}
else
{
cout << "The initial fee is invalid." << endl;
tranFee = 0.0;
}
}
// Function that credits amount into checking account by subtracting the fee amount.
void credit(double amount)
{
if(amount <= 0)
{
cout << "The amount is invalid." << endl;
}
else if(getBal()-tranFee+amount < 0)
{
cout << "Charge fee exceeded account balance after credit." << endl;
cout << "Please enter more money." << endl;
}
else
{
Account :: credit(amount);
Account :: debit(tranFee);
}
}
// Function that debits amount from checking account by subtracting the fee amount.
void debit(double amount)
{
if(amount <= 0)
{
cout << "The amount is invalid." << endl;
}
else if((amount+tranFee) > getBal())
{
cout << "Debit amount along with the transaction fee exceeded account balance." << endl;
}
else
{
Account :: debit(amount);
Account :: debit(tranFee);
}
}
};
// Boolean function to check whether the account number already exists in Savings account LL.
bool savSearch (SavingsLL *head, double x)
{
SavingsLL* current = head;
while (current != NULL)
{
if (current->value1 == x)
return true;
current = current->snext;
}
return false;
}
// Boolean function to check whether the account number already exists in Checking account LL.
bool checSearch (CheckingLL *head, double x)
{
CheckingLL* current = head;
while (current!=NULL)
{
if(current->value1 == x)
return true;
current = current->cnext;
}
return false;
}
// Main function.
int main()
{
int choice,obj;
double temp;
CheckingAccount ch1;
SavingsAccount sA1;
SavingsLL *shead = NULL;
CheckingLL *chead = NULL;
SavingsLL *ptr1 = shead;
CheckingLL *ptr2 = chead;
while(1)
{
cout << "\n 1. Open Account (Savings or Checking Account) " << endl;
cout << "\n 2. Credit in Savings or Checking Account/n" << endl;
cout << "\n 3. Debit in Savings or Checking Account " << endl;
cout << "\n 4. Change/Update Interest rate in Savings Account" << endl;
cout << "\n 5. Calculate Interest in Savings Account and printing " << endl;
cout << "\n 6. Calculate and Update Interest in Savings Account " << endl;
cout << "\n 7. Change/Update Fee Amount in Checking Account " << endl;
cout << "\n 8. Print Checking Fee in Checking Account " << endl;
cout << "\n 9. Transact and Update the balence in Checking Account " << endl;
cout << "\n 10. Exit" << endl;
cout << "\n Select Your Option :" << endl;
cin >> choice;
switch(choice)
{
case 1:
{
A:
cout << "Press 1 for savings Account and 2 for checking Account:" << endl;;
cin >> obj;
if(obj == 1)
{
ptr1 = new SavingsLL( );
cout << "Please enter the Account number: " << endl;
cin >> temp;
if(savSearch(shead,temp)||checSearch(chead,temp))
{
cout << "Account number already exists. Please try again.\n" << endl;
break;
}
else
{
ptr1->value1 = temp;
}
cout << "Please enter the initial Balance: " << endl;
cin >> ptr1->value2;
cout << "Please enter the initial Interest Rate : " << endl;
cin >> ptr1->value3;
if(shead == NULL)
{
shead = ptr1;
shead->snext = NULL;
}
else
{
ptr1->snext = shead;
shead = ptr1;
}
}
else if(obj == 2)
{
ptr2 = new CheckingLL( );
cout << "Please enter the Account number: " << endl;
cin >> temp;
if(checSearch(chead,temp)||savSearch(shead,temp))
{
cout << "Account number already exists. Please try again.\n" << endl;
break;
}
else
{
ptr2->value1 = temp;
}
cout << "Please enter the initial balance: " << endl;
cin >> ptr2->value2;
cout << "Please enter the initial Fee per transaction : " << endl;
cin >> ptr2->value3;
if(chead == NULL)
{
chead = ptr2;
chead->cnext = NULL;
}
else
{
ptr2->cnext = chead;
chead = ptr2;
}
}
else
{
cout << "Please enter an valid option." << endl;
goto A;
}
break;
}
case 2:
{
B:
cout << "Press 1 for crediting amount in savings Account and 2 for checking Account :" << endl;
cin >> obj;
if( obj == 1)
{
cout << "Please enter the Account number: " << endl;
cin >> obj;
SavingsLL *pointer = shead;
if(savSearch(pointer,obj))
{
sA1 = SavingsAccount (pointer->value1,pointer->value2,pointer->value3);
cout << "The balance before the credit is " << sA1.getBal() << endl;
cout << "Please enter the amount to be credited: " << endl;
cin >> temp;
sA1.credit(temp);
pointer->value2 = sA1.accBal;
cout << "The balance after the credit is " << sA1.getBal() << endl;
break;
}
else
{
cout << "There is no account in savings Account" << endl;
break;
}
}
else if( obj == 2)
{
cout << "Please enter the Account number: " << endl;
cin >> obj;
CheckingLL *pointer = chead;
if(checSearch(pointer,obj))
{
ch1 = CheckingAccount (pointer->value1,pointer->value2,pointer->value3);
cout << "The balance before the credit is " << ch1.getBal() << endl;
cout << "Please enter the amount to be credited: " << endl;
cin >> temp;
ch1.Account::credit(temp);
pointer->value2 = ch1.accBal;
cout << "The balance after the credit is " << ch1.getBal() << endl;
break;
}
else
{
cout << "There is no account in checking Account" << endl;
break;
}
}
else
{
cout << "Please enter an valid option." << endl;
goto B;
}
break;
}
case 3:
{
C:
cout << "Press 1 for debiting amount in savings Account and 2 for checking Account :" << endl;
cin >> obj;
if( obj == 1)
{
cout << "Please enter the Account number: " << endl;
cin >> obj;
SavingsLL *pointer = shead;
if(savSearch(pointer,obj))
{
cout << "The balance before the debit is " << sA1.getBal() << endl;
cout << "Please enter the amount to be debited: " << endl;
cin >> temp;
sA1.debit(temp);
pointer->value2 = sA1.accBal;
cout << "The balance after the debit is " << sA1.getBal() << endl;
break;
}
else
{
cout << "There is no account in savings Account" << endl;
break;
}
}
else if( obj == 2)
{
cout << "Please enter the Account number: " << endl;
cin >> obj;
CheckingLL *pointer = chead;
if(checSearch(pointer,obj))
{
cout << "The balance before the debit is " << ch1.getBal() << endl;
cout << "Please enter the amount to be debited: " << endl;
cin >> temp;
ch1.Account::debit(temp);
pointer->value2 = ch1.accBal;
cout << "The balance after the debit is " << ch1.getBal() << endl;
break;
}
else
{
cout << "There is no account in checking Account" << endl;
break;
}
}
else
{
cout << "Please enter an valid option." << endl;
goto C;
}
break;
}
case 4:
{
cout << "Please enter the Account number: " << endl;
cin >> obj;
SavingsLL *pointer = shead;
if(savSearch(pointer,obj))
{
cout << "The existing interest rate is " << pointer->value3 << endl;
cout << "Please enter the new interest rate." << endl;
cin >> temp;
pointer->value3 = temp;
sA1 = SavingsAccount(pointer->value1,pointer->value2,pointer->value3);
break;
}
else
{
cout << "There is no account in savings Account" << endl;
break;
}
break;
}
case 5:
{
cout << "Please enter the Account number: " << endl;
cin >> obj;
SavingsLL *pointer = shead;
if(savSearch(pointer,obj))
{
cout << "The total interest is " << sA1.calculate_interest() << endl;
break;
}
else
{
cout << "There is no account in savings Account" << endl;
break;
}
break;
}
case 6:
{
cout << "Please enter the Account number: " << endl;
cin >> obj;
SavingsLL *pointer = shead;
if(savSearch(pointer,obj))
{
cout << "The balance before adding the interest is " << sA1.accBal << endl;
temp = sA1.calculate_interest();
sA1.credit(temp);
cout << "The balance after adding the interest is " << sA1.accBal << endl;
break;
}
else
{
cout << "There is no account in savings Account" << endl;
break;
}
break;
}
case 7:
{
cout << "Please enter the Account number: " << endl;
cin >> obj;
CheckingLL *pointer = chead;
if(checSearch(pointer,obj))
{
cout << "The existing transaction fee is " << pointer->value3 << endl;
cout << "Please enter the new transaction fee." << endl;
cin >> temp;
pointer->value3 = temp;
ch1 = CheckingAccount(pointer->value1,pointer->value2,pointer->value3);
break;
}
else
{
cout << "There is no account in savings Account" << endl;
break;
}
break;
}
case 8:
{
cout << "Please enter the Account number: " << endl;
cin >> obj;
CheckingLL *pointer = chead;
if(checSearch(pointer,obj))
{
cout << "The existing transaction fee is " << pointer->value3 << endl;
break;
}
else
{
cout << "There is no account in savings Account" << endl;
break;
}
break;
}
case 9:
{
cout << "Please enter the Account number: " << endl;
cin >> obj;
CheckingLL *pointer = chead;
if(checSearch(pointer,obj))
{
cout << "The balance before the debit is " << ch1.getBal() << endl;
cout << "Please enter the amount to be debited: " << endl;
cin >> temp;
ch1.debit(temp);
pointer->value2 = ch1.accBal;
cout << "The balance after the debit along with the transaction fee is " << ch1.getBal() << endl;
break;
}
else
{
cout << "There is no account in checking Account" << endl;
break;
}
break;
}
case 10:
{
exit(1);
}
default:
{
cout << "\n Enter a valid choice, try again!\n";
}
}
}
return 0;
}
| 34.615665
| 132
| 0.38634
|
Hitesh1309
|
bdd9b4727c6c765ecb698174af543ead9964f6d3
| 44,660
|
cpp
|
C++
|
bark_editor/src/GUIContext.cpp
|
Daivuk/onut
|
b02c5969b36897813de9c574a26d9437b67f189e
|
[
"MIT"
] | 50
|
2015-06-01T19:23:24.000Z
|
2021-12-22T02:14:23.000Z
|
bark_editor/src/GUIContext.cpp
|
Daivuk/onut
|
b02c5969b36897813de9c574a26d9437b67f189e
|
[
"MIT"
] | 109
|
2015-07-20T07:43:03.000Z
|
2021-01-31T21:52:36.000Z
|
bark_editor/src/GUIContext.cpp
|
Daivuk/onut
|
b02c5969b36897813de9c574a26d9437b67f189e
|
[
"MIT"
] | 9
|
2015-07-02T21:36:20.000Z
|
2019-10-19T04:18:02.000Z
|
#include <sstream>
#include <iomanip>
#include <onut/ContentManager.h>
#include <onut/Input.h>
#include <onut/Log.h>
#include <onut/Font.h>
#include <onut/Renderer.h>
#include <onut/SpriteBatch.h>
#include <onut/Window.h>
#include <onut/Strings.h>
#include <onut/Texture.h>
#include <onut/TiledMap.h>
#include <onut/Sound.h>
#include <onut/SpriteAnim.h>
#include <onut/Model.h>
#include <onut/Shader.h>
#include "Script.h"
#include "GUIContext.h"
#include "globals.h"
#include "Theme.h"
static const float DRAG_DISTANCE = 3.0f;
static const float INT_DRAG_SENSITIVITY = 0.25f;
static const float FLOAT_DRAG_SENSITIVITY = 0.5f;
GUIContext::GUIContext()
{
oWindow->onWriteFunc = [this](onut::WriteFunc write_func)
{
if (edit_state != State::TextEditing) return;
switch (write_func)
{
case onut::WriteFunc::Backspace:
if (text_editing.selected_from == text_editing.selected_to) // Erase single character
{
if (text_editing.selected_from > 0) // Only if we're not at the beggining
{
text_editing.text.erase(onut::utf8Pos(text_editing.text, text_editing.selected_from - 1), 1);
text_editing.selected_from--;
text_editing.selected_to = text_editing.selected_from;
}
}
else if (!text_editing.text.empty()) // Erase selected section
{
text_editing.text =
text_editing.text.substr(0, onut::utf8Pos(text_editing.text, text_editing.selected_from)) +
text_editing.text.substr(onut::utf8Pos(text_editing.text, text_editing.selected_to), std::string::npos);
text_editing.selected_to = text_editing.selected_from;
}
break;
case onut::WriteFunc::CariageReturn:
text_editing.commited = true;
break;
case onut::WriteFunc::Escape:
edit_state = State::None;
break;
default:
break;
}
};
oWindow->onWriteUTF8 = [this](const std::string& text)
{
if (edit_state != State::TextEditing) return;
// Text insertion
text_editing.text =
text_editing.text.substr(0, onut::utf8Pos(text_editing.text, text_editing.selected_from)) +
text +
text_editing.text.substr(onut::utf8Pos(text_editing.text, text_editing.selected_to), std::string::npos);
text_editing.selected_from++;
text_editing.selected_to = text_editing.selected_from;
};
}
GUIContext::~GUIContext()
{
}
void GUIContext::update()
{
mouse = oInput->mousePosf;
id = 0;
left_button.down = OInputPressed(OMouse1);
left_button.just_down = OInputJustPressed(OMouse1);
left_button.clicked = OInputJustReleased(OMouse1);
left_button.double_clicked = oInput->getDoubleClicked();
if (left_button.double_clicked) left_button.down = false;
keys.ctrl = OInputPressed(OKeyLeftControl);
keys.shift = OInputPressed(OKeyLeftShift);
keys.alt = OInputPressed(OKeyLeftAlt);
keys.esc = OInputJustPressed(OKeyEscape);
keys.enter = OInputJustPressed(OKeyEnter) || OInputJustPressed(OKeyNumPadEnter);
keys.del = OInputJustPressed(OKeyDelete);
keys.left = OInputJustPressed(OKeyLeft);
keys.right = OInputJustPressed(OKeyRight);
keys.home = OInputJustPressed(OKeyHome);
keys.end = OInputJustPressed(OKeyEnd);
scrolling.amount = oInput->getStateValue(OMouseZ) * 0.5f;
if (left_button.just_down) down_id = 0;
if (OInputJustPressed(OMouse1)) down_pos = mouse;
if (left_button.down ||
left_button.clicked ||
left_button.double_clicked ||
scrolling.amount ||
keys.esc ||
keys.enter ||
keys.del ||
keys.left ||
keys.right) invalidate(); // Make sure we'll render the frame after
}
void GUIContext::reset()
{
left_button.clicked = false;
left_button.double_clicked = false;
left_button.just_down = false;
keys.esc = false;
keys.enter = false;
keys.del = false;
keys.left = false;
keys.right = false;
scrolling.amount = 0.0f;
id = 0;
}
void GUIContext::begin()
{
theme = g_theme;
sb = oSpriteBatch.get();
rect = ORectFullScreen.Grow(-theme->panel_margin);
r = oRenderer.get();
rs = &r->renderStates;
drag.type = eUIDrag::None;
saved_draw_point = 0;
cursor_type = eUICursorType::Arrow;
draw_calls.clear();
rect_stack.clear();
scissor_stack.clear();
enable_stack.clear();
}
void GUIContext::end()
{
sb->begin();
drawing_enable_state = true;
for (const auto& draw_call : draw_calls)
{
drawDrawCall(draw_call);
}
if (drag.type != eUIDrag::None)
{
drawing_enable_state = true;
auto diff = mouse - down_pos;
if (drag.type == eUIDrag::HSplit) diff.y = 0.0f;
if (drag.type == eUIDrag::VSplit) diff.x = 0.0f;
for (auto& draw_call : drag.draw_calls)
{
draw_call.color *= 0.65f;
draw_call.rect.x += diff.x;
draw_call.rect.y += diff.y;
draw_call.pos += diff;
drawDrawCall(draw_call);
}
}
sb->end();
switch (cursor_type)
{
case eUICursorType::Arrow: oInput->unsetMouseIcon(); break;
case eUICursorType::SizeEW: oInput->setMouseIcon("cur_size_ew.png", {9, 9}); break;
case eUICursorType::SizeNS: oInput->setMouseIcon("cur_size_ns.png", {9, 9}); break;
case eUICursorType::SizeNESW: oInput->setMouseIcon("cur_size_ne_sw.png", {9, 9}); break;
case eUICursorType::SizeNWSE: oInput->setMouseIcon("cur_size_nw_se.png", {9, 9}); break;
case eUICursorType::SizeAll: oInput->setMouseIcon("cur_size_all.png", {9, 9}); break;
case eUICursorType::RotN: oInput->setMouseIcon("cur_rot_n.png", {9, 9}); break;
case eUICursorType::RotNE: oInput->setMouseIcon("cur_rot_ne.png", {9, 9}); break;
case eUICursorType::RotE: oInput->setMouseIcon("cur_rot_e.png", {9, 9}); break;
case eUICursorType::RotSE: oInput->setMouseIcon("cur_rot_se.png", {9, 9}); break;
case eUICursorType::RotS: oInput->setMouseIcon("cur_rot_s.png", {9, 9}); break;
case eUICursorType::RotSW: oInput->setMouseIcon("cur_rot_sw.png", {9, 9}); break;
case eUICursorType::RotW: oInput->setMouseIcon("cur_rot_w.png", {9, 9}); break;
case eUICursorType::RotNW: oInput->setMouseIcon("cur_rot_nw.png", {9, 9}); break;
}
}
void GUIContext::drawDrawCall(const UIDrawCall& draw_call)
{
Color color = draw_call.color;
if (!drawing_enable_state) color = color.AdjustedSaturation(0.0f) * 0.5f;
switch (draw_call.type)
{
case eUIDrawCall::Outline:
sb->drawInnerOutlineRect(draw_call.rect, draw_call.thickness, color);
break;
case eUIDrawCall::Rect:
sb->drawRect(draw_call.texture, draw_call.rect, color);
break;
case eUIDrawCall::Text:
sb->drawText(draw_call.font, draw_call.text, draw_call.pos, draw_call.origin, color);
break;
case eUIDrawCall::Sprite:
sb->drawSprite(draw_call.texture, draw_call.pos, color, draw_call.origin);
break;
case eUIDrawCall::Slice9:
sb->drawRectScaled9(draw_call.texture, draw_call.rect, draw_call.padding, color);
break;
case eUIDrawCall::SetScissor:
sb->flush();
rs->scissorEnabled = true;
rs->scissor = iRect{
(int)draw_call.rect.x,
(int)draw_call.rect.y,
(int)(draw_call.rect.x + draw_call.rect.z),
(int)(draw_call.rect.y + draw_call.rect.w)};
break;
case eUIDrawCall::UnsetScissor:
sb->flush();
rs->scissorEnabled = false;
break;
case eUIDrawCall::SetEnableStyle:
drawing_enable_state = true;
break;
case eUIDrawCall::SetDisableStyle:
drawing_enable_state = false;
break;
}
}
void GUIContext::pushRect()
{
rect_stack.push_back(rect);
}
Rect GUIContext::popRect()
{
if (rect_stack.empty()) return rect;
rect = rect_stack.back();
rect_stack.pop_back();
return rect;
}
void GUIContext::pushScissor()
{
scissor_stack.push_back(rect);
auto draw_call = getNextDrawCall();
draw_call->type = eUIDrawCall::SetScissor;
draw_call->rect = rect;
}
Rect GUIContext::popScissor()
{
if (scissor_stack.empty()) return rect;
auto ret = scissor_stack.back();
scissor_stack.pop_back();
auto draw_call = getNextDrawCall();
if (scissor_stack.empty())
{
draw_call->type = eUIDrawCall::UnsetScissor;
}
else
{
draw_call->type = eUIDrawCall::SetScissor;
draw_call->rect = scissor_stack.back();
}
return ret;
}
void GUIContext::saveDrawPoint()
{
saved_draw_point = draw_calls.size();
}
void GUIContext::rewindDrawCalls()
{
draw_calls.resize(saved_draw_point);
}
UIDrawCall* GUIContext::getNextDrawCall()
{
draw_calls.push_back({});
return &draw_calls.back();
}
void GUIContext::drawOutline(const Rect& rect, float thickness, const Color& color)
{
auto draw_call = getNextDrawCall();
draw_call->type = eUIDrawCall::Outline;
draw_call->thickness = thickness;
draw_call->color = color;
draw_call->rect = rect;
}
void GUIContext::drawRect(const OTextureRef& texture, const Rect& rect, const Color& color)
{
auto draw_call = getNextDrawCall();
draw_call->texture = texture;
draw_call->type = eUIDrawCall::Rect;
draw_call->rect = rect;
draw_call->color = color;
}
void GUIContext::drawText(const OFontRef& font, const std::string& text, const Vector2& pos, const Vector2& origin, const Color& color)
{
auto draw_call = getNextDrawCall();
draw_call->type = eUIDrawCall::Text;
draw_call->font = font;
draw_call->text = text;
draw_call->pos = pos;
draw_call->origin = origin;
draw_call->color = color;
}
void GUIContext::drawSprite(const OTextureRef& texture, const Vector2& pos, const Color& color, const Vector2& origin)
{
auto draw_call = getNextDrawCall();
draw_call->type = eUIDrawCall::Sprite;
draw_call->texture = texture;
draw_call->pos = pos;
draw_call->color = color;
draw_call->origin = origin;
}
void GUIContext::drawSlice9(const OTextureRef& texture, const Rect& rect, const Vector4& padding, const Color& color)
{
auto draw_call = getNextDrawCall();
draw_call->type = eUIDrawCall::Slice9;
draw_call->texture = texture;
draw_call->rect = rect;
draw_call->padding = padding;
draw_call->color = color;
}
void GUIContext::drawPanel()
{
drawOutline(rect, theme->border_size, theme->panel_border_color);
drawRect(nullptr, rect.Grow(-theme->border_size), theme->panel_color);
}
eUIState GUIContext::drawHSplitHandle()
{
auto state = getState(rect);
if (state != eUIState::None)
{
drawSlice9(theme->scrollbar, Rect(rect.x, rect.y + rect.w * 0.4f, rect.z, rect.w * 0.2f), Vector4(4), theme->disabled_text_color);
cursor_type = eUICursorType::SizeEW;
}
if (state == eUIState::Drag)
{
drag.type = eUIDrag::HSplit;
drag.draw_calls.clear();
}
return state;
}
eUIState GUIContext::drawVSplitHandle()
{
auto state = getState(rect);
if (state != eUIState::None)
{
drawSlice9(theme->scrollbar, Rect(rect.x + rect.z * 0.4f, rect.y, rect.z * 0.2f, rect.w), Vector4(4), theme->disabled_text_color);
cursor_type = eUICursorType::SizeNS;
}
if (state == eUIState::Drag)
{
drag.type = eUIDrag::VSplit;
drag.draw_calls.clear();
}
return state;
}
eUIState GUIContext::drawTab(const std::string& name, float& offset,
const Color& color, const Color& border_color,
const Color& text_colors, bool close_btn)
{
auto tab_draw_point = draw_calls.size();
auto text_size = theme->font->measure(name);
auto width = text_size.x + theme->tab_padding * 2.0f;
auto full_width = width + (close_btn ? (16.0f + theme->tab_padding) : 0.0f);
auto tab_rect = rect;
tab_rect.x += offset;
tab_rect.z = full_width;
tab_rect.w++;
drawRect(nullptr, tab_rect, border_color);
tab_rect = tab_rect.Grow(-theme->border_size);
tab_rect.w += theme->border_size;
drawRect(nullptr, tab_rect, color);
auto state = getState(tab_rect);
auto text_rect = tab_rect;
text_rect.z = width - theme->border_size * 2.0f;
drawText(theme->font, name, text_rect.Center(), OCenter, text_colors);
offset += full_width + theme->tab_spacing;
if (close_btn)
{
if (drawToolButton(theme->x_icon, tab_rect.Right() - Vector2(16.0f + theme->tab_padding, 7.0f)))
{
left_button.clicked = false; // Necessary?
return eUIState::Close;
}
}
if (state == eUIState::Drag)
{
drag.type = eUIDrag::Tab;
drag.draw_calls.assign(draw_calls.begin() + tab_draw_point, draw_calls.end());
}
return state;
}
eUIState GUIContext::drawActiveTab(const std::string& name, float& offset, bool close_btn)
{
return drawTab(name, offset, theme->panel_color, theme->panel_border_color, theme->text_color, close_btn);
}
eUIState GUIContext::drawInactiveTab(const std::string& name, float& offset, bool close_btn)
{
return drawTab(name, offset, theme->inactive_tab_color, theme->window_color, theme->disabled_text_color, close_btn);
}
void GUIContext::drawArea()
{
drawOutline(rect, theme->border_size, theme->area_border_color);
drawRect(nullptr, rect.Grow(-theme->border_size), theme->area_color);
}
eUIState GUIContext::getState(const Rect& in_rect)
{
++id;
if (!isEnabled()) return eUIState::None;
eUIState ret = eUIState::None;
auto rect = in_rect;
if (!scissor_stack.empty())
{
const auto& scissor_rect = scissor_stack.back();
if (!scissor_rect.Overlaps(rect)) return ret; // No need to check further
rect = scissor_rect.Difference(rect);
}
bool is_mouse_hover = rect.Contains(mouse);
if (left_button.just_down && is_mouse_hover)
{
down_id = id;
if (edit_state == State::TextEditing && id != editing_control) text_editing.commited = true;
}
if (left_button.double_clicked && id == down_id)
{
if (is_mouse_hover)
{
ret = eUIState::DoubleClicked;
}
}
else if (left_button.clicked && id == down_id)
{
if (is_mouse_hover)
{
ret = eUIState::Clicked;
}
else
{
ret = eUIState::Drop;
}
}
else if (left_button.down)
{
if (id == down_id)
{
if (is_mouse_hover)
{
ret = eUIState::Down;
}
else if (Vector2::Distance(down_pos, mouse) > DRAG_DISTANCE)
{
ret = eUIState::Drag;
}
else
{
ret = eUIState::Hover;
}
}
}
else if (is_mouse_hover)
{
ret = eUIState::Hover;
}
return ret;
}
const Color& GUIContext::colorForState(eUIState state, Color** colors)
{
switch (state)
{
case eUIState::Hover: return *colors[1];
case eUIState::Down: return *colors[2];
default: return *colors[0];
}
}
bool GUIContext::drawToolButton(const OTextureRef& icon, const Vector2& pos)
{
Rect btn_rect(pos, theme->tool_button_size, theme->tool_button_size);
auto state = getState(btn_rect);
drawSprite(icon, pos, colorForState(state, theme->tool_button_colors), OTopLeft);
return state == eUIState::Clicked;
}
eUIState GUIContext::drawListItem(const std::string& text, const OTextureRef& icon, int indent, bool enabled, bool selected)
{
auto state = getState(rect);
Vector2 left(rect.x + theme->tree_indent * (float)indent, rect.y + rect.w * 0.5f);
if (selected)
{
drawRect(nullptr, rect, theme->dock_color);
}
else if (state == eUIState::Hover || state == eUIState::Down)
{
drawRect(nullptr, rect, theme->disabled_control_border_color);
}
if (icon)
{
drawSprite(icon, left, enabled ? Color::White : theme->disabled_tint, OLeft);
drawText(theme->font, text, left + Vector2(18.0f, -1.0f), OLeft, enabled ? theme->text_color : theme->disabled_text_color);
}
else
{
drawText(theme->font, text, left + Vector2(0.0f, -1.0f), OLeft, enabled ? theme->text_color : theme->disabled_text_color);
}
return state;
}
void GUIContext::beginVScrollArea(float scroll_amount)
{
scrolling.v_view_size = rect.w;
pushRect();
pushScissor();
rect = rect.Grow(-theme->panel_padding);
rect.y -= scroll_amount;
scrolling.v_content_start = rect.y;
}
void GUIContext::endVScrollArea(float* scroll_amount)
{
scrolling.v_content_size = (rect.y + rect.w) - scrolling.v_content_start;
popScissor();
popRect();
vScroll(scroll_amount);
}
bool GUIContext::vScroll(float* amount)
{
if (!rect.Contains(mouse)) return false;
auto prev_value = *amount;
auto new_value = prev_value;
auto max_scroll = std::max(0.0f, scrolling.v_content_size - scrolling.v_view_size);
new_value -= scrolling.amount;
scrolling.amount = 0.0f;
new_value = std::min(max_scroll, new_value);
new_value = std::max(0.0f, new_value);
*amount = new_value;
return prev_value != new_value;
}
bool GUIContext::isEnabled()
{
if (enable_stack.empty()) return true;
return enable_stack.back();
}
void GUIContext::pushEnableState(bool enabled)
{
auto was_enabled = isEnabled();
enable_stack.push_back(enabled);
if (was_enabled && !enabled)
{
UIDrawCall draw_call;
draw_call.type = eUIDrawCall::SetDisableStyle;
draw_calls.push_back(draw_call);
}
else if (!was_enabled && enabled)
{
UIDrawCall draw_call;
draw_call.type = eUIDrawCall::SetEnableStyle;
draw_calls.push_back(draw_call);
}
}
void GUIContext::popEnableState()
{
auto was_enabled = isEnabled();
if (!enable_stack.empty()) enable_stack.pop_back();
auto enabled = isEnabled();
if (was_enabled && !enabled)
{
UIDrawCall draw_call;
draw_call.type = eUIDrawCall::SetDisableStyle;
draw_calls.push_back(draw_call);
}
else if (!was_enabled && enabled)
{
UIDrawCall draw_call;
draw_call.type = eUIDrawCall::SetEnableStyle;
draw_calls.push_back(draw_call);
}
}
static int getNextWordPos(const std::string& str, int cur_pos)
{
auto len = (int)onut::utf8Length(str);
cur_pos = std::min(cur_pos + 1, len);
if (cur_pos == len) return cur_pos;
//TODO
return cur_pos;
}
static int getPrevWordPos(const std::string& str, int cur_pos)
{
auto len = (int)onut::utf8Length(str);
cur_pos = std::min(cur_pos + 1, len);
if (cur_pos == len) return cur_pos;
//TODO
return cur_pos;
}
bool GUIContext::drawEditingText(std::string* value, eUIState state)
{
bool ret = false;
if (editing_control == id && edit_state == State::TextEditing)
{
if (state == eUIState::None && left_button.just_down)
{
text_editing.commited = true;
}
if (text_editing.commited)
{
edit_state = State::None;
ret = *value != text_editing.text;
*value = text_editing.text;
}
else if (keys.left)
{
if (keys.shift) // Range select
{
if (text_editing.select_range_at_start)
{
if (text_editing.selected_from > 0)
{
if (keys.ctrl) // Jump words
{
}
else text_editing.selected_from--;
}
}
else
{
if (text_editing.selected_to > text_editing.selected_from)
{
if (keys.ctrl) // Jump words
{
}
else text_editing.selected_to--;
}
else
{
text_editing.select_range_at_start = true;
if (text_editing.selected_from > 0)
{
if (keys.ctrl) // Jump words
{
}
else text_editing.selected_from--;
}
}
}
}
else // Just move cursor
{
text_editing.select_range_at_start = true;
if (text_editing.selected_to == text_editing.selected_from)
{
if (text_editing.selected_from > 0)
{
if (keys.ctrl) // Jump words
{
}
else text_editing.selected_from--;
text_editing.selected_to = text_editing.selected_from;
}
}
else // Move cursor at start, remove range selection
{
text_editing.selected_to = text_editing.selected_from;
}
}
}
else if (keys.right)
{
if (keys.shift) // Range select
{
if (text_editing.select_range_at_start)
{
if (text_editing.selected_from < text_editing.selected_to)
{
if (keys.ctrl) // Jump words
{
}
else text_editing.selected_from++;
}
else
{
text_editing.select_range_at_start = false;
if (text_editing.selected_to < (int)onut::utf8Length(text_editing.text))
{
if (keys.ctrl) // Jump words
{
}
else text_editing.selected_to++;
}
}
}
else
{
if (text_editing.selected_to < (int)onut::utf8Length(text_editing.text))
{
if (keys.ctrl) // Jump words
{
}
else text_editing.selected_to++;
}
}
}
else // Just move cursor
{
text_editing.select_range_at_start = true;
if (text_editing.selected_to == text_editing.selected_from)
{
if (text_editing.selected_to < (int)onut::utf8Length(text_editing.text))
{
if (keys.ctrl) // Jump words
{
}
else text_editing.selected_to++;
text_editing.selected_from = text_editing.selected_to;
}
}
else // Move cursor at end, remove range selection
{
text_editing.selected_from = text_editing.selected_to;
}
}
}
else if (keys.home)
{
text_editing.selected_from = 0;
text_editing.select_range_at_start = true;
if (!keys.shift) // Range select
{
text_editing.selected_to = text_editing.selected_from;
}
}
else if (keys.end)
{
text_editing.selected_to = (int)onut::utf8Length(text_editing.text);
text_editing.select_range_at_start = false;
if (!keys.shift) // Range select
{
text_editing.selected_from = text_editing.selected_to;
}
}
else if (keys.del)
{
if (text_editing.selected_from == text_editing.selected_to) // Erase single character
{
if (text_editing.selected_from < onut::utf8Length(text_editing.text)) // Only if we're not at the beggining
{
text_editing.text.erase(onut::utf8Pos(text_editing.text, text_editing.selected_from), 1);
}
}
else if (!text_editing.text.empty()) // Erase selected section
{
text_editing.text =
text_editing.text.substr(0, onut::utf8Pos(text_editing.text, text_editing.selected_from)) +
text_editing.text.substr(onut::utf8Pos(text_editing.text, text_editing.selected_to), std::string::npos);
text_editing.selected_to = text_editing.selected_from;
}
}
}
if (edit_state == State::TextEditing && editing_control == id)
{
// Selection/Cursor
auto text_start = theme->font->measure(text_editing.text.substr(0, onut::utf8Pos(text_editing.text, text_editing.selected_from)));
auto text_end = theme->font->measure(text_editing.text.substr(0, onut::utf8Pos(text_editing.text, text_editing.selected_to)));
drawRect(nullptr, Rect(rect.x + text_start.x - 1.0f, rect.y, text_end.x - text_start.x + 2.0f, rect.w), theme->active_color);
drawText(theme->font, text_editing.text, rect.Left(), OLeft, theme->text_color);
}
else
{
drawText(theme->font, *value, rect.Left(), OLeft, theme->text_color);
}
bool is_editing_this_field = (edit_state == State::TextEditing && editing_control == id);
if (state == eUIState::Clicked && !is_editing_this_field)
{
edit_state = State::TextEditing;
editing_control = id;
text_editing.text = *value;
text_editing.selected_from = 0;
text_editing.selected_to = std::max(text_editing.selected_from, (int)onut::utf8Length(text_editing.text));
text_editing.select_range_at_start = false;
text_editing.commited = false;
}
else if (state == eUIState::DoubleClicked && is_editing_this_field)
{
text_editing.selected_from = 0;
text_editing.selected_to = std::max(text_editing.selected_from, (int)onut::utf8Length(text_editing.text));
text_editing.select_range_at_start = false;
}
else if (state == eUIState::Down && is_editing_this_field)
{
if (left_button.just_down)
{
if (keys.shift)
{
auto pos = (int)theme->font->caretPos(text_editing.text, mouse.x - rect.x);
if (text_editing.select_range_at_start)
{
text_editing.selected_from = pos;
if (text_editing.selected_from > text_editing.selected_to)
{
text_editing.select_range_at_start = false;
std::swap(text_editing.selected_from, text_editing.selected_to);
}
}
else
{
text_editing.selected_to = pos;
if (text_editing.selected_to < text_editing.selected_from)
{
text_editing.select_range_at_start = true;
std::swap(text_editing.selected_from, text_editing.selected_to);
}
}
}
else
{
text_editing.selected_from = (int)theme->font->caretPos(text_editing.text, mouse.x - rect.x);
text_editing.selected_to = text_editing.selected_from;
}
}
else
{
auto pos = (int)theme->font->caretPos(text_editing.text, mouse.x - rect.x);
if (text_editing.select_range_at_start)
{
text_editing.selected_from = pos;
if (text_editing.selected_from > text_editing.selected_to)
{
text_editing.select_range_at_start = false;
std::swap(text_editing.selected_from, text_editing.selected_to);
}
}
else
{
text_editing.selected_to = pos;
if (text_editing.selected_to < text_editing.selected_from)
{
text_editing.select_range_at_start = true;
std::swap(text_editing.selected_from, text_editing.selected_to);
}
}
}
}
return ret;
}
void GUIContext::indent()
{
rect.x += theme->tree_indent;
rect.z -= theme->tree_indent;
}
void GUIContext::unindent()
{
rect.x -= theme->tree_indent;
rect.z += theme->tree_indent;
}
void GUIContext::drawControl()
{
drawRect(nullptr, rect, theme->control_border_color);
drawRect(nullptr, rect.Grow(-theme->border_size), theme->dark_color);
}
bool GUIContext::drawBoolControl(bool* value)
{
auto state = getState(rect);
bool changed = false;
if (state == eUIState::Clicked)
{
*value = !*value;
changed = true;
}
//drawControl();
drawRect(nullptr, rect, theme->control_border_color);
drawRect(nullptr, rect.Grow(-theme->border_size), theme->dark_color);
if (*value)
{
auto r = rect.Grow(-theme->border_size * 2.0f);
r.x += r.z - r.w;
r.z = r.w;
drawRect(nullptr, r, theme->active_color);
}
else
{
auto r = rect.Grow(-theme->border_size * 2.0f);
r.z = r.w;
drawRect(nullptr, r, theme->area_color);
}
return changed;
}
bool GUIContext::drawIntControl(int* value)
{
bool ret = false;
auto state = getState(rect);
if (state == eUIState::Down && left_button.just_down)
{
int_editing.start_value = *value;
}
if (state == eUIState::Drag)
{
edit_state = State::IntDragging;
editing_control = id;
}
if (edit_state == State::IntDragging && editing_control == id)
{
auto diff = mouse.y - down_pos.y;
if (diff < 0) diff = std::min(0.0f, diff + DRAG_DISTANCE);
else if (diff > 0) diff = std::max(0.0f, diff - DRAG_DISTANCE);
int_editing.value = int_editing.start_value - (int)(diff * INT_DRAG_SENSITIVITY);
*value = int_editing.value;
if (!left_button.down)
{
ret = int_editing.value != int_editing.start_value;
edit_state = State::None;
}
}
drawRect(nullptr, rect, theme->area_border_color);
pushRect();
rect = rect.Grow(-theme->border_size);
pushScissor();
drawRect(nullptr, rect, theme->control_border_color);
rect.x += theme->control_padding;
rect.z -= theme->control_padding * 2.0f;
auto str_value = std::to_string(*value);
if (edit_state == State::IntDragging && editing_control == id)
{
str_value = std::to_string(int_editing.value);
}
auto text_edit_changed = drawEditingText(&str_value, state);
if (text_edit_changed)
{
try
{
*value = std::stoi(str_value);
ret = true;
}
catch (...)
{
ret = false;
}
}
popScissor();
popRect();
return ret;
}
bool GUIContext::drawFloatControl(float* value, float step)
{
bool ret = false;
auto state = getState(rect);
if (state == eUIState::Down && left_button.just_down)
{
float_editing.start_value = *value;
}
if (state == eUIState::Drag)
{
edit_state = State::FloatDragging;
editing_control = id;
}
if (edit_state == State::FloatDragging && editing_control == id)
{
auto diff = mouse.y - down_pos.y;
if (diff < 0) diff = std::min(0.0f, diff + DRAG_DISTANCE);
else if (diff > 0) diff = std::max(0.0f, diff - DRAG_DISTANCE);
float_editing.value = float_editing.start_value - ((float)(int)(diff * FLOAT_DRAG_SENSITIVITY)) * step;
*value = float_editing.value;
if (!left_button.down)
{
ret = float_editing.value != float_editing.start_value;
edit_state = State::None;
}
}
drawRect(nullptr, rect, theme->area_border_color);
pushRect();
rect = rect.Grow(-theme->border_size);
pushScissor();
drawRect(nullptr, rect, theme->control_border_color);
rect.x += theme->control_padding;
rect.z -= theme->control_padding * 2.0f;
auto val = *value;
if (edit_state == State::FloatDragging && editing_control == id)
{
val = float_editing.value;
}
std::stringstream ss;
ss << val;
auto str_value = ss.str();
//auto s = str_value.find_last_not_of("0");
//str_value = str_value.substr(0, s + 1);
auto text_edit_changed = drawEditingText(&str_value, state);
if (text_edit_changed)
{
try
{
*value = std::stof(str_value);
ret = true;
}
catch (...)
{
ret = false;
}
}
popScissor();
popRect();
return ret;
}
bool GUIContext::drawTextControl(std::string* value)
{
auto state = getState(rect);
bool ret = false;
drawRect(nullptr, rect, theme->area_border_color);
pushRect();
rect = rect.Grow(-theme->border_size);
pushScissor();
drawRect(nullptr, rect, theme->control_border_color);
rect.x += theme->control_padding;
rect.z -= theme->control_padding * 2.0f;
ret |= drawEditingText(value, state);
popScissor();
popRect();
return ret;
}
bool GUIContext::bool_prop(bool* value, const std::string& label, const std::string& tooltip)
{
// Standard control height
rect.w = theme->control_height - 1;
pushRect();
// Content
drawText(theme->font, label, rect.Left(), OLeft, theme->text_color);
auto h = theme->bool_control_width * 0.5f;
rect.x = rect.x + rect.z - theme->bool_control_width;
rect.z = theme->bool_control_width;
rect.y += (rect.w - h) * 0.5f;
rect.w -= (rect.w - h);
auto changed = drawBoolControl(value);
// Advance for next control
popRect();
rect.y += theme->control_height + theme->control_spacing;
return changed;
}
bool GUIContext::int_prop(int* value, const std::string& label, const std::string& tooltip)
{
bool changed = false;
// Standard control height
rect.w = theme->control_height - 1;
pushRect();
// Content
drawText(theme->font, label, rect.Left(), OLeft, theme->text_color);
rect.x = rect.x + rect.z - theme->numeric_control_width;
rect.z = theme->numeric_control_width;
changed |= drawIntControl(value);
// Advance for next control
popRect();
rect.y += theme->control_height + theme->control_spacing;
return changed;
}
bool GUIContext::float_prop(float* value, const std::string& label, const std::string& tooltip)
{
bool changed = false;
// Standard control height
rect.w = theme->control_height - 1;
pushRect();
// Content
drawText(theme->font, label, rect.Left(), OLeft, theme->text_color);
rect.x = rect.x + rect.z - theme->numeric_control_width;
rect.z = theme->numeric_control_width;
changed |= drawFloatControl(value);
// Advance for next control
popRect();
rect.y += theme->control_height + theme->control_spacing;
return changed;
}
bool GUIContext::Point_prop(Point* value, const std::string& label, const std::string& tooltip)
{
// Standard control height
rect.w = theme->control_height - 1;
pushRect();
// Content
drawText(theme->font, label, rect.Left(), OLeft, theme->text_color);
bool changed = false;
{
rect.x = rect.x + rect.z - theme->numeric_control_width * 2.0f - theme->control_margin;
rect.z = theme->numeric_control_width;
changed |= drawIntControl(&value->x);
}
{
rect.x += theme->numeric_control_width + theme->control_margin;
changed |= drawIntControl(&value->y);
}
// Advance for next control
popRect();
rect.y += theme->control_height + theme->control_spacing;
return changed;
}
bool GUIContext::Vector2_prop(Vector2* value, const std::string& label, const std::string& tooltip)
{
// Standard control height
rect.w = theme->control_height - 1;
pushRect();
// Content
drawText(theme->font, label, rect.Left(), OLeft, theme->text_color);
bool changed = false;
{
rect.x = rect.x + rect.z - theme->numeric_control_width * 2.0f - theme->control_margin;
rect.z = theme->numeric_control_width;
changed |= drawFloatControl(&value->x);
}
{
rect.x += theme->numeric_control_width + theme->control_margin;
changed |= drawFloatControl(&value->y);
}
// Advance for next control
popRect();
rect.y += theme->control_height + theme->control_spacing;
return changed;
}
bool GUIContext::Vector3_prop(Vector3* value, const std::string& label, const std::string& tooltip)
{
// Standard control height
rect.w = theme->control_height - 1;
pushRect();
// Content
drawText(theme->font, label, rect.Left(), OLeft, theme->text_color);
bool changed = false;
{
rect.x = rect.x + rect.z - theme->numeric_control_width * 3.0f - theme->control_margin * 2.0f;
rect.z = theme->numeric_control_width;
changed |= drawFloatControl(&value->x);
}
{
rect.x += theme->numeric_control_width + theme->control_margin;
changed |= drawFloatControl(&value->y);
}
{
rect.x += theme->numeric_control_width + theme->control_margin;
changed |= drawFloatControl(&value->z);
}
// Advance for next control
popRect();
rect.y += theme->control_height + theme->control_spacing;
return changed;
}
bool GUIContext::Vector4_prop(Vector4* value, const std::string& label, const std::string& tooltip)
{
// Standard control height
rect.w = theme->control_height - 1;
pushRect();
// Content
drawText(theme->font, label, rect.Left(), OLeft, theme->text_color);
bool changed = false;
{
rect.x = rect.x + rect.z - theme->numeric_control_width * 4.0f - theme->control_margin * 3.0f;
rect.z = theme->numeric_control_width;
changed |= drawFloatControl(&value->x);
}
{
rect.x += theme->numeric_control_width + theme->control_margin;
changed |= drawFloatControl(&value->y);
}
{
rect.x += theme->numeric_control_width + theme->control_margin;
changed |= drawFloatControl(&value->z);
}
{
rect.x += theme->numeric_control_width + theme->control_margin;
changed |= drawFloatControl(&value->w);
}
// Advance for next control
popRect();
rect.y += theme->control_height + theme->control_spacing;
return changed;
}
bool GUIContext::Color_prop(Color* value, const std::string& label, const std::string& tooltip)
{
// Standard control height
rect.w = theme->control_height - 1;
pushRect();
// Content
drawText(theme->font, label, rect.Left(), OLeft, theme->text_color);
bool changed = false;
{
rect.x = rect.x + rect.z - theme->numeric_control_width * 4.0f - theme->control_margin * 3.0f;
rect.z = theme->numeric_control_width;
changed |= drawFloatControl(&value->r, 1.0f / 255.0f);
}
{
rect.x += theme->numeric_control_width + theme->control_margin;
changed |= drawFloatControl(&value->g, 1.0f / 255.0f);
}
{
rect.x += theme->numeric_control_width + theme->control_margin;
changed |= drawFloatControl(&value->b, 1.0f / 255.0f);
}
{
rect.x += theme->numeric_control_width + theme->control_margin;
changed |= drawFloatControl(&value->a, 1.0f / 255.0f);
}
// Advance for next control
popRect();
rect.y += theme->control_height + theme->control_spacing;
return changed;
}
bool GUIContext::std_string_prop(std::string* value, const std::string& label, const std::string& tooltip)
{
// Standard control height
rect.w = theme->control_height - 1;
pushRect();
// Content
drawText(theme->font, label, rect.Left(), OLeft, theme->text_color);
rect.x = rect.x + rect.z - theme->text_control_width;
rect.z = theme->text_control_width;
auto changed = drawTextControl(value);
// Advance for next control
popRect();
rect.y += theme->control_height + theme->control_spacing;
return changed;
}
bool GUIContext::header(const std::string& text, bool* expanded)
{
rect.y += (theme->control_height - theme->header_height) * 0.5f;
auto adjusted_rect = rect;
adjusted_rect.x -= theme->control_padding;
adjusted_rect.z += theme->control_padding * 2.0f;
adjusted_rect.w = theme->header_height;
auto state = getState(adjusted_rect);
if (state == eUIState::Clicked && expanded)
{
*expanded = !*expanded;
}
drawRect(nullptr, adjusted_rect, theme->header_color);
drawText(theme->font, text, adjusted_rect.Center(), OCenter, colorForState(state, theme->text_colors));
if (!expanded || *expanded)
{
drawSprite(theme->asset_icons[(int)eAssetType::ExpandedFolder], adjusted_rect.Left(), Color::White, OLeft);
}
else
{
drawSprite(theme->asset_icons[(int)eAssetType::Folder], adjusted_rect.Left(), Color::White, OLeft);
}
rect.y += theme->header_height + theme->control_spacing;
return expanded ? *expanded : true;
}
#define RESOURCE_PROP(__type__) \
std::string name = *value ? value->get()->getName() : "-- NULL --"; \
if (std_string_prop(&name, label)) \
{ \
*value = g_content_mgr->getResourceAs<__type__>(name); \
changed |= true; \
}
bool GUIContext::OTextureRef_prop(OTextureRef* value, const std::string& label, const std::string& tooltip)
{
bool changed = false;
RESOURCE_PROP(OTexture);
return changed;
}
bool GUIContext::OTiledMapRef_prop(OTiledMapRef* value, const std::string& label, const std::string& tooltip)
{
bool changed = false;
RESOURCE_PROP(OTiledMap);
return changed;
}
bool GUIContext::OSoundRef_prop(OSoundRef* value, const std::string& label, const std::string& tooltip)
{
bool changed = false;
RESOURCE_PROP(OSound);
return changed;
}
bool GUIContext::OSpriteAnimRef_prop(OSpriteAnimRef* value, const std::string& label, const std::string& tooltip)
{
bool changed = false;
RESOURCE_PROP(OSpriteAnim);
return changed;
}
bool GUIContext::OModelRef_prop(OModelRef* value, const std::string& label, const std::string& tooltip)
{
bool changed = false;
RESOURCE_PROP(OModel);
return changed;
}
bool GUIContext::OShaderRef_prop(OShaderRef* value, const std::string& label, const std::string& tooltip)
{
bool changed = false;
RESOURCE_PROP(OShader);
return changed;
}
bool GUIContext::ScriptRef_prop(ScriptRef* value, const std::string& label, const std::string& tooltip)
{
bool changed = false;
RESOURCE_PROP(Script);
return changed;
}
| 30.236967
| 138
| 0.582871
|
Daivuk
|
bde2cdb1ff29141bd8a61024ac8e32ff7e8cb2b2
| 11,550
|
hpp
|
C++
|
lib/player.hpp
|
SailGame/ExplodingKittens
|
0bf2fa3d57accaef1e049122956b57b93a0cc810
|
[
"MIT"
] | null | null | null |
lib/player.hpp
|
SailGame/ExplodingKittens
|
0bf2fa3d57accaef1e049122956b57b93a0cc810
|
[
"MIT"
] | null | null | null |
lib/player.hpp
|
SailGame/ExplodingKittens
|
0bf2fa3d57accaef1e049122956b57b93a0cc810
|
[
"MIT"
] | null | null | null |
#pragma once
#include <algorithm>
#include <boost/mpl/vector.hpp>
#include <boost/msm/back/state_machine.hpp>
#include <boost/msm/front/euml/common.hpp>
#include <boost/msm/front/euml/operator.hpp>
#include <boost/msm/front/functor_row.hpp>
#include <boost/msm/front/state_machine_def.hpp>
#include <iostream>
#include <list>
#include <map>
#include <vector>
#include "card_pool.hpp"
namespace mpl = boost::mpl;
namespace msm = boost::msm;
using namespace msm::front;
using namespace msm::front::euml;
namespace ExplodingKittens {
class Game;
struct Player_;
typedef msm::back::state_machine<Player_> Player;
// events
struct PlayCardSkip {
CardType Card{Skip};
};
struct PlayCardShirk {
CardType Card{Shirk};
int TargetUid{0};
PlayCardShirk(int targetUid) : TargetUid(targetUid) {}
};
struct PlayCardReverse {
CardType Card{Reverse};
};
struct PlayCardPredict {
CardType Card{Predict};
};
struct PlayCardSeeThrough {
CardType Card{SeeThrough};
};
struct PlayCardSwap {
CardType Card{Swap};
int TargetUid{0};
PlayCardSwap(int targetUid) : TargetUid(targetUid) {}
};
struct PlayCardGetBottom {
CardType Card{GetBottom};
};
struct PlayCardShuffle {
CardType Card{Shuffle};
};
struct PlayCardExtort {
CardType Card{Extort};
int TargetUid{0};
};
struct PlayCardBombDisposal {
CardType Card{BombDisposal};
int pos{1};
PlayCardBombDisposal(int pos) : pos(pos) {}
};
struct SelectExtortCard {
int SrcUid{0};
int TargetUid{0};
};
struct GetExtortCard {};
struct EventMyTurn {};
struct DrawCard {};
struct AskExtortCard {
int ExtortSrcUid{0};
AskExtortCard(int srcid) : ExtortSrcUid(srcid) {}
};
struct ExtortCardSelected {
CardType Card{Bomb};
};
// flags
struct Exploded {};
struct Player_ : public msm::front::state_machine_def<Player_> {
Player_(int uid, Game &game) : mUid(uid), mGame(game) {}
// entry and exit of state: log
template <class Event, class FSM>
void on_entry(Event const &, FSM &) {
std::cout << "entering: Player" << std::endl;
}
template <class Event, class FSM>
void on_exit(Event const &, FSM &) {
std::cout << "leaving: Player" << std::endl;
}
// The list of FSM states
struct Exploding : public msm::front::state<> {};
struct Stopped : public msm::front::state<> {};
struct Playing : public msm::front::state<> {};
struct Extorted : public msm::front::state<> {
int ExtortSrcUId{0};
};
struct Died : public msm::front::state<> {
typedef mpl::vector1<Exploded> flag_list;
};
// the initial state of the player SM. Must be defined
typedef Stopped initial_state;
// transition actions
// you can reuse them in another machine if you wish
#define action \
template <class EVT, class FSM, class SourceState, class TargetState> \
void operator()(EVT const &evt, FSM &fsm, SourceState &sstate, \
TargetState &tstate)
struct RoundStart {
action {
// TODO: tell user round start
}
};
struct EndOfTurn {
action {
auto pos =
std::find(fsm.mCards.begin(), fsm.mCards.end(), evt.Card);
fsm.mCards.erase(pos);
fsm.mGame.NextPlayer();
// TODO: tell user end of the turn
}
};
struct ShirkItself {
action {
auto pos =
std::find(fsm.mCards.begin(), fsm.mCards.end(), evt.Card);
fsm.mCards.erase(pos);
// TODO: tell user shirked
}
};
struct ShirkOther {
action {
auto pos =
std::find(fsm.mCards.begin(), fsm.mCards.end(), evt.Card);
fsm.mCards.erase(pos);
for (int i = 0; i < fsm.mGame.mPlayers.size(); ++i) {
if (fsm.mGame.mPlayers[i].mUid == evt.TargetUid) {
fsm.mGame.mPlayingPlayerPos = i;
fsm.mGame.mPlayers[i].process_event(EventMyTurn());
// TODO: tell user shirked
}
}
}
};
struct Reverse {
action {
auto pos =
std::find(fsm.mCards.begin(), fsm.mCards.end(), evt.Card);
fsm.mCards.erase(pos);
fsm.mGame.mClockwise = !fsm.mGame.mClockwise;
fsm.mGame.NextPlayer();
// TODO: tell user end of the turn
}
};
struct SeeThrough {
action {
auto pos =
std::find(fsm.mCards.begin(), fsm.mCards.end(), evt.Card);
fsm.mCards.erase(pos);
// TODO: tell user the first three cards
}
};
struct Predict {
action {
auto pos =
std::find(fsm.mCards.begin(), fsm.mCards.end(), evt.Card);
fsm.mCards.erase(pos);
// TODO: tell user the pos of the first bomb
}
};
struct Swap {
action {
auto pos =
std::find(fsm.mCards.begin(), fsm.mCards.end(), evt.Card);
fsm.mCards.erase(pos);
for (auto &player : fsm.mGame.mPlayers) {
if (player.mUid == evt.TargetUid)
swap(fsm.mCards, player.mCards);
// TODO: tell two user current cards
}
}
};
struct GetBottom {
action {
auto pos =
std::find(fsm.mCards.begin(), fsm.mCards.end(), evt.Card);
fsm.mCards.erase(pos);
fsm.mCards.push_back(fsm.mGame.mCardPool.Back());
fsm.mGame.mCardPool.PopBack();
// TODO: tell use current cards
fsm.mGame.NextPlayer();
}
};
struct GetBottomBomb {
action {
auto pos =
std::find(fsm.mCards.begin(), fsm.mCards.end(), evt.Card);
fsm.mCards.erase(pos);
fsm.mGame.mCardPool.PopBack();
// TODO: tell use get bottom bomb
}
};
struct Shuffle {
action {
auto pos =
std::find(fsm.mCards.begin(), fsm.mCards.end(), evt.Card);
fsm.mCards.erase(pos);
fsm.mGame.mCardPool.ShuffleCards();
}
};
struct HandleExploding {
action {
auto pos =
std::find(fsm.mCards.begin(), fsm.mCards.end(), evt.Card);
fsm.mCards.erase(pos);
fsm.mGame.mCardPool.PutBackBomb(evt.pos);
// TODO: limit the position
fsm.mGame.NextPlayer();
}
};
struct StoreCard {
action {
fsm.mCards.push_back(fsm.mGame.mCardPool.Front());
fsm.mGame.mCardPool.PopFront();
fsm.mGame.NextPlayer();
}
};
struct SelectExtortTarget {
action {
for (auto &player : fsm.mGame.mPlayers) {
if (player.mUid == evt.TargetUid)
player.process_on(AskExtortCard(fsm.mUid));
}
}
};
struct AskExtortCard {
action {
tstate.ExtortSrcUId = evt.ExtortSrcUid;
// TODO: ask user to give an card
}
};
struct ExtortCardSelected {
action {
for (auto player : fsm.mGame.mPlayers) {
if (player.mUid == sstate.ExtortSrcUid) {
player.process_event(GetExtortCard(evt.Card));
}
}
}
};
#undef action
#define guard \
template <class EVT, class FSM, class SourceState, class TargetState> \
bool operator()(EVT const &evt, FSM &fsm, SourceState &sstate, \
TargetState &tstate)
// guard conditions
struct DoesCardExist {
guard {
return std::find(fsm.mCards.begin(), fsm.mCards.end(), evt.Card) !=
fsm.mCards.end();
}
};
struct IsShirkTarget {
guard { return evt.TargetUid == fsm.mUid; }
};
struct IsFrontBomb {
guard { return fsm.mGame.mCardPool.Front() == Bomb; }
};
struct IsBackBomb {
guard { return fsm.mGame.mCardPool.Back() == Bomb; }
};
struct IsExtortTarget {
guard { return evt.TatgetUid == fsm.mUid; }
};
struct IsTargetAlive {
guard {
for (auto player : fsm.mGame.mPlayers) {
if (player.mUid == evt.TargetUid) return true;
}
return false;
}
};
#undef guard
// Transition table for player
struct transition_table
: mpl::vector<
// Start Event Next Action Guard
// +---------+------------------+---------+---------------------------+----------------------+
// stopped phase
Row<Stopped, EventMyTurn, Playing, RoundStart, none>,
Row<Stopped, GetExtortCard, Playing, none, none>,
Row<Stopped, AskExtortCard, Extorted, AskExtortCard,
IsExtortTarget>,
// playing card phase
Row<Playing, PlayCardSkip, Stopped, EndOfTurn, DoesCardExist>,
Row<Playing, PlayCardShirk, Stopped, ShirkOther, DoesCardExist>,
Row<Playing, PlayCardShirk, Playing, ShirkItself,
And_<IsShirkTarget, DoesCardExist>>,
Row<Playing, PlayCardReverse, Stopped, Reverse, DoesCardExist>,
Row<Playing, PlayCardSeeThrough, Playing, SeeThrough,
DoesCardExist>,
Row<Playing, PlayCardPredict, Playing, Predict, DoesCardExist>,
Row<Playing, PlayCardSwap, Playing, Swap,
And_<DoesCardExist, IsTargetAlive>>,
Row<Playing, PlayCardShuffle, Playing, Shuffle, DoesCardExist>,
// extort
Row<Playing, PlayCardExtort, Stopped, SelectExtortTarget,
And_<DoesCardExist, IsTargetAlive>>,
Row<Playing, PlayCardGetBottom, Stopped, GetBottom,
DoesCardExist>,
Row<Playing, PlayCardGetBottom, Exploding, GetBottomBomb,
And_<DoesCardExist, IsBackBomb>>,
// draw card phase
Row<Playing, DrawCard, Stopped, StoreCard, none>,
Row<Playing, DrawCard, Exploding, none, IsFrontBomb>,
// extorted phase
Row<Extorted, ExtortCardSelected, Stopped, ExtortCardSelected,
DoesCardExist>,
// exploding phase
Row<Exploding, PlayCardBombDisposal, Died, none, none>,
Row<Exploding, PlayCardBombDisposal, Stopped, HandleExploding,
DoesCardExist>
// +---------+-------------+---------+---------------------------+----------------------+
> {};
// Replaces the default no-transition response.
template <class FSM, class Event>
void no_transition(Event const &e, FSM &, int state) {
std::cout << "no transition from state " << state << " on event "
<< typeid(e).name() << std::endl;
}
int mUid{0};
std::vector<CardType> mCards;
void PrintCards() {
std::cout << "Player " << mUid << " own " << mCards.size()
<< " cards:\n";
for (auto it : mCards) {
std::cout << CardTypeToString(it) << " ";
}
std::cout << std::endl;
}
Game &mGame;
}; // namespace ExplodingKittens
} // namespace ExplodingKittens
| 32.172702
| 109
| 0.542078
|
SailGame
|
bde89f13ddda00029239c5bba2d511c5130bac31
| 1,229
|
cpp
|
C++
|
src/reactor/application.cpp
|
victor-smirnov/dumbo
|
57fe7f765c69490a9bda6619bcab8fcca0e1d2d9
|
[
"BSL-1.0",
"Apache-2.0"
] | 6
|
2016-10-22T06:37:17.000Z
|
2019-05-09T06:12:48.000Z
|
src/reactor/application.cpp
|
victor-smirnov/dumbo
|
57fe7f765c69490a9bda6619bcab8fcca0e1d2d9
|
[
"BSL-1.0",
"Apache-2.0"
] | null | null | null |
src/reactor/application.cpp
|
victor-smirnov/dumbo
|
57fe7f765c69490a9bda6619bcab8fcca0e1d2d9
|
[
"BSL-1.0",
"Apache-2.0"
] | null | null | null |
// Copyright 2017 Victor Smirnov
//
// 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 <dumbo/v1/reactor/application.hpp>
namespace dumbo {
namespace v1 {
namespace reactor {
Application* Application::application_;
Application::Application(int argc, char** argv, char** envp):
smp_(std::make_shared<Smp>(1)),
reactors_(),
shutdown_hook_([](){engine().stop();})
{
application_ = this;
for (int c = 0; c < smp_->cpu_num(); c++)
{
reactors_.push_back(std::make_shared<Reactor>(smp_, c, c > 0));
}
for (int c = 0; c < smp_->cpu_num(); c++)
{
reactors_[c]->start();
}
}
Application& app() {
return *Application::application_;
}
}}}
| 25.081633
| 75
| 0.662327
|
victor-smirnov
|
bdefba20106bd1f2b3d0dd812cee476ff1d42494
| 329
|
cpp
|
C++
|
11714.cpp
|
abraxaslee/ACM-ICPC
|
d8db31a4a2a36258bfba42a806b02bbf3eceaf2b
|
[
"MIT"
] | 1
|
2018-03-19T05:18:49.000Z
|
2018-03-19T05:18:49.000Z
|
11714.cpp
|
abraxaslee/ACM-ICPC
|
d8db31a4a2a36258bfba42a806b02bbf3eceaf2b
|
[
"MIT"
] | null | null | null |
11714.cpp
|
abraxaslee/ACM-ICPC
|
d8db31a4a2a36258bfba42a806b02bbf3eceaf2b
|
[
"MIT"
] | null | null | null |
//2012/02/25
//11714.cpp
//Run time: 0.024
#include <stdio.h>
#include <math.h>
int main(){
#ifndef ONLINE_JUDGE
freopen("11714.in", "r", stdin);
freopen("11714.out", "w", stdout);
#endif
unsigned int N;
while(scanf("%u", &N) == 1)
printf("%u\n", (N-1)+(unsigned int)(log(N-1)/log(2)));
return 0;
}
| 17.315789
| 57
| 0.56535
|
abraxaslee
|
bdf275538db438f88107062a42962b67fc870cb9
| 15,671
|
cpp
|
C++
|
class/RenderWorkManager.cpp
|
enjiushi/VulkanLearn
|
29fb429a3fb526f8de7406404a983685a7e87117
|
[
"MIT"
] | 272
|
2019-06-27T12:21:49.000Z
|
2022-03-23T07:18:33.000Z
|
class/RenderWorkManager.cpp
|
enjiushi/VulkanLearn
|
29fb429a3fb526f8de7406404a983685a7e87117
|
[
"MIT"
] | 9
|
2019-08-11T13:07:01.000Z
|
2022-01-26T12:30:24.000Z
|
class/RenderWorkManager.cpp
|
enjiushi/VulkanLearn
|
29fb429a3fb526f8de7406404a983685a7e87117
|
[
"MIT"
] | 16
|
2019-09-29T01:41:02.000Z
|
2022-03-29T15:51:35.000Z
|
#include "RenderWorkManager.h"
#include "ComputeMaterialFactory.h"
#include "../vulkan/RenderPass.h"
#include "../vulkan/GlobalDeviceObjects.h"
#include "../vulkan/Framebuffer.h"
#include "../vulkan/SwapChain.h"
#include "../vulkan/Image.h"
#include "../vulkan/GlobalVulkanStates.h"
#include "../common/Util.h"
#include "RenderPassDiction.h"
#include "ForwardRenderPass.h"
#include "DeferredMaterial.h"
#include "ShadowMapMaterial.h"
#include "ForwardMaterial.h"
#include "PostProcessingMaterial.h"
#include "GBufferPlanetMaterial.h"
#include "MaterialInstance.h"
#include "FrameEventManager.h"
#include "../vulkan/ResourceBarrierScheduler.h"
bool RenderWorkManager::Init()
{
if (!Singleton<RenderWorkManager>::Init())
return false;
FrameEventManager::GetInstance()->Register(m_pInstance);
m_materials.resize(MaterialEnumCount);
for (uint32_t i = 0; i < MaterialEnumCount; i++)
{
switch ((MaterialEnum)i)
{
case PBRGBuffer: m_materials[i] = { { GBufferMaterial::CreateDefaultMaterial()} }; break;
case PBRSkinnedGBuffer: m_materials[i] = { { GBufferMaterial::CreateDefaultMaterial(true) } }; break;
case PBRPlanetGBuffer: m_materials[i] = { { GBufferPlanetMaterial::CreateDefaultMaterial() } }; break;
case BackgroundMotion:
{
SimpleMaterialCreateInfo info = {};
info = {};
info.shaderPaths = { L"../data/shaders/background_motion_gen.vert.spv", L"", L"", L"", L"../data/shaders/background_motion_gen.frag.spv", L"" };
info.materialUniformVars = {};
info.vertexFormat = 0;
info.vertexFormatInMem = 0;
info.subpassIndex = 1;
info.pRenderPass = RenderPassDiction::GetInstance()->GetPipelineRenderPass(RenderPassDiction::PipelineRenderPassGBuffer);
info.depthWriteEnable = false;
info.frameBufferType = FrameBufferDiction::FrameBufferType_GBuffer;
m_materials[i] = { {ForwardMaterial::CreateDefaultMaterial(info)} };
}break;
case MotionTileMax:
{
std::vector<std::shared_ptr<Image>> inputImages;
std::vector<std::shared_ptr<Image>> outputImages;
for (uint32_t i = 0; i < GetSwapChain()->GetSwapChainImageCount(); i++)
{
inputImages.push_back(FrameBufferDiction::GetInstance()->GetFrameBuffers(FrameBufferDiction::FrameBufferType_GBuffer)[i]->GetColorTarget(FrameBufferDiction::MotionVector));
outputImages.push_back(FrameBufferDiction::GetInstance()->GetFrameBuffers(FrameBufferDiction::FrameBufferType_MotionTileMax)[i]->GetColorTarget(0));
}
m_materials[i] = { { CreateTileMaxMaterial(inputImages, outputImages) } };
}break;
case MotionNeighborMax:
{
std::vector<std::shared_ptr<Image>> inputImages;
std::vector<std::shared_ptr<Image>> outputImages;
for (uint32_t i = 0; i < GetSwapChain()->GetSwapChainImageCount(); i++)
{
inputImages.push_back(FrameBufferDiction::GetInstance()->GetFrameBuffers(FrameBufferDiction::FrameBufferType_MotionTileMax)[i]->GetColorTarget(0));
outputImages.push_back(FrameBufferDiction::GetInstance()->GetFrameBuffers(FrameBufferDiction::FrameBufferType_MotionNeighborMax)[i]->GetColorTarget(0));
}
m_materials[i] = { { CreateNeighborMaxMaterial(inputImages, outputImages) } };
}break;
case Shadow: m_materials[i] = { { ShadowMapMaterial::CreateDefaultMaterial() } }; break;
case SkinnedShadow: m_materials[i] = { { ShadowMapMaterial::CreateDefaultMaterial(true) } }; break;
case SSAOSSR: m_materials[i] = { { CreateSSAOSSRMaterial() } }; break;
case SSAOBlurV:
{
std::vector<std::shared_ptr<Image>> inputImages;
std::vector<std::shared_ptr<Image>> outputImages;
for (uint32_t i = 0; i < GetSwapChain()->GetSwapChainImageCount(); i++)
{
inputImages.push_back(FrameBufferDiction::GetInstance()->GetFrameBuffers(FrameBufferDiction::FrameBufferType_SSAOSSR)[i]->GetColorTarget(0));
outputImages.push_back(FrameBufferDiction::GetInstance()->GetFrameBuffers(FrameBufferDiction::FrameBufferType_SSAOBlurV)[i]->GetColorTarget(0));
}
m_materials[i] = { { CreateGaussianBlurMaterial(inputImages, outputImages, { true, 1, 1 }) } };
}break;
case SSAOBlurH:
{
std::vector<std::shared_ptr<Image>> inputImages;
std::vector<std::shared_ptr<Image>> outputImages;
for (uint32_t i = 0; i < GetSwapChain()->GetSwapChainImageCount(); i++)
{
inputImages.push_back(FrameBufferDiction::GetInstance()->GetFrameBuffers(FrameBufferDiction::FrameBufferType_SSAOBlurV)[i]->GetColorTarget(0));
outputImages.push_back(FrameBufferDiction::GetInstance()->GetFrameBuffers(FrameBufferDiction::FrameBufferType_SSAOBlurH)[i]->GetColorTarget(0));
}
m_materials[i] = { { CreateGaussianBlurMaterial(inputImages, outputImages,{ false, 1, 1 }) } };
}break;
case DeferredShading: m_materials[i] = { { CreateDeferredShadingMaterial() } }; break;
case TemporalResolve: m_materials[i] = { { CreateTemporalResolveMaterial(0), CreateTemporalResolveMaterial(1) } }; break;
case DepthOfField:
{
for (uint32_t j = 0; j < (uint32_t)DOFPass::COUNT; j++)
{
m_materials[i].materialSet.push_back(CreateDOFMaterial((DOFPass)j));
}
}break;
case BloomDownSample:
{
for (uint32_t j = 0; j < BLOOM_ITER_COUNT; j++)
{
BloomPass bloomPass = (j == 0) ? BloomPass::PREFILTER : BloomPass::DOWNSAMPLE;
m_materials[i].materialSet.push_back(CreateBloomMaterial(bloomPass, j));
}
}break;
case BloomUpSample:
{
for (uint32_t j = 0; j < BLOOM_ITER_COUNT; j++)
{
m_materials[i].materialSet.push_back(CreateBloomMaterial(BloomPass::UPSAMPLE, j));
}
}break;
case Combine: m_materials[i] = { { CreateCombineMaterial() } }; break;
case PostProcess: m_materials[i] = { { PostProcessingMaterial::CreateDefaultMaterial() } }; break;
default:
ASSERTION(false);
break;
}
}
m_pResBarrierScheduler = ResourceBarrierScheduler::Create();
return true;
}
std::shared_ptr<MaterialInstance> RenderWorkManager::AcquirePBRMaterialInstance() const
{
std::shared_ptr<MaterialInstance> pMaterialInstance = GetMaterial(PBRGBuffer)->CreateMaterialInstance();
pMaterialInstance->SetRenderMask(1 << Scene);
return pMaterialInstance;
}
std::shared_ptr<MaterialInstance> RenderWorkManager::AcquirePBRSkinnedMaterialInstance() const
{
std::shared_ptr<MaterialInstance> pMaterialInstance = GetMaterial(PBRSkinnedGBuffer)->CreateMaterialInstance();
pMaterialInstance->SetRenderMask(1 << Scene);
return pMaterialInstance;
}
std::shared_ptr<MaterialInstance> RenderWorkManager::AcquirePBRPlanetMaterialInstance() const
{
std::shared_ptr<MaterialInstance> pMaterialInstance = GetMaterial(PBRPlanetGBuffer)->CreateMaterialInstance();
pMaterialInstance->SetRenderMask(1 << Scene);
return pMaterialInstance;
}
std::shared_ptr<MaterialInstance> RenderWorkManager::AcquireShadowMaterialInstance() const
{
std::shared_ptr<MaterialInstance> pMaterialInstance = GetMaterial(Shadow)->CreateMaterialInstance();
pMaterialInstance->SetRenderMask(1 << ShadowMapGen);
return pMaterialInstance;
}
std::shared_ptr<MaterialInstance> RenderWorkManager::AcquireSkinnedShadowMaterialInstance() const
{
std::shared_ptr<MaterialInstance> pMaterialInstance = GetMaterial(SkinnedShadow)->CreateMaterialInstance();
pMaterialInstance->SetRenderMask(1 << ShadowMapGen);
return pMaterialInstance;
}
void RenderWorkManager::SyncMaterialData()
{
for (auto& materialSet : m_materials)
{
for (auto pMaterial : materialSet.materialSet)
{
pMaterial->SyncBufferData();
}
}
}
void RenderWorkManager::Draw(const std::shared_ptr<CommandBuffer>& pDrawCmdBuffer, uint32_t pingpong)
{
for (uint32_t i = 0; i < (uint32_t)FrameBufferDiction::GBuffer::GBufferCount; i++)
{
m_pResBarrierScheduler->ClaimResourceUsage
(
pDrawCmdBuffer,
FrameBufferDiction::GetInstance()->GetFrameBuffer(FrameBufferDiction::FrameBufferType_GBuffer)->GetColorTarget(i),
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT
);
}
m_pResBarrierScheduler->ClaimResourceUsage
(
pDrawCmdBuffer,
FrameBufferDiction::GetInstance()->GetFrameBuffer(FrameBufferDiction::FrameBufferType_GBuffer)->GetDepthStencilTarget(),
VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT
);
GetMaterial(PBRGBuffer)->BeforeRenderPass(pDrawCmdBuffer, m_pResBarrierScheduler, pingpong);
GetMaterial(PBRSkinnedGBuffer)->BeforeRenderPass(pDrawCmdBuffer, m_pResBarrierScheduler, pingpong);
GetMaterial(PBRPlanetGBuffer)->BeforeRenderPass(pDrawCmdBuffer, m_pResBarrierScheduler, pingpong);
GetMaterial(BackgroundMotion)->BeforeRenderPass(pDrawCmdBuffer, m_pResBarrierScheduler, pingpong);
RenderPassDiction::GetInstance()->GetPipelineRenderPass(RenderPassDiction::PipelineRenderPassGBuffer)->BeginRenderPass(pDrawCmdBuffer, FrameBufferDiction::GetInstance()->GetFrameBuffer(FrameBufferDiction::FrameBufferType_GBuffer));
GetMaterial(PBRGBuffer)->Draw(pDrawCmdBuffer, FrameBufferDiction::GetInstance()->GetFrameBuffer(FrameBufferDiction::FrameBufferType_GBuffer), pingpong);
GetMaterial(PBRSkinnedGBuffer)->Draw(pDrawCmdBuffer, FrameBufferDiction::GetInstance()->GetFrameBuffer(FrameBufferDiction::FrameBufferType_GBuffer), pingpong);
GetMaterial(PBRPlanetGBuffer)->Draw(pDrawCmdBuffer, FrameBufferDiction::GetInstance()->GetFrameBuffer(FrameBufferDiction::FrameBufferType_GBuffer), pingpong);
RenderPassDiction::GetInstance()->GetPipelineRenderPass(RenderPassDiction::PipelineRenderPassGBuffer)->NextSubpass(pDrawCmdBuffer);
GetMaterial(BackgroundMotion)->DrawScreenQuad(pDrawCmdBuffer, FrameBufferDiction::GetInstance()->GetFrameBuffer(FrameBufferDiction::FrameBufferType_GBuffer));
RenderPassDiction::GetInstance()->GetPipelineRenderPass(RenderPassDiction::PipelineRenderPassGBuffer)->EndRenderPass(pDrawCmdBuffer);
GetMaterial(BackgroundMotion)->AfterRenderPass(pDrawCmdBuffer, pingpong);
GetMaterial(PBRPlanetGBuffer)->AfterRenderPass(pDrawCmdBuffer, pingpong);
GetMaterial(PBRSkinnedGBuffer)->AfterRenderPass(pDrawCmdBuffer, pingpong);
GetMaterial(PBRGBuffer)->AfterRenderPass(pDrawCmdBuffer, pingpong);
GetMaterial(MotionTileMax)->BeforeRenderPass(pDrawCmdBuffer, m_pResBarrierScheduler, pingpong);
GetMaterial(MotionTileMax)->Dispatch(pDrawCmdBuffer, pingpong);
GetMaterial(MotionTileMax)->AfterRenderPass(pDrawCmdBuffer, pingpong);
GetMaterial(MotionNeighborMax)->BeforeRenderPass(pDrawCmdBuffer, m_pResBarrierScheduler, pingpong);
GetMaterial(MotionNeighborMax)->Dispatch(pDrawCmdBuffer, pingpong);
GetMaterial(MotionNeighborMax)->AfterRenderPass(pDrawCmdBuffer, pingpong);
m_pResBarrierScheduler->ClaimResourceUsage
(
pDrawCmdBuffer,
FrameBufferDiction::GetInstance()->GetFrameBuffer(FrameBufferDiction::FrameBufferType_ShadowMap)->GetDepthStencilTarget(),
VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT
);
GetMaterial(Shadow)->BeforeRenderPass(pDrawCmdBuffer, m_pResBarrierScheduler, pingpong);
GetMaterial(SkinnedShadow)->BeforeRenderPass(pDrawCmdBuffer, nullptr, pingpong);
RenderPassDiction::GetInstance()->GetPipelineRenderPass(RenderPassDiction::PipelineRenderPassShadowMap)->BeginRenderPass(pDrawCmdBuffer, FrameBufferDiction::GetInstance()->GetFrameBuffer(FrameBufferDiction::FrameBufferType_ShadowMap));
GetMaterial(Shadow)->Draw(pDrawCmdBuffer, FrameBufferDiction::GetInstance()->GetFrameBuffer(FrameBufferDiction::FrameBufferType_ShadowMap), pingpong);
GetMaterial(SkinnedShadow)->Draw(pDrawCmdBuffer, FrameBufferDiction::GetInstance()->GetFrameBuffer(FrameBufferDiction::FrameBufferType_ShadowMap), pingpong);
RenderPassDiction::GetInstance()->GetPipelineRenderPass(RenderPassDiction::PipelineRenderPassShadowMap)->EndRenderPass(pDrawCmdBuffer);
GetMaterial(SkinnedShadow)->AfterRenderPass(pDrawCmdBuffer, pingpong);
GetMaterial(Shadow)->AfterRenderPass(pDrawCmdBuffer, pingpong);
GetMaterial(SSAOSSR)->BeforeRenderPass(pDrawCmdBuffer, m_pResBarrierScheduler, pingpong);
GetMaterial(SSAOSSR)->Dispatch(pDrawCmdBuffer, pingpong);
GetMaterial(SSAOSSR)->AfterRenderPass(pDrawCmdBuffer, pingpong);
GetMaterial(SSAOBlurV)->BeforeRenderPass(pDrawCmdBuffer, m_pResBarrierScheduler, pingpong);
GetMaterial(SSAOBlurV)->Dispatch(pDrawCmdBuffer, pingpong);
GetMaterial(SSAOBlurV)->AfterRenderPass(pDrawCmdBuffer, pingpong);
GetMaterial(SSAOBlurH)->BeforeRenderPass(pDrawCmdBuffer, m_pResBarrierScheduler, pingpong);
GetMaterial(SSAOBlurH)->Dispatch(pDrawCmdBuffer, pingpong);
GetMaterial(SSAOBlurH)->AfterRenderPass(pDrawCmdBuffer, pingpong);
GetMaterial(DeferredShading)->BeforeRenderPass(pDrawCmdBuffer, m_pResBarrierScheduler, pingpong);
GetMaterial(DeferredShading)->Dispatch(pDrawCmdBuffer, pingpong);
GetMaterial(DeferredShading)->AfterRenderPass(pDrawCmdBuffer, pingpong);
GetMaterial(TemporalResolve, pingpong)->BeforeRenderPass(pDrawCmdBuffer, m_pResBarrierScheduler, pingpong);
GetMaterial(TemporalResolve, pingpong)->Dispatch(pDrawCmdBuffer, pingpong);
GetMaterial(TemporalResolve, pingpong)->AfterRenderPass(pDrawCmdBuffer, pingpong);
for (uint32_t i = 0; i < (uint32_t)DOFPass::COUNT; i++)
{
GetMaterial(DepthOfField, i)->BeforeRenderPass(pDrawCmdBuffer, m_pResBarrierScheduler, pingpong);
GetMaterial(DepthOfField, i)->Dispatch(pDrawCmdBuffer, pingpong);
GetMaterial(DepthOfField, i)->AfterRenderPass(pDrawCmdBuffer, pingpong);
}
// Downsample first
for (uint32_t i = 0; i < BLOOM_ITER_COUNT; i++)
{
GetMaterial(BloomDownSample, i)->BeforeRenderPass(pDrawCmdBuffer, m_pResBarrierScheduler, pingpong);
GetMaterial(BloomDownSample, i)->Dispatch(pDrawCmdBuffer, pingpong);
GetMaterial(BloomDownSample, i)->AfterRenderPass(pDrawCmdBuffer, pingpong);
}
// Upsample then
for (int32_t i = BLOOM_ITER_COUNT - 1; i >= 0; i--)
{
GetMaterial(BloomUpSample, i)->BeforeRenderPass(pDrawCmdBuffer, m_pResBarrierScheduler, pingpong);
GetMaterial(BloomUpSample, i)->Dispatch(pDrawCmdBuffer, pingpong);
GetMaterial(BloomUpSample, i)->AfterRenderPass(pDrawCmdBuffer, pingpong);
}
GetMaterial(Combine)->BeforeRenderPass(pDrawCmdBuffer, m_pResBarrierScheduler, pingpong);
GetMaterial(Combine)->Dispatch(pDrawCmdBuffer, pingpong);
GetMaterial(Combine)->AfterRenderPass(pDrawCmdBuffer, pingpong);
GetMaterial(PostProcess)->BeforeRenderPass(pDrawCmdBuffer, m_pResBarrierScheduler, pingpong);
RenderPassDiction::GetInstance()->GetPipelineRenderPass(RenderPassDiction::PipelineRenderPassPostProcessing)->BeginRenderPass(pDrawCmdBuffer, FrameBufferDiction::GetInstance()->GetFrameBuffer(FrameBufferDiction::FrameBufferType_PostProcessing));
GetMaterial(PostProcess)->Draw(pDrawCmdBuffer, FrameBufferDiction::GetInstance()->GetFrameBuffer(FrameBufferDiction::FrameBufferType_PostProcessing), pingpong);
RenderPassDiction::GetInstance()->GetPipelineRenderPass(RenderPassDiction::PipelineRenderPassPostProcessing)->EndRenderPass(pDrawCmdBuffer);
GetMaterial(PostProcess)->AfterRenderPass(pDrawCmdBuffer, pingpong);
m_pResBarrierScheduler->ClearResUsageRecord();
}
void RenderWorkManager::OnFrameBegin()
{
SetRenderStateMask((1 << RenderWorkManager::Scene) | (1 << RenderWorkManager::ShadowMapGen));
}
void RenderWorkManager::OnPostSceneTraversal()
{
SyncMaterialData();
}
void RenderWorkManager::OnPreCmdPreparation()
{
for (auto& materialSet : m_materials)
{
for (auto pMaterial : materialSet.materialSet)
{
pMaterial->OnFrameBegin();
}
}
}
void RenderWorkManager::OnPreCmdSubmission()
{
for (auto& materialSet : m_materials)
{
for (auto pMaterial : materialSet.materialSet)
{
pMaterial->OnFrameEnd();
}
}
}
| 45.821637
| 246
| 0.793695
|
enjiushi
|
da0be6cb8a9294384bc5c7743b2624315a53e9cc
| 2,269
|
hpp
|
C++
|
include/vif/test/unit_test.hpp
|
lmorabit/vif
|
459715c60e0ef6c83c7ebfb8741355d597dbc7aa
|
[
"Apache-2.0"
] | 6
|
2018-09-04T10:57:00.000Z
|
2021-10-05T07:41:50.000Z
|
include/vif/test/unit_test.hpp
|
lmorabit/vif
|
459715c60e0ef6c83c7ebfb8741355d597dbc7aa
|
[
"Apache-2.0"
] | 2
|
2019-05-22T02:59:46.000Z
|
2019-12-02T19:15:43.000Z
|
include/vif/test/unit_test.hpp
|
lmorabit/vif
|
459715c60e0ef6c83c7ebfb8741355d597dbc7aa
|
[
"Apache-2.0"
] | 3
|
2019-05-01T10:20:47.000Z
|
2021-09-20T16:35:34.000Z
|
#ifndef VIF_TEST_UNIT_TEST_HPP
#define VIF_TEST_UNIT_TEST_HPP
#include "vif/core/vec.hpp"
#include "vif/core/print.hpp"
#include "vif/core/string_conversion.hpp"
#include "vif/math/base.hpp"
namespace vif {
uint_t tested = 0u;
uint_t failed = 0u;
bool reduce_and(bool b) {
return b;
}
template<std::size_t Dim>
bool reduce_and(const vec<Dim,bool>& b) {
bool res = true;
for (bool v : b) {
res = res && v;
}
return res;
}
namespace impl {
template<typename T1>
struct is_float_ : std::false_type {
};
template<>
struct is_float_<float> : std::true_type {
};
template<>
struct is_float_<double> : std::true_type {
};
template<std::size_t D, typename T>
struct is_float_<vec<D,T>> : is_float_<typename std::remove_pointer<T>::type> {
};
}
template<typename T1, typename T2>
struct is_float : std::integral_constant<bool, impl::is_float_<T1>::value || impl::is_float_<T2>::value> {
};
namespace impl {
template<typename T1, typename T2>
auto is_same_(const T1& v1, const T2& v2, std::false_type) -> decltype(v1 == v2) {
return v1 == v2;
}
template<typename T1, typename T2>
auto is_same_(const T1& v1, const T2& v2, std::true_type) -> decltype(v1 == v2) {
return abs(v1 - v2) <= std::numeric_limits<float>::epsilon() ||
(is_nan(v1) && is_nan(v2)) || is_nan(v1 - v2);
}
}
template<typename T1, typename T2>
auto is_same(const T1& v1, const T2& v2) -> decltype(v1 == v2) {
return impl::is_same_(v1, v2, is_float<T1,T2>{});
}
static bool check_show_line = false;
#define check_base_(cond, msg, file, line) do { \
if (check_show_line) print(std::string(file)+":"+to_string(line)); \
if (!cond) { \
print(msg); \
++failed; \
} \
++tested; \
} while (false)
#define check_base(cond, msg) check_base_(reduce_and(cond), msg, __FILE__, __LINE__)
#define check(t, s) \
check_base(is_same(t, s), " failed: "+std::string(#t)+" = "+to_string(t)+" != "+to_string(s))
}
#endif
| 28.012346
| 110
| 0.565888
|
lmorabit
|
da0c777b0bc29d4d49a90d04a0c52b64972e1373
| 155
|
hpp
|
C++
|
src/jk/cog/vm/restart_exception.hpp
|
jdmclark/gorc
|
a03d6a38ab7684860c418dd3d2e77cbe6a6d9fc8
|
[
"Apache-2.0"
] | 97
|
2015-02-24T05:09:24.000Z
|
2022-01-23T12:08:22.000Z
|
src/jk/cog/vm/restart_exception.hpp
|
annnoo/gorc
|
1889b4de6380c30af6c58a8af60ecd9c816db91d
|
[
"Apache-2.0"
] | 8
|
2015-03-27T23:03:23.000Z
|
2020-12-21T02:34:33.000Z
|
src/jk/cog/vm/restart_exception.hpp
|
annnoo/gorc
|
1889b4de6380c30af6c58a8af60ecd9c816db91d
|
[
"Apache-2.0"
] | 10
|
2016-03-24T14:32:50.000Z
|
2021-11-13T02:38:53.000Z
|
#pragma once
namespace gorc {
namespace cog {
class restart_exception {
public:
restart_exception();
};
}
}
| 11.923077
| 33
| 0.516129
|
jdmclark
|
da0d78eddc454659ae37a6b292f010a50e03e731
| 28,605
|
cpp
|
C++
|
Examples/SDKLibrary/interface/server/platform_specific/server_class/c_api/value_attribute_reader_writer_for_c_api.cpp
|
beeond/robot-examples
|
afc6b8b10809988b03663d703203625927e66e8f
|
[
"MIT"
] | 1
|
2018-03-29T21:03:31.000Z
|
2018-03-29T21:03:31.000Z
|
Examples/SDKLibrary/interface/server/platform_specific/server_class/c_api/value_attribute_reader_writer_for_c_api.cpp
|
JayeshThamke/robot-examples
|
afc6b8b10809988b03663d703203625927e66e8f
|
[
"MIT"
] | null | null | null |
Examples/SDKLibrary/interface/server/platform_specific/server_class/c_api/value_attribute_reader_writer_for_c_api.cpp
|
JayeshThamke/robot-examples
|
afc6b8b10809988b03663d703203625927e66e8f
|
[
"MIT"
] | 4
|
2018-04-05T21:16:55.000Z
|
2019-10-15T19:01:46.000Z
|
/* ----------------------------------------------------------------------------------------
COPYRIGHT (c) 2009 - 2017
HONEYWELL INC.,
ALL RIGHTS RESERVED
This software is a copyrighted work and/or information protected as a trade
secret. Legal rights of Honeywell Inc. in this software are distinct from
ownership of any medium in which the software is embodied. Copyright or trade
secret notices included must be reproduced in any copies authorized by
Honeywell Inc. The information in this software is subject to change without
notice and should not be considered as a commitment by Honeywell Inc.
---------------------------------------------------------------------------------------- */
#include "value_attribute_reader_writer_for_c_api.h"
#if (UASDK_INCLUDE_SERVER)
#if (UASDK_INCLUDE_SERVER_C_API > 0)
#include "ua_server.h"
#include "opcua_datatype_utilities_t.h"
#include "opcua_base_data_type_t.h"
#include "opcua_array_ua_t.h"
#include "opcua_boolean_t.h"
#include "opcua_sbyte_t.h"
#include "opcua_byte_t.h"
#include "opcua_int16_t.h"
#include "opcua_uint16_t.h"
#include "opcua_int32_t.h"
#include "opcua_uint32_t.h"
#include "opcua_int64_t.h"
#include "opcua_uint64_t.h"
#include "opcua_float_t.h"
#include "opcua_double_t.h"
#include "opcua_string_t.h"
#include "opcua_date_time_t.h"
#include "opcua_guid_t.h"
#include "opcua_bytestring_t.h"
#include "opcua_xml_element_t.h"
#include "browse_names_t.h"
#include "address_space_utilities_t.h"
#include "opcua_datatype_utilities_t.h"
#include "opcua_range_t.h"
#include "utilities.h"
namespace uasdk
{
/*
* private functions
*/
Status_t ConvertToString(uint8_t* data, int32_t length, Array_t<char>& result)
{
if(!data || (length < 0))
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadUnexpectedError);
}
Status_t status = result.Initialise(length + 1);
if(status.IsBad())
{
return status;
}
if(length > 0)
{
UASDK_memcpy(result.Value(), data, length);
}
result[length] = '\0';
return OpcUa_Good;
}
template<typename T, typename U>
Status_t CopyToUaValue(T& val_, U* rawValue_)
{
if (!rawValue_)
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadInvalidArgument);
}
val_.Value(*rawValue_);
return OpcUa_Good;
}
Status_t CopyToUaValue(Guid_t& val_, uint8_t* rawValue_)
{
if (!rawValue_)
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadInvalidArgument);
}
return val_.CopyFrom(rawValue_);
}
Status_t CopyToUaValue(ByteString_t& val_, UA_Byte_string_t* rawValue_)
{
if (!rawValue_ || !rawValue_->data || !rawValue_->length || (rawValue_->max_length < 0))
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadInvalidArgument);
}
return val_.CopyFrom(rawValue_->data, rawValue_->length);
}
Status_t CopyToUaValue(String_t& val_, UA_Var_string_t* rawValue_)
{
if (!rawValue_ || !rawValue_->data || (rawValue_->length < 0) || (rawValue_->max_length < 0))
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadInvalidArgument);
}
Array_t<char> str;
Status_t status = ConvertToString(rawValue_->data, rawValue_->length, str);
if(status.IsBad())
{
UASDK_RETURN_BAD_STATUS(status.Value());
}
return val_.CopyFrom((const char*)str.Value(), (uint32_t)(str.Count() + 1));
}
Status_t CopyToUaValue(XmlElement_t& val_, UA_Xml_element_t* rawValue_)
{
if (!rawValue_ || !rawValue_->data || (rawValue_->length < 0) || (rawValue_->max_length < 0))
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadInvalidArgument);
}
Array_t<char> str;
Status_t status = ConvertToString(rawValue_->data, rawValue_->length, str);
if(status.IsBad())
{
UASDK_RETURN_BAD_STATUS(status.Value());
}
return val_.CopyFrom((const char*)str.Value(), (uint32_t)(str.Count() + 1));
}
template<typename T, typename U>
Status_t CopyToRawValue(T& val_, U* rawValue_)
{
if (!rawValue_)
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadInvalidArgument);
}
*rawValue_ = val_.Value();
return OpcUa_Good;
}
Status_t CopyToRawValue(const Guid_t& val_, uint8_t* rawValue_)
{
if (UASDK_memcpy(rawValue_, val_.Value(), val_.GUID_LENGTH) != rawValue_)
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadUnexpectedError);
}
return OpcUa_Good;
}
Status_t CopyToRawValue(const ByteString_t& val_, UA_Byte_string_t* rawValue_)
{
if (!rawValue_ || !rawValue_->data)
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadUnexpectedError);
}
if (val_.Length() > rawValue_->max_length)
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadOutOfRange);
}
if (val_.Data())
{
UASDK_memcpy(rawValue_->data, val_.Data(), val_.Length());
}
rawValue_->length = val_.Length();
return OpcUa_Good;
}
Status_t CopyToRawValue(const String_t& val_, UA_Var_string_t* rawValue_)
{
if (!rawValue_ || !rawValue_->data)
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadUnexpectedError);
}
if (val_.Length() > rawValue_->max_length)
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadOutOfRange);
}
UA_UTF8_string_t temp = val_.ToLegacy();
if (!temp.data)
{
UASDK_memcpy(rawValue_->data, "", 1);
rawValue_->length = 0;
}
else
{
UASDK_memcpy(rawValue_->data, (temp.data), temp.length);
rawValue_->length = temp.length;
}
return OpcUa_Good;
}
Status_t CopyToRawValue(const XmlElement_t& val_, UA_Xml_element_t* rawValue_)
{
if (!rawValue_ || !rawValue_->data)
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadUnexpectedError);
}
if (val_.Length() > rawValue_->max_length)
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadOutOfRange);
}
if (!val_.Payload().Data())
{
UASDK_memcpy(rawValue_->data, "", 1);
rawValue_->length = 0;
}
else
{
UASDK_memcpy(rawValue_->data, val_.Payload().Data(), val_.Length());
rawValue_->length = val_.Length();
}
return OpcUa_Good;
}
template<typename T, typename U>
Status_t ValueAttributeReaderWriterForCAPI_t::UpdateToBaseDataValue(U* rawValue_, IntrusivePtr_t<BaseDataType_t>& value_)
{
if (!rawValue_)
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadInvalidArgument);
}
Status_t status;
if (!maxArrayLength)
{
T val_;
status = CopyToUaValue(val_, rawValue_);
if (status.IsBad())
{
UASDK_RETURN_BAD_STATUS(status.Value());
}
status = val_.CopyTo(value_);
if (status.IsBad() || !value_.is_set())
{
UASDK_RETURN_BAD_STATUS(status.Value());
}
}
else
{
if (maxArrayLength < actualArraySize)
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadOutOfRange);
}
IntrusivePtr_t< ArrayUA_t<T> > arrayVal_(new SafeRefCount_t< ArrayUA_t<T> >());
if (!arrayVal_.is_set())
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadOutOfMemory);
}
status = arrayVal_->Initialise(actualArraySize);
if (status.IsBad())
{
UASDK_RETURN_BAD_STATUS(status.Value());
}
for (uint32_t i = 0; i < actualArraySize; i++)
{
T val_;
uint32_t rawValueIndex = i;
if (val_.TYPE_ID == OpcUaId_Guid)
{
rawValueIndex = (i * Guid_t::GUID_LENGTH);
}
status = CopyToUaValue(val_, &(rawValue_[rawValueIndex]));
if (status.IsBad())
{
UASDK_RETURN_BAD_STATUS(status.Value());
}
IntrusivePtr_t<T> temp(new SafeRefCount_t<T>());
if (!temp.is_set())
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadOutOfMemory);
}
status = temp->CopyFrom(val_);
if (status.IsBad())
{
UASDK_RETURN_BAD_STATUS(status.Value());
}
(*arrayVal_)[i] = temp;
}
value_ = arrayVal_;
}
return status;
}
Status_t ValueAttributeReaderWriterForCAPI_t::ConvertRawDataToUaData(UA_Value_t& rawData)
{
Status_t status;
IntrusivePtr_t<BaseDataType_t> value;
switch (valueType)
{
case UA_TYPE_Boolean:
status = UpdateToBaseDataValue<Boolean_t>((bool*)(rawData.value_Boolean), value);
break;
case UA_TYPE_SByte:
status = UpdateToBaseDataValue<SByte_t>((rawData.value_SByte), value);
break;
case UA_TYPE_Byte:
status = UpdateToBaseDataValue<Byte_t>((rawData.value_Byte), value);
break;
case UA_TYPE_Int16:
status = UpdateToBaseDataValue<Int16_t>((rawData.value_Int16), value);
break;
case UA_TYPE_UInt16:
status = UpdateToBaseDataValue<UInt16_t>((rawData.value_UInt16), value);
break;
case UA_TYPE_Int32:
status = UpdateToBaseDataValue<Int32_t>((rawData.value_Int32), value);
break;
case UA_TYPE_UInt32:
status = UpdateToBaseDataValue<UInt32_t>((rawData.value_UInt32), value);
break;
case UA_TYPE_Int64:
status = UpdateToBaseDataValue<Int64_t>(rawData.value_Int64, value);
break;
case UA_TYPE_UInt64:
status = UpdateToBaseDataValue<UInt64_t>((rawData.value_UInt64), value);
break;
case UA_TYPE_Float:
status = UpdateToBaseDataValue<Float_t>((rawData.value_Float), value);
break;
case UA_TYPE_Double:
status = UpdateToBaseDataValue<Double_t>((rawData.value_Double), value);
break;
case UA_TYPE_String:
status = UpdateToBaseDataValue<String_t>((rawData.value_String), value);
break;
case UA_TYPE_DateTime:
status = UpdateToBaseDataValue<DateTime_t>((rawData.value_DateTime), value);
break;
case UA_TYPE_Guid:
status = UpdateToBaseDataValue<Guid_t>((rawData.value_GUID), value);
break;
case UA_TYPE_ByteString:
status = UpdateToBaseDataValue<ByteString_t>((rawData.value_ByteString), value);
break;
case UA_TYPE_XmlElement:
status = UpdateToBaseDataValue<XmlElement_t>((rawData.value_XmlElement), value);
break;
default:
UASDK_RETURN_BAD_STATUS(OpcUa_BadTypeMismatch);
}
if (status.IsBad() || !value.is_set())
{
UASDK_RETURN_BAD_STATUS(status.Value());
}
if (dataValue_.is_set() && dataValue_->Value().is_set())
{
if (*(dataValue_->Value()) == *value)
{
return OpcUa_Good;
}
}
{
AutoLock_t lk(lock);
dataValue_.reset(new SafeRefCount_t<DataValue_t>());
if (!dataValue_.is_set())
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadOutOfMemory);
}
dataValue_->Value() = value;
}
return OpcUa_Good;
}
Status_t ValueAttributeReaderWriterForCAPI_t::ReadValue(UA_Value_t& rawData, Status_t& statusCode_, int64_t& sourceTimeStamp)
{
if (!rawData.value_Any)
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadNoData);
}
if(statusCode_.IsBad())
{
return statusCode_;
}
{
AutoLock_t lk(lock);
Status_t status = ConvertRawDataToUaData(rawData);
if (status.IsBad() || !dataValue_.is_set())
{
UASDK_RETURN_BAD_STATUS(status.Value());
}
IntrusivePtr_t<DateTime_t> sourceTimeStamp_(new SafeRefCount_t<DateTime_t>());
if (!sourceTimeStamp_.is_set())
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadOutOfMemory);
}
sourceTimeStamp_->Value(sourceTimeStamp);
dataValue_->SourceTimestamp() = sourceTimeStamp_;
IntrusivePtr_t<StatusCode_t> statusCode_ = new SafeRefCount_t<StatusCode_t>();
if (!statusCode_.is_set())
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadOutOfMemory);
}
statusCode_->Value().Value(OpcUa_Good);
dataValue_->StatusCode() = statusCode_;
return OpcUa_Good;
}
}
template<typename T, typename U>
Status_t ValueAttributeReaderWriterForCAPI_t::UpdateFromBaseDataValue(U* rawValue_, uint32_t& newLengthOfArray)
{
if (!dataValue_.is_set() || !dataValue_->Value().is_set())
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadInvalidArgument);
}
IntrusivePtr_t<const BaseDataType_t> value_ = dataValue_->Value();
if (!value_.is_set())
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadUnexpectedError);
}
Status_t status;
if (!value_->IsArray())
{
const T* val = RuntimeCast<const T*>(*value_);
if (!val)
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadTypeMismatch);
}
status = CopyToRawValue(*val, rawValue_);
if (status.IsBad())
{
return status;
}
newLengthOfArray = 0;
}
else
{
const ArrayUA_t<T>* val = RuntimeCast<const ArrayUA_t<T>* >(*value_);
if (!val)
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadTypeMismatch);
}
if (val->Size() <= 0)
{
newLengthOfArray = val->Size();
return OpcUa_Good;
}
uint32_t startIndex;
uint32_t endIndex;
if (indexRange_.Size() > 0)
{
startIndex = indexRange_[0].start;
endIndex = (indexRange_[0].end);
if ((startIndex < 0) || (startIndex > endIndex) || (startIndex >= maxArrayLength) || (endIndex >= maxArrayLength))
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadOutOfRange);
}
newLengthOfArray = actualArraySize;
}
else
{
startIndex = 0;
endIndex = (val->Size() - 1);
if (endIndex >= maxArrayLength)
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadOutOfRange);
}
newLengthOfArray = val->Size();
}
for (uint32_t i = startIndex; i <= endIndex; i++)
{
IntrusivePtr_t<T> temp = (*val)[i];
if (!temp.is_set())
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadUnexpectedError);
}
uint32_t rawValueIndex = i;
if (temp->TYPE_ID == OpcUaId_Guid)
{
rawValueIndex = (i * Guid_t::GUID_LENGTH);
}
status = CopyToRawValue(const_cast<const T&>(*temp), &rawValue_[rawValueIndex]);
if (status.IsBad())
{
return status;
}
}
}
return OpcUa_Good;
}
Status_t ValueAttributeReaderWriterForCAPI_t::WriteValue(UA_Value_t& rawData, int64_t& sourceTimeStamp, uint32_t& newLengthOfArray)
{
if (!dataValue_.is_set())
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadInvalidArgument);
}
Status_t status;
switch (valueType)
{
case UA_TYPE_Boolean:
status = UpdateFromBaseDataValue<Boolean_t>((bool*)(rawData.value_Boolean), newLengthOfArray);
break;
case UA_TYPE_SByte:
status = UpdateFromBaseDataValue<SByte_t>((rawData.value_SByte), newLengthOfArray);
break;
case UA_TYPE_Byte:
status = UpdateFromBaseDataValue<Byte_t>((rawData.value_Byte), newLengthOfArray);
break;
case UA_TYPE_Int16:
status = UpdateFromBaseDataValue<Int16_t>((rawData.value_Int16), newLengthOfArray);
break;
case UA_TYPE_UInt16:
status = UpdateFromBaseDataValue<UInt16_t>((rawData.value_UInt16), newLengthOfArray);
break;
case UA_TYPE_Int32:
status = UpdateFromBaseDataValue<Int32_t>((rawData.value_Int32), newLengthOfArray);
break;
case UA_TYPE_UInt32:
status = UpdateFromBaseDataValue<UInt32_t>((rawData.value_UInt32), newLengthOfArray);
break;
case UA_TYPE_Int64:
status = UpdateFromBaseDataValue<Int64_t>((rawData.value_Int64), newLengthOfArray);
break;
case UA_TYPE_UInt64:
status = UpdateFromBaseDataValue<UInt64_t>((rawData.value_UInt64), newLengthOfArray);
break;
case UA_TYPE_Float:
status = UpdateFromBaseDataValue<Float_t>((rawData.value_Float), newLengthOfArray);
break;
case UA_TYPE_Double:
status = UpdateFromBaseDataValue<Double_t>((rawData.value_Double), newLengthOfArray);
break;
case UA_TYPE_String:
status = UpdateFromBaseDataValue<String_t>((rawData.value_String), newLengthOfArray);
break;
case UA_TYPE_DateTime:
status = UpdateFromBaseDataValue<DateTime_t>((rawData.value_DateTime), newLengthOfArray);
break;
case UA_TYPE_Guid:
status = UpdateFromBaseDataValue<Guid_t>((rawData.value_GUID), newLengthOfArray);
break;
case UA_TYPE_ByteString:
status = UpdateFromBaseDataValue<ByteString_t>((rawData.value_ByteString), newLengthOfArray);
break;
case UA_TYPE_XmlElement:
status = UpdateFromBaseDataValue<XmlElement_t>((rawData.value_XmlElement), newLengthOfArray);
break;
default:
UASDK_RETURN_BAD_STATUS(OpcUa_BadTypeMismatch);
}
if (status.IsBad())
{
UASDK_RETURN_BAD_STATUS(status.Value());
}
if (dataValue_->SourceTimestamp().is_set())
{
sourceTimeStamp = dataValue_->SourceTimestamp()->Value();
}
return OpcUa_Good;
}
#if ((UASDK_USE_HELPERS > 0) && (UASDK_USE_DATA_ACCESS_HELPERS > 0))
IntrusivePtr_t<IVariableNode_t> ValueAttributeReaderWriterForCAPI_t::GetInstrumentRangePropertyNode(const IVariableNode_t& parentNode, Status_t& result)
{
IntrusivePtr_t<IVariableNode_t> instrumentRangeNode;
String_t browseName;
if (!addressSpace.is_set())
{
return instrumentRangeNode;
}
result = browseName.CopyFrom(BROWSE_NAME_INSTRUMENT_RANGE);
if (result.IsBad())
{
return instrumentRangeNode;
}
result = AddressSpaceUtilities_t::GetProperty(parentNode, *addressSpace, browseName, instrumentRangeNode);
if (result.IsBad() || !instrumentRangeNode.is_set())
{
return instrumentRangeNode;
}
result = OpcUa_Good;
return instrumentRangeNode;
}
Status_t ValueAttributeReaderWriterForCAPI_t::IsInRange(const IVariableNode_t& instrumentRangeNode, const DataValue_t& parentNodeValue)
{
if (!instrumentRangeNode.Value().is_set() || !instrumentRangeNode.Value()->Value().is_set() || !parentNodeValue.Value().is_set())
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadInvalidArgument);
}
IntrusivePtr_t<const Range_t> range_ = RuntimeCast<const Range_t*>(*(instrumentRangeNode.Value()->Value()));
if (!range_.is_set())
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadTypeMismatch);
}
return AddressSpaceUtilities_t::RangeCheck(*range_, *(parentNodeValue.Value()));
}
#endif //#if (UASDK_USE_DATA_ACCESS_HELPERS > 0)
/*
* public functions
*/
ValueAttributeReaderWriterForCAPI_t::ValueAttributeReaderWriterForCAPI_t()
: nodeHandle(0),
maxArrayLength(0),
actualArraySize(0),
valueType(UA_TYPE_Invalid),
timeoutHint_(0),
deferralHandle(0)
{}
ValueAttributeReaderWriterForCAPI_t::~ValueAttributeReaderWriterForCAPI_t()
{
}
Status_t ValueAttributeReaderWriterForCAPI_t::Initialize(uintptr_t nodeHandle_, uint32_t maxArrayLength_, UA_Value_type_t valueType_, IntrusivePtr_t<IAddressSpace_t>& addressSpace_)
{
if (!addressSpace_.is_set())
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadInvalidArgument);
}
nodeHandle = nodeHandle_;
maxArrayLength = maxArrayLength_;
actualArraySize = maxArrayLength;
valueType = valueType_;
addressSpace = addressSpace_;
return lock.Initialise();
}
void ValueAttributeReaderWriterForCAPI_t::PerformRead(UA_Value_t rawData_, Status_t statusCode_, int64_t sourceTimeStamp_)
{
statusCode = ReadValue(rawData_, statusCode_, sourceTimeStamp_);
}
void ValueAttributeReaderWriterForCAPI_t::PerformWrite(UA_Value_t& rawData_, int64_t& sourceTimeStamp_, uint32_t& newLengthOfArray)
{
statusCode = WriteValue(rawData_, sourceTimeStamp_, newLengthOfArray);
{
AutoLock_t lk(lock);
actualArraySize = newLengthOfArray;
}
}
Status_t ValueAttributeReaderWriterForCAPI_t::SetWriteOperationLevelResultCode(Status_t resultCode)
{
if (resultCode.IsBad() && (resultCode != statusCode))
{
statusCode = resultCode;
}
return OpcUa_Good;
}
bool ValueAttributeReaderWriterForCAPI_t::IsReadOperationDeferred(void)
{
if (deferralHandle > 0)
{
return true;
}
return false;
}
uint32_t ValueAttributeReaderWriterForCAPI_t::GetReadTimeOutHint(void)
{
return timeoutHint_;
}
Status_t ValueAttributeReaderWriterForCAPI_t::UpdateDeferralHandle(uintptr_t* deferralHandle_)
{
if (!deferralHandle_)
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadInvalidArgument);
}
if (deferralHandle > 0)
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadNotReadable);
}
{
AutoLock_t lk(lock);
deferralHandle = *deferralHandle_;
}
return OpcUa_Good;
}
Status_t ValueAttributeReaderWriterForCAPI_t::ReadDeferralComplete(void)
{
if (!deferralHandle || !readCompletedCallback.is_set())
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadUnexpectedError);
}
if (statusCode.IsBad() || !dataValue_.is_set())
{
UASDK_RETURN_BAD_STATUS(statusCode.Value());
}
IntrusivePtr_t<DataValue_t> temp (new SafeRefCount_t<DataValue_t>());
if(!temp.is_set())
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadOutOfMemory);
}
Status_t status = temp->CopyFrom(*dataValue_);
if(status.IsBad())
{
UASDK_RETURN_BAD_STATUS(statusCode.Value());
}
status = readCompletedCallback->ReadValueAttributeCompleted(temp);
if (status.IsBad())
{
UASDK_RETURN_BAD_STATUS(status.Value());
}
{
AutoLock_t lk(lock);
timeoutHint_ = 0;
deferralHandle = 0;
readCompletedCallback.reset();
}
return OpcUa_Good;
}
void ValueAttributeReaderWriterForCAPI_t::CallApplicationLayerRead(void)
{
UAServer_Callback_read(nodeHandle, valueType, maxArrayLength, (uintptr_t)this);
}
bool ValueAttributeReaderWriterForCAPI_t::CanReadValueSynchronously(const IVariableNode_t& node)
{
UASDK_UNUSED(node);
//return false; //Asynchronous read is supported in the next release
return true;
}
Status_t ValueAttributeReaderWriterForCAPI_t::ReadValueAttributeBegin(
IntrusivePtr_t<const IVariableNode_t>& node,
uint32_t maxAge,
bool setSourceTimestamp,
IntrusivePtr_t<const ArrayUA_t<String_t> >& locales,
IntrusivePtr_t<const ArrayRef_t<IndexRange_t> >& indexRange,
uint32_t transactionId,
uint32_t timeoutHint,
IntrusivePtr_t<ICallbackNodeValueAttributeAccessCompleted_t>& completedCallback)
{
#if 0 //Eanble this for next release
UASDK_UNUSED(node);
UASDK_UNUSED(maxAge);
UASDK_UNUSED(setSourceTimestamp);
UASDK_UNUSED(locales);
UASDK_UNUSED(indexRange);
UASDK_UNUSED(transactionId);
timeoutHint_ = timeoutHint;
if (!node.is_set() || !completedCallback.is_set())
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadInvalidArgument);
}
Status_t status;
//For backup in case of error
#if (UASDK_USE_DATA_ACCESS_HELPERS > 0)
IntrusivePtr_t<DataValue_t> backup;
if (dataValue_.is_set())
{
backup.reset(new SafeRefCount_t<DataValue_t>);
if (!backup.is_set())
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadOutOfMemory);
}
status = backup->CopyFrom(*dataValue_);
if (status.IsBad())
{
UASDK_RETURN_BAD_STATUS(status.Value());
}
}
#endif //#if (UASDK_USE_DATA_ACCESS_HELPERS > 0)
CallApplicationLayerRead();
if (statusCode.IsBad() || (!deferralHandle && !dataValue_.is_set()) )
{
UASDK_RETURN_BAD_STATUS(statusCode.Value());
}
#if ((UASDK_USE_HELPERS > 0) && (UASDK_USE_DATA_ACCESS_HELPERS > 0))
//Do the range check first. If there is any Instrument range property
{
IntrusivePtr_t<IVariableNode_t> instrumentRangeNode = GetInstrumentRangePropertyNode(*node, status);
if (instrumentRangeNode.is_set() && status.IsGood())
{
status = IsInRange(*instrumentRangeNode, *dataValue_);
if (status.IsBad())
{
dataValue_ = backup;
UASDK_RETURN_BAD_STATUS(status.Value());
}
}
}
#endif //#if (UASDK_USE_DATA_ACCESS_HELPERS > 0)
if(!deferralHandle)
{
IntrusivePtr_t<DataValue_t> temp (new SafeRefCount_t<DataValue_t>());
if(!temp.is_set())
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadOutOfMemory);
}
status = temp->CopyFrom(*dataValue_);
if(status.IsBad())
{
UASDK_RETURN_BAD_STATUS(statusCode.Value());
}
return completedCallback->ReadValueAttributeCompleted(temp);
}
if(!readCompletedCallback.is_set())
{
readCompletedCallback = completedCallback;
}
return OpcUa_Good;
#else
UASDK_UNUSED(node);
UASDK_UNUSED(maxAge);
UASDK_UNUSED(setSourceTimestamp);
UASDK_UNUSED(locales);
UASDK_UNUSED(indexRange);
UASDK_UNUSED(transactionId);
UASDK_UNUSED(timeoutHint);
UASDK_UNUSED(completedCallback);
return OpcUa_BadNotReadable;
#endif //0
}
Status_t ValueAttributeReaderWriterForCAPI_t::ReadValueAttribute(
const IVariableNode_t& node,
uint32_t maxAge,
bool setSourceTimestamp,
const ArrayUA_t<String_t>& locales,
const Array_t<IndexRange_t>& indexRange,
uint32_t transactionId,
uint32_t timeoutHint,
IntrusivePtr_t<DataValue_t>& dataValue,
IntrusivePtr_t<DiagnosticInfo_t>& diagnosticInfo)
{
#if 0 // Enable this from next release
UASDK_UNUSED(node);
UASDK_UNUSED(maxAge);
UASDK_UNUSED(setSourceTimestamp);
UASDK_UNUSED(locales);
UASDK_UNUSED(indexRange);
UASDK_UNUSED(transactionId);
UASDK_UNUSED(timeoutHint);
UASDK_UNUSED(dataValue);
UASDK_UNUSED(diagnosticInfo);
return OpcUa_BadNotReadable;
#else
UASDK_UNUSED(node);
UASDK_UNUSED(maxAge);
UASDK_UNUSED(setSourceTimestamp);
UASDK_UNUSED(locales);
UASDK_UNUSED(transactionId);
UASDK_UNUSED(diagnosticInfo);
timeoutHint_ = timeoutHint;
Status_t status;
//For backup in case of error
#if (UASDK_USE_DATA_ACCESS_HELPERS > 0)
IntrusivePtr_t<DataValue_t> backup;
if (dataValue_.is_set())
{
backup.reset(new SafeRefCount_t<DataValue_t>);
if (!backup.is_set())
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadOutOfMemory);
}
status = backup->CopyFrom(*dataValue_);
if (status.IsBad())
{
UASDK_RETURN_BAD_STATUS(status.Value());
}
}
#endif //#if (UASDK_USE_DATA_ACCESS_HELPERS > 0)
CallApplicationLayerRead();
if (statusCode.IsBad() || !dataValue_.is_set())
{
UASDK_RETURN_BAD_STATUS(statusCode.Value());
}
#if ((UASDK_USE_HELPERS > 0) && (UASDK_USE_DATA_ACCESS_HELPERS > 0))
//Do the range check first. If there is any Instrument range property
{
IntrusivePtr_t<IVariableNode_t> instrumentRangeNode = GetInstrumentRangePropertyNode(node, status);
if (instrumentRangeNode.is_set() && status.IsGood())
{
status = IsInRange(*instrumentRangeNode, *dataValue_);
if (status.IsBad())
{
dataValue_ = backup;
UASDK_RETURN_BAD_STATUS(status.Value());
}
}
}
#endif //#if (UASDK_USE_DATA_ACCESS_HELPERS > 0)
dataValue.reset(new SafeRefCount_t<DataValue_t>());
if (!dataValue.is_set())
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadOutOfMemory);
}
return dataValue->WriteSubsetFrom(indexRange, *dataValue_);
#endif //0
}
bool ValueAttributeReaderWriterForCAPI_t::CanWriteValueSynchronously(const IVariableNode_t& node)
{
UASDK_UNUSED(node);
return true;
}
Status_t ValueAttributeReaderWriterForCAPI_t::WriteValueAttributeBegin(
IntrusivePtr_t<IVariableNode_t>& node,
IntrusivePtr_t<const ArrayRef_t<IndexRange_t> > indexRange,
IntrusivePtr_t<const DataValue_t> dataValue,
uint32_t transactionId,
uint32_t timeoutHint,
IntrusivePtr_t<ICallbackNodeValueAttributeAccessCompleted_t>& completedCallback)
{
UASDK_UNUSED(node);
UASDK_UNUSED(indexRange);
UASDK_UNUSED(dataValue);
UASDK_UNUSED(transactionId);
UASDK_UNUSED(timeoutHint);
UASDK_UNUSED(completedCallback);
UASDK_RETURN_BAD_STATUS(OpcUa_BadNotSupported);
}
Status_t ValueAttributeReaderWriterForCAPI_t::WriteValueAttribute(
IVariableNode_t& node,
const Array_t<IndexRange_t>& indexRange,
IntrusivePtr_t<const DataValue_t> dataValue,
uint32_t transactionId,
uint32_t timeoutHint,
IntrusivePtr_t<DiagnosticInfo_t>& diagnosticInfo)
{
UASDK_UNUSED(node);
UASDK_UNUSED(transactionId);
UASDK_UNUSED(timeoutHint);
UASDK_UNUSED(diagnosticInfo);
if (!dataValue_.is_set() || !dataValue.is_set())
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadInvalidArgument);
}
Status_t status;
#if ((UASDK_USE_HELPERS > 0) && (UASDK_USE_DATA_ACCESS_HELPERS > 0))
//Do the range check first. If there is any Instrument range property
{
IntrusivePtr_t<IVariableNode_t> instrumentRangeNode = GetInstrumentRangePropertyNode(node, status);
if (instrumentRangeNode.is_set() && status.IsGood())
{
status = IsInRange(*instrumentRangeNode, *dataValue);
if (status.IsBad())
{
UASDK_RETURN_BAD_STATUS(status.Value());
}
}
}
#endif //#if (UASDK_USE_DATA_ACCESS_HELPERS > 0)
//For backup in case of error
IntrusivePtr_t<DataValue_t> backup(new SafeRefCount_t<DataValue_t>);
if (!backup.is_set())
{
UASDK_RETURN_BAD_STATUS(OpcUa_BadOutOfMemory);
}
{
AutoLock_t lk(lock);
status = backup->CopyFrom(*dataValue_);
if (status.IsBad())
{
UASDK_RETURN_BAD_STATUS(status.Value());
}
status = dataValue_->WriteSubsetFrom(indexRange, *dataValue);
if (status.IsBad())
{
dataValue_ = backup;
UASDK_RETURN_BAD_STATUS(status.Value());
}
}
indexRange_ = indexRange;
UAServer_Callback_write(nodeHandle, valueType, status.Value(), maxArrayLength, (uintptr_t)this);
//If there was error while writing, keep the old value!
if (statusCode.IsBad())
{
dataValue_ = backup;
}
return statusCode;
}
} //namespace uasdk
#endif // UASDK_INCLUDE_SERVER_C_API
#endif //(UASDK_INCLUDE_SERVER)
| 25.677738
| 181
| 0.703513
|
beeond
|
da0de7f78b4a0407e6d09e7e4abac305eb5be01d
| 12,199
|
cpp
|
C++
|
test/master-keys-test.cpp
|
1984not-GmbH/molch
|
c7f1f646c800ef3388f36e8805a3b94d33d85b12
|
[
"MIT"
] | 15
|
2016-04-12T17:12:19.000Z
|
2019-08-14T17:46:17.000Z
|
test/master-keys-test.cpp
|
1984not-GmbH/molch
|
c7f1f646c800ef3388f36e8805a3b94d33d85b12
|
[
"MIT"
] | 63
|
2016-03-22T14:35:31.000Z
|
2018-07-04T22:17:07.000Z
|
test/master-keys-test.cpp
|
1984not-GmbH/molch
|
c7f1f646c800ef3388f36e8805a3b94d33d85b12
|
[
"MIT"
] | 1
|
2017-08-17T09:27:30.000Z
|
2017-08-17T09:27:30.000Z
|
/*
* Molch, an implementation of the axolotl ratchet based on libsodium
*
* ISC License
*
* Copyright (C) 2015-2016 1984not Security GmbH
* Author: Max Bruckner (FSMaxB)
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <cstdio>
#include <cstdlib>
#include <sodium.h>
#include <memory>
#include <iostream>
#include <string_view>
#include "../lib/master-keys.hpp"
#include "molch/constants.h"
#include "utils.hpp"
#include "inline-utils.hpp"
#include "exception.hpp"
using namespace Molch;
static void protobuf_export(
MasterKeys& keys,
Buffer& public_signing_key_buffer,
Buffer& private_signing_key_buffer,
Buffer& public_identity_key_buffer,
Buffer& private_identity_key_buffer) {
Arena arena;
TRY_WITH_RESULT(exported_result, keys.exportProtobuf(arena));
const auto& exported{exported_result.value()};
//copy keys to buffer
//public signing key
auto public_signing_key_proto_size{molch__protobuf__key__get_packed_size(exported.public_signing_key)};
public_signing_key_buffer = Buffer{public_signing_key_proto_size, 0};
TRY_VOID(public_signing_key_buffer.setSize(molch__protobuf__key__pack(exported.public_signing_key, byte_to_uchar(public_signing_key_buffer.data()))));
if (public_signing_key_buffer.size() != public_signing_key_proto_size) {
throw Molch::Exception{status_type::EXPORT_ERROR, "Failed to export public signing key."};
}
//private signing key
auto private_signing_key_proto_size{molch__protobuf__key__get_packed_size(exported.private_signing_key)};
private_signing_key_buffer = Buffer{private_signing_key_proto_size, 0};
TRY_VOID(private_signing_key_buffer.setSize(molch__protobuf__key__pack(exported.private_signing_key, byte_to_uchar(private_signing_key_buffer.data()))));
if (private_signing_key_buffer.size() != private_signing_key_proto_size) {
throw Molch::Exception{status_type::EXPORT_ERROR, "Failed to export private signing key."};
}
//public identity key
auto public_identity_key_proto_size{molch__protobuf__key__get_packed_size(exported.public_identity_key)};
public_identity_key_buffer = Buffer{public_identity_key_proto_size, 0};
TRY_VOID(public_identity_key_buffer.setSize(molch__protobuf__key__pack(exported.public_identity_key, byte_to_uchar(public_identity_key_buffer.data()))));
if (public_identity_key_buffer.size() != public_identity_key_proto_size) {
throw Molch::Exception{status_type::EXPORT_ERROR, "Failed to export public identity key."};
}
//private identity key
auto private_identity_key_proto_size{molch__protobuf__key__get_packed_size(exported.private_identity_key)};
private_identity_key_buffer = Buffer{private_identity_key_proto_size, 0};
TRY_VOID(private_identity_key_buffer.setSize(molch__protobuf__key__pack(exported.private_identity_key, byte_to_uchar(private_identity_key_buffer.data()))));
if (private_identity_key_buffer.size() != private_identity_key_proto_size) {
throw Molch::Exception{status_type::EXPORT_ERROR, "Failed to export private identity key."};
}
}
static MasterKeys protobuf_import(
Arena& pool,
const Buffer& public_signing_key_buffer,
const Buffer& private_signing_key_buffer,
const Buffer& public_identity_key_buffer,
const Buffer& private_identity_key_buffer) {
auto pool_protoc_allocator{pool.getProtobufCAllocator()};
//unpack the protobuf-c buffers
auto public_signing_key{molch__protobuf__key__unpack(
&pool_protoc_allocator,
public_signing_key_buffer.size(),
byte_to_uchar(public_signing_key_buffer.data()))};
if (public_signing_key == nullptr) {
throw Molch::Exception{status_type::PROTOBUF_UNPACK_ERROR, "Failed to unpack public signing key from protobuf."};
}
auto private_signing_key{molch__protobuf__key__unpack(
&pool_protoc_allocator,
private_signing_key_buffer.size(),
byte_to_uchar(private_signing_key_buffer.data()))};
if (private_signing_key == nullptr) {
throw Molch::Exception{status_type::PROTOBUF_UNPACK_ERROR, "Failed to unpack private signing key from protobuf."};
}
auto public_identity_key{molch__protobuf__key__unpack(
&pool_protoc_allocator,
public_identity_key_buffer.size(),
byte_to_uchar(public_identity_key_buffer.data()))};
if (public_identity_key == nullptr) {
throw Molch::Exception{status_type::PROTOBUF_UNPACK_ERROR, "Failed to unpack public identity key from protobuf."};
}
auto private_identity_key{molch__protobuf__key__unpack(
&pool_protoc_allocator,
private_identity_key_buffer.size(),
byte_to_uchar(private_identity_key_buffer.data()))};
if (private_identity_key == nullptr) {
throw Molch::Exception{status_type::PROTOBUF_UNPACK_ERROR, "Failed to unpack private identity key from protobuf."};
}
TRY_WITH_RESULT(keys_result, MasterKeys::import(
*public_signing_key,
*private_signing_key,
*public_identity_key,
*private_identity_key));
return std::move(keys_result.value());
}
int main() {
try {
TRY_VOID(Molch::sodium_init());
//create the unspiced master keys
TRY_WITH_RESULT(unspiced_master_keys_result, MasterKeys::create());
auto& unspiced_master_keys{unspiced_master_keys_result.value()};
//get the public keys
PublicSigningKey public_signing_key{unspiced_master_keys.getSigningKey()};
PublicKey public_identity_key{unspiced_master_keys.getIdentityKey()};
//print the keys
std::cout << "Signing keypair:\n";
std::cout << "Public:\n";
std::cout << unspiced_master_keys.getSigningKey();
std::cout << "\nPrivate:\n";
{
MasterKeys::Unlocker unlocker{unspiced_master_keys};
TRY_WITH_RESULT(private_signing_key, unspiced_master_keys.getPrivateSigningKey());
std::cout << private_signing_key.value();
}
std::cout << "\n\nIdentity keys:\n";
std::cout << "Public:\n";
std::cout << unspiced_master_keys.getIdentityKey();
std::cout << "\nPrivate:\n";
{
MasterKeys::Unlocker unlocker{unspiced_master_keys};
TRY_WITH_RESULT(private_identity_key, unspiced_master_keys.getPrivateIdentityKey());
std::cout << *private_identity_key.value();
}
//check the exported public keys
if (public_signing_key != unspiced_master_keys.getSigningKey()) {
throw Molch::Exception{status_type::INCORRECT_DATA, "Exported public signing key doesn't match."};
}
if (public_identity_key != unspiced_master_keys.getIdentityKey()) {
throw Molch::Exception{status_type::INCORRECT_DATA, "Exported public identity key doesn't match."};
}
//create the spiced master keys
Buffer seed{";a;awoeih]]pquw4t[spdif\\aslkjdf;'ihdg#)%!@))%)#)(*)@)#)h;kuhe[orih;o's':ke';sa'd;kfa';;.calijv;a/orq930u[sd9f0u;09[02;oasijd;adk"};
TRY_WITH_RESULT(spiced_master_keys_result, MasterKeys::create(seed));
auto& spiced_master_keys{spiced_master_keys_result.value()};
public_signing_key = spiced_master_keys.getSigningKey();
public_identity_key = spiced_master_keys.getIdentityKey();
//print the keys
std::cout << "Signing keypair:\n";
std::cout << "Public:\n";
std::cout << spiced_master_keys.getSigningKey() << std::endl;
std::cout << "Private:\n";
{
MasterKeys::Unlocker unlocker{spiced_master_keys};
TRY_WITH_RESULT(private_signing_key, spiced_master_keys.getPrivateSigningKey());
std::cout << private_signing_key.value() << '\n';
}
std::cout << "\nIdentity keys:\n";
std::cout << "Public:\n";
std::cout << spiced_master_keys.getIdentityKey() << std::endl;
std::cout << "Private:\n";
{
MasterKeys::Unlocker unlocker{spiced_master_keys};
TRY_WITH_RESULT(private_identity_key, spiced_master_keys.getPrivateIdentityKey());
std::cout << *private_identity_key.value();
}
//check the exported public keys
if (public_signing_key != spiced_master_keys.getSigningKey()) {
throw Molch::Exception{status_type::INCORRECT_DATA, "Exported public signing key doesn't match."};
}
if (public_identity_key != spiced_master_keys.getIdentityKey()) {
throw Molch::Exception{status_type::INCORRECT_DATA, "Exported public identity key doesn't match."};
}
//sign some data
Buffer data{"This is some data to be signed."};
std::cout << "Data to be signed.\n";
std::cout << std::string_view(byte_to_char(data.data()), data.size()) << '\n';
TRY_WITH_RESULT(signed_data_result, spiced_master_keys.sign(data));
const auto& signed_data{signed_data_result.value()};
std::cout << "Signed data:\n";
std::cout << signed_data;
//now check the signature
Buffer unwrapped_data{100, 0};
unsigned long long unwrapped_data_length;
auto status{crypto_sign_open(
byte_to_uchar(unwrapped_data.data()),
&unwrapped_data_length,
byte_to_uchar(signed_data.data()),
signed_data.size(),
byte_to_uchar(public_signing_key.data()))};
if (status != 0) {
throw Molch::Exception{status_type::VERIFY_ERROR, "Failed to verify signature."};
}
TRY_VOID(unwrapped_data.setSize(static_cast<size_t>(unwrapped_data_length)));
std::cout << "\nSignature was successfully verified!\n";
//Test Export to Protobuf-C
std::cout << "Export to Protobuf-C:\n";
//export buffers
Buffer protobuf_export_public_signing_key;
Buffer protobuf_export_private_signing_key;
Buffer protobuf_export_public_identity_key;
Buffer protobuf_export_private_identity_key;
protobuf_export(
spiced_master_keys,
protobuf_export_public_signing_key,
protobuf_export_private_signing_key,
protobuf_export_public_identity_key,
protobuf_export_private_identity_key);
std::cout << "Public signing key:\n";
std::cout << protobuf_export_public_signing_key << "\n\n";
std::cout << "Private signing key:\n";
std::cout << protobuf_export_private_signing_key << "\n\n";
std::cout << "Public identity key:\n";
std::cout << protobuf_export_public_identity_key << "\n\n";
std::cout << "Private identity key:\n";
std::cout << protobuf_export_private_identity_key << "\n\n";
//import again
std::cout << "Import from Protobuf-C:\n";
Arena pool;
auto imported_master_keys{protobuf_import(
pool,
protobuf_export_public_signing_key,
protobuf_export_private_signing_key,
protobuf_export_public_identity_key,
protobuf_export_private_identity_key)};
//export again
Buffer protobuf_second_export_public_signing_key;
Buffer protobuf_second_export_private_signing_key;
Buffer protobuf_second_export_public_identity_key;
Buffer protobuf_second_export_private_identity_key;
protobuf_export(
imported_master_keys,
protobuf_second_export_public_signing_key,
protobuf_second_export_private_signing_key,
protobuf_second_export_public_identity_key,
protobuf_second_export_private_identity_key);
//now compare
if (protobuf_export_public_signing_key != protobuf_second_export_public_signing_key) {
throw Molch::Exception{status_type::INCORRECT_DATA, "The public signing keys do not match."};
}
if (protobuf_export_private_signing_key != protobuf_second_export_private_signing_key) {
throw Molch::Exception{status_type::INCORRECT_DATA, "The private signing keys do not match."};
}
if (protobuf_export_public_identity_key != protobuf_second_export_public_identity_key) {
throw Molch::Exception{status_type::INCORRECT_DATA, "The public identity keys do not match."};
}
if (protobuf_export_private_identity_key != protobuf_second_export_private_identity_key) {
throw Molch::Exception{status_type::INCORRECT_DATA, "The private identity keys do not match."};
}
std::cout << "Successfully exported to Protobuf-C and imported again.";
} catch (const std::exception& exception) {
std::cerr << exception.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| 39.866013
| 157
| 0.774818
|
1984not-GmbH
|
da0eda4b7318eb4e4776d0e61b558b3db1fe1de2
| 442
|
cpp
|
C++
|
5-10-21/Odd_even_linked_list.cpp
|
ahanavish/GDSC-DSA-Interview-Preparation
|
d6cfa402dbbe8ed4f5b96f51e2e0fc0e2eabbdaf
|
[
"MIT"
] | null | null | null |
5-10-21/Odd_even_linked_list.cpp
|
ahanavish/GDSC-DSA-Interview-Preparation
|
d6cfa402dbbe8ed4f5b96f51e2e0fc0e2eabbdaf
|
[
"MIT"
] | null | null | null |
5-10-21/Odd_even_linked_list.cpp
|
ahanavish/GDSC-DSA-Interview-Preparation
|
d6cfa402dbbe8ed4f5b96f51e2e0fc0e2eabbdaf
|
[
"MIT"
] | 1
|
2021-11-29T06:10:48.000Z
|
2021-11-29T06:10:48.000Z
|
// https://leetcode.com/problems/odd-even-linked-list/
class Solution {
public:
ListNode* oddEvenList(ListNode* head)
{
if(head==NULL)
return head;
ListNode* odd=head, *even=head->next, *even_start=head->next;
while(even && even->next){
odd->next=odd->next->next;
even->next=even->next->next;
odd=odd->next;
even=even->next;
}
odd->next=even_start;
return head;
}
};
| 21.047619
| 65
| 0.588235
|
ahanavish
|
da11d5ef09f6fd569100633298f01892a9bd1bc1
| 36,037
|
cpp
|
C++
|
src/ImageProcessing/RoadSignDetection/RoadSignDetectionAdapter.cpp
|
FAUtonOHM/AADC_2016
|
ed00b45d53fadb58e26a6879a17eaf4c749da4a5
|
[
"BSD-4-Clause"
] | null | null | null |
src/ImageProcessing/RoadSignDetection/RoadSignDetectionAdapter.cpp
|
FAUtonOHM/AADC_2016
|
ed00b45d53fadb58e26a6879a17eaf4c749da4a5
|
[
"BSD-4-Clause"
] | null | null | null |
src/ImageProcessing/RoadSignDetection/RoadSignDetectionAdapter.cpp
|
FAUtonOHM/AADC_2016
|
ed00b45d53fadb58e26a6879a17eaf4c749da4a5
|
[
"BSD-4-Clause"
] | null | null | null |
/**
* Copyright (c)
* Audi Autonomous Driving Cup. TEAM FAUtonOHM. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software must display the following acknowledgement: This product includes software developed by the Audi AG and its contributors for Audi Autonomous Driving Cup.
* 4. Neither the name of Audi 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 AUDI AG 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 AUDI AG 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.
*
**********************************************************************
* $Author:: schoen $ $Date:: 2016-02-17 #$
* $Author:: fink $ $Date:: 2016-03-11 #$
**********************************************************************/
#include "stdafx.h"
#include "RoadSignDetectionAdapter.h"
#include <roadSign_enums.h>
#include <iostream>
using namespace cv;
using namespace aruco;
#include "CVMath.h"
#include <set>
ADTF_FILTER_PLUGIN("RoadSign", OID_ADTF_ROADSIGNEDETECTIONFILTER, RoadSignDetectionAdapter)
#define RSD_PITCH "Camera position/rotation::pitch"
#define RSD_PITCH_STORAGE "Camera position/rotation::pitch angle file"
#define RSD_MARKER_ANGLE_LIMIT_XY "Marker::angle limit X Y (degree)"
#define RSD_MARKER_ANGLE_LOWER_LIMIT_Z "Marker::angle lower limit Z (degree)"
#define RSD_MARKER_ANGLE_UPPER_LIMIT_Z "Marker::angle upper limit Z (degree)"
#define RSD_MARKER_LIMIT_Y "Marker::limit Y"
#define RSD_MARKER_STEERING_LIMIT "Marker::Steering angle limit"
#define RSD_MARKER_DISTANCE_LIMIT "Marker::distance search limit"
#define RSD_MARKER_REDUCE_RESOLUTION "Marker::reduce image resolution"
#define RSD_START_COMMAND "Debug::start action command"
#define RSD_DEBUG_TO_CONSOLE "Debug::output to console"
#define RSD_EXECTIME_TO_CONSOLE "Debug::print execution time to console"
#define RSD_ARUCO_DICTIONARY "Aruco::Dictionary File For Markers"
#define RSD_ARUCO_CAMERA_CALIBRATION "Aruco::Calibration File for used Camera"
#define RSD_ARUCO_SIZE_OF_MARKERS "Aruco::Size of road sign markers"
RoadSignDetectionAdapter::RoadSignDetectionAdapter(const tChar* __info) :
cAsyncDataTriggeredFilter(__info) {
SetPropertyFloat(RSD_PITCH, 0);
SetPropertyFloat(RSD_PITCH NSSUBPROP_MAX, 0);
SetPropertyFloat(RSD_PITCH NSSUBPROP_MIN, -20);
SetPropertyStr(RSD_PITCH NSSUBPROP_DESCRIPTION, "default angle of the camera in degree. This will be overwritten by the pitch angle file");
SetPropertyStr(RSD_PITCH_STORAGE, "../../../../../Camera_Pitch.txt");
SetPropertyBool(RSD_PITCH_STORAGE NSSUBPROP_FILENAME, tTrue);
SetPropertyStr(RSD_PITCH_STORAGE NSSUBPROP_DESCRIPTION, "file which is used for storing the pitch angle");
SetPropertyFloat(RSD_MARKER_ANGLE_LIMIT_XY, 30);
SetPropertyFloat(RSD_MARKER_ANGLE_LIMIT_XY NSSUBPROP_MAX, 45);
SetPropertyFloat(RSD_MARKER_ANGLE_LIMIT_XY NSSUBPROP_MIN, 0);
SetPropertyStr(RSD_MARKER_ANGLE_LIMIT_XY NSSUBPROP_DESCRIPTION, "in degree");
SetPropertyFloat(RSD_MARKER_ANGLE_LOWER_LIMIT_Z, 30);
SetPropertyFloat(RSD_MARKER_ANGLE_LOWER_LIMIT_Z NSSUBPROP_MAX, 90);
SetPropertyFloat(RSD_MARKER_ANGLE_LOWER_LIMIT_Z NSSUBPROP_MIN, -90);
SetPropertyStr(RSD_MARKER_ANGLE_LOWER_LIMIT_Z NSSUBPROP_DESCRIPTION, "in degree");
SetPropertyFloat(RSD_MARKER_ANGLE_UPPER_LIMIT_Z, 70);
SetPropertyFloat(RSD_MARKER_ANGLE_UPPER_LIMIT_Z NSSUBPROP_MAX, 90);
SetPropertyFloat(RSD_MARKER_ANGLE_UPPER_LIMIT_Z NSSUBPROP_MIN, 0);
SetPropertyStr(RSD_MARKER_ANGLE_UPPER_LIMIT_Z NSSUBPROP_DESCRIPTION, "in degree");
SetPropertyFloat(RSD_MARKER_LIMIT_Y, -0.2);
SetPropertyFloat(RSD_MARKER_LIMIT_Y NSSUBPROP_MAX, 0);
SetPropertyFloat(RSD_MARKER_LIMIT_Y NSSUBPROP_MIN, -1);
SetPropertyStr(RSD_MARKER_LIMIT_Y NSSUBPROP_DESCRIPTION, "in meter top is negative");
SetPropertyFloat(RSD_MARKER_STEERING_LIMIT, 10);
SetPropertyFloat(RSD_MARKER_STEERING_LIMIT NSSUBPROP_MAX, 15);
SetPropertyFloat(RSD_MARKER_STEERING_LIMIT NSSUBPROP_MIN, -15);
SetPropertyStr(RSD_MARKER_STEERING_LIMIT NSSUBPROP_DESCRIPTION, "Steering angle limits for RoadSign Detection");
SetPropertyFloat(RSD_MARKER_DISTANCE_LIMIT, 2.95);
SetPropertyFloat(RSD_MARKER_DISTANCE_LIMIT NSSUBPROP_MAX, 10);
SetPropertyFloat(RSD_MARKER_DISTANCE_LIMIT NSSUBPROP_MIN, 0);
SetPropertyBool(RSD_MARKER_REDUCE_RESOLUTION, tTrue);
SetPropertyStr(RSD_MARKER_REDUCE_RESOLUTION NSSUBPROP_DESCRIPTION, "Reduce resolution of input video stream before detecting aruco markers");
SetPropertyInt(RSD_START_COMMAND, 0);
SetPropertyStr(RSD_START_COMMAND NSSUBPROP_DESCRIPTION,
"If not 0, this is the start command");
SetPropertyBool(RSD_DEBUG_TO_CONSOLE, tFalse);
SetPropertyStr(RSD_DEBUG_TO_CONSOLE NSSUBPROP_DESCRIPTION,
"If enabled additional debug information is printed to the console");
SetPropertyBool(RSD_EXECTIME_TO_CONSOLE, tFalse);
SetPropertyStr(RSD_EXECTIME_TO_CONSOLE NSSUBPROP_DESCRIPTION,
"If enabled execution time of aruco marker detection is printed to the console");
SetPropertyStr(RSD_ARUCO_DICTIONARY, "../../../../configuration_files/roadsign.yml");
SetPropertyBool(RSD_ARUCO_DICTIONARY NSSUBPROP_FILENAME, tTrue);
SetPropertyStr(RSD_ARUCO_DICTIONARY NSSUBPROP_FILENAME NSSUBSUBPROP_EXTENSIONFILTER, "YML Files (*.yml)");
SetPropertyStr(RSD_ARUCO_DICTIONARY NSSUBPROP_DESCRIPTION,
"Here you have to set the dictionary file which holds the marker IDs and their content");
SetPropertyStr(RSD_ARUCO_CAMERA_CALIBRATION, "../../../../configuration_files/xtionIntrinsicCalib.yml");
SetPropertyBool(RSD_ARUCO_CAMERA_CALIBRATION NSSUBPROP_FILENAME, tTrue);
SetPropertyStr(RSD_ARUCO_CAMERA_CALIBRATION NSSUBPROP_FILENAME NSSUBSUBPROP_EXTENSIONFILTER, "YML Files (*.yml)");
SetPropertyStr(RSD_ARUCO_CAMERA_CALIBRATION NSSUBPROP_DESCRIPTION,
"Here you have to set the file with calibration parameters of the used camera");
SetPropertyFloat(RSD_ARUCO_SIZE_OF_MARKERS, 0.1f);
SetPropertyStr(RSD_ARUCO_SIZE_OF_MARKERS NSSUBPROP_DESCRIPTION, "Size (length of one side) of markers in meter");
}
RoadSignDetectionAdapter::~RoadSignDetectionAdapter() {
}
tResult RoadSignDetectionAdapter::Init(tInitStage eStage, __exception)
{
RETURN_IF_FAILED(cAsyncDataTriggeredFilter::Init(eStage, __exception_ptr));
if (eStage == StageFirst)
{
tTrafficSign.StageFirst(__exception_ptr);
tSignalValueSteering.StageFirst(__exception_ptr);
tSignalValueSpeed.StageFirst(__exception_ptr);
tActionStruct.StageFirst(__exception_ptr);
tFeedbackStruct.StageFirst(__exception_ptr);
RETURN_IF_FAILED(steeringInput.Create("steering", tSignalValueSteering.GetMediaType(), static_cast<IPinEventSink*> (this)));
RETURN_IF_FAILED(RegisterPin(&steeringInput));
RETURN_IF_FAILED(speedInput.Create("speed", tSignalValueSpeed.GetMediaType(), static_cast<IPinEventSink*> (this)));
RETURN_IF_FAILED(RegisterPin(&speedInput));
RETURN_IF_FAILED(actionInput.Create("action", tActionStruct.GetMediaType(), static_cast<IPinEventSink*> (this)));
RETURN_IF_FAILED(RegisterPin(&actionInput));
RETURN_IF_FAILED(trafficSignOutput.Create("sign", tTrafficSign.GetMediaType(), 0));
RETURN_IF_FAILED(RegisterPin(&trafficSignOutput));
RETURN_IF_FAILED(feedbackOutput.Create("feedback", tFeedbackStruct.GetMediaType(), 0));
RETURN_IF_FAILED(RegisterPin(&feedbackOutput));
RETURN_IF_FAILED(videoInput.Create("Video_RGB",IPin::PD_Input, static_cast<IPinEventSink*>(this)));
RETURN_IF_FAILED(RegisterPin(&videoInput));
RETURN_IF_FAILED(videoOutput.Create("RGB_Debug", IPin::PD_Output, static_cast<IPinEventSink*>(this)));
RETURN_IF_FAILED(RegisterPin(&videoOutput));
}
else if (eStage == StageNormal)
{
// debugging things
debugMode = tFalse;
debugExecutionTime = tFalse;
debugModeEnabled = GetPropertyBool(RSD_DEBUG_TO_CONSOLE);
thresholds.COS_ANGLE_LIMIT_XY = cos(GetPropertyFloat(RSD_MARKER_ANGLE_LIMIT_XY) / 180 *CV_PI);
thresholds.COS_ANGLE_UPPER_LIMIT_Z = cos(GetPropertyFloat(RSD_MARKER_ANGLE_UPPER_LIMIT_Z) / 180 *CV_PI);
thresholds.COS_ANGLE_LOWER_LIMIT_Z = cos(GetPropertyFloat(RSD_MARKER_ANGLE_LOWER_LIMIT_Z) / 180 *CV_PI);
thresholds.MAX_DISTANCE = GetPropertyFloat(RSD_MARKER_DISTANCE_LIMIT);
thresholds.STEERING_LIMIT = GetPropertyFloat(RSD_MARKER_STEERING_LIMIT) / 180 * CV_PI;
m_bReduceImageResolution = GetPropertyBool(RSD_MARKER_REDUCE_RESOLUTION);
debugExecutionTime = GetPropertyBool(RSD_EXECTIME_TO_CONSOLE);
thresholds.CAMERA_Y_LIMIT = GetPropertyFloat(RSD_MARKER_LIMIT_Y);
// camera calibration
cameraPitch = GetPropertyFloat(RSD_PITCH);
filePitch = GetPropertyStr(RSD_PITCH_STORAGE);
ReadFromFile(&cameraPitch);
// for trajectory estimation
lastSpeed = 0;
lastSteeringAngle = 0;
lastPrioritySign.ui32_filterID = F_ROAD_SIGNS;
lastPrioritySign.ui32_status = FB_RS_CROSSING_SIGN_NONE;
tInt32 startCommand = GetPropertyInt(RSD_START_COMMAND);
if(3000 <= startCommand && startCommand < 4000) {
actionSub.enabled = tTrue;
actionSub.started = tTrue;
actionSub.command = startCommand;
}
cameraParamsLoaded = tFalse;
markerSize = static_cast<tFloat32>(GetPropertyFloat(RSD_ARUCO_SIZE_OF_MARKERS));
//Get path of marker configuration file
cFilename fileConfig = GetPropertyStr(RSD_ARUCO_DICTIONARY);
//create absolute path for marker configuration file
ADTF_GET_CONFIG_FILENAME(fileConfig);
fileConfig = fileConfig.CreateAbsolutePath(".");
//check if marker configuration file exits
if (fileConfig.IsEmpty() || !(cFileSystem::Exists(fileConfig))) {
LOG_ERROR("RoadSign: Dictionary File for Markers not found");
RETURN_ERROR(ERR_INVALID_FILE);
} else {
//try to read the marker configuration file
if(dictionary.fromFile(std::string(fileConfig))==false) {
LOG_ERROR("RoadSign: Dictionary File for Markers could not be read");
RETURN_ERROR(ERR_INVALID_FILE);
} if(dictionary.size()==0) {
RETURN_ERROR(ERR_INVALID_FILE);
LOG_ERROR("RoadSign: Dictionary File does not contain valid markers or could not be read sucessfully");
}
//set marker configuration file to highlyreliable markers class
if (!(HighlyReliableMarkers::loadDictionary(dictionary)==tTrue)) {
LOG_ERROR("RoadSign: Dictionary File could not be read for highly reliable markers");
}
}
//Get path of calibration file with camera paramters
cFilename fileCalibration = GetPropertyStr(RSD_ARUCO_CAMERA_CALIBRATION);
//Get path of calibration file with camera paramters
ADTF_GET_CONFIG_FILENAME(fileCalibration);
fileCalibration = fileCalibration.CreateAbsolutePath(".");
//check if calibration file with camera paramters exits
if (fileCalibration.IsEmpty() || !(cFileSystem::Exists(fileCalibration))) {
LOG_ERROR("RoadSign: Calibration File for camera not found");
} else {
// read the calibration file with camera paramters exits and save to member variable
cameraParameters.readFromXMLFile(fileCalibration.GetPtr());
cv::FileStorage camera_data (fileCalibration.GetPtr(),cv::FileStorage::READ);
camera_data ["camera_matrix"] >> intrinsics;
camera_data ["distortion_coefficients"] >> distortion;
cameraParamsLoaded = tTrue;
// Reduce Image resolution: 640x480 -> 320x240 (change camera matrix)
if(m_bReduceImageResolution) {
cameraParameters_downsampled = cameraParameters;
cameraParameters_downsampled.CameraMatrix.at<tFloat32>(0,0) = cameraParameters.CameraMatrix.at<tFloat32>(0,0)/2;
cameraParameters_downsampled.CameraMatrix.at<tFloat32>(0,2) = cameraParameters.CameraMatrix.at<tFloat32>(0,2)/2;
cameraParameters_downsampled.CameraMatrix.at<tFloat32>(1,1) = cameraParameters.CameraMatrix.at<tFloat32>(1,1)/2;
cameraParameters_downsampled.CameraMatrix.at<tFloat32>(1,2) = cameraParameters.CameraMatrix.at<tFloat32>(1,2)/2;
cameraParameters_downsampled.CamSize.height = cameraParameters.CamSize.height/2;
cameraParameters_downsampled.CamSize.width = cameraParameters.CamSize.width/2;
//LOG_WARNING(cString::Format("RoadSign: Orig fx: %f, cx: %f, fy: %f, cy: %f",cameraParameters.CameraMatrix.at<tFloat32>(0,0),cameraParameters.CameraMatrix.at<tFloat32>(0,2),cameraParameters.CameraMatrix.at<tFloat32>(1,1),cameraParameters.CameraMatrix.at<tFloat32>(1,2)));
//LOG_WARNING(cString::Format("RoadSign: Conv fx: %f, cx: %f, fy: %f, cy: %f",cameraParameters_downsampled.CameraMatrix.at<tFloat32>(0,0),cameraParameters_downsampled.CameraMatrix.at<tFloat32>(0,2),cameraParameters_downsampled.CameraMatrix.at<tFloat32>(1,1),cameraParameters_downsampled.CameraMatrix.at<tFloat32>(1,2)));
}
}
}
else if (eStage == StageGraphReady)
{
tTrafficSign.StageGraphReady();
tSignalValueSteering.StageGraphReady();
tSignalValueSpeed.StageGraphReady();
tActionStruct.StageGraphReady();
tFeedbackStruct.StageGraphReady();
// get the image format of the input video pin
cObjectPtr<IMediaType> pType;
RETURN_IF_FAILED(videoInput.GetMediaType(&pType));
cObjectPtr<IMediaTypeVideo> pTypeVideo;
RETURN_IF_FAILED(pType->GetInterface(IID_ADTF_MEDIA_TYPE_VIDEO, (tVoid**)&pTypeVideo));
// set the image format of the input video pin
UpdateInputImageFormat(pTypeVideo->GetFormat());
// set the image format of the output video pin; reduced resolution is also handled in this case!
UpdateOutputImageFormat(pTypeVideo->GetFormat());
// set paramenter for the marker detector class
// same parameters as in aruco sample aruco_hrm_test.cpp
// effects of parameters has to be tested
markerDetector.setMakerDetectorFunction(aruco::HighlyReliableMarkers::detect);
//markerDetector.setThresholdParams( 21, 7);
markerDetector.setThresholdParams( 10.5, 7.0);
markerDetector.setCornerRefinementMethod(aruco::MarkerDetector::LINES);
//markerDetector.setThresholdMethod(aruco::MarkerDetector::CANNY);
markerDetector.setWarpSize((dictionary[0].n()+2)*8); // default: *8
markerDetector.setMinMaxSize(0.005f, 0.3f); // default: min 0.005f, max 0.5f
// Debugging: measure execution time of aruco marker detection (enabled with property)
ms_sum = 0; // Debugging: overall execution time (aruco detection)
number_of_signs = 0; // Debugging: count number of detected markers
frame_counter = 0; // Debugging: received video frame counter
same_sign_counter = 0; // sign has to be detected multiple times to be valid
prev_closest_sign = -1; // save id of last detected nearest sign
parking_sign_received = tFalse; // save parking sign status
if (videoOutput.IsConnected()) {
debugMode = tTrue;
} else {
debugMode = tFalse;
}
}
RETURN_NOERROR;
}
tResult RoadSignDetectionAdapter::Shutdown(tInitStage eStage, __exception) {
return cAsyncDataTriggeredFilter::Shutdown(eStage, __exception_ptr);
}
tResult RoadSignDetectionAdapter::OnPinEvent(IPin* source, tInt nEventCode, tInt nParam1, tInt nParam2,
IMediaSample* mediaSample) {
RETURN_IF_POINTER_NULL(mediaSample);
RETURN_IF_POINTER_NULL(source);
adtf_util::cSynchronizer _sync_criticalSection_OnPinEvent(&(sync.criticalSection_OnPinEvent));
if (nEventCode == IPinEventSink::PE_MediaSampleReceived) {
if (source == &videoInput) {
if(sync.bufferCount > 2) {
sync.skipNextFrame = true;
}
sync.IncreaseBufferCount();
return cAsyncDataTriggeredFilter::OnPinEvent(source, nEventCode, nParam1, nParam2, mediaSample);
} else if (source == &actionInput){
sync.lastActionMediaSample = mediaSample;
return cAsyncDataTriggeredFilter::OnPinEvent(source, nEventCode, nParam1, nParam2, mediaSample);
} else if (source == &steeringInput) {
TSignalValue::Data data;
tSignalValueSteering.Read(mediaSample, &data);
lastSteeringAngle = (data.f32_value - 90) / 180 * CV_PI;
if (abs(lastSteeringAngle) > 35) {
LOG_WARNING("RoadSignDetection: SteeringAngle out of bounds");
}
} else if (source == &speedInput) {
TSignalValue::Data data;
tSignalValueSpeed.Read(mediaSample, &data);
lastSpeed = data.f32_value;
if (abs(lastSpeed) > 5.0) {
LOG_WARNING("RoadSignDetection: Speed out of bounds");
}
}
} else if (nEventCode == IPinEventSink::PE_MediaTypeChanged) {
if (source == &videoInput) {
//the input format was changed, so the imageformat has to changed in this filter also
cObjectPtr<IMediaType> pType;
RETURN_IF_FAILED(videoInput.GetMediaType(&pType));
cObjectPtr<IMediaTypeVideo> pTypeVideo;
RETURN_IF_FAILED(pType->GetInterface(IID_ADTF_MEDIA_TYPE_VIDEO, (tVoid**)&pTypeVideo));
UpdateInputImageFormat(videoInput.GetFormat());
// reduced resolution is also handled by this function-call !
}
}
RETURN_NOERROR;
}
tResult RoadSignDetectionAdapter::OnAsyncPinEvent(IPin* source, tInt nEventCode, tInt nParam1, tInt nParam2,
IMediaSample* mediaSample) {
RETURN_IF_POINTER_NULL(mediaSample);
RETURN_IF_POINTER_NULL(source);
if (nEventCode == IPinEventSink::PE_MediaSampleReceived) {
// a new image was received so the processing is started
if (source == &actionInput) {
ProcessAction(mediaSample);
} else if (source == &videoInput) {
{
adtf_util::cSynchronizer _sync_criticalSection_OnPinEvent(&(sync.criticalSection_OnPinEvent));
sync.DecreaseBufferCount();
if(sync.skipNextFrame) {
sync.skipNextFrame = false;
RETURN_NOERROR;
}
}
if (actionSub.enabled && actionSub.started) {
if(actionSub.command == AC_RS_START || actionSub.command == AC_RS_START_PARKING_SIGN_LOGGING || actionSub.command == AC_RS_START_PRIORITY_SIGN_LOGGING) {
ProcessVideo(mediaSample);
}
}
}
}
RETURN_NOERROR;
}
tResult RoadSignDetectionAdapter::ProcessAction(IMediaSample* mediaSample) {
TActionStruct::ActionSub currentAction = tActionStruct.Read_Action(sync.lastActionMediaSample, F_ROAD_SIGNS);
if(currentAction.enabled == tFalse || currentAction.started == tFalse) {
lastPrioritySign.ui32_filterID = F_ROAD_SIGNS;
lastPrioritySign.ui32_status = FB_RS_CROSSING_SIGN_NONE;
} else if(currentAction.command == AC_RS_GET_CROSSING_SIGN) {
tFeedbackStruct.Transmit(&feedbackOutput, lastPrioritySign, _clock->GetStreamTime());
} else if(currentAction.command == AC_RS_GET_PARKING_SIGN_RECEIVED) {
TFeedbackStruct::Data feedback;
feedback.ui32_filterID = F_ROAD_SIGNS;
if(parking_sign_received) {
parking_sign_received = tFalse;
feedback.ui32_status = FB_RS_PARKING_SIGN_RECEIVED;
tFeedbackStruct.Transmit(&feedbackOutput, feedback, _clock->GetStreamTime());
} else {
feedback.ui32_status = FB_RS_NO_PARKING_SIGN_RECEIVED;
tFeedbackStruct.Transmit(&feedbackOutput, feedback, _clock->GetStreamTime());
}
} else if (currentAction.command == AC_RS_RESET_PARKING_SIGN) {
parking_sign_received = tFalse; // also reset parking status
} else if (currentAction.command == AC_RS_RESET_CROSSING_SIGN) {
lastPrioritySign.ui32_filterID = F_ROAD_SIGNS;
lastPrioritySign.ui32_status = FB_RS_CROSSING_SIGN_NONE;
TFeedbackStruct::Data feedback;
feedback.ui32_filterID = F_ROAD_SIGNS;
feedback.ui32_status = FB_RS_CROSSING_SIGN_RESET;
tFeedbackStruct.Transmit(&feedbackOutput, feedback, _clock->GetStreamTime());
}
actionSub = currentAction;
RETURN_NOERROR;
}
tResult RoadSignDetectionAdapter::ProcessVideo(adtf::IMediaSample* inputSample) {
//creating new pointer for input data
const tVoid* srcBuffer;
//creating matrix for input image
Mat inputImage;
Mat outputImage;
// new Image with reduced resolution
Mat reduced_Image;
reduced_Image = Mat (cv::Size(320,240), CV_8UC3);
//receiving data from input sample, and saving to InputImage
if (IS_OK(inputSample->Lock(&srcBuffer))) {
try {
//convert to mat
inputImage = Mat(inputFormat.nHeight, inputFormat.nWidth, CV_8UC3, (tVoid*) srcBuffer,
inputFormat.nBytesPerLine);
tTimeStamp starttime = _clock->GetStreamTime();
// doing the detection of markers in image
if(m_bReduceImageResolution) { // reduced image resolution
resize(inputImage,reduced_Image,reduced_Image.size());
markerDetector.detect(reduced_Image(Rect(0, 0, static_cast<tUInt32>(0.85*reduced_Image.cols), static_cast<tUInt32>(0.65*reduced_Image.rows))), cacheMarkers, cameraParameters_downsampled, static_cast<float>(markerSize));
//LOG_WARNING(cString::Format("RoadSign: cols (width) orig: %d, new: %d; rows (height): orig: %d, new: %d", reduced_Image.cols, static_cast<tUInt32>(0.65*reduced_Image.cols), reduced_Image.rows, static_cast<tUInt32>(0.75*reduced_Image.rows)));
} else {
markerDetector.detect(inputImage(Rect(0, 0, 640, 480)), cacheMarkers, cameraParameters, static_cast<float>(markerSize));
}
// Debug Execution time
if(debugExecutionTime) {
tTimeStamp timediff = _clock->GetStreamTime() - starttime;
tFloat32 difftime_ms = timediff / 1000;
ms_sum += difftime_ms;
frame_counter++;
if(frame_counter % 30 == 0) {
LOG_WARNING(cString::Format("RoadSign: execution time in ms: %f, overall time: %f, number of signs: %d", difftime_ms, ms_sum, number_of_signs));
frame_counter = 0;
}
}
} catch (cv::Exception &e) {
LOG_ERROR(cString::Format("RoadSign Exception: %s", e.msg.c_str()));
inputSample->Unlock(srcBuffer);
RETURN_ERROR(ERR_EXCEPTION_RAISED);
}
}
inputSample->Unlock(srcBuffer);
if (debugMode) {
// do a deep copy of the image, otherwise the original frame is modified
if(m_bReduceImageResolution) {
outputImage = reduced_Image.clone();
}
else{
outputImage = inputImage.clone();
}
}
RoadSign closestSign;
closestSign.distance = std::numeric_limits<tFloat32>::max();
RoadSign prevClosestSign;
cv::Point3f m_x;
cv::Point3f m_y;
tFloat32 angle = 0;
for (unsigned int i = 0; i < cacheMarkers.size(); i++) {
if (norm(cacheMarkers[i].Tvec) < closestSign.distance) {
cv::Mat rot;
cv::Rodrigues(cacheMarkers[i].Rvec, rot);
cv::Mat pitchRot = CVMath::RotationX_3D_Degree (cameraPitch);
rot = pitchRot * rot;
cv::Point3f e_x = Point3f(rot.at<tFloat32>(0, 0), rot.at<tFloat32>(1, 0), rot.at<tFloat32>(2, 0));
cv::Point3f e_y = Point3f(rot.at<tFloat32>(0, 1), rot.at<tFloat32>(1, 1), rot.at<tFloat32>(2, 1));
cv::Point3f e_z = Point3f(rot.at<tFloat32>(0, 2), rot.at<tFloat32>(1, 2), rot.at<tFloat32>(2, 2));
//Point3f exp_e_z = Point3f(cos(60.0 / 180 *CV_PI), 0, -sin(60.0 / 180 *CV_PI));
Point3f translation = Point3f(cacheMarkers[i].Tvec);
Mat t = pitchRot * cacheMarkers[i].Tvec;
translation = Point3f(t);
float distance = cv::norm(translation);
if(distance > thresholds.MAX_DISTANCE || translation.y < thresholds.CAMERA_Y_LIMIT) {
continue;
}
// Debug Execution time
if(debugExecutionTime) {
number_of_signs++; // count number of detected signs
}
Point3f exp_e_z = - translation / distance;
Point3f exp_e_x = Point3f(0, 1, 0);
//Point3f exp_e_y = Point3f(1, 0, 0);
e_z.y = 0;
e_z = e_z / cv::norm(e_z);
//const tFloat32 x_dot_x = exp_e_x.dot(e_x);
//const tFloat32 x_dot_y = exp_e_x.dot(e_y);
float y = e_z.z *exp_e_z.x - e_z.x * exp_e_z.z;
/*
if((exp_e_z.dot(e_z) > thresholds.COS_ANGLE_UPPER_LIMIT_Z && y < 0) ||
(exp_e_z.dot(e_z) > thresholds.COS_ANGLE_LOWER_LIMIT_Z && y > 0)) {
//const tFloat32 y_dot_y = exp_e_y.dot(e_y);
//if(x_dot_x > thresholds.COS_ANGLE_LIMIT_XY && y_dot_y > thresholds.COS_ANGLE_LIMIT_XY) {
//} else if(- x_dot_y > thresholds.COS_ANGLE_LIMIT_XY && exp_e_y.dot(e_x) > thresholds.COS_ANGLE_LIMIT_XY) {
//} else if(- x_dot_x > thresholds.COS_ANGLE_LIMIT_XY && - y_dot_y > thresholds.COS_ANGLE_LIMIT_XY) {
//} else if(x_dot_y > thresholds.COS_ANGLE_LIMIT_XY && - x_dot_x > thresholds.COS_ANGLE_LIMIT_XY) {
//}
if ((-x_dot_x > thresholds.COS_ANGLE_LIMIT_XY && e_y.z < 0)
|| (x_dot_x > thresholds.COS_ANGLE_LIMIT_XY && e_y.z > 0)
|| (-x_dot_y > thresholds.COS_ANGLE_LIMIT_XY && e_x.z > 0)
|| (x_dot_y > thresholds.COS_ANGLE_LIMIT_XY && e_x.z < 0)) {
} else {
//continue; // TODO tmp disabled, new sign check method
}
} else {
//continue; TODO tmp disabled, new sign check method
}
*/
// z-axis limits
if((exp_e_z.dot(e_z) > thresholds.COS_ANGLE_UPPER_LIMIT_Z && y < 0) ||
(exp_e_z.dot(e_z) > thresholds.COS_ANGLE_LOWER_LIMIT_Z && y > 0)) {
} else {
if(cacheMarkers[i].id != MARKER_ID_PARKINGAREA) {
continue;
}
}
// x-axis limit
if((e_x.dot(exp_e_x) <= thresholds.COS_ANGLE_LIMIT_XY)) {
continue;
}
// skip sign after s-curve
if( (fabsf(lastSteeringAngle) > thresholds.STEERING_LIMIT && cacheMarkers[i].id != MARKER_ID_PARKINGAREA)) {
if(debugModeEnabled) {
LOG_WARNING(cString::Format("RoadSign: skipped sign with ID %d because steering angle (%f) > limit (%f)", cacheMarkers[i].id, (lastSteeringAngle/CV_PI)*180, (thresholds.STEERING_LIMIT/CV_PI)*180 ));
}
continue;
}
if (debugModeEnabled) {
LOG_WARNING(
cString::Format("RoadSign: ID %d, counter: %d, x: %f, y: %f, z: %f, x_dot_x: %f, z_dot_z: %f, cam pitch: %f, steering: %f", cacheMarkers[i].id, same_sign_counter, translation.x, translation.y,
translation.z, e_x.dot(exp_e_x), exp_e_z.dot(e_z), cameraPitch, (lastSteeringAngle/CV_PI)*180.0f ));
}
m_x = e_x;
m_y = e_y;
prevClosestSign = closestSign;
Mat closestRot = ((pitchRot * cacheMarkers[i].Rvec));
closestSign = RoadSign(translation, Point3f(closestRot), cacheMarkers[i].id, e_z, inputSample->GetTime());
closestSign.index = i;
angle = exp_e_z.dot(e_z);
}
}
// received valid sign
if (closestSign.id != -1) {
// check nearest sign: same as last received nearest sign -> increase counter
if(prev_closest_sign == -1) {
same_sign_counter = 0;
} else {
if(prev_closest_sign == closestSign.id) {
same_sign_counter++;
} else {
same_sign_counter = 0;
}
}
// save last received nearest sign
prev_closest_sign = closestSign.id;
// received same sign three times in a row
if(same_sign_counter >= 2) {
// reset same sign counter
same_sign_counter = 0;
prev_closest_sign = -1;
if(debugModeEnabled) {
LOG_WARNING(cString::Format("RoadSign: Sign with id %d detected three times as nearest sign in a row", closestSign.id));
}
//evaluate signs
tBool near = MatchToTrajectory(closestSign, lastSteeringAngle, lastSpeed);
tBool far = MatchToTrajectory(prevClosestSign, lastSteeringAngle, lastSpeed);
if(far && near == tFalse) {
closestSign = prevClosestSign;
}
// reset parking_sign_received
parking_sign_received = tFalse;
if (far || near) {
TTrafficSign::Data data;
data.ui32_signID = closestSign.id;
data.f32_distance = closestSign.distance;
if(actionSub.command == AC_RS_START || actionSub.command == AC_RS_START_PRIORITY_SIGN_LOGGING) {
if(actionSub.command == AC_RS_START) {
if(data.ui32_signID != MARKER_ID_PARKINGAREA) {
// replace Roundabout sign with giveway sign
if(data.ui32_signID == MARKER_ID_ROUNDABOUT) {
data.ui32_signID = MARKER_ID_GIVEWAY;
}
tTrafficSign.Transmit(&trafficSignOutput, data, inputSample->GetTime());
}
}
switch (closestSign.id) {
case MARKER_ID_ROUNDABOUT: {
lastPrioritySign.ui32_filterID = F_ROAD_SIGNS;
lastPrioritySign.ui32_status = FB_RS_ROUNDABOUT;
break; }
case MARKER_ID_UNMARKEDINTERSECTION:
case MARKER_ID_STOPANDGIVEWAY:
case MARKER_ID_GIVEWAY: {
lastPrioritySign.ui32_filterID = F_ROAD_SIGNS;
lastPrioritySign.ui32_status = FB_RS_CROSSING_SIGN_GIVEWAY;
break; }
case MARKER_ID_HAVEWAY: {
lastPrioritySign.ui32_filterID = F_ROAD_SIGNS;
lastPrioritySign.ui32_status = FB_RS_CROSSING_SIGN_PRIORITY;
break; }
case MARKER_ID_PARKINGAREA: {
parking_sign_received = tTrue; // set parking sign received
TFeedbackStruct::Data response;
response.ui32_filterID = F_ROAD_SIGNS;
response.ui32_status = 3000 + closestSign.id;
tFeedbackStruct.Transmit(&feedbackOutput, response, inputSample->GetTime());
}
}
} else { //AC_RS_START_PARKING_SIGN_LOGGING
if (closestSign.id == MARKER_ID_PARKINGAREA) {
parking_sign_received = tTrue; // set parking sign received
}
}
//if(debugModeEnabled) {
//LOG_WARNING(cString::Format("RoadSign: Marker found %d", closestSign.id));
//}
if (debugMode) {
// vectors x and y are wrong printed
putText(outputImage, cv::String(cString::Format("%.2f %.2f %.2f %.2f", m_x.x, m_y.x, closestSign.z_vec.x, closestSign.translation.x).GetPtr()),
Point2f(0, 25), CV_FONT_NORMAL, 0.35, Scalar(0, 0, 255));
putText(outputImage, cv::String(cString::Format("%.2f %.2f %.2f %.2f", m_x.y, m_y.y, closestSign.z_vec.y, closestSign.translation.y).GetPtr()),
Point2f(0, 50), CV_FONT_NORMAL, 0.35, Scalar(0, 0, 255));
putText(outputImage, cv::String(cString::Format("%.2f %.2f %.2f %.2f %.2f", m_x.z, m_y.z, closestSign.z_vec.z, closestSign.translation.z, angle).GetPtr()),
Point2f(0, 75), CV_FONT_NORMAL, 0.35, Scalar(0, 0, 255));
// draw the marker in the image
cacheMarkers[closestSign.index].draw(outputImage, Scalar(0, 0, 255), 1);
// draw cube in image
//CvDrawingUtils::draw3dCube(TheInputImage,m_TheMarkers[i],m_TheCameraParameters);
// draw 3d axis in image if the intrinsic params were loaded
if (cameraParamsLoaded){
if(m_bReduceImageResolution) {
CvDrawingUtils::draw3dAxis(outputImage, cacheMarkers[closestSign.index], cameraParameters_downsampled);
}
else{
CvDrawingUtils::draw3dAxis(outputImage, cacheMarkers[closestSign.index], cameraParameters);
}
}
}
}
}
}
//update new media sample with image data if something has to be transmitted
if (debugMode ) {
cObjectPtr<IMediaSample> sample;
if (IS_OK(AllocMediaSample(&sample))) {
if(m_bReduceImageResolution) {
sample->Update(inputSample->GetTime(), outputImage.data, tInt32(reducedOutputFormat.nSize), 0);
videoOutput.SetFormat(&reducedOutputFormat, NULL);
videoOutput.Transmit(sample);
}
else{
sample->Update(inputSample->GetTime(), outputImage.data, tInt32(outputFormat.nSize), 0);
videoOutput.SetFormat(&outputFormat, NULL);
videoOutput.Transmit(sample);
}
}
}
RETURN_NOERROR;
}
tResult RoadSignDetectionAdapter::UpdateInputImageFormat(const tBitmapFormat* pFormat) {
if (pFormat != NULL) {
inputFormat = (*pFormat);
LOG_INFO(
adtf_util::cString::Format(
"Marker Detection Filter: Input: Size %d x %d ; BPL %d ; Size %d , PixelFormat; %d",
inputFormat.nWidth, inputFormat.nHeight, inputFormat.nBytesPerLine, inputFormat.nSize,
inputFormat.nPixelFormat));
}
RETURN_NOERROR;
}
tResult RoadSignDetectionAdapter::UpdateOutputImageFormat(const tBitmapFormat* pFormat) {
if (pFormat != NULL) {
outputFormat = (*pFormat);
// reduced image resolution
if(m_bReduceImageResolution){
reducedOutputFormat = outputFormat;
reducedOutputFormat.nWidth = outputFormat.nWidth/2;
reducedOutputFormat.nHeight = outputFormat.nHeight/2;
reducedOutputFormat.nBytesPerLine = outputFormat.nBytesPerLine/2;
reducedOutputFormat.nSize = reducedOutputFormat.nBytesPerLine * reducedOutputFormat.nHeight;
}
LOG_INFO(
adtf_util::cString::Format(
"Marker Detection Filter: Output: Size %d x %d ; BPL %d ; Size %d, PixelFormat; %d",
outputFormat.nWidth, outputFormat.nHeight, outputFormat.nBytesPerLine, outputFormat.nSize,
outputFormat.nPixelFormat));
if(m_bReduceImageResolution){
videoOutput.SetFormat(&reducedOutputFormat, NULL);
}
else{
videoOutput.SetFormat(&outputFormat, NULL);
}
}
RETURN_NOERROR;
}
tResult RoadSignDetectionAdapter::ReadFromFile(tFloat32 *pitch) {
if (filePitch.GetLength() < 2){
LOG_WARNING("RoadSignDetection: No filename for the pitch angle is given");
RETURN_NOERROR;
}
// create absolute path
ADTF_GET_CONFIG_FILENAME(filePitch);
cFilename absFilename = filePitch.CreateAbsolutePath(".");
if (cFileSystem::Exists(filePitch) == tFalse) {
LOG_ERROR("RoadSignDetection: File for stored pitch angle does not exist");
RETURN_NOERROR;
}
cFile file;
file.Open(absFilename.GetPtr(), cFile::OM_Read);
cString tmp;
file.ReadLine(tmp); // comment line
file.ReadLine(tmp);
if(tmp.GetLength() >= 1) {
*pitch = tmp.AsFloat64();
} else {
LOG_ERROR(cString::Format("RoadSignDetection: Something went wrong with opening file %s. Using default pitch angle", absFilename.GetPtr()));
}
RETURN_NOERROR;
}
tBool RoadSignDetectionAdapter::MatchToTrajectory(RoadSign sign, tFloat32 steeringAngle, tFloat32 speed) {
const tFloat32 carLength = 0.6;
const tFloat32 timestep = 0.03333333;
if(sign.id < 0 || sign.index < 0) {
return tFalse;
}
//TODO disabled because it does not work properly
return tTrue;
if(speed < 0.5) {
speed = 0.5;
}
//std::cout << "steering " << steeringAngle << " speed " << speed << std::endl;
tFloat32 psi_point = tan(steeringAngle) * ( speed / carLength );
tFloat psi = psi_point;
Point2f position = Point2f(0,0);
for (tFloat32 absDistance = 0; absDistance < 5;) {
Point2f steering = Point2f (sin(psi), cos(psi));
absDistance += speed * timestep;
position += steering * speed * timestep;
psi += psi_point * timestep;
Point3f dir = Point3f(steering);
Point3f signDir = Point3f(sign.translation.x, sign.translation.z, 0) - Point3f(position);
if(dir.dot(signDir) > 0) {
// angle between dir and signDir bigger than 90 degree
//sign behind the car
Point3f z = dir.cross(signDir);
if(z.z > 0) {
//sign on left hand side
if(Point3f(sign.z_vec.x, sign.z_vec.z, 0).dot(dir) < cos(150.0 / 180 * CV_PI)) {
return tTrue;
}
std::cout << "return false1" << "position " << position.x << " "<< position.y << "dir " << dir.x << " "<< dir.y << "z_vec " << sign.z_vec.x << " " << sign.z_vec.y << std::endl;
}
return tFalse;
}
}
std::cout << "return false2" << std::endl;
return tFalse;
}
| 41.613164
| 730
| 0.72198
|
FAUtonOHM
|
da12478710ee429c6e4978d98659d8fd96fba24b
| 1,449
|
cpp
|
C++
|
src/crosschain/interblockchain.cpp
|
BlockMechanic/rain
|
e8818b75240ff9277b0d14d38769378f05d0b525
|
[
"MIT"
] | null | null | null |
src/crosschain/interblockchain.cpp
|
BlockMechanic/rain
|
e8818b75240ff9277b0d14d38769378f05d0b525
|
[
"MIT"
] | null | null | null |
src/crosschain/interblockchain.cpp
|
BlockMechanic/rain
|
e8818b75240ff9277b0d14d38769378f05d0b525
|
[
"MIT"
] | null | null | null |
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <crosschain/interblockchain.h>
#include <protocol.h>
#include <chainparams.h>
#include <util/strencodings.h>
#include <boost/foreach.hpp>
void CIbtp::LoadMsgStart()
{
//need to find a dynamic method of adding supported networks
vChains.push_back(SChain("Litecoin", "LTC", 0xfb, 0xc0, 0xb6, 0xdb, 23373));
vChains.push_back(SChain("Bitcoin", "BTC", 0xf9, 0xbe, 0xb4, 0xd9, 8372));
vChains.push_back(SChain("bzedge", "BZE", 0x24, 0xe9, 0x27, 0x64, 1990));
vChains.push_back(SChain("Rain", "XQM", 0xf7, 0xba, 0xd4, 0xaa, 8384));
}
bool CIbtp::IsIbtpChain(const unsigned char msgStart[], std::string& chainName)
{
bool bFound = false;
BOOST_FOREACH(SChain p, vChains)
{
unsigned char pchMsg[4] = { p.pchMessageOne, p.pchMessageTwo, p.pchMessageThree, p.pchMessageFour };
if(memcmp(msgStart, pchMsg, sizeof(pchMsg)) == 0)
{
bFound = true;
chainName = p.sChainName;
LogPrintf("Found Supported chain: %s\n", p.sChainName.c_str());
}
}
return bFound;
}
//need to specify addresses for burn
//need to specify either floating or fixed exchange rates
// need to specify limit on the amounts that can be transferred
// need to specify time-frame, ie blocks when it can be done for each coin
| 37.153846
| 108
| 0.68323
|
BlockMechanic
|
da12a6276249a1e2b1bbe1a6ccf43669ca6bc51e
| 568
|
hpp
|
C++
|
android-31/android/os/health/PidHealthStats.hpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 12
|
2020-03-26T02:38:56.000Z
|
2022-03-14T08:17:26.000Z
|
android-31/android/os/health/PidHealthStats.hpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 1
|
2021-01-27T06:07:45.000Z
|
2021-11-13T19:19:43.000Z
|
android-29/android/os/health/PidHealthStats.hpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 3
|
2021-02-02T12:34:55.000Z
|
2022-03-08T07:45:57.000Z
|
#pragma once
#include "../../../JObject.hpp"
namespace android::os::health
{
class PidHealthStats : public JObject
{
public:
// Fields
static jint MEASUREMENT_WAKE_NESTING_COUNT();
static jint MEASUREMENT_WAKE_START_MS();
static jint MEASUREMENT_WAKE_SUM_MS();
// QJniObject forward
template<typename ...Ts> explicit PidHealthStats(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {}
PidHealthStats(QJniObject obj);
// Constructors
// Methods
};
} // namespace android::os::health
| 22.72
| 155
| 0.702465
|
YJBeetle
|
da12a7c5e63ae59962652ebedc1712f7cf326703
| 1,326
|
cpp
|
C++
|
Game/Colour.cpp
|
roooodcastro/gamedev-coursework
|
a4bfdbd8f68cb641c0025ec70270b0a17e2e237d
|
[
"MIT"
] | 1
|
2019-10-05T23:31:00.000Z
|
2019-10-05T23:31:00.000Z
|
Game/Colour.cpp
|
roooodcastro/gamedev-coursework
|
a4bfdbd8f68cb641c0025ec70270b0a17e2e237d
|
[
"MIT"
] | null | null | null |
Game/Colour.cpp
|
roooodcastro/gamedev-coursework
|
a4bfdbd8f68cb641c0025ec70270b0a17e2e237d
|
[
"MIT"
] | null | null | null |
#include "Colour.h"
Colour::Colour(void) {
this->red = 255;
this->green = 255;
this->blue = 255;
this->alpha = 255;
}
Colour::Colour(const Colour ©) {
this->red = copy.red;
this->green = copy.green;
this->blue = copy.blue;
this->alpha = copy.alpha;
}
Colour::Colour(unsigned int colour) {
this->red = 0;
this->green = 0;
this->blue = 0;
this->alpha = 0;
this->setColour(colour);
}
Colour::Colour(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha) {
this->red = red;
this->green = green;
this->blue = blue;
this->alpha = alpha;
}
Colour::~Colour(void) {}
Colour &Colour::operator=(const Colour &other) {
this->red = other.red;
this->green = other.green;
this->blue = other.blue;
this->alpha = other.alpha;
return *this;
}
void Colour::setColour(uint32_t colour) {
red = (uint8_t) (colour & 0x000000FF);
green = (uint8_t) ((colour & 0x0000FF00) >> 8);
blue = (uint8_t) ((colour & 0x00FF0000) >> 16);
alpha = (uint8_t) ((colour & 0xFF000000) >> 24);
}
void Colour::setColour(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha) {
this->red = red;
this->green = green;
this->blue = blue;
this->alpha = alpha;
}
unsigned int Colour::getColour() {
uint32_t colour = 0;
colour += red;
colour += (green << 8);
colour += (blue << 16);
colour += (alpha << 24);
return colour;
}
| 21.047619
| 81
| 0.642534
|
roooodcastro
|
da1308de95dbfcc002e0fdf2829f885b5a409294
| 3,928
|
cpp
|
C++
|
Chapter11/SQL_Model_View/mainwindow.cpp
|
thacngoc/Qt5-CPP-GUI-Programming-Cookbook-Second-Edition
|
0c8ab6efb2c6c18782b2e85c6d8c7bbd22098bd8
|
[
"MIT"
] | 94
|
2019-04-05T09:44:13.000Z
|
2022-03-29T04:04:37.000Z
|
Chapter11/SQL_Model_View/mainwindow.cpp
|
thacngoc/Qt5-CPP-GUI-Programming-Cookbook-Second-Edition
|
0c8ab6efb2c6c18782b2e85c6d8c7bbd22098bd8
|
[
"MIT"
] | 5
|
2019-10-28T10:21:27.000Z
|
2020-08-18T05:42:04.000Z
|
Chapter11/SQL_Model_View/mainwindow.cpp
|
thacngoc/Qt5-CPP-GUI-Programming-Cookbook-Second-Edition
|
0c8ab6efb2c6c18782b2e85c6d8c7bbd22098bd8
|
[
"MIT"
] | 54
|
2019-03-27T11:52:45.000Z
|
2022-03-24T09:21:51.000Z
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
hasInit = false;
ui->setupUi(this);
db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("127.0.0.1");
db.setUserName("yourusername");
db.setPassword("yourpassword");
db.setDatabaseName("databasename");
ui->tableWidget->setColumnHidden(0, true);
if (db.open())
{
QSqlQuery query;
if (query.exec("SELECT id, name, age, gender, married FROM employee"))
{
while (query.next())
{
qDebug() << query.value(0) << query.value(1) << query.value(2) << query.value(3) << query.value(4);
QString id = query.value(0).toString();
QString name = query.value(1).toString();
QString age = query.value(2).toString();
int gender = query.value(3).toInt();
bool married = query.value(4).toBool();
ui->tableWidget->setRowCount(ui->tableWidget->rowCount() + 1);
QTableWidgetItem* idItem = new QTableWidgetItem(id);
QTableWidgetItem* nameItem = new QTableWidgetItem(name);
QTableWidgetItem* ageItem = new QTableWidgetItem(age);
QTableWidgetItem* genderItem = new QTableWidgetItem();
if (gender == 0)
genderItem->setData(0, "Male");
else
genderItem->setData(0, "Female");
QTableWidgetItem* marriedItem = new QTableWidgetItem();
if (married)
marriedItem->setData(0, "Yes");
else
marriedItem->setData(0, "No");
ui->tableWidget->setItem(ui->tableWidget->rowCount() - 1, 0, idItem);
ui->tableWidget->setItem(ui->tableWidget->rowCount() - 1, 1, nameItem);
ui->tableWidget->setItem(ui->tableWidget->rowCount() - 1, 2, ageItem);
ui->tableWidget->setItem(ui->tableWidget->rowCount() - 1, 3, genderItem);
ui->tableWidget->setItem(ui->tableWidget->rowCount() - 1, 4, marriedItem);
}
hasInit = true;
}
else
{
qDebug() << query.lastError().text();
}
}
else
{
qDebug() << "Failed to connect to database.";
}
}
MainWindow::~MainWindow()
{
db.close();
delete ui;
}
void MainWindow::on_tableWidget_itemChanged(QTableWidgetItem *item)
{
if (hasInit)
{
QString id = ui->tableWidget->item(item->row(), 0)->data(0).toString();
QString name = ui->tableWidget->item(item->row(), 1)->data(0).toString();
QString age = QString::number(ui->tableWidget->item(item->row(), 2)->data(0).toInt());
ui->tableWidget->item(item->row(), 2)->setData(0, age);
QString gender;
if (ui->tableWidget->item(item->row(), 3)->data(0).toString() == "Male")
{
gender = "0";
}
else
{
ui->tableWidget->item(item->row(), 3)->setData(0, "Female");
gender = "1";
}
QString married;
if (ui->tableWidget->item(item->row(), 4)->data(0).toString() == "No")
{
married = "0";
}
else
{
ui->tableWidget->item(item->row(), 4)->setData(0, "Yes");
married = "1";
}
qDebug() << id << name << age << gender << married;
QSqlQuery query;
if (query.exec("UPDATE employee SET name = '" + name + "', age = '" + age + "', gender = '" + gender + "', married = '" + married + "' WHERE id = " + id))
{
QMessageBox::information(this, "Update Success", "Data updated to database.");
}
else
{
qDebug() << query.lastError().text();
}
}
}
| 31.424
| 162
| 0.515784
|
thacngoc
|
da16f7fac40a68a32c7aa59a6988ef6676c9a4db
| 289
|
cpp
|
C++
|
MSVC/14.24.28314/crt/src/linkopts/commode.cpp
|
825126369/UCRT
|
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
|
[
"MIT"
] | 2
|
2021-01-27T10:19:30.000Z
|
2021-02-09T06:24:30.000Z
|
MSVC/14.24.28314/crt/src/linkopts/commode.cpp
|
825126369/UCRT
|
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
|
[
"MIT"
] | null | null | null |
MSVC/14.24.28314/crt/src/linkopts/commode.cpp
|
825126369/UCRT
|
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
|
[
"MIT"
] | 1
|
2021-01-27T10:19:36.000Z
|
2021-01-27T10:19:36.000Z
|
//
// commode.cpp
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// A link option that defaults the global commit flag to true.
//
#include <vcruntime.h>
#include <fcntl.h>
extern "C" int __CRTDECL _get_startup_commit_mode()
{
return 0x0800; // _IOCOMMIT
}
| 17
| 65
| 0.688581
|
825126369
|
da2a599cbd917908263cf2ea7417f1a3dae0d830
| 3,677
|
cpp
|
C++
|
Unrest-iOS/MapMarkerMenu.cpp
|
arvindrajayadav/unrest
|
d89f20e95fbcdef37a47ab1454b2479522a0e43f
|
[
"MIT"
] | 11
|
2020-08-04T08:37:46.000Z
|
2022-03-31T22:35:15.000Z
|
CRAB/MapMarkerMenu.cpp
|
arvindrajayadav/unrest
|
d89f20e95fbcdef37a47ab1454b2479522a0e43f
|
[
"MIT"
] | 1
|
2020-12-16T16:51:52.000Z
|
2020-12-18T06:35:38.000Z
|
Unrest-iOS/MapMarkerMenu.cpp
|
arvindrajayadav/unrest
|
d89f20e95fbcdef37a47ab1454b2479522a0e43f
|
[
"MIT"
] | 7
|
2020-08-04T09:34:20.000Z
|
2021-09-11T03:00:16.000Z
|
#include "stdafx.h"
#include "MapMarkerMenu.h"
using namespace pyrodactyl::ui;
//------------------------------------------------------------------------
// Purpose: Load
//------------------------------------------------------------------------
void MapMarkerMenu::Load(rapidxml::xml_node<char> *node)
{
if (NodeValid("ref", node))
ref.Load(node->first_node("ref"));
if (NodeValid("player", node))
player.Load(node->first_node("player"));
if (NodeValid("offset", node))
{
rapidxml::xml_node<char> *offnode = node->first_node("offset");
if (NodeValid("marker", offnode))
offset.marker.Load(offnode->first_node("marker"));
if (NodeValid("player", offnode))
offset.player.Load(offnode->first_node("player"));
}
menu.UseKeyboard(true);
}
//------------------------------------------------------------------------
// Purpose: Draw
//------------------------------------------------------------------------
void MapMarkerMenu::Draw(const Element &pos, const Vector2i &player_pos, const Rect &camera)
{
//Calculate all offsets
Vector2i offset_p(pos.x + player_pos.x + offset.player.x - camera.x, pos.y + player_pos.y + offset.player.y - camera.y);
Vector2i offset_m(pos.x - camera.x + offset.marker.x, pos.y - camera.y + offset.marker.y);
//Only draw the image - captions drawn later to prevent drawing another button over caption
player.ImageCaptionOnlyDraw(offset_p.x, offset_p.y);
for (auto &i : menu.element)
i.ImageCaptionOnlyDraw(offset_m.x, offset_m.y);
//Now draw the tool-tips for everything combined
player.HoverInfoOnlyDraw(offset_p.x, offset_p.y);
for (auto &i : menu.element)
i.HoverInfoOnlyDraw(offset_m.x, offset_m.y);
}
//------------------------------------------------------------------------
// Purpose: Handle Events
//------------------------------------------------------------------------
void MapMarkerMenu::HandleEvents(const Element &pos, const Vector2i &player_pos, const Rect &camera, const SDL_Event &Event)
{
if (player_pos.x >= camera.x && player_pos.y >= camera.y)
player.HandleEvents(Event, pos.x + player_pos.x - camera.x + offset.player.x, pos.y + player_pos.y - camera.y + offset.player.y);
int choice = menu.HandleEvents(Event, pos.x - camera.x + offset.marker.x, pos.y - camera.y + offset.marker.y);
if (choice != -1)
{
int c = 0;
for (auto &i : menu.element)
{
if (c == choice) //For an already selected marker, clicking it toggles the selection state
i.State(!i.State());
else
i.State(false);
++c;
}
}
}
//------------------------------------------------------------------------
// Purpose: Internal Events
//------------------------------------------------------------------------
void MapMarkerMenu::InternalEvents(const Element &pos, const Vector2i &player_pos, const Rect &camera, Rect bounds)
{
//Find if the player marker is visible or not
{
Rect r(pos.x + player_pos.x - offset.marker.x - camera.x,
pos.y + player_pos.y - offset.marker.y - camera.y,
player.w + offset.marker.x,
player.h + offset.marker.y);
player.visible = bounds.Contains(r);
}
//Redefine p for marker buttons
Vector2i p(pos.x - camera.x + offset.marker.x, pos.y - camera.y + offset.marker.y);
//Calculate visibility for each marker
for (auto &i : menu.element)
{
Rect r(i.x + p.x - offset.marker.x, i.y + p.y - offset.marker.y,
i.w + offset.marker.x, i.h + offset.marker.y);
i.visible = bounds.Contains(r);
}
}
//------------------------------------------------------------------------
// Purpose: Reposition UI
//------------------------------------------------------------------------
void MapMarkerMenu::SetUI()
{
player.SetUI();
menu.SetUI();
}
| 32.830357
| 131
| 0.550993
|
arvindrajayadav
|
da2dddbfcdd1adf6919ed987747f1873ab2d37a0
| 2,387
|
cpp
|
C++
|
src/utils/saves/converter/save_converter.cpp
|
Blackhawk-TA/GateKeeper
|
49a260bf7ba2304f1649b5ed487bc1e55028e672
|
[
"MIT"
] | 1
|
2021-12-31T23:52:57.000Z
|
2021-12-31T23:52:57.000Z
|
src/utils/saves/converter/save_converter.cpp
|
Blackhawk-TA/GateKeeper
|
49a260bf7ba2304f1649b5ed487bc1e55028e672
|
[
"MIT"
] | null | null | null |
src/utils/saves/converter/save_converter.cpp
|
Blackhawk-TA/GateKeeper
|
49a260bf7ba2304f1649b5ed487bc1e55028e672
|
[
"MIT"
] | null | null | null |
//
// Created by daniel on 16.04.22.
//
#include "save_converter.hpp"
#include "../save_types.hpp"
#include "legacy_option_structs.hpp"
#include "legacy_game_structs.hpp"
#include "../options.hpp"
namespace save_converter {
/**
* Updates the options save file by parsing the v0 into the v1 struct.
* If no save is found, nothing is updated.
* @return The amount of game saves that have to be updated
*/
uint8_t update_options_v0_v1() {
OptionsDataV0 old_version{};
bool found = read_save(old_version, options::OPTIONS_DATA_SLOT);
if (found) { //If no save is found, nothing will be updated
save::OptionsData new_version = {
old_version.save_count,
old_version.show_fps,
old_version.show_time,
0,
};
write_save(new_version, options::OPTIONS_DATA_SLOT);
}
return old_version.save_count;
}
/**
* Updates the game save files by parsing the v0 into the v1 struct.
* If no save is found, nothing is updated.
* @param save_count The amount of saves that have to be updated
*/
void update_game_v0_v1(uint8_t save_count) {
//Store saves in heap instead of stack due to limit space on PicoSystem
auto *old_version = new SaveDataV0{};
save::SaveData *new_version;
uint8_t save_slot;
for (uint8_t i = 0; i < save_count; i++) {
save_slot = i + 1;
bool found = read_save(*old_version, save_slot);
if (found) { //If no save is found, nothing will be updated
new_version = new save::SaveData{
old_version->map_section,
old_version->camera_position,
old_version->previous_camera_position,
old_version->player_data,
old_version->game_objects,
old_version->items,
old_version->passed_time,
};
write_save(*new_version, save_slot);
delete new_version;
}
}
delete old_version;
}
void update_save_structs() {
Versions versions = {};
uint8_t save_count = 0;
bool found = read_save(versions, VERSION_SAVE_ID);
if (!found) {
versions = {0, 0};
}
//Convert options save struct to latest version
if (versions.options != OPTIONS_SAVE_VERSION) {
save_count = update_options_v0_v1();
versions.options = OPTIONS_SAVE_VERSION;
}
//Convert game save struct to the latest version
if (versions.game != GAME_SAVE_VERSION) {
update_game_v0_v1(save_count);
versions.game = GAME_SAVE_VERSION;
}
write_save(versions, VERSION_SAVE_ID);
}
}
| 25.945652
| 73
| 0.705069
|
Blackhawk-TA
|
da388e1615ded3dedb83447e19c3edc16cb26a5a
| 1,574
|
hpp
|
C++
|
include/PathPlan/PathPlan.hpp
|
shanghaolong04/ROS-ME3243L2
|
47046804a432638f28689e1d32fd83b15693eeb4
|
[
"MIT"
] | null | null | null |
include/PathPlan/PathPlan.hpp
|
shanghaolong04/ROS-ME3243L2
|
47046804a432638f28689e1d32fd83b15693eeb4
|
[
"MIT"
] | null | null | null |
include/PathPlan/PathPlan.hpp
|
shanghaolong04/ROS-ME3243L2
|
47046804a432638f28689e1d32fd83b15693eeb4
|
[
"MIT"
] | null | null | null |
#include <ros/ros.h>
#include <std_msgs/Float32MultiArray.h> //input from range_finder
#include <nav_msgs/Odometry.h> //input from odometry
#include <geometry_msgs/Point.h>
#include <armadillo>
#include <math.h>
#include <stdio.h>
using namespace std;
using namespace arma;
class PathPlan{
private:
ros::NodeHandle nh_;
ros::Subscriber range_sub_;
ros::Subscriber odom_sub_;
ros::Publisher target_pub_;
ros::Publisher curr_pub_;
cube wall_map; // It's a 3d tensor (can create as row, col, slices)
// for /odom
double pos_x_, pos_y_, ang_z_; //current robot position and orientation in euler angle
// for /range_pub
double dist_north_, dist_east_, dist_south_, dist_west_;
int goal_reached_;
// update the map
void initializeWall();
void setWall(int x, int y, int direction);
void removeWall(int x, int y, int direction);
bool hasWall(int x, int y, int direction);
// callback functions
void rangeCallback(const std_msgs::Float32MultiArray& rangeMsg);
void odomCallback(const nav_msgs::OdometryConstPtr& odomMsg);
//Path Planning Algorithm
Mat<int> path_map_;
vec neighbor_value_ = vec(4, fill::zeros);
int target_x_, target_y_, target_x_prev_, target_y_prev_;
bool path_map_initialized_ = false;
void initializePathMap(); // set all the cell with 1000
void setNextDestCell(); // based on the current position, find the next heading cell
int getPathMapValue(int x, int y);
public:
PathPlan(ros::NodeHandle& nh);
void spin();
void checkWall();
void path_plan_alg();
};
| 25.387097
| 88
| 0.719822
|
shanghaolong04
|
da41858ebc75088435eb30326f25e21ef62df3ed
| 1,823
|
cpp
|
C++
|
app/src/main/jni/comitton/PdfFlate.cpp
|
mryp/ComittoNxA
|
9b46c267bff22c2090d75ac70b589f9a12d61457
|
[
"Unlicense"
] | 14
|
2020-08-05T09:36:01.000Z
|
2022-02-23T01:48:18.000Z
|
app/src/main/jni/comitton/PdfFlate.cpp
|
yuma2a/ComittoNxA-Continued
|
9d85c4f5753e534c3ff0cf83fe53df588872c8ff
|
[
"Unlicense"
] | 1
|
2020-11-17T12:55:17.000Z
|
2020-11-17T12:55:17.000Z
|
app/src/main/jni/comitton/PdfFlate.cpp
|
mryp/ComittoNxA
|
9b46c267bff22c2090d75ac70b589f9a12d61457
|
[
"Unlicense"
] | 4
|
2021-04-21T02:56:50.000Z
|
2021-11-08T12:02:32.000Z
|
#include <android/log.h>
#include "../zlib/zlib.h"
#include "PdfCrypt.h"
int FlateDecompress(BYTE *inbuf, int insize)
{
int result = 0;
int count, status;
BYTE *outbuf = init_buffer();
if (outbuf == NULL) {
return -10;
}
/* すべてのメモリ管理をライブラリに任せる */
z_stream z;
z.zalloc = Z_NULL;
z.zfree = Z_NULL;
z.opaque = Z_NULL;
/* 初期化 */
z.next_in = Z_NULL;
z.avail_in = 0;
if (inflateInit(&z) != Z_OK) {
LOGE("inflateInit: %s\n", (z.msg) ? z.msg : "???");
result = -1;
goto error_end;
}
z.next_out = outbuf; /* 出力ポインタ */
z.avail_out = BUFFER_SIZE; /* 出力バッファ残量 */
status = Z_OK;
z.next_in = inbuf; /* 入力ポインタを入力バッファの先頭に */
z.avail_in = insize; /* データを読み込む */
while (status != Z_STREAM_END) {
#ifdef DEBUG
LOGD("inflate: st=%d, in=%d, out=%d", status, z.avail_in, z.avail_out);
#endif
if (z.avail_in == 0) { /* 入力残量がゼロになれば */
LOGE("inflate: avail_in == 0");
result = -2; /* 入力ポインタを元に戻す */
goto error_end;
}
status = inflate(&z, Z_NO_FLUSH); /* 展開 */
if (status == Z_STREAM_END) {
/* 完了 */
break;
}
if (status != Z_OK) { /* エラー */
LOGE("FlateDecompress : inflate(%s)", (z.msg) ? z.msg : "???");
result = -3;
goto error_end;
}
if (z.avail_out == 0) { /* 出力バッファが尽きれば */
/* まとめて書き出す */
set_buffer(BUFFER_SIZE);
outbuf = add_buffer();
if (outbuf == NULL) {
LOGE("FlateDecompress: add_buffer(result == NULL)");
result = -4;
goto error_end;
}
z.next_out = outbuf; /* 出力ポインタを元に戻す */
z.avail_out = BUFFER_SIZE; /* 出力バッファ残量を元に戻す */
}
}
/* 残りを吐き出す */
if ((count = BUFFER_SIZE - z.avail_out) != 0) {
set_buffer(count);
}
error_end:
/* 後始末 */
if (inflateEnd(&z) != Z_OK) {
LOGE("FlateDecompress : inflateEnd(%s)", (z.msg) ? z.msg : "???");
result = -6;
}
if (result != 0) {
free_buffer();
}
return result;
}
| 20.255556
| 73
| 0.580362
|
mryp
|
da41f9f761a05bbed96caaf415e5b47a97f80768
| 331
|
hpp
|
C++
|
booleannetwork-code-66-trunk/booleannetwork-code-66-trunk/include/BnSimulator/lab/expression_based_distance.hpp
|
Markfrancisrogers/BooleanNetwork
|
62e755d938b70e5907e8561909a0637f0682b9b4
|
[
"Apache-2.0"
] | 2
|
2017-07-04T14:57:48.000Z
|
2017-08-04T19:03:51.000Z
|
booleannetwork-code-66-trunk/booleannetwork-code-66-trunk/include/BnSimulator/lab/expression_based_distance.hpp
|
Markfrancisrogers/BooleanNetwork
|
62e755d938b70e5907e8561909a0637f0682b9b4
|
[
"Apache-2.0"
] | null | null | null |
booleannetwork-code-66-trunk/booleannetwork-code-66-trunk/include/BnSimulator/lab/expression_based_distance.hpp
|
Markfrancisrogers/BooleanNetwork
|
62e755d938b70e5907e8561909a0637f0682b9b4
|
[
"Apache-2.0"
] | null | null | null |
/*
* expression_based_distance.hpp
*
* Created on: Aug 28, 2009
* Author: stewie
*/
#ifndef EXPRESSION_BASED_DISTANCE_HPP_
#define EXPRESSION_BASED_DISTANCE_HPP_
namespace bn {
class Attractor;
double expression_based_distance(const Attractor& a, const Attractor& b);
}
#endif /* EXPRESSION_BASED_DISTANCE_HPP_ */
| 16.55
| 73
| 0.758308
|
Markfrancisrogers
|
da43dc3ef3f70832c233032dde35d8e4c056b28f
| 2,223
|
cpp
|
C++
|
src/pddl_solver_action.cpp
|
ysl208/iRoPro
|
72a8b023755b6396239c24fabef79458bcdc3215
|
[
"MIT"
] | 5
|
2020-11-11T10:51:53.000Z
|
2022-01-13T01:32:11.000Z
|
src/pddl_solver_action.cpp
|
ysl208/rapid_pbd
|
72a8b023755b6396239c24fabef79458bcdc3215
|
[
"MIT"
] | 24
|
2018-05-02T17:33:04.000Z
|
2018-12-19T13:06:52.000Z
|
src/pddl_solver_action.cpp
|
ysl208/rapid_pbd
|
72a8b023755b6396239c24fabef79458bcdc3215
|
[
"MIT"
] | 2
|
2018-05-03T07:02:09.000Z
|
2018-05-03T11:36:53.000Z
|
#include "rapid_pbd/pddl_solver_action.h"
#include "rapid_pbd/action_names.h"
#include <sstream>
#include <string>
#include "actionlib/client/simple_action_client.h"
#include "actionlib/server/simple_action_server.h"
#include "pddl_msgs/PDDLPlannerAction.h"
#include "ros/ros.h"
using actionlib::SimpleClientGoalState;
using pddl_msgs::PDDLPlannerFeedback;
using pddl_msgs::PDDLPlannerGoal;
using pddl_msgs::PDDLPlannerResult;
namespace msgs = pddl_msgs;
namespace rapid {
namespace pbd {
PDDLSolverAction::PDDLSolverAction(const std::string& pddl_server_name,
const std::string& pddl_client_name)
: as_(pddl_server_name, boost::bind(&PDDLSolverAction::Execute, this, _1),
false),
pddl_client_(pddl_client_name, true),
nh_() {}
void PDDLSolverAction::Start() {
while (!pddl_client_.waitForServer(ros::Duration(5))) {
ROS_WARN("Waiting for pddl planner server to come up.");
}
as_.start();
}
void PDDLSolverAction::Execute(const msgs::PDDLPlannerGoalConstPtr& pddl_goal) {
msgs::PDDLPlannerGoal goal = *pddl_goal;
ros::Time start = ros::Time::now();
// ROS_INFO("PDDLSolverAction::Execute... ");
pddl_client_.sendGoal(
goal,
boost::function<void(const SimpleClientGoalState&,
const msgs::PDDLPlannerResult::ConstPtr&)>(),
boost::function<void()>(),
boost::bind(&PDDLSolverAction::HandleFeedback, this, _1));
while (!pddl_client_.getState().isDone()) {
if (as_.isPreemptRequested() || !ros::ok()) {
pddl_client_.cancelAllGoals();
as_.setPreempted();
return;
}
ros::spinOnce();
}
if (pddl_client_.getState() == SimpleClientGoalState::PREEMPTED) {
pddl_client_.cancelAllGoals();
as_.setPreempted();
return;
} else if (pddl_client_.getState() == SimpleClientGoalState::ABORTED) {
pddl_client_.cancelAllGoals();
as_.setAborted();
return;
}
msgs::PDDLPlannerResult::ConstPtr result = pddl_client_.getResult();
as_.setSucceeded(*result);
}
void PDDLSolverAction::HandleFeedback(
const msgs::PDDLPlannerFeedback::ConstPtr& pddl_feedback) {
as_.publishFeedback(*pddl_feedback);
}
} // namespace pbd
} // namespace rapid
| 31.309859
| 80
| 0.699955
|
ysl208
|
da496ddfe11844326936184872e597a7e8acc6e9
| 106
|
cpp
|
C++
|
benignware/1008.cpp
|
CodmingOut/SecretProjectAI
|
addc43117eab30a25453c18fa042739c33cc6cfb
|
[
"MIT"
] | 8
|
2018-04-12T15:54:09.000Z
|
2020-06-05T07:41:15.000Z
|
src/1000/1008.cpp
|
upple/BOJ
|
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
|
[
"MIT"
] | null | null | null |
src/1000/1008.cpp
|
upple/BOJ
|
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
|
[
"MIT"
] | null | null | null |
#include <cstdio>
int main()
{
long double a, b;
scanf("%Lf %Lf", &a, &b);
printf("%.10Lf", a / b);
}
| 11.777778
| 26
| 0.518868
|
CodmingOut
|
da59addf353d403e89648d55b03105a2b42f6b9f
| 17,660
|
cpp
|
C++
|
native/svm_bench.cpp
|
PivovarA/scikit-learn_bench
|
52e96f28eda3ca25d0f51594041fd06ee3f8d4c2
|
[
"MIT"
] | null | null | null |
native/svm_bench.cpp
|
PivovarA/scikit-learn_bench
|
52e96f28eda3ca25d0f51594041fd06ee3f8d4c2
|
[
"MIT"
] | null | null | null |
native/svm_bench.cpp
|
PivovarA/scikit-learn_bench
|
52e96f28eda3ca25d0f51594041fd06ee3f8d4c2
|
[
"MIT"
] | 2
|
2020-08-07T16:19:32.000Z
|
2020-08-07T16:22:12.000Z
|
/*
* Copyright (C) 2018-2019 Intel Corporation
*
* SPDX-License-Identifier: MIT
*/
#include <algorithm>
#include <cassert>
#include <chrono>
#include <cmath>
#include <fstream>
#include <iostream>
#include <utility>
#include <vector>
#define DAAL_DATA_TYPE double
#include "CLI11.hpp"
#include "common.hpp"
#include "daal.h"
#include "npyfile.h"
namespace dam = da::multi_class_classifier;
namespace dak = da::kernel_function;
struct svm_params {
double C;
double tol;
double tau;
int max_iter;
double gamma;
std::string kernel;
};
void print_svm_params(svm_params p) {
std::clog << "@ { C: " << p.C << ", tol: " << p.tol << ", tau: " << p.tau
<< ", max_iter: " << p.max_iter << "}" << std::endl;
}
size_t get_optimal_cache_size(size_t n) {
return sizeof(double) * n * n;
}
std::vector<int> lexicographic_permutation(int n_cl) {
std::vector<int> perm;
int *mat = new int[n_cl * n_cl];
for (int i1 = 0, k = 0; i1 < n_cl; i1++) {
mat[i1 * (n_cl + 1)] = 0;
for (int i2 = 0; i2 < i1; i2++, k++) {
mat[i1 * n_cl + i2] = k;
mat[i2 * n_cl + i1] = 0;
}
}
for (int i1 = 0; i1 < n_cl; i1++) {
for (int i2 = i1 + 1; i2 < n_cl; i2++) {
perm.push_back(mat[i2 * n_cl + i1]);
}
}
delete[] mat;
return perm;
}
#if 1
#define ROUND(x) round(x)
#else
#define ROUND(x) x
#endif
std::vector<std::vector<int>>
group_indices_by_class(int n_classes, double *labels,
std::vector<std::vector<int>> sv_ind_by_clf) {
int max_lbl = -1;
std::vector<std::vector<int>> sv_ind_by_class;
sv_ind_by_class.resize(n_classes);
for (std::vector<std::vector<int>>::iterator it = sv_ind_by_clf.begin();
it != sv_ind_by_clf.end(); ++it) {
std::vector<int> v = *it;
for (std::vector<int>::iterator it2 = v.begin(); it2 != v.end();
++it2) {
int idx = *it2;
int lbl = static_cast<int>(ROUND(labels[idx]));
sv_ind_by_class[lbl].push_back(idx);
if (lbl > max_lbl)
max_lbl = lbl;
}
}
if (max_lbl + 1 < n_classes) {
sv_ind_by_class.resize(max_lbl + 1);
}
return sv_ind_by_class;
}
#define IS_IN_MAP(_map, _key) ((_map).count(_key))
std::map<int, int> map_sv_to_columns_on_dual_coef_matrix(
std::vector<std::vector<int>> sv_ind_by_class) {
std::map<int, int> sv_ind_mapping;
int p = 0;
for (auto indices_per_class : sv_ind_by_class) {
std::sort(indices_per_class.begin(), indices_per_class.end());
for (auto sv_index : indices_per_class) {
if (!IS_IN_MAP(sv_ind_mapping, sv_index)) {
sv_ind_mapping[sv_index] = p;
++p;
}
}
}
return sv_ind_mapping;
}
template <typename T>
void permute_vector(std::vector<T> &v, const std::vector<int> &perm) {
std::vector<T> v_permuted;
v_permuted.reserve(v.size());
for (auto idx : perm)
v_permuted.push_back(v[idx]);
std::swap(v, v_permuted);
}
size_t construct_dual_coefs(dam::training::ResultPtr training_result,
int n_classes, dm::NumericTablePtr Y_nt, int n_rows,
double *dual_coef_ptr, bool verbose) {
dm::BlockDescriptor<double> blockY;
Y_nt->getBlockOfRows(0, n_rows, dm::readOnly, blockY);
double *Y_data_ptr = blockY.getBlockPtr();
dam::ModelPtr multi_svm_model =
training_result->get(da::classifier::training::model);
int num_models = multi_svm_model->getNumberOfTwoClassClassifierModels();
std::vector<double> intercepts(num_models);
std::vector<std::vector<double>> coefs(num_models);
std::vector<std::vector<int>> sv_ind_by_clf(num_models);
std::vector<std::vector<int>> label_indexes(n_classes);
for (int i1 = 0, model_id = 0; i1 < n_classes; i1++) {
for (int j = 0; j < n_rows; j++)
if (Y_data_ptr[j] == i1)
label_indexes[i1].push_back(j);
int idx_len = label_indexes[i1].size();
for (int i2 = 0; i2 < i1; i2++, model_id++) {
auto classifier_model =
multi_svm_model->getTwoClassClassifierModel(model_id);
da::svm::ModelPtr bin_svm_model =
ds::dynamicPointerCast<da::svm::Model>(classifier_model);
dm::NumericTablePtr sv_indx = bin_svm_model->getSupportIndices();
/* sv_ind = np.take(np.hstack((label_indexes[i1],
label_indexes[i2])), two_class_sv_ind_.ravel())
sv_ind_by_clf.append(sv_ind) */
dm::BlockDescriptor<int> block_sv_indx;
int two_class_classifier_sv_len = sv_indx->getNumberOfRows();
sv_indx->getBlockOfRows(0, two_class_classifier_sv_len,
dm::readOnly, block_sv_indx);
int *sv_ind_data_ptr = block_sv_indx.getBlockPtr();
for (int j = 0; j < two_class_classifier_sv_len; j++) {
int sv_idx = sv_ind_data_ptr[j];
sv_ind_by_clf[model_id].push_back(
(sv_idx < idx_len) ? label_indexes[i1][sv_idx]
: label_indexes[i2][sv_idx - idx_len]);
}
sv_indx->releaseBlockOfRows(block_sv_indx);
auto bias = bin_svm_model->getBias();
intercepts.push_back(-bias);
auto sv_coefs = bin_svm_model->getClassificationCoefficients();
dm::BlockDescriptor<double> block_sv_coefs;
sv_coefs->getBlockOfRows(0, two_class_classifier_sv_len,
dm::readOnly, block_sv_coefs);
double *sv_coefs_ptr = block_sv_coefs.getBlockPtr();
for (int q = 0; q < two_class_classifier_sv_len; q++) {
coefs[model_id].push_back(sv_coefs_ptr[q]);
}
sv_coefs->releaseBlockOfRows(block_sv_coefs);
}
}
Y_nt->releaseBlockOfRows(blockY);
std::vector<int> perm = lexicographic_permutation(n_classes);
assert(perm.size() == n_classes * (n_classes - 1) / 2);
permute_vector(sv_ind_by_clf, perm);
permute_vector(intercepts, perm);
permute_vector(coefs, perm);
std::vector<std::vector<int>> sv_ind_by_class =
group_indices_by_class(n_classes, Y_data_ptr, sv_ind_by_clf);
auto mp = map_sv_to_columns_on_dual_coef_matrix(sv_ind_by_class);
size_t num_unique_sv = mp.size();
dual_coef_ptr = new double[(n_classes - 1) * num_unique_sv];
std::vector<int> support_(num_unique_sv);
int p = 0;
for (int i = 0; i < n_classes; i++) {
for (int j = i + 1; j < n_classes; j++, p++) {
std::vector<int> sv_ind_i_vs_j = sv_ind_by_clf[p];
std::vector<double> sv_coef_i_vs_j = coefs[p];
int k = 0;
for (auto sv_index : sv_ind_i_vs_j) {
int label = static_cast<int>(round(Y_data_ptr[sv_index]));
int col_index = mp[sv_index];
int row_index = (j == label) ? i : j - 1;
dual_coef_ptr[row_index * (num_unique_sv) + col_index] =
sv_coef_i_vs_j[k];
support_[col_index] = sv_index;
}
}
}
return num_unique_sv;
}
template <typename dtype = double>
ds::SharedPtr<dak::KernelIface> daal_kernel(char kernel, double gamma) {
assert(kernel == 'l' || kernel == 'r');
assert(gamma > 0);
/* Parameters for the SVM kernel function */
ds::SharedPtr<dak::KernelIface> kernel_ptr;
if (kernel == 'l') {
kernel_ptr.reset(new dak::linear::Batch<dtype>());
} else {
dak::rbf::Batch<dtype> *rbf = new dak::rbf::Batch<dtype>();
rbf->parameter.sigma = sqrt(0.5 / gamma);
kernel_ptr.reset(rbf);
}
return kernel_ptr;
}
template <typename dtype = double>
std::tuple<da::classifier::training::ResultPtr, unsigned long>
svm_fit(svm_params &svc_params, dm::NumericTablePtr Xt, dm::NumericTablePtr Yt,
int n_classes, bool verbose) {
ds::SharedPtr<da::svm::training::Batch<dtype>> training_algo_ptr(
new da::svm::training::Batch<dtype>());
size_t n_features = Xt->getNumberOfColumns();
size_t n_samples = Xt->getNumberOfRows();
ds::SharedPtr<dak::KernelIface> kernel_ptr =
daal_kernel(svc_params.kernel[0], svc_params.gamma);
training_algo_ptr->parameter.C = svc_params.C;
training_algo_ptr->parameter.kernel = kernel_ptr;
training_algo_ptr->parameter.cacheSize = get_optimal_cache_size(n_samples);
training_algo_ptr->parameter.accuracyThreshold = svc_params.tol;
training_algo_ptr->parameter.tau = svc_params.tau;
training_algo_ptr->parameter.maxIterations = svc_params.max_iter;
training_algo_ptr->parameter.doShrinking = true;
ds::SharedPtr<da::classifier::training::Batch> algorithm;
if (n_classes > 2) {
if (verbose) {
std::clog << "@ Using DAAL multi_class_classifier training"
<< std::endl;
}
ds::SharedPtr<dam::training::Batch<dtype>> mc_algorithm(
new dam::training::Batch<dtype>(n_classes));
mc_algorithm->parameter.training = training_algo_ptr;
mc_algorithm->parameter.maxIterations = svc_params.max_iter;
mc_algorithm->parameter.accuracyThreshold = svc_params.tol;
algorithm = mc_algorithm;
} else {
algorithm = training_algo_ptr;
}
/* Pass a training data set and dependent values to the algorithm */
algorithm->getInput()->set(da::classifier::training::data, Xt);
algorithm->getInput()->set(da::classifier::training::labels, Yt);
if (verbose) {
print_svm_params(svc_params);
}
/* Build the SVM model */
algorithm->compute();
auto training_result = algorithm->getResult();
// for multi_class: allocates memory for dual coefficients
double *dual_coefs_ptr = NULL;
size_t sv_len;
auto mc_training_result =
ds::dynamicPointerCast<dam::training::Result>(training_result);
if (mc_training_result) {
sv_len = construct_dual_coefs(mc_training_result, n_classes, Yt,
n_samples, dual_coefs_ptr, verbose);
} else {
auto svm_training_result =
ds::dynamicPointerCast<da::svm::training::Result>(training_result);
assert(svm_training_result);
auto svm_model = ds::dynamicPointerCast<da::svm::Model>(
svm_training_result->get(da::classifier::training::model));
assert(svm_model);
auto sv_idx = svm_model->getSupportIndices();
sv_len = sv_idx->getNumberOfRows();
}
if (dual_coefs_ptr) {
delete[] dual_coefs_ptr;
dual_coefs_ptr = NULL;
}
return std::make_tuple(training_result, sv_len);
}
template <typename dtype = double>
dm::NumericTablePtr
svm_predict(svm_params &svc_params, da::classifier::training::ResultPtr result,
dm::NumericTablePtr X_nt, int n_classes, bool verbose) {
ds::SharedPtr<dak::KernelIface> kernel_ptr =
daal_kernel(svc_params.kernel[0], svc_params.gamma);
ds::SharedPtr<da::svm::prediction::Batch<dtype>> pred_algo_ptr(
new da::svm::prediction::Batch<dtype>());
pred_algo_ptr->parameter.kernel = kernel_ptr;
ds::SharedPtr<da::classifier::prediction::Batch> algorithm;
// Was our result from a multi_class_classifier?
auto mc_training_result =
ds::dynamicPointerCast<dam::training::Result>(result);
if (mc_training_result) {
if (verbose) {
std::clog << "@ Using DAAL multi_class_classifier prediction"
<< std::endl;
}
ds::SharedPtr<dam::prediction::Batch<dtype, dam::prediction::voteBased>>
mc_algorithm(
new dam::prediction::Batch<dtype, dam::prediction::voteBased>(
n_classes));
mc_algorithm->parameter.prediction = pred_algo_ptr;
algorithm = mc_algorithm;
} else {
algorithm = pred_algo_ptr;
}
algorithm->getInput()->set(da::classifier::prediction::data, X_nt);
algorithm->getInput()->set(da::classifier::prediction::model,
result->get(da::classifier::training::model));
algorithm->compute();
return algorithm->getResult()->get(da::classifier::prediction::prediction);
}
int main(int argc, char **argv) {
CLI::App app("Native benchmark code for Intel(R) DAAL SVM classifier");
std::string batch, arch, prefix;
int num_threads;
bool header, verbose;
add_common_args(app, batch, arch, prefix, num_threads, header, verbose);
std::string xfn = "./data/mX.csv";
app.add_option("-x,--fileX", xfn, "Feature file name")
->required()
->check(CLI::ExistingFile);
std::string yfn = "./data/mY.csv";
app.add_option("-y,--fileY", yfn, "Labels file name")
->required()
->check(CLI::ExistingFile);
struct timing_options fit_opts = {100, 100, 10., 10};
add_timing_args(app, "fit", fit_opts);
struct timing_options predict_opts = {10, 100, 10., 10};
add_timing_args(app, "predict", predict_opts);
svm_params params;
params.kernel = "linear";
app.add_option("--kernel", params.kernel, "SVM kernel function")
->check(CLI::IsMember({"linear", "rbf"}));
params.gamma = -1.; // will be replaced by 1 / n_features
app.add_option("--gamma", params.gamma, "Kernel coefficient for 'rbf'")
->check(CLI::PositiveNumber);
params.C = 0.01;
app.add_option("-C,--C", params.C, "SVM slack parameter")
->check(CLI::PositiveNumber);
params.tol = 1e-16;
app.add_option("--tol", params.tol, "Tolerance")
->check(CLI::PositiveNumber);
params.tau = 1e-12;
app.add_option("--tau", params.tau,
"Tau parameter for working set selection scheme")
->check(CLI::PositiveNumber);
params.max_iter = 2000;
app.add_option("--maxiter", params.max_iter,
"Maximum iterations for the iterative solver")
->check(CLI::PositiveNumber);
CLI11_PARSE(app, argc, argv);
/* Load data */
struct npyarr *arrX = load_npy(xfn.c_str());
struct npyarr *arrY = load_npy(yfn.c_str());
if (!arrX || !arrY) {
std::cerr << "Failed to load input arrays" << std::endl;
return EXIT_FAILURE;
}
if (arrX->shape_len != 2) {
std::cerr << "Expected 2 dimensions for X, found " << arrX->shape_len
<< std::endl;
return EXIT_FAILURE;
}
if (arrY->shape_len != 1) {
std::cerr << "Expected 1 dimension for y, found " << arrY->shape_len
<< std::endl;
return EXIT_FAILURE;
}
/* Create numeric tables */
dm::NumericTablePtr X_nt = dm::HomogenNumericTable<double>::create(
(double *) arrX->data, arrX->shape[1], arrX->shape[0]);
dm::NumericTablePtr Y_nt = dm::HomogenNumericTable<int64_t>::create(
(int64_t *) arrY->data, 1, arrY->shape[0]);
size_t n_rows = Y_nt->getNumberOfRows();
size_t n_features = X_nt->getNumberOfColumns();
std::ostringstream string_size_stream;
string_size_stream << n_rows << 'x' << n_features;
std::string stringSize = string_size_stream.str();
int daal_threads = set_threads(num_threads);
int n_classes = count_classes(Y_nt);
if (n_classes == 2) {
// DAAL wants labels in {-1, 1} instead of {0, 1}
int64_t *y_data = (int64_t *) arrY->data;
for (int i = 0; i < arrY->shape[0]; i++) {
if (y_data[i] == 0)
y_data[i] = -1;
}
}
if (params.gamma <= 0) {
params.gamma = 1. / (double) n_features;
}
std::string header_string = "batch,arch,prefix,threads,size,classes,"
"function,cache_size_mb,accuracy,sv_len,time";
std::ostringstream meta_info_stream;
meta_info_stream
<< batch << ','
<< arch << ','
<< prefix << ','
<< daal_threads << ','
<< stringSize << ','
<< n_classes << ',';
std::string meta_info = meta_info_stream.str();
size_t cache_size_mb = get_optimal_cache_size(n_rows) / 1048576;
// Actual benchmark timing here:
bool verbose_fit = verbose;
size_t sv_len = 0;
double time;
da::classifier::training::ResultPtr training_result;
std::tuple<da::classifier::training::ResultPtr,
unsigned long> training_pair;
std::tie(time, training_pair)
= time_min<std::tuple<da::classifier::training::ResultPtr,
unsigned long>> ([&] {
auto r = svm_fit(params, X_nt, Y_nt, n_classes, verbose_fit);
verbose_fit = false;
return r;
}, fit_opts, verbose);
std::tie(training_result, sv_len) = training_pair;
if (header) {
std::cout << header_string << std::endl;
}
std::cout << meta_info << "SVM.fit,"
<< cache_size_mb << ",,"
<< sv_len << ','
<< time << std::endl;
dm::NumericTablePtr Yp_nt;
std::tie(time, Yp_nt) = time_min<dm::NumericTablePtr> ([&] {
return svm_predict(params, training_result, X_nt, n_classes,
verbose);
}, predict_opts, verbose);
double accuracy = accuracy_score(Y_nt, Yp_nt) * 100.00;
std::cout << meta_info << "SVM.predict,"
<< cache_size_mb << ','
<< accuracy << ','
<< sv_len << ','
<< time << std::endl;
return EXIT_SUCCESS;
}
| 33.320755
| 80
| 0.602661
|
PivovarA
|
da5e6e7047b2e62066e7b1d6664ca8b9c4503245
| 3,892
|
cpp
|
C++
|
sample/tutorial19.1/main.cpp
|
adi-g15/json_dto
|
62ce52bcf43eede144c99f74223ffb2aff4659c7
|
[
"BSD-3-Clause"
] | 91
|
2018-05-02T08:31:07.000Z
|
2022-03-20T15:14:14.000Z
|
sample/tutorial19.1/main.cpp
|
adi-g15/json_dto
|
62ce52bcf43eede144c99f74223ffb2aff4659c7
|
[
"BSD-3-Clause"
] | 16
|
2018-12-07T11:42:39.000Z
|
2022-03-29T13:55:33.000Z
|
sample/tutorial19.1/main.cpp
|
adi-g15/json_dto
|
62ce52bcf43eede144c99f74223ffb2aff4659c7
|
[
"BSD-3-Clause"
] | 16
|
2018-08-11T12:55:44.000Z
|
2022-03-15T14:31:51.000Z
|
/*
A sample using map<uint32_t, int> with several custom reader_writers.
*/
#include <cstdio>
#include <iostream>
#include <map>
#include <json_dto/pub.hpp>
// Basic functionality for (de)serializing of values.
struct basic_reader_writer
{
void read(
int & value,
const rapidjson::Value & from ) const
{
// Just use json_dto functionality.
json_dto::read_json_value( value, from );
}
void write(
const int & value,
rapidjson::Value & to,
rapidjson::MemoryPoolAllocator<> & allocator ) const
{
// Just use json_dto functionality.
json_dto::write_json_value( value, to, allocator );
}
};
// Reader_Writer for the case of simple representation of keys.
struct simple_reader_writer : basic_reader_writer
{
using basic_reader_writer::read;
using basic_reader_writer::write;
void read(
json_dto::mutable_map_key_t<std::uint32_t> & key,
const rapidjson::Value & from ) const
{
if( !from.IsString() )
throw std::runtime_error( "string value expected" );
if( 1 != std::sscanf( from.GetString(), "%u", &key.v ) )
throw std::runtime_error( "unable to parse key value" );
}
void write(
const json_dto::const_map_key_t<std::uint32_t> & key,
rapidjson::Value & to,
rapidjson::MemoryPoolAllocator<> & allocator ) const
{
char buf[32];
std::sprintf( buf, "%u", key.v );
to.SetString( buf, allocator );
}
};
// Reader_Writer for the case of representation of keys in hexadecimal form.
struct color_hex_reader_writer : basic_reader_writer
{
using basic_reader_writer::read;
using basic_reader_writer::write;
void read(
json_dto::mutable_map_key_t<std::uint32_t> & key,
const rapidjson::Value & from ) const
{
if( !from.IsString() )
throw std::runtime_error( "string value expected" );
const char * str_v = from.GetString();
if( std::strlen(str_v) < 2u )
throw std::runtime_error( "invalid value length" );
if( '#' != *str_v )
throw std::runtime_error( "invalid value format" );
if( 1 != std::sscanf( str_v+1, "%x", &key.v ) )
throw std::runtime_error( "unable to parse key value" );
}
void write(
const json_dto::const_map_key_t<std::uint32_t> & key,
rapidjson::Value & to,
rapidjson::MemoryPoolAllocator<> & allocator ) const
{
char buf[16];
std::sprintf( buf, "#%06x", key.v );
to.SetString( buf, allocator );
}
};
// Data type to be (de)serialized.
struct data_t
{
std::map< std::uint32_t, int > m_weights;
std::map< std::uint32_t, int > m_colors;
template< typename Json_Io >
void json_io( Json_Io & io )
{
io & json_dto::mandatory(
// Use apply_to_content_t from json_dto to apply
// simple_reader_writer to every member of m_weights.
json_dto::apply_to_content_t< simple_reader_writer >{},
"weights", m_weights )
& json_dto::mandatory(
json_dto::apply_to_content_t< color_hex_reader_writer >{},
"colors", m_colors )
;
}
};
const std::string json_data{
R"JSON({
"weights" : {"1": 1, "2": 2, "3": 3},
"colors" : {"#000000":1, "#FF0000": 2, "#00FF00": 3, "#0000FF": 4}
})JSON" };
int
main( int , char *[] )
{
try
{
{
auto data = json_dto::from_json< data_t >( json_data );
std::cout << "Deserialized from JSON:\n"
<< "weights: ";
for( const auto & kv : data.m_weights )
std::cout << kv.first << "->" << kv.second << ", ";
std::cout << "\n" "colors: ";
for( const auto & kv : data.m_colors )
std::cout << std::hex << kv.first << std::dec << "->" << kv.second << ", ";
std::cout << std::endl;
}
{
data_t data;
data.m_weights[ 3 ] = 33;
data.m_weights[ 2 ] = 22;
data.m_weights[ 1 ] = 11;
data.m_colors[ 0x00FF00 ] = 2;
data.m_colors[ 0xFF00FF ] = 3;
std::cout
<< "\nSerialized to JSON:\n"
<< json_dto::to_json( data ) << std::endl;
}
}
catch( const std::exception & ex )
{
std::cerr << "Error: " << ex.what() << "." << std::endl;
return 1;
}
return 0;
}
| 23.877301
| 79
| 0.643114
|
adi-g15
|
da5efbed9701c6e6a86cf24d139afed676d95a9b
| 799
|
cpp
|
C++
|
Chapter06/Cpp_Js/mainwindow.cpp
|
Vaibhav-Kashyap/Hands-on-GUI-Programming-with-CPP-Qt5-pkt
|
4e964f0f4fc344fb7477c01cb22a04fabb5db965
|
[
"MIT"
] | 87
|
2018-05-03T08:57:23.000Z
|
2022-03-25T03:35:56.000Z
|
Chapter06/Cpp_Js/mainwindow.cpp
|
brutspark/Hands-On-GUI-Programming-with-CPP-and-Qt5
|
4d488dd54734954b06842ea25a256e5e18c7b01c
|
[
"MIT"
] | null | null | null |
Chapter06/Cpp_Js/mainwindow.cpp
|
brutspark/Hands-On-GUI-Programming-with-CPP-and-Qt5
|
4d488dd54734954b06842ea25a256e5e18c7b01c
|
[
"MIT"
] | 51
|
2018-04-28T15:04:52.000Z
|
2022-03-07T13:20:30.000Z
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
webview = new QWebEngineView(ui->verticalFrame);
webview->load(QUrl("qrc:///html/test.html"));
QWebChannel* channel = new QWebChannel(this);
channel->registerObject("mainwindow", this);
webview->page()->setWebChannel(channel);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::doSomething()
{
ui->label->setText("This text has been changed by javascript!");
}
void MainWindow::paintEvent(QPaintEvent *event)
{
QMainWindow::paintEvent(event);
webview->resize(ui->verticalFrame->size());
}
void MainWindow::on_pushButton_clicked()
{
webview->page()->runJavaScript("hello();");
}
| 20.487179
| 68
| 0.692115
|
Vaibhav-Kashyap
|
da63b2b8ddbccd81dfe95dc3ed91945146bb60e6
| 4,820
|
hpp
|
C++
|
h5cpp/H5Tall.hpp
|
ChrisDrozdowski/h5cpp
|
6e41361bf860610dcdaedb557d589af9371a7986
|
[
"BSD-3-Clause-LBNL",
"MIT"
] | null | null | null |
h5cpp/H5Tall.hpp
|
ChrisDrozdowski/h5cpp
|
6e41361bf860610dcdaedb557d589af9371a7986
|
[
"BSD-3-Clause-LBNL",
"MIT"
] | null | null | null |
h5cpp/H5Tall.hpp
|
ChrisDrozdowski/h5cpp
|
6e41361bf860610dcdaedb557d589af9371a7986
|
[
"BSD-3-Clause-LBNL",
"MIT"
] | null | null | null |
/*
* Copyright (c) 2018 vargaconsulting, Toronto,ON Canada
* Author: Varga, Steven <steven@vargaconsulting.ca>
*/
#ifndef H5CPP_TALL_HPP
#define H5CPP_TALL_HPP
namespace h5 {
template<class T> hid_t register_struct(){ return H5I_UNINIT; }
}
/* template specialization from hid_t< .. > type which provides syntactic sugar in the form
* h5::dt_t<int> dt;
* */
namespace h5 { namespace impl { namespace detail {
template<class T> // parent type, data_type is inherited from, see H5Iall.hpp top section for details
using dt_p = hid_t<T,H5Tclose,true,true,hdf5::any>;
/*type id*/
template<class T>
struct hid_t<T,H5Tclose,true,true,hdf5::type> : public dt_p<T> {
using parent = dt_p<T>;
using parent::hid_t; // is a must because of ds_t{hid_t} ctor
using hidtype = T;
hid_t() : parent( H5I_UNINIT){};
};
template <class T> using dt_t = hid_t<T,H5Tclose,true,true,hdf5::type>;
}}}
/* template specialization is for the preceding class, and should be used only for HDF5 ELEMENT types
* which are in C/C++ the integral types of: char,short,int,long, ... and C POD types.
* anything else, the ones which are considered objects/classes are broken down into integral types + container
* then pointer read|write is obtained to the continuous slab and delegated to h5::read | h5::write.
* IF the data is not in a continuous memory region then it must be copied!
*/
#define H5CPP_REGISTER_TYPE_( C_TYPE, H5_TYPE ) \
namespace h5 { namespace impl { namespace detail { \
template <> struct hid_t<C_TYPE,H5Tclose,true,true,hdf5::type> : public dt_p<C_TYPE> {\
using parent = dt_p<C_TYPE>; \
using parent::hid_t; \
using hidtype = C_TYPE; \
hid_t() : parent( H5Tcopy( H5_TYPE ) ) { \
hid_t id = static_cast<hid_t>( *this ); \
if constexpr ( std::is_pointer<C_TYPE>::value ) \
H5Tset_size (id,H5T_VARIABLE), H5Tset_cset(id, H5T_CSET_UTF8); \
} \
}; \
}}} \
namespace h5 { \
template <> struct name<C_TYPE> { \
static constexpr char const * value = #C_TYPE; \
}; \
} \
/* registering integral data-types for NATIVE ones, which means all data is stored in the same way
* in file and memory: TODO: allow different types for file storage
* */
H5CPP_REGISTER_TYPE_(bool,H5T_NATIVE_HBOOL)
H5CPP_REGISTER_TYPE_(unsigned char, H5T_NATIVE_UCHAR) H5CPP_REGISTER_TYPE_(char, H5T_NATIVE_CHAR)
H5CPP_REGISTER_TYPE_(unsigned short, H5T_NATIVE_USHORT) H5CPP_REGISTER_TYPE_(short, H5T_NATIVE_SHORT)
H5CPP_REGISTER_TYPE_(unsigned int, H5T_NATIVE_UINT) H5CPP_REGISTER_TYPE_(int, H5T_NATIVE_INT)
H5CPP_REGISTER_TYPE_(unsigned long int, H5T_NATIVE_ULONG) H5CPP_REGISTER_TYPE_(long int, H5T_NATIVE_LONG)
H5CPP_REGISTER_TYPE_(unsigned long long int, H5T_NATIVE_ULLONG) H5CPP_REGISTER_TYPE_(long long int, H5T_NATIVE_LLONG)
H5CPP_REGISTER_TYPE_(float, H5T_NATIVE_FLOAT) H5CPP_REGISTER_TYPE_(double, H5T_NATIVE_DOUBLE)
H5CPP_REGISTER_TYPE_(long double,H5T_NATIVE_LDOUBLE)
H5CPP_REGISTER_TYPE_(char*, H5T_C_S1)
#define H5CPP_REGISTER_STRUCT( POD_STRUCT ) H5CPP_REGISTER_TYPE_( POD_STRUCT, h5::register_struct<POD_STRUCT>() )
/* type alias is responsible for ALL type maps through H5CPP if you want to screw things up
* start here.
* template parameters:
* hid_t< C_TYPE being mapped, conversion_from_capi, conversion_to_capi, marker_for_this_type>
* */
namespace h5 {
template <class T> using dt_t = h5::impl::detail::hid_t<T,H5Tclose,true,true,h5::impl::detail::hdf5::type>;
template<class T>
hid_t copy( const h5::dt_t<T>& dt ){
hid_t id = static_cast<hid_t>(dt);
H5Iinc_ref( id );
return id;
}
}
template<class T>
inline std::ostream& operator<<(std::ostream &os, const h5::dt_t<T>& dt) {
hid_t id = static_cast<hid_t>( dt );
os << "data type: " << h5::name<T>::value << " ";
os << ( std::is_pointer<T>::value ? "pointer" : "value" );
os << ( H5Iis_valid( id ) > 0 ? " valid" : " invalid");
return os;
}
#endif
| 46.346154
| 118
| 0.586515
|
ChrisDrozdowski
|
da69db25860431cdbf826b6ce01d0eb048903918
| 1,287
|
cpp
|
C++
|
packrat/lib/x86_64-w64-mingw32/3.6.1/Rcpp/unitTests/cpp/table.cpp
|
Denia-Vargas-Araya/ApartamentosR
|
3e62de9946efb5b6545ce431972f5cc790dae673
|
[
"MIT"
] | 113
|
2018-07-12T07:49:33.000Z
|
2021-04-16T12:41:53.000Z
|
packrat/lib/x86_64-w64-mingw32/3.6.1/Rcpp/unitTests/cpp/table.cpp
|
Denia-Vargas-Araya/ApartamentosR
|
3e62de9946efb5b6545ce431972f5cc790dae673
|
[
"MIT"
] | 81
|
2018-03-01T18:05:41.000Z
|
2020-01-15T18:47:31.000Z
|
packrat/lib/x86_64-w64-mingw32/3.6.1/Rcpp/unitTests/cpp/table.cpp
|
Denia-Vargas-Araya/ApartamentosR
|
3e62de9946efb5b6545ce431972f5cc790dae673
|
[
"MIT"
] | 55
|
2017-05-20T12:42:19.000Z
|
2019-03-26T16:38:16.000Z
|
// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; tab-width: 8 -*-
//
// table.cpp: Rcpp R/C++ interface class library -- table<> unit tests
//
// Copyright (C) 2013 Dirk Eddelbuettel, Romain Francois, and Kevin Ushey
//
// This file is part of Rcpp.
//
// Rcpp is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// Rcpp 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 Rcpp. If not, see <http://www.gnu.org/licenses/>.
#include <Rcpp.h>
using namespace Rcpp ;
// [[Rcpp::export]]
IntegerVector RcppTable(SEXP x) {
switch (TYPEOF(x)) {
case INTSXP: return table(as<IntegerVector>(x));
case REALSXP: return table(as<NumericVector>(x));
case STRSXP: return table(as<CharacterVector>(x));
case LGLSXP: return table(as<LogicalVector>(x));
default: {
stop("untested SEXP type");
return R_NilValue;
}
}
}
| 33.868421
| 73
| 0.703186
|
Denia-Vargas-Araya
|
da6b766145ede47778135c7108608703c2474d4d
| 748
|
hpp
|
C++
|
include/wtf/policies/has_focus.hpp
|
ahunter-eyelock/wtf
|
c232d89cdf9817c28c4c4937300caf117bcb6876
|
[
"BSL-1.0"
] | 5
|
2017-05-25T03:41:18.000Z
|
2021-06-05T14:04:30.000Z
|
include/wtf/policies/has_focus.hpp
|
ahunter-eyelock/wtf
|
c232d89cdf9817c28c4c4937300caf117bcb6876
|
[
"BSL-1.0"
] | null | null | null |
include/wtf/policies/has_focus.hpp
|
ahunter-eyelock/wtf
|
c232d89cdf9817c28c4c4937300caf117bcb6876
|
[
"BSL-1.0"
] | 3
|
2021-03-18T20:40:27.000Z
|
2021-04-02T11:46:25.000Z
|
/** @file
@copyright David Mott (c) 2016. Distributed under the Boost Software License Version 1.0. See LICENSE.md or http://boost.org/LICENSE_1_0.txt for details.
*/
#pragma once
#define DOXY_INHERIT_HAS_FOCUS
namespace wtf{
namespace policy{
/** @class has_focus
@brief Provides set_focus and got_focus
@ingroup Policies
*/
template <typename _super_t>
struct has_focus : _super_t{
//! @brief Sets input focus on the window
virtual void set_focus() const { wtf::exception::throw_lasterr_if(::SetFocus(*this), [](HWND h)noexcept { return !h; }); }
//! @brief Determines if the window has input focus
virtual bool got_focus() const{ return _super_t::_handle == ::GetFocus(); }
};
}
}
| 27.703704
| 153
| 0.679144
|
ahunter-eyelock
|
da6ef791e8c410c1681259e16e2b75dec4b5264c
| 10,325
|
hpp
|
C++
|
functions.hpp
|
lorycontixd/PNS
|
23f61833ae75a2425d05ca9757ef471aec930654
|
[
"MIT"
] | null | null | null |
functions.hpp
|
lorycontixd/PNS
|
23f61833ae75a2425d05ca9757ef471aec930654
|
[
"MIT"
] | null | null | null |
functions.hpp
|
lorycontixd/PNS
|
23f61833ae75a2425d05ca9757ef471aec930654
|
[
"MIT"
] | null | null | null |
#ifndef __FUNCTIONS_HPP__
#define __FUNCTIONS_HPP__
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <set>
#include <algorithm>
#include <filesystem>
#include <numeric>
#include <cmath>
#include <vector>
#include <sys/stat.h>
#include "ini_reader.hpp"
#if __cplusplus >= 201703L // C++17 and later
#include <string_view>
#endif
using namespace std;
namespace fs = std::filesystem;
//******************************************************************************************
//************************************* GENERAL ******************************************
//******************************************************************************************
namespace general{
namespace filesystem{
auto count_files(string path){
auto dirIter = fs::directory_iterator(path);
int fileCount = 0;
for (auto& entry : dirIter)
{
++fileCount;
}
return fileCount;
}
}
namespace conversion{
/* Group of functions needed for type conversion
-> to_bool: accepts a string and converts it into a boolean value
-> bool_to_string: returns a boolean from a string. if string_repr is true, it returns the boolean value as a word
*/
bool to_bool(std::string str) {
std::transform(str.begin(), str.end(), str.begin(), ::tolower);
std::istringstream is(str);
bool b;
is >> std::boolalpha >> b;
return b;
}
string bool_to_string(bool b,bool string_repr = true){
if (!string_repr){
return to_string(b);
}else{
return b ? "true" : "false";
}
}
}
namespace input{
/* Set of functions to validate some general input
-> check_config_input: requests that the main program is given a config file as input
*/
string check_config_input(int argc,char** argv){
if (argc!=2){
cerr << "Program requires parameter <config_file>." <<endl;
exit(EXIT_FAILURE);
}
string filename = argv[1];
return filename;
}
}
namespace stream{
/* Utility functions for writing and reading files
-> ReadFile: returns a vector of strings which contains each line of the file
-> UpdateRestartFile: reads file named restart.dat and increments it by 1. (used in programs with restart parameter)
*/
static vector<string> ReadFile(string filename){
ifstream read(filename);
string msg = "Error reading "+filename;
if (!read.is_open() || read.fail()){
cerr << msg << endl;
exit(EXIT_FAILURE);
}
vector<string> lines;
string line;
while (getline(read, line))
{
lines.push_back(line);
}
return lines;
}
static void UpdateRestartFile(){
ifstream FileStream("restart.dat");
int value;
FileStream >> value;
FileStream.close();
ofstream ofs;
ofs.open("restart.dat");
ofs << value+1;
ofs.close();
}
}
namespace strings{
/* Set of functions that work with strings
-> split_string: returns a list of substrings from a string separated by a given delimiter
-> replace_substring: replaces a piece of string with another one
-> split_int: returns a list of integers encoded in a string and separated by a given delimiter (e.g. "1,2,3,4")
*/
vector<string> split_string(string s, string delimiter=","){
vector<string> chars = {"{","}","[","]","(",")"};
vector<string> result;
size_t pos = 0;
string token;
while ((pos = s.find(delimiter)) != std::string::npos) {
token = s.substr(0, pos);
for (unsigned i = 0;i<chars.size();i++){
token.erase(std::remove(token.begin(), token.end(), chars[i].c_str()[0]), token.end());
}
result.push_back(token);
s.erase(0, pos + delimiter.length());
}
return result;
}
// replace a substring of a string with another substring
bool replace_substring(std::string& str, const std::string& from, const std::string& to) {
size_t start_pos = str.find(from);
if(start_pos == std::string::npos)
return false;
str.replace(start_pos, from.length(), to);
return true;
}
//
vector<int> split_int(string s,string delimiter=","){
vector<int> result;
size_t pos = 0;
string token;
while ((pos = s.find(delimiter)) != std::string::npos) {
token = s.substr(0, pos);
result.push_back(stoi(token));
s.erase(0, pos + delimiter.length());
}
return result;
}
string upper(string& str){
int len = str.size();
char b;
for (int i = 0; i < len; i++){
b = str[i];
b = toupper(b);
// b = to lower(b); //alternately
str[i] = b;
}
return str;
}
static bool endsWith(std::string_view str, std::string_view suffix)
{
return str.size() >= suffix.size() && 0 == str.compare(str.size()-suffix.size(), suffix.size(), suffix);
}
} // end general->string
} // end general
namespace console{
/* Functions that write outputs to the console
-> newlines: print a given amount of new lines in the console
-> ConsoleHeader: print a nicely formatted header message in the console
- title(str): string representing the header text
- character(char): character used to format the header message
- length(int,30): total length of the message (includes text and char formatter)
- beforelines(int,0): print a number of empty lines before the header
- afterlines(int,1): print a number of empty lines after the header
-> ConsoleTitle: print a nicely formatted title message in the console.
Titles are a considered a subheader, which means are lower in rank than a header
The parameters of ConsoleTitle are the same as the ones for the ConsoleHeader function.
*/
void newlines(unsigned lines=1){
for (unsigned i = 0; i<lines; i++){
cout << "" << endl;
}
}
void ConsoleHeader(string title,const char* character, int length = 30, int beforelines=0, int afterlines=1){
int _size = title.length();
int _size2 = length - _size - 4;
if (_size2%2==1){
length++;
}
if (_size2<=0){
cerr << "Not enough space to write title. Increase length or shorten title. "<<endl;
exit(EXIT_FAILURE);
}
int i;
string templine = "";
string textline = "";
for (i=0;i<length;i++) templine += character;
for (i=0;i<_size2/2;i++) textline += character;
textline = textline +" "+title+" ";
for (i=0;i<_size2/2;i++) textline += character;
string final;
for (i=0;i<beforelines;i++) final+="\n";
final = templine+"\n"+textline+"\n"+templine;
for (i=0;i<afterlines;i++) final+="\n";
cout << final << flush;
}
static void ConsoleTitle(string title, const char* character, int length=30,int beforelines = 0,int afterlines=2){
int _size = title.length();
int _size2 = length - _size - 4;
if (_size2%2==1){
length++;
}
if (_size2<=0){
cerr << "Not enough space to write title. Increase length or shorten title. "<<endl;
exit(EXIT_FAILURE);
}
int i;
string textline = "";
for (i=0;i<beforelines;i++) textline+="\n";
for (i=0;i<_size2/2;i++) textline += character;
textline = textline +" "+title+" ";
for (i=0;i<_size2/2;i++) textline += character;
for (i=0;i<afterlines;i++) textline+="\n";
cout<<textline<<flush;
}
}
//******************************************************************************************
//*************************************** MATHS ******************************************
//******************************************************************************************
namespace maths{
/* Utility maths functions.
*/
double mean(vector<double>& v){
auto n = v.size();
float average = 0.0f;
if ( n != 0) {
average = accumulate( v.begin(), v.end(), 0.0) / n;
}
return average;
}
//vettore di chi quadri
vector<double> chi_squared(vector<double>& v, double expected_value){
vector<double> chis;
for (vector<double>::const_iterator i = v.begin(); i != v.end(); ++i){
chis.push_back(pow((*i - expected_value),2)/expected_value);
}
return chis;
}
//media di un vettore di chi quadri
double mean_chi_squared(vector<double>& v, double expected_value){
vector<double> chi = chi_squared(v,expected_value);
return mean(chi);
}
}
/*
double progressive_mean(vector<double>& v, unsigned i){
vector<double> temp(i,0.0);
for ()
}*/
//******************************************************************************************
//************************************ INI READER ****************************************
//******************************************************************************************
string sections(INIReader &reader)
{
stringstream ss;
set<std::string> sections = reader.Sections();
for (set<string>::iterator it = sections.begin(); it != sections.end(); ++it)
ss << *it << ",";
return ss.str();
}
void printSettings(INIReader reader){
cout << "Config loaded from file.."<<endl;
cout << "Sections: "<<sections(reader)<<endl;
cout << "- Runs: "<<reader.Get("simulation","runs","UNKNOWN")<<endl;
cout << "- Blocks: "<<reader.Get("simulation","blocks","UNKNOWN")<<endl;
cout << "- Debug mode (Logger): "<<reader.Get("settings","logger_debug","UNKNOWN")<<endl;
cout << "- Debug mode (Data): "<<reader.Get("settings","logger_debug","UNKNOWN")<<endl;
cout << "- Data File: "<<reader.Get("settings","input_file","UNKNOWN")<<endl;
cout << " "<<endl;
}
#endif
| 32.265625
| 122
| 0.531719
|
lorycontixd
|
da765bf582556d6392fd70776cbe7fd61cd980b0
| 2,545
|
cpp
|
C++
|
src/ui/stores/qplayer_rank.cpp
|
svendcsvendsen/judoassistant
|
453211bff86d940c2b2de6f9eea2aabcdab830fa
|
[
"MIT"
] | 3
|
2019-04-26T17:48:24.000Z
|
2021-11-08T20:21:51.000Z
|
src/ui/stores/qplayer_rank.cpp
|
svendcsvendsen/judoassistant
|
453211bff86d940c2b2de6f9eea2aabcdab830fa
|
[
"MIT"
] | 90
|
2019-04-25T17:23:10.000Z
|
2022-02-12T19:49:55.000Z
|
src/ui/stores/qplayer_rank.cpp
|
judoassistant/judoassistant
|
3b200d3e35d9aff16ba224e6071ee9d888a5a03c
|
[
"MIT"
] | null | null | null |
#include "ui/stores/qplayer_rank.hpp"
std::vector<QString> QPlayerRank::strings() const {
switch (mValue) {
case KYU_6: return {tr("6th kyu"), tr("6. kyu"), tr("white"), tr("6 kyu")};
case KYU_5: return {tr("5th kyu"), tr("5. kyu"), tr("yellow"), tr("5 kyu")};
case KYU_4: return {tr("5th kyu"), tr("4. kyu"), tr("orange"), tr("4 kyu")};
case KYU_3: return {tr("3rd kyu"), tr("3. kyu"), tr("green"), tr("3 kyu")};
case KYU_2: return {tr("2nd kyu"), tr("2. kyu"), tr("blue"), tr("2 kyu")};
case KYU_1: return {tr("1st kyu"), tr("1. kyu"), tr("brown"), tr("1 kyu")};
case DAN_1: return {tr("1st dan"), tr("1. dan"), tr("black"), tr("1 dan")};
case DAN_2: return {tr("2nd dan"), tr("2. dan"), tr("2 dan")};
case DAN_3: return {tr("3rd dan"), tr("3. dan"), tr("3 dan")};
case DAN_4: return {tr("4th dan"), tr("4. dan"), tr("4 dan")};
case DAN_5: return {tr("5th dan"), tr("5. dan"), tr("5 dan")};
case DAN_6: return {tr("6th dan"), tr("6. dan"), tr("6 dan")};
case DAN_7: return {tr("7th dan"), tr("7. dan"), tr("7 dan")};
case DAN_8: return {tr("8th dan"), tr("8. dan"), tr("8 dan")};
case DAN_9: return {tr("9th dan"), tr("9. dan"), tr("9 dan")};
case DAN_10: return {tr("10th dan"), tr("10. dan"), tr("10 dan")};
default: return {};
}
}
QPlayerRank QPlayerRank::fromHumanString(const QString &str) {
for (int i = 0; i < static_cast<int>(SIZE); ++i) {
QPlayerRank rank(i);
const auto lower = str.toLower();
for (const QString &repr : rank.strings()) {
if (repr.toLower() == lower)
return rank;
}
}
throw std::invalid_argument(str.toStdString());
}
QString QPlayerRank::toHumanString() const {
switch (mValue) {
case KYU_6: return tr("6th kyu");
case KYU_5: return tr("5th kyu");
case KYU_4: return tr("4th kyu");
case KYU_3: return tr("3rd kyu");
case KYU_2: return tr("2nd kyu");
case KYU_1: return tr("1st kyu");
case DAN_1: return tr("1st dan");
case DAN_2: return tr("2nd dan");
case DAN_3: return tr("3rd dan");
case DAN_4: return tr("4th dan");
case DAN_5: return tr("5th dan");
case DAN_6: return tr("6th dan");
case DAN_7: return tr("7th dan");
case DAN_8: return tr("8th dan");
case DAN_9: return tr("9th dan");
case DAN_10: return tr("10th dan");
default: return "";
}
}
| 41.721311
| 84
| 0.532417
|
svendcsvendsen
|
da784bcc1dd515f021e18bb856749093194c4d30
| 2,675
|
cpp
|
C++
|
dbms/src/AggregateFunctions/AggregateFunctionBitwise.cpp
|
solotzg/tiflash
|
66f45c76692e941bc845c01349ea89de0f2cc210
|
[
"Apache-2.0"
] | 85
|
2022-03-25T09:03:16.000Z
|
2022-03-25T09:45:03.000Z
|
dbms/src/AggregateFunctions/AggregateFunctionBitwise.cpp
|
solotzg/tiflash
|
66f45c76692e941bc845c01349ea89de0f2cc210
|
[
"Apache-2.0"
] | 7
|
2022-03-25T08:59:10.000Z
|
2022-03-25T09:40:13.000Z
|
dbms/src/AggregateFunctions/AggregateFunctionBitwise.cpp
|
solotzg/tiflash
|
66f45c76692e941bc845c01349ea89de0f2cc210
|
[
"Apache-2.0"
] | 11
|
2022-03-25T09:15:36.000Z
|
2022-03-25T09:45:07.000Z
|
// Copyright 2022 PingCAP, Ltd.
//
// 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 <AggregateFunctions/AggregateFunctionBitwise.h>
#include <AggregateFunctions/AggregateFunctionFactory.h>
#include <AggregateFunctions/FactoryHelpers.h>
#include <AggregateFunctions/Helpers.h>
namespace DB
{
namespace
{
template <template <typename> class Data>
AggregateFunctionPtr createAggregateFunctionBitwise(const std::string & name, const DataTypes & argument_types, const Array & parameters)
{
assertNoParameters(name, parameters);
assertUnary(name, argument_types);
if (!argument_types[0]->canBeUsedInBitOperations())
throw Exception(
"The type " + argument_types[0]->getName() + " of argument for aggregate function " + name
+ " is illegal, because it cannot be used in bitwise operations",
ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT);
AggregateFunctionPtr res(createWithUnsignedIntegerType<AggregateFunctionBitwise, Data>(*argument_types[0]));
if (!res)
throw Exception(
"Illegal type " + argument_types[0]->getName() + " of argument for aggregate function " + name,
ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT);
return res;
}
} // namespace
void registerAggregateFunctionsBitwise(AggregateFunctionFactory & factory)
{
factory.registerFunction("groupBitOr", createAggregateFunctionBitwise<AggregateFunctionGroupBitOrData>);
factory.registerFunction("groupBitAnd", createAggregateFunctionBitwise<AggregateFunctionGroupBitAndData>);
factory.registerFunction("groupBitXor", createAggregateFunctionBitwise<AggregateFunctionGroupBitXorData>);
/// Aliases for compatibility with MySQL.
factory.registerFunction("BIT_OR", createAggregateFunctionBitwise<AggregateFunctionGroupBitOrData>, AggregateFunctionFactory::CaseInsensitive);
factory.registerFunction("BIT_AND", createAggregateFunctionBitwise<AggregateFunctionGroupBitAndData>, AggregateFunctionFactory::CaseInsensitive);
factory.registerFunction("BIT_XOR", createAggregateFunctionBitwise<AggregateFunctionGroupBitXorData>, AggregateFunctionFactory::CaseInsensitive);
}
} // namespace DB
| 43.145161
| 149
| 0.771589
|
solotzg
|
da7a96d1e41616858a42a6325bcf59325b52bc38
| 129
|
hpp
|
C++
|
dependencies/glm/gtx/string_cast.hpp
|
realtehcman/-UnderwaterSceneProject
|
72cbd375ef5e175bed8f4e8a4d117f5340f239a4
|
[
"MIT"
] | null | null | null |
dependencies/glm/gtx/string_cast.hpp
|
realtehcman/-UnderwaterSceneProject
|
72cbd375ef5e175bed8f4e8a4d117f5340f239a4
|
[
"MIT"
] | null | null | null |
dependencies/glm/gtx/string_cast.hpp
|
realtehcman/-UnderwaterSceneProject
|
72cbd375ef5e175bed8f4e8a4d117f5340f239a4
|
[
"MIT"
] | null | null | null |
version https://git-lfs.github.com/spec/v1
oid sha256:aa5b82c1ae1426ef3e1db052e6372de0205b816a82ca1571604f565df8c4a55c
size 1286
| 32.25
| 75
| 0.883721
|
realtehcman
|
da7bbb45fd53c4163ebf9ea57ec06f95a34e6713
| 147
|
cpp
|
C++
|
Project1/Src/Object.cpp
|
yokamonian/Onepiece_Shooting_Game
|
a21605342e1cf79910b7a7d7c43af3fb18fde723
|
[
"Unlicense"
] | null | null | null |
Project1/Src/Object.cpp
|
yokamonian/Onepiece_Shooting_Game
|
a21605342e1cf79910b7a7d7c43af3fb18fde723
|
[
"Unlicense"
] | null | null | null |
Project1/Src/Object.cpp
|
yokamonian/Onepiece_Shooting_Game
|
a21605342e1cf79910b7a7d7c43af3fb18fde723
|
[
"Unlicense"
] | null | null | null |
#include "Object.h"
HRESULT Object::Init()
{
return S_OK;
}
void Object::Update()
{
}
void Object::Release()
{
}
void Object::Render()
{
}
| 6.681818
| 22
| 0.612245
|
yokamonian
|
da80f34b45079aa6187fb8433d36568e8b4a0af7
| 6,636
|
cpp
|
C++
|
LibSharpPhysX/Generated/PxFiltering.cpp
|
Alan-FGR/SharpPhysX
|
9b6b49d34c94e2fd165ff50795ae36b32149751b
|
[
"MIT"
] | 23
|
2019-03-17T17:35:06.000Z
|
2022-01-12T01:54:43.000Z
|
LibSharpPhysX/Generated/PxFiltering.cpp
|
Alan-FGR/SharpPhysX
|
9b6b49d34c94e2fd165ff50795ae36b32149751b
|
[
"MIT"
] | 1
|
2019-05-10T22:14:33.000Z
|
2019-05-10T22:48:29.000Z
|
LibSharpPhysX/Generated/PxFiltering.cpp
|
Alan-FGR/SharpPhysX
|
9b6b49d34c94e2fd165ff50795ae36b32149751b
|
[
"MIT"
] | 5
|
2019-03-17T17:36:03.000Z
|
2021-08-06T06:42:58.000Z
|
// Generated by minBND 5.1.94.90 - © github.com/Alan-FGR
ES PxPairFlagsPtr PxPairFlagsPtr_operator_Ptr_Pipe_PxPairFlag_PxPairFlag_(physx::PxPairFlag::Enum wrp_a, physx::PxPairFlag::Enum wrp_b){
auto ret = ::physx::operator|(wrp_a, wrp_b);
auto heap = new char[sizeof PxPairFlags];
std::memcpy(heap, &ret, sizeof PxPairFlags);
return (PxPairFlagsPtr) heap;
}
ES PxPairFlagsPtr PxPairFlagsPtr_operator_Ptr_Amp_PxPairFlag_PxPairFlag_(physx::PxPairFlag::Enum wrp_a, physx::PxPairFlag::Enum wrp_b){
auto ret = ::physx::operator&(wrp_a, wrp_b);
auto heap = new char[sizeof PxPairFlags];
std::memcpy(heap, &ret, sizeof PxPairFlags);
return (PxPairFlagsPtr) heap;
}
ES PxPairFlagsPtr PxPairFlagsPtr_operator_Ptr_Tilde_PxPairFlag_(physx::PxPairFlag::Enum wrp_a){
auto ret = ::physx::operator~(wrp_a);
auto heap = new char[sizeof PxPairFlags];
std::memcpy(heap, &ret, sizeof PxPairFlags);
return (PxPairFlagsPtr) heap;
}
ES PxFilterFlagsPtr PxFilterFlagsPtr_operator_Ptr_Pipe_PxFilterFlag_PxFilterFlag_(physx::PxFilterFlag::Enum wrp_a, physx::PxFilterFlag::Enum wrp_b){
auto ret = ::physx::operator|(wrp_a, wrp_b);
auto heap = new char[sizeof PxFilterFlags];
std::memcpy(heap, &ret, sizeof PxFilterFlags);
return (PxFilterFlagsPtr) heap;
}
ES PxFilterFlagsPtr PxFilterFlagsPtr_operator_Ptr_Amp_PxFilterFlag_PxFilterFlag_(physx::PxFilterFlag::Enum wrp_a, physx::PxFilterFlag::Enum wrp_b){
auto ret = ::physx::operator&(wrp_a, wrp_b);
auto heap = new char[sizeof PxFilterFlags];
std::memcpy(heap, &ret, sizeof PxFilterFlags);
return (PxFilterFlagsPtr) heap;
}
ES PxFilterFlagsPtr PxFilterFlagsPtr_operator_Ptr_Tilde_PxFilterFlag_(physx::PxFilterFlag::Enum wrp_a){
auto ret = ::physx::operator~(wrp_a);
auto heap = new char[sizeof PxFilterFlags];
std::memcpy(heap, &ret, sizeof PxFilterFlags);
return (PxFilterFlagsPtr) heap;
}
ES physx::PxFilterObjectType::Enum PxFilterObjectType_PxGetFilterObjectTypePtr_uint_(PxFilterObjectAttributes wrp_attr){
return (physx::PxFilterObjectType::Enum) ::physx::PxGetFilterObjectType(wrp_attr);
}
ES bool bool_PxFilterObjectIsKinematicPtr_uint_(PxFilterObjectAttributes wrp_attr){
return (bool) ::physx::PxFilterObjectIsKinematic(wrp_attr);
}
ES bool bool_PxFilterObjectIsTriggerPtr_uint_(PxFilterObjectAttributes wrp_attr){
return (bool) ::physx::PxFilterObjectIsTrigger(wrp_attr);
}
ES void Freer_physx_PxFilterDataPtr(PxFilterDataPtr ptr){
delete ptr;
}
ES PxFilterDataPtr Ctor_PxFilterDataPtr_PxEMPTY(physx::PxEMPTY wrp__){
auto ret = *(new std::remove_pointer<PxFilterDataPtr>::type(wrp__));
auto heap = new char[sizeof PxFilterData];
std::memcpy(heap, &ret, sizeof PxFilterData);
return (PxFilterDataPtr) heap;
}
ES PxFilterDataPtr Ctor_PxFilterDataPtr_(){
auto ret = *(new std::remove_pointer<PxFilterDataPtr>::type());
auto heap = new char[sizeof PxFilterData];
std::memcpy(heap, &ret, sizeof PxFilterData);
return (PxFilterDataPtr) heap;
}
ES PxFilterDataPtr Ctor_PxFilterDataPtr_PxFilterDataPtr(PxFilterDataPtr wrp_fd){
auto ret = *(new std::remove_pointer<PxFilterDataPtr>::type(*wrp_fd));
auto heap = new char[sizeof PxFilterData];
std::memcpy(heap, &ret, sizeof PxFilterData);
return (PxFilterDataPtr) heap;
}
ES PxFilterDataPtr Ctor_PxFilterDataPtr_uint_uint_uint_uint(PxU32 wrp_w0, PxU32 wrp_w1, PxU32 wrp_w2, PxU32 wrp_w3){
auto ret = *(new std::remove_pointer<PxFilterDataPtr>::type(wrp_w0, wrp_w1, wrp_w2, wrp_w3));
auto heap = new char[sizeof PxFilterData];
std::memcpy(heap, &ret, sizeof PxFilterData);
return (PxFilterDataPtr) heap;
}
ES PxU32 PxFilterDataPtr_GET_word0(PxFilterDataPtr cls) {return (PxU32)cls->word0;}
ES void PxFilterDataPtr_SET_word0(PxFilterDataPtr cls, PxU32 value) {cls->word0 = value;}
ES PxU32 PxFilterDataPtr_GET_word1(PxFilterDataPtr cls) {return (PxU32)cls->word1;}
ES void PxFilterDataPtr_SET_word1(PxFilterDataPtr cls, PxU32 value) {cls->word1 = value;}
ES PxU32 PxFilterDataPtr_GET_word2(PxFilterDataPtr cls) {return (PxU32)cls->word2;}
ES void PxFilterDataPtr_SET_word2(PxFilterDataPtr cls, PxU32 value) {cls->word2 = value;}
ES PxU32 PxFilterDataPtr_GET_word3(PxFilterDataPtr cls) {return (PxU32)cls->word3;}
ES void PxFilterDataPtr_SET_word3(PxFilterDataPtr cls, PxU32 value) {cls->word3 = value;}
ES void void_PxFilterDataPtr_setToDefaultPtr(PxFilterDataPtr wrp_this){
wrp_this->setToDefault();
}
ES void void_PxFilterDataPtr_operator_Ptr_Equal_PxFilterDataPtr_(PxFilterDataPtr wrp_lhs, PxFilterDataPtr wrp_fd){
wrp_lhs->::physx::PxFilterData::operator=(*wrp_fd);
}
ES bool bool_const_PxFilterDataPtr_operator_Ptr_EqualEqual_PxFilterDataPtr_(PxFilterDataPtr wrp_lhs, PxFilterDataPtr wrp_a){
return (bool) wrp_lhs->::physx::PxFilterData::operator==(*wrp_a);
}
ES bool bool_const_PxFilterDataPtr_operator_Ptr_ExclaimEqual_PxFilterDataPtr_(PxFilterDataPtr wrp_lhs, PxFilterDataPtr wrp_a){
return (bool) wrp_lhs->::physx::PxFilterData::operator!=(*wrp_a);
}
ES PxFilterFlagsPtr PxFilterFlagsPtr_PxSimulationFilterCallbackPtr_pairFoundPtr_uint_uint_PxFilterDataPtr_PxActorPtr_PxShapePtr_uint_PxFilterDataPtr_PxActorPtr_PxShapePtr_PxPairFlagsPtr_(PxSimulationFilterCallbackPtr wrp_this, PxU32 wrp_pairID, PxFilterObjectAttributes wrp_attributes0, PxFilterDataPtr wrp_filterData0, PxActorPtr wrp_a0, PxShapePtr wrp_s0, PxFilterObjectAttributes wrp_attributes1, PxFilterDataPtr wrp_filterData1, PxActorPtr wrp_a1, PxShapePtr wrp_s1, PxPairFlagsPtr wrp_pairFlags){
auto ret = wrp_this->pairFound(wrp_pairID, wrp_attributes0, *wrp_filterData0, wrp_a0, wrp_s0, wrp_attributes1, *wrp_filterData1, wrp_a1, wrp_s1, *wrp_pairFlags);
auto heap = new char[sizeof PxFilterFlags];
std::memcpy(heap, &ret, sizeof PxFilterFlags);
return (PxFilterFlagsPtr) heap;
}
ES void void_PxSimulationFilterCallbackPtr_pairLostPtr_uint_uint_PxFilterDataPtr_uint_PxFilterDataPtr_bool_(PxSimulationFilterCallbackPtr wrp_this, PxU32 wrp_pairID, PxFilterObjectAttributes wrp_attributes0, PxFilterDataPtr wrp_filterData0, PxFilterObjectAttributes wrp_attributes1, PxFilterDataPtr wrp_filterData1, bool wrp_objectRemoved){
wrp_this->pairLost(wrp_pairID, wrp_attributes0, *wrp_filterData0, wrp_attributes1, *wrp_filterData1, wrp_objectRemoved);
}
ES bool bool_PxSimulationFilterCallbackPtr_statusChangePtr_uint_PxPairFlagsPtr_PxFilterFlagsPtr_(PxSimulationFilterCallbackPtr wrp_this, PxU32* wrp_pairID, PxPairFlagsPtr wrp_pairFlags, PxFilterFlagsPtr wrp_filterFlags){
return (bool) wrp_this->statusChange(*wrp_pairID, *wrp_pairFlags, *wrp_filterFlags);
}
| 50.272727
| 501
| 0.795961
|
Alan-FGR
|
da85f4026964f9d9d947e89e3a3db18e2007d68d
| 1,443
|
hpp
|
C++
|
Network_Library_Windows/Header_Files/CNetworkLib.hpp
|
SebastienKeroack/MyEA
|
5130056735199595c28c274cf67e7addb280aabc
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
Network_Library_Windows/Header_Files/CNetworkLib.hpp
|
SebastienKeroack/MyEA
|
5130056735199595c28c274cf67e7addb280aabc
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
Network_Library_Windows/Header_Files/CNetworkLib.hpp
|
SebastienKeroack/MyEA
|
5130056735199595c28c274cf67e7addb280aabc
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
/* Copyright 2020 Sébastien Kéroack. 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.
==============================================================================*/
#pragma once
#include <string>
#include <CObject.hpp>
namespace MyEA
{
namespace Network
{
bool Network_Connect_HTTP(bool const use_ssl_received,
unsigned int const try_counTreceived,
unsigned int const try_waiTmilliseconds_received,
wchar_t const *const wc_ptr_url_received);
bool Network_Connect(unsigned short const porTreceived,
unsigned int const try_counTreceived,
unsigned int const try_waiTmilliseconds_received,
wchar_t const *const wc_ptr_url_received);
}
}
| 40.083333
| 100
| 0.593902
|
SebastienKeroack
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.