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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c7f72e6d15db91277c9f4fb1210e6213dd14a20e
| 791
|
cpp
|
C++
|
Codeforces/1618A-polycarp-and-sums-of-subsequences.cpp
|
SusmoySenGupta/online-judge-solutions
|
8735a1bc71a05dc46255664c3ec6f47f042bfa6c
|
[
"MIT"
] | null | null | null |
Codeforces/1618A-polycarp-and-sums-of-subsequences.cpp
|
SusmoySenGupta/online-judge-solutions
|
8735a1bc71a05dc46255664c3ec6f47f042bfa6c
|
[
"MIT"
] | null | null | null |
Codeforces/1618A-polycarp-and-sums-of-subsequences.cpp
|
SusmoySenGupta/online-judge-solutions
|
8735a1bc71a05dc46255664c3ec6f47f042bfa6c
|
[
"MIT"
] | null | null | null |
/*
author: Susmoy Sen Gupta
email: susmoy.cse@gmail.com
github: github.com/SusmoySenGupta
Judge: Codeforces
problem no: 1618A
problem name: Polycarp and Sums of Subsequences
problem link: https://codeforces.com/problemset/problem/1618/A
Status: ____
Solved at: __
*/
#include <iostream>
#include <vector>
using namespace std;
#define INF (int)1e9
#define EPS 1e-9
#define MOD 1000000007ll
#define PI 3.14159
#define MAX 1003
#define ll long long int
void solve()
{
vector<int> numbers(7);
for (int i = 0; i < 7; i++)
cin >> numbers[i];
cout << numbers[0] << " " << numbers[1] << " " << numbers[6] - numbers[1] - numbers[0] << "\n";
}
int main()
{
int t;
cin >> t;
while (t--)
solve();
return 0;
}
| 16.142857
| 100
| 0.60177
|
SusmoySenGupta
|
c7fbd92e7d4db60613a9ef434077b074ab2335ca
| 37,463
|
hpp
|
C++
|
include/tao/algorithm/adjacent_swap.hpp
|
tao-cpp/algorithm
|
156655aed1c522a3386cb82fb4aa2b3a302ee7e8
|
[
"MIT"
] | 2
|
2017-01-13T09:20:58.000Z
|
2019-06-28T15:27:13.000Z
|
include/tao/algorithm/adjacent_swap.hpp
|
tao-cpp/algorithm
|
156655aed1c522a3386cb82fb4aa2b3a302ee7e8
|
[
"MIT"
] | null | null | null |
include/tao/algorithm/adjacent_swap.hpp
|
tao-cpp/algorithm
|
156655aed1c522a3386cb82fb4aa2b3a302ee7e8
|
[
"MIT"
] | 2
|
2017-05-31T12:05:26.000Z
|
2019-10-13T22:36:32.000Z
|
//! \file tao/algorithm/adjacent_swap.hpp
// Tao.Algorithm
//
// Copyright (c) 2016-2021 Fernando Pelliccioni.
//
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef TAO_ALGORITHM_ADJACENT_SWAP_HPP_
#define TAO_ALGORITHM_ADJACENT_SWAP_HPP_
//Position Based Rearrangements
#include <algorithm>
#include <iterator>
#include <utility>
// #include <iostream>
#include <tao/algorithm/concepts.hpp>
#include <tao/algorithm/copy.hpp>
#include <tao/algorithm/iterator.hpp>
#include <tao/algorithm/swap.hpp>
#include <tao/algorithm/type_attributes.hpp>
namespace tao { namespace algorithm {
template <ForwardIterator I>
I adjacent_swap(I f, I l, std::forward_iterator_tag) {
//precondition: mutable_bounded_range(f, l)
while (f != l) {
I n = f; ++n;
if (n == l) return f;
std::iter_swap(f, n);
++n;
f = n;
}
return f;
}
//Complexity:
// Runtime:
// Amortized: O(n)
// Exact:
// Space:
// O(1)
template <RandomAccessIterator I>
I adjacent_swap(I f, I l, std::random_access_iterator_tag) {
//precondition: mutable_bounded_range(f, l)
auto n = l - f;
while (n > 1) {
std::iter_swap(f, f + 1);
f += 2;
n -= 2;
}
return f;
}
template <ForwardIterator I>
inline
I adjacent_swap(I f, I l) {
//precondition: mutable_bounded_range(f, l)
return adjacent_swap(f, l, IteratorCategory<I>{});
}
// -----------------------------------------------------------------
// adjacent_swap_0
// -----------------------------------------------------------------
//Complexity:
// Runtime:
// Amortized: O(n)
// Exact:
// Space:
// O(1)
// template <ForwardIterator I>
// void adjacent_swap_0(I f, I l, std::forward_iterator_tag) {
// //precondition: mutable_bounded_range(f, l)
// using std::swap;
// while (f != l) {
// I n = f; ++n;
// if (n == l) return;
// swap(*f, *n);
// ++n;
// f = n;
// }
// }
}} /*tao::algorithm*/
#endif /* TAO_ALGORITHM_ADJACENT_SWAP_HPP_ */
#ifdef DOCTEST_LIBRARY_INCLUDED
#include <iterator>
#include <forward_list>
#include <list>
#include <vector>
#include <tao/benchmark/instrumented.hpp>
using namespace std;
using namespace tao::algorithm;
TEST_CASE("[adjacent_swap] testing adjacent_swap 0 elements random access") {
using T = int;
vector<T> a;
auto ret = adjacent_swap(begin(a), end(a));
CHECK(a == vector<T>());
CHECK(ret == end(a));
}
TEST_CASE("[adjacent_swap] testing adjacent_swap 1 elements random access") {
using T = int;
vector<T> a = {1};
auto ret = adjacent_swap(begin(a), end(a));
CHECK(a == vector<T>{1});
CHECK(ret == begin(a));
CHECK(*ret == 1);
}
TEST_CASE("[adjacent_swap] testing adjacent_swap 2 elements random access") {
using T = int;
vector<T> a = {1, 2};
auto ret = adjacent_swap(begin(a), end(a));
CHECK(a == vector<T>{2, 1});
CHECK(ret == end(a));
}
TEST_CASE("[adjacent_swap] testing adjacent_swap 3 elements random access") {
using T = int;
vector<T> a = {1, 2, 3};
auto ret = adjacent_swap(begin(a), end(a));
CHECK(a == vector<T>{2, 1, 3});
CHECK(ret == prev(end(a)));
CHECK(*ret == 3);
}
TEST_CASE("[adjacent_swap] testing adjacent_swap 4 elements random access") {
using T = int;
vector<T> a = {1, 2, 3, 4};
auto ret = adjacent_swap(begin(a), end(a));
CHECK(a == vector<T>{2, 1, 4, 3});
CHECK(ret == end(a));
}
TEST_CASE("[adjacent_swap] testing adjacent_swap 5 elements random access") {
using T = int;
vector<T> a = {1, 2, 3, 4, 5};
auto ret = adjacent_swap(begin(a), end(a));
CHECK(a == vector<T>{2, 1, 4, 3, 5});
CHECK(ret == prev(end(a)));
CHECK(*ret == 5);
}
TEST_CASE("[adjacent_swap] testing adjacent_swap 0 elements bidirectional") {
using T = int;
list<T> a;
auto ret = adjacent_swap(begin(a), end(a));
CHECK(a == list<T>());
CHECK(ret == end(a));
}
TEST_CASE("[adjacent_swap] testing adjacent_swap 1 elements bidirectional") {
using T = int;
list<T> a = {1};
auto ret = adjacent_swap(begin(a), end(a));
CHECK(a == list<T>{1});
CHECK(ret == begin(a));
CHECK(*ret == 1);
}
TEST_CASE("[adjacent_swap] testing adjacent_swap 2 elements bidirectional") {
using T = int;
list<T> a = {1, 2};
auto ret = adjacent_swap(begin(a), end(a));
CHECK(a == list<T>{2, 1});
CHECK(ret == end(a));
}
TEST_CASE("[adjacent_swap] testing adjacent_swap 3 elements bidirectional") {
using T = int;
list<T> a = {1, 2, 3};
auto ret = adjacent_swap(begin(a), end(a));
CHECK(a == list<T>{2, 1, 3});
CHECK(ret == prev(end(a)));
CHECK(*ret == 3);
}
TEST_CASE("[adjacent_swap] testing adjacent_swap 4 elements bidirectional") {
using T = int;
list<T> a = {1, 2, 3, 4};
auto ret = adjacent_swap(begin(a), end(a));
CHECK(a == list<T>{2, 1, 4, 3});
CHECK(ret == end(a));
}
TEST_CASE("[adjacent_swap] testing adjacent_swap 5 elements bidirectional") {
using T = int;
list<T> a = {1, 2, 3, 4, 5};
auto ret = adjacent_swap(begin(a), end(a));
CHECK(a == list<T>{2, 1, 4, 3, 5});
CHECK(ret == prev(end(a)));
CHECK(*ret == 5);
}
TEST_CASE("[adjacent_swap] testing adjacent_swap 0 elements forward") {
using T = int;
forward_list<T> a;
auto ret = adjacent_swap(begin(a), end(a));
CHECK(a == forward_list<T>());
CHECK(ret == end(a));
}
TEST_CASE("[adjacent_swap] testing adjacent_swap 1 elements forward") {
using T = int;
forward_list<T> a = {1};
auto ret = adjacent_swap(begin(a), end(a));
CHECK(a == forward_list<T>{1});
CHECK(ret == begin(a));
CHECK(*ret == 1);
}
TEST_CASE("[adjacent_swap] testing adjacent_swap 2 elements forward") {
using T = int;
forward_list<T> a = {1, 2};
auto ret = adjacent_swap(begin(a), end(a));
CHECK(a == forward_list<T>{2, 1});
CHECK(ret == end(a));
}
TEST_CASE("[adjacent_swap] testing adjacent_swap 3 elements forward") {
using T = int;
forward_list<T> a = {1, 2, 3};
auto ret = adjacent_swap(begin(a), end(a));
CHECK(a == forward_list<T>{2, 1, 3});
CHECK(ret == next(begin(a), 3 - 1));
CHECK(*ret == 3);
}
TEST_CASE("[adjacent_swap] testing adjacent_swap 4 elements forward") {
using T = int;
forward_list<T> a = {1, 2, 3, 4};
auto ret = adjacent_swap(begin(a), end(a));
CHECK(a == forward_list<T>{2, 1, 4, 3});
CHECK(ret == end(a));
}
TEST_CASE("[adjacent_swap] testing adjacent_swap 5 elements forward") {
using T = int;
forward_list<T> a = {1, 2, 3, 4, 5};
auto ret = adjacent_swap(begin(a), end(a));
CHECK(a == forward_list<T>{2, 1, 4, 3, 5});
CHECK(ret == next(begin(a), 5 - 1));
CHECK(*ret == 5);
}
// // ---------------------------------------------------------------------------------------------------
// // TEST_CASE("[adjacent_swap] testing adjacent_swap 6 elements random access compare with std::adjacent_swap") {
// // using T = int;
// // vector<T> a = {1, 2, 3, 4, 5, 6};
// // std::auto ret = adjacent_swap(begin(a), end(a) - 1, end(a));
// // CHECK(a == vector<T>{6, 1, 2, 3, 4, 5});
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap instrumented random access compare with std::adjacent_swap") {
// // using T = instrumented<int>;
// // vector<T> a = {1, 2, 3, 4, 5, 6};
// // instrumented<int>::initialize(0);
// // std::auto ret = adjacent_swap(begin(a), std::prev(end(a), 1), end(a));
// // double* count_p = instrumented<int>::counts;
// // CHECK(count_p[instrumented_base::copy_ctor] +
// // count_p[instrumented_base::copy_assignment] +
// // count_p[instrumented_base::move_ctor] +
// // count_p[instrumented_base::move_assignment] == a.size() - 1);
// // CHECK(count_p[instrumented_base::destructor] == 0);
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap instrumented bidirectional compare with std::adjacent_swap") {
// // using T = instrumented<int>;
// // list<T> a = {1, 2, 3, 4, 5, 6};
// // instrumented<int>::initialize(0);
// // std::auto ret = adjacent_swap(begin(a), std::prev(end(a), 1), end(a));
// // double* count_p = instrumented<int>::counts;
// // CHECK(count_p[instrumented_base::copy_ctor] +
// // count_p[instrumented_base::copy_assignment] +
// // count_p[instrumented_base::move_ctor] +
// // count_p[instrumented_base::move_assignment] == a.size() - 1);
// // CHECK(count_p[instrumented_base::destructor] == 0);
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap instrumented forward compare with std::adjacent_swap") {
// // using T = instrumented<int>;
// // forward_list<T> a = {1, 2, 3, 4, 5, 6};
// // auto n = distance(begin(a), end(a));
// // instrumented<int>::initialize(0);
// // std::auto ret = adjacent_swap(begin(a), std::next(begin(a), n - 1), end(a));
// // double* count_p = instrumented<int>::counts;
// // CHECK(count_p[instrumented_base::copy_ctor] +
// // count_p[instrumented_base::copy_assignment] +
// // count_p[instrumented_base::move_ctor] +
// // count_p[instrumented_base::move_assignment] == 2 * n - 1);
// // CHECK(count_p[instrumented_base::destructor] == 0);
// // }
// // ---------------------------------------------------------------------------------------------------
// TEST_CASE("[adjacent_swap] testing adjacent_swap instrumented random access") {
// using T = instrumented<int>;
// vector<T> a = {1, 2, 3, 4, 5, 6};
// instrumented<int>::initialize(0);
// auto ret = adjacent_swap(begin(a), end(a));
// double* count_p = instrumented<int>::counts;
// CHECK(count_p[instrumented_base::copy_ctor] +
// count_p[instrumented_base::copy_assignment] +
// count_p[instrumented_base::move_ctor] +
// count_p[instrumented_base::move_assignment] == a.size() + 1);
// CHECK(count_p[instrumented_base::destructor] == 1);
// }
// TEST_CASE("[adjacent_swap] testing adjacent_swap instrumented bidirectional") {
// using T = instrumented<int>;
// list<T> a = {1, 2, 3, 4, 5, 6};
// instrumented<int>::initialize(0);
// auto ret = adjacent_swap(begin(a), end(a));
// double* count_p = instrumented<int>::counts;
// CHECK(count_p[instrumented_base::copy_ctor] +
// count_p[instrumented_base::copy_assignment] +
// count_p[instrumented_base::move_ctor] +
// count_p[instrumented_base::move_assignment] == a.size() + 1);
// CHECK(count_p[instrumented_base::destructor] == 1);
// }
// TEST_CASE("[adjacent_swap] testing adjacent_swap instrumented forward") {
// using T = instrumented<int>;
// forward_list<T> a = {1, 2, 3, 4, 5, 6};
// auto n = distance(begin(a), end(a));
// instrumented<int>::initialize(0);
// auto ret = adjacent_swap(begin(a), end(a));
// double* count_p = instrumented<int>::counts;
// CHECK(count_p[instrumented_base::copy_ctor] +
// count_p[instrumented_base::copy_assignment] +
// count_p[instrumented_base::move_ctor] +
// count_p[instrumented_base::move_assignment] == 2 * n);
// CHECK(count_p[instrumented_base::destructor] == 2);
// }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_n 0 elements random access") {
// // using T = int;
// // vector<T> a;
// // adjacent_swap_n(begin(a), a.size());
// // CHECK(a == vector<T>());
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_n 1 elements random access") {
// // using T = int;
// // vector<T> a = {1};
// // adjacent_swap_n(begin(a), a.size());
// // CHECK(a == vector<T>{1});
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_n 2 elements random access") {
// // using T = int;
// // vector<T> a = {1, 2};
// // adjacent_swap_n(begin(a), a.size());
// // CHECK(a == vector<T>{2, 1});
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_n 3 elements random access") {
// // using T = int;
// // vector<T> a = {1, 2, 3};
// // adjacent_swap_n(begin(a), a.size());
// // CHECK(a == vector<T>{3, 1, 2});
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_n 4 elements random access") {
// // using T = int;
// // vector<T> a = {1, 2, 3, 4};
// // adjacent_swap_n(begin(a), a.size());
// // CHECK(a == vector<T>{4, 1, 2, 3});
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_n 5 elements random access") {
// // using T = int;
// // vector<T> a = {1, 2, 3, 4, 5};
// // adjacent_swap_n(begin(a), a.size());
// // CHECK(a == vector<T>{5, 1, 2, 3, 4});
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_n 6 elements random access") {
// // using T = int;
// // vector<T> a = {1, 2, 3, 4, 5, 6};
// // adjacent_swap_n(begin(a), a.size());
// // CHECK(a == vector<T>{6, 1, 2, 3, 4, 5});
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_n 0 elements bidirectional") {
// // using T = int;
// // list<T> a;
// // adjacent_swap_n(begin(a), a.size());
// // CHECK(a == list<T>());
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_n 1 elements bidirectional") {
// // using T = int;
// // list<T> a = {1};
// // adjacent_swap_n(begin(a), a.size());
// // CHECK(a == list<T>{1});
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_n 2 elements bidirectional") {
// // using T = int;
// // list<T> a = {1, 2};
// // adjacent_swap_n(begin(a), a.size());
// // CHECK(a == list<T>{2, 1});
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_n 3 elements bidirectional") {
// // using T = int;
// // list<T> a = {1, 2, 3};
// // adjacent_swap_n(begin(a), a.size());
// // CHECK(a == list<T>{3, 1, 2});
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_n 4 elements bidirectional") {
// // using T = int;
// // list<T> a = {1, 2, 3, 4};
// // adjacent_swap_n(begin(a), a.size());
// // CHECK(a == list<T>{4, 1, 2, 3});
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_n 5 elements bidirectional") {
// // using T = int;
// // list<T> a = {1, 2, 3, 4, 5};
// // adjacent_swap_n(begin(a), a.size());
// // CHECK(a == list<T>{5, 1, 2, 3, 4});
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_n 6 elements bidirectional") {
// // using T = int;
// // list<T> a = {1, 2, 3, 4, 5, 6};
// // adjacent_swap_n(begin(a), a.size());
// // CHECK(a == list<T>{6, 1, 2, 3, 4, 5});
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_n 0 elements forward") {
// // using T = int;
// // forward_list<T> a;
// // auto n = distance(begin(a), end(a));
// // adjacent_swap_n(begin(a), n);
// // CHECK(a == forward_list<T>());
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_n 1 elements forward") {
// // using T = int;
// // forward_list<T> a = {1};
// // auto n = distance(begin(a), end(a));
// // adjacent_swap_n(begin(a), n);
// // CHECK(a == forward_list<T>{1});
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_n 2 elements forward") {
// // using T = int;
// // forward_list<T> a = {1, 2};
// // auto n = distance(begin(a), end(a));
// // adjacent_swap_n(begin(a), n);
// // CHECK(a == forward_list<T>{2, 1});
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_n 3 elements forward") {
// // using T = int;
// // forward_list<T> a = {1, 2, 3};
// // auto n = distance(begin(a), end(a));
// // adjacent_swap_n(begin(a), n);
// // CHECK(a == forward_list<T>{3, 1, 2});
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_n 4 elements forward") {
// // using T = int;
// // forward_list<T> a = {1, 2, 3, 4};
// // auto n = distance(begin(a), end(a));
// // adjacent_swap_n(begin(a), n);
// // CHECK(a == forward_list<T>{4, 1, 2, 3});
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_n 5 elements forward") {
// // using T = int;
// // forward_list<T> a = {1, 2, 3, 4, 5};
// // auto n = distance(begin(a), end(a));
// // adjacent_swap_n(begin(a), n);
// // CHECK(a == forward_list<T>{5, 1, 2, 3, 4});
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_n 6 elements forward") {
// // using T = int;
// // forward_list<T> a = {1, 2, 3, 4, 5, 6};
// // auto n = distance(begin(a), end(a));
// // adjacent_swap_n(begin(a), n);
// // CHECK(a == forward_list<T>{6, 1, 2, 3, 4, 5});
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_n instrumented random access") {
// // using T = instrumented<int>;
// // vector<T> a = {1, 2, 3, 4, 5, 6};
// // instrumented<int>::initialize(0);
// // adjacent_swap_n(begin(a), a.size());
// // double* count_p = instrumented<int>::counts;
// // CHECK(count_p[instrumented_base::copy_ctor] +
// // count_p[instrumented_base::copy_assignment] +
// // count_p[instrumented_base::move_ctor] +
// // count_p[instrumented_base::move_assignment] == a.size() + 1);
// // CHECK(count_p[instrumented_base::destructor] == 1);
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_n instrumented bidirectional") {
// // using T = instrumented<int>;
// // list<T> a = {1, 2, 3, 4, 5, 6};
// // instrumented<int>::initialize(0);
// // adjacent_swap_n(begin(a), a.size());
// // double* count_p = instrumented<int>::counts;
// // CHECK(count_p[instrumented_base::copy_ctor] +
// // count_p[instrumented_base::copy_assignment] +
// // count_p[instrumented_base::move_ctor] +
// // count_p[instrumented_base::move_assignment] == a.size() + 1);
// // CHECK(count_p[instrumented_base::destructor] == 1);
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_n instrumented forward") {
// // using T = instrumented<int>;
// // forward_list<T> a = {1, 2, 3, 4, 5, 6};
// // auto n = distance(begin(a), end(a));
// // instrumented<int>::initialize(0);
// // adjacent_swap_n(begin(a), n);
// // double* count_p = instrumented<int>::counts;
// // CHECK(count_p[instrumented_base::copy_ctor] +
// // count_p[instrumented_base::copy_assignment] +
// // count_p[instrumented_base::move_ctor] +
// // count_p[instrumented_base::move_assignment] == 2 * n);
// // CHECK(count_p[instrumented_base::destructor] == 2);
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one 0 elements random access") {
// // using T = int;
// // vector<T> a;
// // auto ret = adjacent_swap_left_by_one(begin(a), end(a));
// // CHECK(a == vector<T>());
// // CHECK(ret == end(a));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one 1 elements random access") {
// // using T = int;
// // vector<T> a = {1};
// // auto ret = adjacent_swap_left_by_one(begin(a), end(a));
// // CHECK(a == vector<T>{1});
// // CHECK(ret == std::next(begin(a), a.size() - 1));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one 2 elements random access") {
// // using T = int;
// // vector<T> a = {1, 2};
// // auto ret = adjacent_swap_left_by_one(begin(a), end(a));
// // CHECK(a == vector<T>{2, 2});
// // CHECK(ret == std::next(begin(a), a.size() - 1));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one 3 elements random access") {
// // using T = int;
// // vector<T> a = {1, 2, 3};
// // auto ret = adjacent_swap_left_by_one(begin(a), end(a));
// // CHECK(a == vector<T>{2, 3, 3});
// // CHECK(ret == std::next(begin(a), a.size() - 1));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one 4 elements random access") {
// // using T = int;
// // vector<T> a = {1, 2, 3, 4};
// // auto ret = adjacent_swap_left_by_one(begin(a), end(a));
// // CHECK(a == vector<T>{2, 3, 4, 4});
// // CHECK(ret == std::next(begin(a), a.size() - 1));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one 5 elements random access") {
// // using T = int;
// // vector<T> a = {1, 2, 3, 4, 5};
// // auto ret = adjacent_swap_left_by_one(begin(a), end(a));
// // CHECK(a == vector<T>{2, 3, 4, 5, 5});
// // CHECK(ret == std::next(begin(a), a.size() - 1));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one 6 elements random access") {
// // using T = int;
// // vector<T> a = {1, 2, 3, 4, 5, 6};
// // auto ret = adjacent_swap_left_by_one(begin(a), end(a));
// // CHECK(a == vector<T>{2, 3, 4, 5, 6, 6});
// // CHECK(ret == std::next(begin(a), a.size() - 1));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one 0 elements bidirectional") {
// // using T = int;
// // list<T> a;
// // auto ret = adjacent_swap_left_by_one(begin(a), end(a));
// // CHECK(a == list<T>());
// // CHECK(ret == end(a));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one 1 elements bidirectional") {
// // using T = int;
// // list<T> a = {1};
// // auto ret = adjacent_swap_left_by_one(begin(a), end(a));
// // CHECK(a == list<T>{1});
// // CHECK(ret == std::next(begin(a), a.size() - 1));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one 2 elements bidirectional") {
// // using T = int;
// // list<T> a = {1, 2};
// // auto ret = adjacent_swap_left_by_one(begin(a), end(a));
// // CHECK(a == list<T>{2, 2});
// // CHECK(ret == std::next(begin(a), a.size() - 1));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one 3 elements bidirectional") {
// // using T = int;
// // list<T> a = {1, 2, 3};
// // auto ret = adjacent_swap_left_by_one(begin(a), end(a));
// // CHECK(a == list<T>{2, 3, 3});
// // CHECK(ret == std::next(begin(a), a.size() - 1));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one 4 elements bidirectional") {
// // using T = int;
// // list<T> a = {1, 2, 3, 4};
// // auto ret = adjacent_swap_left_by_one(begin(a), end(a));
// // CHECK(a == list<T>{2, 3, 4, 4});
// // CHECK(ret == std::next(begin(a), a.size() - 1));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one 5 elements bidirectional") {
// // using T = int;
// // list<T> a = {1, 2, 3, 4, 5};
// // auto ret = adjacent_swap_left_by_one(begin(a), end(a));
// // CHECK(a == list<T>{2, 3, 4, 5, 5});
// // CHECK(ret == std::next(begin(a), a.size() - 1));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one 6 elements bidirectional") {
// // using T = int;
// // list<T> a = {1, 2, 3, 4, 5, 6};
// // auto ret = adjacent_swap_left_by_one(begin(a), end(a));
// // CHECK(a == list<T>{2, 3, 4, 5, 6, 6});
// // CHECK(ret == std::next(begin(a), a.size() - 1));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one 0 elements forward") {
// // using T = int;
// // forward_list<T> a;
// // auto n = distance(begin(a), end(a));
// // auto ret = adjacent_swap_left_by_one(begin(a), end(a));
// // CHECK(a == forward_list<T>());
// // CHECK(ret == end(a));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one 1 elements forward") {
// // using T = int;
// // forward_list<T> a = {1};
// // auto n = distance(begin(a), end(a));
// // auto ret = adjacent_swap_left_by_one(begin(a), end(a));
// // CHECK(a == forward_list<T>{1});
// // CHECK(ret == std::next(begin(a), n - 1));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one 2 elements forward") {
// // using T = int;
// // forward_list<T> a = {1, 2};
// // auto n = distance(begin(a), end(a));
// // auto ret = adjacent_swap_left_by_one(begin(a), end(a));
// // CHECK(a == forward_list<T>{2, 2});
// // CHECK(ret == std::next(begin(a), n - 1));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one 3 elements forward") {
// // using T = int;
// // forward_list<T> a = {1, 2, 3};
// // auto n = distance(begin(a), end(a));
// // auto ret = adjacent_swap_left_by_one(begin(a), end(a));
// // CHECK(a == forward_list<T>{2, 3, 3});
// // CHECK(ret == std::next(begin(a), n - 1));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one 4 elements forward") {
// // using T = int;
// // forward_list<T> a = {1, 2, 3, 4};
// // auto n = distance(begin(a), end(a));
// // auto ret = adjacent_swap_left_by_one(begin(a), end(a));
// // CHECK(a == forward_list<T>{2, 3, 4, 4});
// // CHECK(ret == std::next(begin(a), n - 1));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one 5 elements forward") {
// // using T = int;
// // forward_list<T> a = {1, 2, 3, 4, 5};
// // auto n = distance(begin(a), end(a));
// // auto ret = adjacent_swap_left_by_one(begin(a), end(a));
// // CHECK(a == forward_list<T>{2, 3, 4, 5, 5});
// // CHECK(ret == std::next(begin(a), n - 1));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one 6 elements forward") {
// // using T = int;
// // forward_list<T> a = {1, 2, 3, 4, 5, 6};
// // auto n = distance(begin(a), end(a));
// // auto ret = adjacent_swap_left_by_one(begin(a), end(a));
// // CHECK(a == forward_list<T>{2, 3, 4, 5, 6, 6});
// // CHECK(ret == std::next(begin(a), n - 1));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one instrumented random access") {
// // using T = instrumented<int>;
// // vector<T> a = {1, 2, 3, 4, 5, 6};
// // instrumented<int>::initialize(0);
// // auto ret = adjacent_swap_left_by_one(begin(a), end(a));
// // double* count_p = instrumented<int>::counts;
// // CHECK(count_p[instrumented_base::copy_ctor] +
// // count_p[instrumented_base::copy_assignment] +
// // count_p[instrumented_base::move_ctor] +
// // count_p[instrumented_base::move_assignment] == a.size() - 1);
// // CHECK(count_p[instrumented_base::destructor] == 0);
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one instrumented bidirectional") {
// // using T = instrumented<int>;
// // list<T> a = {1, 2, 3, 4, 5, 6};
// // instrumented<int>::initialize(0);
// // auto ret = adjacent_swap_left_by_one(begin(a), end(a));
// // double* count_p = instrumented<int>::counts;
// // CHECK(count_p[instrumented_base::copy_ctor] +
// // count_p[instrumented_base::copy_assignment] +
// // count_p[instrumented_base::move_ctor] +
// // count_p[instrumented_base::move_assignment] == a.size() - 1);
// // CHECK(count_p[instrumented_base::destructor] == 0);
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one instrumented forward") {
// // using T = instrumented<int>;
// // forward_list<T> a = {1, 2, 3, 4, 5, 6};
// // auto n = distance(begin(a), end(a));
// // instrumented<int>::initialize(0);
// // auto ret = adjacent_swap_left_by_one(begin(a), end(a));
// // double* count_p = instrumented<int>::counts;
// // CHECK(count_p[instrumented_base::copy_ctor] +
// // count_p[instrumented_base::copy_assignment] +
// // count_p[instrumented_base::move_ctor] +
// // count_p[instrumented_base::move_assignment] == n - 1);
// // CHECK(count_p[instrumented_base::destructor] == 0);
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one_n 0 elements random access") {
// // using T = int;
// // vector<T> a;
// // auto ret = adjacent_swap_left_by_one_n(begin(a), a.size());
// // CHECK(a == vector<T>());
// // CHECK(ret == end(a));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one_n 1 elements random access") {
// // using T = int;
// // vector<T> a = {1};
// // auto ret = adjacent_swap_left_by_one_n(begin(a), a.size());
// // CHECK(a == vector<T>{1});
// // CHECK(ret == std::next(begin(a), a.size() - 1));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one_n 2 elements random access") {
// // using T = int;
// // vector<T> a = {1, 2};
// // auto ret = adjacent_swap_left_by_one_n(begin(a), a.size());
// // CHECK(a == vector<T>{2, 2});
// // CHECK(ret == std::next(begin(a), a.size() - 1));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one_n 3 elements random access") {
// // using T = int;
// // vector<T> a = {1, 2, 3};
// // auto ret = adjacent_swap_left_by_one_n(begin(a), a.size());
// // CHECK(a == vector<T>{2, 3, 3});
// // CHECK(ret == std::next(begin(a), a.size() - 1));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one_n 4 elements random access") {
// // using T = int;
// // vector<T> a = {1, 2, 3, 4};
// // auto ret = adjacent_swap_left_by_one_n(begin(a), a.size());
// // CHECK(a == vector<T>{2, 3, 4, 4});
// // CHECK(ret == std::next(begin(a), a.size() - 1));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one_n 5 elements random access") {
// // using T = int;
// // vector<T> a = {1, 2, 3, 4, 5};
// // auto ret = adjacent_swap_left_by_one_n(begin(a), a.size());
// // CHECK(a == vector<T>{2, 3, 4, 5, 5});
// // CHECK(ret == std::next(begin(a), a.size() - 1));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one_n 6 elements random access") {
// // using T = int;
// // vector<T> a = {1, 2, 3, 4, 5, 6};
// // auto ret = adjacent_swap_left_by_one_n(begin(a), a.size());
// // CHECK(a == vector<T>{2, 3, 4, 5, 6, 6});
// // CHECK(ret == std::next(begin(a), a.size() - 1));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one_n 0 elements bidirectional") {
// // using T = int;
// // list<T> a;
// // auto ret = adjacent_swap_left_by_one_n(begin(a), a.size());
// // CHECK(a == list<T>());
// // CHECK(ret == end(a));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one_n 1 elements bidirectional") {
// // using T = int;
// // list<T> a = {1};
// // auto ret = adjacent_swap_left_by_one_n(begin(a), a.size());
// // CHECK(a == list<T>{1});
// // CHECK(ret == std::next(begin(a), a.size() - 1));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one_n 2 elements bidirectional") {
// // using T = int;
// // list<T> a = {1, 2};
// // auto ret = adjacent_swap_left_by_one_n(begin(a), a.size());
// // CHECK(a == list<T>{2, 2});
// // CHECK(ret == std::next(begin(a), a.size() - 1));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one_n 3 elements bidirectional") {
// // using T = int;
// // list<T> a = {1, 2, 3};
// // auto ret = adjacent_swap_left_by_one_n(begin(a), a.size());
// // CHECK(a == list<T>{2, 3, 3});
// // CHECK(ret == std::next(begin(a), a.size() - 1));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one_n 4 elements bidirectional") {
// // using T = int;
// // list<T> a = {1, 2, 3, 4};
// // auto ret = adjacent_swap_left_by_one_n(begin(a), a.size());
// // CHECK(a == list<T>{2, 3, 4, 4});
// // CHECK(ret == std::next(begin(a), a.size() - 1));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one_n 5 elements bidirectional") {
// // using T = int;
// // list<T> a = {1, 2, 3, 4, 5};
// // auto ret = adjacent_swap_left_by_one_n(begin(a), a.size());
// // CHECK(a == list<T>{2, 3, 4, 5, 5});
// // CHECK(ret == std::next(begin(a), a.size() - 1));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one_n 6 elements bidirectional") {
// // using T = int;
// // list<T> a = {1, 2, 3, 4, 5, 6};
// // auto ret = adjacent_swap_left_by_one_n(begin(a), a.size());
// // CHECK(a == list<T>{2, 3, 4, 5, 6, 6});
// // CHECK(ret == std::next(begin(a), a.size() - 1));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one_n 0 elements forward") {
// // using T = int;
// // forward_list<T> a;
// // auto n = distance(begin(a), end(a));
// // auto ret = adjacent_swap_left_by_one_n(begin(a), n);
// // CHECK(a == forward_list<T>());
// // CHECK(ret == end(a));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one_n 1 elements forward") {
// // using T = int;
// // forward_list<T> a = {1};
// // auto n = distance(begin(a), end(a));
// // auto ret = adjacent_swap_left_by_one_n(begin(a), n);
// // CHECK(a == forward_list<T>{1});
// // CHECK(ret == std::next(begin(a), n - 1));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one_n 2 elements forward") {
// // using T = int;
// // forward_list<T> a = {1, 2};
// // auto n = distance(begin(a), end(a));
// // auto ret = adjacent_swap_left_by_one_n(begin(a), n);
// // CHECK(a == forward_list<T>{2, 2});
// // CHECK(ret == std::next(begin(a), n - 1));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one_n 3 elements forward") {
// // using T = int;
// // forward_list<T> a = {1, 2, 3};
// // auto n = distance(begin(a), end(a));
// // auto ret = adjacent_swap_left_by_one_n(begin(a), n);
// // CHECK(a == forward_list<T>{2, 3, 3});
// // CHECK(ret == std::next(begin(a), n - 1));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one_n 4 elements forward") {
// // using T = int;
// // forward_list<T> a = {1, 2, 3, 4};
// // auto n = distance(begin(a), end(a));
// // auto ret = adjacent_swap_left_by_one_n(begin(a), n);
// // CHECK(a == forward_list<T>{2, 3, 4, 4});
// // CHECK(ret == std::next(begin(a), n - 1));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one_n 5 elements forward") {
// // using T = int;
// // forward_list<T> a = {1, 2, 3, 4, 5};
// // auto n = distance(begin(a), end(a));
// // auto ret = adjacent_swap_left_by_one_n(begin(a), n);
// // CHECK(a == forward_list<T>{2, 3, 4, 5, 5});
// // CHECK(ret == std::next(begin(a), n - 1));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one_n 6 elements forward") {
// // using T = int;
// // forward_list<T> a = {1, 2, 3, 4, 5, 6};
// // auto n = distance(begin(a), end(a));
// // auto ret = adjacent_swap_left_by_one_n(begin(a), n);
// // CHECK(a == forward_list<T>{2, 3, 4, 5, 6, 6});
// // CHECK(ret == std::next(begin(a), n - 1));
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one_n instrumented random access") {
// // using T = instrumented<int>;
// // vector<T> a = {1, 2, 3, 4, 5, 6};
// // instrumented<int>::initialize(0);
// // auto ret = adjacent_swap_left_by_one_n(begin(a), a.size());
// // double* count_p = instrumented<int>::counts;
// // CHECK(count_p[instrumented_base::copy_ctor] +
// // count_p[instrumented_base::copy_assignment] +
// // count_p[instrumented_base::move_ctor] +
// // count_p[instrumented_base::move_assignment] == a.size() - 1);
// // CHECK(count_p[instrumented_base::destructor] == 0);
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one_n instrumented bidirectional") {
// // using T = instrumented<int>;
// // list<T> a = {1, 2, 3, 4, 5, 6};
// // instrumented<int>::initialize(0);
// // auto ret = adjacent_swap_left_by_one_n(begin(a), a.size());
// // double* count_p = instrumented<int>::counts;
// // CHECK(count_p[instrumented_base::copy_ctor] +
// // count_p[instrumented_base::copy_assignment] +
// // count_p[instrumented_base::move_ctor] +
// // count_p[instrumented_base::move_assignment] == a.size() - 1);
// // CHECK(count_p[instrumented_base::destructor] == 0);
// // }
// // TEST_CASE("[adjacent_swap] testing adjacent_swap_left_by_one_n instrumented forward") {
// // using T = instrumented<int>;
// // forward_list<T> a = {1, 2, 3, 4, 5, 6};
// // auto n = distance(begin(a), end(a));
// // instrumented<int>::initialize(0);
// // auto ret = adjacent_swap_left_by_one_n(begin(a), n);
// // double* count_p = instrumented<int>::counts;
// // CHECK(count_p[instrumented_base::copy_ctor] +
// // count_p[instrumented_base::copy_assignment] +
// // count_p[instrumented_base::move_ctor] +
// // count_p[instrumented_base::move_assignment] == n - 1);
// // CHECK(count_p[instrumented_base::destructor] == 0);
// // }
#endif /*DOCTEST_LIBRARY_INCLUDED*/
| 36.90936
| 117
| 0.564077
|
tao-cpp
|
c7fde809d3cae6496f625738bb68bf5e73b9de03
| 4,318
|
hpp
|
C++
|
src/game_api/savedata.hpp
|
estebanfer/overlunky
|
ffc41e7cc9bb6345942ed346f1a65a966fd0f39d
|
[
"MIT"
] | null | null | null |
src/game_api/savedata.hpp
|
estebanfer/overlunky
|
ffc41e7cc9bb6345942ed346f1a65a966fd0f39d
|
[
"MIT"
] | null | null | null |
src/game_api/savedata.hpp
|
estebanfer/overlunky
|
ffc41e7cc9bb6345942ed346f1a65a966fd0f39d
|
[
"MIT"
] | 1
|
2020-11-15T05:43:12.000Z
|
2020-11-15T05:43:12.000Z
|
#pragma once
#include <array>
#include <cstdint>
#include "state_structs.hpp"
#pragma pack(push, 1)
struct SaveGameArenaRuleset
{
uint8_t unknown1;
uint8_t unknown12;
uint8_t timer;
uint8_t timer_ending;
uint8_t wins;
uint8_t lives;
uint8_t unknown7;
uint8_t unknown8;
std::array<uint16_t, 4> unused_player_idolheld_countdown; // struct is similar to state.arenas so they just copied it, but this is not useful to store in the savegame
uint8_t health;
uint8_t bombs;
uint8_t ropes;
uint8_t stun_time;
uint8_t mount;
uint8_t arena_select;
ArenaConfigArenas arenas;
uint8_t dark_level_chance;
uint8_t crate_frequency;
ArenaConfigItems items_enabled;
ArenaConfigItems items_in_crate;
int8_t held_item;
int8_t equipped_backitem;
ArenaConfigEquippedItems equipped_items;
uint8_t whip_damage;
bool final_ghost;
uint8_t breath_cooldown;
bool punish_ball;
uint8_t padding[2];
};
struct ConstellationStar
{
uint32_t type;
float x;
float y;
float size;
float red;
float green;
float blue;
float alpha;
float halo_red;
float halo_green;
float halo_blue;
float halo_alpha;
bool canis_ring;
bool fidelis_ring;
uint8_t padding[2];
uint32_t unknown14; // might have something to do with how they are laid out on the path, having/being offshoots etc
};
struct ConstellationLine
{
uint8_t from; // zero based star index into Constellation.stars
uint8_t to;
};
struct Constellation
{
uint32_t star_count;
std::array<ConstellationStar, 45> stars;
float scale;
uint8_t line_count;
std::array<ConstellationLine, 90> lines; // You'd only need 44 lines if you have 45 stars, but there is room for 91. Could be to draw two lines on top of each other to make it brighter.
uint8_t padding[3];
float line_red_intensity; // 0 = normal white, npc_kills 8 - 16 = 0.5 - 1.0 (pink to deep red for criminalis)
};
struct SaveData
{
std::array<bool, 16> places;
std::array<bool, 78> bestiary;
std::array<bool, 38> people;
std::array<bool, 54> items;
std::array<bool, 24> traps;
int8_t skip1[2];
int32_t time_tutorial;
char last_daily[8];
uint8_t show_longer_journal_popup_count; // the next n times the 'Journal entry added' popup is shown, it's shown for 300 frames instead of 180
int8_t skip2[3];
uint32_t characters;
int8_t tutorial_state;
uint8_t shortcuts;
int8_t skip3[2];
std::array<int32_t, 78> bestiary_killed;
std::array<int32_t, 78> bestiary_killed_by;
std::array<int32_t, 38> people_killed;
std::array<int32_t, 38> people_killed_by;
int32_t plays;
int32_t deaths;
int32_t wins_normal;
int32_t wins_hard;
int32_t wins_special;
int64_t score_total;
int32_t score_top;
uint8_t deepest_area;
uint8_t deepest_level;
int8_t skip4[1022]; // TODO
std::array<std::array<uint32_t, 255>, 8> deathcount_per_level; // 8 themes, 255 uint32_t's for each level
int64_t time_total;
int32_t time_best;
std::array<int32_t, 20> character_deaths;
std::array<uint8_t, 3> pets_rescued;
// 1-based theme id into this array (0 = invalid theme, 19 = unknown)
// bool is set during transition with a theme change, except for CO, basecamp, arena
// due to tiamat and hundun, bool for neobab/sunkencity is only set when finishing these as 7-98
std::array<bool, 20> completed_themes;
bool completed_normal;
bool completed_ironman;
bool completed_hard;
bool profile_seen;
bool seeded_unlocked;
uint8_t world_last;
uint8_t level_last;
uint8_t theme_last;
int8_t skip7;
uint32_t score_last;
uint32_t time_last;
std::array<int32_t, 20> stickers;
int8_t skip8[40]; // first dword is a mask(?) that determines horizontal spacing between stickers
std::array<float, 20> sticker_angles; // rotation angle for each sticker
int8_t skip9[40];
std::array<float, 20> sticker_vert_offsets; // vertical offset for each sticker
int8_t skip10[40];
std::array<uint8_t, 4> players;
SaveGameArenaRuleset arena_favorite_ruleset;
Constellation constellation;
};
#pragma pack(pop)
| 30.195804
| 189
| 0.695924
|
estebanfer
|
c7ff8d1ca5558b155a60f714ab2ab389ad30bd33
| 614
|
hpp
|
C++
|
include/boost/sml/policies.hpp
|
GuiCodron/sml
|
2dab1265f87f70a2941af9de8f3f157df9a6a53f
|
[
"BSL-1.0"
] | 320
|
2020-07-03T18:58:34.000Z
|
2022-03-31T05:31:44.000Z
|
include/boost/sml/policies.hpp
|
GuiCodron/sml
|
2dab1265f87f70a2941af9de8f3f157df9a6a53f
|
[
"BSL-1.0"
] | 106
|
2020-06-30T15:03:00.000Z
|
2022-03-31T10:42:38.000Z
|
include/boost/sml/policies.hpp
|
GuiCodron/sml
|
2dab1265f87f70a2941af9de8f3f157df9a6a53f
|
[
"BSL-1.0"
] | 55
|
2020-07-10T12:32:49.000Z
|
2022-03-14T07:12:28.000Z
|
#include "boost/sml/back/policies.hpp"
#include "boost/sml/front/actions/defer.hpp"
template <class T>
struct thread_safe : aux::pair<back::thread_safety_policy__, thread_safe<T>> {
using type = T;
};
template <template <class...> class T>
struct defer_queue : aux::pair<back::defer_queue_policy__, defer_queue<T>> {
template <class U>
using rebind = T<U>;
template <class... Ts>
using defer = front::actions::defer_event<Ts...>;
};
template <class T>
struct logger : aux::pair<back::logger_policy__, logger<T>> {
using type = T;
};
struct testing : aux::pair<back::testing_policy__, testing> {};
| 25.583333
| 78
| 0.701954
|
GuiCodron
|
2a04f476927a2787f725f277f6e2177e7981b46d
| 772
|
hpp
|
C++
|
include/networking/Event.hpp
|
icebreakersentertainment/ice_engine
|
52a8313bc266c053366bdf554b5dc27a54ddcb25
|
[
"MIT"
] | null | null | null |
include/networking/Event.hpp
|
icebreakersentertainment/ice_engine
|
52a8313bc266c053366bdf554b5dc27a54ddcb25
|
[
"MIT"
] | null | null | null |
include/networking/Event.hpp
|
icebreakersentertainment/ice_engine
|
52a8313bc266c053366bdf554b5dc27a54ddcb25
|
[
"MIT"
] | 1
|
2019-06-11T03:41:48.000Z
|
2019-06-11T03:41:48.000Z
|
#ifndef NETWORK_EVENT_H_
#define NETWORK_EVENT_H_
#include <vector>
#include "Types.hpp"
#include "ClientHandle.hpp"
#include "ServerHandle.hpp"
#include "RemoteConnectionHandle.hpp"
namespace ice_engine
{
namespace networking
{
enum EventType
{
UNKNOWN = 0,
SERVERDISCONNECT,
CLIENTDISCONNECT,
SERVERCONNECT,
SERVERCONNECTFAILED,
CLIENTCONNECT,
SERVERMESSAGE,
CLIENTMESSAGE
};
struct GenericEvent
{
uint32 type;
uint32 timestamp;
ServerHandle serverHandle;
ClientHandle clientHandle;
RemoteConnectionHandle remoteConnectionHandle;
};
struct ConnectEvent : public GenericEvent
{
};
struct DisconnectEvent : public GenericEvent
{
};
struct MessageEvent : public GenericEvent
{
std::vector<uint8> message;
};
}
}
#endif /* NETWORK_EVENT_H_ */
| 13.310345
| 47
| 0.774611
|
icebreakersentertainment
|
2a05993080fc16187d08ec6cef2e7ff66e2d0ac3
| 4,031
|
cpp
|
C++
|
test/test_client.cpp
|
lichuan/fly
|
7927f819f74997314fb526c5d8ab4d88ea593b91
|
[
"Apache-2.0"
] | 60
|
2015-06-23T12:36:33.000Z
|
2022-03-09T01:27:14.000Z
|
test/test_client.cpp
|
lichuan/fly
|
7927f819f74997314fb526c5d8ab4d88ea593b91
|
[
"Apache-2.0"
] | 1
|
2021-12-21T11:23:04.000Z
|
2021-12-21T11:23:04.000Z
|
test/test_client.cpp
|
lichuan/fly
|
7927f819f74997314fb526c5d8ab4d88ea593b91
|
[
"Apache-2.0"
] | 30
|
2015-08-03T07:22:04.000Z
|
2022-01-13T08:49:48.000Z
|
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* _______ _ *
* ( ____ \ ( \ |\ /| *
* | ( \/ | ( ( \ / ) *
* | (__ | | \ (_) / *
* | __) | | \ / *
* | ( | | ) ( *
* | ) | (____/\ | | *
* |/ (_______/ \_/ *
* *
* *
* fly is an awesome c++11 network library. *
* *
* @author: lichuan *
* @qq: 308831759 *
* @email: 308831759@qq.com *
* @github: https://github.com/lichuan/fly *
* @date: 2015-06-10 13:34:21 *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#include <unistd.h>
#include "fly/init.hpp"
#include "fly/net/client.hpp"
#include "fly/base/logger.hpp"
using namespace std::placeholders;
using fly::net::Json;
class Test_Client : public fly::base::Singleton<Test_Client>
{
public:
bool init(std::shared_ptr<fly::net::Connection<Json>> connection)
{
rapidjson::Document doc;
doc.SetObject();
rapidjson::Document::AllocatorType &allocator = doc.GetAllocator();
doc.AddMember("msg_type", 9922, allocator);
doc.AddMember("msg_cmd", 2223333, allocator);
connection->send(doc);
return true;
}
void dispatch(std::unique_ptr<fly::net::Message<Json>> connection)
{
CONSOLE_LOG_INFO("disaptch message");
}
void close(std::shared_ptr<fly::net::Connection<Json>> connection)
{
CONSOLE_LOG_INFO("close connection from %s:%d", connection->peer_addr().m_host.c_str(), connection->peer_addr().m_port);
}
void be_closed(std::shared_ptr<fly::net::Connection<Json>> connection)
{
CONSOLE_LOG_INFO("connection from %s:%d be closed", connection->peer_addr().m_host.c_str(), connection->peer_addr().m_port);
}
void main()
{
//init library
fly::init();
//init logger
fly::base::Logger::instance()->init(fly::base::DEBUG, "client", "./log/");
std::shared_ptr<fly::net::Poller<Json>> poller(new fly::net::Poller<Json>(4));
poller->start();
int i = 1;
while(i-- > 0)
{
std::unique_ptr<fly::net::Client<Json>> client(new fly::net::Client<Json>(fly::net::Addr("127.0.0.1", 8088),
std::bind(&Test_Client::init, this, _1),
std::bind(&Test_Client::dispatch, this, _1),
std::bind(&Test_Client::close, this, _1),
std::bind(&Test_Client::be_closed, this, _1),
poller));
if(client->connect(1000))
{
CONSOLE_LOG_INFO("connect to server ok");
}
else
{
CONSOLE_LOG_INFO("connect to server failed");
}
}
poller->wait();
}
};
int main()
{
Test_Client::instance()->main();
}
| 41.556701
| 132
| 0.354999
|
lichuan
|
2a0e0b31f8896732621146f8c97e7bdbbad7ea87
| 5,637
|
hpp
|
C++
|
nvidia_flex/common/helpers.hpp
|
bluekyu/rpcpp_samples
|
dab4d21229e9793434d727b2ed8e4c5088c17218
|
[
"MIT"
] | 4
|
2018-09-15T20:30:38.000Z
|
2022-02-13T19:41:00.000Z
|
nvidia_flex/common/helpers.hpp
|
bluekyu/rpcpp_samples
|
dab4d21229e9793434d727b2ed8e4c5088c17218
|
[
"MIT"
] | 4
|
2017-09-05T15:18:40.000Z
|
2018-08-27T01:15:46.000Z
|
nvidia_flex/common/helpers.hpp
|
bluekyu/rpcpp_samples
|
dab4d21229e9793434d727b2ed8e4c5088c17218
|
[
"MIT"
] | null | null | null |
// This code contains NVIDIA Confidential Information and is disclosed to you
// under a form of NVIDIA software license agreement provided separately to you.
//
// Notice
// NVIDIA Corporation and its licensors retain all intellectual property and
// proprietary rights in and to this software and related documentation and
// any modifications thereto. Any use, reproduction, disclosure, or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA Corporation is strictly prohibited.
//
// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
//
// Information and code furnished is believed to be accurate and reliable.
// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
// information or for any infringement of patents or other rights of third parties that may
// result from its use. No license is granted by implication or otherwise under any patent
// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
// This code supersedes and replaces all information previously supplied.
// NVIDIA Corporation products are not authorized for use as critical
// components in life support devices or systems without express written approval of
// NVIDIA Corporation.
//
// Copyright (c) 2013-2017 NVIDIA Corporation. All rights reserved.
#pragma once
#include <rpflex/plugin.hpp>
#include <rpflex/flex_buffer.hpp>
#include "maths.hpp"
struct Emitter
{
Emitter() : mSpeed(0.0f), mEnabled(false), mLeftOver(0.0f), mWidth(8) {}
LVecBase3 mPos;
LVecBase3 mDir;
LVecBase3 mRight;
float mSpeed;
bool mEnabled;
float mLeftOver;
int mWidth;
};
void CreateParticleGrid(rpflex::FlexBuffer& buffer, const LVecBase3& lower, int dimx, int dimy, int dimz, float radius,
const LVecBase3& velocity, float invMass, bool rigid, float rigidStiffness, int phase, float jitter=0.005f)
{
if (rigid && buffer.rigid_indices.empty())
buffer.rigid_offsets.push_back(0);
for (int x = 0; x < dimx; ++x)
{
for (int y = 0; y < dimy; ++y)
{
for (int z=0; z < dimz; ++z)
{
if (rigid)
buffer.rigid_indices.push_back(int(buffer.positions.size()));
LVecBase3 position = lower + LVecBase3(float(x), float(y), float(z))*radius + RandomUnitVector()*jitter;
buffer.positions.push_back(LVecBase4(position, invMass));
buffer.velocities.push_back(velocity);
buffer.phases.push_back(phase);
}
}
}
if (rigid)
{
buffer.rigid_coefficients.push_back(rigidStiffness);
buffer.rigid_offsets.push_back(int(buffer.rigid_indices.size()));
}
}
void UpdateEmitters(rpflex::Plugin& rpflex_plugin, Emitter& emitter)
{
const auto& flex_params = rpflex_plugin.get_flex_params();
auto& buffer = rpflex_plugin.get_flex_buffer();
NodePath cam = rpcore::Globals::base->get_cam();
LVecBase3 spinned_cam = cam.get_hpr(rpcore::Globals::render) + LVecBase3(15, 0, 0);
LQuaternion rot;
rot.set_hpr(spinned_cam);
LMatrix4 mat;
rot.extract_to_matrix(mat);
const LVecBase3 forward((LVecBase4(0, 1, 0, 0) * mat).get_xyz());
const LVecBase3 right(forward.cross(LVecBase3(0.0f, 0.0f, 1.0f)).normalized());
emitter.mDir = (forward + LVecBase3(0.0, 0.0f, 0.4f)).normalized();
emitter.mRight = right;
emitter.mPos = cam.get_pos(rpcore::Globals::render) + forward*1.f + LVecBase3(0.0f, 0.0f, 0.2f) + right*0.65f;
// process emitters
int activeCount = NvFlexGetActiveCount(rpflex_plugin.get_flex_solver());
float r;
int phase;
if (flex_params.fluid)
{
r = flex_params.fluidRestDistance;
phase = NvFlexMakePhase(0, eNvFlexPhaseSelfCollide | eNvFlexPhaseFluid);
}
else
{
r = flex_params.solidRestDistance;
phase = NvFlexMakePhase(0, eNvFlexPhaseSelfCollide);
}
float numParticles = (emitter.mSpeed / r) * (1/60.0f);
// whole number to emit
int n = int(numParticles + emitter.mLeftOver);
if (n)
emitter.mLeftOver = (numParticles + emitter.mLeftOver) - n;
else
emitter.mLeftOver += numParticles;
// create a grid of particles (n particles thick)
for (int k = 0; k < n; ++k)
{
int emitterWidth = emitter.mWidth;
int numParticles = emitterWidth*emitterWidth;
for (int i = 0; i < numParticles; ++i)
{
float x = float(i%emitterWidth) - float(emitterWidth/2);
float y = float((i / emitterWidth) % emitterWidth) - float(emitterWidth/2);
if ((x*x + y*y) <= (emitterWidth / 2)*(emitterWidth / 2))
{
LVecBase3 up = emitter.mDir.cross(emitter.mRight).normalized();
LVecBase3 offset = r*(emitter.mRight*x + up*y) + float(k)*emitter.mDir*r;
if (activeCount < buffer.positions.size())
{
buffer.positions[activeCount] = LVecBase4f(emitter.mPos + offset, 1.0f);
buffer.velocities[activeCount] = emitter.mDir*emitter.mSpeed;
buffer.phases[activeCount] = phase;
buffer.active_indices.push_back(activeCount);
activeCount++;
}
}
}
}
}
| 35.904459
| 120
| 0.659038
|
bluekyu
|
2a0f6d0725d97dc1332a8ce9872eb32a43402f73
| 33,384
|
cpp
|
C++
|
lipton-tarjan.cpp
|
jeffythedragonslayer/lipton-tarjan
|
d6f43395ca9d5a459c61cd55ccac6ed6295bc1dd
|
[
"BSL-1.0"
] | 8
|
2017-05-20T11:20:39.000Z
|
2020-11-10T15:50:33.000Z
|
lipton-tarjan.cpp
|
jeffythedragonslayer/lipton-tarjan
|
d6f43395ca9d5a459c61cd55ccac6ed6295bc1dd
|
[
"BSL-1.0"
] | 14
|
2017-12-02T06:35:48.000Z
|
2020-04-12T19:58:56.000Z
|
lipton-tarjan.cpp
|
jeffythedragonslayer/lipton-tarjan
|
d6f43395ca9d5a459c61cd55ccac6ed6295bc1dd
|
[
"BSL-1.0"
] | 3
|
2017-04-19T16:37:32.000Z
|
2022-03-19T04:29:33.000Z
|
//=======================================================================
// Copyright 2015 - 2020 Jeff Linahan
//
// 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 "lipton-tarjan.h"
#include "theorem4.h"
#include "lemmas.h"
#include "strutil.h"
#include "BFSVert.h"
#include "BFSVisitorData.h"
#include "BFSVisitor.h"
#include "EmbedStruct.h"
#include "ScanVisitor.h"
#include "graphutil.h"
#include <boost/lexical_cast.hpp>
#include <boost/graph/graph_concepts.hpp>
#include <boost/graph/planar_canonical_ordering.hpp>
#include <boost/graph/is_straight_line_drawing.hpp>
#include <boost/graph/boyer_myrvold_planar_test.hpp>
#include <boost/graph/make_biconnected_planar.hpp>
#include <boost/graph/make_maximal_planar.hpp>
#include <boost/graph/connected_components.hpp>
#include <boost/graph/copy.hpp>
#include <boost/graph/breadth_first_search.hpp>
#include <boost/pending/indirect_cmp.hpp>
#include <boost/range/irange.hpp>
#include <boost/bimap.hpp>
#include <boost/config.hpp>
#include <iostream>
#include <algorithm>
#include <utility>
#include <csignal>
#include <iterator>
using namespace std;
using namespace boost;
// Step 10: construct_vertex_partition
// Time: O(n)
//
// Use the fundamental cycle found in Step 9 and the levels found in Step 4 (l1_and_k) to construct a satisfactory vertex partition as described in the proof of Lemma 3
// Extend this partition from the connected component chosen in Step 2 to the entire graph as described in the proof of Theorem 4.
Partition construct_vertex_partition(GraphCR g_orig, Graph& g_shrunk, vector<uint> const& L, uint l[3], BFSVisitorData const& vis_data_orig, BFSVisitorData const& vis_data_shrunken, vector<vertex_t> const& fundamental_cycle)
{
vertex_map idx;
associative_property_map<vertex_map> vertid_to_component(idx);
uint num_components = connected_components(g_orig, vertid_to_component);
//BOOST_ASSERT(1 == num_components);
uint n = num_vertices(g_orig);
uint n_biggest_comp = vis_data_orig.verts.size(); // if num_components > 1 then num_vertices(g_orig) will not be what we want
//cout << "n_biggest: " << n_biggest_comp << '\n';
cout << "\n------------ 10 - Construct Vertex Partition --------------\n";
cout << "g_orig:\n";
print_graph(g_orig);
cout << "l0: " << l[0] << '\n';
cout << "l1: " << l[1] << '\n';
cout << "l2: " << l[2] << '\n';
uint r = vis_data_orig.num_levels;
cout << "r max distance: " << r << '\n';
Partition biggest_comp_p = lemma3(g_orig, L, l[1], l[2], r, vis_data_orig, vis_data_shrunken, fundamental_cycle, &g_shrunk);
biggest_comp_p.verify_edges(g_orig);
biggest_comp_p.verify_sizes_lemma3(L, l[1], l[2]);
if( 1 == num_components ){
if( biggest_comp_p.verify_sizes(g_orig) && biggest_comp_p.verify_edges(g_orig) ) return biggest_comp_p;
return theorem4_connected(g_orig, L, l, r, &g_shrunk, &vis_data_shrunken);
}
//associative_property_map<vertex_map> const& vertid_to_component, vector<uint> const& num_verts_per_component)
vector<uint> num_verts_per_component(num_components, 0);
VertIter vit, vjt;
for( tie(vit, vjt) = vertices(g_orig); vit != vjt; ++vit ){
++num_verts_per_component[vertid_to_component[*vit]];
}
// somehow the two Partitions need to be stiched together
cout << "biggest comp p:\n";
biggest_comp_p.print(&g_orig);
Partition extended_p = theorem4_disconnected(g_orig, n, num_components, vertid_to_component, num_verts_per_component, biggest_comp_p);
return extended_p; // TODO replace this with extended_p
}
// Locate the triangle (vi, y, wi) which has (vi, wi) as a boundary edge and lies inside the (vi, wi) cycle.
// one of the vertices in the set neighbors_vw is y. Maybe it's .begin(), so we use is_edge_inside_outside_or_on_cycle to test if it is.j
vertex_t findy(vertex_t vi, set<vertex_t> const& neighbors_vw, vector<vertex_t> const& cycle, GraphCR g_shrunk, EmbedStruct const& em, decltype(get(vertex_index, const_cast<Graph&>(g_shrunk))) prop_map)
{
for( vertex_t y_candidate : neighbors_vw ){
pair<edge_t, bool> vi_cy = edge(vi, y_candidate, g_shrunk);
BOOST_ASSERT(vi_cy.second);
edge_t e = vi_cy.first;
InsideOutOn insideout = is_edge_inside_outside_or_on_cycle(e, vi, cycle, g_shrunk, em.em);
if( INSIDE == insideout ){
return y_candidate;
}
}
/*pair<edge_t, bool> maybe_y = edge(vi, *neighbors_vw.begin(), g_shrunk);
BOOST_ASSERT(maybe_y.second); // I'm assuming the bool means that the edge_t exists? Boost Graph docs don't say
cout << "maybe_y: " << to_string(maybe_y.first, g_shrunk) << '\n';
cout << "cycle:\n";
print_cycle(cycle, g_shrunk);
vertex_t common_vert_on_cycle = find(STLALL(cycle), *neighbors_vw.begin()) == cycle.end() ?
*neighbors_vw.rbegin() :
*neighbors_vw.begin() ;
cout << "common vert on cycle: " << prop_map[common_vert_on_cycle] << '\n';
BOOST_ASSERT(find(STLALL(cycle), common_vert_on_cycle) != cycle.end());
InsideOutOn insideout = is_edge_inside_outside_or_on_cycle(maybe_y.first, common_vert_on_cycle, cycle, g_shrunk, em.em);
BOOST_ASSERT(insideout != ON);
vertex_t y = (insideout == INSIDE) ? *neighbors_vw.begin() : *neighbors_vw.rbegin();*/
// We now have the (vi, y, wi) triangle
BOOST_ASSERT(0);
}
// Step 9: Improve Separator
// Time: O(n)
//
// Let (vi, wi) be the nontree edge whose cycle is the current candidate to complete the separator.
// If the cost inside the cycle exceeds 2/3, find a better cycle by the following method.
// Locate the triangle (vi, y, wi) which has (vi, wi) as a boundary edge and lies inside the (vi, wi) cycle.
// If either (vi, y) or (y, wi) is a tree edge, let (vi+1, wi+1) be the nontree edge among (vi, y) and (y, wi).
// Compute the cost inside the (vi+1, wi+1) cycle from the cost inside the (vi, wi) cycle and the cost of vi, y and wi.
// If neither (vi, y) nor (y, wi) is a tree edge, determine the tree path from y to the (vi, wi) cycle by following parent pointers from y.
// Let z be the vertex on the (vi, wi) cycle reached during this search. Compute the total cost of all vertices except z on this tree path.
// Scan the tree edges inside the (y, wi) cycle, alternately scanning an edge in one cycle and an edge in the other cycle.
// Stop scanning when all edges inside one of the cycles have been scanned. Compute the cost inside this cycle by summing the associated costs of all scanned edges.
// Use this cost, the cost inside the (vi, wi) cycle, and the cost on the tree path from y to z to compute the cost inside the other cycle.
// Let (vi+1, wi+1) be the edge among (vi, y) and (y, wi) whose cycle has more cost inside it.
// Repeat Step 9 until finding a cycle whose inside has cost not exceeding 2/3.
Partition improve_separator(GraphCR g_orig, Graph& g_shrunk, CycleCost& cc, edge_t completer_candidate_edge, BFSVisitorData const& vis_data_orig,
BFSVisitorData const& vis_data_shrunken, vector<vertex_t> cycle, EmbedStruct const& em, bool cost_swapped, vector<uint> const& L, uint l[3])
{
cout << "---------------------------- 9 - Improve Separator -----------\n";
print_graph(g_shrunk);
auto prop_map = get(vertex_index, g_shrunk); // writing to this property map has side effects in the graph
cout << "cycle: ";
for( uint i = 0; i < cycle.size(); ++i ) cout << prop_map[cycle[i]] << ' ';
cout << '\n';
uint n_orig = num_vertices(g_orig);
uint n = num_vertices(g_shrunk);
cout << "n_orig: " << n_orig << ", n: " << n << '\n';
while( cc.inside > 2.*n/3 ){
cout << "nontree completer candidate edge: " << to_string(completer_candidate_edge, g_shrunk) << '\n';
cout << "cost inside: " << cc.inside << '\n';
cout << "cost outide: " << cc.outside << '\n';
cout << "looking for a better cycle\n";
// Let (vi, wi) be the nontree edge whose cycle is the current candidate to complete the separator
vertex_t vi = source(completer_candidate_edge, g_shrunk);
vertex_t wi = target(completer_candidate_edge, g_shrunk);
BOOST_ASSERT(!vis_data_shrunken.is_tree_edge(completer_candidate_edge));
cout << " vi: " << prop_map[vi] << '\n';
cout << " wi: " << prop_map[wi] << '\n';
set<vertex_t> neighbors_of_v = get_neighbors(vi, g_shrunk);
set<vertex_t> neighbors_of_w = get_neighbors(wi, g_shrunk);
set<vertex_t> neighbors_vw = get_intersection(neighbors_of_v, neighbors_of_w);
for( auto& ne : neighbors_vw ){
cout << "neighbor: " << ne << " prop_map: " << prop_map[ne] << '\n';
}
cout << " neighbors_vw_begin : " << prop_map[*neighbors_vw.begin()] << '\n';
cout << " neighbors_vw_rbegin: " << prop_map[*neighbors_vw.rbegin()] << '\n';
vertex_t y = findy(vi, neighbors_vw, cycle, g_shrunk, em, prop_map);
cout << " y: " << prop_map[y] << '\n';
pair<edge_t, bool> viy_e = edge(vi, y, g_shrunk); BOOST_ASSERT(viy_e.second); edge_t viy = viy_e.first;
pair<edge_t, bool> ywi_e = edge(y, wi, g_shrunk); BOOST_ASSERT(ywi_e.second); edge_t ywi = ywi_e.first;
edge_t next_edge;
// if either (vi, y) or (y, wi) is a tree edge,
if ( vis_data_shrunken.is_tree_edge(viy) || vis_data_shrunken.is_tree_edge(ywi) ){
// determine the tree path from y to the (vi, wi) cycle by following parent pointers from y.
cout << " at least one tree edge\n";
next_edge = vis_data_shrunken.is_tree_edge(viy) ? ywi : viy;
BOOST_ASSERT(!vis_data_shrunken.is_tree_edge(next_edge));
// Compute the cost inside the (vi+1 wi+1) cycle from the cost inside the (vi, wi) cycle and the cost of vi, y, and wi. See Fig 4.
uint cost[4] = {vis_data_shrunken.verts.find(vi)->second.descendant_cost,
vis_data_shrunken.verts.find(y )->second.descendant_cost,
vis_data_shrunken.verts.find(wi)->second.descendant_cost,
cc.inside};
vector<vertex_t> new_cycle = vis_data_shrunken.get_cycle(source(next_edge, g_shrunk), target(next_edge, g_shrunk));
cc = compute_cycle_cost(new_cycle, g_shrunk, vis_data_shrunken, em); // !! CHEATED !!
if( cost_swapped ) swap(cc.outside, cc.inside);
} else {
// Determine the tree path from y to the (vi, wi) cycle by following parents of y.
cout << " neither are tree edges\n";
vector<vertex_t> y_parents = vis_data_shrunken.ancestors(y);
for( vertex_t vp : y_parents ){
cout << "y parent: " << prop_map[vp] << '\n';
}
uint i = 0;
while( !on_cycle(y_parents.at(i), cycle, g_shrunk) ){
cout << "yparents[" << i << "]: " << y_parents[i] << " propmap: " << prop_map[y_parents[i]] << '\n';
++i;
}
cout << "yparents[" << i << "]: " << y_parents.at(i) << " propmap: " << prop_map[y_parents[i]] << '\n';
// Let z be the vertex on the (vi, wi) cycle reached during the search.
cout << "i: " << i << '\n';
vertex_t z = y_parents.at(i);
cout << "z: " << prop_map[z] << '\n';
BOOST_ASSERT(on_cycle(z, cycle, g_shrunk));
cout << " z: " << prop_map[z] << '\n';
y_parents.erase(y_parents.begin()+i, y_parents.end());
BOOST_ASSERT(y_parents.size() == i);
// Compute the total cost af all vertices except z on this tree path.
uint path_cost = y_parents.size() - 1;
cout << " y-to-z-minus-z cost: " << path_cost << '\n';
// Scan the tree edges inside the (y, wi) cycle, alternately scanning an edge in one cycle and an edge in the other cycle.
// Stop scanning when all edges inside one of the cycles have been scanned. Compute the cost inside this cycle by summing the associated costs of all scanned edges.
// Use this cost, the cost inside the (vi, wi) cycle, and the cost on the tree path from y to z to compute the cost inside the other cycle.
vector<vertex_t> cycle1 = vis_data_shrunken.get_cycle(vi, y);
vector<vertex_t> cycle2 = vis_data_shrunken.get_cycle(y, wi);
CycleCost cost1 = compute_cycle_cost(cycle1, g_shrunk, vis_data_shrunken, em);
CycleCost cost2 = compute_cycle_cost(cycle2, g_shrunk, vis_data_shrunken, em);
if( cost_swapped ){
swap(cost1.inside, cost1.outside);
swap(cost2.inside, cost2.outside);
}
// Let (vi+1, wi+1) be the edge among (vi, y) and (i, wi) whose cycle has more cost inside it.
if( cost1.inside > cost2.inside ){ next_edge = edge(vi, y, g_shrunk).first; cc = cost1; cycle = cycle1;}
else { next_edge = edge(y, wi, g_shrunk).first; cc = cost2; cycle = cycle2;}
}
completer_candidate_edge = next_edge;
}
cout << "found fundamental cycle with inside cost " << cc.inside << " which is less than 2/3\n";
print_cycle(cycle, g_shrunk);
//BOOST_ASSERT(assert_verts(g_copy, vis_data_copy)); // disabled because it doesn't support connected components
//BOOST_ASSERT(vis_data_orig.assert_data());
//BOOST_ASSERT(vis_data_shrunken.assert_data());
return construct_vertex_partition(g_orig, g_shrunk, L, l, vis_data_orig, vis_data_shrunken, cycle); // step 10
}
// Step 8: locate_cycle
// Time: O(n)
//
// Choose any nontree edge (v1, w1).
// Locate the corresponding cycle by following parent pointers from v1 and w1.
// Compute the cost on each side of this cycle by scanning the tree edges incident on either side of the cycle and summing their associated costs.
// If (v, w) is a tree edge with v on the cycle and w not on the cycle, the cost associated with (v,w) is the descendant cost of w if v is the parent of w,
// and the cost of all vertices minus the descendant cost of v if w is the parent of v.
// Determine which side of the cycle has greater cost and call it the "inside"
Partition locate_cycle(GraphCR g_orig, Graph& g_shrunk, BFSVisitorData const& vis_data_orig, BFSVisitorData const& vis_data_shrunken, vector<uint> const& L, uint l[3])
{
//BOOST_ASSERT(vis_data_orig.assert_data()); //BOOST_ASSERT(assert_verts(g_copy, vis_data_copy)); // disabled because it doesn't support connected components
//BOOST_ASSERT(vis_data_shrunken.assert_data()); //BOOST_ASSERT(assert_verts(g_copy, vis_data_copy)); // disabled because it doesn't support connected components
uint n = num_vertices(g_orig);
cout << "----------------------- 8 - Locate Cycle -----------------\n";
print_graph(g_shrunk);
edge_t completer_candidate_edge;
try {
completer_candidate_edge = vis_data_shrunken.arbitrary_nontree_edge(g_shrunk);
} catch (NoNontreeEdgeException const& e){
vector<vertex_t> cycle;
CycleCost cc;
cc.inside = 0;
cc.outside = n; // force Step 9 to exit without going through any iterations
bool cost_swapped = false;
EmbedStruct em(&g_shrunk);
return improve_separator(g_orig, g_shrunk, cc, completer_candidate_edge, vis_data_orig, vis_data_shrunken, cycle, em, cost_swapped, L, l); // step 9
}
vertex_t v1 = source(completer_candidate_edge, g_shrunk);
vertex_t w1 = target(completer_candidate_edge, g_shrunk);
cout << "ancestors v1...\n";
vector<vertex_t> parents_v = vis_data_shrunken.ancestors(v1);
cout << "ancestors v2...\n";
vector<vertex_t> parents_w = vis_data_shrunken.ancestors(w1);
vertex_t common_ancestor = get_common_ancestor(parents_v, parents_w);
cout << "common ancestor: " << common_ancestor << '\n';
vector<vertex_t> cycle = vis_data_shrunken.get_cycle(v1, w1, common_ancestor);
EmbedStruct em(&g_shrunk);
CycleCost cc = compute_cycle_cost(cycle, g_shrunk, vis_data_shrunken, em);
bool cost_swapped;
if( cc.outside > cc.inside ){
swap(cc.outside, cc.inside);
cost_swapped = true;
cout << "!!!!!! cost swapped !!!!!!!!\n";
} else cost_swapped = false;
cout << "total inside cost: " << cc.inside << '\n';
cout << "total outside cost: " << cc.outside << '\n';
return improve_separator(g_orig, g_shrunk, cc, completer_candidate_edge, vis_data_orig, vis_data_shrunken, cycle, em, cost_swapped, L, l); // step 9
}
// Step 7: new_bfs_and_make_max_planar
// Time: O(n)
//
// Construct a breadth-first spanning tree rooted at x in the new (shrunken) graph.
// (This can be done by modifying the breadth-first spanning tree constructed in Step 3 bfs_and_levels.)
// Record, for each vertex v, the parent of v in the tree, and the total cost of all descendants of v includiing v itself.
// Make all faces of the new graph into triangles by scanning the boundary of each face and adding (nontree) edges as necessary.
Partition new_bfs_and_make_max_planar(GraphCR g_orig, Graph& g_shrunk, BFSVisitorData const& vis_data_orig, vertex_t x, vector<uint> const& L, uint l[3])
{
cout << "-------------------- 7 - New BFS and Make Max Planar -----\n";
cout << "g_orig:\n";
print_graph(g_orig);
print_graph_addresses(g_orig);
cout << "g_shrunk:\n";
print_graph(g_shrunk);
print_graph_addresses(g_shrunk);
//reset_vertex_indices(g_shrunk);
//reset_edge_index(g_shrunk);
BFSVisitorData shrunken_vis_data(&g_shrunk, x);
//vis_data.reset(&g_shrunk);
shrunken_vis_data.root = x;
++shrunken_vis_data.verts[shrunken_vis_data.root].descendant_cost;
uint n = num_vertices(g_shrunk);
cout << "n: " << n << '\n';
cout << "null vertex: " << Graph::null_vertex() << '\n';
BFSVisitor visit = BFSVisitor(shrunken_vis_data);
auto bvs = boost::visitor(visit);
cout << "g_shrunk:\n";
print_graph(g_shrunk);
// workaround for https://github.com/boostorg/graph/issues/195
VertIter vit, vjt;
tie(vit, vjt) = vertices(g_shrunk);
for( VertIter next = vit; vit != vjt; ++vit){
if( 0 == in_degree(*vit, g_shrunk) + out_degree(*vit, g_shrunk) ){
add_edge(*vit, *vit, g_shrunk);
}
}
cout << "g_shrunk with workaround:\n";
print_graph(g_shrunk);
BOOST_ASSERT(vertex_exists(shrunken_vis_data.root, g_shrunk));
breadth_first_search(g_shrunk, shrunken_vis_data.root, bvs);
make_max_planar(g_shrunk);
//reset_vertex_indices(g_shrunk);
reset_edge_index(g_shrunk);
print_graph(g_shrunk);
return locate_cycle(g_orig, g_shrunk, vis_data_orig, shrunken_vis_data, L, l); // step 8
}
// Step 6: Shrinktree
// Time: big-theta(n)
//
// Delete all vertices on level l2 and above.
// Construct a new vertex x to represent all vertices on levels 0 through l0.
// Construct a boolean table with one entry per vertex.
// Initialize to true the entry for each vertex on levels 0 through l0 and
// initialize to false the entry for each vertex on levels l0 + 1 through l2 - 1.
// The vertices on levels 0 through l0 correspond to a subtree of the breadth-first spanning tree
// generated in Step 3 (bfs_and_levels).
// Scan the edges incident to this tree clockwise around the tree.
// When scanning an edge(v, w) with v in the tree, check the table entry for w.
// If it is true, delete edge(v, w).
// If it is false, change it to true, construct an edge(x,w) and delete edge(v,w).
// The result of this step is a planar representation of the shrunken graph to which Lemma 2 is to be applied.
//const uint X_VERT_UINT = 9999;
vector<vertex_t> shrinktree_deletel2andabove(Graph& g, uint l[3], BFSVisitorData const& vis_data_copy, vertex_t x)
{
cout << "l[0]: " << l[0] << '\n';
cout << "l[1]: " << l[1] << '\n';
cout << "l[2]: " << l[2] << '\n';
vector<vertex_t> replaced_verts;
VertIter vit, vjt;
tie(vit, vjt) = vertices(g);
for( VertIter next = vit; vit != vjt; vit = next ){
++next;
if( *vit == x ) continue; // don't delete x
if( !vis_data_copy.verts.contains(*vit) ) continue; // *vit is in a different connected component
uint level = vis_data_copy.verts.find(*vit)->second.level;
if( level >= l[2] ){
kill_vertex(*vit, g);
}
if( level <= l[0] ){
replaced_verts.push_back(*vit);
}
}
return replaced_verts;
}
Partition shrinktree(GraphCR g_orig, Graph& g_copy, BFSVisitorData const& vis_data_orig, BFSVisitorData const& vis_data_copy, vector<uint> const& L, uint l[3])
{
Graph& g_shrunk = g_copy;
cout << "---------------------------- 6 - Shrinktree -------------\n";
print_graph(g_copy);
cout << "n: " << num_vertices(g_shrunk) << '\n';
// delete all vertices on level l2 and above
vertex_t x = add_vertex(g_shrunk);
BFSVisitorData vis_data_addx(vis_data_copy);
vis_data_addx.root = x;
vis_data_addx.verts[x].level = 0;
vis_data_addx.verts[x].parent = Graph::null_vertex();
vis_data_addx.verts[x].descendant_cost = -1;
BOOST_ASSERT(vertex_exists(x, g_shrunk));
//BOOST_ASSERT(assert_verts(g_copy, vis_data_addx)); //BOOST_ASSERT(assert_verts(g_copy, vis_data_copy)); // disabled because it doesn't support connected components
vector<vertex_t> replaced_verts = shrinktree_deletel2andabove(g_shrunk, l, vis_data_addx, x);
BOOST_ASSERT(vertex_exists(x, g_shrunk));
//BOOST_ASSERT(assert_verts(g_copy, vis_data_addx)); //BOOST_ASSERT(assert_verts(g_copy, vis_data_copy)); // disabled because it doesn't support connected components
//prop_map[x] = X_VERT_UINT;
map<vertex_t, bool> table; // x will not be in this table
VertIter vit, vjt;
for( tie(vit, vjt) = vertices(g_shrunk); vit != vjt; ++vit ){
if( *vit == x ) continue; // the new x isn't in visdata, std::map::find() will fail
if( !vis_data_addx.verts.contains(*vit) ) continue; // *vit may be in a different connected component
uint level = vis_data_addx.verts.find(*vit)->second.level;
table[*vit] = level <= l[0];
}
BOOST_ASSERT(vertex_exists(x, g_shrunk));
//BOOST_ASSERT(assert_verts(g_copy, vis_data_addx)); //BOOST_ASSERT(assert_verts(g_copy, vis_data_copy)); // disabled because it doesn't support connected components
cout << "g_shrunk:\n";
print_graph(g_shrunk);
reset_vertex_indices(g_shrunk);
//reset_vertex_indices(g_shrunk);
//reset_edge_index(g_shrunk);
EmbedStruct em = ctor_workaround(&g_shrunk);
BOOST_ASSERT(test_planar_workaround(em.em, &g_shrunk));
//BOOST_ASSERT(assert_verts(g_copy, vis_data_addx)); //BOOST_ASSERT(assert_verts(g_copy, vis_data_copy)); // disabled because it doesn't support connected components
VertIter vei, vend;
for( tie(vei, vend) = vertices(g_orig); vei != vend; ++vei ){
vertex_t v = *vei;
if( !vis_data_orig.verts.contains(v) ){
cerr << "lipton-tarjan.cpp: ignoring bad vertex : " << v << '\n';
continue;
}
}
ScanVisitor svis(&table, &g_shrunk, x, l[0]);
svis.scan_nonsubtree_edges_clockwise(*vertices(g_shrunk).first, g_shrunk, em.em, vis_data_addx);
svis.finish();
BOOST_ASSERT(vertex_exists(x, g_shrunk));
cout << "deleting all vertices x has replaced\n"; for( vertex_t& v : replaced_verts ) {cout << "killing " << v << '\n'; kill_vertex(v, g_shrunk); }// delete all vertices x has replaced
reset_vertex_indices(g_shrunk);
BOOST_ASSERT(vertex_exists(x, g_shrunk));
cout << "g_shrunk:\n";
print_graph(g_shrunk);
uint n2 = num_vertices(g_shrunk);
cout << "shrunken size: " << n2 << '\n';
auto prop_map = get(vertex_index, g_shrunk);
cout << "x prop_map: " << prop_map[x] << '\n';
cout << "x : " << x << '\n';
return new_bfs_and_make_max_planar(g_orig, g_shrunk, vis_data_orig, x, L, l); // step 7
}
// Step 5: find_more_levels
// Time: O(n)
//
// Find the highest level l0 <= l1 such that L(l0) + 2(l1 - l0) <= 2*sqrt(k).
// Find the lowest level l2 >= l1 + 1 such that L(l2) + 2(l2-l1-1) <= 2*sqrt(n-k)
Partition find_more_levels(GraphCR g_orig, Graph& g_copy, uint k, uint l[3], vector<uint> const& L, BFSVisitorData const& vis_data_orig, BFSVisitorData const& vis_data_copy)
{
//BOOST_ASSERT(assert_verts(g_copy, vis_data_copy)); // disabled because it doesn't support connected components
cout << "---------------------------- 5 - Find More Levels -------\n";
//print_graph(g_copy);
float sq = 2 * sqrt(k);
float snk = 2 * sqrt(num_vertices(g_copy) - k);
cout << "sq: " << sq << '\n';
cout << "snk: " << snk << '\n';
cout << "L size: " << L.size() << '\n';
l[0] = l[1];
cout << "l[0]: " << l[0] << '\n';
while( l[0] < L.size() ){
float val = L.at(l[0]) + 2*(l[1] - l[0]);
if( val <= sq ) break;
--l[0];
}
cout << "l0: " << l[0] << " highest level <= l1\n";
l[2] = l[1] + 1;
cout << "l[2]" << l[2] << '\n';
while( l[2] < L.size() ){
float val = L.at(l[2]) + 2*(l[2] - l[1] - 1);
if( val <= snk ) break;
++l[2];
}
cout << "l2: " << l[2] << " lowest level >= l1 + 1\n";
return shrinktree(g_orig, g_copy, vis_data_orig, vis_data_copy, L, l); // step 6
}
// Step 4: l1_and_k
// Time: O(n)
//
// Find the level l1 such that the total cost of levels 0 through l1 - 1 does not exceed 1/2,
// but the total cost of levels 0 through l1 does exceed 1/2.
// Let k be the number of vertices in levels 0 through l1
Partition l1_and_k(GraphCR g_orig, Graph& g_copy, vector<uint> const& L, BFSVisitorData const& vis_data_orig, BFSVisitorData const& vis_data_copy)
{
//BOOST_ASSERT(assert_verts(g_copy, vis_data_copy)); // disabled because it doesn't support connected components
cout << "---------------------------- 4 - l1 and k ------------\n";
uint k = L[0];
uint l[3];
uint n = num_vertices(g_copy);
l[1] = 0;
while( k <= n/2 ){
uint indx = ++l[1];
uint lsize = L.size();
if( indx >= lsize ) break;
k += L.at(indx);
}
cout << "k: " << k << " # of verts in levels 0 thru l1\n";
cout << "l1: " << l[1] << " total cost of levels 0 thru l1 barely exceeds 1/2\n";
BOOST_ASSERT(k <= n);
return find_more_levels(g_orig, g_copy, k, l, L, vis_data_orig, vis_data_copy); // step 5
}
// Step 3: bfs_and_levels
// Time: O(n)
//
// Find a breadth-first spanning tree of the most costly component.
// Compute the level of each vertex and the number of vertices L(l) in each level l.
Partition bfs_and_levels(GraphCR g_orig, Graph& g_copy)
{
cout << "---------------------------- 3 - BFS and Levels ------------\n";
BFSVisitorData vis_data_copy(&g_copy, *vertices(g_copy).first);
breadth_first_search(g_copy, vis_data_copy.root, boost::visitor(BFSVisitor(vis_data_copy)));
BFSVisitorData vis_data_orig(&g_orig, *vertices(g_orig).first);
breadth_first_search(g_orig, vis_data_orig.root, boost::visitor(BFSVisitor(vis_data_orig)));
// disabled because they don't support multiple connected components
//BOOST_ASSERT(assert_verts(g_orig, vis_data_orig));
//BOOST_ASSERT(assert_verts(g_copy, vis_data_copy));
vector<uint> L(vis_data_copy.num_levels + 1, 0);
cout << "L levels: " << L.size() << '\n';
for( auto& d : vis_data_copy.verts ){
cout << "level: " << d.second.level << '\n';
++L[d.second.level];
}
VertIter vit, vjt;
for( tie(vit, vjt) = vertices(g_copy); vit != vjt; ++vit ){
if( vis_data_copy.verts.contains(*vit) ) cout << "level/cost of vert " << *vit << ": " << vis_data_copy.verts[*vit].level << '\n';
}
for( uint i = 0; i < L.size(); ++i ){
cout << "L[" << i << "]: " << L[i] << '\n';
}
return l1_and_k(g_orig, g_copy, L, vis_data_orig, vis_data_copy); // step 4
}
// Step 2: find_connected_components
// Time: O(n)
//
// Find the connected components of G and determine the cost of each one.
// If none has cost exceeding 2/3, construct the partition as described in the proof of Theorem 4.
// If some component has cost exceeding 2/3, go to Step 3.
Partition find_connected_components(GraphCR g_orig, Graph& g_copy)
{
uint n = num_vertices(g_copy);
//cout << "---------------------------- 2 - Find Connected Components --------\n";
vertex_map idx;
associative_property_map<vertex_map> vertid_to_component(idx);
VertIter vit, vjt;
tie(vit, vjt) = vertices(g_copy);
for( uint i = 0; vit != vjt; ++vit, ++i ){
//cout << "checking vertex number: " << i << ' ' << *vit << '\n';
put(vertid_to_component, *vit, i);
}
uint num_components = connected_components(g_copy, vertid_to_component);
//cout << "# of connected components: " << num_components << '\n';
vector<uint> num_verts_per_component(num_components, 0);
for( tie(vit, vjt) = vertices(g_copy); vit != vjt; ++vit ){
++num_verts_per_component[vertid_to_component[*vit]];
}
uint biggest_component_index = 0;
uint biggest_size = 0;
bool bigger_than_two_thirds = false;
for( uint i = 0; i < num_components; ++i ){
if( 3*num_verts_per_component[i] > 2*num_vertices(g_copy) ){
//cout << "component " << i << " is bigger than two thirds of the entire graph\n";
bigger_than_two_thirds = true;
}
if( num_verts_per_component[i] > biggest_size ){
biggest_size = num_verts_per_component[i];
biggest_component_index = i;
}
}
if( !bigger_than_two_thirds ){
cout << "exiting early through theorem 4 - no component has cost exceeding two thirds\n";
// connected graphs can never get here because they would have a single component with total cost > 2/3
Partition defp;
return theorem4_disconnected(g_copy, n, num_components, vertid_to_component, num_verts_per_component, defp);
}
cout << "index of biggest component: " << biggest_component_index << '\n';
return bfs_and_levels(g_orig, g_copy); // step 3
}
// Step 1: check_planarity
// Time: big-theta(n)
//
// Find a planar embedding of G and construct a representation for it of the kind described above.
Partition lipton_tarjan_separator(GraphCR g_orig)
{
Graph g_copy(g_orig);
//cout << "@#$original g:\n";
print_graph(g_orig);
//cout << "@#$g_copy:\n";
//print_graph2(g_copy);
/*auto prop_map = get(vertex_index, g_copy);
VertIter vi, vend;
for( tie(vi, vend) = vertices(g_copy); vi != vend; ++vi ){
cout << "vert#: " << prop_map[*vi] << '\n';
}*/
/*cout << "---------------------------- 0 - Printing Edges -------------------\n";
cout << "edges of g:\n";*/
//cout << "edges of g_copy:\n" << std::endl;
cout << "---------------------------- 1 - Check Planarity ------------\n";
EmbedStruct em(&g_copy);
if( !em.test_planar() ) throw NotPlanarException();
return find_connected_components(g_orig, g_copy);
}
| 49.311669
| 224
| 0.603672
|
jeffythedragonslayer
|
2a11bad50ddeed1c4d00966be02e838f549793ce
| 9,417
|
cpp
|
C++
|
Meteorites.Tests/GoldSolverTests.cpp
|
m-krivov/MeteoriteSimulator
|
a60cdef30ffff0bfab11ee8db799b41b3cdee452
|
[
"MIT"
] | null | null | null |
Meteorites.Tests/GoldSolverTests.cpp
|
m-krivov/MeteoriteSimulator
|
a60cdef30ffff0bfab11ee8db799b41b3cdee452
|
[
"MIT"
] | null | null | null |
Meteorites.Tests/GoldSolverTests.cpp
|
m-krivov/MeteoriteSimulator
|
a60cdef30ffff0bfab11ee8db799b41b3cdee452
|
[
"MIT"
] | null | null | null |
#include "TestDefs.h"
#include "Meteorites.CpuSolvers/GoldSolver.h"
TEST_CLASS(GoldSolverTests)
{
public:
TEST_METHOD(Vacuum_VerticalSpeed)
{
GoldSolver solver(GoldSolver::ONE_STEP_ADAMS);
solver.Configure(dt_sim, 3600.0f);
Case problem(1.0f, 0.0f, 2000.0f, 0.0f, 0.0f,
1.0f, 0.5f, 1000.0f, (real)std::_Pi / 2);
FakeFunctional f;
BufferingFormatter fmt(0.1f);
solver.Solve(problem, f, fmt);
decltype(auto) log = ExtractLogPtrs<1>(fmt)[0];
decltype(auto) last_record = log->records[log->records.size() - 1];
Assert::IsTrue(std::abs(last_record.M - problem.M0()) < (real)1e-3);
auto a = -Constants::g() / 2.0;
auto b = -problem.V0();
auto c = problem.h0() - last_record.h;
auto d = b * b - 4 * a * c;
auto t = (-b - std::sqrt(d)) / (2 * a);
Assert::IsTrue(std::abs(last_record.t - t) < 1e-2f);
Assert::IsTrue(std::abs(last_record.V - (problem.V0() + Constants::g() * t)) < 1e-1f);
}
TEST_METHOD(Vacuum_HorizontalSpeed)
{
GoldSolver solver(GoldSolver::ONE_STEP_ADAMS);
solver.Configure(dt_sim, 3600.0f);
Case problem(1.0f, 0.0f, 2000.0f, 0.0f, 0.0f,
1.0f, 2.5f, 500.0f, 0.0f);
FakeFunctional f;
BufferingFormatter fmt(0.1f);
solver.Solve(problem, f, fmt);
decltype(auto) log = ExtractLogPtrs<1>(fmt)[0];
decltype(auto) last_record = log->records[log->records.size() - 1];
Assert::IsTrue(std::abs(last_record.M - problem.M0()) < (real)1e-3);
auto a = -Constants::g() / 2.0;
auto b = 0.0f;
auto c = problem.h0() - last_record.h;
auto d = b * b - 4 * a * c;
auto t = (-b - std::sqrt(d)) / (2 * a);
auto dist = problem.V0() * std::cos(problem.Gamma0()) * t;
Assert::IsTrue(std::abs(last_record.t - t) < 1e-2f);
Assert::IsTrue(std::abs(last_record.V - Constants::g() * t) < 1e-1f);
Assert::IsTrue(std::abs(last_record.l - dist) < 2e-1f);
}
TEST_METHOD(Atmosphere_BrakingForce)
{
GoldSolver solver(GoldSolver::ONE_STEP_ADAMS);
solver.Configure(dt_sim, 3600.0f);
FakeFunctional f;
BufferingFormatter fmt(0.0f);
for (auto Cd : { 0.0f, 0.5f, 1.0f, 1.5f, 2.0f })
{
Case problem(1.0f, 0.0f, 2000.0f, Cd, 0.0f,
1.0f, 50.0f, 500.0f, -(real)std::_Pi / 4);
solver.Solve(problem, f, fmt);
}
decltype(auto) logs = ExtractLogPtrs<5>(fmt);
std::array<std::pair<real, real>, 5> peaks;
for (size_t i = 0; i < logs.size(); i++)
{
decltype(auto) records = logs[i]->records;
auto peak = std::make_pair(records[0].h, records[0].t);
bool peak_reached = false;
for (size_t j = 1; j < records.size(); j++)
{
if (!peak_reached)
{
if (records[j].h < peak.first)
{ peak_reached = true; }
else
{ peak = std::make_pair(records[j].h, records[j].t); }
}
else
{ Assert::IsTrue(records[j].h < peak.first); }
} // for j
peaks[i] = peak;
} // for i
for (size_t i = 1; i < peaks.size(); i++)
{
Assert::IsTrue(peaks[i - 1].first > peaks[i].first * 1.005f);
Assert::IsTrue(peaks[i - 1].second > peaks[i].second * 1.005f);
}
}
TEST_METHOD(Atmosphere_LiftingForce)
{
GoldSolver solver(GoldSolver::ONE_STEP_ADAMS);
solver.Configure(dt_sim, 3600.0f);
FakeFunctional f;
BufferingFormatter fmt(0.0f);
for (auto Cl : { 0.0f, 0.05f, 0.1f, 0.15f })
{
Case problem(1.0f, 0.0f, 2000.0f, 0.0f, Cl,
1.0f, 100.0f, 500.0f, 0.0f);
solver.Solve(problem, f, fmt);
}
decltype(auto) logs = ExtractLogPtrs<4>(fmt);
for (size_t i = 0; i < logs.size() - 1; i++)
{
Assert::IsTrue(logs[i]->reason == IResultFormatter::Reason::Collided);
Assert::IsTrue(logs[i + 1]->reason == IResultFormatter::Reason::Collided);
Assert::IsTrue(logs[i]->records.size() > 1000);
for (size_t j = 1000; j < logs[i]->records.size(); j++)
{
if (j >= logs[i + 1]->records.size()) { break; }
Assert::IsTrue(logs[i + 1]->records[j].h > logs[i]->records[j].h * 1.001f);
} // for j
} // for i
}
TEST_METHOD(Atmosphere_HeatExchange)
{
GoldSolver solver(GoldSolver::ONE_STEP_ADAMS);
solver.Configure(dt_sim, 3600.0f);
FakeFunctional f;
BufferingFormatter fmt(0.0f);
for (auto coeffs : { std::make_pair(1e6f, 0.3f),
std::make_pair(2e6f, 0.2f),
std::make_pair(3e6f, 0.1f) })
{
Case problem(coeffs.first, coeffs.second, 2000.0f, 0.0f, 0.0f,
10.0f, 100.0f, 2000.0f, 0.0f);
solver.Solve(problem, f, fmt);
}
decltype(auto) logs = ExtractLogPtrs<3>(fmt);
for (size_t i = 0; i < logs.size(); i++)
{
decltype(auto) records = logs[i]->records;
for (size_t j = 1; j < records.size(); j++)
{ Assert::IsTrue(records[j - 1].M > records[j].M); }
} // for i
auto n = std::min(logs[0]->records.size(), logs[1]->records.size());
n = std::min(n, logs[2]->records.size());
Assert::IsTrue(n > 1000);
for (size_t i = 1000; i < n; i++)
{
Assert::IsTrue(logs[1]->records[i].M > logs[0]->records[i].M * 1.0001f);
Assert::IsTrue(logs[2]->records[i].M > logs[1]->records[i].M * 1.0001f);
}
}
TEST_METHOD(Method_TwoThreeSteps)
{
GoldSolver one_step(GoldSolver::ONE_STEP_ADAMS),
two_step(GoldSolver::TWO_STEP_ADAMS),
three_step(GoldSolver::THREE_STEP_ADAMS);
for (auto solver : { &one_step, &two_step, &three_step })
{ solver->Configure(dt_sim, 3600.0f); }
FakeFunctional f;
std::vector<Case> problems;
problems.emplace_back(Case(1e6f, 0.35f, 3500.0f, 1.1f, 0.1f,
10.0f, 14e3f, 60e3f, 0.0f));
problems.emplace_back(Case(0.5e6f, 0.5f, 2000.0f, 1.5f, 0.05f,
5.0f, 10e3f, 55e3f, (real)std::_Pi / 9));
for (auto &problem : problems)
{
BufferingFormatter fmt(0.01f);
for (auto solver : { &one_step, &two_step, &three_step })
{ solver->Solve(problem, f, fmt); }
auto logs = ExtractLogPtrs<3>(fmt);
auto n = std::min(logs[0]->records.size(),
logs[1]->records.size());
n = std::min(n, logs[2]->records.size());
for (size_t i = 0; i < n; i++)
{
AreAlmostEqual(logs[0]->records[i].gamma,
logs[1]->records[i].gamma,
logs[2]->records[i].gamma, 1e-2f);
AreAlmostEqual(logs[0]->records[i].h,
logs[1]->records[i].h,
logs[2]->records[i].h, 1e1f);
AreAlmostEqual(logs[0]->records[i].M,
logs[1]->records[i].M,
logs[2]->records[i].M, 1e-1f);
AreAlmostEqual(logs[0]->records[i].V,
logs[1]->records[i].V,
logs[2]->records[i].V, 1e1f);
} // for j
} // for problem
}
TEST_METHOD(Method_Precision)
{
GoldSolver solver(GoldSolver::ONE_STEP_ADAMS);
Case problem(0.5e6f, 0.1f, 4000.0f, 1.0f, 0.01f,
25.0f, 5e3f, 30e3f, (real)std::_Pi / 4);
FakeFunctional f;
BufferingFormatter fmt(0.01f);
for (auto dt : { 1e-3f, 1e-4f, 1e-5f })
{
solver.Configure(dt, 3600.0f);
solver.Solve(problem, f, fmt);
}
auto logs = ExtractLogPtrs<3>(fmt);
auto n = std::min(logs[0]->records.size(),
logs[1]->records.size());
n = std::min(n, logs[2]->records.size());
for (size_t i = 0; i < n; i++)
{
AreAlmostEqual(logs[0]->records[i].gamma,
logs[1]->records[i].gamma,
logs[2]->records[i].gamma, 1e-2f);
AreAlmostEqual(logs[0]->records[i].h,
logs[1]->records[i].h,
logs[2]->records[i].h, 1e1f);
AreAlmostEqual(logs[0]->records[i].M,
logs[1]->records[i].M,
logs[2]->records[i].M, 1e-1f);
AreAlmostEqual(logs[0]->records[i].V,
logs[1]->records[i].V,
logs[2]->records[i].V, 1e1f);
} // for j
}
private:
template <size_t N>
static decltype(auto) ExtractLogPtrs(const BufferingFormatter &fmt)
{
decltype(auto) logs = fmt.Logs();
Assert::AreEqual(logs.size(), N);
std::array<const BufferingFormatter::Log *, N> res;
for (size_t i = 0; i < logs.size(); i++)
{
decltype(auto) log = logs[i];
Assert::IsFalse(log.records.empty());
Assert::IsTrue(log.reason != IResultFormatter::Reason::NA);
res[i] = &log;
}
return res;
}
void AreAlmostEqual(real val1, real val2, real val3, real eps)
{
Assert::IsTrue(std::abs(val1 - val2) <= eps);
Assert::IsTrue(std::abs(val1 - val3) <= eps);
Assert::IsTrue(std::abs(val2 - val3) <= eps);
}
real dt_sim = (real)1e-3;
};
| 35.007435
| 92
| 0.520442
|
m-krivov
|
2a135182bcd849349aba93fed5d88b57833f0d87
| 21,399
|
cpp
|
C++
|
src/core/graph/internal/GraphInternal.cpp
|
alexbatashev/athena
|
eafbb1e16ed0b273a63a20128ebd4882829aa2db
|
[
"MIT"
] | 2
|
2020-07-16T06:42:27.000Z
|
2020-07-16T06:42:28.000Z
|
src/core/graph/internal/GraphInternal.cpp
|
PolarAI/polarai-framework
|
c5fd886732afe787a06ebf6fb05fc38069257457
|
[
"MIT"
] | null | null | null |
src/core/graph/internal/GraphInternal.cpp
|
PolarAI/polarai-framework
|
c5fd886732afe787a06ebf6fb05fc38069257457
|
[
"MIT"
] | null | null | null |
//===----------------------------------------------------------------------===//
// Copyright (c) 2020 PolarAI. All rights reserved.
//
// Licensed under MIT 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 <polarai/core/graph/internal/GraphInternal.hpp>
#include <polarai/core/node/internal/NodeInternal.hpp>
#include <polarai/loaders/internal/ConstantLoaderInternal.hpp>
#include <polarai/loaders/internal/DummyLoaderInternal.hpp>
#include <polarai/operation/AddOperation.hpp>
#include <polarai/operation/MulOperation.hpp>
#include <polarai/operation/internal/AddOperationInternal.hpp>
#include <polarai/operation/internal/MulOperationInternal.hpp>
#include <queue>
namespace polarai::core::internal {
GraphInternal::GraphInternal(utils::WeakPtr<ContextInternal> context,
utils::Index publicGraphIndex, utils::String name)
: Entity(std::move(context), publicGraphIndex, std::move(name)),
mTopology{}, mTraversal{}, mInputNodeIndexes{}, mInputsCount{},
mOutputsCount{} {}
template <typename Queue, typename Storage>
void initQueue(Queue& queue, const Storage& storage) {
for (auto inputNodeIndex : storage) {
queue.push(inputNodeIndex);
}
}
template <typename Map, typename Getter>
size_t safetyIncrementMapValue(Map& map, utils::Index index, Getter& getter) {
auto it = map.find(index);
if (it != map.end()) {
getter(map, index)++;
} else {
getter(map, index) = 1;
}
return getter(map, index);
}
void GraphInternal::connect(utils::Index startNode, utils::Index endNode,
EdgeMark edgeMark) {
mTopology.emplace_back(startNode, endNode, edgeMark);
auto getter = [](std::unordered_map<utils::Index, size_t>& map,
utils::Index index) -> size_t& { return map[index]; };
safetyIncrementMapValue(mInputsCount, endNode, getter);
safetyIncrementMapValue(mOutputsCount, startNode, getter);
}
std::tuple<std::vector<TensorInternal*>, std::unordered_map<int64_t, utils::Index>>
getOperationArgIndexes(utils::SharedPtr<ContextInternal>& context,
const NodeState& nodeState) {
std::vector<TensorInternal*> operationArgs{};
std::unordered_map<int64_t, utils::Index> mapMarkToLocalTensorIndex{};
operationArgs.reserve(nodeState.input.size());
size_t index = 0;
for (auto& inputDependence : nodeState.input) {
mapMarkToLocalTensorIndex[inputDependence.mark] = index;
operationArgs.push_back(
context->getPtr<AbstractNodeInternal>(inputDependence.nodeIndex)
->getTensorPtr());
++index;
}
return std::make_tuple(operationArgs, mapMarkToLocalTensorIndex);
}
void GraphInternal::setUpTensors() const {
auto contextInternal = mContext.lock();
for (auto& cluster : mTraversal.getClusters()) {
for (auto& nodeState : cluster.content) {
auto [args, mapMarkToLocalTensorIndex] = getOperationArgIndexes(contextInternal, nodeState);
auto node =
contextInternal->getPtr<AbstractNodeInternal>(nodeState.nodeIndex);
if (node->getTensorIndex() != 0) {
continue;
}
if (std::find(mInputNodeIndexes.begin(), mInputNodeIndexes.end(),
node->getPublicIndex()) != mInputNodeIndexes.end()) {
continue;
} else if (node->getType() == NodeType::DEFAULT) {
auto funcNode = static_cast<NodeInternal*>(node);
auto tensorIndex = funcNode->getOperationPtr()->createResultTensor(
mContext.lock(), mapMarkToLocalTensorIndex, args);
funcNode->setTensorIndex(tensorIndex);
} else if (node->getType() == NodeType::OUTPUT) {
#ifdef DEBUG
if (args.size() != 1) {
utils::FatalError(utils::ATH_ASSERT,
"Error while setUpTensors() is working. Number "
"arguments coming to output node doesn't equal 1.");
}
#endif
node->setTensorIndex(args[0]->getPublicIndex());
}
}
}
}
void GraphInternal::initInputNodeStates(
std::unordered_map<utils::Index, NodeState>& isPartOfWayToUnfrozenFlags)
const {
auto context = mContext.lock();
for (auto& indexInputNode : mInputNodeIndexes) {
auto& abstractNode = context->getRef<AbstractNodeInternal>(indexInputNode);
if (abstractNode.getType() == NodeType::INPUT) {
auto& inputNode = static_cast<InputNodeInternal&>(abstractNode);
isPartOfWayToUnfrozenFlags[indexInputNode] =
NodeState{inputNode.isFrozen()};
} else {
isPartOfWayToUnfrozenFlags[indexInputNode] = NodeState{true};
}
}
}
void GraphInternal::bypassDependenceOfCurrentNodeState(
const NodeState& currentNodeState, size_t currentClusterIndex,
size_t currentNodeStateIndex,
std::unordered_map<utils::Index, NodeState>& nodeStates,
std::unordered_map<utils::Index, NodeStateIndex>& traversedNodeStates) {
for (auto& dependence : currentNodeState.input) {
auto nodeIndex = dependence.nodeIndex;
std::vector<Dependency>* outputs{};
if (nodeStates.find(nodeIndex) != nodeStates.end()) {
outputs = &nodeStates.at(nodeIndex).output;
} else {
auto index = traversedNodeStates.at(nodeIndex);
outputs = &mTraversal.clusters()[index.clusterIndex]
.content[index.nodeStateIndex]
.output;
}
for (auto& output : *outputs) {
if (output.nodeIndex == currentNodeState.nodeIndex) {
output.clusterIndex = currentClusterIndex;
output.nodeStateIndex = currentNodeStateIndex;
}
}
}
for (auto& dependence : currentNodeState.output) {
auto nodeIndex = dependence.nodeIndex;
std::vector<Dependency>* inputs{};
if (nodeStates.find(nodeIndex) != nodeStates.end()) {
inputs = &nodeStates.at(nodeIndex).input;
} else {
auto index = traversedNodeStates.at(nodeIndex);
inputs = &mTraversal.clusters()[index.clusterIndex]
.content[index.nodeStateIndex]
.input;
}
for (auto& input : *inputs) {
if (input.nodeIndex == currentNodeState.nodeIndex) {
input.clusterIndex = currentClusterIndex;
input.nodeStateIndex = currentNodeStateIndex;
}
}
}
}
const Traversal& GraphInternal::traverse() {
if (mTraversal.isValidTraversal()) {
return mTraversal;
}
std::sort(mTopology.begin(), mTopology.end());
std::queue<utils::Index> currentQueue, newQueue;
initQueue(currentQueue, mInputNodeIndexes);
std::unordered_map<utils::Index, NodeState> nodeStates;
std::unordered_map<utils::Index, NodeStateIndex> traversedNodeStates;
initInputNodeStates(nodeStates);
while (true) {
Cluster cluster{0};
while (!currentQueue.empty()) {
size_t startNodeIndex = currentQueue.front();
currentQueue.pop();
Edge target(startNodeIndex, 0, 0);
auto edgeIterator =
std::lower_bound(mTopology.begin(), mTopology.end(), target);
while (edgeIterator != mTopology.end() &&
edgeIterator->startNodeIndex == startNodeIndex) {
auto endNodeIndex = edgeIterator->endNodeIndex;
auto getter = [](std::unordered_map<utils::Index, NodeState>& map,
utils::Index index) -> size_t& {
return map[index].inputsCount;
};
auto resInputsCount =
safetyIncrementMapValue(nodeStates, endNodeIndex, getter);
auto targetInputCount = mInputsCount.at(endNodeIndex);
if (resInputsCount == targetInputCount) {
newQueue.push(endNodeIndex);
} else if (resInputsCount > targetInputCount) {
utils::FatalError(utils::ATH_FATAL_OTHER,
"traverse() in Graph: ", this,
". Graph has cycle(s)");
}
nodeStates[startNodeIndex].output.emplace_back(endNodeIndex,
edgeIterator->mark);
nodeStates[endNodeIndex].input.emplace_back(startNodeIndex,
edgeIterator->mark);
nodeStates[endNodeIndex].isWayToFrozen =
nodeStates[endNodeIndex].isWayToFrozen &&
nodeStates[startNodeIndex].isWayToFrozen;
++edgeIterator;
}
auto& processedState = nodeStates[startNodeIndex];
cluster.content.emplace_back(startNodeIndex, processedState.inputsCount,
processedState.isWayToFrozen,
std::move(processedState.input),
std::move(processedState.output));
traversedNodeStates[startNodeIndex] = NodeStateIndex{
mTraversal.clusters().size(), cluster.content.size() - 1};
nodeStates.erase(startNodeIndex);
++cluster.nodeCount;
auto& currentNodeState = cluster.content.back();
bypassDependenceOfCurrentNodeState(
currentNodeState, mTraversal.clusters().size(),
cluster.content.size() - 1, nodeStates, traversedNodeStates);
}
if (cluster.nodeCount > 0) {
mTraversal.clusters().emplace_back(std::move(cluster));
}
std::swap(currentQueue, newQueue);
if (currentQueue.empty()) {
break;
}
}
mTraversal.validTraversalFlag() = true;
setUpTensors();
return mTraversal;
}
utils::Index
GraphInternal::createInitialGradientNode(GraphInternal& gradientGraph, const NodeState* nodeStatePtr) const {
auto context = mContext.lock();
auto& node = context->getRef<AbstractNodeInternal>(nodeStatePtr->nodeIndex);
auto tensor = node.getTensorPtr();
auto loaderIndex = context->create<loaders::internal::ConstantLoaderInternal>(
context, context->getNextPublicIndex(), 1.0);
auto resultNodeIndex = context->create<InputNodeInternal>(
context, context->getNextPublicIndex(), tensor->getShape(),
tensor->getDataType(), true, loaderIndex,
(std::string("InitialNode_") +
std::to_string(context->getNextPublicIndex()))
.data());
gradientGraph.mInputNodeIndexes.emplace_back(resultNodeIndex);
return resultNodeIndex;
}
void GraphInternal::mergeEdges(const std::vector<core::internal::Edge>& edges) {
for (auto& edge : edges) {
connect(edge.startNodeIndex, edge.endNodeIndex, edge.mark);
}
}
utils::Index GraphInternal::accumulateOutputNodes(
GraphInternal& gradient, const NodeState* nodeStatePtr,
const std::unordered_map<const NodeState*, utils::Index>&
mapNodeStateToFinalGradientIndex) const {
#ifdef DEBUG
if (nodeStatePtr->output.size() == 0) {
utils::FatalError(utils::ATH_ASSERT,
"Error while accumulateOutputNodes() is working. Output "
"of node state contains 0 states.");
}
#endif
auto context = mContext.lock();
auto addOperationIndex =
context->create<operation::internal::AddOperationInternal>(
context, context->getNextPublicIndex(),
(std::string("AddOperation_") +
std::to_string(context->getNextPublicIndex()))
.data());
auto& shape =
context->getRef<AbstractNodeInternal>(nodeStatePtr->nodeIndex)
.getTensorPtr()
->getShape();
auto zeroLoaderIndex =
context->create<loaders::internal::ConstantLoaderInternal>(
context, context->getNextPublicIndex(), 0.0,
(std::string("ZeroLoaderIndex_") +
std::to_string(context->getNextPublicIndex()))
.data());
auto finalGradientIndex = gradient.create<InputNodeInternal>(
shape, DataType::FLOAT, true, zeroLoaderIndex,
(std::string("ZeroInputNode_") +
std::to_string(context->getNextPublicIndex()))
.data());
for (size_t indexOutputDependence = 0;
indexOutputDependence < nodeStatePtr->output.size();
++indexOutputDependence) {
auto& dependence = nodeStatePtr->output[indexOutputDependence];
auto resNodeStatePtr = &mTraversal.getClusters()[dependence.clusterIndex]
.content[dependence.nodeStateIndex];
auto& abstractNode =
context->getRef<AbstractNodeInternal>(dependence.nodeIndex);
if (abstractNode.getType() == NodeType::DEFAULT) {
auto& node = static_cast<NodeInternal&>(abstractNode);
auto operationPtr = node.getOperationPtr();
auto [newFinalGradientIndex, edges, newInputNodes] =
operationPtr->genDerivative(
nodeStatePtr, resNodeStatePtr, indexOutputDependence,
mapNodeStateToFinalGradientIndex.at(resNodeStatePtr));
auto addNodeIndex = context->create<core::internal::NodeInternal>(
context, context->getNextPublicIndex(), addOperationIndex,
(std::string("AddNodeLinker_") +
std::to_string(context->getNextPublicIndex()))
.data());
gradient.connect(newFinalGradientIndex, addNodeIndex,
operation::AddOperation::LEFT);
gradient.connect(finalGradientIndex, addNodeIndex,
operation::AddOperation::RIGHT);
finalGradientIndex = addNodeIndex;
gradient.mergeEdges(edges);
for (auto newInputNodeIndex : newInputNodes) {
gradient.mInputNodeIndexes.emplace_back(newInputNodeIndex);
}
} else {
// TODO error
}
}
return finalGradientIndex;
}
std::tuple<utils::Index, std::unordered_map<utils::Index, utils::Index>>
GraphInternal::createGradientGraph(utils::Index targetNodeIndex) const {
auto context = mContext.lock();
auto& targetNode = context->getRef<AbstractNodeInternal>(targetNodeIndex);
if (targetNode.getType() != NodeType::DEFAULT) {
utils::FatalError(utils::ATH_BAD_ACCESS, "Target node isn't a functional node.");
return {};
}
auto gradientGraphIndex = context->create<GraphInternal>(
mContext, context->getNextPublicIndex(),
(std::string("GradientGraph_") +
std::to_string(context->getNextPublicIndex()))
.data());
auto& gradientGraph = context->getRef<GraphInternal>(gradientGraphIndex);
std::unordered_map<const NodeState*, utils::Index>
mapNodeStateToFinalGradientIndex;
std::unordered_map<utils::Index, utils::Index> inputNodeChangers;
if (mTraversal.getClusters().size() <= 1) {
return {};
}
utils::Index gradientFinalNodeIndex = 0;
bool targetNodeFound = false;
size_t indexCluster = mTraversal.getClusters().size() - 1;
auto& clusterCollection = mTraversal.getClusters();
for (auto rClusterIterator = clusterCollection.rbegin(); rClusterIterator != clusterCollection.rend(); ++rClusterIterator) {
auto& cluster = *rClusterIterator;
for (const auto& nodeState : cluster.content) {
if (!targetNodeFound) {
if (nodeState.nodeIndex == targetNodeIndex) {
targetNodeFound = true;
gradientFinalNodeIndex = createInitialGradientNode(gradientGraph, &nodeState);
mapNodeStateToFinalGradientIndex[&nodeState] = gradientFinalNodeIndex;
}
} else {
if (nodeState.isWayToFrozen) {
continue;
}
auto nodeStatePtr = &nodeState;
gradientFinalNodeIndex = accumulateOutputNodes(
gradientGraph, nodeStatePtr, mapNodeStateToFinalGradientIndex);
mapNodeStateToFinalGradientIndex[nodeStatePtr] = gradientFinalNodeIndex;
if (indexCluster == 0) {
auto& inputNode = context->getRef<InputNodeInternal>(nodeState.nodeIndex);
if (!inputNode.isFrozen()) {
inputNodeChangers[inputNode.getPublicIndex()] = gradientFinalNodeIndex;
}
}
}
}
--indexCluster;
}
gradientGraph.traverse();
return std::make_tuple(gradientGraphIndex, inputNodeChangers);
}
utils::Index GraphInternal::createWeightChangingGraph(
const std::unordered_map<utils::Index, utils::Index>& mapInputNodes) {
auto context = mContext.lock();
auto weightChangingGraphIndex = context->create<GraphInternal>(
mContext, context->getNextPublicIndex(),
(std::string("WeightChangingGraph_") +
std::to_string(context->getNextPublicIndex()))
.data());
auto& weightChangingGraph =
context->getRef<GraphInternal>(weightChangingGraphIndex);
auto learningRateLoaderIndex =
context->create<loaders::internal::ConstantLoaderInternal>(
context, context->getNextPublicIndex(), -0.01,
(std::string("LearningRateLoader_") +
std::to_string(context->getNextPublicIndex()))
.data()); // TODO give runtime args to graph
auto dummyLoader =
context->create<loaders::internal::DummyLoaderInternal>(
context, context->getNextPublicIndex(),
(std::string("DummyLoader_") +
std::to_string(context->getNextPublicIndex()))
.data());
auto multiplyOperation =
context->create<operation::internal::MulOperationInternal>(
context, context->getNextPublicIndex(),
(std::string("MultiplyOperation_") +
std::to_string(context->getNextPublicIndex()))
.data());
auto addOperation =
context->create<operation::internal::AddOperationInternal>(
context, context->getNextPublicIndex(),
(std::string("AddOperation_") +
std::to_string(context->getNextPublicIndex()))
.data());
for (auto& edge : mapInputNodes) { /// grad - second, initial graph - first
auto gradientFinalNodeIndex = edge.second;
auto sourceGraphInputNodeIndex = edge.first;
auto& sourceGraphInputNode =
context->getRef<internal::AbstractNodeInternal>(
sourceGraphInputNodeIndex);
auto& gradientFinalNode =
context->getRef<internal::AbstractNodeInternal>(gradientFinalNodeIndex);
auto& gradientShape = gradientFinalNode.getTensorPtr()->getShape();
auto gradientDataType = gradientFinalNode.getTensorPtr()->getDataType();
auto dummyNodeIndex = context->create<InputNodeInternal>(context, context->getNextPublicIndex(), gradientShape, gradientDataType, true, dummyLoader, (std::string("DummyNodeGradValueHolder_") +
std::to_string(context->getNextPublicIndex()))
.data());
auto& dummyNode = context->getRef<AbstractNodeInternal>(dummyNodeIndex);
dummyNode.setTensorIndex(gradientFinalNode.getTensorIndex());
auto learningRateHolderNodeIndex = context->create<InputNodeInternal>(
context, context->getNextPublicIndex(), gradientShape, gradientDataType,
true, learningRateLoaderIndex,
(std::string("LearningRateHolderNode_") +
std::to_string(context->getNextPublicIndex()))
.data());
weightChangingGraph.mInputNodeIndexes.emplace_back(dummyNodeIndex);
weightChangingGraph.mInputNodeIndexes.emplace_back(learningRateHolderNodeIndex);
auto multiplyNodeIndex = context->create<NodeInternal>(
context, context->getNextPublicIndex(), multiplyOperation,
(std::string("LearningRateMultiplyNode_") +
std::to_string(context->getNextPublicIndex()))
.data());
weightChangingGraph.connect(dummyNodeIndex, multiplyNodeIndex,
operation::MulOperation::LEFT);
weightChangingGraph.connect(learningRateHolderNodeIndex, multiplyNodeIndex,
operation::MulOperation::RIGHT);
auto sourceGraphInputNodeHolderIndex = context->create<InputNodeInternal>(
context, context->getNextPublicIndex(), gradientShape, gradientDataType,
true, dummyLoader,
(std::string("SourceHolderNode_") +
std::to_string(context->getNextPublicIndex()))
.data());
auto& sourceGraphInputNodeHolder = context->getRef<AbstractNodeInternal>(sourceGraphInputNodeHolderIndex);
sourceGraphInputNodeHolder.setTensorIndex(sourceGraphInputNode.getTensorIndex());
weightChangingGraph.mInputNodeIndexes.emplace_back(sourceGraphInputNodeHolderIndex);
auto addNodeIndex = context->create<NodeInternal>(
context, context->getNextPublicIndex(), addOperation,
(std::string("SourceNodeChanger_") +
std::to_string(context->getNextPublicIndex()))
.data());
auto& addNode = context->getRef<NodeInternal>(addNodeIndex);
addNode.setTensorIndex(sourceGraphInputNode.getTensorIndex());
weightChangingGraph.connect(multiplyNodeIndex, addNodeIndex,
operation::AddOperation::LEFT);
weightChangingGraph.connect(sourceGraphInputNodeHolderIndex,
addNodeIndex,
operation::AddOperation::RIGHT);
}
weightChangingGraph.traverse();
return weightChangingGraphIndex;
}
std::tuple<utils::Index, utils::Index> GraphInternal::getGradient(utils::Index targetNodeIndex) {
traverse();
auto [gradientCalculatingGraphIndex, mapInputNodes] = createGradientGraph(targetNodeIndex);
auto weightChangingGraphIndex = createWeightChangingGraph(mapInputNodes);
return std::make_tuple(gradientCalculatingGraphIndex,
weightChangingGraphIndex);
}
} // namespace polarai::core::internal
| 44.030864
| 196
| 0.672415
|
alexbatashev
|
2a1d93449690fe46cc10bdc1c70c04897ee65cd5
| 351
|
hpp
|
C++
|
include/Client/Vector.hpp
|
semper24/R-Type
|
b91184d656ffcec39b0a43e7a42c1a1ecd236c9b
|
[
"MIT"
] | null | null | null |
include/Client/Vector.hpp
|
semper24/R-Type
|
b91184d656ffcec39b0a43e7a42c1a1ecd236c9b
|
[
"MIT"
] | null | null | null |
include/Client/Vector.hpp
|
semper24/R-Type
|
b91184d656ffcec39b0a43e7a42c1a1ecd236c9b
|
[
"MIT"
] | null | null | null |
/*
** EPITECH PROJECT, 2019
** OOP_arcade_2019
** File description:
** Vector.hpp
*/
#ifndef _VECTOR_HPP_
# define _VECTOR_HPP_
struct posVector {
posVector() = default;
posVector(const posVector& other) = default;
posVector& operator=(const posVector& other) = default;
~posVector() = default;
float x;
float y;
};
#endif
| 15.954545
| 59
| 0.669516
|
semper24
|
2a204353dfa4eebda8b2d6a97be2c9cffc287f6f
| 1,331
|
cpp
|
C++
|
linux/Chess/Player.cpp
|
bricsi0000000000000/Chess
|
f1d93153bc7d2f25a117cdc81c69ac23b6407f87
|
[
"MIT"
] | null | null | null |
linux/Chess/Player.cpp
|
bricsi0000000000000/Chess
|
f1d93153bc7d2f25a117cdc81c69ac23b6407f87
|
[
"MIT"
] | null | null | null |
linux/Chess/Player.cpp
|
bricsi0000000000000/Chess
|
f1d93153bc7d2f25a117cdc81c69ac23b6407f87
|
[
"MIT"
] | null | null | null |
#include "Player.h"
Player::Player(std::string name, Color color, bool is_bot) : name(name), points(0), color(color), is_bot(is_bot) {}
std::string Player::GetName() {
return name;
}
int Player::GetPoints() {
return points;
}
void Player::AddPoints(int point) {
points += point;
}
Color Player::GetColor() {
return color;
}
std::vector<std::shared_ptr<Piece>> Player::GetOffPieces() {
return off_pieces;
}
void Player::AddOffPiece(std::shared_ptr<Piece> piece) {
off_pieces.push_back(piece);
}
void Player::RemoveOffPiece(std::shared_ptr<Piece> piece) {
for (int i = 0; i < off_pieces.size(); i++) {
if (off_pieces[i]->GetPosition()->x == piece->GetPosition()->x && off_pieces[i]->GetPosition()->y == piece->GetPosition()->y) {
off_pieces.erase(off_pieces.begin() + i);
}
}
}
void Player::ClearOffPieces() {
off_pieces.clear();
}
bool Player::IsBot() {
return is_bot;
}
std::string Player::GetStepFrom() {
return step_from;
}
std::string Player::GetStepTo() {
return step_to;
}
void Player::SetStepFrom(std::string position) {
step_from = position;
}
void Player::SetStepTo(std::string position) {
step_to = position;
}
std::shared_ptr<Piece> Player::GetStepPiece() {
return step_piece;
}
void Player::SetStepPiece(std::shared_ptr<Piece> piece) {
step_piece = piece;
}
| 19.573529
| 131
| 0.676935
|
bricsi0000000000000
|
2a20c70f99f9eb70be02ee9758619655be7e7d70
| 14,820
|
cpp
|
C++
|
sources/Engine/Modules/Graphics/OpenGL/GLGraphicsContext.cpp
|
n-paukov/swengine
|
ca7441f238e8834efff5d2b61b079627824bf3e4
|
[
"MIT"
] | 22
|
2017-07-26T17:42:56.000Z
|
2022-03-21T22:12:52.000Z
|
sources/Engine/Modules/Graphics/OpenGL/GLGraphicsContext.cpp
|
n-paukov/swengine
|
ca7441f238e8834efff5d2b61b079627824bf3e4
|
[
"MIT"
] | 50
|
2017-08-02T19:37:48.000Z
|
2020-07-24T21:10:38.000Z
|
sources/Engine/Modules/Graphics/OpenGL/GLGraphicsContext.cpp
|
n-paukov/swengine
|
ca7441f238e8834efff5d2b61b079627824bf3e4
|
[
"MIT"
] | 4
|
2018-08-20T08:12:48.000Z
|
2020-07-19T14:10:05.000Z
|
#include "precompiled.h"
#pragma hdrstop
#include "GLGraphicsContext.h"
#include <spdlog/spdlog.h>
#include "Modules/Graphics/GraphicsSystem/FrameStats.h"
#include "Exceptions/exceptions.h"
#include "options.h"
GLGraphicsContext::GLGraphicsContext(SDL_Window* window)
: m_window(window)
{
spdlog::info("Creating OpenGL context");
m_sdlGLContext.m_glContext = SDL_GL_CreateContext(m_window);
if (m_sdlGLContext.m_glContext == nullptr) {
THROW_EXCEPTION(EngineRuntimeException, std::string(SDL_GetError()));
}
if (gl3wInit()) {
THROW_EXCEPTION(EngineRuntimeException, "Failed to initialize OpenGL");
}
if (!gl3wIsSupported(4, 5)) {
THROW_EXCEPTION(EngineRuntimeException, "Failed to load OpenGL functions");
}
glEnable(GL_DEBUG_OUTPUT);
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
glDebugMessageCallback(reinterpret_cast<GLDEBUGPROCARB>(&debugOutputCallback), this);
int bufferWidth, bufferHeight;
SDL_GetWindowSize(m_window, &bufferWidth, &bufferHeight);
m_defaultFramebuffer = std::unique_ptr<GLFramebuffer>(new GLFramebuffer(bufferWidth, bufferHeight));
m_ndcTexturedQuad = std::make_unique<GLGeometryStore>(
std::vector<VertexPos3Norm3UV>{
{{-1.0f, 1.0f, 1.0f}, glm::vec3(), {0.0f, 1.0f}},
{{-1.0f, -1.0f, 1.0f}, glm::vec3(), {0.0f, 0.0f}},
{{1.0f, 1.0f, 1.0f}, glm::vec3(), {1.0f, 1.0f}},
{{1.0f, -1.0f, 1.0f}, glm::vec3(), {1.0f, 0.0f}},
}, std::vector<std::uint16_t>{0, 2, 1, 1, 2, 3});
int framebufferWidth = bufferWidth;
int framebufferHeight = bufferHeight;
std::shared_ptr<GLTexture> mrtAlbedo = std::make_shared<GLTexture>(GLTextureType::Texture2D,
framebufferWidth,
framebufferHeight,
GLTextureInternalFormat::RGBA8);
std::shared_ptr<GLTexture> mrtNormals = std::make_shared<GLTexture>(GLTextureType::Texture2D,
framebufferWidth,
framebufferHeight,
GLTextureInternalFormat::RGB16F);
std::shared_ptr<GLTexture> mrtPositions = std::make_shared<GLTexture>(GLTextureType::Texture2D,
framebufferWidth,
framebufferHeight,
GLTextureInternalFormat::RGB32F);
std::shared_ptr<GLTexture> depthStencil = std::make_shared<GLTexture>(GLTextureType::Texture2D,
framebufferWidth,
framebufferHeight,
GLTextureInternalFormat::Depth24Stencil8);
m_deferredFramebuffer = std::make_unique<GLFramebuffer>(framebufferWidth,
framebufferHeight,
std::vector{mrtAlbedo, mrtNormals, mrtPositions},
depthStencil);
std::shared_ptr<GLTexture> forwardAlbedo = std::make_shared<GLTexture>(GLTextureType::Texture2D,
framebufferWidth,
framebufferHeight,
GLTextureInternalFormat::RGBA8);
m_forwardFramebuffer = std::make_unique<GLFramebuffer>(framebufferWidth, framebufferHeight,
std::vector{forwardAlbedo}, depthStencil);
m_sceneTransformationBuffer = std::make_unique<GLUniformBuffer<SceneTransformation>>();
m_sceneTransformationBuffer->attachToBindingEntry(0);
m_guiTransformationBuffer = std::make_unique<GLUniformBuffer<GUITransformation>>();
m_guiTransformationBuffer->attachToBindingEntry(1);
spdlog::info("OpenGL context is created");
}
GLGraphicsContext::~GLGraphicsContext()
{
}
void GLGraphicsContext::swapBuffers()
{
SDL_GL_SwapWindow(m_window);
}
void GLGraphicsContext::setDepthTestMode(DepthTestMode mode)
{
switch (mode) {
case DepthTestMode::Disabled:
glDisable(GL_DEPTH_TEST);
break;
case DepthTestMode::LessOrEqual:
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
break;
case DepthTestMode::Less:
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
break;
case DepthTestMode::NotEqual:
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_NOTEQUAL);
default:
break;
}
applyContextChange();
}
void GLGraphicsContext::setFaceCullingMode(FaceCullingMode mode)
{
switch (mode) {
case FaceCullingMode::Disabled:
glDisable(GL_CULL_FACE);
break;
case FaceCullingMode::Back:
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
break;
case FaceCullingMode::Front:
glEnable(GL_CULL_FACE);
glCullFace(GL_FRONT);
break;
default:
break;
}
applyContextChange();
}
void GLGraphicsContext::setPolygonFillingMode(PolygonFillingMode mode)
{
switch (mode) {
case PolygonFillingMode::Fill:
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
break;
case PolygonFillingMode::Wireframe:
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
break;
default:
break;
}
applyContextChange();
}
void GLGraphicsContext::setBlendingMode(BlendingMode mode)
{
switch (mode) {
case BlendingMode::Disabled:
glDisable(GL_BLEND);
break;
case BlendingMode::Alpha_OneMinusAlpha:
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
break;
default:
break;
}
applyContextChange();
}
void GLGraphicsContext::setDepthWritingMode(DepthWritingMode mode)
{
switch (mode) {
case DepthWritingMode::Disabled:
glDepthMask(GL_FALSE);
break;
case DepthWritingMode::Enabled:
glDepthMask(GL_TRUE);
break;
default:
break;
}
applyContextChange();
}
GLGeometryStore& GLGraphicsContext::getNDCTexturedQuad() const
{
return *m_ndcTexturedQuad.get();
}
void GLGraphicsContext::applyContextChange()
{
resetMaterial();
}
void GLGraphicsContext::resetMaterial()
{
m_currentMaterial = nullptr;
}
void APIENTRY GLGraphicsContext::debugOutputCallback(GLenum source,
GLenum type,
GLuint id,
GLenum severity,
GLsizei length,
const GLchar* message,
GLvoid* userParam)
{
ARG_UNUSED(source);
ARG_UNUSED(length);
ARG_UNUSED(userParam);
// Skip some debug information from GPU
if constexpr (!LOG_GPU_ADDITIONAL_DEBUG_INFO_MESSAGES) {
if (id == 131185) {
return;
}
}
std::string debugMessage = "[OpenGL] ";
switch (type) {
case GL_DEBUG_TYPE_ERROR:
debugMessage += "error";
break;
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:
debugMessage += "deprecated behavior";
break;
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:
debugMessage += "undefined behavior";
break;
case GL_DEBUG_TYPE_PORTABILITY:
debugMessage += "portability";
break;
case GL_DEBUG_TYPE_PERFORMANCE:
debugMessage += "performance";
break;
case GL_DEBUG_TYPE_OTHER:
debugMessage += "common";
break;
default:
debugMessage += fmt::format("Unknown ({})", type);
break;
}
debugMessage += " (" + std::to_string(id) + ", ";
switch (severity) {
case GL_DEBUG_SEVERITY_LOW:
debugMessage += "low";
break;
case GL_DEBUG_SEVERITY_MEDIUM:
debugMessage += "medium";
break;
case GL_DEBUG_SEVERITY_HIGH:
debugMessage += "high";
break;
default:
debugMessage += fmt::format("Unknown ({})", severity);
break;
}
debugMessage += ") " + std::string(message);
//GLGraphicsContext* context = static_cast<GLGraphicsContext*>(userParam);
switch (type) {
case GL_DEBUG_TYPE_ERROR:
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:
case GL_DEBUG_TYPE_PORTABILITY:
spdlog::error(debugMessage);
break;
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:
case GL_DEBUG_TYPE_PERFORMANCE:
spdlog::warn(debugMessage);
break;
case GL_DEBUG_TYPE_OTHER:
spdlog::debug(debugMessage);
break;
default:
spdlog::debug(debugMessage);
break;
}
}
void GLGraphicsContext::setupScissorsTest(ScissorsTestMode mode)
{
switch (mode) {
case ScissorsTestMode::Disabled:
glDisable(GL_SCISSOR_TEST);
break;
case ScissorsTestMode::Enabled:
glEnable(GL_SCISSOR_TEST);
break;
default:
break;
}
applyContextChange();
}
void GLGraphicsContext::setupGraphicsScene(std::shared_ptr<GraphicsScene> graphicsScene)
{
m_graphicsScene = std::move(graphicsScene);
}
void GLGraphicsContext::scheduleRenderTask(const RenderTask& task)
{
m_renderingQueues[static_cast<size_t>(task.material->getRenderingStage())].push_back(task);
}
void GLGraphicsContext::executeRenderTasks()
{
// TODO: get rid of buffers clearing and copying as possible
// For example, use depth swap trick to avoid depth buffer clearing
// Setup scene state uniform buffers
std::shared_ptr<Camera> activeCamera = m_graphicsScene->getActiveCamera();
if (activeCamera) {
m_sceneTransformationBuffer->getBufferData().view = m_graphicsScene->getActiveCamera()->getViewMatrix();
m_sceneTransformationBuffer->getBufferData().projection = m_graphicsScene->getActiveCamera()->getProjectionMatrix();
}
else {
m_sceneTransformationBuffer->getBufferData().view = glm::identity<glm::mat4>();
m_sceneTransformationBuffer->getBufferData().projection = glm::identity<glm::mat4>();
}
m_sceneTransformationBuffer->synchronizeWithGpu();
m_guiTransformationBuffer->getBufferData().projection = m_guiProjectionMatrix;
m_guiTransformationBuffer->synchronizeWithGpu();
// Render current frame
glDisable(GL_SCISSOR_TEST);
glDepthMask(GL_TRUE);
m_deferredFramebuffer->clearColor({0.0f, 0.0f, 0.0f, 0.0f}, 0);
m_deferredFramebuffer->clearColor({0.0f, 0.0f, 0.0f, 0.0f}, 1);
m_deferredFramebuffer->clearColor({0.0f, 0.0f, 0.0f, 0.0f}, 2);
m_deferredFramebuffer->clearDepthStencil(1.0f, 0);
glBindFramebuffer(GL_FRAMEBUFFER, m_deferredFramebuffer->getGLHandle());
executeRenderingStageQueue(RenderingStage::Deferred);
GLShadersPipeline* accumulationPipeline = &m_deferredAccumulationMaterial->getShadersPipeline();
GLShader* accumulationFragmentShader = accumulationPipeline->getShader(ShaderType::Fragment);
const GLFramebuffer& deferredFramebuffer = *m_deferredFramebuffer;
accumulationFragmentShader->setParameter("gBuffer.albedo",
*deferredFramebuffer.getColorComponent(0), 0);
accumulationFragmentShader->setParameter("gBuffer.normals",
*deferredFramebuffer.getColorComponent(1), 1);
accumulationFragmentShader->setParameter("gBuffer.positions",
*deferredFramebuffer.getColorComponent(2), 2);
glDisable(GL_SCISSOR_TEST);
glBindFramebuffer(GL_FRAMEBUFFER, m_forwardFramebuffer->getGLHandle());
glBindProgramPipeline(accumulationPipeline->m_programPipeline);
applyGpuState(m_deferredAccumulationMaterial->getGpuStateParameters());
m_deferredAccumulationMaterial->getGLParametersBinder()->bindParameters(*accumulationPipeline);
getNDCTexturedQuad().drawRange(0, 6, GL_TRIANGLES);
executeRenderingStageQueue(RenderingStage::Forward);
executeRenderingStageQueue(RenderingStage::ForwardDebug);
executeRenderingStageQueue(RenderingStage::ForwardEnvironment);
executeRenderingStageQueue(RenderingStage::PostProcess);
executeRenderingStageQueue(RenderingStage::GUI);
// m_defaultFramebuffer->clearColor({0.0f, 0.0f, 0.0f, 1.0f});
// m_defaultFramebuffer->clearDepthStencil(0.0f, 0);
glDisable(GL_SCISSOR_TEST);
m_forwardFramebuffer->copyColor(*m_defaultFramebuffer);
m_forwardFramebuffer->copyDepthStencil(*m_defaultFramebuffer);
}
void GLGraphicsContext::setupDeferredAccumulationMaterial(std::shared_ptr<GLShadersPipeline> pipeline)
{
GpuStateParameters gpuState;
gpuState.setBlendingMode(BlendingMode::Disabled);
gpuState.setDepthTestMode(DepthTestMode::NotEqual);
gpuState.setDepthWritingMode(DepthWritingMode::Disabled);
gpuState.setFaceCullingMode(FaceCullingMode::Disabled);
gpuState.setPolygonFillingMode(PolygonFillingMode::Fill);
m_deferredAccumulationMaterial = std::make_unique<GLMaterial>(RenderingStage::Deferred,
std::move(pipeline),
gpuState,
std::make_unique<ShadingParametersGenericSet>());
}
void GLGraphicsContext::applyGpuState(const GpuStateParameters& gpuState)
{
setBlendingMode(gpuState.getBlendingMode());
setDepthTestMode(gpuState.getDepthTestMode());
setFaceCullingMode(gpuState.getFaceCullingMode());
setPolygonFillingMode(gpuState.getPolygonFillingMode());
setDepthWritingMode(gpuState.getDepthWritingMode());
setupScissorsTest(gpuState.getScissorsTestMode());
}
void GLGraphicsContext::executeRenderingStageQueue(RenderingStage stage)
{
auto& queue = m_renderingQueues[static_cast<size_t>(stage)];
if (queue.empty()) {
return;
}
applyGpuState(queue.begin()->material->getGpuStateParameters());
for (const auto& renderingTask : queue) {
GLShadersPipeline& shadersPipeline = renderingTask.material->getShadersPipeline();
glBindProgramPipeline(shadersPipeline.m_programPipeline);
const auto& shadingParametersBinder = renderingTask.material->getGLParametersBinder();
GLShader* vertexShader = shadersPipeline.getShader(ShaderType::Vertex);
if (&shadersPipeline != m_currentShadersPipeline) {
m_currentShadersPipeline = &shadersPipeline;
}
if (renderingTask.matrixPalette != nullptr && vertexShader->hasParameter("animation.palette[0]")) {
vertexShader->setArrayParameter("animation.palette",
renderingTask.matrixPalette, renderingTask.mesh->getSkeleton()->getBonesCount());
}
shadingParametersBinder->bindParameters(shadersPipeline);
if (vertexShader->hasParameter("transform.local")) {
vertexShader->setParameter("transform.local", *renderingTask.transform);
}
if (renderingTask.material->getGpuStateParameters().getScissorsTestMode() == ScissorsTestMode::Enabled) {
glScissor(renderingTask.scissorsRect.getOriginX(),
m_defaultFramebuffer->getHeight() - renderingTask.scissorsRect.getOriginY()
- renderingTask.scissorsRect.getHeight(),
renderingTask.scissorsRect.getWidth(), renderingTask.scissorsRect.getHeight());
}
renderingTask.mesh->getGeometryStore()->drawRange(
renderingTask.mesh->getSubMeshIndicesOffset(renderingTask.subMeshIndex),
renderingTask.mesh->getSubMeshIndicesCount(renderingTask.subMeshIndex),
renderingTask.primitivesType);
}
m_renderingQueues[static_cast<size_t>(stage)].clear();
}
int GLGraphicsContext::getViewportWidth() const
{
return m_defaultFramebuffer->getWidth();
}
int GLGraphicsContext::getViewportHeight() const
{
return m_defaultFramebuffer->getHeight();
}
void GLGraphicsContext::setGUIProjectionMatrix(const glm::mat4& projection)
{
m_guiProjectionMatrix = projection;
}
const glm::mat4& GLGraphicsContext::getGUIProjectionMatrix() const
{
return m_guiProjectionMatrix;
}
void GLGraphicsContext::unloadResources()
{
m_deferredAccumulationMaterial.reset();
m_defaultFramebuffer.reset();
m_ndcTexturedQuad.reset();
m_deferredFramebuffer.reset();
m_forwardFramebuffer.reset();
m_deferredAccumulationMaterial.reset();
m_sceneTransformationBuffer.reset();
m_guiTransformationBuffer.reset();
}
SDLGLContext::~SDLGLContext()
{
SDL_GL_DeleteContext(m_glContext);
}
| 28.33652
| 120
| 0.741768
|
n-paukov
|
2a264dbac30dca8a07343598e64714d01853f644
| 2,516
|
cpp
|
C++
|
Sources/Core/cpp/NdxDataStorage/IndexStorage_test.cpp
|
elzin/SentimentAnalysisService
|
41fba2ef49746473535196e89a5e49250439fd83
|
[
"MIT"
] | 2
|
2021-07-07T19:39:11.000Z
|
2021-12-02T15:54:15.000Z
|
Sources/Core/cpp/NdxDataStorage/IndexStorage_test.cpp
|
elzin/SentimentAnalysisService
|
41fba2ef49746473535196e89a5e49250439fd83
|
[
"MIT"
] | null | null | null |
Sources/Core/cpp/NdxDataStorage/IndexStorage_test.cpp
|
elzin/SentimentAnalysisService
|
41fba2ef49746473535196e89a5e49250439fd83
|
[
"MIT"
] | 1
|
2021-12-01T17:48:20.000Z
|
2021-12-01T17:48:20.000Z
|
#include "StdAfx.h"
#ifdef _SS_UNITTESTS
#include ".\indexstorage_test.h"
#include ".\test_const.h"
#include ".\console.h"
#include ".\index_storage.h"
#include ".\data_storages_factory.h"
CPPUNIT_TEST_SUITE_REGISTRATION(SS::UnitTests::NdxSE::NdxDataStorage::CIndexStorage_test);
typedef HRESULT (*CREATE_INSTANCE)(const GUID* pGuid, void** ppBase);
namespace SS
{
namespace UnitTests
{
namespace NdxSE
{
namespace NdxDataStorage
{
using namespace SS::Core::NdxSE::NdxDataStorage;
using namespace SS::Interface::Core::NdxSE::NdxDataStorage;
//--------------------------------------------------------------------//
void CIndexStorage_test::Test(void)
{
CPPUNIT_ASSERT(CreateLoadManager());
CDataStorageFactory* pDataStorageFactory=new CDataStorageFactory();
pDataStorageFactory->SetLoadManager(m_pLoadManager);
wchar_t path[MAX_PATH];
::GetCurrentDirectoryW(MAX_PATH, (LPWSTR)path);
wcscat(path, L"\\UT\\");
INdxStorage* pNdxStorage=pDataStorageFactory->CreateNdxStorage();
pNdxStorage->Create(L"index_str", L".ndx");
SNdxLevelInfo NdxLevelInfo;
NdxLevelInfo.m_ucLevelNumber=0;
NdxLevelInfo.m_IndexCoordinateType=SNdxLevelInfo::ictSentenceAbsNumber;
NdxLevelInfo.m_eControlType=SNdxLevelInfo::lctUndefined;
NdxLevelInfo.m_eControlByType=SNdxLevelInfo::lctUndefined;
pNdxStorage->AddLevelInfo(&NdxLevelInfo);
NdxLevelInfo.m_ucLevelNumber++;
pNdxStorage->AddLevelInfo(&NdxLevelInfo);
NdxLevelInfo.m_ucLevelNumber++;
pNdxStorage->AddLevelInfo(&NdxLevelInfo);
NdxLevelInfo.m_ucLevelNumber++;
pNdxStorage->AddLevelInfo(&NdxLevelInfo);
pNdxStorage->Open(path);
pNdxStorage->Close();
pNdxStorage->Release();
delete pDataStorageFactory;
DeleteLoadManager();
}
bool CIndexStorage_test::CreateLoadManager(void)
{
m_pLoadManager=NULL;
wchar_t path[MAX_PATH];
::GetCurrentDirectoryW(MAX_PATH, (LPWSTR)path);
wcscat(path, L"\\LoadManager.dll");
m_hLoadManager=::LoadLibraryW(path);
CREATE_INSTANCE pCreateInstance=(CREATE_INSTANCE)GetProcAddress(m_hLoadManager, "CreateInstance");
if(pCreateInstance==NULL){
wprintf(L"LoadManager entry point not found, error %u\n", GetLastError());
return 0;
}
const GUID Guid=CLSID_LoadManager;
(*pCreateInstance)(&Guid, (void**)&m_pLoadManager);
return m_pLoadManager?true:false;
}
void CIndexStorage_test::DeleteLoadManager(void)
{
if(m_pLoadManager) delete m_pLoadManager;
::FreeLibrary(m_hLoadManager);
}
//--------------------------------------------------------------------//
}
}
}
}
#endif //_SS_UNITTESTS
| 23.514019
| 99
| 0.736089
|
elzin
|
2a26cb3bbb819a3fe4e2ef314cb4739c7b0cc715
| 9,142
|
cpp
|
C++
|
Source/AccelByteUe4Sdk/Private/Api/AccelByteItemApi.cpp
|
leowind/accelbyte-unreal-sdk-plugin
|
73a7bf289abbba8141767eb16005aaf8293f8a63
|
[
"MIT"
] | null | null | null |
Source/AccelByteUe4Sdk/Private/Api/AccelByteItemApi.cpp
|
leowind/accelbyte-unreal-sdk-plugin
|
73a7bf289abbba8141767eb16005aaf8293f8a63
|
[
"MIT"
] | null | null | null |
Source/AccelByteUe4Sdk/Private/Api/AccelByteItemApi.cpp
|
leowind/accelbyte-unreal-sdk-plugin
|
73a7bf289abbba8141767eb16005aaf8293f8a63
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2018 - 2019 AccelByte Inc. All Rights Reserved.
// This is licensed software from AccelByte Inc, for limitations
// and restrictions contact your company contract manager.
#include "Api/AccelByteItemApi.h"
#include "Core/AccelByteError.h"
#include "JsonUtilities.h"
#include "Core/AccelByteRegistry.h"
#include "Core/AccelByteReport.h"
#include "Core/AccelByteHttpRetryScheduler.h"
#include "Core/AccelByteSettings.h"
namespace AccelByte
{
namespace Api
{
Item::Item(const AccelByte::Credentials& Credentials, const AccelByte::Settings& Settings) : Credentials(Credentials), Settings(Settings){}
Item::~Item(){}
FString EAccelByteItemTypeToString(const EAccelByteItemType& EnumValue) {
const UEnum* EnumPtr = FindObject<UEnum>(ANY_PACKAGE, TEXT("EAccelByteItemType"), true);
if (!EnumPtr) return "Invalid";
return EnumPtr->GetNameStringByValue((int64)EnumValue);
}
FString EAccelByteItemStatusToString(const EAccelByteItemStatus& EnumValue) {
const UEnum* EnumPtr = FindObject<UEnum>(ANY_PACKAGE, TEXT("EAccelByteItemStatus"), true);
if (!EnumPtr) return "Invalid";
return EnumPtr->GetNameStringByValue((int64)EnumValue);
}
FString EAccelByteAppTypeToString(const EAccelByteAppType& EnumValue)
{
const UEnum* EnumPtr = FindObject<UEnum>(ANY_PACKAGE, TEXT("EAccelByteAppType"), true);
if (!EnumPtr) return "Invalid";
return EnumPtr->GetNameStringByValue((int64)EnumValue);
}
void Item::GetItemById(const FString& ItemId, const FString& Language, const FString& Region, const THandler<FAccelByteModelsPopulatedItemInfo>& OnSuccess, const FErrorHandler& OnError)
{
FReport::Log(FString(__FUNCTION__));
FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken());
FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/items/%s/locale"), *Settings.PlatformServerUrl, *Credentials.GetNamespace(), *ItemId);
if (!Region.IsEmpty() || !Language.IsEmpty())
{
Url.Append(FString::Printf(TEXT("?")));
if (!Region.IsEmpty())
{
Url.Append(FString::Printf(TEXT("region=%s"), *Region));
if (!Language.IsEmpty())
{
Url.Append(FString::Printf(TEXT("&language=%s"), *Language));
}
}
else if (!Language.IsEmpty())
{
Url.Append(FString::Printf(TEXT("language=%s"), *Language));
}
}
FString Verb = TEXT("GET");
FString ContentType = TEXT("application/json");
FString Accept = TEXT("application/json");
FString Content;
FHttpRequestPtr Request = FHttpModule::Get().CreateRequest();
Request->SetURL(Url);
Request->SetHeader(TEXT("Authorization"), Authorization);
Request->SetVerb(Verb);
Request->SetHeader(TEXT("Content-Type"), ContentType);
Request->SetHeader(TEXT("Accept"), Accept);
Request->SetContentAsString(Content);
FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds());
}
void Item::GetItemByAppId(const FString& AppId, const FString& Language, const FString& Region, const THandler<FAccelByteModelsItemInfo>& OnSuccess, const FErrorHandler& OnError)
{
FReport::Log(FString(__FUNCTION__));
FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken());
FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/items/byAppId?appId=%s"), *Settings.PlatformServerUrl, *Settings.PublisherNamespace, *AppId);
if (!Region.IsEmpty() || !Language.IsEmpty())
{
Url.Append(FString::Printf(TEXT("&")));
if (!Region.IsEmpty())
{
Url.Append(FString::Printf(TEXT("region=%s"), *Region));
if (!Language.IsEmpty())
{
Url.Append(FString::Printf(TEXT("&language=%s"), *Language));
}
}
else if (!Language.IsEmpty())
{
Url.Append(FString::Printf(TEXT("language=%s"), *Language));
}
}
FString Verb = TEXT("GET");
FString ContentType = TEXT("application/json");
FString Accept = TEXT("application/json");
FString Content;
FHttpRequestPtr Request = FHttpModule::Get().CreateRequest();
Request->SetURL(Url);
Request->SetVerb(Verb);
Request->SetHeader(TEXT("Content-Type"), ContentType);
Request->SetHeader(TEXT("Accept"), Accept);
Request->SetContentAsString(Content);
FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds());
}
void Item::GetItemsByCriteria(const FAccelByteModelsItemCriteria& ItemCriteria, const int32& Offset, const int32& Limit, const THandler<FAccelByteModelsItemPagingSlicedResult>& OnSuccess, const FErrorHandler& OnError)
{
FReport::Log(FString(__FUNCTION__));
FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken());
FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/items/byCriteria"), *Settings.PlatformServerUrl, *Settings.Namespace);
bool bIsNotFirst = false;
if (!ItemCriteria.CategoryPath.IsEmpty())
{
bIsNotFirst = true; Url.Append("?");
Url.Append(FString::Printf(TEXT("categoryPath=%s"), *FGenericPlatformHttp::UrlEncode(ItemCriteria.CategoryPath)));
}
if (!ItemCriteria.Region.IsEmpty())
{
if (bIsNotFirst)
{
Url.Append("&");
}
else
{
bIsNotFirst = true; Url.Append("?");
}
Url.Append(FString::Printf(TEXT("region=%s"), *ItemCriteria.Region));
}
if (!ItemCriteria.Language.IsEmpty())
{
if (bIsNotFirst)
{
Url.Append("&");
}
else
{
bIsNotFirst = true; Url.Append("?");
}
Url.Append(FString::Printf(TEXT("language=%s"), *ItemCriteria.Language));
}
if (ItemCriteria.ItemType != EAccelByteItemType::NONE)
{
if (bIsNotFirst)
{
Url.Append("&");
}
else
{
bIsNotFirst = true; Url.Append("?");
}
Url.Append(FString::Printf(TEXT("itemType=%s"), *EAccelByteItemTypeToString(ItemCriteria.ItemType)));
}
if (ItemCriteria.AppType != EAccelByteAppType::NONE)
{
if (bIsNotFirst)
{
Url.Append("&");
}
else
{
bIsNotFirst = true; Url.Append("?");
}
Url.Append(FString::Printf(TEXT("appType=%s"), *EAccelByteAppTypeToString(ItemCriteria.AppType)));
}
if (ItemCriteria.Tags.Num() > 0)
{
if (bIsNotFirst)
{
Url.Append("&");
}
else
{
bIsNotFirst = true; Url.Append("?");
}
for (int i = 0; i < ItemCriteria.Tags.Num(); i++)
{
Url.Append((i == 0) ? TEXT("tags=") : TEXT(",")).Append(ItemCriteria.Tags[i]);
}
}
if (ItemCriteria.Features.Num() > 0)
{
if (bIsNotFirst)
{
Url.Append("&");
}
else
{
bIsNotFirst = true; Url.Append("?");
}
for (int i = 0; i < ItemCriteria.Features.Num(); i++)
{
Url.Append((i == 0) ? TEXT("features=") : TEXT(",")).Append(ItemCriteria.Features[i]);
}
}
if (Offset > 0)
{
if (bIsNotFirst)
{
Url.Append("&");
}
else
{
bIsNotFirst = true; Url.Append("?");
}
Url.Append(FString::Printf(TEXT("offset=%d"), Offset));
}
if (Limit > 0)
{
if (bIsNotFirst)
{
Url.Append("&");
}
else
{
bIsNotFirst = true; Url.Append("?");
}
Url.Append(FString::Printf(TEXT("limit=%d"), Limit));
}
FString Verb = TEXT("GET");
FString ContentType = TEXT("application/json");
FString Accept = TEXT("application/json");
FString Content = TEXT("");
FHttpRequestPtr Request = FHttpModule::Get().CreateRequest();
Request->SetURL(Url);
Request->SetHeader(TEXT("Authorization"), Authorization);
Request->SetVerb(Verb);
Request->SetHeader(TEXT("Content-Type"), ContentType);
Request->SetHeader(TEXT("Accept"), Accept);
Request->SetContentAsString(Content);
FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds());
}
void Item::SearchItem(const FString& Language, const FString& Keyword, const int32& Offset, const int32& Limit, const FString& Region, const THandler<FAccelByteModelsItemPagingSlicedResult>& OnSuccess, const FErrorHandler& OnError)
{
FReport::Log(FString(__FUNCTION__));
FString Authorization = FString::Printf(TEXT("Bearer %s"), *Credentials.GetAccessToken());
FString Url = FString::Printf(TEXT("%s/public/namespaces/%s/items/search?language=%s&keyword=%s"), *Settings.PlatformServerUrl, *Settings.Namespace, *Language, *FGenericPlatformHttp::UrlEncode(Keyword));
if (!Region.IsEmpty())
{
Url.Append(FString::Printf(TEXT("®ion=%s"), *Region));
}
if (Offset > 0)
{
Url.Append(FString::Printf(TEXT("&offset=%d"), Offset));
}
if (Limit > 0)
{
Url.Append(FString::Printf(TEXT("&limit=%d"), Limit));
}
FString Verb = TEXT("GET");
FString ContentType = TEXT("application/json");
FString Accept = TEXT("application/json");
FString Content = TEXT("");
FHttpRequestPtr Request = FHttpModule::Get().CreateRequest();
Request->SetURL(Url);
Request->SetHeader(TEXT("Authorization"), Authorization);
Request->SetVerb(Verb);
Request->SetHeader(TEXT("Content-Type"), ContentType);
Request->SetHeader(TEXT("Accept"), Accept);
Request->SetContentAsString(Content);
FRegistry::HttpRetryScheduler.ProcessRequest(Request, CreateHttpResultHandler(OnSuccess, OnError), FPlatformTime::Seconds());
}
} // Namespace Api
} // Namespace AccelByte
| 32.077193
| 231
| 0.692299
|
leowind
|
2a2aee399852bfcadf84621b8ed8c3ba630b1f54
| 153
|
hh
|
C++
|
CppPool/cpp_d07m/ex04/Destination.hh
|
667MARTIN/Epitech
|
81095d8e7d54e9abd95541ee3dfcc3bc85d5cf0e
|
[
"MIT"
] | 40
|
2018-01-28T14:23:27.000Z
|
2022-03-05T15:57:47.000Z
|
CppPool/cpp_d07m/ex04/Destination.hh
|
667MARTIN/Epitech
|
81095d8e7d54e9abd95541ee3dfcc3bc85d5cf0e
|
[
"MIT"
] | 1
|
2021-10-05T09:03:51.000Z
|
2021-10-05T09:03:51.000Z
|
CppPool/cpp_d07m/ex04/Destination.hh
|
667MARTIN/Epitech
|
81095d8e7d54e9abd95541ee3dfcc3bc85d5cf0e
|
[
"MIT"
] | 73
|
2019-01-07T18:47:00.000Z
|
2022-03-31T08:48:38.000Z
|
#ifndef _DESTINATION_
#define _DESTINATION_
enum Destination
{
EARTH,
VULCAN,
ROMULUS,
REMUS,
UNICOMPLEX,
JUPITER,
BABEL
};
#endif
| 10.2
| 22
| 0.673203
|
667MARTIN
|
2a31ff4194392d7dcf31835486fdf10f91d81e13
| 15,956
|
cpp
|
C++
|
tests/MetadataEngine/tst_metadataenginetest.cpp
|
DatabasesWorks/passiflora-symphytum-configurable-fields
|
6128d0391fe33438250efad4398d65c5982b005b
|
[
"BSD-2-Clause"
] | 374
|
2015-01-03T17:25:16.000Z
|
2022-03-04T07:58:07.000Z
|
tests/MetadataEngine/tst_metadataenginetest.cpp
|
DatabasesWorks/symphytum-configurable-fields
|
187b72e9ff758bd207a415cb3fc9e2d97889996c
|
[
"BSD-2-Clause"
] | 133
|
2015-01-03T17:28:29.000Z
|
2020-09-22T11:44:14.000Z
|
tests/MetadataEngine/tst_metadataenginetest.cpp
|
DatabasesWorks/symphytum-configurable-fields
|
187b72e9ff758bd207a415cb3fc9e2d97889996c
|
[
"BSD-2-Clause"
] | 78
|
2015-01-19T13:26:07.000Z
|
2022-03-21T00:02:55.000Z
|
#include <QString>
#include <QtTest>
#include <QSqlQuery>
#include "../../components/metadataengine.h"
#include "../../components/databasemanager.h"
class MetadataEngineTest : public QObject
{
Q_OBJECT
public:
MetadataEngineTest();
~MetadataEngineTest();
private Q_SLOTS:
void testCollectionId();
void testCollectionName();
void testFieldName();
void testFieldCount();
void testFieldType();
void testFieldPos();
void testFieldSize();
void testFieldProperty();
void testCreateModel();
void testCreateCollection();
void testDeleteCollection();
void testCreateField();
void testDeleteField();
void testModifyField();
void testFileMetadata();
private:
MetadataEngine *m_metadataEngine;
DatabaseManager *m_databaseManager;
};
MetadataEngineTest::MetadataEngineTest()
{
m_metadataEngine = &MetadataEngine::getInstance();
m_databaseManager = &DatabaseManager::getInstance();
}
MetadataEngineTest::~MetadataEngineTest()
{
m_metadataEngine = 0;
m_databaseManager = 0;
}
void MetadataEngineTest::testCollectionId()
{
int originalId = -1;
int newId = 99;
originalId = m_metadataEngine->getCurrentCollectionId();
QVERIFY2((originalId != -1),
"Get collection ID not working");
m_metadataEngine->setCurrentCollectionId(newId);
QVERIFY2((newId == m_metadataEngine->getCurrentCollectionId()),
"Set collection ID not working");
//set original back
m_metadataEngine->setCurrentCollectionId(originalId);
}
void MetadataEngineTest::testCollectionName()
{
//this is the same string from database manager where the default
//collection name is defined for example data
QString defaultCollectionName = "Customers";
QString currentCollectionName = m_metadataEngine->getCurrentCollectionName();
QVERIFY2((defaultCollectionName == currentCollectionName),
"Get collection name not working");
QString getCollectionName = m_metadataEngine->getCollectionName(
m_metadataEngine->getCurrentCollectionId());
QVERIFY(defaultCollectionName == getCollectionName);
}
void MetadataEngineTest::testFieldName()
{
QString originalName, newName, exampleName;
int id, column;
exampleName = "Age"; //from database manager example data
newName = "Weight";
column = 3; //age column from example data
id = m_metadataEngine->getCurrentCollectionId();
originalName = m_metadataEngine->getFieldName(column);
QVERIFY(originalName == exampleName);
QVERIFY(originalName == m_metadataEngine->getFieldName(column, id));
QVERIFY("_invalid_column_name_" == m_metadataEngine->getFieldName(column, 9999));
m_metadataEngine->setFieldName(column, newName);
QVERIFY(newName == m_metadataEngine->getFieldName(column));
m_metadataEngine->setFieldName(column, newName, id);
QVERIFY(newName == m_metadataEngine->getFieldName(column, id));
m_metadataEngine->setFieldName(column, "invalid", 9999);
QVERIFY(newName == m_metadataEngine->getFieldName(column, id));
//set back to original name
m_metadataEngine->setFieldName(column, originalName);
}
void MetadataEngineTest::testFieldCount()
{
int exampleFieldCount = 4; //field count from exmple data
int id = m_metadataEngine->getCurrentCollectionId();
QVERIFY(exampleFieldCount == m_metadataEngine->getFieldCount());
QVERIFY(exampleFieldCount == m_metadataEngine->getFieldCount(id));
QVERIFY(0 == m_metadataEngine->getFieldCount(9999));
}
void MetadataEngineTest::testFieldType()
{
//from example data
MetadataEngine::FieldType exampleFieldType = MetadataEngine::NumericType;
int column = 3;
int id = m_metadataEngine->getCurrentCollectionId();
QString columnName = "Age";
QVERIFY(exampleFieldType == m_metadataEngine->getFieldType(column, id));
QVERIFY(exampleFieldType == m_metadataEngine->getFieldType(column));
QVERIFY(exampleFieldType == m_metadataEngine->getFieldType(columnName, id));
QVERIFY(exampleFieldType == m_metadataEngine->getFieldType(columnName));
}
void MetadataEngineTest::testFieldPos()
{
//from example data
int column = 3;
int id = m_metadataEngine->getCurrentCollectionId();
QString columnName = "Age";
int x, y;
bool ok = m_metadataEngine->getFieldCoordinate(column, x, y, id);
QVERIFY(ok == false);
m_metadataEngine->setFieldCoordinate(column, 1, 2);
ok = m_metadataEngine->getFieldCoordinate(column, x, y, id);
QVERIFY(ok == true);
QVERIFY((x == 1) && (y == 2));
m_metadataEngine->setFieldCoordinate(column, -1, -1);
ok = m_metadataEngine->getFieldCoordinate(column, x, y, id);
QVERIFY(ok == false);
}
void MetadataEngineTest::testFieldSize()
{
//from example data
int column = 3;
int id = m_metadataEngine->getCurrentCollectionId();
QString columnName = "Age";
int w, h;
m_metadataEngine->getFieldFormLayoutSize(column, w, h, 9999);
QVERIFY((w == -1) && (h == -1));
m_metadataEngine->setFieldFormLayoutSize(column, 1, 2);
m_metadataEngine->getFieldFormLayoutSize(column, w, h, id);
QVERIFY((w == 1) && (h == 2));
m_metadataEngine->setFieldFormLayoutSize(column, 1, 1);
}
void MetadataEngineTest::testFieldProperty()
{
//from example data
int column = 3;
int id = m_metadataEngine->getCurrentCollectionId();
QString columnName = "Age";
QString testProperty = "key:value;key2:value2a,value2b;";
QVERIFY(
m_metadataEngine->getFieldProperties(MetadataEngine::DisplayProperty, column)
.isEmpty()); //FIXME: err
m_metadataEngine->setFieldProperties(MetadataEngine::DisplayProperty, column,
testProperty);
QVERIFY(
m_metadataEngine->getFieldProperties(MetadataEngine::DisplayProperty, column)
== testProperty);
//reset
m_metadataEngine->setFieldProperties(MetadataEngine::DisplayProperty, column,
"");
}
void MetadataEngineTest::testCreateModel()
{
//model without init
QAbstractItemModel *model = m_metadataEngine->createModel(
MetadataEngine::StandardCollection);
QVERIFY(model != 0);
QVERIFY(model->columnCount() == 0);
//model with init
int id = m_metadataEngine->getCurrentCollectionId();
int exampleFieldCount = m_metadataEngine->getFieldCount();
QAbstractItemModel *model2 = m_metadataEngine->createModel(
MetadataEngine::StandardCollection, id);
QVERIFY(model2 != 0);
QVERIFY(model2->columnCount() == exampleFieldCount);
}
void MetadataEngineTest::testCreateCollection()
{
int id = -1;
QString tableName;
QString metadataTableName;
//simulate new entry in collection list
QSqlQuery query(m_databaseManager->getDatabase());
query.exec("INSERT INTO \"collections\" (\"name\") VALUES (\"Test\")");
//create tables and metadata
int cid = m_metadataEngine->createNewCollection();
//get id
query.exec("SELECT _id FROM collections WHERE name='Test'");
if (query.next()) {
id = query.value(0).toInt();
}
QVERIFY(id > 0);
QVERIFY(id == cid);
//get table names
query.exec("SELECT table_name FROM collections WHERE name='Test'");
if (query.next()) {
tableName = query.value(0).toString();
metadataTableName = tableName + "_metadata";
}
QVERIFY(!tableName.isEmpty());
//check if tables exist
query.exec(QString("SELECT name FROM sqlite_master WHERE type='table'"
" AND name='%1'").arg(tableName));
bool a = query.next();
QVERIFY(a);
QVERIFY(!query.value(0).toString().isEmpty());
query.exec(QString("SELECT name FROM sqlite_master WHERE type='table'"
" AND name='%1'").arg(metadataTableName));
bool b = query.next();
QVERIFY(b);
QVERIFY(!query.value(0).toString().isEmpty());
}
void MetadataEngineTest::testDeleteCollection()
{
int id = -1;
QString tableName;
QString metadataTableName;
QSqlQuery query(m_databaseManager->getDatabase());
//get id
query.exec("SELECT _id FROM collections WHERE name='Test'");
if (query.next()) {
id = query.value(0).toInt();
}
QVERIFY(id > 0);
query.clear(); //release query otherwise delete will fail
//create tables and metadata
m_metadataEngine->deleteCollection(id);
//get table names
query.exec("SELECT table_name FROM collections WHERE name='Test'");
if (query.next()) {
tableName = query.value(0).toString();
metadataTableName = tableName + "_metadata";
}
QVERIFY(!tableName.isEmpty());
//check if tables exist
query.exec(QString("SELECT name FROM sqlite_master WHERE type='table'"
" AND name='%1'").arg(tableName));
QVERIFY(!query.next());
query.exec(QString("SELECT name FROM sqlite_master WHERE type='table'"
" AND name='%1'").arg(metadataTableName));
QVERIFY(!query.next());
//remove collection from collections list
query.exec(QString("DELETE FROM collections WHERE _id=%1").arg(id));
}
void MetadataEngineTest::testCreateField()
{
QSqlQuery query(m_databaseManager->getDatabase());
QString fieldName("Test Field");
MetadataEngine::FieldType type = MetadataEngine::NumericType;
QString displayProperties = "prop:1;";
QString editProperties = "prop:1;";
QString triggerProperties = "prop:1;";
int fieldId = m_metadataEngine->createField(fieldName,
type,
displayProperties,
editProperties,
triggerProperties);
QVERIFY(fieldId != 0); //0 should be _id column
QVERIFY(fieldId == (m_metadataEngine->getFieldCount() - 1));
QVERIFY(fieldName == m_metadataEngine->getFieldName(fieldId));
QVERIFY(type == m_metadataEngine->getFieldType(fieldId));
QVERIFY(displayProperties ==
m_metadataEngine->getFieldProperties(MetadataEngine::DisplayProperty,
fieldId));
QVERIFY(editProperties ==
m_metadataEngine->getFieldProperties(MetadataEngine::EditProperty,
fieldId));
QVERIFY(triggerProperties ==
m_metadataEngine->getFieldProperties(MetadataEngine::TriggerProperty,
fieldId));
}
void MetadataEngineTest::testDeleteField()
{
QString fieldName2 = "Test2";
MetadataEngine::FieldType type2 = MetadataEngine::NumericType;
int fieldId2 = m_metadataEngine->createField(fieldName2,
type2,
"",
"",
"");
QString fieldName("Test Field");
int fieldId = 4; //hard coded I know :P
int fieldCount = m_metadataEngine->getFieldCount();
//delete Test Field
m_metadataEngine->deleteField(fieldId);
QVERIFY(m_metadataEngine->getFieldCount() == (fieldCount - 1));
QVERIFY(fieldName2 == m_metadataEngine->getFieldName(fieldId));
QVERIFY(m_metadataEngine->getFieldProperties(MetadataEngine::DisplayProperty,
fieldId).isEmpty());
QVERIFY(m_metadataEngine->getFieldProperties(MetadataEngine::EditProperty,
fieldId).isEmpty());
QVERIFY(m_metadataEngine->getFieldProperties(MetadataEngine::TriggerProperty,
fieldId).isEmpty());
//delete Test2
m_metadataEngine->deleteField(fieldId);
QVERIFY(m_metadataEngine->getFieldCount() == (fieldCount - 2));
QVERIFY("_invalid_column_name_" == m_metadataEngine->getFieldName(fieldId));
QVERIFY(m_metadataEngine->getFieldProperties(MetadataEngine::DisplayProperty,
fieldId).isEmpty());
QVERIFY(m_metadataEngine->getFieldProperties(MetadataEngine::EditProperty,
fieldId).isEmpty());
QVERIFY(m_metadataEngine->getFieldProperties(MetadataEngine::TriggerProperty,
fieldId).isEmpty());
}
void MetadataEngineTest::testModifyField()
{
QString fieldName("Test Field");
QString fieldName2("Test Mod Field");
MetadataEngine::FieldType type = MetadataEngine::NumericType;
QString displayProperties = "prop:1;";
QString editProperties = "prop:1;";
QString triggerProperties = "prop:1;";
QString displayProperties2 = "prop:2;";
QString editProperties2 = "prop:2;";
QString triggerProperties2 = "prop:2;";
int fieldId = m_metadataEngine->createField(fieldName,
type,
displayProperties,
editProperties,
triggerProperties);
//modify
m_metadataEngine->modifyField(fieldId, fieldName2,
displayProperties2,
editProperties2,
triggerProperties2);
//verify
QVERIFY(fieldName2 == m_metadataEngine->getFieldName(fieldId));
QVERIFY(displayProperties2 ==
m_metadataEngine->getFieldProperties(MetadataEngine::DisplayProperty,
fieldId));
QVERIFY(editProperties2 ==
m_metadataEngine->getFieldProperties(MetadataEngine::EditProperty,
fieldId));
QVERIFY(triggerProperties2 ==
m_metadataEngine->getFieldProperties(MetadataEngine::TriggerProperty,
fieldId));
//delete
m_metadataEngine->deleteField(fieldId);
}
void MetadataEngineTest::testFileMetadata()
{
QString fileName = "testFileName.txt";
QString hashName = "md5HashName.txt";
//add
int id = m_metadataEngine->addContentFile(fileName, hashName);
QVERIFY(id != 0);
//get id
QVERIFY(id == m_metadataEngine->getContentFileId(hashName));
//get
QString qFileName;
QString qHashName;
QDateTime qFileAddedDate;
bool s = m_metadataEngine->getContentFile(id, qFileName,
qHashName, qFileAddedDate);
QVERIFY(s);
QVERIFY(qFileName == fileName);
QVERIFY(qHashName == hashName);
QVERIFY(qFileAddedDate.isValid());
//update
QString a = "New name.txt";
QString b = "new_hash_md5.txt";
QDateTime c = QDateTime(QDate(1990,6,28));
m_metadataEngine->updateContentFile(id, a, b, c);
s = m_metadataEngine->getContentFile(id, qFileName,
qHashName, qFileAddedDate);
QVERIFY(s);
QVERIFY(qFileName == a);
QVERIFY(qHashName == b);
QVERIFY(qFileAddedDate == c);
//remove
m_metadataEngine->removeContentFile(id);
s = m_metadataEngine->getContentFile(id, qFileName,
qHashName, qFileAddedDate);
QVERIFY(!s);
//get all files
int x = m_metadataEngine->addContentFile(fileName, hashName);
int y = m_metadataEngine->addContentFile(a, b);
QHash<int,QString> map = m_metadataEngine->getAllContentFiles();
m_metadataEngine->removeContentFile(x);
m_metadataEngine->removeContentFile(y);
QVERIFY(map.size() == 2);
QVERIFY(map.value(x) == hashName);
QVERIFY(map.value(y) == b);
}
QTEST_APPLESS_MAIN(MetadataEngineTest)
#include "tst_metadataenginetest.moc"
| 34.686957
| 85
| 0.635435
|
DatabasesWorks
|
2a340eedb70e93dbac2193f8b0125757e80a0feb
| 4,051
|
cpp
|
C++
|
sdk/core/azure-core/test/ut/http.cpp
|
JasonYang-MSFT/azure-sdk-for-cpp
|
c0faea5f90c0d78f088f8c049353a2ee66ba3930
|
[
"MIT"
] | null | null | null |
sdk/core/azure-core/test/ut/http.cpp
|
JasonYang-MSFT/azure-sdk-for-cpp
|
c0faea5f90c0d78f088f8c049353a2ee66ba3930
|
[
"MIT"
] | 1
|
2021-02-23T00:43:57.000Z
|
2021-02-23T00:49:17.000Z
|
sdk/core/azure-core/test/ut/http.cpp
|
JasonYang-MSFT/azure-sdk-for-cpp
|
c0faea5f90c0d78f088f8c049353a2ee66ba3930
|
[
"MIT"
] | null | null | null |
// Copyright (c) Microsoft Corporation. All rights reserved.
// SPDX-License-Identifier: MIT
#include "gtest/gtest.h"
#include <http/http.hpp>
#include <string>
#include <vector>
using namespace Azure::Core;
TEST(Http_Request, getters)
{
Http::HttpMethod httpMethod = Http::HttpMethod::Get;
std::string url = "http://test.url.com";
Http::Request req(httpMethod, url);
// EXPECT_PRED works better than just EQ because it will print values in log
EXPECT_PRED2(
[](Http::HttpMethod a, Http::HttpMethod b) { return a == b; }, req.GetMethod(), httpMethod);
EXPECT_PRED2([](std::string a, std::string b) { return a == b; }, req.GetEncodedUrl(), url);
EXPECT_NO_THROW(req.AddHeader("Name", "value"));
EXPECT_NO_THROW(req.AddHeader("naME2", "value2"));
auto headers = req.GetHeaders();
// Headers should be lower-cased
EXPECT_TRUE(headers.count("name"));
EXPECT_TRUE(headers.count("name2"));
EXPECT_FALSE(headers.count("newHeader"));
auto value = headers.find("name");
EXPECT_PRED2([](std::string a, std::string b) { return a == b; }, value->second, "value");
auto value2 = headers.find("name2");
EXPECT_PRED2([](std::string a, std::string b) { return a == b; }, value2->second, "value2");
// now add to retry headers
req.StartRetry();
// same headers first, then one new
EXPECT_NO_THROW(req.AddHeader("namE", "retryValue"));
EXPECT_NO_THROW(req.AddHeader("HEADER-to-Lower-123", "retryValue2"));
EXPECT_NO_THROW(req.AddHeader("newHeader", "new"));
headers = req.GetHeaders();
EXPECT_TRUE(headers.count("name"));
EXPECT_TRUE(headers.count("header-to-lower-123"));
EXPECT_TRUE(headers.count("newheader"));
value = headers.find("name");
EXPECT_PRED2([](std::string a, std::string b) { return a == b; }, value->second, "retryValue");
value2 = headers.find("header-to-lower-123");
EXPECT_PRED2([](std::string a, std::string b) { return a == b; }, value2->second, "retryValue2");
auto value3 = headers.find("newheader");
EXPECT_PRED2([](std::string a, std::string b) { return a == b; }, value3->second, "new");
}
TEST(Http_Request, query_parameter)
{
Http::HttpMethod httpMethod = Http::HttpMethod::Put;
std::string url = "http://test.com";
Http::Request req(httpMethod, url);
EXPECT_NO_THROW(req.AddQueryParameter("query", "value"));
EXPECT_PRED2(
[](std::string a, std::string b) { return a == b; },
req.GetEncodedUrl(),
url + "?query=value");
std::string url_with_query = "http://test.com?query=1";
Http::Request req_with_query(httpMethod, url_with_query);
// ignore if adding same query parameter key that is already in url
EXPECT_NO_THROW(req_with_query.AddQueryParameter("query", "value"));
EXPECT_PRED2(
[](std::string a, std::string b) { return a == b; },
req_with_query.GetEncodedUrl(),
url_with_query);
// retry query params testing
req.StartRetry();
// same query parameter should override previous
EXPECT_NO_THROW(req.AddQueryParameter("query", "retryValue"));
EXPECT_PRED2(
[](std::string a, std::string b) { return a == b; },
req.GetEncodedUrl(),
url + "?query=retryValue");
}
TEST(Http_Request, add_path)
{
Http::HttpMethod httpMethod = Http::HttpMethod::Post;
std::string url = "http://test.com";
Http::Request req(httpMethod, url);
EXPECT_NO_THROW(req.AppendPath("path"));
EXPECT_PRED2(
[](std::string a, std::string b) { return a == b; }, req.GetEncodedUrl(), url + "/path");
EXPECT_NO_THROW(req.AddQueryParameter("query", "value"));
EXPECT_PRED2(
[](std::string a, std::string b) { return a == b; },
req.GetEncodedUrl(),
url + "/path?query=value");
EXPECT_NO_THROW(req.AppendPath("path2"));
EXPECT_PRED2(
[](std::string a, std::string b) { return a == b; },
req.GetEncodedUrl(),
url + "/path/path2?query=value");
EXPECT_NO_THROW(req.AppendPath("path3"));
EXPECT_PRED2(
[](std::string a, std::string b) { return a == b; },
req.GetEncodedUrl(),
url + "/path/path2/path3?query=value");
}
| 34.042017
| 99
| 0.662552
|
JasonYang-MSFT
|
2a35ba2c64c78650b483bb976d85e5603b77018b
| 258
|
cpp
|
C++
|
Cpp_primer_5th/code_part9/prog9_34.cpp
|
Links789/Cpp_primer_5th
|
18a60b75c358a79fdf006f8cb978c9be6e6aedd5
|
[
"MIT"
] | null | null | null |
Cpp_primer_5th/code_part9/prog9_34.cpp
|
Links789/Cpp_primer_5th
|
18a60b75c358a79fdf006f8cb978c9be6e6aedd5
|
[
"MIT"
] | null | null | null |
Cpp_primer_5th/code_part9/prog9_34.cpp
|
Links789/Cpp_primer_5th
|
18a60b75c358a79fdf006f8cb978c9be6e6aedd5
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<int> vi{1,2,3,4,5};
auto iter = vi.begin();
while(iter != vi.end() ){ //endless loo
iter = vi.insert(iter, *iter);
cout << *iter << endl;
}
++iter;
return 0;
}
| 14.333333
| 40
| 0.581395
|
Links789
|
2a3664d0d70d55544f209d77704c0f9a57ddff24
| 1,116
|
cpp
|
C++
|
mp/src/old/cl_dll/vgui_consolepanel.cpp
|
MaartenS11/Team-Fortress-Invasion
|
f36b96d27f834d94e0db2d2a9470b05b42e9b460
|
[
"Unlicense"
] | 1
|
2021-03-20T14:27:45.000Z
|
2021-03-20T14:27:45.000Z
|
mp/src/old/cl_dll/vgui_consolepanel.cpp
|
MaartenS11/Team-Fortress-Invasion
|
f36b96d27f834d94e0db2d2a9470b05b42e9b460
|
[
"Unlicense"
] | null | null | null |
mp/src/old/cl_dll/vgui_consolepanel.cpp
|
MaartenS11/Team-Fortress-Invasion
|
f36b96d27f834d94e0db2d2a9470b05b42e9b460
|
[
"Unlicense"
] | null | null | null |
//======== (C) Copyright 1999, 2000 Valve, L.L.C. All rights reserved. ========
//
// The copyright to the contents herein is the property of Valve, L.L.C.
// The contents may be used and/or copied only with the written permission of
// Valve, L.L.C., or in accordance with the terms and conditions stipulated in
// the agreement/contract under which the contents have been supplied.
//
// Purpose:
//
// $Workfile: $
// $Date: $
//
//-----------------------------------------------------------------------------
// $Log: $
//
// $NoKeywords: $
//=============================================================================
#include "cbase.h"
#include "iconsole.h"
class CConPanel;
class CConsole : public IConsole
{
private:
CConPanel *conPanel;
public:
CConsole( void )
{
conPanel = NULL;
}
void Create( vgui::VPANEL parent )
{
/*
conPanel = new CConPanel( parent );
*/
}
void Destroy( void )
{
/*
if ( conPanel )
{
conPanel->SetParent( (vgui::Panel *)NULL );
delete conPanel;
}
*/
}
};
static CConsole g_Console;
IConsole *console = ( IConsole * )&g_Console;
| 20.666667
| 79
| 0.543011
|
MaartenS11
|
2a3b854022134ea7d90ee72dcb8b39a2cad1e4a5
| 11,860
|
cpp
|
C++
|
src/native_extensions/process_manager_win.cpp
|
devcxx/zephyros
|
3ba2c63c5d11bfab66b896e8e09287e222f645a2
|
[
"Unlicense",
"MIT"
] | null | null | null |
src/native_extensions/process_manager_win.cpp
|
devcxx/zephyros
|
3ba2c63c5d11bfab66b896e8e09287e222f645a2
|
[
"Unlicense",
"MIT"
] | null | null | null |
src/native_extensions/process_manager_win.cpp
|
devcxx/zephyros
|
3ba2c63c5d11bfab66b896e8e09287e222f645a2
|
[
"Unlicense",
"MIT"
] | null | null | null |
/*******************************************************************************
* Copyright (c) 2015-2017 Vanamco AG, http://www.vanamco.com
*
* The MIT License (MIT)
* 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.
*
* Contributors:
* Matthias Christen, Vanamco AG
*******************************************************************************/
#include <tchar.h>
#include <Shlwapi.h>
#include <algorithm>
#include "lib/CrashRpt/CrashRpt.h"
#include "base/app.h"
#include "base/cef/client_handler.h"
#include "base/cef/extension_handler.h"
#include "util/string_util.h"
#include "native_extensions/os_util.h"
#include "native_extensions/process_manager.h"
//////////////////////////////////////////////////////////////////////////
// Constants
#define BUF_SIZE 8192
//////////////////////////////////////////////////////////////////////////
// Worker Thread Functions
extern CefRefPtr<Zephyros::ClientHandler> g_handler;
DWORD WINAPI ReadOutput(LPVOID param)
{
// install exception handlers for this thread
//const TCHAR* szCrashReportingURL = Zephyros::GetCrashReportingURL();
//if (szCrashReportingURL != NULL && szCrashReportingURL[0] != TCHAR('\0'))
// crInstallToCurrentThread2(0);
Zephyros::PipeData* p = (Zephyros::PipeData*) param;
DWORD numBytesRead;
DWORD numBytesAvail;
char buf[BUF_SIZE + 1];
for ( ; ; )
{
PeekNamedPipe(p->hndRead, NULL, 0, NULL, &numBytesAvail, NULL);
if (numBytesAvail == 0 && p->isTerminated)
break;
// read stdout of the process and process the output
ReadFile(p->hndRead, buf, BUF_SIZE, &numBytesRead, NULL);
if (numBytesRead > 0)
{
Zephyros::StreamDataEntry entry;
entry.type = p->type;
int nWcLen = MultiByteToWideChar(CP_UTF8, 0, (LPCCH) buf, numBytesRead, NULL, 0);
TCHAR* bufWc = new TCHAR[nWcLen + 1];
MultiByteToWideChar(CP_UTF8, 0, (LPCCH) buf, numBytesRead, bufWc, nWcLen);
bufWc[nWcLen] = 0;
entry.text = String(bufWc, bufWc + nWcLen);
EnterCriticalSection(&(p->pData->cs));
p->pData->stream.push_back(entry);
LeaveCriticalSection(&(p->pData->cs));
}
}
CloseHandle(p->hndRead);
CloseHandle(p->hndWrite);
// unset exception handlers before exiting the thread
//crUninstallFromCurrentThread();
return 0;
}
DWORD WINAPI WaitForProcessProc(LPVOID param)
{
Zephyros::ProcessManager* pMgr = (Zephyros::ProcessManager*) param;
DWORD dwExitCode = 0;
// wait until the process has terminated
WaitForSingleObject(pMgr->m_procInfo.hProcess, INFINITE);
GetExitCodeProcess(pMgr->m_procInfo.hProcess, &dwExitCode);
// wait until the reading threads have termiated
pMgr->m_in.isTerminated = true;
pMgr->m_out.isTerminated = true;
pMgr->m_err.isTerminated = true;
HANDLE handles[] = { pMgr->m_hReadOutThread, pMgr->m_hReadErrThread };
WaitForMultipleObjects(2, handles, TRUE, 1000);
CloseHandle(pMgr->m_procInfo.hProcess);
CloseHandle(pMgr->m_procInfo.hThread);
// return the result and clean up
pMgr->FireCallback((int) dwExitCode);
delete pMgr;
return 0;
}
//////////////////////////////////////////////////////////////////////////
// ProcessManager Implementation
namespace Zephyros {
ProcessManager::ProcessManager(CallbackId callbackId, String strExePath, std::vector<String> vecArgs, String strCWD, Error& err)
: m_callbackId(callbackId),
m_strExePath(strExePath),
m_vecArgs(vecArgs),
m_strCWD(strCWD),
m_error(&err)
{
InitializeCriticalSection(&m_data.cs);
if (m_strCWD == TEXT("~"))
m_strCWD = OSUtil::GetHomeDirectory();
}
ProcessManager::~ProcessManager()
{
DeleteCriticalSection(&m_data.cs);
}
bool ProcessManager::Start()
{
m_data.stream.clear();
m_in.isTerminated = false;
m_out.isTerminated = false;
m_err.isTerminated = false;
m_in.type = TYPE_STDIN;
m_out.type = TYPE_STDOUT;
m_err.type = TYPE_STDERR;
m_in.pData = &m_data;
m_out.pData = &m_data;
m_err.pData = &m_data;
if (ProcessManager::CreateProcess(m_strExePath, m_vecArgs, m_strCWD, NULL, &m_procInfo,
&m_in.hndRead, &m_in.hndWrite, &m_out.hndRead, &m_out.hndWrite, &m_err.hndRead, &m_err.hndWrite))
{
m_hReadOutThread = CreateThread(NULL, 0, ReadOutput, &m_out, 0, NULL);
m_hReadErrThread = CreateThread(NULL, 0, ReadOutput, &m_err, 0, NULL);
CreateThread(NULL, 0, WaitForProcessProc, this, 0, NULL);
return true;
}
// creating the process failed
m_error->FromLastError();
delete this;
return false;
}
void ProcessManager::FireCallback(int exitCode)
{
JavaScript::Array args = JavaScript::CreateArray();
JavaScript::Array stream = JavaScript::CreateArray();
int i = 0;
for (StreamDataEntry e : m_data.stream)
{
JavaScript::Object streamEntry = JavaScript::CreateObject();
streamEntry->SetInt(TEXT("fd"), e.type);
streamEntry->SetString(TEXT("text"), e.text);
stream->SetDictionary(i++, streamEntry);
}
args->SetNull(0);
args->SetInt(1, exitCode);
args->SetList(2, stream);
g_handler->GetClientExtensionHandler()->InvokeCallback(m_callbackId, args);
}
bool ProcessManager::CreateProcess(
String strExePath,
std::vector<String> vecArgs,
String strCWD,
LPVOID lpEnv,
PROCESS_INFORMATION* pProcInfo,
HANDLE* phStdinRead, HANDLE* phStdinWrite,
HANDLE* phStdoutRead, HANDLE* phStdoutWrite,
HANDLE* phStderrRead, HANDLE* phStderrWrite)
{
// create pipes
SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = NULL;
HANDLE h1, h2, h3, h4;
if (phStdinRead == NULL)
phStdinRead = &h1;
if (phStdinWrite == NULL)
phStdinWrite = &h2;
if (phStdoutRead == NULL)
phStdoutRead = &h3;
if (phStdoutWrite == NULL)
phStdoutWrite = &h4;
if (phStderrRead == NULL)
phStderrRead = phStdoutRead;
if (phStderrWrite == NULL || phStderrRead == phStdoutRead)
phStderrWrite = phStdoutWrite;
CreatePipe(phStdinRead, phStdinWrite, &sa, 0);
SetHandleInformation(*phStdinWrite, HANDLE_FLAG_INHERIT, 0);
CreatePipe(phStdoutRead, phStdoutWrite, &sa, 0);
SetHandleInformation(*phStdoutRead, HANDLE_FLAG_INHERIT, 0);
if (phStderrRead != phStdoutRead)
{
CreatePipe(phStderrRead, phStderrWrite, &sa, 0);
SetHandleInformation(*phStderrRead, HANDLE_FLAG_INHERIT, 0);
}
// set up members of the PROCESS_INFORMATION structure
ZeroMemory(pProcInfo, sizeof(PROCESS_INFORMATION));
// set up members of the STARTUPINFO structure
// this structure specifies the STDIN and STDOUT handles for redirection
STARTUPINFO startupInfo;
ZeroMemory(&startupInfo, sizeof(STARTUPINFO));
startupInfo.cb = sizeof(STARTUPINFO);
startupInfo.hStdInput = *phStdinRead;
startupInfo.hStdOutput = *phStdoutWrite;
startupInfo.hStdError = *phStderrWrite;
startupInfo.wShowWindow = SW_HIDE;
startupInfo.dwFlags |= STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
// prepare the command line
String cmdLine;
size_t pos = strExePath.find_last_of(TEXT('.'));
String extension = pos == String::npos ? TEXT("") : ToLower(strExePath.substr(pos));
bool usesComSpec = false;
if (extension != TEXT(".exe"))
{
// if this is no exe file, use "cmd.exe /C <file> <args>"
String cmd = ProcessManager::GetEnvVar(TEXT("ComSpec"));
bool hasSpaces = strExePath.find(TEXT(" ")) != String::npos;
cmdLine = cmd + TEXT(" /C \"");
if (hasSpaces)
cmdLine.append(TEXT("\""));
cmdLine.append(strExePath);
if (hasSpaces)
cmdLine.append(TEXT("\""));
strExePath = cmd;
usesComSpec = true;
}
else
{
// resolve the path if needed
if (strExePath.find(TEXT(":\\")) == String::npos)
ProcessManager::FindInPath(strExePath);
cmdLine = TEXT("\"") + strExePath + TEXT("\"");
}
// all arguments are wrapped in quotes, and quotes are escaped with double quotes
// escape '\"' by '\\""'
for (String arg : vecArgs)
{
bool hasSpacesOrQuotationMarks = (arg.find(TEXT(" ")) != String::npos) || (arg.find(TEXT("\"")) != String::npos);
if (hasSpacesOrQuotationMarks)
{
cmdLine.append(TEXT(" \""));
cmdLine.append(StringReplace(StringReplace(arg, TEXT("\""), TEXT("\"\"")), TEXT("\\\"\""), TEXT("\\\\\"\"")));
cmdLine.append(TEXT("\""));
}
else
{
cmdLine.append(TEXT(" "));
cmdLine.append(arg);
}
}
if (usesComSpec)
cmdLine.append(TEXT("\""));
#ifndef NDEBUG
App::Log(cmdLine);
#endif
// start the child process
TCHAR* szCmdLine = new TCHAR[cmdLine.length() + 1];
_tcscpy(szCmdLine, cmdLine.c_str());
BOOL bSuccess = ::CreateProcess(
strExePath.c_str(),
szCmdLine,
NULL,
NULL,
TRUE,
0,
lpEnv,
strCWD == TEXT("") ? NULL : strCWD.c_str(),
&startupInfo,
pProcInfo
);
delete[] szCmdLine;
if (!bSuccess)
App::ShowErrorMessage();
return bSuccess == TRUE;
}
void ProcessManager::FindInPath(String& strFile)
{
bool HasExtension = strFile.find(TEXT(".")) != String::npos;
StringStream ssPath(ProcessManager::GetEnvVar(TEXT("PATH")));
String path;
while (std::getline(ssPath, path, TEXT(';')))
{
String strFileWithPath = path;
if (path.at(path.length() - 1) != TEXT('\\'))
strFileWithPath += TEXT("\\");
strFileWithPath += strFile;
if (HasExtension && PathFileExists(strFileWithPath.c_str()))
{
strFile = strFileWithPath;
break;
}
String strFileWithPathAndExtension = strFileWithPath + TEXT(".exe");
if (PathFileExists(strFileWithPathAndExtension.c_str()))
{
strFile = strFileWithPathAndExtension;
break;
}
strFileWithPathAndExtension = strFileWithPath + TEXT(".bat");
if (PathFileExists(strFileWithPathAndExtension.c_str()))
{
strFile = strFileWithPathAndExtension;
break;
}
}
}
String ProcessManager::GetEnvVar(LPCTSTR strVarName)
{
DWORD dwLen = GetEnvironmentVariable(strVarName, NULL, 0);
TCHAR* pBuf = new TCHAR[dwLen + 1];
GetEnvironmentVariable(strVarName, pBuf, dwLen);
String str(pBuf);
delete[] pBuf;
return str;
}
} // namespace Zephyros
| 30.101523
| 128
| 0.626391
|
devcxx
|
2a3cc5850d3a481d73bb75f09bc6c57020260f4a
| 614
|
hpp
|
C++
|
AdenitaCoreSE/include/SEDSDNACreatorEditorDescriptor.hpp
|
edellano/Adenita-SAMSON-Edition-Win-
|
6df8d21572ef40fe3fc49165dfaa1d4318352a69
|
[
"BSD-3-Clause"
] | 2
|
2020-09-07T20:48:43.000Z
|
2021-09-03T05:49:59.000Z
|
AdenitaCoreSE/include/SEDSDNACreatorEditorDescriptor.hpp
|
edellano/Adenita-SAMSON-Edition-Linux
|
a7e267e5dd37e0073f4d1e3e603c5fb1c69a350a
|
[
"BSD-3-Clause"
] | 6
|
2020-04-05T18:39:28.000Z
|
2022-01-11T14:28:55.000Z
|
AdenitaCoreSE/include/SEDSDNACreatorEditorDescriptor.hpp
|
edellano/Adenita-SAMSON-Edition-Linux
|
a7e267e5dd37e0073f4d1e3e603c5fb1c69a350a
|
[
"BSD-3-Clause"
] | 2
|
2021-07-13T12:58:13.000Z
|
2022-01-11T13:52:00.000Z
|
/// \headerfile SBProxy.hpp "SBProxy.hpp"
#include "SBProxy.hpp"
/// \headerfile SEDSDNACreatorEditor.hpp "SEDSDNACreatorEditor.hpp"
#include "SEDSDNACreatorEditor.hpp"
// Class descriptor
// SAMSON Element generator pro tip: complete this descriptor to expose this class to SAMSON and other SAMSON Elements
SB_CLASS_BEGIN(SEDSDNACreatorEditor);
SB_CLASS_TYPE(SBCClass::Editor);
SB_CLASS_DESCRIPTION("DNA Creator : Add ssDNA and dsDNA");
SB_FACTORY_BEGIN;
SB_CONSTRUCTOR_0(SEDSDNACreatorEditor);
SB_FACTORY_END;
SB_INTERFACE_BEGIN;
SB_INTERFACE_END;
SB_CLASS_END(SEDSDNACreatorEditor);
| 21.172414
| 118
| 0.788274
|
edellano
|
2a3f479e43bd5d826b012ae081234b5767e0c106
| 881
|
cpp
|
C++
|
src/c_handshake.cpp
|
DreamHacks/dd3d
|
4665cc6e55b415c48385c6b6279bb3fd5f8e4bc9
|
[
"MIT"
] | null | null | null |
src/c_handshake.cpp
|
DreamHacks/dd3d
|
4665cc6e55b415c48385c6b6279bb3fd5f8e4bc9
|
[
"MIT"
] | null | null | null |
src/c_handshake.cpp
|
DreamHacks/dd3d
|
4665cc6e55b415c48385c6b6279bb3fd5f8e4bc9
|
[
"MIT"
] | 5
|
2017-07-09T12:03:19.000Z
|
2022-02-09T09:37:36.000Z
|
#include "dd3d.h"
#include "connection.h"
#include "crypt.h"
#include "m_user.h"
#include "log.h"
#include "c_handshake.h"
bool c_handshake_handler(void* message, uint32_t message_size) {
bool rv = false;
if (message_size == 4 + RSA_SIZE) {
uint8_t key[RSA_SIZE];
int key_size = crypt_rsa_private_decrypt(utils_poniter_calc<uint8_t*>(message, 4), RSA_SIZE, key);
if (16 == key_size) {
char reply_data[32 + RSA_SIZE];
if (m_user_create_session(reply_data, key)) {
utils_xxtea_encrypt((uint8_t*)reply_data, 32, key);
key_size = crypt_rsa_private_encrypt(key, 16, utils_poniter_calc<uint8_t*>(reply_data, 32));
if (key_size != -1) {
connection_reply(reply_data, 32 + RSA_SIZE);
return true;
}
} else
syslog(LOG_ERR, "[ERROR]create session failed.\n");
} else {
syslog(LOG_ERR, "[ERROR]handshake failed.\n");
}
}
return rv;
}
| 28.419355
| 100
| 0.687855
|
DreamHacks
|
2a45f8f0806cb2aa41ad4988c5b187d4881018d1
| 1,300
|
hpp
|
C++
|
libs/core/include/fcppt/math/matrix/has_dim.hpp
|
pmiddend/fcppt
|
9f437acbb10258e6df6982a550213a05815eb2be
|
[
"BSL-1.0"
] | null | null | null |
libs/core/include/fcppt/math/matrix/has_dim.hpp
|
pmiddend/fcppt
|
9f437acbb10258e6df6982a550213a05815eb2be
|
[
"BSL-1.0"
] | null | null | null |
libs/core/include/fcppt/math/matrix/has_dim.hpp
|
pmiddend/fcppt
|
9f437acbb10258e6df6982a550213a05815eb2be
|
[
"BSL-1.0"
] | null | null | null |
// Copyright Carl Philipp Reh 2009 - 2018.
// 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 FCPPT_MATH_MATRIX_HAS_DIM_HPP_INCLUDED
#define FCPPT_MATH_MATRIX_HAS_DIM_HPP_INCLUDED
#include <fcppt/math/size_type.hpp>
#include <fcppt/math/detail/dim_matches.hpp>
#include <fcppt/math/matrix/object_fwd.hpp>
#include <fcppt/config/external_begin.hpp>
#include <type_traits>
#include <fcppt/config/external_end.hpp>
namespace fcppt
{
namespace math
{
namespace matrix
{
/**
\brief Metafunction to check if a static matrix has the specified dimensions
\ingroup fcpptmathmatrix
\tparam Matrix A fcppt::math::matrix::object type
\tparam R The static row count
\tparam C The static column count
*/
template<
typename Matrix,
fcppt::math::size_type R,
fcppt::math::size_type C
>
struct has_dim;
template<
typename T,
fcppt::math::size_type R,
fcppt::math::size_type C,
typename S,
fcppt::math::size_type DR,
fcppt::math::size_type DC
>
struct has_dim<
fcppt::math::matrix::object<
T,
R,
C,
S
>,
DR,
DC
>
:
std::conjunction<
fcppt::math::detail::dim_matches<
DR,
R
>,
fcppt::math::detail::dim_matches<
DC,
C
>
>
{
};
}
}
}
#endif
| 16.25
| 76
| 0.719231
|
pmiddend
|
2a4634de99fe9c2e51c1b7786e27d524d5bf7fe6
| 6,482
|
cpp
|
C++
|
test/stream.cpp
|
jspaaks/cuda-wrapper
|
66262b819d55814d35cdb88a7eb9ab3b67fadaf0
|
[
"BSD-3-Clause"
] | null | null | null |
test/stream.cpp
|
jspaaks/cuda-wrapper
|
66262b819d55814d35cdb88a7eb9ab3b67fadaf0
|
[
"BSD-3-Clause"
] | null | null | null |
test/stream.cpp
|
jspaaks/cuda-wrapper
|
66262b819d55814d35cdb88a7eb9ab3b67fadaf0
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright (C) 2020 Jaslo Ziska
*
* This file is part of cuda-wrapper.
*
* This software may be modified and distributed under the terms of the
* 3-clause BSD license. See accompanying file LICENSE for details.
*/
#define BOOST_TEST_MODULE stream
#include <boost/test/unit_test.hpp>
#include <algorithm>
#include <functional>
#include <random>
#include <cmath>
#include <cuda_wrapper/cuda_wrapper.hpp>
#include "test.hpp"
static const size_t BLOCKS = 4096;
static const size_t THREADS = 128;
extern cuda::function<void (double const*, double const*, double*)> kernel_add;
/*
* Both vectors with input numbers and the results are copied asynchronously.
* In addition both kernels are launched asynchronously.
*/
BOOST_AUTO_TEST_CASE(normal) {
using cuda::memory::device::vector;
namespace host = cuda::memory::host;
// create second function object from kernel_add
cuda::function<void (double const*, double const*, double*)> kernel_add2 = kernel_add;
// create two streams (both with default flags)
cuda::stream s1, s2(CU_STREAM_DEFAULT);
// streams should both be empty
BOOST_CHECK(s1.query() == true);
BOOST_CHECK(s2.query() == true);
cuda::config dim(BLOCKS, THREADS);
host::vector<double> h_a(BLOCKS * THREADS);
host::vector<double> h_b(h_a.size());
host::vector<double> h_c(h_a.size());
host::vector<double> h_d(h_a.size());
vector<double> d_a(h_a.size());
vector<double> d_b(h_a.size());
vector<double> d_c(h_a.size());
vector<double> d_d(h_a.size());
// create random number generator
std::default_random_engine gen;
std::uniform_real_distribution<double> rand(0, 1);
// generate random numbers
std::generate(h_a.begin(), h_a.end(), std::bind(rand, std::ref(gen)));
std::generate(h_b.begin(), h_b.end(), std::bind(rand, std::ref(gen)));
// copy data from host to device
// both vectors are copied asynchronously in two different streams
// copy the first vector in stream s1
cuda::copy_async(h_a.begin(), h_a.end(), d_a.begin(), s1);
// stream s1 should now be busy
BOOST_CHECK(s1.query() == false);
// copy the second vector in stream s2
cuda::copy_async(h_b.begin(), h_b.end(), d_b.begin(), s2);
// both streams should be busy
BOOST_CHECK(s1.query() == false);
BOOST_CHECK(s2.query() == false);
// wait for both copies to be complete
s1.synchronize();
s2.synchronize();
// both streams should be empty
BOOST_CHECK(s1.query() == true);
BOOST_CHECK(s2.query() == true);
// configure kernels (with two different streams)
kernel_add.configure(dim.grid, dim.block, s1);
kernel_add2.configure(dim.grid, dim.block, s2);
// launch kernel (in stream s1)
kernel_add(d_a, d_b, d_c);
// stream s1 should now be busy
BOOST_CHECK(s1.query() == false);
// launch kernel (in stream s2)
kernel_add2(d_a, d_b, d_d);
// both streams should now be busy
BOOST_CHECK(s1.query() == false);
BOOST_CHECK(s2.query() == false);
// calculate the result on the host
std::vector<double> result(h_a.size());
std::transform(h_a.begin(), h_a.end(), h_b.begin(), result.begin(), std::plus<double>());
// wait for kernels to finish (if they haven't already)
s1.synchronize();
s2.synchronize();
// both streams should be empty
BOOST_CHECK(s1.query() == true);
BOOST_CHECK(s2.query() == true);
// copy back result from device to host in stream s1
cuda::copy_async(d_c.begin(), d_c.end(), h_c.begin(), s1);
// stream s1 should now be busy
BOOST_CHECK(s1.query() == false);
// copy back result from device to host in stream s2
cuda::copy_async(d_d.begin(), d_d.end(), h_d.begin(), s2);
// both streams should now be busy
BOOST_CHECK(s1.query() == false);
BOOST_CHECK(s2.query() == false);
// wait for asynchronous copy to be finished
s1.synchronize();
s2.synchronize();
// both streams should now be empty
BOOST_CHECK(s1.query() == true);
BOOST_CHECK(s2.query() == true);
// check results
BOOST_CHECK_EQUAL_COLLECTIONS(result.begin(), result.end(), h_c.begin(), h_c.end());
BOOST_CHECK_EQUAL_COLLECTIONS(result.begin(), result.end(), h_d.begin(), h_d.end());
}
BOOST_AUTO_TEST_CASE(attach)
{
// create second function object from kernel_add
cuda::function<void (double const*, double const*, double*)> kernel_add2 = kernel_add;
// create two streams
cuda::stream s1;
cuda::stream s2;
// streams should both be empty
BOOST_CHECK(s1.query() == true);
BOOST_CHECK(s2.query() == true);
cuda::config dim(BLOCKS, THREADS);
// create vectors with managed memory
cuda::vector<double> a(BLOCKS * THREADS);
cuda::vector<double> b(a.size());
cuda::vector<double> c(a.size());
cuda::vector<double> d(a.size());
// attach data to stream s1
// a is not attached because it will be accessed by both streams s1 and s2
s1.attach(b.data());
s1.attach(c.data());
// attach data to stream s2
s2.attach(d.data());
// create random number generator
std::default_random_engine gen;
std::uniform_real_distribution<double> rand(0, 1);
// generate random numbers
std::generate(a.begin(), a.end(), std::bind(rand, std::ref(gen)));
std::generate(b.begin(), b.end(), std::bind(rand, std::ref(gen)));
// configure kernels (with two different streams)
kernel_add.configure(dim.grid, dim.block, s1);
kernel_add2.configure(dim.grid, dim.block, s2);
// launch kernel (in stream s1)
kernel_add(a, b, c);
// stream s1 should now be busy
BOOST_CHECK(s1.query() == false);
// launch kernel (in stream s2)
kernel_add2(a, b, d);
// both streams should now be busy
BOOST_CHECK(s1.query() == false);
BOOST_CHECK(s2.query() == false);
// calculate the results on the host
std::vector<double> result(a.size());
std::transform(a.begin(), a.end(), b.begin(), result.begin(), std::plus<double>());
// wait for kernels to finish (if they haven't already)
s1.synchronize();
s2.synchronize();
// both streams should be empty
BOOST_CHECK(s1.query() == true);
BOOST_CHECK(s2.query() == true);
// check results
BOOST_CHECK_EQUAL_COLLECTIONS(result.begin(), result.end(), c.begin(), c.end());
BOOST_CHECK_EQUAL_COLLECTIONS(result.begin(), result.end(), d.begin(), d.end());
}
| 30.28972
| 93
| 0.655199
|
jspaaks
|
2a46e9dac0560f9dbb529cb6ed9db8b91bb34790
| 44,789
|
cpp
|
C++
|
src/AM/CatalogInstance.cpp
|
fsaintjacques/cstore
|
3300a81c359c4a48e13ad397e3eb09384f57ccd7
|
[
"BSD-2-Clause"
] | 14
|
2016-07-11T04:08:09.000Z
|
2022-03-11T05:56:59.000Z
|
src/AM/CatalogInstance.cpp
|
ibrarahmad/cstore
|
3300a81c359c4a48e13ad397e3eb09384f57ccd7
|
[
"BSD-2-Clause"
] | null | null | null |
src/AM/CatalogInstance.cpp
|
ibrarahmad/cstore
|
3300a81c359c4a48e13ad397e3eb09384f57ccd7
|
[
"BSD-2-Clause"
] | 13
|
2016-06-01T10:41:15.000Z
|
2022-01-06T09:01:15.000Z
|
/* Copyright (c) 2005, Regents of Massachusetts Institute of Technology,
* Brandeis University, Brown University, and University of Massachusetts
* Boston. 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 Massachusetts Institute of Technology,
* Brandeis University, Brown University, or University of
* Massachusetts Boston 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 <iostream>
#include "CatalogInstance.h"
#include "CatalogInstanceBDB.h"
const string CatalogInstance::PROJECTIONS[ /*25*/ ]
= { "lineitem", "orders", "customers", "typetest",
"Q1_projection", "Q2_projection", "Q3_projection",
"Q4_projection", "Q5_projection", "Q6_projection", "Q7_projection",
"D1.data", "D1.shipdate", "D1.suppkey", "D2.data", "D3.data",
"D3.custkey", "D4.data", "D5.data", "D6.data", "D7.data",
"D9.data", "D8_projection", "D10_projection",
"MO_D6.data" };
const string CatalogInstance::TYPE_NAMES[ /*5*/ ]
= { "", "INTEGER", "FLOAT", "STRING", "STAR" };
const string CatalogInstance::COMPRESSION_NAMES[ /*7*/ ]
= { "", "COMPRESSION_TYPE1", "COMPRESSION_TYPE1A",
"COMPRESSION_TYPE2", "COMPRESSION_TYPE3",
"COMPRESSION_TYPE3A", "COMPRESSION_TYPE4" };
using namespace std;
CatalogInstance* CatalogInstance::catalog = NULL;
bool CatalogInstance::gottenCat = false;
DbEnv* CatalogInstance::dbEnv = NULL;
vector<AM*> *CatalogInstance::allocatedAMs = new vector<AM*>();
vector<Node*> *CatalogInstance::allocatedNodes = new vector<Node*>();
string MetaColumn::toString()
{
string mcs = "";
mcs += ("\tColumn: " + _name + ( isSorted() ? " is sorted " : " is NOT sorted" ) + " compression: " + CatalogInstance::COMPRESSION_NAMES[ _compression ] + " dataType: " + CatalogInstance::TYPE_NAMES[_dataType] + " indexes " + ( _numIndexes == 2 ? "2" : "1" ) + " fileName " + _fileName + " filenamWOS " + _fileNameWos + "\n");
return mcs;
}
MetaColumn::MetaColumn( string colName, int dataType, int compType,
int colNum, bool isSK )
{
_name = colName; //string(colName.c_str());
_compression = compType;
_dataType = dataType;
_columnNumber = colNum;
//_fileName = colName + "_mini.dat";
_fileName = colName;
_rosFileName = colName + "_full.ros";
//_fileNameWos = colName + "_full.wos";
_colPosition = colNum;
_isSortKey = isSK;
if ( _compression == COMPRESSION_TYPE2 ||
_compression == COMPRESSION_TYPE4 )
_sorted = false;
else
_sorted = true;
if ( _sorted )
_numIndexes = 2;
else
_numIndexes = 1;
}
void MetaColumn::setColCount( int cc )
{
_colCount = cc;
}
bool MetaProjection::appendTuple( char *tuple )
{
empty = false;
// curr_wos_page doubles up as page counter
int curr_offset = tuple_size*wos_tuple_count -
(WOS_PAGE_SIZE / tuple_size)*curr_wos_page * tuple_size;
//cout << " space " << tuple_size*wos_tuple_count << " WOS PAGE blah " << (WOS_PAGE_SIZE / tuple_size)*curr_wos_page << endl;
if ( curr_offset > WOS_PAGE_SIZE - tuple_size ) // spill into new page
{
curr_wos_page++;
/*if ( _col )
{
for ( int i = 0; i < num_fields+1; i++ )
wos_col_data[ i ].push_back( (char*)malloc( WOS_PAGE_SIZE ) );
}
else*/
wos_data.push_back( (char*)malloc( WOS_PAGE_SIZE ) ); //new char( WOS_PAGE_SIZE ) );
//new_page_counter++;
curr_offset = 0;
}
//else
{
//memcpy( fudge+ curr_offset, tuple, 4 );
/*if ( _col )
for ( int i = 0; i < num_fields+1; i++ )
{
//cout << " TRYING FOR i = " << i << endl;
memcpy( (char*)(wos_col_data[i][ curr_wos_page ])+curr_offset, tuple+i*sizeof(int), tuple_size );
}
else*/
memcpy( (char*)(wos_data[ curr_wos_page ])+curr_offset, tuple, tuple_size );
}
//char *blah = new char[ 100 ];
//char *bleh = new char[ 4 ];
//memcpy( bleh, &wos_tuple_count, 4 );
// update indices on timestamp and sort key
// current version will assume that first column (second value) is the skey
PageWriter::placeRecord( _db_storage_key, tuple, sizeof(int),
(char*)&wos_tuple_count, sizeof(int) );
PageWriter::placeRecord( _db_sort_key, tuple+sizeof(int), sizeof(int),
(char*)&wos_tuple_count, sizeof(int) );
wos_tuple_count++;
int z;
memcpy(&z, tuple+sizeof(int), sizeof(int) );
//cout << " second value " << z << " Placed " << wos_tuple_count << "th tuple " << " page is " << curr_wos_page << " offset " << curr_offset << " page size " << WOS_PAGE_SIZE << endl<< endl;
return true;
}
void MetaColumn::setColPosition( int cp )
{
_colPosition = cp;
}
/*
MetaColumn::MetaColumn( char *col, int dataType, int compType )
{w w
cout << "This constructor is active " << endl;
string s(col);
//_name = s;
MetaColumn::MetaColumn( s, dataType, compType );
//cout << " Ended constructor " << endl << " name? " << _name << " s? " << s << " col " << col << endl << endl;
}
*/
MetaColumn::~MetaColumn()
{
}
string MetaColumn::getName()
{
return _name;
}
bool MetaColumn::isSorted()
{
return _sorted;
}
int MetaColumn::getIndex()
{
return _columnNumber;
}
int MetaColumn::getEncodingType()
{
return _compression;
}
int MetaColumn::getDataType()
{
return _dataType;
}
MetaProjection::MetaProjection( string projName )
{
//cout << " MetaProjection " << _name << " created " << endl;
_name = RUNTIME_DATA + projName;
columnCounter = 0;
_primaryColumn = NULL;
// Moving shared BDB items.
// This is shared stuff for different WOS cursors.
// ROS BDB files are a separate issue!
_db_storage_key = new Db( NULL, 0 );
_db_sort_key = new Db( NULL, 0 );
// Sort key is not guaranteed to be unique. StorageKey has to be.
_db_sort_key->set_flags( DB_DUP );
// assume integers
_db_storage_key->set_bt_compare( ROSAM::compare_int );
_db_storage_key->set_error_stream( &cout );
// do not assume integers on sort key because key is multiple
// fields mended together.
// Actually, we do assume that sort key is now an integer
// but that will change, so segment should ask the catalog and
// decide on this here.
_db_sort_key->set_bt_compare( ROSAM::compare_int );
_db_sort_key->set_error_stream( &cout );
_db_storage_key->set_cachesize( 0, SMALL_CACHE_SIZE, 1 ); // 5Mb cache
//this is very much an open question. There is certainly no need
// to use a large page because we're only indexing storagekey to
// position. Data is stored outside of BDB.
_db_storage_key->set_pagesize( 4096 );
_db_sort_key->set_cachesize( 0, SMALL_CACHE_SIZE, 1 ); // 5Mb cache
_db_sort_key->set_pagesize( 4096 );
string store_k = (_name + ".storage_key");
if ( (_db_storage_key->open( NULL, (store_k.c_str()),NULL,
DB_BTREE, DB_CREATE, 0664) != 0 ))
cerr << "Failed to open table " << (store_k) << endl;
string sort_k = (_name + ".sort_key");
if ((_db_sort_key->open( NULL, (sort_k.c_str()), NULL,
DB_BTREE, DB_CREATE, 0664) != 0 ) )
cerr << "Failed to open table " << (sort_k) << endl;
}
ROSAM *MetaColumn::getROSAM()
{
// ROSAM
cout << " Create and return a ROSAM " << _fileName << " indexes " << _numIndexes << endl;
ROSAM *rosam = new ROSAM( _fileName+
(_fileName.rfind( ".ros" ) == string::npos ? ".ros" : ""),
_numIndexes);
CatalogInstance::allocatedAMs->push_back( rosam );
return ( rosam );
}
WOSAM *MetaColumn::getWOSAM()
{
// maybe can use _numIndices, but not about to check.
//
cout << " Parameters are (PLEASE check): total columns " << _colCount << " field " << _colPosition << endl;
WOSAM *wosam = new WOSAM( _fileNameWos, 2, _colCount, _colPosition );
CatalogInstance::allocatedAMs->push_back( wosam );
return (wosam);
}
MetaProjection::~MetaProjection()
{
for ( map<string, MetaColumn*>::iterator iter = _columns.begin();
iter != _columns.end(); iter++ )
delete iter->second;
}
void MetaProjection::addColumn( MetaColumn *mc )
{
/*
assert ( _columns.find( mc->getName() ) ==
_columns.end() );
*/
if ( !_primaryColumn )
_primaryColumn = mc;
// This assumes that columns are added in the order of
// the schema!
columnPosition = columnCounter;
columnCounter++;
_columns[ mc->getName() ] = mc;
_columnNameInOrder.push_back(mc->getName());
}
vector<string> *MetaProjection::getAllColumns()
{
vector<string> *cols = new vector<string>();
for ( map<string, MetaColumn*>::iterator iter = _columns.begin();
iter != _columns.end(); iter++ ){
cols->push_back( (iter->second)->getName() );
}
return cols;
}
vector<string> *MetaProjection::getAllColumnsInOrder()
{
vector<string> *cols = new vector<string>;
for (int i=0; i<(int) _columnNameInOrder.size(); i++)
{
cols->push_back(_columnNameInOrder[i]);
}
return cols;
}
vector<string> *MetaProjection::getSortOrderColumns()
{
vector<string> *cols = new vector<string>();
/*
for ( map<string, MetaColumn*>::iterator iter = _columns.begin();
iter != _columns.end(); iter++ )
{
if ( (iter->second)->isSortKey() )
cols->push_back( (iter->second)->getName() );
}
*/
for (int i=0; i<(int) _columnNameInOrder.size(); i++)
{
if ( _columns[_columnNameInOrder[i]]->isSortKey() )
cols->push_back(_columnNameInOrder[i]);
}
return cols;
}
MetaColumn* MetaProjection::getColumn( string name )
{
// This is inefficient and should change.
// column count is set every time getColumn is called.
//_columns[ name ]->setColCount( columnCounter );
// Again, hacky. But will only do this once on a get:
/* if ( !wos_data.size() )
{
int num_fields = columnCounter;
tuple_size = (num_fields+1)*sizeof(int);
//cout << "CatalogInstance:: Temporary message, col count is? " << num_fields << endl;
wos_data.push_back( (char*)malloc( WOS_PAGE_SIZE ) );
// Load pre-existing WOS.
// opening file for reading fails miserably if the file
// does not exist. So instead of non-existing file will
// make an empty one by touch.
system( ("touch " + _name + ".wos.TUPLES").c_str() );
FILE *wosfd = fopen((_name + ".wos.TUPLES").c_str(), "r");
char tuple[ (num_fields+1)*sizeof(int) ];
int counter = 0;
while (fread(tuple, 1, (num_fields+1)*sizeof(int), wosfd))
{
//cout << " READ TUPLE from file, count " << a << " REATD " << b << endl;
appendTuple( tuple );
counter++;
}
//if ( counter > 0 )
cout << " Loaded " << counter << " tuples from " + _name << endl;
}
*/
return _columns[ name ];
}
string MetaProjection::getPrimaryColumnName()
{
return _primaryColumn->getName();
}
string MetaProjection::getName()
{
return _name;
}
string MetaProjection::toString()
{
cout << " To String in MetaProjection " << endl;
//_name = NULL;
cout << " NAME " << _name << endl;
string mps = ("Projection: " + _name + ":\n\n");
for ( map<string, MetaColumn*>::iterator iter = _columns.begin();
iter != _columns.end(); iter++ )
mps += iter->second->toString();
return (mps + "\n");
}
CatalogInstance::CatalogInstance()
{
//original constructor loads projections/columns from static arrays
//now replaced with method getCatalogInstanceFromBDB()
//+
cout << "\tloading catalog from BDB files..." << endl;
this->loadCatalogFromBDB();
//-
//this->loadCatalog();
}
void CatalogInstance::loadCatalogFromBDB()
{
string bdbProjection = RUNTIME_DATA + CSTORE_SYSTABLE_PROJECTION;
PROJECTION_REC projRec;
BDBFile* f1 = new BDBFile(bdbProjection);
int rtrnCode = f1->open();
if (rtrnCode != 0) throw UnexpectedException("CatalogInstance: open projection file error");
void* v = f1->readFirstRec(&projRec.projectionID, sizeof(projRec.projectionID));
while (v != NULL) {
memcpy(&projRec, v, sizeof(PROJECTION_REC));
/*
cout.fill(' ');
cout.width(25);
cout.setf(ios_base::left , ios_base::adjustfield);
cout.setf(ios_base::dec, ios_base::basefield);
cout << projRec.projectionName
<< projRec.projectionID
<< projRec.tableID
<< projRec.primaryColumnID << endl;
*/
string sProj = projRec.projectionName;
_projections[ sProj ] = new MetaProjection( sProj );
v = f1->readNextRec();
}
int totProjection = f1->getRecordCount();
//----- loading column -----
COLUMN_REC colRec;
string bdbColumn = RUNTIME_DATA + CSTORE_SYSTABLE_COLUMN;
BDBFile* f2 = new BDBFile(bdbColumn, true);
//secondary index
string bdbColumnAK = RUNTIME_DATA + CSTORE_SYSTABLE_COLUMN_AK;
BDBFile* f3 = new BDBFile(bdbColumnAK, false);
rtrnCode = f2->dbHandle->associate(NULL, f3->dbHandle, altKeyCallBackProjectionID, 0);
if (rtrnCode != 0) throw UnexpectedException("CatalogInstance: associate error");
rtrnCode = f2->open();
if (rtrnCode != 0) throw UnexpectedException("CatalogInstance: open column file error");
rtrnCode = f3->open();
if (rtrnCode != 0) throw UnexpectedException("CatalogInstance: open column file error");
for (int i = 1; i <= totProjection; ++i) {
//cout << "\n\nread column(s) with projectionID " << i << endl;
int* pI = &i;
v = f3->readRec(pI, sizeof(int));
while (v != NULL) {
memcpy(&colRec, v, sizeof(COLUMN_REC));
/*
cout.fill(' ');
cout.width(25);
cout.setf(ios_base::left, ios_base::adjustfield);
cout.setf(ios_base::dec, ios_base::basefield);
cout << colRec.columnName;
cout << colRec.columnID;
cout << colRec.projectionID;
cout << colRec.dataType;
cout << colRec.compressionType;
cout << colRec.isStorageKey << endl;
*/
//get projection name
void* vdata = f1->readRec(pI, sizeof(projRec.projectionID));
if (vdata != NULL) {
memcpy(&projRec, vdata, sizeof(PROJECTION_REC));
} else {
throw UnexpectedException("CatalogInstance: read projection name error");
}
string s = projRec.projectionName;
//adding column to the container
_projections[ s ]->addColumn ( new MetaColumn(
colRec.columnName,
colRec.dataType,
colRec.compressionType,
colRec.columnID,
colRec.isStorageKey) );
v = f3->readNextRec(pI, sizeof(int));
}
}
//WOSManager* wm = new WOSManager( string(D6_DATA_WOS)+string(".dummy.dummy"), 2, 8 );
WOSManager* wm = new WOSManager( string(D6_DATA_WOS), 2, 8 );
//WOSManager* wm = new WOSManager( "RuntimeData/D10_dummy.wos", 2, 8 );
_wosManagers[ wm->getFileName() ] = wm;
_wosManagers[ "D6.data" ] = wm;
_wosManagers[ "Q1_projection" ] = wm;
_wosManagers[ "Q1_l_shipdate" ] = wm; // This is a slight naming hack
// a getWOS call that comes for Q1_l_shipdate column will return same
// as D6_DATA_WOS, because it is the same. Naming should be general
// most likely, the calling code should be fixed to substitute the
// projection name (?)
_wosManagers[ "Q1_l_shipdate" ] = wm;
_wosManagers[ "Q1_l_suppkey" ] = wm;
_wosManagers[ "Q1_l_orderkey" ] = wm;
_wosManagers[ "Q1_l_partkey" ] = wm;
_wosManagers[ "Q1_l_linenumber" ] = wm;
_wosManagers[ "Q1_l_quantity" ] = wm;
_wosManagers[ "Q1_l_extendedprice" ] = wm;
_wosManagers[ "Q1_l_returnflag" ] = wm;
_wosManagers[ "D6_l_shipdate" ] = wm;
_wosManagers[ "Q2_projection" ] = wm;
_wosManagers[ "Q2_l_suppkey" ] = wm;
_wosManagers[ "Q2_l_shipdate" ] = wm;
_wosManagers[ "Q2_l_orderkey" ] = wm;
_wosManagers[ "Q2_l_partkey" ] = wm;
_wosManagers[ "Q2_l_linenumber" ] = wm;
_wosManagers[ "Q2_l_quantity" ] = wm;
_wosManagers[ "Q2_l_extendedprice" ] = wm;
_wosManagers[ "Q2_l_returnflag" ] = wm;
_wosManagers[ "Q3_l_suppkey" ] = wm;
_wosManagers[ "Q3_l_shipdate" ] = wm;
_wosManagers[ "Q3_l_orderkey" ] = wm;
_wosManagers[ "Q3_l_partkey" ] = wm;
_wosManagers[ "Q3_l_linenumber" ] = wm;
_wosManagers[ "Q3_l_quantity" ] = wm;
_wosManagers[ "Q3_l_extendedprice" ] = wm;
_wosManagers[ "Q3_l_returnflag" ] = wm;
_wosManagers[ "D6_l_suppkey" ] = wm;
_wosManagers[ "D6_l_shipdate" ] = wm;
/*
D7.data.ros/wos:
(o_orderdate, l_suppkey, l_shipdate | o_orderdate, l_suppkey)
~= D2 from paper
*/
wm = new WOSManager( (string(D7_DATA_WOS)), 2, 3 );
_wosManagers[ wm->getFileName() ] = wm;
_wosManagers[ "D7.data" ] = wm;
_wosManagers[ "Q4_o_orderdate" ] = wm;
_wosManagers[ "Q5_o_orderdate" ] = wm;
_wosManagers[ "Q6_o_orderdate" ] = wm;
_wosManagers[ "Q4_l_shipdate" ] = wm;
_wosManagers[ "Q5_l_shipdate" ] = wm;
_wosManagers[ "Q6_l_shipdate" ] = wm;
_wosManagers[ "Q5_l_suppkey" ] = wm;
_wosManagers[ "Q6_l_suppkey" ] = wm;
wm = new WOSManager( D9_DATA_WOS, 2, 3 );
_wosManagers[ wm->getFileName() ] = wm;
_wosManagers[ "D9.data" ] = wm;
_wosManagers[ "Q7_c_nationkey" ] = wm;
_wosManagers[ "Q7_l_returnflag" ] = wm;
_wosManagers[ "Q7_l_extendedprice" ] = wm;
//wm = new WOSManager( "RuntimeData/D8_dummy.wos", 2, 8 );
wm = new WOSManager( D8_DATA_WOS, 2, 3 );
_wosManagers[ wm->getFileName() ] = wm;
_wosManagers[ "D8_projection" ] = wm;
_wosManagers[ "D8_orderdate" ] = wm;
_wosManagers[ "D8_custkey" ] = wm;
//wm = new WOSManager( "RuntimeData/D10_dummy.wos", 2, 2 );
wm = new WOSManager( D10_DATA_WOS, 2, 2 );
_wosManagers[ wm->getFileName() ] = wm;
_wosManagers[ "D10_projection" ] = wm;
_wosManagers[ "D10_nationkey" ] = wm;
_wosManagers[ "D10_custkey" ] = wm;
wm = new WOSManager( RUNTIME_DATA "MO_D6.data.wos", 2, 8 );
_wosManagers[ wm->getFileName() ] = wm;
_wosManagers[ "MO_D6.data" ] = wm;
_wosManagers[ "MO_D6_l_suppkey" ] = wm;
_wosManagers[ "MO_D6_l_shipdate" ] = wm;
_wosManagers[ "MO_D6_l_orderkey" ] = wm;
_wosManagers[ "MO_D6_l_partkey" ] = wm;
_wosManagers[ "MO_D6_l_linenumber"] = wm;
_wosManagers[ "MO_D6_l_returnflag" ] = wm;
_wosManagers[ "MO_D6_l_extendedprice"] = wm;
_wosManagers[ "MO_D6_l_quantity" ] = wm;
vector<string> *vec = NULL;
v = f1->readFirstRec(projRec.projectionName, sizeof(projRec.projectionName));
while (v != NULL) {
memcpy(&projRec, v, sizeof(PROJECTION_REC));
string s = projRec.projectionName;
vec = _projections[ s ]->getAllColumns();
for ( vector<string>::iterator iter = vec->begin(); iter != vec->end(); iter++ )
{
_allColumns[ (*iter) ] = _projections[ s ]->getColumn( (*iter) );
}
delete vec;
v = f1->readNextRec();
}
f1->close();
f3->close();
f2->close();
delete f1;
delete f2;
delete f3;
}
//original constructor load catalog from static arrays
void CatalogInstance::loadCatalog()
{
for ( unsigned int i = 0; i < sizeof( PROJECTIONS )/sizeof( string ); i ++ )
{
//cout << " PROJE " << PROJECTIONS[i] << endl;
_projections[ PROJECTIONS[i] ] = new MetaProjection( PROJECTIONS[i] );
}
_projections[ "lineitem" ]->addColumn
( new MetaColumn( "l_shipdate", TYPE_INTEGER, COMPRESSION_TYPE1, 1, true) );
_projections[ "lineitem" ]->addColumn
( new MetaColumn( "l_orderkey", TYPE_INTEGER, COMPRESSION_TYPE4, 2, false ) );
_projections[ "lineitem" ]->addColumn
( new MetaColumn( "l_returnflag", TYPE_STRING, COMPRESSION_TYPE4, 3, false ) );
_projections[ "lineitem" ]->addColumn
( new MetaColumn( "l_extendedprice", TYPE_INTEGER, COMPRESSION_TYPE4, 4, false ) );
_projections[ "lineitem" ]->addColumn
( new MetaColumn( "l_suppkey", TYPE_INTEGER, COMPRESSION_TYPE4, 5, false ) );
_projections[ "orders" ]->addColumn
( new MetaColumn( "o_orderdate", TYPE_INTEGER, COMPRESSION_TYPE1, 1, true) );
_projections[ "orders" ]->addColumn
( new MetaColumn( "o_orderkey", TYPE_INTEGER, COMPRESSION_TYPE4, 2, false ) );
_projections[ "orders" ]->addColumn
( new MetaColumn( "o_custkey", TYPE_INTEGER, COMPRESSION_TYPE4, 3, false ) );
_projections[ "customers" ]->addColumn
( new MetaColumn( "c_nationkey", TYPE_INTEGER, COMPRESSION_TYPE1, 1, true ) );
_projections[ "customers" ]->addColumn
( new MetaColumn( "c_custkey", TYPE_INTEGER, COMPRESSION_TYPE4, 2,false ) );
_projections[ "typetest" ]->addColumn
( new MetaColumn( "t_int", TYPE_INTEGER, COMPRESSION_TYPE4, 1, true ));
_projections[ "typetest" ]->addColumn
( new MetaColumn( "t_float", TYPE_FLOAT, COMPRESSION_TYPE4, 2, false ));
_projections[ "typetest" ]->addColumn
( new MetaColumn( "t_string", TYPE_STRING, COMPRESSION_TYPE4, 3, false ) );
_projections[ "Q1_projection" ]->addColumn
( new MetaColumn( "Q1_l_shipdate", TYPE_INTEGER, COMPRESSION_TYPE1, 1, true ) );
_projections["Q1_projection"]->addColumn
( new MetaColumn( "Q1_l_suppkey", TYPE_INTEGER, COMPRESSION_TYPE4,2, true ) );
_projections["Q1_projection"]->addColumn
( new MetaColumn( "Q1_l_orderkey", TYPE_INTEGER, COMPRESSION_TYPE4,3, false ) );
_projections["Q1_projection"]->addColumn
( new MetaColumn( "Q1_l_partkey", TYPE_INTEGER, COMPRESSION_TYPE4,4, false ) );
_projections["Q1_projection"]->addColumn
( new MetaColumn( "Q1_l_linenumber", TYPE_INTEGER, COMPRESSION_TYPE4,5, false ) );
_projections["Q1_projection"]->addColumn
( new MetaColumn( "Q1_l_quantity", TYPE_INTEGER, COMPRESSION_TYPE4,6, false ) );
_projections["Q1_projection"]->addColumn
( new MetaColumn( "Q1_l_extendedprice",TYPE_INTEGER, COMPRESSION_TYPE4,7, false ));
_projections["Q1_projection"]->addColumn
( new MetaColumn( "Q1_l_returnflag", TYPE_STRING, COMPRESSION_TYPE4,8, false ) );
_projections["Q2_projection"]->addColumn
( new MetaColumn("Q2_l_shipdate", TYPE_INTEGER, COMPRESSION_TYPE1, 1, true ) );
_projections["Q2_projection"]->addColumn
( new MetaColumn("Q2_l_suppkey", TYPE_INTEGER, COMPRESSION_TYPE4, 2, false ) );
_projections["Q2_projection"]->addColumn
( new MetaColumn( "Q2_l_orderkey", TYPE_INTEGER, COMPRESSION_TYPE4,3, false ) );
_projections["Q2_projection"]->addColumn
( new MetaColumn( "Q2_l_partkey", TYPE_INTEGER, COMPRESSION_TYPE4,4, false ) );
_projections["Q2_projection"]->addColumn
( new MetaColumn( "Q2_l_linenumber", TYPE_INTEGER, COMPRESSION_TYPE4,5, false ) );
_projections["Q2_projection"]->addColumn
( new MetaColumn( "Q2_l_quantity", TYPE_INTEGER, COMPRESSION_TYPE4,6, false ) );
_projections["Q2_projection"]->addColumn
( new MetaColumn( "Q2_l_extendedprice",TYPE_INTEGER, COMPRESSION_TYPE4,7, false ));
_projections["Q2_projection"]->addColumn
( new MetaColumn( "Q2_l_returnflag", TYPE_STRING, COMPRESSION_TYPE4,8, false ) );
_projections["Q3_projection"]->addColumn
( new MetaColumn("Q3_l_shipdate", TYPE_INTEGER, COMPRESSION_TYPE1,1, true) );
_projections["Q3_projection"]->addColumn
( new MetaColumn("Q3_l_suppkey", TYPE_INTEGER, COMPRESSION_TYPE4,2, true ) );
_projections["Q3_projection"]->addColumn
( new MetaColumn( "Q3_l_orderkey", TYPE_INTEGER, COMPRESSION_TYPE4,3, false ) );
_projections["Q3_projection"]->addColumn
( new MetaColumn( "Q3_l_partkey", TYPE_INTEGER, COMPRESSION_TYPE4,4, false ) );
_projections["Q3_projection"]->addColumn
( new MetaColumn( "Q3_l_linenumber", TYPE_INTEGER, COMPRESSION_TYPE4,5, false ) );
_projections["Q3_projection"]->addColumn
( new MetaColumn( "Q3_l_quantity", TYPE_INTEGER, COMPRESSION_TYPE4,6, false ) );
_projections["Q3_projection"]->addColumn
( new MetaColumn( "Q3_l_extendedprice",TYPE_INTEGER, COMPRESSION_TYPE4,7, false ));
_projections["Q3_projection"]->addColumn
( new MetaColumn( "Q3_l_returnflag", TYPE_STRING, COMPRESSION_TYPE4,8, false ) );
_projections["Q4_projection"]->addColumn
( new MetaColumn("Q4_o_orderdate", TYPE_INTEGER, COMPRESSION_TYPE1,1, true ) );
// not used in the query, inserted for continuity. Can probably not have
// this entry at all (second column)
// Big mistake. Q4_l_shipdate is in fact 2nd column in the data file!
// Never mind, this was fixed.
_projections["Q4_projection"]->addColumn
( new MetaColumn("Q4_l_suppkey", TYPE_INTEGER, COMPRESSION_TYPE4,2, false ));
_projections["Q4_projection"]->addColumn
( new MetaColumn("Q4_l_shipdate", TYPE_INTEGER, COMPRESSION_TYPE4,3, false ) );
_projections["Q5_projection"]->addColumn
( new MetaColumn("Q5_o_orderdate", TYPE_INTEGER, COMPRESSION_TYPE1,1, true ) );
_projections["Q5_projection"]->addColumn
( new MetaColumn("Q5_l_suppkey", TYPE_INTEGER, COMPRESSION_TYPE4,2, true ));
_projections["Q5_projection"]->addColumn
( new MetaColumn( "Q5_l_shipdate", TYPE_INTEGER, COMPRESSION_TYPE4,3, false ) );
_projections["Q6_projection"]->addColumn
( new MetaColumn("Q6_o_orderdate", TYPE_INTEGER, COMPRESSION_TYPE1,1, true ) );
_projections["Q6_projection"]->addColumn
( new MetaColumn("Q6_l_suppkey", TYPE_INTEGER, COMPRESSION_TYPE4,2, true ) );
_projections["Q6_projection"]->addColumn
( new MetaColumn("Q6_l_shipdate" , TYPE_INTEGER, COMPRESSION_TYPE4,3, false ) );
_projections["Q7_projection"]->addColumn
( new MetaColumn("Q7_l_returnflag", TYPE_INTEGER, COMPRESSION_TYPE1,1, true ) );
_projections["Q7_projection"]->addColumn
( new MetaColumn("Q7_l_extendedprice",TYPE_INTEGER, COMPRESSION_TYPE4, 2, false ));
_projections["Q7_projection"]->addColumn
( new MetaColumn("Q7_c_nationkey", TYPE_INTEGER, COMPRESSION_TYPE4, 3, false ) );
_projections["D1.data"]->addColumn
( new MetaColumn("Q7_l_returnflag", TYPE_INTEGER, COMPRESSION_TYPE1,1, true ) );
/*
These files can be found in the
wosrosplay
directory on sorrel.
D6.data.ros/wos:
(l_shipdate, l_suppkey, l_orderkey, l_partkey, l_linenumber, l_quantity,
l_extendedprice, l_returnflag | l_shipdate, l_suppkey)
*/
_projections["D6.data"]->addColumn
( new MetaColumn( "D6_l_shipdate", TYPE_INTEGER, COMPRESSION_TYPE1,1, true ) );
_projections["D6.data"]->addColumn
( new MetaColumn( "D6_l_suppkey", TYPE_INTEGER, COMPRESSION_TYPE4,2, true ) );
_projections["D6.data"]->addColumn
( new MetaColumn( "D6_l_orderkey", TYPE_INTEGER, COMPRESSION_TYPE4,3, false ) );
_projections["D6.data"]->addColumn
( new MetaColumn( "D6_l_partkey", TYPE_INTEGER, COMPRESSION_TYPE4,4, false ) );
_projections["D6.data"]->addColumn
( new MetaColumn( "D6_l_linenumber", TYPE_INTEGER, COMPRESSION_TYPE4,5, false ) );
_projections["D6.data"]->addColumn
( new MetaColumn( "D6_l_quantity", TYPE_INTEGER, COMPRESSION_TYPE4,6, false ) );
_projections["D6.data"]->addColumn
( new MetaColumn( "D6_l_extendedprice",TYPE_INTEGER, COMPRESSION_TYPE4,7, false ));
_projections["D6.data"]->addColumn
( new MetaColumn( "D6_l_returnflag", TYPE_STRING, COMPRESSION_TYPE4,8, false ) );
//WOSManager* wm = new WOSManager( string(D6_DATA_WOS)+string(".dummy.dummy"), 2, 8 );
WOSManager* wm = new WOSManager( string(D6_DATA_WOS), 2, 8 );
//WOSManager* wm = new WOSManager( "RuntimeData/D10_dummy.wos", 2, 8 );
_wosManagers[ wm->getFileName() ] = wm;
_wosManagers[ "D6.data" ] = wm;
_wosManagers[ "Q1_projection" ] = wm;
_wosManagers[ "Q1_l_shipdate" ] = wm; // This is a slight naming hack
// a getWOS call that comes for Q1_l_shipdate column will return same
// as D6_DATA_WOS, because it is the same. Naming should be general
// most likely, the calling code should be fixed to substitute the
// projection name (?)
_wosManagers[ "Q1_l_shipdate" ] = wm;
_wosManagers[ "Q1_l_suppkey" ] = wm;
_wosManagers[ "Q1_l_orderkey" ] = wm;
_wosManagers[ "Q1_l_partkey" ] = wm;
_wosManagers[ "Q1_l_linenumber" ] = wm;
_wosManagers[ "Q1_l_quantity" ] = wm;
_wosManagers[ "Q1_l_extendedprice" ] = wm;
_wosManagers[ "Q1_l_returnflag" ] = wm;
_wosManagers[ "D6_l_shipdate" ] = wm;
_wosManagers[ "Q2_projection" ] = wm;
_wosManagers[ "Q2_l_suppkey" ] = wm;
_wosManagers[ "Q2_l_shipdate" ] = wm;
_wosManagers[ "Q2_l_orderkey" ] = wm;
_wosManagers[ "Q2_l_partkey" ] = wm;
_wosManagers[ "Q2_l_linenumber" ] = wm;
_wosManagers[ "Q2_l_quantity" ] = wm;
_wosManagers[ "Q2_l_extendedprice" ] = wm;
_wosManagers[ "Q2_l_returnflag" ] = wm;
_wosManagers[ "Q3_l_suppkey" ] = wm;
_wosManagers[ "Q3_l_shipdate" ] = wm;
_wosManagers[ "Q3_l_orderkey" ] = wm;
_wosManagers[ "Q3_l_partkey" ] = wm;
_wosManagers[ "Q3_l_linenumber" ] = wm;
_wosManagers[ "Q3_l_quantity" ] = wm;
_wosManagers[ "Q3_l_extendedprice" ] = wm;
_wosManagers[ "Q3_l_returnflag" ] = wm;
_wosManagers[ "D6_l_suppkey" ] = wm;
_wosManagers[ "D6_l_shipdate" ] = wm;
/*
D7.data.ros/wos:
(o_orderdate, l_suppkey, l_shipdate | o_orderdate, l_suppkey)
~= D2 from paper
*/
_projections[ "D7.data" ]->addColumn
( new MetaColumn( "D7_o_orderdate", TYPE_INTEGER, COMPRESSION_TYPE1,1, true ));
_projections[ "D7.data" ]->addColumn
( new MetaColumn( "D7_l_suppkey", TYPE_INTEGER, COMPRESSION_TYPE4,2, true ));
_projections[ "D7.data" ]->addColumn
( new MetaColumn( "D7_l_shipdate", TYPE_INTEGER, COMPRESSION_TYPE4,3, false ));
wm = new WOSManager( (string(D7_DATA_WOS)), 2, 3 );
_wosManagers[ wm->getFileName() ] = wm;
_wosManagers[ "D7.data" ] = wm;
_wosManagers[ "Q4_o_orderdate" ] = wm;
_wosManagers[ "Q5_o_orderdate" ] = wm;
_wosManagers[ "Q6_o_orderdate" ] = wm;
_wosManagers[ "Q4_l_shipdate" ] = wm;
_wosManagers[ "Q5_l_shipdate" ] = wm;
_wosManagers[ "Q6_l_shipdate" ] = wm;
_wosManagers[ "Q5_l_suppkey" ] = wm;
_wosManagers[ "Q6_l_suppkey" ] = wm;
_projections[ "D9.data" ]->addColumn
( new MetaColumn( "D9_o_orderdate", TYPE_INTEGER, COMPRESSION_TYPE1,1, true ));
_projections[ "D9.data" ]->addColumn
( new MetaColumn( "D9_l_suppkey", TYPE_INTEGER, COMPRESSION_TYPE4,2, true ));
_projections[ "D9.data" ]->addColumn
( new MetaColumn( "D9_l_shipdate", TYPE_INTEGER, COMPRESSION_TYPE4,3, false ));
wm = new WOSManager( D9_DATA_WOS, 2, 3 );
_wosManagers[ wm->getFileName() ] = wm;
_wosManagers[ "D9.data" ] = wm;
_wosManagers[ "Q7_c_nationkey" ] = wm;
_wosManagers[ "Q7_l_returnflag" ] = wm;
_wosManagers[ "Q7_l_extendedprice" ] = wm;
_projections[ "D8_projection" ]->addColumn
( new MetaColumn( "D8_orderdate", TYPE_INTEGER, COMPRESSION_TYPE4,1, true ));
_projections[ "D8_projection" ]->addColumn
( new MetaColumn( "D8_custkey", TYPE_INTEGER, COMPRESSION_TYPE4,2, false ));
_projections[ "D10_projection" ]->addColumn
( new MetaColumn( "D10_custkey", TYPE_INTEGER, COMPRESSION_TYPE4,1, true ));
_projections[ "D10_projection" ]->addColumn
( new MetaColumn( "D10_nationkey", TYPE_INTEGER, COMPRESSION_TYPE4,2, false ));
//wm = new WOSManager( "RuntimeData/D8_dummy.wos", 2, 8 );
wm = new WOSManager( D8_DATA_WOS, 2, 3 );
_wosManagers[ wm->getFileName() ] = wm;
_wosManagers[ "D8_projection" ] = wm;
_wosManagers[ "D8_orderdate" ] = wm;
_wosManagers[ "D8_custkey" ] = wm;
//wm = new WOSManager( "RuntimeData/D10_dummy.wos", 2, 2 );
wm = new WOSManager( D10_DATA_WOS, 2, 2 );
_wosManagers[ wm->getFileName() ] = wm;
_wosManagers[ "D10_projection" ] = wm;
_wosManagers[ "D10_nationkey" ] = wm;
_wosManagers[ "D10_custkey" ] = wm;
/*
MERGE OUT STUFF
*/
_projections["MO_D6.data"]->addColumn
( new MetaColumn( "MO_D6_l_shipdate", TYPE_INTEGER, COMPRESSION_TYPE1,1, true ) );
_projections["MO_D6.data"]->addColumn
( new MetaColumn( "MO_D6_l_suppkey", TYPE_INTEGER, COMPRESSION_TYPE4,2, true ) );
_projections["MO_D6.data"]->addColumn
( new MetaColumn( "MO_D6_l_orderkey", TYPE_INTEGER, COMPRESSION_TYPE4,3, false ) );
_projections["MO_D6.data"]->addColumn
( new MetaColumn( "MO_D6_l_partkey", TYPE_INTEGER, COMPRESSION_TYPE4,4, false ) );
_projections["MO_D6.data"]->addColumn
( new MetaColumn( "MO_D6_l_linenumber", TYPE_INTEGER, COMPRESSION_TYPE4,5, false ) );
_projections["MO_D6.data"]->addColumn
( new MetaColumn( "MO_D6_l_quantity", TYPE_INTEGER, COMPRESSION_TYPE4,6, false ) );
_projections["MO_D6.data"]->addColumn
( new MetaColumn( "MO_D6_l_extendedprice",TYPE_INTEGER, COMPRESSION_TYPE4,7, false ));
_projections["MO_D6.data"]->addColumn
( new MetaColumn( "MO_D6_l_returnflag", TYPE_STRING, COMPRESSION_TYPE4,8, false ) );
wm = new WOSManager( RUNTIME_DATA "MO_D6.data.wos", 2, 8 );
_wosManagers[ wm->getFileName() ] = wm;
_wosManagers[ "MO_D6.data" ] = wm;
_wosManagers[ "MO_D6_l_suppkey" ] = wm;
_wosManagers[ "MO_D6_l_shipdate" ] = wm;
_wosManagers[ "MO_D6_l_orderkey" ] = wm;
_wosManagers[ "MO_D6_l_partkey" ] = wm;
_wosManagers[ "MO_D6_l_linenumber"] = wm;
_wosManagers[ "MO_D6_l_returnflag" ] = wm;
_wosManagers[ "MO_D6_l_extendedprice"] = wm;
_wosManagers[ "MO_D6_l_quantity" ] = wm;
vector<string> *vec = NULL;
for ( unsigned int i = 0; i < sizeof( PROJECTIONS )/sizeof( string ); i ++ )
{
vec = _projections[ PROJECTIONS[i] ]->getAllColumns();
for ( vector<string>::iterator iter = vec->begin(); iter != vec->end(); iter++ )
{
_allColumns[ (*iter) ] = _projections[ PROJECTIONS[i] ]->getColumn( (*iter) );
}
delete vec;
}
}
CatalogInstance::~CatalogInstance()
{
for ( map<string, MetaProjection*>::iterator iter = _projections.begin();
iter != _projections.end(); iter++ )
{
if ( iter->second == NULL )
delete iter->second;
}
}
bool CatalogInstance::isSorted( string projName, string colName )
{
if ( _projections.find( projName ) == _projections.end() )
return false;
if ( _allColumns.find( colName ) == _allColumns.end() )
{
// throw exception
return false;
}
return _projections[ projName ]->getColumn( colName )->isSorted();
}
int CatalogInstance::getColumnIndex( string projName, string colName )
{
if ( _projections.find( projName ) == _projections.end() )
return -1;
if ( _allColumns.find( colName ) == _allColumns.end() )
{
// throw exception
cerr << "Column " << colName << " does not seem to be a column " << endl;
return -1;
}
return _projections[ projName ]->getColumn( colName )->getIndex();
}
bool CatalogInstance::isSorted( string colName )
{
if ( _allColumns.find( colName ) == _allColumns.end() )
{
// throw exception
return false;
}
return _allColumns[ colName ]->isSorted();
}
bool CatalogInstance::isValidProjection(string projName)
{
return ( _projections.find( projName ) != _projections.end() );
}
bool CatalogInstance::isColumnOf(string projName, string colName)
{
if ( isValidProjection( projName ) )
return ( _allColumns.find( colName ) != _allColumns.end() );
return false;
}
vector<string> *CatalogInstance::getSortOrderColumns( string projName )
{
return _projections[ projName ]->getSortOrderColumns();
}
string CatalogInstance::getPrimaryColumnName( string projName )
{
if ( _projections.find( projName ) == _projections.end() )
return NULL;
return _projections[ projName ]->getPrimaryColumnName();
}
int CatalogInstance::getEncodingType( string projName, string colName )
{
if ( _projections.find( projName ) == _projections.end() )
return -1;
if ( _allColumns.find( colName ) == _allColumns.end() )
{
// throw exception
return -1;
}
return _projections[ projName ]->getColumn( colName )->getEncodingType();
}
/*void CatalogInstance::setAlias( string alias ) {
m_sAlias = alias;
}
*/
string CatalogInstance::toString()
{
string cis = "";
for ( map<string, MetaProjection*>::iterator iter = _projections.begin();
iter != _projections.end(); iter++ )
cis += iter->second->toString();
return cis;
}
ROSAM *CatalogInstance::getROSAM( string projName, string colName)
{
if ( _projections.find( projName ) == _projections.end() )
{
cerr << " Looking for proj (and not finding it) " << projName << " name " << colName << endl;
return NULL;
}
if ( _allColumns.find( colName ) == _allColumns.end() )
{
// throw exception
cerr << " Looking for proj (and not finding it) " << projName << " name " << colName << endl;
return NULL;
}
return _projections[ projName ]->getColumn( colName )->getROSAM();
}
ROSAM *CatalogInstance::getROSAM( string colName)
{
//cout << "CATALOG: get ROSAM for " << colName << endl;
if ( _allColumns.find( colName ) == _allColumns.end() )
{
cerr << "Catalog: no such column: " << colName << endl;
// throw exception
return NULL;
}
return _allColumns[ colName ]->getROSAM();
}
WOSAM *CatalogInstance::getWOSAM( string projName, string colName)
{
// cout << " CALL on " << projName << " col name " << colName << " position " << _allColumns[ colName ]->getColumnPosition() << endl;
return _wosManagers[ (CatalogInstance::stripOffDirectory( projName )/* + string(".wos")*/) ]->getWOSAM( _allColumns[ colName ]->getColumnPosition() );
/*if ( _projections.find( projName ) == _projections.end() )
return NULL;
if ( _allColumns.find( colName ) == _allColumns.end() )
{
// throw exception
return NULL;
}
//cout << "Temporary Notice: getting proj " << projName << " column " << colName << endl;
return _projections[ projName ]->getColumn( colName )->getWOSAM();
*/
}
WOSAM *CatalogInstance::getWOSAM( string colName)
{
if ( _allColumns.find( colName ) == _allColumns.end() )
{
// throw exception
return NULL;
}
//cout << "Temporary Notice: getting proj column " << colName << endl;
return _allColumns[ colName ]->getWOSAM();
}
WOSAM *CatalogInstance::getWOSAM( string colName, int colIndex )
{
//cout << "Temporary Notice: getting proj column " << (CatalogInstance::stripOffDirectory( colName )) << " from " << colName << endl;
return _wosManagers[ (CatalogInstance::stripOffDirectory( colName ) /*+ string(".wos")*/) ]->getWOSAM( colIndex );
}
DVAM *CatalogInstance::getDVAM( string colName, bool ros )
{
//cout << "Temporary Notice: getting proj column " << (CatalogInstance::stripOffDirectory( colName ) + string(".wos")) << endl;
return _wosManagers[ (CatalogInstance::stripOffDirectory( colName ) /*+ string(".wos")*/) ]->getDVAM( ros );
}
WOSManager *CatalogInstance::getWOSManager( string colName )
{
return _wosManagers[ (CatalogInstance::stripOffDirectory( colName ) /*+ string(".wos")*/) ];
}
WOSAM *CatalogInstance::getWOSAM( int colIndex )
{
return _wosManagers[ "D6.data.wos" ]->getWOSAM( colIndex );
}
int CatalogInstance::getColumnType( string colName )
{
if ( _allColumns.find( colName ) == _allColumns.end() )
{
throw UnexpectedException("No such column exists");
}
return _allColumns[ colName ]->getDataType();
}
int CatalogInstance::getColumnType( string projName, string colName )
{
if ( _projections.find( projName ) == _projections.end() )
{
return 0;
}
return _projections[ projName ]->getColumn(colName)->getDataType();
}
string CatalogInstance::stripOffDirectory( string fName )
{
string s = fName;
int loc = s.rfind("/", string::npos);
if(s.rfind("/", string::npos) != string::npos)
return s.substr(loc+1);
else
return fName;
}
static bool getCat() {
return CatalogInstance::gottenCat;
}
static CatalogInstance* getCatalog()
{
if ( !CatalogInstance::catalog ) {
CatalogInstance::catalog = new CatalogInstance();
CatalogInstance::gottenCat=true;
}
return CatalogInstance::catalog;
}
vector<string> *CatalogInstance::getColumnNames( string projName )
{
if ( _projections.find( projName ) == _projections.end() )
{
cout << " Failed to find column names for " << projName << endl;
return new vector<string>();
}
return _projections[ projName ]->getAllColumns();
}
vector<string> *CatalogInstance::getColumnNamesInOrder( string projName )
{
if ( _projections.find( projName ) == _projections.end() )
{
cout << " Failed to find column names for " << projName << endl;
return new vector<string>();
}
return _projections[ projName ]->getAllColumnsInOrder();
}
void CatalogInstance::disposeOfWOS( WOSAM *wos )
{
cout << " Dispose of " << wos->getTableName() << endl;
//this migth become more complicated eventually.
if ( wos )
delete wos;
cout << "End Dispose" << endl;
}
void CatalogInstance::disposeOfROS( ROSAM *ros )
{
cout << " Dispose of " << ros->getTableName() << endl;
if ( ros )
delete ros;
cout << "End Dispose" << endl;
}
void CatalogInstance::disposeOfDV ( DVAM *dvam )
{
cout << " Dispose of " << dvam->getTableName() << endl;
/*if ( dvam )
delete dvam;*/
}
list<TVariable*> CatalogInstance::getColumns()
{
vector<string> *cols;
if( m_listTuples.empty() )
{
cols = _projections[ m_sProjName ]->getAllColumns();
for ( vector<string>::iterator iter = cols->begin();
iter != cols->end(); iter++ )
m_listTuples.push_front( getCol( *iter ) );
delete cols;
}
return m_listTuples;
}
CatalogInstance* CatalogInstance::getCatalog()
{
if ( !CatalogInstance::catalog )
{
CatalogInstance::catalog = new CatalogInstance();
CatalogInstance::gottenCat=true;
/*
try
{
CatalogInstance::dbEnv = new DbEnv( 0 );
CatalogInstance::dbEnv->open( ".DbCache",
DB_INIT_MPOOL | DB_CREATE| DB_PRIVATE,
0644 ); // DB_THREAD Not necessary yet?
//CatalogInstance::dbEnv->set_verbose( DB_VERB_REPLICATION, true );
//CatalogInstance::dbEnv->set_cachesize( 0, (10*CACHE_SIZE), 10 );
CatalogInstance::dbEnv->set_cachesize(2, 524288000, 3 );
CatalogInstance::dbEnv->set_data_dir( "." );
CatalogInstance::dbEnv->set_tmp_dir( ".tempDB" );
// DB and other code goes here
}
catch(DbException &e)
{
// DB error handling goes here
cout << "CatalogInstance::getCatalog(), exception: -" << e.what() << " -" << e.get_errno() << "-" << endl;
//char *a = new char[ 100 ];
//bzero( a, 100 );
//CatalogInstance::dbEnv->get_home( (const char **)&a );
//cout << " DB " << string( a ) << endl;
}
*/
}
return CatalogInstance::catalog;
}
void CatalogInstance::deallocAMs()
{
for ( vector<AM*>::iterator iter = CatalogInstance::allocatedAMs->begin();
iter != CatalogInstance::allocatedAMs->end(); iter++ )
{
//uncomment this line will cause exception if you're deleting DVAM
//cout << " deleting AM " << (*iter)->getColumnName() << endl;
delete (*iter);
}
CatalogInstance::allocatedAMs->clear();
}
bool CatalogInstance::getCat() {
return CatalogInstance::gottenCat;
}
TVariable* CatalogInstance::getCol( string name )
{
TVariable* lpTVariable = TVariable::create( m_projection, name, _projections[ m_sProjName ]->getColumn( name )->getDataType() );
return lpTVariable;
}
// Nga: for plan node memory management
void CatalogInstance::addAllocatedNode(Node* lpNode)
{
CatalogInstance::allocatedNodes->push_back(lpNode);
}
void CatalogInstance::deallocNodes()
{
for ( vector<Node*>::iterator iter = CatalogInstance::allocatedNodes->begin();
iter != CatalogInstance::allocatedNodes->end(); iter++ )
{
cout << " deleting Node " << (*iter)->getNodeID() << endl;
delete (*iter);
}
CatalogInstance::allocatedNodes->clear();
}
| 33.549813
| 330
| 0.666458
|
fsaintjacques
|
2a513e5ab77fc89931a095b7e07b743e045f68ce
| 2,807
|
hpp
|
C++
|
src/sprite.hpp
|
gulrak/lostcolonies
|
ba47bbb3b642fbde9c87670666d02f288cfe7984
|
[
"MIT"
] | 1
|
2022-02-03T20:42:24.000Z
|
2022-02-03T20:42:24.000Z
|
src/sprite.hpp
|
gulrak/lostcolonies
|
ba47bbb3b642fbde9c87670666d02f288cfe7984
|
[
"MIT"
] | null | null | null |
src/sprite.hpp
|
gulrak/lostcolonies
|
ba47bbb3b642fbde9c87670666d02f288cfe7984
|
[
"MIT"
] | null | null | null |
#pragma once
#include <raylib.h>
#include <algorithm>
#include <vector>
#include "raymath.hpp"
struct Sprite
{
enum Type { Unused, Alien, Player, ColonyShip, AlienShot, AlienBomb, PlayerShot, DotParticle };
Type _type{Unused};
Vector2 _pos{};
Vector2 _velocity{};
Rectangle _sprite{};
Rectangle _sprite2{};
Color _col{WHITE};
float _age{0};
Texture* _texture{nullptr};
Image* _image{nullptr};
Vector2 _posAlt{-1000,-1000};
std::vector<Vector3> _flightPath{};
void update(float dt_s)
{
_pos.x += _velocity.x * dt_s;
_pos.y += _velocity.y * dt_s;
//if(!_flightPath)
}
void draw(bool drawAlternative = false) const
{
if(drawAlternative && _sprite2.width) {
DrawTextureRec(*_texture, _sprite2, _pos, _col);
}
else {
DrawTextureRec(*_texture, _sprite, _pos, _col);
}
}
void draw(Vector2 offset, bool drawAlternative = false) const
{
if(offset.y + _pos.y + _sprite.height > 0 && offset.y + _pos.y < 400) {
if(drawAlternative && _sprite2.width) {
DrawTextureRec(*_texture, _sprite2, offset + _pos, _col);
}
else {
DrawTextureRec(*_texture, _sprite, offset + _pos, _col);
}
}
}
Vector2 screenToSpriteCoordinates(const Vector2& screenCoordinates) const
{
return Vector2Add(Vector2Subtract(screenCoordinates, _pos), {_sprite.x, _sprite.y});
}
bool isCollidingRect(const Sprite& other)
{
return CheckCollisionRecs({_pos.x, _pos.y, _sprite.width, _sprite.height}, {other._pos.x, other._pos.y, other._sprite.width, other._sprite.height});
}
bool isColliding(const Sprite& other)
{
if(!isCollidingRect(other)) {
return false;
}
Rectangle overlap{};
overlap.x = std::max(_pos.x, other._pos.x);
overlap.width = std::min(_pos.x + _sprite.width, other._pos.x + other._sprite.width) - overlap.x;
overlap.y = std::max(_pos.y, other._pos.y);
overlap.height = std::min(_pos.y + _sprite.height, other._pos.y + other._sprite.height) - overlap.y;
for (int x = overlap.x; x < int(overlap.x + overlap.width); ++x) {
for (int y = overlap.y; y < int(overlap.y + overlap.height); ++y) {
auto pos1 = screenToSpriteCoordinates({float(x), float(y)});
auto c1 = GetImageColor(*_image, pos1.x, pos1.y);
auto pos2 = other.screenToSpriteCoordinates({float(x), float(y)});
auto c2 = GetImageColor(*_image, pos2.x, pos2.y);
if (c1.a > 128 && c2.a > 128) {
return true;
}
}
}
return false;
}
};
| 32.639535
| 156
| 0.576772
|
gulrak
|
2a55eca06e121661d59d4d4095424ee625cddfb3
| 6,514
|
cpp
|
C++
|
source/console/Console.cpp
|
mkapusnik/duel6r
|
1e5ed50035b1c2878622c9129ee8255a5abf9227
|
[
"BSD-3-Clause"
] | 12
|
2015-06-21T14:57:53.000Z
|
2021-11-30T23:32:27.000Z
|
source/console/Console.cpp
|
mkapusnik/duel6r
|
1e5ed50035b1c2878622c9129ee8255a5abf9227
|
[
"BSD-3-Clause"
] | 37
|
2015-01-04T18:21:13.000Z
|
2020-11-02T15:50:38.000Z
|
source/console/Console.cpp
|
mkapusnik/duel6r
|
1e5ed50035b1c2878622c9129ee8255a5abf9227
|
[
"BSD-3-Clause"
] | 10
|
2015-03-12T23:31:31.000Z
|
2020-02-25T23:19:44.000Z
|
/*
* Copyright (c) 2006, Ondrej Danek (www.ondrej-danek.net)
* 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 Ondrej Danek 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.
*/
/*
Projekt: Konzole
Popis: Hlavni funkce
*/
#include <stdlib.h>
#include <string.h>
#include "ConsoleException.h"
#include "Console.h"
namespace Duel6 {
Console::Console(Uint32 flags) {
visible = false;
insert = false;
curpos = 0;
inputscroll = 0;
this->flags = flags;
histcnt = 0;
histscroll = 0;
width = CON_DEF_WIDTH;
show = CON_DEF_SHOWLAST;
text.resize(CON_TEXT_SIZE);
clear();
printLine("==========================");
printLine(CON_Lang("Console -- author O.Danek"));
printLine(CON_Format(CON_Lang("Version {0}")) << CON_VERSION);
printLine("==========================");
}
Console::~Console() {
vars.clear();
cmds.clear();
aliases.clear();
}
void Console::clear() {
bufpos = 0;
scroll = 0;
buffull = false;
memset(&text[0], '\n', CON_TEXT_SIZE);
}
Console &Console::print(const std::string &str) {
for (size_t pos = 0; pos < str.length(); ++pos) {
char tx = str[pos];
switch (tx) {
case '\n':
text[bufpos++] = tx;
break;
case '\t':
for (int i = 0; i < CON_TAB_WIDTH; i++, bufpos++) {
text[bufpos % CON_TEXT_SIZE] = ' ';
}
break;
default:
if (tx >= ' ') {
text[bufpos++] = tx;
}
break;
}
if (bufpos >= CON_TEXT_SIZE) {
bufpos -= CON_TEXT_SIZE;
buffull = true;
}
}
scroll = 0;
return *this;
}
Console &Console::printLine(const std::string &str) {
print(str);
print("\n");
return *this;
}
void Console::verifyRegistration(const std::string &proc, const std::string &name, bool isNull) {
if (name.empty()) {
D6_THROW(ConsoleException, CON_Format(CON_Lang("{0} : cannot register empty name")) << proc);
}
if (findCommand(name) != nullptr || findVar(name) != nullptr || findAlias(name) != nullptr) {
D6_THROW(ConsoleException,
CON_Format(CON_Lang("{0} : name \"{1}\" is already registered")) << proc << name);
}
if (isNull) {
D6_THROW(ConsoleException,
CON_Format(CON_Lang("{0} : attempt to register \"{1}\" with null pointer")) << proc << name);
}
}
void Console::registerCommand(const std::string &name, Command command) {
verifyRegistration(CON_Lang("Command registration"), name, !command);
CommandRecord newCommand(name, command);
// Zaradi novy prikaz tak, aby byly setridene podle abecedy
size_t position = 0;
for (const CommandRecord &cmd : cmds) {
if (cmd.getName().compare(name) > 0) {
break;
}
++position;
}
cmds.insert(cmds.begin() + position, newCommand);
if (hasFlag(RegInfoFlag)) {
print(CON_Format(CON_Lang("Command registration: \"{0}\" has been successful\n")) << name);
}
}
void Console::registerAlias(const std::string &name, const std::string &cmd) {
AliasRecord *a = findAlias(name);
if (a == nullptr) {
verifyRegistration(CON_Lang("Alias registration"), name, false);
AliasRecord newAlias(name, cmd);
// Zaradi novy alias tak, aby byly setridene podle abecedy
size_t position = 0;
for (const AliasRecord &alias : aliases) {
if (alias.getName().compare(name) > 0) {
break;
}
++position;
}
aliases.insert(aliases.begin() + position, newAlias);
} else {
a->setCommand(cmd);
}
if (hasFlag(RegInfoFlag)) {
print(CON_Format(CON_Lang("Alias registration: \"{0}\" as \"{1}\" has been successful\n")) << name << cmd);
}
}
Console::CommandRecord *Console::findCommand(const std::string &name) {
for (CommandRecord &command : cmds) {
if (command.getName() == name) {
return &command;
}
}
return nullptr;
}
Console::AliasRecord *Console::findAlias(const std::string &name) {
for (AliasRecord &alias : aliases) {
if (alias.getName() == name) {
return &alias;
}
}
return nullptr;
}
void Console::setLast(int sl) {
show = sl > 1 ? sl : 2;
}
const Uint8 *Console::getText(Size &bufPos, bool &bufFull) const {
bufPos = bufpos;
bufFull = buffull;
return &text[0];
}
}
| 32.08867
| 119
| 0.558336
|
mkapusnik
|
3987183d1e817ce5ac116084fdd44af061869c3d
| 4,342
|
cpp
|
C++
|
DTLiving/core/effect/video_two_pass_effect.cpp
|
danjiang/DTLiving
|
c0008b7b7f94a392a514b112c0b97564d7d8f12a
|
[
"MIT"
] | 21
|
2020-04-04T13:41:45.000Z
|
2022-02-19T23:38:36.000Z
|
DTLiving/core/effect/video_two_pass_effect.cpp
|
danjiang/DTLiving
|
c0008b7b7f94a392a514b112c0b97564d7d8f12a
|
[
"MIT"
] | 9
|
2020-02-02T10:42:05.000Z
|
2022-02-28T18:50:48.000Z
|
DTLiving/core/effect/video_two_pass_effect.cpp
|
danjiang/DTLiving
|
c0008b7b7f94a392a514b112c0b97564d7d8f12a
|
[
"MIT"
] | 3
|
2020-10-19T08:28:38.000Z
|
2021-11-29T09:24:42.000Z
|
//
// video_two_pass_effect.cpp
// DTLiving
//
// Created by Dan Jiang on 2020/4/15.
// Copyright © 2020 Dan Thought Studio. All rights reserved.
//
#include "video_two_pass_effect.h"
#include "video_texture_cache.h"
namespace dtliving {
namespace effect {
VideoTwoPassEffect::VideoTwoPassEffect(std::string name)
: VideoEffect(name) {
}
void VideoTwoPassEffect::LoadShaderSource(std::string vertex_shader_source1, std::string fragment_shader_source1,
std::string vertex_shader_source2, std::string fragment_shader_source2) {
VideoEffect::LoadShaderSource(vertex_shader_source1, fragment_shader_source1);
program2_ = new ShaderProgram();
program2_->CompileSource(vertex_shader_source2.c_str(), fragment_shader_source2.c_str());
}
void VideoTwoPassEffect::LoadUniform() {
VideoEffect::LoadUniform();
a_position2_ = program2_->AttributeLocation("a_position");
a_texcoord2_ = program2_->AttributeLocation("a_texcoord");
u_texture2_ = program2_->UniformLocation("u_texture");
}
void VideoTwoPassEffect::Render(VideoFrame input_frame, VideoFrame output_frame, std::vector<GLfloat> positions, std::vector<GLfloat> texture_coordinates) {
// first pass
glBindTexture(GL_TEXTURE_2D, input_frame.texture_name);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
auto texture = VideoTextureCache::GetInstance()->FetchTexture(input_frame.width,
input_frame.height);
texture->Lock();
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture->get_texture_name(), 0);
program_->Use();
auto clear_color = get_clear_color();
glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w);
glClear(GL_COLOR_BUFFER_BIT);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, input_frame.texture_name);
glUniform1i(u_texture_, 0);
glEnableVertexAttribArray(a_position_);
glVertexAttribPointer(a_position_,
2,
GL_FLOAT,
GL_FALSE,
0,
positions.data());
glEnableVertexAttribArray(a_texcoord_);
glVertexAttribPointer(a_texcoord_,
2,
GL_FLOAT,
GL_FALSE,
0,
texture_coordinates.data());
BeforeDrawArrays(output_frame.width, output_frame.height, 0);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
// second pass
glBindTexture(GL_TEXTURE_2D, texture->get_texture_name());
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, output_frame.texture_name, 0);
program2_->Use();
glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w);
glClear(GL_COLOR_BUFFER_BIT);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture->get_texture_name());
glUniform1i(u_texture2_, 0);
glEnableVertexAttribArray(a_position2_);
glVertexAttribPointer(a_position2_,
2,
GL_FLOAT,
GL_FALSE,
0,
positions.data());
glEnableVertexAttribArray(a_texcoord2_);
glVertexAttribPointer(a_texcoord2_,
2,
GL_FLOAT,
GL_FALSE,
0,
texture_coordinates.data());
BeforeDrawArrays(output_frame.width, output_frame.height, 1);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
texture->UnLock();
}
}
}
| 34.460317
| 156
| 0.647167
|
danjiang
|
3987220c58035f6fabb2b13fb7b7bb47751ddbf7
| 3,962
|
cpp
|
C++
|
src/ffmpeg_io/avio_reading.cpp
|
zzu-andrew/ffmpeg_doc
|
dd9c3333b2aa00cf57e55fe2bd0d29503f16ab55
|
[
"Apache-2.0"
] | null | null | null |
src/ffmpeg_io/avio_reading.cpp
|
zzu-andrew/ffmpeg_doc
|
dd9c3333b2aa00cf57e55fe2bd0d29503f16ab55
|
[
"Apache-2.0"
] | null | null | null |
src/ffmpeg_io/avio_reading.cpp
|
zzu-andrew/ffmpeg_doc
|
dd9c3333b2aa00cf57e55fe2bd0d29503f16ab55
|
[
"Apache-2.0"
] | null | null | null |
//
// Created by andrew on 2020/12/13.
//
#include <iostream>
extern "C" {
#include <libavformat/avformat.h>
#include <libavutil/log.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avio.h>
#include <libavutil/file.h>
#include <cstdio>
}
using namespace std;
// 为mmap buffer定义一个结构体指针用户管理数据
struct buffer_data {
uint8_t *ptr;
size_t size; // size left in the buffer
};
static int ReadPacket(void *pOpaque, uint8_t *pBuff, int bufferSize) {
auto *bd = (struct buffer_data *) pOpaque;
// #define FFMIN(a,b) ((a) > (b) ? (b) : (a))
bufferSize = FFMIN(bufferSize, bd->size);
if (!bufferSize) {
cout << "ptr = " << bd->ptr << "size = " << bd->size << endl;
}
// 将音视频数据内部的data复制到buff中
memcpy(pBuff, bd->ptr, bufferSize);
bd->ptr += bufferSize;
bd->size -= bufferSize;
return bufferSize;
}
int main(int argc, char *argv[]) {
AVIOContext *pAvioCtx = nullptr;
uint8_t *pAvioCtxBuffer = nullptr;
size_t avioCtxBufferSize = 4096;
struct buffer_data bufferData = {nullptr, 0};
// 贯穿全局的context信息
AVFormatContext *pFmtCtx = nullptr;
// 设置日志等级
av_log_set_level(AV_LOG_DEBUG);
if (argc != 2) {
cout << "please input a reading file" << "argc = " << argc << endl;
return -1;
}
char *inputFileName = argv[1];
// 将文件进行内存映射
/*
* mmap() creates a new mapping in the virtual address space of the calling process. The starting address for the new mapping is specified in addr. The length argument specifies the length of
the mapping (which must be greater than 0).
If addr is NULL, then the kernel chooses the (page-aligned) address at which to create the mapping; this is the most portable method of creating a new mapping. If addr is not NULL, then the
kernel takes it as a hint about where to place the mapping; on Linux, the kernel will pick a nearby page boundary (but always above or equal to the value specified by
/proc/sys/vm/mmap_min_addr) and attempt to create the mapping there. If another mapping already exists there, the kernel picks a new address that may or may not depend on the hint. The ad‐
dress of the new mapping is returned as the result of the call.
* */
uint8_t *buffer = nullptr;
size_t buffer_size = 0;
int ret = av_file_map(inputFileName, &buffer, &buffer_size, 0, nullptr);
if (ret < 0) {
cout << "av_file_map failed" << "ret = " << ret << endl;
goto end;
}
// 记录 @av_file_map 中获取的文件内存映射的内容和长度
bufferData.ptr = buffer;
bufferData.size = buffer_size;
// Allocate an AVFormatContext.
pFmtCtx = avformat_alloc_context();
if (!pFmtCtx) {
ret = AVERROR(ENOMEM);
goto end;
}
pAvioCtxBuffer = (uint8_t *) av_malloc(avioCtxBufferSize);
if (!pAvioCtxBuffer) {
ret = AVERROR(ENOMEM);
goto end;
}
pAvioCtx = avio_alloc_context(pAvioCtxBuffer, avioCtxBufferSize, 0, &bufferData, &ReadPacket,
nullptr,nullptr);
if (!pAvioCtx) {
ret = AVERROR(ENOMEM);
goto end;
}
// 调用 avformat_open_input 之前,要是使用文件的音视频处理,这里需要提前进行初始化,然后再调用、
// avformat_open_input 打开对应的文件
pFmtCtx->pb = pAvioCtx;
ret = avformat_open_input(&pFmtCtx, nullptr, nullptr, nullptr);
if (ret < 0) {
cerr << "Could not open input!" << endl;
goto end;
}
ret = avformat_find_stream_info(pFmtCtx, nullptr);
if (ret < 0) {
cerr << "Could not find stream information!" << endl;
goto end;
}
av_dump_format(pFmtCtx, 0, inputFileName, 0);
cout << "avio reading demo success" << endl;
end:
avformat_close_input(&pFmtCtx);
if (pAvioCtxBuffer && !pAvioCtx)
av_freep(pAvioCtxBuffer);
if (pAvioCtx)
av_freep(&pAvioCtx->buffer);
avio_context_free(&pAvioCtx);
av_file_unmap(buffer, buffer_size);
return 0;
}
| 31.444444
| 199
| 0.636295
|
zzu-andrew
|
39873ae8de1ba67e9cd7c929aa0bbd5fd8502ba5
| 13,585
|
hpp
|
C++
|
include/poplar/compact_bonsai_trie.hpp
|
MatsuTaku/dynpdt_Correction
|
10605c1dc8ae6196741bee0e991935e8877b930a
|
[
"MIT"
] | 47
|
2018-02-24T09:56:24.000Z
|
2022-02-13T12:10:00.000Z
|
include/poplar/compact_bonsai_trie.hpp
|
MatsuTaku/dynpdt_Correction
|
10605c1dc8ae6196741bee0e991935e8877b930a
|
[
"MIT"
] | 4
|
2018-03-08T03:28:05.000Z
|
2021-09-29T06:38:25.000Z
|
include/poplar/compact_bonsai_trie.hpp
|
MatsuTaku/dynpdt_Correction
|
10605c1dc8ae6196741bee0e991935e8877b930a
|
[
"MIT"
] | 5
|
2018-03-07T06:34:43.000Z
|
2022-02-12T19:54:18.000Z
|
/**
* MIT License
*
* Copyright (c) 2018–2019 Shunsuke Kanda
*
* 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.
*/
#ifndef POPLAR_TRIE_COMPACT_BONSAI_TRIE_HPP
#define POPLAR_TRIE_COMPACT_BONSAI_TRIE_HPP
#include "bijective_hash.hpp"
#include "bit_vector.hpp"
#include "compact_hash_table.hpp"
#include "compact_vector.hpp"
#include "standard_hash_table.hpp"
namespace poplar {
template <uint32_t MaxFactor = 90, uint32_t Dsp1Bits = 4, class AuxCht = compact_hash_table<7>,
class AuxMap = standard_hash_table<>, class Hasher = bijective_hash::split_mix_hasher>
class compact_bonsai_trie {
static_assert(0 < MaxFactor and MaxFactor < 100);
static_assert(0 < Dsp1Bits and Dsp1Bits < 64);
public:
using this_type = compact_bonsai_trie<MaxFactor, Dsp1Bits, AuxCht, AuxMap, Hasher>;
using aux_cht_type = AuxCht;
using aux_map_type = AuxMap;
static constexpr uint64_t nil_id = UINT64_MAX;
static constexpr uint32_t min_capa_bits = 16;
static constexpr uint32_t dsp1_bits = Dsp1Bits;
static constexpr uint64_t dsp1_mask = (1ULL << dsp1_bits) - 1;
static constexpr uint32_t dsp2_bits = aux_cht_type::val_bits;
static constexpr uint32_t dsp2_mask = aux_cht_type::val_mask;
static constexpr auto trie_type_id = trie_type_ids::BONSAI_TRIE;
public:
compact_bonsai_trie() = default;
compact_bonsai_trie(uint32_t capa_bits, uint32_t symb_bits, uint32_t cht_capa_bits = 0) {
capa_size_ = size_p2{std::max(min_capa_bits, capa_bits)};
symb_size_ = size_p2{symb_bits};
max_size_ = static_cast<uint64_t>(capa_size_.size() * MaxFactor / 100.0);
hasher_ = Hasher{capa_size_.bits() + symb_size_.bits()};
table_ = compact_vector{capa_size_.size(), symb_size_.bits() + dsp1_bits};
aux_cht_ = aux_cht_type{capa_size_.bits(), cht_capa_bits};
}
~compact_bonsai_trie() = default;
uint64_t get_root() const {
assert(size_ != 0);
return 0;
}
void add_root() {
assert(size_ == 0);
size_ = 1;
}
uint64_t find_child(uint64_t node_id, uint64_t symb) const {
assert(node_id < capa_size_.size());
assert(symb < symb_size_.size());
if (size_ == 0) {
return nil_id;
}
auto [quo, mod] = decompose_(hasher_.hash(make_key_(node_id, symb)));
for (uint64_t i = mod, cnt = 1;; i = right_(i), ++cnt) {
if (i == get_root()) {
// because the root's dsp value is zero though it is defined
continue;
}
if (compare_dsp_(i, 0)) {
// this slot is empty
return nil_id;
}
if (compare_dsp_(i, cnt) and quo == get_quo_(i)) {
return i;
}
}
}
bool add_child(uint64_t& node_id, uint64_t symb) {
assert(node_id < capa_size_.size());
assert(symb < symb_size_.size());
auto [quo, mod] = decompose_(hasher_.hash(make_key_(node_id, symb)));
for (uint64_t i = mod, cnt = 1;; i = right_(i), ++cnt) {
// because the root's dsp value is zero though it is defined
if (i == get_root()) {
continue;
}
if (compare_dsp_(i, 0)) {
// this slot is empty
if (size_ == max_size_) {
return false; // needs to expand
}
update_slot_(i, quo, cnt);
++size_;
node_id = i;
return true;
}
if (compare_dsp_(i, cnt) and quo == get_quo_(i)) {
node_id = i;
return false; // already stored
}
}
}
std::pair<uint64_t, uint64_t> get_parent_and_symb(uint64_t node_id) const {
assert(node_id < capa_size_.size());
if (compare_dsp_(node_id, 0)) {
// root or not exist
return {nil_id, 0};
}
uint64_t dist = get_dsp_(node_id) - 1;
uint64_t init_id = dist <= node_id ? node_id - dist : table_.size() - (dist - node_id);
uint64_t key = hasher_.hash_inv(get_quo_(node_id) << capa_size_.bits() | init_id);
// Returns pair (parent, label)
return std::make_pair(key >> symb_size_.bits(), key & symb_size_.mask());
}
class node_map {
public:
node_map() = default;
node_map(compact_vector&& map_high, compact_vector&& map_low, bit_vector&& done_flags)
: map_high_(std::move(map_high)), map_low_(std::move(map_low)), done_flags_(std::move(done_flags)) {}
~node_map() = default;
uint64_t operator[](uint64_t i) const {
if (!done_flags_[i]) {
return UINT64_MAX;
}
if (map_high_.size() == 0) {
return map_low_[i];
} else {
return map_low_[i] | (map_high_[i] << map_low_.width());
}
}
uint64_t size() const {
return map_low_.size();
}
node_map(const node_map&) = delete;
node_map& operator=(const node_map&) = delete;
node_map(node_map&&) noexcept = default;
node_map& operator=(node_map&&) noexcept = default;
private:
compact_vector map_high_;
compact_vector map_low_;
bit_vector done_flags_;
};
bool needs_to_expand() const {
return max_size() <= size();
}
node_map expand() {
// this_type new_ht{capa_bits() + 1, symb_size_.bits(), aux_cht_.capa_bits()};
this_type new_ht{capa_bits() + 1, symb_size_.bits()};
new_ht.add_root();
#ifdef POPLAR_EXTRA_STATS
new_ht.num_resize_ = num_resize_ + 1;
#endif
bit_vector done_flags(capa_size());
done_flags.set(get_root());
size_p2 low_size{table_.width()};
compact_vector map_high;
if (low_size.bits() < new_ht.capa_bits()) {
map_high = compact_vector(capa_size(), new_ht.capa_bits() - low_size.bits());
}
std::vector<std::pair<uint64_t, uint64_t>> path;
path.reserve(256);
auto get_mapping = [&](uint64_t i) -> uint64_t {
if (map_high.size() == 0) {
return table_[i];
} else {
return table_[i] | (map_high[i] << low_size.bits());
}
};
auto set_mapping = [&](uint64_t i, uint64_t v) {
if (map_high.size() == 0) {
table_.set(i, v);
} else {
table_.set(i, v & low_size.mask());
map_high.set(i, v >> low_size.bits());
}
};
// 0 is root
for (uint64_t i = 1; i < table_.size(); ++i) {
if (done_flags[i] or compare_dsp_(i, 0)) {
// skip already processed or empty elements
continue;
}
path.clear();
uint64_t node_id = i;
do {
auto [parent, label] = get_parent_and_symb(node_id);
assert(parent != nil_id);
path.emplace_back(std::make_pair(node_id, label));
node_id = parent;
} while (!done_flags[node_id]);
uint64_t new_node_id = get_mapping(node_id);
for (auto rit = std::rbegin(path); rit != std::rend(path); ++rit) {
new_ht.add_child(new_node_id, rit->second);
set_mapping(rit->first, new_node_id);
done_flags.set(rit->first);
}
}
node_map node_map{std::move(map_high), std::move(table_), std::move(done_flags)};
std::swap(*this, new_ht);
return node_map;
}
uint64_t size() const {
return size_;
}
uint64_t max_size() const {
return max_size_;
}
uint64_t capa_size() const {
return capa_size_.size();
}
uint32_t capa_bits() const {
return capa_size_.bits();
}
uint64_t symb_size() const {
return symb_size_.size();
}
uint32_t symb_bits() const {
return symb_size_.bits();
}
#ifdef POPLAR_EXTRA_STATS
uint64_t num_resize() const {
return num_resize_;
}
#endif
uint64_t alloc_bytes() const {
uint64_t bytes = 0;
bytes += table_.alloc_bytes();
bytes += aux_cht_.alloc_bytes();
bytes += aux_map_.alloc_bytes();
return bytes;
}
void show_stats(std::ostream& os, int n = 0) const {
auto indent = get_indent(n);
show_stat(os, indent, "name", "compact_hash_trie");
show_stat(os, indent, "factor", double(size()) / capa_size() * 100);
show_stat(os, indent, "max_factor", MaxFactor);
show_stat(os, indent, "size", size());
show_stat(os, indent, "alloc_bytes", alloc_bytes());
show_stat(os, indent, "capa_bits", capa_bits());
show_stat(os, indent, "symb_bits", symb_bits());
show_stat(os, indent, "dsp1st_bits", dsp1_bits);
show_stat(os, indent, "dsp2nd_bits", dsp2_bits);
#ifdef POPLAR_EXTRA_STATS
show_stat(os, indent, "rate_dsp1st", double(num_dsps_[0]) / size());
show_stat(os, indent, "rate_dsp2nd", double(num_dsps_[1]) / size());
show_stat(os, indent, "rate_dsp3rd", double(num_dsps_[2]) / size());
show_stat(os, indent, "num_resize", num_resize_);
#endif
show_member(os, indent, "hasher_");
hasher_.show_stats(os, n + 1);
show_member(os, indent, "aux_cht_");
aux_cht_.show_stats(os, n + 1);
show_member(os, indent, "aux_map_");
aux_map_.show_stats(os, n + 1);
}
compact_bonsai_trie(const compact_bonsai_trie&) = delete;
compact_bonsai_trie& operator=(const compact_bonsai_trie&) = delete;
compact_bonsai_trie(compact_bonsai_trie&&) noexcept = default;
compact_bonsai_trie& operator=(compact_bonsai_trie&&) noexcept = default;
private:
Hasher hasher_;
compact_vector table_;
aux_cht_type aux_cht_; // 2nd dsp
aux_map_type aux_map_; // 3rd dsp
uint64_t size_ = 0; // # of registered nodes
uint64_t max_size_ = 0; // MaxFactor% of the capacity
size_p2 capa_size_;
size_p2 symb_size_;
#ifdef POPLAR_EXTRA_STATS
uint64_t num_resize_ = 0;
uint64_t num_dsps_[3] = {};
#endif
uint64_t make_key_(uint64_t node_id, uint64_t symb) const {
return (node_id << symb_size_.bits()) | symb;
}
std::pair<uint64_t, uint64_t> decompose_(uint64_t x) const {
return {x >> capa_size_.bits(), x & capa_size_.mask()};
}
uint64_t right_(uint64_t slot_id) const {
return (slot_id + 1) & capa_size_.mask();
}
uint64_t get_quo_(uint64_t slot_id) const {
return table_[slot_id] >> dsp1_bits;
}
uint64_t get_dsp_(uint64_t slot_id) const {
uint64_t dsp = table_[slot_id] & dsp1_mask;
if (dsp < dsp1_mask) {
return dsp;
}
dsp = aux_cht_.get(slot_id);
if (dsp != aux_cht_type::nil) {
return dsp + dsp1_mask;
}
return aux_map_.get(slot_id);
}
bool compare_dsp_(uint64_t slot_id, uint64_t rhs) const {
uint64_t lhs = table_[slot_id] & dsp1_mask;
if (lhs < dsp1_mask) {
return lhs == rhs;
}
if (rhs < dsp1_mask) {
return false;
}
lhs = aux_cht_.get(slot_id);
if (lhs != aux_cht_type::nil) {
return lhs + dsp1_mask == rhs;
}
if (rhs < dsp1_mask + dsp2_mask) {
return false;
}
auto val = aux_map_.get(slot_id);
assert(val != aux_map_type::nil);
return val == rhs;
}
void update_slot_(uint64_t slot_id, uint64_t quo, uint64_t dsp) {
assert(table_[slot_id] == 0);
assert(quo < symb_size_.size());
uint64_t v = quo << dsp1_bits;
if (dsp < dsp1_mask) {
v |= dsp;
} else {
v |= dsp1_mask;
uint64_t _dsp = dsp - dsp1_mask;
if (_dsp < dsp2_mask) {
aux_cht_.set(slot_id, _dsp);
} else {
aux_map_.set(slot_id, dsp);
}
}
#ifdef POPLAR_EXTRA_STATS
if (dsp < dsp1_mask) {
++num_dsps_[0];
} else if (dsp < dsp1_mask + dsp2_mask) {
++num_dsps_[1];
} else {
++num_dsps_[2];
}
#endif
table_.set(slot_id, v);
}
};
} // namespace poplar
#endif // POPLAR_TRIE_COMPACT_BONSAI_TRIE_HPP
| 31.666667
| 113
| 0.583585
|
MatsuTaku
|
39892cdc51302fced93a48a78ea60f237a0e6159
| 926
|
cpp
|
C++
|
C++/1663.SmallestStringWithAGivenNumericValue.cpp
|
SSKale1/LeetCode-Solutions
|
dd6ff16f6af1e96acd036b6e9c2a5cc11f0e330b
|
[
"MIT"
] | null | null | null |
C++/1663.SmallestStringWithAGivenNumericValue.cpp
|
SSKale1/LeetCode-Solutions
|
dd6ff16f6af1e96acd036b6e9c2a5cc11f0e330b
|
[
"MIT"
] | null | null | null |
C++/1663.SmallestStringWithAGivenNumericValue.cpp
|
SSKale1/LeetCode-Solutions
|
dd6ff16f6af1e96acd036b6e9c2a5cc11f0e330b
|
[
"MIT"
] | null | null | null |
class Solution {
public:
string getSmallestString(int n, int k) {
//initialising a string of length n and filling it with 'a'
string result(n, 'a');
//numeric value of 'a' = 1, the numeric value of the resulting string will become k-n as we have
//filled all with 'a', so k = k - (1*n);
k = k-n;
while(k>0)
{
//for iterating each index from the end
n--;
//changing the last value from 'a' to 'z' or k, whichever is minimum
result[n] = result[n] + min(25,k);
//decrementing k by the value to which 'a' was changed
k = k - min(25,k);
}
return result;
}
};
/*
You can checkout this link for understanding the problem through an example:
https://leetcode.com/problems/smallest-string-with-a-given-numeric-value/discuss/1871662/JavaC%2B%2B-Easiest-Possible-Exaplained!!
*/
| 29.870968
| 130
| 0.587473
|
SSKale1
|
399484533e6c99bd21e5f923282e780ad8129dac
| 4,076
|
hpp
|
C++
|
code/dtslam/ReprojectionError3DImpl.hpp
|
luoyongheng/dtslam
|
d3c2230d45db14c811eff6fd43e119ac39af1352
|
[
"BSD-3-Clause"
] | 144
|
2015-01-15T03:38:44.000Z
|
2022-02-17T09:07:52.000Z
|
code/dtslam/ReprojectionError3DImpl.hpp
|
luoyongheng/dtslam
|
d3c2230d45db14c811eff6fd43e119ac39af1352
|
[
"BSD-3-Clause"
] | 9
|
2015-09-09T06:51:46.000Z
|
2020-06-17T14:10:10.000Z
|
code/dtslam/ReprojectionError3DImpl.hpp
|
luoyongheng/dtslam
|
d3c2230d45db14c811eff6fd43e119ac39af1352
|
[
"BSD-3-Clause"
] | 58
|
2015-01-14T23:43:49.000Z
|
2021-11-15T05:19:08.000Z
|
/*
* ReprojectionError3DImpl.hpp
*
* Copyright(C) 2014, University of Oulu, all rights reserved.
* Copyright(C) 2014, NVIDIA Corporation, all rights reserved.
* Third party copyrights are property of their respective owners.
* Contact: Daniel Herrera C. (dherrera@ee.oulu.fi),
* Kihwan Kim(kihwank@nvidia.com)
* Author : Daniel Herrera C.
*/
#ifndef REPROJECTIONERROR3DIMPL_HPP_
#define REPROJECTIONERROR3DIMPL_HPP_
namespace dtslam
{
template<class T>
void ReprojectionError3D::pointResiduals(const T &u, const T &v, const int i, T *residuals) const
{
const cv::Point2f &p = mImgPoints[i];
residuals[0] = (u-T(p.x))/T(mScale);
residuals[1] = (v-T(p.y))/T(mScale);
}
template<class T>
void ReprojectionError3D::computeAllResidualsXc(const T * const xc, T *allResiduals) const
{
if(CeresUtils::ToDouble(xc[2]) <= 0)
{
//Negative point
for(int i=0; i<2*mImagePointCount; ++i)
allResiduals[i] = T(1e3);
}
else
{
//Point in front of camera, proceed
T u,v;
mCamera->projectFromWorld(xc[0],xc[1],xc[2],u,v);
//Calculate residuals for all points
for(int i=0; i<mImagePointCount; ++i)
{
pointResiduals(u,v,i,allResiduals+2*i);
}
}
}
template<class T>
void ReprojectionError3D::computeAllResidualsRparams(const T * const rparams, const T * const t, const T * const x, T *allResiduals) const
{
T xr[3];
ceres::AngleAxisRotatePoint(rparams, x, xr);
T xc[3];
xc[0] = xr[0]+t[0];
xc[1] = xr[1]+t[1];
xc[2] = xr[2]+t[2];
computeAllResidualsXc(xc,allResiduals);
}
template<class T>
void ReprojectionError3D::computeAllResidualsRmat(const T * const R, const T * const t, const T * const x, T *allResiduals) const
{
auto xwmat = CeresUtils::FixedRowMajorAdapter3x1(x);
auto Rmat = CeresUtils::FixedRowMajorAdapter3x3(R);
T xr[3];
auto xrmat = CeresUtils::FixedRowMajorAdapter3x1(xr);
CeresUtils::matrixMatrix(Rmat,xwmat,xrmat);
T xc[3];
xc[0] = xr[0]+t[0];
xc[1] = xr[1]+t[1];
xc[2] = xr[2]+t[2];
computeAllResidualsXc(xc,allResiduals);
}
template<class T>
void ReprojectionError3D::residualsToErrors(const std::vector<T> &allResiduals, const float errorThreshold, MatchReprojectionErrors &errors) const
{
assert(allResiduals.size() == 2*mImagePointCount);
float errorThresholdSq = errorThreshold*errorThreshold;
//Init errors
errors.isInlier=false;
errors.bestReprojectionErrorSq = std::numeric_limits<float>::infinity();
errors.reprojectionErrorsSq.resize(mImagePointCount);
errors.isImagePointInlier.resize(mImagePointCount);
for(int i=0; i!=mImagePointCount; ++i)
{
float r1 = (float)allResiduals[2 * i];
float r2 = (float)allResiduals[2 * i + 1];
auto &errorSq = errors.reprojectionErrorsSq[i];
errorSq = r1*r1+r2*r2;
//Min
if(errorSq < errors.bestReprojectionErrorSq)
errors.bestReprojectionErrorSq = errorSq;
//Update errors
if(errorSq < errorThresholdSq)
{
errors.isImagePointInlier[i] = true;
errors.isInlier = true;
}
else
errors.isImagePointInlier[i] = false;
}
}
template<class T>
bool PoseReprojectionError3D::operator()(const T * const rparams, const T * const t, T *residuals) const
{
T x[3] = {T(mFeaturePosition[0]),T(mFeaturePosition[1]),T(mFeaturePosition[2])};
if(mImagePointCount==1)
{
computeAllResidualsRparams(rparams, t, x, residuals);
}
else
{
std::vector<T> allResiduals(2*mImagePointCount);
computeAllResidualsRparams(rparams, t, x, allResiduals.data());
int minIndex;
CeresUtils::GetMinResiduals<2>(allResiduals.data(), mImagePointCount, residuals, minIndex);
}
return true;
}
template<class T>
bool BAReprojectionError3D::operator()(const T * const rparams, const T * const t, const T * const x, T *residuals) const
{
if(mImagePointCount==1)
{
computeAllResidualsRparams(rparams, t, x, residuals);
}
else
{
std::vector<T> allResiduals(2*mImagePointCount);
computeAllResidualsRparams(rparams, t, x, allResiduals.data());
int minIndex;
CeresUtils::GetMinResiduals<2>(allResiduals.data(), mImagePointCount, residuals, minIndex);
}
return true;
}
}
#endif /* REPROJECTIONERROR3DIMPL_HPP_ */
| 25.31677
| 146
| 0.717125
|
luoyongheng
|
399670d626858db8cc6a3719e993b1bbe73c3d4d
| 10,258
|
cpp
|
C++
|
src/common/BitBuffer.cpp
|
AllMethodGrind/bmxlib
|
9480bdec14c082f9b121b7a6102461b05bdea547
|
[
"BSD-3-Clause"
] | 4
|
2015-02-24T23:55:07.000Z
|
2021-04-13T20:48:45.000Z
|
src/common/BitBuffer.cpp
|
AllMethodGrind/bmxlib
|
9480bdec14c082f9b121b7a6102461b05bdea547
|
[
"BSD-3-Clause"
] | null | null | null |
src/common/BitBuffer.cpp
|
AllMethodGrind/bmxlib
|
9480bdec14c082f9b121b7a6102461b05bdea547
|
[
"BSD-3-Clause"
] | 3
|
2019-03-20T18:34:45.000Z
|
2020-10-04T20:37:52.000Z
|
/*
* Copyright (C) 2013, British Broadcasting Corporation
* All Rights Reserved.
*
* Author: Philip de Nier
*
* 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 British Broadcasting 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 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.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#define __STDC_LIMIT_MACROS
#define __STDC_CONSTANT_MACROS
#include <cstring>
#include <memory>
#include <bmx/BitBuffer.h>
#include <bmx/Utils.h>
#include <bmx/BMXException.h>
#include <bmx/Logging.h>
using namespace std;
using namespace bmx;
GetBitBuffer::GetBitBuffer(const unsigned char *data, uint32_t size)
{
mData = data;
mSize = size;
mPos = 0;
mBitSize = (uint64_t)size << 3;
mBitPos = 0;
}
uint32_t GetBitBuffer::GetRemSize() const
{
if (mSize > mPos)
return mSize - mPos;
else
return 0;
}
uint64_t GetBitBuffer::GetRemBitSize() const
{
if (mBitSize > mBitPos)
return mBitSize - mBitPos;
else
return 0;
}
void GetBitBuffer::GetBytes(uint32_t request_size, const unsigned char **data, uint32_t *size)
{
BMX_ASSERT(!(mBitPos & 0x07));
*size = request_size;
if ((*size) > mSize - mPos)
*size = mSize - mPos;
if ((*size) > 0) {
*data = &mData[mPos];
mPos += *size;
mBitPos += (uint64_t)(*size) << 3;
} else {
*data = 0;
}
}
bool GetBitBuffer::GetUInt8(uint8_t *value)
{
BMX_ASSERT(!(mBitPos & 0x07));
if (mPos >= mSize)
return false;
*value = mData[mPos];
mPos++;
mBitPos += 8;
return true;
}
bool GetBitBuffer::GetBits(uint8_t num_bits, uint8_t *value)
{
uint64_t u64_value;
if (!GetBits(num_bits, &u64_value))
return false;
*value = (uint8_t)u64_value;
return true;
}
bool GetBitBuffer::GetBits(uint8_t num_bits, uint16_t *value)
{
uint64_t u64_value;
if (!GetBits(num_bits, &u64_value))
return false;
*value = (uint16_t)u64_value;
return true;
}
bool GetBitBuffer::GetBits(uint8_t num_bits, uint32_t *value)
{
uint64_t u64_value;
if (!GetBits(num_bits, &u64_value))
return false;
*value = (uint32_t)u64_value;
return true;
}
bool GetBitBuffer::GetBits(uint8_t num_bits, uint64_t *value)
{
if (num_bits > mBitSize - mBitPos)
return false;
if (num_bits > 0)
GetBits(mData, &mPos, &mBitPos, num_bits, value);
else
*value = 0;
return true;
}
bool GetBitBuffer::GetBits(uint8_t num_bits, int8_t *value)
{
int64_t i64_value;
if (!GetBits(num_bits, &i64_value))
return false;
*value = (int32_t)i64_value;
return true;
}
bool GetBitBuffer::GetBits(uint8_t num_bits, int16_t *value)
{
int64_t i64_value;
if (!GetBits(num_bits, &i64_value))
return false;
*value = (int32_t)i64_value;
return true;
}
bool GetBitBuffer::GetBits(uint8_t num_bits, int32_t *value)
{
int64_t i64_value;
if (!GetBits(num_bits, &i64_value))
return false;
*value = (int32_t)i64_value;
return true;
}
bool GetBitBuffer::GetBits(uint8_t num_bits, int64_t *value)
{
uint64_t u64_value;
if (!GetBits(num_bits, &u64_value))
return false;
int64_t sign = (int64_t)(UINT64_C(1) << (num_bits - 1));
*value = ((int64_t)u64_value ^ sign) - sign;
return true;
}
void GetBitBuffer::SetPos(uint32_t pos)
{
mPos = pos;
mBitPos = (uint64_t)pos << 3;
}
void GetBitBuffer::SetBitPos(uint64_t bit_pos)
{
mBitPos = bit_pos;
mPos = (uint32_t)(mBitPos >> 3);
}
void GetBitBuffer::GetBits(const unsigned char *data, uint32_t *pos_io, uint64_t *bit_pos_io, uint8_t num_bits,
uint64_t *value)
{
BMX_ASSERT(num_bits > 0 || num_bits <= 64);
const unsigned char *data_ptr = &data[*pos_io];
uint8_t min_consume_bits = (uint8_t)(((*bit_pos_io) & 0x07) + num_bits);
int16_t consumed_bits = 0;
*value = 0;
while (consumed_bits < min_consume_bits) {
*value = ((*value) << 8) | (*data_ptr);
data_ptr++;
consumed_bits += 8;
}
*value >>= consumed_bits - min_consume_bits;
if (consumed_bits > 64)
*value |= ((uint64_t)data[*pos_io]) << (64 - (consumed_bits - min_consume_bits));
*value &= UINT64_MAX >> (64 - num_bits);
*bit_pos_io += num_bits;
*pos_io = (uint32_t)((*bit_pos_io) >> 3);
}
PutBitBuffer::PutBitBuffer(ByteArray *w_buffer)
{
mWBuffer = w_buffer;
mRWBytes = 0;
mRWBytesSize = 0;
mRWBytesPos = 0;
mBitSize = (uint64_t)w_buffer->GetSize() << 3;
}
PutBitBuffer::PutBitBuffer(unsigned char *bytes, uint32_t size)
{
mWBuffer = 0;
mRWBytes = bytes;
mRWBytesSize = size;
mRWBytesPos = 0;
mBitSize = 0;
}
uint32_t PutBitBuffer::GetSize() const
{
if (mWBuffer)
return mWBuffer->GetSize();
else
return mRWBytesPos;
}
void PutBitBuffer::PutBytes(const unsigned char *data, uint32_t size)
{
BMX_ASSERT(!(mBitSize & 0x07));
Append(data, size);
mBitSize += (uint64_t)size << 3;
}
void PutBitBuffer::PutUInt8(uint8_t value)
{
BMX_ASSERT(!(mBitSize & 0x07));
Append(&value, 1);
mBitSize += 8;
}
void PutBitBuffer::PutBits(uint8_t num_bits, uint8_t value)
{
PutBits(num_bits, (uint64_t)value);
}
void PutBitBuffer::PutBits(uint8_t num_bits, uint16_t value)
{
PutBits(num_bits, (uint64_t)value);
}
void PutBitBuffer::PutBits(uint8_t num_bits, uint32_t value)
{
PutBits(num_bits, (uint64_t)value);
}
void PutBitBuffer::PutBits(uint8_t num_bits, uint64_t value)
{
uint8_t byte_bitpos = (uint8_t)(mBitSize & 0x07);
uint8_t next_byte_bitpos = (uint8_t)((mBitSize + num_bits) & 0x07);
uint8_t num_bytes = (byte_bitpos + num_bits + 7) / 8;
uint8_t incr_size = num_bytes;
if (byte_bitpos != 0)
incr_size -= 1;
Grow(incr_size);
unsigned char *bytes = GetBytesAvailable();
if (byte_bitpos != 0)
bytes--;
uint64_t shift_value; // bits shifted to msb
if ((64 - num_bits - byte_bitpos) >= 0)
shift_value = value << (64 - num_bits - byte_bitpos);
else
shift_value = value >> (- (64 - num_bits - byte_bitpos)); // existing + new bits > 64
uint8_t first_byte_mask = (uint8_t)(0xff << (8 - byte_bitpos));
uint8_t last_byte_mask = 0;
if (next_byte_bitpos != 0)
last_byte_mask = (uint8_t)(0xff >> next_byte_bitpos);
uint8_t existing_byte_mask;
uint8_t i;
for (i = 0; i < num_bytes; i++) {
existing_byte_mask = 0;
if (i == 0)
existing_byte_mask |= first_byte_mask;
if (i == num_bytes - 1)
existing_byte_mask |= last_byte_mask;
bytes[i] = (bytes[i] & existing_byte_mask) | (uint8_t)((shift_value >> 56) & 0xff);
shift_value <<= 8;
if (i == 0) // reinstate bits shifted out if (64 - num_bits - byte_bitpos) < 0
shift_value |= ((value << 8) >> byte_bitpos) & 0xff;
}
IncrementSize(incr_size);
mBitSize += num_bits;
}
void PutBitBuffer::PutBits(uint8_t num_bits, int8_t value)
{
PutBits(num_bits, (int64_t)value);
}
void PutBitBuffer::PutBits(uint8_t num_bits, int16_t value)
{
PutBits(num_bits, (int64_t)value);
}
void PutBitBuffer::PutBits(uint8_t num_bits, int32_t value)
{
PutBits(num_bits, (int64_t)value);
}
void PutBitBuffer::PutBits(uint8_t num_bits, int64_t value)
{
uint64_t sign = UINT64_C(1) << (num_bits - 1);
uint64_t u_value;
if (value < 0)
u_value = sign | (value & (sign - 1));
else
u_value = value;
PutBits(num_bits, u_value);
}
void PutBitBuffer::SetBitPos(uint64_t pos)
{
BMX_ASSERT(mRWBytes); // currently only implemented for mRWBytes
mBitSize = pos;
mRWBytesPos = (uint32_t)((pos + 7) >> 3);
}
void PutBitBuffer::Append(const unsigned char *bytes, uint32_t size)
{
if (mWBuffer) {
mWBuffer->Append(bytes, size);
} else {
BMX_CHECK(mRWBytesPos + size <= mRWBytesSize);
memcpy(&mRWBytes[mRWBytesPos], bytes, size);
mRWBytesPos += size;
}
}
unsigned char* PutBitBuffer::GetBytesAvailable() const
{
if (mWBuffer) {
return mWBuffer->GetBytesAvailable();
} else {
if (mRWBytesPos >= mRWBytesSize)
return 0;
else
return &mRWBytes[mRWBytesPos];
}
}
void PutBitBuffer::IncrementSize(uint32_t inc)
{
if (mWBuffer) {
mWBuffer->IncrementSize(inc);
} else {
BMX_CHECK(inc <= mRWBytesSize && mRWBytesPos <= mRWBytesSize - inc);
mRWBytesPos += inc;
}
}
void PutBitBuffer::Grow(uint32_t min_size)
{
if (mWBuffer) {
mWBuffer->Grow(min_size);
if (min_size > 0)
memset(mWBuffer->GetBytesAvailable(), 0, min_size);
} else {
BMX_CHECK(min_size <= mRWBytesSize && mRWBytesPos <= mRWBytesSize - min_size);
}
}
| 25.26601
| 111
| 0.649834
|
AllMethodGrind
|
399a60eb69b17fbcb51cc18fee6538f34f8feef9
| 28,716
|
cpp
|
C++
|
mtp/ffs/mtp_MtpDatabase.cpp
|
imranpopz/android_bootable_recovery-1
|
ec4512ad1e20f640b3dcd6faf8c04cae711e4f30
|
[
"Apache-2.0"
] | 95
|
2018-10-31T12:12:01.000Z
|
2022-03-20T21:30:48.000Z
|
mtp/ffs/mtp_MtpDatabase.cpp
|
imranpopz/android_bootable_recovery-1
|
ec4512ad1e20f640b3dcd6faf8c04cae711e4f30
|
[
"Apache-2.0"
] | 34
|
2018-10-22T11:01:15.000Z
|
2021-11-21T14:10:26.000Z
|
mtp/ffs/mtp_MtpDatabase.cpp
|
imranpopz/android_bootable_recovery-1
|
ec4512ad1e20f640b3dcd6faf8c04cae711e4f30
|
[
"Apache-2.0"
] | 81
|
2018-10-23T08:37:20.000Z
|
2022-03-20T00:27:08.000Z
|
/*
* Copyright (C) 2010 The Android Open Source Project
*
* 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.
*
* Copyright (C) 2014 TeamWin - bigbiff and Dees_Troy mtp database conversion to C++
*/
#include <utils/Log.h>
#include <assert.h>
#include <cutils/properties.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <libgen.h>
#include <limits.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <map>
#include <string>
#include "MtpDataPacket.h"
#include "MtpDatabase.h"
#include "MtpDebug.h"
#include "MtpObjectInfo.h"
#include "MtpProperty.h"
#include "MtpStorage.h"
#include "MtpStringBuffer.h"
#include "MtpUtils.h"
#include "mtp.h"
#include "mtp_MtpDatabase.hpp"
IMtpDatabase::IMtpDatabase() {
storagenum = 0;
count = -1;
}
IMtpDatabase::~IMtpDatabase() {
std::map<int, MtpStorage*>::iterator i;
for (i = storagemap.begin(); i != storagemap.end(); i++) {
delete i->second;
}
}
int IMtpDatabase::DEVICE_PROPERTIES[3] = { MTP_DEVICE_PROPERTY_SYNCHRONIZATION_PARTNER,
MTP_DEVICE_PROPERTY_DEVICE_FRIENDLY_NAME,
MTP_DEVICE_PROPERTY_IMAGE_SIZE };
int IMtpDatabase::FILE_PROPERTIES[10] = {
// NOTE must match beginning of AUDIO_PROPERTIES, VIDEO_PROPERTIES
// and IMAGE_PROPERTIES below
MTP_PROPERTY_STORAGE_ID, MTP_PROPERTY_OBJECT_FORMAT, MTP_PROPERTY_PROTECTION_STATUS,
MTP_PROPERTY_OBJECT_SIZE, MTP_PROPERTY_OBJECT_FILE_NAME, MTP_PROPERTY_DATE_MODIFIED,
MTP_PROPERTY_PARENT_OBJECT, MTP_PROPERTY_PERSISTENT_UID, MTP_PROPERTY_NAME,
// TODO: why is DISPLAY_NAME not here?
MTP_PROPERTY_DATE_ADDED
};
int IMtpDatabase::AUDIO_PROPERTIES[19] = {
// NOTE must match FILE_PROPERTIES above
MTP_PROPERTY_STORAGE_ID, MTP_PROPERTY_OBJECT_FORMAT, MTP_PROPERTY_PROTECTION_STATUS,
MTP_PROPERTY_OBJECT_SIZE, MTP_PROPERTY_OBJECT_FILE_NAME, MTP_PROPERTY_DATE_MODIFIED,
MTP_PROPERTY_PARENT_OBJECT, MTP_PROPERTY_PERSISTENT_UID, MTP_PROPERTY_NAME,
MTP_PROPERTY_DISPLAY_NAME, MTP_PROPERTY_DATE_ADDED,
// audio specific properties
MTP_PROPERTY_ARTIST, MTP_PROPERTY_ALBUM_NAME, MTP_PROPERTY_ALBUM_ARTIST, MTP_PROPERTY_TRACK,
MTP_PROPERTY_ORIGINAL_RELEASE_DATE, MTP_PROPERTY_DURATION, MTP_PROPERTY_GENRE,
MTP_PROPERTY_COMPOSER
};
int IMtpDatabase::VIDEO_PROPERTIES[15] = {
// NOTE must match FILE_PROPERTIES above
MTP_PROPERTY_STORAGE_ID, MTP_PROPERTY_OBJECT_FORMAT, MTP_PROPERTY_PROTECTION_STATUS,
MTP_PROPERTY_OBJECT_SIZE, MTP_PROPERTY_OBJECT_FILE_NAME, MTP_PROPERTY_DATE_MODIFIED,
MTP_PROPERTY_PARENT_OBJECT, MTP_PROPERTY_PERSISTENT_UID, MTP_PROPERTY_NAME,
MTP_PROPERTY_DISPLAY_NAME, MTP_PROPERTY_DATE_ADDED,
// video specific properties
MTP_PROPERTY_ARTIST, MTP_PROPERTY_ALBUM_NAME, MTP_PROPERTY_DURATION, MTP_PROPERTY_DESCRIPTION
};
int IMtpDatabase::IMAGE_PROPERTIES[12] = {
// NOTE must match FILE_PROPERTIES above
MTP_PROPERTY_STORAGE_ID, MTP_PROPERTY_OBJECT_FORMAT, MTP_PROPERTY_PROTECTION_STATUS,
MTP_PROPERTY_OBJECT_SIZE, MTP_PROPERTY_OBJECT_FILE_NAME, MTP_PROPERTY_DATE_MODIFIED,
MTP_PROPERTY_PARENT_OBJECT, MTP_PROPERTY_PERSISTENT_UID, MTP_PROPERTY_NAME,
MTP_PROPERTY_DISPLAY_NAME, MTP_PROPERTY_DATE_ADDED,
// image specific properties
MTP_PROPERTY_DESCRIPTION
};
int IMtpDatabase::ALL_PROPERTIES[25] = {
// NOTE must match FILE_PROPERTIES above
MTP_PROPERTY_STORAGE_ID, MTP_PROPERTY_OBJECT_FORMAT, MTP_PROPERTY_PROTECTION_STATUS,
MTP_PROPERTY_OBJECT_SIZE, MTP_PROPERTY_OBJECT_FILE_NAME, MTP_PROPERTY_DATE_MODIFIED,
MTP_PROPERTY_PARENT_OBJECT, MTP_PROPERTY_PERSISTENT_UID, MTP_PROPERTY_NAME,
MTP_PROPERTY_DISPLAY_NAME, MTP_PROPERTY_DATE_ADDED,
// image specific properties
MTP_PROPERTY_DESCRIPTION,
// audio specific properties
MTP_PROPERTY_ARTIST, MTP_PROPERTY_ALBUM_NAME, MTP_PROPERTY_ALBUM_ARTIST, MTP_PROPERTY_TRACK,
MTP_PROPERTY_ORIGINAL_RELEASE_DATE, MTP_PROPERTY_DURATION, MTP_PROPERTY_GENRE,
MTP_PROPERTY_COMPOSER,
// video specific properties
MTP_PROPERTY_ARTIST, MTP_PROPERTY_ALBUM_NAME, MTP_PROPERTY_DURATION, MTP_PROPERTY_DESCRIPTION,
// image specific properties
MTP_PROPERTY_DESCRIPTION
};
int IMtpDatabase::SUPPORTED_PLAYBACK_FORMATS[26] = { SUPPORTED_PLAYBACK_FORMAT_UNDEFINED,
SUPPORTED_PLAYBACK_FORMAT_ASSOCIATION,
SUPPORTED_PLAYBACK_FORMAT_TEXT,
SUPPORTED_PLAYBACK_FORMAT_HTML,
SUPPORTED_PLAYBACK_FORMAT_WAV,
SUPPORTED_PLAYBACK_FORMAT_MP3,
SUPPORTED_PLAYBACK_FORMAT_MPEG,
SUPPORTED_PLAYBACK_FORMAT_EXIF_JPEG,
SUPPORTED_PLAYBACK_FORMAT_TIFF_EP,
SUPPORTED_PLAYBACK_FORMAT_BMP,
SUPPORTED_PLAYBACK_FORMAT_GIF,
SUPPORTED_PLAYBACK_FORMAT_JFIF,
SUPPORTED_PLAYBACK_FORMAT_PNG,
SUPPORTED_PLAYBACK_FORMAT_TIFF,
SUPPORTED_PLAYBACK_FORMAT_WMA,
SUPPORTED_PLAYBACK_FORMAT_OGG,
SUPPORTED_PLAYBACK_FORMAT_AAC,
SUPPORTED_PLAYBACK_FORMAT_MP4_CONTAINER,
SUPPORTED_PLAYBACK_FORMAT_MP2,
SUPPORTED_PLAYBACK_FORMAT_3GP_CONTAINER,
SUPPORTED_PLAYBACK_FORMAT_ABSTRACT_AV_PLAYLIST,
SUPPORTED_PLAYBACK_FORMAT_WPL_PLAYLIST,
SUPPORTED_PLAYBACK_FORMAT_M3U_PLAYLIST,
SUPPORTED_PLAYBACK_FORMAT_PLS_PLAYLIST,
SUPPORTED_PLAYBACK_FORMAT_XML_DOCUMENT,
SUPPORTED_PLAYBACK_FORMAT_FLAC };
MtpObjectHandle IMtpDatabase::beginSendObject(const char* path, MtpObjectFormat format,
MtpObjectHandle parent, MtpStorageID storageID,
uint64_t size, time_t modified) {
if (storagemap.find(storageID) == storagemap.end()) return kInvalidObjectHandle;
return storagemap[storageID]->beginSendObject(path, format, parent, size, modified);
}
void IMtpDatabase::endSendObject(const char* path, MtpObjectHandle handle, MtpObjectFormat format,
bool succeeded) {
MTPD("endSendObject() %s\n", path);
if (!succeeded) {
MTPE("endSendObject() failed, unlinking %s\n", path);
unlink(path);
}
std::map<int, MtpStorage*>::iterator storit;
for (storit = storagemap.begin(); storit != storagemap.end(); storit++)
storit->second->endSendObject(path, handle, format, succeeded);
}
void IMtpDatabase::createDB(MtpStorage* storage, MtpStorageID storageID) {
storagemap[storageID] = storage;
storage->createDB();
}
void IMtpDatabase::destroyDB(MtpStorageID storageID) {
MtpStorage* storage = storagemap[storageID];
storagemap.erase(storageID);
delete storage;
}
MtpObjectHandleList* IMtpDatabase::getObjectList(MtpStorageID storageID,
__attribute__((unused)) MtpObjectFormat format,
MtpObjectHandle parent) {
MTPD("IMtpDatabase::getObjectList::storageID: %d\n", storageID);
MtpObjectHandleList* list = storagemap[storageID]->getObjectList(storageID, parent);
MTPD("IMtpDatabase::getObjectList::list size: %d\n", list->size());
return list;
}
int IMtpDatabase::getNumObjects(MtpStorageID storageID,
__attribute__((unused)) MtpObjectFormat format,
MtpObjectHandle parent) {
MtpObjectHandleList* list = storagemap[storageID]->getObjectList(storageID, parent);
int size = list->size();
delete list;
return size;
}
MtpObjectFormatList* IMtpDatabase::getSupportedPlaybackFormats() {
// This function tells the host PC which file formats the device supports
MtpObjectFormatList* list = new MtpObjectFormatList();
int length = sizeof(SUPPORTED_PLAYBACK_FORMATS) / sizeof(SUPPORTED_PLAYBACK_FORMATS[0]);
MTPD("IMtpDatabase::getSupportedPlaybackFormats length: %i\n", length);
for (int i = 0; i < length; i++) {
MTPD("supported playback format: %x\n", SUPPORTED_PLAYBACK_FORMATS[i]);
list->push_back(SUPPORTED_PLAYBACK_FORMATS[i]);
}
return list;
}
MtpObjectFormatList* IMtpDatabase::getSupportedCaptureFormats() {
// Android OS implementation of this function returns NULL
// so we are not implementing this function either.
MTPD(
"IMtpDatabase::getSupportedCaptureFormats returning NULL (This is what Android does as "
"well).\n");
return NULL;
}
MtpObjectPropertyList* IMtpDatabase::getSupportedObjectProperties(MtpObjectFormat format) {
int* properties;
MtpObjectPropertyList* list = new MtpObjectPropertyList();
int length = 0;
switch (format) {
case MTP_FORMAT_MP3:
case MTP_FORMAT_WAV:
case MTP_FORMAT_WMA:
case MTP_FORMAT_OGG:
case MTP_FORMAT_AAC:
properties = AUDIO_PROPERTIES;
length = sizeof(AUDIO_PROPERTIES) / sizeof(AUDIO_PROPERTIES[0]);
break;
case MTP_FORMAT_MPEG:
case MTP_FORMAT_3GP_CONTAINER:
case MTP_FORMAT_WMV:
properties = VIDEO_PROPERTIES;
length = sizeof(VIDEO_PROPERTIES) / sizeof(VIDEO_PROPERTIES[0]);
break;
case MTP_FORMAT_EXIF_JPEG:
case MTP_FORMAT_GIF:
case MTP_FORMAT_PNG:
case MTP_FORMAT_BMP:
properties = IMAGE_PROPERTIES;
length = sizeof(IMAGE_PROPERTIES) / sizeof(IMAGE_PROPERTIES[0]);
break;
case 0:
properties = ALL_PROPERTIES;
length = sizeof(ALL_PROPERTIES) / sizeof(ALL_PROPERTIES[0]);
break;
default:
properties = FILE_PROPERTIES;
length = sizeof(FILE_PROPERTIES) / sizeof(FILE_PROPERTIES[0]);
}
MTPD("IMtpDatabase::getSupportedObjectProperties length is: %i, format: %x", length, format);
for (int i = 0; i < length; i++) {
MTPD("supported object property: %x\n", properties[i]);
list->push_back(properties[i]);
}
return list;
}
MtpDevicePropertyList* IMtpDatabase::getSupportedDeviceProperties() {
MtpDevicePropertyList* list = new MtpDevicePropertyList();
int length = sizeof(DEVICE_PROPERTIES) / sizeof(DEVICE_PROPERTIES[0]);
MTPD("IMtpDatabase::getSupportedDeviceProperties length was: %i\n", length);
for (int i = 0; i < length; i++) list->push_back(DEVICE_PROPERTIES[i]);
return list;
}
MtpResponseCode IMtpDatabase::getObjectPropertyValue(MtpObjectHandle handle,
MtpObjectProperty property,
MtpDataPacket& packet) {
MTPD("IMtpDatabase::getObjectPropertyValue mtpid: %u, property: %x\n", handle, property);
int type;
MtpResponseCode result = MTP_RESPONSE_INVALID_OBJECT_HANDLE;
MtpStorage::PropEntry prop;
if (!getObjectPropertyInfo(property, type)) {
MTPE("IMtpDatabase::getObjectPropertyValue returning MTP_RESPONSE_OBJECT_PROP_NOT_SUPPORTED\n");
return MTP_RESPONSE_OBJECT_PROP_NOT_SUPPORTED;
}
std::map<int, MtpStorage*>::iterator storit;
for (storit = storagemap.begin(); storit != storagemap.end(); storit++) {
if (storit->second->getObjectPropertyValue(handle, property, prop) == 0) {
result = MTP_RESPONSE_OK;
break;
}
}
if (result != MTP_RESPONSE_OK) {
MTPE("IMtpDatabase::getObjectPropertyValue unable to locate handle: %u\n", handle);
return MTP_RESPONSE_INVALID_OBJECT_HANDLE;
}
uint64_t longValue = prop.intvalue;
// special case date properties, which are strings to MTP
// but stored internally as a uint64
if (property == MTP_PROPERTY_DATE_MODIFIED || property == MTP_PROPERTY_DATE_ADDED) {
char date[20];
formatDateTime(longValue, date, sizeof(date));
packet.putString(date);
goto out;
}
switch (type) {
case MTP_TYPE_INT8:
packet.putInt8(longValue);
break;
case MTP_TYPE_UINT8:
packet.putUInt8(longValue);
break;
case MTP_TYPE_INT16:
packet.putInt16(longValue);
break;
case MTP_TYPE_UINT16:
packet.putUInt16(longValue);
break;
case MTP_TYPE_INT32:
packet.putInt32(longValue);
break;
case MTP_TYPE_UINT32:
packet.putUInt32(longValue);
break;
case MTP_TYPE_INT64:
packet.putInt64(longValue);
break;
case MTP_TYPE_UINT64:
packet.putUInt64(longValue);
break;
case MTP_TYPE_INT128:
packet.putInt128(longValue);
break;
case MTP_TYPE_UINT128:
packet.putUInt128(longValue);
break;
case MTP_TYPE_STR: {
/*std::string stringValue = (string)stringValuesArray[0];
if (stringValue) {
const char* str = stringValue.c_str();
if (str == NULL) {
return MTP_RESPONSE_GENERAL_ERROR;
}
packet.putString(str);
} else {
packet.putEmptyString();
}*/
packet.putString(prop.strvalue.c_str());
MTPD("MTP_TYPE_STR: %x = %s\n", prop.property, prop.strvalue.c_str());
// MTPE("STRING unsupported type in getObjectPropertyValue\n");
// result = MTP_RESPONSE_INVALID_OBJECT_PROP_FORMAT;
break;
}
default:
MTPE("unsupported type in getObjectPropertyValue\n");
result = MTP_RESPONSE_INVALID_OBJECT_PROP_FORMAT;
}
out:
return result;
}
MtpResponseCode IMtpDatabase::setObjectPropertyValue(MtpObjectHandle handle,
MtpObjectProperty property,
MtpDataPacket& packet) {
int type;
MTPD("IMtpDatabase::setObjectPropertyValue start\n");
if (!getObjectPropertyInfo(property, type)) {
MTPE("IMtpDatabase::setObjectPropertyValue returning MTP_RESPONSE_OBJECT_PROP_NOT_SUPPORTED\n");
return MTP_RESPONSE_OBJECT_PROP_NOT_SUPPORTED;
}
MTPD("IMtpDatabase::setObjectPropertyValue continuing\n");
int8_t int8_t_value;
uint8_t uint8_t_value;
int16_t int16_t_value;
uint16_t uint16_t_value;
int32_t int32_t_value;
uint32_t uint32_t_value;
int64_t int64_t_value;
uint64_t uint64_t_value;
std::string stringValue;
switch (type) {
case MTP_TYPE_INT8:
MTPD("int8\n");
packet.getInt8(int8_t_value);
break;
case MTP_TYPE_UINT8:
MTPD("uint8\n");
packet.getUInt8(uint8_t_value);
break;
case MTP_TYPE_INT16:
MTPD("int16\n");
packet.getInt16(int16_t_value);
break;
case MTP_TYPE_UINT16:
MTPD("uint16\n");
packet.getUInt16(uint16_t_value);
break;
case MTP_TYPE_INT32:
MTPD("int32\n");
packet.getInt32(int32_t_value);
break;
case MTP_TYPE_UINT32:
MTPD("uint32\n");
packet.getUInt32(uint32_t_value);
break;
case MTP_TYPE_INT64:
MTPD("int64\n");
packet.getInt64(int64_t_value);
break;
case MTP_TYPE_UINT64:
MTPD("uint64\n");
packet.getUInt64(uint64_t_value);
break;
case MTP_TYPE_STR: {
MTPD("string\n");
MtpStringBuffer buffer;
packet.getString(buffer);
stringValue = buffer;
break;
}
default:
MTPE("IMtpDatabase::setObjectPropertyValue unsupported type %i in getObjectPropertyValue\n",
type);
return MTP_RESPONSE_INVALID_OBJECT_PROP_FORMAT;
}
int result = MTP_RESPONSE_OBJECT_PROP_NOT_SUPPORTED;
switch (property) {
case MTP_PROPERTY_OBJECT_FILE_NAME: {
MTPD("IMtpDatabase::setObjectPropertyValue renaming file, handle: %d, new name: '%s'\n",
handle, stringValue.c_str());
std::map<int, MtpStorage*>::iterator storit;
for (storit = storagemap.begin(); storit != storagemap.end(); storit++) {
if (storit->second->renameObject(handle, stringValue) == 0) {
MTPD("MTP_RESPONSE_OK\n");
result = MTP_RESPONSE_OK;
break;
}
}
} break;
default:
MTPE("IMtpDatabase::setObjectPropertyValue property %x not supported.\n", property);
result = MTP_RESPONSE_OBJECT_PROP_NOT_SUPPORTED;
}
MTPD("IMtpDatabase::setObjectPropertyValue returning %d\n", result);
return result;
}
MtpResponseCode IMtpDatabase::getDevicePropertyValue(MtpDeviceProperty property,
MtpDataPacket& packet) {
int type, result = 0;
char prop_value[PROPERTY_VALUE_MAX];
MTPD("property %s\n", MtpDebug::getDevicePropCodeName(property));
if (!getDevicePropertyInfo(property, type)) {
MTPE("IMtpDatabase::getDevicePropertyValue MTP_RESPONSE_DEVICE_PROP_NOT_SUPPORTED\n");
return MTP_RESPONSE_DEVICE_PROP_NOT_SUPPORTED;
}
MTPD("property %s\n", MtpDebug::getDevicePropCodeName(property));
MTPD("property %x\n", property);
MTPD("MTP_DEVICE_PROPERTY_DEVICE_FRIENDLY_NAME %x\n", MTP_DEVICE_PROPERTY_DEVICE_FRIENDLY_NAME);
switch (property) {
case MTP_DEVICE_PROPERTY_SYNCHRONIZATION_PARTNER:
case MTP_DEVICE_PROPERTY_DEVICE_FRIENDLY_NAME:
result = MTP_RESPONSE_OK;
break;
default: {
MTPE("IMtpDatabase::getDevicePropertyValue property %x not supported\n", property);
result = MTP_RESPONSE_DEVICE_PROP_NOT_SUPPORTED;
break;
}
}
if (result != MTP_RESPONSE_OK) {
MTPD("MTP_REPONSE_OK NOT OK\n");
return result;
}
long longValue = 0;
property_get("ro.build.product", prop_value, "unknown manufacturer");
switch (type) {
case MTP_TYPE_INT8: {
MTPD("MTP_TYPE_INT8\n");
packet.putInt8(longValue);
break;
}
case MTP_TYPE_UINT8: {
MTPD("MTP_TYPE_UINT8\n");
packet.putUInt8(longValue);
break;
}
case MTP_TYPE_INT16: {
MTPD("MTP_TYPE_INT16\n");
packet.putInt16(longValue);
break;
}
case MTP_TYPE_UINT16: {
MTPD("MTP_TYPE_UINT16\n");
packet.putUInt16(longValue);
break;
}
case MTP_TYPE_INT32: {
MTPD("MTP_TYPE_INT32\n");
packet.putInt32(longValue);
break;
}
case MTP_TYPE_UINT32: {
MTPD("MTP_TYPE_UINT32\n");
packet.putUInt32(longValue);
break;
}
case MTP_TYPE_INT64: {
MTPD("MTP_TYPE_INT64\n");
packet.putInt64(longValue);
break;
}
case MTP_TYPE_UINT64: {
MTPD("MTP_TYPE_UINT64\n");
packet.putUInt64(longValue);
break;
}
case MTP_TYPE_INT128: {
MTPD("MTP_TYPE_INT128\n");
packet.putInt128(longValue);
break;
}
case MTP_TYPE_UINT128: {
MTPD("MTP_TYPE_UINT128\n");
packet.putInt128(longValue);
break;
}
case MTP_TYPE_STR: {
MTPD("MTP_TYPE_STR\n");
char* str = prop_value;
packet.putString(str);
break;
}
default:
MTPE("IMtpDatabase::getDevicePropertyValue unsupported type %i in getDevicePropertyValue\n",
type);
return MTP_RESPONSE_INVALID_DEVICE_PROP_FORMAT;
}
return MTP_RESPONSE_OK;
}
MtpResponseCode IMtpDatabase::setDevicePropertyValue(__attribute__((unused))
MtpDeviceProperty property,
__attribute__((unused))
MtpDataPacket& packet) {
MTPE("IMtpDatabase::setDevicePropertyValue not implemented, returning 0\n");
return 0;
}
MtpResponseCode IMtpDatabase::resetDeviceProperty(__attribute__((unused))
MtpDeviceProperty property) {
MTPE("IMtpDatabase::resetDeviceProperty not implemented, returning -1\n");
return -1;
}
MtpResponseCode IMtpDatabase::getObjectPropertyList(MtpObjectHandle handle, uint32_t format,
uint32_t property, int groupCode, int depth,
MtpDataPacket& packet) {
MTPD("getObjectPropertyList()\n");
MTPD("property: %x\n", property);
std::map<int, MtpStorage*>::iterator storit;
for (storit = storagemap.begin(); storit != storagemap.end(); storit++) {
MTPD("IMtpDatabase::getObjectPropertyList calling getObjectPropertyList\n");
if (storit->second->getObjectPropertyList(handle, format, property, groupCode, depth, packet) ==
0) {
MTPD("MTP_RESPONSE_OK\n");
return MTP_RESPONSE_OK;
}
}
MTPE("IMtpDatabase::getObjectPropertyList MTP_RESPONSE_INVALID_OBJECT_HANDLE %i\n", handle);
return MTP_RESPONSE_INVALID_OBJECT_HANDLE;
}
MtpResponseCode IMtpDatabase::getObjectInfo(MtpObjectHandle handle, MtpObjectInfo& info) {
std::map<int, MtpStorage*>::iterator storit;
for (storit = storagemap.begin(); storit != storagemap.end(); storit++) {
if (storit->second->getObjectInfo(handle, info) == 0) {
MTPD("MTP_RESPONSE_OK\n");
return MTP_RESPONSE_OK;
}
}
MTPE("IMtpDatabase::getObjectInfo MTP_RESPONSE_INVALID_OBJECT_HANDLE %i\n", handle);
return MTP_RESPONSE_INVALID_OBJECT_HANDLE;
}
void* IMtpDatabase::getThumbnail(__attribute__((unused)) MtpObjectHandle handle,
__attribute__((unused)) size_t& outThumbSize) {
MTPE("IMtpDatabase::getThumbnail not implemented, returning 0\n");
return 0;
}
MtpResponseCode IMtpDatabase::getObjectFilePath(MtpObjectHandle handle,
MtpStringBuffer& outFilePath,
int64_t& outFileLength,
MtpObjectFormat& outFormat) {
std::map<int, MtpStorage*>::iterator storit;
for (storit = storagemap.begin(); storit != storagemap.end(); storit++) {
MTPD("IMtpDatabase::getObjectFilePath calling getObjectFilePath\n");
if (storit->second->getObjectFilePath(handle, outFilePath, outFileLength, outFormat) == 0) {
MTPD("MTP_RESPONSE_OK\n");
return MTP_RESPONSE_OK;
}
}
MTPE("IMtpDatabase::getObjectFilePath MTP_RESPONSE_INVALID_OBJECT_HANDLE %i\n", handle);
return MTP_RESPONSE_INVALID_OBJECT_HANDLE;
}
// MtpResponseCode IMtpDatabase::deleteFile(MtpObjectHandle handle) {
// MTPD("IMtpDatabase::deleteFile\n");
// std::map<int, MtpStorage*>::iterator storit;
// for (storit = storagemap.begin(); storit != storagemap.end(); storit++) {
// if (storit->second->deleteFile(handle) == 0) {
// MTPD("MTP_RESPONSE_OK\n");
// return MTP_RESPONSE_OK;
// }
// }
// MTPE("IMtpDatabase::deleteFile MTP_RESPONSE_INVALID_OBJECT_HANDLE %i\n", handle);
// return MTP_RESPONSE_INVALID_OBJECT_HANDLE;
// }
struct PropertyTableEntry {
MtpObjectProperty property;
int type;
};
static const PropertyTableEntry kObjectPropertyTable[] = {
{ MTP_PROPERTY_STORAGE_ID, MTP_TYPE_UINT32 },
{ MTP_PROPERTY_OBJECT_FORMAT, MTP_TYPE_UINT16 },
{ MTP_PROPERTY_PROTECTION_STATUS, MTP_TYPE_UINT16 },
{ MTP_PROPERTY_OBJECT_SIZE, MTP_TYPE_UINT64 },
{ MTP_PROPERTY_OBJECT_FILE_NAME, MTP_TYPE_STR },
{ MTP_PROPERTY_DATE_MODIFIED, MTP_TYPE_STR },
{ MTP_PROPERTY_PARENT_OBJECT, MTP_TYPE_UINT32 },
{ MTP_PROPERTY_PERSISTENT_UID, MTP_TYPE_UINT128 },
{ MTP_PROPERTY_NAME, MTP_TYPE_STR },
{ MTP_PROPERTY_DISPLAY_NAME, MTP_TYPE_STR },
{ MTP_PROPERTY_DATE_ADDED, MTP_TYPE_STR },
{ MTP_PROPERTY_ARTIST, MTP_TYPE_STR },
{ MTP_PROPERTY_ALBUM_NAME, MTP_TYPE_STR },
{ MTP_PROPERTY_ALBUM_ARTIST, MTP_TYPE_STR },
{ MTP_PROPERTY_TRACK, MTP_TYPE_UINT16 },
{ MTP_PROPERTY_ORIGINAL_RELEASE_DATE, MTP_TYPE_STR },
{ MTP_PROPERTY_GENRE, MTP_TYPE_STR },
{ MTP_PROPERTY_COMPOSER, MTP_TYPE_STR },
{ MTP_PROPERTY_DURATION, MTP_TYPE_UINT32 },
{ MTP_PROPERTY_DESCRIPTION, MTP_TYPE_STR },
};
static const PropertyTableEntry kDevicePropertyTable[] = {
{ MTP_DEVICE_PROPERTY_SYNCHRONIZATION_PARTNER, MTP_TYPE_STR },
{ MTP_DEVICE_PROPERTY_DEVICE_FRIENDLY_NAME, MTP_TYPE_STR },
{ MTP_DEVICE_PROPERTY_IMAGE_SIZE, MTP_TYPE_STR },
};
bool IMtpDatabase::getObjectPropertyInfo(MtpObjectProperty property, int& type) {
int count = sizeof(kObjectPropertyTable) / sizeof(kObjectPropertyTable[0]);
const PropertyTableEntry* entry = kObjectPropertyTable;
MTPD("IMtpDatabase::getObjectPropertyInfo size is: %i\n", count);
for (int i = 0; i < count; i++, entry++) {
if (entry->property == property) {
type = entry->type;
return true;
}
}
return false;
}
bool IMtpDatabase::getDevicePropertyInfo(MtpDeviceProperty property, int& type) {
int count = sizeof(kDevicePropertyTable) / sizeof(kDevicePropertyTable[0]);
const PropertyTableEntry* entry = kDevicePropertyTable;
MTPD("IMtpDatabase::getDevicePropertyInfo count is: %i\n", count);
for (int i = 0; i < count; i++, entry++) {
if (entry->property == property) {
type = entry->type;
MTPD("type: %x\n", type);
return true;
}
}
return false;
}
MtpObjectHandleList* IMtpDatabase::getObjectReferences(MtpObjectHandle handle) {
// call function and place files with associated handles into int array
MTPD(
"IMtpDatabase::getObjectReferences returning null, this seems to be what Android always "
"does.\n");
MTPD("handle: %d\n", handle);
// Windows + Android seems to always return a NULL in this function, c == null path
// The way that this is handled in Android then is to do this:
return NULL;
}
MtpResponseCode IMtpDatabase::setObjectReferences(__attribute__((unused)) MtpObjectHandle handle,
__attribute__((unused))
MtpObjectHandleList* references) {
MTPE("IMtpDatabase::setObjectReferences not implemented, returning 0\n");
return 0;
}
MtpProperty* IMtpDatabase::getObjectPropertyDesc(MtpObjectProperty property,
MtpObjectFormat format) {
MTPD("IMtpDatabase::getObjectPropertyDesc start\n");
MtpProperty* result = NULL;
switch (property) {
case MTP_PROPERTY_OBJECT_FORMAT:
// use format as default value
result = new MtpProperty(property, MTP_TYPE_UINT16, false, format);
break;
case MTP_PROPERTY_PROTECTION_STATUS:
case MTP_PROPERTY_TRACK:
result = new MtpProperty(property, MTP_TYPE_UINT16);
break;
case MTP_PROPERTY_STORAGE_ID:
case MTP_PROPERTY_PARENT_OBJECT:
case MTP_PROPERTY_DURATION:
result = new MtpProperty(property, MTP_TYPE_UINT32);
break;
case MTP_PROPERTY_OBJECT_SIZE:
result = new MtpProperty(property, MTP_TYPE_UINT64);
break;
case MTP_PROPERTY_PERSISTENT_UID:
result = new MtpProperty(property, MTP_TYPE_UINT128);
break;
case MTP_PROPERTY_NAME:
case MTP_PROPERTY_DISPLAY_NAME:
case MTP_PROPERTY_ARTIST:
case MTP_PROPERTY_ALBUM_NAME:
case MTP_PROPERTY_ALBUM_ARTIST:
case MTP_PROPERTY_GENRE:
case MTP_PROPERTY_COMPOSER:
case MTP_PROPERTY_DESCRIPTION:
result = new MtpProperty(property, MTP_TYPE_STR);
break;
case MTP_PROPERTY_DATE_MODIFIED:
case MTP_PROPERTY_DATE_ADDED:
case MTP_PROPERTY_ORIGINAL_RELEASE_DATE:
result = new MtpProperty(property, MTP_TYPE_STR);
result->setFormDateTime();
break;
case MTP_PROPERTY_OBJECT_FILE_NAME:
// We allow renaming files and folders
result = new MtpProperty(property, MTP_TYPE_STR, true);
break;
}
return result;
}
MtpProperty* IMtpDatabase::getDevicePropertyDesc(MtpDeviceProperty property) {
MtpProperty* result = NULL;
bool writable = false;
switch (property) {
case MTP_DEVICE_PROPERTY_SYNCHRONIZATION_PARTNER:
case MTP_DEVICE_PROPERTY_DEVICE_FRIENDLY_NAME:
writable = true;
// fall through
case MTP_DEVICE_PROPERTY_IMAGE_SIZE:
result = new MtpProperty(property, MTP_TYPE_STR, writable);
// get current value
// TODO: add actual values
result->setCurrentValue(0);
result->setDefaultValue(0);
break;
}
return result;
}
void IMtpDatabase::sessionStarted() {
MTPD("IMtpDatabase::sessionStarted not implemented or does nothing, returning\n");
return;
}
void IMtpDatabase::sessionEnded() {
MTPD("IMtpDatabase::sessionEnded not implemented or does nothing, returning\n");
return;
}
// ----------------------------------------------------------------------------
void IMtpDatabase::lockMutex(void) {
std::map<int, MtpStorage*>::iterator storit;
for (storit = storagemap.begin(); storit != storagemap.end(); storit++) {
storit->second->lockMutex(0);
}
}
void IMtpDatabase::unlockMutex(void) {
std::map<int, MtpStorage*>::iterator storit;
for (storit = storagemap.begin(); storit != storagemap.end(); storit++) {
storit->second->unlockMutex(0);
}
}
MtpResponseCode IMtpDatabase::beginDeleteObject(MtpObjectHandle handle) {
MTPD("IMtoDatabase::beginDeleteObject handle: %u\n", handle);
std::map<int, MtpStorage*>::iterator storit;
for (storit = storagemap.begin(); storit != storagemap.end(); storit++) {
if (storit->second->deleteFile(handle) == 0) {
MTPD("IMtpDatabase::beginDeleteObject::MTP_RESPONSE_OK\n");
return MTP_RESPONSE_OK;
}
}
return MTP_RESPONSE_INVALID_OBJECT_HANDLE;
}
void IMtpDatabase::endDeleteObject(MtpObjectHandle handle __unused, bool succeeded __unused) {
MTPD("IMtpDatabase::endDeleteObject not implemented yet\n");
}
void IMtpDatabase::rescanFile(const char* path __unused, MtpObjectHandle handle __unused,
MtpObjectFormat format __unused) {
MTPD("IMtpDatabase::rescanFile not implemented yet\n");
}
MtpResponseCode IMtpDatabase::beginMoveObject(MtpObjectHandle handle __unused,
MtpObjectHandle newParent __unused,
MtpStorageID newStorage __unused) {
MTPD("IMtpDatabase::beginMoveObject not implemented yet\n");
return MTP_RESPONSE_INVALID_OBJECT_HANDLE;
}
void IMtpDatabase::endMoveObject(MtpObjectHandle oldParent __unused,
MtpObjectHandle newParent __unused,
MtpStorageID oldStorage __unused, MtpStorageID newStorage __unused,
MtpObjectHandle handle __unused, bool succeeded __unused) {
MTPD("IMtpDatabase::endMoveObject not implemented yet\n");
}
MtpResponseCode IMtpDatabase::beginCopyObject(MtpObjectHandle handle __unused,
MtpObjectHandle newParent __unused,
MtpStorageID newStorage __unused) {
MTPD("IMtpDatabase::beginCopyObject not implemented yet\n");
return MTP_RESPONSE_INVALID_OBJECT_HANDLE;
}
void IMtpDatabase::endCopyObject(MtpObjectHandle handle __unused, bool succeeded __unused) {
MTPD("IMtpDatabase::endCopyObject not implemented yet\n");
}
| 33.743831
| 98
| 0.746309
|
imranpopz
|
399b5fe9995c29421efdc58b92713c79652f4502
| 292
|
cc
|
C++
|
storage/sharding/sharding.cc
|
hjinlin/toft
|
ebf3ebb3d37e9a59e27b197cefe8fdc3e8810441
|
[
"BSD-3-Clause"
] | 264
|
2015-01-03T11:50:17.000Z
|
2022-03-17T02:38:34.000Z
|
storage/sharding/sharding.cc
|
hjinlin/toft
|
ebf3ebb3d37e9a59e27b197cefe8fdc3e8810441
|
[
"BSD-3-Clause"
] | 12
|
2015-04-27T15:17:34.000Z
|
2021-05-01T04:31:18.000Z
|
storage/sharding/sharding.cc
|
hjinlin/toft
|
ebf3ebb3d37e9a59e27b197cefe8fdc3e8810441
|
[
"BSD-3-Clause"
] | 128
|
2015-02-07T18:13:10.000Z
|
2022-02-21T14:24:14.000Z
|
// Copyright (c) 2013, The Toft Authors.
// All rights reserved.
//
// Author: Ye Shunping <yeshunping@gmail.com>
#include "toft/storage/sharding/sharding.h"
namespace toft {
ShardingPolicy::ShardingPolicy() : shard_num_(1) {
}
ShardingPolicy::~ShardingPolicy() {
}
} // namespace util
| 17.176471
| 50
| 0.708904
|
hjinlin
|
399b7ec3c214faa112b544b4bb526a1dde110857
| 387
|
cpp
|
C++
|
recursion/6.cpp
|
ChiragLohani/Dsa-placement
|
be68273528283c41f7598169425b1e731d0eacb9
|
[
"Apache-2.0"
] | null | null | null |
recursion/6.cpp
|
ChiragLohani/Dsa-placement
|
be68273528283c41f7598169425b1e731d0eacb9
|
[
"Apache-2.0"
] | null | null | null |
recursion/6.cpp
|
ChiragLohani/Dsa-placement
|
be68273528283c41f7598169425b1e731d0eacb9
|
[
"Apache-2.0"
] | null | null | null |
#include <iostream>
using namespace std;
double sum_recursive(int n)
{
if (n <= 0) {
return 0.0;
} else {
cout << "1/" << n << (n!=1 ? " + " : " = "); // just for debugging
return (1.0 / double(n)) + sum_recursive(n-1);
}
}
int main()
{
int x;
cin>>x;
cout << sum_recursive(x) << " (recursive)" << endl;
return 0;
}
| 18.428571
| 75
| 0.459948
|
ChiragLohani
|
399f3ab199b29023dc728aec59c3b2639f73c2b5
| 392
|
cpp
|
C++
|
demo/main.cpp
|
IonkinaM/lab2
|
aa06f0430b589b8720bdf883925b4538de395045
|
[
"MIT"
] | null | null | null |
demo/main.cpp
|
IonkinaM/lab2
|
aa06f0430b589b8720bdf883925b4538de395045
|
[
"MIT"
] | null | null | null |
demo/main.cpp
|
IonkinaM/lab2
|
aa06f0430b589b8720bdf883925b4538de395045
|
[
"MIT"
] | null | null | null |
#include <header.hpp>
int main() {
const int L1 = 128;
const int L2 = 12288;
int *values = new int(9);
int k = 16;
filling_arr(values, count(L1, L2), k);
values[8] = pow(2, 20)*3;
print(values, count(L1, L2), std::cout);
delete(values);
// apple silicon 2 уровня кэша, первый = 128кб, второй = 8мб
// 64kb < 128kb < 256kb << 512kb << 1Mb << 2mb << 4mb << 8mb << 12mb
}
| 23.058824
| 70
| 0.589286
|
IonkinaM
|
39a30b122ce0e19281d620512e0297bd264d747e
| 161
|
cpp
|
C++
|
LuoguCodes/AT3918.cpp
|
Anguei/OI-Codes
|
0ef271e9af0619d4c236e314cd6d8708d356536a
|
[
"MIT"
] | null | null | null |
LuoguCodes/AT3918.cpp
|
Anguei/OI-Codes
|
0ef271e9af0619d4c236e314cd6d8708d356536a
|
[
"MIT"
] | null | null | null |
LuoguCodes/AT3918.cpp
|
Anguei/OI-Codes
|
0ef271e9af0619d4c236e314cd6d8708d356536a
|
[
"MIT"
] | null | null | null |
//【AT3918】Infinite Coins - 洛谷 - Wa
#include <iostream>
int main() {
int n, m;
std::cin >> n >> m;
std::cout << (n % 500 <= m ? "Yes" : "No") << std::endl;
}
| 20.125
| 57
| 0.509317
|
Anguei
|
39a32f5be200a05c51505a5fcb4cc8b85c8aa370
| 7,389
|
cpp
|
C++
|
src/irt/translator/expr.cpp
|
martinogden/mer
|
33b4b39b1604ce0708b0d3d1c809b95683a2f4cb
|
[
"Unlicense"
] | 2
|
2019-11-17T22:54:16.000Z
|
2020-08-07T20:53:25.000Z
|
src/irt/translator/expr.cpp
|
martinogden/mer
|
33b4b39b1604ce0708b0d3d1c809b95683a2f4cb
|
[
"Unlicense"
] | null | null | null |
src/irt/translator/expr.cpp
|
martinogden/mer
|
33b4b39b1604ce0708b0d3d1c809b95683a2f4cb
|
[
"Unlicense"
] | null | null | null |
#include "type/comparison.hpp"
#include "irt/size-analyser.hpp"
#include "irt/translator/utils.hpp"
#include "irt/translator/expr.hpp"
#include "irt/translator/bool-expr.hpp"
#include "irt/translator/lvalue.hpp"
ExprTranslator::ExprTranslator(Generator& gen, Map<IRTStruct>& structs) :
gen(gen),
structs(structs),
retval(nullptr)
{}
std::string ExprTranslator::freshLabel() {
return gen.label();
}
std::string ExprTranslator::freshTmp() {
return gen.tmp();
}
IRTStruct& ExprTranslator::getIRTStruct(const std::string& name) {
return structs.lookup(name);
}
void ExprTranslator::ret(CmdExprPtr val) {
retval = std::move(val);
}
void ExprTranslator::ret(IRTCmdPtr cmd, IRTExprPtr e) {
retval = std::make_unique<CmdExpr>(std::move(cmd), std::move(e));
}
CmdExprPtr ExprTranslator::get(Expr* expr) {
expr->accept(*this);
return std::move(retval);
}
CmdExprPtr ExprTranslator::get(ExprPtr expr) {
if (eq(expr->type, Type::BOOL))
return transBool( std::move(expr) );
expr->accept(*this);
return std::move(retval);
}
CmdExprPtr ExprTranslator::getAsLValue(ExprPtr expr) {
LValueTranslator lvt(*this);
return lvt.get(expr.get());
}
void ExprTranslator::visit(CallExpr& expr) {
std::vector<IRTCmdPtr> cmds;
std::vector<std::string> args;
for (auto& arg : expr.args) {
CmdExprPtr e = get( std::move(arg) );
std::string tmp = freshTmp();
cmds.push_back( std::move(e->cmd) );
cmds.push_back( std::make_unique<AssignCmd>(tmp, std::move(e->expr)) );
args.push_back(tmp);
}
std::string t = freshTmp();
cmds.push_back( std::make_unique<CallCmd>(t, expr.identifier, std::move(args)) );
ret( concat( std::move(cmds) ), std::make_unique<IRTIdExpr>(t) );
}
void ExprTranslator::visit(AllocExpr& expr) {
std::string tmp = freshTmp();
std::string param1 = freshTmp();
uint sz;
if ( auto t = dynamic_cast<StructType*>(expr.typeParam.get()) )
sz = structs.lookup(t->name).size;
else {
TypeSizeAnalyser tsa;
sz = tsa.get(expr.type);
}
IRTExprPtr size = std::make_unique<IRTIntExpr>(sz);
std::vector<IRTCmdPtr> cmds;
cmds.push_back( std::make_unique<AssignCmd>(param1, std::move(size)) );
std::vector<std::string> args;
std::string label;
if (expr.expr) {
std::string param2 = freshTmp();
CmdExprPtr e = get( std::move(expr.expr) );
cmds.push_back( std::move(e->cmd) );
cmds.push_back( std::make_unique<AssignCmd>(param2, std::move(e->expr)) );
args = {param1, param2};
label = "alloc_array";
}
else {
args = {param1};
label = "alloc";
}
cmds.push_back( std::make_unique<CallCmd>(tmp, "_c0_" + label, std::move(args)) );
ret( concat(std::move(cmds)), std::make_unique<IRTIdExpr>(tmp) );
}
void ExprTranslator::visit(TernaryExpr& expr) {
assert(eq(expr.type, Type::INT));
BoolExprTranslator btr(*this);
std::string l1 = freshLabel();
std::string l2 = freshLabel();
std::string l3 = freshLabel();
CmdExprPtr then = get( std::move(expr.then) );
CmdExprPtr otherwise = get( std::move(expr.otherwise) );
std::string t = freshTmp();
std::vector<IRTCmdPtr> cmds;
cmds.push_back( btr.get( std::move(expr.cond), l1, l2 ) );
cmds.push_back( std::make_unique<LabelCmd>(l1) );
cmds.push_back( std::move(then->cmd) );
cmds.push_back( std::make_unique<AssignCmd>(t, std::move(then->expr)) );
cmds.push_back( std::make_unique<GotoCmd>(l3) );
cmds.push_back( std::make_unique<LabelCmd>(l2) );
cmds.push_back( std::move(otherwise->cmd) );
cmds.push_back( std::make_unique<AssignCmd>(t, std::move(otherwise->expr)) );
cmds.push_back( std::make_unique<GotoCmd>(l3) );
cmds.push_back( std::make_unique<LabelCmd>(l3) );
IRTCmdPtr cmd = concat( std::move(cmds) );
ret( std::move(cmd), std::make_unique<IRTIdExpr>(t) );
}
void ExprTranslator::visit(BinaryExpr& expr) {
assert(eq(expr.type, Type::INT));
CmdExprPtr lhs = get( std::move(expr.left) );
CmdExprPtr rhs = get( std::move(expr.right) );
IRTCmdPtr left = std::move(lhs->cmd);
IRTCmdPtr right = std::move(rhs->cmd);
assert(left && right);
IRTCmdPtr cmd = std::make_unique<SeqCmd>( std::move(left), std::move(right) );
IRTExprPtr e;
if ( isPureOp(expr.op) )
e = std::make_unique<IRTBinaryExpr>(expr.op, std::move(lhs->expr), std::move(rhs->expr));
else {
std::string t = freshTmp();
std::vector<IRTCmdPtr> cmds;
cmds.push_back( std::move(cmd) );
cmds.push_back( std::make_unique<EffAssignCmd>(t, expr.op, std::move(lhs->expr), std::move(rhs->expr)) );
cmd = concat( std::move(cmds) );
e = std::make_unique<IRTIdExpr>(t);
}
ret( std::move(cmd), std::move(e) );
}
void ExprTranslator::visit(UnaryExpr& unary) {
assert(eq(unary.type, Type::INT));
CmdExprPtr e = get( std::move(unary.expr) );
IRTExprPtr expr;
IRTExprPtr zero = std::make_unique<IRTIntExpr>(0);
IRTExprPtr neg = std::make_unique<IRTBinaryExpr>(BinOp::SUB, std::move(zero), std::move(e->expr));
if (unary.op == UnOp::NEG)
expr = std::move(neg);
else if (unary.op == UnOp::BIT_NOT) {
// ~x = -x - 1
IRTExprPtr one = std::make_unique<IRTIntExpr>(1);
expr = std::make_unique<IRTBinaryExpr>(BinOp::SUB, std::move(neg), std::move(one));
}
else
throw 1; // we should never get here
ret( std::move(e->cmd), std::move(expr) );
}
void ExprTranslator::visit(LiteralExpr& expr) {
assert(eq(expr.type, Type::INT) || eq(expr.type, Type::INDEF));
int64_t val = expr.as.i;
if (val >= INT32_MAX) {
std::string t = freshTmp();
ret( std::make_unique<AssignCmd>(t, std::make_unique<IRTIntExpr>(val)), std::make_unique<IRTIdExpr>(t) );
}
else
ret( std::make_unique<NopCmd>(), std::make_unique<IRTIntExpr>(val) );
}
void ExprTranslator::visit(IdExpr& expr) {
ret( std::make_unique<NopCmd>(), std::make_unique<IRTIdExpr>(expr.identifier) );
}
void ExprTranslator::visit(SubscriptExpr& expr) {
ret( toRValue(expr) );
}
void ExprTranslator::visit(ArrowExpr& expr) {
throw 1; // we should never get here
}
void ExprTranslator::visit(DotExpr& expr) {
ret( toRValue(expr) );
}
void ExprTranslator::visit(DerefExpr& expr) {
ret( toRValue(expr) );
}
CmdExprPtr ExprTranslator::toRValue(Expr& expr) {
LValueTranslator lvt(*this);
CmdExprPtr e = lvt.get(&expr);
if ( dynamic_cast<IRTMemExpr*>(e->expr.get()) ) {
std::string addr = freshTmp();
std::string tmp = freshTmp();
std::vector<IRTCmdPtr> cmds;
cmds.push_back( std::move(e->cmd) );
cmds.push_back( std::make_unique<LoadCmd>(tmp, std::move(e->expr)) );
return std::make_unique<CmdExpr>( concat(std::move(cmds)), std::make_unique<IRTIdExpr>(tmp) );
}
else throw 1; // we should never get here
}
CmdExprPtr ExprTranslator::transBool(ExprPtr expr) {
BoolExprTranslator btr(*this);
std::string l1 = freshLabel();
std::string l2 = freshLabel();
std::string l3 = freshLabel();
std::string t = freshTmp();
std::vector<IRTCmdPtr> cmds;
cmds.push_back( btr.get(std::move(expr), l1, l2) );
cmds.push_back( std::make_unique<LabelCmd>(l1) );
cmds.push_back( std::make_unique<AssignCmd>(t, std::make_unique<IRTIntExpr>(1)) );
cmds.push_back( std::make_unique<GotoCmd>(l3) );
cmds.push_back( std::make_unique<LabelCmd>(l2) );
cmds.push_back( std::make_unique<AssignCmd>(t, std::make_unique<IRTIntExpr>(0)) );
cmds.push_back( std::make_unique<GotoCmd>(l3) );
cmds.push_back( std::make_unique<LabelCmd>(l3) );
IRTCmdPtr cmd = concat( std::move(cmds) );
return std::make_unique<CmdExpr>(std::move(cmd), std::make_unique<IRTIdExpr>(t));
}
| 25.926316
| 107
| 0.68223
|
martinogden
|
39aca69969eed09551e2ce784791eeac654e9393
| 135
|
cpp
|
C++
|
unix/reverse.cpp
|
kybr/MAT240B-2019
|
d3a875f90e12df195a172b4f4f485153d4251086
|
[
"MIT"
] | null | null | null |
unix/reverse.cpp
|
kybr/MAT240B-2019
|
d3a875f90e12df195a172b4f4f485153d4251086
|
[
"MIT"
] | null | null | null |
unix/reverse.cpp
|
kybr/MAT240B-2019
|
d3a875f90e12df195a172b4f4f485153d4251086
|
[
"MIT"
] | null | null | null |
#include "everything.h"
using namespace diy;
int main(int argc, char* argv[]) {
//
// reverse the stream of numbers coming in..
}
| 16.875
| 46
| 0.666667
|
kybr
|
39b2fc3009e1ef4d429390a9b45e43976ae93d52
| 1,002
|
cpp
|
C++
|
private/LoadedSQLData.cpp
|
Izowiuz/iz-sql-utilities
|
307a5c791f4e83b13e9a54dfec60fcd4c24b2ca3
|
[
"MIT"
] | 1
|
2019-07-11T07:05:03.000Z
|
2019-07-11T07:05:03.000Z
|
private/LoadedSQLData.cpp
|
Izowiuz/iz-sql-utilities
|
307a5c791f4e83b13e9a54dfec60fcd4c24b2ca3
|
[
"MIT"
] | null | null | null |
private/LoadedSQLData.cpp
|
Izowiuz/iz-sql-utilities
|
307a5c791f4e83b13e9a54dfec60fcd4c24b2ca3
|
[
"MIT"
] | null | null | null |
#include "LoadedSQLData.h"
QMap<int, QString> IzSQLUtilities::LoadedSQLData::indexColumnMap() const
{
return m_indexColumnMap;
}
void IzSQLUtilities::LoadedSQLData::setIndexColumnMap(const QMap<int, QString>& indexColumnMap)
{
m_indexColumnMap = indexColumnMap;
}
void IzSQLUtilities::LoadedSQLData::addRow(std::unique_ptr<SQLRow> row)
{
m_sqlData.push_back(std::move(row));
}
std::vector<QMetaType>& IzSQLUtilities::LoadedSQLData::sqlDataTypes()
{
return m_sqlDataTypes;
}
void IzSQLUtilities::LoadedSQLData::setSqlDataTypes(const std::vector<QMetaType>& sqlDataTypes)
{
m_sqlDataTypes = sqlDataTypes;
}
QHash<QString, int> IzSQLUtilities::LoadedSQLData::columnIndexMap() const
{
return m_columnIndexMap;
}
void IzSQLUtilities::LoadedSQLData::setColumnIndexMap(const QHash<QString, int>& columnIndexMap)
{
m_columnIndexMap = columnIndexMap;
}
std::vector<std::unique_ptr<IzSQLUtilities::SQLRow>>& IzSQLUtilities::LoadedSQLData::sqlData()
{
return m_sqlData;
}
| 23.857143
| 96
| 0.769461
|
Izowiuz
|
39b490bf22346d620848c16c8a008b0d0fb681d5
| 409
|
cpp
|
C++
|
PAT/PAT Basic/1010.cpp
|
Accelerator404/Algorithm-Demonstration
|
e40a499c23a56d363c743c76ac967d9c4247a4be
|
[
"Apache-2.0"
] | 1
|
2019-09-18T23:45:27.000Z
|
2019-09-18T23:45:27.000Z
|
PAT/PAT Basic/1010.cpp
|
Accelerator404/Algorithm-Demonstration
|
e40a499c23a56d363c743c76ac967d9c4247a4be
|
[
"Apache-2.0"
] | null | null | null |
PAT/PAT Basic/1010.cpp
|
Accelerator404/Algorithm-Demonstration
|
e40a499c23a56d363c743c76ac967d9c4247a4be
|
[
"Apache-2.0"
] | 1
|
2019-09-18T23:45:28.000Z
|
2019-09-18T23:45:28.000Z
|
#include <iostream>
using namespace std;
//PAT Advanced No.1010 “一元多项式求导”
int main() {
int c, i;
bool flag = false;
//利用输入动作触发输入循环
while (cin >> c >> i) {
if (c != 0 && i != 0) {
if (flag)
cout << ' ';
else
flag = true;
cout << c * i << ' ' << i - 1;
}
//注意题设中的指数递降,也就是如果第一次就输入指数为0即触发零多项式判断
else if (i == 0 && !flag) {
cout << "0 0" << endl;
return 0;
}
}
return 0;
}
| 15.730769
| 39
| 0.511002
|
Accelerator404
|
39b77990f6b48c3cd3807cdf1c80cb9066de238f
| 317
|
cpp
|
C++
|
sonar_control/src/SonarControl.cpp
|
g4idrijs/underwater_map_construction
|
04c4ebbc094449994f53e280b85db604b468019b
|
[
"MIT"
] | null | null | null |
sonar_control/src/SonarControl.cpp
|
g4idrijs/underwater_map_construction
|
04c4ebbc094449994f53e280b85db604b468019b
|
[
"MIT"
] | null | null | null |
sonar_control/src/SonarControl.cpp
|
g4idrijs/underwater_map_construction
|
04c4ebbc094449994f53e280b85db604b468019b
|
[
"MIT"
] | 1
|
2020-06-28T09:45:26.000Z
|
2020-06-28T09:45:26.000Z
|
#include "SonarControl.h"
SonarControl::SonarControl(ros::NodeHandle* n){
ros::NodeHandle nh("~");
nh.param("cloudSubscribeTopic_", cloudSubscribeTopic_, string("/Sonar/Scan/SonarCloud"));
nh.param("cloudPublishTopic_", cloudPublishTopic_, string("/SonarControl/Cloud"));
}
int main (int argc, char** argv){
}
| 24.384615
| 90
| 0.735016
|
g4idrijs
|
39b8ae6a3265c4a39077cb71a6ff1392672ebffd
| 3,780
|
cpp
|
C++
|
DEM/Low/src/UI/CEGUI/DEMRenderTarget.cpp
|
niello/deusexmachina
|
2f698054fe82d8b40a0a0e58b86d64ffed0de06c
|
[
"MIT"
] | 15
|
2019-05-07T11:26:13.000Z
|
2022-01-12T18:26:45.000Z
|
DEM/Low/src/UI/CEGUI/DEMRenderTarget.cpp
|
niello/deusexmachina
|
2f698054fe82d8b40a0a0e58b86d64ffed0de06c
|
[
"MIT"
] | 16
|
2021-10-04T17:15:31.000Z
|
2022-03-20T09:34:29.000Z
|
DEM/Low/src/UI/CEGUI/DEMRenderTarget.cpp
|
niello/deusexmachina
|
2f698054fe82d8b40a0a0e58b86d64ffed0de06c
|
[
"MIT"
] | 2
|
2019-04-28T23:27:48.000Z
|
2019-05-07T11:26:18.000Z
|
#if defined(_MSC_VER)
# pragma warning(push)
# pragma warning(disable : 4530) // C++ exception handler used, but unwind semantics not enabled
#endif
#include "DEMRenderTarget.h"
#include <Render/GPUDriver.h>
#include <UI/CEGUI/DEMGeometryBuffer.h>
#include <glm/gtc/matrix_transform.hpp>
namespace CEGUI
{
CDEMRenderTarget::CDEMRenderTarget(CDEMRenderer& owner):
d_owner(owner)
{
}
//---------------------------------------------------------------------
void CDEMRenderTarget::activate()
{
if (!d_matrixValid)
updateMatrix(RenderTarget::createViewProjMatrixForDirect3D()); // FIXME: get handedness from GPU
Render::CViewport VP;
VP.Left = static_cast<float>(d_area.left());
VP.Top = static_cast<float>(d_area.top());
VP.Width = static_cast<float>(d_area.getWidth());
VP.Height = static_cast<float>(d_area.getHeight());
VP.MinDepth = 0.0f;
VP.MaxDepth = 1.0f;
d_owner.getGPUDriver()->SetViewport(0, &VP);
d_owner.setViewProjectionMatrix(RenderTarget::d_matrix);
RenderTarget::activate();
}
//---------------------------------------------------------------------
void CDEMRenderTarget::unprojectPoint(const GeometryBuffer& buff, const glm::vec2& p_in, glm::vec2& p_out) const
{
if (!d_matrixValid)
updateMatrix(RenderTarget::createViewProjMatrixForDirect3D()); // FIXME: get handedness from GPU
const CDEMGeometryBuffer& gb = static_cast<const CDEMGeometryBuffer&>(buff);
const I32 vp[4] = {
static_cast<I32>(RenderTarget::d_area.left()),
static_cast<I32>(RenderTarget::d_area.top()),
static_cast<I32>(RenderTarget::d_area.getWidth()),
static_cast<I32>(RenderTarget::d_area.getHeight())
};
float in_x, in_y = 0.0f, in_z = 0.0f;
glm::ivec4 viewPort = glm::ivec4(vp[0], vp[1], vp[2], vp[3]);
const glm::mat4& projMatrix = RenderTarget::d_matrix;
const glm::mat4& modelMatrix = gb.getModelMatrix();
// unproject the ends of the ray
glm::vec3 unprojected1;
glm::vec3 unprojected2;
in_x = vp[2] * 0.5f;
in_y = vp[3] * 0.5f;
in_z = -RenderTarget::d_viewDistance;
unprojected1 = glm::unProject(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);
in_x = p_in.x;
in_y = vp[3] - p_in.y;
in_z = 0.0;
unprojected2 = glm::unProject(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);
// project points to orientate them with GeometryBuffer plane
glm::vec3 projected1;
glm::vec3 projected2;
glm::vec3 projected3;
in_x = 0.0;
in_y = 0.0;
projected1 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);
in_x = 1.0;
in_y = 0.0;
projected2 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);
in_x = 0.0;
in_y = 1.0;
projected3 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);
// calculate vectors for generating the plane
const glm::vec3 pv1 = projected2 - projected1;
const glm::vec3 pv2 = projected3 - projected1;
// given the vectors, calculate the plane normal
const glm::vec3 planeNormal = glm::cross(pv1, pv2);
// calculate plane
const glm::vec3 planeNormalNormalized = glm::normalize(planeNormal);
const double pl_d = - glm::dot(projected1, planeNormalNormalized);
// calculate vector of picking ray
const glm::vec3 rv = unprojected1 - unprojected2;
// calculate intersection of ray and plane
const double pn_dot_r1 = glm::dot(unprojected1, planeNormal);
const double pn_dot_rv = glm::dot(rv, planeNormal);
const double tmp1 = pn_dot_rv != 0.0 ? (pn_dot_r1 + pl_d) / pn_dot_rv : 0.0;
const double is_x = unprojected1.x - rv.x * tmp1;
const double is_y = unprojected1.y - rv.y * tmp1;
p_out.x = static_cast<float>(is_x);
p_out.y = static_cast<float>(is_y);
}
//---------------------------------------------------------------------
}
#if defined(_MSC_VER)
# pragma warning(pop)
#endif
| 33.75
| 112
| 0.682804
|
niello
|
39bd410749a02210b06bcdb9f71d74595f086d29
| 4,367
|
cpp
|
C++
|
read_rope_shared_library/test/test.cpp
|
adct-the-experimenter/read-rope
|
0f8603cf8d6c197266bcaa447cd3ed92714a5b9d
|
[
"BSD-3-Clause"
] | 2
|
2019-12-27T19:41:27.000Z
|
2019-12-27T19:41:38.000Z
|
read_rope_shared_library/test/test.cpp
|
adct-the-experimenter/read-rope
|
0f8603cf8d6c197266bcaa447cd3ed92714a5b9d
|
[
"BSD-3-Clause"
] | null | null | null |
read_rope_shared_library/test/test.cpp
|
adct-the-experimenter/read-rope
|
0f8603cf8d6c197266bcaa447cd3ed92714a5b9d
|
[
"BSD-3-Clause"
] | null | null | null |
#include "readrope.h"
int main(int argc, char** argv)
{
/*
************************************************************
Initialize read rope system
*************************************************************
*/
//initialize read rope system
ReadRope::InitReadRopeSystem();
/*
************************************************************
Initialize serial communication with the read rope device.
************************************************************
*/
std::string port = ReadRope::GetSerialPortOfReadRopeDevice();
if(port != "Null")
{
std::cout << "Read rope device port is " << port << std::endl;
if(ReadRope::InitSerialCommunication(port,9600) == ReadRope::Status::ERROR)
{
std::cout << "Failed to connect to port " << port << "at baud rate of 9600.\n";
}
else
{
std::cout << "Successfully able to connect to read rope device on port " << port << std::endl;
}
}
else
{
std::cout << "Failed to get port of read rope device! \n.";
}
/*
************************************************************
Get ADC Value from read rope device
************************************************************
*/
uint16_t readRopeADCValue = 0;
readRopeADCValue = ReadRope::GetADCValueOfReadRope();
std::cout << "ADC value from read rope: " << readRopeADCValue << std::endl;
/*
************************************************************
Calibration
************************************************************
*/
double calibrationPhaseTime = 7.0;
std::cout << "\nUsing default library calibration methods to calibrate the device...\n";
//Calibrate section zero
std::cout << "Calibrating section 0. Please bend only section zero as much as you can within " \
<< calibrationPhaseTime << " seconds.\n";
ReadRope::CalibrateSectionZeroMaxLimit(calibrationPhaseTime);
//Calibrate section 1
std::cout << "Calibrating section 1. Please bend only section one as much as you can within " \
<< calibrationPhaseTime << " seconds.\n";
ReadRope::CalibrateSectionOneMaxLimit(calibrationPhaseTime);
//Calibrate section 2
std::cout << "Calibrating section 2. Please bend only section two as much as you can within " \
<< calibrationPhaseTime << " seconds.\n";
ReadRope::CalibrateSectionTwoMaxLimit(calibrationPhaseTime);
/*
************************************************************
Get Bend location
************************************************************
*/
bool quit = false;
while(!quit)
{
switch( ReadRope::GetBendLocationFromReadRopeDevice() )
{
case ReadRope::Bend::ERROR_BEND_NO_CALIBRATION:
{
std::cout << "Error bend without calibration\n";
break;
}
case ReadRope::Bend::NO_BEND:
{
std::cout << "No bend detected." << "ADC value:" << ReadRope::GetADCValueOfReadRope() << std::endl;
break;
}
case ReadRope::Bend::BEND_S0:
{
std::cout << "Bend in section 0 detected." << "ADC value:" << ReadRope::GetADCValueOfReadRope() << std::endl;
break;
}
case ReadRope::Bend::BEND_S1:
{
std::cout << "Bend in section 1 detected." << "ADC value:" << ReadRope::GetADCValueOfReadRope() << std::endl;
break;
}
case ReadRope::Bend::BEND_S0_S1:
{
std::cout << "Bend in section 0 and section 1 detected." << "ADC value:" << ReadRope::GetADCValueOfReadRope() << std::endl;
break;
}
case ReadRope::Bend::BEND_S2:
{
std::cout << "Bend in section 2 detected." << "ADC value:" << ReadRope::GetADCValueOfReadRope() << std::endl;
break;
}
case ReadRope::Bend::BEND_S0_S2:
{
std::cout << "Bend in section 0 and section 2 detected." << "ADC value:" << ReadRope::GetADCValueOfReadRope() << std::endl;
break;
}
case ReadRope::Bend::BEND_S1_S2:
{
std::cout << "Bend in section 1 and section 2 detected." << "ADC value:" << ReadRope::GetADCValueOfReadRope() << std::endl;
break;
}
case ReadRope::Bend::BEND_S0_S1_S2:
{
std::cout << "Bend in all 3 sections detected." << "ADC value:" << ReadRope::GetADCValueOfReadRope() << std::endl;
break;
}
}
}
/*
************************************************************
Close read rope system
*************************************************************
*/
ReadRope::CloseReadRopeSystem();
return 0;
}
| 29.113333
| 127
| 0.531257
|
adct-the-experimenter
|
39c39a66067ff8660dbe12126e281a7095d38236
| 63
|
hpp
|
C++
|
src/boost_mpl_aux__preprocessed_dmc_advance_forward.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 10
|
2018-03-17T00:58:42.000Z
|
2021-07-06T02:48:49.000Z
|
src/boost_mpl_aux__preprocessed_dmc_advance_forward.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 2
|
2021-03-26T15:17:35.000Z
|
2021-05-20T23:55:08.000Z
|
src/boost_mpl_aux__preprocessed_dmc_advance_forward.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 4
|
2019-05-28T21:06:37.000Z
|
2021-07-06T03:06:52.000Z
|
#include <boost/mpl/aux_/preprocessed/dmc/advance_forward.hpp>
| 31.5
| 62
| 0.825397
|
miathedev
|
39c899021bc217a26f65a5a907d6aba381dcfb57
| 75
|
cpp
|
C++
|
dev/premake/premake/samples/project/CppConsoleApp/CppConsoleApp.cpp
|
gdewald/Spacefrog
|
eae9bd5c91670f7d13442740b5d801286ba41e5e
|
[
"BSD-2-Clause"
] | 94
|
2015-04-02T05:41:21.000Z
|
2021-11-14T18:30:12.000Z
|
dev/premake/premake/samples/project/CppConsoleApp/CppConsoleApp.cpp
|
gdewald/Spacefrog
|
eae9bd5c91670f7d13442740b5d801286ba41e5e
|
[
"BSD-2-Clause"
] | 18
|
2015-06-16T16:57:14.000Z
|
2021-04-06T18:35:40.000Z
|
dev/premake/premake/samples/project/CppConsoleApp/CppConsoleApp.cpp
|
gdewald/Spacefrog
|
eae9bd5c91670f7d13442740b5d801286ba41e5e
|
[
"BSD-2-Clause"
] | 33
|
2015-04-07T05:43:54.000Z
|
2021-08-21T22:13:03.000Z
|
#include "stdafx.h"
int main()
{
printf("CppConsoleApp\n");
return 0;
}
| 9.375
| 27
| 0.64
|
gdewald
|
39ceba325ee4ff5066f63d189511d29caafabce4
| 351
|
cpp
|
C++
|
Userland/Libraries/LibWeb/DOM/DOMEventListener.cpp
|
densogiaichned/serenity
|
99c0b895fed02949b528437d6b450d85befde7a5
|
[
"BSD-2-Clause"
] | 2
|
2022-02-16T02:12:38.000Z
|
2022-02-20T18:40:41.000Z
|
Userland/Libraries/LibWeb/DOM/DOMEventListener.cpp
|
densogiaichned/serenity
|
99c0b895fed02949b528437d6b450d85befde7a5
|
[
"BSD-2-Clause"
] | null | null | null |
Userland/Libraries/LibWeb/DOM/DOMEventListener.cpp
|
densogiaichned/serenity
|
99c0b895fed02949b528437d6b450d85befde7a5
|
[
"BSD-2-Clause"
] | null | null | null |
/*
* Copyright (c) 2022, Andreas Kling <kling@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibWeb/DOM/AbortSignal.h>
#include <LibWeb/DOM/DOMEventListener.h>
#include <LibWeb/DOM/IDLEventListener.h>
namespace Web::DOM {
DOMEventListener::DOMEventListener() = default;
DOMEventListener::~DOMEventListener() = default;
}
| 23.4
| 59
| 0.746439
|
densogiaichned
|
39cf381804f87c2540f96d09de47f01591f1f485
| 3,195
|
hpp
|
C++
|
include/metrics/m_psnr.hpp
|
ecarpita93/HPC_projet_1
|
a2c00e056c03227711c43cf2ad23d75c6afbe698
|
[
"Xnet",
"X11"
] | null | null | null |
include/metrics/m_psnr.hpp
|
ecarpita93/HPC_projet_1
|
a2c00e056c03227711c43cf2ad23d75c6afbe698
|
[
"Xnet",
"X11"
] | null | null | null |
include/metrics/m_psnr.hpp
|
ecarpita93/HPC_projet_1
|
a2c00e056c03227711c43cf2ad23d75c6afbe698
|
[
"Xnet",
"X11"
] | null | null | null |
/*
PICCANTE
The hottest HDR imaging library!
http://vcg.isti.cnr.it/piccante
Copyright (C) 2014
Visual Computing Laboratory - ISTI CNR
http://vcg.isti.cnr.it
First author: Francesco Banterle
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifndef PIC_METRICS_M_PSNR_HPP
#define PIC_METRICS_M_PSNR_HPP
#include <math.h>
#include "../base.hpp"
#include "../util/array.hpp"
#include "../image.hpp"
#include "../tone_mapping/get_all_exposures.hpp"
#include "../metrics/base.hpp"
#include "../metrics/mse.hpp"
namespace pic {
enum MULTI_EXPOSURE_TYPE{MET_HISTOGRAM, MET_MIN_MAX, MET_FROM_INPUT};
/**
* @brief mPSNR computes the multiple-exposure peak signal-to-noise ratio (mPSNR) between two images.
* @param ori is the original image.
* @param cmp is the distorted image.
* @param type.
* @param minFstop is the minimum f-stop value of ori.
* @param maxFstop is the maximum f-stop value of ori.
* @return It returns the nMPSR error value between ori and cmp.
*/
PIC_INLINE double mPSNR(Image *ori, Image *cmp, MULTI_EXPOSURE_TYPE type, int minFstop = 0, int maxFstop = 0)
{
if(ori == NULL || cmp == NULL) {
return -2.0;
}
if(!ori->isValid() || !cmp->isValid()) {
return -3.0;
}
if(!ori->isSimilarType(cmp)) {
return -1.0;
}
std::vector<float> exposures;
switch (type) {
case MET_HISTOGRAM: {
exposures = getAllExposures(ori);
} break;
case MET_MIN_MAX: {
if(minFstop == maxFstop) {
getMinMaxFstops(ori, minFstop, maxFstop);
}
int nExposures_v = 0;
float *exposures_v = NULL;
Arrayf::genRange(float(minFstop), 1.0f, float(maxFstop), exposures_v, nExposures_v);
exposures.insert(exposures.begin(), exposures_v, exposures_v + nExposures_v);
} break;
case MET_FROM_INPUT: {
for(int i = minFstop; i <= maxFstop; i++) {
exposures.push_back(float(i));
}
} break;
}
if(exposures.empty()) {
return -5.0;
}
#ifdef PIC_DEBUG
printf("-------------------------------------------------------\n");
printf("-- mPSNR:\n");
printf("-- min F-stop: %d \t max F-stop: %d\n", minFstop, maxFstop);
#endif
int nBit = 8;
float gamma = 2.2f; //typically 2.2
auto n = exposures.size();
double mse = 0.0;
for(auto i = 0; i < n; i++) {
double mse_i = MSE(ori, cmp, gamma, exposures[i], nBit);
#ifdef PIC_DEBUG
printf("-- Pass: %d \t MSE: %g\n", i, mse_i);
#endif
mse += mse_i;
}
mse /= double(n * ori->channels);
int nValues = (1 << nBit) - 1;
double nValuesd = double(nValues);
double ret = 10.0 * log10((nValuesd * nValuesd) / mse);
#ifdef PIC_DEBUG
printf("-- value: %f\n", ret);
printf("-------------------------------------------------------");
#endif
return ret;
}
} // end namespace pic
#endif /* PIC_METRICS_M_PSNR_HPP */
| 24.767442
| 109
| 0.57903
|
ecarpita93
|
39cf9236712bfa5b82bcf8db2a7f5e9f71783921
| 2,155
|
cc
|
C++
|
AbsEnv/AbsDetEnv.cc
|
brownd1978/FastSim
|
05f590d72d8e7f71856fd833114a38b84fc7fd48
|
[
"Apache-2.0"
] | null | null | null |
AbsEnv/AbsDetEnv.cc
|
brownd1978/FastSim
|
05f590d72d8e7f71856fd833114a38b84fc7fd48
|
[
"Apache-2.0"
] | null | null | null |
AbsEnv/AbsDetEnv.cc
|
brownd1978/FastSim
|
05f590d72d8e7f71856fd833114a38b84fc7fd48
|
[
"Apache-2.0"
] | null | null | null |
//--------------------------------------------------------------------------
// File and Version Information:
// $Id: AbsDetEnv.cc 483 2010-01-13 14:03:08Z stroili $
//
// Description:
// Class AbsDetEnv
//
// Abstract class for detector envirnoments. Individual
// detectors' environment classes will inherit from this
// class and define their own environment variables. Access
// to these variables is via an asbtract structure, which
// also contains neighbour information. See EmcEnv.cc/hh for
// an example.
//
//
// Environment:
// Software developed for the BaBar Detector at the SLAC B-Factory.
//
// Author List:
// Bob Jacobsen Original Author
// Stephen J. Gowdy University Of Edinburgh
// Phil Strother Imperial College
//
// Copyright Information:
// Copyright (C) 1995, 1996 Lawrence Berkeley Laboratory
//
//------------------------------------------------------------------------
#include "BaBar/BaBar.hh"
//-----------------------
// This Class's Header --
//-----------------------
#include "AbsEnv/AbsDetEnv.hh"
//-------------
// C Headers --
//-------------
//#include <assert.h>
//#include <string.h>
#include <iostream>
//-------------------------------
// Collaborating Class Headers --
//-------------------------------
//-----------------------------------------------------------------------
// Local Macros, Typedefs, Structures, Unions and Forward Declarations --
//-----------------------------------------------------------------------
// ----------------------------------------
// -- Public Function Member Definitions --
// ----------------------------------------
//----------------
// Constructors --
//----------------
//--------------
// Destructor --
//--------------
AbsDetEnv::~AbsDetEnv( )
{
}
// Selectors
const AbsDetStructure* AbsDetEnv::getDetStructure() const
{
return _detStructure;
}
// Modifiers
void AbsDetEnv::setDetStructure(const AbsDetStructure* detStructure)
{
//_detStructure=const_cast<AbsDetStructure*>(detStructure);
_detStructure=(AbsDetStructure*)detStructure;
}
| 22.925532
| 76
| 0.488631
|
brownd1978
|
39d2feb01906c3ba9ce50d4527fd3a718f70cf2f
| 2,256
|
cpp
|
C++
|
src/OpenGL/entrypoints/GL3.0/gl_uniform_2ui.cpp
|
kbiElude/VKGL
|
fffabf412723a3612ba1c5bfeafe1da38062bd18
|
[
"MIT"
] | 114
|
2018-08-05T16:26:53.000Z
|
2021-12-30T07:28:35.000Z
|
src/OpenGL/entrypoints/GL3.0/gl_uniform_2ui.cpp
|
kbiElude/VKGL
|
fffabf412723a3612ba1c5bfeafe1da38062bd18
|
[
"MIT"
] | 5
|
2018-08-18T21:16:58.000Z
|
2018-11-22T21:50:48.000Z
|
src/OpenGL/entrypoints/GL3.0/gl_uniform_2ui.cpp
|
kbiElude/VKGL
|
fffabf412723a3612ba1c5bfeafe1da38062bd18
|
[
"MIT"
] | 6
|
2018-08-05T22:32:28.000Z
|
2021-10-04T15:39:53.000Z
|
/* VKGL (c) 2018 Dominik Witczak
*
* This code is licensed under MIT license (see LICENSE.txt for details)
*/
#include "OpenGL/entrypoints/GL3.0/gl_uniform_2ui.h"
#include "OpenGL/context.h"
#include "OpenGL/globals.h"
static bool validate(OpenGL::Context* in_context_ptr,
const GLint& in_location,
const GLuint& in_v0,
const GLuint& in_v1)
{
bool result = false;
// ..
result = true;
return result;
}
void VKGL_APIENTRY OpenGL::vkglUniform2ui(GLint location,
GLuint v0,
GLuint v1)
{
const auto& dispatch_table_ptr = OpenGL::g_dispatch_table_ptr;
VKGL_TRACE("glUniform2ui(location=[%d] v0=[%u] v1=[%u])",
location,
v0,
v1);
dispatch_table_ptr->pGLUniform2ui(dispatch_table_ptr->bound_context_ptr,
location,
v0,
v1);
}
static void vkglUniform2ui_execute(OpenGL::Context* in_context_ptr,
const GLint& in_location,
const GLuint& in_v0,
const GLuint& in_v1)
{
const GLuint data[] =
{
in_v0,
in_v1
};
in_context_ptr->set_uniform(in_location,
OpenGL::GetSetArgumentType::Unsigned_Int,
2, /* in_n_components */
1, /* in_n_array_items */
data);
}
void OpenGL::vkglUniform2ui_with_validation(OpenGL::Context* in_context_ptr,
const GLint& in_location,
const GLuint& in_v0,
const GLuint& in_v1)
{
if (validate(in_context_ptr,
in_location,
in_v0,
in_v1) )
{
vkglUniform2ui_execute(in_context_ptr,
in_location,
in_v0,
in_v1);
}
}
| 30.90411
| 76
| 0.449025
|
kbiElude
|
39d72a4f6b8217868560200043da064b13b4df0c
| 430
|
cpp
|
C++
|
day19/main.cpp
|
wuggy-ianw/AoC2017
|
138c66bdd407e76f6ad71c9d68df50e0afa2251a
|
[
"Unlicense"
] | null | null | null |
day19/main.cpp
|
wuggy-ianw/AoC2017
|
138c66bdd407e76f6ad71c9d68df50e0afa2251a
|
[
"Unlicense"
] | null | null | null |
day19/main.cpp
|
wuggy-ianw/AoC2017
|
138c66bdd407e76f6ad71c9d68df50e0afa2251a
|
[
"Unlicense"
] | null | null | null |
#include "day19.h"
#include "../utils/aocutils.h"
#include <iostream>
#include <fstream>
int main(void)
{
std::ifstream ifs("input.txt");
std::vector<std::string> path = AOCUtils::parseByLines<std::string>(ifs, [](const std::string& s) -> std::string {return s;});
std::pair<std::string, int> result = Day19::solve(path);
std::cout << result.first << std::endl;
std::cout << result.second << std::endl;
return 0;
}
| 25.294118
| 128
| 0.646512
|
wuggy-ianw
|
39d7cbb0fba3bbfe79ad50d547f17fe04df866c2
| 286
|
cpp
|
C++
|
22.09.2021-Homework/Task8/Task8.cpp
|
Enigma1123/programming-c-2021-autumn-1course
|
b7c5400298bd9a3e346940e14c4025c954db90aa
|
[
"Apache-2.0"
] | null | null | null |
22.09.2021-Homework/Task8/Task8.cpp
|
Enigma1123/programming-c-2021-autumn-1course
|
b7c5400298bd9a3e346940e14c4025c954db90aa
|
[
"Apache-2.0"
] | null | null | null |
22.09.2021-Homework/Task8/Task8.cpp
|
Enigma1123/programming-c-2021-autumn-1course
|
b7c5400298bd9a3e346940e14c4025c954db90aa
|
[
"Apache-2.0"
] | null | null | null |
#include <iostream>
using namespace std;
int main()
{
int h1 = 0;
int m1 = 0;
int s1 = 0;
int h2 = 0;
int m2 = 0;
int s2 = 0;
int a = 0;
cin >> h1 >> m1 >> s1 >> h2 >> m2 >> s2;
a = abs((h1 * 3600 + m1 * 60 + s1) - (h2 * 3600 + m2 * 60 + s2));
cout << a;
}
| 16.823529
| 67
| 0.447552
|
Enigma1123
|
39d7ccd9b2ba51737016e43eb3e9b9671da3994c
| 29,668
|
cpp
|
C++
|
src/treecore/File.cpp
|
jiandingzhe/treecore
|
0a2a23dce68dbb55174569ec9cff64faeaac4a31
|
[
"MIT"
] | 2
|
2017-10-14T23:13:37.000Z
|
2019-11-18T16:23:49.000Z
|
src/treecore/File.cpp
|
jiandingzhe/treecore
|
0a2a23dce68dbb55174569ec9cff64faeaac4a31
|
[
"MIT"
] | null | null | null |
src/treecore/File.cpp
|
jiandingzhe/treecore
|
0a2a23dce68dbb55174569ec9cff64faeaac4a31
|
[
"MIT"
] | null | null | null |
/*
==============================================================================
This file is part of the juce_core module of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission to use, copy, modify, and/or distribute this software for any purpose with
or without fee is hereby granted, provided that the above copyright notice and this
permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
------------------------------------------------------------------------------
NOTE! This permissive ISC license applies ONLY to files within the juce_core module!
All other JUCE modules are covered by a dual GPL/commercial license, so if you are
using any other modules, be sure to check that you also comply with their license.
For more details, visit www.juce.com
==============================================================================
*/
#include "treecore/File.h"
#include "treecore/DirectoryIterator.h"
#include "treecore/FileInputStream.h"
#include "treecore/FileOutputStream.h"
#include "treecore/MemoryMappedFile.h"
#include "treecore/MT19937.h"
#include "treecore/Process.h"
#include "treecore/ScopedPointer.h"
#include "treecore/StringRef.h"
#include "treecore/TemporaryFile.h"
#include "treecore/Time.h"
#if TREECORE_OS_WINDOWS
#else
# include <pwd.h>
#endif
namespace treecore {
File::File ( const String& fullPathName )
: fullPath( parseAbsolutePath( fullPathName ) )
{}
File File::createFileWithoutCheckingPath( const String& path ) noexcept
{
File f;
f.fullPath = path;
return f;
}
File::File ( const File& other )
: fullPath( other.fullPath )
{}
File& File::operator = ( const String& newPath )
{
fullPath = parseAbsolutePath( newPath );
return *this;
}
File& File::operator = ( const File& other )
{
fullPath = other.fullPath;
return *this;
}
File::File ( File&& other ) noexcept
: fullPath( static_cast<String &&>(other.fullPath) )
{}
File& File::operator = ( File&& other ) noexcept
{
fullPath = static_cast<String &&>(other.fullPath);
return *this;
}
const File File::nonexistent;
//==============================================================================
String File::parseAbsolutePath( const String& p )
{
if ( p.isEmpty() )
return String();
#if TREECORE_OS_WINDOWS
// Windows..
String path( p.replaceCharacter( '/', '\\' ) );
if ( path.startsWithChar( separator ) )
{
if (path[1] != separator)
{
/* When you supply a raw string to the File object constructor, it must be an absolute path.
If you're trying to parse a string that may be either a relative path or an absolute path,
you MUST provide a context against which the partial path can be evaluated - you can do
this by simply using File::getChildFile() instead of the File constructor. E.g. saying
"File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
path if that's what was supplied, or would evaluate a partial path relative to the CWD.
*/
treecore_assert_false;
path = File::getCurrentWorkingDirectory().getFullPathName().substring( 0, 2 ) + path;
}
}
else if ( !path.containsChar( ':' ) )
{
/* When you supply a raw string to the File object constructor, it must be an absolute path.
If you're trying to parse a string that may be either a relative path or an absolute path,
you MUST provide a context against which the partial path can be evaluated - you can do
this by simply using File::getChildFile() instead of the File constructor. E.g. saying
"File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
path if that's what was supplied, or would evaluate a partial path relative to the CWD.
*/
treecore_assert_false;
return File::getCurrentWorkingDirectory().getChildFile( path ).getFullPathName();
}
#elif TREECORE_OS_LINUX || TREECORE_OS_ANDROID || TREECORE_OS_OSX || TREECORE_OS_IOS
// Mac or Linux..
// Yes, I know it's legal for a unix pathname to contain a backslash, but this assertion is here
// to catch anyone who's trying to run code that was written on Windows with hard-coded path names.
// If that's why you've ended up here, use File::getChildFile() to build your paths instead.
treecore_assert( ( !p.containsChar( '\\' ) ) || ( p.indexOfChar( '/' ) >= 0 && p.indexOfChar( '/' ) < p.indexOfChar( '\\' ) ) );
String path( p );
if ( path.startsWithChar( '~' ) )
{
if (path[1] == separator || path[1] == 0)
{
// expand a name of the form "~/abc"
path = File::getSpecialLocation( File::userHomeDirectory ).getFullPathName()
+ path.substring( 1 );
}
else
{
// expand a name of type "~dave/abc"
const String userName( path.substring( 1 ).upToFirstOccurrenceOf( "/", false, false ) );
if ( struct passwd* const pw = getpwnam( userName.toUTF8() ) )
path = addTrailingSeparator( pw->pw_dir ) + path.fromFirstOccurrenceOf( "/", false, false );
}
}
else if ( !path.startsWithChar( separator ) )
{
# if TREECORE_DEBUG || TREECORE_LOG_ASSERTIONS
if ( !( path.startsWith( "./" ) || path.startsWith( "../" ) ) )
{
/* When you supply a raw string to the File object constructor, it must be an absolute path.
If you're trying to parse a string that may be either a relative path or an absolute path,
you MUST provide a context against which the partial path can be evaluated - you can do
this by simply using File::getChildFile() instead of the File constructor. E.g. saying
"File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
path if that's what was supplied, or would evaluate a partial path relative to the CWD.
*/
treecore_assert_false;
# if TREECORE_LOG_ASSERTIONS
Logger::writeToLog( "Illegal absolute path: " + path );
# endif
}
# endif
return File::getCurrentWorkingDirectory().getChildFile( path ).getFullPathName();
}
#else
# error "unsupported OS"
#endif
while (path.endsWithChar( separator ) && path != separatorString) // careful not to turn a single "/" into an empty string.
path = path.dropLastCharacters( 1 );
return path;
}
String File::addTrailingSeparator( const String& path )
{
return path.endsWithChar( separator ) ? path
: path + separator;
}
//==============================================================================
#if TREECORE_OS_LINUX || TREECORE_OS_OSX || TREECORE_OS_IOS
# define NAMES_ARE_CASE_SENSITIVE 1
#elif TREECORE_OS_WINDOWS
#else
# error "TODO"
#endif
bool File::areFileNamesCaseSensitive()
{
#if NAMES_ARE_CASE_SENSITIVE
return true;
#else
return false;
#endif
}
static int compareFilenames( const String& name1, const String& name2 ) noexcept
{
#if NAMES_ARE_CASE_SENSITIVE
return name1.compare( name2 );
#else
return name1.compareIgnoreCase( name2 );
#endif
}
bool File::operator == ( const File& other ) const { return compareFilenames( fullPath, other.fullPath ) == 0; }
bool File::operator != ( const File& other ) const { return compareFilenames( fullPath, other.fullPath ) != 0; }
bool File::operator < ( const File& other ) const { return compareFilenames( fullPath, other.fullPath ) < 0; }
bool File::operator > ( const File& other ) const { return compareFilenames( fullPath, other.fullPath ) > 0; }
//==============================================================================
bool File::setReadOnly( const bool shouldBeReadOnly,
const bool applyRecursively ) const
{
bool worked = true;
if ( applyRecursively && isDirectory() )
{
Array<File> subFiles;
findChildFiles( subFiles, File::findFilesAndDirectories, false );
for (int i = subFiles.size(); --i >= 0; )
worked = subFiles[i].setReadOnly( shouldBeReadOnly, true ) && worked;
}
return setFileReadOnlyInternal( shouldBeReadOnly ) && worked;
}
bool File::deleteRecursively() const
{
bool worked = true;
if ( isDirectory() )
{
Array<File> subFiles;
findChildFiles( subFiles, File::findFilesAndDirectories, false );
for (int i = subFiles.size(); --i >= 0; )
worked = subFiles[i].deleteRecursively() && worked;
}
return deleteFile() && worked;
}
bool File::moveFileTo( const File& newFile ) const
{
if (newFile.fullPath == fullPath)
return true;
if ( !exists() )
return false;
#if !NAMES_ARE_CASE_SENSITIVE
if (*this != newFile)
#endif
if ( !newFile.deleteFile() )
return false;
return moveInternal( newFile );
}
bool File::copyFileTo( const File& newFile ) const
{
return (*this == newFile)
|| ( exists() && newFile.deleteFile() && copyInternal( newFile ) );
}
bool File::copyDirectoryTo( const File& newDirectory ) const
{
if ( isDirectory() && newDirectory.createDirectory() )
{
Array<File> subFiles;
findChildFiles( subFiles, File::findFiles, false );
for (int i = 0; i < subFiles.size(); ++i)
if ( !subFiles[i].copyFileTo( newDirectory.getChildFile( subFiles[i].getFileName() ) ) )
return false;
subFiles.clear();
findChildFiles( subFiles, File::findDirectories, false );
for (int i = 0; i < subFiles.size(); ++i)
if ( !subFiles[i].copyDirectoryTo( newDirectory.getChildFile( subFiles[i].getFileName() ) ) )
return false;
return true;
}
return false;
}
//==============================================================================
String File::getPathUpToLastSlash() const
{
const int lastSlash = fullPath.lastIndexOfChar( separator );
if (lastSlash > 0)
return fullPath.substring( 0, lastSlash );
if (lastSlash == 0)
return separatorString;
return fullPath;
}
File File::getParentDirectory() const
{
File f;
f.fullPath = getPathUpToLastSlash();
return f;
}
//==============================================================================
String File::getFileName() const
{
return fullPath.substring( fullPath.lastIndexOfChar( separator ) + 1 );
}
String File::getFileNameWithoutExtension() const
{
const int lastSlash = fullPath.lastIndexOfChar( separator ) + 1;
const int lastDot = fullPath.lastIndexOfChar( '.' );
if (lastDot > lastSlash)
return fullPath.substring( lastSlash, lastDot );
return fullPath.substring( lastSlash );
}
bool File::isAChildOf( const File& potentialParent ) const
{
if ( potentialParent.fullPath.isEmpty() )
return false;
const String ourPath( getPathUpToLastSlash() );
if (compareFilenames( potentialParent.fullPath, ourPath ) == 0)
return true;
if ( potentialParent.fullPath.length() >= ourPath.length() )
return false;
return getParentDirectory().isAChildOf( potentialParent );
}
int File::hashCode() const { return fullPath.hashCode(); }
int64 File::hashCode64() const { return fullPath.hashCode64(); }
//==============================================================================
bool File::isAbsolutePath( StringRef path )
{
return path.text[0] == separator
#if TREECORE_OS_WINDOWS
|| (path.isNotEmpty() && path.text[1] == ':');
#else
|| path.text[0] == '~';
#endif
}
File File::getChildFile( StringRef relativePath ) const
{
if ( isAbsolutePath( relativePath ) )
return File( String( relativePath.text ) );
if (relativePath[0] != '.')
return File( addTrailingSeparator( fullPath ) + relativePath );
String path( fullPath );
// It's relative, so remove any ../ or ./ bits at the start..
#if TREECORE_OS_WINDOWS
if (relativePath.text.indexOf( (treecore_wchar) '/' ) >= 0)
return getChildFile( String( relativePath.text ).replaceCharacter( '/', '\\' ) );
#endif
while (relativePath[0] == '.')
{
const treecore_wchar secondChar = relativePath[1];
if (secondChar == '.')
{
const treecore_wchar thirdChar = relativePath[2];
if (thirdChar == 0 || thirdChar == separator)
{
const int lastSlash = path.lastIndexOfChar( separator );
if (lastSlash >= 0)
path = path.substring( 0, lastSlash );
relativePath = relativePath.text + (thirdChar == 0 ? 2 : 3);
}
else
{
break;
}
}
else if (secondChar == separator)
{
relativePath = relativePath.text + 2;
}
else
{
break;
}
}
return File( addTrailingSeparator( path ) + relativePath );
}
File File::getSiblingFile( StringRef fileName ) const
{
return getParentDirectory().getChildFile( fileName );
}
//==============================================================================
String File::descriptionOfSizeInBytes( const int64 bytes )
{
const char* suffix;
double divisor = 0;
if (bytes == 1) { suffix = " byte"; }
else if (bytes < 1024) { suffix = " bytes"; }
else if (bytes < 1024 * 1024) { suffix = " KB"; divisor = 1024.0; }
else if (bytes < 1024 * 1024 * 1024) { suffix = " MB"; divisor = 1024.0 * 1024.0; }
else { suffix = " GB"; divisor = 1024.0 * 1024.0 * 1024.0; }
return ( divisor > 0 ? String( bytes / divisor, 1 ) : String( bytes ) ) + suffix;
}
//==============================================================================
Result File::create() const
{
if ( exists() )
return Result::ok();
const File parentDir( getParentDirectory() );
if (parentDir == *this)
return Result::fail( "Cannot create parent directory" );
Result r( parentDir.createDirectory() );
if ( r.wasOk() )
{
FileOutputStream fo( *this, 8 );
r = fo.getStatus();
}
return r;
}
Result File::createDirectory() const
{
if ( isDirectory() )
return Result::ok();
const File parentDir( getParentDirectory() );
if (parentDir == *this)
return Result::fail( "Cannot create parent directory" );
Result r( parentDir.createDirectory() );
if ( r.wasOk() )
r = createDirectoryInternal( fullPath.trimCharactersAtEnd( separatorString ) );
return r;
}
//==============================================================================
Time File::getLastModificationTime() const { int64 m, a, c; getFileTimesInternal( m, a, c ); return Time( m ); }
Time File::getLastAccessTime() const { int64 m, a, c; getFileTimesInternal( m, a, c ); return Time( a ); }
Time File::getCreationTime() const { int64 m, a, c; getFileTimesInternal( m, a, c ); return Time( c ); }
bool File::setLastModificationTime( Time t ) const { return setFileTimesInternal( t.toMilliseconds(), 0, 0 ); }
bool File::setLastAccessTime( Time t ) const { return setFileTimesInternal( 0, t.toMilliseconds(), 0 ); }
bool File::setCreationTime( Time t ) const { return setFileTimesInternal( 0, 0, t.toMilliseconds() ); }
//==============================================================================
bool File::loadFileAsData( MemoryBlock& destBlock ) const
{
if ( !existsAsFile() )
return false;
FileInputStream in( *this );
return in.openedOk() && getSize() == (int64) in.readIntoMemoryBlock( destBlock );
}
String File::loadFileAsString() const
{
if ( !existsAsFile() )
return String();
FileInputStream in( *this );
return in.openedOk() ? in.readEntireStreamAsString()
: String();
}
void File::readLines( StringArray& destLines ) const
{
destLines.addLines( loadFileAsString() );
}
//==============================================================================
int File::findChildFiles( Array<File>& results,
const int whatToLookFor,
const bool searchRecursively,
const String& wildCardPattern ) const
{
int total = 0;
for (DirectoryIterator di( *this, searchRecursively, wildCardPattern, whatToLookFor ); di.next(); )
{
results.add( di.getFile() );
++total;
}
return total;
}
int File::getNumberOfChildFiles( const int whatToLookFor, const String& wildCardPattern ) const
{
int total = 0;
for (DirectoryIterator di( *this, false, wildCardPattern, whatToLookFor ); di.next(); )
++total;
return total;
}
bool File::containsSubDirectories() const
{
if ( !isDirectory() )
return false;
DirectoryIterator di( *this, false, "*", findDirectories );
return di.next();
}
//==============================================================================
File File::getNonexistentChildFile( const String& suggestedPrefix,
const String& suffix,
bool putNumbersInBrackets ) const
{
File f( getChildFile( suggestedPrefix + suffix ) );
if ( f.exists() )
{
int number = 1;
String prefix( suggestedPrefix );
// remove any bracketed numbers that may already be on the end..
if ( prefix.trim().endsWithChar( ')' ) )
{
putNumbersInBrackets = true;
const int openBracks = prefix.lastIndexOfChar( '(' );
const int closeBracks = prefix.lastIndexOfChar( ')' );
if ( openBracks > 0
&& closeBracks > openBracks
&& prefix.substring( openBracks + 1, closeBracks ).containsOnly( "0123456789" ) )
{
number = prefix.substring( openBracks + 1, closeBracks ).getIntValue();
prefix = prefix.substring( 0, openBracks );
}
}
// also use brackets if it ends in a digit.
putNumbersInBrackets = putNumbersInBrackets
|| CharacterFunctions::isDigit( prefix.getLastCharacter() );
do
{
String newName( prefix );
if (putNumbersInBrackets)
newName << '(' << ++number << ')';
else
newName << ++number;
f = getChildFile( newName + suffix );
} while ( f.exists() );
}
return f;
}
File File::getNonexistentSibling( const bool putNumbersInBrackets ) const
{
if ( !exists() )
return *this;
return getParentDirectory().getNonexistentChildFile( getFileNameWithoutExtension(),
getFileExtension(),
putNumbersInBrackets );
}
//==============================================================================
String File::getFileExtension() const
{
const int indexOfDot = fullPath.lastIndexOfChar( '.' );
if ( indexOfDot > fullPath.lastIndexOfChar( separator ) )
return fullPath.substring( indexOfDot );
return String();
}
bool File::hasFileExtension( StringRef possibleSuffix ) const
{
if ( possibleSuffix.isEmpty() )
return fullPath.lastIndexOfChar( '.' ) <= fullPath.lastIndexOfChar( separator );
const int semicolon = possibleSuffix.text.indexOf( (treecore_wchar) ';' );
if (semicolon >= 0)
return hasFileExtension( String( possibleSuffix.text ).substring( 0, semicolon ).trimEnd() )
|| hasFileExtension( ( possibleSuffix.text + (semicolon + 1) ).findEndOfWhitespace() );
if ( fullPath.endsWithIgnoreCase( possibleSuffix ) )
{
if (possibleSuffix.text[0] == '.')
return true;
const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
if (dotPos >= 0)
return fullPath [dotPos] == '.';
}
return false;
}
File File::withFileExtension( StringRef newExtension ) const
{
if ( fullPath.isEmpty() )
return File();
String filePart( getFileName() );
const int i = filePart.lastIndexOfChar( '.' );
if (i >= 0)
filePart = filePart.substring( 0, i );
if (newExtension.isNotEmpty() && newExtension.text[0] != '.')
filePart << '.';
return getSiblingFile( filePart + newExtension );
}
//==============================================================================
bool File::startAsProcess( const String& parameters ) const
{
return exists() && Process::openDocument( fullPath, parameters );
}
//==============================================================================
FileInputStream* File::createInputStream() const
{
ScopedPointer<FileInputStream> fin( new FileInputStream( *this ) );
if ( fin->openedOk() )
return fin.release();
return nullptr;
}
FileOutputStream* File::createOutputStream( const size_t bufferSize ) const
{
ScopedPointer<FileOutputStream> out( new FileOutputStream( *this, bufferSize ) );
return out->failedToOpen() ? nullptr
: out.release();
}
//==============================================================================
bool File::appendData( const void* const dataToAppend,
const size_t numberOfBytes ) const
{
treecore_assert( ( (ssize_t) numberOfBytes ) >= 0 );
if (numberOfBytes == 0)
return true;
FileOutputStream out( *this, 8192 );
return out.openedOk() && out.write( dataToAppend, numberOfBytes );
}
bool File::replaceWithData( const void* const dataToWrite,
const size_t numberOfBytes ) const
{
if (numberOfBytes == 0)
return deleteFile();
TemporaryFile tempFile( *this, TemporaryFile::useHiddenFile );
tempFile.getFile().appendData( dataToWrite, numberOfBytes );
return tempFile.overwriteTargetFileWithTemporary();
}
bool File::appendText( const String& text,
const bool asUnicode,
const bool writeUnicodeHeaderBytes ) const
{
FileOutputStream out( *this );
if ( out.failedToOpen() )
return false;
out.writeText( text, asUnicode, writeUnicodeHeaderBytes );
return true;
}
bool File::replaceWithText( const String& textToWrite,
const bool asUnicode,
const bool writeUnicodeHeaderBytes ) const
{
TemporaryFile tempFile( *this, TemporaryFile::useHiddenFile );
tempFile.getFile().appendText( textToWrite, asUnicode, writeUnicodeHeaderBytes );
return tempFile.overwriteTargetFileWithTemporary();
}
bool File::hasIdenticalContentTo( const File& other ) const
{
if (other == *this)
return true;
if ( getSize() == other.getSize() && existsAsFile() && other.existsAsFile() )
{
FileInputStream in1( *this ), in2( other );
if ( in1.openedOk() && in2.openedOk() )
{
const int bufferSize = 4096;
HeapBlock<char> buffer1( bufferSize ), buffer2( bufferSize );
for (;; )
{
const int num1 = in1.read( buffer1, bufferSize );
const int num2 = in2.read( buffer2, bufferSize );
if (num1 != num2)
break;
if (num1 <= 0)
return true;
if (memcmp( buffer1, buffer2, (size_t) num1 ) != 0)
break;
}
}
}
return false;
}
//==============================================================================
String File::createLegalPathName( const String& original )
{
String s( original );
String start;
if (s.isNotEmpty() && s[1] == ':')
{
start = s.substring( 0, 2 );
s = s.substring( 2 );
}
return start + s.removeCharacters( "\"#@,;:<>*^|?" )
.substring( 0, 1024 );
}
String File::createLegalFileName( const String& original )
{
String s( original.removeCharacters( "\"#@,;:<>*^|?\\/" ) );
const int maxLength = 128; // only the length of the filename, not the whole path
const int len = s.length();
if (len > maxLength)
{
const int lastDot = s.lastIndexOfChar( '.' );
if ( lastDot > jmax( 0, len - 12 ) )
{
s = s.substring( 0, maxLength - (len - lastDot) )
+ s.substring( lastDot );
}
else
{
s = s.substring( 0, maxLength );
}
}
return s;
}
//==============================================================================
static int countNumberOfSeparators( String::CharPointerType s )
{
int num = 0;
for (;; )
{
const treecore_wchar c = s.getAndAdvance();
if (c == 0)
break;
if (c == File::separator)
++num;
}
return num;
}
String File::getRelativePathFrom( const File& dir ) const
{
String thisPath( fullPath );
while ( thisPath.endsWithChar( separator ) )
thisPath = thisPath.dropLastCharacters( 1 );
String dirPath( addTrailingSeparator( dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
: dir.fullPath ) );
int commonBitLength = 0;
String::CharPointerType thisPathAfterCommon( thisPath.getCharPointer() );
String::CharPointerType dirPathAfterCommon( dirPath.getCharPointer() );
{
String::CharPointerType thisPathIter( thisPath.getCharPointer() );
String::CharPointerType dirPathIter( dirPath.getCharPointer() );
for (int i = 0;; )
{
const treecore_wchar c1 = thisPathIter.getAndAdvance();
const treecore_wchar c2 = dirPathIter.getAndAdvance();
#if NAMES_ARE_CASE_SENSITIVE
if (c1 != c2
#else
if ( ( c1 != c2 && CharacterFunctions::toLowerCase( c1 ) != CharacterFunctions::toLowerCase( c2 ) )
#endif
|| c1 == 0 )
break;
++i;
if (c1 == separator)
{
thisPathAfterCommon = thisPathIter;
dirPathAfterCommon = dirPathIter;
commonBitLength = i;
}
}
}
// if the only common bit is the root, then just return the full path..
if ( commonBitLength == 0 || (commonBitLength == 1 && thisPath[1] == separator) )
return fullPath;
const int numUpDirectoriesNeeded = countNumberOfSeparators( dirPathAfterCommon );
if (numUpDirectoriesNeeded == 0)
return thisPathAfterCommon;
#if TREECORE_OS_WINDOWS
String s( String::repeatedString( "..\\", numUpDirectoriesNeeded ) );
#else
String s( String::repeatedString( "../", numUpDirectoriesNeeded ) );
#endif
s.appendCharPointer( thisPathAfterCommon );
return s;
}
//==============================================================================
File File::createTempFile( StringRef fileNameEnding )
{
const File tempFile( getSpecialLocation( tempDirectory )
.getChildFile( "temp_" + String::toHexString( int( MT19937::getInstance()->next_uint64() ) ) )
.withFileExtension( fileNameEnding ) );
if ( tempFile.exists() )
return createTempFile( fileNameEnding );
return tempFile;
}
//==============================================================================
MemoryMappedFile::MemoryMappedFile ( const File& file, MemoryMappedFile::AccessMode mode )
: address( nullptr ), range( 0, file.getSize() ), fileHandle( 0 )
{
openInternal( file, mode );
}
MemoryMappedFile::MemoryMappedFile ( const File& file, const Range<int64>& fileRange, AccessMode mode )
: address( nullptr ), range( fileRange.getIntersectionWith( Range<int64>( 0, file.getSize() ) ) ), fileHandle( 0 )
{
openInternal( file, mode );
}
}
| 32.424044
| 133
| 0.555413
|
jiandingzhe
|
39db3e42db98fa485f60ffb204a13dbd0786931b
| 258
|
cpp
|
C++
|
c++/Project/project6-3/main.cpp
|
roostaa/cpp_archive
|
41e58a8c1e9cb7b4400fa4f5e5aa05df923fd872
|
[
"MIT"
] | null | null | null |
c++/Project/project6-3/main.cpp
|
roostaa/cpp_archive
|
41e58a8c1e9cb7b4400fa4f5e5aa05df923fd872
|
[
"MIT"
] | null | null | null |
c++/Project/project6-3/main.cpp
|
roostaa/cpp_archive
|
41e58a8c1e9cb7b4400fa4f5e5aa05df923fd872
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int main()
{
int x;
for (x = 1; x <=20; x++)
{
if (x == 3 || x == 11 || x == 16)
{
continue;
}
cout << x << endl;
}
return 0;
}
| 12.285714
| 42
| 0.333333
|
roostaa
|
39dff968cb27b359b4c831bedb91c94bbe28945b
| 4,241
|
hpp
|
C++
|
Crowdflower Search Results Relevance/rgf1.2/src/tet/AzTET_Eval_Dflt.hpp
|
Tuanlase02874/Machine-Learning-Kaggle
|
c31651acd8f2407d8b60774e843a2527ce19b013
|
[
"MIT"
] | 1
|
2018-07-11T16:20:43.000Z
|
2018-07-11T16:20:43.000Z
|
Crowdflower Search Results Relevance/rgf1.2/src/tet/AzTET_Eval_Dflt.hpp
|
Tuanlase02874/Machine-Learning-Kaggle
|
c31651acd8f2407d8b60774e843a2527ce19b013
|
[
"MIT"
] | null | null | null |
Crowdflower Search Results Relevance/rgf1.2/src/tet/AzTET_Eval_Dflt.hpp
|
Tuanlase02874/Machine-Learning-Kaggle
|
c31651acd8f2407d8b60774e843a2527ce19b013
|
[
"MIT"
] | null | null | null |
/* * * * *
* AzTET_Eval_Dflt.hpp
* Copyright (C) 2011, 2012 Rie Johnson
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* * * * */
#ifndef _AZ_TET_EVAL_DFLT_HPP_
#define _AZ_TET_EVAL_DFLT_HPP_
#include "AzUtil.hpp"
#include "AzTaskTools.hpp"
#include "AzPerfResult.hpp"
#include "AzDataForTrTree.hpp"
#include "AzLoss.hpp"
#include "AzTET_Eval.hpp"
//! Evaluationt module for Tree Ensemble Trainer.
/*-------------------------------------------------------*/
class AzTET_Eval_Dflt : /* implements */ public virtual AzTET_Eval {
protected:
/*--- targets ---*/
const AzDvect *v_y;
/*--- to output evaluation results ---*/
AzBytArr s_perf_fn;
AzPerfType perf_type;
AzLossType loss_type;
AzBytArr s_config;
AzOfs ofs;
AzOut perf_out;
bool doAppend;
public:
AzTET_Eval_Dflt() : v_y(NULL),
loss_type(AzLoss_None), doAppend(false) {}
~AzTET_Eval_Dflt() {
end();
}
inline virtual bool isActive() const {
if (v_y != NULL) return true;
return false;
}
virtual void reset() {
v_y= NULL;
s_perf_fn.reset();
s_config.reset();
if (ofs.is_open()) {
ofs.close();
}
}
void reset(const AzDvect *inp_v_y,
const char *perf_fn,
bool inp_doAppend)
{
v_y = inp_v_y;
s_perf_fn.reset(perf_fn);
doAppend = inp_doAppend;
}
virtual void resetConfig(const char *config) {
s_config.reset(config);
_clean(&s_config);
}
virtual void begin(const char *config,
AzLossType inp_loss_type) {
if (!isActive()) return;
_begin(config, inp_loss_type);
_clean(&s_config);
}
virtual void end() {
if (ofs.is_open()) {
ofs.close();
}
}
virtual void evaluate(const AzDvect *v_p,
const AzTE_ModelInfo *info,
const char *user_str=NULL) {
if (!isActive()) return;
AzPerfResult result=AzTaskTools::eval(v_p, v_y, loss_type);
/*--- signature and configuration ---*/
AzBytArr s_sign_config(info->s_sign);
s_sign_config.concat(":");
concat_config(info, &s_sign_config);
/*--- print ---*/
AzPrint o(perf_out);
o.printBegin("", ",", ",");
o.print("#tree", info->tree_num);
o.print("#leaf", info->leaf_num);
o.print("acc", result.acc, 4);
o.print("rmse", result.rmse, 4);
o.print("sqerr", result.rmse*result.rmse, 6);
o.print(loss_str[loss_type]);
o.print("loss", result.loss, 6);
o.print("#test", v_p->rowNum());
o.print("cfg"); /* for compatibility */
o.print(s_sign_config);
if (user_str != NULL) {
o.print(user_str);
}
o.printEnd();
}
protected:
virtual void _begin(const char *config, AzLossType inp_loss_type) {
s_config.reset(config);
loss_type = inp_loss_type;
if (ofs.is_open()) {
ofs.close();
}
const char *perf_fn = s_perf_fn.c_str();
if (AzTools::isSpecified(perf_fn)) {
ios_base::openmode mode = ios_base::out;
if (doAppend) {
mode = ios_base::app | ios_base::out;
}
ofs.open(perf_fn, mode);
ofs.set_to(perf_out);
}
else {
perf_out.setStdout();
}
}
virtual void _clean(AzBytArr *s) const {
/*-- replace comma with : for convenience later --*/
s->replace(',', ';');
}
virtual void concat_config(const AzTE_ModelInfo *info, AzBytArr *s) const {
if (s_config.length() > 0) {
s->concat(&s_config);
}
else {
AzBytArr s_cfg(&info->s_config);
_clean(&s_cfg);
s->concat(&s_cfg);
}
}
};
#endif
| 26.50625
| 77
| 0.603867
|
Tuanlase02874
|
39e055bceb1e414cb1b1f47a2fef97e2844cf7f0
| 8,559
|
cpp
|
C++
|
export/release/windows/obj/src/openfl/ui/Keyboard.cpp
|
bobisdabbing/Vs-The-United-Lands-stable
|
0807e58b6d8ad1440bdd350bf006b37a1b7ca9b5
|
[
"MIT"
] | null | null | null |
export/release/windows/obj/src/openfl/ui/Keyboard.cpp
|
bobisdabbing/Vs-The-United-Lands-stable
|
0807e58b6d8ad1440bdd350bf006b37a1b7ca9b5
|
[
"MIT"
] | null | null | null |
export/release/windows/obj/src/openfl/ui/Keyboard.cpp
|
bobisdabbing/Vs-The-United-Lands-stable
|
0807e58b6d8ad1440bdd350bf006b37a1b7ca9b5
|
[
"MIT"
] | null | null | null |
// Generated by Haxe 4.1.5
#include <hxcpp.h>
#ifndef INCLUDED_openfl_ui_Keyboard
#include <openfl/ui/Keyboard.h>
#endif
HX_LOCAL_STACK_FRAME(_hx_pos_410ccb691917537a_815___getCharCode,"openfl.ui.Keyboard","__getCharCode",0x5c5ae14e,"openfl.ui.Keyboard.__getCharCode","openfl/ui/Keyboard.hx",815,0x5fb867bb)
namespace openfl{
namespace ui{
void Keyboard_obj::__construct() { }
Dynamic Keyboard_obj::__CreateEmpty() { return new Keyboard_obj; }
void *Keyboard_obj::_hx_vtable = 0;
Dynamic Keyboard_obj::__Create(::hx::DynamicArray inArgs)
{
::hx::ObjectPtr< Keyboard_obj > _hx_result = new Keyboard_obj();
_hx_result->__construct();
return _hx_result;
}
bool Keyboard_obj::_hx_isInstanceOf(int inClassId) {
return inClassId==(int)0x00000001 || inClassId==(int)0x0c5957a7;
}
int Keyboard_obj::_hx___getCharCode(int key,::hx::Null< bool > __o_shift){
bool shift = __o_shift.Default(false);
HX_STACKFRAME(&_hx_pos_410ccb691917537a_815___getCharCode)
HXLINE( 816) if (!(shift)) {
HXLINE( 818) switch((int)(key)){
case (int)8: {
HXLINE( 821) return 8;
}
break;
case (int)9: {
HXLINE( 823) return 9;
}
break;
case (int)13: {
HXLINE( 825) return 13;
}
break;
case (int)27: {
HXLINE( 827) return 27;
}
break;
case (int)32: {
HXLINE( 829) return 32;
}
break;
case (int)186: {
HXLINE( 831) return 59;
}
break;
case (int)187: {
HXLINE( 833) return 61;
}
break;
case (int)188: {
HXLINE( 835) return 44;
}
break;
case (int)189: {
HXLINE( 837) return 45;
}
break;
case (int)190: {
HXLINE( 839) return 46;
}
break;
case (int)191: {
HXLINE( 841) return 47;
}
break;
case (int)192: {
HXLINE( 843) return 96;
}
break;
case (int)219: {
HXLINE( 845) return 91;
}
break;
case (int)220: {
HXLINE( 847) return 92;
}
break;
case (int)221: {
HXLINE( 849) return 93;
}
break;
case (int)222: {
HXLINE( 851) return 39;
}
break;
}
HXLINE( 854) bool _hx_tmp;
HXDLIN( 854) if ((key >= 48)) {
HXLINE( 854) _hx_tmp = (key <= 57);
}
else {
HXLINE( 854) _hx_tmp = false;
}
HXDLIN( 854) if (_hx_tmp) {
HXLINE( 856) return ((key - 48) + 48);
}
HXLINE( 859) bool _hx_tmp1;
HXDLIN( 859) if ((key >= 65)) {
HXLINE( 859) _hx_tmp1 = (key <= 90);
}
else {
HXLINE( 859) _hx_tmp1 = false;
}
HXDLIN( 859) if (_hx_tmp1) {
HXLINE( 861) return ((key - 65) + 97);
}
}
else {
HXLINE( 866) switch((int)(key)){
case (int)48: {
HXLINE( 869) return 41;
}
break;
case (int)49: {
HXLINE( 871) return 33;
}
break;
case (int)50: {
HXLINE( 873) return 64;
}
break;
case (int)51: {
HXLINE( 875) return 35;
}
break;
case (int)52: {
HXLINE( 877) return 36;
}
break;
case (int)53: {
HXLINE( 879) return 37;
}
break;
case (int)54: {
HXLINE( 881) return 94;
}
break;
case (int)55: {
HXLINE( 883) return 38;
}
break;
case (int)56: {
HXLINE( 885) return 42;
}
break;
case (int)57: {
HXLINE( 887) return 40;
}
break;
case (int)186: {
HXLINE( 889) return 58;
}
break;
case (int)187: {
HXLINE( 891) return 43;
}
break;
case (int)188: {
HXLINE( 893) return 60;
}
break;
case (int)189: {
HXLINE( 895) return 95;
}
break;
case (int)190: {
HXLINE( 897) return 62;
}
break;
case (int)191: {
HXLINE( 899) return 63;
}
break;
case (int)192: {
HXLINE( 901) return 126;
}
break;
case (int)219: {
HXLINE( 903) return 123;
}
break;
case (int)220: {
HXLINE( 905) return 124;
}
break;
case (int)221: {
HXLINE( 907) return 125;
}
break;
case (int)222: {
HXLINE( 909) return 34;
}
break;
}
HXLINE( 912) bool _hx_tmp;
HXDLIN( 912) if ((key >= 65)) {
HXLINE( 912) _hx_tmp = (key <= 90);
}
else {
HXLINE( 912) _hx_tmp = false;
}
HXDLIN( 912) if (_hx_tmp) {
HXLINE( 914) return ((key - 65) + 65);
}
}
HXLINE( 918) bool _hx_tmp;
HXDLIN( 918) if ((key >= 96)) {
HXLINE( 918) _hx_tmp = (key <= 105);
}
else {
HXLINE( 918) _hx_tmp = false;
}
HXDLIN( 918) if (_hx_tmp) {
HXLINE( 920) return ((key - 96) + 48);
}
HXLINE( 923) switch((int)(key)){
case (int)8: {
HXLINE( 940) return 8;
}
break;
case (int)13: {
HXLINE( 938) return 13;
}
break;
case (int)46: {
HXLINE( 936) return 127;
}
break;
case (int)106: {
HXLINE( 926) return 42;
}
break;
case (int)107: {
HXLINE( 928) return 43;
}
break;
case (int)108: {
HXLINE( 930) return 44;
}
break;
case (int)110: {
HXLINE( 932) return 45;
}
break;
case (int)111: {
HXLINE( 934) return 46;
}
break;
}
HXLINE( 943) return 0;
}
STATIC_HX_DEFINE_DYNAMIC_FUNC2(Keyboard_obj,_hx___getCharCode,return )
Keyboard_obj::Keyboard_obj()
{
}
bool Keyboard_obj::__GetStatic(const ::String &inName, Dynamic &outValue, ::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 13:
if (HX_FIELD_EQ(inName,"__getCharCode") ) { outValue = _hx___getCharCode_dyn(); return true; }
}
return false;
}
#ifdef HXCPP_SCRIPTABLE
static ::hx::StorageInfo *Keyboard_obj_sMemberStorageInfo = 0;
static ::hx::StaticInfo *Keyboard_obj_sStaticStorageInfo = 0;
#endif
::hx::Class Keyboard_obj::__mClass;
static ::String Keyboard_obj_sStaticFields[] = {
HX_("__getCharCode",b9,62,90,0a),
::String(null())
};
void Keyboard_obj::__register()
{
Keyboard_obj _hx_dummy;
Keyboard_obj::_hx_vtable = *(void **)&_hx_dummy;
::hx::Static(__mClass) = new ::hx::Class_obj();
__mClass->mName = HX_("openfl.ui.Keyboard",43,b4,37,9a);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &Keyboard_obj::__GetStatic;
__mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField;
__mClass->mStatics = ::hx::Class_obj::dupFunctions(Keyboard_obj_sStaticFields);
__mClass->mMembers = ::hx::Class_obj::dupFunctions(0 /* sMemberFields */);
__mClass->mCanCast = ::hx::TCanCast< Keyboard_obj >;
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = Keyboard_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = Keyboard_obj_sStaticStorageInfo;
#endif
::hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace openfl
} // end namespace ui
| 26.830721
| 186
| 0.468746
|
bobisdabbing
|
39e063360296154fe53e3414e2779cf32e99311c
| 939
|
cpp
|
C++
|
LeetCode/Problems/Algorithms/#203_RemoveLinkedListElements_sol2_O(N)_time_O(1)_extra_space.cpp
|
Tudor67/Competitive-Programming
|
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
|
[
"MIT"
] | 1
|
2022-01-26T14:50:07.000Z
|
2022-01-26T14:50:07.000Z
|
LeetCode/Problems/Algorithms/#203_RemoveLinkedListElements_sol2_O(N)_time_O(1)_extra_space.cpp
|
Tudor67/Competitive-Programming
|
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
|
[
"MIT"
] | null | null | null |
LeetCode/Problems/Algorithms/#203_RemoveLinkedListElements_sol2_O(N)_time_O(1)_extra_space.cpp
|
Tudor67/Competitive-Programming
|
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
|
[
"MIT"
] | null | null | null |
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* prevHead = new ListNode(INT_MIN, head);
ListNode* prevNode = prevHead;
ListNode* node = head;
while(node != NULL){
if(node->val == val){
prevNode->next = node->next;
node->next = NULL;
delete node;
}else{
prevNode = node;
}
node = prevNode->next;
}
head = prevHead->next;
prevHead->next = NULL;
delete prevHead;
return head;
}
};
| 26.828571
| 63
| 0.467519
|
Tudor67
|
39e2c8de74e7882f16e38daa31a1cf9845f5ea05
| 5,158
|
cpp
|
C++
|
test/util/testMath.cpp
|
KUDB/MSDB
|
19e89d1d9c09c57b242737f0634ac30b4c8ecfd7
|
[
"MIT"
] | 2
|
2021-08-31T12:43:16.000Z
|
2021-12-13T13:49:19.000Z
|
test/util/testMath.cpp
|
KUDB/MSDB
|
19e89d1d9c09c57b242737f0634ac30b4c8ecfd7
|
[
"MIT"
] | 3
|
2021-09-09T17:23:31.000Z
|
2021-09-09T19:14:50.000Z
|
test/util/testMath.cpp
|
KUDB/MSDB
|
19e89d1d9c09c57b242737f0634ac30b4c8ecfd7
|
[
"MIT"
] | null | null | null |
#include <pch_test.h>
#include <util/math.h>
using namespace msdb::core;
TEST(util_math, msb_char)
{
// 0111 1000
EXPECT_EQ(msb<char>(120, 1), 7);
EXPECT_EQ(msb<char>(120, 2), 6);
EXPECT_EQ(msb<char>(120, 3), 5);
EXPECT_EQ(msb<char>(120, 4), 4);
EXPECT_EQ(msb<char>(120, 5), 0);
// 0101 0101
EXPECT_EQ(msb<char>(85, 1), 7);
EXPECT_EQ(msb<char>(85, 2), 5);
EXPECT_EQ(msb<char>(85, 3), 3);
EXPECT_EQ(msb<char>(85, 4), 1);
EXPECT_EQ(msb<char>(85, 5), 0);
// 0011 0100
EXPECT_EQ(msb<char>(52, 1), 6);
EXPECT_EQ(msb<char>(52, 2), 5);
EXPECT_EQ(msb<char>(52, 3), 3);
EXPECT_EQ(msb<char>(52, 4), 0);
// 1000 1000
EXPECT_EQ(msb<char>(-120, 1), 8);
EXPECT_EQ(msb<char>(-120, 2), 4);
EXPECT_EQ(msb<char>(-120, 3), 0);
EXPECT_EQ(msb<char>(-120, 4), 0);
EXPECT_EQ(msb<char>(-120, 5), 0);
// 1010 1011
EXPECT_EQ(msb<char>(-85, 1), 8);
EXPECT_EQ(msb<char>(-85, 2), 6);
EXPECT_EQ(msb<char>(-85, 3), 4);
EXPECT_EQ(msb<char>(-85, 4), 2);
EXPECT_EQ(msb<char>(-85, 5), 1);
EXPECT_EQ(msb<char>(-85, 6), 0);
// 1100 1100
EXPECT_EQ(msb<char>(-52, 1), 8);
EXPECT_EQ(msb<char>(-52, 2), 7);
EXPECT_EQ(msb<char>(-52, 3), 4);
EXPECT_EQ(msb<char>(-52, 4), 3);
EXPECT_EQ(msb<char>(-52, 5), 0);
// 1000 0001
EXPECT_EQ(msb<char>(-127, 1), 8);
EXPECT_EQ(msb<char>(-127, 2), 1);
EXPECT_EQ(msb<char>(-127, 3), 0);
// Special case: Min Limit
// 1000 0000
EXPECT_EQ(msb<char>(-128, 1), 7);
EXPECT_EQ(msb<char>(-128, 2), 0);
EXPECT_EQ(msb<char>(-128, 2), 0);
}
TEST(util_math, getMinBoundary)
{
// 28 (0001 1100)
EXPECT_EQ(getMinBoundary<char>(28, 1, 7), 64);
EXPECT_EQ(getMinBoundary<char>(28, 1, 6), 32);
EXPECT_EQ(getMinBoundary<char>(28, 1, 5), 28);
EXPECT_EQ(getMinBoundary<char>(28, 2, 4), 28);
EXPECT_EQ(getMinBoundary<char>(28, 3, 3), 28);
// -28
EXPECT_EQ(getMinBoundary<char>(-28, 1, -5), -28);
EXPECT_EQ(getMinBoundary<char>(-28, 1, -4), -15);
EXPECT_EQ(getMinBoundary<char>(-28, 1, -3), -7);
EXPECT_EQ(getMinBoundary<char>(-28, 1, -2), -3);
EXPECT_EQ(getMinBoundary<char>(-28, 1, -1), -1);
EXPECT_EQ(getMinBoundary<char>(-28, 2, -4), -28);
EXPECT_EQ(getMinBoundary<char>(-28, 2, -3), -23);
EXPECT_EQ(getMinBoundary<char>(-28, 2, -2), -19);
EXPECT_EQ(getMinBoundary<char>(-28, 2, -1), -17);
EXPECT_EQ(getMinBoundary<char>(-28, 3, -3), -28);
EXPECT_EQ(getMinBoundary<char>(-28, 3, -2), -27);
EXPECT_EQ(getMinBoundary<char>(-28, 3, -1), -25);
// 81 (0101 0001)
EXPECT_EQ(getMinBoundary<char>(81, 1, 7), 81);
EXPECT_EQ(getMinBoundary<char>(81, 2, 6), 96);
EXPECT_EQ(getMinBoundary<char>(81, 2, 5), 81);
EXPECT_EQ(getMinBoundary<char>(81, 3, 4), 88);
EXPECT_EQ(getMinBoundary<char>(81, 3, 3), 84);
EXPECT_EQ(getMinBoundary<char>(81, 3, 2), 82);
EXPECT_EQ(getMinBoundary<char>(81, 3, 1), 81);
// -126 (0111 1110)
EXPECT_EQ(getMinBoundary<char>(-126, 1, -7), -126);
// -91 (0101 1011)
EXPECT_EQ(getMinBoundary<char>(-91, 2, -5), -91);
}
TEST(util_math, getMaxBoundary)
{
// 81 (0101 0001)
EXPECT_EQ(getMaxBoundary<char>(81, 1, 7), 81);
EXPECT_EQ(getMaxBoundary<char>(81, 1, 6), 63);
EXPECT_EQ(getMaxBoundary<char>(81, 1, 5), 31);
EXPECT_EQ(getMaxBoundary<char>(81, 1, 4), 15);
EXPECT_EQ(getMaxBoundary<char>(81, 1, 3), 7);
EXPECT_EQ(getMaxBoundary<char>(81, 1, 2), 3);
EXPECT_EQ(getMaxBoundary<char>(81, 1, 1), 1);
// Cannot be large than prevLimit '81'
// 81, 2, (7, 6) >= 96
EXPECT_EQ(getMaxBoundary<char>(81, 2, 5), 81);
EXPECT_EQ(getMaxBoundary<char>(81, 2, 4), 79);
EXPECT_EQ(getMaxBoundary<char>(81, 2, 3), 71);
EXPECT_EQ(getMaxBoundary<char>(81, 2, 2), 67);
EXPECT_EQ(getMaxBoundary<char>(81, 2, 1), 65);
// Cannot be large than prevLimit '81'
// 81, 3, (4, 3, 2) >= 82
EXPECT_EQ(getMaxBoundary<char>(81, 3, 1), 81);
//////////////////////////////
EXPECT_EQ((char)getMaxBoundary<char>(127, 1, -7), -64);
EXPECT_EQ((char)getMaxBoundary<char>(127, 1, -6), -32);
EXPECT_EQ((char)getMaxBoundary<char>(127, 1, -5), -16);
EXPECT_EQ((char)getMaxBoundary<char>(127, 1, -4), -8);
EXPECT_EQ((char)getMaxBoundary<char>(127, 1, -3), -4);
EXPECT_EQ((char)getMaxBoundary<char>(127, 1, -2), -2);
EXPECT_EQ((char)getMaxBoundary<char>(127, 1, -1), -1);
EXPECT_EQ((char)getMaxBoundary<char>(127, 1, 0), 0);
EXPECT_EQ((char)getMaxBoundary<char>(127, 1, 1), 1);
EXPECT_EQ((char)getMaxBoundary<char>(127, 1, 2), 3);
EXPECT_EQ((char)getMaxBoundary<char>(127, 1, 3), 7);
EXPECT_EQ((char)getMaxBoundary<char>(127, 1, 4), 15);
EXPECT_EQ((char)getMaxBoundary<char>(127, 1, 5), 31);
EXPECT_EQ((char)getMaxBoundary<char>(127, 1, 6), 63);
EXPECT_EQ((char)getMaxBoundary<char>(127, 1, 7), 127);
//////////////////////////////
EXPECT_EQ((char)getMaxBoundary<char>(-78, 2, -4), -78);
}
TEST(util_math, getMaxValue)
{
EXPECT_EQ(getMaxValue<char>(), 127);
EXPECT_EQ(getMaxValue<uint8_t>(), 255);
EXPECT_EQ(getMaxValue<int16_t>(), 32767);
EXPECT_EQ(getMaxValue<uint16_t>(), 65535);
}
TEST(util_math, getMinValue)
{
EXPECT_EQ(getMinValue<char>(), -128);
EXPECT_EQ(getMinValue<uint8_t>(), 0);
EXPECT_EQ(getMinValue<int16_t>(), -32768);
EXPECT_EQ(getMinValue<uint16_t>(), 0);
}
TEST(util_math, getPrefixPosForPrevLimit)
{
EXPECT_EQ(getPrefixPosForPrevLimit(64, 2), 7);
}
| 29.988372
| 56
| 0.642691
|
KUDB
|
39e31ff5d9cf5478fc0183ec4f1664a9ad4218e9
| 31,717
|
inl
|
C++
|
engine/xboxsystem.xsessioncallstack.inl
|
DannyParker0001/Kisak-Strike
|
99ed85927336fe3aff2efd9b9382b2b32eb1d05d
|
[
"Unlicense"
] | 252
|
2020-12-16T15:34:43.000Z
|
2022-03-31T23:21:37.000Z
|
cstrike15_src/engine/xboxsystem.xsessioncallstack.inl
|
bahadiraraz/Counter-Strike-Global-Offensive
|
9a0534100cb98ffa1cf0c32e138f0e7971e910d3
|
[
"MIT"
] | 23
|
2020-12-20T18:02:54.000Z
|
2022-03-28T16:58:32.000Z
|
cstrike15_src/engine/xboxsystem.xsessioncallstack.inl
|
bahadiraraz/Counter-Strike-Global-Offensive
|
9a0534100cb98ffa1cf0c32e138f0e7971e910d3
|
[
"MIT"
] | 42
|
2020-12-19T04:32:33.000Z
|
2022-03-30T06:00:28.000Z
|
#define HELPER_OVERLAPPED_SESSION_CALL_C_0( )
#define HELPER_OVERLAPPED_SESSION_CALL_A_0( )
#define HELPER_OVERLAPPED_SESSION_CALL_P_0( )
#define HELPER_OVERLAPPED_SESSION_CALL_I_0( )
#define HELPER_OVERLAPPED_SESSION_CALL_M_0( )
#define DECLARE_OVERLAPPED_SESSION_CALL_0( XCallNameFN_T ) \
struct XCallNameFN_T##_OverlappedCall_t : public XSessionCallStack::OverlappedSessionCall { \
XCallNameFN_T##_OverlappedCall_t( HANDLE hSession, \
HELPER_OVERLAPPED_SESSION_CALL_C_0( ) \
PXOVERLAPPED pxOverlapped ) : \
XSessionCallStack::OverlappedSessionCall( hSession, pxOverlapped ) \
HELPER_OVERLAPPED_SESSION_CALL_A_0( ) {} \
virtual char const * Name() { return #XCallNameFN_T; } \
virtual DWORD Run() { \
DWORD ret = ::XCallNameFN_T( m_hSession, \
HELPER_OVERLAPPED_SESSION_CALL_P_0( ) \
m_pxOverlapped ? &m_xOverlapped : NULL ); \
if ( ret != ERROR_SUCCESS && ret != ERROR_IO_PENDING ) { Warning( "XCall " #XCallNameFN_T " failed ( ret = %d, overlapped = %p )!\n", ret, m_pxOverlapped ); Assert( 0 ); } \
return ret; } \
HELPER_OVERLAPPED_SESSION_CALL_M_0( ) \
};
#define IMPLEMENT_OVERLAPPED_SESSION_CALL_0( XCallNameFN_T ) \
DECLARE_OVERLAPPED_SESSION_CALL_0( XCallNameFN_T ) \
virtual DWORD XCallNameFN_T( HANDLE hSession, \
HELPER_OVERLAPPED_SESSION_CALL_C_0( ) \
PXOVERLAPPED pxOverlapped ) { \
return g_XSessionCallStack.ScheduleOverlappedSessionCall( new XCallNameFN_T##_OverlappedCall_t( hSession, \
HELPER_OVERLAPPED_SESSION_CALL_I_0( ) \
pxOverlapped ) ); \
};
#define HELPER_OVERLAPPED_SESSION_CALL_C_1( ArgType1, ArgName1 ) ArgType1 ArgName1,
#define HELPER_OVERLAPPED_SESSION_CALL_A_1( ArgType1, ArgName1 ) , m_##ArgName1( ArgName1 )
#define HELPER_OVERLAPPED_SESSION_CALL_P_1( ArgType1, ArgName1 ) m_##ArgName1,
#define HELPER_OVERLAPPED_SESSION_CALL_I_1( ArgType1, ArgName1 ) ArgName1,
#define HELPER_OVERLAPPED_SESSION_CALL_M_1( ArgType1, ArgName1 ) ArgType1 m_##ArgName1;
#define DECLARE_OVERLAPPED_SESSION_CALL_1( XCallNameFN_T, ArgType1, ArgName1 ) \
struct XCallNameFN_T##_OverlappedCall_t : public XSessionCallStack::OverlappedSessionCall { \
XCallNameFN_T##_OverlappedCall_t( HANDLE hSession, \
HELPER_OVERLAPPED_SESSION_CALL_C_1( ArgType1, ArgName1 ) \
PXOVERLAPPED pxOverlapped ) : \
XSessionCallStack::OverlappedSessionCall( hSession, pxOverlapped ) \
HELPER_OVERLAPPED_SESSION_CALL_A_1( ArgType1, ArgName1 ) {} \
virtual char const * Name() { return #XCallNameFN_T; } \
virtual DWORD Run() { \
DWORD ret = ::XCallNameFN_T( m_hSession, \
HELPER_OVERLAPPED_SESSION_CALL_P_1( ArgType1, ArgName1 ) \
m_pxOverlapped ? &m_xOverlapped : NULL ); \
if ( ret != ERROR_SUCCESS && ret != ERROR_IO_PENDING ) { Warning( "XCall " #XCallNameFN_T " failed ( ret = %d, overlapped = %p )!\n", ret, m_pxOverlapped ); Assert( 0 ); } \
return ret; } \
HELPER_OVERLAPPED_SESSION_CALL_M_1( ArgType1, ArgName1 ) \
};
#define IMPLEMENT_OVERLAPPED_SESSION_CALL_1( XCallNameFN_T, ArgType1, ArgName1 ) \
DECLARE_OVERLAPPED_SESSION_CALL_1( XCallNameFN_T, ArgType1, ArgName1 ) \
virtual DWORD XCallNameFN_T( HANDLE hSession, \
HELPER_OVERLAPPED_SESSION_CALL_C_1( ArgType1, ArgName1 ) \
PXOVERLAPPED pxOverlapped ) { \
return g_XSessionCallStack.ScheduleOverlappedSessionCall( new XCallNameFN_T##_OverlappedCall_t( hSession, \
HELPER_OVERLAPPED_SESSION_CALL_I_1( ArgType1, ArgName1 ) \
pxOverlapped ) ); \
};
#define HELPER_OVERLAPPED_SESSION_CALL_C_2( ArgType1, ArgName1, ArgType2, ArgName2 ) ArgType1 ArgName1, ArgType2 ArgName2,
#define HELPER_OVERLAPPED_SESSION_CALL_A_2( ArgType1, ArgName1, ArgType2, ArgName2 ) , m_##ArgName1( ArgName1 ), m_##ArgName2( ArgName2 )
#define HELPER_OVERLAPPED_SESSION_CALL_P_2( ArgType1, ArgName1, ArgType2, ArgName2 ) m_##ArgName1, m_##ArgName2,
#define HELPER_OVERLAPPED_SESSION_CALL_I_2( ArgType1, ArgName1, ArgType2, ArgName2 ) ArgName1, ArgName2,
#define HELPER_OVERLAPPED_SESSION_CALL_M_2( ArgType1, ArgName1, ArgType2, ArgName2 ) ArgType1 m_##ArgName1;ArgType2 m_##ArgName2;
#define DECLARE_OVERLAPPED_SESSION_CALL_2( XCallNameFN_T, ArgType1, ArgName1, ArgType2, ArgName2 ) \
struct XCallNameFN_T##_OverlappedCall_t : public XSessionCallStack::OverlappedSessionCall { \
XCallNameFN_T##_OverlappedCall_t( HANDLE hSession, \
HELPER_OVERLAPPED_SESSION_CALL_C_2( ArgType1, ArgName1, ArgType2, ArgName2 ) \
PXOVERLAPPED pxOverlapped ) : \
XSessionCallStack::OverlappedSessionCall( hSession, pxOverlapped ) \
HELPER_OVERLAPPED_SESSION_CALL_A_2( ArgType1, ArgName1, ArgType2, ArgName2 ) {} \
virtual char const * Name() { return #XCallNameFN_T; } \
virtual DWORD Run() { \
DWORD ret = ::XCallNameFN_T( m_hSession, \
HELPER_OVERLAPPED_SESSION_CALL_P_2( ArgType1, ArgName1, ArgType2, ArgName2 ) \
m_pxOverlapped ? &m_xOverlapped : NULL ); \
if ( ret != ERROR_SUCCESS && ret != ERROR_IO_PENDING ) { Warning( "XCall " #XCallNameFN_T " failed ( ret = %d, overlapped = %p )!\n", ret, m_pxOverlapped ); Assert( 0 ); } \
return ret; } \
HELPER_OVERLAPPED_SESSION_CALL_M_2( ArgType1, ArgName1, ArgType2, ArgName2 ) \
};
#define IMPLEMENT_OVERLAPPED_SESSION_CALL_2( XCallNameFN_T, ArgType1, ArgName1, ArgType2, ArgName2 ) \
DECLARE_OVERLAPPED_SESSION_CALL_2( XCallNameFN_T, ArgType1, ArgName1, ArgType2, ArgName2 ) \
virtual DWORD XCallNameFN_T( HANDLE hSession, \
HELPER_OVERLAPPED_SESSION_CALL_C_2( ArgType1, ArgName1, ArgType2, ArgName2 ) \
PXOVERLAPPED pxOverlapped ) { \
return g_XSessionCallStack.ScheduleOverlappedSessionCall( new XCallNameFN_T##_OverlappedCall_t( hSession, \
HELPER_OVERLAPPED_SESSION_CALL_I_2( ArgType1, ArgName1, ArgType2, ArgName2 ) \
pxOverlapped ) ); \
};
#define HELPER_OVERLAPPED_SESSION_CALL_C_3( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3 ) ArgType1 ArgName1, ArgType2 ArgName2, ArgType3 ArgName3,
#define HELPER_OVERLAPPED_SESSION_CALL_A_3( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3 ) , m_##ArgName1( ArgName1 ), m_##ArgName2( ArgName2 ), m_##ArgName3( ArgName3 )
#define HELPER_OVERLAPPED_SESSION_CALL_P_3( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3 ) m_##ArgName1, m_##ArgName2, m_##ArgName3,
#define HELPER_OVERLAPPED_SESSION_CALL_I_3( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3 ) ArgName1, ArgName2, ArgName3,
#define HELPER_OVERLAPPED_SESSION_CALL_M_3( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3 ) ArgType1 m_##ArgName1;ArgType2 m_##ArgName2;ArgType3 m_##ArgName3;
#define DECLARE_OVERLAPPED_SESSION_CALL_3( XCallNameFN_T, ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3 ) \
struct XCallNameFN_T##_OverlappedCall_t : public XSessionCallStack::OverlappedSessionCall { \
XCallNameFN_T##_OverlappedCall_t( HANDLE hSession, \
HELPER_OVERLAPPED_SESSION_CALL_C_3( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3 ) \
PXOVERLAPPED pxOverlapped ) : \
XSessionCallStack::OverlappedSessionCall( hSession, pxOverlapped ) \
HELPER_OVERLAPPED_SESSION_CALL_A_3( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3 ) {} \
virtual char const * Name() { return #XCallNameFN_T; } \
virtual DWORD Run() { \
DWORD ret = ::XCallNameFN_T( m_hSession, \
HELPER_OVERLAPPED_SESSION_CALL_P_3( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3 ) \
m_pxOverlapped ? &m_xOverlapped : NULL ); \
if ( ret != ERROR_SUCCESS && ret != ERROR_IO_PENDING ) { Warning( "XCall " #XCallNameFN_T " failed ( ret = %d, overlapped = %p )!\n", ret, m_pxOverlapped ); Assert( 0 ); } \
return ret; } \
HELPER_OVERLAPPED_SESSION_CALL_M_3( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3 ) \
};
#define IMPLEMENT_OVERLAPPED_SESSION_CALL_3( XCallNameFN_T, ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3 ) \
DECLARE_OVERLAPPED_SESSION_CALL_3( XCallNameFN_T, ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3 ) \
virtual DWORD XCallNameFN_T( HANDLE hSession, \
HELPER_OVERLAPPED_SESSION_CALL_C_3( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3 ) \
PXOVERLAPPED pxOverlapped ) { \
return g_XSessionCallStack.ScheduleOverlappedSessionCall( new XCallNameFN_T##_OverlappedCall_t( hSession, \
HELPER_OVERLAPPED_SESSION_CALL_I_3( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3 ) \
pxOverlapped ) ); \
};
#define HELPER_OVERLAPPED_SESSION_CALL_C_4( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4 ) ArgType1 ArgName1, ArgType2 ArgName2, ArgType3 ArgName3, ArgType4 ArgName4,
#define HELPER_OVERLAPPED_SESSION_CALL_A_4( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4 ) , m_##ArgName1( ArgName1 ), m_##ArgName2( ArgName2 ), m_##ArgName3( ArgName3 ), m_##ArgName4( ArgName4 )
#define HELPER_OVERLAPPED_SESSION_CALL_P_4( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4 ) m_##ArgName1, m_##ArgName2, m_##ArgName3, m_##ArgName4,
#define HELPER_OVERLAPPED_SESSION_CALL_I_4( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4 ) ArgName1, ArgName2, ArgName3, ArgName4,
#define HELPER_OVERLAPPED_SESSION_CALL_M_4( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4 ) ArgType1 m_##ArgName1;ArgType2 m_##ArgName2;ArgType3 m_##ArgName3;ArgType4 m_##ArgName4;
#define DECLARE_OVERLAPPED_SESSION_CALL_4( XCallNameFN_T, ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4 ) \
struct XCallNameFN_T##_OverlappedCall_t : public XSessionCallStack::OverlappedSessionCall { \
XCallNameFN_T##_OverlappedCall_t( HANDLE hSession, \
HELPER_OVERLAPPED_SESSION_CALL_C_4( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4 ) \
PXOVERLAPPED pxOverlapped ) : \
XSessionCallStack::OverlappedSessionCall( hSession, pxOverlapped ) \
HELPER_OVERLAPPED_SESSION_CALL_A_4( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4 ) {} \
virtual char const * Name() { return #XCallNameFN_T; } \
virtual DWORD Run() { \
DWORD ret = ::XCallNameFN_T( m_hSession, \
HELPER_OVERLAPPED_SESSION_CALL_P_4( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4 ) \
m_pxOverlapped ? &m_xOverlapped : NULL ); \
if ( ret != ERROR_SUCCESS && ret != ERROR_IO_PENDING ) { Warning( "XCall " #XCallNameFN_T " failed ( ret = %d, overlapped = %p )!\n", ret, m_pxOverlapped ); Assert( 0 ); } \
return ret; } \
HELPER_OVERLAPPED_SESSION_CALL_M_4( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4 ) \
};
#define IMPLEMENT_OVERLAPPED_SESSION_CALL_4( XCallNameFN_T, ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4 ) \
DECLARE_OVERLAPPED_SESSION_CALL_4( XCallNameFN_T, ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4 ) \
virtual DWORD XCallNameFN_T( HANDLE hSession, \
HELPER_OVERLAPPED_SESSION_CALL_C_4( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4 ) \
PXOVERLAPPED pxOverlapped ) { \
return g_XSessionCallStack.ScheduleOverlappedSessionCall( new XCallNameFN_T##_OverlappedCall_t( hSession, \
HELPER_OVERLAPPED_SESSION_CALL_I_4( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4 ) \
pxOverlapped ) ); \
};
#define HELPER_OVERLAPPED_SESSION_CALL_C_5( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5 ) ArgType1 ArgName1, ArgType2 ArgName2, ArgType3 ArgName3, ArgType4 ArgName4, ArgType5 ArgName5,
#define HELPER_OVERLAPPED_SESSION_CALL_A_5( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5 ) , m_##ArgName1( ArgName1 ), m_##ArgName2( ArgName2 ), m_##ArgName3( ArgName3 ), m_##ArgName4( ArgName4 ), m_##ArgName5( ArgName5 )
#define HELPER_OVERLAPPED_SESSION_CALL_P_5( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5 ) m_##ArgName1, m_##ArgName2, m_##ArgName3, m_##ArgName4, m_##ArgName5,
#define HELPER_OVERLAPPED_SESSION_CALL_I_5( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5 ) ArgName1, ArgName2, ArgName3, ArgName4, ArgName5,
#define HELPER_OVERLAPPED_SESSION_CALL_M_5( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5 ) ArgType1 m_##ArgName1;ArgType2 m_##ArgName2;ArgType3 m_##ArgName3;ArgType4 m_##ArgName4;ArgType5 m_##ArgName5;
#define DECLARE_OVERLAPPED_SESSION_CALL_5( XCallNameFN_T, ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5 ) \
struct XCallNameFN_T##_OverlappedCall_t : public XSessionCallStack::OverlappedSessionCall { \
XCallNameFN_T##_OverlappedCall_t( HANDLE hSession, \
HELPER_OVERLAPPED_SESSION_CALL_C_5( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5 ) \
PXOVERLAPPED pxOverlapped ) : \
XSessionCallStack::OverlappedSessionCall( hSession, pxOverlapped ) \
HELPER_OVERLAPPED_SESSION_CALL_A_5( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5 ) {} \
virtual char const * Name() { return #XCallNameFN_T; } \
virtual DWORD Run() { \
DWORD ret = ::XCallNameFN_T( m_hSession, \
HELPER_OVERLAPPED_SESSION_CALL_P_5( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5 ) \
m_pxOverlapped ? &m_xOverlapped : NULL ); \
if ( ret != ERROR_SUCCESS && ret != ERROR_IO_PENDING ) { Warning( "XCall " #XCallNameFN_T " failed ( ret = %d, overlapped = %p )!\n", ret, m_pxOverlapped ); Assert( 0 ); } \
return ret; } \
HELPER_OVERLAPPED_SESSION_CALL_M_5( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5 ) \
};
#define IMPLEMENT_OVERLAPPED_SESSION_CALL_5( XCallNameFN_T, ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5 ) \
DECLARE_OVERLAPPED_SESSION_CALL_5( XCallNameFN_T, ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5 ) \
virtual DWORD XCallNameFN_T( HANDLE hSession, \
HELPER_OVERLAPPED_SESSION_CALL_C_5( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5 ) \
PXOVERLAPPED pxOverlapped ) { \
return g_XSessionCallStack.ScheduleOverlappedSessionCall( new XCallNameFN_T##_OverlappedCall_t( hSession, \
HELPER_OVERLAPPED_SESSION_CALL_I_5( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5 ) \
pxOverlapped ) ); \
};
#define HELPER_OVERLAPPED_SESSION_CALL_C_6( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6 ) ArgType1 ArgName1, ArgType2 ArgName2, ArgType3 ArgName3, ArgType4 ArgName4, ArgType5 ArgName5, ArgType6 ArgName6,
#define HELPER_OVERLAPPED_SESSION_CALL_A_6( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6 ) , m_##ArgName1( ArgName1 ), m_##ArgName2( ArgName2 ), m_##ArgName3( ArgName3 ), m_##ArgName4( ArgName4 ), m_##ArgName5( ArgName5 ), m_##ArgName6( ArgName6 )
#define HELPER_OVERLAPPED_SESSION_CALL_P_6( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6 ) m_##ArgName1, m_##ArgName2, m_##ArgName3, m_##ArgName4, m_##ArgName5, m_##ArgName6,
#define HELPER_OVERLAPPED_SESSION_CALL_I_6( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6 ) ArgName1, ArgName2, ArgName3, ArgName4, ArgName5, ArgName6,
#define HELPER_OVERLAPPED_SESSION_CALL_M_6( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6 ) ArgType1 m_##ArgName1;ArgType2 m_##ArgName2;ArgType3 m_##ArgName3;ArgType4 m_##ArgName4;ArgType5 m_##ArgName5;ArgType6 m_##ArgName6;
#define DECLARE_OVERLAPPED_SESSION_CALL_6( XCallNameFN_T, ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6 ) \
struct XCallNameFN_T##_OverlappedCall_t : public XSessionCallStack::OverlappedSessionCall { \
XCallNameFN_T##_OverlappedCall_t( HANDLE hSession, \
HELPER_OVERLAPPED_SESSION_CALL_C_6( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6 ) \
PXOVERLAPPED pxOverlapped ) : \
XSessionCallStack::OverlappedSessionCall( hSession, pxOverlapped ) \
HELPER_OVERLAPPED_SESSION_CALL_A_6( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6 ) {} \
virtual char const * Name() { return #XCallNameFN_T; } \
virtual DWORD Run() { \
DWORD ret = ::XCallNameFN_T( m_hSession, \
HELPER_OVERLAPPED_SESSION_CALL_P_6( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6 ) \
m_pxOverlapped ? &m_xOverlapped : NULL ); \
if ( ret != ERROR_SUCCESS && ret != ERROR_IO_PENDING ) { Warning( "XCall " #XCallNameFN_T " failed ( ret = %d, overlapped = %p )!\n", ret, m_pxOverlapped ); Assert( 0 ); } \
return ret; } \
HELPER_OVERLAPPED_SESSION_CALL_M_6( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6 ) \
};
#define IMPLEMENT_OVERLAPPED_SESSION_CALL_6( XCallNameFN_T, ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6 ) \
DECLARE_OVERLAPPED_SESSION_CALL_6( XCallNameFN_T, ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6 ) \
virtual DWORD XCallNameFN_T( HANDLE hSession, \
HELPER_OVERLAPPED_SESSION_CALL_C_6( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6 ) \
PXOVERLAPPED pxOverlapped ) { \
return g_XSessionCallStack.ScheduleOverlappedSessionCall( new XCallNameFN_T##_OverlappedCall_t( hSession, \
HELPER_OVERLAPPED_SESSION_CALL_I_6( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6 ) \
pxOverlapped ) ); \
};
#define HELPER_OVERLAPPED_SESSION_CALL_C_7( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7 ) ArgType1 ArgName1, ArgType2 ArgName2, ArgType3 ArgName3, ArgType4 ArgName4, ArgType5 ArgName5, ArgType6 ArgName6, ArgType7 ArgName7,
#define HELPER_OVERLAPPED_SESSION_CALL_A_7( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7 ) , m_##ArgName1( ArgName1 ), m_##ArgName2( ArgName2 ), m_##ArgName3( ArgName3 ), m_##ArgName4( ArgName4 ), m_##ArgName5( ArgName5 ), m_##ArgName6( ArgName6 ), m_##ArgName7( ArgName7 )
#define HELPER_OVERLAPPED_SESSION_CALL_P_7( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7 ) m_##ArgName1, m_##ArgName2, m_##ArgName3, m_##ArgName4, m_##ArgName5, m_##ArgName6, m_##ArgName7,
#define HELPER_OVERLAPPED_SESSION_CALL_I_7( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7 ) ArgName1, ArgName2, ArgName3, ArgName4, ArgName5, ArgName6, ArgName7,
#define HELPER_OVERLAPPED_SESSION_CALL_M_7( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7 ) ArgType1 m_##ArgName1;ArgType2 m_##ArgName2;ArgType3 m_##ArgName3;ArgType4 m_##ArgName4;ArgType5 m_##ArgName5;ArgType6 m_##ArgName6;ArgType7 m_##ArgName7;
#define DECLARE_OVERLAPPED_SESSION_CALL_7( XCallNameFN_T, ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7 ) \
struct XCallNameFN_T##_OverlappedCall_t : public XSessionCallStack::OverlappedSessionCall { \
XCallNameFN_T##_OverlappedCall_t( HANDLE hSession, \
HELPER_OVERLAPPED_SESSION_CALL_C_7( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7 ) \
PXOVERLAPPED pxOverlapped ) : \
XSessionCallStack::OverlappedSessionCall( hSession, pxOverlapped ) \
HELPER_OVERLAPPED_SESSION_CALL_A_7( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7 ) {} \
virtual char const * Name() { return #XCallNameFN_T; } \
virtual DWORD Run() { \
DWORD ret = ::XCallNameFN_T( m_hSession, \
HELPER_OVERLAPPED_SESSION_CALL_P_7( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7 ) \
m_pxOverlapped ? &m_xOverlapped : NULL ); \
if ( ret != ERROR_SUCCESS && ret != ERROR_IO_PENDING ) { Warning( "XCall " #XCallNameFN_T " failed ( ret = %d, overlapped = %p )!\n", ret, m_pxOverlapped ); Assert( 0 ); } \
return ret; } \
HELPER_OVERLAPPED_SESSION_CALL_M_7( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7 ) \
};
#define IMPLEMENT_OVERLAPPED_SESSION_CALL_7( XCallNameFN_T, ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7 ) \
DECLARE_OVERLAPPED_SESSION_CALL_7( XCallNameFN_T, ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7 ) \
virtual DWORD XCallNameFN_T( HANDLE hSession, \
HELPER_OVERLAPPED_SESSION_CALL_C_7( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7 ) \
PXOVERLAPPED pxOverlapped ) { \
return g_XSessionCallStack.ScheduleOverlappedSessionCall( new XCallNameFN_T##_OverlappedCall_t( hSession, \
HELPER_OVERLAPPED_SESSION_CALL_I_7( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7 ) \
pxOverlapped ) ); \
};
#define HELPER_OVERLAPPED_SESSION_CALL_C_8( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7, ArgType8, ArgName8 ) ArgType1 ArgName1, ArgType2 ArgName2, ArgType3 ArgName3, ArgType4 ArgName4, ArgType5 ArgName5, ArgType6 ArgName6, ArgType7 ArgName7, ArgType8 ArgName8,
#define HELPER_OVERLAPPED_SESSION_CALL_A_8( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7, ArgType8, ArgName8 ) , m_##ArgName1( ArgName1 ), m_##ArgName2( ArgName2 ), m_##ArgName3( ArgName3 ), m_##ArgName4( ArgName4 ), m_##ArgName5( ArgName5 ), m_##ArgName6( ArgName6 ), m_##ArgName7( ArgName7 ), m_##ArgName8( ArgName8 )
#define HELPER_OVERLAPPED_SESSION_CALL_P_8( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7, ArgType8, ArgName8 ) m_##ArgName1, m_##ArgName2, m_##ArgName3, m_##ArgName4, m_##ArgName5, m_##ArgName6, m_##ArgName7, m_##ArgName8,
#define HELPER_OVERLAPPED_SESSION_CALL_I_8( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7, ArgType8, ArgName8 ) ArgName1, ArgName2, ArgName3, ArgName4, ArgName5, ArgName6, ArgName7, ArgName8,
#define HELPER_OVERLAPPED_SESSION_CALL_M_8( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7, ArgType8, ArgName8 ) ArgType1 m_##ArgName1;ArgType2 m_##ArgName2;ArgType3 m_##ArgName3;ArgType4 m_##ArgName4;ArgType5 m_##ArgName5;ArgType6 m_##ArgName6;ArgType7 m_##ArgName7;ArgType8 m_##ArgName8;
#define DECLARE_OVERLAPPED_SESSION_CALL_8( XCallNameFN_T, ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7, ArgType8, ArgName8 ) \
struct XCallNameFN_T##_OverlappedCall_t : public XSessionCallStack::OverlappedSessionCall { \
XCallNameFN_T##_OverlappedCall_t( HANDLE hSession, \
HELPER_OVERLAPPED_SESSION_CALL_C_8( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7, ArgType8, ArgName8 ) \
PXOVERLAPPED pxOverlapped ) : \
XSessionCallStack::OverlappedSessionCall( hSession, pxOverlapped ) \
HELPER_OVERLAPPED_SESSION_CALL_A_8( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7, ArgType8, ArgName8 ) {} \
virtual char const * Name() { return #XCallNameFN_T; } \
virtual DWORD Run() { \
DWORD ret = ::XCallNameFN_T( m_hSession, \
HELPER_OVERLAPPED_SESSION_CALL_P_8( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7, ArgType8, ArgName8 ) \
m_pxOverlapped ? &m_xOverlapped : NULL ); \
if ( ret != ERROR_SUCCESS && ret != ERROR_IO_PENDING ) { Warning( "XCall " #XCallNameFN_T " failed ( ret = %d, overlapped = %p )!\n", ret, m_pxOverlapped ); Assert( 0 ); } \
return ret; } \
HELPER_OVERLAPPED_SESSION_CALL_M_8( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7, ArgType8, ArgName8 ) \
};
#define IMPLEMENT_OVERLAPPED_SESSION_CALL_8( XCallNameFN_T, ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7, ArgType8, ArgName8 ) \
DECLARE_OVERLAPPED_SESSION_CALL_8( XCallNameFN_T, ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7, ArgType8, ArgName8 ) \
virtual DWORD XCallNameFN_T( HANDLE hSession, \
HELPER_OVERLAPPED_SESSION_CALL_C_8( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7, ArgType8, ArgName8 ) \
PXOVERLAPPED pxOverlapped ) { \
return g_XSessionCallStack.ScheduleOverlappedSessionCall( new XCallNameFN_T##_OverlappedCall_t( hSession, \
HELPER_OVERLAPPED_SESSION_CALL_I_8( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7, ArgType8, ArgName8 ) \
pxOverlapped ) ); \
};
#define HELPER_OVERLAPPED_SESSION_CALL_C_9( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7, ArgType8, ArgName8, ArgType9, ArgName9 ) ArgType1 ArgName1, ArgType2 ArgName2, ArgType3 ArgName3, ArgType4 ArgName4, ArgType5 ArgName5, ArgType6 ArgName6, ArgType7 ArgName7, ArgType8 ArgName8, ArgType9 ArgName9,
#define HELPER_OVERLAPPED_SESSION_CALL_A_9( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7, ArgType8, ArgName8, ArgType9, ArgName9 ) , m_##ArgName1( ArgName1 ), m_##ArgName2( ArgName2 ), m_##ArgName3( ArgName3 ), m_##ArgName4( ArgName4 ), m_##ArgName5( ArgName5 ), m_##ArgName6( ArgName6 ), m_##ArgName7( ArgName7 ), m_##ArgName8( ArgName8 ), m_##ArgName9( ArgName9 )
#define HELPER_OVERLAPPED_SESSION_CALL_P_9( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7, ArgType8, ArgName8, ArgType9, ArgName9 ) m_##ArgName1, m_##ArgName2, m_##ArgName3, m_##ArgName4, m_##ArgName5, m_##ArgName6, m_##ArgName7, m_##ArgName8, m_##ArgName9,
#define HELPER_OVERLAPPED_SESSION_CALL_I_9( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7, ArgType8, ArgName8, ArgType9, ArgName9 ) ArgName1, ArgName2, ArgName3, ArgName4, ArgName5, ArgName6, ArgName7, ArgName8, ArgName9,
#define HELPER_OVERLAPPED_SESSION_CALL_M_9( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7, ArgType8, ArgName8, ArgType9, ArgName9 ) ArgType1 m_##ArgName1;ArgType2 m_##ArgName2;ArgType3 m_##ArgName3;ArgType4 m_##ArgName4;ArgType5 m_##ArgName5;ArgType6 m_##ArgName6;ArgType7 m_##ArgName7;ArgType8 m_##ArgName8;ArgType9 m_##ArgName9;
#define DECLARE_OVERLAPPED_SESSION_CALL_9( XCallNameFN_T, ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7, ArgType8, ArgName8, ArgType9, ArgName9 ) \
struct XCallNameFN_T##_OverlappedCall_t : public XSessionCallStack::OverlappedSessionCall { \
XCallNameFN_T##_OverlappedCall_t( HANDLE hSession, \
HELPER_OVERLAPPED_SESSION_CALL_C_9( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7, ArgType8, ArgName8, ArgType9, ArgName9 ) \
PXOVERLAPPED pxOverlapped ) : \
XSessionCallStack::OverlappedSessionCall( hSession, pxOverlapped ) \
HELPER_OVERLAPPED_SESSION_CALL_A_9( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7, ArgType8, ArgName8, ArgType9, ArgName9 ) {} \
virtual char const * Name() { return #XCallNameFN_T; } \
virtual DWORD Run() { \
DWORD ret = ::XCallNameFN_T( m_hSession, \
HELPER_OVERLAPPED_SESSION_CALL_P_9( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7, ArgType8, ArgName8, ArgType9, ArgName9 ) \
m_pxOverlapped ? &m_xOverlapped : NULL ); \
if ( ret != ERROR_SUCCESS && ret != ERROR_IO_PENDING ) { Warning( "XCall " #XCallNameFN_T " failed ( ret = %d, overlapped = %p )!\n", ret, m_pxOverlapped ); Assert( 0 ); } \
return ret; } \
HELPER_OVERLAPPED_SESSION_CALL_M_9( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7, ArgType8, ArgName8, ArgType9, ArgName9 ) \
};
#define IMPLEMENT_OVERLAPPED_SESSION_CALL_9( XCallNameFN_T, ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7, ArgType8, ArgName8, ArgType9, ArgName9 ) \
DECLARE_OVERLAPPED_SESSION_CALL_9( XCallNameFN_T, ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7, ArgType8, ArgName8, ArgType9, ArgName9 ) \
virtual DWORD XCallNameFN_T( HANDLE hSession, \
HELPER_OVERLAPPED_SESSION_CALL_C_9( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7, ArgType8, ArgName8, ArgType9, ArgName9 ) \
PXOVERLAPPED pxOverlapped ) { \
return g_XSessionCallStack.ScheduleOverlappedSessionCall( new XCallNameFN_T##_OverlappedCall_t( hSession, \
HELPER_OVERLAPPED_SESSION_CALL_I_9( ArgType1, ArgName1, ArgType2, ArgName2, ArgType3, ArgName3, ArgType4, ArgName4, ArgType5, ArgName5, ArgType6, ArgName6, ArgType7, ArgName7, ArgType8, ArgName8, ArgType9, ArgName9 ) \
pxOverlapped ) ); \
};
| 90.361823
| 459
| 0.784437
|
DannyParker0001
|
39e32bb345f24ec8e744b243f14681b715305457
| 7,905
|
cpp
|
C++
|
Source/AllProjects/Tests/TestCIDLib/TestCIDLib_PerThreadData.cpp
|
eudora-jia/CIDLib
|
02795d283d95f8a5a4fafa401b6189851901b81b
|
[
"MIT"
] | 1
|
2019-05-28T06:33:01.000Z
|
2019-05-28T06:33:01.000Z
|
Source/AllProjects/Tests/TestCIDLib/TestCIDLib_PerThreadData.cpp
|
eudora-jia/CIDLib
|
02795d283d95f8a5a4fafa401b6189851901b81b
|
[
"MIT"
] | null | null | null |
Source/AllProjects/Tests/TestCIDLib/TestCIDLib_PerThreadData.cpp
|
eudora-jia/CIDLib
|
02795d283d95f8a5a4fafa401b6189851901b81b
|
[
"MIT"
] | null | null | null |
//
// FILE NAME: TestCIDLib_PerThreadData.cpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 01/29/1998
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2019
//
// This file is part of a demonstration program of the CIDLib C++
// Frameworks. Its contents are distributed 'as is', to provide guidance on
// the use of the CIDLib system. However, these demos are not intended to
// represent a full fledged applications. Any direct use of demo code in
// user applications is at the user's discretion, and no warranties are
// implied as to its correctness or applicability.
//
// DESCRIPTION:
//
// This module is part of the TestCIDLib.Exe program and is called from the
// program's main() function. The functions in this module test the
// per-thread data support.
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// $_CIDLib_Log_$
//
// -----------------------------------------------------------------------------
// Facility specific includes
// -----------------------------------------------------------------------------
#include "TestCIDLib.hpp"
// -----------------------------------------------------------------------------
// Local static data
//
// ptdArea
// ptdPoint
// ptdString
// Some per-thread data objects for areas, points, and strings. These are
// used in the testing below.
// -----------------------------------------------------------------------------
#if 0
static TPerThreadDataFor<TArea> ptdArea;
static TPerThreadDataFor<TPoint> ptdPoint;
static TPerThreadDataFor<TString> ptdString;
// -----------------------------------------------------------------------------
// TFacTestCIDLib: Local, static methods
// -----------------------------------------------------------------------------
static tCIDLib::TVoid CommonTests()
{
// Get a short cut to the output stream
TTextOutStream& strmOut = TFacTestCIDLib::strmOut();
//
// Check each of the objects and make sure that the initial values
// in them are initialized correct to zero.
//
if (ptdArea.pobjThis())
strmOut << CUR_LN << L"Area per-thread not initialized to zero" << kCIDLib::EndLn;
if (ptdPoint.pobjThis())
strmOut << CUR_LN << L"Point per-thread not initialized to zero" << kCIDLib::EndLn;
if (ptdString.pobjThis())
strmOut << CUR_LN << L"String per-thread not initialized to zero" << kCIDLib::EndLn;
//
// Set each one with an allocated object, then read the object back out
// and test that its the original object.
//
TArea* pareaSet = new TArea(1,2,3,4);
ptdArea.pobjThis(pareaSet);
TPoint* ppntSet = new TPoint(1,2);
ptdPoint.pobjThis(ppntSet);
TString* pstrSet = new TString(L"This is a test");
ptdString.pobjThis(pstrSet);
if (pareaSet != ptdArea.pobjThis())
strmOut << CUR_LN << L"Area object != to object set" << kCIDLib::EndLn;
if (ppntSet != ptdPoint.pobjThis())
strmOut << CUR_LN << L"Point object != to object set" << kCIDLib::EndLn;
if (pstrSet != ptdString.pobjThis())
strmOut << CUR_LN << L"String object != to object set" << kCIDLib::EndLn;
if (ptdArea.objThis() != TArea(1,2,3,4))
strmOut << CUR_LN << L"Area object value != to object set" << kCIDLib::EndLn;
if (ptdPoint.objThis() != TPoint(1,2))
strmOut << CUR_LN << L"Point object value != to object set" << kCIDLib::EndLn;
if (ptdString.objThis() != TString(L"This is a test"))
strmOut << CUR_LN << L"String object value != to object set" << kCIDLib::EndLn;
//
// Test out the dereference operator, which gets out the object pointer
// such that its convenient to access the methods of the object.
//
if (ptdArea->i4Left() != 1)
strmOut << CUR_LN << L"Deref access to area object failed" << kCIDLib::EndLn;
if (ptdPoint->i4Y() != 2)
strmOut << CUR_LN << L"Deref access to point object failed" << kCIDLib::EndLn;
if (ptdString->chAt(0) != L'T')
strmOut << CUR_LN << L"Deref access to string object failed" << kCIDLib::EndLn;
}
static tCIDLib::EExitCodes eTestFunc(TThread& thrThis, tCIDLib::TVoid* pData)
{
// We have to let our calling thread go first
thrThis.Sync();
// Get a short cut to the output stream
TTextOutStream& strmOut = TFacTestCIDLib::strmOut();
// Get started by doing the common tests
CommonTests();
//
// Loop around for a while and manipulate our copy of the data. Check
// each change to insure that it hasn't been stepped on by another
// thread.
//
for (tCIDLib::TCard4 c4LoopCnt = 0; c4LoopCnt < 256; c4LoopCnt++)
{
//
// Set the point to the loop count. Set the area size to the
// loop count. And set the string to the formatted loop count.
//
ptdArea->SetSize(c4LoopCnt, c4LoopCnt);
ptdPoint->i4X(tCIDLib::TInt4(c4LoopCnt));
ptdString.objThis() = TCardinal(c4LoopCnt);
TThread::Sleep(25);
// Check that the values are correct before doing the next loop
if (ptdArea->szSize() != TSize(c4LoopCnt))
strmOut << CUR_LN << L"Thread's area value change not correct" << kCIDLib::EndLn;
if (ptdPoint->i4X() != tCIDLib::TInt4(c4LoopCnt))
strmOut << CUR_LN << L"Thread's point value change not correct" << kCIDLib::EndLn;
if (ptdString.objThis() != TString(TCardinal(c4LoopCnt)))
strmOut << CUR_LN << L"Thread's string value change not correct" << kCIDLib::EndLn;
}
//
// We don't delete the objects for each thread. They should be deleted
// when this thread ends!
//
return tCIDLib::EExitCodes::Normal;
}
static tCIDLib::TVoid SimpleTests()
{
// Get a short cut to the output stream
TTextOutStream& strmOut = TFacTestCIDLib::strmOut();
// Call the common test function
CommonTests();
//
// Delete the objects and set the pointers back to zero so that it will
// work on the next pass if a memory leak pass is done.
//
ptdArea.CleanUpUserData();
ptdPoint.CleanUpUserData();
ptdString.CleanUpUserData();
}
static tCIDLib::TVoid ThreadedTests()
{
// Get a short cut to the output stream
TTextOutStream& strmOut = TFacTestCIDLib::strmOut();
// Kick off a set of threads and wait for all of them to die
const tCIDLib::TCard4 c4ThreadCount = 16;
TThread* apthrList[c4ThreadCount];
// Use a unique name object to create the thread names
TUniqueName unamThreads(L"PerThread%(1)");
tCIDLib::TCard4 c4Index;
for (c4Index = 0; c4Index < c4ThreadCount; c4Index++)
{
apthrList[c4Index] = new TThread
(
unamThreads.strQueryNewName()
, eTestFunc
);
}
// Kick off the threads
for (c4Index = 0; c4Index < c4ThreadCount; c4Index++)
apthrList[c4Index]->Start();
// And wait for all of them to die
for (c4Index = 0; c4Index < c4ThreadCount; c4Index++)
{
apthrList[c4Index]->eWaitForDeath();
delete apthrList[c4Index];
}
}
#endif
// -----------------------------------------------------------------------------
// TFacTestCIDLib: Public, non-virtual methods
// -----------------------------------------------------------------------------
//
// This method calls a number of local functions that test various
// instantiations of the per-thread data classes.
//
tCIDLib::TVoid TFacTestCIDLib::TestPerThreadData()
{
const tCIDLib::TCh* pszCurTest = L"None";
try
{
pszCurTest = L"Simple Test";
// SimpleTests();
pszCurTest = L"Threaded Test";
// ThreadedTests();
}
catch(TError& errToCatch)
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
strmOut() << L"Exception occured during the " << pszCurTest
<< L" test" << kCIDLib::EndLn;
throw;
}
}
| 31.494024
| 95
| 0.588362
|
eudora-jia
|
39e48bf081d40ec8db3df48831bb390e76566619
| 6,256
|
cpp
|
C++
|
UnitTest/AlgorismTest/vertex_delaunay_test.cpp
|
rocketman123456/RocketEngine
|
ede1670d70c4689a5dc8543ca5351e8f23fcb840
|
[
"Apache-2.0"
] | null | null | null |
UnitTest/AlgorismTest/vertex_delaunay_test.cpp
|
rocketman123456/RocketEngine
|
ede1670d70c4689a5dc8543ca5351e8f23fcb840
|
[
"Apache-2.0"
] | null | null | null |
UnitTest/AlgorismTest/vertex_delaunay_test.cpp
|
rocketman123456/RocketEngine
|
ede1670d70c4689a5dc8543ca5351e8f23fcb840
|
[
"Apache-2.0"
] | null | null | null |
#include "Log/Log.h"
#include "Window/DesktopWindow.h"
#include "Render/SoftRasterizer.h"
#include "Render/SoftTriangle.h"
#include "Geometry/Vertex.h"
#include "Geometry/Triangle.h"
#include "Geometry/Sphere.h"
#include "Geometry/Tetrahedra.h"
#include "Geometry/MeshOperation/Delaunay3D.h"
using namespace Rocket;
#include <GLFW/glfw3.h>
#include <glad/glad.h>
#include <iostream>
#include <iomanip>
#include <random>
#include "../Utils/soft_render.h"
static std::mt19937 generator(0);
static std::uniform_real_distribution<> range_distribute(0.0, 1.0);
static std::vector<Geometry::VertexPtr> nodes;
static Geometry::SpherePtr sphere;
static Geometry::TetrahedraPtr tetrahedra;
static Delaunay3DPtr delaunay_3d;
double random(double a = 0.0, double b = 1.0) {
return range_distribute(generator) * (b-a) + a;
}
void VertexSphereTest() {
int32_t count = 0;
while(count <= 0) {
std::cout << "Input node count:";
std::cin >> count;
}
double radius = 1.0;
for(int i = 0; i < count; i++) {
double t1 = random(-3.14/2.0,3.14/2.0);
double t2 = random(0,3.14*2.0);
double x = radius * sin(t1) * sin(t2);
double y = radius * sin(t1) * cos(t2);
double z = radius * cos(t1);
//nodes.push_back(VertexPtr(new Vertex(Eigen::Vector3d(x, y, z))));
nodes.push_back(Geometry::VertexPtr(new Geometry::Vertex(Eigen::Vector3d(random(-1,1), random(-1,1), random(-1,1)))));
}
sphere = Geometry::SpherePtr(new Geometry::Sphere());
sphere->CreateBoundingSphere(nodes);
std::cout << "Sphere Center: "
<< sphere->center[0] << ","
<< sphere->center[1] << ","
<< sphere->center[2] << std::endl;
std::cout << "Sphere Radius: " << sphere->radius << std::endl;
tetrahedra = Geometry::TetrahedraPtr(new Geometry::Tetrahedra());
tetrahedra->CreateBoundingTetrahedra(
sphere,
Eigen::Vector3d(0,0,1),
Eigen::Vector3d(1,0,0),
Eigen::Vector3d(0,1,0)
);
delaunay_3d = Delaunay3DPtr(new Delaunay3D());
delaunay_3d->method = 1;
delaunay_3d->Initialize(nodes);
}
int main(int argc, char** argv) {
//Log::Init();
RenderApp app;
// load image, create texture and generate mipmaps
int32_t width = 1280;
int32_t height = 720;
int32_t nrChannels = 4;
app.Initialize(width, height);
SoftRasterizer rst(width, height);
rst.ClearAll(BufferType::COLOR | BufferType::DEPTH);
Eigen::Vector3f eye_pos = {0.0, 0.0, 5};
int32_t key = 0;
int32_t frame_count = 0;
//rst.DisableWireFrame();
rst.EnableWireFrame();
rst.EnableMsaa();
rst.SetMsaaLevel(0);
VertexSphereTest();
while(!app.ShouldClose()) {
app.Tick();
rst.NextFrame();
rst.Clear(BufferType::COLOR | BufferType::DEPTH);
rst.SetModel(get_model_matrix(global_angle_x, global_angle_y, global_angle_z));
//rst.SetModel(get_model_matrix(global_angle_y, global_angle_z));
//rst.SetModel(get_model_matrix(global_angle_z));
rst.SetView(get_view_matrix(eye_pos));
rst.SetProjection(get_perspective_matrix(45, ((float)width/(float)height), 0.1, 50));
//rst.SetProjection(get_orthographic_matrix(-6.4, 6.4, -50, 50, 3.6, -3.6));
rst.DrawLine3D({0,0,0}, {1,0,0}, {255,0,0}, {255,0,0}); // x
rst.DrawLine3D({0,0,0}, {0,1,0}, {0,255,0}, {0,255,0}); // y
rst.DrawLine3D({0,0,0}, {0,0,1}, {0,0,255}, {0,0,255}); // z
//rst.DrawLine3D({0.5,0.5,0}, {0.5,0.5,2}, {255,0,0}, {0,255,0});
rst.DrawPoint3D({1,1,0}, {255,0,0});
for(auto& node : delaunay_3d->GetNodes()) {
rst.DrawPoint3D(Eigen::Vector3f(node->position[0], node->position[1], node->position[2]));
}
std::vector<Geometry::TetrahedraPtr>& meshs = delaunay_3d->GetResultTetrahedras();
// for(TetrahedraPtr& mesh : meshs) {
// mesh->UpdateFaces();
// std::array<TrianglePtr, 4>& faces = mesh->faces;
// for(TrianglePtr& face : faces) {
// std::array<EdgePtr, 3>& edges = face->edges;
// for(EdgePtr& edge : edges) {
// rst.DrawLine3D(
// Eigen::Vector3f(edge->start->position[0], edge->start->position[1], edge->start->position[2]),
// Eigen::Vector3f(edge->end->position[0], edge->end->position[1], edge->end->position[2]),
// Eigen::Vector3f(255,0,0),
// Eigen::Vector3f(0,0,255)
// );
// }
// }
// }
static int32_t current = 0;
if(meshs.size() > 0) {
current++;
current = current % meshs.size();
auto mesh = meshs[current];
mesh->UpdateFaces();
std::array<Geometry::TrianglePtr, 4>& faces = mesh->faces;
for(Geometry::TrianglePtr& face : faces) {
std::array<Geometry::EdgePtr, 3>& edges = face->edges;
for(Geometry::EdgePtr& edge : edges) {
rst.DrawLine3D(
Eigen::Vector3f(edge->start->position[0], edge->start->position[1], edge->start->position[2]),
Eigen::Vector3f(edge->end->position[0], edge->end->position[1], edge->end->position[2]),
Eigen::Vector3f(255,0,0),
Eigen::Vector3f(0,0,255)
);
}
}
}
// auto& faces = tetrahedra.faces;
// for(auto face : faces) {
// auto& edges = face.edges;
// for(auto edge : edges) {
// rst.DrawLine3D(
// Eigen::Vector3f(edge.first.position[0], edge.first.position[1], edge.first.position[2]),
// Eigen::Vector3f(edge.second.position[0], edge.second.position[1], edge.second.position[2]),
// Eigen::Vector3f(255,0,0),
// Eigen::Vector3f(0,0,255)
// );
// }
// }
auto data = rst.FrameBuffer().data();
app.Render(data);
}
app.Finalize();
//Log::End();
return 0;
}
| 34
| 126
| 0.556426
|
rocketman123456
|
39ee791e1476915f2238a14bb8473981b6f899bc
| 7,082
|
cpp
|
C++
|
image_common/image_transport/src/image_transport.cpp
|
zhj-buffer/ROS2-driver-for-Realsense
|
936cf27be4e7dc3d699ff99499e72ea8638cc622
|
[
"Apache-2.0"
] | null | null | null |
image_common/image_transport/src/image_transport.cpp
|
zhj-buffer/ROS2-driver-for-Realsense
|
936cf27be4e7dc3d699ff99499e72ea8638cc622
|
[
"Apache-2.0"
] | null | null | null |
image_common/image_transport/src/image_transport.cpp
|
zhj-buffer/ROS2-driver-for-Realsense
|
936cf27be4e7dc3d699ff99499e72ea8638cc622
|
[
"Apache-2.0"
] | null | null | null |
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2009, Willow Garage, Inc.
* 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 Willow Garage 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 "image_transport/image_transport.hpp"
#include <memory>
#include <pluginlib/class_loader.hpp>
#include "image_transport/camera_common.hpp"
#include "image_transport/loader_fwds.hpp"
#include "image_transport/publisher_plugin.hpp"
#include "image_transport/subscriber_plugin.hpp"
namespace image_transport
{
struct Impl
{
PubLoaderPtr pub_loader_;
SubLoaderPtr sub_loader_;
Impl()
: pub_loader_(std::make_shared<PubLoader>("image_transport", "image_transport::PublisherPlugin")),
sub_loader_(std::make_shared<SubLoader>("image_transport", "image_transport::SubscriberPlugin"))
{
}
};
static Impl * kImpl = new Impl();
Publisher create_publisher(
rclcpp::Node * node,
const std::string & base_topic,
rmw_qos_profile_t custom_qos)
{
return Publisher(node, base_topic, kImpl->pub_loader_, custom_qos);
}
Subscriber create_subscription(
rclcpp::Node * node,
const std::string & base_topic,
const Subscriber::Callback & callback,
const std::string & transport,
rmw_qos_profile_t custom_qos,
rclcpp::SubscriptionOptions options)
{
return Subscriber(node, base_topic, callback, kImpl->sub_loader_, transport, custom_qos, options);
}
CameraPublisher create_camera_publisher(
rclcpp::Node * node,
const std::string & base_topic,
rmw_qos_profile_t custom_qos)
{
return CameraPublisher(node, base_topic, custom_qos);
}
CameraSubscriber create_camera_subscription(
rclcpp::Node * node,
const std::string & base_topic,
const CameraSubscriber::Callback & callback,
const std::string & transport,
rmw_qos_profile_t custom_qos)
{
return CameraSubscriber(node, base_topic, callback, transport, custom_qos);
}
std::vector<std::string> getDeclaredTransports()
{
std::vector<std::string> transports = kImpl->sub_loader_->getDeclaredClasses();
// Remove the "_sub" at the end of each class name.
for (std::string & transport: transports) {
transport = erase_last_copy(transport, "_sub");
}
return transports;
}
std::vector<std::string> getLoadableTransports()
{
std::vector<std::string> loadableTransports;
for (const std::string & transportPlugin: kImpl->sub_loader_->getDeclaredClasses() ) {
// If the plugin loads without throwing an exception, add its
// transport name to the list of valid plugins, otherwise ignore
// it.
try {
std::shared_ptr<image_transport::SubscriberPlugin> sub =
kImpl->sub_loader_->createUniqueInstance(transportPlugin);
loadableTransports.push_back(erase_last_copy(transportPlugin, "_sub")); // Remove the "_sub" at the end of each class name.
} catch (const pluginlib::LibraryLoadException & e) {
(void) e;
} catch (const pluginlib::CreateClassException & e) {
(void) e;
}
}
return loadableTransports;
}
struct ImageTransport::Impl
{
rclcpp::Node::SharedPtr node_;
};
ImageTransport::ImageTransport(rclcpp::Node::SharedPtr node)
: impl_(std::make_unique<ImageTransport::Impl>())
{
impl_->node_ = node;
}
ImageTransport::~ImageTransport() = default;
Publisher ImageTransport::advertise(const std::string & base_topic, uint32_t queue_size, bool latch)
{
// TODO(ros2) implement when resolved: https://github.com/ros2/ros2/issues/464
(void) latch;
rmw_qos_profile_t custom_qos = rmw_qos_profile_default;
custom_qos.depth = queue_size;
return create_publisher(impl_->node_.get(), base_topic, custom_qos);
}
Subscriber ImageTransport::subscribe(
const std::string & base_topic, uint32_t queue_size,
const Subscriber::Callback & callback,
const VoidPtr & tracked_object,
const TransportHints * transport_hints)
{
(void) tracked_object;
rmw_qos_profile_t custom_qos = rmw_qos_profile_default;
custom_qos.depth = queue_size;
return create_subscription(impl_->node_.get(), base_topic, callback,
getTransportOrDefault(transport_hints), custom_qos);
}
CameraPublisher ImageTransport::advertiseCamera(
const std::string & base_topic, uint32_t queue_size,
bool latch)
{
// TODO(ros2) implement when resolved: https://github.com/ros2/ros2/issues/464
(void) latch;
rmw_qos_profile_t custom_qos = rmw_qos_profile_default;
custom_qos.depth = queue_size;
return create_camera_publisher(impl_->node_.get(), base_topic, custom_qos);
}
CameraSubscriber ImageTransport::subscribeCamera(
const std::string & base_topic, uint32_t queue_size,
const CameraSubscriber::Callback & callback,
const VoidPtr & tracked_object,
const TransportHints * transport_hints)
{
(void) tracked_object;
rmw_qos_profile_t custom_qos = rmw_qos_profile_default;
custom_qos.depth = queue_size;
return create_camera_subscription(impl_->node_.get(), base_topic, callback,
getTransportOrDefault(transport_hints), custom_qos);
}
std::vector<std::string> ImageTransport::getDeclaredTransports() const
{
return image_transport::getDeclaredTransports();
}
std::vector<std::string> ImageTransport::getLoadableTransports() const
{
return image_transport::getLoadableTransports();
}
std::string ImageTransport::getTransportOrDefault(const TransportHints * transport_hints)
{
std::string ret;
if (nullptr == transport_hints) {
TransportHints th(impl_->node_.get());
ret = th.getTransport();
} else {
ret = transport_hints->getTransport();
}
return ret;
}
} //namespace image_transport
| 33.093458
| 129
| 0.741175
|
zhj-buffer
|
39f29b35292f353d7248f2c14e87aa69ce48235a
| 2,824
|
cpp
|
C++
|
salmap_rv/src/salmap_rv_interface.cpp
|
flyingfalling/salmap_rv
|
61827a42f456afcd9c930646de33bc3f9533e3e2
|
[
"MIT"
] | 1
|
2022-02-17T03:05:40.000Z
|
2022-02-17T03:05:40.000Z
|
salmap_rv/src/salmap_rv_interface.cpp
|
flyingfalling/salmap_rv
|
61827a42f456afcd9c930646de33bc3f9533e3e2
|
[
"MIT"
] | null | null | null |
salmap_rv/src/salmap_rv_interface.cpp
|
flyingfalling/salmap_rv
|
61827a42f456afcd9c930646de33bc3f9533e3e2
|
[
"MIT"
] | null | null | null |
#include <salmap_rv/include/salmap_rv_interface.hpp>
#include <salmap_rv/include/salmap.hpp>
#include <salmap_rv/include/itti_salmap.hpp>
#include <salmap_rv/include/param_set.hpp>
#include <salmap_rv/include/util_functs.hpp>
using namespace salmap_rv;
int salmap_vers( )
{
return salmap_rv::SalMap::VERSION;
}
void* salmap_ptr_init( const std::string& _paramset_fname, const float64_t input_dva_wid, const float64_t input_dva_hei )
{
std::string paramset_fname(_paramset_fname);
param_set p = itti_formal_default_params();
if( false == paramset_fname.empty() )
{
p.fromfile( paramset_fname );
}
p.set<int64_t>("dt_nsec", 1 );
p.set<float64_t>("input_dva_wid", input_dva_wid);
p.set<float64_t>("input_dva_hei", input_dva_hei);
p.enumerate();
SalMap* cpusalmap = new SalMap();
make_itti_dyadic_cpu_weighted_formal( p, *cpusalmap, nullptr );
return (void*)cpusalmap;
}
void salmap_ptr_uninit( void* _salmap )
{
SalMap* salmap = (SalMap*)_salmap ;
delete salmap;
}
void salmap_add_input( void* _salmap, const std::string& _inputmapname, cv::Mat& inputmat )
{
std::string inputmapname( _inputmapname );
SalMap* salmap = (SalMap*) _salmap;
salmap->add_input_direct_realtime( inputmapname, inputmat, salmap->get_realtime_sec() );
}
int64_t salmap_update( void* _salmap )
{
SalMap* salmap = (SalMap*) _salmap;
bool updated = salmap->update();
int64_t time = -1;
if( updated )
{
time = salmap->get_time_nsec();
}
return time;
}
cv::Mat salmap_get_map_now_nickname( void* _salmap, const std::string& _filtername, const std::string& _mapname )
{
SalMap* salmap = (SalMap*) _salmap;
cv::Mat ret = salmap->get_map_now_nickname( _filtername, _mapname, cv::Size(0,0) );
return ret;
}
cv::Mat salmap_get_map_pretty( void* _salmap, const std::string& _filtername, const std::string& _mapname, const std::string& _overlaywithinputmap, const float64_t alpha, const int resize_wid_pix )
{
SalMap* salmap = (SalMap*) _salmap;
cv::Mat raw = salmap->get_map_now_nickname( salmap_rv::SalMap::INPUT_FILTER_NICKNAME, _overlaywithinputmap );
cv::Mat sal = salmap->get_map_now_nickname( _filtername, _mapname );
fflush(stderr);
cv::Mat ret;
if( raw.empty() || sal.empty() )
{
fprintf(stderr, "REV: LOLOLOLOL raw or sal was empty?\n");
return ret;
}
int interp = cv::INTER_LINEAR;
cv::Mat rraw = resize_wid( raw, resize_wid_pix, interp );
cv::Mat rsal = resize_wid( sal, resize_wid_pix, interp );
cv::Mat colorsal = apply_color( rsal );
ret = overlay_salmap( rraw, colorsal, alpha, interp );
return ret;
}
| 25.214286
| 199
| 0.661827
|
flyingfalling
|
39fa8414a7efdd1a3993b0b3a31cad00cf0e31c9
| 10,880
|
hpp
|
C++
|
include/ripple/utility/memory.hpp
|
robclu/ripple
|
734dfa77e100a86b3c60589d41ca627e41d4a783
|
[
"MIT"
] | 4
|
2021-04-25T16:38:12.000Z
|
2021-12-23T08:32:15.000Z
|
include/ripple/utility/memory.hpp
|
robclu/ripple
|
734dfa77e100a86b3c60589d41ca627e41d4a783
|
[
"MIT"
] | null | null | null |
include/ripple/utility/memory.hpp
|
robclu/ripple
|
734dfa77e100a86b3c60589d41ca627e41d4a783
|
[
"MIT"
] | null | null | null |
/**=--- ripple/utility/memory.hpp -------------------------- -*- C++ -*- ---==**
*
* Ripple
*
* Copyright (c) 2019 - 2021 Rob Clucas.
*
* This file is distributed under the MIT License. See LICENSE for details.
*
*==-------------------------------------------------------------------------==*
*
* \file memory.hpp
* \brief This file defines a utility functions for memory related operations.
*
*==------------------------------------------------------------------------==*/
#ifndef RIPPLE_UTILITY_MEMORY_HPP
#define RIPPLE_UTILITY_MEMORY_HPP
#include "portability.hpp"
#include <cassert>
#include <cstdint>
namespace ripple {
/**
* Gets a new ptr offset by the given amount from the ptr.
*
* \note This does __not__ ensure alignemt. If the pointer needs to be aligned,
* then pass the result to `align()`.
*
* \sa align
*
* \param ptr The pointer to offset.
* \param amount The amount to offset ptr by.
* \return A new pointer at the offset location.
*/
ripple_all static inline auto
offset_ptr(const void* ptr, uint32_t amount) noexcept -> void* {
return reinterpret_cast<void*>(uintptr_t(ptr) + amount);
}
/**
* Gets a pointer with an address aligned to the goven alignment.
*
* \note In debug, this will assert at runtime if the alignemnt is not a power
* of two, in release, the behaviour is undefined.
*
* \param ptr The pointer to align.
* \param alignment The alignment to ensure.
*/
ripple_all static inline auto
align_ptr(const void* ptr, size_t alignment) noexcept -> void* {
assert(
!(alignment & (alignment - 1)) &&
"Alignment must be a power of two for linear allocation!");
return reinterpret_cast<void*>(
(uintptr_t(ptr) + alignment - 1) & ~(alignment - 1));
}
namespace gpu {
/*==--- [device to device]--------------------------------------------------==*/
/**
* Copies the given bytes of data from one device pointer to the other.
*
* \note This will block on the host until the copy is complete.
*
* \param dev_ptr_in The device pointer to copy from.
* \param dev_ptr_out The device pointer to copy to.
* \param bytes The number of bytes to copy.
* \tparam DevPtr The type of the device pointer.
*/
template <typename DevPtr>
static inline auto memcpy_device_to_device(
DevPtr* dev_ptr_out, const DevPtr* dev_ptr_in, size_t bytes) -> void {
ripple_check_cuda_result(ripple_if_cuda(
cudaMemcpy(dev_ptr_out, dev_ptr_in, bytes, cudaMemcpyDeviceToDevice)));
}
/**
* Copies given number of bytes of data from the one device pointer to the
* other device ptr, asynchronously.
*
* \note This will not block on the host, and will likely return before the
* copy is complete.
*
* \param dev_ptr_in The device pointer to copy from.
* \param dev_ptr_out The device pointer to copy to.
* \param bytes The number of bytes to copy.
* \tparam DevPtr The type of the device pointer.
*/
template <typename DevPtr>
static inline auto memcpy_device_to_device_async(
DevPtr* dev_ptr_out, const DevPtr* dev_ptr_in, size_t bytes) -> void {
ripple_check_cuda_result(ripple_if_cuda(
cudaMemcpyAsync(dev_ptr_out, dev_ptr_in, bytes, cudaMemcpyDeviceToDevice)));
}
/**
* Copies given number of bytes of data from the one device pointer to the
* other device ptr, asynchronously on the given stream.
*
* \note This will not block on the host, and will likely return before the
* copy is complete.
*
* \param dev_ptr_in The device pointer to copy from.
* \param dev_ptr_out The device pointer to copy to.
* \param bytes The number of bytes to copy.
* \param stream The stream to perform the copy on.
* \tparam DevPtr The type of the device pointer.
*/
template <typename DevPtr>
static inline auto memcpy_device_to_device_async(
DevPtr* dev_ptr_out, const DevPtr* dev_ptr_in, size_t bytes, GpuStream stream)
-> void {
ripple_check_cuda_result(ripple_if_cuda(cudaMemcpyAsync(
dev_ptr_out, dev_ptr_in, bytes, cudaMemcpyDeviceToDevice, stream)));
}
/*==--- [host to device] ---------------------------------------------------==*/
/**
* Copies the given number of bytes of data from the host pointer to the device
* pointer.
*
* \note This will block on the host until the copy completes.
*
* \param dev_ptr The device pointer to copy to.
* \param host_ptr The host pointer to copy from.
* \param bytes The number of bytes to copy.
* \tparam DevPtr The type of the device pointer.
* \tparam HostPtr The type of the host pointer.
*/
template <typename DevPtr, typename HostPtr>
static inline auto
memcpy_host_to_device(DevPtr* dev_ptr, const HostPtr* host_ptr, size_t bytes)
-> void {
ripple_check_cuda_result(ripple_if_cuda(
cudaMemcpy(dev_ptr, host_ptr, bytes, cudaMemcpyHostToDevice)));
}
/**
* Copies the given number of bytes of data from the host pointer to the device
* pointer, asynchronously.
*
* \note This will not block on the host until the copy completes.
*
* \param dev_ptr The device pointer to copy to.
* \param host_ptr The host pointer to copy from.
* \param bytes The number of bytes to copy.
* \tparam DevPtr The type of the device pointer.
* \tparam HostPtr The type of the host pointer.
*/
template <typename DevPtr, typename HostPtr>
static inline auto memcpy_host_to_device_async(
DevPtr* dev_ptr, const HostPtr* host_ptr, size_t bytes) -> void {
ripple_check_cuda_result(ripple_if_cuda(
cudaMemcpyAsync(dev_ptr, host_ptr, bytes, cudaMemcpyHostToDevice)));
}
/**
* Copies the given number of bytes of data from the host pointer to the device
* pointer, asynchronously.
*
* \note This will not block on the host until the copy completes.
*
* \note This requires that the \p host_ptr data be page locked, which should
* have been allocated with alloc_pinned(). This overload alows the
* stream to be specified, which will allow the copy operation to be
* overlapped with operations in other streams, and possibly computation
* in the same stream, if suppored.
*
* \param dev_ptr The device pointer to copy to.
* \param host_ptr The host pointer to copy from.
* \param bytes The number of bytes to copy.
* \param stream The stream to perform the copy on.
* \tparam DevPtr The type of the device pointer.
* \tparam HostPtr The type of the host pointer.
*/
template <typename DevPtr, typename HostPtr>
static inline auto memcpy_host_to_device_async(
DevPtr* dev_ptr, const HostPtr* host_ptr, size_t bytes, GpuStream stream)
-> void {
ripple_check_cuda_result(ripple_if_cuda(
cudaMemcpyAsync(dev_ptr, host_ptr, bytes, cudaMemcpyHostToDevice, stream)));
}
/*==--- [device to host] ---------------------------------------------------==*/
/**
* Copies the given number of bytes of data from the device pointer to the
* host pointer.
*
* \note This will block on the host until the copy is complete.
*
* \param host_ptr The host pointer to copy from.
* \param dev_ptr The device pointer to copy to.
* \param bytes The number of bytes to copy.
* \tparam HostPtr The type of the host pointer.
* \tparam DevPtr The type of the device pointer.
*/
template <typename HostPtr, typename DevPtr>
static inline auto
memcpy_device_to_host(HostPtr* host_ptr, const DevPtr* dev_ptr, size_t bytes)
-> void {
ripple_check_cuda_result(ripple_if_cuda(
cudaMemcpy(host_ptr, dev_ptr, bytes, cudaMemcpyDeviceToHost)));
}
/**
* Copies the given number of bytes of data from the device pointer to the
* host pointer. asynchronously.
*
* \note This will not block on the host until the copy is complete.
*
* \param host_ptr The host pointer to copy from.
* \param dev_ptr The device pointer to copy to.
* \param bytes The number of bytes to copy.
* \tparam HostPtr The type of the host pointer.
* \tparam DevPtr The type of the device pointer.
*/
template <typename HostPtr, typename DevPtr>
static inline auto memcpy_device_to_host_async(
HostPtr* host_ptr, const DevPtr* dev_ptr, size_t bytes) -> void {
ripple_check_cuda_result(ripple_if_cuda(
cudaMemcpyAsync(host_ptr, dev_ptr, bytes, cudaMemcpyDeviceToHost)));
}
/**
* Copies the given number of bytes of data from the device pointer to the
* host pointer. asynchronously, on the given stream.
*
* \note This will not block on the host until the copy is complete.
*
* \param host_ptr The host pointer to copy from.
* \param dev_ptr The device pointer to copy to.
* \param bytes The number of bytes to copy.
* \param stream The stream to perform the copy on.
* \tparam HostPtr The type of the host pointer.
* \tparam DevPtr The type of the device pointer.
*/
template <typename HostPtr, typename DevPtr>
static inline auto memcpy_device_to_host_async(
HostPtr* host_ptr,
const DevPtr* dev_ptr,
size_t bytes,
const GpuStream& stream) -> void {
ripple_check_cuda_result(ripple_if_cuda(
cudaMemcpyAsync(host_ptr, dev_ptr, bytes, cudaMemcpyDeviceToHost, stream)));
}
/*==--- [allocation device] ------------------------------------------------==*/
/**
* Allocates the given number of bytes of memory on the device at the location
* pointed to by the pointer.
* \param dev_ptr The device pointer to allocate memory for.
* \param bytes The number of bytes to allocate.
* \tparam Ptr The type of the pointer.
*/
template <typename Ptr>
static inline auto allocate_device(Ptr** dev_ptr, size_t bytes) -> void {
ripple_check_cuda_result(ripple_if_cuda(cudaMalloc((void**)dev_ptr, bytes)));
}
/**
* Frees the pointer.
* \param ptr The pointer to free.
* \tparam Ptr The type of the pointer to free.
*/
template <typename Ptr>
static inline auto free_device(Ptr* ptr) -> void {
ripple_check_cuda_result(ripple_if_cuda(cudaFree(ptr)));
}
} // namespace gpu
namespace cpu {
/**
* Allocates the given number of bytes of page locked (pinned) memory at the
* location of the host pointer.
*
* \todo Add support for pinned allocation if no cuda.
*
* \param host_ptr The host pointer for the allocated memory.
* \param bytes The number of bytes to allocate.
* \tparam Ptr The type of the pointer.
*/
template <typename Ptr>
static inline auto allocate_host_pinned(Ptr** host_ptr, size_t bytes) -> void {
ripple_check_cuda_result(ripple_if_cuda(
cudaHostAlloc((void**)host_ptr, bytes, cudaHostAllocPortable)));
}
/**
* Frees the pointer which was allocated as pinned memory.
*
* \param ptr The pointer to free.
* \tparam Ptr The type of the pointer to free.
*/
template <typename Ptr>
static inline auto free_host_pinned(Ptr* ptr) -> void {
ripple_check_cuda_result(ripple_if_cuda(cudaFreeHost(ptr)));
}
} // namespace cpu
} // namespace ripple
#endif // RIPPLE_UTILITY_MEMORY_HPP
| 34.983923
| 80
| 0.688879
|
robclu
|
2603f24fa10bb207b89b226b36885e6a30549682
| 5,911
|
hpp
|
C++
|
include/graphics.hpp
|
a276me/MilSim
|
b3ba8ef8cc46b6ae9cc7befece6cd00b016038ea
|
[
"MIT"
] | null | null | null |
include/graphics.hpp
|
a276me/MilSim
|
b3ba8ef8cc46b6ae9cc7befece6cd00b016038ea
|
[
"MIT"
] | null | null | null |
include/graphics.hpp
|
a276me/MilSim
|
b3ba8ef8cc46b6ae9cc7befece6cd00b016038ea
|
[
"MIT"
] | null | null | null |
#pragma once
#include "raylib.h"
#include "main.hpp"
#include "Division.hpp"
const int SCREEN_WIDTH = 1280*1.5;
const int SCREEN_HEIGHT = 960*1.2;
Texture2D natoTest;
Texture2D natoInf;
Texture2D natoArmor;
Texture2D natoMechInf;
Texture2D hostileInf;
Texture2D hostileArmor;
Texture2D hostileMechInf;
void initRL();
void endRL();
void drawUI();
void drawDivision();
void drawCamera();
void drawScreen();
void loadResources();
void updateVariables();
Camera2D camera = { 0 };
void updateVariables(){
int t = 1;
if(IsKeyDown(KEY_LEFT_SHIFT)) t = 3;
int s = 10;
if (IsKeyDown(KEY_A)) camera.target.x -= t*s;
else if (IsKeyDown(KEY_D)) camera.target.x += t*s;
if (IsKeyDown(KEY_W)) camera.target.y -= t*s;
else if (IsKeyDown(KEY_S)) camera.target.y += t*s;
// Camera zoom controls
camera.zoom += ((float)GetMouseWheelMove()*t*0.02f);
if (camera.zoom > 3.f) camera.zoom = 3.f;
else if (camera.zoom < .01f) camera.zoom = .01f;
// Camera reset (zoom and rotation)
if (IsKeyPressed(KEY_R))
{
camera.zoom = 1.0f;
camera.rotation = 0.0f;
camera.target = (Vector2){0,0};
}
}
void loadResources(){
natoTest = LoadTexture("nato.png");
natoInf = LoadTexture("./assets/NATO/friendly_infantry.png");
natoMechInf = LoadTexture("./assets/NATO/friendly_mech_infantry.png");
natoArmor = LoadTexture("./assets/NATO/friendly_armor.png");
hostileInf = LoadTexture("./assets/HOSTILE/hostile_inf.png");
hostileMechInf = LoadTexture("./assets/HOSTILE/hostile_mech_inf.png");
hostileArmor = LoadTexture("./assets/HOSTILE/hostile_armor.png");
}
void initRL(){
InitWindow(SCREEN_WIDTH, SCREEN_HEIGHT, "raylib [core] example - basic window");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
loadResources();
camera.target = (Vector2){ 0,0 };
camera.offset = (Vector2){ SCREEN_WIDTH/2.0f, SCREEN_HEIGHT/2.0f };
camera.rotation = 0.0f;
camera.zoom = 1.0f;
MaximizeWindow();
}
void endRL(){
UnloadTexture(natoTest);
UnloadTexture(natoInf);
UnloadTexture(natoArmor);
UnloadTexture(natoMechInf);
UnloadTexture(hostileInf);
UnloadTexture(hostileArmor);
UnloadTexture(hostileMechInf);
CloseWindow();
}
void drawUI(){
ClearBackground((Color){ 245, 245, 245, 255 });
DrawFPS(10,10);
}
void drawDivision(){
float s = 0.7f;
float ss = 100.f;
for(int i=0; i<divisions.size(); i++){
DrawCircleV((Vector2){divisions[i].position.x*ss, -divisions[i].position.y*ss}, ss*divisions[i].getBD()/2.f, (Color){ 100, 100, 100, 100 });
if(divisions[i].moving) DrawLineEx((Vector2){divisions[i].position.x*ss,-divisions[i].position.y*ss}, (Vector2){divisions[i].getTarget().x*ss, -divisions[i].getTarget().y*ss}, 20, (Color){0,0,0,255});
}
for(int i=0; i<divisions.size(); i++){
if(divisions[i].team == 0){
if(divisions[i].getType() == INFANTRY_DIV){
DrawTextureEx(natoInf, (Vector2){ss*divisions[i].getPos().x-(natoInf.width/2)*s,ss*-divisions[i].getPos().y-(natoInf.height/2)*s}, 0, s,(Color){ 255, 255, 255, 255 });
} else if(divisions[i].getType() == ARMORED_DIV){
DrawTextureEx(natoArmor, (Vector2){ss*divisions[i].getPos().x-(natoArmor.width/2)*s,ss*-divisions[i].getPos().y-(natoArmor.height/2)*s}, 0, s,(Color){ 255, 255, 255, 255 });
} else if(divisions[i].getType() == MECH_INFANTRY_DIV){
DrawTextureEx(natoMechInf, (Vector2){ss*divisions[i].getPos().x-(natoMechInf.width/2)*s,ss*-divisions[i].getPos().y-(natoMechInf.height/2)*s}, 0, s,(Color){ 255, 255, 255, 255 });
}
}else if(divisions[i].team == 1){
if(divisions[i].getType() == INFANTRY_DIV){
DrawTextureEx(hostileInf, (Vector2){ss*divisions[i].getPos().x-(hostileInf.width/2)*s,ss*-divisions[i].getPos().y-(hostileInf.height/2)*s}, 0, s,(Color){ 255, 255, 255, 255 });
} else if(divisions[i].getType() == ARMORED_DIV){
DrawTextureEx(hostileArmor, (Vector2){ss*divisions[i].getPos().x-(hostileArmor.width/2)*s,ss*-divisions[i].getPos().y-(hostileArmor.height/2)*s}, 0, s,(Color){ 255, 255, 255, 255 });
} else if(divisions[i].getType() == MECH_INFANTRY_DIV){
DrawTextureEx(hostileMechInf, (Vector2){ss*divisions[i].getPos().x-(hostileMechInf.width/2)*s,ss*-divisions[i].getPos().y-(hostileMechInf.height/2)*s}, 0, s,(Color){ 255, 255, 255, 255 });
}
}
DrawText(divisions[i].getName().c_str(),ss*divisions[i].getPos().x-(MeasureText(divisions[i].getName().c_str(), 200)/2), ss*-divisions[i].getPos().y-(hostileInf.height/2)*s-220,200,(Color){ 0, 0, 0, 255 });
DrawText(std::to_string((int)divisions[i].getOrg()).c_str(),ss*divisions[i].getPos().x+(natoInf.width/2)*s+20, ss*-divisions[i].getPos().y-210,200,(Color){ 0, 0, 0, 255 });
DrawText(std::to_string((int)divisions[i].getStrength()).c_str(),ss*divisions[i].getPos().x+(natoInf.width/2)*s+20, ss*-divisions[i].getPos().y,200,(Color){ 0, 0, 0, 255 });
DrawText(std::to_string((int)divisions[i].getBV()).c_str(),ss*divisions[i].getPos().x-(natoInf.width/2)*s-MeasureText(std::to_string((int)divisions[i].getBV()).c_str(),200)-30, ss*-divisions[i].getPos().y-200,200,(Color){ 0, 0, 0, 255 });
DrawText(std::to_string((int)divisions[i].getDV()).c_str(),ss*divisions[i].getPos().x-(natoInf.width/2)*s-MeasureText(std::to_string((int)divisions[i].getDV()).c_str(),200)-30, ss*-divisions[i].getPos().y+20,200,(Color){ 0, 0, 0, 255 });
}
}
void drawCamera(){
updateVariables();
BeginMode2D(camera);
drawDivision();
EndMode2D();
}
void drawScreen(){
BeginDrawing();
drawUI();
drawCamera();
EndDrawing();
}
| 34.366279
| 246
| 0.630012
|
a276me
|
26060c9cd453f6eb01ded7d869aafb8e9c4fb67d
| 997
|
hpp
|
C++
|
RayTracer/core/source/RTweekend.hpp
|
ZFhuang/AmbiRenderer
|
d223e1c4d947872c9011c1cba6a8f498ebbaf3b7
|
[
"Apache-2.0"
] | null | null | null |
RayTracer/core/source/RTweekend.hpp
|
ZFhuang/AmbiRenderer
|
d223e1c4d947872c9011c1cba6a8f498ebbaf3b7
|
[
"Apache-2.0"
] | null | null | null |
RayTracer/core/source/RTweekend.hpp
|
ZFhuang/AmbiRenderer
|
d223e1c4d947872c9011c1cba6a8f498ebbaf3b7
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#include <cmath>
#include <limits>
#include <memory>
#include <random>
// 保存Ray Tracing in One Weekend项目所需的基本常量和函数
using std::shared_ptr;
using std::make_shared;
using std::sqrt;
const double infinity = std::numeric_limits<double>::infinity();
const double pi = 3.1415926535897932385;
// 角度转弧度
inline double degrees_to_radians(double degrees) {
return degrees * pi / 180.0;
}
// 生成范围内的double均匀分布随机数
inline double random_double(double min = 0.0, double max = 1.0) {
// 生成种子
static std::random_device rd;
// 调用生成器
static std::mt19937 generator(rd());
// 注意这个该死的生成器只能生成非负数
static std::uniform_real_distribution<double> distribution(0.0, 1.0);
// 移动分布范围
return min + (max - min) * distribution(generator);
}
inline int random_int(int min = 0, int max = 1) {
return static_cast<int>(random_double(min, max + 1));
}
// 按照min和max对值进行截断
inline double clamp(double x, double min, double max) {
if (x < min) {
return min;
}
if (x > max) {
return max;
}
return x;
}
| 20.346939
| 70
| 0.706118
|
ZFhuang
|
2609c25feca6969e8f9c31b3be4f6301848dc8dc
| 3,645
|
cpp
|
C++
|
2017-09-10-practice/E.cpp
|
tangjz/Three-Investigators
|
46dc9b2f0fbb4fe89b075a81feaacc33feeb1b52
|
[
"MIT"
] | 3
|
2018-04-02T06:00:51.000Z
|
2018-05-29T04:46:29.000Z
|
2017-09-10-practice/E.cpp
|
tangjz/Three-Investigators
|
46dc9b2f0fbb4fe89b075a81feaacc33feeb1b52
|
[
"MIT"
] | 2
|
2018-03-31T17:54:30.000Z
|
2018-05-02T11:31:06.000Z
|
2017-09-10-practice/E.cpp
|
tangjz/Three-Investigators
|
46dc9b2f0fbb4fe89b075a81feaacc33feeb1b52
|
[
"MIT"
] | 2
|
2018-10-07T00:08:06.000Z
|
2021-06-28T11:02:59.000Z
|
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef long double DB;
const int maxn = 500001, INF = 0x3f3f3f3f;
int rad, n, totL, totR;
struct Query {
int typ, x, y;
} que[maxn];
struct Fraction {
LL x, y;
Fraction() {}
Fraction(LL _x, LL _y) { // _y > 0
LL r = __gcd(abs(_x), _y);
x = _x / r;
y = _y / r;
}
bool operator == (Fraction const &t) const {
return x == t.x && y == t.y;
}
bool operator < (Fraction const &t) const {
return (DB)x * t.y < (DB)t.x * y;
}
} pL[maxn], pR[maxn], seqL[maxn], seqR[maxn];
int cnt, idx[maxn], ord[maxn], pos[maxn], seg[maxn << 1 | 1];
inline int seg_idx(int L, int R) {
return (L + R) | (L < R);
}
void seg_upd(int L, int R, int x, int v) {
int rt = seg_idx(L, R);
if(L == R) {
seg[rt] = v;
return;
}
int M = (L + R) >> 1, lch = seg_idx(L, M), rch = seg_idx(M + 1, R);
if(x <= M)
seg_upd(L, M, x, v);
else
seg_upd(M + 1, R, x, v);
seg[rt] = min(seg[lch], seg[rch]);
}
int seg_que(int L, int R, int l, int r) {
if(l <= L && R <= r)
return seg[seg_idx(L, R)];
int M = (L + R) >> 1, ret = INF;
if(l <= M)
ret = min(ret, seg_que(L, M, l, r));
if(M < r)
ret = min(ret, seg_que(M + 1, R, l, r));
return ret;
}
inline int sgn(int x) {
return (x > 0) - (x < 0);
}
inline LL sqr(int x) {
return (LL)x * x;
}
bool cmp(int const &u, int const &v) {
return que[u].x < que[v].x;
}
int main() {
scanf("%d%d", &rad, &n);
for(int i = 1; i <= n; ++i) {
int &typ = que[i].typ, &x = que[i].x, &y = que[i].y;
scanf("%d%d", &typ, &x);
if(typ != 2)
scanf("%d", &y);
if(typ != 1)
continue;
LL A = sqr(rad + x), B = sqr(rad - x), C = sqr(y);
seqL[++totL] = pL[i] = Fraction(sgn(rad + x) * A, A + C);
seqR[++totR] = pR[i] = Fraction(sgn(rad - x) * B, B + C);
}
sort(seqL + 1, seqL + totL + 1);
totL = unique(seqL + 1, seqL + totL + 1) - seqL - 1;
sort(seqR + 1, seqR + totR + 1);
totR = unique(seqR + 1, seqR + totR + 1) - seqR - 1;
for(int i = 1; i <= n; ++i) {
int &typ = que[i].typ, &x = que[i].x, &y = que[i].y;
if(typ == 1) {
int px = x, py = y;
x = lower_bound(seqL + 1, seqL + totL + 1, pL[i]) - seqL;
y = lower_bound(seqR + 1, seqR + totR + 1, pR[i]) - seqR;
pL[i] = px >= -rad ? Fraction(sqr(px + rad) - sqr(py), sqr(px + rad) + sqr(py)) : Fraction(-1, 1);
pR[i] = px <= rad ? Fraction(sqr(py) - sqr(px - rad), sqr(px - rad) + sqr(py)) : Fraction(1, 1);
ord[++cnt] = i;
idx[cnt] = i;
}
}
sort(ord + 1, ord + cnt + 1, cmp);
for(int i = 1; i <= cnt; ++i)
pos[ord[i]] = i;
static bool vis[maxn] = {};
memset(seg + 1, 0x3f, (cnt << 1) * sizeof(int));
for(int i = 1; i <= n; ++i) {
int &typ = que[i].typ, &x = que[i].x, &y = que[i].y;
if(typ == 1) {
vis[i] = 1;
// printf("ins %d: %d %d\n", pos[i], que[i].x, que[i].y);
seg_upd(1, cnt, pos[i], que[i].y);
} else if(typ == 2) {
x = idx[x];
assert(vis[x] == 1);
// printf("rem %d: %d %d\n", pos[x], que[x].x, que[x].y);
seg_upd(1, cnt, pos[x], INF);
vis[x] = 0;
} else {
x = idx[x], y = idx[y];
assert(vis[x] == 1 && vis[y] == 1);
// printf("ask (%d, %d) (%d, %d)\n", que[x].x, que[x].y, que[y].x, que[y].y);
if(min(pR[x], pR[y]) < max(pL[x], pL[y])) {
puts("NO");
continue;
}
int A = max(que[x].x, que[y].x), B = max(que[x].y, que[y].y);
seg_upd(1, cnt, pos[x], INF);
seg_upd(1, cnt, pos[y], INF);
que[0] = (Query){0, A};
int id = upper_bound(ord + 1, ord + cnt + 1, 0, cmp) - ord - 1;
// printf("query [%d, %d]\n", 1, id);
puts(seg_que(1, cnt, 1, id) > B ? "YES" : "NO");
seg_upd(1, cnt, pos[x], que[x].y);
seg_upd(1, cnt, pos[y], que[y].y);
}
}
return 0;
}
| 28.476563
| 101
| 0.494925
|
tangjz
|
260e864a1f93c48554bc7ee15e6a536d28c1bc43
| 5,340
|
hpp
|
C++
|
include/GTGE/Editor/ParticleEditor/ParticleEditor.hpp
|
mackron/GTGameEngine
|
380d1e01774fe6bc2940979e4e5983deef0bf082
|
[
"BSD-3-Clause"
] | 31
|
2015-03-19T08:44:48.000Z
|
2021-12-15T20:52:31.000Z
|
include/GTGE/Editor/ParticleEditor/ParticleEditor.hpp
|
mackron/GTGameEngine
|
380d1e01774fe6bc2940979e4e5983deef0bf082
|
[
"BSD-3-Clause"
] | 19
|
2015-07-09T09:02:44.000Z
|
2016-06-09T03:51:03.000Z
|
include/GTGE/Editor/ParticleEditor/ParticleEditor.hpp
|
mackron/GTGameEngine
|
380d1e01774fe6bc2940979e4e5983deef0bf082
|
[
"BSD-3-Clause"
] | 3
|
2017-10-04T23:38:18.000Z
|
2022-03-07T08:27:13.000Z
|
// Copyright (C) 2011 - 2014 David Reid. See included LICENCE.
#ifndef GT_ParticleEditor
#define GT_ParticleEditor
#include "../SubEditor.hpp"
#include "../Editor3DViewportEventHandler.hpp"
#include "../EditorGrid.hpp"
#include "../EditorAxisArrows.hpp"
#include "../../ParticleSystem.hpp"
#include "../../Scene.hpp"
namespace GT
{
/// Class representing the particle system editor.
class ParticleEditor : public SubEditor
{
public:
/// Constructor.
ParticleEditor(Editor &ownerEditor, const char* absolutePath, const char* relativePath);
/// Destructor.
~ParticleEditor();
/// Resets the camera.
void ResetCamera();
/// Retrieves a reference tothe camera scene node.
SceneNode & GetCameraSceneNode() { return this->camera; }
const SceneNode & GetCameraSceneNode() const { return this->camera; }
/// Retrieves a reference to the particle system definition being editted.
ParticleSystemDefinition & GetParticleSystemDefinition();
/// Refreshes the viewport so that it shows the current state of the particle system being editted.
///
/// @remarks
/// This should be called whenever the particle definition has been modified.
void RefreshViewport();
/// Sets the orientation of the preview particle system.
void SetOrientation(const glm::quat &orientation);
/// Shows the grid.
void ShowGrid();
/// Hides the grid.
void HideGrid();
/// Determines whether or not the grid is showing.
bool IsShowingGrid() const;
/// Shows the axis arrows.
void ShowAxisArrows();
/// Hides the axis arrows.
void HideAxisArrows();
/// Determines whether or not the axis arrows is showing.
bool IsShowingAxisArrows() const;
///////////////////////////////////////////////////
// GUI Events.
//
// These events are received in response to certain GUI events.
/// Called when the main viewport is resized.
void OnViewportSize();
///////////////////////////////////////////////////
// Virtual Methods.
/// SubEditor::GetMainElement()
GUIElement* GetMainElement() { return this->mainElement; }
const GUIElement* GetMainElement() const { return this->mainElement; }
/// SubEditor::Show()
void Show();
/// SubEditor::Hide()
void Hide();
/// SubEditor::Save()
bool Save();
/// SubEditor::Update()
void OnUpdate(double deltaTimeInSeconds);
/// SubEditor::OnFileUpdate()
void OnFileUpdate(const char* absolutePath);
private:
private:
/// The particle system definition that is being editted. This is not instantiated by the particle system library.
ParticleSystemDefinition particleSystemDefinition;
/// The particle system to use in the preview window.
ParticleSystem particleSystem;
/// The scene for the preview window.
Scene scene;
/// The scene node acting as the camera for the preview window viewport.
SceneNode camera;
/// The scene node containing the particle system.
SceneNode particleNode;
/// The main container element.
GUIElement* mainElement;
/// The viewport element.
GUIElement* viewportElement;
/// The viewport event handler to we can detect when it is resized.
struct ViewportEventHandler : public Editor3DViewportEventHandler
{
/// Constructor.
ViewportEventHandler(ParticleEditor &ownerIn, Context &context, SceneViewport &viewport)
: Editor3DViewportEventHandler(context, viewport), owner(ownerIn)
{
}
/// Called after the element has been resized.
void OnSize(GUIElement &element)
{
Editor3DViewportEventHandler::OnSize(element);
owner.OnViewportSize();
}
/// The owner of the viewport.
ParticleEditor &owner;
}viewportEventHandler;
float cameraXRotation; ///< The camera's current X rotation.
float cameraYRotation; ///< The camera's current Y rotation.
/// The grid.
EditorGrid grid;
/// The axis arrows.
EditorAxisArrows axisArrows;
/// Keeps track of whether or not the editor is in the middle of saving. We use this in determining whether or not the settings should be
/// set when it detects a modification to the file on disk.
bool isSaving;
/// Keeps track of whether or not we are handling a reload. We use this in keeping track of whether or not to mark the file as modified
/// when the settings are changed.
bool isReloading;
/// Keeps track of whether or not the grid is visible.
bool isShowingGrid;
/// Keeps track of whether or not the axis arrows are visible.
bool isShowingAxisArrows;
private: // No copying.
ParticleEditor(const ParticleEditor &);
ParticleEditor & operator=(const ParticleEditor &);
};
}
#endif
| 27.525773
| 145
| 0.603933
|
mackron
|
260fbcac89d9c171b877e48c878a90c4994a737c
| 1,586
|
hpp
|
C++
|
legacy/galaxy/meta/UniqueId.hpp
|
reworks/rework
|
90508252c9a4c77e45a38e7ce63cfd99f533f42b
|
[
"Apache-2.0"
] | 6
|
2018-07-21T20:37:01.000Z
|
2018-10-31T01:49:35.000Z
|
legacy/galaxy/meta/UniqueId.hpp
|
reworks/rework
|
90508252c9a4c77e45a38e7ce63cfd99f533f42b
|
[
"Apache-2.0"
] | null | null | null |
legacy/galaxy/meta/UniqueId.hpp
|
reworks/rework
|
90508252c9a4c77e45a38e7ce63cfd99f533f42b
|
[
"Apache-2.0"
] | null | null | null |
///
/// UniqueId.hpp
/// galaxy
///
/// Refer to LICENSE.txt for more details.
///
#ifndef GALAXY_META_UNIQUEID_HPP_
#define GALAXY_META_UNIQUEID_HPP_
#include "galaxy/meta/Concepts.hpp"
namespace galaxy
{
namespace meta
{
///
/// Generates a unique id for a type for each type of specialization.
/// And the id is kept as a compile time constant.
///
template<is_class Specialization>
class UniqueId final
{
public:
///
/// Destructor.
///
~UniqueId() noexcept = default;
///
/// Use this function to retrieve the ID.
/// Will generate a new id if it is called for the first time.
///
/// \return Unique ID for the specialization of that type.
///
template<typename Type>
[[nodiscard]] static std::size_t get() noexcept;
private:
///
/// Constructor.
///
UniqueId() noexcept = default;
///
/// Copy constructor.
///
UniqueId(const UniqueId&) = delete;
///
/// Move constructor.
///
UniqueId(UniqueId&&) = delete;
///
/// Copy assignment operator.
///
UniqueId& operator=(const UniqueId&) = delete;
///
/// Move assignment operator.
///
UniqueId& operator=(UniqueId&&) = delete;
private:
///
/// Internal counter to keep track of allocated ids.
///
inline static std::size_t s_counter = 0;
};
template<is_class Specialization>
template<typename Type>
[[nodiscard]] inline std::size_t UniqueId<Specialization>::get() noexcept
{
static std::size_t id = s_counter++;
return id;
}
} // namespace meta
} // namespace galaxy
#endif
| 19.341463
| 75
| 0.628625
|
reworks
|
2613106580d834e6f6c23229ec8e14b28bab861e
| 1,837
|
cpp
|
C++
|
cpp/Maya Calendar/Maya Calendar.cpp
|
xuzishan/Algorithm-learning-through-Problems
|
4aee347af6fd7fd935838e1cbea57c197e88705c
|
[
"MIT"
] | 27
|
2016-11-04T09:18:25.000Z
|
2022-02-12T12:34:01.000Z
|
cpp/Maya Calendar/Maya Calendar.cpp
|
Der1128/Algorithm-learning-through-Problems
|
4aee347af6fd7fd935838e1cbea57c197e88705c
|
[
"MIT"
] | 1
|
2016-11-05T02:30:24.000Z
|
2016-11-16T10:21:09.000Z
|
cpp/Maya Calendar/Maya Calendar.cpp
|
Der1128/Algorithm-learning-through-Problems
|
4aee347af6fd7fd935838e1cbea57c197e88705c
|
[
"MIT"
] | 20
|
2016-11-04T10:26:02.000Z
|
2021-09-25T05:41:21.000Z
|
//
// Maya Calendar.cpp
// laboratory
//
// Created by 徐子珊 on 16/4/4.
// Copyright (c) 2016年 xu_zishan. All rights reserved.
//
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
#include <hash_map>
using namespace std;
pair<string, int> a[]={make_pair("pop", 0), make_pair("no", 1), make_pair("zip", 2), make_pair("zotz", 3),
make_pair("tzec", 4), make_pair("xul", 5), make_pair("yoxkin", 6), make_pair("mol", 7),
make_pair("chen", 8), make_pair("yax", 9), make_pair("zac", 10), make_pair("ceh", 11),
make_pair("mac", 12), make_pair("kankin", 13), make_pair("muan", 14), make_pair("pax", 15),
make_pair("koyab", 16), make_pair("cumhu", 17), make_pair("uayet", 18)};
hash_map<string, int> Haab(a, a+19);
string Tzolkin[]={"imix", "ik", "akbal", "kan", "chicchan", "cimi", "manik", "lamat", "muluk", "ok",
"chuen", "eb", "ben", "ix", "mem", "cib", "caban", "eznab", "canac", "ahau"};
string mayaCalendar(string &haab){
istringstream s(haab);
int NumberOfTheDay, Year;
string Month;
char dot;
s>>NumberOfTheDay>>dot>>Month>>Year;
int days=365*Year+20*Haab[Month]+NumberOfTheDay;
Year=days/260;
int r=days%260;
int Number=(r%13)+1;
string NameOfTheDay=Tzolkin[r%20];
ostringstream os;
os<<Number<<" "<<NameOfTheDay<<" "<<Year;
return os.str();
}
int main(){
ifstream inputdata("Maya Calendar/inputdata.txt");
ofstream outputdata("Maya Calendar/outputdata.txt");
int n;
inputdata>>n;
outputdata<<n<<endl;
cout<<n<<endl;
string haab;
getline(inputdata, haab);
for(int i=0; i<n; i++){
getline(inputdata, haab);
string tzolkin=mayaCalendar(haab);
outputdata<<tzolkin<<endl;
cout<<tzolkin<<endl;
}
inputdata.close();
outputdata.close();
return 0;
}
| 32.22807
| 107
| 0.62221
|
xuzishan
|
2622eab5a23a648711817362a3f70a54c2c7b51c
| 10,696
|
hpp
|
C++
|
src/core/ArrayTraits.hpp
|
gyzhangqm/overkit-1
|
490aa77a79bd9708d7f2af0f3069b86545a2cebc
|
[
"MIT"
] | null | null | null |
src/core/ArrayTraits.hpp
|
gyzhangqm/overkit-1
|
490aa77a79bd9708d7f2af0f3069b86545a2cebc
|
[
"MIT"
] | null | null | null |
src/core/ArrayTraits.hpp
|
gyzhangqm/overkit-1
|
490aa77a79bd9708d7f2af0f3069b86545a2cebc
|
[
"MIT"
] | 1
|
2021-07-21T06:48:19.000Z
|
2021-07-21T06:48:19.000Z
|
// Copyright (c) 2020 Matthew J. Smith and Overkit contributors
// License: MIT (http://opensource.org/licenses/MIT)
#ifndef OVK_CORE_ARRAY_TRAITS_HPP_INCLUDED
#define OVK_CORE_ARRAY_TRAITS_HPP_INCLUDED
#include <ovk/core/ArrayTraitsBase.hpp>
#include <ovk/core/Elem.hpp>
#include <ovk/core/Global.hpp>
#include <ovk/core/IntegerSequence.hpp>
#include <ovk/core/Interval.hpp>
#include <ovk/core/IteratorTraits.hpp>
#include <ovk/core/Requires.hpp>
#include <ovk/core/TypeTraits.hpp>
#include <array>
#include <cstddef>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
namespace ovk {
// C-style array
template <typename T> struct array_traits<T, OVK_SPECIALIZATION_REQUIRES(std::is_array<T>::value)> {
using value_type = typename std::remove_all_extents<T>::type;
static constexpr int Rank = std::rank<T>::value;
static constexpr array_layout Layout = array_layout::ROW_MAJOR;
template <int> static constexpr long long ExtentBegin() { return 0; }
template <int iDim> static constexpr long long ExtentEnd() { return std::extent<T,iDim>::value; }
// Not sure if there's a better way to do this that works for general multidimensional arrays
static const value_type *Data(const T &Array) {
return reinterpret_cast<const value_type *>(&Array[0]);
}
static value_type *Data(T &Array) {
return reinterpret_cast<value_type *>(&Array[0]);
}
};
// std::array
template <typename T, std::size_t N> struct array_traits<std::array<T,N>> {
using value_type = T;
static constexpr int Rank = 1;
static constexpr array_layout Layout = array_layout::ROW_MAJOR;
template <int> static constexpr long long ExtentBegin() { return 0; }
template <int> static constexpr long long ExtentEnd() { return N; }
static const T *Data(const std::array<T,N> &Array) { return Array.data(); }
static T *Data(std::array<T,N> &Array) { return Array.data(); }
};
// std::vector
template <typename T, typename Allocator> struct array_traits<std::vector<T, Allocator>> {
using value_type = T;
static constexpr int Rank = 1;
static constexpr array_layout Layout = array_layout::ROW_MAJOR;
template <int> static long long ExtentBegin(const std::vector<T, Allocator> &) { return 0; }
template <int> static long long ExtentEnd(const std::vector<T, Allocator> &Vec) {
return Vec.size();
}
static const T *Data(const std::vector<T, Allocator> &Vec) { return Vec.data(); }
static T *Data(std::vector<T, Allocator> &Vec) { return Vec.data(); }
};
// std::basic_string
template <typename CharT, typename Traits, typename Allocator> struct array_traits<
std::basic_string<CharT, Traits, Allocator>> {
using value_type = CharT;
static constexpr int Rank = 1;
static constexpr array_layout Layout = array_layout::ROW_MAJOR;
template <int> static long long ExtentBegin(const std::basic_string<CharT, Traits, Allocator> &) {
return 0;
}
template <int> static long long ExtentEnd(const std::basic_string<CharT, Traits, Allocator>
&String) {
return String.length();
}
static const CharT *Data(const std::basic_string<CharT, Traits, Allocator> &String) {
return String.c_str();
}
// No non-const Data access
};
namespace core {
namespace array_value_type_internal {
template <typename T, typename=void> struct helper;
template <typename T> struct helper<T, OVK_SPECIALIZATION_REQUIRES(IsArray<T>())> {
using type = typename array_traits<T>::value_type;
};
template <typename T> struct helper<T, OVK_SPECIALIZATION_REQUIRES(!IsArray<T>())> {
using type = std::false_type;
};
}
template <typename T> using array_value_type = typename array_value_type_internal::helper<T>::type;
template <typename T, OVK_FUNCTION_REQUIRES(IsArray<T>())> constexpr array_layout ArrayLayout() {
return array_traits<T>::Layout;
}
template <typename T, OVK_FUNCTION_REQUIRES(!IsArray<T>())> constexpr array_layout ArrayLayout() {
return array_layout::ROW_MAJOR;
}
template <typename T, int Rank, array_layout Layout, OVK_FUNCTION_REQUIRES(IsArray<T>())>
constexpr bool ArrayHasFootprint() {
return ArrayRank<T>() == Rank && (Rank == 1 || ArrayLayout<T>() == Layout);
}
template <typename T, int Rank, array_layout Layout, OVK_FUNCTION_REQUIRES(!IsArray<T>())>
constexpr bool ArrayHasFootprint() {
return false;
}
template <typename T, typename U, OVK_FUNCTION_REQUIRES(IsArray<T>() && IsArray<U>())>
constexpr bool ArraysAreCongruent() {
return ArrayRank<T>() == ArrayRank<U>() && (ArrayRank<T>() == 1 || ArrayLayout<T>() ==
ArrayLayout<U>());
}
template <typename T, typename U, OVK_FUNCTION_REQUIRES(!IsArray<T>() || !IsArray<U>())>
constexpr bool ArraysAreCongruent() {
return false;
}
namespace array_extents_internal {
template <typename TupleElementType, typename ArrayType, std::size_t... Indices> constexpr
interval<TupleElementType,ArrayRank<ArrayType>()> StaticHelper(core::index_sequence<Indices...>) {
return {
{TupleElementType(array_traits<ArrayType>::template ExtentBegin<Indices>())...},
{TupleElementType(array_traits<ArrayType>::template ExtentEnd<Indices>())...}
};
}
template <typename TupleElementType, typename ArrayType, std::size_t... Indices> interval<
TupleElementType,ArrayRank<ArrayType>()> RuntimeHelper(core::index_sequence<Indices...>, const
ArrayType &Array) {
return {
{TupleElementType(array_traits<ArrayType>::template ExtentBegin<Indices>(Array))...},
{TupleElementType(array_traits<ArrayType>::template ExtentEnd<Indices>(Array))...}
};
}
}
template <typename TupleElementType=long long, typename ArrayType, OVK_FUNCTION_REQUIRES(IsArray<
ArrayType>() && ArrayHasStaticExtents<ArrayType>())> constexpr interval<TupleElementType,
ArrayRank<ArrayType>()> ArrayExtents(const ArrayType &) {
return array_extents_internal::StaticHelper<TupleElementType, ArrayType>(
core::index_sequence_of_size<ArrayRank<ArrayType>()>());
}
template <typename TupleElementType=long long, typename ArrayType, OVK_FUNCTION_REQUIRES(IsArray<
ArrayType>() && ArrayHasRuntimeExtents<ArrayType>())> interval<TupleElementType,ArrayRank<
ArrayType>()> ArrayExtents(const ArrayType &Array) {
return array_extents_internal::RuntimeHelper<TupleElementType, ArrayType>(
core::index_sequence_of_size<ArrayRank<ArrayType>()>(), Array);
}
namespace array_size_internal {
template <typename TupleElementType, typename ArrayType, std::size_t... Indices> constexpr
elem<TupleElementType,ArrayRank<ArrayType>()> StaticHelper(core::index_sequence<Indices...>) {
return {TupleElementType(array_traits<ArrayType>::template ExtentEnd<Indices>() -
array_traits<ArrayType>::template ExtentBegin<Indices>())...};
}
template <typename TupleElementType, typename ArrayType, std::size_t... Indices> elem<
TupleElementType,ArrayRank<ArrayType>()> RuntimeHelper(core::index_sequence<Indices...>, const
ArrayType &Array) {
return {TupleElementType(array_traits<ArrayType>::template ExtentEnd<Indices>(Array) -
array_traits<ArrayType>::template ExtentBegin<Indices>(Array))...};
}
}
template <typename TupleElementType=long long, typename ArrayType, OVK_FUNCTION_REQUIRES(IsArray<
ArrayType>() && ArrayHasStaticExtents<ArrayType>())> constexpr elem<TupleElementType,ArrayRank<
ArrayType>()> ArraySize(const ArrayType &) {
return array_size_internal::StaticHelper<TupleElementType, ArrayType>(
core::index_sequence_of_size<ArrayRank<ArrayType>()>());
}
template <typename TupleElementType=long long, typename ArrayType, OVK_FUNCTION_REQUIRES(IsArray<
ArrayType>() && ArrayHasRuntimeExtents<ArrayType>())> elem<TupleElementType,ArrayRank<ArrayType>()
> ArraySize(const ArrayType &Array) {
return array_size_internal::RuntimeHelper<TupleElementType, ArrayType>(
core::index_sequence_of_size<ArrayRank<ArrayType>()>(), Array);
}
namespace array_count_internal {
template <typename IndexType, typename ArrayType, int Dim, OVK_FUNCTION_REQUIRES(Dim ==
ArrayRank<ArrayType>()-1)> constexpr IndexType StaticHelper() {
return IndexType(array_traits<ArrayType>::template ExtentEnd<Dim>() -
array_traits<ArrayType>::template ExtentBegin<Dim>());
}
template <typename IndexType, typename ArrayType, int Dim, OVK_FUNCTION_REQUIRES(Dim <
ArrayRank<ArrayType>()-1)> constexpr IndexType StaticHelper() {
return IndexType(array_traits<ArrayType>::template ExtentEnd<Dim>() - array_traits<ArrayType>::
template ExtentBegin<Dim>()) * StaticHelper<IndexType, ArrayType, Dim+1>();
}
template <typename IndexType, typename ArrayType, int Dim, OVK_FUNCTION_REQUIRES(Dim ==
ArrayRank<ArrayType>()-1)> IndexType RuntimeHelper(const ArrayType &Array) {
return IndexType(array_traits<ArrayType>::template ExtentEnd<Dim>(Array) -
array_traits<ArrayType>::template ExtentBegin<Dim>(Array));
}
template <typename IndexType, typename ArrayType, int Dim, OVK_FUNCTION_REQUIRES(Dim <
ArrayRank<ArrayType>()-1)> IndexType RuntimeHelper(const ArrayType &Array) {
return IndexType(array_traits<ArrayType>::template ExtentEnd<Dim>(Array) - array_traits<
ArrayType>::template ExtentBegin<Dim>(Array)) * RuntimeHelper<IndexType, ArrayType, Dim+1>(
Array);
}
}
template <typename IndexType=long long, typename ArrayType, OVK_FUNCTION_REQUIRES(IsArray<
ArrayType>() && ArrayHasStaticExtents<ArrayType>())> constexpr IndexType ArrayCount(const
ArrayType &) {
return array_count_internal::StaticHelper<IndexType, ArrayType, 0>();
}
template <typename IndexType=long long, typename ArrayType, OVK_FUNCTION_REQUIRES(IsArray<
ArrayType>() && ArrayHasRuntimeExtents<ArrayType>())> IndexType ArrayCount(const ArrayType
&Array) {
return array_count_internal::RuntimeHelper<IndexType, ArrayType, 0>(Array);
}
template <typename ArrayRefType, OVK_FUNCTION_REQUIRES(IsArray<remove_cvref<ArrayRefType>>())> auto
ArrayData(ArrayRefType &&Array) -> decltype(array_traits<remove_cvref<ArrayRefType>>::Data(
std::forward<ArrayRefType>(Array))) {
return array_traits<remove_cvref<ArrayRefType>>::Data(std::forward<ArrayRefType>(Array));
}
template <typename ArrayRefType, OVK_FUNCTION_REQUIRES(IsArray<remove_cvref<ArrayRefType>>())> auto
ArrayBegin(ArrayRefType &&Array) -> decltype(MakeForwardingIterator<array_access_type<
ArrayRefType &&>>(ArrayData(Array))) {
return MakeForwardingIterator<array_access_type<ArrayRefType &&>>(ArrayData(Array));
}
template <typename ArrayRefType, OVK_FUNCTION_REQUIRES(IsArray<remove_cvref<ArrayRefType>>())> auto
ArrayEnd(ArrayRefType &&Array) -> decltype(MakeForwardingIterator<array_access_type<
ArrayRefType &&>>(core::ArrayData(Array)+ArrayCount(Array))) {
return MakeForwardingIterator<array_access_type<ArrayRefType &&>>(ArrayData(Array)+
ArrayCount(Array));
}
}
}
#endif
| 45.130802
| 100
| 0.755984
|
gyzhangqm
|
2626448ee8c472a55023f86a2caaea7f08d76247
| 158
|
cpp
|
C++
|
old/Codeforces/466/A.cpp
|
not522/Competitive-Programming
|
be4a7d25caf5acbb70783b12899474a56c34dedb
|
[
"Unlicense"
] | 7
|
2018-04-14T14:55:51.000Z
|
2022-01-31T10:49:49.000Z
|
old/Codeforces/466/A.cpp
|
not522/Competitive-Programming
|
be4a7d25caf5acbb70783b12899474a56c34dedb
|
[
"Unlicense"
] | 5
|
2018-04-14T14:28:49.000Z
|
2019-05-11T02:22:10.000Z
|
old/Codeforces/466/A.cpp
|
not522/Competitive-Programming
|
be4a7d25caf5acbb70783b12899474a56c34dedb
|
[
"Unlicense"
] | null | null | null |
#include "template.hpp"
int main() {
int n, m, a, b;
cin >> n >> m >> a >> b;
cout << min(n * a, min(n / m * b + n % m * a, n / m * b + b)) << endl;
}
| 19.75
| 72
| 0.411392
|
not522
|
262cab7befc0663f26883159779c9a7d1d2edb3a
| 4,246
|
hpp
|
C++
|
include/gamma/basis.hpp
|
robashaw/gamma
|
26fba31be640c9bc429f8c22d5c61c0f8e9215e6
|
[
"MIT"
] | 8
|
2019-09-13T10:35:26.000Z
|
2022-03-26T13:20:54.000Z
|
include/gamma/basis.hpp
|
robashaw/gamma
|
26fba31be640c9bc429f8c22d5c61c0f8e9215e6
|
[
"MIT"
] | null | null | null |
include/gamma/basis.hpp
|
robashaw/gamma
|
26fba31be640c9bc429f8c22d5c61c0f8e9215e6
|
[
"MIT"
] | null | null | null |
/*
*
* PURPOSE: To define the class Basis representing a
* basis set.
*
* class Basis:
* owns: bfs - a set of BFs
* data: name - the name of the basis set, needed for file io
* charges - a list of atomic numbers corresponding to
* each BF in bfs.
* shells - a list representing which bfs are in which
* shells - i.e. if the first 3 are in one shell,
* the next two in another, etc, it would be
* 3, 2, ...
* lnums - a list with the angular quantum number
* of each shell in shells
* routines:
* findPosition(q) - find the first position in the bfs
* array of an atom of atomic number q
* findShellPosition(q) - find the first position in the
* shells array
* getNBFs() - returns the total number of basis functions
* getName() - returns the name
* getCharges() - returns the vector of charges
* getBF(charge, i) - return the ith BF corresponding to
* an atom of atomic number charge
* getSize(charge) - return how many basis functions an atom
* of atomic number charge has
* getShellSize(charge) - return how many shells it has
* getShells(charge) - return a vector of the correct subset
* of shells
* getLnums(charge) - return vector of subset of lnums
*
*
* DATE AUTHOR CHANGES
* ====================================================================
* 27/08/15 Robert Shaw Original code.
*
*/
#ifndef BASISHEADERDEF
#define BASISHEADERDEF
// Includes
#include "eigen_wrapper.hpp"
#include <string>
#include <libint2.hpp>
#include <vector>
#include <map>
#include "libecpint/gshell.hpp"
// Forward declarations
class BF;
// Begin class definitions
class Basis
{
private:
std::map<int, std::string> names;
std::string name;
int maxl, nexps;
bool ecps;
std::vector<std::vector <libint2::Shell::Contraction>> raw_contractions;
std::vector<libint2::Shell> intShells;
std::vector<libint2::Shell> jkShells;
std::vector<libint2::Shell> riShells;
std::vector<int> shellAtomList;
std::vector<int> jkShellAtomList;
std::vector<int> riShellAtomList;
public:
// Constructors and destructor
// Note - no copy constructor, as it doesn't really seem necessary
// Need to specify the name of the basis, n, and a list of the
// distinct atoms that are needed (as a vector of atomic numbers)
Basis() : name("Undefined"), nexps(-1) { } // Default constructor
Basis(std::map<int, std::string> ns, bool _ecps = false);
// Accessors
bool hasECPS() const { return ecps; }
std::string getName(int q) const;
std::string getName() const { return name; }
std::map<int, std::string>& getNames() { return names; }
int getShellAtom(int i) const { return shellAtomList[i]; }
int getJKShellAtom(int i) const { return jkShellAtomList[i]; }
int getRIShellAtom(int i) const { return riShellAtomList[i]; }
std::vector<libint2::Shell>& getIntShells() { return intShells; }
std::vector<libint2::Shell>& getJKShells() { return jkShells; }
std::vector<libint2::Shell>& getRIShells() { return riShells; }
std::vector<int>& getShellAtomList() { return shellAtomList; }
std::vector<int>& getJKShellAtomList() { return jkShellAtomList; }
std::vector<int>& getRIShellAtomList() { return riShellAtomList; }
int getNExps();
int getMaxL() const { return maxl; }
void setMaxL(int l) { maxl = l; }
double getExp(int i) const;
void setExp(int i, double value);
double extent() const;
void addShell(libecpint::GaussianShell& g, int atom, int type = 0);
// Overloaded operators
Basis& operator=(const Basis& other);
};
#endif
| 38.252252
| 79
| 0.567358
|
robashaw
|
262e2c6360952d755e2279fb0b1cfb7972446d70
| 1,348
|
cpp
|
C++
|
Kattis/Week0/Wk0j_interpreter.cpp
|
Frodocz/CS2040C
|
d2e132a2f3cf56eef3f725990c7ffcf71a6a76d5
|
[
"MIT"
] | null | null | null |
Kattis/Week0/Wk0j_interpreter.cpp
|
Frodocz/CS2040C
|
d2e132a2f3cf56eef3f725990c7ffcf71a6a76d5
|
[
"MIT"
] | null | null | null |
Kattis/Week0/Wk0j_interpreter.cpp
|
Frodocz/CS2040C
|
d2e132a2f3cf56eef3f725990c7ffcf71a6a76d5
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
using namespace std;
#define MEMORY_SIZE 1000
#define REGISTER_NUM 10
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int i, cnt = 0, idx = 0;
vector<int> registers(REGISTER_NUM), ram(MEMORY_SIZE);
while (cin >> i) {
ram[idx++] = i;
}
idx = 0;
while (true) {
++cnt;
i = ram[idx];
int op = i / 100, a = (i / 10) % 10, b = i % 10;
if (op == 1) {
break;
} else if (op == 2) {
registers[a] = b;
} else if (op == 3) {
registers[a] = (registers[a] + b) % 1000;
} else if (op == 4) {
registers[a] = (registers[a] * b) % 1000;
} else if (op == 5) {
registers[a] = registers[b];
} else if (op == 6) {
registers[a] = (registers[a] + registers[b]) % 1000;
} else if (op == 7) {
registers[a] = (registers[a] * registers[b]) % 1000;
} else if (op == 8) {
registers[a] = ram[registers[b]];
} else if (i / 100 == 9) {
ram[registers[b]] = registers[a];
} else {
if (registers[b] != 0) {
idx = registers[a];
continue;
}
}
++idx;
}
cout << cnt << endl;
return 0;
}
| 24.962963
| 64
| 0.432493
|
Frodocz
|
262e2d197cb7945f4341134e31eac2a8530912dd
| 1,966
|
cpp
|
C++
|
AMM/multiPage.cpp
|
CatOfBlades/ArbitraryMemoryMapper
|
ef49c548b6171ca1b3cac61c5cb6366ca6039abc
|
[
"MIT"
] | null | null | null |
AMM/multiPage.cpp
|
CatOfBlades/ArbitraryMemoryMapper
|
ef49c548b6171ca1b3cac61c5cb6366ca6039abc
|
[
"MIT"
] | null | null | null |
AMM/multiPage.cpp
|
CatOfBlades/ArbitraryMemoryMapper
|
ef49c548b6171ca1b3cac61c5cb6366ca6039abc
|
[
"MIT"
] | null | null | null |
#include "multiPage.h"
#include "../Defines.h"
#ifdef WINBUILD
#include <windows.h>
#endif // WINBUILD
unsigned long int multiPage::_size()
{
if(!bankList.size()){return 0;}
return bankList[_bankNum]->_size();
}
bool multiPage::_is_free()
{
if(!bankList.size()){return 0;}
return bankList[_bankNum]->_is_free();
}
unsigned char* multiPage::_content()
{
if(!bankList.size()){return 0;}
return bankList[_bankNum]->_content();
}
unsigned char multiPage::readByte(unsigned long int offset)
{
if(!bankList.size()){return 0;}
return bankList[_bankNum]->readByte(offset);
}
void multiPage::writeByte(unsigned long int offset,unsigned char Byt)
{
if(!bankList.size()){return;}
bankList[_bankNum]->writeByte(offset, Byt);
return;
}
void multiPage::readMem(unsigned long int offset,unsigned char* buffer ,unsigned long int len)
{
if(!bankList.size()){return;}
bankList[_bankNum]->readMem(offset, buffer, len);
return;
}
void multiPage::writeMem(unsigned long int offset,unsigned char* Byt,unsigned long int len)
{
if(!bankList.size()){return;}
bankList[_bankNum]->writeMem(offset, Byt, len);
return;
}
void multiPage::cleanupAndUnlink()
{
while(bankList.size()>0)
{
//bankList.back()->cleanupAndUnlink();
//If we handle the cleanup elsewhere it allows us even more self reference nonsense.
bankList.pop_back();
}
return;
}
void multiPage::addBank(addressSpace* AS)
{
bankList.push_back(AS);
}
void multiPage::switchBank(int bankNum)
{
bankNum = bankNum%bankList.size();
_bankNum = bankNum;
}
void multiPage::removeBank(int bankNum)
{
bankList.erase(bankList.begin()+bankNum);
}
void multiPage::removeAndUnlinkBank(int bankNum)
{
addressSpace* bank = bankList[bankNum];
bankList.erase(bankList.begin()+bankNum);
bank->cleanupAndUnlink();
}
multiPage::multiPage():addressSpace()
{
memoryTypeID = "multpage";
_bankNum=0;
}
| 22.860465
| 96
| 0.685656
|
CatOfBlades
|
1c7a23c69da6a8ca7bcfc1c13c3afcd7d8b5ab15
| 11,114
|
cpp
|
C++
|
src/EBV_Triangulator.cpp
|
fdebrain/Stereo-Event-Based-Reconstruction-with-Active-Laser-Features
|
9e63a5d15edffba65d6e6ab521c5f6413832a97c
|
[
"MIT"
] | 4
|
2021-08-10T17:35:35.000Z
|
2021-12-06T08:43:07.000Z
|
src/EBV_Triangulator.cpp
|
fdebrain/Stereo-Event-Based-Reconstruction-with-Active-Laser-Features
|
9e63a5d15edffba65d6e6ab521c5f6413832a97c
|
[
"MIT"
] | null | null | null |
src/EBV_Triangulator.cpp
|
fdebrain/Stereo-Event-Based-Reconstruction-with-Active-Laser-Features
|
9e63a5d15edffba65d6e6ab521c5f6413832a97c
|
[
"MIT"
] | null | null | null |
#include <EBV_Triangulator.h>
#include <EBV_Benchmarking.h>
void Triangulator::switchMode()
{
m_mode = static_cast<Triangulator::StereoPair>((m_mode+1)%3);
std::cout << "Switch triangulation mode to: " << stereoPairNames[m_mode] << "\n\r";
}
void Triangulator::resetCalibration()
{
for (auto &k : m_K) { k = cv::Mat(3,3,CV_64FC1); }
for (auto &d : m_D) { d = cv::Mat(1,5,CV_32FC1); }
for (auto &r : m_R) { r = cv::Mat(3,3,CV_32FC1); }
for (auto &t : m_T) { t = cv::Mat(3,1,CV_32FC1); }
for (auto &f : m_F) { f = cv::Mat(3,3,CV_32FC1); }
for (auto &q : m_Q) { q = cv::Mat(4,4,CV_32FC1); }
for (auto &p : m_P) { p[0] = cv::Mat(3,4,CV_32FC1); p[1] = cv::Mat(3,4,CV_32FC1); }
for (auto &rect : m_Rect) { rect[0] = cv::Mat(3,3,CV_32FC1); rect[1] = cv::Mat(3,3,CV_32FC1); }
m_Pfix = cv::Mat(3,4,CV_32FC1);
}
void Triangulator::importCalibration()
{
resetCalibration();
cv::FileStorage fs;
// Import camera calibration
fs.open(m_path_calib_cam, cv::FileStorage::READ);
fs["camera_matrix0"] >> m_K[0];
fs["dist_coeffs0"] >> m_D[0];
fs["camera_matrix1"] >> m_K[1];
fs["dist_coeffs1"] >> m_D[1];
fs["R"] >> m_R[0];
fs["T"] >> m_T[0];
fs["F"] >> m_F[0];
std::cout << "K0: " << m_K[0] << "\n\r";
std::cout << "D0: " << m_D[0] << "\n\r";
std::cout << "K1: " << m_K[1] << "\n\r";
std::cout << "D1: " << m_D[1] << "\n\r";
std::cout << "R: " << m_R[0] << "\n\r";
std::cout << "T: " << m_T[0] << "\n\r";
std::cout << "F: " << m_F[0] << "\n\r";
fs.release();
// Import laser calibration
fs.open(m_path_calib_laser, cv::FileStorage::READ);
fs["camera_matrix_laser"] >> m_K[2];
fs["dist_coeffs_laser"] >> m_D[2];
fs["R1"] >> m_R[1];
fs["T1"] >> m_T[1];
fs["F1"] >> m_F[1];
fs["R2"] >> m_R[2];
fs["T2"] >> m_T[2];
fs["F2"] >> m_F[2];
std::cout << "KLaser: " << m_K[2] << "\n\r";
std::cout << "DLaser: " << m_D[2] << "\n\r";
std::cout << "R1: " << m_R[1] << "\n\r";
std::cout << "T1: " << m_T[1] << "\n\r";
std::cout << "F1: " << m_F[1] << "\n\r";
std::cout << "R2: " << m_R[2] << "\n\r";
std::cout << "T2: " << m_T[2] << "\n\r";
std::cout << "F2: " << m_F[2] << "\n\r";
fs.release();
// Initialize projection matrices for cam0-cam1 stereo pair
if (isValid(0) && isValid(1))
{
m_enable = true;
cv::stereoRectify(m_K[0],m_D[0],
m_K[1],m_D[1],
cv::Size(m_cols,m_rows),
m_R[0],m_T[0],
m_Rect[0][0], m_Rect[0][1],
m_P[0][0], m_P[0][1],
m_Q[0], cv::CALIB_ZERO_DISPARITY);
}
else
{
m_enable = false;
printf("Please press C to calibrate the cameras.\n\r");
return;
}
// Initialize projection matrices for cam0-laser & cam1-laser stereo pairs
if (isValid(0) && isValid(1) && isValid(2))
{
m_enable = true;
// CameraLeft-laser
cv::stereoRectify(m_K[0],m_D[0],
m_K[2],m_D[2],
cv::Size(m_cols,m_rows),
m_R[1],m_T[1],
m_Rect[1][0], m_Rect[1][1],
m_P[1][0], m_P[1][1],
m_Q[1], cv::CALIB_ZERO_DISPARITY);
//CameraRight-laser
cv::stereoRectify(m_K[1],m_D[1],
m_K[2],m_D[2],
cv::Size(m_cols,m_rows),
m_R[2],m_T[2],
m_Rect[2][0], m_Rect[2][1],
m_P[2][0], m_P[2][1],
m_Q[2], cv::CALIB_ZERO_DISPARITY);
}
else
{
m_enable = false;
printf("Please press C to calibrate the laser.\n\r");
return;
}
}
bool Triangulator::isValid(const int id) const
{
return m_K[id].rows==3 && m_K[id].cols==3 &&
m_D[id].rows==1 && m_D[id].cols==5;
}
Triangulator::Triangulator(Matcher* matcher,
LaserController* laser)
: m_matcher(matcher),
m_laser(laser)
{
// Initialize datastructures
resetCalibration();
// Listen to matcher
m_matcher->registerMatcherListener(this);
// Recording triangulation
if (m_record){ m_recorder.open(m_eventRecordFile); }
// Calibration
this->importCalibration();
if (m_enable) { m_thread = std::thread(&Triangulator::run,this); }
}
Triangulator::~Triangulator()
{
m_matcher->deregisterMatcherListener(this);
if (m_record){ m_recorder.close(); }
}
void Triangulator::run()
{
bool hasQueueEvent0;
bool hasQueueEvent1;
DAVIS240CEvent event0;
DAVIS240CEvent event1;
while(true)
{
m_queueAccessMutex0.lock();
hasQueueEvent0 =! m_evtQueue0.empty();
m_queueAccessMutex0.unlock();
m_queueAccessMutex1.lock();
hasQueueEvent1 =! m_evtQueue1.empty();
m_queueAccessMutex1.unlock();
// Process only if incoming filtered events in both cameras
if(hasQueueEvent0 && hasQueueEvent1)
{
m_queueAccessMutex0.lock();
event0 = m_evtQueue0.front();
m_evtQueue0.pop_front();
m_queueAccessMutex0.unlock();
m_queueAccessMutex1.lock();
event1 = m_evtQueue1.front();
m_evtQueue1.pop_front();
m_queueAccessMutex1.unlock();
process(event0,event1);
}
else
{
std::unique_lock<std::mutex> condLock(m_condWaitMutex);
m_condWait.wait(condLock);
condLock.unlock();
}
}
}
void Triangulator::receivedNewMatch(const DAVIS240CEvent& event0,
const DAVIS240CEvent& event1)
{
m_queueAccessMutex0.lock();
m_evtQueue0.push_back(event0);
m_queueAccessMutex0.unlock();
m_queueAccessMutex1.lock();
m_evtQueue1.push_back(event1);
m_queueAccessMutex1.unlock();
std::unique_lock<std::mutex> condLock(m_condWaitMutex);
m_condWait.notify_one();
}
void Triangulator::process(const DAVIS240CEvent& event0, const DAVIS240CEvent& event1)
{
//Timer timer; // 0.1ms on average
std::vector<cv::Point2d> coords0, coords1;
std::vector<cv::Point2d> undistCoords0, undistCoords1;
std::vector<cv::Point2d> undistCoordsCorrected0, undistCoordsCorrected1;
cv::Vec4d point3D;
m_queueAccessMutex0.lock();
const int x0 = event0.m_x;
const int y0 = event0.m_y;
const int x1 = event1.m_x;
const int y1 = event1.m_y;
//const int laser_x = 180*(m_laser->getX()-500)/(4000 - 500);
//const int laser_y = 240*(m_laser->getY())/(4000);
const int laser_x = static_cast<int>(180.*(event0.m_laser_x-500.)/(4000. - 500.));
const int laser_y = static_cast<int>(240.*(event0.m_laser_y)/(4000.));
m_queueAccessMutex0.unlock();
switch (m_mode)
{
case Cameras:
coords0.emplace_back(y0,x0);
coords1.emplace_back(y1,x1);
cv::undistortPoints(coords0, undistCoords0,
m_K[0], m_D[0],
m_Rect[m_mode][0],
m_P[m_mode][0]);
cv::undistortPoints(coords1, undistCoords1,
m_K[1], m_D[1],
m_Rect[m_mode][1],
m_P[m_mode][1]);
cv::triangulatePoints(m_P[m_mode][0], m_P[m_mode][1],
undistCoords0, //undistCoordsCorrected0
undistCoords1, //undistCoordsCorrected1
point3D);
break;
case CamLeftLaser:
coords0.emplace_back(y0,x0);
coords1.emplace_back(laser_y,laser_x);
cv::undistortPoints(coords0, undistCoords0,
m_K[0], m_D[0],
m_Rect[m_mode][0],
m_P[m_mode][0]);
cv::undistortPoints(coords1, undistCoords1,
m_K[2], m_D[2],
m_Rect[m_mode][1],
m_P[m_mode][1]);
// Refine matches coordinates (using epipolar constraint)
cv::correctMatches(m_F[m_mode],undistCoords0,undistCoords1,
undistCoordsCorrected0,
undistCoordsCorrected1);
cv::triangulatePoints(m_P[m_mode][0], m_P[m_mode][1],
undistCoordsCorrected0,
undistCoordsCorrected1,
point3D);
break;
case CamRightLaser:
coords0.emplace_back(y1,x1);
coords1.emplace_back(laser_y,laser_x);
cv::undistortPoints(coords0, undistCoords0,
m_K[1], m_D[1],
m_Rect[m_mode][0],
m_P[m_mode][0]);
cv::undistortPoints(coords1, undistCoords1,
m_K[2], m_D[2],
m_Rect[m_mode][1],
m_P[m_mode][1]);
// Refine matches coordinates (using epipolar constraint)
cv::correctMatches(m_F[m_mode],undistCoords0,undistCoords1,
undistCoordsCorrected0,
undistCoordsCorrected1);
cv::triangulatePoints(m_P[m_mode][0], m_P[m_mode][1],
undistCoordsCorrected0,
undistCoordsCorrected1,
point3D);
break;
}
// Convert to cm + scale
double scale = point3D[3];
double X = 100*point3D[0]/scale;
double Y = 100*point3D[1]/scale;
double Z = 100*point3D[2]/scale;
if (m_record) { recordPoint(X,Y,Z); }
warnDepth(x0,y0,X,Y,Z);
coords0.clear();
coords1.clear();
// DEBUG - CHECK 3D POINT POSITION
if (m_debug) { printf("Point at: (%2.1f,%2.1f,%2.1f,%2.1f). \n\r ",X,Y,Z,scale); }
// END DEBUG
}
void Triangulator::recordPoint(double X, double Y, double Z)
{
m_recorder << X << '\t'
<< Y << '\t'
<< Z << '\n';
}
void Triangulator::computeProjectionMatrix(cv::Mat K, cv::Mat R,
cv::Mat T, cv::Mat& P)
{
K.convertTo(K,CV_64FC1);
cv::hconcat(K*R,K*T,P);
}
void Triangulator::registerTriangulatorListener(TriangulatorListener* listener)
{
m_triangulatorListeners.push_back(listener);
}
void Triangulator::deregisterTriangulatorListener(TriangulatorListener* listener)
{
m_triangulatorListeners.remove(listener);
}
void Triangulator::warnDepth(const int u,
const int v,
const double X,
const double Y,
const double Z)
{
std::list<TriangulatorListener*>::iterator it;
for(it = m_triangulatorListeners.begin(); it!=m_triangulatorListeners.end(); it++)
{
(*it)->receivedNewDepth(u,v,X,Y,Z);
}
}
| 31.936782
| 99
| 0.520875
|
fdebrain
|
1c888ffbcbdae678e1772280f72ea0065ce94d34
| 3,040
|
cpp
|
C++
|
2018/0804_mujin-pc-2018/E.cpp
|
kazunetakahashi/atcoder
|
16ce65829ccc180260b19316e276c2fcf6606c53
|
[
"MIT"
] | 7
|
2019-03-24T14:06:29.000Z
|
2020-09-17T21:16:36.000Z
|
2018/0804_mujin-pc-2018/E.cpp
|
kazunetakahashi/atcoder
|
16ce65829ccc180260b19316e276c2fcf6606c53
|
[
"MIT"
] | null | null | null |
2018/0804_mujin-pc-2018/E.cpp
|
kazunetakahashi/atcoder
|
16ce65829ccc180260b19316e276c2fcf6606c53
|
[
"MIT"
] | 1
|
2020-07-22T17:27:09.000Z
|
2020-07-22T17:27:09.000Z
|
/**
* File : E.cpp
* Author : Kazune Takahashi
* Created : 2018-8-4 22:09:58
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
typedef long long ll;
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};
const char ds[4] = {'D', 'R', 'U', 'L'};
typedef tuple<ll, int, int> state;
// const int C = 1e6+10;
const ll infty = 10000000000007;
int N, M, K;
string D;
string S[1010];
ll dist[300010][4];
ll ans[1010][1010];
int main()
{
cin >> N >> M >> K;
cin >> D;
D = D + D + D;
for (auto i = 0; i < N; i++)
{
cin >> S[i];
}
for (auto k = 0; k < 4; k++)
{
dist[3 * K][k] = infty;
}
for (int i = 3 * K - 1; i >= 0; i--)
{
for (auto k = 0; k < 4; k++)
{
if (D[i] == ds[k])
{
dist[i][k] = 1;
}
else
{
dist[i][k] = dist[i + 1][k] + 1;
}
}
}
/*
for (auto i = 0; i < K; i++)
{
for (auto k = 0; k < 4; k++)
{
cerr << "dist[" << i << "][" << k << "] = " << dist[i][k] << endl;
}
}
*/
int sx, sy, gx, gy;
fill(&ans[0][0], &ans[0][0] + 1010 * 1010, -1);
for (auto i = 0; i < N; i++)
{
for (auto j = 0; j < M; j++)
{
if (S[i][j] == 'S')
{
sx = i;
sy = j;
}
else if (S[i][j] == 'G')
{
gx = i;
gy = j;
}
}
}
priority_queue<state, vector<state>, greater<state>> Q;
Q.push(state(0, sx, sy));
while (!Q.empty())
{
ll d = get<0>(Q.top());
int x = get<1>(Q.top());
int y = get<2>(Q.top());
Q.pop();
if (ans[x][y] == -1)
{
ans[x][y] = d;
// cerr << "ans[" << x << "][" << y << "] = " << ans[x][y] << endl;
if (x == gx && y == gy)
{
cout << d << endl;
return 0;
}
for (auto k = 0; k < 4; k++)
{
int new_x = x + dx[k];
int new_y = y + dy[k];
if (0 <= new_x && new_x < N && 0 <= new_y && new_y < M && S[new_x][new_y] != '#' && ans[new_x][new_y] == -1)
{
ll new_d = d + dist[d % K][k];
if (new_d < infty)
{
Q.push(state(new_d, new_x, new_y));
}
}
}
}
}
cout << -1 << endl;
}
| 22.189781
| 116
| 0.464474
|
kazunetakahashi
|
1c88b3e9ef72afba9c9d5b45ba8a309c3ef87f97
| 1,032
|
hpp
|
C++
|
src/emp_dist.hpp
|
dcjones/isolator
|
24bafc0a102dce213bfc2b5b9744136ceadaba03
|
[
"MIT"
] | 33
|
2015-07-13T03:00:01.000Z
|
2021-03-20T08:49:07.000Z
|
src/emp_dist.hpp
|
dcjones/isolator
|
24bafc0a102dce213bfc2b5b9744136ceadaba03
|
[
"MIT"
] | 9
|
2016-11-29T00:04:30.000Z
|
2020-02-10T17:46:01.000Z
|
src/emp_dist.hpp
|
dcjones/isolator
|
24bafc0a102dce213bfc2b5b9744136ceadaba03
|
[
"MIT"
] | 6
|
2015-09-10T15:49:34.000Z
|
2017-03-09T05:14:06.000Z
|
#ifndef ISOLATOR_EMP_DIST
#define ISOLATOR_EMP_DIST
#include <climits>
#include <vector>
class EmpDist
{
public:
EmpDist(EmpDist&);
/* Construct a emperical distribution from n observations stored in xs.
*
* Input in run-length encoded samples, which must be in sorted order.
*
* Args:
* vals: An array of unique observations.
* lens: Nuber of occurances for each observation.
* n: Length of vals and lens.
*/
EmpDist(const unsigned int* vals,
const unsigned int* lens,
size_t n);
/* Compute the median of the distribution. */
float median() const;
/* Probability density function. */
float pdf(unsigned int x) const;
/* Comulative p robabability. */
float cdf(unsigned int x) const;
private:
std::vector<float> pdfvals;
std::vector<float> cdfvals;
/* Precomputed median */
float med;
};
#endif
| 21.061224
| 79
| 0.573643
|
dcjones
|
1c93f82b414d383676dcdfc79956b5141e8135b4
| 1,104
|
hxx
|
C++
|
tests/cvinvaffine.hxx
|
zardchim/opencvx
|
f3727c9be5532f9a41c29f558e72aa19b6db97a4
|
[
"Unlicense"
] | 10
|
2015-01-29T23:21:06.000Z
|
2019-07-05T06:27:16.000Z
|
tests/cvinvaffine.hxx
|
zardchim/opencvx
|
f3727c9be5532f9a41c29f558e72aa19b6db97a4
|
[
"Unlicense"
] | null | null | null |
tests/cvinvaffine.hxx
|
zardchim/opencvx
|
f3727c9be5532f9a41c29f558e72aa19b6db97a4
|
[
"Unlicense"
] | 13
|
2015-04-13T20:50:36.000Z
|
2022-03-20T16:06:05.000Z
|
#ifdef _MSC_VER
#pragma warning(disable:4996)
#pragma comment(lib, "cv.lib")
#pragma comment(lib, "cxcore.lib")
#pragma comment(lib, "cvaux.lib")
#pragma comment(lib, "highgui.lib")
#endif
#include <stdio.h>
#include <stdlib.h>
#include "cv.h"
#include "cvaux.h"
#include "cxcore.h"
#include "highgui.h"
#include "cvcreateaffine.h"
#include "cvinvaffine.h"
#include <cxxtest/TestSuite.h>
class CvInvAffineTest : public CxxTest::TestSuite
{
public:
void testInvAffine()
{
CvMat* affine = cvCreateMat( 2, 3, CV_64FC1 );
CvMat* invaffine = cvCreateMat( 2, 3, CV_64FC1 );
cvCreateAffine( affine, cvRect32f( 3, 10, 2, 20, 45 ), cvPoint2D32f( 4, 5 ) );
cvInvAffine( affine, invaffine );
double ans[] = {
0.565685, -0.848528, 6.788225,
-0.106066, 0.247487, -2.156676,
};
CvMat Ans = cvMat( 2, 3, CV_64FC1, ans );
for( int i = 0; i < 2; i++ ) {
for( int j = 0; j < 3; j++ ) {
TS_ASSERT_DELTA( cvmGet( invaffine, i, j ), cvmGet( &Ans, i, j ), 0.0001 );
}
}
}
};
| 26.926829
| 91
| 0.577899
|
zardchim
|
1c9b1e3e468091ba85c0dae6153ff9f95968ca8b
| 1,604
|
hpp
|
C++
|
tainthlp.hpp
|
yqw1212/demovfuscator
|
d27dd1c87ba6956dae4a3003497fe8760b7299f9
|
[
"BSD-2-Clause"
] | 614
|
2016-06-19T21:39:02.000Z
|
2022-03-27T06:07:53.000Z
|
tainthlp.hpp
|
yqw1212/demovfuscator
|
d27dd1c87ba6956dae4a3003497fe8760b7299f9
|
[
"BSD-2-Clause"
] | 20
|
2016-06-19T21:44:20.000Z
|
2022-03-31T05:21:34.000Z
|
tainthlp.hpp
|
yqw1212/demovfuscator
|
d27dd1c87ba6956dae4a3003497fe8760b7299f9
|
[
"BSD-2-Clause"
] | 54
|
2016-06-20T07:01:22.000Z
|
2021-12-14T13:34:56.000Z
|
#ifndef TAINTHLP_H
#define TAINTHLP_H
#include <map>
#include <unordered_map>
#include <capstone/x86.h>
class tainthlp{
public:
/**
* Adds taint to a specified address and (len - 1) subsequent addresses
* @param base base address to taint
* @param len length of the area to taint
* @param ref the taint reference number (or colour or whatever)
* @return 0 if successful, else 1
*/
int add_taint(uint64_t base, size_t len, size_t ref);
/**
* Querys whether an address is tainted
* @param addr The Querryed address
* @param len The length of the quarryed area
* @return true if any of the addresses are tainted, else false
*/
bool has_taint(uint64_t addr, size_t len);
/**
* Returns the taint information of an memory cell
* @param addr The Memory address
* @return the taint reference number
*/
size_t get_taint(uint64_t addr);
/**
* Taints a register and the subregisters (tainting ax also taints ah an al, but not eax)
* @param reg The register to taint
* @param ref The taint reference number
* @return 0 on success, 1 on failur
*/
int add_taint(x86_reg reg, size_t ref);
/**
* Get the taintness status from the register
* @param reg The register
* @return true if tainted, false if not
*/
bool has_taint(x86_reg reg);
/**
* @param get the taint information off a specific register
* @return the taint reference number
*/
size_t get_taint(x86_reg reg);
private:
std::map<uint32_t, size_t> mem_taint;
std::unordered_map<x86_reg, size_t, std::hash<unsigned int> > reg_taint;
}
#endif
| 26.733333
| 91
| 0.69015
|
yqw1212
|
1cb443b558689eb8476d57651ccbc56b0b20d513
| 4,703
|
inl
|
C++
|
matlab_code/jjcao_code-head/toolbox/jjcao_mesh/geodesic/mex/gw/gw_core/GW_SmartCounter.inl
|
joycewangsy/normals_pointnet
|
fc74a8ed1a009b18785990b1b4c20eda0549721c
|
[
"MIT"
] | null | null | null |
matlab_code/jjcao_code-head/toolbox/jjcao_mesh/geodesic/mex/gw/gw_core/GW_SmartCounter.inl
|
joycewangsy/normals_pointnet
|
fc74a8ed1a009b18785990b1b4c20eda0549721c
|
[
"MIT"
] | null | null | null |
matlab_code/jjcao_code-head/toolbox/jjcao_mesh/geodesic/mex/gw/gw_core/GW_SmartCounter.inl
|
joycewangsy/normals_pointnet
|
fc74a8ed1a009b18785990b1b4c20eda0549721c
|
[
"MIT"
] | null | null | null |
/*------------------------------------------------------------------------------*/
/**
* \file GW_SmartCounter.inl
* \brief Inlined methods for \c GW_SmartCounter
* \author Gabriel Peyr?2001-09-12
*/
/*------------------------------------------------------------------------------*/
#include "GW_SmartCounter.h"
namespace GW {
/*------------------------------------------------------------------------------*/
/**
* Name : GW_SmartCounter constructor
*
* \author Gabriel Peyr?2001-09-12
*/
/*------------------------------------------------------------------------------*/
GW_INLINE
GW_SmartCounter::GW_SmartCounter()
: nReferenceCounter_ ( 0 )
{
/* NOTHING */
}
/*------------------------------------------------------------------------------
* Name : GW_SmartCounter constructor
*
* \param Dup EXPLANATION
* \return PUT YOUR RETURN VALUE AND ITS EXPLANATION
* \author Antoine Bouthors 2001-11-24
*
* PUT YOUR COMMENTS HERE
*------------------------------------------------------------------------------*/
GW_INLINE
GW_SmartCounter::GW_SmartCounter( const GW_SmartCounter& Dup )
: nReferenceCounter_(0)
{
/* NOTHING */
}
/*------------------------------------------------------------------------------
* Name : GW_SmartCounter::operator
*
* \param Dup EXPLANATION
* \return PUT YOUR RETURN VALUE AND ITS EXPLANATION
* \author Antoine Bouthors 2001-11-24
*
* PUT YOUR COMMENTS HERE
*------------------------------------------------------------------------------*/
GW_INLINE
GW_SmartCounter& GW_SmartCounter::operator=( const GW_SmartCounter& Dup )
{
nReferenceCounter_ = 0;
return (*this);
}
/*------------------------------------------------------------------------------*/
/**
* Name : GW_SmartCounter destructor
*
* \author Gabriel Peyr?2001-09-12
*
* Check that nobody is still using the object.
*/
/*------------------------------------------------------------------------------*/
GW_INLINE
GW_SmartCounter::~GW_SmartCounter()
{
GW_ASSERT( nReferenceCounter_==0 );
}
/*------------------------------------------------------------------------------*/
/**
* Name : GW_SmartCounter::UseIt
*
* \author Gabriel Peyr?2001-09-10
*
* Declare that we use this object. We must call \c ReleaseIt when we no longer use this object.
*/
/*------------------------------------------------------------------------------*/
GW_INLINE
void GW_SmartCounter::UseIt()
{
GW_ASSERT( nReferenceCounter_<=50000 );
nReferenceCounter_++;
}
/*------------------------------------------------------------------------------*/
/**
* Name : GW_SmartCounter::ReleaseIt
*
* \author Gabriel Peyr?2001-09-10
*
* Declare that we no longer use this object.
*/
/*------------------------------------------------------------------------------*/
GW_INLINE
void GW_SmartCounter::ReleaseIt()
{
GW_ASSERT( nReferenceCounter_>0 );
nReferenceCounter_--;
}
/*------------------------------------------------------------------------------*/
/**
* Name : GW_SmartCounter::NoLongerUsed
*
* \return true if no one use this object anymore.
* \author Gabriel Peyr?2001-09-10
*
* We can delete the object only if \c NoLongerUsed return true.
*/
/*------------------------------------------------------------------------------*/
GW_INLINE
bool GW_SmartCounter::NoLongerUsed()
{
GW_ASSERT( nReferenceCounter_>=0 );
return nReferenceCounter_==0;
}
/*------------------------------------------------------------------------------
* Name : GW_SmartCounter::GetReferenceCounter
*
* \return the value of the reference counter
* \author Antoine Bouthors 2001-11-30
*
*------------------------------------------------------------------------------*/
GW_INLINE
GW_I32 GW_SmartCounter::GetReferenceCounter()
{
return nReferenceCounter_;
}
} // End namespace GW
///////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2000-2001 The Orion3D Rewiew Board //
//---------------------------------------------------------------------------//
// This file is under the Orion3D licence. //
// Refer to orion3d_licence.txt for more details about the Orion3D Licence. //
//---------------------------------------------------------------------------//
// Ce fichier est soumis a la Licence Orion3D. //
// Se reporter a orion3d_licence.txt pour plus de details sur cette licence.//
///////////////////////////////////////////////////////////////////////////////
// END OF FILE //
///////////////////////////////////////////////////////////////////////////////
| 29.21118
| 96
| 0.402296
|
joycewangsy
|
1cb60bcb0a7f2747bb34edc4ffef8a1ae21c6fac
| 415
|
cpp
|
C++
|
src/1064b/emm.cpp
|
lifeich1/play-cf
|
7eb6dbb290fcf7935e88d3f090d4af79e7308773
|
[
"WTFPL"
] | null | null | null |
src/1064b/emm.cpp
|
lifeich1/play-cf
|
7eb6dbb290fcf7935e88d3f090d4af79e7308773
|
[
"WTFPL"
] | 8
|
2018-10-15T06:47:19.000Z
|
2019-02-15T09:58:02.000Z
|
src/1064b/emm.cpp
|
lifeich1/play-cf
|
7eb6dbb290fcf7935e88d3f090d4af79e7308773
|
[
"WTFPL"
] | null | null | null |
//-[
#include "type.h"
//-]
namespace licf {
namespace emm_1064b {
// placeholder
}
}
using namespace licf::emm_1064b;
int emm_1064b(const _in_t & in_, _out_t & out_)
{
int n;
while (in_.read(&n))
{
LL res = 1;
for (; n > 0; n >>= 1)
{
if (n & 1)
{
res <<= 1ll;
}
}
in_.put(res);
}
return 0;
}
| 12.96875
| 47
| 0.414458
|
lifeich1
|
1cb6b50ac4e909f6822ded0ee163ee38682adb8b
| 1,093
|
cpp
|
C++
|
src/lib/cert/cvc/cvc_req.cpp
|
el-forkorama/botan
|
4ad555977b03cb92dfac0b87a00febe4d8e7ff5e
|
[
"BSD-2-Clause"
] | null | null | null |
src/lib/cert/cvc/cvc_req.cpp
|
el-forkorama/botan
|
4ad555977b03cb92dfac0b87a00febe4d8e7ff5e
|
[
"BSD-2-Clause"
] | null | null | null |
src/lib/cert/cvc/cvc_req.cpp
|
el-forkorama/botan
|
4ad555977b03cb92dfac0b87a00febe4d8e7ff5e
|
[
"BSD-2-Clause"
] | null | null | null |
/*
* (C) 2007 FlexSecure GmbH
* 2008-2010 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/cvc_req.h>
#include <botan/cvc_cert.h>
#include <botan/ber_dec.h>
namespace Botan {
bool EAC1_1_Req::operator==(EAC1_1_Req const& rhs) const
{
return (this->tbs_data() == rhs.tbs_data() &&
this->get_concat_sig() == rhs.get_concat_sig());
}
void EAC1_1_Req::force_decode()
{
std::vector<byte> enc_pk;
BER_Decoder tbs_cert(m_tbs_bits);
size_t cpi;
tbs_cert.decode(cpi, ASN1_Tag(41), APPLICATION)
.start_cons(ASN1_Tag(73))
.raw_bytes(enc_pk)
.end_cons()
.decode(m_chr)
.verify_end();
if(cpi != 0)
throw Decoding_Error("EAC1_1 requests cpi was not 0");
m_pk = decode_eac1_1_key(enc_pk, m_sig_algo);
}
EAC1_1_Req::EAC1_1_Req(DataSource& in)
{
init(in);
m_self_signed = true;
do_decode();
}
EAC1_1_Req::EAC1_1_Req(const std::string& in)
{
DataSource_Stream stream(in, true);
init(stream);
m_self_signed = true;
do_decode();
}
}
| 20.240741
| 70
| 0.651418
|
el-forkorama
|
1cc2c32fe849253ec5bcaa89abc100f454914d6b
| 6,048
|
cpp
|
C++
|
code/source/thread_capture.cpp
|
DEAKSoftware/KFX
|
8a759d21a651d9f8acbfef2e3d19b1e8580a74b5
|
[
"MIT"
] | null | null | null |
code/source/thread_capture.cpp
|
DEAKSoftware/KFX
|
8a759d21a651d9f8acbfef2e3d19b1e8580a74b5
|
[
"MIT"
] | null | null | null |
code/source/thread_capture.cpp
|
DEAKSoftware/KFX
|
8a759d21a651d9f8acbfef2e3d19b1e8580a74b5
|
[
"MIT"
] | null | null | null |
/*===========================================================================
Video Capture Thread
Dominik Deak
===========================================================================*/
#ifndef ___THREAD_CAPTURE_CPP___
#define ___THREAD_CAPTURE_CPP___
/*---------------------------------------------------------------------------
Header files
---------------------------------------------------------------------------*/
#include "common.h"
#include "debug.h"
#include "mutex.h"
#include "thread_capture.h"
/*---------------------------------------------------------------------------
Static data.
---------------------------------------------------------------------------*/
const char* CaptureThread::ExtTGA = "tga";
const char* CaptureThread::ExtPNG = "png";
/*---------------------------------------------------------------------------
Opens a new target directory for streaming. The subdirectory names are
generated automatically, based on the current date and timestamp, and with
the Prefix added.
---------------------------------------------------------------------------*/
CaptureThread::CaptureThread(QObject* Parent, const QString &Path, const QString &Prefix, CapFormat Format, bool Compress) : QThread(Parent)
{
Clear();
if (Parent == nullptr) {throw dexception("Invalid parameters.");}
setTerminationEnabled(true);
//Hook signal functions to the parent class' slot functions
QObject::connect(this, SIGNAL(SignalError(QString)), Parent, SLOT(CaptureError(QString)));
CaptureThread::Format = Format;
CaptureThread::Compress = Compress;
Dir = Path;
switch (CaptureThread::Format)
{
case CaptureThread::FormatTGA : Ext = CaptureThread::ExtTGA; break;
case CaptureThread::FormatPNG : Ext = CaptureThread::ExtPNG; break;
default : throw dexception("The specified file format is unknown.");
}
QString SubDir;
bool Exists = false;
uint I = 0;
do {
QDate Date = QDate::currentDate();
QTime Time = QTime::currentTime();
SubDir = Prefix;
SubDir += Date.toString(" yyyy-MM-dd ");
SubDir += Time.toString("HH-mm-ss-zzz");
if (I > 0) {SubDir += QString(" %1").arg(I);}
I++;
Exists = Dir.exists(SubDir);
}
while (Exists && I < MaxSubDirAttempts);
if (Exists) {throw dexception("Failed to create a unique subdirectory.");}
if (!Dir.mkdir(SubDir))
{throw dexception("Failed to create a new subdirectory.");}
if (!Dir.cd(SubDir))
{throw dexception("Failed to change into subdirectory.");}
start();
}
/*---------------------------------------------------------------------------
Destructor.
---------------------------------------------------------------------------*/
CaptureThread::~CaptureThread(void)
{
Destroy();
}
/*---------------------------------------------------------------------------
Clears the structure.
---------------------------------------------------------------------------*/
void CaptureThread::Clear(void)
{
Count = 0;
Format = CaptureThread::FormatTGA;
Ext = CaptureThread::ExtTGA;
Compress = false;
Exit = false;
}
/*---------------------------------------------------------------------------
Destroys the structure.
---------------------------------------------------------------------------*/
void CaptureThread::Destroy(void)
{
Clear();
}
/*---------------------------------------------------------------------------
Thread entry point.
---------------------------------------------------------------------------*/
void CaptureThread::run(void)
{
debug("Started capture thread.\n");
try {
while (!Exit)
{
//Wait for new frame
QMutexLocker MutexLocker(&UpdateMutex);
UpdateWait.wait(&UpdateMutex);
//Lock frame
NAMESPACE_PROJECT::MutexControl Mutex(Frame.GetMutexHandle());
if (!Mutex.LockRequest()) {debug("Mutex already locked, dropping frame.\n"); continue;}
if (Frame.Size() < 1) {debug("No data in frame, dropping frame.\n"); continue;}
//Construct file name
FileName = QString("%1.").arg((long)Count, FileNameDigits, FileNameBase, QLatin1Char('0')) + Ext;
FileName = Dir.absoluteFilePath(FileName);
Path = FileName.toAscii();
//Save frame
switch (Format)
{
case CaptureThread::FormatTGA :
TGA.Save(Frame, Path.constData(), false, Compress);
break;
case CaptureThread::FormatPNG :
PNG.Save(Frame, Path.constData(), Compress ? NAMESPACE_PROJECT::File::PNG::CompSpeed : NAMESPACE_PROJECT::File::PNG::CompNone);
break;
default : throw dexception("The specified file format is unknown.");
}
Count++;
}
}
catch (std::exception &e)
{
SignalError(e.what());
Exit = true;
}
catch (...)
{
SignalError("Trapped an unhandled exception in the capture thread.");
Exit = true;
}
debug("Stopping capture thread.\n");
}
/*---------------------------------------------------------------------------
Signals to exit thread.
---------------------------------------------------------------------------*/
void CaptureThread::stop(void)
{
Exit = true;
UpdateWait.wakeAll();
}
/*---------------------------------------------------------------------------
Signals thread to saves a frame to file.
---------------------------------------------------------------------------*/
void CaptureThread::update(void)
{
if (Exit) {return;}
UpdateWait.wakeAll();
}
//==== End of file ===========================================================
#endif
| 31.175258
| 144
| 0.430556
|
DEAKSoftware
|
1cd27e671a0ca1a0581041df32c1c948f55e5809
| 4,119
|
cpp
|
C++
|
src/tanktextures.cpp
|
Eae02/tank-game
|
0c526b177ccc15dd49e3228489163f13335040db
|
[
"Zlib"
] | null | null | null |
src/tanktextures.cpp
|
Eae02/tank-game
|
0c526b177ccc15dd49e3228489163f13335040db
|
[
"Zlib"
] | null | null | null |
src/tanktextures.cpp
|
Eae02/tank-game
|
0c526b177ccc15dd49e3228489163f13335040db
|
[
"Zlib"
] | null | null | null |
#include "tanktextures.h"
#include "exceptions/invalidstateexception.h"
#include "utils/utils.h"
#include "utils/ioutils.h"
#include "graphics/textureloadoperation.h"
namespace TankGame
{
static std::unique_ptr<TankTextures> instance;
class TankTexturesLoadOperation : public IASyncOperation
{
public:
TankTexturesLoadOperation()
: m_baseDiffuseLoadOps{ TextureLoadOperation(GetResDirectory() / "tank" / "base0.png", nullptr),
TextureLoadOperation(GetResDirectory() / "tank" / "base1.png", nullptr),
TextureLoadOperation(GetResDirectory() / "tank" / "base2.png", nullptr),
TextureLoadOperation(GetResDirectory() / "tank" / "base3.png", nullptr),
TextureLoadOperation(GetResDirectory() / "tank" / "base4.png", nullptr),
TextureLoadOperation(GetResDirectory() / "tank" / "base5.png", nullptr),
TextureLoadOperation(GetResDirectory() / "tank" / "base6.png", nullptr),
TextureLoadOperation(GetResDirectory() / "tank" / "base7.png", nullptr),
TextureLoadOperation(GetResDirectory() / "tank" / "base8.png", nullptr) },
m_baseNormalsLoadOp(GetResDirectory() / "tank" / "base-normals.png", nullptr) { }
virtual void DoWork() override
{
for (TextureLoadOperation& loadOperation : m_baseDiffuseLoadOps)
loadOperation.DoWork();
m_baseNormalsLoadOp.DoWork();
}
virtual void ProcessResult() override
{
instance = std::make_unique<TankTextures>(m_baseDiffuseLoadOps[0].CreateTexture(),
m_baseDiffuseLoadOps[1].CreateTexture(), m_baseDiffuseLoadOps[2].CreateTexture(),
m_baseDiffuseLoadOps[3].CreateTexture(), m_baseDiffuseLoadOps[4].CreateTexture(),
m_baseDiffuseLoadOps[5].CreateTexture(), m_baseDiffuseLoadOps[6].CreateTexture(),
m_baseDiffuseLoadOps[7].CreateTexture(), m_baseDiffuseLoadOps[8].CreateTexture(),
m_baseNormalsLoadOp.CreateTexture());
}
private:
TextureLoadOperation m_baseDiffuseLoadOps[9];
TextureLoadOperation m_baseNormalsLoadOp;
};
TankTextures::TankTextures(Texture2D&& baseDiffuse0, Texture2D&& baseDiffuse1, Texture2D&& baseDiffuse2,
Texture2D&& baseDiffuse3, Texture2D&& baseDiffuse4, Texture2D&& baseDiffuse5,
Texture2D&& baseDiffuse6, Texture2D&& baseDiffuse7, Texture2D&& baseDiffuse8,
Texture2D&& baseNormals)
: m_baseDiffuse{ std::move(baseDiffuse0), std::move(baseDiffuse1), std::move(baseDiffuse2),
std::move(baseDiffuse3), std::move(baseDiffuse4), std::move(baseDiffuse5),
std::move(baseDiffuse6), std::move(baseDiffuse7), std::move(baseDiffuse8) },
m_baseNormals(std::move(baseNormals)),
m_baseMaterials{ SpriteMaterial(m_baseDiffuse[0], m_baseNormals, 1, 30),
SpriteMaterial(m_baseDiffuse[1], m_baseNormals, 1, 30),
SpriteMaterial(m_baseDiffuse[2], m_baseNormals, 1, 30),
SpriteMaterial(m_baseDiffuse[3], m_baseNormals, 1, 30),
SpriteMaterial(m_baseDiffuse[4], m_baseNormals, 1, 30),
SpriteMaterial(m_baseDiffuse[5], m_baseNormals, 1, 30),
SpriteMaterial(m_baseDiffuse[6], m_baseNormals, 1, 30),
SpriteMaterial(m_baseDiffuse[7], m_baseNormals, 1, 30),
SpriteMaterial(m_baseDiffuse[8], m_baseNormals, 1, 30)
}
{
for (Texture2D& texture : m_baseDiffuse)
texture.SetWrapMode(GL_CLAMP_TO_EDGE);
m_baseNormals.SetWrapMode(GL_CLAMP_TO_EDGE);
}
std::unique_ptr<IASyncOperation> TankTextures::CreateInstance()
{
if (instance != nullptr)
throw InvalidStateException("Tank textures already loaded.");
CallOnClose([] { instance = nullptr; });
return std::make_unique<TankTexturesLoadOperation>();
}
const TankTextures& TankTextures::GetInstance()
{ return *instance; }
}
| 49.035714
| 105
| 0.646759
|
Eae02
|
1cd2b5bee1b0b729cf337ab461287ad15a9185f9
| 46,483
|
cpp
|
C++
|
external/vsomeip/implementation/endpoints/src/tcp_server_endpoint_impl.cpp
|
lixiaolia/ndk-someip-lib
|
f4088e87f07e3a6bcec402514bb7ebb77ec946ce
|
[
"Apache-2.0"
] | 3
|
2021-06-17T14:01:04.000Z
|
2022-03-18T09:22:44.000Z
|
external/vsomeip/implementation/endpoints/src/tcp_server_endpoint_impl.cpp
|
lixiaolia/ndk-someip-lib
|
f4088e87f07e3a6bcec402514bb7ebb77ec946ce
|
[
"Apache-2.0"
] | 1
|
2022-03-15T06:21:33.000Z
|
2022-03-28T06:31:12.000Z
|
external/vsomeip/implementation/endpoints/src/tcp_server_endpoint_impl.cpp
|
lixiaolia/ndk-someip-lib
|
f4088e87f07e3a6bcec402514bb7ebb77ec946ce
|
[
"Apache-2.0"
] | 4
|
2021-06-17T14:12:18.000Z
|
2021-12-13T11:53:10.000Z
|
// Copyright (C) 2014-2017 Bayerische Motoren Werke Aktiengesellschaft (BMW AG)
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include <iomanip>
#include <boost/asio/write.hpp>
#include <vsomeip/constants.hpp>
#include <vsomeip/internal/logger.hpp>
#include "../include/endpoint_definition.hpp"
#include "../include/endpoint_host.hpp"
#include "../../routing/include/routing_host.hpp"
#include "../include/tcp_server_endpoint_impl.hpp"
#include "../../utility/include/utility.hpp"
#include "../../utility/include/byteorder.hpp"
namespace ip = boost::asio::ip;
namespace vsomeip_v3 {
tcp_server_endpoint_impl::tcp_server_endpoint_impl(
const std::shared_ptr<endpoint_host>& _endpoint_host,
const std::shared_ptr<routing_host>& _routing_host,
const endpoint_type& _local,
boost::asio::io_service &_io,
const std::shared_ptr<configuration>& _configuration)
: tcp_server_endpoint_base_impl(_endpoint_host, _routing_host, _local, _io,
_configuration->get_max_message_size_reliable(_local.address().to_string(), _local.port()),
_configuration->get_endpoint_queue_limit(_local.address().to_string(), _local.port()),
_configuration),
acceptor_(_io),
buffer_shrink_threshold_(configuration_->get_buffer_shrink_threshold()),
local_port_(_local.port()),
// send timeout after 2/3 of configured ttl, warning after 1/3
send_timeout_(configuration_->get_sd_ttl() * 666) {
is_supporting_magic_cookies_ = true;
boost::system::error_code ec;
acceptor_.open(_local.protocol(), ec);
boost::asio::detail::throw_error(ec, "acceptor open");
acceptor_.set_option(boost::asio::socket_base::reuse_address(true), ec);
boost::asio::detail::throw_error(ec, "acceptor set_option");
#ifndef _WIN32
// If specified, bind to device
std::string its_device(configuration_->get_device());
if (its_device != "") {
if (setsockopt(acceptor_.native_handle(),
SOL_SOCKET, SO_BINDTODEVICE, its_device.c_str(), (int)its_device.size()) == -1) {
VSOMEIP_WARNING << "TCP Server: Could not bind to device \"" << its_device << "\"";
}
}
#endif
acceptor_.bind(_local, ec);
boost::asio::detail::throw_error(ec, "acceptor bind");
acceptor_.listen(boost::asio::socket_base::max_connections, ec);
boost::asio::detail::throw_error(ec, "acceptor listen");
}
tcp_server_endpoint_impl::~tcp_server_endpoint_impl() {
}
bool tcp_server_endpoint_impl::is_local() const {
return false;
}
void tcp_server_endpoint_impl::start() {
std::lock_guard<std::mutex> its_lock(acceptor_mutex_);
if (acceptor_.is_open()) {
connection::ptr new_connection = connection::create(
std::dynamic_pointer_cast<tcp_server_endpoint_impl>(
shared_from_this()), max_message_size_,
buffer_shrink_threshold_, has_enabled_magic_cookies_,
service_, send_timeout_);
{
std::unique_lock<std::mutex> its_socket_lock(new_connection->get_socket_lock());
acceptor_.async_accept(new_connection->get_socket(),
std::bind(&tcp_server_endpoint_impl::accept_cbk,
std::dynamic_pointer_cast<tcp_server_endpoint_impl>(
shared_from_this()), new_connection,
std::placeholders::_1));
}
}
}
void tcp_server_endpoint_impl::stop() {
server_endpoint_impl::stop();
{
std::lock_guard<std::mutex> its_lock(acceptor_mutex_);
if(acceptor_.is_open()) {
boost::system::error_code its_error;
acceptor_.close(its_error);
}
}
{
std::lock_guard<std::mutex> its_lock(connections_mutex_);
for (const auto &c : connections_) {
c.second->stop();
}
connections_.clear();
}
}
bool tcp_server_endpoint_impl::send_to(
const std::shared_ptr<endpoint_definition> _target,
const byte_t *_data, uint32_t _size) {
std::lock_guard<std::mutex> its_lock(mutex_);
endpoint_type its_target(_target->get_address(), _target->get_port());
return send_intern(its_target, _data, _size);
}
bool tcp_server_endpoint_impl::send_error(
const std::shared_ptr<endpoint_definition> _target,
const byte_t *_data, uint32_t _size) {
bool ret(false);
std::lock_guard<std::mutex> its_lock(mutex_);
const endpoint_type its_target(_target->get_address(), _target->get_port());
const queue_iterator_type target_queue_iterator(find_or_create_queue_unlocked(its_target));
auto& its_qpair = target_queue_iterator->second;
const bool queue_size_zero_on_entry(its_qpair.second.empty());
if (check_message_size(nullptr, _size, its_target) == endpoint_impl::cms_ret_e::MSG_OK &&
check_queue_limit(_data, _size, its_qpair.first)) {
its_qpair.second.emplace_back(
std::make_shared<message_buffer_t>(_data, _data + _size));
its_qpair.first += _size;
if (queue_size_zero_on_entry) { // no writing in progress
send_queued(target_queue_iterator);
}
ret = true;
}
return ret;
}
void tcp_server_endpoint_impl::send_queued(const queue_iterator_type _queue_iterator) {
connection::ptr its_connection;
{
std::lock_guard<std::mutex> its_lock(connections_mutex_);
auto connection_iterator = connections_.find(_queue_iterator->first);
if (connection_iterator != connections_.end()) {
its_connection = connection_iterator->second;
} else {
VSOMEIP_INFO << "Didn't find connection: "
<< _queue_iterator->first.address().to_string() << ":" << std::dec
<< static_cast<std::uint16_t>(_queue_iterator->first.port())
<< " dropping outstanding messages (" << std::dec
<< _queue_iterator->second.second.size() << ").";
queues_.erase(_queue_iterator->first);
}
}
if (its_connection) {
its_connection->send_queued(_queue_iterator);
}
}
void tcp_server_endpoint_impl::get_configured_times_from_endpoint(
service_t _service, method_t _method,
std::chrono::nanoseconds *_debouncing,
std::chrono::nanoseconds *_maximum_retention) const {
configuration_->get_configured_timing_responses(_service,
tcp_server_endpoint_base_impl::local_.address().to_string(),
tcp_server_endpoint_base_impl::local_.port(), _method,
_debouncing, _maximum_retention);
}
bool tcp_server_endpoint_impl::is_established(const std::shared_ptr<endpoint_definition>& _endpoint) {
bool is_connected = false;
endpoint_type endpoint(_endpoint->get_address(), _endpoint->get_port());
{
std::lock_guard<std::mutex> its_lock(connections_mutex_);
auto connection_iterator = connections_.find(endpoint);
if (connection_iterator != connections_.end()) {
is_connected = true;
} else {
VSOMEIP_INFO << "Didn't find TCP connection: Subscription "
<< "rejected for: " << endpoint.address().to_string() << ":"
<< std::dec << static_cast<std::uint16_t>(endpoint.port());
}
}
return is_connected;
}
bool tcp_server_endpoint_impl::get_default_target(service_t,
tcp_server_endpoint_impl::endpoint_type &) const {
return false;
}
void tcp_server_endpoint_impl::remove_connection(
tcp_server_endpoint_impl::connection *_connection) {
std::lock_guard<std::mutex> its_lock(connections_mutex_);
for (auto it = connections_.begin(); it != connections_.end();) {
if (it->second.get() == _connection) {
it = connections_.erase(it);
break;
} else {
++it;
}
}
}
void tcp_server_endpoint_impl::accept_cbk(const connection::ptr& _connection,
boost::system::error_code const &_error) {
if (!_error) {
boost::system::error_code its_error;
endpoint_type remote;
{
std::unique_lock<std::mutex> its_socket_lock(_connection->get_socket_lock());
socket_type &new_connection_socket = _connection->get_socket();
remote = new_connection_socket.remote_endpoint(its_error);
_connection->set_remote_info(remote);
// Nagle algorithm off
new_connection_socket.set_option(ip::tcp::no_delay(true), its_error);
new_connection_socket.set_option(boost::asio::socket_base::keep_alive(true), its_error);
if (its_error) {
VSOMEIP_WARNING << "tcp_server_endpoint::connect: couldn't enable "
<< "keep_alive: " << its_error.message();
}
}
if (!its_error) {
{
std::lock_guard<std::mutex> its_lock(connections_mutex_);
connections_[remote] = _connection;
}
_connection->start();
}
}
if (_error != boost::asio::error::bad_descriptor
&& _error != boost::asio::error::operation_aborted
&& _error != boost::asio::error::no_descriptors) {
start();
} else if (_error == boost::asio::error::no_descriptors) {
VSOMEIP_ERROR<< "tcp_server_endpoint_impl::accept_cbk: "
<< _error.message() << " (" << std::dec << _error.value()
<< ") Will try to accept again in 1000ms";
std::shared_ptr<boost::asio::steady_timer> its_timer =
std::make_shared<boost::asio::steady_timer>(service_,
std::chrono::milliseconds(1000));
auto its_ep = std::dynamic_pointer_cast<tcp_server_endpoint_impl>(
shared_from_this());
its_timer->async_wait([its_timer, its_ep]
(const boost::system::error_code& _error) {
if (!_error) {
its_ep->start();
}
});
}
}
std::uint16_t tcp_server_endpoint_impl::get_local_port() const {
return local_port_;
}
bool tcp_server_endpoint_impl::is_reliable() const {
return true;
}
///////////////////////////////////////////////////////////////////////////////
// class tcp_service_impl::connection
///////////////////////////////////////////////////////////////////////////////
tcp_server_endpoint_impl::connection::connection(
const std::weak_ptr<tcp_server_endpoint_impl>& _server,
std::uint32_t _max_message_size,
std::uint32_t _recv_buffer_size_initial,
std::uint32_t _buffer_shrink_threshold,
bool _magic_cookies_enabled,
boost::asio::io_service &_io_service,
std::chrono::milliseconds _send_timeout) :
socket_(_io_service),
server_(_server),
max_message_size_(_max_message_size),
recv_buffer_size_initial_(_recv_buffer_size_initial),
recv_buffer_(_recv_buffer_size_initial, 0),
recv_buffer_size_(0),
missing_capacity_(0),
shrink_count_(0),
buffer_shrink_threshold_(_buffer_shrink_threshold),
remote_port_(0),
magic_cookies_enabled_(_magic_cookies_enabled),
last_cookie_sent_(std::chrono::steady_clock::now() - std::chrono::seconds(11)),
send_timeout_(_send_timeout),
send_timeout_warning_(_send_timeout / 2) {
}
tcp_server_endpoint_impl::connection::ptr
tcp_server_endpoint_impl::connection::create(
const std::weak_ptr<tcp_server_endpoint_impl>& _server,
std::uint32_t _max_message_size,
std::uint32_t _buffer_shrink_threshold,
bool _magic_cookies_enabled,
boost::asio::io_service & _io_service,
std::chrono::milliseconds _send_timeout) {
const std::uint32_t its_initial_receveive_buffer_size =
VSOMEIP_SOMEIP_HEADER_SIZE + 8 + MAGIC_COOKIE_SIZE + 8;
return ptr(new connection(_server, _max_message_size,
its_initial_receveive_buffer_size,
_buffer_shrink_threshold, _magic_cookies_enabled,
_io_service, _send_timeout));
}
tcp_server_endpoint_impl::socket_type &
tcp_server_endpoint_impl::connection::get_socket() {
return socket_;
}
std::unique_lock<std::mutex>
tcp_server_endpoint_impl::connection::get_socket_lock() {
return std::unique_lock<std::mutex>(socket_mutex_);
}
void tcp_server_endpoint_impl::connection::start() {
receive();
}
void tcp_server_endpoint_impl::connection::receive() {
std::lock_guard<std::mutex> its_lock(socket_mutex_);
if(socket_.is_open()) {
const std::size_t its_capacity(recv_buffer_.capacity());
size_t buffer_size = its_capacity - recv_buffer_size_;
try {
if (missing_capacity_) {
if (missing_capacity_ > MESSAGE_SIZE_UNLIMITED) {
VSOMEIP_ERROR << "Missing receive buffer capacity exceeds allowed maximum!";
return;
}
const std::size_t its_required_capacity(recv_buffer_size_ + missing_capacity_);
if (its_capacity < its_required_capacity) {
recv_buffer_.reserve(its_required_capacity);
recv_buffer_.resize(its_required_capacity, 0x0);
if (recv_buffer_.size() > 1048576) {
VSOMEIP_INFO << "tse: recv_buffer size is: " <<
recv_buffer_.size()
<< " local: " << get_address_port_local()
<< " remote: " << get_address_port_remote();
}
}
buffer_size = missing_capacity_;
missing_capacity_ = 0;
} else if (buffer_shrink_threshold_
&& shrink_count_ > buffer_shrink_threshold_
&& recv_buffer_size_ == 0) {
recv_buffer_.resize(recv_buffer_size_initial_, 0x0);
recv_buffer_.shrink_to_fit();
buffer_size = recv_buffer_size_initial_;
shrink_count_ = 0;
}
} catch (const std::exception &e) {
handle_recv_buffer_exception(e);
// don't start receiving again
return;
}
socket_.async_receive(boost::asio::buffer(&recv_buffer_[recv_buffer_size_], buffer_size),
std::bind(&tcp_server_endpoint_impl::connection::receive_cbk,
shared_from_this(), std::placeholders::_1,
std::placeholders::_2));
}
}
void tcp_server_endpoint_impl::connection::stop() {
std::lock_guard<std::mutex> its_lock(socket_mutex_);
if (socket_.is_open()) {
boost::system::error_code its_error;
socket_.shutdown(socket_.shutdown_both, its_error);
socket_.close(its_error);
}
}
void tcp_server_endpoint_impl::connection::send_queued(
const queue_iterator_type _queue_iterator) {
std::shared_ptr<tcp_server_endpoint_impl> its_server(server_.lock());
if (!its_server) {
VSOMEIP_TRACE << "tcp_server_endpoint_impl::connection::send_queued "
" couldn't lock server_";
return;
}
message_buffer_ptr_t its_buffer = _queue_iterator->second.second.front();
const service_t its_service = VSOMEIP_BYTES_TO_WORD(
(*its_buffer)[VSOMEIP_SERVICE_POS_MIN],
(*its_buffer)[VSOMEIP_SERVICE_POS_MAX]);
const method_t its_method = VSOMEIP_BYTES_TO_WORD(
(*its_buffer)[VSOMEIP_METHOD_POS_MIN],
(*its_buffer)[VSOMEIP_METHOD_POS_MAX]);
const client_t its_client = VSOMEIP_BYTES_TO_WORD(
(*its_buffer)[VSOMEIP_CLIENT_POS_MIN],
(*its_buffer)[VSOMEIP_CLIENT_POS_MAX]);
const session_t its_session = VSOMEIP_BYTES_TO_WORD(
(*its_buffer)[VSOMEIP_SESSION_POS_MIN],
(*its_buffer)[VSOMEIP_SESSION_POS_MAX]);
if (magic_cookies_enabled_) {
const std::chrono::steady_clock::time_point now =
std::chrono::steady_clock::now();
if (std::chrono::duration_cast<std::chrono::milliseconds>(
now - last_cookie_sent_) > std::chrono::milliseconds(10000)) {
if (send_magic_cookie(its_buffer)) {
last_cookie_sent_ = now;
_queue_iterator->second.first += sizeof(SERVICE_COOKIE);
}
}
}
{
std::lock_guard<std::mutex> its_lock(socket_mutex_);
{
std::lock_guard<std::mutex> its_sent_lock(its_server->sent_mutex_);
its_server->is_sending_ = true;
}
boost::asio::async_write(socket_, boost::asio::buffer(*its_buffer),
std::bind(&tcp_server_endpoint_impl::connection::write_completion_condition,
shared_from_this(),
std::placeholders::_1,
std::placeholders::_2,
its_buffer->size(),
its_service, its_method, its_client, its_session,
std::chrono::steady_clock::now()),
std::bind(&tcp_server_endpoint_base_impl::send_cbk,
its_server,
_queue_iterator,
std::placeholders::_1,
std::placeholders::_2));
}
}
void tcp_server_endpoint_impl::connection::send_queued_sync(
const queue_iterator_type _queue_iterator) {
message_buffer_ptr_t its_buffer = _queue_iterator->second.second.front();
if (magic_cookies_enabled_) {
const std::chrono::steady_clock::time_point now =
std::chrono::steady_clock::now();
if (std::chrono::duration_cast<std::chrono::milliseconds>(
now - last_cookie_sent_) > std::chrono::milliseconds(10000)) {
if (send_magic_cookie(its_buffer)) {
last_cookie_sent_ = now;
_queue_iterator->second.first += sizeof(SERVICE_COOKIE);
}
}
}
try {
std::lock_guard<std::mutex> its_lock(socket_mutex_);
boost::asio::write(socket_, boost::asio::buffer(*its_buffer));
} catch (const boost::system::system_error &e) {
if (e.code() != boost::asio::error::broken_pipe) {
VSOMEIP_ERROR << "tcp_server_endpoint_impl::connection::"
<< __func__ << " " << e.what();
}
}
}
bool tcp_server_endpoint_impl::connection::send_magic_cookie(
message_buffer_ptr_t &_buffer) {
if (max_message_size_ == MESSAGE_SIZE_UNLIMITED
|| max_message_size_ - _buffer->size() >=
VSOMEIP_SOMEIP_HEADER_SIZE + VSOMEIP_SOMEIP_MAGIC_COOKIE_SIZE) {
_buffer->insert(_buffer->begin(), SERVICE_COOKIE,
SERVICE_COOKIE + sizeof(SERVICE_COOKIE));
return true;
}
return false;
}
bool tcp_server_endpoint_impl::connection::is_magic_cookie(size_t _offset) const {
return (0 == std::memcmp(CLIENT_COOKIE, &recv_buffer_[_offset],
sizeof(CLIENT_COOKIE)));
}
void tcp_server_endpoint_impl::connection::receive_cbk(
boost::system::error_code const &_error,
std::size_t _bytes) {
if (_error == boost::asio::error::operation_aborted) {
// endpoint was stopped
return;
}
std::shared_ptr<tcp_server_endpoint_impl> its_server(server_.lock());
if (!its_server) {
VSOMEIP_ERROR << "tcp_server_endpoint_impl::connection::receive_cbk "
" couldn't lock server_";
return;
}
#if 0
std::stringstream msg;
for (std::size_t i = 0; i < _bytes + recv_buffer_size_; ++i)
msg << std::hex << std::setw(2) << std::setfill('0')
<< (int) recv_buffer_[i] << " ";
VSOMEIP_INFO << msg.str();
#endif
std::shared_ptr<routing_host> its_host = its_server->routing_host_.lock();
if (its_host) {
if (!_error && 0 < _bytes) {
if (recv_buffer_size_ + _bytes < recv_buffer_size_) {
VSOMEIP_ERROR << "receive buffer overflow in tcp client endpoint ~> abort!";
return;
}
recv_buffer_size_ += _bytes;
size_t its_iteration_gap = 0;
bool has_full_message;
do {
uint64_t read_message_size
= utility::get_message_size(&recv_buffer_[its_iteration_gap],
recv_buffer_size_);
if (read_message_size > MESSAGE_SIZE_UNLIMITED) {
VSOMEIP_ERROR << "Message size exceeds allowed maximum!";
return;
}
uint32_t current_message_size = static_cast<uint32_t>(read_message_size);
has_full_message = (current_message_size > VSOMEIP_RETURN_CODE_POS
&& current_message_size <= recv_buffer_size_);
if (has_full_message) {
bool needs_forwarding(true);
if (is_magic_cookie(its_iteration_gap)) {
magic_cookies_enabled_ = true;
} else {
if (magic_cookies_enabled_) {
uint32_t its_offset
= its_server->find_magic_cookie(&recv_buffer_[its_iteration_gap],
recv_buffer_size_);
if (its_offset < current_message_size) {
{
std::lock_guard<std::mutex> its_lock(socket_mutex_);
VSOMEIP_ERROR << "Detected Magic Cookie within message data. Resyncing."
<< " local: " << get_address_port_local()
<< " remote: " << get_address_port_remote();
}
if (!is_magic_cookie(its_iteration_gap)) {
auto its_endpoint_host = its_server->endpoint_host_.lock();
if (its_endpoint_host) {
its_endpoint_host->on_error(&recv_buffer_[its_iteration_gap],
static_cast<length_t>(recv_buffer_size_),its_server.get(),
remote_address_, remote_port_);
}
}
current_message_size = its_offset;
needs_forwarding = false;
}
}
}
if (needs_forwarding) {
if (utility::is_request(
recv_buffer_[its_iteration_gap
+ VSOMEIP_MESSAGE_TYPE_POS])) {
const client_t its_client = VSOMEIP_BYTES_TO_WORD(
recv_buffer_[its_iteration_gap + VSOMEIP_CLIENT_POS_MIN],
recv_buffer_[its_iteration_gap + VSOMEIP_CLIENT_POS_MAX]);
if (its_client != MAGIC_COOKIE_CLIENT) {
const session_t its_session = VSOMEIP_BYTES_TO_WORD(
recv_buffer_[its_iteration_gap + VSOMEIP_SESSION_POS_MIN],
recv_buffer_[its_iteration_gap + VSOMEIP_SESSION_POS_MAX]);
its_server->clients_mutex_.lock();
its_server->clients_[its_client][its_session] = remote_;
its_server->clients_mutex_.unlock();
}
}
if (!magic_cookies_enabled_) {
its_host->on_message(&recv_buffer_[its_iteration_gap],
current_message_size, its_server.get(),
boost::asio::ip::address(),
VSOMEIP_ROUTING_CLIENT,
std::make_pair(ANY_UID, ANY_GID),
remote_address_, remote_port_);
} else {
// Only call on_message without a magic cookie in front of the buffer!
if (!is_magic_cookie(its_iteration_gap)) {
its_host->on_message(&recv_buffer_[its_iteration_gap],
current_message_size, its_server.get(),
boost::asio::ip::address(),
VSOMEIP_ROUTING_CLIENT,
std::make_pair(ANY_UID, ANY_GID),
remote_address_, remote_port_);
}
}
}
calculate_shrink_count();
missing_capacity_ = 0;
recv_buffer_size_ -= current_message_size;
its_iteration_gap += current_message_size;
} else if (magic_cookies_enabled_ && recv_buffer_size_ > 0) {
uint32_t its_offset =
its_server->find_magic_cookie(&recv_buffer_[its_iteration_gap],
recv_buffer_size_);
if (its_offset < recv_buffer_size_) {
{
std::lock_guard<std::mutex> its_lock(socket_mutex_);
VSOMEIP_ERROR << "Detected Magic Cookie within message data. Resyncing."
<< " local: " << get_address_port_local()
<< " remote: " << get_address_port_remote();
}
if (!is_magic_cookie(its_iteration_gap)) {
auto its_endpoint_host = its_server->endpoint_host_.lock();
if (its_endpoint_host) {
its_endpoint_host->on_error(&recv_buffer_[its_iteration_gap],
static_cast<length_t>(recv_buffer_size_), its_server.get(),
remote_address_, remote_port_);
}
}
recv_buffer_size_ -= its_offset;
its_iteration_gap += its_offset;
has_full_message = true; // trigger next loop
if (!is_magic_cookie(its_iteration_gap)) {
auto its_endpoint_host = its_server->endpoint_host_.lock();
if (its_endpoint_host) {
its_endpoint_host->on_error(&recv_buffer_[its_iteration_gap],
static_cast<length_t>(recv_buffer_size_), its_server.get(),
remote_address_, remote_port_);
}
}
}
}
if (!has_full_message) {
if (recv_buffer_size_ > VSOMEIP_RETURN_CODE_POS &&
(recv_buffer_[its_iteration_gap + VSOMEIP_PROTOCOL_VERSION_POS] != VSOMEIP_PROTOCOL_VERSION ||
!utility::is_valid_message_type(static_cast<message_type_e>(recv_buffer_[its_iteration_gap + VSOMEIP_MESSAGE_TYPE_POS])) ||
!utility::is_valid_return_code(static_cast<return_code_e>(recv_buffer_[its_iteration_gap + VSOMEIP_RETURN_CODE_POS]))
)) {
if (recv_buffer_[its_iteration_gap + VSOMEIP_PROTOCOL_VERSION_POS] != VSOMEIP_PROTOCOL_VERSION) {
{
std::lock_guard<std::mutex> its_lock(socket_mutex_);
VSOMEIP_ERROR << "tse: Wrong protocol version: 0x"
<< std::hex << std::setw(2) << std::setfill('0')
<< std::uint32_t(recv_buffer_[its_iteration_gap + VSOMEIP_PROTOCOL_VERSION_POS])
<< " local: " << get_address_port_local()
<< " remote: " << get_address_port_remote()
<< ". Closing connection due to missing/broken data TCP stream.";
}
// ensure to send back a error message w/ wrong protocol version
its_host->on_message(&recv_buffer_[its_iteration_gap],
VSOMEIP_SOMEIP_HEADER_SIZE + 8, its_server.get(),
boost::asio::ip::address(),
VSOMEIP_ROUTING_CLIENT,
std::make_pair(ANY_UID, ANY_GID),
remote_address_, remote_port_);
} else if (!utility::is_valid_message_type(static_cast<message_type_e>(
recv_buffer_[its_iteration_gap + VSOMEIP_MESSAGE_TYPE_POS]))) {
std::lock_guard<std::mutex> its_lock(socket_mutex_);
VSOMEIP_ERROR << "tse: Invalid message type: 0x"
<< std::hex << std::setw(2) << std::setfill('0')
<< std::uint32_t(recv_buffer_[its_iteration_gap + VSOMEIP_MESSAGE_TYPE_POS])
<< " local: " << get_address_port_local()
<< " remote: " << get_address_port_remote()
<< ". Closing connection due to missing/broken data TCP stream.";
} else if (!utility::is_valid_return_code(static_cast<return_code_e>(
recv_buffer_[its_iteration_gap + VSOMEIP_RETURN_CODE_POS]))) {
std::lock_guard<std::mutex> its_lock(socket_mutex_);
VSOMEIP_ERROR << "tse: Invalid return code: 0x"
<< std::hex << std::setw(2) << std::setfill('0')
<< std::uint32_t(recv_buffer_[its_iteration_gap + VSOMEIP_RETURN_CODE_POS])
<< " local: " << get_address_port_local()
<< " remote: " << get_address_port_remote()
<< ". Closing connection due to missing/broken data TCP stream.";
}
wait_until_sent(boost::asio::error::operation_aborted);
return;
} else if (max_message_size_ != MESSAGE_SIZE_UNLIMITED
&& current_message_size > max_message_size_) {
recv_buffer_size_ = 0;
recv_buffer_.resize(recv_buffer_size_initial_, 0x0);
recv_buffer_.shrink_to_fit();
if (magic_cookies_enabled_) {
std::lock_guard<std::mutex> its_lock(socket_mutex_);
VSOMEIP_ERROR << "Received a TCP message which exceeds "
<< "maximum message size ("
<< std::dec << current_message_size
<< " > " << std::dec << max_message_size_
<< "). Magic Cookies are enabled: "
<< "Resetting receiver. local: "
<< get_address_port_local() << " remote: "
<< get_address_port_remote();
} else {
{
std::lock_guard<std::mutex> its_lock(socket_mutex_);
VSOMEIP_ERROR << "Received a TCP message which exceeds "
<< "maximum message size ("
<< std::dec << current_message_size
<< " > " << std::dec << max_message_size_
<< ") Magic cookies are disabled: "
<< "Connection will be closed! local: "
<< get_address_port_local() << " remote: "
<< get_address_port_remote();
}
wait_until_sent(boost::asio::error::operation_aborted);
return;
}
} else if (current_message_size > recv_buffer_size_) {
missing_capacity_ = current_message_size
- static_cast<std::uint32_t>(recv_buffer_size_);
} else if (VSOMEIP_SOMEIP_HEADER_SIZE > recv_buffer_size_) {
missing_capacity_ = VSOMEIP_SOMEIP_HEADER_SIZE
- static_cast<std::uint32_t>(recv_buffer_size_);
} else if (magic_cookies_enabled_ && recv_buffer_size_ > 0) {
// no need to check for magic cookie here again: has_full_message
// would have been set to true if there was one present in the data
recv_buffer_size_ = 0;
recv_buffer_.resize(recv_buffer_size_initial_, 0x0);
recv_buffer_.shrink_to_fit();
missing_capacity_ = 0;
std::lock_guard<std::mutex> its_lock(socket_mutex_);
VSOMEIP_ERROR << "Didn't find magic cookie in broken"
<< " data, trying to resync."
<< " local: " << get_address_port_local()
<< " remote: " << get_address_port_remote();
} else {
{
std::lock_guard<std::mutex> its_lock(socket_mutex_);
VSOMEIP_ERROR << "tse::c<" << this
<< ">rcb: recv_buffer_size is: " << std::dec
<< recv_buffer_size_ << " but couldn't read "
"out message_size. recv_buffer_capacity: "
<< recv_buffer_.capacity()
<< " its_iteration_gap: " << its_iteration_gap
<< "local: " << get_address_port_local()
<< " remote: " << get_address_port_remote()
<< ". Closing connection due to missing/broken data TCP stream.";
}
wait_until_sent(boost::asio::error::operation_aborted);
return;
}
}
} while (has_full_message && recv_buffer_size_);
if (its_iteration_gap) {
// Copy incomplete message to front for next receive_cbk iteration
for (size_t i = 0; i < recv_buffer_size_; ++i) {
recv_buffer_[i] = recv_buffer_[i + its_iteration_gap];
}
// Still more capacity needed after shifting everything to front?
if (missing_capacity_ &&
missing_capacity_ <= recv_buffer_.capacity() - recv_buffer_size_) {
missing_capacity_ = 0;
}
}
receive();
}
}
if (_error == boost::asio::error::eof
|| _error == boost::asio::error::connection_reset
|| _error == boost::asio::error::timed_out) {
if(_error == boost::asio::error::timed_out) {
std::lock_guard<std::mutex> its_lock(socket_mutex_);
VSOMEIP_WARNING << "tcp_server_endpoint receive_cbk: " << _error.message()
<< " local: " << get_address_port_local()
<< " remote: " << get_address_port_remote();
}
wait_until_sent(boost::asio::error::operation_aborted);
}
}
void tcp_server_endpoint_impl::connection::calculate_shrink_count() {
if (buffer_shrink_threshold_) {
if (recv_buffer_.capacity() != recv_buffer_size_initial_) {
if (recv_buffer_size_ < (recv_buffer_.capacity() >> 1)) {
shrink_count_++;
} else {
shrink_count_ = 0;
}
}
}
}
void tcp_server_endpoint_impl::connection::set_remote_info(
const endpoint_type &_remote) {
remote_ = _remote;
remote_address_ = _remote.address();
remote_port_ = _remote.port();
}
const std::string tcp_server_endpoint_impl::connection::get_address_port_remote() const {
std::string its_address_port;
its_address_port.reserve(21);
boost::system::error_code ec;
its_address_port += remote_address_.to_string(ec);
its_address_port += ":";
its_address_port += std::to_string(remote_port_);
return its_address_port;
}
const std::string tcp_server_endpoint_impl::connection::get_address_port_local() const {
std::string its_address_port;
its_address_port.reserve(21);
boost::system::error_code ec;
if (socket_.is_open()) {
endpoint_type its_local_endpoint = socket_.local_endpoint(ec);
if (!ec) {
its_address_port += its_local_endpoint.address().to_string(ec);
its_address_port += ":";
its_address_port += std::to_string(its_local_endpoint.port());
}
}
return its_address_port;
}
void tcp_server_endpoint_impl::connection::handle_recv_buffer_exception(
const std::exception &_e) {
std::stringstream its_message;
its_message <<"tcp_server_endpoint_impl::connection catched exception"
<< _e.what() << " local: " << get_address_port_local()
<< " remote: " << get_address_port_remote()
<< " shutting down connection. Start of buffer: ";
for (std::size_t i = 0; i < recv_buffer_size_ && i < 16; i++) {
its_message << std::setw(2) << std::setfill('0') << std::hex
<< (int) (recv_buffer_[i]) << " ";
}
its_message << " Last 16 Bytes captured: ";
for (int i = 15; recv_buffer_size_ > 15 && i >= 0; i--) {
its_message << std::setw(2) << std::setfill('0') << std::hex
<< (int) (recv_buffer_[static_cast<size_t>(i)]) << " ";
}
VSOMEIP_ERROR << its_message.str();
recv_buffer_.clear();
if (socket_.is_open()) {
boost::system::error_code its_error;
socket_.shutdown(socket_.shutdown_both, its_error);
socket_.close(its_error);
}
std::shared_ptr<tcp_server_endpoint_impl> its_server = server_.lock();
if (its_server) {
its_server->remove_connection(this);
}
}
std::size_t
tcp_server_endpoint_impl::connection::get_recv_buffer_capacity() const {
return recv_buffer_.capacity();
}
std::size_t
tcp_server_endpoint_impl::connection::write_completion_condition(
const boost::system::error_code& _error,
std::size_t _bytes_transferred, std::size_t _bytes_to_send,
service_t _service, method_t _method, client_t _client, session_t _session,
const std::chrono::steady_clock::time_point _start) {
if (_error) {
VSOMEIP_ERROR << "tse::write_completion_condition: "
<< _error.message() << "(" << std::dec << _error.value()
<< ") bytes transferred: " << std::dec << _bytes_transferred
<< " bytes to sent: " << std::dec << _bytes_to_send << " "
<< "remote:" << get_address_port_remote() << " ("
<< std::hex << std::setw(4) << std::setfill('0') << _client <<"): ["
<< std::hex << std::setw(4) << std::setfill('0') << _service << "."
<< std::hex << std::setw(4) << std::setfill('0') << _method << "."
<< std::hex << std::setw(4) << std::setfill('0') << _session << "]";
stop_and_remove_connection();
return 0;
}
const std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
const std::chrono::milliseconds passed = std::chrono::duration_cast<std::chrono::milliseconds>(now - _start);
if (passed > send_timeout_warning_) {
if (passed > send_timeout_) {
VSOMEIP_ERROR << "tse::write_completion_condition: "
<< _error.message() << "(" << std::dec << _error.value()
<< ") took longer than " << std::dec << send_timeout_.count()
<< "ms bytes transferred: " << std::dec << _bytes_transferred
<< " bytes to sent: " << std::dec << _bytes_to_send
<< " remote:" << get_address_port_remote() << " ("
<< std::hex << std::setw(4) << std::setfill('0') << _client <<"): ["
<< std::hex << std::setw(4) << std::setfill('0') << _service << "."
<< std::hex << std::setw(4) << std::setfill('0') << _method << "."
<< std::hex << std::setw(4) << std::setfill('0') << _session << "]";
} else {
VSOMEIP_WARNING << "tse::write_completion_condition: "
<< _error.message() << "(" << std::dec << _error.value()
<< ") took longer than " << std::dec << send_timeout_warning_.count()
<< "ms bytes transferred: " << std::dec << _bytes_transferred
<< " bytes to sent: " << std::dec << _bytes_to_send
<< " remote:" << get_address_port_remote() << " ("
<< std::hex << std::setw(4) << std::setfill('0') << _client <<"): ["
<< std::hex << std::setw(4) << std::setfill('0') << _service << "."
<< std::hex << std::setw(4) << std::setfill('0') << _method << "."
<< std::hex << std::setw(4) << std::setfill('0') << _session << "]";
}
}
return _bytes_to_send - _bytes_transferred;
}
void tcp_server_endpoint_impl::connection::stop_and_remove_connection() {
std::shared_ptr<tcp_server_endpoint_impl> its_server(server_.lock());
if (!its_server) {
VSOMEIP_ERROR << "tse::connection::stop_and_remove_connection "
" couldn't lock server_";
return;
}
{
std::lock_guard<std::mutex> its_lock(its_server->connections_mutex_);
stop();
}
its_server->remove_connection(this);
}
// Dummies
void tcp_server_endpoint_impl::receive() {
// intentionally left empty
}
void tcp_server_endpoint_impl::print_status() {
std::lock_guard<std::mutex> its_lock(mutex_);
connections_t its_connections;
{
std::lock_guard<std::mutex> its_lock(connections_mutex_);
its_connections = connections_;
}
VSOMEIP_INFO << "status tse: " << std::dec << local_port_
<< " connections: " << std::dec << its_connections.size()
<< " queues: " << std::dec << queues_.size();
for (const auto &c : its_connections) {
std::size_t its_data_size(0);
std::size_t its_queue_size(0);
std::size_t its_recv_size(0);
{
std::unique_lock<std::mutex> c_s_lock(c.second->get_socket_lock());
its_recv_size = c.second->get_recv_buffer_capacity();
}
auto found_queue = queues_.find(c.first);
if (found_queue != queues_.end()) {
its_queue_size = found_queue->second.second.size();
its_data_size = found_queue->second.first;
}
VSOMEIP_INFO << "status tse: client: "
<< c.second->get_address_port_remote()
<< " queue: " << std::dec << its_queue_size
<< " data: " << std::dec << its_data_size
<< " recv_buffer: " << std::dec << its_recv_size;
}
}
std::string tcp_server_endpoint_impl::get_remote_information(
const queue_iterator_type _queue_iterator) const {
boost::system::error_code ec;
return _queue_iterator->first.address().to_string(ec) + ":"
+ std::to_string(_queue_iterator->first.port());
}
std::string tcp_server_endpoint_impl::get_remote_information(
const endpoint_type& _remote) const {
boost::system::error_code ec;
return _remote.address().to_string(ec) + ":"
+ std::to_string(_remote.port());
}
bool tcp_server_endpoint_impl::tp_segmentation_enabled(service_t _service,
method_t _method) const {
(void)_service;
(void)_method;
return false;
}
void tcp_server_endpoint_impl::connection::wait_until_sent(const boost::system::error_code &_error) {
std::shared_ptr<tcp_server_endpoint_impl> its_server(server_.lock());
std::unique_lock<std::mutex> its_sent_lock(its_server->sent_mutex_);
if (!its_server->is_sending_ || !_error) {
its_sent_lock.unlock();
if (!_error)
VSOMEIP_WARNING << __func__
<< ": Maximum wait time for send operation exceeded for tse.";
{
std::lock_guard<std::mutex> its_lock(its_server->connections_mutex_);
stop();
}
its_server->remove_connection(this);
} else {
std::chrono::milliseconds its_timeout(VSOMEIP_MAX_TCP_SENT_WAIT_TIME);
boost::system::error_code ec;
its_server->sent_timer_.expires_from_now(its_timeout, ec);
its_server->sent_timer_.async_wait(std::bind(&tcp_server_endpoint_impl::connection::wait_until_sent,
std::dynamic_pointer_cast<tcp_server_endpoint_impl::connection>(shared_from_this()),
std::placeholders::_1));
}
}
} // namespace vsomeip_v3
| 47.383282
| 148
| 0.553557
|
lixiaolia
|
1cdb59d29336c26315412dcf45704dbc2251c68b
| 4,803
|
cc
|
C++
|
deps/smmr/example/client_server/client_server.cc
|
xflagstudio/network-bfd-sample
|
89a21dd7ff195527fd8c3ce811ed0520acaac6b5
|
[
"MIT"
] | 6
|
2017-03-24T08:37:39.000Z
|
2020-07-24T08:08:30.000Z
|
deps/smmr/example/client_server/client_server.cc
|
xflagstudio/network-bfd-sample
|
89a21dd7ff195527fd8c3ce811ed0520acaac6b5
|
[
"MIT"
] | null | null | null |
deps/smmr/example/client_server/client_server.cc
|
xflagstudio/network-bfd-sample
|
89a21dd7ff195527fd8c3ce811ed0520acaac6b5
|
[
"MIT"
] | 2
|
2017-07-17T03:25:34.000Z
|
2019-06-09T18:14:15.000Z
|
#include "smmr_pagedbuffer.h"
#include "smmr_categories.h"
#include "smmr_memory.h"
#include "smmr_database.h"
#include "smmr_tree.h"
#include <sys/types.h>
#include <sys/wait.h>
#define UNUSED(x) (void)(x)
const char *SERVER_MSGKEY = "from_server_to_client";
char SERVER_HELLOW[] = "hellow client.";
const char *CLIENT_MSGKEY = "from_client_to_server";
char CLIENT_HELLOW[] = "hi server.";
#define CLIENT_TO (10)
// -----------------------
// クライアント
// -----------------------
static void do_client(void){
//
ipcshm_categories_ptr CATEGORIES_C = (ipcshm_categories_ptr)-1;
ipcshm_datafiles_ptr DATAFILES_C = (ipcshm_datafiles_ptr)-1;
datafiles_on_process_t DATAFILES_INDEX_C;
categories_on_process_t CATEGORIES_INDEX_C;
tree_instance_ptr ROOT_C;
printf("client\n");
//
if (childinit_categories_area(&CATEGORIES_C,&CATEGORIES_INDEX_C) != RET_OK){ exit(1); }
if (childinit_db_area(&DATAFILES_C,&DATAFILES_INDEX_C) != RET_OK){ exit(3); }
// インデックス ルートオブジェクト構築
ROOT_C = create_tree_unsafe(CATEGORIES_C,&CATEGORIES_INDEX_C);
if (!ROOT_C){ exit(2); }
// サーバメッセージを読み取る
char *resp = NULL;
uint32_t resplen = 0;
//
if (search(DATAFILES_C,&DATAFILES_INDEX_C,ROOT_C,SERVER_MSGKEY,strlen(SERVER_MSGKEY),&resp,&resplen) == RET_OK){
if (resp && resplen){
printf("from server .. %s == %s\n", SERVER_HELLOW, resp);
}else{
fprintf(stderr, "failed.search.:resp(%s)\n", SERVER_MSGKEY);
}
}else{
fprintf(stderr, "failed.search.(%s)\n", SERVER_MSGKEY);
}
// ack to server
if (store(DATAFILES_C,&DATAFILES_INDEX_C,ROOT_C,CLIENT_MSGKEY,strlen(CLIENT_MSGKEY),CLIENT_HELLOW,strlen(CLIENT_HELLOW),0)!= RET_OK){
fprintf(stderr, "failed.store.(%s)\n", CLIENT_MSGKEY);
}
// 子プロセスでリソース解放
if (childuninit_db_area(&DATAFILES_C,&DATAFILES_INDEX_C) != RET_OK){ exit(4); }
if (ROOT_C != NULL){
free(ROOT_C);
}
ROOT_C = NULL;
if (childuninit_categories_area(&CATEGORIES_C,&CATEGORIES_INDEX_C) != RET_OK){ exit(5); }
printf("client-completed.\n");
}
// -----------------------
// サーバ
// -----------------------
static void do_server(pid_t pid){
printf("server\n");
//
ipcshm_categories_ptr CATEGORIES = (ipcshm_categories_ptr)-1;
ipcshm_datafiles_ptr DATAFILES = (ipcshm_datafiles_ptr)-1;
datafiles_on_process_t DATAFILES_INDEX;
categories_on_process_t CATEGORIES_INDEX;
tree_instance_ptr ROOT;
int cstat = 0;
int timeout = 0;
char index_dir[128] = {0},data_dir[128] = {0};
snprintf(index_dir,sizeof(index_dir)-1,"/tmp/%u/", (unsigned)getpid());
mkdir(index_dir,0755);
snprintf(data_dir,sizeof(data_dir)-1,"/tmp/%u/db/", (unsigned)getpid());
mkdir(data_dir,0755);
// システム初期化
// サーバプロセスでインデクス初期化
if (create_categories_area(index_dir,&CATEGORIES,&CATEGORIES_INDEX) != RET_OK){ exit(1); }
if (init_categories_from_file(CATEGORIES,&CATEGORIES_INDEX,0) != RET_OK){ exit(1); }
if (rebuild_pages_area(&CATEGORIES_INDEX) != RET_OK){ exit(1); }
// サーバプロセスでデータファイル初期化
if (create_db_area_parent(data_dir,&DATAFILES) != RET_OK){ exit(1); }
if (init_datafiles_from_file(DATAFILES,&DATAFILES_INDEX) != RET_OK){ exit(1); }
// ツリールート
if ((ROOT = create_tree_unsafe(CATEGORIES,&CATEGORIES_INDEX)) ==NULL){ exit(1); }
// サーバでデータを書き込み
if (store(DATAFILES,&DATAFILES_INDEX,ROOT,SERVER_MSGKEY,strlen(SERVER_MSGKEY),SERVER_HELLOW,strlen(SERVER_HELLOW),0)!= RET_OK){ exit(1); }
// クライアントのデータ書き込みを待機
for(timeout=0;timeout < CLIENT_TO;timeout++){
char *resp = NULL;
uint32_t resplen = 0;
sleep(1);
if (search(DATAFILES,&DATAFILES_INDEX,ROOT,CLIENT_MSGKEY,strlen(CLIENT_MSGKEY),&resp,&resplen) == RET_OK){
if (resp && resplen){
printf("%s -> %s\n",CLIENT_MSGKEY, resp);
free(resp);
}
break;
}
fprintf(stderr, "nothing client. responce...(%d)\n", timeout);
}
if (timeout >= CLIENT_TO){
fprintf(stderr, "timeout client. responce...\n");
}
// parent
pid_t pidr = waitpid(pid, &cstat, 0);
printf("waitpid(for client complete) /%d -> %d : %d\n",pid ,pidr, cstat);
// システム終了処理
if (remove_db_area_parent(&DATAFILES,&DATAFILES_INDEX) != RET_OK){ exit(1); }
if (remove_categories_area(&CATEGORIES,&CATEGORIES_INDEX) != RET_OK){ exit(1); }
remove_safe(index_dir);
remove_safe(data_dir);
}
int main(int argc, char** argv) {
pid_t pid = fork();
//
if (pid < 0){ exit(1);
}else if (pid == 0){
// wait for prepared shared area from parent.
sleep(3);
do_client();
exit(0);
}else{
do_server(pid);
}
return(0);
}
| 34.804348
| 142
| 0.634812
|
xflagstudio
|
1cdd107e2bbce48e8df7103aa1c0817e30708734
| 985
|
cpp
|
C++
|
09_QueueWithTwoStacks/main09.cpp
|
HaoliangLi/CodingInterviewChinese2
|
c3ae0d7bec404d92dc3f5f395ccefb5455d08eb3
|
[
"BSD-3-Clause"
] | null | null | null |
09_QueueWithTwoStacks/main09.cpp
|
HaoliangLi/CodingInterviewChinese2
|
c3ae0d7bec404d92dc3f5f395ccefb5455d08eb3
|
[
"BSD-3-Clause"
] | null | null | null |
09_QueueWithTwoStacks/main09.cpp
|
HaoliangLi/CodingInterviewChinese2
|
c3ae0d7bec404d92dc3f5f395ccefb5455d08eb3
|
[
"BSD-3-Clause"
] | null | null | null |
/***
* @Date: 2021-11-27 17:36:41
* @LastEditors: zjulhl
* @LastEditTime: 2021-11-28 13:25:47
* @Description:
* @FilePath: /CodingInterviewChinese2/09_QueueWithTwoStacks/main09.cpp
*/
#include <stack>
using namespace std;
class CQueue
{
stack<int> stack1, stack2;
public:
CQueue()
{
while (!stack1.empty())
{
stack1.pop();
}
while (!stack2.empty())
{
stack2.pop();
}
}
void appendTail(int value)
{
stack1.push(value);
}
int deleteHead()
{
// 如果第二个栈为空
if (stack2.empty())
{
while (!stack1.empty())
{
stack2.push(stack1.top());
stack1.pop();
}
}
if (stack2.empty())
{
return -1;
}
else
{
int deleteItem = stack2.top();
stack2.pop();
return deleteItem;
}
}
};
| 17.589286
| 71
| 0.447716
|
HaoliangLi
|
1cde2492418251c053d007af77a2e1f334cd06e9
| 228
|
hpp
|
C++
|
include/FindTheDifference.hpp
|
yanzhe-chen/LeetCode
|
d82f0b9721ea613ab216c78e7286671d0e9e4187
|
[
"MIT"
] | 43
|
2015-10-10T12:59:52.000Z
|
2018-07-11T18:07:00.000Z
|
include/FindTheDifference.hpp
|
yanzhe-chen/LeetCode
|
d82f0b9721ea613ab216c78e7286671d0e9e4187
|
[
"MIT"
] | null | null | null |
include/FindTheDifference.hpp
|
yanzhe-chen/LeetCode
|
d82f0b9721ea613ab216c78e7286671d0e9e4187
|
[
"MIT"
] | 11
|
2015-10-10T14:41:11.000Z
|
2018-07-28T06:03:16.000Z
|
#ifndef FIND_THE_DIFFERENCE_HPP_
#define FIND_THE_DIFFERENCE_HPP_
#include <string>
using namespace std;
class FindTheDifference {
public:
char findTheDifference(string s, string t);
};
#endif // FIND_THE_DIFFERENCE_HPP_
| 17.538462
| 47
| 0.798246
|
yanzhe-chen
|
1ce098a977b00d0e57343ab54ff9a2978c182aec
| 1,218
|
cpp
|
C++
|
Solutions/Longest Valid Parentheses/main.cpp
|
Crayzero/LeetCodeProgramming
|
b10ebe22c0de1501722f0f5c934c0c1902a26789
|
[
"MIT"
] | 1
|
2015-04-13T10:58:30.000Z
|
2015-04-13T10:58:30.000Z
|
Solutions/Longest Valid Parentheses/main.cpp
|
Crayzero/LeetCodeProgramming
|
b10ebe22c0de1501722f0f5c934c0c1902a26789
|
[
"MIT"
] | null | null | null |
Solutions/Longest Valid Parentheses/main.cpp
|
Crayzero/LeetCodeProgramming
|
b10ebe22c0de1501722f0f5c934c0c1902a26789
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int longestValidParentheses(string s) {
int s_size = s.size();
if (s_size <= 1) {
return 0;
}
int *dp = new int [s_size];
for(int i = 0; i < s_size; i++) {
dp[i] = 0;
}
int res = 0;
for(int i = 1; i < s_size; i++) {
if (s[i] == ')' && s[i-1] == '(') {
dp[i] = (i>=2 ? dp[i-2] : 0) + 2;
}
else if (dp[i-1] != 0 && s[i] == ')') {
if (i-dp[i-1] > 0 && s[i-dp[i-1]-1] == '(') {
dp[i] = dp[i-1] + 2;
if (i-dp[i] > 0 && dp[i-dp[i]] != 0) {
dp[i] = dp[i] + dp[i-dp[i]];
}
}
}
else {
dp[i] = 0;
}
res = max(res, dp[i]);
for(int i = 0; i < s_size; i++) {
cout<<dp[i]<<" ";
}
cout<<endl;
}
return res;
}
};
int main()
{
string s1 = "()(())";
string s2 = "(()())";
Solution s;
cout<<s.longestValidParentheses(s1);
return 0;
}
| 23.882353
| 61
| 0.325123
|
Crayzero
|
1ce568a02137152b50ce38760832e528aa88db29
| 3,318
|
cpp
|
C++
|
examples/rara.cpp
|
rodriguescr/libfastlib
|
b89172ae727cd36f84d0d02359ce635eb11b8472
|
[
"BSD-3-Clause-LBNL"
] | null | null | null |
examples/rara.cpp
|
rodriguescr/libfastlib
|
b89172ae727cd36f84d0d02359ce635eb11b8472
|
[
"BSD-3-Clause-LBNL"
] | null | null | null |
examples/rara.cpp
|
rodriguescr/libfastlib
|
b89172ae727cd36f84d0d02359ce635eb11b8472
|
[
"BSD-3-Clause-LBNL"
] | null | null | null |
// $Id$
// Author: John Wu <John.Wu at ACM.org> Lawrence Berkeley National Laboratory
// Copyright (c) 2008-2017 the Regents of the University of California
/** @file rara.cpp
This is meant to be the simplest test program for the querying
functions of ibis::query and ibis::part. It accepts the following
fixed list of arguments to simplify the program:
data-dir query-conditions [column-to-print [column-to-print ...]]
The data-dir must exist and contain valid data files and query
conditions much be specified as well. If no column-to-print, this
program effective is answering the following SQL query
SELECT count(*) FROM data-dir WHERE query-conditions
If any column-to-print is specified, all of them are concatenated
together and the SQL query answered is of the form
SELECT column-to-print, column-to-print, ... FROM data-dir WHERE query-conditions
About the name: Bostrychia rara, Spot-breasted Ibis, the smallest ibis
<http://www.sandiegozoo.org/animalbytes/t-ibis.html>. As an example
program for using FastBit IBIS, this might be also the smallest.
@ingroup FastBitExamples
*/
#include "ibis.h" // FastBit IBIS primary include file
// printout the usage string
static void usage(const char* name) {
std::cout << "usage:\n" << name << " data-dir query-conditions"
<< " [column-to-print [column-to-print ...]]\n"
<< std::endl;
} // usage
int main(int argc, char** argv) {
if (argc < 3) {
usage(*argv);
return -1;
}
// construct a data partition from the given data directory.
ibis::part apart(argv[1], static_cast<const char*>(0));
// create a query object with the current user name.
ibis::query aquery(ibis::util::userName(), &apart);
// assign the query conditions as the where clause.
int ierr = aquery.setWhereClause(argv[2]);
if (ierr < 0) {
std::clog << *argv << " setWhereClause(" << argv[2]
<< ") failed with error code " << ierr << std::endl;
return -2;
}
// collect all column-to-print together
std::string sel;
for (int j = 3; j < argc; ++ j) {
if (j > 3)
sel += ", ";
sel += argv[j];
}
if (sel.empty()) { // select count(*)...
ierr = aquery.evaluate(); // evaluate the query
std::cout << "SELECT count(*) FROM " << argv[1] << " WHERE "
<< argv[2] << "\n--> ";
if (ierr >= 0) {
std::cout << aquery.getNumHits();
}
else {
std::cout << "error " << ierr;
}
}
else { // select column-to-print...
ierr = aquery.setSelectClause(sel.c_str());
if (ierr < 0) {
std::clog << *argv << " setSelectClause(" << sel
<< ") failed with error code " << ierr << std::endl;
return -3;
}
ierr = aquery.evaluate(); // evaluate the query
std::cout << "SELECT " << sel << " FROM " << argv[1] << " WHERE "
<< argv[2] << "\n--> ";
if (ierr >= 0) { // print out the select values
aquery.printSelected(std::cout);
}
else {
std::cout << "error " << ierr;
}
}
std::cout << std::endl;
return ierr;
} // main
| 35.677419
| 85
| 0.570223
|
rodriguescr
|
1ce9df55b36a4a6a72489cde35526546cb787727
| 1,236
|
hpp
|
C++
|
src/shuffler.hpp
|
nikolaimerkel/edgepart
|
58b3d57eebd850dfdd7016e90352bddcf840e1f5
|
[
"MIT"
] | 21
|
2018-04-19T07:27:18.000Z
|
2022-02-23T19:33:04.000Z
|
src/shuffler.hpp
|
nikolaimerkel/edgepart
|
58b3d57eebd850dfdd7016e90352bddcf840e1f5
|
[
"MIT"
] | 1
|
2020-12-30T01:40:51.000Z
|
2021-02-20T03:36:17.000Z
|
src/shuffler.hpp
|
nikolaimerkel/edgepart
|
58b3d57eebd850dfdd7016e90352bddcf840e1f5
|
[
"MIT"
] | 9
|
2019-06-19T13:40:57.000Z
|
2021-12-09T19:30:50.000Z
|
#pragma once
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "util.hpp"
#include "conversions.hpp"
class Shuffler : public Converter
{
private:
struct work_t {
Shuffler *shuffler;
int nchunks;
std::vector<edge_t> chunk_buf;
void operator()() {
std::random_shuffle(chunk_buf.begin(), chunk_buf.end());
int file =
open(shuffler->chunk_filename(nchunks).c_str(),
O_WRONLY | O_CREAT, S_IROTH | S_IWOTH | S_IWUSR | S_IRUSR);
size_t chunk_size = chunk_buf.size() * sizeof(edge_t);
writea(file, (char *)&chunk_buf[0], chunk_size);
close(file);
chunk_buf.clear();
}
};
size_t chunk_bufsize;
int nchunks, old_nchunks;
std::vector<edge_t> chunk_buf, old_chunk_buf;
std::string chunk_filename(int chunk);
void chunk_clean();
void cwrite(edge_t e, bool flush = false);
public:
Shuffler(std::string basefilename) : Converter(basefilename) {}
bool done() { return is_exists(shuffled_binedgelist_name(basefilename)); }
void init();
void finalize();
void add_edge(vid_t source, vid_t target);
};
| 26.297872
| 80
| 0.618123
|
nikolaimerkel
|
1ced0d82f1e0edc30c2e913f425fbac2084d7fd7
| 1,858
|
cpp
|
C++
|
Source/Game/MainMenuScene.cpp
|
nathanlink169/3D-Shaders-Test
|
2493fb71664d75100fbb4a80ac70f657a189593d
|
[
"MIT"
] | null | null | null |
Source/Game/MainMenuScene.cpp
|
nathanlink169/3D-Shaders-Test
|
2493fb71664d75100fbb4a80ac70f657a189593d
|
[
"MIT"
] | null | null | null |
Source/Game/MainMenuScene.cpp
|
nathanlink169/3D-Shaders-Test
|
2493fb71664d75100fbb4a80ac70f657a189593d
|
[
"MIT"
] | null | null | null |
#include "CommonHeader.h"
MainMenuScene::MainMenuScene()
{
}
MainMenuScene::~MainMenuScene()
{
}
void MainMenuScene::OnSurfaceChanged(unsigned int aWidth, unsigned int aHeight)
{
Scene::OnSurfaceChanged(aWidth, aHeight);
}
void MainMenuScene::LoadContent()
{
Scene::LoadContent();
CreateCameraObject();
Label* label = new Label(this, "Loading Label", "Loading", vec3(0.0f, 0.0f, 0.0f), vec3(0.0f, 0.0f, 0.0f), vec3(0.035f, 0.035f, 0.035f), nullptr, g_pGame->GetShader("2D Colour"), g_pGame->GetTexture("Black"));
label->Colour = Colours::Crimson;
label->SetFont("arial");
label->Text = "Press Space To Start";
label->Orientation = Center;
AddGameObject(label, "Label");
//AudioManager::PlayBGM("Main Theme");
std::ifstream myfile("Data/SaveData/Score.npwscore");
if (myfile.is_open())
{
std::string line;
ScoreEntry entries;
getline(myfile, line);
entries.Name = line;
getline(myfile, line);
entries.Score = (uint)(std::stoi(line));
Label* score = new Label(this, "High Score Label", "Label", vec3(0.0f, -0.1f, 0.0f), vec3(0.0f, 0.0f, 0.0f), vec3(0.015f, 0.015f, 0.015f), nullptr, g_pGame->GetShader("2D Colour"), g_pGame->GetTexture("Black"));
score->Colour = Colours::Crimson;
score->SetFont("arial");
score->Text = "Highscore: " + entries.Name + " - " + std::to_string(entries.Score);
score->Orientation = Center;
AddGameObject(score, "HighScoreLabel");
}
}
void MainMenuScene::Update(double aDelta)
{
Scene::Update(aDelta);
if (Input::KeyJustPressed(VK_SPACE))
g_pGame->StartGame();
}
void MainMenuScene::Draw()
{
m_Matrix.CreatePerspectiveVFoV(CAMERA_PERSPECTIVE_ANGLE, CAMERA_ASPECT_RATIO, CAMERA_NEAR_Z, CAMERA_FAR_Z);
m_MainCamera->CreateLookAtLeftHandAndReturn(Vector3(0, 1, 0), GetGameObject("Label")->GetPosition());
Scene::Draw();
}
| 28.151515
| 213
| 0.684069
|
nathanlink169
|
1cf05e916039a1c77ac99a82b67ece7c35271c0c
| 756
|
cpp
|
C++
|
cpp/bjyd/06/TestGeometricObject2.cpp
|
skyofsmith/servePractice
|
d143497ec7c13dcbb55354c9050fd48e5b1c7b51
|
[
"MIT"
] | null | null | null |
cpp/bjyd/06/TestGeometricObject2.cpp
|
skyofsmith/servePractice
|
d143497ec7c13dcbb55354c9050fd48e5b1c7b51
|
[
"MIT"
] | 18
|
2020-07-16T21:36:57.000Z
|
2022-03-25T18:59:38.000Z
|
cpp/bjyd/06/TestGeometricObject2.cpp
|
skyofsmith/servePractice
|
d143497ec7c13dcbb55354c9050fd48e5b1c7b51
|
[
"MIT"
] | null | null | null |
#include <iostream>
//#include "AbstractGeometricObject.h"
#include "DerivedCircle2.h"
#include "Rectangle2.h"
using namespace std;
bool equalArea(GeometricObject &object1, GeometricObject &object2)
{
return object1.getArea() == object2.getArea();
}
void displayGeometricObject(GeometricObject &object)
{
cout << "The area is " << object.getArea() << endl;
cout << "The perimeter is " << object.getPerimeter() << endl;
}
int main() {
Circle circle(5);
Rectangle rectangle(5, 3);
cout << "Circle info: " << endl;
displayGeometricObject(circle);
cout << "\nRectangle info: " << endl;
displayGeometricObject(rectangle);
cout << "\nThe two objects have the same area? " <<
(equalArea(circle, rectangle) ? "Yes" : "No") << endl;
return 0;
}
| 22.909091
| 66
| 0.691799
|
skyofsmith
|
7f33db92718d0e225f767b59142b526a75fdc42c
| 605
|
cpp
|
C++
|
tests/unit/appc/util/test_option.cpp
|
cdaylward/libappc
|
4f7316b584d92a110198a3f1573c170e5492194c
|
[
"Apache-2.0"
] | 63
|
2015-01-20T18:35:27.000Z
|
2021-11-16T10:53:40.000Z
|
tests/unit/appc/util/test_option.cpp
|
Manu343726/libappc
|
8d181ef4ee80c8f1bcbf6ca04cf66e04e5e5bc8a
|
[
"Apache-2.0"
] | 5
|
2015-01-20T17:28:54.000Z
|
2015-02-09T17:36:54.000Z
|
tests/unit/appc/util/test_option.cpp
|
cdaylward/libappc
|
4f7316b584d92a110198a3f1573c170e5492194c
|
[
"Apache-2.0"
] | 12
|
2015-01-26T04:37:08.000Z
|
2020-11-14T02:19:13.000Z
|
#include "gtest/gtest.h"
#include "appc/util/option.h"
TEST(Option, none_is_false) {
auto none = None<int>();
ASSERT_FALSE(none);
}
TEST(Option, some_is_true) {
auto some = Some(std::string{""});
ASSERT_TRUE(some);
}
TEST(Option, some_is_shared_ptr) {
auto some = Some(std::string(""));
std::shared_ptr<std::string> ptr = some;
ASSERT_EQ(2, ptr.use_count());
}
TEST(Option, some_dereferences) {
auto some = Some(std::string("one"));
ASSERT_EQ(typeid(std::string), typeid(*some));
ASSERT_EQ(typeid(std::string), typeid(from_some(some)));
ASSERT_EQ(std::string{"one"}, *some);
}
| 21.607143
| 58
| 0.669421
|
cdaylward
|
7f344ec08e017dcdf3c41926a1d07bd06a239b8b
| 757
|
hpp
|
C++
|
bia/memory/gc/root.hpp
|
bialang/bia
|
b54fff096b4fe91ddb0b1d509ea828daa11cee7e
|
[
"BSD-3-Clause"
] | 2
|
2017-09-09T17:03:18.000Z
|
2018-03-02T20:02:02.000Z
|
bia/memory/gc/root.hpp
|
terrakuh/Bia
|
412b7e8aeb259f4925c3b588f6025760a43cd0b7
|
[
"BSD-3-Clause"
] | 7
|
2018-10-11T18:14:19.000Z
|
2018-12-26T15:31:04.000Z
|
bia/memory/gc/root.hpp
|
terrakuh/Bia
|
412b7e8aeb259f4925c3b588f6025760a43cd0b7
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef BIA_MEMORY_GC_ROOT_HPP_
#define BIA_MEMORY_GC_ROOT_HPP_
#include <bia/util/gsl.hpp>
#include <cstddef>
#include <memory>
#include <mutex>
namespace bia {
namespace memory {
namespace gc {
class GC;
/// Defines the root for the search tree for the marking phase during garbage collection. This class is not
/// thread-safe.
class Root
{
public:
Root(const Root& copy) = delete;
~Root() noexcept;
void* at(std::size_t index);
void put(std::size_t index, void* ptr);
Root& operator=(const Root& copy) = delete;
private:
friend GC;
typedef util::Span<void**> Data;
GC* _parent = nullptr;
Data _data;
std::mutex _mutex;
Root(GC* parent, std::size_t size) noexcept;
};
} // namespace gc
} // namespace memory
} // namespace bia
#endif
| 18.02381
| 107
| 0.712021
|
bialang
|
7f379093ec9f642f9797b97b5696ef29a2f9e7dc
| 469
|
hpp
|
C++
|
archive/stan/src/stan/model/standalone_functions_header.hpp
|
alashworth/stan-monorepo
|
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
|
[
"BSD-3-Clause"
] | 1
|
2019-09-06T15:53:17.000Z
|
2019-09-06T15:53:17.000Z
|
archive/stan/src/stan/model/standalone_functions_header.hpp
|
alashworth/stan-monorepo
|
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
|
[
"BSD-3-Clause"
] | 8
|
2019-01-17T18:51:16.000Z
|
2019-01-17T18:51:39.000Z
|
archive/stan/src/stan/model/standalone_functions_header.hpp
|
alashworth/stan-monorepo
|
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef STAN_MODEL_STANDALONE_FUNCTIONS_HEADER_HPP
#define STAN_MODEL_STANDALONE_FUNCTIONS_HEADER_HPP
#include <stan/math.hpp>
#include <boost/random/additive_combine.hpp>
#include <stan/io/program_reader.hpp>
#include <stan/lang/rethrow_located.hpp>
#include <stan/model/indexing.hpp>
#include <cmath>
#include <cstddef>
#include <fstream>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <utility>
#include <vector>
#endif
| 22.333333
| 51
| 0.763326
|
alashworth
|
7f5039992eb67ceedc2414dfed8e29ad0caf0b2e
| 109
|
cpp
|
C++
|
sources/shared_ptr.cpp
|
Denis-Gorbachev/lab-03-shared-ptr
|
555967045a5893a0f79507e60e5ccf386335fbe6
|
[
"MIT"
] | null | null | null |
sources/shared_ptr.cpp
|
Denis-Gorbachev/lab-03-shared-ptr
|
555967045a5893a0f79507e60e5ccf386335fbe6
|
[
"MIT"
] | null | null | null |
sources/shared_ptr.cpp
|
Denis-Gorbachev/lab-03-shared-ptr
|
555967045a5893a0f79507e60e5ccf386335fbe6
|
[
"MIT"
] | null | null | null |
// Copyright 2021 Denis <denis.gorbachev2002@yandex.ru>
//#include <stdexcept>
//#include <shared_ptr.hpp>
| 18.166667
| 55
| 0.733945
|
Denis-Gorbachev
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.