hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
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
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
a23cff4835c60c3d585b0c8466da36cbaabba369
1,198
cc
C++
leetcode/leetcode_224.cc
math715/arts
ff73ccb7d67f7f7c87150204e15aeb46047f0e02
[ "MIT" ]
null
null
null
leetcode/leetcode_224.cc
math715/arts
ff73ccb7d67f7f7c87150204e15aeb46047f0e02
[ "MIT" ]
null
null
null
leetcode/leetcode_224.cc
math715/arts
ff73ccb7d67f7f7c87150204e15aeb46047f0e02
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <string> #include <vector> #include <map> #include <stack> #include <cassert> #include <cctype> using namespace std; int calculate(string s) { long a = 0, b = 0, r = 0; stack<long> st; long res = 0; int sign = 1; for (int i = 0; i < s.size(); ++i) { if (isdigit(s[i])) { long num = 0; while (isdigit(s[i]) && i <s.size()) { num = num * 10 + (s[i]-'0'); i++; } res += sign * num; i--; } else if (s[i] == '+') { sign = 1; } else if (s[i] == '-') { sign = -1; } else if (s[i] == '('){ st.push(res); st.push(sign); res = 0; sign = 1; } else if (s[i] == ')') { res *= st.top(); st.pop(); res += st.top(); st.pop(); } } return res; } int main( int argc, char *argv[] ) { // cout << calculate("1+1") << endl; // cout << calculate("1+(1+2)") << endl; // cout << calculate("1+(1-2)") << endl; // cout << calculate("-3") << endl; // cout << calculate("1+3") << endl; cout << calculate("1 + 3") << endl; // cout << calculate("(1+(4+5+2)-3)") << endl; cout << calculate("(1+(4+5+2)-3)+(6+8)") << endl; return 0; }
21.781818
53
0.459933
[ "vector" ]
a2427c08b25020bd556be7c14aacab45a1ec0be5
948
cpp
C++
cf/Div2/C/Number of Ways/main.cpp
wdjpng/soi
dd565587ae30985676f7f374093ec0687436b881
[ "MIT" ]
null
null
null
cf/Div2/C/Number of Ways/main.cpp
wdjpng/soi
dd565587ae30985676f7f374093ec0687436b881
[ "MIT" ]
null
null
null
cf/Div2/C/Number of Ways/main.cpp
wdjpng/soi
dd565587ae30985676f7f374093ec0687436b881
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define int long long using namespace std; signed main() { // Turn off synchronization between cin/cout and scanf/printf ios_base::sync_with_stdio(false); // Disable automatic flush of cout when reading from cin cin.tie(0); cin.tie(0); int n; cin >> n; vector<int>input(n); int s = 0; for (int i = 0; i < n; ++i) { cin >> input[i]; s+=input[i]; } if(s%3||n<3){ cout << "0"; exit(0); } vector<int>indexes; int curS = 0; for (int i = n-1; i >= 2; --i) { curS+=input[i]; if(curS == s/3){ indexes.push_back(i); } } reverse(indexes.begin(), indexes.end()); int ways=0; curS=0; for (int i = 0; i < n-2; ++i) { curS+=input[i]; if(curS==s/3){ ways+=indexes.end() - upper_bound(indexes.begin(), indexes.end(), i+1); } } cout << ways; }
21.066667
83
0.493671
[ "vector" ]
a24482274ad89d7cde8776438c211d33b40a8774
4,708
hpp
C++
src/Common/SpinLock.hpp
dale-wilson/HSQueue
04d01ed42707069d28e81b5494aba61904e6e591
[ "BSD-3-Clause" ]
2
2015-12-29T17:33:25.000Z
2021-12-20T02:30:44.000Z
src/Common/SpinLock.hpp
dale-wilson/HighQueue
04d01ed42707069d28e81b5494aba61904e6e591
[ "BSD-3-Clause" ]
null
null
null
src/Common/SpinLock.hpp
dale-wilson/HighQueue
04d01ed42707069d28e81b5494aba61904e6e591
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2015 Object Computing, Inc. // All rights reserved. // See the file license.txt for licensing information. #pragma once #include <atomic> #define HIGHQUEUE_USE_CRITICAL_SECTION 1 #if HIGHQUEUE_USE_CRITICAL_SECTION && !defined(_WIN32) #include <linux/spinlock.h> #endif namespace HighQueue { class SpinLock { public: SpinLock(); class Unguard; class Guard { public: /// @brief RAII constructor. Guard(SpinLock & spinlock, bool acquireNow = true); /// @brief Move constructor allows delayed attachment to spin lock Guard(Guard && spinlock); /// @Construct an unattached guard Guard(); /// @brief Copy would be a disaster Guard(const Guard &) = delete; /// @brief RAII destructor ~Guard(); /// @brief assignment is move Guard & operator =(Guard && rhs); bool isLocked()const; void acquire(); // todo bool tryAcquire(); private: friend class Unguard; bool release(); private: SpinLock * spinlock_; bool owns_; }; class Unguard { public: Unguard(Guard & guard); ~Unguard(); private: Guard & guard_; bool wasLocked_; }; private: friend class Guard; void acquire(); // todo bool tryAcquire(); void release(); private: #if HIGHQUEUE_USE_CRITICAL_SECTION # if defined(_WIN32) CRITICAL_SECTION criticalSection_; # else // _WIN32 spinlock_t spinlock_; # endif // _WIN32 #else // HIGHQUEUE_USE_CRITICAL_SECTION std::atomic_flag flag_; #endif // HIGHQUEUE_USE_CRITICAL_SECTION }; inline SpinLock::SpinLock() { #if HIGHQUEUE_USE_CRITICAL_SECTION # if defined(_WIN32) InitializeCriticalSection(&criticalSection_); # else // defined(_WIN32) spin_lock_init(&spinlock_); # endif // _WIN32 #else // HIGHQUEUE_USE_CRITICAL_SECTION flag_.clear(); #endif // HIGHQUEUE_USE_CRITICAL_SECTION } inline void SpinLock::acquire() { #if HIGHQUEUE_USE_CRITICAL_SECTION # if defined(_WIN32) EnterCriticalSection(&criticalSection_); # else // defined(_WIN32) spin_lock(&spinlock_); # endif // _WIN32 #else //HIGHQUEUE_USE_CRITICAL_SECTION while(flag_.test_and_set(std::memory_order::memory_order_seq_cst)) { spinDelay(); } #endif // defined(_WIN32) && HIGHQUEUE_USE_CRITICAL_SECTION } // todo bool SpinLock::tryAcquire(); inline void SpinLock::release() { #if HIGHQUEUE_USE_CRITICAL_SECTION # if defined(_WIN32) LeaveCriticalSection(&criticalSection_); # else // defined(_WIN32) spin_unlock(&spinlock_); # endif // _WIN32 #else // HIGHQUEUE_USE_CRITICAL_SECTION flag_.clear(); #endif // defined(_WIN32) && HIGHQUEUE_USE_CRITICAL_SECTION } inline SpinLock::Guard::Guard(SpinLock & spinlock, bool acquireNow) : spinlock_(&spinlock) , owns_(false) { if(acquireNow) { acquire(); } } inline SpinLock::Guard::Guard(SpinLock::Guard && rhs) : spinlock_(rhs.spinlock_) , owns_(rhs.owns_) { rhs.spinlock_ = 0; rhs.owns_ = false; } inline SpinLock::Guard::Guard() : spinlock_(0) , owns_(false) { } inline SpinLock::Guard & SpinLock::Guard::operator= (SpinLock::Guard && rhs) { release(); std::swap(spinlock_, rhs.spinlock_); std::swap(owns_, rhs.owns_); return *this; } inline SpinLock::Guard::~Guard() { if(owns_ && spinlock_) { spinlock_->release(); } } inline void SpinLock::Guard::acquire() { if(spinlock_) { spinlock_->acquire(); owns_ = true; } } //bool SpinLock::Guard::tryAcquire() inline bool SpinLock::Guard::release() { bool wasOwned = owns_; if(owns_ && spinlock_) { spinlock_->release(); owns_ = false; } return wasOwned; } inline bool SpinLock::Guard::isLocked()const { return owns_; } inline SpinLock::Unguard::Unguard(Guard & guard) : guard_(guard) , wasLocked_(guard_.release()) { } inline SpinLock::Unguard::~Unguard() { if(wasLocked_) { guard_.acquire(); } } } // namespace HighQueue
21.497717
78
0.564571
[ "object" ]
a2489e42e1852c679fc58640bde0da230a818ae4
9,154
cpp
C++
aten/src/ATen/native/mkldnn/Conv.cpp
stungkit/pytorch
0f05e398705bf15406bce79f7ee57d3935ad2abd
[ "Intel" ]
2
2020-03-13T06:57:49.000Z
2020-05-17T04:18:14.000Z
aten/src/ATen/native/mkldnn/Conv.cpp
ellhe-blaster/pytorch
e5282c3cb8bf6ad8c5161f9d0cc271edb9abed25
[ "Intel" ]
1
2022-01-10T18:39:28.000Z
2022-01-10T19:15:57.000Z
aten/src/ATen/native/mkldnn/Conv.cpp
ellhe-blaster/pytorch
e5282c3cb8bf6ad8c5161f9d0cc271edb9abed25
[ "Intel" ]
1
2022-03-26T14:42:50.000Z
2022-03-26T14:42:50.000Z
#include <ATen/ATen.h> #include <ATen/native/ConvUtils.h> #include <ATen/NativeFunctions.h> #include <ATen/Config.h> #if !AT_MKLDNN_ENABLED() namespace at { namespace native { Tensor mkldnn_convolution( const Tensor& input, const Tensor& weight, const c10::optional<Tensor>& bias_opt, IntArrayRef padding, IntArrayRef stride, IntArrayRef dilation, int64_t groups) { TORCH_CHECK(false, "mkldnn_convolution_forward: ATen not compiled with MKLDNN support"); } Tensor mkldnn_convolution_backward_input( IntArrayRef input_size, const Tensor& grad_output, const Tensor& weight, IntArrayRef padding, IntArrayRef stride, IntArrayRef dilation, int64_t groups, bool bias_defined) { TORCH_CHECK(false, "mkldnn_convolution_backward_input: ATen not compiled with MKLDNN support"); } std::tuple<Tensor, Tensor> mkldnn_convolution_backward_weights( IntArrayRef weight_size, const Tensor& grad_output, const Tensor& input, IntArrayRef padding, IntArrayRef stride, IntArrayRef dilation, int64_t groups, bool bias_defined) { TORCH_CHECK(false, "mkldnn_convolution_backward_weights: ATen not compiled with MKLDNN support"); } std::tuple<Tensor, Tensor, Tensor> mkldnn_convolution_backward( const Tensor& input, const Tensor& grad_output_t, const Tensor& weight, IntArrayRef padding, IntArrayRef stride, IntArrayRef dilation, int64_t groups, std::array<bool,3> output_mask) { TORCH_CHECK(false, "mkldnn_convolution_backward: ATen not compiled with MKLDNN support"); } REGISTER_NO_CPU_DISPATCH(mkldnn_convolution_backward_stub); }} #else // AT_MKLDNN_ENABLED #include <ATen/native/mkldnn/MKLDNNCommon.h> #include <ATen/native/mkldnn/Utils.h> #include <ATen/native/ConvUtils.h> namespace at { namespace native { #define MKLDNNTensor(itensor, options) \ new_with_itensor_mkldnn( \ std::move(itensor), \ optTypeMetaToScalarType(options.dtype_opt()), \ options.device_opt()) // Note [MKLDNN Convolution Memory Formats] // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // MKLDNN has 3 types of memory formats in convolution: // // In case memory format passed from PyTorch (aka. user layout) // differs from the internal layout which MKLDNN used, a `reorder` is needed; // otherwise when user layout is identical to internal layout, // MKLDNN uses a memory `view` upon an existing CPU tensor. // // 1. NCHW (CPU tensor, contiguous) // input reorder: NCHW(user) -> Blocked(internal) // weight reorder: OIHW(user) -> Blocked(internal) // output reorder: Blocked(internal) -> NCHW(user) // // 2. NHWC: (CPU tensor, channels last) // input view: NHWC(user) -> NHWC(internal) // weight reorder: OHWI(user) -> Blocked(internal) // output view: NHWC(internal) -> NHWC(user) // // 3. Blocked (MKLDNN tensor): // By explicitly converting a tensor to mkldnn, e.g. `x.to_mkldnn()`, // blocked format will propagate between layers. Input, output will be in blocked format. // // For inference case, weight can be prepacked into blocked format by // (so as to save weight reoder overhead): // model = torch.utils.mkldnn.to_mkldnn(model) // // For training case, grad_output can be CPU tensor or MKLDNN tensor, // but weight/bias and grad_weight/grad_bias are always CPU tensor. // Tensor mkldnn_convolution( const Tensor& input, const Tensor& weight, const c10::optional<Tensor>& bias_opt, IntArrayRef padding, IntArrayRef stride, IntArrayRef dilation, int64_t groups) { // See [Note: hacky wrapper removal for optional tensor] c10::MaybeOwned<Tensor> bias_maybe_owned = at::borrow_from_optional_tensor(bias_opt); const Tensor& bias = *bias_maybe_owned; if (input.scalar_type() == ScalarType::BFloat16) { TORCH_CHECK(mkldnn_bf16_device_check(), "mkldnn_convolution: bf16 path needs the cpu support avx512bw, avx512vl and avx512dq"); } bool is_channels_last = input.suggest_memory_format() == at::MemoryFormat::ChannelsLast; auto output_sizes = conv_output_size(input.sizes(), weight.sizes(), padding, stride, dilation); auto output = at::empty({0}, input.options()); const ideep::tensor x = itensor_from_tensor(input); const ideep::tensor w = itensor_from_tensor(weight); ideep::tensor y; if (is_channels_last) { output.resize_(output_sizes, input.suggest_memory_format()); y = itensor_from_tensor(output); } if (bias.defined()) { const ideep::tensor b = itensor_from_tensor(bias); ideep::convolution_forward::compute( x, w, b, {output_sizes.cbegin(), output_sizes.cend()}, y, {stride.begin(), stride.end()}, {dilation.begin(), dilation.end()}, {padding.begin(), padding.end()}, {padding.begin(), padding.end()}, groups); } else { ideep::convolution_forward::compute( x, w, {output_sizes.cbegin(), output_sizes.cend()}, y, {stride.begin(), stride.end()}, {dilation.begin(), dilation.end()}, {padding.begin(), padding.end()}, {padding.begin(), padding.end()}, groups); } if (input.is_mkldnn()) { return MKLDNNTensor(y, input.options()); } else if (!is_channels_last) { return mkldnn_to_dense(MKLDNNTensor(y, input.options())); } else { TORCH_INTERNAL_ASSERT(y.get_desc().is_nhwc()); return output; } } Tensor mkldnn_convolution_backward_input( IntArrayRef input_size, const Tensor& grad_output, const Tensor& weight, IntArrayRef padding, IntArrayRef stride, IntArrayRef dilation, int64_t groups, bool bias_defined) { bool is_channels_last = grad_output.suggest_memory_format() == at::MemoryFormat::ChannelsLast; auto grad_input = at::empty({0}, grad_output.options()); auto grad_y = itensor_from_tensor(grad_output); auto w = itensor_view_from_dense(weight); ideep::tensor grad_x; if (is_channels_last) { grad_input.resize_(input_size, grad_output.suggest_memory_format()); grad_x = itensor_from_tensor(grad_input); } ideep::convolution_backward_data::compute( grad_y, w, input_size.vec(), grad_x, stride.vec(), dilation.vec(), padding.vec(), padding.vec(), groups); if (grad_output.is_mkldnn()) { return MKLDNNTensor(grad_x, grad_output.options()); } else if (!is_channels_last){ return mkldnn_to_dense(MKLDNNTensor(grad_x, grad_output.options())); } else { TORCH_INTERNAL_ASSERT(grad_x.get_desc().is_nhwc()); return grad_input; } } std::tuple<Tensor, Tensor> mkldnn_convolution_backward_weights( IntArrayRef weight_size, const Tensor& grad_output, const Tensor& input, IntArrayRef padding, IntArrayRef stride, IntArrayRef dilation, int64_t groups, bool bias_defined) { bool is_channels_last = grad_output.suggest_memory_format() == at::MemoryFormat::ChannelsLast; const ideep::tensor grad_y = itensor_from_tensor(grad_output); const ideep::tensor x = itensor_from_tensor(input); ideep::tensor grad_w, grad_b; if (bias_defined) { ideep::convolution_backward_weights::compute( x, grad_y, weight_size.vec(), grad_w, grad_b, stride.vec(), dilation.vec(), padding.vec(), padding.vec(), groups); } else { ideep::convolution_backward_weights::compute( x, grad_y, weight_size.vec(), grad_w, stride.vec(), dilation.vec(), padding.vec(), padding.vec(), groups); } if (!is_channels_last) { return std::make_tuple( mkldnn_to_dense(MKLDNNTensor(grad_w, grad_output.options())), bias_defined ? mkldnn_to_dense(MKLDNNTensor(grad_b, grad_output.options())) : Tensor()); } else { return std::make_tuple( mkldnn_to_dense(MKLDNNTensor(grad_w, grad_output.options())).to(at::MemoryFormat::ChannelsLast), bias_defined ? mkldnn_to_dense(MKLDNNTensor(grad_b, grad_output.options())) : Tensor()); } } std::tuple<Tensor, Tensor, Tensor> mkldnn_convolution_backward( const Tensor& input, const Tensor& grad_output_t, const Tensor& weight, IntArrayRef padding, IntArrayRef stride, IntArrayRef dilation, int64_t groups, std::array<bool,3> output_mask) { auto memory_format = input.suggest_memory_format(); Tensor grad_output = grad_output_t.is_mkldnn() ? grad_output_t : grad_output_t.contiguous(memory_format); Tensor grad_input, grad_weight, grad_bias; if (output_mask[0]) { grad_input = mkldnn_convolution_backward_input( input.sizes(), grad_output, weight, padding, stride, dilation, groups, output_mask[2]); } if (output_mask[1] || output_mask[2]) { std::tie(grad_weight, grad_bias) = mkldnn_convolution_backward_weights( weight.sizes(), grad_output, input, padding, stride, dilation, groups, output_mask[2]); } return std::make_tuple(grad_input, grad_weight, grad_bias); } REGISTER_ALL_CPU_DISPATCH(mkldnn_convolution_backward_stub, &mkldnn_convolution_backward); }} // namespace at::native #endif
35.898039
116
0.692921
[ "model" ]
a24dac64fa89eb0bf8e9fca93c7686ad50d818e6
1,933
cc
C++
hackerrank/euler/29.cc
metaflow/contests
5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2
[ "MIT" ]
1
2019-05-12T23:41:00.000Z
2019-05-12T23:41:00.000Z
hackerrank/euler/29.cc
metaflow/contests
5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2
[ "MIT" ]
null
null
null
hackerrank/euler/29.cc
metaflow/contests
5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; using vi = vector<int>; using ii = pair<int,int>; using vii = vector<ii>; using vvi = vector<vi>; using ll = long long; using llu = unsigned long long; using vb = vector<bool>; using vvb = vector<vb>; using vd = vector<double>; using vvd = vector<vd>; using vll = vector<ll>; const int INF = numeric_limits<int>::max(); const double EPS = 1e-10; const ll MAX_PRIME = 1000000; vll sieve_primes() { bitset<MAX_PRIME + 1> b; vll primes; primes.emplace_back(2); for (ll i = 3; i <= MAX_PRIME; i += 2) { if (b[i]) continue; primes.emplace_back(i); for (ll j = i * i; j <= MAX_PRIME; j += i) b.set(j); } return primes; } ll brute(ll n) { set<ll> s; for (ll i = 2; i <= n; i++) { ll a = i; for (ll j = 2; j <= n; j++) { a *= i; s.insert(a); } } return s.size(); } ll gcd(ll a, ll b) { while (b) { ll t = b; b = a % b; a = t; } return a; } ll lcm(ll a, ll b) { return a * b / gcd(a, b); } const int MAX = 100001; ll f(ll n) { ll a = (n - 1) * (n - 1); bitset<MAX> b; auto primes = sieve_primes(); for (ll i = 2; i <= n; i++) { if (b[i]) continue; ll k = 2, t = i * i; while (t <= n) { b.set(t); vector<bool> g(n); for (ll j = 1; j < k; j++) { ll y = lcm(j, k); for (ll h = y; h <= n * j; h += y) { if (g[h / k] || (h / k <= 1)) continue; g[h / k] = true; a--; } // if (j == 1 && y != k) a++; // cout << (n * j / y) << " " << y << " " << i << " " << t << " " << j << endl; // cerr << (n / k - 1) << " " << t << " " << i << endl; } k++; t *= i; } } return a; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); ll n; cin >> n; // for (int n = 2; n < 17; n++) { // cout << n << " " << f(n) << " " << brute(n) << endl; // } cout << f(n) << endl; }
20.347368
88
0.444904
[ "vector" ]
a25055ca98d76d49f14685aa666b337755beeb8c
2,653
cc
C++
Applications/genericCC/rat.cc
comnetsAD/ALCC
fc9c627de8c381987fc775ce0872339fceb43ddf
[ "MIT" ]
6
2021-05-19T16:58:15.000Z
2022-03-10T03:51:20.000Z
Applications/genericCC/rat.cc
comnetsAD/ALCC
fc9c627de8c381987fc775ce0872339fceb43ddf
[ "MIT" ]
null
null
null
Applications/genericCC/rat.cc
comnetsAD/ALCC
fc9c627de8c381987fc775ce0872339fceb43ddf
[ "MIT" ]
4
2021-05-24T11:19:18.000Z
2022-03-08T17:58:24.000Z
#include <algorithm> #include <limits> #include "rat.hh" using namespace std; Rat::Rat( WhiskerTree & s_whiskers, const bool s_track ) : _whiskers( s_whiskers ), _memory(), _packets_sent( 0 ), _packets_received( 0 ), _track( s_track ), _last_send_time( 0 ), _the_window( 0 ), _intersend_time( 0 ), _flow_id( 0 ), _largest_ack( -1 ) { } void Rat::packets_received( const vector< Packet > & packets, const double link_rate_normalizing_factor ) { _packets_received += packets.size(); int flow_id = -1; assert( packets.size() ); for ( auto &packet : packets ){ _largest_ack = max( packet.seq_num, _largest_ack ); flow_id = packet.flow_id; } assert( flow_id != -1 ); _memory.packets_received( packets, flow_id/*_flow_id*/, link_rate_normalizing_factor ); const Whisker & current_whisker( _whiskers.use_whisker( _memory, _track ) ); _the_window = current_whisker.window( _the_window ); _intersend_time = current_whisker.intersend(); } void Rat::reset( const double & ) { _memory.reset(); _last_send_time = 0; _the_window = 0; _intersend_time = 0; _flow_id++; _largest_ack = _packets_sent - 1; /* Assume everything's been delivered */ assert( _flow_id != 0 ); } double Rat::next_event_time( const double & tickno ) const { if ( _packets_sent < _largest_ack + 1 + _the_window ) { if ( _last_send_time + _intersend_time <= tickno ) { return tickno; } else { return _last_send_time + _intersend_time; } } else { /* window is currently closed */ return std::numeric_limits<double>::max(); } } // returns whether or not a packet should be sent. If yes, updates internal state accordingly bool Rat::send( const double & curtime ) { assert( _packets_sent >= _largest_ack + 1 ); if ( _the_window == 0 ) { /* initial window and intersend time */ const Whisker & current_whisker( _whiskers.use_whisker( _memory, _track ) ); _the_window = current_whisker.window( _the_window ); _intersend_time = current_whisker.intersend(); // assert(_the_window != 0 ); //edit - venkat - just to ensure that a sender doesn't stay 0 forever because right now, I believe that memory will never be called if no packets are sent. But something tells me that my understanding is incorrect } if ( (_packets_sent < _largest_ack + 1 + _the_window) and (_last_send_time + _intersend_time <= curtime) ) { //Packet p( id, _flow_id, curtime, _packets_sent ); _packets_sent++; //_memory.packet_sent( p ); //next.accept( p, curtime ); _last_send_time = curtime; return true; } return false; }
29.153846
247
0.676969
[ "vector" ]
a250668b9df49bb3b0d9c5bcbf013d67d171dd3a
1,438
cpp
C++
src/OpenGL/core/ScreenMapper.cpp
kelcykai/softpiple
74ed4b0f239215fb8293cbf8e33436ee404e2c07
[ "MIT" ]
null
null
null
src/OpenGL/core/ScreenMapper.cpp
kelcykai/softpiple
74ed4b0f239215fb8293cbf8e33436ee404e2c07
[ "MIT" ]
null
null
null
src/OpenGL/core/ScreenMapper.cpp
kelcykai/softpiple
74ed4b0f239215fb8293cbf8e33436ee404e2c07
[ "MIT" ]
null
null
null
#include "ScreenMapper.h" #include "DataFlow.h" #include "DrawEngine.h" #include "GLContext.h" NS_OPEN_GLSP_OGL() using glm::vec4; ScreenMapper::ScreenMapper(): PipeStage("Viewport Transform", DrawEngine::getDrawEngine()) { } void ScreenMapper::emit(void *data) { Batch *bat = static_cast<Batch *>(data); viewportTransform(bat); getNextStage()->emit(bat); } void ScreenMapper::viewportTransform(Batch *bat) { GLContext *gc = bat->mDC->gc; int xCenter = gc->mState.mViewport.xCenter; int yCenter = gc->mState.mViewport.yCenter; int xScale = gc->mState.mViewport.xScale; int yScale = gc->mState.mViewport.yScale; Primlist &pl = bat->mPrims; Primlist::iterator it = pl.begin(); while(it != pl.end()) { for(size_t i = 0; i < 3; ++i) { vec4 &pos = it->mVert[i].position(); pos.x = xCenter + pos.x * xScale; pos.y = yCenter + pos.y * yScale; pos.z = (pos.z + 1) * 0.5f; } const vec4 &pos0 = it->mVert[0].position(); const vec4 &pos1 = it->mVert[1].position(); const vec4 &pos2 = it->mVert[2].position(); float ex = pos1.x - pos0.x; float ey = pos1.y - pos0.y; float fx = pos2.x - pos0.x; float fy = pos2.y - pos0.y; float area = ex * fy - ey * fx; // Discard the triangles whose area are less than 1 if(abs(area) <= 1.0f) { it = pl.erase(it); } else { it->mAreaReciprocal = 1.0f / area; it++; } } } void ScreenMapper::finalize() { } NS_CLOSE_GLSP_OGL()
19.173333
61
0.634214
[ "transform" ]
a2521881f96f09638b5bbb2bf51822c9cb8a690a
1,446
cpp
C++
Algorithm/dfs&bfs/2667.cpp
TheStarkor/Major
fd23c3ed4452f7c4748b7afa35f430b3292f8018
[ "MIT" ]
null
null
null
Algorithm/dfs&bfs/2667.cpp
TheStarkor/Major
fd23c3ed4452f7c4748b7afa35f430b3292f8018
[ "MIT" ]
null
null
null
Algorithm/dfs&bfs/2667.cpp
TheStarkor/Major
fd23c3ed4452f7c4748b7afa35f430b3292f8018
[ "MIT" ]
null
null
null
#include <algorithm> #include <iostream> #include <cstring> #include <vector> #include <queue> using namespace std; int n, dx[4] = {0, 0, -1, 1}, dy[4] = {-1, 1, 0, 0}; int map[25][25]; bool check[25][25]; int bfs (int row, int col) { int cnt = 0; queue<pair<int, int>> q; check[row][col] = true; q.push(make_pair(row, col)); while (!q.empty()) { cnt++; int y = q.front().first, x = q.front().second; q.pop(); for (int i = 0; i < 4; i++) { int ny = y + dy[i], nx = x + dx[i]; if (0 <= nx && nx < n && 0 <= ny && ny < n) { if (map[ny][nx] == 1 && check[ny][nx] == false) { check[ny][nx] = true; q.push(make_pair(ny, nx)); } } } } return cnt; } int main(void) { cin >> n; vector<int> ans; memset(check, false, sizeof(check)); for (int i = 0; i < n; i++) { string s; cin >> s; for (int j = 0; j < n; j++) map[i][j] = s[j] - '0'; } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (map[i][j] == 1 && check[i][j] == false) { ans.push_back(bfs(i, j)); } } } sort(ans.begin(), ans.end()); cout << ans.size() << '\n'; for (int i: ans) cout << i << '\n'; }
19.808219
63
0.383126
[ "vector" ]
a25a453cdd3014b7b725e421310c065a2cbb72af
998
cpp
C++
aws-cpp-sdk-mediatailor/source/model/ListPrefetchSchedulesRequest.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-mediatailor/source/model/ListPrefetchSchedulesRequest.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-mediatailor/source/model/ListPrefetchSchedulesRequest.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-12-30T04:25:33.000Z
2021-12-30T04:25:33.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/mediatailor/model/ListPrefetchSchedulesRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::MediaTailor::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; ListPrefetchSchedulesRequest::ListPrefetchSchedulesRequest() : m_maxResults(0), m_maxResultsHasBeenSet(false), m_nextTokenHasBeenSet(false), m_playbackConfigurationNameHasBeenSet(false), m_streamIdHasBeenSet(false) { } Aws::String ListPrefetchSchedulesRequest::SerializePayload() const { JsonValue payload; if(m_maxResultsHasBeenSet) { payload.WithInteger("MaxResults", m_maxResults); } if(m_nextTokenHasBeenSet) { payload.WithString("NextToken", m_nextToken); } if(m_streamIdHasBeenSet) { payload.WithString("StreamId", m_streamId); } return payload.View().WriteReadable(); }
19.192308
69
0.745491
[ "model" ]
a25cad789c698669e952d35c5884bd741839d4e3
5,425
hpp
C++
rpl-shell/rpl/rewriting/rewriter.hpp
Murray1991/rplsh
38c29216c8ec11a10e3bd2ba4f5f55fe23e19995
[ "MIT" ]
6
2017-12-05T12:10:26.000Z
2020-06-01T04:11:00.000Z
rpl-shell/rpl/rewriting/rewriter.hpp
Murray1991/rplsh
38c29216c8ec11a10e3bd2ba4f5f55fe23e19995
[ "MIT" ]
1
2019-07-04T14:05:07.000Z
2019-07-04T19:20:15.000Z
rpl-shell/rpl/rewriting/rewriter.hpp
Murray1991/rplsh
38c29216c8ec11a10e3bd2ba4f5f55fe23e19995
[ "MIT" ]
2
2019-09-07T14:54:03.000Z
2019-10-07T08:42:10.000Z
#pragma once // TODO funzia, ma un po' incasinato #include "rewrules.hpp" #include "nodes/skeletons.hpp" #include "visitors/visitors.hpp" #include <unordered_map> using namespace std; typedef unordered_map<string, skel_node*> node_set; typedef pair<skel_node*, skel_node*> pair_node; void combine( skel_node& root, vector<pair_node>&& pairs, node_set& to_set ); void combine (skel_node& root, node_set&& from_set, node_set& to_set); vector<pair_node> allpairs( node_set&& s1, node_set&& s2); node_set merge(node_set& s1, node_set& s2); void delset( node_set& s ); struct rewriter { rewriter(bool rec) : rec(rec) {} node_set apply_allrules ( skel_node& tree, rr_dispatcher& rr_disp); template <typename Iterator> node_set apply_allrules ( Iterator& it1, Iterator& it2, rr_dispatcher& rr_disp); template <typename Iterator> node_set apply_rule ( Iterator& it1, Iterator& it2, rewrule& r); private: printer print; single_node_cloner snc; skel_node* rewrite( skel_node& n, rewrule& r ); node_set fullrecrewrite( skel_node& n, rewrule& r ); void insert_or_delete( node_set& set, skel_node* rn ); /* When it is set to true, the rewrules are considered as recrewrules: * the rewriter will apply the rule recursively modifying the same * skel tree */ bool rec; }; template <typename Iterator> node_set rewriter::apply_rule ( Iterator& begin, Iterator& end, rewrule& r) { node_set set; for ( auto it = begin ; it != end; ++it) { auto& skelptr = *it; insert_or_delete ( set, rewrite(*skelptr, r) ); } return set; } node_set rewriter::apply_allrules ( skel_node& tree, rr_dispatcher& rr_disp) { node_set set;; vector<node_set> sets; for (auto& str : rr_disp.get_allrules()) sets.push_back( fullrecrewrite(tree, *rr_disp[str]) ); for (auto& curr : sets) set = merge(set, curr); return set; } template <typename Iterator> node_set rewriter::apply_allrules ( Iterator& begin, Iterator& end, rr_dispatcher& rr_disp) { node_set set; vector<node_set> sets; for (auto it = begin; it != end; it++) { auto& skelptr = *it; sets.push_back( apply_allrules(*skelptr, rr_disp) ); } for (auto& curr : sets) set = merge(set, curr); return set; } skel_node* rewriter::rewrite( skel_node& n, rewrule& r ) { skel_node* newptr = r.rewrite(n); skel_node* tmp; /* for rec support */ while ( rec && newptr && (tmp = r.rewrite(*newptr)) ) newptr = tmp; /* TODO really lazy now, should be written in a more concise way */ if ( rec && newptr && newptr->size() == 1) { newptr->set( rewrite(*newptr->get(0), r), 0 ); } else if ( rec && newptr && newptr->size() == 2) { newptr->set( rewrite(*newptr->get(0), r), 0 ); newptr->set( rewrite(*newptr->get(1), r), 1 ); } else if ( rec && n.size() == 1 ) { n.set( rewrite(*n.get(0), r), 0 ); } else if ( rec && n.size() == 2) { n.set( rewrite(*n.get(0), r), 0 ); n.set( rewrite(*n.get(1), r), 1 ); } return newptr == nullptr ? n.clone() : newptr; } node_set rewriter::fullrecrewrite( skel_node& n, rewrule& r ) { node_set set; unique_ptr<skel_node> rn( rewrite(n, r) ); insert_or_delete( set, n.clone() ); insert_or_delete( set, rn->clone() ); if ( n.size() == 1 ) combine(n, fullrecrewrite(*n.get(0), r), set); else if ( n.size() == 2 ) { // Comp or Pipe combine(n, allpairs(fullrecrewrite(*n.get(0),r), fullrecrewrite(*n.get(1), r)), set); if (rn != nullptr && rn->size() == 2) combine(*rn, allpairs(fullrecrewrite(*rn->get(0),r), fullrecrewrite(*rn->get(1), r)), set); } return set; } void rewriter::insert_or_delete( node_set& set, skel_node* rn ) { if (rn != nullptr) { auto p = set.insert({print(*rn), rn}); if (!p.second) delete rn; } } void comb_and_ins( node_set& s, skel_node& n, skel_node* p1 ) { single_node_cloner snc; skel_node * rn = snc(n); printer print; rn->add(p1); auto p = s.insert({print(*rn), rn}); if (!p.second) delete rn; } void comb_and_ins( node_set& s, skel_node& n, skel_node* p1, skel_node* p2 ) { single_node_cloner snc; skel_node * rn = snc(n); printer print; rn->add(p1); rn->add(p2); auto p = s.insert({print(*rn), rn}); if (!p.second) delete rn; } void combine( skel_node& root, vector<pair_node>&& pairs, node_set& to_set ) { for (auto& p : pairs) comb_and_ins(to_set, root, p.first, p.second); } void combine (skel_node& root, node_set&& from_set, node_set& to_set) { for (auto& it : from_set) comb_and_ins(to_set, root, it.second); } void delset( node_set& s ) { for (auto& it : s ) delete it.second; } node_set merge(node_set& s1, node_set& s2) { vector<skel_node*> nodes; for (auto& p : s2) { auto o = s1.insert(p); if (!o.second) delete p.second; } return s1; } //TODO don't clone and avoid memory leaks... vector<pair_node> allpairs( node_set&& s1, node_set&& s2) { vector<pair_node> pairs; for (auto& it1 : s1 ) for (auto& it2 : s2) pairs.push_back(make_pair(it1.second->clone(), it2.second->clone())); delset(s1); delset(s2); return pairs; }
30.138889
103
0.607742
[ "vector" ]
a25e4d5f023c77608a5392a64c68e297fecb213e
3,335
hpp
C++
src/cli/cli_ble.hpp
CAJ2/openthread
120aa72ff2268cce60f773219ebe9162d20f0b90
[ "BSD-3-Clause" ]
null
null
null
src/cli/cli_ble.hpp
CAJ2/openthread
120aa72ff2268cce60f773219ebe9162d20f0b90
[ "BSD-3-Clause" ]
null
null
null
src/cli/cli_ble.hpp
CAJ2/openthread
120aa72ff2268cce60f773219ebe9162d20f0b90
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2017, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * This file defines a simple CLI Bluetooth LE command set. */ #ifndef CLI_BLE_HPP_ #define CLI_BLE_HPP_ #include "openthread-core-config.h" #include <common/instance.hpp> #include <openthread/cli.h> #include <openthread/error.h> namespace ot { namespace Cli { class Interpreter; /** * This class implements a CLI-based Bluetooth LE example. * */ class Ble { public: /** * Constructor for ot::Cli::Ble command processor. * @param[in] aInterpreter The CLI interpreter. * */ Ble(Interpreter &aInterpreter); /** * This method interprets a list of CLI arguments. * * @param[in] argc The number of elements in argv. * @param[in] argv A pointer to an array of command line arguments. * @param[in] aServer Server object to output to. * */ otError Process(otInstance *aInstance, int argc, char *argv[]); private: struct Command { const char *mName; otError (Ble::*mCommand)(int argc, char *argv[]); }; otError ProcessHelp(int argc, char *argv[]); otError ProcessStart(int argc, char *argv[]); otError ProcessStop(int argc, char *argv[]); otError ProcessReset(int argc, char *argv[]); otError ProcessAdvertise(int argc, char *argv[]); otError ProcessScan(int argc, char *argv[]); otError ProcessConnect(int argc, char *argv[]); otError ProcessMtu(int argc, char *argv[]); otError ProcessBdAddr(int argc, char *argv[]); otError ProcessGatt(int argc, char *argv[]); otError ProcessChannel(int argc, char *argv[]); Interpreter &mInterpreter; static const Command sCommands[]; }; } // namespace Cli } // namespace ot #endif // CLI_BLE_HPP_
32.067308
79
0.703148
[ "object" ]
a25fabd6b3ed496cfa1ea95d142abef72e94c83e
431
cpp
C++
src/GameStates/GameState.cpp
marcogillies/ShooterInheritanceExample
7ee315a98e8e96d3086a354f585fa205c0608e9e
[ "MIT" ]
null
null
null
src/GameStates/GameState.cpp
marcogillies/ShooterInheritanceExample
7ee315a98e8e96d3086a354f585fa205c0608e9e
[ "MIT" ]
null
null
null
src/GameStates/GameState.cpp
marcogillies/ShooterInheritanceExample
7ee315a98e8e96d3086a354f585fa205c0608e9e
[ "MIT" ]
null
null
null
// // GameState.cpp // ShooterInhertiance // // Created by Marco Gillies on 04/03/2016. // // #include "GameState.hpp" /* * define the static variables */ std::vector<std::unique_ptr<GameState> > GameState::gameStates; int GameState::currentGameState = -1; /* * base class constructor and destructor do nothing as the * base class contains no data */ GameState::GameState() { } GameState::~GameState() { }
13.46875
63
0.670534
[ "vector" ]
a260eb02e857d0734895237c88847c32576ffbc8
8,371
cpp
C++
software/perception/registration/src/analysis/doMatching2D.cpp
liangfok/oh-distro
eeee1d832164adce667e56667dafc64a8d7b8cee
[ "BSD-3-Clause" ]
92
2016-01-14T21:03:50.000Z
2021-12-01T17:57:46.000Z
software/perception/registration/src/analysis/doMatching2D.cpp
liangfok/oh-distro
eeee1d832164adce667e56667dafc64a8d7b8cee
[ "BSD-3-Clause" ]
62
2016-01-16T18:08:14.000Z
2016-03-24T15:16:28.000Z
software/perception/registration/src/analysis/doMatching2D.cpp
liangfok/oh-distro
eeee1d832164adce667e56667dafc64a8d7b8cee
[ "BSD-3-Clause" ]
41
2016-01-14T21:26:58.000Z
2022-03-28T03:10:39.000Z
// doMatching2D // Program for 2D LIDAR alignment // using the FRSM library. It uses pretty brute force // settings. // // Options: - take 2 scans from user and give transformation between them (-a reference.csv, -b input.csv) // - loop over a dataset and give transformation between all combinations (write to file) #include <icp-registration/icp_utils.h> #include <zlib.h> #include <lcm/lcm-cpp.hpp> #include <lcmtypes/bot_core.hpp> #include <boost/shared_ptr.hpp> #include <lidar-odom/lidar-odometry.hpp> #include <lcmtypes/bot_core.hpp> #include <ConciseArgs> #include <iterator> #include <sstream> #include <iostream> void parseTransf(string& transform, float& x, float& y, float& theta) { transform.erase(std::remove(transform.begin(), transform.end(), '['), transform.end()); transform.erase(std::remove(transform.begin(), transform.end(), ']'), transform.end()); std::replace( transform.begin(), transform.end(), ',', ' '); std::replace( transform.begin(), transform.end(), ';', ' '); float transValues[3] = {0}; stringstream transStringStream(transform); for( int i = 0; i < 3; i++) { if(!(transStringStream >> transValues[i])) { cerr << "An error occured while trying to parse the initial " << "transformation." << endl << "No initial transformation will be used" << endl; return; } } x = transValues[0]; y = transValues[1]; theta = transValues[2]; } struct CommandLineConfig { std::string filenameA; std::string filenameB; }; Eigen::Isometry3d getXYThetaAsIsometry3d(Eigen::Vector3d transl, Eigen::Vector3d rpy){ Eigen::Isometry3d tf_out; tf_out.setIdentity(); tf_out.translation() << transl[0], transl[1], transl[2]; double rpy_d[3] = { rpy[0], rpy[1], rpy[2] }; double quat[4]; bot_roll_pitch_yaw_to_quat(rpy_d, quat); Eigen::Quaterniond q(quat[0], quat[1],quat[2],quat[3]); tf_out.rotate(q); return tf_out; } class App{ public: App(boost::shared_ptr<lcm::LCM> &lcm_, const CommandLineConfig& cl_cfg_, int indTransfFile); ~App(){ } const char *homedir; int num_clouds; //number of clouds to combine string cloudA; string cloudB; string initialT; // We store the transform used to initialize the // pose of cloud B. The lidar odometry class outputs the complete // transformation from the starting pose (without initialization) // of cloud B to cloud A. Instead, we want to store just the remaining // x,y,theta after initialization. ScanTransform initInput; ScanTransform initReference; void doWork(Eigen::MatrixXf &transf_matrix, int transf_index); void doWork(); private: boost::shared_ptr<lcm::LCM> lcm_; const CommandLineConfig cl_cfg_; LidarOdom* lidarOdom_; }; void readCSVFile(std::string filename, std::vector<float> &x, std::vector<float> &y){ std::vector<std::vector<double> > values; std::ifstream fin(filename.c_str()); for (std::string line; std::getline(fin, line); ) { std::replace(line.begin(), line.end(), ',', ' '); std::istringstream in(line); values.push_back( std::vector<double>(std::istream_iterator<double>(in), std::istream_iterator<double>())); } for (size_t i=0; i<values.size(); i++){ x.push_back(values[i][0]); y.push_back(values[i][1]); } } App::App(boost::shared_ptr<lcm::LCM> &lcm_, const CommandLineConfig& cl_cfg_, int indTransfFile) : lcm_(lcm_), cl_cfg_(cl_cfg_){ if ((homedir = getenv("HOME")) == NULL) { homedir = getpwuid(getuid())->pw_dir; } LidarOdomConfig lo_cfg = LidarOdomConfig(); // Overwrite default config values with more brute force search: lo_cfg.matchingMode = FRSM_GRID_COORD; lo_cfg.initialSearchRangeXY = 1.7; lo_cfg.initialSearchRangeTheta = 1.7; lo_cfg.maxSearchRangeXY = 2.0; lo_cfg.maxSearchRangeTheta = 2.0; string fileinitname; fileinitname.clear(); fileinitname.append(homedir); fileinitname.append("/logs/multisenselog__2015-11-16/initialization/initTransf.txt"); initialT = readLineFromFile(fileinitname, indTransfFile); float tmpx, tmpy, tmptheta; parseTransf(initialT, tmpx, tmpy, tmptheta); initInput.x = tmpx; initInput.y = tmpy; initInput.theta = (tmptheta * M_PI)/180; cout << "initInput: " << tmpx << "," << tmpy << "," << tmptheta << endl; initReference.x = 0; initReference.y = 0; initReference.theta = (0 * M_PI)/180; num_clouds = 10; lidarOdom_ = new LidarOdom(lcm_, lo_cfg); } void App::doWork(Eigen::MatrixXf &transf_matrix, int transf_index){ std::vector<float> xA; std::vector<float> yA; readCSVFile(cloudA, xA, yA); std::cout << xA.size() << " points in File A\n"; lidarOdom_->doOdometry(xA, yA, xA.size(), 0, &initReference); std::vector<float> xB; std::vector<float> yB; readCSVFile(cloudB, xB, yB); std::cout << xB.size() << " points in File B\n"; lidarOdom_->doOdometry(xB, yB, xB.size(), 1, &initInput); // 2. Determine the body position using the LIDAR motion estimate: /* Eigen::Isometry3d tf_01_fixed = lidarOdom_->getCurrentPose(); Eigen::Isometry3d head_to_fixscan, fixscan_to_head; head_to_fixscan = getXYThetaAsIsometry3d(transl_head_to_fixed, rpy_head_to_fixed); fixscan_to_head = head_to_fixscan.inverse(); Eigen::Isometry3d tf_01_head = fixscan_to_head * tf_01_fixed * head_to_fixscan; */ Eigen::Isometry3d tf_01_head = lidarOdom_->getCurrentPose(); Eigen::Quaterniond orientation(tf_01_head.rotation()); Eigen::Vector3d rpy = orientation.matrix().eulerAngles(0,1,2); float xres,yres,thetares; xres = tf_01_head.translation().x(); yres = tf_01_head.translation().y(); thetares = rpy[2] * 180 / M_PI; transf_matrix(0, transf_index-1) = xres; transf_matrix(1, transf_index-1) = yres; transf_matrix(2, transf_index-1) = thetares; cout << "x,y,yaw (m,m,deg): "<< xres << ", " << yres << ", " << thetares << "\n"; } int main(int argc, char **argv){ boost::shared_ptr<lcm::LCM> lcm(new lcm::LCM); if(!lcm->good()){ std::cerr <<"ERROR: lcm is not good()" <<std::endl; } CommandLineConfig cl_cfg; ConciseArgs parser(argc, argv, "simple-fusion"); parser.add(cl_cfg.filenameA, "a", "filenameA", "FilenameA.csv"); parser.add(cl_cfg.filenameB, "b", "filenameB", "FilenameB.csv"); parser.parse(); App* app = new App(lcm, cl_cfg, 0); if (cl_cfg.filenameA.empty()) { int transf_index = 0; //------------------------- // To store... int cols = 0; for (int i = app->num_clouds-1; i > 0; i--) { cols = cols + i; } Eigen::MatrixXf truth_res = Eigen::MatrixXf::Zero(3, cols); //------------------------- for (int i = 0; i < app->num_clouds-1; i++) { for (int j = 1+i; j < app->num_clouds; j++) { // Set index to load inital transformations from file transf_index++; // Name reference cloud from file app->cloudA.clear(); app->cloudA.append(app->homedir); app->cloudA.append("/logs/multisenselog__2015-11-16/planar_scans/scan_0"); app->cloudA.append(to_string(i)); app->cloudA.append(".csv"); // Name input cloud from file app->cloudB.clear(); app->cloudB.append(app->homedir); app->cloudB.append("/logs/multisenselog__2015-11-16/planar_scans/scan_0"); app->cloudB.append(to_string(j)); app->cloudB.append(".csv"); app->doWork(truth_res, transf_index); // Uncomment for visualization of matching results one by one: //cout << "Press ENTER to continue..." << endl; //cin.get(); app->~App(); app = new App(lcm, cl_cfg, transf_index); } } cout << "Final matrix:" << endl << truth_res.block(0,0,3,6) << endl; string out_file; out_file.append(app->homedir); out_file.append("/logs/multisenselog__2015-11-16/results/truth_transf.txt"); writeTransformToFile(truth_res, out_file, app->num_clouds); } else { app->~App(); app = new App(lcm, cl_cfg, 0); app->cloudA = cl_cfg.filenameA; app->cloudB = cl_cfg.filenameB; Eigen::MatrixXf truth_res = Eigen::MatrixXf::Zero(3, 1); app->doWork(truth_res, 0); } }
30.551095
106
0.638753
[ "vector", "transform" ]
a265c5f4357cc35bed42939e3248b378e6f5b64c
371
cpp
C++
src/Utility.cpp
JagerDesu/text-renderer
92c6a2b206d86fc90b62098a6435d2e232d6d729
[ "BSD-2-Clause" ]
null
null
null
src/Utility.cpp
JagerDesu/text-renderer
92c6a2b206d86fc90b62098a6435d2e232d6d729
[ "BSD-2-Clause" ]
null
null
null
src/Utility.cpp
JagerDesu/text-renderer
92c6a2b206d86fc90b62098a6435d2e232d6d729
[ "BSD-2-Clause" ]
null
null
null
#include "Utility.hpp" namespace Utility { void LoadFile(const char* path, std::vector<uint8_t>& buffer) { std::ifstream file(path, std::ios::binary); if (!file) { return; } size_t size; file.seekg(0, std::ios::end); size = file.tellg(); file.seekg(0, std::ios::beg); buffer.resize(size); file.read((char*)buffer.data(), buffer.size()); } }
20.611111
64
0.625337
[ "vector" ]
a2697bdf89b6a729e2c2853466569fd4ae0c83e2
103,304
cpp
C++
3rdparty/libVISCA2/visca/libvisca.cpp
dzyswy/stereo-client
2855500187047e535a6834dcad31cf3c6f2b86a3
[ "MIT" ]
2
2019-10-17T09:11:29.000Z
2022-01-17T06:19:25.000Z
3rdparty/libVISCA2/visca/libvisca.cpp
dzyswy/stereo-client
2855500187047e535a6834dcad31cf3c6f2b86a3
[ "MIT" ]
null
null
null
3rdparty/libVISCA2/visca/libvisca.cpp
dzyswy/stereo-client
2855500187047e535a6834dcad31cf3c6f2b86a3
[ "MIT" ]
null
null
null
/* * VISCA(tm) Camera Control Library * Copyright (C) 2002 Damien Douxchamps * * Written by Damien Douxchamps <ddouxchamps@users.sf.net> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "libvisca.h" #ifdef VISCA_WIN # ifdef _DEBUG # define DEBUG 1 # else # undef DEBUG # endif #endif /********************************/ /* PRIVATE FUNCTIONS */ /********************************/ void _VISCA_append_byte(VISCAPacket_t *packet, unsigned char byte) { packet->bytes[packet->length]=byte; (packet->length)++; } void _VISCA_init_packet(VISCAPacket_t *packet) { // we start writing at byte 1, the first byte will be filled by the // packet sending function. This function will also append a terminator. packet->length=1; } VISCA_API uint32_t _VISCA_get_reply(VISCAInterface_t *iface, VISCACamera_t *camera) { // first message: ------------------- if (_VISCA_get_packet(iface)!=VISCA_SUCCESS) return VISCA_FAILURE; iface->type=iface->ibuf[1]&0xF0; // skip ack messages while (iface->type==VISCA_RESPONSE_ACK) { if (_VISCA_get_packet(iface)!=VISCA_SUCCESS) return VISCA_FAILURE; iface->type=iface->ibuf[1]&0xF0; } switch (iface->type) { case VISCA_RESPONSE_CLEAR: return VISCA_SUCCESS; break; case VISCA_RESPONSE_ADDRESS: return VISCA_SUCCESS; break; case VISCA_RESPONSE_COMPLETED: return VISCA_SUCCESS; break; case VISCA_RESPONSE_ERROR: return VISCA_SUCCESS; break; } return VISCA_FAILURE; } VISCA_API uint32_t _VISCA_send_packet_with_reply(VISCAInterface_t *iface, VISCACamera_t *camera, VISCAPacket_t *packet) { if (_VISCA_send_packet(iface,camera,packet)!=VISCA_SUCCESS) return VISCA_FAILURE; if (_VISCA_get_reply(iface,camera)!=VISCA_SUCCESS) return VISCA_FAILURE; return VISCA_SUCCESS; } /****************************************************************************/ /* PUBLIC FUNCTIONS */ /****************************************************************************/ /***********************************/ /* SYSTEM FUNCTIONS */ /***********************************/ VISCA_API uint32_t VISCA_set_address(VISCAInterface_t *iface, int *camera_num) { VISCAPacket_t packet; int backup; VISCACamera_t camera; /* dummy camera struct */ camera.address=0; backup=iface->broadcast; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet,0x30); _VISCA_append_byte(&packet,0x01); iface->broadcast=1; if (_VISCA_send_packet(iface, &camera, &packet)!=VISCA_SUCCESS) { iface->broadcast=backup; return VISCA_FAILURE; } else iface->broadcast=backup; if (_VISCA_get_reply(iface, &camera)!=VISCA_SUCCESS) return VISCA_FAILURE; else { /* We parse the message from the camera here */ /* We expect to receive 4*camera_num bytes, every packet should be 88 30 0x FF, x being the camera id+1. The number of cams will thus be ibuf[bytes-2]-1 */ if ((iface->bytes & 0x3)!=0) /* check multiple of 4 */ return VISCA_FAILURE; else { *camera_num=iface->ibuf[iface->bytes-2]-1; if ((*camera_num==0)||(*camera_num>7)) return VISCA_FAILURE; else return VISCA_SUCCESS; } } } VISCA_API uint32_t VISCA_clear(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet,0x01); _VISCA_append_byte(&packet,0x00); _VISCA_append_byte(&packet,0x01); if (_VISCA_send_packet(iface, camera, &packet)!=VISCA_SUCCESS) return VISCA_FAILURE; else if (_VISCA_get_reply(iface, camera)!=VISCA_SUCCESS) return VISCA_FAILURE; else return VISCA_SUCCESS; } VISCA_API uint32_t VISCA_get_camera_info(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; packet.bytes[0]=0x80 | camera->address; packet.bytes[1]=0x09; packet.bytes[2]=0x00; packet.bytes[3]=0x02; packet.bytes[4]=VISCA_TERMINATOR; packet.length=5; if (_VISCA_write_packet_data(iface, camera, &packet)!=VISCA_SUCCESS) return VISCA_FAILURE; else if (_VISCA_get_reply(iface, camera)!=VISCA_SUCCESS) return VISCA_FAILURE; if (iface->bytes!= 10) /* we expect 10 bytes as answer */ return VISCA_FAILURE; else { camera->vendor=(iface->ibuf[2]<<8) + iface->ibuf[3]; camera->model=(iface->ibuf[4]<<8) + iface->ibuf[5]; camera->rom_version=(iface->ibuf[6]<<8) + iface->ibuf[7]; camera->socket_num=iface->ibuf[8]; return VISCA_SUCCESS; } } /***********************************/ /* COMMAND FUNCTIONS */ /***********************************/ VISCA_API uint32_t VISCA_set_power(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t power) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_POWER); _VISCA_append_byte(&packet, power); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_keylock(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t power) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_KEYLOCK); _VISCA_append_byte(&packet, power); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_camera_id(VISCAInterface_t *iface, VISCACamera_t *camera, uint16_t id) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_ID); _VISCA_append_byte(&packet, (id & 0xF000) >> 12); _VISCA_append_byte(&packet, (id & 0x0F00) >> 8); _VISCA_append_byte(&packet, (id & 0x00F0) >> 4); _VISCA_append_byte(&packet, (id & 0x000F)); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_zoom_tele(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_ZOOM); _VISCA_append_byte(&packet, VISCA_ZOOM_TELE); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_zoom_wide(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_ZOOM); _VISCA_append_byte(&packet, VISCA_ZOOM_WIDE); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_zoom_stop(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_ZOOM); _VISCA_append_byte(&packet, VISCA_ZOOM_STOP); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_zoom_tele_speed(VISCAInterface_t *iface, VISCACamera_t *camera, uint32_t speed) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_ZOOM); _VISCA_append_byte(&packet, VISCA_ZOOM_TELE_SPEED | (speed & 0x7)); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_zoom_wide_speed(VISCAInterface_t *iface, VISCACamera_t *camera, uint32_t speed) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_ZOOM); _VISCA_append_byte(&packet, VISCA_ZOOM_WIDE_SPEED | (speed & 0x7)); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_zoom_value(VISCAInterface_t *iface, VISCACamera_t *camera, uint32_t zoom) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_ZOOM_VALUE); _VISCA_append_byte(&packet, (zoom & 0xF000) >> 12); _VISCA_append_byte(&packet, (zoom & 0x0F00) >> 8); _VISCA_append_byte(&packet, (zoom & 0x00F0) >> 4); _VISCA_append_byte(&packet, (zoom & 0x000F)); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_zoom_and_focus_value(VISCAInterface_t *iface, VISCACamera_t *camera, uint32_t zoom, uint32_t focus) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_ZOOM_FOCUS_VALUE); _VISCA_append_byte(&packet, (zoom & 0xF000) >> 12); _VISCA_append_byte(&packet, (zoom & 0x0F00) >> 8); _VISCA_append_byte(&packet, (zoom & 0x00F0) >> 4); _VISCA_append_byte(&packet, (zoom & 0x000F)); _VISCA_append_byte(&packet, (focus & 0xF000) >> 12); _VISCA_append_byte(&packet, (focus & 0x0F00) >> 8); _VISCA_append_byte(&packet, (focus & 0x00F0) >> 4); _VISCA_append_byte(&packet, (focus & 0x000F)); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_dzoom(VISCAInterface_t *iface, VISCACamera_t *camera, uint32_t power) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_DZOOM); _VISCA_append_byte(&packet, power); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_dzoom_limit(VISCAInterface_t *iface, VISCACamera_t *camera, uint32_t limit) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_DZOOM_LIMIT); _VISCA_append_byte(&packet, limit); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_dzoom_mode(VISCAInterface_t *iface, VISCACamera_t *camera, uint32_t power) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_DZOOM_MODE); _VISCA_append_byte(&packet, power); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_focus_far(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_FOCUS); _VISCA_append_byte(&packet, VISCA_FOCUS_FAR); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_focus_near(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_FOCUS); _VISCA_append_byte(&packet, VISCA_FOCUS_NEAR); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_focus_stop(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_FOCUS); _VISCA_append_byte(&packet, VISCA_FOCUS_STOP); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_focus_far_speed(VISCAInterface_t *iface, VISCACamera_t *camera, uint32_t speed) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_FOCUS); _VISCA_append_byte(&packet, VISCA_FOCUS_FAR_SPEED | (speed & 0x7)); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_focus_near_speed(VISCAInterface_t *iface, VISCACamera_t *camera, uint32_t speed) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_FOCUS); _VISCA_append_byte(&packet, VISCA_FOCUS_NEAR_SPEED | (speed & 0x7)); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_focus_value(VISCAInterface_t *iface, VISCACamera_t *camera, uint32_t focus) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_FOCUS_VALUE); _VISCA_append_byte(&packet, (focus & 0xF000) >> 12); _VISCA_append_byte(&packet, (focus & 0x0F00) >> 8); _VISCA_append_byte(&packet, (focus & 0x00F0) >> 4); _VISCA_append_byte(&packet, (focus & 0x000F)); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_focus_auto(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t power) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_FOCUS_AUTO); _VISCA_append_byte(&packet, power); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_focus_one_push(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_FOCUS_ONE_PUSH); _VISCA_append_byte(&packet, VISCA_FOCUS_ONE_PUSH_TRIG); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_focus_infinity(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_FOCUS_ONE_PUSH); _VISCA_append_byte(&packet, VISCA_FOCUS_ONE_PUSH_INF); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_focus_autosense_high(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_FOCUS_AUTO_SENSE); _VISCA_append_byte(&packet, VISCA_FOCUS_AUTO_SENSE_HIGH); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_focus_autosense_low(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_FOCUS_AUTO_SENSE); _VISCA_append_byte(&packet, VISCA_FOCUS_AUTO_SENSE_LOW); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_focus_near_limit(VISCAInterface_t *iface, VISCACamera_t *camera, uint32_t limit) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_FOCUS_NEAR_LIMIT); _VISCA_append_byte(&packet, (limit & 0xF000) >> 12); _VISCA_append_byte(&packet, (limit & 0x0F00) >> 8); _VISCA_append_byte(&packet, (limit & 0x00F0) >> 4); _VISCA_append_byte(&packet, (limit & 0x000F)); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_whitebal_mode(VISCAInterface_t *iface, VISCACamera_t *camera, uint32_t mode) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_WB); _VISCA_append_byte(&packet, mode); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_whitebal_one_push(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_WB_TRIGGER); _VISCA_append_byte(&packet, VISCA_WB_ONE_PUSH_TRIG); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_rgain_up(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_RGAIN); _VISCA_append_byte(&packet, VISCA_UP); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_rgain_down(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_RGAIN); _VISCA_append_byte(&packet, VISCA_DOWN); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_rgain_reset(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_RGAIN); _VISCA_append_byte(&packet, VISCA_RESET); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_rgain_value(VISCAInterface_t *iface, VISCACamera_t *camera, uint32_t value) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_RGAIN_VALUE); _VISCA_append_byte(&packet, (value & 0xF000) >> 12); _VISCA_append_byte(&packet, (value & 0x0F00) >> 8); _VISCA_append_byte(&packet, (value & 0x00F0) >> 4); _VISCA_append_byte(&packet, (value & 0x000F)); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_bgain_up(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_BGAIN); _VISCA_append_byte(&packet, VISCA_UP); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_bgain_down(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_BGAIN); _VISCA_append_byte(&packet, VISCA_DOWN); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_bgain_reset(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_BGAIN); _VISCA_append_byte(&packet, VISCA_RESET); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_bgain_value(VISCAInterface_t *iface, VISCACamera_t *camera, uint32_t value) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_BGAIN_VALUE); _VISCA_append_byte(&packet, (value & 0xF000) >> 12); _VISCA_append_byte(&packet, (value & 0x0F00) >> 8); _VISCA_append_byte(&packet, (value & 0x00F0) >> 4); _VISCA_append_byte(&packet, (value & 0x000F)); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_shutter_up(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_SHUTTER); _VISCA_append_byte(&packet, VISCA_UP); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_shutter_down(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_SHUTTER); _VISCA_append_byte(&packet, VISCA_DOWN); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_shutter_reset(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_SHUTTER); _VISCA_append_byte(&packet, VISCA_RESET); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_shutter_value(VISCAInterface_t *iface, VISCACamera_t *camera, uint32_t value) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_SHUTTER_VALUE); _VISCA_append_byte(&packet, (value & 0xF000) >> 12); _VISCA_append_byte(&packet, (value & 0x0F00) >> 8); _VISCA_append_byte(&packet, (value & 0x00F0) >> 4); _VISCA_append_byte(&packet, (value & 0x000F)); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_iris_up(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_IRIS); _VISCA_append_byte(&packet, VISCA_UP); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_iris_down(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_IRIS); _VISCA_append_byte(&packet, VISCA_DOWN); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_iris_reset(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_IRIS); _VISCA_append_byte(&packet, VISCA_RESET); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_iris_value(VISCAInterface_t *iface, VISCACamera_t *camera, uint32_t value) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_IRIS_VALUE); _VISCA_append_byte(&packet, (value & 0xF000) >> 12); _VISCA_append_byte(&packet, (value & 0x0F00) >> 8); _VISCA_append_byte(&packet, (value & 0x00F0) >> 4); _VISCA_append_byte(&packet, (value & 0x000F)); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_gain_up(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_GAIN); _VISCA_append_byte(&packet, VISCA_UP); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_gain_down(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_GAIN); _VISCA_append_byte(&packet, VISCA_DOWN); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_gain_reset(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_GAIN); _VISCA_append_byte(&packet, VISCA_RESET); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_gain_value(VISCAInterface_t *iface, VISCACamera_t *camera, uint32_t value) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_GAIN_VALUE); _VISCA_append_byte(&packet, (value & 0xF000) >> 12); _VISCA_append_byte(&packet, (value & 0x0F00) >> 8); _VISCA_append_byte(&packet, (value & 0x00F0) >> 4); _VISCA_append_byte(&packet, (value & 0x000F)); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_bright_up(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_BRIGHT); _VISCA_append_byte(&packet, VISCA_UP); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_bright_down(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_BRIGHT); _VISCA_append_byte(&packet, VISCA_DOWN); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_bright_reset(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_BRIGHT); _VISCA_append_byte(&packet, VISCA_RESET); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_bright_value(VISCAInterface_t *iface, VISCACamera_t *camera, uint32_t value) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_BRIGHT_VALUE); _VISCA_append_byte(&packet, (value & 0xF000) >> 12); _VISCA_append_byte(&packet, (value & 0x0F00) >> 8); _VISCA_append_byte(&packet, (value & 0x00F0) >> 4); _VISCA_append_byte(&packet, (value & 0x000F)); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_aperture_up(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_APERTURE); _VISCA_append_byte(&packet, VISCA_UP); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_aperture_down(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_APERTURE); _VISCA_append_byte(&packet, VISCA_DOWN); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_aperture_reset(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_APERTURE); _VISCA_append_byte(&packet, VISCA_RESET); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_aperture_value(VISCAInterface_t *iface, VISCACamera_t *camera, uint32_t value) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_APERTURE_VALUE); _VISCA_append_byte(&packet, (value & 0xF000) >> 12); _VISCA_append_byte(&packet, (value & 0x0F00) >> 8); _VISCA_append_byte(&packet, (value & 0x00F0) >> 4); _VISCA_append_byte(&packet, (value & 0x000F)); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_exp_comp_up(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_EXP_COMP); _VISCA_append_byte(&packet, VISCA_UP); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_exp_comp_down(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_EXP_COMP); _VISCA_append_byte(&packet, VISCA_DOWN); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_exp_comp_reset(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_EXP_COMP); _VISCA_append_byte(&packet, VISCA_RESET); return _VISCA_send_packet_with_reply(iface, camera, &packet); return VISCA_SUCCESS; } VISCA_API uint32_t VISCA_set_exp_comp_value(VISCAInterface_t *iface, VISCACamera_t *camera, uint32_t value) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_EXP_COMP_VALUE); _VISCA_append_byte(&packet, (value & 0xF000) >> 12); _VISCA_append_byte(&packet, (value & 0x0F00) >> 8); _VISCA_append_byte(&packet, (value & 0x00F0) >> 4); _VISCA_append_byte(&packet, (value & 0x000F)); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_exp_comp_power(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t power) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_EXP_COMP_POWER); _VISCA_append_byte(&packet, power); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_auto_exp_mode(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t mode) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_AUTO_EXP); _VISCA_append_byte(&packet, mode); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_slow_shutter_auto(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t power) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_SLOW_SHUTTER); _VISCA_append_byte(&packet, power); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_backlight_comp(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t power) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_BACKLIGHT_COMP); _VISCA_append_byte(&packet, power); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_zero_lux_shot(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t power) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_ZERO_LUX); _VISCA_append_byte(&packet, power); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_ir_led(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t power) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_IR_LED); _VISCA_append_byte(&packet, power); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_wide_mode(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t mode) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_WIDE_MODE); _VISCA_append_byte(&packet, mode); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_mirror(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t power) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_MIRROR); _VISCA_append_byte(&packet, power); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_freeze(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t power) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_FREEZE); _VISCA_append_byte(&packet, power); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_picture_effect(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t mode) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_PICTURE_EFFECT); _VISCA_append_byte(&packet, mode); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_digital_effect(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t mode) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_DIGITAL_EFFECT); _VISCA_append_byte(&packet, mode); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_digital_effect_level(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t level) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_DIGITAL_EFFECT_LEVEL); _VISCA_append_byte(&packet, level); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_cam_stabilizer(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t power) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_CAM_STABILIZER); _VISCA_append_byte(&packet, power); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_memory_set(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t channel) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_MEMORY); _VISCA_append_byte(&packet, VISCA_MEMORY_SET); _VISCA_append_byte(&packet, channel); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_memory_recall(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t channel) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_MEMORY); _VISCA_append_byte(&packet, VISCA_MEMORY_RECALL); _VISCA_append_byte(&packet, channel); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_memory_reset(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t channel) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_MEMORY); _VISCA_append_byte(&packet, VISCA_MEMORY_RESET); _VISCA_append_byte(&packet, channel); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_display(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t power) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_DISPLAY); _VISCA_append_byte(&packet, power); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_date_time(VISCAInterface_t *iface, VISCACamera_t *camera, uint32_t year, uint32_t month, uint32_t day, uint32_t hour, uint32_t minute) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_DATE_TIME_SET); _VISCA_append_byte(&packet, year/10); _VISCA_append_byte(&packet, year-10*(year/10)); _VISCA_append_byte(&packet, month/10); _VISCA_append_byte(&packet, month-10*(month/10)); _VISCA_append_byte(&packet, day/10); _VISCA_append_byte(&packet, day-10*(day/10)); _VISCA_append_byte(&packet, hour/10); _VISCA_append_byte(&packet, hour-10*(hour/10)); _VISCA_append_byte(&packet, minute/10); _VISCA_append_byte(&packet, minute-10*(minute/10)); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_date_display(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t power) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_DATE_DISPLAY); _VISCA_append_byte(&packet, power); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_time_display(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t power) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_TIME_DISPLAY); _VISCA_append_byte(&packet, power); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_title_display(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t power) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_TITLE_DISPLAY); _VISCA_append_byte(&packet, power); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_title_clear(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_TITLE_DISPLAY); _VISCA_append_byte(&packet, VISCA_TITLE_DISPLAY_CLEAR); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_title_params(VISCAInterface_t *iface, VISCACamera_t *camera, VISCATitleData_t *title) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_TITLE_SET); _VISCA_append_byte(&packet, VISCA_TITLE_SET_PARAMS); _VISCA_append_byte(&packet, title->vposition); _VISCA_append_byte(&packet, title->hposition); _VISCA_append_byte(&packet, title->color); _VISCA_append_byte(&packet, title->blink); _VISCA_append_byte(&packet, 0); _VISCA_append_byte(&packet, 0); _VISCA_append_byte(&packet, 0); _VISCA_append_byte(&packet, 0); _VISCA_append_byte(&packet, 0); _VISCA_append_byte(&packet, 0); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_title(VISCAInterface_t *iface, VISCACamera_t *camera, VISCATitleData_t *title) { VISCAPacket_t packet; int i, err=0; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_TITLE_SET); _VISCA_append_byte(&packet, VISCA_TITLE_SET_PART1); for (i=0;i<10;i++) _VISCA_append_byte(&packet, title->title[i]); err+=_VISCA_send_packet_with_reply(iface, camera, &packet); _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_TITLE_SET); _VISCA_append_byte(&packet, VISCA_TITLE_SET_PART2); for (i=0;i<10;i++) _VISCA_append_byte(&packet, title->title[i+10]); err+=_VISCA_send_packet_with_reply(iface, camera, &packet); return err; } VISCA_API uint32_t VISCA_set_spot_ae_on(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_SPOT_AE); _VISCA_append_byte(&packet, VISCA_SPOT_AE_ON); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_spot_ae_off(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_SPOT_AE); _VISCA_append_byte(&packet, VISCA_SPOT_AE_OFF); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_spot_ae_position(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t x_position, uint8_t y_position) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_SPOT_AE_POSITION); _VISCA_append_byte(&packet, (x_position & 0xF0) >> 4); _VISCA_append_byte(&packet, (x_position & 0x0F)); _VISCA_append_byte(&packet, (y_position & 0xF0) >> 4); _VISCA_append_byte(&packet, (y_position & 0x0F)); return _VISCA_send_packet_with_reply(iface, camera, &packet); } /***********************************/ /* INQUIRY FUNCTIONS */ /***********************************/ VISCA_API uint32_t VISCA_get_power(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t *power) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_POWER); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *power=iface->ibuf[2]; return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_dzoom(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t *power) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_DZOOM); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *power=iface->ibuf[2]; return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_dzoom_limit(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t *value) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_DZOOM_LIMIT); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *value=iface->ibuf[2]; return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_zoom_value(VISCAInterface_t *iface, VISCACamera_t *camera, uint16_t *value) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_ZOOM_VALUE); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *value=(iface->ibuf[2]<<12)+(iface->ibuf[3]<<8)+(iface->ibuf[4]<<4)+iface->ibuf[5]; return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_focus_auto(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t *power) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_FOCUS_AUTO); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *power=iface->ibuf[2]; return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_focus_value(VISCAInterface_t *iface, VISCACamera_t *camera, uint16_t *value) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_FOCUS_VALUE); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *value=(iface->ibuf[2]<<12)+(iface->ibuf[3]<<8)+(iface->ibuf[4]<<4)+iface->ibuf[5]; return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_focus_auto_sense(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t *mode) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_FOCUS_AUTO_SENSE ); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *mode=iface->ibuf[2]; return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_focus_near_limit(VISCAInterface_t *iface, VISCACamera_t *camera, uint16_t *value) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_FOCUS_NEAR_LIMIT); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *value=(iface->ibuf[2]<<12)+(iface->ibuf[3]<<8)+(iface->ibuf[4]<<4)+iface->ibuf[5]; return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_whitebal_mode(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t *mode) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_WB); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *mode=iface->ibuf[2]; return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_rgain_value(VISCAInterface_t *iface, VISCACamera_t *camera, uint16_t *value) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_RGAIN_VALUE); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *value=(iface->ibuf[2]<<12)+(iface->ibuf[3]<<8)+(iface->ibuf[4]<<4)+iface->ibuf[5]; return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_bgain_value(VISCAInterface_t *iface, VISCACamera_t *camera, uint16_t *value) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_BGAIN_VALUE); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *value=(iface->ibuf[2]<<12)+(iface->ibuf[3]<<8)+(iface->ibuf[4]<<4)+iface->ibuf[5]; return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_auto_exp_mode(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t *mode) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_AUTO_EXP); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *mode=iface->ibuf[2]; return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_slow_shutter_auto(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t *mode) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_SLOW_SHUTTER); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *mode=iface->ibuf[2]; return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_shutter_value(VISCAInterface_t *iface, VISCACamera_t *camera, uint16_t *value) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_SHUTTER_VALUE); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *value=(iface->ibuf[2]<<12)+(iface->ibuf[3]<<8)+(iface->ibuf[4]<<4)+iface->ibuf[5]; return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_iris_value(VISCAInterface_t *iface, VISCACamera_t *camera, uint16_t *value) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_IRIS_VALUE); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *value=(iface->ibuf[2]<<12)+(iface->ibuf[3]<<8)+(iface->ibuf[4]<<4)+iface->ibuf[5]; return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_gain_value(VISCAInterface_t *iface, VISCACamera_t *camera, uint16_t *value) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_GAIN_VALUE); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *value=(iface->ibuf[2]<<12)+(iface->ibuf[3]<<8)+(iface->ibuf[4]<<4)+iface->ibuf[5]; return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_bright_value(VISCAInterface_t *iface, VISCACamera_t *camera, uint16_t *value) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_BRIGHT_VALUE); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *value=(iface->ibuf[2]<<12)+(iface->ibuf[3]<<8)+(iface->ibuf[4]<<4)+iface->ibuf[5]; return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_exp_comp_power(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t *power) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_EXP_COMP_POWER); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *power=iface->ibuf[2]; return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_exp_comp_value(VISCAInterface_t *iface, VISCACamera_t *camera, uint16_t *value) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_EXP_COMP_VALUE); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *value=(iface->ibuf[2]<<12)+(iface->ibuf[3]<<8)+(iface->ibuf[4]<<4)+iface->ibuf[5]; return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_backlight_comp(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t *power) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_BACKLIGHT_COMP); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *power=iface->ibuf[2]; return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_aperture_value(VISCAInterface_t *iface, VISCACamera_t *camera, uint16_t *value) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_APERTURE_VALUE); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *value=(iface->ibuf[2]<<12)+(iface->ibuf[3]<<8)+(iface->ibuf[4]<<4)+iface->ibuf[5]; return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_zero_lux_shot(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t *power) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_ZERO_LUX); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *power=iface->ibuf[2]; return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_ir_led(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t *power) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_IR_LED); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *power=iface->ibuf[2]; return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_wide_mode(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t *mode) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_WIDE_MODE); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *mode=iface->ibuf[2]; return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_mirror(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t *power) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_MIRROR); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *power=iface->ibuf[2]; return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_freeze(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t *power) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_FREEZE); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *power=iface->ibuf[2]; return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_picture_effect(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t *mode) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_PICTURE_EFFECT); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *mode=iface->ibuf[2]; return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_digital_effect(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t *mode) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_DIGITAL_EFFECT); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *mode=iface->ibuf[2]; return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_digital_effect_level(VISCAInterface_t *iface, VISCACamera_t *camera, uint16_t *value) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_DIGITAL_EFFECT_LEVEL); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *value=(iface->ibuf[2]<<12)+(iface->ibuf[3]<<8)+(iface->ibuf[4]<<4)+iface->ibuf[5]; return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_memory(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t *channel) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_MEMORY); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *channel=iface->ibuf[2]; return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_display(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t *power) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_DISPLAY); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *power=iface->ibuf[2]; return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_id(VISCAInterface_t *iface, VISCACamera_t *camera, uint16_t *id) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_ID); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *id=(iface->ibuf[2]<<12)+(iface->ibuf[3]<<8)+(iface->ibuf[4]<<4)+iface->ibuf[5]; return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_set_irreceive_on(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_PAN_TILTER); _VISCA_append_byte(&packet, VISCA_IRRECEIVE); _VISCA_append_byte(&packet, VISCA_IRRECEIVE_ON); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_irreceive_off(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_PAN_TILTER); _VISCA_append_byte(&packet, VISCA_IRRECEIVE); _VISCA_append_byte(&packet, VISCA_IRRECEIVE_OFF); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_irreceive_onoff(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_PAN_TILTER); _VISCA_append_byte(&packet, VISCA_IRRECEIVE); _VISCA_append_byte(&packet, VISCA_IRRECEIVE_ONOFF); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_pantilt_up(VISCAInterface_t *iface, VISCACamera_t *camera, uint32_t pan_speed, uint32_t tilt_speed) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_PAN_TILTER); _VISCA_append_byte(&packet, VISCA_PT_DRIVE); _VISCA_append_byte(&packet, pan_speed); _VISCA_append_byte(&packet, tilt_speed); _VISCA_append_byte(&packet, VISCA_PT_DRIVE_HORIZ_STOP); _VISCA_append_byte(&packet, VISCA_PT_DRIVE_VERT_UP); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_pantilt_down(VISCAInterface_t *iface, VISCACamera_t *camera, uint32_t pan_speed, uint32_t tilt_speed) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_PAN_TILTER); _VISCA_append_byte(&packet, VISCA_PT_DRIVE); _VISCA_append_byte(&packet, pan_speed); _VISCA_append_byte(&packet, tilt_speed); _VISCA_append_byte(&packet, VISCA_PT_DRIVE_HORIZ_STOP); _VISCA_append_byte(&packet, VISCA_PT_DRIVE_VERT_DOWN); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_pantilt_left(VISCAInterface_t *iface, VISCACamera_t *camera, uint32_t pan_speed, uint32_t tilt_speed) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_PAN_TILTER); _VISCA_append_byte(&packet, VISCA_PT_DRIVE); _VISCA_append_byte(&packet, pan_speed); _VISCA_append_byte(&packet, tilt_speed); _VISCA_append_byte(&packet, VISCA_PT_DRIVE_HORIZ_LEFT); _VISCA_append_byte(&packet, VISCA_PT_DRIVE_VERT_STOP); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_pantilt_right(VISCAInterface_t *iface, VISCACamera_t *camera, uint32_t pan_speed, uint32_t tilt_speed) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_PAN_TILTER); _VISCA_append_byte(&packet, VISCA_PT_DRIVE); _VISCA_append_byte(&packet, pan_speed); _VISCA_append_byte(&packet, tilt_speed); _VISCA_append_byte(&packet, VISCA_PT_DRIVE_HORIZ_RIGHT); _VISCA_append_byte(&packet, VISCA_PT_DRIVE_VERT_STOP); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_pantilt_upleft(VISCAInterface_t *iface, VISCACamera_t *camera, uint32_t pan_speed, uint32_t tilt_speed) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_PAN_TILTER); _VISCA_append_byte(&packet, VISCA_PT_DRIVE); _VISCA_append_byte(&packet, pan_speed); _VISCA_append_byte(&packet, tilt_speed); _VISCA_append_byte(&packet, VISCA_PT_DRIVE_HORIZ_LEFT); _VISCA_append_byte(&packet, VISCA_PT_DRIVE_VERT_UP); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_pantilt_upright(VISCAInterface_t *iface, VISCACamera_t *camera, uint32_t pan_speed, uint32_t tilt_speed) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_PAN_TILTER); _VISCA_append_byte(&packet, VISCA_PT_DRIVE); _VISCA_append_byte(&packet, pan_speed); _VISCA_append_byte(&packet, tilt_speed); _VISCA_append_byte(&packet, VISCA_PT_DRIVE_HORIZ_RIGHT); _VISCA_append_byte(&packet, VISCA_PT_DRIVE_VERT_UP); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_pantilt_downleft(VISCAInterface_t *iface, VISCACamera_t *camera, uint32_t pan_speed, uint32_t tilt_speed) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_PAN_TILTER); _VISCA_append_byte(&packet, VISCA_PT_DRIVE); _VISCA_append_byte(&packet, pan_speed); _VISCA_append_byte(&packet, tilt_speed); _VISCA_append_byte(&packet, VISCA_PT_DRIVE_HORIZ_LEFT); _VISCA_append_byte(&packet, VISCA_PT_DRIVE_VERT_DOWN); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_pantilt_downright(VISCAInterface_t *iface, VISCACamera_t *camera, uint32_t pan_speed, uint32_t tilt_speed) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_PAN_TILTER); _VISCA_append_byte(&packet, VISCA_PT_DRIVE); _VISCA_append_byte(&packet, pan_speed); _VISCA_append_byte(&packet, tilt_speed); _VISCA_append_byte(&packet, VISCA_PT_DRIVE_HORIZ_RIGHT); _VISCA_append_byte(&packet, VISCA_PT_DRIVE_VERT_DOWN); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_pantilt_stop(VISCAInterface_t *iface, VISCACamera_t *camera, uint32_t pan_speed, uint32_t tilt_speed) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_PAN_TILTER); _VISCA_append_byte(&packet, VISCA_PT_DRIVE); _VISCA_append_byte(&packet, pan_speed); _VISCA_append_byte(&packet, tilt_speed); _VISCA_append_byte(&packet, VISCA_PT_DRIVE_HORIZ_STOP); _VISCA_append_byte(&packet, VISCA_PT_DRIVE_VERT_STOP); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_pantilt_absolute_position(VISCAInterface_t *iface, VISCACamera_t *camera, uint32_t pan_speed, uint32_t tilt_speed, int pan_position, int tilt_position) { VISCAPacket_t packet; uint32_t pan_pos=(uint32_t) pan_position; uint32_t tilt_pos=(uint32_t) tilt_position; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_PAN_TILTER); _VISCA_append_byte(&packet, VISCA_PT_ABSOLUTE_POSITION); _VISCA_append_byte(&packet, pan_speed); _VISCA_append_byte(&packet, tilt_speed); _VISCA_append_byte(&packet, (pan_pos & 0x0f000) >> 12); _VISCA_append_byte(&packet, (pan_pos & 0x00f00) >> 8); _VISCA_append_byte(&packet, (pan_pos & 0x000f0) >> 4); _VISCA_append_byte(&packet, pan_pos & 0x0000f ); _VISCA_append_byte(&packet, (tilt_pos & 0xf000) >> 12); _VISCA_append_byte(&packet, (tilt_pos & 0x0f00) >> 8); _VISCA_append_byte(&packet, (tilt_pos & 0x00f0) >> 4); _VISCA_append_byte(&packet, tilt_pos & 0x000f); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_pantilt_relative_position(VISCAInterface_t *iface, VISCACamera_t *camera, uint32_t pan_speed, uint32_t tilt_speed, int pan_position, int tilt_position) { VISCAPacket_t packet; uint32_t pan_pos=(uint32_t) pan_position; uint32_t tilt_pos=(uint32_t) tilt_position; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_PAN_TILTER); _VISCA_append_byte(&packet, VISCA_PT_RELATIVE_POSITION); _VISCA_append_byte(&packet, pan_speed); _VISCA_append_byte(&packet, tilt_speed); _VISCA_append_byte(&packet, (pan_pos & 0x0f000) >> 12); _VISCA_append_byte(&packet, (pan_pos & 0x00f00) >> 8); _VISCA_append_byte(&packet, (pan_pos & 0x000f0) >> 4); _VISCA_append_byte(&packet, pan_pos & 0x0000f ); _VISCA_append_byte(&packet, (tilt_pos & 0xf000) >> 12); _VISCA_append_byte(&packet, (tilt_pos & 0x0f00) >> 8); _VISCA_append_byte(&packet, (tilt_pos & 0x00f0) >> 4); _VISCA_append_byte(&packet, tilt_pos & 0x000f); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_pantilt_home(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_PAN_TILTER); _VISCA_append_byte(&packet, VISCA_PT_HOME); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_pantilt_reset(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_PAN_TILTER); _VISCA_append_byte(&packet, VISCA_PT_RESET); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_pantilt_limit_upright(VISCAInterface_t *iface, VISCACamera_t *camera, int pan_position, int tilt_position) { VISCAPacket_t packet; uint32_t pan_pos=(uint32_t) pan_position; uint32_t tilt_pos=(uint32_t) tilt_position; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_PAN_TILTER); _VISCA_append_byte(&packet, VISCA_PT_LIMITSET); _VISCA_append_byte(&packet, VISCA_PT_LIMITSET_SET); _VISCA_append_byte(&packet, VISCA_PT_LIMITSET_SET_UR); _VISCA_append_byte(&packet, (pan_pos & 0xf000) >> 12); _VISCA_append_byte(&packet, (pan_pos & 0x0f00) >> 8); _VISCA_append_byte(&packet, (pan_pos & 0x00f0) >> 4); _VISCA_append_byte(&packet, pan_pos & 0x000f); _VISCA_append_byte(&packet, (tilt_pos & 0xf000) >> 12); _VISCA_append_byte(&packet, (tilt_pos & 0x0f00) >> 8); _VISCA_append_byte(&packet, (tilt_pos & 0x00f0) >> 4); _VISCA_append_byte(&packet, tilt_pos & 0x000f); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_pantilt_limit_downleft(VISCAInterface_t *iface, VISCACamera_t *camera, int pan_position, int tilt_position) { VISCAPacket_t packet; uint32_t pan_pos=(uint32_t) pan_position; uint32_t tilt_pos=(uint32_t) tilt_position; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_PAN_TILTER); _VISCA_append_byte(&packet, VISCA_PT_LIMITSET); _VISCA_append_byte(&packet, VISCA_PT_LIMITSET_SET); _VISCA_append_byte(&packet, VISCA_PT_LIMITSET_SET_DL); _VISCA_append_byte(&packet, (pan_pos & 0xf000) >> 12); _VISCA_append_byte(&packet, (pan_pos & 0x0f00) >> 8); _VISCA_append_byte(&packet, (pan_pos & 0x00f0) >> 4); _VISCA_append_byte(&packet, pan_pos & 0x000f); _VISCA_append_byte(&packet, (tilt_pos & 0xf000) >> 12); _VISCA_append_byte(&packet, (tilt_pos & 0x0f00) >> 8); _VISCA_append_byte(&packet, (tilt_pos & 0x00f0) >> 4); _VISCA_append_byte(&packet, tilt_pos & 0x000f); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_pantilt_limit_downleft_clear(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; uint32_t pan_pos=0x7fff; uint32_t tilt_pos=0x7fff; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_PAN_TILTER); _VISCA_append_byte(&packet, VISCA_PT_LIMITSET); _VISCA_append_byte(&packet, VISCA_PT_LIMITSET_CLEAR); _VISCA_append_byte(&packet, VISCA_PT_LIMITSET_SET_DL); _VISCA_append_byte(&packet, (pan_pos & 0xf000) >> 12); _VISCA_append_byte(&packet, (pan_pos & 0x0f00) >> 8); _VISCA_append_byte(&packet, (pan_pos & 0x00f0) >> 4); _VISCA_append_byte(&packet, pan_pos & 0x000f); _VISCA_append_byte(&packet, (tilt_pos & 0xf000) >> 12); _VISCA_append_byte(&packet, (tilt_pos & 0x0f00) >> 8); _VISCA_append_byte(&packet, (tilt_pos & 0x00f0) >> 4); _VISCA_append_byte(&packet, tilt_pos & 0x000f); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_pantilt_limit_upright_clear(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; uint32_t pan_pos=0x7fff; uint32_t tilt_pos=0x7fff; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_PAN_TILTER); _VISCA_append_byte(&packet, VISCA_PT_LIMITSET); _VISCA_append_byte(&packet, VISCA_PT_LIMITSET_CLEAR); _VISCA_append_byte(&packet, VISCA_PT_LIMITSET_SET_UR); _VISCA_append_byte(&packet, (pan_pos & 0xf000) >> 12); _VISCA_append_byte(&packet, (pan_pos & 0x0f00) >> 8); _VISCA_append_byte(&packet, (pan_pos & 0x00f0) >> 4); _VISCA_append_byte(&packet, pan_pos & 0x000f); _VISCA_append_byte(&packet, (tilt_pos & 0xf000) >> 12); _VISCA_append_byte(&packet, (tilt_pos & 0x0f00) >> 8); _VISCA_append_byte(&packet, (tilt_pos & 0x00f0) >> 4); _VISCA_append_byte(&packet, tilt_pos & 0x000f); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_datascreen_on(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_PAN_TILTER); _VISCA_append_byte(&packet, VISCA_PT_DATASCREEN); _VISCA_append_byte(&packet, VISCA_PT_DATASCREEN_ON); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_datascreen_off(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_PAN_TILTER); _VISCA_append_byte(&packet, VISCA_PT_DATASCREEN); _VISCA_append_byte(&packet, VISCA_PT_DATASCREEN_OFF); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_datascreen_onoff(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_PAN_TILTER); _VISCA_append_byte(&packet, VISCA_PT_DATASCREEN); _VISCA_append_byte(&packet, VISCA_PT_DATASCREEN_ONOFF); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_register(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t reg_num, uint8_t reg_val) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_REGISTER_VALUE); _VISCA_append_byte(&packet, reg_num); _VISCA_append_byte(&packet, (reg_val & 0xF0) >> 4); _VISCA_append_byte(&packet, (reg_val & 0x0F)); return _VISCA_send_packet_with_reply(iface, camera, &packet); } /***********************************/ /* INQUIRY FUNCTIONS */ /***********************************/ VISCA_API uint32_t VISCA_get_videosystem(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t *system) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_PAN_TILTER); _VISCA_append_byte(&packet, VISCA_PT_VIDEOSYSTEM_INQ); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *system=iface->ibuf[2]; return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_pantilt_mode(VISCAInterface_t *iface, VISCACamera_t *camera, uint16_t *status) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_PAN_TILTER); _VISCA_append_byte(&packet, VISCA_PT_MODE_INQ); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *status = ((iface->ibuf[2] & 0xff) << 8) + (iface->ibuf[3] & 0xff); return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_pantilt_maxspeed(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t *max_pan_speed, uint8_t *max_tilt_speed) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_PAN_TILTER); _VISCA_append_byte(&packet, VISCA_PT_MAXSPEED_INQ); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *max_pan_speed = (iface->ibuf[2] & 0xff); *max_tilt_speed = (iface->ibuf[3] & 0xff); return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_pantilt_position(VISCAInterface_t *iface, VISCACamera_t *camera, int16_t *pan_position, int16_t *tilt_position) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_PAN_TILTER); _VISCA_append_byte(&packet, VISCA_PT_POSITION_INQ); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *pan_position = ((iface->ibuf[2] & 0xf) << 12) + ((iface->ibuf[3] & 0xf) << 8) + ((iface->ibuf[4] & 0xf) << 4) + (iface->ibuf[5] & 0xf); *tilt_position = ((iface->ibuf[6] & 0xf) << 12) + ((iface->ibuf[7] & 0xf) << 8) + ((iface->ibuf[8] & 0xf) << 4) + (iface->ibuf[9] & 0xf); return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_datascreen(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t *status) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_PAN_TILTER); _VISCA_append_byte(&packet, VISCA_PT_DATASCREEN_INQ); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *status=iface->ibuf[2]; return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_register(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t reg_num, uint8_t* reg_val) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_REGISTER_VALUE); _VISCA_append_byte(&packet, reg_num); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *reg_val=(iface->ibuf[2]<<4)+iface->ibuf[3]; return VISCA_SUCCESS; } } /********************************/ /* SPECIAL FUNCTIONS FOR D30/31 */ /********************************/ VISCA_API uint32_t VISCA_set_wide_con_lens(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t power) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_WIDE_CON_LENS); _VISCA_append_byte(&packet, VISCA_WIDE_CON_LENS_SET); _VISCA_append_byte(&packet, power); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_at_mode_onoff(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_AT_MODE); _VISCA_append_byte(&packet, VISCA_AT_ONOFF); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_at_mode(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t power) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_AT_MODE); _VISCA_append_byte(&packet, power); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_at_ae_onoff(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_AT_AE); _VISCA_append_byte(&packet, VISCA_AT_ONOFF); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_at_ae(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t power) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_AT_AE); _VISCA_append_byte(&packet, power); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_at_autozoom_onoff(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_AT_AUTOZOOM); _VISCA_append_byte(&packet, VISCA_AT_ONOFF); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_at_autozoom(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t power) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_AT_AUTOZOOM); _VISCA_append_byte(&packet, power); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_atmd_framedisplay_onoff(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_ATMD_FRAMEDISPLAY); _VISCA_append_byte(&packet, VISCA_AT_ONOFF); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_atmd_framedisplay(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t power) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_ATMD_FRAMEDISPLAY); _VISCA_append_byte(&packet, power); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_at_frameoffset_onoff(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_AT_FRAMEOFFSET); _VISCA_append_byte(&packet, VISCA_AT_ONOFF); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_at_frameoffset(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t power) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_AT_FRAMEOFFSET); _VISCA_append_byte(&packet, power); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_atmd_startstop(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_ATMD_STARTSTOP); _VISCA_append_byte(&packet, VISCA_AT_ONOFF); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_at_chase(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t power) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_AT_CHASE); _VISCA_append_byte(&packet, power); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_at_chase_next(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_AT_CHASE); _VISCA_append_byte(&packet, VISCA_AT_CHASE_NEXT); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_md_mode_onoff(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_MD_MODE); _VISCA_append_byte(&packet, VISCA_MD_ONOFF); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_md_mode(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t power) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_MD_MODE); _VISCA_append_byte(&packet, power); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_md_frame(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_MD_FRAME); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_md_detect(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_MD_DETECT); _VISCA_append_byte(&packet, VISCA_MD_ONOFF); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_at_entry(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t power) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_AT_ENTRY); _VISCA_append_byte(&packet, power); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_at_lostinfo(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_PAN_TILTER); _VISCA_append_byte(&packet, VISCA_ATMD_LOSTINFO1); _VISCA_append_byte(&packet, VISCA_ATMD_LOSTINFO2); _VISCA_append_byte(&packet, VISCA_AT_LOSTINFO); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_md_lostinfo(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_PAN_TILTER); _VISCA_append_byte(&packet, VISCA_ATMD_LOSTINFO1); _VISCA_append_byte(&packet, VISCA_ATMD_LOSTINFO2); _VISCA_append_byte(&packet, VISCA_MD_LOSTINFO); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_md_adjust_ylevel(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t power) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_MD_ADJUST_YLEVEL); _VISCA_append_byte(&packet, VISCA_MD_ADJUST); _VISCA_append_byte(&packet, power); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_md_adjust_huelevel(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t power) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_MD_ADJUST_HUELEVEL); _VISCA_append_byte(&packet, VISCA_MD_ADJUST); _VISCA_append_byte(&packet, power); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_md_adjust_size(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t power) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_MD_ADJUST_SIZE); _VISCA_append_byte(&packet, VISCA_MD_ADJUST); _VISCA_append_byte(&packet, power); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_md_adjust_disptime(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t power) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_MD_ADJUST_DISPTIME); _VISCA_append_byte(&packet, VISCA_MD_ADJUST); _VISCA_append_byte(&packet, power); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_md_adjust_refmode(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t power) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_MD_ADJUST_REFMODE); _VISCA_append_byte(&packet, power); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_md_adjust_reftime(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t power) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_MD_ADJUST_REFTIME); _VISCA_append_byte(&packet, VISCA_MD_ADJUST); _VISCA_append_byte(&packet, power); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_md_measure_mode1_onoff(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_MD_MEASURE_MODE_1); _VISCA_append_byte(&packet, VISCA_MD_ONOFF); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_md_measure_mode1(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t power) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_MD_MEASURE_MODE_1); _VISCA_append_byte(&packet, power); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_md_measure_mode2_onoff(VISCAInterface_t *iface, VISCACamera_t *camera) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_MD_MEASURE_MODE_2); _VISCA_append_byte(&packet, VISCA_MD_ONOFF); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_set_md_measure_mode2(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t power) { VISCAPacket_t packet; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_COMMAND); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_MD_MEASURE_MODE_2); _VISCA_append_byte(&packet, power); return _VISCA_send_packet_with_reply(iface, camera, &packet); } VISCA_API uint32_t VISCA_get_keylock(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t *power) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_KEYLOCK); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *power=iface->ibuf[2]; return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_wide_con_lens(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t *power) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA1); _VISCA_append_byte(&packet, VISCA_WIDE_CON_LENS); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *power=iface->ibuf[2]; return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_atmd_mode(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t *power) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_ATMD_MODE); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *power=iface->ibuf[2]; return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_at_mode(VISCAInterface_t *iface, VISCACamera_t *camera, uint16_t *value) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_AT_MODE_QUERY); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *value=((iface->ibuf[2] & 0xff) << 8) + (iface->ibuf[3] & 0xff); return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_at_entry(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t *power) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_AT_ENTRY); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *power=iface->ibuf[2]; return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_md_mode(VISCAInterface_t *iface, VISCACamera_t *camera, uint16_t *value) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_MD_MODE_QUERY); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *value=((iface->ibuf[2] & 0xff) << 8) + (iface->ibuf[3] & 0xff); return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_md_ylevel(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t *power) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_MD_ADJUST_YLEVEL); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *power=(iface->ibuf[3] & 0x0f); return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_md_huelevel(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t *power) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_MD_ADJUST_HUELEVEL); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *power=(iface->ibuf[3] & 0x0f); return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_md_size(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t *power) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_MD_ADJUST_SIZE); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *power=(iface->ibuf[3] & 0x0f); return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_md_disptime(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t *power) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_MD_ADJUST_DISPTIME); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *power=(iface->ibuf[3] & 0x0f); return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_md_refmode(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t *power) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_MD_ADJUST_REFMODE); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *power=iface->ibuf[2]; return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_md_reftime(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t *power) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_MD_REFTIME_QUERY); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *power=(iface->ibuf[3] & 0x0f); return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_at_obj_pos(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t *xpos, uint8_t *ypos, uint8_t *status) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_AT_POSITION); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *xpos=iface->ibuf[2]; *ypos=iface->ibuf[3]; *status=(iface->ibuf[4] & 0x0f); return VISCA_SUCCESS; } } VISCA_API uint32_t VISCA_get_md_obj_pos(VISCAInterface_t *iface, VISCACamera_t *camera, uint8_t *xpos, uint8_t *ypos, uint8_t *status) { VISCAPacket_t packet; uint32_t err; _VISCA_init_packet(&packet); _VISCA_append_byte(&packet, VISCA_INQUIRY); _VISCA_append_byte(&packet, VISCA_CATEGORY_CAMERA2); _VISCA_append_byte(&packet, VISCA_MD_POSITION); err=_VISCA_send_packet_with_reply(iface, camera, &packet); if (err!=VISCA_SUCCESS) return err; else { *xpos=iface->ibuf[2]; *ypos=iface->ibuf[3]; *status=(iface->ibuf[4] & 0x0f); return VISCA_SUCCESS; } }
28.655756
161
0.769476
[ "model" ]
a2832571f4d6f4539c0795dc2752ea54c378483e
6,042
hpp
C++
src/Kernel/Sources/StereoCalibration.hpp
dairoku/Calibra
f482cf414c24ddbe103b49c1d3a22a8605bb9b03
[ "MIT" ]
null
null
null
src/Kernel/Sources/StereoCalibration.hpp
dairoku/Calibra
f482cf414c24ddbe103b49c1d3a22a8605bb9b03
[ "MIT" ]
null
null
null
src/Kernel/Sources/StereoCalibration.hpp
dairoku/Calibra
f482cf414c24ddbe103b49c1d3a22a8605bb9b03
[ "MIT" ]
1
2020-08-10T12:43:26.000Z
2020-08-10T12:43:26.000Z
// ============================================================================= // StereoCalibration.hpp // // MIT License // // Copyright (c) 2007-2018 Dairoku Sekiguchi // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // ============================================================================= /*! \file CameraCalibration.hpp \author Dairoku Sekiguchi \version 1.0 \date 2007/04/05 \brief This file is a part of CalibraKernel This is a direct C++ port of "Camera Calibration Toolbox for Matlab" by Jean-Yves Bouguet. Original source can be found at: http://www.vision.caltech.edu/bouguetj/calib_doc/ */ #ifndef __STEREO_CALIBRATION_HPP #define __STEREO_CALIBRATION_HPP // ----------------------------------------------------------------------------- // include files // ----------------------------------------------------------------------------- #include "CameraCalibration.hpp" // ----------------------------------------------------------------------------- // StereoCalibration class // ----------------------------------------------------------------------------- class StereoCalibration : public CameraCalibration { public: // constructor/destructor StereoCalibration(int inImageWidth, int inImageHeight); virtual ~StereoCalibration(); // member functions virtual void DoCalibration(); virtual void DumpResults(); void CalcRectifyIndex(); // member variables std::vector<ublas::matrix<double, ublas::column_major> > X_left_list; std::vector<ublas::matrix<double, ublas::column_major> > x_left_list; std::vector<ublas::matrix<double, ublas::column_major> > omc_left_list; // std::vector<ublas::matrix<double, ublas::column_major> > Rc_left_list; std::vector<ublas::matrix<double, ublas::column_major> > Tc_left_list; std::vector<ublas::matrix<double, ublas::column_major> > X_right_list; std::vector<ublas::matrix<double, ublas::column_major> > x_right_list; std::vector<ublas::matrix<double, ublas::column_major> > omc_right_list; // std::vector<ublas::matrix<double, ublas::column_major> > Rc_right_list; std::vector<ublas::matrix<double, ublas::column_major> > Tc_right_list; // std::vector<ublas::matrix<double, ublas::column_major> > y_list; // std::vector<ublas::matrix<double, ublas::column_major> > ex_list; ublas::vector<double> fc_left; ublas::vector<double> cc_left; ublas::vector<double> kc_left; double alpha_c_left; ublas::vector<double> fc_right; ublas::vector<double> cc_right; ublas::vector<double> kc_right; double alpha_c_right; ublas::matrix<double, ublas::column_major> T; ublas::matrix<double, ublas::column_major> om; ublas::matrix<double, ublas::column_major> R; ublas::vector<double> fc_left_error; ublas::vector<double> cc_left_error; ublas::vector<double> kc_left_error; double alpha_c_left_error; ublas::vector<double> fc_right_error; ublas::vector<double> cc_right_error; ublas::vector<double> kc_right_error; double alpha_c_right_error; ublas::matrix<double, ublas::column_major> T_error; ublas::matrix<double, ublas::column_major> om_error; ublas::vector<double> a1_left; ublas::vector<double> a2_left; ublas::vector<double> a3_left; ublas::vector<double> a4_left; ublas::vector<int> ind_new_left; ublas::vector<int> ind_1_left; ublas::vector<int> ind_2_left; ublas::vector<int> ind_3_left; ublas::vector<int> ind_4_left; ublas::vector<double> a1_right; ublas::vector<double> a2_right; ublas::vector<double> a3_right; ublas::vector<double> a4_right; ublas::vector<int> ind_new_right; ublas::vector<int> ind_1_right; ublas::vector<int> ind_2_right; ublas::vector<int> ind_3_right; ublas::vector<int> ind_4_right; protected: void mainOptimization(); static void compose_motion( const ublas::matrix<double, ublas::column_major> &in_om1, const ublas::matrix<double, ublas::column_major> &in_T1, const ublas::matrix<double, ublas::column_major> &in_om2, const ublas::matrix<double, ublas::column_major> &in_T2, ublas::matrix<double, ublas::column_major> &out_om3, ublas::matrix<double, ublas::column_major> &out_T3, ublas::matrix<double, ublas::column_major> &out_dom3dom1, ublas::matrix<double, ublas::column_major> &out_dom3dT1, ublas::matrix<double, ublas::column_major> &out_dom3dom2, ublas::matrix<double, ublas::column_major> &out_dom3dT2, ublas::matrix<double, ublas::column_major> &out_dT3dom1, ublas::matrix<double, ublas::column_major> &out_dT3dT1, ublas::matrix<double, ublas::column_major> &out_dT3dom2, ublas::matrix<double, ublas::column_major> &out_dT3dT2); static void dAB( const ublas::matrix<double, ublas::column_major> &in_A, const ublas::matrix<double, ublas::column_major> &in_B, ublas::matrix<double, ublas::column_major> &out_dABdA, ublas::matrix<double, ublas::column_major> &out_dABdB); }; #endif // #ifdef __STEREO_CALIBRATION_HPP
37.7625
82
0.675604
[ "vector" ]
a28faf7ff78cd5a8aff3fc1d6731c33da792ef05
3,277
cpp
C++
plugins/community/repos/AudibleInstruments/src/Shades.cpp
guillaume-plantevin/VeeSeeVSTRack
76fafc8e721613669d6f5ae82a0f58ce923a91e1
[ "Zlib", "BSD-3-Clause" ]
233
2018-07-02T16:49:36.000Z
2022-02-27T21:45:39.000Z
plugins/community/repos/AudibleInstruments/src/Shades.cpp
guillaume-plantevin/VeeSeeVSTRack
76fafc8e721613669d6f5ae82a0f58ce923a91e1
[ "Zlib", "BSD-3-Clause" ]
24
2018-07-09T11:32:15.000Z
2022-01-07T01:45:43.000Z
plugins/community/repos/AudibleInstruments/src/Shades.cpp
guillaume-plantevin/VeeSeeVSTRack
76fafc8e721613669d6f5ae82a0f58ce923a91e1
[ "Zlib", "BSD-3-Clause" ]
24
2018-07-14T21:55:30.000Z
2021-05-04T04:20:34.000Z
#include "AudibleInstruments.hpp" #include <string.h> struct Shades : Module { enum ParamIds { GAIN1_PARAM, GAIN2_PARAM, GAIN3_PARAM, MODE1_PARAM, MODE2_PARAM, MODE3_PARAM, NUM_PARAMS }; enum InputIds { IN1_INPUT, IN2_INPUT, IN3_INPUT, NUM_INPUTS }; enum OutputIds { OUT1_OUTPUT, OUT2_OUTPUT, OUT3_OUTPUT, NUM_OUTPUTS }; enum LightIds { OUT1_POS_LIGHT, OUT1_NEG_LIGHT, OUT2_POS_LIGHT, OUT2_NEG_LIGHT, OUT3_POS_LIGHT, OUT3_NEG_LIGHT, NUM_LIGHTS }; Shades() : Module(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS) {} void step() override; }; void Shades::step() { float out = 0.0; for (int i = 0; i < 3; i++) { float in = inputs[IN1_INPUT + i].normalize(5.0); if ((int)params[MODE1_PARAM + i].value == 1) { // attenuverter in *= 2.0 * params[GAIN1_PARAM + i].value - 1.0; } else { // attenuator in *= params[GAIN1_PARAM + i].value; } out += in; lights[OUT1_POS_LIGHT + 2*i].setBrightnessSmooth(fmaxf(0.0, out / 5.0)); lights[OUT1_NEG_LIGHT + 2*i].setBrightnessSmooth(fmaxf(0.0, -out / 5.0)); if (outputs[OUT1_OUTPUT + i].active) { outputs[OUT1_OUTPUT + i].value = out; out = 0.0; } } } struct ShadesWidget : ModuleWidget { ShadesWidget(Shades *module) : ModuleWidget(module) { #ifdef USE_VST2 setPanel(SVG::load(assetStaticPlugin("AudibleInstruments", "res/Shades.svg"))); #else setPanel(SVG::load(assetPlugin(plugin, "res/Shades.svg"))); #endif // USE_VST2 addChild(Widget::create<ScrewSilver>(Vec(15, 0))); addChild(Widget::create<ScrewSilver>(Vec(15, 365))); addParam(ParamWidget::create<Rogan1PSRed>(Vec(40, 40), module, Shades::GAIN1_PARAM, 0.0, 1.0, 0.5)); addParam(ParamWidget::create<Rogan1PSWhite>(Vec(40, 106), module, Shades::GAIN2_PARAM, 0.0, 1.0, 0.5)); addParam(ParamWidget::create<Rogan1PSGreen>(Vec(40, 172), module, Shades::GAIN3_PARAM, 0.0, 1.0, 0.5)); addParam(ParamWidget::create<CKSS>(Vec(10, 51), module, Shades::MODE1_PARAM, 0.0, 1.0, 1.0)); addParam(ParamWidget::create<CKSS>(Vec(10, 117), module, Shades::MODE2_PARAM, 0.0, 1.0, 1.0)); addParam(ParamWidget::create<CKSS>(Vec(10, 183), module, Shades::MODE3_PARAM, 0.0, 1.0, 1.0)); addInput(Port::create<PJ301MPort>(Vec(9, 245), Port::INPUT, module, Shades::IN1_INPUT)); addInput(Port::create<PJ301MPort>(Vec(9, 281), Port::INPUT, module, Shades::IN2_INPUT)); addInput(Port::create<PJ301MPort>(Vec(9, 317), Port::INPUT, module, Shades::IN3_INPUT)); addOutput(Port::create<PJ301MPort>(Vec(56, 245), Port::OUTPUT, module, Shades::OUT1_OUTPUT)); addOutput(Port::create<PJ301MPort>(Vec(56, 281), Port::OUTPUT, module, Shades::OUT2_OUTPUT)); addOutput(Port::create<PJ301MPort>(Vec(56, 317), Port::OUTPUT, module, Shades::OUT3_OUTPUT)); addChild(ModuleLightWidget::create<SmallLight<GreenRedLight>>(Vec(41, 254), module, Shades::OUT1_POS_LIGHT)); addChild(ModuleLightWidget::create<SmallLight<GreenRedLight>>(Vec(41, 290), module, Shades::OUT2_POS_LIGHT)); addChild(ModuleLightWidget::create<SmallLight<GreenRedLight>>(Vec(41, 326), module, Shades::OUT3_POS_LIGHT)); } }; RACK_PLUGIN_MODEL_INIT(AudibleInstruments, Shades) { Model *modelShades = Model::create<Shades, ShadesWidget>("Audible Instruments", "Shades", "Mixer", MIXER_TAG); return modelShades; }
32.127451
113
0.700336
[ "model" ]
a29864833bad8b8c389f1ec822fffa93a49a1469
2,295
hpp
C++
src/include/duckdb/common/types/hyperloglog.hpp
lokax/duckdb
c2581dfebccaebae9468c924c2c722fcf0306944
[ "MIT" ]
1
2022-01-06T17:44:07.000Z
2022-01-06T17:44:07.000Z
src/include/duckdb/common/types/hyperloglog.hpp
lokax/duckdb
c2581dfebccaebae9468c924c2c722fcf0306944
[ "MIT" ]
2
2022-02-16T08:36:03.000Z
2022-03-08T17:13:33.000Z
src/include/duckdb/common/types/hyperloglog.hpp
lokax/duckdb
c2581dfebccaebae9468c924c2c722fcf0306944
[ "MIT" ]
null
null
null
//===----------------------------------------------------------------------===// // DuckDB // // duckdb/common/types/hyperloglog.hpp // // //===----------------------------------------------------------------------===// #pragma once #include "duckdb/common/mutex.hpp" #include "duckdb/common/types/vector.hpp" #include "hyperloglog.hpp" namespace duckdb { enum class HLLStorageType { UNCOMPRESSED = 1 }; class FieldWriter; class FieldReader; //! The HyperLogLog class holds a HyperLogLog counter for approximate cardinality counting class HyperLogLog { public: HyperLogLog(); ~HyperLogLog(); // implicit copying of HyperLogLog is not allowed HyperLogLog(const HyperLogLog &) = delete; //! Adds an element of the specified size to the HyperLogLog counter void Add(data_ptr_t element, idx_t size); //! Return the count of this HyperLogLog counter idx_t Count() const; //! Merge this HyperLogLog counter with another counter to create a new one unique_ptr<HyperLogLog> Merge(HyperLogLog &other); HyperLogLog *MergePointer(HyperLogLog &other); //! Merge a set of HyperLogLogs to create one big one static unique_ptr<HyperLogLog> Merge(HyperLogLog logs[], idx_t count); //! Get the size (in bytes) of a HLL static idx_t GetSize(); //! Get pointer to the HLL data_ptr_t GetPtr() const; //! Get copy of the HLL unique_ptr<HyperLogLog> Copy(); //! (De)Serialize the HLL void Serialize(FieldWriter &writer) const; static unique_ptr<HyperLogLog> Deserialize(FieldReader &reader); public: //! Compute HLL hashes over vdata, and store them in 'hashes' //! Then, compute register indices and prefix lengths, and also store them in 'hashes' as a pair of uint32_t static void ProcessEntries(VectorData &vdata, const LogicalType &type, uint64_t hashes[], uint8_t counts[], idx_t count); //! Add the indices and counts to the logs static void AddToLogs(VectorData &vdata, idx_t count, uint64_t indices[], uint8_t counts[], HyperLogLog **logs[], const SelectionVector *log_sel); //! Add the indices and counts to THIS log void AddToLog(VectorData &vdata, idx_t count, uint64_t indices[], uint8_t counts[]); private: explicit HyperLogLog(void *hll); void *hll; mutex lock; }; } // namespace duckdb
34.772727
114
0.672767
[ "vector" ]
a29e56997e9b13ab6870ea2cd682d56288930ffe
2,232
cpp
C++
src/kalman_filter.cpp
JamesDiDonato/CarND-Extended-Kalman-Filter
79f57fbb0627a9cf9aa758fd4063eb8841a2226d
[ "MIT" ]
null
null
null
src/kalman_filter.cpp
JamesDiDonato/CarND-Extended-Kalman-Filter
79f57fbb0627a9cf9aa758fd4063eb8841a2226d
[ "MIT" ]
null
null
null
src/kalman_filter.cpp
JamesDiDonato/CarND-Extended-Kalman-Filter
79f57fbb0627a9cf9aa758fd4063eb8841a2226d
[ "MIT" ]
null
null
null
#include "kalman_filter.h" using Eigen::MatrixXd; using Eigen::VectorXd; // Please note that the Eigen library does not initialize // VectorXd or MatrixXd objects with zeros upon creation. KalmanFilter::KalmanFilter() {} KalmanFilter::~KalmanFilter() {} # define PI 3.14159265358979323846 void KalmanFilter::Init(VectorXd &x_in, MatrixXd &P_in, MatrixXd &F_in, MatrixXd &H_in, MatrixXd &R_in, MatrixXd &Q_in) { x_ = x_in; P_ = P_in; F_ = F_in; H_ = H_in; R_ = R_in; Q_ = Q_in; } void KalmanFilter::Predict() { x_ = F_ * x_; MatrixXd Ft = F_.transpose(); P_ = F_*P_*Ft + Q_; } void KalmanFilter::Update(const VectorXd &z) { // Perform Measurment Update: VectorXd z_predicton = H_ * x_; VectorXd y = z - z_predicton; // y = z - H*x' MatrixXd Ht = H_.transpose(); MatrixXd S = H_ * P_ * Ht + R_; MatrixXd Si = S.inverse(); MatrixXd K = P_ * Ht * Si; // Estimate New State: x_ = x_ + (K * y); long x_size = x_.size(); MatrixXd I = MatrixXd::Identity(x_size, x_size); P_ = (I - K * H_) * P_; } void KalmanFilter::UpdateEKF(const VectorXd &z) { // Predict the state vector by converting to polar: float px = x_(0); float py = x_(1); float vx = x_(2); float vy = x_(3); //Compute polar coordinates of position: float rho = sqrt(px*px + py*py); float theta = atan2(py,px); float rho_dot; //Avoid divide by zero: if(fabs(rho) < 0.0001){ rho_dot = 0; } else{ rho_dot = (px*vx + py*vy) / rho; } // Store measurment vector h(x') VectorXd z_prediction = VectorXd(3); z_prediction << rho,theta,rho_dot; //Perform Measurement Update: VectorXd y = z - z_prediction; // y = z - h(x') //Adjust delta phi to fit between -pi and pi float delta_phi = y(1); if(delta_phi >PI){y(1)-=2*PI;} if(delta_phi <(-PI)){y(1)+=2*PI;} MatrixXd Ht = H_.transpose(); MatrixXd S = H_ * P_ * Ht + R_; MatrixXd Si = S.inverse(); MatrixXd K = P_ * Ht * Si; //Calculate New State: x_ = x_ + (K*y); long x_size = x_.size(); MatrixXd I = MatrixXd::Identity(x_size, x_size); P_ = (I - K*H_)*P_; }
24
73
0.586022
[ "vector" ]
a2a0cdc8b37d57ce88d86d2f47d51b19cada22c4
10,890
cpp
C++
Pages/ManageTicketWidget.cpp
rafaelgc/EasyReceipt
c4dae474fff0bba14f0f64ff485e3e3e19a9f399
[ "MIT" ]
1
2021-07-12T06:36:10.000Z
2021-07-12T06:36:10.000Z
Pages/ManageTicketWidget.cpp
rafaelgc/SplitQt
c4dae474fff0bba14f0f64ff485e3e3e19a9f399
[ "MIT" ]
null
null
null
Pages/ManageTicketWidget.cpp
rafaelgc/SplitQt
c4dae474fff0bba14f0f64ff485e3e3e19a9f399
[ "MIT" ]
null
null
null
#include "ManageTicketWidget.hpp" ManageTicketWidget::ManageTicketWidget(UserContainer *userContainer, TicketContainer *ticketContainer, Config *config, QWidget *parent) : QWidget(parent),ui(new Ui::TicketManagerForm) { ui->setupUi(this); ui->historialList->installEventFilter(this); this->config = config; this->ticketContainer = ticketContainer; this->userContainer = userContainer; setupInterface(); makeConnections(); } ManageTicketWidget::~ManageTicketWidget() { delete ui; } void ManageTicketWidget::setupInterface() { costInput = new SpaceLineEdit(); costInput->setPlaceholderText(config->getMonetarySymbol()); costInput->setAlignment(Qt::AlignRight); costInput->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); QDoubleValidator *validator = new QDoubleValidator(-10000,10000,4,costInput); costInput->setValidator(validator); QFont font; font.setPixelSize(18); costInput->setFont(font); ui->topInputLayout->addWidget(costInput,1); usersInput = new PredictionLineEdit(userContainer); usersInput->setPlaceholderText("Nombre1,Nombre2,Nombre3"); usersInput->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); usersInput->setFont(font); ui->topInputLayout->addWidget(usersInput,3); okButton = new QPushButton(QIcon(":/icons/add.png"),""); okButton->setIconSize(QSize(20,20)); ui->topInputLayout->addWidget(okButton); productContextMenu = new QMenu(ui->historialList); QAction *deleteProductAction = new QAction(QIcon(":/icons/trash.png"),tr("Eliminar producto"),productContextMenu); productContextMenu->addAction(deleteProductAction); QObject::connect(deleteProductAction,SIGNAL(triggered()),this,SLOT(deleteSelectedInput())); } void ManageTicketWidget::makeConnections() { QObject::connect(usersInput,SIGNAL(returnPressed()),this,SLOT(processInput())); QObject::connect(okButton,SIGNAL(clicked()),this,SLOT(processInput())); QObject::connect(ui->deleteSelection,SIGNAL(clicked()),this,SLOT(deleteSelectedInput())); QObject::connect(ui->upSelection,SIGNAL(clicked()),this,SLOT(copyHistorialSelectionToInput())); QObject::connect(costInput,SIGNAL(spacePressed()),usersInput,SLOT(setFocus())); QObject::connect(ui->clearButton,SIGNAL(clicked()),this,SLOT(cleanAll())); QObject::connect(ui->next,SIGNAL(clicked()),this,SLOT(nextPressed())); QObject::connect(ui->cancelBtn,SIGNAL(clicked()),this,SIGNAL(goToCreateTicket())); } void ManageTicketWidget::showEvent(QShowEvent *){ costInput->setFocus(); } bool ManageTicketWidget::eventFilter(QObject *object, QEvent *event) { if (event->type()==QEvent::ContextMenu){ QContextMenuEvent *contextEvent = static_cast<QContextMenuEvent*>(event); QListWidgetItem *item = ui->historialList->itemAt(contextEvent->pos()); if (item){ productContextMenu->exec(ui->historialList->mapToGlobal(contextEvent->pos())); } } else if (event->type()==QEvent::KeyPress){ QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event); if (keyEvent->key()==Qt::Key_Delete){ if (ui->historialList->selectedItems().count()==1){ this->deleteSelectedInput(); } } } return QObject::eventFilter(object,event); } void ManageTicketWidget::processInput(){ //Nos aseguramos de que la entrada del coste no esté vacía. if (costInput->text().isEmpty()){ QMessageBox::warning(this,"Error","Introduce un coste."); return; } //Y también de que dicho valor sea un número. En principio //siempre debería serlo porque Qt lo restringe. bool conversionOk; float moneyInput = QLocale::system().toFloat(costInput->text(),&conversionOk); if (!conversionOk){ QMessageBox::warning(this,"Error",QString("Formato numérico inválido. Recuerta que debes usar '%1' como separador decimal.").arg(QLocale::system().decimalPoint())); return; } QString users = usersInput->text(); //Igualmente, se comprueba que se haya escrito algo en los usuarios. if (users.isEmpty()){ QMessageBox::warning(this,"Error","Entrada de usuarios vacía."); return; } //Por razones estéticas, si el string de los usuarios termina en , //se eliminará. if (users.endsWith(",")){ users = users.mid(0,users.length()-1); } //Se realizan los cálculos. compute(users,moneyInput); } void ManageTicketWidget::compute(QString users, float cost) { Product product(cost); QStringList tokens = users.split(","); for (QString userName : tokens){ if (!userName.isEmpty()){ if (userContainer->userExists(userName)==-1){ //Se crea un usuario volátil. userContainer->addUser(userName); //payersSelection->updatePayers(); emit volatileUserCreated(); } product.addBuyer(userName); } } Product *productPointer = ticketContainer->getCurrentTicket()->addProduct(product); addInputToHistory(productPointer); updateUsersPayout(); costInput->clear(); costInput->setFocus(); usersInput->clear(); } void ManageTicketWidget::addInputToHistory(const Product*product){ QListWidgetItem *item = new QListWidgetItem(ui->historialList); HistoryWidget *itemWidget = new HistoryWidget(product); item->setSizeHint(itemWidget->sizeHint()); //Imprescindible. ui->historialList->addItem(item); ui->historialList->setItemWidget(item,itemWidget); } void ManageTicketWidget::deleteSelectedInput(){ //Este método es el encargado de eliminar un cierto registro. Lo que tendrá //que hacer es tomar el elemento seleccionado, ver qué usuarios debían el dinero //y descontárselo. if (ui->historialList->selectedItems().count()==1){ //Se obtiene el elemento seleccionado. HistoryWidget* hi = (HistoryWidget*)ui->historialList->itemWidget(ui->historialList->selectedItems().first());//Upcast ticketContainer->getCurrentTicket()->removeProduct(hi->getProduct()); updateUsersPayout(); delete ui->historialList->takeItem(ui->historialList->currentRow()); } } void ManageTicketWidget::copyHistorialSelectionToInput(){ if (ui->historialList->selectedItems().count()==1){ HistoryWidget* hi = (HistoryWidget*)ui->historialList->itemWidget(ui->historialList->selectedItems().first());//Upcast costInput->setText(QLocale::system().toString(hi->getProduct()->getPrice())); usersInput->setText(hi->getProduct()->getStringBuyers()); usersInput->setFocus(); } } void ManageTicketWidget::updateUsersPayout(){ //La llamada a este método es un buen momento para eliminar //a los usuarios volátiles que no deban nada. for (unsigned int i = 0; i<userContainer->size(); i++){ //Si lo que debe es cero y es volátil, pues se borra. User* usr = userContainer->userAt(i); if (usr->isVolatile() && ticketContainer->getTotalSpentBy(usr->getName())==0){ userContainer->deleteUser(usr->getName()); i--; //Así solo se incrementa cuando se ha eliminado un objeto. Si no crashea. //Aunque el nombre de la señal que se va a emitir no coincide con lo que se //está haciendo, funcionará porque, al fin y al cabo, lo que se quiere hacer //es notificar que un usuario cambió para que la siguiente página se actualice. emit this->volatileUserCreated(); } } //Lo más sencillo para actualizar lo que debe pagar cada usuario //es eliminar todos los labels que contienen lo que debían y sustituirlos //por unos nuevos. //En primer lugar se eliminan los labels que antes había. Se creó un vector //específicamente para guardarlos y eliminarlos en este momento. for (unsigned int i=0; i<usersList.size(); i++){ delete usersList[i]; } //Es importante cambiar el tamaño a 0. De lo contrario se seguirá considerando //que hay un cierto número de usuarios. usersList.resize(0); /*El procedimiento ahora es iterar sobre todos los usuarios y buscar lo que * cada uno de ellos debe pagar de la factura actual. * */ for (unsigned int i = 0; i<userContainer->size(); i++){ /*Obtenermos el nombre del usuario.*/ QString currName = userContainer->userAt(i)->getName(); //Buscamos lo que el usuario debe de la factura actual. float money = ticketContainer->getCurrentTicket()->getPurchasePriceOf(currName,true); //Si no debe nada, money será 0, en ese caso no lo mostraremos. if (money>0){ /*Pero si es meyor que 0 implica que ha comprado algo por lo que *habrá que añadir un label para que el usuario lo vea. * */ QString txt = QString("%1: %2").arg(currName).arg(config->constructMoney(money)); QLabel *label = new QLabel(txt); //El objetivo de usersList es almacenar punteros a todos estos //labels para que puedan ser eliminados posteriormente. usersList.push_back(label); ui->userListLayout->addWidget(label); } } //Se actualiza el coste total de la factura. ui->totalLabel->setText(QString("%1").arg(config->constructMoney(ticketContainer->getCurrentTicket()->getTotalCost(true)))); } void ManageTicketWidget::cleanAll(){ //IMPORTANTE: Este método limpìa tanto la interfaz como el contenido del ticket actual. //Se limpia el ticket, eso quiere decir que todos los productos //que hay vinculados a él serán eliminados. ticketContainer->getCurrentTicket()->clear(); cleanUI(); } void ManageTicketWidget::nextPressed() { if (ticketContainer->getCurrentTicket()->getTotalCost()>0){ emit this->goToPayersSelection(); } else{ QMessageBox::warning(this,tr("Aviso"),tr("Antes de continuar, inserte algún producto.")); } } void ManageTicketWidget::cleanUI() { //Debe eliminarse en orden inverso (desde el final hasta el principio) for (int i=ui->historialList->count(); i>0; i--){ delete ui->historialList->takeItem(i-1); } //userContainer->cleanUpVolatileUsersIfPossible(); //Y se actualiza la interfaz gráfica para reflejar esto. this->updateUsersPayout(); //Al limpiar todo, los usuarios volátiles desaparecen, es //recomendable hacer una limpieza en payersSelection. Se manda una //señal para que se haga. emit cleanAllRequest(); } void ManageTicketWidget::fillUIFromTicket() { this->cleanUI(); Ticket *ticket = ticketContainer->getCurrentTicket(); for (unsigned int i = 0; i<ticket->countProducts(); i++){ addInputToHistory(ticket->productAt(i)); } updateUsersPayout(); }
36.915254
172
0.679706
[ "object", "vector" ]
947e3549dad002aa9639f2524bed7e0a8613e922
37,473
hh
C++
src/c++/include/alignment/FragmentMetadata.hh
Illumina/Isaac4
0924fba8b467868da92e1c48323b15d7cbca17dd
[ "BSD-3-Clause" ]
13
2018-02-09T22:59:39.000Z
2021-11-29T06:33:22.000Z
src/c++/include/alignment/FragmentMetadata.hh
Illumina/Isaac4
0924fba8b467868da92e1c48323b15d7cbca17dd
[ "BSD-3-Clause" ]
17
2018-01-26T11:36:07.000Z
2022-02-03T18:48:43.000Z
src/c++/include/alignment/FragmentMetadata.hh
Illumina/Isaac4
0924fba8b467868da92e1c48323b15d7cbca17dd
[ "BSD-3-Clause" ]
4
2018-10-19T20:00:00.000Z
2020-10-29T14:44:06.000Z
/** ** Isaac Genome Alignment Software ** Copyright (c) 2010-2017 Illumina, Inc. ** All rights reserved. ** ** This software is provided under the terms and conditions of the ** GNU GENERAL PUBLIC LICENSE Version 3 ** ** You should have received a copy of the GNU GENERAL PUBLIC LICENSE Version 3 ** along with this program. If not, see ** <https://github.com/illumina/licenses/>. ** ** \file FragmentMetadata.hh ** ** \brief Component to encapsulate all metadata associated to a fragment. ** ** \author Come Raczy **/ #ifndef iSAAC_ALIGNMENT_FRAGMENT_METADATA_HH #define iSAAC_ALIGNMENT_FRAGMENT_METADATA_HH #include <vector> #include <algorithm> #include <iostream> #include <bitset> #include "../common/StaticVector.hh" #include "alignment/AlignmentCfg.hh" #include "alignment/Mismatch.hh" #include "alignment/Cigar.hh" #include "alignment/Cluster.hh" #include "alignment/Quality.hh" #include "reference/ReferencePosition.hh" namespace isaac { namespace alignment { struct Anchor : public std::pair<unsigned short, unsigned short> { Anchor(unsigned short f, unsigned short s, bool kUnique) : std::pair<unsigned short, unsigned short>(f,s), kUnique_(kUnique)//, kRepeat_(false) {} Anchor(bool kUnique = false) : std::pair<unsigned short, unsigned short>(0,0), kUnique_(kUnique)//, kRepeat_(false) {} unsigned short length() const {return second - first;} bool empty() const {return second == first;} bool good() const {return !empty()/* && (kUnique_ || kRepeat_)*/;} bool betterThan(const Anchor &that) const {return (!empty() && that.empty()) || (good() && !that.good());} bool kUnique_ : 1; // bool kRepeat_ : 1; // friend std::ostream &operator <<(std::ostream &os, const Anchor &a) { return os << "Anchor(" << a.first << "," << a.second << "," << (a.kUnique_ ? "ku," : "") // << (a.kRepeat_ ? "kr" : "") << ")"; } }; /** ** \brief Alignment information for a fragment (as defined by the SAM Format ** Specification (v1.4-r962) ** ** This component is the building block for the FragmentBuilder. It is ** designed for efficiency, and does not involve any memory allocation (which ** is the reason why it does not and should not store the CIGAR). **/ struct FragmentMetadata { static const unsigned MAX_CYCLES = 1024; static const unsigned POSSIBLY_SEMIALIGNED_MISMATCH_COUNT = 8; /** ** \brief Cluster associated to the fragment ** ** Note, it is the responsibility of the calling code to ensure the ** validity of the cluster. **/ const Cluster *cluster; /// Id of the contig where the fragment is located unsigned contigId; /** ** \brief 0-based leftmost position of the fragment on the forward strand ** of the contig. ** ** Even though the position can become negative while building the fragment ** (before calculating the cigar), the final position will be guaranteed to ** be positive (or 0). The final position is the position of the first ** aligned base ('M', '=' or 'X'). If the read extends outside the contig, ** this will be reflected by appropriate insertions or clipping operations ** in the cigar. **/ int64_t position; /// number of bases clipped from the lowest read cycle irrespective of alignment unsigned short lowClipped; /// number of bases clipped from the highest read cycle irrespective of alignment unsigned short highClipped; // number of bases clipped due to adapter unsigned short adapterClipped_; /** ** \brief observed length of the fragment on the contig ** ** If there are no indels and no clipping, this would be the length of the ** read. With indels this is the read length minus the insertions plus the ** deletions (resp. to and from the reference). Clipped areas of the read ** are also subtracted from the length of the read. **/ // unsigned observedLength; reference::ReferencePosition rStrandPos; /// 0-based index of the read in the list of ReadMetadata unsigned readIndex; /// Orientation of the read. False is forward, true is reverse bool reverse:1; bool splitAlignment:1; bool largeDeletion:1; bool decoyAlignment:1; // number of equivalent alignments when discovered by seeds if this one is best. 1 means this is best unique alignmet. Otherwise undetermined unsigned repeatCount; /// Cigar offset in the associated cigar buffer (see FragmentBuilder) unsigned cigarOffset; /// Number of operations in the cigar unsigned cigarLength; /// Buffer containing the cigar data const Cigar *cigarBuffer; /// Number of mismatches in the alignment (can't be more than read length) unsigned mismatchCount; unsigned uncheckedSeeds; /// Number of breakpoints (indels and other splits) in the fragment unsigned gapCount; /// Edit distance from the alignment (including indels and ambiguous bases) unsigned editDistance; bool isSplit() const {return splitAlignment;} // set fo cycles containing mismatches (outside indels). typedef std::bitset<MAX_CYCLES> MismatchCycles; std::bitset<MAX_CYCLES> mismatchCycles; class ConstMismatchCycleIterator : public boost::iterator_facade< ConstMismatchCycleIterator , unsigned , boost::forward_traversal_tag , unsigned const & > { unsigned cycle_; boost::reference_wrapper<const MismatchCycles> mismatchCycles_; public: explicit ConstMismatchCycleIterator(const MismatchCycles &mismatchCycles, const std::size_t cycle = 1) : cycle_(cycle), mismatchCycles_(mismatchCycles) { ISAAC_ASSERT_MSG(cycle_, "Cycle must be a 1-based integer."); while (cycle_ != (mismatchCycles_.get().size() + 1) && !mismatchCycles_.get().test(cycle_ - 1)) ++cycle_; } private: friend class boost::iterator_core_access; void increment() { ++cycle_; while (cycle_ != (mismatchCycles_.get().size() + 1) && !mismatchCycles_.get().test(cycle_ - 1)) ++cycle_; } bool equal(ConstMismatchCycleIterator const& other) const { ISAAC_ASSERT_MSG(mismatchCycles_.get_pointer() == other.mismatchCycles_.get_pointer(), "Illegal compare for iterators of different containers."); return this->cycle_ == other.cycle_; } const unsigned &dereference() const { return cycle_; } }; /** ** \brief natural logarithm of the probability that the fragment is correct ** ** This is intrinsic to the fragment and depends only of the quality of all ** matching base and and the quality of all mismatching bases (indel are ** counted as matching bases). See AlignmentQuality for the detail of the ** probabilities used in each case. **/ double logProbability; /// lowest subsequence in the direction of the reference that anchors the alignment Anchor firstAnchor_; /// highest subsequence in the direction of the reference that anchors the alignment Anchor lastAnchor_; const Anchor &headAnchor() const {return reverse ? lastAnchor_ : firstAnchor_;} const Anchor &tailAnchor() const {return reverse ? firstAnchor_ : lastAnchor_;} Anchor &headAnchor() {return reverse ? lastAnchor_ : firstAnchor_;} Anchor &tailAnchor() {return reverse ? firstAnchor_ : lastAnchor_;} /// recompute anchor static const unsigned ALLOWED_MISMATCHES_IN_ANCHOR = 3; static const unsigned ANCHOR_LENGTH = 16; template<bool firstOnly = true> bool recomputeTailAnchor(const reference::ContigList& contigList) {return recomputeAnchor<false, firstOnly, ALLOWED_MISMATCHES_IN_ANCHOR>(contigList, ANCHOR_LENGTH); } template<bool firstOnly = true, unsigned anchorMismatches = ALLOWED_MISMATCHES_IN_ANCHOR> bool recomputeHeadAnchor(const reference::ContigList& contigList, const unsigned anchorLength = ANCHOR_LENGTH) {return recomputeAnchor<true, firstOnly, anchorMismatches>(contigList, anchorLength);} template <bool head, bool firstOnly, unsigned anchorMismatches> const Anchor computeAnchor(const reference::ContigList& contigList, const unsigned anchorLength) const { ISAAC_ASSERT_MSG(!splitAlignment, "Can't compute anchor on a split alignment:" << *this); const Sequence & strandSequence = getStrandSequence(); const reference::Contig &contig = contigList.at(getContigId()); if (head != reverse) { return makeForwardAnchor<firstOnly>( contig, anchorLength, anchorMismatches, getPosition(), strandSequence.begin(), getBeginClippedLength(), strandSequence.end() - getEndClippedLength()); } else { return makeReverseAnchor<firstOnly>( contig, anchorLength, anchorMismatches, rStrandPos.getPosition(), strandSequence, getEndClippedLength(), strandSequence.rend() - getBeginClippedLength()); } } /** ** \brief Alignment score in the global context of the reference ** ** This depends on the all the pLogCorrect values for all the possible ** alignments for this read across the whole reference. It also takes into ** account the rest-of-genome correction. Value of -1U indicates unknown alignment score. **/ unsigned alignmentScore; unsigned char mapQ; // Weighted sum of mismatch and gap penalties similar to what's used for Smith-Waterman alignment int smithWatermanScore; bool isBetterUngapped(const FragmentMetadata &right) const { return ISAAC_LP_LESS(right.logProbability, logProbability) || (ISAAC_LP_EQUALS(right.logProbability, logProbability) && smithWatermanScore < right.smithWatermanScore); } /** * \brief prefers small gaps to big or structural variants */ bool isBetterGapped(const FragmentMetadata &right) const { if (smithWatermanScore < right.smithWatermanScore) { return true; } if (smithWatermanScore == right.smithWatermanScore) { if (splitAlignment < right.splitAlignment) { return true; } else if (splitAlignment > right.splitAlignment) { return false; } // if both don't have splits pick the shortest. if (!splitAlignment && !right.splitAlignment) { if (getObservedLength() < right.getObservedLength()) { return true; } else if (right.getObservedLength() < getObservedLength()) { return false; } } //split alignment or observed lengths match return ISAAC_LP_LESS(right.logProbability, logProbability); } return false; } static bool bestUngappedLess(const FragmentMetadata &left, const FragmentMetadata &right) { return left.isBetterUngapped(right); } static bool bestGappedLess(const FragmentMetadata &left, const FragmentMetadata &right) { return left.isBetterGapped(right); } static bool alignmentsEquivalent(const FragmentMetadata &left, const FragmentMetadata &right) { return left.smithWatermanScore == right.smithWatermanScore && ISAAC_LP_EQUALS(right.logProbability, left.logProbability); } /** ** \brief Comparison of FragmentMetadata by reference position **/ bool operator<(const FragmentMetadata &f) const { ISAAC_ASSERT_MSG(cluster == f.cluster && readIndex == f.readIndex, "Comparison makes sense only for metadata representing the same fragment " << *this << " vs " << f); return (this->contigId < f.contigId || (this->contigId == f.contigId && (this->position < f.position || (this->position == f.position && (this->reverse < f.reverse || (reverse == f.reverse && (rStrandPos < f.rStrandPos || (rStrandPos == f.rStrandPos && std::lexicographical_compare(cigarBegin(), cigarEnd(), f.cigarBegin(), f.cigarEnd()) )))))))); } bool operator == (const FragmentMetadata &that) const { ISAAC_ASSERT_MSG(cluster == that.cluster && readIndex == that.readIndex, "Comparison makes sense only for metadata representing the same fragment " << *this << " vs " << that); return position == that.position && contigId == that.contigId && reverse == that.reverse && rStrandPos ==that.rStrandPos && getCigarLength() == that.getCigarLength() && std::equal(cigarBegin(), cigarEnd(), that.cigarBegin()); } bool operator != (const FragmentMetadata &that) const { return !(*this == that); } friend std::ostream &operator<<(std::ostream &os, const FragmentMetadata &f); /** * \param readLength is needed to preallocate buffer to avoid memory operations during the processing. * auxiliary code, such as unit tests, does not need to supply it. */ FragmentMetadata(): cluster(0), contigId(reference::ReferencePosition::MAX_CONTIG_ID), position(0), lowClipped(0), highClipped(0), adapterClipped_(0), rStrandPos(reference::ReferencePosition::NoMatch), readIndex(0), reverse(false), splitAlignment(false), largeDeletion(false), decoyAlignment(false), repeatCount(0), cigarOffset(0), cigarLength(0), cigarBuffer(0), mismatchCount(0), uncheckedSeeds(0), gapCount(0), editDistance(0), logProbability(0.0), firstAnchor_(0, 0, false), lastAnchor_(0, 0, false), alignmentScore(-1U), mapQ(UNKNOWN_MAPQ), smithWatermanScore(0) { } FragmentMetadata(const Cluster *cluster, unsigned readIndex): FragmentMetadata() { this->cluster = cluster; this->readIndex = readIndex; this->lastAnchor_ = Anchor(getReadLength(), getReadLength(), false); } FragmentMetadata( const Cluster *cluster, unsigned readIndex, const unsigned short lowClipped, const unsigned short highClipped, const bool reverse, const unsigned contigId, const int64_t position, const bool decoyAlignment): FragmentMetadata(cluster, readIndex) { this->contigId = contigId; this->position = position; this->decoyAlignment = decoyAlignment; this->lowClipped = lowClipped; this->highClipped = highClipped; this->reverse = reverse; } FragmentMetadata( const Cluster *cluster, unsigned readIndex, const unsigned short lowClipped, const unsigned short highClipped, const bool reverse, const unsigned contigId, const int64_t position, const bool decoyAlignment, const unsigned uncheckedSeeds): FragmentMetadata(cluster, readIndex, lowClipped, highClipped, reverse, contigId, position, decoyAlignment) { this->uncheckedSeeds = uncheckedSeeds; } bool isReverse() const {return reverse;} unsigned getReadLength() const { assert(0 != cluster); assert(cluster->size() > readIndex); return (*cluster)[readIndex].getLength(); } unsigned getReadIndex() const {return readIndex;} unsigned getObservedLength() const { ISAAC_ASSERT_MSG(!splitAlignment, "Split alignments can't have observed length" << *this); return rStrandPos.getPosition() - position; } unsigned getAlignmentScore() const {return alignmentScore;} void setAlignmentScore(unsigned as) {alignmentScore = as;} unsigned getCigarLength() const {return cigarLength;} /// Position of the first base of the fragment reference::ReferencePosition getFStrandReferencePosition() const { return !isNoMatch() ? reference::ReferencePosition(contigId, position) : reference::ReferencePosition(reference::ReferencePosition::NoMatch); } /// Position of the last base of the fragment reference::ReferencePosition getRStrandReferencePosition() const { return rStrandPos - 1; // // ensure that the position is positive! // return !isNoMatch() ? // // observedLength can be zero if the CIGAR is soft-clipped to death or in case of // // split alignment with alignment position immediately following the alignment position of the last base // // think local translocations (most of them are fake though) // reference::ReferencePosition(contigId, position + std::max(observedLength, 1U) - 1) : // reference::ReferencePosition(reference::ReferencePosition::NoMatch); } /// Position of the first aligned cycle reference::ReferencePosition getStrandReferencePosition() const { return isReverse() ? getRStrandReferencePosition() : getFStrandReferencePosition(); } /// Same as f-strand position reference::ReferencePosition getBeginReferencePosition() const { return getFStrandReferencePosition(); } /// Different from r-strand position in that it always points to the base following the last unclipped base of the fragment reference::ReferencePosition getEndReferencePosition() const { return !isNoMatch() ? rStrandPos : reference::ReferencePosition(reference::ReferencePosition::NoMatch); } /// First cycle of fragment bcl data BclClusters::const_iterator getBclData() const { return cluster->getBclData(getReadIndex()); } /// Cluster of the fragment const Cluster &getCluster() const { return *cluster; } const Read &getRead() const { return getCluster()[getReadIndex()]; } Cigar::const_iterator cigarBegin() const { ISAAC_ASSERT_MSG(isAligned(), "Requesting CIGAR of unaligned fragment is not allowed " << *this); return cigarBuffer->begin() + cigarOffset; } Cigar::const_iterator cigarEnd() const { ISAAC_ASSERT_MSG(isAligned(), "Requesting CIGAR of unaligned fragment is not allowed " << *this); return cigarBuffer->begin() + cigarOffset + cigarLength; } uint32_t getBeginClippedLength() const { if (cigarBuffer && cigarLength) { Cigar::Component operation = Cigar::decode(cigarBuffer->at(cigarOffset)); if (Cigar::SOFT_CLIP == operation.second) { return operation.first; } } return 0; } uint32_t getEndClippedLength() const { if (cigarBuffer && cigarLength) { Cigar::Component operation = Cigar::decode(cigarBuffer->at(cigarOffset + cigarLength - 1)); if (Cigar::SOFT_CLIP == operation.second) { return operation.first; } } return 0; } bool isPerfectMatch() const { return !getMismatchCount() && !getBeginClippedLength() && !getEndClippedLength(); } /// Unlike the observed length, excludes gaps (deletions and insertion bases) unsigned getMappedLength() const { ISAAC_ASSERT_MSG(cigarBuffer && cigarLength, "Read must have a valid CIGAR"); return Cigar::getMappedLength(cigarBuffer->begin() + cigarOffset, cigarBuffer->begin() + cigarOffset + cigarLength); } /** * \brief Returns unadjusted position if it is adjusted due to a soft clipping */ int64_t getUnclippedPosition() const { return position - getBeginClippedLength(); } unsigned getMismatchCount() const { return mismatchCount; } bool possiblySemialigned(const reference::ContigList &contigList, const unsigned anchorLength) const { ISAAC_ASSERT_MSG(!splitAlignment, "Not checking split alignments for being semialigned:" << *this); const Sequence & strandSequence = getStrandSequence(); const reference::Contig &contig = contigList.at(getContigId()); const unsigned semialignedMismatchesMin = anchorLength / 3; // assume semialigned is a bad gapped aligned or an ungapped aligned with 30% mismatches on one of the ends return (gapCount && semialignedMismatchesMin < mismatchCount) || makeForwardAnchor<true>( contig, anchorLength, semialignedMismatchesMin, getPosition(), strandSequence.begin(), getBeginClippedLength(), strandSequence.end() - getEndClippedLength()).empty() || makeReverseAnchor<true>( contig, anchorLength, semialignedMismatchesMin, rStrandPos.getPosition(), strandSequence, getEndClippedLength(), strandSequence.rend() - getBeginClippedLength()).empty(); } unsigned getGapCount() const { return gapCount; } unsigned getEditDistance() const { return editDistance; } ConstMismatchCycleIterator getMismatchCyclesBegin() const {return ConstMismatchCycleIterator(mismatchCycles, 1);} ConstMismatchCycleIterator getMismatchCyclesEnd() const {return ConstMismatchCycleIterator(mismatchCycles, MAX_CYCLES + 1);} void addMismatchCycle(const unsigned cycle) { ISAAC_ASSERT_MSG(cycle > 0, "Cycle numbers expected to be 1-based." << *this); ISAAC_ASSERT_MSG(MAX_CYCLES >= cycle, "Cycle number is too high. Check MAX_CYCLES." << *this); mismatchCycles.set(cycle - 1); } std::string getCigarString() const { if (cigarBuffer && cigarLength) { return Cigar::toString(*cigarBuffer, cigarOffset, cigarLength); } else { return "UNALIGNED"; } } std::ostream &serializeCigar(std::ostream &os) const { if (cigarBuffer && cigarLength) { return Cigar::toStream(cigarBuffer->begin() + cigarOffset, cigarBuffer->begin() + cigarOffset + cigarLength, os); } else { return os << "UNALIGNED"; } } /** ** \brief The cigarLength can be used to identify if a fragment has been ** successfully aligned **/ bool isAligned() const {return 0 != cigarLength;} /** ** \brief Marks read as unaligned. **/ void setUnaligned() { cigarBuffer = 0; cigarLength = 0; alignmentScore = UNKNOWN_ALIGNMENT_SCORE; mapQ = UNKNOWN_MAPQ; reverse = false, splitAlignment = false; largeDeletion = false; } /** ** \brief Marks read as something that has no match position. This is different from setUnaligned ** as unaligned shadows still have a position of their orphan **/ void setNoMatch() {setUnaligned(); contigId = reference::ReferencePosition::MAX_CONTIG_ID; position = 0;} bool isNoMatch() const {return reference::ReferencePosition::MAX_CONTIG_ID == contigId;} /** * \brief Notion of uniquely aligned in CASAVA means that a fragment was * seen to have only one candidate alignment position. As this is * highly dependent on the choice of seeds, alignment score based * approximation should do. */ bool isUniquelyAligned() const {return isAligned() && hasAlignmentScore() && (1 == repeatCount || isUnique(getAlignmentScore()));} bool isRepeat() const {return isAligned() && hasAlignmentScore() && REPEAT_ALIGNMENT_SCORE >= getAlignmentScore();} unsigned getQuality() const { const std::vector<char> &quality = getRead().getForwardQuality(); return std::accumulate(quality.begin(), quality.end(), 0U); } typedef std::vector<char> Sequence; const Sequence &getStrandSequence() const {return getRead().getStrandSequence(reverse);} const Sequence &getStrandQuality() const {return getRead().getStrandQuality(reverse);} bool hasAlignmentScore() const {return UNKNOWN_ALIGNMENT_SCORE != alignmentScore;} bool hasMapQ() const { // can't assert as dodgyMapq depends on the command line argument. //ISAAC_ASSERT_MSG(UNKNOWN_MAPQ == mapQ || isAligned(), "mapq in unaligned: " << *this); return UNKNOWN_MAPQ != mapQ;} void incrementClipLeft(const unsigned short bases) {position += bases; if (reverse) {highClipped += bases;} else {lowClipped += bases;}} void incrementClipRight(const unsigned short bases) {if (!rStrandPos.isNoMatch()){ rStrandPos -= bases; } if (reverse) {lowClipped += bases;} else {highClipped += bases;}} void incrementAdapterClip(const unsigned short bases) {adapterClipped_ += bases;} /// \return number of bases clipped on the left side of the fragment in respect to the reference unsigned short leftClipped() const {return reverse ? highClipped : lowClipped;} /// \return number of bases clipped on the right side of the fragment in respect to the reference unsigned short rightClipped() const {return reverse ? lowClipped : highClipped;} /// \return number of bases clipped on the left side of the fragment in respect to the reference unsigned short &leftClipped() {return reverse ? highClipped : lowClipped;} /// \return number of bases clipped on the right side of the fragment in respect to the reference unsigned short &rightClipped() {return reverse ? lowClipped : highClipped;} void resetAlignment() { *this = FragmentMetadata(cluster, readIndex, lowClipped, highClipped, reverse, contigId, getUnclippedPosition(), decoyAlignment, uncheckedSeeds); } void resetClipping() { ISAAC_ASSERT_MSG(!isAligned(), "Alignment must be reset before clipping"); lowClipped = 0; highClipped = 0; adapterClipped_ = 0; } unsigned getContigId() const {return contigId;} int64_t getPosition() const {return position;} unsigned updateAlignment( const bool collectMismatchCycles, const AlignmentCfg &cfg, const flowcell::ReadMetadata &readMetadata, const reference::ContigList &contigList, bool reverse, unsigned contigId, const int64_t strandPosition, const Cigar &cigarBuffer, const unsigned cigarOffset, const unsigned cigarLength = 0); static double calculateLogProbability( unsigned length, reference::Contig::const_iterator currentReference, std::vector<char>::const_iterator currentSequence, std::vector<char>::const_iterator currentQuality); private: double calculateInsertionLogProbability( unsigned length, std::vector<char>::const_iterator currentQuality) const; void addMismatchCycles( std::vector<char>::const_iterator currentSequence, reference::Contig::const_iterator currentReference, unsigned sequenceOffset, unsigned length, bool reverse, const unsigned lastCycle, const unsigned firstCycle); int64_t processBackDels(const AlignmentCfg &cfg, const Cigar &cigarBuffer, const unsigned cigarEnd, unsigned &i); unsigned processAlign( const AlignmentCfg &cfg, unsigned &currentBase, const unsigned length, const std::vector<char>::const_iterator sequenceBegin, const std::vector<char>::const_iterator qualityBegin, const reference::Contig::const_iterator referenceBegin, const bool collectMismatchCycles, const flowcell::ReadMetadata &readMetadata, const bool currentReverse, int64_t &currentPosition); void processInsertion( const AlignmentCfg& cfg, unsigned &offset, const unsigned bases, std::vector<char>::const_iterator qualityBegin); void processDeletion( const AlignmentCfg& cfg, unsigned offset, const unsigned length, const std::vector<char>::const_iterator qualityBegin, const std::vector<char>::const_iterator qualityEnd, int64_t &currentPosition); void processNegativeDeletion( const AlignmentCfg& cfg, unsigned offset, const unsigned length, const std::vector<char>::const_iterator qualityBegin, const std::vector<char>::const_iterator qualityEnd, int64_t &currentPosition); void processSoftClip( unsigned &offset, const unsigned length, const std::vector<char>::const_iterator qualityBegin); void processHardClip( unsigned &offset, const unsigned length); void processContigChange( const AlignmentCfg& cfg, const unsigned newContigId, unsigned &currentCigarOffset, const reference::ContigList& contigList, reference::Contig::const_iterator& referenceBegin, unsigned &currentContigId, int64_t &currentPosition); void processFlip( const AlignmentCfg& cfg, unsigned & currentBase, const unsigned length, bool &currentReverse, const Read& read, std::vector<char>::const_iterator& sequenceBegin, std::vector<char>::const_iterator& qualityBegin, std::vector<char>::const_iterator& qualityEnd); template <bool firstOnly> Anchor makeForwardAnchor( const reference::Contig &contig, const unsigned anchorLength, const unsigned anchorMismatches, const int64_t startPosition, const Sequence::const_iterator &forwardBegin, uint32_t startOffset, const Sequence::const_iterator &forwardEnd) const { Sequence::const_iterator s = forwardBegin + startOffset; if (std::distance(s, forwardEnd) >= anchorLength) { reference::Contig::const_iterator r = contig.begin() + startPosition; std::size_t mismatches = countMismatches(s, r, contig.end(), anchorLength, [](char c){return c;}); if (!firstOnly) { while (mismatches > anchorMismatches && forwardEnd != s + anchorLength && contig.end() != r + anchorLength) { // ISAAC_THREAD_CERR_DEV_TRACE_CLUSTER_ID(getCluster().getId(), "fmismatches:" << mismatches << " at " << // std::distance(forwardBegin, s) << " s:" << *s << " r:" << *r); mismatches += isMismatch(*(s + anchorLength), *(r + anchorLength)); mismatches -= isMismatch(*s, *r); ++s; ++r; } startOffset = std::distance(forwardBegin, s); } if (anchorMismatches >= mismatches) { const Anchor ret(startOffset, startOffset + anchorLength, false); // ISAAC_THREAD_CERR_DEV_TRACE_CLUSTER_ID(getCluster().getId(), "returning fmismatches:" << mismatches << " at " << // std::distance(forwardBegin, s) << " s:" << *s << " r:" << *r << " " << ret << " " << *this); return ret; } // ISAAC_THREAD_CERR_DEV_TRACE_CLUSTER_ID(getCluster().getId(), "returning empty fanchor:" << mismatches << " at " << // std::distance(forwardBegin, s) << " s:" << *s << " r:" << *r << " startPosition:" << startPosition); } // return empty anchor return Anchor(startOffset, startOffset, false); } template <bool firstOnly> Anchor makeReverseAnchor( const reference::Contig &contig, const unsigned anchorLength, const unsigned anchorMismatches, const int64_t endPosition, const Sequence &reverseSequence, uint32_t endOffset, const Sequence::const_reverse_iterator &reverseEnd) const { Sequence::const_reverse_iterator s = reverseSequence.rbegin() + endOffset; if (std::distance(s, reverseEnd) >= anchorLength) { reference::Contig::const_reverse_iterator r(contig.begin() + endPosition); std::size_t mismatches = countMismatches(s, r, contig.rend(), anchorLength, [](char c){return c;}); if (!firstOnly) { while (mismatches > anchorMismatches && reverseEnd != s + anchorLength && contig.rend() != r + anchorLength) { // ISAAC_THREAD_CERR_DEV_TRACE_CLUSTER_ID(getCluster().getId(), "rmismatches:" << mismatches << " at " << // std::distance(reverseSequence.rbegin(), s) << " s:" << *s << " r:" << *r); mismatches += isMismatch(*(s + anchorLength), *(r + anchorLength)); mismatches -= isMismatch(*s, *r); ++s; ++r; } endOffset = std::distance(reverseSequence.rbegin(), s); } if (anchorMismatches >= mismatches) { const Anchor ret(reverseSequence.size() - endOffset - anchorLength, reverseSequence.size() - endOffset, false); // ISAAC_THREAD_CERR_DEV_TRACE_CLUSTER_ID(getCluster().getId(), "returning rmismatches:" << mismatches << " at " << // std::distance(reverseSequence.rbegin(), s) << " s:" << *s << " r:" << *r << " " << ret << " " << *this); return ret; } // ISAAC_THREAD_CERR_DEV_TRACE_CLUSTER_ID(getCluster().getId(), "returning empty ranchor:" << mismatches << " at " << // std::distance(reverseSequence.rbegin(), s) << " s:" << *s << " r:" << *r); } // return empty anchor return Anchor(reverseSequence.size() - endOffset, reverseSequence.size() - endOffset, false); } /** * \brief @head - whether to update the anchor at the start or end of the sequence (in the direction of the cycles) */ template <bool head, bool firstOnly, unsigned anchorMismatches> bool recomputeAnchor(const reference::ContigList& contigList, const unsigned anchorLength) { if (head) { headAnchor() = computeAnchor<true, firstOnly, anchorMismatches>(contigList, anchorLength); return !headAnchor().empty(); } else { tailAnchor() = computeAnchor<false, firstOnly, anchorMismatches>(contigList, anchorLength); return !tailAnchor().empty(); } } }; #ifndef _GLIBCXX_DEBUG BOOST_STATIC_ASSERT(sizeof(FragmentMetadata) <= 256); #endif typedef std::vector<FragmentMetadata, common::NumaAllocator<FragmentMetadata, common::numa::defaultNodeLocal> > FragmentMetadataList; typedef FragmentMetadataList::const_iterator FragmentIterator; template <bool gapped> bool putBestOnTop( FragmentMetadataList &fragments) { FragmentMetadata &top = fragments.front(); FragmentMetadataList::iterator best = std::min_element(fragments.begin(), fragments.end(), gapped ? FragmentMetadata::bestGappedLess : FragmentMetadata::bestUngappedLess); ISAAC_THREAD_CERR_DEV_TRACE_CLUSTER_ID(top.getCluster().getId(), " putBest" << (gapped ? "Gapped" : "Ungapped") << "OnTop\nbest: " << *best << "\ntop:" << top); if (fragments.begin() != best) { std::swap(*best, top); return true; } return false; } inline bool clippedByReference(const reference::ContigList& contigList, FragmentMetadata const &fragment) { ISAAC_ASSERT_MSG(fragment.rStrandPos.getPosition() <= contigList.at(fragment.rStrandPos.getContigId()).size(), "rStrandPos outside contig end " << fragment); return // ignore clipped by reference begin (fragment.getBeginClippedLength() && 0 == fragment.position) || // ingnore clipped by reference end (fragment.getEndClippedLength() && fragment.rStrandPos.getPosition() == contigList.at(fragment.rStrandPos.getContigId()).size()); } inline std::ostream &operator<<(std::ostream &os, const FragmentMetadata &f) { os << "FragmentMetadata("; if (f.cluster) { os << common::makeFastIoString(f.getCluster().nameBegin(), f.getCluster().nameEnd()) << ","; } os << (f.cluster ? f.getCluster().getId() : 0UL) << "id " << f.contigId << ":" << f.position << ", " << f.rStrandPos << "rsp " << f.readIndex << (f.reverse ? 'R' : 'F') << " " << f.mismatchCount << "mm " << f.gapCount << "g " << f.editDistance << "ed "; return f.serializeCigar(os) << " " << f.decoyAlignment << "dcy " << f.splitAlignment << "sa " << f.logProbability << "lp " << f.alignmentScore << "sm " << int(f.mapQ) << "mq " << f.smithWatermanScore << "sws " << f.firstAnchor_<< "fa " << f.lastAnchor_<< "la " << f.leftClipped() << "lc " << f.rightClipped() << "rc " << f.uncheckedSeeds << "rs " << f.repeatCount << "rec)"; } } // namespace alignment } // namespace isaac #endif // #ifndef iSAAC_ALIGNMENT_FRAGMENT_METADATA_HH
39.570222
175
0.638033
[ "vector" ]
94821c57acc3cb3cf39f20a0a0caa708ee03d7d0
9,559
cpp
C++
Source/MiniSolarSystem/Private/Star.cpp
setg2002/SpaceGame
7e2c78b077e9331aec4310f6cfc9e309c2c6989b
[ "MIT" ]
1
2021-12-29T18:05:35.000Z
2021-12-29T18:05:35.000Z
Source/MiniSolarSystem/Private/Star.cpp
setg2002/SpaceGame
7e2c78b077e9331aec4310f6cfc9e309c2c6989b
[ "MIT" ]
null
null
null
Source/MiniSolarSystem/Private/Star.cpp
setg2002/SpaceGame
7e2c78b077e9331aec4310f6cfc9e309c2c6989b
[ "MIT" ]
null
null
null
// Copyright Soren Gilbertson #include "Star.h" #include "NiagaraSystem.h" #include "OverviewPlayer.h" #include "CelestialPlayer.h" #include "OrbitDebugActor.h" #include "NiagaraComponent.h" #include "CelestialGameMode.h" #include "NiagaraFunctionLibrary.h" #include "Kismet/KismetMathLibrary.h" #include "Components/SceneComponent.h" #include "Materials/MaterialInstanceDynamic.h" #include "Components/DirectionalLightComponent.h" #include "Materials/MaterialParameterCollection.h" #include "Materials/MaterialParameterCollectionInstance.h" // Delay shortcut #define LATER_SECS(seconds, ...) \ FTimerHandle __tempTimerHandle; \ GetWorldTimerManager().SetTimer(__tempTimerHandle, FTimerDelegate().CreateLambda(__VA_ARGS__), seconds, false); AStar::AStar() { Sphere = CreateDefaultSubobject<UStaticMeshComponent>(FName("Sphere")); Sphere->SetupAttachment(RootComponent); Sphere->CastShadow = 0; Sphere->bCastDynamicShadow = 0; this->initialVelocity = FVector::ZeroVector; dynamicMaterial = Sphere->CreateAndSetMaterialInstanceDynamicFromMaterial(0, Sphere->GetMaterial(0)); Sphere->SetMaterial(0, dynamicMaterial); Light = CreateDefaultSubobject<UDirectionalLightComponent>("Light"); Light->SetLightColor(FColor( FMath::Max(starProperties.color.R, uint8(178.5f)), FMath::Max(starProperties.color.G, uint8(178.5f)), FMath::Max(starProperties.color.B, uint8(178.5f)) )); SolarParticleTemplate = LoadObject<UNiagaraSystem>(NULL, TEXT("NiagaraSystem'/Game/Particles/Star/SolarNiagaraSystem.SolarNiagaraSystem'"), NULL, LOAD_None, NULL); } void AStar::OnConstruction(const FTransform & Transform) { Super::OnConstruction(Transform); } void AStar::BeginPlay() { Super::BeginPlay(); if (!ParticleComponent) { ParticleComponent = UNiagaraFunctionLibrary::SpawnSystemAttached(SolarParticleTemplate, RootComponent, FName(""), FVector::ZeroVector, FRotator::ZeroRotator, EAttachLocation::SnapToTarget, false); ParticleComponent->SetNiagaraVariableLinearColor(FString("User.StarColor"), starProperties.color); ParticleComponent->SetNiagaraVariableFloat(FString("User.Radius"), float(starProperties.radius) * 100.f); } PlanetIlluminationInst = GetWorld()->GetParameterCollectionInstance(LoadObject<UMaterialParameterCollection>(NULL, TEXT("MaterialParameterCollection'/Game/Materials/PlanetIllumination.PlanetIllumination'"), NULL, LOAD_None, NULL)); SetStarProperties(starProperties); if (Cast<ACelestialGameMode>(GetWorld()->GetAuthGameMode())->GetCurrentPerspective() == 0) { ParticleComponent->SetPaused(true); dynamicMaterial->SetScalarParameterValue("bIsPaused", 1); } } void AStar::Tick(float DeltaTime) { Super::Tick(DeltaTime); // Probably not the most effieient way of detecting a change in star properties. if (OldProperties != starProperties) { SetStarProperties(starProperties); } PlayerPawn = GetWorld()->GetFirstPlayerController()->GetPawn(); if (Cast<ACelestialPlayer>(PlayerPawn)) Light->SetWorldRotation(UKismetMathLibrary::FindLookAtRotation(this->GetActorLocation(), PlayerPawn->GetActorLocation())); else if (Cast<AOverviewPlayer>(PlayerPawn)) Light->SetWorldRotation(UKismetMathLibrary::FindLookAtRotation(this->GetActorLocation(), Cast<AOverviewPlayer>(PlayerPawn)->GetCameraLocation())); PlanetIlluminationInst->SetVectorParameterValue(FName("StarPos" + FString::FromInt(StarNum)), this->GetActorLocation()); OldProperties = starProperties; } void AStar::SetStarNum(uint8 num) { StarNum = num; if (PlanetIlluminationInst) PlanetIlluminationInst->SetScalarParameterValue(FName("StarIntensity" + FString::FromInt(StarNum)), starProperties.luminosity / 25); } bool AStar::SetStarProperties(FStarProperties NewProperties) { starProperties = NewProperties; SetRadius(starProperties.radius); SetLuminosity(starProperties.luminosity); UpdateColor(); return true; } void AStar::SetRadius(float NewRadius) { starProperties.radius = NewRadius; Collider->SetSphereRadius(NewRadius * 100); Sphere->SetRelativeScale3D(FVector(starProperties.radius, starProperties.radius, starProperties.radius)); ParticleComponent->SetNiagaraVariableFloat(FString("User.Radius"), float(starProperties.radius) * 100.f); bool WasPaused = ParticleComponent->IsPaused(); ParticleComponent->ReinitializeSystem(); LATER_SECS(0.05f, [this, WasPaused]() { ParticleComponent->SetPaused(WasPaused); }); if (Cast<ACelestialGameMode>(GetWorld()->GetAuthGameMode())->GetCurrentPerspective() == 0) AOrbitDebugActor::Get()->UpdateWidthSpecificBody(this); } void AStar::SetLuminosity(int NewLuminosity) { starProperties.luminosity = NewLuminosity; if (Sphere->GetMaterial(0) != dynamicMaterial) { dynamicMaterial = Sphere->CreateAndSetMaterialInstanceDynamicFromMaterial(0, Sphere->GetMaterial(0)); Sphere->SetMaterial(0, dynamicMaterial); } if (PlanetIlluminationInst == nullptr) PlanetIlluminationInst = GetWorld()->GetParameterCollectionInstance(planetMateralParameterCollection); dynamicMaterial->SetScalarParameterValue(FName("_glowPower"), starProperties.luminosity); PlanetIlluminationInst->SetScalarParameterValue(FName("StarIntensity" + FString::FromInt(StarNum)), starProperties.luminosity / 25); Light->SetIntensity(starProperties.luminosity / 5); } void AStar::SetColor(FColor NewColor) { starProperties.color = NewColor; UpdateColor(); } void AStar::ReInitParticles() { if (ParticleComponent) { ParticleComponent->Deactivate(); ParticleComponent->DestroyComponent(); } ParticleComponent = UNiagaraFunctionLibrary::SpawnSystemAttached(SolarParticleTemplate, RootComponent, FName(""), FVector::ZeroVector, FRotator::ZeroRotator, EAttachLocation::SnapToTarget, false); ParticleComponent->SetNiagaraVariableLinearColor(FString("User.StarColor"), starProperties.color); ParticleComponent->SetNiagaraVariableFloat(FString("User.Radius"), float(starProperties.radius) * 100.f); ParticleComponent->ReinitializeSystem(); } void AStar::UpdateColor() { if (Sphere->GetMaterial(0) != dynamicMaterial) { dynamicMaterial = Sphere->CreateAndSetMaterialInstanceDynamicFromMaterial(0, Sphere->GetMaterial(0)); Sphere->SetMaterial(0, dynamicMaterial); } dynamicMaterial->SetVectorParameterValue(FName("_baseColor"), starProperties.color); ParticleComponent->SetNiagaraVariableLinearColor(FString("User.StarColor"), starProperties.color); Light->SetLightColor(FColor( FMath::Max(starProperties.color.R, uint8(178.5f)), FMath::Max(starProperties.color.G, uint8(178.5f)), FMath::Max(starProperties.color.B, uint8(178.5f)) )); } #if WITH_EDITOR void AStar::PostEditChangeProperty(FPropertyChangedEvent & PropertyChangedEvent) { if (PropertyChangedEvent.Property != nullptr) { const FName PropertyName(PropertyChangedEvent.Property->GetName()); if (PropertyName == GET_MEMBER_NAME_CHECKED(FStarProperties, radius)) { Sphere->SetRelativeScale3D(FVector(starProperties.radius, starProperties.radius, starProperties.radius)); ParticleComponent->SetNiagaraVariableFloat(FString("User.Radius"), float(starProperties.radius) * 100.f); } if (PropertyName == GET_MEMBER_NAME_CHECKED(FStarProperties, mass)) { this->mass = starProperties.mass; } if (PropertyName == GET_MEMBER_NAME_CHECKED(FStarProperties, color)) { if (Sphere->GetMaterial(0) != dynamicMaterial) { dynamicMaterial = Sphere->CreateAndSetMaterialInstanceDynamicFromMaterial(0, Sphere->GetMaterial(0)); Sphere->SetMaterial(0, dynamicMaterial); } if (PlanetIlluminationInst == nullptr) { PlanetIlluminationInst = GetWorld()->GetParameterCollectionInstance(planetMateralParameterCollection); } UpdateColor(); } if (PropertyName == GET_MEMBER_NAME_CHECKED(FStarProperties, luminosity)) { if (Sphere->GetMaterial(0) != dynamicMaterial) { dynamicMaterial = Sphere->CreateAndSetMaterialInstanceDynamicFromMaterial(0, Sphere->GetMaterial(0)); Sphere->SetMaterial(0, dynamicMaterial); } if (PlanetIlluminationInst == nullptr) { PlanetIlluminationInst = GetWorld()->GetParameterCollectionInstance(planetMateralParameterCollection); } dynamicMaterial->SetScalarParameterValue(FName("_glowPower"), starProperties.luminosity); PlanetIlluminationInst->SetScalarParameterValue(FName("StarLuminosity"), starProperties.luminosity); Light->SetIntensity(starProperties.luminosity / 5); } if (PropertyName == GET_MEMBER_NAME_CHECKED(AStar, starType)) { static const FString ContextString(TEXT("Star Type")); starProperties = *(starTypeData->FindRow<FStarProperties>(FName(UEnum::GetValueAsString<EStarType>(starType.GetValue())), ContextString, true)); Sphere->SetRelativeScale3D(FVector(starProperties.radius, starProperties.radius, starProperties.radius)); this->mass = starProperties.mass; if (Sphere->GetMaterial(0) != dynamicMaterial) { dynamicMaterial = Sphere->CreateAndSetMaterialInstanceDynamicFromMaterial(0, Sphere->GetMaterial(0)); Sphere->SetMaterial(0, dynamicMaterial); } dynamicMaterial->SetVectorParameterValue(FName("_baseColor"), starProperties.color); dynamicMaterial->SetScalarParameterValue(FName("_glowPower"), starProperties.luminosity); } } Super::PostEditChangeProperty(PropertyChangedEvent); } void AStar::PostEditMove(bool bFinished) { Super::PostEditMove(bFinished); if (PlanetIlluminationInst == nullptr) { PlanetIlluminationInst = GetWorld()->GetParameterCollectionInstance(planetMateralParameterCollection); } PlanetIlluminationInst->SetVectorParameterValue(FName("SunLocation"), this->GetActorLocation()); } #endif
38.236
232
0.785333
[ "transform" ]
9484fbf7dfb2db865c35eaca614d8f272e471296
920
cc
C++
src/other/stepcode/src/clSchemas/example/schema.cc
Zitara/BRLCAD
620449d036e38bd52257f6b5b10daa55d9284900
[ "BSD-4-Clause", "BSD-3-Clause" ]
35
2015-03-11T11:51:48.000Z
2021-07-25T16:04:49.000Z
src/other/stepcode/src/clSchemas/example/schema.cc
pombredanne/sf.net-brlcad
fb56f37c201b51241e8f3aa7b979436856f43b8c
[ "BSD-4-Clause", "BSD-3-Clause" ]
null
null
null
src/other/stepcode/src/clSchemas/example/schema.cc
pombredanne/sf.net-brlcad
fb56f37c201b51241e8f3aa7b979436856f43b8c
[ "BSD-4-Clause", "BSD-3-Clause" ]
19
2016-05-04T08:39:37.000Z
2021-12-07T12:45:54.000Z
#ifndef SCHEMA_CC #define SCHEMA_CC // This file was generated by exp2cxx. You probably don't want to edit // it since your modifications will be lost if exp2cxx is used to // regenerate it. /* $Id$ */ #include <schema.h> class Registry; void SchemaInit( Registry & reg ) { extern void InitSchemasAndEnts( Registry & r ); InitSchemasAndEnts( reg ); extern void SdaiEXAMPLE_SCHEMAInit( Registry & r ); SdaiEXAMPLE_SCHEMAInit( reg ); reg.SetCompCollect( gencomplex() ); } // Generate a function to be called by Model to help it // create the necessary Model_contents without the // dictionary (Registry) handle since it doesn't have a // predetermined way to access to the handle. SDAI_Model_contents_ptr GetModelContents( char * schemaName ) { if( !strcmp( schemaName, "example_schema" ) ) { return ( SDAI_Model_contents_ptr ) new SdaiModel_contents_example_schema; } } #endif
30.666667
81
0.726087
[ "model" ]
9485fd3664f0da6b88038e5563d8324a1f40469b
7,125
cpp
C++
tools/model_compiler/mesh_builder.cpp
SharpLinesTech/slt_tech_runtime
53689dd1d4907659335187d10621d9785c0164e0
[ "Apache-2.0" ]
null
null
null
tools/model_compiler/mesh_builder.cpp
SharpLinesTech/slt_tech_runtime
53689dd1d4907659335187d10621d9785c0164e0
[ "Apache-2.0" ]
null
null
null
tools/model_compiler/mesh_builder.cpp
SharpLinesTech/slt_tech_runtime
53689dd1d4907659335187d10621d9785c0164e0
[ "Apache-2.0" ]
null
null
null
#include "slt/log/log.h" #include "mesh_builder.h" slt::Setting<std::string> vertex_attrib_name( "slt_vertex", "vertex_attrib", "The attribute name to assign tp vertices when exporting a mesh."); slt::Setting<std::string> normal_attrib_name("slt_normal", "normal_attrib", "The attribute name to give " "normals when exporting a mesh " "(set to empty to not export " "normals)."); slt::Setting<std::string> uv_attrib_name("slt_uv", "uv_attrib", "The attribute name to give " "UVs when exporting a mesh " "(set to empty to not export " "normals)."); namespace { template <typename LAYER_ELEM_T> size_t resolveAttribIndex(FbxMesh* mesh, LAYER_ELEM_T& layer_elements, unsigned int vertex_index, int poly_id, int v_id) { size_t result = 0; auto mapping_mode = layer_elements.GetMappingMode(); auto ref_mode = layer_elements.GetReferenceMode(); switch(mapping_mode) { case FbxGeometryElement::eByControlPoint: result = mesh->GetPolygonVertex(poly_id, v_id); break; case FbxGeometryElement::eByPolygonVertex: result = vertex_index; break; default: slt::log->error("Unhandled attrib mapping mode"); std::terminate(); break; } switch(ref_mode) { case FbxGeometryElement::eDirect: break; case FbxGeometryElement::eIndexToDirect: result = layer_elements.GetIndexArray().GetAt(int(result)); break; default: slt::log->error("Unhandled attrib ref mode"); std::terminate(); break; } return result; } template <typename LAYER_ELEM_T> slt::tools::MeshBuilder::SingleAttriData extractAttrib( FbxMesh* mesh, std::string const& name, LAYER_ELEM_T& layer_elements, unsigned int dims) { unsigned int vertex_id = 0; slt::tools::MeshBuilder::SingleAttriData result; result.name = name; result.dim = dims; auto polys = mesh->GetPolygonCount(); for(auto p = 0; p < polys; p++) { int p_size = mesh->GetPolygonSize(p); SLT_ASSERT_EQ(p_size, 3); for(int point = 0; point < p_size; ++point) { std::size_t attr_index = resolveAttribIndex(mesh, layer_elements, vertex_id, p, point); auto attrib_data = layer_elements.GetDirectArray().GetAt(int(attr_index)); for(unsigned int i = 0; i < dims; ++i) { result.data.emplace_back(float(attrib_data[i])); } ++vertex_id; } } return result; } slt::render::ModelData compileModel( std::vector<slt::tools::MeshBuilder::SingleAttriData> data) { std::vector<uint16_t> tri_indices; auto raw_vertex_count = data[0].data.size() / data[0].dim; SLT_ASSERT_EQ(raw_vertex_count % 3, 0); // Aren't we building triangles? for(auto const& raw_attrib : data) { SLT_ASSERT_EQ(raw_attrib.data.size(), raw_vertex_count * raw_attrib.dim); } std::vector<float> final_data; std::map<std::vector<float>, unsigned int> reverse_vertex_map; for(std::size_t i = 0; i < raw_vertex_count; ++i) { std::vector<float> vertex; for(auto const& raw_attrib : data) { auto data_start = i * raw_attrib.dim; auto data_end = (i + 1) * raw_attrib.dim; vertex.insert(vertex.end(), raw_attrib.data.begin() + data_start, raw_attrib.data.begin() + data_end); } auto found = reverse_vertex_map.find(vertex); if(found == reverse_vertex_map.end()) { unsigned int new_vertex_index = unsigned int(reverse_vertex_map.size()); final_data.insert(final_data.end(), vertex.begin(), vertex.end()); reverse_vertex_map.emplace(vertex, new_vertex_index); tri_indices.emplace_back(new_vertex_index); } else { tri_indices.emplace_back(found->second); } } slt::render::ModelData result; result.drawOp_.prim = slt::render::PrimType::TRIANGLES; result.drawOp_.indices = std::move(tri_indices); result.data_ = std::move(final_data); uint16_t offset = 0; for(auto const& raw_attrib : data) { slt::render::ModelAttrib built_attrib; built_attrib.name = raw_attrib.name; built_attrib.dimensions = raw_attrib.dim; built_attrib.offset = offset; offset += raw_attrib.dim; result.attribs_.emplace_back(built_attrib); } return result; } } namespace slt { namespace tools { MeshBuilder::MeshBuilder(FbxMesh* mesh) : mesh_(mesh) {} MeshBuilder::SingleAttriData MeshBuilder::getVertices() { SingleAttriData result; result.dim = 3; result.name = vertex_attrib_name.get(); slt::log->info("using vertex attrib name: {}", vertex_attrib_name.get()); auto points = mesh_->GetControlPoints(); float scale = 0.01f; scale *= (float)mesh_->GetScene() ->GetGlobalSettings() .GetSystemUnit() .GetScaleFactor(); auto polys = mesh_->GetPolygonCount(); unsigned int vertex_id = 0; for(auto poly = 0; poly < polys; poly++) { int p_size = mesh_->GetPolygonSize(poly); if(p_size != 3) { slt::log->error("Non triangle mesh: {}", mesh_->GetNode()->GetName()); std::terminate(); } for(int point = 0; point < p_size; ++point) { auto vertex = mesh_->GetPolygonVertex(poly, point); result.data.emplace_back((float)points[vertex][0] * scale); result.data.emplace_back((float)points[vertex][1] * scale); result.data.emplace_back((float)points[vertex][2] * scale); } } return result; } slt::render::ModelData MeshBuilder::build() { std::vector<SingleAttriData> raw_data; // We always have vertices. raw_data.emplace_back(getVertices()); int normal_set_found = 0; int uv_sets_found = 0; auto num_layers = mesh_->GetLayerCount(); for(auto layer_index = 0; layer_index < num_layers; ++layer_index) { auto layer = mesh_->GetLayer(layer_index); slt::log->info(" Layer {}:", layer_index); auto normals = layer->GetNormals(); auto uv_sets = layer->GetUVSets(); // auto binormals = layer->GetBinormals(); //auto tangents = layer->GetTangents(); //auto v_color = layer->GetVertexColors(); if(normals && !normal_attrib_name.get().empty()) { if(normal_set_found != 0) { slt::log->error( " Multiple normal sets, not sure what do do with them."); std::terminate(); } raw_data.emplace_back( extractAttrib(mesh_, normal_attrib_name.get(), *normals, 3)); ++normal_set_found; } for(auto uv_id = 0; uv_id < uv_sets.Size(); ++uv_id) { if(uv_sets_found != 0 && !uv_attrib_name.get().empty()) { slt::log->error(" Multiple UV sets, not sure what do do with them."); std::terminate(); } raw_data.emplace_back( extractAttrib(mesh_, uv_attrib_name.get(), *uv_sets[uv_id], 2)); ++uv_sets_found; } } return compileModel(std::move(raw_data)); } } }
31.113537
80
0.62807
[ "mesh", "render", "vector" ]
94877f08f1ebf1f4bbaee564e48694cdf89f179a
7,113
cpp
C++
src/shapes/mesh.cpp
neverfelly/LuisaRender
2f7a2b52908b81b035d17e541df1ce3dbc18b2b8
[ "BSD-3-Clause" ]
null
null
null
src/shapes/mesh.cpp
neverfelly/LuisaRender
2f7a2b52908b81b035d17e541df1ce3dbc18b2b8
[ "BSD-3-Clause" ]
null
null
null
src/shapes/mesh.cpp
neverfelly/LuisaRender
2f7a2b52908b81b035d17e541df1ce3dbc18b2b8
[ "BSD-3-Clause" ]
null
null
null
// // Created by Mike on 2022/1/7. // #include <assimp/Importer.hpp> #include <assimp/postprocess.h> #include <assimp/scene.h> #include <assimp/mesh.h> #include <core/thread_pool.h> #include <base/shape.h> namespace luisa::render { class MeshLoader { private: luisa::vector<Shape::Vertex> _vertices; luisa::vector<Triangle> _triangles; bool _has_uv{}; public: [[nodiscard]] auto vertices() const noexcept { return luisa::span{_vertices}; } [[nodiscard]] auto triangles() const noexcept { return luisa::span{_triangles}; } [[nodiscard]] auto has_uv() const noexcept { return _has_uv; } [[nodiscard]] static auto load(std::filesystem::path path) noexcept { return ThreadPool::global().async([path = std::move(path)] { Clock clock; auto path_string = path.string(); Assimp::Importer importer; importer.SetPropertyInteger( AI_CONFIG_PP_RVC_FLAGS, aiComponent_ANIMATIONS | aiComponent_BONEWEIGHTS | aiComponent_CAMERAS | aiComponent_COLORS | aiComponent_LIGHTS | aiComponent_MATERIALS | aiComponent_TEXTURES); importer.SetPropertyInteger( AI_CONFIG_PP_SBP_REMOVE, aiPrimitiveType_LINE | aiPrimitiveType_POINT); importer.SetPropertyBool( AI_CONFIG_PP_FD_CHECKAREA, false); auto model = importer.ReadFile( path_string.c_str(), aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcess_RemoveComponent | aiProcess_ImproveCacheLocality | aiProcess_OptimizeGraph | aiProcess_GenNormals | aiProcess_GenUVCoords | aiProcess_CalcTangentSpace | aiProcess_FixInfacingNormals | aiProcess_RemoveRedundantMaterials | aiProcess_FindInvalidData | aiProcess_FlipUVs | aiProcess_TransformUVCoords | aiProcess_SortByPType | aiProcess_FindDegenerates); if (model == nullptr || (model->mFlags & AI_SCENE_FLAGS_INCOMPLETE) || model->mRootNode == nullptr || model->mRootNode->mNumMeshes == 0) [[unlikely]] { LUISA_ERROR_WITH_LOCATION( "Failed to load mesh '{}': {}.", path_string, importer.GetErrorString()); } auto mesh = model->mMeshes[0]; if (auto uv_count = std::count_if( std::cbegin(mesh->mTextureCoords), std::cend(mesh->mTextureCoords), [](auto p) noexcept { return p != nullptr; }); uv_count > 1) [[unlikely]] { LUISA_WARNING_WITH_LOCATION( "More than one set of texture coordinates " "found in mesh '{}'. Only the first set " "will be considered.", path_string); } if (mesh->mTextureCoords[0] == nullptr || mesh->mNumUVComponents[0] != 2) [[unlikely]] { LUISA_WARNING_WITH_LOCATION( "Invalid texture coordinates in mesh '{}': " "address = {}, components = {}.", path_string, fmt::ptr(mesh->mTextureCoords[0]), mesh->mNumUVComponents[0]); } MeshLoader loader; auto vertex_count = mesh->mNumVertices; auto ai_positions = mesh->mVertices; auto ai_normals = mesh->mNormals; auto ai_tex_coords = mesh->mTextureCoords[0]; auto ai_bitangents = mesh->mBitangents; if (ai_bitangents == nullptr) { LUISA_WARNING_WITH_LOCATION( "Invalid tangent space in mesh '{}'.", path_string); } loader._vertices.resize(vertex_count); auto compute_tangent = [ai_bitangents](auto i, float3 n) noexcept { if (ai_bitangents == nullptr) { auto b = abs(n.x) > abs(n.z) ? make_float3(-n.y, n.x, 0.0f) : make_float3(0.0f, -n.z, n.y); return normalize(cross(b, n)); } auto bitangent = make_float3( ai_bitangents[i].x, ai_bitangents[i].y, ai_bitangents[i].z); return normalize(cross(bitangent, n)); }; loader._has_uv = ai_tex_coords != nullptr; auto compute_uv = [ai_tex_coords](auto i) noexcept { if (ai_tex_coords == nullptr) { return make_float2(); } return make_float2(ai_tex_coords[i].x, ai_tex_coords[i].y); }; for (auto i = 0; i < vertex_count; i++) { auto p = make_float3(ai_positions[i].x, ai_positions[i].y, ai_positions[i].z); auto n = make_float3(ai_normals[i].x, ai_normals[i].y, ai_normals[i].z); auto t = compute_tangent(i, n); auto uv = compute_uv(i); loader._vertices[i] = Shape::Vertex::encode(p, n, t, uv); } auto triangle_count = mesh->mNumFaces; auto ai_triangles = mesh->mFaces; loader._triangles.resize(triangle_count); std::transform( ai_triangles, ai_triangles + triangle_count, loader._triangles.begin(), [](const aiFace &face) noexcept { auto t = face.mIndices; return Triangle{t[0], t[1], t[2]}; }); LUISA_INFO( "Loaded triangle mesh '{}' in {} ms.", path_string, clock.toc()); return loader; }); } }; class Mesh final : public Shape { private: std::shared_future<MeshLoader> _loader; AccelBuildHint _build_hint{AccelBuildHint::FAST_TRACE}; public: Mesh(Scene *scene, const SceneNodeDesc *desc) noexcept : Shape{scene, desc}, _loader{MeshLoader::load(desc->property_path("file"))} { auto hint = desc->property_string_or_default("build_hint", ""); if (hint == "fast_update") { _build_hint = AccelBuildHint::FAST_UPDATE; } else if (hint == "fast_rebuild") { _build_hint = AccelBuildHint::FAST_REBUILD; } } [[nodiscard]] luisa::string_view impl_type() const noexcept override { return LUISA_RENDER_PLUGIN_NAME; } [[nodiscard]] luisa::span<const Shape *const> children() const noexcept override { return {}; } [[nodiscard]] bool deformable() const noexcept override { return false; } [[nodiscard]] bool is_mesh() const noexcept override { return true; } [[nodiscard]] luisa::span<const Vertex> vertices() const noexcept override { return _loader.get().vertices(); } [[nodiscard]] luisa::span<const Triangle> triangles() const noexcept override { return _loader.get().triangles(); } }; }// namespace luisa::render LUISA_RENDER_MAKE_SCENE_NODE_PLUGIN(luisa::render::Mesh)
44.45625
119
0.565022
[ "mesh", "render", "shape", "vector", "model", "transform" ]
9493ca6eb5116d663445694724d623a2240ca0f9
3,356
hpp
C++
source/mapping/occupating_grid.hpp
Gabriellgpc/Sistemas_Roboticos
299fe01b85c3644acb7fa2141d9b095649c5dcef
[ "MIT" ]
4
2021-02-06T09:13:54.000Z
2021-12-14T20:09:23.000Z
source/mapping/occupating_grid.hpp
Gabriellgpc/Sistemas_Roboticos
299fe01b85c3644acb7fa2141d9b095649c5dcef
[ "MIT" ]
null
null
null
source/mapping/occupating_grid.hpp
Gabriellgpc/Sistemas_Roboticos
299fe01b85c3644acb7fa2141d9b095649c5dcef
[ "MIT" ]
1
2021-12-30T15:49:42.000Z
2021-12-30T15:49:42.000Z
#pragma once #include <configSpaceTools.hpp> //Vector2D, Config #include <vector> #include <string> #include <iostream> constexpr double l_0 = 0.0;//iniciar desconhecidas constexpr double l_oc= 0.8;//incremento em log odd para celulas provavelmente ocupadas constexpr double l_L =-0.5;//incremento para log odd para celulas provavelmente nao ocupadas double log_odd(const double &p); double inv_log_odd(const double &l); class ProximitySensorInfo { public: ProximitySensorInfo(const float &min_range, const float &max_range, const float &opening, const float &angle, const float &e = 0); ~ProximitySensorInfo(); //atualize measure_dist com um valor negativo para indicar que não ha dados de medição void updateMeasure(const float& measure_dist, const Vector2D & measure_point); //retorna um valor negativo caso não tenha dados de medições inline float zt()const{ return sensor_measure_dist; } inline float get_measure_dist()const{ return sensor_measure_dist; } inline Vector2D get_measure_point()const{ return sensor_measure_point; } inline float get_error()const{ return error; } inline float e()const{ return error; } inline float get_opening_angle()const{ return opening_angle; } inline float ang_range()const{ return opening_angle; } inline float max()const{ return range[1]; } inline float min()const{ return range[0]; } inline float get_ori()const{ return theta; } inline float ori()const{ return theta; } inline Vector2D &point(){ return sensor_measure_point; } private: /** Propriedades do sensor **/ //erro na distancia float error; //angulo de abertura float opening_angle; //[min, max] float range[2]; //orientação do sensor com relação à orientação do robo float theta; /** Dados da medição **/ //distancia ate o ponto mais proximo float sensor_measure_dist; //ponto no plano x,y do mundo / localização do ponto detectado Vector2D sensor_measure_point; }; class OccupationGridCell { public: Vector2D pos; double l; double p; std::istream &load_from_stream(std::istream &I); std::ostream &save_to_stream(std::ostream &O); }; class OccupationGrid { public: //grade com width e height composta de celulas quadradas com size_cell de lado OccupationGrid(const float &width, const float &height, const float& size_cell = 0.1); ~OccupationGrid(); void update(const ProximitySensorInfo& sensor, const Config & q); inline std::vector<OccupationGridCell> get_OG()const { return map; } inline std::size_t size()const { return map.size(); } inline OccupationGridCell operator[](const uint32_t &i)const { return map[i];} inline float get_width()const { return _width; } inline float get_height()const { return _height; } inline float get_size_cell()const { return _size_cell; } void save_to_file(const std::string file); void load_from_file(const std::string file); private: std::vector<OccupationGridCell> map; float _width; float _height; float _size_cell; //modelo inverso simples de um sensor de proximidade double _inverse_model(const OccupationGridCell &mi, const ProximitySensorInfo &z, const Config& q); };
34.597938
103
0.69994
[ "vector" ]
9496569ea1248d4739032558ab2367cf9da08a59
6,268
cpp
C++
uxn/demos/muxoclon/muxoclon.cpp
kaagha/patl
878542818a0a41f2d993ef49b8ff5249e902fd9d
[ "BSD-3-Clause" ]
null
null
null
uxn/demos/muxoclon/muxoclon.cpp
kaagha/patl
878542818a0a41f2d993ef49b8ff5249e902fd9d
[ "BSD-3-Clause" ]
null
null
null
uxn/demos/muxoclon/muxoclon.cpp
kaagha/patl
878542818a0a41f2d993ef49b8ff5249e902fd9d
[ "BSD-3-Clause" ]
null
null
null
/*- | This source code is part of PATL (Practical Algorithm Template Library) | Released under the BSD License (http://www.opensource.org/licenses/bsd-license.php) | Copyright (c) 2005, 2007..2009, Roman S. Klyujkov (uxnuxn AT gmail.com) | | Find the shortest word ladders stretching between the following pairs | rus: http://community.livejournal.com/coding4fun_ru/1510.html | eng: http://stason.org/TULARC/self-growth/puzzles/291-language-english-spelling-sets-of-words-ladder-p.html | examples: | hit ace (length 4) | pig sty (6) | four five (7) | play game (8) | green grass (5) | wheat bread (7) | order chaos (12) | sixth hubby (10) | speedy comedy (19) | chasing robbers (20) | griming goblets (23) | effaces cabaret (50) -*/ // C4503: decorated name length exceeded, name was truncated #pragma warning(disable : 4503) #include <fstream> #include <vector> #include <set> #include <map> #include <uxn/patl/trie_set.hpp> #include <uxn/patl/partial.hpp> #include <uxn/patl/aux_/perf_timer.hpp> namespace patl = uxn::patl; typedef patl::trie_set<std::string> trie_string; typedef std::map<unsigned, trie_string> map_sized_string; typedef trie_string::const_vertex const_vertex; typedef std::vector<const_vertex> vector_vertex; typedef std::map<const_vertex, const_vertex> map_vertex; typedef std::vector<map_vertex> vector_wave; void directed_search( const trie_string &dict, vector_wave &wave, vector_wave &antiwave, std::set<const_vertex> &used, bool reversed, vector_vertex &chain) { wave.push_back(map_vertex()); map_vertex &next = wave.back(); const map_vertex &current = wave[wave.size() - 2], &antipode = antiwave.back(); for (map_vertex::const_iterator it = current.begin() ; it != current.end() ; ++it) { const const_vertex &seed = it->first; typedef patl::hamming_distance<trie_string, true> hamm_dist; hamm_dist hd(dict, 1, seed.key()); trie_string::const_partimator<hamm_dist> pmi = dict.begin(hd), pmi_end = dict.end(hd); for (; pmi != pmi_end; ++pmi) { const const_vertex &vtx = pmi; if (used.find(vtx) == used.end()) { const map_vertex::const_iterator match = antipode.find(vtx); if (match != antipode.end()) { wave.pop_back(); const_vertex cur = reversed ? vtx : seed; vector_wave &front_wave = reversed ? antiwave : wave, &back_wave = reversed ? wave : antiwave; // G++ not allowed to use const_reverse_iterator // error: no match for 'operator!=' for (vector_wave::reverse_iterator rit = front_wave.rbegin() ; rit != front_wave.rend() ; cur = rit++->find(cur)->second) chain.push_back(cur); std::reverse(chain.begin(), chain.end()); cur = reversed ? seed : vtx; for (vector_wave::reverse_iterator rit = back_wave.rbegin() ; rit != back_wave.rend() ; cur = rit++->find(cur)->second) chain.push_back(cur); return; } used.insert(vtx); next.insert(std::make_pair(vtx, seed)); } } } } bool search_work( const trie_string &dict, const const_vertex &src_vtx, const const_vertex &dst_vtx, vector_vertex &chain) { if (src_vtx == dst_vtx) { chain.push_back(src_vtx); return true; } const const_vertex dict_end = dict.end(); vector_wave front_wave, back_wave; front_wave.push_back(map_vertex()); front_wave.back().insert(std::make_pair(src_vtx, dict_end)); back_wave.push_back(map_vertex()); back_wave.back().insert(std::make_pair(dst_vtx, dict_end)); std::set<const_vertex> front_used, back_used; front_used.insert(src_vtx); back_used.insert(dst_vtx); for (int level = 0; ; ++level) { // front directed_search(dict, front_wave, back_wave, front_used, false, chain); if (!chain.empty()) return true; if (front_wave.back().empty()) return false; // back directed_search(dict, back_wave, front_wave, back_used, true, chain); if (!chain.empty()) return true; if (back_wave.back().empty()) return false; } } int main(int argc, char *argv[]) { std::ifstream fin(argc > 1 ? argv[1] : "WORD.LST"); if (!fin.is_open()) { printf("Unable to open input file!\n"); return 0; } map_sized_string sdict; std::string str; while (fin >> str) sdict[str.length()].insert(str); for (;;) { fseek(stdin, 0, SEEK_END); printf("Input two words: "); char word0[256] = "", word1[256] = ""; if (scanf("%s %s", word0, word1) != 2 || !*word0 || !*word1) { printf("\nBye.\n"); break; } if (strlen(word0) != strlen(word1)) { printf("Words must be equal in length!\n"); continue; } const trie_string &dict = sdict[strlen(word0)]; trie_string::const_iterator src_it = dict.find(word0), dst_it = dict.find(word1); if (src_it == dict.end() || dst_it == dict.end()) { printf("Both words must be in dictionary!\n"); continue; } printf("Transform: '%s' ==> '%s'\n", word0, word1); vector_vertex chain; patl::aux::performance_timer tim; if (search_work(dict, src_it, dst_it, chain)) { for (vector_vertex::const_iterator it = chain.begin() ; it != chain.end() ; ++it) printf("%s ", it->key().c_str()); printf("\n"); } else printf("Chain not found!\n"); tim.finish(); printf("time: %.2f sec.\n", tim.get_seconds()); } }
32.816754
110
0.556637
[ "vector", "transform" ]
94a58145e217f7e33a9742e6678cb59b2bd08a0a
748
cpp
C++
arrays-101/in-place/move-zeroes.cpp
lpapp/leetcode
58274e021004824bea9c58033632f1d5cf11a7e9
[ "MIT" ]
null
null
null
arrays-101/in-place/move-zeroes.cpp
lpapp/leetcode
58274e021004824bea9c58033632f1d5cf11a7e9
[ "MIT" ]
null
null
null
arrays-101/in-place/move-zeroes.cpp
lpapp/leetcode
58274e021004824bea9c58033632f1d5cf11a7e9
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; class Solution { public: void moveZeroes_suboptimal(vector<int>& nums) { size_t k = 0; for (size_t i = 0; i < nums.size(); ++i) if (nums[i]) nums[k++] = nums[i]; for (; k < nums.size(); ++k) nums[k] = 0; } void moveZeroes(vector<int>& nums) { for (size_t i = 0, k = 0; i < nums.size(); ++i) if (nums[i]) swap(nums[k++], nums[i]); } }; void test(vector<int>& nums) { Solution s; s.moveZeroes(nums); for (const int e : nums) cout << e << ","; cout << endl; } int main() { vector<int> A1{0, 1, 0, 3, 12}; cout << "[0,1,0,3,12] => [1,3,12,0,0]: "; test(A1); vector<int> A2{0}; cout << "[0] => [0]: "; test(A2); return 0; }
18.7
92
0.520053
[ "vector" ]
94b411a6b39613a09304f097163c53b71a7455f9
86,139
cpp
C++
src/postgres/backend/optimizer/plan/subselect.cpp
jessesleeping/my_peloton
a19426cfe34a04692a11008eaffc9c3c9b49abc4
[ "Apache-2.0" ]
6
2017-04-28T00:38:52.000Z
2018-11-06T07:06:49.000Z
src/postgres/backend/optimizer/plan/subselect.cpp
jessesleeping/my_peloton
a19426cfe34a04692a11008eaffc9c3c9b49abc4
[ "Apache-2.0" ]
57
2016-03-19T22:27:55.000Z
2017-07-08T00:41:51.000Z
src/postgres/backend/optimizer/plan/subselect.cpp
eric-haibin-lin/pelotondb
904d6bbd041a0498ee0e034d4f9f9f27086c3cab
[ "Apache-2.0" ]
4
2016-07-17T20:44:56.000Z
2018-06-27T01:01:36.000Z
/*------------------------------------------------------------------------- * * subselect.c * Planning routines for subselects and parameters. * * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION * src/backend/optimizer/plan/subselect.c * *------------------------------------------------------------------------- */ #include "postgres.h" #include "access/htup_details.h" #include "catalog/pg_operator.h" #include "catalog/pg_type.h" #include "executor/executor.h" #include "miscadmin.h" #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "optimizer/clauses.h" #include "optimizer/cost.h" #include "optimizer/planmain.h" #include "optimizer/planner.h" #include "optimizer/prep.h" #include "optimizer/subselect.h" #include "optimizer/var.h" #include "parser/parse_relation.h" #include "rewrite/rewriteManip.h" #include "utils/builtins.h" #include "utils/lsyscache.h" #include "utils/syscache.h" typedef struct convert_testexpr_context { PlannerInfo *root; List *subst_nodes; /* Nodes to substitute for Params */ } convert_testexpr_context; typedef struct process_sublinks_context { PlannerInfo *root; bool isTopQual; } process_sublinks_context; typedef struct finalize_primnode_context { PlannerInfo *root; Bitmapset *paramids; /* Non-local PARAM_EXEC paramids found */ } finalize_primnode_context; static Node *build_subplan(PlannerInfo *root, Plan *plan, PlannerInfo *subroot, List *plan_params, SubLinkType subLinkType, int subLinkId, Node *testexpr, bool adjust_testexpr, bool unknownEqFalse); static List *generate_subquery_params(PlannerInfo *root, List *tlist, List **paramIds); static List *generate_subquery_vars(PlannerInfo *root, List *tlist, Index varno); static Node *convert_testexpr(PlannerInfo *root, Node *testexpr, List *subst_nodes); static Node *convert_testexpr_mutator(Node *node, convert_testexpr_context *context); static bool subplan_is_hashable(Plan *plan); static bool testexpr_is_hashable(Node *testexpr); static bool hash_ok_operator(OpExpr *expr); static bool simplify_EXISTS_query(PlannerInfo *root, Query *query); static Query *convert_EXISTS_to_ANY(PlannerInfo *root, Query *subselect, Node **testexpr, List **paramIds); static Node *replace_correlation_vars_mutator(Node *node, PlannerInfo *root); static Node *process_sublinks_mutator(Node *node, process_sublinks_context *context); static Bitmapset *finalize_plan(PlannerInfo *root, Plan *plan, Bitmapset *valid_params, Bitmapset *scan_params); static bool finalize_primnode(Node *node, finalize_primnode_context *context); /* * Select a PARAM_EXEC number to identify the given Var as a parameter for * the current subquery, or for a nestloop's inner scan. * If the Var already has a param in the current context, return that one. */ static int assign_param_for_var(PlannerInfo *root, Var *var) { ListCell *ppl; PlannerParamItem *pitem; Index levelsup; /* Find the query level the Var belongs to */ for (levelsup = var->varlevelsup; levelsup > 0; levelsup--) root = root->parent_root; /* If there's already a matching PlannerParamItem there, just use it */ foreach(ppl, root->plan_params) { pitem = (PlannerParamItem *) lfirst(ppl); if (IsA(pitem->item, Var)) { Var *pvar = (Var *) pitem->item; /* * This comparison must match _equalVar(), except for ignoring * varlevelsup. Note that _equalVar() ignores the location. */ if (pvar->varno == var->varno && pvar->varattno == var->varattno && pvar->vartype == var->vartype && pvar->vartypmod == var->vartypmod && pvar->varcollid == var->varcollid && pvar->varnoold == var->varnoold && pvar->varoattno == var->varoattno) return pitem->paramId; } } /* Nope, so make a new___ one */ var = (Var *) copyObject(var); var->varlevelsup = 0; pitem = makeNode(PlannerParamItem); pitem->item = (Node *) var; pitem->paramId = root->glob->nParamExec++; root->plan_params = lappend(root->plan_params, pitem); return pitem->paramId; } /* * Generate a Param node to replace the given Var, * which is expected to have varlevelsup > 0 (ie, it is not local). */ static Param * replace_outer_var(PlannerInfo *root, Var *var) { Param *retval; int i; Assert(var->varlevelsup > 0 && var->varlevelsup < root->query_level); /* Find the Var in the appropriate plan_params, or add it if not present */ i = assign_param_for_var(root, var); retval = makeNode(Param); retval->paramkind = PARAM_EXEC; retval->paramid = i; retval->paramtype = var->vartype; retval->paramtypmod = var->vartypmod; retval->paramcollid = var->varcollid; retval->location = var->location; return retval; } /* * Generate a Param node to replace the given Var, which will be supplied * from an upper NestLoop join node. * * This is effectively the same as replace_outer_var, except that we expect * the Var to be local to the current query level. */ Param * assign_nestloop_param_var(PlannerInfo *root, Var *var) { Param *retval; int i; Assert(var->varlevelsup == 0); i = assign_param_for_var(root, var); retval = makeNode(Param); retval->paramkind = PARAM_EXEC; retval->paramid = i; retval->paramtype = var->vartype; retval->paramtypmod = var->vartypmod; retval->paramcollid = var->varcollid; retval->location = var->location; return retval; } /* * Select a PARAM_EXEC number to identify the given PlaceHolderVar as a * parameter for the current subquery, or for a nestloop's inner scan. * If the PHV already has a param in the current context, return that one. * * This is just like assign_param_for_var, except for PlaceHolderVars. */ static int assign_param_for_placeholdervar(PlannerInfo *root, PlaceHolderVar *phv) { ListCell *ppl; PlannerParamItem *pitem; Index levelsup; /* Find the query level the PHV belongs to */ for (levelsup = phv->phlevelsup; levelsup > 0; levelsup--) root = root->parent_root; /* If there's already a matching PlannerParamItem there, just use it */ foreach(ppl, root->plan_params) { pitem = (PlannerParamItem *) lfirst(ppl); if (IsA(pitem->item, PlaceHolderVar)) { PlaceHolderVar *pphv = (PlaceHolderVar *) pitem->item; /* We assume comparing the PHIDs is sufficient */ if (pphv->phid == phv->phid) return pitem->paramId; } } /* Nope, so make a new___ one */ phv = (PlaceHolderVar *) copyObject(phv); if (phv->phlevelsup != 0) { IncrementVarSublevelsUp((Node *) phv, -((int) phv->phlevelsup), 0); Assert(phv->phlevelsup == 0); } pitem = makeNode(PlannerParamItem); pitem->item = (Node *) phv; pitem->paramId = root->glob->nParamExec++; root->plan_params = lappend(root->plan_params, pitem); return pitem->paramId; } /* * Generate a Param node to replace the given PlaceHolderVar, * which is expected to have phlevelsup > 0 (ie, it is not local). * * This is just like replace_outer_var, except for PlaceHolderVars. */ static Param * replace_outer_placeholdervar(PlannerInfo *root, PlaceHolderVar *phv) { Param *retval; int i; Assert(phv->phlevelsup > 0 && phv->phlevelsup < root->query_level); /* Find the PHV in the appropriate plan_params, or add it if not present */ i = assign_param_for_placeholdervar(root, phv); retval = makeNode(Param); retval->paramkind = PARAM_EXEC; retval->paramid = i; retval->paramtype = exprType((Node *) phv->phexpr); retval->paramtypmod = exprTypmod((Node *) phv->phexpr); retval->paramcollid = exprCollation((Node *) phv->phexpr); retval->location = -1; return retval; } /* * Generate a Param node to replace the given PlaceHolderVar, which will be * supplied from an upper NestLoop join node. * * This is just like assign_nestloop_param_var, except for PlaceHolderVars. */ Param * assign_nestloop_param_placeholdervar(PlannerInfo *root, PlaceHolderVar *phv) { Param *retval; int i; Assert(phv->phlevelsup == 0); i = assign_param_for_placeholdervar(root, phv); retval = makeNode(Param); retval->paramkind = PARAM_EXEC; retval->paramid = i; retval->paramtype = exprType((Node *) phv->phexpr); retval->paramtypmod = exprTypmod((Node *) phv->phexpr); retval->paramcollid = exprCollation((Node *) phv->phexpr); retval->location = -1; return retval; } /* * Generate a Param node to replace the given Aggref * which is expected to have agglevelsup > 0 (ie, it is not local). */ static Param * replace_outer_agg(PlannerInfo *root, Aggref *agg) { Param *retval; PlannerParamItem *pitem; Index levelsup; Assert(agg->agglevelsup > 0 && agg->agglevelsup < root->query_level); /* Find the query level the Aggref belongs to */ for (levelsup = agg->agglevelsup; levelsup > 0; levelsup--) root = root->parent_root; /* * It does not seem worthwhile to try to match duplicate outer aggs. Just * make a new___ slot every time. */ agg = (Aggref *) copyObject(agg); IncrementVarSublevelsUp((Node *) agg, -((int) agg->agglevelsup), 0); Assert(agg->agglevelsup == 0); pitem = makeNode(PlannerParamItem); pitem->item = (Node *) agg; pitem->paramId = root->glob->nParamExec++; root->plan_params = lappend(root->plan_params, pitem); retval = makeNode(Param); retval->paramkind = PARAM_EXEC; retval->paramid = pitem->paramId; retval->paramtype = agg->aggtype; retval->paramtypmod = -1; retval->paramcollid = agg->aggcollid; retval->location = agg->location; return retval; } /* * Generate a Param node to replace the given GroupingFunc expression which is * expected to have agglevelsup > 0 (ie, it is not local). */ static Param * replace_outer_grouping(PlannerInfo *root, GroupingFunc *grp) { Param *retval; PlannerParamItem *pitem; Index levelsup; Assert(grp->agglevelsup > 0 && grp->agglevelsup < root->query_level); /* Find the query level the GroupingFunc belongs to */ for (levelsup = grp->agglevelsup; levelsup > 0; levelsup--) root = root->parent_root; /* * It does not seem worthwhile to try to match duplicate outer aggs. Just * make a new___ slot every time. */ grp = (GroupingFunc *) copyObject(grp); IncrementVarSublevelsUp((Node *) grp, -((int) grp->agglevelsup), 0); Assert(grp->agglevelsup == 0); pitem = makeNode(PlannerParamItem); pitem->item = (Node *) grp; pitem->paramId = root->glob->nParamExec++; root->plan_params = lappend(root->plan_params, pitem); retval = makeNode(Param); retval->paramkind = PARAM_EXEC; retval->paramid = pitem->paramId; retval->paramtype = exprType((Node *) grp); retval->paramtypmod = -1; retval->paramcollid = InvalidOid; retval->location = grp->location; return retval; } /* * Generate a new___ Param node that will not conflict with any other. * * This is used to create Params representing subplan outputs. * We don't need to build a PlannerParamItem for such a Param, but we do * need to record the PARAM_EXEC slot number as being allocated. */ static Param * generate_new_param(PlannerInfo *root, Oid paramtype, int32 paramtypmod, Oid paramcollation) { Param *retval; retval = makeNode(Param); retval->paramkind = PARAM_EXEC; retval->paramid = root->glob->nParamExec++; retval->paramtype = paramtype; retval->paramtypmod = paramtypmod; retval->paramcollid = paramcollation; retval->location = -1; return retval; } /* * Assign a (nonnegative) PARAM_EXEC ID for a special parameter (one that * is not actually used to carry a value at runtime). Such parameters are * used for special runtime signaling purposes, such as connecting a * recursive union node to its worktable scan node or forcing plan * re-evaluation within the EvalPlanQual mechanism. No actual Param node * exists with this ID, however. */ int SS_assign_special_param(PlannerInfo *root) { return root->glob->nParamExec++; } /* * Get the datatype/typmod/collation of the first column of the plan's output. * * This information is stored for ARRAY_SUBLINK execution and for * exprType()/exprTypmod()/exprCollation(), which have no way to get at the * plan associated with a SubPlan node. We really only need the info for * EXPR_SUBLINK and ARRAY_SUBLINK subplans, but for consistency we save it * always. */ static void get_first_col_type(Plan *plan, Oid *coltype, int32 *coltypmod, Oid *colcollation) { /* In cases such as EXISTS, tlist might be empty; arbitrarily use VOID */ if (plan->targetlist) { TargetEntry *tent = (TargetEntry *) linitial(plan->targetlist); Assert(IsA(tent, TargetEntry)); if (!tent->resjunk) { *coltype = exprType((Node *) tent->expr); *coltypmod = exprTypmod((Node *) tent->expr); *colcollation = exprCollation((Node *) tent->expr); return; } } *coltype = VOIDOID; *coltypmod = -1; *colcollation = InvalidOid; } /* * Convert a SubLink (as created by the parser) into a SubPlan. * * We are given the SubLink's contained query, type, ID, and testexpr. We are * also told if this expression appears at top level of a WHERE/HAVING qual. * * Note: we assume that the testexpr has been AND/OR flattened (actually, * it's been through eval_const_expressions), but not converted to * implicit-AND form; and any SubLinks in it should already have been * converted to SubPlans. The subquery is as yet untouched, however. * * The result is whatever we need to substitute in place of the SubLink node * in the executable expression. If we're going to do the subplan as a * regular subplan, this will be the constructed SubPlan node. If we're going * to do the subplan as an InitPlan, the SubPlan node instead goes into * root->init_plans, and what we return here is an expression tree * representing the InitPlan's result: usually just a Param node representing * a single scalar result, but possibly a row comparison tree containing * multiple Param nodes, or for a MULTIEXPR subquery a simple NULL constant * (since the real output Params are elsewhere in the tree, and the MULTIEXPR * subquery itself is in a resjunk tlist entry whose value is uninteresting). */ static Node * make_subplan(PlannerInfo *root, Query *orig_subquery, SubLinkType subLinkType, int subLinkId, Node *testexpr, bool isTopQual) { Query *subquery; bool simple_exists = false; double tuple_fraction; Plan *plan; PlannerInfo *subroot; List *plan_params; Node *result; /* * Copy the source Query node. This is a quick and dirty kluge to resolve * the fact that the parser can generate trees with multiple links to the * same sub-Query node, but the planner wants to scribble on the Query. * Try to clean this up when we do querytree redesign... */ subquery = (Query *) copyObject(orig_subquery); /* * If it's an EXISTS subplan, we might be able to simplify it. */ if (subLinkType == EXISTS_SUBLINK) simple_exists = simplify_EXISTS_query(root, subquery); /* * For an EXISTS subplan, tell lower-level planner to expect that only the * first tuple will be retrieved. For ALL and ANY subplans, we will be * able to stop evaluating if the test condition fails or matches, so very * often not all the tuples will be retrieved; for lack of a better idea, * specify 50% retrieval. For EXPR, MULTIEXPR, and ROWCOMPARE subplans, * use default behavior (we're only expecting one row out, anyway). * * NOTE: if you change these numbers, also change cost_subplan() in * path/costsize.c. * * XXX If an ANY subplan is uncorrelated, build_subplan may decide to hash * its output. In that case it would've been better to specify full * retrieval. At present, however, we can only check hashability after * we've made the subplan :-(. (Determining whether it'll fit in work_mem * is the really hard part.) Therefore, we don't want to be too * optimistic about the percentage of tuples retrieved, for fear of * selecting a plan that's bad for the materialization case. */ if (subLinkType == EXISTS_SUBLINK) tuple_fraction = 1.0; /* just like a LIMIT 1 */ else if (subLinkType == ALL_SUBLINK || subLinkType == ANY_SUBLINK) tuple_fraction = 0.5; /* 50% */ else tuple_fraction = 0.0; /* default behavior */ /* plan_params should not be in use in current query level */ Assert(root->plan_params == NIL); /* * Generate the plan for the subquery. */ plan = subquery_planner(root->glob, subquery, root, false, tuple_fraction, &subroot); /* Isolate the params needed by this specific subplan */ plan_params = root->plan_params; root->plan_params = NIL; /* And convert to SubPlan or InitPlan format. */ result = build_subplan(root, plan, subroot, plan_params, subLinkType, subLinkId, testexpr, true, isTopQual); /* * If it's a correlated EXISTS with an unimportant targetlist, we might be * able to transform it to the equivalent of an IN and then implement it * by hashing. We don't have enough information yet to tell which way is * likely to be better (it depends on the expected number of executions of * the EXISTS qual, and we are much too early in planning the outer query * to be able to guess that). So we generate both plans, if possible, and * leave it to the executor to decide which to use. */ if (simple_exists && IsA(result, SubPlan)) { Node *newtestexpr; List *paramIds; /* Make a second copy of the original subquery */ subquery = (Query *) copyObject(orig_subquery); /* and re-simplify */ simple_exists = simplify_EXISTS_query(root, subquery); Assert(simple_exists); /* See if it can be converted to an ANY query */ subquery = convert_EXISTS_to_ANY(root, subquery, &newtestexpr, &paramIds); if (subquery) { /* Generate the plan for the ANY subquery; we'll need all rows */ plan = subquery_planner(root->glob, subquery, root, false, 0.0, &subroot); /* Isolate the params needed by this specific subplan */ plan_params = root->plan_params; root->plan_params = NIL; /* Now we can check if it'll fit in work_mem */ if (subplan_is_hashable(plan)) { SubPlan *hashplan; AlternativeSubPlan *asplan; /* OK, convert to SubPlan format. */ hashplan = (SubPlan *) build_subplan(root, plan, subroot, plan_params, ANY_SUBLINK, 0, newtestexpr, false, true); /* Check we got what we expected */ Assert(IsA(hashplan, SubPlan)); Assert(hashplan->parParam == NIL); Assert(hashplan->useHashTable); /* build_subplan won't have filled in paramIds */ hashplan->paramIds = paramIds; /* Leave it to the executor to decide which plan to use */ asplan = makeNode(AlternativeSubPlan); asplan->subplans = list_make2(result, hashplan); result = (Node *) asplan; } } } return result; } /* * Build a SubPlan node given the raw inputs --- subroutine for make_subplan * * Returns either the SubPlan, or a replacement expression if we decide to * make it an InitPlan, as explained in the comments for make_subplan. */ static Node * build_subplan(PlannerInfo *root, Plan *plan, PlannerInfo *subroot, List *plan_params, SubLinkType subLinkType, int subLinkId, Node *testexpr, bool adjust_testexpr, bool unknownEqFalse) { Node *result; SubPlan *splan; bool isInitPlan; ListCell *lc; /* * Initialize the SubPlan node. Note plan_id, plan_name, and cost fields * are set further down. */ splan = makeNode(SubPlan); splan->subLinkType = subLinkType; splan->testexpr = NULL; splan->paramIds = NIL; get_first_col_type(plan, &splan->firstColType, &splan->firstColTypmod, &splan->firstColCollation); splan->useHashTable = false; splan->unknownEqFalse = unknownEqFalse; splan->setParam = NIL; splan->parParam = NIL; splan->args = NIL; /* * Make parParam and args lists of param IDs and expressions that current * query level will pass to this child plan. */ foreach(lc, plan_params) { PlannerParamItem *pitem = (PlannerParamItem *) lfirst(lc); Node *arg = pitem->item; /* * The Var, PlaceHolderVar, or Aggref has already been adjusted to * have the correct varlevelsup, phlevelsup, or agglevelsup. * * If it's a PlaceHolderVar or Aggref, its arguments might contain * SubLinks, which have not yet been processed (see the comments for * SS_replace_correlation_vars). Do that now. */ if (IsA(arg, PlaceHolderVar) || IsA(arg, Aggref)) arg = SS_process_sublinks(root, arg, false); splan->parParam = lappend_int(splan->parParam, pitem->paramId); splan->args = lappend(splan->args, arg); } /* * Un-correlated or undirect correlated plans of EXISTS, EXPR, ARRAY, * ROWCOMPARE, or MULTIEXPR types can be used as initPlans. For EXISTS, * EXPR, or ARRAY, we return a Param referring to the result of evaluating * the initPlan. For ROWCOMPARE, we must modify the testexpr tree to * contain PARAM_EXEC Params instead of the PARAM_SUBLINK Params emitted * by the parser, and then return that tree. For MULTIEXPR, we return a * null constant: the resjunk targetlist item containing the SubLink does * not need to return anything useful, since the referencing Params are * elsewhere. */ if (splan->parParam == NIL && subLinkType == EXISTS_SUBLINK) { Param *prm; Assert(testexpr == NULL); prm = generate_new_param(root, BOOLOID, -1, InvalidOid); splan->setParam = list_make1_int(prm->paramid); isInitPlan = true; result = (Node *) prm; } else if (splan->parParam == NIL && subLinkType == EXPR_SUBLINK) { TargetEntry *te = static_cast<TargetEntry *>(linitial(plan->targetlist)); Param *prm; Assert(!te->resjunk); Assert(testexpr == NULL); prm = generate_new_param(root, exprType((Node *) te->expr), exprTypmod((Node *) te->expr), exprCollation((Node *) te->expr)); splan->setParam = list_make1_int(prm->paramid); isInitPlan = true; result = (Node *) prm; } else if (splan->parParam == NIL && subLinkType == ARRAY_SUBLINK) { TargetEntry *te = static_cast<TargetEntry *>(linitial(plan->targetlist)); Oid arraytype; Param *prm; Assert(!te->resjunk); Assert(testexpr == NULL); arraytype = get_promoted_array_type(exprType((Node *) te->expr)); if (!OidIsValid(arraytype)) elog(ERROR, "could not find array type for datatype %s", format_type_be(exprType((Node *) te->expr))); prm = generate_new_param(root, arraytype, exprTypmod((Node *) te->expr), exprCollation((Node *) te->expr)); splan->setParam = list_make1_int(prm->paramid); isInitPlan = true; result = (Node *) prm; } else if (splan->parParam == NIL && subLinkType == ROWCOMPARE_SUBLINK) { /* Adjust the Params */ List *params; Assert(testexpr != NULL); params = generate_subquery_params(root, plan->targetlist, &splan->paramIds); result = convert_testexpr(root, testexpr, params); splan->setParam = list_copy(splan->paramIds); isInitPlan = true; /* * The executable expression is returned to become part of the outer * plan's expression tree; it is not kept in the initplan node. */ } else if (subLinkType == MULTIEXPR_SUBLINK) { /* * Whether it's an initplan or not, it needs to set a PARAM_EXEC Param * for each output column. */ List *params; Assert(testexpr == NULL); params = generate_subquery_params(root, plan->targetlist, &splan->setParam); /* * Save the list of replacement Params in the n'th cell of * root->multiexpr_params; setrefs.c will use it to replace * PARAM_MULTIEXPR Params. */ while (list_length(root->multiexpr_params) < subLinkId) root->multiexpr_params = lappend(root->multiexpr_params, NIL); lc = list_nth_cell(root->multiexpr_params, subLinkId - 1); Assert(lfirst(lc) == NIL); lfirst(lc) = params; /* It can be an initplan if there are no parParams. */ if (splan->parParam == NIL) { isInitPlan = true; result = (Node *) makeNullConst(RECORDOID, -1, InvalidOid); } else { isInitPlan = false; result = (Node *) splan; } } else { /* * Adjust the Params in the testexpr, unless caller said it's not * needed. */ if (testexpr && adjust_testexpr) { List *params; params = generate_subquery_params(root, plan->targetlist, &splan->paramIds); splan->testexpr = convert_testexpr(root, testexpr, params); } else splan->testexpr = testexpr; /* * We can't convert subplans of ALL_SUBLINK or ANY_SUBLINK types to * initPlans, even when they are uncorrelated or undirect correlated, * because we need to scan the output of the subplan for each outer * tuple. But if it's a not-direct-correlated IN (= ANY) test, we * might be able to use a hashtable to avoid comparing all the tuples. */ if (subLinkType == ANY_SUBLINK && splan->parParam == NIL && subplan_is_hashable(plan) && testexpr_is_hashable(splan->testexpr)) splan->useHashTable = true; /* * Otherwise, we have the option to tack a Material node onto the top * of the subplan, to reduce the cost of reading it repeatedly. This * is pointless for a direct-correlated subplan, since we'd have to * recompute its results each time anyway. For uncorrelated/undirect * correlated subplans, we add Material unless the subplan's top plan * node would materialize its output anyway. Also, if enable_material * is false, then the user does not want us to materialize anything * unnecessarily, so we don't. */ else if (splan->parParam == NIL && enable_material && !ExecMaterializesOutput(nodeTag(plan))) plan = materialize_finished_plan(plan); result = (Node *) splan; isInitPlan = false; } /* * Add the subplan and its PlannerInfo to the global lists. */ root->glob->subplans = lappend(root->glob->subplans, plan); root->glob->subroots = lappend(root->glob->subroots, subroot); splan->plan_id = list_length(root->glob->subplans); if (isInitPlan) root->init_plans = lappend(root->init_plans, splan); /* * A parameterless subplan (not initplan) should be prepared to handle * REWIND efficiently. If it has direct parameters then there's no point * since it'll be reset on each scan anyway; and if it's an initplan then * there's no point since it won't get re-run without parameter changes * anyway. The input of a hashed subplan doesn't need REWIND either. */ if (splan->parParam == NIL && !isInitPlan && !splan->useHashTable) root->glob->rewindPlanIDs = bms_add_member(root->glob->rewindPlanIDs, splan->plan_id); /* Label the subplan for EXPLAIN purposes */ splan->plan_name = static_cast<char *>(palloc(32 + 12 * list_length(splan->setParam))); sprintf(splan->plan_name, "%s %d", isInitPlan ? "InitPlan" : "SubPlan", splan->plan_id); if (splan->setParam) { char *ptr = splan->plan_name + strlen(splan->plan_name); ptr += sprintf(ptr, " (returns "); foreach(lc, splan->setParam) { ptr += sprintf(ptr, "$%d%s", lfirst_int(lc), lnext(lc) ? "," : ")"); } } /* Lastly, fill in the cost estimates for use later */ cost_subplan(root, splan, plan); return result; } /* * generate_subquery_params: build a list of Params representing the output * columns of a sublink's sub-select, given the sub-select's targetlist. * * We also return an integer list of the paramids of the Params. */ static List * generate_subquery_params(PlannerInfo *root, List *tlist, List **paramIds) { List *result; List *ids; ListCell *lc; result = ids = NIL; foreach(lc, tlist) { TargetEntry *tent = (TargetEntry *) lfirst(lc); Param *param; if (tent->resjunk) continue; param = generate_new_param(root, exprType((Node *) tent->expr), exprTypmod((Node *) tent->expr), exprCollation((Node *) tent->expr)); result = lappend(result, param); ids = lappend_int(ids, param->paramid); } *paramIds = ids; return result; } /* * generate_subquery_vars: build a list of Vars representing the output * columns of a sublink's sub-select, given the sub-select's targetlist. * The Vars have the specified varno (RTE index). */ static List * generate_subquery_vars(PlannerInfo *root, List *tlist, Index varno) { List *result; ListCell *lc; result = NIL; foreach(lc, tlist) { TargetEntry *tent = (TargetEntry *) lfirst(lc); Var *var; if (tent->resjunk) continue; var = makeVarFromTargetEntry(varno, tent); result = lappend(result, var); } return result; } /* * convert_testexpr: convert the testexpr given by the parser into * actually executable form. This entails replacing PARAM_SUBLINK Params * with Params or Vars representing the results of the sub-select. The * nodes to be substituted are passed in as the List result from * generate_subquery_params or generate_subquery_vars. */ static Node * convert_testexpr(PlannerInfo *root, Node *testexpr, List *subst_nodes) { convert_testexpr_context context; context.root = root; context.subst_nodes = subst_nodes; return convert_testexpr_mutator(testexpr, &context); } static Node * convert_testexpr_mutator(Node *node, convert_testexpr_context *context) { if (node == NULL) return NULL; if (IsA(node, Param)) { Param *param = (Param *) node; if (param->paramkind == PARAM_SUBLINK) { if (param->paramid <= 0 || param->paramid > list_length(context->subst_nodes)) elog(ERROR, "unexpected PARAM_SUBLINK ID: %d", param->paramid); /* * We copy the list item to avoid having doubly-linked * substructure in the modified parse tree. This is probably * unnecessary when it's a Param, but be safe. */ return (Node *) copyObject(list_nth(context->subst_nodes, param->paramid - 1)); } } if (IsA(node, SubLink)) { /* * If we come across a nested SubLink, it is neither necessary nor * correct to recurse into it: any PARAM_SUBLINKs we might find inside * belong to the inner SubLink not the outer. So just return it as-is. * * This reasoning depends on the assumption that nothing will pull * subexpressions into or out of the testexpr field of a SubLink, at * least not without replacing PARAM_SUBLINKs first. If we did want * to do that we'd need to rethink the parser-output representation * altogether, since currently PARAM_SUBLINKs are only unique per * SubLink not globally across the query. The whole point of * replacing them with Vars or PARAM_EXEC nodes is to make them * globally unique before they escape from the SubLink's testexpr. * * Note: this can't happen when called during SS_process_sublinks, * because that recursively processes inner SubLinks first. It can * happen when called from convert_ANY_sublink_to_join, though. */ return node; } return expression_tree_mutator(node, reinterpret_cast<expression_tree_mutator_fptr>(convert_testexpr_mutator), (void *) context); } /* * subplan_is_hashable: can we implement an ANY subplan by hashing? */ static bool subplan_is_hashable(Plan *plan) { double subquery_size; /* * The estimated size of the subquery result must fit in work_mem. (Note: * we use heap tuple overhead here even though the tuples will actually be * stored as MinimalTuples; this provides some fudge factor for hashtable * overhead.) */ subquery_size = plan->plan_rows * (MAXALIGN(plan->plan_width) + MAXALIGN(SizeofHeapTupleHeader)); if (subquery_size > work_mem * 1024L) return false; return true; } /* * testexpr_is_hashable: is an ANY SubLink's test expression hashable? */ static bool testexpr_is_hashable(Node *testexpr) { /* * The testexpr must be a single OpExpr, or an AND-clause containing only * OpExprs. * * The combining operators must be hashable and strict. The need for * hashability is obvious, since we want to use hashing. Without * strictness, behavior in the presence of nulls is too unpredictable. We * actually must assume even more than plain strictness: they can't yield * NULL for non-null inputs, either (see nodeSubplan.c). However, hash * indexes and hash joins assume that too. */ if (testexpr && IsA(testexpr, OpExpr)) { if (hash_ok_operator((OpExpr *) testexpr)) return true; } else if (and_clause(testexpr)) { ListCell *l; foreach(l, ((BoolExpr *) testexpr)->args) { Node *andarg = (Node *) lfirst(l); if (!IsA(andarg, OpExpr)) return false; if (!hash_ok_operator((OpExpr *) andarg)) return false; } return true; } return false; } /* * Check expression is hashable + strict * * We could use op_hashjoinable() and op_strict(), but do it like this to * avoid a redundant cache lookup. */ static bool hash_ok_operator(OpExpr *expr) { Oid opid = expr->opno; /* quick out if not a binary operator___ */ if (list_length(expr->args) != 2) return false; if (opid == ARRAY_EQ_OP) { /* array_eq is strict, but must check input type to ensure hashable */ /* XXX record_eq will need same treatment when it becomes hashable */ Node *leftarg = static_cast<Node *>(linitial(expr->args)); return op_hashjoinable(opid, exprType(leftarg)); } else { /* else must look up the operator___ properties */ HeapTuple tup; Form_pg_operator optup; tup = SearchSysCache1(OPEROID, ObjectIdGetDatum(opid)); if (!HeapTupleIsValid(tup)) elog(ERROR, "cache lookup failed for operator___ %u", opid); optup = (Form_pg_operator) GETSTRUCT(tup); if (!optup->oprcanhash || !func_strict(optup->oprcode)) { ReleaseSysCache(tup); return false; } ReleaseSysCache(tup); return true; } } /* * SS_process_ctes: process a query's WITH list * * We plan each interesting WITH item and convert it to an initplan. * A side effect is to fill in root->cte_plan_ids with a list that * parallels root->parse->cteList and provides the subplan ID for * each CTE's initplan. */ void SS_process_ctes(PlannerInfo *root) { ListCell *lc; Assert(root->cte_plan_ids == NIL); foreach(lc, root->parse->cteList) { CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc); CmdType cmdType = ((Query *) cte->ctequery)->commandType; Query *subquery; Plan *plan; PlannerInfo *subroot; SubPlan *splan; int paramid; /* * Ignore SELECT CTEs that are not actually referenced anywhere. */ if (cte->cterefcount == 0 && cmdType == CMD_SELECT) { /* Make a dummy entry in cte_plan_ids */ root->cte_plan_ids = lappend_int(root->cte_plan_ids, -1); continue; } /* * Copy the source Query node. Probably not necessary, but let's keep * this similar to make_subplan. */ subquery = (Query *) copyObject(cte->ctequery); /* plan_params should not be in use in current query level */ Assert(root->plan_params == NIL); /* * Generate the plan for the CTE query. Always plan for full * retrieval --- we don't have enough info to predict otherwise. */ plan = subquery_planner(root->glob, subquery, root, cte->cterecursive, 0.0, &subroot); /* * Since the current query level doesn't yet contain any RTEs, it * should not be possible for the CTE to have requested parameters of * this level. */ if (root->plan_params) elog(ERROR, "unexpected outer reference in CTE query"); /* * Make a SubPlan node for it. This is just enough unlike * build_subplan that we can't share code. * * Note plan_id, plan_name, and cost fields are set further down. */ splan = makeNode(SubPlan); splan->subLinkType = CTE_SUBLINK; splan->testexpr = NULL; splan->paramIds = NIL; get_first_col_type(plan, &splan->firstColType, &splan->firstColTypmod, &splan->firstColCollation); splan->useHashTable = false; splan->unknownEqFalse = false; splan->setParam = NIL; splan->parParam = NIL; splan->args = NIL; /* * The node can't have any inputs (since it's an initplan), so the * parParam and args lists remain empty. (It could contain references * to earlier CTEs' output param IDs, but CTE outputs are not * propagated via the args list.) */ /* * Assign a param ID to represent the CTE's output. No ordinary * "evaluation" of this param slot ever happens, but we use the param * ID for setParam/chgParam signaling just as if the CTE plan were * returning a simple scalar output. (Also, the executor abuses the * ParamExecData slot for this param ID for communication among * multiple CteScan nodes that might be scanning this CTE.) */ paramid = SS_assign_special_param(root); splan->setParam = list_make1_int(paramid); /* * Add the subplan and its PlannerInfo to the global lists. */ root->glob->subplans = lappend(root->glob->subplans, plan); root->glob->subroots = lappend(root->glob->subroots, subroot); splan->plan_id = list_length(root->glob->subplans); root->init_plans = lappend(root->init_plans, splan); root->cte_plan_ids = lappend_int(root->cte_plan_ids, splan->plan_id); /* Label the subplan for EXPLAIN purposes */ splan->plan_name = psprintf("CTE %s", cte->ctename); /* Lastly, fill in the cost estimates for use later */ cost_subplan(root, splan, plan); } } /* * convert_ANY_sublink_to_join: try to convert an ANY SubLink to a join * * The caller has found an ANY SubLink at the top level of one of the query's * qual clauses, but has not checked the properties of the SubLink further. * Decide whether it is appropriate to process this SubLink in join style. * If so, form a JoinExpr and return it. Return NULL if the SubLink cannot * be converted to a join. * * The only non-obvious input parameter is available_rels: this is the set * of query rels that can safely be referenced in the sublink expression. * (We must restrict this to avoid changing the semantics when a sublink * is present in an outer join's ON qual.) The conversion must fail if * the converted qual would reference any but these parent-query relids. * * On success, the returned JoinExpr has larg = NULL and rarg = the jointree * item representing the pulled-up subquery. The caller must set larg to * represent the relation(s) on the lefthand side of the new___ join, and insert * the JoinExpr into the upper query's jointree at an appropriate place * (typically, where the lefthand relation(s) had been). Note that the * passed-in SubLink must also be removed from its original position in the * query quals, since the quals of the returned JoinExpr replace it. * (Notionally, we replace the SubLink with a constant TRUE, then elide the * redundant constant from the qual.) * * On success, the caller is also responsible for recursively applying * pull_up_sublinks processing to the rarg and quals of the returned JoinExpr. * (On failure, there is no need to do anything, since pull_up_sublinks will * be applied when we recursively plan the sub-select.) * * Side effects of a successful conversion include adding the SubLink's * subselect to the query's rangetable, so that it can be referenced in * the JoinExpr's rarg. */ JoinExpr * convert_ANY_sublink_to_join(PlannerInfo *root, SubLink *sublink, Relids available_rels) { JoinExpr *result; Query *parse = root->parse; Query *subselect = (Query *) sublink->subselect; Relids upper_varnos; int rtindex; RangeTblEntry *rte; RangeTblRef *rtr; List *subquery_vars; Node *quals; ParseState *pstate; Assert(sublink->subLinkType == ANY_SUBLINK); /* * The sub-select must not refer to any Vars of the parent query. (Vars of * higher levels should be okay, though.) */ if (contain_vars_of_level((Node *) subselect, 1)) return NULL; /* * The test expression must contain some Vars of the parent query, else * it's not gonna be a join. (Note that it won't have Vars referring to * the subquery, rather Params.) */ upper_varnos = pull_varnos(sublink->testexpr); if (bms_is_empty(upper_varnos)) return NULL; /* * However, it can't refer to anything outside available_rels. */ if (!bms_is_subset(upper_varnos, available_rels)) return NULL; /* * The combining operators and left-hand expressions mustn't be volatile. */ if (contain_volatile_functions(sublink->testexpr)) return NULL; /* Create a dummy ParseState for addRangeTableEntryForSubquery */ pstate = make_parsestate(NULL); /* * Okay, pull up the sub-select into upper range table. * * We rely here on the assumption that the outer query has no references * to the inner (necessarily true, other than the Vars that we build * below). Therefore this is a lot easier than what pull_up_subqueries has * to go through. */ rte = addRangeTableEntryForSubquery(pstate, subselect, makeAlias("ANY_subquery", NIL), false, false); parse->rtable = lappend(parse->rtable, rte); rtindex = list_length(parse->rtable); /* * Form a RangeTblRef for the pulled-up sub-select. */ rtr = makeNode(RangeTblRef); rtr->rtindex = rtindex; /* * Build a list of Vars representing the subselect outputs. */ subquery_vars = generate_subquery_vars(root, subselect->targetList, rtindex); /* * Build the new___ join's qual expression, replacing Params with these Vars. */ quals = convert_testexpr(root, sublink->testexpr, subquery_vars); /* * And finally, build the JoinExpr node. */ result = makeNode(JoinExpr); result->jointype = JOIN_SEMI; result->isNatural = false; result->larg = NULL; /* caller must fill this in */ result->rarg = (Node *) rtr; result->usingClause = NIL; result->quals = quals; result->alias = NULL; result->rtindex = 0; /* we don't need an RTE for it */ return result; } /* * convert_EXISTS_sublink_to_join: try to convert an EXISTS SubLink to a join * * The API of this function is identical to convert_ANY_sublink_to_join's, * except that we also support the case where the caller has found NOT EXISTS, * so we need an additional input parameter "under_not". */ JoinExpr * convert_EXISTS_sublink_to_join(PlannerInfo *root, SubLink *sublink, bool under_not, Relids available_rels) { JoinExpr *result; Query *parse = root->parse; Query *subselect = (Query *) sublink->subselect; Node *whereClause; int rtoffset; int varno; Relids clause_varnos; Relids upper_varnos; Assert(sublink->subLinkType == EXISTS_SUBLINK); /* * Can't flatten if it contains WITH. (We could arrange to pull up the * WITH into the parent query's cteList, but that risks changing the * semantics, since a WITH ought to be executed once per associated query * call.) Note that convert_ANY_sublink_to_join doesn't have to reject * this case, since it just produces a subquery RTE that doesn't have to * get flattened into the parent query. */ if (subselect->cteList) return NULL; /* * Copy the subquery so we can modify it safely (see comments in * make_subplan). */ subselect = (Query *) copyObject(subselect); /* * See if the subquery can be simplified based on the knowledge that it's * being used in EXISTS(). If we aren't able to get rid of its * targetlist, we have to fail, because the pullup operation leaves us * with noplace to evaluate the targetlist. */ if (!simplify_EXISTS_query(root, subselect)) return NULL; /* * The subquery must have a nonempty jointree, else we won't have a join. */ if (subselect->jointree->fromlist == NIL) return NULL; /* * Separate out the WHERE clause. (We could theoretically also remove * top-level plain JOIN/ON clauses, but it's probably not worth the * trouble.) */ whereClause = subselect->jointree->quals; subselect->jointree->quals = NULL; /* * The rest of the sub-select must not refer to any Vars of the parent * query. (Vars of higher levels should be okay, though.) */ if (contain_vars_of_level((Node *) subselect, 1)) return NULL; /* * On the other hand, the WHERE clause must contain some Vars of the * parent query, else it's not gonna be a join. */ if (!contain_vars_of_level(whereClause, 1)) return NULL; /* * We don't risk optimizing if the WHERE clause is volatile, either. */ if (contain_volatile_functions(whereClause)) return NULL; /* * Prepare to pull up the sub-select into top range table. * * We rely here on the assumption that the outer query has no references * to the inner (necessarily true). Therefore this is a lot easier than * what pull_up_subqueries has to go through. * * In fact, it's even easier than what convert_ANY_sublink_to_join has to * do. The machinations of simplify_EXISTS_query ensured that there is * nothing interesting in the subquery except an rtable and jointree, and * even the jointree FromExpr no longer has quals. So we can just append * the rtable to our own and use the FromExpr in our jointree. But first, * adjust all level-zero varnos in the subquery to account for the rtable * merger. */ rtoffset = list_length(parse->rtable); OffsetVarNodes((Node *) subselect, rtoffset, 0); OffsetVarNodes(whereClause, rtoffset, 0); /* * Upper-level vars in subquery will now be one level closer to their * parent than before; in particular, anything that had been level 1 * becomes level zero. */ IncrementVarSublevelsUp((Node *) subselect, -1, 1); IncrementVarSublevelsUp(whereClause, -1, 1); /* * Now that the WHERE clause is adjusted to match the parent query * environment, we can easily identify all the level-zero rels it uses. * The ones <= rtoffset belong to the upper query; the ones > rtoffset do * not. */ clause_varnos = pull_varnos(whereClause); upper_varnos = NULL; while ((varno = bms_first_member(clause_varnos)) >= 0) { if (varno <= rtoffset) upper_varnos = bms_add_member(upper_varnos, varno); } bms_free(clause_varnos); Assert(!bms_is_empty(upper_varnos)); /* * Now that we've got the set of upper-level varnos, we can make the last * check: only available_rels can be referenced. */ if (!bms_is_subset(upper_varnos, available_rels)) return NULL; /* Now we can attach the modified subquery rtable to the parent */ parse->rtable = list_concat(parse->rtable, subselect->rtable); /* * And finally, build the JoinExpr node. */ result = makeNode(JoinExpr); result->jointype = under_not ? JOIN_ANTI : JOIN_SEMI; result->isNatural = false; result->larg = NULL; /* caller must fill this in */ /* flatten out the FromExpr node if it's useless */ if (list_length(subselect->jointree->fromlist) == 1) result->rarg = (Node *) linitial(subselect->jointree->fromlist); else result->rarg = (Node *) subselect->jointree; result->usingClause = NIL; result->quals = whereClause; result->alias = NULL; result->rtindex = 0; /* we don't need an RTE for it */ return result; } /* * simplify_EXISTS_query: remove any useless stuff in an EXISTS's subquery * * The only thing that matters about an EXISTS query is whether it returns * zero or more than zero rows. Therefore, we can remove certain SQL features * that won't affect that. The only part that is really likely to matter in * typical usage is simplifying the targetlist: it's a common habit to write * "SELECT * FROM" even though there is no need to evaluate any columns. * * Note: by suppressing the targetlist we could cause an observable behavioral * change, namely that any errors that might occur in evaluating the tlist * won't occur, nor will other side-effects of volatile functions. This seems * unlikely to bother anyone in practice. * * Returns TRUE if was able to discard the targetlist, else FALSE. */ static bool simplify_EXISTS_query(PlannerInfo *root, Query *query) { /* * We don't try to simplify at all if the query uses set operations, * aggregates, grouping sets, modifying CTEs, HAVING, OFFSET, or FOR * UPDATE/SHARE; none of these seem likely in normal usage and their * possible effects are complex. (Note: we could ignore an "OFFSET 0" * clause, but that traditionally is used as an optimization fence, so we * don't.) */ if (query->commandType != CMD_SELECT || query->setOperations || query->hasAggs || query->groupingSets || query->hasWindowFuncs || query->hasModifyingCTE || query->havingQual || query->limitOffset || query->rowMarks) return false; /* * LIMIT with a constant positive (or NULL) value doesn't affect the * semantics of EXISTS, so let's ignore such clauses. This is worth doing * because people accustomed to certain other DBMSes may be in the habit * of writing EXISTS(SELECT ... LIMIT 1) as an optimization. If there's a * LIMIT with anything else as argument, though, we can't simplify. */ if (query->limitCount) { /* * The LIMIT clause has not yet been through eval_const_expressions, * so we have to apply that here. It might seem like this is a waste * of cycles, since the only case plausibly worth worrying about is * "LIMIT 1" ... but what we'll actually see is "LIMIT int8(1::int4)", * so we have to fold constants or we're not going to recognize it. */ Node *node = eval_const_expressions(root, query->limitCount); Const *limit; /* Might as well update the query if we simplified the clause. */ query->limitCount = node; if (!IsA(node, Const)) return false; limit = (Const *) node; Assert(limit->consttype == INT8OID); if (!limit->constisnull && DatumGetInt64(limit->constvalue) <= 0) return false; /* Whether or not the targetlist is safe, we can drop the LIMIT. */ query->limitCount = NULL; } /* * Mustn't throw away the targetlist if it contains set-returning * functions; those could affect whether zero rows are returned! */ if (expression_returns_set((Node *) query->targetList)) return false; /* * Otherwise, we can throw away the targetlist, as well as any GROUP, * WINDOW, DISTINCT, and ORDER BY clauses; none of those clauses will * change a nonzero-rows result to zero rows or vice versa. (Furthermore, * since our parsetree representation of these clauses depends on the * targetlist, we'd better throw them away if we drop the targetlist.) */ query->targetList = NIL; query->groupClause = NIL; query->windowClause = NIL; query->distinctClause = NIL; query->sortClause = NIL; query->hasDistinctOn = false; return true; } /* * convert_EXISTS_to_ANY: try to convert EXISTS to a hashable ANY sublink * * The subselect is expected to be a fresh copy that we can munge up, * and to have been successfully passed through simplify_EXISTS_query. * * On success, the modified subselect is returned, and we store a suitable * upper-level test expression at *testexpr, plus a list of the subselect's * output Params at *paramIds. (The test expression is already Param-ified * and hence need not go through convert_testexpr, which is why we have to * deal with the Param IDs specially.) * * On failure, returns NULL. */ static Query * convert_EXISTS_to_ANY(PlannerInfo *root, Query *subselect, Node **testexpr, List **paramIds) { Node *whereClause; List *leftargs, *rightargs, *opids, *opcollations, *newWhere, *tlist, *testlist, *paramids; ListCell *lc, *rc, *oc, *cc; AttrNumber resno; /* * Query must not require a targetlist, since we have to insert a new___ one. * Caller should have dealt with the case already. */ Assert(subselect->targetList == NIL); /* * Separate out the WHERE clause. (We could theoretically also remove * top-level plain JOIN/ON clauses, but it's probably not worth the * trouble.) */ whereClause = subselect->jointree->quals; subselect->jointree->quals = NULL; /* * The rest of the sub-select must not refer to any Vars of the parent * query. (Vars of higher levels should be okay, though.) * * Note: we need not check for Aggrefs separately because we know the * sub-select is as yet unoptimized; any uplevel Aggref must therefore * contain an uplevel Var reference. This is not the case below ... */ if (contain_vars_of_level((Node *) subselect, 1)) return NULL; /* * We don't risk optimizing if the WHERE clause is volatile, either. */ if (contain_volatile_functions(whereClause)) return NULL; /* * Clean up the WHERE clause by doing const-simplification etc on it. * Aside from simplifying the processing we're about to do, this is * important for being able to pull chunks of the WHERE clause up into the * parent query. Since we are invoked partway through the parent's * preprocess_expression() work, earlier steps of preprocess_expression() * wouldn't get applied to the pulled-up stuff unless we do them here. For * the parts of the WHERE clause that get put back into the child query, * this work is partially duplicative, but it shouldn't hurt. * * Note: we do not run flatten_join_alias_vars. This is OK because any * parent aliases were flattened already, and we're not going to pull any * child Vars (of any description) into the parent. * * Note: passing the parent's root to eval_const_expressions is * technically wrong, but we can get away with it since only the * boundParams (if any) are used, and those would be the same in a * subroot. */ whereClause = eval_const_expressions(root, whereClause); whereClause = (Node *) canonicalize_qual((Expr *) whereClause); whereClause = (Node *) make_ands_implicit((Expr *) whereClause); /* * We now have a flattened implicit-AND list of clauses, which we try to * break apart into "outervar = innervar" hash clauses. Anything that * can't be broken apart just goes back into the newWhere list. Note that * we aren't trying hard yet to ensure that we have only outer or only * inner on each side; we'll check that if we get to the end. */ leftargs = rightargs = opids = opcollations = newWhere = NIL; foreach(lc, (List *) whereClause) { OpExpr *expr = (OpExpr *) lfirst(lc); if (IsA(expr, OpExpr) && hash_ok_operator(expr)) { Node *leftarg = (Node *) linitial(expr->args); Node *rightarg = (Node *) lsecond(expr->args); if (contain_vars_of_level(leftarg, 1)) { leftargs = lappend(leftargs, leftarg); rightargs = lappend(rightargs, rightarg); opids = lappend_oid(opids, expr->opno); opcollations = lappend_oid(opcollations, expr->inputcollid); continue; } if (contain_vars_of_level(rightarg, 1)) { /* * We must commute the clause to put the outer var on the * left, because the hashing code in nodeSubplan.c expects * that. This probably shouldn't ever fail, since hashable * operators ought to have commutators, but be paranoid. */ expr->opno = get_commutator(expr->opno); if (OidIsValid(expr->opno) && hash_ok_operator(expr)) { leftargs = lappend(leftargs, rightarg); rightargs = lappend(rightargs, leftarg); opids = lappend_oid(opids, expr->opno); opcollations = lappend_oid(opcollations, expr->inputcollid); continue; } /* If no commutator, no chance to optimize the WHERE clause */ return NULL; } } /* Couldn't handle it as a hash clause */ newWhere = lappend(newWhere, expr); } /* * If we didn't find anything we could convert, fail. */ if (leftargs == NIL) return NULL; /* * There mustn't be any parent Vars or Aggs in the stuff that we intend to * put back into the child query. Note: you might think we don't need to * check for Aggs separately, because an uplevel Agg must contain an * uplevel Var in its argument. But it is possible that the uplevel Var * got optimized away by eval_const_expressions. Consider * * SUM(CASE WHEN false THEN uplevelvar ELSE 0 END) */ if (contain_vars_of_level((Node *) newWhere, 1) || contain_vars_of_level((Node *) rightargs, 1)) return NULL; if (root->parse->hasAggs && (contain_aggs_of_level((Node *) newWhere, 1) || contain_aggs_of_level((Node *) rightargs, 1))) return NULL; /* * And there can't be any child Vars in the stuff we intend to pull up. * (Note: we'd need to check for child Aggs too, except we know the child * has no aggs at all because of simplify_EXISTS_query's check. The same * goes for window functions.) */ if (contain_vars_of_level((Node *) leftargs, 0)) return NULL; /* * Also reject sublinks in the stuff we intend to pull up. (It might be * possible to support this, but doesn't seem worth the complication.) */ if (contain_subplans((Node *) leftargs)) return NULL; /* * Okay, adjust the sublevelsup in the stuff we're pulling up. */ IncrementVarSublevelsUp((Node *) leftargs, -1, 1); /* * Put back any child-level-only WHERE clauses. */ if (newWhere) subselect->jointree->quals = (Node *) make_ands_explicit(newWhere); /* * Build a new___ targetlist for the child that emits the expressions we * need. Concurrently, build a testexpr for the parent using Params to * reference the child outputs. (Since we generate Params directly here, * there will be no need to convert the testexpr in build_subplan.) */ tlist = testlist = paramids = NIL; resno = 1; /* there's no "forfour" so we have to chase one of the lists manually */ cc = list_head(opcollations); forthree(lc, leftargs, rc, rightargs, oc, opids) { Node *leftarg = (Node *) lfirst(lc); Node *rightarg = (Node *) lfirst(rc); Oid opid = lfirst_oid(oc); Oid opcollation = lfirst_oid(cc); Param *param; cc = lnext(cc); param = generate_new_param(root, exprType(rightarg), exprTypmod(rightarg), exprCollation(rightarg)); tlist = lappend(tlist, makeTargetEntry((Expr *) rightarg, resno++, NULL, false)); testlist = lappend(testlist, make_opclause(opid, BOOLOID, false, (Expr *) leftarg, (Expr *) param, InvalidOid, opcollation)); paramids = lappend_int(paramids, param->paramid); } /* Put everything where it should go, and we're done */ subselect->targetList = tlist; *testexpr = (Node *) make_ands_explicit(testlist); *paramIds = paramids; return subselect; } /* * Replace correlation vars (uplevel vars) with Params. * * Uplevel PlaceHolderVars and aggregates are replaced, too. * * Note: it is critical that this runs immediately after SS_process_sublinks. * Since we do not recurse into the arguments of uplevel PHVs and aggregates, * they will get copied to the appropriate subplan args list in the parent * query with uplevel vars not replaced by Params, but only adjusted in level * (see replace_outer_placeholdervar and replace_outer_agg). That's exactly * what we want for the vars of the parent level --- but if a PHV's or * aggregate's argument contains any further-up variables, they have to be * replaced with Params in their turn. That will happen when the parent level * runs SS_replace_correlation_vars. Therefore it must do so after expanding * its sublinks to subplans. And we don't want any steps in between, else * those steps would never get applied to the argument expressions, either in * the parent or the child level. * * Another fairly tricky thing going on here is the handling of SubLinks in * the arguments of uplevel PHVs/aggregates. Those are not touched inside the * intermediate query level, either. Instead, SS_process_sublinks recurses on * them after copying the PHV or Aggref expression into the parent plan level * (this is actually taken care of in build_subplan). */ Node * SS_replace_correlation_vars(PlannerInfo *root, Node *expr) { /* No setup needed for tree walk, so away we go */ return replace_correlation_vars_mutator(expr, root); } static Node * replace_correlation_vars_mutator(Node *node, PlannerInfo *root) { if (node == NULL) return NULL; if (IsA(node, Var)) { if (((Var *) node)->varlevelsup > 0) return (Node *) replace_outer_var(root, (Var *) node); } if (IsA(node, PlaceHolderVar)) { if (((PlaceHolderVar *) node)->phlevelsup > 0) return (Node *) replace_outer_placeholdervar(root, (PlaceHolderVar *) node); } if (IsA(node, Aggref)) { if (((Aggref *) node)->agglevelsup > 0) return (Node *) replace_outer_agg(root, (Aggref *) node); } if (IsA(node, GroupingFunc)) { if (((GroupingFunc *) node)->agglevelsup > 0) return (Node *) replace_outer_grouping(root, (GroupingFunc *) node); } return expression_tree_mutator(node, reinterpret_cast<expression_tree_mutator_fptr>(replace_correlation_vars_mutator), (void *) root); } /* * Expand SubLinks to SubPlans in the given expression. * * The isQual argument tells whether or not this expression is a WHERE/HAVING * qualifier expression. If it is, any sublinks appearing at top level need * not distinguish FALSE from UNKNOWN return values. */ Node * SS_process_sublinks(PlannerInfo *root, Node *expr, bool isQual) { process_sublinks_context context; context.root = root; context.isTopQual = isQual; return process_sublinks_mutator(expr, &context); } static Node * process_sublinks_mutator(Node *node, process_sublinks_context *context) { process_sublinks_context locContext; locContext.root = context->root; if (node == NULL) return NULL; if (IsA(node, SubLink)) { SubLink *sublink = (SubLink *) node; Node *testexpr; /* * First, recursively process the lefthand-side expressions, if any. * They're not top-level anymore. */ locContext.isTopQual = false; testexpr = process_sublinks_mutator(sublink->testexpr, &locContext); /* * Now build the SubPlan node and make the expr to return. */ return make_subplan(context->root, (Query *) sublink->subselect, sublink->subLinkType, sublink->subLinkId, testexpr, context->isTopQual); } /* * Don't recurse into the arguments of an outer PHV or aggregate here. Any * SubLinks in the arguments have to be dealt with at the outer query * level; they'll be handled when build_subplan collects the PHV or Aggref * into the arguments to be passed down to the current subplan. */ if (IsA(node, PlaceHolderVar)) { if (((PlaceHolderVar *) node)->phlevelsup > 0) return node; } else if (IsA(node, Aggref)) { if (((Aggref *) node)->agglevelsup > 0) return node; } /* * We should never see a SubPlan expression in the input (since this is * the very routine that creates 'em to begin with). We shouldn't find * ourselves invoked directly on a Query, either. */ Assert(!IsA(node, SubPlan)); Assert(!IsA(node, AlternativeSubPlan)); Assert(!IsA(node, Query)); /* * Because make_subplan() could return an AND or OR clause, we have to * take steps to preserve AND/OR flatness of a qual. We assume the input * has been AND/OR flattened and so we need no recursion here. * * (Due to the coding here, we will not get called on the List subnodes of * an AND; and the input is *not* yet in implicit-AND format. So no check * is needed for a bare List.) * * Anywhere within the top-level AND/OR clause structure, we can tell * make_subplan() that NULL and FALSE are interchangeable. So isTopQual * propagates down in both cases. (Note that this is unlike the meaning * of "top level qual" used in most other places in Postgres.) */ if (and_clause(node)) { List *newargs = NIL; ListCell *l; /* Still at qual top-level */ locContext.isTopQual = context->isTopQual; foreach(l, ((BoolExpr *) node)->args) { Node *newarg; newarg = process_sublinks_mutator(static_cast<Node *>(lfirst(l)), &locContext); if (and_clause(newarg)) newargs = list_concat(newargs, ((BoolExpr *) newarg)->args); else newargs = lappend(newargs, newarg); } return (Node *) make_andclause(newargs); } if (or_clause(node)) { List *newargs = NIL; ListCell *l; /* Still at qual top-level */ locContext.isTopQual = context->isTopQual; foreach(l, ((BoolExpr *) node)->args) { Node *newarg; newarg = process_sublinks_mutator(static_cast<Node *>(lfirst(l)), &locContext); if (or_clause(newarg)) newargs = list_concat(newargs, ((BoolExpr *) newarg)->args); else newargs = lappend(newargs, newarg); } return (Node *) make_orclause(newargs); } /* * If we recurse down through anything other than an AND or OR node, we * are definitely not at top qual level anymore. */ locContext.isTopQual = false; return expression_tree_mutator(node, reinterpret_cast<expression_tree_mutator_fptr>(process_sublinks_mutator), (void *) &locContext); } /* * SS_finalize_plan - do final sublink and parameter processing for a * completed Plan. * * This recursively computes the extParam and allParam sets for every Plan * node in the given plan tree. It also optionally attaches any previously * generated InitPlans to the top plan node. (Any InitPlans should already * have been put through SS_finalize_plan.) */ void SS_finalize_plan(PlannerInfo *root, Plan *plan, bool attach_initplans) { Bitmapset *valid_params, *initExtParam, *initSetParam; Cost initplan_cost; PlannerInfo *proot; ListCell *l; /* * Examine any initPlans to determine the set of external params they * reference, the set of output params they supply, and their total cost. * We'll use at least some of this info below. (Note we are assuming that * finalize_plan doesn't touch the initPlans.) * * In the case where attach_initplans is false, we are assuming that the * existing initPlans are siblings that might supply params needed by the * current plan. */ initExtParam = initSetParam = NULL; initplan_cost = 0; foreach(l, root->init_plans) { SubPlan *initsubplan = (SubPlan *) lfirst(l); Plan *initplan = planner_subplan_get_plan(root, initsubplan); ListCell *l2; initExtParam = bms_add_members(initExtParam, initplan->extParam); foreach(l2, initsubplan->setParam) { initSetParam = bms_add_member(initSetParam, lfirst_int(l2)); } initplan_cost += initsubplan->startup_cost + initsubplan->per_call_cost; } /* * Now determine the set of params that are validly referenceable in this * query level; to wit, those available from outer query levels plus the * output parameters of any local initPlans. (We do not include output * parameters of regular subplans. Those should only appear within the * testexpr of SubPlan nodes, and are taken care of locally within * finalize_primnode. Likewise, special parameters that are generated by * nodes such as ModifyTable are handled within finalize_plan.) */ valid_params = bms_copy(initSetParam); for (proot = root->parent_root; proot != NULL; proot = proot->parent_root) { /* Include ordinary Var/PHV/Aggref params */ foreach(l, proot->plan_params) { PlannerParamItem *pitem = (PlannerParamItem *) lfirst(l); valid_params = bms_add_member(valid_params, pitem->paramId); } /* Include any outputs of outer-level initPlans */ foreach(l, proot->init_plans) { SubPlan *initsubplan = (SubPlan *) lfirst(l); ListCell *l2; foreach(l2, initsubplan->setParam) { valid_params = bms_add_member(valid_params, lfirst_int(l2)); } } /* Include worktable ID, if a recursive query is being planned */ if (proot->wt_param_id >= 0) valid_params = bms_add_member(valid_params, proot->wt_param_id); } /* * Now recurse through plan tree. */ (void) finalize_plan(root, plan, valid_params, NULL); bms_free(valid_params); /* * Finally, attach any initPlans to the topmost plan node, and add their * extParams to the topmost node's, too. However, any setParams of the * initPlans should not be present in the topmost node's extParams, only * in its allParams. (As of PG 8.1, it's possible that some initPlans * have extParams that are setParams of other initPlans, so we have to * take care of this situation explicitly.) * * We also add the eval cost of each initPlan to the startup cost of the * top node. This is a conservative overestimate, since in fact each * initPlan might be executed later than plan startup, or even not at all. */ if (attach_initplans) { plan->initPlan = root->init_plans; root->init_plans = NIL; /* make sure they're not attached twice */ /* allParam must include all these params */ plan->allParam = bms_add_members(plan->allParam, initExtParam); plan->allParam = bms_add_members(plan->allParam, initSetParam); /* extParam must include any child extParam */ plan->extParam = bms_add_members(plan->extParam, initExtParam); /* but extParam shouldn't include any setParams */ plan->extParam = bms_del_members(plan->extParam, initSetParam); /* ensure extParam is exactly NULL if it's empty */ if (bms_is_empty(plan->extParam)) plan->extParam = NULL; plan->startup_cost += initplan_cost; plan->total_cost += initplan_cost; } } /* * Recursive processing of all nodes in the plan tree * * valid_params is the set of param IDs considered valid to reference in * this plan node or its children. * scan_params is a set of param IDs to force scan plan nodes to reference. * This is for EvalPlanQual support, and is always NULL at the top of the * recursion. * * The return value is the computed allParam set for the given Plan node. * This is just an internal notational convenience. */ static Bitmapset * finalize_plan(PlannerInfo *root, Plan *plan, Bitmapset *valid_params, Bitmapset *scan_params) { finalize_primnode_context context; int locally_added_param; Bitmapset *nestloop_params; Bitmapset *child_params; if (plan == NULL) return NULL; context.root = root; context.paramids = NULL; /* initialize set to empty */ locally_added_param = -1; /* there isn't one */ nestloop_params = NULL; /* there aren't any */ /* * When we call finalize_primnode, context.paramids sets are automatically * merged together. But when recursing to self, we have to do it the hard * way. We want the paramids set to include params in subplans as well as * at this level. */ /* Find params in targetlist and qual */ finalize_primnode((Node *) plan->targetlist, &context); finalize_primnode((Node *) plan->qual, &context); /* Check additional node-type-specific fields */ switch (nodeTag(plan)) { case T_Result: finalize_primnode(((Result *) plan)->resconstantqual, &context); break; case T_SeqScan: case T_SampleScan: context.paramids = bms_add_members(context.paramids, scan_params); break; case T_IndexScan: finalize_primnode((Node *) ((IndexScan *) plan)->indexqual, &context); finalize_primnode((Node *) ((IndexScan *) plan)->indexorderby, &context); /* * we need not look at indexqualorig, since it will have the same * param references as indexqual. Likewise, we can ignore * indexorderbyorig. */ context.paramids = bms_add_members(context.paramids, scan_params); break; case T_IndexOnlyScan: finalize_primnode((Node *) ((IndexOnlyScan *) plan)->indexqual, &context); finalize_primnode((Node *) ((IndexOnlyScan *) plan)->indexorderby, &context); /* * we need not look at indextlist, since it cannot contain Params. */ context.paramids = bms_add_members(context.paramids, scan_params); break; case T_BitmapIndexScan: finalize_primnode((Node *) ((BitmapIndexScan *) plan)->indexqual, &context); /* * we need not look at indexqualorig, since it will have the same * param references as indexqual. */ break; case T_BitmapHeapScan: finalize_primnode((Node *) ((BitmapHeapScan *) plan)->bitmapqualorig, &context); context.paramids = bms_add_members(context.paramids, scan_params); break; case T_TidScan: finalize_primnode((Node *) ((TidScan *) plan)->tidquals, &context); context.paramids = bms_add_members(context.paramids, scan_params); break; case T_SubqueryScan: /* * In a SubqueryScan, SS_finalize_plan has already been run on the * subplan by the inner invocation of subquery_planner, so there's * no need to do it again. Instead, just pull out the subplan's * extParams list, which represents the params it needs from my * level and higher levels. */ context.paramids = bms_add_members(context.paramids, ((SubqueryScan *) plan)->subplan->extParam); /* We need scan_params too, though */ context.paramids = bms_add_members(context.paramids, scan_params); break; case T_FunctionScan: { FunctionScan *fscan = (FunctionScan *) plan; ListCell *lc; /* * Call finalize_primnode independently on each function * expression, so that we can record which params are * referenced in each, in order to decide which need * re-evaluating during rescan. */ foreach(lc, fscan->functions) { RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc); finalize_primnode_context funccontext; funccontext = context; funccontext.paramids = NULL; finalize_primnode(rtfunc->funcexpr, &funccontext); /* remember results for execution */ rtfunc->funcparams = funccontext.paramids; /* add the function's params to the overall set */ context.paramids = bms_add_members(context.paramids, funccontext.paramids); } context.paramids = bms_add_members(context.paramids, scan_params); } break; case T_ValuesScan: finalize_primnode((Node *) ((ValuesScan *) plan)->values_lists, &context); context.paramids = bms_add_members(context.paramids, scan_params); break; case T_CteScan: { /* * You might think we should add the node's cteParam to * paramids, but we shouldn't because that param is just a * linkage mechanism for multiple CteScan nodes for the same * CTE; it is never used for changed-param signaling. What we * have to do instead is to find the referenced CTE plan and * incorporate its external paramids, so that the correct * things will happen if the CTE references outer-level * variables. See test cases for bug #4902. */ int plan_id = ((CteScan *) plan)->ctePlanId; Plan *cteplan; /* so, do this ... */ if (plan_id < 1 || plan_id > list_length(root->glob->subplans)) elog(ERROR, "could not find plan for CteScan referencing plan ID %d", plan_id); cteplan = (Plan *) list_nth(root->glob->subplans, plan_id - 1); context.paramids = bms_add_members(context.paramids, cteplan->extParam); #ifdef NOT_USED /* ... but not this */ context.paramids = bms_add_member(context.paramids, ((CteScan *) plan)->cteParam); #endif context.paramids = bms_add_members(context.paramids, scan_params); } break; case T_WorkTableScan: context.paramids = bms_add_member(context.paramids, ((WorkTableScan *) plan)->wtParam); context.paramids = bms_add_members(context.paramids, scan_params); break; case T_ForeignScan: finalize_primnode((Node *) ((ForeignScan *) plan)->fdw_exprs, &context); /* We assume fdw_scan_tlist cannot contain Params */ context.paramids = bms_add_members(context.paramids, scan_params); break; case T_CustomScan: finalize_primnode((Node *) ((CustomScan *) plan)->custom_exprs, &context); /* We assume custom_scan_tlist cannot contain Params */ context.paramids = bms_add_members(context.paramids, scan_params); break; case T_ModifyTable: { ModifyTable *mtplan = (ModifyTable *) plan; ListCell *l; /* Force descendant scan nodes to reference epqParam */ locally_added_param = mtplan->epqParam; valid_params = bms_add_member(bms_copy(valid_params), locally_added_param); scan_params = bms_add_member(bms_copy(scan_params), locally_added_param); finalize_primnode((Node *) mtplan->returningLists, &context); finalize_primnode((Node *) mtplan->onConflictSet, &context); finalize_primnode((Node *) mtplan->onConflictWhere, &context); foreach(l, mtplan->plans) { context.paramids = bms_add_members(context.paramids, finalize_plan(root, (Plan *) lfirst(l), valid_params, scan_params)); } } break; case T_Append: { ListCell *l; foreach(l, ((Append *) plan)->appendplans) { context.paramids = bms_add_members(context.paramids, finalize_plan(root, (Plan *) lfirst(l), valid_params, scan_params)); } } break; case T_MergeAppend: { ListCell *l; foreach(l, ((MergeAppend *) plan)->mergeplans) { context.paramids = bms_add_members(context.paramids, finalize_plan(root, (Plan *) lfirst(l), valid_params, scan_params)); } } break; case T_BitmapAnd: { ListCell *l; foreach(l, ((BitmapAnd *) plan)->bitmapplans) { context.paramids = bms_add_members(context.paramids, finalize_plan(root, (Plan *) lfirst(l), valid_params, scan_params)); } } break; case T_BitmapOr: { ListCell *l; foreach(l, ((BitmapOr *) plan)->bitmapplans) { context.paramids = bms_add_members(context.paramids, finalize_plan(root, (Plan *) lfirst(l), valid_params, scan_params)); } } break; case T_NestLoop: { ListCell *l; finalize_primnode((Node *) ((Join *) plan)->joinqual, &context); /* collect set of params that will be passed to right child */ foreach(l, ((NestLoop *) plan)->nestParams) { NestLoopParam *nlp = (NestLoopParam *) lfirst(l); nestloop_params = bms_add_member(nestloop_params, nlp->paramno); } } break; case T_MergeJoin: finalize_primnode((Node *) ((Join *) plan)->joinqual, &context); finalize_primnode((Node *) ((MergeJoin *) plan)->mergeclauses, &context); break; case T_HashJoin: finalize_primnode((Node *) ((Join *) plan)->joinqual, &context); finalize_primnode((Node *) ((HashJoin *) plan)->hashclauses, &context); break; case T_Limit: finalize_primnode(((Limit *) plan)->limitOffset, &context); finalize_primnode(((Limit *) plan)->limitCount, &context); break; case T_RecursiveUnion: /* child nodes are allowed to reference wtParam */ locally_added_param = ((RecursiveUnion *) plan)->wtParam; valid_params = bms_add_member(bms_copy(valid_params), locally_added_param); /* wtParam does *not* get added to scan_params */ break; case T_LockRows: /* Force descendant scan nodes to reference epqParam */ locally_added_param = ((LockRows *) plan)->epqParam; valid_params = bms_add_member(bms_copy(valid_params), locally_added_param); scan_params = bms_add_member(bms_copy(scan_params), locally_added_param); break; case T_WindowAgg: finalize_primnode(((WindowAgg *) plan)->startOffset, &context); finalize_primnode(((WindowAgg *) plan)->endOffset, &context); break; case T_Hash: case T_Agg: case T_Material: case T_Sort: case T_Unique: case T_SetOp: case T_Group: break; default: elog(ERROR, "unrecognized node type: %d", (int) nodeTag(plan)); } /* Process left and right child plans, if any */ child_params = finalize_plan(root, plan->lefttree, valid_params, scan_params); context.paramids = bms_add_members(context.paramids, child_params); if (nestloop_params) { /* right child can reference nestloop_params as well as valid_params */ child_params = finalize_plan(root, plan->righttree, bms_union(nestloop_params, valid_params), scan_params); /* ... and they don't count as parameters used at my level */ child_params = bms_difference(child_params, nestloop_params); bms_free(nestloop_params); } else { /* easy case */ child_params = finalize_plan(root, plan->righttree, valid_params, scan_params); } context.paramids = bms_add_members(context.paramids, child_params); /* * Any locally generated parameter doesn't count towards its generating * plan node's external dependencies. (Note: if we changed valid_params * and/or scan_params, we leak those bitmapsets; not worth the notational * trouble to clean them up.) */ if (locally_added_param >= 0) { context.paramids = bms_del_member(context.paramids, locally_added_param); } /* Now we have all the paramids */ if (!bms_is_subset(context.paramids, valid_params)) elog(ERROR, "plan should not reference subplan's variable"); /* * Note: by definition, extParam and allParam should have the same value * in any plan node that doesn't have child initPlans. We set them equal * here, and later SS_finalize_plan will update them properly in node(s) * that it attaches initPlans to. * * For speed at execution time, make sure extParam/allParam are actually * NULL if they are empty sets. */ if (bms_is_empty(context.paramids)) { plan->extParam = NULL; plan->allParam = NULL; } else { plan->extParam = context.paramids; plan->allParam = bms_copy(context.paramids); } return plan->allParam; } /* * finalize_primnode: add IDs of all PARAM_EXEC params appearing in the given * expression tree to the result set. */ static bool finalize_primnode(Node *node, finalize_primnode_context *context) { if (node == NULL) return false; if (IsA(node, Param)) { if (((Param *) node)->paramkind == PARAM_EXEC) { int paramid = ((Param *) node)->paramid; context->paramids = bms_add_member(context->paramids, paramid); } return false; /* no more to do here */ } if (IsA(node, SubPlan)) { SubPlan *subplan = (SubPlan *) node; Plan *plan = planner_subplan_get_plan(context->root, subplan); ListCell *lc; Bitmapset *subparamids; /* Recurse into the testexpr, but not into the Plan */ finalize_primnode(subplan->testexpr, context); /* * Remove any param IDs of output parameters of the subplan that were * referenced in the testexpr. These are not interesting for * parameter change signaling since we always re-evaluate the subplan. * Note that this wouldn't work too well if there might be uses of the * same param IDs elsewhere in the plan, but that can't happen because * generate_new_param never tries to merge params. */ foreach(lc, subplan->paramIds) { context->paramids = bms_del_member(context->paramids, lfirst_int(lc)); } /* Also examine args list */ finalize_primnode((Node *) subplan->args, context); /* * Add params needed by the subplan to paramids, but excluding those * we will pass down to it. */ subparamids = bms_copy(plan->extParam); foreach(lc, subplan->parParam) { subparamids = bms_del_member(subparamids, lfirst_int(lc)); } context->paramids = bms_join(context->paramids, subparamids); return false; /* no more to do here */ } return expression_tree_walker(node, reinterpret_cast<expression_tree_walker_fptr>(finalize_primnode), (void *) context); } /* * SS_make_initplan_from_plan - given a plan tree, make it an InitPlan * * The plan is expected to return a scalar value of the given type/collation. * We build an EXPR_SUBLINK SubPlan node and put it into the initplan * list for the current query level. A Param that represents the initplan's * output is returned. * * We assume the plan hasn't been put through SS_finalize_plan. */ Param * SS_make_initplan_from_plan(PlannerInfo *root, Plan *plan, Oid resulttype, int32 resulttypmod, Oid resultcollation) { SubPlan *node; Param *prm; /* * We must run SS_finalize_plan(), since that's normally done before a * subplan gets put into the initplan list. Tell it not to attach any * pre-existing initplans to this one, since they are siblings not * children of this initplan. (This is something else that could perhaps * be cleaner if we did extParam/allParam processing in setrefs.c instead * of here? See notes for materialize_finished_plan.) */ /* * Build extParam/allParam sets for plan nodes. */ SS_finalize_plan(root, plan, false); /* * Add the subplan and its PlannerInfo to the global lists. */ root->glob->subplans = lappend(root->glob->subplans, plan); root->glob->subroots = lappend(root->glob->subroots, root); /* * Create a SubPlan node and add it to the outer list of InitPlans. Note * it has to appear after any other InitPlans it might depend on (see * comments in ExecReScan). */ node = makeNode(SubPlan); node->subLinkType = EXPR_SUBLINK; get_first_col_type(plan, &node->firstColType, &node->firstColTypmod, &node->firstColCollation); node->plan_id = list_length(root->glob->subplans); root->init_plans = lappend(root->init_plans, node); /* * The node can't have any inputs (since it's an initplan), so the * parParam and args lists remain empty. */ cost_subplan(root, node, plan); /* * Make a Param that will be the subplan's output. */ prm = generate_new_param(root, resulttype, resulttypmod, resultcollation); node->setParam = list_make1_int(prm->paramid); /* Label the subplan for EXPLAIN purposes */ node->plan_name = psprintf("InitPlan %d (returns $%d)", node->plan_id, prm->paramid); return prm; }
31.300509
102
0.693995
[ "transform" ]
94c43169940239317774f9d1d1cf5b8b446da353
5,012
hxx
C++
main/sc/source/ui/inc/AccessibleDataPilotControl.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/sc/source/ui/inc/AccessibleDataPilotControl.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/sc/source/ui/inc/AccessibleDataPilotControl.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef _SC_ACCESSIBLEDATAPILOTCONTROL_HXX #define _SC_ACCESSIBLEDATAPILOTCONTROL_HXX #include "AccessibleContextBase.hxx" class ScPivotFieldWindow; class ScAccessibleDataPilotButton; class ScAccessibleDataPilotControl : public ScAccessibleContextBase { public: //===== internal ======================================================== ScAccessibleDataPilotControl( const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible>& rxParent, ScPivotFieldWindow* pFieldWindow); virtual void Init(); using ScAccessibleContextBase::disposing; virtual void SAL_CALL disposing(); void AddField(sal_Int32 nNewIndex); void RemoveField(sal_Int32 nOldIndex); void FieldFocusChange(sal_Int32 nOldIndex, sal_Int32 nNewIndex); void FieldNameChange(sal_Int32 nIndex); void GotFocus(); void LostFocus(); protected: virtual ~ScAccessibleDataPilotControl(void); public: ///===== XAccessibleComponent ============================================ virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleAtPoint( const ::com::sun::star::awt::Point& rPoint ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isVisible( ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL grabFocus( ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getForeground( ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getBackground( ) throw (::com::sun::star::uno::RuntimeException); ///===== XAccessibleContext ============================================== /// Return the number of currently visible children. virtual sal_Int32 SAL_CALL getAccessibleChildCount(void) throw (::com::sun::star::uno::RuntimeException); /// Return the specified child or NULL if index is invalid. virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> SAL_CALL getAccessibleChild(sal_Int32 nIndex) throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::lang::IndexOutOfBoundsException); /// Return the set of current states. virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleStateSet> SAL_CALL getAccessibleStateSet(void) throw (::com::sun::star::uno::RuntimeException); ///===== XServiceInfo ==================================================== /** Returns an identifier for the implementation of this object. */ virtual ::rtl::OUString SAL_CALL getImplementationName(void) throw (::com::sun::star::uno::RuntimeException); ///===== XTypeProvider =================================================== /** Returns a implementation id. */ virtual ::com::sun::star::uno::Sequence<sal_Int8> SAL_CALL getImplementationId(void) throw (::com::sun::star::uno::RuntimeException); protected: /// Return this object's description. virtual ::rtl::OUString SAL_CALL createAccessibleDescription(void) throw (::com::sun::star::uno::RuntimeException); /// Return the object's current name. virtual ::rtl::OUString SAL_CALL createAccessibleName(void) throw (::com::sun::star::uno::RuntimeException); /// Return the object's current bounding box relative to the desktop. virtual Rectangle GetBoundingBoxOnScreen(void) const throw (::com::sun::star::uno::RuntimeException); /// Return the object's current bounding box relative to the parent object. virtual Rectangle GetBoundingBox(void) const throw (::com::sun::star::uno::RuntimeException); private: ScPivotFieldWindow* mpFieldWindow; struct AccessibleWeak { ::com::sun::star::uno::WeakReference< ::com::sun::star::accessibility::XAccessible > xWeakAcc; ScAccessibleDataPilotButton* pAcc; AccessibleWeak() : pAcc(NULL) {} }; ::std::vector< AccessibleWeak > maChildren; }; #endif
35.295775
102
0.652833
[ "object", "vector" ]
94c77ae8983f1a9c9118373b67bee9c731cc253a
5,781
cpp
C++
day23-2/day23-2.cpp
throx/advent2021
2295a65e14a8defacd3e83229985c97134c21501
[ "Unlicense" ]
1
2021-12-05T14:19:59.000Z
2021-12-05T14:19:59.000Z
day23-2/day23-2.cpp
throx/advent2021
2295a65e14a8defacd3e83229985c97134c21501
[ "Unlicense" ]
null
null
null
day23-2/day23-2.cpp
throx/advent2021
2295a65e14a8defacd3e83229985c97134c21501
[ "Unlicense" ]
null
null
null
#include <iostream> #include <string> #include <vector> #include <set> #include <map> #include <cassert> #include "../shared/Point.h" using namespace std; int COST[] = { 1, 10, 100, 1000 }; //char STATE[] = "BDDACCBDBBACDACA"; char STATE[] = "BDDBACBCABADDACC"; // Part2 //############# //#ab.c.d.e.fg# //###h#l#p#t### // #i#m#q#u# // #j#n#r#v# // #k#o#s#w# // ######### // Insert: // #D#C#B#A# // #D#B#A#C# typedef char Vertex; struct Edge { Vertex v1; Vertex v2; set<Vertex> blocks; int dist; }; typedef vector<Edge> Edges; typedef map<Vertex, Edges> World; typedef char Amphi; typedef map<Vertex, Amphi> State; typedef map<pair<Vertex, Vertex>, int> Dists; static World world; static Dists dists; Amphi Goal(Vertex v) { if (v < 'h') return 0; return 'A' + (v - 'h') / 4; } vector<Vertex> OtherGoal(Vertex v) { if (v < 'h') return {}; vector<Vertex> ret; ret.push_back('h' + ((v - 'h') ^ 1)); ret.push_back('h' + ((v - 'h') ^ 2)); ret.push_back('h' + ((v - 'h') ^ 3)); return ret; } void MakeWorld() { // From hallway to first spots world['a'] = { {'a', 'h', {'b'}, 3 }, {'a', 'l', {'b', 'c'}, 5}, {'a', 'p', {'b', 'c', 'd'}, 7}, {'a', 't', {'b', 'c', 'd', 'e'}, 9}, }; world['b'] = { {'b', 'h', {}, 2}, {'b', 'l', {'c'}, 4}, {'b', 'p', {'c', 'd'}, 6}, {'b', 't', {'c', 'd', 'e'}, 8}, }; world['c'] = { {'c', 'h', {}, 2}, {'c', 'l', {}, 2}, {'c', 'p', {'d'}, 4}, {'c', 't', {'d', 'e'}, 6}, }; world['d'] = { {'d', 'h', {'c'}, 4}, {'d', 'l', {}, 2}, {'d', 'p', {}, 2}, {'d', 't', {'e'}, 4}, }; world['e'] = { {'e', 'h', {'c', 'd'}, 6}, {'e', 'l', {'d'}, 4}, {'e', 'p', {}, 2}, {'e', 't', {}, 2}, }; world['f'] = { {'f', 'h', {'c', 'd', 'e'}, 8}, {'f', 'l', {'d', 'e'}, 6}, {'f', 'p', {'e'}, 4}, {'f', 't', {}, 2}, }; world['g'] = { {'g', 'h', {'c', 'd', 'e', 'f'}, 9}, {'g', 'l', {'d', 'e', 'f'}, 7}, {'g', 'p', {'e', 'f'}, 5}, {'g', 't', {'f'}, 3}, }; // From hall to other spots for (char c = 'a'; c != 'h'; ++c) { Edges es = world[c]; for (Edge e : es) { for (int i = 0; i < 3; ++i) { e.blocks.insert(e.v2); ++e.v2; ++e.dist; world[c].push_back(e); } } } // To hallway for (char c = 'a'; c != 'h'; ++c) { for (auto& e : world[c]) { world[e.v2].push_back({ e.v2, e.v1, e.blocks, e.dist }); } } // Construct dists for (auto& kv : world) { for (auto& e : kv.second) { dists[{e.v1, e.v2}] = e.dist; } } } State MakeState() { State s; for (char c = 'h'; c <= 'w'; ++c) { s.insert({ c, STATE[c - 'h'] }); } return s; } State MakeGoal() { State s; for (char c = 'h'; c <= 'w'; ++c) { s.insert({ c, Goal(c) }); } return s; } set<Vertex> GetOpen(const State& state, const Vertex& from) { set<Vertex> to; assert(state.find(from) != state.end()); Amphi us = state.find(from)->second; for (auto& e : world[from]) { // Dest is clear if (state.find(e.v2) == state.end()) { // Nothing in the way bool blocked = false; for (auto& b : e.blocks) { if (state.find(b) != state.end()) { blocked = true; break; } } if (!blocked) { // Can only move to our own goal, or hallway if (Goal(e.v2) == 0) { to.insert(e.v2); } else if (Goal(e.v2) == us) { // Can only move to our own goal if it's empty or // occupied by another of us // TODO: Optimisation? Only makes sense to move to bottom of goal? assert(OtherGoal(e.v2).size() > 0); bool goalok = true; for (auto& og : OtherGoal(e.v2)) { auto it = state.find(og); if (it != state.end() && it->second != us) { goalok = false; break; } } if (goalok) { to.insert(e.v2); } } } } } return to; } int main() { MakeWorld(); State goal = MakeGoal(); multimap<int, State> open; set<State> closed; open.insert({ 0, MakeState() }); int bestcost = 0; while (!open.empty()) { int cost = open.begin()->first; State state = open.begin()->second; open.erase(open.begin()); if (state == goal) { bestcost = cost; break; } if (closed.find(state) != closed.end()) { continue; } closed.insert(state); if (closed.size() % 10000 == 0) cout << closed.size() << ": " << cost << endl; for (auto& kv : state) { auto tos = GetOpen(state, kv.first); for (auto& to : tos) { State newstate = state; newstate.erase(kv.first); newstate.insert({ to, kv.second }); int newcost = cost + dists[{kv.first, to}] * COST[kv.second - 'A']; assert(newcost > cost); open.insert({ newcost, newstate }); } } } cout << "Part 2 Best Cost: " << bestcost << endl; }
23.216867
86
0.383671
[ "vector" ]
94ca67cd232939c086cf7f576ebc1d5903736486
6,235
cpp
C++
jni/application/bootstrap.cpp
garoose/eecs494.p2
fc86f50a9ba77f4b653b3b3cd6e6c61aa2e1ca27
[ "MIT" ]
null
null
null
jni/application/bootstrap.cpp
garoose/eecs494.p2
fc86f50a9ba77f4b653b3b3cd6e6c61aa2e1ca27
[ "MIT" ]
null
null
null
jni/application/bootstrap.cpp
garoose/eecs494.p2
fc86f50a9ba77f4b653b3b3cd6e6c61aa2e1ca27
[ "MIT" ]
null
null
null
/* This file is part of the Zenipex Library (zenilib). * Copyleft (C) 2011 Mitchell Keith Bloch (bazald). * * This source file is simply under the public domain. */ #include <zenilib.h> #include <string> #include "Buggy.h" #include "Map.h" #include "Score.h" #if defined(_DEBUG) && defined(_WINDOWS) #define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__) #define new DEBUG_NEW #endif using namespace std; using namespace Zeni; std::string test; class Play_State : public Gamestate_Base { Play_State(const Play_State &); Play_State operator=(const Play_State &); public: Play_State() : game_resolution(1280.0f, 768.0f), top_left(-256.0f, 0.0f), map1("maps/map1.txt"), map_scroll_speed(0.0f), m_time_passed(0.0f), m_max_time_step(1.0f / 20.0f), // make the largest physics step 1/20 of a second m_max_time_steps(10.0f), // allow no more than 10 physics steps per frame // position, size, theta, speed, min_speed, max_speed, acceleration m_buggy(Point2f(50.0f, 300.0f), Vector2f(256.0f, 128.0f), 0, 110.0f, 20.0f, 300.0f, 90.0f, &m_score) { // If our game has no real time component in real life, allow the user to pause the game. // This would be a BAD idea in a networked multiplayer mode for a game. // (Or at the very least, this would be the wrong way to do it.) set_pausable(true); m_score.reset(); show_cboxes = false; } private: Vector2f game_resolution; Point2f top_left; Map map1; float map_scroll_speed; Buggy m_buggy; Score m_score; bool show_cboxes; void on_push() { //get_Window().mouse_grab(true); get_Window().mouse_hide(true); //get_Game().joy_mouse.enabled = false; m_chrono.start(); get_Sound().play_BGM(); } void on_pop() { m_chrono.stop(); get_Sound().stop_BGM(); //get_Window().mouse_grab(false); get_Window().mouse_hide(false); //get_Game().joy_mouse.enabled = true; } Zeni::Time m_current_time; Chronometer<Time> m_chrono; float m_time_passed; float m_max_time_step; //< Optional float m_max_time_steps; //< Optional void Play_State::on_key(const SDL_KeyboardEvent &event) { switch (event.keysym.sym) { case SDLK_F1: if (event.type == SDL_KEYDOWN) show_cboxes = !show_cboxes; break; } m_buggy.on_key(event); Gamestate_Base::on_key(event); } void adjust_map_scroll() { //TODO: speed up map scroll when buggy gets to certain point float distance = (m_buggy.get_position().x + m_buggy.get_size().x) - (top_left.x + game_resolution.x / 4); map_scroll_speed = distance; if (distance < 0) map_scroll_speed *= 6; } void perform_logic() { // Update time_passed const float time_passed = m_chrono.seconds(); float time_step = time_passed - m_time_passed; m_time_passed = time_passed; /* Shrink time passed to an upper bound * * If your program is ever paused by your computer for 10 * minutes and then allowed to continue running, you don't want * it to pause at the physics loop for another 10 minutes. */ if (time_step / m_max_time_step > m_max_time_steps) time_step = m_max_time_steps * m_max_time_step; while (time_step > m_max_time_step) { m_buggy.step(time_step, &map1); adjust_map_scroll(); map1.step_all(time_step, game_resolution, top_left); top_left.x += map_scroll_speed * time_step; time_step -= m_max_time_step; } m_buggy.step(time_step, &map1); adjust_map_scroll(); map1.step_all(time_step, game_resolution, top_left); top_left.x += map_scroll_speed * time_step; time_step = 0.0f; } void Play_State::render_bg() { map1.render_all(game_resolution, top_left, &m_buggy, show_cboxes); } void Play_State::render() { Video &vr = get_Video(); vr.set_2d(make_pair(top_left, game_resolution + top_left)); render_bg(); m_buggy.render(); if (show_cboxes) m_buggy.render_collisions(&map1); m_score.render(top_left); //For debugging /*Zeni::Font &fr = get_Fonts()["title"]; fr.render_text( test.c_str(), Point2f(top_left.x + 100.0f + 0.5f * fr.get_text_width(test.c_str()), top_left.y + 400.0f - 0.5f * fr.get_text_height()), get_Colors()["title_text"], ZENI_CENTER);*/ } }; class Instructions_State : public Widget_Gamestate { Instructions_State(const Instructions_State &); Instructions_State operator=(const Instructions_State &); public: Instructions_State() : Widget_Gamestate(make_pair(Point2f(0.0f, 0.0f), Point2f(800.0f, 600.0f))) { } private: void on_key(const SDL_KeyboardEvent &event) { if (event.keysym.sym == SDLK_ESCAPE && event.state == SDL_PRESSED) get_Game().pop_state(); } void render() { Widget_Gamestate::render(); Zeni::Font &fr = get_Fonts()["system_36_x600"]; Zeni::Font &frt = get_Fonts()["title_small"]; fr.render_text( "Use the left and right arrows or A and D\n to adjust the Buggy's speed\n\n" "Press the up arrow or W to jump\n\n" "Avoid crashing the buggy or being hit by asteroids!\n\n" "Press " #if defined(_WINDOWS) "ALT+F4" #elif defined(_MACOSX) "Apple+Q" #else "Ctrl+Q" #endif " to Quit\n\n\n\n\n\n" "(F1 - show collision boxes, F2 - toggle buggy explosions)", Point2f(400.0f, 100.0f - 0.5f * fr.get_text_height()), get_Colors()["red"], ZENI_CENTER); frt.render_text("Press escape to return\nto the main menu", Point2f(400.0f, 400.0f - 0.05f * fr.get_text_height()), get_Colors()["title_text"], ZENI_CENTER); } }; class Bootstrap { class Gamestate_One_Initializer : public Gamestate_Zero_Initializer { virtual Gamestate_Base * operator()() { Window::set_title("zenilib Mars Buggy"); get_Joysticks(); get_Video(); get_Textures(); get_Fonts(); get_Sounds(); get_Game().joy_mouse.enabled = true; get_Sound().set_BGM("sfx/intro1.2"); get_Sound().set_BGM_looping(true); //get_Sound().play_BGM(); return new Title_State<Play_State, Instructions_State>("Zenipex Library\nMars Patrol"); } } m_goi; public: Bootstrap() { g_gzi = &m_goi; } } g_bootstrap; int main(int argc, char **argv) { return zenilib_main(argc, argv); }
25.345528
125
0.676183
[ "render" ]
94d4f232efab09f7671ba470b0e87f9f28ff1656
4,235
cpp
C++
Cpp14/Strou/ctor_17/class_object_initialization_main.cpp
ernestyalumni/HrdwCCppCUDA
17ed937dea06431a4d5ca103f993ea69a6918734
[ "MIT" ]
1
2018-02-09T19:44:51.000Z
2018-02-09T19:44:51.000Z
Cpp14/Strou/ctor_17/class_object_initialization_main.cpp
ernestyalumni/HrdwCCppCUDA
17ed937dea06431a4d5ca103f993ea69a6918734
[ "MIT" ]
null
null
null
Cpp14/Strou/ctor_17/class_object_initialization_main.cpp
ernestyalumni/HrdwCCppCUDA
17ed937dea06431a4d5ca103f993ea69a6918734
[ "MIT" ]
null
null
null
//------------------------------------------------------------------------------ /// \file class_object_initialization_main.cpp /// \author Ernest Yeung /// \email ernestyalumni@gmail.com /// \brief Main driver file for class object initialization examples.. /// \ref Ch. 17 Constructors; Bjarne Stroustrup, 17.3 Class Object /// Initialization. The C++ Programming Language, 4th Ed., Stroustrup; /// \details Initialize objects of a class with and without ctors. /// \copyright If you find this code useful, feel free to donate directly and /// easily at this direct PayPal link: /// /// https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=ernestsaveschristmas%2bpaypal%40gmail%2ecom&lc=US&item_name=ernestyalumni&currency_code=USD&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted /// /// which won't go through a 3rd. party such as indiegogo, kickstarter, patreon. /// Otherwise, I receive emails and messages on how all my (free) material on /// physics, math, and engineering have helped students with their studies, and /// I know what it's like to not have money as a student, but love physics (or /// math, sciences, etc.), so I am committed to keeping all my material /// open-source and free, whether or not sufficiently crowdfunded, under the /// open-source MIT license: feel free to copy, edit, paste, make your own /// versions, share, use as you wish. /// Peace out, never give up! -EY //------------------------------------------------------------------------------ /// COMPILATION TIPS: /// g++ -std=c++14 class_object_initialization_main.cpp -o class_object_initialization_main //------------------------------------------------------------------------------ #include <iostream> #include <netinet/in.h> // ::sockaddr_in #include <netinet/ip.h> // superset of previous #include <string> /// \details We can initialize objects of a class for which we haven't defined /// ctor using /// * memberwise initialization /// * copy initialization, or /// * default initialization (without an initializer or with an empty /// initializer list) struct Work { std::string author; std::string name; int year; }; struct SocketAddressInContainer { ::sockaddr_in SocketAddressIn; }; struct Buf { int count; char buf[16*1024]; }; void f() { Buf buf1; // leave elements uninitialized Buf buf2 {}; // I really want to zero out those elements int* p1 = new int; // *p1 is uninitialized int* p2 = new int{}; // *p2 ==0 int* p3 = new int{7}; // *p3 == 7 } /// \details If a ctor is declared for a class, some ctor will be used for /// every object. It's an error to try to create an object without a proper /// initializer as required by the ctors. /// /// References and consts must be initialized (Sec. 7.7, Sec. 7.5). Therefore, /// a class containing such members can't be default constructed unless the /// programmer supplies in-class member initializers (Sec. 17.4.4), or defines /// a default ctor that initializes them (Sec. 17.4.1) int glob {9}; struct X { const int a1 {7}; // OK const int& r {9}; // OK int& r1 {glob}; // OK }; int main() { /// \ref 17.3.1. Initialization Without Constructors, Stroustrup. /// \details We can't define a ctor for a built-in type, yet we can /// initialize it with a value of suitable type int a {1}; char* p {nullptr}; Work s9 {"Beethoven", "Symphony No. 9 in D minor, Op. 125; Choral", 1824}; // memberwise initialization Work currently_playing {s9}; // copy initialization Work none {}; // default initialization SocketAddressInContainer socket_address_in_container; SocketAddressInContainer socket_address_in_container1 { 8, // unsigned short = uint8_t 808, // unsigned short = sa_family_t 42, // struct in_addr = unsigned long = in_port_t {0, 1, 0, 1, 1, 1, 0, 0} // char [8] }; // Where no ctor requiring arguments is declared, it's also possible to // leave out the initializer completely. Work alpha; Buf buf0; // statically allocated, so initialized by default. f(); // X x2 {2}; // OK // X x3 {x2}; // OK : a copy ctor is implicitly defined (Sec. 17.6) X x {}; std::cout << " x : " << x.a1 << ' ' << x.r << ' ' << x.r1 << '\n'; }
33.346457
214
0.649351
[ "object" ]
94d54ec12d52fc52b42339c3833cb7a170da57dc
3,335
cpp
C++
src/Plugins/OpenGL/Shader/GLShader.cpp
MemoryDealer/LORE
2ce0c6cf03c119e5d1b0b90f3ee044901353283a
[ "MIT" ]
2
2021-07-14T06:05:48.000Z
2021-07-14T18:07:18.000Z
src/Plugins/OpenGL/Shader/GLShader.cpp
MemoryDealer/LORE
2ce0c6cf03c119e5d1b0b90f3ee044901353283a
[ "MIT" ]
null
null
null
src/Plugins/OpenGL/Shader/GLShader.cpp
MemoryDealer/LORE
2ce0c6cf03c119e5d1b0b90f3ee044901353283a
[ "MIT" ]
null
null
null
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // // The MIT License (MIT) // This source file is part of LORE // ( Lightweight Object-oriented Rendering Engine ) // // Copyright (c) 2017-2021 Jordan Sparks // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files ( the "Software" ), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and / or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions : // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // #include "GLShader.h" // ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // using namespace Lore::OpenGL; // ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // GLShader::GLShader() : _shader( 0 ) { } // ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // GLShader::~GLShader() { unload(); } // ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // void GLShader::init( const Shader::Type& type ) { _type = type; GLenum shaderType = 0; switch ( type ) { default: LogWrite( Error, "Unknown shader type requested for Shader %s", _name.c_str() ); return; case Shader::Type::Vertex: shaderType = GL_VERTEX_SHADER; break; case Shader::Type::Geometry: shaderType = GL_GEOMETRY_SHADER; break; case Shader::Type::Fragment: shaderType = GL_FRAGMENT_SHADER; break; } _shader = glCreateShader( shaderType ); } // ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // bool GLShader::loadFromFile( const string& file ) { return false; } // ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // bool GLShader::loadFromSource( const string& source ) { const char* psrc = source.c_str(); glShaderSource( _shader, 1, &psrc, nullptr ); glCompileShader( _shader ); GLint success = 0; GLchar buf[512]; glGetShaderiv( _shader, GL_COMPILE_STATUS, &success ); if ( !success ) { glGetShaderInfoLog( _shader, sizeof( buf ), nullptr, buf ); LogWrite( Error, "Failed to load and compile shader %s: %s", _name.c_str(), buf ); return false; } _loaded = true; return true; } // ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // void GLShader::unload() { glDeleteShader( _shader ); _loaded = false; } // ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
29.254386
86
0.537331
[ "geometry", "object" ]
94dd0ef94e363d5f3553b82479cbe7b7379c88dd
6,224
hpp
C++
examples/include/base.hpp
mshiryaev/oneccl
fb4bd69b0bfa72f0ed16ac2328205e51cf12d4aa
[ "Apache-2.0" ]
null
null
null
examples/include/base.hpp
mshiryaev/oneccl
fb4bd69b0bfa72f0ed16ac2328205e51cf12d4aa
[ "Apache-2.0" ]
null
null
null
examples/include/base.hpp
mshiryaev/oneccl
fb4bd69b0bfa72f0ed16ac2328205e51cf12d4aa
[ "Apache-2.0" ]
null
null
null
/* Copyright 2016-2019 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef BASE_HPP #define BASE_HPP #include "ccl.hpp" #include <chrono> #include <cstring> #include <functional> #include <math.h> #include <stdexcept> #include <stdio.h> #include <sys/time.h> #include <vector> #ifdef CCL_ENABLE_SYCL #include <CL/sycl.hpp> using namespace cl::sycl; using namespace cl::sycl::access; #endif #define DEFAULT_BACKEND "cpu" #define ITERS (16) #define COLL_ROOT (0) #define MSG_SIZE_COUNT (6) #define START_MSG_SIZE_POWER (10) #define PRINT(fmt, ...) \ printf(fmt"\n", ##__VA_ARGS__); \ #define PRINT_BY_ROOT(fmt, ...) \ if (comm->rank() == 0) \ { \ printf(fmt"\n", ##__VA_ARGS__); \ } #define ASSERT(cond, fmt, ...) \ do \ { \ if (!(cond)) \ { \ printf("FAILED\n"); \ fprintf(stderr, "ASSERT '%s' FAILED " fmt "\n", \ #cond, ##__VA_ARGS__); \ throw std::runtime_error("ASSERT FAILED"); \ } \ } while (0) #define MSG_LOOP(per_msg_code) \ do \ { \ PRINT_BY_ROOT("iters=%d, msg_size_count=%d, " \ "start_msg_size_power=%d, coll_root=%d", \ ITERS, MSG_SIZE_COUNT, \ START_MSG_SIZE_POWER, COLL_ROOT); \ std::vector<size_t> msg_counts(MSG_SIZE_COUNT); \ std::vector<std::string> msg_match_ids(MSG_SIZE_COUNT); \ for (size_t idx = 0; idx < MSG_SIZE_COUNT; ++idx) \ { \ msg_counts[idx] = 1u << (START_MSG_SIZE_POWER + idx); \ msg_match_ids[idx] = std::to_string(msg_counts[idx]); \ } \ try \ { \ for (size_t idx = 0; idx < MSG_SIZE_COUNT; ++idx) \ { \ size_t msg_count = msg_counts[idx]; \ coll_attr.match_id = msg_match_ids[idx].c_str(); \ PRINT_BY_ROOT("msg_count=%zu, match_id=%s", \ msg_count, coll_attr.match_id); \ per_msg_code; \ } \ } \ catch (ccl::ccl_error& e) \ { \ printf("FAILED\n"); \ fprintf(stderr, "ccl exception:\n%s\n", e.what()); \ } \ catch (...) \ { \ printf("FAILED\n"); \ fprintf(stderr, "other exception\n"); \ } \ PRINT_BY_ROOT("PASSED"); \ } while (0) double when(void) { struct timeval tv; static struct timeval tv_base; static int is_first = 1; if (gettimeofday(&tv, NULL)) { perror("gettimeofday"); return 0; } if (is_first) { tv_base = tv; is_first = 0; } return (double)(tv.tv_sec - tv_base.tv_sec) * 1.0e6 + (double)(tv.tv_usec - tv_base.tv_usec); } void print_timings(ccl::communicator& comm, double* timer, size_t elem_count, size_t elem_size, size_t buf_count, size_t rank, size_t size) { double* timers = (double*)malloc(size * sizeof(double)); size_t* recv_counts = (size_t*)malloc(size * sizeof(size_t)); size_t idx; for (idx = 0; idx < size; idx++) recv_counts[idx] = 1; ccl::coll_attr attr; memset(&attr, 0, sizeof(ccl_coll_attr_t)); comm.allgatherv(timer, 1, timers, recv_counts, &attr, nullptr)->wait(); if (rank == 0) { double avg_timer = 0; double avg_timer_per_buf = 0; for (idx = 0; idx < size; idx++) { avg_timer += timers[idx]; } avg_timer /= (ITERS * size); avg_timer_per_buf = avg_timer / buf_count; double stddev_timer = 0; double sum = 0; for (idx = 0; idx < size; idx++) { double val = timers[idx] / ITERS; sum += (val - avg_timer) * (val - avg_timer); } stddev_timer = sqrt(sum / size) / avg_timer * 100; printf("size %10zu x %5zu bytes, avg %10.2lf us, avg_per_buf %10.2f, stddev %5.1lf %%\n", elem_count * elem_size, buf_count, avg_timer, avg_timer_per_buf, stddev_timer); } comm.barrier(); free(timers); free(recv_counts); } #endif /* BASE_HPP */
35.976879
97
0.424325
[ "vector" ]
94e3ace4a3da98d53397f0f75620bc216082fb6b
1,399
cpp
C++
atl/codes/Graph/edmond.cpp
rknguyen/teamnote
52c47eefee432e66695473b50ad03554510e336c
[ "MIT" ]
null
null
null
atl/codes/Graph/edmond.cpp
rknguyen/teamnote
52c47eefee432e66695473b50ad03554510e336c
[ "MIT" ]
null
null
null
atl/codes/Graph/edmond.cpp
rknguyen/teamnote
52c47eefee432e66695473b50ad03554510e336c
[ "MIT" ]
null
null
null
struct Edge { int u, v, cap, flow; }; const int N = 1007; vector <Edge> E; vector <int> adj[N]; int n, m, s, t, trace[N]; void addEdge(int u, int v, int cap) { E.push_back(Edge({ v, u, 0, 0 })); E.push_back(Edge({ u, v, cap, 0 })); adj[u].push_back(E.size() - 1); adj[v].push_back(E.size() - 2); } int Edmonds_Karp(int s, int t) { fill(trace, trace + n, 0); int maxFlow = 0; do { fill(trace, trace + n + 1, 0); queue <int> q; q.push(s); while (!q.empty()) { int u = q.front(); q.pop(); for (int eid : adj[u]) { Edge ed = E[eid]; int v = ed.v, c = ed.cap, f = ed.flow; if (!trace[v] && v != f && c > f) { trace[v] = eid + 1; q.push(v); } } } if (trace[t]) { int v = t, delta = (int) 1e9 + 7; while (v != s) { int eid = trace[v] - 1; delta = min(delta, E[eid].cap - E[eid].flow); v = E[eid].u; } v = t; while (v != s) { int eid = trace[v] - 1; E[eid].flow += delta; E[eid - 1].flow -= delta; v = E[eid].u; } maxFlow += delta; } } while(trace[t]); return maxFlow; }
26.903846
61
0.373838
[ "vector" ]
94e890677db5ec21e4133d50d7a03099266b32c8
2,899
cpp
C++
CodeForces/Miscellaneous/762/usb_ps2.cpp
Alecs-Li/Competitive-Programming
39941ff8e2c8994abbae8c96a1ed0a04b10058b8
[ "MIT" ]
1
2021-07-06T02:14:03.000Z
2021-07-06T02:14:03.000Z
CodeForces/Miscellaneous/762/usb_ps2.cpp
Alex01890-creator/competitive-programming
39941ff8e2c8994abbae8c96a1ed0a04b10058b8
[ "MIT" ]
null
null
null
CodeForces/Miscellaneous/762/usb_ps2.cpp
Alex01890-creator/competitive-programming
39941ff8e2c8994abbae8c96a1ed0a04b10058b8
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <tuple> #include <algorithm> #include <string> #include <set> #include <queue> #include <map> #include <cmath> using namespace std; typedef long double ld; typedef long long ll; typedef pair<int, int> pi; typedef pair<ll,ll> pll; typedef pair<char, char> pc; typedef pair<string, string> ps; typedef tuple<int, int, int> ti; typedef tuple<ll, ll, ll> tll; typedef tuple<string, string, string> ts; typedef tuple<char, char, char> tc; typedef vector<int> vi; typedef vector<string> vs; typedef vector<ll> vll; typedef vector<pi> vpi; typedef vector<ps> vps; typedef vector<pll> vpll; typedef vector<ti> vti; typedef vector<bool> vb; typedef vector<ts> vts; typedef multiset<int> msi; typedef multiset<ll> msll; typedef multiset<string> mss; typedef multiset<char> mc; typedef queue<char> qc; typedef queue<int> qi; typedef queue<ll> qll; typedef queue<string> qs; typedef set<int> si; typedef set<ll> sll; typedef set<string> ss; typedef set<char> sc; #define FORd(i,a,b) for (int i = (b)-1; i >= a; i--) #define FOR(a, b, c) for (int a=(b); a<(c); a++) #define F0R(i, a) for (int i=0; i<(a); i++) #define F1R(i, a) for (int i=1; i<(a); i++) #define mp make_pair #define mt make_tuple #define pb push_back #define popb pop_back #define f first #define sec second #define ub upper_bound #define lb lower_bound #define beg begin #define all(x) x.begin(), x.end() #define sz(x) (int)(x).size() void solve(){ ll x, y, z, n; cin >> x >> y >> z >> n; priority_queue<ll, vi, greater<ll>> p1; priority_queue<ll, vi, greater<ll>> p2; F0R(a, n){ ll b; string s; cin >> b >> s; if(s == "USB"){ p1.push(b); } else { p2.push(b); } } ll count = 0, count2 = 0; ll ans1 = 0, ans2 = 0; while(count < x){ if(!p1.empty()){ ans1 += p1.top(); p1.pop(); count++; } else { break; } } while(count2 < y){ if(!p2.empty()){ count2++; ans1 += p2.top(); p2.pop(); } else { break; } } ll count3 = 0; ll ans3 = 0; while(count3 < z){ if(!p1.empty() && !p2.empty()){ if(p1.top() > p2.top()){ ans2 += p2.top(); p2.pop(); count3++; } else { ans1 += p1.top(); p1.pop(); count3++; } } else if(!p2.empty()){ ans2 += p2.top(); p2.pop(); count3++; } else if(!p1.empty()){ ans1 += p1.top(); p1.pop(); count3++; } else { break; } } cout << count + count2 + count3 << " " << ans1 + ans2; } int main(){ int t = 1; //cin >> t; while(t--){ solve(); } }
22.826772
58
0.51742
[ "vector" ]
94eb5533d3ef837ac191391fab989ab9ff9dd820
4,813
cc
C++
src/problem.cc
russellw/Ayane
8109f9f134053fa1ededd2a4ff54da050291244e
[ "MIT" ]
null
null
null
src/problem.cc
russellw/Ayane
8109f9f134053fa1ededd2a4ff54da050291244e
[ "MIT" ]
null
null
null
src/problem.cc
russellw/Ayane
8109f9f134053fa1ededd2a4ff54da050291244e
[ "MIT" ]
2
2015-04-14T12:44:58.000Z
2019-09-02T15:37:24.000Z
#include "main.h" template <class T> T* alloc(uint32_t& o) { o = heap->alloc(sizeof(T)); return (T*)heap->ptr(o); } void Problem::axiom(term a, const char* file, const char* name) { // Check where to put a formula object corresponding to this term. auto& o = initialFormulas.gadd(a); // If we have already recorded an identical formula, return. if (o) return; // Placing an object at an address aligned only to 4 bytes, but some fields of the object are pointers, which are typically 8 // bytes. Depending on CPU, this may incur a slight slowdown accessing those fields. That's fine, because they are rarely // accessed. If we ever need to run on a CPU where it's more than a slight slowdown, it might be necessary to look for another // solution. auto f = alloc<InputFormula>(o); new (f) InputFormula(FormulaClass::Axiom, a, file, name); } void Problem::conjecture(term a, const char* file, const char* name) { // If multiple conjectures occur in a problem, there are two possible interpretations (conjunction or disjunction), and no // consensus on which is correct, so rather than risk silently giving a wrong answer, reject the problem as ambiguous and // require it to be restated with the conjectures folded into one, using explicit conjunction or disjunction. if (hasConjecture) err("Multiple conjectures not supported"); hasConjecture = 1; // The formula actually added to the set whose satisfiability is to be tested, is the negated conjecture. auto b = term(tag::Not, a); // Check where to put a formula object corresponding to this term. auto& o = initialFormulas.gadd(b); // If we have already recorded an identical formula, return. if (o) return; // Make a formula object for the conjecture. This will not be added to the set of clauses, only used as the source of the // negated conjecture. uint32_t conp; auto conf = alloc<InputFormula>(conp); new (conf) InputFormula(FormulaClass::Conjecture, a, file, name); // Make and place the formula for the negated conjecture. auto f = alloc<NegatedFormula>(o); new (f) NegatedFormula(b, conp); } size_t Problem::walk(term a) { auto& o = visitedFormulas.gadd(a); if (o) return o; // Check this term against the initial formulas. uint32_t i; if (initialFormulas.get(a, i)) { // This is one of the initial formulas, so already has a formula object; we don't need to make one. auto f = (AbstractFormula*)heap->ptr(i); // But if it is the negated conjecture, we do need to add the conjecture before it, to the list of formulas to print out in // the proof. if (f->Class == FormulaClass::Negation) proofv.push_back(((NegatedFormula*)f)->from); } else { // Not one of the initial formulas, so it must be a definition introduced during CNF conversion. Make a formula object for // it. (Some definitions may not be involved in the proof. By waiting to make formula objects until they are definitely // needed, we can entirely avoid doing it for those definitions.) auto f = alloc<Formula>(i); new (f) Formula(FormulaClass::Definition, a); } // Remember that we already visited this formula, in case it is referred to multiple times in the proof. o = i; // Add it to the list of formulas to be printed out. proofv.push_back(i); // And return a reference to the object. return i; } size_t Problem::walk(const ProofCnf& proofCnf, const Proof& proof, const clause& c) { auto& o = visitedcs.gadd(c); if (o) return o; // Allocate an object representing this clause, and also remember that we already visited it. auto f = alloc<Clause>(o); // Need to be careful here: We have a pointer to the allocated object, in the 32-bit offset format we will need to return, and // it would be easy to just return it at the end of the function. But it is actually currently being held by reference, and may // become invalid if recursive calls result in more clauses being added to the map, triggering a reallocation, so make a copy of // it by value. auto r = o; // Now we need to check where it came from. rule rl; term a; size_t from; size_t from1 = 0; if (proofCnf.get(c, a)) { // The clause was CNF-converted from a formula. rl = rule::cnf; from = walk(a); } else { // Otherwise, it must have been inferred from other clauses. auto& derivation = proof.at(c); rl = derivation.first; from = walk(proofCnf, proof, derivation.second[0]); if (derivation.second.size() == 2) from1 = walk(proofCnf, proof, derivation.second[1]); } // Fill in the allocated object. new (f) Clause(c, rl, from, from1); // Add it to the list of clauses to be printed out, in order after its sources. proofv.push_back(r); // And return a reference to the object. return r; } void Problem::setProof(const ProofCnf& proofCnf, const Proof& proof) { walk(proofCnf, proof, falsec); }
38.814516
129
0.719302
[ "object" ]
a2027fd935e1d5306886e69d8a27d16394b79455
261,596
cpp
C++
286-walls-and-gates/solution.cpp
darxsys/leetcode
1174f0dbad56c6bfd8196bc4c14798b5f8cee418
[ "MIT" ]
null
null
null
286-walls-and-gates/solution.cpp
darxsys/leetcode
1174f0dbad56c6bfd8196bc4c14798b5f8cee418
[ "MIT" ]
null
null
null
286-walls-and-gates/solution.cpp
darxsys/leetcode
1174f0dbad56c6bfd8196bc4c14798b5f8cee418
[ "MIT" ]
null
null
null
#include <cstdio> #include <cstring> #include <climits> #include <cstdlib> #include <cassert> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <map> #include <unordered_map> #include <algorithm> #include <unordered_set> using namespace std; class Solution { public: void wallsAndGates(vector<vector<int>>& rooms) { if (rooms.empty() || rooms[0].empty()) return; int m = rooms.size(); int n = rooms[0].size(); vector<int> v(n, 0); vector<vector<int>> visited(m, v); queue<pair<int, int>> q; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (rooms[i][j] != 0) continue; q.push({i,j}); } } int dist = 0; while (!q.empty()) { int k = q.size(); for (int l = 0; l < k; ++l) { pair<int, int> cur = q.front(); q.pop(); for (int p = 0; p < 4; ++p) { int nextx = cur.second + xdir[p]; int nexty = cur.first + ydir[p]; if (nextx >= 0 && nextx < n && nexty >= 0 && nexty < m && !visited[nexty][nextx] && rooms[nexty][nextx] != -1) { rooms[nexty][nextx] = min(dist+1, rooms[nexty][nextx]); q.push({nexty, nextx}); visited[nexty][nextx] = 1; } } } dist++; } } private: int xdir[4] = {0, -1, 0, 1}; int ydir[4] = {1, 0, -1, 0}; }; int main() { Solution s; vector<vector<int>> input = {{-1,2147483647,2147483647,0,2147483647,0,-1,0,2147483647,-1,0,-1,2147483647,0,-1,-1,2147483647,0,-1,-1,2147483647,0,-1,-1,2147483647,2147483647,-1,2147483647,0,-1,0,-1,0,0,-1,2147483647,2147483647,2147483647,-1,0,0,2147483647,0,2147483647,-1,2147483647,-1,-1,0,0,-1,2147483647,-1,0,0,2147483647,0,-1,-1,0,0,2147483647,-1,-1,-1,2147483647,-1,0,0,2147483647,-1,-1,2147483647,2147483647,2147483647,0,2147483647,0,0,2147483647,2147483647,-1,0,0,0,2147483647,-1,0,-1,-1,0,0,0,-1,2147483647,0,-1,2147483647,-1,-1,-1,-1,-1,-1,0,0,2147483647,0,-1,0,2147483647,-1,-1,-1,2147483647,-1,-1,-1,2147483647,0,2147483647,-1,2147483647,-1,0,-1,2147483647,0,2147483647,2147483647,-1,-1,-1,-1,-1,-1,-1,-1,0,-1,-1,0,0,0,-1,-1,2147483647,2147483647,0,0,2147483647,0,2147483647,2147483647,2147483647,0,0,2147483647,0,-1,-1,0,0,-1,0,-1,2147483647,-1,-1,0,0,2147483647,0,-1,-1,2147483647,2147483647,2147483647,-1,2147483647,0,-1,2147483647,2147483647,-1,-1,2147483647,0,2147483647,0,0,-1,0,2147483647,2147483647,2147483647,2147483647,-1,0,-1,2147483647,2147483647,0,2147483647,2147483647,-1,0,0,-1,2147483647,0,0,-1,-1,2147483647,2147483647,-1,0,0,0,2147483647},{0,-1,0,-1,-1,0,-1,2147483647,2147483647,-1,-1,2147483647,-1,-1,0,0,-1,-1,-1,2147483647,2147483647,-1,-1,-1,0,-1,-1,0,2147483647,-1,2147483647,2147483647,-1,-1,-1,0,2147483647,-1,2147483647,2147483647,-1,-1,2147483647,-1,2147483647,2147483647,2147483647,-1,2147483647,-1,2147483647,-1,2147483647,0,0,0,-1,-1,0,0,2147483647,-1,0,-1,2147483647,0,2147483647,-1,-1,-1,2147483647,0,-1,0,2147483647,-1,0,-1,2147483647,-1,2147483647,0,2147483647,2147483647,-1,2147483647,0,-1,-1,2147483647,2147483647,2147483647,-1,0,0,-1,0,-1,-1,2147483647,0,0,-1,2147483647,-1,0,0,2147483647,0,0,0,-1,2147483647,2147483647,0,-1,0,2147483647,0,0,-1,0,2147483647,-1,-1,2147483647,-1,0,-1,2147483647,0,2147483647,0,0,0,2147483647,2147483647,0,0,-1,0,-1,-1,-1,2147483647,-1,0,-1,2147483647,0,-1,0,0,0,0,2147483647,2147483647,2147483647,0,-1,0,-1,0,-1,0,2147483647,-1,2147483647,0,-1,0,0,0,-1,2147483647,-1,-1,2147483647,0,0,-1,-1,0,-1,-1,-1,0,2147483647,2147483647,-1,0,0,-1,-1,0,-1,2147483647,0,0,2147483647,2147483647,-1,2147483647,2147483647,0,2147483647,-1,-1,0,-1,0,-1,0,0,-1,2147483647,-1,-1,-1,-1,0},{-1,-1,0,2147483647,2147483647,-1,2147483647,-1,-1,2147483647,2147483647,0,2147483647,-1,-1,-1,-1,-1,0,2147483647,0,-1,2147483647,2147483647,0,-1,2147483647,2147483647,2147483647,-1,2147483647,0,2147483647,0,0,0,2147483647,2147483647,2147483647,0,-1,-1,0,2147483647,-1,-1,2147483647,0,0,2147483647,0,2147483647,0,0,2147483647,-1,2147483647,2147483647,-1,-1,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,0,-1,-1,2147483647,2147483647,0,2147483647,-1,-1,2147483647,2147483647,0,2147483647,-1,2147483647,-1,0,-1,2147483647,-1,0,0,-1,-1,-1,2147483647,2147483647,2147483647,0,2147483647,-1,0,0,2147483647,-1,0,-1,-1,-1,-1,-1,2147483647,-1,-1,0,-1,-1,-1,2147483647,-1,0,0,0,-1,2147483647,2147483647,0,0,0,-1,-1,-1,2147483647,0,0,-1,-1,2147483647,0,-1,-1,0,-1,0,2147483647,0,2147483647,0,0,2147483647,2147483647,0,-1,0,2147483647,0,2147483647,0,-1,-1,-1,0,-1,0,0,2147483647,-1,2147483647,0,0,-1,2147483647,2147483647,0,2147483647,2147483647,0,2147483647,0,0,2147483647,0,2147483647,-1,-1,-1,-1,2147483647,-1,2147483647,-1,-1,2147483647,0,0,0,2147483647,0,2147483647,0,0,0,0,2147483647,2147483647,2147483647,-1,0,2147483647,2147483647,-1,-1,0,-1,2147483647,2147483647,2147483647,-1,2147483647,2147483647,2147483647,2147483647,2147483647,0,0},{2147483647,-1,-1,0,2147483647,0,2147483647,0,0,0,-1,-1,0,0,0,2147483647,-1,-1,2147483647,-1,-1,0,0,0,2147483647,-1,-1,0,2147483647,2147483647,0,2147483647,2147483647,0,0,-1,0,0,2147483647,2147483647,-1,0,0,0,2147483647,2147483647,-1,-1,-1,-1,0,-1,2147483647,0,2147483647,2147483647,-1,2147483647,0,2147483647,-1,-1,2147483647,-1,-1,0,-1,0,2147483647,-1,-1,-1,0,-1,2147483647,-1,-1,0,-1,-1,0,-1,0,2147483647,-1,-1,0,0,-1,0,-1,0,0,-1,0,2147483647,-1,2147483647,2147483647,-1,0,0,0,0,0,2147483647,2147483647,0,0,0,-1,0,2147483647,2147483647,2147483647,-1,2147483647,-1,0,-1,-1,0,-1,-1,2147483647,2147483647,0,2147483647,-1,2147483647,2147483647,2147483647,2147483647,0,0,0,2147483647,2147483647,0,0,0,2147483647,2147483647,2147483647,2147483647,2147483647,-1,0,0,0,2147483647,0,2147483647,-1,0,2147483647,0,-1,-1,2147483647,-1,-1,-1,2147483647,2147483647,2147483647,0,0,0,0,0,2147483647,-1,0,2147483647,-1,0,-1,0,-1,-1,0,-1,0,0,0,0,2147483647,2147483647,2147483647,0,2147483647,2147483647,-1,2147483647,-1,2147483647,2147483647,2147483647,0,0,0,2147483647,0,-1,-1,0,-1,-1,0,2147483647,2147483647,-1,2147483647,-1,0,0,-1,0,2147483647,-1},{-1,-1,0,2147483647,0,-1,0,-1,0,2147483647,-1,0,-1,2147483647,2147483647,0,2147483647,-1,0,-1,2147483647,0,2147483647,2147483647,-1,2147483647,0,-1,2147483647,2147483647,2147483647,-1,2147483647,-1,2147483647,0,-1,-1,0,0,0,-1,0,-1,-1,2147483647,0,2147483647,-1,0,2147483647,2147483647,-1,-1,2147483647,-1,2147483647,0,2147483647,2147483647,-1,0,0,2147483647,0,0,2147483647,2147483647,-1,2147483647,2147483647,-1,2147483647,0,2147483647,-1,0,-1,0,-1,2147483647,0,-1,-1,-1,2147483647,-1,2147483647,2147483647,0,-1,0,2147483647,2147483647,0,0,-1,0,2147483647,-1,2147483647,2147483647,-1,2147483647,2147483647,-1,-1,0,-1,0,-1,2147483647,-1,-1,2147483647,2147483647,-1,0,-1,-1,-1,2147483647,2147483647,0,0,2147483647,-1,-1,0,2147483647,-1,0,2147483647,0,0,-1,2147483647,2147483647,-1,2147483647,2147483647,0,-1,0,2147483647,0,2147483647,0,-1,-1,0,0,-1,2147483647,-1,2147483647,2147483647,0,-1,-1,2147483647,0,0,2147483647,0,2147483647,-1,-1,2147483647,-1,0,0,2147483647,0,0,2147483647,-1,-1,0,0,-1,0,2147483647,2147483647,0,0,-1,-1,2147483647,0,-1,2147483647,-1,-1,2147483647,2147483647,2147483647,2147483647,0,2147483647,2147483647,0,2147483647,0,0,-1,-1,0,2147483647,-1,0,-1,-1,0,0,2147483647,0,2147483647,0,-1,-1},{2147483647,-1,0,-1,0,-1,-1,2147483647,2147483647,-1,2147483647,-1,0,0,0,-1,-1,-1,0,2147483647,0,-1,-1,0,-1,0,-1,0,-1,0,0,0,-1,2147483647,-1,-1,0,-1,0,2147483647,0,2147483647,0,0,-1,2147483647,2147483647,0,-1,2147483647,0,2147483647,-1,-1,-1,-1,-1,-1,-1,0,-1,0,-1,-1,0,2147483647,0,2147483647,0,2147483647,0,-1,2147483647,2147483647,2147483647,0,2147483647,-1,0,2147483647,0,0,2147483647,2147483647,-1,2147483647,-1,0,-1,-1,-1,0,0,-1,2147483647,2147483647,-1,-1,-1,2147483647,-1,0,0,0,2147483647,-1,0,-1,2147483647,-1,-1,0,2147483647,0,-1,-1,2147483647,0,-1,2147483647,-1,2147483647,2147483647,-1,2147483647,2147483647,-1,-1,0,2147483647,0,0,2147483647,0,2147483647,-1,-1,0,2147483647,0,0,-1,0,-1,0,0,-1,0,2147483647,-1,-1,-1,0,0,-1,2147483647,-1,2147483647,-1,-1,-1,0,2147483647,-1,-1,2147483647,0,2147483647,-1,2147483647,2147483647,2147483647,0,2147483647,0,-1,-1,2147483647,-1,0,2147483647,0,0,-1,-1,2147483647,-1,2147483647,0,0,-1,0,2147483647,2147483647,0,-1,2147483647,2147483647,0,0,2147483647,0,-1,0,0,2147483647,0,0,-1,-1,-1,-1,0,0,2147483647,2147483647,2147483647,-1,-1,-1,0},{-1,0,0,-1,-1,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,0,2147483647,2147483647,2147483647,0,0,2147483647,0,-1,0,-1,-1,2147483647,2147483647,2147483647,-1,2147483647,2147483647,-1,2147483647,-1,-1,-1,-1,-1,0,-1,-1,2147483647,-1,2147483647,0,0,-1,-1,0,2147483647,0,0,2147483647,0,0,0,0,-1,0,0,0,2147483647,-1,2147483647,0,0,-1,0,-1,-1,0,-1,0,2147483647,0,-1,2147483647,2147483647,2147483647,-1,0,2147483647,-1,2147483647,-1,2147483647,2147483647,0,0,2147483647,2147483647,0,2147483647,2147483647,0,2147483647,0,0,-1,0,2147483647,2147483647,0,0,2147483647,2147483647,2147483647,-1,0,0,0,-1,-1,0,0,-1,0,2147483647,-1,2147483647,0,-1,0,0,0,-1,-1,0,0,0,0,2147483647,2147483647,2147483647,2147483647,0,-1,0,-1,2147483647,0,0,-1,2147483647,-1,-1,-1,-1,-1,-1,0,-1,2147483647,0,2147483647,-1,2147483647,2147483647,-1,2147483647,2147483647,-1,-1,2147483647,0,-1,-1,2147483647,-1,0,2147483647,-1,2147483647,2147483647,0,-1,2147483647,2147483647,-1,0,2147483647,2147483647,2147483647,-1,2147483647,2147483647,2147483647,0,0,-1,0,-1,-1,2147483647,-1,-1,-1,-1,-1,-1,2147483647,2147483647,2147483647,0,2147483647,0,2147483647,2147483647,-1,0,2147483647,-1,-1,0,0,-1,0,0,2147483647,0,-1,-1,0},{-1,2147483647,2147483647,0,0,2147483647,-1,0,0,-1,0,-1,0,0,-1,0,2147483647,0,0,0,0,2147483647,2147483647,0,2147483647,2147483647,-1,0,-1,-1,2147483647,0,-1,0,0,2147483647,2147483647,0,-1,0,-1,2147483647,-1,-1,0,0,-1,2147483647,0,-1,0,-1,0,-1,-1,-1,-1,0,-1,2147483647,-1,0,2147483647,0,-1,0,-1,-1,0,-1,0,2147483647,2147483647,2147483647,0,0,2147483647,2147483647,2147483647,2147483647,0,2147483647,2147483647,0,2147483647,2147483647,0,0,0,-1,2147483647,-1,2147483647,-1,0,2147483647,2147483647,0,0,-1,0,-1,0,2147483647,0,2147483647,2147483647,2147483647,0,2147483647,-1,2147483647,0,0,2147483647,-1,0,0,-1,2147483647,0,-1,2147483647,0,-1,-1,0,2147483647,-1,0,2147483647,-1,-1,2147483647,0,2147483647,-1,0,2147483647,-1,0,-1,0,2147483647,-1,-1,-1,0,0,-1,-1,-1,0,-1,2147483647,-1,0,-1,0,2147483647,-1,0,2147483647,-1,0,0,0,2147483647,2147483647,-1,2147483647,2147483647,0,2147483647,0,-1,-1,0,-1,2147483647,-1,0,-1,2147483647,0,0,-1,0,0,2147483647,-1,2147483647,2147483647,0,-1,0,0,2147483647,0,0,0,-1,-1,-1,2147483647,0,0,-1,2147483647,-1,-1,2147483647,0,0,-1,-1,2147483647,2147483647,2147483647,2147483647,-1},{-1,2147483647,0,-1,2147483647,2147483647,0,0,-1,-1,2147483647,0,0,-1,0,-1,2147483647,-1,-1,-1,2147483647,2147483647,0,2147483647,0,0,2147483647,2147483647,2147483647,0,2147483647,0,0,0,-1,-1,0,2147483647,0,2147483647,0,2147483647,-1,-1,-1,-1,-1,2147483647,0,2147483647,-1,-1,-1,2147483647,0,0,0,0,-1,2147483647,-1,2147483647,2147483647,-1,2147483647,0,2147483647,2147483647,0,0,2147483647,-1,2147483647,0,-1,2147483647,0,-1,2147483647,-1,2147483647,-1,0,0,-1,-1,-1,-1,2147483647,2147483647,2147483647,2147483647,2147483647,-1,-1,2147483647,0,0,0,-1,2147483647,-1,-1,0,2147483647,0,-1,2147483647,2147483647,2147483647,-1,-1,0,2147483647,2147483647,2147483647,-1,-1,-1,-1,0,-1,-1,0,0,2147483647,0,2147483647,2147483647,0,-1,-1,-1,-1,2147483647,2147483647,2147483647,0,0,-1,2147483647,-1,-1,0,-1,2147483647,2147483647,2147483647,-1,2147483647,-1,0,0,-1,2147483647,-1,0,2147483647,0,2147483647,2147483647,0,-1,2147483647,2147483647,0,2147483647,2147483647,-1,-1,-1,0,2147483647,-1,-1,2147483647,2147483647,-1,-1,2147483647,0,2147483647,2147483647,2147483647,0,-1,-1,0,-1,2147483647,0,0,-1,0,0,0,-1,0,2147483647,0,-1,0,0,-1,2147483647,2147483647,2147483647,0,2147483647,-1,0,2147483647,2147483647,2147483647,0,-1,2147483647,-1,0,2147483647,2147483647},{-1,2147483647,0,0,2147483647,2147483647,2147483647,-1,2147483647,-1,0,2147483647,0,-1,0,2147483647,-1,0,-1,0,0,2147483647,-1,-1,0,-1,0,0,-1,2147483647,0,0,0,-1,-1,-1,0,2147483647,2147483647,-1,2147483647,2147483647,2147483647,0,-1,0,-1,-1,2147483647,0,2147483647,2147483647,-1,0,0,0,-1,-1,-1,-1,2147483647,-1,0,0,2147483647,-1,-1,2147483647,-1,2147483647,-1,-1,2147483647,-1,-1,2147483647,0,-1,2147483647,2147483647,2147483647,2147483647,-1,-1,-1,-1,2147483647,-1,2147483647,0,0,2147483647,-1,0,-1,2147483647,0,0,2147483647,0,2147483647,0,2147483647,2147483647,0,0,-1,2147483647,0,2147483647,2147483647,0,2147483647,-1,0,2147483647,0,-1,-1,0,0,0,-1,2147483647,0,0,0,-1,0,0,2147483647,-1,-1,0,0,2147483647,-1,2147483647,0,-1,0,2147483647,2147483647,0,-1,2147483647,2147483647,2147483647,2147483647,-1,2147483647,-1,2147483647,0,-1,2147483647,2147483647,0,-1,2147483647,-1,-1,-1,2147483647,-1,2147483647,2147483647,-1,2147483647,0,-1,-1,-1,-1,2147483647,-1,0,0,0,-1,2147483647,0,0,2147483647,-1,-1,0,0,2147483647,0,0,0,0,0,-1,-1,0,2147483647,0,0,0,2147483647,0,-1,-1,-1,2147483647,-1,0,0,-1,2147483647,-1,2147483647,-1,2147483647,-1,-1,2147483647,-1,-1},{-1,-1,2147483647,2147483647,0,0,2147483647,0,0,-1,2147483647,-1,-1,2147483647,-1,2147483647,-1,2147483647,2147483647,2147483647,0,2147483647,2147483647,2147483647,-1,-1,-1,2147483647,0,2147483647,2147483647,-1,0,-1,-1,-1,-1,-1,-1,2147483647,0,2147483647,-1,-1,2147483647,0,2147483647,0,0,0,2147483647,2147483647,0,-1,0,2147483647,-1,0,0,0,2147483647,2147483647,2147483647,-1,0,2147483647,-1,2147483647,0,0,0,2147483647,2147483647,-1,-1,0,0,0,-1,2147483647,-1,-1,2147483647,2147483647,2147483647,-1,-1,2147483647,0,-1,2147483647,0,-1,2147483647,0,0,0,0,-1,-1,-1,-1,-1,2147483647,0,2147483647,-1,2147483647,0,0,2147483647,0,0,-1,-1,2147483647,-1,0,2147483647,0,2147483647,-1,0,2147483647,-1,0,-1,0,2147483647,-1,2147483647,2147483647,-1,0,2147483647,2147483647,2147483647,0,0,0,-1,2147483647,2147483647,2147483647,2147483647,-1,-1,2147483647,2147483647,2147483647,0,-1,2147483647,0,2147483647,-1,-1,2147483647,0,2147483647,0,0,2147483647,2147483647,-1,0,-1,-1,0,-1,2147483647,2147483647,2147483647,-1,2147483647,0,-1,-1,2147483647,2147483647,-1,0,0,-1,2147483647,0,2147483647,2147483647,0,2147483647,2147483647,-1,2147483647,0,-1,-1,0,0,2147483647,-1,-1,2147483647,2147483647,2147483647,0,0,0,2147483647,-1,-1,0,0,2147483647,-1,2147483647,-1,-1,-1,2147483647,-1,2147483647},{-1,-1,2147483647,2147483647,0,-1,2147483647,2147483647,2147483647,-1,-1,0,-1,0,2147483647,2147483647,-1,-1,-1,2147483647,0,0,0,0,2147483647,2147483647,-1,0,0,0,0,2147483647,0,0,-1,-1,0,0,-1,0,-1,2147483647,2147483647,2147483647,0,-1,-1,0,2147483647,0,2147483647,-1,0,0,2147483647,2147483647,2147483647,0,2147483647,2147483647,2147483647,2147483647,0,-1,2147483647,0,-1,-1,2147483647,-1,0,-1,2147483647,2147483647,2147483647,2147483647,2147483647,-1,0,2147483647,2147483647,2147483647,0,0,2147483647,-1,-1,-1,2147483647,0,-1,0,2147483647,2147483647,-1,0,-1,0,2147483647,0,-1,-1,2147483647,2147483647,-1,2147483647,-1,-1,2147483647,-1,0,-1,-1,0,-1,0,0,-1,2147483647,2147483647,2147483647,-1,-1,-1,0,-1,2147483647,2147483647,0,-1,0,-1,-1,0,0,2147483647,-1,-1,-1,-1,2147483647,0,2147483647,2147483647,2147483647,-1,0,-1,0,0,0,2147483647,0,-1,-1,2147483647,0,2147483647,2147483647,-1,2147483647,-1,2147483647,-1,2147483647,-1,-1,-1,0,0,2147483647,2147483647,-1,2147483647,0,0,2147483647,0,-1,0,0,0,0,2147483647,-1,-1,-1,-1,0,0,-1,2147483647,0,-1,2147483647,2147483647,2147483647,2147483647,-1,0,2147483647,-1,0,0,-1,2147483647,2147483647,0,0,-1,-1,2147483647,2147483647,2147483647,0,0,0,-1,2147483647,2147483647,2147483647},{2147483647,0,-1,-1,0,0,-1,0,0,-1,0,2147483647,0,-1,-1,0,0,0,-1,-1,-1,2147483647,2147483647,-1,2147483647,-1,-1,2147483647,-1,0,2147483647,-1,-1,-1,-1,0,2147483647,-1,-1,2147483647,2147483647,-1,2147483647,2147483647,0,2147483647,2147483647,2147483647,0,0,0,0,2147483647,-1,2147483647,2147483647,-1,2147483647,2147483647,2147483647,0,-1,2147483647,0,0,2147483647,0,-1,2147483647,0,-1,2147483647,-1,0,-1,-1,-1,2147483647,2147483647,-1,2147483647,2147483647,-1,-1,-1,0,-1,-1,0,2147483647,2147483647,0,0,2147483647,0,0,2147483647,0,0,2147483647,0,0,0,0,-1,0,2147483647,2147483647,-1,-1,0,-1,-1,-1,2147483647,-1,-1,-1,-1,-1,0,0,2147483647,-1,-1,2147483647,-1,2147483647,2147483647,0,0,2147483647,2147483647,-1,-1,0,0,-1,0,2147483647,-1,2147483647,2147483647,-1,2147483647,-1,-1,-1,-1,-1,2147483647,-1,0,0,2147483647,-1,0,2147483647,2147483647,-1,2147483647,2147483647,2147483647,0,0,2147483647,2147483647,-1,0,2147483647,2147483647,2147483647,-1,-1,-1,2147483647,0,-1,2147483647,2147483647,0,0,-1,-1,-1,2147483647,2147483647,0,0,0,-1,2147483647,2147483647,2147483647,0,2147483647,0,0,0,2147483647,-1,0,2147483647,2147483647,2147483647,0,2147483647,2147483647,-1,-1,0,-1,-1,2147483647,-1,2147483647,0,-1,0,2147483647,-1},{2147483647,-1,0,0,-1,0,0,0,0,-1,2147483647,2147483647,2147483647,2147483647,0,0,0,-1,-1,-1,0,0,2147483647,0,2147483647,2147483647,2147483647,-1,0,0,-1,-1,-1,-1,0,0,0,0,0,-1,-1,2147483647,-1,0,2147483647,2147483647,-1,2147483647,-1,2147483647,-1,-1,-1,2147483647,0,2147483647,-1,0,-1,0,-1,0,2147483647,0,0,-1,0,2147483647,0,-1,0,2147483647,-1,0,2147483647,-1,0,2147483647,0,0,0,2147483647,0,0,-1,0,2147483647,0,2147483647,0,-1,0,0,2147483647,0,-1,-1,-1,0,0,-1,-1,0,2147483647,0,0,-1,0,-1,0,0,-1,2147483647,-1,0,0,0,-1,2147483647,-1,0,-1,0,0,-1,-1,-1,-1,2147483647,0,0,0,0,0,-1,-1,-1,0,0,2147483647,2147483647,-1,0,0,0,0,-1,-1,0,0,0,2147483647,2147483647,0,-1,-1,2147483647,2147483647,2147483647,-1,-1,2147483647,2147483647,0,-1,-1,2147483647,0,-1,0,0,0,0,-1,0,2147483647,2147483647,-1,2147483647,0,2147483647,0,-1,2147483647,-1,-1,2147483647,2147483647,0,2147483647,2147483647,-1,2147483647,0,2147483647,-1,0,0,2147483647,2147483647,-1,-1,0,2147483647,0,0,2147483647,0,2147483647,2147483647,0,-1,2147483647,0,0,2147483647,2147483647,-1,-1,2147483647,2147483647},{0,2147483647,-1,-1,2147483647,-1,-1,-1,2147483647,0,-1,0,-1,2147483647,2147483647,2147483647,2147483647,-1,-1,2147483647,-1,2147483647,0,2147483647,2147483647,0,2147483647,2147483647,2147483647,2147483647,-1,0,0,0,-1,0,2147483647,2147483647,0,0,0,-1,0,0,-1,-1,2147483647,-1,-1,-1,-1,0,2147483647,0,-1,-1,2147483647,2147483647,0,-1,2147483647,2147483647,0,-1,0,2147483647,2147483647,0,0,0,-1,-1,0,0,0,-1,2147483647,0,0,0,2147483647,0,2147483647,-1,-1,0,2147483647,0,-1,-1,-1,-1,2147483647,-1,0,0,-1,-1,2147483647,2147483647,0,0,-1,2147483647,0,0,-1,-1,2147483647,0,-1,2147483647,0,2147483647,0,0,-1,0,0,0,2147483647,0,-1,2147483647,-1,-1,2147483647,0,-1,2147483647,-1,2147483647,0,0,-1,-1,0,-1,-1,2147483647,-1,2147483647,-1,2147483647,-1,2147483647,2147483647,0,0,0,-1,-1,0,0,0,0,2147483647,2147483647,-1,2147483647,0,0,-1,-1,0,-1,-1,0,2147483647,0,2147483647,0,2147483647,-1,2147483647,0,-1,0,-1,0,2147483647,-1,-1,-1,2147483647,0,2147483647,0,2147483647,0,0,-1,0,0,-1,-1,-1,-1,0,-1,0,-1,2147483647,-1,0,0,2147483647,0,-1,-1,2147483647,2147483647,0,2147483647,0,0,-1,2147483647,-1,0,-1},{0,2147483647,0,2147483647,-1,-1,0,2147483647,2147483647,2147483647,0,0,0,0,0,2147483647,-1,0,0,0,-1,0,2147483647,0,-1,-1,-1,2147483647,-1,-1,2147483647,-1,0,-1,2147483647,-1,2147483647,0,-1,2147483647,0,0,0,2147483647,2147483647,-1,-1,2147483647,0,0,0,2147483647,0,0,2147483647,0,0,2147483647,-1,2147483647,-1,2147483647,-1,0,0,0,0,0,-1,0,2147483647,-1,0,2147483647,2147483647,0,-1,2147483647,2147483647,2147483647,2147483647,2147483647,-1,2147483647,-1,-1,0,0,2147483647,2147483647,0,0,-1,-1,-1,-1,-1,-1,0,2147483647,2147483647,-1,0,2147483647,2147483647,-1,0,-1,0,2147483647,-1,-1,0,-1,-1,-1,0,-1,2147483647,0,-1,-1,0,-1,0,-1,-1,2147483647,2147483647,-1,2147483647,-1,2147483647,2147483647,0,0,2147483647,2147483647,-1,-1,2147483647,2147483647,0,0,0,0,2147483647,2147483647,-1,2147483647,2147483647,2147483647,0,-1,-1,0,2147483647,-1,0,0,-1,0,2147483647,2147483647,0,2147483647,0,0,0,-1,-1,-1,-1,-1,-1,0,0,0,-1,0,0,0,0,2147483647,2147483647,-1,-1,2147483647,0,2147483647,-1,0,0,2147483647,0,2147483647,-1,0,-1,2147483647,-1,2147483647,0,0,0,-1,0,2147483647,0,2147483647,-1,2147483647,2147483647,2147483647,2147483647,0,2147483647,-1,-1,-1,-1},{0,-1,0,2147483647,-1,-1,2147483647,0,-1,2147483647,2147483647,0,-1,2147483647,-1,2147483647,-1,0,0,-1,0,-1,-1,0,2147483647,0,0,0,-1,0,-1,0,2147483647,-1,0,2147483647,0,-1,-1,-1,-1,2147483647,0,0,-1,-1,-1,2147483647,-1,-1,-1,2147483647,0,0,-1,2147483647,2147483647,-1,2147483647,2147483647,0,2147483647,2147483647,2147483647,2147483647,-1,2147483647,-1,0,2147483647,2147483647,2147483647,2147483647,-1,0,2147483647,0,2147483647,2147483647,2147483647,-1,0,0,0,-1,2147483647,2147483647,0,0,2147483647,-1,2147483647,0,2147483647,0,2147483647,0,-1,-1,0,2147483647,2147483647,-1,-1,2147483647,2147483647,-1,-1,0,-1,2147483647,0,0,0,0,-1,0,2147483647,-1,-1,0,2147483647,0,0,0,-1,-1,-1,2147483647,0,-1,-1,0,0,2147483647,0,0,2147483647,2147483647,2147483647,0,0,-1,0,-1,0,2147483647,0,2147483647,-1,0,-1,-1,2147483647,0,0,2147483647,2147483647,0,0,2147483647,-1,-1,2147483647,2147483647,2147483647,-1,0,2147483647,2147483647,-1,2147483647,-1,-1,0,-1,2147483647,0,0,-1,-1,0,2147483647,2147483647,-1,0,2147483647,-1,2147483647,2147483647,2147483647,-1,0,0,-1,0,0,0,2147483647,-1,2147483647,0,2147483647,2147483647,2147483647,0,2147483647,2147483647,2147483647,2147483647,0,2147483647,0,2147483647,2147483647,2147483647,0,0,2147483647,-1,2147483647},{-1,2147483647,2147483647,-1,0,0,-1,-1,2147483647,0,-1,2147483647,0,0,2147483647,-1,-1,0,-1,0,-1,0,0,2147483647,0,-1,2147483647,-1,2147483647,-1,2147483647,-1,2147483647,0,-1,0,-1,0,2147483647,0,0,0,-1,0,-1,0,0,2147483647,2147483647,-1,2147483647,2147483647,2147483647,-1,0,-1,2147483647,2147483647,2147483647,-1,2147483647,2147483647,-1,2147483647,0,2147483647,2147483647,2147483647,0,2147483647,2147483647,2147483647,-1,2147483647,2147483647,0,0,2147483647,0,2147483647,2147483647,0,2147483647,-1,2147483647,0,2147483647,-1,2147483647,0,2147483647,0,-1,2147483647,0,-1,-1,2147483647,-1,0,2147483647,0,0,-1,2147483647,2147483647,-1,2147483647,0,2147483647,0,-1,0,2147483647,2147483647,0,0,0,2147483647,2147483647,0,-1,2147483647,0,2147483647,0,-1,0,0,2147483647,0,2147483647,0,-1,-1,-1,0,2147483647,0,2147483647,-1,2147483647,-1,2147483647,2147483647,-1,-1,0,2147483647,0,2147483647,2147483647,2147483647,0,2147483647,2147483647,0,2147483647,2147483647,2147483647,2147483647,0,0,2147483647,-1,-1,2147483647,2147483647,2147483647,-1,0,0,2147483647,0,2147483647,-1,-1,0,0,-1,-1,0,0,-1,-1,2147483647,2147483647,-1,0,0,-1,0,0,0,2147483647,-1,-1,2147483647,2147483647,0,2147483647,0,0,-1,0,2147483647,2147483647,2147483647,-1,0,0,2147483647,2147483647,2147483647,-1,0,0,2147483647,0,0,-1},{-1,2147483647,2147483647,0,2147483647,0,2147483647,2147483647,-1,0,2147483647,2147483647,0,0,-1,-1,-1,-1,0,-1,0,-1,0,2147483647,-1,2147483647,-1,2147483647,2147483647,0,-1,0,2147483647,2147483647,2147483647,2147483647,0,2147483647,2147483647,2147483647,-1,0,0,0,0,0,0,0,0,2147483647,-1,0,2147483647,0,2147483647,0,-1,0,-1,2147483647,-1,-1,0,0,2147483647,-1,0,0,-1,0,-1,-1,-1,0,0,-1,-1,2147483647,0,2147483647,-1,0,0,0,2147483647,-1,2147483647,-1,-1,0,2147483647,2147483647,0,2147483647,-1,-1,-1,2147483647,2147483647,0,0,0,-1,2147483647,-1,0,2147483647,2147483647,-1,-1,2147483647,2147483647,0,2147483647,-1,0,2147483647,-1,0,-1,0,2147483647,2147483647,0,-1,2147483647,2147483647,-1,-1,0,-1,0,-1,-1,0,2147483647,0,-1,-1,2147483647,0,0,2147483647,-1,0,-1,2147483647,2147483647,-1,0,2147483647,-1,2147483647,0,0,-1,-1,-1,-1,2147483647,2147483647,2147483647,0,2147483647,-1,0,2147483647,2147483647,0,2147483647,-1,-1,2147483647,2147483647,2147483647,-1,0,0,-1,-1,-1,0,-1,-1,-1,2147483647,0,-1,-1,0,2147483647,2147483647,-1,-1,0,-1,2147483647,0,-1,0,0,0,2147483647,-1,-1,-1,0,-1,2147483647,2147483647,2147483647,2147483647,-1,2147483647,-1,-1,2147483647,-1,-1,0,0},{0,0,0,2147483647,-1,-1,2147483647,2147483647,-1,0,2147483647,2147483647,2147483647,2147483647,0,0,-1,0,2147483647,-1,-1,-1,-1,2147483647,2147483647,2147483647,2147483647,-1,-1,0,-1,-1,0,0,0,2147483647,0,-1,-1,0,-1,-1,0,0,2147483647,-1,2147483647,2147483647,-1,-1,2147483647,-1,-1,-1,-1,2147483647,2147483647,-1,0,2147483647,-1,2147483647,0,-1,2147483647,-1,0,2147483647,-1,0,-1,0,0,0,-1,0,0,2147483647,-1,0,2147483647,-1,0,0,2147483647,2147483647,0,-1,0,2147483647,-1,0,0,0,0,-1,2147483647,0,2147483647,-1,0,2147483647,-1,2147483647,0,0,0,2147483647,2147483647,2147483647,-1,2147483647,-1,2147483647,2147483647,0,2147483647,-1,0,0,-1,-1,2147483647,0,0,0,2147483647,0,2147483647,-1,-1,-1,0,2147483647,2147483647,2147483647,0,0,-1,0,0,2147483647,2147483647,-1,0,2147483647,-1,2147483647,2147483647,-1,0,0,-1,2147483647,2147483647,2147483647,2147483647,2147483647,0,0,-1,0,0,-1,0,-1,-1,-1,0,0,2147483647,2147483647,0,0,2147483647,2147483647,2147483647,0,2147483647,2147483647,0,-1,-1,2147483647,-1,2147483647,0,0,0,2147483647,-1,2147483647,0,0,0,-1,2147483647,0,-1,2147483647,0,2147483647,0,0,2147483647,2147483647,-1,0,2147483647,2147483647,2147483647,-1,0,-1,-1,2147483647,2147483647,-1,-1,0,0},{2147483647,0,0,2147483647,2147483647,-1,-1,-1,0,0,0,0,2147483647,-1,2147483647,-1,0,2147483647,2147483647,2147483647,-1,0,2147483647,-1,-1,2147483647,2147483647,2147483647,2147483647,0,-1,0,2147483647,0,0,-1,-1,2147483647,0,-1,2147483647,-1,0,-1,2147483647,-1,2147483647,-1,0,0,-1,0,0,0,2147483647,0,-1,-1,0,0,-1,2147483647,0,-1,0,0,2147483647,2147483647,-1,-1,0,2147483647,2147483647,2147483647,2147483647,0,0,2147483647,-1,-1,0,0,-1,0,0,2147483647,-1,-1,-1,0,2147483647,0,2147483647,2147483647,0,-1,0,0,2147483647,0,-1,2147483647,2147483647,0,-1,0,-1,0,0,2147483647,2147483647,-1,-1,-1,2147483647,-1,0,2147483647,-1,0,0,2147483647,0,0,2147483647,-1,-1,2147483647,2147483647,0,0,2147483647,2147483647,-1,-1,-1,0,-1,0,-1,0,2147483647,-1,0,0,0,0,0,-1,-1,0,-1,2147483647,0,2147483647,2147483647,2147483647,2147483647,-1,-1,2147483647,0,0,-1,0,2147483647,2147483647,-1,2147483647,0,-1,2147483647,0,2147483647,0,0,-1,-1,-1,-1,-1,2147483647,2147483647,-1,2147483647,-1,-1,2147483647,0,2147483647,-1,-1,2147483647,2147483647,2147483647,-1,2147483647,-1,-1,-1,-1,-1,0,0,-1,2147483647,2147483647,0,2147483647,-1,2147483647,2147483647,-1,2147483647,0,-1,2147483647,0,0,0,-1},{0,0,2147483647,2147483647,0,-1,0,-1,0,-1,0,-1,0,0,0,-1,2147483647,0,2147483647,-1,-1,2147483647,2147483647,2147483647,-1,0,2147483647,2147483647,-1,-1,2147483647,2147483647,-1,2147483647,0,2147483647,0,2147483647,-1,0,0,0,2147483647,-1,2147483647,-1,0,2147483647,2147483647,-1,0,2147483647,2147483647,-1,0,2147483647,-1,-1,0,2147483647,0,2147483647,2147483647,2147483647,-1,2147483647,0,-1,-1,0,2147483647,0,2147483647,-1,-1,2147483647,2147483647,2147483647,-1,2147483647,0,2147483647,2147483647,0,-1,2147483647,2147483647,-1,0,-1,2147483647,2147483647,-1,0,-1,0,-1,0,-1,2147483647,0,-1,-1,-1,0,-1,2147483647,2147483647,-1,2147483647,-1,0,-1,0,2147483647,0,2147483647,-1,2147483647,2147483647,2147483647,0,0,0,0,0,0,0,0,-1,0,0,0,-1,-1,0,2147483647,-1,-1,-1,-1,2147483647,-1,0,2147483647,0,-1,-1,2147483647,2147483647,0,0,0,-1,2147483647,-1,0,-1,-1,2147483647,0,0,-1,-1,-1,-1,0,0,-1,0,0,-1,-1,0,-1,2147483647,0,-1,2147483647,-1,2147483647,0,2147483647,2147483647,-1,0,0,2147483647,0,2147483647,0,2147483647,-1,-1,-1,0,2147483647,-1,-1,2147483647,-1,0,-1,2147483647,0,0,-1,0,2147483647,0,-1,0,0,-1,2147483647,2147483647,0,2147483647,-1,-1,0},{2147483647,0,0,2147483647,2147483647,-1,0,2147483647,-1,2147483647,2147483647,0,0,0,-1,2147483647,0,0,0,0,2147483647,2147483647,-1,2147483647,0,2147483647,2147483647,2147483647,0,-1,-1,2147483647,-1,-1,0,-1,2147483647,2147483647,2147483647,-1,-1,0,2147483647,-1,-1,2147483647,-1,0,2147483647,-1,0,2147483647,0,2147483647,2147483647,2147483647,2147483647,0,-1,2147483647,0,2147483647,2147483647,2147483647,-1,0,-1,2147483647,-1,0,-1,-1,-1,-1,2147483647,2147483647,-1,-1,2147483647,0,2147483647,-1,2147483647,-1,-1,-1,-1,2147483647,0,-1,0,2147483647,-1,0,2147483647,0,0,2147483647,-1,0,-1,2147483647,0,-1,2147483647,0,-1,-1,2147483647,-1,2147483647,2147483647,-1,0,-1,2147483647,2147483647,-1,-1,-1,2147483647,-1,-1,-1,2147483647,-1,0,0,0,2147483647,0,-1,-1,-1,-1,0,0,-1,2147483647,-1,2147483647,2147483647,0,2147483647,-1,2147483647,-1,-1,2147483647,0,0,-1,0,0,2147483647,0,-1,2147483647,-1,0,-1,0,0,2147483647,0,0,0,-1,-1,0,2147483647,-1,2147483647,0,0,0,2147483647,0,-1,2147483647,0,0,0,-1,2147483647,0,0,0,0,-1,2147483647,-1,-1,0,0,2147483647,2147483647,2147483647,0,-1,-1,2147483647,-1,2147483647,0,0,0,0,-1,2147483647,-1,0,2147483647,2147483647,-1,2147483647,-1,0,2147483647,-1,0},{-1,2147483647,0,-1,0,2147483647,-1,-1,2147483647,-1,-1,0,2147483647,2147483647,2147483647,2147483647,0,2147483647,0,0,-1,-1,2147483647,0,2147483647,-1,2147483647,2147483647,0,2147483647,-1,0,-1,-1,0,2147483647,-1,0,0,2147483647,-1,0,2147483647,-1,2147483647,-1,-1,2147483647,2147483647,0,2147483647,0,0,0,0,2147483647,2147483647,-1,-1,2147483647,-1,0,0,2147483647,2147483647,0,-1,-1,-1,2147483647,-1,0,-1,0,2147483647,2147483647,-1,2147483647,-1,-1,0,-1,0,2147483647,2147483647,-1,2147483647,2147483647,0,2147483647,0,0,-1,-1,-1,-1,2147483647,0,-1,-1,2147483647,-1,0,-1,2147483647,0,0,2147483647,-1,2147483647,-1,0,0,2147483647,-1,2147483647,0,0,0,-1,2147483647,-1,2147483647,-1,-1,-1,-1,2147483647,0,2147483647,0,-1,-1,2147483647,2147483647,-1,0,2147483647,2147483647,2147483647,2147483647,0,2147483647,0,0,2147483647,0,-1,2147483647,-1,0,-1,2147483647,0,-1,-1,-1,2147483647,2147483647,0,2147483647,2147483647,-1,-1,0,2147483647,2147483647,2147483647,0,0,-1,0,-1,0,2147483647,-1,-1,0,2147483647,2147483647,0,0,2147483647,-1,2147483647,2147483647,-1,2147483647,2147483647,2147483647,-1,0,0,-1,0,0,-1,0,0,2147483647,-1,2147483647,0,2147483647,2147483647,2147483647,2147483647,0,0,-1,0,0,2147483647,0,2147483647,-1,-1,0,2147483647,-1,-1},{2147483647,2147483647,-1,-1,-1,2147483647,-1,2147483647,0,-1,-1,-1,0,0,0,-1,0,0,0,-1,2147483647,0,0,0,0,2147483647,0,0,2147483647,2147483647,0,2147483647,-1,-1,2147483647,2147483647,2147483647,2147483647,2147483647,0,2147483647,0,0,-1,2147483647,0,2147483647,0,2147483647,0,0,-1,-1,2147483647,2147483647,0,-1,0,0,-1,-1,-1,2147483647,0,2147483647,-1,0,-1,-1,0,-1,2147483647,-1,0,0,0,0,-1,0,2147483647,0,0,-1,0,2147483647,2147483647,0,2147483647,-1,0,2147483647,2147483647,0,0,-1,-1,2147483647,-1,0,2147483647,2147483647,-1,2147483647,2147483647,2147483647,0,0,-1,0,0,0,0,2147483647,2147483647,-1,0,0,2147483647,0,2147483647,0,-1,2147483647,2147483647,2147483647,0,0,2147483647,0,0,0,0,2147483647,2147483647,2147483647,2147483647,0,0,0,0,-1,0,-1,2147483647,2147483647,0,-1,-1,-1,-1,2147483647,0,2147483647,-1,-1,0,2147483647,-1,0,0,2147483647,0,0,0,-1,2147483647,2147483647,-1,0,2147483647,0,0,0,2147483647,2147483647,-1,-1,-1,0,0,2147483647,2147483647,2147483647,2147483647,-1,0,0,2147483647,-1,0,-1,0,2147483647,-1,-1,2147483647,2147483647,0,-1,-1,-1,-1,2147483647,0,-1,2147483647,-1,2147483647,0,2147483647,0,2147483647,2147483647,0,-1,0,0,-1,2147483647,2147483647,0},{-1,0,0,-1,0,0,-1,2147483647,-1,2147483647,0,2147483647,0,2147483647,0,-1,2147483647,2147483647,2147483647,2147483647,2147483647,-1,2147483647,0,0,0,0,0,2147483647,2147483647,2147483647,2147483647,0,0,-1,0,0,-1,0,0,0,-1,2147483647,0,2147483647,0,-1,-1,-1,-1,2147483647,-1,2147483647,2147483647,2147483647,-1,-1,2147483647,0,0,0,0,0,0,0,-1,2147483647,2147483647,0,0,0,0,-1,2147483647,2147483647,0,2147483647,2147483647,0,-1,2147483647,-1,0,2147483647,0,0,0,2147483647,0,-1,0,0,-1,-1,0,0,0,2147483647,2147483647,-1,-1,-1,-1,2147483647,0,0,-1,-1,2147483647,-1,-1,2147483647,2147483647,0,0,2147483647,-1,2147483647,2147483647,-1,0,-1,0,0,-1,2147483647,-1,2147483647,2147483647,0,0,2147483647,0,2147483647,-1,0,2147483647,2147483647,0,0,-1,0,0,0,-1,2147483647,2147483647,2147483647,-1,2147483647,0,0,2147483647,2147483647,2147483647,0,2147483647,2147483647,2147483647,-1,-1,0,0,0,-1,0,2147483647,2147483647,2147483647,0,2147483647,-1,0,2147483647,2147483647,2147483647,-1,-1,2147483647,2147483647,2147483647,0,-1,2147483647,0,-1,2147483647,-1,2147483647,2147483647,-1,2147483647,-1,0,2147483647,2147483647,-1,-1,-1,-1,2147483647,0,0,0,-1,0,0,-1,2147483647,-1,-1,-1,-1,-1,-1,0,2147483647,2147483647,-1,2147483647,0},{2147483647,-1,0,0,2147483647,-1,-1,-1,0,0,0,-1,0,0,-1,-1,-1,2147483647,2147483647,0,-1,2147483647,0,-1,2147483647,0,-1,2147483647,-1,0,0,0,-1,2147483647,2147483647,2147483647,2147483647,0,0,0,-1,-1,0,2147483647,2147483647,0,0,0,0,0,-1,-1,-1,2147483647,2147483647,2147483647,0,-1,-1,0,2147483647,2147483647,2147483647,-1,0,2147483647,0,0,2147483647,2147483647,0,2147483647,-1,2147483647,2147483647,2147483647,2147483647,2147483647,0,2147483647,-1,2147483647,2147483647,2147483647,2147483647,2147483647,-1,2147483647,-1,0,2147483647,0,0,-1,2147483647,2147483647,2147483647,2147483647,0,0,2147483647,-1,-1,0,2147483647,-1,-1,2147483647,-1,-1,2147483647,0,-1,-1,-1,-1,-1,-1,0,0,2147483647,2147483647,0,0,-1,-1,-1,0,0,0,2147483647,2147483647,2147483647,0,2147483647,0,2147483647,2147483647,0,0,0,0,2147483647,-1,2147483647,0,2147483647,-1,2147483647,0,0,0,-1,2147483647,2147483647,-1,2147483647,0,0,2147483647,-1,0,0,-1,0,2147483647,2147483647,-1,2147483647,2147483647,-1,2147483647,2147483647,2147483647,0,2147483647,0,-1,0,-1,0,0,2147483647,0,2147483647,-1,2147483647,-1,0,0,-1,-1,0,2147483647,0,-1,-1,-1,0,0,0,2147483647,0,2147483647,-1,2147483647,2147483647,-1,-1,-1,0,0,2147483647,2147483647,2147483647,2147483647,2147483647,-1,-1,0,0},{-1,-1,-1,2147483647,0,-1,0,0,2147483647,2147483647,0,2147483647,-1,0,0,2147483647,2147483647,2147483647,-1,2147483647,-1,0,0,0,0,0,-1,0,-1,0,2147483647,2147483647,0,2147483647,-1,2147483647,0,2147483647,0,0,0,0,0,-1,-1,0,-1,2147483647,-1,2147483647,2147483647,2147483647,2147483647,2147483647,0,2147483647,0,-1,-1,2147483647,0,0,0,-1,-1,-1,0,2147483647,2147483647,-1,2147483647,2147483647,-1,2147483647,-1,2147483647,2147483647,2147483647,0,-1,-1,-1,0,-1,-1,0,-1,0,0,2147483647,0,2147483647,2147483647,0,2147483647,-1,-1,0,-1,-1,-1,-1,2147483647,0,0,2147483647,-1,0,-1,0,-1,-1,0,0,0,2147483647,2147483647,-1,2147483647,-1,0,2147483647,2147483647,0,2147483647,-1,2147483647,0,0,0,-1,2147483647,0,-1,0,2147483647,2147483647,2147483647,2147483647,0,2147483647,-1,-1,2147483647,2147483647,0,-1,2147483647,2147483647,0,0,-1,-1,0,2147483647,-1,-1,-1,2147483647,2147483647,0,2147483647,-1,0,-1,2147483647,2147483647,-1,2147483647,2147483647,0,2147483647,2147483647,2147483647,2147483647,0,2147483647,0,-1,-1,-1,0,2147483647,-1,-1,0,-1,-1,-1,2147483647,-1,0,2147483647,-1,2147483647,0,-1,0,0,-1,0,0,-1,-1,0,-1,-1,2147483647,0,-1,-1,0,2147483647,-1,-1,0,-1,2147483647,2147483647,-1,-1},{0,0,0,2147483647,-1,-1,2147483647,0,0,0,-1,-1,2147483647,-1,-1,-1,-1,0,2147483647,2147483647,-1,-1,0,-1,2147483647,2147483647,-1,-1,-1,0,0,2147483647,2147483647,2147483647,0,0,0,0,-1,0,-1,0,-1,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,-1,-1,0,-1,-1,-1,-1,2147483647,2147483647,-1,-1,0,2147483647,0,-1,0,-1,-1,0,2147483647,-1,2147483647,-1,0,-1,2147483647,2147483647,0,-1,0,-1,-1,-1,-1,-1,-1,0,0,2147483647,0,-1,-1,-1,-1,2147483647,0,0,2147483647,0,-1,0,0,0,0,0,0,0,-1,0,2147483647,2147483647,2147483647,-1,2147483647,-1,2147483647,2147483647,0,0,0,0,0,-1,2147483647,0,2147483647,-1,0,-1,-1,-1,2147483647,2147483647,-1,2147483647,0,0,-1,0,2147483647,-1,0,0,-1,0,-1,0,0,0,-1,-1,-1,2147483647,2147483647,-1,2147483647,2147483647,-1,0,0,2147483647,-1,-1,-1,0,-1,-1,2147483647,-1,0,-1,0,2147483647,-1,0,2147483647,0,2147483647,0,-1,-1,-1,0,0,-1,0,2147483647,2147483647,2147483647,-1,0,0,2147483647,-1,-1,0,2147483647,2147483647,2147483647,0,-1,-1,0,0,0,-1,-1,-1,2147483647,0,-1,2147483647,2147483647,-1,0,-1,2147483647,2147483647,-1,0,0,-1},{-1,0,2147483647,-1,-1,0,2147483647,0,2147483647,2147483647,-1,2147483647,2147483647,-1,0,2147483647,0,-1,-1,-1,-1,-1,-1,-1,0,-1,-1,0,2147483647,0,-1,2147483647,2147483647,0,0,-1,-1,2147483647,0,2147483647,0,2147483647,-1,-1,0,-1,-1,2147483647,2147483647,2147483647,-1,0,0,-1,2147483647,2147483647,-1,0,2147483647,-1,2147483647,2147483647,0,-1,2147483647,2147483647,-1,-1,2147483647,2147483647,-1,0,2147483647,2147483647,2147483647,2147483647,2147483647,-1,0,-1,2147483647,0,-1,0,0,2147483647,0,-1,-1,0,0,-1,-1,-1,0,0,0,2147483647,0,0,0,-1,0,0,0,-1,-1,-1,-1,0,2147483647,0,-1,0,-1,2147483647,-1,0,-1,2147483647,-1,0,0,-1,-1,-1,2147483647,0,-1,-1,2147483647,-1,2147483647,2147483647,2147483647,2147483647,-1,0,0,2147483647,0,2147483647,-1,0,2147483647,-1,2147483647,2147483647,0,2147483647,2147483647,-1,-1,2147483647,-1,-1,-1,-1,0,2147483647,0,0,-1,2147483647,-1,0,0,2147483647,0,0,-1,0,2147483647,2147483647,-1,0,-1,0,0,2147483647,0,2147483647,0,0,0,-1,2147483647,0,2147483647,-1,0,2147483647,-1,0,0,-1,2147483647,2147483647,-1,-1,2147483647,0,2147483647,2147483647,2147483647,-1,2147483647,-1,0,2147483647,-1,0,-1,0,0,2147483647,0,0,0,0,-1},{2147483647,-1,0,2147483647,-1,-1,2147483647,-1,-1,2147483647,0,-1,-1,0,2147483647,2147483647,2147483647,0,2147483647,0,0,0,2147483647,-1,-1,0,2147483647,-1,0,-1,2147483647,2147483647,2147483647,2147483647,0,-1,-1,-1,-1,0,0,2147483647,-1,-1,2147483647,2147483647,-1,0,-1,-1,0,2147483647,0,0,0,2147483647,2147483647,2147483647,-1,0,-1,0,2147483647,-1,2147483647,2147483647,2147483647,0,2147483647,-1,2147483647,0,2147483647,2147483647,0,2147483647,-1,2147483647,0,0,-1,-1,-1,2147483647,-1,2147483647,0,-1,2147483647,0,2147483647,2147483647,-1,2147483647,0,2147483647,-1,0,2147483647,0,-1,-1,0,0,2147483647,-1,-1,0,-1,2147483647,0,2147483647,-1,-1,-1,0,-1,-1,0,-1,2147483647,2147483647,2147483647,0,-1,0,0,2147483647,-1,0,2147483647,2147483647,-1,2147483647,-1,2147483647,2147483647,-1,-1,-1,0,0,2147483647,2147483647,-1,2147483647,2147483647,2147483647,2147483647,-1,2147483647,-1,0,2147483647,2147483647,2147483647,2147483647,0,0,2147483647,0,0,-1,2147483647,2147483647,2147483647,2147483647,0,0,2147483647,0,2147483647,2147483647,0,-1,0,-1,0,0,2147483647,0,2147483647,2147483647,-1,0,-1,2147483647,0,0,2147483647,-1,-1,-1,0,-1,0,-1,2147483647,2147483647,0,-1,2147483647,0,-1,0,0,-1,-1,0,2147483647,2147483647,2147483647,2147483647,-1,2147483647,2147483647,0,-1,-1,0,2147483647},{2147483647,0,-1,0,2147483647,-1,2147483647,0,-1,0,2147483647,-1,0,-1,-1,2147483647,2147483647,2147483647,-1,0,2147483647,-1,-1,0,2147483647,-1,0,-1,-1,0,-1,-1,2147483647,2147483647,-1,-1,-1,0,0,2147483647,2147483647,2147483647,2147483647,-1,0,-1,0,2147483647,2147483647,-1,2147483647,2147483647,-1,2147483647,0,2147483647,0,0,-1,0,0,0,0,2147483647,0,0,2147483647,0,-1,2147483647,-1,2147483647,-1,0,0,-1,2147483647,-1,-1,2147483647,-1,2147483647,0,-1,2147483647,-1,0,-1,0,2147483647,0,-1,0,-1,0,2147483647,2147483647,-1,-1,2147483647,0,2147483647,0,2147483647,2147483647,2147483647,-1,-1,2147483647,0,2147483647,0,0,-1,0,0,0,0,2147483647,-1,-1,0,2147483647,0,-1,-1,2147483647,0,-1,-1,0,0,2147483647,2147483647,0,-1,2147483647,2147483647,0,2147483647,-1,-1,0,2147483647,2147483647,2147483647,2147483647,0,-1,0,0,0,-1,-1,0,2147483647,-1,0,-1,2147483647,2147483647,2147483647,0,-1,0,0,-1,-1,2147483647,-1,2147483647,0,0,2147483647,2147483647,0,2147483647,2147483647,0,0,-1,2147483647,2147483647,-1,2147483647,0,0,2147483647,0,0,0,2147483647,-1,-1,-1,0,-1,0,0,0,2147483647,-1,-1,-1,2147483647,0,0,0,-1,-1,0,-1,-1,-1,0,-1,2147483647,-1,-1,0,-1},{-1,0,-1,2147483647,2147483647,-1,2147483647,0,0,2147483647,-1,0,-1,0,-1,-1,0,0,0,-1,2147483647,0,0,-1,2147483647,0,2147483647,-1,-1,-1,-1,0,0,0,2147483647,2147483647,-1,0,2147483647,0,-1,0,-1,0,-1,0,2147483647,-1,0,-1,0,-1,-1,-1,2147483647,2147483647,0,-1,0,0,-1,-1,0,0,-1,-1,0,2147483647,0,2147483647,2147483647,-1,0,2147483647,-1,2147483647,0,0,0,0,-1,0,0,0,-1,2147483647,-1,-1,0,2147483647,-1,0,-1,0,0,0,2147483647,-1,2147483647,2147483647,2147483647,0,2147483647,2147483647,0,0,0,-1,2147483647,2147483647,2147483647,0,-1,0,2147483647,2147483647,-1,-1,0,0,2147483647,2147483647,-1,0,-1,2147483647,2147483647,0,-1,0,2147483647,2147483647,-1,-1,2147483647,-1,0,-1,2147483647,2147483647,2147483647,2147483647,-1,2147483647,-1,0,-1,2147483647,2147483647,-1,-1,-1,2147483647,0,2147483647,-1,0,0,-1,2147483647,0,2147483647,2147483647,0,-1,-1,-1,0,0,2147483647,0,0,2147483647,0,-1,-1,2147483647,-1,0,-1,-1,-1,-1,0,2147483647,-1,0,2147483647,-1,2147483647,0,-1,2147483647,0,0,0,0,2147483647,-1,0,0,-1,0,-1,-1,2147483647,2147483647,-1,0,0,-1,-1,2147483647,0,0,2147483647,0,0,0,0,0},{0,2147483647,-1,0,0,2147483647,2147483647,-1,0,0,0,2147483647,2147483647,2147483647,2147483647,2147483647,0,-1,-1,0,2147483647,0,-1,0,0,2147483647,0,2147483647,0,2147483647,2147483647,-1,2147483647,2147483647,-1,0,2147483647,0,-1,2147483647,0,2147483647,0,2147483647,-1,-1,0,-1,-1,-1,-1,0,0,2147483647,-1,0,-1,2147483647,0,-1,2147483647,-1,2147483647,2147483647,2147483647,-1,2147483647,2147483647,0,0,-1,0,-1,2147483647,-1,2147483647,2147483647,2147483647,2147483647,-1,2147483647,0,-1,-1,2147483647,2147483647,2147483647,2147483647,-1,-1,0,0,-1,2147483647,0,0,-1,-1,-1,-1,-1,0,2147483647,2147483647,2147483647,0,0,-1,0,2147483647,-1,2147483647,-1,-1,-1,-1,-1,-1,2147483647,-1,0,0,2147483647,-1,-1,-1,0,2147483647,0,-1,2147483647,2147483647,-1,0,0,-1,-1,0,-1,2147483647,2147483647,-1,-1,0,-1,-1,2147483647,-1,0,-1,2147483647,-1,-1,2147483647,-1,-1,2147483647,0,0,-1,0,-1,0,2147483647,0,-1,0,-1,-1,0,2147483647,-1,2147483647,0,0,0,0,2147483647,2147483647,-1,2147483647,0,2147483647,-1,0,2147483647,-1,0,-1,-1,2147483647,0,-1,-1,-1,0,0,2147483647,0,2147483647,-1,-1,2147483647,-1,2147483647,0,0,-1,0,2147483647,2147483647,0,0,0,0,-1,2147483647,-1,-1,-1,0},{2147483647,-1,0,2147483647,2147483647,0,2147483647,-1,2147483647,0,-1,-1,-1,2147483647,0,-1,-1,0,-1,2147483647,0,-1,2147483647,-1,0,0,0,2147483647,2147483647,2147483647,-1,-1,-1,-1,0,2147483647,0,0,-1,2147483647,-1,0,-1,-1,2147483647,0,0,0,-1,-1,2147483647,0,2147483647,2147483647,-1,0,0,0,0,0,-1,0,0,2147483647,2147483647,2147483647,-1,0,-1,-1,2147483647,-1,-1,-1,0,2147483647,0,2147483647,2147483647,2147483647,-1,0,-1,0,-1,0,0,-1,0,2147483647,-1,0,2147483647,-1,0,2147483647,0,0,0,2147483647,2147483647,0,0,0,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,-1,-1,2147483647,0,-1,-1,2147483647,2147483647,2147483647,2147483647,-1,2147483647,2147483647,0,-1,0,0,0,0,0,-1,-1,-1,0,0,2147483647,0,0,2147483647,0,0,-1,0,-1,-1,0,0,-1,-1,2147483647,2147483647,0,0,-1,0,0,0,-1,2147483647,-1,-1,2147483647,2147483647,2147483647,2147483647,-1,-1,0,2147483647,2147483647,0,-1,0,0,-1,-1,0,2147483647,-1,-1,2147483647,0,0,2147483647,2147483647,-1,-1,0,2147483647,0,2147483647,0,0,2147483647,-1,-1,-1,-1,-1,-1,0,-1,0,-1,2147483647,2147483647,2147483647,0,-1,2147483647,2147483647,2147483647,2147483647,2147483647,0,0,-1,0,-1,0,-1},{2147483647,2147483647,2147483647,0,-1,0,2147483647,-1,2147483647,2147483647,0,2147483647,2147483647,2147483647,-1,-1,0,0,2147483647,2147483647,2147483647,2147483647,2147483647,0,-1,2147483647,-1,-1,2147483647,0,0,0,0,0,-1,0,-1,2147483647,0,0,-1,-1,2147483647,2147483647,0,0,0,0,2147483647,2147483647,-1,-1,0,2147483647,-1,-1,0,2147483647,-1,-1,0,0,2147483647,2147483647,2147483647,2147483647,0,0,0,2147483647,0,-1,-1,-1,2147483647,2147483647,2147483647,2147483647,-1,-1,-1,2147483647,-1,-1,-1,2147483647,-1,-1,-1,0,0,0,0,0,2147483647,-1,-1,2147483647,2147483647,0,0,0,-1,0,-1,2147483647,0,2147483647,2147483647,0,0,-1,2147483647,0,2147483647,2147483647,2147483647,0,2147483647,0,0,0,2147483647,-1,2147483647,0,-1,-1,-1,-1,0,-1,-1,2147483647,-1,2147483647,0,-1,0,0,2147483647,0,-1,-1,2147483647,0,0,2147483647,-1,-1,0,2147483647,-1,2147483647,2147483647,0,-1,-1,-1,2147483647,-1,-1,-1,2147483647,2147483647,2147483647,-1,0,-1,-1,0,-1,-1,-1,0,2147483647,-1,0,2147483647,0,0,2147483647,2147483647,-1,2147483647,0,0,0,-1,-1,-1,2147483647,-1,-1,2147483647,-1,2147483647,2147483647,0,0,0,2147483647,2147483647,0,0,0,0,0,0,-1,-1,-1,2147483647,0,0,0,-1,-1,0,0,2147483647},{-1,-1,2147483647,-1,0,2147483647,-1,0,0,2147483647,-1,0,-1,0,0,-1,2147483647,0,0,-1,0,0,-1,-1,-1,0,2147483647,2147483647,0,-1,-1,0,-1,0,2147483647,-1,-1,2147483647,-1,2147483647,0,2147483647,0,0,0,2147483647,-1,-1,-1,2147483647,2147483647,-1,0,0,0,-1,2147483647,-1,-1,0,2147483647,-1,2147483647,-1,-1,-1,-1,-1,-1,2147483647,2147483647,2147483647,2147483647,0,0,0,2147483647,0,0,-1,2147483647,0,2147483647,-1,0,2147483647,0,0,0,2147483647,0,2147483647,-1,-1,0,-1,0,2147483647,0,-1,-1,0,0,2147483647,-1,0,0,0,-1,-1,-1,-1,0,2147483647,2147483647,-1,0,0,0,2147483647,-1,0,2147483647,-1,2147483647,0,2147483647,-1,-1,-1,2147483647,0,2147483647,-1,0,2147483647,2147483647,0,-1,2147483647,2147483647,-1,2147483647,0,2147483647,-1,0,0,2147483647,2147483647,0,0,0,0,-1,0,-1,2147483647,0,0,0,-1,2147483647,-1,-1,0,2147483647,2147483647,0,2147483647,-1,-1,0,2147483647,0,2147483647,-1,-1,-1,-1,0,0,-1,-1,-1,-1,0,2147483647,-1,0,2147483647,2147483647,0,0,-1,0,0,-1,-1,0,-1,-1,2147483647,0,2147483647,-1,2147483647,2147483647,2147483647,-1,0,2147483647,-1,-1,2147483647,-1,-1,0,2147483647,0,0},{-1,-1,0,0,2147483647,0,2147483647,0,0,-1,2147483647,-1,-1,0,2147483647,0,-1,0,0,2147483647,-1,0,2147483647,2147483647,0,0,2147483647,0,2147483647,0,-1,-1,-1,2147483647,0,2147483647,-1,2147483647,0,-1,-1,-1,0,-1,-1,2147483647,2147483647,0,2147483647,2147483647,-1,2147483647,0,2147483647,0,0,-1,-1,0,-1,2147483647,0,0,2147483647,0,-1,0,-1,2147483647,0,0,2147483647,-1,2147483647,-1,0,2147483647,-1,0,2147483647,0,2147483647,0,-1,0,-1,0,2147483647,2147483647,0,2147483647,2147483647,0,2147483647,0,0,0,2147483647,-1,-1,-1,0,0,2147483647,0,-1,-1,-1,2147483647,2147483647,0,2147483647,-1,2147483647,-1,-1,0,-1,-1,-1,0,-1,-1,2147483647,0,2147483647,2147483647,2147483647,0,0,-1,2147483647,-1,0,-1,2147483647,2147483647,0,0,-1,0,-1,2147483647,0,0,0,0,0,-1,2147483647,0,2147483647,0,-1,2147483647,-1,-1,-1,0,-1,-1,-1,-1,-1,-1,-1,0,2147483647,2147483647,2147483647,0,0,-1,2147483647,-1,-1,0,2147483647,0,0,-1,-1,2147483647,2147483647,-1,0,0,-1,2147483647,0,0,2147483647,-1,-1,2147483647,2147483647,-1,0,0,0,2147483647,-1,0,0,-1,-1,-1,2147483647,0,-1,0,-1,-1,0,0,-1,2147483647,2147483647,2147483647,0,2147483647},{0,2147483647,0,-1,-1,0,2147483647,2147483647,-1,0,-1,0,0,0,-1,2147483647,-1,2147483647,-1,0,0,0,0,-1,0,2147483647,0,0,-1,2147483647,-1,-1,-1,0,-1,-1,2147483647,0,2147483647,2147483647,0,0,2147483647,2147483647,-1,-1,2147483647,2147483647,0,2147483647,2147483647,-1,0,0,-1,0,-1,0,2147483647,2147483647,0,-1,-1,2147483647,0,-1,0,-1,0,2147483647,2147483647,2147483647,2147483647,-1,0,-1,2147483647,2147483647,-1,0,0,2147483647,2147483647,-1,2147483647,2147483647,-1,-1,2147483647,2147483647,0,0,-1,-1,2147483647,2147483647,-1,0,2147483647,2147483647,-1,2147483647,2147483647,0,2147483647,-1,0,2147483647,0,2147483647,2147483647,2147483647,-1,-1,0,0,0,0,2147483647,-1,2147483647,-1,0,2147483647,2147483647,2147483647,2147483647,0,0,-1,-1,0,0,2147483647,-1,0,2147483647,0,2147483647,0,-1,-1,0,0,2147483647,2147483647,-1,0,-1,0,2147483647,2147483647,2147483647,0,2147483647,-1,2147483647,0,-1,0,0,0,2147483647,-1,-1,2147483647,2147483647,0,0,-1,2147483647,-1,2147483647,-1,2147483647,0,0,0,2147483647,0,0,-1,-1,-1,2147483647,2147483647,2147483647,-1,0,0,-1,0,0,0,0,0,2147483647,-1,2147483647,2147483647,0,0,2147483647,0,-1,2147483647,0,2147483647,-1,-1,2147483647,0,-1,2147483647,0,2147483647,0,-1,2147483647,-1,2147483647},{2147483647,-1,2147483647,2147483647,2147483647,0,-1,2147483647,-1,2147483647,0,2147483647,2147483647,2147483647,0,2147483647,2147483647,-1,2147483647,-1,0,0,-1,2147483647,2147483647,0,-1,0,-1,-1,-1,-1,0,2147483647,-1,0,2147483647,-1,2147483647,-1,-1,2147483647,-1,0,-1,-1,-1,0,-1,-1,-1,-1,0,2147483647,2147483647,-1,0,2147483647,-1,-1,2147483647,0,2147483647,-1,2147483647,0,2147483647,0,-1,2147483647,0,-1,2147483647,2147483647,0,2147483647,0,0,2147483647,2147483647,2147483647,2147483647,0,0,-1,2147483647,-1,0,-1,2147483647,2147483647,0,-1,-1,0,0,2147483647,-1,2147483647,2147483647,0,-1,-1,0,2147483647,2147483647,2147483647,2147483647,-1,2147483647,2147483647,2147483647,0,-1,-1,2147483647,2147483647,2147483647,-1,-1,0,2147483647,-1,0,2147483647,-1,-1,-1,0,0,0,2147483647,-1,-1,0,-1,0,2147483647,2147483647,2147483647,-1,-1,2147483647,-1,0,-1,0,0,0,0,2147483647,2147483647,-1,2147483647,-1,0,0,-1,2147483647,0,-1,0,0,2147483647,2147483647,-1,0,-1,0,-1,-1,0,2147483647,-1,0,-1,-1,2147483647,-1,2147483647,2147483647,-1,2147483647,0,0,0,0,2147483647,0,2147483647,0,2147483647,2147483647,2147483647,-1,2147483647,-1,2147483647,2147483647,0,-1,0,-1,0,0,-1,2147483647,2147483647,2147483647,0,-1,0,2147483647,0,-1,2147483647,2147483647,-1,2147483647,2147483647,0},{0,2147483647,-1,0,-1,-1,2147483647,2147483647,2147483647,2147483647,0,0,2147483647,-1,0,-1,0,0,0,0,0,0,2147483647,2147483647,-1,-1,0,0,0,2147483647,2147483647,-1,-1,2147483647,2147483647,0,-1,0,2147483647,-1,2147483647,-1,2147483647,0,0,0,0,2147483647,-1,2147483647,2147483647,2147483647,-1,2147483647,-1,-1,-1,0,2147483647,0,2147483647,0,0,0,2147483647,2147483647,-1,-1,0,2147483647,2147483647,-1,-1,0,2147483647,2147483647,0,-1,2147483647,-1,-1,0,2147483647,0,0,-1,2147483647,0,0,2147483647,-1,-1,2147483647,0,2147483647,0,-1,-1,2147483647,0,0,-1,2147483647,0,2147483647,2147483647,0,-1,2147483647,0,-1,2147483647,-1,-1,-1,2147483647,-1,2147483647,0,2147483647,2147483647,0,2147483647,2147483647,2147483647,-1,0,0,-1,-1,2147483647,0,0,-1,0,-1,-1,2147483647,0,0,-1,-1,0,-1,0,2147483647,2147483647,0,0,0,-1,2147483647,0,0,2147483647,2147483647,0,-1,0,2147483647,0,-1,0,2147483647,0,-1,2147483647,-1,0,2147483647,2147483647,0,0,2147483647,2147483647,0,2147483647,0,0,0,2147483647,-1,0,0,2147483647,2147483647,2147483647,0,0,-1,2147483647,-1,-1,0,2147483647,-1,-1,0,0,2147483647,2147483647,-1,-1,2147483647,0,2147483647,2147483647,-1,0,0,2147483647,2147483647,-1,0,-1,0,0,0,-1,2147483647,2147483647},{0,2147483647,0,0,-1,0,2147483647,0,-1,-1,0,0,-1,2147483647,0,0,2147483647,2147483647,0,-1,-1,2147483647,-1,0,0,-1,-1,0,2147483647,-1,-1,-1,2147483647,2147483647,-1,0,0,2147483647,2147483647,0,0,-1,-1,-1,2147483647,2147483647,0,-1,2147483647,2147483647,2147483647,0,0,0,2147483647,2147483647,0,2147483647,0,0,-1,-1,0,2147483647,0,0,0,-1,0,-1,-1,2147483647,0,-1,-1,0,-1,0,-1,2147483647,0,-1,2147483647,2147483647,-1,0,0,2147483647,2147483647,2147483647,-1,0,-1,-1,-1,2147483647,2147483647,0,0,2147483647,-1,0,-1,0,-1,2147483647,2147483647,-1,0,2147483647,2147483647,0,0,-1,2147483647,2147483647,-1,2147483647,2147483647,0,-1,2147483647,-1,0,2147483647,0,2147483647,0,2147483647,2147483647,0,-1,-1,0,-1,2147483647,-1,2147483647,2147483647,0,-1,-1,2147483647,0,0,2147483647,2147483647,-1,2147483647,0,-1,-1,0,-1,2147483647,-1,-1,2147483647,2147483647,0,-1,-1,2147483647,2147483647,0,-1,-1,-1,-1,2147483647,2147483647,0,-1,2147483647,0,2147483647,-1,2147483647,0,0,0,2147483647,-1,2147483647,-1,0,2147483647,-1,0,-1,2147483647,2147483647,2147483647,2147483647,0,2147483647,2147483647,-1,-1,2147483647,2147483647,-1,0,0,-1,2147483647,2147483647,-1,2147483647,2147483647,-1,0,-1,2147483647,0,2147483647,-1,-1,2147483647,-1,-1},{2147483647,0,-1,2147483647,0,-1,0,0,-1,0,2147483647,2147483647,2147483647,-1,2147483647,2147483647,-1,-1,2147483647,2147483647,0,2147483647,0,0,-1,0,2147483647,-1,0,-1,-1,0,2147483647,0,2147483647,2147483647,2147483647,0,2147483647,0,2147483647,2147483647,0,-1,0,-1,0,2147483647,0,2147483647,-1,2147483647,-1,2147483647,0,0,2147483647,-1,0,0,0,-1,2147483647,0,-1,2147483647,0,-1,-1,-1,0,2147483647,-1,2147483647,2147483647,2147483647,0,0,-1,0,-1,2147483647,-1,2147483647,2147483647,0,0,-1,-1,0,0,2147483647,-1,0,2147483647,2147483647,-1,-1,2147483647,2147483647,-1,2147483647,2147483647,2147483647,0,2147483647,2147483647,2147483647,2147483647,2147483647,0,-1,-1,0,2147483647,2147483647,0,-1,-1,-1,-1,0,-1,2147483647,2147483647,2147483647,2147483647,-1,2147483647,2147483647,-1,0,-1,0,0,0,2147483647,0,2147483647,-1,-1,0,0,-1,0,0,-1,-1,2147483647,-1,2147483647,-1,-1,0,2147483647,2147483647,-1,0,-1,0,2147483647,0,2147483647,0,2147483647,2147483647,2147483647,-1,-1,-1,2147483647,2147483647,-1,-1,2147483647,2147483647,-1,-1,-1,2147483647,-1,0,-1,-1,2147483647,0,0,-1,0,-1,2147483647,0,-1,2147483647,2147483647,0,2147483647,0,0,0,-1,2147483647,2147483647,0,2147483647,2147483647,-1,-1,2147483647,2147483647,0,-1,-1,2147483647,2147483647,-1,2147483647,0,-1,2147483647,-1},{2147483647,0,0,2147483647,-1,2147483647,2147483647,-1,0,2147483647,2147483647,2147483647,-1,2147483647,0,2147483647,2147483647,0,-1,2147483647,0,-1,-1,0,2147483647,0,-1,-1,-1,2147483647,2147483647,2147483647,2147483647,0,2147483647,-1,0,-1,-1,2147483647,-1,-1,-1,0,2147483647,0,2147483647,-1,0,0,2147483647,0,0,-1,2147483647,-1,0,2147483647,2147483647,-1,0,0,-1,2147483647,-1,0,2147483647,-1,0,-1,-1,0,-1,2147483647,0,0,0,2147483647,2147483647,2147483647,-1,0,0,-1,2147483647,0,2147483647,0,0,0,0,-1,2147483647,0,2147483647,2147483647,-1,0,0,0,0,2147483647,-1,2147483647,2147483647,2147483647,2147483647,0,-1,0,2147483647,2147483647,-1,2147483647,0,2147483647,0,0,0,0,-1,-1,0,0,2147483647,2147483647,-1,0,0,0,0,0,-1,-1,2147483647,2147483647,2147483647,2147483647,0,2147483647,-1,2147483647,2147483647,-1,2147483647,0,2147483647,0,0,-1,-1,-1,-1,-1,0,-1,0,-1,2147483647,0,-1,2147483647,-1,-1,-1,0,-1,0,2147483647,-1,-1,2147483647,0,0,-1,2147483647,2147483647,-1,0,-1,2147483647,2147483647,-1,2147483647,-1,-1,-1,0,2147483647,2147483647,2147483647,-1,0,2147483647,0,2147483647,0,-1,0,-1,2147483647,2147483647,0,0,-1,0,2147483647,0,-1,2147483647,2147483647,0,-1,0,-1,0,-1,0,0,-1,2147483647},{2147483647,2147483647,0,2147483647,-1,0,0,0,-1,-1,0,0,2147483647,0,2147483647,-1,2147483647,2147483647,-1,0,-1,-1,-1,-1,0,2147483647,0,2147483647,0,-1,-1,2147483647,0,2147483647,-1,2147483647,0,2147483647,-1,-1,0,2147483647,0,-1,-1,-1,-1,-1,0,2147483647,0,-1,0,0,2147483647,0,-1,-1,0,-1,2147483647,-1,0,0,0,0,-1,0,0,2147483647,-1,2147483647,2147483647,0,-1,-1,0,-1,-1,0,0,0,2147483647,-1,0,0,-1,2147483647,0,0,2147483647,0,-1,-1,0,-1,0,2147483647,-1,-1,-1,-1,-1,0,-1,-1,2147483647,0,2147483647,2147483647,-1,0,0,-1,-1,-1,-1,0,-1,-1,-1,2147483647,-1,-1,-1,-1,0,0,2147483647,0,0,-1,0,-1,0,2147483647,2147483647,0,-1,0,2147483647,0,0,-1,0,-1,0,2147483647,2147483647,-1,0,2147483647,0,0,2147483647,-1,-1,-1,0,-1,0,-1,2147483647,-1,0,0,2147483647,0,2147483647,-1,-1,0,2147483647,-1,2147483647,0,-1,2147483647,2147483647,0,-1,0,-1,0,-1,0,-1,0,0,0,-1,0,2147483647,2147483647,0,-1,-1,2147483647,-1,-1,0,2147483647,0,2147483647,-1,0,0,0,2147483647,-1,0,0,-1,-1,2147483647,-1,-1,0,-1,2147483647,2147483647},{0,2147483647,-1,-1,-1,2147483647,-1,-1,-1,0,2147483647,-1,2147483647,-1,0,0,2147483647,2147483647,0,2147483647,-1,2147483647,0,2147483647,0,-1,-1,-1,0,0,0,2147483647,2147483647,0,2147483647,0,2147483647,2147483647,2147483647,0,2147483647,-1,0,2147483647,-1,0,-1,-1,2147483647,0,2147483647,-1,0,2147483647,0,-1,2147483647,0,2147483647,2147483647,0,0,0,2147483647,2147483647,0,2147483647,2147483647,2147483647,0,-1,-1,2147483647,2147483647,-1,2147483647,2147483647,0,0,-1,-1,-1,0,-1,0,0,2147483647,2147483647,0,-1,-1,0,2147483647,0,0,0,0,-1,-1,0,2147483647,2147483647,2147483647,0,0,2147483647,0,-1,2147483647,2147483647,-1,-1,0,2147483647,2147483647,0,0,-1,0,-1,-1,-1,2147483647,2147483647,0,-1,-1,0,2147483647,2147483647,2147483647,0,2147483647,-1,2147483647,2147483647,0,2147483647,-1,-1,0,-1,0,2147483647,-1,-1,2147483647,-1,-1,2147483647,0,0,0,0,0,2147483647,2147483647,0,-1,0,-1,-1,2147483647,-1,-1,-1,2147483647,-1,-1,-1,2147483647,-1,-1,0,2147483647,-1,0,2147483647,2147483647,0,2147483647,0,-1,-1,2147483647,-1,0,-1,0,-1,-1,0,0,0,-1,0,2147483647,-1,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,-1,-1,0,-1,2147483647,-1,0,2147483647,0,2147483647,2147483647,0,0,0,2147483647},{2147483647,-1,-1,2147483647,0,2147483647,-1,-1,0,-1,2147483647,2147483647,-1,2147483647,0,0,2147483647,2147483647,0,0,-1,-1,0,-1,-1,-1,0,2147483647,0,2147483647,-1,0,2147483647,0,-1,-1,-1,0,0,2147483647,-1,2147483647,2147483647,-1,-1,-1,0,0,2147483647,2147483647,2147483647,-1,0,-1,-1,-1,-1,2147483647,0,-1,0,0,2147483647,0,-1,-1,2147483647,2147483647,2147483647,2147483647,0,2147483647,-1,2147483647,0,-1,2147483647,0,2147483647,0,-1,2147483647,2147483647,0,-1,-1,0,0,-1,2147483647,0,2147483647,2147483647,-1,0,-1,-1,-1,2147483647,2147483647,-1,-1,0,2147483647,2147483647,-1,-1,-1,-1,-1,0,-1,2147483647,0,2147483647,0,-1,0,0,0,-1,0,2147483647,0,2147483647,-1,-1,-1,-1,0,2147483647,0,-1,0,2147483647,2147483647,-1,-1,2147483647,0,-1,0,0,2147483647,-1,0,-1,0,-1,-1,0,0,0,0,0,2147483647,0,0,2147483647,-1,0,2147483647,0,-1,0,2147483647,-1,-1,2147483647,2147483647,-1,2147483647,-1,-1,0,0,0,-1,0,-1,-1,0,0,2147483647,-1,0,-1,2147483647,2147483647,2147483647,2147483647,-1,0,2147483647,-1,0,-1,-1,-1,-1,-1,0,-1,0,2147483647,-1,0,0,0,2147483647,-1,2147483647,-1,-1,-1,2147483647,-1,-1,0,2147483647,-1},{2147483647,0,2147483647,-1,0,0,-1,2147483647,-1,0,0,-1,0,-1,0,0,0,0,2147483647,0,0,2147483647,-1,-1,2147483647,0,0,2147483647,0,0,-1,2147483647,-1,-1,2147483647,0,2147483647,-1,0,0,2147483647,-1,-1,2147483647,0,-1,-1,2147483647,2147483647,-1,-1,0,-1,0,-1,2147483647,2147483647,0,2147483647,0,0,-1,2147483647,-1,2147483647,-1,2147483647,0,2147483647,2147483647,0,-1,2147483647,-1,2147483647,-1,2147483647,-1,-1,2147483647,-1,0,2147483647,-1,2147483647,-1,-1,2147483647,0,0,2147483647,2147483647,-1,2147483647,2147483647,2147483647,0,-1,-1,2147483647,0,2147483647,2147483647,0,0,0,-1,-1,0,-1,0,2147483647,-1,-1,0,0,0,2147483647,0,0,2147483647,0,2147483647,2147483647,-1,0,2147483647,-1,0,0,-1,-1,0,2147483647,-1,2147483647,-1,0,-1,-1,2147483647,0,-1,0,0,-1,-1,-1,-1,0,-1,2147483647,2147483647,2147483647,0,-1,-1,-1,0,-1,-1,2147483647,2147483647,-1,-1,0,-1,0,2147483647,-1,0,0,-1,0,2147483647,0,2147483647,0,2147483647,-1,2147483647,-1,2147483647,2147483647,0,0,0,-1,0,0,2147483647,2147483647,0,0,2147483647,-1,-1,0,0,-1,2147483647,-1,2147483647,-1,-1,2147483647,2147483647,0,0,2147483647,2147483647,0,2147483647,0,-1,2147483647,-1,-1,0,0,0},{-1,2147483647,0,2147483647,2147483647,0,0,-1,-1,0,-1,0,-1,2147483647,0,0,-1,-1,-1,0,0,-1,-1,2147483647,2147483647,0,2147483647,2147483647,2147483647,2147483647,0,-1,-1,2147483647,0,-1,-1,0,2147483647,0,-1,-1,0,-1,0,2147483647,-1,-1,0,2147483647,0,2147483647,0,2147483647,-1,-1,2147483647,0,-1,-1,-1,-1,-1,0,-1,2147483647,2147483647,-1,0,2147483647,0,0,0,-1,0,0,-1,0,2147483647,-1,-1,-1,2147483647,2147483647,2147483647,-1,2147483647,0,2147483647,0,2147483647,0,-1,2147483647,-1,-1,-1,2147483647,0,0,-1,0,-1,0,-1,0,-1,2147483647,-1,-1,-1,-1,0,0,2147483647,2147483647,-1,-1,-1,2147483647,-1,0,2147483647,0,-1,2147483647,2147483647,2147483647,0,2147483647,2147483647,2147483647,0,-1,0,0,2147483647,0,-1,0,-1,-1,2147483647,2147483647,0,0,2147483647,0,-1,2147483647,-1,2147483647,0,2147483647,2147483647,0,2147483647,2147483647,2147483647,-1,2147483647,2147483647,0,0,0,2147483647,2147483647,-1,2147483647,0,-1,0,-1,-1,-1,0,2147483647,2147483647,-1,0,2147483647,0,2147483647,-1,-1,0,0,0,-1,0,0,2147483647,-1,0,0,0,0,0,2147483647,-1,-1,0,-1,2147483647,2147483647,-1,-1,-1,0,-1,0,0,-1,2147483647,0,0,2147483647,2147483647,2147483647,-1,-1},{0,0,-1,2147483647,0,-1,2147483647,0,0,0,2147483647,-1,2147483647,0,2147483647,-1,0,2147483647,2147483647,-1,0,2147483647,-1,-1,2147483647,-1,-1,0,0,-1,2147483647,-1,-1,0,-1,0,-1,2147483647,2147483647,2147483647,2147483647,0,0,-1,0,2147483647,0,2147483647,0,2147483647,-1,-1,-1,-1,0,0,2147483647,-1,0,2147483647,2147483647,-1,-1,2147483647,2147483647,2147483647,2147483647,2147483647,0,0,2147483647,0,-1,0,0,-1,2147483647,2147483647,2147483647,-1,2147483647,-1,0,0,-1,0,-1,0,0,0,-1,0,2147483647,-1,-1,-1,-1,-1,0,-1,-1,0,2147483647,2147483647,0,2147483647,2147483647,0,-1,-1,2147483647,-1,-1,0,2147483647,0,0,2147483647,-1,0,2147483647,0,2147483647,-1,2147483647,0,2147483647,0,2147483647,0,2147483647,0,-1,0,2147483647,0,0,2147483647,-1,-1,2147483647,0,-1,2147483647,-1,0,-1,0,0,0,2147483647,0,-1,-1,2147483647,0,2147483647,0,0,2147483647,-1,2147483647,0,2147483647,-1,2147483647,-1,-1,0,0,2147483647,2147483647,0,2147483647,2147483647,-1,2147483647,0,2147483647,2147483647,0,2147483647,0,0,2147483647,0,0,-1,2147483647,2147483647,2147483647,0,2147483647,0,2147483647,-1,0,0,2147483647,0,-1,2147483647,2147483647,0,0,2147483647,0,2147483647,2147483647,0,2147483647,-1,0,-1,-1,2147483647,0,-1,0,0,-1},{2147483647,-1,2147483647,0,0,-1,0,-1,2147483647,-1,-1,-1,2147483647,0,-1,-1,0,0,2147483647,-1,2147483647,2147483647,-1,2147483647,2147483647,-1,0,2147483647,2147483647,0,0,-1,-1,-1,0,0,2147483647,-1,0,-1,-1,2147483647,2147483647,-1,-1,-1,2147483647,2147483647,0,2147483647,-1,-1,0,0,2147483647,2147483647,0,2147483647,0,-1,-1,0,-1,-1,0,-1,0,-1,2147483647,-1,0,-1,0,0,-1,2147483647,-1,-1,0,0,2147483647,0,0,2147483647,0,-1,0,2147483647,2147483647,0,0,2147483647,0,0,0,0,-1,0,2147483647,-1,0,-1,0,2147483647,0,0,0,2147483647,-1,2147483647,-1,0,2147483647,-1,2147483647,-1,-1,0,0,2147483647,2147483647,2147483647,2147483647,0,0,-1,0,2147483647,-1,0,-1,-1,-1,-1,2147483647,-1,0,2147483647,0,-1,0,-1,2147483647,2147483647,-1,2147483647,2147483647,2147483647,0,0,0,2147483647,-1,0,-1,2147483647,2147483647,2147483647,-1,2147483647,2147483647,0,2147483647,2147483647,2147483647,-1,-1,2147483647,2147483647,-1,0,2147483647,0,2147483647,2147483647,-1,0,-1,-1,-1,0,0,-1,-1,2147483647,-1,2147483647,2147483647,2147483647,0,-1,0,0,-1,2147483647,-1,0,0,2147483647,0,-1,0,-1,-1,-1,-1,0,2147483647,0,-1,0,-1,2147483647,2147483647,0,0,2147483647,-1,-1,-1,-1},{-1,-1,2147483647,-1,2147483647,0,-1,2147483647,-1,0,0,-1,0,2147483647,2147483647,-1,0,0,2147483647,0,0,2147483647,2147483647,-1,2147483647,2147483647,-1,0,-1,0,-1,0,-1,0,0,-1,-1,2147483647,-1,2147483647,0,2147483647,0,-1,-1,2147483647,-1,-1,2147483647,-1,0,2147483647,0,-1,-1,-1,0,-1,-1,0,-1,2147483647,2147483647,0,-1,-1,-1,-1,2147483647,-1,-1,-1,-1,2147483647,0,2147483647,0,0,2147483647,-1,0,2147483647,2147483647,0,-1,0,0,-1,-1,0,0,-1,0,2147483647,2147483647,2147483647,2147483647,0,0,-1,0,0,-1,-1,2147483647,-1,0,0,0,2147483647,2147483647,-1,-1,2147483647,0,0,-1,2147483647,2147483647,-1,0,-1,-1,-1,-1,2147483647,-1,0,-1,0,2147483647,-1,0,2147483647,2147483647,-1,0,0,2147483647,0,2147483647,-1,0,0,2147483647,2147483647,-1,2147483647,0,2147483647,0,0,2147483647,2147483647,0,0,0,0,-1,2147483647,0,-1,-1,2147483647,-1,2147483647,0,0,0,0,2147483647,2147483647,-1,-1,0,0,-1,2147483647,0,2147483647,-1,2147483647,0,-1,-1,0,2147483647,-1,0,2147483647,-1,-1,0,0,2147483647,0,2147483647,0,0,0,0,0,2147483647,0,2147483647,2147483647,2147483647,0,2147483647,2147483647,2147483647,0,2147483647,2147483647,-1,0,-1,-1,2147483647,2147483647,-1},{2147483647,-1,0,0,-1,-1,-1,2147483647,-1,2147483647,2147483647,-1,2147483647,0,2147483647,2147483647,2147483647,-1,0,-1,2147483647,2147483647,-1,0,-1,2147483647,2147483647,2147483647,0,0,2147483647,-1,0,-1,0,-1,-1,0,2147483647,-1,-1,2147483647,2147483647,-1,2147483647,0,2147483647,2147483647,-1,-1,0,0,0,2147483647,-1,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,-1,0,2147483647,2147483647,2147483647,0,2147483647,2147483647,-1,2147483647,0,-1,-1,-1,-1,-1,0,0,0,2147483647,2147483647,0,0,-1,2147483647,0,2147483647,0,-1,-1,2147483647,2147483647,0,2147483647,0,0,0,0,-1,2147483647,-1,-1,0,2147483647,-1,-1,-1,0,-1,2147483647,0,0,0,0,-1,2147483647,2147483647,0,-1,0,2147483647,2147483647,2147483647,0,0,0,0,0,0,2147483647,0,2147483647,-1,0,-1,-1,0,2147483647,2147483647,2147483647,0,-1,2147483647,0,0,0,0,2147483647,-1,2147483647,0,0,-1,0,2147483647,-1,-1,2147483647,0,0,2147483647,2147483647,2147483647,0,-1,0,-1,2147483647,2147483647,0,2147483647,0,0,2147483647,2147483647,2147483647,2147483647,-1,2147483647,2147483647,0,0,-1,-1,0,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,-1,0,-1,-1,0,0,0,-1,2147483647,2147483647,0,2147483647,-1,0,0,-1,-1,0,0,0,2147483647,2147483647,0,-1,2147483647,2147483647,2147483647},{0,2147483647,2147483647,-1,-1,-1,2147483647,2147483647,0,-1,0,0,0,0,0,-1,0,0,-1,2147483647,2147483647,2147483647,2147483647,-1,0,2147483647,0,-1,0,-1,0,0,2147483647,0,2147483647,0,2147483647,-1,2147483647,0,-1,0,0,0,0,2147483647,0,-1,0,2147483647,2147483647,0,0,2147483647,2147483647,0,0,2147483647,-1,0,-1,0,-1,-1,2147483647,-1,-1,2147483647,2147483647,-1,0,-1,2147483647,-1,-1,-1,0,-1,-1,0,2147483647,-1,-1,2147483647,2147483647,0,2147483647,-1,0,-1,-1,-1,-1,-1,2147483647,0,0,-1,-1,2147483647,-1,-1,2147483647,2147483647,2147483647,-1,-1,0,2147483647,2147483647,0,-1,2147483647,-1,0,2147483647,2147483647,0,2147483647,0,0,0,-1,0,2147483647,-1,2147483647,2147483647,-1,-1,2147483647,-1,2147483647,2147483647,0,0,-1,-1,2147483647,-1,2147483647,0,0,0,-1,0,-1,-1,-1,0,-1,0,-1,0,0,-1,0,0,2147483647,2147483647,0,0,0,-1,-1,2147483647,-1,2147483647,0,-1,0,-1,-1,2147483647,2147483647,2147483647,-1,-1,0,2147483647,0,2147483647,2147483647,0,-1,0,-1,2147483647,0,-1,-1,-1,2147483647,0,2147483647,-1,-1,2147483647,-1,-1,0,0,-1,0,-1,0,2147483647,2147483647,2147483647,2147483647,2147483647,-1,-1,2147483647,2147483647,2147483647,-1,0,-1,2147483647,-1},{2147483647,2147483647,-1,-1,2147483647,-1,2147483647,0,-1,0,-1,0,2147483647,2147483647,0,0,2147483647,-1,-1,0,2147483647,2147483647,0,0,0,-1,-1,-1,0,-1,-1,2147483647,0,0,2147483647,0,0,0,0,2147483647,0,0,-1,0,2147483647,0,0,2147483647,0,2147483647,0,-1,0,2147483647,-1,0,2147483647,2147483647,-1,0,-1,-1,-1,0,0,0,2147483647,2147483647,0,2147483647,2147483647,0,2147483647,2147483647,-1,2147483647,-1,2147483647,0,-1,2147483647,-1,-1,-1,-1,2147483647,0,-1,0,-1,2147483647,-1,-1,0,0,0,-1,-1,2147483647,0,0,0,-1,0,2147483647,0,-1,0,-1,-1,2147483647,2147483647,2147483647,2147483647,-1,0,2147483647,0,0,2147483647,0,-1,-1,0,-1,-1,0,0,-1,0,2147483647,2147483647,2147483647,0,-1,-1,-1,-1,-1,-1,2147483647,2147483647,0,2147483647,-1,2147483647,0,0,2147483647,2147483647,2147483647,0,2147483647,-1,-1,2147483647,0,2147483647,0,0,0,2147483647,-1,2147483647,0,0,0,-1,0,-1,0,-1,-1,0,-1,-1,-1,2147483647,0,2147483647,0,2147483647,0,0,2147483647,0,0,2147483647,-1,2147483647,-1,0,-1,0,0,2147483647,-1,0,0,0,2147483647,-1,2147483647,2147483647,0,-1,-1,-1,2147483647,2147483647,0,2147483647,2147483647,-1,-1,0,2147483647,-1,2147483647,2147483647,-1},{2147483647,2147483647,0,-1,-1,0,2147483647,-1,2147483647,0,0,-1,0,-1,0,2147483647,2147483647,-1,0,-1,0,-1,-1,-1,2147483647,2147483647,2147483647,0,-1,2147483647,0,0,0,-1,2147483647,0,0,-1,0,0,-1,0,0,0,-1,0,-1,-1,2147483647,2147483647,0,2147483647,2147483647,0,0,-1,2147483647,0,2147483647,2147483647,-1,2147483647,-1,0,2147483647,-1,2147483647,0,0,-1,2147483647,2147483647,0,-1,2147483647,0,0,2147483647,2147483647,-1,-1,-1,0,0,2147483647,2147483647,-1,0,0,0,-1,2147483647,0,0,-1,0,0,0,2147483647,0,2147483647,0,2147483647,2147483647,-1,2147483647,2147483647,-1,2147483647,-1,-1,2147483647,-1,0,2147483647,0,0,0,-1,-1,-1,-1,2147483647,-1,-1,2147483647,-1,2147483647,0,2147483647,-1,0,-1,-1,2147483647,-1,2147483647,-1,-1,0,-1,-1,2147483647,-1,0,0,2147483647,0,-1,0,0,-1,2147483647,2147483647,2147483647,-1,-1,0,2147483647,0,0,2147483647,0,2147483647,0,0,-1,0,0,2147483647,2147483647,2147483647,0,0,0,0,-1,2147483647,-1,-1,2147483647,0,0,2147483647,-1,0,-1,0,0,-1,-1,-1,2147483647,-1,0,-1,2147483647,-1,-1,0,2147483647,0,-1,-1,2147483647,0,0,0,-1,-1,-1,-1,0,2147483647,0,0,-1,-1,-1,0,-1},{-1,-1,0,2147483647,0,-1,2147483647,2147483647,0,2147483647,0,-1,0,2147483647,-1,0,0,2147483647,-1,2147483647,-1,2147483647,-1,2147483647,0,0,0,2147483647,2147483647,2147483647,-1,2147483647,0,0,2147483647,2147483647,0,-1,-1,0,0,0,-1,2147483647,-1,2147483647,2147483647,0,2147483647,-1,-1,0,0,2147483647,-1,0,0,0,2147483647,0,0,2147483647,2147483647,0,0,-1,-1,-1,0,-1,0,2147483647,2147483647,0,-1,2147483647,-1,-1,2147483647,-1,0,-1,-1,-1,2147483647,-1,2147483647,0,2147483647,-1,0,0,2147483647,0,-1,2147483647,0,2147483647,2147483647,-1,2147483647,0,0,0,2147483647,0,0,-1,-1,0,-1,0,-1,2147483647,0,-1,2147483647,0,2147483647,2147483647,-1,-1,0,-1,2147483647,2147483647,-1,-1,-1,2147483647,-1,2147483647,0,0,-1,-1,2147483647,2147483647,2147483647,-1,0,0,2147483647,2147483647,-1,0,-1,-1,2147483647,2147483647,2147483647,0,0,2147483647,-1,-1,2147483647,2147483647,2147483647,-1,2147483647,0,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,-1,2147483647,2147483647,2147483647,0,0,0,-1,0,0,-1,0,0,0,-1,-1,0,-1,2147483647,2147483647,-1,0,0,0,2147483647,0,2147483647,0,-1,-1,2147483647,0,-1,-1,2147483647,-1,2147483647,-1,-1,0,0,0,-1,-1,0,0,0,0,-1,-1,2147483647,-1,-1},{-1,0,2147483647,-1,-1,2147483647,0,-1,-1,2147483647,2147483647,0,2147483647,0,-1,-1,0,2147483647,0,2147483647,2147483647,0,2147483647,2147483647,-1,0,-1,0,-1,0,2147483647,2147483647,2147483647,0,2147483647,0,0,-1,0,-1,2147483647,2147483647,-1,0,0,2147483647,0,-1,2147483647,2147483647,-1,2147483647,2147483647,-1,2147483647,-1,2147483647,-1,2147483647,0,2147483647,0,0,0,-1,0,2147483647,-1,2147483647,0,2147483647,0,-1,2147483647,2147483647,0,0,-1,-1,0,0,0,0,-1,0,2147483647,-1,2147483647,0,-1,-1,2147483647,0,0,-1,2147483647,0,-1,0,-1,2147483647,2147483647,0,2147483647,0,0,2147483647,-1,0,2147483647,0,2147483647,-1,-1,2147483647,0,0,2147483647,0,0,0,0,-1,0,2147483647,-1,2147483647,0,2147483647,-1,2147483647,2147483647,-1,0,0,-1,0,2147483647,-1,0,0,-1,-1,-1,-1,0,2147483647,-1,2147483647,0,2147483647,-1,-1,-1,-1,0,-1,-1,-1,2147483647,-1,2147483647,0,2147483647,2147483647,0,0,2147483647,-1,-1,2147483647,-1,0,-1,2147483647,2147483647,0,-1,-1,0,2147483647,0,2147483647,0,0,-1,0,2147483647,0,2147483647,-1,-1,0,-1,0,-1,2147483647,0,0,0,-1,-1,-1,0,0,2147483647,0,2147483647,-1,2147483647,-1,0,2147483647,2147483647,2147483647,-1,-1,0,-1,-1,2147483647},{-1,0,-1,-1,0,2147483647,2147483647,0,2147483647,-1,2147483647,2147483647,-1,0,-1,2147483647,2147483647,-1,2147483647,0,-1,2147483647,2147483647,2147483647,2147483647,-1,2147483647,0,2147483647,0,2147483647,2147483647,0,2147483647,2147483647,-1,-1,2147483647,2147483647,2147483647,0,2147483647,2147483647,-1,-1,0,-1,2147483647,-1,-1,2147483647,0,0,-1,0,-1,0,2147483647,-1,-1,0,-1,2147483647,0,0,2147483647,0,0,0,2147483647,-1,2147483647,-1,0,2147483647,0,0,-1,0,2147483647,-1,0,-1,-1,0,0,2147483647,0,0,0,2147483647,-1,-1,-1,2147483647,-1,-1,2147483647,-1,0,0,0,0,2147483647,-1,2147483647,-1,0,0,-1,-1,-1,0,2147483647,-1,-1,-1,-1,2147483647,-1,-1,-1,2147483647,0,0,2147483647,2147483647,2147483647,-1,-1,-1,2147483647,-1,-1,2147483647,0,0,2147483647,-1,2147483647,0,2147483647,0,-1,-1,2147483647,2147483647,0,-1,2147483647,2147483647,2147483647,0,-1,2147483647,-1,0,2147483647,2147483647,2147483647,2147483647,0,-1,-1,0,2147483647,2147483647,-1,0,-1,0,2147483647,0,-1,-1,0,2147483647,2147483647,2147483647,0,-1,-1,0,2147483647,2147483647,-1,0,2147483647,2147483647,-1,0,-1,0,0,2147483647,-1,2147483647,-1,2147483647,2147483647,0,-1,0,2147483647,-1,0,2147483647,0,0,0,0,-1,0,-1,-1,0,-1,0,2147483647,0,0},{2147483647,0,0,0,0,-1,-1,0,-1,2147483647,-1,2147483647,2147483647,2147483647,0,2147483647,0,-1,-1,2147483647,2147483647,-1,0,-1,2147483647,-1,0,-1,2147483647,2147483647,0,2147483647,0,-1,0,-1,2147483647,0,2147483647,2147483647,-1,-1,-1,-1,-1,-1,0,2147483647,0,-1,-1,-1,-1,2147483647,-1,2147483647,2147483647,2147483647,2147483647,2147483647,0,2147483647,0,0,2147483647,-1,2147483647,-1,0,0,2147483647,-1,-1,-1,2147483647,2147483647,0,-1,0,2147483647,2147483647,-1,-1,-1,-1,0,2147483647,2147483647,2147483647,0,2147483647,-1,-1,0,2147483647,2147483647,2147483647,0,2147483647,-1,-1,2147483647,0,-1,0,0,-1,0,-1,2147483647,-1,-1,-1,0,2147483647,2147483647,2147483647,0,0,0,-1,0,0,-1,-1,2147483647,-1,2147483647,0,-1,2147483647,2147483647,2147483647,0,0,2147483647,-1,0,-1,2147483647,-1,2147483647,2147483647,0,-1,-1,-1,0,2147483647,-1,-1,2147483647,0,2147483647,2147483647,0,2147483647,-1,0,0,-1,0,2147483647,2147483647,2147483647,-1,0,0,2147483647,-1,0,2147483647,2147483647,-1,-1,0,0,0,0,2147483647,-1,2147483647,-1,2147483647,-1,0,2147483647,0,0,2147483647,-1,-1,-1,-1,-1,0,2147483647,0,0,2147483647,0,2147483647,0,-1,0,2147483647,-1,-1,-1,-1,0,0,2147483647,0,2147483647,0,2147483647,2147483647,2147483647,0,2147483647},{2147483647,0,2147483647,0,2147483647,2147483647,-1,-1,2147483647,2147483647,0,0,0,-1,0,0,-1,0,-1,0,0,-1,0,-1,2147483647,-1,2147483647,2147483647,2147483647,0,-1,2147483647,2147483647,0,2147483647,-1,0,2147483647,0,2147483647,0,0,0,0,0,0,0,0,-1,-1,2147483647,0,0,2147483647,0,-1,-1,2147483647,0,-1,-1,-1,-1,-1,-1,-1,-1,2147483647,0,2147483647,2147483647,-1,0,2147483647,-1,0,-1,2147483647,0,-1,2147483647,-1,-1,2147483647,0,-1,2147483647,0,2147483647,-1,2147483647,-1,2147483647,0,-1,2147483647,-1,0,-1,-1,-1,2147483647,-1,2147483647,2147483647,-1,2147483647,0,0,0,0,-1,2147483647,0,2147483647,0,-1,0,0,2147483647,0,-1,-1,0,2147483647,2147483647,0,-1,0,-1,0,0,-1,0,2147483647,0,-1,-1,0,-1,2147483647,0,2147483647,-1,2147483647,2147483647,-1,2147483647,-1,-1,0,2147483647,0,2147483647,-1,2147483647,-1,2147483647,0,0,-1,-1,2147483647,2147483647,-1,-1,2147483647,-1,0,0,0,2147483647,2147483647,0,0,0,-1,0,-1,2147483647,2147483647,2147483647,-1,2147483647,-1,-1,2147483647,0,-1,-1,-1,-1,-1,-1,-1,2147483647,2147483647,0,-1,0,2147483647,-1,0,2147483647,-1,2147483647,2147483647,0,2147483647,0,-1,0,-1,2147483647,-1,0,-1,0,-1,-1,2147483647},{-1,2147483647,0,2147483647,-1,-1,0,2147483647,-1,2147483647,-1,-1,0,2147483647,2147483647,2147483647,-1,-1,-1,2147483647,-1,-1,-1,-1,-1,0,0,-1,-1,2147483647,0,2147483647,0,-1,2147483647,-1,-1,2147483647,-1,0,-1,-1,0,2147483647,0,0,0,-1,2147483647,-1,0,2147483647,2147483647,-1,2147483647,0,0,2147483647,2147483647,2147483647,-1,0,-1,0,-1,2147483647,-1,0,-1,-1,-1,-1,0,-1,-1,-1,2147483647,-1,2147483647,0,0,0,-1,-1,0,0,0,0,-1,2147483647,0,-1,2147483647,2147483647,-1,-1,-1,0,0,-1,-1,2147483647,-1,-1,2147483647,2147483647,0,-1,0,0,2147483647,2147483647,-1,2147483647,-1,2147483647,-1,-1,-1,-1,-1,-1,0,0,-1,2147483647,0,-1,-1,0,2147483647,0,2147483647,-1,2147483647,-1,0,2147483647,-1,-1,-1,-1,-1,0,-1,2147483647,2147483647,-1,2147483647,-1,2147483647,2147483647,0,-1,-1,2147483647,2147483647,-1,-1,0,-1,2147483647,-1,2147483647,-1,2147483647,2147483647,2147483647,-1,2147483647,-1,2147483647,2147483647,0,-1,0,0,0,-1,2147483647,2147483647,-1,2147483647,0,2147483647,2147483647,2147483647,0,2147483647,2147483647,-1,2147483647,-1,0,0,0,0,0,2147483647,2147483647,2147483647,2147483647,-1,2147483647,0,-1,2147483647,2147483647,0,0,0,-1,2147483647,2147483647,0,0,0,-1,0,0,0},{2147483647,-1,2147483647,-1,0,2147483647,-1,2147483647,2147483647,0,-1,0,-1,0,2147483647,-1,0,-1,0,-1,0,2147483647,2147483647,-1,2147483647,-1,-1,0,-1,0,-1,-1,2147483647,-1,2147483647,0,2147483647,0,-1,0,-1,2147483647,-1,2147483647,-1,2147483647,-1,2147483647,0,2147483647,0,2147483647,2147483647,0,2147483647,0,2147483647,-1,0,-1,0,0,-1,2147483647,0,2147483647,-1,2147483647,0,0,0,0,0,2147483647,-1,-1,0,-1,0,2147483647,-1,2147483647,-1,-1,0,0,-1,2147483647,0,0,2147483647,0,2147483647,2147483647,2147483647,0,2147483647,-1,0,2147483647,-1,0,2147483647,0,-1,-1,2147483647,-1,0,-1,-1,-1,0,2147483647,0,-1,0,0,2147483647,-1,2147483647,0,2147483647,2147483647,0,2147483647,-1,2147483647,2147483647,0,-1,-1,-1,2147483647,0,-1,2147483647,2147483647,0,-1,-1,0,0,2147483647,2147483647,-1,0,-1,0,2147483647,2147483647,-1,-1,2147483647,2147483647,0,-1,2147483647,0,0,2147483647,0,-1,-1,2147483647,2147483647,2147483647,0,0,0,0,-1,2147483647,0,-1,-1,2147483647,0,0,2147483647,-1,-1,0,2147483647,0,-1,2147483647,-1,-1,2147483647,2147483647,-1,0,-1,-1,2147483647,-1,0,0,-1,-1,0,0,-1,-1,0,-1,2147483647,0,2147483647,2147483647,2147483647,2147483647,-1,-1,2147483647,-1,2147483647,-1,0,2147483647},{0,0,0,0,2147483647,0,2147483647,0,-1,0,-1,2147483647,2147483647,-1,0,-1,-1,2147483647,0,-1,-1,0,0,0,2147483647,-1,0,2147483647,0,0,0,-1,0,-1,-1,2147483647,0,0,2147483647,0,2147483647,0,-1,-1,2147483647,2147483647,-1,2147483647,2147483647,-1,0,0,2147483647,2147483647,-1,0,-1,-1,0,0,2147483647,0,-1,0,2147483647,-1,0,2147483647,-1,-1,-1,0,0,0,0,0,2147483647,-1,0,2147483647,-1,2147483647,2147483647,-1,2147483647,-1,2147483647,-1,0,0,0,0,0,2147483647,-1,-1,2147483647,-1,-1,0,-1,2147483647,0,2147483647,-1,0,-1,-1,2147483647,0,2147483647,2147483647,0,2147483647,-1,2147483647,-1,-1,2147483647,0,0,-1,-1,2147483647,0,2147483647,2147483647,0,0,-1,0,0,-1,0,-1,0,0,2147483647,0,0,0,-1,2147483647,0,2147483647,-1,2147483647,2147483647,-1,-1,0,-1,-1,0,2147483647,0,2147483647,0,-1,-1,0,-1,2147483647,2147483647,-1,2147483647,2147483647,0,2147483647,0,2147483647,0,0,0,2147483647,0,0,0,-1,2147483647,2147483647,0,2147483647,-1,0,0,0,2147483647,2147483647,0,0,2147483647,0,0,2147483647,2147483647,-1,0,-1,-1,2147483647,-1,2147483647,-1,-1,2147483647,0,-1,2147483647,-1,-1,0,0,-1,2147483647,-1,0,-1,0,-1,-1},{-1,-1,-1,2147483647,2147483647,2147483647,-1,0,2147483647,-1,-1,2147483647,-1,2147483647,0,-1,-1,0,2147483647,0,2147483647,-1,0,-1,0,2147483647,2147483647,-1,-1,2147483647,2147483647,2147483647,0,-1,0,0,2147483647,2147483647,-1,2147483647,2147483647,0,0,2147483647,-1,-1,2147483647,-1,2147483647,-1,2147483647,0,-1,2147483647,0,-1,-1,0,0,0,-1,-1,2147483647,2147483647,0,0,0,0,2147483647,-1,0,0,0,-1,0,0,2147483647,0,-1,2147483647,2147483647,0,0,-1,-1,2147483647,0,2147483647,-1,-1,2147483647,2147483647,-1,-1,2147483647,0,-1,2147483647,0,0,2147483647,0,2147483647,2147483647,-1,0,-1,2147483647,-1,0,-1,-1,0,0,-1,0,-1,-1,2147483647,-1,0,0,0,-1,0,0,0,0,-1,-1,0,0,-1,-1,0,2147483647,-1,2147483647,-1,2147483647,2147483647,0,0,2147483647,0,-1,-1,0,2147483647,0,2147483647,0,2147483647,-1,2147483647,-1,2147483647,-1,2147483647,-1,0,-1,-1,0,-1,-1,-1,2147483647,0,2147483647,2147483647,2147483647,0,0,-1,0,2147483647,0,-1,-1,-1,2147483647,0,-1,-1,2147483647,-1,-1,-1,2147483647,0,2147483647,0,0,2147483647,-1,0,2147483647,-1,-1,2147483647,0,-1,0,2147483647,-1,0,0,0,-1,-1,0,2147483647,0,0,-1,2147483647,2147483647,-1,-1,2147483647},{-1,-1,0,-1,2147483647,2147483647,-1,-1,2147483647,0,-1,0,-1,2147483647,2147483647,2147483647,0,-1,0,0,-1,0,2147483647,2147483647,-1,-1,0,0,-1,2147483647,2147483647,2147483647,2147483647,-1,2147483647,0,2147483647,2147483647,-1,0,-1,2147483647,2147483647,2147483647,-1,2147483647,2147483647,-1,0,-1,0,-1,2147483647,2147483647,-1,2147483647,-1,-1,0,0,-1,0,-1,-1,2147483647,-1,0,0,2147483647,2147483647,-1,2147483647,-1,0,0,0,2147483647,2147483647,-1,-1,2147483647,2147483647,-1,-1,0,0,0,0,0,2147483647,-1,-1,-1,2147483647,2147483647,-1,2147483647,-1,0,0,0,2147483647,-1,2147483647,0,-1,-1,0,-1,-1,-1,2147483647,0,0,0,2147483647,0,2147483647,0,0,0,2147483647,-1,-1,2147483647,-1,0,0,-1,2147483647,0,2147483647,0,2147483647,2147483647,0,2147483647,2147483647,-1,-1,0,0,-1,2147483647,0,0,0,0,-1,0,0,2147483647,0,2147483647,2147483647,-1,-1,0,-1,2147483647,2147483647,0,2147483647,2147483647,2147483647,0,0,0,-1,2147483647,2147483647,0,0,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,-1,0,0,-1,0,2147483647,2147483647,-1,0,0,0,0,-1,-1,0,-1,2147483647,-1,2147483647,2147483647,-1,0,-1,0,0,2147483647,-1,0,-1,-1,-1,2147483647,-1,2147483647,-1,-1,2147483647,-1,0,0,-1,2147483647},{-1,-1,2147483647,2147483647,2147483647,-1,0,0,-1,0,0,0,2147483647,2147483647,0,-1,0,-1,-1,-1,2147483647,0,0,-1,2147483647,0,-1,0,0,-1,2147483647,2147483647,-1,-1,0,2147483647,0,0,0,2147483647,0,2147483647,0,-1,-1,2147483647,2147483647,0,-1,-1,2147483647,2147483647,2147483647,-1,0,-1,2147483647,0,-1,-1,2147483647,2147483647,0,2147483647,0,-1,-1,0,0,0,0,-1,0,0,-1,-1,2147483647,-1,-1,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,0,-1,0,0,0,-1,-1,-1,0,2147483647,0,0,2147483647,2147483647,-1,-1,-1,-1,-1,2147483647,0,-1,-1,0,2147483647,2147483647,0,2147483647,0,2147483647,-1,2147483647,-1,2147483647,2147483647,0,2147483647,0,2147483647,-1,-1,0,0,0,2147483647,0,-1,-1,-1,2147483647,2147483647,2147483647,2147483647,-1,0,-1,0,2147483647,0,-1,2147483647,-1,-1,2147483647,0,0,-1,-1,-1,-1,0,-1,-1,0,0,0,0,-1,2147483647,2147483647,0,2147483647,-1,0,-1,2147483647,2147483647,2147483647,0,0,0,0,-1,2147483647,0,-1,2147483647,-1,-1,-1,2147483647,2147483647,0,0,2147483647,-1,2147483647,2147483647,2147483647,0,0,-1,0,-1,2147483647,-1,-1,-1,0,-1,0,-1,0,-1,0,2147483647,2147483647,0,0,2147483647,0,0,2147483647,0,-1},{2147483647,2147483647,-1,0,0,2147483647,0,-1,2147483647,-1,2147483647,2147483647,2147483647,-1,2147483647,-1,0,2147483647,-1,0,2147483647,-1,-1,0,0,-1,0,0,-1,-1,-1,-1,-1,-1,2147483647,0,-1,0,2147483647,2147483647,-1,0,0,-1,0,2147483647,2147483647,-1,2147483647,0,0,2147483647,-1,2147483647,0,0,-1,-1,-1,-1,2147483647,-1,0,-1,-1,0,-1,2147483647,0,-1,-1,2147483647,2147483647,0,0,2147483647,-1,2147483647,-1,-1,2147483647,-1,0,0,2147483647,0,0,2147483647,0,2147483647,0,2147483647,2147483647,2147483647,-1,2147483647,2147483647,0,0,-1,0,0,2147483647,-1,2147483647,0,2147483647,2147483647,2147483647,-1,2147483647,-1,0,2147483647,2147483647,-1,-1,0,0,0,0,-1,-1,0,-1,0,0,2147483647,2147483647,2147483647,0,2147483647,0,2147483647,-1,0,2147483647,0,-1,0,0,0,0,0,-1,0,0,-1,2147483647,0,0,-1,0,2147483647,0,0,0,-1,2147483647,0,0,-1,0,2147483647,-1,2147483647,2147483647,2147483647,0,2147483647,-1,0,-1,0,2147483647,-1,2147483647,2147483647,0,2147483647,-1,-1,2147483647,2147483647,0,-1,-1,0,0,0,-1,-1,-1,-1,-1,0,-1,-1,2147483647,-1,2147483647,-1,2147483647,-1,0,2147483647,2147483647,0,0,2147483647,2147483647,0,-1,-1,-1,2147483647,-1,-1,-1,0,-1},{-1,0,0,2147483647,0,2147483647,0,2147483647,-1,0,-1,-1,0,0,2147483647,2147483647,2147483647,-1,2147483647,-1,0,2147483647,0,0,0,2147483647,2147483647,0,-1,-1,2147483647,0,-1,0,0,0,0,2147483647,2147483647,0,0,2147483647,-1,2147483647,2147483647,-1,0,-1,0,-1,-1,0,-1,0,0,0,0,0,2147483647,-1,-1,-1,2147483647,-1,0,2147483647,0,2147483647,2147483647,2147483647,2147483647,-1,-1,0,2147483647,0,-1,-1,2147483647,0,-1,2147483647,2147483647,0,0,2147483647,0,0,2147483647,2147483647,2147483647,0,0,2147483647,-1,-1,2147483647,0,-1,0,0,0,2147483647,2147483647,-1,2147483647,2147483647,0,-1,0,-1,-1,-1,-1,2147483647,2147483647,-1,-1,0,0,-1,0,-1,-1,-1,2147483647,2147483647,-1,0,-1,2147483647,2147483647,2147483647,-1,0,-1,0,-1,0,0,-1,-1,0,0,0,0,-1,-1,0,-1,-1,2147483647,2147483647,2147483647,0,0,-1,-1,-1,-1,-1,0,0,0,0,-1,2147483647,2147483647,-1,0,-1,-1,-1,-1,-1,2147483647,2147483647,-1,0,-1,0,0,0,2147483647,2147483647,-1,0,0,2147483647,0,0,2147483647,-1,0,-1,0,0,-1,-1,0,0,-1,-1,-1,0,2147483647,-1,-1,2147483647,0,-1,0,2147483647,2147483647,2147483647,2147483647,0,2147483647,-1,0,-1},{2147483647,0,0,2147483647,2147483647,0,2147483647,2147483647,2147483647,2147483647,0,2147483647,2147483647,-1,-1,-1,-1,0,0,2147483647,-1,2147483647,0,0,2147483647,2147483647,0,-1,-1,-1,-1,0,-1,0,0,0,0,-1,2147483647,-1,2147483647,0,0,-1,0,2147483647,-1,-1,2147483647,0,-1,2147483647,-1,0,2147483647,-1,2147483647,-1,0,-1,-1,-1,2147483647,0,-1,2147483647,0,0,0,0,-1,-1,-1,0,2147483647,-1,2147483647,2147483647,2147483647,0,2147483647,2147483647,0,-1,2147483647,0,0,-1,-1,0,0,-1,-1,0,2147483647,2147483647,2147483647,0,0,2147483647,0,0,-1,0,-1,-1,2147483647,2147483647,0,0,0,2147483647,-1,0,-1,0,-1,0,0,0,0,-1,0,0,2147483647,-1,-1,0,-1,2147483647,0,-1,2147483647,0,0,0,0,2147483647,2147483647,-1,2147483647,-1,-1,-1,-1,-1,2147483647,-1,-1,2147483647,2147483647,-1,0,2147483647,-1,0,2147483647,-1,2147483647,-1,-1,0,0,2147483647,2147483647,2147483647,-1,-1,2147483647,-1,0,0,0,2147483647,-1,2147483647,2147483647,-1,2147483647,-1,0,0,-1,2147483647,2147483647,0,-1,-1,-1,-1,-1,2147483647,2147483647,0,-1,2147483647,-1,2147483647,0,0,0,0,-1,-1,0,2147483647,-1,-1,-1,-1,2147483647,0,-1,-1,0,-1,-1,2147483647,0,-1,-1},{-1,2147483647,-1,-1,2147483647,2147483647,2147483647,0,0,2147483647,2147483647,0,0,-1,0,2147483647,2147483647,0,0,2147483647,-1,-1,0,0,0,-1,2147483647,0,0,0,-1,-1,2147483647,0,-1,2147483647,0,2147483647,-1,-1,2147483647,2147483647,2147483647,0,-1,2147483647,0,2147483647,2147483647,0,-1,2147483647,2147483647,2147483647,0,2147483647,0,2147483647,2147483647,2147483647,0,-1,0,2147483647,-1,2147483647,-1,0,0,-1,2147483647,-1,2147483647,0,-1,-1,-1,0,2147483647,2147483647,2147483647,-1,2147483647,2147483647,2147483647,2147483647,2147483647,-1,2147483647,0,0,2147483647,2147483647,2147483647,2147483647,0,-1,0,-1,-1,-1,2147483647,0,-1,2147483647,2147483647,2147483647,0,-1,0,2147483647,2147483647,0,2147483647,-1,-1,2147483647,0,0,-1,2147483647,-1,-1,-1,-1,-1,2147483647,-1,2147483647,-1,0,2147483647,0,2147483647,2147483647,-1,-1,-1,2147483647,-1,-1,2147483647,0,-1,-1,0,-1,0,0,-1,0,0,-1,0,0,0,0,0,0,-1,2147483647,-1,-1,0,2147483647,0,0,2147483647,0,0,-1,0,0,2147483647,-1,-1,2147483647,2147483647,0,-1,0,-1,2147483647,-1,-1,0,2147483647,0,-1,2147483647,-1,0,2147483647,2147483647,2147483647,2147483647,0,-1,2147483647,2147483647,2147483647,0,2147483647,-1,0,2147483647,0,2147483647,2147483647,-1,-1,2147483647,2147483647,-1,2147483647,0,0,-1,0,0,-1},{2147483647,0,0,-1,0,2147483647,-1,-1,-1,2147483647,-1,2147483647,2147483647,2147483647,2147483647,0,-1,2147483647,-1,0,2147483647,2147483647,-1,0,0,-1,-1,2147483647,-1,0,2147483647,-1,2147483647,0,0,2147483647,0,2147483647,0,2147483647,2147483647,2147483647,0,-1,0,0,2147483647,-1,2147483647,2147483647,-1,2147483647,0,0,-1,0,0,2147483647,2147483647,0,-1,-1,0,2147483647,2147483647,-1,0,2147483647,0,2147483647,-1,2147483647,-1,0,-1,0,-1,2147483647,0,2147483647,2147483647,-1,-1,0,2147483647,0,2147483647,0,0,0,2147483647,2147483647,2147483647,2147483647,-1,2147483647,-1,2147483647,2147483647,-1,-1,0,-1,2147483647,2147483647,0,0,-1,2147483647,0,-1,-1,2147483647,-1,2147483647,2147483647,-1,2147483647,2147483647,2147483647,-1,0,0,2147483647,0,0,-1,0,0,2147483647,-1,-1,0,-1,-1,2147483647,0,2147483647,2147483647,2147483647,0,-1,0,-1,-1,-1,0,2147483647,-1,0,0,0,2147483647,-1,2147483647,0,2147483647,0,-1,2147483647,-1,-1,-1,-1,0,2147483647,-1,2147483647,2147483647,2147483647,2147483647,0,-1,0,-1,0,0,0,0,-1,0,2147483647,0,-1,-1,-1,-1,0,-1,2147483647,2147483647,2147483647,-1,-1,-1,-1,2147483647,2147483647,-1,-1,-1,0,2147483647,0,2147483647,-1,2147483647,-1,0,-1,0,0,-1,2147483647,-1,2147483647,2147483647,0,-1,-1,0},{0,2147483647,2147483647,2147483647,-1,2147483647,0,2147483647,2147483647,2147483647,2147483647,0,0,0,0,2147483647,2147483647,-1,-1,-1,0,-1,0,0,0,-1,0,2147483647,0,2147483647,2147483647,-1,-1,0,0,-1,-1,2147483647,2147483647,0,2147483647,2147483647,0,-1,0,0,-1,-1,2147483647,0,-1,-1,2147483647,0,0,2147483647,-1,2147483647,-1,0,0,0,2147483647,-1,2147483647,0,2147483647,0,2147483647,0,0,0,0,-1,0,0,0,0,0,0,-1,0,-1,0,-1,0,-1,2147483647,-1,2147483647,2147483647,0,2147483647,-1,-1,2147483647,0,0,2147483647,-1,2147483647,-1,2147483647,0,-1,-1,-1,2147483647,0,-1,-1,2147483647,0,0,-1,2147483647,2147483647,0,-1,0,-1,-1,0,0,-1,2147483647,0,2147483647,-1,0,2147483647,0,0,0,2147483647,2147483647,2147483647,2147483647,0,0,-1,-1,-1,0,-1,0,-1,0,-1,0,0,0,0,-1,2147483647,-1,2147483647,2147483647,2147483647,0,0,2147483647,0,2147483647,2147483647,2147483647,2147483647,2147483647,-1,0,0,2147483647,0,0,0,-1,-1,-1,-1,2147483647,2147483647,0,2147483647,2147483647,0,2147483647,0,-1,2147483647,2147483647,2147483647,-1,2147483647,2147483647,-1,0,2147483647,2147483647,2147483647,-1,2147483647,-1,0,0,-1,0,0,2147483647,2147483647,-1,0,-1,2147483647,2147483647,0,0,2147483647,-1,0,0,2147483647},{0,2147483647,0,-1,0,2147483647,0,-1,2147483647,0,-1,-1,0,2147483647,-1,-1,2147483647,0,0,0,2147483647,0,0,-1,2147483647,0,0,-1,0,-1,0,0,2147483647,0,2147483647,-1,-1,2147483647,2147483647,2147483647,2147483647,-1,0,-1,0,2147483647,-1,0,-1,2147483647,-1,-1,-1,2147483647,2147483647,2147483647,2147483647,2147483647,0,0,0,2147483647,0,-1,2147483647,0,-1,2147483647,0,2147483647,2147483647,2147483647,-1,2147483647,2147483647,2147483647,0,2147483647,2147483647,2147483647,0,2147483647,-1,2147483647,0,2147483647,2147483647,-1,0,2147483647,0,2147483647,-1,2147483647,0,2147483647,0,2147483647,2147483647,2147483647,-1,-1,0,2147483647,-1,2147483647,0,-1,-1,0,-1,0,-1,2147483647,-1,-1,2147483647,-1,-1,2147483647,-1,0,0,-1,-1,0,0,2147483647,-1,-1,-1,0,-1,-1,-1,-1,-1,-1,-1,2147483647,0,0,-1,0,0,2147483647,0,2147483647,0,0,2147483647,2147483647,-1,2147483647,-1,2147483647,0,-1,-1,0,0,-1,-1,-1,2147483647,2147483647,2147483647,2147483647,0,-1,2147483647,-1,-1,0,2147483647,-1,-1,-1,-1,-1,-1,-1,-1,2147483647,-1,0,-1,0,0,-1,0,-1,-1,0,0,2147483647,-1,0,-1,0,0,-1,-1,-1,-1,-1,-1,2147483647,0,2147483647,0,-1,2147483647,0,2147483647,2147483647,2147483647,0,0,2147483647,-1},{2147483647,2147483647,0,2147483647,2147483647,2147483647,0,2147483647,0,-1,0,-1,0,2147483647,0,-1,2147483647,2147483647,0,2147483647,0,-1,-1,-1,2147483647,0,-1,-1,2147483647,-1,-1,0,-1,2147483647,0,2147483647,-1,0,0,2147483647,2147483647,-1,-1,0,2147483647,-1,0,0,0,-1,2147483647,0,0,-1,0,-1,-1,-1,0,2147483647,0,-1,0,2147483647,-1,0,0,-1,0,2147483647,0,2147483647,2147483647,0,-1,2147483647,2147483647,2147483647,-1,2147483647,0,-1,2147483647,0,2147483647,2147483647,0,-1,0,2147483647,2147483647,0,0,2147483647,-1,0,-1,0,2147483647,2147483647,0,-1,0,-1,0,-1,2147483647,-1,2147483647,2147483647,2147483647,2147483647,0,-1,0,0,-1,-1,2147483647,2147483647,0,0,-1,0,0,2147483647,0,0,-1,0,2147483647,2147483647,2147483647,0,0,0,0,0,-1,2147483647,-1,0,0,-1,-1,2147483647,2147483647,0,-1,-1,2147483647,0,-1,-1,0,2147483647,0,0,2147483647,0,-1,2147483647,0,-1,-1,0,0,2147483647,0,2147483647,2147483647,2147483647,2147483647,2147483647,-1,2147483647,-1,2147483647,2147483647,0,0,0,0,-1,2147483647,-1,0,2147483647,-1,-1,2147483647,0,0,-1,0,2147483647,2147483647,0,0,-1,0,-1,2147483647,0,0,-1,-1,0,2147483647,-1,-1,-1,-1,-1,-1,0,0,-1,2147483647,-1,0},{2147483647,2147483647,0,-1,-1,0,2147483647,-1,0,0,-1,-1,-1,2147483647,0,2147483647,-1,2147483647,2147483647,2147483647,2147483647,-1,-1,2147483647,2147483647,2147483647,-1,-1,0,-1,-1,2147483647,2147483647,-1,-1,2147483647,0,2147483647,2147483647,0,-1,2147483647,2147483647,-1,0,2147483647,-1,-1,0,2147483647,-1,0,0,2147483647,0,-1,0,-1,2147483647,-1,0,-1,0,2147483647,0,0,2147483647,0,-1,-1,-1,0,0,0,0,0,0,2147483647,2147483647,0,2147483647,2147483647,0,-1,2147483647,-1,-1,0,2147483647,-1,2147483647,2147483647,-1,-1,-1,0,0,2147483647,2147483647,-1,0,2147483647,0,-1,-1,0,0,-1,-1,-1,0,0,2147483647,2147483647,-1,-1,-1,0,2147483647,2147483647,-1,2147483647,2147483647,-1,2147483647,-1,0,-1,-1,-1,0,-1,-1,2147483647,0,-1,-1,2147483647,-1,-1,-1,0,0,2147483647,2147483647,0,2147483647,-1,2147483647,-1,0,-1,2147483647,-1,0,-1,2147483647,-1,2147483647,2147483647,0,0,0,0,0,0,2147483647,-1,0,0,-1,0,2147483647,2147483647,2147483647,2147483647,0,2147483647,-1,0,-1,2147483647,0,2147483647,0,2147483647,2147483647,0,0,2147483647,0,0,0,0,2147483647,2147483647,-1,0,-1,0,0,0,0,2147483647,2147483647,2147483647,2147483647,0,0,-1,-1,-1,2147483647,2147483647,0,0,-1,2147483647,2147483647,0,0},{0,-1,2147483647,2147483647,0,-1,0,0,-1,0,0,-1,0,2147483647,-1,-1,-1,-1,2147483647,-1,0,-1,0,2147483647,0,-1,2147483647,-1,2147483647,0,-1,-1,0,0,0,0,-1,0,2147483647,0,-1,0,0,-1,-1,2147483647,0,0,2147483647,-1,-1,2147483647,0,0,-1,-1,0,-1,2147483647,0,-1,0,-1,2147483647,0,0,-1,-1,0,0,-1,-1,-1,2147483647,2147483647,-1,-1,-1,0,0,0,2147483647,0,0,0,0,0,0,-1,2147483647,2147483647,-1,2147483647,-1,0,2147483647,-1,2147483647,0,2147483647,2147483647,2147483647,0,2147483647,2147483647,-1,-1,2147483647,2147483647,-1,-1,-1,2147483647,0,0,0,0,-1,0,-1,-1,-1,-1,0,-1,-1,-1,0,2147483647,0,-1,2147483647,-1,-1,0,-1,0,2147483647,0,-1,0,-1,0,-1,-1,0,-1,-1,0,2147483647,2147483647,0,-1,-1,-1,2147483647,2147483647,-1,2147483647,0,2147483647,2147483647,-1,-1,0,-1,-1,0,-1,-1,2147483647,2147483647,-1,-1,0,-1,2147483647,-1,-1,0,-1,2147483647,2147483647,-1,-1,-1,2147483647,0,-1,0,2147483647,0,2147483647,-1,0,-1,-1,-1,-1,0,2147483647,2147483647,2147483647,0,0,2147483647,2147483647,-1,2147483647,0,-1,2147483647,0,-1,0,0,2147483647,2147483647,2147483647,2147483647,-1},{2147483647,0,2147483647,0,2147483647,0,2147483647,0,-1,2147483647,2147483647,2147483647,0,2147483647,2147483647,0,2147483647,-1,-1,2147483647,-1,2147483647,0,0,0,2147483647,2147483647,2147483647,0,0,2147483647,2147483647,-1,0,2147483647,0,2147483647,2147483647,0,0,2147483647,-1,-1,2147483647,-1,2147483647,-1,-1,2147483647,-1,2147483647,-1,-1,0,-1,0,0,2147483647,-1,-1,-1,2147483647,-1,2147483647,-1,0,2147483647,2147483647,-1,-1,2147483647,2147483647,2147483647,2147483647,0,2147483647,-1,0,2147483647,0,0,-1,0,-1,2147483647,-1,-1,0,0,2147483647,0,-1,-1,-1,2147483647,-1,2147483647,-1,2147483647,0,2147483647,-1,-1,-1,-1,0,-1,-1,0,-1,2147483647,2147483647,-1,0,-1,2147483647,2147483647,2147483647,2147483647,-1,-1,0,2147483647,0,2147483647,0,-1,-1,2147483647,-1,0,0,2147483647,0,-1,2147483647,-1,2147483647,-1,2147483647,-1,-1,0,2147483647,0,0,-1,2147483647,0,0,-1,0,0,2147483647,-1,2147483647,-1,-1,0,2147483647,2147483647,2147483647,2147483647,2147483647,0,2147483647,0,2147483647,0,-1,0,-1,-1,0,-1,-1,2147483647,-1,0,2147483647,2147483647,0,2147483647,-1,-1,0,0,0,-1,2147483647,-1,0,2147483647,0,2147483647,0,-1,2147483647,2147483647,-1,-1,0,-1,0,2147483647,-1,-1,2147483647,-1,0,0,0,2147483647,0,2147483647,2147483647,2147483647,0,0,0,0},{2147483647,0,2147483647,-1,-1,2147483647,2147483647,0,0,-1,-1,0,0,-1,2147483647,2147483647,0,2147483647,0,-1,2147483647,0,-1,-1,2147483647,2147483647,2147483647,-1,0,-1,0,0,0,0,-1,-1,2147483647,2147483647,-1,2147483647,-1,0,0,2147483647,0,0,2147483647,-1,-1,-1,-1,0,-1,2147483647,0,-1,0,2147483647,-1,-1,2147483647,2147483647,0,-1,2147483647,0,-1,2147483647,-1,2147483647,-1,2147483647,-1,0,2147483647,0,0,-1,0,0,-1,-1,0,0,-1,-1,0,-1,2147483647,-1,2147483647,0,0,2147483647,0,2147483647,2147483647,0,0,-1,-1,2147483647,0,2147483647,2147483647,-1,2147483647,2147483647,2147483647,2147483647,0,2147483647,2147483647,2147483647,2147483647,0,0,0,0,2147483647,0,0,-1,2147483647,-1,-1,2147483647,2147483647,0,-1,2147483647,-1,2147483647,2147483647,-1,2147483647,0,0,0,2147483647,0,2147483647,0,2147483647,2147483647,0,-1,2147483647,0,2147483647,0,2147483647,-1,2147483647,0,0,2147483647,2147483647,-1,2147483647,-1,2147483647,-1,2147483647,2147483647,0,0,0,2147483647,0,2147483647,0,0,-1,-1,2147483647,-1,-1,-1,-1,0,0,-1,2147483647,0,0,2147483647,2147483647,0,-1,0,0,-1,-1,0,0,-1,2147483647,2147483647,2147483647,2147483647,0,-1,2147483647,0,0,0,0,0,2147483647,0,-1,-1,0,-1,-1,2147483647,2147483647,2147483647,-1,-1},{-1,2147483647,-1,-1,0,-1,-1,2147483647,-1,0,2147483647,2147483647,2147483647,2147483647,2147483647,-1,2147483647,0,-1,0,0,-1,-1,0,2147483647,-1,-1,0,-1,-1,-1,0,-1,2147483647,-1,2147483647,2147483647,-1,2147483647,-1,2147483647,0,0,-1,2147483647,0,-1,0,2147483647,0,2147483647,-1,2147483647,2147483647,0,0,0,-1,-1,-1,0,-1,-1,-1,0,2147483647,0,0,0,-1,-1,-1,-1,0,0,-1,-1,0,0,-1,0,0,-1,0,2147483647,2147483647,-1,2147483647,0,2147483647,0,2147483647,-1,-1,2147483647,-1,0,2147483647,-1,0,0,0,-1,0,-1,0,0,2147483647,-1,2147483647,2147483647,0,2147483647,0,2147483647,0,-1,-1,0,2147483647,-1,0,0,0,0,0,0,2147483647,0,0,2147483647,2147483647,-1,0,-1,-1,0,2147483647,2147483647,0,-1,-1,2147483647,2147483647,2147483647,-1,-1,0,-1,0,2147483647,2147483647,0,0,0,0,0,2147483647,0,2147483647,2147483647,0,2147483647,2147483647,-1,-1,-1,-1,2147483647,-1,2147483647,-1,0,-1,-1,0,0,-1,0,0,0,2147483647,0,0,-1,-1,-1,-1,2147483647,0,2147483647,2147483647,-1,0,-1,-1,0,-1,0,-1,0,2147483647,0,-1,0,0,0,-1,0,2147483647,0,-1,0,0,0,0,-1,2147483647,2147483647,-1,0},{0,2147483647,0,2147483647,2147483647,2147483647,-1,-1,-1,2147483647,2147483647,2147483647,0,0,0,-1,-1,2147483647,-1,-1,2147483647,2147483647,-1,0,0,-1,-1,0,0,-1,-1,-1,0,2147483647,2147483647,2147483647,2147483647,0,-1,2147483647,2147483647,-1,0,0,2147483647,0,-1,0,-1,2147483647,-1,-1,2147483647,-1,2147483647,2147483647,0,0,-1,2147483647,0,0,-1,-1,2147483647,2147483647,-1,2147483647,2147483647,2147483647,0,0,2147483647,-1,2147483647,2147483647,2147483647,-1,2147483647,2147483647,2147483647,2147483647,2147483647,0,2147483647,2147483647,2147483647,0,-1,-1,0,2147483647,2147483647,-1,0,-1,-1,-1,0,0,0,0,-1,2147483647,2147483647,-1,0,0,0,2147483647,-1,0,-1,-1,2147483647,2147483647,-1,-1,-1,0,2147483647,-1,-1,2147483647,0,0,-1,2147483647,2147483647,2147483647,-1,-1,-1,-1,0,-1,0,0,0,2147483647,0,-1,0,-1,-1,-1,2147483647,0,2147483647,0,0,-1,-1,-1,0,2147483647,0,-1,2147483647,0,0,2147483647,2147483647,0,-1,2147483647,-1,2147483647,0,2147483647,2147483647,-1,2147483647,0,-1,0,-1,-1,-1,0,-1,2147483647,-1,2147483647,2147483647,2147483647,0,2147483647,2147483647,-1,2147483647,2147483647,-1,0,2147483647,0,2147483647,-1,-1,0,2147483647,2147483647,0,2147483647,-1,0,0,0,0,2147483647,2147483647,-1,-1,2147483647,0,2147483647,-1,-1,-1,-1,2147483647},{0,2147483647,0,2147483647,0,2147483647,-1,0,0,-1,2147483647,-1,-1,0,0,2147483647,-1,2147483647,-1,-1,-1,-1,-1,2147483647,0,2147483647,2147483647,2147483647,-1,-1,0,0,2147483647,-1,2147483647,-1,-1,-1,0,2147483647,2147483647,0,2147483647,-1,0,2147483647,2147483647,0,-1,2147483647,0,-1,2147483647,2147483647,2147483647,-1,-1,-1,2147483647,-1,2147483647,-1,-1,0,0,-1,-1,2147483647,0,0,2147483647,0,-1,0,-1,-1,2147483647,-1,0,0,2147483647,-1,-1,2147483647,0,0,-1,-1,2147483647,-1,0,-1,2147483647,2147483647,2147483647,2147483647,2147483647,0,2147483647,2147483647,-1,-1,-1,-1,-1,2147483647,-1,2147483647,-1,2147483647,0,0,0,0,-1,0,-1,-1,2147483647,2147483647,-1,2147483647,0,-1,0,2147483647,2147483647,2147483647,0,2147483647,-1,2147483647,0,-1,-1,2147483647,0,0,0,0,0,2147483647,2147483647,2147483647,-1,2147483647,-1,0,-1,0,0,0,-1,2147483647,2147483647,0,0,-1,0,-1,-1,0,0,2147483647,-1,2147483647,-1,2147483647,2147483647,0,2147483647,-1,-1,2147483647,0,2147483647,2147483647,-1,0,-1,2147483647,0,-1,-1,0,2147483647,-1,-1,-1,2147483647,-1,2147483647,0,0,2147483647,-1,-1,0,-1,0,-1,0,2147483647,0,-1,-1,-1,2147483647,-1,2147483647,-1,2147483647,2147483647,-1,-1,2147483647,-1,-1,-1,-1,-1},{2147483647,2147483647,-1,-1,2147483647,-1,0,-1,2147483647,2147483647,2147483647,0,-1,-1,2147483647,2147483647,-1,0,0,0,0,0,2147483647,0,-1,2147483647,-1,0,-1,0,-1,-1,0,2147483647,-1,2147483647,2147483647,-1,-1,-1,-1,2147483647,-1,0,0,0,2147483647,0,2147483647,0,-1,2147483647,2147483647,-1,2147483647,2147483647,-1,0,2147483647,0,-1,2147483647,0,2147483647,0,0,2147483647,2147483647,0,-1,0,0,0,0,-1,0,0,2147483647,-1,-1,2147483647,-1,0,2147483647,0,2147483647,0,2147483647,-1,2147483647,0,2147483647,2147483647,0,-1,0,0,0,0,-1,-1,-1,2147483647,2147483647,2147483647,-1,-1,0,-1,-1,0,-1,2147483647,-1,0,2147483647,0,-1,2147483647,2147483647,0,2147483647,2147483647,2147483647,-1,2147483647,2147483647,0,0,2147483647,-1,0,0,2147483647,0,2147483647,0,0,2147483647,0,-1,0,0,0,2147483647,2147483647,2147483647,0,2147483647,2147483647,0,0,-1,2147483647,-1,-1,2147483647,-1,-1,-1,2147483647,-1,2147483647,0,-1,-1,0,2147483647,-1,0,0,-1,-1,-1,2147483647,-1,2147483647,2147483647,2147483647,-1,-1,0,0,-1,0,-1,-1,0,-1,-1,0,2147483647,-1,0,2147483647,2147483647,-1,0,0,-1,2147483647,2147483647,-1,2147483647,0,2147483647,2147483647,-1,0,-1,0,0,2147483647,2147483647,-1,-1,-1,0,-1,-1,-1},{2147483647,2147483647,-1,0,0,-1,-1,2147483647,0,2147483647,-1,0,2147483647,2147483647,2147483647,2147483647,-1,0,0,2147483647,-1,-1,-1,2147483647,0,2147483647,-1,0,-1,2147483647,-1,-1,2147483647,-1,2147483647,2147483647,0,0,-1,-1,2147483647,2147483647,2147483647,2147483647,-1,0,-1,2147483647,-1,0,0,0,2147483647,0,-1,0,0,-1,2147483647,-1,2147483647,0,2147483647,2147483647,2147483647,-1,-1,-1,0,-1,0,0,2147483647,2147483647,0,-1,2147483647,-1,-1,0,2147483647,0,-1,0,2147483647,-1,-1,-1,-1,-1,-1,0,-1,0,0,0,-1,2147483647,0,-1,2147483647,-1,2147483647,-1,2147483647,2147483647,0,0,-1,0,2147483647,-1,-1,-1,2147483647,0,-1,0,-1,2147483647,2147483647,0,2147483647,0,2147483647,2147483647,0,2147483647,0,-1,-1,0,0,0,2147483647,2147483647,2147483647,-1,-1,2147483647,2147483647,0,2147483647,-1,2147483647,-1,0,0,-1,2147483647,0,2147483647,0,0,0,0,-1,0,-1,2147483647,2147483647,2147483647,0,0,0,2147483647,0,-1,-1,-1,2147483647,2147483647,-1,2147483647,2147483647,-1,2147483647,2147483647,0,-1,-1,-1,0,2147483647,0,2147483647,0,0,0,2147483647,0,2147483647,-1,-1,2147483647,0,-1,2147483647,0,-1,-1,-1,0,0,0,-1,0,2147483647,0,0,-1,2147483647,2147483647,0,0,2147483647,2147483647,2147483647,-1,0,2147483647},{-1,0,0,2147483647,2147483647,-1,2147483647,-1,0,0,-1,-1,0,2147483647,-1,2147483647,-1,2147483647,2147483647,0,-1,0,2147483647,2147483647,2147483647,2147483647,2147483647,0,-1,2147483647,2147483647,-1,2147483647,2147483647,0,-1,2147483647,-1,-1,0,0,-1,0,-1,-1,-1,2147483647,-1,-1,0,2147483647,0,-1,2147483647,0,0,0,2147483647,0,-1,0,2147483647,2147483647,0,-1,0,0,0,-1,-1,2147483647,-1,0,-1,2147483647,2147483647,0,0,0,2147483647,0,0,2147483647,0,2147483647,0,2147483647,2147483647,2147483647,2147483647,0,-1,0,-1,0,2147483647,0,0,2147483647,0,2147483647,0,2147483647,0,2147483647,-1,0,-1,0,0,0,0,0,2147483647,0,0,0,-1,-1,2147483647,2147483647,2147483647,2147483647,-1,-1,0,2147483647,2147483647,0,2147483647,0,2147483647,2147483647,0,-1,0,2147483647,2147483647,0,0,-1,-1,-1,0,-1,-1,-1,-1,2147483647,2147483647,0,-1,-1,0,0,2147483647,-1,2147483647,2147483647,-1,2147483647,0,2147483647,-1,2147483647,-1,2147483647,2147483647,2147483647,-1,2147483647,2147483647,-1,0,0,0,2147483647,-1,2147483647,-1,0,0,0,-1,2147483647,2147483647,2147483647,-1,0,0,-1,0,-1,-1,2147483647,0,2147483647,0,2147483647,2147483647,2147483647,-1,-1,-1,2147483647,0,0,2147483647,2147483647,2147483647,-1,2147483647,-1,-1,-1,-1,2147483647,2147483647,0,0,-1},{-1,2147483647,2147483647,0,2147483647,-1,0,0,-1,2147483647,2147483647,2147483647,2147483647,-1,2147483647,0,0,2147483647,0,2147483647,0,2147483647,0,-1,2147483647,0,2147483647,0,-1,-1,-1,0,2147483647,0,0,0,-1,-1,-1,-1,2147483647,2147483647,0,2147483647,0,0,0,-1,0,0,-1,2147483647,0,0,0,0,-1,2147483647,0,0,2147483647,-1,2147483647,-1,2147483647,2147483647,-1,2147483647,0,2147483647,0,2147483647,2147483647,-1,0,2147483647,0,-1,2147483647,0,2147483647,-1,-1,-1,-1,2147483647,2147483647,-1,0,2147483647,-1,0,2147483647,0,0,2147483647,0,2147483647,-1,-1,2147483647,-1,0,-1,0,-1,2147483647,-1,-1,-1,0,2147483647,0,-1,-1,2147483647,2147483647,2147483647,2147483647,0,0,2147483647,0,0,2147483647,2147483647,-1,0,-1,2147483647,0,-1,0,0,-1,2147483647,0,-1,-1,2147483647,0,-1,0,-1,2147483647,-1,0,-1,0,0,0,0,-1,2147483647,0,-1,0,-1,-1,0,-1,2147483647,2147483647,0,-1,0,-1,-1,0,0,0,-1,0,2147483647,0,0,2147483647,0,0,2147483647,2147483647,2147483647,0,0,-1,0,2147483647,2147483647,-1,2147483647,0,0,-1,0,-1,0,0,-1,0,2147483647,0,2147483647,0,0,-1,0,0,-1,2147483647,-1,0,0,0,0,2147483647,2147483647,-1,2147483647,0,-1,-1},{0,2147483647,-1,2147483647,2147483647,2147483647,0,2147483647,-1,2147483647,-1,2147483647,2147483647,-1,-1,2147483647,-1,-1,-1,0,2147483647,-1,-1,0,-1,-1,0,0,-1,2147483647,-1,-1,0,-1,0,0,2147483647,2147483647,2147483647,2147483647,0,2147483647,0,-1,-1,0,-1,0,0,-1,0,2147483647,-1,-1,0,0,2147483647,0,0,-1,0,2147483647,0,0,0,2147483647,-1,-1,2147483647,-1,-1,-1,2147483647,-1,2147483647,0,0,2147483647,2147483647,0,-1,2147483647,2147483647,-1,-1,0,-1,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,0,0,2147483647,-1,0,-1,2147483647,2147483647,-1,2147483647,0,2147483647,-1,2147483647,0,0,-1,-1,0,-1,2147483647,2147483647,0,-1,2147483647,-1,-1,0,2147483647,0,-1,0,-1,-1,0,-1,0,2147483647,0,0,0,2147483647,-1,2147483647,0,0,-1,2147483647,2147483647,-1,2147483647,-1,-1,0,2147483647,-1,0,0,-1,2147483647,-1,2147483647,2147483647,0,0,-1,-1,-1,2147483647,-1,2147483647,0,2147483647,-1,0,0,-1,-1,0,2147483647,2147483647,-1,2147483647,0,2147483647,2147483647,2147483647,2147483647,2147483647,-1,0,0,0,2147483647,-1,-1,-1,2147483647,-1,-1,-1,2147483647,0,0,0,2147483647,-1,-1,2147483647,-1,-1,0,2147483647,2147483647,2147483647,2147483647,0,2147483647,0,2147483647,-1,2147483647,2147483647,-1,-1,2147483647},{-1,2147483647,2147483647,2147483647,0,2147483647,-1,0,0,-1,0,-1,-1,-1,2147483647,0,-1,0,-1,2147483647,2147483647,0,-1,-1,-1,2147483647,2147483647,-1,2147483647,2147483647,-1,0,2147483647,-1,2147483647,0,2147483647,0,0,2147483647,2147483647,-1,0,-1,-1,0,-1,2147483647,2147483647,0,0,0,0,2147483647,0,-1,0,2147483647,2147483647,-1,0,0,0,2147483647,2147483647,2147483647,2147483647,2147483647,0,2147483647,0,2147483647,-1,2147483647,2147483647,0,-1,-1,0,2147483647,2147483647,0,-1,2147483647,-1,2147483647,-1,0,0,2147483647,-1,0,2147483647,-1,0,0,-1,-1,0,2147483647,2147483647,-1,-1,-1,2147483647,0,2147483647,-1,0,0,-1,0,0,0,0,0,0,2147483647,0,0,2147483647,0,2147483647,0,-1,0,0,0,-1,-1,0,2147483647,0,2147483647,2147483647,-1,0,-1,2147483647,0,0,2147483647,2147483647,2147483647,2147483647,0,2147483647,2147483647,-1,-1,-1,-1,0,2147483647,0,-1,-1,0,0,2147483647,0,0,2147483647,2147483647,0,0,0,2147483647,-1,0,2147483647,0,0,0,2147483647,0,2147483647,0,0,-1,0,-1,0,-1,0,0,2147483647,-1,-1,-1,-1,-1,-1,2147483647,0,2147483647,2147483647,2147483647,-1,2147483647,-1,0,2147483647,0,-1,0,-1,0,0,-1,2147483647,-1,0,-1,0,2147483647,2147483647,2147483647,-1,-1,0},{2147483647,-1,2147483647,0,2147483647,-1,2147483647,2147483647,-1,2147483647,-1,2147483647,0,0,2147483647,0,-1,2147483647,2147483647,0,-1,0,-1,-1,-1,2147483647,0,-1,-1,2147483647,-1,0,0,-1,2147483647,-1,-1,-1,0,-1,2147483647,-1,2147483647,2147483647,0,-1,0,-1,-1,0,-1,2147483647,2147483647,-1,2147483647,2147483647,0,2147483647,0,2147483647,-1,-1,-1,-1,2147483647,0,-1,-1,2147483647,0,-1,2147483647,0,-1,2147483647,0,2147483647,2147483647,2147483647,2147483647,2147483647,-1,2147483647,0,-1,-1,-1,-1,0,2147483647,-1,-1,0,0,2147483647,-1,0,-1,0,2147483647,-1,2147483647,0,0,2147483647,2147483647,2147483647,-1,0,-1,2147483647,-1,2147483647,-1,-1,2147483647,2147483647,-1,0,0,-1,0,-1,-1,2147483647,-1,-1,0,0,-1,0,0,0,-1,-1,2147483647,2147483647,-1,-1,2147483647,0,2147483647,-1,2147483647,2147483647,-1,-1,-1,0,2147483647,2147483647,0,0,2147483647,0,2147483647,-1,2147483647,2147483647,0,-1,2147483647,-1,-1,0,2147483647,2147483647,2147483647,-1,2147483647,2147483647,2147483647,2147483647,2147483647,0,2147483647,2147483647,0,-1,-1,0,-1,0,0,2147483647,-1,0,0,2147483647,0,0,2147483647,0,2147483647,0,0,-1,-1,0,2147483647,2147483647,-1,-1,2147483647,0,-1,2147483647,0,2147483647,2147483647,2147483647,2147483647,-1,2147483647,-1,2147483647,2147483647,0,2147483647,-1,2147483647},{0,2147483647,-1,0,2147483647,2147483647,-1,2147483647,2147483647,-1,-1,-1,0,0,2147483647,2147483647,2147483647,2147483647,-1,0,2147483647,0,2147483647,2147483647,-1,0,-1,2147483647,0,0,2147483647,-1,2147483647,-1,-1,-1,-1,-1,2147483647,0,2147483647,2147483647,2147483647,-1,-1,-1,2147483647,0,2147483647,-1,0,0,0,-1,0,2147483647,2147483647,0,2147483647,2147483647,0,0,2147483647,2147483647,0,-1,2147483647,-1,2147483647,-1,-1,2147483647,0,0,-1,2147483647,2147483647,2147483647,2147483647,-1,0,-1,2147483647,2147483647,0,-1,2147483647,2147483647,0,-1,-1,0,-1,0,2147483647,-1,0,2147483647,0,2147483647,0,0,0,-1,0,2147483647,2147483647,2147483647,0,0,-1,2147483647,-1,2147483647,2147483647,-1,2147483647,-1,2147483647,0,2147483647,2147483647,2147483647,-1,0,0,2147483647,0,2147483647,-1,2147483647,-1,2147483647,0,0,-1,-1,0,-1,0,-1,-1,2147483647,2147483647,2147483647,-1,-1,-1,-1,2147483647,0,-1,-1,-1,-1,-1,2147483647,0,-1,0,-1,-1,0,0,0,2147483647,-1,2147483647,-1,0,2147483647,-1,0,-1,0,0,2147483647,2147483647,-1,0,0,-1,2147483647,2147483647,-1,0,0,0,-1,-1,2147483647,0,2147483647,-1,2147483647,0,2147483647,-1,0,0,-1,-1,0,0,2147483647,-1,0,-1,0,0,2147483647,2147483647,0,0,-1,0,2147483647,2147483647,-1,2147483647,-1},{0,0,-1,2147483647,2147483647,2147483647,-1,2147483647,0,0,-1,2147483647,-1,2147483647,0,2147483647,0,-1,2147483647,2147483647,-1,0,0,0,2147483647,-1,2147483647,2147483647,0,-1,0,2147483647,-1,-1,-1,0,0,0,-1,-1,2147483647,0,0,-1,-1,0,0,0,0,0,0,2147483647,-1,-1,-1,-1,-1,0,-1,-1,0,-1,-1,0,2147483647,2147483647,0,0,2147483647,0,2147483647,0,2147483647,2147483647,2147483647,2147483647,-1,0,-1,2147483647,2147483647,2147483647,2147483647,-1,-1,0,2147483647,2147483647,-1,2147483647,2147483647,-1,0,-1,-1,2147483647,-1,-1,-1,2147483647,0,-1,-1,0,2147483647,-1,2147483647,-1,-1,2147483647,0,2147483647,0,0,-1,-1,0,2147483647,2147483647,0,2147483647,-1,-1,-1,-1,0,-1,-1,2147483647,0,2147483647,2147483647,-1,0,0,-1,-1,-1,-1,-1,0,0,-1,0,0,-1,2147483647,2147483647,0,0,0,0,2147483647,-1,2147483647,-1,0,-1,-1,2147483647,0,0,2147483647,2147483647,-1,2147483647,0,2147483647,2147483647,2147483647,0,-1,0,2147483647,0,2147483647,0,2147483647,0,2147483647,-1,2147483647,0,-1,0,2147483647,-1,-1,2147483647,-1,-1,0,0,0,0,-1,2147483647,2147483647,-1,0,-1,0,2147483647,0,-1,2147483647,0,2147483647,-1,0,0,2147483647,2147483647,0,-1,-1,-1,0,2147483647,2147483647,0},{0,-1,-1,0,-1,2147483647,-1,-1,2147483647,0,0,2147483647,0,2147483647,2147483647,0,0,2147483647,2147483647,0,2147483647,0,-1,-1,0,2147483647,-1,2147483647,0,2147483647,0,-1,-1,-1,2147483647,2147483647,0,2147483647,2147483647,-1,-1,-1,0,0,2147483647,2147483647,2147483647,-1,2147483647,2147483647,0,2147483647,0,-1,-1,-1,0,0,0,-1,2147483647,0,2147483647,0,2147483647,-1,-1,0,0,2147483647,2147483647,2147483647,0,0,2147483647,0,0,-1,2147483647,2147483647,-1,0,-1,-1,0,2147483647,2147483647,-1,-1,2147483647,2147483647,0,-1,2147483647,2147483647,0,-1,2147483647,0,2147483647,0,-1,-1,2147483647,2147483647,2147483647,0,0,2147483647,-1,2147483647,-1,-1,-1,0,0,0,2147483647,2147483647,-1,2147483647,2147483647,2147483647,-1,-1,-1,0,0,-1,2147483647,-1,2147483647,-1,0,2147483647,-1,-1,0,-1,0,2147483647,0,0,0,-1,0,2147483647,-1,2147483647,-1,-1,-1,0,-1,2147483647,-1,-1,0,-1,-1,0,2147483647,-1,0,2147483647,0,-1,2147483647,0,2147483647,2147483647,-1,0,0,0,0,-1,0,-1,-1,-1,2147483647,2147483647,-1,-1,-1,0,0,-1,2147483647,2147483647,2147483647,2147483647,0,-1,0,2147483647,-1,-1,-1,0,2147483647,0,-1,-1,-1,0,-1,-1,-1,2147483647,0,2147483647,2147483647,-1,2147483647,2147483647,0,-1,-1,2147483647},{0,-1,-1,-1,-1,2147483647,2147483647,-1,0,2147483647,-1,2147483647,-1,2147483647,2147483647,2147483647,2147483647,-1,2147483647,0,2147483647,2147483647,0,-1,-1,-1,0,0,0,0,-1,0,0,0,0,2147483647,-1,-1,2147483647,-1,0,-1,0,0,0,2147483647,0,2147483647,2147483647,-1,2147483647,0,2147483647,2147483647,2147483647,-1,2147483647,0,-1,-1,0,-1,0,2147483647,2147483647,2147483647,-1,0,-1,-1,2147483647,0,0,-1,2147483647,2147483647,-1,0,2147483647,-1,2147483647,2147483647,-1,-1,0,0,-1,-1,0,2147483647,2147483647,2147483647,2147483647,-1,0,0,-1,-1,2147483647,-1,0,0,2147483647,2147483647,-1,2147483647,-1,2147483647,0,-1,0,2147483647,-1,2147483647,2147483647,2147483647,-1,2147483647,2147483647,-1,0,2147483647,-1,-1,2147483647,-1,-1,-1,-1,0,-1,0,2147483647,0,2147483647,0,0,0,-1,-1,2147483647,2147483647,0,0,-1,-1,-1,2147483647,2147483647,-1,2147483647,0,0,2147483647,2147483647,2147483647,0,2147483647,0,2147483647,0,-1,2147483647,2147483647,-1,2147483647,2147483647,-1,0,0,2147483647,-1,2147483647,0,2147483647,2147483647,2147483647,2147483647,0,-1,2147483647,0,2147483647,0,2147483647,2147483647,0,2147483647,-1,2147483647,-1,0,0,-1,0,-1,0,0,-1,-1,2147483647,2147483647,2147483647,-1,0,0,2147483647,0,-1,0,-1,0,-1,-1,2147483647,-1,-1,2147483647,-1,2147483647,2147483647},{0,2147483647,0,-1,-1,-1,-1,0,2147483647,2147483647,2147483647,-1,2147483647,-1,-1,0,0,2147483647,0,-1,-1,0,0,2147483647,0,2147483647,0,-1,0,2147483647,2147483647,-1,-1,0,2147483647,-1,0,0,-1,2147483647,2147483647,-1,2147483647,-1,-1,-1,2147483647,2147483647,0,0,0,0,0,2147483647,-1,0,-1,-1,0,0,2147483647,-1,-1,2147483647,0,0,-1,0,0,2147483647,2147483647,2147483647,0,2147483647,0,0,0,-1,0,0,-1,-1,2147483647,0,0,0,0,-1,0,0,-1,-1,-1,-1,-1,0,2147483647,2147483647,2147483647,2147483647,0,2147483647,-1,2147483647,0,-1,2147483647,0,0,2147483647,2147483647,2147483647,0,2147483647,-1,2147483647,-1,2147483647,0,0,2147483647,2147483647,-1,2147483647,0,2147483647,2147483647,2147483647,-1,0,2147483647,0,0,-1,0,2147483647,0,2147483647,0,2147483647,0,0,2147483647,0,2147483647,0,0,2147483647,-1,0,-1,-1,0,0,2147483647,-1,2147483647,0,-1,-1,-1,-1,-1,-1,-1,2147483647,-1,-1,-1,2147483647,-1,2147483647,0,-1,0,0,-1,-1,2147483647,0,0,-1,2147483647,-1,-1,-1,2147483647,-1,2147483647,-1,0,0,0,2147483647,0,0,0,0,0,-1,2147483647,0,2147483647,2147483647,-1,2147483647,0,-1,2147483647,0,2147483647,0,2147483647,2147483647,0,0,0,-1,2147483647,-1,0},{0,-1,-1,0,-1,-1,-1,0,2147483647,0,0,2147483647,2147483647,0,0,0,0,0,-1,2147483647,0,2147483647,-1,2147483647,2147483647,-1,0,2147483647,0,-1,2147483647,0,-1,2147483647,2147483647,2147483647,0,-1,-1,2147483647,-1,2147483647,-1,2147483647,-1,-1,2147483647,2147483647,2147483647,0,0,0,-1,2147483647,0,2147483647,0,2147483647,-1,2147483647,-1,2147483647,-1,2147483647,-1,0,2147483647,0,-1,0,-1,0,0,2147483647,-1,-1,2147483647,-1,-1,-1,0,2147483647,0,-1,-1,0,0,-1,2147483647,2147483647,0,-1,0,-1,-1,0,-1,0,2147483647,0,2147483647,2147483647,2147483647,2147483647,0,-1,-1,2147483647,2147483647,2147483647,-1,-1,-1,-1,2147483647,0,-1,-1,0,-1,-1,0,0,-1,-1,-1,2147483647,0,-1,2147483647,2147483647,-1,-1,2147483647,2147483647,-1,-1,0,-1,2147483647,0,-1,2147483647,-1,-1,0,2147483647,-1,2147483647,-1,-1,2147483647,2147483647,0,0,0,0,0,-1,2147483647,-1,-1,0,2147483647,0,0,0,0,0,-1,2147483647,0,2147483647,-1,-1,0,-1,-1,0,0,2147483647,0,2147483647,0,-1,2147483647,-1,2147483647,-1,0,0,-1,2147483647,2147483647,2147483647,-1,2147483647,0,2147483647,2147483647,-1,-1,-1,-1,-1,-1,2147483647,2147483647,2147483647,0,2147483647,0,-1,0,0,0,-1,0,2147483647,-1,2147483647},{2147483647,-1,-1,0,-1,2147483647,0,0,2147483647,2147483647,0,2147483647,-1,2147483647,0,-1,0,-1,0,2147483647,0,-1,0,-1,-1,2147483647,0,0,-1,0,2147483647,-1,2147483647,-1,2147483647,0,-1,2147483647,2147483647,2147483647,-1,2147483647,2147483647,-1,0,2147483647,2147483647,-1,-1,2147483647,2147483647,0,2147483647,-1,2147483647,-1,2147483647,-1,0,0,-1,2147483647,2147483647,0,0,0,0,-1,-1,0,0,0,2147483647,0,0,2147483647,0,-1,0,0,-1,2147483647,2147483647,0,-1,0,2147483647,2147483647,0,2147483647,-1,2147483647,2147483647,-1,2147483647,-1,2147483647,0,2147483647,0,-1,2147483647,0,0,-1,-1,-1,0,-1,2147483647,0,-1,-1,2147483647,0,2147483647,-1,0,0,2147483647,2147483647,0,0,0,2147483647,0,-1,-1,2147483647,0,0,2147483647,2147483647,-1,-1,-1,-1,0,2147483647,0,-1,0,-1,2147483647,0,2147483647,0,-1,2147483647,0,-1,0,2147483647,-1,0,0,-1,0,-1,0,0,-1,-1,-1,2147483647,0,-1,2147483647,2147483647,2147483647,-1,2147483647,-1,2147483647,2147483647,2147483647,2147483647,0,0,2147483647,-1,2147483647,-1,-1,0,0,2147483647,0,-1,0,-1,2147483647,-1,-1,2147483647,-1,2147483647,0,-1,0,2147483647,-1,2147483647,2147483647,0,0,0,-1,0,-1,2147483647,-1,-1,2147483647,-1,0,2147483647,-1,-1,0,2147483647},{2147483647,0,-1,0,0,0,2147483647,0,-1,0,2147483647,-1,0,2147483647,2147483647,-1,0,-1,0,-1,0,0,2147483647,0,-1,2147483647,0,0,2147483647,0,0,-1,2147483647,-1,2147483647,-1,2147483647,-1,2147483647,2147483647,0,-1,2147483647,0,0,-1,2147483647,2147483647,-1,-1,-1,0,0,2147483647,0,0,-1,-1,-1,2147483647,0,2147483647,0,-1,-1,2147483647,2147483647,2147483647,-1,2147483647,0,-1,2147483647,0,0,0,-1,2147483647,2147483647,2147483647,2147483647,2147483647,0,0,-1,0,2147483647,2147483647,-1,-1,2147483647,-1,-1,-1,0,-1,2147483647,0,2147483647,2147483647,2147483647,-1,-1,2147483647,2147483647,2147483647,-1,2147483647,0,0,0,-1,-1,2147483647,0,-1,0,2147483647,-1,0,-1,-1,2147483647,-1,-1,2147483647,0,-1,2147483647,2147483647,-1,0,2147483647,2147483647,-1,0,2147483647,2147483647,0,2147483647,2147483647,-1,-1,-1,2147483647,0,0,2147483647,2147483647,2147483647,2147483647,-1,0,-1,0,-1,0,0,-1,2147483647,2147483647,0,2147483647,-1,2147483647,2147483647,2147483647,0,-1,0,-1,2147483647,2147483647,0,2147483647,0,2147483647,-1,0,-1,2147483647,-1,0,-1,-1,2147483647,0,2147483647,-1,0,2147483647,0,-1,2147483647,-1,-1,-1,0,0,2147483647,2147483647,-1,0,0,2147483647,0,0,0,2147483647,2147483647,0,2147483647,-1,0,0,0,2147483647,2147483647,2147483647,0,-1},{-1,2147483647,0,0,2147483647,2147483647,0,0,-1,0,0,0,-1,0,0,-1,2147483647,0,2147483647,0,-1,-1,0,0,2147483647,2147483647,-1,-1,2147483647,2147483647,0,-1,0,2147483647,2147483647,-1,2147483647,0,0,0,-1,0,2147483647,-1,-1,0,-1,2147483647,-1,2147483647,-1,2147483647,-1,-1,-1,0,-1,0,2147483647,-1,2147483647,2147483647,2147483647,2147483647,-1,0,0,-1,2147483647,-1,2147483647,-1,0,0,2147483647,-1,0,2147483647,-1,0,0,2147483647,2147483647,0,0,-1,2147483647,2147483647,2147483647,0,0,0,0,2147483647,0,2147483647,-1,0,-1,-1,-1,-1,0,2147483647,2147483647,2147483647,0,2147483647,2147483647,-1,-1,2147483647,2147483647,0,-1,-1,2147483647,0,2147483647,0,2147483647,2147483647,-1,-1,2147483647,0,0,-1,-1,-1,2147483647,-1,0,2147483647,-1,-1,2147483647,2147483647,-1,2147483647,0,-1,2147483647,-1,0,2147483647,2147483647,2147483647,0,-1,0,2147483647,2147483647,2147483647,-1,2147483647,-1,2147483647,-1,2147483647,2147483647,-1,0,-1,2147483647,-1,2147483647,0,-1,2147483647,-1,0,-1,-1,-1,0,-1,2147483647,0,0,2147483647,0,-1,0,0,2147483647,2147483647,2147483647,2147483647,0,-1,0,2147483647,0,-1,0,-1,2147483647,2147483647,-1,0,2147483647,0,2147483647,-1,-1,2147483647,0,2147483647,2147483647,2147483647,-1,0,-1,0,2147483647,-1,-1,-1,0,-1},{-1,0,-1,0,2147483647,-1,2147483647,-1,0,-1,-1,0,0,2147483647,0,2147483647,2147483647,0,0,0,2147483647,-1,2147483647,-1,0,2147483647,2147483647,0,-1,0,-1,2147483647,2147483647,2147483647,-1,-1,2147483647,2147483647,-1,2147483647,0,2147483647,2147483647,2147483647,-1,-1,-1,0,-1,2147483647,-1,2147483647,2147483647,-1,-1,2147483647,0,-1,2147483647,2147483647,0,2147483647,2147483647,-1,0,2147483647,0,0,-1,2147483647,2147483647,0,0,0,-1,-1,-1,0,-1,2147483647,-1,0,-1,-1,-1,-1,-1,-1,0,-1,-1,0,-1,0,2147483647,0,0,0,-1,-1,-1,-1,2147483647,0,2147483647,-1,0,-1,-1,0,0,2147483647,2147483647,0,0,-1,2147483647,0,2147483647,2147483647,-1,0,2147483647,2147483647,0,0,0,2147483647,2147483647,2147483647,0,2147483647,-1,2147483647,2147483647,2147483647,-1,0,0,0,2147483647,0,0,-1,2147483647,-1,2147483647,2147483647,2147483647,2147483647,0,2147483647,2147483647,0,-1,0,2147483647,-1,0,-1,-1,0,2147483647,-1,0,0,-1,-1,0,-1,-1,-1,-1,-1,2147483647,0,2147483647,0,-1,-1,2147483647,2147483647,0,-1,0,0,2147483647,-1,0,0,2147483647,2147483647,-1,0,0,-1,-1,0,-1,2147483647,0,2147483647,-1,2147483647,-1,2147483647,0,-1,0,-1,-1,-1,-1,-1,0,-1,-1,2147483647,0,0,2147483647},{0,0,-1,0,0,2147483647,2147483647,-1,-1,2147483647,-1,0,2147483647,-1,0,-1,2147483647,2147483647,-1,-1,0,0,-1,-1,0,0,0,0,2147483647,-1,2147483647,-1,2147483647,0,-1,-1,-1,-1,2147483647,0,2147483647,-1,-1,0,0,-1,-1,2147483647,-1,0,2147483647,2147483647,0,-1,2147483647,2147483647,-1,-1,2147483647,0,-1,0,2147483647,-1,-1,-1,2147483647,2147483647,-1,-1,0,-1,-1,0,0,2147483647,2147483647,-1,-1,0,2147483647,-1,-1,-1,-1,0,0,0,-1,2147483647,0,-1,-1,0,0,-1,-1,0,0,0,0,0,-1,2147483647,-1,2147483647,-1,2147483647,2147483647,0,-1,-1,0,-1,-1,-1,2147483647,2147483647,0,2147483647,2147483647,0,-1,2147483647,-1,0,0,-1,-1,2147483647,-1,0,0,2147483647,0,-1,0,-1,2147483647,0,-1,2147483647,-1,0,2147483647,0,2147483647,-1,0,0,2147483647,2147483647,2147483647,0,-1,2147483647,0,0,0,2147483647,-1,0,0,-1,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,0,-1,0,0,-1,0,2147483647,-1,2147483647,0,-1,-1,2147483647,-1,-1,0,0,0,2147483647,2147483647,2147483647,2147483647,-1,-1,-1,2147483647,-1,2147483647,2147483647,0,2147483647,0,2147483647,0,0,0,-1,0,0,0,-1,0,-1,0,-1,0,0,-1,2147483647,-1,2147483647},{0,-1,0,0,0,-1,2147483647,0,0,-1,0,-1,2147483647,-1,2147483647,-1,0,-1,-1,2147483647,-1,-1,-1,-1,0,-1,0,-1,0,0,-1,0,0,-1,0,-1,0,0,0,0,2147483647,-1,-1,0,-1,-1,2147483647,2147483647,-1,2147483647,-1,2147483647,2147483647,-1,2147483647,-1,0,2147483647,-1,0,-1,2147483647,-1,0,0,-1,-1,0,-1,2147483647,-1,0,2147483647,-1,0,2147483647,0,2147483647,0,2147483647,-1,-1,-1,2147483647,2147483647,0,-1,0,2147483647,0,2147483647,-1,0,0,2147483647,0,2147483647,0,-1,-1,2147483647,2147483647,-1,2147483647,2147483647,-1,0,0,2147483647,2147483647,-1,-1,0,-1,-1,2147483647,2147483647,-1,-1,2147483647,0,-1,0,0,0,0,2147483647,0,0,-1,2147483647,2147483647,2147483647,2147483647,-1,2147483647,-1,0,0,-1,-1,-1,-1,0,0,0,0,-1,0,0,0,-1,2147483647,2147483647,2147483647,-1,-1,0,0,2147483647,0,0,-1,0,0,-1,0,2147483647,2147483647,-1,2147483647,-1,-1,0,-1,0,2147483647,2147483647,-1,2147483647,0,2147483647,0,0,0,0,2147483647,0,-1,2147483647,2147483647,-1,0,-1,2147483647,2147483647,-1,2147483647,0,0,0,0,0,0,0,0,0,-1,0,2147483647,-1,0,2147483647,-1,0,0,2147483647,-1,2147483647,0,-1},{0,0,2147483647,0,0,2147483647,-1,2147483647,2147483647,0,0,2147483647,0,2147483647,2147483647,2147483647,-1,2147483647,0,2147483647,2147483647,0,0,2147483647,-1,0,0,0,-1,0,0,2147483647,2147483647,2147483647,0,-1,0,0,2147483647,2147483647,0,2147483647,2147483647,2147483647,0,0,0,2147483647,2147483647,2147483647,-1,2147483647,0,0,-1,0,-1,-1,2147483647,0,-1,0,2147483647,2147483647,-1,2147483647,0,-1,2147483647,-1,-1,0,0,2147483647,0,2147483647,0,2147483647,0,-1,0,0,-1,-1,0,-1,0,-1,2147483647,2147483647,0,2147483647,0,0,0,-1,0,-1,2147483647,0,-1,-1,0,2147483647,2147483647,0,2147483647,-1,-1,-1,2147483647,2147483647,-1,2147483647,-1,0,0,-1,0,0,0,0,2147483647,0,0,2147483647,-1,-1,2147483647,2147483647,0,2147483647,-1,-1,0,-1,-1,-1,0,2147483647,2147483647,0,-1,0,2147483647,2147483647,-1,2147483647,0,0,-1,0,0,-1,-1,2147483647,-1,-1,-1,-1,2147483647,0,-1,0,2147483647,2147483647,-1,2147483647,2147483647,2147483647,0,0,-1,-1,2147483647,0,-1,-1,0,0,-1,2147483647,2147483647,0,0,-1,-1,2147483647,2147483647,0,0,-1,0,2147483647,2147483647,2147483647,-1,2147483647,-1,-1,0,0,0,0,2147483647,0,0,-1,2147483647,-1,-1,-1,0,-1,2147483647,0,2147483647,-1,-1,-1,0},{-1,-1,0,0,0,-1,2147483647,2147483647,0,2147483647,2147483647,0,0,0,-1,-1,-1,-1,0,2147483647,-1,2147483647,-1,2147483647,0,0,-1,0,-1,-1,2147483647,2147483647,-1,2147483647,0,0,0,2147483647,2147483647,0,2147483647,-1,-1,-1,0,-1,2147483647,0,2147483647,-1,0,2147483647,-1,0,0,0,-1,-1,0,2147483647,2147483647,-1,2147483647,2147483647,2147483647,0,-1,-1,-1,-1,-1,-1,2147483647,0,-1,2147483647,2147483647,2147483647,2147483647,-1,-1,0,2147483647,2147483647,-1,0,2147483647,0,0,0,0,2147483647,-1,2147483647,2147483647,0,2147483647,0,0,-1,-1,0,-1,-1,2147483647,2147483647,2147483647,0,0,2147483647,2147483647,2147483647,-1,2147483647,0,0,0,-1,2147483647,0,-1,-1,2147483647,0,0,-1,2147483647,-1,0,0,0,-1,2147483647,0,-1,-1,-1,0,-1,-1,2147483647,0,0,-1,2147483647,0,0,2147483647,-1,0,0,-1,0,0,0,0,-1,-1,2147483647,2147483647,-1,0,2147483647,0,2147483647,-1,-1,0,2147483647,2147483647,0,2147483647,0,-1,0,2147483647,-1,-1,0,2147483647,0,2147483647,2147483647,2147483647,2147483647,0,-1,2147483647,2147483647,0,-1,-1,-1,-1,2147483647,-1,2147483647,2147483647,-1,0,0,-1,-1,-1,0,0,0,2147483647,2147483647,-1,0,2147483647,0,0,0,2147483647,0,0,2147483647,-1,-1},{0,2147483647,0,0,2147483647,-1,2147483647,0,-1,0,2147483647,-1,-1,-1,-1,2147483647,2147483647,-1,0,0,2147483647,0,0,-1,0,2147483647,2147483647,0,0,0,-1,-1,-1,-1,-1,0,2147483647,0,0,-1,2147483647,2147483647,2147483647,0,0,-1,0,2147483647,0,0,0,2147483647,2147483647,2147483647,0,2147483647,0,-1,0,2147483647,2147483647,0,2147483647,-1,0,0,2147483647,0,-1,-1,0,2147483647,-1,2147483647,0,-1,-1,2147483647,0,-1,0,2147483647,2147483647,2147483647,0,2147483647,-1,0,2147483647,-1,0,0,0,0,0,-1,0,2147483647,0,-1,0,0,0,-1,-1,0,-1,0,-1,0,-1,0,-1,2147483647,-1,0,0,-1,-1,0,-1,0,-1,2147483647,0,-1,2147483647,0,2147483647,2147483647,0,2147483647,-1,-1,-1,-1,-1,-1,-1,0,0,0,-1,-1,-1,2147483647,0,2147483647,-1,0,-1,-1,2147483647,-1,2147483647,0,2147483647,0,-1,0,2147483647,0,-1,2147483647,0,-1,-1,-1,0,-1,2147483647,2147483647,0,0,-1,2147483647,-1,-1,2147483647,-1,2147483647,2147483647,2147483647,0,0,2147483647,2147483647,0,-1,2147483647,2147483647,0,-1,-1,-1,-1,2147483647,2147483647,-1,0,0,2147483647,0,2147483647,2147483647,-1,0,2147483647,0,0,-1,-1,0,0,0,0,2147483647,-1,0,0,-1},{-1,2147483647,0,-1,2147483647,2147483647,2147483647,-1,0,0,-1,0,2147483647,2147483647,2147483647,-1,-1,0,-1,0,0,-1,2147483647,2147483647,0,0,0,2147483647,0,0,-1,0,-1,0,2147483647,2147483647,-1,0,-1,-1,2147483647,0,2147483647,-1,2147483647,0,2147483647,0,-1,2147483647,-1,2147483647,2147483647,-1,-1,0,2147483647,2147483647,2147483647,-1,0,2147483647,-1,2147483647,-1,-1,0,-1,0,0,0,0,-1,-1,2147483647,-1,0,0,-1,-1,-1,-1,2147483647,-1,2147483647,0,0,2147483647,2147483647,2147483647,2147483647,2147483647,0,0,0,0,-1,0,2147483647,2147483647,0,0,0,0,2147483647,2147483647,0,-1,0,-1,0,2147483647,2147483647,-1,2147483647,0,-1,2147483647,-1,0,-1,-1,2147483647,-1,0,-1,2147483647,2147483647,0,-1,-1,-1,-1,-1,-1,2147483647,0,0,-1,0,0,0,2147483647,-1,0,0,0,-1,0,-1,-1,-1,0,2147483647,0,-1,-1,0,-1,2147483647,2147483647,-1,-1,2147483647,2147483647,-1,-1,0,2147483647,2147483647,0,2147483647,0,0,0,2147483647,2147483647,0,0,0,0,0,-1,-1,-1,0,-1,0,0,0,0,2147483647,0,0,2147483647,-1,2147483647,-1,2147483647,-1,0,2147483647,2147483647,-1,0,2147483647,0,2147483647,-1,2147483647,0,0,-1,0,0,-1,-1,-1,0,0,2147483647},{-1,0,2147483647,0,2147483647,2147483647,2147483647,2147483647,0,2147483647,2147483647,0,2147483647,2147483647,-1,2147483647,0,2147483647,-1,2147483647,-1,2147483647,-1,2147483647,-1,2147483647,-1,2147483647,2147483647,2147483647,2147483647,-1,2147483647,-1,2147483647,0,0,0,-1,2147483647,2147483647,0,-1,2147483647,-1,2147483647,2147483647,-1,0,-1,-1,2147483647,-1,0,-1,2147483647,2147483647,2147483647,0,-1,0,-1,0,2147483647,0,2147483647,0,0,0,-1,-1,2147483647,2147483647,-1,2147483647,0,0,2147483647,-1,0,2147483647,-1,2147483647,-1,0,0,2147483647,0,0,-1,0,2147483647,-1,2147483647,2147483647,0,-1,-1,0,2147483647,-1,-1,-1,-1,0,0,2147483647,0,0,-1,2147483647,2147483647,-1,2147483647,2147483647,2147483647,0,0,0,0,2147483647,2147483647,0,-1,0,2147483647,-1,2147483647,-1,-1,2147483647,0,0,-1,-1,-1,2147483647,-1,2147483647,2147483647,0,0,0,0,-1,2147483647,0,-1,0,0,2147483647,0,2147483647,-1,2147483647,-1,0,-1,0,0,-1,-1,2147483647,2147483647,-1,2147483647,0,-1,-1,-1,-1,-1,0,-1,-1,2147483647,2147483647,-1,2147483647,0,2147483647,-1,2147483647,-1,-1,-1,0,0,-1,0,0,0,2147483647,2147483647,2147483647,-1,0,2147483647,2147483647,0,2147483647,0,0,2147483647,0,-1,2147483647,2147483647,-1,0,0,2147483647,-1,2147483647,0,0,0,-1,0,0,0},{-1,2147483647,0,2147483647,0,2147483647,-1,-1,2147483647,-1,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,-1,-1,-1,0,-1,-1,-1,-1,0,2147483647,0,2147483647,2147483647,-1,-1,0,2147483647,-1,0,2147483647,2147483647,-1,-1,-1,2147483647,0,-1,-1,-1,2147483647,-1,2147483647,-1,0,-1,0,0,2147483647,0,2147483647,2147483647,0,-1,2147483647,-1,2147483647,0,0,-1,-1,2147483647,-1,-1,2147483647,-1,-1,2147483647,0,-1,0,0,0,0,-1,-1,2147483647,2147483647,-1,-1,2147483647,2147483647,0,2147483647,-1,2147483647,-1,2147483647,2147483647,0,2147483647,2147483647,2147483647,2147483647,0,-1,0,2147483647,2147483647,2147483647,2147483647,-1,0,2147483647,-1,2147483647,-1,-1,-1,-1,-1,0,-1,-1,0,-1,-1,-1,0,2147483647,2147483647,2147483647,0,-1,2147483647,-1,2147483647,2147483647,2147483647,2147483647,0,0,0,0,-1,0,2147483647,0,2147483647,-1,-1,-1,0,-1,0,-1,-1,-1,-1,2147483647,0,0,2147483647,2147483647,2147483647,0,2147483647,-1,0,0,2147483647,-1,2147483647,-1,2147483647,2147483647,-1,-1,0,2147483647,-1,2147483647,2147483647,2147483647,-1,2147483647,0,-1,2147483647,-1,2147483647,0,-1,0,2147483647,2147483647,0,0,-1,0,-1,0,-1,-1,2147483647,0,-1,2147483647,-1,2147483647,-1,0,-1,2147483647,2147483647,-1,0,0,0,2147483647,-1,0,0,2147483647,2147483647,-1},{0,0,0,0,-1,-1,0,2147483647,0,2147483647,0,0,-1,2147483647,-1,-1,2147483647,2147483647,0,0,0,2147483647,2147483647,-1,0,2147483647,0,0,2147483647,2147483647,2147483647,2147483647,-1,-1,2147483647,2147483647,-1,0,0,-1,-1,2147483647,2147483647,2147483647,-1,-1,2147483647,-1,0,0,2147483647,0,2147483647,2147483647,-1,-1,2147483647,0,0,-1,2147483647,2147483647,-1,2147483647,0,2147483647,2147483647,-1,0,2147483647,2147483647,-1,-1,2147483647,2147483647,0,0,0,2147483647,-1,0,0,2147483647,-1,2147483647,-1,-1,0,0,0,0,2147483647,-1,2147483647,2147483647,2147483647,2147483647,0,0,2147483647,-1,-1,2147483647,0,0,2147483647,2147483647,0,2147483647,2147483647,2147483647,2147483647,-1,-1,0,2147483647,2147483647,-1,-1,0,0,2147483647,0,0,0,0,0,2147483647,-1,2147483647,2147483647,0,0,2147483647,2147483647,-1,2147483647,2147483647,0,2147483647,2147483647,2147483647,0,0,0,0,2147483647,-1,-1,2147483647,0,0,-1,0,2147483647,-1,2147483647,-1,2147483647,-1,0,0,0,0,2147483647,0,-1,-1,-1,0,-1,2147483647,0,2147483647,-1,0,2147483647,-1,0,0,0,-1,-1,-1,2147483647,-1,2147483647,0,2147483647,0,0,2147483647,-1,2147483647,0,2147483647,-1,2147483647,0,0,0,-1,-1,0,0,-1,0,2147483647,2147483647,0,0,0,0,0,-1,2147483647,2147483647,2147483647,-1,2147483647,2147483647},{0,-1,0,-1,2147483647,2147483647,2147483647,0,2147483647,0,2147483647,0,-1,2147483647,-1,-1,-1,-1,0,2147483647,2147483647,-1,2147483647,0,2147483647,-1,-1,0,0,-1,-1,0,2147483647,0,0,0,-1,0,2147483647,-1,2147483647,0,-1,2147483647,0,2147483647,-1,0,0,-1,2147483647,0,2147483647,-1,-1,2147483647,0,0,0,-1,2147483647,0,0,2147483647,2147483647,2147483647,2147483647,0,2147483647,-1,2147483647,2147483647,-1,2147483647,0,2147483647,2147483647,-1,0,2147483647,-1,-1,2147483647,-1,2147483647,0,-1,0,-1,2147483647,0,-1,2147483647,0,0,-1,2147483647,2147483647,2147483647,0,2147483647,0,2147483647,0,-1,0,-1,-1,2147483647,2147483647,0,-1,-1,-1,-1,0,-1,-1,-1,-1,-1,-1,0,-1,0,-1,2147483647,-1,-1,0,-1,-1,2147483647,2147483647,-1,2147483647,-1,2147483647,2147483647,-1,0,2147483647,0,-1,0,0,0,2147483647,-1,0,0,2147483647,0,0,0,0,0,-1,-1,2147483647,0,-1,0,-1,2147483647,2147483647,0,-1,0,0,0,-1,2147483647,-1,0,2147483647,0,-1,0,2147483647,0,2147483647,-1,2147483647,0,-1,0,-1,-1,2147483647,0,0,-1,0,2147483647,-1,0,-1,-1,2147483647,-1,-1,-1,0,-1,0,2147483647,-1,-1,-1,-1,2147483647,2147483647,2147483647,-1,0,-1,-1,0,0,2147483647},{-1,2147483647,2147483647,0,2147483647,-1,0,2147483647,-1,-1,0,-1,2147483647,-1,-1,-1,2147483647,2147483647,0,0,0,0,0,2147483647,2147483647,2147483647,0,2147483647,2147483647,-1,2147483647,2147483647,2147483647,0,0,2147483647,-1,2147483647,2147483647,-1,-1,0,0,2147483647,2147483647,0,0,0,2147483647,2147483647,-1,-1,0,0,2147483647,2147483647,2147483647,-1,0,0,0,2147483647,-1,2147483647,0,0,0,0,0,0,-1,2147483647,0,-1,-1,0,0,2147483647,2147483647,2147483647,-1,-1,2147483647,0,2147483647,2147483647,0,2147483647,0,0,2147483647,-1,0,-1,0,-1,2147483647,-1,0,0,-1,2147483647,2147483647,-1,2147483647,0,0,2147483647,0,-1,0,0,0,0,0,2147483647,0,0,2147483647,2147483647,0,0,0,0,2147483647,-1,-1,-1,-1,0,-1,-1,-1,2147483647,2147483647,-1,0,2147483647,0,2147483647,0,-1,2147483647,-1,0,0,0,-1,2147483647,-1,-1,0,0,0,2147483647,2147483647,0,0,0,2147483647,-1,2147483647,-1,-1,-1,0,0,2147483647,-1,2147483647,-1,2147483647,-1,2147483647,-1,-1,2147483647,2147483647,0,-1,0,0,0,2147483647,2147483647,0,-1,0,0,-1,-1,2147483647,0,2147483647,0,0,0,-1,-1,2147483647,2147483647,-1,-1,2147483647,0,-1,2147483647,2147483647,2147483647,-1,2147483647,0,2147483647,0,0,2147483647,2147483647,0,0,0,2147483647},{2147483647,0,-1,2147483647,2147483647,2147483647,0,0,-1,2147483647,0,2147483647,0,2147483647,2147483647,0,-1,-1,-1,0,2147483647,2147483647,-1,0,-1,0,2147483647,0,2147483647,-1,2147483647,2147483647,-1,0,-1,2147483647,2147483647,0,2147483647,2147483647,2147483647,-1,-1,-1,0,0,-1,0,-1,-1,2147483647,2147483647,2147483647,0,0,-1,-1,-1,-1,0,-1,2147483647,0,0,2147483647,0,2147483647,2147483647,-1,2147483647,2147483647,2147483647,2147483647,-1,2147483647,0,0,2147483647,0,0,0,2147483647,2147483647,0,-1,2147483647,2147483647,0,-1,-1,2147483647,0,2147483647,2147483647,2147483647,-1,-1,0,2147483647,0,0,0,-1,2147483647,-1,0,0,2147483647,-1,-1,0,2147483647,0,-1,2147483647,0,-1,2147483647,0,2147483647,2147483647,-1,-1,2147483647,-1,0,0,2147483647,2147483647,-1,-1,-1,-1,-1,-1,0,2147483647,-1,-1,0,2147483647,-1,-1,0,-1,-1,2147483647,2147483647,0,-1,2147483647,-1,-1,2147483647,-1,0,-1,-1,2147483647,0,2147483647,-1,2147483647,-1,-1,2147483647,-1,2147483647,0,2147483647,2147483647,-1,0,2147483647,-1,-1,2147483647,0,0,0,-1,2147483647,2147483647,-1,-1,2147483647,-1,2147483647,0,2147483647,2147483647,-1,-1,-1,2147483647,2147483647,0,-1,2147483647,0,-1,-1,-1,2147483647,0,-1,2147483647,-1,2147483647,-1,0,0,2147483647,0,2147483647,2147483647,0,2147483647,-1,-1,0},{0,-1,0,-1,2147483647,-1,-1,0,-1,2147483647,-1,2147483647,2147483647,-1,2147483647,0,0,2147483647,2147483647,-1,0,2147483647,0,-1,0,2147483647,0,0,2147483647,0,0,0,0,-1,2147483647,-1,-1,0,-1,-1,2147483647,-1,2147483647,0,2147483647,-1,0,0,0,-1,0,-1,-1,2147483647,2147483647,2147483647,0,2147483647,2147483647,-1,2147483647,2147483647,-1,2147483647,2147483647,2147483647,2147483647,2147483647,-1,2147483647,-1,-1,0,2147483647,2147483647,2147483647,2147483647,-1,2147483647,0,0,-1,2147483647,2147483647,0,2147483647,0,-1,2147483647,2147483647,2147483647,2147483647,0,0,0,0,2147483647,2147483647,2147483647,-1,-1,-1,0,-1,-1,-1,2147483647,0,2147483647,0,2147483647,-1,2147483647,-1,-1,-1,2147483647,0,-1,2147483647,2147483647,0,-1,-1,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,0,0,2147483647,2147483647,2147483647,-1,-1,-1,2147483647,2147483647,2147483647,2147483647,2147483647,0,2147483647,0,-1,-1,2147483647,-1,0,0,2147483647,0,0,0,-1,-1,-1,2147483647,2147483647,0,-1,-1,0,2147483647,-1,0,-1,-1,2147483647,-1,0,2147483647,-1,2147483647,-1,0,-1,0,-1,-1,-1,2147483647,2147483647,0,0,0,2147483647,2147483647,2147483647,-1,2147483647,0,0,0,-1,2147483647,0,0,-1,2147483647,-1,0,-1,0,2147483647,0,2147483647,-1,2147483647,-1,2147483647,2147483647,2147483647,-1,2147483647,0,0,2147483647,2147483647},{2147483647,0,0,2147483647,0,2147483647,-1,2147483647,2147483647,2147483647,0,-1,0,-1,2147483647,-1,2147483647,-1,-1,0,0,0,2147483647,0,0,-1,-1,2147483647,-1,2147483647,2147483647,0,-1,0,-1,0,2147483647,2147483647,2147483647,-1,0,-1,-1,0,2147483647,-1,2147483647,2147483647,-1,2147483647,2147483647,0,-1,2147483647,-1,2147483647,0,-1,-1,2147483647,-1,0,2147483647,0,-1,2147483647,2147483647,2147483647,-1,2147483647,0,0,2147483647,-1,0,-1,-1,2147483647,-1,2147483647,2147483647,-1,0,0,-1,-1,2147483647,2147483647,2147483647,-1,0,0,-1,2147483647,0,0,2147483647,0,2147483647,-1,0,0,2147483647,-1,-1,0,-1,-1,-1,0,0,2147483647,-1,0,0,0,2147483647,0,2147483647,2147483647,0,2147483647,2147483647,0,-1,2147483647,0,-1,2147483647,0,-1,0,2147483647,2147483647,0,-1,0,-1,-1,0,0,0,2147483647,2147483647,2147483647,2147483647,0,-1,0,-1,-1,2147483647,0,2147483647,-1,-1,-1,2147483647,0,0,2147483647,2147483647,2147483647,0,2147483647,0,0,0,0,0,-1,0,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,-1,-1,0,0,-1,2147483647,-1,0,-1,0,0,0,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,-1,2147483647,2147483647,0,2147483647,-1,-1,0,-1,-1,-1,-1,-1,2147483647,0,2147483647,-1,-1,2147483647,0,0,2147483647,-1,-1},{0,2147483647,0,2147483647,2147483647,-1,-1,0,-1,-1,-1,0,2147483647,2147483647,-1,2147483647,-1,0,0,-1,-1,2147483647,0,2147483647,-1,2147483647,0,-1,-1,-1,2147483647,2147483647,0,0,2147483647,0,0,2147483647,0,2147483647,2147483647,2147483647,0,0,2147483647,0,-1,2147483647,-1,2147483647,-1,-1,2147483647,0,2147483647,2147483647,-1,-1,2147483647,-1,2147483647,0,-1,-1,-1,0,2147483647,0,2147483647,2147483647,2147483647,-1,2147483647,2147483647,-1,0,-1,0,0,2147483647,-1,-1,2147483647,0,-1,-1,-1,-1,2147483647,-1,0,2147483647,-1,2147483647,0,0,2147483647,-1,-1,0,-1,2147483647,2147483647,0,-1,0,2147483647,2147483647,2147483647,-1,-1,-1,2147483647,0,0,0,-1,-1,0,-1,0,2147483647,2147483647,2147483647,2147483647,2147483647,-1,-1,0,2147483647,2147483647,0,0,0,-1,0,0,0,0,-1,2147483647,-1,-1,-1,2147483647,0,2147483647,2147483647,0,2147483647,2147483647,2147483647,2147483647,0,2147483647,0,-1,0,0,2147483647,-1,0,0,2147483647,0,0,0,-1,-1,-1,0,0,2147483647,2147483647,0,-1,0,2147483647,-1,0,2147483647,0,-1,0,0,0,2147483647,-1,-1,0,0,0,2147483647,-1,0,-1,2147483647,2147483647,0,2147483647,2147483647,2147483647,-1,-1,-1,0,0,-1,2147483647,0,-1,-1,-1,2147483647,-1,0,2147483647,2147483647,-1,-1,0},{2147483647,0,2147483647,2147483647,0,-1,-1,-1,0,2147483647,2147483647,0,0,0,2147483647,0,-1,-1,2147483647,0,0,2147483647,-1,-1,0,0,0,-1,0,-1,-1,0,-1,-1,-1,0,0,-1,-1,-1,0,-1,-1,2147483647,-1,2147483647,0,0,0,-1,-1,0,0,2147483647,2147483647,-1,0,-1,0,0,2147483647,2147483647,2147483647,-1,0,-1,0,0,0,0,-1,0,-1,0,-1,0,-1,2147483647,0,2147483647,2147483647,-1,-1,0,-1,2147483647,-1,0,2147483647,0,-1,0,-1,-1,2147483647,-1,-1,-1,0,0,-1,2147483647,0,-1,-1,2147483647,-1,0,0,0,0,-1,-1,2147483647,0,-1,0,2147483647,2147483647,0,-1,-1,-1,2147483647,-1,2147483647,2147483647,2147483647,-1,2147483647,2147483647,2147483647,2147483647,-1,0,2147483647,0,0,0,2147483647,0,0,-1,2147483647,2147483647,0,2147483647,2147483647,-1,-1,2147483647,2147483647,2147483647,0,2147483647,-1,-1,2147483647,0,2147483647,-1,2147483647,-1,-1,0,2147483647,0,2147483647,2147483647,2147483647,-1,-1,0,-1,0,0,0,2147483647,-1,-1,0,0,2147483647,0,2147483647,0,2147483647,-1,-1,0,0,0,0,-1,0,2147483647,0,-1,-1,-1,2147483647,0,-1,2147483647,-1,-1,2147483647,2147483647,0,2147483647,-1,2147483647,-1,0,-1,-1,0,-1,-1,0,2147483647},{0,0,-1,0,-1,0,-1,-1,-1,-1,-1,0,0,0,-1,-1,2147483647,2147483647,2147483647,0,0,2147483647,2147483647,-1,0,2147483647,2147483647,2147483647,2147483647,-1,0,0,-1,-1,0,-1,0,0,2147483647,-1,2147483647,2147483647,-1,0,0,-1,2147483647,2147483647,2147483647,0,-1,0,2147483647,2147483647,-1,2147483647,-1,0,2147483647,-1,-1,-1,0,2147483647,-1,0,-1,-1,-1,2147483647,-1,-1,-1,2147483647,2147483647,2147483647,2147483647,0,-1,0,-1,2147483647,2147483647,0,2147483647,0,0,-1,0,2147483647,2147483647,2147483647,2147483647,-1,2147483647,0,-1,0,0,2147483647,0,-1,2147483647,-1,2147483647,2147483647,2147483647,0,2147483647,2147483647,-1,2147483647,-1,2147483647,-1,0,-1,0,-1,0,0,0,0,-1,0,2147483647,2147483647,2147483647,-1,2147483647,0,-1,0,-1,2147483647,2147483647,-1,0,0,0,0,-1,0,2147483647,0,0,-1,-1,-1,2147483647,-1,-1,2147483647,2147483647,-1,0,2147483647,2147483647,-1,2147483647,2147483647,2147483647,0,2147483647,-1,2147483647,-1,2147483647,-1,-1,0,0,0,2147483647,2147483647,0,-1,-1,0,2147483647,-1,2147483647,-1,0,2147483647,-1,2147483647,2147483647,2147483647,0,2147483647,-1,2147483647,0,0,2147483647,2147483647,0,2147483647,-1,-1,2147483647,-1,2147483647,2147483647,-1,-1,0,-1,0,2147483647,0,0,-1,0,0,-1,-1,2147483647,2147483647,0},{2147483647,2147483647,2147483647,-1,2147483647,0,0,-1,0,-1,-1,-1,-1,0,0,2147483647,0,0,-1,-1,0,-1,2147483647,2147483647,-1,-1,2147483647,-1,-1,2147483647,0,-1,2147483647,0,-1,0,0,2147483647,-1,-1,-1,-1,2147483647,2147483647,-1,0,2147483647,-1,-1,0,-1,2147483647,2147483647,-1,0,-1,2147483647,2147483647,-1,2147483647,-1,-1,2147483647,-1,-1,2147483647,2147483647,2147483647,2147483647,0,-1,-1,2147483647,2147483647,2147483647,-1,-1,-1,2147483647,2147483647,-1,2147483647,2147483647,0,2147483647,-1,2147483647,2147483647,0,0,0,0,2147483647,0,2147483647,0,-1,-1,0,0,2147483647,0,-1,-1,0,2147483647,0,0,-1,0,-1,0,0,-1,-1,2147483647,0,-1,2147483647,2147483647,0,2147483647,-1,-1,2147483647,-1,0,2147483647,2147483647,2147483647,0,-1,-1,-1,2147483647,-1,0,-1,2147483647,-1,2147483647,-1,0,0,-1,0,2147483647,-1,2147483647,2147483647,2147483647,-1,0,2147483647,-1,0,-1,2147483647,2147483647,-1,-1,2147483647,0,-1,-1,2147483647,0,0,2147483647,2147483647,0,2147483647,0,-1,0,2147483647,2147483647,2147483647,2147483647,2147483647,0,2147483647,0,2147483647,2147483647,2147483647,-1,-1,-1,-1,2147483647,-1,0,-1,-1,-1,2147483647,-1,2147483647,2147483647,2147483647,0,-1,2147483647,-1,-1,-1,0,2147483647,2147483647,-1,0,-1,2147483647,-1,2147483647,-1,2147483647,0,-1,2147483647},{0,-1,-1,-1,-1,0,2147483647,0,0,2147483647,0,0,-1,-1,2147483647,2147483647,2147483647,-1,-1,2147483647,2147483647,0,0,0,2147483647,2147483647,-1,0,2147483647,0,-1,-1,0,0,2147483647,-1,-1,2147483647,-1,0,0,0,-1,-1,-1,2147483647,-1,2147483647,0,2147483647,-1,-1,0,2147483647,-1,-1,2147483647,0,0,0,0,-1,0,2147483647,2147483647,-1,-1,0,0,2147483647,-1,0,0,-1,-1,-1,2147483647,0,2147483647,2147483647,0,0,-1,-1,2147483647,0,-1,-1,-1,0,-1,2147483647,-1,2147483647,2147483647,-1,2147483647,-1,0,0,2147483647,2147483647,0,0,2147483647,0,-1,2147483647,-1,-1,0,-1,-1,2147483647,-1,2147483647,0,2147483647,2147483647,-1,0,0,2147483647,0,0,0,0,2147483647,0,2147483647,-1,-1,2147483647,0,-1,0,0,2147483647,-1,-1,2147483647,0,0,0,0,2147483647,0,2147483647,-1,-1,2147483647,0,2147483647,-1,0,2147483647,-1,-1,-1,2147483647,-1,-1,2147483647,0,-1,0,0,0,2147483647,0,-1,0,-1,-1,-1,2147483647,2147483647,-1,2147483647,2147483647,-1,2147483647,0,0,0,0,0,2147483647,-1,0,2147483647,2147483647,0,0,0,0,0,2147483647,0,-1,0,-1,0,-1,-1,2147483647,0,0,-1,0,0,0,2147483647,2147483647,2147483647,0,0,-1,-1,2147483647,-1},{0,0,-1,0,2147483647,0,-1,-1,2147483647,0,-1,0,2147483647,2147483647,-1,2147483647,2147483647,-1,0,-1,2147483647,-1,0,2147483647,0,0,-1,-1,0,0,-1,-1,2147483647,0,-1,-1,2147483647,0,-1,0,0,0,-1,0,-1,0,-1,0,-1,-1,0,-1,2147483647,2147483647,-1,-1,2147483647,-1,2147483647,0,0,0,-1,0,0,2147483647,2147483647,-1,2147483647,2147483647,2147483647,0,2147483647,0,2147483647,2147483647,2147483647,2147483647,-1,-1,0,2147483647,0,2147483647,0,2147483647,0,0,0,-1,0,0,0,-1,-1,0,-1,2147483647,0,-1,0,2147483647,0,0,-1,-1,-1,2147483647,-1,2147483647,0,0,-1,-1,-1,2147483647,2147483647,0,2147483647,-1,0,0,-1,-1,-1,2147483647,-1,2147483647,-1,0,0,0,0,0,-1,2147483647,0,2147483647,-1,-1,0,-1,-1,2147483647,0,-1,0,2147483647,-1,2147483647,2147483647,-1,2147483647,2147483647,2147483647,2147483647,-1,2147483647,2147483647,0,2147483647,2147483647,0,0,-1,0,-1,2147483647,-1,-1,2147483647,0,2147483647,2147483647,0,0,0,-1,0,2147483647,0,0,0,0,0,0,2147483647,0,-1,2147483647,2147483647,0,-1,2147483647,0,0,2147483647,0,0,-1,-1,-1,0,0,2147483647,-1,-1,0,2147483647,-1,0,2147483647,0,0,2147483647,0,0,-1,2147483647,-1,2147483647},{2147483647,2147483647,0,2147483647,-1,0,-1,-1,0,0,2147483647,2147483647,2147483647,-1,-1,-1,2147483647,-1,2147483647,2147483647,0,2147483647,0,-1,0,0,0,-1,-1,2147483647,-1,2147483647,-1,2147483647,-1,2147483647,-1,-1,2147483647,-1,-1,-1,2147483647,-1,0,0,2147483647,0,0,-1,2147483647,-1,0,0,0,2147483647,0,2147483647,0,2147483647,-1,2147483647,2147483647,0,-1,2147483647,2147483647,2147483647,2147483647,2147483647,0,-1,2147483647,0,-1,2147483647,2147483647,2147483647,2147483647,0,2147483647,-1,0,2147483647,-1,2147483647,0,2147483647,-1,0,0,0,2147483647,0,2147483647,-1,0,2147483647,0,-1,2147483647,2147483647,2147483647,0,2147483647,2147483647,0,-1,-1,-1,0,0,-1,0,2147483647,2147483647,2147483647,2147483647,0,-1,-1,-1,0,0,2147483647,0,0,-1,-1,0,0,0,-1,2147483647,-1,-1,-1,-1,-1,-1,2147483647,-1,0,2147483647,2147483647,-1,2147483647,0,-1,2147483647,0,0,0,0,2147483647,-1,0,-1,-1,0,0,2147483647,2147483647,0,-1,0,-1,0,-1,0,0,-1,0,0,2147483647,0,-1,0,0,0,-1,2147483647,-1,-1,0,2147483647,0,2147483647,-1,2147483647,-1,-1,-1,2147483647,2147483647,-1,0,0,2147483647,-1,-1,0,0,2147483647,-1,0,0,0,0,-1,2147483647,0,2147483647,0,-1,2147483647,2147483647,-1,2147483647,-1,2147483647},{-1,0,2147483647,-1,-1,2147483647,-1,-1,-1,0,0,0,0,0,-1,0,-1,0,0,0,-1,-1,-1,2147483647,0,2147483647,-1,-1,2147483647,2147483647,-1,-1,0,2147483647,2147483647,-1,-1,0,2147483647,0,-1,2147483647,-1,-1,-1,-1,-1,-1,2147483647,-1,2147483647,2147483647,0,2147483647,2147483647,-1,-1,-1,2147483647,2147483647,0,-1,0,2147483647,-1,2147483647,0,-1,-1,-1,-1,2147483647,0,2147483647,-1,2147483647,0,0,0,2147483647,-1,-1,0,2147483647,2147483647,2147483647,2147483647,-1,0,2147483647,2147483647,0,2147483647,-1,2147483647,-1,0,2147483647,2147483647,-1,2147483647,-1,2147483647,-1,2147483647,0,2147483647,-1,0,0,-1,2147483647,2147483647,0,-1,-1,0,2147483647,2147483647,2147483647,-1,-1,2147483647,2147483647,2147483647,2147483647,-1,-1,2147483647,0,0,2147483647,0,-1,2147483647,-1,0,0,0,-1,-1,-1,2147483647,0,-1,0,2147483647,-1,-1,2147483647,2147483647,-1,2147483647,-1,-1,0,-1,2147483647,2147483647,0,-1,2147483647,-1,2147483647,2147483647,2147483647,-1,2147483647,2147483647,-1,0,0,0,-1,-1,0,0,0,0,-1,2147483647,0,2147483647,-1,0,-1,-1,-1,2147483647,0,-1,2147483647,-1,2147483647,0,2147483647,2147483647,-1,2147483647,-1,0,2147483647,2147483647,2147483647,-1,2147483647,2147483647,0,2147483647,2147483647,0,0,2147483647,-1,2147483647,2147483647,2147483647,2147483647,2147483647,-1,0},{2147483647,2147483647,-1,0,-1,-1,2147483647,0,-1,0,-1,-1,-1,0,2147483647,0,2147483647,0,-1,2147483647,2147483647,2147483647,0,0,2147483647,0,0,-1,-1,-1,2147483647,-1,2147483647,-1,2147483647,-1,0,0,2147483647,-1,2147483647,2147483647,0,-1,0,-1,-1,-1,2147483647,-1,2147483647,0,2147483647,2147483647,0,2147483647,2147483647,-1,0,2147483647,0,-1,-1,2147483647,0,2147483647,-1,-1,-1,0,0,0,-1,0,2147483647,0,-1,2147483647,-1,2147483647,0,0,0,-1,0,-1,-1,-1,0,-1,-1,-1,2147483647,-1,2147483647,0,-1,0,2147483647,2147483647,0,2147483647,2147483647,0,2147483647,0,0,0,2147483647,2147483647,-1,0,-1,-1,2147483647,0,-1,0,0,-1,0,2147483647,-1,-1,2147483647,2147483647,2147483647,2147483647,0,-1,0,-1,-1,0,2147483647,0,2147483647,0,2147483647,0,2147483647,2147483647,0,-1,0,0,2147483647,-1,2147483647,-1,2147483647,2147483647,-1,2147483647,-1,0,2147483647,0,-1,-1,2147483647,-1,2147483647,0,-1,2147483647,0,2147483647,2147483647,2147483647,0,-1,2147483647,2147483647,2147483647,2147483647,-1,0,0,2147483647,-1,0,-1,0,-1,0,-1,-1,-1,-1,-1,-1,-1,2147483647,0,-1,0,-1,0,2147483647,2147483647,-1,-1,-1,-1,-1,0,2147483647,0,0,0,0,2147483647,-1,-1,-1,-1,0,0,2147483647,0},{2147483647,0,-1,-1,2147483647,-1,0,0,-1,-1,-1,2147483647,2147483647,2147483647,2147483647,0,-1,0,2147483647,-1,2147483647,0,-1,2147483647,-1,-1,-1,0,-1,0,2147483647,2147483647,-1,2147483647,2147483647,2147483647,0,-1,-1,-1,0,0,2147483647,0,2147483647,0,-1,2147483647,2147483647,0,0,-1,-1,2147483647,2147483647,0,-1,2147483647,-1,2147483647,-1,-1,-1,2147483647,-1,2147483647,-1,-1,2147483647,2147483647,0,-1,-1,2147483647,0,2147483647,-1,-1,2147483647,0,-1,0,-1,0,-1,-1,2147483647,2147483647,-1,-1,-1,0,2147483647,-1,0,2147483647,0,2147483647,2147483647,-1,-1,-1,-1,0,-1,0,-1,2147483647,-1,0,-1,2147483647,-1,-1,2147483647,0,0,0,2147483647,0,-1,-1,2147483647,0,2147483647,0,2147483647,0,2147483647,-1,-1,0,2147483647,2147483647,2147483647,-1,-1,-1,0,-1,0,-1,0,2147483647,0,0,0,2147483647,0,0,2147483647,-1,0,-1,0,0,0,0,-1,-1,0,0,-1,-1,-1,-1,2147483647,-1,0,-1,2147483647,-1,2147483647,0,-1,-1,-1,2147483647,2147483647,-1,0,0,0,-1,-1,2147483647,-1,-1,2147483647,0,-1,0,0,-1,-1,2147483647,2147483647,0,2147483647,-1,0,0,-1,2147483647,0,2147483647,-1,-1,0,-1,2147483647,0,0,-1,0,0,2147483647,0,2147483647,2147483647,-1},{0,2147483647,2147483647,2147483647,2147483647,0,0,-1,2147483647,2147483647,-1,2147483647,2147483647,0,2147483647,0,0,-1,2147483647,-1,2147483647,0,2147483647,-1,2147483647,0,-1,0,0,-1,0,2147483647,2147483647,0,-1,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,-1,0,2147483647,2147483647,-1,0,-1,0,2147483647,0,-1,0,-1,0,-1,2147483647,0,-1,-1,0,2147483647,2147483647,0,2147483647,-1,-1,0,-1,-1,2147483647,0,0,0,0,-1,2147483647,2147483647,0,2147483647,0,-1,0,0,-1,2147483647,-1,2147483647,0,0,0,0,2147483647,2147483647,2147483647,-1,0,2147483647,0,0,2147483647,2147483647,0,-1,0,-1,0,2147483647,-1,-1,-1,-1,-1,2147483647,2147483647,0,-1,0,2147483647,2147483647,-1,2147483647,0,-1,2147483647,-1,-1,2147483647,2147483647,2147483647,2147483647,2147483647,-1,0,-1,2147483647,-1,-1,2147483647,2147483647,0,2147483647,2147483647,0,-1,2147483647,0,2147483647,0,-1,0,-1,0,-1,2147483647,0,0,0,-1,2147483647,2147483647,-1,-1,0,-1,0,2147483647,-1,2147483647,2147483647,2147483647,0,2147483647,-1,2147483647,2147483647,2147483647,2147483647,-1,-1,-1,0,-1,-1,2147483647,0,-1,2147483647,-1,0,2147483647,0,-1,2147483647,0,-1,0,0,0,2147483647,2147483647,2147483647,2147483647,0,0,2147483647,0,-1,0,-1,0,2147483647,2147483647,-1,2147483647,-1,2147483647,0,-1,2147483647,2147483647},{-1,0,0,2147483647,-1,-1,2147483647,0,-1,2147483647,0,2147483647,2147483647,-1,0,-1,0,0,2147483647,-1,-1,2147483647,2147483647,2147483647,-1,-1,-1,0,2147483647,0,2147483647,2147483647,-1,0,0,-1,0,0,2147483647,-1,0,0,-1,2147483647,0,2147483647,0,2147483647,0,0,0,0,2147483647,2147483647,0,-1,0,2147483647,-1,-1,0,-1,2147483647,0,0,2147483647,2147483647,0,-1,2147483647,-1,2147483647,0,0,0,2147483647,-1,-1,-1,2147483647,0,-1,2147483647,-1,2147483647,2147483647,-1,2147483647,-1,0,0,-1,-1,-1,-1,2147483647,0,0,2147483647,0,-1,2147483647,0,0,-1,0,2147483647,0,0,0,0,0,0,-1,-1,0,0,-1,2147483647,2147483647,0,-1,0,0,-1,2147483647,-1,2147483647,0,-1,-1,2147483647,2147483647,2147483647,0,2147483647,-1,-1,2147483647,2147483647,-1,2147483647,-1,-1,-1,2147483647,0,2147483647,-1,2147483647,0,0,0,-1,0,-1,-1,-1,0,-1,0,2147483647,-1,-1,0,2147483647,-1,0,0,0,-1,-1,-1,-1,-1,2147483647,2147483647,-1,2147483647,-1,0,2147483647,-1,-1,2147483647,0,-1,2147483647,2147483647,-1,-1,-1,2147483647,-1,-1,-1,0,0,-1,2147483647,-1,0,2147483647,2147483647,-1,2147483647,2147483647,0,-1,0,2147483647,-1,-1,2147483647,2147483647,-1,0,2147483647,-1,-1,0},{2147483647,2147483647,0,0,0,0,0,-1,2147483647,2147483647,-1,2147483647,2147483647,-1,0,-1,2147483647,0,0,2147483647,-1,2147483647,0,0,2147483647,2147483647,-1,2147483647,0,-1,2147483647,2147483647,-1,-1,2147483647,2147483647,0,-1,2147483647,0,0,2147483647,-1,-1,0,2147483647,-1,0,2147483647,-1,2147483647,0,-1,2147483647,2147483647,-1,2147483647,-1,-1,2147483647,2147483647,-1,0,2147483647,-1,0,0,0,-1,2147483647,0,2147483647,2147483647,2147483647,0,0,0,2147483647,2147483647,-1,-1,-1,2147483647,-1,2147483647,0,2147483647,2147483647,-1,-1,-1,2147483647,0,2147483647,-1,0,0,0,2147483647,2147483647,2147483647,2147483647,-1,-1,2147483647,-1,2147483647,2147483647,2147483647,0,-1,0,2147483647,0,-1,-1,0,0,0,0,-1,-1,0,2147483647,0,0,0,2147483647,0,0,0,-1,0,-1,2147483647,-1,-1,2147483647,2147483647,-1,-1,2147483647,-1,-1,0,0,0,-1,0,-1,2147483647,-1,0,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,-1,0,-1,2147483647,-1,2147483647,2147483647,0,0,2147483647,0,2147483647,-1,0,2147483647,2147483647,0,-1,0,2147483647,0,2147483647,0,0,-1,-1,-1,-1,2147483647,2147483647,-1,-1,2147483647,0,-1,0,0,0,0,-1,0,0,-1,0,0,0,-1,0,2147483647,0,2147483647,-1,2147483647,0,0,-1,-1,0,-1,0,-1,-1},{2147483647,-1,0,2147483647,-1,-1,-1,-1,2147483647,2147483647,-1,-1,2147483647,-1,2147483647,-1,0,-1,-1,-1,2147483647,-1,2147483647,2147483647,0,0,0,2147483647,2147483647,-1,0,0,2147483647,-1,-1,0,2147483647,2147483647,-1,-1,-1,2147483647,-1,0,-1,-1,-1,0,2147483647,2147483647,-1,-1,-1,-1,0,0,2147483647,2147483647,2147483647,0,2147483647,0,2147483647,-1,-1,-1,2147483647,-1,0,2147483647,0,-1,-1,0,-1,2147483647,-1,0,0,-1,2147483647,0,2147483647,0,-1,0,2147483647,0,-1,0,2147483647,0,2147483647,0,-1,2147483647,0,0,0,0,0,2147483647,-1,0,2147483647,0,0,0,0,0,-1,-1,0,0,-1,0,2147483647,0,0,0,-1,0,2147483647,-1,0,-1,0,-1,-1,0,-1,0,2147483647,-1,-1,2147483647,-1,0,0,0,2147483647,0,0,-1,2147483647,2147483647,-1,-1,2147483647,2147483647,2147483647,0,0,2147483647,-1,0,0,0,-1,0,2147483647,-1,0,2147483647,2147483647,-1,2147483647,2147483647,-1,0,2147483647,-1,-1,2147483647,-1,-1,0,2147483647,2147483647,-1,2147483647,2147483647,-1,0,-1,-1,-1,-1,-1,0,0,0,0,2147483647,0,0,2147483647,-1,-1,2147483647,0,0,0,-1,0,-1,0,0,-1,2147483647,-1,2147483647,2147483647,-1,0,-1,0,-1,0,2147483647,0},{2147483647,-1,2147483647,0,-1,0,2147483647,2147483647,0,-1,-1,2147483647,0,-1,-1,2147483647,-1,0,-1,2147483647,0,0,-1,-1,2147483647,0,0,2147483647,-1,-1,-1,2147483647,-1,2147483647,0,-1,-1,-1,2147483647,2147483647,-1,-1,2147483647,2147483647,-1,2147483647,0,2147483647,-1,-1,2147483647,2147483647,2147483647,0,0,0,-1,-1,0,2147483647,0,0,-1,-1,2147483647,-1,-1,-1,-1,0,0,2147483647,-1,-1,-1,-1,2147483647,2147483647,0,0,2147483647,-1,2147483647,0,-1,2147483647,0,-1,2147483647,2147483647,-1,2147483647,-1,-1,2147483647,-1,0,2147483647,-1,2147483647,0,2147483647,0,0,2147483647,-1,-1,0,-1,0,-1,-1,2147483647,2147483647,-1,-1,-1,2147483647,2147483647,0,-1,-1,0,2147483647,2147483647,-1,-1,2147483647,2147483647,-1,-1,0,0,2147483647,-1,0,-1,0,-1,-1,0,2147483647,0,0,2147483647,2147483647,2147483647,0,0,2147483647,-1,0,2147483647,0,2147483647,2147483647,0,0,2147483647,0,-1,2147483647,0,2147483647,2147483647,0,0,0,-1,0,2147483647,-1,2147483647,0,0,-1,0,-1,2147483647,2147483647,-1,-1,2147483647,2147483647,0,2147483647,-1,-1,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,0,-1,0,2147483647,0,-1,-1,-1,2147483647,-1,-1,-1,0,2147483647,2147483647,-1,2147483647,-1,2147483647,0,0,-1,0,0,0,2147483647,2147483647},{0,2147483647,2147483647,0,2147483647,-1,2147483647,2147483647,2147483647,0,2147483647,2147483647,0,-1,2147483647,2147483647,-1,2147483647,2147483647,0,0,0,-1,0,0,0,-1,-1,0,-1,2147483647,2147483647,0,0,2147483647,2147483647,0,2147483647,-1,-1,0,0,0,2147483647,-1,0,-1,0,-1,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,0,-1,0,-1,2147483647,0,0,-1,0,0,0,0,2147483647,2147483647,-1,-1,-1,0,-1,0,-1,-1,2147483647,-1,0,0,-1,2147483647,-1,-1,-1,-1,-1,2147483647,-1,2147483647,-1,0,-1,2147483647,2147483647,-1,2147483647,-1,-1,2147483647,-1,2147483647,-1,-1,2147483647,0,2147483647,-1,0,-1,0,0,-1,-1,-1,0,0,-1,2147483647,0,-1,-1,0,-1,-1,0,0,0,2147483647,0,2147483647,-1,2147483647,-1,2147483647,0,-1,-1,0,0,-1,-1,0,0,0,2147483647,-1,2147483647,0,0,-1,2147483647,0,-1,-1,-1,2147483647,0,2147483647,2147483647,2147483647,2147483647,-1,0,0,2147483647,0,2147483647,2147483647,-1,2147483647,2147483647,2147483647,-1,0,2147483647,0,2147483647,2147483647,-1,2147483647,-1,-1,-1,-1,0,2147483647,-1,2147483647,0,0,-1,-1,2147483647,0,-1,-1,2147483647,2147483647,0,0,2147483647,0,2147483647,-1,-1,-1,2147483647,0,0,2147483647,2147483647,0,2147483647,2147483647,2147483647,-1,2147483647,2147483647,-1},{-1,0,-1,-1,-1,2147483647,0,-1,-1,0,0,0,2147483647,2147483647,0,0,0,-1,2147483647,0,2147483647,2147483647,-1,2147483647,0,-1,2147483647,0,2147483647,2147483647,0,0,2147483647,0,-1,0,2147483647,-1,-1,-1,0,0,2147483647,2147483647,0,0,2147483647,2147483647,-1,0,-1,0,-1,2147483647,-1,-1,2147483647,0,-1,2147483647,-1,2147483647,2147483647,-1,0,2147483647,0,-1,2147483647,-1,2147483647,2147483647,2147483647,2147483647,2147483647,-1,-1,2147483647,2147483647,-1,2147483647,-1,2147483647,0,0,2147483647,0,0,-1,2147483647,2147483647,0,-1,2147483647,0,2147483647,-1,-1,0,0,-1,2147483647,2147483647,0,2147483647,-1,2147483647,0,2147483647,2147483647,2147483647,2147483647,2147483647,0,2147483647,-1,-1,2147483647,0,2147483647,2147483647,0,0,-1,-1,2147483647,2147483647,2147483647,2147483647,-1,0,0,-1,0,-1,-1,0,0,-1,0,2147483647,2147483647,2147483647,2147483647,-1,-1,2147483647,-1,0,2147483647,-1,0,-1,2147483647,-1,2147483647,-1,2147483647,-1,0,-1,0,2147483647,0,0,-1,2147483647,0,2147483647,-1,-1,2147483647,2147483647,-1,0,0,2147483647,-1,0,2147483647,-1,-1,0,2147483647,-1,-1,-1,0,0,2147483647,0,0,2147483647,2147483647,2147483647,-1,-1,2147483647,2147483647,2147483647,0,-1,2147483647,0,-1,0,-1,0,-1,0,-1,-1,2147483647,-1,2147483647,-1,0,2147483647,0,2147483647,-1},{0,0,2147483647,-1,-1,2147483647,-1,-1,2147483647,2147483647,-1,0,-1,2147483647,-1,-1,2147483647,-1,0,2147483647,0,2147483647,2147483647,-1,-1,-1,2147483647,-1,-1,-1,2147483647,2147483647,-1,-1,0,0,2147483647,0,0,0,-1,-1,-1,2147483647,-1,2147483647,-1,-1,0,-1,2147483647,2147483647,2147483647,2147483647,0,2147483647,2147483647,0,-1,-1,0,0,-1,-1,2147483647,2147483647,0,2147483647,-1,0,-1,-1,2147483647,2147483647,0,-1,0,-1,2147483647,2147483647,2147483647,2147483647,0,0,0,-1,2147483647,-1,2147483647,0,0,2147483647,-1,0,-1,0,2147483647,2147483647,0,-1,2147483647,0,0,2147483647,2147483647,0,-1,2147483647,2147483647,2147483647,0,2147483647,0,-1,2147483647,-1,-1,2147483647,-1,2147483647,0,2147483647,2147483647,0,0,0,2147483647,0,-1,0,0,-1,-1,-1,2147483647,-1,2147483647,2147483647,2147483647,0,-1,2147483647,0,0,0,-1,2147483647,-1,2147483647,2147483647,-1,-1,0,2147483647,-1,2147483647,2147483647,0,2147483647,0,-1,0,-1,2147483647,2147483647,0,0,-1,2147483647,-1,2147483647,2147483647,0,2147483647,-1,-1,2147483647,-1,-1,-1,0,-1,2147483647,-1,0,0,2147483647,2147483647,0,0,-1,0,2147483647,2147483647,2147483647,-1,0,0,2147483647,-1,2147483647,0,0,-1,0,2147483647,-1,0,2147483647,2147483647,-1,2147483647,-1,2147483647,-1,-1,2147483647,0,-1,2147483647,-1},{-1,-1,0,2147483647,-1,2147483647,0,0,0,0,2147483647,0,2147483647,-1,2147483647,2147483647,-1,0,2147483647,2147483647,0,0,0,2147483647,0,2147483647,0,2147483647,-1,-1,-1,-1,0,-1,2147483647,0,-1,-1,0,0,2147483647,0,0,-1,-1,-1,2147483647,-1,-1,-1,0,0,0,-1,2147483647,2147483647,0,0,0,0,2147483647,2147483647,2147483647,2147483647,-1,-1,2147483647,-1,-1,2147483647,0,0,2147483647,-1,0,0,2147483647,0,2147483647,-1,-1,0,0,2147483647,2147483647,-1,-1,2147483647,-1,0,0,-1,0,-1,-1,0,-1,2147483647,2147483647,-1,-1,0,-1,-1,2147483647,2147483647,2147483647,0,-1,-1,0,2147483647,2147483647,0,0,2147483647,-1,0,0,0,0,-1,0,-1,0,0,2147483647,-1,-1,-1,0,0,0,-1,2147483647,2147483647,-1,0,-1,0,0,2147483647,-1,0,-1,2147483647,2147483647,2147483647,0,0,0,-1,-1,0,2147483647,2147483647,2147483647,-1,2147483647,2147483647,2147483647,2147483647,0,2147483647,2147483647,2147483647,2147483647,-1,2147483647,-1,2147483647,-1,0,-1,-1,2147483647,-1,0,0,0,-1,2147483647,0,2147483647,0,0,-1,0,-1,-1,2147483647,-1,-1,2147483647,2147483647,-1,-1,2147483647,2147483647,2147483647,0,-1,0,2147483647,-1,-1,0,-1,-1,2147483647,0,2147483647,0,2147483647,2147483647,2147483647,2147483647,2147483647,-1,0,-1},{0,-1,0,-1,0,-1,2147483647,-1,-1,-1,0,2147483647,2147483647,0,-1,2147483647,2147483647,2147483647,2147483647,-1,0,-1,-1,0,0,0,-1,0,0,2147483647,2147483647,-1,2147483647,-1,2147483647,2147483647,2147483647,2147483647,-1,-1,2147483647,2147483647,0,-1,0,-1,0,-1,-1,0,-1,2147483647,0,0,-1,0,0,0,2147483647,-1,0,0,2147483647,0,0,0,2147483647,2147483647,2147483647,-1,-1,2147483647,-1,2147483647,-1,2147483647,2147483647,-1,0,0,-1,-1,-1,-1,2147483647,2147483647,0,-1,-1,-1,-1,2147483647,2147483647,2147483647,-1,2147483647,2147483647,2147483647,2147483647,0,0,2147483647,0,0,0,2147483647,2147483647,-1,2147483647,0,0,2147483647,0,-1,2147483647,2147483647,2147483647,2147483647,-1,0,0,2147483647,2147483647,-1,-1,2147483647,0,0,-1,-1,-1,0,0,0,0,-1,0,-1,0,-1,0,0,2147483647,2147483647,2147483647,-1,0,-1,0,-1,-1,0,-1,-1,2147483647,2147483647,0,2147483647,-1,-1,-1,2147483647,2147483647,-1,-1,2147483647,0,0,2147483647,2147483647,-1,0,0,2147483647,0,0,2147483647,2147483647,2147483647,2147483647,2147483647,0,0,-1,-1,-1,2147483647,0,2147483647,-1,-1,-1,-1,2147483647,-1,-1,0,2147483647,0,-1,2147483647,0,0,-1,0,2147483647,2147483647,0,2147483647,2147483647,2147483647,-1,-1,2147483647,0,-1,-1,2147483647,2147483647,0,-1},{0,0,-1,2147483647,2147483647,-1,-1,2147483647,0,0,-1,2147483647,0,-1,0,0,2147483647,-1,0,2147483647,0,-1,-1,0,0,-1,0,2147483647,2147483647,0,0,-1,0,2147483647,2147483647,2147483647,2147483647,2147483647,-1,2147483647,0,-1,2147483647,-1,2147483647,-1,0,0,2147483647,2147483647,0,0,-1,2147483647,0,0,0,-1,-1,-1,0,2147483647,2147483647,2147483647,2147483647,-1,0,0,2147483647,2147483647,0,-1,-1,2147483647,0,-1,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,-1,-1,0,-1,2147483647,0,2147483647,2147483647,0,0,0,2147483647,-1,2147483647,2147483647,-1,0,0,2147483647,-1,0,-1,2147483647,2147483647,-1,-1,0,0,-1,-1,2147483647,0,-1,2147483647,2147483647,2147483647,0,2147483647,0,2147483647,2147483647,0,0,-1,0,-1,-1,0,-1,2147483647,2147483647,-1,2147483647,0,2147483647,-1,-1,-1,2147483647,2147483647,2147483647,0,0,0,-1,2147483647,-1,-1,-1,-1,2147483647,2147483647,-1,0,-1,2147483647,2147483647,0,0,0,-1,2147483647,2147483647,2147483647,-1,0,-1,0,-1,0,2147483647,2147483647,0,-1,-1,-1,2147483647,0,-1,0,0,2147483647,2147483647,-1,0,0,-1,0,0,2147483647,-1,0,0,2147483647,0,-1,0,-1,-1,2147483647,-1,-1,2147483647,2147483647,0,2147483647,-1,0,-1,-1,0,2147483647,-1,-1,-1,-1,0,2147483647,0},{2147483647,0,-1,0,-1,2147483647,2147483647,0,2147483647,0,0,2147483647,-1,2147483647,-1,0,0,-1,0,0,0,0,0,0,2147483647,2147483647,-1,0,-1,0,-1,2147483647,2147483647,-1,-1,-1,0,2147483647,2147483647,2147483647,2147483647,0,0,2147483647,0,2147483647,0,-1,-1,0,2147483647,2147483647,-1,0,-1,-1,0,0,0,2147483647,-1,0,2147483647,2147483647,0,0,-1,0,-1,2147483647,0,2147483647,-1,2147483647,2147483647,2147483647,2147483647,2147483647,0,2147483647,2147483647,0,2147483647,-1,0,-1,2147483647,-1,2147483647,0,-1,-1,2147483647,0,-1,-1,-1,2147483647,-1,-1,0,-1,2147483647,-1,-1,-1,0,0,-1,0,-1,2147483647,-1,0,0,2147483647,0,2147483647,2147483647,0,-1,-1,-1,0,0,0,2147483647,-1,2147483647,0,2147483647,0,0,0,0,-1,2147483647,-1,-1,2147483647,0,-1,-1,-1,-1,-1,2147483647,-1,2147483647,-1,-1,-1,-1,2147483647,0,-1,2147483647,-1,0,2147483647,-1,0,0,-1,0,2147483647,0,2147483647,2147483647,0,2147483647,0,2147483647,0,0,-1,2147483647,2147483647,0,-1,0,2147483647,0,0,-1,0,-1,-1,2147483647,2147483647,2147483647,-1,-1,-1,0,-1,-1,-1,0,0,-1,-1,2147483647,2147483647,2147483647,2147483647,2147483647,-1,-1,0,0,-1,0,0,-1,0,2147483647,-1,2147483647,0,2147483647},{0,2147483647,0,2147483647,-1,-1,2147483647,-1,2147483647,0,0,2147483647,0,-1,-1,-1,-1,0,0,-1,-1,-1,2147483647,2147483647,0,2147483647,0,0,-1,-1,0,2147483647,2147483647,0,-1,-1,-1,2147483647,0,-1,2147483647,-1,-1,-1,-1,2147483647,2147483647,0,0,-1,-1,-1,0,0,0,2147483647,0,-1,2147483647,0,-1,-1,0,2147483647,0,2147483647,-1,2147483647,0,0,-1,-1,-1,2147483647,2147483647,2147483647,-1,0,-1,0,-1,-1,0,2147483647,2147483647,-1,-1,2147483647,-1,2147483647,2147483647,2147483647,-1,0,0,0,0,-1,-1,-1,-1,2147483647,0,-1,0,2147483647,2147483647,-1,0,0,2147483647,0,2147483647,-1,2147483647,0,2147483647,0,0,2147483647,2147483647,2147483647,0,-1,0,0,2147483647,2147483647,0,2147483647,-1,2147483647,2147483647,0,2147483647,2147483647,2147483647,-1,0,2147483647,2147483647,-1,0,2147483647,-1,-1,0,-1,-1,2147483647,-1,0,0,-1,0,0,-1,0,0,-1,-1,0,2147483647,0,2147483647,2147483647,0,2147483647,-1,2147483647,2147483647,0,-1,-1,-1,-1,2147483647,-1,2147483647,0,0,-1,-1,-1,0,-1,-1,2147483647,2147483647,0,2147483647,-1,-1,0,2147483647,-1,2147483647,-1,-1,2147483647,2147483647,0,-1,0,-1,-1,-1,2147483647,2147483647,2147483647,-1,-1,2147483647,0,-1,2147483647,2147483647,-1,0,-1,0},{-1,2147483647,0,2147483647,0,0,0,2147483647,-1,2147483647,2147483647,0,-1,-1,0,0,0,-1,0,-1,-1,2147483647,0,-1,2147483647,-1,0,0,0,2147483647,-1,-1,2147483647,0,-1,2147483647,2147483647,2147483647,0,-1,2147483647,2147483647,2147483647,0,-1,2147483647,2147483647,2147483647,-1,-1,-1,2147483647,2147483647,2147483647,-1,-1,0,2147483647,2147483647,2147483647,2147483647,2147483647,0,-1,-1,0,-1,2147483647,0,0,-1,0,2147483647,2147483647,2147483647,2147483647,0,0,2147483647,0,-1,-1,0,2147483647,0,-1,0,-1,-1,2147483647,0,-1,2147483647,2147483647,2147483647,0,-1,2147483647,2147483647,2147483647,-1,0,-1,2147483647,0,2147483647,2147483647,-1,0,0,-1,-1,0,2147483647,-1,-1,0,0,2147483647,-1,-1,2147483647,2147483647,-1,2147483647,0,-1,2147483647,2147483647,2147483647,0,2147483647,-1,0,2147483647,2147483647,2147483647,0,-1,-1,2147483647,2147483647,0,2147483647,-1,2147483647,0,0,2147483647,2147483647,-1,-1,-1,0,2147483647,-1,2147483647,2147483647,2147483647,2147483647,0,0,-1,0,2147483647,0,0,2147483647,-1,-1,2147483647,-1,2147483647,2147483647,2147483647,0,2147483647,-1,2147483647,2147483647,2147483647,2147483647,0,2147483647,-1,0,0,2147483647,0,0,2147483647,2147483647,-1,0,2147483647,2147483647,0,2147483647,0,-1,-1,0,-1,-1,-1,2147483647,0,2147483647,2147483647,2147483647,2147483647,-1,-1,-1,0,0,2147483647,0,2147483647,-1,2147483647},{0,0,0,0,2147483647,-1,-1,2147483647,2147483647,-1,-1,2147483647,2147483647,2147483647,2147483647,0,-1,-1,-1,2147483647,0,-1,-1,0,2147483647,-1,-1,-1,-1,-1,2147483647,0,2147483647,0,0,2147483647,2147483647,0,-1,-1,0,2147483647,0,2147483647,2147483647,0,2147483647,0,2147483647,2147483647,-1,-1,2147483647,2147483647,0,0,2147483647,-1,0,0,0,0,2147483647,-1,0,0,-1,2147483647,-1,0,2147483647,0,2147483647,-1,-1,2147483647,-1,0,-1,2147483647,0,2147483647,-1,0,0,0,0,0,0,0,0,2147483647,-1,2147483647,2147483647,2147483647,0,0,2147483647,2147483647,2147483647,-1,2147483647,2147483647,-1,0,-1,0,0,2147483647,2147483647,0,-1,0,2147483647,0,2147483647,2147483647,-1,-1,2147483647,2147483647,2147483647,-1,2147483647,-1,0,2147483647,0,2147483647,2147483647,-1,0,0,-1,-1,-1,2147483647,0,-1,2147483647,2147483647,-1,2147483647,0,2147483647,2147483647,0,0,0,0,2147483647,2147483647,2147483647,-1,2147483647,-1,-1,0,-1,2147483647,0,0,0,0,0,2147483647,2147483647,2147483647,2147483647,2147483647,0,-1,0,0,0,0,2147483647,2147483647,2147483647,2147483647,-1,0,2147483647,-1,0,-1,2147483647,-1,2147483647,2147483647,-1,-1,2147483647,-1,-1,-1,0,-1,-1,2147483647,-1,0,2147483647,0,2147483647,-1,-1,0,2147483647,0,0,-1,-1,2147483647,-1,0,-1,2147483647,0,-1},{2147483647,0,-1,2147483647,0,2147483647,0,0,0,-1,0,0,-1,0,2147483647,2147483647,-1,2147483647,0,0,-1,0,0,2147483647,2147483647,2147483647,-1,0,0,-1,0,0,0,2147483647,2147483647,0,2147483647,2147483647,0,-1,2147483647,-1,0,-1,0,-1,0,2147483647,2147483647,0,2147483647,2147483647,-1,2147483647,-1,2147483647,0,0,0,-1,-1,-1,-1,-1,-1,0,0,-1,2147483647,0,0,0,2147483647,0,0,0,-1,-1,0,2147483647,2147483647,2147483647,-1,0,2147483647,0,2147483647,-1,-1,-1,0,-1,2147483647,2147483647,2147483647,2147483647,-1,2147483647,2147483647,-1,2147483647,0,0,0,-1,0,2147483647,2147483647,-1,2147483647,0,2147483647,-1,-1,-1,0,0,2147483647,0,0,0,2147483647,0,2147483647,0,2147483647,2147483647,-1,-1,0,0,2147483647,-1,0,0,-1,2147483647,-1,2147483647,0,-1,2147483647,2147483647,0,2147483647,2147483647,-1,-1,2147483647,2147483647,0,2147483647,2147483647,-1,0,2147483647,0,2147483647,2147483647,-1,-1,-1,-1,0,-1,0,0,-1,0,0,-1,2147483647,2147483647,2147483647,2147483647,2147483647,0,2147483647,2147483647,2147483647,0,-1,2147483647,-1,-1,0,-1,2147483647,2147483647,2147483647,-1,2147483647,2147483647,0,-1,0,0,-1,0,-1,0,-1,0,0,0,0,0,2147483647,2147483647,0,2147483647,-1,-1,0,-1,2147483647,2147483647,2147483647,2147483647,0,-1},{-1,2147483647,2147483647,0,-1,-1,-1,2147483647,-1,2147483647,2147483647,-1,0,2147483647,-1,2147483647,2147483647,0,-1,2147483647,0,2147483647,2147483647,0,2147483647,2147483647,0,-1,-1,0,2147483647,-1,2147483647,0,2147483647,-1,2147483647,-1,-1,0,2147483647,2147483647,0,0,0,2147483647,-1,2147483647,2147483647,0,0,2147483647,2147483647,0,2147483647,0,0,0,-1,2147483647,-1,-1,-1,0,2147483647,0,-1,-1,0,2147483647,2147483647,0,-1,2147483647,2147483647,-1,2147483647,2147483647,2147483647,-1,-1,2147483647,-1,-1,0,2147483647,2147483647,0,0,2147483647,2147483647,-1,0,2147483647,0,-1,-1,2147483647,0,0,0,2147483647,2147483647,0,2147483647,0,2147483647,-1,0,-1,0,0,2147483647,0,-1,-1,0,0,0,2147483647,-1,0,0,2147483647,-1,0,-1,2147483647,0,0,2147483647,-1,2147483647,-1,2147483647,-1,0,-1,2147483647,0,2147483647,0,2147483647,2147483647,2147483647,0,0,0,0,2147483647,0,0,0,-1,0,0,-1,0,-1,0,-1,-1,2147483647,-1,2147483647,0,-1,0,0,0,0,0,2147483647,0,0,-1,-1,2147483647,0,0,-1,-1,-1,2147483647,2147483647,2147483647,-1,0,0,2147483647,2147483647,-1,2147483647,0,0,0,0,-1,0,2147483647,2147483647,2147483647,2147483647,-1,2147483647,2147483647,0,0,2147483647,0,2147483647,0,-1,2147483647,0,-1,2147483647,0,-1,-1,0},{0,2147483647,2147483647,-1,2147483647,-1,2147483647,2147483647,2147483647,0,2147483647,2147483647,2147483647,2147483647,-1,2147483647,0,-1,0,0,-1,2147483647,-1,0,0,0,2147483647,0,-1,0,-1,-1,-1,-1,2147483647,2147483647,2147483647,2147483647,-1,-1,2147483647,0,0,2147483647,0,2147483647,-1,0,2147483647,0,0,0,0,2147483647,2147483647,-1,-1,-1,0,0,0,0,-1,-1,0,2147483647,-1,-1,0,2147483647,-1,2147483647,-1,2147483647,0,0,0,2147483647,2147483647,2147483647,2147483647,0,-1,0,0,2147483647,2147483647,0,0,0,-1,0,-1,-1,-1,2147483647,0,0,2147483647,0,-1,0,-1,2147483647,-1,2147483647,-1,2147483647,0,-1,2147483647,2147483647,0,-1,-1,-1,-1,0,0,0,0,-1,-1,2147483647,2147483647,2147483647,0,-1,0,0,2147483647,2147483647,-1,-1,2147483647,-1,-1,-1,0,0,0,2147483647,2147483647,0,0,2147483647,0,-1,2147483647,0,0,2147483647,-1,-1,2147483647,-1,2147483647,0,2147483647,2147483647,2147483647,0,-1,-1,2147483647,2147483647,-1,2147483647,2147483647,0,0,0,0,0,0,0,-1,2147483647,-1,0,0,2147483647,2147483647,-1,-1,-1,-1,-1,0,2147483647,-1,0,0,2147483647,2147483647,0,-1,0,0,2147483647,0,0,2147483647,-1,-1,0,0,2147483647,-1,0,2147483647,-1,2147483647,0,2147483647,0,2147483647,-1,-1,0,0},{2147483647,-1,-1,-1,2147483647,2147483647,2147483647,0,-1,2147483647,2147483647,2147483647,2147483647,2147483647,0,0,2147483647,0,0,2147483647,0,0,0,-1,-1,0,0,0,0,2147483647,0,2147483647,-1,-1,0,2147483647,-1,0,2147483647,2147483647,-1,0,0,2147483647,2147483647,0,-1,-1,0,2147483647,2147483647,-1,-1,-1,0,-1,0,-1,-1,-1,2147483647,2147483647,-1,2147483647,2147483647,0,0,2147483647,0,0,2147483647,-1,2147483647,0,-1,0,2147483647,-1,0,2147483647,-1,2147483647,2147483647,-1,-1,0,2147483647,2147483647,0,2147483647,2147483647,-1,2147483647,2147483647,0,2147483647,-1,-1,2147483647,0,0,-1,0,2147483647,2147483647,-1,-1,-1,2147483647,2147483647,-1,2147483647,0,2147483647,-1,-1,-1,-1,0,2147483647,-1,-1,0,2147483647,0,-1,2147483647,-1,0,0,2147483647,2147483647,2147483647,-1,-1,2147483647,0,-1,2147483647,2147483647,0,0,-1,-1,-1,-1,2147483647,0,2147483647,-1,0,-1,0,-1,0,0,0,0,0,2147483647,-1,-1,0,2147483647,-1,2147483647,2147483647,2147483647,2147483647,0,-1,0,-1,0,0,-1,0,2147483647,-1,2147483647,0,2147483647,0,-1,2147483647,2147483647,-1,2147483647,-1,-1,-1,-1,2147483647,-1,2147483647,0,-1,0,0,2147483647,0,2147483647,0,0,-1,2147483647,0,-1,-1,2147483647,2147483647,0,-1,-1,0,2147483647,0,-1,2147483647,0,0},{0,0,2147483647,-1,-1,2147483647,-1,0,-1,0,-1,2147483647,0,0,0,0,2147483647,2147483647,2147483647,-1,0,0,-1,2147483647,0,-1,2147483647,0,2147483647,2147483647,0,-1,0,0,2147483647,-1,0,2147483647,0,0,-1,-1,-1,0,2147483647,0,-1,-1,0,-1,0,0,-1,0,0,0,2147483647,2147483647,2147483647,-1,2147483647,0,-1,0,2147483647,-1,2147483647,-1,0,0,2147483647,-1,0,2147483647,-1,2147483647,-1,0,-1,-1,2147483647,0,2147483647,-1,0,-1,-1,0,0,-1,2147483647,-1,2147483647,2147483647,2147483647,2147483647,2147483647,-1,2147483647,0,-1,0,-1,2147483647,0,2147483647,2147483647,2147483647,2147483647,-1,0,2147483647,2147483647,0,-1,0,0,-1,0,2147483647,-1,2147483647,-1,2147483647,-1,0,0,2147483647,0,2147483647,-1,-1,-1,-1,2147483647,2147483647,0,-1,2147483647,0,-1,0,0,-1,2147483647,0,0,-1,0,0,-1,0,-1,0,-1,2147483647,2147483647,0,0,-1,2147483647,-1,0,2147483647,-1,0,0,2147483647,-1,0,-1,0,2147483647,2147483647,0,2147483647,2147483647,2147483647,0,-1,0,0,2147483647,-1,-1,0,2147483647,-1,-1,-1,2147483647,0,0,2147483647,0,0,-1,-1,-1,2147483647,-1,0,-1,0,2147483647,-1,0,0,0,-1,0,-1,-1,2147483647,2147483647,-1,2147483647,-1,2147483647,0,-1},{-1,-1,2147483647,0,0,2147483647,2147483647,2147483647,0,0,-1,0,2147483647,-1,0,2147483647,0,2147483647,-1,2147483647,0,-1,-1,2147483647,2147483647,-1,-1,0,-1,-1,2147483647,-1,0,0,0,-1,-1,0,0,2147483647,-1,2147483647,-1,0,-1,2147483647,2147483647,0,0,-1,-1,0,2147483647,0,-1,-1,0,2147483647,2147483647,-1,2147483647,-1,-1,2147483647,2147483647,2147483647,2147483647,0,2147483647,0,2147483647,0,2147483647,2147483647,2147483647,-1,-1,-1,0,0,-1,0,0,0,-1,2147483647,-1,0,2147483647,2147483647,-1,-1,2147483647,-1,2147483647,-1,0,-1,-1,2147483647,0,-1,0,0,0,2147483647,0,2147483647,-1,-1,-1,2147483647,2147483647,-1,0,0,0,0,2147483647,0,-1,0,-1,0,0,-1,0,2147483647,2147483647,2147483647,-1,0,-1,-1,2147483647,-1,0,2147483647,0,2147483647,2147483647,2147483647,2147483647,0,-1,2147483647,0,-1,0,2147483647,0,0,-1,2147483647,0,0,0,2147483647,-1,0,0,-1,2147483647,2147483647,-1,0,2147483647,0,0,2147483647,-1,2147483647,-1,0,0,0,-1,0,-1,-1,-1,0,-1,2147483647,-1,-1,-1,2147483647,-1,2147483647,0,2147483647,-1,0,0,-1,-1,0,2147483647,0,2147483647,-1,0,-1,-1,2147483647,0,2147483647,-1,2147483647,-1,2147483647,2147483647,-1,0,2147483647,0,-1,0,0,0},{0,2147483647,2147483647,0,0,0,2147483647,0,-1,0,0,-1,-1,-1,0,0,0,2147483647,2147483647,-1,-1,2147483647,0,2147483647,0,0,2147483647,-1,2147483647,2147483647,2147483647,0,2147483647,0,-1,0,0,0,2147483647,0,-1,-1,2147483647,0,-1,0,2147483647,0,-1,2147483647,0,2147483647,-1,0,0,-1,0,-1,0,-1,-1,0,-1,0,-1,2147483647,-1,-1,-1,0,-1,-1,0,0,0,2147483647,2147483647,0,2147483647,0,-1,-1,-1,2147483647,-1,2147483647,0,2147483647,0,-1,0,-1,0,0,2147483647,-1,0,-1,2147483647,2147483647,0,-1,-1,-1,0,-1,-1,-1,0,0,2147483647,0,-1,2147483647,2147483647,2147483647,-1,2147483647,0,0,-1,2147483647,-1,0,-1,-1,0,-1,2147483647,-1,-1,2147483647,0,2147483647,2147483647,2147483647,2147483647,-1,0,-1,2147483647,-1,-1,-1,0,0,2147483647,2147483647,-1,0,-1,2147483647,0,2147483647,2147483647,2147483647,-1,2147483647,-1,0,0,-1,2147483647,0,-1,2147483647,-1,-1,-1,-1,-1,0,2147483647,0,2147483647,2147483647,0,0,0,0,2147483647,2147483647,2147483647,-1,-1,-1,2147483647,0,2147483647,-1,-1,2147483647,-1,2147483647,2147483647,2147483647,-1,2147483647,2147483647,0,-1,-1,0,-1,2147483647,-1,-1,2147483647,-1,-1,-1,0,0,0,2147483647,0,0,0,0,0,2147483647},{-1,0,2147483647,-1,-1,0,0,2147483647,-1,2147483647,2147483647,0,2147483647,2147483647,-1,0,0,2147483647,-1,-1,2147483647,0,0,0,-1,-1,2147483647,2147483647,2147483647,0,2147483647,-1,2147483647,2147483647,2147483647,0,2147483647,-1,-1,0,-1,0,2147483647,-1,-1,0,-1,-1,0,2147483647,-1,2147483647,0,-1,-1,0,2147483647,0,2147483647,-1,-1,-1,-1,2147483647,-1,2147483647,2147483647,0,0,2147483647,0,2147483647,-1,2147483647,0,2147483647,2147483647,-1,0,-1,-1,0,-1,-1,0,2147483647,2147483647,0,2147483647,-1,0,-1,0,0,0,2147483647,0,2147483647,-1,-1,-1,2147483647,-1,-1,0,0,0,-1,-1,-1,2147483647,0,0,2147483647,-1,-1,0,-1,-1,0,-1,0,2147483647,2147483647,0,-1,2147483647,2147483647,0,2147483647,-1,0,-1,0,-1,0,2147483647,2147483647,2147483647,-1,-1,0,2147483647,-1,-1,2147483647,0,2147483647,0,2147483647,2147483647,2147483647,0,0,-1,0,2147483647,2147483647,2147483647,2147483647,2147483647,0,2147483647,-1,2147483647,-1,2147483647,-1,-1,2147483647,0,2147483647,2147483647,2147483647,0,0,2147483647,-1,0,-1,-1,-1,0,0,0,-1,0,0,0,-1,2147483647,2147483647,2147483647,-1,0,2147483647,0,0,-1,0,-1,-1,0,0,2147483647,0,0,-1,-1,0,2147483647,2147483647,0,0,-1,2147483647,0,2147483647,0,0,2147483647},{2147483647,-1,2147483647,2147483647,0,-1,2147483647,-1,2147483647,-1,-1,-1,-1,0,-1,-1,-1,2147483647,-1,2147483647,-1,0,-1,0,-1,-1,0,2147483647,-1,0,2147483647,2147483647,-1,0,0,-1,-1,-1,2147483647,-1,-1,-1,-1,0,0,0,0,0,0,0,-1,-1,-1,-1,2147483647,0,2147483647,-1,-1,2147483647,2147483647,0,2147483647,-1,0,-1,-1,2147483647,0,-1,-1,-1,2147483647,0,-1,-1,-1,2147483647,2147483647,0,0,0,0,-1,-1,-1,0,-1,-1,2147483647,-1,-1,-1,2147483647,-1,2147483647,2147483647,0,-1,-1,-1,0,-1,2147483647,2147483647,0,-1,2147483647,2147483647,0,-1,-1,-1,2147483647,0,-1,0,2147483647,0,-1,-1,2147483647,0,-1,-1,2147483647,-1,0,2147483647,0,0,0,2147483647,0,-1,2147483647,2147483647,-1,2147483647,2147483647,-1,-1,2147483647,0,-1,-1,2147483647,-1,0,2147483647,-1,-1,2147483647,0,0,0,-1,2147483647,-1,2147483647,0,-1,2147483647,2147483647,2147483647,-1,2147483647,-1,0,0,2147483647,-1,-1,2147483647,0,0,0,0,-1,0,-1,0,-1,2147483647,0,2147483647,-1,0,2147483647,2147483647,2147483647,0,0,2147483647,0,-1,-1,-1,2147483647,2147483647,0,2147483647,-1,2147483647,0,2147483647,0,2147483647,-1,-1,-1,2147483647,2147483647,2147483647,-1,-1,-1,0,-1,2147483647,0},{-1,2147483647,2147483647,-1,-1,-1,0,-1,-1,2147483647,-1,0,0,0,0,-1,2147483647,0,-1,-1,0,-1,2147483647,0,2147483647,-1,-1,0,-1,2147483647,0,2147483647,2147483647,0,2147483647,0,0,0,0,2147483647,-1,0,-1,2147483647,2147483647,0,2147483647,2147483647,0,-1,2147483647,-1,-1,0,0,-1,2147483647,-1,2147483647,2147483647,2147483647,0,0,-1,0,0,0,2147483647,0,2147483647,2147483647,2147483647,0,0,-1,0,0,0,0,0,0,0,-1,0,-1,-1,0,2147483647,2147483647,2147483647,2147483647,-1,-1,-1,-1,2147483647,2147483647,2147483647,0,0,0,0,-1,2147483647,-1,2147483647,-1,2147483647,2147483647,2147483647,2147483647,2147483647,-1,-1,-1,-1,0,-1,2147483647,0,0,2147483647,2147483647,0,2147483647,-1,0,-1,-1,2147483647,0,2147483647,0,0,-1,2147483647,-1,-1,2147483647,-1,0,-1,-1,2147483647,2147483647,2147483647,-1,0,-1,2147483647,-1,-1,0,-1,-1,-1,2147483647,2147483647,-1,0,2147483647,0,0,2147483647,-1,-1,-1,-1,0,2147483647,2147483647,-1,0,2147483647,2147483647,2147483647,2147483647,-1,0,2147483647,2147483647,-1,-1,0,2147483647,0,0,-1,-1,0,0,0,0,2147483647,0,-1,2147483647,2147483647,2147483647,-1,2147483647,-1,0,-1,0,2147483647,0,-1,-1,0,0,-1,-1,-1,-1,2147483647,2147483647,0,0,2147483647,-1},{-1,-1,-1,0,-1,2147483647,2147483647,-1,2147483647,0,2147483647,2147483647,-1,-1,0,0,0,0,0,0,0,0,2147483647,-1,-1,-1,2147483647,-1,-1,2147483647,0,-1,2147483647,2147483647,-1,0,2147483647,2147483647,0,2147483647,2147483647,-1,-1,2147483647,-1,2147483647,0,-1,2147483647,0,-1,-1,0,0,0,-1,2147483647,2147483647,2147483647,2147483647,-1,2147483647,2147483647,0,0,-1,0,0,-1,2147483647,0,0,0,-1,2147483647,0,2147483647,2147483647,-1,-1,0,2147483647,-1,0,2147483647,2147483647,-1,2147483647,2147483647,-1,0,0,2147483647,0,0,0,2147483647,2147483647,0,2147483647,0,2147483647,0,-1,2147483647,-1,2147483647,2147483647,2147483647,0,2147483647,-1,-1,-1,-1,0,2147483647,0,0,0,0,0,-1,-1,0,0,0,2147483647,-1,2147483647,0,-1,2147483647,-1,2147483647,0,2147483647,-1,-1,0,0,-1,-1,0,-1,2147483647,0,2147483647,0,0,-1,-1,-1,2147483647,-1,2147483647,-1,0,2147483647,2147483647,-1,2147483647,0,-1,0,0,0,0,2147483647,-1,0,0,0,0,0,2147483647,2147483647,0,0,2147483647,0,-1,2147483647,0,0,-1,0,-1,0,2147483647,0,0,-1,-1,2147483647,-1,2147483647,2147483647,2147483647,2147483647,2147483647,0,2147483647,2147483647,0,-1,-1,-1,-1,0,-1,0,-1,0,-1,2147483647,-1,-1,0,-1,-1},{2147483647,2147483647,0,0,2147483647,0,-1,-1,0,0,2147483647,2147483647,2147483647,2147483647,0,-1,-1,2147483647,-1,0,0,0,2147483647,0,-1,0,2147483647,2147483647,2147483647,0,0,0,0,0,-1,0,2147483647,-1,-1,2147483647,0,-1,2147483647,-1,2147483647,0,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,-1,-1,-1,-1,2147483647,2147483647,0,2147483647,0,2147483647,2147483647,0,0,2147483647,-1,-1,-1,0,2147483647,2147483647,-1,-1,0,2147483647,0,-1,-1,-1,0,0,0,0,0,-1,-1,-1,2147483647,-1,-1,2147483647,-1,0,-1,-1,2147483647,-1,0,0,-1,0,-1,0,-1,0,0,2147483647,0,2147483647,-1,0,-1,0,-1,0,-1,2147483647,0,2147483647,0,-1,2147483647,-1,-1,-1,2147483647,0,0,0,-1,-1,2147483647,2147483647,0,2147483647,2147483647,2147483647,-1,2147483647,0,0,0,-1,-1,2147483647,-1,0,-1,-1,2147483647,-1,2147483647,-1,-1,-1,0,2147483647,0,2147483647,2147483647,0,-1,0,-1,-1,0,-1,-1,2147483647,0,2147483647,2147483647,-1,2147483647,2147483647,-1,2147483647,-1,0,2147483647,0,2147483647,2147483647,-1,2147483647,-1,-1,0,-1,2147483647,2147483647,-1,-1,2147483647,0,2147483647,-1,-1,2147483647,2147483647,2147483647,-1,0,2147483647,-1,2147483647,-1,0,2147483647,-1,-1,0,-1,-1,0,2147483647,-1,2147483647,0},{-1,-1,0,-1,-1,2147483647,-1,-1,2147483647,0,2147483647,0,2147483647,0,-1,2147483647,2147483647,2147483647,2147483647,-1,2147483647,-1,-1,-1,-1,-1,-1,2147483647,-1,2147483647,2147483647,2147483647,2147483647,0,0,2147483647,2147483647,2147483647,0,2147483647,2147483647,2147483647,2147483647,0,2147483647,2147483647,0,2147483647,0,0,0,-1,-1,0,0,-1,0,-1,2147483647,2147483647,0,2147483647,-1,0,2147483647,0,-1,2147483647,2147483647,-1,-1,2147483647,2147483647,2147483647,0,2147483647,-1,2147483647,2147483647,0,2147483647,2147483647,2147483647,-1,-1,0,2147483647,-1,-1,0,0,-1,0,2147483647,-1,2147483647,-1,0,2147483647,2147483647,2147483647,2147483647,0,0,2147483647,0,-1,0,2147483647,2147483647,-1,0,-1,2147483647,-1,2147483647,-1,2147483647,0,0,2147483647,-1,-1,2147483647,0,-1,-1,0,2147483647,2147483647,2147483647,2147483647,0,2147483647,2147483647,0,0,2147483647,0,0,2147483647,2147483647,-1,-1,-1,-1,0,-1,-1,-1,2147483647,0,2147483647,0,2147483647,-1,-1,-1,2147483647,0,0,-1,2147483647,0,2147483647,0,2147483647,-1,-1,2147483647,2147483647,-1,0,2147483647,-1,0,2147483647,0,2147483647,0,-1,0,-1,2147483647,0,0,2147483647,2147483647,0,2147483647,0,2147483647,-1,2147483647,-1,2147483647,0,2147483647,2147483647,-1,0,-1,-1,0,0,-1,0,-1,-1,2147483647,-1,0,0,0,0,0,-1,0,2147483647,-1,-1},{0,-1,0,0,2147483647,-1,-1,2147483647,-1,2147483647,0,2147483647,-1,0,0,0,0,2147483647,-1,2147483647,-1,0,-1,2147483647,0,0,-1,0,2147483647,-1,2147483647,2147483647,0,2147483647,-1,0,-1,-1,0,-1,-1,-1,0,2147483647,-1,2147483647,0,-1,0,-1,-1,-1,2147483647,2147483647,0,2147483647,-1,2147483647,0,2147483647,0,0,2147483647,-1,0,2147483647,-1,-1,-1,2147483647,0,0,0,2147483647,-1,-1,0,0,2147483647,-1,-1,2147483647,0,2147483647,-1,2147483647,0,2147483647,-1,0,2147483647,0,-1,-1,2147483647,-1,2147483647,0,2147483647,-1,2147483647,0,0,0,0,-1,2147483647,-1,2147483647,-1,0,2147483647,2147483647,-1,0,2147483647,0,0,0,2147483647,0,2147483647,-1,0,-1,2147483647,2147483647,2147483647,0,-1,0,2147483647,0,-1,0,2147483647,0,-1,-1,0,2147483647,0,2147483647,0,-1,2147483647,0,2147483647,2147483647,2147483647,0,0,0,-1,2147483647,0,0,-1,-1,0,-1,2147483647,2147483647,-1,-1,2147483647,0,2147483647,2147483647,0,2147483647,2147483647,0,-1,-1,0,2147483647,-1,2147483647,0,-1,2147483647,2147483647,2147483647,2147483647,0,2147483647,0,-1,0,0,-1,0,2147483647,0,2147483647,0,2147483647,2147483647,-1,2147483647,-1,2147483647,0,0,2147483647,-1,-1,2147483647,-1,-1,2147483647,2147483647,2147483647,0,-1,2147483647,-1,2147483647,2147483647,2147483647},{0,-1,-1,0,0,2147483647,0,0,0,0,2147483647,2147483647,2147483647,2147483647,-1,-1,-1,-1,-1,-1,0,2147483647,2147483647,0,-1,-1,-1,2147483647,-1,2147483647,-1,-1,2147483647,0,2147483647,-1,0,2147483647,0,0,0,0,0,0,-1,2147483647,2147483647,2147483647,-1,2147483647,0,0,0,2147483647,0,2147483647,2147483647,2147483647,0,2147483647,0,0,0,2147483647,-1,-1,-1,2147483647,0,2147483647,0,0,0,2147483647,-1,2147483647,-1,0,0,0,2147483647,2147483647,-1,2147483647,2147483647,-1,-1,0,0,-1,-1,-1,0,-1,-1,0,-1,-1,-1,0,2147483647,2147483647,0,-1,2147483647,2147483647,-1,-1,0,-1,2147483647,0,0,2147483647,0,0,0,0,-1,0,2147483647,0,-1,-1,2147483647,-1,2147483647,-1,-1,2147483647,2147483647,-1,2147483647,-1,-1,0,-1,2147483647,0,0,-1,-1,2147483647,-1,2147483647,-1,2147483647,2147483647,2147483647,-1,0,2147483647,0,-1,0,0,2147483647,0,2147483647,-1,-1,2147483647,2147483647,0,-1,-1,2147483647,2147483647,-1,2147483647,-1,-1,0,2147483647,0,2147483647,0,-1,0,0,-1,0,2147483647,0,-1,-1,0,0,-1,0,2147483647,0,-1,2147483647,0,0,-1,-1,2147483647,2147483647,-1,2147483647,-1,2147483647,2147483647,0,0,2147483647,2147483647,0,-1,0,0,0,0,2147483647,-1,2147483647,2147483647,0,2147483647},{-1,2147483647,-1,-1,0,2147483647,2147483647,2147483647,2147483647,-1,0,2147483647,2147483647,2147483647,2147483647,-1,0,2147483647,-1,0,-1,-1,0,0,-1,-1,0,0,0,0,-1,2147483647,0,-1,0,0,2147483647,-1,-1,2147483647,2147483647,-1,2147483647,0,-1,0,-1,2147483647,0,2147483647,0,0,0,2147483647,0,-1,-1,2147483647,-1,-1,0,2147483647,2147483647,-1,-1,-1,2147483647,-1,2147483647,-1,-1,-1,2147483647,2147483647,-1,0,2147483647,-1,0,0,-1,2147483647,2147483647,0,2147483647,0,-1,-1,2147483647,-1,-1,0,2147483647,0,2147483647,0,-1,2147483647,-1,-1,0,-1,2147483647,-1,2147483647,2147483647,-1,2147483647,-1,0,-1,0,0,0,0,2147483647,0,2147483647,-1,2147483647,0,0,0,2147483647,-1,-1,-1,0,-1,2147483647,2147483647,0,-1,2147483647,0,-1,2147483647,0,-1,0,-1,2147483647,-1,-1,0,0,2147483647,-1,2147483647,2147483647,2147483647,-1,2147483647,-1,2147483647,0,-1,2147483647,0,-1,0,-1,2147483647,2147483647,0,-1,-1,-1,0,0,2147483647,2147483647,0,-1,2147483647,2147483647,2147483647,2147483647,-1,2147483647,-1,-1,-1,-1,2147483647,2147483647,-1,0,2147483647,2147483647,2147483647,2147483647,0,-1,-1,2147483647,0,0,0,2147483647,0,2147483647,-1,-1,0,0,2147483647,-1,0,2147483647,2147483647,2147483647,2147483647,-1,-1,0,2147483647,-1,-1,-1,2147483647},{2147483647,-1,2147483647,0,-1,0,2147483647,-1,2147483647,2147483647,0,0,2147483647,2147483647,-1,0,0,2147483647,2147483647,0,0,-1,-1,-1,2147483647,0,0,-1,-1,0,2147483647,-1,0,0,0,-1,0,2147483647,0,0,0,-1,0,0,0,2147483647,0,-1,0,-1,0,2147483647,2147483647,-1,2147483647,2147483647,2147483647,0,2147483647,-1,-1,-1,0,2147483647,2147483647,-1,-1,0,0,-1,-1,2147483647,0,-1,-1,-1,-1,0,0,0,2147483647,2147483647,-1,2147483647,0,0,0,-1,0,-1,-1,2147483647,-1,-1,-1,0,2147483647,2147483647,-1,2147483647,0,2147483647,2147483647,0,2147483647,2147483647,2147483647,0,2147483647,0,0,-1,0,0,2147483647,-1,2147483647,0,-1,0,0,0,2147483647,2147483647,0,0,-1,0,-1,2147483647,2147483647,2147483647,0,-1,2147483647,-1,0,0,0,0,2147483647,0,-1,-1,-1,-1,-1,2147483647,0,0,-1,2147483647,2147483647,2147483647,-1,-1,2147483647,0,-1,-1,2147483647,0,-1,2147483647,0,-1,0,2147483647,2147483647,-1,2147483647,2147483647,2147483647,0,-1,-1,-1,2147483647,0,2147483647,-1,0,0,-1,2147483647,2147483647,0,2147483647,0,0,2147483647,-1,0,2147483647,0,-1,-1,2147483647,0,0,-1,-1,0,0,2147483647,-1,2147483647,-1,2147483647,2147483647,-1,2147483647,-1,-1,-1,-1,0,0,0,0,-1},{2147483647,0,2147483647,2147483647,-1,2147483647,-1,2147483647,2147483647,-1,0,2147483647,-1,0,2147483647,0,-1,-1,-1,0,-1,0,-1,-1,2147483647,0,2147483647,0,0,-1,-1,2147483647,2147483647,-1,-1,-1,0,0,0,2147483647,0,2147483647,-1,0,2147483647,0,0,2147483647,-1,2147483647,-1,-1,2147483647,0,2147483647,2147483647,0,2147483647,-1,-1,2147483647,2147483647,-1,0,-1,0,0,0,2147483647,0,2147483647,0,0,0,-1,2147483647,-1,2147483647,-1,2147483647,2147483647,-1,0,-1,-1,-1,-1,-1,-1,0,0,-1,-1,2147483647,0,2147483647,2147483647,0,0,2147483647,2147483647,0,-1,-1,2147483647,0,2147483647,0,-1,2147483647,2147483647,2147483647,0,0,0,2147483647,0,0,0,-1,-1,0,-1,2147483647,2147483647,-1,2147483647,0,0,-1,0,0,2147483647,0,2147483647,0,0,-1,2147483647,-1,2147483647,0,2147483647,0,2147483647,0,0,0,-1,0,0,-1,0,0,0,2147483647,-1,-1,2147483647,2147483647,-1,2147483647,2147483647,0,0,0,0,-1,2147483647,-1,2147483647,-1,-1,2147483647,-1,2147483647,0,-1,0,2147483647,-1,2147483647,0,2147483647,2147483647,-1,0,-1,2147483647,-1,2147483647,-1,-1,-1,0,2147483647,2147483647,-1,-1,2147483647,2147483647,0,-1,2147483647,-1,2147483647,-1,-1,0,2147483647,-1,2147483647,0,-1,2147483647,0,-1,-1,-1,0,2147483647},{0,2147483647,-1,0,0,2147483647,0,2147483647,-1,2147483647,2147483647,-1,0,0,0,-1,0,0,-1,2147483647,2147483647,-1,2147483647,-1,-1,2147483647,-1,0,-1,2147483647,2147483647,0,0,2147483647,2147483647,0,2147483647,-1,2147483647,-1,-1,2147483647,2147483647,2147483647,2147483647,0,-1,-1,-1,-1,-1,0,2147483647,-1,2147483647,0,-1,2147483647,-1,-1,0,2147483647,0,2147483647,0,-1,-1,2147483647,2147483647,2147483647,2147483647,2147483647,0,-1,0,0,-1,0,0,2147483647,0,2147483647,2147483647,-1,2147483647,-1,2147483647,0,-1,-1,-1,0,2147483647,0,0,0,2147483647,-1,2147483647,-1,-1,2147483647,0,-1,2147483647,-1,0,2147483647,-1,-1,0,0,2147483647,0,0,0,2147483647,2147483647,2147483647,0,2147483647,0,-1,2147483647,-1,-1,0,2147483647,0,0,-1,0,2147483647,0,0,2147483647,0,-1,0,0,0,2147483647,0,2147483647,0,0,-1,2147483647,-1,-1,2147483647,2147483647,2147483647,-1,2147483647,-1,0,2147483647,-1,0,2147483647,-1,-1,-1,2147483647,2147483647,-1,2147483647,-1,0,2147483647,2147483647,2147483647,2147483647,-1,0,-1,0,-1,2147483647,-1,2147483647,-1,-1,2147483647,-1,-1,-1,2147483647,0,-1,-1,2147483647,2147483647,-1,2147483647,2147483647,-1,-1,-1,0,2147483647,-1,2147483647,2147483647,-1,-1,-1,2147483647,0,2147483647,2147483647,2147483647,-1,-1,2147483647,-1,2147483647,-1,0,0},{0,2147483647,2147483647,0,0,2147483647,-1,-1,-1,0,0,-1,-1,0,0,-1,2147483647,2147483647,0,0,-1,0,0,-1,2147483647,2147483647,2147483647,2147483647,0,-1,2147483647,0,0,2147483647,0,-1,-1,2147483647,2147483647,0,-1,-1,-1,2147483647,-1,2147483647,2147483647,-1,0,2147483647,0,2147483647,-1,2147483647,0,2147483647,2147483647,0,-1,-1,2147483647,2147483647,2147483647,0,2147483647,-1,0,0,-1,0,2147483647,-1,2147483647,2147483647,2147483647,-1,2147483647,-1,-1,2147483647,0,2147483647,0,-1,-1,-1,-1,0,-1,2147483647,0,0,0,2147483647,0,0,2147483647,2147483647,-1,0,-1,2147483647,-1,0,-1,0,0,2147483647,2147483647,2147483647,0,2147483647,-1,-1,2147483647,-1,-1,2147483647,2147483647,2147483647,2147483647,-1,-1,-1,-1,2147483647,0,0,-1,2147483647,-1,0,0,0,0,0,0,2147483647,0,2147483647,-1,-1,2147483647,-1,-1,-1,-1,0,-1,-1,2147483647,0,-1,2147483647,-1,-1,-1,0,0,-1,2147483647,-1,0,0,0,-1,2147483647,2147483647,2147483647,-1,2147483647,0,-1,2147483647,0,-1,2147483647,0,-1,2147483647,0,2147483647,2147483647,0,0,2147483647,0,0,2147483647,-1,-1,0,-1,0,-1,-1,0,-1,-1,0,0,0,-1,-1,2147483647,2147483647,-1,-1,-1,2147483647,-1,0,2147483647,-1,2147483647,2147483647,-1,-1,-1,2147483647,0},{0,2147483647,0,-1,0,0,2147483647,-1,2147483647,0,0,0,2147483647,0,0,2147483647,0,0,0,2147483647,0,0,0,0,-1,-1,0,-1,2147483647,-1,2147483647,2147483647,-1,2147483647,0,-1,-1,0,2147483647,2147483647,0,-1,-1,2147483647,-1,0,0,0,0,-1,2147483647,0,-1,-1,-1,-1,0,-1,-1,2147483647,-1,2147483647,0,2147483647,2147483647,2147483647,-1,2147483647,-1,0,2147483647,-1,2147483647,-1,0,2147483647,2147483647,-1,2147483647,0,0,2147483647,-1,-1,0,-1,0,-1,-1,-1,0,0,-1,2147483647,0,0,0,0,0,0,2147483647,-1,2147483647,-1,-1,-1,0,0,0,-1,0,-1,-1,-1,0,-1,0,2147483647,2147483647,0,0,0,-1,2147483647,0,2147483647,-1,0,0,0,2147483647,-1,0,-1,0,0,2147483647,-1,0,2147483647,0,0,2147483647,2147483647,2147483647,0,2147483647,-1,2147483647,-1,-1,0,2147483647,-1,-1,0,2147483647,-1,2147483647,2147483647,-1,-1,-1,0,2147483647,2147483647,2147483647,-1,2147483647,2147483647,2147483647,-1,-1,0,2147483647,0,-1,-1,-1,2147483647,-1,0,0,-1,-1,2147483647,2147483647,0,-1,0,-1,-1,2147483647,-1,-1,0,0,2147483647,-1,-1,2147483647,0,-1,2147483647,-1,-1,-1,0,-1,-1,-1,-1,2147483647,0,2147483647,-1,0,2147483647,2147483647,-1,2147483647},{-1,0,0,-1,2147483647,-1,0,2147483647,0,0,-1,0,0,-1,-1,0,2147483647,-1,-1,0,2147483647,2147483647,2147483647,2147483647,0,-1,-1,-1,0,2147483647,-1,0,0,-1,-1,0,-1,0,2147483647,0,2147483647,-1,-1,2147483647,2147483647,-1,-1,0,-1,0,0,-1,-1,-1,2147483647,2147483647,2147483647,2147483647,0,-1,2147483647,2147483647,-1,2147483647,0,-1,2147483647,-1,2147483647,-1,2147483647,-1,-1,2147483647,-1,2147483647,-1,2147483647,0,-1,-1,0,2147483647,2147483647,2147483647,0,2147483647,-1,-1,-1,0,-1,-1,0,0,-1,2147483647,-1,-1,0,0,0,0,2147483647,0,0,2147483647,-1,2147483647,2147483647,2147483647,2147483647,0,-1,2147483647,0,0,-1,2147483647,-1,2147483647,-1,2147483647,2147483647,2147483647,2147483647,-1,0,0,2147483647,-1,0,-1,-1,-1,2147483647,-1,-1,0,2147483647,0,-1,2147483647,0,2147483647,-1,2147483647,0,2147483647,2147483647,0,-1,2147483647,0,2147483647,2147483647,-1,-1,-1,-1,2147483647,-1,-1,0,-1,-1,0,0,2147483647,2147483647,0,2147483647,-1,2147483647,2147483647,0,-1,2147483647,0,-1,2147483647,-1,0,-1,-1,0,0,-1,-1,-1,-1,0,-1,2147483647,-1,0,0,2147483647,0,2147483647,2147483647,2147483647,2147483647,0,2147483647,0,2147483647,-1,-1,-1,-1,2147483647,2147483647,2147483647,0,0,0,-1,-1,-1,2147483647},{2147483647,0,2147483647,0,2147483647,0,2147483647,2147483647,2147483647,0,2147483647,-1,-1,-1,0,2147483647,-1,0,0,0,0,0,0,-1,-1,0,0,-1,2147483647,-1,0,0,2147483647,-1,-1,0,0,0,0,2147483647,0,0,0,-1,-1,0,2147483647,2147483647,0,2147483647,-1,-1,-1,2147483647,0,0,-1,0,0,-1,-1,0,0,0,2147483647,-1,-1,0,-1,0,-1,0,-1,2147483647,2147483647,2147483647,0,0,-1,2147483647,2147483647,0,-1,-1,2147483647,2147483647,-1,0,-1,2147483647,2147483647,2147483647,-1,-1,2147483647,0,-1,2147483647,-1,2147483647,-1,-1,2147483647,2147483647,-1,0,-1,-1,0,-1,0,-1,0,2147483647,2147483647,-1,0,2147483647,0,-1,0,-1,0,0,0,0,0,2147483647,-1,0,0,-1,0,0,2147483647,-1,0,2147483647,0,2147483647,2147483647,-1,0,-1,0,0,-1,0,0,0,0,-1,2147483647,0,0,-1,2147483647,0,2147483647,-1,0,2147483647,0,0,0,-1,2147483647,2147483647,-1,0,-1,0,2147483647,-1,-1,0,0,0,-1,2147483647,-1,-1,-1,2147483647,0,-1,0,0,-1,-1,0,0,-1,0,2147483647,0,0,-1,2147483647,-1,0,-1,-1,0,-1,-1,2147483647,0,-1,2147483647,2147483647,2147483647,2147483647,0,-1,-1,2147483647,2147483647,2147483647,0,2147483647},{0,-1,0,0,2147483647,2147483647,2147483647,0,2147483647,0,0,-1,2147483647,-1,-1,2147483647,2147483647,-1,0,0,2147483647,2147483647,0,-1,0,-1,0,-1,-1,-1,2147483647,-1,0,2147483647,-1,0,2147483647,-1,0,2147483647,0,-1,2147483647,-1,2147483647,-1,0,0,2147483647,-1,0,0,-1,2147483647,2147483647,0,-1,-1,2147483647,-1,-1,-1,2147483647,2147483647,-1,-1,2147483647,-1,-1,-1,2147483647,2147483647,-1,-1,-1,0,2147483647,0,0,-1,-1,2147483647,2147483647,-1,-1,2147483647,2147483647,2147483647,2147483647,-1,-1,-1,-1,0,0,2147483647,2147483647,0,-1,2147483647,-1,2147483647,2147483647,0,-1,0,2147483647,2147483647,-1,0,2147483647,0,0,2147483647,0,-1,0,-1,-1,0,-1,2147483647,-1,-1,2147483647,-1,0,2147483647,2147483647,-1,-1,0,2147483647,2147483647,0,-1,2147483647,0,0,2147483647,-1,-1,2147483647,2147483647,-1,2147483647,0,2147483647,-1,2147483647,2147483647,2147483647,0,-1,-1,2147483647,-1,0,-1,-1,2147483647,2147483647,2147483647,-1,-1,2147483647,2147483647,0,-1,-1,-1,0,-1,-1,-1,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,-1,2147483647,0,0,0,0,2147483647,2147483647,0,2147483647,2147483647,0,-1,2147483647,2147483647,0,0,-1,2147483647,0,0,-1,-1,0,2147483647,-1,-1,0,2147483647,2147483647,0,0,-1,-1,2147483647,0,-1,2147483647,-1,2147483647},{-1,2147483647,-1,0,2147483647,0,-1,2147483647,0,2147483647,-1,0,0,0,0,0,0,2147483647,0,2147483647,2147483647,2147483647,-1,-1,-1,0,-1,2147483647,-1,2147483647,-1,2147483647,0,2147483647,0,-1,2147483647,0,-1,-1,-1,-1,2147483647,-1,0,0,-1,-1,-1,-1,0,2147483647,-1,0,2147483647,-1,2147483647,2147483647,0,2147483647,-1,2147483647,0,2147483647,0,-1,2147483647,-1,2147483647,0,-1,0,-1,0,2147483647,0,0,2147483647,0,0,-1,2147483647,0,0,0,0,0,2147483647,2147483647,2147483647,-1,-1,-1,-1,2147483647,0,-1,-1,0,0,-1,-1,0,-1,-1,-1,0,2147483647,2147483647,-1,2147483647,-1,-1,0,0,-1,0,2147483647,-1,-1,0,0,0,-1,2147483647,-1,-1,0,-1,-1,-1,2147483647,2147483647,-1,-1,2147483647,-1,2147483647,-1,2147483647,-1,2147483647,2147483647,2147483647,-1,2147483647,0,0,-1,0,2147483647,0,-1,0,-1,0,0,-1,2147483647,0,0,-1,0,2147483647,2147483647,0,2147483647,-1,-1,0,2147483647,2147483647,-1,-1,0,2147483647,2147483647,-1,0,0,-1,0,0,-1,-1,0,-1,0,-1,2147483647,0,-1,0,2147483647,-1,-1,2147483647,2147483647,-1,-1,-1,2147483647,2147483647,0,0,-1,-1,-1,-1,0,2147483647,2147483647,-1,2147483647,-1,2147483647,2147483647,0,-1,-1,0},{0,-1,0,0,-1,-1,0,0,-1,-1,-1,-1,2147483647,2147483647,2147483647,0,-1,0,2147483647,2147483647,2147483647,0,2147483647,-1,-1,2147483647,0,2147483647,-1,-1,0,2147483647,2147483647,0,-1,2147483647,-1,0,-1,0,2147483647,0,2147483647,0,2147483647,-1,-1,2147483647,0,-1,2147483647,2147483647,-1,0,2147483647,0,2147483647,-1,-1,-1,-1,2147483647,2147483647,-1,2147483647,-1,0,-1,-1,0,-1,0,0,0,2147483647,-1,0,0,0,2147483647,0,2147483647,2147483647,0,-1,2147483647,2147483647,0,2147483647,0,2147483647,0,2147483647,-1,0,-1,0,2147483647,-1,2147483647,2147483647,0,2147483647,2147483647,0,0,2147483647,-1,-1,-1,-1,0,-1,0,0,0,-1,-1,0,0,0,0,-1,0,0,0,0,0,2147483647,0,0,2147483647,-1,-1,2147483647,0,-1,0,-1,-1,2147483647,2147483647,0,0,2147483647,0,2147483647,-1,-1,0,0,-1,-1,2147483647,0,-1,-1,0,-1,-1,0,0,0,-1,0,0,2147483647,2147483647,2147483647,0,2147483647,0,2147483647,-1,0,2147483647,0,2147483647,2147483647,0,-1,0,-1,2147483647,0,-1,2147483647,-1,-1,2147483647,-1,0,2147483647,0,2147483647,2147483647,-1,2147483647,-1,2147483647,-1,2147483647,-1,-1,0,0,0,-1,0,0,2147483647,2147483647,0,0,2147483647,0,2147483647,0,0,2147483647,2147483647},{-1,-1,-1,2147483647,2147483647,2147483647,0,2147483647,0,0,0,2147483647,-1,0,0,-1,-1,0,0,-1,2147483647,2147483647,-1,0,-1,0,0,-1,0,-1,0,2147483647,2147483647,2147483647,2147483647,-1,2147483647,-1,-1,2147483647,2147483647,0,0,0,0,0,-1,2147483647,2147483647,2147483647,2147483647,2147483647,0,0,2147483647,2147483647,2147483647,-1,2147483647,2147483647,-1,2147483647,0,2147483647,-1,-1,-1,-1,-1,-1,-1,2147483647,0,0,-1,-1,-1,2147483647,2147483647,-1,2147483647,2147483647,2147483647,0,0,0,0,-1,-1,-1,0,0,2147483647,2147483647,0,0,0,0,0,2147483647,2147483647,-1,2147483647,0,2147483647,0,0,0,-1,2147483647,0,2147483647,2147483647,0,0,-1,0,-1,-1,2147483647,0,-1,0,0,-1,2147483647,2147483647,2147483647,2147483647,0,0,0,0,-1,-1,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,-1,2147483647,0,-1,2147483647,0,-1,2147483647,-1,2147483647,2147483647,-1,-1,2147483647,0,0,2147483647,-1,2147483647,0,-1,2147483647,0,-1,-1,0,-1,2147483647,2147483647,2147483647,2147483647,0,-1,2147483647,2147483647,0,0,0,-1,-1,0,2147483647,-1,0,0,-1,-1,0,0,2147483647,2147483647,-1,-1,2147483647,2147483647,0,-1,2147483647,0,2147483647,-1,2147483647,-1,2147483647,2147483647,2147483647,0,2147483647,-1,-1,2147483647,-1,-1,0,-1,-1,0,-1,-1,2147483647},{0,0,-1,0,0,2147483647,-1,2147483647,2147483647,-1,2147483647,-1,-1,0,0,0,-1,0,0,-1,2147483647,0,-1,-1,0,-1,-1,0,0,-1,2147483647,-1,-1,-1,2147483647,2147483647,-1,2147483647,2147483647,0,-1,2147483647,-1,-1,-1,-1,-1,2147483647,2147483647,2147483647,0,0,-1,-1,-1,2147483647,2147483647,-1,-1,-1,2147483647,-1,2147483647,2147483647,2147483647,-1,0,2147483647,0,-1,2147483647,0,0,2147483647,-1,2147483647,-1,2147483647,0,-1,0,0,2147483647,-1,-1,-1,2147483647,0,0,-1,2147483647,-1,2147483647,0,0,2147483647,-1,0,0,2147483647,-1,0,2147483647,2147483647,0,-1,-1,-1,-1,0,0,2147483647,2147483647,2147483647,0,0,-1,-1,0,0,2147483647,0,0,-1,2147483647,0,2147483647,2147483647,2147483647,2147483647,0,2147483647,0,0,-1,2147483647,2147483647,-1,2147483647,0,-1,-1,-1,0,0,0,2147483647,2147483647,2147483647,-1,0,2147483647,-1,2147483647,0,2147483647,0,2147483647,0,2147483647,0,2147483647,-1,2147483647,0,-1,0,-1,0,-1,2147483647,2147483647,2147483647,-1,2147483647,-1,-1,2147483647,0,0,0,2147483647,-1,2147483647,-1,-1,0,0,-1,0,-1,2147483647,0,-1,0,0,0,2147483647,2147483647,0,-1,0,2147483647,2147483647,0,0,0,-1,0,0,2147483647,-1,-1,0,2147483647,0,0,-1,0,-1,-1},{2147483647,0,-1,2147483647,-1,-1,-1,-1,-1,2147483647,0,0,0,2147483647,2147483647,2147483647,2147483647,-1,-1,2147483647,0,0,-1,2147483647,-1,2147483647,2147483647,-1,0,0,0,-1,-1,2147483647,2147483647,0,0,-1,2147483647,-1,2147483647,2147483647,2147483647,0,-1,2147483647,-1,-1,0,2147483647,2147483647,2147483647,-1,2147483647,2147483647,2147483647,2147483647,2147483647,-1,2147483647,2147483647,2147483647,2147483647,0,-1,0,0,-1,0,0,-1,-1,-1,-1,-1,2147483647,2147483647,2147483647,0,0,0,2147483647,0,2147483647,0,0,-1,2147483647,0,-1,2147483647,2147483647,-1,-1,2147483647,2147483647,2147483647,2147483647,-1,-1,2147483647,2147483647,-1,0,2147483647,2147483647,2147483647,-1,0,2147483647,0,0,0,0,0,0,2147483647,0,0,-1,0,0,-1,0,2147483647,2147483647,0,-1,0,-1,0,2147483647,2147483647,0,0,2147483647,2147483647,-1,0,0,2147483647,2147483647,0,2147483647,-1,-1,2147483647,2147483647,-1,2147483647,2147483647,0,0,-1,-1,0,2147483647,0,-1,0,2147483647,2147483647,-1,0,-1,-1,0,0,2147483647,-1,0,0,2147483647,0,2147483647,2147483647,0,2147483647,2147483647,0,0,2147483647,0,-1,-1,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,-1,0,0,-1,-1,-1,-1,-1,0,0,2147483647,2147483647,0,0,2147483647,-1,0,-1,-1,0,0,0,2147483647,-1,-1,0,2147483647,0,-1,0},{2147483647,2147483647,-1,0,2147483647,0,2147483647,-1,-1,0,2147483647,-1,2147483647,-1,0,2147483647,2147483647,0,2147483647,2147483647,-1,0,-1,-1,-1,-1,2147483647,2147483647,0,-1,2147483647,2147483647,-1,0,2147483647,0,2147483647,0,-1,-1,2147483647,0,-1,0,-1,0,-1,0,0,2147483647,-1,-1,2147483647,-1,-1,0,0,-1,-1,2147483647,-1,0,2147483647,0,-1,-1,2147483647,2147483647,0,0,0,-1,-1,2147483647,-1,2147483647,-1,-1,-1,-1,0,-1,-1,-1,2147483647,0,2147483647,-1,-1,2147483647,2147483647,0,-1,0,0,2147483647,2147483647,2147483647,2147483647,2147483647,-1,2147483647,-1,0,-1,-1,-1,2147483647,2147483647,-1,2147483647,-1,-1,0,0,2147483647,0,0,-1,2147483647,-1,-1,2147483647,2147483647,0,0,2147483647,2147483647,-1,0,-1,2147483647,-1,2147483647,-1,0,2147483647,0,-1,2147483647,-1,2147483647,2147483647,2147483647,-1,-1,-1,2147483647,0,2147483647,2147483647,2147483647,0,-1,-1,0,2147483647,2147483647,0,0,-1,0,0,0,-1,0,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,0,2147483647,-1,0,2147483647,0,0,0,0,0,2147483647,0,2147483647,-1,0,-1,2147483647,2147483647,2147483647,2147483647,-1,2147483647,0,-1,-1,0,-1,0,0,0,-1,0,0,2147483647,2147483647,-1,-1,-1,2147483647,0,-1,0,-1,-1,-1,2147483647,0,0,2147483647},{2147483647,-1,0,-1,-1,0,2147483647,0,0,0,0,2147483647,2147483647,-1,0,2147483647,-1,0,-1,-1,2147483647,2147483647,0,-1,0,0,0,0,2147483647,2147483647,2147483647,-1,2147483647,2147483647,2147483647,0,0,-1,2147483647,2147483647,2147483647,2147483647,0,0,-1,-1,0,0,-1,0,-1,-1,2147483647,0,2147483647,2147483647,0,-1,2147483647,2147483647,-1,2147483647,2147483647,-1,2147483647,-1,0,2147483647,2147483647,-1,0,2147483647,2147483647,0,2147483647,0,2147483647,2147483647,2147483647,0,2147483647,2147483647,-1,0,2147483647,0,2147483647,0,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,0,0,0,0,-1,-1,-1,2147483647,-1,2147483647,-1,0,0,2147483647,0,2147483647,-1,0,2147483647,-1,0,0,0,-1,-1,-1,0,-1,0,0,2147483647,0,-1,0,2147483647,2147483647,2147483647,0,-1,-1,0,-1,-1,-1,-1,-1,0,2147483647,2147483647,0,-1,2147483647,0,-1,2147483647,0,-1,0,-1,-1,0,2147483647,2147483647,-1,0,2147483647,2147483647,-1,2147483647,2147483647,0,2147483647,-1,-1,2147483647,-1,0,0,-1,0,2147483647,0,2147483647,2147483647,2147483647,-1,2147483647,0,-1,2147483647,0,-1,0,-1,-1,2147483647,0,-1,0,0,-1,2147483647,-1,2147483647,-1,0,2147483647,2147483647,2147483647,2147483647,-1,-1,-1,-1,-1,0,-1,2147483647,0,2147483647,2147483647,0,-1,-1,2147483647,0,0},{2147483647,0,0,2147483647,2147483647,2147483647,-1,2147483647,2147483647,0,2147483647,2147483647,2147483647,0,2147483647,2147483647,0,2147483647,2147483647,2147483647,-1,0,-1,0,-1,-1,-1,2147483647,0,0,0,2147483647,-1,2147483647,0,2147483647,-1,2147483647,0,-1,0,0,0,2147483647,2147483647,0,0,0,-1,-1,2147483647,0,2147483647,-1,2147483647,0,-1,0,0,-1,0,0,2147483647,2147483647,2147483647,2147483647,-1,2147483647,0,-1,-1,0,0,2147483647,0,0,2147483647,0,0,-1,0,2147483647,0,2147483647,2147483647,0,0,2147483647,2147483647,0,0,0,0,0,0,2147483647,2147483647,0,0,-1,-1,-1,-1,2147483647,2147483647,-1,0,-1,2147483647,2147483647,-1,2147483647,0,2147483647,-1,2147483647,0,2147483647,2147483647,-1,2147483647,2147483647,0,-1,-1,0,2147483647,0,-1,0,2147483647,-1,0,2147483647,2147483647,2147483647,-1,-1,2147483647,-1,2147483647,-1,0,0,2147483647,0,0,2147483647,2147483647,-1,-1,0,2147483647,-1,-1,2147483647,0,0,0,2147483647,2147483647,2147483647,0,0,2147483647,-1,2147483647,0,-1,2147483647,0,0,0,0,0,-1,-1,0,-1,2147483647,-1,-1,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,0,0,-1,2147483647,2147483647,-1,2147483647,2147483647,2147483647,2147483647,0,2147483647,-1,2147483647,0,2147483647,-1,-1,2147483647,-1,0,0,2147483647,0,2147483647,2147483647,2147483647,0,2147483647,-1,0,-1,2147483647},{0,0,2147483647,-1,0,2147483647,2147483647,0,-1,0,-1,2147483647,0,0,0,0,-1,2147483647,2147483647,-1,-1,2147483647,0,2147483647,-1,2147483647,-1,-1,-1,-1,-1,0,2147483647,0,0,0,-1,-1,0,-1,0,2147483647,0,2147483647,0,0,2147483647,2147483647,0,0,2147483647,2147483647,2147483647,0,-1,0,2147483647,2147483647,2147483647,0,-1,0,0,0,2147483647,0,2147483647,-1,-1,-1,2147483647,2147483647,0,0,0,-1,0,2147483647,-1,0,-1,0,-1,2147483647,2147483647,0,2147483647,2147483647,-1,2147483647,0,2147483647,-1,0,0,0,-1,0,2147483647,0,0,-1,-1,0,-1,-1,0,0,-1,2147483647,-1,2147483647,-1,0,2147483647,2147483647,2147483647,-1,2147483647,2147483647,0,-1,-1,-1,2147483647,0,0,2147483647,-1,0,2147483647,2147483647,2147483647,0,2147483647,2147483647,0,2147483647,2147483647,2147483647,2147483647,0,0,0,-1,0,-1,0,-1,-1,0,0,0,-1,0,-1,-1,2147483647,0,-1,-1,-1,2147483647,2147483647,0,-1,-1,0,-1,-1,-1,-1,2147483647,0,2147483647,0,-1,2147483647,2147483647,-1,0,2147483647,0,-1,-1,2147483647,0,-1,0,2147483647,2147483647,0,-1,-1,-1,0,-1,-1,-1,0,2147483647,0,2147483647,-1,0,-1,-1,-1,-1,0,-1,2147483647,0,-1,0,-1,-1,-1,0,0,-1},{2147483647,-1,0,2147483647,2147483647,2147483647,2147483647,-1,2147483647,0,-1,0,0,2147483647,-1,2147483647,-1,0,2147483647,-1,-1,0,0,-1,0,-1,2147483647,0,-1,-1,0,-1,-1,0,-1,0,2147483647,0,-1,0,-1,0,0,0,2147483647,-1,2147483647,-1,2147483647,2147483647,2147483647,0,-1,0,2147483647,2147483647,-1,0,-1,2147483647,0,-1,0,0,2147483647,-1,-1,2147483647,-1,2147483647,-1,-1,0,0,2147483647,-1,2147483647,0,-1,0,0,-1,0,0,2147483647,0,0,0,2147483647,-1,0,0,-1,-1,0,0,-1,0,2147483647,2147483647,-1,0,2147483647,0,-1,2147483647,0,-1,-1,-1,0,0,-1,0,0,0,2147483647,2147483647,-1,-1,2147483647,2147483647,2147483647,-1,-1,2147483647,2147483647,2147483647,-1,2147483647,0,2147483647,-1,2147483647,2147483647,-1,0,-1,0,-1,2147483647,-1,0,-1,2147483647,0,-1,0,-1,0,2147483647,2147483647,0,2147483647,-1,0,2147483647,-1,0,-1,-1,-1,0,-1,-1,0,0,2147483647,0,-1,2147483647,0,-1,-1,2147483647,0,0,2147483647,0,0,2147483647,2147483647,0,2147483647,0,2147483647,2147483647,0,-1,0,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,2147483647,-1,0,0,0,2147483647,0,0,-1,2147483647,-1,0,0,0,0,2147483647},{2147483647,-1,0,0,-1,-1,-1,2147483647,0,2147483647,2147483647,-1,0,2147483647,0,-1,-1,-1,0,2147483647,0,0,2147483647,0,-1,0,-1,2147483647,0,-1,-1,2147483647,2147483647,0,-1,2147483647,-1,2147483647,2147483647,-1,-1,0,-1,0,0,-1,2147483647,2147483647,2147483647,-1,0,2147483647,-1,-1,2147483647,2147483647,0,2147483647,0,-1,0,0,2147483647,0,-1,-1,0,-1,2147483647,0,0,-1,0,-1,0,2147483647,0,0,-1,-1,2147483647,0,-1,0,-1,2147483647,0,0,-1,2147483647,2147483647,-1,-1,-1,0,-1,2147483647,0,2147483647,-1,0,-1,0,2147483647,-1,0,-1,2147483647,2147483647,2147483647,0,0,0,0,2147483647,2147483647,0,2147483647,0,0,0,0,2147483647,-1,0,0,-1,2147483647,2147483647,-1,0,2147483647,0,0,2147483647,0,-1,-1,-1,0,2147483647,2147483647,2147483647,0,2147483647,2147483647,-1,0,0,-1,-1,0,0,0,0,0,-1,2147483647,0,0,2147483647,2147483647,-1,0,2147483647,2147483647,0,-1,-1,-1,-1,-1,0,-1,-1,2147483647,0,2147483647,0,-1,2147483647,-1,0,0,0,-1,2147483647,-1,2147483647,2147483647,-1,-1,-1,2147483647,-1,-1,-1,-1,0,-1,-1,0,2147483647,0,2147483647,-1,0,-1,2147483647,-1,2147483647,0,0,2147483647,-1,-1,2147483647,-1,2147483647,-1,0},{-1,2147483647,2147483647,-1,-1,-1,0,2147483647,-1,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,0,0,0,-1,2147483647,-1,-1,2147483647,0,2147483647,2147483647,2147483647,2147483647,0,2147483647,-1,-1,0,-1,0,-1,0,0,0,-1,2147483647,0,2147483647,-1,2147483647,-1,2147483647,-1,-1,0,0,2147483647,0,2147483647,-1,2147483647,0,2147483647,-1,-1,2147483647,-1,2147483647,2147483647,2147483647,0,2147483647,2147483647,2147483647,2147483647,2147483647,0,2147483647,2147483647,-1,2147483647,0,-1,0,-1,-1,0,0,-1,0,0,2147483647,-1,-1,0,2147483647,0,-1,-1,2147483647,0,-1,-1,0,2147483647,2147483647,0,0,2147483647,2147483647,0,0,0,2147483647,-1,-1,2147483647,2147483647,-1,-1,2147483647,0,2147483647,-1,2147483647,-1,-1,2147483647,0,-1,2147483647,-1,0,2147483647,2147483647,2147483647,2147483647,-1,2147483647,-1,-1,-1,0,2147483647,-1,2147483647,0,2147483647,-1,-1,0,0,2147483647,0,0,-1,-1,-1,-1,2147483647,0,-1,0,-1,0,2147483647,0,0,0,2147483647,-1,0,-1,0,-1,2147483647,2147483647,2147483647,-1,2147483647,0,2147483647,-1,-1,2147483647,0,-1,-1,2147483647,0,0,0,0,2147483647,2147483647,0,0,-1,0,0,2147483647,-1,0,0,2147483647,2147483647,0,0,-1,2147483647,-1,0,0,0,0,2147483647,-1,0,2147483647,-1,2147483647,2147483647,0,0,0,-1},{0,2147483647,0,0,-1,0,-1,-1,2147483647,-1,0,-1,2147483647,-1,0,0,-1,0,0,-1,0,0,2147483647,0,-1,2147483647,-1,0,-1,-1,-1,-1,-1,0,0,-1,2147483647,0,-1,2147483647,-1,-1,2147483647,2147483647,-1,2147483647,0,2147483647,-1,0,0,0,2147483647,-1,-1,2147483647,0,0,2147483647,-1,-1,-1,-1,0,2147483647,-1,0,-1,0,2147483647,2147483647,-1,-1,-1,0,2147483647,-1,0,-1,-1,-1,-1,0,-1,-1,-1,0,2147483647,2147483647,0,2147483647,0,2147483647,0,2147483647,-1,-1,2147483647,2147483647,-1,-1,2147483647,2147483647,-1,0,2147483647,0,2147483647,2147483647,0,0,-1,2147483647,0,0,-1,2147483647,0,0,-1,2147483647,-1,0,-1,-1,0,-1,0,0,-1,-1,2147483647,0,0,0,-1,2147483647,2147483647,-1,0,2147483647,0,-1,2147483647,-1,0,0,2147483647,2147483647,0,0,2147483647,2147483647,-1,2147483647,2147483647,0,2147483647,2147483647,0,0,-1,2147483647,2147483647,2147483647,2147483647,2147483647,0,-1,0,2147483647,2147483647,2147483647,0,-1,0,-1,0,-1,0,0,0,0,0,-1,-1,-1,0,0,2147483647,2147483647,2147483647,0,2147483647,2147483647,-1,-1,2147483647,0,-1,0,2147483647,-1,0,2147483647,-1,0,2147483647,-1,-1,2147483647,0,-1,2147483647,-1,0,-1,2147483647,0,0,0},{0,-1,-1,0,2147483647,2147483647,-1,-1,2147483647,2147483647,-1,0,2147483647,-1,-1,2147483647,2147483647,2147483647,0,0,-1,0,0,0,-1,2147483647,2147483647,0,-1,-1,0,-1,2147483647,2147483647,0,0,-1,2147483647,-1,-1,2147483647,-1,-1,-1,0,-1,2147483647,-1,0,-1,-1,2147483647,0,-1,-1,-1,-1,-1,0,0,0,0,0,2147483647,-1,2147483647,0,2147483647,-1,-1,0,2147483647,0,-1,0,0,-1,0,0,2147483647,2147483647,0,0,-1,-1,-1,2147483647,0,2147483647,0,2147483647,0,2147483647,2147483647,0,-1,0,-1,-1,-1,0,0,-1,0,0,2147483647,-1,0,0,0,0,-1,-1,-1,-1,-1,2147483647,-1,0,0,-1,0,2147483647,0,-1,0,2147483647,2147483647,0,0,0,-1,-1,-1,0,-1,2147483647,2147483647,-1,2147483647,2147483647,-1,0,0,-1,-1,-1,2147483647,2147483647,0,0,-1,0,2147483647,-1,0,-1,-1,0,0,-1,2147483647,-1,-1,2147483647,2147483647,-1,0,0,0,-1,-1,0,2147483647,2147483647,0,0,0,0,2147483647,0,0,0,2147483647,2147483647,0,0,0,-1,0,-1,0,2147483647,2147483647,2147483647,-1,2147483647,0,0,-1,2147483647,-1,2147483647,0,0,0,2147483647,0,0,0,0,-1,-1,-1,0,2147483647,-1,0,0,0,0},{2147483647,0,-1,0,2147483647,-1,-1,-1,-1,-1,-1,2147483647,2147483647,-1,2147483647,-1,0,0,2147483647,0,0,0,-1,0,-1,-1,0,2147483647,0,-1,0,2147483647,-1,-1,2147483647,-1,2147483647,2147483647,-1,2147483647,0,-1,2147483647,2147483647,2147483647,0,0,0,2147483647,0,0,2147483647,0,-1,-1,2147483647,-1,2147483647,2147483647,2147483647,0,-1,-1,-1,-1,0,2147483647,-1,0,2147483647,0,2147483647,0,0,-1,2147483647,0,0,0,-1,-1,2147483647,0,2147483647,-1,-1,0,-1,-1,2147483647,-1,-1,0,2147483647,0,2147483647,-1,0,0,0,-1,0,-1,0,-1,0,-1,2147483647,-1,2147483647,-1,2147483647,-1,-1,2147483647,2147483647,0,-1,-1,0,0,2147483647,-1,-1,0,0,-1,0,0,0,-1,-1,2147483647,-1,2147483647,2147483647,2147483647,0,-1,2147483647,2147483647,-1,-1,2147483647,-1,0,2147483647,-1,2147483647,-1,2147483647,0,-1,0,0,0,-1,-1,2147483647,-1,2147483647,0,0,0,-1,0,2147483647,0,-1,0,2147483647,2147483647,-1,-1,2147483647,2147483647,0,2147483647,-1,-1,-1,-1,2147483647,-1,0,-1,2147483647,0,-1,0,0,2147483647,-1,-1,-1,0,2147483647,-1,0,0,-1,0,0,-1,0,0,0,0,2147483647,-1,0,-1,-1,0,0,2147483647,0,-1,2147483647,2147483647,2147483647},{2147483647,0,-1,-1,-1,0,-1,-1,-1,2147483647,-1,2147483647,-1,2147483647,2147483647,-1,2147483647,2147483647,0,-1,2147483647,0,2147483647,0,-1,0,2147483647,2147483647,-1,2147483647,2147483647,2147483647,-1,0,0,2147483647,0,0,0,2147483647,-1,0,0,-1,-1,0,0,-1,0,0,0,2147483647,2147483647,-1,-1,2147483647,-1,-1,-1,0,-1,0,2147483647,-1,2147483647,2147483647,0,0,2147483647,-1,2147483647,0,2147483647,-1,-1,0,2147483647,0,-1,0,-1,0,-1,2147483647,-1,-1,0,2147483647,0,2147483647,0,-1,2147483647,2147483647,2147483647,2147483647,2147483647,0,-1,2147483647,0,0,2147483647,2147483647,0,-1,0,0,-1,0,-1,2147483647,0,-1,0,-1,0,0,2147483647,-1,-1,0,-1,2147483647,0,2147483647,-1,-1,0,-1,-1,0,0,2147483647,0,2147483647,0,0,2147483647,2147483647,-1,0,2147483647,-1,-1,2147483647,2147483647,-1,0,-1,-1,2147483647,0,2147483647,0,0,0,-1,2147483647,-1,0,-1,2147483647,-1,-1,0,0,-1,0,0,0,0,2147483647,-1,0,-1,-1,0,-1,2147483647,2147483647,-1,-1,-1,0,-1,2147483647,-1,0,0,2147483647,2147483647,0,2147483647,0,0,-1,2147483647,2147483647,2147483647,2147483647,-1,-1,2147483647,0,-1,-1,2147483647,2147483647,2147483647,-1,-1,-1,2147483647,-1,-1,-1,-1,-1,-1,0},{-1,-1,-1,2147483647,-1,0,-1,0,-1,-1,-1,2147483647,2147483647,2147483647,0,2147483647,-1,2147483647,0,0,-1,-1,-1,-1,-1,-1,-1,0,0,0,2147483647,2147483647,-1,0,-1,0,0,2147483647,0,0,-1,-1,-1,-1,0,0,0,-1,0,-1,0,0,0,0,2147483647,2147483647,-1,2147483647,2147483647,2147483647,-1,0,-1,2147483647,2147483647,0,2147483647,-1,2147483647,0,0,2147483647,-1,2147483647,0,2147483647,2147483647,-1,2147483647,2147483647,0,0,-1,0,2147483647,-1,0,0,0,2147483647,-1,-1,-1,2147483647,0,0,0,2147483647,0,-1,-1,2147483647,2147483647,-1,0,-1,0,2147483647,2147483647,2147483647,0,0,2147483647,2147483647,2147483647,2147483647,0,0,2147483647,2147483647,-1,2147483647,2147483647,2147483647,-1,0,0,0,2147483647,-1,0,2147483647,0,-1,0,0,2147483647,2147483647,2147483647,-1,0,0,-1,2147483647,-1,0,-1,2147483647,-1,0,-1,2147483647,-1,-1,-1,0,-1,-1,-1,0,2147483647,2147483647,2147483647,-1,2147483647,0,2147483647,0,0,2147483647,-1,-1,-1,2147483647,-1,-1,0,-1,-1,-1,-1,2147483647,0,0,2147483647,-1,-1,-1,0,-1,-1,2147483647,0,2147483647,2147483647,2147483647,0,2147483647,0,0,2147483647,0,2147483647,2147483647,2147483647,-1,-1,2147483647,0,2147483647,-1,2147483647,2147483647,0,2147483647,2147483647,0,-1,-1,2147483647,0},{2147483647,0,-1,2147483647,-1,2147483647,0,-1,-1,0,2147483647,0,-1,0,-1,0,2147483647,0,2147483647,2147483647,0,2147483647,2147483647,-1,2147483647,-1,-1,0,-1,2147483647,2147483647,0,-1,0,0,2147483647,0,-1,2147483647,2147483647,0,2147483647,0,2147483647,0,0,0,-1,0,2147483647,-1,0,2147483647,-1,-1,-1,-1,-1,0,0,0,0,0,-1,2147483647,0,2147483647,2147483647,2147483647,0,-1,-1,2147483647,0,-1,0,-1,2147483647,2147483647,0,2147483647,2147483647,-1,-1,-1,2147483647,2147483647,-1,0,2147483647,-1,2147483647,0,-1,0,-1,-1,-1,-1,2147483647,2147483647,0,0,0,0,0,2147483647,0,0,2147483647,2147483647,-1,2147483647,0,-1,2147483647,-1,-1,-1,0,-1,0,-1,0,-1,0,-1,2147483647,2147483647,-1,0,0,0,-1,0,0,2147483647,-1,2147483647,-1,-1,-1,2147483647,-1,2147483647,-1,-1,2147483647,2147483647,-1,0,0,-1,-1,-1,-1,2147483647,-1,2147483647,2147483647,2147483647,0,2147483647,2147483647,0,0,-1,0,-1,2147483647,2147483647,-1,0,0,2147483647,-1,2147483647,0,-1,2147483647,2147483647,-1,-1,-1,-1,2147483647,2147483647,-1,0,-1,0,0,-1,2147483647,-1,-1,2147483647,2147483647,0,-1,0,2147483647,-1,2147483647,2147483647,2147483647,-1,2147483647,-1,-1,-1,0,2147483647,-1,-1,2147483647,-1,-1,-1,0,0},{2147483647,2147483647,0,2147483647,2147483647,0,0,-1,0,0,0,2147483647,-1,-1,2147483647,-1,2147483647,-1,2147483647,-1,2147483647,-1,-1,-1,-1,-1,-1,0,2147483647,2147483647,2147483647,2147483647,-1,0,2147483647,2147483647,-1,2147483647,0,-1,0,2147483647,-1,-1,0,-1,2147483647,2147483647,0,2147483647,-1,2147483647,0,2147483647,-1,-1,-1,0,2147483647,-1,2147483647,2147483647,0,0,2147483647,0,-1,-1,-1,2147483647,2147483647,2147483647,0,2147483647,2147483647,2147483647,0,2147483647,2147483647,-1,-1,-1,2147483647,2147483647,0,0,0,0,2147483647,0,-1,2147483647,0,2147483647,2147483647,0,2147483647,-1,2147483647,2147483647,-1,2147483647,-1,-1,0,2147483647,-1,-1,2147483647,0,-1,2147483647,0,-1,-1,-1,-1,-1,2147483647,-1,-1,0,-1,2147483647,2147483647,2147483647,0,2147483647,-1,0,2147483647,-1,2147483647,0,-1,-1,-1,-1,0,0,0,0,0,-1,0,-1,-1,0,2147483647,-1,2147483647,-1,2147483647,0,0,2147483647,0,2147483647,0,0,0,-1,0,-1,0,2147483647,2147483647,2147483647,-1,2147483647,-1,0,0,2147483647,0,-1,2147483647,0,-1,2147483647,2147483647,0,0,-1,0,-1,2147483647,0,-1,2147483647,2147483647,2147483647,-1,0,0,2147483647,0,2147483647,0,2147483647,0,-1,2147483647,0,0,0,2147483647,2147483647,-1,2147483647,0,-1,0,2147483647,-1,0,2147483647,2147483647,0,-1,2147483647},{2147483647,-1,0,-1,2147483647,0,0,-1,-1,0,-1,-1,-1,-1,-1,-1,2147483647,2147483647,0,2147483647,2147483647,-1,2147483647,0,2147483647,-1,2147483647,0,2147483647,0,0,0,-1,2147483647,0,0,0,-1,-1,2147483647,2147483647,-1,0,0,0,2147483647,2147483647,-1,-1,0,-1,2147483647,0,2147483647,2147483647,2147483647,0,0,2147483647,2147483647,-1,0,0,2147483647,0,2147483647,-1,2147483647,0,2147483647,-1,-1,0,2147483647,0,-1,2147483647,0,2147483647,-1,0,-1,2147483647,2147483647,-1,0,0,-1,2147483647,0,0,2147483647,0,2147483647,-1,-1,0,-1,-1,2147483647,2147483647,2147483647,-1,-1,-1,0,-1,0,-1,0,-1,2147483647,0,0,-1,0,-1,2147483647,0,0,0,0,0,-1,2147483647,0,2147483647,-1,-1,0,0,-1,2147483647,-1,2147483647,0,-1,0,0,2147483647,2147483647,2147483647,0,0,2147483647,0,-1,2147483647,0,-1,2147483647,0,2147483647,0,-1,2147483647,-1,0,-1,2147483647,2147483647,0,0,-1,-1,-1,0,2147483647,-1,2147483647,-1,-1,-1,0,0,0,2147483647,2147483647,0,0,0,0,-1,0,-1,2147483647,2147483647,-1,0,0,2147483647,2147483647,2147483647,0,-1,2147483647,0,-1,-1,2147483647,2147483647,2147483647,2147483647,0,0,0,0,2147483647,-1,-1,2147483647,-1,0,-1,2147483647,2147483647,2147483647,-1,0,-1,-1},{2147483647,-1,2147483647,2147483647,-1,-1,-1,2147483647,2147483647,0,2147483647,0,0,2147483647,-1,2147483647,-1,2147483647,0,0,-1,2147483647,-1,2147483647,0,0,2147483647,0,2147483647,0,-1,0,-1,-1,0,0,2147483647,0,-1,0,-1,-1,0,0,2147483647,2147483647,-1,2147483647,-1,2147483647,-1,2147483647,0,0,2147483647,2147483647,2147483647,0,2147483647,-1,2147483647,-1,0,0,-1,0,2147483647,2147483647,-1,-1,-1,2147483647,2147483647,0,0,-1,2147483647,0,2147483647,2147483647,0,-1,-1,0,2147483647,2147483647,-1,-1,2147483647,0,0,-1,-1,-1,2147483647,0,2147483647,0,0,-1,2147483647,2147483647,2147483647,0,2147483647,0,2147483647,2147483647,2147483647,-1,2147483647,2147483647,0,2147483647,0,-1,0,-1,0,0,0,0,2147483647,-1,-1,-1,-1,0,2147483647,0,0,0,-1,0,0,0,2147483647,-1,0,2147483647,-1,0,-1,0,0,2147483647,-1,0,2147483647,-1,-1,-1,2147483647,2147483647,-1,-1,0,0,2147483647,-1,0,0,0,2147483647,2147483647,-1,-1,-1,0,2147483647,0,0,-1,-1,-1,2147483647,0,2147483647,2147483647,2147483647,0,2147483647,-1,0,2147483647,0,-1,-1,0,0,0,-1,-1,0,0,-1,2147483647,-1,0,-1,2147483647,-1,-1,2147483647,2147483647,2147483647,2147483647,2147483647,0,0,0,0,0,2147483647,2147483647,2147483647,2147483647,-1,2147483647,2147483647,0},{0,2147483647,2147483647,2147483647,0,-1,0,2147483647,2147483647,-1,2147483647,0,0,2147483647,0,2147483647,2147483647,0,2147483647,0,2147483647,0,-1,0,0,0,0,0,2147483647,0,2147483647,2147483647,2147483647,-1,-1,2147483647,0,0,2147483647,-1,2147483647,-1,2147483647,0,-1,-1,0,-1,2147483647,0,2147483647,2147483647,-1,2147483647,0,2147483647,0,-1,0,0,-1,-1,2147483647,0,0,2147483647,2147483647,-1,-1,-1,-1,2147483647,0,0,2147483647,0,0,-1,-1,2147483647,0,-1,-1,-1,0,2147483647,-1,0,2147483647,2147483647,2147483647,-1,0,2147483647,0,-1,0,-1,-1,2147483647,0,-1,-1,0,-1,2147483647,2147483647,2147483647,0,2147483647,0,2147483647,2147483647,0,2147483647,2147483647,2147483647,0,2147483647,0,2147483647,2147483647,2147483647,-1,0,-1,0,-1,-1,0,-1,2147483647,0,-1,-1,0,2147483647,-1,0,2147483647,-1,2147483647,-1,0,2147483647,-1,0,-1,-1,0,2147483647,-1,0,2147483647,0,-1,2147483647,-1,0,0,0,2147483647,0,2147483647,-1,0,2147483647,2147483647,0,2147483647,-1,-1,2147483647,-1,2147483647,2147483647,0,0,2147483647,2147483647,-1,-1,-1,0,-1,-1,-1,0,0,-1,0,-1,2147483647,0,-1,2147483647,0,0,2147483647,-1,2147483647,-1,2147483647,2147483647,0,2147483647,-1,0,0,0,2147483647,2147483647,-1,2147483647,2147483647,-1,2147483647,2147483647,-1,2147483647,2147483647},{0,-1,0,0,0,-1,2147483647,0,-1,2147483647,0,0,-1,-1,2147483647,0,0,2147483647,2147483647,0,2147483647,-1,0,2147483647,-1,0,-1,2147483647,-1,2147483647,-1,0,2147483647,-1,-1,2147483647,2147483647,-1,2147483647,2147483647,-1,0,-1,0,0,-1,2147483647,-1,0,-1,-1,-1,-1,2147483647,-1,-1,0,0,2147483647,0,2147483647,2147483647,-1,-1,0,-1,-1,2147483647,2147483647,-1,-1,0,-1,-1,2147483647,0,2147483647,2147483647,2147483647,2147483647,-1,0,0,0,2147483647,-1,-1,0,-1,0,2147483647,0,-1,-1,-1,-1,-1,0,-1,-1,2147483647,2147483647,2147483647,2147483647,0,2147483647,2147483647,2147483647,0,0,0,2147483647,2147483647,2147483647,2147483647,0,0,0,-1,-1,0,0,0,0,0,-1,2147483647,-1,0,-1,2147483647,0,0,2147483647,0,2147483647,-1,0,-1,0,2147483647,0,-1,2147483647,2147483647,0,-1,0,-1,-1,2147483647,-1,2147483647,2147483647,2147483647,0,2147483647,2147483647,0,0,2147483647,-1,2147483647,-1,2147483647,2147483647,0,2147483647,2147483647,0,-1,-1,2147483647,0,0,-1,-1,0,2147483647,2147483647,2147483647,-1,2147483647,2147483647,-1,2147483647,2147483647,2147483647,2147483647,2147483647,0,-1,2147483647,0,2147483647,-1,2147483647,0,-1,2147483647,-1,2147483647,-1,-1,2147483647,2147483647,-1,-1,-1,0,0,0,2147483647,2147483647,-1,0,2147483647,2147483647,-1,2147483647,-1},{2147483647,-1,0,-1,-1,2147483647,0,-1,2147483647,-1,0,2147483647,-1,-1,2147483647,0,-1,-1,0,-1,-1,-1,0,2147483647,-1,2147483647,-1,2147483647,-1,0,2147483647,0,0,2147483647,2147483647,0,0,2147483647,2147483647,2147483647,-1,-1,0,2147483647,-1,-1,-1,2147483647,2147483647,-1,2147483647,2147483647,0,0,2147483647,0,2147483647,2147483647,0,0,-1,2147483647,0,-1,0,2147483647,0,2147483647,0,0,-1,0,2147483647,2147483647,0,2147483647,0,-1,-1,2147483647,-1,0,-1,2147483647,2147483647,-1,2147483647,2147483647,-1,2147483647,-1,2147483647,-1,-1,0,-1,0,0,0,2147483647,0,2147483647,-1,2147483647,-1,2147483647,-1,0,-1,2147483647,0,-1,0,2147483647,-1,-1,-1,2147483647,0,0,2147483647,0,2147483647,2147483647,-1,2147483647,2147483647,2147483647,2147483647,0,-1,-1,0,2147483647,-1,0,2147483647,2147483647,2147483647,0,2147483647,2147483647,0,-1,0,-1,-1,0,2147483647,2147483647,2147483647,0,2147483647,-1,0,-1,0,-1,-1,-1,0,2147483647,2147483647,-1,2147483647,0,2147483647,2147483647,0,0,0,-1,2147483647,2147483647,-1,2147483647,-1,-1,0,0,2147483647,0,-1,2147483647,2147483647,0,2147483647,2147483647,-1,2147483647,0,-1,2147483647,2147483647,-1,-1,2147483647,-1,0,0,2147483647,0,0,0,-1,-1,-1,0,0,2147483647,0,2147483647,-1,2147483647,0,-1,-1,-1,-1,2147483647,2147483647},{2147483647,-1,-1,2147483647,2147483647,0,-1,0,0,2147483647,0,-1,0,0,0,2147483647,2147483647,2147483647,2147483647,0,2147483647,-1,0,0,2147483647,0,-1,0,0,-1,0,0,0,-1,-1,-1,2147483647,0,2147483647,-1,0,0,2147483647,2147483647,0,-1,-1,2147483647,-1,-1,-1,2147483647,-1,-1,0,2147483647,-1,0,2147483647,0,-1,0,2147483647,0,2147483647,-1,-1,-1,-1,0,0,2147483647,-1,-1,-1,2147483647,2147483647,2147483647,0,-1,-1,0,-1,-1,2147483647,-1,-1,-1,0,-1,0,2147483647,-1,2147483647,-1,-1,2147483647,0,0,-1,0,-1,-1,0,-1,-1,2147483647,0,-1,0,-1,-1,0,-1,-1,-1,0,2147483647,-1,0,0,0,0,-1,-1,0,2147483647,2147483647,0,0,-1,2147483647,-1,0,-1,0,2147483647,0,0,2147483647,-1,-1,-1,-1,0,0,0,0,0,-1,-1,2147483647,0,2147483647,-1,2147483647,0,0,2147483647,2147483647,2147483647,-1,0,2147483647,0,0,-1,2147483647,-1,-1,0,2147483647,2147483647,2147483647,2147483647,-1,0,0,2147483647,2147483647,-1,0,2147483647,2147483647,2147483647,-1,2147483647,0,-1,2147483647,0,0,0,-1,-1,0,2147483647,-1,2147483647,-1,2147483647,-1,0,0,-1,-1,0,2147483647,-1,0,-1,0,2147483647,-1,0,2147483647,-1,-1,0,2147483647,2147483647},{-1,0,0,0,-1,-1,-1,-1,2147483647,0,-1,-1,2147483647,-1,0,2147483647,-1,2147483647,2147483647,-1,2147483647,-1,2147483647,2147483647,-1,0,2147483647,2147483647,2147483647,0,0,2147483647,2147483647,-1,-1,2147483647,2147483647,0,2147483647,2147483647,2147483647,2147483647,0,-1,-1,0,2147483647,-1,-1,2147483647,2147483647,2147483647,0,2147483647,0,0,2147483647,-1,2147483647,0,-1,-1,0,0,2147483647,0,0,0,0,-1,2147483647,-1,0,-1,0,0,0,2147483647,0,-1,2147483647,-1,-1,2147483647,0,2147483647,-1,0,-1,-1,0,-1,0,0,0,2147483647,2147483647,0,0,0,-1,-1,2147483647,-1,2147483647,0,0,2147483647,2147483647,0,-1,2147483647,0,-1,-1,2147483647,0,0,-1,2147483647,2147483647,0,-1,2147483647,2147483647,2147483647,0,0,0,0,0,-1,2147483647,-1,-1,0,-1,-1,0,-1,-1,2147483647,2147483647,0,-1,0,0,0,0,2147483647,2147483647,-1,0,0,2147483647,-1,2147483647,-1,-1,-1,0,0,0,2147483647,-1,-1,-1,2147483647,2147483647,2147483647,0,2147483647,-1,-1,2147483647,-1,0,-1,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,-1,0,-1,0,2147483647,-1,0,2147483647,0,2147483647,2147483647,0,0,-1,2147483647,0,0,-1,0,2147483647,0,2147483647,-1,0,0,2147483647,-1,0,-1,2147483647,-1,0,0,-1,2147483647,-1,-1},{2147483647,2147483647,-1,0,0,-1,2147483647,2147483647,-1,-1,2147483647,2147483647,-1,-1,2147483647,0,-1,0,0,-1,2147483647,0,-1,0,-1,-1,0,-1,2147483647,-1,-1,-1,0,0,2147483647,-1,2147483647,2147483647,0,2147483647,-1,-1,2147483647,-1,0,-1,-1,2147483647,-1,-1,-1,0,2147483647,2147483647,2147483647,-1,2147483647,-1,0,0,0,0,2147483647,-1,-1,0,2147483647,-1,-1,2147483647,-1,0,0,-1,2147483647,2147483647,0,0,2147483647,0,-1,2147483647,2147483647,0,2147483647,-1,0,-1,0,0,2147483647,0,-1,2147483647,-1,2147483647,2147483647,0,-1,-1,-1,-1,-1,2147483647,2147483647,0,0,0,-1,0,0,-1,2147483647,-1,-1,2147483647,2147483647,-1,0,0,2147483647,2147483647,0,0,0,-1,0,-1,0,2147483647,0,-1,0,2147483647,0,0,0,-1,0,2147483647,2147483647,-1,0,2147483647,-1,2147483647,2147483647,2147483647,-1,-1,0,0,2147483647,-1,0,-1,2147483647,2147483647,2147483647,2147483647,2147483647,-1,0,-1,2147483647,2147483647,-1,-1,2147483647,0,0,2147483647,0,2147483647,2147483647,2147483647,2147483647,-1,2147483647,0,0,2147483647,0,-1,0,2147483647,-1,0,0,2147483647,2147483647,0,2147483647,-1,-1,-1,2147483647,0,2147483647,-1,2147483647,2147483647,0,0,2147483647,0,0,-1,2147483647,2147483647,2147483647,-1,2147483647,-1,-1,0,-1,2147483647,2147483647,-1,-1},{2147483647,0,0,2147483647,2147483647,2147483647,2147483647,-1,-1,0,2147483647,2147483647,0,-1,0,2147483647,2147483647,2147483647,-1,2147483647,-1,0,-1,0,2147483647,0,0,-1,2147483647,-1,-1,0,-1,0,0,0,2147483647,-1,2147483647,2147483647,2147483647,0,0,2147483647,-1,2147483647,2147483647,2147483647,0,2147483647,-1,-1,0,0,0,-1,2147483647,2147483647,-1,0,-1,-1,-1,2147483647,-1,0,-1,0,-1,2147483647,0,2147483647,0,2147483647,2147483647,-1,0,-1,2147483647,0,0,2147483647,2147483647,-1,0,-1,2147483647,0,2147483647,-1,0,-1,2147483647,-1,0,-1,-1,0,2147483647,2147483647,2147483647,-1,2147483647,2147483647,0,2147483647,0,0,0,0,0,0,2147483647,-1,0,2147483647,-1,0,0,0,-1,-1,-1,0,-1,2147483647,0,-1,-1,2147483647,2147483647,2147483647,-1,-1,0,2147483647,0,-1,2147483647,2147483647,0,0,-1,0,0,-1,-1,-1,-1,-1,0,0,0,2147483647,-1,0,0,2147483647,0,0,0,0,-1,-1,2147483647,2147483647,-1,-1,0,-1,2147483647,2147483647,2147483647,0,2147483647,2147483647,2147483647,-1,0,2147483647,-1,-1,-1,2147483647,2147483647,2147483647,-1,0,2147483647,-1,2147483647,-1,-1,0,2147483647,2147483647,-1,2147483647,2147483647,2147483647,0,2147483647,2147483647,0,-1,-1,2147483647,2147483647,-1,-1,2147483647,-1,-1,0,2147483647,-1,-1,0,0,-1,-1},{-1,0,2147483647,0,-1,-1,-1,-1,2147483647,0,-1,0,-1,2147483647,2147483647,0,2147483647,2147483647,2147483647,0,2147483647,0,-1,2147483647,2147483647,2147483647,2147483647,0,-1,0,0,-1,2147483647,-1,0,0,2147483647,-1,0,-1,-1,-1,2147483647,0,0,-1,-1,2147483647,2147483647,2147483647,0,-1,2147483647,0,0,2147483647,2147483647,2147483647,0,2147483647,2147483647,-1,0,2147483647,-1,2147483647,-1,-1,-1,-1,2147483647,2147483647,-1,-1,-1,2147483647,2147483647,0,0,-1,2147483647,2147483647,2147483647,0,2147483647,2147483647,0,-1,0,-1,2147483647,0,-1,2147483647,-1,2147483647,2147483647,-1,-1,-1,-1,2147483647,0,-1,0,0,2147483647,0,2147483647,0,0,-1,2147483647,2147483647,-1,-1,2147483647,-1,0,-1,0,-1,0,2147483647,2147483647,2147483647,-1,0,0,0,2147483647,2147483647,-1,2147483647,0,0,2147483647,0,0,2147483647,2147483647,-1,2147483647,2147483647,-1,-1,-1,0,2147483647,0,-1,2147483647,0,-1,2147483647,-1,2147483647,2147483647,0,2147483647,0,-1,-1,2147483647,2147483647,2147483647,-1,-1,-1,0,2147483647,-1,0,2147483647,2147483647,0,-1,0,2147483647,0,0,0,2147483647,0,2147483647,0,2147483647,-1,2147483647,2147483647,0,0,2147483647,-1,-1,2147483647,0,0,2147483647,0,2147483647,0,-1,-1,-1,-1,2147483647,-1,2147483647,0,2147483647,-1,0,2147483647,0,-1,2147483647,0,2147483647,-1,-1},{0,-1,2147483647,-1,2147483647,0,0,-1,-1,-1,0,2147483647,-1,0,2147483647,2147483647,-1,2147483647,2147483647,2147483647,0,0,-1,-1,2147483647,0,0,-1,0,0,2147483647,-1,2147483647,0,2147483647,-1,0,2147483647,-1,2147483647,2147483647,-1,-1,-1,0,2147483647,-1,-1,2147483647,-1,2147483647,0,0,0,-1,-1,2147483647,0,-1,0,0,-1,0,0,-1,0,2147483647,0,-1,0,2147483647,2147483647,2147483647,-1,-1,0,2147483647,-1,0,0,2147483647,-1,2147483647,0,0,-1,-1,0,0,0,0,2147483647,-1,-1,0,-1,2147483647,2147483647,2147483647,0,2147483647,0,0,2147483647,0,2147483647,0,2147483647,-1,-1,0,0,-1,0,-1,-1,-1,2147483647,-1,-1,2147483647,0,2147483647,2147483647,-1,0,0,0,0,-1,2147483647,0,0,-1,0,-1,2147483647,2147483647,-1,-1,2147483647,-1,0,-1,0,0,0,2147483647,0,2147483647,-1,-1,-1,-1,0,-1,-1,0,-1,-1,0,-1,0,0,0,2147483647,2147483647,-1,0,0,2147483647,-1,-1,2147483647,2147483647,2147483647,0,0,0,2147483647,-1,2147483647,-1,2147483647,2147483647,2147483647,2147483647,0,0,2147483647,2147483647,-1,2147483647,2147483647,2147483647,0,-1,0,2147483647,2147483647,0,0,-1,2147483647,2147483647,0,-1,2147483647,-1,2147483647,2147483647,2147483647,-1,0,2147483647,2147483647,2147483647,2147483647,-1,2147483647,-1},{-1,-1,-1,-1,-1,0,0,-1,0,-1,2147483647,2147483647,2147483647,-1,0,2147483647,2147483647,-1,0,2147483647,2147483647,0,2147483647,2147483647,0,0,0,-1,2147483647,-1,0,2147483647,0,2147483647,0,2147483647,-1,0,-1,-1,0,2147483647,-1,2147483647,2147483647,2147483647,2147483647,0,2147483647,2147483647,-1,0,-1,2147483647,-1,2147483647,-1,2147483647,0,2147483647,0,-1,2147483647,2147483647,-1,2147483647,-1,2147483647,0,0,2147483647,2147483647,-1,2147483647,-1,0,0,2147483647,-1,0,0,-1,-1,2147483647,0,-1,0,2147483647,2147483647,0,0,-1,0,-1,2147483647,2147483647,0,0,-1,2147483647,-1,0,0,0,-1,0,2147483647,-1,0,0,-1,0,2147483647,0,0,-1,-1,-1,2147483647,-1,-1,0,0,-1,0,-1,0,0,-1,2147483647,0,-1,0,-1,2147483647,0,-1,-1,-1,0,0,0,0,2147483647,-1,0,-1,-1,-1,0,-1,-1,0,0,2147483647,-1,2147483647,2147483647,0,-1,-1,0,2147483647,2147483647,2147483647,0,0,0,0,-1,2147483647,0,0,-1,-1,-1,0,2147483647,-1,2147483647,-1,-1,2147483647,2147483647,0,-1,-1,0,0,-1,2147483647,0,-1,2147483647,0,-1,-1,0,2147483647,-1,0,2147483647,2147483647,0,0,-1,2147483647,2147483647,2147483647,2147483647,2147483647,-1,0,0,-1,0,-1,-1,-1,0,2147483647},{0,-1,-1,2147483647,0,2147483647,0,-1,-1,0,-1,-1,0,-1,0,2147483647,0,0,0,2147483647,2147483647,0,-1,-1,2147483647,2147483647,2147483647,0,-1,-1,2147483647,-1,2147483647,2147483647,-1,-1,2147483647,2147483647,0,2147483647,-1,0,-1,2147483647,0,2147483647,-1,-1,2147483647,2147483647,-1,2147483647,0,0,-1,0,2147483647,0,0,0,2147483647,0,0,-1,2147483647,0,-1,-1,-1,0,0,2147483647,-1,-1,0,0,-1,-1,-1,0,-1,-1,-1,-1,2147483647,0,0,2147483647,0,-1,2147483647,2147483647,-1,0,0,2147483647,-1,0,0,0,2147483647,0,2147483647,2147483647,0,0,-1,2147483647,0,-1,0,-1,0,2147483647,-1,0,2147483647,2147483647,2147483647,-1,2147483647,-1,2147483647,-1,-1,0,-1,-1,2147483647,-1,0,2147483647,0,2147483647,2147483647,0,0,-1,2147483647,2147483647,2147483647,-1,0,2147483647,2147483647,0,2147483647,0,2147483647,2147483647,2147483647,0,2147483647,0,-1,0,2147483647,2147483647,0,-1,0,0,-1,0,0,0,0,-1,-1,0,-1,0,2147483647,-1,0,2147483647,0,2147483647,-1,2147483647,2147483647,0,0,2147483647,2147483647,0,-1,0,0,2147483647,2147483647,2147483647,0,0,-1,2147483647,0,-1,2147483647,-1,2147483647,-1,-1,2147483647,2147483647,2147483647,-1,2147483647,2147483647,0,2147483647,2147483647,2147483647,0,-1,0,0,0,0,2147483647,2147483647},{0,-1,0,2147483647,0,0,0,-1,-1,-1,-1,-1,2147483647,2147483647,2147483647,-1,-1,0,2147483647,-1,0,2147483647,2147483647,0,-1,2147483647,2147483647,2147483647,2147483647,-1,0,0,0,2147483647,-1,2147483647,0,0,-1,2147483647,2147483647,2147483647,2147483647,2147483647,-1,0,2147483647,-1,-1,0,2147483647,-1,2147483647,2147483647,0,2147483647,2147483647,-1,0,2147483647,-1,-1,-1,0,0,2147483647,2147483647,0,0,-1,0,-1,0,-1,0,-1,-1,2147483647,2147483647,0,-1,2147483647,-1,-1,-1,0,-1,0,2147483647,-1,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,0,2147483647,2147483647,-1,0,0,2147483647,2147483647,0,0,-1,-1,2147483647,0,0,0,2147483647,0,-1,2147483647,2147483647,0,0,-1,2147483647,2147483647,-1,2147483647,2147483647,-1,-1,2147483647,-1,2147483647,0,-1,-1,-1,2147483647,2147483647,0,2147483647,-1,2147483647,-1,2147483647,0,0,0,2147483647,2147483647,2147483647,-1,-1,0,-1,2147483647,2147483647,-1,2147483647,2147483647,0,-1,0,2147483647,0,-1,2147483647,2147483647,2147483647,-1,0,-1,-1,0,0,-1,0,0,2147483647,0,2147483647,2147483647,2147483647,0,2147483647,-1,2147483647,-1,2147483647,2147483647,0,0,-1,2147483647,-1,2147483647,2147483647,0,-1,2147483647,2147483647,0,0,2147483647,2147483647,-1,-1,0,0,-1,2147483647,2147483647,0,-1,2147483647,0,-1,0,0,0,2147483647,2147483647,-1,-1},{-1,-1,0,2147483647,2147483647,2147483647,-1,2147483647,2147483647,-1,0,-1,-1,-1,0,-1,2147483647,2147483647,2147483647,2147483647,-1,0,-1,-1,2147483647,-1,0,2147483647,0,0,0,-1,-1,-1,2147483647,0,-1,2147483647,2147483647,2147483647,2147483647,-1,2147483647,0,-1,-1,-1,2147483647,0,-1,2147483647,-1,-1,2147483647,0,-1,0,2147483647,2147483647,2147483647,0,-1,0,0,0,-1,0,0,2147483647,-1,2147483647,2147483647,0,2147483647,0,-1,-1,0,-1,0,0,0,2147483647,0,0,2147483647,2147483647,-1,2147483647,2147483647,-1,0,2147483647,-1,-1,-1,0,2147483647,0,0,-1,-1,-1,2147483647,0,0,-1,2147483647,2147483647,-1,-1,0,2147483647,2147483647,2147483647,2147483647,2147483647,0,0,0,0,-1,-1,2147483647,0,0,-1,2147483647,-1,-1,2147483647,2147483647,0,-1,0,0,-1,0,-1,-1,0,2147483647,-1,0,-1,-1,2147483647,-1,-1,0,0,2147483647,-1,2147483647,2147483647,0,2147483647,0,0,2147483647,-1,2147483647,0,-1,2147483647,0,-1,0,-1,0,2147483647,0,-1,-1,0,-1,-1,0,0,-1,2147483647,2147483647,-1,-1,-1,2147483647,0,2147483647,0,0,2147483647,0,2147483647,-1,2147483647,0,2147483647,0,2147483647,-1,2147483647,0,-1,-1,0,-1,0,0,2147483647,-1,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,0,2147483647,-1,2147483647,2147483647},{0,2147483647,2147483647,0,2147483647,2147483647,-1,2147483647,2147483647,0,0,2147483647,0,-1,-1,-1,2147483647,2147483647,0,0,0,-1,2147483647,-1,0,2147483647,0,-1,0,-1,2147483647,0,-1,-1,-1,2147483647,-1,2147483647,2147483647,2147483647,0,0,-1,2147483647,-1,0,0,2147483647,-1,2147483647,2147483647,-1,-1,2147483647,2147483647,0,-1,0,-1,-1,2147483647,0,0,2147483647,0,0,-1,2147483647,2147483647,-1,-1,-1,2147483647,0,0,2147483647,-1,2147483647,2147483647,2147483647,0,2147483647,2147483647,0,0,-1,2147483647,2147483647,2147483647,2147483647,-1,0,0,0,-1,0,2147483647,0,-1,2147483647,-1,0,-1,2147483647,2147483647,0,2147483647,-1,-1,0,-1,0,-1,-1,2147483647,2147483647,0,-1,0,-1,-1,-1,0,-1,0,-1,-1,-1,0,0,-1,-1,2147483647,-1,-1,0,2147483647,0,-1,0,2147483647,0,2147483647,-1,2147483647,0,0,2147483647,2147483647,-1,0,2147483647,0,-1,0,0,-1,2147483647,2147483647,2147483647,-1,0,2147483647,2147483647,2147483647,-1,0,0,2147483647,-1,2147483647,-1,2147483647,-1,-1,-1,2147483647,0,0,2147483647,2147483647,0,0,2147483647,-1,0,2147483647,2147483647,0,-1,0,-1,0,2147483647,-1,-1,-1,0,0,0,0,-1,-1,0,2147483647,-1,2147483647,0,2147483647,0,-1,0,0,2147483647,-1,2147483647,0,0,0,-1,0},{-1,0,-1,2147483647,0,-1,2147483647,2147483647,0,-1,2147483647,2147483647,-1,2147483647,2147483647,-1,2147483647,0,-1,2147483647,0,2147483647,0,2147483647,-1,2147483647,-1,-1,2147483647,-1,2147483647,0,2147483647,2147483647,2147483647,-1,2147483647,-1,-1,-1,-1,2147483647,-1,2147483647,-1,0,-1,2147483647,2147483647,-1,-1,-1,0,-1,-1,0,0,-1,0,0,-1,-1,-1,2147483647,2147483647,2147483647,0,0,2147483647,-1,2147483647,-1,-1,-1,-1,2147483647,0,0,2147483647,2147483647,2147483647,0,2147483647,0,0,0,0,2147483647,-1,0,2147483647,-1,2147483647,0,2147483647,-1,0,-1,0,-1,0,2147483647,0,2147483647,2147483647,-1,-1,-1,-1,-1,-1,2147483647,2147483647,2147483647,2147483647,0,0,2147483647,2147483647,-1,-1,-1,-1,-1,0,-1,0,-1,2147483647,-1,0,2147483647,0,0,2147483647,-1,0,-1,0,-1,2147483647,0,-1,0,-1,0,-1,0,2147483647,2147483647,0,-1,-1,2147483647,0,0,2147483647,2147483647,0,0,-1,2147483647,2147483647,0,2147483647,-1,0,0,0,0,0,2147483647,-1,-1,0,2147483647,2147483647,-1,2147483647,-1,0,2147483647,-1,0,0,0,-1,-1,-1,0,-1,0,-1,2147483647,2147483647,2147483647,-1,0,2147483647,2147483647,0,-1,-1,2147483647,0,-1,-1,2147483647,2147483647,0,0,-1,-1,-1,2147483647,-1,2147483647,0,-1,2147483647,2147483647},{2147483647,-1,0,-1,0,0,-1,2147483647,0,-1,2147483647,0,0,-1,-1,2147483647,-1,0,-1,0,0,2147483647,0,2147483647,0,-1,2147483647,-1,0,2147483647,0,-1,-1,0,2147483647,0,2147483647,-1,-1,0,0,2147483647,2147483647,2147483647,0,0,0,0,0,-1,0,2147483647,-1,2147483647,0,0,2147483647,2147483647,0,0,0,0,2147483647,0,0,-1,-1,0,-1,2147483647,2147483647,2147483647,-1,-1,0,0,2147483647,0,2147483647,-1,-1,2147483647,-1,-1,0,0,-1,2147483647,2147483647,2147483647,-1,-1,2147483647,-1,-1,-1,2147483647,-1,-1,2147483647,-1,2147483647,0,0,2147483647,-1,0,0,0,0,-1,0,-1,-1,0,2147483647,2147483647,0,0,2147483647,-1,0,0,0,0,2147483647,-1,2147483647,0,0,-1,2147483647,0,-1,0,2147483647,2147483647,-1,0,0,0,0,-1,-1,-1,-1,0,-1,2147483647,-1,2147483647,-1,2147483647,0,-1,2147483647,2147483647,2147483647,0,0,-1,0,0,-1,0,2147483647,2147483647,2147483647,2147483647,0,0,0,2147483647,0,-1,0,-1,-1,-1,0,2147483647,2147483647,2147483647,-1,2147483647,0,-1,-1,0,-1,0,0,-1,0,2147483647,-1,2147483647,2147483647,-1,2147483647,0,0,-1,-1,2147483647,2147483647,2147483647,2147483647,-1,2147483647,0,0,2147483647,-1,0,2147483647,2147483647,2147483647,-1,2147483647,0},{-1,-1,-1,2147483647,-1,2147483647,0,-1,0,0,0,0,0,2147483647,2147483647,0,2147483647,0,-1,2147483647,0,0,-1,-1,2147483647,2147483647,0,0,0,-1,0,-1,-1,0,0,2147483647,-1,2147483647,0,0,2147483647,-1,-1,2147483647,-1,-1,0,2147483647,-1,0,2147483647,2147483647,2147483647,-1,2147483647,-1,2147483647,2147483647,2147483647,2147483647,0,0,-1,-1,-1,2147483647,0,2147483647,2147483647,2147483647,0,-1,0,0,0,2147483647,2147483647,0,0,0,2147483647,2147483647,2147483647,-1,2147483647,-1,-1,0,-1,2147483647,-1,-1,2147483647,2147483647,2147483647,2147483647,0,-1,2147483647,-1,-1,2147483647,0,2147483647,2147483647,-1,-1,0,0,-1,0,-1,0,0,-1,2147483647,0,2147483647,-1,0,0,-1,-1,-1,2147483647,-1,-1,0,-1,-1,-1,-1,-1,-1,0,0,-1,-1,-1,-1,2147483647,0,2147483647,2147483647,2147483647,-1,-1,0,2147483647,0,-1,0,-1,-1,-1,0,0,0,2147483647,0,0,2147483647,0,2147483647,0,0,-1,0,-1,2147483647,-1,-1,2147483647,0,-1,-1,2147483647,0,-1,2147483647,2147483647,-1,2147483647,2147483647,0,-1,0,0,-1,0,-1,-1,-1,2147483647,-1,0,2147483647,0,2147483647,2147483647,0,2147483647,2147483647,-1,2147483647,0,-1,-1,2147483647,0,0,0,2147483647,2147483647,-1,-1,0,2147483647,0,-1,2147483647},{-1,2147483647,-1,0,-1,0,0,-1,2147483647,0,-1,-1,0,-1,0,-1,0,-1,2147483647,2147483647,0,0,-1,2147483647,-1,0,2147483647,-1,-1,0,-1,0,-1,2147483647,-1,2147483647,-1,-1,0,0,2147483647,-1,-1,-1,2147483647,0,-1,-1,0,-1,2147483647,-1,-1,-1,2147483647,-1,-1,0,-1,0,2147483647,2147483647,2147483647,0,-1,0,2147483647,0,2147483647,-1,2147483647,-1,-1,2147483647,0,-1,0,-1,0,-1,-1,-1,-1,-1,0,2147483647,-1,-1,2147483647,2147483647,2147483647,0,2147483647,2147483647,-1,2147483647,2147483647,2147483647,0,-1,-1,-1,2147483647,0,2147483647,-1,-1,-1,0,2147483647,0,2147483647,-1,0,2147483647,0,-1,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,0,0,-1,-1,-1,0,0,2147483647,-1,-1,-1,0,-1,2147483647,2147483647,-1,0,0,0,-1,2147483647,-1,-1,-1,0,2147483647,2147483647,-1,0,-1,-1,-1,0,2147483647,2147483647,-1,-1,2147483647,-1,-1,2147483647,0,0,-1,-1,-1,0,2147483647,0,2147483647,2147483647,2147483647,-1,0,2147483647,2147483647,2147483647,-1,0,0,-1,-1,2147483647,0,-1,2147483647,2147483647,0,0,0,-1,-1,-1,2147483647,0,2147483647,0,2147483647,0,0,0,0,-1,-1,0,-1,0,2147483647,-1,2147483647,2147483647},{0,2147483647,2147483647,-1,0,-1,2147483647,2147483647,0,-1,0,-1,-1,0,-1,-1,2147483647,-1,2147483647,0,2147483647,0,0,0,0,0,0,2147483647,0,0,-1,-1,0,2147483647,0,2147483647,0,0,-1,2147483647,2147483647,-1,0,0,-1,0,0,2147483647,0,2147483647,0,2147483647,-1,0,2147483647,-1,-1,-1,2147483647,-1,0,0,-1,0,0,0,2147483647,2147483647,0,-1,0,2147483647,0,0,-1,-1,-1,2147483647,2147483647,-1,-1,-1,-1,2147483647,2147483647,2147483647,-1,2147483647,-1,-1,-1,2147483647,-1,2147483647,-1,0,-1,-1,2147483647,2147483647,2147483647,-1,0,2147483647,-1,2147483647,2147483647,0,0,-1,0,-1,0,-1,0,0,0,2147483647,0,2147483647,-1,2147483647,2147483647,-1,0,2147483647,0,2147483647,2147483647,-1,0,-1,0,-1,2147483647,0,2147483647,0,0,0,-1,-1,-1,0,2147483647,2147483647,2147483647,-1,-1,0,2147483647,-1,2147483647,0,-1,-1,0,2147483647,-1,2147483647,-1,0,0,0,-1,2147483647,0,-1,2147483647,0,-1,2147483647,-1,0,-1,2147483647,-1,-1,-1,-1,2147483647,0,-1,-1,2147483647,2147483647,0,0,2147483647,0,0,-1,2147483647,2147483647,0,-1,2147483647,2147483647,-1,2147483647,-1,2147483647,0,2147483647,-1,-1,-1,-1,2147483647,-1,2147483647,2147483647,-1,2147483647,0,2147483647,2147483647,0,0,2147483647,0},{2147483647,-1,2147483647,2147483647,0,0,0,2147483647,0,0,2147483647,0,-1,2147483647,0,-1,-1,0,2147483647,-1,-1,-1,-1,-1,-1,0,2147483647,-1,2147483647,-1,0,0,-1,0,-1,0,-1,2147483647,0,0,0,-1,0,0,0,0,2147483647,0,-1,0,-1,0,0,-1,-1,2147483647,2147483647,0,2147483647,2147483647,2147483647,0,-1,0,2147483647,0,-1,0,2147483647,-1,0,-1,2147483647,-1,0,-1,2147483647,2147483647,0,0,-1,2147483647,2147483647,2147483647,0,2147483647,0,-1,0,2147483647,-1,0,-1,-1,2147483647,2147483647,-1,2147483647,0,0,2147483647,-1,0,2147483647,-1,0,2147483647,2147483647,0,0,2147483647,0,-1,2147483647,-1,0,0,2147483647,2147483647,-1,2147483647,2147483647,-1,0,-1,0,-1,-1,0,0,2147483647,0,-1,-1,2147483647,2147483647,-1,2147483647,-1,2147483647,2147483647,-1,-1,-1,0,0,2147483647,0,0,2147483647,0,-1,-1,0,0,0,-1,0,0,2147483647,-1,-1,-1,2147483647,2147483647,-1,2147483647,2147483647,0,0,0,2147483647,0,0,-1,-1,2147483647,2147483647,0,0,0,0,0,0,-1,2147483647,2147483647,2147483647,2147483647,0,0,0,2147483647,0,0,0,-1,0,2147483647,-1,2147483647,-1,-1,2147483647,-1,2147483647,2147483647,0,0,0,2147483647,-1,-1,-1,0,0,-1,0,-1,0,0},{-1,0,2147483647,2147483647,2147483647,0,2147483647,2147483647,0,0,0,0,0,-1,-1,-1,0,-1,-1,0,-1,0,-1,-1,-1,-1,-1,2147483647,0,0,0,0,-1,2147483647,-1,0,-1,-1,-1,-1,0,-1,0,2147483647,0,2147483647,0,-1,0,2147483647,0,2147483647,-1,2147483647,0,-1,0,2147483647,0,0,2147483647,2147483647,2147483647,2147483647,0,-1,2147483647,-1,0,-1,-1,0,2147483647,-1,0,-1,2147483647,2147483647,0,2147483647,2147483647,-1,0,2147483647,-1,0,-1,2147483647,2147483647,0,-1,0,0,0,2147483647,-1,-1,0,0,0,-1,2147483647,-1,2147483647,0,0,-1,-1,-1,-1,0,-1,2147483647,-1,2147483647,-1,2147483647,0,2147483647,2147483647,2147483647,2147483647,0,-1,2147483647,2147483647,0,0,0,0,0,0,-1,-1,-1,2147483647,2147483647,2147483647,0,-1,-1,-1,2147483647,0,2147483647,0,-1,2147483647,-1,2147483647,2147483647,2147483647,2147483647,-1,2147483647,0,-1,-1,-1,0,0,2147483647,2147483647,2147483647,-1,0,0,-1,2147483647,2147483647,2147483647,-1,2147483647,2147483647,2147483647,-1,2147483647,2147483647,0,0,2147483647,0,0,-1,0,-1,2147483647,-1,2147483647,-1,-1,0,0,0,2147483647,2147483647,0,-1,-1,0,0,0,2147483647,0,0,0,0,0,-1,0,2147483647,-1,2147483647,-1,0,2147483647,0,-1,-1,2147483647,-1},{0,-1,0,2147483647,0,-1,-1,2147483647,2147483647,0,0,2147483647,0,2147483647,2147483647,-1,2147483647,0,-1,-1,2147483647,2147483647,-1,-1,-1,0,-1,2147483647,-1,2147483647,2147483647,-1,-1,0,0,-1,-1,-1,-1,0,0,-1,0,-1,-1,-1,-1,2147483647,-1,2147483647,-1,2147483647,2147483647,0,-1,2147483647,2147483647,2147483647,2147483647,0,0,0,0,-1,0,0,0,0,2147483647,2147483647,0,2147483647,-1,-1,-1,-1,-1,-1,0,2147483647,2147483647,2147483647,2147483647,2147483647,-1,-1,0,-1,0,0,-1,2147483647,-1,-1,-1,-1,2147483647,0,-1,2147483647,2147483647,0,2147483647,-1,-1,-1,0,2147483647,-1,-1,2147483647,2147483647,0,2147483647,-1,2147483647,2147483647,2147483647,-1,-1,2147483647,-1,0,-1,2147483647,2147483647,2147483647,-1,0,2147483647,2147483647,-1,0,-1,-1,2147483647,-1,2147483647,2147483647,0,-1,0,-1,2147483647,-1,2147483647,2147483647,2147483647,0,-1,0,2147483647,0,2147483647,-1,0,-1,-1,-1,-1,2147483647,-1,2147483647,-1,-1,0,0,2147483647,-1,2147483647,0,2147483647,-1,2147483647,0,2147483647,-1,2147483647,-1,-1,-1,-1,2147483647,0,0,0,-1,2147483647,0,0,2147483647,0,0,-1,2147483647,0,0,0,-1,0,0,-1,2147483647,0,-1,0,0,-1,0,2147483647,2147483647,-1,-1,2147483647,2147483647,2147483647,-1,2147483647,-1,0,-1},{2147483647,-1,-1,-1,0,0,0,-1,0,2147483647,-1,-1,2147483647,2147483647,-1,0,2147483647,2147483647,-1,2147483647,2147483647,0,-1,2147483647,0,2147483647,-1,-1,-1,0,-1,2147483647,2147483647,0,0,2147483647,0,-1,0,-1,-1,0,0,2147483647,-1,2147483647,2147483647,-1,2147483647,-1,0,2147483647,2147483647,2147483647,-1,2147483647,0,-1,2147483647,2147483647,0,2147483647,-1,0,-1,0,0,-1,2147483647,0,0,-1,-1,-1,-1,-1,-1,2147483647,0,0,2147483647,-1,2147483647,0,-1,2147483647,0,-1,0,0,2147483647,2147483647,2147483647,2147483647,-1,0,-1,2147483647,-1,0,0,2147483647,2147483647,-1,-1,2147483647,-1,0,2147483647,0,2147483647,-1,-1,-1,0,-1,2147483647,-1,2147483647,0,0,0,0,0,2147483647,2147483647,0,2147483647,2147483647,0,2147483647,0,-1,2147483647,0,-1,0,0,0,-1,0,-1,0,0,2147483647,2147483647,-1,-1,2147483647,0,2147483647,-1,2147483647,-1,2147483647,0,2147483647,0,0,-1,2147483647,0,2147483647,-1,0,0,0,2147483647,2147483647,0,2147483647,0,0,-1,-1,0,0,0,0,0,-1,-1,2147483647,-1,-1,0,-1,-1,2147483647,0,0,0,2147483647,2147483647,2147483647,-1,2147483647,-1,-1,-1,0,0,0,2147483647,0,2147483647,2147483647,0,0,2147483647,2147483647,0,-1,-1,0,-1,2147483647,-1,2147483647,2147483647,0},{-1,-1,0,2147483647,-1,2147483647,-1,0,0,0,2147483647,2147483647,0,0,2147483647,-1,2147483647,2147483647,0,2147483647,2147483647,-1,2147483647,0,-1,0,2147483647,0,0,2147483647,0,2147483647,-1,0,0,2147483647,2147483647,0,0,2147483647,2147483647,2147483647,-1,-1,2147483647,-1,2147483647,-1,2147483647,0,-1,0,-1,0,-1,-1,0,2147483647,0,2147483647,2147483647,0,2147483647,-1,-1,0,0,2147483647,2147483647,0,-1,-1,0,-1,0,0,0,0,0,-1,0,2147483647,0,2147483647,2147483647,-1,-1,-1,0,0,2147483647,2147483647,2147483647,0,0,0,2147483647,2147483647,0,2147483647,-1,2147483647,0,2147483647,2147483647,0,0,2147483647,0,-1,-1,2147483647,-1,0,0,0,2147483647,-1,0,0,2147483647,-1,0,2147483647,-1,2147483647,2147483647,0,0,0,0,2147483647,0,2147483647,0,0,0,0,-1,-1,0,0,2147483647,2147483647,2147483647,-1,-1,2147483647,0,2147483647,2147483647,0,0,2147483647,2147483647,2147483647,2147483647,-1,2147483647,0,2147483647,-1,2147483647,2147483647,0,0,-1,2147483647,2147483647,2147483647,2147483647,2147483647,-1,0,0,-1,-1,2147483647,2147483647,2147483647,2147483647,2147483647,-1,-1,-1,-1,0,2147483647,0,2147483647,0,2147483647,-1,2147483647,-1,2147483647,2147483647,2147483647,2147483647,0,-1,0,0,2147483647,0,-1,0,0,0,2147483647,2147483647,-1,2147483647,-1,-1,0,-1,2147483647,0,-1,-1},{-1,2147483647,2147483647,0,-1,-1,2147483647,2147483647,-1,-1,-1,-1,0,2147483647,2147483647,-1,0,-1,0,-1,2147483647,2147483647,2147483647,0,2147483647,-1,0,-1,-1,2147483647,0,2147483647,-1,2147483647,2147483647,2147483647,2147483647,0,2147483647,2147483647,0,-1,0,-1,2147483647,2147483647,0,0,0,2147483647,0,-1,0,-1,-1,2147483647,0,2147483647,0,2147483647,-1,0,2147483647,-1,-1,-1,2147483647,2147483647,-1,0,2147483647,-1,0,0,2147483647,2147483647,2147483647,0,-1,0,2147483647,2147483647,-1,2147483647,0,0,-1,2147483647,-1,2147483647,-1,-1,-1,0,-1,-1,-1,-1,2147483647,2147483647,-1,0,2147483647,2147483647,0,0,2147483647,0,0,2147483647,0,2147483647,0,0,-1,0,0,2147483647,-1,0,2147483647,0,-1,-1,-1,-1,-1,0,-1,2147483647,2147483647,2147483647,-1,0,0,-1,2147483647,-1,2147483647,2147483647,2147483647,2147483647,-1,0,0,2147483647,0,-1,0,2147483647,2147483647,2147483647,0,-1,0,-1,2147483647,2147483647,2147483647,-1,0,0,-1,-1,-1,2147483647,-1,0,2147483647,0,-1,-1,2147483647,-1,2147483647,-1,2147483647,0,-1,2147483647,2147483647,-1,2147483647,-1,-1,0,-1,-1,-1,2147483647,-1,0,-1,-1,2147483647,-1,0,0,0,0,2147483647,0,2147483647,2147483647,0,-1,0,-1,2147483647,0,0,2147483647,-1,2147483647,0,0,2147483647,2147483647,-1,0,0},{-1,0,0,0,0,2147483647,2147483647,0,-1,2147483647,0,-1,-1,2147483647,-1,2147483647,0,0,0,0,0,-1,-1,0,0,-1,-1,0,0,2147483647,2147483647,0,-1,-1,2147483647,-1,2147483647,0,2147483647,2147483647,2147483647,0,0,-1,2147483647,0,-1,2147483647,0,2147483647,-1,2147483647,-1,-1,0,-1,2147483647,-1,-1,2147483647,2147483647,0,2147483647,0,-1,2147483647,-1,2147483647,0,2147483647,0,0,0,2147483647,-1,0,2147483647,0,2147483647,-1,0,2147483647,0,-1,-1,-1,2147483647,2147483647,0,0,0,-1,-1,2147483647,0,0,-1,2147483647,2147483647,0,0,0,0,-1,-1,-1,2147483647,2147483647,0,0,2147483647,-1,2147483647,2147483647,-1,-1,-1,-1,-1,0,0,2147483647,-1,-1,0,0,2147483647,-1,-1,-1,0,0,2147483647,2147483647,2147483647,0,2147483647,2147483647,0,0,-1,-1,-1,2147483647,-1,2147483647,2147483647,-1,-1,0,-1,2147483647,2147483647,-1,2147483647,0,0,0,-1,-1,2147483647,-1,0,2147483647,-1,0,0,-1,-1,2147483647,-1,-1,2147483647,-1,-1,0,0,2147483647,-1,0,2147483647,2147483647,-1,-1,2147483647,0,2147483647,2147483647,0,2147483647,0,-1,0,0,0,0,-1,2147483647,0,0,0,0,-1,0,2147483647,0,2147483647,-1,2147483647,2147483647,0,0,-1,-1,-1,-1,0,0,0,-1,0},{2147483647,2147483647,-1,-1,2147483647,2147483647,0,2147483647,-1,-1,2147483647,-1,-1,-1,0,-1,0,2147483647,2147483647,0,2147483647,0,2147483647,0,-1,2147483647,0,2147483647,-1,2147483647,2147483647,-1,-1,2147483647,2147483647,-1,0,0,-1,2147483647,0,2147483647,2147483647,0,0,-1,-1,2147483647,2147483647,0,2147483647,-1,2147483647,-1,2147483647,2147483647,0,2147483647,0,2147483647,2147483647,-1,-1,2147483647,0,0,0,2147483647,-1,-1,2147483647,2147483647,2147483647,-1,2147483647,2147483647,-1,-1,-1,-1,2147483647,-1,2147483647,-1,-1,-1,0,0,-1,0,2147483647,-1,2147483647,0,-1,0,2147483647,2147483647,2147483647,0,0,0,-1,2147483647,-1,0,0,0,0,0,-1,-1,-1,0,0,0,0,-1,0,0,-1,0,0,-1,2147483647,0,-1,0,2147483647,0,-1,-1,0,0,2147483647,-1,-1,0,-1,2147483647,0,0,2147483647,-1,2147483647,-1,0,-1,2147483647,0,-1,-1,0,2147483647,2147483647,2147483647,0,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,0,2147483647,2147483647,2147483647,-1,2147483647,0,0,0,0,0,-1,0,-1,2147483647,2147483647,0,0,-1,2147483647,0,2147483647,2147483647,-1,-1,-1,-1,-1,-1,0,-1,2147483647,0,-1,2147483647,-1,2147483647,2147483647,0,-1,0,2147483647,-1,-1,0,2147483647,2147483647,-1,2147483647,2147483647,-1,2147483647,2147483647,0,0,2147483647,2147483647},{2147483647,2147483647,-1,-1,-1,-1,2147483647,2147483647,2147483647,0,-1,0,0,0,2147483647,0,-1,-1,-1,2147483647,2147483647,2147483647,0,0,2147483647,0,0,2147483647,0,2147483647,2147483647,-1,-1,2147483647,2147483647,-1,0,-1,-1,-1,2147483647,0,-1,0,0,0,0,2147483647,-1,2147483647,0,2147483647,2147483647,0,2147483647,-1,0,-1,0,2147483647,-1,-1,2147483647,0,2147483647,2147483647,2147483647,2147483647,2147483647,-1,2147483647,-1,2147483647,2147483647,2147483647,0,0,0,0,2147483647,0,0,0,2147483647,0,0,0,2147483647,2147483647,-1,-1,0,0,0,0,0,0,2147483647,0,2147483647,2147483647,0,0,-1,0,-1,2147483647,2147483647,0,0,-1,-1,0,2147483647,2147483647,-1,2147483647,2147483647,-1,0,2147483647,-1,-1,0,-1,2147483647,0,0,0,2147483647,-1,2147483647,-1,0,-1,-1,0,2147483647,-1,2147483647,2147483647,0,2147483647,-1,0,0,0,2147483647,2147483647,2147483647,2147483647,-1,-1,2147483647,0,2147483647,0,-1,0,0,2147483647,-1,-1,-1,0,2147483647,-1,0,2147483647,-1,2147483647,2147483647,-1,-1,0,-1,0,-1,0,0,0,2147483647,-1,2147483647,0,0,-1,-1,-1,0,0,0,2147483647,2147483647,0,2147483647,0,-1,-1,0,2147483647,2147483647,2147483647,2147483647,0,2147483647,0,0,2147483647,2147483647,2147483647,-1,2147483647,2147483647,0,-1,0,0,0,2147483647,0},{2147483647,-1,-1,-1,2147483647,-1,2147483647,-1,-1,2147483647,0,-1,0,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,0,0,0,0,2147483647,0,0,0,2147483647,2147483647,0,2147483647,-1,0,-1,0,0,-1,2147483647,0,-1,0,0,2147483647,0,-1,2147483647,2147483647,2147483647,2147483647,-1,2147483647,0,-1,0,-1,0,-1,2147483647,-1,0,-1,0,0,0,2147483647,-1,2147483647,0,0,-1,0,0,0,-1,2147483647,0,-1,-1,0,0,2147483647,-1,0,0,-1,-1,-1,2147483647,0,2147483647,2147483647,0,2147483647,0,-1,0,-1,2147483647,-1,0,-1,2147483647,0,0,2147483647,0,-1,2147483647,2147483647,2147483647,0,0,2147483647,0,-1,-1,-1,2147483647,-1,2147483647,2147483647,0,2147483647,0,-1,2147483647,2147483647,0,2147483647,-1,-1,0,-1,0,2147483647,0,-1,2147483647,2147483647,2147483647,-1,2147483647,0,0,0,-1,2147483647,-1,0,-1,0,0,2147483647,-1,0,0,-1,-1,0,-1,2147483647,0,2147483647,2147483647,2147483647,2147483647,0,-1,-1,2147483647,-1,-1,0,2147483647,2147483647,2147483647,-1,-1,-1,-1,0,0,2147483647,-1,-1,-1,-1,0,0,2147483647,-1,2147483647,0,-1,-1,-1,-1,-1,2147483647,0,0,2147483647,2147483647,2147483647,2147483647,0,-1,0,2147483647,2147483647,-1,0,-1,-1,-1,-1,0,-1,0,0},{0,-1,-1,2147483647,0,2147483647,2147483647,-1,2147483647,-1,-1,2147483647,-1,2147483647,2147483647,-1,2147483647,-1,-1,2147483647,-1,2147483647,2147483647,2147483647,0,0,-1,0,0,-1,2147483647,-1,0,0,0,0,-1,0,-1,2147483647,-1,-1,2147483647,2147483647,-1,2147483647,0,0,0,-1,0,0,-1,0,0,2147483647,0,-1,-1,0,0,2147483647,0,0,2147483647,2147483647,2147483647,0,2147483647,2147483647,-1,-1,-1,-1,-1,2147483647,2147483647,2147483647,2147483647,-1,2147483647,-1,0,-1,-1,0,0,-1,0,0,2147483647,-1,0,-1,2147483647,2147483647,-1,-1,-1,0,2147483647,2147483647,2147483647,2147483647,-1,2147483647,2147483647,2147483647,-1,-1,2147483647,2147483647,-1,-1,-1,0,2147483647,-1,0,0,-1,2147483647,-1,-1,-1,2147483647,-1,2147483647,2147483647,0,0,0,-1,-1,2147483647,-1,-1,2147483647,2147483647,-1,2147483647,2147483647,-1,-1,0,-1,-1,0,0,2147483647,2147483647,2147483647,0,0,2147483647,2147483647,0,2147483647,-1,-1,0,0,2147483647,2147483647,-1,0,2147483647,0,2147483647,0,2147483647,-1,0,2147483647,-1,-1,-1,0,0,2147483647,0,-1,-1,2147483647,2147483647,-1,-1,-1,2147483647,2147483647,-1,0,-1,-1,-1,2147483647,0,2147483647,2147483647,2147483647,2147483647,-1,-1,0,-1,2147483647,-1,-1,0,-1,2147483647,0,-1,0,2147483647,-1,0,2147483647,-1,2147483647,-1},{-1,-1,0,2147483647,0,0,-1,2147483647,-1,-1,2147483647,0,-1,0,2147483647,2147483647,0,0,-1,0,2147483647,-1,-1,2147483647,-1,-1,-1,0,-1,-1,-1,-1,2147483647,-1,0,-1,0,0,-1,-1,2147483647,-1,0,2147483647,2147483647,2147483647,0,0,0,2147483647,-1,0,-1,2147483647,0,-1,-1,0,-1,-1,2147483647,-1,0,-1,-1,0,2147483647,-1,2147483647,2147483647,2147483647,0,-1,2147483647,-1,0,-1,0,0,2147483647,-1,0,2147483647,-1,0,2147483647,-1,2147483647,0,0,0,0,-1,2147483647,0,-1,-1,0,-1,0,0,2147483647,2147483647,0,0,-1,2147483647,-1,2147483647,2147483647,2147483647,0,2147483647,-1,0,-1,2147483647,2147483647,0,0,2147483647,0,2147483647,2147483647,-1,2147483647,-1,2147483647,0,2147483647,-1,-1,2147483647,2147483647,2147483647,-1,-1,-1,0,2147483647,0,0,-1,0,-1,0,-1,0,-1,0,0,-1,-1,-1,2147483647,-1,0,2147483647,-1,2147483647,-1,-1,0,0,-1,-1,0,-1,2147483647,0,2147483647,0,2147483647,0,-1,2147483647,0,-1,-1,-1,-1,2147483647,2147483647,-1,0,-1,2147483647,0,0,0,2147483647,0,-1,0,0,0,-1,0,0,0,2147483647,-1,0,0,2147483647,2147483647,2147483647,-1,0,0,-1,2147483647,-1,-1,-1,-1,2147483647,0,-1,2147483647,-1},{-1,-1,-1,-1,-1,2147483647,-1,0,0,0,-1,0,-1,2147483647,2147483647,2147483647,0,0,0,2147483647,2147483647,-1,0,2147483647,-1,0,2147483647,-1,-1,0,-1,0,0,0,0,2147483647,2147483647,2147483647,0,0,0,0,0,0,0,2147483647,-1,0,0,0,0,-1,0,-1,-1,2147483647,-1,-1,2147483647,0,0,0,0,-1,2147483647,-1,0,2147483647,2147483647,0,-1,0,-1,0,-1,-1,-1,2147483647,0,2147483647,2147483647,-1,2147483647,-1,2147483647,-1,0,0,0,2147483647,0,-1,0,0,-1,2147483647,0,0,2147483647,2147483647,2147483647,-1,0,2147483647,-1,0,0,-1,-1,-1,2147483647,2147483647,-1,0,2147483647,-1,-1,0,0,-1,-1,0,0,2147483647,2147483647,-1,0,2147483647,-1,-1,-1,2147483647,2147483647,0,2147483647,0,2147483647,-1,0,-1,0,-1,0,-1,-1,-1,-1,-1,0,-1,0,2147483647,2147483647,2147483647,0,0,-1,0,0,0,2147483647,0,2147483647,0,-1,2147483647,0,0,-1,0,-1,2147483647,0,-1,0,-1,2147483647,-1,0,0,0,-1,0,0,0,2147483647,0,0,-1,2147483647,2147483647,-1,2147483647,0,2147483647,0,-1,0,-1,-1,2147483647,2147483647,2147483647,2147483647,0,0,2147483647,0,-1,-1,2147483647,-1,0,-1,0,2147483647,-1,0,-1,0,-1},{2147483647,2147483647,0,0,0,-1,0,0,-1,2147483647,0,-1,-1,0,-1,2147483647,-1,2147483647,-1,0,2147483647,0,-1,-1,2147483647,2147483647,2147483647,2147483647,0,0,-1,2147483647,0,2147483647,2147483647,0,-1,2147483647,-1,-1,-1,0,-1,0,0,2147483647,0,2147483647,0,-1,2147483647,-1,2147483647,-1,0,0,-1,-1,0,2147483647,0,2147483647,2147483647,0,2147483647,2147483647,-1,2147483647,0,2147483647,-1,2147483647,-1,-1,0,2147483647,2147483647,0,0,2147483647,0,2147483647,0,0,0,2147483647,0,2147483647,-1,0,-1,2147483647,0,-1,0,0,-1,-1,2147483647,-1,0,0,-1,2147483647,0,0,-1,2147483647,2147483647,2147483647,-1,2147483647,-1,2147483647,0,-1,2147483647,-1,0,2147483647,0,0,-1,-1,-1,2147483647,2147483647,0,0,0,0,-1,0,2147483647,0,-1,2147483647,-1,2147483647,-1,2147483647,-1,0,2147483647,2147483647,2147483647,-1,2147483647,-1,-1,2147483647,-1,2147483647,2147483647,0,2147483647,0,-1,-1,0,2147483647,0,-1,-1,-1,2147483647,0,2147483647,2147483647,0,-1,0,0,0,-1,0,2147483647,-1,0,-1,-1,-1,-1,-1,0,2147483647,-1,0,-1,-1,0,-1,-1,-1,0,2147483647,-1,-1,-1,2147483647,2147483647,2147483647,2147483647,0,2147483647,-1,0,-1,2147483647,0,2147483647,-1,-1,0,0,0,2147483647,2147483647,0,0,-1},{-1,2147483647,-1,-1,0,0,2147483647,-1,-1,-1,-1,-1,2147483647,-1,0,-1,0,0,0,0,2147483647,2147483647,2147483647,2147483647,0,-1,0,0,2147483647,2147483647,0,0,-1,0,0,2147483647,0,0,-1,-1,2147483647,2147483647,0,-1,0,-1,0,2147483647,0,2147483647,2147483647,-1,0,2147483647,0,-1,2147483647,-1,2147483647,2147483647,2147483647,0,2147483647,2147483647,2147483647,2147483647,0,-1,0,2147483647,0,0,-1,-1,-1,2147483647,0,0,-1,0,-1,0,0,0,0,-1,-1,0,-1,0,-1,2147483647,2147483647,0,2147483647,0,2147483647,0,2147483647,-1,2147483647,2147483647,0,0,2147483647,-1,-1,0,-1,2147483647,0,-1,-1,-1,0,2147483647,0,2147483647,2147483647,0,-1,-1,-1,0,0,-1,0,-1,2147483647,0,-1,-1,0,0,0,0,0,0,-1,2147483647,0,0,2147483647,2147483647,0,0,-1,0,-1,-1,0,2147483647,0,0,-1,2147483647,0,0,2147483647,2147483647,2147483647,-1,-1,0,-1,0,-1,0,0,-1,2147483647,-1,0,0,0,-1,-1,-1,-1,-1,-1,0,2147483647,2147483647,-1,2147483647,-1,-1,-1,0,2147483647,0,-1,2147483647,0,2147483647,0,-1,0,0,-1,-1,2147483647,2147483647,2147483647,2147483647,-1,-1,2147483647,-1,0,0,-1,2147483647,-1,0,-1,2147483647,2147483647,2147483647,2147483647},{0,0,0,2147483647,-1,0,2147483647,2147483647,2147483647,-1,2147483647,2147483647,0,0,0,2147483647,-1,-1,2147483647,2147483647,2147483647,0,-1,2147483647,0,2147483647,0,2147483647,-1,-1,0,0,2147483647,2147483647,-1,2147483647,0,2147483647,-1,2147483647,0,-1,-1,-1,0,0,0,0,-1,-1,-1,-1,-1,2147483647,-1,0,2147483647,0,0,0,0,-1,2147483647,0,0,-1,0,0,0,0,-1,0,2147483647,-1,0,-1,-1,0,-1,-1,0,-1,2147483647,0,0,-1,2147483647,2147483647,2147483647,-1,2147483647,-1,0,0,0,-1,-1,2147483647,2147483647,-1,-1,2147483647,0,-1,2147483647,-1,2147483647,0,0,-1,0,-1,0,-1,2147483647,2147483647,-1,0,-1,0,-1,2147483647,2147483647,0,-1,2147483647,-1,0,-1,0,2147483647,-1,0,-1,0,2147483647,0,2147483647,2147483647,0,-1,2147483647,2147483647,-1,-1,2147483647,0,-1,0,2147483647,-1,0,2147483647,0,0,2147483647,-1,2147483647,2147483647,2147483647,2147483647,-1,0,-1,0,-1,0,-1,0,0,0,-1,-1,2147483647,0,2147483647,-1,0,0,0,2147483647,2147483647,2147483647,2147483647,-1,-1,2147483647,-1,0,0,-1,0,-1,0,0,-1,0,0,2147483647,-1,-1,2147483647,-1,0,0,2147483647,2147483647,0,-1,0,-1,2147483647,0,-1,0,0,2147483647,-1,2147483647,-1,0},{0,0,0,0,2147483647,0,-1,2147483647,2147483647,2147483647,2147483647,0,-1,-1,0,2147483647,2147483647,2147483647,-1,0,2147483647,2147483647,2147483647,2147483647,2147483647,-1,-1,0,0,-1,0,-1,2147483647,0,2147483647,0,0,2147483647,-1,2147483647,2147483647,-1,-1,0,-1,0,2147483647,-1,2147483647,2147483647,-1,2147483647,0,-1,0,-1,0,0,2147483647,0,0,-1,-1,2147483647,0,-1,-1,2147483647,-1,0,2147483647,0,-1,0,0,-1,-1,0,2147483647,-1,0,0,0,2147483647,-1,2147483647,-1,2147483647,0,0,-1,0,2147483647,0,0,-1,2147483647,2147483647,-1,0,0,0,0,-1,0,-1,0,0,0,2147483647,-1,0,0,0,-1,0,0,2147483647,0,2147483647,0,-1,-1,0,0,2147483647,-1,0,2147483647,-1,0,-1,0,0,-1,2147483647,2147483647,-1,2147483647,2147483647,0,0,0,2147483647,-1,-1,2147483647,0,0,-1,0,2147483647,2147483647,0,-1,-1,2147483647,0,-1,0,0,-1,-1,2147483647,0,-1,-1,2147483647,-1,0,-1,2147483647,0,0,-1,2147483647,2147483647,2147483647,-1,2147483647,2147483647,-1,-1,0,2147483647,2147483647,2147483647,-1,0,-1,-1,2147483647,2147483647,2147483647,2147483647,2147483647,2147483647,0,-1,0,2147483647,2147483647,-1,-1,-1,0,2147483647,-1,-1,2147483647,2147483647,2147483647,0,-1,-1,2147483647,2147483647,-1,0,0,2147483647},{2147483647,2147483647,-1,2147483647,-1,-1,2147483647,0,0,0,0,-1,2147483647,-1,2147483647,2147483647,0,-1,-1,2147483647,2147483647,0,-1,0,-1,2147483647,2147483647,0,0,2147483647,-1,2147483647,-1,2147483647,-1,2147483647,-1,0,-1,-1,2147483647,0,2147483647,0,2147483647,2147483647,2147483647,0,0,0,-1,-1,-1,2147483647,2147483647,-1,2147483647,2147483647,-1,-1,-1,2147483647,0,-1,-1,2147483647,2147483647,2147483647,2147483647,-1,2147483647,-1,0,-1,-1,-1,2147483647,-1,0,0,2147483647,2147483647,-1,-1,2147483647,0,2147483647,-1,0,-1,-1,0,2147483647,2147483647,0,-1,0,2147483647,0,2147483647,0,-1,-1,0,-1,-1,0,2147483647,0,2147483647,-1,0,0,0,0,2147483647,2147483647,2147483647,-1,-1,2147483647,-1,2147483647,-1,0,-1,-1,-1,2147483647,0,0,0,0,-1,2147483647,0,0,2147483647,0,0,2147483647,2147483647,-1,2147483647,-1,0,-1,2147483647,0,2147483647,0,0,0,-1,0,0,2147483647,-1,2147483647,-1,0,0,0,2147483647,2147483647,2147483647,2147483647,0,0,2147483647,0,2147483647,2147483647,0,2147483647,-1,0,-1,2147483647,-1,-1,0,0,2147483647,2147483647,0,-1,-1,-1,0,-1,-1,2147483647,0,-1,2147483647,0,0,2147483647,-1,0,-1,2147483647,-1,-1,-1,2147483647,0,0,0,2147483647,0,0,2147483647,2147483647,-1,2147483647,2147483647,2147483647,-1,0},{-1,-1,-1,2147483647,0,-1,-1,2147483647,0,-1,0,0,-1,2147483647,-1,-1,-1,-1,-1,2147483647,-1,-1,2147483647,0,0,-1,-1,0,2147483647,-1,0,2147483647,-1,2147483647,-1,-1,-1,-1,2147483647,2147483647,0,2147483647,0,0,0,-1,-1,0,2147483647,0,0,-1,0,2147483647,-1,2147483647,0,2147483647,-1,2147483647,0,0,-1,0,-1,-1,0,-1,0,2147483647,-1,0,-1,-1,2147483647,2147483647,-1,0,0,-1,0,-1,-1,2147483647,2147483647,-1,0,0,0,0,0,2147483647,-1,-1,2147483647,0,2147483647,0,-1,-1,0,-1,2147483647,0,-1,-1,0,2147483647,2147483647,-1,-1,2147483647,0,0,0,-1,2147483647,-1,0,-1,-1,0,-1,0,0,-1,-1,-1,0,0,0,2147483647,2147483647,2147483647,-1,2147483647,0,0,0,0,2147483647,2147483647,-1,-1,0,2147483647,-1,-1,0,2147483647,-1,2147483647,2147483647,-1,-1,-1,2147483647,2147483647,2147483647,-1,0,2147483647,-1,0,-1,-1,-1,-1,0,-1,2147483647,-1,0,-1,0,-1,2147483647,-1,-1,0,0,-1,2147483647,0,0,0,2147483647,-1,2147483647,-1,0,2147483647,2147483647,2147483647,0,0,-1,-1,0,0,0,2147483647,2147483647,2147483647,2147483647,0,2147483647,2147483647,-1,2147483647,-1,0,0,0,2147483647,-1,2147483647,2147483647,0,-1,-1}}; s.wallsAndGates(input); return 0; }
3,442.052632
259,807
0.744878
[ "vector" ]
a206fcac79fdc4188940c8d3fda7a363146b6862
5,562
cpp
C++
samples/tests/chain_problem.cpp
henrytseng/Box2D
022d9eccfcbebe339f1df3a17d205110d9623a80
[ "MIT" ]
1
2020-05-25T20:36:19.000Z
2020-05-25T20:36:19.000Z
samples/tests/chain_problem.cpp
henrytseng/Box2D
022d9eccfcbebe339f1df3a17d205110d9623a80
[ "MIT" ]
null
null
null
samples/tests/chain_problem.cpp
henrytseng/Box2D
022d9eccfcbebe339f1df3a17d205110d9623a80
[ "MIT" ]
null
null
null
// MIT License // Copyright (c) 2019 Erin Catto // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include "test.h" class ChainProblem : public Test { public: ChainProblem() { //dump { b2Vec2 g(0.000000000000000e+00f, -1.000000000000000e+01f); m_world->SetGravity(g); b2Body** bodies = (b2Body**)b2Alloc(2 * sizeof(b2Body*)); b2Joint** joints = (b2Joint**)b2Alloc(0 * sizeof(b2Joint*)); { b2BodyDef bd; bd.type = b2BodyType(0); bd.position.Set(0.000000000000000e+00f, 0.000000000000000e+00f); bd.angle = 0.000000000000000e+00f; bd.linearVelocity.Set(0.000000000000000e+00f, 0.000000000000000e+00f); bd.angularVelocity = 0.000000000000000e+00f; bd.linearDamping = 0.000000000000000e+00f; bd.angularDamping = 0.000000000000000e+00f; bd.allowSleep = bool(4); bd.awake = bool(2); bd.fixedRotation = bool(0); bd.bullet = bool(0); bd.active = bool(32); bd.gravityScale = 1.000000000000000e+00f; bodies[0] = m_world->CreateBody(&bd); { b2FixtureDef fd; fd.friction = 2.000000029802322e-01f; fd.restitution = 0.000000000000000e+00f; fd.density = 0.000000000000000e+00f; fd.isSensor = bool(0); fd.filter.categoryBits = uint16(1); fd.filter.maskBits = uint16(65535); fd.filter.groupIndex = int16(0); b2ChainShape shape; b2Vec2 vs[3]; vs[0].Set(0.000000000000000e+00f, 1.000000000000000e+00f); vs[1].Set(0.000000000000000e+00f, 0.000000000000000e+00f); vs[2].Set(4.000000000000000e+00f, 0.000000000000000e+00f); shape.CreateChain(vs, 3); shape.m_prevVertex.Set(4.719737010713663e-34f, 8.266340761211261e-34f); shape.m_nextVertex.Set(1.401298464324817e-45f, 8.266340761211261e-34f); shape.m_hasPrevVertex = bool(0); shape.m_hasNextVertex = bool(0); fd.shape = &shape; bodies[0]->CreateFixture(&fd); } } { b2BodyDef bd; bd.type = b2BodyType(2); bd.position.Set(6.033980250358582e-01f, 3.028350114822388e+00f); bd.angle = 0.000000000000000e+00f; bd.linearVelocity.Set(0.000000000000000e+00f, 0.000000000000000e+00f); bd.angularVelocity = 0.000000000000000e+00f; bd.linearDamping = 0.000000000000000e+00f; bd.angularDamping = 0.000000000000000e+00f; bd.allowSleep = bool(4); bd.awake = bool(2); bd.fixedRotation = bool(0); bd.bullet = bool(1); bd.active = bool(32); bd.gravityScale = 1.000000000000000e+00f; bodies[1] = m_world->CreateBody(&bd); { b2FixtureDef fd; fd.friction = 2.000000029802322e-01f; fd.restitution = 0.000000000000000e+00f; fd.density = 1.000000000000000e+01f; fd.isSensor = bool(0); fd.filter.categoryBits = uint16(1); fd.filter.maskBits = uint16(65535); fd.filter.groupIndex = int16(0); b2PolygonShape shape; b2Vec2 vs[8]; vs[0].Set(5.000000000000000e-01f, -3.000000000000000e+00f); vs[1].Set(5.000000000000000e-01f, 3.000000000000000e+00f); vs[2].Set(-5.000000000000000e-01f, 3.000000000000000e+00f); vs[3].Set(-5.000000000000000e-01f, -3.000000000000000e+00f); shape.Set(vs, 4); fd.shape = &shape; bodies[1]->CreateFixture(&fd); } } b2Free(joints); b2Free(bodies); joints = NULL; bodies = NULL; } } static Test* Create() { return new ChainProblem; } }; static int testIndex = RegisterTest("Bugs", "Chain Problem", ChainProblem::Create);
41.819549
91
0.552499
[ "shape" ]
a20bf595de77ed97412c904677ceee08bc4f1251
16,383
cpp
C++
src/external_plugins/term_buffer/internal_term_buffer.cpp
stonewell/wxglterm
27480ed01e2832e98785b517ac17037a71cefe7c
[ "MIT" ]
12
2017-11-23T16:02:41.000Z
2019-12-29T08:36:36.000Z
src/external_plugins/term_buffer/internal_term_buffer.cpp
stonewell/wxglterm
27480ed01e2832e98785b517ac17037a71cefe7c
[ "MIT" ]
9
2017-12-04T15:55:51.000Z
2019-11-01T13:08:21.000Z
src/external_plugins/term_buffer/internal_term_buffer.cpp
stonewell/wxglterm
27480ed01e2832e98785b517ac17037a71cefe7c
[ "MIT" ]
5
2018-09-02T07:35:13.000Z
2019-12-29T08:36:37.000Z
#include "default_term_selection_decl.h" #include "default_term_line.h" #include "default_term_cell.h" #include "internal_term_buffer.h" #include "default_term_buffer_decl.h" #include <vector> #include <iostream> #include <cassert> #include <functional> __InternalTermBuffer::__InternalTermBuffer(DefaultTermBuffer* term_buffer) : m_TermBuffer(term_buffer) , m_Rows(0) , m_Cols(0) , m_CurRow(0) , m_CurCol(0) , m_ScrollRegionBegin(0) , m_ScrollRegionEnd(0) , m_Lines() , m_Selection{new DefaultTermSelection} , m_VisRowHeaderBegin {0} , m_VisRowScrollRegionBegin {0} , m_VisRowFooterBegin {0} , m_Mode{0} { } __InternalTermBuffer::__InternalTermBuffer(const __InternalTermBuffer & term_buffer) : m_TermBuffer(nullptr) , m_Rows(term_buffer.m_Rows) , m_Cols(term_buffer.m_Cols) , m_CurRow(term_buffer.m_CurRow) , m_CurCol(term_buffer.m_CurCol) , m_ScrollRegionBegin(term_buffer.m_ScrollRegionBegin) , m_ScrollRegionEnd(term_buffer.m_ScrollRegionEnd) , m_Lines() , m_Selection{new DefaultTermSelection} , m_VisRowHeaderBegin {term_buffer.m_VisRowHeaderBegin} , m_VisRowScrollRegionBegin {term_buffer.m_VisRowScrollRegionBegin} , m_VisRowFooterBegin {term_buffer.m_VisRowFooterBegin} { m_Lines.resize(term_buffer.m_Lines.size()); uint32_t index = 0; for(TermLinePtr line : term_buffer.m_Lines) { if (!line) { index++; continue; } TermLinePtr new_line = CreateDefaultTermLine(m_TermBuffer); new_line->Resize(GetCols()); for(uint32_t i=0;i < GetCols(); i++) { TermCellPtr cell = line->GetCell(i); TermCellPtr new_cell = new_line->GetCell(i); new_cell->Reset(cell); } m_Lines[index++] = new_line; } } void __InternalTermBuffer::Resize(uint32_t row, uint32_t col) { std::function<void()> reset_lines { [this]() { for (TermLineVector::iterator it = m_Lines.begin(), it_end = m_Lines.end(); it != it_end; it++) { if (*it) { (*it)->Resize(m_Cols); } } } }; if (m_Rows == row && m_Cols == col) { reset_lines(); return; } ClearHistoryLinesData(); m_Rows = row; m_Cols = col; m_ScrollRegionBegin = 0; m_ScrollRegionEnd = 0; if (m_CurRow >= m_Rows) SetRow(m_Rows ? m_Rows - 1 : 0); if (m_CurCol >= m_Cols) SetCol(m_Cols ? m_Cols - 1 : 0); m_Lines.resize(m_Rows); reset_lines(); ClearSelection(); m_VisRowHeaderBegin = 0; m_VisRowFooterBegin = row; m_VisRowScrollRegionBegin = 0; } bool __InternalTermBuffer::HasScrollRegion() { return m_ScrollRegionBegin < m_ScrollRegionEnd; } uint32_t __InternalTermBuffer::RowToLineIndex(uint32_t row) { if (HasScrollRegion()) { if (row < m_ScrollRegionBegin) return m_VisRowHeaderBegin + row; else if (row >= m_ScrollRegionBegin && row <= m_ScrollRegionEnd) return m_VisRowScrollRegionBegin + row - m_ScrollRegionBegin; else return m_VisRowFooterBegin + row - m_ScrollRegionEnd - 1; } else { return m_VisRowHeaderBegin + row; } } bool __InternalTermBuffer::__NormalizeBeginEndPositionResetLinesWhenDeleteOrInsert(uint32_t & begin, uint32_t count, uint32_t & end) { end = begin + count; if (HasScrollRegion()) { if (begin < m_ScrollRegionBegin) begin = m_ScrollRegionBegin; if (end > m_ScrollRegionEnd) { //Reset line directly for (uint32_t i = begin;i <= m_ScrollRegionEnd; i++) { auto line = GetLine(i); if (line) { line->Resize(0); line->Resize(GetCols()); } } return true; } end = m_ScrollRegionEnd + 1; } else { if (end >= m_Rows) { //Reset line directly for (uint32_t i = begin;i < m_Rows; i++) { auto line = GetLine(i); if (line) { line->Resize(0); line->Resize(GetCols()); } } return true; } end = m_Rows; } return false; } void __InternalTermBuffer::SetCurCellData(uint32_t ch, bool wide_char, bool insert, const TermCellPtr & cell_template) { int new_cell_count = wide_char ? 2 : 1; if (m_TermBuffer->m_Debug) std::cout << "set:[" << (char)ch << "], c:" << m_CurCol << ", r:" << m_CurRow << std::endl; if (!insert) { if (m_CurCol + new_cell_count > m_Cols) { MoveCurRow(1, true, false, cell_template); SetCol(0); } TermCellPtr cell = GetCurCell(); if (!cell) return; cell->Reset(cell_template); cell->SetChar((wchar_t)ch); cell->SetWideChar(wide_char); SetCol(m_CurCol + 1); if (wide_char) { cell = GetCurCell(); cell->Reset(cell_template); cell->SetChar((wchar_t)0); SetCol(m_CurCol + 1); } } else { uint32_t saved_row = m_CurRow; uint32_t saved_col = m_CurCol; TermLinePtr line = GetLine(m_CurRow); TermCellPtr extra_cell = line->InsertCell(m_CurCol); TermCellPtr cell = line->GetCell(m_CurCol); cell->Reset(cell_template); cell->SetChar((wchar_t)ch); cell->SetWideChar(wide_char); SetCol(m_CurCol + 1); TermCellPtr extra_cell_2{}; if (wide_char) { extra_cell_2 = line->InsertCell(m_CurCol); cell = line->GetCell(m_CurCol); cell->Reset(cell_template); cell->SetChar((wchar_t)0); SetCol(m_CurCol + 1); } if (!IsDefaultCell(extra_cell) || !IsDefaultCell(extra_cell_2)) { MoveCurRow(1, true, false, cell_template); SetCol(0); if (m_CurRow > saved_row) { if (!IsDefaultCell(extra_cell)) { SetCurCellData((uint32_t)extra_cell->GetChar(), extra_cell->IsWideChar(), insert, extra_cell); } if (!IsDefaultCell(extra_cell_2)) { SetCurCellData((uint32_t)extra_cell_2->GetChar(), extra_cell_2->IsWideChar(), insert, extra_cell_2); } } } SetRow(saved_row); SetCol(saved_col); } if (m_CurCol > m_Cols) SetCol(m_Cols - 1); } bool __InternalTermBuffer::IsDefaultCell(TermCellPtr cell) { if (!cell) return true; return (cell->GetChar() == ' ' && cell->GetForeColorIndex() == m_TermBuffer->m_DefaultForeColorIndex && cell->GetBackColorIndex() == m_TermBuffer->m_DefaultBackColorIndex && cell->GetMode() == m_TermBuffer->m_DefaultMode); } TermLinePtr __InternalTermBuffer::GetLine(uint32_t row) { if (row < GetRows()) { auto index = RowToLineIndex(row); auto line = m_Lines[index]; if (!line) { line = CreateDefaultTermLine(m_TermBuffer); line->Resize(GetCols()); m_Lines[index] = line; } return line; } printf("invalid row:%u, rows:%u\n", row, GetRows()); return TermLinePtr{}; } void __InternalTermBuffer::DeleteLines(uint32_t begin, uint32_t count, const TermCellPtr & cell_template) { uint32_t end = m_Rows; //delete/insert lines will clear all saved history data ClearHistoryLinesData(); if (__NormalizeBeginEndPositionResetLinesWhenDeleteOrInsert(begin, count, end)) { return; } if (end <= begin) return; TermLineVector tmpVector; //Insert First, then delete for (uint32_t i = begin; i < begin + count; i++) { TermLinePtr new_line = CreateDefaultTermLine(m_TermBuffer); new_line->Resize(GetCols(), cell_template); tmpVector.push_back(new_line); } TermLineVector::iterator b_it = m_Lines.begin() + RowToLineIndex(begin), e_it = m_Lines.begin() + RowToLineIndex(end); m_Lines.insert(e_it, tmpVector.begin(), tmpVector.end()); //recalculate iterator b_it = m_Lines.begin() + RowToLineIndex(begin); e_it = m_Lines.begin() + RowToLineIndex(begin + count); m_Lines.erase(b_it, e_it); } void __InternalTermBuffer::InsertLines(uint32_t begin, uint32_t count, const TermCellPtr & cell_template) { uint32_t end = m_Rows; //delete/insert lines will clear all saved history data ClearHistoryLinesData(); if (__NormalizeBeginEndPositionResetLinesWhenDeleteOrInsert(begin, count, end)) { return; } if (end <= begin) return; TermLineVector::iterator b_it = m_Lines.begin() + RowToLineIndex(end - count), e_it = m_Lines.begin() + RowToLineIndex(end); m_Lines.erase(b_it, e_it); TermLineVector tmpVector; for (uint32_t i = 0; i < count; i++) { TermLinePtr new_line = CreateDefaultTermLine(m_TermBuffer); new_line->Resize(GetCols(), cell_template); tmpVector.push_back(new_line); } b_it = m_Lines.begin() + RowToLineIndex(begin); m_Lines.insert(b_it, tmpVector.begin(), tmpVector.end()); } void __InternalTermBuffer::ScrollBuffer(int32_t scroll_offset, const TermCellPtr & cell_template) { if (scroll_offset < 0) { if (HasScrollRegion()) { uint32_t begin = m_VisRowScrollRegionBegin - scroll_offset; uint32_t end = begin + m_ScrollRegionEnd - m_ScrollRegionBegin + 1; while (end > m_VisRowFooterBegin) { TermLinePtr new_line = CreateDefaultTermLine(m_TermBuffer); new_line->Resize(GetCols(), cell_template); m_Lines.insert(m_Lines.begin() + m_VisRowFooterBegin, new_line); m_VisRowFooterBegin++; } m_VisRowScrollRegionBegin = begin; } else { uint32_t begin = m_VisRowHeaderBegin - scroll_offset; uint32_t end = begin + m_Rows; if (m_Lines.size() < end) { m_Lines.resize(end); } m_VisRowHeaderBegin = begin; m_VisRowFooterBegin = end; } } else if (scroll_offset > 0) { if (HasScrollRegion()) { if (m_VisRowHeaderBegin + m_ScrollRegionBegin + scroll_offset > m_VisRowScrollRegionBegin) { for(uint32_t i = m_VisRowScrollRegionBegin; i < m_VisRowHeaderBegin + m_ScrollRegionBegin + scroll_offset; i++) { TermLinePtr new_line = CreateDefaultTermLine(m_TermBuffer); new_line->Resize(GetCols(), cell_template); m_Lines.insert(m_Lines.begin() + m_VisRowHeaderBegin + m_ScrollRegionBegin, new_line); m_VisRowFooterBegin ++; } m_VisRowScrollRegionBegin = m_VisRowHeaderBegin + m_ScrollRegionBegin + scroll_offset; } m_VisRowScrollRegionBegin -= scroll_offset; } else { if (m_VisRowHeaderBegin < (uint32_t)scroll_offset) { for(uint32_t i = m_VisRowHeaderBegin;i < (uint32_t)scroll_offset;i++) { TermLinePtr new_line = CreateDefaultTermLine(m_TermBuffer); new_line->Resize(GetCols(), cell_template); m_Lines.insert(m_Lines.begin(), new_line); } m_VisRowHeaderBegin = scroll_offset; } m_VisRowHeaderBegin -= scroll_offset; m_VisRowFooterBegin = m_VisRowHeaderBegin + m_Rows; } } } bool __InternalTermBuffer::MoveCurRow(uint32_t offset, bool move_down, bool scroll_buffer, const TermCellPtr & cell_template) { uint32_t begin = 0, end = GetRows() - 1; bool scrolled = false; if (HasScrollRegion()) { begin = m_ScrollRegionBegin; end = m_ScrollRegionEnd; } if (move_down) { if (m_CurRow + offset <= end) { SetRow(m_CurRow + offset); } else { SetRow(end); //scroll if (scroll_buffer) { ScrollBuffer(-1 * (m_CurRow + offset - end), cell_template); scrolled = true; } } } else { if (m_CurRow >= offset && (m_CurRow - offset) >= begin) { SetRow(m_CurRow - offset); } else { SetRow(begin); //scroll if (scroll_buffer) { ScrollBuffer(begin + offset - m_CurRow, cell_template); scrolled = true; } } } return scrolled; } void __InternalTermBuffer::SetRow(uint32_t row) { m_CurRow = row; } void __InternalTermBuffer::SetCol(uint32_t col) { m_CurCol = col; } void __InternalTermBuffer::SetScrollRegionBegin(uint32_t begin) { ClearHistoryLinesData(); m_ScrollRegionBegin = begin; m_VisRowScrollRegionBegin = HasScrollRegion() ? m_VisRowHeaderBegin + begin : 0; m_VisRowFooterBegin = HasScrollRegion() ? m_ScrollRegionEnd + 1 : m_Rows; } void __InternalTermBuffer::SetScrollRegionEnd(uint32_t end) { ClearHistoryLinesData(); m_ScrollRegionEnd = end; m_VisRowScrollRegionBegin = HasScrollRegion() ? m_VisRowHeaderBegin + m_ScrollRegionBegin : 0; m_VisRowFooterBegin = HasScrollRegion() ? m_ScrollRegionEnd + 1 : m_Rows; } void __InternalTermBuffer::ClearHistoryLinesData() { auto it = m_Lines.begin(); if (HasScrollRegion()) { it = m_Lines.begin() + m_VisRowFooterBegin + m_Rows - m_ScrollRegionEnd - 1; if (it != m_Lines.end()) m_Lines.erase(it, m_Lines.end()); it = m_Lines.begin() + m_VisRowScrollRegionBegin + m_ScrollRegionEnd - m_ScrollRegionBegin + 1; if (it != m_Lines.end() && (m_VisRowScrollRegionBegin + m_ScrollRegionEnd - m_ScrollRegionBegin + 1 < m_VisRowFooterBegin)) m_Lines.erase(it, m_Lines.begin() + m_VisRowFooterBegin); it = m_Lines.begin() + m_VisRowHeaderBegin + m_ScrollRegionBegin; if (it != m_Lines.end() && (m_VisRowHeaderBegin + m_ScrollRegionBegin < m_VisRowScrollRegionBegin)) m_Lines.erase(it, m_Lines.begin() + m_VisRowScrollRegionBegin); } else { it = m_Lines.begin() + m_VisRowHeaderBegin + m_Rows; if (it != m_Lines.end()) m_Lines.erase(it, m_Lines.end()); } it = m_Lines.begin(); if (it != m_Lines.end() && (m_VisRowHeaderBegin > 0)) m_Lines.erase(it, m_Lines.begin() + m_VisRowHeaderBegin); if (m_Lines.size() > 0) assert(m_Lines.size() >= m_Rows); m_VisRowHeaderBegin = 0; m_VisRowFooterBegin = HasScrollRegion() ? m_ScrollRegionEnd + 1 : m_Rows; m_VisRowScrollRegionBegin = HasScrollRegion() ? m_ScrollRegionBegin : 0; } uint32_t __InternalTermBuffer::GetMode() const { return (uint32_t)m_Mode.to_ulong(); } void __InternalTermBuffer::SetMode(uint32_t m) { m_Mode = std::bitset<16>(m); } void __InternalTermBuffer::AddMode(uint32_t m) { m_Mode.set(m); } void __InternalTermBuffer::RemoveMode(uint32_t m) { m_Mode.reset(m); }
29.895985
127
0.564732
[ "vector" ]
a213e6da67c5f4c511b6abcb03a5f4468b1fa1f2
1,087
hpp
C++
TP01_SDL/include/utils.hpp
diogenesvazmelo/Computacao_Grafica
9a9742fc9e9ea19182c7b4dff5c02cf57188cd5d
[ "MIT" ]
null
null
null
TP01_SDL/include/utils.hpp
diogenesvazmelo/Computacao_Grafica
9a9742fc9e9ea19182c7b4dff5c02cf57188cd5d
[ "MIT" ]
null
null
null
TP01_SDL/include/utils.hpp
diogenesvazmelo/Computacao_Grafica
9a9742fc9e9ea19182c7b4dff5c02cf57188cd5d
[ "MIT" ]
null
null
null
#ifndef MY_UTILS_HPP #define MY_UTILS_HPP #if __linux__ #include <SDL2/SDL.h> #elif _WIN32 #include <SDL.h> #endif #include <vector> #include "../include/spaceship.hpp" namespace utils { enum STATES { PLAYING, VICTORY, PAUSED, GAME_OVER, EXIT }; SDL_Rect makeRect(int _x, int _y, int _h, int _w); void reset(Spaceship &player, std::vector<Spaceship> &enemies, std::vector<std::pair<bool, Blast> > &enemiesBlasts, float window_width, float window_height, float padding, float enemyArea); bool checkWinCondition(std::vector<Spaceship> sps); bool collision(Spaceship player, Spaceship enemy); bool collision(Blast blast, Spaceship enemy); void enemyMovement(Spaceship &sp, float tConst, float leftLimit, float rightLimit, bool &direction); bool canGoLeft(Spaceship player, float movConst); bool canGoRight(Spaceship player, float movConst, float window_width); bool outOfBounds(Spaceship sp, float SCREEN_WIDTH, float SCREEN_HEIGHT); bool outOfBounds(Blast b, float SCREEN_WIDTH, float SCREEN_HEIGHT); } // namespace utils #endif
31.057143
72
0.74149
[ "vector" ]
a21ce646a8093fa3df8891d6626442859dd9c3b7
3,898
cpp
C++
algorithms/graph theory/RoadsAndLibraries.cpp
HannoFlohr/hackerrank
9644c78ce05a6b1bc5d8f542966781d53e5366e3
[ "MIT" ]
null
null
null
algorithms/graph theory/RoadsAndLibraries.cpp
HannoFlohr/hackerrank
9644c78ce05a6b1bc5d8f542966781d53e5366e3
[ "MIT" ]
null
null
null
algorithms/graph theory/RoadsAndLibraries.cpp
HannoFlohr/hackerrank
9644c78ce05a6b1bc5d8f542966781d53e5366e3
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; vector<string> split_string(string); class City { public: int id; vector<int> neighbors; City(){} City(int i) { id = i; neighbors = vector<int>(); } }; int visitNeighbors(int n, const vector<City*>& cities, vector<bool>& visited, int& roads) { City* c; int neighborhood = 0; queue<City*> q; q.push( cities[n] ); while(!q.empty()) { c = q.front(); q.pop(); if(!visited[c->id]) { visited[c->id] = true; if(c->id != n) roads++; neighborhood++; for(int i=0; i<c->neighbors.size(); i++) if(!visited[ c->neighbors[i] ]) q.push( cities[ c->neighbors[i] ] ); } } return neighborhood; } // Complete the roadsAndLibraries function below. long roadsAndLibraries(int n, int c_lib, int c_road, vector<vector<int>> roads) { vector<bool> visited (n,false); vector<City*> cities; City* c; for(int i=0; i<n; i++) { c = new City(i); cities.push_back(c); } for(int i=0; i<roads.size(); i++) { cities[ roads[i][0]-1 ]->neighbors.push_back( roads[i][1]-1 ); cities[ roads[i][1]-1 ]->neighbors.push_back( roads[i][0]-1 ); } int roadsToBuild; vector<int> neighborhoods; vector<int> roadsInNeighborHood; for(int i=0; i<n; i++) { if(!visited[i]) { roadsToBuild = 0; neighborhoods.push_back( visitNeighbors(i,cities,visited, roadsToBuild) ); roadsInNeighborHood.push_back(roadsToBuild); } } long totalCost=0, costLibrariesInAllCities=0, costMinRoadsOneLibrary=0; for(int i=0; i<neighborhoods.size(); i++) { if(neighborhoods[i]==1) totalCost += c_lib; else { costLibrariesInAllCities = neighborhoods[i] * c_lib; costMinRoadsOneLibrary = roadsInNeighborHood[i] * c_road + c_lib; totalCost += min(costLibrariesInAllCities,costMinRoadsOneLibrary); } } for(int i=0; i<cities.size(); i++) delete cities[i]; cities.clear(); return totalCost; } int main() { ofstream fout(getenv("OUTPUT_PATH")); int q; cin >> q; cin.ignore(numeric_limits<streamsize>::max(), '\n'); for (int q_itr = 0; q_itr < q; q_itr++) { string nmC_libC_road_temp; getline(cin, nmC_libC_road_temp); vector<string> nmC_libC_road = split_string(nmC_libC_road_temp); int n = stoi(nmC_libC_road[0]); int m = stoi(nmC_libC_road[1]); int c_lib = stoi(nmC_libC_road[2]); int c_road = stoi(nmC_libC_road[3]); vector<vector<int>> cities(m); for (int i = 0; i < m; i++) { cities[i].resize(2); for (int j = 0; j < 2; j++) { cin >> cities[i][j]; } cin.ignore(numeric_limits<streamsize>::max(), '\n'); } long result = roadsAndLibraries(n, c_lib, c_road, cities); fout << result << "\n"; } fout.close(); return 0; } vector<string> split_string(string input_string) { string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { return x == y and x == ' '; }); input_string.erase(new_end, input_string.end()); while (input_string[input_string.length() - 1] == ' ') { input_string.pop_back(); } vector<string> splits; char delimiter = ' '; size_t i = 0; size_t pos = input_string.find(delimiter); while (pos != string::npos) { splits.push_back(input_string.substr(i, pos - i)); i = pos + 1; pos = input_string.find(delimiter, i); } splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); return splits; }
25.311688
115
0.556183
[ "vector" ]
b8c5e20cc9522adaa5086538eb9a27ccfcc69b12
432
cpp
C++
code/ch11/11.1.2_maxslidingwindow.cpp
leetcode-pp/leetcode-pp1
a1f9e46fdd2f480d2fcb94e76370e040e0f0a4f5
[ "MIT" ]
22
2021-02-23T13:42:28.000Z
2022-03-02T11:19:28.000Z
code/ch11/11.1.2_maxslidingwindow.cpp
leetcode-pp/leetcode-pp1
a1f9e46fdd2f480d2fcb94e76370e040e0f0a4f5
[ "MIT" ]
9
2021-06-16T10:42:01.000Z
2021-08-24T09:06:29.000Z
code/ch11/11.1.2_maxslidingwindow.cpp
leetcode-pp/leetcode-pp1
a1f9e46fdd2f480d2fcb94e76370e040e0f0a4f5
[ "MIT" ]
9
2021-02-20T08:29:00.000Z
2021-09-18T08:52:25.000Z
class Solution { public: vector<int> maxSlidingWindow(vector<int>& nums, int k) { vector<int> res; multiset<int> mysetting; for (int i = 0; i < nums.size(); i++) { mysetting.insert(nums[i]); if (i >= k - 1) { res.push_back(*mysetting.rbegin()); mysetting.erase(mysetting.find(nums[i - k + 1])); } } return res; } };
27
65
0.476852
[ "vector" ]
b8c95e9b52feb61f74fdba615d4e032b377f0efa
1,962
cpp
C++
MSVC/14.24.28314/crt/src/stl/iosptrs.cpp
825126369/UCRT
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
[ "MIT" ]
2
2021-01-27T10:19:30.000Z
2021-02-09T06:24:30.000Z
MSVC/14.24.28314/crt/src/stl/iosptrs.cpp
825126369/UCRT
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
[ "MIT" ]
null
null
null
MSVC/14.24.28314/crt/src/stl/iosptrs.cpp
825126369/UCRT
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
[ "MIT" ]
1
2021-01-27T10:19:36.000Z
2021-01-27T10:19:36.000Z
// Copyright (c) Microsoft Corporation. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // iostream object pointers #include <iostream> #include <Windows.h> _STD_BEGIN #if defined(_M_CEE) && !defined(_M_CEE_MIXED) #error This file cannot be built /clr:pure, etc. because of the use of _PGLOBAL. #endif #pragma warning(disable : 4074) #pragma init_seg(compiler) _PGLOBAL static std::_Init_locks initlocks; // OBJECT DECLARATIONS __PURE_APPDOMAIN_GLOBAL extern _CRTDATA2_IMPORT istream* _Ptr_cin = 0; __PURE_APPDOMAIN_GLOBAL extern _CRTDATA2_IMPORT ostream* _Ptr_cout = 0; __PURE_APPDOMAIN_GLOBAL extern _CRTDATA2_IMPORT ostream* _Ptr_cerr = 0; __PURE_APPDOMAIN_GLOBAL extern _CRTDATA2_IMPORT ostream* _Ptr_clog = 0; // WIDE OBJECTS __PURE_APPDOMAIN_GLOBAL extern _CRTDATA2_IMPORT wistream* _Ptr_wcin = 0; __PURE_APPDOMAIN_GLOBAL extern _CRTDATA2_IMPORT wostream* _Ptr_wcout = 0; __PURE_APPDOMAIN_GLOBAL extern _CRTDATA2_IMPORT wostream* _Ptr_wcerr = 0; __PURE_APPDOMAIN_GLOBAL extern _CRTDATA2_IMPORT wostream* _Ptr_wclog = 0; _STD_END // FINALIZATION CODE #define NATS 10 // fclose, xgetloc, locks, facet free, etc. // static data __PURE_APPDOMAIN_GLOBAL static void(__cdecl* atfuns_cdecl[NATS])() = {0}; __PURE_APPDOMAIN_GLOBAL static size_t atcount_cdecl = {NATS}; _MRTIMP2 void __cdecl _Atexit(void(__cdecl* pf)()) { // add to wrapup list if (atcount_cdecl == 0) { abort(); // stack full, give up } else { atfuns_cdecl[--atcount_cdecl] = (void(__cdecl*)()) EncodePointer(pf); } } struct _Init_atexit { // controller for atexit processing __CLR_OR_THIS_CALL ~_Init_atexit() noexcept { // process wrapup functions while (atcount_cdecl < NATS) { void(__cdecl * pf)() = (void(__cdecl*)()) DecodePointer(atfuns_cdecl[atcount_cdecl++]); if (pf) { (*pf)(); } } } }; __PURE_APPDOMAIN_GLOBAL static _Init_atexit init_atexit;
33.827586
99
0.729358
[ "object" ]
b8d497c3108ecffd637a2bd08869358dcb607803
8,322
cpp
C++
src/ShapeTools.cpp
tapeguy/heekscad
e5037d15d642551de756f352e4e14505c39ad7cf
[ "BSD-3-Clause" ]
null
null
null
src/ShapeTools.cpp
tapeguy/heekscad
e5037d15d642551de756f352e4e14505c39ad7cf
[ "BSD-3-Clause" ]
null
null
null
src/ShapeTools.cpp
tapeguy/heekscad
e5037d15d642551de756f352e4e14505c39ad7cf
[ "BSD-3-Clause" ]
null
null
null
// ShapeTools.cpp // Copyright (c) 2009, Dan Heeks // This program is released under the BSD license. See the file COPYING for details. #include "stdafx.h" #include "Face.h" #include "ShapeTools.h" #include "Vertex.h" #include <BRepAdaptor_Curve.hxx> const wxBitmap &CFaceList::GetIcon() { static wxBitmap* icon = NULL; if(icon == NULL)icon = new wxBitmap(wxImage(wxGetApp().GetResFolder() + _T("/icons/faces.png"))); return *icon; } const wxBitmap &CEdgeList::GetIcon() { static wxBitmap* icon = NULL; if(icon == NULL)icon = new wxBitmap(wxImage(wxGetApp().GetResFolder() + _T("/icons/edges.png"))); return *icon; } const wxBitmap &CVertexList::GetIcon() { static wxBitmap* icon = NULL; if(icon == NULL)icon = new wxBitmap(wxImage(wxGetApp().GetResFolder() + _T("/icons/vertices.png"))); return *icon; } void CreateFacesAndEdges(TopoDS_Shape shape, CFaceList* faces, CEdgeList* edges, CVertexList* vertices) { // create index maps TopTools_IndexedMapOfShape faceMap; TopTools_IndexedMapOfShape edgeMap; TopTools_IndexedMapOfShape vertexMap; for (TopExp_Explorer explorer(shape, TopAbs_FACE); explorer.More(); explorer.Next()) { faceMap.Add(explorer.Current()); } for (TopExp_Explorer explorer(shape, TopAbs_EDGE); explorer.More(); explorer.Next()) { edgeMap.Add(explorer.Current()); } for (TopExp_Explorer explorer(shape, TopAbs_VERTEX); explorer.More(); explorer.Next()) { vertexMap.Add(explorer.Current()); } std::vector<CFace*> face_array; face_array.resize(faceMap.Extent() + 1); std::vector<CEdge*> edge_array; edge_array.resize(edgeMap.Extent() + 1); std::vector<HVertex*> vertex_array; vertex_array.resize(vertexMap.Extent() + 1); // create the edge objects for(int i = 1;i<=edgeMap.Extent();i++) { const TopoDS_Shape &s = edgeMap(i); CEdge* new_object = new CEdge(TopoDS::Edge(s)); edge_array[i] = new_object; } // create the vertex objects for(int i = 1;i<=vertexMap.Extent();i++) { const TopoDS_Shape &s = vertexMap(i); HVertex* new_object = new HVertex(TopoDS::Vertex(s)); vertex_array[i] = new_object; } // add the edges in their face loop order std::set<CEdge*> edges_added; std::set<HVertex*> vertices_added; // create the face objects for(int i = 1;i<=faceMap.Extent();i++) { const TopoDS_Shape &s = faceMap(i); CFace* new_face_object = new CFace(TopoDS::Face(s)); faces->Add(new_face_object); face_array[i] = new_face_object; // create the loop objects TopTools_IndexedMapOfShape loopMap; for (TopExp_Explorer explorer(s, TopAbs_WIRE); explorer.More(); explorer.Next()) { loopMap.Add(explorer.Current()); } TopoDS_Wire outerWire=BRepTools::OuterWire(new_face_object->Face()); int outer_index = loopMap.FindIndex(outerWire); for(int i = 1;i<=loopMap.Extent();i++) { const TopoDS_Shape &s = loopMap(i); CLoop* new_loop_object = new CLoop(TopoDS::Wire(s)); new_face_object->m_loops.push_back(new_loop_object); if(outer_index == i)new_loop_object->m_is_outer = true; new_loop_object->m_pface = new_face_object; // find the loop's edges for(BRepTools_WireExplorer explorer(TopoDS::Wire(s)); explorer.More(); explorer.Next()) { CEdge* e = edge_array[edgeMap.FindIndex(explorer.Current())]; new_loop_object->m_edges.push_back(e); // add the edge if(edges_added.find(e) == edges_added.end()) { edges->Add(e); edges_added.insert(e); } // add the vertex HVertex* v = vertex_array[vertexMap.FindIndex(explorer.CurrentVertex())]; if(vertices_added.find(v) == vertices_added.end()) { vertices->Add(v); vertices_added.insert(v); } } } } // find the vertices' edges for(unsigned int i = 1; i<vertex_array.size(); i++) { HVertex* v = vertex_array[i]; TopTools_IndexedMapOfShape vertexEdgeMap; for (TopExp_Explorer expEdge(v->Vertex(), TopAbs_EDGE); expEdge.More(); expEdge.Next()) { vertexEdgeMap.Add(expEdge.Current()); } for(int i = 1; i<=vertexEdgeMap.Extent(); i++) { const TopoDS_Shape &s = vertexEdgeMap(i); CEdge* e = edge_array[edgeMap.FindIndex(s)]; v->m_edges.push_back(e); } } // find the faces' edges for(unsigned int i = 1; i<face_array.size(); i++) { CFace* face = face_array[i]; TopTools_IndexedMapOfShape faceEdgeMap; for (TopExp_Explorer expEdge(face->Face(), TopAbs_EDGE); expEdge.More(); expEdge.Next()) { faceEdgeMap.Add(expEdge.Current()); } for(int i = 1; i<=faceEdgeMap.Extent(); i++) { const TopoDS_Shape &s = faceEdgeMap(i); CEdge* e = edge_array[edgeMap.FindIndex(s)]; face->m_edges.push_back(e); e->m_faces.push_back(face); bool sense = (s.IsEqual(e->Edge()) == Standard_True); e->m_face_senses.push_back(sense); } } } wxString TopoDS_ToString(const TopoDS_Shape& shape, int level) { wxString rtn = (level == 0) ? "Shape:\n" : ""; if (shape.IsNull()) { rtn += "NULL\n"; return rtn; } wxString indent('\t', level); wxString format; rtn += indent; rtn += "{"; switch(shape.ShapeType()) { case TopAbs_COMPOUND: rtn += "COMPOUND"; break; case TopAbs_COMPSOLID: rtn += "COMPSOLID"; break; case TopAbs_SOLID: rtn += "SOLID"; break; case TopAbs_SHELL: rtn += "SHELL"; break; case TopAbs_FACE: { rtn += "FACE"; BRepAdaptor_Surface surface(TopoDS::Face(shape)); switch(surface.GetType()) { case GeomAbs_Plane: format = "type: plane"; break; case GeomAbs_Cylinder: format = "type: cylinder"; break; case GeomAbs_Cone: format = "type: cone"; break; case GeomAbs_Sphere: format = "type: sphere"; break; case GeomAbs_Torus: format = "type: torus"; break; case GeomAbs_BezierSurface: format = "type: bezier_surface"; break; case GeomAbs_BSplineSurface: format = "type: bspline_surface"; break; case GeomAbs_SurfaceOfRevolution: format = "type: revolution_surface"; break; case GeomAbs_SurfaceOfExtrusion: format = "type: extrusion_surface"; break; case GeomAbs_OffsetSurface: format = "type: offset_surface"; break; case GeomAbs_OtherSurface: format = "type: other_surface"; break; } } break; case TopAbs_WIRE: rtn += "WIRE"; break; case TopAbs_EDGE: { rtn += "EDGE"; BRepAdaptor_Curve curve(TopoDS::Edge(shape)); switch(curve.GetType()) { case GeomAbs_Line: format = "type: line"; break; case GeomAbs_Circle: format = "type: circle"; break; case GeomAbs_Ellipse: format = "type: ellipse"; break; case GeomAbs_Hyperbola: format = "type: hyperbola"; break; case GeomAbs_Parabola: format = "type: parabola"; break; case GeomAbs_BezierCurve: format = "type: bezier"; break; case GeomAbs_BSplineCurve: format = "type: bspline"; break; case GeomAbs_OtherCurve: format = "type: other"; break; } } break; case TopAbs_VERTEX: { rtn += "VERTEX"; gp_Pnt pnt = BRep_Tool::Pnt(TopoDS::Vertex(shape)); format = wxString::Format("point: (%f, %f, %f)", pnt.X(), pnt.Y(), pnt.Z()); } break; case TopAbs_SHAPE: rtn += "SHAPE"; break; } TopAbs_Orientation orientation = shape.Orientation(); rtn += ", closed: "; rtn += (shape.Closed() ? "true" : "false"); rtn += ", orientation: "; rtn += ((orientation == TopAbs_FORWARD) ? "forward" : (orientation == TopAbs_REVERSED) ? "reversed" : (orientation == TopAbs_INTERNAL) ? "internal" : (orientation == TopAbs_EXTERNAL) ? "external" : "<unknown>"); if (!format.IsEmpty()) rtn += ", " + format; rtn += "}\n"; for (TopoDS_Iterator iter2(shape); iter2.More(); iter2.Next()) { // Recurse rtn += TopoDS_ToString(iter2.Value(), level + 1); } return rtn; }
26.758842
103
0.616318
[ "shape", "vector", "solid" ]
b8d6aeecb0181797c4dd6ae32edd330b5b62c9a3
11,956
cpp
C++
tester/tests/test_merge_float_cpu_random.cpp
01org/idlf
6f9b1986bc67856e3019ae3c83ed8d4b8a3b3972
[ "BSD-3-Clause" ]
375
2015-03-03T12:09:07.000Z
2019-01-14T09:22:56.000Z
tester/tests/test_merge_float_cpu_random.cpp
intel/idlf
6f9b1986bc67856e3019ae3c83ed8d4b8a3b3972
[ "BSD-3-Clause" ]
5
2015-07-14T02:48:45.000Z
2016-07-08T08:02:06.000Z
tester/tests/test_merge_float_cpu_random.cpp
01org/idlf
6f9b1986bc67856e3019ae3c83ed8d4b8a3b3972
[ "BSD-3-Clause" ]
103
2015-04-18T10:57:02.000Z
2018-07-29T23:56:12.000Z
/* Copyright (c) 2015, Intel Corporation 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 Intel 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. */ #include "tester/common/test_aggregator.h" #include "tester/common/workflows_for_tests.h" // If test needs a workflow definition #include "tester/common/test_common_tools.h" #include "common/time_control.h" class test_merge_float_cpu_random : public test_base { private: tested_device* current_tested_device; nn_device_interface_0_t* di; bool init(); bool done(); void cleanup(); nn::data<float>* cpu_layer_merge( nn::data<float>& work_item1, nn::data<float>& work_item2 ); // If test needs a workflow definition workflows_for_tests_base *workflow_wrapper; nn_workflow_t *workflow; // Add current test specific variables uint32_t input_size_x, input_size_y, input_size_z, output_size_x, output_size_y, output_size_z; public: test_merge_float_cpu_random() { test_description = "merge float cpu random"; }; ~test_merge_float_cpu_random() {}; bool run(); }; nn::data<float>* test_merge_float_cpu_random::cpu_layer_merge( nn::data<float>& work_item1, nn::data<float>& work_item2) { auto batch = work_item1.size[3]; auto output = new nn::data<float>( output_size_z, output_size_x, output_size_y, batch ); size_t tabXYZN[4] = { (size_t) (output_size_x), (size_t) (output_size_y), (size_t) (output_size_z), (size_t) (batch) }; for(uint32_t n = 0; n < batch; ++n) for(uint32_t z = 0; z < output_size_z; ++z) for(uint32_t x = 0; x < output_size_x; ++x) for(uint32_t y = 0; y < output_size_y; ++y) output->at(z, x, y, n) = ( z < input_size_z )? work_item1.at(z, x, y, n) : work_item2.at(z - input_size_z, x, y, n); return output; } bool test_merge_float_cpu_random::init() { bool init_ok = true; test_measurement_result init_result; init_result.description = "INIT: " + test_description; C_time_control init_timer; try { if( devices != nullptr ) { current_tested_device = devices->get( "device_cpu" + dynamic_library_extension ); di = current_tested_device->get_device_interface(); } else throw std::runtime_error( std::string( "Can't find aggregator of devices" ) ); // TODO: here code of test initiation: // If test needs a workflow definition workflow_wrapper = workflows_for_tests::instance().get( "workflow_merge" ); workflow = workflow_wrapper->init_test_workflow( di ); if( workflow == nullptr ) throw std::runtime_error( "Workflow has not been initialized" ); input_size_x = workflow->input[0]->output_format->format_3d.size[0]; input_size_y = workflow->input[0]->output_format->format_3d.size[1]; input_size_z = workflow->input[0]->output_format->format_3d.size[2]; output_size_x = workflow->input[0]->use[0].item->output_format->format_3d.size[0]; output_size_y = workflow->input[0]->use[0].item->output_format->format_3d.size[1]; output_size_z = workflow->input[0]->use[0].item->output_format->format_3d.size[2]; // END test initiation init_ok = true; } catch( std::runtime_error &error ) { init_result << "error: " + std::string( error.what() ); init_ok = false; } catch( std::exception &error ) { init_result << "error: " + std::string( error.what() ); init_ok = false; } catch( ... ) { init_result << "unknown error"; init_ok = false; } init_timer.tock(); init_result.time_consumed = init_timer.get_time_diff(); init_result.clocks_consumed = init_timer.get_clocks_diff(); init_result.passed = init_ok; tests_results << init_result; return init_ok; } bool test_merge_float_cpu_random::run() { bool run_ok = true; test_measurement_result run_result; run_result.description = "RUN SUMMARY: " + test_description; C_time_control run_timer; std::cout << "-> Testing: " << test_description << std::endl; try { if( !init() ) throw std::runtime_error( "init() returns false so can't run test" ); run_timer.tick(); //start time measurement run_result << std::string( "run test with " + current_tested_device->get_device_description() ); NN_WORKLOAD_DATA_TYPE input_formats[] = { NN_WORKLOAD_DATA_TYPE_F32_ZXY_BATCH, NN_WORKLOAD_DATA_TYPE_F32_ZXY_BATCH }; NN_WORKLOAD_DATA_TYPE output_format = NN_WORKLOAD_DATA_TYPE_F32_ZXY_BATCH; for( auto batch : { 1, 8, 48 } ) { // --------------------------------------------------------------------------------------------------------- { // simple sample pattern of test with time measuring: bool local_ok = true; test_measurement_result local_result; local_result.description = "RUN PART: (batch " + std::to_string( batch ) + ") execution of " + test_description; C_time_control local_timer; // begin local test auto input1 = new nn::data<float>( input_size_z, input_size_x, input_size_y, batch ); if(input1 == nullptr) throw std::runtime_error("unable to create input1 for batch = " +std::to_string(batch)); auto input2 = new nn::data<float>( input_size_z, input_size_x, input_size_y, batch ); if(input2 == nullptr) { delete input1; throw std::runtime_error("unable to create input2 for batch = " +std::to_string(batch)); } auto workload_output = new nn::data<float>( output_size_z, output_size_x, output_size_y, batch ); if(workload_output == nullptr) { delete input1; delete input2; throw std::runtime_error("unable to create workload_output for batch = " +std::to_string(batch)); } nn_data_populate( workload_output, 0.0f ); nn_data_populate( input1, -255.0f, 255.0f ); nn_data_populate( input2, -255.0f, 255.0f ); nn_workload_t *workload = nullptr; nn_data_t *input_array[2] = { input1, input2 }; nn::data<float> *output_array_cmpl[1] = { nn::data_cast<float, 0>(workload_output) }; auto status = di->workflow_compile_function( &workload, di->device, workflow, input_formats, &output_format, batch ); if( !workload ) throw std::runtime_error( "workload compilation failed for batch = " + std::to_string( batch ) + " status: " + std::to_string( status ) ); di->workload_execute_function( workload, reinterpret_cast<void**>(input_array), reinterpret_cast<void**>(output_array_cmpl), &status ); auto naive_output = cpu_layer_merge( *input1, *input2 ); if(naive_output == nullptr) { delete input1; delete input2; delete workload_output; throw std::runtime_error("unable to create naive_output for batch = " +std::to_string(batch)); } local_ok = compare_data(workload_output, naive_output); // end of local test // summary: local_timer.tock(); local_result.time_consumed = local_timer.get_time_diff(); local_result.clocks_consumed = local_timer.get_clocks_diff(); local_result.passed = local_ok; tests_results << local_result; run_ok = run_ok && local_ok; if( input1 ) delete input1; if( input2 ) delete input2; if( workload_output ) delete workload_output; if( naive_output ) delete naive_output; if( workload ) delete workload; } // The pattern, of complex instruction above, can be multiplied // END of run tests // --------------------------------------------------------------------------------------------------------- } } catch( std::runtime_error &error ) { run_result << "error: " + std::string( error.what() ); run_ok = false; } catch( std::exception &error ) { run_result << "error: " + std::string( error.what() ); run_ok = false; } catch( ... ) { run_result << "unknown error"; run_ok = false; } run_timer.tock(); run_result.time_consumed = run_timer.get_time_diff(); run_result.clocks_consumed = run_timer.get_clocks_diff(); run_result.passed = run_ok; tests_results << run_result; if( !done() ) run_ok = false; std::cout << "<- Test " << (run_ok ? "passed" : "failed") << std::endl; return run_ok; } bool test_merge_float_cpu_random::done() { bool done_ok = true; test_measurement_result done_result; done_result.description = "DONE: " + test_description; C_time_control done_timer; try { // TODO: here clean up after the test // If the test used definition of workflow: if( workflow_wrapper != nullptr ) workflow_wrapper->cleanup(); // END of cleaning done_ok = true; } catch( std::runtime_error &error ) { done_result << "error: " + std::string( error.what() ); done_ok = false; } catch( std::exception &error ) { done_result << "error: " + std::string( error.what() ); done_ok = false; } catch( ... ) { done_result << "unknown error"; done_ok = false; } done_timer.tock(); done_result.time_consumed = done_timer.get_time_diff(); done_result.clocks_consumed = done_timer.get_clocks_diff(); done_result.passed = done_ok; tests_results << done_result; return done_ok; } // Code below creates 'attach_' object in anonymous namespace at global scope. // This ensures, that object itself is not visible to other compilation units // and it's constructor is ran befor main execution starts. // The sole function of this construction is attaching this test to // library of tests (singleton command pattern). namespace { struct attach { test_merge_float_cpu_random test; attach() { test_aggregator::instance().add( &test ); } }; attach attach_; }
42.098592
151
0.621613
[ "object" ]
b8deef42cceb62789877a8f1b1d862901a731d2f
2,074
cpp
C++
ICCardSystem/CEmployeeDB.cpp
zaxai/ICCardSystem
ccd02bd90d0481b90061d3c99bd40c2adc54ebd4
[ "MIT" ]
2
2019-03-30T01:58:59.000Z
2019-09-12T06:50:37.000Z
ICCardSystem/CEmployeeDB.cpp
zaxai/ICCardSystem
ccd02bd90d0481b90061d3c99bd40c2adc54ebd4
[ "MIT" ]
null
null
null
ICCardSystem/CEmployeeDB.cpp
zaxai/ICCardSystem
ccd02bd90d0481b90061d3c99bd40c2adc54ebd4
[ "MIT" ]
3
2018-12-21T18:31:27.000Z
2020-12-07T05:44:22.000Z
#include "stdafx.h" #include "CEmployeeDB.h" CEmployeeDB::CEmployeeDB() : m_strPathDB(_T("")) { m_strPathDB = ZUtil::GetExeCatalogPath() + _T("\\Data.mdb"); CreateTable(); } CEmployeeDB::~CEmployeeDB() { } void CEmployeeDB::CreateTable() { ZSqlite3 zsql; zsql.OpenDB(m_strPathDB); CString strSql; strSql = _T("CREATE TABLE Employee (\ ID INT PRIMARY KEY NOT NULL,\ Name NVARCHAR(100),\ Password NVARCHAR(100),\ GradeID INT,\ IsUsing INT\ )"); zsql.ExecSQL(strSql); } bool CEmployeeDB::Insert(const CEmployee & employee) { CreateTable(); ZSqlite3 zsql; zsql.OpenDB(m_strPathDB); CString strSql, strError; strSql.Format(_T("INSERT INTO Employee VALUES (%d,'%s','%s',%d,%d)"), employee.GetID(), employee.GetName(), employee.GetPassword(),employee.GetGradeID(), employee.IsUsing()); if (zsql.ExecSQL(strSql, &strError) == ZSqlite3::ERROR_OK) return true; else return false; } bool CEmployeeDB::Update(const CEmployee & employee) { CreateTable(); ZSqlite3 zsql; zsql.OpenDB(m_strPathDB); CString strSql, strError; strSql.Format(_T("UPDATE Employee SET Name='%s',Password='%s',GradeID=%d,IsUsing=%d WHERE ID=%d"), employee.GetName(), employee.GetPassword(), employee.GetGradeID(), employee.IsUsing(), employee.GetID()); if (zsql.ExecSQL(strSql, &strError) == ZSqlite3::ERROR_OK) return true; else return false; } bool CEmployeeDB::Select(const CString & strSql, std::vector<CEmployee> & vec_employee) { vec_employee.clear(); std::vector<std::vector <CString>> vec2_strData; ZSqlite3 zsql; zsql.OpenDB(m_strPathDB); CString strError; int nRtn = zsql.GetTable(strSql, vec2_strData, &strError); int nRow = vec2_strData.size(); if (nRow) { int nColumn = vec2_strData[0].size(); if (nColumn == 5) { for (int i = 1; i < nRow; ++i) { CEmployee employee(_ttoi(vec2_strData[i][0]), vec2_strData[i][1], vec2_strData[i][2], _ttoi(vec2_strData[i][3]), _ttoi(vec2_strData[i][4])); vec_employee.push_back(employee); } } } if (nRtn == ZSqlite3::ERROR_OK) return true; else return false; }
23.83908
205
0.690935
[ "vector" ]
b8e6f5846f74080776b97ee0b7ef72a5488fb02a
37,658
cpp
C++
docs/template_plugin/tests/functional/op_reference/convert.cpp
ethz-asl/openvino
b4ad7a1755b4799f92ef042bacc719ec3c0c1cbd
[ "Apache-2.0" ]
null
null
null
docs/template_plugin/tests/functional/op_reference/convert.cpp
ethz-asl/openvino
b4ad7a1755b4799f92ef042bacc719ec3c0c1cbd
[ "Apache-2.0" ]
11
2021-08-04T10:06:53.000Z
2022-02-21T13:10:58.000Z
docs/template_plugin/tests/functional/op_reference/convert.cpp
ethz-asl/openvino
b4ad7a1755b4799f92ef042bacc719ec3c0c1cbd
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <gtest/gtest.h> #include <ie_core.hpp> #include <ie_ngraph_utils.hpp> #include <ngraph/ngraph.hpp> #include <shared_test_classes/base/layer_test_utils.hpp> #include <tuple> #include "base_reference_test.hpp" using namespace reference_tests; using namespace ngraph; using namespace InferenceEngine; struct ConvertParams { template <class IT, class OT> ConvertParams(const ngraph::PartialShape& shape, const ngraph::element::Type& iType, const ngraph::element::Type& oType, const std::vector<IT>& iValues, const std::vector<OT>& oValues, size_t iSize = 0, size_t oSize = 0) : pshape(shape), inType(iType), outType(oType), inputData(CreateBlob(iType, iValues, iSize)), refData(CreateBlob(oType, oValues, oSize)) {} ngraph::PartialShape pshape; ngraph::element::Type inType; ngraph::element::Type outType; InferenceEngine::Blob::Ptr inputData; InferenceEngine::Blob::Ptr refData; }; class ReferenceConvertLayerTest : public testing::TestWithParam<ConvertParams>, public CommonReferenceTest { public: void SetUp() override { auto params = GetParam(); function = CreateFunction(params.pshape, params.inType, params.outType); inputData = {params.inputData}; refOutData = {params.refData}; } static std::string getTestCaseName(const testing::TestParamInfo<ConvertParams>& obj) { auto param = obj.param; std::ostringstream result; result << "shape=" << param.pshape << "_"; result << "iType=" << param.inType << "_"; result << "oType=" << param.outType; return result.str(); } private: static std::shared_ptr<Function> CreateFunction(const PartialShape& input_shape, const element::Type& input_type, const element::Type& expected_output_type) { const auto in = std::make_shared<op::Parameter>(input_type, input_shape); const auto convert = std::make_shared<op::Convert>(in, expected_output_type); return std::make_shared<Function>(NodeVector {convert}, ParameterVector {in}); } }; TEST_P(ReferenceConvertLayerTest, CompareWithHardcodedRefs) { Exec(); } INSTANTIATE_TEST_SUITE_P( smoke_Convert_With_Hardcoded_Refs, ReferenceConvertLayerTest, ::testing::Values( // destination boolean ConvertParams(ngraph::PartialShape {2, 3}, ngraph::element::u8, ngraph::element::boolean, std::vector<uint8_t> {0, 12, 23, 0, std::numeric_limits<uint8_t>::lowest(), std::numeric_limits<uint8_t>::max()}, std::vector<char> {0, 1, 1, 0, 0, 1}), ConvertParams(ngraph::PartialShape {2, 3}, ngraph::element::i32, ngraph::element::boolean, std::vector<int32_t> {0, -12, 23, 0, std::numeric_limits<int32_t>::lowest(), std::numeric_limits<int32_t>::max()}, std::vector<char> {0, 1, 1, 0, 1, 1}), ConvertParams(ngraph::PartialShape {3, 3}, ngraph::element::f32, ngraph::element::boolean, std::vector<float> {0.f, 1.5745f, 0.12352f, 0.f, std::numeric_limits<float>::lowest(), std::numeric_limits<float>::max(), std::numeric_limits<float>::min(), std::numeric_limits<float>::infinity(), -std::numeric_limits<float>::infinity()}, std::vector<char> {0, 1, 1, 0, 1, 1, 1, 1, 1}), // destination bf16 ConvertParams(ngraph::PartialShape {1, 1, 3, 5}, ngraph::element::f32, ngraph::element::bf16, std::vector<float> {0.5f, 1.5f, 0.5f, 2.5f, 1.5f, 0.5f, 3.5f, 2.5f, 0.5f, 0.5f, 2.5f, 0.5f, 0.5f, 0.5f, 1.5f}, std::vector<bfloat16> {0.5f, 1.5f, 0.5f, 2.5f, 1.5f, 0.5f, 3.5f, 2.5f, 0.5f, 0.5f, 2.5f, 0.5f, 0.5f, 0.5f, 1.5f}), ConvertParams(ngraph::PartialShape {11}, ngraph::element::u8, ngraph::element::bf16, std::vector<uint8_t> {0, 10, 15, 20, 43, 56, 78, 99, 102, 130, 142}, std::vector<bfloat16> {0, 10, 15, 20, 43, 56, 78, 99, 102, 130, 142}), // destination f16 ConvertParams(ngraph::PartialShape {1, 1, 3, 5}, ngraph::element::f32, ngraph::element::f16, std::vector<float> {0.5f, 1.5f, 0.5f, 2.5f, 1.5f, 0.5f, 3.5f, 2.5f, 0.5f, 0.5f, 2.5f, 0.5f, 0.5f, 0.5f, 1.5f}, std::vector<float16> {0.5f, 1.5f, 0.5f, 2.5f, 1.5f, 0.5f, 3.5f, 2.5f, 0.5f, 0.5f, 2.5f, 0.5f, 0.5f, 0.5f, 1.5f}), ConvertParams(ngraph::PartialShape {11}, ngraph::element::u8, ngraph::element::f16, std::vector<uint8_t> {0, 10, 15, 20, 43, 56, 78, 99, 102, 130, 142}, std::vector<float16> {0, 10, 15, 20, 43, 56, 78, 99, 102, 130, 142}), // destination f32 ConvertParams(ngraph::PartialShape {2, 2}, ngraph::element::u1, ngraph::element::f32, std::vector<uint8_t> {0xA0}, std::vector<float> {1.0f, 0.0f, 1.0f, 0.0f}, 4), ConvertParams(ngraph::PartialShape {2, 2}, ngraph::element::u4, ngraph::element::f32, std::vector<uint8_t> {0xFB, 0x0A}, std::vector<float> {15.0f, 11.0f, 0.0f, 10.0f}, 4), ConvertParams(ngraph::PartialShape {2, 2}, ngraph::element::u8, ngraph::element::f32, std::vector<uint8_t> {255, 128, 32, 0}, std::vector<float> {255.0f, 128.0f, 32.0f, 0.0f}), ConvertParams(ngraph::PartialShape {2, 2}, ngraph::element::u16, ngraph::element::f32, std::vector<uint16_t> {64000, 32000, 128, 0}, std::vector<float> {64000.0f, 32000.0f, 128.0f, 0.0f}), ConvertParams(ngraph::PartialShape {2, 2}, ngraph::element::u32, ngraph::element::f32, std::vector<uint32_t> {4000000, 2000000, 128, 0}, std::vector<float> {4000000.0f, 2000000.0f, 128.0f, 0.0f}), ConvertParams(ngraph::PartialShape {2, 2}, ngraph::element::u64, ngraph::element::f32, std::vector<uint64_t> {4000000, 2000000, 128, 0}, std::vector<float> {4000000.0f, 2000000.0f, 128.0f, 0.0f}), ConvertParams(ngraph::PartialShape {2, 2}, ngraph::element::i4, ngraph::element::f32, std::vector<uint8_t> {0xFE, 0xF2}, std::vector<float> {-1.0f, -2.0f, -1.0f, 2.0f}, 4), ConvertParams(ngraph::PartialShape {2, 2}, ngraph::element::i8, ngraph::element::f32, std::vector<int8_t> {-127, -0, 0, 127}, std::vector<float> {-127.0f, -0.0f, 0.0f, 127.0f}), ConvertParams(ngraph::PartialShape {2, 2}, ngraph::element::i16, ngraph::element::f32, std::vector<int16_t> {-32000, -0, 0, 32000}, std::vector<float> {-32000.0f, -0.0f, 0.0f, 32000.0f}), ConvertParams(ngraph::PartialShape {2, 2}, ngraph::element::i32, ngraph::element::f32, std::vector<int32_t> {-64000, -0, 0, 64000}, std::vector<float> {-64000.0f, -0.0f, 0.0f, 64000.0f}), ConvertParams(ngraph::PartialShape {2, 2}, ngraph::element::i64, ngraph::element::f32, std::vector<int64_t> {-64000, -0, 0, 64000}, std::vector<float> {-64000.0f, -0.0f, 0.0f, 64000.0f}), ConvertParams(ngraph::PartialShape {1, 1, 3, 5}, ngraph::element::bf16, ngraph::element::f32, std::vector<bfloat16> {0.5f, 1.5f, 0.5f, 2.5f, 1.5f, 0.5f, 3.5f, 2.5f, 0.5f, 0.5f, 2.5f, 0.5f, 0.5f, 0.5f, 1.5f}, std::vector<float> {0.5f, 1.5f, 0.5f, 2.5f, 1.5f, 0.5f, 3.5f, 2.5f, 0.5f, 0.5f, 2.5f, 0.5f, 0.5f, 0.5f, 1.5f}), ConvertParams(ngraph::PartialShape {1, 1, 3, 5}, ngraph::element::f16, ngraph::element::f32, std::vector<float16> {0.5f, 1.5f, 0.5f, 2.5f, 1.5f, 0.5f, 3.5f, 2.5f, 0.5f, 0.5f, 2.5f, 0.5f, 0.5f, 0.5f, 1.5f}, std::vector<float> {0.5f, 1.5f, 0.5f, 2.5f, 1.5f, 0.5f, 3.5f, 2.5f, 0.5f, 0.5f, 2.5f, 0.5f, 0.5f, 0.5f, 1.5f}), ConvertParams(ngraph::PartialShape {1, 1, 3, 5}, ngraph::element::f32, ngraph::element::f32, std::vector<float> {0.5f, 1.5f, 0.5f, 2.5f, 1.5f, 0.5f, 3.5f, 2.5f, 0.5f, 0.5f, 2.5f, 0.5f, 0.5f, 0.5f, 1.5f}, std::vector<float> {0.5f, 1.5f, 0.5f, 2.5f, 1.5f, 0.5f, 3.5f, 2.5f, 0.5f, 0.5f, 2.5f, 0.5f, 0.5f, 0.5f, 1.5f}), // destination i4 ConvertParams(ngraph::PartialShape {4}, ngraph::element::u1, ngraph::element::i4, std::vector<uint8_t> {0xA0}, std::vector<uint8_t> {0x10, 0x10}, 4, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u4, ngraph::element::i4, std::vector<uint8_t> {0x12, 0x03}, std::vector<uint8_t> {0x12, 0x03}, 4, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u8, ngraph::element::i4, std::vector<uint8_t> {1, 2, 0, 3}, std::vector<uint8_t> {0x12, 0x03}, 4, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u16, ngraph::element::i4, std::vector<uint16_t> {1, 2, 0, 3}, std::vector<uint8_t> {0x12, 0x03}, 4, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u32, ngraph::element::i4, std::vector<uint32_t> {1, 2, 0, 3}, std::vector<uint8_t> {0x12, 0x03}, 4, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u64, ngraph::element::i4, std::vector<uint64_t> {1, 2, 0, 3}, std::vector<uint8_t> {0x12, 0x03}, 4, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i4, ngraph::element::i4, std::vector<uint8_t> {0xFE, 0x03}, std::vector<uint8_t> {0xFE, 0x03}, 4, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i8, ngraph::element::i4, std::vector<int8_t> {-1, -2, 2, 3}, std::vector<uint8_t> {0xFE, 0x23}, 4, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i16, ngraph::element::i4, std::vector<int16_t> {-1, -2, 2, 3}, std::vector<uint8_t> {0xFE, 0x23}, 4, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i32, ngraph::element::i4, std::vector<int32_t> {-1, -2, 2, 3}, std::vector<uint8_t> {0xFE, 0x23}, 4, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i64, ngraph::element::i4, std::vector<int64_t> {-1, -2, 2, 3}, std::vector<uint8_t> {0xFE, 0x23}, 4, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::f16, ngraph::element::i4, std::vector<ngraph::float16> {-1, -2, 0, 3}, std::vector<uint8_t> {0xFE, 0x03}, 4, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::bf16, ngraph::element::i4, std::vector<ngraph::bfloat16> {-1, -2, 0, 3}, std::vector<uint8_t> {0xFE, 0x03}, 4, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::f32, ngraph::element::i4, std::vector<float> {-1, -2, 2, 3}, std::vector<uint8_t> {0xFE, 0x23}, 4, 4), // destination i8 ConvertParams(ngraph::PartialShape {8}, ngraph::element::u1, ngraph::element::i8, std::vector<uint8_t> {0x81}, std::vector<int8_t> {1, 0, 0, 0, 0, 0, 0, 1}, 8), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u4, ngraph::element::i8, std::vector<uint8_t> {0x21, 0x43}, std::vector<int8_t> {2, 1, 4, 3}, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u8, ngraph::element::i8, std::vector<uint8_t> {1, 2, 0, 3}, std::vector<int8_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u16, ngraph::element::i8, std::vector<uint16_t> {1, 2, 0, 3}, std::vector<int8_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u32, ngraph::element::i8, std::vector<uint32_t> {1, 2, 0, 3}, std::vector<int8_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u64, ngraph::element::i8, std::vector<uint64_t> {1, 2, 0, 3}, std::vector<int8_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i4, ngraph::element::i8, std::vector<uint8_t> {0x21, 0x43}, std::vector<int8_t> {2, 1, 4, 3}, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i8, ngraph::element::i8, std::vector<int8_t> {-1, -2, 2, 3}, std::vector<int8_t> {-1, -2, 2, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i16, ngraph::element::i8, std::vector<int16_t> {-1, -2, 2, 3}, std::vector<int8_t> {-1, -2, 2, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i32, ngraph::element::i8, std::vector<int32_t> {-1, -2, 2, 3}, std::vector<int8_t> {-1, -2, 2, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i64, ngraph::element::i8, std::vector<int64_t> {-1, -2, 2, 3}, std::vector<int8_t> {-1, -2, 2, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::f16, ngraph::element::i8, std::vector<ngraph::float16> {-1, -2, 0, 3}, std::vector<int8_t> {-1, -2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::bf16, ngraph::element::i8, std::vector<ngraph::bfloat16> {-1, -2, 0, 3}, std::vector<int8_t> {-1, -2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::f32, ngraph::element::i8, std::vector<float> {-1, -2, 2, 3}, std::vector<int8_t> {-1, -2, 2, 3}), // destination i16 ConvertParams(ngraph::PartialShape {8}, ngraph::element::u1, ngraph::element::i16, std::vector<uint8_t> {0x81}, std::vector<int16_t> {1, 0, 0, 0, 0, 0, 0, 1}, 8), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u4, ngraph::element::i16, std::vector<uint8_t> {0x21, 0x43}, std::vector<int16_t> {2, 1, 4, 3}, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u8, ngraph::element::i16, std::vector<uint8_t> {1, 2, 0, 3}, std::vector<int16_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u16, ngraph::element::i16, std::vector<uint16_t> {1, 2, 0, 3}, std::vector<int16_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u32, ngraph::element::i16, std::vector<uint32_t> {1, 2, 0, 3}, std::vector<int16_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u64, ngraph::element::i16, std::vector<uint64_t> {1, 2, 0, 3}, std::vector<int16_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i4, ngraph::element::i16, std::vector<uint8_t> {0x21, 0x43}, std::vector<int16_t> {2, 1, 4, 3}, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i8, ngraph::element::i16, std::vector<int8_t> {-1, -2, 2, 3}, std::vector<int16_t> {-1, -2, 2, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i16, ngraph::element::i16, std::vector<int16_t> {-1, -2, 2, 3}, std::vector<int16_t> {-1, -2, 2, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i32, ngraph::element::i16, std::vector<int32_t> {-1, -2, 2, 3}, std::vector<int16_t> {-1, -2, 2, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i64, ngraph::element::i16, std::vector<int64_t> {-1, -2, 2, 3}, std::vector<int16_t> {-1, -2, 2, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::f16, ngraph::element::i16, std::vector<ngraph::float16> {-1, -2, 0, 3}, std::vector<int16_t> {-1, -2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::bf16, ngraph::element::i16, std::vector<ngraph::bfloat16> {-1, -2, 0, 3}, std::vector<int16_t> {-1, -2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::f32, ngraph::element::i16, std::vector<float> {-1, -2, 2, 3}, std::vector<int16_t> {-1, -2, 2, 3}), // destination i32 ConvertParams(ngraph::PartialShape {8}, ngraph::element::u1, ngraph::element::i32, std::vector<uint8_t> {0x81}, std::vector<int32_t> {1, 0, 0, 0, 0, 0, 0, 1}, 8), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u4, ngraph::element::i32, std::vector<uint8_t> {0x21, 0x43}, std::vector<int32_t> {2, 1, 4, 3}, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u8, ngraph::element::i32, std::vector<uint8_t> {1, 2, 0, 3}, std::vector<int32_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u16, ngraph::element::i32, std::vector<uint16_t> {1, 2, 0, 3}, std::vector<int32_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u32, ngraph::element::i32, std::vector<uint32_t> {1, 2, 0, 3}, std::vector<int32_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u64, ngraph::element::i32, std::vector<uint64_t> {1, 2, 0, 3}, std::vector<int32_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i4, ngraph::element::i32, std::vector<uint8_t> {0x21, 0x43}, std::vector<int32_t> {2, 1, 4, 3}, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i8, ngraph::element::i32, std::vector<int8_t> {-1, -2, 2, 3}, std::vector<int32_t> {-1, -2, 2, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i16, ngraph::element::i32, std::vector<int16_t> {-1, -2, 2, 3}, std::vector<int32_t> {-1, -2, 2, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i32, ngraph::element::i32, std::vector<int32_t> {-1, -2, 2, 3}, std::vector<int32_t> {-1, -2, 2, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i64, ngraph::element::i32, std::vector<int64_t> {-1, -2, 2, 3}, std::vector<int32_t> {-1, -2, 2, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::f16, ngraph::element::i32, std::vector<ngraph::float16> {-1, -2, 0, 3}, std::vector<int32_t> {-1, -2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::bf16, ngraph::element::i32, std::vector<ngraph::bfloat16> {-1, -2, 0, 3}, std::vector<int32_t> {-1, -2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::f32, ngraph::element::i32, std::vector<float> {-1, -2, 2, 3}, std::vector<int32_t> {-1, -2, 2, 3}), // destination i64 ConvertParams(ngraph::PartialShape {8}, ngraph::element::u1, ngraph::element::i64, std::vector<uint8_t> {0x81}, std::vector<int64_t> {1, 0, 0, 0, 0, 0, 0, 1}, 8), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u4, ngraph::element::i64, std::vector<uint8_t> {0x21, 0x43}, std::vector<int64_t> {2, 1, 4, 3}, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u8, ngraph::element::i64, std::vector<uint8_t> {1, 2, 0, 3}, std::vector<int64_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u16, ngraph::element::i64, std::vector<uint16_t> {1, 2, 0, 3}, std::vector<int64_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u32, ngraph::element::i64, std::vector<uint32_t> {1, 2, 0, 3}, std::vector<int64_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u64, ngraph::element::i64, std::vector<uint64_t> {1, 2, 0, 3}, std::vector<int64_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i4, ngraph::element::i64, std::vector<uint8_t> {0x21, 0x43}, std::vector<int64_t> {2, 1, 4, 3}, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i8, ngraph::element::i64, std::vector<int8_t> {-1, -2, 2, 3}, std::vector<int64_t> {-1, -2, 2, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i16, ngraph::element::i64, std::vector<int16_t> {-1, -2, 2, 3}, std::vector<int64_t> {-1, -2, 2, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i32, ngraph::element::i64, std::vector<int32_t> {-1, -2, 2, 3}, std::vector<int64_t> {-1, -2, 2, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i64, ngraph::element::i64, std::vector<int64_t> {-1, -2, 2, 3}, std::vector<int64_t> {-1, -2, 2, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::f16, ngraph::element::i64, std::vector<ngraph::float16> {-1, -2, 0, 3}, std::vector<int64_t> {-1, -2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::bf16, ngraph::element::i64, std::vector<ngraph::bfloat16> {-1, -2, 0, 3}, std::vector<int64_t> {-1, -2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::f32, ngraph::element::i64, std::vector<float> {-1, -2, 2, 3}, std::vector<int64_t> {-1, -2, 2, 3}), // destination u1 ConvertParams(ngraph::PartialShape {8}, ngraph::element::u1, ngraph::element::u1, std::vector<uint8_t> {0xA0}, std::vector<uint8_t> {0xA0}, 8, 8), ConvertParams(ngraph::PartialShape {8}, ngraph::element::u4, ngraph::element::u1, std::vector<uint8_t> {0x10, 0x01, 0x00, 0x00}, std::vector<uint8_t> {0x90}, 8, 8), ConvertParams(ngraph::PartialShape {8}, ngraph::element::u8, ngraph::element::u1, std::vector<uint8_t> {1, 0, 1, 0, 0, 0, 0, 1}, std::vector<uint8_t> {0xA1}, 8, 8), ConvertParams(ngraph::PartialShape {8}, ngraph::element::u16, ngraph::element::u1, std::vector<uint16_t> {1, 0, 1, 0, 0, 0, 0, 1}, std::vector<uint8_t> {0xA1}, 8, 8), ConvertParams(ngraph::PartialShape {8}, ngraph::element::u32, ngraph::element::u1, std::vector<uint32_t> {1, 0, 1, 0, 0, 0, 0, 1}, std::vector<uint8_t> {0xA1}, 8, 8), ConvertParams(ngraph::PartialShape {8}, ngraph::element::u64, ngraph::element::u1, std::vector<uint64_t> {1, 0, 1, 0, 0, 0, 0, 1}, std::vector<uint8_t> {0xA1}, 8, 8), ConvertParams(ngraph::PartialShape {8}, ngraph::element::i4, ngraph::element::u1, std::vector<uint8_t> {0x10, 0x01, 0x00, 0x00}, std::vector<uint8_t> {0x90}, 8, 8), ConvertParams(ngraph::PartialShape {8}, ngraph::element::i8, ngraph::element::u1, std::vector<int8_t> {1, 0, 1, 0, 0, 0, 0, 1}, std::vector<uint8_t> {0xA1}, 8, 8), ConvertParams(ngraph::PartialShape {8}, ngraph::element::i16, ngraph::element::u1, std::vector<int16_t> {1, 0, 1, 0, 0, 0, 0, 1}, std::vector<uint8_t> {0xA1}, 8, 8), ConvertParams(ngraph::PartialShape {8}, ngraph::element::i32, ngraph::element::u1, std::vector<int32_t> {1, 0, 1, 0, 0, 0, 0, 1}, std::vector<uint8_t> {0xA1}, 8, 8), ConvertParams(ngraph::PartialShape {8}, ngraph::element::i64, ngraph::element::u1, std::vector<int64_t> {1, 0, 1, 0, 0, 0, 0, 1}, std::vector<uint8_t> {0xA1}, 8, 8), ConvertParams(ngraph::PartialShape {8}, ngraph::element::f16, ngraph::element::u1, std::vector<ngraph::float16> {1, 0, 1, 0, 0, 0, 0, 1}, std::vector<uint8_t> {0xA1}, 8, 8), ConvertParams(ngraph::PartialShape {8}, ngraph::element::bf16, ngraph::element::u1, std::vector<ngraph::bfloat16> {1, 0, 1, 0, 0, 0, 0, 1}, std::vector<uint8_t> {0xA1}, 8, 8), ConvertParams(ngraph::PartialShape {8}, ngraph::element::f32, ngraph::element::u1, std::vector<float> {1, 0, 1, 0, 0, 0, 0, 1}, std::vector<uint8_t> {0xA1}, 8, 8), // destination u4 ConvertParams(ngraph::PartialShape {4}, ngraph::element::u1, ngraph::element::u4, std::vector<uint8_t> {0xA0}, std::vector<uint8_t> {0x10, 0x10}, 4, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u4, ngraph::element::u4, std::vector<uint8_t> {0x12, 0x03}, std::vector<uint8_t> {0x12, 0x03}, 4, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u8, ngraph::element::u4, std::vector<uint8_t> {1, 2, 0, 3}, std::vector<uint8_t> {0x12, 0x03}, 4, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u16, ngraph::element::u4, std::vector<uint16_t> {1, 2, 0, 3}, std::vector<uint8_t> {0x12, 0x03}, 4, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u32, ngraph::element::u4, std::vector<uint32_t> {1, 2, 0, 3}, std::vector<uint8_t> {0x12, 0x03}, 4, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u64, ngraph::element::u4, std::vector<uint64_t> {1, 2, 0, 3}, std::vector<uint8_t> {0x12, 0x03}, 4, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i4, ngraph::element::u4, std::vector<uint8_t> {0xFE, 0x03}, std::vector<uint8_t> {0xFE, 0x03}, 4, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i8, ngraph::element::u4, std::vector<int8_t> {-1, -2, 2, 3}, std::vector<uint8_t> {0xFE, 0x23}, 4, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i16, ngraph::element::u4, std::vector<int16_t> {-1, -2, 2, 3}, std::vector<uint8_t> {0xFE, 0x23}, 4, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i32, ngraph::element::u4, std::vector<int32_t> {-1, -2, 2, 3}, std::vector<uint8_t> {0xFE, 0x23}, 4, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i64, ngraph::element::u4, std::vector<int64_t> {-1, -2, 2, 3}, std::vector<uint8_t> {0xFE, 0x23}, 4, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::f16, ngraph::element::u4, std::vector<ngraph::float16> {-1, -2, 0, 3}, std::vector<uint8_t> {0xFE, 0x03}, 4, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::bf16, ngraph::element::u4, std::vector<ngraph::bfloat16> {-1, -2, 0, 3}, std::vector<uint8_t> {0xFE, 0x03}, 4, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::f32, ngraph::element::u4, std::vector<float> {-1, -2, 2, 3}, std::vector<uint8_t> {0xFE, 0x23}, 4, 4), // destination u8 ConvertParams(ngraph::PartialShape {8}, ngraph::element::u1, ngraph::element::u8, std::vector<uint8_t> {0x81}, std::vector<uint8_t> {1, 0, 0, 0, 0, 0, 0, 1}, 8), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u4, ngraph::element::u8, std::vector<uint8_t> {0x21, 0x43}, std::vector<uint8_t> {2, 1, 4, 3}, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u8, ngraph::element::u8, std::vector<uint8_t> {1, 2, 0, 3}, std::vector<uint8_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u16, ngraph::element::u8, std::vector<uint16_t> {1, 2, 0, 3}, std::vector<uint8_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u32, ngraph::element::u8, std::vector<uint32_t> {1, 2, 0, 3}, std::vector<uint8_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u64, ngraph::element::u8, std::vector<uint64_t> {1, 2, 0, 3}, std::vector<uint8_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i4, ngraph::element::u8, std::vector<uint8_t> {0x21, 0x43}, std::vector<uint8_t> {2, 1, 4, 3}, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i8, ngraph::element::u8, std::vector<int8_t> {1, 2, 2, 3}, std::vector<uint8_t> {1, 2, 2, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i16, ngraph::element::u8, std::vector<int16_t> {1, 2, 2, 3}, std::vector<uint8_t> {1, 2, 2, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i32, ngraph::element::u8, std::vector<int32_t> {1, 2, 2, 3}, std::vector<uint8_t> {1, 2, 2, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i64, ngraph::element::u8, std::vector<int64_t> {1, 2, 2, 3}, std::vector<uint8_t> {1, 2, 2, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::f16, ngraph::element::u8, std::vector<ngraph::float16> {1, 2, 0, 3}, std::vector<uint8_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::bf16, ngraph::element::u8, std::vector<ngraph::bfloat16> {1, 2, 0, 3}, std::vector<uint8_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::f32, ngraph::element::u8, std::vector<float> {1, 2, 2, 3}, std::vector<uint8_t> {1, 2, 2, 3}), // destination u16 ConvertParams(ngraph::PartialShape {8}, ngraph::element::u1, ngraph::element::u16, std::vector<uint8_t> {0x81}, std::vector<uint16_t> {1, 0, 0, 0, 0, 0, 0, 1}, 8), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u4, ngraph::element::u16, std::vector<uint8_t> {0x21, 0x43}, std::vector<uint16_t> {2, 1, 4, 3}, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u8, ngraph::element::u16, std::vector<uint8_t> {1, 2, 0, 3}, std::vector<uint16_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u16, ngraph::element::u16, std::vector<uint16_t> {1, 2, 0, 3}, std::vector<uint16_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u32, ngraph::element::u16, std::vector<uint32_t> {1, 2, 0, 3}, std::vector<uint16_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u64, ngraph::element::u16, std::vector<uint64_t> {1, 2, 0, 3}, std::vector<uint16_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i4, ngraph::element::u16, std::vector<uint8_t> {0x21, 0x43}, std::vector<uint16_t> {2, 1, 4, 3}, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i8, ngraph::element::u16, std::vector<int8_t> {1, 2, 2, 3}, std::vector<uint16_t> {1, 2, 2, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i16, ngraph::element::u16, std::vector<int16_t> {1, 2, 2, 3}, std::vector<uint16_t> {1, 2, 2, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i32, ngraph::element::u16, std::vector<int32_t> {1, 2, 2, 3}, std::vector<uint16_t> {1, 2, 2, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i64, ngraph::element::u16, std::vector<int64_t> {1, 2, 2, 3}, std::vector<uint16_t> {1, 2, 2, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::f16, ngraph::element::u16, std::vector<ngraph::float16> {1, 2, 0, 3}, std::vector<uint16_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::bf16, ngraph::element::u16, std::vector<ngraph::bfloat16> {1, 2, 0, 3}, std::vector<uint16_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::f32, ngraph::element::u16, std::vector<float> {1, 2, 2, 3}, std::vector<uint16_t> {1, 2, 2, 3}), // destination u32 ConvertParams(ngraph::PartialShape {8}, ngraph::element::u1, ngraph::element::u32, std::vector<uint8_t> {0x81}, std::vector<uint32_t> {1, 0, 0, 0, 0, 0, 0, 1}, 8), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u4, ngraph::element::u32, std::vector<uint8_t> {0x21, 0x43}, std::vector<uint32_t> {2, 1, 4, 3}, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u8, ngraph::element::u32, std::vector<uint8_t> {1, 2, 0, 3}, std::vector<uint32_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u16, ngraph::element::u32, std::vector<uint16_t> {1, 2, 0, 3}, std::vector<uint32_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u32, ngraph::element::u32, std::vector<uint32_t> {1, 2, 0, 3}, std::vector<uint32_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u64, ngraph::element::u32, std::vector<uint64_t> {1, 2, 0, 3}, std::vector<uint32_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i4, ngraph::element::u32, std::vector<uint8_t> {0x21, 0x43}, std::vector<uint32_t> {2, 1, 4, 3}, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i8, ngraph::element::u32, std::vector<int8_t> {1, 2, 2, 3}, std::vector<uint32_t> {1, 2, 2, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i16, ngraph::element::u32, std::vector<int16_t> {1, 2, 2, 3}, std::vector<uint32_t> {1, 2, 2, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i32, ngraph::element::u32, std::vector<int32_t> {1, 2, 2, 3}, std::vector<uint32_t> {1, 2, 2, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i64, ngraph::element::u32, std::vector<int64_t> {1, 2, 2, 3}, std::vector<uint32_t> {1, 2, 2, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::f16, ngraph::element::u32, std::vector<ngraph::float16> {1, 2, 0, 3}, std::vector<uint32_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::bf16, ngraph::element::u32, std::vector<ngraph::bfloat16> {1, 2, 0, 3}, std::vector<uint32_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::f32, ngraph::element::u32, std::vector<float> {1, 2, 2, 3}, std::vector<uint32_t> {1, 2, 2, 3}), // destination u64 ConvertParams(ngraph::PartialShape {8}, ngraph::element::u1, ngraph::element::u64, std::vector<uint8_t> {0x81}, std::vector<uint64_t> {1, 0, 0, 0, 0, 0, 0, 1}, 8), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u4, ngraph::element::u64, std::vector<uint8_t> {0x21, 0x43}, std::vector<uint64_t> {2, 1, 4, 3}, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u8, ngraph::element::u64, std::vector<uint8_t> {1, 2, 0, 3}, std::vector<uint64_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u16, ngraph::element::u64, std::vector<uint16_t> {1, 2, 0, 3}, std::vector<uint64_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u32, ngraph::element::u64, std::vector<uint32_t> {1, 2, 0, 3}, std::vector<uint64_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::u64, ngraph::element::u64, std::vector<uint64_t> {1, 2, 0, 3}, std::vector<uint64_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i4, ngraph::element::u64, std::vector<uint8_t> {0x21, 0x43}, std::vector<uint64_t> {2, 1, 4, 3}, 4), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i8, ngraph::element::u64, std::vector<int8_t> {1, 2, 2, 3}, std::vector<uint64_t> {1, 2, 2, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i16, ngraph::element::u64, std::vector<int16_t> {1, 2, 2, 3}, std::vector<uint64_t> {1, 2, 2, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i32, ngraph::element::u64, std::vector<int32_t> {1, 2, 2, 3}, std::vector<uint64_t> {1, 2, 2, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::i64, ngraph::element::u64, std::vector<int64_t> {1, 2, 2, 3}, std::vector<uint64_t> {1, 2, 2, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::f16, ngraph::element::u64, std::vector<ngraph::float16> {1, 2, 0, 3}, std::vector<uint64_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::bf16, ngraph::element::u64, std::vector<ngraph::bfloat16> {1, 2, 0, 3}, std::vector<uint64_t> {1, 2, 0, 3}), ConvertParams(ngraph::PartialShape {4}, ngraph::element::f32, ngraph::element::u64, std::vector<float> {1, 2, 2, 3}, std::vector<uint64_t> {1, 2, 2, 3})), ReferenceConvertLayerTest::getTestCaseName);
85.006772
160
0.572999
[ "shape", "vector" ]
b8f02f5f980f2a2bad4057192ea2fe915587b030
31,870
cpp
C++
src/lower/lowerer_impl.cpp
ychen306/taco
c81053c0388eeaecbb6e59403dadefe2a7ad0f2d
[ "MIT" ]
null
null
null
src/lower/lowerer_impl.cpp
ychen306/taco
c81053c0388eeaecbb6e59403dadefe2a7ad0f2d
[ "MIT" ]
null
null
null
src/lower/lowerer_impl.cpp
ychen306/taco
c81053c0388eeaecbb6e59403dadefe2a7ad0f2d
[ "MIT" ]
null
null
null
#include "taco/lower/lowerer_impl.h" #include "taco/index_notation/index_notation.h" #include "taco/index_notation/index_notation_nodes.h" #include "taco/index_notation/index_notation_visitor.h" #include "taco/ir/ir.h" #include "ir/ir_generators.h" #include "taco/ir/simplify.h" #include "taco/lower/iterator.h" #include "taco/lower/merge_lattice.h" #include "mode_access.h" #include "taco/util/collections.h" using namespace std; using namespace taco::ir; using taco::util::combine; namespace taco { class LowererImpl::Visitor : public IndexNotationVisitorStrict { public: Visitor(LowererImpl* impl) : impl(impl) {} Stmt lower(IndexStmt stmt) { this->stmt = Stmt(); IndexStmtVisitorStrict::visit(stmt); return this->stmt; } Expr lower(IndexExpr expr) { this->expr = Expr(); IndexExprVisitorStrict::visit(expr); return this->expr; } private: LowererImpl* impl; Expr expr; Stmt stmt; using IndexNotationVisitorStrict::visit; void visit(const AssignmentNode* node) { stmt = impl->lowerAssignment(node); } void visit(const ForallNode* node) { stmt = impl->lowerForall(node); } void visit(const WhereNode* node) { stmt = impl->lowerWhere(node); } void visit(const MultiNode* node) { stmt = impl->lowerMulti(node); } void visit(const SequenceNode* node) { stmt = impl->lowerSequence(node); } void visit(const AccessNode* node) { expr = impl->lowerAccess(node); } void visit(const LiteralNode* node) { expr = impl->lowerLiteral(node); } void visit(const NegNode* node) { expr = impl->lowerNeg(node); } void visit(const AddNode* node) { expr = impl->lowerAdd(node); } void visit(const SubNode* node) { expr = impl->lowerSub(node); } void visit(const MulNode* node) { expr = impl->lowerMul(node); } void visit(const DivNode* node) { expr = impl->lowerDiv(node); } void visit(const SqrtNode* node) { expr = impl->lowerSqrt(node); } void visit(const ReductionNode* node) { taco_ierror << "Reduction nodes not supported in concrete index notation"; } }; LowererImpl::LowererImpl() : visitor(new Visitor(this)) { } /// Convert index notation tensor variables to IR pointer variables. static vector<Expr> createVars(const vector<TensorVar>& tensorVars, map<TensorVar, Expr>* vars) { taco_iassert(vars != nullptr); vector<Expr> irVars; for (auto& var : tensorVars) { Expr irVar = Var::make(var.getName(), var.getType().getDataType(), true, true); irVars.push_back(irVar); vars->insert({var, irVar}); } return irVars; } /// Replace scalar tensor pointers with stack scalar for lowering static Stmt declareScalarArgumentVar(TensorVar var, bool zero, map<TensorVar, Expr>* tensorVars) { Datatype type = var.getType().getDataType(); Expr varValueIR = Var::make(var.getName() + "_val", type, false, false); Expr init = (zero) ? ir::Literal::zero(type) : Load::make(GetProperty::make(tensorVars->at(var), TensorProperty::Values)); tensorVars->find(var)->second = varValueIR; return VarDecl::make(varValueIR, init); } Stmt LowererImpl::lower(IndexStmt stmt, string name, bool assemble, bool compute) { this->assemble = assemble; this->compute = compute; // Create result and parameter variables vector<TensorVar> results = getResultTensorVars(stmt); vector<TensorVar> arguments = getInputTensorVars(stmt); vector<TensorVar> temporaries = getTemporaryTensorVars(stmt); // Convert tensor results, arguments and temporaries to IR variables map<TensorVar, Expr> resultVars; vector<Expr> resultsIR = createVars(results, &resultVars); tensorVars.insert(resultVars.begin(), resultVars.end()); vector<Expr> argumentsIR = createVars(arguments, &tensorVars); vector<Expr> temporariesIR = createVars(temporaries, &tensorVars); // Create iterators iterators = createIterators(stmt, tensorVars, &indexVars, &coordVars); map<TensorVar, Expr> scalars; vector<Stmt> headerStmts; vector<Stmt> footerStmts; // Declare and initialize dimension variables vector<IndexVar> indexVars = getIndexVars(stmt); for (auto& ivar : indexVars) { Expr dimension; match(stmt, function<void(const AssignmentNode*,Matcher*)>([&]( const AssignmentNode* n, Matcher* m) { m->match(n->rhs); if (!dimension.defined()) { auto ivars = n->lhs.getIndexVars(); int loc = (int)distance(ivars.begin(), find(ivars.begin(),ivars.end(), ivar)); dimension = GetProperty::make(tensorVars.at(n->lhs.getTensorVar()), TensorProperty::Dimension, loc); } }), function<void(const AccessNode*)>([&](const AccessNode* n) { auto ivars = n->indexVars; int loc = (int)distance(ivars.begin(), find(ivars.begin(),ivars.end(), ivar)); dimension = GetProperty::make(tensorVars.at(n->tensorVar), TensorProperty::Dimension, loc); }) ); dimensions.insert({ivar, dimension}); } // Declare and initialize scalar results and arguments if (generateComputeCode()) { for (auto& result : results) { if (isScalar(result.getType())) { taco_iassert(!util::contains(scalars, result)); taco_iassert(util::contains(tensorVars, result)); scalars.insert({result, tensorVars.at(result)}); headerStmts.push_back(declareScalarArgumentVar(result, true, &tensorVars)); } } for (auto& argument : arguments) { if (isScalar(argument.getType())) { taco_iassert(!util::contains(scalars, argument)); taco_iassert(util::contains(tensorVars, argument)); scalars.insert({argument, tensorVars.at(argument)}); headerStmts.push_back(declareScalarArgumentVar(argument, false, &tensorVars)); } } } // Allocate memory for scalar results if (generateAssembleCode()) { for (auto& result : results) { if (result.getOrder() == 0) { Expr resultIR = resultVars.at(result); Expr vals = GetProperty::make(resultIR, TensorProperty::Values); Expr valsSize = GetProperty::make(resultIR, TensorProperty::ValuesSize); headerStmts.push_back(Assign::make(valsSize, 1)); headerStmts.push_back(Allocate::make(vals, valsSize)); } } } // Allocate and initialize append and insert mode indices Stmt initResultArrays = generateInitResultArrays(getResultAccesses(stmt)); // Declare, allocate, and initialize temporaries Stmt declareTemporaries = generateTemporaryDecls(temporaries, scalars); // Lower the index statement to compute and/or assemble Stmt body = lower(stmt); // Post-process result modes. Stmt finalizeResultModes = generateModeFinalizes(getResultAccesses(stmt)); // If assembling without computing then allocate value memory at the end Stmt postAllocValues = generatePostAllocValues(getResultAccesses(stmt)); // Store scalar stack variables back to results. if (generateComputeCode()) { for (auto& result : results) { if (isScalar(result.getType())) { taco_iassert(util::contains(scalars, result)); taco_iassert(util::contains(tensorVars, result)); Expr resultIR = scalars.at(result); Expr varValueIR = tensorVars.at(result); Expr valuesArrIR = GetProperty::make(resultIR, TensorProperty::Values); footerStmts.push_back(Store::make(valuesArrIR, 0, varValueIR)); } } } // Create function Stmt header = (headerStmts.size() > 0) ? Block::make(headerStmts) : Stmt(); Stmt footer = (footerStmts.size() > 0) ? Block::make(footerStmts) : Stmt(); return Function::make(name, resultsIR, argumentsIR, Block::blanks({header, declareTemporaries, initResultArrays, body, finalizeResultModes, postAllocValues, footer})); } Stmt LowererImpl::lowerAssignment(Assignment assignment) { TensorVar result = assignment.getLhs().getTensorVar(); if (generateComputeCode()) { Expr var = getTensorVar(result); Expr rhs = lower(assignment.getRhs()); // Assignment to scalar variables. if (isScalar(result.getType())) { if (!assignment.getOperator().defined()) { return Assign::make(var, rhs); } else { taco_iassert(isa<taco::Add>(assignment.getOperator())); return Assign::make(var, ir::Add::make(var,rhs)); } } // Assignments to tensor variables (non-scalar). else { Expr values = GetProperty::make(var, TensorProperty::Values); Expr size = GetProperty::make(var, TensorProperty::ValuesSize); Expr loc = generateValueLocExpr(assignment.getLhs()); // When we're assembling while computing we need to allocate more // value memory as we write to the values array. Iterator lastIterator = getIterators(assignment.getLhs()).back(); Stmt resizeValueArray; if (generateAssembleCode() && lastIterator.hasAppend()) { resizeValueArray = doubleSizeIfFull(values, size, loc); } Stmt computeStmt = Store::make(values, loc, rhs); return resizeValueArray.defined() ? Block::make({resizeValueArray, computeStmt}) : computeStmt; } } // We're only assembling so defer allocating value memory to the end when // we'll know exactly how much we need. else if (generateAssembleCode()) { // TODO return Stmt(); } // We're neither assembling or computing so we emit nothing. else { return Stmt(); } taco_unreachable; return Stmt(); } static pair<vector<Iterator>, vector<Iterator>> splitAppenderAndInserters(const vector<Iterator>& results) { vector<Iterator> appenders; vector<Iterator> inserters; // TODO: Choose insert when the current forall is nested inside a reduction for (auto& result : results) { taco_iassert(result.hasAppend() || result.hasInsert()) << "Results must support append or insert"; if (result.hasAppend()) { appenders.push_back(result); } else { taco_iassert(result.hasInsert()); inserters.push_back(result); } } return {appenders, inserters}; } Stmt LowererImpl::lowerForall(Forall forall) { MergeLattice lattice = MergeLattice::make(forall, getIteratorMap()); // Emit a loop that iterates over over a single iterator (optimization) if (lattice.getPoints().size() == 1 && lattice.getIterators().size() == 1) { MergePoint point = lattice.getPoints()[0]; Iterator iterator = lattice.getIterators()[0]; vector<Iterator> locaters = point.getLocators(); vector<Iterator> appenders; vector<Iterator> inserters; tie(appenders, inserters) = splitAppenderAndInserters(point.getResults()); // Emit dimension coordinate iteration loop if (iterator.isDimensionIterator()) { return lowerForallDimension(forall, point.getLocators(), inserters, appenders); } // Emit position iteration loop else if (iterator.hasPosIter()) { return lowerForallPosition(forall, iterator, locaters, inserters, appenders); } // Emit coordinate iteration loop else { taco_iassert(iterator.hasCoordIter()); taco_not_supported_yet; return Stmt(); } } // Emit general loops to merge multiple iterators else { return lowerForallMerge(forall, lattice); } } Stmt LowererImpl::lowerForallDimension(Forall forall, vector<Iterator> locators, vector<Iterator> inserters, vector<Iterator> appenders) { Expr coordinate = getCoordinateVar(forall.getIndexVar()); Stmt header = lowerForallHeader(forall, locators, inserters, appenders); Stmt body = lowerForallBody(coordinate, forall.getStmt(), locators, inserters, appenders); Stmt footer = lowerForallFooter(forall, locators, inserters, appenders); // Emit loop with preamble and postamble Expr dimension = getDimension(forall.getIndexVar()); return Block::blanks({header, For::make(coordinate, 0, dimension, 1, body), footer }); } Stmt LowererImpl::lowerForallCoordinate(Forall forall, Iterator iterator, vector<Iterator> locaters, vector<Iterator> inserters, vector<Iterator> appenders) { taco_not_supported_yet; return Stmt(); } Stmt LowererImpl::lowerForallPosition(Forall forall, Iterator iterator, vector<Iterator> locators, vector<Iterator> inserters, vector<Iterator> appenders) { Expr coordinate = getCoordinateVar(forall.getIndexVar()); Expr coordinateArray= iterator.posAccess(getCoords(iterator)).getResults()[0]; Stmt declareCoordinate = VarDecl::make(coordinate, coordinateArray); Stmt header = lowerForallHeader(forall, locators, inserters, appenders); Stmt body = lowerForallBody(coordinate, forall.getStmt(), locators, inserters, appenders); Stmt footer = lowerForallFooter(forall, locators, inserters, appenders); // Loop with preamble and postamble ModeFunction bounds = iterator.posBounds(); return Block::blanks({header, bounds.compute(), For::make(iterator.getPosVar(), bounds[0], bounds[1], 1, Block::make({declareCoordinate, body})), footer }); } Stmt LowererImpl::lowerForallMerge(Forall forall, MergeLattice lattice) { Expr coordinate = getCoordinateVar(forall.getIndexVar()); vector<Iterator> iterators = lattice.getIterators(); // Declare and initialize range iterator position variables Stmt declPosVarIterators = generateDeclPosVarIterators(iterators); // One loop for each merge lattice point lp Stmt loops = lowerMergeLoops(coordinate, forall.getStmt(), lattice); return Block::make({declPosVarIterators, loops}); } Stmt LowererImpl::lowerMergeLoops(ir::Expr coordinate, IndexStmt stmt, MergeLattice lattice) { vector<Stmt> result; for (MergePoint point : lattice.getPoints()) { MergeLattice sublattice = lattice.subLattice(point); Stmt mergeLoop = lowerMergeLoop(coordinate, stmt, sublattice); result.push_back(mergeLoop); } return Block::make(result); } Stmt LowererImpl::lowerMergeLoop(ir::Expr coordinate, IndexStmt stmt, MergeLattice lattice) { vector<Iterator> iterators = lattice.getIterators(); // Merge range iterator coordinate variables Stmt mergeCoordinates = generateMergeCoordinates(coordinate, iterators); // Emit located position variables // TODO // One case for each child lattice point lp Stmt cases = lowerMergeCases(coordinate, stmt, lattice); /// While loop over rangers return While::make(generateNoneExhausted(iterators), Block::make({mergeCoordinates, cases})); } Stmt LowererImpl::lowerMergeCases(ir::Expr coordinate, IndexStmt stmt, MergeLattice lattice) { vector<Stmt> result; // Just one iterator so no conditionals if (lattice.getIterators().size() == 1) { Stmt body = Comment::make("..."); vector<Iterator> appenders; vector<Iterator> inserters; tie(appenders, inserters) = splitAppenderAndInserters(lattice.getResults()); result.push_back(lowerForallBody(coordinate, stmt, {},inserters,appenders)); } else { vector<pair<Expr,Stmt>> cases; for (MergePoint point : lattice.getPoints()) { vector<Iterator> iterators = point.getIterators(); Stmt body = Stmt(); if (iterators.size() == 1) { cases.push_back({true, body}); } else { // Conditionals to execute code for the intersection cases vector<Expr> coordComparisons; for (Iterator iterator : iterators) { coordComparisons.push_back(Eq::make(iterator.getCoordVar(), coordinate)); } Expr expr = conjunction(coordComparisons); cases.push_back({expr, body}); } } } return Block::make(result); } Stmt LowererImpl::lowerForallBody(Expr coordinate, IndexStmt stmt, vector<Iterator> locators, vector<Iterator> inserters, vector<Iterator> appenders) { // Insert positions Stmt declInserterPosVars = generateDeclLocatePosVars(inserters); // Locate positions Stmt declLocatorPosVars = generateDeclLocatePosVars(locators); // Code of loop body statement Stmt body = lower(stmt); // Code to append coordinates Stmt appendCoordinate = generateAppendCoordinate(appenders, coordinate); // Code to increment append position variables Stmt incrementAppendPositionVars = generateAppendPosVarIncrements(appenders); return Block::make({declInserterPosVars, declLocatorPosVars, body, appendCoordinate, incrementAppendPositionVars }); } Stmt LowererImpl::lowerForallHeader(Forall forall, vector<Iterator> locaters, vector<Iterator> inserters, vector<Iterator> appenders) { // Pre-allocate/initialize memory of value arrays that are full below this // loops index variable Stmt preInitValues = generatePreInitValues(forall.getIndexVar(), getResultAccesses(forall)); return preInitValues; } /// Lower a forall loop footer. Stmt LowererImpl::lowerForallFooter(Forall forall, vector<Iterator> locaters, vector<Iterator> inserters, vector<Iterator> appenders) { // Code to append positions Stmt appendPositions = generateAppendPositions(appenders); return appendPositions; } Stmt LowererImpl::lowerWhere(Where where) { // TODO: Either initialise or re-initialize temporary memory Stmt producer = lower(where.getProducer()); Stmt consumer = lower(where.getConsumer()); return Block::make({producer, consumer}); } Stmt LowererImpl::lowerSequence(Sequence sequence) { Stmt definition = lower(sequence.getDefinition()); Stmt mutation = lower(sequence.getMutation()); return Block::make({definition, mutation}); } Stmt LowererImpl::lowerMulti(Multi multi) { Stmt stmt1 = lower(multi.getStmt1()); Stmt stmt2 = lower(multi.getStmt2()); return Block::make({stmt1, stmt2}); } Expr LowererImpl::lowerAccess(Access access) { TensorVar var = access.getTensorVar(); Expr varIR = getTensorVar(var); return (isScalar(var.getType())) ? varIR : Load::make(GetProperty::make(varIR, TensorProperty::Values), generateValueLocExpr(access)); } Expr LowererImpl::lowerLiteral(Literal) { taco_not_supported_yet; return Expr(); } Expr LowererImpl::lowerNeg(Neg neg) { return ir::Neg::make(lower(neg.getA())); } Expr LowererImpl::lowerAdd(Add add) { return ir::Add::make(lower(add.getA()), lower(add.getB())); } Expr LowererImpl::lowerSub(Sub sub) { return ir::Sub::make(lower(sub.getA()), lower(sub.getB())); } Expr LowererImpl::lowerMul(Mul mul) { return ir::Mul::make(lower(mul.getA()), lower(mul.getB())); } Expr LowererImpl::lowerDiv(Div div) { return ir::Div::make(lower(div.getA()), lower(div.getB())); } Expr LowererImpl::lowerSqrt(Sqrt sqrt) { return ir::Sqrt::make(lower(sqrt.getA())); } Stmt LowererImpl::lower(IndexStmt stmt) { return visitor->lower(stmt); } Expr LowererImpl::lower(IndexExpr expr) { return visitor->lower(expr); } bool LowererImpl::generateAssembleCode() const { return this->assemble; } bool LowererImpl::generateComputeCode() const { return this->compute; } Expr LowererImpl::getTensorVar(TensorVar tensorVar) const { taco_iassert(util::contains(this->tensorVars, tensorVar)) << tensorVar; return this->tensorVars.at(tensorVar); } Expr LowererImpl::getDimension(IndexVar indexVar) const { taco_iassert(util::contains(this->dimensions, indexVar)) << indexVar; return this->dimensions.at(indexVar); } Iterator LowererImpl::getIterator(ModeAccess modeAccess) const { return getIteratorMap().at(modeAccess); } std::vector<Iterator> LowererImpl::getIterators(Access access) const { vector<Iterator> result; TensorVar tensor = access.getTensorVar(); for (int i = 0; i < tensor.getOrder(); i++) { int mode = tensor.getFormat().getModeOrdering()[i]; result.push_back(getIterator(ModeAccess(access, mode+1))); } return result; } const map<ModeAccess, Iterator>& LowererImpl::getIteratorMap() const { return this->iterators; } Expr LowererImpl::getCoordinateVar(IndexVar indexVar) const { taco_iassert(util::contains(this->coordVars, indexVar)) << indexVar; return this->coordVars.at(indexVar); } Expr LowererImpl::getCoordinateVar(Iterator iterator) const { taco_iassert(util::contains(this->indexVars, iterator)) << iterator; auto& indexVar = this->indexVars.at(iterator); return this->getCoordinateVar(indexVar); } vector<Expr> LowererImpl::getCoords(Iterator iterator) const { vector<Expr> coords; do { coords.push_back(getCoordinateVar(iterator)); iterator = iterator.getParent(); } while (iterator.getParent().defined()); util::reverse(coords); return coords; } vector<Expr> LowererImpl::getCoords(vector<Iterator> iterators) { vector<Expr> result; for (auto& iterator : iterators) { result.push_back(iterator.getCoordVar()); } return result; } Stmt LowererImpl::generateInitResultArrays(vector<Access> writes) { vector<Stmt> result; for (auto& write : writes) { if (write.getTensorVar().getOrder() == 0) continue; vector<Stmt> initArrays; Expr parentSize = 1; auto iterators = getIterators(write); if (generateAssembleCode()) { for (auto& iterator : iterators) { Expr size; Stmt init; if (iterator.hasAppend()) { size = 0; init = iterator.getAppendInitLevel(parentSize, size); } else if (iterator.hasInsert()) { size = ir::Mul::make(parentSize, iterator.getSize()); init = iterator.getInsertInitLevel(parentSize, size); } else { taco_ierror << "Write iterator supports neither append nor insert"; } initArrays.push_back(init); // Declare position variable of append modes if (iterator.hasAppend()) { initArrays.push_back(VarDecl::make(iterator.getPosVar(), 0)); } parentSize = size; } // Pre-allocate memory for the value array if computing while assembling if (generateComputeCode() && !isDense(write.getTensorVar().getFormat())) { taco_iassert(iterators.size() > 0); Iterator lastIterator = iterators.back(); Expr tensor = getTensorVar(write.getTensorVar()); Expr valuesArr = GetProperty::make(tensor, TensorProperty::Values); Expr valsSize = GetProperty::make(tensor, TensorProperty::ValuesSize); Stmt assignValsSize = Assign::make(valsSize, DEFAULT_ALLOC_SIZE); Stmt allocVals = Allocate::make(valuesArr, valsSize); initArrays.push_back(Block::make({assignValsSize, allocVals})); } taco_iassert(initArrays.size() > 0); result.push_back(Block::make(initArrays)); } // Declare position variable for the last level else if (generateComputeCode()) { result.push_back(VarDecl::make(iterators.back().getPosVar(), 0)); } } return (result.size() > 0) ? Block::blanks(result) : Stmt(); } ir::Stmt LowererImpl::generateModeFinalizes(std::vector<Access> writes) { vector<Stmt> result; return (result.size() > 0) ? Block::make(result) : Stmt(); } Stmt LowererImpl::generateTemporaryDecls(vector<TensorVar> temporaries, map<TensorVar, Expr> scalars) { vector<Stmt> result; if (generateComputeCode()) { for (auto& temporary : temporaries) { if (isScalar(temporary.getType())) { taco_iassert(!util::contains(scalars, temporary)) << temporary; taco_iassert(util::contains(tensorVars, temporary)); scalars.insert({temporary, tensorVars.at(temporary)}); result.push_back(declareScalarArgumentVar(temporary,true,&tensorVars)); } } } return (result.size() > 0) ? Block::make(result) : Stmt(); } static vector<Iterator> getIteratorsFrom(IndexVar var, vector<Iterator> iterators) { vector<Iterator> result; bool found = false; for (Iterator iterator : iterators) { if (var == iterator.getIndexVar()) found = true; if (found) { result.push_back(iterator); } } return result; } static bool allInsert(vector<Iterator> iterators) { for (Iterator iterator : iterators) { if (!iterator.hasInsert()) { return false; } } return true; } Stmt LowererImpl::generatePreInitValues(IndexVar var, vector<Access> writes) { vector<Stmt> result; for (auto& write : writes) { Expr tensor = getTensorVar(write.getTensorVar()); Expr values = GetProperty::make(tensor, TensorProperty::Values); Expr valuesSizeVar = GetProperty::make(tensor, TensorProperty::ValuesSize); vector<Iterator> iterators = getIteratorsFrom(var, getIterators(write)); taco_iassert(iterators.size() > 0); if (!allInsert(iterators)) continue; Expr size = iterators[0].getSize(); for (size_t i = 1; i < iterators.size(); i++) { size = ir::Mul::make(size, iterators[i].getSize()); } if (generateAssembleCode()) { // Allocate value memory result.push_back(Assign::make(valuesSizeVar, size)); result.push_back(Allocate::make(values, valuesSizeVar)); } if (generateComputeCode()) { Expr i = Var::make(var.getName() + "z", Int()); result.push_back(For::make(i, 0,size,1, Store::make(values, i, 0.0))); } } return (result.size() > 0) ? Block::make(result) : Stmt(); } Stmt LowererImpl::generateDeclLocatePosVars(vector<Iterator> locaters) { vector<Stmt> result; for (Iterator& locateIterator : locaters) { ModeFunction locate = locateIterator.locate(getCoords(locateIterator)); taco_iassert(isValue(locate.getResults()[1], true)); Stmt declarePosVar = VarDecl::make(locateIterator.getPosVar(), locate.getResults()[0]); result.push_back(declarePosVar); } return (result.size() > 0) ? Block::make(result) : Stmt(); } Stmt LowererImpl::generateDeclPosVarIterators(vector<Iterator> iterators) { vector<Stmt> result; for (Iterator iterator : iterators) { taco_iassert(iterator.hasPosIter()); ModeFunction bounds = iterator.posBounds(); result.push_back(bounds.compute()); result.push_back(VarDecl::make(iterator.getIteratorVar(), bounds[0])); result.push_back(VarDecl::make(iterator.getEndVar(), bounds[1])); } return (result.size() > 0) ? Block::make(result) : Stmt(); } Stmt LowererImpl::generateMergeCoordinates(Expr coordinate, vector<Iterator> iterators) { taco_iassert(iterators.size() > 0); /// Just one iterator so it's coordinate var is the resolved coordinate. if (iterators.size() == 1) { ModeFunction posAccess = iterators[0].posAccess(getCoords(iterators[0])); return Block::make({posAccess.compute(), VarDecl::make(coordinate, posAccess[0]) }); } // Multiple iterators so we compute the min of their coordinate variables. vector<Stmt> result; vector<Expr> iteratorCoordVars; for (Iterator iterator : iterators) { taco_iassert(iterator.hasPosIter()); ModeFunction posAccess = iterator.posAccess(getCoords(iterator)); result.push_back(posAccess.compute()); result.push_back(VarDecl::make(iterator.getCoordVar(), posAccess[0])); } result.push_back(VarDecl::make(coordinate, Min::make(getCoords(iterators)))); return Block::make(result); } Stmt LowererImpl::generateAppendCoordinate(vector<Iterator> appenders, Expr coord) { vector<Stmt> result; if (generateAssembleCode()) { for (Iterator appender : appenders) { Expr pos = appender.getPosVar(); Stmt appendCoord = appender.getAppendCoord(pos, coord); result.push_back(appendCoord); } } return (result.size() > 0) ? Block::make(result) : Stmt(); } Stmt LowererImpl::generateAppendPositions(vector<Iterator> appenders) { vector<Stmt> result; if (generateAssembleCode()) { for (Iterator appender : appenders) { Expr pos = appender.getPosVar(); Expr parentPos = appender.getParent().getPosVar(); Stmt appendPos = appender.getAppendEdges(parentPos, ir::Sub::make(pos,1), pos); result.push_back(appendPos); } } return (result.size() > 0) ? Block::make(result) : Stmt(); } Stmt LowererImpl::generateAppendPosVarIncrements(vector<Iterator> appenders) { vector<Stmt> result; for (auto& appender : appenders) { Expr increment = ir::Add::make(appender.getPosVar(), 1); Stmt incrementPos = ir::Assign::make(appender.getPosVar(), increment); result.push_back(incrementPos); } return Block::make(result); } Stmt LowererImpl::generatePostAllocValues(vector<Access> writes) { if (generateComputeCode() || !generateAssembleCode()) { return Stmt(); } vector<Stmt> result; for (auto& write : writes) { if (write.getTensorVar().getOrder() == 0) continue; auto iterators = getIterators(write); taco_iassert(iterators.size() > 0); Iterator lastIterator = iterators[0]; if (lastIterator.hasAppend()) { Expr tensor = getTensorVar(write.getTensorVar()); Expr valuesArr = GetProperty::make(tensor, TensorProperty::Values); Expr valuesSize = GetProperty::make(tensor, TensorProperty::ValuesSize); result.push_back(Assign::make(valuesSize, lastIterator.getPosVar())); result.push_back(Allocate::make(valuesArr, valuesSize)); } } return Block::make(result); } Expr LowererImpl::generateValueLocExpr(Access access) const { if (isScalar(access.getTensorVar().getType())) { return ir::Literal::make(0); } int loc = (int)access.getIndexVars().size(); Iterator it = getIterator(ModeAccess(access, loc)); return it.getPosVar(); } Expr LowererImpl::generateNoneExhausted(std::vector<Iterator> iterators) { taco_iassert(!iterators.empty()); vector<Expr> result; for (const auto& iterator : iterators) { taco_iassert(!iterator.isFull()); Expr iterUnexhausted = Lt::make(iterator.getIteratorVar(), iterator.getEndVar()); result.push_back(iterUnexhausted); } return (!result.empty()) ? conjunction(result) : Lt::make(iterators[0].getIteratorVar(), iterators[0].getEndVar()); } }
35.137817
83
0.649137
[ "vector" ]
b8f221a9ff06958de14c5bd22ecbfb4979ad5f22
1,658
hh
C++
DRsim/include/HepMCG4Interface.hh
chanchoen/eic-dual-readout
8cea1f6df9f837c9355416ad84df33a8de2ab600
[ "Apache-2.0" ]
1
2021-04-19T02:33:00.000Z
2021-04-19T02:33:00.000Z
DRsim/include/HepMCG4Interface.hh
chanchoen/eic-dual-readout
8cea1f6df9f837c9355416ad84df33a8de2ab600
[ "Apache-2.0" ]
1
2021-04-16T05:37:08.000Z
2021-07-21T12:05:07.000Z
DRsim/include/HepMCG4Interface.hh
chanchoen/eic-dual-readout
8cea1f6df9f837c9355416ad84df33a8de2ab600
[ "Apache-2.0" ]
3
2021-04-25T23:02:22.000Z
2021-07-19T08:14:49.000Z
#ifndef HEPMC_G4_INTERFACE_h #define HEPMC_G4_INTERFACE_h 1 #include "G4VPrimaryGenerator.hh" #include "HepMC3/GenEvent.h" #include "HepMC3/GenVertex.h" #include "HepMC3/GenParticle.h" /// A base class for primary generation via HepMC object. /// This class is derived from G4VPrimaryGenerator. class HepMCG4Interface : public G4VPrimaryGenerator { protected: // Note that the life of HepMC event object must be handled by users. // In the default implementation, a current HepMC event will be // deleted at GeneratePrimaryVertex() in the next event. HepMC3::GenEvent* fHepmcEvent; // (care for single event case only) // We have to take care for the position of primaries because // primary vertices outside the world voulme give rise to G4Execption. // If the default implementation is not adequate, an alternative // can be implemented in your own class. virtual G4bool CheckVertexInsideWorld(const G4ThreeVector& pos) const; // service method for conversion from HepMC::GenEvent to G4Event void HepMC2G4(const HepMC3::GenEvent* hepmcevt, G4Event* g4event); // Implement this method in his/her own concrete class. // An empty event will be created in default. virtual HepMC3::GenEvent* GenerateHepMCEvent(); public: HepMCG4Interface(); virtual ~HepMCG4Interface(); HepMC3::GenEvent* GetHepMCGenEvent() const; // The default behavior is that a single HepMC event generated by // GenerateHepMCEvent() will be converted to G4Event through HepMC2G4(). virtual void GeneratePrimaryVertex(G4Event* anEvent); }; inline HepMC3::GenEvent* HepMCG4Interface::GetHepMCGenEvent() const { return fHepmcEvent; } #endif
36.043478
91
0.767189
[ "object" ]
b8f641fdaae3d1ce9e815646993259307ee86509
1,227
cpp
C++
639-2/2.cpp
deepankar/topcoder-srm
0efc596662211bf74ede4896eb43b787d31f8a83
[ "MIT" ]
null
null
null
639-2/2.cpp
deepankar/topcoder-srm
0efc596662211bf74ede4896eb43b787d31f8a83
[ "MIT" ]
null
null
null
639-2/2.cpp
deepankar/topcoder-srm
0efc596662211bf74ede4896eb43b787d31f8a83
[ "MIT" ]
null
null
null
//passed #include <limits.h> #include <stdio.h> #include <iostream> #include <stdlib.h> #include <string.h> #include <math.h> #include <vector> #include <map> #include <algorithm> #include <string> using namespace std; typedef vector<int> VI; typedef vector<bool> VB; typedef vector<string> VS; typedef long long int lint; typedef unsigned long long int luint; #define FOR0(i, n) for(int i = 0; i < n; i++) #define Class_Name AliceGameEasy #define FuncName findMinimumValue class Class_Name { public: long long findMinimumValue(long long x, long long y) { long long p = 2*(x+y); long long n = sqrtl(p); if(n*(n+1) != p){ return -1; } long long t = 0; long long rd = x; for(long long i = n; i>0 && rd > 0; i--){ if(i <= rd){ rd -= i; t++; } } if(rd){ return -1; } return t; } }; #include "../utils.cpp" int main(int argc, char **argv) { Class_Name g; if(argc == 2 && strstr(argv[1],".txt")){ filename = argv[1]; } int n; // while((n = parseInt()) != -1){ // a = parseVI(); long long a = atoll(argv[1]); long long b = atoll(argv[2]); cout << g.FuncName(a,b) << "\n"; return 0; }
19.171875
55
0.562347
[ "vector" ]
b8f92976d89e8c53f07c64939c7dfc3148ea25ca
26,806
cpp
C++
src/pke/lib/bv.cpp
marcelmon/PALISADE_capstone
2cfd1626b26576f8fe93bb3a424f934ef700c5b2
[ "BSD-2-Clause" ]
null
null
null
src/pke/lib/bv.cpp
marcelmon/PALISADE_capstone
2cfd1626b26576f8fe93bb3a424f934ef700c5b2
[ "BSD-2-Clause" ]
null
null
null
src/pke/lib/bv.cpp
marcelmon/PALISADE_capstone
2cfd1626b26576f8fe93bb3a424f934ef700c5b2
[ "BSD-2-Clause" ]
null
null
null
/* * @file bv.cpp - BV scheme implementation. * @author TPOC: palisade@njit.edu * * @copyright Copyright (c) 2017, New Jersey Institute of Technology (NJIT) * All rights reserved. * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /* This code implements the Brakerski-Vaikuntanathan (BV) homomorphic encryption scheme. The scheme is described at http://www.wisdom.weizmann.ac.il/~zvikab/localpapers/IdealHom.pdf (or alternative Internet source: http://dx.doi.org/10.1007/978-3-642-22792-9_29). The levelled Homomorphic scheme is described in "Fully Homomorphic Encryption without Bootstrapping", Internet Source: https://eprint.iacr.org/2011/277.pdf . Implementation details are provided in "Homomorphic Evaluation of the AES Circuit" Internet source: https://eprint.iacr.org/2012/099.pdf . {the link to the ACM TISSEC manuscript to be added}. License Information: Copyright (c) 2015, New Jersey Institute of Technology (NJIT) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef LBCRYPTO_CRYPTO_BV_C #define LBCRYPTO_CRYPTO_BV_C #include "bv.h" namespace lbcrypto { template <class Element> bool LPCryptoParametersBV<Element>::Serialize(Serialized* serObj) const { if (!serObj->IsObject()) return false; SerialItem cryptoParamsMap(rapidjson::kObjectType); if (this->SerializeRLWE(serObj, cryptoParamsMap) == false) return false; cryptoParamsMap.AddMember("mode", std::to_string(m_mode), serObj->GetAllocator()); serObj->AddMember("LPCryptoParametersBV", cryptoParamsMap.Move(), serObj->GetAllocator()); serObj->AddMember("LPCryptoParametersType", "LPCryptoParametersBV", serObj->GetAllocator()); return true; } template <class Element> bool LPCryptoParametersBV<Element>::Deserialize(const Serialized& serObj) { Serialized::ConstMemberIterator mIter = serObj.FindMember("LPCryptoParametersBV"); if (mIter == serObj.MemberEnd()) return false; if (this->DeserializeRLWE(mIter) == false) { return false; } SerialItem::ConstMemberIterator pIt; if ((pIt = mIter->value.FindMember("mode")) == serObj.MemberEnd()) { return false; } MODE mode = (MODE)atoi(pIt->value.GetString()); this->SetMode(mode); return true; } //makeSparse is not used by this scheme template <class Element> LPKeyPair<Element> LPAlgorithmBV<Element>::KeyGen(CryptoContext<Element>* cc, bool makeSparse) { LPKeyPair<Element> kp(new LPPublicKey<Element>(cc), new LPPrivateKey<Element>(cc)); const shared_ptr<LPCryptoParametersBV<Element>> cryptoParams = std::static_pointer_cast<LPCryptoParametersBV<Element>>(cc->GetCryptoParameters()); const shared_ptr<typename Element::Params> elementParams = cryptoParams->GetElementParams(); const typename Element::Integer &p = cryptoParams->GetPlaintextModulus(); const typename Element::DggType &dgg = cryptoParams->GetDiscreteGaussianGenerator(); typename Element::DugType dug; typename Element::TugType tug; //Generate the element "a" of the public key Element a(dug, elementParams, Format::EVALUATION); //Generate the secret key Element s; //Done in two steps not to use a random polynomial from a pre-computed pool //Supports both discrete Gaussian (RLWE) and ternary uniform distribution (OPTIMIZED) cases if (cryptoParams->GetMode() == RLWE) { s = Element(dgg, elementParams, Format::COEFFICIENT); } else { s = Element(tug, elementParams, Format::COEFFICIENT); } s.SwitchFormat(); //public key is generated and set //privateKey->MakePublicKey(a, publicKey); Element e(dgg, elementParams, Format::COEFFICIENT); e.SwitchFormat(); Element b = a*s + p*e; kp.secretKey->SetPrivateElement(std::move(s)); kp.publicKey->SetPublicElementAtIndex(0, std::move(a)); kp.publicKey->SetPublicElementAtIndex(1, std::move(b)); return kp; } template <class Element> shared_ptr<Ciphertext<Element>> LPAlgorithmBV<Element>::Encrypt(const shared_ptr<LPPublicKey<Element>> publicKey, Poly &ptxt, bool doEncryption) const { const shared_ptr<LPCryptoParametersBV<Element>> cryptoParams = std::dynamic_pointer_cast<LPCryptoParametersBV<Element>>(publicKey->GetCryptoParameters()); shared_ptr<Ciphertext<Element>> ciphertext(new Ciphertext<Element>(publicKey->GetCryptoContext())); const shared_ptr<typename Element::Params> elementParams = cryptoParams->GetElementParams(); const typename Element::Integer &p = cryptoParams->GetPlaintextModulus(); const typename Element::DggType &dgg = cryptoParams->GetDiscreteGaussianGenerator(); typename Element::TugType tug; Element plaintext(ptxt, elementParams); plaintext.SwitchFormat(); std::vector<Element> cVector; if (doEncryption) { const Element &a = publicKey->GetPublicElements().at(0); const Element &b = publicKey->GetPublicElements().at(1); Element v; //Supports both discrete Gaussian (RLWE) and ternary uniform distribution (OPTIMIZED) cases if (cryptoParams->GetMode() == RLWE) v = Element(dgg, elementParams, Format::EVALUATION); else v = Element(tug, elementParams, Format::EVALUATION); Element e0(dgg, elementParams, Format::EVALUATION); Element e1(dgg, elementParams, Format::EVALUATION); Element c0(b*v + p*e0 + plaintext); Element c1(a*v + p*e1); cVector.push_back(std::move(c0)); cVector.push_back(std::move(c1)); ciphertext->SetElements(std::move(cVector)); } else { Element c0(plaintext); Element c1(elementParams,Format::EVALUATION,true); cVector.push_back(std::move(c0)); cVector.push_back(std::move(c1)); ciphertext->SetElements(std::move(cVector)); } return ciphertext; } template <class Element> DecryptResult LPAlgorithmBV<Element>::Decrypt(const shared_ptr<LPPrivateKey<Element>> privateKey, const shared_ptr<Ciphertext<Element>> ciphertext, Poly *plaintext) const { const shared_ptr<LPCryptoParameters<Element>> cryptoParams = privateKey->GetCryptoParameters(); const typename Element::Integer &p = cryptoParams->GetPlaintextModulus(); const std::vector<Element> &c = ciphertext->GetElements(); const Element &s = privateKey->GetPrivateElement(); Element b = c[0] - s*c[1]; b.SwitchFormat(); // Interpolation is needed in the case of Double-CRT interpolation, for example, DCRTPoly // CRTInterpolate does nothing when dealing with single-CRT ring elements, such as Poly Poly interpolatedElement = b.CRTInterpolate(); *plaintext = interpolatedElement.SignedMod(p); return DecryptResult(plaintext->GetLength()); } template <class Element> shared_ptr<Ciphertext<Element>> LPAlgorithmSHEBV<Element>::EvalAdd( const shared_ptr<Ciphertext<Element>> ciphertext1, const shared_ptr<Ciphertext<Element>> ciphertext2) const { shared_ptr<Ciphertext<Element>> newCiphertext(new Ciphertext<Element>(ciphertext1->GetCryptoContext())); const std::vector<Element> &c1 = ciphertext1->GetElements(); const std::vector<Element> &c2 = ciphertext2->GetElements(); std::vector<Element> cNew; cNew.push_back(std::move(c1[0] + c2[0])); cNew.push_back(std::move(c1[1] + c2[1])); newCiphertext->SetElements(std::move(cNew)); return newCiphertext; } template <class Element> shared_ptr<Ciphertext<Element>> LPAlgorithmSHEBV<Element>::EvalSub(const shared_ptr<Ciphertext<Element>> ciphertext1, const shared_ptr<Ciphertext<Element>> ciphertext2) const { shared_ptr<Ciphertext<Element>> newCiphertext(new Ciphertext<Element>(ciphertext1->GetCryptoContext())); const std::vector<Element> &c1 = ciphertext1->GetElements(); const std::vector<Element> &c2 = ciphertext2->GetElements(); std::vector<Element> cNew; cNew.push_back(std::move(c1[0] - c2[0])); cNew.push_back(std::move(c1[1] - c2[1])); newCiphertext->SetElements(std::move(cNew)); return newCiphertext; } template <class Element> shared_ptr<Ciphertext<Element>> LPAlgorithmSHEBV<Element>::EvalMult( const shared_ptr<Ciphertext<Element>> ciphertext1, const shared_ptr<Ciphertext<Element>> ciphertext2) const { if (ciphertext1->GetElements()[0].GetFormat() == Format::COEFFICIENT || ciphertext2->GetElements()[0].GetFormat() == Format::COEFFICIENT) { throw std::runtime_error("EvalMult cannot multiply in COEFFICIENT domain."); } shared_ptr<Ciphertext<Element>> newCiphertext(new Ciphertext<Element>(ciphertext1->GetCryptoContext())); const std::vector<Element> &c1 = ciphertext1->GetElements(); const std::vector<Element> &c2 = ciphertext2->GetElements(); std::vector<Element> cNew; cNew.push_back(std::move(c1[0] * c2[0])); cNew.push_back(std::move(c1[0] * c2[1] + c1[1] * c2[0])); cNew.push_back(std::move((c1[1] * c2[1]).Negate())); newCiphertext->SetElements(std::move(cNew)); return newCiphertext; } template <class Element> shared_ptr<Ciphertext<Element>> LPAlgorithmSHEBV<Element>::EvalMultPlain( const shared_ptr<Ciphertext<Element>> ciphertext, const shared_ptr<Ciphertext<Element>> plaintext) const { if (ciphertext->GetElements()[0].GetFormat() == Format::COEFFICIENT || plaintext->GetElements()[0].GetFormat() == Format::COEFFICIENT) { throw std::runtime_error("EvalMult cannot multiply in COEFFICIENT domain."); } shared_ptr<Ciphertext<Element>> newCiphertext(new Ciphertext<Element>(ciphertext->GetCryptoContext())); const std::vector<Element> &c1 = ciphertext->GetElements(); const std::vector<Element> &c2 = plaintext->GetElements(); std::vector<Element> cNew; cNew.push_back(std::move(c1[0] * c2[0])); cNew.push_back(std::move(c1[1] * c2[0])); newCiphertext->SetElements(std::move(cNew)); return newCiphertext; } template <class Element> shared_ptr<Ciphertext<Element>> LPAlgorithmSHEBV<Element>::EvalMult(const shared_ptr<Ciphertext<Element>> ciphertext1, const shared_ptr<Ciphertext<Element>> ciphertext2, const shared_ptr<LPEvalKey<Element>> ek) const { shared_ptr<Ciphertext<Element>> newCiphertext = this->EvalMult(ciphertext1, ciphertext2); return this->KeySwitch(ek, newCiphertext); } template <class Element> shared_ptr<Ciphertext<Element>> LPAlgorithmSHEBV<Element>::EvalNegate(const shared_ptr<Ciphertext<Element>> ciphertext) const { shared_ptr<Ciphertext<Element>> newCiphertext(new Ciphertext<Element>(ciphertext->GetCryptoContext())); const std::vector<Element> &cipherTextElements = ciphertext->GetElements(); Element c0 = cipherTextElements[0].Negate(); Element c1 = cipherTextElements[1].Negate(); newCiphertext->SetElements({ c0, c1 }); return newCiphertext; } template <class Element> shared_ptr<LPEvalKey<Element>> LPAlgorithmSHEBV<Element>::KeySwitchGen(const shared_ptr<LPPrivateKey<Element>> originalPrivateKey, const shared_ptr<LPPrivateKey<Element>> newPrivateKey) const { const shared_ptr<LPCryptoParametersBV<Element>> cryptoParams = std::dynamic_pointer_cast<LPCryptoParametersBV<Element>>(originalPrivateKey->GetCryptoParameters()); const shared_ptr<typename Element::Params> originalKeyParams = cryptoParams->GetElementParams(); const BigInteger &p = cryptoParams->GetPlaintextModulus(); shared_ptr<LPEvalKey<Element>> keySwitchHintRelin(new LPEvalKeyRelin<Element>(originalPrivateKey->GetCryptoContext())); //Getting a reference to the polynomials of new private key. const Element &sNew = newPrivateKey->GetPrivateElement(); //Getting a reference to the polynomials of original private key. const Element &s = originalPrivateKey->GetPrivateElement(); //Getting a refernce to discrete gaussian distribution generator. const typename Element::DggType &dgg = cryptoParams->GetDiscreteGaussianGenerator(); //Getting a reference to discrete uniform generator. typename Element::DugType dug; //Relinearization window is used to calculate the base exponent. usint relinWindow = cryptoParams->GetRelinWindow(); //Pushes the powers of base exponent of original key polynomial onto evalKeyElements. std::vector<Element> evalKeyElements(s.PowersOfBase(relinWindow)); //evalKeyElementsGenerated hold the generated noise distribution. std::vector<Element> evalKeyElementsGenerated; for (usint i = 0; i < (evalKeyElements.size()); i++) { // Generate a_i vectors Element a(dug, originalKeyParams, Format::EVALUATION); evalKeyElementsGenerated.push_back(a); //alpha's of i // Generate a_i * newSK + p * e - PowerOfBase(oldSK) Element e(dgg, originalKeyParams, Format::EVALUATION); evalKeyElements.at(i) = (a*sNew + p*e) - evalKeyElements.at(i); } keySwitchHintRelin->SetAVector(std::move(evalKeyElementsGenerated)); keySwitchHintRelin->SetBVector(std::move(evalKeyElements)); return keySwitchHintRelin; } template <class Element> shared_ptr<Ciphertext<Element>> LPAlgorithmSHEBV<Element>::KeySwitch(const shared_ptr<LPEvalKey<Element>> keySwitchHint, const shared_ptr<Ciphertext<Element>> cipherText) const { shared_ptr<Ciphertext<Element>> newCiphertext(new Ciphertext<Element>(*cipherText)); const shared_ptr<LPCryptoParametersBV<Element>> cryptoParamsLWE = std::dynamic_pointer_cast<LPCryptoParametersBV<Element>>(keySwitchHint->GetCryptoParameters()); const shared_ptr<LPEvalKeyRelin<Element>> evalKey = std::static_pointer_cast<LPEvalKeyRelin<Element>>(keySwitchHint); const std::vector<Element> &a = evalKey->GetAVector(); const std::vector<Element> &b = evalKey->GetBVector(); usint relinWindow = cryptoParamsLWE->GetRelinWindow(); const std::vector<Element> &c = cipherText->GetElements(); std::vector<Element> digitsC1; Element ct1; if (c.size() == 2) //case of PRE or automorphism { digitsC1 = c[1].BaseDecompose(relinWindow); ct1 = digitsC1[0] * a[0]; } else //case of EvalMult { digitsC1 = c[2].BaseDecompose(relinWindow); ct1 = c[1] + digitsC1[0] * a[0]; } Element ct0(c[0] + digitsC1[0] * b[0]); //Relinearization Step. for (usint i = 1; i < digitsC1.size(); ++i) { ct0 += digitsC1[i] * b[i]; ct1 += digitsC1[i] * a[i]; } std::vector<Element> ctVector; ctVector.push_back(std::move(ct0)); ctVector.push_back(std::move(ct1)); newCiphertext->SetElements(std::move(ctVector)); return newCiphertext; } template <class Element> shared_ptr<LPEvalKey<Element>> LPAlgorithmSHEBV<Element>::EvalMultKeyGen(const shared_ptr<LPPrivateKey<Element>> originalPrivateKey) const { shared_ptr<LPPrivateKey<Element>> originalPrivateKeySquared = std::shared_ptr<LPPrivateKey<Element>>(new LPPrivateKey<Element>(originalPrivateKey->GetCryptoContext())); Element sSquare(originalPrivateKey->GetPrivateElement()*originalPrivateKey->GetPrivateElement()); originalPrivateKeySquared->SetPrivateElement(std::move(sSquare)); return this->KeySwitchGen(originalPrivateKeySquared, originalPrivateKey); } template <class Element> shared_ptr<Ciphertext<Element>> LPAlgorithmSHEBV<Element>::EvalAutomorphism(const shared_ptr<Ciphertext<Element>> ciphertext, usint i, const std::map<usint, shared_ptr<LPEvalKey<Element>>> &evalKeys) const { shared_ptr<Ciphertext<Element>> permutedCiphertext(new Ciphertext<Element>(*ciphertext)); const std::vector<Element> &c = ciphertext->GetElements(); std::vector<Element> cNew; cNew.push_back(std::move(c[0].AutomorphismTransform(i))); cNew.push_back(std::move(c[1].AutomorphismTransform(i))); permutedCiphertext->SetElements(std::move(cNew)); return this->KeySwitch(evalKeys.find(i)->second, permutedCiphertext); } template <class Element> shared_ptr<std::map<usint, shared_ptr<LPEvalKey<Element>>>> LPAlgorithmSHEBV<Element>::EvalAutomorphismKeyGen(const shared_ptr<LPPrivateKey<Element>> privateKey, const std::vector<usint> &indexList) const { const Element &privateKeyElement = privateKey->GetPrivateElement(); usint n = privateKeyElement.GetRingDimension(); shared_ptr<LPPrivateKey<Element>> tempPrivateKey(new LPPrivateKey<Element>(privateKey->GetCryptoContext())); shared_ptr<std::map<usint, shared_ptr<LPEvalKey<Element>>>> evalKeys(new std::map<usint, shared_ptr<LPEvalKey<Element>>>()); if (indexList.size() > n - 1) throw std::runtime_error("size exceeds the ring dimension"); else { for (usint i = 0; i < indexList.size(); i++) { Element permutedPrivateKeyElement = privateKeyElement.AutomorphismTransform(indexList[i]); tempPrivateKey->SetPrivateElement(permutedPrivateKeyElement); (*evalKeys)[indexList[i]] = this->KeySwitchGen(tempPrivateKey, privateKey); } } return evalKeys; } template <class Element> shared_ptr<LPEvalKey<Element>> LPAlgorithmPREBV<Element>::ReKeyGen(const shared_ptr<LPPrivateKey<Element>> newSK, const shared_ptr<LPPrivateKey<Element>> origPrivateKey) const { return origPrivateKey->GetCryptoContext()->GetEncryptionAlgorithm()->KeySwitchGen(origPrivateKey, newSK); } //Function for re-encypting ciphertext using the arrays generated by ReKeyGen template <class Element> shared_ptr<Ciphertext<Element>> LPAlgorithmPREBV<Element>::ReEncrypt(const shared_ptr<LPEvalKey<Element>> EK, const shared_ptr<Ciphertext<Element>> ciphertext) const { return ciphertext->GetCryptoContext()->GetEncryptionAlgorithm()->KeySwitch(EK, ciphertext); } template <class Element> shared_ptr<Ciphertext<Element>> LPLeveledSHEAlgorithmBV<Element>::ModReduce(shared_ptr<Ciphertext<Element>> cipherText) const { shared_ptr<Ciphertext<Element>> newcipherText(new Ciphertext<Element>(*cipherText)); std::vector<Element> cipherTextElements(cipherText->GetElements()); BigInteger plaintextModulus(cipherText->GetCryptoParameters()->GetPlaintextModulus()); for (auto &cipherTextElement : cipherTextElements) { cipherTextElement.ModReduce(plaintextModulus); // this is being done at the lattice layer. The ciphertext is mod reduced. } newcipherText->SetElements(cipherTextElements); return newcipherText; } //makeSparse is not used by this scheme template <class Element> LPKeyPair<Element> LPAlgorithmMultipartyBV<Element>::MultipartyKeyGen(CryptoContext<Element>* cc, const vector<shared_ptr<LPPrivateKey<Element>>>& secretKeys, bool makeSparse) { LPKeyPair<Element> kp(new LPPublicKey<Element>(cc), new LPPrivateKey<Element>(cc)); const shared_ptr<LPCryptoParametersBV<Element>> cryptoParams = std::static_pointer_cast<LPCryptoParametersBV<Element>>(cc->GetCryptoParameters()); const shared_ptr<typename Element::Params> elementParams = cryptoParams->GetElementParams(); const typename Element::Integer &p = cryptoParams->GetPlaintextModulus(); const typename Element::DggType &dgg = cryptoParams->GetDiscreteGaussianGenerator(); typename Element::DugType dug; typename Element::TugType tug; //Generate the element "a" of the public key Element a(dug, elementParams, Format::EVALUATION); //Generate the secret key Element s(elementParams, Format::EVALUATION, true); //Supports both discrete Gaussian (RLWE) and ternary uniform distribution (OPTIMIZED) cases size_t numKeys = secretKeys.size(); for( size_t i = 0; i < numKeys; i++ ) { shared_ptr<LPPrivateKey<Element>> sk1 = secretKeys[i]; Element s1 = sk1->GetPrivateElement(); s += s1; } // s.SwitchFormat(); //public key is generated and set //privateKey->MakePublicKey(a, publicKey); Element e(dgg, elementParams, Format::COEFFICIENT); e.SwitchFormat(); Element b = a*s + p*e; kp.secretKey->SetPrivateElement(std::move(s)); kp.publicKey->SetPublicElementAtIndex(0, std::move(a)); kp.publicKey->SetPublicElementAtIndex(1, std::move(b)); return kp; } //makeSparse is not used by this scheme template <class Element> LPKeyPair<Element> LPAlgorithmMultipartyBV<Element>::MultipartyKeyGen(CryptoContext<Element>* cc, const shared_ptr<LPPublicKey<Element>> pk1, bool makeSparse) { LPKeyPair<Element> kp(new LPPublicKey<Element>(cc), new LPPrivateKey<Element>(cc)); const shared_ptr<LPCryptoParametersBV<Element>> cryptoParams = std::static_pointer_cast<LPCryptoParametersBV<Element>>(cc->GetCryptoParameters()); const shared_ptr<typename Element::Params> elementParams = cryptoParams->GetElementParams(); const typename Element::Integer &p = cryptoParams->GetPlaintextModulus(); const typename Element::DggType &dgg = cryptoParams->GetDiscreteGaussianGenerator(); typename Element::DugType dug; typename Element::TugType tug; //Generate the element "a" of the public key Element a = pk1->GetPublicElements()[1]; //Generate the secret key Element s; //Done in two steps not to use a random polynomial from a pre-computed pool //Supports both discrete Gaussian (RLWE) and ternary uniform distribution (OPTIMIZED) cases if (cryptoParams->GetMode() == RLWE) { s = Element(dgg, elementParams, Format::COEFFICIENT); } else { s = Element(tug, elementParams, Format::COEFFICIENT); } s.SwitchFormat(); //public key is generated and set //privateKey->MakePublicKey(a, publicKey); Element e(dgg, elementParams, Format::COEFFICIENT); e.SwitchFormat(); //a.SwitchFormat(); Element b = a*s + p*e; kp.secretKey->SetPrivateElement(std::move(s)); kp.publicKey->SetPublicElementAtIndex(0, std::move(a)); kp.publicKey->SetPublicElementAtIndex(1, std::move(b)); return kp; } template <class Element> shared_ptr<Ciphertext<Element>> LPAlgorithmMultipartyBV<Element>::MultipartyDecryptLead(const shared_ptr<LPPrivateKey<Element>> privateKey, const shared_ptr<Ciphertext<Element>> ciphertext) const { const shared_ptr<LPCryptoParameters<Element>> cryptoParams = privateKey->GetCryptoParameters(); const std::vector<Element> &c = ciphertext->GetElements(); const Element &s = privateKey->GetPrivateElement(); Element b = c[0] - s*c[1]; shared_ptr<Ciphertext<Element>> newCiphertext(new Ciphertext<Element>(ciphertext->GetCryptoContext())); newCiphertext->SetElements({ b }); return newCiphertext; } template <class Element> shared_ptr<Ciphertext<Element>> LPAlgorithmMultipartyBV<Element>::MultipartyDecryptMain(const shared_ptr<LPPrivateKey<Element>> privateKey, const shared_ptr<Ciphertext<Element>> ciphertext) const { const shared_ptr<LPCryptoParameters<Element>> cryptoParams = privateKey->GetCryptoParameters(); const std::vector<Element> &c = ciphertext->GetElements(); const Element &s = privateKey->GetPrivateElement(); Element b = s*c[1]; shared_ptr<Ciphertext<Element>> newCiphertext(new Ciphertext<Element>(ciphertext->GetCryptoContext())); newCiphertext->SetElements({ b }); return newCiphertext; } template <class Element> DecryptResult LPAlgorithmMultipartyBV<Element>::MultipartyDecryptFusion(const vector<shared_ptr<Ciphertext<Element>>>& ciphertextVec, Poly *plaintext) const { const shared_ptr<LPCryptoParameters<Element>> cryptoParams = ciphertextVec[0]->GetCryptoParameters(); const BigInteger &p = cryptoParams->GetPlaintextModulus(); const std::vector<Element> &cElem = ciphertextVec[0]->GetElements(); Element b = cElem[0]; size_t numCipher = ciphertextVec.size(); for( size_t i = 1; i < numCipher; i++ ) { const std::vector<Element> &c2 = ciphertextVec[i]->GetElements(); b -= c2[0]; } b.SwitchFormat(); // Interpolation is needed in the case of Double-CRT interpolation, for example, DCRTPoly // CRTInterpolate does nothing when dealing with single-CRT ring elements, such as Poly Poly interpolatedElement = b.CRTInterpolate(); *plaintext = interpolatedElement.SignedMod(p); return DecryptResult(plaintext->GetLength()); } // Enable for LPPublicKeyEncryptionSchemeLTV template <class Element> void LPPublicKeyEncryptionSchemeBV<Element>::Enable(PKESchemeFeature feature) { switch (feature) { case ENCRYPTION: if (this->m_algorithmEncryption == NULL) this->m_algorithmEncryption = new LPAlgorithmBV<Element>(); break; case PRE: if (this->m_algorithmPRE == NULL) this->m_algorithmPRE = new LPAlgorithmPREBV<Element>(); break; case SHE: if (this->m_algorithmSHE == NULL) this->m_algorithmSHE = new LPAlgorithmSHEBV<Element>(); break; case LEVELEDSHE: if (this->m_algorithmLeveledSHE == NULL) this->m_algorithmLeveledSHE = new LPLeveledSHEAlgorithmBV<Element>(); break; case MULTIPARTY: if (this->m_algorithmMultiparty == NULL) this->m_algorithmMultiparty = new LPAlgorithmMultipartyBV<Element>(); break; case FHE: throw std::logic_error("FHE feature not supported for BV scheme"); } } } // namespace lbcrypto ends #endif
35.646277
755
0.753637
[ "vector" ]
b8fda7e68c2704ff3dc5f968781c99b9dfacd998
1,613
cpp
C++
main.cpp
Charl86/Random-Sequences
b036ca15190eea5f09fd610338959cb6ba2fbd5a
[ "MIT" ]
null
null
null
main.cpp
Charl86/Random-Sequences
b036ca15190eea5f09fd610338959cb6ba2fbd5a
[ "MIT" ]
null
null
null
main.cpp
Charl86/Random-Sequences
b036ca15190eea5f09fd610338959cb6ba2fbd5a
[ "MIT" ]
null
null
null
/* This program takes a file of randomly generated sequences and processess them, or creates a new file of randomly generated sequences in order to process it. During the processing phase this program will normalize the sequences, find the mean value, find the standard deviation and sorts them using the Selection Sort and Bubble Sort algorithms. */ #include "Sequence.h" #include <ctime> #include <vector> int main() { srand((unsigned)time(0)); // Start a new random seed using the current time. int numberOfSeqs; // Number of sequences to be read or to be created. bool readFile; // Hold value of true if sequences are to be read. fstream SeqsFile; // fstream object to read random sequences file. fstream NormlicedFile; // fstream object wherein to output processed sequences. /* Ask user how many sequences are wanted to be processed and whether or not to create said sequences on the spot or read them from an existing file. */ numberOfSeqs = userSequence(); // Create a vector of sequences. vector <Sequence> Sequences(0); makeFilenames(SeqsFile, NormlicedFile, readFile, numberOfSeqs); // Create files. if (readFile) // If sequences are to be read, call readSequences function readSequences(SeqsFile, numberOfSeqs, Sequences); else // Otherwise, create the sequences. makeSequences(SeqsFile, numberOfSeqs, Sequences); // Normalize sequences. getSequences(SeqsFile, NormlicedFile, numberOfSeqs, Sequences); // Close files. SeqsFile.close(); NormlicedFile.close(); return 0; }
36.659091
88
0.717297
[ "object", "vector" ]
b8ffaa1c3dde0438482b12ba6c1bf86bf69668c5
3,272
cpp
C++
Tests/2018-2019/T2/Tests/tests.cpp
DoStini/FEUP-AEDA
4ac4bbeda07c17837a13a81de197bfcc7857c3be
[ "MIT" ]
null
null
null
Tests/2018-2019/T2/Tests/tests.cpp
DoStini/FEUP-AEDA
4ac4bbeda07c17837a13a81de197bfcc7857c3be
[ "MIT" ]
1
2020-09-30T18:59:40.000Z
2020-10-09T22:13:39.000Z
Tests/2018-2019/T2/Tests/tests.cpp
DoStini/FEUP-AEDA
4ac4bbeda07c17837a13a81de197bfcc7857c3be
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <gmock/gmock.h> #include <cstdlib> #include <iostream> #include <queue> #include <sstream> #include <vector> #include <time.h> #include "Kart.h" #include "CStack.h" #include "CSimpleList.h" using testing::Eq; using namespace std; TEST(test_1, test_a){ CGrupo grupo1; grupo1.criaGrupo(); vector<CKart> kartsOrdenados = grupo1.ordenaKarts(); EXPECT_EQ(kartsOrdenados.size(), 2500); if (kartsOrdenados.size()>0) for (unsigned int i=0;i<kartsOrdenados.size()-1;i++) EXPECT_LE(kartsOrdenados[i].getNumero(), kartsOrdenados[i + 1].getNumero()); } TEST(test_1, test_b){ CGrupo grupo1; grupo1.criaGrupo(); EXPECT_EQ(grupo1.numAvariados(134), 210); EXPECT_EQ(grupo1.numAvariados(250), 219); EXPECT_EQ(grupo1.numAvariados(450), 212); EXPECT_EQ(grupo1.numAvariados(600), 206); } TEST(test_1, test_c){ CGrupo grupo1; grupo1.criaGrupo(); vector <CPista> vecP = grupo1.getPistas(); vecP[0].prepararCorrida(10, 134); queue<CKart> q1= vecP[0].getKartsLinhaPartida(); EXPECT_EQ(false, q1.empty()); if (!q1.empty()) { EXPECT_EQ(13, q1.front().getNumero()); q1.pop(); if (!q1.empty()) { EXPECT_EQ(31, q1.front().getNumero()); q1.pop(); if (!q1.empty()) EXPECT_EQ(33, q1.front().getNumero()); } } } TEST(test_1, test_d){ CGrupo grupo1; grupo1.criaGrupo(); vector <CPista> vecP = grupo1.getPistas(); vecP[0].prepararCorrida(10, 134); EXPECT_EQ(7,vecP[0].inicioCorrida()); vector<CKart> v1= vecP[0].getKartsEmProva(); EXPECT_EQ(false, v1.empty()); if (v1.size()>=1) EXPECT_EQ(13, v1[0].getNumero()); if (v1.size()>=2) EXPECT_EQ(31, v1[1].getNumero()); if (v1.size()>=3) EXPECT_EQ(33, v1[2].getNumero()); } TEST(test_2, test_a){ CStack s1(20); s1.push(1); s1.push(2); s1.push(3); s1.adicionaN(4); //s1.print(); EXPECT_EQ("7 6 5 4 3 2 1 ",s1.toStr()); s1.adicionaN(2); //s1.print(); EXPECT_EQ("9 8 7 6 5 4 3 2 1 ",s1.toStr()); } TEST(test_2, test_b){ CStack s2(20); s2.push(1); s2.push(2); s2.push(3); EXPECT_EQ(false,s2.inverte4()); s2.push(4); s2.push(5); s2.inverte4(); //s2.print(); EXPECT_EQ("2 3 4 5 1 ",s2.toStr()); s2.push(6); s2.push(7); s2.inverte4(); //s2.print(); EXPECT_EQ("3 2 6 7 4 5 1 ",s2.toStr()); } TEST(test_2, test_c){ CSimpleList l1, l2, l3; l1.insert_end(1); l1.insert_end(2); l1.insert_end(3); l1.insert_end(4); l1.insert_end(5); l2.insert_end(6); l2.insert_end(7); l2.insert_end(8); //l1.print(); l2.print(); l1.intercalar(l2); //l1.print(); EXPECT_EQ("1 6 2 7 3 8 4 5 ",l1.toStr()); l1.intercalar(l2); //l1.print(); EXPECT_EQ("1 6 6 7 2 8 7 3 8 4 5 ",l1.toStr()); } TEST(test_2, test_d){ CSimpleList l3; int elem[14] = {1,1,2,2,2,3,3,3,3,4,4,7,8,8}; for(int i=0; i<14; i++) l3.insert_end(elem[i]); l3.print(); //cout << "Zipados: " << l3.zipar() << endl; EXPECT_EQ(8,l3.zipar()); EXPECT_EQ("1 2 3 4 7 8 ",l3.toStr()); l3.print(); CSimpleList l4; int elem2[10] = {1,1,1,2,4,6,6,6,6,7}; for(int i=0; i<10; i++) l4.insert_end(elem2[i]); l4.print(); //cout << "Zipados: " << l3.zipar() << endl; EXPECT_EQ(5,l4.zipar()); EXPECT_EQ("1 2 4 6 7 ",l4.toStr()); l4.print(); }
25.364341
88
0.610636
[ "vector" ]
77149f69a98cabba63807358ec025b3f98aa0e35
5,545
hpp
C++
dynd/include/type_unpack.hpp
mwiebe/dynd-python
45ffecaf7887761a5634140f0ed120b33ace58a3
[ "BSD-2-Clause" ]
93
2015-01-29T14:00:57.000Z
2021-11-23T14:37:27.000Z
dynd/include/type_unpack.hpp
ContinuumIO/dynd-python
bae7afb8eb604b0bce09befc9e896c8ec8357aaa
[ "BSD-2-Clause" ]
143
2015-01-04T12:30:24.000Z
2016-09-29T18:36:22.000Z
dynd/include/type_unpack.hpp
ContinuumIO/dynd-python
bae7afb8eb604b0bce09befc9e896c8ec8357aaa
[ "BSD-2-Clause" ]
20
2015-06-08T11:54:46.000Z
2021-03-09T07:57:25.000Z
// // Copyright (C) 2011-15 DyND Developers // BSD 2-Clause License, see LICENSE.txt // #pragma once #include <Python.h> #include <type_traits> #include <dynd/type_registry.hpp> #include "types/pyobject_type.hpp" using namespace dynd; // Unpack and convert a single element to a PyObject. template <typename T, typename std::enable_if< std::is_integral<T>::value && std::is_signed<T>::value && sizeof(T) <= sizeof(long long), int>::type = 0> inline PyObject *unpack_single(const char *data) { return PyLong_FromLongLong(*reinterpret_cast<const T *>(data)); } template <typename T, typename std::enable_if_t<std::is_integral<T>::value && std::is_unsigned<T>::value && sizeof(T) <= sizeof(unsigned long long), int> = 0> inline PyObject *unpack_single(const char *data) { return PyLong_FromUnsignedLongLong(*reinterpret_cast<const T *>(data)); } template <typename T, typename std::enable_if_t<std::is_same<T, bool1>::value, int> = 0> inline PyObject *unpack_single(const char *data) { return PyBool_FromLong(*reinterpret_cast<const T *>(data)); } template <typename T, typename std::enable_if_t<std::is_same<T, float64>::value, int> = 0> inline PyObject *unpack_single(const char *data) { return PyFloat_FromDouble(*reinterpret_cast<const T *>(data)); } template <typename T, typename std::enable_if_t<std::is_same<T, complex128>::value, int> = 0> inline PyObject *unpack_single(const char *data) { complex128 c = *reinterpret_cast<const T *>(data); return PyComplex_FromDoubles(c.real(), c.imag()); } template <typename T, typename std::enable_if_t<std::is_same<T, std::string>::value, int> = 0> inline PyObject *unpack_single(const char *data) { const std::string &s = *reinterpret_cast<const T *>(data); return PyUnicode_FromString(s.data()); } template <typename T, typename std::enable_if_t<std::is_same<T, ndt::type>::value, int> = 0> inline PyObject *unpack_single(const char *data) { return pydynd::type_from_cpp(*reinterpret_cast<const T *>(data)); } // Convert a single element to a PyObject. template <typename T, typename std::enable_if_t< std::is_integral<T>::value && std::is_signed<T>::value && sizeof(T) <= sizeof(long long), int> = 0> inline PyObject *convert_single(T value) { return PyLong_FromLongLong(value); } template <typename T, typename std::enable_if_t<std::is_integral<T>::value && std::is_unsigned<T>::value && sizeof(T) <= sizeof(unsigned long long), int> = 0> inline PyObject *convert_single(T value) { return PyLong_FromUnsignedLongLong(value); } template <typename T, typename std::enable_if_t<std::is_same<T, bool1>::value, int> = 0> inline PyObject *convert_single(T value) { return PyBool_FromLong(value); } template <typename T, typename std::enable_if_t<std::is_same<T, float64>::value, int> = 0> inline PyObject *convert_single(T value) { return PyFloat_FromDouble(value); } template <typename T, typename std::enable_if_t<std::is_same<T, complex128>::value, int> = 0> inline PyObject *convert_single(T value) { return PyComplex_FromDoubles(value.real(), value.imag()); } template <typename T, typename std::enable_if_t<std::is_same<T, std::string>::value, int> = 0> inline PyObject *convert_single(const T &value) { return PyUnicode_FromString(value.data()); } template <typename T, typename std::enable_if_t<std::is_same<T, ndt::type>::value, int> = 0> inline PyObject *convert_single(const T &value) { return pydynd::type_from_cpp(value); } template <typename T> PyObject *unpack_vector(const char *data) { auto &vec = *reinterpret_cast<const std::vector<T> *>(data); PyObject *lst, *item; lst = PyList_New(vec.size()); if (lst == NULL) { return NULL; } for (size_t i = 0; i < vec.size(); ++i) { item = convert_single<T>(vec[i]); if (item == NULL) { Py_DECREF(lst); return NULL; } PyList_SET_ITEM(lst, i, item); } return lst; } template <typename T> inline PyObject *unpack(bool is_vector, const char *data) { if (is_vector) { return unpack_vector<T>(data); } else { return unpack_single<T>(data); } } PyObject *from_type_property(const std::pair<ndt::type, const char *> &pair) { type_id_t id = pair.first.get_id(); bool is_vector = false; if (id == fixed_dim_id) { id = pair.first.get_dtype().get_id(); is_vector = true; } switch (id) { case bool_id: return unpack<bool1>(is_vector, pair.second); case int8_id: return unpack<int8>(is_vector, pair.second); case int16_id: return unpack<int16>(is_vector, pair.second); case int32_id: return unpack<int32>(is_vector, pair.second); case int64_id: return unpack<int64>(is_vector, pair.second); case uint8_id: return unpack<uint8>(is_vector, pair.second); case uint16_id: return unpack<uint16>(is_vector, pair.second); case uint32_id: return unpack<uint32>(is_vector, pair.second); case uint64_id: return unpack<uint64>(is_vector, pair.second); case float64_id: return unpack<float64>(is_vector, pair.second); case complex_float64_id: return unpack<complex128>(is_vector, pair.second); case type_id: return unpack<ndt::type>(is_vector, pair.second); case string_id: return unpack<std::string>(is_vector, pair.second); default: throw std::runtime_error("invalid type property"); } }
29.184211
119
0.676826
[ "vector" ]
77167c6e8ec53c08a8eda83a9764ba050d7a3312
1,268
cpp
C++
SimpleLearn/13.MMapTest01/GetHisData.cpp
codeworkscn/learn-cpp
c72b2330934bdead2489509cd89343e666e631b4
[ "Apache-2.0" ]
null
null
null
SimpleLearn/13.MMapTest01/GetHisData.cpp
codeworkscn/learn-cpp
c72b2330934bdead2489509cd89343e666e631b4
[ "Apache-2.0" ]
null
null
null
SimpleLearn/13.MMapTest01/GetHisData.cpp
codeworkscn/learn-cpp
c72b2330934bdead2489509cd89343e666e631b4
[ "Apache-2.0" ]
null
null
null
#include "PutHisData.h" DWORD GetMapMemory(unsigned char *szResult,long len,const char* svcname) { HANDLE hMapFile = NULL; PVOID pView = NULL; DWORD dwError = 0; char fullmapname[_MAX_FNAME+1]; char tempsvcname[256]; strcpy_s(tempsvcname,128,svcname); sprintf_s(fullmapname,_MAX_FNAME+1,"%s%s",MAP_PREFIX,strlwr((char*)tempsvcname)); hMapFile = OpenFileMapping( FILE_MAP_READ, // Read access FALSE, // Do not inherit the name fullmapname // File mapping name ); if (hMapFile == NULL) { dwError = GetLastError(); goto Cleanup; } // Map a view of the file mapping into the address space of the current // process. pView = MapViewOfFile( hMapFile, // Handle of the map object FILE_MAP_READ, // Read access 0, // High-order DWORD of the file offset VIEW_OFFSET, // Low-order DWORD of the file offset VIEW_SIZE // The number of bytes to map to view ); if (pView == NULL) { dwError = GetLastError(); goto Cleanup; } memcpy(szResult,pView,len); dwError = 0; Cleanup: if (hMapFile) { if (pView) { UnmapViewOfFile(pView); pView = NULL; } CloseHandle(hMapFile); hMapFile = NULL; } return dwError; }
23.924528
82
0.634069
[ "object" ]
772120d32178922e9ca36b17e7d48df82ffe49ff
41,432
cpp
C++
wznmcmbd/CrdWznmApp/DlgWznmAppWrite_blks.cpp
mpsitech/wznm-WhizniumSBE
4911d561b28392d485c46e98fb915168d82b3824
[ "MIT" ]
3
2020-09-20T16:24:48.000Z
2021-12-01T19:44:51.000Z
wznmcmbd/CrdWznmApp/DlgWznmAppWrite_blks.cpp
mpsitech/wznm-WhizniumSBE
4911d561b28392d485c46e98fb915168d82b3824
[ "MIT" ]
null
null
null
wznmcmbd/CrdWznmApp/DlgWznmAppWrite_blks.cpp
mpsitech/wznm-WhizniumSBE
4911d561b28392d485c46e98fb915168d82b3824
[ "MIT" ]
null
null
null
/** * \file DlgWznmAppWrite_blks.cpp * job handler for job DlgWznmAppWrite (implementation of blocks) * \copyright (C) 2016-2020 MPSI Technologies GmbH * \author Alexander Wirthmueller (auto-generation) * \date created: 28 Nov 2020 */ // IP header --- ABOVE using namespace std; using namespace Sbecore; using namespace Xmlio; /****************************************************************************** class DlgWznmAppWrite::VecVDit ******************************************************************************/ uint DlgWznmAppWrite::VecVDit::getIx( const string& sref ) { string s = StrMod::lc(sref); if (s == "det") return DET; if (s == "cuc") return CUC; if (s == "wrc") return WRC; if (s == "lfi") return LFI; if (s == "fia") return FIA; return(0); }; string DlgWznmAppWrite::VecVDit::getSref( const uint ix ) { if (ix == DET) return("Det"); if (ix == CUC) return("Cuc"); if (ix == WRC) return("Wrc"); if (ix == LFI) return("Lfi"); if (ix == FIA) return("Fia"); return(""); }; string DlgWznmAppWrite::VecVDit::getTitle( const uint ix , const uint ixWznmVLocale ) { if (ixWznmVLocale == 1) { if (ix == DET) return("Details"); if (ix == CUC) return("Custom code"); if (ix == WRC) return("Writing"); if (ix == LFI) return("Log file"); if (ix == FIA) return("File archive"); return(getSref(ix)); }; return(""); }; void DlgWznmAppWrite::VecVDit::fillFeed( const uint ixWznmVLocale , Feed& feed ) { feed.clear(); for (unsigned int i = 1; i <= 5; i++) feed.appendIxSrefTitles(i, getSref(i), getTitle(i, ixWznmVLocale)); }; /****************************************************************************** class DlgWznmAppWrite::VecVDo ******************************************************************************/ uint DlgWznmAppWrite::VecVDo::getIx( const string& sref ) { string s = StrMod::lc(sref); if (s == "butdneclick") return BUTDNECLICK; return(0); }; string DlgWznmAppWrite::VecVDo::getSref( const uint ix ) { if (ix == BUTDNECLICK) return("ButDneClick"); return(""); }; /****************************************************************************** class DlgWznmAppWrite::VecVDoWrc ******************************************************************************/ uint DlgWznmAppWrite::VecVDoWrc::getIx( const string& sref ) { string s = StrMod::lc(sref); if (s == "butrunclick") return BUTRUNCLICK; if (s == "butstoclick") return BUTSTOCLICK; return(0); }; string DlgWznmAppWrite::VecVDoWrc::getSref( const uint ix ) { if (ix == BUTRUNCLICK) return("ButRunClick"); if (ix == BUTSTOCLICK) return("ButStoClick"); return(""); }; /****************************************************************************** class DlgWznmAppWrite::VecVSge ******************************************************************************/ uint DlgWznmAppWrite::VecVSge::getIx( const string& sref ) { string s = StrMod::lc(sref); if (s == "idle") return IDLE; if (s == "alrmer") return ALRMER; if (s == "upkidle") return UPKIDLE; if (s == "unpack") return UNPACK; if (s == "upkdone") return UPKDONE; if (s == "write") return WRITE; if (s == "mrggnr") return MRGGNR; if (s == "mrgcust") return MRGCUST; if (s == "pack") return PACK; if (s == "fail") return FAIL; if (s == "done") return DONE; return(0); }; string DlgWznmAppWrite::VecVSge::getSref( const uint ix ) { if (ix == IDLE) return("idle"); if (ix == ALRMER) return("alrmer"); if (ix == UPKIDLE) return("upkidle"); if (ix == UNPACK) return("unpack"); if (ix == UPKDONE) return("upkdone"); if (ix == WRITE) return("write"); if (ix == MRGGNR) return("mrggnr"); if (ix == MRGCUST) return("mrgcust"); if (ix == PACK) return("pack"); if (ix == FAIL) return("fail"); if (ix == DONE) return("done"); return(""); }; void DlgWznmAppWrite::VecVSge::fillFeed( Feed& feed ) { feed.clear(); for (unsigned int i = 1; i <= 11; i++) feed.appendIxSrefTitles(i, getSref(i), getSref(i)); }; /****************************************************************************** class DlgWznmAppWrite::ContIac ******************************************************************************/ DlgWznmAppWrite::ContIac::ContIac( const uint numFDse ) : Block() { this->numFDse = numFDse; mask = {NUMFDSE}; }; bool DlgWznmAppWrite::ContIac::readJSON( Json::Value& sup , bool addbasetag ) { clear(); bool basefound; Json::Value& me = sup; if (addbasetag) me = sup["ContIacDlgWznmAppWrite"]; basefound = (me != Json::nullValue); if (basefound) { if (me.isMember("numFDse")) {numFDse = me["numFDse"].asUInt(); add(NUMFDSE);}; }; return basefound; }; bool DlgWznmAppWrite::ContIac::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "ContIacDlgWznmAppWrite"); else basefound = checkXPath(docctx, basexpath); string itemtag = "ContitemIacDlgWznmAppWrite"; if (basefound) { if (extractUintAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "numFDse", numFDse)) add(NUMFDSE); }; return basefound; }; void DlgWznmAppWrite::ContIac::writeJSON( Json::Value& sup , string difftag ) { if (difftag.length() == 0) difftag = "ContIacDlgWznmAppWrite"; Json::Value& me = sup[difftag] = Json::Value(Json::objectValue); me["numFDse"] = numFDse; }; void DlgWznmAppWrite::ContIac::writeXML( xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "ContIacDlgWznmAppWrite"; string itemtag; if (shorttags) itemtag = "Ci"; else itemtag = "ContitemIacDlgWznmAppWrite"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); writeUintAttr(wr, itemtag, "sref", "numFDse", numFDse); xmlTextWriterEndElement(wr); }; set<uint> DlgWznmAppWrite::ContIac::comm( const ContIac* comp ) { set<uint> items; if (numFDse == comp->numFDse) insert(items, NUMFDSE); return(items); }; set<uint> DlgWznmAppWrite::ContIac::diff( const ContIac* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {NUMFDSE}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class DlgWznmAppWrite::ContIacDet ******************************************************************************/ DlgWznmAppWrite::ContIacDet::ContIacDet( const bool ChkUsf ) : Block() { this->ChkUsf = ChkUsf; mask = {CHKUSF}; }; bool DlgWznmAppWrite::ContIacDet::readJSON( Json::Value& sup , bool addbasetag ) { clear(); bool basefound; Json::Value& me = sup; if (addbasetag) me = sup["ContIacDlgWznmAppWriteDet"]; basefound = (me != Json::nullValue); if (basefound) { if (me.isMember("ChkUsf")) {ChkUsf = me["ChkUsf"].asBool(); add(CHKUSF);}; }; return basefound; }; bool DlgWznmAppWrite::ContIacDet::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "ContIacDlgWznmAppWriteDet"); else basefound = checkXPath(docctx, basexpath); string itemtag = "ContitemIacDlgWznmAppWriteDet"; if (basefound) { if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "ChkUsf", ChkUsf)) add(CHKUSF); }; return basefound; }; void DlgWznmAppWrite::ContIacDet::writeJSON( Json::Value& sup , string difftag ) { if (difftag.length() == 0) difftag = "ContIacDlgWznmAppWriteDet"; Json::Value& me = sup[difftag] = Json::Value(Json::objectValue); me["ChkUsf"] = ChkUsf; }; void DlgWznmAppWrite::ContIacDet::writeXML( xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "ContIacDlgWznmAppWriteDet"; string itemtag; if (shorttags) itemtag = "Ci"; else itemtag = "ContitemIacDlgWznmAppWriteDet"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); writeBoolAttr(wr, itemtag, "sref", "ChkUsf", ChkUsf); xmlTextWriterEndElement(wr); }; set<uint> DlgWznmAppWrite::ContIacDet::comm( const ContIacDet* comp ) { set<uint> items; if (ChkUsf == comp->ChkUsf) insert(items, CHKUSF); return(items); }; set<uint> DlgWznmAppWrite::ContIacDet::diff( const ContIacDet* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {CHKUSF}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class DlgWznmAppWrite::ContInf ******************************************************************************/ DlgWznmAppWrite::ContInf::ContInf( const uint numFSge ) : Block() { this->numFSge = numFSge; mask = {NUMFSGE}; }; void DlgWznmAppWrite::ContInf::writeJSON( Json::Value& sup , string difftag ) { if (difftag.length() == 0) difftag = "ContInfDlgWznmAppWrite"; Json::Value& me = sup[difftag] = Json::Value(Json::objectValue); me["numFSge"] = numFSge; }; void DlgWznmAppWrite::ContInf::writeXML( xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "ContInfDlgWznmAppWrite"; string itemtag; if (shorttags) itemtag = "Ci"; else itemtag = "ContitemInfDlgWznmAppWrite"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); writeUintAttr(wr, itemtag, "sref", "numFSge", numFSge); xmlTextWriterEndElement(wr); }; set<uint> DlgWznmAppWrite::ContInf::comm( const ContInf* comp ) { set<uint> items; if (numFSge == comp->numFSge) insert(items, NUMFSGE); return(items); }; set<uint> DlgWznmAppWrite::ContInf::diff( const ContInf* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {NUMFSGE}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class DlgWznmAppWrite::ContInfFia ******************************************************************************/ DlgWznmAppWrite::ContInfFia::ContInfFia( const string& Dld ) : Block() { this->Dld = Dld; mask = {DLD}; }; void DlgWznmAppWrite::ContInfFia::writeJSON( Json::Value& sup , string difftag ) { if (difftag.length() == 0) difftag = "ContInfDlgWznmAppWriteFia"; Json::Value& me = sup[difftag] = Json::Value(Json::objectValue); me["Dld"] = Dld; }; void DlgWznmAppWrite::ContInfFia::writeXML( xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "ContInfDlgWznmAppWriteFia"; string itemtag; if (shorttags) itemtag = "Ci"; else itemtag = "ContitemInfDlgWznmAppWriteFia"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); writeStringAttr(wr, itemtag, "sref", "Dld", Dld); xmlTextWriterEndElement(wr); }; set<uint> DlgWznmAppWrite::ContInfFia::comm( const ContInfFia* comp ) { set<uint> items; if (Dld == comp->Dld) insert(items, DLD); return(items); }; set<uint> DlgWznmAppWrite::ContInfFia::diff( const ContInfFia* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {DLD}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class DlgWznmAppWrite::ContInfLfi ******************************************************************************/ DlgWznmAppWrite::ContInfLfi::ContInfLfi( const string& Dld ) : Block() { this->Dld = Dld; mask = {DLD}; }; void DlgWznmAppWrite::ContInfLfi::writeJSON( Json::Value& sup , string difftag ) { if (difftag.length() == 0) difftag = "ContInfDlgWznmAppWriteLfi"; Json::Value& me = sup[difftag] = Json::Value(Json::objectValue); me["Dld"] = Dld; }; void DlgWznmAppWrite::ContInfLfi::writeXML( xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "ContInfDlgWznmAppWriteLfi"; string itemtag; if (shorttags) itemtag = "Ci"; else itemtag = "ContitemInfDlgWznmAppWriteLfi"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); writeStringAttr(wr, itemtag, "sref", "Dld", Dld); xmlTextWriterEndElement(wr); }; set<uint> DlgWznmAppWrite::ContInfLfi::comm( const ContInfLfi* comp ) { set<uint> items; if (Dld == comp->Dld) insert(items, DLD); return(items); }; set<uint> DlgWznmAppWrite::ContInfLfi::diff( const ContInfLfi* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {DLD}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class DlgWznmAppWrite::ContInfWrc ******************************************************************************/ DlgWznmAppWrite::ContInfWrc::ContInfWrc( const string& TxtPrg ) : Block() { this->TxtPrg = TxtPrg; mask = {TXTPRG}; }; void DlgWznmAppWrite::ContInfWrc::writeJSON( Json::Value& sup , string difftag ) { if (difftag.length() == 0) difftag = "ContInfDlgWznmAppWriteWrc"; Json::Value& me = sup[difftag] = Json::Value(Json::objectValue); me["TxtPrg"] = TxtPrg; }; void DlgWznmAppWrite::ContInfWrc::writeXML( xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "ContInfDlgWznmAppWriteWrc"; string itemtag; if (shorttags) itemtag = "Ci"; else itemtag = "ContitemInfDlgWznmAppWriteWrc"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); writeStringAttr(wr, itemtag, "sref", "TxtPrg", TxtPrg); xmlTextWriterEndElement(wr); }; set<uint> DlgWznmAppWrite::ContInfWrc::comm( const ContInfWrc* comp ) { set<uint> items; if (TxtPrg == comp->TxtPrg) insert(items, TXTPRG); return(items); }; set<uint> DlgWznmAppWrite::ContInfWrc::diff( const ContInfWrc* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {TXTPRG}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class DlgWznmAppWrite::StatApp ******************************************************************************/ void DlgWznmAppWrite::StatApp::writeJSON( Json::Value& sup , string difftag , const bool initdone , const string& shortMenu ) { if (difftag.length() == 0) difftag = "StatAppDlgWznmAppWrite"; Json::Value& me = sup[difftag] = Json::Value(Json::objectValue); me["initdone"] = initdone; me["shortMenu"] = shortMenu; }; void DlgWznmAppWrite::StatApp::writeXML( xmlTextWriter* wr , string difftag , bool shorttags , const bool initdone , const string& shortMenu ) { if (difftag.length() == 0) difftag = "StatAppDlgWznmAppWrite"; string itemtag; if (shorttags) itemtag = "Si"; else itemtag = "StatitemAppDlgWznmAppWrite"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); writeBoolAttr(wr, itemtag, "sref", "initdone", initdone); writeStringAttr(wr, itemtag, "sref", "shortMenu", shortMenu); xmlTextWriterEndElement(wr); }; /****************************************************************************** class DlgWznmAppWrite::StatShr ******************************************************************************/ DlgWznmAppWrite::StatShr::StatShr( const bool ButDneActive ) : Block() { this->ButDneActive = ButDneActive; mask = {BUTDNEACTIVE}; }; void DlgWznmAppWrite::StatShr::writeJSON( Json::Value& sup , string difftag ) { if (difftag.length() == 0) difftag = "StatShrDlgWznmAppWrite"; Json::Value& me = sup[difftag] = Json::Value(Json::objectValue); me["ButDneActive"] = ButDneActive; }; void DlgWznmAppWrite::StatShr::writeXML( xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "StatShrDlgWznmAppWrite"; string itemtag; if (shorttags) itemtag = "Si"; else itemtag = "StatitemShrDlgWznmAppWrite"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); writeBoolAttr(wr, itemtag, "sref", "ButDneActive", ButDneActive); xmlTextWriterEndElement(wr); }; set<uint> DlgWznmAppWrite::StatShr::comm( const StatShr* comp ) { set<uint> items; if (ButDneActive == comp->ButDneActive) insert(items, BUTDNEACTIVE); return(items); }; set<uint> DlgWznmAppWrite::StatShr::diff( const StatShr* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {BUTDNEACTIVE}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class DlgWznmAppWrite::StatShrCuc ******************************************************************************/ DlgWznmAppWrite::StatShrCuc::StatShrCuc( const bool UldActive ) : Block() { this->UldActive = UldActive; mask = {ULDACTIVE}; }; void DlgWznmAppWrite::StatShrCuc::writeJSON( Json::Value& sup , string difftag ) { if (difftag.length() == 0) difftag = "StatShrDlgWznmAppWriteCuc"; Json::Value& me = sup[difftag] = Json::Value(Json::objectValue); me["UldActive"] = UldActive; }; void DlgWznmAppWrite::StatShrCuc::writeXML( xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "StatShrDlgWznmAppWriteCuc"; string itemtag; if (shorttags) itemtag = "Si"; else itemtag = "StatitemShrDlgWznmAppWriteCuc"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); writeBoolAttr(wr, itemtag, "sref", "UldActive", UldActive); xmlTextWriterEndElement(wr); }; set<uint> DlgWznmAppWrite::StatShrCuc::comm( const StatShrCuc* comp ) { set<uint> items; if (UldActive == comp->UldActive) insert(items, ULDACTIVE); return(items); }; set<uint> DlgWznmAppWrite::StatShrCuc::diff( const StatShrCuc* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {ULDACTIVE}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class DlgWznmAppWrite::StatShrFia ******************************************************************************/ DlgWznmAppWrite::StatShrFia::StatShrFia( const bool DldActive ) : Block() { this->DldActive = DldActive; mask = {DLDACTIVE}; }; void DlgWznmAppWrite::StatShrFia::writeJSON( Json::Value& sup , string difftag ) { if (difftag.length() == 0) difftag = "StatShrDlgWznmAppWriteFia"; Json::Value& me = sup[difftag] = Json::Value(Json::objectValue); me["DldActive"] = DldActive; }; void DlgWznmAppWrite::StatShrFia::writeXML( xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "StatShrDlgWznmAppWriteFia"; string itemtag; if (shorttags) itemtag = "Si"; else itemtag = "StatitemShrDlgWznmAppWriteFia"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); writeBoolAttr(wr, itemtag, "sref", "DldActive", DldActive); xmlTextWriterEndElement(wr); }; set<uint> DlgWznmAppWrite::StatShrFia::comm( const StatShrFia* comp ) { set<uint> items; if (DldActive == comp->DldActive) insert(items, DLDACTIVE); return(items); }; set<uint> DlgWznmAppWrite::StatShrFia::diff( const StatShrFia* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {DLDACTIVE}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class DlgWznmAppWrite::StatShrLfi ******************************************************************************/ DlgWznmAppWrite::StatShrLfi::StatShrLfi( const bool DldActive ) : Block() { this->DldActive = DldActive; mask = {DLDACTIVE}; }; void DlgWznmAppWrite::StatShrLfi::writeJSON( Json::Value& sup , string difftag ) { if (difftag.length() == 0) difftag = "StatShrDlgWznmAppWriteLfi"; Json::Value& me = sup[difftag] = Json::Value(Json::objectValue); me["DldActive"] = DldActive; }; void DlgWznmAppWrite::StatShrLfi::writeXML( xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "StatShrDlgWznmAppWriteLfi"; string itemtag; if (shorttags) itemtag = "Si"; else itemtag = "StatitemShrDlgWznmAppWriteLfi"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); writeBoolAttr(wr, itemtag, "sref", "DldActive", DldActive); xmlTextWriterEndElement(wr); }; set<uint> DlgWznmAppWrite::StatShrLfi::comm( const StatShrLfi* comp ) { set<uint> items; if (DldActive == comp->DldActive) insert(items, DLDACTIVE); return(items); }; set<uint> DlgWznmAppWrite::StatShrLfi::diff( const StatShrLfi* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {DLDACTIVE}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class DlgWznmAppWrite::StatShrWrc ******************************************************************************/ DlgWznmAppWrite::StatShrWrc::StatShrWrc( const bool ButRunActive , const bool ButStoActive ) : Block() { this->ButRunActive = ButRunActive; this->ButStoActive = ButStoActive; mask = {BUTRUNACTIVE, BUTSTOACTIVE}; }; void DlgWznmAppWrite::StatShrWrc::writeJSON( Json::Value& sup , string difftag ) { if (difftag.length() == 0) difftag = "StatShrDlgWznmAppWriteWrc"; Json::Value& me = sup[difftag] = Json::Value(Json::objectValue); me["ButRunActive"] = ButRunActive; me["ButStoActive"] = ButStoActive; }; void DlgWznmAppWrite::StatShrWrc::writeXML( xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "StatShrDlgWznmAppWriteWrc"; string itemtag; if (shorttags) itemtag = "Si"; else itemtag = "StatitemShrDlgWznmAppWriteWrc"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); writeBoolAttr(wr, itemtag, "sref", "ButRunActive", ButRunActive); writeBoolAttr(wr, itemtag, "sref", "ButStoActive", ButStoActive); xmlTextWriterEndElement(wr); }; set<uint> DlgWznmAppWrite::StatShrWrc::comm( const StatShrWrc* comp ) { set<uint> items; if (ButRunActive == comp->ButRunActive) insert(items, BUTRUNACTIVE); if (ButStoActive == comp->ButStoActive) insert(items, BUTSTOACTIVE); return(items); }; set<uint> DlgWznmAppWrite::StatShrWrc::diff( const StatShrWrc* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {BUTRUNACTIVE, BUTSTOACTIVE}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class DlgWznmAppWrite::Tag ******************************************************************************/ void DlgWznmAppWrite::Tag::writeJSON( const uint ixWznmVLocale , Json::Value& sup , string difftag ) { if (difftag.length() == 0) difftag = "TagDlgWznmAppWrite"; Json::Value& me = sup[difftag] = Json::Value(Json::objectValue); if (ixWznmVLocale == VecWznmVLocale::ENUS) { me["Cpt"] = "Write code"; }; me["ButDne"] = StrMod::cap(VecWznmVTag::getTitle(VecWznmVTag::DONE, ixWznmVLocale)); }; void DlgWznmAppWrite::Tag::writeXML( const uint ixWznmVLocale , xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "TagDlgWznmAppWrite"; string itemtag; if (shorttags) itemtag = "Ti"; else itemtag = "TagitemDlgWznmAppWrite"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); if (ixWznmVLocale == VecWznmVLocale::ENUS) { writeStringAttr(wr, itemtag, "sref", "Cpt", "Write code"); }; writeStringAttr(wr, itemtag, "sref", "ButDne", StrMod::cap(VecWznmVTag::getTitle(VecWznmVTag::DONE, ixWznmVLocale))); xmlTextWriterEndElement(wr); }; /****************************************************************************** class DlgWznmAppWrite::TagCuc ******************************************************************************/ void DlgWznmAppWrite::TagCuc::writeJSON( const uint ixWznmVLocale , Json::Value& sup , string difftag ) { if (difftag.length() == 0) difftag = "TagDlgWznmAppWriteCuc"; Json::Value& me = sup[difftag] = Json::Value(Json::objectValue); if (ixWznmVLocale == VecWznmVLocale::ENUS) { }; me["Uld"] = StrMod::cap(VecWznmVTag::getTitle(VecWznmVTag::UPLOAD, ixWznmVLocale)); me["Cpt"] = StrMod::cap(VecWznmVTag::getTitle(VecWznmVTag::FILENAME, ixWznmVLocale)); }; void DlgWznmAppWrite::TagCuc::writeXML( const uint ixWznmVLocale , xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "TagDlgWznmAppWriteCuc"; string itemtag; if (shorttags) itemtag = "Ti"; else itemtag = "TagitemDlgWznmAppWriteCuc"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); if (ixWznmVLocale == VecWznmVLocale::ENUS) { }; writeStringAttr(wr, itemtag, "sref", "Uld", StrMod::cap(VecWznmVTag::getTitle(VecWznmVTag::UPLOAD, ixWznmVLocale))); writeStringAttr(wr, itemtag, "sref", "Cpt", StrMod::cap(VecWznmVTag::getTitle(VecWznmVTag::FILENAME, ixWznmVLocale))); xmlTextWriterEndElement(wr); }; /****************************************************************************** class DlgWznmAppWrite::TagDet ******************************************************************************/ void DlgWznmAppWrite::TagDet::writeJSON( const uint ixWznmVLocale , Json::Value& sup , string difftag ) { if (difftag.length() == 0) difftag = "TagDlgWznmAppWriteDet"; Json::Value& me = sup[difftag] = Json::Value(Json::objectValue); if (ixWznmVLocale == VecWznmVLocale::ENUS) { me["CptUsf"] = "Unspec. st. mach. features"; }; }; void DlgWznmAppWrite::TagDet::writeXML( const uint ixWznmVLocale , xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "TagDlgWznmAppWriteDet"; string itemtag; if (shorttags) itemtag = "Ti"; else itemtag = "TagitemDlgWznmAppWriteDet"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); if (ixWznmVLocale == VecWznmVLocale::ENUS) { writeStringAttr(wr, itemtag, "sref", "CptUsf", "Unspec. st. mach. features"); }; xmlTextWriterEndElement(wr); }; /****************************************************************************** class DlgWznmAppWrite::TagFia ******************************************************************************/ void DlgWznmAppWrite::TagFia::writeJSON( const uint ixWznmVLocale , Json::Value& sup , string difftag ) { if (difftag.length() == 0) difftag = "TagDlgWznmAppWriteFia"; Json::Value& me = sup[difftag] = Json::Value(Json::objectValue); if (ixWznmVLocale == VecWznmVLocale::ENUS) { }; me["Dld"] = StrMod::cap(VecWznmVTag::getTitle(VecWznmVTag::DOWNLOAD, ixWznmVLocale)); }; void DlgWznmAppWrite::TagFia::writeXML( const uint ixWznmVLocale , xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "TagDlgWznmAppWriteFia"; string itemtag; if (shorttags) itemtag = "Ti"; else itemtag = "TagitemDlgWznmAppWriteFia"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); if (ixWznmVLocale == VecWznmVLocale::ENUS) { }; writeStringAttr(wr, itemtag, "sref", "Dld", StrMod::cap(VecWznmVTag::getTitle(VecWznmVTag::DOWNLOAD, ixWznmVLocale))); xmlTextWriterEndElement(wr); }; /****************************************************************************** class DlgWznmAppWrite::TagLfi ******************************************************************************/ void DlgWznmAppWrite::TagLfi::writeJSON( const uint ixWznmVLocale , Json::Value& sup , string difftag ) { if (difftag.length() == 0) difftag = "TagDlgWznmAppWriteLfi"; Json::Value& me = sup[difftag] = Json::Value(Json::objectValue); if (ixWznmVLocale == VecWznmVLocale::ENUS) { }; me["Dld"] = StrMod::cap(VecWznmVTag::getTitle(VecWznmVTag::DOWNLOAD, ixWznmVLocale)); }; void DlgWznmAppWrite::TagLfi::writeXML( const uint ixWznmVLocale , xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "TagDlgWznmAppWriteLfi"; string itemtag; if (shorttags) itemtag = "Ti"; else itemtag = "TagitemDlgWznmAppWriteLfi"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); if (ixWznmVLocale == VecWznmVLocale::ENUS) { }; writeStringAttr(wr, itemtag, "sref", "Dld", StrMod::cap(VecWznmVTag::getTitle(VecWznmVTag::DOWNLOAD, ixWznmVLocale))); xmlTextWriterEndElement(wr); }; /****************************************************************************** class DlgWznmAppWrite::TagWrc ******************************************************************************/ void DlgWznmAppWrite::TagWrc::writeJSON( const uint ixWznmVLocale , Json::Value& sup , string difftag ) { if (difftag.length() == 0) difftag = "TagDlgWznmAppWriteWrc"; Json::Value& me = sup[difftag] = Json::Value(Json::objectValue); if (ixWznmVLocale == VecWznmVLocale::ENUS) { }; me["CptPrg"] = StrMod::cap(VecWznmVTag::getTitle(VecWznmVTag::PROGRESS, ixWznmVLocale)); me["ButRun"] = StrMod::cap(VecWznmVTag::getTitle(VecWznmVTag::RUN, ixWznmVLocale)); me["ButSto"] = StrMod::cap(VecWznmVTag::getTitle(VecWznmVTag::STOP, ixWznmVLocale)); }; void DlgWznmAppWrite::TagWrc::writeXML( const uint ixWznmVLocale , xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "TagDlgWznmAppWriteWrc"; string itemtag; if (shorttags) itemtag = "Ti"; else itemtag = "TagitemDlgWznmAppWriteWrc"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); if (ixWznmVLocale == VecWznmVLocale::ENUS) { }; writeStringAttr(wr, itemtag, "sref", "CptPrg", StrMod::cap(VecWznmVTag::getTitle(VecWznmVTag::PROGRESS, ixWznmVLocale))); writeStringAttr(wr, itemtag, "sref", "ButRun", StrMod::cap(VecWznmVTag::getTitle(VecWznmVTag::RUN, ixWznmVLocale))); writeStringAttr(wr, itemtag, "sref", "ButSto", StrMod::cap(VecWznmVTag::getTitle(VecWznmVTag::STOP, ixWznmVLocale))); xmlTextWriterEndElement(wr); }; /****************************************************************************** class DlgWznmAppWrite::DpchAppData ******************************************************************************/ DlgWznmAppWrite::DpchAppData::DpchAppData() : DpchAppWznm(VecWznmVDpch::DPCHAPPDLGWZNMAPPWRITEDATA) { }; string DlgWznmAppWrite::DpchAppData::getSrefsMask() { vector<string> ss; string srefs; if (has(JREF)) ss.push_back("jref"); if (has(CONTIAC)) ss.push_back("contiac"); if (has(CONTIACDET)) ss.push_back("contiacdet"); StrMod::vectorToString(ss, srefs); return(srefs); }; void DlgWznmAppWrite::DpchAppData::readJSON( Json::Value& sup , bool addbasetag ) { clear(); bool basefound; Json::Value& me = sup; if (addbasetag) me = sup["DpchAppDlgWznmAppWriteData"]; basefound = (me != Json::nullValue); if (basefound) { if (me.isMember("scrJref")) {jref = Scr::descramble(me["scrJref"].asString()); add(JREF);}; if (contiac.readJSON(me, true)) add(CONTIAC); if (contiacdet.readJSON(me, true)) add(CONTIACDET); } else { contiac = ContIac(); contiacdet = ContIacDet(); }; }; void DlgWznmAppWrite::DpchAppData::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); string scrJref; bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "DpchAppDlgWznmAppWriteData"); else basefound = checkXPath(docctx, basexpath); if (basefound) { if (extractStringUclc(docctx, basexpath, "scrJref", "", scrJref)) { jref = Scr::descramble(scrJref); add(JREF); }; if (contiac.readXML(docctx, basexpath, true)) add(CONTIAC); if (contiacdet.readXML(docctx, basexpath, true)) add(CONTIACDET); } else { contiac = ContIac(); contiacdet = ContIacDet(); }; }; /****************************************************************************** class DlgWznmAppWrite::DpchAppDo ******************************************************************************/ DlgWznmAppWrite::DpchAppDo::DpchAppDo() : DpchAppWznm(VecWznmVDpch::DPCHAPPDLGWZNMAPPWRITEDO) { ixVDo = 0; ixVDoWrc = 0; }; string DlgWznmAppWrite::DpchAppDo::getSrefsMask() { vector<string> ss; string srefs; if (has(JREF)) ss.push_back("jref"); if (has(IXVDO)) ss.push_back("ixVDo"); if (has(IXVDOWRC)) ss.push_back("ixVDoWrc"); StrMod::vectorToString(ss, srefs); return(srefs); }; void DlgWznmAppWrite::DpchAppDo::readJSON( Json::Value& sup , bool addbasetag ) { clear(); bool basefound; Json::Value& me = sup; if (addbasetag) me = sup["DpchAppDlgWznmAppWriteDo"]; basefound = (me != Json::nullValue); if (basefound) { if (me.isMember("scrJref")) {jref = Scr::descramble(me["scrJref"].asString()); add(JREF);}; if (me.isMember("srefIxVDo")) {ixVDo = VecVDo::getIx(me["srefIxVDo"].asString()); add(IXVDO);}; if (me.isMember("srefIxVDoWrc")) {ixVDoWrc = VecVDoWrc::getIx(me["srefIxVDoWrc"].asString()); add(IXVDOWRC);}; } else { }; }; void DlgWznmAppWrite::DpchAppDo::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); string scrJref; string srefIxVDo; string srefIxVDoWrc; bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "DpchAppDlgWznmAppWriteDo"); else basefound = checkXPath(docctx, basexpath); if (basefound) { if (extractStringUclc(docctx, basexpath, "scrJref", "", scrJref)) { jref = Scr::descramble(scrJref); add(JREF); }; if (extractStringUclc(docctx, basexpath, "srefIxVDo", "", srefIxVDo)) { ixVDo = VecVDo::getIx(srefIxVDo); add(IXVDO); }; if (extractStringUclc(docctx, basexpath, "srefIxVDoWrc", "", srefIxVDoWrc)) { ixVDoWrc = VecVDoWrc::getIx(srefIxVDoWrc); add(IXVDOWRC); }; } else { }; }; /****************************************************************************** class DlgWznmAppWrite::DpchEngData ******************************************************************************/ DlgWznmAppWrite::DpchEngData::DpchEngData( const ubigint jref , ContIac* contiac , ContIacDet* contiacdet , ContInf* continf , ContInfFia* continffia , ContInfLfi* continflfi , ContInfWrc* continfwrc , Feed* feedFDse , Feed* feedFSge , StatShr* statshr , StatShrCuc* statshrcuc , StatShrFia* statshrfia , StatShrLfi* statshrlfi , StatShrWrc* statshrwrc , const set<uint>& mask ) : DpchEngWznm(VecWznmVDpch::DPCHENGDLGWZNMAPPWRITEDATA, jref) { if (find(mask, ALL)) this->mask = {JREF, CONTIAC, CONTIACDET, CONTINF, CONTINFFIA, CONTINFLFI, CONTINFWRC, FEEDFDSE, FEEDFSGE, STATAPP, STATSHR, STATSHRCUC, STATSHRFIA, STATSHRLFI, STATSHRWRC, TAG, TAGCUC, TAGDET, TAGFIA, TAGLFI, TAGWRC}; else this->mask = mask; if (find(this->mask, CONTIAC) && contiac) this->contiac = *contiac; if (find(this->mask, CONTIACDET) && contiacdet) this->contiacdet = *contiacdet; if (find(this->mask, CONTINF) && continf) this->continf = *continf; if (find(this->mask, CONTINFFIA) && continffia) this->continffia = *continffia; if (find(this->mask, CONTINFLFI) && continflfi) this->continflfi = *continflfi; if (find(this->mask, CONTINFWRC) && continfwrc) this->continfwrc = *continfwrc; if (find(this->mask, FEEDFDSE) && feedFDse) this->feedFDse = *feedFDse; if (find(this->mask, FEEDFSGE) && feedFSge) this->feedFSge = *feedFSge; if (find(this->mask, STATSHR) && statshr) this->statshr = *statshr; if (find(this->mask, STATSHRCUC) && statshrcuc) this->statshrcuc = *statshrcuc; if (find(this->mask, STATSHRFIA) && statshrfia) this->statshrfia = *statshrfia; if (find(this->mask, STATSHRLFI) && statshrlfi) this->statshrlfi = *statshrlfi; if (find(this->mask, STATSHRWRC) && statshrwrc) this->statshrwrc = *statshrwrc; }; string DlgWznmAppWrite::DpchEngData::getSrefsMask() { vector<string> ss; string srefs; if (has(JREF)) ss.push_back("jref"); if (has(CONTIAC)) ss.push_back("contiac"); if (has(CONTIACDET)) ss.push_back("contiacdet"); if (has(CONTINF)) ss.push_back("continf"); if (has(CONTINFFIA)) ss.push_back("continffia"); if (has(CONTINFLFI)) ss.push_back("continflfi"); if (has(CONTINFWRC)) ss.push_back("continfwrc"); if (has(FEEDFDSE)) ss.push_back("feedFDse"); if (has(FEEDFSGE)) ss.push_back("feedFSge"); if (has(STATAPP)) ss.push_back("statapp"); if (has(STATSHR)) ss.push_back("statshr"); if (has(STATSHRCUC)) ss.push_back("statshrcuc"); if (has(STATSHRFIA)) ss.push_back("statshrfia"); if (has(STATSHRLFI)) ss.push_back("statshrlfi"); if (has(STATSHRWRC)) ss.push_back("statshrwrc"); if (has(TAG)) ss.push_back("tag"); if (has(TAGCUC)) ss.push_back("tagcuc"); if (has(TAGDET)) ss.push_back("tagdet"); if (has(TAGFIA)) ss.push_back("tagfia"); if (has(TAGLFI)) ss.push_back("taglfi"); if (has(TAGWRC)) ss.push_back("tagwrc"); StrMod::vectorToString(ss, srefs); return(srefs); }; void DlgWznmAppWrite::DpchEngData::merge( DpchEngWznm* dpcheng ) { DpchEngData* src = (DpchEngData*) dpcheng; if (src->has(JREF)) {jref = src->jref; add(JREF);}; if (src->has(CONTIAC)) {contiac = src->contiac; add(CONTIAC);}; if (src->has(CONTIACDET)) {contiacdet = src->contiacdet; add(CONTIACDET);}; if (src->has(CONTINF)) {continf = src->continf; add(CONTINF);}; if (src->has(CONTINFFIA)) {continffia = src->continffia; add(CONTINFFIA);}; if (src->has(CONTINFLFI)) {continflfi = src->continflfi; add(CONTINFLFI);}; if (src->has(CONTINFWRC)) {continfwrc = src->continfwrc; add(CONTINFWRC);}; if (src->has(FEEDFDSE)) {feedFDse = src->feedFDse; add(FEEDFDSE);}; if (src->has(FEEDFSGE)) {feedFSge = src->feedFSge; add(FEEDFSGE);}; if (src->has(STATAPP)) add(STATAPP); if (src->has(STATSHR)) {statshr = src->statshr; add(STATSHR);}; if (src->has(STATSHRCUC)) {statshrcuc = src->statshrcuc; add(STATSHRCUC);}; if (src->has(STATSHRFIA)) {statshrfia = src->statshrfia; add(STATSHRFIA);}; if (src->has(STATSHRLFI)) {statshrlfi = src->statshrlfi; add(STATSHRLFI);}; if (src->has(STATSHRWRC)) {statshrwrc = src->statshrwrc; add(STATSHRWRC);}; if (src->has(TAG)) add(TAG); if (src->has(TAGCUC)) add(TAGCUC); if (src->has(TAGDET)) add(TAGDET); if (src->has(TAGFIA)) add(TAGFIA); if (src->has(TAGLFI)) add(TAGLFI); if (src->has(TAGWRC)) add(TAGWRC); }; void DlgWznmAppWrite::DpchEngData::writeJSON( const uint ixWznmVLocale , Json::Value& sup ) { Json::Value& me = sup["DpchEngDlgWznmAppWriteData"] = Json::Value(Json::objectValue); if (has(JREF)) me["scrJref"] = Scr::scramble(jref); if (has(CONTIAC)) contiac.writeJSON(me); if (has(CONTIACDET)) contiacdet.writeJSON(me); if (has(CONTINF)) continf.writeJSON(me); if (has(CONTINFFIA)) continffia.writeJSON(me); if (has(CONTINFLFI)) continflfi.writeJSON(me); if (has(CONTINFWRC)) continfwrc.writeJSON(me); if (has(FEEDFDSE)) feedFDse.writeJSON(me); if (has(FEEDFSGE)) feedFSge.writeJSON(me); if (has(STATAPP)) StatApp::writeJSON(me); if (has(STATSHR)) statshr.writeJSON(me); if (has(STATSHRCUC)) statshrcuc.writeJSON(me); if (has(STATSHRFIA)) statshrfia.writeJSON(me); if (has(STATSHRLFI)) statshrlfi.writeJSON(me); if (has(STATSHRWRC)) statshrwrc.writeJSON(me); if (has(TAG)) Tag::writeJSON(ixWznmVLocale, me); if (has(TAGCUC)) TagCuc::writeJSON(ixWznmVLocale, me); if (has(TAGDET)) TagDet::writeJSON(ixWznmVLocale, me); if (has(TAGFIA)) TagFia::writeJSON(ixWznmVLocale, me); if (has(TAGLFI)) TagLfi::writeJSON(ixWznmVLocale, me); if (has(TAGWRC)) TagWrc::writeJSON(ixWznmVLocale, me); }; void DlgWznmAppWrite::DpchEngData::writeXML( const uint ixWznmVLocale , xmlTextWriter* wr ) { xmlTextWriterStartElement(wr, BAD_CAST "DpchEngDlgWznmAppWriteData"); xmlTextWriterWriteAttribute(wr, BAD_CAST "xmlns", BAD_CAST "http://www.mpsitech.com/wznm"); if (has(JREF)) writeString(wr, "scrJref", Scr::scramble(jref)); if (has(CONTIAC)) contiac.writeXML(wr); if (has(CONTIACDET)) contiacdet.writeXML(wr); if (has(CONTINF)) continf.writeXML(wr); if (has(CONTINFFIA)) continffia.writeXML(wr); if (has(CONTINFLFI)) continflfi.writeXML(wr); if (has(CONTINFWRC)) continfwrc.writeXML(wr); if (has(FEEDFDSE)) feedFDse.writeXML(wr); if (has(FEEDFSGE)) feedFSge.writeXML(wr); if (has(STATAPP)) StatApp::writeXML(wr); if (has(STATSHR)) statshr.writeXML(wr); if (has(STATSHRCUC)) statshrcuc.writeXML(wr); if (has(STATSHRFIA)) statshrfia.writeXML(wr); if (has(STATSHRLFI)) statshrlfi.writeXML(wr); if (has(STATSHRWRC)) statshrwrc.writeXML(wr); if (has(TAG)) Tag::writeXML(ixWznmVLocale, wr); if (has(TAGCUC)) TagCuc::writeXML(ixWznmVLocale, wr); if (has(TAGDET)) TagDet::writeXML(ixWznmVLocale, wr); if (has(TAGFIA)) TagFia::writeXML(ixWznmVLocale, wr); if (has(TAGLFI)) TagLfi::writeXML(ixWznmVLocale, wr); if (has(TAGWRC)) TagWrc::writeXML(ixWznmVLocale, wr); xmlTextWriterEndElement(wr); };
26.730323
239
0.624348
[ "vector" ]
7722564fff555d3e6030ca86cf06eb32667d10fc
1,331
cpp
C++
PC/SDK/Entity/entity.cpp
sn0wyQ/SQ-Project-CSGO-Arduino
50515e44b55d9e867c8eb60fa79e4737244b3990
[ "BSD-3-Clause" ]
25
2021-07-15T14:31:06.000Z
2022-03-26T11:51:30.000Z
PC/SDK/Entity/entity.cpp
sn0wyQ/SQ-Project-CSGO-Arduino
50515e44b55d9e867c8eb60fa79e4737244b3990
[ "BSD-3-Clause" ]
7
2021-07-16T07:25:00.000Z
2022-02-25T13:20:17.000Z
PC/SDK/Entity/entity.cpp
sn0wyQ/SQ-Project-CSGO-Arduino
50515e44b55d9e867c8eb60fa79e4737244b3990
[ "BSD-3-Clause" ]
null
null
null
#include "entity.h" Entity::Entity(DWORD address) : address_(address) {} DWORD Entity::GetAddress() const { return address_; } int Entity::GetHP() const { return Memory::Read<int>(address_ + NetVars::m_iHealth); } bool Entity::IsAlive() const { return (this->GetHP() > 0); } bool Entity::IsDormant() const { return Memory::Read<bool>(address_ + Signatures::m_bDormant); } Team Entity::GetTeam() const { return static_cast<Team>(Memory::Read<int>(address_ + NetVars::m_iTeamNum)); } int Entity::GetFlags() const { return Memory::Read<int>(address_ + NetVars::m_fFlags); } bool Entity::IsInAir() const { return !(this->GetFlags() & FL_ON_GROUND); } Vector Entity::GetPos() const { return Memory::Read<Vector>(address_ + NetVars::m_vecOrigin); } Vector Entity::GetViewAngle() const { return Memory::Read<Vector>(address_ + NetVars::m_vecViewOffset); } Vector Entity::GetView() const { return (this->GetPos() + this->GetViewAngle()); } Vector Entity::GetBonePos(int bone) const { const auto matrix_address = Memory::Read<DWORD>(address_ + NetVars::m_dwBoneMatrix); return Vector(Memory::Read<float>(matrix_address + (0x30 * bone) + 0xC), Memory::Read<float>(matrix_address + (0x30 * bone) + 0x1C), Memory::Read<float>(matrix_address + (0x30 * bone) + 0x2C)); }
25.596154
78
0.67994
[ "vector" ]
772d914c177d0a5f56b92d307506729d1c6f4a9f
30,686
hxx
C++
itkCudaRWSegmentationFilter/itkCudaRWSegmentationFilter.hxx
enricperera/itkRWSegmentationFilter
0188a4cfa31c8798301af58c37b28d430efdef06
[ "Apache-2.0" ]
1
2021-01-20T13:29:02.000Z
2021-01-20T13:29:02.000Z
itkCudaRWSegmentationFilter/itkCudaRWSegmentationFilter.hxx
enricperera/itkRWSegmentationFilter
0188a4cfa31c8798301af58c37b28d430efdef06
[ "Apache-2.0" ]
1
2020-04-10T09:48:45.000Z
2020-04-10T09:48:45.000Z
Plugins/org.upf.rwSegmentationPlugin/src/internal/itkCudaRWSegmentationFilter/itkCudaRWSegmentationFilter.hxx
enricperera/mitkRWSegmentationPlugin
20e4bbb7bd977fdc929e694a233410af1aa67cab
[ "BSD-2-Clause" ]
null
null
null
/*========================================================================= * * Copyright Universitat Pompeu Fabra, Department of Information and * Comunication Technologies. * * 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.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef itkCudaRWSegmentationFilter_hxx #define itkCudaRWSegmentationFilter_hxx #include <itkImageRegionIterator.h> #include <itkImageRegionConstIterator.h> #include <vector> #include <Eigen/Dense> #include <Eigen/Sparse> #define CLEANUP(s) \ do \ { \ printf("%s\n", s); \ fflush(stdout); \ } while (0) namespace itk { template <typename TInputImage, typename TOutputImage> void CudaRWSegmentationFilter<TInputImage, TOutputImage>::GenerateData() { if (m_LabelImage == nullptr) // Exit if SetLabelImage has not been called { std::cout << "Label image has not been set" << std::endl; return; } if (OutputImageType::ImageDimension != 2 && OutputImageType::ImageDimension != 3) { std::cout << "Exit segmentation. Image dimension must be 2 or 3 but is " << OutputImageType::ImageDimension << std::endl; return; } // Get regions to iterate for original and label images typename OutputImageType::RegionType regionLabel = m_LabelImage->GetLargestPossibleRegion(); // Set label image iterator to get the bounding box size and the quantity of marked nodes typedef itk::ImageRegionIterator<OutputImageType> IteratorLabelType; IteratorLabelType itLabel(m_LabelImage, regionLabel); // Crop image to bounds containin labels typename OutputImageType::RegionType regionLabelCrop; typename InputImageType::RegionType regionCrop; for (int i = 0; i != OutputImageType::ImageDimension; ++i) { regionLabelCrop.SetSize(i, regionLabel.GetIndex()[i]); regionLabelCrop.SetIndex(i, regionLabel.GetSize()[i]); } int markedLength = 0; itLabel.GoToBegin(); while (!itLabel.IsAtEnd()) { // Get image boundaries to crop image if (itLabel.Get() != 0) { ++markedLength; // Get bounding region for (int i = 0; i != OutputImageType::ImageDimension; ++i) { if (itLabel.GetIndex()[i] < regionLabelCrop.GetIndex()[i]) { regionCrop.SetIndex(i, itLabel.GetIndex()[i]); regionLabelCrop.SetIndex(i, itLabel.GetIndex()[i]); } else if (itLabel.GetIndex()[i] > regionLabelCrop.GetSize()[i]) { regionCrop.SetSize(i, itLabel.GetIndex()[i]); regionLabelCrop.SetSize(i, itLabel.GetIndex()[i]); } } } ++itLabel; } int totalNodes = 1; for (int i = 0; i != OutputImageType::ImageDimension; ++i) { regionCrop.SetIndex(i, regionCrop.GetIndex()[i]); regionLabelCrop.SetIndex(i, regionLabelCrop.GetIndex()[i]); regionCrop.SetSize(i, regionCrop.GetSize()[i] - regionCrop.GetIndex()[i] + 1); regionLabelCrop.SetSize(i, regionLabelCrop.GetSize()[i] - regionLabelCrop.GetIndex()[i] + 1); totalNodes *= regionCrop.GetSize()[i]; } /////////////////////// Build Graph ///////////////////////////// /* // Create graph. Each node will correspond to a pixel connected to its neighbors by an edge. // Neighbors are those nodes which distance is 1 ( d = sqrt((x-xi)² + (y-yi)² + (z-zi)²) = 1 ), // where x, y, and z are the indices of a pixel and xi, yi, and zi are the indeces of a neighboring pixel // Iterate through all pixels of input and label images */ int unmarkedLength = totalNodes - markedLength; /* Quantity of unmarked nodes */ // Define vectors to store graph data std::vector<float> *nodes = new std::vector<float>(totalNodes); /* Pixel intensity for all nodes/pixels */ std::vector<float> *labels = new std::vector<float>(totalNodes); /* Label of each node/pixel */ /* For node 'i'. If 'i' is a marked node, previousFound->at(i) is how many unmarked nodes there are before node 'i'. If 'i' is an unmarked node, previousFound->at(i) is how many marked nodes there are before node 'i'. This values are needed to build ordered Lu and BT matrices. */ std::vector<int> *previousFound = new std::vector<int>(totalNodes); std::vector<int> *unmarked = new std::vector<int>(unmarkedLength); /* Indices of unmarked nodes ordered */ std::vector<int> *marked = new std::vector<int>(markedLength); /* Store labels of marked nodes */ std::vector<int> *markedIdx = new std::vector<int>(markedLength); /* Indices of marked nodes ordered */ std::vector<int> *nameLabels = new std::vector<int>(); /* Values of the different labels of the prior */ // Set bounding box image iterators typedef itk::ImageRegionConstIterator<InputImageType> ConstIteratorImageType; ConstIteratorImageType itImageCrop(this->GetInput(), regionCrop); IteratorLabelType itLabelCrop(m_LabelImage, regionLabelCrop); int foundMarked = 0; int foundUnmarked = 0; int NodeIdx = 0; itImageCrop.GoToBegin(); itLabelCrop.GoToBegin(); while (!itImageCrop.IsAtEnd()) { // Store intensity in a std::vector nodes->at(NodeIdx) = itImageCrop.Get(); // Store labels in a std::vector. Each index of 'nodes' and 'labels' correspond to the same pixel labels->at(NodeIdx) = itLabelCrop.Get(); if (itLabelCrop.Get() == 0) { // Get the index of each node that is unmarked unmarked->at(foundUnmarked) = NodeIdx; // Store how many marked points have been found before this unmarked node previousFound->at(NodeIdx) = foundMarked; ++foundUnmarked; } else { // Set to label value if label != 0 marked->at(foundMarked) = itLabelCrop.Get(); // Get the index of each node that is marked markedIdx->at(foundMarked) = NodeIdx; // Store how many unmarked points have been found before this marked node previousFound->at(NodeIdx) = foundUnmarked; ++foundMarked; bool found; // Store the different labels in a std::vector found = std::find(nameLabels->begin(), nameLabels->end(), itLabelCrop.Get()) != nameLabels->end(); if (!found) { nameLabels->push_back(itLabelCrop.Get()); } } ++itImageCrop; ++itLabelCrop; ++NodeIdx; } // Sort labels std::sort(nameLabels->begin(), nameLabels->end()); int totalLabels = nameLabels->size(); if (m_SolveForAllLabels) { totalLabels += 1; } // Linear system: Lu * X = -BT * M // Convert marked (M) into a Eigen::Sparse matrix markedRHS. Needed for the computation of -BT * M (Eigen::SparseMatrix * Eigen::SparseMatrix) Eigen::SparseMatrix<float, Eigen::ColMajor> *markedRHS = new Eigen::SparseMatrix<float, Eigen::ColMajor>(markedLength, totalLabels - 1); for (int i = 0; i != totalLabels - 1; ++i) { int pos = 0; for (auto itMarked = marked->begin(); itMarked != marked->end(); ++itMarked) { if (*itMarked == nameLabels->at(i)) markedRHS->insert(pos, i) = 1; ++pos; } } marked->clear(); delete marked; /////////////////////// Build Laplacian matrix ///////////////////////////// // Normalize intensity gradient over image spacing std::vector<float> spacing; typename InputImageType::SpacingType space = this->GetInput()->GetSpacing(); if (OutputImageType::ImageDimension == 2) spacing = {space[1], space[0], space[0], space[1]}; else if (OutputImageType::ImageDimension == 3) spacing = {space[2], space[1], space[0], space[0], space[1], space[2]}; std::vector<int> neighbors; int x = regionCrop.GetSize()[0]; int y = regionCrop.GetSize()[1]; // Right hand of the equation: -BT * M Eigen::SparseMatrix<float, Eigen::ColMajor> *BTxM = new Eigen::SparseMatrix<float, Eigen::ColMajor>(markedLength, totalLabels - 1); // Build BT // Compare whether NumCols < NumRows for less iterations during BT building if (markedIdx->size() < unmarked->size()) { Eigen::SparseMatrix<float, Eigen::ColMajor> *BT = new Eigen::SparseMatrix<float, Eigen::ColMajor>(unmarkedLength, markedLength); BT->reserve(Eigen::VectorXi::Constant(markedLength, 6)); int node; float valNode, valNeighbor, w; // Iterate through marked nodes to build BT. Rows correspond to unmarked nodes, columns to marked nodes for (auto itMarked = markedIdx->begin(); itMarked != markedIdx->end(); ++itMarked) { valNode = nodes->at(*itMarked); // Intensity of node // Obtain neighbors indexes. right and left, top and bottom, front and back. node = *itMarked; if (OutputImageType::ImageDimension == 2) neighbors = {node - x, node - 1, node + 1, node + x}; else if (OutputImageType::ImageDimension == 3) neighbors = {node - x * y, node - x, node - 1, node + 1, node + x, node + x * y}; for (int i = 0; i != neighbors.size(); ++i) { // Make sure all the neighbors computed fall within the bounding box dimension if (neighbors.at(i) >= 0 && neighbors.at(i) < totalNodes && labels->at(neighbors.at(i)) == 0) { valNeighbor = nodes->at(neighbors.at(i)); // Intensity of neighbor pixel w = (exp(-m_Beta * pow((valNode - valNeighbor) / spacing.at(i), 2)) + 1e-6); // Intensity gradient following a Gaussian function // Columns of BT correspond to marked nodes, rows to unmarked BT->insert(neighbors.at(i) - previousFound->at(neighbors.at(i)), node - previousFound->at(node)) = -w; } } } markedIdx->clear(); // Right hand of the equation: -BT * M *BTxM = -*BT * *markedRHS; BT->resize(0, 0); BT->data().squeeze(); markedRHS->resize(0, 0); markedRHS->data().squeeze(); delete markedIdx, markedRHS, BT; } else { markedIdx->clear(); delete markedIdx; Eigen::SparseMatrix<float, Eigen::RowMajor> *BT = new Eigen::SparseMatrix<float, Eigen::RowMajor>(unmarkedLength, markedLength); BT->reserve(Eigen::VectorXi::Constant(markedLength, 6)); int node; float valNode, valNeighbor, w; // Iterate through unmarked nodes to build BT. Rows correspond to unmarked nodes, columns to marked nodes for (auto itUnmarked = unmarked->begin(); itUnmarked != unmarked->end(); ++itUnmarked) { valNode = nodes->at(*itUnmarked); // Intensity of node // Obtain neighbors indexes. right and left, top and bottom, front and back. node = *itUnmarked; if (OutputImageType::ImageDimension == 2) neighbors = {node - x, node - 1, node + 1, node + x}; else if (OutputImageType::ImageDimension == 3) neighbors = {node - x * y, node - x, node - 1, node + 1, node + x, node + x * y}; for (int i = 0; i != neighbors.size(); ++i) { // Make sure all the neighbors computed fall within the bounding box dimension if (neighbors.at(i) >= 0 && neighbors.at(i) < totalNodes && labels->at(neighbors.at(i)) != 0) { valNeighbor = nodes->at(neighbors.at(i)); // Intensity of neighbor pixel w = (exp(-m_Beta * pow((valNode - valNeighbor) / spacing.at(i), 2)) + 1e-6); // Intensity gradient following a Gaussian function // Columns of BT correspond to marked nodes, rows to unmarked BT->insert(node - previousFound->at(node), neighbors.at(i) - previousFound->at(neighbors.at(i))) = -w; } } } // Right hand of the equation: -BT * M *BTxM = -*BT * *markedRHS; BT->resize(0, 0); BT->data().squeeze(); markedRHS->resize(0, 0); markedRHS->data().squeeze(); delete markedRHS, BT; } int nnz = 0; // Build Lu. LHS of the equation Eigen::SparseMatrix<float, Eigen::RowMajor> *Lu = new Eigen::SparseMatrix<float, Eigen::RowMajor>(unmarkedLength, unmarkedLength); Lu->reserve(Eigen::VectorXi::Constant(unmarkedLength, 7)); // Iterate through unmarked nodes to build Lu. Rows correspond to unmarked nodes, columns to unmarked nodes for (auto itUnmarked = unmarked->begin(); itUnmarked != unmarked->end(); ++itUnmarked) { int node; float valNode, valNeighbor, w, degree; valNode = nodes->at(*itUnmarked); // Intensity of node // Obtain neighbors indexes. right and left, top and bottom, front and back. node = *itUnmarked; if (OutputImageType::ImageDimension == 2) neighbors = {node - x, node - 1, node + 1, node + x}; else if (OutputImageType::ImageDimension == 3) neighbors = {node - x * y, node - x, node - 1, node + 1, node + x, node + x * y}; degree = 0.0; for (int i = 0; i != neighbors.size(); ++i) { // Make sure all the neighbors computed fall within the bounding box dimension if (neighbors.at(i) >= 0 && neighbors.at(i) < totalNodes) { valNeighbor = nodes->at(neighbors.at(i)); // Intensity of neighbor pixel w = (exp(-m_Beta * pow((valNode - valNeighbor) / spacing.at(i), 2)) + 1e-6); // Intensity gradient following a Gaussian function degree += w; // Sum of the weights // Columns of Lu correspond to unmarked nodes if (labels->at(neighbors.at(i)) == 0) // If neighbor is an unmarked node, build Lu { Lu->insert(node - previousFound->at(node), neighbors.at(i) - previousFound->at(neighbors.at(i))) = -w; ++nnz; } } } // Add node degree to diagonal of Lu Lu->insert(node - previousFound->at(node), node - previousFound->at(node)) = degree; ++nnz; } Lu->makeCompressed(); Eigen::SparseMatrix<float, Eigen::RowMajor> *Lu_PreconditionerGpu = new Eigen::SparseMatrix<float, Eigen::RowMajor>(unmarkedLength, unmarkedLength); Lu_PreconditionerGpu->reserve(Eigen::VectorXi::Constant(unmarkedLength, 1)); for (int i = 0; i != unmarkedLength; ++i) Lu_PreconditionerGpu->insert(i, i) = 1 / Lu->coeffRef(i, i); Lu_PreconditionerGpu->makeCompressed(); nodes->clear(); unmarked->clear(); previousFound->clear(); neighbors.clear(); delete nodes, unmarked, previousFound; // /////////////////////// Solve linear system ///////////////////////////// // Convert BTxM into a float array for bicgstab cuda solver float *bhost_all_labels = new float[unmarkedLength * (totalLabels - 1)]; for (int i = 0; i != unmarkedLength * (totalLabels - 1); ++i) bhost_all_labels[i] = 0; for (int k = 0; k < BTxM->outerSize(); ++k) { for (Eigen::SparseMatrix<float, Eigen::ColMajor>::InnerIterator itMat(*BTxM, k); itMat; ++itMat) { bhost_all_labels[itMat.row() + k * unmarkedLength] = itMat.value(); } } // Get pointers for CSR matrices Lu and Lu_PreconditionerGpu cooValAhost = Lu->valuePtr(); csrColPtrAhost = Lu->outerIndexPtr(); cooRowPtrAhost = Lu->innerIndexPtr(); cooValAhostM = Lu_PreconditionerGpu->valuePtr(); csrColPtrAhostM = Lu_PreconditionerGpu->outerIndexPtr(); cooRowPtrAhostM = Lu_PreconditionerGpu->innerIndexPtr(); int bicgstab_exit_status, cuda_mem_cpy_exit_status, cuda_mem_free_exit_status; // Result vector probabilities = new float[unmarkedLength * (totalLabels - 1)]; probabilitiesInner = new float[unmarkedLength]; // Allocate GPU memory cuda_mem_cpy_exit_status = this->AllocGPUMemory(unmarkedLength, nnz); if (cuda_mem_cpy_exit_status != 0) { std::cout << "GPU memory allocation failed with error " << cuda_mem_cpy_exit_status << std::endl; return; } // Solve S-1 linear systems for (int linearSystem = 0; linearSystem != totalLabels - 1; ++linearSystem) { // Get pinter for each linear system RHS bhost = &bhost_all_labels[linearSystem * unmarkedLength]; // Call CUDA BiCGStab solver bicgstab_exit_status = this->BiCGStab(unmarkedLength, nnz); if (bicgstab_exit_status != 0) { std::cout << "BiCStab failed with error" << bicgstab_exit_status << std::endl; return; } for (int i = 0; i != unmarkedLength; ++i) probabilities[i + linearSystem * unmarkedLength] = probabilitiesInner[i]; } // Free GPU memeory when all linear systems have been solved cuda_mem_free_exit_status = this->FreeGPUMemory(); if (cuda_mem_free_exit_status != 0) { std::cout << "GPU memory free failed with error" << cuda_mem_free_exit_status << std::endl; } Lu->resize(0, 0); Lu->data().squeeze(); Lu_PreconditionerGpu->resize(0, 0); Lu_PreconditionerGpu->data().squeeze(); BTxM->resize(0, 0); BTxM->data().squeeze(); delete Lu, Lu_PreconditionerGpu, BTxM; delete[] probabilitiesInner, bhost, bhost_all_labels, cooRowPtrAhost, csrColPtrAhost, cooValAhost, cooRowPtrAhostM, csrColPtrAhostM, cooValAhostM; std::vector<int> *RWLabels = new std::vector<int>(unmarkedLength); /* Assign a label to each unmarked node according to the result of the solver. The label that is assigned is that one corresponding to the highest probability. Since we solver for S-1 systems, last label probability is computed by subtraction */ for (int i = 0; i != unmarkedLength; ++i) { float maxProbability = probabilities[i]; int maxLabelPos = 0; float accumulatedProbability = maxProbability; for (int j = 1; j != totalLabels - 1; ++j) { accumulatedProbability += probabilities[i + j * unmarkedLength]; if (probabilities[i + j * unmarkedLength] > maxProbability) { maxProbability = probabilities[i + j * unmarkedLength]; maxLabelPos = j; } } RWLabels->at(i) = 0.95 - accumulatedProbability > maxProbability ? nameLabels->back() : nameLabels->at(maxLabelPos); } delete[] probabilities; int valBackground; if (!m_WriteBackground) valBackground = 0; else valBackground = nameLabels->back(); typename OutputImageType::Pointer outputLabels = this->GetOutput(); outputLabels->Graft(m_LabelImage); outputLabels->FillBuffer(valBackground); // Iterate through original label image to create segmentation image // Assign labels known from label image to their original value. Assign unmarked labels // according to the result from the solver IteratorLabelType itOut1(outputLabels, regionLabelCrop); // Set computed labels to segmentation image int unmarkedIdx = 0; int idxOutput = 0; itOut1.GoToBegin(); while (!itOut1.IsAtEnd()) { if (labels->at(idxOutput) == 0) { if (RWLabels->at(unmarkedIdx) != nameLabels->back()) itOut1.Set(RWLabels->at(unmarkedIdx)); else itOut1.Set(valBackground); ++unmarkedIdx; } else if (labels->at(idxOutput) != nameLabels->back()) itOut1.Set(labels->at(idxOutput)); ++idxOutput; ++itOut1; } labels->clear(); RWLabels->clear(); nameLabels->clear(); delete labels, RWLabels, nameLabels; return; } template <typename TInputImage, typename TOutputImage> int CudaRWSegmentationFilter<TInputImage, TOutputImage>::BiCGStab(int M, int nnz) { int iter, flag; cusparseStatus_t status; cusparseHandle_t handle = 0; cusparseMatDescr_t descra = 0; int nnzM = M; int N = M; int N2 = N; float timesOne[1] = {1.0}; float timesZero[1] = {0.0}; float timesMinusOne[1] = {-1.0}; cudaStat4 = cudaMemcpy(r, bhost, (size_t)(N * sizeof(r[0])), cudaMemcpyHostToDevice); cudaStat5 = cudaMemcpy(xdev, xhost, (size_t)(N * sizeof(xdev[0])), cudaMemcpyHostToDevice); // Copy right hand side to GPU memory if ((cudaStat4 != cudaSuccess) || (cudaStat5 != cudaSuccess)) { CLEANUP("Memcpy from Host to Device failed"); return EXIT_FAILURE; } /* initialize cusparse library */ status = cusparseCreate(&handle); if (status != CUSPARSE_STATUS_SUCCESS) { CLEANUP("CUSPARSE Library initialization failed"); return EXIT_FAILURE; } /* create and setup matrix descriptor */ status = cusparseCreateMatDescr(&descra); if (status != CUSPARSE_STATUS_SUCCESS) { CLEANUP("Matrix descriptor initialization failed"); return EXIT_FAILURE; } cusparseSetMatType(descra, CUSPARSE_MATRIX_TYPE_GENERAL); cusparseSetMatIndexBase(descra, CUSPARSE_INDEX_BASE_ZERO); bnrm2 = cublasSnrm2(N, r, 1); float tol = m_Tolerance * bnrm2; status = cusparseScsrmv(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, N, N, nnz, timesMinusOne, descra, cooValAdev, csrColPtrAdev, cooRowPtrAdev, xdev, timesOne, r); /* r = r - A*x; r is now residual */ if (status != CUSPARSE_STATUS_SUCCESS) { CLEANUP("Matrix‐vector multiplication failed"); return EXIT_FAILURE; } error = cublasSnrm2(N, r, 1) / bnrm2; /* norm_r = norm(b) */ if (error < tol) { CLEANUP("Error smaller than tolerance failed"); return EXIT_FAILURE; /* x is close enough already */ } omega = 1.0; cudaStat1 = cudaMemcpy(r_tld, r, (size_t)(N * sizeof(r[0])), cudaMemcpyDeviceToDevice); /* r_tld = r */ if ((cudaStat1 != cudaSuccess)) { CLEANUP("Memcpy from r to r_tld failed"); return EXIT_FAILURE; } // Loop of the BiCGStab solver for (iter = 0; iter < m_MaximumNumberOfIterations; ++iter) { rho = cublasSdot(N, r_tld, 1, r, 1); /* rho = r_tld'*r */ if (rho == 0.0) break; if (iter > 0) { beta = (rho / rho_1) * (alpha / omega); cublasSaxpy(N, -omega, v, 1, p, 1); cublasSaxpy(N, 1.0 / beta, r, 1, p, 1); cublasSscal(N, beta, p, 1); /* p = r + beta*( p - omega*v ) */ } else { cudaStat1 = cudaMemcpy(p, r, (size_t)(N * sizeof(r[0])), cudaMemcpyDeviceToDevice); /* p = r */ if ((cudaStat1 != cudaSuccess)) { CLEANUP("Memcpy from r to p failed"); return EXIT_FAILURE; } } status = cusparseScsrmv(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, N2, N2, nnzM, timesOne, descra, cooValAdevM, csrColPtrAdevM, cooRowPtrAdevM, p, timesZero, p_hat); status = cusparseScsrmv(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, N, N, nnz, timesOne, descra, cooValAdev, csrColPtrAdev, cooRowPtrAdev, p_hat, timesZero, v); /* v = A*p_hat */ alpha = rho / cublasSdot(N, r_tld, 1, v, 1); /* alph = rho / ( r_tld'*v ) */ cudaStat1 = cudaMemcpy(s, r, (size_t)(N * sizeof(r[0])), cudaMemcpyDeviceToDevice); /* s = r */ if ((cudaStat1 != cudaSuccess)) { CLEANUP("Memcpy from r to s failed"); return EXIT_FAILURE; } cublasSaxpy(N, -alpha, v, 1, s, 1); snrm2 = cublasSnrm2(N, s, 1); cublasSaxpy(N, alpha, p_hat, 1, xdev, 1); /* h = x + alph*p_hat */ if (snrm2 < tol) { // cublasSaxpy(N, alpha, p_hat, 1, s, 1); resid = snrm2 / bnrm2; cudaStat5 = cudaMemcpy(probabilitiesInner, xdev, (size_t)(N * sizeof(probabilitiesInner[0])), cudaMemcpyDeviceToHost); /* x = h */ if ((cudaStat5 != cudaSuccess)) { CLEANUP("Memcpy from x to xhost failed"); return EXIT_FAILURE; } break; } status = cusparseScsrmv(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, N2, N2, nnzM, timesOne, descra, cooValAdevM, csrColPtrAdevM, cooRowPtrAdevM, s, timesZero, s_hat); status = cusparseScsrmv(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, N, N, nnz, timesOne, descra, cooValAdev, csrColPtrAdev, cooRowPtrAdev, s_hat, timesZero, t); /* t = A*s_hat */ omega = cublasSdot(N, t, 1, s, 1) / cublasSdot(N, t, 1, t, 1); /* omega = ( t'*s) / ( t'*t ) */ cublasSaxpy(N, omega, s_hat, 1, xdev, 1); /* x = h + omega*s_hat */ cudaStat1 = cudaMemcpy(r, s, (size_t)(N * sizeof(r[0])), cudaMemcpyDeviceToDevice); /* r = s */ if ((cudaStat1 != cudaSuccess)) { CLEANUP("Memcpy from s to r failed"); return EXIT_FAILURE; } cublasSaxpy(N, -omega, t, 1, r, 1); /* r = s - omega*t */ snrm2 = cublasSnrm2(N, r, 1); if (snrm2 <= tol) { resid = snrm2 / bnrm2; cudaStat5 = cudaMemcpy(probabilitiesInner, xdev, (size_t)(N * sizeof(probabilitiesInner[0])), cudaMemcpyDeviceToHost); /* x = x */ if ((cudaStat5 != cudaSuccess)) { CLEANUP("Memcpy from x to xhost failed"); return EXIT_FAILURE; } break; } if (omega == 0.0) break; rho_1 = rho; } ++iter; error = snrm2 / bnrm2; if (error <= tol) { flag = 0; } else if (omega == 0.0) { flag = -2; } else if (rho == 0.0) { flag = -1; } else flag = 1; m_SolverIterations += iter; m_SolverError = std::min(m_SolverError, error); return flag; } // Allocate GPU memory and copy data to device template <typename TInputImage, typename TOutputImage> int CudaRWSegmentationFilter<TInputImage, TOutputImage>::AllocGPUMemory(int M, int nnz) { int nnzM = M; // Lu has size MxM, Lu_PreconditionerGpu has size MxM int N = M; // Define initial guess xhost = new float[N]; for (int i = 0; i < N; i++) { xhost[i] = 0; } cudaStat1 = cudaMalloc((void **)&cooRowPtrAdev, nnz * sizeof(cooRowPtrAdev[0])); cudaStat3 = cudaMalloc((void **)&cooValAdev, nnz * sizeof(cooValAdev[0])); cudaStat4 = cudaMalloc((void **)&r, N * sizeof(r[0])); cudaStat5 = cudaMalloc((void **)&s, N * sizeof(s[0])); cudaStat6 = cudaMalloc((void **)&t, N * sizeof(t[0])); cudaStat7 = cudaMalloc((void **)&r_tld, N * sizeof(r_tld[0])); cudaStat8 = cudaMalloc((void **)&p, N * sizeof(p[0])); cudaStat9 = cudaMalloc((void **)&p_hat, N * sizeof(p_hat[0])); cudaStat10 = cudaMalloc((void **)&s_hat, N * sizeof(s_hat[0])); cudaStat11 = cudaMalloc((void **)&v, N * sizeof(v[0])); cudaStat12 = cudaMalloc((void **)&xdev, N * sizeof(xdev[0])); cudaStat13 = cudaMalloc((void **)&csrColPtrAdev, (N + 1) * sizeof(csrColPtrAdev[0])); cudaStat14 = cudaMalloc((void **)&cooRowPtrAdevM, nnzM * sizeof(cooRowPtrAdevM[0])); cudaStat16 = cudaMalloc((void **)&cooValAdevM, nnzM * sizeof(cooValAdevM[0])); cudaStat17 = cudaMalloc((void **)&csrColPtrAdevM, (N + 1) * sizeof(csrColPtrAdevM[0])); if ((cudaStat1 != cudaSuccess) || (cudaStat3 != cudaSuccess) || (cudaStat4 != cudaSuccess) || (cudaStat5 != cudaSuccess) || (cudaStat6 != cudaSuccess) || (cudaStat7 != cudaSuccess) || (cudaStat8 != cudaSuccess) || (cudaStat9 != cudaSuccess) || (cudaStat10 != cudaSuccess) || (cudaStat11 != cudaSuccess) || (cudaStat12 != cudaSuccess) || (cudaStat14 != cudaSuccess) || (cudaStat16 != cudaSuccess) || (cudaStat17 != cudaSuccess)) { CLEANUP("Device malloc failed"); return EXIT_FAILURE; } cudaStat1 = cudaMemcpy(cooRowPtrAdev, cooRowPtrAhost, (size_t)(nnz * sizeof(cooRowPtrAdev[0])), cudaMemcpyHostToDevice); cudaStat13 = cudaMemcpy(csrColPtrAdev, csrColPtrAhost, (size_t)((N + 1) * sizeof(csrColPtrAdev[0])), cudaMemcpyHostToDevice); cudaStat3 = cudaMemcpy(cooValAdev, cooValAhost, (size_t)(nnz * sizeof(cooValAdev[0])), cudaMemcpyHostToDevice); cudaStat14 = cudaMemcpy(cooRowPtrAdevM, cooRowPtrAhostM, (size_t)(nnzM * sizeof(cooRowPtrAdevM[0])), cudaMemcpyHostToDevice); cudaStat17 = cudaMemcpy(csrColPtrAdevM, csrColPtrAhostM, (size_t)((N + 1) * sizeof(cooColPtrAdevM[0])), cudaMemcpyHostToDevice); cudaStat16 = cudaMemcpy(cooValAdevM, cooValAhostM, (size_t)(nnzM * sizeof(cooValAdevM[0])), cudaMemcpyHostToDevice); if ((cudaStat1 != cudaSuccess) || (cudaStat13 != cudaSuccess) || (cudaStat3 != cudaSuccess) || (cudaStat14 != cudaSuccess) || (cudaStat17 != cudaSuccess) || (cudaStat16 != cudaSuccess)) { CLEANUP("Memcpy from Host to Device failed"); return EXIT_FAILURE; } return 0; } // Free GPU memeory when all linear systems have been solved template <typename TInputImage, typename TOutputImage> int CudaRWSegmentationFilter<TInputImage, TOutputImage>::FreeGPUMemory() { /* shutdown CUBLAS */ cublas_status = cublasShutdown(); if (cublas_status != CUBLAS_STATUS_SUCCESS) { fprintf(stderr, "!!!! shutdown error (A)\n"); return EXIT_FAILURE; } cudaStat1 = cudaFree(cooRowPtrAdev); cudaStat3 = cudaFree(cooValAdev); cudaStat4 = cudaFree(r); cudaStat5 = cudaFree(s); cudaStat6 = cudaFree(t); cudaStat7 = cudaFree(r_tld); cudaStat8 = cudaFree(p); cudaStat9 = cudaFree(p_hat); cudaStat10 = cudaFree(s_hat); cudaStat11 = cudaFree(v); cudaStat12 = cudaFree(xdev); cudaStat13 = cudaFree(csrColPtrAdev); cudaStat14 = cudaFree(cooRowPtrAdevM); cudaStat16 = cudaFree(cooValAdevM); cudaStat17 = cudaFree(csrColPtrAdevM); if ((cudaStat1 != cudaSuccess) || (cudaStat3 != cudaSuccess) || (cudaStat4 != cudaSuccess) || (cudaStat5 != cudaSuccess) || (cudaStat6 != cudaSuccess) || (cudaStat7 != cudaSuccess) || (cudaStat8 != cudaSuccess) || (cudaStat9 != cudaSuccess) || (cudaStat10 != cudaSuccess) || (cudaStat11 != cudaSuccess) || (cudaStat12 != cudaSuccess) || (cudaStat14 != cudaSuccess) || (cudaStat16 != cudaSuccess) || (cudaStat17 != cudaSuccess)) { CLEANUP("Device memory free failed"); return EXIT_FAILURE; } return 0; } template <typename TInputImage, typename TOutputImage> void CudaRWSegmentationFilter<TInputImage, TOutputImage>::PrintSelf(std::ostream &os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "Beta: " << m_Beta << std::endl; os << indent << "Tolerance: " << m_Tolerance << std::endl; os << indent << "MaximumNumberOfIterations: " << m_MaximumNumberOfIterations << std::endl; os << indent << "WriteBackground: " << m_WriteBackground << std::endl; } } // namespace itk #endif
35.932084
200
0.629831
[ "vector" ]
772dcd2a48fdd525df7d56e8bf01725152a348be
918
cpp
C++
Entry 1 - Into the Unknown/ex2_0_region_database.cpp
tensorush/Cpp-Deep-Dive
fa2aa46b906662cf29b48359a2f17c3ddc1b1792
[ "MIT" ]
1
2021-01-24T22:42:29.000Z
2021-01-24T22:42:29.000Z
Entry 1 - Into the Unknown/ex2_0_region_database.cpp
geotrush/Cpp-Deep-Dive
fa2aa46b906662cf29b48359a2f17c3ddc1b1792
[ "MIT" ]
null
null
null
Entry 1 - Into the Unknown/ex2_0_region_database.cpp
geotrush/Cpp-Deep-Dive
fa2aa46b906662cf29b48359a2f17c3ddc1b1792
[ "MIT" ]
1
2021-09-12T11:41:35.000Z
2021-09-12T11:41:35.000Z
/* Task You should write a function that accepts a regional database and returns the maximal number of region repetitions. */ #include <algorithm> #include <string> #include <vector> #include <tuple> #include <map> using std::max; using std::map; using std::tuple; using std::string; using std::vector; enum class Lang { DE, FR, IT }; struct Region { string std_name; string parent_std_name; map<Lang, string> names; int64_t population; }; bool operator < (const Region& lhs, const Region& rhs) { return tie(lhs.std_name, lhs.parent_std_name, lhs.names, lhs.population) < tie(rhs.std_name, rhs.parent_std_name, rhs.names, rhs.population); } int FindMaxRepetitionCount(const vector<Region>& regions) { int result = 0; map<Region, int> repetition_count; for (const Region& region : regions) { result = max(result, ++repetition_count[region]); } return result; }
21.348837
78
0.700436
[ "vector" ]
77322436aeb5739095e6426849e95b4739c2ccff
469
cpp
C++
BaekJoon/11650.cpp
falconlee236/Algorithm_Practice
4e6e380a0e6c840525ca831a05c35253eeaaa25c
[ "MIT" ]
null
null
null
BaekJoon/11650.cpp
falconlee236/Algorithm_Practice
4e6e380a0e6c840525ca831a05c35253eeaaa25c
[ "MIT" ]
null
null
null
BaekJoon/11650.cpp
falconlee236/Algorithm_Practice
4e6e380a0e6c840525ca831a05c35253eeaaa25c
[ "MIT" ]
null
null
null
/*11650*/ /*Got it!*/ #include <iostream> #include <vector> #include <algorithm> using namespace std; int main(){ ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n; cin >> n; vector<pair<int, int>> v; for(int i = 0; i < n; i++){ int a, b; cin >> a >> b; v.push_back(make_pair(a, b)); } sort(v.begin(), v.end()); for(int i = 0; i < n; i++) cout << v[i].first << " " << v[i].second << "\n"; return 0; }
23.45
80
0.513859
[ "vector" ]
773d9ae81998353c14a173d86bf2681c7ac22eb2
7,347
cpp
C++
applications/ParticlesEditor/src/Objects/ParticleField.cpp
AluminiumRat/mtt
3052f8ad0ffabead05a1033e1d714a61e77d0aa8
[ "MIT" ]
null
null
null
applications/ParticlesEditor/src/Objects/ParticleField.cpp
AluminiumRat/mtt
3052f8ad0ffabead05a1033e1d714a61e77d0aa8
[ "MIT" ]
null
null
null
applications/ParticlesEditor/src/Objects/ParticleField.cpp
AluminiumRat/mtt
3052f8ad0ffabead05a1033e1d714a61e77d0aa8
[ "MIT" ]
null
null
null
#include <algorithm> #include <exception> #include <mtt/utilities/Abort.h> #include <Objects/Fluid/FluidObject.h> #include <Objects/EmitterObject.h> #include <Objects/ModificatorObject.h> #include <Objects/ParticleField.h> ParticleField::ParticleField( const QString& name, bool canBeRenamed, const mtt::UID& theId) : MovableObject(name, canBeRenamed, theId), _size(10.f, 10.f, 10.f), _lodMppx(.005f), _lodSmoothing(1.f) { mtt::UID fluidId(id().mixedUID(18395279348825422041ull)); std::unique_ptr<FluidObject> fluid( new FluidObject(tr("Fluid"), false, *this, fluidId)); _fluid = fluid.get(); addSubobject(std::move(fluid)); } void ParticleField::setSize(const glm::vec3& newValue) { if(_size == newValue) return; _size = newValue; clear(); emit sizeChanged(_size); } void ParticleField::clear() noexcept { _workIndices.clear(); _freeIndices.clear(); _particlesData.clear(); _newParticles.clear(); _fluid->clear(); emit cleared(); } void ParticleField::addParticle(const ParticleData& particle) { _newParticles.push_back(particle); } void ParticleField::setTextureDescriptions( const ParticleTextureDescriptions& newDescriptions) { _textureDescriptions.clear(); try { _textureDescriptions = newDescriptions; } catch (...) { emit textureDescriptionsChanged(_textureDescriptions); throw; } emit textureDescriptionsChanged(_textureDescriptions); } void ParticleField::setLodMppx(float newValue) noexcept { newValue = glm::max(newValue, 0.f); if(_lodMppx == newValue) return; _lodMppx = newValue; emit lodMppxChanged(newValue); } void ParticleField::setLodSmoothing(float newValue) noexcept { newValue = glm::max(newValue, 0.f); if(_lodSmoothing == newValue) return; _lodSmoothing = newValue; emit lodSmoothingChanged(newValue); } void ParticleField::registerEmitter(EmitterObject& emitter) { if(std::find( _emitters.begin(), _emitters.end(), &emitter) != _emitters.end()) mtt::Abort("ParticleField::registerEmitter: emitter is already registerd."); _emitters.push_back(&emitter); } void ParticleField::unregisterEmitter(EmitterObject& emitter) noexcept { Emitters::iterator iEmitter = std::find(_emitters.begin(), _emitters.end(), &emitter); if(iEmitter == _emitters.end()) return; _emitters.erase(iEmitter); } void ParticleField::registerModificator(ModificatorObject& modificator) { if(std::find( _modificators.begin(), _modificators.end(), &modificator) != _modificators.end()) mtt::Abort("ParticleField::registerModificator: modificator is already registerd."); _modificators.push_back(&modificator); } void ParticleField::unregisterModificator( ModificatorObject& modificator) noexcept { Modificators::iterator iModificator = std::find(_modificators.begin(), _modificators.end(), &modificator); if(iModificator == _modificators.end()) return; _modificators.erase(iModificator); } void ParticleField::_applyModificators( mtt::TimeRange time, ModificatorApplyTime applyTime) { for (ModificatorObject* modificator : _modificators) { if(modificator->enabled() && modificator->applyTime() == applyTime) { modificator->simulationStep(time); } } } void ParticleField::simulationStep(mtt::TimeRange time) { emit simulationStepStarted(); try { for (EmitterObject* emitter : _emitters) { if(emitter->enabled()) emitter->simulationStep(time); } _addParticles(); _applyModificators(time, PREFLUID_TIME); _fluid->simulationStep(time); _applyModificators(time, POSTFLUID_TIME); _updateParticlesData(time.length()); _applyModificators(time, POSTUPDATE_TIME); _deleteParticles(); } catch (...) { mtt::Log() << "ParticleField::simulationStep: error in simulation, field will be cleared."; clear(); emit simulationStepFinished(); throw; } emit simulationStepFinished(); } void ParticleField::_addParticles() { if(_newParticles.empty()) return; std::vector<ParticleIndex> newIndices; newIndices.reserve(_newParticles.size()); if(_newParticles.size() > _freeIndices.size()) { size_t newParticlesCount = _particlesData.size() + _newParticles.size() - _freeIndices.size(); _particlesData.reserve(newParticlesCount); _workIndices.reserve(newParticlesCount); } while (!_newParticles.empty()) { ParticleData particle = _newParticles.back(); _newParticles.pop_back(); if (_freeIndices.empty()) { ParticleIndex newIndex(_particlesData.size()); _workIndices.push_back(newIndex); _particlesData.push_back(particle); newIndices.push_back(newIndex); } else { ParticleIndex newIndex = _freeIndices.back(); _workIndices.push_back(newIndex); _freeIndices.pop_back(); _particlesData[newIndex] = particle; newIndices.push_back(newIndex); } } if(!newIndices.empty()) emit particlesAdded(newIndices); } void ParticleField::_updateParticlesData(mtt::TimeT delta) { float floatDelta = mtt::toFloatTime(delta); for (ParticleIndex index : _workIndices) { ParticleData& particle = _particlesData[index]; particle.position += particle.speed * floatDelta; particle.rotation += particle.rotationSpeed * floatDelta; particle.currentTime += delta; } } void ParticleField::_deleteParticles() { if(_workIndices.empty()) return; std::vector<ParticleIndex> deletedIndices; deletedIndices.reserve(_workIndices.size()); glm::vec3 halfsize = _size / 2.f; std::vector<ParticleIndex>::iterator currentCursor = _workIndices.begin(); std::vector<ParticleIndex>::iterator copyPlace = _workIndices.begin(); while (currentCursor != _workIndices.end()) { ParticleData& particle = _particlesData[*currentCursor]; float particleRadius = particle.size / 2.f; if( particle.currentTime >= particle.maxTime || !isfinite(particle.position.x) || particle.position.x > halfsize.x - particleRadius || particle.position.x < -halfsize.x + particleRadius || !isfinite(particle.position.y) || particle.position.y > halfsize.y - particleRadius || particle.position.y < -halfsize.y + particleRadius || !isfinite(particle.position.z) || particle.position.z > halfsize.z - particleRadius || particle.position.z < -halfsize.z + particleRadius) { deletedIndices.push_back(*currentCursor); _freeIndices.push_back(*currentCursor); } else { if(copyPlace != currentCursor) *copyPlace = *currentCursor; copyPlace++; } currentCursor++; } if (copyPlace != _workIndices.end()) { _workIndices.erase(copyPlace, _workIndices.end()); } emit particlesDeleted(deletedIndices); }
27.620301
138
0.654417
[ "vector" ]
77476ecfc9726ed5db62bafea578e3cd072f211f
1,050
cpp
C++
ACM/Math and Geometry/SieveOfEratosthenes_RepeatingGoldbachs.cpp
JahodaPaul/FIT_CTU
2d96f18c7787ddfe340a15a36da6eea910225461
[ "MIT" ]
17
2019-03-09T17:13:40.000Z
2022-03-05T14:42:05.000Z
ACM/Math and Geometry/SieveOfEratosthenes_RepeatingGoldbachs.cpp
JahodaPaul/FIT_CTU
2d96f18c7787ddfe340a15a36da6eea910225461
[ "MIT" ]
1
2018-06-23T15:57:32.000Z
2018-06-23T15:57:32.000Z
ACM/Math and Geometry/SieveOfEratosthenes_RepeatingGoldbachs.cpp
JahodaPaul/FIT_CTU
2d96f18c7787ddfe340a15a36da6eea910225461
[ "MIT" ]
16
2019-04-09T00:10:55.000Z
2022-02-21T20:28:05.000Z
#include <bits/stdc++.h> using namespace std; int n; int primes[1000007]; void SieveOfEratosthenes(int n) { // Create a boolean array "prime[0..n]" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. vector<bool> prime; prime.resize((unsigned long)(n+1),true); for (int p=2; p*p<=n; ++p) { if (prime[p]) { for (int i=p*2; i<=n; i += p) prime[i] = false; } } for (int p=2; p<=n; p++) if (prime[p]) primes[p] = 1; } int main() { SieveOfEratosthenes(1000005); cin>>n; int smallIndex = 2; int result = 0; while(n >= 4){ if(primes[n - smallIndex] == 1){ n = (n - smallIndex) - smallIndex; smallIndex = 2; result++; } else{ smallIndex++; while(!primes[smallIndex]){ smallIndex++; } } } cout << result << endl; return 0; }
20.192308
58
0.475238
[ "vector" ]
7747f1df99a5759723a073c100332fab0ffd1166
2,656
hpp
C++
Sub3D/Tools.Depth.hpp
slavanap/ssifSource
739f42b62cffe4072c3a9ec602e5c595c8af7be8
[ "MIT" ]
15
2016-06-23T03:01:56.000Z
2022-02-15T23:19:17.000Z
Sub3D/Tools.Depth.hpp
slavanap/ssifSource
739f42b62cffe4072c3a9ec602e5c595c8af7be8
[ "MIT" ]
null
null
null
Sub3D/Tools.Depth.hpp
slavanap/ssifSource
739f42b62cffe4072c3a9ec602e5c595c8af7be8
[ "MIT" ]
3
2018-09-27T07:04:41.000Z
2020-07-15T05:50:22.000Z
// // 3D subtitle rendering tool // Copyright 2016 Vyacheslav Napadovsky. // // 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. #pragma once #include "Tools.Lua.hpp" #include <Tools.Motion.hpp> namespace Tools { namespace Depth { using AviSynth::Frame; using Motion::Map; using Lua::Script; inline bool subtitle_monitored_by_alpha(const Frame::Pixel& p) { return p.a != 0; } inline bool subtitle_monitored_by_color(const Frame::Pixel& p) { return p.r != 0 && p.g != 0 && p.b != 0; } template<typename F> bool IsSubtitleExists(const Frame& sub, F is_monitored) { for (auto it = sub.cbegin(); it != sub.cend(); ++it) if (is_monitored(*it)) return true; return false; } class Estimator { public: Estimator(std::shared_ptr<Script> script); template<typename F> void SetMasks(const Frame& sub, F is_monitored) { SetMasksSize(sub.width(), sub.height()); for (auto it = sub.cbegin(); it != sub.cend(); ++it) { bool m = is_monitored(*it); subtitle_mask(it.get_x(), it.get_y()) = m; auto &v = mv_mask(it.get_x() / Tools::Motion::BLOCK_SIZE, it.get_y() / Tools::Motion::BLOCK_SIZE); v = v || m; } } void SetMasksSize(int x, int y); void ProcessFrame(const Frame &left, const Frame &right, int frame_num); bool CalculateDepth(int& depth) { bool ret = m_script->CalculateForSubtitle(startFrame, lastFrame - startFrame + 1, depth); startFrame = -1; return ret; } Array2D<char> mv_mask, subtitle_mask; private: std::shared_ptr<Script> m_script; int startFrame, lastFrame; Motion::Map mv_map; }; } }
30.883721
103
0.695783
[ "3d" ]
7748bb229a2c912d070922cbf13d88b506c3b70d
4,591
cpp
C++
Google Kickstart/2019/Round 2019/B.cpp
Mindjolt2406/Competitive-Programming
d000d98bf7005ee4fb809bcea2f110e4c4793b80
[ "MIT" ]
2
2018-12-11T14:37:24.000Z
2022-01-23T18:11:54.000Z
Google Kickstart/2019/Round 2019/B.cpp
Mindjolt2406/Competitive-Programming
d000d98bf7005ee4fb809bcea2f110e4c4793b80
[ "MIT" ]
null
null
null
Google Kickstart/2019/Round 2019/B.cpp
Mindjolt2406/Competitive-Programming
d000d98bf7005ee4fb809bcea2f110e4c4793b80
[ "MIT" ]
null
null
null
/* Rathin Bhargava IIIT Bangalore */ #include<bits/stdc++.h> #define mt make_tuple #define mp make_pair #define pu push_back #define INF 1000000001 #define MOD 1000000007 #define ll long long int #define ld long double #define vi vector<int> #define vll vector<long long int> #define fi first #define se second #define pr(v) { for(int i=0;i<v.size();i++) { v[i]==INF? cout<<"INF " : cout<<v[i]<<" "; } cout<<endl;} #define t1(x) cerr<<#x<<" : "<<x<<endl #define t2(x, y) cerr<<#x<<" : "<<x<<" "<<#y<<" : "<<y<<endl #define t3(x, y, z) cerr<<#x<<" : " <<x<<" "<<#y<<" : "<<y<<" "<<#z<<" : "<<z<<endl #define t4(a,b,c,d) cerr<<#a<<" : "<<a<<" "<<#b<<" : "<<b<<" "<<#c<<" : "<<c<<" "<<#d<<" : "<<d<<endl #define t5(a,b,c,d,e) cerr<<#a<<" : "<<a<<" "<<#b<<" : "<<b<<" "<<#c<<" : "<<c<<" "<<#d<<" : "<<d<<" "<<#e<<" : "<<e<<endl #define t6(a,b,c,d,e,f) cerr<<#a<<" : "<<a<<" "<<#b<<" : "<<b<<" "<<#c<<" : "<<c<<" "<<#d<<" : "<<d<<" "<<#e<<" : "<<e<<" "<<#f<<" : "<<f<<endl #define GET_MACRO(_1,_2,_3,_4,_5,_6,NAME,...) NAME #define t(...) GET_MACRO(__VA_ARGS__,t6,t5, t4, t3, t2, t1)(__VA_ARGS__) #define _ cerr<<"here"<<endl; #define __ {ios::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);} using namespace std; const int N = 255; vector<vector<int> > vis1(N,vector<int>(N)), vis2(N,vector<int>(N)), v(N,vector<int> (N)); bool find(int k,int n,int m) { // Alternate formulation of abs(x1-x2) + abs(y1-y2) is max( abs(x2-y2-(x1-y1)), abs(x2+y2-(x1+y1)) ) // Compute min and max of x2-y2 and x2+y2 where x2 and y2 are points whose distances are greater than k // Then for each point, compare these 4 things and get the max distances for each point. Once you get them, then // return true if your max is <=k. Else return false int min1 = INF,max1 = -1,min2 = INF,max2 = -1; int flag = 0; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(vis1[i][j]>k) { min1 = min(min1,j-i); max1 = max(max1,j-i); min2 = min(min2,i+j); max2 = max(max2,i+j); flag = 1; } } } if(flag==0) return true; int dist = INF; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { int distmax = -1; // Calculate the distances for each point distmax = max(distmax,max(abs(min1-(j-i)),abs(min2-(i+j)))); distmax = max(distmax,max(abs(min1-(j-i)),abs(max2-(i+j)))); distmax = max(distmax,max(abs(max1-(j-i)),abs(min2-(i+j)))); distmax = max(distmax,max(abs(max1-(j-i)),abs(max2-(i+j)))); dist = min(dist,distmax); // t(i,j,distmax,abs(min1-(j-i))); // t(min1,max1,min2,max2,i,j); // dist = max(dist,max(min1-(i-j),min2-(i+j))); // dist = max(dist,max(min1-(i-j),max2-(i+j))); // dist = max(dist,max(max1-(i-j),min2-(i+j))); // dist = max(dist,max(max1-(i-j),max2-(i+j))); } } // t(k,dist); if(dist<=k) return true; return false; } int main() { __; int t; cin>>t; for(int h=1;h<=t;h++) { queue<pair<int,int> > q1,q2; int n,m; cin>>n>>m; for(int i=0;i<n;i++) { string s; cin>>s; for(int j=0;j<m;j++) { v[i][j] = s[j]-'0'; vis1[i][j] = vis2[i][j] = -1; if(v[i][j]) {q1.push(mp(i,j)); q2.push(mp(i,j));vis1[i][j] = vis2[i][j] = 0;} } } int dx[4] = {1,-1,0,0}, dy[4] = {0,0,1,-1}; q1.push(mp(-1,-1)); int counter = 0; while(!q1.empty()) { pair<int,int> p = q1.front(); q1.pop(); if(p==mp(-1,-1)) { counter++; if(q1.front()==p || q1.empty()) break; else q1.push(p); continue; } int a = p.fi, b = p.se; // t(a,b,counter); // if(!v[a][b]) {vis1[a][b]++;t(a,b,v[a][b]);} for(int i=0;i<4;i++) { int c = a+dx[i], d = b+dy[i]; if(c<0 || c>=n || d<0 || d>=m) continue; if(vis1[c][d]!=-1) continue; vis1[c][d] = vis1[a][b]+1; // t(a,b,c,d,vis1[c][d]); q1.push(mp(c,d)); } } int max1 = -1; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { max1 = max(max1,vis1[i][j]); } } // for(int i=0;i<n;i++) // { // for(int j=0;j<m;j++) // { // cout<<vis1[i][j]<<" "; // } // cout<<endl; // } int beg = 0, end = max1,ans = 0; while(beg<=end) { int mid = (beg+end)>>1; if(find(mid,n,m)) {end = mid-1;ans = mid;} else beg = mid+1; } cout<<"Case #"<<h<<": "<<ans<<endl; } return 0; } /* */
26.537572
152
0.464169
[ "vector" ]
77494f80b06a53b787a4ea26403a76a6b7d04108
695
hpp
C++
Source/System/Graphics/DataType/MatrixData.hpp
arian153/Engine-5
34f85433bc0a74a7ebe7da350d3f3698de77226e
[ "MIT" ]
2
2020-01-09T07:48:24.000Z
2020-01-09T07:48:26.000Z
Source/System/Graphics/DataType/MatrixData.hpp
arian153/Engine-5
34f85433bc0a74a7ebe7da350d3f3698de77226e
[ "MIT" ]
null
null
null
Source/System/Graphics/DataType/MatrixData.hpp
arian153/Engine-5
34f85433bc0a74a7ebe7da350d3f3698de77226e
[ "MIT" ]
null
null
null
#pragma once #include "../../Math/Algebra/Matrix44.hpp" namespace Engine5 { class MatrixData { public: MatrixData() { } MatrixData(const Matrix44& m, const Matrix44& v, const Matrix44& p) : model(m), view(v), projection(p) { } MatrixData(const Matrix44& v, const Matrix44& p) : view(v), projection(p) { model.SetIdentity(); } ~MatrixData() { } Matrix44 GetMVPMatrix() const { return model * view * projection; } public: Matrix44 model; Matrix44 view; Matrix44 projection; }; }
17.820513
75
0.48777
[ "model" ]
774bf3e8104ceba3089a9825a0514abba500b358
45,060
cpp
C++
source/DefaultSceneRenderer/DefaultSceneRenderer.cpp
mackron/GTGameEngine
380d1e01774fe6bc2940979e4e5983deef0bf082
[ "BSD-3-Clause" ]
31
2015-03-19T08:44:48.000Z
2021-12-15T20:52:31.000Z
source/DefaultSceneRenderer/DefaultSceneRenderer.cpp
mackron/GTGameEngine
380d1e01774fe6bc2940979e4e5983deef0bf082
[ "BSD-3-Clause" ]
19
2015-07-09T09:02:44.000Z
2016-06-09T03:51:03.000Z
source/DefaultSceneRenderer/DefaultSceneRenderer.cpp
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. #include <GTGE/DefaultSceneRenderer/DefaultSceneRenderer.hpp> #include <GTGE/DefaultSceneRenderer/DefaultSceneRenderer_SinglePassPipeline.hpp> #include <GTGE/DefaultSceneRenderer/DefaultSceneRenderer_MultiPassPipeline.hpp> #include <GTGE/ShaderLibrary.hpp> #include <GTGE/Context.hpp> #if defined(_MSC_VER) #pragma warning(push) #pragma warning(disable:4355) // 'this' used in initialise list. #endif namespace GT { static const bool SplitShadowLights = true; DefaultSceneRenderer::DefaultSceneRenderer(Context &context) : m_context(context), viewportFramebuffers(), m_materialShaders(), depthPassShader(nullptr), externalMeshes(), directionalShadowMapFramebuffer(1, 1), pointShadowMapFramebuffer(1, 1), spotShadowMapFramebuffer(1, 1), fullscreenTriangleVA(nullptr), shadowMapShader(nullptr), pointShadowMapShader(nullptr), finalCompositionShaderHDR(nullptr), finalCompositionShaderHDRNoBloom(nullptr), finalCompositionShaderLDR(nullptr), bloomShader(nullptr), highlightShader(nullptr), bloomBlurShaderX(nullptr), bloomBlurShaderY(nullptr), shadowBlurShaderX(nullptr), shadowBlurShaderY(nullptr), shaderBuilder(), luminanceChain(context), materialUniformNames(), isHDREnabled(true), isBloomEnabled(true), hdrExposure(1.0f), bloomFactor(1.0f), directionalShadowMapSize(1024), pointShadowMapSize(256), spotShadowMapSize(512), materialLibraryEventHandler(*this) { this->directionalShadowMapFramebuffer.Resize(this->directionalShadowMapSize, this->directionalShadowMapSize); this->pointShadowMapFramebuffer.Resize(this->pointShadowMapSize, this->pointShadowMapSize); this->spotShadowMapFramebuffer.Resize(this->spotShadowMapSize, this->spotShadowMapSize); this->depthPassShader = this->shaderBuilder.CreateDepthPassShader(); this->highlightShader = this->shaderBuilder.CreateHighlightShader(); this->bloomBlurShaderX = this->shaderBuilder.CreateXGaussianBlurShader(21, 8.0f); this->bloomBlurShaderY = this->shaderBuilder.CreateYGaussianBlurShader(21, 8.0f); this->shadowBlurShaderX = this->shaderBuilder.CreateXGaussianBlurShader(11, 2.0f); this->shadowBlurShaderY = this->shaderBuilder.CreateYGaussianBlurShader(11, 2.0f); this->shadowMapShader = this->shaderBuilder.CreateShadowMapShader(); this->pointShadowMapShader = this->shaderBuilder.CreatePointShadowMapShader(); this->bloomShader = this->shaderBuilder.CreateBloomShader(); this->finalCompositionShaderLDR = this->shaderBuilder.CreateLDRFinalCompositionShader(); this->finalCompositionShaderHDR = this->shaderBuilder.CreateHDRFinalCompositionShader(); this->finalCompositionShaderHDRNoBloom = this->shaderBuilder.CreateHDRNoBloomFinalCompositionShader(); /// Fullscreen Triangle Vertex Array. this->fullscreenTriangleVA = Renderer::CreateVertexArray(VertexArrayUsage_Static, VertexFormat::P3T2); float triangleVertices[] = { -3.0f, -1.0f, 0.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 3.0f, 0.0f, 1.0f, 2.0f, }; unsigned int triangleIndices[] = { 0, 1, 2 }; this->fullscreenTriangleVA->SetData(triangleVertices, 3, triangleIndices, 3); // The event handler needs to be attached to the material library so we can catch when a material definition is deleted an // in turn delete the shaders we've associated with that material. m_context.GetMaterialLibrary().AttachEventHandler(this->materialLibraryEventHandler); } DefaultSceneRenderer::~DefaultSceneRenderer() { Renderer::DeleteShader(this->depthPassShader); Renderer::DeleteShader(this->shadowMapShader); Renderer::DeleteShader(this->pointShadowMapShader); Renderer::DeleteShader(this->finalCompositionShaderHDR); Renderer::DeleteShader(this->finalCompositionShaderHDRNoBloom); Renderer::DeleteShader(this->finalCompositionShaderLDR); Renderer::DeleteShader(this->bloomShader); Renderer::DeleteShader(this->highlightShader); Renderer::DeleteShader(this->bloomBlurShaderX); Renderer::DeleteShader(this->bloomBlurShaderY); Renderer::DeleteShader(this->shadowBlurShaderX); Renderer::DeleteShader(this->shadowBlurShaderY); for (size_t i = 0; i < m_materialShaders.count; ++i) { auto materialShaders = m_materialShaders.buffer[i]->value; assert(materialShaders != nullptr); { delete materialShaders; } } Renderer::DeleteVertexArray(this->fullscreenTriangleVA); m_context.GetMaterialLibrary().RemoveEventHandler(this->materialLibraryEventHandler); } void DefaultSceneRenderer::Begin(Scene &scene) { (void)scene; } void DefaultSceneRenderer::End(Scene &scene) { (void)scene; } void DefaultSceneRenderer::RenderViewport(Scene &scene, SceneViewport &viewport) { // 0) Retrieve visible objects. DefaultSceneRenderer_VisibilityProcessor visibleObjects(scene, viewport); scene.QueryVisibleSceneNodes(viewport.GetMVPMatrix(), visibleObjects); // All external meshes are considered visible. Not going to do any frustum culling here. for (size_t i = 0; i < this->externalMeshes.count; ++i) { auto externalMesh = this->externalMeshes[i]; assert(externalMesh != nullptr); { DefaultSceneRendererMesh meshToAdd; meshToAdd.vertexArray = externalMesh->vertexArray; meshToAdd.drawMode = externalMesh->drawMode; meshToAdd.material = externalMesh->material; meshToAdd.transform = externalMesh->transform; meshToAdd.flags = externalMesh->flags; visibleObjects.AddMesh(meshToAdd); } } // Post-processing needs to be done after everything has been added. visibleObjects.PostProcess(); // We'll want to grab the framebuffer and set a few defaults. auto framebuffer = this->GetViewportFramebuffer(viewport); assert(framebuffer != nullptr); { Renderer::SetCurrentFramebuffer(framebuffer->framebuffer); Renderer::SetViewport(0, 0, framebuffer->width, framebuffer->height); } Renderer::DisableBlending(); Renderer::EnableDepthTest(); Renderer::EnableDepthWrites(); Renderer::SetDepthFunction(RendererFunction_LEqual); // With the visible objects determined we can now choose a pipeline to run rendering operations through. We want to use fast paths where // they're available. if (visibleObjects.lightManager.shadowDirectionalLights.count <= 1 && visibleObjects.lightManager.shadowPointLights.count <= 1 && visibleObjects.lightManager.shadowSpotLights.count <= 1) { // Shadow-casting lights can be combined into the main lighting pass. If the total number of lights is small enough, we can combine // everything into a single pass and do an even faster path. // // At the moment we need to be conservative, but this will likely be improved later. if (visibleObjects.lightManager.GetTotalLightCount() <= 4) { // Single pass. //DefaultSceneRenderer_SinglePassPipeline pipeline(*this, framebuffer, visibleObjects); DefaultSceneRenderer_MultiPassPipeline pipeline(*this, *framebuffer, visibleObjects, !SplitShadowLights); pipeline.Execute(); } else { // Multi-pass. DefaultSceneRenderer_MultiPassPipeline pipeline(*this, *framebuffer, visibleObjects, !SplitShadowLights); pipeline.Execute(); } } else { // Multi-pass, slower due to too many shadow-casting lights. DefaultSceneRenderer_MultiPassPipeline pipeline(*this, *framebuffer, visibleObjects, SplitShadowLights); pipeline.Execute(); } // Here we just render the final image. Basically, this is just the post-process step. This will eventually be made into a proper // pipeline stage. this->RenderFinalComposition(framebuffer, framebuffer->colourBuffer0); } void DefaultSceneRenderer::AddViewport(SceneViewport &viewport) { // We create a framebuffer for every viewport. We map these to viewports with a simple Map container. auto framebuffer = new DefaultSceneRendererFramebuffer(viewport.GetWidth(), viewport.GetHeight()); assert(framebuffer != nullptr); { viewport.SetColourBuffer(framebuffer->finalColourBuffer); this->viewportFramebuffers.Add(&viewport, framebuffer); } } void DefaultSceneRenderer::RemoveViewport(SceneViewport &viewport) { // When a viewport is removed, the framebuffer needs to be deleted. viewport.SetColourBuffer(nullptr); auto iFramebuffer = this->viewportFramebuffers.Find(&viewport); assert(iFramebuffer != nullptr); { auto framebuffer = iFramebuffer->value; assert(framebuffer != nullptr); { delete framebuffer; this->viewportFramebuffers.RemoveByIndex(iFramebuffer->index); } } } void DefaultSceneRenderer::OnViewportResized(SceneViewport &viewport) { auto framebuffer = this->GetViewportFramebuffer(viewport); assert(framebuffer != nullptr); { framebuffer->Resize(viewport.GetWidth(), viewport.GetHeight()); } } void DefaultSceneRenderer::AddExternalMesh(const SceneRendererMesh &meshToAdd) { if (!this->externalMeshes.Exists(&meshToAdd)) { this->externalMeshes.PushBack(&meshToAdd); } } void DefaultSceneRenderer::RemoveExternalMesh(const SceneRendererMesh &meshToRemove) { this->externalMeshes.RemoveFirstOccuranceOf(&meshToRemove); } //////////////////////////////////////////////////////////////// // Properties void DefaultSceneRenderer::SetProperty(const char* name, const char* value) { (void)name; (void)value; } void DefaultSceneRenderer::SetProperty(const char* name, int value) { (void)name; (void)value; } void DefaultSceneRenderer::SetProperty(const char* name, float value) { if (Strings::Equal(name, "HDRExposure")) { this->SetHDRExposure(value); } else if (Strings::Equal(name, "BloomFactor")) { this->SetBloomFactor(value); } } void DefaultSceneRenderer::SetProperty(const char* name, bool value) { if (Strings::Equal(name, "IsBackgroundClearEnabled")) { if (value) { this->EnableBackgroundColourClearing(this->GetBackgroundClearColour()); } else { this->DisableBackgroundColourClearing(); } } else if (Strings::Equal(name, "IsHDREnabled")) { if (value) { this->EnableHDR(); } else { this->DisableHDR(); } } else if (Strings::Equal(name, "IsBloomEnabled")) { if (value) { this->EnableBloom(); } else { this->DisableBloom(); } } } void DefaultSceneRenderer::SetProperty(const char* name, const glm::vec2 &value) { (void)name; (void)value; } void DefaultSceneRenderer::SetProperty(const char* name, const glm::vec3 &value) { if (Strings::Equal(name, "BackgroundClearColour")) { bool isEnabled = this->IsBackgroundColourClearingEnabled(); this->EnableBackgroundColourClearing(value); if (!isEnabled) { this->DisableBackgroundColourClearing(); } } } void DefaultSceneRenderer::SetProperty(const char* name, const glm::vec4 &value) { (void)name; (void)value; } String DefaultSceneRenderer::GetStringProperty(const char* name) const { (void)name; return ""; } int DefaultSceneRenderer::GetIntegerProperty(const char* name) const { (void)name; return 0; } float DefaultSceneRenderer::GetFloatProperty(const char* name) const { if (Strings::Equal(name, "HDRExposure")) { return this->GetHDRExposure(); } else if (Strings::Equal(name, "BloomFactor")) { return this->GetBloomFactor(); } return 0.0f; } bool DefaultSceneRenderer::GetBooleanProperty(const char* name) const { if (Strings::Equal(name, "IsBackgroundClearEnabled")) { return this->IsBackgroundColourClearingEnabled(); } else if (Strings::Equal(name, "IsHDREnabled")) { return this->IsHDREnabled(); } else if (Strings::Equal(name, "IsBloomEnabled")) { return this->IsBloomEnabled(); } return false; } glm::vec2 DefaultSceneRenderer::GetVector2Property(const char* name) const { (void)name; return glm::vec2(); } glm::vec3 DefaultSceneRenderer::GetVector3Property(const char* name) const { if (Strings::Equal(name, "BackgroundClearColour")) { return this->GetBackgroundClearColour(); } return glm::vec3(); } glm::vec4 DefaultSceneRenderer::GetVector4Property(const char* name) const { (void)name; return glm::vec4(); } //////////////////////////////////////////////////////////////// // Settings. void DefaultSceneRenderer::EnableHDR() { this->isHDREnabled = true; } void DefaultSceneRenderer::DisableHDR() { this->isHDREnabled = false; } bool DefaultSceneRenderer::IsHDREnabled() const { return this->isHDREnabled; } void DefaultSceneRenderer::EnableBloom() { this->isBloomEnabled = true; } void DefaultSceneRenderer::DisableBloom() { this->isBloomEnabled = false; } bool DefaultSceneRenderer::IsBloomEnabled() const { return this->isBloomEnabled; } void DefaultSceneRenderer::SetHDRExposure(float newExposure) { this->hdrExposure = newExposure; } float DefaultSceneRenderer::GetHDRExposure() const { return this->hdrExposure; } void DefaultSceneRenderer::SetBloomFactor(float newBloomFactor) { this->bloomFactor = newBloomFactor; } float DefaultSceneRenderer::GetBloomFactor() const { return this->bloomFactor; } //////////////////////////////////////////////////////////////// // Resource Access. Shader* DefaultSceneRenderer::GetDepthPassShader() const { return this->depthPassShader; } Texture2D* DefaultSceneRenderer::GetDirectionalShadowMapByIndex(size_t index) { assert(index == 0); // <-- Temp assert until multiple shadow maps are supported. (void)index; return this->directionalShadowMapFramebuffer.colourBuffer; } TextureCube* DefaultSceneRenderer::GetPointShadowMapByIndex(size_t index) { assert(index == 0); // <-- Temp assert until multiple shadow maps are supported. (void)index; return this->pointShadowMapFramebuffer.colourBuffer; } Texture2D* DefaultSceneRenderer::GetSpotShadowMapByIndex(size_t index) { assert(index == 0); // <-- Temp assert until multiple shadow maps are supported. (void)index; return this->spotShadowMapFramebuffer.colourBuffer; } Shader* DefaultSceneRenderer::GetMaterialShader(Material &material, const DefaultSceneRenderer_LightGroupID &lightGroupID, uint32_t flags) { auto materialShaders = this->GetMaterialShaders(material); assert(materialShaders != nullptr); { DefaultSceneRenderer_MaterialShaderID shaderID(lightGroupID, flags); auto iShader = materialShaders->shaders.Find(shaderID); if (iShader != nullptr) { return iShader->value; } else { auto shader = this->shaderBuilder.CreateShader(shaderID, material.GetDefinition()); if (shader != nullptr) { materialShaders->shaders.Add(shaderID, shader); } return shader; } } } Shader* DefaultSceneRenderer::GetHighlightShader() const { return this->highlightShader; } Shader* DefaultSceneRenderer::GetFullscreenTriangleCopyShader() const { return this->finalCompositionShaderLDR; } const VertexArray & DefaultSceneRenderer::GetFullscreenTriangleVA() const { assert(this->fullscreenTriangleVA != nullptr); { return *this->fullscreenTriangleVA; } } //////////////////////////////////////////////////////////////// // Rendering Helpers. Texture2D* DefaultSceneRenderer::RenderDirectionalLightShadowMap(DefaultSceneRendererDirectionalLight &light, size_t shadowMapIndex) { assert(shadowMapIndex == 0); // <-- temp assert until we add support for multiple shadow maps. (void)shadowMapIndex; // State setup. Renderer::DisableBlending(); Renderer::EnableDepthWrites(); // Framebuffer setup. Renderer::SetCurrentFramebuffer(this->directionalShadowMapFramebuffer.framebuffer); Renderer::SetViewport(0, 0, this->directionalShadowMapFramebuffer.width, this->directionalShadowMapFramebuffer.height); int colourBufferIndex = 0; int blurBufferIndex = 1; Renderer::SetDrawBuffers(1, &colourBufferIndex); // Clear. Renderer::SetClearColour(1.0f, 1.0f, 1.0f, 1.0f); Renderer::SetClearDepth(1.0f); Renderer::Clear(BufferType_Colour | BufferType_Depth); // Shader setup. Renderer::SetCurrentShader(this->shadowMapShader); glm::mat4 lightProjectionView = light.projection * light.view; for (size_t iMesh = 0; iMesh < light.containedMeshes.meshes.count; ++iMesh) { auto &mesh = light.containedMeshes.meshes[iMesh]; assert(mesh.vertexArray != nullptr); { // Shader setup. this->shadowMapShader->SetUniform("PVMMatrix", lightProjectionView * mesh.transform); Renderer::PushPendingUniforms(*this->shadowMapShader); // Draw. Renderer::Draw(*mesh.vertexArray, mesh.drawMode); } } // Here is where we perform the blurring of the shadow map. This renders a fullscreen quad, so we don't want depth testing here. Renderer::DisableDepthWrites(); Renderer::DisableDepthTest(); // Blur X. { Renderer::SetDrawBuffers(1, &blurBufferIndex); // Shader. Renderer::SetCurrentShader(this->shadowBlurShaderX); this->shadowBlurShaderX->SetUniform("Texture", this->directionalShadowMapFramebuffer.colourBuffer); this->shadowBlurShaderX->SetUniform("TextureSizeReciprocal", 1.0f / static_cast<float>(this->directionalShadowMapFramebuffer.colourBuffer->GetWidth())); Renderer::PushPendingUniforms(*this->shadowBlurShaderX); // Draw. Renderer::Draw(*this->fullscreenTriangleVA); } // Blur Y. { Renderer::SetDrawBuffers(1, &colourBufferIndex); // Shader. Renderer::SetCurrentShader(this->shadowBlurShaderY); this->shadowBlurShaderY->SetUniform("Texture", this->directionalShadowMapFramebuffer.blurBuffer); this->shadowBlurShaderY->SetUniform("TextureSizeReciprocal", 1.0f / static_cast<float>(this->directionalShadowMapFramebuffer.colourBuffer->GetHeight())); Renderer::PushPendingUniforms(*this->shadowBlurShaderY); // Draw. Renderer::Draw(*this->fullscreenTriangleVA); } // The blurring is now done, but we want to restore depth testing. Renderer::EnableDepthTest(); return this->directionalShadowMapFramebuffer.colourBuffer; } TextureCube* DefaultSceneRenderer::RenderPointLightShadowMap(DefaultSceneRendererPointLight &light, size_t shadowMapIndex) { assert(shadowMapIndex == 0); // <-- temp assert until we add support for multiple shadow maps. (void)shadowMapIndex; // State setup. Renderer::DisableBlending(); Renderer::EnableDepthWrites(); // Framebuffer setup. Renderer::SetCurrentFramebuffer(this->pointShadowMapFramebuffer.framebuffer); Renderer::SetViewport(0, 0, this->pointShadowMapFramebuffer.width, this->pointShadowMapFramebuffer.height); this->RenderPointShapowMapFace(light, light.positiveXView, 0, light.containedMeshesPositiveX.meshes); this->RenderPointShapowMapFace(light, light.negativeXView, 1, light.containedMeshesNegativeX.meshes); this->RenderPointShapowMapFace(light, light.positiveYView, 2, light.containedMeshesPositiveY.meshes); this->RenderPointShapowMapFace(light, light.negativeYView, 3, light.containedMeshesNegativeY.meshes); this->RenderPointShapowMapFace(light, light.positiveZView, 4, light.containedMeshesPositiveZ.meshes); this->RenderPointShapowMapFace(light, light.negativeZView, 5, light.containedMeshesNegativeZ.meshes); return this->pointShadowMapFramebuffer.colourBuffer; } Texture2D* DefaultSceneRenderer::RenderSpotLightShadowMap(DefaultSceneRendererSpotLight &light, size_t shadowMapIndex) { assert(shadowMapIndex == 0); // <-- temp assert until we add support for multiple shadow maps. (void)shadowMapIndex; // State setup. Renderer::DisableBlending(); Renderer::EnableDepthWrites(); // Framebuffer setup. Renderer::SetCurrentFramebuffer(this->spotShadowMapFramebuffer.framebuffer); Renderer::SetViewport(0, 0, this->spotShadowMapFramebuffer.width, this->spotShadowMapFramebuffer.height); int colourBufferIndex = 0; int blurBufferIndex = 1; Renderer::SetDrawBuffers(1, &colourBufferIndex); // Clear. Renderer::SetClearColour(1.0f, 1.0f, 1.0f, 1.0f); Renderer::SetClearDepth(1.0f); Renderer::Clear(BufferType_Colour | BufferType_Depth); // Shader setup. Renderer::SetCurrentShader(this->shadowMapShader); glm::mat4 lightProjectionView = light.projection * light.view; for (size_t iMesh = 0; iMesh < light.containedMeshes.meshes.count; ++iMesh) { auto &mesh = light.containedMeshes.meshes[iMesh]; assert(mesh.vertexArray != nullptr); { // Shader setup. this->shadowMapShader->SetUniform("PVMMatrix", lightProjectionView * mesh.transform); Renderer::PushPendingUniforms(*this->shadowMapShader); // Draw. Renderer::Draw(*mesh.vertexArray, mesh.drawMode); } } // Here is where we perform the blurring of the shadow map. This renders a fullscreen quad, so we don't want depth testing here. Renderer::DisableDepthWrites(); Renderer::DisableDepthTest(); // Blur X. { Renderer::SetDrawBuffers(1, &blurBufferIndex); // Shader. Renderer::SetCurrentShader(this->shadowBlurShaderX); this->shadowBlurShaderX->SetUniform("Texture", this->spotShadowMapFramebuffer.colourBuffer); this->shadowBlurShaderX->SetUniform("TextureSizeReciprocal", 1.0f / static_cast<float>(this->spotShadowMapFramebuffer.colourBuffer->GetWidth())); Renderer::PushPendingUniforms(*this->shadowBlurShaderX); // Draw. Renderer::Draw(*this->fullscreenTriangleVA); } // Blur Y. { Renderer::SetDrawBuffers(1, &colourBufferIndex); // Shader. Renderer::SetCurrentShader(this->shadowBlurShaderY); this->shadowBlurShaderY->SetUniform("Texture", this->spotShadowMapFramebuffer.blurBuffer); this->shadowBlurShaderY->SetUniform("TextureSizeReciprocal", 1.0f / static_cast<float>(this->spotShadowMapFramebuffer.colourBuffer->GetHeight())); Renderer::PushPendingUniforms(*this->shadowBlurShaderY); // Draw. Renderer::Draw(*this->fullscreenTriangleVA); } // The blurring is now done, but we want to restore depth testing. Renderer::EnableDepthTest(); return this->spotShadowMapFramebuffer.colourBuffer; } void DefaultSceneRenderer::RenderPointShapowMapFace(const DefaultSceneRendererPointLight &light, const glm::mat4 &faceViewMatrix, int faceIndex, const Vector<DefaultSceneRendererMesh> &meshes) { // The draw buffer needs to be set. The appropriate framebuffer will have already been set. int blurBuffer0Index = 6; int blurBuffer1Index = 7; Renderer::SetDrawBuffers(1, &blurBuffer0Index); Renderer::SetCurrentShader(this->pointShadowMapShader); // We need to clear both depth and colour. The colour needs to be cleared to the radius of the light. float radius = light.radius; Renderer::SetClearColour(radius, radius * radius, 0.0f, 1.0f); Renderer::SetClearDepth(1.0f); Renderer::Clear(BufferType_Colour | BufferType_Depth); glm::mat4 projectionView = light.projection * faceViewMatrix; for (size_t i = 0; i < meshes.count; ++i) { auto &mesh = meshes[i]; assert(mesh.vertexArray != nullptr); { // Shader setup. this->pointShadowMapShader->SetUniform("PVMMatrix", projectionView * mesh.transform); this->pointShadowMapShader->SetUniform("ViewModelMatrix", faceViewMatrix * mesh.transform); Renderer::PushPendingUniforms(*this->pointShadowMapShader); // Draw. Renderer::Draw(*mesh.vertexArray, mesh.drawMode); } } // TODO: Make this optional. // Now we want to do a gaussian blur on the face. The way we do it is we first blur on the X axis and then do the same on the Y axis. We use // an intermediary buffer that is bound to index 6 in the framebuffer. Not sure how seams will work here. Renderer::DisableDepthTest(); Renderer::DisableDepthWrites(); // Blur X. { Renderer::SetDrawBuffers(1, &blurBuffer1Index); // Shader. Renderer::SetCurrentShader(this->shadowBlurShaderX); this->shadowBlurShaderX->SetUniform("Texture", this->pointShadowMapFramebuffer.blurBuffer0); this->shadowBlurShaderX->SetUniform("TextureSizeReciprocal", 1.0f / static_cast<float>(this->pointShadowMapFramebuffer.blurBuffer0->GetWidth())); Renderer::PushPendingUniforms(*this->shadowBlurShaderX); // Draw. Renderer::Draw(*this->fullscreenTriangleVA); } // Blur Y { Renderer::SetDrawBuffers(1, &faceIndex); // Shader. Renderer::SetCurrentShader(this->shadowBlurShaderY); this->shadowBlurShaderY->SetUniform("Texture", this->pointShadowMapFramebuffer.blurBuffer1); this->shadowBlurShaderY->SetUniform("TextureSizeReciprocal", 1.0f / static_cast<float>(this->pointShadowMapFramebuffer.blurBuffer1->GetHeight())); Renderer::PushPendingUniforms(*this->shadowBlurShaderY); // Draw. Renderer::Draw(*this->fullscreenTriangleVA); } Renderer::EnableDepthTest(); Renderer::EnableDepthWrites(); } void DefaultSceneRenderer::SetMaterialShaderUniforms(Shader &shader, const Material &material, const DefaultSceneRenderer_LightGroup &lightGroup, uint32_t flags, const DefaultSceneRenderer_VisibilityProcessor &visibleObjects) { (void)flags; uint16_t ambientLightCount = lightGroup.GetAmbientLightCount(); uint16_t directionalLightCount = lightGroup.GetDirectionalLightCount(); uint16_t pointLightCount = lightGroup.GetPointLightCount(); uint16_t spotLightCount = lightGroup.GetSpotLightCount(); uint16_t shadowDirectionalLightCount = lightGroup.GetShadowDirectionalLightCount(); uint16_t shadowPointLightCount = lightGroup.GetShadowPointLightCount(); uint16_t shadowSpotLightCount = lightGroup.GetShadowSpotLightCount(); auto ambientLightStartIndex = lightGroup.GetAmbientLightStartIndex(); auto directionalLightStartIndex = lightGroup.GetDirectionalLightStartIndex(); auto pointLightStartIndex = lightGroup.GetPointLightStartIndex(); auto spotLightStartIndex = lightGroup.GetSpotLightStartIndex(); auto shadowDirectionalLightStartIndex = lightGroup.GetShadowDirectionalLightStartIndex(); auto shadowPointLightStartIndex = lightGroup.GetShadowPointLightStartIndex(); auto shadowSpotLightStartIndex = lightGroup.GetShadowSpotLightStartIndex(); // Ambient Lights. for (int i = 0; i < ambientLightCount; ++i) { auto light = visibleObjects.lightManager.ambientLights.buffer[lightGroup.lightIDs[ambientLightStartIndex + i]]->value; assert(light != nullptr); { shader.SetUniform(this->materialUniformNames.GetLightUniformName(MaterialUniform_AmbientLightFS_Colour, i), light->colour); } } // Directional Lights. for (int i = 0; i < directionalLightCount; ++i) { auto light = visibleObjects.lightManager.directionalLights.buffer[lightGroup.lightIDs[directionalLightStartIndex + i]]->value; assert(light != nullptr); { shader.SetUniform(this->materialUniformNames.GetLightUniformName(MaterialUniform_DirectionalLightFS_Colour, i), light->colour); shader.SetUniform(this->materialUniformNames.GetLightUniformName(MaterialUniform_DirectionalLightFS_Direction, i), glm::normalize(glm::mat3(visibleObjects.viewMatrix) * light->GetForwardVector())); } } // Point Lights. for (int i = 0; i < pointLightCount; ++i) { auto light = visibleObjects.lightManager.pointLights.buffer[lightGroup.lightIDs[pointLightStartIndex + i]]->value; assert(light != nullptr); { shader.SetUniform(this->materialUniformNames.GetLightUniformName(MaterialUniform_PointLightVS_PositionVS, i), glm::vec3(visibleObjects.viewMatrix * glm::vec4(light->position, 1.0f))); shader.SetUniform(this->materialUniformNames.GetLightUniformName(MaterialUniform_PointLightFS_Colour, i), light->colour); shader.SetUniform(this->materialUniformNames.GetLightUniformName(MaterialUniform_PointLightFS_Radius, i), light->radius); shader.SetUniform(this->materialUniformNames.GetLightUniformName(MaterialUniform_PointLightFS_Falloff, i), light->falloff); } } // Spot Lights. for (int i = 0; i < spotLightCount; ++i) { auto light = visibleObjects.lightManager.spotLights.buffer[lightGroup.lightIDs[spotLightStartIndex + i]]->value; assert(light != nullptr); { shader.SetUniform(this->materialUniformNames.GetLightUniformName(MaterialUniform_SpotLightFS_Position, i), glm::vec3(visibleObjects.viewMatrix * glm::vec4(light->position, 1.0f))); shader.SetUniform(this->materialUniformNames.GetLightUniformName(MaterialUniform_SpotLightFS_Colour, i), light->colour); shader.SetUniform(this->materialUniformNames.GetLightUniformName(MaterialUniform_SpotLightFS_Direction, i), glm::normalize(glm::mat3(visibleObjects.viewMatrix) * light->GetForwardVector())); shader.SetUniform(this->materialUniformNames.GetLightUniformName(MaterialUniform_SpotLightFS_Length, i), light->length); shader.SetUniform(this->materialUniformNames.GetLightUniformName(MaterialUniform_SpotLightFS_Falloff, i), light->falloff); shader.SetUniform(this->materialUniformNames.GetLightUniformName(MaterialUniform_SpotLightFS_CosAngleInner, i), glm::cos(glm::radians(light->innerAngle))); shader.SetUniform(this->materialUniformNames.GetLightUniformName(MaterialUniform_SpotLightFS_CosAngleOuter, i), glm::cos(glm::radians(light->outerAngle))); } } // Shadow-Casting Directional Lights. for (int i = 0; i < shadowDirectionalLightCount; ++i) { auto light = visibleObjects.lightManager.directionalLights.buffer[lightGroup.lightIDs[shadowDirectionalLightStartIndex + i]]->value; assert(light != nullptr); { shader.SetUniform(this->materialUniformNames.GetLightUniformName(MaterialUniform_ShadowDirectionalLightVS_ProjectionView, i), light->projection * light->view); shader.SetUniform(this->materialUniformNames.GetLightUniformName(MaterialUniform_ShaderDirectionalLightFS_Colour, i), light->colour); shader.SetUniform(this->materialUniformNames.GetLightUniformName(MaterialUniform_ShaderDirectionalLightFS_Direction, i), glm::normalize(glm::mat3(visibleObjects.viewMatrix) * light->GetForwardVector())); // TODO: set the shadow map. } } // Shadow-Casting Point Lights. for (int i = 0; i < shadowPointLightCount; ++i) { auto light = visibleObjects.lightManager.pointLights.buffer[lightGroup.lightIDs[shadowPointLightStartIndex + i]]->value; assert(light != nullptr); { shader.SetUniform(this->materialUniformNames.GetLightUniformName(MaterialUniform_ShadowPointLightFS_PositionVS, i), glm::vec3(visibleObjects.viewMatrix * glm::vec4(light->position, 1.0f))); shader.SetUniform(this->materialUniformNames.GetLightUniformName(MaterialUniform_ShadowPointLightFS_PositionWS, i), light->position); shader.SetUniform(this->materialUniformNames.GetLightUniformName(MaterialUniform_ShadowPointLightFS_Colour, i), light->colour); shader.SetUniform(this->materialUniformNames.GetLightUniformName(MaterialUniform_ShadowPointLightFS_Radius, i), light->radius); shader.SetUniform(this->materialUniformNames.GetLightUniformName(MaterialUniform_ShadowPointLightFS_Falloff, i), light->falloff); // TODO: set the shadow map. } } // Shadow-Casting Spot Lights. for (int i = 0; i < shadowSpotLightCount; ++i) { auto light = visibleObjects.lightManager.spotLights.buffer[lightGroup.lightIDs[shadowSpotLightStartIndex + i]]->value; assert(light != nullptr); { shader.SetUniform(this->materialUniformNames.GetLightUniformName(MaterialUniforms_ShadowSpotLightVS_ProjectionView, i), light->projection * light->view); shader.SetUniform(this->materialUniformNames.GetLightUniformName(MaterialUniforms_ShadowSpotLightFS_Position, i), glm::vec3(visibleObjects.viewMatrix * glm::vec4(light->position, 1.0f))); shader.SetUniform(this->materialUniformNames.GetLightUniformName(MaterialUniforms_ShadowSpotLightFS_Colour, i), light->colour); shader.SetUniform(this->materialUniformNames.GetLightUniformName(MaterialUniforms_ShadowSpotLightFS_Direction, i), glm::normalize(glm::mat3(visibleObjects.viewMatrix) * light->GetForwardVector())); shader.SetUniform(this->materialUniformNames.GetLightUniformName(MaterialUniforms_ShadowSpotLightFS_Length, i), light->length); shader.SetUniform(this->materialUniformNames.GetLightUniformName(MaterialUniforms_ShadowSpotLightFS_Falloff, i), light->falloff); shader.SetUniform(this->materialUniformNames.GetLightUniformName(MaterialUniforms_ShadowSpotLightFS_CosAngleInner, i), glm::cos(glm::radians(light->innerAngle))); shader.SetUniform(this->materialUniformNames.GetLightUniformName(MaterialUniforms_ShadowSpotLightFS_CosAngleOuter, i), glm::cos(glm::radians(light->outerAngle))); // TODO: set the shadow map. } } shader.SetUniformsFromMaterial(material); } //////////////////////////////////////////////////////////////// // Event Handlers from MaterialLibrary. void DefaultSceneRenderer::OnDeleteMaterialDefinition(MaterialDefinition &definition) { auto iShaders = m_materialShaders.Find(&definition); if (iShaders != nullptr) { delete iShaders->value; m_materialShaders.RemoveByIndex(iShaders->index); } } void DefaultSceneRenderer::OnReloadMaterialDefinition(MaterialDefinition &definition) { // All we want to do is delete the shaders. This will force the renderer to recreated them when the material is used next. auto iShaders = m_materialShaders.Find(&definition); if (iShaders != nullptr) { delete iShaders->value; m_materialShaders.RemoveByIndex(iShaders->index); } } ///////////////////////////////////////////////////////// // Private DefaultSceneRendererFramebuffer* DefaultSceneRenderer::GetViewportFramebuffer(SceneViewport &viewport) { auto iFramebuffer = this->viewportFramebuffers.Find(&viewport); if (iFramebuffer != nullptr) { return iFramebuffer->value; } return nullptr; } /////////////////////// // Rendering. void DefaultSceneRenderer::RenderFinalComposition(DefaultSceneRendererFramebuffer* framebuffer, Texture2D* sourceColourBuffer) { Renderer::DisableDepthTest(); Renderer::DisableDepthWrites(); Renderer::DisableStencilTest(); if (this->IsHDREnabled()) { // HDR requires luminocity. this->luminanceChain.ComputeLuminance(*sourceColourBuffer, this->hdrExposure); // Might need a bloom buffer. if (this->IsBloomEnabled()) { this->RenderBloomMap(framebuffer, sourceColourBuffer); } // Framebuffer Setup. int finalOutputBufferIndex = 4; Renderer::SetCurrentFramebuffer(framebuffer->framebuffer); Renderer::SetDrawBuffers(1, &finalOutputBufferIndex); Renderer::SetViewport(0, 0, framebuffer->width, framebuffer->height); // Shader Setup. if (this->IsBloomEnabled()) { Renderer::SetCurrentShader(this->finalCompositionShaderHDR); this->finalCompositionShaderHDR->SetUniform("ColourBuffer", sourceColourBuffer); this->finalCompositionShaderHDR->SetUniform("LuminanceBuffer", this->luminanceChain.GetLuminanceBuffer()); this->finalCompositionShaderHDR->SetUniform("BloomBuffer", framebuffer->bloomBuffer); this->finalCompositionShaderHDR->SetUniform("BloomFactor", this->bloomFactor); Renderer::PushPendingUniforms(*this->finalCompositionShaderHDR); } else { Renderer::SetCurrentShader(this->finalCompositionShaderHDRNoBloom); this->finalCompositionShaderHDRNoBloom->SetUniform("ColourBuffer", sourceColourBuffer); this->finalCompositionShaderHDRNoBloom->SetUniform("LuminanceBuffer", this->luminanceChain.GetLuminanceBuffer()); Renderer::PushPendingUniforms(*this->finalCompositionShaderHDRNoBloom); } } else { Renderer::SetTexture2DFilter(*sourceColourBuffer, TextureFilter_Nearest, TextureFilter_Nearest); // Framebuffer Setup. int finalOutputBufferIndex = 4; Renderer::SetCurrentFramebuffer(framebuffer->framebuffer); Renderer::SetDrawBuffers(1, &finalOutputBufferIndex); Renderer::SetViewport(0, 0, framebuffer->width, framebuffer->height); // Shader Setup. Renderer::SetCurrentShader(this->finalCompositionShaderLDR); this->finalCompositionShaderLDR->SetUniform("ColourBuffer", sourceColourBuffer); Renderer::PushPendingUniforms(*this->finalCompositionShaderLDR); } // Draw. Renderer::Draw(*this->fullscreenTriangleVA); } void DefaultSceneRenderer::RenderBloomMap(DefaultSceneRendererFramebuffer* framebuffer, Texture2D* sourceColourBuffer) { // Framebuffer Setup. int bufferIndex = 0; int blurBufferIndex = 1; Renderer::SetCurrentFramebuffer(framebuffer->bloomFramebuffer); Renderer::SetDrawBuffers(1, &bufferIndex); Renderer::SetViewport(0, 0, framebuffer->bloomBuffer->GetWidth(), framebuffer->bloomBuffer->GetHeight()); // Shader Setup. Renderer::SetCurrentShader(this->bloomShader); this->bloomShader->SetUniform("ColourBuffer", sourceColourBuffer); Renderer::PushPendingUniforms(*this->bloomShader); // Draw. Renderer::Draw(*this->fullscreenTriangleVA); // Gaussian Blur. // Blur X. { Renderer::SetDrawBuffers(1, &blurBufferIndex); // Shader. Renderer::SetCurrentShader(this->bloomBlurShaderX); this->bloomBlurShaderX->SetUniform("Texture", framebuffer->bloomBuffer); this->bloomBlurShaderX->SetUniform("TextureSizeReciprocal", 1.0f / static_cast<float>(framebuffer->bloomBlurBuffer->GetWidth())); Renderer::PushPendingUniforms(*this->bloomBlurShaderX); // Draw. Renderer::Draw(*this->fullscreenTriangleVA); } // Blur Y. { Renderer::SetDrawBuffers(1, &bufferIndex); // Shader. Renderer::SetCurrentShader(this->bloomBlurShaderY); this->bloomBlurShaderY->SetUniform("Texture", framebuffer->bloomBlurBuffer); this->bloomBlurShaderY->SetUniform("TextureSizeReciprocal", 1.0f / static_cast<float>(framebuffer->bloomBlurBuffer->GetHeight())); Renderer::PushPendingUniforms(*this->bloomBlurShaderY); // Draw. Renderer::Draw(*this->fullscreenTriangleVA); } } /////////////////////// // Materials. DefaultSceneRenderer_MaterialShaders* DefaultSceneRenderer::GetMaterialShaders(Material &material) { // A single set of shaders is created for each definition. We map the shaders to the definition, with the definition acting as the key. auto iMaterialShaders = m_materialShaders.Find(&material.GetDefinition()); if (iMaterialShaders == nullptr) { // The shaders structure has not yet been created, so it needs to be created now. auto shaders = new DefaultSceneRenderer_MaterialShaders; m_materialShaders.Add(&material.GetDefinition(), shaders); return shaders; } else { // The shaders structure has already been created, so we just return that. return iMaterialShaders->value; } } } #if defined(_MSC_VER) #pragma warning(pop) #endif
39.665493
229
0.640524
[ "mesh", "render", "vector", "transform" ]
774ecc1e0d00569c0bafa70c527da91833aad864
3,039
cpp
C++
src/GLEngine/graphics/Camera.cpp
michaelbuerger/GLEngine
cf0bc2d7e1e955c2fcb3fafb154a2af7a5e3cd6b
[ "MIT" ]
1
2019-08-01T04:53:45.000Z
2019-08-01T04:53:45.000Z
src/GLEngine/graphics/Camera.cpp
michaelbuerger/GLEngine
cf0bc2d7e1e955c2fcb3fafb154a2af7a5e3cd6b
[ "MIT" ]
null
null
null
src/GLEngine/graphics/Camera.cpp
michaelbuerger/GLEngine
cf0bc2d7e1e955c2fcb3fafb154a2af7a5e3cd6b
[ "MIT" ]
2
2020-07-20T20:43:24.000Z
2020-12-07T06:02:14.000Z
#include "GLEngine/graphics/Camera.hpp" #include "GLEngine/graphics/Transform.hpp" #include "glm/gtc/matrix_transform.hpp" namespace GLEngine { Camera::Camera(const Transform &transform) { m_projectionMatrixNeedsRecalc = true; this->transform = transform; m_fov = 90.0f; m_aspectRatio = 16.0f/9.0f; m_projectionMode = GLE_CAMERA_MODE_PERSPECTIVE; this->SetViewDistance(100.0f); } Camera::Camera(const Transform &transform, const float &fov, const float &aspectRatio, const float &viewDistance, const ProjectionMode &projectionMode) { m_projectionMatrixNeedsRecalc = true; this->transform = transform; m_fov = fov; m_aspectRatio = aspectRatio; m_projectionMode = projectionMode; this->SetViewDistance(viewDistance); } void Camera::SetFov(const float &fov) { m_projectionMatrixNeedsRecalc = true; m_fov = fov; } void Camera::SetAspectRatio(const float &aspectRatio) { m_projectionMatrixNeedsRecalc = true; m_aspectRatio = aspectRatio; } void Camera::SetViewDistance(const float &viewDistance) { m_projectionMatrixNeedsRecalc = true; m_nearClippingPlane = 0.1f; m_farClippingPlane = viewDistance+m_nearClippingPlane; } void Camera::SetProjectionMode(const ProjectionMode &projectionMode) { m_projectionMatrixNeedsRecalc = true; m_projectionMode = projectionMode; } float Camera::GetFov() const { return m_fov; } float Camera::GetAspectRatio() const { return m_aspectRatio; } float Camera::GetViewDistance() const { return m_farClippingPlane - m_nearClippingPlane; } ProjectionMode Camera::GetProjectionMode() const { return m_projectionMode; } glm::mat4 Camera::GetViewMatrix() // Inverse of transformation matrix { RecalcViewMatrix(); return m_viewMatrix; } glm::mat4 Camera::GetProjectionMatrix() // Perspective or Orthographic { if(m_projectionMatrixNeedsRecalc) { RecalcProjectionMatrix(); m_projectionMatrixNeedsRecalc = false; } return m_projectionMatrix; } void Camera::RecalcViewMatrix() { if(transform.GetScale() != glm::vec3(1.0f, 1.0f, 1.0f)) { transform.SetScale(glm::vec3(1.0f, 1.0f, 1.0f)); // Override transform scale and account for lazy calculation } m_viewMatrix = transform.GetMatrixInverse(); } void Camera::RecalcProjectionMatrix() { if(m_projectionMode == GLE_CAMERA_MODE_ORTHOGRAPHIC) { m_projectionMatrix = glm::ortho(0.0f, 1.0f, 1.0f, 0.0f, m_nearClippingPlane, m_farClippingPlane); } if(m_projectionMode == GLE_CAMERA_MODE_PERSPECTIVE) { m_projectionMatrix = glm::perspective(glm::radians(m_fov), m_aspectRatio, m_nearClippingPlane, m_farClippingPlane); } } }
31.329897
155
0.649227
[ "transform" ]
7758b8c17257b53b4e159a2d98debfae6b8d0dbf
699
cpp
C++
src/Core/ResourceManager/FileLoaderManager.cpp
bluespeck/OakVR
65d56942af390dc2ab2d969b44285d23bd53f139
[ "MIT" ]
null
null
null
src/Core/ResourceManager/FileLoaderManager.cpp
bluespeck/OakVR
65d56942af390dc2ab2d969b44285d23bd53f139
[ "MIT" ]
null
null
null
src/Core/ResourceManager/FileLoaderManager.cpp
bluespeck/OakVR
65d56942af390dc2ab2d969b44285d23bd53f139
[ "MIT" ]
null
null
null
#include "FileLoaderManager.h" #include <algorithm> namespace oakvr { namespace core { std::vector<sp<FileLoader>> &FileLoaderManager::GetFileLoaders() { static std::vector<sp<FileLoader>> s_fileLoaders; return s_fileLoaders; } auto FileLoaderManager::RegisterFileLoader(sp<FileLoader> pFileLoader) -> void { GetFileLoaders().push_back(pFileLoader); } auto FileLoaderManager::UnregisterFileLoader(sp<FileLoader> pFileLoader) -> void { auto &s_fileLoaders = GetFileLoaders(); s_fileLoaders.erase(std::remove_if(std::begin(s_fileLoaders), std::end(s_fileLoaders), [&](const sp<FileLoader> &pFL)->bool{ return pFL == pFileLoader; }), s_fileLoaders.end()); } } }
27.96
180
0.726753
[ "vector" ]
775f4ce173e5ae887c451e5e163180cb3bdd8812
1,336
cpp
C++
others/groupAnagrams.cpp
wanghengg/LeetCode
4f73d7e176c8de5d2d9b87ab2812f7aa80c20a79
[ "Apache-2.0" ]
null
null
null
others/groupAnagrams.cpp
wanghengg/LeetCode
4f73d7e176c8de5d2d9b87ab2812f7aa80c20a79
[ "Apache-2.0" ]
null
null
null
others/groupAnagrams.cpp
wanghengg/LeetCode
4f73d7e176c8de5d2d9b87ab2812f7aa80c20a79
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <unordered_map> #include <vector> #include <string> #include <algorithm> /* * 用hash map求解 */ class Solution{ public: std::vector<std::vector<std::string>> groupAnagrams(std::vector<std::string>& data) { std::unordered_map<std::string, int> hash; std::vector<std::vector<std::string>> result; int value = 0; int len = data.size(); for (int i = 0; i < len; ++i) { std::string temp = data[i]; std::sort(temp.begin(), temp.end()); // 将每个string先排序 if (hash.count(temp) == 0) { hash.insert({temp, value}); // 如果排序后的string还未存在,添加到hash中 // 重新构造一个新的vector<string>插入 result.push_back(std::vector<std::string>{data[i]}); ++value; } else{ result[hash[temp]].push_back(data[i]); } } return result; } }; int main() { std::vector<std::string> data{"eat", "tea", "tan", "ate", "nat", "cod", "atb", "bat", "doc"}; Solution solution; std::vector<std::vector<std::string>> result = solution.groupAnagrams(data); for (auto& line : result) { for (auto& iter : line) std::cout << iter << ' '; std::cout << std::endl; } return 0; }
29.043478
89
0.511976
[ "vector" ]
7767a7f45f7e3bd46e5db019289c805a1a2504a2
1,499
cpp
C++
Sid's Levels/Level - 3/Graphs/Word Ladder - Optimized.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
14
2021-08-22T18:21:14.000Z
2022-03-08T12:04:23.000Z
Sid's Levels/Level - 3/Graphs/Word Ladder - Optimized.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
1
2021-10-17T18:47:17.000Z
2021-10-17T18:47:17.000Z
Sid's Levels/Level - 3/Graphs/Word Ladder - Optimized.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
5
2021-09-01T08:21:12.000Z
2022-03-09T12:13:39.000Z
//Usage of dictionary for lookups class Solution { public: //OM GAN GANAPATHAYE NAMO NAMAH //JAI SHRI RAM //JAI BAJRANGBALI //AMME NARAYANA, DEVI NARAYANA, LAKSHMI NARAYANA, BHADRE NARAYANA struct Node { string s; int d; }; int ladderLength(string beginWord, string endWord, vector<string>& wordList) { Node start = {beginWord, 0}; queue<Node> q; q.push(start); unordered_map<string, bool> visited; visited[beginWord] = true; unordered_set<string> dict(wordList.begin(), wordList.end()); while(!q.empty()) { Node top = q.front(); q.pop(); string ts = top.s; int td = top.d; if(ts == endWord) return td + 1; string word = ts; for(int i = 0; i < word.size(); i++) { char x = word[i]; for(int j = 0; j < 26; j++) { char ch = j + 'a'; word[i] = ch; if(!visited[word]) { if(dict.find(word) != dict.end()) { visited[word] = true; Node temp = {word, td+1}; q.push(temp); } } } word[i] = x; } } return 0; } };
28.826923
82
0.393596
[ "vector" ]
776b451a5b85ef299d6a11ec2bbbde5f5f755636
6,129
cxx
C++
src/BinnedCountsCache.cxx
fermi-lat/Likelihood
78f6bd72449896e0699ffd832826f1b0dfffa3cc
[ "BSD-3-Clause" ]
5
2017-11-09T09:27:27.000Z
2020-06-26T14:22:37.000Z
src/BinnedCountsCache.cxx
fermi-lat/Likelihood
78f6bd72449896e0699ffd832826f1b0dfffa3cc
[ "BSD-3-Clause" ]
60
2018-01-11T01:57:51.000Z
2022-02-25T19:49:40.000Z
src/BinnedCountsCache.cxx
fermi-lat/Likelihood
78f6bd72449896e0699ffd832826f1b0dfffa3cc
[ "BSD-3-Clause" ]
2
2018-11-14T19:17:59.000Z
2020-01-13T11:43:34.000Z
/** * @file BinnedCountsCache.cxx * @brief * @author * * $Header: /nfs/slac/g/glast/ground/cvs/Likelihood/src/BinnedCountsCache.cxx,v 1.3 2017/10/06 01:31:00 echarles Exp $ */ #include "Likelihood/BinnedCountsCache.h" #include <stdexcept> #include "Likelihood/WeightMap.h" #include "Likelihood/FileUtils.h" #include "Likelihood/FitUtils.h" #include "Likelihood/ProjMap.h" namespace Likelihood { BinnedCountsCache::BinnedCountsCache(CountsMapBase & dataMap, const Observation & observation, const ProjMap* weightMap, const std::string& srcMapsFile, bool overwriteWeights) :m_dataMap(dataMap), m_numPixels(dataMap.pixels().size()), m_weightMap_orig(weightMap), m_weightMap(0), m_weightedCounts(0) { log_energy_ratios(m_dataMap.energies(),m_log_energy_ratios); if ( weightMap != 0 ) { if ( FileUtils::fileHasExtension(srcMapsFile,"__weights__") && !overwriteWeights ) { st_stream::StreamFormatter formatter("BinnedLikelihood","", 2); formatter.warn() << "Reading existing weights map from file " << srcMapsFile << std::endl; m_weightMap = new WeightMap(srcMapsFile, &dataMap, observation); } else { m_weightMap = new WeightMap(*weightMap,&dataMap,observation,true); } } identifyFilledPixels(); computeCountsSpectrum(); } BinnedCountsCache::~BinnedCountsCache() { delete m_weightMap; delete m_weightedCounts; } void BinnedCountsCache::setCountsMap(const std::vector<float> & counts) { if(counts.size() != m_dataMap.data().size()) throw std::runtime_error("Wrong size for input counts map."); m_dataMap.setImage(counts); identifyFilledPixels(); computeCountsSpectrum(); } void BinnedCountsCache::setWeightsMap(const ProjMap* wmap, const Observation & observation) { if ( wmap == m_weightMap_orig) return; // EAC, FIXME. This is a memory leak. Need to reference count the maps, // Or use clones. // delete m_weightMap_orig; delete m_weightMap; m_weightMap_orig = wmap; if ( wmap == 0 ) { m_weightMap = 0; } else { m_weightMap = new WeightMap(*wmap,&m_dataMap,observation,true); } identifyFilledPixels(); computeCountsSpectrum(); } tip::Extension* BinnedCountsCache::saveWeightsMap(const std::string& srcMapsFile, bool replace) const { if ( m_weightMap == 0 ) return 0; bool has_weights = FileUtils::fileHasExtension(srcMapsFile,"__weights__"); if ( has_weights ) { if ( replace ) { return FileUtils::replace_image_from_float_vector(srcMapsFile,"__weights__", m_dataMap,m_weightMap->model(),false); } else { // just leave it be; ; } } else { return FileUtils::append_image_from_float_vector(srcMapsFile,"__weights__", m_dataMap,m_weightMap->model(),false); } return 0; } void BinnedCountsCache::fillWeightedCounts() { if ( m_weightMap == 0 ) { delete m_weightedCounts; m_weightedCounts = 0; return; } delete m_weightedCounts; m_weightedCounts = m_dataMap.clone(); // FIXME, this would be more efficient if CountsMapBase had a multiply by function size_t ne = num_ebins(); size_t npix = num_pixels(); std::vector<float> wts(ne*npix); for ( size_t j(0); j < npix; j++ ) { for (size_t k(0); k < ne; k++) { size_t idx = k*npix +j; double w = m_weightMap->model()[idx]; bool is_null = w <= 0 || m_dataMap.data()[idx] <= 0; w = is_null ? 0 : w; wts[idx] = m_dataMap.data()[idx] * w; } } m_weightedCounts->setImage(wts); } void BinnedCountsCache::identifyFilledPixels() { fillWeightedCounts(); const std::vector<float> & the_data = data(has_weights()); m_filledPixels.clear(); m_firstPixels.clear(); m_firstPixels.resize(num_ebins() + 1, 0); size_t i(0); for (unsigned int k(0); k < num_ebins(); k++ ) { m_firstPixels[k] = m_filledPixels.size(); for (unsigned int ipix(0); ipix < m_numPixels; ipix++, i++) { if (the_data[i] > 0) { size_t idx = i % m_numPixels; m_filledPixels.push_back(idx); } } } m_firstPixels[num_ebins()] = m_filledPixels.size(); } void BinnedCountsCache::log_energy_ratios(const std::vector<double>& energies, std::vector<double>& log_ratios) { FitUtils::log_energy_ratios(energies, log_ratios); } void BinnedCountsCache::computeCountsSpectrum() { // EAC_FIX, CountsMap should be able to do this switch ( m_dataMap.projection().method() ) { case astro::ProjBase::WCS: computeCountsSpectrum_wcs(); return; case astro::ProjBase::HEALPIX: computeCountsSpectrum_healpix(); return; default: break; } std::string errMsg("BinnedLikelihood did not recognize projection method used for CountsMap: "); errMsg += m_dataMap.filename(); throw std::runtime_error(errMsg); } void BinnedCountsCache::computeCountsSpectrum_wcs() { m_countsSpectrum.clear(); m_countsSpectrum_wt.clear(); size_t nx(m_dataMap.imageDimension(0)); size_t ny(m_dataMap.imageDimension(1)); size_t nz(m_dataMap.imageDimension(2)); size_t indx(0); for (size_t k = 0; k < nz; k++) { double ntot(0); double ntot_wt(0); for (size_t j = 0; j < ny; j++) { for (size_t i = 0; i < nx; i++) { ntot += data(false)[indx]; ntot_wt += data(has_weights())[indx]; indx++; } } m_countsSpectrum.push_back(ntot); m_countsSpectrum_wt.push_back(ntot_wt); } } void BinnedCountsCache::computeCountsSpectrum_healpix() { m_countsSpectrum.clear(); m_countsSpectrum_wt.clear(); size_t nx(m_dataMap.imageDimension(0)); size_t ny(m_dataMap.imageDimension(1)); size_t indx(0); for (size_t k = 0; k < ny; k++) { double ntot(0); double ntot_wt(0); for (size_t i = 0; i < nx; i++) { ntot += data(false)[indx]; ntot_wt += data(has_weights())[indx]; indx++; } m_countsSpectrum.push_back(ntot); m_countsSpectrum_wt.push_back(ntot_wt); } } } // namespace Likelihood
30.192118
118
0.653124
[ "vector", "model" ]
776e54a312cd4658419f25a63e08954edee3cff2
5,699
cpp
C++
matrix_chain_multiplication.cpp
SAK90/dynamicProgramming
09dbcd701fd121582956812ec4200bb4f81b8419
[ "MIT" ]
null
null
null
matrix_chain_multiplication.cpp
SAK90/dynamicProgramming
09dbcd701fd121582956812ec4200bb4f81b8419
[ "MIT" ]
null
null
null
matrix_chain_multiplication.cpp
SAK90/dynamicProgramming
09dbcd701fd121582956812ec4200bb4f81b8419
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; /* int MCM_recursive(vector<int>& v, int i, int j){ // dimension of matrix a[i] = v[i-1] x v[i] if(i>=j) return 0; int ans = INT_MAX; for(int k = i; k <= j-1; k++){ int temp_ans_left = MCM_recursive(v, i, k); int temp_ans_right = MCM_recursive(v, k+1, j); int temp_ans = temp_ans_left + temp_ans_right + v[i-1]*v[k]*v[j]; ans = min(ans, temp_ans); } return ans; } int dp[100][100]; int MCM_memoised(vector<int>& v, int i, int j){ if(i >= j){ dp[i][j] = 0; return 0; } if(dp[i][j] != -1){ return dp[i][j]; } int ans = INT_MAX; for(int k = i; k <= j-1; ++k){ int temp_ans = MCM_memoised(v, i, k) + MCM_memoised(v, k+1, j) + v[i-1]*v[k]*v[j]; ans = min(ans, temp_ans); } dp[i][j] = ans; return dp[i][j]; } */ bool is_palindrome(string s, int i, int j){ int ans = true; while(i <= j){ if(s[i] != s[j]){ ans = false; break; } ++i, --j; } return ans; } int dp_1[100][100]; int palindrome_partition(string s, int i, int j){ if(i >= j){ return 0; } if(is_palindrome(s, i, j)){ return 0; } int ans = INT_MAX; for(int k = i; k <= j-1; ++k){ int temp_ans = palindrome_partition(s, i, k) + palindrome_partition(s, k+1, j) + 1; ans = min(ans, temp_ans); } return ans; } int palindrome_partition_memo(string s, int i, int j){ if(i >= j){ return 0; } if(dp_1[i][j] != -1){ return dp_1[i][j]; } if(is_palindrome(s, i, j)){ return 0; } int ans = INT_MAX; for(int k = i; k <= j-1; ++k){ int temp_left, temp_right; if(dp_1[i][k] != -1){ temp_left = dp_1[i][k]; }else{ temp_left = palindrome_partition_memo(s, i, k); dp_1[i][k] = temp_left; } if(dp_1[k+1][j] != -1){ temp_right = dp_1[k+1][j]; }else{ temp_right = palindrome_partition_memo(s, k+1, j); dp_1[k+1][j] = temp_right; } int temp_ans = temp_left + temp_right + 1; ans = min(ans, temp_ans); } dp_1[i][j] = ans; return ans; } int bool_true(string s, bool t, int i, int j){ if(i>=j){ if(t){ return s[i] == 'T'; }else{ return s[i] == 'F'; } } int ans = 0; for(int k = i+1; k <= j-1; k+=2){ int left_false = bool_true(s, false, i, k-1); int left_true = bool_true(s, true, i, k-1); int right_false = bool_true(s, false, k+1, j); int right_true = bool_true(s, true, k+1, j); if(s[k] == '|'){ if(t==true){ ans += left_false*right_true + left_true*right_false + left_true*right_true; }else{ ans += left_false*right_false; } } else if(s[k] == '^'){ if(t==true){ ans += left_false*right_true + left_true*right_false; }else{ ans += left_false*right_false + left_true*right_true; } } else if(s[k] == '&'){ if(t==true){ ans += left_true*right_true; }else{ ans += left_false*right_false + left_true*right_false + left_false*right_true; } } } return ans; } const int d = 1001; int dp_2[d][d][2]; int bool_true_memo(string s, bool t, int i, int j){ if(i>=j){ if(t){ dp_2[i][j][t] = s[i] == 'T'; }else{ dp_2[i][j][t] = s[i] == 'F'; } return dp_2[i][j][t]; } if(dp_2[i][j][t] != -1){ return dp_2[i][j][t]; } int ans = 0; for(int k = i+1; k <= j-1; k+=2){ int left_false = bool_true_memo(s, false, i, k-1); int left_true = bool_true_memo(s, true, i, k-1); int right_false = bool_true_memo(s, false, k+1, j); int right_true = bool_true_memo(s, true, k+1, j); if(s[k] == '|'){ if(t==true){ ans += left_false*right_true + left_true*right_false + left_true*right_true; }else{ ans += left_false*right_false; } } else if(s[k] == '^'){ if(t==true){ ans += left_false*right_true + left_true*right_false; }else{ ans += left_false*right_false + left_true*right_true; } } else if(s[k] == '&'){ if(t==true){ ans += left_true*right_true; }else{ ans += left_false*right_false + left_true*right_false + left_false*right_true; } } } dp_2[i][j][t] = ans; return ans; } //T^F&T int main(){ //mcm /*vector<int> v = {40, 20, 30, 10, 30}; cout << MCM_recursive(v, 1, v.size()-1) << '\n'; memset(dp, -1, sizeof(dp)); cout << MCM_memoised(v, 1, v.size()-1) << '\n';*/ //palindrome_partition /*string s; cin >> s; cout << palindrome_partition(s, 0, s.size()-1) << '\n'; memset(dp_1, -1, sizeof(dp_1)); cout << palindrome_partition_memo(s, 0, s.size()-1) << '\n';*/ //bool_true string s; cin >> s; //cout << bool_true(s, true, 0, s.size()-1) << '\n'; memset(dp_2, -1, sizeof(dp_2)); cout << bool_true_memo(s, true, 0, s.size()-1) << '\n'; }
26.506977
95
0.451307
[ "vector" ]
7770d09f1872990f7922c525a5895b68f02103be
4,664
cpp
C++
IrrlichtExtensions/TouchKey.cpp
wolfgang1991/CommonLibraries
949251019cc8dd532938d16ab85a4e772eb6817e
[ "Zlib" ]
null
null
null
IrrlichtExtensions/TouchKey.cpp
wolfgang1991/CommonLibraries
949251019cc8dd532938d16ab85a4e772eb6817e
[ "Zlib" ]
1
2020-07-31T13:20:54.000Z
2020-08-06T15:45:39.000Z
IrrlichtExtensions/TouchKey.cpp
wolfgang1991/CommonLibraries
949251019cc8dd532938d16ab85a4e772eb6817e
[ "Zlib" ]
null
null
null
#include <TouchKey.h> #include <ICommonAppContext.h> #include <timing.h> #include <FlexibleFont.h> #include <mathUtils.h> #include <Drawer2D.h> #include <IrrlichtDevice.h> using namespace std; using namespace irr; using namespace core; using namespace video; using namespace gui; #define PRESS_SCALE 0.75 TouchKey::TouchKey(ICommonAppContext* context, wchar_t C, wchar_t CShifted, irr::EKEY_CODE Keycode, irr::core::rect<s32> Rectangle, irr::video::ITexture* OverrideTex){ ch = C; cString = stringw(&C, 1); cShiftedString = stringw(&CShifted, 1); cShifted = CShifted; keycode = Keycode; overrideTex = OverrideTex; event.Char = ch; event.Control = false; event.Key = Keycode; event.PressedDown = false; event.Shift = false; rectangle = Rectangle; c = context; drawer = c->getDrawer(); device = c->getIrrlichtDevice(); driver = device->getVideoDriver(); env = device->getGUIEnvironment(); wasPressedOutside = false; T0 = 1.0; t0 = 0.5; m = 0.1; lastPressedEventTime = lastPressedTime = 0.0; } void TouchKey::reset(){ wasPressedOutside = false; event.PressedDown = false; lastPressedTime = lastPressedEventTime = 0.0; } static inline bool isPointInsideExcludingLowerRight(const rect<s32>& r, const vector2d<s32>& v){ return v.X>=r.UpperLeftCorner.X && v.X<r.LowerRightCorner.X && v.Y>=r.UpperLeftCorner.Y && v.Y<r.LowerRightCorner.Y; } bool TouchKey::processMouseEvent(irr::SEvent::SMouseInput mevent, bool* isMouseInside){ vector2d<s32> mpos(mevent.X, mevent.Y); bool mInside = isPointInsideExcludingLowerRight(rectangle, mpos); if(isMouseInside){*isMouseInside = mInside;} if(mInside){ if(mevent.Event == EMIE_LMOUSE_PRESSED_DOWN){ event.PressedDown = true; lastPressedEventTime = 0.0; lastPressedTime = getSecs(); return true; }else if(mevent.Event == EMIE_LMOUSE_LEFT_UP){ wasPressedOutside = false; event.PressedDown = false; return true; } }else{ bool ret = false; if(event.PressedDown){ret = true;} event.PressedDown = false; wasPressedOutside = mevent.isLeftPressed(); return ret; } return false; } bool TouchKey::mousePressedDownOutside(){ return wasPressedOutside; } bool TouchKey::render(FlexibleFont* font, bool drawBox, SColor color){ if(event.PressedDown){color.setAlpha(255); color.setRed(PRESS_SCALE*color.getRed()); color.setGreen(PRESS_SCALE*color.getGreen()); color.setBlue(PRESS_SCALE*color.getBlue());} SColor halfColor(255, color.getRed()/2, color.getGreen()/2, color.getBlue()/2); if(drawBox){ driver->draw2DRectangle(color, rectangle); driver->draw2DRectangleOutline(rect<s32>(rectangle.UpperLeftCorner.X+1,rectangle.UpperLeftCorner.Y+1,rectangle.LowerRightCorner.X-1,rectangle.LowerRightCorner.Y-1), halfColor); } if(overrideTex){ dimension2d<u32> tsize = overrideTex->getOriginalSize(); rect<s32> texrect = makeXic(rectangle, (float)tsize.Width/(float)tsize.Height); drawer->setTextureWrap(ETC_CLAMP, ETC_CLAMP); drawer->draw(overrideTex, texrect.UpperLeftCorner, texrect.getSize()); drawer->setTextureWrap(); }else{ if(!event.Shift){ font->draw(cString, rectangle, SColor(255, 0, 0, 0), true, true, &rectangle); if(!(ch>=L'a' && ch<=L'z')){ rect<s32> greyRect(rectangle); greyRect.LowerRightCorner.Y = (greyRect.UpperLeftCorner.Y+greyRect.LowerRightCorner.Y)/2; greyRect.LowerRightCorner.X = (greyRect.UpperLeftCorner.X+greyRect.LowerRightCorner.X)/2; irr::f32 optimalScale = font->calculateOptimalScale(cShiftedString.c_str(), dimension2d<u32>(greyRect.getWidth(), greyRect.getHeight())); vector2d<f32> currentScale = font->getDefaultScale(); font->setDefaultScale(vector2d<f32>(optimalScale,optimalScale)); font->draw(cShiftedString, greyRect, halfColor, true, true, &greyRect); font->setDefaultScale(currentScale); } }else{ font->draw(cShiftedString, rectangle, SColor(255, 0, 0, 0), true, true, &rectangle); } } if(event.PressedDown){//automatically create event for pressed key in case of a longer tap (with increasing frequency) double t = getSecs()-lastPressedTime; double T = Clamp(T0-((t-t0)*((T0-m)/(2.0*t0))), m, T0); if(t-lastPressedEventTime>=T){ lastPressedEventTime = t; return true; } } return false; } irr::SEvent::SKeyInput TouchKey::getEvent(){ return event; } void TouchKey::setOverrideTexture(irr::video::ITexture* OverrideTex){ overrideTex = OverrideTex; } irr::video::ITexture* TouchKey::getOverrideTexture(){ return overrideTex; } void TouchKey::setShiftPressed(bool pressed){ event.Shift = pressed; event.Char = pressed?cShifted:ch; } void TouchKey::setRectangle(const irr::core::rect<irr::s32>& rectangle){ this->rectangle = rectangle; }
33.314286
178
0.733491
[ "render" ]
a5666baaba944991bda93cecdc3c1aaf7c31ecb9
2,233
hpp
C++
TFD_Units/Classes/Vehicles/SoldierSurvival.hpp
Heartbroken-Git/TFP_CORE
2102248d548f2a2d69794f6c47932f9a998c5c3a
[ "RSA-MD", "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
TFD_Units/Classes/Vehicles/SoldierSurvival.hpp
Heartbroken-Git/TFP_CORE
2102248d548f2a2d69794f6c47932f9a998c5c3a
[ "RSA-MD", "Naumen", "Condor-1.1", "MS-PL" ]
37
2016-03-29T06:25:42.000Z
2021-01-03T19:12:19.000Z
TFD_Units/Classes/Vehicles/SoldierSurvival.hpp
Heartbroken-Git/TFP_CORE
2102248d548f2a2d69794f6c47932f9a998c5c3a
[ "RSA-MD", "Naumen", "Condor-1.1", "MS-PL" ]
2
2017-12-13T23:10:05.000Z
2019-03-16T11:55:34.000Z
class TFD_Plouf_UBACS: b_soldier_survival_F // Define of a new class, which parameters are inherited from B_Soldier_base_F, with exception of those defined below. { author = "Heartbroken"; // The name of the author of the asset, which is displayed in the editor. displayName = "Sauveteur-plongeur (UBACS)"; side = 1; faction = "TFD_AA"; scope = 2; // 2 = class is available in the editor; 1 = class is unavailable in the editor, but can be accessed via a macro; 0 = class is unavailable (and used for inheritance only). scopeCurator = 2; // 2 = class is available in Zeus; 0 = class is unavailable in Zeus. scopeArsenal = 2; // 2 = class is available in the Virtual Arsenal; 0 = class is unavailable in the Virtual Arsenal. uniformClass = "TFD_UBACSCE_Palmes"; // This links this soldier to a particular uniform. For the details, see below. hiddenSelections[] = {"camo"}; // List of model selections which can be changed with hiddenSelectionTextures[] and hiddenSelectionMaterials[] properties. If empty, model textures are used. hiddenSelectionsTextures[] = {"\TFD_Units\Data\Uniform\UBACS_CE.paa"}; backpack = ""; weapons[] = {Throw, Put}; // Which weapons the character has. respawnWeapons[] = {Throw, Put}; // Which weapons the character respawns with. Items[] = {FirstAidKit, FirstAidKit, FirstAidKit, FirstAidKit}; // Which items the character has. RespawnItems[] = {FirstAidKit, FirstAidKit, FirstAidKit, FirstAidKit}; // Which items the character respawns with. magazines[] = {Chemlight_green, Chemlight_green, Chemlight_red, Chemlight_red}; // What ammunition the character has. respawnMagazines[] = {Chemlight_green, Chemlight_green, Chemlight_red, Chemlight_red}; // What ammunition the character respawns with. linkedItems[] = {G_B_Diving, ItemMap, ItemCompass, ItemWatch, ItemRadio}; // Which items the character has. respawnLinkedItems[] = {G_B_Diving, ItemMap, ItemCompass, ItemWatch, ItemRadio}; // Which items the character respawns with. };
101.5
217
0.667712
[ "model" ]
a56daf82fdf4967917d4b89d3f3ab2408182cd02
1,188
cpp
C++
xdl-algorithm-solution/TDMServing/test/model/blaze/blaze_model_conf_test.cpp
Ru-Xiang/x-deeplearning
04cc0497150920c64b06bb8c314ef89977a3427a
[ "Apache-2.0" ]
4,071
2018-12-13T04:17:38.000Z
2022-03-30T03:29:35.000Z
xdl-algorithm-solution/TDMServing/test/model/blaze/blaze_model_conf_test.cpp
laozhuang727/x-deeplearning
781545783a4e2bbbda48fc64318fb2c6d8bbb3cc
[ "Apache-2.0" ]
359
2018-12-21T01:14:57.000Z
2022-02-15T07:18:02.000Z
xdl-algorithm-solution/TDMServing/test/model/blaze/blaze_model_conf_test.cpp
laozhuang727/x-deeplearning
781545783a4e2bbbda48fc64318fb2c6d8bbb3cc
[ "Apache-2.0" ]
1,054
2018-12-20T09:57:42.000Z
2022-03-29T07:16:53.000Z
/* Copyright (C) 2016-2018 Alibaba Group Holding Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "gtest/gtest.h" #define protected public #define private public #include "model/blaze/blaze_model_conf.h" namespace tdm_serving { TEST(BlazeModelConf, init) { std::string conf_path = "test_data/conf/model.conf"; std::string section_name = "simp_model"; util::ConfParser conf_parser; ASSERT_TRUE(conf_parser.Init(conf_path)); BlazeModelConf model_conf; ASSERT_TRUE(model_conf.Init(section_name, conf_parser)); EXPECT_EQ(blaze::kPDT_CPU, model_conf.device_type()); } } // namespace tdm_serving
30.461538
80
0.723906
[ "model" ]
a573d0041e4318272e1b9bcd087c11156e2dcc29
2,598
cpp
C++
CppLisp/CppLispInterpreter/Exception.cpp
mneuroth/fuel-lang
3b21d058a0eaf43df5c73685a4079bdb877c3c07
[ "MIT" ]
1
2018-08-14T00:11:35.000Z
2018-08-14T00:11:35.000Z
CppLisp/CppLispInterpreter/Exception.cpp
mneuroth/fuel-lang
3b21d058a0eaf43df5c73685a4079bdb877c3c07
[ "MIT" ]
null
null
null
CppLisp/CppLispInterpreter/Exception.cpp
mneuroth/fuel-lang
3b21d058a0eaf43df5c73685a4079bdb877c3c07
[ "MIT" ]
2
2018-08-14T00:11:39.000Z
2020-09-03T08:36:36.000Z
/* * FUEL(isp) is a fast usable embeddable lisp interpreter. * * Copyright (c) 2016 Michael Neuroth * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * */ #include "Exception.h" #include "Scope.h" namespace CppLisp { LispException::LispException(const string & text, LispScope * scope) //: base(text) : LispExceptionBase(text) { Message = text; if (scope != 0) { string sStack; #ifndef _DISABLE_DEBUGGER sStack = scope->DumpStackToString(); #endif AddModuleNameAndStackInfos(scope->ModuleName, sStack); AddTokenInfos(scope->CurrentToken); } else { AddModuleNameAndStackInfos("???", "???"); AddTokenInfos(null); } } LispException::LispException(const string & text, std::shared_ptr<LispToken> token, const string & moduleName, const string & stackInfo) //: base(text) : LispExceptionBase(text) { Message = text; AddModuleNameAndStackInfos(moduleName, stackInfo); AddTokenInfos(token); } void LispException::AddModuleNameAndStackInfos(const string & moduleName, const string & stackInfo) { // TODO konstanten korrekt behandeln Data["ModuleName"] = std::make_shared<object>(moduleName); Data["StackInfo"] = std::make_shared<object>(stackInfo); } void LispException::AddTokenInfos(std::shared_ptr<LispToken> token) { // TODO konstanten korrekt behandeln Data["LineNo"] = std::make_shared<object>(token != null ? (int)token->LineNo : -1); Data["StartPos"] = std::make_shared<object>(token != null ? (int)token->StartPos : -1); Data["StopPos"] = std::make_shared<object>(token != null ? (int)token->StopPos : -1); } }
32.886076
137
0.734026
[ "object" ]
a57dbc9de4af3bfe47521fd874381107be3d23b8
27,502
inl
C++
blast/include/util/row_reader.inl
mycolab/ncbi-blast
e59746cec78044d2bf6d65de644717c42f80b098
[ "Apache-2.0" ]
null
null
null
blast/include/util/row_reader.inl
mycolab/ncbi-blast
e59746cec78044d2bf6d65de644717c42f80b098
[ "Apache-2.0" ]
null
null
null
blast/include/util/row_reader.inl
mycolab/ncbi-blast
e59746cec78044d2bf6d65de644717c42f80b098
[ "Apache-2.0" ]
null
null
null
#ifndef UTIL___ROW_READER__INL #define UTIL___ROW_READER__INL /* $Id: row_reader.inl 575325 2018-11-27 18:22:00Z ucko $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Authors: Design and advice - Denis Vakatov * Implementation and critique - Sergey Satskiy * * Credits: Alex Astashyn * (GetFieldValueConverted) * * File Description: * CRowReader utility types, classes, functions ** =========================================================================== */ #ifndef UTIL___ROW_READER_INCLUDE__INL # error "The row_reader.inl must only be included in row_reader.hpp" #endif /// Delimited stream traits use the ERR_Action members to instruct what should /// be done next. These values are returned by various trait callbacks. enum ERR_Action { /// Skip this line eRR_Skip, /// Continue processing this line, in full eRR_Continue_Data, /// Continue processing this line but skip Tokenize() and Translate() /// @note /// Not allowed for Tokenize() and Translate() returns eRR_Continue_Comment, /// Continue processing this line but skip Tokenize() and Translate() /// @note /// Not allowed for Tokenize() and Translate() returns eRR_Continue_Metadata, /// Continue processing this line but skip Tokenize() and Translate() /// @note /// not allowed for Tokenize() and Translate() returns eRR_Continue_Invalid, /// Stop processing the stream eRR_Interrupt }; /// The Translate() callback result. It is used to translate field values. enum ERR_TranslationResult { eRR_UseOriginal, ///< No translation done eRR_Translated, ///< The value has been translated to another string eRR_Null ///< The value has been translated to NULL }; /// Miscellaneous trait-specific flags /// It is used when a row stream should be built on a file. The file will be /// opened with the mode provided by the traits, see /// TTraitsFlags GetFlags(void) const /// member. enum ERR_TraitsFlags { fRR_OpenFile_AsBinary = (0 << 1), ///< open file in a binary mode fRR_Default = 0 ///< open file in a text mode }; typedef int TTraitsFlags; ///< Bit-wise OR of ERR_TraitsFlags /// CRowReader passes such events to the Traits via OnEvent() callback enum ERR_Event { eRR_Event_SourceBegin, ///< Data source has started or been switched ///< (no reads yet though). eRR_Event_SourceEnd, ///< Data source has hit EOF eRR_Event_SourceError ///< Data source has hit an error on read }; /// Indicate whether the "ERR_Event" event (passed to the OnEvent() callback) /// occured during regular read vs during validation enum ERR_EventMode { eRR_EventMode_Iterating, ///< We are iterating through the rows eRR_EventMode_Validating ///< We are performing data validation }; /// How to react to the potentially disruptive events /// @sa OnEvent() enum ERR_EventAction { eRR_EventAction_Default, ///< Do some default action eRR_EventAction_Stop, ///< Stop further processing eRR_EventAction_Continue ///< Resume processing }; /// The class represents the current delimited row stream context class CRR_Context { public: virtual string Serialize() const { string context = "Row reader context: "; if ( !m_SourceName.empty() ) context += "Source name: " + m_SourceName + "; "; if (m_LinesAlreadyRead) { context += "Last read line position in the stream: " + NStr::NumericToString(m_CurrentLinePos) + "; " "Last read line number: " + NStr::NumericToString(m_CurrentLineNo) + "; "; } else { if (!m_ReachedEnd) context += "Position in the stream: " + NStr::NumericToString(m_CurrentLinePos) + "; " "No lines read yet; "; } if (m_RawDataAvailable) context += "Raw line data: '" + m_RawData + "'; "; else context += "Raw line data are not available; "; if (m_ReachedEnd) context += "Stream has reached end"; else context += "Stream has not reached end yet"; return context; } virtual ~CRR_Context() {} CRR_Context() : m_LinesAlreadyRead(false), m_CurrentLineNo(0), m_CurrentLinePos(0), m_RawDataAvailable(false), m_ReachedEnd(false) {} CRR_Context(const string& sourcename, bool lines_already_read, TLineNo line_no, TStreamPos current_line_pos, bool raw_data_available, const string& raw_data, bool reached_end) : m_SourceName(sourcename), m_LinesAlreadyRead(lines_already_read), m_CurrentLineNo(line_no), m_CurrentLinePos(current_line_pos), m_RawDataAvailable(raw_data_available), m_RawData(raw_data), m_ReachedEnd(reached_end) {} // Deriving classes must implement their own version of this member to // have the exceptions working properly virtual CRR_Context* Clone(void) const { return new CRR_Context(m_SourceName, m_LinesAlreadyRead, m_CurrentLineNo, m_CurrentLinePos, m_RawDataAvailable, m_RawData, m_ReachedEnd); } public: /// Name of the data source, such as: /// - file name if the stream was constructed on a file using SetDataSource() /// - URL if the stream was constructed on some other resource /// - "User Stream" stream was passed in using SetDataSource() string m_SourceName; // true if at least one line has been successfully read from the stream bool m_LinesAlreadyRead; TLineNo m_CurrentLineNo; // 0-based TStreamPos m_CurrentLinePos; // 0-based // true if the raw data has been read successfully bool m_RawDataAvailable; string m_RawData; bool m_ReachedEnd; }; /// Exception to be used throughout API class CRowReaderException : public CException { public: enum EErrCode { eUnexpectedRowType, eStreamFailure, eFieldNoNotFound, eDereferencingEndIterator, eAdvancingEndIterator, eDereferencingNoDataIterator, eFileNotFound, eNoReadPermissions, eInvalidAction, eLineProcessing, eEndIteratorRowAccess, eFieldNoOutOfRange, eFieldAccess, eFieldNameNotFound, eFieldMetaInfoAccess, eFieldConvert, eNullField, eValidating, eNonEndIteratorCompare, eIteratorWhileValidating, eRowDataReading, eTraitsOnEvent, eFieldValueValidation, eInvalidStream }; CRowReaderException( const CDiagCompileInfo& info, const CException* prev_exception, EErrCode err_code, const string& message, CRR_Context* ctxt, EDiagSev severity = eDiag_Error) : CException(info, prev_exception, message, severity), m_Context(ctxt) NCBI_EXCEPTION_DEFAULT_IMPLEMENTATION(CRowReaderException, CException); virtual const char * GetErrCodeString(void) const override { switch (GetErrCode()) { case eUnexpectedRowType: return "eUnexpectedRowType"; case eStreamFailure: return "eStreamFailure"; case eFieldNoNotFound: return "eFieldNoNotFound"; case eDereferencingEndIterator: return "eDereferencingEndIterator"; case eAdvancingEndIterator: return "eAdvancingEndIterator"; case eDereferencingNoDataIterator: return "eDereferencingNoDataIterator"; case eFileNotFound: return "eFileNotFound"; case eNoReadPermissions: return "eNoReadPermissions"; case eInvalidAction: return "eInvalidAction"; case eLineProcessing: return "eLineProcessing"; case eEndIteratorRowAccess: return "eEndIteratorRowAccess"; case eFieldNoOutOfRange: return "eFieldNoOutOfRange"; case eFieldAccess: return "eFieldAccess"; case eFieldNameNotFound: return "eFieldNameNotFound"; case eFieldMetaInfoAccess: return "eFieldMetaInfoAccess"; case eFieldConvert: return "eFieldConvert"; case eNullField: return "eNullField"; case eValidating: return "eValidating"; case eNonEndIteratorCompare: return "eNonEndIteratorCompare"; case eIteratorWhileValidating: return "eIteratorWhileValidating"; case eRowDataReading: return "eRowDataReading"; case eTraitsOnEvent: return "eTraitsOnEvent"; case eFieldValueValidation: return "eFieldValueValidation"; case eInvalidStream: return "eInvalidStream"; default: return CException::GetErrCodeString(); } } virtual void ReportExtra(ostream& out) const override { if (m_Context) out << m_Context->Serialize(); else out << "No context available"; } public: CRR_Context* GetContext(void) const { return m_Context.get(); } void SetContext(CRR_Context* ctxt) { m_Context.reset(ctxt); } protected: virtual void x_Assign(const CException& src) override { CException::x_Assign(src); const CRowReaderException& other = dynamic_cast<const CRowReaderException&>(src); if (other.m_Context) m_Context.reset(other.m_Context->Clone()); else m_Context.reset(nullptr); } private: unique_ptr<CRR_Context> m_Context; }; // Utility class merely for a scope class CRR_Util { public: // Converts a callback provided action to a string static string ERR_ActionToString(ERR_Action action) { switch (action) { case eRR_Skip: return "eRR_Skip"; case eRR_Continue_Data: return "eRR_Continue_Data"; case eRR_Continue_Comment: return "eRR_Continue_Comment"; case eRR_Continue_Metadata: return "eRR_Continue_Metadata"; case eRR_Continue_Invalid: return "eRR_Continue_Invalid"; case eRR_Interrupt: return "eRR_Interrupt"; } return "unknown"; } // Converts a framework event into a string static string ERR_EventToString(ERR_Event event) { switch (event) { case eRR_Event_SourceBegin: return "eRR_Event_SourceBegin"; case eRR_Event_SourceEnd: return "eRR_Event_SourceEnd"; case eRR_Event_SourceError: return "eRR_Event_SourceError"; } return "unknown"; } // Converts a basic field type into a string static string ERR_FieldTypeToString(ERR_FieldType type) { switch (type) { case eRR_String: return "eRR_String"; case eRR_Boolean: return "eRR_Boolean"; case eRR_Integer: return "eRR_Integer"; case eRR_Double: return "eRR_Double"; case eRR_DateTime: return "eRR_DateTime"; } return "unknown"; } // Converts the callback returned action to a row type static ERR_RowType ActionToRowType(ERR_Action action) { switch (action) { case eRR_Continue_Data: return eRR_Data; case eRR_Continue_Comment: return eRR_Comment; case eRR_Continue_Metadata: return eRR_Metadata; case eRR_Continue_Invalid: return eRR_Invalid; default: NCBI_THROW2(CRowReaderException, eUnexpectedRowType, "Unexpected action to convert to a row type", nullptr); } } // Checks the file existance and read permissions static void CheckExistanceAndPermissions(const string& sourcename) { CFile file(sourcename); if ( !file.Exists() ) NCBI_THROW2(CRowReaderException, eFileNotFound, "File " + sourcename + " is not found", nullptr); if ( !file.CheckAccess(CDirEntry::fRead) ) NCBI_THROW2(CRowReaderException, eNoReadPermissions, "No read permissions for file " + sourcename, nullptr); } // Utility functions to implement field value conversions static void GetFieldValueConverted(const CTempString& str_value, CTime& converted) { converted = CTime(string(str_value.data(), str_value.size())); } static void GetFieldValueConverted(const CTempString& str_value, string& converted) { converted = string(str_value.data(), str_value.size()); } static void GetFieldValueConverted(const CTempString& str_value, bool& converted) { converted = NStr::StringToBool(str_value); } static void GetFieldValueConverted(const CTempString& str_value, CTempString& converted) { converted = str_value; } // Conversion implementation respecting overflow // and covering all the arithmetic types template<typename T, typename = typename std::enable_if<std::is_arithmetic<T>::value>::type> static void GetFieldValueConverted(const CTempString& str_value, T& converted) { errno = 0; try { if (!NStr::StringToNumeric(str_value, &converted) || errno != 0) throw; } catch (const CException& exc) { NCBI_RETHROW2(exc, CRowReaderException, eFieldConvert, "Cannot convert field value '" + string(str_value.data(), str_value.size()) + "' to " + typeid(T).name(), nullptr); } catch (const exception& exc) { NCBI_THROW2(CRowReaderException, eFieldConvert, "Cannot convert field value '" + string(str_value.data(), str_value.size()) + "' to " + typeid(T).name() + ": " + exc.what(), nullptr); } catch (...) { NCBI_THROW2(CRowReaderException, eFieldConvert, "Unknown error while converting field value '" + string(str_value.data(), str_value.size()) + "' to " + typeid(T).name(), nullptr); } } // Validates a few basic type fields static void ValidateBasicTypeFieldValue(const CTempString& str_value, ERR_FieldType field_type, const string& props) { try { switch (field_type) { case eRR_Boolean: { bool converted; CRR_Util::GetFieldValueConverted(str_value, converted); } break; case eRR_Integer: { Int8 converted_int8; try { CRR_Util::GetFieldValueConverted(str_value, converted_int8); } catch (...) { Uint8 converted_uint8; CRR_Util::GetFieldValueConverted(str_value, converted_uint8); } } break; case eRR_Double: { double converted; CRR_Util::GetFieldValueConverted(str_value, converted); } break; case eRR_DateTime: { CTime(string(str_value.data(), str_value.size()), props); } default: break; } } catch (const CException& exc) { NCBI_RETHROW2(exc, CRowReaderException, eFieldValueValidation, "Error validating field value '" + string(str_value.data(), str_value.size()) + "' of type " + CRR_Util::ERR_FieldTypeToString(field_type), nullptr); } catch (const exception& exc) { NCBI_THROW2(CRowReaderException, eFieldValueValidation, "Error validating field value '" + string(str_value.data(), str_value.size()) + "' of type " + CRR_Util::ERR_FieldTypeToString(field_type) + ": " + exc.what(), nullptr); } catch (...) { NCBI_THROW2(CRowReaderException, eFieldValueValidation, "Unknown error while validating field value '" + string(str_value.data(), str_value.size()) + "' of type " + CRR_Util::ERR_FieldTypeToString(field_type), nullptr); } } }; // Stores the fields meta information: field names and types template <typename TTraits> class CRR_MetaInfo : public CObject { public: CRR_MetaInfo() : CObject() { m_FieldsInfo.reserve(64); } CRR_MetaInfo(const CRR_MetaInfo& other) : CObject() { Clear(true); // true -> clears both user and traits provided info m_FieldNamesIndex = other.m_FieldNamesIndex; m_FieldsInfo.reserve(other.m_FieldsInfo.size()); for (size_t k = 0; k < other.m_FieldsInfo.size(); ++k) { m_FieldsInfo.push_back(other.m_FieldsInfo[k]); if (other.m_FieldsInfo[k].m_NameInit != eNotInitialized) { auto it = m_FieldNamesIndex.find( *other.m_FieldsInfo[k].m_FieldName); m_FieldsInfo[k].m_FieldName = &it->first; } } } public: void Clear(bool user_clear) { if (user_clear) { m_FieldsInfo.clear(); m_FieldNamesIndex.clear(); return; } // Non-user clear, i.e. the only traits provided meta information // should be erased. for (size_t index = 0; index < m_FieldsInfo.size(); ++index) { if (m_FieldsInfo[index].m_ExtTypeInit == eTraitInitialized) m_FieldsInfo[index].m_ExtTypeInit = eNotInitialized; if (m_FieldsInfo[index].m_TypeInit == eTraitInitialized) m_FieldsInfo[index].m_TypeInit = eNotInitialized; if (m_FieldsInfo[index].m_NameInit == eTraitInitialized) { if (x_UpdateNameRef((TFieldNo)index) == 1) m_FieldNamesIndex.erase(*m_FieldsInfo[index].m_FieldName); m_FieldsInfo[index].m_NameInit = eNotInitialized; m_FieldsInfo[index].m_FieldName = nullptr; } } } void SetFieldName(TFieldNo field, const string& name, bool user_init) { if (field >= m_FieldsInfo.size()) m_FieldsInfo.resize(field + 1); // Traits provided name must be ignored if the user has already set it if (m_FieldsInfo[field].m_NameInit == eUserInitialized && (!user_init)) return; if (m_FieldsInfo[field].m_NameInit != eNotInitialized) { if (name == *m_FieldsInfo[field].m_FieldName) { x_UpdateInitField(&m_FieldsInfo[field].m_NameInit, user_init); if (user_init) m_FieldNamesIndex[name] = field; return; } if (x_UpdateNameRef(field) == 1) m_FieldNamesIndex.erase(*m_FieldsInfo[field].m_FieldName); } auto inserted = m_FieldNamesIndex.insert(make_pair(name, field)); m_FieldsInfo[field].m_FieldName = &inserted.first->first; x_UpdateInitField(&m_FieldsInfo[field].m_NameInit, user_init); } void SetFieldType( TFieldNo field, const CRR_FieldType<ERR_FieldType>& type, bool user_init) { if (field >= m_FieldsInfo.size()) m_FieldsInfo.resize(field + 1); // Traits provided type must be ignored if the user has already set it if (m_FieldsInfo[field].m_TypeInit == eUserInitialized && (!user_init)) return; m_FieldsInfo[field].m_FieldType = type; x_UpdateInitField(&m_FieldsInfo[field].m_TypeInit, user_init); } void SetFieldTypeEx( TFieldNo field, const CRR_FieldType<ERR_FieldType>& type, const CRR_FieldType<typename TTraits::TExtendedFieldType>& extended_type, bool user_init) { if (field >= m_FieldsInfo.size()) m_FieldsInfo.resize(field + 1); // Traits provided type must be ignored if the user has already set it. // To avoid non-synced type updates the extended type is not set // (updated) either even if it was not initialized. if (m_FieldsInfo[field].m_TypeInit == eUserInitialized && (!user_init)) return; m_FieldsInfo[field].m_FieldType = type; m_FieldsInfo[field].m_FieldExtType = extended_type; x_UpdateInitField(&m_FieldsInfo[field].m_TypeInit, user_init); x_UpdateInitField(&m_FieldsInfo[field].m_ExtTypeInit, user_init); } TFieldNo GetFieldIndexByName(const string& field) const { auto it = m_FieldNamesIndex.find(field); if (it == m_FieldNamesIndex.end()) NCBI_THROW2(CRowReaderException, eFieldNoNotFound, "Unknown field name '" + field + "'", nullptr); return it->second; } TFieldNo GetDescribedFieldCount(void) const { TFieldNo count = 0; for (size_t index = 0; index < m_FieldsInfo.size(); ++index) if (m_FieldsInfo[index].IsInitialized()) ++count; return count; } private: size_t x_UpdateNameRef(TFieldNo field) { const string* name_ptr = m_FieldsInfo[field].m_FieldName; size_t use_count = 0; TFieldNo candidate = 0; for (TFieldNo index = 0; index < m_FieldNamesIndex.size(); ++index) { if (m_FieldsInfo[index].m_NameInit != eNotInitialized) { if (m_FieldsInfo[index].m_FieldName == name_ptr) { ++use_count; if (index != field) candidate = index; } } } if (use_count > 1) m_FieldNamesIndex[*name_ptr] = candidate; return use_count; } private: friend class CRR_Row<TTraits>; enum ERR_FieldMetaInfoInit { eNotInitialized = 0, eTraitInitialized = 1, eUserInitialized = 2 }; void x_UpdateInitField(ERR_FieldMetaInfoInit* field, bool user_init) { if (user_init) *field = eUserInitialized; else *field = eTraitInitialized; } struct SMetainfo { SMetainfo() : m_FieldName(nullptr), m_NameInit(eNotInitialized), m_TypeInit(eNotInitialized), m_ExtTypeInit(eNotInitialized) {} const string * m_FieldName; CRR_FieldType<ERR_FieldType> m_FieldType; CRR_FieldType<typename TTraits::TExtendedFieldType> m_FieldExtType; ERR_FieldMetaInfoInit m_NameInit; ERR_FieldMetaInfoInit m_TypeInit; ERR_FieldMetaInfoInit m_ExtTypeInit; bool IsInitialized(void) const { return (m_NameInit != eNotInitialized) || (m_TypeInit != eNotInitialized) || (m_ExtTypeInit != eNotInitialized); } }; map<string, TFieldNo> m_FieldNamesIndex; vector<SMetainfo> m_FieldsInfo; }; // Auxiliary structure to store a current stream info and a next stream info in // case of SetDataSource() calls struct SRR_SourceInfo { SRR_SourceInfo(): m_Stream(nullptr), m_StreamOwner(false) {} SRR_SourceInfo(CNcbiIstream* s, const string& sourcename, bool owner) : m_Stream(s), m_Sourcename(sourcename), m_StreamOwner(owner) {} ~SRR_SourceInfo() { Clear(); } void Clear(void) { if (m_StreamOwner && m_Stream != nullptr) delete m_Stream; m_Stream = nullptr; m_Sourcename.clear(); m_StreamOwner = false; } CNcbiIstream* m_Stream; string m_Sourcename; bool m_StreamOwner; }; /// This macro can be used in the traits class declaration to provide /// standard typedefs and methods to bind to the traits' "parent stream" #define RR_TRAITS_PARENT_STREAM(TTraits) \ public: \ /* Convenience stream type shorthand */ \ typedef CRowReader<TTraits> TStreamType; \ protected: \ TStreamType& GetMyStream(void) const { return *m_MyStream; } \ private: \ friend TStreamType; \ /* The CRowReader objects calls this function */ \ void x_SetMyStream(TStreamType* my_stream) { m_MyStream = my_stream; } \ TStreamType* m_MyStream #endif /* UTIL___ROW_READER__INL */
34.901015
84
0.575885
[ "vector" ]
a57e18cada3186a84566b43e04b766818c30d041
22,544
cc
C++
Code/Components/Analysis/analysis/current/patternmatching/Matcher.cc
rtobar/askapsoft
6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
1
2020-06-18T08:37:43.000Z
2020-06-18T08:37:43.000Z
Code/Components/Analysis/analysis/current/patternmatching/Matcher.cc
ATNF/askapsoft
d839c052d5c62ad8a511e58cd4b6548491a6006f
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
null
null
null
Code/Components/Analysis/analysis/current/patternmatching/Matcher.cc
ATNF/askapsoft
d839c052d5c62ad8a511e58cd4b6548491a6006f
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
null
null
null
/// @file /// /// Provides base class for handling the matching of lists of points /// /// @copyright (c) 2007 CSIRO /// Australia Telescope National Facility (ATNF) /// Commonwealth Scientific and Industrial Research Organisation (CSIRO) /// PO Box 76, Epping NSW 1710, Australia /// atnf-enquiries@csiro.au /// /// This file is part of the ASKAP software distribution. /// /// The ASKAP software distribution is free software: you can redistribute it /// and/or modify it under the terms of the GNU General Public License as /// published by the Free Software Foundation; either version 2 of the License, /// or (at your option) any later version. /// /// 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, write to the Free Software /// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /// /// @author Matthew Whiting <matthew.whiting@csiro.au> /// #include <askap_analysis.h> #include <askap/AskapLogging.h> #include <askap/AskapError.h> #include <patternmatching/Matcher.h> #include <patternmatching/Triangle.h> #include <patternmatching/Point.h> #include <patternmatching/MatchingUtilities.h> #include <Common/ParameterSet.h> #include <duchamp/fitsHeader.hh> #include <iostream> #include <iomanip> #include <fstream> #include <vector> #include <utility> #include <string> #include <math.h> ///@brief Where the log messages go. ASKAP_LOGGER(logger, ".matching"); using namespace askap; namespace askap { namespace analysis { namespace matching { Matcher::Matcher() { itsMeanDx = 0.; itsMeanDy = 0.; itsRmsDx = 0.; itsRmsDy = 0.; } Matcher::~Matcher() { } Matcher::Matcher(const Matcher &m) { operator=(m); } Matcher& Matcher::operator=(const Matcher &m) { if (this == &m) return *this; itsFITShead = m.itsFITShead; itsSrcFile = m.itsSrcFile; itsRefFile = m.itsRefFile; itsRA = m.itsRA; itsDec = m.itsDec; itsSrcPosType = m.itsSrcPosType; itsRefPosType = m.itsRefPosType; itsRadius = m.itsRadius; itsFluxMethod = m.itsFluxMethod; itsFluxUseFit = m.itsFluxUseFit; itsSrcPixList = m.itsSrcPixList; itsRefPixList = m.itsRefPixList; itsSrcTriList = m.itsSrcTriList; itsRefTriList = m.itsRefTriList; itsMatchingTriList = m.itsMatchingTriList; itsMatchingPixList = m.itsMatchingPixList; itsEpsilon = m.itsEpsilon; itsTrimSize = m.itsTrimSize; itsMeanDx = m.itsMeanDx; itsMeanDy = m.itsMeanDy; itsRmsDx = m.itsRmsDx; itsRmsDy = m.itsRmsDy; itsNumMatch1 = m.itsNumMatch1; itsNumMatch2 = m.itsNumMatch2; itsSenseMatch = m.itsSenseMatch; itsOutputBestFile = m.itsOutputBestFile; itsOutputMissFile = m.itsOutputMissFile; return *this; } Matcher::Matcher(const LOFAR::ParameterSet& parset) { itsSrcFile = parset.getString("srcFile", ""); itsRefFile = parset.getString("refFile", ""); itsFluxMethod = parset.getString("fluxMethod", "peak"); itsFluxUseFit = parset.getString("fluxUseFit", "best"); itsRA = parset.getString("RA", "00:00:00"); itsDec = parset.getString("Dec", "00:00:00"); itsSrcPosType = parset.getString("srcPosType", "deg"); itsRefPosType = parset.getString("refPosType", "deg"); itsRadius = parset.getDouble("radius", -1.); itsEpsilon = parset.getDouble("epsilon", defaultEpsilon); itsTrimSize = parset.getInt16("trimsize", matching::maxSizePointList); itsMeanDx = 0.; itsMeanDy = 0.; itsRmsDx = 0.; itsRmsDy = 0.; itsOutputBestFile = parset.getString("matchFile", "matches.txt"); itsOutputMissFile = parset.getString("missFile", "misses.txt"); } //**************************************************************// void Matcher::setHeader(duchamp::FitsHeader &head) { itsFITShead = head; } //**************************************************************// void Matcher::readLists() { bool filesOK = true; if (itsSrcFile == "") { ASKAPTHROW(AskapError, "srcFile not defined. Cannot get pixel list!"); filesOK = false; } if (itsRefFile == "") { ASKAPTHROW(AskapError, "refFile not defined. Cannot get pixel list!"); filesOK = false; } if (filesOK) { std::ifstream fsrc(itsSrcFile.c_str()); if (!fsrc.is_open()) { ASKAPTHROW(AskapError, "srcFile (" << itsSrcFile << ") not valid. Error opening file."); } std::ifstream fref(itsRefFile.c_str()); if (!fref.is_open()) { ASKAPTHROW(AskapError, "refFile (" << itsRefFile << ") not valid. Error opening file."); } itsSrcPixList = getSrcPixList(fsrc, itsFITShead, itsRA, itsDec, itsSrcPosType, itsRadius, itsFluxMethod, itsFluxUseFit); ASKAPLOG_INFO_STR(logger, "Size of source pixel list = " << itsSrcPixList.size()); itsRefPixList = getPixList(fref, itsFITShead, itsRA, itsDec, itsRefPosType, itsRadius); ASKAPLOG_INFO_STR(logger, "Size of reference pixel list = " << itsRefPixList.size()); } else { ASKAPLOG_WARN_STR(logger, "Not reading any pixel lists!"); } } //**************************************************************// void Matcher::fixRefList(std::vector<float> beam) { // ASKAPLOG_INFO_STR(logger, "Beam info being used: maj=" << beam[0]*3600. // << ", min=" << beam[1]*3600. << ", pa=" << beam[2]); // float a1 = std::max(beam[0] * 3600., beam[1] * 3600.); // float b1 = std::min(beam[0] * 3600., beam[1] * 3600.); // float pa1 = beam[2]; // float d1 = a1 * a1 - b1 * b1; // std::vector<Point>::iterator pix = itsRefPixList.begin(); // for (; pix < itsRefPixList.end(); pix++) { // double a2 = std::max(pix->majorAxis(), pix->minorAxis()); // double b2 = std::min(pix->majorAxis(), pix->minorAxis()); // double pa2 = pix->PA(); // double d2 = a2 * a2 - b2 * b2; // double d0sq = d1 * d1 + d2 * d2 + 2. * d1 * d2 * cos(2.*(pa1 - pa2)); // double d0 = sqrt(d0sq); // double a0sq = 0.5 * (a1 * a1 + b1 * b1 + a2 * a2 + b2 * b2 + d0); // double b0sq = 0.5 * (a1 * a1 + b1 * b1 + a2 * a2 + b2 * b2 - d0); // pix->setMajorAxis(sqrt(a0sq)); // pix->setMinorAxis(sqrt(b0sq)); // if (d0sq > 0) { // // leave out normalisation by d0, since we will take ratios to get tan2pa0 // double sin2pa0 = (d1 * sin(2.*pa1) + d2 * sin(2.*pa2)); // double cos2pa0 = (d1 * cos(2.*pa1) + d2 * cos(2.*pa2)); // double pa0 = atan(fabs(sin2pa0 / cos2pa0)); // // atan of the absolute value of the ratio returns a value between 0 and 90 degrees. // // Need to correct the value of l according to the correct quandrant it is in. // // This is worked out using the signs of sinl and cosl // if (sin2pa0 > 0) { // if (cos2pa0 > 0) pa0 = pa0; // else pa0 = M_PI - pa0; // } else { // if (cos2pa0 > 0) pa0 = 2.*M_PI - pa0; // else pa0 = M_PI + pa0; // } // pix->setPA(pa0 / 2.); // } else pix->setPA(0.); // } } //**************************************************************// void Matcher::setTriangleLists() { std::vector<Point> srclist = trimList(itsSrcPixList, itsTrimSize); ASKAPLOG_INFO_STR(logger, "Trimmed src list to " << srclist.size() << " points"); // std::vector<Point> reflist = trimList(itsRefPixList, itsTrimSize); // ASKAPLOG_INFO_STR(logger, "Trimmed ref list to " << reflist.size() << " points"); itsSrcTriList = getTriList(srclist); ASKAPLOG_INFO_STR(logger, "Performing crude match on reference list"); std::vector<Point> newreflist = crudeMatchList(itsRefPixList, itsSrcPixList, 5); // ASKAPLOG_INFO_STR(logger, "Performing crude match on trimmed reference list"); // std::vector<Point> newreflist = crudeMatchList(itsRefPixList, srclist,5); ASKAPLOG_INFO_STR(logger, "Now have reference list of size " << newreflist.size() << " points"); newreflist = trimList(newreflist, itsTrimSize); ASKAPLOG_INFO_STR(logger, "Reference list trimmed to " << newreflist.size() << " points"); // itsRefTriList = getTriList(reflist); itsRefTriList = getTriList(newreflist); itsMatchingTriList = matchLists(itsSrcTriList, itsRefTriList, itsEpsilon); trimTriList(itsMatchingTriList); ASKAPLOG_INFO_STR(logger, "Found " << itsMatchingTriList.size() << " matches\n"); } //**************************************************************// void Matcher::findMatches() { itsNumMatch1 = 0; if (itsMatchingTriList.size() > 0) { itsMatchingPixList = vote(itsMatchingTriList); itsNumMatch1 = itsMatchingPixList.size(); ASKAPLOG_INFO_STR(logger, "After voting, have found " << itsMatchingPixList.size() << " matching points\n"); itsSenseMatch = (itsMatchingTriList[0].first.isClockwise() == itsMatchingTriList[0].second.isClockwise()); if (itsSenseMatch) { ASKAPLOG_INFO_STR(logger, "The two lists have the same sense."); } else { ASKAPLOG_INFO_STR(logger, "The two lists have the opposite sense."); } } } //**************************************************************// void Matcher::findOffsets() { std::vector<double> dx(itsNumMatch1, 0.), dy(itsNumMatch1, 0.); for (int i = 0; i < itsNumMatch1; i++) { if (itsSenseMatch) { dx[i] = itsMatchingPixList[i].first.x() - itsMatchingPixList[i].second.x(); dy[i] = itsMatchingPixList[i].first.y() - itsMatchingPixList[i].second.y(); } else { dx[i] = itsMatchingPixList[i].first.x() - itsMatchingPixList[i].second.x(); dy[i] = itsMatchingPixList[i].first.y() + itsMatchingPixList[i].second.y(); } } itsMeanDx = itsMeanDy = 0.; for (int i = 0; i < itsNumMatch1; i++) { itsMeanDx += dx[i]; itsMeanDy += dy[i]; } itsMeanDx /= double(itsNumMatch1); itsMeanDy /= double(itsNumMatch1); itsRmsDx = itsRmsDy = 0.; for (int i = 0; i < itsNumMatch1; i++) { itsRmsDx += (dx[i] - itsMeanDx) * (dx[i] - itsMeanDx); itsRmsDy += (dy[i] - itsMeanDy) * (dy[i] - itsMeanDy); } itsRmsDx = sqrt(itsRmsDx / (double(itsNumMatch1 - 1))); itsRmsDy = sqrt(itsRmsDy / (double(itsNumMatch1 - 1))); std::stringstream ss; ss.setf(std::ios::fixed); ss << "Offsets between the two are dx = " << itsMeanDx << " +- " << itsRmsDx << " dy = " << itsMeanDy << " +- " << itsRmsDy; ASKAPLOG_INFO_STR(logger, ss.str()); } //**************************************************************// void Matcher::addNewMatches() { if (itsNumMatch1 > 0) { this->rejectMultipleMatches(); const float matchRadius = 3.; std::vector<Point>::iterator src, ref; std::vector<std::pair<Point, Point> >::iterator match; for (src = itsSrcPixList.begin(); src < itsSrcPixList.end(); src++) { bool isMatch = false; match = itsMatchingPixList.begin(); for (; match < itsMatchingPixList.end() && !isMatch; match++) { isMatch = (src->ID() == match->first.ID()); } if (!isMatch) { float minOffset = 0.; int minRef = -1; for (ref = itsRefPixList.begin(); ref < itsRefPixList.end(); ref++) { float offset = hypot(src->x() - ref->x() - itsMeanDx, src->y() - ref->y() - itsMeanDy); if (offset < matchRadius * itsEpsilon) { if ((minRef == -1) || (offset < minOffset)) { minOffset = offset; minRef = int(ref - itsRefPixList.begin()); } } } if (minRef >= 0) { // there was a match within errors ref = itsRefPixList.begin() + minRef; std::pair<Point, Point> newMatch(*src, *ref); itsMatchingPixList.push_back(newMatch); } } } this->rejectMultipleMatches(); itsNumMatch2 = itsMatchingPixList.size(); } } //**************************************************************// void Matcher::rejectMultipleMatches() { if (itsMatchingPixList.size() < 2) return; std::vector<std::pair<Point, Point> >::iterator alice, bob; alice = itsMatchingPixList.begin(); while (alice < itsMatchingPixList.end() - 1) { bool bobGone = false; bool aliceGone = false; bob = alice + 1; while (bob < itsMatchingPixList.end() && !aliceGone) { if (alice->second.ID() == bob->second.ID()) { // alice & bob have the same reference source float df_alice, df_bob; // if (itsFluxMethod == "integrated") { // df_alice = alice->first.stuff().flux() - alice->second.flux(); // df_bob = bob->first.stuff().flux() - bob->second.flux(); // } else { df_alice = alice->first.flux() - alice->second.flux(); df_bob = bob->first.flux() - bob->second.flux(); // } if (fabs(df_alice) < fabs(df_bob)) { // delete bob itsMatchingPixList.erase(bob); bobGone = true; } else { // delete alice itsMatchingPixList.erase(alice); aliceGone = true; } } if (!bobGone) bob++; else bobGone = false; } if (!aliceGone) alice++; } } //**************************************************************// void Matcher::outputMatches() { std::ofstream fout(itsOutputBestFile.c_str()); std::vector<std::pair<Point, Point> >::iterator match; int prec = 3; for (match = itsMatchingPixList.begin(); match < itsMatchingPixList.end(); match++) { // if (itsFluxMethod == "integrated") { // need to swap around since we have initially stored peak flux in object. // float tmpflux; // tmpflux = match->first.stuff().flux(); // match->first.stuff().setFlux(match->first.flux()); // match->first.setFlux(tmpflux); // } int newprec = int(ceil(log10(1. / match->first.flux()))) + 1; prec = std::max(prec, newprec); newprec = int(ceil(log10(1. / match->first.flux()))) + 1; prec = std::max(prec, newprec); } fout.setf(std::ios::fixed); int ct = 0; char matchType; for (match = itsMatchingPixList.begin(); match < itsMatchingPixList.end(); match++) { if (ct++ < itsNumMatch1) matchType = '1'; else matchType = '2'; fout << matchType << "\t" << match->first.ID() << " " << match->second.ID() << " " << std::setw(8) << std::setprecision(3) << match->first.sep(match->second) << "\n"; // fout << matchType << "\t" // << "[" << match->first.ID() << "]\t" // << std::setw(10) << std::setprecision(3) << match->first.x() << " " // << std::setw(10) << std::setprecision(3) << match->first.y() << " " // << std::setw(10) << std::setprecision(8) << match->first.flux() << " " // << std::setw(10) << std::setprecision(3) << match->first.majorAxis() << " " // << std::setw(10) << std::setprecision(3) << match->first.minorAxis() << " " // << std::setw(10) << std::setprecision(3) << match->first.PA() << " " // << std::setw(10) << std::setprecision(3) << match->first.alpha() << " " // << std::setw(10) << std::setprecision(3) << match->first.beta() << " " // << std::setw(10) << match->first.stuff() << "\t" // << "[" << match->second.ID() << "]\t" // << std::setw(10) << std::setprecision(3) << match->second.x() << " " // << std::setw(10) << std::setprecision(3) << match->second.y() << " " // << std::setw(10) << std::setprecision(8) << match->second.flux() << " " // << std::setw(10) << std::setprecision(3) << match->second.majorAxis() << " " // << std::setw(10) << std::setprecision(3) << match->second.minorAxis() << " " // << std::setw(10) << std::setprecision(3) << match->second.PA() << "\t" // << std::setw(10) << std::setprecision(3) << match->second.alpha() << " " // << std::setw(10) << std::setprecision(3) << match->second.beta() << " " // << std::setw(8) << std::setprecision(3) << match->first.sep(match->second) << " " // << std::setw(8) << std::setprecision(8) << match->first.flux() - match->second.flux() << " " // << std::setw(8) << std::setprecision(6) << (match->first.flux() - match->second.flux()) / match->second.flux() << "\n"; } fout.close(); } //**************************************************************// void Matcher::outputMisses() { std::ofstream fout(itsOutputMissFile.c_str()); fout.setf(std::ios::fixed); std::vector<Point>::iterator pt; std::vector<std::pair<Point, Point> >::iterator match; // Stuff nullstuff(0., 0., 0., 0, 0, 0, 0, 0.); for (pt = itsRefPixList.begin(); pt < itsRefPixList.end(); pt++) { bool isMatch = false; match = itsMatchingPixList.begin(); for (; match < itsMatchingPixList.end() && !isMatch; match++) { isMatch = (pt->ID() == match->second.ID()); } if (!isMatch) { fout << "R\t[" << pt->ID() << "]\t" << std::setw(10) << std::setprecision(3) << pt->x() << " " << std::setw(10) << std::setprecision(3) << pt->y() << " " << std::setw(10) << std::setprecision(8) << pt->flux() << " " // << std::setw(10) << std::setprecision(3) << pt->majorAxis() << " " // << std::setw(10) << std::setprecision(3) << pt->minorAxis() << " " // << std::setw(10) << std::setprecision(3) << pt->PA() << " " // << std::setw(10) << nullstuff << "\n"; } } for (pt = itsSrcPixList.begin(); pt < itsSrcPixList.end(); pt++) { bool isMatch = false; match = itsMatchingPixList.begin(); for (; match < itsMatchingPixList.end() && !isMatch; match++) { isMatch = (pt->ID() == match->first.ID()); } if (!isMatch) { fout << "S\t[" << pt->ID() << "]\t" << std::setw(10) << std::setprecision(3) << pt->x() << " " << std::setw(10) << std::setprecision(3) << pt->y() << " " << std::setw(10) << std::setprecision(8) << pt->flux() << " " // << std::setw(10) << std::setprecision(3) << pt->majorAxis() << " " // << std::setw(10) << std::setprecision(3) << pt->minorAxis() << " " // << std::setw(10) << std::setprecision(3) << pt->PA() << " " // << std::setw(10) << pt->stuff() << "\n"; } } } void Matcher::outputSummary() { std::ofstream fout; // Stuff nullstuff(0., 0., 0., 0, 0, 0, 0, 0.); std::vector<Point>::iterator pt; std::vector<std::pair<Point, Point> >::iterator mpair; Point match; fout.open("match-summary-sources.txt"); for (pt = itsSrcPixList.begin(); pt < itsSrcPixList.end(); pt++) { bool isMatch = false; for (mpair = itsMatchingPixList.begin(); mpair < itsMatchingPixList.end() && !isMatch; mpair++) { isMatch = (pt->ID() == mpair->first.ID()); if (isMatch) { match = mpair->second; } } std::string matchID = isMatch ? match.ID() : "---"; fout << pt->ID() << " " << matchID << "\t" << std::setw(10) << std::setprecision(3) << pt->x() << " " << std::setw(10) << std::setprecision(3) << pt->y() << " " << std::setw(10) << std::setprecision(8) << pt->flux() << " " // << std::setw(10) << std::setprecision(3) << pt->majorAxis() << " " // << std::setw(10) << std::setprecision(3) << pt->minorAxis() << " " // << std::setw(10) << std::setprecision(3) << pt->PA() << " " // << std::setw(10) << pt->stuff() << "\n"; } fout.close(); fout.open("match-summary-reference.txt"); for (pt = itsRefPixList.begin(); pt < itsRefPixList.end(); pt++) { bool isMatch = false; for (mpair = itsMatchingPixList.begin(); mpair < itsMatchingPixList.end() && !isMatch; mpair++) { isMatch = (pt->ID() == mpair->second.ID()); if (isMatch) { match = mpair->first; } } std::string matchID = isMatch ? match.ID() : "---"; fout << pt->ID() << " " << matchID << "\t" << std::setw(10) << std::setprecision(3) << pt->x() << " " << std::setw(10) << std::setprecision(3) << pt->y() << " " << std::setw(10) << std::setprecision(8) << pt->flux() << " " // << std::setw(10) << std::setprecision(3) << pt->majorAxis() << " " // << std::setw(10) << std::setprecision(3) << pt->minorAxis() << " " // << std::setw(10) << std::setprecision(3) << pt->PA() << " " // << std::setw(10) << nullstuff << "\n"; } fout.close(); } } } }
36.302738
135
0.512952
[ "object", "vector" ]
a57f83d1a34a1ef2d8604caae8e60d6f02bd1176
1,616
cpp
C++
src/yars/physics/bullet/Actuator.cpp
kzahedi/YARS
48d9fe4178d699fba38114d3b299a228da41293d
[ "MIT" ]
4
2017-08-05T03:33:21.000Z
2021-11-08T09:15:42.000Z
src/yars/physics/bullet/Actuator.cpp
kzahedi/YARS
48d9fe4178d699fba38114d3b299a228da41293d
[ "MIT" ]
null
null
null
src/yars/physics/bullet/Actuator.cpp
kzahedi/YARS
48d9fe4178d699fba38114d3b299a228da41293d
[ "MIT" ]
1
2019-03-24T08:35:25.000Z
2019-03-24T08:35:25.000Z
#include <yars/physics/bullet/Actuator.h> #include <yars/configuration/YarsConfiguration.h> #include <yars/util/YarsErrorHandler.h> #include <sstream> Actuator::Actuator(string name, string source, string destination, Robot *robot) { _robot = robot; if (source == "") { YarsErrorHandler *e = YarsErrorHandler::instance(); (*e) << "In " << name << ": You need to define a source" << endl; YarsErrorHandler::push(); } _sourceObject = __find(source); _destinationObject = __find(destination); if (_sourceObject == NULL) { YarsErrorHandler *e = YarsErrorHandler::instance(); (*e) << "In " << name << ": Source " << source << " was not found."; YarsErrorHandler::push(); } } Object *Actuator::__find(string name) { for (std::vector<Object *>::iterator o = _robot->o_begin(); o != _robot->o_end(); o++) { if ((*o)->type() == DATA_OBJECT_COMPOSITE) { for (std::vector<Object *>::iterator co = (*o)->begin(); co != (*o)->end(); co++) { if ((*co)->data()->name() == name) return (*co); } } else { if ((*o)->data()->name() == name) return (*o); } } if (name != "") { YarsErrorHandler *e = YarsErrorHandler::instance(); (*e) << "Actuators: Cannot find object \"" << name << "\"" << endl; YarsErrorHandler::push(); } return NULL; } vector<btTypedConstraint *>::iterator Actuator::c_begin() { return _constraints.begin(); } vector<btTypedConstraint *>::iterator Actuator::c_end() { return _constraints.end(); } int Actuator::c_size() { return (int)_constraints.size(); }
22.760563
88
0.593441
[ "object", "vector" ]
a58222722d2c577f75b2412a2957cfa2f812e358
1,445
cpp
C++
shared_interest.cpp
karanjakhar/technical_training
a22092ef233d76362e89f92fc17b546dfac7aa5d
[ "Apache-2.0" ]
null
null
null
shared_interest.cpp
karanjakhar/technical_training
a22092ef233d76362e89f92fc17b546dfac7aa5d
[ "Apache-2.0" ]
null
null
null
shared_interest.cpp
karanjakhar/technical_training
a22092ef233d76362e89f92fc17b546dfac7aa5d
[ "Apache-2.0" ]
null
null
null
int sharedInterests(int friends_nodes, int friends_edges, std::vector<int> friends_from, std::vector<int> friends_to, std::vector<int> friends_weight) { map<int,vector<int>>mp; for(int i = 0; i < friends_edges; i++){ mp[friends_from[i]].push_back(friends_weight[i]); mp[friends_to[i]].push_back(friends_weight[i]); } map<pair<int,int>,int>common; set<int>s; set<int>s1,s2; for(int i = 1; i <= friends_nodes; i++){ for(int j = i+1; j <= friends_nodes; j++){ for(int p = 0; p < mp[i].size(); p++){ s1.insert(mp[i][p]); s.insert(mp[i][p]); } for(int p = 0; p < mp[j].size(); p++){ s2.insert(mp[j][p]); s.insert(mp[j][p]); } common[make_pair(i,j)] = (s1.size()+s2.size()) - s.size(); s1.clear(); s2.clear(); s.clear(); } } int max=-1,max_value=-1; for(int i = 1; i <= friends_nodes; i++){ for(int j = i+1; j <= friends_nodes; j++){ if(common[make_pair(i,j)] == max ){ if(max_value < i*j){ max_value = i*j; } } else if(common[make_pair(i,j)] > max ){ max = common[make_pair(i,j)]; max_value = i*j; } } } return max_value; }
30.744681
152
0.442907
[ "vector" ]
a58c5acc7d728860e650f924689a252104cd70c1
918
cpp
C++
test/test_high-side-switch.cpp
NikhitaR-IFX/high-side-switch
37ce95da04f228a36885c14e2b2046e7137e1996
[ "MIT" ]
6
2020-09-17T14:34:56.000Z
2022-01-26T02:41:15.000Z
test/test_high-side-switch.cpp
NikhitaR-IFX/high-side-switch
37ce95da04f228a36885c14e2b2046e7137e1996
[ "MIT" ]
3
2020-05-19T12:03:07.000Z
2021-09-09T10:53:51.000Z
test/test_high-side-switch.cpp
NikhitaR-IFX/high-side-switch
37ce95da04f228a36885c14e2b2046e7137e1996
[ "MIT" ]
3
2021-08-30T13:13:55.000Z
2022-01-26T02:41:11.000Z
#include <gtest/gtest.h> #include <gmock/gmock.h> #include "../src/corelib/high-side-switch.h" using ::testing::Return; //using ::testing::Matcher; // using ::testing::NotNull; // using ::testing::Sequence; using ::testing::_; /** * Class High Side Switch Test Suite */ class HSSwitchAPI: public ::testing::Test { public: HighSideSwitch hsswitch; void setUp() { } void TearDown() { } }; TEST_F(HSSwitchAPI, checkBegin) { ASSERT_EQ(hsswitch.begin(),0); } /** * Mock Utility Class */ // class MockUtility: public Utility // { // public: // MOCK_METHOD(char, someUtilFunction, (char a),(override)); // }; // TEST_F(ArduinoAPI, checkSomeFunctionError) // { // MockUtility mocku; // EXPECT_CALL(mocku, someUtilFunction(_)) // .WillOnce(Return((char)'e')); // ASSERT_EQ(object.someFunction(mocku),1); // }
16.690909
68
0.600218
[ "object" ]
a58d9836bf28e898f9f22efef7e21bb586321aa5
2,292
cpp
C++
C++/1563. StoneGameV.cpp
nizD/LeetCode-Solutions
7f4ca37bab795e0d6f9bfd9148a8fe3b62aa5349
[ "MIT" ]
263
2020-10-05T18:47:29.000Z
2022-03-31T19:44:46.000Z
C++/1563. StoneGameV.cpp
nizD/LeetCode-Solutions
7f4ca37bab795e0d6f9bfd9148a8fe3b62aa5349
[ "MIT" ]
1,264
2020-10-05T18:13:05.000Z
2022-03-31T23:16:35.000Z
C++/1563. StoneGameV.cpp
nizD/LeetCode-Solutions
7f4ca37bab795e0d6f9bfd9148a8fe3b62aa5349
[ "MIT" ]
760
2020-10-05T18:22:51.000Z
2022-03-29T06:06:20.000Z
/* Probelem Statement: There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue. In each round of the game, Alice divides the row into two non-empty rows (i.e. left row and right row), then Bob calculates the value of each row which is the sum of the values of all the stones in this row. Bob throws away the row which has the maximum value, and Alice's score increases by the value of the remaining row. If the value of the two rows are equal, Bob lets Alice decide which row will be thrown away. The next round starts with the remaining row. The game ends when there is only one stone remaining. Alice's is initially zero. Return the maximum score that Alice can obtain. Approach: Recursion + Dynamic Programming - We will need two pointers do indicate our current range of numbers that we can split - After the split, the two rows should not be empty - We will discard the row with the larger sum - What if both of the rows have the same sum? - We will want to pick the row that will give us a higher score - We will need a quick way to find the sum within a range of indices - We can create a prefix sum array to quickly retrieve the sum within 2 indices */ class Solution { public: int dp[501][501]; int solve(vector<int>& arr,int start,int end,int sum){ if(start>=end){return 0;} if(dp[start][end]!=-1){return dp[start][end];} int maxi =0,add=0; for(int i=start;i<=end;i++){ add += arr[i]; if(add==sum-add){ maxi = max(maxi,max(add + solve(arr,start,i,add),sum-add + solve(arr,i+1,end,add))); // When the sum of both row are equal , we can go anyways. } else if(add<sum-add){ maxi = max(maxi,add + solve(arr,start,i,add)); // when sum of second row is maximum } else maxi = max(maxi,sum-add+solve(arr,i+1,end,sum - add)); // when sum of first row is maximum } return dp[start][end] = maxi; } int stoneGameV(vector<int>& stoneValue) { int i=0,n = stoneValue.size(),sum=0; memset(dp,-1,sizeof(dp)); for(i=0;i<n;i++){ sum += stoneValue[i]; } return solve(stoneValue,0,n-1,sum); } };
47.75
462
0.655323
[ "vector" ]
a590b3523c48e1f92093d6b30fd98364849434fd
2,597
cpp
C++
codeforces/gym/2019-2020 ACM-ICPC Pacific Northwest Regional Contest/m.cpp
tysm/cpsols
262212646203e516d1706edf962290de93762611
[ "MIT" ]
4
2020-10-05T19:24:10.000Z
2021-07-15T00:45:43.000Z
codeforces/gym/2019-2020 ACM-ICPC Pacific Northwest Regional Contest/m.cpp
tysm/cpsols
262212646203e516d1706edf962290de93762611
[ "MIT" ]
null
null
null
codeforces/gym/2019-2020 ACM-ICPC Pacific Northwest Regional Contest/m.cpp
tysm/cpsols
262212646203e516d1706edf962290de93762611
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define eb emplace_back #define ii pair<int, int> #define OK (cerr << "OK" << endl) #define debug(x) cerr << #x " = " << (x) << endl #define ff first #define ss second #define int long long #define tt tuple<int, int, int> #define all(x) x.begin(), x.end() #define Matrix vector<vector<int>> #define Mat(n, m, v) vector<vector<int>>(n, vector<int>(m, v)) #define endl '\n' constexpr int INF = 2e18; constexpr int MOD = 1e9 + 7; constexpr int MAXN = 1e3 + 3; char lo[2][2] = {{'/', '\\'}, {'\\', '/'}}; int vis[MAXN][MAXN]; char mat[MAXN][MAXN]; int dx[] = {0, 0, -1, 1}; int dy[] = {1, -1, 0, 0}; int n; int m; void dfs(int x, int y) { vis[x][y] = true; for (int k = 0; k < 4; ++k) { int nx = dx[k] + x, ny = dy[k] + y; if (0 <= nx && nx < n && 0 <= ny && ny < m && mat[nx][ny] == '.' && !vis[nx][ny]) { dfs(nx, ny); } } if(x+1 < n and y+1 < m and mat[x+1][y+1] == '.' and !vis[x+1][y+1]){ if(!(mat[x+1][y] == '/' and mat[x][y+1] == '/')) dfs(x+1, y+1); } if(x+1 < n and y-1 >= 0 and mat[x+1][y-1] == '.' and !vis[x+1][y-1]){ if(!(mat[x+1][y] == '\\' and mat[x][y-1] == '\\')) dfs(x+1, y-1); } if(x-1 >= 0 and y-1 >= 0 and mat[x-1][y-1] == '.' and !vis[x-1][y-1]){ if(!(mat[x-1][y] == '/' and mat[x][y-1] == '/')) dfs(x-1, y-1); } if(x-1 >= 0 and y+1 < m and mat[x-1][y+1] == '.' and !vis[x-1][y+1]){ if(!(mat[x-1][y] == '\\' and mat[x][y+1] == '\\')) dfs(x-1, y+1); } } void solve() { cin >> n; cin >> m; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { cin >> mat[i][j]; } } for(int i=0; i<n; ++i){ if(mat[i][0] == '.' and !vis[i][0]) dfs(i, 0); if(mat[i][m-1] == '.' and !vis[i][m-1]) dfs(i, m-1); } for(int j=0; j<m; ++j){ if(mat[0][j] == '.' and !vis[0][j]) dfs(0, j); if(mat[n-1][j] == '.' and !vis[n-1][j]) dfs(n-1, j); } int ans = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (mat[i][j] == '.' && !vis[i][j]) { dfs(i, j); ++ans; } else if (i + 1 < n && j + 1 < m) { bool ok = true; for (int k = 0; k < 2; ++k) for (int l = 0; l < 2; ++l) if (mat[i + k][j + l] != lo[k][l]) ok = false; ans += ok; } } } cout << ans << endl; } signed main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t = 1; #ifdef MULTIPLE_TEST_CASES cin >> t; #endif while (t--) solve(); }
22.982301
72
0.41625
[ "vector" ]
a5920f489a1bb8b1862a5d5a26fd75f674f0fb40
857
cpp
C++
128. Longest Consecutive Sequence.cpp
rajeev-ranjan-au6/Leetcode_Cpp
f64cd98ab96ec110f1c21393f418acf7d88473e8
[ "MIT" ]
3
2020-12-30T00:29:59.000Z
2021-01-24T22:43:04.000Z
128. Longest Consecutive Sequence.cpp
rajeevranjancom/Leetcode_Cpp
f64cd98ab96ec110f1c21393f418acf7d88473e8
[ "MIT" ]
null
null
null
128. Longest Consecutive Sequence.cpp
rajeevranjancom/Leetcode_Cpp
f64cd98ab96ec110f1c21393f418acf7d88473e8
[ "MIT" ]
null
null
null
class Solution { public: int longestConsecutive(vector<int>& nums) { int maxlen = 0; unordered_map<int, int>m; for(auto x: nums){ if(m[x]) continue; int left = m[x - 1]; int right = m[x + 1]; m[x + right] = m[x - left] = m[x] = left + right + 1; maxlen = max(maxlen, m[x]); } return maxlen; } }; class Solution { public: int longestConsecutive(vector<int>& nums) { unordered_map<int, int>m; int res = 0; for (int& x: nums) { if (m[x]) { continue; } int l = m[x - 1]; int r = m[x + 1]; m[x] = l + r + 1; m[x - l] = l + r + 1; m[x + r] = l + r + 1; res = max(res, m[x]); } return res; } };
23.805556
65
0.392065
[ "vector" ]
a5999e984f0ef1ecfed28b288e17dd8cdfd8b23a
27,024
cpp
C++
src/blockchain/txpool.cpp
metabasenet/metabasenet
e9bc89b22c11981bcf1d71b63b9b66df3a4e54e1
[ "MIT" ]
null
null
null
src/blockchain/txpool.cpp
metabasenet/metabasenet
e9bc89b22c11981bcf1d71b63b9b66df3a4e54e1
[ "MIT" ]
null
null
null
src/blockchain/txpool.cpp
metabasenet/metabasenet
e9bc89b22c11981bcf1d71b63b9b66df3a4e54e1
[ "MIT" ]
null
null
null
// Copyright (c) 2021-2022 The MetabaseNet developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "txpool.h" #include <algorithm> #include <boost/range/adaptor/reversed.hpp> #include <deque> using namespace std; using namespace hcode; namespace metabasenet { ////////////////////////////// // CForkTxPool bool CForkTxPool::GetSaveTxList(vector<std::pair<uint256, CTransaction>>& vTx) { CPooledTxLinkSetBySequenceNumber& idxTx = setTxLinkIndex.get<1>(); for (const auto& kv : idxTx) { const CTransaction& tx = *static_cast<CTransaction*>(kv.ptx); vTx.push_back(make_pair(kv.txid, tx)); } return true; } bool CForkTxPool::AddPooledTx(const uint256& txid, const CTransaction& tx, const int64 nTxSeq) { auto it = mapTx.insert(make_pair(txid, CPooledTx(tx, nTxSeq))).first; if (it == mapTx.end()) { return false; } if (!setTxLinkIndex.insert(CPooledTxLink(&it->second)).second) { mapTx.erase(it); return false; } if (!tx.from.IsNull()) { mapDestTx[tx.from].insert(txid); } if (!tx.to.IsNull() && tx.from != tx.to) { mapDestTx[tx.to].insert(txid); } return true; } bool CForkTxPool::RemovePooledTx(const uint256& txid, const CTransaction& tx, const bool fInvalidTx) { auto it = mapTx.find(txid); if (it != mapTx.end()) { auto removeDestTx = [&](const CDestination& dest, const uint256& txidc) -> bool { auto mt = mapDestTx.find(dest); if (mt == mapDestTx.end()) { return false; } mt->second.erase(txidc); if (mt->second.empty()) { mapDestTx.erase(dest); mapDestState.erase(dest); } return true; }; if (!tx.from.IsNull()) { if (!removeDestTx(tx.from, txid)) { StdError("CForkTxPool", "Remove Pooled Tx: Remove dest tx error, from: %s, txid: %s", tx.from.ToString().c_str(), txid.GetHex().c_str()); return false; } } if (!tx.to.IsNull() && tx.to != tx.from) { if (!removeDestTx(tx.to, txid)) { StdError("CForkTxPool", "Remove Pooled Tx: Remove dest tx error, to: %s, txid: %s", tx.to.ToString().c_str(), txid.GetHex().c_str()); return false; } } setTxLinkIndex.erase(txid); mapTx.erase(it); if (mapTx.empty() && nTxSequenceNumber > 0xFFFFFFFFFFFFFFFL) { nTxSequenceNumber = INIT_TX_SEQUENCE_NUMBER; } } else { if (fInvalidTx) { StdError("CForkTxPool", "Remove Pooled Tx: Remove invalud tx error, from: %s, txid: %s", tx.from.ToString().c_str(), txid.GetHex().c_str()); return false; } if (!tx.from.IsNull()) { vector<pair<uint256, CPooledTx>> vDelTx; auto mt = mapDestTx.find(tx.from); if (mt != mapDestTx.end()) { for (const uint256& txidn : mt->second) { auto nt = mapTx.find(txidn); if (nt != mapTx.end()) { const CPooledTx& txn = nt->second; if (txn.from == tx.from && txn.nTxNonce >= tx.nTxNonce) { vDelTx.push_back(make_pair(txidn, txn)); } } } } for (const auto& txs : vDelTx) { const uint256& txids = txs.first; const CDestination& destFrom = txs.second.from; const uint64 nTxNonce = txs.second.nTxNonce; if (!RemovePooledTx(txids, txs.second, true)) { StdLog("CForkTxPool", "Remove Pooled Tx: Remove invalid tx fail, from: %s, txid: %s", destFrom.ToString().c_str(), txids.GetHex().c_str()); return false; } StdLog("CForkTxPool", "Remove Pooled Tx: Remove invalid tx success, nonce: %ld, count: %ld, from: %s, txid: %s", nTxNonce, vDelTx.size(), destFrom.ToString().c_str(), txids.GetHex().c_str()); } } } return true; } Errno CForkTxPool::AddTx(const uint256& txid, const CTransaction& tx) { if (mapTx.find(txid) != mapTx.end()) { StdLog("CForkTxPool", "Add Tx: Tx exist, from: %s, txid: %s", tx.from.ToString().c_str(), txid.GetHex().c_str()); return ERR_ALREADY_HAVE; } if (tx.from.IsNull() || tx.to.IsNull()) { StdLog("CForkTxPool", "Add Tx: From or to address is null, from: %s, to: %s, txid: %s", tx.from.ToString().c_str(), tx.to.ToString().c_str(), txid.GetHex().c_str()); return ERR_TRANSACTION_INPUT_INVALID; } CDestState stateFrom; if (!GetDestState(tx.from, stateFrom)) { StdLog("CForkTxPool", "Add Tx: Get from state fail, from: %s, txid: %s", tx.from.ToString().c_str(), txid.GetHex().c_str()); return ERR_MISSING_PREV; } CAddressContext ctxtAddressFrom; CAddressContext ctxtAddressTo; if (!GetAddressContext(tx.from, ctxtAddressFrom)) { StdLog("CForkTxPool", "Add Tx: Get from address context fail, from: %s, txid: %s", tx.from.ToString().c_str(), txid.GetHex().c_str()); return ERR_MISSING_PREV; } if (tx.to.data != 0 && !GetAddressContext(tx.to, ctxtAddressTo)) { bytes btTempData; if (tx.to.IsTemplate() && tx.GetTxData(CTransaction::DF_TEMPLATEDATA, btTempData)) { ctxtAddressTo = CAddressContext(CTemplateAddressContext(std::string(), std::string(), btTempData), CBlock::GetBlockHeightByHash(hashLastBlock) + 1); } else { StdLog("CForkTxPool", "Add Tx: Get to address context fail, to: %s, txid: %s", tx.to.ToString().c_str(), txid.GetHex().c_str()); return ERR_MISSING_PREV; } } std::map<uint256, CAddressContext> mapBlockAddress; mapBlockAddress.insert(make_pair(tx.from.data, ctxtAddressFrom)); if (tx.to.data != 0) { mapBlockAddress.insert(make_pair(tx.to.data, ctxtAddressTo)); } Errno err; if ((err = pCoreProtocol->VerifyTransaction(tx, hashLastBlock, CBlock::GetBlockHeightByHash(hashLastBlock) + 1, stateFrom, mapBlockAddress)) != OK) { StdLog("CForkTxPool", "Add Tx: Verify transaction fail, txid: %s", txid.GetHex().c_str()); return err; } if (!AddPooledTx(txid, tx, nTxSequenceNumber++)) { StdLog("CForkTxPool", "Add Tx: Add pooled tx fail, txid: %s", txid.GetHex().c_str()); return ERR_TRANSACTION_INVALID; } if (tx.from == tx.to) { stateFrom.nBalance += tx.nAmount; } else if (tx.to.data != 0) { CDestState stateTo; if (!GetDestState(tx.to, stateTo)) { stateTo.SetNull(); } stateTo.nBalance += tx.nAmount; SetDestState(tx.to, stateTo); } stateFrom.nTxNonce++; stateFrom.nBalance -= (tx.nAmount + tx.GetTxFee()); SetDestState(tx.from, stateFrom); return OK; } bool CForkTxPool::Exists(const uint256& txid) { return (mapTx.count(txid) > 0); } bool CForkTxPool::CheckTxNonce(const CDestination& destFrom, const uint64 nTxNonce) { CDestState state; if (!GetDestState(destFrom, state)) { return false; } if (state.nTxNonce < nTxNonce) { return false; } return true; } std::size_t CForkTxPool::GetTxCount() const { return mapTx.size(); } bool CForkTxPool::GetTx(const uint256& txid, CTransaction& tx) const { auto it = mapTx.find(txid); if (it != mapTx.end()) { tx = static_cast<CTransaction>(it->second); return true; } return false; } uint64 CForkTxPool::GetDestNextTxNonce(const CDestination& dest) { CDestState state; if (!GetDestState(dest, state)) { return 0; } return state.GetNextTxNonce(); } uint64 CForkTxPool::GetCertTxNextNonce(const CDestination& dest) { int nTxCount = 0; auto mt = mapDestTx.find(dest); if (mt != mapDestTx.end()) { for (const uint256& txid : mt->second) { auto nt = mapTx.find(txid); if (nt != mapTx.end()) { const CPooledTx& tx = nt->second; if (tx.nType == CTransaction::TX_CERT && tx.from == dest) { nTxCount++; } } } } if (nTxCount >= CONSENSUS_ENROLL_INTERVAL) { StdLog("CForkTxPool", "Get Cert Tx Next Nonce: nTxCount >= CONSENSUS_ENROLL_INTERVAL, nTxCount: %d, dest: %s", nTxCount, dest.ToString().c_str()); return 0; } CDestState state; if (!GetDestState(dest, state)) { StdLog("CForkTxPool", "Get Cert Tx Next Nonce: Get dest state fail, dest: %s", dest.ToString().c_str()); return 0; } return state.GetNextTxNonce(); } bool CForkTxPool::FetchArrangeBlockTx(const uint256& hashPrev, const int64 nBlockTime, const size_t nMaxSize, vector<CTransaction>& vtx, uint256& nTotalTxFee) { if (hashPrev != hashLastBlock) { return true; } map<CDestination, int> mapVoteCert; if (!pBlockChain->GetDelegateCertTxCount(hashPrev, mapVoteCert)) { StdError("CForkTxPool", "Fetch Arrange Block Tx: Get delegate cert tx count fail, prev: %s", hashPrev.GetHex().c_str()); return false; } set<CDestination> setDisable; size_t nTotalSize = 0; CPooledTxLinkSetBySequenceNumber& idxTx = setTxLinkIndex.get<1>(); for (const auto& kv : idxTx) { const CTransaction& tx = *static_cast<CTransaction*>(kv.ptx); if (setDisable.find(tx.from) != setDisable.end()) { continue; } if (tx.nTimeStamp > nBlockTime) { setDisable.insert(tx.from); continue; } if (tx.nType == CTransaction::TX_CERT) { auto it = mapVoteCert.find(tx.from); if (it != mapVoteCert.end()) { if (it->second <= 0) { setDisable.insert(tx.from); continue; } } else { it = mapVoteCert.insert(make_pair(tx.from, CONSENSUS_ENROLL_INTERVAL * 2)).first; } it->second--; } if (nTotalSize + kv.ptx->nSerializeSize > nMaxSize) { break; } vtx.push_back(tx); nTotalSize += kv.ptx->nSerializeSize; nTotalTxFee += kv.ptx->GetTxFee(); } return true; } bool CForkTxPool::SynchronizeBlockChain(const CBlockChainUpdate& update) { int64 nTxCount = 0; for (const CBlockEx& block : update.vBlockRemove) { nTxCount += block.vtx.size(); } int64 nRemoveTxSeq = GetMinTxSequenceNumber() - nTxCount; uint256 hashBranchBlock; set<CDestination> setNewDest; for (const CBlockEx& block : boost::adaptors::reverse(update.vBlockRemove)) { if (hashBranchBlock == 0) { hashBranchBlock = block.hashPrev; } for (const auto& tx : block.vtx) { if (!tx.IsNoMintRewardTx()) { if (!AddSynchronizeTx(hashBranchBlock, tx.GetHash(), tx, nRemoveTxSeq++, setNewDest)) { StdLog("CForkTxPool", "Synchronize Block Chain: Add synchronize tx fail, remove block: %s, txid: %s", block.GetHash().GetHex().c_str(), tx.GetHash().GetHex().c_str()); return false; } } } } for (const CBlockEx& block : update.vBlockAddNew) { for (const auto& tx : block.vtx) { if (!tx.IsNoMintRewardTx()) { const uint256 txid = tx.GetHash(); if (!RemovePooledTx(txid, tx, false)) { StdLog("CForkTxPool", "Synchronize Block Chain: Remove pooled tx fail, new block: %s, txid: %s", block.GetHash().GetHex().c_str(), txid.GetHex().c_str()); return false; } } } } hashLastBlock = update.hashLastBlock; nLastBlockTime = update.nLastBlockTime; return true; } void CForkTxPool::ListTx(vector<pair<uint256, size_t>>& vTxPool) { CPooledTxLinkSetBySequenceNumber& idxTx = setTxLinkIndex.get<1>(); for (const auto& kv : idxTx) { vTxPool.push_back(make_pair(kv.txid, kv.ptx->nSerializeSize)); } } void CForkTxPool::ListTx(vector<uint256>& vTxPool) { CPooledTxLinkSetBySequenceNumber& idxTx = setTxLinkIndex.get<1>(); for (const auto& kv : idxTx) { vTxPool.push_back(kv.txid); } } bool CForkTxPool::ListTx(const CDestination& dest, vector<CTxInfo>& vTxPool, const int64 nGetOffset, const int64 nGetCount) { uint64 nTxSeq = 0; CPooledTxLinkSetBySequenceNumber& idxTx = setTxLinkIndex.get<1>(); for (const auto& kv : idxTx) { if (nTxSeq >= nGetOffset) { CTxInfo txInfo; const CTransaction& tx = *static_cast<CTransaction*>(kv.ptx); txInfo.txid = kv.txid; txInfo.hashFork = tx.hashFork; txInfo.nTxType = tx.nType; txInfo.nTimeStamp = tx.nTimeStamp; txInfo.nTxNonce = tx.nTxNonce; txInfo.nBlockHeight = -1; txInfo.nTxSeq = nTxSeq; txInfo.destFrom = tx.from; txInfo.destTo = tx.to; txInfo.nAmount = tx.nAmount; txInfo.nGasPrice = tx.nGasPrice; txInfo.nGas = tx.nGasLimit; txInfo.nSize = kv.ptx->nSerializeSize; vTxPool.push_back(txInfo); if (vTxPool.size() >= nGetCount) { break; } } nTxSeq++; } return true; } void CForkTxPool::GetDestBalance(const CDestination& dest, uint64& nTxNonce, uint256& nAvail, uint256& nUnconfirmedIn, uint256& nUnconfirmedOut) { CDestState state; if (!GetDestState(dest, state)) { state.SetNull(); } nTxNonce = state.nTxNonce; nAvail = state.nBalance; nUnconfirmedIn = 0; nUnconfirmedOut = 0; auto mt = mapDestTx.find(dest); if (mt != mapDestTx.end()) { for (const uint256& txid : mt->second) { auto nt = mapTx.find(txid); if (nt != mapTx.end()) { const CPooledTx& tx = nt->second; if (tx.from == dest) { nUnconfirmedOut += (tx.nAmount + tx.GetTxFee()); } if (tx.to == dest) { nUnconfirmedIn += tx.nAmount; } } } } } bool CForkTxPool::GetAddressContext(const CDestination& dest, CAddressContext& ctxtAddress) { if (dest.IsPubKey()) { ctxtAddress.nType = CDestination::PREFIX_PUBKEY; ctxtAddress.btData.clear(); ctxtAddress.nBlockNumber = CBlock::GetBlockHeightByHash(hashLastBlock) + 1; return true; } else if (dest.IsContract()) { ctxtAddress.nType = CDestination::PREFIX_CONTRACT; ctxtAddress.btData.clear(); ctxtAddress.nBlockNumber = CBlock::GetBlockHeightByHash(hashLastBlock) + 1; return true; } else if (dest.IsTemplate()) { if (pBlockChain->RetrieveAddressContext(hashFork, hashLastBlock, dest.data, ctxtAddress)) { if (ctxtAddress.nType != dest.prefix) { StdLog("CForkTxPool", "Get Address Context: Address type error, db address type: %d, query address type: %d, dest: %s", ctxtAddress.nType, dest.prefix, dest.ToString().c_str()); return false; } return true; } auto mt = mapDestTx.find(dest); if (mt != mapDestTx.end()) { for (const uint256& txid : mt->second) { auto nt = mapTx.find(txid); if (nt != mapTx.end()) { const CPooledTx& tx = nt->second; if (tx.to == dest) { bytes btTempData; if (tx.GetTxData(CTransaction::DF_TEMPLATEDATA, btTempData)) { ctxtAddress = CAddressContext(CTemplateAddressContext(std::string(), std::string(), btTempData), CBlock::GetBlockHeightByHash(hashLastBlock) + 1); return true; } } } } } } return false; } //////////////////////////////////// bool CForkTxPool::GetDestState(const CDestination& dest, CDestState& state) { auto it = mapDestState.find(dest); if (it == mapDestState.end()) { if (!pBlockChain->RetrieveDestState(hashFork, hashLastBlock, dest, state)) { return false; } } else { state = it->second; } return true; } void CForkTxPool::SetDestState(const CDestination& dest, const CDestState& state) { mapDestState[dest] = state; } int64 CForkTxPool::GetMinTxSequenceNumber() { CPooledTxLinkSetBySequenceNumber& idxTx = setTxLinkIndex.get<1>(); auto it = idxTx.begin(); if (it != idxTx.end()) { return it->nSequenceNumber; } return nTxSequenceNumber; } bool CForkTxPool::AddSynchronizeTx(const uint256& hashBranchBlock, const uint256& txid, const CTransaction& tx, const int64 nTxSeq, std::set<CDestination>& setNewDest) { auto isNewDest = [&](const CDestination& dest) -> bool { if (setNewDest.count(dest) > 0) { return true; } if (mapDestState.find(dest) == mapDestState.end()) { setNewDest.insert(dest); return true; } return false; }; auto getDestState = [&](const CDestination& dest) -> CDestState& { auto it = mapDestState.find(dest); if (it == mapDestState.end()) { CDestState state; if (!pBlockChain->RetrieveDestState(hashFork, hashBranchBlock, dest, state)) { state.SetNull(); } it = mapDestState.insert(make_pair(dest, state)).first; } return it->second; }; if (!AddPooledTx(txid, tx, nTxSeq)) { return false; } if (isNewDest(tx.from)) { CDestState& stateFrom = getDestState(tx.from); stateFrom.nTxNonce++; stateFrom.nBalance -= (tx.nAmount + tx.GetTxFee()); } if (isNewDest(tx.to)) { getDestState(tx.to).nBalance += tx.nAmount; } return true; } ////////////////////////////// // CTxPool CTxPool::CTxPool() { pCoreProtocol = nullptr; pBlockChain = nullptr; } CTxPool::~CTxPool() { } bool CTxPool::HandleInitialize() { if (!GetObject("coreprotocol", pCoreProtocol)) { Error("Failed to request coreprotocol"); return false; } if (!GetObject("blockchain", pBlockChain)) { Error("Failed to request blockchain"); return false; } return true; } void CTxPool::HandleDeinitialize() { pCoreProtocol = nullptr; pBlockChain = nullptr; } bool CTxPool::HandleInvoke() { if (!datTxPool.Initialize(Config()->pathData)) { Error("Failed to initialize txpool data"); return false; } if (!LoadData()) { Error("Failed to load txpool data"); return false; } return true; } void CTxPool::HandleHalt() { if (!SaveData()) { Error("Failed to save txpool data"); } //Clear(); } bool CTxPool::LoadData() { boost::unique_lock<boost::shared_mutex> wlock(rwAccess); std::map<uint256, CForkStatus> mapForkStatus; pBlockChain->GetForkStatus(mapForkStatus); for (const auto& kv : mapForkStatus) { mapForkPool.insert(make_pair(kv.first, CForkTxPool(pCoreProtocol, pBlockChain, kv.first, kv.second.hashLastBlock, kv.second.nLastBlockTime))); } std::map<uint256, std::vector<std::pair<uint256, CTransaction>>> mapSaveTx; if (!datTxPool.Load(mapSaveTx)) { Error("Load Data failed"); return false; } for (const auto& kv : mapSaveTx) { const uint256& hashFork = kv.first; CForkTxPool* pFork = GetForkTxPool(hashFork); if (pFork == nullptr) { Error("Get fork tx pool failed"); return false; } for (const auto& vd : kv.second) { const uint256& txid = vd.first; const CTransaction& tx = vd.second; if (pFork->AddTx(txid, tx) != OK) { StdLog("CTxPool", "LoadData: Add tx fail, txid: %s", txid.GetHex().c_str()); } } } return true; } bool CTxPool::SaveData() { boost::shared_lock<boost::shared_mutex> rlock(rwAccess); std::map<uint256, std::vector<std::pair<uint256, CTransaction>>> mapSaveTx; for (auto& kv : mapForkPool) { kv.second.GetSaveTxList(mapSaveTx[kv.first]); } return datTxPool.Save(mapSaveTx); } CForkTxPool* CTxPool::GetForkTxPool(const uint256& hashFork) { auto it = mapForkPool.find(hashFork); if (it == mapForkPool.end()) { CBlockStatus status; if (!pBlockChain->GetLastBlockStatus(hashFork, status)) { return nullptr; } it = mapForkPool.insert(make_pair(hashFork, CForkTxPool(pCoreProtocol, pBlockChain, hashFork, status.hashBlock, status.nBlockTime))).first; } return &(it->second); } /////////////////////////////////////////////////////////// bool CTxPool::Exists(const uint256& hashFork, const uint256& txid) { boost::shared_lock<boost::shared_mutex> rlock(rwAccess); auto it = mapForkPool.find(hashFork); if (it != mapForkPool.end()) { return it->second.Exists(txid); } return false; } bool CTxPool::CheckTxNonce(const uint256& hashFork, const CDestination& destFrom, const uint64 nTxNonce) { boost::shared_lock<boost::shared_mutex> rlock(rwAccess); auto it = mapForkPool.find(hashFork); if (it != mapForkPool.end()) { return it->second.CheckTxNonce(destFrom, nTxNonce); } return false; } size_t CTxPool::Count(const uint256& hashFork) const { boost::shared_lock<boost::shared_mutex> rlock(rwAccess); auto it = mapForkPool.find(hashFork); if (it != mapForkPool.end()) { return it->second.GetTxCount(); } return 0; } Errno CTxPool::Push(const CTransaction& tx) { boost::unique_lock<boost::shared_mutex> wlock(rwAccess); uint256 txid = tx.GetHash(); if (tx.IsRewardTx()) { StdError("CTxPool", "Push: tx is mint, txid: %s", txid.GetHex().c_str()); return ERR_TRANSACTION_INVALID; } CForkTxPool* pFork = GetForkTxPool(tx.hashFork); if (pFork == nullptr) { StdError("CTxPool", "Push: Get fork tx pool failed, txid: %s", txid.GetHex().c_str()); return ERR_TRANSACTION_INVALID; } return pFork->AddTx(txid, tx); } bool CTxPool::Get(const uint256& txid, CTransaction& tx) const { boost::shared_lock<boost::shared_mutex> rlock(rwAccess); for (const auto& kv : mapForkPool) { if (kv.second.GetTx(txid, tx)) { return true; } } return false; } void CTxPool::ListTx(const uint256& hashFork, vector<pair<uint256, size_t>>& vTxPool) { boost::shared_lock<boost::shared_mutex> rlock(rwAccess); auto it = mapForkPool.find(hashFork); if (it != mapForkPool.end()) { it->second.ListTx(vTxPool); } } void CTxPool::ListTx(const uint256& hashFork, vector<uint256>& vTxPool) { boost::shared_lock<boost::shared_mutex> rlock(rwAccess); auto it = mapForkPool.find(hashFork); if (it != mapForkPool.end()) { it->second.ListTx(vTxPool); } } bool CTxPool::ListTx(const uint256& hashFork, const CDestination& dest, vector<CTxInfo>& vTxPool, const int64 nGetOffset, const int64 nGetCount) { boost::shared_lock<boost::shared_mutex> rlock(rwAccess); auto it = mapForkPool.find(hashFork); if (it != mapForkPool.end()) { return it->second.ListTx(dest, vTxPool, nGetOffset, nGetCount); } return false; } bool CTxPool::FetchArrangeBlockTx(const uint256& hashFork, const uint256& hashPrev, const int64 nBlockTime, const size_t nMaxSize, vector<CTransaction>& vtx, uint256& nTotalTxFee) { boost::shared_lock<boost::shared_mutex> rlock(rwAccess); CForkTxPool* pFork = GetForkTxPool(hashFork); if (pFork) { return pFork->FetchArrangeBlockTx(hashPrev, nBlockTime, nMaxSize, vtx, nTotalTxFee); } return false; } bool CTxPool::SynchronizeBlockChain(const CBlockChainUpdate& update) { boost::unique_lock<boost::shared_mutex> wlock(rwAccess); CForkTxPool* pFork = GetForkTxPool(update.hashFork); if (pFork) { return pFork->SynchronizeBlockChain(update); } return false; } void CTxPool::AddDestDelegate(const CDestination& destDeleage) { } int CTxPool::GetDestTxpoolTxCount(const CDestination& dest) { return 0; } void CTxPool::GetDestBalance(const uint256& hashFork, const CDestination& dest, uint64& nTxNonce, uint256& nAvail, uint256& nUnconfirmedIn, uint256& nUnconfirmedOut) { boost::shared_lock<boost::shared_mutex> rlock(rwAccess); CForkTxPool* pFork = GetForkTxPool(hashFork); if (pFork) { pFork->GetDestBalance(dest, nTxNonce, nAvail, nUnconfirmedIn, nUnconfirmedOut); } } uint64 CTxPool::GetDestNextTxNonce(const uint256& hashFork, const CDestination& dest) { boost::shared_lock<boost::shared_mutex> rlock(rwAccess); CForkTxPool* pFork = GetForkTxPool(hashFork); if (pFork) { return pFork->GetDestNextTxNonce(dest); } return 0; } uint64 CTxPool::GetCertTxNextNonce(const CDestination& dest) { boost::shared_lock<boost::shared_mutex> rlock(rwAccess); CForkTxPool* pFork = GetForkTxPool(pCoreProtocol->GetGenesisBlockHash()); if (pFork) { return pFork->GetCertTxNextNonce(dest); } return 0; } } // namespace metabasenet
28.566596
174
0.568273
[ "vector" ]
a59b7c4b258c78a1cf323a96554f8a69327f0df0
3,435
cpp
C++
Board.cpp
Orya-s/Ariel_CPP_Ex2
b5300705533a138a9ed5c13b18d584036db76c7e
[ "MIT" ]
null
null
null
Board.cpp
Orya-s/Ariel_CPP_Ex2
b5300705533a138a9ed5c13b18d584036db76c7e
[ "MIT" ]
null
null
null
Board.cpp
Orya-s/Ariel_CPP_Ex2
b5300705533a138a9ed5c13b18d584036db76c7e
[ "MIT" ]
null
null
null
#include "Board.hpp" #include <iostream> #include <stdexcept> #include <algorithm> using namespace std; namespace ariel { string const message; void Board::post(uint row, uint col, Direction direction, const string &message) { // adding more vectors aka lines if (board.size() <= row + message.size()) { int vecNum = 0; uint size = message.size() + 1; if(direction == Direction::Horizontal){ vecNum = (int)(row - board.size() + 1); } else { vecNum = (int)(row - board.size() + message.size() + 1); } while (vecNum > 0){ vector<char> v(size); fill(v.begin(), v.end(), '_'); board.push_back(v); vecNum--; } } // if didn't need more lines but the line isn't long enough if (board.at(row).size() <= col + message.size()) { for (uint i = board.at(row).size(); i <= col + message.size() +1; i++) { board.at(row).push_back('_'); } } // if the message is vertical - make sure all lines of the message are long enough if (direction == Direction::Vertical){ for (uint i = row; i < row+message.size()+1; i++) { for (uint j = board.at(i).size(); j <= col + message.size() +1; j++) { board.at(i).push_back('_'); } } } // posting the message ulong index = 0; if (direction == Direction::Horizontal) { for (uint j = col; j < col+message.size(); j++) { board.at(row).at(j) = message.at(index++); } } else{ for (uint i = row; i < row+message.size(); i++) { board.at(i).at(col) = message.at(index++); } } } std::string Board::read(uint row, uint col, Direction direction, uint length) { string ans; // if the reading location is beyond the board's current size if (board.size() <= row) { for (int i = 0; i < length; i++) { ans += "_"; } return ans; } if (board.at(row).size() <= col) { for (int i = 0; i < length; i++) { ans += "_"; } return ans; } // reading the line if (direction == Direction::Horizontal) { for (uint j = col; j < col+length && j < board.at(row).size(); j++) { ans += board.at(row).at(j); } } else{ for (uint i = row; i < row+length && i < board.size(); i++) { ans += board.at(i).at(col); } } // if part of the reading is beyond the board's current size while (ans.size() < length) { ans += '_'; } return ans; } void Board::show() { for(uint i = 0; i < board.size(); i++) { for(uint j = 0; j < board.at(i).size(); j++) { cout << board.at(i).at(j) << " "; } cout << endl; } } }
26.835938
91
0.406405
[ "vector" ]
a59d789eb8b2457d0c7f45ce68d4c59dfa0dc57e
810
cpp
C++
tests/word-break-ii-test.cpp
Red-Li/leetcode
908d579f4dbf63a0099b6aae909265300ead46c5
[ "Apache-2.0" ]
null
null
null
tests/word-break-ii-test.cpp
Red-Li/leetcode
908d579f4dbf63a0099b6aae909265300ead46c5
[ "Apache-2.0" ]
null
null
null
tests/word-break-ii-test.cpp
Red-Li/leetcode
908d579f4dbf63a0099b6aae909265300ead46c5
[ "Apache-2.0" ]
null
null
null
/** * @file word-break-ii-test.cpp * @brief * @author Red Li * @version * @date 2014-11-27 */ #include <sstream> #include <gtest/gtest.h> #include <unordered_set> using namespace std; namespace word_break_ii{ #define NAMESPACE #include "word-break-ii.hpp" } using namespace word_break_ii; class WordBreakIITest : public testing::Test { public: static void SetUpTestCase() { } static void TearDownTestCase() { } virtual void SetUp() { } virtual void TearDown() { } }; TEST_F(WordBreakIITest, test) { unordered_set<string> dict; dict.insert("cat"); dict.insert("cats"); dict.insert("and"); dict.insert("sand"); dict.insert("dog"); Solution sol; vector<string> res = sol.wordBreak("catsanddog", dict); }
14.210526
59
0.623457
[ "vector" ]
a5a12e3af7b22e7993d3f8d7ac77b144340ff9b2
9,080
cpp
C++
irohad/synchronizer/impl/synchronizer_impl.cpp
kuvaldini/iroha
f6a739743f8c5d80bc341c1e286b56fe484e5daa
[ "Apache-2.0" ]
1
2021-05-18T09:02:45.000Z
2021-05-18T09:02:45.000Z
irohad/synchronizer/impl/synchronizer_impl.cpp
kuvaldini/iroha
f6a739743f8c5d80bc341c1e286b56fe484e5daa
[ "Apache-2.0" ]
6
2021-05-20T15:07:14.000Z
2021-05-21T08:50:11.000Z
irohad/synchronizer/impl/synchronizer_impl.cpp
kuvaldini/iroha
f6a739743f8c5d80bc341c1e286b56fe484e5daa
[ "Apache-2.0" ]
1
2021-05-13T09:20:23.000Z
2021-05-13T09:20:23.000Z
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #include "synchronizer/impl/synchronizer_impl.hpp" #include <utility> #include "ametsuchi/block_query_factory.hpp" #include "ametsuchi/command_executor.hpp" #include "ametsuchi/mutable_storage.hpp" #include "common/bind.hpp" #include "common/result.hpp" #include "common/visitor.hpp" #include "interfaces/common_objects/string_view_types.hpp" #include "interfaces/iroha_internal/block.hpp" #include "logger/logger.hpp" using namespace shared_model::interface::types; namespace iroha { namespace synchronizer { SynchronizerImpl::SynchronizerImpl( std::unique_ptr<iroha::ametsuchi::CommandExecutor> command_executor, std::shared_ptr<validation::ChainValidator> validator, std::shared_ptr<ametsuchi::MutableFactory> mutable_factory, std::shared_ptr<ametsuchi::BlockQueryFactory> block_query_factory, std::shared_ptr<network::BlockLoader> block_loader, logger::LoggerPtr log) : command_executor_(std::move(command_executor)), validator_(std::move(validator)), mutable_factory_(std::move(mutable_factory)), block_query_factory_(std::move(block_query_factory)), block_loader_(std::move(block_loader)), log_(std::move(log)) {} SynchronizationEvent SynchronizerImpl::processOutcome( consensus::GateObject object) { log_->info("processing consensus outcome"); auto process_reject = [this](auto outcome_type, const auto &msg) { assert(msg.ledger_state->top_block_info.height + 1 == msg.round.block_round); return SynchronizationEvent{outcome_type, msg.round, msg.ledger_state}; }; return visit_in_place( object, [this](const consensus::PairValid &msg) { assert(msg.ledger_state->top_block_info.height + 1 == msg.round.block_round); return this->processNext(msg); }, [this](const consensus::VoteOther &msg) { assert(msg.ledger_state->top_block_info.height + 1 == msg.round.block_round); return this->processDifferent(msg, msg.round.block_round); }, [&](const consensus::ProposalReject &msg) { return process_reject(SynchronizationOutcomeType::kReject, msg); }, [&](const consensus::BlockReject &msg) { return process_reject(SynchronizationOutcomeType::kReject, msg); }, [&](const consensus::AgreementOnNone &msg) { return process_reject(SynchronizationOutcomeType::kNothing, msg); }, [this](const consensus::Future &msg) { assert(msg.ledger_state->top_block_info.height + 1 < msg.round.block_round); // we do not know the ledger state for round n, so we // cannot claim that the bunch of votes we got is a // commit certificate and hence we do not know if the // block n is committed and cannot require its // acquisition. return this->processDifferent(msg, msg.round.block_round - 1); }); } ametsuchi::CommitResult SynchronizerImpl::downloadAndCommitMissingBlocks( const shared_model::interface::types::HeightType start_height, const shared_model::interface::types::HeightType target_height, const PublicKeyCollectionType &public_keys) { auto storage_result = getStorage(); if (iroha::expected::hasError(storage_result)) { return std::move(storage_result).assumeError(); } auto storage = std::move(storage_result).assumeValue(); shared_model::interface::types::HeightType my_height = start_height; // TODO andrei 17.10.18 IR-1763 Add delay strategy for loading blocks using namespace iroha::expected; for (const auto &public_key : public_keys) { while (true) { bool peer_ok = false; log_->debug( "trying to download blocks from {} to {} from peer with key {}", my_height + 1, target_height, public_key); auto maybe_reader = block_loader_->retrieveBlocks( my_height, PublicKeyHexStringView{public_key}); if (hasError(maybe_reader)) { log_->warn( "failed to retrieve blocks starting from {} from peer {}: {}", my_height, public_key, maybe_reader.assumeError()); continue; } auto block_var = maybe_reader.assumeValue()->read(); for (auto maybe_block = std::get_if< std::shared_ptr<const shared_model::interface::Block>>( &block_var); maybe_block; block_var = maybe_reader.assumeValue()->read(), maybe_block = std::get_if< std::shared_ptr<const shared_model::interface::Block>>( &block_var)) { if (not(peer_ok = validator_->validateAndApply(*maybe_block, *storage))) { break; } my_height = (*maybe_block)->height(); } if (auto error = std::get_if<std::string>(&block_var)) { log_->warn("failed to retrieve block: {}", *error); } if (my_height >= target_height) { return mutable_factory_->commit(std::move(storage)); } if (not peer_ok) { // if the last block did not apply or we got no new blocks from this // peer we should switch to next peer break; } } } return expected::makeError( "Failed to download and commit any blocks from given peers"); } iroha::expected::Result<std::unique_ptr<ametsuchi::MutableStorage>, std::string> SynchronizerImpl::getStorage() { return mutable_factory_->createMutableStorage(command_executor_); } SynchronizationEvent SynchronizerImpl::processNext( const consensus::PairValid &msg) { log_->info("at handleNext"); const auto notify = [this, &msg](std::shared_ptr<const iroha::LedgerState> &&ledger_state) { return SynchronizationEvent{SynchronizationOutcomeType::kCommit, msg.round, std::move(ledger_state)}; }; if (mutable_factory_->preparedCommitEnabled()) { auto result = mutable_factory_->commitPrepared(msg.block); if (iroha::expected::hasValue(result)) { return notify(std::move(result).assumeValue()); } log_->error("Error committing prepared block: {}", result.assumeError()); } auto commit_result = getStorage() | [&](auto &&storage) -> ametsuchi::CommitResult { if (storage->apply(msg.block)) { return mutable_factory_->commit(std::move(storage)); } else { return "Block failed to apply."; } }; return std::move(commit_result) .match( [&notify](auto &&ledger_state) { return notify(std::move(ledger_state.value)); }, [this, &msg](const auto &error) { this->log_->error("Failed to commit: {}", error.error); return SynchronizationEvent{SynchronizationOutcomeType::kError, msg.round, msg.ledger_state}; }); } SynchronizationEvent SynchronizerImpl::processDifferent( const consensus::Synchronizable &msg, shared_model::interface::types::HeightType required_height) { log_->info("at handleDifferent"); auto commit_result = downloadAndCommitMissingBlocks( msg.ledger_state->top_block_info.height, required_height, msg.public_keys); return commit_result.match( [this, &msg](auto &value) { auto &ledger_state = value.value; assert(ledger_state); const auto new_height = ledger_state->top_block_info.height; return SynchronizationEvent{SynchronizationOutcomeType::kCommit, new_height != msg.round.block_round ? consensus::Round{new_height, 0} : msg.round, std::move(ledger_state)}; }, [this, &msg](const auto &error) { log_->error("Synchronization failed: {}", error.error); return SynchronizationEvent{SynchronizationOutcomeType::kError, msg.round, msg.ledger_state}; }); } } // namespace synchronizer } // namespace iroha
40.355556
80
0.582599
[ "object" ]
a5a3892d9050489546337061cd7568cac357f6ea
14,228
hpp
C++
inference-engine/src/inference_engine/low_precision_transformations/network_helper.hpp
giulio1979/dldt
e7061922066ccefc54c8dae6e3215308ce9559e1
[ "Apache-2.0" ]
1
2021-07-30T17:03:50.000Z
2021-07-30T17:03:50.000Z
inference-engine/src/inference_engine/low_precision_transformations/network_helper.hpp
Dipet/dldt
b2140c083a068a63591e8c2e9b5f6b240790519d
[ "Apache-2.0" ]
null
null
null
inference-engine/src/inference_engine/low_precision_transformations/network_helper.hpp
Dipet/dldt
b2140c083a068a63591e8c2e9b5f6b240790519d
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2018-2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include <cmath> #include <memory> #include <string> #include <vector> #include <unordered_set> #include "cnn_network_impl.hpp" #include "low_precision_transformations/common/dequantization_details.hpp" #include "low_precision_transformations/transformation_context.hpp" #include "low_precision_transformations/quantization_details.hpp" namespace InferenceEngine { namespace details { /** * @brief CNNNetworkHelper class encapsulates manipulations with CNN Network. */ class INFERENCE_ENGINE_API_CLASS(CNNNetworkHelper) { public: static CNNLayerPtr getLayer(const ICNNNetwork& network, const std::string& layerName); static Blob::Ptr makeNewBlobPtr(const TensorDesc& desc); static void invertFakeQuantize(const CNNLayer& fakeQuantize); static void updateBlobs(CNNLayer& layer, const std::string& blobName, float value); static void updateBlobs(const CNNLayer& quantizeLayer, int constLayerIndex, float value); static void updateBlobs(const CNNLayer& quantizeLayer, int constLayerIndex, const std::vector<float>& values); static void updateBlobs(CNNLayer& layer, const std::string& blobName, const std::vector<float>& values); // return true if at least one child uses layer on weights static bool onWeights(const CNNLayer& layer); static size_t getIndex(const CNNLayer& layer); static std::vector<CNNLayerPtr> transformFakeQuantizeToConst( TransformationContext& context, const CNNLayerPtr fakeQuantize, const Blob::Ptr weights, const std::string& constLayerName); static void setOutDataPrecision(const CNNLayer& layer, const Precision& precision); static void setOutDataPrecision(const std::vector<CNNLayerPtr>& layers, const Precision& precision); static void setOutDataPrecision( const CNNLayer& beginLayer, const size_t branchWithEndBeforeLayer, const CNNLayer& endBeforeLayer, const Precision& precision); static bool IsChild( const std::vector<CNNLayerPtr>& children, const std::unordered_set<std::string>& layerTypes, const std::unordered_set<std::string>& ignoreLayerTypes = {}); static size_t getOutputChannelsCount(const CNNLayer& layer, bool isOnWeights = false); static std::vector<CNNLayerPtr> getLayers(const CNNLayer& parent, const CNNLayer& child); static Blob::Ptr getBlob(CNNLayerPtr layer, const std::string& blobName); static Blob::Ptr getBlob(CNNLayer* layer, const std::string& blobName); static std::shared_ptr<float> getFloatData(const CNNLayerPtr& layer, const std::string& blobName); static std::shared_ptr<float> getFloatData(const Blob::Ptr& srcBlob); static bool isBlobPrecisionSupported(const Precision precision); static void fillBlobByFP32(Blob::Ptr& dstBlob, float value); static void fillBlobByFP32(Blob::Ptr& dstBlob, const float* srcData); static void fillBlobByFP32(const CNNLayerPtr& layer, const std::string& blobName, const float* srcData); static std::shared_ptr<float> convertFloatData(const float* srcData, const size_t dataSize, const Precision precision); static CNNLayerPtr getParent( const CNNLayer& layer, const size_t index = 0, const std::string& ignoreLayerType = ""); static std::vector<CNNLayerPtr> getParents( const CNNLayer& layer, const std::string& exceptionLayerName = ""); static std::vector<CNNLayerPtr> getParentsRecursivelyExceptTypes( const CNNLayer& layer, const std::unordered_set<std::string>& exceptionLayerTypes = {}, const int portIndex = -1); static size_t getInputChannelsCount(const CNNLayer& layer); static size_t getParamOutput(const CNNLayer& layer); static size_t getKernelSize(const CNNLayer& layer); static void renameLayer(ICNNNetwork& net, const std::string& currentName, const std::string& newName); static CNNLayerPtr addLayer( TransformationContext& context, const CNNLayerPtr parent, const CNNLayerPtr child, const CNNLayerPtr newLayer); static void replaceLayer(TransformationContext& context, const CNNLayerPtr source, const CNNLayerPtr target); static CNNLayerPtr addScaleShiftBetween( TransformationContext& context, const CNNLayerPtr parent, const CNNLayerPtr child, const DequantizationDetails& dequantizationDetails, const std::string& name = ""); static CNNLayerPtr addConstBetween( ICNNNetwork& net, const CNNLayerPtr layer1, const CNNLayerPtr layer2, const Blob::Ptr customBlob, const std::string& name); static void addLayerToCNNNetworkAfterData( DataPtr parentOutData, CNNLayer::Ptr layer, const std::string& nextLayerName, ICNNNetwork& net); static void fillInScaleShift(ScaleShiftLayer* layer, const size_t channels, const float* scales, const float* shifts); static std::vector<CNNLayerPtr> getChildren(const CNNLayer& layer, const std::string& exceptionLayerName = ""); static std::vector<CNNLayerPtr> getChildrenRecursivelyExceptTypes( const CNNLayer& layer, const std::unordered_set<std::string>& exceptionLayerTypes = {}); static void checkConstWithBlobs(const CNNLayerPtr layer); static void checkQuantizeOnWeights(const CNNLayerPtr layer); static void updateInput(details::CNNNetworkImpl* network, CNNLayerPtr& layer, DataPtr outData); static size_t disconnectLayers( CNNNetworkImpl* network, const CNNLayerPtr& parentLayer, const CNNLayerPtr& childLayer); static size_t getInputIndex(const CNNLayerPtr& childLayer, const CNNLayerPtr& parentLayer); static void removeLayer(ICNNNetwork& network, const CNNLayerPtr& layer); static bool isWeightsSupported(const CNNLayer& layer) noexcept; static Blob::Ptr getWeights(const CNNLayer& layer, const bool roundQuantizedValues, const std::vector<float>& weightsShiftPerChannel = {}); static Blob::Ptr getBiases(const CNNLayer& layer); static Blob::Ptr quantizeWeights( const CNNLayer& quantize, const bool roundValues, const Precision precision = Precision::UNSPECIFIED, const std::vector<float>& weightsShiftPerChannel = {}); static int getConstParentBranchID(const CNNLayer& layer); static int getFakeQuantizeBranchWithOneChild(const CNNLayer& layer); static Precision getPrecisionParent(const CNNLayer& layer); static Precision getPrecisionParent(const CNNLayer& layer, const size_t parentIndex); static DataPtr getOutData(const CNNLayer& parentLayer, const CNNLayer& childLayer); private: // 1 - on weights // 0 - weightable layer was not found // -1 - on activations static int onWeightsInDepth(const CNNLayer& layer); static Precision getPrecisionParent(const CNNLayer& layer, const size_t parentIndex, const bool useParentIndex); static Blob::Ptr getQuantizeLayerBlob(const CNNLayer& quantize) { if (quantize.insData.size() < 1) { THROW_IE_EXCEPTION << "unexpected parents count for " << quantize.type << " layer " << quantize.name; } DataPtr data = quantize.insData[0].lock(); if (data == nullptr) { THROW_IE_EXCEPTION << "parent data is absent for " << quantize.type << " layer " << quantize.name; } CNNLayerPtr blobLayer = data->getCreatorLayer().lock(); if (blobLayer == nullptr) { THROW_IE_EXCEPTION << "parent layer is absent for " << quantize.type << " layer " << quantize.name; } if (blobLayer->blobs.size() != 1) { THROW_IE_EXCEPTION << "unexpected blobs count for " << blobLayer->type << " layer " << blobLayer->name; } return blobLayer->blobs.begin()->second;; } // TODO: don't need to define type for weights quantization: separate to two methods template <class T> static Blob::Ptr quantizeBlob( const CNNLayer& quantize, const bool roundValues, const Precision precision, const std::vector<float>& shiftPerChannel = {}) { const Blob::Ptr sourceBlob = getQuantizeLayerBlob(quantize); if (sourceBlob == nullptr) { THROW_IE_EXCEPTION << "quantized blob is empty for " << quantize.type << " layer " << quantize.name; } auto srcData = getFloatData(sourceBlob); const std::vector<size_t>& originalDims = quantize.outData[0]->getDims(); const std::vector<size_t>& dims = originalDims.size() == 2lu ? std::vector<size_t>({ originalDims[0], originalDims[1], 1lu, 1lu, 1lu }) : originalDims.size() == 4lu ? std::vector<size_t>({ originalDims[0], originalDims[1], 1lu, originalDims[2], originalDims[3] }) : originalDims; if (dims.size() != 5lu) { THROW_IE_EXCEPTION << "Unexpected dimensions count " << dims.size() << " for layer '" << quantize.name << "'"; } // OIDHW const size_t outputsSize = dims[0]; // O const size_t inputsSize = dims[1]; // I const size_t D = dims[2]; // D const size_t H = dims[3]; // H const size_t W = dims[4]; // W const auto& sourceBlobTensorDesc = sourceBlob->getTensorDesc(); Blob::Ptr targetBlob = make_shared_blob<T>(TensorDesc( precision != Precision::UNSPECIFIED ? precision : sourceBlobTensorDesc.getPrecision(), sourceBlobTensorDesc.getDims(), sourceBlobTensorDesc.getLayout())); targetBlob->allocate(); const size_t sourceBlobSize = sourceBlob->size(); if (sourceBlobSize != (inputsSize * outputsSize * D * H * W)) { THROW_IE_EXCEPTION << "Unexpected weights dimensions " << outputsSize << "x" << inputsSize << "x" << D << "x" << H << "x" << W << " for layer '" << quantize.name << "'"; } auto dstBuffer = getFloatData(targetBlob); const QuantizationDetails quantizationDetails = QuantizationDetails::getDetails(quantize); const bool isInputLowBroadcasted = quantizationDetails.inputLowValues.size() != outputsSize; if ((quantizationDetails.inputLowValues.size() != 1) && (quantizationDetails.inputLowValues.size() != outputsSize)) { THROW_IE_EXCEPTION << "Unexpected input low values count " << quantizationDetails.inputLowValues.size() << " for " << outputsSize << " channels, layer '" << quantize.name << "'"; } const bool isInputHighBroadcasted = quantizationDetails.inputHighValues.size() != outputsSize; if ((quantizationDetails.inputHighValues.size() != 1) && (quantizationDetails.inputHighValues.size() != outputsSize)) { THROW_IE_EXCEPTION << "Unexpected input high values count " << quantizationDetails.inputHighValues.size() << " for " << outputsSize << " channels, layer '" << quantize.name << "'"; } const bool isOutputLowBroadcasted = quantizationDetails.outputLowValues.size() != outputsSize; if ((quantizationDetails.outputLowValues.size() != 1) && (quantizationDetails.outputLowValues.size() != outputsSize)) { THROW_IE_EXCEPTION << "Unexpected output low values count " << quantizationDetails.outputLowValues.size() << " for " << outputsSize << " channels, layer '" << quantize.name << "'"; } const bool isOutputHighBroadcasted = quantizationDetails.outputHighValues.size() != outputsSize; if ((quantizationDetails.outputHighValues.size() != 1) && (quantizationDetails.outputHighValues.size() != outputsSize)) { THROW_IE_EXCEPTION << "Unexpected output high values count " << quantizationDetails.outputHighValues.size() << " for " << outputsSize << " channels, layer '" << quantize.name << "'"; } const float levels_1 = static_cast<float>(quantize.GetParamAsUInt("levels")) - 1.f; const size_t DHW = D * H * W; const size_t IDHW = inputsSize * DHW; for (size_t outputIndex = 0; outputIndex < outputsSize; outputIndex++) { for (size_t inputIndex = 0; inputIndex < inputsSize; inputIndex++) { for (size_t d = 0; d < D; d++) { for (size_t h = 0; h < H; h++) { for (size_t w = 0; w < W; w++) { const float inputLow = quantizationDetails.inputLowValues[isInputLowBroadcasted ? 0 : outputIndex]; const float inputHigh = quantizationDetails.inputHighValues[isInputHighBroadcasted ? 0 : outputIndex]; const float outputLow = quantizationDetails.outputLowValues[isOutputLowBroadcasted ? 0 : outputIndex]; const float outputHigh = quantizationDetails.outputHighValues[isOutputHighBroadcasted ? 0 : outputIndex]; const size_t idx = outputIndex * IDHW + inputIndex * DHW + d * H * W + h * W + w; if (srcData.get()[idx] <= inputLow) { dstBuffer.get()[idx] = roundValues ? std::roundf(outputLow) : outputLow; } else if (srcData.get()[idx] > inputHigh) { dstBuffer.get()[idx] = roundValues ? std::roundf(outputHigh) : outputHigh; } else { const float value = std::roundf((srcData.get()[idx] - inputLow) / (inputHigh - inputLow) * levels_1) / levels_1 * (outputHigh - outputLow) + outputLow; dstBuffer.get()[idx] = roundValues ? std::roundf(value) : value; } } } } } } fillBlobByFP32(targetBlob, dstBuffer.get()); return targetBlob; } }; } // namespace details } // namespace InferenceEngine
43.378049
143
0.653289
[ "vector" ]
a5a76af9816a1c09dea59a232f69eb0c9aee3307
3,818
cpp
C++
src/LightBulb/Learning/Evolution/SharedSamplingCombiningStrategy.cpp
domin1101/ANNHelper
50acb5746d6dad6777532e4c7da4983a7683efe0
[ "Zlib" ]
5
2016-02-04T06:14:42.000Z
2017-02-06T02:21:43.000Z
src/LightBulb/Learning/Evolution/SharedSamplingCombiningStrategy.cpp
domin1101/ANNHelper
50acb5746d6dad6777532e4c7da4983a7683efe0
[ "Zlib" ]
41
2015-04-15T21:05:45.000Z
2015-07-09T12:59:02.000Z
src/LightBulb/Learning/Evolution/SharedSamplingCombiningStrategy.cpp
domin1101/LightBulb
50acb5746d6dad6777532e4c7da4983a7683efe0
[ "Zlib" ]
null
null
null
// Includes #include "LightBulb/Learning/Evolution/SharedSamplingCombiningStrategy.hpp" #include "LightBulb/Learning/Evolution/AbstractIndividual.hpp" #include "LightBulb/Learning/Evolution/AbstractCoevolutionEnvironment.hpp" //Library includes namespace LightBulb { void SharedSamplingCombiningStrategy::combine(AbstractCoevolutionEnvironment& simulationEnvironment, std::vector<AbstractIndividual*>& firstIndividuals, std::vector<AbstractIndividual*>& secondIndividuals) { if (!otherCombiningStrategy) throw std::invalid_argument("SharedSamplingCombiningStrategy only works with two environments."); std::vector<AbstractIndividual*> sample; std::map<AbstractIndividual*, std::map<int, int>> beat; std::map<AbstractIndividual*, double> sampleFitness; auto prevResults = otherCombiningStrategy->getPrevResults(); while (sample.size() < amountOfCompetitionsPerIndividual) { AbstractIndividual* bestIndividual = nullptr; for (auto secondPlayer = secondIndividuals.begin(); secondPlayer != secondIndividuals.end(); secondPlayer++) { if (sampleFitness[*secondPlayer] != -1) { sampleFitness[*secondPlayer] = 0; for (auto resultsPerSecondPlayer = prevResults.matchIndices[*secondPlayer].begin(); resultsPerSecondPlayer != prevResults.matchIndices[*secondPlayer].end(); resultsPerSecondPlayer++) { for (auto result = resultsPerSecondPlayer->second.begin(); result != resultsPerSecondPlayer->second.end(); result++) { if (prevResults.resultVector.getEigenValue()(result->second)) sampleFitness[*secondPlayer] += 1.0 / (1 + beat[resultsPerSecondPlayer->first][result->first]); } } if (bestIndividual == nullptr || sampleFitness[bestIndividual] < sampleFitness[*secondPlayer]) bestIndividual = *secondPlayer; } } if (!bestIndividual) break; sample.push_back(bestIndividual); sampleFitness[bestIndividual] = -1; for (auto resultsPerSecondPlayer = prevResults.matchIndices[bestIndividual].begin(); resultsPerSecondPlayer != prevResults.matchIndices[bestIndividual].end(); resultsPerSecondPlayer++) { for (auto result = resultsPerSecondPlayer->second.begin(); result != resultsPerSecondPlayer->second.end(); result++) { if (prevResults.resultVector.getEigenValue()(result->second)) beat[resultsPerSecondPlayer->first][result->first]++; } } } for (auto firstPlayer = firstIndividuals.begin(); firstPlayer != firstIndividuals.end(); firstPlayer++) { for (auto secondPlayer = sample.begin(); secondPlayer != sample.end(); secondPlayer++) { if (*firstPlayer != *secondPlayer) { for (int r = 0; r < simulationEnvironment.getRoundCount(); r++) { simulationEnvironment.compareIndividuals(**firstPlayer, **secondPlayer, r, firstPlayerHasWon); setResult(**firstPlayer, **secondPlayer, r, firstPlayerHasWon); } } } } } void SharedSamplingCombiningStrategy::setSecondEnvironment(AbstractCoevolutionEnvironment& newSecondEnvironment) { AbstractCombiningStrategy::setSecondEnvironment(newSecondEnvironment); otherCombiningStrategy = &secondEnvironment->getCombiningStrategy(); } SharedSamplingCombiningStrategy::SharedSamplingCombiningStrategy(int amountOfCompetitionsPerIndividual_, AbstractCoevolutionEnvironment* secondEnvironment_) :AbstractCombiningStrategy(secondEnvironment_) { if (secondEnvironment) otherCombiningStrategy = &secondEnvironment->getCombiningStrategy(); amountOfCompetitionsPerIndividual = amountOfCompetitionsPerIndividual_; } int SharedSamplingCombiningStrategy::getTotalMatches(const AbstractCoevolutionEnvironment& simulationEnvironment) const { return amountOfCompetitionsPerIndividual * simulationEnvironment.getPopulationSize() * simulationEnvironment.getRoundCount(); } }
42.898876
206
0.762179
[ "vector" ]
a5ae2ff500cfaa1e251b5ac468864560c8bfde78
1,590
hh
C++
src/link.hh
CN-TU/remy
0c0887322b0cbf6e3497e3aeb95c979907f03623
[ "Apache-2.0" ]
6
2020-03-19T04:16:02.000Z
2022-03-30T15:41:39.000Z
src/link.hh
CN-TU/remy
0c0887322b0cbf6e3497e3aeb95c979907f03623
[ "Apache-2.0" ]
1
2020-05-20T12:05:49.000Z
2021-11-14T13:39:23.000Z
src/link.hh
CN-TU/remy
0c0887322b0cbf6e3497e3aeb95c979907f03623
[ "Apache-2.0" ]
null
null
null
#ifndef LINK_HH #define LINK_HH #include <deque> #include <vector> #include "packet.hh" using namespace remy; #include "delay.hh" #include "receiver.hh" class Link { private: std::deque< Packet > _buffer; Delay _pending_packet; unsigned int _limit; public: Link( const double s_rate, const unsigned int s_limit) : _buffer(), _pending_packet( 1.0 / s_rate ), _limit( s_limit ) {} void accept( const Packet & p, const double & tickno ) noexcept { if ( _pending_packet.empty() ) { _pending_packet.accept( p, tickno ); } else { if ( _limit and _buffer.size() < _limit ) { _buffer.push_back( p ); } } } template <class NextHop> void tick( NextHop & next, const double & tickno ); double next_event_time( const double & tickno ) const { return _pending_packet.next_event_time( tickno ); } std::vector<unsigned int> packets_in_flight( const unsigned int num_senders ) const { std::vector<unsigned int> ret( num_senders ); for ( const auto & x : _buffer ) { ret.at( x.src )++; } std::vector<unsigned int> propagating = _pending_packet.packets_in_flight( num_senders ); for ( unsigned int i = 0; i < num_senders; i++ ) { ret.at( i ) += propagating.at( i ); } return ret; } void set_rate( const double rate ) { _pending_packet.set_delay( 1.0 / rate ); } double rate( void ) const { return 1.0 / _pending_packet.delay(); } void set_limit( const unsigned int limit ) { _limit = limit; while ( _buffer.size() > _limit ) { _buffer.pop_back(); } } }; #endif
24.090909
109
0.644025
[ "vector" ]
a5b408881dae0ca7c054827318462499e234492b
13,531
cpp
C++
xlitomatic/urlsource.cpp
srl295/icu
7c7f805b917476f269babc853fb1eb3e0a17a88b
[ "ICU", "Unlicense" ]
1
2018-07-24T21:03:12.000Z
2018-07-24T21:03:12.000Z
xlitomatic/urlsource.cpp
srl295/icu
7c7f805b917476f269babc853fb1eb3e0a17a88b
[ "ICU", "Unlicense" ]
null
null
null
xlitomatic/urlsource.cpp
srl295/icu
7c7f805b917476f269babc853fb1eb3e0a17a88b
[ "ICU", "Unlicense" ]
1
2018-07-13T15:52:46.000Z
2018-07-13T15:52:46.000Z
/********************************************************************** * Copyright (C) 2000, International Business Machines * Corporation and others. All Rights Reserved. ***********************************************************************/ #include "urlsource.h" # include <sys/socket.h> #include <signal.h> #include <unistd.h> #include <stdio.h> # include <netdb.h> # include <arpa/inet.h> # include <netinet/in.h> # include <unistd.h> #include <string.h> #include <time.h> #include<stdlib.h> # include <netinet/tcp.h> # include <sys/types.h> #include <fcntl.h> #define LINEBUFSIZ 10 /* Error Handling */ const char *alarmError = NULL; void alrmHandler(int signnum) { fprintf(stderr, "Caught signal %d, msg = %s\n", signnum, alarmError); fprintf(stdout, "Content-type: text/html\r\n\r\n<B>Error: [%s]", alarmError); // Can't throw from here.. :( exit(0); } int reAlarm(int secs) { alarm(secs); } void setAlarm(const char *err = NULL, int secs=0) { signal(SIGALRM, alrmHandler); if(err == NULL) { secs = 0; } else if(secs == 0) { err = NULL; } alarmError = err; // reset the alarm alarm(secs); } struct URLSourceImp { public: bool encodingTry; struct sockaddr_in skin; struct hostent *hp; int fSd; bool_t eof; char buf[LINEBUFSIZ]; int32_t rdPtr, wrPtr; int32_t readInternal(char *out, int32_t len); void readInternal(); // throws a char* error. tries to fill the buffer. int32_t readNextLine(char *out, int32_t len); // throws a char* error inline bool_t isFull() { return ((wrPtr+1)%LINEBUFSIZ)==rdPtr; } inline bool_t isEmpty() { return (wrPtr == rdPtr); } void write(const char *s); void connect(const char *host, int32_t port); int32_t copyTo(char *out, int32_t last); }; int32_t URLSourceImp::copyTo(char *out, int32_t last) { // last = our 'wrptr' for this. int32_t total; if(isEmpty()) return 0; if(rdPtr > last) { memcpy(out, buf+last, LINEBUFSIZ-rdPtr); total += (LINEBUFSIZ-rdPtr); memcpy(out+total, buf, last); } else { memcpy(out, buf+rdPtr, wrPtr-rdPtr); total = wrPtr - rdPtr; } rdPtr = last; // advance ptr.. return total; } void URLSourceImp::write(const char *s) { if(fSd == -1) return; ::write(fSd, s, strlen(s)); } int32_t URLSourceImp::readInternal(char *out, int32_t len) { int32_t n; if(eof) return 0; if(fSd == -1) { throw "Read on unopened socket."; } setAlarm("reading data", 4); n = recv(fSd, out, len, 0); setAlarm(0); if(n == -1) { fprintf(stderr, "Got err on socket, -> EOF\n"); eof = TRUE; return 0; } if(n == 0) { eof = TRUE; } return n; } void URLSourceImp::readInternal() { if(eof) return; // #1 is there any space in the buffer fill it if(isFull()) { fprintf(stderr, "BUffer is full.\n"); return; } fprintf(stderr, "R%d, W%d:\n ", rdPtr, wrPtr); if(wrPtr == rdPtr) { int32_t toRead,actRead; toRead = LINEBUFSIZ-wrPtr-1; if(toRead == 0) { wrPtr = 0; rdPtr = 0; } else { actRead = readInternal(buf+wrPtr, toRead); fprintf(stderr, " .. read %d of %d\n", actRead, toRead); if(actRead > 0) { wrPtr += actRead; return; } } } if(wrPtr > rdPtr) { int32_t toRead,actRead; toRead = LINEBUFSIZ-wrPtr-1; if(toRead == 0) { wrPtr = 0; } else { actRead = readInternal(buf+wrPtr, toRead); fprintf(stderr, " .. read %d of %d\n", actRead, toRead); if(actRead > 0) { wrPtr += actRead; return; } } } else { int32_t toRead,actRead; toRead = rdPtr - wrPtr - 1; if(toRead <= 0) { return; } actRead = readInternal(buf + wrPtr, toRead); fprintf(stderr, " ..+ read %d of %d\n", actRead, toRead); if(actRead > 0) { wrPtr += actRead; } } } int32_t URLSourceImp::readNextLine(char *out, int32_t len) { if(len < LINEBUFSIZ) { throw "give me a bigger buffer next time."; } // for now - copy all data. while(isEmpty() && !eof) { readInternal(); } return copyTo(out,wrPtr); } void URLSourceImp::connect(const char *host, int32_t port) { int32_t rv; setAlarm("looking up host..", 10); hp = gethostbyname(host); if(!hp) { char junk[200]; sprintf(junk,"Cannot resolve host: %s",host); throw junk; } memset((char *)&skin,0,sizeof(skin)); memcpy((char *)&(skin.sin_addr),hp->h_addr,hp->h_length); skin.sin_port = htons(port); skin.sin_family = AF_INET; fSd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if(fSd < 0) { perror("socket"); fSd = -1; throw "Error in socket()"; } fprintf(stderr, "Connected to %s:%d\n", host, port); if (rv = ::connect(fSd,(sockaddr*)&skin,sizeof(skin))) { fSd = -1; perror("connect"); throw "Error in connect"; } setAlarm(0); eof = FALSE; } URLSource::URLSource(const char *url) : u(url), encoding(NULL), imp(new URLSourceImp) { imp->encodingTry = FALSE; imp->hp = NULL; imp->fSd = -1; imp->rdPtr = 0; imp->wrPtr = 0; imp->eof = TRUE; } URLSource::URLSource(const char *url, bool_t testEnc) : u(url), encoding(NULL), imp(new URLSourceImp) { imp->encodingTry = testEnc; imp->hp = NULL; imp->fSd = -1; imp->rdPtr = 0; imp->wrPtr = 0; imp->eof = TRUE; } void URLSource::rewind() { if(!imp) return; if(imp->fSd != -1) { close(imp->fSd); imp->fSd = -1; imp->eof = TRUE; } } int32_t URLSource::read(const uint8_t* &start, const uint8_t* &end) { char junk[999]; int len; if(fEOF) return 0; imp->connect("daphne",80); imp->write("GET / HTTP/1.0\r\n\r\n"); while(!imp->eof) { len = imp->readNextLine((char*)buffer, sizeof(buffer)); fprintf(stderr, "[%d]::: ", len); strncpy(junk,buffer,len); fprintf(stderr, "%s<<\n", junk); } fEOF = TRUE; return 0; } URLSource::~URLSource() { rewind(); delete imp; } const char *URLSource::getEncoding() { if(encoding != NULL) { return encoding; } if(imp->encodingTry == FALSE) { // use a sub object URLSource sub(u, TRUE); return sub.getEncoding(); } while(encoding == NULL) { const uint8_t *start,*end; read(start,end); } return encoding; } #if 0 void processLine(char *s) { char *c; char tmp[999]; if(passThrough == 1) { puts(s); return; } if(strncmp(s,"HTTP/",5) == 0) { /* printf("Content-type: text/html\n\n\n"); */ /* nothing to do */ } else if(strstr(s,"Content-Length")) { } else if(strstr(s,"Content-Type")) { if(!strstr(s,"text")) { /* uh oh.. bail out.. */ passThrough = 1; puts(s); } else { strcpy(tmp,s); c = strchr(tmp,';'); if(c == 0) { strcat(tmp,";charset="); if((!strncmp(dstEncoding, "mt-", 3)) || (strncmp(dstEncoding, "latin3", 6)) ) strcat(tmp, "x-user-defined"); else strcat(tmp,dstEncoding); } else { strcpy(c,";charset="); strcat(c,dstEncoding); puts("x-thought-i-fixed-it:"); } puts(tmp); } } else printf("%s\n",s); } void writeData(char *b, int n) { const char *source,*consumed; UChar * target; if(passThrough == 1) write(1,b,n); /* straight copy for now.. */ else { /* srcUC,dstUC */ int nn,j; UErrorCode status; status = U_ZERO_ERROR; source = b; consumed = 0; target = ucbuf; /* b[n] = 0; */ target[0] = '/'; target[1] = '/'; target[2] = '/'; ucnv_toUnicode(srcUC, &target, target+UCSIZ, &source, source+n, NULL, FALSE, &status); nn = target-ucbuf; /* printf("c = %d\n",consumed-b); printf("ds = %d\n",source-b); */ /* printf("Got %d(%d)->%d... [%s]\n", n,strlen(b),nn,b); fflush(stdout); */ /* ucbuf[nn] = 0; */ if(U_FAILURE(status)) { char tmp[99]; sprintf(tmp,"Failed to do ucnv_toUchars - %d\n",(int)status); err(tmp,""); return; } /* printf("%x %x %x %x\n",ucbuf[0],ucbuf[1],ucbuf[2],ucbuf[3]); */ status = U_ZERO_ERROR; strcpy(tmpbuf,"____________"); ucbuf[nn] = 0; j = ucnv_fromUChars(dstUC, tmpbuf, 10000,ucbuf,&status); if(U_FAILURE(status)) { char tmp[99]; sprintf(tmp,"Failed to do ucnv_toUchars - %d\n",(int)status); err(tmp,""); return; } /* printf("-->%d (%d)\n",j,strlen(tmpbuf),tmpbuf[0],tmpbuf[1],tmpbuf[2]); fflush(stdout); */ /* { int q; for( q=0;q<j;q++) { if(tmpbuf[q] != 0) printf("%c",tmpbuf[q]); }fflush(stdout); }*/ fflush(stdout); write(1,tmpbuf,j); fflush(stdout); } } void doload(const char *path) { int rv; int count; char *cr; FILE *f; char *contentType = "text/html"; chdir("/home/srl/public_html/malta/"); /* err("no err- connected.",""); */ f = fopen(path , "r"); if(!f) { fprintf(stderr,"* could not load %s\n", path); err("Couldn't load %s", path); return; } if(strstr(path,".jpg")) { contentType = "image/jpeg"; passThrough = 1; } else if (strstr(path,".gif")) { contentType = "image/gif"; passThrough = 1; } if(!passThrough) { printf("Content-type: text/html; charset=%s\r\n", dstEncoding); fprintf(stderr, "*Content-type: text/html; charset=%s\r\n", dstEncoding); } else printf("Content-type: %s\r\n", contentType); printf("\r\n"); fprintf(stderr, "*\r\n"); if(!passThrough) { if(!strcmp(dstEncoding, "mt-times")) { printf("<FONT FACE=\"MTimes\">"); } else if(!strcmp(dstEncoding, "mt-tornado")) { printf("<FONT FACE=\"tornado\">"); } else if(!strcmp(dstEncoding, "latin3")) { } if(!strcmp(path, "TEST")) { printf("<A TARGET=\"_top\" HREF=\"./%s\">", getenv("QUERY_STRING")); } } tmpbuf[1] = '_'; tmpbuf[2] = '_'; while((count = fread(tmpbuf, 1,READCHUNK, f)) >0 ) { writeData(tmpbuf,count); } #if 0 fprintf(stderr, "[read %d, %c[%02x] %c %c...]\n", count, tmpbuf[0], (int)tmpbuf[0], tmpbuf[1], tmpbuf[2]); fflush(stdout); if(foundAll == 1) /* we're just copying */ { } else { char *startfrom; /* the beginning of the current input chunk under consideration*/ tmpbuf[count] = 0; /* sanity! */ startfrom = tmpbuf; /* start from the beginning of the read buffer .. */ do { /* look for a cr. */ cr = strchr(startfrom,'\r'); if(cr >= (startfrom+count)) cr == 0; if(cr == 0) /* none this time */ { /* printf("Nocr,cpoying %d bytes \n", count);fflush(stdout); */ /* copy everything into the line buffer */ /* printf("Copying %d bytes into lb[%d]\n",count,linecnt); */ memcpy(&linebuf[linecnt],startfrom,count); linecnt += count; /* we'll pass through */ count = 0; } else { int thisline = cr - startfrom; /* # of chars on this line */ /* printf("Gotcr,lfrag=%d, [%x-%x] [%c]\n",thisline, startfrom, cr, startfrom[0]); fflush(stdout); */ memcpy(&linebuf[linecnt],startfrom,thisline); linecnt += thisline; startfrom += thisline; count -= thisline; /* Before we go any further, eat up that CR/LF */ count --; startfrom++; if(count == 0) { /* printf("Need to do another read to eat up the 0x0a\n"); */ recv(fSd,tmpbuf,1,0); /* printf("done.\n"); fflush(stdout); */ } else { /* eat 0x0a this way */ count--; startfrom++; } /* ** have a good line, ship it */ /* printf("putting in null term @ lb[%d]\n",linecnt); */ linebuf[linecnt] = 0; if(linecnt == 0) /* found header stop line */ { foundAll = 1; /* STOP */ /* printf("Content-Base: http://%s%s\n",host,path); */ } /* printf("Line found=>>%s<<[%d]\n",linebuf,linecnt); */ processLine(linebuf); /* Now, back to 0 */ linecnt = 0; if((foundAll == 1) && (count > 0) ) /* excess data in the buffer, deal. */ { /* printf("************8xxx*"); */ /* get the last one */ fflush(stdout); writeData(startfrom,count); } /* printf("sotw: sf=[%c%c%c...], cnt=%d\n", startfrom[0],startfrom[1],startfrom[2],count); fflush(stdout);*/ } fflush(stdout); } while (count > 0); } tmpbuf[1] = '_'; tmpbuf[2] = '_'; } #endif if(count < 0 ) { err("Error in read.",""); perror("read"); fclose(f); return; } fclose(f); if(!passThrough) { if(!strcmp(path, "TEST")) printf("</A> - %s", dstEncoding); else printf("<HR><A NAME=\"_chencoding\"><P><B>Current encoding: [click to change]<P><UL><A TARGET=_top HREF=\"./CHANGE?%s\">%s</A></UL><A HREF=\"encodings_help.html\">Help!</A></A>\n", path, dstEncoding); } } #endif
19.840176
205
0.523686
[ "object" ]
a5bb76d0979893935fe7f6016f275d514ac407ad
3,327
cc
C++
RecoLocalTracker/Phase2TrackerRecHits/src/Phase2StripCPE.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
RecoLocalTracker/Phase2TrackerRecHits/src/Phase2StripCPE.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
RecoLocalTracker/Phase2TrackerRecHits/src/Phase2StripCPE.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
#include "RecoLocalTracker/Phase2TrackerRecHits/interface/Phase2StripCPE.h" #include "Geometry/CommonTopologies/interface/PixelTopology.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" Phase2StripCPE::Phase2StripCPE(edm::ParameterSet & conf, const MagneticField & magf,const TrackerGeometry& geom) : magfield_(magf), geom_(geom), tanLorentzAnglePerTesla_(conf.getParameter<double>("TanLorentzAnglePerTesla")) { use_LorentzAngle_DB_ = conf.getParameter<bool>("LorentzAngle_DB"); if (use_LorentzAngle_DB_) { throw cms::Exception("Lorentz Angle from DB not implemented yet"); tanLorentzAnglePerTesla_ = 0; // old code: LorentzAngleMap_.getLorentzAngle(det->geographicalId().rawId()); } fillParam(); } Phase2StripCPE::LocalValues Phase2StripCPE::localParameters( const Phase2TrackerCluster1D & cluster, const GeomDetUnit & detunit) const { auto const & p = m_Params[detunit.index()-m_off]; auto const & topo = *p.topology; float ix = cluster.center() - 0.5f * p.coveredStrips; float iy = float(cluster.column())+0.5f; // halfway the column LocalPoint lp( topo.localX(ix), topo.localY(iy), 0 ); // x, y, z return std::make_pair( lp, p.localErr ); } LocalVector Phase2StripCPE::driftDirection( const Phase2TrackerGeomDetUnit & det) const { LocalVector lbfield = (det.surface()).toLocal(magfield_.inTesla(det.surface().position())); float dir_x = -tanLorentzAnglePerTesla_ * lbfield.y(); float dir_y = tanLorentzAnglePerTesla_ * lbfield.x(); float dir_z = 1.f; // E field always in z direction return LocalVector(dir_x,dir_y,dir_z); } void Phase2StripCPE::fillParam() { // in phase 2 they are all pixel topologies... auto const & dus = geom_.detUnits(); m_off = dus.size(); // skip Barrel and Foward pixels... for(unsigned int i=3;i<7;++i) { LogDebug("LookingForFirstPhase2OT") << " Subdetector " << i << " GeomDetEnumerator " << GeomDetEnumerators::tkDetEnum[i] << " offset " << geom_.offsetDU(GeomDetEnumerators::tkDetEnum[i]) << std::endl; if(geom_.offsetDU(GeomDetEnumerators::tkDetEnum[i]) != dus.size()) { if(geom_.offsetDU(GeomDetEnumerators::tkDetEnum[i]) < m_off) m_off = geom_.offsetDU(GeomDetEnumerators::tkDetEnum[i]); } } LogDebug("LookingForFirstPhase2OT") << " Chosen offset: " << m_off; m_Params.resize(dus.size()-m_off); // very very minimal, for sure it will need to expand... for (auto i=m_off; i!=dus.size();++i) { auto & p= m_Params[i-m_off]; const Phase2TrackerGeomDetUnit & det = (const Phase2TrackerGeomDetUnit &)(*dus[i]); assert(det.index()==int(i)); p.topology = &det.specificTopology(); auto pitch_x = p.topology->pitch().first; auto pitch_y = p.topology->pitch().second; // see https://github.com/cms-sw/cmssw/blob/CMSSW_8_1_X/RecoLocalTracker/SiStripRecHitConverter/src/StripCPE.cc auto thickness = det.specificSurface().bounds().thickness(); auto drift = driftDirection(det) * thickness; auto lvec = drift + LocalVector(0,0,-thickness); p.coveredStrips = lvec.x() / pitch_x; // simplifies wrt Phase0 tracker because only rectangular modules constexpr float o12 = 1./12; p.localErr = LocalError( o12*pitch_x*pitch_x, 0, o12*pitch_y*pitch_y); // e2_xx, e2_xy, e2_yy } }
38.686047
125
0.700331
[ "geometry" ]
a5bf156807254884676a7f37ec9fe5c7909a2cd0
20,880
cc
C++
elang/compiler/syntax/parser.cc
eval1749/elang
5208b386ba3a3e866a5c0f0271280f79f9aac8c4
[ "Apache-2.0" ]
1
2018-01-27T22:40:53.000Z
2018-01-27T22:40:53.000Z
elang/compiler/syntax/parser.cc
eval1749/elang
5208b386ba3a3e866a5c0f0271280f79f9aac8c4
[ "Apache-2.0" ]
1
2016-01-29T00:54:49.000Z
2016-01-29T00:54:49.000Z
elang/compiler/syntax/parser.cc
eval1749/elang
5208b386ba3a3e866a5c0f0271280f79f9aac8c4
[ "Apache-2.0" ]
null
null
null
// Copyright 2014-2015 Project Vogue. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "elang/compiler/syntax/parser.h" #include <string> #include <vector> #include <unordered_set> #include "base/logging.h" #include "elang/compiler/ast/class.h" #include "elang/compiler/ast/enum.h" #include "elang/compiler/ast/expressions.h" #include "elang/compiler/ast/factory.h" #include "elang/compiler/ast/namespace.h" #include "elang/compiler/ast/types.h" #include "elang/compiler/compilation_session.h" #include "elang/compiler/compilation_unit.h" #include "elang/compiler/modifiers_builder.h" #include "elang/compiler/public/compiler_error_code.h" #include "elang/compiler/syntax/lexer.h" #include "elang/compiler/token_type.h" namespace elang { namespace compiler { namespace { Token* MakeQualifiedNameToken(ast::Node* thing) { if (auto const name_reference = thing->as<ast::NameReference>()) return name_reference->name(); if (auto const type_name_reference = thing->as<ast::TypeNameReference>()) return type_name_reference->name(); if (auto const type_member_access = thing->as<ast::TypeMemberAccess>()) return MakeQualifiedNameToken(type_member_access->reference()); if (auto const member_access = thing->as<ast::MemberAccess>()) { return member_access->token(); } return nullptr; } } // namespace ////////////////////////////////////////////////////////////////////// // // ContainerScope // Parser::ContainerScope::ContainerScope(Parser* parser, ast::ContainerNode* new_container) : container_(parser->container_), parser_(parser) { parser->container_ = new_container; } Parser::ContainerScope::~ContainerScope() { parser_->container_ = container_; } ////////////////////////////////////////////////////////////////////// // // Parser::ModifierParser // class Parser::ModifierParser final { public: explicit ModifierParser(Parser* parser); ~ModifierParser() = default; const std::vector<Token*>& tokens() const { return tokens_; } bool Add(Token* token); Modifiers Get() const; void Reset(); private: ModifiersBuilder builder_; std::vector<Token*> tokens_; Parser* const parser_; DISALLOW_COPY_AND_ASSIGN(ModifierParser); }; Parser::ModifierParser::ModifierParser(Parser* parser) : parser_(parser) { } bool Parser::ModifierParser::Add(Token* token) { switch (token->type()) { #define CASE_CLAUSE(name, string, details) \ case TokenType::name: \ if (builder_.Has##name()) { \ parser_->Error(ErrorCode::SyntaxModifierDuplicate); \ return true; \ } \ builder_.Set##name(); \ tokens_.push_back(token); \ return true; FOR_EACH_MODIFIER(CASE_CLAUSE) #undef CASE_CLAUSE } return false; } Modifiers Parser::ModifierParser::Get() const { return builder_.Get(); } void Parser::ModifierParser::Reset() { builder_.Reset(); } ////////////////////////////////////////////////////////////////////// // // Parser // Parser::Parser(CompilationSession* session, CompilationUnit* compilation_unit) : CompilationSessionUser(session), compilation_unit_(compilation_unit), container_(compilation_unit->namespace_body()), declaration_space_(nullptr), expression_(nullptr), last_source_offset_(0), lexer_(new Lexer(session, compilation_unit)), modifiers_(new ModifierParser(this)), statement_(nullptr), statement_scope_(nullptr), token_(nullptr) { } Parser::~Parser() { } ast::Factory* Parser::factory() const { return session()->ast_factory(); } void Parser::Advance() { DCHECK(token_); token_ = nullptr; PeekToken(); } bool Parser::AdvanceIf(TokenType type) { if (PeekToken() != type) return false; Advance(); return true; } Token* Parser::ConsumeName(ErrorCode error_code) { DCHECK(token_); if (PeekToken()->is_name()) return ConsumeToken(); return session()->NewUniqueNameToken(token_->location(), L"@var%d"); } Token* Parser::ConsumeOperator(TokenType type, ErrorCode error_code) { DCHECK(token_); if (auto const token = ConsumeTokenIf(type)) return token; return session()->NewToken(token_->location(), TokenData(type)); } void Parser::ConsumeSemiColon(ErrorCode error_code) { if (AdvanceIf(TokenType::SemiColon)) return; Error(error_code); } Token* Parser::ConsumeToken() { DCHECK(token_); auto const result = token_; Advance(); return result; } Token* Parser::ConsumeTokenIf(TokenType type) { if (PeekToken() != type) return nullptr; return ConsumeToken(); } void Parser::Error(ErrorCode error_code, Token* token, Token* token2) { DCHECK(token); session()->AddError(error_code, token, token2); } void Parser::Error(ErrorCode error_code, Token* token) { DCHECK(token); session()->AddError(error_code, token); } void Parser::Error(ErrorCode error_code) { Error(error_code, token_); } Token* Parser::NewUniqueNameToken(const base::char16* format) { return session()->NewUniqueNameToken( SourceCodeRange(compilation_unit_->source_code(), last_source_offset_, last_source_offset_), format); } // ClassDecl ::= Attribute* ClassModifier* 'partial'? 'class' // Name TypeParamereList? ClassBase? // TypeParameterConstraintsClasses? // Class ';'? // ClassModifier ::= ClassModifierAccessibility | // ClassModifierKind | // 'new' // ClassModifierAccessibility := 'private' | 'protected' | 'public' // ClassModifierKind := 'abstract' | 'static' | 'final' // // Class ::= '{' ClassMemberDecl* '}' // void Parser::ParseClass() { ValidateClassModifiers(); // TODO(eval1749) Support partial class. auto const class_modifiers = modifiers_->Get(); auto const class_keyword = ConsumeToken(); auto const class_name = ConsumeToken(); if (!class_name->is_name()) return Error(ErrorCode::SyntaxClassName, class_name); // TypeParameterList if (AdvanceIf(TokenType::LeftAngleBracket)) ParseTypeParameterList(); // ClassBase std::vector<ast::Type*> base_class_names; if (AdvanceIf(TokenType::Colon)) { do { ParseNamespaceOrTypeName(); base_class_names.push_back(ConsumeType()); } while (AdvanceIf(TokenType::Comma)); } auto const clazz = factory()->NewClass( container_, class_modifiers, class_keyword, class_name, base_class_names); container_->AddMember(clazz); ContainerScope container_scope(this, clazz); if (class_modifiers.HasExtern()) return ConsumeSemiColon(ErrorCode::SyntaxClassSemiColon); // Class ::= "{" ClassMemberDeclaration* "}" // ClassMemberDeclaration ::= // ConstantDecl | // FieldDecl | // MethodDecl | // PropertyDecl | // IndexerDecl | // OperatorDecl | // ConstructorDecl | // FinalizerDecl | // StaticConstructorDecl | // TypeDecl if (!AdvanceIf(TokenType::LeftCurryBracket)) return Error(ErrorCode::SyntaxClassLeftCurryBracket); for (;;) { modifiers_->Reset(); while (modifiers_->Add(PeekToken())) Advance(); switch (PeekToken()->type()) { case TokenType::Class: case TokenType::Interface: case TokenType::Struct: ParseClass(); continue; case TokenType::Enum: ParseEnum(); continue; case TokenType::Function: ParseFunction(); continue; case TokenType::RightCurryBracket: return Advance(); } // ConstDecl ::= 'var' Type? name ('=' Expression) ';' if (auto const keyword = ConsumeTokenIf(TokenType::Const)) { auto const name = ParseVarTypeAndName(); ParseConst(keyword, ConsumeType(), name); continue; } // FieldDecl ::= 'var' Type? name ('=' Expression) ';' if (auto const keyword = ConsumeTokenIf(TokenType::Var)) { auto const name = ParseVarTypeAndName(); ParseField(keyword, ConsumeType(), name); continue; } // MethodDecl ::= // Type Name TypeParameterList? ParameterDecl ';' // Type Name TypeParameterList? ParameterDecl '{' // Statement* '}' auto const member_modifiers = modifiers_->Get(); auto const member_type = ParseAndConsumeType(); auto const member_name = ConsumeToken(); if (!member_name->is_name()) return Error(ErrorCode::SyntaxClassMemberName); if (AdvanceIf(TokenType::LeftAngleBracket)) { auto const type_parameters = ParseTypeParameterList(); if (!AdvanceIf(TokenType::LeftParenthesis)) { Error(ErrorCode::SyntaxClassMemberParenthesis); // TODO(eval1749) Skip until '{' or '}' continue; } ParseMethod(member_modifiers, member_type, member_name, type_parameters); continue; } if (AdvanceIf(TokenType::LeftParenthesis)) { ParseMethod(member_modifiers, member_type, member_name, {}); continue; } // FieldDecl ::= Type Name ('=' Expression) ';' auto const keyword = session()->NewToken( member_name->location(), TokenData(TokenType::Var, session()->NewAtomicString(L"var"))); ParseField(keyword, member_type, member_name); } } // CompilationUnit ::= // ExternalAliasDirective // UsingDirective* // GlobalAttribute* // NamedNodeDecl* void Parser::ParseCompilationUnit() { ParseUsingDirectives(); ParseNamedNodes(); if (session()->HasError() || PeekToken() == TokenType::EndOfSource) return; Error(ErrorCode::SyntaxCompilationUnitInvalid, token_); } // ConstDecl ::= 'const' Type? Name '=' Expression ';' void Parser::ParseConst(Token* keyword, ast::Type* type, Token* name) { DCHECK_EQ(keyword, TokenType::Const); DCHECK(name->is_name()); auto const clazz = container_->as<ast::Class>(); auto const modifiers = modifiers_->Get(); ValidateFieldModifiers(); if (AdvanceIf(TokenType::Assign)) { ParseExpression(ErrorCode::SyntaxFieldExpression); } else { Error(ErrorCode::SyntaxConstAssign); ProduceInvalidExpression(PeekToken()); } auto const node = factory()->NewConst(clazz, modifiers, keyword, type, name, ConsumeExpression()); clazz->AddMember(node); ConsumeSemiColon(ErrorCode::SyntaxClassMemberSemiColon); } // EnumDecl := EnumModifier* "enum" Name EnumBase? "{" EnumField* "}" // EnumBase ::= ':' IntegralType // EnumField ::= Name ("=" Expression)? ","? // EnumModifier ::= 'new' | 'public' | 'protected' | 'private' void Parser::ParseEnum() { // TODO(eval1749) Validate EnumModifier auto const enum_modifiers = modifiers_->Get(); auto const enum_keyword = ConsumeToken(); DCHECK_EQ(enum_keyword->type(), TokenType::Enum); if (!PeekToken()->is_name()) { Error(ErrorCode::SyntaxEnumNameInvalid); token_ = session()->NewUniqueNameToken(token_->location(), L"enum%d"); } auto const enum_name = ConsumeToken(); auto const enum_base = AdvanceIf(TokenType::Colon) ? ParseAndConsumeType() : nullptr; auto const enum_node = factory()->NewEnum(container_, enum_modifiers, enum_keyword, enum_name, enum_base); container_->AddMember(enum_node); if (!AdvanceIf(TokenType::LeftCurryBracket)) Error(ErrorCode::SyntaxEnumLeftCurryBracket); ast::EnumMember* last_member = nullptr; while (PeekToken()->is_name()) { auto const member_name = ConsumeToken(); auto const explicit_value = AdvanceIf(TokenType::Assign) ? (ParseExpression(ErrorCode::SyntaxEnumExpression), ConsumeExpression()) : nullptr; ast::Expression* implicit_value = nullptr; if (!explicit_value) { if (last_member) { auto const add = session()->NewToken(member_name->location(), TokenData(TokenType::Add)); auto const left = factory()->NewNameReference(last_member->name()); auto const one = session()->NewToken( member_name->location(), TokenData(TokenType::Int32Literal, 1)); auto const right = factory()->NewLiteral(one); implicit_value = factory()->NewBinaryOperation(add, left, right); } else { auto const zero = session()->NewToken( member_name->location(), TokenData(TokenType::Int32Literal, static_cast<uint64_t>(0))); implicit_value = factory()->NewLiteral(zero); } } auto const member = factory()->NewEnumMember( enum_node, member_name, explicit_value, implicit_value); enum_node->AddMember(member); last_member = member; if (PeekToken() == TokenType::RightCurryBracket) break; if (AdvanceIf(TokenType::Comma)) continue; } if (!AdvanceIf(TokenType::RightCurryBracket)) Error(ErrorCode::SyntaxEnumRightCurryBracket); } // FieldDecl ::= 'var' Type? Name ('=' Expression)? ';' | // Type Name ('=' Expression)? ';' void Parser::ParseField(Token* keyword, ast::Type* type, Token* name) { DCHECK_EQ(keyword, TokenType::Var); DCHECK(name->is_name()); auto const clazz = container_->as<ast::Class>(); auto const modifiers = modifiers_->Get(); ValidateFieldModifiers(); if (AdvanceIf(TokenType::Assign)) { ParseExpression(ErrorCode::SyntaxFieldExpression); } else { if (type->is<ast::TypeVariable>()) Error(ErrorCode::SyntaxVarAssign); ProduceExpression(factory()->NewNoExpression(PeekToken())); } auto const node = factory()->NewField(clazz, modifiers, keyword, type, name, ConsumeExpression()); clazz->AddMember(node); ConsumeSemiColon(ErrorCode::SyntaxClassMemberSemiColon); } void Parser::ParseFunction() { // TODO(eval1749) Implement 'function' parser. } // NamespaceDecl ::= "namespace" QualifiedName Namespace ";"? // Namespace ::= "{" ExternAliasDirective* UsingDirective* // NamedNodeDecl* "}" void Parser::ParseNamespace() { auto const namespace_keyword = ConsumeToken(); DCHECK_EQ(namespace_keyword->type(), TokenType::Namespace); std::vector<Token*> names; do { if (!PeekToken()->is_name()) { if (!names.empty()) Error(ErrorCode::SyntaxNamespaceName); if (PeekToken() != TokenType::LeftCurryBracket) Advance(); break; } names.push_back(ConsumeToken()); } while (AdvanceIf(TokenType::Dot)); if (names.empty()) { Error(ErrorCode::SyntaxNamespaceAnonymous); names.push_back(NewUniqueNameToken(L"ns%d")); } ParseNamespace(namespace_keyword, names, 0); } void Parser::ParseNamespace(Token* namespace_keyword, const std::vector<Token*>& names, size_t index) { auto const ns_body = container_->as<ast::NamespaceBody>(); DCHECK(ns_body); auto const name = names[index]; auto const new_ns_body = factory()->NewNamespaceBody(ns_body, namespace_keyword, name); ns_body->AddMember(new_ns_body); ContainerScope container_scope(this, new_ns_body); if (index + 1 < names.size()) return ParseNamespace(namespace_keyword, names, index + 1); if (!AdvanceIf(TokenType::LeftCurryBracket)) { Error(ErrorCode::SyntaxNamespaceLeftCurryBracket); return; } ParseUsingDirectives(); ParseNamedNodes(); AdvanceIf(TokenType::RightCurryBracket); AdvanceIf(TokenType::SemiColon); } // NamedNodeDecl ::= NamespaceDecl | TypeDecl // TypeDecl ::= ClassDecl | InterfaceDecl | StructDecl | EnumDecl | // FunctionDecl void Parser::ParseNamedNodes() { auto is_top_level = container_ == compilation_unit_->namespace_body(); auto skipping = false; for (;;) { modifiers_->Reset(); while (modifiers_->Add(PeekToken())) Advance(); switch (PeekToken()->type()) { case TokenType::Class: case TokenType::Interface: case TokenType::Struct: ParseClass(); continue; case TokenType::Enum: ParseEnum(); continue; case TokenType::Function: ParseFunction(); continue; case TokenType::Namespace: ParseNamespace(); continue; case TokenType::EndOfSource: return; case TokenType::RightCurryBracket: if (!is_top_level) return; Advance(); skipping = false; continue; case TokenType::SemiColon: if (skipping) { skipping = false; Advance(); continue; } break; case TokenType::Using: skipping = true; break; default: if (skipping) { Advance(); continue; } break; } if (is_top_level) { Error(ErrorCode::SyntaxCompilationUnitInvalid, ConsumeToken()); return; } Error(ErrorCode::SyntaxNamespaceInvalid, ConsumeToken()); } } // UsingDirective ::= AliasDef | ImportNamespace // AliasDef ::= 'using' Name '=' NamespaceOrTypeName ';' // ImportNamespace ::= 'using' QualfiedName ';' void Parser::ParseUsingDirectives() { auto const ns_body = container_->as<ast::NamespaceBody>(); DCHECK(ns_body); while (auto const using_keyword = ConsumeTokenIf(TokenType::Using)) { ParseNamespaceOrTypeName(); auto const thing = ConsumeType(); if (AdvanceIf(TokenType::Assign)) { // AliasDef ::= 'using' Name '=' NamespaceOrTypeName ';' auto const type_name_ref = thing->as<ast::TypeNameReference>(); if (!type_name_ref) { Error(ErrorCode::SyntaxUsingDirectiveAlias); AdvanceIf(TokenType::SemiColon); continue; } auto const alias_name = type_name_ref->name(); ParseNamespaceOrTypeName(); auto const reference = ConsumeType(); auto const alias = factory()->NewAlias(ns_body, using_keyword, alias_name, reference); ns_body->AddMember(alias); } else { // ImportNamespace ::= 'using' QualfiedName ';' auto const qualified_name = MakeQualifiedNameToken(thing); if (!qualified_name) { Error(ErrorCode::SyntaxUsingDirectiveImport, thing->token()); AdvanceIf(TokenType::SemiColon); continue; } if (auto const import = ns_body->FindImport(qualified_name)) { Error(ErrorCode::SyntaxUsingDirectiveDuplicate, qualified_name, import->reference()->token()); } else { ns_body->AddImport(factory()->NewImport(ns_body, using_keyword, thing)); } } ConsumeSemiColon(ErrorCode::SyntaxUsingDirectiveSemiColon); } } Token* Parser::PeekToken() { if (token_) return token_; token_ = lexer_->GetToken(); last_source_offset_ = token_->location().start_offset(); if (token_->is_left_bracket()) { delimiters_.push_back(token_); return token_; } if (!token_->is_right_bracket()) return token_; Token* left_bracket = nullptr; for (auto it = delimiters_.rbegin(); it != delimiters_.rend(); ++it) { auto const delimiter = *it; if (!delimiter->is_left_bracket()) continue; if (token_ == delimiter->right_bracket()) { if (left_bracket) Error(ErrorCode::SyntaxBracketNotClosed, left_bracket, token_); while (delimiters_.back() != delimiter) delimiters_.pop_back(); delimiters_.pop_back(); return token_; } left_bracket = delimiter; } if (left_bracket) Error(ErrorCode::SyntaxBracketNotClosed, left_bracket, token_); else Error(ErrorCode::SyntaxBracketExtra); return token_; } void Parser::Run() { ParseCompilationUnit(); } void Parser::ValidateClassModifiers() { auto has_accessibility = false; auto has_inheritance = false; for (const auto& token : modifiers_->tokens()) { switch (token->type()) { case TokenType::Abstract: case TokenType::New: case TokenType::Static: if (has_inheritance) Error(ErrorCode::SyntaxClassModifier, token); else has_inheritance = true; break; case TokenType::Private: case TokenType::Protected: case TokenType::Public: if (has_accessibility) Error(ErrorCode::SyntaxClassModifier, token); else has_accessibility = true; break; case TokenType::Virtual: case TokenType::Volatile: Error(ErrorCode::SyntaxClassModifier, token); break; } } } void Parser::ValidateEnumModifiers() { // TODO(eval1749) NYI validate enum modifier } void Parser::ValidateFieldModifiers() { // TODO(eval1749) NYI validate field modifier } void Parser::ValidateMethodModifiers() { // TODO(eval1749) NYI validate method modifier } } // namespace compiler } // namespace elang
31.164179
80
0.64636
[ "vector" ]
a5c36cfcd8261b1d3c0bc0f59ea5dab4a4db10a2
5,083
hpp
C++
src/TransportCellProperty.hpp
OSS-Lab/ChemChaste
d32c36afa1cd870512fee3cba0753d5c6faf8109
[ "BSD-3-Clause" ]
null
null
null
src/TransportCellProperty.hpp
OSS-Lab/ChemChaste
d32c36afa1cd870512fee3cba0753d5c6faf8109
[ "BSD-3-Clause" ]
null
null
null
src/TransportCellProperty.hpp
OSS-Lab/ChemChaste
d32c36afa1cd870512fee3cba0753d5c6faf8109
[ "BSD-3-Clause" ]
null
null
null
#ifndef TRANSPORTCELLPROPERTY_HPP #define TRANSPORTCELLPROPERTY_HPP //general includes #include <vector> #include <boost/shared_ptr.hpp> // chaste includes #include "Cell.hpp" #include "AbstractCellProperty.hpp" #include "StateVariableRegister.hpp" #include "AbstractTransportReactionSystem.hpp" #include "AbstractTransportOdeSystem.hpp" #include "AbstractIvpOdeSolver.hpp" #include "EulerIvpOdeSolver.hpp" #include "ChastePoint.hpp" class TransportCellProperty : public AbstractCellProperty { protected: // CellPtr to a given cell for access to cell data and for properties that relate ot the transport ode CellPtr mThis_cellPtr; // register for variables that cross the membrane; either side StateVariableRegister* mpBulkStateVariableRegister; StateVariableRegister* mpCellStateVariableRegister; // transport reaction system for the passage of state variables across the boundary AbstractTransportReactionSystem* mpTransportReactionSystem; // transport reaction system Ode corresponding to the mpTransportReactionSystem AbstractTransportOdeSystem* mpTransportOdeSystem; // transport Ode solver boost::shared_ptr<AbstractIvpOdeSolver> mpSolver; // concentration of state variables at the internal boundary of the cell if this is to remain constant bool mIsConstantCellConcentration = false; // for use in averaged source for example? std::vector<double> mBulkBoundaryConcentrationVector; std::vector<double> mChangeBulkBoundaryConcentrationVector; std::vector<double> mCellBoundaryConcentrationVector; std::vector<double> mChangeCellBoundaryConcentrationVector; bool mIncludeOdeInterpolationOnBoundary=false; //15/10/2020 std::vector<double> mInitBulkBoundaryConcentrationVector; unsigned mNumberOCalls_this_reaction_step =0; public: TransportCellProperty(); virtual ~TransportCellProperty(); TransportCellProperty(const TransportCellProperty&); // virtual methods virtual void SetUp(AbstractTransportReactionSystem*, CellPtr); virtual void UpdateCellConcentrationVector(std::vector<double>); virtual void UpdateBulkConcentrationVector(std::vector<double>); virtual void PerformTransportSystem(const std::vector<double>&, const std::vector<double>&, std::vector<double>&, std::vector<double>&); virtual void UpdateTransportReactionSystem(AbstractTransportReactionSystem*); virtual void UpdateTransportOdeSystem(AbstractTransportOdeSystem*); virtual void PreparePostDivisionParent(double); virtual void PreparePostDivisionDaughter(const TransportCellProperty&, double); // concrete methods //double RetrieveBoundarySourceByStateName(std::string,ChastePoint<SPACE_DIM> ); // moved to extended cell property void SetUpCellConcentrationVector(unsigned); void SetUpBulkConcentrationVector(unsigned); void SetUpChangeCellConcentrationVector(unsigned); void SetUpChangeBulkConcentrationVector(unsigned); double RetrieveBoundarySourceByStateName(std::string); // overload for non-extended cell property case double RetrieveChangeBoundarySourceByStateName(std::string); // overload for non-extended cell property case void AppendInternalCellBoundaryConcentrations(std::vector<double>&); void ReplaceBoundaryStateVariables(std::vector<double>&); void ReplaceChangeBoundaryStateVariables(std::vector<double>&); void ResetReactionCalls(); unsigned GetReactionCalls(); // set methods void SetBulkStateVariableRegister(StateVariableRegister*); void SetCellStateVariableRegister(StateVariableRegister*); void SetConstantCellConcentrationBool(bool); void SetCellBoundaryConcentrationVector(std::vector<double>); void SetBulkBoundaryConcentrationVector(std::vector<double>); void SetInitBulkBoundaryConcentrationVector(std::vector<double>); void SetTransportOdeSolver(boost::shared_ptr<AbstractIvpOdeSolver>); void SetIncludeOdeInterpolationOnBoundary(bool); void SetCellPtr(CellPtr); // get methods StateVariableRegister* GetBulkStateVariableRegister(); StateVariableRegister* GetCellStateVariableRegister(); bool GetConstantCellConcentrationBool(); std::vector<double> GetInternalCellBoundaryConcentrationVector(); double GetInternalCellBoundaryConcentrationByIndex(unsigned); double GetInternalCellBoundaryConcentrationByName(std::string); double GetChangeInternalCellBoundaryConcentrationByName(std::string); std::vector<double> GetExternalCellBoundaryConcentrationVector(); double GetExternalCellBoundaryConcentrationByIndex(unsigned); double GetChangeExternalCellBoundaryConcentrationByIndex(unsigned); double GetExternalCellBoundaryConcentrationByName(std::string); AbstractTransportReactionSystem* GetTransportReactionSystem(); AbstractTransportOdeSystem* GetTransportOdeSystem(); boost::shared_ptr<AbstractIvpOdeSolver> GetTransportOdeSolver(); bool GetIncludeOdeInterpolationOnBoundary(); CellPtr GetCellPtr(); }; #endif
30.620482
140
0.793823
[ "vector" ]
a5d84ddbce08e076bf3bbd985fc93e73e6710989
62,599
cpp
C++
bagged_boosting_ensemble.cpp
ninoarsov/collaborative_bagging_of_gentle_boost_ensembles
6c67794f545f615c795baccc4ac97e5b508363a3
[ "MIT" ]
null
null
null
bagged_boosting_ensemble.cpp
ninoarsov/collaborative_bagging_of_gentle_boost_ensembles
6c67794f545f615c795baccc4ac97e5b508363a3
[ "MIT" ]
null
null
null
bagged_boosting_ensemble.cpp
ninoarsov/collaborative_bagging_of_gentle_boost_ensembles
6c67794f545f615c795baccc4ac97e5b508363a3
[ "MIT" ]
null
null
null
#include "bagged_boosting_ensemble.hpp" #include <limits> #include <algorithm> #include <iostream> #include <functional> #include <thread> #include <cstdlib> #include <cmath> #define MAX_MP std::numeric_limits<double>::max() namespace bu = BaggingUtils; /* Helper functions */ void remove_row ( Matrix& matrix, const int row_to_remove ) { matrix.shed_row(row_to_remove); } void remove_coeff ( Vector& vec, const int coeff_to_remove ) { vec.shed_row(coeff_to_remove); } void append_row ( Matrix& matrix, const Matrix& row_to_append ) { matrix.resize(matrix.n_rows + 1, matrix.n_cols); matrix.row(matrix.n_rows - 1) = row_to_append; } void append_coeff ( Vector& vec, double coeff_to_append ){ vec.resize(vec.n_elem + 1); vec(vec.n_elem - 1) = coeff_to_append; } bool is_equal ( Matrix& a, Matrix& b ) { if(a.n_rows != b.n_rows || a.n_cols != b.n_cols) return false; for(arma::uword i = 0; i < a.n_rows; ++i) { for(arma::uword j = 0; j < a.n_cols; ++j) { if(a(i, j) != b(i, j)) return false; } } return true; } /* Destructor */ BaggedBoostingEnsemble::~BaggedBoostingEnsemble ( ) { for(auto&& i : _ensembles) { i.reset(); } } /* Default constructor */ BaggedBoostingEnsemble::BaggedBoostingEnsemble ( ) { } /* Constructor with options. Sets the options and subsequently parses them. */ BaggedBoostingEnsemble::BaggedBoostingEnsemble ( const options& opts ) { _opts = opts; } /* Copy constructor */ BaggedBoostingEnsemble::BaggedBoostingEnsemble ( const BaggedBoostingEnsemble& other ) { _opts = other._opts; for(decltype(other._ensembles.size())i=0; i < other._ensembles.size(); ++i){ _ensembles.push_back(std::make_shared<GentleBoostEnsemble>(*other._ensembles[i])); } } /* Splits the data into training and validation sets and then: 1) Uses Max-Flow bagging to distribute data among the ensembles 2) Preservs the original class balance factor in each subset */ void BaggedBoostingEnsemble::distribute_training_data ( const Matrix& data ) { const std::size_t NEG = 0; const std::size_t POS = 1; bu::sampled_data s = bu::split_data(data, _opts.validation_frac); // create vectors of positive and negative indices for sampling std::vector<int> p, n; for(unsigned int i = 0; i < s.x_train[NEG].n_rows; ++i) n.push_back((int)i); for(unsigned int i = 0; i < s.x_train[POS].n_rows; ++i) p.push_back((int)i); int pos_sample_size = _opts.bagging_data_frac * s.x_train[POS].n_rows, neg_sample_size = _opts.bagging_data_frac * s.x_train[NEG].n_rows; // allocate data and ensembles if(_opts.bagging_data_frac < 1.0) for(int e = 0; e < _opts.n_ensembles; ++e) { // draw a random sample without replacement std::vector<int> pos_indices = bu::sampling_without_replacement(pos_sample_size, p); std::vector<int> neg_indices = bu::sampling_without_replacement(neg_sample_size, n); Matrix e_x(pos_sample_size + neg_sample_size, s.x_train[POS].n_cols); Vector e_y(pos_sample_size + neg_sample_size); unsigned int k = 0; for(auto idx : pos_indices) { e_x.row(k) = s.x_train[POS].row(idx); e_y(k) = s.y_train[POS](idx); k++; } for(auto idx : neg_indices) { e_x.row(k) = s.x_train[NEG].row(idx); e_y(k) = s.y_train[NEG](idx); k++; } // create the gentle boost ensemble and its base learners _ensembles.push_back(std::make_shared<GentleBoostEnsemble>(e_x, e_y)); _ensembles[e]->create_base_learners(); } else { Matrix x = arma::join_cols(s.x_train[POS], s.x_train[NEG]); Vector y(x.n_rows); int k = 0; for(int i = 0; i < s.y_train[POS].n_elem; i++) { y(k) = s.y_train[POS](i); k++; } for(int i = 0; i < s.y_train[NEG].n_elem; i++) { y(k) = s.y_train[NEG](i); k++; } for(int e = 0; e < _opts.n_ensembles; ++e) { Matrix e_x(x.n_rows, x.n_cols); Vector e_y(y.n_elem); for(int i = 0 ; i < e_x.n_rows; i++) { Vector rnd = arma::randi<Vector>(1, arma::distr_param(0, e_x.n_rows-1)); e_x.row(i) = x.row(rnd(0)); e_y(i) = y(rnd(0)); } _ensembles.push_back(std::make_shared<GentleBoostEnsemble>(e_x, e_y)); _ensembles[e]->create_base_learners(); } } // set the validation data _validation_data = Matrix(s.x_valid[NEG].n_rows + s.x_valid[POS].n_rows, s.x_valid[NEG].n_cols); _validation_labels = Vector(s.y_valid[NEG].n_elem + s.y_valid[POS].n_elem); _validation_data = arma::join_cols<Matrix>(s.x_valid[NEG], s.x_valid[POS]); _validation_labels = arma::join_cols<Matrix>(s.y_valid[NEG], s.y_valid[POS]); } void step_one(unsigned int &step, arma::mat &cost, const unsigned int &N) { for (unsigned int r = 0; r < N; ++r) { cost.row(r) -= arma::min(cost.row(r)); } step = 2; } void step_two (unsigned int &step, const arma::mat &cost, arma::umat &indM, arma::ivec &rcov, arma::ivec &ccov, const unsigned int &N) { for (unsigned int r = 0; r < N; ++r) { for (unsigned int c = 0; c < N; ++c) { if (cost.at(r, c) == 0.0 && rcov.at(r) == 0 && ccov.at(c) == 0) { indM.at(r, c) = 1; rcov.at(r) = 1; ccov.at(c) = 1; break; // Only take the first // zero in a row and column } } } /* for later reuse */ rcov.fill(0); ccov.fill(0); step = 3; } void step_three(unsigned int &step, const arma::umat &indM, arma::ivec &ccov, const unsigned int &N) { unsigned int colcount = 0; for (unsigned int r = 0; r < N; ++r) { for (unsigned int c = 0; c < N; ++c) { if (indM.at(r, c) == 1) { ccov.at(c) = 1; } } } for (unsigned int c = 0; c < N; ++c) { if (ccov.at(c) == 1) { ++colcount; } } if (colcount == N) { step = 7; } else { step = 4; } } void find_noncovered_zero(int &row, int &col, const arma::mat &cost, const arma::ivec &rcov, const arma::ivec &ccov, const unsigned int &N) { unsigned int r = 0; unsigned int c; bool done = false; row = -1; col = -1; while (!done) { c = 0; while (true) { if (cost.at(r, c) == 0.0 && rcov.at(r) == 0 && ccov.at(c) == 0) { row = r; col = c; done = true; } ++c; if (c == N || done) { break; } } ++r; if (r == N) { done = true; } } } bool star_in_row(int &row, const arma::umat &indM, const unsigned int &N) { bool tmp = false; for (unsigned int c = 0; c < N; ++c) { if (indM.at(row, c) == 1) { tmp = true; break; } } return tmp; } void find_star_in_row (const int &row, int &col, const arma::umat &indM, const unsigned int &N) { col = -1; for (unsigned int c = 0; c < N; ++c) { if (indM.at(row, c) == 1) { col = c; } } } void step_four (unsigned int &step, const arma::mat &cost, arma::umat &indM, arma::ivec &rcov, arma::ivec &ccov, int &rpath_0, int &cpath_0, const unsigned int &N) { int row = -1; int col = -1; bool done = false; while(!done) { find_noncovered_zero(row, col, cost, rcov, ccov, N); if (row == -1) { done = true; step = 6; } else { /* uncovered zero */ indM(row, col) = 2; if (star_in_row(row, indM, N)) { find_star_in_row(row, col, indM, N); /* Cover the row with the starred zero * and uncover the column with the starred * zero. */ rcov.at(row) = 1; ccov.at(col) = 0; } else { /* No starred zero in row with * uncovered zero */ done = true; step = 5; rpath_0 = row; cpath_0 = col; } } } } void find_star_in_col (const int &col, int &row, const arma::umat &indM, const unsigned int &N) { row = -1; for (unsigned int r = 0; r < N; ++r) { if (indM.at(r, col) == 1) { row = r; } } } void find_prime_in_row (const int &row, int &col, const arma::umat &indM, const unsigned int &N) { for (unsigned int c = 0; c < N; ++c) { if (indM.at(row, c) == 2) { col = c; } } } void augment_path (const int &path_count, arma::umat &indM, const arma::imat &path) { for (unsigned int p = 0; p < path_count; ++p) { if (indM.at(path(p, 0), path(p, 1)) == 1) { indM.at(path(p, 0), path(p, 1)) = 0; } else { indM.at(path(p, 0), path(p, 1)) = 1; } } } void clear_covers (arma::ivec &rcov, arma::ivec &ccov) { rcov.fill(0); ccov.fill(0); } void erase_primes(arma::umat &indM, const unsigned int &N) { for (unsigned int r = 0; r < N; ++r) { for (unsigned int c = 0; c < N; ++c) { if (indM.at(r, c) == 2) { indM.at(r, c) = 0; } } } } void step_five (unsigned int &step, arma::umat &indM, arma::ivec &rcov, arma::ivec &ccov, arma::imat &path, int &rpath_0, int &cpath_0, const unsigned int &N) { bool done = false; int row = -1; int col = -1; unsigned int path_count = 1; path.at(path_count - 1, 0) = rpath_0; path.at(path_count - 1, 1) = cpath_0; while (!done) { find_star_in_col(path.at(path_count - 1, 1), row, indM, N); if (row > -1) { /* Starred zero in row 'row' */ ++path_count; path.at(path_count - 1, 0) = row; path.at(path_count - 1, 1) = path.at(path_count - 2, 1); } else { done = true; } if (!done) { /* If there is a starred zero find a primed * zero in this row; write index to 'col' */ find_prime_in_row(path.at(path_count - 1, 0), col, indM, N); ++path_count; path.at(path_count - 1, 0) = path.at(path_count - 2, 0); path.at(path_count - 1, 1) = col; } } augment_path(path_count, indM, path); clear_covers(rcov, ccov); erase_primes(indM, N); step = 3; } void find_smallest (double &minval, const arma::mat &cost, const arma::ivec &rcov, const arma::ivec &ccov, const unsigned int &N) { for (unsigned int r = 0; r < N; ++r) { for (unsigned int c = 0; c < N; ++c) { if (rcov.at(r) == 0 && ccov.at(c) == 0) { if (minval > cost.at(r, c)) { minval = cost.at(r, c); } } } } } void step_six (unsigned int &step, arma::mat &cost, const arma::ivec &rcov, const arma::ivec &ccov, const unsigned int &N) { double minval = std::numeric_limits<double>::max(); find_smallest(minval, cost, rcov, ccov, N); for (unsigned int r = 0; r < N; ++r) { for (unsigned int c = 0; c < N; ++c) { if (rcov.at(r) == 1) { cost.at(r, c) += minval; } if (ccov.at(c) == 0) { cost.at(r, c) -= minval; } } } step = 4; } arma::umat hungarian(const arma::mat &input_cost) { const unsigned int N = input_cost.n_rows; unsigned int step = 1; int cpath_0 = 0; int rpath_0 = 0; arma::mat cost(input_cost); arma::umat indM(N, N); arma::ivec rcov(N); arma::ivec ccov(N); arma::imat path(2 * N, 2); indM = arma::zeros<arma::umat>(N, N); bool done = false; while (!done) { switch (step) { case 1: step_one(step, cost, N); break; case 2: step_two(step, cost, indM, rcov, ccov, N); break; case 3: step_three(step, indM, ccov, N); break; case 4: step_four(step, cost, indM, rcov, ccov, rpath_0, cpath_0, N); break; case 5: step_five(step, indM, rcov, ccov, path, rpath_0, cpath_0, N); break; case 6: step_six(step, cost, rcov, ccov, N); break; case 7: done = true; break; } } return indM; } void BaggedBoostingEnsemble::collaborate() { int iter = _ensembles[0]->get_iteration(); // adaptive n_exch, i.e. exchange only while all weak learners have // at least one positive margin for(int exch = 0; exch < _opts.instances_to_exchange; exch++) { Matrix LORx(_opts.n_ensembles, _ensembles[0]->get_x().n_cols); Vector LORy(_opts.n_ensembles); Vector from(_opts.n_ensembles); Vector weight(_opts.n_ensembles); UVector positions(_opts.n_ensembles); Vector max_margins_after_removal(_opts.n_ensembles); unsigned int k = 0; for(decltype(_ensembles.size())e = 0; e < _ensembles.size(); ++e) { arma::uword max_pos; Vector margins = _ensembles[e]->get_base_learners()[iter]->compute_margins(); // make n_exch adaptive UVector positive_margins_cnt = (margins >= 0.0); if(accu(positive_margins_cnt) == 0) return; Vector weighted_margins = _ensembles[e]->get_x_weights() % _ensembles[e]->get_base_learners()[iter]->compute_margins(); double max_w_margin = weighted_margins.max(max_pos); weighted_margins(max_pos) = -std::numeric_limits<double>::infinity(); max_margins_after_removal(e) = weighted_margins.max(); positions(e) = max_pos; LORx.row(k) = _ensembles[e]->get_x().row(max_pos); LORy(k) = _ensembles[e]->get_y()(max_pos); weight(e) = _ensembles[e]->get_x_weights()(max_pos); from(e) = e; k++; } // calculate a matrix cost for minimization Matrix assignment_cost = arma::zeros<Matrix>(_opts.n_ensembles, _opts.n_ensembles); for(unsigned int i = 0; i < LORx.n_rows; ++i) for(unsigned int j = 0; j < _opts.n_ensembles; ++j){ int weighted_margin = weight(j) * _ensembles[j]-> get_base_learners()[iter]->compute_margin(LORx.row(i), LORy(i)); assignment_cost(i, j) = weighted_margin-max_margins_after_removal(j); } UMatrix opt_assignment = hungarian(assignment_cost); for(unsigned int lor = 0; lor < opt_assignment.n_rows; ++lor) { int e = 0; while(opt_assignment(lor, e) == 0) e++; _ensembles[e]->get_x_nonconst().row(positions(e)) = LORx.row(lor); _ensembles[e]->get_y_nonconst()(positions(e)) = LORy(lor); } // retrain the regression stump // for(decltype(_ensembles.size())e = 0; e < _ensembles.size(); ++e) // _ensembles[e]->train_single(); } } double BaggedBoostingEnsemble::compute_stability( int e ) { // we only compute stability over positive margins !!!!!! // std::cout << "Iteration: " << _ensembles[e]->get_iteration() << " "; // first, find an instance that is not in the set (take the first from validation) RowVector probe_x = _validation_data.row(0); double probe_y = _validation_labels(0); // we use the current iteration Vector loss_before = arma::exp(-1.0 * _ensembles[e]->get_base_learners()[_ensembles[e]->get_iteration()]->compute_margins()); Vector loss_after(_ensembles[e]->get_x().n_rows); for(arma::uword i = 0; i < _ensembles[e]->get_x().n_rows; ++i) { // if(loss_before(i) >= 1.0) { // loss_before(i) = 0.0; // loss_after(i) = 0.0; // continue; // } // save prior to replacement RowVector old_x = _ensembles[e]->get_x().row(i); double old_y = _ensembles[e]->get_y()(i); // replace _ensembles[e]->get_x_nonconst().row(i) = probe_x; _ensembles[e]->get_y_nonconst()(i) = probe_y; // train _ensembles[e]->get_base_learners()[_ensembles[e]->get_iteration()]->train(); // get the loss on old_x loss_after(i) = std::exp(_ensembles[e]->get_base_learners()[_ensembles[e]->get_iteration()]->compute_margin(old_x, old_y)); // revert x back to old x _ensembles[e]->get_x_nonconst().row(i) = old_x; _ensembles[e]->get_y_nonconst()(i) = old_y; } // re-train again to return the weak learner's state to its initial _ensembles[e]->get_base_learners()[_ensembles[e]->get_iteration()]->train(); double stability = arma::mean(arma::abs(loss_before - loss_after)); return stability; } double BaggedBoostingEnsemble::compute_mean_emp_loss ( ) { double s = 0.0; for(decltype(_ensembles.size())e = 0; e < _ensembles.size(); ++e) { s += arma::mean(arma::exp(-1.0 * _ensembles[e]->compute_margins())); } return s / (double)_opts.n_ensembles; } void BaggedBoostingEnsemble::collaborate_exp() { int iter = _ensembles[0]->get_iteration(), min2 = _opts.instances_to_exchange; for(decltype(_ensembles.size())e = 0; e < _ensembles.size(); ++e) { Vector margins_of_e = _ensembles[e]->get_base_learners()[iter]->compute_margins(); UVector margins_of_e_positive = (margins_of_e > 0.0); if(accu(margins_of_e_positive) < min2) min2 = accu(margins_of_e_positive); } int correct_hits = 0; bool incorrect_prev = false; for(int brojac = 0; brojac < min2; brojac++) { int min = 1, k = 0; // remove "min" instances from each ensemble Matrix LORx(_opts.n_ensembles * min, _ensembles[0]->get_x().n_cols); Vector LORy(_opts.n_ensembles * min); Matrix weights(_opts.n_ensembles, min); Matrix cost(LORx.n_rows, _ensembles.size()); //double stability_before = compute_stability(0); for(decltype(_ensembles.size())e = 0; e < _ensembles.size(); ++e) { arma::uword min_pos; Vector margins_of_e = _ensembles[e]->get_base_learners()[iter]->compute_margins(); // filter out negative margins margins_of_e.elem(arma::find(margins_of_e <= 0.0)) += std::numeric_limits<double>::infinity(); if(incorrect_prev) { margins_of_e.min(min_pos); margins_of_e(min_pos) = std::numeric_limits<double>::infinity(); incorrect_prev = false; } std::vector<arma::uword> positions_of_removed_of_e; // find minimal margins_of_e for(int i = 0; i < min; i++) { double min_margin = margins_of_e.min(min_pos); margins_of_e(min_pos) = std::numeric_limits<double>::infinity(); positions_of_removed_of_e.push_back(min_pos); LORx.row(k) = _ensembles[e]->get_x().row(min_pos); LORy(k) = _ensembles[e]->get_y()(min_pos); weights(e, i) = _ensembles[e]->get_x_weights()(min_pos); k++; } // remove instances with minimal margins_of_e, but first sort the positions in descending order std::sort(positions_of_removed_of_e.begin(), positions_of_removed_of_e.end(), std::greater<arma::uword>()); for(auto&& pos_to_remove_from_e : positions_of_removed_of_e) { remove_row(_ensembles[e]->get_x_nonconst(), pos_to_remove_from_e); remove_coeff(_ensembles[e]->get_y_nonconst(), pos_to_remove_from_e); remove_coeff(_ensembles[e]->get_x_weights_nonconst(), pos_to_remove_from_e); } } // now, we construct the cost matrix for(arma::uword ens_j = 0; ens_j < _ensembles.size(); ++ens_j) { cost.col(ens_j) = 1.0 - _ensembles[ens_j]->get_base_learners()[iter]->compute_margins(LORx, LORy); } // std::cout << cost << std::endl; // save the cost matrix to a file "example.txt" // std::system("rm simplex_input"); // cost.save("simplex_input", arma::raw_ascii); // // run the java program and read the result from the file simplex_result // int retval = std::system("java SimplexTest"); // UMatrix optimal_assignment; // optimal_assignment.load("simplex_result", arma::raw_ascii); // // // Matrix optimal_assignment_real = arma::conv_to<Matrix>::from(optimal_assignment); // optimal_assignment_real = optimal_assignment_real % cost; // Matrix default_assignment = arma::eye(arma::size(optimal_assignment)); // Matrix default_assignment_real = default_assignment % cost; // // std::cout << optimal_assignment_real << std::endl; // bool correct = true; // for(arma::uword j = 0; j < optimal_assignment.n_cols; ++j) { // // std::cout << "ACCU = " << accu(optimal_assignment.col(j)) << std::endl; // if(accu(optimal_assignment.col(j)) > 1) { // correct = false; // break; // } // else if(accu(optimal_assignment_real.col(j)) < accu(default_assignment_real.col(j))) { // correct = false; // break; // } // // } // if(!correct) optimal_assignment.eye(); // //std::system("rm simplex_result"); double costb = accu(cost.diag()); UMatrix optimal_assignment = hungarian(cost); Matrix oar = arma::conv_to<Matrix>::from(optimal_assignment); Matrix cafter = oar % cost; double costa = accu(oar % cost); for(int j = 0; j < optimal_assignment.n_cols; j++) { if(accu(cafter.col(j)) >= cost.diag()(j)) { incorrect_prev = true; optimal_assignment.eye(); break; } } if(!incorrect_prev) correct_hits++; // assign the instances according to optimal_assignment for(arma::uword e = 0; e < _ensembles.size(); ++e) { // get removed weights from the e-th ensemble and sort them //Vector sorted_removed_weights_from_e = arma::sort(weights.row(e).t()); // get instances from LOR that need to be added to the e-th ensemble // Matrix instances_to_add_to_e(min, LORx.n_cols); // Vector labels_to_add_to_e(min); arma::uword kk = 0; Vector weights_of_e = weights.row(e).t(); for(arma::uword i = 0; i < optimal_assignment.n_rows; ++i) // if(optimal_assignment(i, e) == 1) { // instances_to_add_to_e.row(kk) = LORx.row(i); // labels_to_add_to_e(kk) = LORy(i); // kk++; // } if(optimal_assignment(i, e) == 1) { // std::cout << "ASSIGNED " <<i << " " << e << std::endl; append_row(_ensembles[e]->get_x_nonconst(), LORx.row(i)); append_coeff(_ensembles[e]->get_y_nonconst(), LORy(i)); append_coeff(_ensembles[e]->get_x_weights_nonconst(), weights_of_e(kk++)); for(int dim = 0; dim < _ensembles[e]->get_x().n_cols; ++dim) { _ensembles[e]->_max.push_back(_ensembles[e]->get_x().col(dim).max()); } } // // sort the margins of the instances that need to be added to e // Vector margins_to_add_to_e = sorted_removed_weights_from_e % _ensembles[e]->get_base_learners()[iter]->compute_margins(instances_to_add_to_e, labels_to_add_to_e); // UVector sorted_margins_to_add_to_e_idx = arma::stable_sort_index(margins_to_add_to_e); // // // now we have pairs (sorted_removed_weights_from_e, sorted_margins_to_add_to_e_idx) // for(arma::uword i = 0; i < margins_to_add_to_e.n_elem; ++i) { // append_row(_ensembles[e]->get_x_nonconst(), instances_to_add_to_e.row(sorted_margins_to_add_to_e_idx(i))); // append_coeff(_ensembles[e]->get_y_nonconst(), labels_to_add_to_e(sorted_margins_to_add_to_e_idx(i))); // append_coeff(_ensembles[e]->get_x_weights_nonconst(), sorted_removed_weights_from_e(i)); // } } // std::cout << optimal_assignment%cost << std::endl; } // D O N E ! ! ! // int iter = _ensembles[0]->get_iteration(); // // // adaptive n_exch, i.e. exchange only while all weak learners have // // at least one positive margin // for(int exch = 0; exch < _opts.instances_to_exchange; exch++) { // // Matrix LORx(_opts.n_ensembles, _ensembles[0]->get_x().n_cols); // Vector LORy(_opts.n_ensembles); // Vector from(_opts.n_ensembles); // Vector weight(_opts.n_ensembles); // UVector positions(_opts.n_ensembles); // Vector min_margins_after_removal(_opts.n_ensembles); // Vector max_margins_after_removal(_opts.n_ensembles); // // unsigned int k = 0; // Vector min_margins_before_removal(_opts.n_ensembles); // // for(decltype(_ensembles.size())e = 0; e < _ensembles.size(); ++e) { // arma::uword min_pos; // Vector margins = _ensembles[e]->get_base_learners()[iter]->compute_margins(); // // // // // make n_exch adaptive // UVector positive_margins_cnt = (margins >= 0.0); // if(accu(positive_margins_cnt) == 0) return; // // Vector weighted_margins = _ensembles[e]->get_x_weights() % // _ensembles[e]->get_base_learners()[iter]->compute_margins(); // Vector unweighted_margins = _ensembles[e]->get_base_learners()[iter]->compute_margins(); // // // filter out the negative margins // max_margins_after_removal(e) = unweighted_margins.max(); // weighted_margins.elem(find(weighted_margins < 0.0)) += std::numeric_limits<double>::infinity(); // // double min_w_margin = weighted_margins.min(min_pos); // min_margins_before_removal(e) = min_w_margin; // weighted_margins(min_pos) = std::numeric_limits<double>::infinity(); // min_margins_after_removal(e) = weighted_margins.min(); // // positions(e) = min_pos; // LORx.row(k) = _ensembles[e]->get_x().row(min_pos); // LORy(k) = _ensembles[e]->get_y()(min_pos); // weight(e) = _ensembles[e]->get_x_weights()(min_pos); // from(e) = e; // k++; // } // // // calculate a matrix cost for minimization // Matrix assignment_cost = arma::zeros<Matrix>(_opts.n_ensembles, // _opts.n_ensembles); // // for(unsigned int i = 0; i < LORx.n_rows; ++i) // for(unsigned int j = 0; j < _opts.n_ensembles; ++j){ // int weighted_margin = weight(j) * _ensembles[j]-> // get_base_learners()[iter]->compute_margin(LORx.row(i), LORy(i)); // assignment_cost(i, j) = (max_margins_after_removal(j)-weighted_margin/weight(j)); // } // UMatrix opt_assignment = hungarian(assignment_cost); // // Matrix opt_assignment_real = arma::conv_to<Matrix>::from(opt_assignment); // Matrix loss = assignment_cost % opt_assignment_real; // // // ova e za da se garantira deka m-clb ke podobri // if(accu(loss) > 0.0) { // opt_assignment.eye(); // } // // for(unsigned int lor = 0; lor < opt_assignment.n_rows; ++lor) { // int e = 0; // while(opt_assignment(lor, e) == 0) e++; // _ensembles[e]->get_x_nonconst().row(positions(e)) = LORx.row(lor); // _ensembles[e]->get_y_nonconst()(positions(e)) = LORy(lor); // } // // // std::cout << "AC = " << assignment_cost << std::endl; // // retrain the regression stump if(correct_hits > 0) for(decltype(_ensembles.size())e = 0; e < _ensembles.size(); ++e) _ensembles[e]->retrain_current(correct_hits); if(correct_hits > 0) std::cout << ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" << std::endl; // put everything back // } } /* Wrapper for trian */ void train_ensemble ( GentleBoostEnsemble& ens, int collab_on_each ) { ens.train(collab_on_each); ens.train_single(); } /* Implements the core training functionality of the bagged boosting ensemble */ void BaggedBoostingEnsemble::train ( const bool collaboration, const int validation, const bool mt ) { int collab_on_each = (int) (1.0/_opts.p_c); bool after_clb = false; while(_ensembles.back()->get_iteration() < GentleBoostEnsemble::_T) { if(mt) { std::vector<std::thread> threads; for(decltype(_ensembles.size()) e = 0; e < _ensembles.size(); ++e) { threads.push_back(std::thread(&train_ensemble, std::ref(*_ensembles[e]), collab_on_each)); } for(auto&& thr : threads) { if(thr.joinable()) { thr.join(); } } threads.clear(); } else { if(!collaboration && collab_on_each==1) { for(int i = 0; i < collab_on_each && _ensembles.back()->get_iteration() < GentleBoostEnsemble::_T; i++) { for(decltype(_ensembles.size()) e = 0; e < _ensembles.size(); ++e) { _ensembles[e]->train_single(); _ensembles[e]->set_iteration(_ensembles[e]->get_iteration() + 1); } double er, et; // usde sq.err.min as default for debugging if(validation == SQUARED_ERROR_MINIMIZATION) { validate(SQUARED_ERROR_MINIMIZATION); er = compute_error_rate_real(*_opts.train_data, *_opts.train_labels); et = compute_error_rate_real(*_opts.test_data, *_opts.test_labels); } else if(validation == DIVERSITY_MAXIMIZATION) { // validate(DIVERSITY_MAXIMIZATION); // er = compute_error_rate_real(*_opts.train_data, *_opts.train_labels); // et = compute_error_rate_real(*_opts.test_data, *_opts.test_labels); } else { //report_errors_real(); er = compute_error_rate_real(*_opts.train_data, *_opts.train_labels); et = compute_error_rate_real(*_opts.test_data, *_opts.test_labels); } for(decltype(_ensembles.size()) e = 0; e < _ensembles.size(); ++e) _ensembles[e]->set_weight(1.0); std::cout << er << "," << et << "|"; report_errors_discrete(); } } for(int i = 0; i < collab_on_each - 1 && _ensembles.back()->get_iteration() < GentleBoostEnsemble::_T; i++) { for(decltype(_ensembles.size()) e = 0; e < _ensembles.size(); ++e) { _ensembles[e]->train_single_no_update(); _ensembles[e]->update_and_normalize_weights(); //ova za stability da se trgne _ensembles[e]->set_iteration(_ensembles[e]->get_iteration() + 1); } // std::cout << "Before: " << compute_stability(0) << std::endl; if(collaboration) { if(validation == SQUARED_ERROR_MINIMIZATION) { validate(SQUARED_ERROR_MINIMIZATION); report_errors_real(); } else if(validation == DIVERSITY_MAXIMIZATION) { // validate(DIVERSITY_MAXIMIZATION); // report_errors_real(); } else{ report_errors_real(); double s = 0.0; // for(decltype(_ensembles.size()) e = 0; e < _ensembles.size(); ++e) // s+= arma::sum(arma::exp(-1.0 * _ensembles[e]->compute_margins())); // std::cout << s; // if(after_clb) { // std::cout << " Iteration after M-CLB" << std::endl; // after_clb = false; // } // else std::cout << std::endl; } } else { double er, et; // usde sq.err.min as default for debugging if(validation == SQUARED_ERROR_MINIMIZATION) { validate(SQUARED_ERROR_MINIMIZATION); er = compute_error_rate_real(*_opts.train_data, *_opts.train_labels); et = compute_error_rate_real(*_opts.test_data, *_opts.test_labels); } else if(validation == DIVERSITY_MAXIMIZATION) { // validate(DIVERSITY_MAXIMIZATION); // er = compute_error_rate_real(*_opts.train_data, *_opts.train_labels); // et = compute_error_rate_real(*_opts.test_data, *_opts.test_labels); } else { er = compute_error_rate_real(*_opts.train_data, *_opts.train_labels); et = compute_error_rate_real(*_opts.test_data, *_opts.test_labels); // report_errors_real(); } for(decltype(_ensembles.size()) e = 0; e < _ensembles.size(); ++e) _ensembles[e]->set_weight(1.0); // bidejki gore se mesti na slednata iteracija, a stability po greska ke zeme od taa // if((_ensembles[0]->get_iteration()) % collab_on_each == 0) { // // fix because iteration in B_GB is updated earlier // _ensembles[0]->set_iteration(_ensembles[0]->get_iteration()-1); // // double stability = compute_stability(0); // _ensembles[0]->set_iteration(_ensembles[0]->get_iteration()+1); // // std::cout << "Stability/Emp: " << stability << "," << compute_mean_emp_loss() << std::endl; // } std::cout << er << "," << et << "|"; report_errors_discrete(); } // // update and normalize weights as a last step (we need this to compute stability correctly) // for(decltype(_ensembles.size()) e = 0; e < _ensembles.size(); ++e) { // _ensembles[e]->set_iteration(_ensembles[e]->get_iteration()-1); // _ensembles[e]->update_and_normalize_weights(); // _ensembles[e]->set_iteration(_ensembles[e]->get_iteration()+1); // } } } if(collaboration) { double emp_before = -1; if(!mt) { for(decltype(_ensembles.size()) e = 0; e < _ensembles.size(); ++e) { _ensembles[e]->train_single_no_update(); // _ensembles[e]->set_iteration(_ensembles[e]->get_iteration() -1); // ova e poradi emp loss // _ensembles[e]->set_iteration(_ensembles[e]->get_iteration() + 1); } // ova e poradi emp loss // emp_before = compute_mean_emp_loss(); // for(decltype(_ensembles.size()) e = 0; e < _ensembles.size(); ++e) { // _ensembles[e]->set_iteration(_ensembles[e]->get_iteration() -1); // } } // save // std::vector<Matrix> old_x; // std::vector<Vector> old_y; // std::vector<Vector> x_weights_for_next; // // for(int e = 0; e < _ensembles.size(); e++) { // old_x.push_back(_ensembles[e]->get_x_copy()); // old_y.push_back(_ensembles[e]->get_y_copy()); // Vector w = _ensembles[e]->get_x_weights_copy(); // w = w % arma::exp(-1.0 * _ensembles[e]->get_base_learners()[_ensembles[e]->get_iteration()]->compute_margins()); // w /= arma::sum(w); // x_weights_for_next.push_back(w); // // } // COLLABORATION // double stability_before = compute_stability(0); collaborate_exp(); // double stability_after = compute_stability(0); for(decltype(_ensembles.size()) e = 0; e < _ensembles.size(); ++e) { // _ensembles[e]->set_x(old_x[e]); // _ensembles[e]->set_y(old_y[e]); // _ensembles[e]->set_x_weights(x_weights_for_next[e]); _ensembles[e]->update_and_normalize_weights(); _ensembles[e]->set_iteration(_ensembles[e]->get_iteration() + 1); after_clb = true; } // double emp_after = compute_mean_emp_loss(); // std::cout << "Stability: " << stability_before << "," << stability_after; // std::cout<< " EmpErr: " << emp_before << "," << emp_after << std::endl; if(validation == SQUARED_ERROR_MINIMIZATION) { validate(SQUARED_ERROR_MINIMIZATION); report_errors_real(); } else if(validation == DIVERSITY_MAXIMIZATION) { // validate(DIVERSITY_MAXIMIZATION); // report_errors_real(); } else { report_errors_real(); // double s = 0.0; // for(decltype(_ensembles.size()) e = 0; e < _ensembles.size(); ++e) // s+= arma::sum(arma::exp(-1.0 * _ensembles[e]->compute_margins())); // std::cout << s << " M-CLB" << std::endl; } } } } // void BaggedBoostingEnsemble::train ( const bool collaboration, const int validation, const bool mt ) { // // int collab_on_each = (int) (1.0/_opts.p_c); // // bool after_clb = false; // // while(_ensembles.back()->get_iteration() < GentleBoostEnsemble::_T) { // // if(mt) { // std::vector<std::thread> threads; // // for(decltype(_ensembles.size()) e = 0; e < _ensembles.size(); ++e) { // threads.push_back(std::thread(&train_ensemble, std::ref(*_ensembles[e]), collab_on_each)); // } // // for(auto&& thr : threads) { // if(thr.joinable()) { // thr.join(); // } // } // // threads.clear(); // } // else { // if(!collaboration && collab_on_each==1) { // for(int i = 0; i < collab_on_each && _ensembles.back()->get_iteration() < GentleBoostEnsemble::_T; i++) { // // for(decltype(_ensembles.size()) e = 0; e < _ensembles.size(); ++e) { // _ensembles[e]->train_single(); // //_ensembles[e]->set_iteration(_ensembles[e]->get_iteration() + 1); // } // // double er, et; // // usde sq.err.min as default for debugging // if(validation == SQUARED_ERROR_MINIMIZATION) { // validate(SQUARED_ERROR_MINIMIZATION); // er = compute_error_rate_real(*_opts.train_data, *_opts.train_labels); // et = compute_error_rate_real(*_opts.test_data, *_opts.test_labels); // } // else if(validation == DIVERSITY_MAXIMIZATION) { // // validate(DIVERSITY_MAXIMIZATION); // // er = compute_error_rate_real(*_opts.train_data, *_opts.train_labels); // // et = compute_error_rate_real(*_opts.test_data, *_opts.test_labels); // } // else { // //report_errors_real(); // er = compute_error_rate_real(*_opts.train_data, *_opts.train_labels); // et = compute_error_rate_real(*_opts.test_data, *_opts.test_labels); // } // // // // for(decltype(_ensembles.size()) e = 0; e < _ensembles.size(); ++e) // _ensembles[e]->set_weight(1.0); // // std::cout << er << "," << et << "|"; // // report_errors_discrete(); // } // } // for(int i = 0; i < collab_on_each - 1 && _ensembles.back()->get_iteration() < GentleBoostEnsemble::_T; i++) { // // for(decltype(_ensembles.size()) e = 0; e < _ensembles.size(); ++e) { // // _ensembles[e]->train_single_no_update(); // // _ensembles[e]->update_and_normalize_weights(); //ova za stability da se trgne // _ensembles[e]->set_iteration(_ensembles[e]->get_iteration() + 1); // // } // // // // if(collaboration) { // if(validation == SQUARED_ERROR_MINIMIZATION) { // validate(SQUARED_ERROR_MINIMIZATION); // // report_errors_real(); // // } // else if(validation == DIVERSITY_MAXIMIZATION) { // // validate(DIVERSITY_MAXIMIZATION); // // report_errors_real(); // } // else{ // // report_errors_real(); // } // } // else { // double er, et; // // usde sq.err.min as default for debugging // if(validation == SQUARED_ERROR_MINIMIZATION) { // validate(SQUARED_ERROR_MINIMIZATION); // er = compute_error_rate_real(*_opts.train_data, *_opts.train_labels); // et = compute_error_rate_real(*_opts.test_data, *_opts.test_labels); // } // else if(validation == DIVERSITY_MAXIMIZATION) { // // validate(DIVERSITY_MAXIMIZATION); // // er = compute_error_rate_real(*_opts.train_data, *_opts.train_labels); // // et = compute_error_rate_real(*_opts.test_data, *_opts.test_labels); // } // else { // er = compute_error_rate_real(*_opts.train_data, *_opts.train_labels); // et = compute_error_rate_real(*_opts.test_data, *_opts.test_labels); // // report_errors_real(); // // } // // for(decltype(_ensembles.size()) e = 0; e < _ensembles.size(); ++e) // _ensembles[e]->set_weight(1.0); // // // bidejki gore se mesti na slednata iteracija, a stability po greska ke zeme od taa // // // if((_ensembles[0]->get_iteration()) % collab_on_each == 0) { // // fix because iteration in B_GB is updated earlier // _ensembles[0]->set_iteration(_ensembles[0]->get_iteration()-1); // double stability = compute_stability(0); // _ensembles[0]->set_iteration(_ensembles[0]->get_iteration()+1); // std::cout << "Stability/Emp: " << stability << "," << compute_mean_emp_loss() << std::endl; // } // // // // // // std::cout << er << "," << et << "|"; // // report_errors_discrete(); // } // // // // update and normalize weights as a last step (we need this to compute stability correctly) // for(decltype(_ensembles.size()) e = 0; e < _ensembles.size(); ++e) { // _ensembles[e]->set_iteration(_ensembles[e]->get_iteration()-1); // _ensembles[e]->update_and_normalize_weights(); // _ensembles[e]->set_iteration(_ensembles[e]->get_iteration()+1); // } // // // } // } // // if(collaboration) { // double emp_before = -1; // if(!mt) { // for(decltype(_ensembles.size()) e = 0; e < _ensembles.size(); ++e) { // _ensembles[e]->train_single_no_update(); // // _ensembles[e]->set_iteration(_ensembles[e]->get_iteration() -1); // // ova e poradi emp loss // _ensembles[e]->set_iteration(_ensembles[e]->get_iteration() + 1); // } // // // ova e poradi emp loss // emp_before = compute_mean_emp_loss(); // for(decltype(_ensembles.size()) e = 0; e < _ensembles.size(); ++e) { // _ensembles[e]->set_iteration(_ensembles[e]->get_iteration() -1); // } // } // // // save // // std::vector<Matrix> old_x; // // std::vector<Vector> old_y; // // std::vector<Vector> x_weights_for_next; // // // // for(int e = 0; e < _ensembles.size(); e++) { // // old_x.push_back(_ensembles[e]->get_x_copy()); // // old_y.push_back(_ensembles[e]->get_y_copy()); // // Vector w = _ensembles[e]->get_x_weights_copy(); // // w = w % arma::exp(-1.0 * _ensembles[e]->get_base_learners()[_ensembles[e]->get_iteration()]->compute_margins()); // // w /= arma::sum(w); // // x_weights_for_next.push_back(w); // // // // } // // // // COLLABORATION // double stability_before = compute_stability(0); // collaborate_exp(); // double stability_after = compute_stability(0); // // for(decltype(_ensembles.size()) e = 0; e < _ensembles.size(); ++e) { // // _ensembles[e]->set_x(old_x[e]); // // _ensembles[e]->set_y(old_y[e]); // // _ensembles[e]->set_x_weights(x_weights_for_next[e]); // _ensembles[e]->update_and_normalize_weights(); // _ensembles[e]->set_iteration(_ensembles[e]->get_iteration() + 1); // after_clb = true; // } // double emp_after = compute_mean_emp_loss(); // std::cout << "Stability: " << stability_before << "," << stability_after; // std::cout<< " EmpErr: " << emp_before << "," << emp_after << std::endl; // // if(validation == SQUARED_ERROR_MINIMIZATION) { // validate(SQUARED_ERROR_MINIMIZATION); // // report_errors_real(); // } // else if(validation == DIVERSITY_MAXIMIZATION) { // // validate(DIVERSITY_MAXIMIZATION); // // report_errors_real(); // } // else { // // report_errors_real(); // // double s = 0.0; // // for(decltype(_ensembles.size()) e = 0; e < _ensembles.size(); ++e) // // s+= arma::sum(arma::exp(-1.0 * _ensembles[e]->compute_margins())); // // std::cout << s << " M-CLB" << std::endl; // } // } // // } // } /* non-member diversity function */ double diversity ( const std::vector<double>& w, std::vector<double>& grad, void* func_data ) { BaggedBoostingEnsemble* ens = (BaggedBoostingEnsemble*) func_data; Matrix margins(ens->_validation_data.n_rows, ens->_opts.n_ensembles); for(decltype(ens->_ensembles.size()) e = 0; e < ens->_ensembles.size(); ++e) { margins.col(e) = ens->_ensembles[e]->compute_margins(ens->_validation_data, ens->_validation_labels); } RowVector w_row(w.size()); for(unsigned int i = 0; i < w_row.size(); ++i) w_row(i) = w[i]; Matrix margins_sigmoid(margins.n_rows, margins.n_cols); for(unsigned int i = 0; i < margins.n_rows; ++i) { RowVector temp = margins.row(i) % w_row; margins_sigmoid.row(i) = arma::sigmoid(temp); } Vector margins_sigmoid_mean = mean(margins_sigmoid, 1); if(!grad.empty()) { for(decltype(grad.size()) i = 0; i < grad.size(); ++i) { Vector inner_sum = arma::zeros<Vector>(ens->_validation_data.n_rows); for(unsigned int j = 0; j < w.size(); ++j) { if(j != i) { inner_sum += ((double)(-2) / (double)(w.size())) * (margins_sigmoid.col(j) - margins_sigmoid_mean) % ( margins.col(i) % (margins_sigmoid.col(i)) % ( (-margins_sigmoid.col(i) + 1.0))); } else { inner_sum += ((double)(2) * ((double)(w.size() - 1))/ (double)(w.size())) * (margins_sigmoid.col(j) - margins_sigmoid_mean) % (margins.col(i) % ( margins_sigmoid.col(i)) % ( (-margins_sigmoid.col(i) + 1.0))); } } grad[i] = (1.0 / (double)(w.size()-1)) * arma::accu(inner_sum); } } double variance = arma::accu(stddev(margins_sigmoid, 0, 1)); return variance; } /* Implements a validation method */ void BaggedBoostingEnsemble::validate ( const int METHOD ) { if(METHOD == SQUARED_ERROR_MINIMIZATION) { // first compute the outputs on the validations set Matrix f_valid(_validation_data.n_rows, _opts.n_ensembles); Matrix G(_opts.n_ensembles, _opts.n_ensembles); Vector b(_opts.n_ensembles); for(decltype(_ensembles.size()) e = 0; e < _ensembles.size(); ++e) { f_valid.col(e) = _ensembles[e]->predict_real(_validation_data); } for(unsigned int j = 0; j < _opts.n_ensembles; ++j) { for(unsigned int k = 0; k < _opts.n_ensembles; ++k) { G(j, k) = dot(f_valid.col(j), f_valid.col(k)); } b(j) = dot(_validation_labels, f_valid.col(j)); } Vector ensemble_weights = arma::solve(G, b); for(decltype(_ensembles.size()) e = 0; e < _ensembles.size(); ++e) { _ensembles[e]->set_weight(ensemble_weights(e)); } return; } } /* Predicts the output labels using real outputs from the gentle boost ensembles */ Vector BaggedBoostingEnsemble::predict_real ( const Matrix& x ) const { Vector y = arma::zeros<Vector>(x.n_rows); for(auto&& ens_ptr : _ensembles) { y += ens_ptr->get_weight() * ens_ptr->predict_real(x); } return arma::sign(y); } Vector BaggedBoostingEnsemble::compute_margins( const Matrix& x, const Vector& y ) const { Vector o = arma::zeros<Vector>(x.n_rows); for(auto&& ens_ptr : _ensembles) { o += ens_ptr->get_weight() * ens_ptr->predict_real(x); } return y % o; } /* Predicts the output labels using discrete outputs from the gentle boost ensembles */ Vector BaggedBoostingEnsemble::predict_discrete ( const Matrix& x ) const { Vector y = arma::zeros<Vector>(x.n_rows); for(auto&& ens_ptr : _ensembles) { y += ens_ptr->get_weight() * ens_ptr->predict_discrete(x); } return sign(y); } /* Computes the error (misclassification rate) in percent */ double BaggedBoostingEnsemble::compute_error_rate_real ( const Matrix& x, const Vector& y ) const { Vector f = predict_real(x); int misclassified = sum(f != y); return ((double) misclassified / (double) y.n_elem); } /* Computes the error (misclassification rate) in percent */ double BaggedBoostingEnsemble::compute_error_rate_discrete ( const Matrix& x, const Vector& y ) const { Vector f = predict_discrete(x); int misclassified = sum(f != y); return ((double) misclassified / (double) y.n_elem); } /* Reports errors to the standard output */ void BaggedBoostingEnsemble::report_errors_discrete ( ) { if(_opts.train_data != nullptr && _opts.train_labels != nullptr) { double train_err = compute_error_rate_discrete(*_opts.train_data, *_opts.train_labels); std::cout << train_err << ","; } if(_opts.test_data != nullptr && _opts.test_labels != nullptr) { double test_err = compute_error_rate_discrete(*_opts.test_data, *_opts.test_labels); std::cout << test_err << std::endl; } } void BaggedBoostingEnsemble::report_errors_real ( ) { if(_opts.train_data != nullptr && _opts.train_labels != nullptr) { double train_err = compute_error_rate_real(*_opts.train_data, *_opts.train_labels); std::cout << train_err << ","; } if(_opts.test_data != nullptr && _opts.test_labels != nullptr) { double test_err = compute_error_rate_real(*_opts.test_data, *_opts.test_labels); std::cout << test_err << std::endl; } } /* Implements the inter-ensemble collaboration procedure */ // void BaggedBoostingEnsemble::collaborate ( ) { // std::vector<std::vector<unsigned int>> max_margin_indices( // _opts.instances_to_exchange); // Matrix max_margins(_opts.instances_to_exchange, _opts.n_ensembles); // // for(auto&& i : max_margin_indices) { // i = std::vector<unsigned int>(_opts.n_ensembles); // } // // for(decltype(_ensembles.size()) j = 0; j < _ensembles.size(); ++j) { // // Vector weights_for_margins = _ensembles[j]->get_x_weights(); // // Vector margins = _ensembles[j]->get_base_learners() // [_ensembles[j]->get_iteration()]->compute_margins(); // // Vector weighted_margins = weights_for_margins % (margins); // // int to_exch = 0; // while(to_exch < _opts.instances_to_exchange) { // max_margins(to_exch, j) = weighted_margins.max(max_margin_indices[to_exch][j]); // weighted_margins(max_margin_indices[to_exch][j]) = // (double)(std::numeric_limits<double>::min()); // to_exch++; // } // } // // // list of removed instances // Matrix LOR(_opts.n_ensembles * _opts.instances_to_exchange, // _ensembles[0]->get_x().n_cols); // Vector LOR_y(_opts.n_ensembles * _opts.instances_to_exchange); // std::vector<int> index_of; // std::vector<double> weight_of; // std::vector<int> subset_of; // int row_ind = 0; // for(decltype(max_margin_indices[0].size()) j = 0; j < max_margin_indices[0]. // size(); ++j) { // for(decltype(max_margin_indices.size()) i = 0; i < max_margin_indices. // size(); ++i) { // // LOR.row(row_ind) = _ensembles[j]->get_x().row( // max_margin_indices[i][j]); // LOR_y(row_ind) = _ensembles[j]->get_y()(max_margin_indices[i][j]); // index_of.push_back(max_margin_indices[i][j]); // subset_of.push_back(j); // weight_of.push_back(_ensembles[j]->get_x_weights()(max_margin_indices[i][j])); // row_ind++; // } // } // // // remove the rows from each subset // Matrix removed_weights(_opts.instances_to_exchange, _opts.n_ensembles); // // for(decltype(max_margin_indices[0].size()) j = 0; j < max_margin_indices[0]. // size(); ++j) { // std::vector<int> j_th_rows; // for(decltype(max_margin_indices.size()) i = 0; i < max_margin_indices. // size(); ++i) { // j_th_rows.push_back(max_margin_indices[i][j]); // } // // sort the indices in descending order // std::sort(j_th_rows.begin(), j_th_rows.end(), std::greater<int>()); // // remove the rows // // for(auto ind_to_remove : j_th_rows) { // remove_row(_ensembles[j]->get_x_nonconst(), ind_to_remove); // remove_coeff(_ensembles[j]->get_y_nonconst(), ind_to_remove); // remove_coeff(_ensembles[j]->get_x_weights_nonconst(),ind_to_remove); // } // } // // // re-train the current weak learner in each ensemble // for(decltype(_ensembles.size()) e = 0; e < _ensembles.size(); ++e) { // // _ensembles[e]->normalize_weights(); // // _ensembles[e]->retrain_current(); // } // // // // // at this point, each ensemble must receive exactly 'instances_to_exchange' // // new, unseen instances from any of the rest in LOR // std::vector<int> num_received(_ensembles.size(), 0); // std::vector<bool> is_taken(LOR.n_rows, false); // Vector new_min_margins(_ensembles.size()); // // for(decltype(_ensembles.size()) e = 0; e < _ensembles.size(); ++e) { // // recalculate the minimum weighted margins for each ensemble (weak) // Vector weights_for_margins = _ensembles[e]->get_x_weights(); // // Vector margins = _ensembles[e]->get_base_learners() // [_ensembles[e]->get_iteration()]->compute_margins(); // // // // Vector weighted_margins = weights_for_margins % (margins); // // double min_margin = weighted_margins.max(); // new_min_margins(e) = min_margin; // // // now, the e-th ensemble tries to get at most 'instances_to_exchange' // // new instances // for(unsigned int i = 0; i < LOR.n_rows && num_received[e] < // _opts.instances_to_exchange; ++i) // { // if((unsigned)subset_of[i] != e) { // // compute the margin of the instance as a test instance with // // an estimated uniform weight // double margin = _ensembles[e]->get_base_learners() // [_ensembles[e]->get_iteration()]->compute_margin( // LOR.row(i), LOR_y(i)); // // // estimated normalized weight upon adding the instance // double weight = weight_of[i]; // // // margin *= weight; // // if(margin <= (min_margin + (double)( // std::numeric_limits<double>::epsilon()))) { // // // take the instance // append_row(_ensembles[e]->get_x_nonconst(), LOR.row(i)); // append_coeff(_ensembles[e]->get_y_nonconst(), LOR_y(i)); // append_coeff(_ensembles[e]->get_x_weights_nonconst(), // 1.0 / // (double)(_ensembles[e]->get_x().n_rows + // _opts.instances_to_exchange - (num_received[e] + 1))); // // ++num_received[e]; // is_taken[i] = true; // } // } // } // } // // // // at this point, all untaken instances are redistributed to a best-fit ens. // // for(unsigned int i = 0; i < LOR.n_rows; ++i) { // if(!is_taken[i]) { // // decltype(_ensembles.size()) best_fit_e = -1; // double best_offset = MAX_MP; // // for(decltype(_ensembles.size()) e = 0; e < _ensembles.size(); ++e) { // if(num_received[e] < _opts.instances_to_exchange) { // // double margin = _ensembles[e]-> // get_base_learners()[_ensembles[e]->get_iteration()]-> // compute_margin(LOR.row(i), LOR_y(i)); // // // estimated normalized weight upon adding the instance // double weight = weight_of[i]; // // margin *= weight; // // // if(margin - new_min_margins(e) < best_offset) { // best_offset = new_min_margins(e) - margin; // best_fit_e = e; // } // } // } // // // add the instance to the best-fit ensemble (if possible) // if(best_fit_e != -1) { // append_row(_ensembles[best_fit_e]->get_x_nonconst(), LOR.row(i)); // append_coeff(_ensembles[best_fit_e]->get_y_nonconst(), LOR_y(i)); // append_coeff(_ensembles[best_fit_e]->get_x_weights_nonconst(),removed_weights(i, best_fit_e)); // // is_taken[i] = true; // ++num_received[best_fit_e]; // } // } // } // // // re-train the current weak learner in each ensemble and prepare for next i // for(decltype(_ensembles.size()) e = 0; e < _ensembles.size(); ++e) { // _ensembles[e]->update_max(); // _ensembles[e]->normalize_weights(); // _ensembles[e]->train_single(); // _ensembles[e]->set_iteration(_ensembles[e]->get_iteration() + 1); // } // }
37.801329
177
0.522708
[ "vector" ]
a5da21f8571f823f54b0470e2adc99743a96ae68
2,108
cpp
C++
version1.0/REX_TO_DFA/REX_TO_DFA/main.cpp
henry-bugfree/regex_to_nfa_to_dfa_to_minimizedDfa
4e4cba6b8145649d3e153ad97e6e7a58357c7447
[ "MIT" ]
null
null
null
version1.0/REX_TO_DFA/REX_TO_DFA/main.cpp
henry-bugfree/regex_to_nfa_to_dfa_to_minimizedDfa
4e4cba6b8145649d3e153ad97e6e7a58357c7447
[ "MIT" ]
null
null
null
version1.0/REX_TO_DFA/REX_TO_DFA/main.cpp
henry-bugfree/regex_to_nfa_to_dfa_to_minimizedDfa
4e4cba6b8145649d3e153ad97e6e7a58357c7447
[ "MIT" ]
null
null
null
#include"graph.h" #include"rex_to_rpn.h" #include"nfa_to_dfa.h" #include"main.h" #include"rpn_to_nfa.h" #include"nfa_to_dfa.h" #include"minimize_dfa.h" using namespace std; #define MAX_REX_SIZE 100 #define TEST_NUM 5 stack<graph> temp_nfa_stack; extern vector<char> rpn_vector; extern stack<char> rpn_op_stack; extern vector<char> tran_char_vector; extern vector<int> set_search_vector; extern stack<int> set_search_stack; extern vector<new_node> new_node_vector_spt; extern vector<new_node> new_node_vector; extern vector<int> better_prt_vector; extern vector<int> m_set; extern vector<int> m_set1; extern vector<int> m_set2; extern vector<vector<int> > spt_set_vector; int main() { FILE* input; FILE* output; freopen_s(&input, "input.txt", "r", stdin); freopen_s(&output, "output.txt", "w", stdout); for (int i = 0; i < TEST_NUM; i++) { solve(i); reset(); cout << endl; } fclose(stdin); return 0; } int solve(int i) { //declare graph_nfa graph graph_nfa; //input regular expression char rex[MAX_REX_SIZE]; cin >> rex; cout << "test" << i << ":" << endl << "regular expression: " << rex << endl; int rex_len = (int)strlen(rex); //rex to rpn if (rpn_check(to_rpn(rex, rex_len)) == false) return 1; print_rnp(); //rpn to nfa rpn_to_nfa(); graph_nfa = temp_nfa_stack.top(); temp_nfa_stack.pop(); //print nfa print_nfa(graph_nfa); //nfa to dfa dfa_graph dfa; get_tran_char(rex, rex_len); if (nfa_to_dfa(graph_nfa, &dfa) == -2) return 1; print_dfa(&dfa); //minimize dfa minimize_dfa(&dfa); cout << endl; return 0; } int reset(void) { while(!temp_nfa_stack.empty()) temp_nfa_stack.pop(); while (!rpn_op_stack.empty()) rpn_op_stack.pop(); while (!set_search_stack.empty()) set_search_stack.pop(); rpn_vector.clear(); tran_char_vector.clear(); set_search_vector.clear(); new_node_vector_spt.clear(); new_node_vector.clear(); better_prt_vector.clear(); m_set.clear(); m_set1.clear(); m_set2.clear(); spt_set_vector.clear(); return 0; }
20.466019
78
0.673624
[ "vector" ]
777ed40514b05144dd8bf67389ba50fa50cd771d
34,176
hpp
C++
src/fuml/src_gen/fUML/FUMLFactory.hpp
dataliz9r/MDE4CPP
9c5ce01c800fb754c371f1a67f648366eeabae49
[ "MIT" ]
null
null
null
src/fuml/src_gen/fUML/FUMLFactory.hpp
dataliz9r/MDE4CPP
9c5ce01c800fb754c371f1a67f648366eeabae49
[ "MIT" ]
null
null
null
src/fuml/src_gen/fUML/FUMLFactory.hpp
dataliz9r/MDE4CPP
9c5ce01c800fb754c371f1a67f648366eeabae49
[ "MIT" ]
null
null
null
//******************************************************************** //* //* Warning: This file was generated by ecore4CPP Generator //* //******************************************************************** #ifndef FUMLFACTORY_HPP #define FUMLFACTORY_HPP #include <map> #include <memory> #include "ecore/EFactory.hpp" namespace fUML { class FUMLPackage; } namespace fUML::Semantics::Actions { class AcceptCallActionActivation; class AcceptCallActionActivations; class AcceptEventActionActivation; class AcceptEventActionEventAccepter; class ActionActivation; class AddStructuralFeatureValueActionActivation; class CallActionActivation; class CallBehaviorActionActivation; class CallOperationActionActivation; class ClauseActivation; class ClearAssociationActionActivation; class ClearStructuralFeatureActionActivation; class ConditionalNodeActivation; class CreateLinkActionActivation; class CreateObjectActionActivation; class DestroyLinkActionActivation; class DestroyObjectActionActivation; class InputPinActivation; class InvocationActionActivation; class LinkActionActivation; class LoopNodeActivation; class OutputPinActivation; class PinActivation; class ReadExtentActionActivation; class ReadIsClassifiedObjectActionActivation; class ReadLinkActionActivation; class ReadSelfActionActivation; class ReadStructuralFeatureActionActivation; class ReclassifyObjectActionActivation; class ReduceActionActivation; class RemoveStructuralFeatureValueActivation; class ReplyActionActivation; class ReturnInformation; class SendSignalActionActivation; class StartClassifierBehaviorActionActivation; class StartObjectBehaviorActionActivation; class StructuralFeatureActionActivation; class StructuredActivityNodeActivation; class TestIdentityActionActivation; class ValueSpecificationActionActivation; class Values; class WriteLinkActionActivation; class WriteStructuralFeatureActionActivation; } namespace fUML::Semantics::Activities { class ActivityNodeActivationGroup; } namespace fUML::Semantics::Activities { class ActivityEdgeInstance; class ActivityExecution; class ActivityFinalNodeActivation; class ActivityNodeActivation; class ActivityNodeActivationGroup; class ActivityParameterNodeActivation; class CentralBufferNodeActivation; class ClassifierBehaviorExecutionActivity; class ClassifierBehaviorExecutionActivity_OwnedBehaviorActivity1; class ControlNodeActivation; class ControlToken; class DataStoreNodeActivation; class DecisionNodeActivation; class ExpansionActivationGroup; class ExpansionNodeActivation; class ExpansionRegionActivation; class FlowFinalNodeActivation; class ForkNodeActivation; class ForkedToken; class InitialNodeActivation; class JoinNodeActivation; class MergeNodeActivation; class ObjectNodeActivation; class ObjectToken; class Offer; class Token; class TokenSet; } namespace fUML::Semantics::Activities { class ActivityExecution; } namespace fUML::Semantics::Actions { class StructuredActivityNodeActivation; } namespace fUML::Semantics::Activities { class ActivityNodeActivationGroup; } namespace fUML::Semantics::Activities { class ActivityNodeActivationGroup; } namespace fUML::Semantics::Classification { class InstanceValueEvaluation; } namespace fUML::Semantics::CommonBehavior { class CallEventBehavior; class CallEventExecution; class CallEventOccurrence; class ClassifierBehaviorExecution; class ClassifierBehaviorInvocationEventAccepter; class EventAccepter; class EventDispatchLoop; class EventOccurrence; class Execution; class FIFOGetNextEventStrategy; class GetNextEventStrategy; class InvocationEventOccurrence; class ObjectActivation; class OpaqueBehaviorExecution; class ParameterValue; class SignalEventOccurrence; } namespace fUML::Semantics::Loci { class ChoiceStrategy; class ExecutionFactory; class Executor; class FirstChoiceStrategy; class Locus; class SemanticStrategy; class SemanticVisitor; } namespace fUML::Semantics::Loci { class Locus; } namespace fUML::Semantics::Loci { class Locus; } namespace fUML::Semantics::SimpleClassifiers { class BooleanValue; class CompoundValue; class DataValue; class EnumerationValue; class FeatureValue; class IntegerValue; class PrimitiveValue; class RealValue; class SignalInstance; class StringValue; class StructuredValue; class UnlimitedNaturalValue; } namespace fUML::Semantics::StructuredClassifiers { class DispatchStrategy; class ExtensionalValue; class ExtensionalValueList; class Link; class Object; class RedefinitionBasedDispatchStrategy; class Reference; } namespace fUML::Semantics::Values { class Evaluation; class LiteralBooleanEvaluation; class LiteralEvaluation; class LiteralIntegerEvaluation; class LiteralNullEvaluation; class LiteralRealEvaluation; class LiteralStringEvaluation; class LiteralUnlimitedNaturalEvaluation; class Value; } namespace fUML { class FUMLFactory : virtual public ecore::EFactory { private: FUMLFactory(FUMLFactory const&) = delete; FUMLFactory& operator=(FUMLFactory const&) = delete; protected: FUMLFactory(){} //Singleton Instance and Getter private: static std::shared_ptr<FUMLFactory> instance; public: static std::shared_ptr<FUMLFactory> eInstance(); //Creator functions virtual std::shared_ptr<ecore::EObject> create(std::string _className, std::shared_ptr<ecore::EObject> container=nullptr, const int referenceID = -1) const = 0; virtual std::shared_ptr<ecore::EObject> create(const int classID, std::shared_ptr<ecore::EObject> container = nullptr, const int referenceID = -1) const = 0; virtual std::shared_ptr<ecore::EObject> create(std::shared_ptr<ecore::EClass> _class, std::shared_ptr<EObject> _container=nullptr, const int referenceID = -1) const = 0; virtual std::shared_ptr<fUML::Semantics::Actions::AcceptCallActionActivation> createAcceptCallActionActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Actions::AcceptCallActionActivation> createAcceptCallActionActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Actions::AcceptCallActionActivations> createAcceptCallActionActivations(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Actions::AcceptEventActionActivation> createAcceptEventActionActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Actions::AcceptEventActionActivation> createAcceptEventActionActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Actions::AcceptEventActionEventAccepter> createAcceptEventActionEventAccepter(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Activities::ActivityEdgeInstance> createActivityEdgeInstance(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Activities::ActivityEdgeInstance> createActivityEdgeInstance_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Activities::ActivityExecution> createActivityExecution(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Activities::ActivityFinalNodeActivation> createActivityFinalNodeActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Activities::ActivityFinalNodeActivation> createActivityFinalNodeActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup> createActivityNodeActivationGroup(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup> createActivityNodeActivationGroup_in_ActivityExecution(std::weak_ptr<fUML::Semantics::Activities::ActivityExecution > par_activityExecution, const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup> createActivityNodeActivationGroup_in_ContainingNodeActivation(std::weak_ptr<fUML::Semantics::Actions::StructuredActivityNodeActivation > par_containingNodeActivation, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Activities::ActivityParameterNodeActivation> createActivityParameterNodeActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Activities::ActivityParameterNodeActivation> createActivityParameterNodeActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Actions::AddStructuralFeatureValueActionActivation> createAddStructuralFeatureValueActionActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Actions::AddStructuralFeatureValueActionActivation> createAddStructuralFeatureValueActionActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::SimpleClassifiers::BooleanValue> createBooleanValue(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Actions::CallBehaviorActionActivation> createCallBehaviorActionActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Actions::CallBehaviorActionActivation> createCallBehaviorActionActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::CommonBehavior::CallEventBehavior> createCallEventBehavior(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::CommonBehavior::CallEventExecution> createCallEventExecution(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::CommonBehavior::CallEventOccurrence> createCallEventOccurrence(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Actions::CallOperationActionActivation> createCallOperationActionActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Actions::CallOperationActionActivation> createCallOperationActionActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Activities::CentralBufferNodeActivation> createCentralBufferNodeActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Activities::CentralBufferNodeActivation> createCentralBufferNodeActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::CommonBehavior::ClassifierBehaviorExecution> createClassifierBehaviorExecution(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Activities::ClassifierBehaviorExecutionActivity> createClassifierBehaviorExecutionActivity(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Activities::ClassifierBehaviorExecutionActivity_OwnedBehaviorActivity1> createClassifierBehaviorExecutionActivity_OwnedBehaviorActivity1(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::CommonBehavior::ClassifierBehaviorInvocationEventAccepter> createClassifierBehaviorInvocationEventAccepter(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Actions::ClauseActivation> createClauseActivation(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Actions::ClearAssociationActionActivation> createClearAssociationActionActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Actions::ClearAssociationActionActivation> createClearAssociationActionActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Actions::ClearStructuralFeatureActionActivation> createClearStructuralFeatureActionActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Actions::ClearStructuralFeatureActionActivation> createClearStructuralFeatureActionActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Actions::ConditionalNodeActivation> createConditionalNodeActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Actions::ConditionalNodeActivation> createConditionalNodeActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Activities::ControlToken> createControlToken(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Actions::CreateLinkActionActivation> createCreateLinkActionActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Actions::CreateLinkActionActivation> createCreateLinkActionActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Actions::CreateObjectActionActivation> createCreateObjectActionActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Actions::CreateObjectActionActivation> createCreateObjectActionActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Activities::DataStoreNodeActivation> createDataStoreNodeActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Activities::DataStoreNodeActivation> createDataStoreNodeActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::SimpleClassifiers::DataValue> createDataValue(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Activities::DecisionNodeActivation> createDecisionNodeActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Activities::DecisionNodeActivation> createDecisionNodeActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Actions::DestroyLinkActionActivation> createDestroyLinkActionActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Actions::DestroyLinkActionActivation> createDestroyLinkActionActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Actions::DestroyObjectActionActivation> createDestroyObjectActionActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Actions::DestroyObjectActionActivation> createDestroyObjectActionActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::StructuredClassifiers::DispatchStrategy> createDispatchStrategy(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::SimpleClassifiers::EnumerationValue> createEnumerationValue(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::CommonBehavior::EventDispatchLoop> createEventDispatchLoop(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::CommonBehavior::EventOccurrence> createEventOccurrence(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Loci::ExecutionFactory> createExecutionFactory(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Loci::ExecutionFactory> createExecutionFactory_in_Locus(std::weak_ptr<fUML::Semantics::Loci::Locus > par_locus, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Loci::Executor> createExecutor(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Loci::Executor> createExecutor_in_Locus(std::weak_ptr<fUML::Semantics::Loci::Locus > par_locus, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Activities::ExpansionActivationGroup> createExpansionActivationGroup(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Activities::ExpansionActivationGroup> createExpansionActivationGroup_in_ActivityExecution(std::weak_ptr<fUML::Semantics::Activities::ActivityExecution > par_activityExecution, const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Activities::ExpansionActivationGroup> createExpansionActivationGroup_in_ContainingNodeActivation(std::weak_ptr<fUML::Semantics::Actions::StructuredActivityNodeActivation > par_containingNodeActivation, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Activities::ExpansionNodeActivation> createExpansionNodeActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Activities::ExpansionNodeActivation> createExpansionNodeActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Activities::ExpansionRegionActivation> createExpansionRegionActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Activities::ExpansionRegionActivation> createExpansionRegionActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::StructuredClassifiers::ExtensionalValueList> createExtensionalValueList(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::CommonBehavior::FIFOGetNextEventStrategy> createFIFOGetNextEventStrategy(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::SimpleClassifiers::FeatureValue> createFeatureValue(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Loci::FirstChoiceStrategy> createFirstChoiceStrategy(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Activities::FlowFinalNodeActivation> createFlowFinalNodeActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Activities::FlowFinalNodeActivation> createFlowFinalNodeActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Activities::ForkNodeActivation> createForkNodeActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Activities::ForkNodeActivation> createForkNodeActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Activities::ForkedToken> createForkedToken(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Activities::InitialNodeActivation> createInitialNodeActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Activities::InitialNodeActivation> createInitialNodeActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Actions::InputPinActivation> createInputPinActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Actions::InputPinActivation> createInputPinActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Classification::InstanceValueEvaluation> createInstanceValueEvaluation(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::SimpleClassifiers::IntegerValue> createIntegerValue(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::CommonBehavior::InvocationEventOccurrence> createInvocationEventOccurrence(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Activities::JoinNodeActivation> createJoinNodeActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Activities::JoinNodeActivation> createJoinNodeActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::StructuredClassifiers::Link> createLink(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Values::LiteralBooleanEvaluation> createLiteralBooleanEvaluation(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Values::LiteralIntegerEvaluation> createLiteralIntegerEvaluation(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Values::LiteralNullEvaluation> createLiteralNullEvaluation(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Values::LiteralRealEvaluation> createLiteralRealEvaluation(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Values::LiteralStringEvaluation> createLiteralStringEvaluation(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Values::LiteralUnlimitedNaturalEvaluation> createLiteralUnlimitedNaturalEvaluation(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Loci::Locus> createLocus(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Actions::LoopNodeActivation> createLoopNodeActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Actions::LoopNodeActivation> createLoopNodeActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Activities::MergeNodeActivation> createMergeNodeActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Activities::MergeNodeActivation> createMergeNodeActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::StructuredClassifiers::Object> createObject(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::CommonBehavior::ObjectActivation> createObjectActivation(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Activities::ObjectToken> createObjectToken(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Activities::Offer> createOffer(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Actions::OutputPinActivation> createOutputPinActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Actions::OutputPinActivation> createOutputPinActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::CommonBehavior::ParameterValue> createParameterValue(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Actions::ReadExtentActionActivation> createReadExtentActionActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Actions::ReadExtentActionActivation> createReadExtentActionActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Actions::ReadIsClassifiedObjectActionActivation> createReadIsClassifiedObjectActionActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Actions::ReadIsClassifiedObjectActionActivation> createReadIsClassifiedObjectActionActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Actions::ReadLinkActionActivation> createReadLinkActionActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Actions::ReadLinkActionActivation> createReadLinkActionActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Actions::ReadSelfActionActivation> createReadSelfActionActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Actions::ReadSelfActionActivation> createReadSelfActionActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Actions::ReadStructuralFeatureActionActivation> createReadStructuralFeatureActionActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Actions::ReadStructuralFeatureActionActivation> createReadStructuralFeatureActionActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::SimpleClassifiers::RealValue> createRealValue(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Actions::ReclassifyObjectActionActivation> createReclassifyObjectActionActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Actions::ReclassifyObjectActionActivation> createReclassifyObjectActionActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::StructuredClassifiers::RedefinitionBasedDispatchStrategy> createRedefinitionBasedDispatchStrategy(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Actions::ReduceActionActivation> createReduceActionActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Actions::ReduceActionActivation> createReduceActionActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::StructuredClassifiers::Reference> createReference(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Actions::RemoveStructuralFeatureValueActivation> createRemoveStructuralFeatureValueActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Actions::RemoveStructuralFeatureValueActivation> createRemoveStructuralFeatureValueActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Actions::ReplyActionActivation> createReplyActionActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Actions::ReplyActionActivation> createReplyActionActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Actions::ReturnInformation> createReturnInformation(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Actions::SendSignalActionActivation> createSendSignalActionActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Actions::SendSignalActionActivation> createSendSignalActionActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::CommonBehavior::SignalEventOccurrence> createSignalEventOccurrence(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::SimpleClassifiers::SignalInstance> createSignalInstance(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Actions::StartClassifierBehaviorActionActivation> createStartClassifierBehaviorActionActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Actions::StartClassifierBehaviorActionActivation> createStartClassifierBehaviorActionActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Actions::StartObjectBehaviorActionActivation> createStartObjectBehaviorActionActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Actions::StartObjectBehaviorActionActivation> createStartObjectBehaviorActionActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::SimpleClassifiers::StringValue> createStringValue(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Actions::StructuredActivityNodeActivation> createStructuredActivityNodeActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Actions::StructuredActivityNodeActivation> createStructuredActivityNodeActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Actions::TestIdentityActionActivation> createTestIdentityActionActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Actions::TestIdentityActionActivation> createTestIdentityActionActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Activities::TokenSet> createTokenSet(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::SimpleClassifiers::UnlimitedNaturalValue> createUnlimitedNaturalValue(const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Actions::ValueSpecificationActionActivation> createValueSpecificationActionActivation(const int metaElementID=-1) const = 0; //Add containing object virtual std::shared_ptr<fUML::Semantics::Actions::ValueSpecificationActionActivation> createValueSpecificationActionActivation_in_Group(std::weak_ptr<fUML::Semantics::Activities::ActivityNodeActivationGroup > par_group, const int metaElementID=-1) const = 0; virtual std::shared_ptr<fUML::Semantics::Actions::Values> createValues(const int metaElementID=-1) const = 0; //Package virtual std::shared_ptr<FUMLPackage> getFUMLPackage() const = 0; }; } #endif /* end of include guard: FUMLFACTORY_HPP */
64.727273
290
0.807526
[ "object" ]