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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ff05932e8e55201de1611d969f06a644cc0a651f | 2,062 | cpp | C++ | src/UI/Core/TextArea.cpp | Goof-fr/OPHD | ab3414181b04ab2757b124d81fd5592f930c5370 | [
"BSD-3-Clause"
] | 2 | 2020-01-27T19:44:45.000Z | 2020-01-27T19:44:49.000Z | src/UI/Core/TextArea.cpp | Goof-fr/OPHD | ab3414181b04ab2757b124d81fd5592f930c5370 | [
"BSD-3-Clause"
] | null | null | null | src/UI/Core/TextArea.cpp | Goof-fr/OPHD | ab3414181b04ab2757b124d81fd5592f930c5370 | [
"BSD-3-Clause"
] | null | null | null | // This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
#include "TextArea.h"
#include "../../Common.h"
#include "../../Constants.h"
#include "../../FontManager.h"
#include "NAS2D/Utility.h"
#include "NAS2D/Renderer/Renderer.h"
using namespace NAS2D;
void TextArea::font(const std::string& font, size_t size)
{
mFont = Utility<FontManager>::get().font(font, size);
}
void TextArea::processString()
{
mFormattedList.clear();
if (width() < 10 || !mFont || text().empty()) { return; }
StringList tokenList = split_string(text().c_str(), ' ');
size_t w = 0, i = 0;
while (i < tokenList.size())
{
std::string line;
while (w < width() && i < tokenList.size())
{
int tokenWidth = mFont->width(tokenList[i] + " ");
w += tokenWidth;
if (w >= width())
{
/**
* \todo In some edge cases where the width of the TextArea is too
* narrow for a single word/token, this will result in an infinite
* loop. This edge case will need to be resolved either by splitting
* the token that's too wide or by simply rendering it as is.
*/
//++i;
break;
}
if (tokenList[i] == "\n")
{
++i;
break;
}
line += (tokenList[i] + " ");
++i;
}
w = 0;
mFormattedList.push_back(line);
}
mNumLines = static_cast<size_t>(height() / mFont->height());
}
void TextArea::onSizeChanged()
{
Control::onSizeChanged();
processString();
}
void TextArea::onTextChanged()
{
processString();
}
void TextArea::onFontChanged()
{
processString();
}
void TextArea::update()
{
draw();
}
void TextArea::draw()
{
Renderer& r = Utility<Renderer>::get();
if (highlight()) { r.drawBox(rect(), 255, 255, 255); }
if (!mFont) { return; }
for (size_t i = 0; i < mFormattedList.size() && i < mNumLines; ++i)
{
r.drawText(*mFont, mFormattedList[i], positionX(), positionY() + (mFont->height() * i), mTextColor.red(), mTextColor.green(), mTextColor.blue(), mTextColor.alpha());
}
}
| 19.826923 | 167 | 0.618817 | Goof-fr |
ff0dbeaaa207b26349a0dd1cccc12db72b12809c | 317 | hpp | C++ | include/RED4ext/Scripting/Natives/Generated/game/PSMZones.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 42 | 2020-12-25T08:33:00.000Z | 2022-03-22T14:47:07.000Z | include/RED4ext/Scripting/Natives/Generated/game/PSMZones.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 38 | 2020-12-28T22:36:06.000Z | 2022-02-16T11:25:47.000Z | include/RED4ext/Scripting/Natives/Generated/game/PSMZones.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 20 | 2020-12-28T22:17:38.000Z | 2022-03-22T17:19:01.000Z | #pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
namespace RED4ext
{
namespace game {
enum class PSMZones : uint32_t
{
Default = 0,
Public = 1,
Safe = 2,
Restricted = 3,
Dangerous = 4,
Any = 4294967295,
};
} // namespace game
} // namespace RED4ext
| 15.85 | 57 | 0.649842 | jackhumbert |
ff14623c4a3e531d648f00c5d95c6fcc02d58690 | 2,679 | cc | C++ | thirdparty/aria2/test/array_funTest.cc | deltegic/deltegic | 9b4f3a505a6842db52efbe850150afbab3af5e2f | [
"BSD-3-Clause"
] | null | null | null | thirdparty/aria2/test/array_funTest.cc | deltegic/deltegic | 9b4f3a505a6842db52efbe850150afbab3af5e2f | [
"BSD-3-Clause"
] | 2 | 2021-04-08T08:46:23.000Z | 2021-04-08T08:57:58.000Z | thirdparty/aria2/test/array_funTest.cc | deltegic/deltegic | 9b4f3a505a6842db52efbe850150afbab3af5e2f | [
"BSD-3-Clause"
] | null | null | null | #include "array_fun.h"
#include <cppunit/extensions/HelperMacros.h>
using namespace aria2::expr;
namespace aria2 {
class array_funTest : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(array_funTest);
CPPUNIT_TEST(testArray_negate);
CPPUNIT_TEST(testArray_and);
CPPUNIT_TEST(testArrayLength);
CPPUNIT_TEST(testArrayWrapper);
CPPUNIT_TEST_SUITE_END();
public:
void testBit_negate();
void testBit_and();
void testArray_negate();
void testArray_and();
void testArrayLength();
void testArrayWrapper();
struct X {
int m;
};
};
CPPUNIT_TEST_SUITE_REGISTRATION(array_funTest);
void array_funTest::testArray_negate()
{
unsigned char a[] = {0xaa, 0x55};
CPPUNIT_ASSERT_EQUAL((unsigned char)0x55, (~array(a))[0]);
CPPUNIT_ASSERT_EQUAL((unsigned char)0xaa, (~array((unsigned char*)a))[1]);
CPPUNIT_ASSERT_EQUAL((unsigned char)0xaa, (~~array(a))[0]);
CPPUNIT_ASSERT_EQUAL((unsigned char)0x55, (~~array(a))[1]);
}
void array_funTest::testArray_and()
{
unsigned char a1[] = {0xaa, 0x55};
unsigned char a2[] = {0x1a, 0x25};
CPPUNIT_ASSERT_EQUAL((unsigned char)0x0a, (array(a1) & array(a2))[0]);
CPPUNIT_ASSERT_EQUAL((unsigned char)0x05, (array(a1) & array(a2))[1]);
CPPUNIT_ASSERT_EQUAL((unsigned char)0xa0, (array(a1) & ~array(a2))[0]);
CPPUNIT_ASSERT_EQUAL((unsigned char)0x50, (array(a1) & ~array(a2))[1]);
CPPUNIT_ASSERT_EQUAL((unsigned char)0xa0, (~array(a2) & array(a1))[0]);
CPPUNIT_ASSERT_EQUAL((unsigned char)0x50, (~array(a2) & array(a1))[1]);
CPPUNIT_ASSERT_EQUAL((unsigned char)0x45, (~array(a1) & ~array(a2))[0]);
CPPUNIT_ASSERT_EQUAL((unsigned char)0x8a, (~array(a1) & ~array(a2))[1]);
}
void array_funTest::testArrayLength()
{
int64_t ia[] = {1, 2, 3, 4, 5};
CPPUNIT_ASSERT_EQUAL((size_t)5, arraySize(ia));
// This causes compile error under clang and gcc v3.4.3 opensolaris
// 5.11
// int64_t zeroLengthArray[] = {};
// CPPUNIT_ASSERT_EQUAL((size_t)0, arraySize(zeroLengthArray));
}
namespace {
void arrayPtrCast(struct array_funTest::X* x) {}
} // namespace
namespace {
void arrayPtrConstCast(const struct array_funTest::X* x) {}
} // namespace
namespace {
void arrayWrapperConst(const array_wrapper<int, 10>& array)
{
CPPUNIT_ASSERT_EQUAL(9, array[9]);
}
} // namespace
void array_funTest::testArrayWrapper()
{
array_wrapper<int, 10> a1;
CPPUNIT_ASSERT_EQUAL((size_t)10, a1.size());
for (size_t i = 0; i < a1.size(); ++i) {
a1[i] = i;
}
CPPUNIT_ASSERT_EQUAL(9, a1[9]);
array_wrapper<int, 10> a2 = a1;
CPPUNIT_ASSERT_EQUAL(9, a2[9]);
arrayWrapperConst(a2);
array_wrapper<struct X, 10> x1;
arrayPtrCast(x1);
arrayPtrConstCast(x1);
}
} // namespace aria2
| 26.009709 | 76 | 0.702128 | deltegic |
d4332047cfa3d0a3a68ad938fae594992542c332 | 1,032 | hpp | C++ | libvvhd/headers/XIsoline.hpp | rosik/vvflow | 87caadf3973b31058a16a1372365ae8a7a157cdb | [
"MIT"
] | 29 | 2020-08-05T16:08:35.000Z | 2022-02-21T06:43:01.000Z | libvvhd/headers/XIsoline.hpp | rosik/vvflow | 87caadf3973b31058a16a1372365ae8a7a157cdb | [
"MIT"
] | 6 | 2021-01-07T21:29:57.000Z | 2021-06-28T20:54:04.000Z | libvvhd/headers/XIsoline.hpp | rosik/vvflow | 87caadf3973b31058a16a1372365ae8a7a157cdb | [
"MIT"
] | 6 | 2020-07-24T06:53:54.000Z | 2022-01-06T06:12:45.000Z | #pragma once
#include "XField.hpp"
#include <list>
#include <deque>
#include <sstream>
class XIsoline {
public:
XIsoline() = delete;
XIsoline(const XIsoline&) = delete;
XIsoline(XIsoline&&) = delete;
XIsoline& operator=(const XIsoline&) = delete;
XIsoline& operator=(XIsoline&&) = delete;
XIsoline(
const XField &field,
double vmin,
double vmax,
double dv
);
// ~XIsoline();
friend std::ostream& operator<< (std::ostream& os, const XIsoline&);
private:
struct TPoint {
float x, y;
TPoint(): x(0),y(0) {}
TPoint(float x, float y): x(x), y(y) {}
inline bool operator==(const TPoint &v) const {
return (v.x == x) && (v.y == y);
}
};
typedef std::deque<TPoint> TLine;
std::list<TLine> isolines;
float xmin, ymin, dxdy;
private:
void merge_lines(TLine* dst, bool dst_side);
void commit_segment(TPoint p1, TPoint p2);
void process_rect(float x, float y, float z[5], float C);
};
| 22.933333 | 72 | 0.585271 | rosik |
d43ce46ed6cf430880372955c8ab51fc2c09aca2 | 1,184 | cpp | C++ | tests/regression/GoToLoops1/test.cpp | SusanTan/noelle | 33c9e10a20bc59590c13bf29fb661fc406a9e687 | [
"MIT"
] | 43 | 2020-09-04T15:21:40.000Z | 2022-03-23T03:53:02.000Z | tests/regression/GoToLoops1/test.cpp | SusanTan/noelle | 33c9e10a20bc59590c13bf29fb661fc406a9e687 | [
"MIT"
] | 15 | 2020-09-17T18:06:15.000Z | 2022-01-24T17:14:36.000Z | tests/regression/GoToLoops1/test.cpp | SusanTan/noelle | 33c9e10a20bc59590c13bf29fb661fc406a9e687 | [
"MIT"
] | 23 | 2020-09-04T15:50:09.000Z | 2022-03-25T13:38:25.000Z | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
void func1();
void func2();
int sccCausing1 = 0;
void func1() {
if (sccCausing1++ > 2) {
sccCausing1 = 0;
func2();
}
}
int sccCausing2 = 1;
void func2() {
if (sccCausing2++ > 2) {
sccCausing2 = 0;
func1();
}
}
int main (int argc, char *argv[]){
if (argc < 2){
fprintf(stderr, "USAGE: %s LOOP_ITERATIONS\n", argv[0]);
return -1;
}
auto iterations = atoll(argv[1]);
if (iterations == 0) return 0;
LOOP0:
auto maxIters2 = iterations;
int i = 0, j = 0, k = 0;
for (i = 0; i < iterations; ++i) {
// Introduce a control flow path from loop 0 to loop 2
if (maxIters2 == 0) {
maxIters2 = iterations;
} else {
j = 0;
goto LOOP2;
}
LOOP1:
for (j = 0; j < argc; ++j) {
func1();
// LLVM doesn't even identify this as a loop...
LOOP2:
for (k = 0; k < argc; ++k) {
func2();
// Introduce a control flow path from loop 2 to loop 0
if (maxIters2-- == 0) goto LOOP0_NEXT_ITER;
}
}
LOOP0_NEXT_ITER:
continue;
}
printf("%d, %d\n", sccCausing1, sccCausing2);
return 0;
} | 17.411765 | 62 | 0.537162 | SusanTan |
d43f88f0da65efa13a81277c2e8a34f637314dfe | 3,186 | cpp | C++ | JAERO/tests/fftwrapper_tests.cpp | Roethenbach/JAERO | 753a4409507a356489f3635b93dc16955c8cf01a | [
"MIT"
] | 152 | 2015-12-02T01:38:42.000Z | 2022-03-29T10:41:37.000Z | JAERO/tests/fftwrapper_tests.cpp | Roethenbach/JAERO | 753a4409507a356489f3635b93dc16955c8cf01a | [
"MIT"
] | 59 | 2015-12-02T02:11:24.000Z | 2022-03-21T02:48:11.000Z | JAERO/tests/fftwrapper_tests.cpp | Roethenbach/JAERO | 753a4409507a356489f3635b93dc16955c8cf01a | [
"MIT"
] | 38 | 2015-12-07T16:24:03.000Z | 2021-12-25T15:44:27.000Z | #include "../fftwrapper.h"
#include "../util/RuntimeError.h"
#include "../DSP.h"
//important for Qt include cpputest last as it mucks up new and causes compiling to fail
#include "CppUTest/TestHarness.h"
TEST_GROUP(Test_FFTWrapper)
{
const double doubles_equal_threshold=0.00001;
void setup()
{
srand(1);
}
void teardown()
{
// This gets run after every test
}
};
TEST(Test_FFTWrapper, fftwrapper_matches_unusual_kissfft_scalling_as_expected_by_old_jaero_code_by_default)
{
//this was obtained from v1.0.4.11 of JAERO
QVector<cpx_type> input={cpx_type(-0.997497,0.127171),cpx_type(-0.613392,0.617481),cpx_type(0.170019,-0.040254),cpx_type(-0.299417,0.791925),cpx_type(0.645680,0.493210),cpx_type(-0.651784,0.717887),cpx_type(0.421003,0.027070),cpx_type(-0.392010,-0.970031),cpx_type(-0.817194,-0.271096),cpx_type(-0.705374,-0.668203),cpx_type(0.977050,-0.108615),cpx_type(-0.761834,-0.990661),cpx_type(-0.982177,-0.244240),cpx_type(0.063326,0.142369),cpx_type(0.203528,0.214331),cpx_type(-0.667531,0.326090)};
QVector<cpx_type> expected_forward={cpx_type(-4.407605,0.164434),cpx_type(2.204298,2.308064),cpx_type(-2.713014,-1.356784),cpx_type(-2.347572,1.698848),cpx_type(-2.270577,-0.201056),cpx_type(1.611736,-2.136282),cpx_type(-0.902078,1.606222),cpx_type(0.335445,-0.964384),cpx_type(3.648427,0.230720),cpx_type(-2.707027,-3.571981),cpx_type(-1.023916,-0.474082),cpx_type(1.792787,2.825653),cpx_type(-5.574999,0.226081),cpx_type(1.119577,-1.518164),cpx_type(-1.273769,-1.346937),cpx_type(-3.451670,4.544378)};
QVector<cpx_type> expected_forward_backwards={cpx_type(-15.959960,2.034730),cpx_type(-9.814264,9.879696),cpx_type(2.720298,-0.644063),cpx_type(-4.790674,12.670797),cpx_type(10.330882,7.891354),cpx_type(-10.428541,11.486190),cpx_type(6.736045,0.433119),cpx_type(-6.272164,-15.520493),cpx_type(-13.075106,-4.337535),cpx_type(-11.285989,-10.691244),cpx_type(15.632801,-1.737846),cpx_type(-12.189337,-15.850581),cpx_type(-15.714835,-3.907834),cpx_type(1.013215,2.277902),cpx_type(3.256447,3.429304),cpx_type(-10.680502,5.217444)};
int nfft=input.size();
CHECK(input.size()==nfft);
CHECK(expected_forward.size()==nfft);
CHECK(expected_forward_backwards.size()==nfft);
FFTWrapper<double> fft=FFTWrapper<double>(nfft,false);
FFTWrapper<double> ifft=FFTWrapper<double>(nfft,true);
QVector<cpx_type> actual_forward,actual_forward_backwards;
actual_forward.resize(nfft);
actual_forward_backwards.resize(nfft);
CHECK(actual_forward.size()==nfft);
CHECK(actual_forward_backwards.size()==nfft);
fft.transform(input,actual_forward);
ifft.transform(actual_forward,actual_forward_backwards);
for(int k=0;k<nfft;k++)
{
DOUBLES_EQUAL(actual_forward[k].real(),expected_forward[k].real(),doubles_equal_threshold);
DOUBLES_EQUAL(actual_forward[k].imag(),expected_forward[k].imag(),doubles_equal_threshold);
DOUBLES_EQUAL(actual_forward_backwards[k].real(),expected_forward_backwards[k].real(),doubles_equal_threshold);
DOUBLES_EQUAL(actual_forward_backwards[k].imag(),expected_forward_backwards[k].imag(),doubles_equal_threshold);
}
}
| 57.927273 | 527 | 0.743879 | Roethenbach |
d440af2356c934fd13611eaccc185007e848b38f | 2,411 | cpp | C++ | inorder_traversal.cpp | akhilesh59/Programming-Helpers | c4af814f99fc8288e28fb6fb8fee61acf9549f2c | [
"MIT"
] | null | null | null | inorder_traversal.cpp | akhilesh59/Programming-Helpers | c4af814f99fc8288e28fb6fb8fee61acf9549f2c | [
"MIT"
] | null | null | null | inorder_traversal.cpp | akhilesh59/Programming-Helpers | c4af814f99fc8288e28fb6fb8fee61acf9549f2c | [
"MIT"
] | 6 | 2021-10-21T13:01:30.000Z | 2021-10-31T08:29:34.000Z |
// RECURSION METHOD
// #include <iostream>
// using namespace std;
// struct Node {
// int data;
// Node *left, *right;
// Node (int data) {
// this->data = data;
// this->left = this->right = nullptr;
// }
// };
// // recursion function
// void inorder(Node* root) {
// if (root == nullptr)
// return;
// inorder(root->left);
// cout << root -> data << " ";
// inorder(root->right);
// }
// int main() {
// /* Construct the following tree
// 1
// / \
// / \
// 2 3
// / / \
// / / \
// 4 5 6
// / \
// / \
// 7 8
// */
// Node* root = new Node(1);
// root->left = new Node(2);
// root->right = new Node(3);
// root->left->left = new Node(4);
// root->right->left = new Node(4);
// root->right->right = new Node(4);
// root->right->left->left = new Node(4);
// root->right->left->right = new Node(4);
// inorder(root);
// return 0;
// }
//**************************************************************
// Iterative method
#include <iostream>
#include <stack>
using namespace std;
struct Node {
int data;
Node *left, *right;
Node(int data) {
this->data = data;
this->left = this->right = nullptr;
}
};
void inorderIterative (Node* root) {
stack<Node*> stack;
Node* curr = root;
while (!stack.empty() || curr != nullptr) {
if (curr != nullptr) {
stack.push(curr) ;
curr = curr->left;
}
else {
curr = stack.top();
stack.pop();
cout << curr->data << " ";
curr = curr-> right;
}
}
}
int main()
{
/* Construct the following tree
1
/ \
/ \
2 3
/ / \
/ / \
4 5 6
/ \
/ \
7 8
*/
Node *root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->right->left = new Node(5);
root->right->right = new Node(6);
root->right->left->left = new Node(7);
root->right->left->right = new Node(8);
inorderIterative(root);
return 0;
} | 19.601626 | 64 | 0.404811 | akhilesh59 |
d440b79d4eeeecba139bcead65783a7cf67fb3c2 | 5,961 | cpp | C++ | kcalg/sec/zk/ffs/ffsa.cpp | kn1ghtc/kctsb | ee0e5b31dbe293dad0fb6ea5acf5da1652e4e733 | [
"Apache-2.0"
] | 1 | 2021-03-16T00:10:51.000Z | 2021-03-16T00:10:51.000Z | kcalg/sec/zk/ffs/ffsa.cpp | kn1ghtc/kctsb | ee0e5b31dbe293dad0fb6ea5acf5da1652e4e733 | [
"Apache-2.0"
] | null | null | null | kcalg/sec/zk/ffs/ffsa.cpp | kn1ghtc/kctsb | ee0e5b31dbe293dad0fb6ea5acf5da1652e4e733 | [
"Apache-2.0"
] | null | null | null | #include "ffsa.h"
#include "opentsb/kc_sec.h"
#include <iostream>
/*check GMP number for primality*/
bool ffsa_check_prime(mpz_class p)
{
int8_t reps = 25;
int prob = mpz_probab_prime_p(p.get_mpz_t(), reps);
if(prob == 2)
return true;
else if(prob == 0)
return false;
else if(prob == 1)
{
/*REMARK: Instead of increasing the reps(maybe even n number of times)
one may run some deterministic prime verification algorithm like AKS
to provide a level of certainty. But, since Miller-Rabin is likely or
almost definitely destined to return "probably prime", one may also
consider going with a deterministic version all along as the speedup
may not be achieved through double checking.*/
reps = 50;
prob = mpz_probab_prime_p(p.get_mpz_t(), reps);
if(prob == 2)
return true;
else if(prob == 0)
return false;
else if(prob == 1)
return true;
}
return false;
}
/*generate random prime couple p,q and derive the modulus n=pq*/
mpz_class ffsa_get_modulus(void)
{
mpz_class p, q;
gmp_randclass r (gmp_randinit_mt);
srand(time(NULL));
unsigned long int seed = (unsigned long int) rand();
r.seed(seed);
p = r.get_z_bits(1024);
q = r.get_z_bits(1024);
while(p % 2 == 0 || p % 4 != 3)
p = r.get_z_bits(1024);
while(q % 2 == 0 || q % 4 != 3)
q = r.get_z_bits(1024);
while(ffsa_check_prime(p) == false || p % 4 != 3)
p = p + 2;
while(ffsa_check_prime(q) == false || p == q || q % 4 != 3)
q = q + 2;
return p * q;
}
/*get random bool vector of length k*/
bool_vec_t ffsa_get_bool_vector(int8_t k) {
bool_vec_t a;
a.reserve(k);
srand(time(NULL));
for(int8_t i = 0; i < k; i++)
a.push_back((bool)rand() % 2);
return a;
}
/*get random coprime vector of length k derived from n*/
mpz_vec_t ffsa_get_secrets(int8_t k, mpz_class n)
{
mpz_vec_t s;
s.reserve(k);
gmp_randclass r (gmp_randinit_mt);
srand(time(NULL));
unsigned long int seed = (unsigned long int) rand();
r.seed(seed);
mpz_class intermediate;
for(int8_t i = 0; i < k; i++)
{
begin:
do
{
intermediate = r.get_z_range(n-1) + 1;
} while(gcd(intermediate, n) != 1);
for(int8_t j = 0; j < i; j++)
if(s[i] == intermediate)
goto begin;
s.push_back(intermediate);
}
return s;
}
/*derive verifier vector from secret vector and modulus*/
mpz_vec_t ffsa_get_verifiers(mpz_vec_t s, mpz_class n)
{
srand(time(NULL));
mpz_vec_t v;
v.reserve(s.size());
mpz_class inter;
int8_t sig;
for(int8_t i = 0; i < s.size(); i++)
{
sig = (rand() % 2) ? -1 : 1;
inter = s[i] * s[i];
inter = inter % n;
inter = sig * inter;
v.push_back(inter);
}
return v;
}
/*compute verifier constant*/
mpz_class ffsa_compute_x(mpz_class r, int8_t sig, mpz_class n)
{
mpz_class x = r * r;
x = x % n;
x = sig * x;
return x;
}
/*compute share number*/
mpz_class ffsa_compute_y(mpz_vec_t s, const bool_vec_t a, mpz_class r, mpz_class n)
{
if(s.size() != a.size())
return 0;
mpz_class y = r;
for(int8_t i = 0; i < s.size(); i++)
if(a[i])
y = y * s[i];
return y % n;
}
/*verify share number and verify-vector*/
bool ffsa_verify_values(mpz_class y, mpz_vec_t v, const bool_vec_t a, mpz_class n, mpz_class x)
{
if(v.size() != a.size() || x == 0)
return false;
mpz_class verifier = y * y, check = x;
verifier = verifier % n;
for(int8_t i = 0; i < v.size(); i++)
if(a[i])
check = check * v[i];
check = check % n;
if(verifier == check || verifier == -1 * check)
return true;
else
return false;
}
int test_ffsa_main()
{
/*Example run*/
/*--------
* Setup -
*--------
*/
/*set number of streams and rounds*/
int8_t k = 6, t = 5;
/*derive private primes and modulus*/
mpz_class n = ffsa_get_modulus();
/*derive secrets vector*/
mpz_vec_t s = ffsa_get_secrets(k, n);
/*derive derive verifier vector*/
mpz_vec_t v = ffsa_get_verifiers(s, n);
/*initialize random generator*/
srand(time(NULL));
gmp_randclass rand_c (gmp_randinit_mt);
/*-----------------------------
* Prover and verifier dialog -
*-----------------------------
*/
mpz_class r, x, y;
int8_t sig;
/*round based iteration*/
for(int8_t i = 1; i <= t; i++)
{
/*--------
* Round -
*--------
*/
/*REMARK: Round iteration may be too fast for providing sufficient
distinct rand seeds generated over the time parameter. Fast
computers may require a wait command.*/
/*seed GMP random generator*/
unsigned long int seed = (unsigned long int) rand();
rand_c.seed(seed);
/*derive random round constant and sign*/
r = rand_c.get_z_range(n-1) + 1;
sig = (rand() % 2) ? -1 : 1;
/*derive verifier constant*/
x = ffsa_compute_x(r, sig, n);
/*get random bool vector of length k*/
const bool_vec_t a = ffsa_get_bool_vector(k);
/*derive share number*/
y = ffsa_compute_y(s, a, r, n);
/*single round verification of derived values*/
if(ffsa_verify_values(y, v, a, n, x))
std::cout << "Round " << (int)i << ": Correct\n";
else
{
std::cout << "####Uncorrect -- Aborted####\n";
return 0;
}
}
/*Complete verification after t successful rounds*/
std::cout << "####Verified####\n";
return 0;
}
| 23.104651 | 95 | 0.539171 | kn1ghtc |
d446a9568df176437c55638ff603caf95c5e8191 | 5,671 | hpp | C++ | include/uxr/agent/transport/util/InterfaceLinux.hpp | vibnwis/Micro-XRCE-DDS-Agent | 57ff677855b75d79657b7c20110241e6c1eec351 | [
"Apache-2.0"
] | null | null | null | include/uxr/agent/transport/util/InterfaceLinux.hpp | vibnwis/Micro-XRCE-DDS-Agent | 57ff677855b75d79657b7c20110241e6c1eec351 | [
"Apache-2.0"
] | null | null | null | include/uxr/agent/transport/util/InterfaceLinux.hpp | vibnwis/Micro-XRCE-DDS-Agent | 57ff677855b75d79657b7c20110241e6c1eec351 | [
"Apache-2.0"
] | null | null | null | // Copyright 2017-present Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef UXR_AGENT_TRANSPORT_UTIL_INTERFACELINUX_HPP_
#define UXR_AGENT_TRANSPORT_UTIL_INTERFACELINUX_HPP_
#include <uxr/agent/transport/util/Interface.hpp>
#include <uxr/agent/transport/endpoint/CAN2EndPoint.hpp>
#include <uxr/agent/transport/endpoint/IPv4EndPoint.hpp>
#include <uxr/agent/transport/endpoint/IPv6EndPoint.hpp>
#include <uxr/agent/logger/Logger.hpp>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <ifaddrs.h>
namespace eprosima {
namespace uxr {
namespace util {
template<typename E>
void get_transport_interfaces(
uint16_t agent_port,
std::vector<dds::xrce::TransportAddress>& transport_addresses);
template<>
inline
void get_transport_interfaces<CAN2EndPoint>(
uint16_t agent_port,
std::vector<dds::xrce::TransportAddress>& transport_addresses)
{
struct ifaddrs* ifaddr;
struct ifaddrs* ptr;
transport_addresses.clear();
if (-1 != getifaddrs(&ifaddr))
{
for (ptr = ifaddr; ptr != nullptr; ptr = ptr->ifa_next)
{
if (AF_INET == ptr->ifa_addr->sa_family)
{
dds::xrce::TransportAddressMedium medium_locator;
medium_locator.port(agent_port);
medium_locator.address(
{uint8_t(ptr->ifa_addr->sa_data[2]),
uint8_t(ptr->ifa_addr->sa_data[3]),
uint8_t(ptr->ifa_addr->sa_data[4]),
uint8_t(ptr->ifa_addr->sa_data[5])});
transport_addresses.emplace_back();
transport_addresses.back().medium_locator(medium_locator);
UXR_AGENT_LOG_TRACE(
UXR_DECORATE_WHITE("interface found"),
"address: {}",
transport_addresses.back()
);
}
}
}
freeifaddrs(ifaddr);
}
template<>
inline
void get_transport_interfaces<IPv4EndPoint>(
uint16_t agent_port,
std::vector<dds::xrce::TransportAddress>& transport_addresses)
{
struct ifaddrs* ifaddr;
struct ifaddrs* ptr;
transport_addresses.clear();
if (-1 != getifaddrs(&ifaddr))
{
for (ptr = ifaddr; ptr != nullptr; ptr = ptr->ifa_next)
{
if (AF_INET == ptr->ifa_addr->sa_family)
{
dds::xrce::TransportAddressMedium medium_locator;
medium_locator.port(agent_port);
medium_locator.address(
{uint8_t(ptr->ifa_addr->sa_data[2]),
uint8_t(ptr->ifa_addr->sa_data[3]),
uint8_t(ptr->ifa_addr->sa_data[4]),
uint8_t(ptr->ifa_addr->sa_data[5])});
transport_addresses.emplace_back();
transport_addresses.back().medium_locator(medium_locator);
UXR_AGENT_LOG_TRACE(
UXR_DECORATE_WHITE("interface found"),
"address: {}",
transport_addresses.back()
);
}
}
}
freeifaddrs(ifaddr);
}
template<>
inline
void get_transport_interfaces<IPv6EndPoint>(
uint16_t agent_port,
std::vector<dds::xrce::TransportAddress>& transport_addresses)
{
struct ifaddrs* ifaddr;
struct ifaddrs* ptr;
transport_addresses.clear();
if (-1 != getifaddrs(&ifaddr))
{
for (ptr = ifaddr; ptr != nullptr; ptr = ptr->ifa_next)
{
if (AF_INET6 == ptr->ifa_addr->sa_family)
{
dds::xrce::TransportAddressLarge large_locator;
large_locator.port(agent_port);
struct sockaddr_in6* addr = reinterpret_cast<sockaddr_in6*>(ptr->ifa_addr);
large_locator.address(
{addr->sin6_addr.s6_addr[0],
addr->sin6_addr.s6_addr[1],
addr->sin6_addr.s6_addr[2],
addr->sin6_addr.s6_addr[3],
addr->sin6_addr.s6_addr[4],
addr->sin6_addr.s6_addr[5],
addr->sin6_addr.s6_addr[6],
addr->sin6_addr.s6_addr[7],
addr->sin6_addr.s6_addr[8],
addr->sin6_addr.s6_addr[9],
addr->sin6_addr.s6_addr[10],
addr->sin6_addr.s6_addr[11],
addr->sin6_addr.s6_addr[12],
addr->sin6_addr.s6_addr[13],
addr->sin6_addr.s6_addr[14],
addr->sin6_addr.s6_addr[15]});
transport_addresses.emplace_back();
transport_addresses.back().large_locator(large_locator);
UXR_AGENT_LOG_TRACE(
UXR_DECORATE_WHITE("interface found"),
"address: {}",
transport_addresses.back()
);
}
}
}
freeifaddrs(ifaddr);
}
} // namespace util
} // namespace uxr
} // namespace eprosima
#endif // UXR_AGENT_TRANSPORT_UTIL_INTERFACELINUX_HPP_
| 33.556213 | 91 | 0.588256 | vibnwis |
d4496a1f863a7e06e2727f8ec8ec8dcc773f8e61 | 2,757 | hpp | C++ | src/mlpack/core/metrics/iou_metric_impl.hpp | gaurav-singh1998/mlpack | c104a2dcf0b51a98d9d6fcfc01d4e7047cc83872 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-12-09T17:58:29.000Z | 2021-12-09T17:58:29.000Z | src/mlpack/core/metrics/iou_metric_impl.hpp | R-Aravind/mlpack | 99d11a9b4d379885cf7f8160d8c71fb792fa1bbc | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | src/mlpack/core/metrics/iou_metric_impl.hpp | R-Aravind/mlpack | 99d11a9b4d379885cf7f8160d8c71fb792fa1bbc | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2019-09-17T21:33:59.000Z | 2019-09-17T21:33:59.000Z | /**
* @file core/metrics/iou_metric_impl.hpp
* @author Kartik Dutt
*
* Implementation of Intersection Over Union metric.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_CORE_METRICS_IOU_IMPL_HPP
#define MLPACK_CORE_METRICS_IOU_IMPL_HPP
// In case it hasn't been included.
#include "iou_metric.hpp"
namespace mlpack {
namespace metric {
template<bool UseCoordinates>
template <typename VecTypeA, typename VecTypeB>
typename VecTypeA::elem_type IoU<UseCoordinates>::Evaluate(
const VecTypeA& a,
const VecTypeB& b)
{
Log::Assert(a.n_elem == b.n_elem && a.n_elem == 4, "Incorrect \
shape for bounding boxes. They must contain 4 elements either be \
{x0, y0, x1, y1} or {x0, y0, h, w}. Refer to the documentation \
for more information.");
// Bounding boxes represented as {x0, y0, x1, y1}.
if (UseCoordinates)
{
// Check the correctness of bounding box.
if (a(0) >= a(2) || a(1) >= a(3) || b(0) >= b(2) || b(1) >= b(3))
{
Log::Fatal << "Check the correctness of bounding boxes i.e. " <<
"{x0, y0} must represent lower left coordinates and " <<
"{x1, y1} must represent upper right coordinates of bounding" <<
"box." << std::endl;
}
typename VecTypeA::elem_type interSectionArea = std::max(0.0,
std::min(a(2), b(2)) - std::max(a(0), b(0)) + 1) * std::max(0.0,
std::min(a(3), b(3)) - std::max(a(1), b(1)) + 1);
// Union of Area can be calculated using the following equation
// A union B = A + B - A intersection B.
return interSectionArea / (1.0 * ((a(2) - a(0) + 1) * (a(3) - a(1) + 1) +
(b(2) - b(0) + 1) * (b(3) - b(1) + 1) - interSectionArea));
}
// Bounding boxes represented as {x0, y0, h, w}.
// Check correctness of bounding box.
Log::Assert(a(2) > 0 && b(2) > 0 && a(3) > 0 && b(3) > 0, "Height and width \
of bounding boxes must be greater than zero.");
typename VecTypeA::elem_type interSectionArea = std::max(0.0,
std::min(a(0) + a(2), b(0) + b(2)) - std::max(a(0), b(0)) + 1)
* std::max(0.0, std::min(a(1) + a(3), b(1) + b(3)) - std::max(a(1),
b(1)) + 1);
return interSectionArea / (1.0 * ((a(2) + 1) * (a(3) + 1) + (b(2) + 1) *
(b(3) + 1) - interSectionArea));
}
template<bool UseCoordinates>
template<typename Archive>
void IoU<UseCoordinates>::serialize(
Archive& /* ar */,
const unsigned int /* version */)
{
// Nothing to do here.
}
} // namespace metric
} // namespace mlpack
#endif
| 34.898734 | 79 | 0.608995 | gaurav-singh1998 |
d44ed9ea3d1c11e444823cbd28a6c503669cd4a2 | 10,283 | cpp | C++ | src/test/unit/lang/parser/math_functions_test.cpp | drezap/stan | 9b319ed125e2a7d14d0c9c246d2f462dad668537 | [
"BSD-3-Clause"
] | 1 | 2019-07-05T01:40:40.000Z | 2019-07-05T01:40:40.000Z | src/test/unit/lang/parser/math_functions_test.cpp | drezap/stan | 9b319ed125e2a7d14d0c9c246d2f462dad668537 | [
"BSD-3-Clause"
] | null | null | null | src/test/unit/lang/parser/math_functions_test.cpp | drezap/stan | 9b319ed125e2a7d14d0c9c246d2f462dad668537 | [
"BSD-3-Clause"
] | 1 | 2018-08-28T12:09:08.000Z | 2018-08-28T12:09:08.000Z | #include <gtest/gtest.h>
#include <test/unit/lang/utility.hpp>
TEST(lang_parser, abs_math_function_signatures) {
test_parsable("function-signatures/math/functions/abs");
}
TEST(lang_parser, asin_math_function_signatures) {
test_parsable("function-signatures/math/functions/asin");
}
TEST(lang_parser, asinh_math_function_signatures) {
test_parsable("function-signatures/math/functions/asinh");
}
TEST(lang_parser, acos_math_function_signatures) {
test_parsable("function-signatures/math/functions/acos");
}
TEST(lang_parser, acosh_math_function_signatures) {
test_parsable("function-signatures/math/functions/acosh");
}
TEST(lang_parser, atan_math_function_signatures) {
test_parsable("function-signatures/math/functions/atan");
}
TEST(lang_parser, atan2_math_function_signatures) {
test_parsable("function-signatures/math/functions/atan2");
}
TEST(lang_parser, atanh_math_function_signatures) {
test_parsable("function-signatures/math/functions/atanh");
}
TEST(lang_parser, bessel_first_kind_math_function_signatures) {
test_parsable("function-signatures/math/functions/bessel_first_kind");
}
TEST(lang_parser, bessel_second_kind_math_function_signatures) {
test_parsable("function-signatures/math/functions/bessel_second_kind");
}
TEST(lang_parser, binary_log_loss_math_function_signatures) {
test_parsable("function-signatures/math/functions/binary_log_loss");
}
TEST(lang_parser, binomial_coefficient_log_math_function_signatures) {
test_parsable("function-signatures/math/functions/binomial_coefficient_log");
}
TEST(lang_parser, cbrt_math_function_signatures) {
test_parsable("function-signatures/math/functions/cbrt");
}
TEST(lang_parser, ceil_math_function_signatures) {
test_parsable("function-signatures/math/functions/ceil");
}
TEST(lang_parser, constants_math_function_signatures) {
test_parsable("function-signatures/math/functions/constants");
}
TEST(lang_parser, cos_math_function_signatures) {
test_parsable("function-signatures/math/functions/cos");
}
TEST(lang_parser, cosh_math_function_signatures) {
test_parsable("function-signatures/math/functions/cosh");
}
TEST(lang_parser, digamma_math_function_signatures) {
test_parsable("function-signatures/math/functions/digamma");
}
TEST(lang_parser, erf_math_function_signatures) {
test_parsable("function-signatures/math/functions/erf");
}
TEST(lang_parser, erfc_math_function_signatures) {
test_parsable("function-signatures/math/functions/erfc");
}
TEST(lang_parser, exp_math_function_signatures) {
test_parsable("function-signatures/math/functions/exp");
}
TEST(lang_parser, exp2_math_function_signatures) {
test_parsable("function-signatures/math/functions/exp2");
}
TEST(lang_parser, expm1_math_function_signatures) {
test_parsable("function-signatures/math/functions/expm1");
}
TEST(lang_parser, fabs_math_function_signatures) {
test_parsable("function-signatures/math/functions/fabs");
}
TEST(lang_parser, falling_factorial_math_function_signatures) {
test_parsable("function-signatures/math/functions/falling_factorial");
}
TEST(lang_parser, fdim_math_function_signatures) {
test_parsable("function-signatures/math/functions/fdim");
}
TEST(lang_parser, floor_math_function_signatures) {
test_parsable("function-signatures/math/functions/floor");
}
TEST(lang_parser, fma_math_function_signatures) {
test_parsable("function-signatures/math/functions/fma");
}
TEST(lang_parser, fmax_math_function_signatures) {
test_parsable("function-signatures/math/functions/fmax");
}
TEST(lang_parser, fmin_math_function_signatures) {
test_parsable("function-signatures/math/functions/fmin");
}
TEST(lang_parser, fmod_math_function_signatures) {
test_parsable("function-signatures/math/functions/fmod");
}
TEST(lang_parser, gamma_p_math_function_signatures) {
test_parsable("function-signatures/math/functions/gamma_p");
}
TEST(lang_parser, gamma_q_math_function_signatures) {
test_parsable("function-signatures/math/functions/gamma_q");
}
TEST(lang_parser, hypot_math_function_signatures) {
test_parsable("function-signatures/math/functions/hypot");
}
TEST(lang_parser, if_else_math_function_signatures) {
test_parsable("function-signatures/math/functions/if_else");
}
TEST(lang_parser, inc_beta_math_function_signatures) {
test_parsable("function-signatures/math/functions/inc_beta");
}
TEST(lang_parser, int_step_math_function_signatures) {
test_parsable("function-signatures/math/functions/int_step");
}
TEST(lang_parser, inv_math_function_signatures) {
test_parsable("function-signatures/math/functions/inv");
}
TEST(lang_parser, inv_logit_math_function_signatures) {
test_parsable("function-signatures/math/functions/inv_logit");
}
TEST(lang_parser, inv_cloglog_math_function_signatures) {
test_parsable("function-signatures/math/functions/inv_cloglog");
}
TEST(lang_parser, inv_square_math_function_signatures) {
test_parsable("function-signatures/math/functions/inv_square");
}
TEST(lang_parser, inv_sqrt_math_function_signatures) {
test_parsable("function-signatures/math/functions/inv_sqrt");
}
TEST(lang_parser, lbeta_math_function_signatures) {
test_parsable("function-signatures/math/functions/lbeta");
}
TEST(lang_parser, lgamma_math_function_signatures) {
test_parsable("function-signatures/math/functions/lgamma");
}
TEST(lang_parser, lmgamma_math_function_signatures) {
test_parsable("function-signatures/math/functions/lmgamma");
}
TEST(lang_parser, log1m_math_function_signatures) {
test_parsable("function-signatures/math/functions/log1m");
}
TEST(lang_parser, log1m_exp_math_function_signatures) {
test_parsable("function-signatures/math/functions/log1m_exp");
}
TEST(lang_parser, log1m_inv_logit_math_function_signatures) {
test_parsable("function-signatures/math/functions/log1m_inv_logit");
}
TEST(lang_parser, log1p_math_function_signatures) {
test_parsable("function-signatures/math/functions/log1p");
}
TEST(lang_parser, log1p_exp_math_function_signatures) {
test_parsable("function-signatures/math/functions/log1p_exp");
}
TEST(lang_parser, log_math_function_signatures) {
test_parsable("function-signatures/math/functions/log");
}
TEST(lang_parser, log10_math_function_signatures) {
test_parsable("function-signatures/math/functions/log10");
}
TEST(lang_parser, log2_math_function_signatures) {
test_parsable("function-signatures/math/functions/log2");
}
TEST(lang_parser, log_diff_exp_math_function_signatures) {
test_parsable("function-signatures/math/functions/log_diff_exp");
}
TEST(lang_parser, log_inv_logit_math_function_signatures) {
test_parsable("function-signatures/math/functions/log_inv_logit");
}
TEST(lang_parser, logit_math_function_signatures) {
test_parsable("function-signatures/math/functions/logit");
}
TEST(lang_parser, log_falling_factorial_math_function_signatures) {
test_parsable("function-signatures/math/functions/log_falling_factorial");
}
TEST(lang_parser, log_mix_math_function_signatures) {
test_parsable("function-signatures/math/functions/log_mix");
}
TEST(lang_parser, log_rising_factorial_math_function_signatures) {
test_parsable("function-signatures/math/functions/log_rising_factorial");
}
TEST(lang_parser, log_sum_exp_math_function_signatures) {
test_parsable("function-signatures/math/functions/log_sum_exp");
}
TEST(lang_parser, max_math_function_signatures) {
test_parsable("function-signatures/math/functions/max");
}
TEST(lang_parser, min_math_function_signatures) {
test_parsable("function-signatures/math/functions/min");
}
TEST(lang_parser, modified_bessel_first_kind_math_function_signatures) {
test_parsable("function-signatures/math/functions/modified_bessel_first_kind");
}
TEST(lang_parser, modified_bessel_second_kind_math_function_signatures) {
test_parsable("function-signatures/math/functions/modified_bessel_second_kind");
}
TEST(lang_parser, multiply_log_math_function_signatures) {
test_parsable("function-signatures/math/functions/multiply_log");
}
TEST(lang_parser, operators_int_math_function_signatures) {
test_parsable("function-signatures/math/functions/operators_int");
}
TEST(lang_parser, operators_real_math_function_signatures) {
test_parsable("function-signatures/math/functions/operators_real");
}
TEST(lang_parser, owens_t_math_function_signatures) {
test_parsable("function-signatures/math/functions/owens_t");
}
TEST(lang_parser, phi_math_function_signatures) {
test_parsable("function-signatures/math/functions/phi");
}
TEST(lang_parser, phi_approx_math_function_signatures) {
test_parsable("function-signatures/math/functions/phi_approx");
}
TEST(lang_parser, pow_math_function_signatures) {
test_parsable("function-signatures/math/functions/pow");
}
TEST(lang_parser, sin_math_function_signatures) {
test_parsable("function-signatures/math/functions/sin");
}
TEST(lang_parser, sinh_math_function_signatures) {
test_parsable("function-signatures/math/functions/sinh");
}
TEST(lang_parser, step_math_function_signatures) {
test_parsable("function-signatures/math/functions/step");
}
TEST(lang_parser, special_values_math_function_signatures) {
test_parsable("function-signatures/math/functions/special_values");
}
TEST(lang_parser, sqrt_math_function_signatures) {
test_parsable("function-signatures/math/functions/sqrt");
}
TEST(lang_parser, square_math_function_signatures) {
test_parsable("function-signatures/math/functions/square");
}
TEST(lang_parser, rising_factorial_math_function_signatures) {
test_parsable("function-signatures/math/functions/rising_factorial");
}
TEST(lang_parser, round_math_function_signatures) {
test_parsable("function-signatures/math/functions/round");
}
TEST(lang_parser, tan_math_function_signatures) {
test_parsable("function-signatures/math/functions/tan");
}
TEST(lang_parser, tanh_math_function_signatures) {
test_parsable("function-signatures/math/functions/tanh");
}
TEST(lang_parser, tgamma_math_function_signatures) {
test_parsable("function-signatures/math/functions/tgamma");
}
TEST(lang_parser, trigamma_math_function_signatures) {
test_parsable("function-signatures/math/functions/trigamma");
}
TEST(lang_parser, trunc_math_function_signatures) {
test_parsable("function-signatures/math/functions/trunc");
}
| 30.333333 | 82 | 0.817563 | drezap |
d45284ba5583709a12d74e1d5b741b1777075e51 | 683 | cxx | C++ | NeosegPipeline/AntsJointFusionParameters.cxx | KevinPhamCPE/Neosegpipeline | 91b4c4f3e56dd5f3203d240a5aca932c28287bd3 | [
"Apache-2.0"
] | null | null | null | NeosegPipeline/AntsJointFusionParameters.cxx | KevinPhamCPE/Neosegpipeline | 91b4c4f3e56dd5f3203d240a5aca932c28287bd3 | [
"Apache-2.0"
] | null | null | null | NeosegPipeline/AntsJointFusionParameters.cxx | KevinPhamCPE/Neosegpipeline | 91b4c4f3e56dd5f3203d240a5aca932c28287bd3 | [
"Apache-2.0"
] | null | null | null | #include "AntsJointFusionParameters.h"
AntsJointFusionParameters::AntsJointFusionParameters()
{
m_output_dir_default="";
m_output_dir=m_output_dir_default;
m_compute_rois_parc_fusion_default= false ;
m_compute_rois_parc_fusion=m_compute_rois_parc_fusion_default;
}
void AntsJointFusionParameters::setOutputDir(QString output_dir)
{
m_output_dir=output_dir;
}
QString AntsJointFusionParameters::getOutputDir()
{
return m_output_dir;
}
void AntsJointFusionParameters::setRoicParcFusion(bool rois_parc_fusion)
{
m_compute_rois_parc_fusion=rois_parc_fusion;
}
bool AntsJointFusionParameters::getRoicParcFusion()
{
return m_compute_rois_parc_fusion;
}
| 20.088235 | 72 | 0.82284 | KevinPhamCPE |
d453fbb44894c49055ea505f25e6961ee52c79f2 | 456 | hpp | C++ | library/ATF/DLGTEMPLATE.hpp | lemkova/Yorozuya | f445d800078d9aba5de28f122cedfa03f26a38e4 | [
"MIT"
] | 29 | 2017-07-01T23:08:31.000Z | 2022-02-19T10:22:45.000Z | library/ATF/DLGTEMPLATE.hpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 90 | 2017-10-18T21:24:51.000Z | 2019-06-06T02:30:33.000Z | library/ATF/DLGTEMPLATE.hpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 44 | 2017-12-19T08:02:59.000Z | 2022-02-24T23:15:01.000Z | // This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
START_ATF_NAMESPACE
#pragma pack(push, 2)
const struct DLGTEMPLATE
{
unsigned int style;
unsigned int dwExtendedStyle;
unsigned __int16 cdit;
__int16 x;
__int16 y;
__int16 cx;
__int16 cy;
};
#pragma pack(pop)
END_ATF_NAMESPACE
| 21.714286 | 108 | 0.649123 | lemkova |
d454b0536ea3bd6a168d8daac1a5c6451443e237 | 4,488 | cpp | C++ | UnitTest/Primitive.cpp | garlyon/onion2 | b20d966de6a9ddeee0b66478d50725d1eaaad4c8 | [
"MIT"
] | null | null | null | UnitTest/Primitive.cpp | garlyon/onion2 | b20d966de6a9ddeee0b66478d50725d1eaaad4c8 | [
"MIT"
] | null | null | null | UnitTest/Primitive.cpp | garlyon/onion2 | b20d966de6a9ddeee0b66478d50725d1eaaad4c8 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "CppUnitTest.h"
#include "../Collision/Primitive.h"
#include "Tetrahedron.h"
#include <set>
#include <algorithm>
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace UnitTest
{
TEST_CLASS( Neighborhood )
{
template <typename A, typename B>
void check( A a, B b )
{
std::set<std::pair<size_t, size_t>> ids;
a.forEachNb( [&ids, b]( auto, auto pa )
{
b.forEachNb( [&ids, pa]( auto, auto pb )
{
Assert::IsTrue( ids.insert( { id( pa ), id( pb ) } ).second );
} );
} );
}
public:
TEST_METHOD( UniqueNbId )
{
Test_NS::Tetrahedron x, y;
using V = Collision_NS::Vert;
using E = Collision_NS::Edge;
using F = Collision_NS::Face;
check<V, V>( x.a, y.a );
check<V, E>( x.a, y.a );
check<V, F>( x.a, y.a );
check<E, V>( x.a, y.a );
check<E, E>( x.a, y.a );
check<E, F>( x.a, y.a );
check<F, V>( x.a, y.a );
check<F, E>( x.a, y.a );
}
};
TEST_CLASS( PrimitiveId )
{
public:
TEST_METHOD( FaceId )
{
QEdge_NS::Shape s;
auto a = s.makeEdge();
auto b = s.makeEdge();
auto c = s.makeEdge();
a.splice0( b.sym() );
b.splice0( c.sym() );
c.splice0( a.sym() );
Assert::AreEqual( a.l().id(), b.l().id() );
Assert::AreEqual( c.l().id(), c.l().id() );
Assert::AreEqual<size_t>( a.l().id(), id( Collision_NS::Face( a ) ) );
Assert::AreEqual<size_t>( b.l().id(), id( Collision_NS::Face( b ) ) );
Assert::AreEqual<size_t>( c.l().id(), id( Collision_NS::Face( c ) ) );
Assert::AreEqual<size_t>( a.r().id(), id( Collision_NS::Face( a.sym() ) ) );
Assert::AreEqual<size_t>( b.r().id(), id( Collision_NS::Face( b.sym() ) ) );
Assert::AreEqual<size_t>( c.r().id(), id( Collision_NS::Face( c.sym() ) ) );
}
TEST_METHOD( EdgeId )
{
QEdge_NS::Shape s;
auto a = s.makeEdge();
auto b = s.makeEdge();
auto c = s.makeEdge();
a.splice0( b.sym() );
b.splice0( c.sym() );
c.splice0( a.sym() );
Assert::AreEqual<size_t>( a.id(), id( Collision_NS::Edge( a ) ) );
Assert::AreEqual<size_t>( b.id(), id( Collision_NS::Edge( b ) ) );
Assert::AreEqual<size_t>( c.id(), id( Collision_NS::Edge( c ) ) );
Assert::AreEqual<size_t>( a.id(), id( Collision_NS::Edge( a.sym() ) ) );
Assert::AreEqual<size_t>( b.id(), id( Collision_NS::Edge( b.sym() ) ) );
Assert::AreEqual<size_t>( c.id(), id( Collision_NS::Edge( c.sym() ) ) );
}
TEST_METHOD( VertId )
{
QEdge_NS::Shape s;
auto a = s.makeEdge();
auto b = s.makeEdge();
auto c = s.makeEdge();
a.splice0( b.sym() );
b.splice0( c.sym() );
c.splice0( a.sym() );
Assert::AreEqual<size_t>( a.o().id(), id( Collision_NS::Vert( a ) ) );
Assert::AreEqual<size_t>( b.o().id(), id( Collision_NS::Vert( b ) ) );
Assert::AreEqual<size_t>( c.o().id(), id( Collision_NS::Vert( c ) ) );
Assert::AreEqual<size_t>( a.d().id(), id( Collision_NS::Vert( a.sym() ) ) );
Assert::AreEqual<size_t>( b.d().id(), id( Collision_NS::Vert( b.sym() ) ) );
Assert::AreEqual<size_t>( c.d().id(), id( Collision_NS::Vert( c.sym() ) ) );
}
};
TEST_CLASS( Major )
{
public:
TEST_METHOD( Vert )
{
Test_NS::Tetrahedron t;
Assert::AreEqual( id( major( Collision_NS::Vert( t.A ) ) ), id( major( Collision_NS::Vert( t.B ) ) ) );
Assert::AreEqual( id( major( Collision_NS::Vert( t.B ) ) ), id( major( Collision_NS::Vert( t.C ) ) ) );
Assert::AreNotEqual( id( major( Collision_NS::Vert( t.a ) ) ), id( major( Collision_NS::Vert( t.A ) ) ) );
}
TEST_METHOD( Edge )
{
Test_NS::Tetrahedron t;
Assert::AreEqual( id( major( Collision_NS::Edge( t.a ) ) ), id( major( Collision_NS::Edge( t.a.sym() ) ) ) );
Assert::AreNotEqual( id( major( Collision_NS::Edge( t.a ) ) ), id( major( Collision_NS::Edge( t.b ) ) ) );
}
TEST_METHOD( Face )
{
Test_NS::Tetrahedron t;
Assert::AreEqual( id( major( Collision_NS::Face( t.a ) ) ), id( major( Collision_NS::Face( t.b ) ) ) );
Assert::AreEqual( id( major( Collision_NS::Face( t.a ) ) ), id( major( Collision_NS::Face( t.c ) ) ) );
Assert::AreNotEqual( id( major( Collision_NS::Face( t.a ) ) ), id( major( Collision_NS::Face( t.A ) ) ) );
}
};
} | 28.769231 | 115 | 0.532531 | garlyon |
d4556d997b55c84d1489226659aa8bd4165e704f | 5,888 | cpp | C++ | Phase #3/Items.cpp | Squshy/sqa-baller-squad-v2 | a63cac6d24f282137864453727fa1c35371997fd | [
"MIT"
] | null | null | null | Phase #3/Items.cpp | Squshy/sqa-baller-squad-v2 | a63cac6d24f282137864453727fa1c35371997fd | [
"MIT"
] | null | null | null | Phase #3/Items.cpp | Squshy/sqa-baller-squad-v2 | a63cac6d24f282137864453727fa1c35371997fd | [
"MIT"
] | 1 | 2020-02-27T13:18:06.000Z | 2020-02-27T13:18:06.000Z | /**
* Items Function Definition file for Our Auction Sales Service Project
*
* @author Paul Kerrigan, Henry Zheng, Calvin Lapp
* @date January 24, 2020
* @version 1.0
* @name Items.cpp
*/
#include "Items.h"
#include <string>
#include "Users.h"
#include "AuctionLib.h"
string** bidList;
int bidListCount = 0;
bool itemMatch = false;
bool itemCheck = false;
int itemLength = 0;
string itemNameListCut = "";
const string EXIT = "exit";
int j = 0;
string usernameplusspaces = "";
Items::Items(){
}
void Items::CheckItems(string** items, int itemCount, Users user){
//Item stores the username + spaces for a total of 16 characters
//So we need to add spaces at the end of user's username until it's 16 characters long to compare properly
usernameplusspaces = user.getUserName();
for (int i = user.getUserName().length(); i < 16; i++){
usernameplusspaces += " ";
}
for (int i = 0; i < itemCount; i++){
//Compares username but right now item stores the username + spaces
//Either trim the spaces at the end or add spaces at the end of user input until it's 15 characters long
if(usernameplusspaces.compare(items[i][2]) == 0){
bidListCount++;
}
}
bidList = new string*[bidListCount];
for (int i = 0; i < bidListCount; i++){
bidList[i] = new string[5];
}
if (bidListCount <= 0){
cout << "\nYou have no items in auction.";
}else if(bidListCount >= 1){
for (int i = 0; i < itemCount; i++){
//Get Item name, seller's name, remaining days and current bid when it matches
//TODO: Check if seller's name is same as current user and don't add it in bidList
if(usernameplusspaces.compare(items[i][2]) == 0){ //We need i on the items array but we want to increment
bidList[j][0] = items[i][1]; //Item ID
bidList[j][1] = items[i][1]; //Item Name
bidList[j][2] = items[i][3]; //Current bidder's name
bidList[j][3] = items[i][4]; //Remaining days
bidList[j][4] = items[i][5]; //Current Bid
j++;
}
}
}
for (int i = 0; i < bidListCount; i++){
std::cout << "\n" << i << ". " << bidList[i][0] << " " << bidList[i][1] << " " << bidList[i][2] << " " << bidList[i][3] << " " << bidList[i][4];
}
}
void Items::FindItems(string** items, int itemCount){
// Resets
string** bidList;
int bidListCount = 0;
bool itemMatch = false;
bool itemCheck = false;
int itemLength = 0;
string itemNameListCut = "";
int j = 0;
while (itemMatch == false){
itemName = "";
itemCheck = false;
while (itemCheck == false){
std::cout << "\nEnter an Item name: ";
getline(cin, itemName);
if (exitCmd(itemName)){
std::cout << "Hi " << exitCmd(itemName);
break;
}
//Item name has to be 19 characters or fewer
if (itemName.length() > MAX_ITEM_NAME_LENGTH){
std::cout << "\nItem Name must be 19 characters or fewer";
}
else{
itemCheck = true;
}
}
//Get the first number of characters based on the length of input of itemName and see if they match
//So if someone types Ham
//Ham, Hammer, Hamster gets sent into bidList and is counted, while han,hanmster,chammer doesn't
//TODO: This needs to ignore case sensitivity
//Compare input to the item file in a loop and add it into an array if matches
itemLength = itemName.length();
//Gets the total number of matching items, which will be used for the array
for (int i = 0; i < itemCount; i++){
itemNameListCut = items[i][1].substr(0,itemLength);
if(itemName.compare(itemNameListCut) == 0){
bidListCount++;
}
}
//If itemCount is 0 then that means there are no matches and will prompt user to start over
if (bidListCount == 0){
std::cout << "\nThere are no matching results. Please enter a new item name.";
itemCheck = false; //reset itemNameCheck
}else{
itemMatch = true;
}
// 2D array for the bidlist to contain item name and current bid on it
bidList = new string*[bidListCount];
for (int i = 0; i < bidListCount; i++){
bidList[i] = new string[4];
}
//Now we can put the item name, seller's name, remaining days and current bid inside with this defined array
for (int i = 0; i < itemCount; i++){
itemNameListCut = items[i][1].substr(0,itemLength);
//Get Item name, seller's name, remaining days and current bid when it matches
//TODO: Check if seller's name is same as current user and don't add it in bidList
if(itemName.compare(itemNameListCut) == 0){ //We need i on the items array but we want to increment
bidList[j][0] = items[i][1]; //Item Name
bidList[j][1] = items[i][2]; //Seller's name
bidList[j][2] = items[i][4]; //Remaining days
bidList[j][3] = items[i][5]; //Current Bid
j++;
}
}
//Do another for loop and print out each item with a cooresponding number for user to input, the name and the current bid per line
// Calculates the number of elements inside an array
for (int i = 0; i < bidListCount; i++){
std::cout << "\n" << i << ". " << bidList[i][0] << " " << bidList[i][1] << " " << bidList[i][2] << " " << bidList[i][3];
}
}
}
bool Items::exitCmd(string buffer){
if (ToLower(buffer).compare(EXIT) == 0){
return true;
}else {
return false;
}
}
| 37.503185 | 152 | 0.563179 | Squshy |
d4560b83baff7d59f3efc50a387b12ff9f04e9f8 | 217 | cpp | C++ | source/Node.cpp | xzrunner/sop | 80f84765548fde33d990663d4a4b8054bb6714d1 | [
"MIT"
] | null | null | null | source/Node.cpp | xzrunner/sop | 80f84765548fde33d990663d4a4b8054bb6714d1 | [
"MIT"
] | null | null | null | source/Node.cpp | xzrunner/sop | 80f84765548fde33d990663d4a4b8054bb6714d1 | [
"MIT"
] | null | null | null | #include "sop/Node.h"
#include <assert.h>
namespace sop
{
Node::Node()
: m_parms(*this)
{
}
void Node::SetParent(const std::shared_ptr<Node>& node)
{
m_parent = node;
m_level = node->m_level + 1;
}
} | 10.85 | 55 | 0.617512 | xzrunner |
d457e79f2a5d43b52250b34878bd5ed5d996e0d4 | 1,462 | cpp | C++ | ch16/ex16.53.54.55/main.cpp | zhang1990215/Cpp-Primer | 81e51869c02f2ba75e4fe491dee07eaedce2bbc9 | [
"CC0-1.0"
] | null | null | null | ch16/ex16.53.54.55/main.cpp | zhang1990215/Cpp-Primer | 81e51869c02f2ba75e4fe491dee07eaedce2bbc9 | [
"CC0-1.0"
] | null | null | null | ch16/ex16.53.54.55/main.cpp | zhang1990215/Cpp-Primer | 81e51869c02f2ba75e4fe491dee07eaedce2bbc9 | [
"CC0-1.0"
] | null | null | null | /***************************************************************************
* @file main.cpp
* @author Yue Wang
* @date 16 Feb 2014
Aug, 2015
* @remark This code is for the exercises from C++ Primer 5th Edition
* @note
***************************************************************************/
//
// Exercise 16.53:
// Write your own version of the print functions and test them by printing
// one, two, and five arguments, each of which should have different types.
//
// Exercise 16.54:
// What happens if we call print on a type that doesn’t have an << operator?
// It didn't compile.
//
// Exercise 16.55:
// Explain how the variadic version of print would execute if we declared
// the nonvariadic version of print after the definition of the variadic
// version.
// error: no matching function for call to 'print(std::ostream&)'
//
#include <iostream>
// trivial case
template<typename Printable>
std::ostream& print(std::ostream& os, Printable const& printable)
{
return os << printable;
}
// recursion
template<typename Printable, typename... Args>
std::ostream& print(std::ostream& os, Printable const& printable, Args const&... rest)
{
return print(os << printable << ", ", rest...);
}
int main(int argc, char const *argv[])
{
print(std::cout, 1) << std::endl;
print(std::cout, 1, 2) << std::endl;
print(std::cout, 1, 2, 3, 4, "sss", 42.4242) << std::endl;
return 0;
}
| 30.458333 | 86 | 0.583447 | zhang1990215 |
d461774f952bed1c0d629aa1a558f1dc90ec3f9e | 10,453 | cpp | C++ | src/MapDrawer.cpp | sarthou/semantic_map_drawer | 2e1bce2fdefb25d87194a5ee888b03c2807b0bca | [
"Apache-2.0"
] | null | null | null | src/MapDrawer.cpp | sarthou/semantic_map_drawer | 2e1bce2fdefb25d87194a5ee888b03c2807b0bca | [
"Apache-2.0"
] | null | null | null | src/MapDrawer.cpp | sarthou/semantic_map_drawer | 2e1bce2fdefb25d87194a5ee888b03c2807b0bca | [
"Apache-2.0"
] | null | null | null | #include "route_drawer/MapDrawer.h"
#include <opencv2/imgproc/imgproc.hpp>
void MapDrawer::draw(std::vector<corridor_t> corridors)
{
for(size_t i = 0; i < corridors.size(); i++)
drawOneCorridor(corridors[i]);
}
void MapDrawer::draw(std::vector<openspace_t> openspaces)
{
for(size_t i = 0; i < openspaces.size(); i++)
drawOneCorridor(openspace2corridor(openspaces[i]));
}
corridor_t MapDrawer::openspace2corridor(openspace_t openspace)
{
corridor_t res;
size_t half = openspace.around_.size() / 2;
std::vector<std::string> side_I, side_II;
for(size_t i = 0; i < half; i++)
side_I.push_back(openspace.around_[i]);
for(size_t i = half; i < openspace.around_.size(); i++)
side_II.push_back(openspace.around_[i]);
std::vector<std::string> side_1, side_2, side_3, side_4;
half = side_I.size() / 2;
for(size_t i = 0; i < half; i++)
side_1.push_back(side_I[i]);
for(size_t i = half; i < side_I.size(); i++)
side_2.push_back(side_I[i]);
half = side_II.size() / 2;
for(size_t i = 0; i < half; i++)
side_3.push_back(side_II[i]);
for(size_t i = half; i < side_II.size(); i++)
side_4.push_back(side_II[i]);
res.name_ = openspace.name_;
res.in_front_of_ = openspace.in_front_of_;
res.at_end_edge_ = side_1;
std::reverse(side_2.begin(),side_2.end());
res.at_right_ = side_2;
std::reverse(side_3.begin(),side_3.end());
res.at_begin_edge_ = side_3;
res.at_left_ = side_4;
return res;
}
void MapDrawer::drawOneCorridor(corridor_t corridor)
{
size_t nb_places = 0;
image = cvCreateImage(cvSize(1000, 400), IPL_DEPTH_8U, 3);
cvSet(image, cvScalar(255,255,255));
drawCorridor_t to_draw;
size_t height_offset = 50;
size_t width_offset = 50;
for(size_t begin_i = 0; begin_i < corridor.at_begin_edge_.size(); begin_i++)
{
rect_t rect(width_offset, height_offset + rect_t::HEIGHT * (begin_i + 1), rect_t::WIDTH, rect_t::HEIGHT);
to_draw.at_begin_edge_rects_.push_back(rect);
to_draw.at_begin_edge_names_.push_back(corridor.at_begin_edge_[begin_i]);
nb_places++;
}
for(size_t left_i = 0; left_i < corridor.at_left_.size(); left_i++)
{
rect_t rect(width_offset + rect_t::WIDTH * (left_i + 1), height_offset, rect_t::WIDTH, rect_t::HEIGHT);
to_draw.at_left_rects_.push_back(rect);
to_draw.at_left_names_.push_back(corridor.at_left_[left_i]);
nb_places++;
}
height_offset = height_offset + (corridor.at_begin_edge_.size() + 1) * rect_t::HEIGHT;
for(size_t right_i = 0; right_i < corridor.at_right_.size(); right_i++)
{
rect_t rect(width_offset + rect_t::WIDTH * (right_i + 1), height_offset, rect_t::WIDTH, rect_t::HEIGHT);
to_draw.at_right_rects_.push_back(rect);
to_draw.at_right_names_.push_back(corridor.at_right_[right_i]);
nb_places++;
}
int right_trig_pose = -1;
int left_trig_pose = -1;
findRightLeftTrigger(corridor, right_trig_pose, left_trig_pose);
if((right_trig_pose != -1) && (left_trig_pose != -1))
{
while((right_trig_pose != -1) && (left_trig_pose != -1))
{
to_draw.at_right_rects_[right_trig_pose].fix_ = true;
to_draw.at_left_rects_[left_trig_pose].fix_ = true;
if(right_trig_pose > left_trig_pose)
{
int move_of = to_draw.at_right_rects_[right_trig_pose].x - to_draw.at_left_rects_[left_trig_pose].x;
for(size_t left_i = left_trig_pose; left_i < to_draw.at_left_rects_.size(); left_i++)
to_draw.at_left_rects_[left_i].x += move_of;
int fix = getPreviousFix(to_draw.at_left_rects_, left_trig_pose);
if(fix != -1)
{
int delta = to_draw.at_left_rects_[left_trig_pose].x_top() - to_draw.at_left_rects_[fix].x_bot();
size_t nb = left_trig_pose - fix + 1;
int add = delta /nb;
to_draw.at_left_rects_[fix].x += add/2;
to_draw.at_left_rects_[fix].width += add;
for(size_t move_i = 1; move_i < nb - 1; move_i++)
{
to_draw.at_left_rects_[fix + move_i].x += add/2 + add*move_i;
to_draw.at_left_rects_[fix + move_i].width += add;
}
to_draw.at_left_rects_[left_trig_pose].x -= add/2;
to_draw.at_left_rects_[left_trig_pose].width += add;
}
}
else if(right_trig_pose < left_trig_pose)
{
int move_of = to_draw.at_left_rects_[left_trig_pose].x - to_draw.at_right_rects_[right_trig_pose].x;
for(size_t right_i = right_trig_pose; right_i < to_draw.at_right_rects_.size(); right_i++)
to_draw.at_right_rects_[right_i].x += move_of;
int fix = getPreviousFix(to_draw.at_right_rects_, right_trig_pose);
if(fix != -1)
{
int delta = to_draw.at_right_rects_[right_trig_pose].x_top() - to_draw.at_right_rects_[fix].x_bot();
size_t nb = right_trig_pose - fix + 1;
int add = delta /nb;
to_draw.at_right_rects_[fix].x += add/2;
to_draw.at_right_rects_[fix].width += add;
for(size_t move_i = 1; move_i < nb - 1; move_i++)
{
to_draw.at_right_rects_[fix + move_i].x += add/2 + add*move_i;
to_draw.at_right_rects_[fix + move_i].width += add;
}
to_draw.at_right_rects_[right_trig_pose].x -= add/2;
to_draw.at_right_rects_[right_trig_pose].width += add;
}
}
else
{
std::cout << "ALIGNED" << std::endl;
}
findRightLeftTrigger(corridor, right_trig_pose, left_trig_pose);
}
}
if((to_draw.at_right_rects_.size() > 0) && (to_draw.at_left_rects_.size() > 0))
if(to_draw.at_right_rects_[to_draw.at_right_rects_.size() - 1].x_bot() > to_draw.at_left_rects_[to_draw.at_left_rects_.size() - 1].x_bot())
width_offset = to_draw.at_right_rects_[to_draw.at_right_rects_.size() - 1].x_bot() + rect_t::WIDTH/2;
else
width_offset = to_draw.at_left_rects_[to_draw.at_left_rects_.size() - 1].x_bot() + rect_t::WIDTH/2;
else if(to_draw.at_right_rects_.size() > 0)
width_offset = to_draw.at_right_rects_[to_draw.at_right_rects_.size() - 1].x_bot() + rect_t::WIDTH/2;
else if(to_draw.at_left_rects_.size() > 0)
width_offset = to_draw.at_left_rects_[to_draw.at_left_rects_.size() - 1].x_bot() + rect_t::WIDTH/2;
for(size_t end_i = 0; end_i < corridor.at_end_edge_.size(); end_i++)
{
rect_t rect(width_offset, 50 + rect_t::HEIGHT * (end_i + 1), rect_t::WIDTH, rect_t::HEIGHT);
to_draw.at_end_edge_rects_.push_back(rect);
to_draw.at_end_edge_names_.push_back(corridor.at_end_edge_[end_i]);
nb_places++;
}
if((to_draw.at_end_edge_rects_.size() > 0) && (to_draw.at_begin_edge_rects_.size() > 0))
if(to_draw.at_end_edge_rects_[to_draw.at_end_edge_rects_.size() - 1].y_bot() > to_draw.at_begin_edge_rects_[to_draw.at_begin_edge_rects_.size() - 1].y_bot())
height_offset = to_draw.at_end_edge_rects_[to_draw.at_end_edge_rects_.size() - 1].y_bot() + rect_t::HEIGHT/2;
else
height_offset = to_draw.at_begin_edge_rects_[to_draw.at_begin_edge_rects_.size() - 1].y_bot() + rect_t::HEIGHT/2;
else if(to_draw.at_end_edge_rects_.size() > 0)
height_offset = to_draw.at_end_edge_rects_[to_draw.at_end_edge_rects_.size() - 1].y_bot() + rect_t::HEIGHT/2;
else if(to_draw.at_begin_edge_rects_.size() > 0)
height_offset = to_draw.at_begin_edge_rects_[to_draw.at_begin_edge_rects_.size() - 1].y_bot() + rect_t::HEIGHT/2;
for(size_t right_i = 0; right_i < corridor.at_right_.size(); right_i++)
{
to_draw.at_right_rects_[right_i].y = height_offset;
}
for(size_t begin_i = 0; begin_i < to_draw.at_begin_edge_rects_.size(); begin_i++)
set_rect(to_draw.at_begin_edge_rects_[begin_i], to_draw.at_begin_edge_names_[begin_i]);
for(size_t left_i = 0; left_i < to_draw.at_left_rects_.size(); left_i++)
set_rect(to_draw.at_left_rects_[left_i], to_draw.at_left_names_[left_i]);
for(size_t right_i = 0; right_i < to_draw.at_right_rects_.size(); right_i++)
set_rect(to_draw.at_right_rects_[right_i], to_draw.at_right_names_[right_i]);
for(size_t end_i = 0; end_i < to_draw.at_end_edge_rects_.size(); end_i++)
set_rect(to_draw.at_end_edge_rects_[end_i], to_draw.at_end_edge_names_[end_i]);
if(nb_places != 0)
cvSaveImage(std::string(corridor.name_ + ".png").c_str(), image);
}
void MapDrawer::set_rect(rect_t rect, std::string name)
{
cv::Scalar color = getColor(name);
cvRectangle(image, cvPoint(rect.x_top(), rect.y_top()),
cvPoint(rect.x_bot(), rect.y_bot()),
color,
-1, 8, 0);
cvRectangle(image, cvPoint(rect.x_top(), rect.y_top()),
cvPoint(rect.x_bot(), rect.y_bot()),
color - cv::Scalar(50, 50, 50),
1, 8, 0);
CvFont font;
cvInitFont(&font, CV_FONT_HERSHEY_COMPLEX, 0.4, 0.6, 0, 1);
cvPutText(image, name.c_str(), cvPoint(rect.x_top() + 3, rect.y_top() + 20), &font,
cv::Scalar(0, 0, 0));
}
void MapDrawer::findRightLeftTrigger(corridor_t corridor, int& right_trig, int& left_trig)
{
int right_trig_pose;
right_trig >= 0 ? right_trig_pose = right_trig + 1 : right_trig_pose = 0;
int left_trig_pose = -1;
left_trig >= 0 ? left_trig_pose = left_trig + 1 : left_trig_pose = 0;
right_trig = -1;
left_trig = -1;
for(size_t right_i = right_trig_pose; right_i < corridor.at_right_.size(); right_i++)
{
if(corridor.in_front_of_.find(corridor.at_right_[right_i]) != corridor.in_front_of_.end())
{
right_trig = right_i;
for(size_t left_i = left_trig_pose; left_i < corridor.at_left_.size(); left_i++)
if(corridor.at_left_[left_i] == corridor.in_front_of_[corridor.at_right_[right_i]])
{
left_trig = left_i;
break;
}
break;
}
}
}
int MapDrawer::getPreviousFix(std::vector<rect_t> rects, size_t pose)
{
for(int i = pose - 1; i >= 0; i--)
if(rects[i].fix_ == true)
return i;
return -1;
}
cv::Scalar MapDrawer::getColor(std::string name)
{
std::vector<std::string> up = onto_.individuals.getUp(name);
if(std::find(up.begin(), up.end(), "interface") != up.end())
return cv::Scalar(255, 100, 0);
else if(std::find(up.begin(), up.end(), "restaurant") != up.end())
return cv::Scalar(0, 160, 255);
else if(std::find(up.begin(), up.end(), "clothes_shop") != up.end())
return cv::Scalar(0, 0, 255);
else if(std::find(up.begin(), up.end(), "pathIntersection") != up.end())
return cv::Scalar(60, 170, 60);
else
return cv::Scalar(255, 150, 150);
}
| 38.430147 | 161 | 0.667368 | sarthou |
d4622904c62f26a74067e522b4c5f303b223aaff | 11,086 | cpp | C++ | test/new_lexer_test.cpp | Nicholas-Baron/little-lang | dc7cca0ad4d06987f12edbe990ae6f27ec02d182 | [
"MIT"
] | 1 | 2019-08-09T13:59:32.000Z | 2019-08-09T13:59:32.000Z | test/new_lexer_test.cpp | Nicholas-Baron/little-lang | dc7cca0ad4d06987f12edbe990ae6f27ec02d182 | [
"MIT"
] | 3 | 2019-08-08T04:39:49.000Z | 2019-12-11T20:57:47.000Z | test/new_lexer_test.cpp | Nicholas-Baron/little-lang | dc7cca0ad4d06987f12edbe990ae6f27ec02d182 | [
"MIT"
] | null | null | null | #include "new_lexer.hpp"
#include <catch2/catch.hpp>
TEST_CASE("the lexer will not accept empty inputs") {
std::string buffer;
auto lexer = lexer::from_buffer(buffer);
CHECK(lexer != nullptr);
CHECK(lexer->peek_token() == lexer::token_type::eof);
}
TEST_CASE("the lexer will report locations for tokens") {
std::string buffer = "foo\n bar";
auto lexer = lexer::from_buffer(buffer);
CHECK(lexer != nullptr);
CHECK(lexer->next_token().location == Location{1, 0});
CHECK(lexer->next_token().location == Location{2, 2});
CHECK(lexer->next_token().location == Location{2, 5});
}
TEST_CASE("the lexer can look ahead for whole text fragments") {
std::string buffer = "foo bar baz";
auto lexer = lexer::from_buffer(buffer);
CHECK(lexer != nullptr);
CHECK(lexer->next_chars("foo"));
CHECK(lexer->next_chars("oo", 1));
CHECK(lexer->next_chars("bar", 4));
CHECK(lexer->next_chars("baz", 8));
}
TEST_CASE("the lexer will ignore comments") {
std::string buffer = R"(// this is a comment
# this is another comment
comment I am from the 1960s
Comment I am also from the 1960s
foo bar baz)";
auto lexer = lexer::from_buffer(buffer);
CHECK(lexer != nullptr);
CHECK(lexer->next_token() == "foo");
CHECK(lexer->next_token() == "bar");
CHECK(lexer->next_token() == "baz");
CHECK(lexer->next_token() == lexer::token_type::eof);
}
TEST_CASE("the lexer will parse an identifier") {
std::string buffer = "main";
auto lexer = lexer::from_buffer(buffer);
CHECK(lexer != nullptr);
auto tok = lexer->next_token();
CHECK(tok == lexer::token_type::identifier);
CHECK(tok == "main");
CHECK(lexer->next_token() == lexer::token_type::eof);
}
TEST_CASE("the lexer will parse primitive types") {
std::string buffer = "int unit string char bool float";
auto lexer = lexer::from_buffer(buffer);
CHECK(lexer != nullptr);
CHECK(lexer->next_token() == lexer::token_type::prim_type);
CHECK(lexer->next_token() == lexer::token_type::prim_type);
CHECK(lexer->next_token() == lexer::token_type::prim_type);
CHECK(lexer->next_token() == lexer::token_type::prim_type);
CHECK(lexer->next_token() == lexer::token_type::prim_type);
CHECK(lexer->next_token() == lexer::token_type::prim_type);
CHECK(lexer->next_token() == lexer::token_type::eof);
}
TEST_CASE("the lexer will parse an identifier containing underscores") {
std::string buffer = "my_value";
auto lexer = lexer::from_buffer(buffer);
CHECK(lexer != nullptr);
auto tok = lexer->next_token();
CHECK(tok == lexer::token_type::identifier);
CHECK(tok == "my_value");
CHECK(lexer->next_token() == lexer::token_type::eof);
}
TEST_CASE("the lexer will parse an identifier starting with underscores") {
std::string buffer = "_value";
auto lexer = lexer::from_buffer(buffer);
CHECK(lexer != nullptr);
auto tok = lexer->next_token();
CHECK(tok == lexer::token_type::identifier);
CHECK(tok == "_value");
CHECK(lexer->next_token() == lexer::token_type::eof);
}
TEST_CASE("the lexer will parse a plain string") {
std::string buffer = "\"raw\"";
auto lexer = lexer::from_buffer(buffer);
CHECK(lexer != nullptr);
auto tok = lexer->next_token();
CHECK(tok == lexer::token_type::string);
CHECK(tok == "\"raw\"");
CHECK(lexer->next_token() == lexer::token_type::eof);
}
TEST_CASE("the lexer will parse a string with escaped character") {
std::string buffer = R"("raw\n")";
auto lexer = lexer::from_buffer(buffer);
CHECK(lexer != nullptr);
auto tok = lexer->next_token();
CHECK(tok == lexer::token_type::string);
CHECK(tok == "\"raw\n\"");
CHECK(lexer->next_token() == lexer::token_type::eof);
}
TEST_CASE("the lexer will parse a character literal") {
std::string buffer = "\'w\'";
auto lexer = lexer::from_buffer(buffer);
CHECK(lexer != nullptr);
auto tok = lexer->next_token();
CHECK(tok == lexer::token_type::character);
CHECK(tok == "\'w\'");
CHECK(lexer->next_token() == lexer::token_type::eof);
}
TEST_CASE("the lexer will parse an integer") {
std::string buffer = "1234";
auto lexer = lexer::from_buffer(buffer);
CHECK(lexer != nullptr);
auto tok = lexer->next_token();
CHECK(tok == lexer::token_type::integer);
CHECK(tok == "1234");
CHECK(lexer->next_token() == lexer::token_type::eof);
}
TEST_CASE("the lexer will parse a hexadecimal integer") {
std::string buffer = "0x123456789aBcDeF";
auto lexer = lexer::from_buffer(buffer);
CHECK(lexer != nullptr);
auto tok = lexer->next_token();
CHECK(tok == lexer::token_type::integer);
CHECK(tok == buffer);
CHECK(lexer->next_token() == lexer::token_type::eof);
}
TEST_CASE("the lexer will parse a colon and the word 'is' as the same token") {
std::string buffer = "is:";
auto lexer = lexer::from_buffer(buffer);
CHECK(lexer != nullptr);
CHECK(lexer->next_token() == lexer::token_type::colon);
CHECK(lexer->next_token() == lexer::token_type::colon);
CHECK(lexer->next_token() == lexer::token_type::eof);
}
TEST_CASE("the lexer will parse parentheses") {
std::string buffer = "()";
auto lexer = lexer::from_buffer(buffer);
CHECK(lexer != nullptr);
CHECK(lexer->next_token() == lexer::token_type::lparen);
CHECK(lexer->next_token() == lexer::token_type::rparen);
CHECK(lexer->next_token() == lexer::token_type::eof);
}
TEST_CASE("the lexer will parse braces") {
std::string buffer = "{}";
auto lexer = lexer::from_buffer(buffer);
CHECK(lexer != nullptr);
CHECK(lexer->next_token() == lexer::token_type::lbrace);
CHECK(lexer->next_token() == lexer::token_type::rbrace);
CHECK(lexer->next_token() == lexer::token_type::eof);
}
TEST_CASE("the lexer will parse a 'skinny' arrow") {
std::string buffer = "->";
auto lexer = lexer::from_buffer(buffer);
CHECK(lexer != nullptr);
CHECK(lexer->next_token() == lexer::token_type::arrow);
CHECK(lexer->next_token() == lexer::token_type::eof);
}
TEST_CASE("the lexer will parse a comma") {
std::string buffer = ",";
auto lexer = lexer::from_buffer(buffer);
CHECK(lexer != nullptr);
CHECK(lexer->next_token() == lexer::token_type::comma);
CHECK(lexer->next_token() == lexer::token_type::eof);
}
TEST_CASE("the lexer will parse a semicolon") {
std::string buffer = ";";
auto lexer = lexer::from_buffer(buffer);
CHECK(lexer != nullptr);
CHECK(lexer->next_token() == lexer::token_type::semi);
CHECK(lexer->next_token() == lexer::token_type::eof);
}
TEST_CASE("the lexer will parse 'from', 'import', and 'export'") {
std::string buffer = "from import export";
auto lexer = lexer::from_buffer(buffer);
CHECK(lexer != nullptr);
CHECK(lexer->next_token() == lexer::token_type::from);
CHECK(lexer->next_token() == lexer::token_type::import_);
CHECK(lexer->next_token() == lexer::token_type::export_);
CHECK(lexer->next_token() == lexer::token_type::eof);
}
TEST_CASE("the lexer will parse 'if', 'then', and 'else'") {
std::string buffer = "if else then";
auto lexer = lexer::from_buffer(buffer);
CHECK(lexer != nullptr);
CHECK(lexer->next_token() == lexer::token_type::if_);
CHECK(lexer->next_token() == lexer::token_type::else_);
CHECK(lexer->next_token() == lexer::token_type::then);
CHECK(lexer->next_token() == lexer::token_type::eof);
}
TEST_CASE("the lexer will parse 'return' and 'ret' the same") {
std::string buffer = "return ret";
auto lexer = lexer::from_buffer(buffer);
CHECK(lexer != nullptr);
CHECK(lexer->next_token() == lexer::token_type::return_);
CHECK(lexer->next_token() == lexer::token_type::return_);
CHECK(lexer->next_token() == lexer::token_type::eof);
}
TEST_CASE("the lexer will parse '<' and '>'") {
std::string buffer = "< >";
auto lexer = lexer::from_buffer(buffer);
CHECK(lexer != nullptr);
CHECK(lexer->next_token() == lexer::token_type::lt);
CHECK(lexer->next_token() == lexer::token_type::gt);
CHECK(lexer->next_token() == lexer::token_type::eof);
}
TEST_CASE("the lexer will parse '<=' and '>=' as 1 token each") {
std::string buffer = "<= >=";
auto lexer = lexer::from_buffer(buffer);
CHECK(lexer != nullptr);
CHECK(lexer->next_token() == lexer::token_type::le);
CHECK(lexer->next_token() == lexer::token_type::ge);
CHECK(lexer->next_token() == lexer::token_type::eof);
}
TEST_CASE("the lexer will parse 'let' and 'const'") {
std::string buffer = "let const";
auto lexer = lexer::from_buffer(buffer);
CHECK(lexer != nullptr);
CHECK(lexer->next_token() == lexer::token_type::let);
CHECK(lexer->next_token() == lexer::token_type::const_);
CHECK(lexer->next_token() == lexer::token_type::eof);
}
TEST_CASE("the lexer will parse 'and' as '&&'") {
std::string buffer = "and &&";
auto lexer = lexer::from_buffer(buffer);
CHECK(lexer != nullptr);
CHECK(lexer->next_token() == lexer::token_type::double_and);
CHECK(lexer->next_token() == lexer::token_type::double_and);
CHECK(lexer->next_token() == lexer::token_type::eof);
}
TEST_CASE("the lexer will parse 'or' as '||'") {
std::string buffer = "or ||";
auto lexer = lexer::from_buffer(buffer);
CHECK(lexer != nullptr);
CHECK(lexer->next_token() == lexer::token_type::double_or);
CHECK(lexer->next_token() == lexer::token_type::double_or);
CHECK(lexer->next_token() == lexer::token_type::eof);
}
TEST_CASE("the lexer will parse 'equals' as '=='") {
std::string buffer = "equals ==";
auto lexer = lexer::from_buffer(buffer);
CHECK(lexer != nullptr);
CHECK(lexer->next_token() == lexer::token_type::eq);
CHECK(lexer->next_token() == lexer::token_type::eq);
CHECK(lexer->next_token() == lexer::token_type::eof);
}
TEST_CASE("the lexer will parse basic mathematical symbols") {
std::string buffer = "= + - / * %";
auto lexer = lexer::from_buffer(buffer);
CHECK(lexer != nullptr);
CHECK(lexer->next_token() == lexer::token_type::equal);
CHECK(lexer->next_token() == lexer::token_type::plus);
CHECK(lexer->next_token() == lexer::token_type::minus);
CHECK(lexer->next_token() == lexer::token_type::slash);
CHECK(lexer->next_token() == lexer::token_type::asterik);
CHECK(lexer->next_token() == lexer::token_type::percent);
CHECK(lexer->next_token() == lexer::token_type::eof);
}
TEST_CASE("the lexer will parse pointer-related tokens") {
std::string buffer = " & ? null";
auto lexer = lexer::from_buffer(buffer);
CHECK(lexer != nullptr);
CHECK(lexer->next_token() == lexer::token_type::amp);
CHECK(lexer->next_token() == lexer::token_type::question);
CHECK(lexer->next_token() == lexer::token_type::null);
CHECK(lexer->next_token() == lexer::token_type::eof);
}
| 30.539945 | 79 | 0.638102 | Nicholas-Baron |
d466d3fc9ad349b40da93af5b1f5ae6e4d78ec36 | 5,442 | cc | C++ | msf_distort/src/msf_distort.cc | tdnet12434/multi_sensor_fusion | fea64a56ecab2bd65f96675c207cd0d776c4a969 | [
"Apache-2.0"
] | 1 | 2018-07-11T11:32:26.000Z | 2018-07-11T11:32:26.000Z | msf_distort/src/msf_distort.cc | tdnet12434/multi_sensor_fusion | fea64a56ecab2bd65f96675c207cd0d776c4a969 | [
"Apache-2.0"
] | null | null | null | msf_distort/src/msf_distort.cc | tdnet12434/multi_sensor_fusion | fea64a56ecab2bd65f96675c207cd0d776c4a969 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2012-2013 Simon Lynen, ASL, ETH Zurich, Switzerland
* You can contact the author at <slynen at ethz dot ch>
*
* 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 <ros/ros.h>
#include <sensor_msgs/NavSatFix.h>
#include <geometry_msgs/PoseWithCovariance.h>
#include <geometry_msgs/PoseWithCovarianceStamped.h>
#include <tf/transform_broadcaster.h>
#include <geometry_msgs/TransformStamped.h>
#include <msf_distort/MSF_DistortConfig.h>
#include <dynamic_reconfigure/Reconfigure.h>
#include <dynamic_reconfigure/server.h>
#include <msf_core/msf_macros.h>
struct CallbackHandler {
typedef msf_distort::MSF_DistortConfig Config_T;
Config_T config_;
ros::Publisher pubPoseWithCovarianceStamped_;
ros::Publisher pubTransformStamped_;
ros::Publisher pubPoseStamped_;
ros::Publisher pubNavSatFix_;
ros::Publisher pubPoint_;
ros::Publisher pubPoseWithCovarianceStampedGPS_;
CallbackHandler(ros::NodeHandle& nh) {
pubPoseWithCovarianceStamped_ =
nh.advertise<geometry_msgs::PoseWithCovarianceStamped>
("pose_with_covariance_output", 100);
pubTransformStamped_ =
nh.advertise<geometry_msgs::TransformStamped>("transform_output", 100);
pubPoseStamped_ =
nh.advertise<geometry_msgs::PoseStamped>("pose_output", 100);
pubNavSatFix_ =
nh.advertise<sensor_msgs::NavSatFix>("navsatfix_output", 100);
pubPoint_ =
nh.advertise<geometry_msgs::PointStamped>("point_output", 100);
pubPoseWithCovarianceStampedGPS_ =
nh.advertise<geometry_msgs::PoseWithCovarianceStamped>("pose_with_covariance_gps_output", 100);
}
void config(Config_T &config, uint32_t /*level*/) {
config_ = config;
}
void MeasurementCallback(
const geometry_msgs::PoseWithCovarianceStampedConstPtr & msg) {
if (config_.publish_pose) {
pubPoseWithCovarianceStamped_.publish(msg);
}
}
void MeasurementCallback(
const geometry_msgs::TransformStampedConstPtr & msg) {
if (config_.publish_pose) {
pubTransformStamped_.publish(msg);
}
}
void MeasurementCallback(const geometry_msgs::PoseStampedConstPtr & msg) {
if (config_.publish_pose) {
pubPoseStamped_.publish(msg);
}
}
void MeasurementCallback(const sensor_msgs::NavSatFixConstPtr & msg) {
if (config_.publish_position) {
pubNavSatFix_.publish(msg);
}
}
void MeasurementCallback(const geometry_msgs::PointStampedConstPtr & msg) {
if (config_.publish_position) {
pubPoint_.publish(msg);
}
}
void MeasurementCallback2(
const geometry_msgs::PoseWithCovarianceStampedConstPtr & msg) {
if (config_.publish_position) {
pubPoseWithCovarianceStampedGPS_.publish(msg);
}
}
};
int main(int argc, char** argv) {
ros::init(argc, argv, "msf_distort");
typedef msf_distort::MSF_DistortConfig Config_T;
typedef dynamic_reconfigure::Server<Config_T> ReconfigureServer;
typedef boost::shared_ptr<ReconfigureServer> ReconfigureServerPtr;
ros::NodeHandle nh("msf_distort");
CallbackHandler handler(nh);
ReconfigureServerPtr reconf_server_; ///< dynamic reconfigure server
reconf_server_.reset(new ReconfigureServer(nh));
ReconfigureServer::CallbackType f = boost::bind(&CallbackHandler::config,
&handler, _1, _2);
reconf_server_->setCallback(f);
ros::Subscriber subPoseWithCovarianceStamped_ =
nh.subscribe < geometry_msgs::PoseWithCovarianceStamped
> ("pose_with_covariance_input", 20, &CallbackHandler::MeasurementCallback, &handler);
ros::Subscriber subTransformStamped_ =
nh.subscribe < geometry_msgs::TransformStamped
> ("transform_input", 20, &CallbackHandler::MeasurementCallback, &handler);
ros::Subscriber subPoseStamped_ = nh.subscribe < geometry_msgs::PoseStamped
> ("pose_input", 20, &CallbackHandler::MeasurementCallback, &handler);
ros::Subscriber subNavSatFix_ =
nh.subscribe < sensor_msgs::NavSatFix
> ("navsatfix_input", 20, &CallbackHandler::MeasurementCallback, &handler);
ros::Subscriber subPoint_ = nh.subscribe < geometry_msgs::PointStamped
> ("point_input", 20, &CallbackHandler::MeasurementCallback, &handler);
ros::Subscriber subPoseGPS_ = nh.subscribe < geometry_msgs::PoseWithCovarianceStamped
> ("posegps_input", 20, &CallbackHandler::MeasurementCallback2, &handler);
ros::V_string topics;
ros::this_node::getSubscribedTopics(topics);
std::string nodeName = ros::this_node::getName();
std::string topicsStr = nodeName + ":\n\tsubscribed to topics:\n";
for (unsigned int i = 0; i < topics.size(); i++)
topicsStr += ("\t\t" + topics.at(i) + "\n");
topicsStr += "\tadvertised topics:\n";
ros::this_node::getAdvertisedTopics(topics);
for (unsigned int i = 0; i < topics.size(); i++)
topicsStr += ("\t\t" + topics.at(i) + "\n");
MSF_INFO_STREAM("" << topicsStr);
ros::spin();
}
| 37.020408 | 103 | 0.725101 | tdnet12434 |
d46764d908176863484f6f12857d802e55eeba10 | 7,601 | cpp | C++ | libs/gui/src/font.cpp | blagodarin/yttrium | 534289c3082355e5537a03c0b5855b60f0c344ad | [
"Apache-2.0"
] | null | null | null | libs/gui/src/font.cpp | blagodarin/yttrium | 534289c3082355e5537a03c0b5855b60f0c344ad | [
"Apache-2.0"
] | null | null | null | libs/gui/src/font.cpp | blagodarin/yttrium | 534289c3082355e5537a03c0b5855b60f0c344ad | [
"Apache-2.0"
] | null | null | null | // This file is part of the Yttrium toolkit.
// Copyright (C) Sergei Blagodarin.
// SPDX-License-Identifier: Apache-2.0
#include <yttrium/gui/font.h>
#include <yttrium/base/exceptions.h>
#include <yttrium/geometry/rect.h>
#include <yttrium/image/image.h>
#include <yttrium/renderer/2d.h>
#include <yttrium/renderer/manager.h>
#include <yttrium/renderer/texture.h>
#include <yttrium/storage/reader.h>
#include <yttrium/storage/source.h>
#include <seir_base/utf8.hpp>
#include <cassert>
#include <cstring>
#include <optional>
#include <unordered_map>
#include <ft2build.h>
#include FT_FREETYPE_H
namespace
{
constexpr size_t builtinWidth = 4;
constexpr size_t builtinHeight = 4;
constexpr uint8_t builtinData[builtinHeight][builtinWidth]{
{ 0xff, 0xff, 0x00, 0x00 },
{ 0xff, 0xff, 0x00, 0x00 },
{ 0x00, 0x00, 0x00, 0x00 },
{ 0x00, 0x00, 0x00, 0x00 },
};
constexpr Yt::RectF builtinWhiteRect{ {}, Yt::SizeF{ 1, 1 } };
}
namespace Yt
{
struct FreeTypeWrapper
{
FT_Library _library = nullptr;
Buffer _faceBuffer;
FT_Face _face = nullptr;
FreeTypeWrapper()
{
if (FT_Init_FreeType(&_library))
throw InitializationError{ "Failed to initialize FreeType library" };
}
~FreeTypeWrapper() noexcept
{
if (_face)
FT_Done_Face(_face); // TODO: Handle error code.
FT_Done_FreeType(_library); // TODO: Handle error code.
}
void load(Buffer&& buffer)
{
assert(!_face);
if (buffer.size() > static_cast<size_t>(std::numeric_limits<FT_Long>::max())
|| FT_New_Memory_Face(_library, static_cast<const FT_Byte*>(buffer.data()), static_cast<FT_Long>(buffer.size()), 0, &_face))
throw DataError{ "Failed to load font" };
_faceBuffer = std::move(buffer);
}
};
class FontImpl final : public Font
{
public:
FontImpl(const Source& source, RenderManager& renderManager, size_t size)
: _size{ static_cast<int>(size) }
{
_freetype.load(source.to_buffer());
_hasKerning = FT_HAS_KERNING(_freetype._face);
FT_Set_Pixel_Sizes(_freetype._face, 0, static_cast<FT_UInt>(size));
Image image{ { size * 32, size * 32, PixelFormat::Intensity8 } };
size_t x_offset = 0;
size_t y_offset = 0;
size_t row_height = 0;
const auto copy_rect = [&](const uint8_t* src, size_t width, size_t height, ptrdiff_t stride) {
if (height > 0)
{
if (stride < 0)
src += (height - 1) * static_cast<size_t>(-stride);
auto dst = static_cast<uint8_t*>(image.data()) + image.info().stride() * y_offset + x_offset;
for (size_t y = 0; y < height; ++y)
{
std::memcpy(dst, src, width);
src += stride;
dst += image.info().stride();
}
if (row_height < height)
row_height = height;
}
x_offset += width + 1;
};
copy_rect(::builtinData[0], ::builtinWidth, ::builtinHeight, ::builtinWidth);
const auto baseline = static_cast<FT_Int>(size) * _freetype._face->ascender / _freetype._face->height;
for (FT_UInt codepoint = 0; codepoint < 65536; ++codepoint)
{
const auto id = FT_Get_Char_Index(_freetype._face, codepoint);
if (!id)
continue;
if (FT_Load_Glyph(_freetype._face, id, FT_LOAD_RENDER))
continue; // TODO: Report error.
const auto glyph = _freetype._face->glyph;
if (x_offset + glyph->bitmap.width > image.info().width())
{
x_offset = 0;
y_offset += row_height + 1;
row_height = 0;
}
if (y_offset + glyph->bitmap.rows > image.info().height())
break; // TODO: Report error.
auto& glyphInfo = _glyph[codepoint];
glyphInfo._id = id;
glyphInfo._rect = { { static_cast<int>(x_offset), static_cast<int>(y_offset) }, Size{ static_cast<int>(glyph->bitmap.width), static_cast<int>(glyph->bitmap.rows) } };
glyphInfo._offset = { glyph->bitmap_left, baseline - glyph->bitmap_top };
glyphInfo._advance = static_cast<int>(glyph->advance.x >> 6);
copy_rect(glyph->bitmap.buffer, glyph->bitmap.width, glyph->bitmap.rows, glyph->bitmap.pitch);
}
_texture = renderManager.create_texture_2d(image);
}
void render(Renderer2D& renderer, const RectF& rect, std::string_view text) const override
{
const auto scale = rect.height() / static_cast<float>(_size);
int x = 0;
auto previous = _glyph.end();
renderer.setTexture(_texture);
for (size_t i = 0; i < text.size();)
{
const auto current = _glyph.find(seir::readUtf8(text, i));
if (current == _glyph.end())
continue;
if (_hasKerning && previous != _glyph.end())
{
FT_Vector kerning;
if (!FT_Get_Kerning(_freetype._face, previous->second._id, current->second._id, FT_KERNING_DEFAULT, &kerning))
x += static_cast<int>(kerning.x >> 6);
}
const auto left = rect.left() + static_cast<float>(x + current->second._offset._x) * scale;
if (left >= rect.right())
break;
RectF positionRect{ { left, rect.top() + static_cast<float>(current->second._offset._y) * scale }, SizeF{ current->second._rect.size() } * scale };
RectF glyphRect{ current->second._rect };
bool clipped = false;
if (positionRect.right() > rect.right())
{
const auto originalWidth = positionRect.width();
positionRect._right = rect._right;
glyphRect.setWidth(glyphRect.width() * positionRect.width() / originalWidth);
clipped = true;
}
renderer.setTextureRect(glyphRect);
renderer.addBorderlessRect(positionRect);
if (clipped)
return;
x += current->second._advance;
previous = current;
}
}
float textWidth(std::string_view text, float fontSize, TextCapture* capture) const override
{
const auto scale = fontSize / static_cast<float>(_size);
int x = 0;
std::optional<float> selectionX;
const auto updateCapture = [&](size_t offset) {
if (!capture)
return;
if (capture->_cursorOffset == offset)
capture->_cursorPosition.emplace(static_cast<float>(x) * scale);
if (capture->_selectionBegin < capture->_selectionEnd)
{
if (selectionX)
{
if (offset == capture->_selectionEnd)
{
capture->_selectionRange.emplace(*selectionX, static_cast<float>(x) * scale);
selectionX.reset();
}
}
else if (offset == capture->_selectionBegin)
selectionX = static_cast<float>(x) * scale;
}
};
auto previous = _glyph.end();
for (size_t i = 0; i < text.size();)
{
const auto offset = i;
const auto current = _glyph.find(seir::readUtf8(text, i));
if (current == _glyph.end())
continue;
if (_hasKerning && previous != _glyph.end())
{
FT_Vector kerning;
if (!FT_Get_Kerning(_freetype._face, previous->second._id, current->second._id, FT_KERNING_DEFAULT, &kerning))
x += static_cast<int>(kerning.x >> 6);
}
updateCapture(offset);
x += current->second._advance;
previous = current;
}
updateCapture(text.size());
return static_cast<float>(x) * scale;
}
std::shared_ptr<const Texture2D> texture() const noexcept override
{
return _texture;
}
RectF textureRect(Graphics graphics) const noexcept override
{
switch (graphics)
{
case Graphics::WhiteRect: return ::builtinWhiteRect;
}
return {};
}
private:
struct Glyph
{
FT_UInt _id = 0;
Rect _rect;
Point _offset;
int _advance = 0;
};
FreeTypeWrapper _freetype;
const int _size;
bool _hasKerning = false;
std::unordered_map<char32_t, Glyph> _glyph;
std::shared_ptr<const Texture2D> _texture;
};
std::shared_ptr<const Font> Font::load(const Source& source, RenderManager& renderManager)
{
return std::make_shared<FontImpl>(source, renderManager, 64);
}
}
| 30.526104 | 170 | 0.662281 | blagodarin |
d46f2d4882e48f3e55477fc22a159829c7d2ca77 | 7,282 | cpp | C++ | dp/gl/src/Shader.cpp | asuessenbach/pipeline | 2e49968cc3b9948a57f7ee6c4cc3258925c92ab2 | [
"BSD-3-Clause"
] | 217 | 2015-01-06T09:26:53.000Z | 2022-03-23T14:03:18.000Z | dp/gl/src/Shader.cpp | asuessenbach/pipeline | 2e49968cc3b9948a57f7ee6c4cc3258925c92ab2 | [
"BSD-3-Clause"
] | 10 | 2015-01-25T12:42:05.000Z | 2017-11-28T16:10:16.000Z | dp/gl/src/Shader.cpp | asuessenbach/pipeline | 2e49968cc3b9948a57f7ee6c4cc3258925c92ab2 | [
"BSD-3-Clause"
] | 44 | 2015-01-13T01:19:41.000Z | 2022-02-21T21:35:08.000Z | // Copyright (c) 2010-2016, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <dp/gl/Shader.h>
namespace dp
{
namespace gl
{
std::string shaderTypeToName( GLenum type )
{
switch( type )
{
case GL_COMPUTE_SHADER : return( "ComputeShader" );
case GL_VERTEX_SHADER : return( "VertexShader" );
case GL_TESS_CONTROL_SHADER : return( "TessControlShader" );
case GL_TESS_EVALUATION_SHADER : return( "TessEvaluationShader" );
case GL_GEOMETRY_SHADER : return( "GeometryShader" );
case GL_FRAGMENT_SHADER : return( "FragmentShader" );
default :
DP_ASSERT( false );
return( "" );
}
}
ShaderSharedPtr Shader::create( GLenum type, std::string const& source )
{
switch( type )
{
case GL_COMPUTE_SHADER : return( ComputeShader::create( source ) );
case GL_VERTEX_SHADER : return( VertexShader::create( source ) );
case GL_TESS_CONTROL_SHADER : return( TessControlShader::create( source ) );
case GL_TESS_EVALUATION_SHADER : return( TessEvaluationShader::create( source ) );
case GL_GEOMETRY_SHADER : return( GeometryShader::create( source ) );
case GL_FRAGMENT_SHADER : return( FragmentShader::create( source ) );
default :
DP_ASSERT( false );
return( ShaderSharedPtr() );
}
}
Shader::Shader( GLenum type, std::string const& source )
{
GLuint id = glCreateShader( type );
setGLId( id );
GLint length = dp::checked_cast<GLint>(source.length());
GLchar const* src = source.c_str();
glShaderSource( id, 1, &src, &length );
glCompileShader( id );
#if !defined( NDEBUG )
GLint result;
glGetShaderiv( id, GL_COMPILE_STATUS, &result );
if ( ! result )
{
GLint errorLen;
glGetShaderiv( id, GL_INFO_LOG_LENGTH, &errorLen );
std::string buffer;
buffer.resize( errorLen, 0 );
glGetShaderInfoLog( id, errorLen, NULL, &buffer[0] );
DP_ASSERT( false );
}
#endif
}
Shader::~Shader( )
{
if ( getGLId() )
{
if ( getShareGroup() )
{
DEFINE_PTR_TYPES( CleanupTask );
class CleanupTask : public ShareGroupTask
{
public:
static CleanupTaskSharedPtr create( GLuint id )
{
return( std::shared_ptr<CleanupTask>( new CleanupTask( id ) ) );
}
virtual void execute() { glDeleteShader( m_id ); }
protected:
CleanupTask( GLuint id ) : m_id( id ) {}
private:
GLuint m_id;
};
// make destructor exception safe
try
{
getShareGroup()->executeTask( CleanupTask::create( getGLId() ) );
} catch (...) {}
}
else
{
glDeleteShader( getGLId() );
}
}
}
std::string Shader::getSource() const
{
GLint sourceLength;
glGetShaderiv( getGLId(), GL_SHADER_SOURCE_LENGTH, &sourceLength );
std::vector<char> source( sourceLength );
glGetShaderSource( getGLId(), sourceLength, nullptr, source.data() );
return( source.data() );
}
VertexShaderSharedPtr VertexShader::create( std::string const& source )
{
return( std::shared_ptr<VertexShader>( new VertexShader( source ) ) );
}
VertexShader::VertexShader( std::string const& source )
: Shader( GL_VERTEX_SHADER, source )
{
}
GLenum VertexShader::getType() const
{
return( GL_VERTEX_SHADER );
}
TessControlShaderSharedPtr TessControlShader::create( std::string const& source )
{
return( std::shared_ptr<TessControlShader>( new TessControlShader( source ) ) );
}
TessControlShader::TessControlShader( std::string const& source )
: Shader( GL_TESS_CONTROL_SHADER, source )
{
}
GLenum TessControlShader::getType() const
{
return( GL_TESS_CONTROL_SHADER );
}
TessEvaluationShaderSharedPtr TessEvaluationShader::create( std::string const& source )
{
return( std::shared_ptr<TessEvaluationShader>( new TessEvaluationShader( source ) ) );
}
TessEvaluationShader::TessEvaluationShader( std::string const& source )
: Shader( GL_TESS_EVALUATION_SHADER, source )
{
}
GLenum TessEvaluationShader::getType() const
{
return( GL_TESS_EVALUATION_SHADER );
}
GeometryShaderSharedPtr GeometryShader::create( std::string const& source )
{
return( std::shared_ptr<GeometryShader>( new GeometryShader( source ) ) );
}
GeometryShader::GeometryShader( std::string const& source )
: Shader( GL_GEOMETRY_SHADER, source )
{
}
GLenum GeometryShader::getType() const
{
return( GL_GEOMETRY_SHADER );
}
FragmentShaderSharedPtr FragmentShader::create( std::string const& source )
{
return( std::shared_ptr<FragmentShader>( new FragmentShader( source ) ) );
}
FragmentShader::FragmentShader( std::string const& source )
: Shader( GL_FRAGMENT_SHADER, source )
{
}
GLenum FragmentShader::getType() const
{
return( GL_FRAGMENT_SHADER );
}
ComputeShaderSharedPtr ComputeShader::create( std::string const& source )
{
return( std::shared_ptr<ComputeShader>( new ComputeShader( source ) ) );
}
ComputeShader::ComputeShader( std::string const& source )
: Shader( GL_COMPUTE_SHADER, source )
{
}
GLenum ComputeShader::getType() const
{
return( GL_COMPUTE_SHADER );
}
} // namespace gl
} // namespace dp
| 30.855932 | 92 | 0.634304 | asuessenbach |
d46f9faa425e0f5c23fb0c5f229aa7cc9b820409 | 1,153 | cpp | C++ | OperatorsAndConditions/06.PointDistance/Startup.cpp | Tanya-Zheleva/FMI-Intro-Programming | c326d331ac72bc41e4664b23fc56a4da7d2d6729 | [
"MIT"
] | 2 | 2020-10-27T09:27:14.000Z | 2021-10-09T14:57:15.000Z | OperatorsAndConditions/06.PointDistance/Startup.cpp | Tanya-Zheleva/FMI-Intro-Programming | c326d331ac72bc41e4664b23fc56a4da7d2d6729 | [
"MIT"
] | null | null | null | OperatorsAndConditions/06.PointDistance/Startup.cpp | Tanya-Zheleva/FMI-Intro-Programming | c326d331ac72bc41e4664b23fc56a4da7d2d6729 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cmath>
using namespace std;
int main()
{
double x1 = 0, y1 = 0, x2 = 0, y2 = 0, x = 0, y = 0;
cin >> x1 >> y1 >> x2 >> y2 >> x >> y;
double distance = 0;
if (x >= x1 && x <= x2 && y >= y1 && y <= y2)
{
cout << "distance=" << distance << endl;
}
else
{
if (x > x1 && x < x2 && y < y1) //Bottom
{
distance = abs(y1 - y);
}
else if (x > x1 && x < x2 && y > y2) //Top
{
distance = abs(y - y2);
}
else if (y > y1 && y < y2 && x < x1) //Left
{
distance = abs(x1 - x);
}
else if (y > y1 && y < y2 && x > x2) //Right
{
distance = abs(x - x2);
}
else if (x < x1 && y > y2) //Top left
{
distance = abs(x1 - x) * abs(x1 - x) + abs(y - y2) * abs(y - y2);
}
else if (x > x2 && y > y2) //Top right
{
distance = abs(x - x2) * abs(x - x2) + abs(y - y2) * abs(y - y2);
}
else if (x < x1 && y < y1) //Bottom left
{
distance = abs(x1 - x) * abs(x1 - x) + abs(y1 - y) * abs(y1 - y);
}
else if (x > x2 && y < y1) //Bottom right
{
distance = abs(x - x2) * abs(x - x2) + abs(y1 - y) * abs(y1 - y);
}
cout << "distance=" << distance << endl;
}
return 0;
} | 20.589286 | 68 | 0.447528 | Tanya-Zheleva |
d471b6e9e858654e1c9ae2a9bdaa02e9dbc17322 | 22,747 | cpp | C++ | src/EditorRuntime/GUI/PreferencesGenerated.cpp | akumetsuv/flood | e0d6647df9b7fac72443a0f65c0003b0ead7ed3a | [
"BSD-2-Clause"
] | null | null | null | src/EditorRuntime/GUI/PreferencesGenerated.cpp | akumetsuv/flood | e0d6647df9b7fac72443a0f65c0003b0ead7ed3a | [
"BSD-2-Clause"
] | null | null | null | src/EditorRuntime/GUI/PreferencesGenerated.cpp | akumetsuv/flood | e0d6647df9b7fac72443a0f65c0003b0ead7ed3a | [
"BSD-2-Clause"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////
// C++ code generated with wxFormBuilder (version Jun 30 2011)
// http://www.wxformbuilder.org/
//
// PLEASE DO "NOT" EDIT THIS FILE!
///////////////////////////////////////////////////////////////////////////
#include "Editor/API.h"
#include "PreferencesGenerated.h"
///////////////////////////////////////////////////////////////////////////
Bindings::Bindings( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : wxPanel( parent, id, pos, size, style )
{
wxBoxSizer* bSizer15;
bSizer15 = new wxBoxSizer( wxVERTICAL );
m_panelBindings = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL );
wxBoxSizer* bSizer4;
bSizer4 = new wxBoxSizer( wxVERTICAL );
wxBoxSizer* bSizer5;
bSizer5 = new wxBoxSizer( wxHORIZONTAL );
wxBoxSizer* bSizer7;
bSizer7 = new wxBoxSizer( wxVERTICAL );
m_staticText2 = new wxStaticText( m_panelBindings, wxID_ANY, wxT("Commands"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText2->Wrap( -1 );
bSizer7->Add( m_staticText2, 0, wxALL|wxEXPAND, 5 );
m_treeCtrl1 = new wxTreeCtrl( m_panelBindings, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTR_DEFAULT_STYLE );
bSizer7->Add( m_treeCtrl1, 1, wxALL|wxEXPAND, 5 );
bSizer5->Add( bSizer7, 1, wxEXPAND, 5 );
wxBoxSizer* bSizer8;
bSizer8 = new wxBoxSizer( wxVERTICAL );
bSizer8->SetMinSize( wxSize( 160,-1 ) );
m_staticText3 = new wxStaticText( m_panelBindings, wxID_ANY, wxT("Current Shortcuts"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText3->Wrap( -1 );
bSizer8->Add( m_staticText3, 0, wxALL|wxEXPAND, 5 );
m_listBox1 = new wxListBox( m_panelBindings, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0, NULL, 0 );
bSizer8->Add( m_listBox1, 1, wxALL|wxEXPAND, 5 );
wxBoxSizer* bSizer9;
bSizer9 = new wxBoxSizer( wxHORIZONTAL );
m_button1 = new wxButton( m_panelBindings, wxID_ANY, wxT("Remove"), wxDefaultPosition, wxDefaultSize, 0 );
m_button1->Enable( false );
bSizer9->Add( m_button1, 0, wxALL, 5 );
m_button2 = new wxButton( m_panelBindings, wxID_ANY, wxT("Remove All"), wxDefaultPosition, wxDefaultSize, 0 );
bSizer9->Add( m_button2, 0, wxALL, 5 );
bSizer8->Add( bSizer9, 0, wxEXPAND, 5 );
m_staticText4 = new wxStaticText( m_panelBindings, wxID_ANY, wxT("New"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText4->Wrap( -1 );
bSizer8->Add( m_staticText4, 0, wxALL|wxEXPAND, 5 );
m_textCtrl2 = new wxTextCtrl( m_panelBindings, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_READONLY );
bSizer8->Add( m_textCtrl2, 0, wxALL|wxEXPAND, 5 );
m_staticText5 = new wxStaticText( m_panelBindings, wxID_ANY, wxT("Currently Assigned"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText5->Wrap( -1 );
bSizer8->Add( m_staticText5, 0, wxALL|wxEXPAND, 5 );
m_textCtrl3 = new wxTextCtrl( m_panelBindings, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_READONLY );
m_textCtrl3->Enable( false );
bSizer8->Add( m_textCtrl3, 0, wxALL|wxEXPAND, 5 );
m_button3 = new wxButton( m_panelBindings, wxID_ANY, wxT("Add"), wxDefaultPosition, wxDefaultSize, 0 );
m_button3->Enable( false );
bSizer8->Add( m_button3, 0, wxALL|wxEXPAND, 5 );
bSizer5->Add( bSizer8, 0, wxEXPAND, 5 );
bSizer4->Add( bSizer5, 1, wxEXPAND, 5 );
wxBoxSizer* bSizer6;
bSizer6 = new wxBoxSizer( wxVERTICAL );
m_staticText1 = new wxStaticText( m_panelBindings, wxID_ANY, wxT("Description"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText1->Wrap( -1 );
bSizer6->Add( m_staticText1, 0, wxALL, 5 );
m_textCtrl1 = new wxTextCtrl( m_panelBindings, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize( -1,48 ), wxTE_MULTILINE|wxTE_NO_VSCROLL|wxTE_READONLY );
m_textCtrl1->Enable( false );
bSizer6->Add( m_textCtrl1, 1, wxALL|wxEXPAND, 5 );
bSizer4->Add( bSizer6, 0, wxEXPAND, 5 );
m_panelBindings->SetSizer( bSizer4 );
m_panelBindings->Layout();
bSizer4->Fit( m_panelBindings );
bSizer15->Add( m_panelBindings, 1, wxEXPAND | wxALL, 5 );
this->SetSizer( bSizer15 );
this->Layout();
}
Bindings::~Bindings()
{
}
Plugins::Plugins( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : wxPanel( parent, id, pos, size, style )
{
wxBoxSizer* bSizer1;
bSizer1 = new wxBoxSizer( wxVERTICAL );
wxBoxSizer* bSizer11;
bSizer11 = new wxBoxSizer( wxVERTICAL );
m_listPlugins = new wxListCtrl( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_REPORT|wxLC_SINGLE_SEL );
bSizer11->Add( m_listPlugins, 1, wxALL|wxEXPAND, 5 );
wxBoxSizer* bSizer19;
bSizer19 = new wxBoxSizer( wxHORIZONTAL );
m_buttonPluginEnable = new wxButton( this, wxID_ANY, wxT("Disable"), wxDefaultPosition, wxDefaultSize, 0 );
m_buttonPluginEnable->Enable( false );
bSizer19->Add( m_buttonPluginEnable, 0, wxALL, 5 );
m_buttonPluginUninstall = new wxButton( this, wxID_ANY, wxT("Uninstall"), wxDefaultPosition, wxDefaultSize, 0 );
m_buttonPluginUninstall->Enable( false );
bSizer19->Add( m_buttonPluginUninstall, 1, wxALL, 5 );
m_staticline1 = new wxStaticLine( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_VERTICAL );
bSizer19->Add( m_staticline1, 0, wxEXPAND | wxALL, 5 );
m_buttonPluginCheckUpdates = new wxButton( this, wxID_ANY, wxT("Check Updates"), wxDefaultPosition, wxDefaultSize, 0 );
bSizer19->Add( m_buttonPluginCheckUpdates, 1, wxALL, 5 );
m_buttonPluginInstall = new wxButton( this, wxID_ANY, wxT("Install..."), wxDefaultPosition, wxDefaultSize, 0 );
bSizer19->Add( m_buttonPluginInstall, 1, wxALL, 5 );
bSizer11->Add( bSizer19, 0, wxEXPAND, 5 );
bSizer1->Add( bSizer11, 1, wxEXPAND, 5 );
wxBoxSizer* bSizer18;
bSizer18 = new wxBoxSizer( wxVERTICAL );
wxBoxSizer* bSizer61;
bSizer61 = new wxBoxSizer( wxVERTICAL );
m_staticText11 = new wxStaticText( this, wxID_ANY, wxT("Description:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText11->Wrap( -1 );
bSizer61->Add( m_staticText11, 0, wxEXPAND|wxRIGHT|wxLEFT, 5 );
m_textPluginDescription = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize( -1,48 ), wxTE_MULTILINE|wxTE_NO_VSCROLL|wxTE_READONLY );
bSizer61->Add( m_textPluginDescription, 1, wxALL|wxEXPAND, 5 );
bSizer18->Add( bSizer61, 0, wxEXPAND, 5 );
bSizer1->Add( bSizer18, 0, wxEXPAND, 5 );
this->SetSizer( bSizer1 );
this->Layout();
// Connect Events
this->Connect( wxEVT_INIT_DIALOG, wxInitDialogEventHandler( Plugins::OnPluginInit ) );
m_listPlugins->Connect( wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler( Plugins::OnPluginSelected ), NULL, this );
m_buttonPluginEnable->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( Plugins::OnPluginEnable ), NULL, this );
m_buttonPluginCheckUpdates->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( Plugins::OnPluginCheckUpdates ), NULL, this );
m_buttonPluginInstall->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( Plugins::OnPluginInstall ), NULL, this );
}
Plugins::~Plugins()
{
// Disconnect Events
this->Disconnect( wxEVT_INIT_DIALOG, wxInitDialogEventHandler( Plugins::OnPluginInit ) );
m_listPlugins->Disconnect( wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler( Plugins::OnPluginSelected ), NULL, this );
m_buttonPluginEnable->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( Plugins::OnPluginEnable ), NULL, this );
m_buttonPluginCheckUpdates->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( Plugins::OnPluginCheckUpdates ), NULL, this );
m_buttonPluginInstall->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( Plugins::OnPluginInstall ), NULL, this );
}
Resources::Resources( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : wxPanel( parent, id, pos, size, style )
{
wxBoxSizer* bSizer22;
bSizer22 = new wxBoxSizer( wxVERTICAL );
wxBoxSizer* bSizer30;
bSizer30 = new wxBoxSizer( wxVERTICAL );
m_staticText21 = new wxStaticText( this, wxID_ANY, wxT("Lookup Paths"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText21->Wrap( -1 );
bSizer30->Add( m_staticText21, 0, wxALL, 5 );
m_listResourcePaths = new wxListCtrl( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_REPORT|wxLC_SINGLE_SEL );
bSizer30->Add( m_listResourcePaths, 1, wxALL|wxEXPAND, 5 );
wxBoxSizer* bSizer28;
bSizer28 = new wxBoxSizer( wxHORIZONTAL );
bSizer28->Add( 0, 0, 1, wxEXPAND, 5 );
m_button10 = new wxButton( this, wxID_ANY, wxT("Add..."), wxDefaultPosition, wxDefaultSize, 0 );
bSizer28->Add( m_button10, 0, wxALL, 5 );
m_button11 = new wxButton( this, wxID_ANY, wxT("Remove"), wxDefaultPosition, wxDefaultSize, 0 );
m_button11->Enable( false );
bSizer28->Add( m_button11, 0, wxALL, 5 );
bSizer30->Add( bSizer28, 0, wxEXPAND, 5 );
bSizer22->Add( bSizer30, 1, wxEXPAND, 5 );
wxStaticBoxSizer* sbSizer1;
sbSizer1 = new wxStaticBoxSizer( new wxStaticBox( this, wxID_ANY, wxT("Indexing") ), wxVERTICAL );
m_checkBox1 = new wxCheckBox( this, wxID_ANY, wxT("Generate thumbnails"), wxDefaultPosition, wxDefaultSize, 0 );
m_checkBox1->SetValue(true);
sbSizer1->Add( m_checkBox1, 0, wxALL, 5 );
wxBoxSizer* bSizer23;
bSizer23 = new wxBoxSizer( wxHORIZONTAL );
m_staticText8 = new wxStaticText( this, wxID_ANY, wxT("Thumbnails Cache"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText8->Wrap( -1 );
bSizer23->Add( m_staticText8, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 );
m_dirPicker1 = new wxDirPickerCtrl( this, wxID_ANY, wxEmptyString, wxT("Select a folder"), wxDefaultPosition, wxDefaultSize, wxDIRP_DEFAULT_STYLE|wxDIRP_DIR_MUST_EXIST );
bSizer23->Add( m_dirPicker1, 1, wxALL, 5 );
sbSizer1->Add( bSizer23, 0, wxEXPAND, 5 );
m_button14 = new wxButton( this, wxID_ANY, wxT("Cleanup cache"), wxDefaultPosition, wxDefaultSize, 0 );
sbSizer1->Add( m_button14, 0, wxALL, 5 );
bSizer22->Add( sbSizer1, 0, wxEXPAND, 5 );
this->SetSizer( bSizer22 );
this->Layout();
// Connect Events
this->Connect( wxEVT_INIT_DIALOG, wxInitDialogEventHandler( Resources::OnResourcesInit ) );
m_button10->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( Resources::OnResourcesPathAdd ), NULL, this );
}
Resources::~Resources()
{
// Disconnect Events
this->Disconnect( wxEVT_INIT_DIALOG, wxInitDialogEventHandler( Resources::OnResourcesInit ) );
m_button10->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( Resources::OnResourcesPathAdd ), NULL, this );
}
Renderers::Renderers( wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style ) : wxPanel( parent, id, pos, size, style )
{
wxBoxSizer* bSizer19;
bSizer19 = new wxBoxSizer( wxVERTICAL );
wxBoxSizer* bSizer20;
bSizer20 = new wxBoxSizer( wxVERTICAL );
m_staticText8 = new wxStaticText( this, wxID_ANY, wxT("Default Renderer:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText8->Wrap( -1 );
bSizer20->Add( m_staticText8, 0, wxALL, 5 );
wxArrayString m_choice1Choices;
m_choice1 = new wxChoice( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, m_choice1Choices, 0 );
m_choice1->SetSelection( -1 );
bSizer20->Add( m_choice1, 0, wxALL|wxEXPAND, 5 );
m_staticText10 = new wxStaticText( this, wxID_ANY, wxT("Renderers:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText10->Wrap( -1 );
bSizer20->Add( m_staticText10, 0, wxALL, 5 );
m_listCtrl2 = new wxListCtrl( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_NO_HEADER|wxLC_REPORT|wxLC_SINGLE_SEL );
bSizer20->Add( m_listCtrl2, 0, wxALL|wxEXPAND, 5 );
m_staticText9 = new wxStaticText( this, wxID_ANY, wxT("Extensions:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText9->Wrap( -1 );
bSizer20->Add( m_staticText9, 0, wxALL, 5 );
m_listBox3 = new wxListBox( this, wxID_ANY, wxDefaultPosition, wxSize( -1,120 ), 0, NULL, 0 );
bSizer20->Add( m_listBox3, 1, wxALL|wxEXPAND, 5 );
bSizer19->Add( bSizer20, 1, wxEXPAND, 5 );
this->SetSizer( bSizer19 );
this->Layout();
}
Renderers::~Renderers()
{
}
ResourcesFrame::ResourcesFrame( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style )
{
this->SetSizeHints( wxDefaultSize, wxDefaultSize );
wxBoxSizer* bSizer16;
bSizer16 = new wxBoxSizer( wxVERTICAL );
m_splitter2 = new wxSplitterWindow( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSP_3D );
m_splitter2->Connect( wxEVT_IDLE, wxIdleEventHandler( ResourcesFrame::m_splitter2OnIdle ), NULL, this );
m_panel2 = new wxPanel( m_splitter2, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL );
wxBoxSizer* bSizer20;
bSizer20 = new wxBoxSizer( wxVERTICAL );
m_resourceGroups = new wxTreeCtrl( m_panel2, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTR_DEFAULT_STYLE|wxTR_HIDE_ROOT|wxTR_ROW_LINES );
bSizer20->Add( m_resourceGroups, 1, wxEXPAND|wxTOP|wxBOTTOM|wxLEFT, 5 );
m_panel2->SetSizer( bSizer20 );
m_panel2->Layout();
bSizer20->Fit( m_panel2 );
m_panel3 = new wxPanel( m_splitter2, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL );
wxBoxSizer* bSizer18;
bSizer18 = new wxBoxSizer( wxVERTICAL );
wxBoxSizer* bSizer21;
bSizer21 = new wxBoxSizer( wxHORIZONTAL );
m_searchCtrl = new wxSearchCtrl( m_panel3, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 );
#ifndef __WXMAC__
m_searchCtrl->ShowSearchButton( true );
#endif
m_searchCtrl->ShowCancelButton( false );
bSizer21->Add( m_searchCtrl, 1, wxEXPAND|wxRIGHT, 5 );
m_staticText17 = new wxStaticText( m_panel3, wxID_ANY, wxT("Detail"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText17->Wrap( -1 );
bSizer21->Add( m_staticText17, 0, wxALL, 5 );
m_detailSlider = new wxSlider( m_panel3, wxID_ANY, 0, 0, 256, wxDefaultPosition, wxSize( 60,-1 ), wxSL_HORIZONTAL );
bSizer21->Add( m_detailSlider, 0, 0, 5 );
bSizer18->Add( bSizer21, 0, wxEXPAND|wxTOP, 5 );
m_resourceList = new wxListCtrl( m_panel3, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_ICON );
bSizer18->Add( m_resourceList, 1, wxEXPAND|wxTOP|wxBOTTOM|wxRIGHT, 5 );
m_gauge1 = new wxGauge( m_panel3, wxID_ANY, 100, wxDefaultPosition, wxSize( -1,8 ), wxGA_HORIZONTAL );
bSizer18->Add( m_gauge1, 0, wxEXPAND|wxBOTTOM|wxRIGHT, 5 );
m_panel3->SetSizer( bSizer18 );
m_panel3->Layout();
bSizer18->Fit( m_panel3 );
m_splitter2->SplitVertically( m_panel2, m_panel3, 121 );
bSizer16->Add( m_splitter2, 1, wxEXPAND, 5 );
this->SetSizer( bSizer16 );
this->Layout();
this->Centre( wxBOTH );
// Connect Events
this->Connect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( ResourcesFrame::OnClose ) );
m_resourceGroups->Connect( wxEVT_COMMAND_TREE_SEL_CHANGED, wxTreeEventHandler( ResourcesFrame::onResourceGroupChanged ), NULL, this );
m_detailSlider->Connect( wxEVT_SCROLL_THUMBTRACK, wxScrollEventHandler( ResourcesFrame::onResourceSliderScroll ), NULL, this );
m_resourceList->Connect( wxEVT_COMMAND_LIST_BEGIN_DRAG, wxListEventHandler( ResourcesFrame::OnListBeginDrag ), NULL, this );
m_resourceList->Connect( wxEVT_COMMAND_LIST_ITEM_ACTIVATED, wxListEventHandler( ResourcesFrame::onResourceListActivated ), NULL, this );
m_resourceList->Connect( wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler( ResourcesFrame::onResourceListSelection ), NULL, this );
}
ResourcesFrame::~ResourcesFrame()
{
// Disconnect Events
this->Disconnect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( ResourcesFrame::OnClose ) );
m_resourceGroups->Disconnect( wxEVT_COMMAND_TREE_SEL_CHANGED, wxTreeEventHandler( ResourcesFrame::onResourceGroupChanged ), NULL, this );
m_detailSlider->Disconnect( wxEVT_SCROLL_THUMBTRACK, wxScrollEventHandler( ResourcesFrame::onResourceSliderScroll ), NULL, this );
m_resourceList->Disconnect( wxEVT_COMMAND_LIST_BEGIN_DRAG, wxListEventHandler( ResourcesFrame::OnListBeginDrag ), NULL, this );
m_resourceList->Disconnect( wxEVT_COMMAND_LIST_ITEM_ACTIVATED, wxListEventHandler( ResourcesFrame::onResourceListActivated ), NULL, this );
m_resourceList->Disconnect( wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler( ResourcesFrame::onResourceListSelection ), NULL, this );
}
ServerFrame::ServerFrame( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxFrame( parent, id, title, pos, size, style )
{
this->SetSizeHints( wxDefaultSize, wxDefaultSize );
wxBoxSizer* bSizer22;
bSizer22 = new wxBoxSizer( wxVERTICAL );
m_notebookServer = new wxNotebook( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0 );
m_panelStatus = new wxPanel( m_notebookServer, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL );
wxBoxSizer* bSizer251;
bSizer251 = new wxBoxSizer( wxVERTICAL );
wxStaticBoxSizer* sbSizer2;
sbSizer2 = new wxStaticBoxSizer( new wxStaticBox( m_panelStatus, wxID_ANY, wxEmptyString ), wxVERTICAL );
wxFlexGridSizer* fgSizer1;
fgSizer1 = new wxFlexGridSizer( 0, 2, 0, 0 );
fgSizer1->AddGrowableCol( 1 );
fgSizer1->SetFlexibleDirection( wxVERTICAL );
fgSizer1->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED );
m_staticText11 = new wxStaticText( m_panelStatus, wxID_ANY, wxT("Host:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText11->Wrap( -1 );
fgSizer1->Add( m_staticText11, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 );
m_textHost = new wxTextCtrl( m_panelStatus, wxID_ANY, wxT("localhost"), wxDefaultPosition, wxDefaultSize, 0 );
fgSizer1->Add( m_textHost, 1, wxALL|wxEXPAND|wxALIGN_CENTER_VERTICAL, 5 );
m_staticText12 = new wxStaticText( m_panelStatus, wxID_ANY, wxT("Port:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText12->Wrap( -1 );
fgSizer1->Add( m_staticText12, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 );
m_textPort = new wxTextCtrl( m_panelStatus, wxID_ANY, wxT("9999"), wxDefaultPosition, wxDefaultSize, 0 );
m_textPort->SetValidator( wxTextValidator( wxFILTER_NUMERIC, &port ) );
fgSizer1->Add( m_textPort, 0, wxALL|wxEXPAND|wxALIGN_CENTER_VERTICAL, 5 );
m_staticText16 = new wxStaticText( m_panelStatus, wxID_ANY, wxT("Name:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText16->Wrap( -1 );
fgSizer1->Add( m_staticText16, 0, wxALL, 5 );
m_textName = new wxTextCtrl( m_panelStatus, wxID_ANY, wxT("triton"), wxDefaultPosition, wxDefaultSize, 0 );
fgSizer1->Add( m_textName, 0, wxALL|wxEXPAND, 5 );
m_staticText15 = new wxStaticText( m_panelStatus, wxID_ANY, wxT("Authentication:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText15->Wrap( -1 );
fgSizer1->Add( m_staticText15, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 );
wxString m_choiceAuthChoices[] = { wxT("None"), wxT("Password"), wxT("Certificate") };
int m_choiceAuthNChoices = sizeof( m_choiceAuthChoices ) / sizeof( wxString );
m_choiceAuth = new wxChoice( m_panelStatus, wxID_ANY, wxDefaultPosition, wxDefaultSize, m_choiceAuthNChoices, m_choiceAuthChoices, 0 );
m_choiceAuth->SetSelection( 0 );
fgSizer1->Add( m_choiceAuth, 1, wxALL|wxEXPAND|wxALIGN_CENTER_VERTICAL, 5 );
sbSizer2->Add( fgSizer1, 1, wxEXPAND, 5 );
bSizer251->Add( sbSizer2, 1, wxEXPAND, 5 );
wxBoxSizer* bSizer26;
bSizer26 = new wxBoxSizer( wxHORIZONTAL );
m_staticText13 = new wxStaticText( m_panelStatus, wxID_ANY, wxT("Status:"), wxDefaultPosition, wxDefaultSize, 0 );
m_staticText13->Wrap( -1 );
bSizer26->Add( m_staticText13, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 );
m_textStatus = new wxStaticText( m_panelStatus, wxID_ANY, wxT("Disconnected"), wxDefaultPosition, wxDefaultSize, 0 );
m_textStatus->Wrap( -1 );
bSizer26->Add( m_textStatus, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 );
bSizer26->Add( 0, 0, 1, wxEXPAND|wxALIGN_CENTER_VERTICAL, 5 );
m_buttonConnect = new wxButton( m_panelStatus, wxID_ANY, wxT("Connect"), wxDefaultPosition, wxDefaultSize, 0 );
bSizer26->Add( m_buttonConnect, 0, wxALL|wxEXPAND, 5 );
bSizer251->Add( bSizer26, 0, wxEXPAND, 5 );
m_panelStatus->SetSizer( bSizer251 );
m_panelStatus->Layout();
bSizer251->Fit( m_panelStatus );
m_notebookServer->AddPage( m_panelStatus, wxT("Status"), true );
m_panelChat = new wxPanel( m_notebookServer, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL );
wxBoxSizer* bSizer25;
bSizer25 = new wxBoxSizer( wxVERTICAL );
wxBoxSizer* bSizer24;
bSizer24 = new wxBoxSizer( wxHORIZONTAL );
m_textChat = new wxTextCtrl( m_panelChat, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE|wxTE_READONLY );
bSizer24->Add( m_textChat, 1, wxALL|wxEXPAND, 5 );
m_listBox3 = new wxListBox( m_panelChat, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0, NULL, 0 );
bSizer24->Add( m_listBox3, 0, wxALL|wxEXPAND, 5 );
bSizer25->Add( bSizer24, 1, wxEXPAND, 5 );
wxBoxSizer* bSizer23;
bSizer23 = new wxBoxSizer( wxHORIZONTAL );
m_textMessage = new wxTextCtrl( m_panelChat, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_NO_VSCROLL|wxTE_PROCESS_ENTER );
bSizer23->Add( m_textMessage, 1, wxALL, 5 );
m_button10 = new wxButton( m_panelChat, wxID_ANY, wxT("Send"), wxDefaultPosition, wxDefaultSize, 0 );
bSizer23->Add( m_button10, 0, wxALL, 5 );
bSizer25->Add( bSizer23, 0, wxEXPAND, 5 );
m_panelChat->SetSizer( bSizer25 );
m_panelChat->Layout();
bSizer25->Fit( m_panelChat );
m_notebookServer->AddPage( m_panelChat, wxT("Chat"), false );
bSizer22->Add( m_notebookServer, 1, wxEXPAND, 5 );
this->SetSizer( bSizer22 );
this->Layout();
this->Centre( wxBOTH );
// Connect Events
m_buttonConnect->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( ServerFrame::onConnectButtonClick ), NULL, this );
m_textMessage->Connect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( ServerFrame::onChatSendButtonClick ), NULL, this );
m_button10->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( ServerFrame::onChatSendButtonClick ), NULL, this );
}
ServerFrame::~ServerFrame()
{
// Disconnect Events
m_buttonConnect->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( ServerFrame::onConnectButtonClick ), NULL, this );
m_textMessage->Disconnect( wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler( ServerFrame::onChatSendButtonClick ), NULL, this );
m_button10->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( ServerFrame::onChatSendButtonClick ), NULL, this );
}
| 43.913127 | 191 | 0.728624 | akumetsuv |
d478c34c9e275be45836a40c4ceb1088c1206cf9 | 1,728 | cpp | C++ | third-party/Empirical/examples/math/math.cpp | koellingh/empirical-p53-simulator | aa6232f661e8fc65852ab6d3e809339557af521b | [
"MIT"
] | null | null | null | third-party/Empirical/examples/math/math.cpp | koellingh/empirical-p53-simulator | aa6232f661e8fc65852ab6d3e809339557af521b | [
"MIT"
] | null | null | null | third-party/Empirical/examples/math/math.cpp | koellingh/empirical-p53-simulator | aa6232f661e8fc65852ab6d3e809339557af521b | [
"MIT"
] | null | null | null | // This file is part of Empirical, https://github.com/devosoft/Empirical
// Copyright (C) Michigan State University, 2016-2017.
// Released under the MIT Software license; see doc/LICENSE
//
//
// Some examples code for using math functions.
#include <iostream>
#include "emp/math/math.hpp"
int main()
{
std::cout.setf( std::ios::fixed, std::ios::floatfield );
for (double i = 1; i <= 20; i += 1.0) {
std::cout << "Log2(" << i << ") = " << emp::Log2(i)
<< " Log(10, " << i << ") = " << emp::Log(10, i)
<< " Pow(" << i << ", 3.0) = " << emp::Pow(i, 3.0)
<< std::endl;
}
constexpr double x = emp::Log(10, emp::E);
std::cout << "x = " << x << std::endl;
std::cout << "emp::Mod(10, 7) = " << emp::Mod(10, 7) << " (expected 3)" << std::endl;
std::cout << "emp::Mod(3, 7) = " << emp::Mod(3, 7) << " (expected 3)" << std::endl;
std::cout << "emp::Mod(-4, 7) = " << emp::Mod(-4, 7) << " (expected 3)" << std::endl;
std::cout << "emp::Mod(-11, 7) = " << emp::Mod(-11, 7) << " (expected 3)" << std::endl;
std::cout << "emp::Mod(3.0, 2.5) = " << emp::Mod(3.0, 2.5) << " (expected 0.5)" << std::endl;
std::cout << "emp::Mod(-1.1, 2.5) = " << emp::Mod(-1.1, 2.5) << " (expected 1.4)" << std::endl;
std::cout << "emp::Mod(12.34, 2.5) = " << emp::Mod(12.34, 2.5) << " (expected 2.34)" << std::endl;
std::cout << "emp::Mod(-12.34, 2.5) = " << emp::Mod(-12.34, 2.5) << " (expected 0.16)" << std::endl;
std::cout << "emp::Pow(2,3) = " << emp::Pow(2,3) << " (expected 8)" << std::endl;
std::cout << "emp::Pow(-2,2) = " << emp::Pow(-2,2) << " (expected 4)" << std::endl;
std::cout << "emp::Pow(3,4) = " << emp::Pow(3,4) << " (expected 81)" << std::endl;
}
| 45.473684 | 102 | 0.488426 | koellingh |
d47a5cf69d13c7bea9bca793f3911943798bc2d2 | 2,915 | cpp | C++ | miditool/miditool.cpp | DannyHavenith/miditool | f3a371912ef5d2d5f23fce30c06a378575debb36 | [
"BSL-1.0"
] | null | null | null | miditool/miditool.cpp | DannyHavenith/miditool | f3a371912ef5d2d5f23fce30c06a378575debb36 | [
"BSL-1.0"
] | null | null | null | miditool/miditool.cpp | DannyHavenith/miditool | f3a371912ef5d2d5f23fce30c06a378575debb36 | [
"BSL-1.0"
] | null | null | null | //
// Copyright (C) 2012 Danny Havenith
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#include <iostream>
#include <fstream>
#include <exception>
#include <iomanip> // for setiosflags, setw
#include "midilib/include/midi_parser.hpp"
#include "midilib/include/midi_multiplexer.hpp"
#include "midilib/include/timed_midi_visitor.hpp"
///
/// This class only reacts on meta events. If the meta event is of type "text" (0x01)
/// then it will print the data of the event to the given output stream.
/// backward- and forward slashes will be converted to newlines.
/// texts that start with @ will be ignored.
///
struct print_text_visitor: public events::timed_visitor<print_text_visitor>
{
typedef events::timed_visitor< print_text_visitor> parent;
using parent::operator();
print_text_visitor( std::ostream &output, midi_header &header)
: output(output), parent( header)
{
}
void operator()( const events::meta &event)
{
using namespace std;
// is it a text event?
// we're ignoring lyrics (0x05) events, because text events have more
// information (like 'start of new line')
if (event.type == 0x01)
{
string event_text( event.bytes.begin(), event.bytes.end());
if (event_text.size() > 0 && event_text[0] != '@')
{
if (event_text[0] == '/' || event_text[0] == '\\')
{
output << "\n" << setiosflags( ios::right) << setprecision(2) << fixed << setw( 6) << get_current_time() << '\t';
output << event_text.substr( 1);
}
else
{
output << event_text;
}
}
}
}
private:
std::ostream &output;
};
int main( int argc, char *argv[])
{
using namespace std;
if (argc != 2)
{
cerr << "usage: miditool <midi file name>\n";
exit( -1);
}
try
{
string filename( argv[1]);
ifstream inputfile( filename.c_str(), ios::binary);
if (!inputfile)
{
throw runtime_error( "could not open " + filename + " for reading");
}
midi_file midi;
if (!parse_midifile( inputfile, midi))
{
throw runtime_error( "I can't parse " + filename + " as a valid midi file");
}
// combine all midi tracks into one virtual track.
midi_multiplexer multiplexer( midi.tracks);
// now print all lyrics in the midi file by sending a print_text_visitor into the data structure.
multiplexer.accept( print_text_visitor( cout, midi.header));
}
catch (const exception &e)
{
cerr << "something went wrong: " << e.what() << '\n';
}
return 0;
}
| 29.15 | 133 | 0.578731 | DannyHavenith |
d47f901d5644fd16a972e82ad4b2cfe6670851c4 | 512 | hxx | C++ | util-lib/include/util/VectorComparator.hxx | andrey-nakin/caen-v1720e-frontend | 00d713df62cf3abe330b08411e1f3732e56b4895 | [
"MIT"
] | null | null | null | util-lib/include/util/VectorComparator.hxx | andrey-nakin/caen-v1720e-frontend | 00d713df62cf3abe330b08411e1f3732e56b4895 | [
"MIT"
] | 8 | 2019-03-06T08:43:29.000Z | 2019-05-07T11:28:08.000Z | util-lib/include/util/VectorComparator.hxx | andrey-nakin/gneis-daq | 00d713df62cf3abe330b08411e1f3732e56b4895 | [
"MIT"
] | null | null | null | #pragma once
#include <cstring>
#include <vector>
namespace util {
class VectorComparator {
VectorComparator() = delete;
public:
template<typename ValueT>
static bool equal(std::vector<ValueT> const& a,
std::vector<ValueT> const& b) {
if (a.size() != b.size()) {
return false;
}
if (a.empty()) {
return true;
}
return 0 == memcmp(&a[0], &b[0], a.size() * sizeof(a[0]));
}
static bool equal(std::vector<bool> const& a, std::vector<bool> const& b) {
return a == b;
}
};
}
| 13.128205 | 76 | 0.605469 | andrey-nakin |
d481bf312f155e5eedaad5a503d3e60689a8e52e | 6,271 | cc | C++ | src/SymmetryAxisNormal.cc | maruinen/FullereneViewer | da1554af2de21e90bfa0380a5b635f8bab8e2d8c | [
"Apache-2.0"
] | null | null | null | src/SymmetryAxisNormal.cc | maruinen/FullereneViewer | da1554af2de21e90bfa0380a5b635f8bab8e2d8c | [
"Apache-2.0"
] | null | null | null | src/SymmetryAxisNormal.cc | maruinen/FullereneViewer | da1554af2de21e90bfa0380a5b635f8bab8e2d8c | [
"Apache-2.0"
] | null | null | null | /*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-14 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#include <assert.h>
#include "SymmetryAxisNormal.h"
#include "CarbonAllotrope.h"
#include "OpenGLUtil.h"
#include "ShutUp.h"
SymmetryAxisNormal::SymmetryAxisNormal(CarbonAllotrope* ca, SymmetryAxis* axis)
: InteractiveRegularPolygon(ca, 0, 1.0, 2), p_ca(ca), p_axis(axis)
{
}
SymmetryAxisNormal::~SymmetryAxisNormal()
{
}
void SymmetryAxisNormal::reset_interaction()
{
InteractiveRegularPolygon::reset_interaction();
}
void SymmetryAxisNormal::interaction_original(OriginalForceType UNUSED(force_type),
Interactives* UNUSED(interactives), double UNUSED(delta))
{
Vector3 north_location;
Vector3 south_location;
int north = p_axis->get_north_sequence_no();
int south = p_axis->get_south_sequence_no();
switch (p_axis->get_type())
{
case AXIS_TYPE_CENTER_OF_TWO_CARBONS:
{
Carbon* north_carbon = p_ca->get_carbon_by_sequence_no(north);
Carbon* south_carbon = p_ca->get_carbon_by_sequence_no(south);
north_location = north_carbon->get_center_location();
south_location = south_carbon->get_center_location();
}
break;
case AXIS_TYPE_CENTER_OF_CARBON_AND_BOND:
{
Carbon* north_carbon = p_ca->get_carbon_by_sequence_no(north);
Bond* south_bond = p_ca->get_bond_by_sequence_no(south);
north_location = north_carbon->get_center_location();
south_location = south_bond->get_center_location();
}
break;
case AXIS_TYPE_CENTER_OF_CARBON_AND_RING:
{
Carbon* north_carbon = p_ca->get_carbon_by_sequence_no(north);
Ring* south_ring = p_ca->get_ring_by_sequence_no(south);
north_location = north_carbon->get_center_location();
south_location = south_ring->get_center_location();
}
break;
case AXIS_TYPE_CENTER_OF_CARBON_AND_BOUNDARY:
{
Carbon* north_carbon = p_ca->get_carbon_by_sequence_no(north);
ConnectedBoundary* south_boundary = p_ca->get_boundary_by_sequence_no(south);
north_location = north_carbon->get_center_location();
south_location = south_boundary->get_center_location();
}
break;
case AXIS_TYPE_CENTER_OF_TWO_BONDS:
{
Bond* north_bond = p_ca->get_bond_by_sequence_no(north);
Bond* south_bond = p_ca->get_bond_by_sequence_no(south);
north_location = north_bond->get_center_location();
south_location = south_bond->get_center_location();
}
break;
case AXIS_TYPE_CENTER_OF_BOND_AND_RING:
{
Bond* north_bond = p_ca->get_bond_by_sequence_no(north);
Ring* south_ring = p_ca->get_ring_by_sequence_no(south);
north_location = north_bond->get_center_location();
south_location = south_ring->get_center_location();
}
break;
case AXIS_TYPE_CENTER_OF_BOND_AND_BOUNDARY:
{
Bond* north_bond = p_ca->get_bond_by_sequence_no(north);
ConnectedBoundary* south_boundary = p_ca->get_boundary_by_sequence_no(south);
north_location = north_bond->get_center_location();
south_location = south_boundary->get_center_location();
}
break;
case AXIS_TYPE_CENTER_OF_TWO_RINGS:
{
Ring* north_ring = p_ca->get_ring_by_sequence_no(north);
Ring* south_ring = p_ca->get_ring_by_sequence_no(south);
north_location = north_ring->get_center_location();
south_location = south_ring->get_center_location();
}
break;
case AXIS_TYPE_CENTER_OF_RING_AND_BOUNDARY:
{
Ring* north_ring = p_ca->get_ring_by_sequence_no(north);
ConnectedBoundary* south_boundary = p_ca->get_boundary_by_sequence_no(south);
north_location = north_ring->get_center_location();
south_location = south_boundary->get_center_location();
}
break;
case AXIS_TYPE_CENTER_OF_TWO_BOUNDARIES:
{
ConnectedBoundary* north_boundary = p_ca->get_boundary_by_sequence_no(north);
ConnectedBoundary* south_boundary = p_ca->get_boundary_by_sequence_no(south);
north_location = north_boundary->get_center_location();
south_location = south_boundary->get_center_location();
}
break;
case AXIS_TYPE_CENTER_OF_ONLY_ONE_CARBON:
{
Carbon* north_carbon = p_ca->get_carbon_by_sequence_no(north);
Vector3 center_location = p_ca->get_center_location();
north_location = north_carbon->get_center_location();
south_location = Vector3() - north_location;
}
break;
case AXIS_TYPE_CENTER_OF_ONLY_ONE_BOND:
{
Bond* north_bond = p_ca->get_bond_by_sequence_no(north);
Vector3 center_location = p_ca->get_center_location();
north_location = north_bond->get_center_location();
south_location = Vector3() - north_location;
}
break;
case AXIS_TYPE_CENTER_OF_ONLY_ONE_RING:
{
Ring* north_ring = p_ca->get_ring_by_sequence_no(north);
Vector3 center_location = p_ca->get_center_location();
north_location = north_ring->get_center_location();
south_location = Vector3() - north_location;
}
break;
case AXIS_TYPE_CENTER_OF_ONLY_ONE_BOUNDARY:
{
ConnectedBoundary* north_boundary = p_ca->get_boundary_by_sequence_no(north);
Vector3 center_location = p_ca->get_center_location();
north_location = north_boundary->get_center_location();
south_location = Vector3() - north_location;
}
break;
default:
assert(0);
}
Vector3 center = (north_location + south_location) * 0.5;
Vector3 normal = north_location - south_location;
p_normal.clockwise = 1;
fix_center_location(center);
fix_radius_length(normal.abs() * 0.6);
fix_posture(Matrix3(Quaternion(Vector3(0.0, 0.0, 1.0), normal)));
}
void SymmetryAxisNormal::draw_opaque_by_OpenGL(bool UNUSED(selection)) const
{
Vector3 norm = get_normal();
norm *= p_radius.length;
OpenGLUtil::set_color(0x001810);
OpenGLUtil::draw_cylinder(0.1, get_center_location() - norm,
get_center_location() + norm);
}
/* Local Variables: */
/* mode: c++ */
/* End: */
| 36.672515 | 103 | 0.69351 | maruinen |
d482493f22cee7d1d51fd9516f9bc6a9e3f4c973 | 2,222 | cpp | C++ | Visual Studio 2010/Projects/bjarneStroustrupC++PartIII/bjarneStroustrupC++PartIII/Chapter20TryThis1.cpp | Ziezi/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup- | 6fd64801863e883508f15d16398744405f4f9e34 | [
"Unlicense"
] | 9 | 2018-10-24T15:16:47.000Z | 2021-12-14T13:53:50.000Z | Visual Studio 2010/Projects/bjarneStroustrupC++PartIII/bjarneStroustrupC++PartIII/Chapter20TryThis1.cpp | ChrisBKirov/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup- | 6fd64801863e883508f15d16398744405f4f9e34 | [
"Unlicense"
] | null | null | null | Visual Studio 2010/Projects/bjarneStroustrupC++PartIII/bjarneStroustrupC++PartIII/Chapter20TryThis1.cpp | ChrisBKirov/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup- | 6fd64801863e883508f15d16398744405f4f9e34 | [
"Unlicense"
] | 7 | 2018-10-29T15:30:37.000Z | 2021-01-18T15:15:09.000Z | /*
TITLE Improving "ugly" code Chapter20TryThis1.cpp
"Bjarne Stroustrup "C++ Programming: Principles and Practice.""
COMMENT
Objective: If you were able how would you change Jill's code
to get rid of the ugliness?
Input: -
Output: -
Author: Chris B. Kirov
Date: 17. 02. 2017
*/
#include <iostream>
#include <vector>
double* get_from_jack(int* count); // read from array
std::vector<double>* get_from_jill(); // read from vector
// First attempt
void fct()
{
int jack_count = 0;
double* jack_data = get_from_jack(&jack_count);
std::vector<double>* jill_data = get_from_jill();
std::vector<double>& v = *jill_data; // introduce a reference to eliminate ptr dereference in the code
// process
double h = -1;
double* jack_high;
double* jill_high;
for (int i = 0; i < jack_count; ++i)
{
if (h < jack_data[i])
{
jack_high = &jack_data[i];
}
}
h = -1;
for (int i = 0; i < v.size(); ++i)
{
if (h < v[i])
{
jill_high = &v[i];
}
}
std::cout <<"Jill's max: " << *jill_high <<" Jack's max: "<< *jack_high;
delete[] jack_data;
delete jill_data;
}
//---------------------------------------------------------------------------------------------------------------------------
// Second attempt
double* high (double* first, double* last)
{
double h = -1;
double* high;
for (double* p = first; p != last; ++p)
{
if (h < *p)
{
high = p;
}
}
return high;
}
//---------------------------------------------------------------------------------------------------------------------------
void fct2()
{
int jack_count = 0;
double* jack_data = get_from_jack(&jack_count);
std::vector<double>* jill_data = get_from_jill();
std::vector<double>& v = *jill_data;
double* jack_high = high(jack_data, jack_data + jack_count);
double* jill_high = high(&v[0], &v[0] + v.size());
std::cout <<"Jill's max: " << *jill_high <<" Jack's max: "<< *jack_high;
delete[] jack_data;
delete jill_data;
}
//---------------------------------------------------------------------------------------------------------------------------
int main()
{
try
{
}
catch (std::exception& e)
{
std::cerr << e.what();
}
getchar ();
} | 21.572816 | 125 | 0.5045 | Ziezi |
d4839516c3e8b8be4f0bab362e61cfb67d92d376 | 1,125 | hpp | C++ | include/Frame.hpp | AgostonSzepessy/oxshans-battle | 15d4cd5eb6375cca5e8e426fc9b8f70e74ca28b0 | [
"MIT"
] | null | null | null | include/Frame.hpp | AgostonSzepessy/oxshans-battle | 15d4cd5eb6375cca5e8e426fc9b8f70e74ca28b0 | [
"MIT"
] | null | null | null | include/Frame.hpp | AgostonSzepessy/oxshans-battle | 15d4cd5eb6375cca5e8e426fc9b8f70e74ca28b0 | [
"MIT"
] | null | null | null | #pragma once
#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>
#include <vector>
/**
* A class that .
*/
/**
* @brief The Frame class Contains the frames in a vector that are needed for an AnimatedSprite
* and the delay between each frame. A frame is an sf::IntRect and the
* AnimatedSprite uses that to find the subimage
*/
class Frame
{
public:
/**
* @brief Frame Creates a new Frame
*/
Frame();
/**
* @brief setDelay Sets the delay between the frames
* @param d The delay between frames
*/
void setDelay(double d);
/**
* @brief addFrame Adds a frame to the back of the vector
* @param rect The Frame to add
*/
void addFrame(const sf::IntRect rect);
/**
* @brief getFrames Returns a vector that contains all the frames
* that have been added.
* @return A vector with all the frames
*/
std::vector<sf::IntRect> getFrames() const;
/**
* @brief getDelay Gets the delay between frames.
* @return Delay between frames
*/
int getDelay() const;
protected:
private:
std::vector<sf::IntRect> frames;
int delay;
int height;
int width;
};
| 21.226415 | 95 | 0.661333 | AgostonSzepessy |
d48e6d4501bd9a61aedb5138d3e0d499ed60ec4e | 356 | cpp | C++ | libs/libc/unistd.cpp | jasonwer/WingOS | 1e3b8b272bc93542fda48ed1cf3226e63c923f39 | [
"BSD-2-Clause"
] | null | null | null | libs/libc/unistd.cpp | jasonwer/WingOS | 1e3b8b272bc93542fda48ed1cf3226e63c923f39 | [
"BSD-2-Clause"
] | null | null | null | libs/libc/unistd.cpp | jasonwer/WingOS | 1e3b8b272bc93542fda48ed1cf3226e63c923f39 | [
"BSD-2-Clause"
] | null | null | null | #include "unistd.h"
#include <kern/syscall.h>
unsigned int sleep(unsigned int sec)
{
timespec time = {0, 0};
time.tv_sec = sec;
return sys::sys$nano_sleep(&time, nullptr);
}
suseconds_t usleep(suseconds_t sec)
{
timespec time = {0, 0};
time.tv_sec = 0;
time.tv_nsec = sec * 1000;
return sys::sys$nano_sleep(&time, nullptr);
}
| 19.777778 | 47 | 0.646067 | jasonwer |
d491564c71c02486d74c18544dd6e9165346ab3f | 6,337 | hpp | C++ | include/dragon/graph/graph.hpp | parth-07/dragon | 2e771d698398303c8ae6d603d28bc3acfa116181 | [
"MIT"
] | 1 | 2021-02-24T17:51:32.000Z | 2021-02-24T17:51:32.000Z | include/dragon/graph/graph.hpp | parth-07/dragon | 2e771d698398303c8ae6d603d28bc3acfa116181 | [
"MIT"
] | 1 | 2021-02-24T17:57:04.000Z | 2021-05-17T11:09:40.000Z | include/dragon/graph/graph.hpp | parth-07/ds-and-algos | 2e771d698398303c8ae6d603d28bc3acfa116181 | [
"MIT"
] | null | null | null | #ifndef DRAGON_GRAPH_GRAPH_HPP
#define DRAGON_GRAPH_GRAPH_HPP
#include <limits>
#include <map>
#include <vector>
namespace dragon {
/**
* `Graph` is an efficient, easy to use generic implementation of the basic
* graph data structure.
*
* @param ValueT type of value of graph nodes.
* @param EdgeValueT type of weight of graph edges.
*
* @note `Graph` do not support multiple edges between the same nodes.
*/
template <typename ValueT, typename EdgeValueT = int> class Graph {
public:
using ValueType = ValueT;
using EdgeValueType = EdgeValueT;
using SizeType = std::size_t;
using AdjacencyStructureType = std::map<SizeType, EdgeValueType>;
class Node;
using size_type = SizeType; // NOLINT
private:
template <typename T> using Sequence = std::vector<T>;
using NodeSequenceType = Sequence<Node>;
public:
using iterator = typename NodeSequenceType::iterator; // NOLINT
using const_iterator = typename NodeSequenceType::const_iterator; // NOLINT
public:
static constexpr SizeType npos = std::numeric_limits<SizeType>::max();
static constexpr EdgeValueType
nweight = std::numeric_limits<EdgeValueType>::max();
public:
Graph(SizeType sz = 0, SizeType root = 0) : m_root(root) {
for (auto i = 0U; i < sz; ++i) {
m_nodes.emplace_back(i);
}
}
Graph(const Graph&) = default;
Graph(Graph&&) noexcept = default;
Graph& operator=(const Graph&) = default;
Graph& operator=(Graph&&) noexcept = default;
~Graph() = default;
/// Returns a reference to ith node of the graph.
auto& operator[](SizeType index) { return m_nodes[index]; }
auto& operator[](SizeType index) const { return m_nodes[index]; }
/// Returns begin iterator for the nodes of the graph.
auto begin() { return m_nodes.begin(); }
auto begin() const { return m_nodes.begin(); }
/// Returns end iterator for the nodes of the graph.
auto end() { return m_nodes.end(); }
auto end() const { return m_nodes.end(); }
auto cbegin() const { return m_nodes.cbegin(); }
auto cend() const { return m_nodes.cend(); }
/**
* Clears all nodes of the graph.
*/
void clear();
/**
* Adds a weighted directed edge from node `u` to `v` (`u` -> `v`),
*
* If an edge already exists from node `u` to node `v`, then the edge weight
* is updated.
*
* @param u first node of the edge.
* @param v second node of the edge.
* @param weight weight of the edge.
*/
void add_directed_edge(SizeType u_i, SizeType v_i, EdgeValueType weight = 1);
/**
* Adds a weighted undirected edge between node `u` and `v`.
*
* If an undirected edge already exists between nodes `u` and `v`, then the
* edge weight is updated.
*
* @param u first node of the edge.
* @param v second node of the edge.
* @param weight weight of the edge.
*/
void add_undirected_edge(SizeType u_i, SizeType v_i,
EdgeValueType weight = 1);
/**
* Remove a directed edge from node `u` to `v`.
*
* Does nothing if no directed edge exist from node `u` to `v`.
*
* @param u_i index of the first node
* @param v_i index of the second node
*/
void remove_directed_edge(SizeType u_i, SizeType v_i);
/**
* Remove an undirected edge between nodes `u` and `v`.
*
* Does nothing if no undirected edge exist between nodes `u` and `v`.
*/
void remove_undirected_edge(SizeType u_i, SizeType v_i);
/// Reset all nodes color to `Color::white`.
void reset_color();
/// Returns the number of nodes in the graph.
auto size() const;
/// Returns the index of the root node.
auto root() const;
enum class Color { white, grey, black };
/**
* `Node` is a data structure to represent a node of the graph.
*/
class Node {
public:
Node(SizeType index) : m_index(index) {}
Node(SizeType index, ValueType p_value) : m_index(index), value(p_value) {}
Node(const Node&) = default;
Node(Node&&) noexcept = default;
Node& operator=(const Node&) = default;
Node& operator=(Node&&) noexcept = default;
~Node() = default;
public:
SizeType index() const { return m_index; }
ValueType value;
AdjacencyStructureType edges;
Color color = Color::white;
SizeType parent = npos, depth = npos;
private:
const SizeType m_index;
};
public:
const NodeSequenceType& nodes = m_nodes; // NOLINT
private:
/// Stores nodes of the graph.
NodeSequenceType m_nodes;
/// Stores index of the root node.
const SizeType m_root;
};
template <typename ValueT, typename EdgeValueT>
constexpr typename Graph<ValueT, EdgeValueT>::SizeType
Graph<ValueT, EdgeValueT>::npos;
template <typename ValueT, typename EdgeValueT>
constexpr typename Graph<ValueT, EdgeValueT>::EdgeValueType
Graph<ValueT, EdgeValueT>::nweight;
template <typename ValueT, typename EdgeValueT>
void Graph<ValueT, EdgeValueT>::add_directed_edge(SizeType u_i, SizeType v_i,
EdgeValueType weight) {
m_nodes[u_i].edges[v_i] = weight;
}
template <typename ValueT, typename EdgeValueT>
void Graph<ValueT, EdgeValueT>::add_undirected_edge(SizeType u_i, SizeType v_i,
EdgeValueType weight) {
m_nodes[u_i].edges[v_i] = weight;
m_nodes[v_i].edges[u_i] = weight;
}
template <typename ValueT, typename EdgeValueT>
void Graph<ValueT, EdgeValueT>::remove_directed_edge(SizeType u_i,
SizeType v_i) {
m_nodes[u_i].edges.erase(v_i);
}
template <typename ValueT, typename EdgeValueT>
void Graph<ValueT, EdgeValueT>::remove_undirected_edge(SizeType u_i,
SizeType v_i) {
m_nodes[u_i].edges.erase(v_i);
m_nodes[v_i].edges.erase(u_i);
}
template <typename ValueT, typename EdgeValueT>
void Graph<ValueT, EdgeValueT>::clear() {
m_nodes.clear();
}
template <typename ValueT, typename EdgeValueT>
void Graph<ValueT, EdgeValueT>::reset_color() {
for (auto& node : m_nodes) {
node.color = Color::white;
}
}
template <typename ValueT, typename EdgeValueT>
auto Graph<ValueT, EdgeValueT>::size() const {
return m_nodes.size();
}
template <typename ValueT, typename EdgeValueT>
auto Graph<ValueT, EdgeValueT>::root() const {
return m_root;
}
} // namespace dragon
#endif | 29.751174 | 79 | 0.666246 | parth-07 |
d49271aab644f8d38800109d637721cba882a027 | 11,956 | cpp | C++ | cmd/silkrpc_toolbox.cpp | enriavil1/silkrpc | 1fa2109658d4c89b6cfdd5190d919bd1324f367e | [
"Apache-2.0"
] | null | null | null | cmd/silkrpc_toolbox.cpp | enriavil1/silkrpc | 1fa2109658d4c89b6cfdd5190d919bd1324f367e | [
"Apache-2.0"
] | null | null | null | cmd/silkrpc_toolbox.cpp | enriavil1/silkrpc | 1fa2109658d4c89b6cfdd5190d919bd1324f367e | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2020-2021 The Silkrpc Authors
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 <iostream>
#include <string>
#include <absl/flags/flag.h>
#include <absl/flags/parse.h>
#include <absl/flags/usage.h>
#include <silkworm/common/util.hpp>
#include <silkrpc/common/constants.hpp>
#include <silkrpc/common/log.hpp>
int ethbackend_async(const std::string& target);
int ethbackend_coroutines(const std::string& target);
int ethbackend(const std::string& target);
int kv_seek_async_callback(const std::string& target, const std::string& table_name, const silkworm::Bytes& key, uint32_t timeout);
int kv_seek_async_coroutines(const std::string& target, const std::string& table_name, const silkworm::Bytes& key, uint32_t timeout);
int kv_seek_async(const std::string& target, const std::string& table_name, const silkworm::Bytes& key, uint32_t timeout);
int kv_seek_both(const std::string& target, const std::string& table_name, const silkworm::Bytes& key, const silkworm::Bytes& subkey);
int kv_seek(const std::string& target, const std::string& table_name, const silkworm::Bytes& key);
ABSL_FLAG(std::string, key, "", "key as hex string w/o leading 0x");
ABSL_FLAG(silkrpc::LogLevel, logLevel, silkrpc::LogLevel::Critical, "logging level as string");
ABSL_FLAG(std::string, seekkey, "", "seek key as hex string w/o leading 0x");
ABSL_FLAG(std::string, subkey, "", "subkey as hex string w/o leading 0x");
ABSL_FLAG(std::string, tool, "", "gRPC remote interface tool name as string");
ABSL_FLAG(std::string, target, silkrpc::kDefaultTarget, "Erigon location as string <address>:<port>");
ABSL_FLAG(std::string, table, "", "database table name as string");
ABSL_FLAG(uint32_t, timeout, silkrpc::kDefaultTimeout.count(), "gRPC call timeout as integer");
int ethbackend_async(int argc, char* argv[]) {
auto target{absl::GetFlag(FLAGS_target)};
if (target.empty() || target.find(":") == std::string::npos) {
std::cerr << "Parameter target is invalid: [" << target << "]\n";
std::cerr << "Use --target flag to specify the location of Erigon running instance\n";
return -1;
}
return ethbackend_async(target);
}
int ethbackend_coroutines(int argc, char* argv[]) {
auto target{absl::GetFlag(FLAGS_target)};
if (target.empty() || target.find(":") == std::string::npos) {
std::cerr << "Parameter target is invalid: [" << target << "]\n";
std::cerr << "Use --target flag to specify the location of Erigon running instance\n";
return -1;
}
return ethbackend_coroutines(target);
}
int ethbackend(int argc, char* argv[]) {
auto target{absl::GetFlag(FLAGS_target)};
if (target.empty() || target.find(":") == std::string::npos) {
std::cerr << "Parameter target is invalid: [" << target << "]\n";
std::cerr << "Use --target flag to specify the location of Erigon running instance\n";
return -1;
}
return ethbackend(target);
}
int kv_seek_async_callback(int argc, char* argv[]) {
auto target{absl::GetFlag(FLAGS_target)};
if (target.empty() || target.find(":") == std::string::npos) {
std::cerr << "Parameter target is invalid: [" << target << "]\n";
std::cerr << "Use --target flag to specify the location of Erigon running instance\n";
return -1;
}
auto table_name{absl::GetFlag(FLAGS_table)};
if (table_name.empty()) {
std::cerr << "Parameter table is invalid: [" << table_name << "]\n";
std::cerr << "Use --table flag to specify the name of Erigon database table\n";
return -1;
}
auto key{absl::GetFlag(FLAGS_key)};
const auto key_bytes = silkworm::from_hex(key);
if (key.empty() || !key_bytes.has_value()) {
std::cerr << "Parameter key is invalid: [" << key << "]\n";
std::cerr << "Use --key flag to specify the key in key-value dupsort table\n";
return -1;
}
auto timeout{absl::GetFlag(FLAGS_timeout)};
if (timeout < 0) {
std::cerr << "Parameter timeout is invalid: [" << timeout << "]\n";
std::cerr << "Use --timeout flag to specify the timeout in msecs for Erigon KV gRPC calls\n";
return -1;
}
return kv_seek_async_callback(target, table_name, key_bytes.value(), timeout);
}
int kv_seek_async_coroutines(int argc, char* argv[]) {
auto target{absl::GetFlag(FLAGS_target)};
if (target.empty() || target.find(":") == std::string::npos) {
std::cerr << "Parameter target is invalid: [" << target << "]\n";
std::cerr << "Use --target flag to specify the location of Erigon running instance\n";
return -1;
}
auto table_name{absl::GetFlag(FLAGS_table)};
if (table_name.empty()) {
std::cerr << "Parameter table is invalid: [" << table_name << "]\n";
std::cerr << "Use --table flag to specify the name of Erigon database table\n";
return -1;
}
auto key{absl::GetFlag(FLAGS_key)};
const auto key_bytes = silkworm::from_hex(key);
if (key.empty() || !key_bytes.has_value()) {
std::cerr << "Parameter key is invalid: [" << key << "]\n";
std::cerr << "Use --key flag to specify the key in key-value dupsort table\n";
return -1;
}
auto timeout{absl::GetFlag(FLAGS_timeout)};
if (timeout < 0) {
std::cerr << "Parameter timeout is invalid: [" << timeout << "]\n";
std::cerr << "Use --timeout flag to specify the timeout in msecs for Erigon KV gRPC calls\n";
return -1;
}
return kv_seek_async_coroutines(target, table_name, key_bytes.value(), timeout);
}
int kv_seek_async(int argc, char* argv[]) {
auto target{absl::GetFlag(FLAGS_target)};
if (target.empty() || target.find(":") == std::string::npos) {
std::cerr << "Parameter target is invalid: [" << target << "]\n";
std::cerr << "Use --target flag to specify the location of Erigon running instance\n";
return -1;
}
auto table_name{absl::GetFlag(FLAGS_table)};
if (table_name.empty()) {
std::cerr << "Parameter table is invalid: [" << table_name << "]\n";
std::cerr << "Use --table flag to specify the name of Erigon database table\n";
return -1;
}
auto key{absl::GetFlag(FLAGS_key)};
const auto key_bytes = silkworm::from_hex(key);
if (key.empty() || !key_bytes.has_value()) {
std::cerr << "Parameter key is invalid: [" << key << "]\n";
std::cerr << "Use --key flag to specify the key in key-value dupsort table\n";
return -1;
}
auto timeout{absl::GetFlag(FLAGS_timeout)};
if (timeout < 0) {
std::cerr << "Parameter timeout is invalid: [" << timeout << "]\n";
std::cerr << "Use --timeout flag to specify the timeout in msecs for Erigon KV gRPC calls\n";
return -1;
}
return kv_seek_async(target, table_name, key_bytes.value(), timeout);
}
int kv_seek_both(int argc, char* argv[]) {
auto target{absl::GetFlag(FLAGS_target)};
if (target.empty() || target.find(":") == std::string::npos) {
std::cerr << "Parameter target is invalid: [" << target << "]\n";
std::cerr << "Use --target flag to specify the location of Erigon running instance\n";
return -1;
}
auto table_name{absl::GetFlag(FLAGS_table)};
if (table_name.empty()) {
std::cerr << "Parameter table is invalid: [" << table_name << "]\n";
std::cerr << "Use --table flag to specify the name of Erigon database table\n";
return -1;
}
auto key{absl::GetFlag(FLAGS_key)};
const auto key_bytes = silkworm::from_hex(key);
if (key.empty() || !key_bytes.has_value()) {
std::cerr << "Parameter key is invalid: [" << key << "]\n";
std::cerr << "Use --key flag to specify the key in key-value dupsort table\n";
return -1;
}
auto subkey{absl::GetFlag(FLAGS_subkey)};
const auto subkey_bytes = silkworm::from_hex(subkey);
if (subkey.empty() || !subkey_bytes.has_value()) {
std::cerr << "Parameter subkey is invalid: [" << subkey << "]\n";
std::cerr << "Use --subkey flag to specify the subkey in key-value dupsort table\n";
return -1;
}
return kv_seek_both(target, table_name, key_bytes.value(), subkey_bytes.value());
}
int kv_seek(int argc, char* argv[]) {
auto target{absl::GetFlag(FLAGS_target)};
if (target.empty() || target.find(":") == std::string::npos) {
std::cerr << "Parameter target is invalid: [" << target << "]\n";
std::cerr << "Use --target flag to specify the location of Erigon running instance\n";
return -1;
}
auto table_name{absl::GetFlag(FLAGS_table)};
if (table_name.empty()) {
std::cerr << "Parameter table is invalid: [" << table_name << "]\n";
std::cerr << "Use --table flag to specify the name of Erigon database table\n";
return -1;
}
auto key{absl::GetFlag(FLAGS_key)};
const auto key_bytes = silkworm::from_hex(key);
if (key.empty() || !key_bytes.has_value()) {
std::cerr << "Parameter key is invalid: [" << key << "]\n";
std::cerr << "Use --key flag to specify the key in key-value dupsort table\n";
return -1;
}
return kv_seek(target, table_name, key_bytes.value());
}
int main(int argc, char* argv[]) {
absl::SetProgramUsageMessage("Execute specified Silkrpc tool:\n"
"\tethbackend\t\t\tquery the Erigon/Silkworm ETHBACKEND remote interface\n"
"\tethbackend_async\t\tquery the Erigon/Silkworm ETHBACKEND remote interface\n"
"\tethbackend_coroutines\t\tquery the Erigon/Silkworm ETHBACKEND remote interface\n"
"\tkv_seek\t\t\t\tquery using SEEK the Erigon/Silkworm Key-Value (KV) remote interface to database\n"
"\tkv_seek_async\t\t\tquery using SEEK the Erigon/Silkworm Key-Value (KV) remote interface to database\n"
"\tkv_seek_async_callback\t\tquery using SEEK the Erigon/Silkworm Key-Value (KV) remote interface to database\n"
"\tkv_seek_async_coroutines\tquery using SEEK the Erigon/Silkworm Key-Value (KV) remote interface to database\n"
"\tkv_seek_both\t\t\tquery using SEEK_BOTH the Erigon/Silkworm Key-Value (KV) remote interface to database\n"
);
const auto positional_args = absl::ParseCommandLine(argc, argv);
if (positional_args.size() < 2) {
std::cerr << "No Silkrpc tool specified as first positional argument\n\n";
std::cerr << absl::ProgramUsageMessage();
return -1;
}
SILKRPC_LOG_VERBOSITY(absl::GetFlag(FLAGS_logLevel));
const std::string tool{positional_args[1]};
if (tool == "ethbackend_async") {
return ethbackend_async(argc, argv);
}
if (tool == "ethbackend_coroutines") {
return ethbackend_coroutines(argc, argv);
}
if (tool == "ethbackend") {
return ethbackend(argc, argv);
}
if (tool == "kv_seek_async_callback") {
return kv_seek_async_callback(argc, argv);
}
if (tool == "kv_seek_async_coroutines") {
return kv_seek_async_coroutines(argc, argv);
}
if (tool == "kv_seek_async") {
return kv_seek_async(argc, argv);
}
if (tool == "kv_seek_both") {
return kv_seek_both(argc, argv);
}
if (tool == "kv_seek") {
return kv_seek(argc, argv);
}
std::cerr << "Unknown tool " << tool << " specified as first argument\n\n";
std::cerr << absl::ProgramUsageMessage();
return -1;
}
| 41.513889 | 134 | 0.640683 | enriavil1 |
d49658b46836b6b2620117739b0a4e5e9eb6a2cb | 836 | cpp | C++ | tests/math_unit/math/rev/scal/fun/digamma_test.cpp | alashworth/stan-monorepo | 75596bc1f860ededd7b3e9ae9002aea97ee1cd46 | [
"BSD-3-Clause"
] | 1 | 2019-09-06T15:53:17.000Z | 2019-09-06T15:53:17.000Z | tests/math_unit/math/rev/scal/fun/digamma_test.cpp | alashworth/stan-monorepo | 75596bc1f860ededd7b3e9ae9002aea97ee1cd46 | [
"BSD-3-Clause"
] | 8 | 2019-01-17T18:51:16.000Z | 2019-01-17T18:51:39.000Z | tests/math_unit/math/rev/scal/fun/digamma_test.cpp | alashworth/stan-monorepo | 75596bc1f860ededd7b3e9ae9002aea97ee1cd46 | [
"BSD-3-Clause"
] | null | null | null | #include <stan/math/rev/scal.hpp>
#include <gtest/gtest.h>
#include <math/rev/scal/fun/nan_util.hpp>
#include <math/rev/scal/util.hpp>
#include <boost/math/special_functions/digamma.hpp>
#include <boost/math/special_functions/zeta.hpp>
TEST(AgradRev, digamma) {
AVAR a = 0.5;
AVAR f = digamma(a);
EXPECT_FLOAT_EQ(boost::math::digamma(0.5), f.val());
AVEC x = createAVEC(a);
VEC grad_f;
f.grad(x, grad_f);
EXPECT_FLOAT_EQ(4.9348022005446793094, grad_f[0]);
}
namespace {
struct digamma_fun {
template <typename T0>
inline T0 operator()(const T0& arg1) const {
return digamma(arg1);
}
};
} // namespace
TEST(AgradRev, digamma_NaN) {
digamma_fun digamma_;
test_nan(digamma_, false, true);
}
TEST(AgradRev, check_varis_on_stack_10) {
AVAR a = 0.5;
test::check_varis_on_stack(stan::math::digamma(a));
}
| 22.594595 | 54 | 0.704545 | alashworth |
d49a88af357d8cbe7924edd00ab4b2f556ee786b | 2,238 | tcc | C++ | phpcxx/fcall.tcc | sjinks/php-cxx | c519f841c2d7122bcf02db7d43a109a6ec818e1d | [
"MIT"
] | 5 | 2017-02-26T23:55:20.000Z | 2019-10-12T04:04:38.000Z | phpcxx/fcall.tcc | sjinks/php-cxx | c519f841c2d7122bcf02db7d43a109a6ec818e1d | [
"MIT"
] | 25 | 2017-03-18T07:03:42.000Z | 2018-03-28T21:33:57.000Z | phpcxx/fcall.tcc | sjinks/php-cxx | c519f841c2d7122bcf02db7d43a109a6ec818e1d | [
"MIT"
] | 1 | 2017-03-18T07:27:25.000Z | 2017-03-18T07:27:25.000Z | #ifndef PHPCXX_FCALL_TCC
#define PHPCXX_FCALL_TCC
#ifndef PHPCXX_FCALL_H
#error "Please do not include this file directly, use fcall.h instead"
#endif
#include "array.h"
#include "value.h"
#include "bailoutrestorer.h"
namespace {
/**
* @internal
* @brief Helper function for codecov (`_zend_bailout` is for some reason not marked as `noreturn`)
* @param filename
* @param line
*/
[[noreturn]] static inline void bailout(const char* filename, long int line)
{
_zend_bailout(const_cast<char*>(filename), line);
ZEND_ASSUME(0);
}
}
namespace phpcxx {
template<typename... Params>
static Value call(const char* name, Params&&... p)
{
{
BailoutRestorer br;
JMP_BUF bailout;
FCall call(name);
EG(bailout) = &bailout;
if (EXPECTED(0 == SETJMP(bailout))) {
return call(std::forward<Params>(p)...);
}
}
bailout(__FILE__, __LINE__);
}
template<typename... Params>
static Value call(const Value& v, Params&&... p)
{
{
BailoutRestorer br;
JMP_BUF bailout;
FCall call(v.pzval());
EG(bailout) = &bailout;
if (EXPECTED(0 == SETJMP(bailout))) {
return call(std::forward<Params>(p)...);
}
}
bailout(__FILE__, __LINE__);
}
/**
* @brief Constructs `zval` from `phpcxx::Value`
* @param[in] v `phpcxx::Value`
* @return Pointer to `zval`
*/
template<> [[gnu::returns_nonnull]] inline zval* FCall::paramHelper(phpcxx::Value&& v, zval&) { return v.pzval(); }
/**
* @brief Constructs `zval` from `phpcxx::Array`
* @param[in] v `phpcxx::Array`
* @return Pointer to `zval`
*/
template<> [[gnu::returns_nonnull]] inline zval* FCall::paramHelper(phpcxx::Array&& v, zval&) { return v.pzval(); }
template<typename... Params>
inline phpcxx::Value FCall::operator()(Params&&... p)
{
return this->call(IndicesFor<Params...>{}, std::forward<Params>(p)...);
}
template<typename ...Args, std::size_t ...Is>
inline Value FCall::call(indices<Is...>, Args&&... args)
{
zval zparams[sizeof...(args) ? sizeof...(args) : sizeof...(args) + 1] = { *FCall::paramHelper(std::move(args), zparams[Is])... };
return this->operator()(sizeof...(args), zparams);
}
}
#endif /* PHPCXX_FCALL_TCC */
| 24.064516 | 133 | 0.628686 | sjinks |
d49f7b41346bf9acb7b3d683c824f176ca38aca6 | 1,481 | cpp | C++ | set1/repeat_key_xor_test.cpp | guzhoucan/cryptopals | a45280158867a86b5d8c61bf7194277d05abdf14 | [
"MIT"
] | 1 | 2020-08-07T22:38:27.000Z | 2020-08-07T22:38:27.000Z | set1/repeat_key_xor_test.cpp | guzhoucan/cryptopals | a45280158867a86b5d8c61bf7194277d05abdf14 | [
"MIT"
] | null | null | null | set1/repeat_key_xor_test.cpp | guzhoucan/cryptopals | a45280158867a86b5d8c61bf7194277d05abdf14 | [
"MIT"
] | null | null | null | #include "repeat_key_xor.h"
#include <fstream>
#include "absl/strings/escaping.h"
#include "gtest/gtest.h"
namespace cryptopals {
namespace {
TEST(RepeatKeyXorTest, RepeatKeyXorEncode) {
std::string key = "ICE";
std::string plaintext =
"Burning 'em, if you ain't quick and nimble\nI go crazy when I hear a "
"cymbal";
std::string ciphertext = RepeatKeyXorEncode(plaintext, key);
EXPECT_EQ(
"0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765"
"272a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27"
"282f",
absl::BytesToHexString(ciphertext));
}
TEST(RepeatKeyXorTest, GetHammingDistance) {
std::string str1 = "this is a test";
std::string str2 = "wokka wokka!!!";
EXPECT_EQ(37, GetHammingDistance(str1, str2));
}
TEST(RepeatKeyXorTest, BreakRepeatKeyXor) {
std::ifstream file("break_repeat_key_xor.txt",
std::ios::in | std::ios::binary);
ASSERT_TRUE(file.is_open());
std::stringstream ss;
ss << file.rdbuf();
std::string ciphertext_base64 = ss.str();
file.close();
std::string ciphertext;
ASSERT_TRUE(absl::Base64Unescape(ciphertext_base64, &ciphertext));
BreakRepeatKeyXorOutput output = BreakRepeatKeyXor(ciphertext);
EXPECT_EQ("I'm back and I'm ringin' the bell ",
output.plaintext.substr(0, output.plaintext.find('\n')));
EXPECT_EQ("Terminator X: Bring the noise", output.key);
}
} // namespace
} // namespace cryptopals | 30.854167 | 80 | 0.713032 | guzhoucan |
d4a03b833995edadf3870c0ab6fb12ddb9534388 | 1,151 | hpp | C++ | src/Logic/JFIFRewriter.hpp | vividos/RemotePhotoTool | d17ae2abbda531acbd0ec8e90ddc4856c4fdfa00 | [
"BSD-2-Clause"
] | 16 | 2015-03-26T02:32:43.000Z | 2021-10-18T16:34:31.000Z | src/Logic/JFIFRewriter.hpp | vividos/RemotePhotoTool | d17ae2abbda531acbd0ec8e90ddc4856c4fdfa00 | [
"BSD-2-Clause"
] | 7 | 2019-02-21T06:07:09.000Z | 2022-01-01T10:00:50.000Z | src/Logic/JFIFRewriter.hpp | vividos/RemotePhotoTool | d17ae2abbda531acbd0ec8e90ddc4856c4fdfa00 | [
"BSD-2-Clause"
] | 6 | 2019-05-07T09:21:15.000Z | 2021-09-01T06:36:24.000Z | //
// RemotePhotoTool - remote camera control software
// Copyright (C) 2008-2018 Michael Fink
//
/// \file JFIFRewriter.hpp JFIF (JPEG File Interchange Format) rewriter
//
#pragma once
// includes
#include <ulib/stream/IStream.hpp>
/// \brief JFIF rewriter
/// Loads JFIF data stream (used internally by JPEG images) and calls OnBlock() when a new block
/// arrives. Derived classes can then choose to re-write that block, e.g. EXIF data.
class JFIFRewriter
{
public:
/// ctor
JFIFRewriter(Stream::IStream& streamIn, Stream::IStream& streamOut)
:m_streamIn(streamIn), m_streamOut(streamOut)
{
}
/// starts rewriting process
void Start();
/// JFIF block marker
enum T_JFIFBlockMarker
{
SOI = 0xd8,
EOI = 0xd9,
APP0 = 0xe0,
APP1 = 0xe1, ///< Exif data is store in this block
DQT = 0xdb,
SOF0 = 0xc0,
DHT = 0xc4,
SOS = 0xda,
};
protected:
/// called when the next JFIF block is starting
virtual void OnBlock(BYTE marker, WORD length);
protected:
Stream::IStream& m_streamIn; ///< input stream
Stream::IStream& m_streamOut; ///< output stream
};
| 23.979167 | 96 | 0.658558 | vividos |
d4a0b39ea7a1e18149b9e420fe6231854b636669 | 8,625 | cpp | C++ | examples/ota-provider-app/ota-provider-common/OTAProviderExample.cpp | jimlyall-q/connectedhomeip | e4d15a802e663f1f2ed7b8205f027d30e447eb0e | [
"Apache-2.0"
] | 19 | 2021-02-17T12:31:28.000Z | 2022-03-24T09:15:43.000Z | examples/ota-provider-app/ota-provider-common/OTAProviderExample.cpp | jimlyall-q/connectedhomeip | e4d15a802e663f1f2ed7b8205f027d30e447eb0e | [
"Apache-2.0"
] | 18 | 2021-06-01T20:01:19.000Z | 2022-03-11T09:43:52.000Z | examples/ota-provider-app/ota-provider-common/OTAProviderExample.cpp | jimlyall-q/connectedhomeip | e4d15a802e663f1f2ed7b8205f027d30e447eb0e | [
"Apache-2.0"
] | 14 | 2020-12-14T11:05:45.000Z | 2022-03-29T08:42:30.000Z | /*
*
* Copyright (c) 2021 Project CHIP Authors
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <ota-provider-common/OTAProviderExample.h>
#include <app-common/zap-generated/cluster-id.h>
#include <app-common/zap-generated/command-id.h>
#include <app/CommandPathParams.h>
#include <app/clusters/ota-provider/ota-provider-delegate.h>
#include <app/util/af.h>
#include <lib/core/CHIPTLV.h>
#include <lib/support/CHIPMemString.h>
#include <lib/support/RandUtils.h>
#include <protocols/secure_channel/PASESession.h> // For chip::kTestDeviceNodeId
#include <string.h>
using chip::ByteSpan;
using chip::Span;
using chip::app::CommandPathFlags;
using chip::app::CommandPathParams;
using chip::app::clusters::OTAProviderDelegate;
using chip::TLV::ContextTag;
using chip::TLV::TLVWriter;
constexpr uint8_t kUpdateTokenLen = 32; // must be between 8 and 32
constexpr uint8_t kUpdateTokenStrLen = kUpdateTokenLen * 2 + 1; // Hex string needs 2 hex chars for every byte
constexpr size_t kUriMaxLen = 256;
void GetUpdateTokenString(const chip::ByteSpan & token, char * buf, size_t bufSize)
{
const uint8_t * tokenData = static_cast<const uint8_t *>(token.data());
size_t minLength = chip::min(token.size(), bufSize);
for (size_t i = 0; i < (minLength / 2) - 1; ++i)
{
snprintf(&buf[i * 2], bufSize, "%02X", tokenData[i]);
}
}
void GenerateUpdateToken(uint8_t * buf, size_t bufSize)
{
for (size_t i = 0; i < bufSize; ++i)
{
buf[i] = chip::GetRandU8();
}
}
bool GenerateBdxUri(const Span<char> & fileDesignator, Span<char> outUri, size_t availableSize)
{
static constexpr char bdxPrefix[] = "bdx://";
chip::NodeId nodeId = chip::kTestDeviceNodeId; // TODO: read this dynamically
size_t nodeIdHexStrLen = sizeof(nodeId) * 2;
size_t expectedLength = strlen(bdxPrefix) + nodeIdHexStrLen + fileDesignator.size();
if (expectedLength >= availableSize)
{
return false;
}
size_t written = static_cast<size_t>(snprintf(outUri.data(), availableSize, "%s" ChipLogFormatX64 "%s", bdxPrefix,
ChipLogValueX64(nodeId), fileDesignator.data()));
return expectedLength == written;
}
OTAProviderExample::OTAProviderExample()
{
memset(mOTAFilePath, 0, kFilepathBufLen);
}
void OTAProviderExample::SetOTAFilePath(const char * path)
{
if (path != nullptr)
{
chip::Platform::CopyString(mOTAFilePath, path);
}
else
{
memset(mOTAFilePath, 0, kFilepathBufLen);
}
}
EmberAfStatus OTAProviderExample::HandleQueryImage(chip::app::CommandHandler * commandObj, uint16_t vendorId, uint16_t productId,
uint16_t imageType, uint16_t hardwareVersion, uint32_t currentVersion,
uint8_t protocolsSupported, const chip::Span<const char> & location,
bool clientCanConsent, const chip::ByteSpan & metadataForServer)
{
// TODO: add confiuration for returning BUSY status
EmberAfOTAQueryStatus queryStatus =
(strlen(mOTAFilePath) ? EMBER_ZCL_OTA_QUERY_STATUS_UPDATE_AVAILABLE : EMBER_ZCL_OTA_QUERY_STATUS_NOT_AVAILABLE);
uint32_t delayedActionTimeSec = 0;
uint32_t softwareVersion = currentVersion + 1; // This implementation will always indicate that an update is available
// (if the user provides a file).
bool userConsentNeeded = false;
uint8_t updateToken[kUpdateTokenLen] = { 0 };
char strBuf[kUpdateTokenStrLen] = { 0 };
char uriBuf[kUriMaxLen] = { 0 };
GenerateUpdateToken(updateToken, kUpdateTokenLen);
GetUpdateTokenString(ByteSpan(updateToken), strBuf, kUpdateTokenStrLen);
ChipLogDetail(SoftwareUpdate, "generated updateToken: %s", strBuf);
if (strlen(mOTAFilePath))
{
// Only doing BDX transport for now
GenerateBdxUri(Span<char>(mOTAFilePath, strlen(mOTAFilePath)), Span<char>(uriBuf, 0), kUriMaxLen);
ChipLogDetail(SoftwareUpdate, "generated URI: %s", uriBuf);
}
CommandPathParams cmdParams = { emberAfCurrentEndpoint(), 0 /* mGroupId */, ZCL_OTA_PROVIDER_CLUSTER_ID,
ZCL_QUERY_IMAGE_RESPONSE_COMMAND_ID, (CommandPathFlags::kEndpointIdValid) };
TLVWriter * writer = nullptr;
uint8_t tagNum = 0;
VerifyOrReturnError((commandObj->PrepareCommand(cmdParams) == CHIP_NO_ERROR), EMBER_ZCL_STATUS_FAILURE);
VerifyOrReturnError((writer = commandObj->GetCommandDataElementTLVWriter()) != nullptr, EMBER_ZCL_STATUS_FAILURE);
VerifyOrReturnError(writer->Put(ContextTag(tagNum++), queryStatus) == CHIP_NO_ERROR, EMBER_ZCL_STATUS_FAILURE);
VerifyOrReturnError(writer->Put(ContextTag(tagNum++), delayedActionTimeSec) == CHIP_NO_ERROR, EMBER_ZCL_STATUS_FAILURE);
VerifyOrReturnError(writer->PutString(ContextTag(tagNum++), uriBuf) == CHIP_NO_ERROR, EMBER_ZCL_STATUS_FAILURE);
VerifyOrReturnError(writer->Put(ContextTag(tagNum++), softwareVersion) == CHIP_NO_ERROR, EMBER_ZCL_STATUS_FAILURE);
VerifyOrReturnError(writer->PutBytes(ContextTag(tagNum++), updateToken, kUpdateTokenLen) == CHIP_NO_ERROR,
EMBER_ZCL_STATUS_FAILURE);
VerifyOrReturnError(writer->Put(ContextTag(tagNum++), userConsentNeeded) == CHIP_NO_ERROR, EMBER_ZCL_STATUS_FAILURE);
VerifyOrReturnError(writer->PutBytes(ContextTag(tagNum++), updateToken, kUpdateTokenLen) == CHIP_NO_ERROR,
EMBER_ZCL_STATUS_FAILURE); // metadata
VerifyOrReturnError((commandObj->FinishCommand() == CHIP_NO_ERROR), EMBER_ZCL_STATUS_FAILURE);
return EMBER_ZCL_STATUS_SUCCESS;
}
EmberAfStatus OTAProviderExample::HandleApplyUpdateRequest(chip::app::CommandHandler * commandObj,
const chip::ByteSpan & updateToken, uint32_t newVersion)
{
// TODO: handle multiple transfers by tracking updateTokens
// TODO: add configuration for sending different updateAction and delayedActionTime values
EmberAfOTAApplyUpdateAction updateAction = EMBER_ZCL_OTA_APPLY_UPDATE_ACTION_PROCEED; // For now, just allow any update request
uint32_t delayedActionTimeSec = 0;
char tokenBuf[kUpdateTokenStrLen] = { 0 };
GetUpdateTokenString(updateToken, tokenBuf, kUpdateTokenStrLen);
ChipLogDetail(SoftwareUpdate, "%s: token: %s, version: %" PRIu32, __FUNCTION__, tokenBuf, newVersion);
VerifyOrReturnError(commandObj != nullptr, EMBER_ZCL_STATUS_INVALID_VALUE);
CommandPathParams cmdParams = { emberAfCurrentEndpoint(), 0 /* mGroupId */, ZCL_OTA_PROVIDER_CLUSTER_ID,
ZCL_APPLY_UPDATE_REQUEST_RESPONSE_COMMAND_ID, (CommandPathFlags::kEndpointIdValid) };
TLVWriter * writer = nullptr;
VerifyOrReturnError((commandObj->PrepareCommand(cmdParams) == CHIP_NO_ERROR), EMBER_ZCL_STATUS_FAILURE);
VerifyOrReturnError((writer = commandObj->GetCommandDataElementTLVWriter()) != nullptr, EMBER_ZCL_STATUS_FAILURE);
VerifyOrReturnError(writer->Put(ContextTag(0), updateAction) == CHIP_NO_ERROR, EMBER_ZCL_STATUS_FAILURE);
VerifyOrReturnError(writer->Put(ContextTag(1), delayedActionTimeSec) == CHIP_NO_ERROR, EMBER_ZCL_STATUS_FAILURE);
VerifyOrReturnError((commandObj->FinishCommand() == CHIP_NO_ERROR), EMBER_ZCL_STATUS_FAILURE);
return EMBER_ZCL_STATUS_SUCCESS;
}
EmberAfStatus OTAProviderExample::HandleNotifyUpdateApplied(const chip::ByteSpan & updateToken, uint32_t currentVersion)
{
char tokenBuf[kUpdateTokenStrLen] = { 0 };
GetUpdateTokenString(updateToken, tokenBuf, kUpdateTokenStrLen);
ChipLogDetail(SoftwareUpdate, "%s: token: %s, version: %" PRIu32, __FUNCTION__, tokenBuf, currentVersion);
emberAfSendImmediateDefaultResponse(EMBER_ZCL_STATUS_SUCCESS);
return EMBER_ZCL_STATUS_SUCCESS;
}
| 46.621622 | 131 | 0.69971 | jimlyall-q |
d4a81fdf75a61d38c73dcd454e601354f1b4ac0e | 461 | cpp | C++ | sqrt.cpp | LiFengcheng01/CPP-Homework | 192766b689996b166a394ceb4e9b256fa39e54e0 | [
"Apache-2.0"
] | 1 | 2018-10-12T05:00:45.000Z | 2018-10-12T05:00:45.000Z | sqrt.cpp | LiFengcheng01/CPP-Homework | 192766b689996b166a394ceb4e9b256fa39e54e0 | [
"Apache-2.0"
] | null | null | null | sqrt.cpp | LiFengcheng01/CPP-Homework | 192766b689996b166a394ceb4e9b256fa39e54e0 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <cmath>
using namespace std;
int int_sqrt(int x);
int Mypow(int di,int mi);
int main()
{
int i;
for(i=0;i<=100;i++)
cout<<i<<" "<<int_sqrt(i)<<endl;
system("pause");
return 0;
}
int int_sqrt(int x)
{
int i;
for(i=0;;i++)
{
if(x>=Mypow(i,2)&&x<Mypow(i+1,2))
break;
}
return i;
}
int Mypow(int di,int mi)
{
int i,tmp=1;
for(i=0;i<mi;i++)
tmp*=di;
return tmp;
}
| 14.40625 | 39 | 0.518438 | LiFengcheng01 |
d4aa0ce1738e379af3688b811645da90f4788173 | 12,682 | hpp | C++ | sdk/core/azure-core/inc/azure/core/http/http.hpp | ahsonkhan/azure-sdk-for-cpp | ae612c5db562bb2176bdbc3cc1550a2ed835d553 | [
"MIT"
] | null | null | null | sdk/core/azure-core/inc/azure/core/http/http.hpp | ahsonkhan/azure-sdk-for-cpp | ae612c5db562bb2176bdbc3cc1550a2ed835d553 | [
"MIT"
] | null | null | null | sdk/core/azure-core/inc/azure/core/http/http.hpp | ahsonkhan/azure-sdk-for-cpp | ae612c5db562bb2176bdbc3cc1550a2ed835d553 | [
"MIT"
] | null | null | null | // Copyright (c) Microsoft Corporation. All rights reserved.
// SPDX-License-Identifier: MIT
/**
* @file
* @brief HTTP request and response functionality.
*/
#pragma once
#include "azure/core/case_insensitive_containers.hpp"
#include "azure/core/dll_import_export.hpp"
#include "azure/core/exception.hpp"
#include "azure/core/http/http_status_code.hpp"
#include "azure/core/http/raw_response.hpp"
#include "azure/core/internal/contract.hpp"
#include "azure/core/io/body_stream.hpp"
#include "azure/core/nullable.hpp"
#include "azure/core/url.hpp"
#include <algorithm>
#include <cstdint>
#include <functional>
#include <map>
#include <memory>
#include <stdexcept>
#include <string>
#include <unordered_set>
#include <vector>
#if defined(TESTING_BUILD)
// Define the class used from tests to validate retry enabled
namespace Azure { namespace Core { namespace Test {
class TestHttp_getters_Test;
class TestHttp_query_parameter_Test;
class TestHttp_RequestStartTry_Test;
class TestURL_getters_Test;
class TestURL_query_parameter_Test;
class TransportAdapter_headWithStream_Test;
class TransportAdapter_putWithStream_Test;
class TransportAdapter_deleteRequestWithStream_Test;
class TransportAdapter_patchWithStream_Test;
class TransportAdapter_putWithStreamOnFail_Test;
class TransportAdapter_SizePutFromFile_Test;
class TransportAdapter_SizePutFromFileDefault_Test;
class TransportAdapter_SizePutFromFileBiggerPage_Test;
}}} // namespace Azure::Core::Test
#endif
namespace Azure { namespace Core { namespace Http {
/********************* Exceptions **********************/
/**
* @brief An error while sending the HTTP request with the transport adapter.
*/
class TransportException final : public Azure::Core::RequestFailedException {
public:
/**
* @brief Constructs `%TransportException` with a \p message string.
*
* @remark The transport policy will throw this error whenever the transport adapter fail to
* perform a request.
*
* @param whatArg The explanatory string.
*/
explicit TransportException(std::string const& whatArg)
: Azure::Core::RequestFailedException(whatArg)
{
}
};
/**
* @brief The range of bytes within an HTTP resource.
*
* @note Starts at an `Offset` and ends at `Offset + Length - 1` inclusively.
*/
struct HttpRange final
{
/**
* @brief The starting point of the HTTP Range.
*
*/
int64_t Offset = 0;
/**
* @brief The size of the HTTP Range.
*
*/
Azure::Nullable<int64_t> Length;
};
/**
* @brief The method to be performed on the resource identified by the Request.
*/
class HttpMethod final {
public:
/**
* @brief Constructs `%HttpMethod` from string.
*
* @note Won't check if \p value is a known HttpMethod defined as per any RFC.
*
* @param value A given string to represent the `%HttpMethod`.
*/
explicit HttpMethod(std::string value) : m_value(std::move(value)) {}
/**
* @brief Compares two instances of `%HttpMethod` for equality.
*
* @param other Some `%HttpMethod` instance to compare with.
* @return `true` if instances are equal; otherwise, `false`.
*/
bool operator==(const HttpMethod& other) const { return m_value == other.m_value; }
/**
* @brief Compares two instances of `%HttpMethod` for equality.
*
* @param other Some `%HttpMethod` instance to compare with.
* @return `false` if instances are equal; otherwise, `true`.
*/
bool operator!=(const HttpMethod& other) const { return !(*this == other); }
/**
* @brief Returns the `%HttpMethod` represented as a string.
*/
const std::string& ToString() const { return m_value; }
/**
* @brief The representation of a `GET` HTTP method based on [RFC 7231]
* (https://datatracker.ietf.org/doc/html/rfc7231#section-4.3.1).
*/
AZ_CORE_DLLEXPORT const static HttpMethod Get;
/**
* @brief The representation of a `HEAD` HTTP method based on [RFC 7231]
* (https://datatracker.ietf.org/doc/html/rfc7231#section-4.3.2).
*/
AZ_CORE_DLLEXPORT const static HttpMethod Head;
/**
* @brief The representation of a `POST` HTTP method based on [RFC 7231]
* (https://datatracker.ietf.org/doc/html/rfc7231#section-4.3.3).
*/
AZ_CORE_DLLEXPORT const static HttpMethod Post;
/**
* @brief The representation of a `PUT` HTTP method based on [RFC 7231]
* (https://datatracker.ietf.org/doc/html/rfc7231#section-4.3.4).
*/
AZ_CORE_DLLEXPORT const static HttpMethod Put;
/**
* @brief The representation of a `DELETE` HTTP method based on [RFC 7231]
* (https://datatracker.ietf.org/doc/html/rfc7231#section-4.3.5).
*/
AZ_CORE_DLLEXPORT const static HttpMethod Delete;
/**
* @brief The representation of a `PATCH` HTTP method based on [RFC 5789]
* (https://datatracker.ietf.org/doc/html/rfc5789).
*/
AZ_CORE_DLLEXPORT const static HttpMethod Patch;
private:
std::string m_value;
}; // extensible enum HttpMethod
namespace Policies { namespace _internal {
class RetryPolicy;
}} // namespace Policies::_internal
/**
* @brief A request message from a client to a server.
*
* @details Includes, within the first line of the message, the HttpMethod to be applied to the
* resource, the URL of the resource, and the protocol version in use.
*/
class Request final {
friend class Azure::Core::Http::Policies::_internal::RetryPolicy;
#if defined(TESTING_BUILD)
// make tests classes friends to validate set Retry
friend class Azure::Core::Test::TestHttp_getters_Test;
friend class Azure::Core::Test::TestHttp_query_parameter_Test;
friend class Azure::Core::Test::TestHttp_RequestStartTry_Test;
friend class Azure::Core::Test::TestURL_getters_Test;
friend class Azure::Core::Test::TestURL_query_parameter_Test;
// make tests classes friends to validate private Request ctor that takes both stream and bool
friend class Azure::Core::Test::TransportAdapter_headWithStream_Test;
friend class Azure::Core::Test::TransportAdapter_putWithStream_Test;
friend class Azure::Core::Test::TransportAdapter_deleteRequestWithStream_Test;
friend class Azure::Core::Test::TransportAdapter_patchWithStream_Test;
friend class Azure::Core::Test::TransportAdapter_putWithStreamOnFail_Test;
friend class Azure::Core::Test::TransportAdapter_SizePutFromFile_Test;
friend class Azure::Core::Test::TransportAdapter_SizePutFromFileDefault_Test;
friend class Azure::Core::Test::TransportAdapter_SizePutFromFileBiggerPage_Test;
#endif
private:
HttpMethod m_method;
Url m_url;
CaseInsensitiveMap m_headers;
CaseInsensitiveMap m_retryHeaders;
Azure::Core::IO::BodyStream* m_bodyStream;
// flag to know where to insert header
bool m_retryModeEnabled{false};
bool m_shouldBufferResponse{true};
// Expected to be called by a Retry policy to reset all headers set after this function was
// previously called
void StartTry();
/**
* @brief Construct an #Azure::Core::Http::Request.
*
* @param httpMethod HttpMethod.
* @param url %Request URL.
* @param bodyStream #Azure::Core::IO::BodyStream.
* @param shouldBufferResponse A boolean value indicating whether the returned response should
* be buffered or returned as a body stream instead.
*/
explicit Request(
HttpMethod httpMethod,
Url url,
Azure::Core::IO::BodyStream* bodyStream,
bool shouldBufferResponse)
: m_method(std::move(httpMethod)), m_url(std::move(url)), m_bodyStream(bodyStream),
m_retryModeEnabled(false), m_shouldBufferResponse(shouldBufferResponse)
{
AZURE_ASSERT_MSG(bodyStream, "The bodyStream pointer cannot be null.");
}
public:
/**
* @brief Constructs a `%Request`.
*
* @param httpMethod HTTP method.
* @param url %Request URL.
* @param bodyStream #Azure::Core::IO::BodyStream.
*/
explicit Request(HttpMethod httpMethod, Url url, Azure::Core::IO::BodyStream* bodyStream)
: Request(httpMethod, std::move(url), bodyStream, true)
{
}
/**
* @brief Constructs a `%Request`.
*
* @param httpMethod HTTP method.
* @param url %Request URL.
* @param shouldBufferResponse A boolean value indicating whether the returned response should
* be buffered or returned as a body stream instead.
*/
explicit Request(HttpMethod httpMethod, Url url, bool shouldBufferResponse);
/**
* @brief Constructs a `%Request`.
*
* @param httpMethod HTTP method.
* @param url %Request URL.
*/
explicit Request(HttpMethod httpMethod, Url url);
/**
* @brief Set an HTTP header to the #Azure::Core::Http::Request.
*
* @remark If the header key does not exists, it is added.
*
*
* @param name The name for the header to be set or added.
* @param value The value for the header to be set or added.
*
* @throw if \p name is an invalid header key.
*/
void SetHeader(std::string const& name, std::string const& value);
/**
* @brief Remove an HTTP header.
*
* @param name HTTP header name.
*/
void RemoveHeader(std::string const& name);
// Methods used by transport layer (and logger) to send request
/**
* @brief Get HttpMethod.
*
*/
HttpMethod GetMethod() const;
/**
* @brief Get HTTP headers.
*
*/
CaseInsensitiveMap GetHeaders() const;
/**
* @brief Get HTTP body as #Azure::Core::IO::BodyStream.
*
*/
Azure::Core::IO::BodyStream* GetBodyStream() { return this->m_bodyStream; }
/**
* @brief A value indicating whether the returned raw response for this request will be buffered
* within a memory buffer or if it will be returned as a body stream instead.
*/
bool ShouldBufferResponse() { return this->m_shouldBufferResponse; }
/**
* @brief Get URL.
*
*/
Url& GetUrl() { return this->m_url; }
/**
* @brief Get URL.
*
*/
Url const& GetUrl() const { return this->m_url; }
};
namespace _detail {
struct RawResponseHelpers final
{
/**
* @brief Insert a header into \p headers checking that \p headerName does not contain invalid
* characters.
*
* @param headers The headers map where to insert header.
* @param headerName The header name for the header to be inserted.
* @param headerValue The header value for the header to be inserted.
*
* @throw if \p headerName is invalid.
*/
static void InsertHeaderWithValidation(
CaseInsensitiveMap& headers,
std::string const& headerName,
std::string const& headerValue);
static void inline SetHeader(
Azure::Core::Http::RawResponse& response,
uint8_t const* const first,
uint8_t const* const last)
{
// get name and value from header
auto start = first;
auto end = std::find(start, last, ':');
if (end == last)
{
throw std::invalid_argument("Invalid header. No delimiter ':' found.");
}
// Always toLower() headers
auto headerName
= Azure::Core::_internal::StringExtensions::ToLower(std::string(start, end));
start = end + 1; // start value
while (start < last && (*start == ' ' || *start == '\t'))
{
++start;
}
end = std::find(start, last, '\r');
auto headerValue = std::string(start, end); // remove \r
response.SetHeader(headerName, headerValue);
}
};
} // namespace _detail
namespace _internal {
struct HttpShared final
{
AZ_CORE_DLLEXPORT static char const ContentType[];
AZ_CORE_DLLEXPORT static char const ApplicationJson[];
AZ_CORE_DLLEXPORT static char const Accept[];
AZ_CORE_DLLEXPORT static char const MsRequestId[];
AZ_CORE_DLLEXPORT static char const MsClientRequestId[];
static inline std::string GetHeaderOrEmptyString(
Azure::Core::CaseInsensitiveMap const& headers,
std::string const& headerName)
{
auto header = headers.find(headerName);
if (header != headers.end())
{
return header->second; // second is the header value.
}
return {}; // empty string
}
};
} // namespace _internal
}}} // namespace Azure::Core::Http
| 32.025253 | 100 | 0.6607 | ahsonkhan |
d4b604ba4e9830111aac0f0aa9f91986efd8a541 | 2,005 | cpp | C++ | AtCoder/E_CoinsRespawn.cpp | davimedio01/competitive-programming | e2a90f0183c11a90a50738a9a690efe03773d43f | [
"MIT"
] | 2 | 2020-09-10T15:48:02.000Z | 2020-09-12T00:05:35.000Z | AtCoder/E_CoinsRespawn.cpp | davimedio01/competitive-programming | e2a90f0183c11a90a50738a9a690efe03773d43f | [
"MIT"
] | null | null | null | AtCoder/E_CoinsRespawn.cpp | davimedio01/competitive-programming | e2a90f0183c11a90a50738a9a690efe03773d43f | [
"MIT"
] | 2 | 2020-09-09T17:01:05.000Z | 2020-09-09T17:02:27.000Z | #include <bits/stdc++.h>
using namespace std;
int N, M, P;
vector<tuple<int, int, long long>> grafo;
long long resp;
void BellmanFord(int inicio)
{
vector<long long> distancia(N + 1, LONG_LONG_MAX);
distancia[inicio] = 0;
//Verifica o looping negativo (não há máximo)
vector<bool> verifica(N + 1, false);
verifica[N] = true;
int primeiro, segundo;
long long moedas;
//Verifica o máximo possível, exceto os casos de looping negativo
for (int i = 1; i < N; i++)
{
for (int j = 0; j < M; j++)
{
tie(primeiro, segundo, moedas) = grafo[j];
if (distancia[primeiro] != LONG_LONG_MAX &&
distancia[primeiro] + moedas < distancia[segundo])
{
distancia[segundo] = distancia[primeiro] + moedas;
}
//Salvando o vértice percorrido
if(verifica[segundo] == true)
{
verifica[primeiro] = true;
}
}
}
//Salvando a resposta máxima atual
resp = max((long long)0, -distancia[N]);
//Percorrendo o grafo e verificando se há o looping negativo
for(int i = 0; i < M; i++)
{
tie(primeiro, segundo, moedas) = grafo[i];
if (distancia[primeiro] != LONG_LONG_MAX &&
distancia[primeiro] + moedas < distancia[segundo] &&
verifica[segundo] == true)
{
//Looping negativo = impossível
resp = -1;
break;
}
}
}
int main()
{
cin >> N >> M >> P;
for (int i = 0; i < M; i++)
{
int primeiro, segundo;
long long moedas;
cin >> primeiro >> segundo >> moedas;
grafo.push_back({primeiro, segundo, P - moedas});
}
BellmanFord(1);
cout << resp << endl;
return 0;
} | 25.0625 | 71 | 0.4798 | davimedio01 |
d4b7acfb32f080d3f7986adf3300da9d34419eb3 | 12,490 | cpp | C++ | Backends/Graphics4/OpenGL/Sources/Kore/RenderTargetImpl.cpp | varomix/Kore | fca273e3d865898e87bebd9ee58b13635bcdfd5c | [
"Zlib"
] | null | null | null | Backends/Graphics4/OpenGL/Sources/Kore/RenderTargetImpl.cpp | varomix/Kore | fca273e3d865898e87bebd9ee58b13635bcdfd5c | [
"Zlib"
] | null | null | null | Backends/Graphics4/OpenGL/Sources/Kore/RenderTargetImpl.cpp | varomix/Kore | fca273e3d865898e87bebd9ee58b13635bcdfd5c | [
"Zlib"
] | null | null | null | #include "pch.h"
#include "RenderTargetImpl.h"
#include "ogl.h"
#include <Kore/Graphics4/Graphics.h>
#include <Kore/Log.h>
#include <Kore/System.h>
#ifdef KORE_ANDROID
#include <GLContext.h>
#endif
using namespace Kore;
#ifndef GL_RGBA16F_EXT
#define GL_RGBA16F_EXT 0x881A
#endif
#ifndef GL_RGBA32F_EXT
#define GL_RGBA32F_EXT 0x8814
#endif
#ifndef GL_R16F_EXT
#define GL_R16F_EXT 0x822D
#endif
#ifndef GL_R32F_EXT
#define GL_R32F_EXT 0x822E
#endif
#ifndef GL_HALF_FLOAT
#define GL_HALF_FLOAT 0x140B
#endif
#ifndef GL_RED
#define GL_RED GL_LUMINANCE
#endif
namespace {
int pow(int pow) {
int ret = 1;
for (int i = 0; i < pow; ++i) ret *= 2;
return ret;
}
int getPower2(int i) {
for (int power = 0;; ++power)
if (pow(power) >= i) return pow(power);
}
bool nonPow2RenderTargetsSupported() {
#ifdef KORE_OPENGL_ES
#ifdef KORE_ANDROID
if (ndk_helper::GLContext::GetInstance()->GetGLVersion() >= 3.0)
return true;
else
return false;
#else
return true;
#endif
#else
return true;
#endif
}
}
void RenderTargetImpl::setupDepthStencil(GLenum texType, int depthBufferBits, int stencilBufferBits, int width, int height) {
if (depthBufferBits > 0 && stencilBufferBits > 0) {
_hasDepth = true;
#if defined(KORE_OPENGL_ES) && !defined(KORE_PI) && !defined(KORE_HTML5)
GLenum internalFormat = GL_DEPTH24_STENCIL8_OES;
#elif defined(KORE_OPENGL_ES)
GLenum internalFormat = NULL;
#else
GLenum internalFormat;
if (depthBufferBits == 24)
internalFormat = GL_DEPTH24_STENCIL8;
else
internalFormat = GL_DEPTH32F_STENCIL8;
#endif
// Renderbuffer
// glGenRenderbuffers(1, &_depthRenderbuffer);
// glCheckErrors();
// glBindRenderbuffer(GL_RENDERBUFFER, _depthRenderbuffer);
// glCheckErrors();
// glRenderbufferStorage(GL_RENDERBUFFER, internalFormat, width, height);
// glCheckErrors();
// #ifdef KORE_OPENGL_ES
// glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _depthRenderbuffer);
// glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, _depthRenderbuffer);
// #else
// glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, _depthRenderbuffer);
// #endif
// glCheckErrors();
// Texture
glGenTextures(1, &_depthTexture);
glCheckErrors();
glBindTexture(texType, _depthTexture);
glCheckErrors();
glTexImage2D(texType, 0, internalFormat, width, height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, 0);
glCheckErrors();
glTexParameteri(texType, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(texType, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(texType, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(texType, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glCheckErrors();
glBindFramebuffer(GL_FRAMEBUFFER, _framebuffer);
glCheckErrors();
#ifdef KORE_OPENGL_ES
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, texType, _depthTexture, 0);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, texType, _depthTexture, 0);
#else
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, texType, _depthTexture, 0);
#endif
glCheckErrors();
}
else if (depthBufferBits > 0) {
_hasDepth = true;
// Renderbuffer
// glGenRenderbuffers(1, &_depthRenderbuffer);
// glCheckErrors();
// glBindRenderbuffer(GL_RENDERBUFFER, _depthRenderbuffer);
// glCheckErrors();
// glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, width, height);
// glCheckErrors();
// glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _depthRenderbuffer);
// glCheckErrors();
// Texture
glGenTextures(1, &_depthTexture);
glCheckErrors();
glBindTexture(texType, _depthTexture);
glCheckErrors();
GLint format = depthBufferBits == 16 ? GL_DEPTH_COMPONENT16 : GL_DEPTH_COMPONENT;
glTexImage2D(texType, 0, format, width, height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, 0);
glCheckErrors();
glTexParameteri(texType, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(texType, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(texType, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(texType, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glCheckErrors();
glBindFramebuffer(GL_FRAMEBUFFER, _framebuffer);
glCheckErrors();
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, texType, _depthTexture, 0);
glCheckErrors();
}
}
Graphics4::RenderTarget::RenderTarget(int width, int height, int depthBufferBits, bool antialiasing, RenderTargetFormat format, int stencilBufferBits,
int contextId)
: width(width), height(height), isCubeMap(false), isDepthAttachment(false) {
_hasDepth = false;
if (nonPow2RenderTargetsSupported()) {
texWidth = width;
texHeight = height;
}
else {
texWidth = getPower2(width);
texHeight = getPower2(height);
}
this->format = (int)format;
this->contextId = contextId;
// (DK) required on windows/gl
Kore::System::makeCurrent(contextId);
glGenTextures(1, &_texture);
glCheckErrors();
glBindTexture(GL_TEXTURE_2D, _texture);
glCheckErrors();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glCheckErrors();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glCheckErrors();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glCheckErrors();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glCheckErrors();
switch (format) {
case Target128BitFloat:
#ifdef KORE_OPENGL_ES
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F_EXT, texWidth, texHeight, 0, GL_RGBA, GL_FLOAT, 0);
#else
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, texWidth, texHeight, 0, GL_RGBA, GL_FLOAT, 0);
#endif
break;
case Target64BitFloat:
#ifdef KORE_OPENGL_ES
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_EXT, texWidth, texHeight, 0, GL_RGBA, GL_HALF_FLOAT, 0);
#else
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, texWidth, texHeight, 0, GL_RGBA, GL_HALF_FLOAT, 0);
#endif
break;
case Target16BitDepth:
#ifdef KORE_OPENGL_ES
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
#endif
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, texWidth, texHeight, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, 0);
break;
case Target8BitRed:
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, texWidth, texHeight, 0, GL_RED, GL_UNSIGNED_BYTE, 0);
break;
case Target16BitRedFloat:
glTexImage2D(GL_TEXTURE_2D, 0, GL_R16F_EXT, texWidth, texHeight, 0, GL_RED, GL_HALF_FLOAT, 0);
break;
case Target32BitRedFloat:
glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F_EXT, texWidth, texHeight, 0, GL_RED, GL_FLOAT, 0);
break;
case Target32Bit:
default:
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texWidth, texHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
}
glCheckErrors();
glGenFramebuffers(1, &_framebuffer);
glCheckErrors();
glBindFramebuffer(GL_FRAMEBUFFER, _framebuffer);
glCheckErrors();
setupDepthStencil(GL_TEXTURE_2D, depthBufferBits, stencilBufferBits, texWidth, texHeight);
if (format == Target16BitDepth) {
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, _texture, 0);
#ifndef KORE_OPENGL_ES
glDrawBuffer(GL_NONE);
glReadBuffer(GL_NONE);
#endif
}
else {
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _texture, 0);
}
glCheckErrors();
// GLenum drawBuffers[1] = { GL_COLOR_ATTACHMENT0 };
// glDrawBuffers(1, drawBuffers);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glCheckErrors();
glBindTexture(GL_TEXTURE_2D, 0);
glCheckErrors();
}
Graphics4::RenderTarget::RenderTarget(int cubeMapSize, int depthBufferBits, bool antialiasing, RenderTargetFormat format, int stencilBufferBits, int contextId)
: width(cubeMapSize), height(cubeMapSize), isCubeMap(true), isDepthAttachment(false) {
_hasDepth = false;
if (nonPow2RenderTargetsSupported()) {
texWidth = width;
texHeight = height;
}
else {
texWidth = getPower2(width);
texHeight = getPower2(height);
}
this->format = (int)format;
this->contextId = contextId;
// (DK) required on windows/gl
Kore::System::makeCurrent(contextId);
glGenTextures(1, &_texture);
glCheckErrors();
glBindTexture(GL_TEXTURE_CUBE_MAP, _texture);
glCheckErrors();
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glCheckErrors();
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glCheckErrors();
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glCheckErrors();
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glCheckErrors();
switch (format) {
case Target128BitFloat:
#ifdef KORE_OPENGL_ES
for (int i = 0; i < 6; i++) glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGBA32F_EXT, texWidth, texHeight, 0, GL_RGBA, GL_FLOAT, 0);
#else
for (int i = 0; i < 6; i++) glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGBA32F, texWidth, texHeight, 0, GL_RGBA, GL_FLOAT, 0);
#endif
break;
case Target64BitFloat:
#ifdef KORE_OPENGL_ES
for (int i = 0; i < 6; i++) glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGBA16F_EXT, texWidth, texHeight, 0, GL_RGBA, GL_HALF_FLOAT, 0);
#else
for (int i = 0; i < 6; i++) glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGBA16F, texWidth, texHeight, 0, GL_RGBA, GL_HALF_FLOAT, 0);
#endif
break;
case Target16BitDepth:
#ifdef KORE_OPENGL_ES
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
#endif
for (int i = 0; i < 6; i++)
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_DEPTH_COMPONENT16, texWidth, texHeight, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, 0);
break;
case Target32Bit:
default:
for (int i = 0; i < 6; i++) glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGBA, texWidth, texHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
}
glCheckErrors();
glGenFramebuffers(1, &_framebuffer);
glCheckErrors();
glBindFramebuffer(GL_FRAMEBUFFER, _framebuffer);
glCheckErrors();
setupDepthStencil(GL_TEXTURE_CUBE_MAP, depthBufferBits, stencilBufferBits, texWidth, texHeight);
if (format == Target16BitDepth) {
isDepthAttachment = true;
#ifndef KORE_OPENGL_ES
glDrawBuffer(GL_NONE);
glCheckErrors();
glReadBuffer(GL_NONE);
glCheckErrors();
#endif
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glCheckErrors();
glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
glCheckErrors();
}
Graphics4::RenderTarget::~RenderTarget() {
{
GLuint textures[] = {_texture};
glDeleteTextures(1, textures);
}
if (_hasDepth) {
GLuint textures[] = {_depthTexture};
glDeleteTextures(1, textures);
}
GLuint framebuffers[] = {_framebuffer};
glDeleteFramebuffers(1, framebuffers);
}
void Graphics4::RenderTarget::useColorAsTexture(TextureUnit unit) {
glActiveTexture(GL_TEXTURE0 + unit.unit);
glCheckErrors();
glBindTexture(isCubeMap ? GL_TEXTURE_CUBE_MAP : GL_TEXTURE_2D, _texture);
glCheckErrors();
}
void Graphics4::RenderTarget::useDepthAsTexture(TextureUnit unit) {
glActiveTexture(GL_TEXTURE0 + unit.unit);
glCheckErrors();
glBindTexture(isCubeMap ? GL_TEXTURE_CUBE_MAP : GL_TEXTURE_2D, _depthTexture);
glCheckErrors();
}
void Graphics4::RenderTarget::setDepthStencilFrom(RenderTarget* source) {
glBindFramebuffer(GL_FRAMEBUFFER, _framebuffer);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, isCubeMap ? GL_TEXTURE_CUBE_MAP : GL_TEXTURE_2D, source->_depthTexture, 0);
}
void Graphics4::RenderTarget::getPixels(u8* data) {
glBindFramebuffer(GL_FRAMEBUFFER, _framebuffer);
switch ((RenderTargetFormat)format) {
case Target128BitFloat:
glReadPixels(0, 0, texWidth, texHeight, GL_RGBA, GL_FLOAT, data);
break;
case Target64BitFloat:
glReadPixels(0, 0, texWidth, texHeight, GL_RGBA, GL_HALF_FLOAT, data);
break;
case Target8BitRed:
glReadPixels(0, 0, texWidth, texHeight, GL_RED, GL_UNSIGNED_BYTE, data);
break;
case Target16BitRedFloat:
glReadPixels(0, 0, texWidth, texHeight, GL_RED, GL_HALF_FLOAT, data);
break;
case Target32BitRedFloat:
glReadPixels(0, 0, texWidth, texHeight, GL_RED, GL_FLOAT, data);
break;
case Target32Bit:
default:
glReadPixels(0, 0, texWidth, texHeight, GL_RGBA, GL_UNSIGNED_BYTE, data);
}
}
void Graphics4::RenderTarget::generateMipmaps(int levels) {
glBindTexture(GL_TEXTURE_2D, _texture);
glCheckErrors();
glGenerateMipmap(GL_TEXTURE_2D);
glCheckErrors();
}
| 31.700508 | 159 | 0.766453 | varomix |
d4b9a9a7f341c505aef9f2b9e908a91ef4a6d1b8 | 473 | cpp | C++ | firmware/examples/Delay/source/main.cpp | znic1967/Khalils-Kids | 4e8d744837c1ba63adf3ec3ec317a40860b463aa | [
"Apache-2.0"
] | null | null | null | firmware/examples/Delay/source/main.cpp | znic1967/Khalils-Kids | 4e8d744837c1ba63adf3ec3ec317a40860b463aa | [
"Apache-2.0"
] | null | null | null | firmware/examples/Delay/source/main.cpp | znic1967/Khalils-Kids | 4e8d744837c1ba63adf3ec3ec317a40860b463aa | [
"Apache-2.0"
] | null | null | null | #include <inttypes.h>
#include <cstdint>
#include "utility/log.hpp"
#include "utility/time.hpp"
int main(void)
{
LOG_INFO("Delay Application Starting...");
LOG_INFO(
"This example merely prints a statement every second using the delay "
"function.");
uint32_t counter = 0;
while (true)
{
LOG_INFO("[%lu] Hello, World! (milliseconds = %lu)", counter++,
static_cast<uint32_t>(Milliseconds()));
Delay(1000);
}
return 0;
}
| 19.708333 | 76 | 0.634249 | znic1967 |
d4cb4d5e46c607312b1d1c274f5280a31eb5ad58 | 2,145 | hpp | C++ | tiffconvert/Font.hpp | Imagine-Programming/tiffconvert | 1eba05f3f876ac669d28ab9309326376bef61ef1 | [
"MIT"
] | null | null | null | tiffconvert/Font.hpp | Imagine-Programming/tiffconvert | 1eba05f3f876ac669d28ab9309326376bef61ef1 | [
"MIT"
] | 3 | 2021-02-15T08:10:59.000Z | 2021-03-13T10:52:47.000Z | tiffconvert/Font.hpp | Imagine-Programming/tiffconvert | 1eba05f3f876ac669d28ab9309326376bef61ef1 | [
"MIT"
] | null | null | null | #pragma once
#ifndef libtiffconvert_font_h
#define libtiffconvert_font_h
#include "libtiffconvert.h"
#include <string>
#include <cstdint>
#include <Windows.h>
namespace TiffConvert {
/// <summary>
/// Flags that specify how a font should be loaded.
/// </summary>
enum FontConfig : uint32_t {
FONT_BOLD = (1 << 0),
FONT_ITALIC = (1 << 1),
FONT_UNDERLINE = (1 << 2),
FONT_STRIKEOUT = (1 << 3),
FONT_ANTIALIAS = (1 << 4)
};
/// <summary>
/// Font describes a font that is loaded through libtiffconvert.
/// </summary>
class Font {
private:
const font_handle* m_Font = nullptr;
public:
/// <summary>
/// Convert a LOGFONTA descriptor to usable flags.
/// </summary>
/// <param name="descriptor">The LOGFONTA instance.</param>
/// <param name="hq">Whether or not anti-aliasing should be applied to the font.</param>
/// <returns>Combined flags.</returns>
static uint32_t FlagsFromLogFont(const LOGFONTA& descriptor, bool hq = true);
/// <summary>
/// Construct a new font by name, height and flags.
/// </summary>
/// <param name="name">Font family name.</param>
/// <param name="height">Font height, in points.</param>
/// <param name="flags">Font style flags.</param>
Font(const std::string& name, uint32_t height, uint32_t flags = 0);
/// <summary>
/// Construct a new font by name, height and flags.
/// </summary>
/// <param name="name">Font family name.</param>
/// <param name="height">Font height, in points.</param>
/// <param name="flags">Font style flags.</param>
Font(const std::wstring& name, uint32_t height, uint32_t flags = 0);
/// <summary>
/// Construct a new font from LOGFONTA descriptor.
/// </summary>
/// <param name="descriptor">The LOGFONTA instance.</param>
Font(const LOGFONTA& descriptor);
/// <summary>
/// The destructor frees the internal font.
/// </summary>
~Font();
/// <summary>
/// Get a const pointer to the internal font object.
/// </summary>
/// <returns>A const pointer to the internal font object.</returns>
const font_handle* get() const noexcept;
};
}
#endif | 28.986486 | 91 | 0.644755 | Imagine-Programming |
d4cec0522b84a09c904aa4bb7f30637fcf727dac | 3,702 | cpp | C++ | libs/multi_array/test/storage_order.cpp | zyiacas/boost-doc-zh | 689e5a3a0a4dbead1a960f7b039e3decda54aa2c | [
"BSL-1.0"
] | 198 | 2015-01-13T05:47:18.000Z | 2022-03-09T04:46:46.000Z | libs/multi_array/test/storage_order.cpp | sdfict/boost-doc-zh | 689e5a3a0a4dbead1a960f7b039e3decda54aa2c | [
"BSL-1.0"
] | 9 | 2015-01-28T16:33:19.000Z | 2020-04-12T23:03:28.000Z | libs/multi_array/test/storage_order.cpp | sdfict/boost-doc-zh | 689e5a3a0a4dbead1a960f7b039e3decda54aa2c | [
"BSL-1.0"
] | 139 | 2015-01-15T20:09:31.000Z | 2022-01-31T15:21:16.000Z | // Copyright 2002 The Trustees of Indiana University.
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// Boost.MultiArray Library
// Authors: Ronald Garcia
// Jeremy Siek
// Andrew Lumsdaine
// See http://www.boost.org/libs/multi_array for documentation.
//
// storage_order.cpp - testing storage_order-isms.
//
#include "boost/multi_array.hpp"
#include "boost/test/minimal.hpp"
#include "boost/array.hpp"
int
test_main(int,char*[])
{
const int ndims=3;
int data_row[] = {
0,1,2,3,
4,5,6,7,
8,9,10,11,
12,13,14,15,
16,17,18,19,
20,21,22,23
};
int data_col[] = {
0,12,
4,16,
8,20,
1,13,
5,17,
9,21,
2,14,
6,18,
10,22,
3,15,
7,19,
11,23
};
const int num_elements = 24;
// fortran storage order
{
typedef boost::multi_array<int,ndims> array;
array::extent_gen extents;
array A(extents[2][3][4],boost::fortran_storage_order());
A.assign(data_col,data_col+num_elements);
int* num = data_row;
for (array::index i = 0; i != 2; ++i)
for (array::index j = 0; j != 3; ++j)
for (array::index k = 0; k != 4; ++k)
BOOST_CHECK(A[i][j][k] == *num++);
}
// Mimic fortran_storage_order using
// general_storage_order data placement
{
typedef boost::general_storage_order<ndims> storage;
typedef boost::multi_array<int,ndims> array;
array::size_type ordering[] = {0,1,2};
bool ascending[] = {true,true,true};
array::extent_gen extents;
array A(extents[2][3][4], storage(ordering,ascending));
A.assign(data_col,data_col+num_elements);
int* num = data_row;
for (array::index i = 0; i != 2; ++i)
for (array::index j = 0; j != 3; ++j)
for (array::index k = 0; k != 4; ++k)
BOOST_CHECK(A[i][j][k] == *num++);
}
// general_storage_order with arbitrary storage order
{
typedef boost::general_storage_order<ndims> storage;
typedef boost::multi_array<int,ndims> array;
array::size_type ordering[] = {2,0,1};
bool ascending[] = {true,true,true};
array::extent_gen extents;
array A(extents[2][3][4], storage(ordering,ascending));
int data_arb[] = {
0,1,2,3,
12,13,14,15,
4,5,6,7,
16,17,18,19,
8,9,10,11,
20,21,22,23
};
A.assign(data_arb,data_arb+num_elements);
int* num = data_row;
for (array::index i = 0; i != 2; ++i)
for (array::index j = 0; j != 3; ++j)
for (array::index k = 0; k != 4; ++k)
BOOST_CHECK(A[i][j][k] == *num++);
}
// general_storage_order with descending dimensions.
{
const int ndims=3;
typedef boost::general_storage_order<ndims> storage;
typedef boost::multi_array<int,ndims> array;
array::size_type ordering[] = {2,0,1};
bool ascending[] = {false,true,true};
array::extent_gen extents;
array A(extents[2][3][4], storage(ordering,ascending));
int data_arb[] = {
12,13,14,15,
0,1,2,3,
16,17,18,19,
4,5,6,7,
20,21,22,23,
8,9,10,11
};
A.assign(data_arb,data_arb+num_elements);
int* num = data_row;
for (array::index i = 0; i != 2; ++i)
for (array::index j = 0; j != 3; ++j)
for (array::index k = 0; k != 4; ++k)
BOOST_CHECK(A[i][j][k] == *num++);
}
return boost::exit_success;
}
| 23.1375 | 75 | 0.551053 | zyiacas |
d4d6c86fbc8fe8dc720abba88f7ddf72d7917792 | 7,897 | cpp | C++ | all/native/renderers/NMLModelRenderer.cpp | mostafa-j13/mobile-sdk | 60d51e4d37c7fb9558b1310345083c7f7d6b79e7 | [
"BSD-3-Clause"
] | null | null | null | all/native/renderers/NMLModelRenderer.cpp | mostafa-j13/mobile-sdk | 60d51e4d37c7fb9558b1310345083c7f7d6b79e7 | [
"BSD-3-Clause"
] | null | null | null | all/native/renderers/NMLModelRenderer.cpp | mostafa-j13/mobile-sdk | 60d51e4d37c7fb9558b1310345083c7f7d6b79e7 | [
"BSD-3-Clause"
] | null | null | null | #include "NMLModelRenderer.h"
#include "components/ThreadWorker.h"
#include "datasources/VectorDataSource.h"
#include "graphics/Shader.h"
#include "graphics/ShaderManager.h"
#include "graphics/ViewState.h"
#include "graphics/utils/GLContext.h"
#include "layers/VectorLayer.h"
#include "projections/Projection.h"
#include "renderers/MapRenderer.h"
#include "renderers/components/RayIntersectedElement.h"
#include "utils/Log.h"
#include <nml/GLModel.h>
#include <nml/GLTexture.h>
#include <nml/GLResourceManager.h>
namespace {
struct GLResourceDeleter : carto::ThreadWorker {
GLResourceDeleter(std::shared_ptr<carto::nml::GLResourceManager> glResourceManager) : _glResourceManager(std::move(glResourceManager)) { }
virtual void operator () () {
_glResourceManager->deleteAll();
}
private:
std::shared_ptr<carto::nml::GLResourceManager> _glResourceManager;
};
}
namespace carto {
NMLModelRenderer::NMLModelRenderer() :
_glResourceManager(),
_glModelMap(),
_elements(),
_tempElements(),
_mapRenderer(),
_options(),
_mutex()
{
}
NMLModelRenderer::~NMLModelRenderer() {
if (_glResourceManager) {
if (auto mapRenderer = _mapRenderer.lock()) {
mapRenderer->addRenderThreadCallback(std::make_shared<GLResourceDeleter>(_glResourceManager));
}
}
}
void NMLModelRenderer::addElement(const std::shared_ptr<NMLModel>& element) {
_tempElements.push_back(element);
}
void NMLModelRenderer::refreshElements() {
std::lock_guard<std::mutex> lock(_mutex);
_elements.clear();
_elements.swap(_tempElements);
}
void NMLModelRenderer::updateElement(const std::shared_ptr<NMLModel>& element) {
std::lock_guard<std::mutex> lock(_mutex);
if (std::find(_elements.begin(), _elements.end(), element) == _elements.end()) {
_elements.push_back(element);
}
}
void NMLModelRenderer::removeElement(const std::shared_ptr<NMLModel>& element) {
std::lock_guard<std::mutex> lock(_mutex);
_elements.erase(std::remove(_elements.begin(), _elements.end(), element), _elements.end());
}
void NMLModelRenderer::setMapRenderer(const std::weak_ptr<MapRenderer>& mapRenderer) {
std::lock_guard<std::mutex> lock(_mutex);
_mapRenderer = mapRenderer;
}
void NMLModelRenderer::setOptions(const std::weak_ptr<Options>& options) {
std::lock_guard<std::mutex> lock(_mutex);
_options = options;
}
void NMLModelRenderer::offsetLayerHorizontally(double offset) {
std::lock_guard<std::mutex> lock(_mutex);
for (const std::shared_ptr<NMLModel>& element : _elements) {
element->getDrawData()->offsetHorizontally(offset);
}
}
void NMLModelRenderer::onSurfaceCreated(const std::shared_ptr<ShaderManager>& shaderManager, const std::shared_ptr<TextureManager>& textureManager) {
_glResourceManager = std::make_shared<nml::GLResourceManager>();
_glModelMap.clear();
nml::GLTexture::registerGLExtensions();
}
bool NMLModelRenderer::onDrawFrame(float deltaSeconds, const ViewState& viewState) {
std::lock_guard<std::mutex> lock(_mutex);
std::shared_ptr<Options> options = _options.lock();
if (!options) {
return false;
}
// Set expected GL state
glDepthMask(GL_TRUE);
glEnable(GL_DEPTH_TEST);
// Calculate lighting state
Color ambientColor = options->getAmbientLightColor();
cglib::vec4<float> ambientLightColor = cglib::vec4<float>(ambientColor.getR(), ambientColor.getG(), ambientColor.getB(), ambientColor.getA()) * (1.0f / 255.0f);
Color mainColor = options->getMainLightColor();
cglib::vec4<float> mainLightColor = cglib::vec4<float>(mainColor.getR(), mainColor.getG(), mainColor.getB(), mainColor.getA()) * (1.0f / 255.0f);
MapVec mainDir = options->getMainLightDirection();
cglib::vec3<float> mainLightDir = cglib::unit(cglib::vec3<float>::convert(cglib::transform_vector(cglib::vec3<double>(mainDir.getX(), mainDir.getY(), mainDir.getZ()), viewState.getModelviewMat())));
// Draw models
cglib::mat4x4<float> projMat = cglib::mat4x4<float>::convert(viewState.getProjectionMat());
for (const std::shared_ptr<NMLModel>& element : _elements) {
const NMLModelDrawData& drawData = *element->getDrawData();
std::shared_ptr<nml::Model> sourceModel = drawData.getSourceModel();
std::shared_ptr<nml::GLModel> glModel = _glModelMap[sourceModel];
if (!glModel) {
glModel = std::make_shared<nml::GLModel>(*sourceModel);
glModel->create(*_glResourceManager);
_glModelMap[sourceModel] = glModel;
}
cglib::mat4x4<float> mvMat = cglib::mat4x4<float>::convert(viewState.getModelviewMat() * drawData.getLocalMat());
nml::RenderState renderState(projMat, mvMat, ambientLightColor, mainLightColor, -mainLightDir);
glModel->draw(*_glResourceManager, renderState);
}
// Remove stale models
for (auto it = _glModelMap.begin(); it != _glModelMap.end(); ) {
if (it->first.expired()) {
it = _glModelMap.erase(it);
} else {
it++;
}
}
// Dispose unused models
_glResourceManager->deleteUnused();
// Restore expected GL state
glDepthMask(GL_TRUE);
glDisable(GL_DEPTH_TEST);
glActiveTexture(GL_TEXTURE0);
GLContext::CheckGLError("NMLModelRenderer::onDrawFrame");
return false;
}
void NMLModelRenderer::onSurfaceDestroyed() {
_glResourceManager.reset();
_glModelMap.clear();
}
void NMLModelRenderer::calculateRayIntersectedElements(const std::shared_ptr<VectorLayer>& layer, const cglib::ray3<double>& ray, const ViewState& viewState, std::vector<RayIntersectedElement>& results) const {
std::lock_guard<std::mutex> lock(_mutex);
for (const std::shared_ptr<NMLModel>& element : _elements) {
const NMLModelDrawData& drawData = *element->getDrawData();
std::shared_ptr<nml::Model> sourceModel = drawData.getSourceModel();
auto modelIt = _glModelMap.find(sourceModel);
if (modelIt == _glModelMap.end()) {
continue;
}
std::shared_ptr<nml::GLModel> glModel = modelIt->second;
cglib::mat4x4<double> modelMat = drawData.getLocalMat();
cglib::mat4x4<double> invModelMat = cglib::inverse(modelMat);
cglib::ray3<double> rayModel = cglib::transform_ray(ray, invModelMat);
cglib::bbox3<double> modelBounds = cglib::bbox3<double>::convert(glModel->getBounds());
if (!cglib::intersect_bbox(modelBounds, rayModel)) {
continue;
}
std::vector<nml::RayIntersection> intersections;
glModel->calculateRayIntersections(rayModel, intersections);
for (std::size_t i = 0; i < intersections.size(); i++) {
cglib::vec3<double> pos = cglib::transform_point(intersections[i].pos, modelMat);
MapPos clickPos(pos(0), pos(1), pos(2));
MapPos projectedClickPos = layer->getDataSource()->getProjection()->fromInternal(clickPos);
int priority = static_cast<int>(results.size());
results.push_back(RayIntersectedElement(std::static_pointer_cast<VectorElement>(element), layer, projectedClickPos, projectedClickPos, priority, true));
}
}
}
}
| 39.288557 | 214 | 0.635431 | mostafa-j13 |
d4d989943cc7f3ea91b3aa28139e790d5e4b652d | 1,219 | hpp | C++ | source/graphs/depth_first_search.hpp | pawel-kieliszczyk/algorithms | 0703ec99ce9fb215709b56fb0eefbdd576c71ed2 | [
"MIT"
] | null | null | null | source/graphs/depth_first_search.hpp | pawel-kieliszczyk/algorithms | 0703ec99ce9fb215709b56fb0eefbdd576c71ed2 | [
"MIT"
] | null | null | null | source/graphs/depth_first_search.hpp | pawel-kieliszczyk/algorithms | 0703ec99ce9fb215709b56fb0eefbdd576c71ed2 | [
"MIT"
] | null | null | null | #ifndef PK_GRAPHS_DEPTHFIRSTSEARCH_HPP
#define PK_GRAPHS_DEPTHFIRSTSEARCH_HPP
#include "stack.hpp"
#include "vector.hpp"
namespace pk
{
namespace graphs
{
class depth_first_search
{
public:
template<
class graph_type,
class visitor_type>
static void run(
const graph_type& g,
const int starting_vertex_id,
visitor_type& visitor)
{
pk::stack<int, graph_type::max_num_of_edges> s;
pk::vector<bool, graph_type::max_num_of_vertices> visited(false, g.get_num_of_vertices());
s.push(starting_vertex_id);
while(!s.empty())
{
const int v = s.top();
s.pop();
if(visited[v])
continue;
visitor.visit(v);
visited[v] = true;
const typename graph_type::adjacency_list& adj_v = g.get_adjacency_list(v);
for(int i = adj_v.size() - 1; i >= 0; --i)
{
const int u = adj_v[i].to;
if(visited[u])
continue;
s.push(u);
}
}
}
};
} // namespace graphs
} // namespace pk
#endif // PK_GRAPHS_DEPTHFIRSTSEARCH_HPP
| 19.66129 | 98 | 0.541427 | pawel-kieliszczyk |
d4d98ae4a5a7b0a378fc0783f1409b9d0246eed3 | 1,547 | hpp | C++ | include/help_line.hpp | matt-harvey/swx | e7b10fe7d4bf0bd6581ceada53ad14b08bc1d852 | [
"Apache-2.0"
] | 7 | 2017-10-08T08:08:25.000Z | 2020-04-27T09:25:00.000Z | include/help_line.hpp | matt-harvey/swx | e7b10fe7d4bf0bd6581ceada53ad14b08bc1d852 | [
"Apache-2.0"
] | null | null | null | include/help_line.hpp | matt-harvey/swx | e7b10fe7d4bf0bd6581ceada53ad14b08bc1d852 | [
"Apache-2.0"
] | 1 | 2020-04-27T09:24:42.000Z | 2020-04-27T09:24:42.000Z | /*
* Copyright 2014 Matthew Harvey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef GUARD_help_line_hpp_07384218837779118
#define GUARD_help_line_hpp_07384218837779118
#include <string>
namespace swx
{
/**
* Represents a line of help information for presentation to user,
* describing a particular string of arguments that might be passed to
* a command or command option, together with a description of how the
* command or option is used in conjunction with that string of arguments.
*/
class HelpLine
{
// special member functions
public:
HelpLine
( std::string const& p_usage_descriptor,
std::string const& p_args_descriptor = std::string()
);
HelpLine(char const* p_usage_descriptor);
// accessors
public:
std::string usage_descriptor() const;
std::string args_descriptor() const;
// data members
private:
std::string m_usage_descriptor;
std::string m_args_descriptor;
}; // class HelpLine
} // namespace swx
#endif // GUARD_help_line_hpp_07384218837779118
| 27.140351 | 75 | 0.740142 | matt-harvey |
d4da5e2271d4defc822bb600d756a6ff27a0535e | 214 | hpp | C++ | include/transactions/entities/BillGates.hpp | perriera/blockchain | 2c89ecc110dcc9c042bdb919c7cf3017a43d4ce8 | [
"MIT"
] | null | null | null | include/transactions/entities/BillGates.hpp | perriera/blockchain | 2c89ecc110dcc9c042bdb919c7cf3017a43d4ce8 | [
"MIT"
] | null | null | null | include/transactions/entities/BillGates.hpp | perriera/blockchain | 2c89ecc110dcc9c042bdb919c7cf3017a43d4ce8 | [
"MIT"
] | null | null | null | #ifndef _BILLGATES_HPP
#define _BILLGATES_HPP
#include <iostream>
#include "../../../extra/include/Definitions.hpp"
#include "../Entity.hpp"
class BillGates extends Entity {
public:
};
#endif // _BILLGATES_HPP
| 15.285714 | 49 | 0.728972 | perriera |
d4dc6e15a639a65d420fa629c3ea962a0daa2b07 | 5,268 | hpp | C++ | src/sdglib/readers/FileReader.hpp | KatOfCats/sdg | 1916e5c86dd88e601ab7476f38daef2bd3b3b6fc | [
"MIT"
] | null | null | null | src/sdglib/readers/FileReader.hpp | KatOfCats/sdg | 1916e5c86dd88e601ab7476f38daef2bd3b3b6fc | [
"MIT"
] | null | null | null | src/sdglib/readers/FileReader.hpp | KatOfCats/sdg | 1916e5c86dd88e601ab7476f38daef2bd3b3b6fc | [
"MIT"
] | null | null | null | //
// Created by Luis Yanes (EI) on 15/09/2017.
//
#ifndef SEQSORTER_FILEREADER_H
#define SEQSORTER_FILEREADER_H
#include <cstring>
#include <fstream>
#include <iostream>
#include <fcntl.h>
#include <sdglib/readers/Common.hpp>
#include <sdglib/utilities/OutputLog.hpp>
#include "kseq.hpp"
struct FastxReaderParams {
uint32_t min_length=0;
};
struct FastaRecord {
int32_t id;
std::string name,seq;
};
template<typename FileRecord>
class FastaReader {
public:
/**
* @brief
* Initialises the FastaReader, opens the file based on the format and instantiates a reader (plain, gzip or bzip2)
* @param params
* Parameters for filtering the records (i.e. min_size, max_size)
* @param filepath
* Relative or absolute path to the file that is going to be read.
*/
explicit FastaReader(FastxReaderParams params, const std::string &filepath) : params(params), numRecords(0) {
sdglib::OutputLog(sdglib::LogLevels::INFO) << "Opening: " << filepath << "\n";
gz_file = gzopen(filepath.c_str(), "r");
if (gz_file == Z_NULL || gz_file == NULL) {
sdglib::OutputLog(sdglib::LogLevels::WARN) << "Error opening FASTA " << filepath << ": " << std::strerror(errno) << std::endl;
throw std::runtime_error("Error opening " + filepath + ": " + std::strerror(errno));
}
ks = new kstream<gzFile, FunctorZlib>(gz_file, gzr);
}
~FastaReader() {
delete ks;
gzclose(gz_file);
}
/**
* @brief
* Calls the file reader and places the fields from the file onto the FileRecord, the ID is set to the
* number of records seen so far.
* @param rec
* Input/Output parameter where the file fields will be stored.
* @return
* Whether the function will generate another object or not
*/
bool next_record(FileRecord& rec) {
int l;
do {
l=(ks -> readFasta(seq));
std::swap(rec.seq, seq.seq);
std::swap(rec.name, seq.name);
rec.id = numRecords;
numRecords++;
stats.totalLength+=rec.seq.size();
} while(rec.seq.size() < params.min_length && l >= 0);
stats.filteredRecords++;
stats.filteredLength+=rec.seq.size();
return (l >= 0);
}
ReaderStats getSummaryStatistics() {
stats.totalRecords = numRecords;
return stats;
}
private:
kstream<gzFile, FunctorZlib> *ks;
kstream<BZFILE, FunctorBZlib2> *bzKS;
kseq seq;
uint32_t numRecords = 0;
gzFile gz_file;
BZFILE * bz_File{};
int fq_File{};
FunctorZlib gzr;
FunctorRead rr;
FastxReaderParams params;
ReaderStats stats;
};
struct FastqRecord{
int64_t id;
std::string name, comment, seq, qual;
};
template<typename FileRecord>
class FastqReader {
public:
/**
* @brief
* Initialises the FastaReader, opens the file based on the format and instantiates a reader (plain, gzip or bzip2)
* @param params
* Parameters for filtering the records (i.e. min_size, max_size)
* @param filepath
* Relative or absolute path to the file that is going to be read.
*/
explicit FastqReader(FastxReaderParams params, const std::string &filepath) : params(params), numRecords(0),eof_flag(false) {
sdglib::OutputLog() << "Opening: " << filepath << "\n";
gz_file = gzopen(filepath.c_str(), "r");
if (gz_file == Z_NULL) {
std::cout << "Error opening FASTQ " << filepath << ": " << std::strerror(errno) << std::endl;
throw std::runtime_error("Error opening " + filepath + ": " + std::strerror(errno));
}
ks = new kstream<gzFile, FunctorZlib>(gz_file, gzr);
}
/**
* @brief
* Calls the file reader and places the fields from the file onto the FileRecord, the ID is set to the
* number of records seen so far.
* @param rec
* Input/Output parameter where the file fields will be stored.
* @return
* Whether the function will generate another object or not
*/
bool next_record(FileRecord& rec) {
int l;
if ( eof_flag) return false;
{
do {
l = (ks->readFastq(seq));
std::swap(rec.seq, seq.seq);
std::swap(rec.qual, seq.qual);
std::swap(rec.name, seq.name);
std::swap(rec.comment, seq.comment);
rec.id = numRecords;
numRecords++;
stats.totalLength += rec.seq.size();
} while (rec.seq.size() < params.min_length && l >= 0);
}
if (l<0) eof_flag=true;
else {
stats.filteredRecords++;
stats.filteredLength += rec.seq.size();
}
return (l >= 0);
}
ReaderStats getSummaryStatistics() {
stats.totalRecords=numRecords;
return stats;
}
~FastqReader() {
gzclose(gz_file);
delete ks;
}
private:
kstream<gzFile, FunctorZlib> *ks;
kseq seq;
uint64_t numRecords=0;
gzFile gz_file;
BZFILE * bz_File{};
int fq_File{};
FunctorZlib gzr;
FastxReaderParams params;
ReaderStats stats;
bool eof_flag;
};
#endif //SEQSORTER_FILEREADER_H
| 29.931818 | 138 | 0.598899 | KatOfCats |
d4e1aecf20faef926ca29686f1962cabc17116de | 5,299 | cpp | C++ | ReferenceDesign/SampleQTHMI/SDLApps/Templates/ChoiceSet/test/ChoiceSetTest.cpp | zenghuan1/HMI_SDK_LIB | d0d03af04abe07f5ca087cabcbb1e4f4858f266a | [
"BSD-3-Clause"
] | 8 | 2019-01-04T10:08:39.000Z | 2021-12-13T16:34:08.000Z | ReferenceDesign/SampleQTHMI/SDLApps/Templates/ChoiceSet/test/ChoiceSetTest.cpp | zenghuan1/HMI_SDK_LIB | d0d03af04abe07f5ca087cabcbb1e4f4858f266a | [
"BSD-3-Clause"
] | 33 | 2017-07-27T09:51:59.000Z | 2018-07-13T09:45:52.000Z | ReferenceDesign/SampleQTHMI/SDLApps/Templates/ChoiceSet/test/ChoiceSetTest.cpp | JH-G/HMI_SDK_LIB | caa4eac66d1f3b76349ef5d6ca5cf7dd69fcd760 | [
"BSD-3-Clause"
] | 12 | 2017-07-28T02:54:53.000Z | 2022-02-20T15:48:24.000Z | #include "ChoiceSetTest.h"
using namespace test;
using namespace hmi_sdk;
using namespace rpc_test;
CChoiceSetTest::CChoiceSetTest()
{
}
void CChoiceSetTest::SetUpTestCase()
{
}
void CChoiceSetTest::TearDownTestCase()
{
}
void CChoiceSetTest::SetUp()
{
}
void CChoiceSetTest::TearDown()
{
}
TEST_F(CChoiceSetTest,OnVRPerformInteraction_Success)
{
AppListMock appListMock;
AppDataMock appDataMock;
appListMock.DelegateGetActiveApp();
EXPECT_CALL(appListMock,getActiveApp()).WillRepeatedly(Return(&appDataMock));
EXPECT_CALL(appDataMock,OnPerformInteraction(PERFORMINTERACTION_TIMEOUT, 0, true));
EXPECT_CALL(appDataMock,OnPerformInteraction(PERFORMINTERACTION_TIMEOUT, 0, false));
CChoiceSet choiceSet(&appListMock);
choiceSet.OnTimeOut();
}
TEST_F(CChoiceSetTest,OnPerformInteraction_Success)
{
AppListMock appListMock;
AppDataMock appDataMock;
appListMock.DelegateGetActiveApp();
EXPECT_CALL(appListMock,getActiveApp()).WillRepeatedly(Return(&appDataMock));
EXPECT_CALL(appDataMock,OnPerformInteraction(PERFORMINTERACTION_TIMEOUT, 0, true));
EXPECT_CALL(appDataMock,OnPerformInteraction(PERFORMINTERACTION_TIMEOUT, 0, false));
CChoiceSet choiceSet(&appListMock);
choiceSet.OnTimeOut();
}
TEST_F(CChoiceSetTest,OnPerformInteraction_OnListItemClicked_Success)
{
AppListMock appListMock;
AppDataMock appDataMock;
appListMock.DelegateGetActiveApp();
EXPECT_CALL(appListMock,getActiveApp()).WillRepeatedly(Return(&appDataMock));
EXPECT_CALL(appDataMock,OnPerformInteraction(PERFORMINTERACTION_CHOICE, 0, _)).Times(AtLeast(1));
CChoiceSet choiceSet(&appListMock);
choiceSet.OnListItemClicked(0);
}
TEST_F(CChoiceSetTest,OnPerformInteraction_OnChoiceVRClicked_Success)
{
AppListMock appListMock;
AppDataMock appDataMock;
appListMock.DelegateGetActiveApp();
EXPECT_CALL(appListMock,getActiveApp()).WillRepeatedly(Return(&appDataMock));
EXPECT_CALL(appDataMock,OnPerformInteraction(PERFORMINTERACTION_TIMEOUT, 0, _)).Times(AtLeast(1));
CChoiceSet choiceSet(&appListMock);
choiceSet.OnChoiceVRClicked();
}
TEST_F(CChoiceSetTest,OnPerformInteraction_OnReturnBtnClicked_Success)
{
AppListMock appListMock;
AppDataMock appDataMock;
appListMock.DelegateGetActiveApp();
EXPECT_CALL(appListMock,getActiveApp()).WillRepeatedly(Return(&appDataMock));
EXPECT_CALL(appDataMock,OnPerformInteraction(RESULT_ABORTED, 0, _)).Times(AtLeast(1));
CChoiceSet choiceSet(&appListMock);
choiceSet.OnReturnBtnClicked();
}
TEST_F(CChoiceSetTest,getInteractionJson_Success)
{
AppListMock appListMock;
UIInterfaceMock uiManagerMock;
Json::Value obj;
Json::Value appList_;
Json::Value eleArr_;
Json::Value element1;
Json::Value element2;
element1["appName"] = "Music1";
element1["appID"] = 3;
element1["icon"] = "";
element2["appName"] = "Music2";
element2["appID"] = 4;
element2["icon"] = "";
eleArr_.append(element1);
eleArr_.append(element2);
appList_["applications"] = eleArr_;
obj["id"] = 64;
obj["jsonrpc"] = "2.0";
obj["method"] = "BasicCommunication.UpdateAppList";
obj["params"] = appList_;
appListMock.DelegateOnRequest(obj);
appListMock.DelegateSetUIManager(&uiManagerMock);
EXPECT_CALL(appListMock,onRequest(obj)).Times(AtLeast(1));
EXPECT_CALL(appListMock,setUIManager(&uiManagerMock));
EXPECT_CALL(uiManagerMock,onAppShow(ID_APPLINK)).Times(AtLeast(1));
appListMock.setUIManager(&uiManagerMock);
appListMock.onRequest(obj);
appListMock.DelegateGetActiveApp();
EXPECT_CALL(appListMock,getActiveApp());
EXPECT_FALSE(appListMock.getActiveApp());
Json::Value appObj;
Json::Value appId;
appObj["method"] = "BasicCommunication.ActivateApp";
appId["appID"] = 3;
appObj["id"] = 64;
appObj["jsonrpc"] = "2.0";
appObj["params"] = appId;
appListMock.DelegateOnRequest(appObj);
EXPECT_CALL(appListMock,onRequest(appObj)).Times(AtLeast(1));
appListMock.onRequest(appObj);
EXPECT_CALL(appListMock,getActiveApp()).Times(AtLeast(1));
EXPECT_TRUE(appListMock.getActiveApp());
Json::Value InteractionObj;
Json::Value choiceSet;
Json::Value params;
Json::Value initialText;
initialText["fieldName"] = "initialInteractionText";
initialText["fieldText"] = "1111111";
for (int i = 0; i< 10;++i)
{
Json::Value choiceSetEle;
choiceSetEle["choiceID"] = i+1;
choiceSetEle["menuName"] = QString(("MenuName" + QString::number(i+1))).toStdString();
choiceSet.append(choiceSetEle);
}
params["appID"] = 3;
params["choiceSet"] = choiceSet;
params["initialText"] = initialText;
InteractionObj["method"] = "UI.PerformInteraction";
InteractionObj["id"] = 127;
InteractionObj["jsonrpc"] = "2.0";
InteractionObj["params"] = params;
appListMock.DelegateOnRequest(InteractionObj);
EXPECT_CALL(appListMock,onRequest(InteractionObj)).Times(AtLeast(1));
appListMock.onRequest(InteractionObj);
EXPECT_EQ(3,appListMock.getActiveApp()->getInteractionJson()["Choiceset"]["params"]["appID"].asInt());
// CChoiceSet* cChoiceSet = new CChoiceSet(&appListMock);
// cChoiceSet->show();
}
| 27.743455 | 106 | 0.727873 | zenghuan1 |
d4e7f73096ec165db0e99002e18f0747627aea84 | 15,597 | cc | C++ | src/driver/tcp/TcpConnection.cc | lsgw/longd | 31caabd42a47c05857ae98716ef877052092aabe | [
"MIT"
] | null | null | null | src/driver/tcp/TcpConnection.cc | lsgw/longd | 31caabd42a47c05857ae98716ef877052092aabe | [
"MIT"
] | null | null | null | src/driver/tcp/TcpConnection.cc | lsgw/longd | 31caabd42a47c05857ae98716ef877052092aabe | [
"MIT"
] | null | null | null | #include "driver.h"
#include "Buffer.h"
#include "sockets.h"
#include "tcp.h"
#include <strings.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
class TcpConnnection : public driver<TcpConnnection> {
public:
void init(PortPtr port, MessagePtr& message) override
{
assert(message->type == MSG_TYPE_TCP);
time_t now = 0;
char timebuf[32];
struct tm tm;
now = time(NULL);
localtime_r(&now, &tm);
// gmtime_r(&now, &tm);
strftime(timebuf, sizeof timebuf, "%Y.%m.%d-%H:%M:%S", &tm);
start_ = timebuf;
state_ = kConnecting;
TcpPacket* packet = static_cast<TcpPacket*>(message->data);
assert(packet->type == TcpPacket::kShift);
assert(packet->shift.fd > 0);
fd_ = packet->shift.fd;
state_ = kConnected;
PortCtl(port, port->id(), 0, port->owner());
// printf("TcpConnnection id=%d init fd = %d\n", port->id(), packet->shift.fd);
}
void release(PortPtr port, MessagePtr& message) override
{
port->channel(fd_)->disableAll()->update();
sockets::close(fd_);
state_ = kDisconnected;
// printf("TcpConnnection id=%d release fd = %d\n", port->id(), fd_);
}
bool receive(PortPtr port, MessagePtr& message) override
{
if (message->type == MSG_TYPE_TCP) {
TcpPacket* packet = static_cast<TcpPacket*>(message->data);
switch (packet->type) {
case TcpPacket::kRead:
return recv(port, message->source, packet->session, packet->read.nbyte);
case TcpPacket::kWrite:
return send(port, packet);
case TcpPacket::kClose:
return close(port, message->source, packet->id);
case TcpPacket::kShutdown:
return shutdown(port, message->source, packet->id);
case TcpPacket::kOpts:
return setopts(port, packet);
case TcpPacket::kLowWaterMark:
return lowWaterMark(port, packet->lowWaterMark.on, packet->lowWaterMark.value);
case TcpPacket::kHighWaterMark:
return highWaterMark(port, packet->highWaterMark.on, packet->highWaterMark.value);
case TcpPacket::kInfo:
return getinfo(port, message->source, packet->session);
default:
return true;
}
} else if (message->type == MSG_TYPE_EVENT) {
Event* event = static_cast<Event*>(message->data);
switch (event->type) {
case Event::kRead:
return handleIoReadEvent(port, event->fd);
case Event::kWrite:
return handleIoWriteEvent(port, event->fd);
case Event::kError:
return true;
default:
return true;
}
} else {
assert(false);
return true;
}
}
bool setopts(PortPtr port, TcpPacket* packet)
{
// printf("port->id() = %d, setopts\n", port->id());
if (packet->opts.optsbits & 0B00000001) {
// printf("port->id() = %d, opts.reuseaddr = %d\n", port->id(), packet->opts.reuseaddr);
reuseaddr_ = packet->opts.reuseaddr;
}
if (packet->opts.optsbits & 0B00000010) {
// printf("port->id() = %d, opts.reuseport = %d\n", port->id(), packet->opts.reuseport);
reuseport_ = packet->opts.reuseport;
}
if (packet->opts.optsbits & 0B00000100) {
// printf("port->id() = %d, opts.keepalive = %d\n", port->id(), packet->opts.keepalive);
keepalive_ = packet->opts.keepalive;
sockets::setKeepAlive(fd_, keepalive_);
}
if (packet->opts.optsbits & 0B00001000) {
// printf("port->id() = %d, opts.nodelay = %d\n", port->id(), packet->opts.nodelay);
nodelay_ = packet->opts.nodelay;
sockets::setTcpNoDelay(fd_, nodelay_);
}
if (packet->opts.optsbits & 0B00010000) {
// printf("port->id() = %d, opts.active = %d\n", port->id(), packet->opts.active);
active_ = packet->opts.active;
}
if (packet->opts.optsbits & 0B00100000) {
// printf("port->id() = %d, opts.owner = %d\n", port->id(), packet->opts.owner);
if (port->owner() != packet->opts.owner) {
PortCtl(port, port->id(), port->owner(), packet->opts.owner);
port->setOwner(packet->opts.owner);
}
}
if (packet->opts.optsbits & 0B01000000) {
// printf("port->id() = %d, opts.read = %d\n", port->id(), packet->opts.read);
read_ = packet->opts.read;
if (read_) {
port->channel(fd_)->enableReading()->update();
} else {
port->channel(fd_)->disableReading()->update();
}
}
return true;
}
bool handleIoReadEvent(PortPtr port, int fd)
{
assert(fd_ == fd);
int savedErrno = 0;
ssize_t n = inputBuffer_.readFd(fd, &savedErrno);
if (n > 0) {
readCount_ += n;
}
// printf("port->id() = %d, new message = %zd, active = %d, fd = %d, \n", port->id(), n, active_, fd_);
if (active_) {
if (n > 0) {
TcpPacket* packet = (TcpPacket*)malloc(sizeof(TcpPacket) + n);
packet->type = TcpPacket::kRead;
packet->id = port->id();
packet->session = 0;
packet->read.nbyte = n;
memcpy(packet->read.data, inputBuffer_.peek(), n);
inputBuffer_.retrieve(n);
auto msg = port->makeMessage();
msg->type = MSG_TYPE_TCP;
msg->data = packet;
msg->size = sizeof(TcpPacket) + n;
port->send(port->owner(), msg);
return true;
} else if (n == 0) {
if (state_ == kDisconnecting) {
port->channel(fd_)->disableReading()->update();
close(port, port->owner(), port->id());
} else {
TcpPacket* packet = (TcpPacket*)malloc(sizeof(TcpPacket));
packet->type = TcpPacket::kRead;
packet->id = port->id();
packet->session = 0;
packet->read.nbyte = 0;
auto msg = port->makeMessage();
msg->type = MSG_TYPE_TCP;
msg->data = packet;
msg->size = sizeof(TcpPacket);
port->send(port->owner(), msg);
port->channel(fd_)->disableReading()->update();
state_ = kDisconnecting;
}
return true;
} else {
char t_errnobuf[512] = {'\0'};
strerror_r(savedErrno, t_errnobuf, sizeof t_errnobuf);
fprintf(stderr, "port->id() = %d, fd = %d read error=%s\n", port->id(), fd, t_errnobuf);
return true;
}
} else {
if (n > 0) {
if (inputBuffer_.readableBytes() >= highWaterMark_) {
port->channel(fd_)->disableReading()->update();
}
} else if (n == 0) {
if (state_ == kDisconnecting) {
port->channel(fd_)->disableReading()->update();
close(port, port->owner(), port->id());
} else {
port->channel(fd_)->disableReading()->update();
state_ = kDisconnecting;
}
}
}
return true;
}
bool handleIoWriteEvent(PortPtr port, int fd)
{
// static uint32_t i = 0;
// i++;
assert(fd_ == fd);
if (port->channel(fd_)->isWriting()) {
ssize_t n = sockets::write(fd_, outputBuffer_.peek(), outputBuffer_.readableBytes());
// if (i < 5) {
// printf("port->id() = %d, total = %zd, write = %zd, i = %d\n", port->id(), outputBuffer_.readableBytes(), n, i);
// }
if (n > 0) {
writeCount_ += n;
outputBuffer_.retrieve(n);
// 低水位回调
if (outputBuffer_.readableBytes() <= lowWaterMark_ && lowWaterMarkResponse_ && state_ == kConnected) {
TcpPacket* packet = (TcpPacket*)malloc(sizeof(TcpPacket));
packet->type = TcpPacket::kLowWaterMark;
packet->id = port->id();
packet->session = 0;
packet->lowWaterMark.on = true;
packet->lowWaterMark.value = outputBuffer_.readableBytes();
auto msg = port->makeMessage();
msg->type = MSG_TYPE_TCP;
msg->data = packet;
msg->size = sizeof(TcpPacket);
port->send(port->owner(), msg);
}
if (outputBuffer_.readableBytes() == 0) {
port->channel(fd_)->disableWriting()->update();
if (state_ == kDisconnecting) {
// close(port, port->owner(), port->id());
sockets::shutdownWrite(fd_);
}
}
} else {
char t_errnobuf[512] = {'\0'};
strerror_r(errno, t_errnobuf, sizeof t_errnobuf);
// fprintf(stderr, "port->id() = %d, fd = %d, errno = %d, write error = %s\n", port->id(), fd, errno, t_errnobuf);
port->channel(fd_)->disableWriting()->update();
// if (state_ == kDisconnecting)
// {
// sockets::shutdownWrite(connfd_);
// }
}
} else {
//LOG_TRACE << "Connection fd = " << channel_->fd() << " is down, no more writing";
}
return true;
}
bool send(PortPtr port, TcpPacket* packet)
{
// printf("port->id() = %d, send total message = %d\n", port->id(), cmd->towrite.nbyte);
const void* data = static_cast<const void*>(packet->write.data);
size_t len = packet->write.nbyte;
ssize_t nwrote = 0;
size_t remaining = len;
bool faultError = false;
if (state_ != kConnected) {
return true;
}
// if no thing in output queue, try writing directly
if (!port->channel(fd_)->isWriting() && outputBuffer_.readableBytes() == 0) {
nwrote = sockets::write(fd_, data, len);
if (nwrote >= 0) {
writeCount_ += nwrote;
remaining = len - nwrote;
// 低水位回调
if (remaining <= lowWaterMark_ && lowWaterMarkResponse_) {
TcpPacket* packet = (TcpPacket*)malloc(sizeof(TcpPacket));
packet->type = TcpPacket::kLowWaterMark;
packet->id = port->id();
packet->session = 0;
packet->lowWaterMark.on = true;
packet->lowWaterMark.value = remaining;
auto msg = port->makeMessage();
msg->type = MSG_TYPE_TCP;
msg->data = packet;
msg->size = sizeof(TcpPacket);
port->send(port->owner(), msg);
}
} else { // nwrote < 0
nwrote = 0;
if (errno != EWOULDBLOCK) {
if (errno == EPIPE || errno == ECONNRESET) { // FIXME: any others?
faultError = true;
}
}
}
}
assert(remaining <= len);
if (!faultError && remaining > 0) {
size_t oldLen = outputBuffer_.readableBytes();
// 高水位回调
if (oldLen + remaining >= highWaterMark_ && oldLen < highWaterMark_ && highWaterMarkResponse_) {
TcpPacket* packet = (TcpPacket*)malloc(sizeof(TcpPacket));
packet->type = TcpPacket::kHighWaterMark;
packet->id = port->id();
packet->session = 0;
packet->highWaterMark.on = true;
packet->highWaterMark.value = oldLen + remaining;
auto msg = port->makeMessage();
msg->type = MSG_TYPE_TCP;
msg->data = packet;
msg->size = sizeof(TcpPacket);
port->send(port->owner(), msg);
}
outputBuffer_.append(static_cast<const char*>(data)+nwrote, remaining);
if (!port->channel(fd_)->isWriting()) {
// printf("port->id() = %d, enableWriting\n", port->id());
port->channel(fd_)->enableWriting()->update();
}
}
// printf("port->id() = %d, send save message = %zd\n", port->id(), outputBuffer_.readableBytes());
return true;
}
bool recv(PortPtr port, uint32_t source, uint32_t session, int nbyte)
{
size_t size = static_cast<size_t>(nbyte);
assert(port->owner() == source);
assert(state_ == kConnected || state_ == kDisconnecting);
// printf("port->id() = %d, total = %zu, read msg start size = %d\n", port->id(), inputBuffer_.readableBytes(), size);
if (state_ == kDisconnecting && inputBuffer_.readableBytes() == 0) {
// printf("port->id() = %d, read msg 0, close connection\n", port->id());
TcpPacket* packet = (TcpPacket*)malloc(sizeof(TcpPacket));
packet->type = TcpPacket::kRead;
packet->id = port->id();
packet->session = session;
packet->read.nbyte = 0;
auto msg = port->makeMessage();
msg->type = MSG_TYPE_TCP;
msg->data = packet;
msg->size = sizeof(TcpPacket);
port->send(source, msg);
return true;
}
if (state_ == kDisconnecting && inputBuffer_.readableBytes() <= size) {
// printf("port->id() = %d, read all msg, close connection\n", port->id());
int n = inputBuffer_.readableBytes();
TcpPacket* packet = (TcpPacket*)malloc(sizeof(TcpPacket) + n);
packet->type = TcpPacket::kRead;
packet->id = port->id();
packet->session = session;
packet->read.nbyte = n;
memcpy(packet->read.data, inputBuffer_.peek(), n);
inputBuffer_.retrieve(n);
auto msg = port->makeMessage();
msg->type = MSG_TYPE_TCP;
msg->data = packet;
msg->size = sizeof(TcpPacket) + n;
port->send(source, msg);
return true;
}
if (state_ == kConnected && read_ && inputBuffer_.readableBytes() <= size && !port->channel(fd_)->isReading()) {
port->channel(fd_)->enableReading()->update();
return false;
}
if (inputBuffer_.readableBytes() == 0) {
return false;
}
if (inputBuffer_.readableBytes() < size) {
return false;
}
int n = size>0? size : inputBuffer_.readableBytes();
TcpPacket* packet = (TcpPacket*)malloc(sizeof(TcpPacket) + n);
packet->type = TcpPacket::kRead;
packet->id = port->id();
packet->session = session;
packet->read.nbyte = n;
memcpy(packet->read.data, inputBuffer_.peek(), n);
inputBuffer_.retrieve(n);
auto msg = port->makeMessage();
msg->type = MSG_TYPE_TCP;
msg->data = packet;
msg->size = sizeof(TcpPacket) + n;
port->send(source, msg);
// printf("port->id() = %d, read msg size %d [ok]\n", port->id(), n);
return true;
}
bool shutdown(PortPtr port, uint32_t source, uint32_t id)
{
// printf("port->id() = %d, shutdown\n", port->id());
assert(port->owner() == source);
assert(port->id() == id);
if (state_ == kConnected || state_ == kDisconnecting) {
// printf("shutdown to close1\n");
if (state_ == kDisconnecting) {
close(port, port->owner(), port->id());
return true;
}
if (!port->channel(fd_)->isWriting()) {
// printf("shutdown to close2\n");
// close(port, port->owner(), port->id());
sockets::shutdownWrite(fd_);
state_ = kDisconnecting;
return true;
}
}
return true;
}
bool close(PortPtr port, uint32_t source, uint32_t id)
{
// printf("port->id() = %d, close\n", port->id());
assert(port->owner() == source);
assert(port->id() == id);
assert(state_ == kConnected || state_ == kDisconnecting);
PortCtl(port, port->id(), port->owner(), 0);
// we don't close fd, leave it to dtor, so we can find leaks easily.
port->exit();
return true;
}
bool lowWaterMark(PortPtr port, bool on, uint64_t value)
{
lowWaterMarkResponse_ = on;
lowWaterMark_ = value;
return true;
}
bool highWaterMark(PortPtr port, bool on, uint64_t value)
{
highWaterMarkResponse_ = on;
highWaterMark_ = value;
return true;
}
bool getinfo(PortPtr port, uint32_t source, uint32_t session)
{
struct sockaddr_in6 addr6 = sockets::getPeerAddr(fd_);
struct sockaddr* addr = (struct sockaddr*)&addr6;
TcpPacket* packet = (TcpPacket*)malloc(sizeof(TcpPacket));
memset(packet, 0, sizeof(TcpPacket));
packet->type = TcpPacket::kInfo;
packet->id = port->id();
packet->session = session;
sockets::toIp(packet->info.ip, 64, addr);
packet->info.port = sockets::toPort(addr);
packet->info.ipv6 = addr->sa_family == AF_INET6;
memcpy(packet->info.start, start_.data(), start_.size());
packet->info.owner = port->owner();
packet->info.readCount = readCount_;
packet->info.readBuff = inputBuffer_.readableBytes();
packet->info.writeCount = writeCount_;
packet->info.writeBuff = outputBuffer_.readableBytes();
auto msg = port->makeMessage();
msg->type = MSG_TYPE_TCP;
msg->data = packet;
msg->size = sizeof(TcpPacket);
port->send(source, msg);
return true;
}
private:
enum State {kConnecting, kConnected, kDisconnecting, kDisconnected};
State state_;
int fd_ = 0;
Buffer inputBuffer_;
Buffer outputBuffer_;
// 高低水位回调设置
bool lowWaterMarkResponse_ = false;
bool highWaterMarkResponse_ = false;
uint64_t lowWaterMark_ = 0;
uint64_t highWaterMark_ = 1024*1024*1024;
bool reuseaddr_ = false;
bool reuseport_ = false;
bool keepalive_ = false;
bool nodelay_ = false;
bool active_ = false;
bool read_ = false;
std::string start_;
uint32_t readCount_ = 0;
uint32_t writeCount_ = 0;
};
reg(TcpConnnection)
| 31.509091 | 120 | 0.623838 | lsgw |
d4e812eef103969aebf1cacaaa70cb49ecaaf4be | 534 | cpp | C++ | path_planning/a_star/main.cpp | EatAllBugs/cpp_robotics | f0ee1b936f8f3d40ec78c30846cd1fbdf72ef27c | [
"MIT"
] | 1 | 2022-01-23T13:17:28.000Z | 2022-01-23T13:17:28.000Z | path_planning/a_star/main.cpp | yinflight/cpp_robotics | f0ee1b936f8f3d40ec78c30846cd1fbdf72ef27c | [
"MIT"
] | null | null | null | path_planning/a_star/main.cpp | yinflight/cpp_robotics | f0ee1b936f8f3d40ec78c30846cd1fbdf72ef27c | [
"MIT"
] | 1 | 2022-01-23T13:17:16.000Z | 2022-01-23T13:17:16.000Z | #include <iostream>
#include "a_star.hpp"
using namespace cpp_robotics::path_planning;
int main() {
std::cout << "Hello, World!" << std::endl;
//! load map data
cv::Mat map_data = cv::imread("../maps/map2.png", CV_8UC1);
if (map_data.empty()) {
std::cerr << "load map image fail." << std::endl;
return -1;
}
//! a_star
std::cout << map_data.size() << std::endl;
a_star::Astar astar(a_star::Heuristic::euclidean, true);
astar.init(map_data);
auto path = astar.findPath({25,25}, {480, 480});
return 0;
} | 25.428571 | 61 | 0.625468 | EatAllBugs |
d4f027e29b231c1032a15d9481272ce7db913a8a | 791 | cpp | C++ | LeetCode/ThousandOne/0287-find_duplicated_num.cpp | Ginkgo-Biloba/Cpp-Repo1-VS | 231c68a055e6bf69a3f7c224e7c0182b67ce5b67 | [
"Apache-2.0"
] | null | null | null | LeetCode/ThousandOne/0287-find_duplicated_num.cpp | Ginkgo-Biloba/Cpp-Repo1-VS | 231c68a055e6bf69a3f7c224e7c0182b67ce5b67 | [
"Apache-2.0"
] | null | null | null | LeetCode/ThousandOne/0287-find_duplicated_num.cpp | Ginkgo-Biloba/Cpp-Repo1-VS | 231c68a055e6bf69a3f7c224e7c0182b67ce5b67 | [
"Apache-2.0"
] | null | null | null | #include "leetcode.hpp"
/* 287. 寻找重复数
给定一个包含 n + 1 个整数的数组 nums,其数字都在 1 到 n 之间(包括 1 和 n),可知至少存在一个重复的整数。
假设只有一个重复的整数,找出这个重复的数。
示例 1:
输入: [1,3,4,2,2]
输出: 2
示例 2:
输入: [3,1,3,4,2]
输出: 3
说明:
不能更改原数组(假设数组是只读的)。
只能使用额外的 O(1) 的空间。
时间复杂度小于 O(n^2) 。
数组中只有一个重复的数字,但它可能不止重复出现一次。
*/
int findDuplicate(vector<int>& A)
{
int len = static_cast<int>(A.size());
for (int i = 0; i < len;)
{
if (A[i] == i + 1)
++i;
else
{
if (A[A[i] - 1] != A[i])
std::swap(A[A[i] - 1], A[i]);
else
return A[i];
}
}
return 0;
}
int main()
{
vector<int>
a = { 1, 3, 4, 2, 2 },
b = { 3, 1, 3, 4, 2 },
c = { 1, 1, 2 },
d = { 3, 3, 3, 3 };
OutExpr(findDuplicate(a), "%d");
OutExpr(findDuplicate(b), "%d");
OutExpr(findDuplicate(c), "%d");
OutExpr(findDuplicate(d), "%d");
}
| 14.125 | 64 | 0.529709 | Ginkgo-Biloba |
d4f2f70717ce542d8b524f37266924a3ed61637b | 19,726 | cpp | C++ | Backends/Graphics5/Vulkan/Sources/Kore/PipelineState5Impl.cpp | hyperluminality/Kinc | f1802becc92e9a9eaa2e13b205d6a18eb58359a3 | [
"Zlib"
] | null | null | null | Backends/Graphics5/Vulkan/Sources/Kore/PipelineState5Impl.cpp | hyperluminality/Kinc | f1802becc92e9a9eaa2e13b205d6a18eb58359a3 | [
"Zlib"
] | null | null | null | Backends/Graphics5/Vulkan/Sources/Kore/PipelineState5Impl.cpp | hyperluminality/Kinc | f1802becc92e9a9eaa2e13b205d6a18eb58359a3 | [
"Zlib"
] | null | null | null | #include "pch.h"
#include "Vulkan.h"
#include <kinc/graphics5/shader.h>
#include <kinc/graphics5/pipeline.h>
#include <assert.h>
#include <malloc.h>
#include <map>
#include <string>
#include <string.h>
extern VkDevice device;
extern VkRenderPass render_pass;
extern VkDescriptorSet desc_set;
bool memory_type_from_properties(uint32_t typeBits, VkFlags requirements_mask, uint32_t* typeIndex);
void createDescriptorLayout(PipelineState5Impl* pipeline);
kinc_g5_pipeline_t *currentPipeline = NULL;
static bool has_number(kinc_internal_named_number *named_numbers, const char *name) {
for (int i = 0; i < KINC_INTERNAL_NAMED_NUMBER_COUNT; ++i) {
if (strcmp(named_numbers[i].name, name) == 0) {
return true;
}
}
return false;
}
static uint32_t find_number(kinc_internal_named_number *named_numbers, const char *name) {
for (int i = 0; i < KINC_INTERNAL_NAMED_NUMBER_COUNT; ++i) {
if (strcmp(named_numbers[i].name, name) == 0) {
return named_numbers[i].number;
}
}
return 0;
}
static void set_number(kinc_internal_named_number *named_numbers, const char *name, uint32_t number) {
for (int i = 0; i < KINC_INTERNAL_NAMED_NUMBER_COUNT; ++i) {
if (strcmp(named_numbers[i].name, name) == 0) {
named_numbers[i].number = number;
return;
}
}
for (int i = 0; i < KINC_INTERNAL_NAMED_NUMBER_COUNT; ++i) {
if (named_numbers[i].name[0] == 0) {
strcpy(named_numbers[i].name, name);
named_numbers[i].number = number;
return;
}
}
assert(false);
}
namespace {
void parseShader(kinc_g5_shader_t *shader, kinc_internal_named_number *locations, kinc_internal_named_number *textureBindings,
kinc_internal_named_number *uniformOffsets) {
memset(locations, 0, sizeof(kinc_internal_named_number) * KINC_INTERNAL_NAMED_NUMBER_COUNT);
memset(textureBindings, 0, sizeof(kinc_internal_named_number) * KINC_INTERNAL_NAMED_NUMBER_COUNT);
memset(uniformOffsets, 0, sizeof(kinc_internal_named_number) * KINC_INTERNAL_NAMED_NUMBER_COUNT);
uint32_t *spirv = (uint32_t *)shader->impl.source;
int spirvsize = shader->impl.length / 4;
int index = 0;
unsigned magicNumber = spirv[index++];
unsigned version = spirv[index++];
unsigned generator = spirv[index++];
unsigned bound = spirv[index++];
index++;
std::map<uint32_t, std::string> names;
std::map<uint32_t, std::string> memberNames;
std::map<uint32_t, uint32_t> locs;
std::map<uint32_t, uint32_t> bindings;
std::map<uint32_t, uint32_t> offsets;
while (index < spirvsize) {
int wordCount = spirv[index] >> 16;
uint32_t opcode = spirv[index] & 0xffff;
uint32_t *operands = wordCount > 1 ? &spirv[index + 1] : nullptr;
uint32_t length = wordCount - 1;
switch (opcode) {
case 5: { // OpName
uint32_t id = operands[0];
char* string = (char*)&operands[1];
names[id] = string;
break;
}
case 6: { // OpMemberName
uint32_t type = operands[0];
if (names[type] == "_k_global_uniform_buffer_type") {
uint32_t member = operands[1];
char* string = (char*)&operands[2];
memberNames[member] = string;
}
break;
}
case 71: { // OpDecorate
uint32_t id = operands[0];
uint32_t decoration = operands[1];
if (decoration == 30) { // location
uint32_t location = operands[2];
locs[id] = location;
}
if (decoration == 33) { // binding
uint32_t binding = operands[2];
bindings[id] = binding;
}
break;
}
case 72: { // OpMemberDecorate
uint32_t type = operands[0];
if (names[type] == "_k_global_uniform_buffer_type") {
uint32_t member = operands[1];
uint32_t decoration = operands[2];
if (decoration == 35) { // offset
uint32_t offset = operands[3];
offsets[member] = offset;
}
}
}
}
index += wordCount;
}
for (std::map<uint32_t, uint32_t>::iterator it = locs.begin(); it != locs.end(); ++it) {
set_number(locations, names[it->first].c_str(), it->second);
}
for (std::map<uint32_t, uint32_t>::iterator it = bindings.begin(); it != bindings.end(); ++it) {
set_number(textureBindings, names[it->first].c_str(), it->second);
}
for (std::map<uint32_t, uint32_t>::iterator it = offsets.begin(); it != offsets.end(); ++it) {
set_number(uniformOffsets, memberNames[it->first].c_str(), it->second);
}
}
VkShaderModule demo_prepare_shader_module(const void* code, size_t size) {
VkShaderModuleCreateInfo moduleCreateInfo;
VkShaderModule module;
VkResult err;
moduleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
moduleCreateInfo.pNext = NULL;
moduleCreateInfo.codeSize = size;
moduleCreateInfo.pCode = (const uint32_t*)code;
moduleCreateInfo.flags = 0;
err = vkCreateShaderModule(device, &moduleCreateInfo, NULL, &module);
assert(!err);
return module;
}
VkShaderModule demo_prepare_vs(VkShaderModule& vert_shader_module, kinc_g5_shader_t *vertexShader) {
vert_shader_module = demo_prepare_shader_module(vertexShader->impl.source, vertexShader->impl.length);
return vert_shader_module;
}
VkShaderModule demo_prepare_fs(VkShaderModule& frag_shader_module, kinc_g5_shader_t *fragmentShader) {
frag_shader_module = demo_prepare_shader_module(fragmentShader->impl.source, fragmentShader->impl.length);
return frag_shader_module;
}
}
void kinc_g5_pipeline_init(kinc_g5_pipeline_t *pipeline) {
pipeline->vertexShader = nullptr;
pipeline->fragmentShader = nullptr;
pipeline->geometryShader = nullptr;
pipeline->tessellationEvaluationShader = nullptr;
pipeline->tessellationControlShader = nullptr;
createDescriptorLayout(&pipeline->impl);
Kore::Vulkan::createDescriptorSet(&pipeline->impl, nullptr, nullptr, desc_set);
}
void kinc_g5_pipeline_destroy(kinc_g5_pipeline_t *pipeline) {}
kinc_g5_constant_location_t kinc_g5_pipeline_get_constant_location(kinc_g5_pipeline_t *pipeline, const char *name) {
kinc_g5_constant_location_t location;
location.impl.vertexOffset = -1;
location.impl.fragmentOffset = -1;
if (has_number(pipeline->impl.vertexOffsets, name)) {
location.impl.vertexOffset = find_number(pipeline->impl.vertexOffsets, name);
}
if (has_number(pipeline->impl.fragmentOffsets, name)) {
location.impl.fragmentOffset = find_number(pipeline->impl.fragmentOffsets, name);
}
return location;
}
kinc_g5_texture_unit_t kinc_g5_pipeline_get_texture_unit(kinc_g5_pipeline_t *pipeline, const char *name) {
kinc_g5_texture_unit_t unit;
unit.impl.binding = find_number(pipeline->impl.textureBindings, name);
return unit;
}
void kinc_g5_pipeline_compile(kinc_g5_pipeline_t *pipeline) {
parseShader(pipeline->vertexShader, pipeline->impl.vertexLocations, pipeline->impl.textureBindings, pipeline->impl.vertexOffsets);
parseShader(pipeline->fragmentShader, pipeline->impl.fragmentLocations, pipeline->impl.textureBindings, pipeline->impl.fragmentOffsets);
//
VkPipelineLayoutCreateInfo pPipelineLayoutCreateInfo = {};
pPipelineLayoutCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pPipelineLayoutCreateInfo.pNext = NULL;
pPipelineLayoutCreateInfo.setLayoutCount = 1;
pPipelineLayoutCreateInfo.pSetLayouts = &pipeline->impl.desc_layout;
VkResult err = vkCreatePipelineLayout(device, &pPipelineLayoutCreateInfo, NULL, &pipeline->impl.pipeline_layout);
assert(!err);
//
VkGraphicsPipelineCreateInfo pipeline_info = {};
VkPipelineCacheCreateInfo pipelineCache_info = {};
VkPipelineInputAssemblyStateCreateInfo ia = {};
VkPipelineRasterizationStateCreateInfo rs = {};
VkPipelineColorBlendStateCreateInfo cb = {};
VkPipelineDepthStencilStateCreateInfo ds = {};
VkPipelineViewportStateCreateInfo vp = {};
VkPipelineMultisampleStateCreateInfo ms = {};
VkDynamicState dynamicStateEnables[VK_DYNAMIC_STATE_RANGE_SIZE];
VkPipelineDynamicStateCreateInfo dynamicState = {};
memset(dynamicStateEnables, 0, sizeof dynamicStateEnables);
memset(&dynamicState, 0, sizeof dynamicState);
dynamicState.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
dynamicState.pDynamicStates = dynamicStateEnables;
memset(&pipeline_info, 0, sizeof(pipeline_info));
pipeline_info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
pipeline_info.layout = pipeline->impl.pipeline_layout;
uint32_t stride = 0;
for (int i = 0; i < pipeline->inputLayout[0]->size; ++i) {
kinc_g5_vertex_element_t element = pipeline->inputLayout[0]->elements[i];
switch (element.data) {
case KINC_G4_VERTEX_DATA_COLOR:
stride += 1 * 4;
break;
case KINC_G4_VERTEX_DATA_FLOAT1:
stride += 1 * 4;
break;
case KINC_G4_VERTEX_DATA_FLOAT2:
stride += 2 * 4;
break;
case KINC_G4_VERTEX_DATA_FLOAT3:
stride += 3 * 4;
break;
case KINC_G4_VERTEX_DATA_FLOAT4:
stride += 4 * 4;
break;
case KINC_G4_VERTEX_DATA_FLOAT4X4:
stride += 4 * 4 * 4;
break;
}
}
VkVertexInputBindingDescription vi_bindings[1];
#ifdef KORE_WINDOWS
VkVertexInputAttributeDescription* vi_attrs = (VkVertexInputAttributeDescription*)alloca(sizeof(VkVertexInputAttributeDescription) * pipeline->inputLayout[0]->size);
#else
VkVertexInputAttributeDescription vi_attrs[pipeline->inputLayout[0]->size];
#endif
VkPipelineVertexInputStateCreateInfo vi = {};
vi.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
vi.pNext = NULL;
vi.vertexBindingDescriptionCount = 1;
vi.pVertexBindingDescriptions = vi_bindings;
vi.vertexAttributeDescriptionCount = pipeline->inputLayout[0]->size;
vi.pVertexAttributeDescriptions = vi_attrs;
vi_bindings[0].binding = 0;
vi_bindings[0].stride = stride;
vi_bindings[0].inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
uint32_t offset = 0;
for (int i = 0; i < pipeline->inputLayout[0]->size; ++i) {
kinc_g5_vertex_element_t element = pipeline->inputLayout[0]->elements[i];
switch (element.data) {
case KINC_G4_VERTEX_DATA_COLOR:
vi_attrs[i].binding = 0;
vi_attrs[i].location = find_number(pipeline->impl.vertexLocations, element.name);
vi_attrs[i].format = VK_FORMAT_R32_UINT;
vi_attrs[i].offset = offset;
offset += 1 * 4;
break;
case KINC_G4_VERTEX_DATA_FLOAT1:
vi_attrs[i].binding = 0;
vi_attrs[i].location = find_number(pipeline->impl.vertexLocations, element.name);
vi_attrs[i].format = VK_FORMAT_R32_SFLOAT;
vi_attrs[i].offset = offset;
offset += 1 * 4;
break;
case KINC_G4_VERTEX_DATA_FLOAT2:
vi_attrs[i].binding = 0;
vi_attrs[i].location = find_number(pipeline->impl.vertexLocations, element.name);
vi_attrs[i].format = VK_FORMAT_R32G32_SFLOAT;
vi_attrs[i].offset = offset;
offset += 2 * 4;
break;
case KINC_G4_VERTEX_DATA_FLOAT3:
vi_attrs[i].binding = 0;
vi_attrs[i].location = find_number(pipeline->impl.vertexLocations, element.name);
vi_attrs[i].format = VK_FORMAT_R32G32B32_SFLOAT;
vi_attrs[i].offset = offset;
offset += 3 * 4;
break;
case KINC_G4_VERTEX_DATA_FLOAT4:
vi_attrs[i].binding = 0;
vi_attrs[i].location = find_number(pipeline->impl.vertexLocations, element.name);
vi_attrs[i].format = VK_FORMAT_R32G32B32A32_SFLOAT;
vi_attrs[i].offset = offset;
offset += 4 * 4;
break;
case KINC_G4_VERTEX_DATA_FLOAT4X4:
vi_attrs[i].binding = 0;
vi_attrs[i].location = find_number(pipeline->impl.vertexLocations, element.name);
vi_attrs[i].format = VK_FORMAT_R32G32B32A32_SFLOAT; // TODO
vi_attrs[i].offset = offset;
offset += 4 * 4 * 4;
break;
}
}
memset(&ia, 0, sizeof(ia));
ia.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
ia.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
memset(&rs, 0, sizeof(rs));
rs.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
rs.polygonMode = VK_POLYGON_MODE_FILL;
rs.cullMode = VK_CULL_MODE_NONE;
rs.frontFace = VK_FRONT_FACE_CLOCKWISE;
rs.depthClampEnable = VK_FALSE;
rs.rasterizerDiscardEnable = VK_FALSE;
rs.depthBiasEnable = VK_FALSE;
rs.lineWidth = 1.0f;
memset(&cb, 0, sizeof(cb));
cb.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
VkPipelineColorBlendAttachmentState att_state[1];
memset(att_state, 0, sizeof(att_state));
att_state[0].colorWriteMask = 0xf;
att_state[0].blendEnable = VK_FALSE;
cb.attachmentCount = 1;
cb.pAttachments = att_state;
memset(&vp, 0, sizeof(vp));
vp.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
vp.viewportCount = 1;
dynamicStateEnables[dynamicState.dynamicStateCount++] = VK_DYNAMIC_STATE_VIEWPORT;
vp.scissorCount = 1;
dynamicStateEnables[dynamicState.dynamicStateCount++] = VK_DYNAMIC_STATE_SCISSOR;
memset(&ds, 0, sizeof(ds));
ds.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
ds.depthTestEnable = VK_FALSE;
ds.depthWriteEnable = VK_FALSE;
ds.depthCompareOp = VK_COMPARE_OP_LESS_OR_EQUAL;
ds.depthBoundsTestEnable = VK_FALSE;
ds.back.failOp = VK_STENCIL_OP_KEEP;
ds.back.passOp = VK_STENCIL_OP_KEEP;
ds.back.compareOp = VK_COMPARE_OP_ALWAYS;
ds.stencilTestEnable = VK_FALSE;
ds.front = ds.back;
memset(&ms, 0, sizeof(ms));
ms.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
ms.pSampleMask = nullptr;
ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
pipeline_info.stageCount = 2;
VkPipelineShaderStageCreateInfo shaderStages[2];
memset(&shaderStages, 0, 2 * sizeof(VkPipelineShaderStageCreateInfo));
shaderStages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
shaderStages[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
shaderStages[0].module = demo_prepare_vs(pipeline->impl.vert_shader_module, pipeline->vertexShader);
shaderStages[0].pName = "main";
shaderStages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
shaderStages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
shaderStages[1].module = demo_prepare_fs(pipeline->impl.frag_shader_module, pipeline->fragmentShader);
shaderStages[1].pName = "main";
pipeline_info.pVertexInputState = &vi;
pipeline_info.pInputAssemblyState = &ia;
pipeline_info.pRasterizationState = &rs;
pipeline_info.pColorBlendState = &cb;
pipeline_info.pMultisampleState = &ms;
pipeline_info.pViewportState = &vp;
pipeline_info.pDepthStencilState = &ds;
pipeline_info.pStages = shaderStages;
pipeline_info.renderPass = render_pass;
pipeline_info.pDynamicState = &dynamicState;
memset(&pipelineCache_info, 0, sizeof(pipelineCache_info));
pipelineCache_info.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
err = vkCreatePipelineCache(device, &pipelineCache_info, nullptr, &pipeline->impl.pipelineCache);
assert(!err);
err = vkCreateGraphicsPipelines(device, pipeline->impl.pipelineCache, 1, &pipeline_info, nullptr, &pipeline->impl.pipeline);
assert(!err);
vkDestroyPipelineCache(device, pipeline->impl.pipelineCache, nullptr);
vkDestroyShaderModule(device, pipeline->impl.frag_shader_module, nullptr);
vkDestroyShaderModule(device, pipeline->impl.vert_shader_module, nullptr);
}
extern VkDescriptorPool desc_pool;
void createDescriptorLayout(PipelineState5Impl* pipeline) {
VkDescriptorSetLayoutBinding layoutBindings[8];
memset(layoutBindings, 0, sizeof(layoutBindings));
layoutBindings[0].binding = 0;
layoutBindings[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
layoutBindings[0].descriptorCount = 1;
layoutBindings[0].stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
layoutBindings[0].pImmutableSamplers = nullptr;
layoutBindings[1].binding = 1;
layoutBindings[1].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
layoutBindings[1].descriptorCount = 1;
layoutBindings[1].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
layoutBindings[1].pImmutableSamplers = nullptr;
for (int i = 2; i < 8; ++i) {
layoutBindings[i].binding = i;
layoutBindings[i].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
layoutBindings[i].descriptorCount = 1;
layoutBindings[i].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
layoutBindings[i].pImmutableSamplers = nullptr;
}
VkDescriptorSetLayoutCreateInfo descriptor_layout = {};
descriptor_layout.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
descriptor_layout.pNext = NULL;
descriptor_layout.bindingCount = 8;
descriptor_layout.pBindings = layoutBindings;
VkResult err = vkCreateDescriptorSetLayout(device, &descriptor_layout, NULL, &pipeline->desc_layout);
assert(!err);
VkDescriptorPoolSize typeCounts[8];
memset(typeCounts, 0, sizeof(typeCounts));
typeCounts[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
typeCounts[0].descriptorCount = 1;
typeCounts[1].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
typeCounts[1].descriptorCount = 1;
for (int i = 2; i < 8; ++i) {
typeCounts[i].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
typeCounts[i].descriptorCount = 1;
}
VkDescriptorPoolCreateInfo descriptor_pool = {};
descriptor_pool.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
descriptor_pool.pNext = NULL;
descriptor_pool.maxSets = 128;
descriptor_pool.poolSizeCount = 8;
descriptor_pool.pPoolSizes = typeCounts;
err = vkCreateDescriptorPool(device, &descriptor_pool, NULL, &desc_pool);
assert(!err);
}
void Kore::Vulkan::createDescriptorSet(struct PipelineState5Impl_s *pipeline, kinc_g5_texture_t *texture, kinc_g5_render_target_t *renderTarget,
VkDescriptorSet &desc_set) {
// VkDescriptorImageInfo tex_descs[DEMO_TEXTURE_COUNT];
VkDescriptorBufferInfo buffer_descs[2];
VkDescriptorSetAllocateInfo alloc_info = {};
alloc_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
alloc_info.pNext = NULL;
alloc_info.descriptorPool = desc_pool;
alloc_info.descriptorSetCount = 1;
alloc_info.pSetLayouts = &pipeline->desc_layout;
VkResult err = vkAllocateDescriptorSets(device, &alloc_info, &desc_set);
assert(!err);
memset(&buffer_descs, 0, sizeof(buffer_descs));
if (vertexUniformBuffer != nullptr) {
buffer_descs[0].buffer = *vertexUniformBuffer;
}
buffer_descs[0].offset = 0;
buffer_descs[0].range = 256 * sizeof(float);
if (fragmentUniformBuffer != nullptr) {
buffer_descs[1].buffer = *fragmentUniformBuffer;
}
buffer_descs[1].offset = 0;
buffer_descs[1].range = 256 * sizeof(float);
VkDescriptorImageInfo tex_desc;
memset(&tex_desc, 0, sizeof(tex_desc));
if (texture != nullptr) {
tex_desc.sampler = texture->impl.texture.sampler;
tex_desc.imageView = texture->impl.texture.view;
}
if (renderTarget != nullptr) {
tex_desc.sampler = renderTarget->impl.sampler;
tex_desc.imageView = renderTarget->impl.destView;
}
tex_desc.imageLayout = VK_IMAGE_LAYOUT_GENERAL;
VkWriteDescriptorSet writes[8];
memset(writes, 0, sizeof(writes));
writes[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
writes[0].dstSet = desc_set;
writes[0].dstBinding = 0;
writes[0].descriptorCount = 1;
writes[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
writes[0].pBufferInfo = &buffer_descs[0];
writes[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
writes[1].dstSet = desc_set;
writes[1].dstBinding = 1;
writes[1].descriptorCount = 1;
writes[1].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
writes[1].pBufferInfo = &buffer_descs[1];
for (int i = 2; i < 8; ++i) {
writes[i].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
writes[i].dstSet = desc_set;
writes[i].dstBinding = i;
writes[i].descriptorCount = 1;
writes[i].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
writes[i].pImageInfo = &tex_desc;
}
if (texture != nullptr || renderTarget != nullptr) {
if (vertexUniformBuffer != nullptr && fragmentUniformBuffer != nullptr) {
vkUpdateDescriptorSets(device, 3, writes, 0, nullptr);
}
else {
vkUpdateDescriptorSets(device, 1, writes + 2, 0, nullptr);
}
}
else {
if (vertexUniformBuffer != nullptr && fragmentUniformBuffer != nullptr) {
vkUpdateDescriptorSets(device, 2, writes, 0, nullptr);
}
}
}
| 34.913274 | 166 | 0.759302 | hyperluminality |
be02da1e4682e055e9bd49fd7c5f526f8bf1be96 | 2,031 | cpp | C++ | src/Graphics/Camera.cpp | khskarl/tori | 52e07e7b8bdbab7b46c4565a6be9353c0ce59422 | [
"MIT"
] | 2 | 2018-07-05T23:50:20.000Z | 2020-02-07T12:34:05.000Z | src/Graphics/Camera.cpp | khskarl/tori | 52e07e7b8bdbab7b46c4565a6be9353c0ce59422 | [
"MIT"
] | null | null | null | src/Graphics/Camera.cpp | khskarl/tori | 52e07e7b8bdbab7b46c4565a6be9353c0ce59422 | [
"MIT"
] | null | null | null | #include "Camera.hpp"
#include <glm/gtx/rotate_vector.hpp>
#include <glm/gtc/matrix_transform.hpp>
Camera::Camera () {
this->BuildProjectionMatrix();
}
Camera::Camera (const glm::vec3 pos, const glm::vec3 direction, const float width, const float height) {
m_position = pos;
m_direction = direction;
m_width = width;
m_height = height;
this->BuildProjectionMatrix();
}
void Camera::BuildProjectionMatrix () {
mProjectionMatrix = glm::perspective(glm::radians(m_fov),
GetAspectRatio(),
m_nearPlane,
m_farPlane);
}
glm::mat4 const Camera::GetViewMatrix () {
return glm::lookAt(m_position, m_position + m_direction, m_up);
}
glm::mat4 const& Camera::GetProjectionMatrix () {
return mProjectionMatrix;
}
glm::vec3 const& Camera::GetPosition () {
return m_position;
}
glm::vec3 const& Camera::GetDirection () {
return m_direction;
}
glm::vec3 const& Camera::GetUp () {
return m_up;
}
glm::vec3 const Camera::GetRight () {
return glm::normalize(glm::cross(m_direction, m_up));
}
float const Camera::GetAspectRatio () {
return m_width / m_height;
}
void Camera::MoveForward (const float amount) {
m_position += m_direction * amount;
}
void Camera::MoveRight (const float amount) {
m_position += GetRight() * amount;
}
void Camera::RotatePitch (const float amount) {
m_pitch += amount;
if (m_pitch > 90.f) m_pitch = 90.f - 0.001f;
if (m_pitch < -90.f) m_pitch = -90.f + 0.001f;
RecomputeDirection();
}
void Camera::RotateYaw (const float amount) {
m_yaw += amount;
if (m_yaw > 360.0f) m_yaw = 0.0f;
if (m_yaw < 0.0f) m_yaw = 360.0f;
RecomputeDirection();
}
void Camera::RecomputeDirection () {
float pitch = glm::radians(m_pitch);
float yaw = glm::radians(m_yaw);
m_direction = (glm::vec3(glm::cos(pitch) * glm::cos(yaw),
glm::sin(pitch),
glm::cos(pitch) * glm::sin(yaw)));
m_direction = glm::normalize(m_direction);\
}
| 24.178571 | 104 | 0.641556 | khskarl |
be07628f4cf1c892299c014a9e0346b5e18eb045 | 2,661 | cpp | C++ | outputDialogs/signaldata.cpp | kerdemdemir/sharpEar | 6193fad5a776b246caed72d89009d64afc1db5a0 | [
"BSD-4-Clause"
] | 5 | 2016-04-27T08:01:06.000Z | 2021-12-21T07:07:14.000Z | outputDialogs/signaldata.cpp | kerdemdemir/sharpEar | 6193fad5a776b246caed72d89009d64afc1db5a0 | [
"BSD-4-Clause"
] | 3 | 2016-04-27T08:02:17.000Z | 2017-04-18T18:46:40.000Z | outputDialogs/signaldata.cpp | kerdemdemir/sharpEar | 6193fad5a776b246caed72d89009d64afc1db5a0 | [
"BSD-4-Clause"
] | null | null | null | #include "signaldata.h"
#include <qvector.h>
#include <qmutex.h>
#include <qreadwritelock.h>
class SignalData::PrivateData
{
public:
PrivateData():
boundingRect( 1.0, 1.0, -2.0, -2.0 ) // invalid
{
values.reserve( 1000 );
}
inline void append( const QPointF &sample )
{
values.append( sample );
// adjust the bounding rectangle
if ( boundingRect.width() < 0 || boundingRect.height() < 0 )
{
boundingRect.setRect( sample.x(), sample.y(), 0.0, 0.0 );
}
else
{
boundingRect.setRight( sample.x() );
if ( sample.y() > boundingRect.bottom() )
boundingRect.setBottom( sample.y() );
if ( sample.y() < boundingRect.top() )
boundingRect.setTop( sample.y() );
}
}
QReadWriteLock lock;
QVector<QPointF> values;
QRectF boundingRect;
QMutex mutex; // protecting pendingValues
QVector<QPointF> pendingValues;
};
SignalData::SignalData()
{
elapsedDataSize = 0;
d_data = new PrivateData();
}
SignalData::~SignalData()
{
delete d_data;
}
int SignalData::size() const
{
return d_data->values.size();
}
QPointF SignalData::value( int index ) const
{
return d_data->values[index];
}
QRectF SignalData::boundingRect() const
{
return d_data->boundingRect;
}
void SignalData::lock()
{
d_data->lock.lockForRead();
}
void SignalData::unlock()
{
d_data->lock.unlock();
}
void SignalData::append( const QPointF &sample )
{
d_data->mutex.lock();
d_data->pendingValues += sample;
elapsedDataSize++;
const bool isLocked = d_data->lock.tryLockForWrite();
if ( isLocked )
{
const int numValues = d_data->pendingValues.size();
const QPointF *pendingValues = d_data->pendingValues.data();
for ( int i = 0; i < numValues; i++ )
d_data->append( pendingValues[i] );
d_data->pendingValues.clear();
d_data->lock.unlock();
}
d_data->mutex.unlock();
}
void SignalData::clearStaleValues( double limit )
{
d_data->lock.lockForWrite();
d_data->boundingRect = QRectF( 1.0, 1.0, -2.0, -2.0 ); // invalid
const QVector<QPointF> values = d_data->values;
d_data->values.clear();
d_data->values.reserve( values.size() );
int index;
for ( index = values.size() - 1; index >= 0; index-- )
{
if ( values[index].x() < limit )
break;
}
if ( index > 0 )
d_data->append( values[index++] );
while ( index < values.size() - 1 )
d_data->append( values[index++] );
d_data->lock.unlock();
}
| 20.469231 | 69 | 0.585118 | kerdemdemir |
be089947172f9410e10fb07cb376d3c43383fa65 | 5,762 | hpp | C++ | code/path_marker.hpp | LoginLEE/HKUST-COMP2012h-2D-Shooting-Game | d03812a4a8cba8d31873157d71818b8c67d495fd | [
"MIT"
] | null | null | null | code/path_marker.hpp | LoginLEE/HKUST-COMP2012h-2D-Shooting-Game | d03812a4a8cba8d31873157d71818b8c67d495fd | [
"MIT"
] | null | null | null | code/path_marker.hpp | LoginLEE/HKUST-COMP2012h-2D-Shooting-Game | d03812a4a8cba8d31873157d71818b8c67d495fd | [
"MIT"
] | null | null | null | #pragma once
#include <SFML/Graphics.hpp>
#include "global_defines.hpp"
#include "game_entity.hpp"
#include "collision_box.hpp"
#include "textured_block.hpp"
class Enemy;
/**
* @brief Class for Enemy Path Markers
*
* This class represents a invisible Entity that guides the Enemy and controls their pathing around the level
*/
class PathMarker : public GameEntity {
public:
/**
* @brief Movement Direction for the Enemy
*/
enum Direction {
EnemyPathIdle,
EnemyPathLeft,
EnemyPathRight,
EnemyPathJumpLeft,
EnemyPathJumpRight,
};
private:
/**
* @brief The movement direction that this path marker will tell an Enemy to follow
*/
Direction pathDir = Direction::EnemyPathRight;
/**
* @brief Speed of the path that the enemy should take
*/
float speed = 1.0f;
/**
* @brief Should the enemy shoot while following this path?
*/
bool shoot = true;
/**
* @brief CollisionBox of this Path Marker
*/
CollisionBox collisionBox;
/**
* @brief Create a new Path Marker with a certain generation code at the default position
*
* @param _manager The global GameManager pointer
* @param[in] generationCode The generation code
* @param parent The parent GameEntity node
*/
PathMarker(GameManager *_manager, int generationCode, GameEntity *parent)
: PathMarker(_manager, generationCode, parent, 0, 0) {}
/**
* @brief Create a new Path Marker with a certain generation code at the given position
*
* @param _manager The global GameManager pointer
* @param[in] generationCode The generation code
* @param parent The parent GameEntity node
* @param[in] x x coordinate
* @param[in] y y coordinate
*/
PathMarker(GameManager *_manager, int generationCode, GameEntity *parent, float x, float y)
: PathMarker(_manager, generationCode, parent, sf::Vector2f(x, y)) {}
/**
* @brief Create a new Path Marker with a certain generation code at the given position
*
* @param _manager The global GameManager pointer
* @param[in] generationCode The generation code
* @param parent The parent GameEntity node
* @param[in] pos The position
*/
PathMarker(GameManager *_manager, int generationCode, GameEntity *parent, sf::Vector2f pos)
: GameEntity(_manager, parent) {
pathDir = static_cast<Direction>(generationCode % 5);
setPosition(pos);
setSize(sf::Vector2f(BLOCK_SIZE*0.5f, BLOCK_SIZE));
switch (pathDir) {
case EnemyPathIdle:
setSize(sf::Vector2f(BLOCK_SIZE, BLOCK_SIZE));
break;
case EnemyPathLeft:
case EnemyPathJumpLeft:
setPosition(pos + sf::Vector2f(BLOCK_SIZE*0.25f, 0));
break;
case EnemyPathRight:
case EnemyPathJumpRight:
setPosition(pos - sf::Vector2f(BLOCK_SIZE*0.25f, 0));
break;
}
collisionBox = CollisionBox(getTotalPosition(), getSize());
}
public:
/**
* @brief Static function for creating Path Markers from Map file codes
*
* Used to allow for the possibility of generating subclasses of Path Markers in the future
*
* @param _manager The global GameManager pointer
* @param[in] generationCode The generation code
* @param parent The parent GameEntity node
* @param[in] x The X coordinate
* @param[in] y The Y coordinate
*
* @return The created Path Marker
*/
static PathMarker* create(GameManager *_manager, int generationCode, GameEntity *parent, float x, float y) {
return new PathMarker(_manager, generationCode, parent, x, y); //may return sub classes in the future
}
/**
* @brief Gets the collision box.
*
* @return The collision box.
*/
CollisionBox getCollisionBox() const {return collisionBox;}
/**
* @brief Is the given Enemy Entity stepping in this Path Marker?
*
* @param[in] enemy The enemy
*
* @return True if Enemy's feet is inside this collision box
*/
bool steppingIn(const Enemy* enemy) const;
/**
* @brief Gets the path direction
*/
Direction getPathDir() const {return pathDir;};
/**
* @brief Gets the speed.
*/
float getSpeed() const {return speed;};
/**
* @brief Should enemy shoot?
*
* @return { description_of_the_return_value }
*/
float shouldShoot() const {return shoot;};
/**
* @brief Draw Collision Box and Arrows for Debugging
*
* @param renderer The Render Target to Draw to
*/
virtual void draw(sf::RenderTarget &renderer) const override {
if (DISPLAY_DEBUGGING_STUFF) {
collisionBox.draw(renderer);
if (pathDir == EnemyPathIdle) return;
sf::ConvexShape arrow;
arrow.setPointCount(3);
switch (pathDir) {
case EnemyPathLeft:
arrow.setPoint(0, sf::Vector2f(getSize().x, 0));
arrow.setPoint(1, sf::Vector2f(0, getSize().y/2));
arrow.setPoint(2, sf::Vector2f(getSize().x, getSize().y));
break;
case EnemyPathRight:
arrow.setPoint(0, sf::Vector2f(0, 0));
arrow.setPoint(1, sf::Vector2f(0, getSize().y));
arrow.setPoint(2, sf::Vector2f(getSize().x, getSize().y/2));
break;
case EnemyPathJumpLeft:
arrow.setPoint(0, sf::Vector2f(0, 0));
arrow.setPoint(1, sf::Vector2f(0, getSize().y/2));
arrow.setPoint(2, sf::Vector2f(getSize().x, 0));
break;
case EnemyPathJumpRight:
arrow.setPoint(0, sf::Vector2f(0, 0));
arrow.setPoint(1, sf::Vector2f(getSize().x, getSize().y/2));
arrow.setPoint(2, sf::Vector2f(getSize().x, 0));
break;
case EnemyPathIdle:
break;
}
arrow.setFillColor(sf::Color::Green);
arrow.setPosition(getTotalPosition());
arrow.setOrigin(getSize()/2.0f);
renderer.draw(arrow);
}
}
}; | 29.548718 | 109 | 0.660708 | LoginLEE |
be157d8576d9ca5d82098886d9298f0c468cfbd9 | 1,553 | cpp | C++ | IntervalsList.cpp | alechh/test-opencv | ab82723e4f9dda88a63add60d5f28dda5a22bc73 | [
"Apache-2.0"
] | 1 | 2022-03-24T08:05:22.000Z | 2022-03-24T08:05:22.000Z | IntervalsList.cpp | alechh/test-opencv | ab82723e4f9dda88a63add60d5f28dda5a22bc73 | [
"Apache-2.0"
] | null | null | null | IntervalsList.cpp | alechh/test-opencv | ab82723e4f9dda88a63add60d5f28dda5a22bc73 | [
"Apache-2.0"
] | null | null | null | #include "IntervalsList.h"
#include <iostream>
/**
* Default constructor
*/
IntervalsList::IntervalsList()
{
head = nullptr;
tail = nullptr;
next = nullptr;
}
/**
* Destructor
*/
IntervalsList::~IntervalsList()
{
while (head != nullptr)
{
Interval* oldHead = head;
head = head->next;
delete oldHead;
}
}
/**
* Add interval to the list
* @param begin -- x coordinate of the begin of the new interval
* @param end -- x coordinate of the end of the new interval
* @param y_coordinate -- y coordinate of the new interval
* @param color -- the color of the cluster that the interval belongs to
*/
void IntervalsList::addInterval(int begin, int end, int y_coordinate, cv::Vec3b color)
{
if (head == nullptr)
{
head = new Interval(begin, end, y_coordinate, color);
tail = head;
return;
}
tail->next = new Interval(begin, end, y_coordinate, color);
tail = tail->next;
}
/**
* Add interval to the list
* @param newInterval -- Pointer to the interval
*/
void IntervalsList::addInterval(Interval *newInterval)
{
if (head == nullptr)
{
head = newInterval;
tail = head;
return;
}
tail->next = newInterval;
tail = tail->next;
}
/**
* Length of the list
* @return
*/
int IntervalsList::getLength()
{
if (this->head == nullptr)
{
return 0;
}
int res = 1;
Interval *temp = head;
while (temp->next != nullptr)
{
res++;
temp = temp->next;
}
return res;
}
| 19.17284 | 86 | 0.59369 | alechh |
be15ae8b056357a1e3842f6e767273f5e01852bd | 4,342 | hpp | C++ | nucleo-g431-akashi04-i2s/Core/Inc/murasaki_platform.hpp | suikan4github/murasaki_samples_audio | 30ce5bc821e529e3415c7983ed435dbacc9b1126 | [
"MIT"
] | 12 | 2019-02-24T05:22:37.000Z | 2021-10-01T05:56:59.000Z | nucleo-g431-akashi04-i2s/Core/Inc/murasaki_platform.hpp | suikan4github/murasaki_samples_audio | 30ce5bc821e529e3415c7983ed435dbacc9b1126 | [
"MIT"
] | 122 | 2019-02-23T13:51:42.000Z | 2021-11-13T01:24:34.000Z | nucleo-l412-64/Inc/murasaki_platform.hpp | suikan4github/murasaki_samples | f339c1bf555035f4416797e3938fbe25cc82414c | [
"MIT"
] | 3 | 2019-02-24T16:38:25.000Z | 2022-03-22T15:25:09.000Z | /**
* @file murasaki_platform.hpp
*
* @date 2017/11/12
* @author Seiichi "Suikan" Horie
* @brief An interface for the applicaiton from murasaki library to main.c
* @details
* The resources below are impremented in the murasaki_platform.cpp and serve as glue to the main.c.
*/
#ifndef MURASAKI_PLATFORM_HPP_
#define MURASAKI_PLATFORM_HPP_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
// Murasaki platform control
/**
* @brief Initialize the platform variables.
* @ingroup MURASAKI_PLATFORM_GROUP
* @details
* The murasaki::platform variable is an interface between the application program and HAL / RTOS.
* To use it correctly, the initialization is needed before any activity of murasaki client.
*
* @code
* void StartDefaultTask(void const * argument)
* {
* InitPlatform();
* ExecPlatform();
* }
* @endcode
*
* This function have to be invoked from the StartDefaultTask() of the main.c only once
* to initialize the platform variable.
*
*/
void InitPlatform();
/**
* @brief The body of the real application.
* @ingroup MURASAKI_PLATFORM_GROUP
* @details
* The body function of the murasaki application. Usually this function is called from
* the StartDefaultTask() of the main.c.
*
* This function is invoked only once, and never return. See @ref InitPlatform() as calling sample.
*
* By default, it toggles LED as sample program.
* This function can be customized freely.
*/
void ExecPlatform();
/**
* @brief Hook for the assert_failure() in main.c
* @ingroup MURASAKI_PLATFORM_GROUP
* @param file Name of the source file where assertion happen
* @param line Number of the line where assertion happen
* @details
* This routine provides a custom hook for the assertion inside STM32Cube HAL.
* All assertion raised in HAL will be redirected here.
*
* @code
* void assert_failed(uint8_t* file, uint32_t line)
* {
* CustomAssertFailed(file, line);
* }
* @endcode
* By default, this routine output a message with location informaiton
* to the debugger console.
*/
void CustomAssertFailed(uint8_t* file, uint32_t line);
/**
* @brief Hook for the default exception handler. Never return.
* @ingroup MURASAKI_PLATFORM_GROUP
* @details
* An entry of the exception. Especialy for the Hard Fault exception.
* In this function, the Stack pointer just before exception is retrieved
* and pass as the first parameter of the PrintFaultResult().
*
* Note : To print the correct information, this function have to be
* Jumped in from the exception entry without any data push to the stack.
* To avoid the pushing extra data to stack or making stack frame,
* Compile the program without debug information and with certain
* optimization leve, when you investigate the Hard Fault.
*
* For example, the start up code for the Nucleo-L152RE is startup_stml152xe.s.
* This file is generated by CubeIDE. This file has default handler as like this:
*
* @code
* .section .text.Default_Handler,"ax",%progbits
* Default_Handler:
* Infinite_Loop:
* b Infinite_Loop
* @endcode
*
* This code can be modified to call CustomDefaultHanler as like this :
* @code
* .global CustomDefaultHandler
* .section .text.Default_Handler,"ax",%progbits
* Default_Handler:
* bl CustomDefaultHandler
* Infinite_Loop:
* b Infinite_Loop
* @endcode
*
* While it is declared as function prototype, the CustomDefaultHandler is just a label.
* Do not call from user application.
*/
void CustomDefaultHandler();
/**
* @brief Printing out the context information.
* @param stack_pointer retrieved stack pointer before interrupt / exception.
* @details
* Do not call from application. This is murasaki_internal_only.
*
*/
void PrintFaultResult(unsigned int * stack_pointer);
/**
* @brief StackOverflow hook for FreeRTOS
* @param xTask Task ID which causes stack overflow.
* @param pcTaskName Name of the task which cuases stack overflow.
* @fn vApplicationStackOverflowHook
* @ingroup MURASAKI_PLATFORM_GROUP
*
* @details
* This function will be called from FreeRTOS when some task causes overflow.
* See TaskStrategy::getStackMinHeadroom() for details.
*
* Because this function prototype is declared by system,
* we don't have prototype in the murasaki_platform.hpp.
*/
#ifdef __cplusplus
}
#endif
#endif /* MURASAKI_PLATFORM_HPP_ */
| 30.363636 | 100 | 0.739982 | suikan4github |
be16f13425dc340b268540882541197a0db249a2 | 343 | cpp | C++ | src/filter_cells.cpp | LTLA/diet.scran | c274bf058e10c174a06a409af50fcad225d40f0d | [
"MIT"
] | null | null | null | src/filter_cells.cpp | LTLA/diet.scran | c274bf058e10c174a06a409af50fcad225d40f0d | [
"MIT"
] | null | null | null | src/filter_cells.cpp | LTLA/diet.scran | c274bf058e10c174a06a409af50fcad225d40f0d | [
"MIT"
] | null | null | null | #include "tatamize.h"
#include "scran/quality_control/FilterCells.hpp"
#include "Rcpp.h"
//[[Rcpp::export(rng=false)]]
SEXP filter_cells(SEXP x, Rcpp::LogicalVector discard) {
scran::FilterCells qc;
auto y = qc.run(extract_NumericMatrix_shared(x), static_cast<const int*>(discard.begin()));
return new_MatrixChan(std::move(y));
}
| 31.181818 | 95 | 0.723032 | LTLA |
be18722437b404c2701a0321ff7f681cac1ac88a | 1,777 | cpp | C++ | Prim's_Algorithm _for_MST.cpp | taareek/c-plus-plus | b9d04f710e9b2e65786618f8bbced4a56c149444 | [
"Unlicense"
] | null | null | null | Prim's_Algorithm _for_MST.cpp | taareek/c-plus-plus | b9d04f710e9b2e65786618f8bbced4a56c149444 | [
"Unlicense"
] | null | null | null | Prim's_Algorithm _for_MST.cpp | taareek/c-plus-plus | b9d04f710e9b2e65786618f8bbced4a56c149444 | [
"Unlicense"
] | null | null | null | #include<iostream>
#include<cstdlib>
#define a 9
using namespace std;
struct prims
{
int cost;
int parent;
bool visited;
};
void printGraph(int graph[a][a]){
for(int i=0; i<a; i++){
for(int j=0; j<a; j++){
cout<<graph[i][j]<<" ";
}
cout<<endl;
}
}
int find_min(struct prims arr[a]){
int least, index;
for(int i=0; i<a; i++){
if(arr[i].visited==false && arr[i].cost<least){
least= arr[i].cost;
index= i;
}
}
return index;
}
void prims_mst(int graph[a][a], struct prims arr[a]){
for(int m=0; m<a-1; m++){
int k= find_min(arr);
arr[k].visited= true;
for(int n=0; n<a; n++){
if(arr[n].visited!=true && graph[k][n]<arr[n].cost){
arr[n].parent= k;
arr[n].cost= graph[k][n];
}
}
}
for(int i=0; i<a; i++){
cout<<arr[i].parent<<"-> ";
}
}
int main(){
//Graph
int graph[a][a]= {
{ 0,4,0,0,0,0,0,8,0},
{ 4,0,8,0,0,0,0,11,0},
{ 0,8,0,7,0,4,0,2,0},
{ 0,0,7,0,9,14,0,0,0},
{ 0,0,0,9,0,10,0,0,0},
{ 0,0,4,14,10,0,2,0,0},
{ 0,0,0,0,0,2,0,1,6},
{ 8,11,0,0,0,0,1,0,7},
{ 0,0,2,0,0,0,6,7,0},
};
//Label Array
struct prims arr[a];
int INFINITY, m;
for(int i=0; i<a; i++){
arr[i].cost= INFINITY;
arr[i].parent= -1;
arr[i].visited= false;
}
int start;
//cout<<"Enter the node from which you want to start(0-8): ";
//cin>>start;
arr[0].cost=0;
//printGraph(graph);
cout<<endl;
prims_mst(graph, arr);
}
| 20.662791 | 66 | 0.420934 | taareek |
be1aa88cce90ce63ac8cd0d78f3045ee6dd9cdf8 | 12,230 | hpp | C++ | framework/areg/base/RuntimeClassID.hpp | Ali-Nasrolahi/areg-sdk | 4fbc2f2644220196004a31672a697a864755f0b6 | [
"Apache-2.0"
] | 70 | 2021-07-20T11:26:16.000Z | 2022-03-27T11:17:43.000Z | framework/areg/base/RuntimeClassID.hpp | Ali-Nasrolahi/areg-sdk | 4fbc2f2644220196004a31672a697a864755f0b6 | [
"Apache-2.0"
] | 32 | 2021-07-31T05:20:44.000Z | 2022-03-20T10:11:52.000Z | framework/areg/base/RuntimeClassID.hpp | Ali-Nasrolahi/areg-sdk | 4fbc2f2644220196004a31672a697a864755f0b6 | [
"Apache-2.0"
] | 40 | 2021-11-02T09:45:38.000Z | 2022-03-27T11:17:46.000Z | #pragma once
/************************************************************************
* This file is part of the AREG SDK core engine.
* AREG SDK is dual-licensed under Free open source (Apache version 2.0
* License) and Commercial (with various pricing models) licenses, depending
* on the nature of the project (commercial, research, academic or free).
* You should have received a copy of the AREG SDK license description in LICENSE.txt.
* If not, please contact to info[at]aregtech.com
*
* \copyright (c) 2017-2021 Aregtech UG. All rights reserved.
* \file areg/base/RuntimeClassID.hpp
* \ingroup AREG SDK, Asynchronous Event Generator Software Development Kit
* \author Artak Avetyan
* \brief AREG Platform, Runtime Class ID
* This class contains information of Runtime Class ID.
* Every Runtime Class contains class ID value to identify and
* cast instances of Runtime Object.
* As an ID of Runtime class used class name.
*
************************************************************************/
/************************************************************************
* Include files.
************************************************************************/
#include "areg/base/GEGlobal.h"
#include "areg/base/String.hpp"
#include <utility>
//////////////////////////////////////////////////////////////////////////
// RuntimeClassID class declaration
//////////////////////////////////////////////////////////////////////////
/**
* \brief Runtime Class ID is used in all objects derived from
* Runtime Objects. It contains the class ID, so that during
* runtime can check and cast the instance of Runtime Object.
* In particular, Runtime Object and Runtime Class ID are used
* in Threads, Events and other objects to check the instance
* of object during runtime.
*
* \see RuntimeObject
**/
class AREG_API RuntimeClassID
{
/************************************************************************
* friend classes to access default constructor.
************************************************************************/
/**
* \brief Declare friend classes to access private default constructor
* required to initialize runtime class ID in hash map blocks.
**/
template < typename KEY, typename VALUE, typename KEY_TYPE, typename VALUE_TYPE, class Implement >
friend class TEHashMap;
template <typename RESOURCE_KEY, typename RESOURCE_OBJECT, class HashMap, class Implement>
friend class TEResourceMap;
//////////////////////////////////////////////////////////////////////////
// Static members
//////////////////////////////////////////////////////////////////////////
public:
/**
* \brief Static function to create empty Runtime Class ID object.
* By default, the class ID value is BAD_CLASS_ID.
* Change the value after creating class ID object.
**/
static inline RuntimeClassID createEmptyClassID( void );
//////////////////////////////////////////////////////////////////////////
// Constructors / Destructor
//////////////////////////////////////////////////////////////////////////
public:
/**
* \brief Initialization constructor.
* This constructor is initializing the name Runtime Class ID
* \param className The name of Runtime Class ID
**/
explicit RuntimeClassID( const char * className );
/**
* \brief Copy constructor.
* \param src The source to copy data.
**/
RuntimeClassID( const RuntimeClassID & src );
/**
* \brief Move constructor.
* \param src The source to move data.
**/
RuntimeClassID( RuntimeClassID && src ) noexcept;
/**
* \brief Destructor
**/
~RuntimeClassID( void ) = default;
//////////////////////////////////////////////////////////////////////////
// Operators
//////////////////////////////////////////////////////////////////////////
public:
/************************************************************************/
// friend global operators
/************************************************************************/
/**
* \brief Compares null-terminated string with Runtime Class ID name.
* \param lhs Left-Hand Operand, string to compare.
* \param rhs Right-Hand Operand, Runtime Class ID to compare the name.
* \return Returns true if string is equal to Runtime Class ID.
**/
friend inline bool operator == ( const char * lhs, const RuntimeClassID & rhs );
/**
* \brief Compare null-terminated string with Runtime Class ID name.
* \param lhs Left-Hand Operand, string to compare.
* \param rhs Right-Hand Operand, Runtime Class to compare the name.
* \return Returns true if string is not equal to Runtime Class ID.
**/
friend inline bool operator != ( const char * lhs, const RuntimeClassID & rhs );
/**
* \brief Compares number with Runtime Class ID calculated number.
* \param lhs Left-Hand Operand, number to compare.
* \param rhs Right-Hand Operand, Runtime Class ID to compare the calculated number.
* \return Returns true if number is equal to Runtime Class ID.
**/
friend inline bool operator == ( unsigned int lhs, const RuntimeClassID & rhs );
/**
* \brief Compares number with Runtime Class ID calculated number.
* \param lhs Left-Hand Operand, number to compare.
* \param rhs Right-Hand Operand, Runtime Class ID to compare the calculated number.
* \return Returns true if number is not equal to Runtime Class ID.
**/
friend inline bool operator != ( unsigned int lhs, const RuntimeClassID & rhs );
/************************************************************************/
// class members operators
/************************************************************************/
/**
* \brief Assigning operator. Copies Runtime Class ID name from given Runtime Class ID source
* \param src The source of Runtime Class ID to copy.
* \return Returns Runtime Class ID object.
**/
inline RuntimeClassID & operator = ( const RuntimeClassID & src );
/**
* \brief Move operator. Moves Runtime Class ID name from given Runtime Class ID source.
* \param src The source of Runtime Class ID to move.
* \return Returns Runtime Class ID object.
**/
inline RuntimeClassID & operator = ( RuntimeClassID && src ) noexcept;
/**
* \brief Assigning operator. Copies Runtime Class ID name from given string buffer source
* \param src The source of string buffer to copy.
* \return Returns Runtime Class ID object.
**/
inline RuntimeClassID & operator = ( const char * src );
/**
* \brief Assigning operator. Copies Runtime Class ID name from given string source
* \param src The source of string to copy.
* \return Returns Runtime Class ID object.
**/
inline RuntimeClassID & operator = ( const String & src );
/**
* \brief Comparing operator. Compares 2 Runtime Class ID objects.
* \param other The Runtime Class ID object to compare
* \return Returns true if 2 instance of Runtime Class ID have same Class ID value.
**/
inline bool operator == ( const RuntimeClassID & other ) const;
/**
* \brief Comparing operator. Compares Runtime Class ID and string.
* \param other The null-terminated string to compare
* \return Returns true if Runtime Class ID value is equal to null-terminated string.
**/
inline bool operator == ( const char * other ) const;
/**
* \brief Comparing operator. Compares 2 Runtime Class ID objects.
* \param other The Runtime Class ID object to compare
* \return Returns true if 2 instance of Runtime Class ID have different Class ID values.
**/
inline bool operator != ( const RuntimeClassID & other ) const;
/**
* \brief Comparing operator. Compares Runtime Class ID and string.
* \param other The null-terminated string to compare
* \return Returns true if Runtime Class ID value is not equal to given null-terminated string.
**/
inline bool operator != (const char * other) const;
/**
* \brief Operator to convert the value or Runtime Class ID to unsigned integer value.
* Used to calculate hash value in hash map
**/
inline explicit operator unsigned int ( void ) const;
//////////////////////////////////////////////////////////////////////////
// Attributes
//////////////////////////////////////////////////////////////////////////
/**
* \brief Returns true if the value of Runtime Class ID is not equal to RuntimeClassID::BAD_CLASS_ID.
**/
inline bool isValid( void ) const;
/**
* \brief Returns the name of Runtime Class ID.
**/
inline const char * getName( void ) const;
/**
* \brief Sets the name of Runtime Class ID.
**/
void setName( const char * className );
/**
* \brief Returns calculated number of runtime class.
**/
inline unsigned getMagic( void ) const;
//////////////////////////////////////////////////////////////////////////
// Hidden methods
//////////////////////////////////////////////////////////////////////////
private:
/**
* \brief Default constructor. Private. Will create BAD_CLASS_ID
* object.
**/
RuntimeClassID( void );
//////////////////////////////////////////////////////////////////////////
// Member variables
//////////////////////////////////////////////////////////////////////////
private:
/**
* \brief Runtime Class ID value.
**/
String mClassName;
/**
* \brief The calculated number of runtime class.
**/
unsigned int mMagicNum;
};
//////////////////////////////////////////////////////////////////////////
// RuntimeClassID class inline function implementation
//////////////////////////////////////////////////////////////////////////
inline RuntimeClassID RuntimeClassID::createEmptyClassID( void )
{
return RuntimeClassID();
}
inline RuntimeClassID & RuntimeClassID::operator = ( const RuntimeClassID & src )
{
this->mClassName= src.mClassName;
this->mMagicNum = src.mMagicNum;
return (*this);
}
inline RuntimeClassID & RuntimeClassID::operator = ( RuntimeClassID && src ) noexcept
{
this->mClassName= std::move(src.mClassName);
this->mMagicNum = src.mMagicNum;
return (*this);
}
inline RuntimeClassID & RuntimeClassID::operator = ( const char * src )
{
setName(src);
return (*this);
}
inline RuntimeClassID & RuntimeClassID::operator = ( const String & src )
{
setName(src);
return (*this);
}
inline bool RuntimeClassID::operator == ( const RuntimeClassID & other ) const
{
return (mMagicNum == other.mMagicNum);
}
inline bool RuntimeClassID::operator == ( const char * other ) const
{
return mClassName == other;
}
inline bool RuntimeClassID::operator != ( const RuntimeClassID & other ) const
{
return (mMagicNum != other.mMagicNum);
}
inline bool RuntimeClassID::operator != ( const char* other ) const
{
return mClassName != other;
}
inline RuntimeClassID::operator unsigned int ( void ) const
{
return mMagicNum;
}
inline bool RuntimeClassID::isValid( void ) const
{
return (mMagicNum != NEMath::CHECKSUM_IGNORE);
}
inline const char* RuntimeClassID::getName( void ) const
{
return mClassName.getString();
}
inline unsigned RuntimeClassID::getMagic(void) const
{
return mMagicNum;
}
inline bool operator == ( const char * lhs, const RuntimeClassID & rhs )
{
return rhs.mClassName == lhs;
}
inline bool operator != ( const char* lhs, const RuntimeClassID & rhs )
{
return rhs.mClassName != lhs;
}
inline bool operator == ( unsigned int lhs, const RuntimeClassID & rhs )
{
return rhs.mMagicNum == lhs;
}
inline bool operator != ( unsigned int lhs, const RuntimeClassID & rhs )
{
return rhs.mMagicNum != lhs;
}
| 35.865103 | 107 | 0.553802 | Ali-Nasrolahi |
be1ec1f0e46485e8f7775cc784e8d2d64e8b2c98 | 1,200 | cpp | C++ | RLSimion/CNTKWrapper/InputData.cpp | xcillero001/SimionZoo | b343b08f3356e1aa230d4132b0abb58aac4c5e98 | [
"MIT"
] | 1 | 2019-02-21T10:40:28.000Z | 2019-02-21T10:40:28.000Z | RLSimion/CNTKWrapper/InputData.cpp | JosuGom3z/SimionZoo | b343b08f3356e1aa230d4132b0abb58aac4c5e98 | [
"MIT"
] | null | null | null | RLSimion/CNTKWrapper/InputData.cpp | JosuGom3z/SimionZoo | b343b08f3356e1aa230d4132b0abb58aac4c5e98 | [
"MIT"
] | null | null | null | #include "InputData.h"
#include "xmltags.h"
#include "ParameterValues.h"
#include "CNTKWrapperInternals.h"
#include "Exceptions.h"
InputData::InputData(tinyxml2::XMLElement * pParentNode)
{
m_id = pParentNode->Attribute(XML_ATTRIBUTE_Id);
if (m_id.empty())
throw ProblemParserElementNotFound(XML_ATTRIBUTE_Id);
m_name = pParentNode->Attribute(XML_ATTRIBUTE_Name);
if (m_name.empty())
m_name = "InputData";
tinyxml2::XMLElement* pNode = pParentNode->FirstChildElement(XML_TAG_Shape);
if (pNode == nullptr)
throw ProblemParserElementNotFound(XML_TAG_Shape);
m_pShape = CIntTuple::getInstance(pNode);
}
InputData::InputData(string id, CNTK::Variable pInputVariable)
{
m_id = id;
m_inputVariable = pInputVariable;
}
InputData::~InputData()
{
}
InputData * InputData::getInstance(tinyxml2::XMLElement * pNode)
{
if (!strcmp(pNode->Name(), XML_TAG_InputData))
return new InputData(pNode);
return nullptr;
}
NDShape InputData::getNDShape()
{
return m_pShape->getNDShape();
}
void InputData::createInputVariable()
{
m_isInitialized = true;
m_inputVariable = CNTK::InputVariable(m_pShape->getNDShape(), CNTK::DataType::Double, CNTKWrapper::Internal::string2wstring(m_id));
}
| 22.222222 | 132 | 0.758333 | xcillero001 |
be2028dd6194d28f16be8bda33256e006569f045 | 14,138 | cpp | C++ | private/src/diagnostic/IasDiagnosticStream.cpp | juimonen/SmartXbar | 033f521a5dba5bce5e097df9c98af5b2cc2636dd | [
"BSD-3-Clause"
] | 5 | 2018-11-05T07:37:58.000Z | 2022-03-04T06:40:09.000Z | private/src/diagnostic/IasDiagnosticStream.cpp | juimonen/SmartXbar | 033f521a5dba5bce5e097df9c98af5b2cc2636dd | [
"BSD-3-Clause"
] | null | null | null | private/src/diagnostic/IasDiagnosticStream.cpp | juimonen/SmartXbar | 033f521a5dba5bce5e097df9c98af5b2cc2636dd | [
"BSD-3-Clause"
] | 7 | 2018-12-04T07:32:19.000Z | 2021-02-17T11:28:28.000Z | /*
* Copyright (C) 2018 Intel Corporation.All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
/**
* File: IasDiagnosticStream.cpp
*/
#include <assert.h>
#include <ctime>
#include <cstdio>
#include <algorithm>
#include <chrono>
#include "diagnostic/IasDiagnosticStream.hpp"
#include "diagnostic/IasDiagnosticLogWriter.hpp"
namespace IasAudio {
#define TMP_PATH "/tmp/"
static const std::string cClassName = "IasDiagnosticStream::";
#define LOG_PREFIX cClassName + __func__ + "(" + std::to_string(__LINE__) + "):"
#define LOG_DEVICE "device=" + mParams.deviceName + ":"
#define LOG_STATE "[" + toString(mStreamState) + "]"
IasDiagnosticStream::IasDiagnosticStream(const struct IasParams& params, IasDiagnosticLogWriter& logWriter)
:mLog(IasAudioLogging::registerDltContext("AHD", "ALSA Handler"))
,mLogThread(IasAudioLogging::registerDltContext("AHDD", "ALSA Handler Diagnostic File Operations Thread"))
,mParams(params)
,mPeriodCounter(0)
,mMaxCounter(0)
,mTmpFile()
,mTmpFileName()
,mTmpFileNameFull()
,mStreamState(eIasStreamStateIdle)
,mStreamStateMutex()
,mFileOpen()
,mFileClose()
,mCondWaitForStart()
,mMutexWaitForStart()
,mStreamStarted(false)
,mErrorCounter(0)
,mLogWriter(logWriter)
,mFileIdx(0)
{
if (mParams.periodTime == 0)
{
// Set default to 5333us
mParams.periodTime = 5333;
}
std::uint32_t bytesPerSecond = cBytesPerPeriod * 1000 * 1000 / mParams.periodTime;
std::uint32_t bytesPerHour = bytesPerSecond * 60 * 60;
mMaxCounter = bytesPerHour / cBytesPerPeriod;
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_DEVICE, "Maximum bytes recorded per hour=", bytesPerHour, "maximum counter=", mMaxCounter);
}
IasDiagnosticStream::~IasDiagnosticStream()
{
changeState(IasTriggerStateChange::eIasStop);
isStopped(); // this call really waits until the stream is stopped and the file is closed
if (mFileOpen.joinable())
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, "File open thread will be joined now");
mFileOpen.join();
}
if (mFileClose.joinable())
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, "File close thread will be joined now");
mFileClose.join();
}
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX);
}
void IasDiagnosticStream::writeAlsaHandlerData(std::uint64_t timestampDeviceBuffer, std::uint64_t numTransmittedFramesDevice, std::uint64_t timestampAsrcBuffer, std::uint64_t numTransmittedFramesAsrc, std::uint32_t asrcBufferNumFramesAvailable, std::uint32_t numTotalFrames, std::float_t ratioAdaptive)
{
if (mStreamState != eIasStreamStateStarted)
{
DLT_LOG_CXX(*mLog, DLT_LOG_VERBOSE, LOG_PREFIX, LOG_STATE, "Stream not started yet");
return;
}
DLT_LOG_CXX(*mLog, DLT_LOG_VERBOSE, LOG_PREFIX, "Writing data to file, period #", mPeriodCounter);
char tmpBuffer[cBytesPerPeriod];
std::uint64_t* ptr_ui64 = reinterpret_cast<std::uint64_t*>(tmpBuffer);
*ptr_ui64++ = timestampDeviceBuffer;
*ptr_ui64++ = numTransmittedFramesDevice;
*ptr_ui64++ = timestampAsrcBuffer;
*ptr_ui64++ = numTransmittedFramesAsrc;
std::uint32_t* ptr_ui32 = reinterpret_cast<std::uint32_t*>(ptr_ui64);
*ptr_ui32++ = asrcBufferNumFramesAvailable;
*ptr_ui32++ = numTotalFrames;
std::float_t* ptr_float = reinterpret_cast<std::float_t*>(ptr_ui32);
*ptr_float = ratioAdaptive;
mTmpFile.write(tmpBuffer, cBytesPerPeriod);
++mPeriodCounter;
if (mPeriodCounter > mMaxCounter)
{
mPeriodCounter = 0;
changeState(eIasStop);
}
}
IasDiagnosticStream::IasResult IasDiagnosticStream::startStream()
{
IasStreamState newState = changeState(eIasStart);
if ((newState == eIasStreamStateOpening) || (newState == eIasStreamStatePendingOpen))
{
return IasResult::eIasOk;
}
else
{
return IasResult::eIasFailed;
}
}
IasDiagnosticStream::IasResult IasDiagnosticStream::stopStream()
{
IasStreamState newState = changeState(eIasStop);
if ((newState == eIasStreamStateClosing) || (newState == eIasStreamStatePendingClose))
{
return IasResult::eIasOk;
}
else
{
return IasResult::eIasFailed;
}
}
IasDiagnosticStream::IasStreamState IasDiagnosticStream::changeState(IasTriggerStateChange trigger)
{
std::lock_guard<std::mutex> lock(mStreamStateMutex);
switch (mStreamState)
{
case eIasStreamStateIdle:
if (trigger == IasTriggerStateChange::eIasStart)
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Trigger=", toString(trigger), ". New state=", toString(eIasStreamStateOpening));
mStreamState = eIasStreamStateOpening;
if (mFileOpen.joinable())
{
mFileOpen.join();
}
mFileOpen = std::thread(&IasDiagnosticStream::openFile, this);
}
else
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Ignoring trigger", toString(trigger));
}
break;
case eIasStreamStateStarted:
if (trigger == IasTriggerStateChange::eIasStop)
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Trigger=", toString(trigger), ". New state=", toString(eIasStreamStateClosing));
mStreamState = eIasStreamStateClosing;
if (mFileClose.joinable())
{
mFileClose.join();
}
mFileClose = std::thread(&IasDiagnosticStream::closeFile, this);
}
else
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Ignoring trigger", toString(trigger));
}
break;
case eIasStreamStateOpening:
if (trigger == IasTriggerStateChange::eIasOpeningFinished)
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Trigger=", toString(trigger), ". New state=", toString(eIasStreamStateStarted));
mStreamState = eIasStreamStateStarted;
{
std::lock_guard<std::mutex> lk(mMutexWaitForStart);
mStreamStarted = true;
}
mCondWaitForStart.notify_one();
}
else if (trigger == IasTriggerStateChange::eIasStop)
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Trigger=", toString(trigger), ". New state=", toString(eIasStreamStatePendingClose));
mStreamState = eIasStreamStatePendingClose;
}
else
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Ignoring trigger", toString(trigger));
}
break;
case eIasStreamStatePendingClose:
if (trigger == IasTriggerStateChange::eIasOpeningFinished)
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Trigger=", toString(trigger), ". New state=", toString(eIasStreamStateClosing));
mStreamState = eIasStreamStateClosing;
{
std::lock_guard<std::mutex> lk(mMutexWaitForStart);
mStreamStarted = true;
}
mCondWaitForStart.notify_one();
if (mFileClose.joinable())
{
mFileClose.join();
}
mFileClose = std::thread(&IasDiagnosticStream::closeFile, this);
}
else
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Ignoring trigger", toString(trigger));
}
break;
case eIasStreamStateClosing:
if (trigger == IasTriggerStateChange::eIasClosingFinished)
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Trigger=", toString(trigger), ". New state=", toString(eIasStreamStateIdle));
mStreamState = eIasStreamStateIdle;
{
std::lock_guard<std::mutex> lk(mMutexWaitForStart);
mStreamStarted = false;
}
mCondWaitForStart.notify_one();
}
else if (trigger == IasTriggerStateChange::eIasStart)
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Trigger=", toString(trigger), ". New state=", toString(eIasStreamStatePendingOpen));
mStreamState = eIasStreamStatePendingOpen;
}
else
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Ignoring trigger", toString(trigger));
}
break;
case eIasStreamStatePendingOpen:
if (trigger == IasTriggerStateChange::eIasClosingFinished)
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Trigger=", toString(trigger), ". New state=", toString(eIasStreamStateOpening));
mStreamState = eIasStreamStateOpening;
{
std::lock_guard<std::mutex> lk(mMutexWaitForStart);
mStreamStarted = false;
}
mCondWaitForStart.notify_one();
if (mFileOpen.joinable())
{
mFileOpen.join();
}
mFileOpen = std::thread(&IasDiagnosticStream::openFile, this);
}
else if (trigger == IasTriggerStateChange::eIasStop)
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Trigger=", toString(trigger), ". New state=", toString(eIasStreamStatePendingClose));
mStreamState = eIasStreamStatePendingClose;
}
else
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, LOG_STATE, "Ignoring trigger", toString(trigger));
}
break;
}
return mStreamState;
}
void IasDiagnosticStream::openFile()
{
if (mTmpFile.is_open() == false)
{
std::time_t t = std::time(nullptr);
std::tm* tm = std::localtime(&t);
char currentTime[20] = {'\0'};
if (tm != nullptr)
{
std::strftime(currentTime, sizeof(currentTime), "%T", tm);
}
mTmpFileName = std::string(currentTime) + "_" + mParams.deviceName + "_asrc_diag_" + std::to_string(mFileIdx) + ".bin";
mFileIdx++;
// Replace all commas with underscore to have a cleaner filename
std::replace(mTmpFileName.begin(), mTmpFileName.end(), ',', '_');
mTmpFileNameFull = std::string(TMP_PATH) + mTmpFileName;
DLT_LOG_CXX(*mLogThread, DLT_LOG_INFO, LOG_PREFIX, "Opening tmp file", mTmpFileNameFull, "for writing diagnostic log");
mTmpFile.open(mTmpFileNameFull, std::ios::binary|std::ios::out|std::ios::trunc);
mErrorCounter = 0;
}
changeState(eIasOpeningFinished);
}
void IasDiagnosticStream::closeFile()
{
if (mTmpFile.is_open())
{
std::uint32_t fileSize = static_cast<std::uint32_t>(mTmpFile.tellp());
DLT_LOG_CXX(*mLogThread, DLT_LOG_INFO, LOG_PREFIX, mTmpFileNameFull, "file size=", fileSize);
mTmpFile.close();
}
DLT_LOG_CXX(*mLogThread, DLT_LOG_INFO, LOG_PREFIX, "Closing file", mTmpFileNameFull, "finished");
bool writeToLog = false;
if (mParams.copyTo.compare("log") == 0)
{
writeToLog = true;
}
if (mErrorCounter >= mParams.errorThreshold)
{
if (writeToLog)
{
mLogWriter.addFile(mTmpFileNameFull);
}
else
{
copyFile();
}
}
else
{
std::remove(mTmpFileNameFull.c_str());
DLT_LOG_CXX(*mLogThread, DLT_LOG_INFO, LOG_PREFIX, "Removed", mTmpFileNameFull);
}
mErrorCounter = 0;
changeState(eIasClosingFinished);
}
void IasDiagnosticStream::copyFile()
{
std::ofstream dstFile;
std::ifstream srcFile;
std::string dstFileName = mParams.copyTo;
if (dstFileName.back() != '/')
{
dstFileName.append("/");
}
dstFileName += mTmpFileName;
DLT_LOG_CXX(*mLogThread, DLT_LOG_INFO, LOG_PREFIX, "Copying from", mTmpFileNameFull, "to", dstFileName);
dstFile.open(dstFileName, std::ios::binary|std::ios::out|std::ios::trunc);
if (dstFile.is_open())
{
srcFile.open(mTmpFileNameFull, std::ios::binary);
dstFile<<srcFile.rdbuf();
srcFile.close();
dstFile.close();
DLT_LOG_CXX(*mLogThread, DLT_LOG_INFO, LOG_PREFIX, "Copying from", mTmpFileNameFull, "to", dstFileName, "finished successfully.");
}
else
{
DLT_LOG_CXX(*mLogThread, DLT_LOG_ERROR, LOG_PREFIX, "Destination file", dstFileName, "couldn't be created");
}
std::remove(mTmpFileNameFull.c_str());
DLT_LOG_CXX(*mLogThread, DLT_LOG_INFO, LOG_PREFIX, "Removed", mTmpFileNameFull);
}
bool IasDiagnosticStream::isStarted()
{
std::unique_lock<std::mutex> lk(mMutexWaitForStart);
bool status = mCondWaitForStart.wait_for(lk, std::chrono::seconds(1), [this] { return mStreamStarted == true; });
if (status == true)
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, "Stream is started");
}
else
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, "Stream is not started after timeout of 1s");
}
return status;
}
bool IasDiagnosticStream::isStopped()
{
std::unique_lock<std::mutex> lk(mMutexWaitForStart);
bool status = mCondWaitForStart.wait_for(lk, std::chrono::seconds(1), [this] { return mStreamStarted == false; });
if (status == true)
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, "Stream is stopped");
}
else
{
DLT_LOG_CXX(*mLog, DLT_LOG_INFO, LOG_PREFIX, "Stream is not stopped after timeout of 1s");
}
return status;
}
void IasDiagnosticStream::errorOccurred()
{
++mErrorCounter;
}
#define STRING_RETURN_CASE(name) case name: return std::string(#name); break
#define DEFAULT_STRING(name) default: return std::string(name)
std::string IasDiagnosticStream::toString(const IasStreamState& streamState)
{
switch(streamState)
{
STRING_RETURN_CASE(IasDiagnosticStream::IasStreamState::eIasStreamStateIdle);
STRING_RETURN_CASE(IasDiagnosticStream::IasStreamState::eIasStreamStateStarted);
STRING_RETURN_CASE(IasDiagnosticStream::IasStreamState::eIasStreamStateOpening);
STRING_RETURN_CASE(IasDiagnosticStream::IasStreamState::eIasStreamStateClosing);
STRING_RETURN_CASE(IasDiagnosticStream::IasStreamState::eIasStreamStatePendingClose);
STRING_RETURN_CASE(IasDiagnosticStream::IasStreamState::eIasStreamStatePendingOpen);
DEFAULT_STRING("Invalid IasStreamState => " + std::to_string(streamState));
}
}
std::string IasDiagnosticStream::toString(const IasTriggerStateChange& trigger)
{
switch(trigger)
{
STRING_RETURN_CASE(IasDiagnosticStream::IasTriggerStateChange::eIasStart);
STRING_RETURN_CASE(IasDiagnosticStream::IasTriggerStateChange::eIasStop);
STRING_RETURN_CASE(IasDiagnosticStream::IasTriggerStateChange::eIasOpeningFinished);
STRING_RETURN_CASE(IasDiagnosticStream::IasTriggerStateChange::eIasClosingFinished);
DEFAULT_STRING("Invalid IasTriggerStateChange => " + std::to_string(trigger));
}
}
} /* namespace IasAudio */
| 33.742243 | 302 | 0.698331 | juimonen |
be25620a6c09d51fbd97664e0d6e263b4fb04e7f | 130 | cpp | C++ | src/modules/vmount/vmount.cpp | Diksha-agg/Firmware_val | 1efc1ba06997d19df3ed9bd927cfb24401b0fe03 | [
"BSD-3-Clause"
] | null | null | null | src/modules/vmount/vmount.cpp | Diksha-agg/Firmware_val | 1efc1ba06997d19df3ed9bd927cfb24401b0fe03 | [
"BSD-3-Clause"
] | null | null | null | src/modules/vmount/vmount.cpp | Diksha-agg/Firmware_val | 1efc1ba06997d19df3ed9bd927cfb24401b0fe03 | [
"BSD-3-Clause"
] | null | null | null | version https://git-lfs.github.com/spec/v1
oid sha256:c3585e2db12c3926546d8188a694cd568aa96746e1589110d909fb4649296d1f
size 18247
| 32.5 | 75 | 0.884615 | Diksha-agg |
be2927dafaa6379e3f2fe1a3f64700e9781ce4ed | 981 | cpp | C++ | examples/gpds/main.cpp | Tectu/cpp-properties | b56a5ae13a21a3d8569cce9290d8d8befae15f3f | [
"MIT"
] | 9 | 2021-01-08T11:44:14.000Z | 2021-09-05T13:48:35.000Z | examples/gpds/main.cpp | Tectu/cpp-properties | b56a5ae13a21a3d8569cce9290d8d8befae15f3f | [
"MIT"
] | 4 | 2021-01-07T22:32:41.000Z | 2021-09-14T20:08:04.000Z | examples/gpds/main.cpp | Tectu/cpp-properties | b56a5ae13a21a3d8569cce9290d8d8befae15f3f | [
"MIT"
] | 1 | 2021-03-04T06:28:20.000Z | 2021-03-04T06:28:20.000Z | #include <iostream>
#include <gpds/container.hpp>
#include <gpds/archiver_xml.hpp>
#include "cppproperties/properties.hpp"
#include "cppproperties/archiver_gpds.hpp"
struct shape :
tct::properties::properties
{
MAKE_PROPERTY(locked, bool);
MAKE_PROPERTY(x, int);
MAKE_PROPERTY(y, int);
MAKE_PROPERTY(name, std::string);
};
int main()
{
shape s;
s.locked = false;
s.x = 24;
s.y = 48;
s.name = "My Shape";
s.set_attribute("foobar", "zbar");
s.name.set_attribute("name-attr", "test1234");
tct::properties::archiver_gpds ar;
const gpds::container& c = ar.save(s);
std::stringstream ss;
gpds::archiver_xml gpds_ar;
gpds_ar.save(ss, c, "properties");
gpds::container gpds_c;
gpds_ar.load(ss, gpds_c, "properties");
shape s2;
ar.load(s2, gpds_c);
std::cout << s2.locked << "\n";
std::cout << s2.x << "\n";
std::cout << s2.y << "\n";
std::cout << s2.name << "\n";
return 0;
}
| 20.87234 | 50 | 0.610601 | Tectu |
be2c2fafa2b3aed8c193c6c1bf55d2fdb5f05f13 | 965 | cpp | C++ | Medium/19_Remove_Nth_Node_From_End_of_List.cpp | Napolean28/leet | 80854c24a9549cc665bddc8e87489bd4b550a00d | [
"MIT"
] | 1 | 2019-12-24T19:41:34.000Z | 2019-12-24T19:41:34.000Z | Medium/19_Remove_Nth_Node_From_End_of_List.cpp | Napolean28/leet | 80854c24a9549cc665bddc8e87489bd4b550a00d | [
"MIT"
] | null | null | null | Medium/19_Remove_Nth_Node_From_End_of_List.cpp | Napolean28/leet | 80854c24a9549cc665bddc8e87489bd4b550a00d | [
"MIT"
] | 1 | 2019-12-23T10:20:00.000Z | 2019-12-23T10:20:00.000Z | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
int getLen(ListNode* head){
int len = 0;
while(head != NULL){
len++;
head = head->next;
}
return len;
}
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(head == NULL) return head;
int len = getLen(head);
n = len - n + 1;
int cur_node_id = 0;
ListNode* head_keep;
head_keep = head;
if(n == 1){
head = head->next;
return head;
}
while(head_keep != NULL){
cur_node_id++;
if(cur_node_id + 1 == n){
head_keep->next = head_keep->next->next;
break;
}
head_keep = head_keep->next;
}
return head;
}
}; | 22.44186 | 56 | 0.448705 | Napolean28 |
be3001675b70a04f35feab7ee872b2a8bbfadc18 | 7,011 | cpp | C++ | src/core/postprocessing/backbuffer_resolver.cpp | SleepKiller/swbfii-shaderpatch | b49ce3349d4dd09b19237ff4766652166ba1ffd4 | [
"MIT"
] | 5 | 2018-03-02T04:02:39.000Z | 2018-08-07T19:36:50.000Z | src/core/postprocessing/backbuffer_resolver.cpp | SleepKiller/swbfii-shaderpatch | b49ce3349d4dd09b19237ff4766652166ba1ffd4 | [
"MIT"
] | 27 | 2018-03-10T20:37:38.000Z | 2018-10-08T11:10:34.000Z | src/core/postprocessing/backbuffer_resolver.cpp | SleepKiller/swbfii-shaderpatch | b49ce3349d4dd09b19237ff4766652166ba1ffd4 | [
"MIT"
] | null | null | null |
#include "backbuffer_resolver.hpp"
#include "../d3d11_helpers.hpp"
#include <DirectXTex.h>
namespace sp::core::postprocessing {
Backbuffer_resolver::Backbuffer_resolver(Com_ptr<ID3D11Device5> device,
shader::Database& shaders)
: _resolve_vs{std::get<0>(
shaders.vertex("late_backbuffer_resolve"sv).entrypoint("main_vs"sv))},
_resolve_ps{shaders.pixel("late_backbuffer_resolve"sv).entrypoint("main_ps"sv)},
_resolve_ps_x2{
shaders.pixel("late_backbuffer_resolve"sv).entrypoint("main_x2_ps"sv)},
_resolve_ps_x4{
shaders.pixel("late_backbuffer_resolve"sv).entrypoint("main_x4_ps"sv)},
_resolve_ps_x8{
shaders.pixel("late_backbuffer_resolve"sv).entrypoint("main_x8_ps"sv)},
_resolve_ps_linear{
shaders.pixel("late_backbuffer_resolve"sv).entrypoint("main_linear_ps"sv)},
_resolve_ps_linear_x2{
shaders.pixel("late_backbuffer_resolve"sv).entrypoint("main_linear_x2_ps"sv)},
_resolve_ps_linear_x4{
shaders.pixel("late_backbuffer_resolve"sv).entrypoint("main_linear_x4_ps"sv)},
_resolve_ps_linear_x8{
shaders.pixel("late_backbuffer_resolve"sv).entrypoint("main_linear_x8_ps"sv)},
_resolve_cb{
create_dynamic_constant_buffer(*device, sizeof(std::array<std::uint32_t, 4>))}
{
}
void Backbuffer_resolver::apply(ID3D11DeviceContext1& dc, const Input input,
const Flags flags, Swapchain& swapchain,
const Interfaces interfaces) noexcept
{
if (DirectX::MakeTypeless(input.format) == DirectX::MakeTypeless(Swapchain::format)) {
apply_matching_format(dc, input, flags, swapchain, interfaces);
}
else {
apply_mismatch_format(dc, input, flags, swapchain, interfaces);
}
}
void Backbuffer_resolver::apply_matching_format(ID3D11DeviceContext1& dc,
const Input& input, const Flags flags,
Swapchain& swapchain,
const Interfaces& interfaces) noexcept
{
const bool msaa_input = input.sample_count > 1;
const bool want_post_aa = flags.use_cmma2;
// Fast Path for MSAA only.
if (msaa_input && !want_post_aa) {
dc.ResolveSubresource(swapchain.texture(), 0, &input.texture, 0, input.format);
return;
}
if (flags.use_cmma2) {
interfaces.cmaa2.apply(dc, interfaces.profiler,
{.input = input.srv,
.output = *input.uav,
.width = input.width,
.height = input.height});
}
dc.CopyResource(swapchain.texture(), &input.texture);
}
void Backbuffer_resolver::apply_mismatch_format(ID3D11DeviceContext1& dc,
const Input& input, const Flags flags,
Swapchain& swapchain,
const Interfaces& interfaces) noexcept
{
[[maybe_unused]] const bool msaa_input = input.sample_count > 1;
const bool want_post_aa = flags.use_cmma2;
// Fast Path for no post AA.
if (!want_post_aa) {
resolve_input(dc, input, flags, interfaces, *swapchain.rtv());
return;
}
if (flags.use_cmma2) {
auto cmma_target = interfaces.rt_allocator.allocate(
{.format = DXGI_FORMAT_R8G8B8A8_TYPELESS,
.width = input.width,
.height = input.height,
.bind_flags = effects::rendertarget_bind_srv_rtv_uav,
.srv_format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB,
.rtv_format = DXGI_FORMAT_R8G8B8A8_UNORM,
.uav_format = DXGI_FORMAT_R8G8B8A8_UNORM});
resolve_input(dc, input, flags, interfaces, *cmma_target.rtv());
interfaces.cmaa2.apply(dc, interfaces.profiler,
{.input = *cmma_target.srv(),
.output = *cmma_target.uav(),
.width = input.width,
.height = input.height});
dc.CopyResource(swapchain.texture(), &cmma_target.texture());
return;
}
log_and_terminate("Failed to resolve backbuffer! This should never happen.");
}
void Backbuffer_resolver::resolve_input(ID3D11DeviceContext1& dc,
const Input& input, const Flags flags,
const Interfaces& interfaces,
ID3D11RenderTargetView& target) noexcept
{
effects::Profile profile{interfaces.profiler, dc, "Backbuffer Resolve"};
dc.ClearState();
dc.IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
dc.VSSetShader(_resolve_vs.get(), nullptr, 0);
const D3D11_VIEWPORT viewport{.TopLeftX = 0.0f,
.TopLeftY = 0.0f,
.Width = static_cast<float>(input.width),
.Height = static_cast<float>(input.height),
.MinDepth = 0.0f,
.MaxDepth = 1.0f};
dc.RSSetViewports(1, &viewport);
auto* const rtv = ⌖
dc.OMSetRenderTargets(1, &rtv, nullptr);
const std::array srvs{&input.srv, get_blue_noise_texture(interfaces)};
dc.PSSetShaderResources(0, srvs.size(), srvs.data());
const std::array<std::uint32_t, 4> randomness{_resolve_rand_dist(_resolve_xorshift),
_resolve_rand_dist(_resolve_xorshift)};
update_dynamic_buffer(dc, *_resolve_cb, randomness);
auto* const cb = _resolve_cb.get();
dc.PSSetConstantBuffers(0, 1, &cb);
dc.PSSetShader(get_resolve_pixel_shader(input, flags), nullptr, 0);
dc.Draw(3, 0);
}
auto Backbuffer_resolver::get_blue_noise_texture(const Interfaces& interfaces) noexcept
-> ID3D11ShaderResourceView*
{
if (_blue_noise_srvs[0] == nullptr) {
for (int i = 0; i < 64; ++i) {
_blue_noise_srvs[i] = interfaces.resources.at_if(
"_SP_BUILTIN_blue_noise_rgb_"s + std::to_string(i));
}
}
return _blue_noise_srvs[_resolve_rand_dist(_resolve_xorshift)].get();
}
auto Backbuffer_resolver::get_resolve_pixel_shader(const Input& input,
const Flags flags) noexcept
-> ID3D11PixelShader*
{
if (flags.linear_input) {
switch (input.sample_count) {
case 1:
return _resolve_ps_linear.get();
case 2:
return _resolve_ps_linear_x2.get();
case 4:
return _resolve_ps_linear_x4.get();
case 8:
return _resolve_ps_linear_x8.get();
}
}
switch (input.sample_count) {
case 1:
return _resolve_ps.get();
case 2:
return _resolve_ps_x2.get();
case 4:
return _resolve_ps_x4.get();
case 8:
return _resolve_ps_x8.get();
default:
log_and_terminate("Unsupported sample count!");
}
}
} | 36.326425 | 89 | 0.607046 | SleepKiller |
be336e816c8b899a7c976e3e9a0ac37c4b723b66 | 4,465 | cpp | C++ | armm/STM32/src/hwi2cslave_stm32_v1.cpp | Bergi84/vihal | 7c139b544bb5ed5a27088bbb6b993f061e055ce8 | [
"BSD-2-Clause"
] | 13 | 2018-02-26T14:56:02.000Z | 2022-03-31T06:01:56.000Z | armm/STM32/src/hwi2cslave_stm32_v1.cpp | Bergi84/vihal | 7c139b544bb5ed5a27088bbb6b993f061e055ce8 | [
"BSD-2-Clause"
] | 2 | 2022-03-12T10:18:07.000Z | 2022-03-14T20:06:26.000Z | armm/STM32/src/hwi2cslave_stm32_v1.cpp | Bergi84/vihal | 7c139b544bb5ed5a27088bbb6b993f061e055ce8 | [
"BSD-2-Clause"
] | 3 | 2020-11-04T09:15:01.000Z | 2021-07-06T09:42:00.000Z | /* -----------------------------------------------------------------------------
* This file is a part of the NVCM project: https://github.com/nvitya/nvcm
* Copyright (c) 2018 Viktor Nagy, nvitya
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from
* the use of this software. Permission is granted to anyone to use this
* software for any purpose, including commercial applications, and to alter
* it and redistribute it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software in
* a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
* --------------------------------------------------------------------------- */
/*
* file: hwi2cslave_stm32_v1.cpp
* brief: STM32 I2C / TWI Slave for F1, F4
* version: 1.00
* date: 2020-03-06
* authors: nvitya
*/
#include "platform.h"
#include "hwpins.h"
#include "hwi2cslave.h"
#include "stm32_utils.h"
#include "traces.h"
#if I2C_HW_VER == 1
// v1 (STM32F1xx, STM32F4xx): different register names and defines
bool THwI2cSlave_stm32::InitHw(int adevnum)
{
unsigned tmp;
uint8_t busid = STM32_BUSID_APB1;
initialized = false;
devnum = adevnum;
regs = nullptr;
if (false)
{
}
#ifdef I2C1
else if (1 == devnum)
{
regs = I2C1;
RCC->APB1ENR |= RCC_APB1ENR_I2C1EN;
}
#endif
#ifdef I2C2
else if (2 == devnum)
{
regs = I2C2;
RCC->APB1ENR |= RCC_APB1ENR_I2C2EN;
}
#endif
#ifdef I2C3
else if (3 == devnum)
{
regs = I2C3;
RCC->APB1ENR |= RCC_APB1ENR_I2C3EN;
}
#endif
if (!regs)
{
return false;
}
// disable for setup
regs->CR1 &= ~I2C_CR1_PE;
regs->CR1 |= I2C_CR1_SWRST;
regs->CR1 &= ~I2C_CR1_SWRST;
unsigned cr1 = 0; // use the default settings, keep disabled
regs->CR1 = cr1;
// setup address
// this device does not support address mask
regs->OAR1 = ((address & 0x7F) << 1);
unsigned periphclock = stm32_bus_speed(busid);
// CR2
tmp = 0
| (0 << 12) // LAST: 1 = Last transfer on DMA EOT
| (0 << 11) // DMAEN: 1 = enable DMA
| (1 << 10) // ITBUFEN: 1 = enable data interrupt
| (1 << 9) // ITEVTEN: 1 = enable event interrupt
| (1 << 8) // ITERREN: 1 = enable error interrupt
| ((periphclock / 1000000) << 0) // set clock speed in MHz
;
regs->CR2 = tmp;
cr1 |= 0
| I2C_CR1_ACK // ACKnowledge must be enabled, otherwise even the own address won't be handled
| I2C_CR1_PE // Enable
;
regs->CR1 = cr1;
initialized = true;
return true;
}
// runstate:
// 0: idle
// 1: receive data
// 5: transmit data
void THwI2cSlave_stm32::HandleIrq()
{
uint32_t sr1 = regs->SR1;
uint32_t sr2 = regs->SR2;
// warning, the sequence above clears some of the status bits
//TRACE("[I2C IRQ %04X %04X]\r\n", sr1, sr2);
// check errors
if (sr1 & 0xFF00)
{
if (sr1 & I2C_SR1_AF) // ACK Failure ?
{
// this is normal
regs->SR1 = ~I2C_SR1_AF; // clear AF error
}
else
{
//TRACE("I2C errors: %04X\r\n", sr1);
regs->SR1 = ~(sr1 & 0xFF00); // clear errors
}
}
// check events
if (sr1 & I2C_SR1_ADDR) // address matched, after start / restart
{
if (sr2 & I2C_SR2_TRA)
{
istx = true;
runstate = 5; // go to transfer data
}
else
{
istx = false;
runstate = 1; // go to receive data
}
OnAddressRw(address); // there is no other info on this chip, use own address
}
if (sr1 & I2C_SR1_RXNE)
{
uint8_t d = regs->DR;
if (1 == runstate)
{
OnByteReceived(d);
}
else
{
// unexpected byte
}
}
if (sr1 & I2C_SR1_TXE)
{
if (5 == runstate)
{
uint8_t d = OnTransmitRequest();
regs->DR = d;
}
else
{
// force stop, releases the data lines
regs->CR1 |= I2C_CR1_STOP; // this must be done here for the proper STOP
}
}
// check stop
if (sr1 & I2C_SR1_STOPF)
{
//TRACE(" STOP DETECTED.\r\n");
// the CR1 must be written in order to clear this flag
runstate = 0;
uint32_t cr1 = regs->CR1;
cr1 &= ~I2C_CR1_STOP;
regs->CR1 = cr1;
}
if (sr2) // to keep sr2 if unused
{
}
}
#endif
| 20.864486 | 97 | 0.618365 | Bergi84 |
be3944e34edde676ff4d93b9d326f3e846e7198f | 5,877 | cpp | C++ | src/globalsearch/http/httprequestmanager.cpp | lilithean/XtalOpt | 9ebc125e6014b27e72a04fb62c8820c7b9670c61 | [
"BSD-3-Clause"
] | 23 | 2017-09-01T04:35:02.000Z | 2022-01-16T13:51:17.000Z | src/globalsearch/http/httprequestmanager.cpp | lilithean/XtalOpt | 9ebc125e6014b27e72a04fb62c8820c7b9670c61 | [
"BSD-3-Clause"
] | 20 | 2017-08-29T15:29:46.000Z | 2022-01-20T09:10:59.000Z | src/globalsearch/http/httprequestmanager.cpp | lilithean/XtalOpt | 9ebc125e6014b27e72a04fb62c8820c7b9670c61 | [
"BSD-3-Clause"
] | 21 | 2017-06-15T03:11:34.000Z | 2022-02-28T05:20:44.000Z | /**********************************************************************
HttpRequestManager - Submit http 'get' and 'post' requests with a
QNetworkAccessManager and receive the results
Copyright (C) 2017-2018 by Patrick Avery
This source code is released under the New BSD License, (the "License").
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 "httprequestmanager.h"
#include <QDebug>
#include <QNetworkRequest>
HttpRequestManager::HttpRequestManager(
const std::shared_ptr<QNetworkAccessManager>& networkManager, QObject* parent)
: QObject(parent), m_networkManager(networkManager), m_requestCounter(0)
{
// This is done so that handleGet and handlePost are always ran in the
// main thread
connect(this, &HttpRequestManager::signalGet, this,
&HttpRequestManager::handleGet);
connect(this, &HttpRequestManager::signalPost, this,
&HttpRequestManager::handlePost);
}
size_t HttpRequestManager::sendGet(QUrl url)
{
std::unique_lock<std::mutex> lock(m_mutex);
QNetworkRequest request(url);
emit signalGet(request, m_requestCounter);
return m_requestCounter++;
}
size_t HttpRequestManager::sendPost(QUrl url, const QByteArray& data)
{
std::unique_lock<std::mutex> lock(m_mutex);
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader,
"application/x-www-form-urlencoded");
emit signalPost(request, data, m_requestCounter);
return m_requestCounter++;
}
bool HttpRequestManager::containsData(size_t i) const
{
std::unique_lock<std::mutex> lock(m_mutex);
return m_receivedReplies.find(i) != m_receivedReplies.end();
}
const QByteArray& HttpRequestManager::data(size_t i) const
{
std::unique_lock<std::mutex> lock(m_mutex);
static const QByteArray empty = "";
if (m_receivedReplies.find(i) == m_receivedReplies.end())
return empty;
return m_receivedReplies.at(i);
}
void HttpRequestManager::handleGet(QNetworkRequest request, size_t requestId)
{
std::unique_lock<std::mutex> lock(m_mutex);
QNetworkReply* reply = m_networkManager->get(request);
connect(reply, (void (QNetworkReply::*)(QNetworkReply::NetworkError))(
&QNetworkReply::error),
this, &HttpRequestManager::handleError);
connect(reply, &QNetworkReply::finished, this,
&HttpRequestManager::handleFinished);
m_pendingReplies[requestId] = reply;
}
void HttpRequestManager::handlePost(QNetworkRequest request, QByteArray data,
size_t requestId)
{
std::unique_lock<std::mutex> lock(m_mutex);
QNetworkReply* reply = m_networkManager->post(request, data);
connect(reply, (void (QNetworkReply::*)(QNetworkReply::NetworkError))(
&QNetworkReply::error),
this, &HttpRequestManager::handleError);
connect(reply, &QNetworkReply::finished, this,
&HttpRequestManager::handleFinished);
m_pendingReplies[requestId] = reply;
}
void HttpRequestManager::handleError(QNetworkReply::NetworkError ec)
{
std::unique_lock<std::mutex> lock(m_mutex);
// Make sure the sender is a QNetworkReply
QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
if (!reply) {
qDebug() << "Error in" << __FUNCTION__ << ": sender() is not a"
<< "QNetworkReply!";
return;
}
// Make sure this HttpRequestManager owns this reply
auto it =
std::find_if(m_pendingReplies.begin(), m_pendingReplies.end(),
[reply](const std::pair<size_t, QNetworkReply*>& item) {
return reply == item.second;
});
// If not, print an error and return
if (it == m_pendingReplies.end()) {
qDebug() << "Error in" << __FUNCTION__ << ": sender() is not owned by"
<< "this HttpRequestManager instance!";
return;
}
size_t receivedInd = it->first;
// Print a message for some of the more common errors
if (ec == QNetworkReply::ConnectionRefusedError)
qDebug() << "QNetworkReply received an error: connection refused";
else if (ec == QNetworkReply::RemoteHostClosedError)
qDebug() << "QNetworkReply received an error: remote host closed";
else if (ec == QNetworkReply::HostNotFoundError)
qDebug() << "QNetworkReply received an error: host not found";
else if (ec == QNetworkReply::TimeoutError)
qDebug() << "QNetworkReply received an error: timeout";
else
qDebug() << "QNetworkReply received error code:" << ec;
m_receivedReplies[receivedInd] = reply->readAll();
m_pendingReplies.erase(receivedInd);
reply->deleteLater();
// Emit a signal
emit received(receivedInd);
}
void HttpRequestManager::handleFinished()
{
std::unique_lock<std::mutex> lock(m_mutex);
// Make sure the sender is a QNetworkReply
QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
if (!reply) {
qDebug() << "Error in" << __FUNCTION__ << ": sender() is not a"
<< "QNetworkReply!";
return;
}
// Make sure this HttpRequestManager owns this reply
auto it =
std::find_if(m_pendingReplies.begin(), m_pendingReplies.end(),
[reply](const std::pair<size_t, QNetworkReply*>& item) {
return reply == item.second;
});
// If not, just return
if (it == m_pendingReplies.end())
return;
size_t receivedInd = it->first;
m_receivedReplies[receivedInd] = reply->readAll();
m_pendingReplies.erase(receivedInd);
reply->deleteLater();
// Emit a signal
emit received(receivedInd);
}
| 30.931579 | 80 | 0.674153 | lilithean |
be3deb80e8531487df0b431d675cadcadfb98212 | 3,633 | hpp | C++ | Periapsis/src/game/main_window.hpp | kulibali/periapsis | 8a8588caff526d3b17604c96338145329be160b8 | [
"MIT"
] | null | null | null | Periapsis/src/game/main_window.hpp | kulibali/periapsis | 8a8588caff526d3b17604c96338145329be160b8 | [
"MIT"
] | null | null | null | Periapsis/src/game/main_window.hpp | kulibali/periapsis | 8a8588caff526d3b17604c96338145329be160b8 | [
"MIT"
] | null | null | null | #ifndef PERIAPSIS_MAIN_WINDOW_H
#define PERIAPSIS_MAIN_WINDOW_H
//
// $Id$
//
// Copyright (c) 2008, The Periapsis Project. 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 the The Periapsis Project nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
// OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#include "data/singleton.hpp"
#include "data/string.hpp"
#include "data/config.hpp"
#include "framework/widget.hpp"
namespace gsgl
{
namespace framework
{
class textbox;
class button;
class tabbox;
}
}
namespace periapsis
{
class periapsis_app;
class simulation_tab;
class settings_tab;
class load_scenery_thread;
class main_window
: public gsgl::framework::widget, public gsgl::data::singleton<main_window>
{
gsgl::framework::textbox *title_box, *status_bar;
gsgl::framework::button *quit_button;
gsgl::framework::tabbox *tab_box;
simulation_tab *sim_tab;
settings_tab *set_tab;
bool need_to_load_scenery;
load_scenery_thread *loading_thread;
public:
main_window(gsgl::platform::display & screen, const gsgl::string & title, const int x, const int y);
virtual ~main_window();
//
void set_status(const gsgl::string & message);
//
virtual void draw();
//
static gsgl::data::config_variable<int> WIDTH;
static gsgl::data::config_variable<int> HEIGHT;
static gsgl::data::config_variable<gsgl::platform::color> FOREGROUND;
static gsgl::data::config_variable<gsgl::platform::color> BACKGROUND;
static gsgl::data::config_variable<gsgl::string> FONT_FACE;
static gsgl::data::config_variable<int> FONT_SIZE;
static gsgl::data::config_variable<int> TITLE_BOX_HEIGHT;
static gsgl::data::config_variable<int> STATUS_BAR_HEIGHT;
static gsgl::data::config_variable<int> TAB_BOX_SPACE;
static gsgl::data::config_variable<int> QUIT_BUTTON_WIDTH;
}; // class main_window
} // namespace periapsis
#endif
| 35.271845 | 109 | 0.674649 | kulibali |
be3e65e07c3fcb64b7a52b965e48bccb6d9f8577 | 340 | cpp | C++ | src/patternMatchValidator/AnyPatternMatchValidator.cpp | sroehling/ChartPatternRecognitionLib | d9bd25c0fc5a8942bb98c74c42ab52db80f680c1 | [
"MIT"
] | 9 | 2019-07-15T19:10:07.000Z | 2021-12-14T12:16:18.000Z | src/patternMatchValidator/AnyPatternMatchValidator.cpp | sroehling/ChartPatternRecognitionLib | d9bd25c0fc5a8942bb98c74c42ab52db80f680c1 | [
"MIT"
] | null | null | null | src/patternMatchValidator/AnyPatternMatchValidator.cpp | sroehling/ChartPatternRecognitionLib | d9bd25c0fc5a8942bb98c74c42ab52db80f680c1 | [
"MIT"
] | 2 | 2020-05-23T03:25:25.000Z | 2021-11-19T16:41:44.000Z | /*
* AnyPatternMatchValidator.cpp
*
* Created on: Jun 18, 2014
* Author: sroehling
*/
#include <AnyPatternMatchValidator.h>
AnyPatternMatchValidator::AnyPatternMatchValidator() {
}
bool AnyPatternMatchValidator::validPattern(const PatternMatch &)
{
return true;
}
AnyPatternMatchValidator::~AnyPatternMatchValidator() {
}
| 15.454545 | 65 | 0.75 | sroehling |
be41f1e87de4fe59078b694951cb90900698e62d | 826 | cpp | C++ | src/gamelib/components/CollisionComponent.cpp | mall0c/GameLib | df4116b53c39be7b178dd87f7eb0fe32a94d00d3 | [
"MIT"
] | 1 | 2020-02-17T09:53:36.000Z | 2020-02-17T09:53:36.000Z | src/gamelib/components/CollisionComponent.cpp | mall0c/GameLib | df4116b53c39be7b178dd87f7eb0fe32a94d00d3 | [
"MIT"
] | null | null | null | src/gamelib/components/CollisionComponent.cpp | mall0c/GameLib | df4116b53c39be7b178dd87f7eb0fe32a94d00d3 | [
"MIT"
] | null | null | null | #include "gamelib/components/CollisionComponent.hpp"
#include "gamelib/core/geometry/CollisionSystem.hpp"
namespace gamelib
{
CollisionComponent::CollisionComponent()
{
_props.registerProperty("flags", flags, 0, num_colflags, str_colflags);
}
CollisionComponent::~CollisionComponent()
{
quit();
}
bool CollisionComponent::_init()
{
auto sys = getSubsystem<CollisionSystem>();
if (!sys)
return false;
sys->add(this);
return true;
}
void CollisionComponent::_quit()
{
getSubsystem<CollisionSystem>()->remove(this);
}
Transformable* CollisionComponent::getTransform()
{
return this;
}
const Transformable* CollisionComponent::getTransform() const
{
return this;
}
}
| 20.146341 | 79 | 0.623487 | mall0c |
be45a5d04efd03001b7ea061367aba467b00b7ba | 349 | cpp | C++ | library/succinct/main.cpp | bluedawnstar/algorithm_library | 4c7f64ec61fc2ba059b64ad7ba20fcb5b838ced6 | [
"Unlicense"
] | 40 | 2017-11-26T05:29:18.000Z | 2020-11-13T00:29:26.000Z | library/succinct/main.cpp | bluedawnstar/algorithm_library | 4c7f64ec61fc2ba059b64ad7ba20fcb5b838ced6 | [
"Unlicense"
] | 101 | 2019-02-09T06:06:09.000Z | 2021-12-25T16:55:37.000Z | library/succinct/main.cpp | bluedawnstar/algorithm_library | 4c7f64ec61fc2ba059b64ad7ba20fcb5b838ced6 | [
"Unlicense"
] | 6 | 2017-01-03T14:17:58.000Z | 2021-01-22T10:37:04.000Z | #include <iostream>
using namespace std;
#define TEST(ModuleName) extern void test##ModuleName(void); \
test##ModuleName()
int main(void) {
TEST(BitVectorRank);
TEST(WaveletTree);
TEST(WaveletTreeBitVector);
TEST(WaveletMatrix);
TEST(WaveletMatrixArray);
TEST(WaveletMatrixArrayIndirect);
}
| 21.8125 | 65 | 0.659026 | bluedawnstar |
be46616bf23901fa75ab08931a99583b1bce52bd | 530 | hpp | C++ | unit_tests/classgenerator.hpp | julienlopez/CppDependencyAnalyzer | d29065e7988ef7f553785ce7cb8bf2bb03097c66 | [
"MIT"
] | null | null | null | unit_tests/classgenerator.hpp | julienlopez/CppDependencyAnalyzer | d29065e7988ef7f553785ce7cb8bf2bb03097c66 | [
"MIT"
] | 7 | 2019-12-10T12:59:20.000Z | 2020-07-01T14:13:44.000Z | unit_tests/classgenerator.hpp | julienlopez/CppDependencyAnalyzer | d29065e7988ef7f553785ce7cb8bf2bb03097c66 | [
"MIT"
] | null | null | null | #pragma once
#include "class.hpp"
namespace Testing
{
class ClassGenerator
{
public:
explicit ClassGenerator(std::wstring class_name = L"A", std::wstring header_file_name = L"a.hpp");
~ClassGenerator() = default;
operator Cda::ClassFiles() const;
ClassGenerator& addLine(std::wstring line);
private:
const std::wstring m_class_name;
const std::wstring m_header_file_name;
std::wstring m_content;
};
std::vector<Cda::File::Line> linesFromString(const std::wstring& str);
} // namespace Testing
| 18.928571 | 102 | 0.713208 | julienlopez |
be4723f5197a44609d384533bee263f0f7a7494d | 4,825 | cpp | C++ | demo/sdk_demo_v2/SETTINGS_virtualBG_workflow.cpp | j421037/zoom | 3ba230a3ace50b7b8d722550eb320011a374f90d | [
"RSA-MD"
] | null | null | null | demo/sdk_demo_v2/SETTINGS_virtualBG_workflow.cpp | j421037/zoom | 3ba230a3ace50b7b8d722550eb320011a374f90d | [
"RSA-MD"
] | null | null | null | demo/sdk_demo_v2/SETTINGS_virtualBG_workflow.cpp | j421037/zoom | 3ba230a3ace50b7b8d722550eb320011a374f90d | [
"RSA-MD"
] | 3 | 2020-11-04T08:51:33.000Z | 2020-11-06T04:49:07.000Z | #include "stdafx.h"
#include "SETTINGS_virtualBG_workflow.h"
CSDKVirtualBGSettingsWorkFlow::CSDKVirtualBGSettingsWorkFlow()
{
m_pSettingService = NULL;
m_pVBGSettingContext = NULL;
m_pVideoSettingsContext = NULL;
m_pTestVideoDeviceHelper = NULL;
Init();
}
CSDKVirtualBGSettingsWorkFlow::~CSDKVirtualBGSettingsWorkFlow()
{
m_pSettingService = NULL;
m_pVBGSettingContext = NULL;
m_pTestVideoDeviceHelper = NULL;
m_pVideoSettingsContext = NULL;
}
ZOOM_SDK_NAMESPACE::SDKError CSDKVirtualBGSettingsWorkFlow::Init()
{
if(NULL == m_pSettingService)
{
m_pSettingService = SDKInterfaceWrap::GetInst().GetSettingService();
}
if(m_pSettingService)
{
m_pVBGSettingContext = m_pSettingService->GetVirtualBGSettings();
m_pVideoSettingsContext = m_pSettingService->GetVideoSettings();
}
if(NULL == m_pVBGSettingContext)
{
return ZOOM_SDK_NAMESPACE::SDKERR_UNINITIALIZE;
}
if(m_pVideoSettingsContext)
{
m_pTestVideoDeviceHelper = m_pVideoSettingsContext->GetTestVideoDeviceHelper();
if(m_pTestVideoDeviceHelper)
{
ZOOM_SDK_NAMESPACE::SDKError err = ZOOM_SDK_NAMESPACE::SDKERR_SUCCESS;
err = m_pTestVideoDeviceHelper->SetEvent(this);
return err;
}
}
return ZOOM_SDK_NAMESPACE::SDKERR_SUCCESS;
}
bool CSDKVirtualBGSettingsWorkFlow::IsSupportVirtualBG()
{
if(m_pVBGSettingContext)
return m_pVBGSettingContext->IsSupportVirtualBG();
return false;
}
bool CSDKVirtualBGSettingsWorkFlow::IsSupportSmartVirtualBG()
{
if(m_pVBGSettingContext)
return m_pVBGSettingContext->IsSupportSmartVirtualBG();
return false;
}
bool CSDKVirtualBGSettingsWorkFlow::IsUsingGreenScreenOn()
{
if(m_pVBGSettingContext)
return m_pVBGSettingContext->IsUsingGreenScreenOn ();
return false;
}
DWORD CSDKVirtualBGSettingsWorkFlow::GetBGReplaceColor()
{
if(m_pVBGSettingContext)
return m_pVBGSettingContext->GetBGReplaceColor();
return 0;
}
ZOOM_SDK_NAMESPACE::SDKError CSDKVirtualBGSettingsWorkFlow::SetUsingGreenScreen(bool bUse)
{
if(m_pVBGSettingContext)
{
ZOOM_SDK_NAMESPACE::SDKError err = ZOOM_SDK_NAMESPACE::SDKERR_SUCCESS;
err = m_pVBGSettingContext->SetUsingGreenScreen(bUse);
return err;
}
return ZOOM_SDK_NAMESPACE::SDKERR_UNINITIALIZE;
}
ZOOM_SDK_NAMESPACE::SDKError CSDKVirtualBGSettingsWorkFlow::AddBGImage(const wchar_t* file_path)
{
if(m_pVBGSettingContext)
{
ZOOM_SDK_NAMESPACE::SDKError err = ZOOM_SDK_NAMESPACE::SDKERR_SUCCESS;
err = m_pVBGSettingContext->AddBGImage(file_path);
return err;
}
return ZOOM_SDK_NAMESPACE::SDKERR_UNINITIALIZE;
}
ZOOM_SDK_NAMESPACE::SDKError CSDKVirtualBGSettingsWorkFlow::RemoveBGImage(ZOOM_SDK_NAMESPACE::IVirtualBGImageInfo* pRemoveImage)
{
if(m_pVBGSettingContext)
{
ZOOM_SDK_NAMESPACE::SDKError err = ZOOM_SDK_NAMESPACE::SDKERR_SUCCESS;
err = m_pVBGSettingContext->RemoveBGImage(pRemoveImage);
return err;
}
return ZOOM_SDK_NAMESPACE::SDKERR_UNINITIALIZE;
}
ZOOM_SDK_NAMESPACE::IList<ZOOM_SDK_NAMESPACE::IVirtualBGImageInfo* >* CSDKVirtualBGSettingsWorkFlow::GetBGImageList()
{
if(m_pVBGSettingContext)
{
return m_pVBGSettingContext->GetBGImageList();
}
return NULL;
}
ZOOM_SDK_NAMESPACE::SDKError CSDKVirtualBGSettingsWorkFlow::UseBGImage(ZOOM_SDK_NAMESPACE::IVirtualBGImageInfo* pImage)
{
if(m_pVBGSettingContext)
{
ZOOM_SDK_NAMESPACE::SDKError err = ZOOM_SDK_NAMESPACE::SDKERR_SUCCESS;
err = m_pVBGSettingContext->UseBGImage(pImage);
return err;
}
return ZOOM_SDK_NAMESPACE::SDKERR_UNINITIALIZE;
}
ZOOM_SDK_NAMESPACE::SDKError CSDKVirtualBGSettingsWorkFlow::BeginSelectReplaceVBColor()
{
if(m_pVBGSettingContext)
{
ZOOM_SDK_NAMESPACE::SDKError err = ZOOM_SDK_NAMESPACE::SDKERR_SUCCESS;
err = m_pVBGSettingContext->BeginSelectReplaceVBColor();
return err;
}
return ZOOM_SDK_NAMESPACE::SDKERR_UNINITIALIZE;
}
ZOOM_SDK_NAMESPACE::SDKError CSDKVirtualBGSettingsWorkFlow::SetVideoPreviewParentWnd(HWND hParentWnd, RECT rc /* = _SDK_TEST_VIDEO_INIT_RECT */)
{
if(m_pTestVideoDeviceHelper)
{
ZOOM_SDK_NAMESPACE::SDKError err = ZOOM_SDK_NAMESPACE::SDKERR_SUCCESS;
err = m_pTestVideoDeviceHelper->SetVideoPreviewParentWnd(hParentWnd,rc);
return err;
}
return ZOOM_SDK_NAMESPACE::SDKERR_UNINITIALIZE;
}
ZOOM_SDK_NAMESPACE::SDKError CSDKVirtualBGSettingsWorkFlow::TestVideoStartPreview(const wchar_t* deviceID /* = NULL */)
{
if(m_pTestVideoDeviceHelper)
{
ZOOM_SDK_NAMESPACE::SDKError err = ZOOM_SDK_NAMESPACE::SDKERR_SUCCESS;
err = m_pTestVideoDeviceHelper->TestVideoStartPreview(deviceID);
return err;
}
return ZOOM_SDK_NAMESPACE::SDKERR_UNINITIALIZE;
}
ZOOM_SDK_NAMESPACE::SDKError CSDKVirtualBGSettingsWorkFlow::TestVideoStopPreview()
{
if(m_pTestVideoDeviceHelper)
{
ZOOM_SDK_NAMESPACE::SDKError err = ZOOM_SDK_NAMESPACE::SDKERR_SUCCESS;
err = m_pTestVideoDeviceHelper->TestVideoStopPreview();
return err;
}
return ZOOM_SDK_NAMESPACE::SDKERR_UNINITIALIZE;
}
| 28.382353 | 144 | 0.813886 | j421037 |
be487eca0271cd5326b4063632b42274629692ef | 1,363 | hpp | C++ | source/URI/Query.hpp | kurocha/uri | b920d01de5323126eaf539d4217d357b47fde64e | [
"Unlicense",
"MIT"
] | 2 | 2018-07-06T19:43:16.000Z | 2018-07-06T19:44:46.000Z | source/URI/Query.hpp | kurocha/uri | b920d01de5323126eaf539d4217d357b47fde64e | [
"Unlicense",
"MIT"
] | null | null | null | source/URI/Query.hpp | kurocha/uri | b920d01de5323126eaf539d4217d357b47fde64e | [
"Unlicense",
"MIT"
] | null | null | null | //
// Query.hpp
// File file is part of the "URI" project and released under the MIT License.
//
// Created by Samuel Williams on 17/7/2017.
// Copyright, 2017, by Samuel Williams. All rights reserved.
//
#pragma once
#include "Encoding.hpp"
#include <string>
#include <map>
namespace URI
{
/// Assumes application/x-www-form-urlencoded.
struct Query
{
std::string value;
Query() {}
template <typename ValueT>
Query(const ValueT & value_) : value(value_) {}
template <typename IteratorT>
Query(IteratorT begin, IteratorT end) : Query(Encoding::encode_query(begin, end)) {}
bool empty () const noexcept {return value.empty();}
explicit operator bool() const noexcept {return !empty();}
std::multimap<std::string, std::string> to_map() const;
Query operator+(const Query & other);
bool operator==(const Query & other) const {return value == other.value;}
bool operator!=(const Query & other) const {return value != other.value;}
bool operator<(const Query & other) const {return value < other.value;}
bool operator<=(const Query & other) const {return value <= other.value;}
bool operator>(const Query & other) const {return value > other.value;}
bool operator>=(const Query & other) const {return value >= other.value;}
};
std::ostream & operator<<(std::ostream & output, const Query & query);
}
| 28.395833 | 86 | 0.685253 | kurocha |
be56e60561f98ff854f29f7a4636fda78b0f6ce8 | 647 | hpp | C++ | src/Cell.hpp | JaroslawWiosna/nonogram-solver | 5d6f9eec5b56700e2930478e67bc99b7b8951664 | [
"MIT"
] | null | null | null | src/Cell.hpp | JaroslawWiosna/nonogram-solver | 5d6f9eec5b56700e2930478e67bc99b7b8951664 | [
"MIT"
] | null | null | null | src/Cell.hpp | JaroslawWiosna/nonogram-solver | 5d6f9eec5b56700e2930478e67bc99b7b8951664 | [
"MIT"
] | null | null | null | #pragma once
#include <array>
#include <cassert>
#include <functional>
#include <iostream>
#include <memory>
#include <vector>
enum class Cell_type {
unfilled = -1,
empty,
one,
};
struct Cell {
Cell_type type = Cell_type::unfilled;
void print() const {
switch (type) {
case Cell_type::unfilled: {
std::cout << "-";
return;
}
case Cell_type::empty: {
std::cout << "x";
return;
}
case Cell_type::one: {
std::cout << "1";
return;
}
}
}
};
| 18.485714 | 41 | 0.446677 | JaroslawWiosna |
be57434d352eadefc22396c8caa40c1f7027e55d | 807 | cc | C++ | src/.unfinished/_89-gray-code.cc | q191201771/yoko_leetcode | a29b163169f409856e9c9808890bcb25ca976f78 | [
"MIT"
] | 2 | 2018-07-28T06:11:30.000Z | 2019-01-15T15:16:54.000Z | src/.unfinished/_89-gray-code.cc | q191201771/yoko_leetcode | a29b163169f409856e9c9808890bcb25ca976f78 | [
"MIT"
] | null | null | null | src/.unfinished/_89-gray-code.cc | q191201771/yoko_leetcode | a29b163169f409856e9c9808890bcb25ca976f78 | [
"MIT"
] | null | null | null | The gray code is a binary numeral system where two successive values differ in only one bit.
Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A
gray code sequence must begin with 0.
Example 1:
Input: 2
Output: [0,1,3,2]
Explanation:
00 - 0
01 - 1
11 - 3
10 - 2
For a given n, a gray code sequence may not be uniquely defined.
For example, [0,2,3,1] is also a valid gray code sequence.
00 - 0
10 - 2
11 - 3
01 - 1
Example 2:
Input: 0
Output: [0]
Explanation: We define the gray code sequence to begin with 0.
A gray code sequence of n has size = 2n, which for n = 0 the size is 20 = 1.
Therefore, for n = 0 the gray code sequence is [0].
class Solution {
public:
vector<int> grayCode(int n) {
}
};
| 20.692308 | 116 | 0.677819 | q191201771 |
be586aef943398347d424720037eeb46d868e3a7 | 632 | cpp | C++ | FlightComputerV2/src/Mount.cpp | jowallace1/FlightComputerV2 | b8ea60bd370243ef05611267cba214bf72c34f9b | [
"MIT"
] | null | null | null | FlightComputerV2/src/Mount.cpp | jowallace1/FlightComputerV2 | b8ea60bd370243ef05611267cba214bf72c34f9b | [
"MIT"
] | null | null | null | FlightComputerV2/src/Mount.cpp | jowallace1/FlightComputerV2 | b8ea60bd370243ef05611267cba214bf72c34f9b | [
"MIT"
] | null | null | null | #include "Mount.h"
Mount::Mount(double yawRatio, unsigned int yawOffset, unsigned int yawPin, double pitchRatio, unsigned int pitchOffset, unsigned int pitchPin)
: yawRatio(yawRatio), pitchRatio(pitchRatio)
{
yawServo.offset = yawOffset;
yawServo.pin = yawPin;
pitchServo.offset = pitchOffset;
pitchServo.pin = pitchPin;
}
void Mount::attach()
{
yawServo.attach();
pitchServo.attach();
}
void Mount::detach()
{
yawServo.detach();
pitchServo.detach();
}
Pair Mount::getState()
{
Pair temp;
temp.yaw = yawServo.readAngle();
temp.pitch = pitchServo.readAngle();
return temp;
} | 19.151515 | 142 | 0.683544 | jowallace1 |
41534a336201e5b58c51aa778b08dc92074aa99a | 21,709 | cpp | C++ | bindings/cpp/opencv_4/superres.cpp | bamorim/opencv-rust | d83ac457cea9540f2d535bc6158e1910ba887eea | [
"MIT"
] | null | null | null | bindings/cpp/opencv_4/superres.cpp | bamorim/opencv-rust | d83ac457cea9540f2d535bc6158e1910ba887eea | [
"MIT"
] | null | null | null | bindings/cpp/opencv_4/superres.cpp | bamorim/opencv-rust | d83ac457cea9540f2d535bc6158e1910ba887eea | [
"MIT"
] | null | null | null | #include "common.hpp"
#include <opencv2/superres.hpp>
#include "superres_types.hpp"
extern "C" {
Result<cv::Ptr<cv::superres::FrameSource>*> cv_superres_createFrameSource_Camera_int(int deviceId) {
try {
cv::Ptr<cv::superres::FrameSource> ret = cv::superres::createFrameSource_Camera(deviceId);
return Ok(new cv::Ptr<cv::superres::FrameSource>(ret));
} OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::superres::FrameSource>*>))
}
Result<cv::Ptr<cv::superres::FrameSource>*> cv_superres_createFrameSource_Empty() {
try {
cv::Ptr<cv::superres::FrameSource> ret = cv::superres::createFrameSource_Empty();
return Ok(new cv::Ptr<cv::superres::FrameSource>(ret));
} OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::superres::FrameSource>*>))
}
Result<cv::Ptr<cv::superres::FrameSource>*> cv_superres_createFrameSource_Video_CUDA_const_StringR(const char* fileName) {
try {
cv::Ptr<cv::superres::FrameSource> ret = cv::superres::createFrameSource_Video_CUDA(std::string(fileName));
return Ok(new cv::Ptr<cv::superres::FrameSource>(ret));
} OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::superres::FrameSource>*>))
}
Result<cv::Ptr<cv::superres::FrameSource>*> cv_superres_createFrameSource_Video_const_StringR(const char* fileName) {
try {
cv::Ptr<cv::superres::FrameSource> ret = cv::superres::createFrameSource_Video(std::string(fileName));
return Ok(new cv::Ptr<cv::superres::FrameSource>(ret));
} OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::superres::FrameSource>*>))
}
Result<cv::Ptr<cv::superres::BroxOpticalFlow>*> cv_superres_createOptFlow_Brox_CUDA() {
try {
cv::Ptr<cv::superres::BroxOpticalFlow> ret = cv::superres::createOptFlow_Brox_CUDA();
return Ok(new cv::Ptr<cv::superres::BroxOpticalFlow>(ret));
} OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::superres::BroxOpticalFlow>*>))
}
Result<cv::Ptr<cv::superres::DualTVL1OpticalFlow>*> cv_superres_createOptFlow_DualTVL1() {
try {
cv::Ptr<cv::superres::DualTVL1OpticalFlow> ret = cv::superres::createOptFlow_DualTVL1();
return Ok(new cv::Ptr<cv::superres::DualTVL1OpticalFlow>(ret));
} OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::superres::DualTVL1OpticalFlow>*>))
}
Result<cv::Ptr<cv::superres::DualTVL1OpticalFlow>*> cv_superres_createOptFlow_DualTVL1_CUDA() {
try {
cv::Ptr<cv::superres::DualTVL1OpticalFlow> ret = cv::superres::createOptFlow_DualTVL1_CUDA();
return Ok(new cv::Ptr<cv::superres::DualTVL1OpticalFlow>(ret));
} OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::superres::DualTVL1OpticalFlow>*>))
}
Result<cv::Ptr<cv::superres::FarnebackOpticalFlow>*> cv_superres_createOptFlow_Farneback() {
try {
cv::Ptr<cv::superres::FarnebackOpticalFlow> ret = cv::superres::createOptFlow_Farneback();
return Ok(new cv::Ptr<cv::superres::FarnebackOpticalFlow>(ret));
} OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::superres::FarnebackOpticalFlow>*>))
}
Result<cv::Ptr<cv::superres::FarnebackOpticalFlow>*> cv_superres_createOptFlow_Farneback_CUDA() {
try {
cv::Ptr<cv::superres::FarnebackOpticalFlow> ret = cv::superres::createOptFlow_Farneback_CUDA();
return Ok(new cv::Ptr<cv::superres::FarnebackOpticalFlow>(ret));
} OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::superres::FarnebackOpticalFlow>*>))
}
Result<cv::Ptr<cv::superres::PyrLKOpticalFlow>*> cv_superres_createOptFlow_PyrLK_CUDA() {
try {
cv::Ptr<cv::superres::PyrLKOpticalFlow> ret = cv::superres::createOptFlow_PyrLK_CUDA();
return Ok(new cv::Ptr<cv::superres::PyrLKOpticalFlow>(ret));
} OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::superres::PyrLKOpticalFlow>*>))
}
Result<cv::Ptr<cv::superres::SuperResolution>*> cv_superres_createSuperResolution_BTVL1() {
try {
cv::Ptr<cv::superres::SuperResolution> ret = cv::superres::createSuperResolution_BTVL1();
return Ok(new cv::Ptr<cv::superres::SuperResolution>(ret));
} OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::superres::SuperResolution>*>))
}
Result<cv::Ptr<cv::superres::SuperResolution>*> cv_superres_createSuperResolution_BTVL1_CUDA() {
try {
cv::Ptr<cv::superres::SuperResolution> ret = cv::superres::createSuperResolution_BTVL1_CUDA();
return Ok(new cv::Ptr<cv::superres::SuperResolution>(ret));
} OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::superres::SuperResolution>*>))
}
Result<double> cv_superres_BroxOpticalFlow_getAlpha_const(const cv::superres::BroxOpticalFlow* instance) {
try {
double ret = instance->getAlpha();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<double>))
}
Result_void cv_superres_BroxOpticalFlow_setAlpha_double(cv::superres::BroxOpticalFlow* instance, double val) {
try {
instance->setAlpha(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<double> cv_superres_BroxOpticalFlow_getGamma_const(const cv::superres::BroxOpticalFlow* instance) {
try {
double ret = instance->getGamma();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<double>))
}
Result_void cv_superres_BroxOpticalFlow_setGamma_double(cv::superres::BroxOpticalFlow* instance, double val) {
try {
instance->setGamma(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<double> cv_superres_BroxOpticalFlow_getScaleFactor_const(const cv::superres::BroxOpticalFlow* instance) {
try {
double ret = instance->getScaleFactor();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<double>))
}
Result_void cv_superres_BroxOpticalFlow_setScaleFactor_double(cv::superres::BroxOpticalFlow* instance, double val) {
try {
instance->setScaleFactor(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_BroxOpticalFlow_getInnerIterations_const(const cv::superres::BroxOpticalFlow* instance) {
try {
int ret = instance->getInnerIterations();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_BroxOpticalFlow_setInnerIterations_int(cv::superres::BroxOpticalFlow* instance, int val) {
try {
instance->setInnerIterations(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_BroxOpticalFlow_getOuterIterations_const(const cv::superres::BroxOpticalFlow* instance) {
try {
int ret = instance->getOuterIterations();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_BroxOpticalFlow_setOuterIterations_int(cv::superres::BroxOpticalFlow* instance, int val) {
try {
instance->setOuterIterations(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_BroxOpticalFlow_getSolverIterations_const(const cv::superres::BroxOpticalFlow* instance) {
try {
int ret = instance->getSolverIterations();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_BroxOpticalFlow_setSolverIterations_int(cv::superres::BroxOpticalFlow* instance, int val) {
try {
instance->setSolverIterations(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result_void cv_superres_DenseOpticalFlowExt_calc_const__InputArrayR_const__InputArrayR_const__OutputArrayR_const__OutputArrayR(cv::superres::DenseOpticalFlowExt* instance, const cv::_InputArray* frame0, const cv::_InputArray* frame1, const cv::_OutputArray* flow1, const cv::_OutputArray* flow2) {
try {
instance->calc(*frame0, *frame1, *flow1, *flow2);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result_void cv_superres_DenseOpticalFlowExt_collectGarbage(cv::superres::DenseOpticalFlowExt* instance) {
try {
instance->collectGarbage();
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<double> cv_superres_DualTVL1OpticalFlow_getTau_const(const cv::superres::DualTVL1OpticalFlow* instance) {
try {
double ret = instance->getTau();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<double>))
}
Result_void cv_superres_DualTVL1OpticalFlow_setTau_double(cv::superres::DualTVL1OpticalFlow* instance, double val) {
try {
instance->setTau(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<double> cv_superres_DualTVL1OpticalFlow_getLambda_const(const cv::superres::DualTVL1OpticalFlow* instance) {
try {
double ret = instance->getLambda();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<double>))
}
Result_void cv_superres_DualTVL1OpticalFlow_setLambda_double(cv::superres::DualTVL1OpticalFlow* instance, double val) {
try {
instance->setLambda(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<double> cv_superres_DualTVL1OpticalFlow_getTheta_const(const cv::superres::DualTVL1OpticalFlow* instance) {
try {
double ret = instance->getTheta();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<double>))
}
Result_void cv_superres_DualTVL1OpticalFlow_setTheta_double(cv::superres::DualTVL1OpticalFlow* instance, double val) {
try {
instance->setTheta(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_DualTVL1OpticalFlow_getScalesNumber_const(const cv::superres::DualTVL1OpticalFlow* instance) {
try {
int ret = instance->getScalesNumber();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_DualTVL1OpticalFlow_setScalesNumber_int(cv::superres::DualTVL1OpticalFlow* instance, int val) {
try {
instance->setScalesNumber(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_DualTVL1OpticalFlow_getWarpingsNumber_const(const cv::superres::DualTVL1OpticalFlow* instance) {
try {
int ret = instance->getWarpingsNumber();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_DualTVL1OpticalFlow_setWarpingsNumber_int(cv::superres::DualTVL1OpticalFlow* instance, int val) {
try {
instance->setWarpingsNumber(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<double> cv_superres_DualTVL1OpticalFlow_getEpsilon_const(const cv::superres::DualTVL1OpticalFlow* instance) {
try {
double ret = instance->getEpsilon();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<double>))
}
Result_void cv_superres_DualTVL1OpticalFlow_setEpsilon_double(cv::superres::DualTVL1OpticalFlow* instance, double val) {
try {
instance->setEpsilon(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_DualTVL1OpticalFlow_getIterations_const(const cv::superres::DualTVL1OpticalFlow* instance) {
try {
int ret = instance->getIterations();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_DualTVL1OpticalFlow_setIterations_int(cv::superres::DualTVL1OpticalFlow* instance, int val) {
try {
instance->setIterations(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<bool> cv_superres_DualTVL1OpticalFlow_getUseInitialFlow_const(const cv::superres::DualTVL1OpticalFlow* instance) {
try {
bool ret = instance->getUseInitialFlow();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<bool>))
}
Result_void cv_superres_DualTVL1OpticalFlow_setUseInitialFlow_bool(cv::superres::DualTVL1OpticalFlow* instance, bool val) {
try {
instance->setUseInitialFlow(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<double> cv_superres_FarnebackOpticalFlow_getPyrScale_const(const cv::superres::FarnebackOpticalFlow* instance) {
try {
double ret = instance->getPyrScale();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<double>))
}
Result_void cv_superres_FarnebackOpticalFlow_setPyrScale_double(cv::superres::FarnebackOpticalFlow* instance, double val) {
try {
instance->setPyrScale(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_FarnebackOpticalFlow_getLevelsNumber_const(const cv::superres::FarnebackOpticalFlow* instance) {
try {
int ret = instance->getLevelsNumber();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_FarnebackOpticalFlow_setLevelsNumber_int(cv::superres::FarnebackOpticalFlow* instance, int val) {
try {
instance->setLevelsNumber(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_FarnebackOpticalFlow_getWindowSize_const(const cv::superres::FarnebackOpticalFlow* instance) {
try {
int ret = instance->getWindowSize();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_FarnebackOpticalFlow_setWindowSize_int(cv::superres::FarnebackOpticalFlow* instance, int val) {
try {
instance->setWindowSize(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_FarnebackOpticalFlow_getIterations_const(const cv::superres::FarnebackOpticalFlow* instance) {
try {
int ret = instance->getIterations();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_FarnebackOpticalFlow_setIterations_int(cv::superres::FarnebackOpticalFlow* instance, int val) {
try {
instance->setIterations(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_FarnebackOpticalFlow_getPolyN_const(const cv::superres::FarnebackOpticalFlow* instance) {
try {
int ret = instance->getPolyN();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_FarnebackOpticalFlow_setPolyN_int(cv::superres::FarnebackOpticalFlow* instance, int val) {
try {
instance->setPolyN(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<double> cv_superres_FarnebackOpticalFlow_getPolySigma_const(const cv::superres::FarnebackOpticalFlow* instance) {
try {
double ret = instance->getPolySigma();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<double>))
}
Result_void cv_superres_FarnebackOpticalFlow_setPolySigma_double(cv::superres::FarnebackOpticalFlow* instance, double val) {
try {
instance->setPolySigma(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_FarnebackOpticalFlow_getFlags_const(const cv::superres::FarnebackOpticalFlow* instance) {
try {
int ret = instance->getFlags();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_FarnebackOpticalFlow_setFlags_int(cv::superres::FarnebackOpticalFlow* instance, int val) {
try {
instance->setFlags(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result_void cv_superres_FrameSource_nextFrame_const__OutputArrayR(cv::superres::FrameSource* instance, const cv::_OutputArray* frame) {
try {
instance->nextFrame(*frame);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result_void cv_superres_FrameSource_reset(cv::superres::FrameSource* instance) {
try {
instance->reset();
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_PyrLKOpticalFlow_getWindowSize_const(const cv::superres::PyrLKOpticalFlow* instance) {
try {
int ret = instance->getWindowSize();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_PyrLKOpticalFlow_setWindowSize_int(cv::superres::PyrLKOpticalFlow* instance, int val) {
try {
instance->setWindowSize(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_PyrLKOpticalFlow_getMaxLevel_const(const cv::superres::PyrLKOpticalFlow* instance) {
try {
int ret = instance->getMaxLevel();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_PyrLKOpticalFlow_setMaxLevel_int(cv::superres::PyrLKOpticalFlow* instance, int val) {
try {
instance->setMaxLevel(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_PyrLKOpticalFlow_getIterations_const(const cv::superres::PyrLKOpticalFlow* instance) {
try {
int ret = instance->getIterations();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_PyrLKOpticalFlow_setIterations_int(cv::superres::PyrLKOpticalFlow* instance, int val) {
try {
instance->setIterations(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result_void cv_superres_SuperResolution_setInput_const_Ptr_FrameSource_R(cv::superres::SuperResolution* instance, const cv::Ptr<cv::superres::FrameSource>* frameSource) {
try {
instance->setInput(*frameSource);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result_void cv_superres_SuperResolution_nextFrame_const__OutputArrayR(cv::superres::SuperResolution* instance, const cv::_OutputArray* frame) {
try {
instance->nextFrame(*frame);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result_void cv_superres_SuperResolution_reset(cv::superres::SuperResolution* instance) {
try {
instance->reset();
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result_void cv_superres_SuperResolution_collectGarbage(cv::superres::SuperResolution* instance) {
try {
instance->collectGarbage();
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_SuperResolution_getScale_const(const cv::superres::SuperResolution* instance) {
try {
int ret = instance->getScale();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_SuperResolution_setScale_int(cv::superres::SuperResolution* instance, int val) {
try {
instance->setScale(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_SuperResolution_getIterations_const(const cv::superres::SuperResolution* instance) {
try {
int ret = instance->getIterations();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_SuperResolution_setIterations_int(cv::superres::SuperResolution* instance, int val) {
try {
instance->setIterations(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<double> cv_superres_SuperResolution_getTau_const(const cv::superres::SuperResolution* instance) {
try {
double ret = instance->getTau();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<double>))
}
Result_void cv_superres_SuperResolution_setTau_double(cv::superres::SuperResolution* instance, double val) {
try {
instance->setTau(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<double> cv_superres_SuperResolution_getLambda_const(const cv::superres::SuperResolution* instance) {
try {
double ret = instance->getLambda();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<double>))
}
Result_void cv_superres_SuperResolution_setLambda_double(cv::superres::SuperResolution* instance, double val) {
try {
instance->setLambda(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<double> cv_superres_SuperResolution_getAlpha_const(const cv::superres::SuperResolution* instance) {
try {
double ret = instance->getAlpha();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<double>))
}
Result_void cv_superres_SuperResolution_setAlpha_double(cv::superres::SuperResolution* instance, double val) {
try {
instance->setAlpha(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_SuperResolution_getKernelSize_const(const cv::superres::SuperResolution* instance) {
try {
int ret = instance->getKernelSize();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_SuperResolution_setKernelSize_int(cv::superres::SuperResolution* instance, int val) {
try {
instance->setKernelSize(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_SuperResolution_getBlurKernelSize_const(const cv::superres::SuperResolution* instance) {
try {
int ret = instance->getBlurKernelSize();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_SuperResolution_setBlurKernelSize_int(cv::superres::SuperResolution* instance, int val) {
try {
instance->setBlurKernelSize(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<double> cv_superres_SuperResolution_getBlurSigma_const(const cv::superres::SuperResolution* instance) {
try {
double ret = instance->getBlurSigma();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<double>))
}
Result_void cv_superres_SuperResolution_setBlurSigma_double(cv::superres::SuperResolution* instance, double val) {
try {
instance->setBlurSigma(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<int> cv_superres_SuperResolution_getTemporalAreaRadius_const(const cv::superres::SuperResolution* instance) {
try {
int ret = instance->getTemporalAreaRadius();
return Ok(ret);
} OCVRS_CATCH(OCVRS_TYPE(Result<int>))
}
Result_void cv_superres_SuperResolution_setTemporalAreaRadius_int(cv::superres::SuperResolution* instance, int val) {
try {
instance->setTemporalAreaRadius(val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
Result<cv::Ptr<cv::superres::DenseOpticalFlowExt>*> cv_superres_SuperResolution_getOpticalFlow_const(const cv::superres::SuperResolution* instance) {
try {
cv::Ptr<cv::superres::DenseOpticalFlowExt> ret = instance->getOpticalFlow();
return Ok(new cv::Ptr<cv::superres::DenseOpticalFlowExt>(ret));
} OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::superres::DenseOpticalFlowExt>*>))
}
Result_void cv_superres_SuperResolution_setOpticalFlow_const_Ptr_DenseOpticalFlowExt_R(cv::superres::SuperResolution* instance, const cv::Ptr<cv::superres::DenseOpticalFlowExt>* val) {
try {
instance->setOpticalFlow(*val);
return Ok();
} OCVRS_CATCH(OCVRS_TYPE(Result_void))
}
}
| 34.845907 | 298 | 0.752591 | bamorim |
4154f0845f18ec1e6c102c2171fd1da3a8b4d1d9 | 1,187 | cpp | C++ | src/unitTest/rootNodeTest/piecewiseLR_test.cpp | JiaoYiZhang/learned_index | bc8028edcc8c63609bbad7b9c591704fbca838bb | [
"MIT"
] | 3 | 2021-03-13T07:07:51.000Z | 2021-11-17T10:36:57.000Z | src/unitTest/rootNodeTest/piecewiseLR_test.cpp | JiaoYiZhang/learned_index | bc8028edcc8c63609bbad7b9c591704fbca838bb | [
"MIT"
] | null | null | null | src/unitTest/rootNodeTest/piecewiseLR_test.cpp | JiaoYiZhang/learned_index | bc8028edcc8c63609bbad7b9c591704fbca838bb | [
"MIT"
] | null | null | null | /**
* @file piecewiseLR_test.cpp
* @author Jiaoyi
* @brief
* @version 0.1
* @date 2021-11-03
*
* @copyright Copyright (c) 2021
*
*/
#include "../../include/nodes/rootNode/trainModel/piecewiseLR.h"
#include "../../experiment/dataset/lognormal_distribution.h"
#include "gtest/gtest.h"
std::vector<std::pair<double, double>> initData;
std::vector<std::pair<double, double>> insertData;
std::vector<std::pair<double, double>> testInsert;
const int kChildNum = 512;
const int kTestMaxValue = kMaxValue;
LognormalDataset logData(0.9);
PiecewiseLR<DataVecType, double> model;
TEST(TestTrain, TrainPLRModel) {
logData.GenerateDataset(&initData, &insertData, &testInsert);
model.maxChildIdx = kChildNum - 1;
model.Train(initData);
EXPECT_EQ(kChildNum - 1, model.maxChildIdx);
}
TEST(TestPredictInitData, PredictInitData) {
for (int i = 0; i < initData.size(); i++) {
int p = model.Predict(initData[i].first);
EXPECT_GE(p, 0);
EXPECT_LT(p, kChildNum);
}
}
TEST(TestPredictInsertData, PredictInsertData) {
for (int i = 0; i < insertData.size(); i++) {
int p = model.Predict(insertData[i].first);
EXPECT_GE(p, 0);
EXPECT_LT(p, kChildNum);
}
} | 24.729167 | 64 | 0.69166 | JiaoYiZhang |
415704f4b50e4fbda53e66a4c20d451e2d2493ec | 933 | cpp | C++ | luogu_1378/luogu_1378.cpp | skyfackr/luogu_personal_cppcode | b59af9839745d65091e6c01cddf53e5bb6fb274a | [
"BSD-3-Clause"
] | null | null | null | luogu_1378/luogu_1378.cpp | skyfackr/luogu_personal_cppcode | b59af9839745d65091e6c01cddf53e5bb6fb274a | [
"BSD-3-Clause"
] | null | null | null | luogu_1378/luogu_1378.cpp | skyfackr/luogu_personal_cppcode | b59af9839745d65091e6c01cddf53e5bb6fb274a | [
"BSD-3-Clause"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
double allsquare;
double beginx,beginy,endx,endy,ans;
bool bj[10];
int n,i,j,k;
const double pi=3.1415926535;
struct oils
{
double x,y;
double r;
} oil[10];
void rget(int i)
{
oil[i].r=min(min(abs(oil[i].x-beginx),abs(oil[i].x-endx)),min(abs(oil[i].y-beginy),abs(oil[i].y-endy)));
for (int j=1;j<=n;j++)
{
if (i!=j&&bj[j]==1)
{
oil[i].r=min(oil[i].r,max(0.0,sqrt(pow(oil[i].x-oil[j].x,2)+pow(oil[i].y-oil[j].y,2))-oil[j].r));
}
}
}
void dfs(int now,double ansx)
{
if (now>n)
{
ans=max(ans,ansx);
return ;
}
for (int i=1;i<=n;i++)
{
if (bj[i]==0)
{
bj[i]=1;
rget(i);
dfs(now+1,ansx+pow(oil[i].r,2)*pi);
bj[i]=0;
}
}
}
int main()
{
cin>>n;
cin>>beginx>>beginy>>endx>>endy;
for (i=1;i<=n;i++)
{
cin>>oil[i].x>>oil[i].y;
}
allsquare=abs(beginx-endx)*abs(beginy-endy);
dfs(1,0);
cout<<int(allsquare-ans+0.5)<<endl;
return 0;
}
| 16.660714 | 106 | 0.562701 | skyfackr |
4159c0f78d3e75c0d3e38523117ebefd0e8603f1 | 4,095 | cpp | C++ | PseudoContact.cpp | fanufree/assign-it | 7eae0828aea4964f1d459a14a0e13025fefc4c9a | [
"MIT"
] | null | null | null | PseudoContact.cpp | fanufree/assign-it | 7eae0828aea4964f1d459a14a0e13025fefc4c9a | [
"MIT"
] | null | null | null | PseudoContact.cpp | fanufree/assign-it | 7eae0828aea4964f1d459a14a0e13025fefc4c9a | [
"MIT"
] | null | null | null | /*
* PseudoContact.cpp
*
* Created on: 2012-05-03
* Author: e4k2
*/
#include <algorithm>
#include <cassert>
#include "PseudoContact.h"
#include "Utilities.h"
PseudoContact::PseudoContact() : contacts(), res1(-1), res2(-1)
{
}
PseudoContact::PseudoContact(const Contact& c) : contacts(), res1(c.r1->num), res2(c.r2->num)
{
contacts.insert(c);
}
PseudoContact::~PseudoContact()
{
}
PseudoContact::PseudoContact(const PseudoContact& pc) : contacts(pc.contacts), res1(pc.res1), res2(pc.res2)
{
}
void swap(PseudoContact& first, PseudoContact& second)
{
using std::swap;
swap(first.contacts,second.contacts);
swap(first.res1,second.res1);
swap(first.res2,second.res2);
}
//PseudoContact::PseudoContact(PseudoContact&& pc) : contacts()
//{
// swap(*this,pc);
//}
PseudoContact& PseudoContact::operator=(PseudoContact pc)
{
swap(*this,pc);
return *this;
}
void PseudoContact::add(const Contact& c)
{
contacts.insert(c);
if (res1 < 0)
{
res1 = c.r1->num;
res2 = c.r2->num;
}
else
{
assert(c.r1->num == res1 && c.r2->num == res2);
}
}
int PseudoContact::numContacts() const
{
return contacts.size();
}
void PseudoContact::print() const
{
for (tr1::unordered_set<Contact>::const_iterator it = contacts.begin(); it != contacts.end(); ++it)
{
it->print();
}
}
bool PseudoContact::operator==(const PseudoContact& pc) const
{
if (contacts.size() != pc.contacts.size())
return false;
for (tr1::unordered_set<Contact>::const_iterator it = pc.contacts.begin(); it != pc.contacts.end(); ++it)
{
if (contacts.find(*it) == contacts.end())
return false;
}
return true;
}
bool PseudoContact::areSymmetric(const PseudoContact& pc) const
{
if (contacts.size() != pc.contacts.size())
return false;
for (tr1::unordered_set<Contact>::const_iterator it = pc.contacts.begin(); it != pc.contacts.end(); ++it)
{
Contact c = it->reverse();
if (contacts.find(c) == contacts.end())
return false;
}
return true;
}
bool PseudoContact::operator!=(const PseudoContact& pc) const
{
return !(*this == pc);
}
tr1::unordered_set<Contact>& PseudoContact::getContacts()
{
return contacts;
}
Contact PseudoContact::getOneContact()
{
return *(contacts.begin());
}
// returns res1 <= res2
void PseudoContact::getResPairOrdered(int& res1, int& res2) const
{
if (this->res1 <= this->res2)
{
res1 = this->res1;
res2 = this->res2;
}
else
{
res1 = this->res2;
res2 = this->res1;
}
}
void PseudoContact::getResPair(int& res1, int& res2) const
{
res1 = this->res1;
res2 = this->res2;
}
void PseudoContact::setReverse()
{
std::swap(res1,res2);
vector<Contact> temp(contacts.begin(),contacts.end());
contacts.clear();
for (vector<Contact>::iterator it = temp.begin(); it != temp.end(); ++it)
{
contacts.insert(it->reverse());
}
}
bool PseudoContact::overlaps(const PseudoContact& pc) const
{
if (res1 == pc.res1 && res2 == pc.res2)
{
for (tr1::unordered_set<Contact>::const_iterator it1 = contacts.begin(); it1 != contacts.end(); ++it1)
{
const Contact& c1 = *it1;
for (tr1::unordered_set<Contact>::const_iterator it2 = pc.contacts.begin(); it2 != pc.contacts.end(); ++it2)
{
const Contact& c2 = *it2;
if (c1 == c2)
return true;
}
}
}
else if (res1 == pc.res2 && res2 == pc.res1)
{
for (tr1::unordered_set<Contact>::const_iterator it1 = contacts.begin(); it1 != contacts.end(); ++it1)
{
const Contact& c1 = *it1;
for (tr1::unordered_set<Contact>::const_iterator it2 = pc.contacts.begin(); it2 != pc.contacts.end(); ++it2)
{
const Contact& c2 = it2->reverse();
if (c1 == c2)
return true;
}
}
}
return false;
}
void PseudoContact::addAll(const PseudoContact& pc)
{
if (res1 == pc.res1 && res2 == pc.res2)
{
contacts.insert(pc.contacts.begin(),pc.contacts.end());
}
else if (res1 == pc.res2 && res2 == pc.res1)
{
for (tr1::unordered_set<Contact>::const_iterator it2 = pc.contacts.begin(); it2 != pc.contacts.end(); ++it2)
{
const Contact& c2 = it2->reverse();
contacts.insert(c2);
}
}
}
int PseudoContact::getSeqSep() const
{
return abs(res1-res2);
}
| 20.475 | 111 | 0.652259 | fanufree |
415a0601f9d104e6a6c2922a448f82de09c901bf | 6,714 | hpp | C++ | test/profiling/PubSubWriter.hpp | zhangzhimin/Fast-RTPS | 3032f11d0c62d226eea39ea4f8428afef4558693 | [
"Apache-2.0"
] | null | null | null | test/profiling/PubSubWriter.hpp | zhangzhimin/Fast-RTPS | 3032f11d0c62d226eea39ea4f8428afef4558693 | [
"Apache-2.0"
] | null | null | null | test/profiling/PubSubWriter.hpp | zhangzhimin/Fast-RTPS | 3032f11d0c62d226eea39ea4f8428afef4558693 | [
"Apache-2.0"
] | 1 | 2021-08-23T01:09:51.000Z | 2021-08-23T01:09:51.000Z | // Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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.
/**
* @file PubSubWriter.hpp
*
*/
#ifndef _TEST_PROFILING_PUBSUBWRITER_HPP_
#define _TEST_PROFILING_PUBSUBWRITER_HPP_
#include <fastrtps/fastrtps_fwd.h>
#include <fastrtps/Domain.h>
#include <fastrtps/participant/Participant.h>
#include <fastrtps/attributes/ParticipantAttributes.h>
#include <fastrtps/publisher/Publisher.h>
#include <fastrtps/publisher/PublisherListener.h>
#include <fastrtps/attributes/PublisherAttributes.h>
#include <string>
#include <list>
#include <condition_variable>
#include <boost/asio.hpp>
#include <boost/interprocess/detail/os_thread_functions.hpp>
template<class TypeSupport>
class PubSubWriter
{
class Listener : public eprosima::fastrtps::PublisherListener
{
public:
Listener(PubSubWriter &writer) : writer_(writer){};
~Listener(){};
void onPublicationMatched(eprosima::fastrtps::Publisher* /*pub*/, MatchingInfo &info)
{
if (info.status == MATCHED_MATCHING)
writer_.matched();
else
writer_.unmatched();
}
private:
Listener& operator=(const Listener&) NON_COPYABLE_CXX11;
PubSubWriter &writer_;
} listener_;
public:
typedef TypeSupport type_support;
typedef typename type_support::type type;
PubSubWriter(const std::string &topic_name) : listener_(*this), participant_(nullptr),
publisher_(nullptr), topic_name_(topic_name), initialized_(false), matched_(0)
{
publisher_attr_.topic.topicDataType = type_.getName();
// Generate topic name
std::ostringstream t;
t << topic_name_ << "_" << boost::asio::ip::host_name() << "_" << boost::interprocess::ipcdetail::get_current_process_id();
publisher_attr_.topic.topicName = t.str();
}
~PubSubWriter()
{
if(participant_ != nullptr)
eprosima::fastrtps::Domain::removeParticipant(participant_);
}
void init()
{
//Create participant
eprosima::fastrtps::ParticipantAttributes pattr;
pattr.rtps.builtin.domainId = (uint32_t)boost::interprocess::ipcdetail::get_current_process_id() % 230;
participant_ = eprosima::fastrtps::Domain::createParticipant(pattr);
if(participant_ != nullptr)
{
// Register type
eprosima::fastrtps::Domain::registerType(participant_, &type_);
//Create publisher
publisher_ = eprosima::fastrtps::Domain::createPublisher(participant_, publisher_attr_, &listener_);
if(publisher_ != nullptr)
{
initialized_ = true;
return;
}
eprosima::fastrtps::Domain::removeParticipant(participant_);
}
}
bool isInitialized() const { return initialized_; }
void destroy()
{
if(participant_ != nullptr)
{
eprosima::fastrtps::Domain::removeParticipant(participant_);
participant_ = nullptr;
}
}
void send(std::list<type>& msgs)
{
auto it = msgs.begin();
while(it != msgs.end())
{
if(publisher_->write((void*)&(*it)))
{
it = msgs.erase(it);
}
else
break;
}
}
void waitDiscovery()
{
std::cout << "Writer waiting for discovery..." << std::endl;
std::unique_lock<std::mutex> lock(mutex_);
if(matched_ == 0)
cv_.wait_for(lock, std::chrono::seconds(10));
std::cout << "Writer discovery phase finished" << std::endl;
}
void waitRemoval()
{
std::unique_lock<std::mutex> lock(mutex_);
if(matched_ != 0)
cv_.wait_for(lock, std::chrono::seconds(10));
}
bool waitForAllAcked(const std::chrono::seconds& max_wait)
{
return publisher_->wait_for_all_acked(Time_t((int32_t)max_wait.count(), 0));
}
/*** Function to change QoS ***/
PubSubWriter& reliability(const eprosima::fastrtps::ReliabilityQosPolicyKind kind)
{
publisher_attr_.qos.m_reliability.kind = kind;
return *this;
}
PubSubWriter& asynchronously(const eprosima::fastrtps::PublishModeQosPolicyKind kind)
{
publisher_attr_.qos.m_publishMode.kind = kind;
return *this;
}
PubSubWriter& history_kind(const eprosima::fastrtps::HistoryQosPolicyKind kind)
{
publisher_attr_.topic.historyQos.kind = kind;
return *this;
}
PubSubWriter& history_depth(const int32_t depth)
{
publisher_attr_.topic.historyQos.depth = depth;
return *this;
}
PubSubWriter& durability_kind(const eprosima::fastrtps::DurabilityQosPolicyKind kind)
{
publisher_attr_.qos.m_durability.kind = kind;
return *this;
}
PubSubWriter& resource_limits_max_samples(const int32_t max)
{
publisher_attr_.topic.resourceLimitsQos.max_samples = max;
return *this;
}
PubSubWriter& heartbeat_period_seconds(int32_t sec)
{
publisher_attr_.times.heartbeatPeriod.seconds = sec;
return *this;
}
PubSubWriter& heartbeat_period_fraction(uint32_t frac)
{
publisher_attr_.times.heartbeatPeriod.fraction = frac;
return *this;
}
private:
void matched()
{
std::unique_lock<std::mutex> lock(mutex_);
++matched_;
cv_.notify_one();
}
void unmatched()
{
std::unique_lock<std::mutex> lock(mutex_);
--matched_;
cv_.notify_one();
}
PubSubWriter& operator=(const PubSubWriter&)NON_COPYABLE_CXX11;
eprosima::fastrtps::Participant *participant_;
eprosima::fastrtps::PublisherAttributes publisher_attr_;
eprosima::fastrtps::Publisher *publisher_;
std::string topic_name_;
bool initialized_;
std::mutex mutex_;
std::condition_variable cv_;
unsigned int matched_;
type_support type_;
};
#endif // _TEST_PROFILING_PUBSUBWRITER_HPP_
| 28.09205 | 135 | 0.634346 | zhangzhimin |
4163f0229edb2eeda4f6cdd66a0b3c9b5e0da52e | 2,216 | hpp | C++ | src/common/Surface.hpp | LibreSprite/Dotto | 3d057875fd0e33d2a72add44c316af9fdc5be7c8 | [
"MIT"
] | 151 | 2021-12-28T21:22:42.000Z | 2022-03-30T13:53:28.000Z | src/common/Surface.hpp | LibreSprite/Dotto | 3d057875fd0e33d2a72add44c316af9fdc5be7c8 | [
"MIT"
] | 9 | 2021-12-29T13:20:00.000Z | 2022-03-18T12:47:19.000Z | src/common/Surface.hpp | Linux-Gamer/Dotto | ed722f0bbcbcb230b7c40977a5552cba81e5075d | [
"MIT"
] | 18 | 2021-12-28T19:58:49.000Z | 2022-03-31T16:38:14.000Z | // Copyright (c) 2021 LibreSprite Authors (cf. AUTHORS.md)
// This file is released under the terms of the MIT license.
// Read LICENSE.txt for more information.
#pragma once
#include <memory>
#include <variant>
#include <common/Color.hpp>
#include <common/Rect.hpp>
#include <common/types.hpp>
#include <gui/Texture.hpp>
class Surface : public std::enable_shared_from_this<Surface> {
public:
using PixelType = U32;
private:
U32 _width = 0, _height = 0;
Vector<PixelType> pixels;
std::unique_ptr<TextureInfo> _textureInfo;
public:
U32 width() const {return _width;}
U32 height() const {return _height;}
Rect rect() const {return {0, 0, _width, _height};}
PixelType* data() {return pixels.data();}
U32 dataSize() {return _width * _height * sizeof(PixelType);};
const Vector<PixelType>& getPixels() {return pixels;}
std::shared_ptr<Surface> clone();
TextureInfo& info();
void resize(U32 width, U32 height);
void setDirty(const Rect& region);
void setPixels(const Vector<PixelType>& read);
Color getPixel(U32 x, U32 y) {
U32 index = x + y * _width;
return (index >= _width * _height) ? Color{} : getColor(pixels[index]);
}
PixelType getPixelUnsafe(U32 x, U32 y) {
return pixels[x + y * _width];
}
void setPixelUnsafe(U32 x, U32 y, PixelType pixel) {
U32 index = x + y * _width;
pixels[index] = pixel;
setDirty({S32(x), S32(y), 1, 1});
}
void setHLine(S32 x, S32 y, S32 w, PixelType pixel);
void antsHLine(S32 x, S32 y, S32 w, U32 age, PixelType A, PixelType B);
void setVLine(S32 x, S32 y, S32 h, PixelType pixel);
void antsVLine(S32 x, S32 y, S32 h, U32 age, PixelType A, PixelType B);
void fillRect(const Rect& rect, PixelType pixel);
void setPixel(U32 x, U32 y, PixelType pixel);
void setPixel(U32 x, U32 y, const Color& color) {
setPixel(x, y, color.toU32());
}
Color getColor(PixelType pixel) {
return pixel;
}
Surface& operator = (const Surface& other) {
_width = other._width;
_height = other._height;
pixels = other.pixels;
setDirty(rect());
return *this;
}
};
| 29.157895 | 79 | 0.636733 | LibreSprite |
416b5fab9b61a030672653091ad09ce3e4bb9f7a | 3,965 | hpp | C++ | ql/experimental/preexperimental/cmsSwap.hpp | universe1987/QuantLib | bbb0145aff285853755b9f6ed013f53a41163acb | [
"BSD-3-Clause"
] | 4 | 2016-03-28T15:05:23.000Z | 2020-02-17T23:05:57.000Z | ql/experimental/preexperimental/cmsSwap.hpp | universe1987/QuantLib | bbb0145aff285853755b9f6ed013f53a41163acb | [
"BSD-3-Clause"
] | 1 | 2015-02-02T20:32:43.000Z | 2015-02-02T20:32:43.000Z | ql/experimental/preexperimental/cmsSwap.hpp | pcaspers/quantlib | bbb0145aff285853755b9f6ed013f53a41163acb | [
"BSD-3-Clause"
] | 10 | 2015-01-26T14:50:24.000Z | 2015-10-23T07:41:30.000Z | /*! \file cmsSwap.hpp
\brief Cms Swap
Peter Caspers
*/
#include <ql/quantlib.hpp>
#include <CmsPricer.hpp>
#ifndef quantlib_cmsSwap_hpp
#define quantlib_cmsSwap_hpp
using namespace boost;
using namespace std;
namespace QuantLib {
/*! cms swap */
class CmsSwap {
public:
/*! construct cms swap
for the structured leg the curve in the cms pricer is used as estimation and discount curve
for the float leg the estimation curve is the curve of the floatIndex
the discount curve for the float leg must be specified separately */
CmsSwap(boost::shared_ptr<Schedule> fixingSchedule,
boost::shared_ptr<Schedule> paymentSchedule,
boost::shared_ptr<Schedule> calculationSchedule,
boost::shared_ptr<SwapIndex> swapIndex,
DayCounter couponDayCounter,
boost::shared_ptr<Schedule> floatLegFixingSchedule,
boost::shared_ptr<Schedule> floatLegPaymentSchedule,
boost::shared_ptr<Schedule> floatLegCalculationSchedule,
boost::shared_ptr<IborIndex> floatIndex,
DayCounter floatLegCouponDayCounter,
boost::shared_ptr<YieldTermStructure> floatDiscountCurve
);
CmsSwap(boost::shared_ptr<Schedule> calculationSchedule,
int fixingDays,
boost::shared_ptr<SwapIndex> swapIndex,
DayCounter couponDayCounter,
boost::shared_ptr<Schedule> floatLegCalculationSchedule,
int floatFixingDays,
boost::shared_ptr<IborIndex> iborIndex,
DayCounter floatLegCouponDayCounter,
boost::shared_ptr<YieldTermStructure> floatDiscountCurve,
double strike=0.0000,
int flavour=1);
/*! return schedules */
std::vector<Date> fixingSchedule();
std::vector<Date> paymentSchedule();
std::vector<Date> calculationSchedule();
/*! return cms rates
adjusted = false => forward swap rates
adjusted = true => convexity adjusted forward swap rates */
std::vector<double> rates(bool adjusted);
/*! return upper bound of hedge portfolio */
std::vector<double> upperBounds();
/*! set cap floor payoff
flavour = 1 cap, -1 floor
strike of cap or floor */
bool setCapPayoff(double strike, int flavour) {
strike_=strike;
flavour_=flavour;
return true;
}
/*! set margin this is added _after_ flooring / capping (!) to structured leg */
bool setMargin(double margin) {
margin_=margin;
return true;
}
/*! npv of structured leg
precomputedSwaplets is the number of already computed swaplet prices
precomputedPrice is the price of the precomputed swaplets
swapletUppterBound is the index of the first swaplet that will not be computed (if 0 all swaplets will be computed) */
Real npv(boost::shared_ptr<CmsPricer> pricer,int precomputedSwaplets=0,double precomputedPrice=0.0,int swapletUpperBound=0);
/*! total npv of swap (pay structured leg, receive float leg with flat margin) */
Real CmsSwap::totalNpv(boost::shared_ptr<CmsPricer> pricer);
/*! get implied margin for cms swap
if number of swaplets is given, only implied margin of this part is returned (but including precomputed swaplets)
precomputed floatlets and floatlets upper bound refer to the float leg of the swap
they must be given, because the frequency of this leg can be different
if the latter two numbers are zero they are set to the corresponding values of the cms leg */
Real margin(boost::shared_ptr<CmsPricer> pricer, int precomputedSwaplets=0, double precomputedMargin=0.0, int swapletUpperBound=0, int precomputedFloatlets=0, int floatletUpperBound=0);
private:
vector<Date> fixings_,payments_,calc_;
vector<Date> floatFixings_,floatPayments_,floatCalc_;
vector<double> rates_,adjustedRates_,upperBound_;
boost::shared_ptr<SwapIndex> swapIndex_;
boost::shared_ptr<IborIndex> floatIndex_;
DayCounter couponDayCounter_,floatLegCouponDayCounter_;
double strike_,margin_;
int flavour_;
boost::shared_ptr<YieldTermStructure> floatDiscountCurve_;
};
}
#endif
| 35.720721 | 188 | 0.743253 | universe1987 |
416b984d852fec81708615caf4def63394124b70 | 1,056 | cpp | C++ | src/NeuralNetwork.cpp | lymven-io/NeuralNet | a1f997cea55d9e74e766c8a7f81e0d76e88f81b1 | [
"MIT"
] | null | null | null | src/NeuralNetwork.cpp | lymven-io/NeuralNet | a1f997cea55d9e74e766c8a7f81e0d76e88f81b1 | [
"MIT"
] | null | null | null | src/NeuralNetwork.cpp | lymven-io/NeuralNet | a1f997cea55d9e74e766c8a7f81e0d76e88f81b1 | [
"MIT"
] | null | null | null | #include "../include/NeuralNetwork.hpp"
void NeuralNetwork::printToConsole()
{
for(int i = 0; i < this->layers.size(); i++)
{
if(i == 0) {
Matrix *m = this->layers.at(i)->matrixifyVals();
m->printToConsole();
}
else {
Matrix *m = this->layers.at(i)->matrixifyActivatedVals();
m->printToConsole();
}
}
}
void NeuralNetwork::setCurrentInput(vector<double> input)
{
this->input = input;
for(int i = 0; i < input.size(); i++) {
this->layers.at(0)->setVal(i, input.at(i));
}
this->layers.at(0);
}
NeuralNetwork::NeuralNetwork(vector<int> topology) {
this->topology = topology;
this->topologySize = topology.size();
for(int i = 0; i < topology.size(); i++)
{
Layer *l = new Layer(topology.at(i));
this->layers.push_back(l);
}
for(int i = 0; i < (topologySize - 1); i++)
{
Matrix *m = new Matrix(topology.at(i), topology.at(i + 1), true);
this->weightMatrices.push_back(m);
}
} | 25.142857 | 73 | 0.542614 | lymven-io |
416def2f661532e2721ba6137ca76ccaa59f3195 | 72 | hpp | C++ | include/mruby_integration/shapes/pixel.hpp | HellRok/Taylor | aa9d901b4db77395a0bde896500016353adcd73b | [
"MIT"
] | 40 | 2021-05-25T04:21:49.000Z | 2022-02-19T05:05:45.000Z | include/mruby_integration/shapes/pixel.hpp | HellRok/Taylor | aa9d901b4db77395a0bde896500016353adcd73b | [
"MIT"
] | 4 | 2021-09-17T06:52:35.000Z | 2021-12-29T23:07:18.000Z | include/mruby_integration/shapes/pixel.hpp | HellRok/Taylor | aa9d901b4db77395a0bde896500016353adcd73b | [
"MIT"
] | 1 | 2021-12-23T00:59:27.000Z | 2021-12-23T00:59:27.000Z | #pragma once
#include "mruby.h"
void append_shapes_pixel(mrb_state*);
| 12 | 37 | 0.763889 | HellRok |
4174b84df1271075afe71f1bb0f028e0b2917692 | 3,898 | cpp | C++ | examples/model.cpp | afranchuk/clipp | 74f40c1718acc0822a4338587b9bbea9fdc5f737 | [
"MIT"
] | 910 | 2017-11-08T20:27:19.000Z | 2022-03-31T03:35:11.000Z | examples/model.cpp | afranchuk/clipp | 74f40c1718acc0822a4338587b9bbea9fdc5f737 | [
"MIT"
] | 58 | 2017-11-15T20:13:10.000Z | 2022-03-26T20:14:22.000Z | examples/model.cpp | afranchuk/clipp | 74f40c1718acc0822a4338587b9bbea9fdc5f737 | [
"MIT"
] | 98 | 2017-11-11T00:02:07.000Z | 2022-03-29T06:54:19.000Z | /*****************************************************************************
*
* demo program - part of CLIPP (command line interfaces for modern C++)
*
* released under MIT license
*
* (c) 2017-2018 André Müller; [email protected]
*
*****************************************************************************/
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
#include <clipp.h>
//-------------------------------------------------------------------
enum class mode {
none, train, validate, classify
};
struct settings {
mode selected = mode::none;
std::string imageFile;
std::string labelFile;
std::string modelFile = "out.mdl";
std::size_t batchSize = 128;
std::size_t threads = 0;
std::size_t inputLimit = 0;
std::vector<std::string> inputFiles;
};
//-------------------------------------------------------------------
settings configuration(int argc, char* argv[])
{
using namespace clipp;
settings s;
std::vector<std::string> unrecognized;
auto isfilename = clipp::match::prefix_not("-");
auto inputOptions = (
required("-i", "-I", "--img") & !value(isfilename, "image file", s.imageFile),
required("-l", "-L", "--lbl") & !value(isfilename, "label file", s.labelFile)
);
auto trainMode = (
command("train", "t", "T").set(s.selected,mode::train)
.if_conflicted([]{std::cerr << "conflicting modes\n"; }),
inputOptions,
(option("-n") & integer("limit", s.inputLimit))
% "limit number of input images",
(option("-o", "-O", "--out") & !value("model file", s.modelFile))
% "write model to specific file; default: 'out.mdl'",
(option("-b", "--batch-size") & integer("batch size", s.batchSize)),
(option("-p") & integer("threads", s.threads))
% "number of threads to use; default: optimum for machine"
);
auto validationMode = (
command("validate", "v", "V").set(s.selected,mode::validate),
!value(isfilename, "model", s.modelFile),
inputOptions
);
auto classificationMode = (
command("classify", "c", "C").set(s.selected,mode::classify),
!value(isfilename, "model", s.modelFile),
!values(isfilename, "images", s.inputFiles)
);
auto cli = (
trainMode | validationMode | classificationMode,
any_other(unrecognized)
);
auto res = parse(argc, argv, cli);
debug::print(std::cout, res);
if(!res || !unrecognized.empty()) {
std::string msg = "Wrong command line arguments!\n";
if(s.selected == mode::none) {
msg += "Please select a mode!\n";
}
else {
for(const auto& m : res.missing()) {
if(!m.param()->flags().empty()) {
msg += "Missing option: " + m.param()->flags().front() + '\n';
}
else if(!m.param()->label().empty()) {
msg += "Missing value: " + m.param()->label() + '\n';
}
}
for(const auto& arg : unrecognized) {
msg += "Argument not recognized: " + arg + '\n';
}
}
auto fmt = doc_formatting{}.first_column(8).doc_column(16);
//.max_flags_per_param_in_usage(3).surround_alternative_flags("(", ")");
msg += "\nUsage:\n" + usage_lines(cli, argv[0], fmt).str() + '\n';
msg += "\nOptions:\n" + documentation(cli, fmt).str() + '\n';
throw std::invalid_argument{msg};
}
return s;
}
//-------------------------------------------------------------------
int main(int argc, char* argv[])
{
try {
auto conf = configuration(argc, argv);
std::cout << "SUCCESS\n";
}
catch(std::exception& e) {
std::cerr << "ERROR: " << e.what() << '\n';
}
}
| 28.452555 | 86 | 0.491534 | afranchuk |
41780564bbf49892598f3708aef43749eaedd17a | 1,173 | hpp | C++ | Types/Containers/GpBytesArray.hpp | ITBear/GpCore2 | 7ae6d9d93aae55e2b3060077b5bb9d5f07e59ee4 | [
"MIT"
] | null | null | null | Types/Containers/GpBytesArray.hpp | ITBear/GpCore2 | 7ae6d9d93aae55e2b3060077b5bb9d5f07e59ee4 | [
"MIT"
] | 1 | 2020-06-19T18:38:40.000Z | 2020-06-19T18:38:40.000Z | Types/Containers/GpBytesArray.hpp | ITBear/GpCore2 | 7ae6d9d93aae55e2b3060077b5bb9d5f07e59ee4 | [
"MIT"
] | 6 | 2020-06-04T07:32:59.000Z | 2021-05-17T15:41:30.000Z | #pragma once
#include "../../Config/GpConfig.hpp"
#if defined(GP_USE_CONTAINERS)
#include "GpContainersT.hpp"
#include "../../Constexpr/GpConstexprIterator.hpp"
#include "../Pointers/GpRawPtr.hpp"
namespace GPlatform {
using GpBytesArray = GpVector<std::byte>;
class GpBytesArrayUtils
{
CLASS_REMOVE_CTRS_DEFAULT_MOVE_COPY(GpBytesArrayUtils)
public:
template<typename FROM, typename = std::enable_if_t<has_random_access_iter_v<FROM>, FROM>>
static GpBytesArray SMake (const FROM& aContainer)
{
GpBytesArray res;
const size_t size = aContainer.size();
res.resize(size);
MemOps::SCopy(res.data(),
reinterpret_cast<const std::byte*>(aContainer.data()),
count_t::SMake(size));
return res;
}
static GpBytesArray SMake (GpRawPtr<const std::byte*> aData)
{
GpBytesArray res;
res.resize(aData.CountLeft().As<size_t>());
GpRawPtr<std::byte*> resPtr(res);
resPtr.CopyFrom(aData);
return res;
}
};
}//GPlatform
#endif//#if defined(GP_USE_CONTAINERS)
| 24.957447 | 95 | 0.614663 | ITBear |
417b1b70e7606aacc175addf77c75c6a4037f285 | 16,048 | hpp | C++ | sprout/type_traits/std_type_traits.hpp | EzoeRyou/Sprout | 12e12373d0f70543eac5f2ecfbec8f5112765f98 | [
"BSL-1.0"
] | 1 | 2016-09-29T21:55:58.000Z | 2016-09-29T21:55:58.000Z | sprout/type_traits/std_type_traits.hpp | EzoeRyou/Sprout | 12e12373d0f70543eac5f2ecfbec8f5112765f98 | [
"BSL-1.0"
] | null | null | null | sprout/type_traits/std_type_traits.hpp | EzoeRyou/Sprout | 12e12373d0f70543eac5f2ecfbec8f5112765f98 | [
"BSL-1.0"
] | null | null | null | /*=============================================================================
Copyright (c) 2011-2014 Bolero MURAKAMI
https://github.com/bolero-MURAKAMI/Sprout
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#ifndef SPROUT_TYPE_TRAITS_STD_TYPE_TRAITS_HPP
#define SPROUT_TYPE_TRAITS_STD_TYPE_TRAITS_HPP
#include <cstddef>
#include <type_traits>
#include <sprout/config.hpp>
#include <sprout/detail/predef.hpp>
#include <sprout/type_traits/detail/type_traits_wrapper.hpp>
#if !defined(_LIBCPP_VERSION) || (_LIBCPP_VERSION < 1101)
# include <sprout/tpp/algorithm/max_element.hpp>
#endif
namespace sprout {
// 20.10.4.1 Primary type categories
template<typename T>
struct is_void
: public sprout::detail::type_traits_wrapper<std::is_void<T> >
{};
template<typename T>
struct is_null_pointer
: public sprout::detail::type_traits_wrapper<std::is_same<typename std::remove_cv<T>::type, std::nullptr_t> >
{};
template<typename T>
struct is_integral
: public sprout::detail::type_traits_wrapper<std::is_integral<T> >
{};
template<typename T>
struct is_floating_point
: public sprout::detail::type_traits_wrapper<std::is_floating_point<T> >
{};
template<typename T>
struct is_array
: public sprout::detail::type_traits_wrapper<std::is_array<T> >
{};
template<typename T>
struct is_pointer
: public sprout::detail::type_traits_wrapper<std::is_pointer<T> >
{};
template<typename T>
struct is_lvalue_reference
: public sprout::detail::type_traits_wrapper<std::is_lvalue_reference<T> >
{};
template<typename T>
struct is_rvalue_reference
: public sprout::detail::type_traits_wrapper<std::is_rvalue_reference<T> >
{};
template<typename T>
struct is_member_object_pointer
: public sprout::detail::type_traits_wrapper<std::is_member_object_pointer<T> >
{};
template<typename T>
struct is_member_function_pointer
: public sprout::detail::type_traits_wrapper<std::is_member_function_pointer<T> >
{};
template<typename T>
struct is_enum
: public sprout::detail::type_traits_wrapper<std::is_enum<T> >
{};
template<typename T>
struct is_union
: public sprout::detail::type_traits_wrapper<std::is_union<T> >
{};
template<typename T>
struct is_class
: public sprout::detail::type_traits_wrapper<std::is_class<T> >
{};
template<typename T>
struct is_function
: public sprout::detail::type_traits_wrapper<std::is_function<T> >
{};
// 20.10.4.2 Composite type traits
template<typename T>
struct is_reference
: public sprout::detail::type_traits_wrapper<std::is_reference<T> >
{};
template<typename T>
struct is_arithmetic
: public sprout::detail::type_traits_wrapper<std::is_arithmetic<T> >
{};
template<typename T>
struct is_fundamental
: public sprout::detail::type_traits_wrapper<std::is_fundamental<T> >
{};
template<typename T>
struct is_object
: public sprout::detail::type_traits_wrapper<std::is_object<T> >
{};
template<typename T>
struct is_scalar
: public sprout::detail::type_traits_wrapper<std::is_scalar<T> >
{};
template<typename T>
struct is_compound
: public sprout::detail::type_traits_wrapper<std::is_compound<T> >
{};
template<typename T>
struct is_member_pointer
: public sprout::detail::type_traits_wrapper<std::is_member_pointer<T> >
{};
// 20.10.4.3 Type properties
template<typename T>
struct is_const
: public sprout::detail::type_traits_wrapper<std::is_const<T> >
{};
template<typename T>
struct is_volatile
: public sprout::detail::type_traits_wrapper<std::is_volatile<T> >
{};
template<typename T>
struct is_trivial
: public sprout::detail::type_traits_wrapper<std::is_trivial<T> >
{};
#if !defined(_LIBCPP_VERSION)
template<typename T>
struct is_trivially_copyable
: public sprout::is_scalar<typename std::remove_all_extents<T>::type>
{};
#else
template<typename T>
struct is_trivially_copyable
: public sprout::detail::type_traits_wrapper<std::is_trivially_copyable<T> >
{};
#endif
template<typename T>
struct is_standard_layout
: public sprout::detail::type_traits_wrapper<std::is_standard_layout<T> >
{};
template<typename T>
struct is_pod
: public sprout::detail::type_traits_wrapper<std::is_pod<T> >
{};
template<typename T>
struct is_literal_type
: public sprout::detail::type_traits_wrapper<std::is_literal_type<T> >
{};
template<typename T>
struct is_empty
: public sprout::detail::type_traits_wrapper<std::is_empty<T> >
{};
template<typename T>
struct is_polymorphic
: public sprout::detail::type_traits_wrapper<std::is_polymorphic<T> >
{};
template<typename T>
struct is_abstract
: public sprout::detail::type_traits_wrapper<std::is_abstract<T> >
{};
template<typename T>
struct is_signed
: public sprout::detail::type_traits_wrapper<std::is_signed<T> >
{};
template<typename T>
struct is_unsigned
: public sprout::detail::type_traits_wrapper<std::is_unsigned<T> >
{};
template<typename T, typename... Args>
struct is_constructible
: public sprout::detail::type_traits_wrapper<std::is_constructible<T, Args...> >
{};
template<typename T>
struct is_default_constructible
: public sprout::detail::type_traits_wrapper<std::is_default_constructible<T> >
{};
template<typename T>
struct is_copy_constructible
: public sprout::detail::type_traits_wrapper<std::is_copy_constructible<T> >
{};
template<typename T>
struct is_move_constructible
: public sprout::detail::type_traits_wrapper<std::is_move_constructible<T> >
{};
template<typename T, typename U>
struct is_assignable
: public sprout::detail::type_traits_wrapper<std::is_assignable<T, U> >
{};
template<typename T>
struct is_copy_assignable
: public sprout::detail::type_traits_wrapper<std::is_copy_assignable<T> >
{};
template<typename T>
struct is_move_assignable
: public sprout::detail::type_traits_wrapper<std::is_move_assignable<T> >
{};
template<typename T>
struct is_destructible
: public sprout::detail::type_traits_wrapper<std::is_destructible<T> >
{};
#if !defined(_LIBCPP_VERSION)
#if SPROUT_CLANG_HAS_FUTURE(is_trivially_constructible)
template<typename T, typename... Args>
struct is_trivially_constructible
: public sprout::integral_constant<bool, __is_trivially_constructible(T, Args...)>
{};
#else // #if SPROUT_CLANG_HAS_FUTURE(is_trivially_constructible)
template<typename T, typename... Args>
struct is_trivially_constructible
: public sprout::false_type
{};
#if SPROUT_CLANG_HAS_FUTURE(has_trivial_constructor) || SPROUT_GCC_OR_LATER(4, 3, 0)
template<typename T>
struct is_trivially_constructible<T>
: public sprout::integral_constant<bool, __has_trivial_constructor(T)>
{};
#else // #if SPROUT_CLANG_HAS_FUTURE(has_trivial_constructor) || SPROUT_GCC_OR_LATER(4, 3, 0)
template<typename T>
struct is_trivially_constructible<T>
: public sprout::is_scalar<T>
{};
#endif // #if SPROUT_CLANG_HAS_FUTURE(has_trivial_constructor) || SPROUT_GCC_OR_LATER(4, 3, 0)
template<typename T>
struct is_trivially_constructible<T, T&>
: public sprout::is_scalar<T>
{};
template<typename T>
struct is_trivially_constructible<T, T const&>
: public sprout::is_scalar<T>
{};
template<typename T>
struct is_trivially_constructible<T, T&&>
: public sprout::is_scalar<T>
{};
template<typename T>
struct is_trivially_constructible<T, T const&&>
: public sprout::is_scalar<T>
{};
#endif // #if SPROUT_CLANG_HAS_FUTURE(is_trivially_constructible)
template<typename T>
struct is_trivially_default_constructible
: public sprout::is_trivially_constructible<T>
{};
template<typename T>
struct is_trivially_copy_constructible
: public sprout::is_trivially_constructible<T, typename std::add_lvalue_reference<T>::type const>
{};
template<typename T>
struct is_trivially_move_constructible
: public sprout::is_trivially_constructible<T, typename std::add_rvalue_reference<T>::type const>
{};
#if SPROUT_CLANG_HAS_FUTURE(is_trivially_assignable)
template<typename T, typename U>
struct is_trivially_assignable
: public sprout::integral_constant<bool, __is_trivially_assignable(T, U)>
{};
#else // #if SPROUT_CLANG_HAS_FUTURE(is_trivially_assignable)
template<typename T, typename U>
struct is_trivially_assignable
: public sprout::false_type
{};
template<typename T>
struct is_trivially_assignable<T&, T>
: public sprout::is_scalar<T>
{};
template<typename T>
struct is_trivially_assignable<T&, T&>
: public sprout::is_scalar<T>
{};
template<typename T>
struct is_trivially_assignable<T&, T const&>
: public sprout::is_scalar<T>
{};
template<typename T>
struct is_trivially_assignable<T&, T&&>
: public sprout::is_scalar<T>
{};
template<typename T>
struct is_trivially_assignable<T&, T const&&>
: public sprout::is_scalar<T>
{};
#endif // #if SPROUT_CLANG_HAS_FUTURE(is_trivially_assignable)
template<typename T>
struct is_trivially_copy_assignable
: public sprout::is_trivially_assignable<
typename std::add_lvalue_reference<T>::type,
typename std::add_lvalue_reference<T>::type const
>
{};
template<typename T>
struct is_trivially_move_assignable
: public sprout::is_trivially_assignable<
typename std::add_lvalue_reference<T>::type,
typename std::add_rvalue_reference<T>::type
>
{};
#else // #if !defined(_LIBCPP_VERSION)
template<typename T, typename... Args>
struct is_trivially_constructible
: public sprout::detail::type_traits_wrapper<std::is_trivially_constructible<T, Args...> >
{};
template<typename T>
struct is_trivially_default_constructible
: public sprout::detail::type_traits_wrapper<std::is_trivially_default_constructible<T> >
{};
template<typename T>
struct is_trivially_copy_constructible
: public sprout::detail::type_traits_wrapper<std::is_trivially_copy_constructible<T> >
{};
template<typename T>
struct is_trivially_move_constructible
: public sprout::detail::type_traits_wrapper<std::is_trivially_move_constructible<T> >
{};
template<typename T, typename U>
struct is_trivially_assignable
: public sprout::detail::type_traits_wrapper<std::is_trivially_assignable<T, U> >
{};
template<typename T>
struct is_trivially_copy_assignable
: public sprout::detail::type_traits_wrapper<std::is_trivially_copy_assignable<T> >
{};
template<typename T>
struct is_trivially_move_assignable
: public sprout::detail::type_traits_wrapper<std::is_trivially_move_assignable<T> >
{};
#endif // #if !defined(_LIBCPP_VERSION)
#if !defined(_LIBCPP_VERSION) && SPROUT_GCC_EARLIER(4, 8, 0)
#if SPROUT_CLANG_HAS_FUTURE(has_trivial_destructor) || SPROUT_GCC_OR_LATER(4, 3, 0)
template<typename T>
struct is_trivially_destructible
: public sprout::integral_constant<bool, __has_trivial_destructor(T)>
{};
#else // #if SPROUT_CLANG_HAS_FUTURE(has_trivial_destructor) || SPROUT_GCC_OR_LATER(4, 3, 0)
template<typename T>
struct is_trivially_destructible
: public sprout::integral_constant<
bool,
std::is_scalar<typename std::remove_all_extents<T>::type>::value
|| std::is_reference<typename std::remove_all_extents<T>::type>::value
>
{};
#endif // #if SPROUT_CLANG_HAS_FUTURE(has_trivial_destructor) || SPROUT_GCC_OR_LATER(4, 3, 0)
#else // #if !defined(_LIBCPP_VERSION) && SPROUT_GCC_EARLIER(4, 8, 0)
template<typename T>
struct is_trivially_destructible
: public sprout::detail::type_traits_wrapper<std::is_trivially_destructible<T> >
{};
#endif // #if !defined(_LIBCPP_VERSION) && SPROUT_GCC_EARLIER(4, 8, 0)
template<typename T, typename... Args>
struct is_nothrow_constructible
: public sprout::detail::type_traits_wrapper<std::is_nothrow_constructible<T, Args...> >
{};
template<typename T>
struct is_nothrow_default_constructible
: public sprout::detail::type_traits_wrapper<std::is_nothrow_default_constructible<T> >
{};
template<typename T>
struct is_nothrow_copy_constructible
: public sprout::detail::type_traits_wrapper<std::is_nothrow_copy_constructible<T> >
{};
template<typename T>
struct is_nothrow_move_constructible
: public sprout::detail::type_traits_wrapper<std::is_nothrow_move_constructible<T> >
{};
template<typename T, typename U>
struct is_nothrow_assignable
: public sprout::detail::type_traits_wrapper<std::is_nothrow_assignable<T, U> >
{};
template<typename T>
struct is_nothrow_copy_assignable
: public sprout::detail::type_traits_wrapper<std::is_nothrow_copy_assignable<T> >
{};
template<typename T>
struct is_nothrow_move_assignable
: public sprout::detail::type_traits_wrapper<std::is_nothrow_move_assignable<T> >
{};
#if !defined(_LIBCPP_VERSION) && SPROUT_GCC_EARLIER(4, 8, 0)
template<typename T>
struct is_nothrow_destructible
: public sprout::integral_constant<
bool,
std::is_scalar<typename std::remove_all_extents<T>::type>::value
|| std::is_reference<typename std::remove_all_extents<T>::type>::value
>
{};
#else // #if !defined(_LIBCPP_VERSION) && SPROUT_GCC_EARLIER(4, 8, 0)
template<typename T>
struct is_nothrow_destructible
: public sprout::detail::type_traits_wrapper<std::is_nothrow_destructible<T> >
{};
#endif // #if !defined(_LIBCPP_VERSION) && SPROUT_GCC_EARLIER(4, 8, 0)
template<typename T>
struct has_virtual_destructor
: public sprout::detail::type_traits_wrapper<std::has_virtual_destructor<T> >
{};
// 20.10.5 Type property queries
template<typename T>
struct alignment_of
: public sprout::detail::type_traits_wrapper<std::alignment_of<T> >
{};
template<typename T>
struct rank
: public sprout::detail::type_traits_wrapper<std::rank<T> >
{};
template<typename T, unsigned I = 0>
struct extent
: public sprout::detail::type_traits_wrapper<std::extent<T, I> >
{};
// 20.10.6 Relationships between types
template<typename T, typename U>
struct is_same
: public sprout::detail::type_traits_wrapper<std::is_same<T, U> >
{};
template<typename From, typename To>
struct is_base_of
: public sprout::detail::type_traits_wrapper<std::is_base_of<From, To> >
{};
template<typename From, typename To>
struct is_convertible
: public sprout::detail::type_traits_wrapper<std::is_convertible<From, To> >
{};
// 20.10.7.1 Const-volatile modifications
using std::remove_const;
using std::remove_volatile;
using std::remove_cv;
using std::add_const;
using std::add_volatile;
using std::add_cv;
// 20.10.7.2 Reference modifications
using std::remove_reference;
using std::add_lvalue_reference;
using std::add_rvalue_reference;
// 20.10.7.3 Sign modifications
using std::make_signed;
using std::make_unsigned;
// 20.10.7.4 Array modifications
using std::remove_extent;
using std::remove_all_extents;
// 20.10.7.5 Pointer modifications
using std::remove_pointer;
using std::add_pointer;
// 20.10.7.6 Other transformations
using std::aligned_storage;
#if !defined(_LIBCPP_VERSION) || (_LIBCPP_VERSION < 1101)
template<std::size_t Len, typename... Types>
struct aligned_union
: public std::aligned_storage<
sprout::tpp::max_element_c<std::size_t, Len, sizeof(Types)...>::value,
sprout::tpp::max_element_c<std::size_t, std::alignment_of<Types>::value...>::value
>
{};
#else // #if !defined(_LIBCPP_VERSION) || (_LIBCPP_VERSION < 1101)
using std::aligned_union;
#endif // #if !defined(_LIBCPP_VERSION) || (_LIBCPP_VERSION < 1101)
using std::decay;
using std::enable_if;
using std::conditional;
using std::common_type;
using std::underlying_type;
using std::result_of;
} // namespace sprout
#endif // #ifndef SPROUT_TYPE_TRAITS_STD_TYPE_TRAITS_HPP
| 33.433333 | 112 | 0.730122 | EzoeRyou |
417c4a8dbd295fa9a54b47e487a667ba1b57d815 | 5,772 | cpp | C++ | src/common/test/test_term_tokenizer.cpp | datavetaren/prologcoin | 8583db7d99a8007f634210aefdfb92bf45596fd3 | [
"MIT"
] | 38 | 2017-06-14T07:13:10.000Z | 2022-02-16T15:41:25.000Z | src/common/test/test_term_tokenizer.cpp | datavetaren/prologcoin | 8583db7d99a8007f634210aefdfb92bf45596fd3 | [
"MIT"
] | 10 | 2017-07-01T11:13:10.000Z | 2021-02-27T05:40:30.000Z | src/common/test/test_term_tokenizer.cpp | datavetaren/prologcoin | 8583db7d99a8007f634210aefdfb92bf45596fd3 | [
"MIT"
] | 7 | 2017-07-05T20:38:51.000Z | 2021-08-02T04:30:46.000Z | #include <iostream>
#include <iomanip>
#include <assert.h>
#include <common/term_tokenizer.hpp>
#include <common/token_chars.hpp>
using namespace prologcoin::common;
static void header( const std::string &str )
{
std::cout << "\n";
std::cout << "--- [" + str + "] " + std::string(60 - str.length(), '-') << "\n";
std::cout << "\n";
}
static void test_is_symbol_char()
{
header( "test_is_symbol_char()" );
std::string str;
bool in_seq = false;
for (int i = 0; i < 500; i++) {
if (term_tokenizer::is_symbol_char(i)) {
if (!in_seq && !str.empty()) {
str += ", ";
}
if (!in_seq) {
str += boost::lexical_cast<std::string>(i);
}
if (!in_seq &&
term_tokenizer::is_symbol_char(i+1) &&
term_tokenizer::is_symbol_char(i+2)) {
in_seq = true;
}
}
if (in_seq && !term_tokenizer::is_symbol_char(i)) {
str += "..";
str += boost::lexical_cast<std::string>(i-1);
in_seq = false;
}
}
std::cout << "Symbol chars: " + str + "\n";
assert( str ==
"35, 36, 38, 42, 43, 45..47, 58, 60..64, 92, 94, 96, 126, "
"160..191, 215, 247");
}
static void test_tokens()
{
header( "test_tokens()" );
std::string s = "this is a test'\\^?\\^Z\\^a'\t\n\t+=/*bla/* ha */ xx *q*/\001%To/*themoon\xf0\n'foo'!0'a0'\\^g4242 42.4711 42e3 47.11e-12Foo_Bar\"string\"\"\\^g\" _Baz__ 'bar\x55'[;].";
std::string expected[] = { "token<NAME>[this]@(L1,C1)",
"token<LAYOUT_TEXT>[\\x20]@(L1,C5)",
"token<NAME>[is]@(L1,C6)",
"token<LAYOUT_TEXT>[\\x20]@(L1,C8)",
"token<NAME>[a]@(L1,C9)",
"token<LAYOUT_TEXT>[\\x20]@(L1,C10)",
"token<NAME>[test]@(L1,C11)",
"token<NAME>[\\x7f\\x1a\\x01]@(L1,C15)",
"token<LAYOUT_TEXT>[\\x09\\x0a\\x09]@(L1,C26)",
"token<NAME>[+=]@(L2,C8)",
"token<LAYOUT_TEXT>[/*bla/*\\x20ha\\x20*/\\x20xx\\x20*q*/\\x01%To/*themoon\\xf0\\x0a]@(L2,C10)",
"token<NAME>[foo]@(L3,C1)",
"token<NAME>[!]@(L3,C6)",
"token<NATURAL_NUMBER>[97]@(L3,C7)",
"token<NATURAL_NUMBER>[7]@(L3,C10)",
"token<NATURAL_NUMBER>[4242]@(L3,C15)",
"token<LAYOUT_TEXT>[\\x20]@(L3,C19)",
"token<UNSIGNED_FLOAT>[42.4711]@(L3,C20)",
"token<LAYOUT_TEXT>[\\x20]@(L3,C27)",
"token<UNSIGNED_FLOAT>[42e3]@(L3,C28)",
"token<LAYOUT_TEXT>[\\x20]@(L3,C32)",
"token<UNSIGNED_FLOAT>[47.11e-12]@(L3,C33)",
"token<VARIABLE>[Foo_Bar]@(L3,C42)",
"token<STRING>[string\\x22\\x07]@(L3,C49)",
"token<LAYOUT_TEXT>[\\x20]@(L3,C62)",
"token<VARIABLE>[_Baz__]@(L3,C63)",
"token<LAYOUT_TEXT>[\\x20]@(L3,C69)",
"token<NAME>[barU]@(L3,C70)",
"token<PUNCTUATION_CHAR>[[]@(L3,C76)",
"token<NAME>[;]@(L3,C77)",
"token<PUNCTUATION_CHAR>[]]@(L3,C78)",
"token<FULL_STOP>[.]@(L3,C79)" };
std::stringstream ss(s, (std::stringstream::in | std::stringstream::binary));
term_tokenizer tt(ss);
int cnt = 0;
while (tt.has_more_tokens()) {
auto tok = tt.next_token();
std::cout << tok.str() << "\n";
if (tok.str() != expected[cnt]) {
std::cout << "Expected token: " << expected[cnt] << "\n";
std::cout << "But got : " << tok.str() << "\n";
}
assert( tok.str() == expected[cnt] );
cnt++;
}
}
static void test_negative_tokens()
{
header( "test_negative_tokens()" );
struct entry { std::string str;
token_exception *exc;
};
auto p = [](int line, int col) { return token_position(line,col); };
entry table[] =
{ { "'foo", new token_exception_unterminated_quoted_name("",p(1,1)) }
,{ "'esc\\", new token_exception_unterminated_escape("",p(1,1)) }
,{ "'esc\\x", new token_exception_unterminated_escape("",p(1,1)) }
,{ "'esc\\x3", new token_exception_unterminated_escape("",p(1,1)) }
,{ "'esc\\^", new token_exception_unterminated_escape("",p(1,1)) }
,{ "'esc\\^\t", new token_exception_control_char("",p(1,1)) }
,{ "'esc\\xg", new token_exception_hex_code("", p(1,1)) }
,{ "0'", new token_exception_no_char_code("", p(1,1)) }
,{ "11'", new token_exception_missing_number_after_base("", p(1,1)) }
,{ "1.x", new token_exception_missing_decimal("", p(1,1)) }
,{ "1.e", new token_exception_missing_decimal("", p(1,1)) }
,{ "1ex", new token_exception_missing_exponent("", p(1,1)) }
,{ "1e+", new token_exception_missing_exponent("", p(1,1)) }
,{ "1e-", new token_exception_missing_exponent("", p(1,1)) }
,{ "2E-", new token_exception_missing_exponent("", p(1,1)) }
,{ "\"foo", new token_exception_unterminated_string("", p(1,1)) }
};
for (auto e : table) {
std::stringstream ss(e.str);
term_tokenizer tt(ss);
try {
std::cout << "Testing token: " << e.str << "\n";
tt.next_token();
std::cout << " (Expected exception '" << typeid(e.exc).name() << "' not thrown)\n";
assert(false);
} catch (token_exception &exc) {
std::string actual = typeid(exc).name();
std::string expected = typeid(*e.exc).name();
std::cout << " Thrown: " << actual << "\n";
if (actual != expected) {
std::cout << " (Expected exception '" << expected
<< "' but got '" << actual << "'\n";
assert(false);
}
if (exc.pos() != e.exc->pos()) {
std::cout << " (Expected position " << e.exc->pos().str()
<< " but got " << exc.pos().str() << ")\n";
assert(false);
}
delete e.exc; // Free memory (good for valgrind)
}
}
}
int main( int argc, char *argv[] )
{
test_is_symbol_char();
test_tokens();
test_negative_tokens();
return 0;
}
| 33.754386 | 190 | 0.537769 | datavetaren |
41810bee9ee062e7d157e3b6810e18d0ad0ab638 | 41 | cpp | C++ | libwinston/Route.cpp | danie1kr/winston | 18fe865dc59e8315cb1d85c6fa60c4ddeaf83202 | [
"MIT"
] | null | null | null | libwinston/Route.cpp | danie1kr/winston | 18fe865dc59e8315cb1d85c6fa60c4ddeaf83202 | [
"MIT"
] | null | null | null | libwinston/Route.cpp | danie1kr/winston | 18fe865dc59e8315cb1d85c6fa60c4ddeaf83202 | [
"MIT"
] | null | null | null | #include "Route.h"
namespace winston {
} | 10.25 | 19 | 0.707317 | danie1kr |
4181584b4077eb16adf436c1548283fa45fe66fc | 2,530 | cc | C++ | local/Ground.cc | jube/pong | df14055f4185a6b680acb9de685a94ccd6b33946 | [
"MIT"
] | null | null | null | local/Ground.cc | jube/pong | df14055f4185a6b680acb9de685a94ccd6b33946 | [
"MIT"
] | null | null | null | local/Ground.cc | jube/pong | df14055f4185a6b680acb9de685a94ccd6b33946 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2015, Julien Bernard
*
* 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 "Ground.h"
#include "Ball.h"
#include "Events.h"
#include "Singletons.h"
Ground::Ground() {
gEventManager().registerHandler<BallLocationEvent>(&Ground::onBallLocation, this);
}
void Ground::render(sf::RenderWindow& window) {
sf::RectangleShape shape({ WIDTH, HEIGHT });
shape.setOrigin(WIDTH / 2, HEIGHT / 2);
shape.setPosition(0.0f, 0.0f);
shape.setFillColor(sf::Color::Black);
window.draw(shape);
}
game::EventStatus Ground::onBallLocation(game::EventType type, game::Event *event) {
auto loc = static_cast<BallLocationEvent*>(event);
static constexpr float Y_LIMIT = HEIGHT / 2 - Ball::RADIUS;
if (loc->position.y > Y_LIMIT) {
loc->velocity.y = -loc->velocity.y;
loc->position.y = Y_LIMIT;
}
if (loc->position.y < -Y_LIMIT) {
loc->velocity.y = -loc->velocity.y;
loc->position.y = -Y_LIMIT;
}
static constexpr float X_LIMIT = WIDTH / 2 - Ball::RADIUS;
if (loc->position.x > X_LIMIT) {
PointEvent point;
point.location = Paddle::Location::RIGHT;
gEventManager().triggerEvent(&point);
loc->velocity.x = -loc->velocity.x;
loc->position = sf::Vector2f(0, 0);
}
if (loc->position.x < -X_LIMIT) {
PointEvent point;
point.location = Paddle::Location::LEFT;
gEventManager().triggerEvent(&point);
loc->velocity.x = -loc->velocity.x;
loc->position = sf::Vector2f(0, 0);
}
return game::EventStatus::KEEP;
}
| 32.857143 | 84 | 0.706719 | jube |
41868d148862cc4c37bf157b2c06ca6d9b488c22 | 1,002 | cpp | C++ | 14/tests/into.cpp | rapha-opensource/viper | 78f25771c7198ac66b846afde3f38c8b2c1c7cc9 | [
"MIT"
] | 2 | 2018-04-28T19:54:49.000Z | 2021-01-13T17:31:12.000Z | 17/tests/into.cpp | rapha-opensource/viper | 78f25771c7198ac66b846afde3f38c8b2c1c7cc9 | [
"MIT"
] | null | null | null | 17/tests/into.cpp | rapha-opensource/viper | 78f25771c7198ac66b846afde3f38c8b2c1c7cc9 | [
"MIT"
] | null | null | null | #include <vector>
#include "catch.hpp"
#include "../headers/iterator_cast.h"
SCENARIO(" 'into' with only an input container, no transformation", "[into]") {
GIVEN(" a std::vector<char> vc") {
std::vector<char> vc{'a','b','c','d'};
WHEN( " make a string using into<std::string>(vc) " ) {
auto str = into<std::string>(vc);
THEN(" the size and value match ") {
REQUIRE( str.size() == vc.size() );
REQUIRE( str == "abcd" );
}
}
}
}
SCENARIO( " 'into' with a unary fn ", "[into], [transform]") {
GIVEN(" a std::vector<int> ") {
std::vector<int> vi{1,2,3,4};
WHEN(" transformed 'into' in a string ") {
auto str = into<std::string>([](const int& i) { return (char)(i+48); }, vi);
THEN(" must match in size and content ") {
REQUIRE( str.size() == vi.size() );
REQUIRE( str == "1234" );
}
}
}
}
| 23.302326 | 89 | 0.474052 | rapha-opensource |
4189e9260add3f96370d11651bb4c773844223d5 | 2,658 | cpp | C++ | contracts/calculator/calc.cpp | koinos/koinos-contract-examples | 27f2bd11b31997ac69d824a5d8a729295072a4c3 | [
"MIT"
] | 1 | 2021-12-21T20:01:36.000Z | 2021-12-21T20:01:36.000Z | contracts/calculator/calc.cpp | koinos/koinos-contract-examples | 27f2bd11b31997ac69d824a5d8a729295072a4c3 | [
"MIT"
] | null | null | null | contracts/calculator/calc.cpp | koinos/koinos-contract-examples | 27f2bd11b31997ac69d824a5d8a729295072a4c3 | [
"MIT"
] | 1 | 2021-11-23T19:10:26.000Z | 2021-11-23T19:10:26.000Z | #include <koinos/system/system_calls.hpp>
#include <koinos/buffer.hpp>
#include <koinos/common.h>
#include <calc.h>
using namespace koinos;
using namespace koinos::contracts;
enum entries : uint32_t
{
add_entry = 1,
sub_entry = 2,
mul_entry = 3,
div_entry = 4
};
class calculator
{
public:
calc::add_result add( int64_t x, int64_t y ) noexcept;
calc::sub_result sub( int64_t x, int64_t y ) noexcept;
calc::mul_result mul( int64_t x, int64_t y ) noexcept;
calc::div_result div( int64_t x, int64_t y ) noexcept;
};
calc::add_result calculator::add( int64_t x, int64_t y ) noexcept
{
calc::add_result res;
res.set_value( x + y );
return res;
}
calc::sub_result calculator::sub( int64_t x, int64_t y ) noexcept
{
calc::sub_result res;
res.set_value( x - y );
return res;
}
calc::mul_result calculator::mul( int64_t x, int64_t y ) noexcept
{
calc::mul_result res;
res.set_value( x * y );
return res;
}
calc::div_result calculator::div( int64_t x, int64_t y ) noexcept
{
calc::div_result res;
if ( y == 0 )
{
system::print( "cannot divide by zero" );
system::exit_contract( 1 );
}
res.set_value( x / y );
return res;
}
int main()
{
auto entry_point = system::get_entry_point();
auto args = system::get_contract_arguments();
std::array< uint8_t, 32 > retbuf;
koinos::read_buffer rdbuf( (uint8_t*)args.c_str(), args.size() );
koinos::write_buffer buffer( retbuf.data(), retbuf.size() );
calculator c;
switch( entry_point )
{
case entries::add_entry:
{
calc::add_arguments args;
args.deserialize( rdbuf );
auto res = c.add( args.x(), args.y() );
res.serialize( buffer );
break;
}
case entries::sub_entry:
{
calc::sub_arguments args;
args.deserialize( rdbuf );
auto res = c.sub( args.x(), args.y() );
res.serialize( buffer );
break;
}
case entries::mul_entry:
{
calc::mul_arguments args;
args.deserialize( rdbuf );
auto res = c.mul( args.x(), args.y() );
res.serialize( buffer );
break;
}
case entries::div_entry:
{
calc::div_arguments args;
args.deserialize( rdbuf );
auto res = c.div( args.x(), args.y() );
res.serialize( buffer );
break;
}
default:
system::exit_contract( 1 );
}
std::string retval( reinterpret_cast< const char* >( buffer.data() ), buffer.get_size() );
system::set_contract_result_bytes( retval );
system::exit_contract( 0 );
return 0;
}
| 21.435484 | 93 | 0.599323 | koinos |
418d9b77a6c64fdf521ccc324cec54c858d1fc4a | 2,233 | cc | C++ | re2c/src/codegen/helpers.cc | adesutherland/crexx | e8d17152c565e9387ee8c33c653b4910b56f5165 | [
"MIT"
] | 8 | 2020-11-08T15:36:14.000Z | 2022-03-27T13:50:07.000Z | re2c/src/codegen/helpers.cc | adesutherland/crexx | e8d17152c565e9387ee8c33c653b4910b56f5165 | [
"MIT"
] | 98 | 2020-11-12T11:49:41.000Z | 2022-03-27T17:24:13.000Z | re2c/src/codegen/helpers.cc | adesutherland/crexx | e8d17152c565e9387ee8c33c653b4910b56f5165 | [
"MIT"
] | 10 | 2021-03-31T13:50:52.000Z | 2021-12-02T03:34:42.000Z | #include <iostream>
#include "src/codegen/helpers.h"
namespace re2c {
static bool is_space(uint32_t c)
{
switch (c) {
case '\t':
case '\f':
case '\v':
case '\n':
case '\r':
case ' ': return true;
default: return false;
}
}
static inline char hex(uint32_t c)
{
static const char * sHex = "0123456789ABCDEF";
return sHex[c & 0x0F];
}
static void prtCh(std::ostream& o, uint32_t c, bool dot)
{
switch (c) {
case '\'': o << (dot ? "'" : "\\'"); break;
case '"': o << (dot ? "\\\"" : "\""); break;
case '\n': o << (dot ? "\\\\n" : "\\n"); break;
case '\t': o << (dot ? "\\\\t" : "\\t"); break;
case '\v': o << (dot ? "\\\\v" : "\\v"); break;
case '\b': o << (dot ? "\\\\b" : "\\b"); break;
case '\r': o << (dot ? "\\\\r" : "\\r"); break;
case '\f': o << (dot ? "\\\\f" : "\\f"); break;
case '\a': o << (dot ? "\\\\a" : "\\a"); break;
case '\\': o << "\\\\"; break; // both .dot and C/C++ code expect "\\"
default: o << static_cast<char> (c); break;
}
}
bool is_print(uint32_t c)
{
return c >= 0x20 && c < 0x7F;
}
void prtHex(std::ostream& o, uint32_t c, uint32_t szcunit)
{
o << "0x";
if (szcunit >= 4) {
o << hex(c >> 28u) << hex(c >> 24u) << hex(c >> 20u) << hex(c >> 16u);
}
if (szcunit >= 2) {
o << hex(c >> 12u) << hex(c >> 8u);
}
o << hex(c >> 4u) << hex(c);
}
void prtChOrHex(std::ostream& o, uint32_t c, uint32_t szcunit, bool ebcdic, bool dot)
{
if (!ebcdic && (is_print(c) || is_space(c))) {
o << '\'';
prtCh(o, c, dot);
o << '\'';
} else {
prtHex(o, c, szcunit);
}
}
static void prtChOrHexForSpan(std::ostream& o, uint32_t c, uint32_t szcunit, bool ebcdic, bool dot)
{
if (!ebcdic && c != ']' && is_print(c)) {
prtCh(o, c, dot);
} else {
prtHex(o, c, szcunit);
}
}
void printSpan(std::ostream& o, uint32_t l, uint32_t u, uint32_t szcunit, bool ebcdic, bool dot)
{
o << "[";
prtChOrHexForSpan(o, l, szcunit, ebcdic, dot);
if (u - l > 1) {
o << "-";
prtChOrHexForSpan(o, u - 1, szcunit, ebcdic, dot);
}
o << "]";
}
} // namespace re2c
| 23.260417 | 99 | 0.467532 | adesutherland |
418df50b16205e781e5fc25d772cd4ffbaf5a2c1 | 311 | cpp | C++ | beginners/easy/014.grade-description/034.rishankahn.grade-description.cpp | Md-Maruf-Sarker/strangers | 6f9eae6c15f1e1c5b6ef2965eb2422a01203f1ad | [
"MIT"
] | 3 | 2022-03-26T17:56:38.000Z | 2022-03-27T10:47:26.000Z | beginners/easy/014.grade-description/034.rishankahn.grade-description.cpp | Md-Maruf-Sarker/strangers | 6f9eae6c15f1e1c5b6ef2965eb2422a01203f1ad | [
"MIT"
] | null | null | null | beginners/easy/014.grade-description/034.rishankahn.grade-description.cpp | Md-Maruf-Sarker/strangers | 6f9eae6c15f1e1c5b6ef2965eb2422a01203f1ad | [
"MIT"
] | 8 | 2022-03-26T18:19:49.000Z | 2022-03-31T18:18:34.000Z | #include <iostream>
using namespace std;
int main() {
char g;
cout<<"Input the grade : ";
cin>>g;
if(g=='E'){
cout<<"Excellent\n";
}
else if(g=='V'){
cout<<"Very Good\n";
}
else if(g=='G'){
cout<<"Good\n";
}
else if(g=='A'){
cout<<"Average\n";
}
else{
cout<<"Fail\n";
}
}
| 12.958333 | 28 | 0.495177 | Md-Maruf-Sarker |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.