hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 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 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7b47036661d4b580854a359716405bc723c25137 | 810 | cpp | C++ | hackerrank/c++/stl/vector_erase.cpp | Rkhoiwal/Competitive-prog-Archive | 18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9 | [
"MIT"
] | 1 | 2020-07-16T01:46:38.000Z | 2020-07-16T01:46:38.000Z | hackerrank/c++/stl/vector_erase.cpp | Rkhoiwal/Competitive-prog-Archive | 18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9 | [
"MIT"
] | null | null | null | hackerrank/c++/stl/vector_erase.cpp | Rkhoiwal/Competitive-prog-Archive | 18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9 | [
"MIT"
] | 1 | 2020-05-27T14:30:43.000Z | 2020-05-27T14:30:43.000Z | #include <iostream>
#include <vector>
using namespace std;
inline
void use_io_optimizations()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
}
int main()
{
use_io_optimizations();
unsigned int length;
cin >> length;
vector<unsigned int> sequence(length);
for (auto& element : sequence)
{
cin >> element;
}
unsigned int index;
unsigned int left;
unsigned int right;
cin >> index >> left >> right;
sequence.erase(sequence.cbegin() + index - 1);
sequence.erase(sequence.cbegin() + left - 1,
sequence.cbegin() + right - 1);
cout << sequence.size() << '\n';
for (auto i = sequence.cbegin(); i != sequence.cend(); ++i)
{
cout << *i << " \n"[i + 1 == sequence.cend()];
}
return 0;
}
| 17.608696 | 63 | 0.569136 | Rkhoiwal |
0da2fba5c2f892c74d3f8f0f7cea5fa22c42a8a3 | 2,703 | cpp | C++ | Chapter_4_Graph/SSSP/kattis_emptyingbaltic.cpp | BrandonTang89/CP4_Code | 5114471f439978dd11f6f2cbf6af20ca654593da | [
"MIT"
] | 2 | 2021-12-29T04:12:59.000Z | 2022-03-30T09:32:19.000Z | Chapter_4_Graph/SSSP/kattis_emptyingbaltic.cpp | BrandonTang89/CP4_Code | 5114471f439978dd11f6f2cbf6af20ca654593da | [
"MIT"
] | null | null | null | Chapter_4_Graph/SSSP/kattis_emptyingbaltic.cpp | BrandonTang89/CP4_Code | 5114471f439978dd11f6f2cbf6af20ca654593da | [
"MIT"
] | 1 | 2022-03-01T06:12:46.000Z | 2022-03-01T06:12:46.000Z | /* kattis - emptyingbaltic
Observation 1:
When considering how much water will eventually be drained from a cell r,c, we realise it is actually
drained until the level of the minimum max height along all paths from r,c to the drain. This is
actually similar to the SSSP principle but instead of minimising distance, we minimise the maximum
height along the path to get to r,c.
So our distance values will all be replaced by "minimum max height to get to r,c". And instead
the the dist to nr, nc being dist(r,c) + w, instead it will be max(grid(nr,nc), ldu(r,c)).
While this problem looks scary cos its some strange variant, once you figure out the observation,
the implementation actually isn't that difficult.
Time: O(hw log hw), Mem: O(hw)
*/
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,fma")
#pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
#define fast_cin() ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
int h, w, s_r, s_c;
vector<vector<int>>grid, ldu; //grid slows elevation, ldu (level drained until) shows how far the water level is drained
int dr[] = {-1, -1, 0, 1, 1, 1, 0, -1};
int dc[] = {0, 1, 1, 1, 0, -1, -1, -1};
priority_queue<tuple<int,int,int>, vector<tuple<int,int,int>>, greater<tuple<int,int,int>>> pq;
int main(){
fast_cin();
cin >> h >> w;
grid.assign(h, vector<int>(w, 0));
ldu.assign(h, vector<int>(w, 0));
for (int r=0;r<h;r++){
for (int c=0;c<w;c++){
cin >> grid[r][c];
grid[r][c] = min(grid[r][c], 0); // we can more or less ignore all heights above 0
}
}
cin >> s_r >> s_c; // starting row and column
s_r--;
s_c--;
pq.emplace(grid[s_r][s_c], s_r, s_c);
ldu[s_r][s_c] = grid[s_r][s_c];
while (!pq.empty()){
auto [d, r, c] = pq.top();
pq.pop();
//printf("d: %d, r: %d, c:%d\n", d, r, c);
if (d > ldu[r][c])continue; // inferior pair
for (int i=0;i<8;i++){
int nc = c + dc[i];
int nr = r + dr[i];
if (nc < 0 || nr < 0 || nc >= w || nr >= h)continue;
if (max(ldu[r][c], grid[nr][nc]) >= ldu[nr][nc])continue; // relaxing through this node doesn't help
ldu[nr][nc] = max(ldu[r][c], grid[nr][nc]);
pq.emplace(ldu[nr][nc], nr, nc);
}
}
ll total = 0;
for (int r=0;r<h;r++){
for (int c=0;c<w;c++){
//cout << ldu[r][c]<< " ";
total -= ldu[r][c];
}
//cout << endl;
}
cout << total << endl;
return 0;
} | 34.653846 | 120 | 0.572327 | BrandonTang89 |
0da5bf18e4e0ca7b2684740e13a4964a656c8332 | 370 | cpp | C++ | 09-Inheritance/06-Gen_Spec.cpp | PronomitaDey/Cpp_Tutorial | a64a10a27d018bf9edf5280505201a1fbfd359ed | [
"MIT"
] | null | null | null | 09-Inheritance/06-Gen_Spec.cpp | PronomitaDey/Cpp_Tutorial | a64a10a27d018bf9edf5280505201a1fbfd359ed | [
"MIT"
] | 1 | 2021-10-01T13:35:44.000Z | 2021-10-02T03:54:29.000Z | 09-Inheritance/06-Gen_Spec.cpp | PronomitaDey/Cpp_Tutorial | a64a10a27d018bf9edf5280505201a1fbfd359ed | [
"MIT"
] | 3 | 2021-10-01T14:07:09.000Z | 2021-10-01T18:24:31.000Z | #include <iostream>
using namespace std;
// Generalization
/*
Shape is not something real whereas Rectangle,
Square and all are so Shape is just a Generalization
of those This is also called as
Polymorphism
*/
// Specialization
/*
Cuboid is an extension of Rectangle So this method is
called specialization
*/
int main()
{
return 0;
} | 16.818182 | 57 | 0.694595 | PronomitaDey |
0da642165d7437a4d49fd5224549f9f7b091fadc | 2,196 | cpp | C++ | Jimmy_Core/source/Sys_Init.cpp | nozsavsev/jimmy | 0be7a153e9c1a2f14710d072fd172ee1b3402742 | [
"Apache-2.0"
] | 1 | 2021-05-17T23:03:14.000Z | 2021-05-17T23:03:14.000Z | Jimmy_Core/source/Sys_Init.cpp | nozsavsev/jimmy | 0be7a153e9c1a2f14710d072fd172ee1b3402742 | [
"Apache-2.0"
] | null | null | null | Jimmy_Core/source/Sys_Init.cpp | nozsavsev/jimmy | 0be7a153e9c1a2f14710d072fd172ee1b3402742 | [
"Apache-2.0"
] | null | null | null | /*Copyright 2020 Nozdrachev Ilia
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 "Jimmy_Core.h"
bool Is_Running_As_Admin()
{
BOOL is_run_as_admin = FALSE;
PSID administrators_group = NULL;
SID_IDENTIFIER_AUTHORITY nt_authority = SECURITY_NT_AUTHORITY;
if (!AllocateAndInitializeSid(&nt_authority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &administrators_group))
{
FreeSid(administrators_group);
return false;
}
else
CheckTokenMembership(NULL, administrators_group, &is_run_as_admin);
FreeSid(administrators_group);
return is_run_as_admin ? true : false;
}
void Sys_Init(int argc, char** argv)
{
if (!Is_Running_As_Admin())
{
MessageBoxW(NULL, L"Jimmy cannot work without administrator privileges\npress Ok to restart winth admin rights", L"Jimmy - accessibility alert", MB_OK | MB_TOPMOST);
{
wchar_t szPath[MAX_PATH];
GetModuleFileNameW(NULL, szPath, MAX_PATH);
SHELLEXECUTEINFO sei = { sizeof(sei) };
sei.lpParameters = L"";
sei.lpVerb = L"runas";
sei.lpFile = szPath;
sei.hwnd = NULL;
sei.nShow = SW_NORMAL;
if (ShellExecuteEx(&sei))
exit(0);
}
}
Log("Admin check OK\n");
CreateMutex(NULL, true, L"JYMMY_GLOBAL_START_MUTEX");
if (GetLastError() == ERROR_ALREADY_EXISTS)
{
Log("Jimmy is alaredy running!\n");
MessageBoxW(NULL, L"Jimmy is alaredy running!", L"Jimmy", MB_OK | MB_TOPMOST);
exit(0);
}
Log("Instance check OK\n");
} | 32.776119 | 174 | 0.651639 | nozsavsev |
0da6a82aa2a526dede29cb766c8cc4d129cc92c6 | 2,513 | cpp | C++ | CameraCtrl.cpp | neil3d/ShadowMappingD3D | fa5c856ae8fb7ee0afa22e70e84c1dd34fbce52f | [
"MIT"
] | 1 | 2019-11-29T01:19:31.000Z | 2019-11-29T01:19:31.000Z | CameraCtrl.cpp | neil3d/ShadowMappingD3D | fa5c856ae8fb7ee0afa22e70e84c1dd34fbce52f | [
"MIT"
] | null | null | null | CameraCtrl.cpp | neil3d/ShadowMappingD3D | fa5c856ae8fb7ee0afa22e70e84c1dd34fbce52f | [
"MIT"
] | null | null | null | #include ".\cameractrl.h"
#include "SGITrackBall.h"
CameraCtrl g_camera;
inline D3DXVECTOR3 operator * (const D3DXVECTOR3& v,const D3DXMATRIX& m)
{
return D3DXVECTOR3(v.x*m._11+v.y*m._21+v.z*m._31+m._41,
v.x*m._12+v.y*m._22+v.z*m._32+m._42,
v.x*m._13+v.y*m._23+v.z*m._33+m._43);
}
CameraCtrl::CameraCtrl(void)
{
D3DXMatrixIdentity(&m_matPrj);
setDefaultView();
m_bDrag = false;
}
CameraCtrl::~CameraCtrl(void)
{
}
void CameraCtrl::setDefaultView()
{
m_lookAt = D3DXVECTOR3(0,0,0);
m_dist = 400;
D3DXQuaternionRotationYawPitchRoll(&m_rotate,0,-D3DX_PI/4,0);
updateViewMat();
}
void CameraCtrl::setPerspective(float fov, int clientW, int clientH, float zNear, float zFar)
{
float aspect = float(clientW)/clientH;
D3DXMatrixPerspectiveFovLH(&m_matPrj, fov, aspect, zNear, zFar);
m_zNear = zNear;
m_zFar = zFar;
}
void CameraCtrl::updateViewMat()
{
D3DXMATRIX matR;
D3DXMatrixRotationQuaternion(&matR,&m_rotate);
D3DXVECTOR3 vViewDir = D3DXVECTOR3(0,0,1);
D3DXVECTOR3 vUp(0,1,0);
vViewDir = vViewDir * matR;
vUp = vUp * matR;
m_eyePos = vViewDir*m_dist + m_lookAt;
D3DXMatrixLookAtLH(&m_matView,&m_eyePos,&m_lookAt,&vUp);
}
void CameraCtrl::onKeyDown(DWORD vk)
{
D3DXVECTOR3 vX(m_matView._11,m_matView._21,m_matView._31);
D3DXVECTOR3 vY(m_matView._12,m_matView._22,m_matView._32);
D3DXVECTOR3 vZ(m_matView._13,m_matView._23,m_matView._33);
float s = 10;
switch(vk)
{
case 'W':
m_lookAt += vZ*s;
break;
case 'S':
m_lookAt -= vZ*s;
break;
case 'A':
m_lookAt += vX*s;
break;
case 'D':
m_lookAt -= vX*s;
break;
case 'Z':
m_lookAt += vY*s;
break;
case 'X':
m_lookAt -= vY*s;
break;
default:
break;
}
updateViewMat();
}
void CameraCtrl::onLButtonDown(int x,int y)
{
m_bDrag = true;
m_lastDragPt.x = x;
m_lastDragPt.y = y;
trackball((float*)m_lastRotate,0,0,0,0);
}
void CameraCtrl::onLbuttonUp()
{
m_bDrag = false;
}
D3DXVECTOR2 _normalize(int x, int y)
{
return D3DXVECTOR2( ( ( 2.0f * x ) / clientWidth ) - 1 ,
-( ( ( 2.0f * y ) / clientHeight ) - 1 ));
}
void CameraCtrl::onMouseMove(int x,int y)
{
if(m_bDrag)
{
D3DXVECTOR2 lastPt = _normalize(m_lastDragPt.x,m_lastDragPt.y);
D3DXVECTOR2 nowPt = _normalize(x,y);
trackball((float*)&m_lastRotate,lastPt.x,lastPt.y,nowPt.x,nowPt.y);
m_lastDragPt.x = x;
m_lastDragPt.y = y;
add_quats((float*)&m_lastRotate,(float*)&m_rotate,(float*)&m_rotate);
updateViewMat();
}
}
void CameraCtrl::onMouseWheel(int delta)
{
m_dist += delta*0.2f;
updateViewMat();
} | 18.477941 | 93 | 0.68842 | neil3d |
0daa96caab68a09d8f1da30958d5760679e5f0e3 | 1,938 | cpp | C++ | graph-source-code/174-D/1509433.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/174-D/1509433.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/174-D/1509433.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | //Language: GNU C++
#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <string.h>
#define rep(i,n) for(int i=0; i<n; i++)
#define reps(i,m,n) for(int i=m; i<n; i++)
#define repe(i,m,n) for(int i=m; i<=n; i++)
#define repi(it,stl) for(typeof((stl).begin()) it = (stl).begin(); (it)!=stl.end(); ++(it))
#define sz(a) ((int)(a).size())
#define mem(a,n) memset((a), (n), sizeof(a))
#define all(n) (n).begin(),(n).end()
#define rall(n) (n).rbegin(),(n).rend()
#define mp(a,b) make_pair((a),(b))
#define pii pair<int,int>
#define vi vector<int>
#define vs vector<string>
#define sstr stringstream
#define fnd(v,x) (find(all((v)),(x))!=(v).end())
#define itr(A,B) typeof(B) A = B
typedef long long ll;
using namespace std;
const int size = 100002;
int states[size];
vi g[size],revg[size];
bool mark1[size],mark2[size];
void DFS(int idx){
mark1[idx] = 1;
// if(states[idx]==2) return;
rep(i,sz(g[idx])){
if(!mark1[g[idx][i]])
DFS(g[idx][i]);
}
}
void DFS2(int idx){
mark2[idx] = 1;
if(states[idx]==1) return;
rep(i,sz(revg[idx])){
if(!mark2[revg[idx][i]])
DFS2(revg[idx][i]);
}
}
int main(){
#ifndef ONLINE_JUDGE
freopen("in","rt",stdin);
freopen("out","wt",stdout);
#endif
int n,m,a,b;
scanf("%d%d",&n,&m);
rep(i,n){
scanf("%d",states+i);
}
rep(i,m){
scanf("%d%d",&a,&b);
--a, --b;
g[a].push_back(b);
revg[b].push_back(a);
}
rep(i,n){
if(states[i]==1) DFS(i);
if(states[i]==2) DFS2(i);
}
rep(i,n)
printf(mark1[i] && mark2[i]?"1\n":"0\n");
}
| 19.188119 | 91 | 0.557276 | AmrARaouf |
0daba5852d634fb454ef7bfa9bfe9b59927befc4 | 867 | cpp | C++ | src/main.cpp | RomainAmuat/apt_project | 520281a09756816f6297e3f35b42bce2ab12973b | [
"MIT"
] | null | null | null | src/main.cpp | RomainAmuat/apt_project | 520281a09756816f6297e3f35b42bce2ab12973b | [
"MIT"
] | null | null | null | src/main.cpp | RomainAmuat/apt_project | 520281a09756816f6297e3f35b42bce2ab12973b | [
"MIT"
] | null | null | null | #include <pistache/http.h>
#include <pistache/description.h>
#include <pistache/endpoint.h>
#include <pistache/serializer/rapidjson.h>
#include "view/ServiceManager.h"
#include "model/MySQLLink.h"
using namespace std;
using namespace Pistache;
int main(int argc, char *argv[]) {
std::string url;
if (argc > 1) {
url = argv[1];
std::cout << "Using MySQL URL given in command line : " << url << std::endl;
}
else {
url = "tcp://127.0.0.1:3306";
}
Port port(9080);
ConMySQL * msql = new ConMySQL(url);
int thr = 2;
Address addr(Ipv4::any(), port);
cout << "Cores = " << hardware_concurrency() << endl;
cout << "Using " << thr << " threads" << endl;
ServiceManager manager(addr, msql);
manager.init(thr);
manager.start();
auto c = getchar();
manager.shutdown();
}
| 19.704545 | 84 | 0.594002 | RomainAmuat |
0dabefa1becca43221ab84ce7c3307441bbbeb58 | 6,550 | cpp | C++ | src/vm/appdomainstack.cpp | CyberSys/coreclr-mono | 83b2cb83b32faa45b4f790237b5c5e259692294a | [
"MIT"
] | 10 | 2015-11-03T16:35:25.000Z | 2021-07-31T16:36:29.000Z | src/vm/appdomainstack.cpp | CyberSys/coreclr-mono | 83b2cb83b32faa45b4f790237b5c5e259692294a | [
"MIT"
] | 1 | 2019-03-05T18:50:09.000Z | 2019-03-05T18:50:09.000Z | src/vm/appdomainstack.cpp | CyberSys/coreclr-mono | 83b2cb83b32faa45b4f790237b5c5e259692294a | [
"MIT"
] | 4 | 2015-10-28T12:26:26.000Z | 2021-09-04T11:36:04.000Z | //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
//
//
#include "common.h"
#include "appdomainstack.h"
#include "appdomainstack.inl"
#include "security.h"
#include "securitypolicy.h"
#include "appdomain.inl"
#ifdef FEATURE_REMOTING
#include "crossdomaincalls.h"
#else
#include "callhelpers.h"
#endif
#ifdef _DEBUG
void AppDomainStack::CheckOverridesAssertCounts()
{
LIMITED_METHOD_CONTRACT;
DWORD dwAppDomainIndex = 0;
DWORD dwOverrides = 0;
DWORD dwAsserts = 0;
AppDomainStackEntry *pEntry = NULL;
for(dwAppDomainIndex=0;dwAppDomainIndex<m_numEntries;dwAppDomainIndex++)
{
pEntry = __GetEntryPtr(dwAppDomainIndex);
dwOverrides += pEntry->m_dwOverridesCount;
dwAsserts += pEntry->m_dwAsserts;
}
_ASSERTE(dwOverrides == m_dwOverridesCount);
_ASSERTE(dwAsserts == m_dwAsserts);
}
#endif
BOOL AppDomainStackEntry::IsFullyTrustedWithNoStackModifiers(void)
{
LIMITED_METHOD_CONTRACT;
if (m_domainID.m_dwId == INVALID_APPDOMAIN_ID || m_dwOverridesCount != 0 || m_dwAsserts != 0)
return FALSE;
AppDomainFromIDHolder pDomain(m_domainID, FALSE);
if (pDomain.IsUnloaded())
return FALSE;
IApplicationSecurityDescriptor *currAppSecDesc = pDomain->GetSecurityDescriptor();
if (currAppSecDesc == NULL)
return FALSE;
return Security::CheckDomainWideSpecialFlag(currAppSecDesc, 1 << SECURITY_FULL_TRUST);
}
BOOL AppDomainStackEntry::IsHomogeneousWithNoStackModifiers(void)
{
LIMITED_METHOD_CONTRACT;
if (m_domainID.m_dwId == INVALID_APPDOMAIN_ID || m_dwOverridesCount != 0 || m_dwAsserts != 0)
return FALSE;
AppDomainFromIDHolder pDomain(m_domainID, FALSE);
if (pDomain.IsUnloaded())
return FALSE;
IApplicationSecurityDescriptor *currAppSecDesc = pDomain->GetSecurityDescriptor();
if (currAppSecDesc == NULL)
return FALSE;
return (currAppSecDesc->IsHomogeneous() && !currAppSecDesc->ContainsAnyRefusedPermissions());
}
BOOL AppDomainStackEntry::HasFlagsOrFullyTrustedWithNoStackModifiers(DWORD flags)
{
LIMITED_METHOD_CONTRACT;
if (m_domainID.m_dwId == INVALID_APPDOMAIN_ID || m_dwOverridesCount != 0 || m_dwAsserts != 0)
return FALSE;
AppDomainFromIDHolder pDomain(m_domainID, FALSE);
if (pDomain.IsUnloaded())
return FALSE;
IApplicationSecurityDescriptor *currAppSecDesc = pDomain->GetSecurityDescriptor();
if (currAppSecDesc == NULL)
return FALSE;
// either the desired flag (often 0) or fully trusted will do
flags |= (1<<SECURITY_FULL_TRUST);
return Security::CheckDomainWideSpecialFlag(currAppSecDesc, flags);
}
void AppDomainStackEntry::UpdateHomogeneousPLS(OBJECTREF* homogeneousPLS)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
}
CONTRACTL_END;
AppDomainFromIDHolder domain(m_domainID, TRUE);
if (domain.IsUnloaded())
return;
IApplicationSecurityDescriptor *thisAppSecDesc = domain->GetSecurityDescriptor();
if (thisAppSecDesc->IsHomogeneous())
{
// update the intersection with the current grant set
NewArrayHolder<BYTE> pbtmpSerializedObject(NULL);
struct gc
{
OBJECTREF refGrantSet;
} gc;
ZeroMemory( &gc, sizeof( gc ) );
AppDomain* pCurrentDomain;
pCurrentDomain = GetAppDomain();
GCPROTECT_BEGIN( gc );
#ifdef FEATURE_REMOTING // should not be possible without remoting
DWORD cbtmpSerializedObject = 0;
if (pCurrentDomain->GetId() != m_domainID)
{
// Unlikely scenario where we have another homogeneous AD on the callstack that's different from
// the current one. If there's another AD on the callstack, it's likely to be FT.
ENTER_DOMAIN_ID(m_domainID)
{
// Release the holder to allow GCs. This is safe because we've entered the AD, so it won't go away.
domain.Release();
gc.refGrantSet = thisAppSecDesc->GetGrantedPermissionSet(NULL);
AppDomainHelper::MarshalObject(GetAppDomain(), &gc.refGrantSet, &pbtmpSerializedObject, &cbtmpSerializedObject);
if (pbtmpSerializedObject == NULL)
{
// this is an error: possibly an OOM prevented the blob from getting created.
// We could return null and let the managed code use a fully restricted object or throw here.
// Let's throw here...
COMPlusThrow(kSecurityException);
}
gc.refGrantSet = NULL;
}
END_DOMAIN_TRANSITION
AppDomainHelper::UnmarshalObject(pCurrentDomain,pbtmpSerializedObject, cbtmpSerializedObject, &gc.refGrantSet);
}
else
#else
_ASSERTE(pCurrentDomain->GetId() == m_domainID);
#endif //!FEATURE_CORECLR
{
// Release the holder to allow GCs. This is safe because we're running in this AD, so it won't go away.
domain.Release();
gc.refGrantSet = thisAppSecDesc->GetGrantedPermissionSet(NULL);
}
// At this point gc.refGrantSet has the grantSet of pDomain (thisAppSecDesc) in the current domain.
// We don't care about refused perms since we established there were
// none earlier for this call stack.
// Let's intersect with what we've already got.
PREPARE_NONVIRTUAL_CALLSITE(METHOD__PERMISSION_LIST_SET__UPDATE);
DECLARE_ARGHOLDER_ARRAY(args, 2);
args[ARGNUM_0] = OBJECTREF_TO_ARGHOLDER(*homogeneousPLS); // arg 0
args[ARGNUM_1] = OBJECTREF_TO_ARGHOLDER(gc.refGrantSet); // arg 1
CALL_MANAGED_METHOD_NORET(args);
GCPROTECT_END();
}
}
BOOL AppDomainStack::AllDomainsHomogeneousWithNoStackModifiers()
{
WRAPPER_NO_CONTRACT;
// Used primarily by CompressedStack code to decide if a CS has to be constructed
DWORD dwAppDomainIndex = 0;
InitDomainIteration(&dwAppDomainIndex);
while (dwAppDomainIndex != 0)
{
AppDomainStackEntry* pEntry = GetNextDomainEntryOnStack(&dwAppDomainIndex);
_ASSERTE(pEntry != NULL);
if (!pEntry->IsHomogeneousWithNoStackModifiers() && !pEntry->IsFullyTrustedWithNoStackModifiers())
return FALSE;
}
return TRUE;
}
| 33.248731 | 128 | 0.671145 | CyberSys |
0daec77a627b03e2bc4ead844c9bc8c9c0e152ff | 1,535 | cpp | C++ | FindMissingNumber.cpp | Cuncis/codeWith-hacktoberfest | 9cd5059e4d90b42fa9e12ba5ec8bf3f49c9e6c63 | [
"MIT"
] | null | null | null | FindMissingNumber.cpp | Cuncis/codeWith-hacktoberfest | 9cd5059e4d90b42fa9e12ba5ec8bf3f49c9e6c63 | [
"MIT"
] | null | null | null | FindMissingNumber.cpp | Cuncis/codeWith-hacktoberfest | 9cd5059e4d90b42fa9e12ba5ec8bf3f49c9e6c63 | [
"MIT"
] | null | null | null | /* Problem-Task : Create a function that takes an array of numbers between 1 and 10
(excluding one number) and returns the missing number.
* Problem Link : https://edabit.com/challenge/7YaJhC4terApw5DFa
*/
//C++ Program to find the Missing Number
/*The logic we are using is:
Sum of n integer elements is: n(n+1)/2. Here we are missing one element which means we
should replace n with n+1 so the total of elements in our case becomes: (n+1)(n+2)/2.
Once we have the total, we are removing all the elements that user has entered
from the total, this way the remaining value is our missing number.*/
CODE:-
#include <iostream>
using namespace std;
int findMissingNo (int arr[], int len){
int temp;
temp = ((len+1)*(len+2))/2;
for (int i = 0; i<len; i++)
temp -= arr[i];
return temp;
}
int main() {
int n;
cout<<"Enter the size of array: ";
cin>>n;
int arr[n-1];
cout<<"Enter array elements: ";
for(int i=0; i<n; i++){
cin>>arr[i];
}
int missingNo = findMissingNo(arr , 10 );
cout<<"Missing Number is: "<<missingNo;
return 0;
}
Output:
Example 1:-
Enter the size of array: 10
Enter array elements:
1
2
3
5
6
7
8
9
10
Missing Number is: 4
Example 2:-
Enter the size of array: 10
Enter array elements:
1
3
4
5
6
7
8
9
10
Missing Number is: 2
Example 3:-
Enter the size of array: 10
Enter array elements:
1
2
3
4
5
7
8
9
10
Missing Number is: 6
| 18.058824 | 88 | 0.614332 | Cuncis |
0dafd3e5017fc24e0fc51d2e5dc1f14112a97272 | 3,108 | cpp | C++ | sp800-22/runs_test.cpp | ilwoong/randomness_library | 6d00cd4810b2dc793c1f057b3a40cab30dbd0ac8 | [
"MIT"
] | null | null | null | sp800-22/runs_test.cpp | ilwoong/randomness_library | 6d00cd4810b2dc793c1f057b3a40cab30dbd0ac8 | [
"MIT"
] | null | null | null | sp800-22/runs_test.cpp | ilwoong/randomness_library | 6d00cd4810b2dc793c1f057b3a40cab30dbd0ac8 | [
"MIT"
] | 1 | 2020-06-27T08:08:18.000Z | 2020-06-27T08:08:18.000Z | /**
* The MIT License
*
* Copyright (c) 2020 Ilwoong Jeong (https://github.com/ilwoong)
*
* 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 "runs_test.h"
#include "../common/hamming_weight.h"
using namespace randomness::sp800_22;
using namespace randomness::common;
const std::string RunsTest::Name() const
{
return "Runs test";
}
const std::string RunsTest::ShortName() const
{
return "Runs";
}
size_t RunsTest::MinimumLengthInBits() const
{
return 100;
}
static size_t TotalNumberOfOnes(const Sample& sample)
{
auto data = sample.OctalData();
auto length = data.size();
size_t vobs = 1;
uint8_t idx = 0;
for (auto k = 0; k < length - 1; ++k) {
idx = data[k] ^ ((data[k] << 1) ^ (data[k + 1] >> 7));
vobs += HammingWeight(idx);
}
idx = data[length - 1] ^ (data[length - 1] << 1) ^ (data[length - 1] & 0x1);
vobs += HammingWeight(idx);
return vobs;
}
static double CalculateStatistic(const Sample& sample, double pi)
{
auto vobs = TotalNumberOfOnes(sample);
auto term = pi * (1.0 - pi);
auto length = sample.BinaryData().size();
auto numerator = abs(vobs - (2 * length * term));
auto denominator = 2 * sqrt(2 * length) * term;
return numerator / denominator;
}
std::vector<randomness_result_t> RunsTest::Evaluate(const Sample& sample)
{
auto length = sample.BinaryData().size();
auto pi = HammingWeight(sample) / static_cast<double>(length);
auto tau = 2.0 / length;
auto pvalue = 0.0;
if (abs(pi - 0.5) < tau) {
auto fraction = CalculateStatistic(sample, pi);
pvalue = std::erfc(fraction);
logstream << "𝜋 = " << pi << ", 𝜏 = " << tau << ", fraction = " << fraction;
}
else {
pvalue = 0.0;
logstream << "monobit test failed";
}
auto result = std::vector<randomness_result_t>{};
result.push_back(randomness_result_t {Name(), ShortName(), "", pvalue});
return result;
} | 31.393939 | 85 | 0.642535 | ilwoong |
0db0ca1c31bf042834d85629285d51b66d9a2362 | 352 | hpp | C++ | include/cuda_dl.hpp | jetd1/kuafu | 819d338682f3e889710731cf7ca16f790b54568f | [
"MIT"
] | 17 | 2021-09-03T03:06:48.000Z | 2022-03-27T04:02:14.000Z | include/cuda_dl.hpp | jetd1/kuafu | 819d338682f3e889710731cf7ca16f790b54568f | [
"MIT"
] | null | null | null | include/cuda_dl.hpp | jetd1/kuafu | 819d338682f3e889710731cf7ca16f790b54568f | [
"MIT"
] | null | null | null | //
// Created by jet on 9/17/21.
//
#pragma once
#include <cuda.h>
namespace kuafu {
void kfCuDlOpen();
void kfCuDlClose();
CUresult kfCuInit(unsigned int Flags);
CUresult kfCuStreamCreate(CUstream* phStream, unsigned int Flags);
CUresult kfCuCtxCreate(CUcontext* pctx, unsigned int flags, CUdevice dev);
CUresult kfCuCtxDestroy(CUcontext ctx);
}
| 18.526316 | 74 | 0.758523 | jetd1 |
0db79073d01f6a5e7dc7459f93003d3937f68c78 | 3,819 | cpp | C++ | Lab4/src/CircleHough.cpp | DavidePistilli173/Computer-Vision | 4066a99f6f6fdc941829d3cd3015565ec0046a2f | [
"Apache-2.0"
] | null | null | null | Lab4/src/CircleHough.cpp | DavidePistilli173/Computer-Vision | 4066a99f6f6fdc941829d3cd3015565ec0046a2f | [
"Apache-2.0"
] | null | null | null | Lab4/src/CircleHough.cpp | DavidePistilli173/Computer-Vision | 4066a99f6f6fdc941829d3cd3015565ec0046a2f | [
"Apache-2.0"
] | null | null | null | #include "CircleHough.hpp"
#include <opencv2/imgproc.hpp>
using namespace lab4;
CircleHough::CircleHough(const cv::Mat& img, std::string_view winName) :
ImgProcessor(img, winName, CV_8UC3)
{
bool success{ true };
/* Add trackbars for parameters of type double. */
for (int i = 0; i < static_cast<int>(DoubleParam::tot); ++i)
{
success =
success && win_.addTrackBar(double_param_names[i], double_param_start_vals[i], double_param_max[i]);
}
/* Add trackbars for parameters of type int. */
for (int i = 0; i < static_cast<int>(IntParam::tot); ++i)
{
success = success && win_.addTrackBar(int_param_names[i], int_param_start_vals[i], int_param_max[i]);
}
if (!success) Log::error("Failed to create enough trackbars for all parameters.");
}
std::optional<cv::Vec3f> CircleHough::getRelevantCircle()
{
if (circles_.empty()) return std::optional<cv::Vec3f>();
return std::optional(circles_[0]);
}
bool CircleHough::update(bool force)
{
/* If the update is not forced and if no trackbars were changed don't perform any computation. */
if (!force && !win_.modified()) return false;
/* Convert the input image to greyscale. */
cv::cvtColor(srcImg_, greyScaleImg_, cv::COLOR_BGR2GRAY);
fetchNormalisedParams_(); // Get the current parameter values.
circles_.clear(); // Clear the result from previous computations.
Log::info("Computing HoughCircles...");
cv::HoughCircles(
greyScaleImg_,
circles_,
cv::HOUGH_GRADIENT,
double_params_[static_cast<int>(DoubleParam::res)],
double_params_[static_cast<int>(DoubleParam::dist)],
double_params_[static_cast<int>(DoubleParam::th1)],
double_params_[static_cast<int>(DoubleParam::th2)],
int_params_[static_cast<int>(IntParam::min_r)],
int_params_[static_cast<int>(IntParam::max_r)]
);
Log::info("SUCCESS");
resultImg_ = srcImg_.clone();
Log::info("Drawing circles...");
drawCircles_(); // Draw detected circles.
Log::info("SUCCESS");
win_.showImg(resultImg_);
return true;
}
void CircleHough::drawCircles_()
{
for (const auto& circle : circles_)
{
cv::circle(
resultImg_,
cv::Point
{
cvRound(circle[static_cast<int>(CircleParam::x)]),
cvRound(circle[static_cast<int>(CircleParam::y)])
},
cvRound(circle[static_cast<int>(CircleParam::r)]),
cv::Scalar{ 0, circle_intensity, 0 },
circle_thickness,
cv::LINE_AA
);
}
}
void CircleHough::fetchNormalisedParams_()
{
Log::info("Normalising CirleHough parameters.");
if (
std::vector<int> params = win_.fetchTrckVals();
params.size() >= static_cast<int>(DoubleParam::tot) + static_cast<int>(IntParam::tot)
)
{
/* Normalise parameters of type double. */
for (int i = 0; i < double_param_num; ++i)
{
double_params_[i] = scale(
double_param_limits[i].first,
double_param_limits[i].second,
scaling_coeff(params[i], double_param_max[i])
);
Log::info("Parameter %d = %f.", i, double_params_[i]);
}
/* Normalise parameters of type int. */
for (int i = 0; i < int_param_num; ++i)
{
int_params_[i] = scale(
int_param_limits[i].first,
int_param_limits[i].second,
scaling_coeff(params[i + double_param_num], int_param_max[i])
);
Log::info("Parameter %d = %d.", i + double_param_num, int_params_[i]);
}
}
else
{
Log::error("Not enough parameters available.");
}
} | 32.092437 | 112 | 0.59911 | DavidePistilli173 |
0dbf9b4c39ae19b637977f9af9789b6e31d8d519 | 29,310 | cpp | C++ | sketchup_converter/main.cpp | jhhsia/sketchup_converter | 7d8daffd61c8d8f6c214640672e38c7817e37788 | [
"MIT"
] | 1 | 2020-09-27T10:55:07.000Z | 2020-09-27T10:55:07.000Z | sketchup_converter/main.cpp | jhhsia/sketchup_converter | 7d8daffd61c8d8f6c214640672e38c7817e37788 | [
"MIT"
] | null | null | null | sketchup_converter/main.cpp | jhhsia/sketchup_converter | 7d8daffd61c8d8f6c214640672e38c7817e37788 | [
"MIT"
] | null | null | null | //
// main.cpp
// sketchup_converter
//
// Created by jahsia on 10/26/18.
// Copyright © 2018 trisetra. All rights reserved.
//
#include <iostream>
#include <SketchUpAPI/common.h>
#include <SketchUpAPI/geometry.h>
#include <SketchUpAPI/geometry/vector3d.h>
#include <SketchUpAPI/initialize.h>
#include <SketchUpAPI/model/component_definition.h>
#include <SketchUpAPI/model/component_instance.h>
#include <SketchUpAPI/model/drawing_element.h>
#include <SketchUpAPI/model/edge.h>
#include <SketchUpAPI/model/entities.h>
#include <SketchUpAPI/model/entity.h>
#include <SketchUpAPI/model/face.h>
#include <SketchUpAPI/model/group.h>
#include <SketchUpAPI/model/image_rep.h>
#include <SketchUpAPI/model/layer.h>
#include <SketchUpAPI/model/loop.h>
#include <SketchUpAPI/model/material.h>
#include <SketchUpAPI/model/mesh_helper.h>
#include <SketchUpAPI/model/model.h>
#include <SketchUpAPI/model/texture.h>
#include <SketchUpAPI/model/texture_writer.h>
#include <SketchUpAPI/model/uv_helper.h>
#include <SketchUpAPI/model/vertex.h>
#include <SketchUpAPI/unicodestring.h>
#include <Eigen/Dense>
#include "MeshImporter.hpp"
#include <map>
#include <vector>
#include <unordered_set>
#define SU_CALL(func) \
if ((func) != SU_ERROR_NONE) \
throw std::exception()
#define Y_UP false
using namespace trisetra;
class CSUString {
public:
CSUString() {
SUSetInvalid(su_str_);
SUStringCreate(&su_str_);
}
~CSUString() {
SUStringRelease(&su_str_);
}
operator SUStringRef*() {
return &su_str_;
}
std::string utf8() {
size_t length;
SUStringGetUTF8Length(su_str_, &length);
std::string string;
string.resize(length + 1);
size_t returned_length;
SUStringGetUTF8(su_str_, length, &string[0], &returned_length);
string.erase(length, 1);
return string;
}
private:
// Disallow copying for simplicity
CSUString(const CSUString& copy);
CSUString& operator=(const CSUString& copy);
SUStringRef su_str_;
};
static std::string GetComponentDefinitionName(SUComponentDefinitionRef comp_def) {
CSUString name;
SU_CALL(SUComponentDefinitionGetName(comp_def, name));
return name.utf8();
}
struct SUImportInfo {
std::vector<SUMaterialRef> mats;
std::vector<std::string> names;
std::vector<SUImageRepRef> textures;
std::vector<SUPoint2D> texST;
std::map<void*, MeshSource*> def_map;
std::map<void*, std::vector<SUMaterialRef>> mat_map;
};
struct SUPolyInfo {
std::vector<float> vertex_positions; // The vertex's position (x,y,z)
std::vector<uint32_t> vertex_indices;
std::vector<float> vertex_normals; // The vertex's surface normal (x,y,z)
std::vector<float> uvs; // The vertex's texture coordinates (u,v)
std::vector<int32_t> material_ids;
std::vector<int32_t> face_material;
};
static std::vector<float> EigenToVector(const Eigen::Affine3f& t) {
std::vector<float> local_transformations(12);
local_transformations[0] = t(0, 0);
local_transformations[1] = t(1, 0);
local_transformations[2] = t(2, 0);
local_transformations[3] = t(0, 1);
local_transformations[4] = t(1, 1);
local_transformations[5] = t(2, 1);
local_transformations[6] = t(0, 2);
local_transformations[7] = t(1, 2);
local_transformations[8] = t(2, 2);
local_transformations[9] = t(0, 3);
local_transformations[10] = t(1, 3);
local_transformations[11] = t(2, 3);
return local_transformations;
}
static Eigen::Affine3f ToEigenAffine(const double* raw_data) {
Eigen::Affine3f t;
float scale = 1.0f / (float)(raw_data[15]);
t(0, 0) = (float)(raw_data[0]) * scale;
t(1, 0) = (float)(raw_data[1]) * scale;
t(2, 0) = (float)(raw_data[2]) * scale;
t(3, 0) = 0.0f;
t(0, 1) = (float)(raw_data[4]) * scale;
t(1, 1) = (float)(raw_data[5]) * scale;
t(2, 1) = (float)(raw_data[6]) * scale;
t(3, 1) = 0.0f;
t(0, 2) = (float)(raw_data[8]) * scale;
t(1, 2) = (float)(raw_data[9]) * scale;
t(2, 2) = (float)(raw_data[10]) * scale;
t(3, 2) = 0.0f;
t(0, 3) = (float)(raw_data[12]) * scale;
t(1, 3) = (float)(raw_data[13]) * scale;
t(2, 3) = (float)(raw_data[14]) * scale;
t(3, 3) = 1.0f;
return t;
}
static void InitMaterialData(std::shared_ptr<MaterialData>& material, const SUImportInfo& su_mats, int src_idx) {
SUColor color;
double opt = 1.0;
bool use_opacity;
SUMaterialGetColor(su_mats.mats[src_idx], &color);
SUMaterialGetOpacity(su_mats.mats[src_idx], &opt);
SUMaterialGetUseOpacity(su_mats.mats[src_idx], &use_opacity);
material->name = su_mats.names[src_idx];
material->base_color[0] = color.red / 255.0f;
material->base_color[1] = color.green / 255.0f;
material->base_color[2] = color.blue / 255.0f;
material->base_color[3] = color.alpha / 255.0f;
if (use_opacity)
material->opacity = opt;
}
static void AddTextrueToMat(SUImageRepRef& img_rep,
std::shared_ptr<MaterialData>& material,
const std::string& composed_name) {
if (SUIsValid(img_rep)) {
size_t width, height, data_size, bits_per_pixel;
SUImageRepGetPixelDimensions(img_rep, &width, &height);
SUImageRepGetDataSize(img_rep, &data_size, &bits_per_pixel);
std::string file_path = "./" +composed_name+".png";
SUImageRepSaveToFile(img_rep, file_path.c_str());
material->base_color_map = file_path;
}
}
// returns first the transform to store for the node3d
// the second transform (might cointains negtive scale) to be baked into vertecies
static std::tuple<Eigen::Affine3f, Eigen::Affine3f> DecomposeTransform(Eigen::Affine3f t) {
Eigen::Affine3f original_t = t;
Eigen::Matrix3f rotation_scale_part(original_t.linear());
if (rotation_scale_part.determinant() > 0.0f) {
Eigen::Affine3f identity = Eigen::Affine3f::Identity();
return std::make_tuple(original_t, identity);
} else {
t.translation() = Eigen::Vector3f(0.0f, 0.0f, 0.0f);
Eigen::Matrix3f M = t.linear();
Eigen::Matrix3f rotation_matrix = t.rotation();
Eigen::Matrix3f scaling_matrix = rotation_matrix.transpose() * M;
// sanitize non rotational component (only scaling > 0)
scaling_matrix(0, 0) = std::abs(scaling_matrix(0, 0));
scaling_matrix(1, 1) = std::abs(scaling_matrix(1, 1));
scaling_matrix(2, 2) = std::abs(scaling_matrix(2, 2));
scaling_matrix(0, 1) = scaling_matrix(0, 2) = scaling_matrix(1, 0) = scaling_matrix(1, 2) = scaling_matrix(2, 0) =
scaling_matrix(2, 1) = 0.0f;
t.linear() = rotation_matrix * scaling_matrix;
t.translation() = original_t.translation();
Eigen::Affine3f inverse_t = t.inverse();
Eigen::Affine3f bake_t = inverse_t * original_t;
return std::make_tuple(t, bake_t);
}
}
static void WriteFace(SUFaceRef face,
SUTextureWriterRef texture_writer,
SUPolyInfo& m_data,
SUImportInfo& mat_info,
int parent_idx,
bool front,
SUMaterialRef assigned,
bool instanced,
MeshImport* mesh_import,
MeshSource* mesh,
const Eigen::Affine3f& transform,
const Eigen::Matrix3f& normal_transform) {
if (SUIsInvalid(face))
return;
SUMaterialRef face_material = SU_INVALID;
// sort of hack as may face expect back face to be front facing due to material assignment.
// so we use a key here to be smart about back/front face selection
bool prefer_back_face = false;
bool has_face_material = true;
{
SUMaterialRef bface_material = SU_INVALID;
SUTextureRef ftexture_ref = SU_INVALID;
SUFaceGetFrontMaterial(face, &face_material);
if (SUIsValid(face_material)) {
SUMaterialGetTexture(face_material, &ftexture_ref);
}
SUFaceGetBackMaterial(face, &bface_material);
if (SUIsValid(bface_material)) {
SUTextureRef texture_ref = SU_INVALID;
SUMaterialGetTexture(bface_material, &texture_ref);
if (SUIsValid(texture_ref) && SUIsInvalid(ftexture_ref)) {
SUFaceReverse(face);
face_material = bface_material;
prefer_back_face = true;
}
}
}
SUVector3D fnorm;
SUFaceGetNormal(face, &fnorm);
// Get the current front and back materials off of our stack
if (SUIsInvalid(face_material)) {
face_material = assigned;
has_face_material = false;
}
long mat_idx = 0;
auto find_mat_it = std::find_if(
mat_info.mats.begin(), mat_info.mats.end(), [face_material](const SUMaterialRef& in) { return face_material.ptr == in.ptr; });
if (find_mat_it != mat_info.mats.end()) {
mat_idx = find_mat_it - mat_info.mats.begin();
}
bool has_texture = SUIsValid(mat_info.textures[mat_idx]); // info.has_front_texture_ || info.has_back_texture_;
if (has_texture && has_face_material) {
long textureId = 0;
SUTextureWriterGetTextureIdForFace(texture_writer, face, true, &textureId);
}
size_t local_mat_id = std::distance(m_data.material_ids.begin(), find(m_data.material_ids.begin(), m_data.material_ids.end(), mat_idx));
if (local_mat_id == m_data.material_ids.size()) {
m_data.material_ids.push_back((int)mat_idx);
}
if (mesh) {
// 0 is defefault material
auto eu_material = mesh_import->get_material((int)mat_idx);
mesh_import->apply_material(mesh, eu_material.get());
}
// Get a uv helper
float inv_ss = 1.0f;
float inv_tt = 1.0f;
if (!has_face_material) {
inv_ss = mat_info.texST[mat_idx].x;
inv_tt = mat_info.texST[mat_idx].y;
}
// Find out how many loops the face has
size_t num_loops = 0;
SU_CALL(SUFaceGetNumInnerLoops(face, &num_loops));
num_loops++; // add the outer loop
// If this is a complex face with one or more holes in it
// we tessellate it into triangles using the polygon mesh class, then
// export each triangle as a face.
// info.has_single_loop_ = false;
// Create a mesh from face.
SUMeshHelperRef mesh_ref = SU_INVALID;
SU_CALL(SUMeshHelperCreateWithTextureWriter(&mesh_ref, face, texture_writer));
// Get the vertices
size_t num_vertices = 0;
SU_CALL(SUMeshHelperGetNumVertices(mesh_ref, &num_vertices));
if (num_vertices == 0)
return;
std::vector<SUPoint3D> vertices(num_vertices);
SU_CALL(SUMeshHelperGetVertices(mesh_ref, num_vertices, &vertices[0], &num_vertices));
std::vector<SUVector3D> normals(num_vertices);
SU_CALL(SUMeshHelperGetNormals(mesh_ref, num_vertices, &normals[0], &num_vertices));
std::vector<SUPoint3D> stq_coords(num_vertices);
size_t uv_size = 0;
if (!prefer_back_face) {
SUMeshHelperGetFrontSTQCoords(mesh_ref, num_vertices, &stq_coords[0], &uv_size);
} else {
SUMeshHelperGetBackSTQCoords(mesh_ref, num_vertices, &stq_coords[0], &uv_size);
}
std::vector<float> vertex_positions(num_vertices * 3);
std::vector<float> vertex_normal(num_vertices * 3);
// dimension is Y up
for (size_t i = 0; i < num_vertices; ++i) {
Eigen::Vector3f pos(vertices[i].x, vertices[i].y, vertices[i].z);
Eigen::Vector3f norm(normals[i].x, normals[i].y, normals[i].z);
Eigen::Vector3f post_trans = transform * pos;
Eigen::Vector3f norm_trans = normal_transform * norm;
norm_trans.normalize();
vertex_positions[i * 3 + 0] = post_trans.x();
vertex_positions[i * 3 + 1] = post_trans.y();
vertex_positions[i * 3 + 2] = post_trans.z();
vertex_normal[i * 3 + 0] = norm_trans.x();
vertex_normal[i * 3 + 1] = norm_trans.y();
vertex_normal[i * 3 + 2] = norm_trans.z();
}
// Get triangle indices.
size_t num_triangles = 0;
SU_CALL(SUMeshHelperGetNumTriangles(mesh_ref, &num_triangles));
const size_t num_indices = 3 * num_triangles;
size_t num_retrieved = 0;
std::vector<size_t> indices(num_indices);
SU_CALL(SUMeshHelperGetVertexIndices(mesh_ref, num_indices, &indices[0], &num_retrieved));
std::vector<uint32_t> dst_idx(num_indices);
std::vector<float> uv_coord;
if (uv_size > 0) {
uv_coord.resize(num_vertices * 2);
for (size_t i = 0; i < num_vertices; ++i) {
uv_coord[i * 2 + 0] = inv_ss * stq_coords[i].x / stq_coords[i].z;
uv_coord[i * 2 + 1] = inv_tt * stq_coords[i].y / stq_coords[i].z;
}
}
size_t base_idx = m_data.vertex_positions.size() / 3;
std::vector<int32_t> face_materials(num_triangles);
front = !prefer_back_face;
for (size_t i_triangle = 0; i_triangle < num_triangles; i_triangle++) {
face_materials[i_triangle] = (int)local_mat_id;
// Three points in each triangle
if (front) {
for (size_t i = 0; i < 3; i++) {
size_t index = indices[i_triangle * 3 + i];
dst_idx[i_triangle * 3 + i] = (int)(index + base_idx);
}
} else {
// back face
size_t index0 = indices[i_triangle * 3 + 0];
size_t index1 = indices[i_triangle * 3 + 1];
size_t index2 = indices[i_triangle * 3 + 2];
dst_idx[i_triangle * 3 + 0] = (int)(index2 + base_idx);
dst_idx[i_triangle * 3 + 1] = (int)(index1 + base_idx);
dst_idx[i_triangle * 3 + 2] = (int)(index0 + base_idx);
}
}
// combine to original array
m_data.vertex_positions.insert(m_data.vertex_positions.end(), vertex_positions.begin(), vertex_positions.end());
m_data.vertex_normals.insert(m_data.vertex_normals.end(), vertex_normal.begin(), vertex_normal.end());
m_data.vertex_indices.insert(m_data.vertex_indices.end(), dst_idx.begin(), dst_idx.end());
m_data.face_material.insert(m_data.face_material.end(), face_materials.begin(), face_materials.end());
if (uv_size > 0) {
m_data.uvs.insert(m_data.uvs.end(), uv_coord.begin(), uv_coord.end());
}
}
static void WriteEntities(SUEntitiesRef entities,
SUTextureWriterRef texture_writer,
SUGroupRef group,
SUImportInfo& mat_info,
int parent_idx,
SUMaterialRef parent_mat,
MeshImport* mesh_import,
const Node* parent,
Eigen::Affine3f bake_transform) {
#if 1
size_t num_instances = 0;
SU_CALL(SUEntitiesGetNumInstances(entities, &num_instances));
if (num_instances > 0) {
std::vector<SUComponentInstanceRef> instances(num_instances);
SU_CALL(SUEntitiesGetInstances(entities, num_instances, &instances[0], &num_instances));
for (size_t c = 0; c < num_instances; c++) {
SUComponentInstanceRef instance = instances[c];
SUComponentDefinitionRef definition = SU_INVALID;
SU_CALL(SUComponentInstanceGetDefinition(instance, &definition));
size_t attached_instance = 0;
SUComponentInstanceGetNumAttachedInstances(instance, &attached_instance);
SUEntitiesRef entity_from_def;
SUComponentDefinitionGetEntities(definition, &entity_from_def);
size_t num_faces;
SUEntitiesGetNumFaces(entity_from_def, &num_faces);
SUTransformation transform;
SU_CALL(SUComponentInstanceGetTransform(instance, &transform));
const double* raw_data = (const double*)transform.values;
//---- checking if matrix has neg scal term, if so, we need to bake into vertecies
auto src_affine = ToEigenAffine(raw_data);
auto stacked = src_affine;
Eigen::Affine3f to_transform;
Eigen::Affine3f to_bake;
std::tie(to_transform, to_bake) = DecomposeTransform(src_affine);
bool need_baking = !to_bake.matrix().isIdentity();
auto sanitized_transform = EigenToVector(bake_transform * to_transform);
//-----------------------------------------------------------------------------
std::string def_name = GetComponentDefinitionName(definition);
// add transformation info
auto instance_node = mesh_import->create_node(parent, def_name);
mesh_import->add_tranform3x4(instance_node.get(), std::move(sanitized_transform));
SUMaterialRef material = SU_INVALID;
SUDrawingElementGetMaterial(SUComponentInstanceToDrawingElement(instance), &material);
if (num_faces > 0) {
MeshSource* mesh_node = nullptr;
auto eu_mesh = mat_info.def_map.find(definition.ptr);
if ((eu_mesh == mat_info.def_map.end()) || need_baking) {
auto mesh = mesh_import->create_mesh(def_name);
// only sotre into map if we dont need baking
if (!need_baking)
mat_info.def_map[definition.ptr] = mesh.get();
mesh_node = mesh.get();
mesh_import->add_face_descriptor(mesh_node, {3});
mesh_import->add_mesh_to_node(instance_node.get(), mesh_node);
} else {
// hook up instance.
mesh_import->add_mesh_to_node(instance_node.get(), eu_mesh->second);
}
std::vector<SUFaceRef> faces(num_faces);
SU_CALL(SUEntitiesGetFaces(entity_from_def, num_faces, &faces[0], &num_faces));
if (SUIsValid(material) == false) {
material = parent_mat;
}
SUPolyInfo front_mesh;
auto normal_transform = ((to_bake.linear()).inverse()).transpose();
for (size_t i = 0; i < num_faces; i++) {
WriteFace(faces[i],
texture_writer,
front_mesh,
mat_info,
parent_idx,
true,
material,
true,
mesh_import,
mesh_node,
to_bake,
normal_transform);
}
if (mesh_node) {
mesh_import->add_positions(mesh_node, std::move(front_mesh.vertex_positions), std::move(front_mesh.vertex_indices));
mesh_import->add_normals(mesh_node, std::move(front_mesh.vertex_normals), {});
mesh_import->add_uv(mesh_node, 0, std::move(front_mesh.uvs), {});
mesh_import->add_face_material_idx(mesh_node, std::move(front_mesh.face_material));
}
}
WriteEntities(entity_from_def, texture_writer, group, mat_info, -1, material, mesh_import, instance_node.get(), to_bake);
}
}
#endif
// Groups
size_t num_groups = 0;
SU_CALL(SUEntitiesGetNumGroups(entities, &num_groups));
if (num_groups > 0) {
std::vector<SUGroupRef> groups(num_groups);
SU_CALL(SUEntitiesGetGroups(entities, num_groups, &groups[0], &num_groups));
for (size_t g = 0; g < num_groups; g++) {
SUGroupRef group = groups[g];
if (!SUIsValid(group)) {
continue;
}
// SUComponentDefinitionRef group_component = SU_INVALID;
SUEntitiesRef group_entities = SU_INVALID;
SU_CALL(SUGroupGetEntities(group, &group_entities));
int my_idx = parent_idx;
size_t num_faces = 0;
SUTransformation transform;
SU_CALL(SUGroupGetTransform(group, &transform));
// FbxAMatrix& lLocalTransform = pNode->EvaluateLocalTransform();
const double* raw_data = (const double*)transform.values;
//---- checking if matrix has neg scal term, if so, we need to bake into vertecies
auto src_affine = ToEigenAffine(raw_data);
auto stacked = src_affine;
Eigen::Affine3f to_transform;
Eigen::Affine3f to_bake;
std::tie(to_transform, to_bake) = DecomposeTransform(src_affine);
auto sanitized_transform = EigenToVector(bake_transform * to_transform);
//-----------------------------------------------------------------------------
CSUString name;
SUGroupGetName(group, name);
auto def_name = "group_" + name.utf8();
//------ add transformation info
auto instance_node = mesh_import->create_node(parent, def_name);
mesh_import->add_tranform3x4(instance_node.get(), std::move(sanitized_transform));
SU_CALL(SUEntitiesGetNumFaces(group_entities, &num_faces));
SUDrawingElementRef dwrf = SUGroupToDrawingElement(group);
SUMaterialRef material = SU_INVALID;
if (SUIsValid(dwrf)) {
SUDrawingElementGetMaterial(dwrf, &material);
if (SUIsValid(material))
parent_mat = material;
}
if (num_faces > 0) {
auto mesh = mesh_import->create_mesh(name.utf8());
mesh_import->add_face_descriptor(mesh.get(), {3});
mesh_import->add_mesh_to_node(instance_node.get(), mesh.get());
std::vector<SUFaceRef> faces(num_faces);
SU_CALL(SUEntitiesGetFaces(group_entities, num_faces, &faces[0], &num_faces));
if (SUIsInvalid(material))
material = parent_mat;
SUPolyInfo front_mesh;
auto normal_transform = ((to_bake.linear()).inverse()).transpose();
for (size_t i = 0; i < num_faces; i++) {
WriteFace(faces[i],
texture_writer,
front_mesh,
mat_info,
parent_idx,
true,
material,
false,
mesh_import,
mesh.get(),
to_bake,
normal_transform);
}
if (mesh.get()) {
mesh_import->add_positions(mesh.get(), std::move(front_mesh.vertex_positions), std::move(front_mesh.vertex_indices));
mesh_import->add_normals(mesh.get(), std::move(front_mesh.vertex_normals), {});
mesh_import->add_uv(mesh.get(), 0, std::move(front_mesh.uvs), {});
mesh_import->add_face_material_idx(mesh.get(), std::move(front_mesh.face_material));
}
}
// Write entities
WriteEntities(group_entities, texture_writer, group, mat_info, my_idx, parent_mat, mesh_import, instance_node.get(), to_bake);
}
}
}
void load_skp(const std::string& path, MeshImport* mesh_import) {
// Always initialize the API before using it
SUInitialize();
// Load the model from a file
SUModelRef model = SU_INVALID;
SUResult res = SUModelCreateFromFile(&model, path.c_str());
// It's best to always check the return code from each SU function call.
// Only showing this check once to keep this example short.
if (res != SU_ERROR_NONE)
throw std::runtime_error("SUModelCreateFromFile failed to open: " + path);
SUTextureWriterRef texture_writer;
SU_CALL(SUTextureWriterCreate(&texture_writer));
// Get the entity container of the model.
SUEntitiesRef entities = SU_INVALID;
SUModelGetEntities(model, &entities);
//---------------- material ------------------------
size_t material_count = 0;
SUModelGetNumMaterials(model, &material_count);
SUImportInfo su_mats;
su_mats.mats.resize(material_count + 1);
su_mats.textures.resize(material_count + 1);
su_mats.names.resize(material_count + 1);
su_mats.texST.resize(material_count + 1);
// with default material
std::vector<std::shared_ptr<MaterialData>> materials(material_count + 1);
;
for (int i = 0; i < material_count + 1; ++i) {
materials[i] = std::make_shared<MaterialData>();
}
// material creation...
{
SUModelGetMaterials(model, material_count, &su_mats.mats[1], &material_count);
// set 0 to default material
// su_mats.names[0] = "default";
materials[0]->name = "default";
su_mats.textures[0] = SU_INVALID;
su_mats.mats[0] = SU_INVALID;
for (int i = 1; i < material_count + 1; ++i) {
CSUString name;
SUMaterialGetNameLegacyBehavior(su_mats.mats[i], name);
SUTextureRef texture_ref = SU_INVALID;
SUMaterialGetTexture(su_mats.mats[i], &texture_ref);
su_mats.names[i] = name.utf8();
InitMaterialData(materials[i], su_mats, i);
if (SUIsValid(texture_ref)) {
size_t width, height;
double ss, st;
SUTextureGetDimensions(texture_ref, &width, &height, &ss, &st);
SUImageRepRef img_rep = SU_INVALID;
SUImageRepCreate(&img_rep);
su_mats.textures[i] = img_rep;
SUTextureGetImageRep(texture_ref, &img_rep);
CSUString tex_name;
SUTextureGetFileName(texture_ref, tex_name);
std::string composed_name = tex_name.utf8() + "_" + name.utf8();
su_mats.texST[i].x = (float)ss;
su_mats.texST[i].y = (float)st;
AddTextrueToMat(img_rep, materials[i], composed_name );
SUImageRepRelease(&img_rep);
}
}
}
mesh_import->add_materials(materials);
// Get model name
CSUString name;
SUModelGetName(model, name);
std::vector<float> local_transformations(12);
{
local_transformations[0] = 1;
local_transformations[1] = 0;
local_transformations[2] = 0;
local_transformations[3] = 0;
local_transformations[4] = 1;
local_transformations[5] = 0;
local_transformations[6] = 0;
local_transformations[7] = 0;
local_transformations[8] = 1;
local_transformations[9] = 0;
local_transformations[10] = 0;
local_transformations[11] = 0;
}
auto root_node = mesh_import->create_node(nullptr, "y_up_convert" + name.utf8());
{ mesh_import->add_tranform3x4(root_node.get(), std::move(local_transformations)); }
size_t num_faces = 0;
Eigen::Affine3f identity;
identity.setIdentity();
SU_CALL(SUEntitiesGetNumFaces(entities, &num_faces));
if (num_faces > 0) {
auto en_mesh = mesh_import->create_mesh("entity");
mesh_import->add_face_descriptor(en_mesh.get(), {3});
mesh_import->add_mesh_to_node(root_node.get(), en_mesh.get());
std::vector<SUFaceRef> faces(num_faces);
SU_CALL(SUEntitiesGetFaces(entities, num_faces, &faces[0], &num_faces));
SUPolyInfo front_mesh;
for (size_t i = 0; i < num_faces; i++) {
WriteFace(faces[i],
texture_writer,
front_mesh,
su_mats,
0,
true,
SU_INVALID,
false,
mesh_import,
en_mesh.get(),
identity,
identity.linear());
}
if (en_mesh.get()) {
mesh_import->add_positions(en_mesh.get(), std::move(front_mesh.vertex_positions), std::move(front_mesh.vertex_indices));
mesh_import->add_normals(en_mesh.get(), std::move(front_mesh.vertex_normals), {});
mesh_import->add_uv(en_mesh.get(), 0, std::move(front_mesh.uvs), {});
mesh_import->add_face_material_idx(en_mesh.get(), std::move(front_mesh.face_material));
}
}
// material gathering
// GetEntitiesMaterial(entities, texture_writer, SU_INVALID, model_data_ptr, su_mats, 0);
// Groups
SUMaterialRef material = SU_INVALID;
WriteEntities(entities, texture_writer, SU_INVALID, su_mats, 0, material, mesh_import, root_node.get(), identity);
// Must release the model or there will be memory leaks
SUModelRelease(&model);
// Always terminate the API when done using it
SUTerminate();
}
int main(int argc, const char * argv[]) {
// insert code here...
MeshImporter mi;
if( argc > 1){
float rotate = 0.0f;
std::string file_name = std::string(argv[1]);
if(argc > 2)
rotate = std::stof( std::string(argv[2]));
load_skp(file_name, &mi );
size_t lastindex = file_name.find_last_of(".");
std::string rawname = file_name.substr(0, lastindex);
rawname = rawname + ".tri";
//mi.serialize_to_file(rawname, true, Y_UP, -1.571f);
mi.serialize_to_file(rawname, true, Y_UP, rotate);
}
return 0;
}
| 38.872679 | 162 | 0.608393 | jhhsia |
0dbff02f2d2ddc13d3713e7691ed49c0ee996e42 | 1,028 | cpp | C++ | Luogu/P3805/manacher.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | 2 | 2018-02-14T01:59:31.000Z | 2018-03-28T03:30:45.000Z | Luogu/P3805/manacher.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | null | null | null | Luogu/P3805/manacher.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | 2 | 2017-12-30T02:46:35.000Z | 2018-03-28T03:30:49.000Z | #include <bits/stdc++.h>
using namespace std;
#define SIZE 11000010
int radius[SIZE << 1];
string man;
void init(const string & str) {
memset(radius, 0, sizeof(radius));
man.clear();
man.push_back('#');
for (auto ch : str) {
man.push_back(ch);
man.push_back('#');
}
}
void manacher() {
int rightPt = -1, midPt = -1, len = man.size();
for (int i = 0; i < len; i++) {
radius[i] = i < rightPt ? min(radius[(midPt << 1) - i], radius[midPt] + midPt - i) : 1;
while (radius[i] < min(len - i, i + 1) && man[i + radius[i]] == man[i - radius[i]])
radius[i]++;
if (radius[i] + i > rightPt) {
rightPt = radius[i] + i;
midPt = i;
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
string str;
cin >> str;
init(str);
manacher();
int ans = 0;
for (int i = 0; i < (int)man.size(); i++)
ans = max(ans, radius[i]);
cout << ans - 1 << '\n';
return 0;
} | 21.87234 | 95 | 0.488327 | codgician |
0dc05ff01b6e68b3e8529d0234a5cd5841eee709 | 6,156 | cc | C++ | src/App.cc | ElChapos/BlockWorld | 9fcd224682ef52a1ca82d7f4ff6c1b39afe97b94 | [
"BSD-2-Clause"
] | 1 | 2016-05-24T17:25:51.000Z | 2016-05-24T17:25:51.000Z | src/App.cc | ElChapos/BlockWorld | 9fcd224682ef52a1ca82d7f4ff6c1b39afe97b94 | [
"BSD-2-Clause"
] | null | null | null | src/App.cc | ElChapos/BlockWorld | 9fcd224682ef52a1ca82d7f4ff6c1b39afe97b94 | [
"BSD-2-Clause"
] | null | null | null | #define GLEW_STATIC // Easier debugging
#define RUN_GRAPHICS_DISPLAY 0x00;
#include <GL/glew.h>
#ifdef __APPLE__
#include <OpenGL/gl.h>
#else
#include <GL/gl.h>
#endif
#include <SDL2/SDL.h>
#include <iostream>
#include <memory>
#include <boost/program_options.hpp>
#include "common.h"
#include "App.h"
#include "GameWorld.h"
/**
* SDL timers run in separate threads. In the timer thread
* push an event onto the event queue. This event signifies
* to call display() from the thread in which the OpenGL
* context was created.
*/
Uint32 tick(Uint32 interval, void *param)
{
SDL_Event event;
event.type = SDL_USEREVENT;
event.user.code = RUN_GRAPHICS_DISPLAY;
event.user.data1 = 0;
event.user.data2 = 0;
SDL_PushEvent(&event);
return interval;
}
/**
* Destroys the game SDL_Window
*/
struct SDLWindowDeleter
{
inline void operator()(SDL_Window* window)
{
SDL_DestroyWindow(window);
}
};
/**
* Handles global input from mouse and keyboard
*/
void App::HandleInput(const std::shared_ptr<GameWorld> &game_world)
{
int mouse_x;
int mouse_y;
const Uint8 * keyboard_state;
Input input_direction = NILL;
// For camera pitch/yaw
SDL_GetRelativeMouseState(&mouse_x, &mouse_y);
// Slow down the mouse_x and mouse_y
mouse_x = mouse_x*0.2;
mouse_y = mouse_y*0.2;
game_world->UpdateCameraPosition(input_direction, mouse_x, mouse_y);
// For keyboard presses
keyboard_state = SDL_GetKeyboardState(NULL);
if(keyboard_state[SDL_SCANCODE_W])
{
game_world->UpdateCameraPosition(UP, mouse_x, mouse_y);
}
if(keyboard_state[SDL_SCANCODE_A])
{
game_world->UpdateCameraPosition(LEFT, mouse_x, mouse_y);
}
if(keyboard_state[SDL_SCANCODE_S])
{
game_world->UpdateCameraPosition(DOWN, mouse_x, mouse_y);
}
if(keyboard_state[SDL_SCANCODE_D])
{
game_world->UpdateCameraPosition(RIGHT, mouse_x, mouse_y);
}
if(keyboard_state[SDL_SCANCODE_SPACE])
{
game_world->UpdateCameraPosition(SPACE, mouse_x, mouse_y);
}
if(keyboard_state[SDL_SCANCODE_LCTRL])
{
game_world->UpdateCameraPosition(CTRL, mouse_x, mouse_y);
}
if(SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(SDL_BUTTON_LEFT))
{
game_world->BlockAction(true);
}
if(SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(SDL_BUTTON_RIGHT))
{
game_world->BlockAction(false);
}
if(keyboard_state[SDL_SCANCODE_ESCAPE])
{
SDL_Quit();
}
if(keyboard_state[SDL_SCANCODE_1])
{
game_world->BlockType(BW_CUBE);
}
if(keyboard_state[SDL_SCANCODE_2])
{
game_world->BlockType(BW_STAR);
}
if(keyboard_state[SDL_SCANCODE_3])
{
game_world->BlockType(BW_DIAMOND);
}
}
/**
* Draws the colour and calls to GameWorld for Drawing
*/
void App::Draw(const std::shared_ptr<SDL_Window> &window, const std::shared_ptr<GameWorld> &game_world)
{
// Background
glClearColor(0.0f, 0.2f, 0.2f, 0.3f);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
game_world->Draw();
// Don't forget to swap the buffers
SDL_GL_SwapWindow(window.get());
}
/**
* Initialises the SDL_Window and OpenGL 3.0
*/
std::shared_ptr<SDL_Window> App::InitWorld()
{
Uint32 width = 1027;
Uint32 height = 768;
SDL_Window * _window;
std::shared_ptr<SDL_Window> window;
// Glew will later ensure that OpenGL 3 *is* supported
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
// Do double buffering in GL
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
// Initialise SDL - when using C/C++ it's common to have to
// initialise libraries by calling a function within them.
if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO|SDL_INIT_TIMER)<0)
{
std::cout << "Failed to initialise SDL: " << SDL_GetError() << std::endl;
return nullptr;
}
// When we close a window quit the SDL application
atexit(SDL_Quit);
SDL_ShowCursor(0);
// Create a new window with an OpenGL surface
_window = SDL_CreateWindow("BlockWorld",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
width,
height,
SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN
);
if (!_window)
{
std::cout << "Failed to create SDL window: " << SDL_GetError() << std::endl;
return nullptr;
}
SDL_GLContext glContext = SDL_GL_CreateContext(_window);
if (!glContext)
{
std::cout << "Failed to create OpenGL context: " << SDL_GetError() << std::endl;
return nullptr;
}
// Initialise GLEW - an easy way to ensure OpenGl 3.0+
// The *must* be done after we have set the video mode - otherwise we have no
// OpenGL context to test.
glewInit();
if (!glewIsSupported("GL_VERSION_3_0"))
{
std::cerr << "OpenGL 3.0 not available" << std::endl;
return nullptr;
}
// OpenGL settings
glDisable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
window.reset(_window, SDL_DestroyWindow);
return window;
}
/**
* Starts our game loop, called via Python or Main
*/
void App::Run()
{
Uint32 delay = 1000/60; // in milliseconds
auto window = InitWorld();
auto game_world = std::make_shared<GameWorld>();
if(!window)
{
SDL_Quit();
}
// Call the function "tick" every delay milliseconds
SDL_AddTimer(delay, tick, NULL);
SDL_SetRelativeMouseMode(SDL_TRUE);
// Add the main event loop
SDL_Event event;
while (SDL_WaitEvent(&event))
{
switch (event.type)
{
case SDL_QUIT:
{
SDL_Quit();
break;
}
case SDL_USEREVENT:
{
HandleInput(game_world);
Draw(window, game_world);
break;
}
default:
break;
}
}
}
| 24.722892 | 103 | 0.647336 | ElChapos |
0dc233941ea24ea4d103cddb6fb8270bc31dbbe1 | 3,192 | cpp | C++ | gcommon/source/gsoundmanager.cpp | DavidCoenFish/ancient-code-0 | 243fb47b9302a77f9b9392b6e3f90bba2ef3c228 | [
"Unlicense"
] | null | null | null | gcommon/source/gsoundmanager.cpp | DavidCoenFish/ancient-code-0 | 243fb47b9302a77f9b9392b6e3f90bba2ef3c228 | [
"Unlicense"
] | null | null | null | gcommon/source/gsoundmanager.cpp | DavidCoenFish/ancient-code-0 | 243fb47b9302a77f9b9392b6e3f90bba2ef3c228 | [
"Unlicense"
] | null | null | null | //
// GSoundManager.cpp
//
// Created by David Coen on 2011 03 11
// Copyright 2010 Pleasure seeking morons. All rights reserved.
//
#include "GSoundManager.h"
#include "GBuffer.h"
#include "GSoundBuffer.h"
#include "GSoundContext.h"
#include "GSoundLoad.h"
#include "GSoundManagerLoad.h"
#include "GSoundUtility.h"
#include "gassert.h"
#include <OpenAL/al.h>
#include <OpenAL/alc.h>
//constructor
GSoundManager::GSoundManager(
GFileSystem& inout_fileSystem,
const GSoundManagerLoad& in_soundManagerLoad,
const TArrayInt& in_arrayBufferIndexStaticGroup
)
: mDevice(0)
, mSoundContext()
, mArraySoundBuffer()
{
AL_ERROR_CHECK();
const ALCchar* defaultDevice;
defaultDevice = alcGetString(NULL, ALC_DEFAULT_DEVICE_SPECIFIER);
mDevice = alcOpenDevice(defaultDevice);
AL_ERROR_CHECK();
mSoundContext.reset(new GSoundContext(mDevice));
const int count = in_soundManagerLoad.GetArraySoundLoadCount();
mArraySoundBuffer.resize(count);
for (int index = 0; index < count; ++index)
{
const GSoundLoad& soundLoad = in_soundManagerLoad.GetArraySoundLoad()[index];
mArraySoundBuffer[index].reset(new GSoundBuffer(inout_fileSystem, soundLoad.GetResourceName()));
}
if (mSoundContext)
{
mSoundContext->CreateSoundSourceStaticGroup(
in_arrayBufferIndexStaticGroup,
mArraySoundBuffer
);
}
return;
}
GSoundManager::~GSoundManager()
{
mSoundContext.reset();
alcCloseDevice(mDevice);
return;
}
//public methods
void GSoundManager::CreateSoundSourceDynamicGroup(
const TArrayInt& in_arrayBufferIndex
)
{
if (mSoundContext)
{
mSoundContext->CreateSoundSourceDynamicGroup(
in_arrayBufferIndex,
mArraySoundBuffer
);
}
return;
}
GSoundManager::TWeakSoundSource GSoundManager::GetSoundSource(const int in_soundSourceIndex)
{
if (mSoundContext)
{
return mSoundContext->GetSoundSource(in_soundSourceIndex);
}
return TWeakSoundSource();
}
void GSoundManager::SetVolume(const float in_volume)
{
if (mSoundContext)
{
mSoundContext->SetVolume(in_volume);
}
return;
}
void GSoundManager::SetListenerPosition(
const GVector3Float& in_position,
const GVector3Float& in_at,
const GVector3Float& in_up,
const GVector3Float& in_velocity
)
{
if (mSoundContext)
{
mSoundContext->SetListenerPosition(
in_position,
in_at,
in_up,
in_velocity
);
}
return;
}
//GSoundManager::TWeakSoundContext GSoundManager::CreateSoundContext(
// const TArrayInt& in_arrayBufferIndex
// )
//{
// TPointerSoundContext pointerSoundContext;
//
// pointerSoundContext.reset(new GSoundContext(
// mDevice,
// in_arrayBufferIndex,
// mArraySoundBuffer
// ));
//
// mArraySoundContext.push_back(pointerSoundContext);
//
// return pointerSoundContext;
//}
//
//void GSoundManager::DestroySoundContext(
// TWeakSoundContext& in_soundContext
// )
//{
// TPointerSoundContext toErase = in_soundContext.lock();
// if (!toErase)
// {
// return;
// }
// TArrayPointerSoundContext::iterator iterator = mArraySoundContext.begin();
// while (iterator != mArraySoundContext.end())
// {
// if (*iterator == toErase)
// {
// iterator = mArraySoundContext.erase(iterator);
// }
// else
// {
// ++iterator;
// }
// }
//
// return;
//} | 19.228916 | 98 | 0.740602 | DavidCoenFish |
0dc5ef8e54d12820990e9e15b07f85e89723a40d | 900 | cpp | C++ | src/util/function.cpp | keszocze/abo | 2d59ac20832b308ef5f90744fc98752797a4f4ba | [
"MIT"
] | null | null | null | src/util/function.cpp | keszocze/abo | 2d59ac20832b308ef5f90744fc98752797a4f4ba | [
"MIT"
] | null | null | null | src/util/function.cpp | keszocze/abo | 2d59ac20832b308ef5f90744fc98752797a4f4ba | [
"MIT"
] | 1 | 2020-03-11T14:50:31.000Z | 2020-03-11T14:50:31.000Z | #include "function.hpp"
#include <algorithm>
#include <cassert>
namespace abo::util {
Function::Function(const Cudd &mgr, const std::vector<BDD> &value, NumberRepresentation representation) :
mgr(mgr),
value(value),
representation(representation)
{
assert(value.size() > 0);
}
BDD& Function::operator[](std::size_t index) {
return value.at(index);
}
const BDD& Function::operator[](std::size_t index) const {
return value.at(index);
}
Function Function::operator&(const BDD& b) const {
Function result = *this;
result &= b;
return result;
}
Function Function::operator|(const BDD& b) const {
Function result = *this;
result |= b;
return result;
}
void Function::operator&=(const BDD& b) {
for (BDD& own : value) {
own &= b;
}
}
void Function::operator|=(const BDD& b) {
for (BDD& own : value) {
own |= b;
}
}
}
| 18.75 | 105 | 0.626667 | keszocze |
0dc64440407d2d613efff0eb8498a34a4459d305 | 1,122 | cpp | C++ | data_structures/trie/CPP/trie_bits.cpp | CarbonDDR/al-go-rithms | 8e65affbe812931b7dde0e2933eb06c0f44b4130 | [
"CC0-1.0"
] | 1,253 | 2017-06-06T07:19:25.000Z | 2022-03-30T17:07:58.000Z | data_structures/trie/CPP/trie_bits.cpp | rishabh99-rc/al-go-rithms | 4df20d7ef7598fda4bc89101f9a99aac94cdd794 | [
"CC0-1.0"
] | 554 | 2017-09-29T18:56:01.000Z | 2022-02-21T15:48:13.000Z | data_structures/trie/CPP/trie_bits.cpp | rishabh99-rc/al-go-rithms | 4df20d7ef7598fda4bc89101f9a99aac94cdd794 | [
"CC0-1.0"
] | 2,226 | 2017-09-29T19:59:59.000Z | 2022-03-25T08:59:55.000Z | class trie {
struct node {
int words;
int prefix;
struct node *edge[2];
};
public:
struct node *root;
trie() {
root = newnode();
root -> words = 0;
root -> prefix = 0;
root -> edge[0] = root -> edge[1] = NULL;
}
struct node * newnode() {
struct node *x = (struct node *)malloc(sizeof(struct node));
return x;
}
void to_bits(int a[],int n) {
for(int i = 0;i < 32;i++) {
a[i] = n%2; n /= 2;
}
reverse(a,a+32);
}
void add(int n) {
int bits[32];
to_bits(bits,n);
struct node *x = root;
for(auto i: bits) {
x -> prefix += 1;
if(x -> edge[i] == NULL)
x -> edge[i] = newnode();
x = x -> edge[i];
}
x -> words += 1;
}
int cword(int n) {
int bits[32]; to_bits(bits,n);
struct node *x = root;
for(auto i: bits) {
if(x -> edge[i] == NULL)
return 0;
x = x -> edge[i];
}
return x -> words;
}
};
| 23.375 | 68 | 0.399287 | CarbonDDR |
0dc78a607390e1fcc4c43afa5600113d3d44d7c2 | 22,062 | hpp | C++ | src/algorithms/bfs.hpp | KIwabuchi/gbtl | 62c6b1e3262f3623359e793edb5ec4fa7bb471f0 | [
"Unlicense"
] | 112 | 2016-04-26T05:54:30.000Z | 2022-03-27T05:56:16.000Z | src/algorithms/bfs.hpp | KIwabuchi/gbtl | 62c6b1e3262f3623359e793edb5ec4fa7bb471f0 | [
"Unlicense"
] | 21 | 2016-03-22T19:06:46.000Z | 2021-10-07T15:40:18.000Z | src/algorithms/bfs.hpp | KIwabuchi/gbtl | 62c6b1e3262f3623359e793edb5ec4fa7bb471f0 | [
"Unlicense"
] | 22 | 2016-04-26T05:54:35.000Z | 2021-12-21T03:33:20.000Z | /*
* GraphBLAS Template Library (GBTL), Version 3.0
*
* Copyright 2020 Carnegie Mellon University, Battelle Memorial Institute, and
* Authors.
*
* THIS MATERIAL WAS PREPARED AS AN ACCOUNT OF WORK SPONSORED BY AN AGENCY OF
* THE UNITED STATES GOVERNMENT. NEITHER THE UNITED STATES GOVERNMENT NOR THE
* UNITED STATES DEPARTMENT OF ENERGY, NOR THE UNITED STATES DEPARTMENT OF
* DEFENSE, NOR CARNEGIE MELLON UNIVERSITY, NOR BATTELLE, NOR ANY OF THEIR
* EMPLOYEES, NOR ANY JURISDICTION OR ORGANIZATION THAT HAS COOPERATED IN THE
* DEVELOPMENT OF THESE MATERIALS, MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR
* ASSUMES ANY LEGAL LIABILITY OR RESPONSIBILITY FOR THE ACCURACY, COMPLETENESS,
* OR USEFULNESS OR ANY INFORMATION, APPARATUS, PRODUCT, SOFTWARE, OR PROCESS
* DISCLOSED, OR REPRESENTS THAT ITS USE WOULD NOT INFRINGE PRIVATELY OWNED
* RIGHTS.
*
* Released under a BSD-style license, please see LICENSE file or contact
* permission@sei.cmu.edu for full terms.
*
* [DISTRIBUTION STATEMENT A] This material has been approved for public release
* and unlimited distribution. Please see Copyright notice for non-US
* Government use and distribution.
*
* DM20-0442
*/
#pragma once
#include <limits>
#include <tuple>
#include <graphblas/graphblas.hpp>
//****************************************************************************
namespace algorithms
{
//************************************************************************
/**
* @brief Perform a single "parent" breadth first search (BFS) traversal
* on the given graph.
*
* @param[in] graph N x N adjacency matrix of the graph on which to
* perform a BFS. (NOT the transpose). The value
* 1 should indicate an edge.
* @param[in] source Index of the root vertex to use in the
* calculation.
* @param[out] parent_list The list of parents for each traversal (row)
* specified in the roots array.
*/
template <typename MatrixT,
typename ParentListVectorT>
void bfs(MatrixT const &graph,
grb::IndexType source,
ParentListVectorT &parent_list)
{
grb::IndexType const N(graph.nrows());
// assert parent_list is N-vector
// assert source is in proper range
// assert parent_list ScalarType is grb::IndexType
// create index ramp for index_of() functionality
grb::Vector<grb::IndexType> index_ramp(N);
for (grb::IndexType i = 0; i < N; ++i)
{
index_ramp.setElement(i, i);
}
// initialize wavefront to source node.
grb::Vector<grb::IndexType> wavefront(N);
wavefront.setElement(source, 1UL);
// set root parent to self;
parent_list.clear();
parent_list.setElement(source, source);
while (wavefront.nvals() > 0)
{
// convert all stored values to their column index
grb::eWiseMult(wavefront,
grb::NoMask(), grb::NoAccumulate(),
grb::First<grb::IndexType>(),
index_ramp, wavefront);
// First because we are left multiplying wavefront rows
// Masking out the parent list ensures wavefront values do not
// overlap values already stored in the parent list
grb::vxm(wavefront,
grb::complement(grb::structure(parent_list)),
grb::NoAccumulate(),
grb::MinFirstSemiring<grb::IndexType>(),
wavefront, graph, grb::REPLACE);
// We don't need to mask here since we did it in mxm.
// Merges new parents in current wavefront with existing parents
// parent_list<!parent_list,merge> += wavefront
grb::apply(parent_list,
grb::NoMask(),
grb::Plus<grb::IndexType>(),
grb::Identity<grb::IndexType>(),
wavefront,
grb::MERGE);
}
}
//************************************************************************
/**
* @brief Perform a single "parent" breadth first search (BFS) traversal
* on the given graph.
*
* @param[in] graph N x N adjacency matrix of the graph on which to
* perform a BFS. (NOT the transpose). The value
* 1 should indicate an edge.
* @param[in] wavefront N-vector, initial wavefront/root to use in the
* calculation. It should have a
* single value set to '1' corresponding to the
* root.
* @param[out] parent_list The list of parents for each traversal (row)
* specified in the roots array.
*/
template <typename MatrixT,
typename WavefrontVectorT,
typename ParentListVectorT>
void bfs(MatrixT const &graph,
WavefrontVectorT wavefront, // copy is intentional
ParentListVectorT &parent_list)
{
using T = typename MatrixT::ScalarType;
grb::IndexType const N(graph.nrows());
// assert parent_list is N-vector
// assert wavefront is N-vector
// assert parent_list ScalarType is grb::IndexType
// create index ramp for index_of() functionality
grb::Vector<grb::IndexType> index_ramp(N);
for (grb::IndexType i = 0; i < N; ++i)
{
index_ramp.setElement(i, i);
}
// Set the roots parents to themselves using indices
grb::eWiseMult(parent_list,
grb::NoMask(), grb::NoAccumulate(),
grb::First<grb::IndexType>(),
index_ramp, wavefront);
// convert all stored values to their column index
grb::eWiseMult(parent_list,
grb::NoMask(), grb::NoAccumulate(),
grb::First<grb::IndexType>(),
index_ramp, parent_list);
while (wavefront.nvals() > 0)
{
// convert all stored values to their column index
grb::eWiseMult(wavefront,
grb::NoMask(), grb::NoAccumulate(),
grb::First<grb::IndexType>(),
index_ramp, wavefront);
// First because we are left multiplying wavefront rows
// Masking out the parent list ensures wavefront values do not
// overlap values already stored in the parent list
grb::vxm(wavefront,
grb::complement(grb::structure(parent_list)),
grb::NoAccumulate(),
grb::MinFirstSemiring<T>(),
wavefront, graph, grb::REPLACE);
// We don't need to mask here since we did it in mxm.
// Merges new parents in current wavefront with existing parents
// parent_list<!parent_list,merge> += wavefront
grb::apply(parent_list,
grb::NoMask(),
grb::Plus<T>(),
grb::Identity<T>(),
wavefront,
grb::MERGE);
}
}
//************************************************************************
/**
* @brief Perform a set of breadth first search (BFS) traversals on the
* given graph.
*
* @param[in] graph N x N adjacency matrix of the graph on which to
* perform a BFS. (NOT the transpose). The value
* 1 should indicate an edge,
* @param[in] wavefronts R x N, initial wavefront(s)/root(s) to use in the
* calculation. Each row (1) corresponds to a
* different BFS traversal and (2) should have a
* single value set to '1' corresponding to the
* root.
* @param[out] parent_list The list of parents for each traversal (row)
* specified in the roots array.
*/
template <typename MatrixT,
typename WavefrontMatrixT,
typename ParentListMatrixT>
void bfs_batch(MatrixT const &graph,
WavefrontMatrixT wavefronts, // copy is intentional
ParentListMatrixT &parent_list)
{
using T = typename MatrixT::ScalarType;
grb::IndexType const N(graph.nrows());
// assert parent_list is RxN
// assert wavefront is RxN
// assert parent_list ScalarType is grb::IndexType
// create index ramp for index_of() functionality
grb::Matrix<grb::IndexType> index_ramp(N, N);
for (grb::IndexType idx = 0; idx < N; ++idx)
{
index_ramp.setElement(idx, idx, idx);
}
// Set the roots parents to themselves.
grb::mxm(parent_list,
grb::NoMask(), grb::NoAccumulate(),
grb::MinSecondSemiring<T>(),
wavefronts, index_ramp);
while (wavefronts.nvals() > 0)
{
// convert all stored values to their column index
grb::mxm(wavefronts,
grb::NoMask(), grb::NoAccumulate(),
grb::MinSecondSemiring<T>(),
wavefronts, index_ramp);
// First because we are left multiplying wavefront rows
// Masking out the parent list ensures wavefronts values do not
// overlap values already stored in the parent list
grb::mxm(wavefronts,
grb::complement(grb::structure(parent_list)),
grb::NoAccumulate(),
grb::MinFirstSemiring<T>(),
wavefronts, graph, grb::REPLACE);
// We don't need to mask here since we did it in mxm.
// Merges new parents in current wavefront with existing parents
// parent_list<!parent_list,merge> += wavefronts
grb::apply(parent_list,
grb::NoMask(),
grb::Plus<T>(),
grb::Identity<T>(),
wavefronts,
grb::MERGE);
}
}
//************************************************************************
/**
* @brief Perform a single "level" breadth first search (BFS) traversal
* on the given graph.
*
* @param[in] graph N x N adjacency matrix of the graph on which to
* perform a BFS. (NOT the transpose). The value
* 1 should indicate an edge.
* @param[in] source Index of the root vertex to use in the
* calculation.
* @param[out] levels The level (distance in unweighted graphs) from
* the source (root) of the BFS.
*/
template <typename MatrixT,
typename LevelsVectorT>
void bfs_level(MatrixT const &graph,
grb::IndexType source,
LevelsVectorT &levels)
{
grb::IndexType const N(graph.nrows());
/// @todo Assert graph is square
grb::Vector<bool> wavefront(N);
wavefront.setElement(source, true);
grb::IndexType depth(0);
while (wavefront.nvals() > 0)
{
// Increment the level
++depth;
// Apply the level to all newly visited nodes
grb::apply(levels, grb::NoMask(),
grb::Plus<grb::IndexType>(),
//[depth](auto arg) { return arg * depth; },
std::bind(grb::Times<grb::IndexType>(),
depth,
std::placeholders::_1),
wavefront);
grb::mxv(wavefront, complement(levels),
grb::NoAccumulate(),
grb::LogicalSemiring<bool>(),
transpose(graph), wavefront, grb::REPLACE);
}
}
//************************************************************************
/**
* @brief Perform a breadth first search (BFS) on the given graph.
*
* @param[in] graph The graph to perform a BFS on. NOT built from
* the transpose of the adjacency matrix.
* (1 indicates edge, structural zero = 0).
* @param[in] wavefront The initial wavefront to use in the calculation.
* (1 indicates root, structural zero = 0).
* @param[out] levels The level (distance in unweighted graphs) from
* the corresponding root of that BFS
*
* @deprecated Use batched_bfs_level_masked
*/
template <typename MatrixT,
typename WavefrontMatrixT,
typename LevelListMatrixT>
void bfs_level(MatrixT const &graph,
WavefrontMatrixT wavefront, //row vectors, copy made
LevelListMatrixT &levels)
{
/// @todo Assert graph is square
/// @todo Assert graph has a compatible shape with wavefront?
unsigned int depth = 0;
while (wavefront.nvals() > 0)
{
// Increment the level
++depth;
// Apply the level to all newly visited nodes
grb::apply(levels,
grb::NoMask(),
grb::Plus<unsigned int>(),
std::bind(grb::Times<unsigned int>(),
depth,
std::placeholders::_1),
wavefront,
grb::REPLACE);
grb::mxm(wavefront,
grb::NoMask(),
grb::NoAccumulate(),
grb::LogicalSemiring<unsigned int>(),
wavefront, graph,
grb::REPLACE);
// Cull previously visited nodes from the wavefront
grb::apply(
wavefront,
grb::complement(levels),
grb::NoAccumulate(),
grb::Identity<typename WavefrontMatrixT::ScalarType>(),
wavefront,
grb::REPLACE);
}
}
//************************************************************************
/**
* @brief Perform a single breadth first searches (BFS) on the given graph.
*
* @param[in] graph NxN adjacency matrix of the graph on which to
* perform a BFS (not the transpose). A value of
* 1 indicates an edge (structural zero = 0).
* @param[in] wavefront N-vector initial wavefront to use in the calculation
* of R simultaneous traversals. A value of 1 in a
* given position indicates a root for the
* traversal..
* @param[out] levels The level (distance in unweighted graphs) from
* the corresponding root of that BFS. Roots are
* assigned a value of 1. (a value of 0 implies not
* reachable.
*/
template <typename MatrixT,
typename WavefrontT,
typename LevelListT>
void bfs_level_masked(MatrixT const &graph,
WavefrontT wavefront, //row vector, copy made
LevelListT &levels)
{
/// Assert graph is square/have a compatible shape with wavefront
grb::IndexType grows(graph.nrows());
grb::IndexType gcols(graph.ncols());
grb::IndexType wsize(wavefront.size());
if ((grows != gcols) || (wsize != grows))
{
throw grb::DimensionException();
}
grb::IndexType depth = 0;
while (wavefront.nvals() > 0)
{
// Increment the level
++depth;
// Apply the level to all newly visited nodes
grb::apply(levels,
grb::NoMask(),
grb::Plus<unsigned int>(),
std::bind(grb::Times<grb::IndexType>(),
depth,
std::placeholders::_1),
wavefront,
grb::REPLACE);
// Advance the wavefront and mask out nodes already assigned levels
grb::vxm(wavefront,
grb::complement(levels),
grb::NoAccumulate(),
grb::LogicalSemiring<grb::IndexType>(),
wavefront, graph,
grb::REPLACE);
}
}
//************************************************************************
/**
* @brief Perform multiple breadth first searches (BFS) on the given graph.
*
* @param[in] graph NxN adjacency matrix of the graph on which to
* perform a BFS (not the transpose). A value of
* 1 indicates an edge (structural zero = 0).
* @param[in] wavefronts RxN initial wavefronts to use in the calculation
* of R simultaneous traversals. A value of 1 in a
* given row indicates a root for the corresponding
* traversal. (structural zero = 0).
* @param[out] levels The level (distance in unweighted graphs) from
* the corresponding root of that BFS. Roots are
* assigned a value of 1. (a value of 0 implies not
* reachable.
*/
template <typename MatrixT,
typename WavefrontsMatrixT,
typename LevelListMatrixT>
void batch_bfs_level_masked(MatrixT const &graph,
WavefrontsMatrixT wavefronts, //row vectors, copy
LevelListMatrixT &levels)
{
/// Assert graph is square/have a compatible shape with wavefronts
grb::IndexType grows(graph.nrows());
grb::IndexType gcols(graph.ncols());
grb::IndexType cols(wavefronts.ncols());
if ((grows != gcols) || (cols != grows))
{
throw grb::DimensionException();
}
grb::IndexType depth = 0;
while (wavefronts.nvals() > 0)
{
// Increment the level
++depth;
// Apply the level to all newly visited nodes
grb::apply(levels,
grb::NoMask(),
grb::Plus<unsigned int>(),
std::bind(grb::Times<grb::IndexType>(),
depth,
std::placeholders::_1),
wavefronts,
grb::REPLACE);
// Advance the wavefronts and mask out nodes already assigned levels
grb::mxm(wavefronts,
grb::complement(levels),
grb::NoAccumulate(),
grb::LogicalSemiring<grb::IndexType>(),
wavefronts, graph,
grb::REPLACE);
}
}
//************************************************************************
/**
* @brief Perform a single breadth first searches (BFS) on the given graph.
*
* @param[in] graph NxN adjacency matrix of the graph on which to
* perform a BFS (not the transpose). A value of
* 1 indicates an edge (structural zero = 0).
* @param[in] wavefront N-vector initial wavefront to use in the calculation
* of R simultaneous traversals. A value of 1 in a
* given position indicates a root for the
* traversal..
* @param[out] levels The level (distance in unweighted graphs) from
* the corresponding root of that BFS. Roots are
* assigned a value of 1. (a value of 0 implies not
* reachable.
*/
template <typename MatrixT,
typename WavefrontT,
typename LevelListT>
void bfs_level_masked_v2(MatrixT const &graph,
WavefrontT wavefront, //row vector, copy made
LevelListT &levels)
{
/// Assert graph is square/have a compatible shape with wavefront
grb::IndexType grows(graph.nrows());
grb::IndexType gcols(graph.ncols());
grb::IndexType wsize(wavefront.size());
if ((grows != gcols) || (wsize != grows))
{
throw grb::DimensionException();
}
grb::IndexType depth = 0;
while (wavefront.nvals() > 0)
{
// Increment the level
++depth;
grb::assign(levels,
wavefront,
grb::NoAccumulate(),
depth,
grb::AllIndices(),
grb::MERGE);
// Advance the wavefront and mask out nodes already assigned levels
grb::vxm(wavefront,
grb::complement(levels),
grb::NoAccumulate(),
grb::LogicalSemiring<grb::IndexType>(),
wavefront, graph,
grb::REPLACE);
}
}
}
| 40.780037 | 82 | 0.493382 | KIwabuchi |
0dcb057950b893631379a1046ec6e5980495ccf5 | 1,175 | hpp | C++ | include/fcppt/container/is_raw_vector.hpp | vinzenz/fcppt | 3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a | [
"BSL-1.0"
] | null | null | null | include/fcppt/container/is_raw_vector.hpp | vinzenz/fcppt | 3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a | [
"BSL-1.0"
] | null | null | null | include/fcppt/container/is_raw_vector.hpp | vinzenz/fcppt | 3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a | [
"BSL-1.0"
] | null | null | null | // Copyright Carl Philipp Reh 2009 - 2016.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef FCPPT_CONTAINER_IS_RAW_VECTOR_HPP_INCLUDED
#define FCPPT_CONTAINER_IS_RAW_VECTOR_HPP_INCLUDED
#include <fcppt/container/raw_vector_fwd.hpp>
#include <fcppt/preprocessor/disable_gcc_warning.hpp>
#include <fcppt/preprocessor/pop_warning.hpp>
#include <fcppt/preprocessor/push_warning.hpp>
#include <fcppt/config/external_begin.hpp>
#include <type_traits>
#include <fcppt/config/external_end.hpp>
namespace fcppt
{
namespace container
{
FCPPT_PP_PUSH_WARNING
FCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)
/**
\brief Metafunction to test if a container is a fcppt::container::raw_vector
\ingroup fcpptcontainer
*/
template<
typename T
>
struct is_raw_vector
:
std::false_type
{};
// Without this, doxygen generates another raw_vector type (wtf?)
/// \cond FCPPT_DOXYGEN_DEBUG
template<
typename T,
typename A
>
struct is_raw_vector<
fcppt::container::raw_vector<
T,
A
>
>
:
std::true_type
{};
/// \endcond
FCPPT_PP_POP_WARNING
}
}
#endif
| 18.951613 | 76 | 0.765106 | vinzenz |
0dcfca94ba8ea1a603a51334ea8cc925cdc8cc88 | 26,336 | cpp | C++ | Engine/Src/SFEngine/Graphics/Vulkan/SFVulkanLibrary.cpp | blue3k/StormForge | 1557e699a673ae9adcc8f987868139f601ec0887 | [
"Apache-2.0"
] | 1 | 2020-06-20T07:35:25.000Z | 2020-06-20T07:35:25.000Z | Engine/Src/SFEngine/Graphics/Vulkan/SFVulkanLibrary.cpp | blue3k/StormForge | 1557e699a673ae9adcc8f987868139f601ec0887 | [
"Apache-2.0"
] | null | null | null | Engine/Src/SFEngine/Graphics/Vulkan/SFVulkanLibrary.cpp | blue3k/StormForge | 1557e699a673ae9adcc8f987868139f601ec0887 | [
"Apache-2.0"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
//
// CopyRight (c) 2017 Kyungkun Ko
//
// Author : KyungKun Ko
//
// Description : Vulkan library
//
////////////////////////////////////////////////////////////////////////////////
#include "SFEnginePCH.h"
#include "SFVulkanLibrary.h"
#if HAVE_VULKAN
#if SF_PLATFORM == SF_PLATFORM_ANDROID
#include <dlfcn.h>
#define LOAD_VULKAN_LIBRARY() dlopen("libvulkan.so", RTLD_NOW | RTLD_LOCAL)
namespace SF
{
template<class FunctionType>
FunctionType GetDLLProcAddress(void* dllInstance, const char* procName)
{
return reinterpret_cast<FunctionType>(dlsym(dllInstance, procName));
}
}
#elif SF_PLATFORM == SF_PLATFORM_WINDOWS
#define LOAD_VULKAN_LIBRARY() LoadLibraryA("vulkan-1.dll")
namespace SF
{
template<class FunctionType>
FunctionType GetDLLProcAddress(HMODULE dllInstance, const char* procName)
{
return reinterpret_cast<FunctionType>(GetProcAddress(dllInstance, procName));
}
}
#else
#error "Not supported platform"
#endif
#define GET_PROCADDRESS(libvulkan, procName) GetDLLProcAddress<PFN_##procName>(libvulkan, #procName)
namespace SF
{
bool SFVulkanLibrary_Initialize()
{
#if SF_VULKAN_DYNAMIC_LIBRARY
if (vkCreateInstance != nullptr)
return true;
auto libvulkan = LOAD_VULKAN_LIBRARY();
if (!libvulkan)
{
assert(false);
return false;
}
// Vulkan supported, set function addresses
vkCreateInstance = GET_PROCADDRESS(libvulkan, vkCreateInstance);
vkDestroyInstance = GET_PROCADDRESS(libvulkan, vkDestroyInstance);
vkEnumeratePhysicalDevices = GET_PROCADDRESS(libvulkan, vkEnumeratePhysicalDevices);
vkGetPhysicalDeviceFeatures = GET_PROCADDRESS(libvulkan, vkGetPhysicalDeviceFeatures);
vkGetPhysicalDeviceFormatProperties = GET_PROCADDRESS(libvulkan, vkGetPhysicalDeviceFormatProperties);
vkGetPhysicalDeviceImageFormatProperties = GET_PROCADDRESS(libvulkan, vkGetPhysicalDeviceImageFormatProperties);
vkGetPhysicalDeviceProperties = GET_PROCADDRESS(libvulkan, vkGetPhysicalDeviceProperties);
vkGetPhysicalDeviceQueueFamilyProperties = GET_PROCADDRESS(libvulkan, vkGetPhysicalDeviceQueueFamilyProperties);
vkGetPhysicalDeviceMemoryProperties = GET_PROCADDRESS(libvulkan, vkGetPhysicalDeviceMemoryProperties);
vkGetInstanceProcAddr = GET_PROCADDRESS(libvulkan, vkGetInstanceProcAddr);
vkGetDeviceProcAddr = GET_PROCADDRESS(libvulkan, vkGetDeviceProcAddr);
vkCreateDevice = GET_PROCADDRESS(libvulkan, vkCreateDevice);
vkDestroyDevice = GET_PROCADDRESS(libvulkan, vkDestroyDevice);
vkEnumerateInstanceExtensionProperties = GET_PROCADDRESS(libvulkan, vkEnumerateInstanceExtensionProperties);
vkEnumerateDeviceExtensionProperties = GET_PROCADDRESS(libvulkan, vkEnumerateDeviceExtensionProperties);
vkEnumerateInstanceLayerProperties = GET_PROCADDRESS(libvulkan, vkEnumerateInstanceLayerProperties);
vkEnumerateDeviceLayerProperties = GET_PROCADDRESS(libvulkan, vkEnumerateDeviceLayerProperties);
vkGetDeviceQueue = GET_PROCADDRESS(libvulkan, vkGetDeviceQueue);
vkQueueSubmit = GET_PROCADDRESS(libvulkan, vkQueueSubmit);
vkQueueWaitIdle = GET_PROCADDRESS(libvulkan, vkQueueWaitIdle);
vkDeviceWaitIdle = GET_PROCADDRESS(libvulkan, vkDeviceWaitIdle);
vkAllocateMemory = GET_PROCADDRESS(libvulkan, vkAllocateMemory);
vkFreeMemory = GET_PROCADDRESS(libvulkan, vkFreeMemory);
vkMapMemory = GET_PROCADDRESS(libvulkan, vkMapMemory);
vkUnmapMemory = GET_PROCADDRESS(libvulkan, vkUnmapMemory);
vkFlushMappedMemoryRanges = GET_PROCADDRESS(libvulkan, vkFlushMappedMemoryRanges);
vkInvalidateMappedMemoryRanges = GET_PROCADDRESS(libvulkan, vkInvalidateMappedMemoryRanges);
vkGetDeviceMemoryCommitment = GET_PROCADDRESS(libvulkan, vkGetDeviceMemoryCommitment);
vkBindBufferMemory = GET_PROCADDRESS(libvulkan, vkBindBufferMemory);
vkBindImageMemory = GET_PROCADDRESS(libvulkan, vkBindImageMemory);
vkGetBufferMemoryRequirements = GET_PROCADDRESS(libvulkan, vkGetBufferMemoryRequirements);
vkGetImageMemoryRequirements = GET_PROCADDRESS(libvulkan, vkGetImageMemoryRequirements);
vkGetImageSparseMemoryRequirements = GET_PROCADDRESS(libvulkan, vkGetImageSparseMemoryRequirements);
vkGetPhysicalDeviceSparseImageFormatProperties = GET_PROCADDRESS(libvulkan, vkGetPhysicalDeviceSparseImageFormatProperties);
vkQueueBindSparse = GET_PROCADDRESS(libvulkan, vkQueueBindSparse);
vkCreateFence = GET_PROCADDRESS(libvulkan, vkCreateFence);
vkDestroyFence = GET_PROCADDRESS(libvulkan, vkDestroyFence);
vkResetFences = GET_PROCADDRESS(libvulkan, vkResetFences);
vkGetFenceStatus = GET_PROCADDRESS(libvulkan, vkGetFenceStatus);
vkWaitForFences = GET_PROCADDRESS(libvulkan, vkWaitForFences);
vkCreateSemaphore = GET_PROCADDRESS(libvulkan, vkCreateSemaphore);
vkDestroySemaphore = GET_PROCADDRESS(libvulkan, vkDestroySemaphore);
vkCreateEvent = GET_PROCADDRESS(libvulkan, vkCreateEvent);
vkDestroyEvent = GET_PROCADDRESS(libvulkan, vkDestroyEvent);
vkGetEventStatus = GET_PROCADDRESS(libvulkan, vkGetEventStatus);
vkSetEvent = GET_PROCADDRESS(libvulkan, vkSetEvent);
vkResetEvent = GET_PROCADDRESS(libvulkan, vkResetEvent);
vkCreateQueryPool = GET_PROCADDRESS(libvulkan, vkCreateQueryPool);
vkDestroyQueryPool = GET_PROCADDRESS(libvulkan, vkDestroyQueryPool);
vkGetQueryPoolResults = GET_PROCADDRESS(libvulkan, vkGetQueryPoolResults);
vkCreateBuffer = GET_PROCADDRESS(libvulkan, vkCreateBuffer);
vkDestroyBuffer = GET_PROCADDRESS(libvulkan, vkDestroyBuffer);
vkCreateBufferView = GET_PROCADDRESS(libvulkan, vkCreateBufferView);
vkDestroyBufferView = GET_PROCADDRESS(libvulkan, vkDestroyBufferView);
vkCreateImage = GET_PROCADDRESS(libvulkan, vkCreateImage);
vkDestroyImage = GET_PROCADDRESS(libvulkan, vkDestroyImage);
vkGetImageSubresourceLayout = GET_PROCADDRESS(libvulkan, vkGetImageSubresourceLayout);
vkCreateImageView = GET_PROCADDRESS(libvulkan, vkCreateImageView);
vkDestroyImageView = GET_PROCADDRESS(libvulkan, vkDestroyImageView);
vkCreateShaderModule = GET_PROCADDRESS(libvulkan, vkCreateShaderModule);
vkDestroyShaderModule = GET_PROCADDRESS(libvulkan, vkDestroyShaderModule);
vkCreatePipelineCache = GET_PROCADDRESS(libvulkan, vkCreatePipelineCache);
vkDestroyPipelineCache = GET_PROCADDRESS(libvulkan, vkDestroyPipelineCache);
vkGetPipelineCacheData = GET_PROCADDRESS(libvulkan, vkGetPipelineCacheData);
vkMergePipelineCaches = GET_PROCADDRESS(libvulkan, vkMergePipelineCaches);
vkCreateGraphicsPipelines = GET_PROCADDRESS(libvulkan, vkCreateGraphicsPipelines);
vkCreateComputePipelines = GET_PROCADDRESS(libvulkan, vkCreateComputePipelines);
vkDestroyPipeline = GET_PROCADDRESS(libvulkan, vkDestroyPipeline);
vkCreatePipelineLayout = GET_PROCADDRESS(libvulkan, vkCreatePipelineLayout);
vkDestroyPipelineLayout = GET_PROCADDRESS(libvulkan, vkDestroyPipelineLayout);
vkCreateSampler = GET_PROCADDRESS(libvulkan, vkCreateSampler);
vkDestroySampler = GET_PROCADDRESS(libvulkan, vkDestroySampler);
vkCreateDescriptorSetLayout = GET_PROCADDRESS(libvulkan, vkCreateDescriptorSetLayout);
vkDestroyDescriptorSetLayout = GET_PROCADDRESS(libvulkan, vkDestroyDescriptorSetLayout);
vkCreateDescriptorPool = GET_PROCADDRESS(libvulkan, vkCreateDescriptorPool);
vkDestroyDescriptorPool = GET_PROCADDRESS(libvulkan, vkDestroyDescriptorPool);
vkResetDescriptorPool = GET_PROCADDRESS(libvulkan, vkResetDescriptorPool);
vkAllocateDescriptorSets = GET_PROCADDRESS(libvulkan, vkAllocateDescriptorSets);
vkFreeDescriptorSets = GET_PROCADDRESS(libvulkan, vkFreeDescriptorSets);
vkUpdateDescriptorSets = GET_PROCADDRESS(libvulkan, vkUpdateDescriptorSets);
vkCreateFramebuffer = GET_PROCADDRESS(libvulkan, vkCreateFramebuffer);
vkDestroyFramebuffer = GET_PROCADDRESS(libvulkan, vkDestroyFramebuffer);
vkCreateRenderPass = GET_PROCADDRESS(libvulkan, vkCreateRenderPass);
vkDestroyRenderPass = GET_PROCADDRESS(libvulkan, vkDestroyRenderPass);
vkGetRenderAreaGranularity = GET_PROCADDRESS(libvulkan, vkGetRenderAreaGranularity);
vkCreateCommandPool = GET_PROCADDRESS(libvulkan, vkCreateCommandPool);
vkDestroyCommandPool = GET_PROCADDRESS(libvulkan, vkDestroyCommandPool);
vkResetCommandPool = GET_PROCADDRESS(libvulkan, vkResetCommandPool);
vkAllocateCommandBuffers = GET_PROCADDRESS(libvulkan, vkAllocateCommandBuffers);
vkFreeCommandBuffers = GET_PROCADDRESS(libvulkan, vkFreeCommandBuffers);
vkBeginCommandBuffer = GET_PROCADDRESS(libvulkan, vkBeginCommandBuffer);
vkEndCommandBuffer = GET_PROCADDRESS(libvulkan, vkEndCommandBuffer);
vkResetCommandBuffer = GET_PROCADDRESS(libvulkan, vkResetCommandBuffer);
vkCmdBindPipeline = GET_PROCADDRESS(libvulkan, vkCmdBindPipeline);
vkCmdSetViewport = GET_PROCADDRESS(libvulkan, vkCmdSetViewport);
vkCmdSetScissor = GET_PROCADDRESS(libvulkan, vkCmdSetScissor);
vkCmdSetLineWidth = GET_PROCADDRESS(libvulkan, vkCmdSetLineWidth);
vkCmdSetDepthBias = GET_PROCADDRESS(libvulkan, vkCmdSetDepthBias);
vkCmdSetBlendConstants = GET_PROCADDRESS(libvulkan, vkCmdSetBlendConstants);
vkCmdSetDepthBounds = GET_PROCADDRESS(libvulkan, vkCmdSetDepthBounds);
vkCmdSetStencilCompareMask = GET_PROCADDRESS(libvulkan, vkCmdSetStencilCompareMask);
vkCmdSetStencilWriteMask = GET_PROCADDRESS(libvulkan, vkCmdSetStencilWriteMask);
vkCmdSetStencilReference = GET_PROCADDRESS(libvulkan, vkCmdSetStencilReference);
vkCmdBindDescriptorSets = GET_PROCADDRESS(libvulkan, vkCmdBindDescriptorSets);
vkCmdBindIndexBuffer = GET_PROCADDRESS(libvulkan, vkCmdBindIndexBuffer);
vkCmdBindVertexBuffers = GET_PROCADDRESS(libvulkan, vkCmdBindVertexBuffers);
vkCmdDraw = GET_PROCADDRESS(libvulkan, vkCmdDraw);
vkCmdDrawIndexed = GET_PROCADDRESS(libvulkan, vkCmdDrawIndexed);
vkCmdDrawIndirect = GET_PROCADDRESS(libvulkan, vkCmdDrawIndirect);
vkCmdDrawIndexedIndirect = GET_PROCADDRESS(libvulkan, vkCmdDrawIndexedIndirect);
vkCmdDispatch = GET_PROCADDRESS(libvulkan, vkCmdDispatch);
vkCmdDispatchIndirect = GET_PROCADDRESS(libvulkan, vkCmdDispatchIndirect);
vkCmdCopyBuffer = GET_PROCADDRESS(libvulkan, vkCmdCopyBuffer);
vkCmdCopyImage = GET_PROCADDRESS(libvulkan, vkCmdCopyImage);
vkCmdBlitImage = GET_PROCADDRESS(libvulkan, vkCmdBlitImage);
vkCmdCopyBufferToImage = GET_PROCADDRESS(libvulkan, vkCmdCopyBufferToImage);
vkCmdCopyImageToBuffer = GET_PROCADDRESS(libvulkan, vkCmdCopyImageToBuffer);
vkCmdUpdateBuffer = GET_PROCADDRESS(libvulkan, vkCmdUpdateBuffer);
vkCmdFillBuffer = GET_PROCADDRESS(libvulkan, vkCmdFillBuffer);
vkCmdClearColorImage = GET_PROCADDRESS(libvulkan, vkCmdClearColorImage);
vkCmdClearDepthStencilImage = GET_PROCADDRESS(libvulkan, vkCmdClearDepthStencilImage);
vkCmdClearAttachments = GET_PROCADDRESS(libvulkan, vkCmdClearAttachments);
vkCmdResolveImage = GET_PROCADDRESS(libvulkan, vkCmdResolveImage);
vkCmdSetEvent = GET_PROCADDRESS(libvulkan, vkCmdSetEvent);
vkCmdResetEvent = GET_PROCADDRESS(libvulkan, vkCmdResetEvent);
vkCmdWaitEvents = GET_PROCADDRESS(libvulkan, vkCmdWaitEvents);
vkCmdPipelineBarrier = GET_PROCADDRESS(libvulkan, vkCmdPipelineBarrier);
vkCmdBeginQuery = GET_PROCADDRESS(libvulkan, vkCmdBeginQuery);
vkCmdEndQuery = GET_PROCADDRESS(libvulkan, vkCmdEndQuery);
vkCmdResetQueryPool = GET_PROCADDRESS(libvulkan, vkCmdResetQueryPool);
vkCmdWriteTimestamp = GET_PROCADDRESS(libvulkan, vkCmdWriteTimestamp);
vkCmdCopyQueryPoolResults = GET_PROCADDRESS(libvulkan, vkCmdCopyQueryPoolResults);
vkCmdPushConstants = GET_PROCADDRESS(libvulkan, vkCmdPushConstants);
vkCmdBeginRenderPass = GET_PROCADDRESS(libvulkan, vkCmdBeginRenderPass);
vkCmdNextSubpass = GET_PROCADDRESS(libvulkan, vkCmdNextSubpass);
vkCmdEndRenderPass = GET_PROCADDRESS(libvulkan, vkCmdEndRenderPass);
vkCmdExecuteCommands = GET_PROCADDRESS(libvulkan, vkCmdExecuteCommands);
vkDestroySurfaceKHR = GET_PROCADDRESS(libvulkan, vkDestroySurfaceKHR);
vkGetPhysicalDeviceSurfaceSupportKHR = GET_PROCADDRESS(libvulkan, vkGetPhysicalDeviceSurfaceSupportKHR);
vkGetPhysicalDeviceSurfaceCapabilitiesKHR = GET_PROCADDRESS(libvulkan, vkGetPhysicalDeviceSurfaceCapabilitiesKHR);
vkGetPhysicalDeviceSurfaceFormatsKHR = GET_PROCADDRESS(libvulkan, vkGetPhysicalDeviceSurfaceFormatsKHR);
vkGetPhysicalDeviceSurfacePresentModesKHR = GET_PROCADDRESS(libvulkan, vkGetPhysicalDeviceSurfacePresentModesKHR);
vkCreateSwapchainKHR = GET_PROCADDRESS(libvulkan, vkCreateSwapchainKHR);
vkDestroySwapchainKHR = GET_PROCADDRESS(libvulkan, vkDestroySwapchainKHR);
vkGetSwapchainImagesKHR = GET_PROCADDRESS(libvulkan, vkGetSwapchainImagesKHR);
vkAcquireNextImageKHR = GET_PROCADDRESS(libvulkan, vkAcquireNextImageKHR);
vkQueuePresentKHR = GET_PROCADDRESS(libvulkan, vkQueuePresentKHR);
vkGetPhysicalDeviceDisplayPropertiesKHR = GET_PROCADDRESS(libvulkan, vkGetPhysicalDeviceDisplayPropertiesKHR);
vkGetPhysicalDeviceDisplayPlanePropertiesKHR = GET_PROCADDRESS(libvulkan, vkGetPhysicalDeviceDisplayPlanePropertiesKHR);
vkGetDisplayPlaneSupportedDisplaysKHR = GET_PROCADDRESS(libvulkan, vkGetDisplayPlaneSupportedDisplaysKHR);
vkGetDisplayModePropertiesKHR = GET_PROCADDRESS(libvulkan, vkGetDisplayModePropertiesKHR);
vkCreateDisplayModeKHR = GET_PROCADDRESS(libvulkan, vkCreateDisplayModeKHR);
vkGetDisplayPlaneCapabilitiesKHR = GET_PROCADDRESS(libvulkan, vkGetDisplayPlaneCapabilitiesKHR);
vkCreateDisplayPlaneSurfaceKHR = GET_PROCADDRESS(libvulkan, vkCreateDisplayPlaneSurfaceKHR);
vkCreateSharedSwapchainsKHR = GET_PROCADDRESS(libvulkan, vkCreateSharedSwapchainsKHR);
#ifdef VK_USE_PLATFORM_XLIB_KHR
vkCreateXlibSurfaceKHR = GET_PROCADDRESS(libvulkan, vkCreateXlibSurfaceKHR);
vkGetPhysicalDeviceXlibPresentationSupportKHR = GET_PROCADDRESS(libvulkan, vkGetPhysicalDeviceXlibPresentationSupportKHR);
#endif
#ifdef VK_USE_PLATFORM_XCB_KHR
vkCreateXcbSurfaceKHR = GET_PROCADDRESS(libvulkan, vkCreateXcbSurfaceKHR);
vkGetPhysicalDeviceXcbPresentationSupportKHR = GET_PROCADDRESS(libvulkan, vkGetPhysicalDeviceXcbPresentationSupportKHR);
#endif
#ifdef VK_USE_PLATFORM_WAYLAND_KHR
vkCreateWaylandSurfaceKHR = GET_PROCADDRESS(libvulkan, vkCreateWaylandSurfaceKHR);
vkGetPhysicalDeviceWaylandPresentationSupportKHR = GET_PROCADDRESS(libvulkan, vkGetPhysicalDeviceWaylandPresentationSupportKHR);
#endif
#ifdef VK_USE_PLATFORM_MIR_KHR
vkCreateMirSurfaceKHR = GET_PROCADDRESS(libvulkan, vkCreateMirSurfaceKHR);
vkGetPhysicalDeviceMirPresentationSupportKHR = GET_PROCADDRESS(libvulkan, vkGetPhysicalDeviceMirPresentationSupportKHR);
#endif
#ifdef VK_USE_PLATFORM_ANDROID_KHR
vkCreateAndroidSurfaceKHR = GET_PROCADDRESS(libvulkan, vkCreateAndroidSurfaceKHR);
#endif
#ifdef VK_USE_PLATFORM_WIN32_KHR
vkCreateWin32SurfaceKHR = GET_PROCADDRESS(libvulkan, vkCreateWin32SurfaceKHR);
vkGetPhysicalDeviceWin32PresentationSupportKHR = GET_PROCADDRESS(libvulkan, vkGetPhysicalDeviceWin32PresentationSupportKHR);
#endif
#ifdef USE_DEBUG_EXTENTIONS
vkCreateDebugReportCallbackEXT = GET_PROCADDRESS(libvulkan, vkCreateDebugReportCallbackEXT);
vkDestroyDebugReportCallbackEXT = GET_PROCADDRESS(libvulkan, vkDestroyDebugReportCallbackEXT);
vkDebugReportMessageEXT = GET_PROCADDRESS(libvulkan, vkDebugReportMessageEXT);
#endif
#endif
return true;
}
}
#if SF_VULKAN_DYNAMIC_LIBRARY
// No Vulkan support, do not set function addresses
PFN_vkCreateInstance vkCreateInstance = nullptr;
PFN_vkDestroyInstance vkDestroyInstance = nullptr;
PFN_vkEnumeratePhysicalDevices vkEnumeratePhysicalDevices = nullptr;
PFN_vkGetPhysicalDeviceFeatures vkGetPhysicalDeviceFeatures = nullptr;
PFN_vkGetPhysicalDeviceFormatProperties vkGetPhysicalDeviceFormatProperties = nullptr;
PFN_vkGetPhysicalDeviceImageFormatProperties vkGetPhysicalDeviceImageFormatProperties = nullptr;
PFN_vkGetPhysicalDeviceProperties vkGetPhysicalDeviceProperties = nullptr;
PFN_vkGetPhysicalDeviceQueueFamilyProperties vkGetPhysicalDeviceQueueFamilyProperties = nullptr;
PFN_vkGetPhysicalDeviceMemoryProperties vkGetPhysicalDeviceMemoryProperties = nullptr;
PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr = nullptr;
PFN_vkGetDeviceProcAddr vkGetDeviceProcAddr = nullptr;
PFN_vkCreateDevice vkCreateDevice = nullptr;
PFN_vkDestroyDevice vkDestroyDevice = nullptr;
PFN_vkEnumerateInstanceExtensionProperties vkEnumerateInstanceExtensionProperties = nullptr;
PFN_vkEnumerateDeviceExtensionProperties vkEnumerateDeviceExtensionProperties = nullptr;
PFN_vkEnumerateInstanceLayerProperties vkEnumerateInstanceLayerProperties = nullptr;
PFN_vkEnumerateDeviceLayerProperties vkEnumerateDeviceLayerProperties = nullptr;
PFN_vkGetDeviceQueue vkGetDeviceQueue = nullptr;
PFN_vkQueueSubmit vkQueueSubmit = nullptr;
PFN_vkQueueWaitIdle vkQueueWaitIdle = nullptr;
PFN_vkDeviceWaitIdle vkDeviceWaitIdle = nullptr;
PFN_vkAllocateMemory vkAllocateMemory = nullptr;
PFN_vkFreeMemory vkFreeMemory = nullptr;
PFN_vkMapMemory vkMapMemory = nullptr;
PFN_vkUnmapMemory vkUnmapMemory = nullptr;
PFN_vkFlushMappedMemoryRanges vkFlushMappedMemoryRanges = nullptr;
PFN_vkInvalidateMappedMemoryRanges vkInvalidateMappedMemoryRanges = nullptr;
PFN_vkGetDeviceMemoryCommitment vkGetDeviceMemoryCommitment = nullptr;
PFN_vkBindBufferMemory vkBindBufferMemory = nullptr;
PFN_vkBindImageMemory vkBindImageMemory = nullptr;
PFN_vkGetBufferMemoryRequirements vkGetBufferMemoryRequirements = nullptr;
PFN_vkGetImageMemoryRequirements vkGetImageMemoryRequirements = nullptr;
PFN_vkGetImageSparseMemoryRequirements vkGetImageSparseMemoryRequirements = nullptr;
PFN_vkGetPhysicalDeviceSparseImageFormatProperties vkGetPhysicalDeviceSparseImageFormatProperties = nullptr;
PFN_vkQueueBindSparse vkQueueBindSparse = nullptr;
PFN_vkCreateFence vkCreateFence = nullptr;
PFN_vkDestroyFence vkDestroyFence = nullptr;
PFN_vkResetFences vkResetFences = nullptr;
PFN_vkGetFenceStatus vkGetFenceStatus = nullptr;
PFN_vkWaitForFences vkWaitForFences = nullptr;
PFN_vkCreateSemaphore vkCreateSemaphore = nullptr;
PFN_vkDestroySemaphore vkDestroySemaphore = nullptr;
PFN_vkCreateEvent vkCreateEvent = nullptr;
PFN_vkDestroyEvent vkDestroyEvent = nullptr;
PFN_vkGetEventStatus vkGetEventStatus = nullptr;
PFN_vkSetEvent vkSetEvent = nullptr;
PFN_vkResetEvent vkResetEvent = nullptr;
PFN_vkCreateQueryPool vkCreateQueryPool = nullptr;
PFN_vkDestroyQueryPool vkDestroyQueryPool = nullptr;
PFN_vkGetQueryPoolResults vkGetQueryPoolResults = nullptr;
PFN_vkCreateBuffer vkCreateBuffer = nullptr;
PFN_vkDestroyBuffer vkDestroyBuffer = nullptr;
PFN_vkCreateBufferView vkCreateBufferView = nullptr;
PFN_vkDestroyBufferView vkDestroyBufferView = nullptr;
PFN_vkCreateImage vkCreateImage = nullptr;
PFN_vkDestroyImage vkDestroyImage = nullptr;
PFN_vkGetImageSubresourceLayout vkGetImageSubresourceLayout = nullptr;
PFN_vkCreateImageView vkCreateImageView = nullptr;
PFN_vkDestroyImageView vkDestroyImageView = nullptr;
PFN_vkCreateShaderModule vkCreateShaderModule = nullptr;
PFN_vkDestroyShaderModule vkDestroyShaderModule = nullptr;
PFN_vkCreatePipelineCache vkCreatePipelineCache = nullptr;
PFN_vkDestroyPipelineCache vkDestroyPipelineCache = nullptr;
PFN_vkGetPipelineCacheData vkGetPipelineCacheData = nullptr;
PFN_vkMergePipelineCaches vkMergePipelineCaches = nullptr;
PFN_vkCreateGraphicsPipelines vkCreateGraphicsPipelines = nullptr;
PFN_vkCreateComputePipelines vkCreateComputePipelines = nullptr;
PFN_vkDestroyPipeline vkDestroyPipeline = nullptr;
PFN_vkCreatePipelineLayout vkCreatePipelineLayout = nullptr;
PFN_vkDestroyPipelineLayout vkDestroyPipelineLayout = nullptr;
PFN_vkCreateSampler vkCreateSampler = nullptr;
PFN_vkDestroySampler vkDestroySampler = nullptr;
PFN_vkCreateDescriptorSetLayout vkCreateDescriptorSetLayout = nullptr;
PFN_vkDestroyDescriptorSetLayout vkDestroyDescriptorSetLayout = nullptr;
PFN_vkCreateDescriptorPool vkCreateDescriptorPool = nullptr;
PFN_vkDestroyDescriptorPool vkDestroyDescriptorPool = nullptr;
PFN_vkResetDescriptorPool vkResetDescriptorPool = nullptr;
PFN_vkAllocateDescriptorSets vkAllocateDescriptorSets = nullptr;
PFN_vkFreeDescriptorSets vkFreeDescriptorSets = nullptr;
PFN_vkUpdateDescriptorSets vkUpdateDescriptorSets = nullptr;
PFN_vkCreateFramebuffer vkCreateFramebuffer = nullptr;
PFN_vkDestroyFramebuffer vkDestroyFramebuffer = nullptr;
PFN_vkCreateRenderPass vkCreateRenderPass = nullptr;
PFN_vkDestroyRenderPass vkDestroyRenderPass = nullptr;
PFN_vkGetRenderAreaGranularity vkGetRenderAreaGranularity = nullptr;
PFN_vkCreateCommandPool vkCreateCommandPool = nullptr;
PFN_vkDestroyCommandPool vkDestroyCommandPool = nullptr;
PFN_vkResetCommandPool vkResetCommandPool = nullptr;
PFN_vkAllocateCommandBuffers vkAllocateCommandBuffers = nullptr;
PFN_vkFreeCommandBuffers vkFreeCommandBuffers = nullptr;
PFN_vkBeginCommandBuffer vkBeginCommandBuffer = nullptr;
PFN_vkEndCommandBuffer vkEndCommandBuffer = nullptr;
PFN_vkResetCommandBuffer vkResetCommandBuffer = nullptr;
PFN_vkCmdBindPipeline vkCmdBindPipeline = nullptr;
PFN_vkCmdSetViewport vkCmdSetViewport = nullptr;
PFN_vkCmdSetScissor vkCmdSetScissor = nullptr;
PFN_vkCmdSetLineWidth vkCmdSetLineWidth = nullptr;
PFN_vkCmdSetDepthBias vkCmdSetDepthBias = nullptr;
PFN_vkCmdSetBlendConstants vkCmdSetBlendConstants = nullptr;
PFN_vkCmdSetDepthBounds vkCmdSetDepthBounds = nullptr;
PFN_vkCmdSetStencilCompareMask vkCmdSetStencilCompareMask = nullptr;
PFN_vkCmdSetStencilWriteMask vkCmdSetStencilWriteMask = nullptr;
PFN_vkCmdSetStencilReference vkCmdSetStencilReference = nullptr;
PFN_vkCmdBindDescriptorSets vkCmdBindDescriptorSets = nullptr;
PFN_vkCmdBindIndexBuffer vkCmdBindIndexBuffer = nullptr;
PFN_vkCmdBindVertexBuffers vkCmdBindVertexBuffers = nullptr;
PFN_vkCmdDraw vkCmdDraw = nullptr;
PFN_vkCmdDrawIndexed vkCmdDrawIndexed = nullptr;
PFN_vkCmdDrawIndirect vkCmdDrawIndirect = nullptr;
PFN_vkCmdDrawIndexedIndirect vkCmdDrawIndexedIndirect = nullptr;
PFN_vkCmdDispatch vkCmdDispatch = nullptr;
PFN_vkCmdDispatchIndirect vkCmdDispatchIndirect = nullptr;
PFN_vkCmdCopyBuffer vkCmdCopyBuffer = nullptr;
PFN_vkCmdCopyImage vkCmdCopyImage = nullptr;
PFN_vkCmdBlitImage vkCmdBlitImage = nullptr;
PFN_vkCmdCopyBufferToImage vkCmdCopyBufferToImage = nullptr;
PFN_vkCmdCopyImageToBuffer vkCmdCopyImageToBuffer = nullptr;
PFN_vkCmdUpdateBuffer vkCmdUpdateBuffer = nullptr;
PFN_vkCmdFillBuffer vkCmdFillBuffer = nullptr;
PFN_vkCmdClearColorImage vkCmdClearColorImage = nullptr;
PFN_vkCmdClearDepthStencilImage vkCmdClearDepthStencilImage = nullptr;
PFN_vkCmdClearAttachments vkCmdClearAttachments = nullptr;
PFN_vkCmdResolveImage vkCmdResolveImage = nullptr;
PFN_vkCmdSetEvent vkCmdSetEvent = nullptr;
PFN_vkCmdResetEvent vkCmdResetEvent = nullptr;
PFN_vkCmdWaitEvents vkCmdWaitEvents = nullptr;
PFN_vkCmdPipelineBarrier vkCmdPipelineBarrier = nullptr;
PFN_vkCmdBeginQuery vkCmdBeginQuery = nullptr;
PFN_vkCmdEndQuery vkCmdEndQuery = nullptr;
PFN_vkCmdResetQueryPool vkCmdResetQueryPool = nullptr;
PFN_vkCmdWriteTimestamp vkCmdWriteTimestamp = nullptr;
PFN_vkCmdCopyQueryPoolResults vkCmdCopyQueryPoolResults = nullptr;
PFN_vkCmdPushConstants vkCmdPushConstants = nullptr;
PFN_vkCmdBeginRenderPass vkCmdBeginRenderPass = nullptr;
PFN_vkCmdNextSubpass vkCmdNextSubpass = nullptr;
PFN_vkCmdEndRenderPass vkCmdEndRenderPass = nullptr;
PFN_vkCmdExecuteCommands vkCmdExecuteCommands = nullptr;
PFN_vkDestroySurfaceKHR vkDestroySurfaceKHR = nullptr;
PFN_vkGetPhysicalDeviceSurfaceSupportKHR vkGetPhysicalDeviceSurfaceSupportKHR = nullptr;
PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR vkGetPhysicalDeviceSurfaceCapabilitiesKHR = nullptr;
PFN_vkGetPhysicalDeviceSurfaceFormatsKHR vkGetPhysicalDeviceSurfaceFormatsKHR = nullptr;
PFN_vkGetPhysicalDeviceSurfacePresentModesKHR vkGetPhysicalDeviceSurfacePresentModesKHR = nullptr;
PFN_vkCreateSwapchainKHR vkCreateSwapchainKHR = nullptr;
PFN_vkDestroySwapchainKHR vkDestroySwapchainKHR = nullptr;
PFN_vkGetSwapchainImagesKHR vkGetSwapchainImagesKHR = nullptr;
PFN_vkAcquireNextImageKHR vkAcquireNextImageKHR = nullptr;
PFN_vkQueuePresentKHR vkQueuePresentKHR = nullptr;
PFN_vkGetPhysicalDeviceDisplayPropertiesKHR vkGetPhysicalDeviceDisplayPropertiesKHR = nullptr;
PFN_vkGetPhysicalDeviceDisplayPlanePropertiesKHR vkGetPhysicalDeviceDisplayPlanePropertiesKHR = nullptr;
PFN_vkGetDisplayPlaneSupportedDisplaysKHR vkGetDisplayPlaneSupportedDisplaysKHR = nullptr;
PFN_vkGetDisplayModePropertiesKHR vkGetDisplayModePropertiesKHR = nullptr;
PFN_vkCreateDisplayModeKHR vkCreateDisplayModeKHR = nullptr;
PFN_vkGetDisplayPlaneCapabilitiesKHR vkGetDisplayPlaneCapabilitiesKHR = nullptr;
PFN_vkCreateDisplayPlaneSurfaceKHR vkCreateDisplayPlaneSurfaceKHR = nullptr;
PFN_vkCreateSharedSwapchainsKHR vkCreateSharedSwapchainsKHR = nullptr;
#ifdef VK_USE_PLATFORM_XLIB_KHR
PFN_vkCreateXlibSurfaceKHR vkCreateXlibSurfaceKHR = nullptr;
PFN_vkGetPhysicalDeviceXlibPresentationSupportKHR vkGetPhysicalDeviceXlibPresentationSupportKHR = nullptr;
#endif
#ifdef VK_USE_PLATFORM_XCB_KHR
PFN_vkCreateXcbSurfaceKHR vkCreateXcbSurfaceKHR = nullptr;
PFN_vkGetPhysicalDeviceXcbPresentationSupportKHR vkGetPhysicalDeviceXcbPresentationSupportKHR = nullptr;
#endif
#ifdef VK_USE_PLATFORM_WAYLAND_KHR
PFN_vkCreateWaylandSurfaceKHR vkCreateWaylandSurfaceKHR = nullptr;
PFN_vkGetPhysicalDeviceWaylandPresentationSupportKHR vkGetPhysicalDeviceWaylandPresentationSupportKHR = nullptr;
#endif
#ifdef VK_USE_PLATFORM_MIR_KHR
PFN_vkCreateMirSurfaceKHR vkCreateMirSurfaceKHR = nullptr;
PFN_vkGetPhysicalDeviceMirPresentationSupportKHR vkGetPhysicalDeviceMirPresentationSupportKHR = nullptr;
#endif
#ifdef VK_USE_PLATFORM_ANDROID_KHR
PFN_vkCreateAndroidSurfaceKHR vkCreateAndroidSurfaceKHR = nullptr;
#endif
#ifdef VK_USE_PLATFORM_WIN32_KHR
PFN_vkCreateWin32SurfaceKHR vkCreateWin32SurfaceKHR = nullptr;
PFN_vkGetPhysicalDeviceWin32PresentationSupportKHR vkGetPhysicalDeviceWin32PresentationSupportKHR = nullptr;
#endif
PFN_vkCreateDebugReportCallbackEXT vkCreateDebugReportCallbackEXT = nullptr;
PFN_vkDestroyDebugReportCallbackEXT vkDestroyDebugReportCallbackEXT = nullptr;
PFN_vkDebugReportMessageEXT vkDebugReportMessageEXT = nullptr;
#endif
#endif // #if HAVE_VULKAN
| 57.881319 | 131 | 0.851306 | blue3k |
0dd1418522f97a08080e378c45d316b27f9933c8 | 2,610 | cpp | C++ | src/qt/orphandownloader.cpp | Mart1250/biblepay | d53d04f74242596b104d360187268a50b845b82e | [
"MIT"
] | null | null | null | src/qt/orphandownloader.cpp | Mart1250/biblepay | d53d04f74242596b104d360187268a50b845b82e | [
"MIT"
] | null | null | null | src/qt/orphandownloader.cpp | Mart1250/biblepay | d53d04f74242596b104d360187268a50b845b82e | [
"MIT"
] | null | null | null | #include "orphandownloader.h"
#include <univalue.h>
#include "rpcipfs.h"
#include "guiutil.h"
#include "rpcpog.h"
#include "timedata.h"
#include <QUrl>
#include <boost/algorithm/string/case_conv.hpp>
#include <QDir>
#include <QTimer>
#include <QString>
OrphanDownloader::OrphanDownloader(QString xURL, QString xDestName, int xTimeout) : sURL(xURL), sDestName(xDestName), iTimeout(xTimeout)
{
}
void OrphanDownloader::Get()
{
if (sURL == "" || sDestName == "") return;
int64_t nFileSize = GetFileSize(GUIUtil::FROMQS(sDestName));
bDownloadFinished = false;
if (nFileSize > 0)
{
return;
}
// We must call out using an HTTPS request here - to pull down the Orphan's picture locally (otherwise QT won't display the image)
manager = new QNetworkAccessManager;
QNetworkRequest request;
request.setUrl(QUrl(sURL));
reply = manager->get(request);
file = new QFile;
file->setFileName(sDestName);
file->open(QIODevice::WriteOnly);
connect(reply,SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(onDownloadProgress(qint64,qint64)));
connect(reply,SIGNAL(readyRead()), this, SLOT(onReadyRead()));
connect(reply,SIGNAL(finished()), this, SLOT(onReplyFinished()));
connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(onFinished(QNetworkReply*)));
QTimer::singleShot(iTimeout, this, SLOT(DownloadFailure()));
}
void OrphanDownloader::BusyWait()
{
int iBroken = 0;
while (1==1)
{
int64_t nFileSize = GetFileSize(GUIUtil::FROMQS(sDestName));
if (nFileSize > 0 || bDownloadFinished) break;
MilliSleep(250);
iBroken++;
if (iBroken > (iTimeout/500)) break;
}
}
void OrphanDownloader::DownloadFailure()
{
LogPrintf("Download failed\n");
bDownloadFinished = true;
}
void OrphanDownloader::onDownloadProgress(qint64 bytesRead,qint64 bytesTotal)
{
printf("OnDownloadProgress %f ", (double)bytesRead);
}
void OrphanDownloader::onFinished(QNetworkReply * reply)
{
switch(reply->error())
{
case QNetworkReply::NoError:
{
printf(" \n Downloaded successfully. ");
}
break;
default:
{
printf(" BioDownloadError %s ", GUIUtil::FROMQS(reply->errorString()).c_str());
};
}
if(file->isOpen())
{
file->close();
file->deleteLater();
}
bDownloadFinished = true;
}
void OrphanDownloader::onReadyRead()
{
file->write(reply->readAll());
}
void OrphanDownloader::onReplyFinished()
{
if(file->isOpen())
{
file->close();
file->deleteLater();
}
}
OrphanDownloader::~OrphanDownloader()
{
// Note - there is no UI to delete
}
| 23.097345 | 136 | 0.67931 | Mart1250 |
0dd1f5ec98aef716956bd127f9d70e50b8adfc43 | 1,254 | hpp | C++ | ufora/core/UnitTest.hpp | ufora/ufora | 04db96ab049b8499d6d6526445f4f9857f1b6c7e | [
"Apache-2.0",
"CC0-1.0",
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 571 | 2015-11-05T20:07:07.000Z | 2022-01-24T22:31:09.000Z | ufora/core/UnitTest.hpp | timgates42/ufora | 04db96ab049b8499d6d6526445f4f9857f1b6c7e | [
"Apache-2.0",
"CC0-1.0",
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 218 | 2015-11-05T20:37:55.000Z | 2021-05-30T03:53:50.000Z | ufora/core/UnitTest.hpp | timgates42/ufora | 04db96ab049b8499d6d6526445f4f9857f1b6c7e | [
"Apache-2.0",
"CC0-1.0",
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 40 | 2015-11-07T21:42:19.000Z | 2021-05-23T03:48:19.000Z | /***************************************************************************
Copyright 2015 Ufora Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
****************************************************************************/
#include "Platform.hpp"
#ifdef BSA_PLATFORM_WINDOWS
#define BOOST_TEST_DYN_LINK
#endif
#include <boost/test/unit_test.hpp>
#define BOOST_TEST_USE_CPPML_PRINTER( T ) \
namespace boost { namespace test_tools { \
template<> \
struct print_log_value<T> { \
void operator()( std::ostream& os, T const& t ) \
{ \
os << prettyPrintString(t); \
} \
}; \
}} // End of macro.
| 35.828571 | 77 | 0.555821 | ufora |
0dd7bc5f047c985bf90a901d7f732c8482e23cff | 1,204 | cpp | C++ | pc_code/Serial/SerialTestMFC/AboutDlg.cpp | johnenrickplenos/water_level_monitoring | 3e0628daea5eb1caba1fb69efdd2691590ce6c32 | [
"MIT"
] | null | null | null | pc_code/Serial/SerialTestMFC/AboutDlg.cpp | johnenrickplenos/water_level_monitoring | 3e0628daea5eb1caba1fb69efdd2691590ce6c32 | [
"MIT"
] | null | null | null | pc_code/Serial/SerialTestMFC/AboutDlg.cpp | johnenrickplenos/water_level_monitoring | 3e0628daea5eb1caba1fb69efdd2691590ce6c32 | [
"MIT"
] | null | null | null | #include "StdAfx.h"
#include "SerialTestMFC.h"
#include "AboutDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg methods
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
//{{AFX_DATA_INIT(CAboutDlg)
//}}AFX_DATA_INIT
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAboutDlg)
//}}AFX_DATA_MAP
}
BOOL CAboutDlg::OnInitDialog()
{
// Call base class
CDialog::OnInitDialog();
LOGFONT logFont = {0};
logFont.lfCharSet = DEFAULT_CHARSET;
logFont.lfHeight = 24;
logFont.lfWeight = FW_BOLD;
lstrcpy(logFont.lfFaceName, _T("Arial"));
HFONT hFont = ::CreateFontIndirect(&logFont);
SendDlgItemMessage(IDC_ABOUT_TITLE, WM_SETFONT, LPARAM(hFont), FALSE);
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
| 21.122807 | 77 | 0.63206 | johnenrickplenos |
0dd8861e56ff759a80a345bc27736ff4ef253114 | 2,796 | hpp | C++ | include/musycl/midi/midi_out.hpp | keryell/muSYCL | 130e4b29c3a4daf4c908b08263b53910acb13787 | [
"Apache-2.0"
] | 16 | 2021-05-07T11:33:59.000Z | 2022-03-05T02:36:06.000Z | include/musycl/midi/midi_out.hpp | keryell/muSYCL | 130e4b29c3a4daf4c908b08263b53910acb13787 | [
"Apache-2.0"
] | null | null | null | include/musycl/midi/midi_out.hpp | keryell/muSYCL | 130e4b29c3a4daf4c908b08263b53910acb13787 | [
"Apache-2.0"
] | null | null | null | #ifndef MUSYCL_MIDI_MIDI_OUT_HPP
#define MUSYCL_MIDI_MIDI_OUT_HPP
/** \file SYCL abstraction for a MIDI output pipe
Based on RtMidi library.
*/
#include <cstdlib>
#include <functional>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include "rtmidi/RtMidi.h"
#include "musycl/midi.hpp"
namespace musycl {
// To use time unit literals directly
using namespace std::chrono_literals;
/** A MIDI output interface exposed as a SYCL pipe.
In SYCL the type is used to synthesize the connection between
kernels, so there can be only 1 instance of a MIDI input
interface. */
class midi_out {
/** The handlers to control the MIDI output interfaces
Use a pointer because RtMidiOut is a broken type and is neither
copyable nor movable */
static inline std::vector<std::unique_ptr<RtMidiOut>> interfaces;
/// Check for RtMidi errors
static auto constexpr check_error = [] (auto&& function) {
try {
return function();
}
catch (const RtMidiError &error) {
error.printMessage();
std::exit(EXIT_FAILURE);
}
};
public:
/// Open all the IMID input ports available
void open(const std::string& application_name,
const std::string& port_name,
RtMidi::Api backend) {
std::cout << "RtMidi version " << RtMidi::getVersion() << std::endl;
// Create a throwable MIDI output just to get later the number of port
auto midi_out = check_error([&] { return RtMidiOut { backend,
"muSYCLtest" }; });
auto n_out_ports = midi_out.getPortCount();
std::cout << "\nThere are " << n_out_ports
<< " MIDI output ports available." << std::endl;;
for (auto i = 0; i < n_out_ports; ++i) {
interfaces.push_back(check_error([&] {
return std::make_unique<RtMidiOut>(backend, application_name);
}));
auto port_name = check_error([&] { return midi_out.getPortName(i); });
std::cout << " Output Port #" << i << ": " << port_name << std::endl;
// Open the port and give it a fancy name
check_error([&] { interfaces[i]->openPort(i, port_name); });
}
}
/// The sycl::pipe::write-like interface to write a MIDI message
static void write(const std::vector<std::uint8_t>& v) {
#if 0
for (int e : v)
std::cout << std::hex << e << ' ';
std::cout << std::endl;
for (int e : v)
std::cout << std::dec << e << ' ';
std::cout << std::endl;
#endif
// Hard-code now for KeyLab Essential
interfaces[1]->sendMessage(&v);
}
/// The non-blocking sycl::pipe::write-like interface to write a MIDI message
static void try_write(const std::vector<std::uint8_t>& v) {
write(v);
}
};
}
#endif // MUSYCL_MIDI_MIDI_OUT_HPP
| 27.145631 | 79 | 0.628755 | keryell |
0ddb16c6f91457457938bd229b881a1937481b02 | 4,044 | cc | C++ | src/Test/mutant_test_2.cc | hgl71964/PET | 4cedb25c5dce0c49eebb693125235fc4ad1e26f8 | [
"Apache-2.0"
] | 69 | 2021-06-01T03:19:12.000Z | 2022-03-26T00:14:20.000Z | src/Test/mutant_test_2.cc | hgl71964/PET | 4cedb25c5dce0c49eebb693125235fc4ad1e26f8 | [
"Apache-2.0"
] | null | null | null | src/Test/mutant_test_2.cc | hgl71964/PET | 4cedb25c5dce0c49eebb693125235fc4ad1e26f8 | [
"Apache-2.0"
] | 4 | 2021-07-10T07:21:11.000Z | 2022-02-06T18:56:56.000Z | #include "generator.h"
#include "graph.h"
#include "operator.h"
#include "search_engine.h"
#include "tensor.h"
#include <cstdlib>
#include <iostream>
const int n = 16, c = 16, h = 14, w = 14;
const int f = 32, r = 3, s = 3;
int main() {
auto i0 = new tpm::Tensor({n, c, h, w});
auto i1 = new tpm::Tensor({n, c, h, w});
auto i2 = new tpm::Tensor({n, c, h, w});
// auto i0 = new tpm::Tensor({1, 1, n, n});
// auto i1 = new tpm::Tensor({1, 1, n, n});
// auto i2 = new tpm::Tensor({1, 1, n, n});
auto trans0 = new tpm::TransposeOp(i0, i1, 2, {0, 1, {-1, 2}, 3}, 2);
auto trans1 = new tpm::TransposeOp(i1, i2, 3, {0, 1, 2, {-1, 3}}, 2);
i0->dataRand();
i1->dataMalloc();
i2->dataMalloc();
auto i0d = i0->getDataPtr();
i1->getDataPtr();
i2->getDataPtr();
for (size_t i = 0; i < i0->size(); ++i)
i0d[i] = i;
// std::cout << "input: " << std::endl;
// for (int i = 0; i < i0->size(); ++i) {
// std::cout << i0d[i] << ", ";
// if (i % n == n - 1)
// std::cout << std::endl;
// }
trans0->compute();
// std::cout << "output: " << std::endl;
// for (int i = 0; i < i1->size(); ++i) {
// std::cout << i1d[i] << ", ";
// if (i % n == n - 1)
// std::cout << std::endl;
// }
trans1->compute();
// std::cout << "output: " << std::endl;
// for (int i = 0; i < i2->size(); ++i) {
// std::cout << i2d[i] << ", ";
// if (i % n == n - 1)
// std::cout << std::endl;
// }
auto w0 = new tpm::Tensor({f, c, r, s});
w0->dataRand();
auto w0d = w0->getDataPtr();
for (size_t i = 0; i < w0->size(); ++i)
w0d[i] = i;
auto o1 = new tpm::Tensor({n, f, h, w});
auto o2 = new tpm::Tensor({n, f, h, w});
o1->dataMalloc();
o2->dataMalloc();
auto o1d = o1->getDataPtr();
o2->getDataPtr();
auto convd2 = new tpm::ConvOp(i0, w0, o1, 2, 2, 1, 1, 2, 2);
auto convd1 = new tpm::ConvOp(i2, w0, o2, 1, 1, 1, 1, 1, 1);
convd2->compute();
convd1->compute();
// std::cout << "o1: " << std::endl;
// for (int i = 0; i < o1->size(); ++i) {
// std::cout << o1d[i] << ", ";
// if (i % n == n - 1)
// std::cout << std::endl;
// }
// std::cout << "o2: " << std::endl;
// for (int i = 0; i < o2->size(); ++i) {
// std::cout << o2d[i] << ", ";
// if (i % n == n - 1)
// std::cout << std::endl;
// }
auto o3 = new tpm::Tensor({n, f, h, w});
auto o4 = new tpm::Tensor({n, f, h, w});
o3->dataMalloc();
o4->dataMalloc();
o3->getDataPtr();
auto o4d = o4->getDataPtr();
auto trans2 = new tpm::TransposeOp(o2, o3, 2, {0, 1, {-1, 2}, 3}, -2);
auto trans3 = new tpm::TransposeOp(o3, o4, 3, {0, 1, 2, {-1, 3}}, -2);
trans2->compute();
trans3->compute();
// std::cout << "o3: " << std::endl;
// for (int i = 0; i < o3->size(); ++i) {
// std::cout << o3d[i] << ", ";
// if (i % n == n - 1)
// std::cout << std::endl;
// }
// std::cout << "o4: " << std::endl;
// for (int i = 0; i < o4->size(); ++i) {
// std::cout << o4d[i] << ", ";
// if (i % n == n - 1)
// std::cout << std::endl;
// }
// std::cout << "o1: " << std::endl;
// for (int i = 0; i < o1->size(); ++i) {
// std::cout << o1d[i] << ", ";
// if (i % n == n - 1)
// std::cout << std::endl;
// }
int total = 0, equal = 0;
for (size_t i = 0; i < o1->size() && i < o4->size(); ++i) {
total++;
if (o1d[i] == o4d[i])
equal++;
}
std::cout << "equal/total = " << equal << "/" << total << " = "
<< (double)equal / total << std::endl;
delete trans0;
delete trans1;
delete trans2;
delete trans3;
delete convd1;
delete convd2;
delete i0;
delete i1;
delete i2;
delete w0;
delete o1;
delete o2;
delete o3;
delete o4;
return 0;
}
| 27.889655 | 74 | 0.426558 | hgl71964 |
0ddfb804bf0e44a86e59569681b9e4f64d988f9e | 13,615 | cpp | C++ | ObjGroupTree.cpp | joeriedel/Tread3.0A2 | 337c4aa74d554e21b50d6bd4406ce0f67aa39144 | [
"MIT"
] | 1 | 2020-07-19T10:19:18.000Z | 2020-07-19T10:19:18.000Z | ObjGroupTree.cpp | joeriedel/Tread3.0A2 | 337c4aa74d554e21b50d6bd4406ce0f67aa39144 | [
"MIT"
] | null | null | null | ObjGroupTree.cpp | joeriedel/Tread3.0A2 | 337c4aa74d554e21b50d6bd4406ce0f67aa39144 | [
"MIT"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////
// ObjGroupTree.cpp
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008, Joe Riedel
// All rights reserved.
//
// Redistribution and use in source and binary forms,
// with or without modification, are permitted provided
// that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// Neither the name of the <ORGANIZATION> 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 "stdafx.h"
#include "Tread.h"
#include "ObjGroupTree.h"
#include "System.h"
#include "TreadDoc.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#define EYE_ICON 3
#define BLANK_ICON 2
/////////////////////////////////////////////////////////////////////////////
// CObjGroupTree
CObjGroupTree::CObjGroupTree()
{
m_pDoc = 0;
}
CObjGroupTree::~CObjGroupTree()
{
}
void CObjGroupTree::ShowGroup( CObjectGroup* obj )
{
if( obj->GetTreeItem() )
{
EnsureVisible( obj->GetTreeItem() );
Expand( obj->GetTreeItem(), TVE_COLLAPSE );
}
}
void CObjGroupTree::SetDoc( CTreadDoc* pDoc )
{
m_pDoc = pDoc;
}
void CObjGroupTree::SelectItemUID( int uid )
{
HTREEITEM item = FindItemByUID( uid, TVI_ROOT );
if( item )
{
//Select( item, TVGN_CARET|TVGN_FIRSTVISIBLE );
SelectItem( item );
//if( GetChildItem( item ) != 0 )
// Expand( item, TVE_EXPAND );
}
}
int CObjGroupTree::AddObjectProc( CMapObject* obj, void* p, void* p2 )
{
if( !obj->CanAddToTree() )
return 0;
CObjGroupTree* tree = (CObjGroupTree*)p;
HTREEITEM item;
int icon;
item = 0;
//
// find the parent?
//
if( obj->GetGroupUID() != -1 )
{
CObjectGroup* gr = tree->m_pDoc->GroupForUID( obj->GetGroupUID() );
if( gr )
item = gr->GetTreeItem();
}
if( !item ) item = tree->m_pRoot;
icon = (obj->IsVisible())?EYE_ICON:BLANK_ICON;
item = tree->InsertItem( obj->GetName(), icon, icon, item );
tree->SetItemData( item, obj->GetUID() );
obj->SetTreeItem( item );
return 0;
}
int CObjGroupTree::ClearObjectTreeItemProc( CMapObject* obj, void* p, void* p2 )
{
obj->SetTreeItem( 0 );
return 0;
}
int CObjGroupTree::ClearGroupTreeItemProc( CObjectGroup* gr, void* p, void* p2 )
{
gr->SetTreeItem( 0 );
return 0;
}
void CObjGroupTree::AddObject( CMapObject* obj )
{
HTREEITEM item;
int icon;
item = 0;
//
// find the parent?
//
if( obj->GetGroupUID() != -1 )
{
CObjectGroup* gr = m_pDoc->GroupForUID( obj->GetGroupUID() );
if( gr )
item = gr->GetTreeItem();
}
if( !item ) item = m_pRoot;
icon = (obj->IsVisible())?EYE_ICON:BLANK_ICON;
item = InsertItem( obj->GetName(), icon, icon, item );
SetItemData( item, obj->GetUID() );
obj->SetTreeItem( item );
//Expand( m_pRoot, TVE_EXPAND );
SelectSetFirstVisible( item );
}
void CObjGroupTree::RemoveObject( CMapObject* obj )
{
if( obj->GetTreeItem() )
{
DeleteItem( obj->GetTreeItem() );
obj->SetTreeItem( 0 );
}
}
void CObjGroupTree::AddGroup( CObjectGroup* gr )
{
HTREEITEM item;
int icon;
icon = (gr->IsVisible())?EYE_ICON:BLANK_ICON;
item = InsertItem( gr->GetName(), icon, icon, m_pRoot );
SetItemData( item, gr->GetUID() );
gr->SetTreeItem( item );
Expand( item, TVE_COLLAPSE );
}
void CObjGroupTree::RemoveGroup( CObjectGroup* gr )
{
if( gr->GetTreeItem() )
{
DeleteItem( gr->GetTreeItem() );
gr->SetTreeItem( 0 );
}
}
void CObjGroupTree::ObjectStateChange( CMapObject* obj )
{
if( !obj->GetTreeItem() )
return;
int icon;
icon = (obj->IsVisible())?EYE_ICON:BLANK_ICON;
SetItemImage( obj->GetTreeItem(), icon, icon );
SetItemText( obj->GetTreeItem(), obj->GetName() );
}
void CObjGroupTree::GroupStateChange( CObjectGroup* obj )
{
if( !obj->GetTreeItem() )
return;
int icon;
icon = (obj->IsVisible())?EYE_ICON:BLANK_ICON;
SetItemImage( obj->GetTreeItem(), icon, icon );
SetItemText( obj->GetTreeItem(), obj->GetName() );
}
void CObjGroupTree::BuildTree()
{
DeleteItem( TVI_ROOT );
//
// create the root.
//
m_pRoot = InsertItem( "Objects/Groups", 4, 4 );
//
// clear all objects.
//
m_pDoc->GetObjectGroupList()->WalkList( ClearGroupTreeItemProc );
m_pDoc->GetObjectList()->WalkList( ClearObjectTreeItemProc );
m_pDoc->GetSelectedObjectList()->WalkList( ClearObjectTreeItemProc );
//
// add all groups.
//
int icon;
HTREEITEM item;
CObjectGroup* gr;
for( gr = m_pDoc->GetObjectGroupList()->ResetPos(); gr; gr = m_pDoc->GetObjectGroupList()->GetNextItem() )
{
icon = (gr->IsVisible())?EYE_ICON:BLANK_ICON;
item = InsertItem( gr->GetName(), icon, icon, m_pRoot );
SetItemData( item, gr->GetUID() );
gr->SetTreeItem( item );
}
m_pDoc->GetObjectList()->WalkList( AddObjectProc, this );
m_pDoc->GetSelectedObjectList()->WalkList( AddObjectProc, this );
Expand( m_pRoot, TVE_EXPAND );
//SortList( TVI_ROOT );
}
HTREEITEM CObjGroupTree::FindItemByUID( int uid, HTREEITEM pRoot )
{
HTREEITEM item = GetChildItem( pRoot );
HTREEITEM child;
while( item != 0 )
{
if( item != m_pRoot && GetItemData( item ) == (DWORD)uid )
return item;
child = FindItemByUID( uid, item ); // search children.
if( child )
return child;
item = GetNextSiblingItem( item );
}
return 0;
}
BEGIN_MESSAGE_MAP(CObjGroupTree, CTreeCtrl)
//{{AFX_MSG_MAP(CObjGroupTree)
ON_WM_LBUTTONDOWN()
ON_NOTIFY_REFLECT(TVN_BEGINLABELEDIT, OnBeginlabeledit)
ON_NOTIFY_REFLECT(TVN_ENDLABELEDIT, OnEndlabeledit)
ON_WM_LBUTTONDBLCLK()
ON_WM_MOUSEMOVE()
ON_WM_RBUTTONDOWN()
ON_WM_RBUTTONDBLCLK()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CObjGroupTree message handlers
void CObjGroupTree::OnBeginlabeledit(NMHDR* pNMHDR, LRESULT* pResult)
{
TV_DISPINFO* pTVDispInfo = (TV_DISPINFO*)pNMHDR;
// TODO: Add your control notification handler code here
if( pTVDispInfo->item.hItem == TVI_ROOT ||
pTVDispInfo->item.hItem == m_pRoot )
{
*pResult = 1;
return;
}
*pResult = 0;
}
void CObjGroupTree::OnEndlabeledit(NMHDR* pNMHDR, LRESULT* pResult)
{
TV_DISPINFO* pTVDispInfo = (TV_DISPINFO*)pNMHDR;
// TODO: Add your control notification handler code here
if( pTVDispInfo->item.pszText == 0 ||
pTVDispInfo->item.pszText[0] == 0 )
return;
CString s = pTVDispInfo->item.pszText;
HTREEITEM item = pTVDispInfo->item.hItem;
int uid = (int)GetItemData( item );
CMapObject* obj = m_pDoc->ObjectForUID( uid );
if( obj )
{
obj->SetName( s );
m_pDoc->Prop_UpdateObjectState( obj );
m_pDoc->Prop_UpdateSelection();
}
else
{
CObjectGroup* gr = m_pDoc->GroupForUID( uid );
if( gr )
{
gr->SetName( s );
m_pDoc->Prop_UpdateGroupState( gr );
}
}
*pResult = 0;
}
void CObjGroupTree::OnLButtonDown(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
//
// modify visibility.
//
TVHITTESTINFO hitTest;
hitTest.pt = point;
HitTest( &hitTest );
if( hitTest.hItem == TVI_ROOT || hitTest.hItem == m_pRoot || hitTest.hItem == 0 )
return;
if( (hitTest.flags&TVHT_ONITEMICON) )
{
//
// toggle the object.
//
CMapObject* obj;
CObjectGroup* gr;
int uid, icon;
uid = GetItemData( hitTest.hItem );
obj = m_pDoc->ObjectForUID( uid );
if( obj )
{
bool deselect = obj->IsSelected();
if( deselect )
m_pDoc->MakeUndoDeselectAction();
obj->SetVisible( m_pDoc, !obj->IsVisible() );
if( deselect )
obj->Deselect( m_pDoc );
icon = (obj->IsVisible())?EYE_ICON:BLANK_ICON;
}
else
{
gr = m_pDoc->GroupForUID( uid );
if( gr )
{
gr->SetVisible( m_pDoc, !gr->IsVisible() );
icon = (gr->IsVisible())?EYE_ICON:BLANK_ICON;
}
}
SetItemImage( hitTest.hItem, icon, icon );
m_pDoc->UpdateSelectionInterface();
m_pDoc->Prop_UpdateSelection();
Sys_RedrawWindows();
return;
}
CTreeCtrl::OnLButtonDown(nFlags, point);
}
void CObjGroupTree::OnLButtonDblClk(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
//
// modify visibility.
//
TVHITTESTINFO hitTest;
hitTest.pt = point;
HitTest( &hitTest );
if( hitTest.hItem == TVI_ROOT || hitTest.hItem == m_pRoot || hitTest.hItem == 0 )
return;
if( (hitTest.flags&TVHT_ONITEMICON) )
{
//
// toggle the object.
//
CMapObject* obj;
CObjectGroup* gr;
int uid, icon;
uid = GetItemData( hitTest.hItem );
obj = m_pDoc->ObjectForUID( uid );
if( obj )
{
bool deselect = obj->IsSelected();
if( deselect )
m_pDoc->MakeUndoDeselectAction();
obj->SetVisible( m_pDoc, !obj->IsVisible() );
if( deselect )
obj->Deselect( m_pDoc );
icon = (obj->IsVisible())?EYE_ICON:BLANK_ICON;
}
else
{
gr = m_pDoc->GroupForUID( uid );
if( gr )
{
gr->SetVisible( m_pDoc, !gr->IsVisible() );
icon = (gr->IsVisible())?EYE_ICON:BLANK_ICON;
}
}
SetItemImage( hitTest.hItem, icon, icon );
m_pDoc->UpdateSelectionInterface();
m_pDoc->Prop_UpdateSelection();
Sys_RedrawWindows();
return;
}
CTreeCtrl::OnLButtonDblClk(nFlags, point);
}
void CObjGroupTree::OnMouseMove(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
CTreeCtrl::OnMouseMove(nFlags, point);
}
void CObjGroupTree::DeleteGroup()
{
HTREEITEM item = GetSelectedItem();
if( !item )
return;
int uid = (int)GetItemData( item );
CObjectGroup* gr;
gr = m_pDoc->GroupForUID( uid );
if( gr )
{
//
// orhpan all the objects.
//
gr->OrphanObjects( m_pDoc );
RemoveGroup( gr );
m_pDoc->GetObjectGroupList()->RemoveItem( gr );
delete gr;
}
}
BOOL CObjGroupTree::PreTranslateMessage(MSG* pMsg)
{
// TODO: Add your specialized code here and/or call the base class
if( pMsg->message == WM_KEYDOWN )
{
// When an item is being edited make sure the edit control
// receives certain important key strokes
if( GetEditControl()
&& (pMsg->wParam == VK_RETURN
|| pMsg->wParam == VK_DELETE
|| pMsg->wParam == VK_ESCAPE
|| GetKeyState( VK_CONTROL)
)
)
{
::TranslateMessage(pMsg);
::DispatchMessage(pMsg);
return TRUE; // DO NOT process further
}
else
if( pMsg->wParam == VK_DELETE )
{
DeleteGroup();
return TRUE;
}
}
return CTreeCtrl::PreTranslateMessage(pMsg);
}
void CObjGroupTree::OnRButtonDown(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
TVHITTESTINFO hitTest;
hitTest.pt = point;
HitTest( &hitTest );
if( hitTest.hItem == TVI_ROOT || hitTest.hItem == m_pRoot || hitTest.hItem == 0 )
return;
//
// select the object/group.
//
CMapObject* obj;
int uid;
bool deselect = (nFlags&MS_CONTROL)?false:true;
bool jump = (nFlags&MS_SHIFT)?true:false;
uid = GetItemData( hitTest.hItem );
obj = m_pDoc->ObjectForUID( uid );
if( obj )
{
obj->SetVisible( m_pDoc, true );
m_pDoc->Prop_UpdateObjectState( obj );
bool wassel = obj->IsSelected();
if( deselect )
{
m_pDoc->MakeUndoDeselectAction();
m_pDoc->ClearSelection();
}
if( wassel && !deselect )
{
obj->Deselect( m_pDoc );
}
else if( !wassel )
{
obj->Select( m_pDoc );
}
}
else
{
CObjectGroup* gr = m_pDoc->GroupForUID( uid );
if( gr )
{
bool wassel = gr->IsSelected( m_pDoc );
if( deselect )
{
m_pDoc->MakeUndoDeselectAction();
m_pDoc->ClearSelection();
}
gr->SetVisible( m_pDoc, true );
m_pDoc->Prop_UpdateGroupState( gr );
if( wassel && !deselect )
{
gr->DeselectObjects( m_pDoc );
}
else if( !wassel )
{
gr->SelectObjects( m_pDoc );
}
}
}
m_pDoc->UpdateSelectionInterface();
m_pDoc->Prop_UpdateSelection();
Sys_RedrawWindows();
//Select( hitTest.hItem, TVGN_CARET|TVGN_FIRSTVISIBLE );
SelectItem( hitTest.hItem );
//CTreeCtrl::OnRButtonDown(nFlags, point);
}
void CObjGroupTree::OnRButtonDblClk(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
OnRButtonDown(nFlags, point);
//CTreeCtrl::OnRButtonDblClk(nFlags, point);
}
| 22.541391 | 107 | 0.644142 | joeriedel |
0ddff55376d488420ae6b66a411a78d0e238d768 | 3,969 | cxx | C++ | private/inet/mshtml/src/site/base/wfromd.cxx | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | 11 | 2017-09-02T11:27:08.000Z | 2022-01-02T15:25:24.000Z | private/inet/mshtml/src/site/base/wfromd.cxx | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | null | null | null | private/inet/mshtml/src/site/base/wfromd.cxx | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | 14 | 2019-01-16T01:01:23.000Z | 2022-02-20T15:54:27.000Z | //+---------------------------------------------------------------------------
//
// Microsoft Forms
// Copyright (C) Microsoft Corporation, 1992 - 1996.
//
// File: wfromd.cxx
//
// Contents: Contains coordinate conversion functions.
//
// Classes: CDoc (partial)
//
//----------------------------------------------------------------------------
#include "headers.hxx"
#ifndef X_FORMKRNL_HXX_
#define X_FORMKRNL_HXX_
#include "formkrnl.hxx"
#endif
//+------------------------------------------------------------------------
//
// Member: CDoc::DocumentFromWindow
// CDoc::DocumentFromScreen
// CDoc::ScreenFromDocument
// CDoc::ScreenFromWindow
// CDoc::HimetricFromDevice
// CDoc::DeviceFromHimetric
//
// Synopsis: Coordinate conversion using the document transform
//
//-------------------------------------------------------------------------
void
CDoc::DocumentFromWindow(RECTL *prcl, const RECT *prc)
{
DocumentFromWindow((POINTL *)&prcl->left, *(POINT *)&prc->left);
DocumentFromWindow((POINTL *)&prcl->right, *(POINT *)&prc->right);
}
void
CDoc::DocumentFromScreen(POINTL *pptl, POINT pt)
{
*(POINT *)pptl = pt;
ScreenToClient(GetHWND(), (POINT *)pptl);
DocumentFromWindow(pptl, pptl->x, pptl->y);
}
void
CDoc::ScreenFromWindow (POINT *ppt, POINT pt)
{
*ppt = pt;
ClientToScreen(GetHWND(), ppt);
}
void
CDoc::HimetricFromDevice(RECTL *prcl, const RECT *prc)
{
HimetricFromDevice((POINTL *)&prcl->left, *(POINT *)&prc->left);
HimetricFromDevice((POINTL *)&prcl->right, *(POINT *)&prc->right);
}
void
CDoc::DeviceFromHimetric(RECT *prc, const RECTL *prcl)
{
DeviceFromHimetric((POINT *)&prc->left, *(POINTL *)&prcl->left);
DeviceFromHimetric((POINT *)&prc->right, *(POINTL *)&prcl->right);
}
//+------------------------------------------------------------------------
//
// Member: CDoc::DeviceFromHimetric
// CDoc::HimetricFromDevice
// CDoc::DocumentFromScreen
//
// Synopsis: Convert between himetric CDoc coordinates and
// window coordinates, accounting for scaling.
//
//-------------------------------------------------------------------------
/*
void
CDoc::DeviceFromHimetric(SIZE *psize, int cxl, int cyl)
{
psize->cx = MulDivQuick(cxl,
100 * _pSiteRoot->_rc.right,
100 * _sizel.cx);
psize->cy = MulDivQuick(cyl,
100 * _pSiteRoot->_rc.bottom,
100 * _sizel.cy);
}
void
CDoc::DeviceFromHimetric(POINT *ppt, int xl, int yl)
{
ppt->x = _pSiteRoot->_rc.left + MulDivQuick(xl,
100 * _pSiteRoot->_rc.right,
100 *_sizel.cx);
ppt->y = _pSiteRoot->_rc.top + MulDivQuick(yl,
100 * _pSiteRoot->_rc.bottom,
100 * _sizel.cy);
}
void
CDoc::DeviceFromHimetric(RECT *prc, const RECTL *prcl)
{
DeviceFromHimetric((POINT *)&prc->left, *(POINTL *)&prcl->left);
DeviceFromHimetric((POINT *)&prc->right, *(POINTL *)&prcl->right);
}
void
CDoc::HimetricFromDevice(SIZEL *psizel, int cx, int cy)
{
psizel->cx = MulDivQuick(cx,
100 * _sizel.cx,
100 * _pSiteRoot->_rc.right);
psizel->cy = MulDivQuick(cy,
100 * _sizel.cy,
100 * _pSiteRoot->_rc.bottom);
}
void
CDoc::HimetricFromDevice(POINTL *pptl, int x, int y)
{
pptl->x = MulDivQuick(x - _pSiteRoot->_rc.left,
100 * _sizel.cx,
100 * _pSiteRoot->_rc.right);
pptl->y = MulDivQuick(y - _pSiteRoot->_rc.top,
100 * _sizel.cy,
100 * _pSiteRoot->_rc.bottom);
}
void
CDoc::HimetricFromDevice(RECTL *prcl, const RECT *prc)
{
HimetricFromDevice((POINTL *)&prcl->left, *(POINT *)&prc->left);
HimetricFromDevice((POINTL *)&prcl->right, *(POINT *)&prc->right);
}
*/
| 28.35 | 79 | 0.525321 | King0987654 |
0de65532cb5c29f81f26e0e4af0b35029675c23d | 605 | cpp | C++ | qmessagebox/mainwindow.cpp | orthoWitch/gosha-dudar-qt | 6ec073a2bd1e6bd13f9084d84b6340d60753b978 | [
"Apache-2.0"
] | null | null | null | qmessagebox/mainwindow.cpp | orthoWitch/gosha-dudar-qt | 6ec073a2bd1e6bd13f9084d84b6340d60753b978 | [
"Apache-2.0"
] | null | null | null | qmessagebox/mainwindow.cpp | orthoWitch/gosha-dudar-qt | 6ec073a2bd1e6bd13f9084d84b6340d60753b978 | [
"Apache-2.0"
] | null | null | null | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
QMessageBox::StandardButton reply = QMessageBox::question(this, "Заголовок", "Просто текст внутри",
QMessageBox::Yes | QMessageBox::No);
if(reply == QMessageBox::Yes) {
QApplication::quit();
} else {
qDebug() << "Кнопка нет была нажата";
}
}
| 20.862069 | 103 | 0.636364 | orthoWitch |
0de69b676def4b06bd314dfdd1dbf06961d598ea | 1,987 | inl | C++ | include/Nazara/Renderer/ShaderBuilder.inl | AntoineJT/NazaraEngine | e0b05a7e7a2779e20a593b4083b4a881cc57ce14 | [
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | null | null | null | include/Nazara/Renderer/ShaderBuilder.inl | AntoineJT/NazaraEngine | e0b05a7e7a2779e20a593b4083b4a881cc57ce14 | [
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | null | null | null | include/Nazara/Renderer/ShaderBuilder.inl | AntoineJT/NazaraEngine | e0b05a7e7a2779e20a593b4083b4a881cc57ce14 | [
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | null | null | null | // Copyright (C) 2016 Jérôme Leclercq
// This file is part of the "Nazara Engine - Renderer module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Renderer/ShaderBuilder.hpp>
#include <Nazara/Renderer/Debug.hpp>
namespace Nz { namespace ShaderBuilder
{
template<typename T>
template<typename... Args>
std::shared_ptr<T> GenBuilder<T>::operator()(Args&&... args) const
{
return std::make_shared<T>(std::forward<Args>(args)...);
}
template<ShaderAst::AssignType op>
std::shared_ptr<ShaderAst::AssignOp> AssignOpBuilder<op>::operator()(const ShaderAst::VariablePtr& left, const ShaderAst::ExpressionPtr& right) const
{
return std::make_shared<ShaderAst::AssignOp>(op, left, right);
}
template<ShaderAst::BinaryType op>
std::shared_ptr<ShaderAst::BinaryOp> BinOpBuilder<op>::operator()(const ShaderAst::ExpressionPtr& left, const ShaderAst::ExpressionPtr& right) const
{
return std::make_shared<ShaderAst::BinaryOp>(op, left, right);
}
inline std::shared_ptr<ShaderAst::Variable> BuiltinBuilder::operator()(ShaderAst::BuiltinEntry builtin) const
{
ShaderAst::ExpressionType exprType = ShaderAst::ExpressionType::Void;
switch (builtin)
{
case ShaderAst::BuiltinEntry::VertexPosition:
exprType = ShaderAst::ExpressionType::Float4;
break;
}
NazaraAssert(exprType != ShaderAst::ExpressionType::Void, "Unhandled builtin");
return std::make_shared<ShaderAst::BuiltinVariable>(builtin, exprType);
}
template<ShaderAst::VariableType type>
template<typename... Args>
std::shared_ptr<ShaderAst::Variable> VarBuilder<type>::operator()(Args&&... args) const
{
return std::make_shared<ShaderAst::NamedVariable>(type, std::forward<Args>(args)...);
}
template<ShaderAst::ExpressionType Type, typename... Args>
std::shared_ptr<ShaderAst::Cast> Cast(Args&&... args)
{
return std::make_shared<ShaderAst::Cast>(Type, std::forward<Args>(args)...);
}
} }
#include <Nazara/Renderer/DebugOff.hpp>
| 33.116667 | 150 | 0.739809 | AntoineJT |
0df0d2d980557624e8cef36ad62f2c6d03e28351 | 2,939 | cpp | C++ | SyscallDumper/main.cpp | Nerlant/SyscallDumper | 89c3e8e20119cf0c8c339f7620375e2fbd478927 | [
"MIT"
] | 20 | 2019-12-24T05:17:35.000Z | 2021-08-07T05:29:13.000Z | SyscallDumper/main.cpp | Nerlant/SyscallDumper | 89c3e8e20119cf0c8c339f7620375e2fbd478927 | [
"MIT"
] | null | null | null | SyscallDumper/main.cpp | Nerlant/SyscallDumper | 89c3e8e20119cf0c8c339f7620375e2fbd478927 | [
"MIT"
] | 7 | 2019-12-24T05:41:11.000Z | 2020-05-10T22:14:21.000Z |
#include <Windows.h>
#include <fstream>
#include <memory>
#include <cstdint>
#include <ctime>
#include <iomanip>
#include <sstream>
#include <string>
template<class T = void*>
T RvaToVa(PIMAGE_NT_HEADERS nt_headers, char* image_base, uintptr_t rva)
{
auto getEnclosingSectionHeader = [&]() -> PIMAGE_SECTION_HEADER
{
auto section = reinterpret_cast<PIMAGE_SECTION_HEADER>(nt_headers + 1);
for (uint16_t i = 0; i < nt_headers->FileHeader.NumberOfSections; i++, section++)
{
auto size = section->Misc.VirtualSize;
if (!size)
size = section->SizeOfRawData;
if (rva >= section->VirtualAddress && rva < static_cast<uintptr_t>(section->VirtualAddress) + size)
return section;
}
return nullptr;
};
const PIMAGE_SECTION_HEADER sectionHeader = getEnclosingSectionHeader();
if (sectionHeader == nullptr)
return 0;
return reinterpret_cast<T>(image_base + rva - static_cast<uintptr_t>(sectionHeader->VirtualAddress) + sectionHeader->PointerToRawData);
}
int main()
{
char systemDir[MAX_PATH];
if (!GetSystemDirectoryA(systemDir, MAX_PATH))
return 1;
std::ifstream stream(std::string(systemDir) + "\\ntdll.dll", std::ifstream::binary);
if (!stream.is_open())
return 1;
stream.seekg(0, stream.end);
const auto size = stream.tellg();
stream.seekg(0, stream.beg);
std::unique_ptr<char> image(new char[size]);
stream.read(image.get(), size);
stream.close();
const auto ntHeaders = reinterpret_cast<PIMAGE_NT_HEADERS>(image.get() + reinterpret_cast<PIMAGE_DOS_HEADER>(image.get())->e_lfanew);
const auto optionalHeader = &ntHeaders->OptionalHeader;
const auto fileHeader = &ntHeaders->FileHeader;
if (fileHeader->Machine != IMAGE_FILE_MACHINE_AMD64)
return 1;
const auto t = std::time(nullptr);
tm time;
localtime_s(&time, &t);
std::stringstream ss;
ss << std::put_time(&time, "Syscall_Dump_%FT%H%M%S%z.txt");
std::ofstream output(ss.str());
const auto exportDir = RvaToVa<PIMAGE_EXPORT_DIRECTORY>(ntHeaders, image.get(), optionalHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress);
const auto funcTable = RvaToVa<DWORD*>(ntHeaders, image.get(), exportDir->AddressOfFunctions);
const auto ordTable = RvaToVa<WORD*>(ntHeaders, image.get(), exportDir->AddressOfNameOrdinals);
const auto nameTable = RvaToVa<DWORD*>(ntHeaders, image.get(), exportDir->AddressOfNames);
for (DWORD i = 0; i < exportDir->NumberOfNames; i++)
{
const auto functionName = RvaToVa<char*>(ntHeaders, image.get(), nameTable[i]);
const auto ordinal = ordTable[i];
const auto functionOffset = funcTable[ordinal];
const auto function = RvaToVa<uint8_t*>(ntHeaders, image.get(), functionOffset);
/*
mov r10, rcx
mov eax, index
*/
if (function[0] == 0x4C && function[1] == 0x8B && function[2] == 0xD1 && function[3] == 0xB8)
output << functionName << ": 0x" << std::hex << *reinterpret_cast<uint32_t*>(function + 4) << std::endl;
}
output.close();
return 0;
} | 31.265957 | 157 | 0.71555 | Nerlant |
0df9f590fbd72930ba5426cc87c399f81bd1378b | 12,959 | cpp | C++ | CHE/io/HByteConvert.cpp | CUITCHE/CHE.Network.cpp | 9f102b5a3ff585c6756e63574b461d71a767decc | [
"MIT"
] | null | null | null | CHE/io/HByteConvert.cpp | CUITCHE/CHE.Network.cpp | 9f102b5a3ff585c6756e63574b461d71a767decc | [
"MIT"
] | null | null | null | CHE/io/HByteConvert.cpp | CUITCHE/CHE.Network.cpp | 9f102b5a3ff585c6756e63574b461d71a767decc | [
"MIT"
] | null | null | null | #include "HByteConvert.h"
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <cassert>
CHE_NAMESPACE_BEGIN
DATATYPESET HByteConvert::_convertDataTypeCollection;
string HByteConvert::ws2s(const wstring &ws)
{
string curLocale = setlocale(LC_ALL, NULL); // curLocale = "C";
setlocale(LC_ALL, "chs");
const wchar_t* _Source = ws.c_str();
size_t _Dsize = 2 * ws.size() + 1;
char *_Dest = new char[_Dsize];
assert(_Dest != NULL);
CheZeroMemory(_Dest, _Dsize);
uint32 returnValue(0);
wcstombs_s(&returnValue, _Dest, _Dsize, _Source, _TRUNCATE);
string result = _Dest;
delete[]_Dest;
setlocale(LC_ALL, curLocale.c_str());
return (result);
}
wstring HByteConvert::s2ws(const string &s)
{
setlocale(LC_ALL, "chs");
const char* _Source = s.c_str();
size_t _Dsize = s.size() + 1;
wchar_t *_Dest = new wchar_t[_Dsize];
assert(_Dest != NULL);
CheZeroMemory(_Dest, _Dsize);
uint32 returnValue(0);
mbstowcs_s(&returnValue, _Dest, _Dsize, _Source, _TRUNCATE);
std::wstring result = _Dest;
delete[] _Dest;
setlocale(LC_ALL, "C");
return (result);
}
/*
const byte* HByteConvert::shortToByte(const short data)
{
//
// byte *pBuf = new byte[2];
// assert(pBuf != NULL);
//
// pBuf[0] = (byte)((data & 0xff00) >> 8);
// pBuf[1] = (byte)(data & 0x00ff);
_convertDataTypeCollection = data;
return _convertDataTypeCollection;
}
void HByteConvert::shortToByte(const short data, byte *pBuf)
{
assert(pBuf != NULL);
//
// pBuf[0] = (byte)((data & 0xff00) >> 8);
// pBuf[1] = (byte)(data & 0x00ff);
_convertDataTypeCollection = data;
memcpy2(pBuf, _convertDataTypeCollection);
}
short HByteConvert::byteToShort(const byte *pBuf)
{
assert(pBuf != NULL);
//
// short high = (short)((pBuf[0] << 8) & 0xff00);
// short low = (short)(pBuf[1] & 0xff);
// short t = high | low;
_convertDataTypeCollection.memcpy2(pBuf);
return _convertDataTypeCollection;
}
byte* HByteConvert::intToByte(const int data)
{
//
// byte *pBuf = new byte[4];
// assert(pBuf != NULL);
//
// pBuf[3] = (byte)((data & 0xff));
// pBuf[2] = (byte)((data & 0xff00) >> 8);
// pBuf[1] = (byte)((data & 0xff0000) >> 16);
// pBuf[0] = (byte)((data & 0xff000000) >> 24);
_convertDataTypeCollection = data;
return _convertDataTypeCollection;
}
void HByteConvert::intToByte(const int data, byte *pBuf)
{
assert(pBuf != NULL);
// pBuf[3] = (byte)((data & 0xff));
// pBuf[2] = (byte)((data & 0xff00) >> 8);
// pBuf[1] = (byte)((data & 0xff0000) >> 16);
// pBuf[0] = (byte)((data & 0xff000000) >> 24);
_convertDataTypeCollection = data;
memcpy4(pBuf, _convertDataTypeCollection);
}
int HByteConvert::byteToInt(const byte *pBuf)
{
assert(pBuf != NULL);
//
// int h24 = pBuf[0] << 24 & 0xff000000;
// int h16 = pBuf[1] << 16 & 0xff0000;
// int l8 = pBuf[2] << 8 & 0xff00;
// int l = pBuf[3] & 0xff;
//
// int t = h24 | h16 | l8 | l;
_convertDataTypeCollection.memcpy4(pBuf);
return _convertDataTypeCollection;
}
byte* HByteConvert::long64ToByte(const long long &data)
{
// byte *pBuf = new byte[8];
// assert(pBuf != NULL);
//
// pBuf[7] = (byte)(data & 0xffL);
// pBuf[6] = (byte)((data & 0xff00L) >> 8);
// pBuf[5] = (byte)((data & 0xff0000L) >> 16);
// pBuf[4] = (byte)((data & 0xff000000L) >> 24);
// pBuf[3] = (byte)((data & 0xff00000000L) >> 32);
// pBuf[2] = (byte)((data & 0xff0000000000L) >> 40);
// pBuf[1] = (byte)((data & 0xff000000000000L) >> 48);
// pBuf[0] = (byte)((data & 0xff00000000000000L) >> 56);
_convertDataTypeCollection = data;
return _convertDataTypeCollection;
}
void HByteConvert::long64ToByte(const long long &data, byte *pBuf)
{
assert(pBuf != NULL);
// pBuf[7] = (byte)(data & 0xffL);
// pBuf[6] = (byte)((data & 0xff00L) >> 8);
// pBuf[5] = (byte)((data & 0xff0000L) >> 16);
// pBuf[4] = (byte)((data & 0xff000000L) >> 24);
// pBuf[3] = (byte)((data & 0xff00000000L) >> 32);
// pBuf[2] = (byte)((data & 0xff0000000000L) >> 40);
// pBuf[1] = (byte)((data & 0xff000000000000L) >> 48);
// pBuf[0] = (byte)((data & 0xff00000000000000L) >> 56);
_convertDataTypeCollection = data;
memcpy8(pBuf, _convertDataTypeCollection);
}
long long HByteConvert::byteToLong64(const byte *pBuf)
{
assert(pBuf != NULL);
// long long h56 = (long long)pBuf[0] << 56 & 0xff00000000000000L;
// long long h48 = (long long)pBuf[1] << 48 & 0xff000000000000L;
// long long h40 = (long long)pBuf[2] << 40 & 0xff0000000000L;
// long long h32 = (long long)pBuf[3] << 32 & 0xff00000000L;
// long long l24 = (long long)pBuf[4] << 24 & 0xff000000L;
// long long l16 = (long long)pBuf[5] << 16 & 0xff0000L;
// long long l08 = (long long)pBuf[6] << 8 & 0xff00L;
// long long l00 = (long long)pBuf[7] & 0xffL;
//
// long long t = h32 | h40 | h48 | h56 | l00 | l08 | l16 | l24;
_convertDataTypeCollection.memcpy8(pBuf);
return _convertDataTypeCollection;
}
*/
/*
byte* HByteConvert::stringToByte(const string &data)
{
QString str = QString::fromStdString(data);
QByteArray array = str.toLocal8Bit();
char *pchar = new char[array.size() + 1];
pchar[array.size()] = 0;
memcpy_s(pchar, array.size(), array.constData(), array.size());
return (byte *)pchar;
// wstring wstr = s2ws(data);
// wchar_t *wchar = const_cast<wchar_t *>(wstr.c_str());
// assert(wchar != NULL);
// int size = WideCharToMultiByte(CP_ACP, 0, wchar, -1, NULL, 0, NULL, NULL);
// char *pchar = new char[size + 1];
// if (!WideCharToMultiByte(CP_ACP, 0, wchar, -1, pchar, size, NULL, NULL))
// {
// delete[]pchar;
// }
// return (byte *)pchar;
}
void HByteConvert::stringToByte(const string &data, byte *pBuf)
{
assert(pBuf == NULL);
QString str = QString::fromStdString(data);
QByteArray array = str.toLocal8Bit();
pBuf = new byte[array.size() + 1];
memcpy_s(pBuf, array.size(), array.constData(), array.size());
// assert(pBuf == NULL);
// wstring wstr = s2ws(data);
// wchar_t *wchar = const_cast<wchar_t *>(wstr.c_str());
// assert(wchar != NULL);
// int size = WideCharToMultiByte(CP_ACP, 0, wchar, -1, NULL, 0, NULL, NULL);
// char *pchar = new char[size + 1];
// if (!WideCharToMultiByte(CP_ACP, 0, wchar, -1, pchar, size, NULL, NULL))
// {
// delete[]pchar;
// }
//
// pBuf = (byte *)pchar;
}
void HByteConvert::byteToString(string &data, const byte *pBuf)
{
data = utf8((const char *)pBuf).toStdString();
// char *pchar = (char *)pBuf;
// int size = MultiByteToWideChar(CP_ACP, 0, pchar, -1, NULL, 0);
// wchar_t *wchar = new wchar_t[size + 1];
// assert(wchar != NULL);
// if (!MultiByteToWideChar(CP_ACP, 0, pchar, -1, wchar, size))
// {
// delete[]wchar;
// }
// wstring wstr = wchar;
// data = ws2s(wstr);
// wchar != NULL ? delete[]wchar, wchar = NULL : 0;
}
byte* HByteConvert::stringToByte(const QString &data)
{
QByteArray array = data.toLocal8Bit();
char *pchar = new char[array.size() + 1];
pchar[array.size()] = 0;
memcpy_s(pchar, array.size(), array.constData(), array.size());
return (byte *)pchar;
}
void HByteConvert::stringToByte(const QString &data, byte *pBuf)
{
QByteArray array = data.toLocal8Bit();
char *pchar = new char[array.size() + 1];
pchar[array.size()] = 0;
memcpy_s(pchar, array.size(), array.constData(), array.size());
}
void HByteConvert::byteToString(QString &data, const byte *pBuf)
{
data = utf8((const char *)pBuf);
}
*/
/*
byte* HByteConvert::doubleToByte(const double &data)
{
// byte *pBuf = new byte[9];
// memcpy_s(pBuf, 8, &data, 8);
_convertDataTypeCollection = data;
return _convertDataTypeCollection;
}
void HByteConvert::doubleToByte(const double &data, byte *&pBuf)
{
// memcpy_s(pBuf, 8, &data, 8);
_convertDataTypeCollection = data;
memcpy8(pBuf, _convertDataTypeCollection);
}
double HByteConvert::byteToDouble(const byte *pBuf)
{
_convertDataTypeCollection.memcpy8(pBuf);
return _convertDataTypeCollection;
}
byte* HByteConvert::floatToByte(const float data)
{
// byte *pBuf = new byte[4];
// memcpy_s(pBuf, 4, &data, 4);
// return pBuf;
_convertDataTypeCollection = data;
return _convertDataTypeCollection;
}
void HByteConvert::floatToByte(const float data, byte *pBuf)
{
// memcpy_s(pBuf, 4, &data, 4);
_convertDataTypeCollection = data;
memcpy4(pBuf, _convertDataTypeCollection);
}
float HByteConvert::byteToFloat(const byte *pBuf)
{
// float value = 0;
// memcpy_s(&value, 4, pBuf, 4);
// return value;
_convertDataTypeCollection.memcpy4(pBuf);
return _convertDataTypeCollection;
}
*/
/*
void HByteConvert::writeByte(HDataBuffer &buf, byte data)
{
buf.putBytes(&data, 1);
}
byte HByteConvert::readByte(HDataBuffer &buf)
{
const byte *pBuf = buf.fetchBytes(1);
return *pBuf;
}
void HByteConvert::writeBytes(HDataBuffer &buf, byte *data, INT length)
{
byte *pBuf = intToByte(length);
buf.putBytes(pBuf,4); //先写入长度
buf.putBytes(data,length); //再写入bytes 数据
}
//返回bytes的长度
const byte* HByteConvert::readBytes(HDataBuffer &buf, int &size)
{
const byte *pBuf = buf.fetchBytes(4); //得到长度数据
size = byteToInt(pBuf);
return buf.fetchBytes(size);
}
void HByteConvert::writeShort(HDataBuffer &buf, short data)
{
byte *pBuf = shortToByte(data);
buf.putBytes(pBuf, 2);
}
short HByteConvert::readShort(HDataBuffer &buf)
{
const byte *pBuf = buf.fetchBytes(2);
short t = byteToShort(pBuf);
return t;
}
void HByteConvert::writeInt(HDataBuffer &buf, int data)
{
byte *pBuf = intToByte(data);
buf.putBytes(pBuf, 4);
}
int HByteConvert::readInt(HDataBuffer &buf)
{
const byte *pBuf = buf.fetchBytes(4);
int t = byteToInt(pBuf);
return t;
}
void HByteConvert::writeDouble(HDataBuffer &buf, double &data)
{
const byte *pBuf = doubleToByte(data);
// int16 len = strlen((char *)pBuf);
//
// byte *pBuf_ = shortToByte(len);//写入长度
// buf.putBytes(pBuf_, 2);
// delete[]pBuf_;
buf.putBytes(pBuf, 8);//写入数据
}
double HByteConvert::readDouble(HDataBuffer &buf)
{
const byte *pBuf = buf.fetchBytes(8);
// uint16 len = byteToShort(pBuf);//获取长度
// delete []pBuf;
//
// if (len == 0) return 0;
//
// pBuf = buf.fetchBytes(len);
double ret = byteToDouble(pBuf);
return ret;
}
void HByteConvert::writeLong64(HDataBuffer &buf, long long data)
{
byte *pBuf = long64ToByte(data);
buf.putBytes(pBuf, 8);
}
long long HByteConvert::readLong64(HDataBuffer &buf)
{
const byte *pBuf = buf.fetchBytes(8);
long long t = byteToLong64(pBuf);
return t;
}
*/
/*
void HByteConvert::write256String(HDataBuffer &buf, string &data)
{
int16 len = data.length();
len >= 255 ? len = 255 : 0;
byte l = (byte)len;
buf.putBytes(&l,1);//写入string长度
byte *pBuf = stringToByte(data);
buf.putBytes(pBuf, len);
delete[]pBuf;
}
void HByteConvert::write256String(HDataBuffer &buf, QString &data)
{
int16 len = data.size();
len >= 255 ? len = 255 : 0;
byte l = (byte)len;
buf.putBytes(&l, 1);
byte *pBuf = stringToByte(data);
buf.putBytes(pBuf, len);
delete[]pBuf;
}
void HByteConvert::read256String(string &_256String, HDataBuffer &buf)
{
const byte *pBuf = buf.fetchBytes(1);//得到长度
int len = pBuf[0];
if (len == 0)
{
_256String = "";
return;
}
pBuf = buf.fetchBytes(len);
byteToString(_256String, pBuf);
}
void HByteConvert::read256String(QString &_256String, HDataBuffer &buf)
{
const byte *pBuf = buf.fetchBytes(1);//得到长度
int len = pBuf[0];
if (len == 0)
{
_256String = "";
return;
}
pBuf = buf.fetchBytes(len);
byteToString(_256String, pBuf);
}
void HByteConvert::writeShortString(HDataBuffer &buf, string &data)
{
int32 len = data.length();
len > 65535 ? len = 65535 : 0;
const byte *pBuf = shortToByte((uint16)len);
buf.putBytes(pBuf, 2);
pBuf = stringToByte(data);
buf.putBytes(pBuf, (uint16)len);
delete[]pBuf;
}
void HByteConvert::writeShortString(HDataBuffer &buf, QString &data)
{
int32 len = data.length();
len > 65535 ? len = 65535 : 0;
byte *pBuf = shortToByte((uint16)len);
buf.putBytes(pBuf, 2);
pBuf = stringToByte(data);
buf.putBytes(pBuf, (uint16)len);
delete[]pBuf;
}
void HByteConvert::readShortString(string &_shortString, HDataBuffer &buf)
{
const byte *pBuf = buf.fetchBytes(2);//得到长度
uint16 len = byteToShort(pBuf);
if (len == 0)
{
_shortString = "";
return;
}
pBuf = buf.fetchBytes(len);
byteToString(_shortString, pBuf);
}
void HByteConvert::readShortString(QString &_shortString, HDataBuffer &buf)
{
const byte *pBuf = buf.fetchBytes(2);//得到长度
uint16 len = byteToShort(pBuf);
if (len == 0)
{
_shortString = "";
return;
}
pBuf = buf.fetchBytes(len);
byteToString(_shortString, pBuf);
}
void HByteConvert::writeVectorString(HDataBuffer &buf, vector<string> &arry)
{
int num = arry.size();
const byte *pBuf = shortToByte((uint16)num);
buf.putBytes(pBuf, 2);
vector<string>::iterator iter = arry.begin();
while (iter != arry.end())
{
writeShortString(buf,*iter);
++iter;
}
}
void HByteConvert::readVectorString(HDataBuffer &buf, vector<string> &result)
{
const byte *pBuf = buf.fetchBytes(2);//得到vector的个数
uint16 len = byteToShort(pBuf);
for (uint16 i = 0; i < len; i++)
{
string str;
readShortString(str, buf);
result.push_back(str);
}
}
*/
CHE_NAMESPACE_END
| 24.590133 | 78 | 0.665869 | CUITCHE |
df0438c6e92f5a896f8a86d411d0dd99d5462aff | 910 | hpp | C++ | shared_model/backend/plain/domain.hpp | akshatkarani/iroha | 5acef9dd74720c6185360d951e9b11be4ef73260 | [
"Apache-2.0"
] | 1,467 | 2016-10-25T12:27:19.000Z | 2022-03-28T04:32:05.000Z | shared_model/backend/plain/domain.hpp | akshatkarani/iroha | 5acef9dd74720c6185360d951e9b11be4ef73260 | [
"Apache-2.0"
] | 2,366 | 2016-10-25T10:07:57.000Z | 2022-03-31T22:03:24.000Z | shared_model/backend/plain/domain.hpp | akshatkarani/iroha | 5acef9dd74720c6185360d951e9b11be4ef73260 | [
"Apache-2.0"
] | 662 | 2016-10-26T04:41:22.000Z | 2022-03-31T04:15:02.000Z | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef IROHA_SHARED_MODEL_PLAIN_DOMAIN_HPP
#define IROHA_SHARED_MODEL_PLAIN_DOMAIN_HPP
#include "interfaces/common_objects/domain.hpp"
#include "interfaces/common_objects/types.hpp"
namespace shared_model {
namespace plain {
class Domain final : public interface::Domain {
public:
Domain(const interface::types::DomainIdType &domain_id,
const interface::types::RoleIdType &default_role_id);
const interface::types::DomainIdType &domainId() const override;
const interface::types::RoleIdType &defaultRole() const override;
private:
const interface::types::DomainIdType domain_id_;
const interface::types::RoleIdType default_role_id_;
};
} // namespace plain
} // namespace shared_model
#endif // IROHA_SHARED_MODEL_PLAIN_DOMAIN_HPP
| 27.575758 | 71 | 0.737363 | akshatkarani |
df0572c7a7727ed9b03a627e2cd179d045a053cd | 6,414 | cpp | C++ | Oblig2/PhysicsEngine.cpp | RyanTorant/simple-physx | a065a9c734c134074c63c80a9109a398b22d040c | [
"Unlicense"
] | 1 | 2019-12-09T16:03:55.000Z | 2019-12-09T16:03:55.000Z | Oblig2/PhysicsEngine.cpp | RyanTorant/simple-physx | a065a9c734c134074c63c80a9109a398b22d040c | [
"Unlicense"
] | null | null | null | Oblig2/PhysicsEngine.cpp | RyanTorant/simple-physx | a065a9c734c134074c63c80a9109a398b22d040c | [
"Unlicense"
] | null | null | null | #include "PhysicsEngine.h"
#include <chrono>
PhysicsEngine::ErrorLogger PhysicsEngine::ErrorCallback;
PxDefaultAllocator PhysicsEngine::Allocator;
PhysicsEngine::~PhysicsEngine()
{
if (GlobalScene)
GlobalScene->release();
if (Dispatcher)
Dispatcher->release();
if (Physics)
Physics->release();
if (PVD)
{
PxPvdTransport* transport = PVD->getTransport();
PVD->release();
transport->release();
}
if (Foundation)
Foundation->release();
}
bool PhysicsEngine::Initialize(uint32_t NumThreads, PxVec3 Gravity)
{
this->Gravity = Gravity;
using namespace std;
Foundation = PxCreateFoundation(PX_FOUNDATION_VERSION, Allocator, ErrorCallback);
if (!Foundation)
{
cout << "Failed to create the PhysX foundation instance" << endl;
return false;
}
#ifdef _DEBUG
bool record_memory_allocations = true;
// Support for the PhysX Visual Debugger [https://developer.nvidia.com/physx-visual-debugger]
PVD = PxCreatePvd(*Foundation);
PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate("127.0.0.1", 5425, 10);
if (!PVD->connect(*transport, PxPvdInstrumentationFlag::eALL))
cout << "[Warning] Could not connect to the visual debugger. Maybe it's not open?" << endl;
#else
bool record_memory_allocations = false;
#endif
PxTolerancesScale scaling;
scaling.length = 100;
Physics = PxCreatePhysics(PX_PHYSICS_VERSION, *Foundation, scaling, record_memory_allocations, PVD);
if (!Physics)
{
cout << "Failed to create the PhysX physics instance" << endl;
return false;
}
Cooker = PxCreateCooking(PX_PHYSICS_VERSION, *Foundation, PxCookingParams(scaling));
if (!Cooker)
{
cout << "Failed to create the PhysX cooker instance" << endl;
return false;
}
PxSceneDesc scene_desc(Physics->getTolerancesScale());
scene_desc.gravity = Gravity;
Dispatcher = PxDefaultCpuDispatcherCreate(NumThreads);
scene_desc.cpuDispatcher = Dispatcher;
scene_desc.filterShader = PxDefaultSimulationFilterShader;
GlobalScene = Physics->createScene(scene_desc);
CharacterManager = PxCreateControllerManager(*GlobalScene);
#ifdef _DEBUG
PxPvdSceneClient* pvd_client = GlobalScene->getScenePvdClient();
if (pvd_client)
{
pvd_client->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true);
pvd_client->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true);
pvd_client->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true);
}
#endif
// Create default material
DefaultMaterial = Physics->createMaterial(0.5f, 0.5f, 0.6f);
return true;
}
void PhysicsEngine::Simulate(float ElapsedTimeSeconds)
{
GlobalScene->simulate(ElapsedTimeSeconds);
GlobalScene->fetchResults(true);
}
bool PhysicsEngine::CreateStaticActor(size_t MeshID,PxVec3 Position, PxQuat Rotation, PxVec3 Scale)
{
using namespace std;
if (MeshID < 0 && MeshID >= TriangleMeshes.size())
{
cout << "Invalid mesh id [" << MeshID << "] provided to CreateStaticActor" << endl;
return false;
}
PxTriangleMeshGeometry instance;
instance.triangleMesh = TriangleMeshes[MeshID];
instance.scale = Scale;
PxTransform tworld(Position, Rotation);
// No need to keep the rigid body pointer and clean it by hand, they are removed by the SDK
auto actor = PxCreateStatic(*Physics, tworld, instance, *DefaultMaterial);
if (!actor)
{
cout << "Failed to create the static actor" << endl;
return false;
}
GlobalScene->addActor(*actor);
return true;
}
bool PhysicsEngine::CreateTerrain(PxVec3 Position, PxVec3 Scale, uint32_t SizeX, uint32_t SizeY, float MinZ, float MaxZ, const std::vector<float>& Heightmap)
{
using namespace std;
PxHeightFieldDesc hf_desc;
hf_desc.format = PxHeightFieldFormat::eS16_TM;
hf_desc.nbColumns = SizeX;
hf_desc.nbRows = SizeY;
vector<PxHeightFieldSample> px_data(Heightmap.size());
for (uint32_t y = 0; y < SizeY; y++)
{
for (uint32_t x = 0; x < SizeX; x++)
{
uint32_t out_idx = y + x * hf_desc.nbRows;
uint32_t in_idx = x * sizeof(float) + y * SizeX;
px_data[out_idx].height = (MaxZ - MinZ) * Heightmap[in_idx] + MinZ;
px_data[out_idx].materialIndex0 = 0;
px_data[out_idx].materialIndex1 = 0;
}
}
hf_desc.samples.data = px_data.data();
hf_desc.samples.stride = sizeof(PxHeightFieldSample);
auto hf_ptr = Cooker->createHeightField(hf_desc, Physics->getPhysicsInsertionCallback());
PxHeightFieldGeometry geo(hf_ptr, PxMeshGeometryFlags(), 1, Scale.x / hf_desc.nbColumns, Scale.z / hf_desc.nbRows);
PxTransform tworld(PxVec3(Position.x, Position.y, Position.z));
// No need to keep the rigid body pointer and clean it by hand, they are removed by the SDK
auto actor = PxCreateStatic(*Physics, tworld, geo, *DefaultMaterial);
if (!actor)
{
cout << "Failed to create the terrain actor" << endl;
return false;
}
GlobalScene->addActor(*actor);
return true;
}
size_t PhysicsEngine::CreateCharacterController(PxVec3 StartPosition, float Height, float Radius)
{
PxCapsuleControllerDesc desc;
desc.height = Height;
desc.radius = Radius;
desc.position = PxExtendedVec3(StartPosition.x, StartPosition.y, StartPosition.z);
desc.contactOffset = Radius + Radius * 0.1;
desc.stepOffset = Height * 0.25;
desc.material = DefaultMaterial;
PxController * controller = CharacterManager->createController(desc);
if (!controller)
{
std::cout << "Failed to create the character controller" << std::endl;
return -1;
}
Characters.push_back(controller);
return Characters.size() - 1;
}
PxController * PhysicsEngine::GetCharacter(size_t ID)
{
if (ID < 0 && ID >= Characters.size())
{
std::cout << "Invalid character ID [" << ID << "] provided to GetCharacter" << std::endl;
return nullptr;
}
return Characters[ID];
}
void PhysicsEngine::SimulateFixedFrequency(float Frequency, std::function<void(float ElapsedTime)> Callback)
{
using namespace std;
static auto start_time = chrono::high_resolution_clock::now();
float step_size = 1.0f / Frequency;
ElapsedTime = chrono::duration<float, std::deca>(chrono::high_resolution_clock::now() - start_time).count();
if (ElapsedTime >= step_size)
{
if (Callback) Callback(ElapsedTime);
Simulate(ElapsedTime);
start_time = chrono::high_resolution_clock::now();
}
}
PxControllerCollisionFlags PhysicsEngine::MoveCharacter(size_t ID, PxVec3 Disp, float ElapsedTime, bool ApplyGravity)
{
auto char_ptr = GetCharacter(ID);
if (ApplyGravity) Disp += Gravity;
return char_ptr->move(Disp, 1e-6, ElapsedTime, PxControllerFilters());
}
| 27.886957 | 157 | 0.741347 | RyanTorant |
df062277220920056aca384d72091bc21acee2b1 | 14,766 | cpp | C++ | flow/MkCert.cpp | sfc-gh-bvr/foundationdb | 7594f5c0f92d2582dae717ce0244c11642b27dd4 | [
"Apache-2.0"
] | null | null | null | flow/MkCert.cpp | sfc-gh-bvr/foundationdb | 7594f5c0f92d2582dae717ce0244c11642b27dd4 | [
"Apache-2.0"
] | null | null | null | flow/MkCert.cpp | sfc-gh-bvr/foundationdb | 7594f5c0f92d2582dae717ce0244c11642b27dd4 | [
"Apache-2.0"
] | null | null | null | /*
* MkCert.cpp
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2013-2022 Apple Inc. and the FoundationDB project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "flow/Arena.h"
#include "flow/IRandom.h"
#include "flow/MkCert.h"
#include "flow/ScopeExit.h"
#include <limits>
#include <memory>
#include <string>
#include <cstring>
#include <openssl/bio.h>
#include <openssl/ec.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/objects.h>
#include <openssl/pem.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
namespace {
[[noreturn]] void traceAndThrow(const char* condition, int line) {
auto te = TraceEvent(SevWarnAlways, "MkCertOrKeyError");
te.suppressFor(10).detail("Line", line).detail("Condition", condition);
if (auto err = ::ERR_get_error()) {
char buf[256]{
0,
};
::ERR_error_string_n(err, buf, sizeof(buf));
te.detail("OpenSSLError", static_cast<const char*>(buf));
}
throw tls_error();
}
} // anonymous namespace
#define OSSL_ASSERT(condition) \
do { \
if (!(condition)) \
traceAndThrow(#condition, __LINE__); \
} while (false)
namespace mkcert {
// Helper functions working with OpenSSL native types
std::shared_ptr<X509> readX509CertPem(StringRef x509CertPem);
std::shared_ptr<EVP_PKEY> readPrivateKeyPem(StringRef privateKeyPem);
std::shared_ptr<EVP_PKEY> readPrivateKeyPem(StringRef privateKeyPem);
std::shared_ptr<EVP_PKEY> makeEllipticCurveKeyPairNative();
StringRef writeX509CertPem(Arena& arena, const std::shared_ptr<X509>& nativeCert);
StringRef writePrivateKeyPem(Arena& arena, const std::shared_ptr<EVP_PKEY>& nativePrivateKey);
struct CertAndKeyNative {
std::shared_ptr<X509> cert;
std::shared_ptr<EVP_PKEY> privateKey;
bool valid() const noexcept { return cert && privateKey; }
// self-signed cert case
bool null() const noexcept { return !cert && !privateKey; }
using SelfType = CertAndKeyNative;
using PemType = CertAndKeyRef;
static SelfType fromPem(PemType certAndKey) {
auto ret = SelfType{};
if (certAndKey.empty())
return ret;
auto [certPem, keyPem] = certAndKey;
// either both set or both unset
ASSERT(!certPem.empty() && !keyPem.empty());
ret.cert = readX509CertPem(certPem);
ret.privateKey = readPrivateKeyPem(keyPem);
return ret;
}
PemType toPem(Arena& arena) {
auto ret = PemType{};
if (null())
return ret;
ASSERT(valid());
ret.certPem = writeX509CertPem(arena, cert);
ret.privateKeyPem = writePrivateKeyPem(arena, privateKey);
return ret;
}
};
CertAndKeyNative makeCertNative(CertSpecRef spec, CertAndKeyNative issuer);
void printCert(FILE* out, StringRef certPem) {
auto x = readX509CertPem(certPem);
OSSL_ASSERT(0 < ::X509_print_fp(out, x.get()));
}
void printPrivateKey(FILE* out, StringRef privateKeyPem) {
auto key = readPrivateKeyPem(privateKeyPem);
auto bio = ::BIO_new_fp(out, BIO_NOCLOSE);
OSSL_ASSERT(bio);
auto bioGuard = ScopeExit([bio]() { ::BIO_free(bio); });
OSSL_ASSERT(0 < ::EVP_PKEY_print_private(bio, key.get(), 0, nullptr));
}
std::shared_ptr<EVP_PKEY> makeEllipticCurveKeyPairNative() {
auto params = std::add_pointer_t<EVP_PKEY>();
{
auto pctx = ::EVP_PKEY_CTX_new_id(EVP_PKEY_EC, nullptr);
OSSL_ASSERT(pctx);
auto ctxGuard = ScopeExit([pctx]() { ::EVP_PKEY_CTX_free(pctx); });
OSSL_ASSERT(0 < ::EVP_PKEY_paramgen_init(pctx));
OSSL_ASSERT(0 < ::EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx, NID_X9_62_prime256v1));
OSSL_ASSERT(0 < ::EVP_PKEY_paramgen(pctx, ¶ms));
OSSL_ASSERT(params);
}
auto paramsGuard = ScopeExit([params]() { ::EVP_PKEY_free(params); });
// keygen
auto kctx = ::EVP_PKEY_CTX_new(params, nullptr);
OSSL_ASSERT(kctx);
auto kctxGuard = ScopeExit([kctx]() { ::EVP_PKEY_CTX_free(kctx); });
auto key = std::add_pointer_t<EVP_PKEY>();
OSSL_ASSERT(0 < ::EVP_PKEY_keygen_init(kctx));
OSSL_ASSERT(0 < ::EVP_PKEY_keygen(kctx, &key));
OSSL_ASSERT(key);
return std::shared_ptr<EVP_PKEY>(key, &::EVP_PKEY_free);
}
std::shared_ptr<X509> readX509CertPem(StringRef x509CertPem) {
ASSERT(!x509CertPem.empty());
auto bio_mem = ::BIO_new_mem_buf(x509CertPem.begin(), x509CertPem.size());
OSSL_ASSERT(bio_mem);
auto bioGuard = ScopeExit([bio_mem]() { ::BIO_free(bio_mem); });
auto ret = ::PEM_read_bio_X509(bio_mem, nullptr, nullptr, nullptr);
OSSL_ASSERT(ret);
return std::shared_ptr<X509>(ret, &::X509_free);
}
std::shared_ptr<EVP_PKEY> readPrivateKeyPem(StringRef privateKeyPem) {
ASSERT(!privateKeyPem.empty());
auto bio_mem = ::BIO_new_mem_buf(privateKeyPem.begin(), privateKeyPem.size());
OSSL_ASSERT(bio_mem);
auto bioGuard = ScopeExit([bio_mem]() { ::BIO_free(bio_mem); });
auto ret = ::PEM_read_bio_PrivateKey(bio_mem, nullptr, nullptr, nullptr);
OSSL_ASSERT(ret);
return std::shared_ptr<EVP_PKEY>(ret, &::EVP_PKEY_free);
}
StringRef writeX509CertPem(Arena& arena, const std::shared_ptr<X509>& nativeCert) {
auto mem = ::BIO_new(::BIO_s_mem());
OSSL_ASSERT(mem);
auto memGuard = ScopeExit([mem]() { ::BIO_free(mem); });
OSSL_ASSERT(::PEM_write_bio_X509(mem, nativeCert.get()));
auto bioBuf = std::add_pointer_t<char>{};
auto const len = ::BIO_get_mem_data(mem, &bioBuf);
ASSERT_GT(len, 0);
auto buf = new (arena) uint8_t[len];
::memcpy(buf, bioBuf, len);
return StringRef(buf, static_cast<int>(len));
}
StringRef writePrivateKeyPem(Arena& arena, const std::shared_ptr<EVP_PKEY>& nativePrivateKey) {
auto mem = ::BIO_new(::BIO_s_mem());
OSSL_ASSERT(mem);
auto memGuard = ScopeExit([mem]() { ::BIO_free(mem); });
OSSL_ASSERT(::PEM_write_bio_PrivateKey(mem, nativePrivateKey.get(), nullptr, nullptr, 0, 0, nullptr));
auto bioBuf = std::add_pointer_t<char>{};
auto const len = ::BIO_get_mem_data(mem, &bioBuf);
ASSERT_GT(len, 0);
auto buf = new (arena) uint8_t[len];
::memcpy(buf, bioBuf, len);
return StringRef(buf, static_cast<int>(len));
}
KeyPairRef KeyPairRef::make(Arena& arena) {
auto keypair = makeEllipticCurveKeyPairNative();
auto ret = KeyPairRef{};
{
auto len = 0;
len = ::i2d_PrivateKey(keypair.get(), nullptr);
ASSERT_LT(0, len);
auto buf = new (arena) uint8_t[len];
auto out = std::add_pointer_t<uint8_t>(buf);
len = ::i2d_PrivateKey(keypair.get(), &out);
ret.privateKeyDer = StringRef(buf, len);
}
{
auto len = 0;
len = ::i2d_PUBKEY(keypair.get(), nullptr);
ASSERT_LT(0, len);
auto buf = new (arena) uint8_t[len];
auto out = std::add_pointer_t<uint8_t>(buf);
len = ::i2d_PUBKEY(keypair.get(), &out);
ret.publicKeyDer = StringRef(buf, len);
}
return ret;
}
CertAndKeyNative makeCertNative(CertSpecRef spec, CertAndKeyNative issuer) {
// issuer key/cert must be both set or both null (self-signed case)
ASSERT(issuer.valid() || issuer.null());
auto const isSelfSigned = issuer.null();
auto nativeKeyPair = makeEllipticCurveKeyPairNative();
auto newX = ::X509_new();
OSSL_ASSERT(newX);
auto x509Guard = ScopeExit([&newX]() {
if (newX)
::X509_free(newX);
});
auto smartX = std::shared_ptr<X509>(newX, &::X509_free);
newX = nullptr;
auto x = smartX.get();
OSSL_ASSERT(0 < ::X509_set_version(x, 2 /*X509_VERSION_3*/));
auto serialPtr = ::X509_get_serialNumber(x);
OSSL_ASSERT(serialPtr);
OSSL_ASSERT(0 < ::ASN1_INTEGER_set(serialPtr, spec.serialNumber));
auto notBefore = ::X509_getm_notBefore(x);
OSSL_ASSERT(notBefore);
OSSL_ASSERT(::X509_gmtime_adj(notBefore, spec.offsetNotBefore));
auto notAfter = ::X509_getm_notAfter(x);
OSSL_ASSERT(notAfter);
OSSL_ASSERT(::X509_gmtime_adj(notAfter, spec.offsetNotAfter));
OSSL_ASSERT(0 < ::X509_set_pubkey(x, nativeKeyPair.get()));
auto subjectName = ::X509_get_subject_name(x);
OSSL_ASSERT(subjectName);
for (const auto& entry : spec.subjectName) {
// field names are expected to null-terminate
auto fieldName = entry.field.toString();
OSSL_ASSERT(0 <
::X509_NAME_add_entry_by_txt(
subjectName, fieldName.c_str(), MBSTRING_ASC, entry.bytes.begin(), entry.bytes.size(), -1, 0));
}
auto issuerName = ::X509_get_issuer_name(x);
OSSL_ASSERT(issuerName);
OSSL_ASSERT(::X509_set_issuer_name(x, (isSelfSigned ? subjectName : ::X509_get_subject_name(issuer.cert.get()))));
auto ctx = X509V3_CTX{};
X509V3_set_ctx_nodb(&ctx);
::X509V3_set_ctx(&ctx, (isSelfSigned ? x : issuer.cert.get()), x, nullptr, nullptr, 0);
for (const auto& entry : spec.extensions) {
// extension field names and values are expected to null-terminate
auto extName = entry.field.toString();
auto extValue = entry.bytes.toString();
auto extNid = ::OBJ_txt2nid(extName.c_str());
if (extNid == NID_undef) {
TraceEvent(SevWarnAlways, "MkCertInvalidExtName").suppressFor(10).detail("Name", extName);
throw tls_error();
}
#ifdef OPENSSL_IS_BORINGSSL
auto ext = ::X509V3_EXT_nconf_nid(nullptr, &ctx, extNid, const_cast<char*>(extValue.c_str()));
#else
auto ext = ::X509V3_EXT_nconf_nid(nullptr, &ctx, extNid, extValue.c_str());
#endif
OSSL_ASSERT(ext);
auto extGuard = ScopeExit([ext]() { ::X509_EXTENSION_free(ext); });
OSSL_ASSERT(::X509_add_ext(x, ext, -1));
}
OSSL_ASSERT(::X509_sign(x, (isSelfSigned ? nativeKeyPair.get() : issuer.privateKey.get()), ::EVP_sha256()));
auto ret = CertAndKeyNative{};
ret.cert = smartX;
ret.privateKey = nativeKeyPair;
return ret;
}
CertAndKeyRef CertAndKeyRef::make(Arena& arena, CertSpecRef spec, CertAndKeyRef issuerPem) {
auto issuer = CertAndKeyNative::fromPem(issuerPem);
auto newCertAndKey = makeCertNative(spec, issuer);
return newCertAndKey.toPem(arena);
}
CertSpecRef CertSpecRef::make(Arena& arena, CertKind kind) {
auto spec = CertSpecRef{};
spec.serialNumber = static_cast<long>(deterministicRandom()->randomInt64(0, 1e10));
spec.offsetNotBefore = 0; // now
spec.offsetNotAfter = 60 * 60 * 24 * 365; // 1 year from now
auto& subject = spec.subjectName;
subject.push_back(arena, { "countryName"_sr, "DE"_sr });
subject.push_back(arena, { "localityName"_sr, "Berlin"_sr });
subject.push_back(arena, { "organizationName"_sr, "FoundationDB"_sr });
subject.push_back(arena, { "commonName"_sr, kind.getCommonName("FDB Testing Services"_sr, arena) });
auto& ext = spec.extensions;
if (kind.isCA()) {
ext.push_back(arena, { "basicConstraints"_sr, "critical, CA:TRUE"_sr });
ext.push_back(arena, { "keyUsage"_sr, "critical, digitalSignature, keyCertSign, cRLSign"_sr });
} else {
ext.push_back(arena, { "basicConstraints"_sr, "critical, CA:FALSE"_sr });
ext.push_back(arena, { "keyUsage"_sr, "critical, digitalSignature, keyEncipherment"_sr });
ext.push_back(arena, { "extendedKeyUsage"_sr, "serverAuth, clientAuth"_sr });
}
ext.push_back(arena, { "subjectKeyIdentifier"_sr, "hash"_sr });
if (!kind.isRootCA())
ext.push_back(arena, { "authorityKeyIdentifier"_sr, "keyid, issuer"_sr });
return spec;
}
StringRef concatCertChain(Arena& arena, CertChainRef chain) {
auto len = 0;
for (const auto& entry : chain) {
len += entry.certPem.size();
}
if (len == 0)
return StringRef();
auto buf = new (arena) uint8_t[len];
auto offset = 0;
for (auto const& entry : chain) {
::memcpy(&buf[offset], entry.certPem.begin(), entry.certPem.size());
offset += entry.certPem.size();
}
UNSTOPPABLE_ASSERT(offset == len);
return StringRef(buf, len);
}
CertChainRef makeCertChain(Arena& arena, VectorRef<CertSpecRef> specs, CertAndKeyRef rootAuthority) {
ASSERT_GT(specs.size(), 0);
// if rootAuthority is empty, use last element in specs to make root CA
auto const needRootCA = rootAuthority.empty();
if (needRootCA) {
int const chainLength = specs.size();
auto chain = new (arena) CertAndKeyRef[chainLength];
auto caNative = makeCertNative(specs.back(), CertAndKeyNative{} /* empty issuer == self-signed */);
chain[chainLength - 1] = caNative.toPem(arena);
for (auto i = chainLength - 2; i >= 0; i--) {
auto cnkNative = makeCertNative(specs[i], caNative);
chain[i] = cnkNative.toPem(arena);
caNative = cnkNative;
}
return CertChainRef(chain, chainLength);
} else {
int const chainLength = specs.size() + 1; /* account for deep-copied rootAuthority */
auto chain = new (arena) CertAndKeyRef[chainLength];
auto caNative = CertAndKeyNative::fromPem(rootAuthority);
chain[chainLength - 1] = rootAuthority.deepCopy(arena);
for (auto i = chainLength - 2; i >= 0; i--) {
auto cnkNative = makeCertNative(specs[i], caNative);
chain[i] = cnkNative.toPem(arena);
caNative = cnkNative;
}
return CertChainRef(chain, chainLength);
}
}
VectorRef<CertSpecRef> makeCertChainSpec(Arena& arena, unsigned length, ESide side) {
if (!length)
return {};
auto specs = new (arena) CertSpecRef[length];
auto const isServerSide = side == ESide::Server;
for (auto i = 0u; i < length; i++) {
auto kind = CertKind{};
if (i == 0u)
kind = isServerSide ? CertKind(Server{}) : CertKind(Client{});
else if (i == length - 1)
kind = isServerSide ? CertKind(ServerRootCA{}) : CertKind(ClientRootCA{});
else
kind = isServerSide ? CertKind(ServerIntermediateCA{ i }) : CertKind(ClientIntermediateCA{ i });
specs[i] = CertSpecRef::make(arena, kind);
}
return VectorRef<CertSpecRef>(specs, length);
}
CertChainRef makeCertChain(Arena& arena, unsigned length, ESide side) {
if (!length)
return {};
// temporary arena for writing up specs
auto tmpArena = Arena();
auto specs = makeCertChainSpec(tmpArena, length, side);
return makeCertChain(arena, specs, {} /*root*/);
}
StringRef CertKind::getCommonName(StringRef prefix, Arena& arena) const {
auto const side = std::string(isClientSide() ? " Client" : " Server");
if (isIntermediateCA()) {
auto const level = isClientSide() ? get<ClientIntermediateCA>().level : get<ServerIntermediateCA>().level;
return prefix.withSuffix(fmt::format("{} Intermediate {}", side, level), arena);
} else if (isRootCA()) {
return prefix.withSuffix(fmt::format("{} Root", side), arena);
} else {
return prefix.withSuffix(side, arena);
}
}
} // namespace mkcert
| 37.382278 | 120 | 0.697684 | sfc-gh-bvr |
df06417639a31e1dfee729a0b26871250a217391 | 856 | cc | C++ | type_traits/remove_cvref.cc | pycpp/stl-test | cbae1e77a16c102715c1c0c64ba3f929f78aadef | [
"MIT"
] | null | null | null | type_traits/remove_cvref.cc | pycpp/stl-test | cbae1e77a16c102715c1c0c64ba3f929f78aadef | [
"MIT"
] | null | null | null | type_traits/remove_cvref.cc | pycpp/stl-test | cbae1e77a16c102715c1c0c64ba3f929f78aadef | [
"MIT"
] | null | null | null | // :copyright: (c) 2017-2018 Alex Huszagh.
// :license: MIT, see LICENSE.md for more details.
/*
* \addtogroup Tests
* \brief `remove_cvref` unittests.
*/
#include <pycpp/stl/type_traits/remove_cvref.h>
#include <gtest/gtest.h>
PYCPP_USING_NAMESPACE
// TESTS
// -----
TEST(remove_cvref, remove_cvref)
{
static_assert(std::is_same<typename remove_cvref<int>::type, int>::value, "");
static_assert(std::is_same<remove_cvref_t<int>, int>::value, "");
static_assert(std::is_same<remove_cvref_t<int&>, int>::value, "");
static_assert(std::is_same<remove_cvref_t<const int&>, int>::value, "");
static_assert(std::is_same<remove_cvref_t<volatile int&>, int>::value, "");
static_assert(std::is_same<remove_cvref_t<const volatile int&>, int>::value, "");
static_assert(!std::is_same<remove_cvref_t<float>, int>::value, "");
}
| 32.923077 | 85 | 0.690421 | pycpp |
df0964fdde61703a0a7213b88824e398666942fb | 899 | cpp | C++ | leet_code/binary_tree/rightView.cpp | sahilduhan/codeforces | a8042d52c12806e026fd7027e35e97ed8b4eeed6 | [
"MIT"
] | null | null | null | leet_code/binary_tree/rightView.cpp | sahilduhan/codeforces | a8042d52c12806e026fd7027e35e97ed8b4eeed6 | [
"MIT"
] | null | null | null | leet_code/binary_tree/rightView.cpp | sahilduhan/codeforces | a8042d52c12806e026fd7027e35e97ed8b4eeed6 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(): val(0), left(nullptr), right(nullptr) {}
TreeNode(int x): val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode* left, TreeNode* right): val(x), left(left), right(right) {}
};
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> ans;
if (!root) return ans;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
int n = q.size();
for (int i = 0; i < n; i++) {
TreeNode* temp = q.front();
q.pop();
if (i == n - 1) ans.push_back(temp->val);
if (temp->left) q.push(temp->left);
if (temp->right) q.push(temp->right);
}
}
return ans;
}
};
| 25.685714 | 89 | 0.498331 | sahilduhan |
df09a90d5ebc6d66d817f8134c6ca75c28082158 | 828 | cpp | C++ | Siv3D/src/ThirdParty/lunasvg/svgpathelement.cpp | nokotan/siv6 | 7df183550a6c0160ba918d6ad24c3ae48231e26b | [
"MIT"
] | 1 | 2020-05-16T14:13:04.000Z | 2020-05-16T14:13:04.000Z | Siv3D/src/ThirdParty/lunasvg/svgpathelement.cpp | nokotan/siv6 | 7df183550a6c0160ba918d6ad24c3ae48231e26b | [
"MIT"
] | null | null | null | Siv3D/src/ThirdParty/lunasvg/svgpathelement.cpp | nokotan/siv6 | 7df183550a6c0160ba918d6ad24c3ae48231e26b | [
"MIT"
] | null | null | null | #include "svgpathelement.h"
namespace lunasvg {
SVGPathElement::SVGPathElement(SVGDocument *document) :
SVGGeometryElement(ElementIdPath, document),
m_d(DOMPropertyIdD)
{
addToPropertyMap(m_d);
}
Path SVGPathElement::makePath(const RenderState&) const
{
return m_d.property()->value();
}
Rect SVGPathElement::makeBoundingBox(const RenderState&) const
{
const Path& path = m_d.property()->value();
return path.boundingBox();
}
void SVGPathElement::render(RenderContext& context) const
{
if(!m_d.isSpecified())
{
context.skipElement();
return;
}
SVGGeometryElement::render(context);
}
SVGElementImpl* SVGPathElement::clone(SVGDocument* document) const
{
SVGPathElement* e = new SVGPathElement(document);
baseClone(*e);
return e;
}
} // namespace lunasvg
| 19.714286 | 66 | 0.704106 | nokotan |
df0cc0584c20635ed0c1bf551cb33223da674d80 | 30 | cpp | C++ | benchmarks/include/mpl11.min.erb.cpp | ldionne/benchcc | 87cd508b47b39c9da5fb2152ec3f07de62297771 | [
"BSL-1.0"
] | 1 | 2017-10-12T11:54:43.000Z | 2017-10-12T11:54:43.000Z | benchmarks/include/mpl11.min.erb.cpp | ldionne/benchcc | 87cd508b47b39c9da5fb2152ec3f07de62297771 | [
"BSL-1.0"
] | null | null | null | benchmarks/include/mpl11.min.erb.cpp | ldionne/benchcc | 87cd508b47b39c9da5fb2152ec3f07de62297771 | [
"BSL-1.0"
] | null | null | null | #include <boost/mpl11.min.hpp> | 30 | 30 | 0.766667 | ldionne |
df10176a1456f058a91b8d2845d7763e2770a302 | 140 | cpp | C++ | Lab0/Module1.cpp | Eistern/17206-Zulin-Labs | d07f2c942c4ac4522c9eada0fc30eb4a332a3f9f | [
"MIT"
] | null | null | null | Lab0/Module1.cpp | Eistern/17206-Zulin-Labs | d07f2c942c4ac4522c9eada0fc30eb4a332a3f9f | [
"MIT"
] | null | null | null | Lab0/Module1.cpp | Eistern/17206-Zulin-Labs | d07f2c942c4ac4522c9eada0fc30eb4a332a3f9f | [
"MIT"
] | null | null | null | #include "Module1.h"
namespace Module1
{
std::string getMyName()
{
std::string name = "John";
return name;
}
}
| 12.727273 | 34 | 0.542857 | Eistern |
df11c53fdd1dc265f1bd7528a8245261b1dbc2a1 | 8,640 | cpp | C++ | src/backtester/TickGenerator.cpp | paps/Open-Trading | b62f85f391be9975a161713f87aeff0cae0a1e37 | [
"BSD-2-Clause"
] | 23 | 2015-07-24T15:45:36.000Z | 2021-11-23T15:35:33.000Z | src/backtester/TickGenerator.cpp | paps/Open-Trading | b62f85f391be9975a161713f87aeff0cae0a1e37 | [
"BSD-2-Clause"
] | null | null | null | src/backtester/TickGenerator.cpp | paps/Open-Trading | b62f85f391be9975a161713f87aeff0cae0a1e37 | [
"BSD-2-Clause"
] | 21 | 2015-07-12T16:42:01.000Z | 2020-08-23T22:56:50.000Z | // The Open Trading Project - open-trading.org
//
// Copyright (c) 2011 Martin Tapia - martin.tapia@open-trading.org
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//
// 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 <cmath>
#include "TickGenerator.hpp"
#include "core/History.hpp"
#include "core/strategy/Strategy.hpp"
#include "Conf.hpp"
#include "Logger.hpp"
#define CLASS "[Backtester/TickGenerator] "
namespace Backtester
{
TickGenerator::TickGenerator(Core::History const& history, Logger const& logger, Conf const& conf) :
_history(history), _conf(conf), _logger(logger), _barPos(0)
{
this->_historyPos = this->_history.GetFirstBarPosOfPeriod(this->_conf.period);
}
TickGenerator::GenerationResult TickGenerator::GenerateNextTick(Core::Strategy::Strategy const& strategy, std::pair<float, float>& tick, Core::Bar& bar)
{
if (this->_tickBuffer.empty())
{
Core::Bar minuteBar;
Core::History::FetchType fetch = this->_history.FetchBar(minuteBar, this->_historyPos, 1);
if (fetch == Core::History::FetchError)
return NoMoreTicks;
else if (fetch == Core::History::FetchGap)
{
this->_NextBar();
return Interruption;
}
this->_currentBar.time = minuteBar.time;
if (this->_conf.fewerTicks)
this->_GenerateFewerTicks(strategy, minuteBar);
else
this->_GenerateTicks(strategy, minuteBar);
}
float value = this->_tickBuffer.front();
this->_tickBuffer.pop();
GenerationResult ret;
if (this->_currentBar.valid)
{
if (this->_currentBar.h < value)
this->_currentBar.h = value;
if (this->_currentBar.l > value)
this->_currentBar.l = value;
this->_currentBar.c = value;
ret = NormalTick;
}
else
{
this->_currentBar.valid = true;
this->_currentBar.o = value;
this->_currentBar.h = value;
this->_currentBar.l = value;
this->_currentBar.c = value;
ret = NewBarTick;
}
bar = this->_currentBar;
++this->_currentBar.time; // adds 1 second so that the next tick is not a multiple of 60
tick.first = value + strategy.PipsToOffset(this->_conf.spread);
tick.second = value;
if (this->_tickBuffer.empty())
this->_NextBar();
return ret;
}
void TickGenerator::_NextBar()
{
++this->_historyPos;
++this->_barPos;
if (this->_barPos >= this->_conf.period)
{
this->_barPos = 0;
this->_currentBar.valid = false;
}
}
void TickGenerator::_GenerateFewerTicks(Core::Strategy::Strategy const&, Core::Bar const& bar)
{
this->_tickBuffer.push(bar.o);
if (bar.o == bar.c)
{
if (bar.h == bar.l)
return;
else if (bar.l == bar.o)
this->_tickBuffer.push(bar.h);
else if (bar.h == bar.o)
this->_tickBuffer.push(bar.l);
else
{
this->_tickBuffer.push(bar.l);
this->_tickBuffer.push(bar.h);
}
}
else if (bar.l == bar.c && bar.h != bar.o)
this->_tickBuffer.push(bar.h);
else if (bar.h == bar.c && bar.l != bar.o)
this->_tickBuffer.push(bar.l);
else if (bar.o == bar.l)
this->_tickBuffer.push(bar.h);
else if (bar.o == bar.h)
this->_tickBuffer.push(bar.l);
else
{
if (bar.c > bar.o)
{
this->_tickBuffer.push(bar.l);
this->_tickBuffer.push(bar.h);
}
else
{
this->_tickBuffer.push(bar.h);
this->_tickBuffer.push(bar.l);
}
}
this->_tickBuffer.push(bar.c);
}
void TickGenerator::_GenerateTicks(Core::Strategy::Strategy const& strategy, Core::Bar const& bar)
{
this->_tickBuffer.push(bar.o);
if (bar.o == bar.c)
{
if (bar.h == bar.l) // l | h ~
return;
else if (bar.l == bar.o) // l |- h ~
this->_tickBuffer.push(bar.h);
else if (bar.h == bar.o) // l -| h ~
this->_tickBuffer.push(bar.l);
else // l -|- h ~
{
this->_tickBuffer.push(bar.l);
this->_tickBuffer.push(bar.h);
}
}
else if (bar.l == bar.c)
{
if (bar.h == bar.o) // l | | h <
this->_tickBuffer.push(strategy.FloorPrice(bar.c + 0.5 * (bar.o - bar.c)));
else // l | |- h <
this->_tickBuffer.push(bar.h);
}
else if (bar.h == bar.c)
{
if (bar.l == bar.o) // l | | h >
this->_tickBuffer.push(strategy.CeilPrice(bar.o + 0.5 * (bar.c - bar.o)));
else // l -| | h >
this->_tickBuffer.push(bar.l);
}
else if (bar.o == bar.l) // l | |- h >
this->_tickBuffer.push(bar.h);
else if (bar.o == bar.h) // l -| | h <
this->_tickBuffer.push(bar.l);
else
{
float unit = fabs(bar.c - bar.o) > strategy.GetPriceUnit() ? strategy.GetPriceUnit() : 0;
if (bar.c > bar.o) // l -| |- h >
{
this->_tickBuffer.push(strategy.CeilPrice(bar.l + 0.25 * (bar.o - bar.l)));
this->_tickBuffer.push(strategy.CeilPrice(bar.l + 0.5 * (bar.o - bar.l)));
this->_tickBuffer.push(bar.l);
this->_tickBuffer.push(strategy.CeilPrice(bar.l + 0.33 * (bar.h - bar.l)));
this->_tickBuffer.push(strategy.CeilPrice(bar.l + 0.33 * (bar.h - bar.l) - unit));
this->_tickBuffer.push(strategy.CeilPrice(bar.l + 0.66 * (bar.h - bar.l)));
this->_tickBuffer.push(strategy.CeilPrice(bar.l + 0.66 * (bar.h - bar.l) - unit));
this->_tickBuffer.push(bar.h);
this->_tickBuffer.push(strategy.CeilPrice(bar.h - 0.75 * (bar.h - bar.c)));
this->_tickBuffer.push(strategy.CeilPrice(bar.h - 0.5 * (bar.h - bar.c)));
}
else // l -| |- h <
{
this->_tickBuffer.push(strategy.FloorPrice(bar.h - 0.25 * (bar.h - bar.o)));
this->_tickBuffer.push(strategy.FloorPrice(bar.h - 0.5 * (bar.h - bar.o)));
this->_tickBuffer.push(bar.h);
this->_tickBuffer.push(strategy.FloorPrice(bar.l + 0.66 * (bar.h - bar.l)));
this->_tickBuffer.push(strategy.FloorPrice(bar.l + 0.66 * (bar.h - bar.l) + unit));
this->_tickBuffer.push(strategy.FloorPrice(bar.l + 0.33 * (bar.h - bar.l)));
this->_tickBuffer.push(strategy.FloorPrice(bar.l + 0.33 * (bar.h - bar.l) + unit));
this->_tickBuffer.push(bar.l);
this->_tickBuffer.push(strategy.FloorPrice(bar.l + 0.75 * (bar.c - bar.l)));
this->_tickBuffer.push(strategy.FloorPrice(bar.l + 0.5 * (bar.c - bar.l)));
}
}
this->_tickBuffer.push(bar.c);
}
}
| 40 | 156 | 0.544792 | paps |
df1411ccbf54ff4c863292ddc46e2123e034a1cd | 1,114 | cc | C++ | src/114_flatten-binary-tree-to-linked-list.cc | q191201771/yoko_leetcode | a29b163169f409856e9c9808890bcb25ca976f78 | [
"MIT"
] | 2 | 2018-07-28T06:11:30.000Z | 2019-01-15T15:16:54.000Z | src/114_flatten-binary-tree-to-linked-list.cc | q191201771/yoko_leetcode | a29b163169f409856e9c9808890bcb25ca976f78 | [
"MIT"
] | null | null | null | src/114_flatten-binary-tree-to-linked-list.cc | q191201771/yoko_leetcode | a29b163169f409856e9c9808890bcb25ca976f78 | [
"MIT"
] | null | null | null | // Given a binary tree, flatten it to a linked list in-place.
//
// For example, given the following tree:
//
// 1
// / \
// 2 5
// / \ \
// 3 4 6
// The flattened tree should look like:
//
// 1
// \
// 2
// \
// 3
// \
// 4
// \
// 5
// \
// 6
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
void help(TreeNode *root, TreeNode **ret, TreeNode **prev) {
if (!root) { return; }
if (*prev == NULL) { *prev = new TreeNode(root->val); *ret = *prev; }
else { (*prev)->right = new TreeNode(root->val); *prev = (*prev)->right; }
help(root->left, ret, prev);
help(root->right, ret, prev);
}
public:
void flatten(TreeNode* root) {
if (!root) { return; }
TreeNode *ret = NULL;
TreeNode *prev = NULL;
help(root, &ret, &prev);
root->val = ret->val;
root->left = NULL;
root->right = ret->right;
}
};
| 19.206897 | 78 | 0.493716 | q191201771 |
df16cfbc43d6c923158fd70b144f1c999c74c0d9 | 4,039 | cpp | C++ | Gems/Atom/Tools/AtomToolsFramework/Code/Tests/AtomToolsFrameworkTest.cpp | TheKeaver/o3de | 3791149c6bb18d007ee375f592bdd031871f793d | [
"Apache-2.0",
"MIT"
] | 1 | 2021-08-11T02:20:46.000Z | 2021-08-11T02:20:46.000Z | Gems/Atom/Tools/AtomToolsFramework/Code/Tests/AtomToolsFrameworkTest.cpp | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | null | null | null | Gems/Atom/Tools/AtomToolsFramework/Code/Tests/AtomToolsFrameworkTest.cpp | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | null | null | null | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <AzTest/AzTest.h>
#include <Atom/Utils/TestUtils/AssetSystemStub.h>
#include <AtomToolsFramework/Util/MaterialPropertyUtil.h>
namespace UnitTest
{
class AtomToolsFrameworkTest : public ::testing::Test
{
protected:
void SetUp() override
{
if (!AZ::AllocatorInstance<AZ::SystemAllocator>::IsReady())
{
AZ::AllocatorInstance<AZ::SystemAllocator>::Create(AZ::SystemAllocator::Descriptor());
}
m_assetSystemStub.Activate();
RegisterSourceAsset("objects/upgrades/materials/supercondor.material");
RegisterSourceAsset("materials/condor.material");
RegisterSourceAsset("materials/talisman.material");
RegisterSourceAsset("materials/city.material");
RegisterSourceAsset("materials/totem.material");
RegisterSourceAsset("textures/orange.png");
RegisterSourceAsset("textures/red.png");
RegisterSourceAsset("textures/gold.png");
RegisterSourceAsset("textures/fuzz.png");
}
void TearDown() override
{
m_assetSystemStub.Deactivate();
if (AZ::AllocatorInstance<AZ::SystemAllocator>::IsReady())
{
AZ::AllocatorInstance<AZ::SystemAllocator>::Destroy();
}
}
void RegisterSourceAsset(const AZStd::string& path)
{
const AZ::IO::BasicPath assetRootPath = AZ::IO::PathView(m_assetRoot).LexicallyNormal();
const AZ::IO::BasicPath normalizedPath = AZ::IO::BasicPath(assetRootPath).Append(path).LexicallyNormal();
AZ::Data::AssetInfo assetInfo = {};
assetInfo.m_assetId = AZ::Uuid::CreateRandom();
assetInfo.m_relativePath = normalizedPath.LexicallyRelative(assetRootPath).StringAsPosix();
m_assetSystemStub.RegisterSourceInfo(normalizedPath.StringAsPosix().c_str(), assetInfo, assetRootPath.StringAsPosix().c_str());
}
static constexpr const char* m_assetRoot = "d:/project/assets/";
AssetSystemStub m_assetSystemStub;
};
TEST_F(AtomToolsFrameworkTest, GetExteralReferencePath_Succeeds)
{
ASSERT_EQ(AtomToolsFramework::GetExteralReferencePath("", "", 2), "");
ASSERT_EQ(AtomToolsFramework::GetExteralReferencePath("d:/project/assets/materials/condor.material", "", 2), "");
ASSERT_EQ(AtomToolsFramework::GetExteralReferencePath("d:/project/assets/materials/talisman.material", "", 2), "");
ASSERT_EQ(AtomToolsFramework::GetExteralReferencePath("d:/project/assets/materials/talisman.material", "d:/project/assets/textures/gold.png", 2), "../textures/gold.png");
ASSERT_EQ(AtomToolsFramework::GetExteralReferencePath("d:/project/assets/materials/talisman.material", "d:/project/assets/textures/gold.png", 0), "textures/gold.png");
ASSERT_EQ(AtomToolsFramework::GetExteralReferencePath("d:/project/assets/objects/upgrades/materials/supercondor.material", "d:/project/assets/materials/condor.material", 3), "../../../materials/condor.material");
ASSERT_EQ(AtomToolsFramework::GetExteralReferencePath("d:/project/assets/objects/upgrades/materials/supercondor.material", "d:/project/assets/materials/condor.material", 2), "materials/condor.material");
ASSERT_EQ(AtomToolsFramework::GetExteralReferencePath("d:/project/assets/objects/upgrades/materials/supercondor.material", "d:/project/assets/materials/condor.material", 1), "materials/condor.material");
ASSERT_EQ(AtomToolsFramework::GetExteralReferencePath("d:/project/assets/objects/upgrades/materials/supercondor.material", "d:/project/assets/materials/condor.material", 0), "materials/condor.material");
}
AZ_UNIT_TEST_HOOK(DEFAULT_UNIT_TEST_ENV);
} // namespace UnitTest
| 51.782051 | 220 | 0.694726 | TheKeaver |
df17e6d56363be3e65b1829713daf59c85f5d89c | 729 | cpp | C++ | LeetCode/687.Longest_Univalue_Path.cpp | w181496/OJ | 67d1d32770376865eba8a9dd1767e97dae68989a | [
"MIT"
] | 9 | 2017-10-08T16:22:03.000Z | 2021-08-20T09:32:17.000Z | LeetCode/687.Longest_Univalue_Path.cpp | w181496/OJ | 67d1d32770376865eba8a9dd1767e97dae68989a | [
"MIT"
] | null | null | null | LeetCode/687.Longest_Univalue_Path.cpp | w181496/OJ | 67d1d32770376865eba8a9dd1767e97dae68989a | [
"MIT"
] | 2 | 2018-01-15T16:35:44.000Z | 2019-03-21T18:30:04.000Z | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int longestUnivaluePath(TreeNode* root) {
int ans = 0;
find(root, ans);
return max(ans - 1, 0);
}
int find(TreeNode *root, int &ans) {
if(root == NULL) return 0;
int l = 0, r = 0;
l = find(root->left, ans);
r = find(root->right, ans);
if(root->left && root->left->val != root->val) l = 0;
if(root->right && root->right->val != root->val) r = 0;
ans = max(ans, l + r + 1);
return max(l, r) + 1;
}
};
| 25.137931 | 63 | 0.492455 | w181496 |
df1fd94d698e594f2648c6836684b55cfa8e3785 | 3,506 | cc | C++ | src/app/main.cc | JeanTracker/qt-qml-project-template-with-ci | 022992af4bd4e4df006a3125fe124a56a25c23a5 | [
"BSD-2-Clause"
] | null | null | null | src/app/main.cc | JeanTracker/qt-qml-project-template-with-ci | 022992af4bd4e4df006a3125fe124a56a25c23a5 | [
"BSD-2-Clause"
] | null | null | null | src/app/main.cc | JeanTracker/qt-qml-project-template-with-ci | 022992af4bd4e4df006a3125fe124a56a25c23a5 | [
"BSD-2-Clause"
] | null | null | null | //
// Copyright (c) 2020, 219 Design, LLC
// See LICENSE.txt
//
// https://www.219design.com
// Software | Electrical | Mechanical | Product Design
//
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickStyle>
#include "autogenerated/version.h" // USE THIS INCLUDE SPARINGLY. IT CAN TRIGGER REBUILDS.
#include "src/app/view_model_collection.h"
#include "src/lib_app/cli_options.h"
#include "src/lib_app/ios/ios_log_redirect.h"
#include "src/minutil/logger.h" // <--- included for DEMONSTRATION. Prefer Qt logging where available.
#include "src/util/am_i_inside_debugger.h"
#include "util-assert.h"
int main( int argc, char* argv[] )
{
project::SetAppVersionStringForLogging( project::GIT_HASH_WHEN_BUILT );
project::WhenOnIos_RerouteStdoutStderrToDeviceFilesystem();
qSetMessagePattern( QString( "%{time yyyy-MM-dd hh:mm:ss.zzz} [QT-%{type}][v-" ) + project::GIT_HASH_WHEN_BUILT
+ "][thr:%{threadid}]%{if-category}%{category}: %{endif}%{file}(%{line}): %{message}" );
if( !project::OkToEnableAssertions() )
{
// In production mobile apps, disable our assertions
Suppress_All_Assertions();
}
// project::log used for DEMONSTRATION. Prefer Qt logging where available.
project::log( "main.cc starting now %d", static_cast<int>( __LINE__ ) );
QGuiApplication app( argc, argv ); // ... note next line...
// QQuickStyle::setStyle( "Fusion" ); // <-- call setStyle after creating app (if style is needed)
// ViewModels must OUTLIVE the qml engine, so create them first:
project::ViewModelCollection vms( app, false /*cliArgsOnlyParseThenSkipErrorHandling*/ );
// For antialiasing: https://stackoverflow.com/a/49576756/10278
// QSurfaceFormat format;
// format.setSamples( 8 );
// LEAVING THIS HERE AS A "WARNING". This gave us good antialiasing on
// the QML ShapePath that it was intended to help. It DID help where we
// wanted it to help. But it also caused weird tiny lines to intermittently
// appear around some of our SVG icons.
// So now we use a different, QML-only tactic in the ShapePath.
// QSurfaceFormat::setDefaultFormat( format );
//
// Instead, do this in the QML of your ShapePath:
// layer.enabled: true // Without this, the edges look "jaggy" and pixelated
// layer.samples: 4 // Without this, the edges look "jaggy" and pixelated
// Created after vms, so that we avoid null vm qml warnings upon vm dtors
QQmlApplicationEngine engine;
vms.ExportContextPropertiesToQml( &engine );
engine.addImportPath( "qrc:///" ); // needed for finding qml in our plugins
engine.load( QUrl( QStringLiteral( "qrc:///qml/main.qml" ) ) );
if( vms.Options().ShowColorPalette() )
{
// This second app window will cause the FASSERT about root objects
// count to trigger below, but just choose 'c' to continue beyond the
// failed assert prompt. (It's ok to keep the assertion as-is, because
// this color palette option is not meant be used in production.)
engine.load( QUrl( QStringLiteral( "qrc:///qml/viewColorPalette.qml" ) ) );
}
const QList<QObject*> objs = engine.rootObjects();
FASSERT( objs.size() == 1, "if the app starts creating more than one root window, "
"please reevaluate the logic of SetRootObject and our global event filter" );
vms.SetRootObject( objs[ 0 ] );
return app.exec();
}
| 43.283951 | 115 | 0.67741 | JeanTracker |
b3001cd9dca2fec92853765f70b6a3c3d674c66e | 3,538 | cpp | C++ | modules/io/bitcount_benchmark.cpp | spiralgenetics/biograph | 33c78278ce673e885f38435384f9578bfbf9cdb8 | [
"BSD-2-Clause"
] | 16 | 2021-07-14T23:32:31.000Z | 2022-03-24T16:25:15.000Z | modules/io/bitcount_benchmark.cpp | spiralgenetics/biograph | 33c78278ce673e885f38435384f9578bfbf9cdb8 | [
"BSD-2-Clause"
] | 9 | 2021-07-20T20:39:47.000Z | 2021-09-16T20:57:59.000Z | modules/io/bitcount_benchmark.cpp | spiralgenetics/biograph | 33c78278ce673e885f38435384f9578bfbf9cdb8 | [
"BSD-2-Clause"
] | 9 | 2021-07-15T19:38:35.000Z | 2022-01-31T19:24:56.000Z | #include "modules/io/bitcount.h"
#include "benchmark/benchmark.h"
#include <iomanip>
#include <iostream>
#include <random>
namespace {
const size_t nbits = 16ULL * 1024 * 1024 * 1024;
size_t bufsize = 0;
char* bcbuf = nullptr;
std::unique_ptr<bitcount> bc;
size_t seed = time(0);
std::mt19937_64 random_source(seed);
void init_bc() {
if (bcbuf) {
return;
}
bufsize = bitcount::compute_size(nbits);
bcbuf = new char[bufsize];
uint64_t* bcbuf_64 = reinterpret_cast<uint64_t*>(bcbuf);
std::cerr << "Populating bitcount with random data, seed " << seed << "\n";
CHECK_EQ(0, random_source.min());
CHECK_EQ(std::numeric_limits<uint64_t>::max(), random_source.max());
size_t tot_uint64s = bufsize / sizeof(uint64_t);
for (size_t i = 0; i < tot_uint64s; ++i) {
if (!(i & ((1 << 20) - 1))) {
std::cerr << " " << i;
}
bcbuf_64[i] = random_source();
// Have some sections be sparser than others.
if (i < (tot_uint64s/2)) {
// Densify first half.
size_t shifted = i >> 10;
while (shifted) {
bcbuf_64[i] |= random_source();
shifted >>= 10;
}
} else {
// Sparsify second half.
size_t shifted = (tot_uint64s - i) >> 10;
while (shifted) {
bcbuf_64[i] &= random_source();
shifted >>= 10;
}
}
}
bc.reset(new bitcount(bcbuf, nbits));
std::cerr << "\nFinalizing...\n";
bc->finalize();
std::cerr << bc->total_bits() << " total bits present out of " << bc->size()
<< ": " << std::fixed << std::setw(6) << std::setprecision(2)
<< bc->total_bits() * 100. / bc->size() << "%.\n";
std::cerr << "Done\n";
}
} // namespace
static void BM_bitcount_count(benchmark::State& state) {
init_bc();
bitcount bc(bcbuf, nbits);
std::uniform_int_distribution<size_t> random_pos(0, nbits - 1);
size_t pos = random_pos(random_source);
const size_t stride = random_pos(random_source);
while (state.KeepRunning()) {
size_t count = bc.count(pos);
pos += stride ^ count;
pos %= nbits;
}
}
BENCHMARK(BM_bitcount_count);
static void BM_bitcount_find_count(benchmark::State& state) {
init_bc();
size_t total_bits_set = bc->total_bits();
std::uniform_int_distribution<size_t> random_pos(0, total_bits_set - 1);
size_t pos = random_pos(random_source);
const size_t stride = random_pos(random_source);
while (state.KeepRunning()) {
size_t count = bc->find_count(pos);
pos += stride ^ count;
pos %= total_bits_set;
}
}
BENCHMARK(BM_bitcount_find_count);
static void BM_bitcount_find_count_with_index(benchmark::State& state) {
init_bc();
bitcount bc(bcbuf, nbits);
bc.make_find_count_index();
size_t total_bits_set = bc.total_bits();
std::uniform_int_distribution<size_t> random_pos(0, total_bits_set - 1);
size_t pos = random_pos(random_source);
const size_t stride = random_pos(random_source);
while (state.KeepRunning()) {
size_t count = bc.find_count(pos);
pos += stride ^ count;
pos %= total_bits_set;
}
}
BENCHMARK(BM_bitcount_find_count_with_index);
static void BM_bitcount_make_find_count_index(benchmark::State& state) {
init_bc();
bitcount bc(bcbuf, nbits);
while (state.KeepRunning()) {
bc.make_find_count_index();
}
}
BENCHMARK(BM_bitcount_make_find_count_index);
static void BM_bitcount_finalize(benchmark::State& state) {
init_bc();
bitcount bc(bcbuf, nbits);
while (state.KeepRunning()) {
bc.finalize();
}
}
BENCHMARK(BM_bitcount_finalize);
BENCHMARK_MAIN();
| 23.905405 | 78 | 0.652063 | spiralgenetics |
b300462d0cc129dc0951fdd26952b5ad963cc218 | 712 | cpp | C++ | UVa 13038 - Directed Forest/sample/13038 - Directed Forest.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | 1 | 2020-11-24T03:17:21.000Z | 2020-11-24T03:17:21.000Z | UVa 13038 - Directed Forest/sample/13038 - Directed Forest.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | null | null | null | UVa 13038 - Directed Forest/sample/13038 - Directed Forest.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | 1 | 2021-04-11T16:22:31.000Z | 2021-04-11T16:22:31.000Z | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 131072;
vector<int> g[MAXN];
int indeg[MAXN];
int dfs(int u) {
int ret = 1;
for (auto &v : g[u])
ret = max(ret, dfs(v)+1);
return ret;
}
int solve(int root, int N) {
return dfs(root);
}
int main() {
int testcase, cases = 0;
int N, M, u, v;
scanf("%d", &testcase);
while (testcase--) {
scanf("%d %d", &N, &M);
for (int i = 0; i <= N; i++)
g[i].clear(), indeg[i] = 0;
for (int i = 0; i < M; i++) {
scanf("%d %d", &u, &v);
g[u].push_back(v), indeg[v]++;
}
int ret = 1;
for (int i = 1; i <= N; i++) {
if (indeg[i] == 0)
ret = max(solve(i, N), ret);
}
printf("Case %d: %d\n", ++cases, ret);
}
return 0;
}
| 18.25641 | 40 | 0.505618 | tadvi |
b3018ed8c9a08a6736a0df27939557770c4f67bb | 1,161 | cc | C++ | samples/06-looping/do_while_loop/main.cc | brockus/the_cpp_tutorial | 87d73fa7111dd6fe22299b01edc5663bfd192782 | [
"Apache-2.0"
] | null | null | null | samples/06-looping/do_while_loop/main.cc | brockus/the_cpp_tutorial | 87d73fa7111dd6fe22299b01edc5663bfd192782 | [
"Apache-2.0"
] | null | null | null | samples/06-looping/do_while_loop/main.cc | brockus/the_cpp_tutorial | 87d73fa7111dd6fe22299b01edc5663bfd192782 | [
"Apache-2.0"
] | null | null | null | //
// author: Michael Brockus
// gmail : <michaelbrockus@gmail.com>
//
#include <iostream>
#include <cstdlib>
int main()
{
//
// To run a block of code repeatedly in a predetermined
// time, you use the for loop statement. In cases you
// want to run a block of code repeatedly based on a
// given condition with a check at the end of each
// iteration, you use the do while loop statement.
//
// The do while loop statement consists of execution
// statements and a Boolean condition. First, the execute
// statements are executed, and then the condition is
// checked. If the condition evaluates to true, the execute
// statements are executed again until the condition evaluates
// to false.
//
// Unlike the while loop, the execute statements inside the
// do while loop execute at least one time because the condition
// is checked at the end of each iteration.
//
int x = 5;
int i = 0;
//
// using do while loop statement
//
do
{
i++;
std::cout << i << std::endl;
} while (i < x);
return EXIT_SUCCESS;
} // end of function main
| 27.642857 | 68 | 0.63652 | brockus |
b305adef83ef8dcb74344a6b7039844e1bc9def9 | 1,778 | cpp | C++ | CastleDoctrine/gameSource/FastBoxBlurFilter.cpp | PhilipLudington/CastleDoctrine | 443f2b6b0215a6d71515c8887c99b4322965622e | [
"Unlicense"
] | 1 | 2020-01-16T00:07:11.000Z | 2020-01-16T00:07:11.000Z | CastleDoctrine/gameSource/FastBoxBlurFilter.cpp | PhilipLudington/CastleDoctrine | 443f2b6b0215a6d71515c8887c99b4322965622e | [
"Unlicense"
] | null | null | null | CastleDoctrine/gameSource/FastBoxBlurFilter.cpp | PhilipLudington/CastleDoctrine | 443f2b6b0215a6d71515c8887c99b4322965622e | [
"Unlicense"
] | 2 | 2019-09-17T12:08:20.000Z | 2020-09-26T00:54:48.000Z | #include "FastBoxBlurFilter.h"
#include <string.h>
FastBoxBlurFilter::FastBoxBlurFilter() {
}
void FastBoxBlurFilter::applySubRegion( unsigned char *inChannel,
int *inTouchPixelIndices,
int inNumTouchPixels,
int inWidth, int inHeight ) {
// use pointer tricks to walk through neighbor box of each pixel
// four "corners" around box in accumulation table used to compute
// box total
// these are offsets to current accumulation pointer
int cornerOffsetA = inWidth + 1;
int cornerOffsetB = -inWidth + 1;
int cornerOffsetC = inWidth - 1;
int cornerOffsetD = -inWidth - 1;
// sides around box
int sideOffsetA = inWidth;
int sideOffsetB = -inWidth;
int sideOffsetC = 1;
int sideOffsetD = -1;
unsigned char *sourceData = new unsigned char[ inWidth * inHeight ];
memcpy( sourceData, inChannel, inWidth * inHeight );
// sum boxes right into passed-in channel
for( int i=0; i<inNumTouchPixels; i++ ) {
int pixelIndex = inTouchPixelIndices[ i ];
unsigned char *sourcePointer = &( sourceData[ pixelIndex ] );
inChannel[ pixelIndex ] =
( sourcePointer[ 0 ] +
sourcePointer[ cornerOffsetA ] +
sourcePointer[ cornerOffsetB ] +
sourcePointer[ cornerOffsetC ] +
sourcePointer[ cornerOffsetD ] +
sourcePointer[ sideOffsetA ] +
sourcePointer[ sideOffsetB ] +
sourcePointer[ sideOffsetC ] +
sourcePointer[ sideOffsetD ]
) / 9;
}
delete [] sourceData;
return;
}
| 24.694444 | 72 | 0.568616 | PhilipLudington |
b30a3afe090e14054c69844fa0888371e872001c | 844 | cpp | C++ | Dynamic Programming/0-1 Knapsack/(6)CountOfSubsetDiff.cpp | jaydulera/data-structure-and-algorithms | abc2d67871add6f314888a72215ff3a2da2dc6e1 | [
"Apache-2.0"
] | 53 | 2020-09-26T19:44:33.000Z | 2021-09-30T20:38:52.000Z | Dynamic Programming/0-1 Knapsack/(6)CountOfSubsetDiff.cpp | jaydulera/data-structure-and-algorithms | abc2d67871add6f314888a72215ff3a2da2dc6e1 | [
"Apache-2.0"
] | 197 | 2020-08-25T18:13:56.000Z | 2021-06-19T07:26:19.000Z | Dynamic Programming/0-1 Knapsack/(6)CountOfSubsetDiff.cpp | jaydulera/data-structure-and-algorithms | abc2d67871add6f314888a72215ff3a2da2dc6e1 | [
"Apache-2.0"
] | 204 | 2020-08-24T09:21:02.000Z | 2022-02-13T06:13:42.000Z | #include<bits/stdc++.h>
using namespace std;
int t[100][100];
// LeetCode Target sum ques
int CountSubsetGivenSum(int *wt, int Sum, int n) {
for (int i = 0; i <= Sum; i++) t[0][i] = 0;
for (int i = 0; i <= n; i++) t[i][0] = 1; //empty set
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= Sum; j++) {
if (wt[i - 1] <= j) {
t[i][j] = (t[i - 1][j - wt[i - 1]] + t[i - 1][j]);
}
else {
t[i][j] = t[i - 1][j];
}
}
}
return t[n][Sum];
}
int main() {
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int wt[] = {1, 2, 4};
int diff = 3;
int range = 0;
int n = sizeof(wt) / sizeof(int);
for (int i = 0; i < n; i++) range += wt[i];
int S1 = (diff + range) / 2; // diff+range should be even else ans=0
cout << CountSubsetGivenSum(wt, S1, n) << endl;
}
| 18.347826 | 69 | 0.50237 | jaydulera |
b30d10103431820beadc98732b0b43a20758dbbd | 3,475 | cpp | C++ | Source/Common/Src/Memory/RangeAllocator.cpp | vasumahesh1/azura | 80aa23e2fb498e6288484bc49b0d5b8889db6ebb | [
"MIT"
] | 12 | 2019-01-08T23:10:37.000Z | 2021-06-04T09:48:42.000Z | Source/Common/Src/Memory/RangeAllocator.cpp | vasumahesh1/azura | 80aa23e2fb498e6288484bc49b0d5b8889db6ebb | [
"MIT"
] | 38 | 2017-04-05T00:27:24.000Z | 2018-12-25T08:34:04.000Z | Source/Common/Src/Memory/RangeAllocator.cpp | vasumahesh1/azura | 80aa23e2fb498e6288484bc49b0d5b8889db6ebb | [
"MIT"
] | 4 | 2019-03-27T10:07:32.000Z | 2021-07-15T03:22:27.000Z | #include "Memory/RangeAllocator.h"
#include "Memory/MemoryBuffer.h"
namespace Azura {
namespace Memory {
namespace {
/**
* \brief Finds the next largest Aligned multiple according to the input size
* \param size Size of Bytes to Allocate
* \param alignment Alignment of the data to allocate
* \return Next greatest alignment multiple that can fit `size` bytes
*/
U32 AlignAhead(U32 size, U32 alignment) {
return (size + (alignment - 1)) & ~(alignment - 1);
}
} // namespace
RangeAllocator::RangeAllocator(MemoryBuffer& buffer, U32 size)
: Allocator(buffer.Allocate(size), size), m_sourceBuffer(buffer) {}
RangeAllocator::~RangeAllocator() {
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
m_sourceBuffer.Deallocate(reinterpret_cast<void*>(BasePtr()));
}
void* RangeAllocator::Allocate(U32 size, U32 alignment) {
auto finalRangeItr = m_freeRanges.end();
U32 finalOffsetInRange = 0;
const U32 expectedSize = AlignAhead(size, alignment);
for (auto itr = m_freeRanges.begin(); itr != m_freeRanges.end(); ++itr) {
const auto& range = *itr;
const AddressPtr rangeBase = BasePtr() + range.m_offset;
const U32 mask = alignment - 1;
const UPTR misalignment = (rangeBase & mask);
// TODO(vasumahesh1): Check Logic
const U32 requiredSize = U32(misalignment) + expectedSize;
if (range.m_size >= requiredSize) {
finalRangeItr = itr;
finalOffsetInRange = U32(misalignment);
break;
}
}
if (finalRangeItr == m_freeRanges.end()) {
// TODO(vasumahesh1): Must GC
return nullptr;
}
// Take Copy
const MemoryRange targetRange = *finalRangeItr;
// Remove Free Range
m_freeRanges.erase(finalRangeItr);
// TODO(vasumahesh1): Should Sort or Place as sorted?
if (finalOffsetInRange > 0) {
m_freeRanges.emplace_back(targetRange.m_offset, finalOffsetInRange);
}
const U32 remainingRangeSize = targetRange.m_size - finalOffsetInRange - expectedSize;
if (remainingRangeSize > 0) {
m_freeRanges.emplace_back(targetRange.m_offset + finalOffsetInRange + expectedSize, remainingRangeSize);
}
const auto targetOffset = targetRange.m_offset + finalOffsetInRange;
m_occupiedRanges.emplace_back(targetOffset, expectedSize);
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
return reinterpret_cast<void*>(static_cast<AddressPtr>(BasePtr() + targetOffset));
}
void RangeAllocator::Deallocate(void* address) {
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
const auto addressPtr = reinterpret_cast<AddressPtr>(address);
auto finalRangeItr = m_occupiedRanges.end();
for (auto itr = m_occupiedRanges.begin(); itr != m_occupiedRanges.end(); ++itr) {
const auto& range = *itr;
const AddressPtr rangeBase = BasePtr() + range.m_offset;
if (rangeBase == addressPtr) {
finalRangeItr = itr;
break;
}
}
if (finalRangeItr == m_occupiedRanges.end()) {
// TODO(vasumahesh1): Must Throw here?
return;
}
// Take Copy
const MemoryRange targetRange = *finalRangeItr;
// Remove Free Range
m_occupiedRanges.erase(finalRangeItr);
// Release to free ranges
m_freeRanges.emplace_back(targetRange.m_offset, targetRange.m_size);
// TODO(vasumahesh1): Should Amalgamate Free Ranges?
}
} // namespace Memory
} // namespace Azura
| 30.752212 | 109 | 0.688058 | vasumahesh1 |
b30da676a7caee2ef266513e36e81e6522c5994f | 3,909 | hpp | C++ | pybnesian/learning/scores/scores.hpp | vishalbelsare/PyBNesian | 0190cd4cf6d133746741e2750004ccf0a9061fbd | [
"MIT"
] | 8 | 2021-06-22T19:21:12.000Z | 2022-03-26T13:08:05.000Z | pybnesian/learning/scores/scores.hpp | vishalbelsare/PyBNesian | 0190cd4cf6d133746741e2750004ccf0a9061fbd | [
"MIT"
] | null | null | null | pybnesian/learning/scores/scores.hpp | vishalbelsare/PyBNesian | 0190cd4cf6d133746741e2750004ccf0a9061fbd | [
"MIT"
] | 3 | 2021-08-20T13:44:46.000Z | 2022-03-27T02:57:02.000Z | #ifndef PYBNESIAN_LEARNING_SCORES_SCORES_HPP
#define PYBNESIAN_LEARNING_SCORES_SCORES_HPP
#include <models/GaussianNetwork.hpp>
#include <models/SemiparametricBN.hpp>
#include <dataset/dynamic_dataset.hpp>
using dataset::DynamicDataFrame, dataset::DynamicAdaptator;
using models::BayesianNetworkBase, models::GaussianNetwork, models::SemiparametricBN;
using models::ConditionalBayesianNetworkBase;
namespace learning::scores {
class Score {
public:
virtual ~Score() {}
virtual double score(const BayesianNetworkBase& model) const {
double s = 0;
for (const auto& node : model.nodes()) {
s += local_score(model, node);
}
return s;
}
virtual double local_score(const BayesianNetworkBase& model, const std::string& variable) const {
auto parents = model.parents(variable);
return local_score(model, variable, parents);
}
virtual double local_score(const BayesianNetworkBase& model,
const std::string& variable,
const std::vector<std::string>& parents) const = 0;
virtual double local_score(const BayesianNetworkBase& model,
const std::shared_ptr<FactorType>& node_type,
const std::string& variable,
const std::vector<std::string>& parents) const = 0;
virtual std::string ToString() const = 0;
virtual bool has_variables(const std::string& name) const = 0;
virtual bool has_variables(const std::vector<std::string>& cols) const = 0;
virtual bool compatible_bn(const BayesianNetworkBase& model) const = 0;
virtual bool compatible_bn(const ConditionalBayesianNetworkBase& model) const = 0;
virtual DataFrame data() const = 0;
};
class ValidatedScore : public Score {
public:
virtual ~ValidatedScore() {}
virtual double vscore(const BayesianNetworkBase& model) const {
double s = 0;
for (const auto& node : model.nodes()) {
s += vlocal_score(model, node);
}
return s;
}
virtual double vlocal_score(const BayesianNetworkBase& model, const std::string& variable) const {
auto parents = model.parents(variable);
return vlocal_score(model, variable, parents);
}
virtual double vlocal_score(const BayesianNetworkBase& model,
const std::string& variable,
const std::vector<std::string>& parents) const = 0;
virtual double vlocal_score(const BayesianNetworkBase&,
const std::shared_ptr<FactorType>& variable_type,
const std::string& variable,
const std::vector<std::string>& parents) const = 0;
};
class DynamicScore {
public:
virtual ~DynamicScore() {}
virtual Score& static_score() = 0;
virtual Score& transition_score() = 0;
virtual bool has_variables(const std::string& name) const = 0;
virtual bool has_variables(const std::vector<std::string>& cols) const = 0;
};
template <typename BaseScore>
class DynamicScoreAdaptator : public DynamicScore, public DynamicAdaptator<BaseScore> {
public:
template <typename... Args>
DynamicScoreAdaptator(const DynamicDataFrame& df, const Args&... args) : DynamicAdaptator<BaseScore>(df, args...) {}
Score& static_score() override { return this->static_element(); }
Score& transition_score() override { return this->transition_element(); }
bool has_variables(const std::string& name) const override {
return DynamicAdaptator<BaseScore>::has_variables(name);
}
bool has_variables(const std::vector<std::string>& cols) const override {
return DynamicAdaptator<BaseScore>::has_variables(cols);
}
};
} // namespace learning::scores
#endif // PYBNESIAN_LEARNING_SCORES_SCORES_HPP
| 36.877358 | 120 | 0.658736 | vishalbelsare |
b30ed7b2523b1e1d820217fed82ab8f66189698e | 363 | cpp | C++ | 09_lambda/09_07_generic_lambda_capture_expressions/09_07_00_generic_lambda_capture_expressions.cpp | pAbogn/cpp_courses | 6ffa7da5cc440af3327139a38cfdefcfaae1ebed | [
"MIT"
] | 13 | 2020-09-01T14:57:21.000Z | 2021-11-24T06:00:26.000Z | 09_lambda/09_07_generic_lambda_capture_expressions/09_07_00_generic_lambda_capture_expressions.cpp | pAbogn/cpp_courses | 6ffa7da5cc440af3327139a38cfdefcfaae1ebed | [
"MIT"
] | 5 | 2020-06-11T14:13:00.000Z | 2021-07-14T05:27:53.000Z | 09_lambda/09_07_generic_lambda_capture_expressions/09_07_00_generic_lambda_capture_expressions.cpp | pAbogn/cpp_courses | 6ffa7da5cc440af3327139a38cfdefcfaae1ebed | [
"MIT"
] | 10 | 2021-03-22T07:54:36.000Z | 2021-09-15T04:03:32.000Z | // Generic lambda
// Capture expressions
#include <iostream>
#include <vector>
class move_only
{
public:
move_only() = default;
move_only(move_only&& other) = default;
};
int main() {
[](auto x){};
move_only mo;
[mo](){}(); // how to fix
int a{};
int b{};
// capture sum
// type of sum
// return back to example 6
}
| 12.964286 | 43 | 0.564738 | pAbogn |
b30ffaede353aba08afbb5b713d9f296fd70fce9 | 2,175 | cxx | C++ | smtk/attribute/ComponentItemDefinition.cxx | jcfr/SMTK | 0069ea37f8f71a440b8f10a157b84a56ca004551 | [
"BSD-3-Clause-Clear"
] | 40 | 2015-02-21T19:55:54.000Z | 2022-01-06T13:13:05.000Z | smtk/attribute/ComponentItemDefinition.cxx | jcfr/SMTK | 0069ea37f8f71a440b8f10a157b84a56ca004551 | [
"BSD-3-Clause-Clear"
] | 127 | 2015-01-15T20:55:45.000Z | 2021-08-19T17:34:15.000Z | smtk/attribute/ComponentItemDefinition.cxx | jcfr/SMTK | 0069ea37f8f71a440b8f10a157b84a56ca004551 | [
"BSD-3-Clause-Clear"
] | 27 | 2015-03-04T14:17:51.000Z | 2021-12-23T01:05:42.000Z | //=========================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
//
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//=========================================================================
#include "smtk/attribute/ComponentItemDefinition.h"
#include "smtk/attribute/Attribute.h"
#include "smtk/attribute/ComponentItem.h"
#include "smtk/resource/Container.h"
#include "smtk/resource/Manager.h"
#include "smtk/resource/Metadata.h"
#include "smtk/common/UUID.h"
#include <cassert>
using namespace smtk::attribute;
/// Construct an item definition given a name. Names should be unique and non-empty.
ComponentItemDefinition::ComponentItemDefinition(const std::string& sname)
: Superclass(sname)
{
setOnlyResources(false);
}
/// Destructor.
ComponentItemDefinition::~ComponentItemDefinition() = default;
/// Return the type of storage used by items defined by this class.
Item::Type ComponentItemDefinition::type() const
{
return Item::ComponentType;
}
bool ComponentItemDefinition::isValueValid(smtk::resource::ConstPersistentObjectPtr obj) const
{
const auto* comp = dynamic_cast<const smtk::resource::Component*>(obj.get());
if (comp == nullptr)
{
return false;
}
return this->checkComponent(comp);
}
smtk::attribute::ItemPtr ComponentItemDefinition::buildItem(
Attribute* owningAttribute,
int itemPosition) const
{
return smtk::attribute::ItemPtr(new ComponentItem(owningAttribute, itemPosition));
}
smtk::attribute::ItemPtr
ComponentItemDefinition::buildItem(Item* owningItem, int itemPosition, int subGroupPosition) const
{
return smtk::attribute::ItemPtr(new ComponentItem(owningItem, itemPosition, subGroupPosition));
}
smtk::attribute::ItemDefinitionPtr ComponentItemDefinition::createCopy(
smtk::attribute::ItemDefinition::CopyInfo& info) const
{
(void)info;
auto copy = ComponentItemDefinition::New(this->name());
this->copyTo(copy, info);
return copy;
}
| 29.794521 | 98 | 0.711724 | jcfr |
b310c32bc0bc1ed676d6841e2f40f15979ad8fc3 | 1,180 | cpp | C++ | src/main.cpp | int08h/SumoJam-Line-Sensors-Example | b5c5cfd15e7deb5446b3097f9dee31c796685c65 | [
"Unlicense"
] | null | null | null | src/main.cpp | int08h/SumoJam-Line-Sensors-Example | b5c5cfd15e7deb5446b3097f9dee31c796685c65 | [
"Unlicense"
] | null | null | null | src/main.cpp | int08h/SumoJam-Line-Sensors-Example | b5c5cfd15e7deb5446b3097f9dee31c796685c65 | [
"Unlicense"
] | null | null | null | //
// Example how to read the Zumo32U4 line sensors
//
#include <Zumo32U4.h>
namespace {
// Delay between loop()s in milliseconds
constexpr unsigned long DELAY_MS = 100;
// Line sensors interface
Zumo32U4LineSensors lineSensors = Zumo32U4LineSensors{};
// Enable the LCD Screen
Zumo32U4LCD lcd = Zumo32U4LCD{};
// Sensor values will go in this array
// array indicies Left = 0, Center = 1, Right = 2
unsigned int lineSensorValues[3] = {};
// Constants for the accessing sensor values array indicies
enum Position { LEFT = 0, CENTER = 1, RIGHT = 2 };
}
void setup()
{
// Initialize the sensors
lineSensors.initThreeSensors();
// Initialize the LCD display
lcd.init();
}
void loop()
{
// Read in the values
lineSensors.read(lineSensorValues);
// Display the values divided by 10 (to fit on LCD)
// L R
// C
lcd.clear();
// Left sensor
lcd.gotoXY(0, 0);
lcd.print(lineSensorValues[Position::LEFT] / 10);
// Right sensor
lcd.gotoXY(5, 0);
lcd.print(lineSensorValues[Position::RIGHT] / 10);
// Center sensor
lcd.gotoXY(3, 1);
lcd.print(lineSensorValues[Position::CENTER] / 10);
delay(DELAY_MS);
} | 21.454545 | 61 | 0.668644 | int08h |
b314b54045963787d616d62b053d379759f5fb49 | 283 | hpp | C++ | src/tests/functional/plugin/shared/include/single_layer_tests/einsum.hpp | wood-ghost/openvino | 0babf20bd2f4cd3f0be3c025d91ea55526b36fb2 | [
"Apache-2.0"
] | 1,127 | 2018-10-15T14:36:58.000Z | 2020-04-20T09:29:44.000Z | src/tests/functional/plugin/shared/include/single_layer_tests/einsum.hpp | wood-ghost/openvino | 0babf20bd2f4cd3f0be3c025d91ea55526b36fb2 | [
"Apache-2.0"
] | 439 | 2018-10-20T04:40:35.000Z | 2020-04-19T05:56:25.000Z | src/tests/functional/plugin/shared/include/single_layer_tests/einsum.hpp | tuxedcat/openvino | 5939cb1b363ebb56b73c2ad95d8899961a084677 | [
"Apache-2.0"
] | 414 | 2018-10-17T05:53:46.000Z | 2020-04-16T17:29:53.000Z | // Copyright (C) 2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include "shared_test_classes/single_layer/einsum.hpp"
namespace LayerTestsDefinitions {
TEST_P(EinsumLayerTest, CompareWithRefs) {
Run();
}
} // namespace LayerTestsDefinitions
| 17.6875 | 54 | 0.759717 | wood-ghost |
b31636287ed68f8f3b2037eb8d1dfc484fece7b2 | 869 | cpp | C++ | Leetcode/Day023/string_to_int_atoi.cpp | SujalAhrodia/Practice_2020 | 59b371ada245ed8253d12327f18deee3e47f31d6 | [
"MIT"
] | null | null | null | Leetcode/Day023/string_to_int_atoi.cpp | SujalAhrodia/Practice_2020 | 59b371ada245ed8253d12327f18deee3e47f31d6 | [
"MIT"
] | null | null | null | Leetcode/Day023/string_to_int_atoi.cpp | SujalAhrodia/Practice_2020 | 59b371ada245ed8253d12327f18deee3e47f31d6 | [
"MIT"
] | null | null | null | /*
Imp to remember: erasing string mechanism | isdigit() | str.erase()
*/
class Solution {
public:
int myAtoi(string str)
{
long long int ans=0;
string temp=str;
bool pos=true;
while(temp[0]==' ')
temp.erase(temp.begin());
if(temp[0]=='-' || temp[0]=='+')
{
if(temp[0]=='-')
pos=false;
temp.erase(temp.begin());
}
for(char ch:temp)
{
if(!isdigit(ch))
break;
ans=ans*10+(ch-'0');
if(ans>INT_MAX)
{
if(!pos)
return INT_MIN;
else
return INT_MAX;
}
}
if(!pos)
ans=-ans;
return ans;
}
};
| 18.891304 | 67 | 0.352129 | SujalAhrodia |
b3169991554b43dcb993a85a054ccb07c974c53c | 8,881 | cpp | C++ | src/state/StateVector.cpp | neophack/steam | 28f0637e3ae4ff2c21ad12b2331c535e9873c997 | [
"BSD-3-Clause"
] | null | null | null | src/state/StateVector.cpp | neophack/steam | 28f0637e3ae4ff2c21ad12b2331c535e9873c997 | [
"BSD-3-Clause"
] | null | null | null | src/state/StateVector.cpp | neophack/steam | 28f0637e3ae4ff2c21ad12b2331c535e9873c997 | [
"BSD-3-Clause"
] | null | null | null | //////////////////////////////////////////////////////////////////////////////////////////////
/// \file StateVector.cpp
///
/// \author Sean Anderson, ASRL
//////////////////////////////////////////////////////////////////////////////////////////////
#include <steam/state/StateVector.hpp>
#include <steam/blockmat/BlockVector.hpp>
#include <iostream>
namespace steam {
//////////////////////////////////////////////////////////////////////////////////////////////
/// \brief Default constructor
//////////////////////////////////////////////////////////////////////////////////////////////
StateVector::StateVector() : numBlockEntries_(0) {}
//////////////////////////////////////////////////////////////////////////////////////////////
/// \brief Copy constructor -- deep copy
//////////////////////////////////////////////////////////////////////////////////////////////
StateVector::StateVector(const StateVector& other) : states_(other.states_),
numBlockEntries_(other.numBlockEntries_) {
// Map is copied in initialization list to avoid re-hashing all the entries,
// now we go through the entries and perform a deep copy
boost::unordered_map<StateID, StateContainer>::iterator it = states_.begin();
for(; it != states_.end(); ++it) {
it->second.state = it->second.state->clone();
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
/// \brief Assignment operator -- deep copy
//////////////////////////////////////////////////////////////////////////////////////////////
StateVector& StateVector::operator= (const StateVector& other) {
// Copy-swap idiom
StateVector tmp(other); // note, copy constructor makes a deep copy
std::swap(states_, tmp.states_);
std::swap(numBlockEntries_, tmp.numBlockEntries_);
return *this;
}
//////////////////////////////////////////////////////////////////////////////////////////////
/// \brief Copy the values of 'other' into 'this' (states must already align, typically
/// this means that one is already a deep copy of the other)
//////////////////////////////////////////////////////////////////////////////////////////////
void StateVector::copyValues(const StateVector& other) {
// Check state vector are the same size
if (this->states_.empty() ||
this->numBlockEntries_ != other.numBlockEntries_ ||
this->states_.size() != other.states_.size()) {
throw std::invalid_argument("StateVector size was not the same in copyValues()");
}
// Iterate over the state vectors and perform a "deep" copy without allocation new memory.
// Keeping the original pointers is important as they are shared in other places, and we
// want to update the shared memory.
// todo: can we avoid a 'find' here?
boost::unordered_map<StateID, StateContainer>::iterator it = states_.begin();
for(; it != states_.end(); ++it) {
// Find matching state by ID
boost::unordered_map<StateID, StateContainer>::const_iterator itOther = other.states_.find(it->second.state->getKey().getID());
// Check that matching state was found and has the same structure
if (itOther == other.states_.end() ||
it->second.state->getKey().getID() != itOther->second.state->getKey().getID() ||
it->second.localBlockIndex != itOther->second.localBlockIndex) {
throw std::runtime_error("StateVector was missing an entry in copyValues(), "
"or structure of StateVector did not match.");
}
// Copy
it->second.state->setFromCopy(itOther->second.state);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
/// \brief Add state variable
//////////////////////////////////////////////////////////////////////////////////////////////
void StateVector::addStateVariable(const StateVariableBase::Ptr& state) {
// Verify that state is not locked
if (state->isLocked()) {
throw std::invalid_argument("Tried to add locked state variable to "
"an optimizable state vector");
}
// Verify we don't already have this state
StateKey key = state->getKey();
if (this->hasStateVariable(key)) {
throw std::runtime_error("StateVector already contains the state being added.");
}
// Create new container
StateContainer newEntry;
newEntry.state = state; // copy the shared_ptr (increases ref count)
newEntry.localBlockIndex = numBlockEntries_;
states_[key.getID()] = newEntry;
// Increment number of entries
numBlockEntries_++;
}
//////////////////////////////////////////////////////////////////////////////////////////////
/// \brief Check if a state variable exists in the vector
//////////////////////////////////////////////////////////////////////////////////////////////
bool StateVector::hasStateVariable(const StateKey& key) const {
// Find the StateContainer for key
boost::unordered_map<StateID, StateContainer>::const_iterator it = states_.find(key.getID());
// Return if found
return it != states_.end();
}
//////////////////////////////////////////////////////////////////////////////////////////////
/// \brief Get a state variable using a key
//////////////////////////////////////////////////////////////////////////////////////////////
StateVariableBase::ConstPtr StateVector::getStateVariable(const StateKey& key) const {
// Find the StateContainer for key
boost::unordered_map<StateID, StateContainer>::const_iterator it = states_.find(key.getID());
// Check that it was found
if (it == states_.end()) {
throw std::runtime_error("State variable was not found in call to getStateVariable()");
}
// Return state variable reference
return it->second.state;
}
//////////////////////////////////////////////////////////////////////////////////////////////
/// \brief Get number of state variables
//////////////////////////////////////////////////////////////////////////////////////////////
unsigned int StateVector::getNumberOfStates() const {
return states_.size();
}
//////////////////////////////////////////////////////////////////////////////////////////////
/// \brief Get the block index of a state
//////////////////////////////////////////////////////////////////////////////////////////////
int StateVector::getStateBlockIndex(const StateKey& key) const {
// Find the StateContainer for key
boost::unordered_map<StateID, StateContainer>::const_iterator it = states_.find(key.getID());
// Check that the state exists in the state vector
// **Note the likely causes that this occurs:
// 1) A cost term includes a state that is not added to the problem
// 2) A cost term is not checking whether states are locked, and adding a Jacobian for a locked state variable
if (it == states_.end()) {
std::stringstream ss; ss << "Tried to find a state that does not exist "
"in the state vector (ID: " << key.getID() << ").";
throw std::runtime_error(ss.str());
}
// Return block index
return it->second.localBlockIndex;
}
//////////////////////////////////////////////////////////////////////////////////////////////
/// \brief Get an ordered list of the sizes of the 'block' state variables
//////////////////////////////////////////////////////////////////////////////////////////////
std::vector<unsigned int> StateVector::getStateBlockSizes() const {
// Init return
std::vector<unsigned int> result;
result.resize(states_.size());
// Iterate over states and populate result
for (boost::unordered_map<StateID, StateContainer>::const_iterator it = states_.begin();
it != states_.end(); ++it ) {
// Check that the local block index is in a valid range
if (it->second.localBlockIndex < 0 ||
it->second.localBlockIndex >= (int)result.size()) {
throw std::logic_error("localBlockIndex is not a valid range");
}
// Populate return vector
result[it->second.localBlockIndex] = it->second.state->getPerturbDim();
}
return result;
}
//////////////////////////////////////////////////////////////////////////////////////////////
/// \brief Update the state vector
//////////////////////////////////////////////////////////////////////////////////////////////
void StateVector::update(const Eigen::VectorXd& perturbation) {
// Convert single vector to a block-vector of perturbations (this checks sizes)
BlockVector blkPerturb(this->getStateBlockSizes(), perturbation);
// Iterate over states and update each
for ( boost::unordered_map<StateID, StateContainer>::const_iterator it = states_.begin(); it != states_.end(); ++it ) {
// Check for valid index
if (it->second.localBlockIndex < 0) {
throw std::runtime_error("localBlockIndex is not initialized");
}
// Update state
it->second.state->update(blkPerturb.at(it->second.localBlockIndex));
}
}
} // steam
| 41.306977 | 131 | 0.515145 | neophack |
b317e81ff1a1e7f9dc81cff75135cbb04210ca85 | 1,074 | cc | C++ | bin/zxdb/client/thread_impl_test_support.cc | PowerOlive/garnet | 16b5b38b765195699f41ccb6684cc58dd3512793 | [
"BSD-3-Clause"
] | null | null | null | bin/zxdb/client/thread_impl_test_support.cc | PowerOlive/garnet | 16b5b38b765195699f41ccb6684cc58dd3512793 | [
"BSD-3-Clause"
] | null | null | null | bin/zxdb/client/thread_impl_test_support.cc | PowerOlive/garnet | 16b5b38b765195699f41ccb6684cc58dd3512793 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "garnet/bin/zxdb/client/thread_impl_test_support.h"
#include "garnet/bin/zxdb/client/thread.h"
#include "garnet/bin/zxdb/common/err.h"
namespace zxdb {
ThreadImplTest::ThreadImplTest() = default;
ThreadImplTest::~ThreadImplTest() = default;
std::unique_ptr<RemoteAPI> ThreadImplTest::GetRemoteAPIImpl() {
auto remote_api = std::make_unique<MockRemoteAPI>();
mock_remote_api_ = remote_api.get();
return std::move(remote_api);
}
TestThreadObserver::TestThreadObserver(Thread* thread) : thread_(thread) {
thread->AddObserver(this);
}
TestThreadObserver::~TestThreadObserver() { thread_->RemoveObserver(this); }
void TestThreadObserver::OnThreadStopped(
Thread* thread, debug_ipc::NotifyException::Type type,
std::vector<fxl::WeakPtr<Breakpoint>> hit_breakpoints) {
EXPECT_EQ(thread_, thread);
got_stopped_ = true;
hit_breakpoints_ = hit_breakpoints;
}
} // namespace zxdb
| 29.833333 | 76 | 0.759777 | PowerOlive |
b319184ac9b6fc21959e9ad978f1b468791faacd | 1,431 | cpp | C++ | leetcode/problems/hard/115-distinct-subsequences.cpp | wingkwong/competitive-programming | e8bf7aa32e87b3a020b63acac20e740728764649 | [
"MIT"
] | 18 | 2020-08-27T05:27:50.000Z | 2022-03-08T02:56:48.000Z | leetcode/problems/hard/115-distinct-subsequences.cpp | wingkwong/competitive-programming | e8bf7aa32e87b3a020b63acac20e740728764649 | [
"MIT"
] | null | null | null | leetcode/problems/hard/115-distinct-subsequences.cpp | wingkwong/competitive-programming | e8bf7aa32e87b3a020b63acac20e740728764649 | [
"MIT"
] | 1 | 2020-10-13T05:23:58.000Z | 2020-10-13T05:23:58.000Z | /*
Distinct Subsequences
https://leetcode.com/problems/distinct-subsequences/
Given two strings s and t, return the number of distinct subsequences of s which equals t.
A string's subsequence is a new string formed from the original string by deleting some (can be none) of the characters without disturbing the remaining characters' relative positions. (i.e., "ACE" is a subsequence of "ABCDE" while "AEC" is not).
It is guaranteed the answer fits on a 32-bit signed integer.
Example 1:
Input: s = "rabbbit", t = "rabbit"
Output: 3
Explanation:
As shown below, there are 3 ways you can generate "rabbit" from S.
rabbbit
rabbbit
rabbbit
Example 2:
Input: s = "babgbag", t = "bag"
Output: 5
Explanation:
As shown below, there are 5 ways you can generate "bag" from S.
babgbag
babgbag
babgbag
babgbag
babgbag
Constraints:
1 <= s.length, t.length <= 1000
s and t consist of English letters.
*/
class Solution {
public:
int numDistinct(string s, string t) {
int n = s.size(), m = t.size();
unsigned long long dp[n + 1][m + 1];
memset(dp, 0, sizeof(dp));
for(int i = 0; i <= n; i++) dp[i][0] = 1;
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= m; j++) {
dp[i][j] = dp[i - 1][j];
if(s[i - 1] == t[j - 1]) {
dp[i][j] += dp[i - 1][j - 1];
}
}
}
return dp[n][m];
}
}; | 24.672414 | 246 | 0.594689 | wingkwong |
b31a116dfe80be72926d7f7dfe00938e3c20b5db | 21,701 | hpp | C++ | Project/include/lak/transform.hpp | LAK132/OpenGL-Trash | 9ddedf65792de78f642f47ad032b5027e4c390c1 | [
"MIT"
] | null | null | null | Project/include/lak/transform.hpp | LAK132/OpenGL-Trash | 9ddedf65792de78f642f47ad032b5027e4c390c1 | [
"MIT"
] | null | null | null | Project/include/lak/transform.hpp | LAK132/OpenGL-Trash | 9ddedf65792de78f642f47ad032b5027e4c390c1 | [
"MIT"
] | null | null | null | /*
MIT License
Copyright (c) 2018 Lucas Kleiss (LAK132)
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.
*/
/*
Dual Quaternion concepts from "A Beginners Guide to Dual-Quaternions" (Ben Kenwright)
https://cs.gmu.edu/~jmlien/teaching/cs451/uploads/Main/dual-quaternion.pdf
https://web.archive.org/web/20180622093933/https://cs.gmu.edu/~jmlien/teaching/cs451/uploads/Main/dual-quaternion.pdf
*/
#include <cmath>
#include <type_traits>
// #include <lak/mstream.hpp>
#ifndef DEBUG
# ifdef NDEBUG
# define DEBUG(x)
# else
# include <iostream>
# define DEBUG(x) std::cout << __FILE__ << "(" << std::dec << __LINE__ << ") " << x
# endif
#endif
#ifndef LAK_TRANSFORM_MAT4
#include <glm/mat4x4.hpp>
#define LAK_TRANSFORM_MAT4 glm::mat4
#endif
#ifndef LAK_TRANSFORM_VEC3
#include <glm/vec3.hpp>
#define LAK_TRANSFORM_VEC3 glm::vec3
#endif
#ifndef LAK_TRANSFORM_VEC2
#include <glm/vec2.hpp>
#define LAK_TRANSFORM_VEC2 glm::vec2
#endif
#ifndef LAK_TRANSFORM_H
#define LAK_TRANSFORM_H
namespace lak
{
using mat4_t = LAK_TRANSFORM_MAT4;
using vec3_t = LAK_TRANSFORM_VEC3;
using vec2_t = LAK_TRANSFORM_VEC2;
// template <>
// mstream &operator>><vec3_t &>(mstream &strm, vec3_t &obj)
// {
// strm >> obj.x >> obj.y >> obj.z;
// return strm;
// }
// template <>
// mstream &operator<<<vec3_t &>(mstream &strm, vec3_t &obj)
// {
// strm << obj.x << obj.y << obj.z;
// return strm;
// }
// template <>
// mstream &operator>><vec2_t &>(mstream &strm, vec2_t &obj)
// {
// strm >> obj.x >> obj.y;
// return strm;
// }
// template <>
// mstream &operator<<<vec2_t &>(mstream &strm, vec2_t &obj)
// {
// strm << obj.x << obj.y;
// return strm;
// }
#if defined(LAK_TRANSFORM_BIGGER_TYPE_ADD)
template<typename L, typename R>
using biggerType = decltype(L(0) + R(0));
#elif defined(LAK_TRANSFORM_BIGGER_TYPE_SUB)
template<typename L, typename R>
using biggerType = decltype(L(0) - R(0));
#else
template<typename L, typename R>
using biggerType = decltype(L(0) * R(0));
#endif
template<typename T> struct quaternion_t;
template<typename T>
struct quaternion_t
{
typedef typename std::decay<T>::type _value_type;
typedef quaternion_t<_value_type> _type;
_value_type x;
_value_type y;
_value_type z;
_value_type w;
quaternion_t() : x(_value_type(0)), y(_value_type(0)), z(_value_type(0)), w(_value_type(1)) {}
// quaternion_t(const _value_type& X, const _value_type& Y, const _value_type& Z, const _value_type& W) : x(X), y(Y), z(Z), w(W) {}
// quaternion_t(_value_type&& X, _value_type&& Y, _value_type&& Z, _value_type&& W) : x(X), y(Y), z(Z), w(W) {}
quaternion_t(_value_type X, _value_type Y, _value_type Z, _value_type W) : x(X), y(Y), z(Z), w(W) {}
quaternion_t(const _value_type XYZW[4]) : x(XYZW[0]), y(XYZW[1]), z(XYZW[2]), w(XYZW[3]) {}
template<typename R>
quaternion_t(const quaternion_t<R>& other)
{
*this = other;
}
template<typename R>
quaternion_t(quaternion_t<R>&& other)
{
*this = other;
}
template<typename R>
_type& operator=(const quaternion_t<R>& rhs)
{
x = rhs.x;
y = rhs.y;
z = rhs.z;
w = rhs.w;
return *this;
}
template<typename R>
_type& operator=(quaternion_t<R>&& rhs)
{
x = rhs.x;
y = rhs.y;
z = rhs.z;
w = rhs.w;
return *this;
}
_type operator*() // abuse the derefernce operator for conjugate operation
{
return _type(-x, -y, -z, w);
}
_type conjugate()
{
return _type(-x, -y, -z, w);
}
_value_type operator~() // magnitude
{
// sqrt(this->dot(*this)) // overkill
// sqrt((*this * this->conjugate()).w) // overkill
return sqrt((x*x)+(y*y)+(z*z)+(w*w));
}
_value_type magnitude()
{
return sqrt((x*x)+(y*y)+(z*z)+(w*w));
}
_type norm()
{
return *this * (_value_type(1) / magnitude());
}
_type& normalize()
{
return *this *= _value_type(1) / magnitude();
}
_value_type& operator[](const size_t& index) // useful for &(qrtn[0])
{
return *((&x)+index);
}
_value_type& operator[](size_t&& index) // useful for &(qrtn[0])
{
return *((&x)+index);
}
_value_type* operator[](const char& index)
{
switch(index)
{
case 'x': return &x;
case 'y': return &y;
case 'z': return &z;
case 'w': return &w;
}
return nullptr;
}
template<typename R>
bool operator==(const quaternion_t<R>& rhs)
{
return x == rhs.x && y == rhs.y && z == rhs.z && w == rhs.w;
}
template<typename R>
bool operator==(quaternion_t<R>&& rhs)
{
return x == rhs.x && y == rhs.y && z == rhs.z && w == rhs.w;
}
template<typename R>
bool operator!=(const quaternion_t<R>& rhs)
{
return x != rhs.x && y != rhs.y && z != rhs.z && w != rhs.w;
}
template<typename R>
bool operator!=(quaternion_t<R>&& rhs)
{
return x != rhs.x && y != rhs.y && z != rhs.z && w != rhs.w;
}
template<typename R>
biggerType<_value_type, typename std::decay<R>::type> dot(const quaternion_t<R>& rhs)
{
return (x * rhs.x) + (y * rhs.y) + (z * rhs.z) + (w * rhs.w);
}
template<typename R>
biggerType<_value_type, typename std::decay<R>::type> dot(quaternion_t<R>&& rhs)
{
return (x * rhs.x) + (y * rhs.y) + (z * rhs.z) + (w * rhs.w);
}
template<typename R>
_type& operator+=(const quaternion_t<R>& rhs)
{
x += rhs.x;
y += rhs.y;
z += rhs.z;
w += rhs.w;
return *this;
}
template<typename R>
_type& operator+=(quaternion_t<R>&& rhs)
{
x += rhs.x;
y += rhs.y;
z += rhs.z;
w += rhs.w;
return *this;
}
template<typename R>
quaternion_t<biggerType<_value_type, R>> operator+(const quaternion_t<R>& rhs)
{
return quaternion_t<biggerType<_value_type, R>>(x+rhs.x, y+rhs.y, z+rhs.z, z+rhs.z);
}
template<typename R>
quaternion_t<biggerType<_value_type, R>> operator+(quaternion_t<R>&& rhs)
{
return quaternion_t<biggerType<_value_type, R>>(x+rhs.x, y+rhs.y, z+rhs.z, z+rhs.z);
}
template<typename R>
_type& operator*=(R rhs) // scalar mult
{
x *= rhs;
y *= rhs;
z *= rhs;
w *= rhs;
return *this;
}
template<typename R>
_type& operator*=(const quaternion_t<R>& rhs)
{
_value_type _x = ((y * rhs.z) - (z * rhs.y)) + (w * rhs.x) + (x * rhs.w);
_value_type _y = ((z * rhs.x) - (x * rhs.z)) + (w * rhs.y) + (y * rhs.w);
_value_type _z = ((x * rhs.y) - (y * rhs.x)) + (w * rhs.z) + (z * rhs.w);
_value_type _w = (w * rhs.w) - ((x * rhs.x) + (y * rhs.y) + (z * rhs.z));
x = _x; y = _y; z = _z; w = _w;
return *this;
}
template<typename R>
_type& operator*=(quaternion_t<R>&& rhs)
{
_value_type _x = ((y * rhs.z) - (z * rhs.y)) + (w * rhs.x) + (x * rhs.w);
_value_type _y = ((z * rhs.x) - (x * rhs.z)) + (w * rhs.y) + (y * rhs.w);
_value_type _z = ((x * rhs.y) - (y * rhs.x)) + (w * rhs.z) + (z * rhs.w);
_value_type _w = (w * rhs.w) - ((x * rhs.x) + (y * rhs.y) + (z * rhs.z));
x = _x; y = _y; z = _z; w = _w;
return *this;
}
template<typename R>
quaternion_t<biggerType<_value_type, typename std::decay<R>::type>> operator*(R rhs)
{
quaternion_t<biggerType<_value_type, typename std::decay<R>::type>> rtn = *this;
return rtn *= rhs;
}
template<typename R>
quaternion_t<biggerType<_value_type, R>> operator*(const quaternion_t<R>& rhs)
{
quaternion_t<biggerType<_value_type, R>> rtn = *this;
return rtn *= rhs;
}
template<typename R>
quaternion_t<biggerType<_value_type, R>> operator*(quaternion_t<R>&& rhs)
{
quaternion_t<biggerType<_value_type, R>> rtn = *this;
return rtn *= rhs;
}
template<typename L>
friend quaternion_t<biggerType<_value_type, typename std::decay<L>::type>> operator*(L lhs, quaternion_t<_value_type> rhs)
{
quaternion_t<biggerType<_value_type, typename std::decay<L>::type>> rtn = rhs;
return rtn *= lhs;
}
};
// template <typename T>
// mstream &operator>><quaternion_t<T>>(mstream &strm, quaternion_t<T> &obj)
// {
// strm >> obj.x >> obj.y >> obj.z >> obj.w;
// return strm;
// }
// template <typename T>
// mstream &operator<<<quaternion_t<T>>(mstream &strm, quaternion_t<T> &obj)
// {
// strm << obj.x << obj.y << obj.z << obj.w;
// return strm;
// }
typedef quaternion_t<float> quaternionf_t;
typedef quaternion_t<double> quaterniond_t;
template<typename T>
struct dualquaternion_t
{
typedef typename std::decay<T>::type _value_type;
typedef quaternion_t<_value_type> _qtrn_type;
typedef dualquaternion_t<_value_type> _type;
_qtrn_type real;
_qtrn_type dual;
dualquaternion_t() : real(_value_type(0), _value_type(0), _value_type(0), _value_type(1)), dual(_value_type(0), _value_type(0), _value_type(0), _value_type(0)) {}
// dualquaternion_t(const _qtrn_type& R, const _qtrn_type& D) : real(R), dual(D) {}
// dualquaternion_t(_qtrn_type&& R, _qtrn_type&& D) : real(R), dual(D) {}
dualquaternion_t(_qtrn_type R, _qtrn_type D) : real(R), dual(D) {}
dualquaternion_t(const _qtrn_type RD[2]) : real(RD[0]), dual(RD[1]) {}
// dualquaternion_t(
// const _value_type& rX, const _value_type& rY, const _value_type& rZ, const _value_type& rW,
// const _value_type& dX, const _value_type& dY, const _value_type& dZ, const _value_type& dW
// ) : real(rX, rY, rZ, rW), dual(dX, dY, dZ, dW) {}
// dualquaternion_t(
// _value_type&& rX, _value_type&& rY, _value_type&& rZ, _value_type&& rW,
// _value_type&& dX, _value_type&& dY, _value_type&& dZ, _value_type&& dW
// ) : real(rX, rY, rZ, rW), dual(dX, dY, dZ, dW) {}
dualquaternion_t(
_value_type rX, _value_type rY, _value_type rZ, _value_type rW,
_value_type dX, _value_type dY, _value_type dZ, _value_type dW
) : real(rX, rY, rZ, rW), dual(dX, dY, dZ, dW) {}
dualquaternion_t(const _value_type vals[8]) : real(vals[0], vals[1], vals[2], vals[3]), dual(vals[4], vals[5], vals[6], vals[7]) {}
_type& fromRotTrans(const _qtrn_type& rot, _qtrn_type trans)
{
real = rot;
trans.w = _value_type(0);
dual = _value_type(0.5) * trans * rot;
return *this;
}
_type& fromRotTrans(_qtrn_type&& rot, _qtrn_type&& trans)
{
real = rot;
trans.w = _value_type(0);
dual = _value_type(0.5) * trans * rot;
return *this;
}
_type& fromEuler(const _qtrn_type& rot, _qtrn_type trans)
{
real.w = cos(rot.w / 2);
_value_type srw2 = sin(rot.w / 2);// / sqrt((rot.x*rot.x) + (rot.y*rot.y) + (rot.z*rot.z));
real.x = rot.x * srw2;
real.y = rot.y * srw2;
real.z = rot.z * srw2;
trans.w = _value_type(0);
dual = _value_type(0.5) * trans * real;
return *this;
}
_type& fromEuler(_qtrn_type&& rot, _qtrn_type&& trans)
{
real.w = cos(rot.w / 2);
_value_type srw2 = sin(rot.w / 2);
real.x = rot.x * srw2;
real.y = rot.y * srw2;
real.z = rot.z * srw2;
trans.w = _value_type(0);
dual = _value_type(0.5) * trans * real;
return *this;
}
_qtrn_type rotation()
{
return real;
}
_qtrn_type eulerRotation()
{
_qtrn_type rtn;
rtn.w = acos(real.w) * 2;
_value_type srw2 = sin(rtn.w / 2);
if(srw2 == 0.0f)
{
rtn.x = 0.0f;
rtn.y = 0.0f;
rtn.z = 0.0f;
}
else
{
rtn.x = real.x / srw2;
rtn.y = real.y / srw2;
rtn.z = real.z / srw2;
}
return rtn;
}
_qtrn_type translation()
{
_qtrn_type& trans = (dual * _value_type(2)) * *real;
trans.w = _value_type(0);
return trans;
}
mat4_t transform()
{
normalize();
_qtrn_type& trans = translation();
_value_type &x = real.x,
&y = real.y,
&z = real.z,
&w = real.w;
const _value_type t = 2;
return mat4_t {
(w*w) + (x*x) - (y*y) - (z*z),
(t*x*y) + (t*w*z),
(t*x*z) - (t*w*y),
_value_type(0),
(t*x*y) - (t*w*z),
(w*w) + (y*y) - (x*x) - (z*z),
(t*y*z) + (t*w*x),
_value_type(0),
(t*x*z) + (t*w*y),
(t*y*z) - (t*w*x),
(w*w) + (z*z) - (x*x) - (y*y),
_value_type(0),
trans.x,
trans.y,
trans.z,
_value_type(1)
};
}
_type operator*() // abuse the derefernce operator for conjugate operation
{
return _type(*real, *dual);
}
_type conjugate()
{
return _type(*real, *dual);
}
_value_type operator~() // magnitude
{
// ||dq|| = sqrt(dq*(*dq))
// dq1*dq2 = dq1.r*dq2.r + (dq1.r*dq2.d + dq1.d*dq2.r)ε
// dq*(*dq) = dq.r*(*dq.r) + (dq.r*(*dq.d) + dq.d*(*dq.r))ε
// dq*(*dq) = dq.r*(*dq.r) + (0)ε
// ||dq|| = ||dq.r||
return ~real;
}
_value_type magnitude()
{
return ~real;
}
_type norm()
{
return *this * (_value_type(1) / magnitude());
}
_type& normalize()
{
return *this *= _value_type(1) / magnitude();
}
_value_type& operator[](const size_t& index) // useful for &(qrtn[0])
{
return *((&real)+index);
}
_value_type& operator[](size_t&& index) // useful for &(qrtn[0])
{
return *((&real)+index);
}
_value_type* operator[](const char& index)
{
switch(index)
{
case 'r': return ℜ
case 'd': return &dual;
}
return nullptr;
}
template<typename R>
bool operator==(const dualquaternion_t<R>& rhs)
{
return real == rhs.real && dual == rhs.dual;
}
template<typename R>
bool operator==(dualquaternion_t<R>&& rhs)
{
return real == rhs.real && dual == rhs.dual;
}
template<typename R>
bool operator!=(const dualquaternion_t<R>& rhs)
{
return real != rhs.real && dual != rhs.dual;
}
template<typename R>
bool operator!=(dualquaternion_t<R>&& rhs)
{
return real != rhs.real && dual != rhs.dual;
}
template<typename R>
quaternion_t<biggerType<_value_type, typename std::decay<R>::type>> dot(const dualquaternion_t<R>& rhs)
{
return real.dot(rhs.real);
}
template<typename R>
quaternion_t<biggerType<_value_type, typename std::decay<R>::type>> dot(dualquaternion_t<R>&& rhs)
{
return real.dot(rhs.real);
}
template<typename R>
_type& operator=(const dualquaternion_t<R>& rhs)
{
real = rhs.real;
dual = rhs.dual;
return *this;
}
template<typename R>
_type& operator=(dualquaternion_t<R>&& rhs)
{
real = rhs.real;
dual = rhs.dual;
return *this;
}
template<typename R>
_type& operator+=(const dualquaternion_t<R>& rhs)
{
real += rhs.real;
dual += rhs.dual;
return *this;
}
template<typename R>
_type& operator+=(dualquaternion_t<R>&& rhs)
{
real += rhs.real;
dual += rhs.dual;
return *this;
}
template<typename R>
dualquaternion_t<biggerType<_value_type, R>> operator+(const dualquaternion_t<R>& rhs)
{
return dualquaternion_t<biggerType<_value_type, R>>(real+rhs.real, dual+rhs.dual);
}
template<typename R>
dualquaternion_t<biggerType<_value_type, R>> operator+(dualquaternion_t<R>&& rhs)
{
return dualquaternion_t<biggerType<_value_type, R>>(real+rhs.real, dual+rhs.dual);
}
template<typename R>
_type& operator*=(R rhs) // scalar mult
{
real *= rhs;
dual *= rhs;
return *this;
}
template<typename R>
_type& operator*=(const dualquaternion_t<R>& rhs)
{
// NOTE: current real is needed to calculate new dual! beware of order!
dual = (real * rhs.dual) + (dual * rhs.real);
real *= rhs.real;
return *this;
}
template<typename R>
_type& operator*=(dualquaternion_t<R>&& rhs)
{
dual = (real * rhs.dual) + (dual * rhs.real);
real *= rhs.real;
return *this;
}
template<typename R>
dualquaternion_t<biggerType<_value_type, typename std::decay<R>::type>> operator*(R rhs)
{
dualquaternion_t<biggerType<_value_type, typename std::decay<R>::type>> rtn = *this;
return rtn *= rhs;
}
template<typename R>
dualquaternion_t<biggerType<_value_type, R>> operator*(const dualquaternion_t<R>& rhs)
{
dualquaternion_t<biggerType<_value_type, R>> rtn = *this;
return rtn *= rhs;
}
template<typename R>
dualquaternion_t<biggerType<_value_type, R>> operator*(dualquaternion_t<R>&& rhs)
{
dualquaternion_t<biggerType<_value_type, R>> rtn = *this;
return rtn *= rhs;
}
template<typename L>
friend dualquaternion_t<biggerType<_value_type, typename std::decay<L>::type>> operator*(L lhs, dualquaternion_t<_value_type> rhs)
{
dualquaternion_t<biggerType<_value_type, typename std::decay<L>::type>> rtn = rhs;
return rtn *= lhs;
}
};
// template <typename T>
// mstream &operator>><dualquaternion_t<T>>(mstream &strm, dualquaternion_t<T> &obj)
// {
// strm >> obj.real >> obj.dual;
// return strm;
// }
// template <typename T>
// mstream &operator<<<dualquaternion_t<T>>(mstream &strm, dualquaternion_t<T> &obj)
// {
// strm << obj.real << obj.dual;
// return strm;
// }
typedef dualquaternion_t<float> dualquaternionf_t;
typedef dualquaternion_t<double> dualquaterniond_t;
}
#endif // LAK_TRANSFORM_H
// #define LAK_TRANSFORM_IMPLEM
#ifdef LAK_TRANSFORM_IMPLEM
#ifndef LAK_TRANSFORM_HAS_IMPLEM
#define LAK_TRANSFORM_HAS_IMPLEM
namespace lak
{
}
#endif // LAK_TRANSFORM_HAS_IMPLEM
#endif // LAK_TRANSFORM_IMPLEM | 33.592879 | 170 | 0.516059 | LAK132 |
b31e07989aeebeb61c6c758cbd2368a8c67891dc | 8,707 | cpp | C++ | ze_imu/src/imu_buffer.cpp | rockenbf/ze_oss | ee04158e2d51acb07a267196f618e9afbc3ffd83 | [
"BSD-3-Clause"
] | 30 | 2016-09-27T07:41:28.000Z | 2021-12-03T20:44:28.000Z | ze_imu/src/imu_buffer.cpp | rockenbf/ze_oss | ee04158e2d51acb07a267196f618e9afbc3ffd83 | [
"BSD-3-Clause"
] | 1 | 2018-12-18T15:53:06.000Z | 2018-12-21T03:10:06.000Z | ze_imu/src/imu_buffer.cpp | rockenbf/ze_oss | ee04158e2d51acb07a267196f618e9afbc3ffd83 | [
"BSD-3-Clause"
] | 12 | 2016-11-05T07:51:29.000Z | 2020-07-13T02:26:08.000Z | // Copyright (c) 2015-2016, ETH Zurich, Wyss Zurich, Zurich Eye
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the ETH Zurich, Wyss Zurich, Zurich Eye 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 ETH Zurich, Wyss Zurich, Zurich Eye 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 <ze/imu/imu_buffer.hpp>
namespace ze {
template<int BufferSize, typename GyroInterp, typename AccelInterp>
ImuBuffer<BufferSize, GyroInterp, AccelInterp>::ImuBuffer(ImuModel::Ptr imu_model)
: imu_model_(imu_model)
, gyro_delay_(secToNanosec(imu_model->gyroscopeModel()->intrinsicModel()->delay()))
, accel_delay_(secToNanosec(imu_model->accelerometerModel()->intrinsicModel()->delay()))
{
}
template<int BufferSize, typename GyroInterp, typename AccelInterp>
void ImuBuffer<BufferSize, GyroInterp, AccelInterp>::insertImuMeasurement(
int64_t time, const ImuAccGyr value)
{
acc_buffer_.insert(correctStampAccel(time), value.head<3>(3));
gyr_buffer_.insert(correctStampGyro(time), value.tail<3>(3));
}
template<int BufferSize, typename GyroInterp, typename AccelInterp>
void ImuBuffer<BufferSize, GyroInterp, AccelInterp>::insertGyroscopeMeasurement(
int64_t time, const Vector3 value)
{
gyr_buffer_.insert(correctStampGyro(time), value);
}
template<int BufferSize, typename GyroInterp, typename AccelInterp>
void ImuBuffer<BufferSize, GyroInterp, AccelInterp>::insertAccelerometerMeasurement(
int64_t time, const Vector3 value)
{
acc_buffer_.insert(correctStampAccel(time), value);
}
template<int BufferSize, typename GyroInterp, typename AccelInterp>
bool ImuBuffer<BufferSize, GyroInterp, AccelInterp>::get(int64_t time,
Eigen::Ref<ImuAccGyr> out)
{
std::lock_guard<std::mutex> gyr_lock(gyr_buffer_.mutex());
std::lock_guard<std::mutex> acc_lock(acc_buffer_.mutex());
if (time > gyr_buffer_.times().back()
|| time > acc_buffer_.times().back())
{
return false;
}
const auto gyro_before = gyr_buffer_.iterator_equal_or_before(time);
const auto acc_before = acc_buffer_.iterator_equal_or_before(time);
if (gyro_before == gyr_buffer_.times().end()
|| acc_before == acc_buffer_.times().end()) {
return false;
}
VectorX w = GyroInterp::interpolate(&gyr_buffer_, time, gyro_before);
VectorX a = AccelInterp::interpolate(&acc_buffer_, time, acc_before);
out = imu_model_->undistort(a, w);
return true;
}
template<int BufferSize, typename GyroInterp, typename AccelInterp>
bool ImuBuffer<BufferSize, GyroInterp, AccelInterp>::getAccelerometerDistorted(
int64_t time,
Eigen::Ref<Vector3> out)
{
return acc_buffer_.getValueInterpolated(time, out);
}
template<int BufferSize, typename GyroInterp, typename AccelInterp>
bool ImuBuffer<BufferSize, GyroInterp, AccelInterp>::getGyroscopeDistorted(
int64_t time,
Eigen::Ref<Vector3> out)
{
return gyr_buffer_.getValueInterpolated(time, out);
}
template<int BufferSize, typename GyroInterp, typename AccelInterp>
std::pair<ImuStamps, ImuAccGyrContainer>
ImuBuffer<BufferSize, GyroInterp, AccelInterp>::getBetweenValuesInterpolated(
int64_t stamp_from, int64_t stamp_to)
{
//Takes gyroscope timestamps and interpolates accelerometer measurements at
// same times. Rectifies all measurements.
CHECK_GE(stamp_from, 0u);
CHECK_LT(stamp_from, stamp_to);
ImuAccGyrContainer rectified_measurements;
ImuStamps stamps;
std::lock_guard<std::mutex> gyr_lock(gyr_buffer_.mutex());
std::lock_guard<std::mutex> acc_lock(acc_buffer_.mutex());
if(gyr_buffer_.times().size() < 2)
{
LOG(WARNING) << "Buffer has less than 2 entries.";
// return empty means unsuccessful.
return std::make_pair(stamps, rectified_measurements);
}
const time_t oldest_stamp = gyr_buffer_.times().front();
const time_t newest_stamp = gyr_buffer_.times().back();
if (stamp_from < oldest_stamp)
{
LOG(WARNING) << "Requests older timestamp than in buffer.";
// return empty means unsuccessful.
return std::make_pair(stamps, rectified_measurements);
}
if (stamp_to > newest_stamp)
{
LOG(WARNING) << "Requests newer timestamp than in buffer.";
// return empty means unsuccessful.
return std::make_pair(stamps, rectified_measurements);
}
const auto it_from_before = gyr_buffer_.iterator_equal_or_before(stamp_from);
const auto it_to_after = gyr_buffer_.iterator_equal_or_after(stamp_to);
CHECK(it_from_before != gyr_buffer_.times().end());
CHECK(it_to_after != gyr_buffer_.times().end());
const auto it_from_after = it_from_before + 1;
const auto it_to_before = it_to_after - 1;
if (it_from_after == it_to_before)
{
LOG(WARNING) << "Not enough data for interpolation";
// return empty means unsuccessful.
return std::make_pair(stamps, rectified_measurements);
}
// resize containers
const size_t range = it_to_before.index() - it_from_after.index() + 3;
rectified_measurements.resize(Eigen::NoChange, range);
stamps.resize(range);
// first element
VectorX w = GyroInterp::interpolate(&gyr_buffer_, stamp_from, it_from_before);
VectorX a = AccelInterp::interpolate(&acc_buffer_, stamp_from);
stamps(0) = stamp_from;
rectified_measurements.col(0) = imu_model_->undistort(a, w);
// this is a real edge case where we hit the two consecutive timestamps
// with from and to.
size_t col = 1;
if (range > 2)
{
for (auto it=it_from_before+1; it!=it_to_after; ++it) {
w = GyroInterp::interpolate(&gyr_buffer_, (*it), it);
a = AccelInterp::interpolate(&acc_buffer_, (*it));
stamps(col) = (*it);
rectified_measurements.col(col) = imu_model_->undistort(a, w);
++col;
}
}
// last element
w = GyroInterp::interpolate(&gyr_buffer_, stamp_to, it_to_before);
a = AccelInterp::interpolate(&acc_buffer_, stamp_to);
stamps(range - 1) = stamp_to;
rectified_measurements.col(range - 1) = imu_model_->undistort(a, w);
return std::make_pair(stamps, rectified_measurements);
}
template<int BufferSize, typename GyroInterp, typename AccelInterp>
std::tuple<int64_t, int64_t, bool>
ImuBuffer<BufferSize, GyroInterp, AccelInterp>::getOldestAndNewestStamp() const
{
std::tuple<int64_t, int64_t, bool> accel =
acc_buffer_.getOldestAndNewestStamp();
std::tuple<int64_t, int64_t, bool> gyro =
gyr_buffer_.getOldestAndNewestStamp();
if (!std::get<2>(accel) || !std::get<2>(gyro))
{
return std::make_tuple(-1, -1, false);
}
int64_t oldest = std::get<0>(accel) < std::get<0>(gyro) ?
std::get<0>(gyro) : std::get<0>(accel);
int64_t newest = std::get<1>(accel) < std::get<1>(gyro) ?
std::get<1>(accel) : std::get<1>(gyro);
// This is an extreme edge case where the accel and gyro measurements
// do not overlap at all.
if (oldest > newest)
{
return std::make_tuple(-1, -1, false);
}
return std::make_tuple(oldest, newest, true);
}
// A set of explicit declarations
template class ImuBuffer<2000, InterpolatorLinear>;
template class ImuBuffer<5000, InterpolatorLinear>;
template class ImuBuffer<2000, InterpolatorNearest>;
template class ImuBuffer<5000, InterpolatorNearest>;
template class ImuBuffer<2000, InterpolatorDifferentiatorLinear,
InterpolatorLinear>;
template class ImuBuffer<5000, InterpolatorDifferentiatorLinear,
InterpolatorLinear>;
} // namespace ze
| 37.856522 | 90 | 0.733892 | rockenbf |
b31e1924b3771d8de37591c535cf466976b452ee | 5,623 | cc | C++ | pmlc/dialect/stdx/transforms/split_closure.cc | IsolatedMy/plaidml | 34538a9224e770fd79151105399d8d7ea08678c0 | [
"Apache-2.0"
] | null | null | null | pmlc/dialect/stdx/transforms/split_closure.cc | IsolatedMy/plaidml | 34538a9224e770fd79151105399d8d7ea08678c0 | [
"Apache-2.0"
] | null | null | null | pmlc/dialect/stdx/transforms/split_closure.cc | IsolatedMy/plaidml | 34538a9224e770fd79151105399d8d7ea08678c0 | [
"Apache-2.0"
] | null | null | null | // Copyright 2021 Intel Corporation
#include "mlir/Dialect/MemRef/IR/MemRef.h"
#include "mlir/Dialect/StandardOps/IR/Ops.h"
#include "mlir/IR/ImplicitLocOpBuilder.h"
#include "mlir/IR/Matchers.h"
#include "mlir/Transforms/RegionUtils.h"
#include "pmlc/dialect/stdx/transforms/pass_detail.h"
#include "pmlc/dialect/stdx/transforms/passes.h"
using namespace mlir; // NOLINT[build/namespaces]
namespace pmlc::dialect::stdx {
namespace {
struct ValuesWithCast {
Value value;
memref::CastOp castOp;
};
struct SplitClosurePass : public SplitClosureBase<SplitClosurePass> {
void runOnOperation() final {
ModuleOp module = getOperation();
FuncOp main = module.lookupSymbol<FuncOp>("main");
if (!main)
return;
auto it = main.body().op_begin<ClosureOp>();
if (it == main.body().op_end<ClosureOp>())
return;
splitClosure(*it);
}
void splitClosure(ClosureOp op) {
MLIRContext *context = &getContext();
ModuleOp module = getOperation();
FuncOp func = op->getParentOfType<FuncOp>();
auto &funcOps = func.body().front().getOperations();
auto itOp = Block::iterator(op);
auto itNextOp = std::next(itOp);
SetVector<Value> values;
visitUsedValuesDefinedAbove(op.body(), op.body(), [&](OpOperand *operand) {
addUsedValue(*operand, values);
});
Block *cleanup = func.body().front().splitBlock(itNextOp);
getUsedValuesDefinedOutside(cleanup, values);
SmallVector<Type> packedTypes;
SmallVector<Value> packedValues;
SmallVector<ValuesWithCast> valuesWithCast;
for (Value value : values) {
if (auto op = dyn_cast_or_null<memref::CastOp>(value.getDefiningOp())) {
packedValues.push_back(op.source());
packedTypes.push_back(op.source().getType());
valuesWithCast.emplace_back(ValuesWithCast{value, op});
} else {
packedValues.push_back(value);
packedTypes.push_back(value.getType());
valuesWithCast.emplace_back(ValuesWithCast{value, nullptr});
}
}
auto tupleType = TupleType::get(context, packedTypes);
auto initFuncType =
FunctionType::get(context, func.getType().getInputs(), {tupleType});
auto mainFuncType = FunctionType::get(context, op.getType().getInputs(),
func.getType().getResults());
auto finiFuncType = FunctionType::get(context, {tupleType}, {});
ImplicitLocOpBuilder builder(op.getLoc(), func);
auto init = builder.create<FuncOp>("init", initFuncType);
auto main = builder.create<FuncOp>("main", mainFuncType);
auto fini = builder.create<FuncOp>("fini", finiFuncType);
// Construct the `init` function.
builder.setInsertionPointToStart(init.addEntryBlock());
auto packOp = builder.create<PackOp>(tupleType, packedValues);
builder.create<ReturnOp>(packOp.getResult());
auto &initOps = init.body().front().getOperations();
initOps.splice(initOps.begin(), funcOps, funcOps.begin(), itOp);
// Construct the new `main` function.
main.body().takeBody(op.body());
Operation *yield = main.body().front().getTerminator();
builder.setInsertionPoint(yield);
builder.create<ReturnOp>();
yield->erase();
main.insertArgument(0, tupleType, /*argAttrs=*/nullptr);
builder.setInsertionPointToStart(&main.body().front());
auto mainUnpackOp =
builder.create<UnpackOp>(packedTypes, main.getArgument(0));
replaceWithUnpacked(valuesWithCast, mainUnpackOp, main, builder);
// Construct the `fini` function.
builder.setInsertionPointToStart(fini.addEntryBlock());
auto finiUnpackOp =
builder.create<UnpackOp>(packedTypes, fini.getArgument(0));
auto &finiOps = fini.body().front().getOperations();
finiOps.splice(finiOps.end(), funcOps, cleanup->begin(),
std::prev(cleanup->end()));
replaceWithUnpacked(valuesWithCast, finiUnpackOp, fini, builder);
builder.create<ReturnOp>();
// NOTE: we need to replace these at the end so that the `values` used in
// `replaceWithUnpacked` remain valid.
for (BlockArgument arg : func.getArguments()) {
arg.replaceAllUsesWith(init.getArgument(arg.getArgNumber()));
}
func.erase();
}
void replaceWithUnpacked(ArrayRef<ValuesWithCast> values, UnpackOp unpackOp,
FuncOp func, OpBuilder &builder) {
for (auto it : llvm::enumerate(values)) {
Value value = it.value().value;
memref::CastOp castOp = it.value().castOp;
Value newValue = unpackOp.getResult(it.index());
if (castOp) {
newValue = builder.create<memref::CastOp>(
castOp.getLoc(), castOp.dest().getType(), newValue);
}
value.replaceUsesWithIf(newValue, [&](OpOperand &operand) {
return operand.getOwner()->getParentOfType<FuncOp>() == func;
});
}
}
void getUsedValuesDefinedOutside(Block *block, SetVector<Value> &values) {
block->walk([&](Operation *op) {
for (OpOperand &operand : op->getOpOperands()) {
if (operand.get().getParentBlock() != block)
addUsedValue(operand, values);
}
});
}
void addUsedValue(OpOperand &operand, SetVector<Value> &values) {
if (matchPattern(operand.get(), m_Constant())) {
OpBuilder builder(operand.getOwner());
Operation *op = builder.clone(*operand.get().getDefiningOp());
operand.set(op->getResult(0));
} else {
values.insert(operand.get());
}
}
};
} // namespace
std::unique_ptr<Pass> createSplitClosurePass() {
return std::make_unique<SplitClosurePass>();
}
} // namespace pmlc::dialect::stdx
| 34.709877 | 79 | 0.667971 | IsolatedMy |
b31f20b37b5ecdb9921dbc8412cce7adb328b677 | 3,034 | hpp | C++ | core/injector/block_producing_node_injector.hpp | FlorianFranzen/kagome | 27ee11c78767e72f0ecd2c515c77bebc2ff5758d | [
"Apache-2.0"
] | null | null | null | core/injector/block_producing_node_injector.hpp | FlorianFranzen/kagome | 27ee11c78767e72f0ecd2c515c77bebc2ff5758d | [
"Apache-2.0"
] | null | null | null | core/injector/block_producing_node_injector.hpp | FlorianFranzen/kagome | 27ee11c78767e72f0ecd2c515c77bebc2ff5758d | [
"Apache-2.0"
] | null | null | null | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef KAGOME_CORE_INJECTOR_BLOCK_PRODUCING_NODE_INJECTOR_HPP
#define KAGOME_CORE_INJECTOR_BLOCK_PRODUCING_NODE_INJECTOR_HPP
#include "application/app_config.hpp"
#include "application/impl/local_key_storage.hpp"
#include "consensus/babe/impl/babe_impl.hpp"
#include "consensus/babe/impl/syncing_babe_observer.hpp"
#include "consensus/grandpa/impl/syncing_round_observer.hpp"
#include "injector/application_injector.hpp"
#include "injector/validating_node_injector.hpp"
#include "runtime/dummy/grandpa_api_dummy.hpp"
#include "storage/in_memory/in_memory_storage.hpp"
namespace kagome::injector {
namespace di = boost::di;
template <typename... Ts>
auto makeBlockProducingNodeInjector(
const application::AppConfigPtr &app_config, Ts &&... args) {
using namespace boost; // NOLINT;
assert(app_config);
return di::make_injector(
// inherit application injector
makeApplicationInjector(app_config->genesis_path(),
app_config->leveldb_path(),
app_config->rpc_http_endpoint(),
app_config->rpc_ws_endpoint()),
// bind sr25519 keypair
di::bind<crypto::SR25519Keypair>.to(
[](auto const &inj) { return get_sr25519_keypair(inj); }),
// bind ed25519 keypair
di::bind<crypto::ED25519Keypair>.to(
[](auto const &inj) { return get_ed25519_keypair(inj); }),
// compose peer keypair
di::bind<libp2p::crypto::KeyPair>.to([](auto const &inj) {
return get_peer_keypair(inj);
})[boost::di::override],
// peer info
di::bind<network::OwnPeerInfo>.to(
[p2p_port{app_config->p2p_port()}](const auto &injector) {
return get_peer_info(injector, p2p_port);
}),
di::bind<consensus::Babe>.to(
[](auto const &inj) { return get_babe(inj); }),
di::bind<consensus::BabeLottery>.template to<consensus::BabeLotteryImpl>(),
di::bind<network::BabeObserver>.to(
[](auto const &inj) { return get_babe(inj); }),
di::bind<consensus::grandpa::RoundObserver>.template to<consensus::grandpa::SyncingRoundObserver>(),
di::bind<application::KeyStorage>.to(
[app_config](const auto &injector) {
return get_key_storage(app_config->keystore_path(), injector);
}),
di::bind<runtime::GrandpaApi>.template to<runtime::dummy::GrandpaApiDummy>()
[boost::di::override],
di::bind<crypto::CryptoStore>.template to(
[app_config](const auto &injector) {
return get_crypto_store(app_config->keystore_path(), injector);
})[boost::di::override],
// user-defined overrides...
std::forward<decltype(args)>(args)...);
}
} // namespace kagome::injector
#endif // KAGOME_CORE_INJECTOR_BLOCK_PRODUCING_NODE_INJECTOR_HPP
| 41 | 108 | 0.649637 | FlorianFranzen |
b320f1f2824b2938836eba833807f18832e371eb | 5,423 | cpp | C++ | src/CourseContentsList.cpp | Midiman/stepmania | a55d5d614c4caa8b035b9b7cdca94017baba026b | [
"MIT"
] | 1 | 2019-02-13T07:01:27.000Z | 2019-02-13T07:01:27.000Z | src/CourseContentsList.cpp | Tatsh/stepmania | bff04ba72e9d578e922fd830819515559b535c45 | [
"MIT"
] | null | null | null | src/CourseContentsList.cpp | Tatsh/stepmania | bff04ba72e9d578e922fd830819515559b535c45 | [
"MIT"
] | null | null | null | #include "global.h"
#include "CourseContentsList.h"
#include "GameConstantsAndTypes.h"
#include "RageLog.h"
#include "Course.h"
#include "Trail.h"
#include "GameState.h"
#include "XmlFile.h"
#include "ActorUtil.h"
#include "RageUtil.h"
#include "Steps.h"
REGISTER_ACTOR_CLASS( CourseContentsList );
CourseContentsList::~CourseContentsList()
{
FOREACH( Actor *, m_vpDisplay, d )
delete *d;
m_vpDisplay.clear();
}
void CourseContentsList::LoadFromNode( const XNode* pNode )
{
int iMaxSongs = 5;
pNode->GetAttrValue( "MaxSongs", iMaxSongs );
const XNode *pDisplayNode = pNode->GetChild( "Display" );
if( pDisplayNode == NULL )
{
LuaHelpers::ReportScriptErrorFmt("%s: CourseContentsList: missing the Display child", ActorUtil::GetWhere(pNode).c_str());
return;
}
for( int i=0; i<iMaxSongs; i++ )
{
Actor *pDisplay = ActorUtil::LoadFromNode( pDisplayNode, this );
pDisplay->SetUseZBuffer( true );
m_vpDisplay.push_back( pDisplay );
}
ActorScroller::LoadFromNode( pNode );
}
void CourseContentsList::SetFromGameState()
{
RemoveAllChildren();
if( GAMESTATE->GetMasterPlayerNumber() == PlayerNumber_Invalid )
return;
const Trail *pMasterTrail = GAMESTATE->m_pCurTrail[GAMESTATE->GetMasterPlayerNumber()];
if( pMasterTrail == NULL )
return;
unsigned uNumEntriesToShow = pMasterTrail->m_vEntries.size();
CLAMP( uNumEntriesToShow, 0, m_vpDisplay.size() );
for( int i=0; i<(int)uNumEntriesToShow; i++ )
{
Actor *pDisplay = m_vpDisplay[i];
SetItemFromGameState( pDisplay, i );
this->AddChild( pDisplay );
}
bool bLoop = pMasterTrail->m_vEntries.size() > uNumEntriesToShow;
this->SetLoop( bLoop );
this->Load2();
this->SetTransformFromHeight( m_vpDisplay[0]->GetUnzoomedHeight() );
this->EnableMask( m_vpDisplay[0]->GetUnzoomedWidth(), m_vpDisplay[0]->GetUnzoomedHeight() );
if( bLoop )
{
SetPauseCountdownSeconds( 1.5f );
this->SetDestinationItem( m_vpDisplay.size()+1 ); // loop forever
}
}
void CourseContentsList::SetItemFromGameState( Actor *pActor, int iCourseEntryIndex )
{
const Course *pCourse = GAMESTATE->m_pCurCourse;
FOREACH_HumanPlayer(pn)
{
const Trail *pTrail = GAMESTATE->m_pCurTrail[pn];
if( pTrail == NULL
|| iCourseEntryIndex >= (int) pTrail->m_vEntries.size()
|| iCourseEntryIndex >= (int) pCourse->m_vEntries.size() )
continue;
const TrailEntry *te = &pTrail->m_vEntries[iCourseEntryIndex];
const CourseEntry *ce = &pCourse->m_vEntries[iCourseEntryIndex];
if( te == NULL )
continue;
RString s;
Difficulty dc;
if( te->bSecret )
{
if( ce == NULL )
continue;
int iLow = ce->stepsCriteria.m_iLowMeter;
int iHigh = ce->stepsCriteria.m_iHighMeter;
bool bLowIsSet = iLow != -1;
bool bHighIsSet = iHigh != -1;
if( !bLowIsSet && !bHighIsSet )
{
s = "?";
}
if( !bLowIsSet && bHighIsSet )
{
s = ssprintf( ">=%d", iHigh );
}
else if( bLowIsSet && !bHighIsSet )
{
s = ssprintf( "<=%d", iLow );
}
else if( bLowIsSet && bHighIsSet )
{
if( iLow == iHigh )
s = ssprintf( "%d", iLow );
else
s = ssprintf( "%d-%d", iLow, iHigh );
}
dc = te->dc;
if( dc == Difficulty_Invalid )
dc = Difficulty_Edit;
}
else
{
s = ssprintf("%d", te->pSteps->GetMeter());
dc = te->pSteps->GetDifficulty();
}
Message msg("SetSong");
msg.SetParam( "PlayerNumber", pn );
msg.SetParam( "Song", te->pSong );
msg.SetParam( "Steps", te->pSteps );
msg.SetParam( "Difficulty", dc );
msg.SetParam( "Meter", s );
msg.SetParam( "Number", iCourseEntryIndex+1 );
msg.SetParam( "Modifiers", te->Modifiers );
msg.SetParam( "Secret", te->bSecret );
pActor->HandleMessage( msg );
}
}
// lua start
#include "LuaBinding.h"
/** @brief Allow Lua to have access to the CourseContentsList. */
class LunaCourseContentsList: public Luna<CourseContentsList>
{
public:
static int SetFromGameState( T* p, lua_State *L ) { p->SetFromGameState(); COMMON_RETURN_SELF; }
LunaCourseContentsList()
{
ADD_METHOD( SetFromGameState );
}
};
LUA_REGISTER_DERIVED_CLASS( CourseContentsList, ActorScroller )
// lua end
/*
* (c) 2001-2004 Chris Danford
* All rights reserved.
*
* 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, and/or sell copies of the Software, and to permit persons to
* whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* 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 OF
* THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS
* INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT
* OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
* OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
| 28.244792 | 124 | 0.698506 | Midiman |
b32301da1cb7c2a96f6380fd55244a4d53b7a467 | 1,156 | cpp | C++ | IocpServer/IocpHandler.cpp | askldjd/iocp-server | ac6b4c5b6980fcd3a20664ec1e8dcc024a481c5e | [
"BSL-1.0"
] | 32 | 2016-05-14T18:51:51.000Z | 2022-03-23T14:14:15.000Z | IocpServer/IocpHandler.cpp | askldjd/iocp-server | ac6b4c5b6980fcd3a20664ec1e8dcc024a481c5e | [
"BSL-1.0"
] | 1 | 2021-12-07T09:07:44.000Z | 2021-12-09T21:07:09.000Z | IocpServer/IocpHandler.cpp | askldjd/iocp-server | ac6b4c5b6980fcd3a20664ec1e8dcc024a481c5e | [
"BSL-1.0"
] | 22 | 2015-12-01T12:25:19.000Z | 2022-03-23T14:14:11.000Z | //! Copyright Alan Ning 2010
//! Distributed under the Boost Software License, Version 1.0.
//! (See accompanying file LICENSE_1_0.txt or copy at
//! http://www.boost.org/LICENSE_1_0.txt)
#include "StdAfx.h"
#include "IocpHandler.h"
#include "IocpServer.h"
namespace iocp {
void CIocpHandler::OnNewConnection( uint64_t, ConnectionInformation const & )
{
}
void CIocpHandler::OnServerError( int /*errorCode*/ )
{
}
void CIocpHandler::OnSentData( uint64_t /*cid*/, uint64_t /*byteTransferred*/ )
{
}
void CIocpHandler::OnReceiveData( uint64_t /*cid*/, std::vector<uint8_t> const &/*data*/ )
{
}
void iocp::CIocpHandler::OnClientDisconnect( uint64_t cid, int32_t )
{
try
{
GetIocpServer().Shutdown(cid, SD_SEND);
GetIocpServer().Disconnect(cid);
}
catch (iocp::CWin32Exception const &)
{
}
catch (iocp::CIocpException const &)
{
}
}
void CIocpHandler::OnServerClose( int32_t /*errorCode*/ )
{
}
void CIocpHandler::OnDisconnect( uint64_t /*cid*/, int32_t /*errorcode*/)
{
}
CIocpServer & CIocpHandler::GetIocpServer()
{
return *m_iocpServer;
}
} // end namespace | 17.784615 | 91 | 0.668685 | askldjd |
b3273e345a61d0540a01c6c887b6cd82cb5c672a | 1,818 | cpp | C++ | llvm/lib/Object/TapiUniversal.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 4,812 | 2015-01-02T19:38:10.000Z | 2022-03-27T12:42:24.000Z | llvm/lib/Object/TapiUniversal.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 71 | 2016-07-26T15:16:53.000Z | 2022-03-31T14:39:47.000Z | llvm/lib/Object/TapiUniversal.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 2,543 | 2015-01-01T11:18:36.000Z | 2022-03-22T21:32:36.000Z | //===- TapiUniversal.cpp --------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines the Text-based Dynamic Library Stub format.
//
//===----------------------------------------------------------------------===//
#include "llvm/Object/TapiUniversal.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Object/Error.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/TextAPI/MachO/TextAPIReader.h"
using namespace llvm;
using namespace MachO;
using namespace object;
TapiUniversal::TapiUniversal(MemoryBufferRef Source, Error &Err)
: Binary(ID_TapiUniversal, Source) {
auto Result = TextAPIReader::get(Source);
ErrorAsOutParameter ErrAsOuParam(&Err);
if (!Result) {
Err = Result.takeError();
return;
}
ParsedFile = std::move(Result.get());
auto Archs = ParsedFile->getArchitectures();
for (auto Arch : Archs)
Architectures.emplace_back(Arch);
}
TapiUniversal::~TapiUniversal() = default;
Expected<std::unique_ptr<TapiFile>>
TapiUniversal::ObjectForArch::getAsObjectFile() const {
return std::unique_ptr<TapiFile>(new TapiFile(Parent->getMemoryBufferRef(),
*Parent->ParsedFile.get(),
Parent->Architectures[Index]));
}
Expected<std::unique_ptr<TapiUniversal>>
TapiUniversal::create(MemoryBufferRef Source) {
Error Err = Error::success();
std::unique_ptr<TapiUniversal> Ret(new TapiUniversal(Source, Err));
if (Err)
return std::move(Err);
return std::move(Ret);
}
| 33.054545 | 80 | 0.610011 | medismailben |
b3277c54f2f9682638c1eabd079b04dc002fd030 | 6,462 | cpp | C++ | software/protoDUNE/protoDUNE/DataDpmSystem.cpp | slaclab/proto-dune | e487ee6d40359b40776098410d7fd302b9631448 | [
"BSD-3-Clause-LBNL"
] | null | null | null | software/protoDUNE/protoDUNE/DataDpmSystem.cpp | slaclab/proto-dune | e487ee6d40359b40776098410d7fd302b9631448 | [
"BSD-3-Clause-LBNL"
] | 2 | 2017-05-11T04:22:27.000Z | 2018-09-18T16:10:29.000Z | software/protoDUNE/protoDUNE/DataDpmSystem.cpp | slaclab/proto-dune | e487ee6d40359b40776098410d7fd302b9631448 | [
"BSD-3-Clause-LBNL"
] | 2 | 2017-04-03T21:59:53.000Z | 2020-12-13T00:14:20.000Z | //-----------------------------------------------------------------------------
// File : DataDpmSystem.h
// Author : Ryan Herbst <rherbst@slac.stanford.edu>
// Created : 06/19/2014
// Project : LBNE DAQ
//-----------------------------------------------------------------------------
// Description :
// DataDpmSystem Top Device
//-----------------------------------------------------------------------------
// This file is part of 'DUNE Development Software'.
// It is subject to the license terms in the LICENSE.txt file found in the
// top-level directory of this distribution and at:
// https://confluence.slac.stanford.edu/display/ppareg/LICENSE.html.
// No part of 'DUNE Development Software', including this file,
// may be copied, modified, propagated, or distributed except according to
// the terms contained in the LICENSE.txt file.
// Proprietary and confidential to SLAC.
//-----------------------------------------------------------------------------
// Modification history :
// 06/19/2014: created
//-----------------------------------------------------------------------------
#include <Register.h>
#include <Variable.h>
#include <Command.h>
#include <CommLink.h>
#include <MultLink.h>
#include <MultDestMapped.h>
#include <MultDestAxis.h>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <DataDpmSystem.h>
#include <DataDpm.h>
#include <DataBuffer.h>
using namespace std;
// Constructor
DataDpmSystem::DataDpmSystem (string defaults, uint32_t idx ) : System("DataDpmSystem") {
stringstream tmp;
MultLink *link;
dest_[0] = new MultDestMapped (15,
0x80000000,0x2000, // Core registers
0x84000000,0x1000, // BSI registers
0xA0000000,0x1000, // DataCompression[0]
0xA0010000,0x1000, // DataCompression[1]
0xA0020000,0x1000, // DataDpmHlsMon
0xA1000000,0x1000, // DataDpmWib[0]
0xA1010000,0x1000, // DataDpmWib[1]
0xA1020000,0x1000, // DataDpmWibDbg[0]
0xA1030000,0x1000, // DataDpmWibDbg[1]
0xA2000000,0x1000, // DataDpmEmu
0xA3000000,0x1000, // DataDpmTiming
0xA4000000,0x1000, // UdpReg
0xA4010000,0x1000, // RssiReg
0xA4020000,0x1000, // PrbsTx
0xA4030000,0x1000); // PrbsRx
//dest_[0]->setDebug(true);
/*
| 2017.04.08 -- jjr
| -----------------
| Adjustmets for the V2 driver
*/
dest_[1] = new MultDestAxis("/dev/axi_stream_dma_0", 0); // Future FEB path???
//dest_[2] = new MultDestAxis("/dev/axi_stream_dma_0",64); // DMA'd Local register Interface
dest_[2] = new MultDestAxis("/dev/axi_stream_dma_1",0); // DMA'd Local register Interface
link = new MultLink();
//link->setDebug(true);
link->setMaxRxTx(0x800000);
link->open(3,dest_[0],dest_[1],dest_[2]);
tmp.str("");
tmp << "DataDpm_" << std::dec << std::setw(3) << setfill('0') << idx;
// Description
desc_ = tmp.str();
defaults_ = defaults;
idx_ = idx;
commLink_ = link;
// Set run states
static const char *States[] = { "Stopped", "Enable" };
vector<string> states (States, States + sizeof (States) /sizeof (*States));
getVariable("RunState")->setEnums(states);
set("HideRunControl","True");
set("HideDataControl","True");
// Disable poll rate by default
getVariable("PollPeriod")->setInt(0);
addDevice(new DataDpm(0x00000000,idx,this));
}
// Deconstructor
DataDpmSystem::~DataDpmSystem ( ) {
delete commLink_;
delete dest_[0];
delete dest_[1];
delete dest_[2];
}
//! Method to perform soft reset
void DataDpmSystem::softReset ( ) {
setRunState("Stopped");
command("CloseDataFile","");
Device::softReset();
allStatusReq_ = true;
System::countReset();
// Removed in favor of the above
//System::softReset();
}
//! Method to perform hard reset
void DataDpmSystem::hardReset ( ) {
errorFlag_ = false;
configureFlag_ = false;
configureMsg_ = "System Is Not Configured.\nSet Defaults Or Load Settings!\n";
setRunState ("Stopped");
command ("CloseDataFile","");
Device::hardReset();
topStatusReq_ = true;
Device::countReset();
// Removed in favor of the above
//System::hardReset();
}
/* ---------------------------------------------------------------------- *//*!
*
* \brief Local method to retrieve the data buffer
* \return A pointer to the data buffer
*
\* ---------------------------------------------------------------------- */
inline DataBuffer *DataDpmSystem::dataBuffer ()
{
DataBuffer *buff = (DataBuffer*)(device("DataDpm", idx_)->device("DataBuffer", 0));
return buff;
}
/* ---------------------------------------------------------------------- */
//! Method to set run state
void DataDpmSystem::setRunState ( string state ) {
static const char Name[] = "DataDpmSystem::setRunState ";
DataBuffer *buff = dataBuffer ();
// Pass run state to device configuration
if ( state == "Enable")
{
buff->enableRun();
cout << Name << state <<" Should be Enable " << endl;
}
else
{
cout << "Stopping Run..." << endl;
cout << "\t\t\t disabling run in buffer" << endl;
buff->disableRun();
cout << Name << state << " Should be Stopped " << endl;
}
getVariable("RunState")->set(state);
allStatusReq_ = true;
// Removed in favor of the above
//System::setRunState(state);
}
//! Method to process a command
void DataDpmSystem::command ( string name, string arg ) {
System::command(name, arg);
}
//! Return local state, specific to each implementation
string DataDpmSystem::localState() {
DataBuffer *buff = dataBuffer ();
uint32_t errors = buff->getInt("RxErrors") + buff->getInt("TxErrors");
uint32_t events = buff->getInt("TxCount");
getVariable("ErrorCount" )->setInt(errors);
getVariable("DataRxCount")->setInt(events);
if ( errors != lastErrors_ ) buffState_ = 2;
else if ( errors > 0 ) buffState_ = 1;
else buffState_ = 0;
lastErrors_ = errors;
if (buffState_)
{
Variable *v = getVariable ("SystemStatus");
if ( v->get() == "Ready" )
{
if ( buffState_ == 1 ) v->set("Warning");
else if ( buffState_ == 2 ) v->set("Error");
}
}
return("");
}
| 28.59292 | 95 | 0.562674 | slaclab |
b32cbaa75e3a7496f340f5d835fafde175b5877c | 1,233 | cpp | C++ | DSA/Graphs/Topological_Sort.cpp | ShrishtiAgarwal/DSA | 8086cc31bef3aefc06a8ea5c7c36fa4aabe7c1df | [
"MIT"
] | null | null | null | DSA/Graphs/Topological_Sort.cpp | ShrishtiAgarwal/DSA | 8086cc31bef3aefc06a8ea5c7c36fa4aabe7c1df | [
"MIT"
] | null | null | null | DSA/Graphs/Topological_Sort.cpp | ShrishtiAgarwal/DSA | 8086cc31bef3aefc06a8ea5c7c36fa4aabe7c1df | [
"MIT"
] | null | null | null | /*
Topological sort using bfs
*/
class Solution {
public:
vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
int in_degree[numCourses];
for(int i=0;i<numCourses;i++)
in_degree[i]=0;
vector<int>q[numCourses];
vector<int>t;
for(int i=0;i<prerequisites.size();i++)
{
int u=prerequisites[i][0];
int v=prerequisites[i][1];
in_degree[u]++;
q[v].push_back(u);
}
queue<int>qp;
for(int i=0;i<numCourses;i++)
{
if(in_degree[i]==0)
qp.push(i);
}
if(qp.empty()==true)
{
vector<int>o;
return o;
}
while(!qp.empty())
{
int j=qp.front();
qp.pop();
t.push_back(j);
for(int i=0;i<q[j].size();i++)
{
in_degree[q[j][i]]--;
if(in_degree[q[j][i]]==0)
qp.push(q[j][i]);
}
}
if(t.size()==numCourses)
return t;
else
{
vector<int>o;
return o;
}
}
}; | 22.418182 | 79 | 0.394972 | ShrishtiAgarwal |
b333b03b2917ac62ad74a0bfaa214bb113a85ef3 | 430 | cc | C++ | P10-FundamentalAlgorithms&AdvancedExercises/P98179.cc | srmeeseeks/PRO1-jutge-FIB | 3af3d28c77ff14a5dbff20b1b5ddc4178462d8a1 | [
"MIT"
] | null | null | null | P10-FundamentalAlgorithms&AdvancedExercises/P98179.cc | srmeeseeks/PRO1-jutge-FIB | 3af3d28c77ff14a5dbff20b1b5ddc4178462d8a1 | [
"MIT"
] | null | null | null | P10-FundamentalAlgorithms&AdvancedExercises/P98179.cc | srmeeseeks/PRO1-jutge-FIB | 3af3d28c77ff14a5dbff20b1b5ddc4178462d8a1 | [
"MIT"
] | null | null | null | //Inserció en taula ordenada
#include <iostream>
#include <vector>
using namespace std;
void insereix(vector<double>& v) {
int tam = v.size();
for (int i = 1; i < tam; ++i) {
double x = v[i];
int j = i;
while (j > 0 && x < v[j - 1]) {
v[j] = v[j - 1];
--j;
}
v[j] = x;
}
}
| 22.631579 | 47 | 0.351163 | srmeeseeks |
b3342d81ae0cdb7f677a1ecf5c5ca693c503cd90 | 1,224 | cpp | C++ | tests/categorytest.cpp | jgcoded/UVA-Arena-Qt | 084cb5031e5faa8a9bfe5256959584a9cb0cf82b | [
"MIT"
] | 1 | 2020-03-02T09:25:44.000Z | 2020-03-02T09:25:44.000Z | tests/categorytest.cpp | jgcoded/UVA-Arena-Qt | 084cb5031e5faa8a9bfe5256959584a9cb0cf82b | [
"MIT"
] | null | null | null | tests/categorytest.cpp | jgcoded/UVA-Arena-Qt | 084cb5031e5faa8a9bfe5256959584a9cb0cf82b | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <iostream>
#include <memory>
#include <QList>
#include <QNetworkAccessManager>
#include <QApplication>
#include <QFrame>
#include <QPushButton>
#include <QVBoxLayout>
#include <QFile>
#include "mainwindow.h"
#include "uhunt/uhunt.h"
#include "uhunt/category.h"
using namespace std;
using namespace uva;
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
/*
Category data file
Download link: https://raw.githubusercontent.com/dipu-bd/uva-problem-category/master/data/CP%20Book3.cat
*/
QString file = "CP-Book-3.cat";
if (!QFile::exists(file)) {
cout << "File does not exist." << endl;
getchar();
return 0;
}
//Get category node
QFile f(file);
if (!f.open(QFile::ReadOnly | QFile::Text))
qDebug() << "Error while reading the file";
const QJsonDocument& jdoc = QJsonDocument::fromJson(f.readAll());
std::shared_ptr<Category> node(Category::fromJsonObject(jdoc.object()));
cout << node->Name.toStdString() << endl;
cout << node->Note.toStdString() << endl;
cout << node->Problems.count() << endl;
cout << node->Branches.count() << endl;
return app.exec();
}
| 23.538462 | 110 | 0.640523 | jgcoded |
b33652c79834a08b143fc9f3818d8e09301810fe | 9,746 | hpp | C++ | src/flow/mergeable_flow.hpp | DARMA-tasking/darma-simple-backend | 3ea4fa297756eddb906f5918fef083e64f1f69e7 | [
"BSD-Source-Code"
] | 1 | 2018-05-29T13:04:16.000Z | 2018-05-29T13:04:16.000Z | src/flow/mergeable_flow.hpp | DARMA-tasking/darma-simple-backend | 3ea4fa297756eddb906f5918fef083e64f1f69e7 | [
"BSD-Source-Code"
] | null | null | null | src/flow/mergeable_flow.hpp | DARMA-tasking/darma-simple-backend | 3ea4fa297756eddb906f5918fef083e64f1f69e7 | [
"BSD-Source-Code"
] | null | null | null | /*
//@HEADER
// ************************************************************************
//
// mergeable_flow.hpp
// DARMA
// Copyright (C) 2017 Sandia Corporation
//
// Under the terms of Contract DE-NA-0003525 with NTESS, LLC,
// the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 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 Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Questions? Contact the DARMA developers (darma-admins@sandia.gov)
//
// ************************************************************************
//@HEADER
*/
#ifndef DARMASIMPLEBACKEND_FLOW_MERGEABLE_FLOW_HPP
#define DARMASIMPLEBACKEND_FLOW_MERGEABLE_FLOW_HPP
#include <shared_mutex>
#include <atomic>
#include <config.hpp>
//namespace simple_backend {
//
//// The object underlying both Flows and AntiFlows which is one layer of
//// abstraction (via pointers) removed from the flows themselves, allowing
//// for efficient implementation of aliasing
//class MergeableTrigger {
//
// private:
//
// using shared_mutex_t = std::shared_timed_mutex;
// using shared_lock_t = std::shared_lock<shared_mutex_t>;
// using unique_lock_t = std::unique_lock<shared_mutex_t>;
// // items are deleted via a SelfDeleting action
// using action_queue_t = types::thread_safe_queue_t<TriggeredActionBase*>;
//
// // We need a shared pointer so that _do_actions() can race with the
// // destructor (or so that actions in the list can delete the MergeableTrigger),
// // and we need an atomic so that _do_actions() can race with add_action()
// // and with the aliasing operation.
// std::shared_ptr<std::atomic<action_queue_t*>> actions_ = { nullptr };
//
// shared_mutex_t aliasing_mutex_;
// // Semantics: once aliased_to_ becomes non-null, it doesn't change for the
// // rest of this object's lifetime
// std::shared_ptr<MergeableTrigger> aliased_to_ = nullptr;
//
// std::atomic<int> counter_ = { 0 };
// std::atomic<bool> triggered_ = { false };
//
// void _do_actions(shared_lock_t aliasing_lock) {
// // make a copy of the shared ptr, so that we can race with the destructor
// auto actions = actions_;
// if(actions == nullptr) return; // unlock happens via aliasing_lock destructor
// // get a view of some queue, either the one we were called with or the
// // one someone else swapped in (do an exchange so that we don't race with
// // the destructor
// auto* my_queue = new action_queue_t(1);
// my_queue = actions->exchange(my_queue);
//
// // as soon as we've exchanged with the action queue, we can release the
// // aliasing lock because it's safe for aliasing to happen
// aliasing_lock.unlock();
//
// // just start with consumed at some number larger than 0
// size_t consumed = 1;
//
// while(my_queue != nullptr and consumed > 0) {
// consumed = my_queue->consume_all([](TriggeredActionBase* action) {
// action->run();
// });
// my_queue = actions->exchange(my_queue);
// }
//
// if(my_queue != nullptr) {
// delete my_queue;
// }
// }
//
// public:
//
// explicit
// MergeableTrigger(int initial_count)
// : counter_(initial_count), actions_(
// std::make_shared<std::atomic<action_queue_t*>>(new action_queue_t(1))
// )
// { }
//
// // Note: add action *cannot* be called at any time after the destructor
// // could have been called
// template <typename Callable>
// void add_action(Callable&& callable) {
// // We can check if it's triggered first and just run on the stack if so
// if(triggered_.load()) {
// callable();
// }
// else {
// std::shared_lock<shared_mutex_t> aliasing_lock(aliasing_mutex_);
// // This only applies if the trigger was aliased while we were waiting to
// // obtain the aliasing_lock
// if(aliased_to_) {
// aliased_to_->add_action(std::forward<Callable>(callable));
// }
// else {
// actions_->load()->push(make_new_self_deleting_action(
// std::forward<Callable>(callable)
// ));
//
// if(triggered_.load()) { _do_actions(std::move(aliasing_lock)); }
// }
//
// } // release the aliasing_lock here if not already released
// }
//
//
// void increment_count() {
// // prevent aliasing while we increment (do we need this?)
// std::shared_lock<shared_mutex_t> aliasing_lock(aliasing_mutex_);
// // semantic assertion: triggers not allowed to increment after going to
// // zero once. This isn't a bulletproof assertion, since setting triggered
// // and the last decrement of counter are separate operations
// assert(not triggered_.load());
// if(aliased_to_) {
// aliased_to_->increment_count();
// }
// else {
// ++counter_;
// }
// }
//
// void advance_count(std::size_t size) {
// // prevent aliasing while we increment
// shared_lock_t aliasing_lock(aliasing_mutex_);
// // semantic assertion: triggers not allowed to increment after going to
// // zero once. This isn't a bulletproof assertion, since setting triggered
// // and the last decrement of counter are separate operations
// assert(not triggered_.load());
// if(aliased_to_) {
// aliased_to_->advance_count(size);
// }
// else {
// counter_ += size;
// }
// }
//
// void decrement_count() {
// // prevent aliasing while we decrement
// shared_lock_t aliasing_lock(aliasing_mutex_);
// // semantic assertion: triggers not allowed to decrement after going to
// // zero once. This isn't a bulletproof assertion, since setting triggered
// // and the last decrement of counter are separate operations
// assert(not triggered_.load());
//
// if(aliased_to_) {
// aliased_to_->decrement_count();
// }
// else if(--counter_ == 0) {
// triggered_.store(true);
// _do_actions(std::move(aliasing_lock));
// }
// }
//
// // returns the pointer that it's actually aliased to
// std::shared_ptr<MergeableTrigger>
// alias_to(std::shared_ptr<MergeableTrigger> other) {
// unique_lock_t my_aliasing_lock(aliasing_mutex_, std::defer_lock);
// unique_lock_t other_aliasing_lock(other->aliasing_mutex_, std::defer_lock);
// std::lock(my_aliasing_lock, other_aliasing_lock);
//
// assert(!other->triggered_.load());
//
// // Make sure another aliasing operation didn't take place while we were
// // waiting for the lock (if it did, alias to that one instead)
// auto to_alias_to = other;
// while(to_alias_to->aliased_to_ != nullptr) {
// to_alias_to = to_alias_to->aliased_to_;
// // Release the old other aliasing lock (at the end of this scope) and
// // grab the new one
// unique_lock_t new_other_aliasing_lock(to_alias_to->aliasing_mutex_);
// std::swap(other_aliasing_lock, new_other_aliasing_lock);
// }
//
// // both are locked (so their counts can't change until we release the
// // locks), so we can add their counts together here
// to_alias_to->counter_ += counter_.exchange(0);
//
// auto* my_actions = actions_->exchange(new action_queue_t(1));
// assert(my_actions);
// assert(to_alias_to->actions_);
// assert(to_alias_to->actions_->load());
//
// to_alias_to->actions_->load()->push(make_new_self_deleting_action([my_actions]{
// my_actions->consume_all([](TriggeredActionBase* action){
// action->run();
// });
// delete my_actions;
// }));
//
// return to_alias_to;
// // Unique locks released at the end of this scope
// }
//
//
// // For approximate debugging purposes only
// std::size_t get_count() const { return counter_.load(); }
//
// // For approximate debugging purposes only
// bool get_triggered() const { return triggered_.load(); }
//
//
// ~MergeableTrigger() {
// auto actions = std::atomic_exchange(&actions_, std::make_shared<std::atomic<action_queue_t*>>());
// delete actions->load();
// }
//
//
//};
//
//} // end namespace simple_backend
#endif //DARMASIMPLEBACKEND_FLOW_MERGEABLE_FLOW_HPP
| 38.521739 | 105 | 0.647548 | DARMA-tasking |
b33907f967ff49758d5a1f84e421620393fb82e4 | 66,803 | hpp | C++ | include/SSDK/Archive/Json/json.hpp | djc80s/c-cpp_study | 3ea8289c358a2b732524ab391aa87c4a8fc0b6a7 | [
"BSD-2-Clause"
] | null | null | null | include/SSDK/Archive/Json/json.hpp | djc80s/c-cpp_study | 3ea8289c358a2b732524ab391aa87c4a8fc0b6a7 | [
"BSD-2-Clause"
] | null | null | null | include/SSDK/Archive/Json/json.hpp | djc80s/c-cpp_study | 3ea8289c358a2b732524ab391aa87c4a8fc0b6a7 | [
"BSD-2-Clause"
] | null | null | null | #ifndef JSONHELPER_H
#define JSONHELPER_H
#include <string>
#include <type_traits>
#include <map>
#include <iostream>
#include <fstream>
#include <memory>
#include <stdio.h>
#include <math.h>
#include <boost/variant/variant.hpp>
#include <boost/variant.hpp>
#include <rapidjson/writer.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/document.h>
//#include <rapidjson/filestream.h>
#include <rapidjson/prettywriter.h>
#include "Exception/customexception.hpp"
#include "TypeTraits/typetraits.hpp"
namespace SSDK
{
namespace Archive
{
/**
* @brief This class is used to wrap Json operation
* 参考:
* 1.refer to <<深入应用c++11>> P310 “rapidjson的基本用法”
* 2.rapidjson首页说明:http://rapidjson.org/zh-cn/
*
* rapidjson基本操作:
* 1.读操作: 从文件,从字符串,从对象(反序列化)
* 2.创建一个Json对象
* 3.写文件: 到文件, 序列化
* 4.查询Object, 查询Array
* 5.修改成员的值
* 6.删除/增加成员
* 7.删除/增加/清空Array的成员
*
* @author rime
* @version 1.00 2017-04-06 rime
* note:create it
*/
class Json
{
public:
//>>>----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//enum & unsing
using JsonWriter = rapidjson::PrettyWriter<rapidjson::StringBuffer>;
/**
*RapidJson的数据类型分为以下几种:
* union Data {
* String s;(可以为null)
* Number n;(bool,int,uint,int64,uint64,double)
* Object o;(复杂对象, 可以包含各种类型的Value,所以它是老大,可以为null)
* Array a;
* };
*
* 这4种类型都成为Value
* */
/**
* @brief The ValueType enum
* Value的类型
* 对于最上层Value的类型(也就是doc), 对于Json只可能是Object和Array
*/
enum ValueType
{
NUMBER,
STRING,
ARRAY,
OBJECT
};
//<<<----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//>>>----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//constructor & deconstructor
/**
* 仅仅是创建一个对象,没有任何数据
*/
Json();
/**
* @brief Json
* 创建Json对象后进行读取操作
* @param str
* 1.当从文件读取时,str表示文件路径
* 2.当从字符串读取时,str表示读取的字符串
* @param isFromString
* true:从字符串读取
* false:从文件读取
*/
Json(const std::string& str, bool isFromString);
Json(const QString &str,bool isFromString);
virtual ~Json();
//<<<----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//>>>----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//get & set functions
rapidjson::Value& doc(){return this->m_doc;}
JsonWriter& write(){return this->m_writer;}
//<<<----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//>>>----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//read functions
/**
* @brief loadFromFile
* 读取一个Json文件
* @param filePath
* 文件路径
* 如果文件不存在或者打开失败,该函数不进行任何操作
*/
void loadFromFile(const std::string& filePath);
void loadFromFile(const QString& filePath);
// void loadFromDoc(const rapidjson::Document& doc);
/**
* @brief parseFromString
* 从字符串解析得到一个Json对象
* @param JsonString
* 对应Json的字符串
*/
void parseFromString(const std::string& jsonString);
void parseFromString(const QString& jsonString);
void parseFromString(const char* jsonStr);
/**
* 返回对象序列化后端的json字符串
*/
const char* toString() ;
/**
* @brief docType
* @return
* 获取Doc的类型, 只可能是Object或者Array
*/
ValueType docType();
//<<<----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//>>>----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//write functions
//>>>-------------------------------------------------------------------------------------------------------------------------------------
//1. write string for json creation
/**
*writeValue 创建一个Json对象的时候通过writeValue写键值对
*/
template<typename V>//int
typename std::enable_if<std::is_same<V, int>::value>::type
writeValue(const V& value);
template<typename V>//int
typename std::enable_if<std::is_same<V, uint>::value>::type
writeValue(const V& value);
template<typename V>//long unsigned int(uint64)
typename std::enable_if<std::is_same<V,uint64_t>::value>::type
writeValue(const V& value);
template<typename V>//int64
typename std::enable_if<std::is_same<V, int64_t>::value>::type
writeValue(const V& value);
template<typename V>//float or double
typename std::enable_if<std::is_floating_point<V>::value>::type
writeValue(const V& value);
template<typename V>//bool
typename std::enable_if<std::is_same<V, bool>::value>::type
writeValue(const V& value);
void writeValue(const char* value);
template<typename V>//null
typename std::enable_if<std::is_same<V, std::nullptr_t>::value>::type
writeValue(const V& value);
template<typename T>
void writeValue(const char* key, const T& value);
/**
* 序列化结构体数组之前需要调用此接口,然后再循环去序列化
*/
void startArray();
void endArray();
/**
*每次写一个对象都要调用startObject函数,结束调用endObject
*/
void startObject();
void endObject();
//>>>-------------------------------------------------------------------------------------------------------------------------------------
//2. serialization
/**
* @brief writeToFile
* 写一个Json对象到文件
* @param filePath
* 文件保存路径
*/
void writeToFile(const QString& filePath);
void writeToFile(const std::string& filePath);
//<<<----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//>>>----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//query function
//>>>-------------------------------------------------------------------------------------------------------------------------------------
//0.Value
/**
* @brief queryValue
* 在obj查找指定key的Value
* @param parentKey
* 父Value的Name
* @param childKey
* 子Value的Name
* @param isFound
* 是否找到对应的Value, 如果找到返回true,否则返回false
* @return
* 返回查找到的Value
*/
rapidjson::Value& queryValue( const char* parentKey, const char* childKey, bool& isFound);
/**
* @brief queryValue
* 在obj查找指定key的对象.
* @param key
* 查找的起始value
* @param isFound
* 输入参数:是否已经到对对象, 找到设置为true, 否则设置为false
* @return
* 返回查找到的Value
*/
rapidjson::Value& queryValue(const char* key, bool& isFound);
/**
* @brief queryValue
* 在obj查找指定key的Value.
* @param obj
* 查找的起始value
* @param key
* 需要查找的对象的name
* @param isFound
* 输入参数:是否已经到对对象, 找到设置为true, 否则设置为false
* @return
* 输出参数:是否已经找到对象
*
* 注意:
* 1.该函数能够遍历json树,
* 如果找到对象key的对象,返回第一个满足条件的对象,返回true
* 如果没有任何满足条件的对象,返回false
*
* 2.该函数只支持在Object中查找, 无法搜索在Array中的对象, rapid中FindMember本身就不支持查找Array对象
*/
static rapidjson::Value& queryValue( rapidjson::Value& obj, const char* key, bool& isFound);
//>>>-------------------------------------------------------------------------------------------------------------------------------------
//1.Number
/**
* @brief queryNumber
* 查询指定key的Number, 包含了多个重载函数
* @param parentKey
* Number所在的上一层Value的Name
* @param childKey
* Number所在的Value的Name
* @return
* 返回查找到的Number
*
* 注意:
* 1.childKey任意一个为key都会抛出异常, parentKey为null时默认从最上层开始查找
* 2.没有key的成员或者key的类型和T的类型不匹配时,会抛出异常
* 3.当key的成员类型为数组时, 会被忽略掉, 最终还是会触发没有找到的异常
* 4.当key的成员存在并类型匹配时,返回该成员
* 5.使用enable_if进行函数的重载时,能够实现仅仅返回参数类型不同的重载(其它方式做不到)
*
*/
template<typename T>
T queryNumber(const char* parentKey, const char* childKey);
/**
*和上面的重载函数类似,只不过没有parentKey参数,那么默认就是从json的最上层开始检索
* 这样可能存在Json文件中不同的Object中含有相同Name的Value, 这种情况下类型不一致就会引发异常
*/
template<typename T>
T queryNumber(const char* key);
/**
* @brief queryNumber
* 查询指定key的Number
* @param value
* 查找Number所在的父Value
* @param key
* Number所在的Value的Name
* @param isFound
* 是否已经找到, 找到返回true, 没找到的话返回false
* @return
* 查找到的Number, isFound为false, 请忽略该值
*/
template<typename T>
static T queryNumber(rapidjson::Value& value,const char* key,bool& isFound);
//>>>-------------------------------------------------------------------------------------------------------------------------------------
//2.String
/**
* @brief queryString
* 查询指定key的Number, 包含了多个重载函数
* @param parentKey
* String所在的上一层Value的Name
* @param childKey
* String所在的Value的Name
* @return
* 返回查找到的String
*
* 注意:
* 1.childKey任意一个为key都会抛出异常, parentKey为null时默认从最上层开始查找
* 2.没有key的成员或者key的类型和T的类型不匹配时,会抛出异常
* 3.当key的成员类型为数组时, 会被忽略掉, 最终还是会触发没有找到的异常
* 4.当key的成员存在并类型匹配时,返回该成员
*
*/
const char* queryString(const char* parentKey, const char* childKey);
/**
*和上面的重载函数类似,只不过没有parentKey参数,那么默认就是从json的最上层开始检索
* 这样可能存在Json文件中不同的Object中含有相同Name的Value, 这种情况下类型不一致就会引发异常
*/
const char* queryString(const char* key);
static const char* queryString(rapidjson::Value& value,bool& isTypeMatched);
static const char* queryString(rapidjson::Value& value, const char* key, bool& isFound);
//>>>-------------------------------------------------------------------------------------------------------------------------------------
//3.Array
/**
* 查询指定key的Array, 包含了多个重载函数
*
* 注意:
* 1.对于数组来说
* 返回Value, 因为Array中可能包含不同的类型, 由调用方进一步解析
* 当Array的所有成员都属于同一类型的话,那么可以直接返回一个vector, 但是需要进行类型验证
* 2.支持嵌套在一个Object层级结构中的数组对象的查询, 即Array并不是在Object的最上层
* 3.rapidjson不支持数组嵌套数组的情况(包括最新的版本)
*/
/**
* @brief querryArray
* 查询指定key的Array
* @param parentObjKey
* 父Object的Name
* @param arrayName
* Array的Name
* @param isFound
* 输入参数:是否已经到对对象, 找到设置为true, 否则设置为false
* @return
* 找到的Array类型的Value
*/
rapidjson::Value& queryArray(const char* parentObjKey, const char* arrayName, bool& isFound);
/**
*和上面的重载函数类似,只不过没有parentObjKey参数,那么默认就是从json的最上层开始检索
* 这样可能存在Json文件中不同的Object中含有相同Name的Value, 这种情况下类型不一致就会引发异常
*/
rapidjson::Value& queryArray(const char* arrayName, bool& isFound);
/**
* @brief queryArray
* 查询指定key的Array
* @param parentObjKey
* 父Object的Name
* @param arrayName
* 需要查找的数组的arrayName
* @param vector
* 输出参数, 查找到的对象放置在这个vector容器中
* @return
* 查询成功返回true, 否则返回false
*
* 注意:
* 只有当Array的成员类型完全一样时才生效, 否则返回false
*/
template<typename T>
bool queryArray(const char* parentObjKey,const char* arrayName, std::vector<T>& vector);
/**
* @brief queryArray
* 查询指定key的Array
* @param arrayName
* 需要查找的数组的arrayName
* @param vector
* 输出参数, 查找到的对象放置在这个vector容器中
* @return
* 查询成功返回true, 否则返回false
*
* 注意:
* 只有当Array的成员类型完全一样时才生效, 否则返回false
*/
template<typename T>
bool queryArray(const char* arrayName, std::vector<T>& vector);
/**
* @brief queryDocArrayBasedOnIndex
* 当doc为array类型时, 根据返回对象的值
* @param index
* Array的索引
* @param elementName
* 数组成员的名称
* @return
* 返回的值
*
* 注意:
* 1.只有当doc为Array类型时,才能调用该方法, 否则会抛出异常
* 2.doc为Array时, elememt一般为简单类型, 即Number和String
* 3.elementName不能为null, 否则会抛出异常
*/
template<typename T>
typename std::enable_if<
(std::is_same<T, bool>::value)||
(std::is_same<T, int>::value)||
(std::is_same<T, uint>::value)||
(std::is_same<T, int64_t>::value)||
(std::is_same<T,uint64_t>::value)||
(std::is_same<T, double>::value),T>::type
queryNumberOfDocArray( int index, const char* elementName);
const char* queryStringOfDocArray( int index, const char* elementName);
// template<typename T>
// T queryDocArrayBasedOnIndex( int objIndex , int elementIndex);
/**
* @brief queryEmbededArrayElementBasedOnIndex
* 当doc不是array类型时, 即array作为doc的一个嵌入数组, 根据索引返回对象的值
* @param parentObjKey
* array对象所在的父对象的Key
* @param arrayName
* 嵌入对象的Name
* @param index
* 访问对象的索引
* @return
* 返回的值
*
* 注意:
* 该函数只有在数组中所有成员的类型一致时才能时候, 否则将抛出异常
*/
template<typename T>
T queryEmbededArrayBasedOnIndex(const char* parentObjKey,const char* arrayName, uint index);
template<typename T>
T queryEmbededArrayBasedOnIndex(const char* arrayName, uint index);
template<typename T>
T queryLastElementOfEmbededArray(const char* parentObjKey,const char* arrayName);
template<typename T>
T queryLastElementOfEmbededArray(const char* arrayName);
template<typename T>
T queryFirstElementOfEmbededArray(const char* parentObjKey,const char* arrayName);
template<typename T>
T queryFirstElementOfEmbededArray(const char* arrayName);
/**
* @brief getArrayCount
* 获取到Array成员的数量
* @param parentObjKey
* Array所在的父Value
* @param arrayName
* Array的名称
* @return
* Array成员的数量
*
* 当获取失败时, 返回-1
*/
int getArrayCount(const char* parentObjKey, const char* arrayName);
/**
*和上面的重载函数类似,只不过没有parentObjKey参数,那么默认就是从json的最上层开始检索
* 这样可能存在Json文件中不同的Object中含有相同Name的Value, 这种情况下类型不一致就会引发异常
*/
int getArrayCount(const char* arrayName);
/**
* @brief getArrayCount
* 当Doc为Array类型时,返回其长度
* @return
* Doc为数组的长度, 当Doc不是数组时,返回-1
*/
int getArrayCount();
//<<<----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//>>>----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//modify functions
//>>>-------------------------------------------------------------------------------------------------------------------------------------
//1.Number
/**
* @brief modifyNumber
* 修正指定key的value, 包含如下行为
* 对于Number, 具体是bool, int, uint, int64, uint64, double
* @param parentKey
* 父对象的name
* @param childKey
* 子对象的name
* @param value
* 需要修正的值
*
* * 注意:
* 1.没有key的成员或者key的类型和T的类型不匹配时,会抛出异常
* 2.当key的成员存在并类型匹配时,会修正该值
* 3.虽然下面几个函数都是模板函数, 可以支持任何类型的输入, 但是内部调用的modify模板函数都是有类型收窄的, 一旦都不支持的类型输入,编译将报错
* 4.不支持原来是Number类型的成员对象设置为指定类型( 官方文档没有类似的set函数 )
*/
template<typename T>
void modifyNumber(const char* parentKey, const char* childKey, const T& value);
template<typename T>
void modifyNumber(const char* key, const T& value);//主要用于const char*/char* ,这2中类型不会调用上面的重载
//>>>-------------------------------------------------------------------------------------------------------------------------------------
//2.String
/**
* @brief modifyString
* 修正指定key的value, 包含如下行为
* 对于String类型, 原来是null类型的对象可以设置为string
* @param parentKey
* 父Value的name
* @param childKey
* 需要修改的value的name
*
* @param value
* 需要查找的值
*
* * 注意:
* 1.没有key的成员或者key的类型和T的类型不匹配时,会抛出异常
* 2.当key的成员存在并类型匹配时,会修正该值
* 3.虽然下面几个函数都是模板函数, 可以支持任何类型的输入, 但是内部调用的modify模板函数都是有类型收窄的, 一旦都不支持的类型输入,编译将报错
* 4.不支持原来是null类型的成员对象设置为指定类型( 官方文档没有类似的set函数 )
* 5.不支持直接修正一个Value类型的成员(即需要指定到基础类型,如Number和String的修改,大对象的修改需要分解到小对象, 官方文档没有类似的set函数)
*/
void modifyString(const char* parentKey, const char* childKey, const char* value);
void modifyString(const char* key, const char* value);
//>>>-------------------------------------------------------------------------------------------------------------------------------------
//3.Array
/**
* 修改指定key的Array, 包含如下行为
* 1. 增加成员
* 2. 删除成员
* 3. 清空Array
* 4. 修改成员
*/
/**
* @brief pushValBackToArray
* 在Array末尾插入Value成员
* @param parentKey
* 父对象的Key
* @param childkey
* Array的Key
* @param newElementVal
* 待插入的Value
* @return
* 插入成功返回true, 插入失败返回false
*
* 注意:
* 1.当没有找到指定Key的Array,抛出异常
* 2.当插入的Val类型无法匹配Array中现有成员的类型,抛出异常
*/
bool pushValBackToArray(const char* parentKey, const char* childkey, rapidjson::Value& newElementVal);
bool pushValBackToArray(const char* key, rapidjson::Value& newElementVal);
/**
* @brief pushNumberBackToArray
* 在Array末尾插入一个Number成员
* @param parentKey
* 父对象的Key
* @param childkey
* Array的Key
* @param newElementVal
* 待插入的Value
* @return
* 插入成功返回true, 插入失败返回false
*
* 注意:
* 1.当没有找到指定Key的Array,抛出异常
* 2.当插入的Val类型无法匹配Array中现有成员的类型,抛出异常
*/
template<typename T>
typename std::enable_if<
(std::is_same<T, bool>::value)||
(std::is_same<T, int>::value)||
(std::is_same<T, uint>::value)||
(std::is_same<T, int64_t>::value)||
(std::is_same<T, double>::value), bool>::type
pushNumberBackToArray(const char* parentKey,const char* childkey, const T& newElementVal);
template<typename T>
typename std::enable_if<
(std::is_same<T, bool>::value)||
(std::is_same<T, int>::value)||
(std::is_same<T, uint>::value)||
(std::is_same<T, int64_t>::value)||
(std::is_same<T, double>::value), bool>::type
pushNumberBackToArray(const char* key, const T& newElementVal);
/**
* @brief pushStringBackToArray
* 在Array末尾插入Value成员
* @param parentkey
* 父对象的Key
* @param childkey
* Array的Key
* @param newElementVal
* 待插入的Value
* @return
* 插入成功返回true, 插入失败返回false
*/
bool pushStringBackToArray(const char *parentkey,const char *childkey, const char *newElementVal);
bool pushStringBackToArray(const char* key, const char* newElementVal);
/**
* @brief popBackFromArray
* 移除Array末尾的成员
* @param parentkey
* 父对象的Key
* @param childKey
* Array的Key
* @return
* 插入成功返回true, 插入失败返回false
*/
bool popBackFromArray(const char *parentkey,const char* childKey);
bool popBackFromArray(const char* key);
bool clearArray(const char *parentkey,const char *childKey);
bool clearArray(const char* key);
/**
* @brief modifyElementOfArrayBasedOnIndex
* 修改Array指定index的值
* @param parentKey
* Array的父对象的Key
* @param childKey
* Array的Key
* @param index
* 修改Array的Index
* @param value
* 待修改的值
*
* 注意
* 涉及到修改单个成员:
* 1.如果Array的成员是复杂类型, 即成员由不同类型的Object组成,请使用queryArray得到数组的Array, 然后再手动修改
* 2.如果Array的成员是简单类型, 请使用modifyArrayElementBasedOnIndex修改
*/
template<typename T>
bool modifyNumberElementOfArrayBasedOnIndex(const char* parentKey,const char* childKey, uint index, const T& value);
template<typename T>
bool modifyNumberElementOfArrayBasedOnIndex(const char* key, uint index, const T& value);
bool modifyStringElementOfArrayBasedOnIndex(const char* parentKey,const char* childKey, uint index, const char* value);
bool modifyStringElementOfArrayBasedOnIndex(const char* key, uint index, const char* value);
//>>>-------------------------------------------------------------------------------------------------------------------------------------
//4.Object
/**
* 添加删除成员操作,
* 1.这里的操作是指针对Object类型的Value, 可以添加和删除成员, 不包括基础类型(Number&String)和Array
* 2.不同于查询, add/remove 的成员可能是复杂的对象,如果再进一步拆解成基础类型会很不方便,同时官网API也只是支持到Value
*/
/**
* @brief addValueToObject
* 增加一个Value到Object
* @param parentKey
* 需要被添加的Object的value
* @param childKey
* 需要添加的子Value的name
* @param childValue
* 需要添加的Value
*
*/
void addValueToObject(const char* parentKey, const char* childKey, const char* memName, rapidjson::Value& childValue);
void addValueToObject(const char *key,const char* memName, rapidjson::Value &childValue);
/**
* @brief Json::addStringToObject
* 增加一个String到Object
* @param parentKey
* Object所在的父Object的name
* @param childKey
* Object的name
* @param memName
* 待添加的Object的name
* @param memVal
* 待添加的Object的value
*/
void addStringToObject(const char *parentKey, const char *childKey, const char *memName, const char* memVal);
void addStringToObject(const char *key, const char *memName, const char* memVal);
/**
* @brief addNumberToObject
* 增加一个Number到Object
* @paramt T
* 待添加Number的类型,这里可以为bool,int,uint,int64,uint64和double
* @param parentKey
* Object所在的父Object的name
* @param childKey
* Object的name
* @param memName
* 待添加的Object的name
* @param memVal
* 待添加的Object的value
*/
template<typename T>
typename std::enable_if<
(std::is_same<T, bool>::value)||
(std::is_same<T, int>::value)||
(std::is_same<T, uint>::value)||
(std::is_same<T, int64_t>::value)||
(std::is_same<T,uint64_t>::value)||
(std::is_same<T, double>::value)>::type
addNumberToObject(const char *parentKey, const char *childKey, const char *memName, const T& memVal);
template<typename T>
typename std::enable_if<
(std::is_same<T, bool>::value)||
(std::is_same<T, int>::value)||
(std::is_same<T, uint>::value)||
(std::is_same<T, int64_t>::value)||
(std::is_same<T,uint64_t>::value)||
(std::is_same<T, double>::value)>::type
addNumberToObject(const char *key, const char *memName, const T& memVal);
/**
* @brief removeMemberFromObject
* 从Object中移除成员
* @param parentKey
* Object所在的父Object的name
* @param childKey
* Object的name
* @param memName
* 待添加的Object的name
*/
void removeMemberFromObject(const char *parentKey, const char *childKey,const char *memName);
void removeMemberFromObject(const char *key,const char *memName);
private:
//>>>----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//member variant
rapidjson::StringBuffer m_buf;
JsonWriter m_writer;
rapidjson::Document m_doc;
//是否需要重新accept, 默认不需要, 但是当发生修改时,需要重写accept
bool m_isReAccept{false};
//<<<----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//>>>----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//query functions
//>>>-------------------------------------------------------------------------------------------------------------------------------------
//1.Number
/**
*queryNumber 在Value查询不同类型的Number
*/
template<typename T>
typename std::enable_if<std::is_same<T, bool>::value, T>::type//bool
static queryNumber(rapidjson::Value& value, bool& isTypeMatched);
template<typename T>
typename std::enable_if<std::is_same<T, int>::value, T>::type//int
static queryNumber(rapidjson::Value& value, bool& isTypeMatched);
template<typename T>
typename std::enable_if<std::is_same<T, uint>::value, T>::type//uint
static queryNumber(rapidjson::Value& value, bool& isTypeMatched);
template<typename T>
typename std::enable_if<std::is_same<T, int64_t>::value, T>::type//int64
static queryNumber(rapidjson::Value& value, bool& isTypeMatched);
template<typename T>
typename std::enable_if<std::is_same<T, uint64_t>::value, T>::type//uint64
static queryNumber(rapidjson::Value& value, bool& isTypeMatched);
template<typename T>
typename std::enable_if<std::is_same<T,double>::value, T>::type//double or float
static queryNumber(rapidjson::Value& value, bool& isTypeMatched);
//>>>-------------------------------------------------------------------------------------------------------------------------------------
//2.string
//...
//>>>-------------------------------------------------------------------------------------------------------------------------------------
//3.Array
/**
* @brief queryArray
* 查询指定key的Array
* @param parentObj
* 查找数组的起始Object
* @param arrayName
* 需要查找的数组的name
* @param resVal
* 输出参数, 查找到的对象
* @return
* 是否已经找到对象, 找到的话返回true;否则返回false
*
*/
rapidjson::Value& queryArray( rapidjson::Value& parentObj, const char* arrayName, bool& isFound);
//>>>-------------------------------------------------------------------------------------------------------------------------------------
//4.Object
//...
//<<<----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//>>>----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//modify functions
//>>>-------------------------------------------------------------------------------------------------------------------------------------
//1.Number
/**
*以下的重载modify函数都是用于按照类型modify对应的key值
* 1.当输入的模板类型不支持或者模板类型与key值类型不符合时,返回false
* 2.设置成功返回true
*/
template<typename T>
typename std::enable_if<std::is_same<T, bool>::value, bool>::type//bool
modifyNumber( rapidjson::Value& val, const T& value);
template<typename T>
typename std::enable_if<std::is_same<T, int>::value, bool>::type//int
modifyNumber( rapidjson::Value& val, const T& value);
template<typename T>
typename std::enable_if<std::is_same<T, uint>::value, bool>::type//uint
modifyNumber( rapidjson::Value& val, const T& value);
template<typename T>
typename std::enable_if<std::is_same<T, int64_t>::value, bool>::type//int64_t
modifyNumber( rapidjson::Value& val, const T& value);
template<typename T>
typename std::enable_if<std::is_same<T, uint64_t>::value, bool>::type//uint64_t
modifyNumber( rapidjson::Value& val, const T& value);
template<typename T>
typename std::enable_if<std::is_same<T, double>::value, bool>::type//double
modifyNumber( rapidjson::Value& val, const T& value);
//>>>-------------------------------------------------------------------------------------------------------------------------------------
//2.String
bool modifyString( rapidjson::Value& val, const char* value);
//>>>-------------------------------------------------------------------------------------------------------------------------------------
//3.Array
/**
*以下几个重载函数:pushElementToVector
* 在Array所有成员类型全部一致,并且为简单类型(string, number, nullptr)的情况下封装到一个外部传入的vector中
*/
template<typename T>
typename std::enable_if<std::is_same<T, bool>::value, bool>::type//bool
pushElementOfArrayToVector(const rapidjson::Value::ConstValueIterator& arrayElementVal, std::vector<T>& vector)const;
template<typename T>
typename std::enable_if<std::is_same<T, int>::value, bool>::type//int
pushElementOfArrayToVector(const rapidjson::Value::ConstValueIterator& arrayElementVal, std::vector<T>& vector)const;
template<typename T>
typename std::enable_if<std::is_same<T, int64_t>::value, bool>::type//int64_t
pushElementOfArrayToVector(const rapidjson::Value::ConstValueIterator& arrayElementVal, std::vector<T>& vector)const;
template<typename T>
typename std::enable_if<std::is_same<T, uint64_t>::value, bool>::type//uint64_t
pushElementOfArrayToVector(const rapidjson::Value::ConstValueIterator& arrayElementVal, std::vector<T>& vector)const;
template<typename T>
typename std::enable_if<std::is_same<T, double>::value, bool>::type//double
pushElementOfArrayToVector(const rapidjson::Value::ConstValueIterator& arrayElementVal, std::vector<T>& vector)const;
template<typename T>
typename std::enable_if<std::is_same<T, std::string>::value, bool>::type//string
pushElementOfArrayToVector(const rapidjson::Value::ConstValueIterator& arrayElementVal, std::vector<T>& vector)const;
template<typename T>
typename std::enable_if<std::is_same<char*, T>::value || std::is_same<const char*,T>::value, bool>::type//char* or const char*
pushElementOfArrayToVector(const rapidjson::Value::ConstValueIterator& arrayElementVal, std::vector<T>& vector)const;
//>>>-------------------------------------------------------------------------------------------------------------------------------------
//4.Object
//...
//<<<----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
};//End of Json
}//End of namespace Archive
}//End of namespace SSDK
//>>>----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//write functions
template<typename V>//int
typename std::enable_if<std::is_same<V, int>::value>::type
SSDK::Archive::Json::writeValue(const V& value)
{
m_writer.Int(value);
}
template<typename V>//int
typename std::enable_if<std::is_same<V, uint>::value>::type
SSDK::Archive::Json::writeValue(const V& value)
{
m_writer.Uint(value);
}
template<typename V>//long unsigned int(uint64)
typename std::enable_if<std::is_same<V,uint64_t>::value>::type
SSDK::Archive::Json::writeValue(const V& value)
{
m_writer.Uint64(value);
}
template<typename V>//int64
typename std::enable_if<std::is_same<V, int64_t>::value>::type
SSDK::Archive::Json::writeValue(const V& value)
{
m_writer.Int64(value);
}
template<typename V>//float or double
typename std::enable_if<std::is_floating_point<V>::value>::type
SSDK::Archive::Json::writeValue(const V& value)
{
m_writer.Double(value);
}
template<typename V>//bool
typename std::enable_if<std::is_same<V, bool>::value>::type
SSDK::Archive::Json::writeValue(const V& value)
{
m_writer.Bool(value);
}
template<typename V>//null
typename std::enable_if<std::is_same<V, std::nullptr_t>::value>::type
SSDK::Archive::Json::writeValue(const V& value)
{
m_writer.Null();
}
template<typename T>
void SSDK::Archive::Json::writeValue(const char* key, const T& value)
{
m_writer.String(key);
writeValue(value);
}
//<<<----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//>>>----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//query functions
//>>>-------------------------------------------------------------------------------------------------------------------------------------
//1.Number
template<typename T>
T SSDK::Archive::Json::queryNumber(const char* key)
{
return queryNumber<T>(nullptr, key);
}
template<typename T>
T SSDK::Archive::Json::queryNumber(const char* parentKey, const char* childKey)
{
using namespace rapidjson;
bool isFound = false;
auto& childVal = queryValue(parentKey,childKey,isFound);//找出子Value
if(isFound)
{
bool isTypeMatched = false;
auto val = queryNumber<T>(childVal,isTypeMatched);
if(!isTypeMatched)
{
THROW_EXCEPTION_WITH_OBJ("Type of Member["+std::string(childKey)+"] is not matched!");
}
else
{
return val;
}
}
else
{
THROW_EXCEPTION_WITH_OBJ("Member["+std::string(childKey)+"] is not found!");
}
}
template<typename T>
typename std::enable_if<std::is_same<T, bool>::value, T>::type//bool
SSDK::Archive::Json::queryNumber(rapidjson::Value& value, bool& isTypeMatched)
{
isTypeMatched = false;
if(value.IsBool())
{
isTypeMatched = true;
return value.GetBool();
}
else
{
return false;
}
}
template<typename T>
T SSDK::Archive::Json::queryNumber(rapidjson::Value& value,const char* key,bool& isFound)
{
isFound = false;
auto& val = queryValue(value,key, isFound);
return queryNumber<T>(val,isFound);
}
template<typename T>
typename std::enable_if<std::is_same<T, int>::value, T>::type//int
SSDK::Archive::Json::queryNumber(rapidjson::Value& value, bool& isTypeMatched)
{
isTypeMatched = false;
if(value.IsInt())
{
isTypeMatched = true;
return value.GetInt();
}
else
{
return 0;
}
}
template<typename T>
typename std::enable_if<std::is_same<T, uint>::value, T>::type//uint
SSDK::Archive::Json::queryNumber(rapidjson::Value& value, bool& isTypeMatched)
{
isTypeMatched = false;
if(value.IsUint())
{
isTypeMatched = true;
return value.GetUint();
}
else
{
return 0;
}
}
template<typename T>
typename std::enable_if<std::is_same<T, int64_t>::value, T>::type//int64
SSDK::Archive::Json::queryNumber(rapidjson::Value& value, bool& isTypeMatched)
{
isTypeMatched = false;
if(value.IsInt64())
{
isTypeMatched = true;
return value.GetInt64();
}
else
{
return 0;
}
}
template<typename T>
typename std::enable_if<std::is_same<T, uint64_t>::value, T>::type//uint64
SSDK::Archive::Json::queryNumber(rapidjson::Value& value, bool& isTypeMatched)
{
isTypeMatched = false;
if(value.IsUint64())
{
isTypeMatched = true;
return value.GetUint64();
}
else
{
return 0;
}
}
template<typename T>
typename std::enable_if<std::is_same<T,double>::value, T>::type//double or float
SSDK::Archive::Json::queryNumber(rapidjson::Value& value, bool& isTypeMatched)
{
isTypeMatched = false;
if(value.IsDouble())
{
isTypeMatched = true;
return value.GetDouble();
}
else
{
return 0.0;
}
}
//>>>-------------------------------------------------------------------------------------------------------------------------------------
//2.String
//>>>-------------------------------------------------------------------------------------------------------------------------------------
//3.Array
template<typename T>
bool SSDK::Archive::Json::queryArray(const char* arrayName, std::vector<T>& vector)
{
using namespace rapidjson;
bool isFound = false;
auto& val = queryArray(this->m_doc, arrayName, isFound);;
if(isFound && val.IsArray())
{
//注意,这里要使用Begin(), 而不是MemberBegin
for (auto itr = val.Begin(); itr != val.End(); ++itr)
{
pushElementOfArrayToVector(itr,vector);
}
return true;
}
else
{
return false;
}
}
template<typename T>
bool SSDK::Archive::Json::queryArray(const char* parentObjKey,const char* arrayName, std::vector<T>& vector)
{
using namespace rapidjson;
bool isFound = false;
auto& val = queryValue(parentObjKey, arrayName, isFound);;
if(isFound && val.IsArray())
{
//注意,这里要使用Begin(), 而不是MemberBegin
for (auto itr = val.Begin(); itr != val.End(); ++itr)
{
pushElementOfArrayToVector(itr,vector);
}
return true;
}
else
{
return false;
}
}
template<typename T>
typename std::enable_if<
(std::is_same<T, bool>::value)||
(std::is_same<T, int>::value)||
(std::is_same<T, uint>::value)||
(std::is_same<T, int64_t>::value)||
(std::is_same<T,uint64_t>::value)||
(std::is_same<T, double>::value),T>::type
SSDK::Archive::Json::queryNumberOfDocArray( int index, const char* elementName)
{
if(nullptr == elementName)
{
THROW_EXCEPTION_WITH_OBJ("Element Name can not be nullptr");
}
if(this->m_doc.IsArray())
{
int elementCnt = this->m_doc.Size();
if(index<0 || index>elementCnt-1)
{
std::ostringstream stream;
stream<<"Index["<<index<<"] is invaild, it must be in[0,"<<elementCnt - 1<<"]";
THROW_EXCEPTION_WITH_OBJ( stream.str());
}
else
{
bool isFound {false};
auto& value = queryValue( this->m_doc[index],elementName,isFound);
if(!isFound)
{
THROW_EXCEPTION_WITH_OBJ("Array[Name:"+std::string(elementName)+"] is not found!" );
}
else
{
bool isMatched {false};
return queryNumber<T>(value,isMatched);
}
}
}
else
{
THROW_EXCEPTION_WITH_OBJ("Doc must be array type");
}
}
template<typename T>
T SSDK::Archive::Json::queryEmbededArrayBasedOnIndex(const char* parentObjKey,const char* arrayName, uint index)
{
using namespace rapidjson;
std::vector<T> vector;
bool isFound = queryArray(parentObjKey,arrayName,vector);
if(!isFound)
{
THROW_EXCEPTION_WITH_OBJ("Array[Name:"+std::string(arrayName)+"] is not found!" );
}
else
{
if(index > vector.size())
{
std::ostringstream stream;
stream<<"Index["<<index<<"] is invaild, it must be in[0,"<<vector.size()<<"]";
THROW_EXCEPTION_WITH_OBJ( stream.str() );
}
else
{
return vector[index];
}
}
return true;
}
template<typename T>
T SSDK::Archive::Json::queryEmbededArrayBasedOnIndex(const char* arrayName, uint index)
{
return queryEmbededArrayBasedOnIndex<T>(nullptr,arrayName,index);
}
template<typename T>
T SSDK::Archive::Json::queryLastElementOfEmbededArray(const char* parentObjKey,const char* arrayName)
{
using namespace rapidjson;
std::vector<T> vector;
bool isFound = queryArray(parentObjKey,arrayName,vector);
if(!isFound)
{
THROW_EXCEPTION_WITH_OBJ("Array[Name:"+std::string(arrayName)+"] is not found!" );
}
else
{
if(vector.size()==0)
{
return vector[0];
}
else
{
return vector[vector.size()-1];
}
}
}
template<typename T>
T SSDK::Archive::Json::queryLastElementOfEmbededArray(const char* arrayName)
{
return queryLastElementOfEmbededArray<T>(nullptr,arrayName);
}
template<typename T>
T SSDK::Archive::Json::queryFirstElementOfEmbededArray(const char* parentObjKey,const char* arrayName)
{
using namespace rapidjson;
std::vector<T> vector;
bool isFound = queryArray(parentObjKey,arrayName,vector);
if(!isFound)
{
THROW_EXCEPTION_WITH_OBJ("Array[Name:"+std::string(arrayName)+"] is not found!" );
}
else
{
if(!isFound)
{
THROW_EXCEPTION_WITH_OBJ("Array[Name:"+std::string(arrayName)+"] is not found!" );
}
else
{
return vector[0];
}
}
// return true;
}
template<typename T>
T SSDK::Archive::Json::queryFirstElementOfEmbededArray(const char* arrayName)
{
return queryFirstElementOfEmbededArray<T>(nullptr, arrayName);
}
//<<<----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//>>>----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//modify functions
//>>>-------------------------------------------------------------------------------------------------------------------------------------
//1.Number
template<typename T>
void SSDK::Archive::Json::modifyNumber(const char* parentKey, const char* childKey, const T& value)
{
using namespace rapidjson;
bool isFound{false};
auto& val = queryValue(parentKey,childKey,isFound);
if(isFound)//对于rapidjson v1.0 需要判断是否为0, 对于最新的v1.1 要判断是否为EndMember
{
if(!modifyNumber<T>(val, value))
{
THROW_EXCEPTION_WITH_OBJ("Member["+std::string(parentKey)+"] is bool type!");
}
this->m_isReAccept = true;
}
else
{
THROW_EXCEPTION_WITH_OBJ("Member["+std::string(parentKey)+"] is not found!");
}
}
template<typename T>
void SSDK::Archive::Json::modifyNumber(const char* key, const T& value)//主要用于const char*/char* ,这2中类型不会调用上面的重载
{
modifyNumber(nullptr,key,value);
}
template<typename T>
typename std::enable_if<std::is_same<T, bool>::value, bool>::type//bool
SSDK::Archive::Json::modifyNumber( rapidjson::Value& val, const T& value)
{
if(val.IsBool())
{
val.SetBool(value);
return true;
}
else
{
return false;
}
}
template<typename T>
typename std::enable_if<std::is_same<T, int>::value, bool>::type//int
SSDK::Archive::Json::modifyNumber( rapidjson::Value& val, const T& value)
{
if(val.IsInt())
{
val.SetInt(value);
return true;
}
else
{
return false;
}
}
template<typename T>
typename std::enable_if<std::is_same<T, uint>::value, bool>::type//uint
SSDK::Archive::Json::modifyNumber( rapidjson::Value& val, const T& value)
{
if(val.IsUint())
{
val.SetUint(value);
return true;
}
else
{
return false;
}
}
template<typename T>
typename std::enable_if<std::is_same<T, int64_t>::value, bool>::type//int64_t
SSDK::Archive::Json::modifyNumber( rapidjson::Value& val, const T& value)
{
if(val.IsInt64())
{
val.SetInt64(value);
return true;
}
else
{
return false;
}
}
template<typename T>
typename std::enable_if<std::is_same<T, uint64_t>::value, bool>::type//uint64_t
SSDK::Archive::Json::modifyNumber( rapidjson::Value& val, const T& value)
{
if(val.IsUint64())
{
val.SetUint64(value);
return true;
}
else
{
return false;
}
}
template<typename T>
typename std::enable_if<std::is_same<T, double>::value, bool>::type//double
SSDK::Archive::Json::modifyNumber( rapidjson::Value& val, const T& value)
{
if(val.IsDouble())
{
val.SetDouble(value);
return true;
}
else
{
return false;
}
}
//>>>-------------------------------------------------------------------------------------------------------------------------------------
//3.Array
/**
* @brief modifyElementOfArrayBasedOnIndex
* 修改Array指定index的值
* @param parentKey
* Array的父对象的Key
* @param childKey
* Array的Key
* @param index
* 修改Array的Index
* @param value
* 待修改的值
*
* 注意
* 涉及到修改单个成员:
* 1.如果Array的成员是复杂类型, 即成员由不同类型的Object组成,请使用queryArray得到数组的Array, 然后再手动修改
* 2.如果Array的成员是简单类型, 请使用modifyArrayElementBasedOnIndex修改
*/
template<typename T>
bool SSDK::Archive::Json::modifyNumberElementOfArrayBasedOnIndex(const char* parentKey,const char* childKey, uint index, const T& value)
{
using namespace rapidjson;
bool isFound = false;
auto& val = queryValue(parentKey,childKey,isFound);
if(isFound && val.IsArray())
{
if(index<0 || index > val.Size())
{
std::ostringstream stream;
stream<<"Index["<<index<<"] is invaild, it must be in[0,"<<val.Size()<<"]";
THROW_EXCEPTION_WITH_OBJ( stream.str() );
}
else
{
modifyNumber(val[index], value);
}
}
else
{
THROW_EXCEPTION_WITH_OBJ("Member["+std::string(childKey)+"] is not found!");
}
}
template<typename T>
bool SSDK::Archive::Json::modifyNumberElementOfArrayBasedOnIndex(const char* key, uint index, const T& value)
{
using namespace rapidjson;
bool isSuccessful{false};
bool isFound {false};
auto& val = queryValue(this->m_doc,key,isFound);
if(isFound && val.IsArray())
{
if( index > val.Size())
{
std::ostringstream stream;
stream<<"Index["<<index<<"] is invaild, it must be in[0,"<<val.Size()<<"]";
THROW_EXCEPTION_WITH_OBJ( stream.str() );
}
else
{
isSuccessful = modifyNumber(val[index], value);
}
}
else
{
THROW_EXCEPTION_WITH_OBJ("Member["+std::string(key)+"] is not found!");
}
return isSuccessful;
}
template<typename T>
typename std::enable_if<
(std::is_same<T, bool>::value)||
(std::is_same<T, int>::value)||
(std::is_same<T, uint>::value)||
(std::is_same<T, int64_t>::value)||
(std::is_same<T, double>::value), bool>::type
SSDK::Archive::Json::pushNumberBackToArray(const char* parentKey,const char* childkey, const T& newElementVal)
{
rapidjson::Value val(newElementVal);
return pushValBackToArray(parentKey,childkey,val);
}
template<typename T>
typename std::enable_if<
(std::is_same<T, bool>::value)||
(std::is_same<T, int>::value)||
(std::is_same<T, uint>::value)||
(std::is_same<T, int64_t>::value)||
(std::is_same<T, double>::value), bool>::type
SSDK::Archive::Json::pushNumberBackToArray(const char* key, const T& newElementVal)
{
return pushNumberBackToArray(nullptr,key,newElementVal);
}
template<typename T>
typename std::enable_if<std::is_same<T, bool>::value, bool>::type//bool
SSDK::Archive::Json::pushElementOfArrayToVector(const rapidjson::Value::ConstValueIterator& arrayElementVal, std::vector<T>& vector)const
{
if(arrayElementVal->IsBool())
{
vector.push_back(arrayElementVal->GetBool());
return true;
}
else
{
return false;
}
}
template<typename T>
typename std::enable_if<std::is_same<T, int>::value, bool>::type//int
SSDK::Archive::Json::pushElementOfArrayToVector(const rapidjson::Value::ConstValueIterator& arrayElementVal, std::vector<T>& vector)const
{
if(arrayElementVal->IsInt())
{
vector.push_back(arrayElementVal->GetInt());
return true;
}
else
{
return false;
}
}
template<typename T>
typename std::enable_if<std::is_same<T, int64_t>::value, bool>::type//int64_t
SSDK::Archive::Json::pushElementOfArrayToVector(const rapidjson::Value::ConstValueIterator& arrayElementVal, std::vector<T>& vector)const
{
if(arrayElementVal->IsInt64())
{
vector.push_back(arrayElementVal->GetInt64());
return true;
}
else
{
return false;
}
}
template<typename T>
typename std::enable_if<std::is_same<T, uint64_t>::value, bool>::type//uint64_t
SSDK::Archive::Json::pushElementOfArrayToVector(const rapidjson::Value::ConstValueIterator& arrayElementVal, std::vector<T>& vector)const
{
if(arrayElementVal->IsUint64())
{
vector.push_back(arrayElementVal->GetUint64());
return true;
}
else
{
return false;
}
}
template<typename T>
typename std::enable_if<std::is_same<T, double>::value, bool>::type//double
SSDK::Archive::Json::pushElementOfArrayToVector(const rapidjson::Value::ConstValueIterator& arrayElementVal, std::vector<T>& vector)const
{
if(arrayElementVal->IsDouble())
{
vector.push_back(arrayElementVal->GetDouble());
return true;
}
else
{
return false;
}
}
template<typename T>
typename std::enable_if<std::is_same<T, std::string>::value, bool>::type//string
SSDK::Archive::Json::pushElementOfArrayToVector(const rapidjson::Value::ConstValueIterator& arrayElementVal, std::vector<T>& vector)const
{
if(arrayElementVal->IsString())
{
vector.emplace_back(std::string(arrayElementVal->GetString()));
return true;
}
else
{
return false;
}
}
template<typename T>
typename std::enable_if<std::is_same<char*, T>::value || std::is_same<const char*,T>::value, bool>::type//char* or const char*
SSDK::Archive::Json::pushElementOfArrayToVector(const rapidjson::Value::ConstValueIterator& arrayElementVal, std::vector<T>& vector)const
{
if(arrayElementVal->IsString())
{
vector.push_back((T)arrayElementVal->GetString());
return true;
}
else
{
return false;
}
}
//>>>-------------------------------------------------------------------------------------------------------------------------------------
//4.Object
/**
* @brief addNumberToObject
* 增加一个Number到Object
* @paramt T
* 待添加Number的类型,这里可以为bool,int,uint,int64,uint64和double
* @param parentKey
* Object所在的父Object的name
* @param childKey
* Object的name
* @param memName
* 待添加的Object的name
* @param memVal
* 待添加的Object的value
*/
template<typename T>
typename std::enable_if<
(std::is_same<T, bool>::value)||
(std::is_same<T, int>::value)||
(std::is_same<T, uint>::value)||
(std::is_same<T, int64_t>::value)||
(std::is_same<T,uint64_t>::value)||
(std::is_same<T, double>::value)>::type
SSDK::Archive::Json::addNumberToObject(const char *parentKey, const char *childKey, const char *memName, const T& memVal)
{
bool isFound{false};
auto& parentObj = queryValue(parentKey, childKey,isFound);
if(!isFound && !parentObj.IsObject())
{
THROW_EXCEPTION_WITH_OBJ("Object["+std::string(childKey)+"] is not found!");
}
else
{
parentObj.AddMember(rapidjson::Value::StringRefType(memName),memVal,this->m_doc.GetAllocator());
this->m_isReAccept = true;
}
}
template<typename T>
typename std::enable_if<
(std::is_same<T, bool>::value)||
(std::is_same<T, int>::value)||
(std::is_same<T, uint>::value)||
(std::is_same<T, int64_t>::value)||
(std::is_same<T,uint64_t>::value)||
(std::is_same<T, double>::value)>::type
SSDK::Archive::Json::addNumberToObject(const char *key, const char *memName, const T& memVal)
{
addNumberToObject(nullptr,key,memName,memVal);
}
//<<<----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
#endif // JSONHELPER_H
| 38.74884 | 229 | 0.416613 | djc80s |
b339e1d03d64d14f58233230589a3734d14290da | 4,504 | cc | C++ | chrome/browser/prefs/session_startup_pref.cc | Gitman1989/chromium | 2b1cceae1075ef012fb225deec8b4c8bbe4bc897 | [
"BSD-3-Clause"
] | 2 | 2017-09-02T19:08:28.000Z | 2021-11-15T15:15:14.000Z | chrome/browser/prefs/session_startup_pref.cc | Gitman1989/chromium | 2b1cceae1075ef012fb225deec8b4c8bbe4bc897 | [
"BSD-3-Clause"
] | null | null | null | chrome/browser/prefs/session_startup_pref.cc | Gitman1989/chromium | 2b1cceae1075ef012fb225deec8b4c8bbe4bc897 | [
"BSD-3-Clause"
] | 1 | 2020-04-13T05:45:10.000Z | 2020-04-13T05:45:10.000Z | // Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/prefs/session_startup_pref.h"
#include <string>
#include "base/string_piece.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/defaults.h"
#include "chrome/browser/net/url_fixer_upper.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/prefs/scoped_pref_update.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/pref_names.h"
namespace {
// For historical reasons the enum and value registered in the prefs don't line
// up. These are the values registered in prefs.
const int kPrefValueDefault = 0;
const int kPrefValueLast = 1;
const int kPrefValueURLs = 4;
// Converts a SessionStartupPref::Type to an integer written to prefs.
int TypeToPrefValue(SessionStartupPref::Type type) {
switch (type) {
case SessionStartupPref::LAST: return kPrefValueLast;
case SessionStartupPref::URLS: return kPrefValueURLs;
default: return kPrefValueDefault;
}
}
// Converts an integer pref value to a SessionStartupPref::Type.
SessionStartupPref::Type PrefValueToType(int pref_value) {
switch (pref_value) {
case kPrefValueLast: return SessionStartupPref::LAST;
case kPrefValueURLs: return SessionStartupPref::URLS;
default: return SessionStartupPref::DEFAULT;
}
}
} // namespace
// static
void SessionStartupPref::RegisterUserPrefs(PrefService* prefs) {
prefs->RegisterIntegerPref(prefs::kRestoreOnStartup,
TypeToPrefValue(browser_defaults::kDefaultSessionStartupType));
prefs->RegisterListPref(prefs::kURLsToRestoreOnStartup);
}
// static
void SessionStartupPref::SetStartupPref(
Profile* profile,
const SessionStartupPref& pref) {
DCHECK(profile);
SetStartupPref(profile->GetPrefs(), pref);
}
// static
void SessionStartupPref::SetStartupPref(PrefService* prefs,
const SessionStartupPref& pref) {
DCHECK(prefs);
if (!SessionStartupPref::TypeIsManaged(prefs))
prefs->SetInteger(prefs::kRestoreOnStartup, TypeToPrefValue(pref.type));
if (!SessionStartupPref::URLsAreManaged(prefs)) {
// Always save the URLs, that way the UI can remain consistent even if the
// user changes the startup type pref.
// Ownership of the ListValue retains with the pref service.
ScopedPrefUpdate update(prefs, prefs::kURLsToRestoreOnStartup);
ListValue* url_pref_list =
prefs->GetMutableList(prefs::kURLsToRestoreOnStartup);
DCHECK(url_pref_list);
url_pref_list->Clear();
for (size_t i = 0; i < pref.urls.size(); ++i) {
url_pref_list->Set(static_cast<int>(i),
new StringValue(pref.urls[i].spec()));
}
}
}
// static
SessionStartupPref SessionStartupPref::GetStartupPref(Profile* profile) {
DCHECK(profile);
return GetStartupPref(profile->GetPrefs());
}
// static
SessionStartupPref SessionStartupPref::GetStartupPref(PrefService* prefs) {
DCHECK(prefs);
SessionStartupPref pref(
PrefValueToType(prefs->GetInteger(prefs::kRestoreOnStartup)));
// Always load the urls, even if the pref type isn't URLS. This way the
// preferences panels can show the user their last choice.
const ListValue* url_pref_list = prefs->GetList(
prefs::kURLsToRestoreOnStartup);
if (url_pref_list) {
for (size_t i = 0; i < url_pref_list->GetSize(); ++i) {
Value* value = NULL;
if (url_pref_list->Get(i, &value)) {
std::string url_text;
if (value->GetAsString(&url_text)) {
GURL fixed_url = URLFixerUpper::FixupURL(url_text, "");
pref.urls.push_back(fixed_url);
}
}
}
}
return pref;
}
// static
bool SessionStartupPref::TypeIsManaged(PrefService* prefs) {
DCHECK(prefs);
const PrefService::Preference* pref_restore =
prefs->FindPreference(prefs::kRestoreOnStartup);
DCHECK(pref_restore);
return pref_restore->IsManaged();
}
// static
bool SessionStartupPref::URLsAreManaged(PrefService* prefs) {
DCHECK(prefs);
const PrefService::Preference* pref_urls =
prefs->FindPreference(prefs::kURLsToRestoreOnStartup);
DCHECK(pref_urls);
return pref_urls->IsManaged();
}
SessionStartupPref::SessionStartupPref() : type(DEFAULT) {}
SessionStartupPref::SessionStartupPref(Type type) : type(type) {}
SessionStartupPref::~SessionStartupPref() {}
| 32.402878 | 79 | 0.720249 | Gitman1989 |
b33bba60bd697a1fff48ac10a5d457938b0056fb | 870 | cpp | C++ | modes/ModeMessage.cpp | bl4ckic3/fsfw | c76fc8c703e19d917c45a25710b4642e5923c68a | [
"Apache-2.0"
] | null | null | null | modes/ModeMessage.cpp | bl4ckic3/fsfw | c76fc8c703e19d917c45a25710b4642e5923c68a | [
"Apache-2.0"
] | null | null | null | modes/ModeMessage.cpp | bl4ckic3/fsfw | c76fc8c703e19d917c45a25710b4642e5923c68a | [
"Apache-2.0"
] | null | null | null | #include "ModeMessage.h"
Mode_t ModeMessage::getMode(const CommandMessage* message) {
return message->getParameter();
}
Submode_t ModeMessage::getSubmode(const CommandMessage* message) {
return message->getParameter2();
}
void ModeMessage::setModeMessage(CommandMessage* message,
Command_t command, Mode_t mode, Submode_t submode) {
message->setCommand( command );
message->setParameter( mode );
message->setParameter2( submode );
}
ReturnValue_t ModeMessage::getCantReachModeReason(const CommandMessage* message) {
return message->getParameter();
}
void ModeMessage::clear(CommandMessage* message) {
message->setCommand(CommandMessage::CMD_NONE);
}
void ModeMessage::setCantReachMode(CommandMessage* message,
ReturnValue_t reason) {
message->setCommand(REPLY_CANT_REACH_MODE);
message->setParameter(reason);
message->setParameter2(0);
}
| 27.1875 | 82 | 0.774713 | bl4ckic3 |
b33c17115f15fc746cc25d602d3a1c792163ca63 | 7,315 | cc | C++ | tddd38-cpp/exams/ten-210114/message.cc | AxelGard/university-projects | 0c9a6e785f1918c6ed0fd365b2d419c9f52edb50 | [
"MIT"
] | null | null | null | tddd38-cpp/exams/ten-210114/message.cc | AxelGard/university-projects | 0c9a6e785f1918c6ed0fd365b2d419c9f52edb50 | [
"MIT"
] | null | null | null | tddd38-cpp/exams/ten-210114/message.cc | AxelGard/university-projects | 0c9a6e785f1918c6ed0fd365b2d419c9f52edb50 | [
"MIT"
] | null | null | null | // Suggestions and hints:
// - Read the 'main' function to understand how the code is used.
// - Don't worry too much about rewriting everything. Find a few
// places where you can demonstrate your knowledge and only change
// those places.
// - The wishlists are just hints/suggestions. You don't have to
// follow them if you don't want to.
// - It is more important to understand how the code is used rather
// than what it does.
// - To help you understand the code it might be helpful to make small
// changes in the code and then see what effect it has on the
// output.
// - It is ok if the behaviour of the code changes, as long as it
// stays approximately the same. Use your own judgement.
// - There are a lot of comments in this file, read them.
#include <string>
#include <iostream>
#include <vector>
#include <sstream>
#include <utility>
// This enum represents the different types of messages that can be
// handled in the messaging system. These are:
// - None: An empty message, doesn't contain any data.
// - Text: A message which contains a string (without the '#'
// character).
// - Integer: A message which contains a single integer value.
// - Floating: A message which contains a single floating-point
// (double) value.
// - Composite: A message which consists of several submessages.
// This struct represents a message that can be sent or
// recieved. There are four types of messages (see above) determined
// by 'type'.
// 'text' is used for Text messages. It contains the actual string
// (text) content.
// 'integer' is used for Integer messages. It contains the integer
// value.
// 'floating' is used for Floating messages. It contains the
// floating-point value.
// 'submessages' is a vector of messages that are used in Composite
// messages.
// Wishlist:
// - It would be a good idea to represent the 'type' in some other way.
// - It should be easy to add other types of messages.
// - Would be nice if 'integer' could be other types as well, for
// example float, double, bool and other types that has operator<<.
// - Can we store only the relevant data member for the corresponding
// type somehow?
/*
struct Message
{
Message_Type type { None };
std::string text;
int integer;
double floating;
std::vector<Message*> submessages;
};
*/
class Message {
public:
virtual ~Message() = default;
virtual int encode_type() const
{
return -1;
}
virtual void serialize(std::ostream& os) const
{
os << this->encode_type() << " ";
}
};
class None : public Message
{
public:
int encode_type() const override
{
return 0;
}
};
class Text : public Message
{
private:
std::string text;
public:
Text(std::string const& text)
: text{text}
{ }
int encode_type() const override
{
return 1;
}
void serialize(std::ostream& os) const override
{
Message::serialize(os);
os << this->text << "# ";
}
};
template<typename T>
class Data : public Message
{
private:
T data;
public:
Data(T const& data)
: data { data }
{ }
int encode_type() const override
{
return 2;
}
void serialize(std::ostream& os) const override
{
Message::serialize(os)
os << this->data << " ";
}
};
class Composite : public Message
{
private:
std::vector<Message*> messages;
public:
Composite(std::vector<Message*> const& messages)
: messages { messages }
{ }
~Composite(){
for (auto&& message : messages){
delete message;
}
}
int encode_type() const override
{
return 4;
}
void serialize(std::ostream& os) const override
{
Message::serialize(os);
os << messages.size() << " ";
for (auto&& message : messages)
{
message->serialize(os);
}
}
};
class Terminal
{
private:
std::string name;
std::vector<Message*> messages {};
public:
Terminal(std::string const& name, std::vector<Message*> const& messages = {})
: name { name }, messages {messages}
{ }
~Terminal(){
for (auto&& message : this->messages){
delete message;
}
}
void add(Message* message)
{
this->messages.push_back(message);
}
void serialize(std::ostream& os) const
{
os << name << " " << messages.size() << " ";
for (auto&& message : this->messages)
{
message->serialize(os);
}
}
template <typename Comparator>
std::vector<Message*> sort_messages(Comparator comarator)
{
std::vector<Message*> result {messages};
std::sort(std::begin(result), std::end(result), comparator);
return result;
}
template <typename Predicate>
std::vector<Message*> filter_messages(Predicate predicate){
std::copy_if(std::begin(this->messages), std::end(this->messages), std::back_inserter(result)
[&predicate](auto&& a){return !predicate(a); });
}
};
bool comp(Message const* a, Message const* b){
return a->encode_type() < b->encode_type();
}
bool pred(Message const* msg){
int type{msg->encode_type()};
return type==2 || type == 3;
}
int main(){
Terminal terminal { "My Terminal" };
// create some messages
terminal.add(new None());
terminal.add(new Text("This string is my message"));
terminal.add(new Data<int>(12));
terminal.add(new Data<double>(3.14));
terminal.add(new None());
terminal.add(new Text("More text"));
// create a composite message
std::vector<Message*> messages {
new Text("1"),
new Data<double>(2.3),
new Data<int>(45)
};
terminal.add(new Composite(messages));
// check if we can serialize all the messages
terminal.serialize(std::cout);
std::cout << std::endl;
std::cout << "========" << std::endl;
// test the sort_messages function. We sort on the type of message.
// Would be nice if we could do this:
// sort_messages(terminal, [](Message* a, Message* b) { return return encode_type(a) > encode_type(b); });
std::vector<Message*> sorted { terminal.sort_messages(comp) };
for (Message const* message : sorted)
{
message->serialize(std::cout);
std::cout << std::endl;
}
std::cout << "========" << std::endl;
// test the filter_messages function. We remove all Integer and
// Floating messages.
// Would be nice if we could do this:
// filter_messages(terminal, [](Message* a) { encode_type(a) > 1; });
std::vector<Message*> filtered { terminal.filter_messages(pred) };
for (Message const* message : filtered)
{
message->serialize(std::cout);
std::cout << std::endl;
}
} | 25.224138 | 110 | 0.577717 | AxelGard |
b33e057cacd37ac8f7bc73917ca18819cb249b07 | 1,795 | cpp | C++ | Problem Sets/Problem Set 4/Problem 6.54/main.cpp | joseramosp/Learning-C- | 7003ff56745f7b8ebe21211ca692670bb4728bfe | [
"MIT"
] | 1 | 2020-10-11T00:09:48.000Z | 2020-10-11T00:09:48.000Z | Problem Sets/Problem Set 4/Problem 6.54/main.cpp | joseramosp/Learning-Cpp | 7003ff56745f7b8ebe21211ca692670bb4728bfe | [
"MIT"
] | null | null | null | Problem Sets/Problem Set 4/Problem 6.54/main.cpp | joseramosp/Learning-Cpp | 7003ff56745f7b8ebe21211ca692670bb4728bfe | [
"MIT"
] | null | null | null | //
// Created by Jose Ramos on 2/20/20.
//
// 6.54 (C++11 Random Numbers: Modified Craps Game) Modify the program of Fig. 6.9 to use the new C++11 random-
// number generation features shown in Section 6.9.
#include <iostream>
#include <random>
using namespace std;
unsigned int rollDice();
int main() {
//default_random_engine engine{static_cast<unsigned int> (time(NULL))};
//RandomDevice::RandomDevice(unsigned long n) : rand_seed(n), engine(n){ };
enum class Status {
CONTINUE, WON, LOST
};
unsigned int myPoint{0};
Status gameStatus;
unsigned int sumOfDice{rollDice()};
switch (sumOfDice) {
case 7:
case 11:
gameStatus = Status::WON;
break;
case 2:
case 3:
case 12:
gameStatus = Status::LOST;
break;
default:
gameStatus = Status::CONTINUE;
myPoint = sumOfDice;
cout << "Point is " << myPoint << endl;
break;
}
while (Status::CONTINUE == gameStatus) {
sumOfDice = rollDice();
if (sumOfDice == myPoint) {
gameStatus = Status::WON;
} else {
if (sumOfDice == 7) {
gameStatus = Status::LOST;
}
}
}
if (Status::WON == gameStatus) {
cout << "Player wins" << endl;
} else {
cout << "Player loses" << endl;
}
}
unsigned int rollDice() {
random_device rd;
default_random_engine engine(rd());
uniform_int_distribution<unsigned int> randomInt{1,6};
auto roll = bind (randomInt, engine);
int die1{int(roll())};
int die2{int(roll())};
int sum{die1 + die2};
cout << "Player rolled " << die1 << " + " << die2 << " = " << sum << endl;
return sum;
}
| 23.618421 | 111 | 0.547632 | joseramosp |
b33ea83d066a38090cfc443fe727b5b3e5879ecc | 9,226 | cpp | C++ | historyView.cpp | neelsoumya/cycells | a3a6e632addf0a91c75c0a579ad0d41ad9d7a089 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | historyView.cpp | neelsoumya/cycells | a3a6e632addf0a91c75c0a579ad0d41ad9d7a089 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | historyView.cpp | neelsoumya/cycells | a3a6e632addf0a91c75c0a579ad0d41ad9d7a089 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 3 | 2018-06-20T21:55:11.000Z | 2020-10-21T19:04:54.000Z | /************************************************************************
* *
* Copyright (C) 2007 Christina Warrender and Drew Levin *
* *
* This file is part of QtCyCells. *
* *
* QtCyCells 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. *
* *
* QtCyCells 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 QtCyCells; if not, write to the Free Software Foundation, *
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
* *
************************************************************************/
/************************************************************************
* file historyView.cc *
* render() routine for HistoryView *
* Graphs cell populations and molecular concentrations over time *
* This version plots with wx/GTK instead of openGL - can use text *
************************************************************************/
#include "historyView.h"
#include <GL/gl.h>
#include "history.h"
/************************************************************************
* HistoryView() *
* Constructor *
* *
* Parameters *
* int x, y, w, h: position (x,y) and size (w,h) of view *
* *
* Returns - nothing *
************************************************************************/
HistoryView::HistoryView(QWidget *parent, int x, int y, int w, int h,
const History *hist)
: SimView(parent, x, y, w, h), history(hist), m_first(true)
{
m_border = 100;
QRect geo = geometry();
m_height = geo.height();
m_width = geo.width();
}
void HistoryView::paintEvent(QPaintEvent * /* event */)
{
QPainter painter(this);
// get number of samples taken and max value for each axis
const vector<double> times = history->getTimes();
int numsamples = times.size();
double maxTime = times[numsamples-1];
int maxCells = history->getMaxCount();
double maxConc = history->getMaxConc();
// Set Painter Properties
painter.setPen(Qt::black);
painter.setFont(QFont("Modern", 10));
// Draw the graph's axes
drawAxes(painter, maxTime, maxCells, maxConc);
// Only plot if there are two more more data points
if (numsamples > 1)
{
// Get the data
History::CellHistory counts;
History::ConcHistory concs;
int t0 = m_border;
int tmax = m_width-m_border;
double tscale = (tmax-t0)/maxTime;
int y0 = m_height-m_border;
int ymax = m_border;
// Cell counts first - scale according to max count so far
if (maxCells == 0)
{
if (int last = history->getNumCellTypes())
{
// just draw one line (last color) along x axis
painter.setPen(QColor(cell_palette[last].red(),
cell_palette[last].green(),
cell_palette[last].blue()));
painter.drawLine(t0, y0, tmax, y0);
}
}
else {
double yscale = (y0-ymax)/double(maxCells);
// Each loop handles drawing one cell type
for (int i=0; i<history->getNumCellTypes(); i++) {
counts = history->getCounts(i);
// Set color according to palette
painter.setPen(QColor(cell_palette[i].red(), cell_palette[i].green(),
cell_palette[i].blue()));
for (int j=0; j<numsamples-1; j++)
painter.drawLine(int(tscale*times[j]+t0), y0-int(yscale*counts[j]),
int(tscale*times[j+1] + t0), y0 - int(yscale*counts[j+1]));
} // end for loop
} // end if maxCells not 0
// Rescale for molecular concentrations
if (maxConc == 0) {
if (int last = history->getNumMolTypes()) {
// Just draw one line (last color) along the x-axis
painter.setPen(QColor(mol_palette[last].red(), mol_palette[last].green(),
mol_palette[last].blue()));
painter.drawLine(t0, y0, tmax, y0);
}
}
else {
double yscale = (y0-ymax)/maxConc;
// Each loop handles drawing one molecule type
for (int i=0; i<history->getNumMolTypes(); i++) {
concs = history->getConc(i);
// Set color according to palette
painter.setPen(QColor(mol_palette[i].red(), mol_palette[i].green(),
mol_palette[i].blue()));
for (int j=0; j<numsamples-1; j++)
painter.drawLine(int(tscale*times[j] + t0), y0 - int(yscale*concs[j]),
int(tscale*times[j+1] + t0), y0 - int(yscale*concs[j+1]));
} // end for loop
} // end if maxConc not 0
} // end if more than one sample
}
/************************************************************************
* render() *
* Qt code to draw history of sim *
* *
* Returns - nothing *
************************************************************************/
void HistoryView::render()
{
}
/************************************************************************
* drawAxes() *
* Sets up xaxis (time) and 2 yaxes (one for cells and one for *
* molecules) *
* *
* Parameters - *
* double maxTime: max value on y axis *
* int maxCells: max value on left y axis *
* double maxConc: max value on right y axis *
* *
\ * Returns - nothing *
************************************************************************/
void HistoryView::drawAxes(QPainter &painter, double maxTime,
int maxCells, double maxConc)
{
QString str;
// Draw lines for axes
painter.drawLine(m_border, m_border, m_border, m_height - m_border);
painter.drawLine(m_border, m_height - m_border,
m_width - m_border, m_height - m_border);
painter.drawLine(m_width - m_border, m_height - m_border,
m_width - m_border, m_border);
// X-Axis Label
painter.drawText(m_width/2-100,
m_height-(3*m_border/4)-25,
200,
50,
Qt::AlignCenter,
tr("Time (sec)"));
painter.save();
painter.rotate(-90);
// Left Y-Axis Label
painter.drawText(-m_height/2-100,
(3*m_border)/4-25,
200,
50,
Qt::AlignCenter,
tr("# of Cells"));
// Right Y-Axis Label
painter.drawText(-m_height/2-100,
m_width-(3*m_border)/4-25,
200,
50,
Qt::AlignCenter,
tr("Concentration (Moles/ml)"));
painter.restore();
// X-Axis Max Value
str.sprintf("%.1f", maxTime);
painter.drawText(m_width-m_border-100,
height-4*m_border/5-25,
200,
50,
Qt::AlignCenter,
str);
// Left Y-Axis Max Value
str.sprintf("%d", maxCells);
painter.drawText(m_border/2-100,
m_border-25,
200,
50,
Qt::AlignCenter,
str);
// Right Y-Axis Max Value
str.sprintf("%.1e", maxConc);
painter.drawText(m_width-m_border/2-100,
m_border-25,
200,
50,
Qt::AlignCenter,
str);
}
| 39.939394 | 82 | 0.423911 | neelsoumya |
b33f308ad5284b295bc1aa8c12a524b657fb5637 | 531 | hpp | C++ | libraries/plugins/chain/include/steem/plugins/chain/abstract_block_producer.hpp | reactivespace/Steemit-Fork-2.0 | 1bf860963f5715309bda6f77e362e09e9d3ccf8a | [
"MIT"
] | null | null | null | libraries/plugins/chain/include/steem/plugins/chain/abstract_block_producer.hpp | reactivespace/Steemit-Fork-2.0 | 1bf860963f5715309bda6f77e362e09e9d3ccf8a | [
"MIT"
] | null | null | null | libraries/plugins/chain/include/steem/plugins/chain/abstract_block_producer.hpp | reactivespace/Steemit-Fork-2.0 | 1bf860963f5715309bda6f77e362e09e9d3ccf8a | [
"MIT"
] | null | null | null | #pragma once
#include <fc/time.hpp>
#include <clout/chain/database.hpp>
namespace clout { namespace plugins { namespace chain {
class abstract_block_producer {
public:
virtual ~abstract_block_producer() = default;
virtual clout::chain::signed_block generate_block(
fc::time_point_sec when,
const clout::chain::account_name_type& witness_owner,
const fc::ecc::private_key& block_signing_private_key,
uint32_t skip = clout::chain::database::skip_nothing) = 0;
};
} } } // clout::plugins::chain
| 25.285714 | 64 | 0.721281 | reactivespace |
b3406b533c5cc030f01da5fc7a49f8ad453a7bb6 | 4,815 | hpp | C++ | sandbox/core/system.hpp | KabelitzJ/sandbox | fe870387e634e101a63398409966c61088e1384b | [
"MIT"
] | null | null | null | sandbox/core/system.hpp | KabelitzJ/sandbox | fe870387e634e101a63398409966c61088e1384b | [
"MIT"
] | null | null | null | sandbox/core/system.hpp | KabelitzJ/sandbox | fe870387e634e101a63398409966c61088e1384b | [
"MIT"
] | null | null | null | #ifndef SBX_ECS_SYSTEM_HPP_
#define SBX_ECS_SYSTEM_HPP_
#include <type_traits>
#include <utility>
#include <iostream>
#include <memory>
#include <string>
#include <types/primitives.hpp>
#include <types/transform.hpp>
#include "resource_cache.hpp"
#include "scene.hpp"
#include "event_queue.hpp"
#include "input.hpp"
#include "key.hpp"
#include "mouse_button.hpp"
namespace sbx {
class system {
public:
system();
virtual ~system() = default;
virtual void initialize() = 0;
virtual void update(const time delta_time) = 0;
virtual void terminate() = 0;
[[nodiscard]] bool is_running() const noexcept;
protected:
void exit() noexcept {
_terminate();
}
entity create_entity(const transform& transform = transform{}, const entity parent = null_entity);
void destroy_entity(const entity entity);
template<typename Component, typename... Args>
decltype(auto) add_component(const entity entity, Args&&... args) {
assert(_scene); // Scene is uninitialized
return _scene->add_component<Component>(entity, std::forward<Args>(args)...);
}
template<typename... Components>
decltype(auto) get_components(const entity entity) const {
assert(_scene); // Scene is uninitialized
return _scene->get_components<Components...>(entity);
}
template<typename... Components>
decltype(auto) get_components(const entity entity) {
assert(_scene); // Scene is uninitialized
return _scene->get_components<Components...>(entity);
}
template<typename... Components>
void remove_components(const entity entity) {
assert(_scene); // Scene is uninitialized
return _scene->remove_components<Components...>(entity);
}
template<typename... Components>
[[nodiscard]] bool has_components(const entity entity) const {
assert(_scene); // Scene is uninitialized
return _scene->has_components<Components...>(entity);
}
template<typename... Components, typename... Excludes>
[[nodiscard]] decltype(auto) create_view(exclude_t<Excludes...> = {}) const {
assert(_scene); // Scene is uninitialized
return _scene->create_view<Components..., Excludes...>();
}
template<typename... Components, typename... Excludes>
[[nodiscard]] decltype(auto) create_view(exclude_t<Excludes...> = {}) {
assert(_scene); // Scene is uninitialized
return _scene->create_view<Components..., Excludes...>();
}
template<typename Event, typename Listener>
void add_listener(Listener&& listener) {
assert(_event_queue); // Event queue is uninitialized
_event_queue->add_listener<Event>(std::move(listener));
}
template<typename Event, typename... Args>
void dispatch_event(Args&&... args) {
assert(_event_queue); // Event queue is uninitialized
_event_queue->dispatch_event<Event>(std::forward<Args>(args)...);
}
template<typename Resource, typename... Args>
void load_resource(const std::string& name, Args&&... args) {
assert(_resource_cache); // Resource cache is uninitialized
_resource_cache->load<Resource>(name, std::forward<Args>(args)...);
}
template<typename Resource>
std::shared_ptr<Resource> get_resource(const std::string& name) {
assert(_resource_cache); // Resource cache is uninitialized
return _resource_cache->get<Resource>(name);
}
bool is_key_down(const key key) const;
bool is_key_up(const key key) const;
bool is_mouse_button_down(const mouse_button button) const;
bool is_mouse_button_up(const mouse_button button) const;
scene* get_scene() noexcept {
assert(_scene); // Scene is uninitialized
return _scene;
}
event_queue* get_event_queue() noexcept {
assert(_event_queue); // Event queue is uninitialized
return _event_queue;
}
resource_cache* get_resource_cache() noexcept {
assert(_resource_cache); // Resource cache is uninitialized
return _resource_cache;
}
input* get_input() noexcept {
assert(_input); // Input is uninitialized
return _input;
}
private:
friend class scheduler;
friend class engine;
inline static scene* _scene{nullptr};
inline static event_queue* _event_queue{nullptr};
inline static resource_cache* _resource_cache{nullptr};
inline static input* _input{nullptr};
void _initialize();
void _update(const time delta_time);
void _terminate();
bool _is_running{false};
}; // class system
template<typename Function>
class system_adaptor : public system, private Function {
public:
template<typename... Args>
system_adaptor(Args&&... args)
: Function{std::forward<Args>(args)...} { }
void initialize() override { }
void update(const time delta_time) override {
Function::operator()(delta_time, [this](){ exit(); });
}
void terminate() override { }
}; // class system_adaptor
} // namespace sbx
#endif // SBX_ECS_SYSTEM_HPP_
| 26.75 | 100 | 0.71298 | KabelitzJ |
b3474ba95efadd131a0fca3e23e2f99058671c84 | 22,454 | cpp | C++ | qikkDB_test/DispatcherTestsRegression.cpp | veselyja/qikkdb-community | 680f62632ba85e468beee672624b80a61ed40f55 | [
"Apache-2.0"
] | 15 | 2020-06-30T13:43:42.000Z | 2022-02-02T12:52:33.000Z | qikkDB_test/DispatcherTestsRegression.cpp | veselyja/qikkdb-community | 680f62632ba85e468beee672624b80a61ed40f55 | [
"Apache-2.0"
] | 1 | 2020-11-28T22:29:35.000Z | 2020-12-22T10:28:25.000Z | qikkDB_test/DispatcherTestsRegression.cpp | qikkDB/qikkdb | 4ee657c7d2bfccd460d2f0d2c84a0bbe72d9a80a | [
"Apache-2.0"
] | 1 | 2020-06-30T12:41:37.000Z | 2020-06-30T12:41:37.000Z | #include <cmath>
#include "gtest/gtest.h"
#include "../qikkDB/DatabaseGenerator.h"
#include "../qikkDB/ColumnBase.h"
#include "../qikkDB/BlockBase.h"
#include "../qikkDB/PointFactory.h"
#include "../qikkDB/ComplexPolygonFactory.h"
#include "../qikkDB/Database.h"
#include "../qikkDB/Table.h"
#include "../qikkDB/QueryEngine/Context.h"
#include "../qikkDB/GpuSqlParser/GpuSqlCustomParser.h"
#include "../qikkDB/messages/QueryResponseMessage.pb.h"
#include "../qikkDB/GpuSqlParser/ParserExceptions.h"
#include "DispatcherObjs.h"
TEST(DispatcherTestsRegression, EmptyResultFromGtColConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE colInteger1 > 4096;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0); // Check if the result size is also 0
}
TEST(DispatcherTestsRegression, EmptyResultFromGroupByOrderBy)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE colInteger1 > 4096 "
"GROUP BY colInteger1 ORDER BY colInteger1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
TEST(DispatcherTestsRegression, EmptyResultFromGroupByCount)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT COUNT(colInteger1) FROM TableA WHERE colInteger1 > 4096 "
"GROUP BY colInteger1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
TEST(DispatcherTestsRegression, EmptyResultFromGroupByAvg)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT AVG(colInteger1) FROM TableA WHERE colInteger1 > 4096 GROUP "
"BY colInteger1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
TEST(DispatcherTestsRegression, EmptyResultFromGroupBySum)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT SUM(colInteger1) FROM TableA WHERE colInteger1 > 4096 GROUP "
"BY colInteger1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
TEST(DispatcherTestsRegression, EmptySetAggregationCount)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT COUNT(colInteger1) FROM TableA WHERE colInteger1 > 4096;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), Configuration::GetInstance().IsUsingWhereEvaluationSpeedup() ? 0 : 1);
// TODO fix this test when COUNT returns "0" when there is empty result set
// ASSERT_EQ(result->payloads().size(), 1);
// ASSERT_EQ(result->payloads().at("COUNT(colInteger1)").int64payload().int64data()[0], 0);
}
TEST(DispatcherTestsRegression, EmptySetAggregationSum)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT SUM(colInteger1) FROM TableA WHERE colInteger1 > 4096;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), Configuration::GetInstance().IsUsingWhereEvaluationSpeedup() ? 0 : 1);
// TODO fix this test when SUM returns no rows when there is empty result set
// ASSERT_EQ(result->payloads().size(), 0);
}
TEST(DispatcherTestsRegression, EmptySetAggregationMin)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT MIN(colInteger1) FROM TableA WHERE colInteger1 > 4096;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), Configuration::GetInstance().IsUsingWhereEvaluationSpeedup() ? 0 : 1);
// TODO fix this test when MIN returns no rows when there is empty result set
// ASSERT_EQ(result->payloads().size(), 0);
}
TEST(DispatcherTestsRegression, PointAggregationCount)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT COUNT(colPoint1) FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payloads = result->payloads().at("COUNT(colPoint1)");
ASSERT_EQ(payloads.int64payload().int64data_size(), 1);
ASSERT_EQ(payloads.int64payload().int64data()[0], TEST_BLOCK_COUNT * TEST_BLOCK_SIZE);
}
TEST(DispatcherTestsRegression, AggregationCountAsteriskNoGroupBy)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT COUNT(*) FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payloads = result->payloads().at("COUNT(*)");
ASSERT_EQ(payloads.int64payload().int64data_size(), 1);
ASSERT_EQ(payloads.int64payload().int64data()[0], TEST_BLOCK_COUNT * TEST_BLOCK_SIZE);
}
TEST(DispatcherTestsRegression, PointAggregationCountWithWhere)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT COUNT(colPoint1) FROM TableA WHERE colInteger1 > 0;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payloads = result->payloads().at("COUNT(colPoint1)");
ASSERT_EQ(payloads.int64payload().int64data_size(), 1);
// Count sufficient row on CPU
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
int32_t expectedCount = 0;
for (int i = 0; i < TEST_BLOCK_COUNT; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < TEST_BLOCK_SIZE; k++)
{
if (blockInt->GetData()[k] > 0)
{
expectedCount++;
}
}
}
ASSERT_EQ(payloads.int64payload().int64data()[0], expectedCount);
}
TEST(DispatcherTestsRegression, Int32AggregationCount)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT COUNT(colInteger1) FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payloads = result->payloads().at("COUNT(colInteger1)");
ASSERT_EQ(payloads.int64payload().int64data_size(), 1);
ASSERT_EQ(payloads.int64payload().int64data()[0], TEST_BLOCK_COUNT * TEST_BLOCK_SIZE);
}
TEST(DispatcherTestsRegression, GroupByKeyOpCorrectSemantic)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT (colInteger1 + 2) * 10, COUNT(colFloat1) FROM TableA GROUP "
"BY colInteger1 + 2;");
ASSERT_NO_THROW(parser.Parse());
}
TEST(DispatcherTestsRegression, GroupByKeyOpWrongSemantic)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT (10 * colInteger1) + 2, COUNT(colFloat1) FROM TableA GROUP "
"BY colInteger1 + 2;");
ASSERT_THROW(parser.Parse(), ColumnGroupByException);
GpuSqlCustomParser parser2(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 + 3, COUNT(colFloat1) FROM TableA GROUP BY "
"colInteger1 + 2;");
ASSERT_THROW(parser2.Parse(), ColumnGroupByException);
}
TEST(DispatcherTestsRegression, NonGroupByAggWrongSemantic)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1, SUM(colInteger2) FROM TableA;");
ASSERT_THROW(parser.Parse(), ColumnGroupByException);
}
TEST(DispatcherTestsRegression, NonGroupByAggCorrectSemantic)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT MIN(colInteger1), SUM(colInteger2) FROM TableA;");
ASSERT_NO_THROW(parser.Parse());
}
TEST(DispatcherTestsRegression, AggInWhereWrongSemantic)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1, SUM(colInteger2) FROM TableA WHERE "
"SUM(colInteger2) > 2;");
ASSERT_THROW(parser.Parse(), AggregationWhereException);
}
TEST(DispatcherTestsRegression, AggInGroupByWrongSemantic)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT SUM(colInteger2) FROM TableA GROUP BY SUM(colInteger2);");
ASSERT_THROW(parser.Parse(), AggregationGroupByException);
}
TEST(DispatcherTestsRegression, AggInGroupByAliasWrongSemantic)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT SUM(colInteger2) FROM TableA GROUP BY 1;");
ASSERT_THROW(parser.Parse(), AggregationGroupByException);
}
TEST(DispatcherTestsRegression, GroupByAliasDataTypeWrongSemantic)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1, SUM(colInteger2) FROM TableA GROUP BY 1.1;");
ASSERT_THROW(parser.Parse(), GroupByInvalidColumnException);
}
TEST(DispatcherTestsRegression, GroupByAliasOutOfRangeWrongSemantic)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1, SUM(colInteger2) FROM TableA GROUP BY 100;");
ASSERT_THROW(parser.Parse(), GroupByInvalidColumnException);
}
TEST(DispatcherTestsRegression, OrderByAliasDataTypeWrongSemantic)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA ORDER BY 1.1;");
ASSERT_THROW(parser.Parse(), OrderByInvalidColumnException);
}
TEST(DispatcherTestsRegression, OrderByAliasOutOfRangeWrongSemantic)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA ORDER BY 100;");
ASSERT_THROW(parser.Parse(), OrderByInvalidColumnException);
}
TEST(DispatcherTestsRegression, ConstOpOnMultiGPU)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "SELECT ABS(1) FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payloads = result->payloads().at("ABS(1)");
ASSERT_EQ(payloads.intpayload().intdata_size(), DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
->GetSize());
ASSERT_EQ(payloads.intpayload().intdata()[0], 1);
}
TEST(DispatcherTestsRegression, SameAliasAsColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 as colInteger1 FROM TableA WHERE colInteger1 > "
"20;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
}
// == JOIN ==
/* // TODO Fix empty results of JOIN
TEST(DispatcherTestsRegression, JoinEmptyResult)
{
Context::getInstance();
const std::string dbName = "JoinTestDb";
const std::string tableAName = "TableA";
const std::string tableBName = "TableB";
const int32_t blockSize = 32; // length of a block
std::vector<int32_t> idsA = {1};
std::vector<int32_t> valuesA = {50};
std::vector<int32_t> idsB = {1, 1};
std::vector<int32_t> valuesB = {32, 33};
std::shared_ptr<Database> joinDatabase = std::make_shared<Database>(dbName.c_str(), blockSize);
Database::AddToInMemoryDatabaseList(joinDatabase);
auto columnsA = std::unordered_map<std::string, DataType>();
columnsA.insert(std::make_pair<std::string, DataType>("id", DataType::COLUMN_INT));
columnsA.insert(std::make_pair<std::string, DataType>("value", DataType::COLUMN_INT));
joinDatabase->CreateTable(columnsA, tableAName.c_str());
auto columnsB = std::unordered_map<std::string, DataType>();
columnsB.insert(std::make_pair<std::string, DataType>("id", DataType::COLUMN_INT));
columnsB.insert(std::make_pair<std::string, DataType>("value", DataType::COLUMN_INT));
joinDatabase->CreateTable(columnsB, tableBName.c_str());
reinterpret_cast<ColumnBase<int32_t>*>(
joinDatabase->GetTables().at(tableAName).GetColumns().at("id").get())
->InsertData(idsA);
reinterpret_cast<ColumnBase<int32_t>*>(
joinDatabase->GetTables().at(tableAName).GetColumns().at("value").get())
->InsertData(valuesA);
reinterpret_cast<ColumnBase<int32_t>*>(
joinDatabase->GetTables().at(tableBName).GetColumns().at("id").get())
->InsertData(idsB);
reinterpret_cast<ColumnBase<int32_t>*>(
joinDatabase->GetTables().at(tableBName).GetColumns().at("value").get())
->InsertData(valuesB);
GpuSqlCustomParser parser(joinDatabase, "SELECT TableA.value, TableB.value FROM TableA JOIN "
"TableB ON TableA.id = TableB.id;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payloadA = result->payloads().at("TableA.value");
auto& payloadB = result->payloads().at("TableB.value");
ASSERT_EQ(2, payloadA.intpayload().intdata_size());
ASSERT_EQ(2, payloadB.intpayload().intdata_size());
// TODO assert values
Database::RemoveFromInMemoryDatabaseList(dbName.c_str());
}
// == JOIN ==
TEST(DispatcherTestsRegression, JoinTableAliasResult)
{
Context::getInstance();
const std::string dbName = "JoinTestDb";
const std::string tableAName = "TableA";
const std::string tableBName = "TableB";
const int32_t blockSize = 32; // length of a block
std::vector<int32_t> idsA = {1};
std::vector<int32_t> valuesA = {50};
std::vector<int32_t> idsB = {1, 1};
std::vector<int32_t> valuesB = {32, 33};
std::shared_ptr<Database> joinDatabase = std::make_shared<Database>(dbName.c_str(), blockSize);
Database::AddToInMemoryDatabaseList(joinDatabase);
auto columnsA = std::unordered_map<std::string, DataType>();
columnsA.insert(std::make_pair<std::string, DataType>("id", DataType::COLUMN_INT));
columnsA.insert(std::make_pair<std::string, DataType>("value", DataType::COLUMN_INT));
joinDatabase->CreateTable(columnsA, tableAName.c_str());
auto columnsB = std::unordered_map<std::string, DataType>();
columnsB.insert(std::make_pair<std::string, DataType>("id", DataType::COLUMN_INT));
columnsB.insert(std::make_pair<std::string, DataType>("value", DataType::COLUMN_INT));
joinDatabase->CreateTable(columnsB, tableBName.c_str());
reinterpret_cast<ColumnBase<int32_t>*>(
joinDatabase->GetTables().at(tableAName).GetColumns().at("id").get())
->InsertData(idsA);
reinterpret_cast<ColumnBase<int32_t>*>(
joinDatabase->GetTables().at(tableAName).GetColumns().at("value").get())
->InsertData(valuesA);
reinterpret_cast<ColumnBase<int32_t>*>(
joinDatabase->GetTables().at(tableBName).GetColumns().at("id").get())
->InsertData(idsB);
reinterpret_cast<ColumnBase<int32_t>*>(
joinDatabase->GetTables().at(tableBName).GetColumns().at("value").get())
->InsertData(valuesB);
GpuSqlCustomParser parser(joinDatabase, "SELECT ta.value, tb.value FROM TableA AS ta JOIN "
"TableB AS tb ON ta.id = tb.id;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payloadA = result->payloads().at("TableA.value");
auto& payloadB = result->payloads().at("TableB.value");
ASSERT_EQ(2, payloadA.intpayload().intdata_size());
ASSERT_EQ(2, payloadB.intpayload().intdata_size());
Database::RemoveFromInMemoryDatabaseList(dbName.c_str());
}
*/
TEST(DispatcherTestsRegression, AggregationInWhereWrongSemantic)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1, COUNT(colInteger2) FROM TableA WHERE "
"COUNT(colInteger2) > 10 GROUP "
"BY colInteger1;");
ASSERT_THROW(parser.Parse(), AggregationWhereException);
}
TEST(DispatcherTestsRegression, CreateIndexWrongSemantic)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"CREATE TABLE tblA (colA GEO_POINT, INDEX ind (colA));");
ASSERT_THROW(parser.Parse(), IndexColumnDataTypeException);
GpuSqlCustomParser parser2(DispatcherObjs::GetInstance().database,
"CREATE TABLE tblA (colA GEO_POLYGON, INDEX ind (colA));");
ASSERT_THROW(parser2.Parse(), IndexColumnDataTypeException);
}
TEST(DispatcherTestsRegression, FixedColumnOrdering)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1, SUM(colInteger2) FROM TableA GROUP BY "
"colInteger1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->columnorder().Get(0), "TableA.colInteger1");
ASSERT_EQ(result->columnorder().Get(1), "SUM(colInteger2)");
}
TEST(DispatcherTestsRegression, MultiBlockAggWithAlias)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT COUNT(colInteger2) as alias FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payloadAlias = result->payloads().at("alias");
ASSERT_EQ(1, payloadAlias.int64payload().int64data_size());
}
TEST(DispatcherTestsRegression, ConstantWithWhere)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT 1 FROM TableA WHERE colInteger1 > 0;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payload = result->payloads().at("1");
ASSERT_EQ(2048, payload.intpayload().intdata_size());
for (size_t i = 0; i < payload.intpayload().intdata_size(); i++)
{
ASSERT_EQ(1, payload.intpayload().intdata()[i]) << " at resrow " << i;
}
}
TEST(DispatcherTestsRegression, FunctionWithWhere)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT POW(2,2) FROM TableA WHERE colInteger1 > 0;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payload = result->payloads().at("POW(2,2)");
ASSERT_EQ(2048, payload.intpayload().intdata_size());
for (size_t i = 0; i < payload.intpayload().intdata_size(); i++)
{
ASSERT_EQ(4, payload.intpayload().intdata()[i]) << " at resrow " << i;
}
}
TEST(DispatcherTestsRegression, FunctionWithWhereAndLimit)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT POW(2,2) FROM TableA WHERE ABS(colInteger1) >= 512 LIMIT 1536;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payload = result->payloads().at("POW(2,2)");
ASSERT_EQ(1536, payload.intpayload().intdata_size());
for (size_t i = 0; i < payload.intpayload().intdata_size(); i++)
{
ASSERT_EQ(4, payload.intpayload().intdata()[i]) << " at resrow " << i;
}
}
| 40.457658 | 111 | 0.659927 | veselyja |
b34a02e8f2302d1c41d7c7187ef2a1028b702a9d | 2,314 | cpp | C++ | lib-rdmnet/example/dummy_device.cpp | vanvught/rpidmx512 | b56bb2db406247b4fd4c56aa372952939f4a3290 | [
"MIT"
] | 328 | 2015-02-26T09:54:16.000Z | 2022-03-31T11:04:00.000Z | lib-rdmnet/example/dummy_device.cpp | vanvught/rpidmx512 | b56bb2db406247b4fd4c56aa372952939f4a3290 | [
"MIT"
] | 195 | 2016-07-13T10:43:37.000Z | 2022-03-20T19:14:55.000Z | lib-rdmnet/example/dummy_device.cpp | vanvught/rpidmx512 | b56bb2db406247b4fd4c56aa372952939f4a3290 | [
"MIT"
] | 113 | 2015-06-08T04:54:23.000Z | 2022-02-15T09:06:10.000Z | /**
* @file dummy_device.cpp
*
*/
/* Copyright (C) 2019-2021 by Arjan van Vught mailto:info@orangepi-dmx.nl
*
* 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 <cstdio>
#include <cstdint>
#include <cstring>
#include <stdlib.h>
#include "hardware.h"
#include "network.h"
#include "ledblink.h"
#include "firmwareversion.h"
#include "software_version.h"
#include "rdmnetdevice.h"
#include "lightsetdebug.h"
#include "rdmpersonality.h"
#include "rdmdeviceparams.h"
#include "identify.h"
int main(int argc, char **argv) {
Hardware hw;
Network nw;
LedBlink lb;
FirmwareVersion fw(SOFTWARE_VERSION, __DATE__, __TIME__);
if (argc < 2) {
printf("Usage: %s ip_address|interface_name\n", argv[0]);
return -1;
}
fw.Print();
if (nw.Init(argv[1]) < 0) {
fprintf(stderr, "Not able to start the network\n");
return -1;
}
nw.Print();
lb.SetMode(ledblink::Mode::NORMAL);
Identify identify;
LightSetDebug lighSetDebug;
RDMPersonality personality("LLRP Dummy device", lighSetDebug.GetDmxFootprint());
RDMNetDevice device(&personality);
RDMDeviceParams rdmDeviceParams;
if (rdmDeviceParams.Load()) {
rdmDeviceParams.Set(&device);
rdmDeviceParams.Dump();
}
device.Init();
device.Print();
device.Start();
for (;;) {
device.Run();
}
return 0;
}
| 25.152174 | 81 | 0.730337 | vanvught |
b34a5a6353725e2d7b35c78dd8471fecee5c3bb4 | 363 | cc | C++ | jax/training/21-03/21-03-22-night/a.cc | JaxVanYang/acm | ee41f1cbf692b7b1463a9467401bb6e7d38aecce | [
"MIT"
] | 2 | 2022-01-01T16:55:02.000Z | 2022-03-16T14:47:29.000Z | jax/training/21-03/21-03-22-night/a.cc | JaxVanYang/acm | ee41f1cbf692b7b1463a9467401bb6e7d38aecce | [
"MIT"
] | null | null | null | jax/training/21-03/21-03-22-night/a.cc | JaxVanYang/acm | ee41f1cbf692b7b1463a9467401bb6e7d38aecce | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
const int maxn = 1005;
int arr[maxn];
int main() {
int n, a, b, c, t;
scanf("%d%d%d%d%d", &n, &a, &b, &c, &t);
for (int i = 0; i < n; ++i) scanf("%d", arr + i);
int ans = n * a;
int k = c - b;
if (k > 0) {
for (int i = 0; i < n; ++i) ans += (t - arr[i]) * k;
}
printf("%d", ans);
} | 22.6875 | 60 | 0.432507 | JaxVanYang |
b34b3c8a71724c473ca5e182ca4726b0963d46bf | 822 | cc | C++ | libDatabase/variant.cc | marcbejerano/cpp-tools | 9ef62064a5b826b8722ff96e423ffff2d85f49f1 | [
"BSD-3-Clause"
] | null | null | null | libDatabase/variant.cc | marcbejerano/cpp-tools | 9ef62064a5b826b8722ff96e423ffff2d85f49f1 | [
"BSD-3-Clause"
] | null | null | null | libDatabase/variant.cc | marcbejerano/cpp-tools | 9ef62064a5b826b8722ff96e423ffff2d85f49f1 | [
"BSD-3-Clause"
] | null | null | null | #include "variant.h"
#include <iostream>
#include <string>
const std::string Variant::toString() const
{
std::string result = "";
switch (type) {
case CHAR: result += data.c; break;
case SHORT: result = std::to_string(data.sh); break;
case INT: result = std::to_string(data.i); break;
case LONG: result = std::to_string(data.l); break;
case FLOAT: result = std::to_string(data.f); break;
case DOUBLE:result = std::to_string(data.d); break;
case TIME:
{
char buffer[128] = {0};
size_t len = strftime(buffer, sizeof(buffer), "%F %T", &data.t);
result = std::string(buffer);
}
break;
case STRING:
default: result = s; break;
}
return result;
}
| 29.357143 | 80 | 0.536496 | marcbejerano |
b3575470bab04331f6592ea84dfbad7c51468d31 | 973 | cpp | C++ | contracts/libc++/upstream/test/std/numerics/complex.number/complex.value.ops/conj.pass.cpp | cubetrain/CubeTrain | b930a3e88e941225c2c54219267f743c790e388f | [
"MIT"
] | null | null | null | contracts/libc++/upstream/test/std/numerics/complex.number/complex.value.ops/conj.pass.cpp | cubetrain/CubeTrain | b930a3e88e941225c2c54219267f743c790e388f | [
"MIT"
] | null | null | null | contracts/libc++/upstream/test/std/numerics/complex.number/complex.value.ops/conj.pass.cpp | cubetrain/CubeTrain | b930a3e88e941225c2c54219267f743c790e388f | [
"MIT"
] | null | null | null | //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <complex>
// template<class T>
// complex<T>
// conj(const complex<T>& x);
#include <complex>
#include <cassert>
template <class T>
void
test(const std::complex<T>& z, std::complex<T> x)
{
assert(conj(z) == x);
}
template <class T>
void
test()
{
test(std::complex<T>(1, 2), std::complex<T>(1, -2));
test(std::complex<T>(-1, 2), std::complex<T>(-1, -2));
test(std::complex<T>(1, -2), std::complex<T>(1, 2));
test(std::complex<T>(-1, -2), std::complex<T>(-1, 2));
}
int main()
{
test<float>();
test<double>();
test<long double>();
}
| 23.166667 | 81 | 0.461459 | cubetrain |
b357869e3e23b1f62d8e822acd60b6e6e79393fa | 76,249 | hpp | C++ | tm_kit/infra/RealTimeApp_TimeChecker_Piece.hpp | cd606/tm_infra | 27f93cc3cf4344a962aa5faeb4105be8458d34f0 | [
"Apache-2.0"
] | 1 | 2020-05-22T08:47:05.000Z | 2020-05-22T08:47:05.000Z | tm_kit/infra/RealTimeApp_TimeChecker_Piece.hpp | cd606/tm_infra | 27f93cc3cf4344a962aa5faeb4105be8458d34f0 | [
"Apache-2.0"
] | null | null | null | tm_kit/infra/RealTimeApp_TimeChecker_Piece.hpp | cd606/tm_infra | 27f93cc3cf4344a962aa5faeb4105be8458d34f0 | [
"Apache-2.0"
] | null | null | null | template <class A0, class A1>
class TimeChecker<false, std::variant<A0,A1>> {
private:
std::bitset<2> finalMask_;
std::optional<typename StateT::TimePointType> tp0_;
VersionChecker<A0> versionChecker0_;
std::optional<typename StateT::TimePointType> tp1_;
VersionChecker<A1> versionChecker1_;
public:
TimeChecker() :
finalMask_(), tp0_(std::nullopt), versionChecker0_(), tp1_(std::nullopt), versionChecker1_()
{}
inline bool operator()(TimedDataWithEnvironment<std::variant<A0,A1>, StateT, typename StateT::TimePointType> const &data) {
switch (data.timedData.value.index()) {
case 0:
if (!versionChecker0_.checkVersion(std::get<0>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp0_ && data.timedData.timePoint < *tp0_) {
return false;
}
}
tp0_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(0);
}
break;
case 1:
if (!versionChecker1_.checkVersion(std::get<1>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp1_ && data.timedData.timePoint < *tp1_) {
return false;
}
}
tp1_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(1);
}
break;
}
return true;
}
inline bool isFinalUpdate() const {
return finalMask_.all();
}
};
template <class A0, class A1>
class TimeChecker<true, std::variant<A0,A1>> {
private:
std::bitset<2> finalMask_;
std::optional<typename StateT::TimePointType> tp0_;
VersionChecker<A0> versionChecker0_;
std::optional<typename StateT::TimePointType> tp1_;
VersionChecker<A1> versionChecker1_;
mutable std::mutex mutex_;
public:
TimeChecker() :
finalMask_(), tp0_(std::nullopt), versionChecker0_(), tp1_(std::nullopt), versionChecker1_(), mutex_()
{}
inline bool operator()(TimedDataWithEnvironment<std::variant<A0,A1>, StateT, typename StateT::TimePointType> const &data) {
std::lock_guard<std::mutex> _(mutex_);
switch (data.timedData.value.index()) {
case 0:
if (!versionChecker0_.checkVersion(std::get<0>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp0_ && data.timedData.timePoint < *tp0_) {
return false;
}
}
tp0_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(0);
}
break;
case 1:
if (!versionChecker1_.checkVersion(std::get<1>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp1_ && data.timedData.timePoint < *tp1_) {
return false;
}
}
tp1_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(1);
}
break;
}
return true;
}
inline bool isFinalUpdate() const {
std::lock_guard<std::mutex> _(mutex_);
return finalMask_.all();
}
};
template <class A0, class A1, class A2>
class TimeChecker<false, std::variant<A0,A1,A2>> {
private:
std::bitset<3> finalMask_;
std::optional<typename StateT::TimePointType> tp0_;
VersionChecker<A0> versionChecker0_;
std::optional<typename StateT::TimePointType> tp1_;
VersionChecker<A1> versionChecker1_;
std::optional<typename StateT::TimePointType> tp2_;
VersionChecker<A2> versionChecker2_;
public:
TimeChecker() :
finalMask_(), tp0_(std::nullopt), versionChecker0_(), tp1_(std::nullopt), versionChecker1_(), tp2_(std::nullopt), versionChecker2_()
{}
inline bool operator()(TimedDataWithEnvironment<std::variant<A0,A1,A2>, StateT, typename StateT::TimePointType> const &data) {
switch (data.timedData.value.index()) {
case 0:
if (!versionChecker0_.checkVersion(std::get<0>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp0_ && data.timedData.timePoint < *tp0_) {
return false;
}
}
tp0_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(0);
}
break;
case 1:
if (!versionChecker1_.checkVersion(std::get<1>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp1_ && data.timedData.timePoint < *tp1_) {
return false;
}
}
tp1_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(1);
}
break;
case 2:
if (!versionChecker2_.checkVersion(std::get<2>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp2_ && data.timedData.timePoint < *tp2_) {
return false;
}
}
tp2_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(2);
}
break;
}
return true;
}
inline bool isFinalUpdate() const {
return finalMask_.all();
}
};
template <class A0, class A1, class A2>
class TimeChecker<true, std::variant<A0,A1,A2>> {
private:
std::bitset<3> finalMask_;
std::optional<typename StateT::TimePointType> tp0_;
VersionChecker<A0> versionChecker0_;
std::optional<typename StateT::TimePointType> tp1_;
VersionChecker<A1> versionChecker1_;
std::optional<typename StateT::TimePointType> tp2_;
VersionChecker<A2> versionChecker2_;
mutable std::mutex mutex_;
public:
TimeChecker() :
finalMask_(), tp0_(std::nullopt), versionChecker0_(), tp1_(std::nullopt), versionChecker1_(), tp2_(std::nullopt), versionChecker2_(), mutex_()
{}
inline bool operator()(TimedDataWithEnvironment<std::variant<A0,A1,A2>, StateT, typename StateT::TimePointType> const &data) {
std::lock_guard<std::mutex> _(mutex_);
switch (data.timedData.value.index()) {
case 0:
if (!versionChecker0_.checkVersion(std::get<0>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp0_ && data.timedData.timePoint < *tp0_) {
return false;
}
}
tp0_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(0);
}
break;
case 1:
if (!versionChecker1_.checkVersion(std::get<1>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp1_ && data.timedData.timePoint < *tp1_) {
return false;
}
}
tp1_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(1);
}
break;
case 2:
if (!versionChecker2_.checkVersion(std::get<2>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp2_ && data.timedData.timePoint < *tp2_) {
return false;
}
}
tp2_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(2);
}
break;
}
return true;
}
inline bool isFinalUpdate() const {
std::lock_guard<std::mutex> _(mutex_);
return finalMask_.all();
}
};
template <class A0, class A1, class A2, class A3>
class TimeChecker<false, std::variant<A0,A1,A2,A3>> {
private:
std::bitset<4> finalMask_;
std::optional<typename StateT::TimePointType> tp0_;
VersionChecker<A0> versionChecker0_;
std::optional<typename StateT::TimePointType> tp1_;
VersionChecker<A1> versionChecker1_;
std::optional<typename StateT::TimePointType> tp2_;
VersionChecker<A2> versionChecker2_;
std::optional<typename StateT::TimePointType> tp3_;
VersionChecker<A3> versionChecker3_;
public:
TimeChecker() :
finalMask_(), tp0_(std::nullopt), versionChecker0_(), tp1_(std::nullopt), versionChecker1_(), tp2_(std::nullopt), versionChecker2_(), tp3_(std::nullopt), versionChecker3_()
{}
inline bool operator()(TimedDataWithEnvironment<std::variant<A0,A1,A2,A3>, StateT, typename StateT::TimePointType> const &data) {
switch (data.timedData.value.index()) {
case 0:
if (!versionChecker0_.checkVersion(std::get<0>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp0_ && data.timedData.timePoint < *tp0_) {
return false;
}
}
tp0_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(0);
}
break;
case 1:
if (!versionChecker1_.checkVersion(std::get<1>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp1_ && data.timedData.timePoint < *tp1_) {
return false;
}
}
tp1_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(1);
}
break;
case 2:
if (!versionChecker2_.checkVersion(std::get<2>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp2_ && data.timedData.timePoint < *tp2_) {
return false;
}
}
tp2_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(2);
}
break;
case 3:
if (!versionChecker3_.checkVersion(std::get<3>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp3_ && data.timedData.timePoint < *tp3_) {
return false;
}
}
tp3_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(3);
}
break;
}
return true;
}
inline bool isFinalUpdate() const {
return finalMask_.all();
}
};
template <class A0, class A1, class A2, class A3>
class TimeChecker<true, std::variant<A0,A1,A2,A3>> {
private:
std::bitset<4> finalMask_;
std::optional<typename StateT::TimePointType> tp0_;
VersionChecker<A0> versionChecker0_;
std::optional<typename StateT::TimePointType> tp1_;
VersionChecker<A1> versionChecker1_;
std::optional<typename StateT::TimePointType> tp2_;
VersionChecker<A2> versionChecker2_;
std::optional<typename StateT::TimePointType> tp3_;
VersionChecker<A3> versionChecker3_;
mutable std::mutex mutex_;
public:
TimeChecker() :
finalMask_(), tp0_(std::nullopt), versionChecker0_(), tp1_(std::nullopt), versionChecker1_(), tp2_(std::nullopt), versionChecker2_(), tp3_(std::nullopt), versionChecker3_(), mutex_()
{}
inline bool operator()(TimedDataWithEnvironment<std::variant<A0,A1,A2,A3>, StateT, typename StateT::TimePointType> const &data) {
std::lock_guard<std::mutex> _(mutex_);
switch (data.timedData.value.index()) {
case 0:
if (!versionChecker0_.checkVersion(std::get<0>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp0_ && data.timedData.timePoint < *tp0_) {
return false;
}
}
tp0_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(0);
}
break;
case 1:
if (!versionChecker1_.checkVersion(std::get<1>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp1_ && data.timedData.timePoint < *tp1_) {
return false;
}
}
tp1_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(1);
}
break;
case 2:
if (!versionChecker2_.checkVersion(std::get<2>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp2_ && data.timedData.timePoint < *tp2_) {
return false;
}
}
tp2_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(2);
}
break;
case 3:
if (!versionChecker3_.checkVersion(std::get<3>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp3_ && data.timedData.timePoint < *tp3_) {
return false;
}
}
tp3_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(3);
}
break;
}
return true;
}
inline bool isFinalUpdate() const {
std::lock_guard<std::mutex> _(mutex_);
return finalMask_.all();
}
};
template <class A0, class A1, class A2, class A3, class A4>
class TimeChecker<false, std::variant<A0,A1,A2,A3,A4>> {
private:
std::bitset<5> finalMask_;
std::optional<typename StateT::TimePointType> tp0_;
VersionChecker<A0> versionChecker0_;
std::optional<typename StateT::TimePointType> tp1_;
VersionChecker<A1> versionChecker1_;
std::optional<typename StateT::TimePointType> tp2_;
VersionChecker<A2> versionChecker2_;
std::optional<typename StateT::TimePointType> tp3_;
VersionChecker<A3> versionChecker3_;
std::optional<typename StateT::TimePointType> tp4_;
VersionChecker<A4> versionChecker4_;
public:
TimeChecker() :
finalMask_(), tp0_(std::nullopt), versionChecker0_(), tp1_(std::nullopt), versionChecker1_(), tp2_(std::nullopt), versionChecker2_(), tp3_(std::nullopt), versionChecker3_(), tp4_(std::nullopt), versionChecker4_()
{}
inline bool operator()(TimedDataWithEnvironment<std::variant<A0,A1,A2,A3,A4>, StateT, typename StateT::TimePointType> const &data) {
switch (data.timedData.value.index()) {
case 0:
if (!versionChecker0_.checkVersion(std::get<0>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp0_ && data.timedData.timePoint < *tp0_) {
return false;
}
}
tp0_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(0);
}
break;
case 1:
if (!versionChecker1_.checkVersion(std::get<1>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp1_ && data.timedData.timePoint < *tp1_) {
return false;
}
}
tp1_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(1);
}
break;
case 2:
if (!versionChecker2_.checkVersion(std::get<2>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp2_ && data.timedData.timePoint < *tp2_) {
return false;
}
}
tp2_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(2);
}
break;
case 3:
if (!versionChecker3_.checkVersion(std::get<3>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp3_ && data.timedData.timePoint < *tp3_) {
return false;
}
}
tp3_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(3);
}
break;
case 4:
if (!versionChecker4_.checkVersion(std::get<4>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp4_ && data.timedData.timePoint < *tp4_) {
return false;
}
}
tp4_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(4);
}
break;
}
return true;
}
inline bool isFinalUpdate() const {
return finalMask_.all();
}
};
template <class A0, class A1, class A2, class A3, class A4>
class TimeChecker<true, std::variant<A0,A1,A2,A3,A4>> {
private:
std::bitset<5> finalMask_;
std::optional<typename StateT::TimePointType> tp0_;
VersionChecker<A0> versionChecker0_;
std::optional<typename StateT::TimePointType> tp1_;
VersionChecker<A1> versionChecker1_;
std::optional<typename StateT::TimePointType> tp2_;
VersionChecker<A2> versionChecker2_;
std::optional<typename StateT::TimePointType> tp3_;
VersionChecker<A3> versionChecker3_;
std::optional<typename StateT::TimePointType> tp4_;
VersionChecker<A4> versionChecker4_;
mutable std::mutex mutex_;
public:
TimeChecker() :
finalMask_(), tp0_(std::nullopt), versionChecker0_(), tp1_(std::nullopt), versionChecker1_(), tp2_(std::nullopt), versionChecker2_(), tp3_(std::nullopt), versionChecker3_(), tp4_(std::nullopt), versionChecker4_(), mutex_()
{}
inline bool operator()(TimedDataWithEnvironment<std::variant<A0,A1,A2,A3,A4>, StateT, typename StateT::TimePointType> const &data) {
std::lock_guard<std::mutex> _(mutex_);
switch (data.timedData.value.index()) {
case 0:
if (!versionChecker0_.checkVersion(std::get<0>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp0_ && data.timedData.timePoint < *tp0_) {
return false;
}
}
tp0_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(0);
}
break;
case 1:
if (!versionChecker1_.checkVersion(std::get<1>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp1_ && data.timedData.timePoint < *tp1_) {
return false;
}
}
tp1_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(1);
}
break;
case 2:
if (!versionChecker2_.checkVersion(std::get<2>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp2_ && data.timedData.timePoint < *tp2_) {
return false;
}
}
tp2_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(2);
}
break;
case 3:
if (!versionChecker3_.checkVersion(std::get<3>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp3_ && data.timedData.timePoint < *tp3_) {
return false;
}
}
tp3_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(3);
}
break;
case 4:
if (!versionChecker4_.checkVersion(std::get<4>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp4_ && data.timedData.timePoint < *tp4_) {
return false;
}
}
tp4_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(4);
}
break;
}
return true;
}
inline bool isFinalUpdate() const {
std::lock_guard<std::mutex> _(mutex_);
return finalMask_.all();
}
};
template <class A0, class A1, class A2, class A3, class A4, class A5>
class TimeChecker<false, std::variant<A0,A1,A2,A3,A4,A5>> {
private:
std::bitset<6> finalMask_;
std::optional<typename StateT::TimePointType> tp0_;
VersionChecker<A0> versionChecker0_;
std::optional<typename StateT::TimePointType> tp1_;
VersionChecker<A1> versionChecker1_;
std::optional<typename StateT::TimePointType> tp2_;
VersionChecker<A2> versionChecker2_;
std::optional<typename StateT::TimePointType> tp3_;
VersionChecker<A3> versionChecker3_;
std::optional<typename StateT::TimePointType> tp4_;
VersionChecker<A4> versionChecker4_;
std::optional<typename StateT::TimePointType> tp5_;
VersionChecker<A5> versionChecker5_;
public:
TimeChecker() :
finalMask_(), tp0_(std::nullopt), versionChecker0_(), tp1_(std::nullopt), versionChecker1_(), tp2_(std::nullopt), versionChecker2_(), tp3_(std::nullopt), versionChecker3_(), tp4_(std::nullopt), versionChecker4_(), tp5_(std::nullopt), versionChecker5_()
{}
inline bool operator()(TimedDataWithEnvironment<std::variant<A0,A1,A2,A3,A4,A5>, StateT, typename StateT::TimePointType> const &data) {
switch (data.timedData.value.index()) {
case 0:
if (!versionChecker0_.checkVersion(std::get<0>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp0_ && data.timedData.timePoint < *tp0_) {
return false;
}
}
tp0_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(0);
}
break;
case 1:
if (!versionChecker1_.checkVersion(std::get<1>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp1_ && data.timedData.timePoint < *tp1_) {
return false;
}
}
tp1_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(1);
}
break;
case 2:
if (!versionChecker2_.checkVersion(std::get<2>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp2_ && data.timedData.timePoint < *tp2_) {
return false;
}
}
tp2_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(2);
}
break;
case 3:
if (!versionChecker3_.checkVersion(std::get<3>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp3_ && data.timedData.timePoint < *tp3_) {
return false;
}
}
tp3_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(3);
}
break;
case 4:
if (!versionChecker4_.checkVersion(std::get<4>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp4_ && data.timedData.timePoint < *tp4_) {
return false;
}
}
tp4_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(4);
}
break;
case 5:
if (!versionChecker5_.checkVersion(std::get<5>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp5_ && data.timedData.timePoint < *tp5_) {
return false;
}
}
tp5_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(5);
}
break;
}
return true;
}
inline bool isFinalUpdate() const {
return finalMask_.all();
}
};
template <class A0, class A1, class A2, class A3, class A4, class A5>
class TimeChecker<true, std::variant<A0,A1,A2,A3,A4,A5>> {
private:
std::bitset<6> finalMask_;
std::optional<typename StateT::TimePointType> tp0_;
VersionChecker<A0> versionChecker0_;
std::optional<typename StateT::TimePointType> tp1_;
VersionChecker<A1> versionChecker1_;
std::optional<typename StateT::TimePointType> tp2_;
VersionChecker<A2> versionChecker2_;
std::optional<typename StateT::TimePointType> tp3_;
VersionChecker<A3> versionChecker3_;
std::optional<typename StateT::TimePointType> tp4_;
VersionChecker<A4> versionChecker4_;
std::optional<typename StateT::TimePointType> tp5_;
VersionChecker<A5> versionChecker5_;
mutable std::mutex mutex_;
public:
TimeChecker() :
finalMask_(), tp0_(std::nullopt), versionChecker0_(), tp1_(std::nullopt), versionChecker1_(), tp2_(std::nullopt), versionChecker2_(), tp3_(std::nullopt), versionChecker3_(), tp4_(std::nullopt), versionChecker4_(), tp5_(std::nullopt), versionChecker5_(), mutex_()
{}
inline bool operator()(TimedDataWithEnvironment<std::variant<A0,A1,A2,A3,A4,A5>, StateT, typename StateT::TimePointType> const &data) {
std::lock_guard<std::mutex> _(mutex_);
switch (data.timedData.value.index()) {
case 0:
if (!versionChecker0_.checkVersion(std::get<0>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp0_ && data.timedData.timePoint < *tp0_) {
return false;
}
}
tp0_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(0);
}
break;
case 1:
if (!versionChecker1_.checkVersion(std::get<1>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp1_ && data.timedData.timePoint < *tp1_) {
return false;
}
}
tp1_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(1);
}
break;
case 2:
if (!versionChecker2_.checkVersion(std::get<2>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp2_ && data.timedData.timePoint < *tp2_) {
return false;
}
}
tp2_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(2);
}
break;
case 3:
if (!versionChecker3_.checkVersion(std::get<3>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp3_ && data.timedData.timePoint < *tp3_) {
return false;
}
}
tp3_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(3);
}
break;
case 4:
if (!versionChecker4_.checkVersion(std::get<4>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp4_ && data.timedData.timePoint < *tp4_) {
return false;
}
}
tp4_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(4);
}
break;
case 5:
if (!versionChecker5_.checkVersion(std::get<5>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp5_ && data.timedData.timePoint < *tp5_) {
return false;
}
}
tp5_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(5);
}
break;
}
return true;
}
inline bool isFinalUpdate() const {
std::lock_guard<std::mutex> _(mutex_);
return finalMask_.all();
}
};
template <class A0, class A1, class A2, class A3, class A4, class A5, class A6>
class TimeChecker<false, std::variant<A0,A1,A2,A3,A4,A5,A6>> {
private:
std::bitset<7> finalMask_;
std::optional<typename StateT::TimePointType> tp0_;
VersionChecker<A0> versionChecker0_;
std::optional<typename StateT::TimePointType> tp1_;
VersionChecker<A1> versionChecker1_;
std::optional<typename StateT::TimePointType> tp2_;
VersionChecker<A2> versionChecker2_;
std::optional<typename StateT::TimePointType> tp3_;
VersionChecker<A3> versionChecker3_;
std::optional<typename StateT::TimePointType> tp4_;
VersionChecker<A4> versionChecker4_;
std::optional<typename StateT::TimePointType> tp5_;
VersionChecker<A5> versionChecker5_;
std::optional<typename StateT::TimePointType> tp6_;
VersionChecker<A6> versionChecker6_;
public:
TimeChecker() :
finalMask_(), tp0_(std::nullopt), versionChecker0_(), tp1_(std::nullopt), versionChecker1_(), tp2_(std::nullopt), versionChecker2_(), tp3_(std::nullopt), versionChecker3_(), tp4_(std::nullopt), versionChecker4_(), tp5_(std::nullopt), versionChecker5_(), tp6_(std::nullopt), versionChecker6_()
{}
inline bool operator()(TimedDataWithEnvironment<std::variant<A0,A1,A2,A3,A4,A5,A6>, StateT, typename StateT::TimePointType> const &data) {
switch (data.timedData.value.index()) {
case 0:
if (!versionChecker0_.checkVersion(std::get<0>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp0_ && data.timedData.timePoint < *tp0_) {
return false;
}
}
tp0_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(0);
}
break;
case 1:
if (!versionChecker1_.checkVersion(std::get<1>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp1_ && data.timedData.timePoint < *tp1_) {
return false;
}
}
tp1_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(1);
}
break;
case 2:
if (!versionChecker2_.checkVersion(std::get<2>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp2_ && data.timedData.timePoint < *tp2_) {
return false;
}
}
tp2_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(2);
}
break;
case 3:
if (!versionChecker3_.checkVersion(std::get<3>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp3_ && data.timedData.timePoint < *tp3_) {
return false;
}
}
tp3_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(3);
}
break;
case 4:
if (!versionChecker4_.checkVersion(std::get<4>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp4_ && data.timedData.timePoint < *tp4_) {
return false;
}
}
tp4_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(4);
}
break;
case 5:
if (!versionChecker5_.checkVersion(std::get<5>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp5_ && data.timedData.timePoint < *tp5_) {
return false;
}
}
tp5_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(5);
}
break;
case 6:
if (!versionChecker6_.checkVersion(std::get<6>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp6_ && data.timedData.timePoint < *tp6_) {
return false;
}
}
tp6_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(6);
}
break;
}
return true;
}
inline bool isFinalUpdate() const {
return finalMask_.all();
}
};
template <class A0, class A1, class A2, class A3, class A4, class A5, class A6>
class TimeChecker<true, std::variant<A0,A1,A2,A3,A4,A5,A6>> {
private:
std::bitset<7> finalMask_;
std::optional<typename StateT::TimePointType> tp0_;
VersionChecker<A0> versionChecker0_;
std::optional<typename StateT::TimePointType> tp1_;
VersionChecker<A1> versionChecker1_;
std::optional<typename StateT::TimePointType> tp2_;
VersionChecker<A2> versionChecker2_;
std::optional<typename StateT::TimePointType> tp3_;
VersionChecker<A3> versionChecker3_;
std::optional<typename StateT::TimePointType> tp4_;
VersionChecker<A4> versionChecker4_;
std::optional<typename StateT::TimePointType> tp5_;
VersionChecker<A5> versionChecker5_;
std::optional<typename StateT::TimePointType> tp6_;
VersionChecker<A6> versionChecker6_;
mutable std::mutex mutex_;
public:
TimeChecker() :
finalMask_(), tp0_(std::nullopt), versionChecker0_(), tp1_(std::nullopt), versionChecker1_(), tp2_(std::nullopt), versionChecker2_(), tp3_(std::nullopt), versionChecker3_(), tp4_(std::nullopt), versionChecker4_(), tp5_(std::nullopt), versionChecker5_(), tp6_(std::nullopt), versionChecker6_(), mutex_()
{}
inline bool operator()(TimedDataWithEnvironment<std::variant<A0,A1,A2,A3,A4,A5,A6>, StateT, typename StateT::TimePointType> const &data) {
std::lock_guard<std::mutex> _(mutex_);
switch (data.timedData.value.index()) {
case 0:
if (!versionChecker0_.checkVersion(std::get<0>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp0_ && data.timedData.timePoint < *tp0_) {
return false;
}
}
tp0_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(0);
}
break;
case 1:
if (!versionChecker1_.checkVersion(std::get<1>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp1_ && data.timedData.timePoint < *tp1_) {
return false;
}
}
tp1_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(1);
}
break;
case 2:
if (!versionChecker2_.checkVersion(std::get<2>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp2_ && data.timedData.timePoint < *tp2_) {
return false;
}
}
tp2_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(2);
}
break;
case 3:
if (!versionChecker3_.checkVersion(std::get<3>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp3_ && data.timedData.timePoint < *tp3_) {
return false;
}
}
tp3_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(3);
}
break;
case 4:
if (!versionChecker4_.checkVersion(std::get<4>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp4_ && data.timedData.timePoint < *tp4_) {
return false;
}
}
tp4_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(4);
}
break;
case 5:
if (!versionChecker5_.checkVersion(std::get<5>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp5_ && data.timedData.timePoint < *tp5_) {
return false;
}
}
tp5_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(5);
}
break;
case 6:
if (!versionChecker6_.checkVersion(std::get<6>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp6_ && data.timedData.timePoint < *tp6_) {
return false;
}
}
tp6_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(6);
}
break;
}
return true;
}
inline bool isFinalUpdate() const {
std::lock_guard<std::mutex> _(mutex_);
return finalMask_.all();
}
};
template <class A0, class A1, class A2, class A3, class A4, class A5, class A6, class A7>
class TimeChecker<false, std::variant<A0,A1,A2,A3,A4,A5,A6,A7>> {
private:
std::bitset<8> finalMask_;
std::optional<typename StateT::TimePointType> tp0_;
VersionChecker<A0> versionChecker0_;
std::optional<typename StateT::TimePointType> tp1_;
VersionChecker<A1> versionChecker1_;
std::optional<typename StateT::TimePointType> tp2_;
VersionChecker<A2> versionChecker2_;
std::optional<typename StateT::TimePointType> tp3_;
VersionChecker<A3> versionChecker3_;
std::optional<typename StateT::TimePointType> tp4_;
VersionChecker<A4> versionChecker4_;
std::optional<typename StateT::TimePointType> tp5_;
VersionChecker<A5> versionChecker5_;
std::optional<typename StateT::TimePointType> tp6_;
VersionChecker<A6> versionChecker6_;
std::optional<typename StateT::TimePointType> tp7_;
VersionChecker<A7> versionChecker7_;
public:
TimeChecker() :
finalMask_(), tp0_(std::nullopt), versionChecker0_(), tp1_(std::nullopt), versionChecker1_(), tp2_(std::nullopt), versionChecker2_(), tp3_(std::nullopt), versionChecker3_(), tp4_(std::nullopt), versionChecker4_(), tp5_(std::nullopt), versionChecker5_(), tp6_(std::nullopt), versionChecker6_(), tp7_(std::nullopt), versionChecker7_()
{}
inline bool operator()(TimedDataWithEnvironment<std::variant<A0,A1,A2,A3,A4,A5,A6,A7>, StateT, typename StateT::TimePointType> const &data) {
switch (data.timedData.value.index()) {
case 0:
if (!versionChecker0_.checkVersion(std::get<0>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp0_ && data.timedData.timePoint < *tp0_) {
return false;
}
}
tp0_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(0);
}
break;
case 1:
if (!versionChecker1_.checkVersion(std::get<1>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp1_ && data.timedData.timePoint < *tp1_) {
return false;
}
}
tp1_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(1);
}
break;
case 2:
if (!versionChecker2_.checkVersion(std::get<2>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp2_ && data.timedData.timePoint < *tp2_) {
return false;
}
}
tp2_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(2);
}
break;
case 3:
if (!versionChecker3_.checkVersion(std::get<3>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp3_ && data.timedData.timePoint < *tp3_) {
return false;
}
}
tp3_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(3);
}
break;
case 4:
if (!versionChecker4_.checkVersion(std::get<4>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp4_ && data.timedData.timePoint < *tp4_) {
return false;
}
}
tp4_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(4);
}
break;
case 5:
if (!versionChecker5_.checkVersion(std::get<5>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp5_ && data.timedData.timePoint < *tp5_) {
return false;
}
}
tp5_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(5);
}
break;
case 6:
if (!versionChecker6_.checkVersion(std::get<6>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp6_ && data.timedData.timePoint < *tp6_) {
return false;
}
}
tp6_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(6);
}
break;
case 7:
if (!versionChecker7_.checkVersion(std::get<7>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp7_ && data.timedData.timePoint < *tp7_) {
return false;
}
}
tp7_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(7);
}
break;
}
return true;
}
inline bool isFinalUpdate() const {
return finalMask_.all();
}
};
template <class A0, class A1, class A2, class A3, class A4, class A5, class A6, class A7>
class TimeChecker<true, std::variant<A0,A1,A2,A3,A4,A5,A6,A7>> {
private:
std::bitset<8> finalMask_;
std::optional<typename StateT::TimePointType> tp0_;
VersionChecker<A0> versionChecker0_;
std::optional<typename StateT::TimePointType> tp1_;
VersionChecker<A1> versionChecker1_;
std::optional<typename StateT::TimePointType> tp2_;
VersionChecker<A2> versionChecker2_;
std::optional<typename StateT::TimePointType> tp3_;
VersionChecker<A3> versionChecker3_;
std::optional<typename StateT::TimePointType> tp4_;
VersionChecker<A4> versionChecker4_;
std::optional<typename StateT::TimePointType> tp5_;
VersionChecker<A5> versionChecker5_;
std::optional<typename StateT::TimePointType> tp6_;
VersionChecker<A6> versionChecker6_;
std::optional<typename StateT::TimePointType> tp7_;
VersionChecker<A7> versionChecker7_;
mutable std::mutex mutex_;
public:
TimeChecker() :
finalMask_(), tp0_(std::nullopt), versionChecker0_(), tp1_(std::nullopt), versionChecker1_(), tp2_(std::nullopt), versionChecker2_(), tp3_(std::nullopt), versionChecker3_(), tp4_(std::nullopt), versionChecker4_(), tp5_(std::nullopt), versionChecker5_(), tp6_(std::nullopt), versionChecker6_(), tp7_(std::nullopt), versionChecker7_(), mutex_()
{}
inline bool operator()(TimedDataWithEnvironment<std::variant<A0,A1,A2,A3,A4,A5,A6,A7>, StateT, typename StateT::TimePointType> const &data) {
std::lock_guard<std::mutex> _(mutex_);
switch (data.timedData.value.index()) {
case 0:
if (!versionChecker0_.checkVersion(std::get<0>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp0_ && data.timedData.timePoint < *tp0_) {
return false;
}
}
tp0_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(0);
}
break;
case 1:
if (!versionChecker1_.checkVersion(std::get<1>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp1_ && data.timedData.timePoint < *tp1_) {
return false;
}
}
tp1_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(1);
}
break;
case 2:
if (!versionChecker2_.checkVersion(std::get<2>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp2_ && data.timedData.timePoint < *tp2_) {
return false;
}
}
tp2_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(2);
}
break;
case 3:
if (!versionChecker3_.checkVersion(std::get<3>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp3_ && data.timedData.timePoint < *tp3_) {
return false;
}
}
tp3_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(3);
}
break;
case 4:
if (!versionChecker4_.checkVersion(std::get<4>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp4_ && data.timedData.timePoint < *tp4_) {
return false;
}
}
tp4_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(4);
}
break;
case 5:
if (!versionChecker5_.checkVersion(std::get<5>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp5_ && data.timedData.timePoint < *tp5_) {
return false;
}
}
tp5_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(5);
}
break;
case 6:
if (!versionChecker6_.checkVersion(std::get<6>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp6_ && data.timedData.timePoint < *tp6_) {
return false;
}
}
tp6_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(6);
}
break;
case 7:
if (!versionChecker7_.checkVersion(std::get<7>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp7_ && data.timedData.timePoint < *tp7_) {
return false;
}
}
tp7_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(7);
}
break;
}
return true;
}
inline bool isFinalUpdate() const {
std::lock_guard<std::mutex> _(mutex_);
return finalMask_.all();
}
};
template <class A0, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8>
class TimeChecker<false, std::variant<A0,A1,A2,A3,A4,A5,A6,A7,A8>> {
private:
std::bitset<9> finalMask_;
std::optional<typename StateT::TimePointType> tp0_;
VersionChecker<A0> versionChecker0_;
std::optional<typename StateT::TimePointType> tp1_;
VersionChecker<A1> versionChecker1_;
std::optional<typename StateT::TimePointType> tp2_;
VersionChecker<A2> versionChecker2_;
std::optional<typename StateT::TimePointType> tp3_;
VersionChecker<A3> versionChecker3_;
std::optional<typename StateT::TimePointType> tp4_;
VersionChecker<A4> versionChecker4_;
std::optional<typename StateT::TimePointType> tp5_;
VersionChecker<A5> versionChecker5_;
std::optional<typename StateT::TimePointType> tp6_;
VersionChecker<A6> versionChecker6_;
std::optional<typename StateT::TimePointType> tp7_;
VersionChecker<A7> versionChecker7_;
std::optional<typename StateT::TimePointType> tp8_;
VersionChecker<A8> versionChecker8_;
public:
TimeChecker() :
finalMask_(), tp0_(std::nullopt), versionChecker0_(), tp1_(std::nullopt), versionChecker1_(), tp2_(std::nullopt), versionChecker2_(), tp3_(std::nullopt), versionChecker3_(), tp4_(std::nullopt), versionChecker4_(), tp5_(std::nullopt), versionChecker5_(), tp6_(std::nullopt), versionChecker6_(), tp7_(std::nullopt), versionChecker7_(), tp8_(std::nullopt), versionChecker8_()
{}
inline bool operator()(TimedDataWithEnvironment<std::variant<A0,A1,A2,A3,A4,A5,A6,A7,A8>, StateT, typename StateT::TimePointType> const &data) {
switch (data.timedData.value.index()) {
case 0:
if (!versionChecker0_.checkVersion(std::get<0>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp0_ && data.timedData.timePoint < *tp0_) {
return false;
}
}
tp0_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(0);
}
break;
case 1:
if (!versionChecker1_.checkVersion(std::get<1>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp1_ && data.timedData.timePoint < *tp1_) {
return false;
}
}
tp1_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(1);
}
break;
case 2:
if (!versionChecker2_.checkVersion(std::get<2>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp2_ && data.timedData.timePoint < *tp2_) {
return false;
}
}
tp2_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(2);
}
break;
case 3:
if (!versionChecker3_.checkVersion(std::get<3>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp3_ && data.timedData.timePoint < *tp3_) {
return false;
}
}
tp3_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(3);
}
break;
case 4:
if (!versionChecker4_.checkVersion(std::get<4>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp4_ && data.timedData.timePoint < *tp4_) {
return false;
}
}
tp4_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(4);
}
break;
case 5:
if (!versionChecker5_.checkVersion(std::get<5>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp5_ && data.timedData.timePoint < *tp5_) {
return false;
}
}
tp5_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(5);
}
break;
case 6:
if (!versionChecker6_.checkVersion(std::get<6>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp6_ && data.timedData.timePoint < *tp6_) {
return false;
}
}
tp6_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(6);
}
break;
case 7:
if (!versionChecker7_.checkVersion(std::get<7>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp7_ && data.timedData.timePoint < *tp7_) {
return false;
}
}
tp7_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(7);
}
break;
case 8:
if (!versionChecker8_.checkVersion(std::get<8>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp8_ && data.timedData.timePoint < *tp8_) {
return false;
}
}
tp8_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(8);
}
break;
}
return true;
}
inline bool isFinalUpdate() const {
return finalMask_.all();
}
};
template <class A0, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8>
class TimeChecker<true, std::variant<A0,A1,A2,A3,A4,A5,A6,A7,A8>> {
private:
std::bitset<9> finalMask_;
std::optional<typename StateT::TimePointType> tp0_;
VersionChecker<A0> versionChecker0_;
std::optional<typename StateT::TimePointType> tp1_;
VersionChecker<A1> versionChecker1_;
std::optional<typename StateT::TimePointType> tp2_;
VersionChecker<A2> versionChecker2_;
std::optional<typename StateT::TimePointType> tp3_;
VersionChecker<A3> versionChecker3_;
std::optional<typename StateT::TimePointType> tp4_;
VersionChecker<A4> versionChecker4_;
std::optional<typename StateT::TimePointType> tp5_;
VersionChecker<A5> versionChecker5_;
std::optional<typename StateT::TimePointType> tp6_;
VersionChecker<A6> versionChecker6_;
std::optional<typename StateT::TimePointType> tp7_;
VersionChecker<A7> versionChecker7_;
std::optional<typename StateT::TimePointType> tp8_;
VersionChecker<A8> versionChecker8_;
mutable std::mutex mutex_;
public:
TimeChecker() :
finalMask_(), tp0_(std::nullopt), versionChecker0_(), tp1_(std::nullopt), versionChecker1_(), tp2_(std::nullopt), versionChecker2_(), tp3_(std::nullopt), versionChecker3_(), tp4_(std::nullopt), versionChecker4_(), tp5_(std::nullopt), versionChecker5_(), tp6_(std::nullopt), versionChecker6_(), tp7_(std::nullopt), versionChecker7_(), tp8_(std::nullopt), versionChecker8_(), mutex_()
{}
inline bool operator()(TimedDataWithEnvironment<std::variant<A0,A1,A2,A3,A4,A5,A6,A7,A8>, StateT, typename StateT::TimePointType> const &data) {
std::lock_guard<std::mutex> _(mutex_);
switch (data.timedData.value.index()) {
case 0:
if (!versionChecker0_.checkVersion(std::get<0>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp0_ && data.timedData.timePoint < *tp0_) {
return false;
}
}
tp0_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(0);
}
break;
case 1:
if (!versionChecker1_.checkVersion(std::get<1>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp1_ && data.timedData.timePoint < *tp1_) {
return false;
}
}
tp1_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(1);
}
break;
case 2:
if (!versionChecker2_.checkVersion(std::get<2>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp2_ && data.timedData.timePoint < *tp2_) {
return false;
}
}
tp2_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(2);
}
break;
case 3:
if (!versionChecker3_.checkVersion(std::get<3>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp3_ && data.timedData.timePoint < *tp3_) {
return false;
}
}
tp3_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(3);
}
break;
case 4:
if (!versionChecker4_.checkVersion(std::get<4>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp4_ && data.timedData.timePoint < *tp4_) {
return false;
}
}
tp4_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(4);
}
break;
case 5:
if (!versionChecker5_.checkVersion(std::get<5>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp5_ && data.timedData.timePoint < *tp5_) {
return false;
}
}
tp5_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(5);
}
break;
case 6:
if (!versionChecker6_.checkVersion(std::get<6>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp6_ && data.timedData.timePoint < *tp6_) {
return false;
}
}
tp6_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(6);
}
break;
case 7:
if (!versionChecker7_.checkVersion(std::get<7>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp7_ && data.timedData.timePoint < *tp7_) {
return false;
}
}
tp7_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(7);
}
break;
case 8:
if (!versionChecker8_.checkVersion(std::get<8>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp8_ && data.timedData.timePoint < *tp8_) {
return false;
}
}
tp8_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(8);
}
break;
}
return true;
}
inline bool isFinalUpdate() const {
std::lock_guard<std::mutex> _(mutex_);
return finalMask_.all();
}
};
template <class A0, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9>
class TimeChecker<false, std::variant<A0,A1,A2,A3,A4,A5,A6,A7,A8,A9>> {
private:
std::bitset<10> finalMask_;
std::optional<typename StateT::TimePointType> tp0_;
VersionChecker<A0> versionChecker0_;
std::optional<typename StateT::TimePointType> tp1_;
VersionChecker<A1> versionChecker1_;
std::optional<typename StateT::TimePointType> tp2_;
VersionChecker<A2> versionChecker2_;
std::optional<typename StateT::TimePointType> tp3_;
VersionChecker<A3> versionChecker3_;
std::optional<typename StateT::TimePointType> tp4_;
VersionChecker<A4> versionChecker4_;
std::optional<typename StateT::TimePointType> tp5_;
VersionChecker<A5> versionChecker5_;
std::optional<typename StateT::TimePointType> tp6_;
VersionChecker<A6> versionChecker6_;
std::optional<typename StateT::TimePointType> tp7_;
VersionChecker<A7> versionChecker7_;
std::optional<typename StateT::TimePointType> tp8_;
VersionChecker<A8> versionChecker8_;
std::optional<typename StateT::TimePointType> tp9_;
VersionChecker<A9> versionChecker9_;
public:
TimeChecker() :
finalMask_(), tp0_(std::nullopt), versionChecker0_(), tp1_(std::nullopt), versionChecker1_(), tp2_(std::nullopt), versionChecker2_(), tp3_(std::nullopt), versionChecker3_(), tp4_(std::nullopt), versionChecker4_(), tp5_(std::nullopt), versionChecker5_(), tp6_(std::nullopt), versionChecker6_(), tp7_(std::nullopt), versionChecker7_(), tp8_(std::nullopt), versionChecker8_(), tp9_(std::nullopt), versionChecker9_()
{}
inline bool operator()(TimedDataWithEnvironment<std::variant<A0,A1,A2,A3,A4,A5,A6,A7,A8,A9>, StateT, typename StateT::TimePointType> const &data) {
switch (data.timedData.value.index()) {
case 0:
if (!versionChecker0_.checkVersion(std::get<0>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp0_ && data.timedData.timePoint < *tp0_) {
return false;
}
}
tp0_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(0);
}
break;
case 1:
if (!versionChecker1_.checkVersion(std::get<1>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp1_ && data.timedData.timePoint < *tp1_) {
return false;
}
}
tp1_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(1);
}
break;
case 2:
if (!versionChecker2_.checkVersion(std::get<2>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp2_ && data.timedData.timePoint < *tp2_) {
return false;
}
}
tp2_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(2);
}
break;
case 3:
if (!versionChecker3_.checkVersion(std::get<3>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp3_ && data.timedData.timePoint < *tp3_) {
return false;
}
}
tp3_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(3);
}
break;
case 4:
if (!versionChecker4_.checkVersion(std::get<4>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp4_ && data.timedData.timePoint < *tp4_) {
return false;
}
}
tp4_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(4);
}
break;
case 5:
if (!versionChecker5_.checkVersion(std::get<5>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp5_ && data.timedData.timePoint < *tp5_) {
return false;
}
}
tp5_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(5);
}
break;
case 6:
if (!versionChecker6_.checkVersion(std::get<6>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp6_ && data.timedData.timePoint < *tp6_) {
return false;
}
}
tp6_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(6);
}
break;
case 7:
if (!versionChecker7_.checkVersion(std::get<7>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp7_ && data.timedData.timePoint < *tp7_) {
return false;
}
}
tp7_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(7);
}
break;
case 8:
if (!versionChecker8_.checkVersion(std::get<8>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp8_ && data.timedData.timePoint < *tp8_) {
return false;
}
}
tp8_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(8);
}
break;
case 9:
if (!versionChecker9_.checkVersion(std::get<9>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp9_ && data.timedData.timePoint < *tp9_) {
return false;
}
}
tp9_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(9);
}
break;
}
return true;
}
inline bool isFinalUpdate() const {
return finalMask_.all();
}
};
template <class A0, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9>
class TimeChecker<true, std::variant<A0,A1,A2,A3,A4,A5,A6,A7,A8,A9>> {
private:
std::bitset<10> finalMask_;
std::optional<typename StateT::TimePointType> tp0_;
VersionChecker<A0> versionChecker0_;
std::optional<typename StateT::TimePointType> tp1_;
VersionChecker<A1> versionChecker1_;
std::optional<typename StateT::TimePointType> tp2_;
VersionChecker<A2> versionChecker2_;
std::optional<typename StateT::TimePointType> tp3_;
VersionChecker<A3> versionChecker3_;
std::optional<typename StateT::TimePointType> tp4_;
VersionChecker<A4> versionChecker4_;
std::optional<typename StateT::TimePointType> tp5_;
VersionChecker<A5> versionChecker5_;
std::optional<typename StateT::TimePointType> tp6_;
VersionChecker<A6> versionChecker6_;
std::optional<typename StateT::TimePointType> tp7_;
VersionChecker<A7> versionChecker7_;
std::optional<typename StateT::TimePointType> tp8_;
VersionChecker<A8> versionChecker8_;
std::optional<typename StateT::TimePointType> tp9_;
VersionChecker<A9> versionChecker9_;
mutable std::mutex mutex_;
public:
TimeChecker() :
finalMask_(), tp0_(std::nullopt), versionChecker0_(), tp1_(std::nullopt), versionChecker1_(), tp2_(std::nullopt), versionChecker2_(), tp3_(std::nullopt), versionChecker3_(), tp4_(std::nullopt), versionChecker4_(), tp5_(std::nullopt), versionChecker5_(), tp6_(std::nullopt), versionChecker6_(), tp7_(std::nullopt), versionChecker7_(), tp8_(std::nullopt), versionChecker8_(), tp9_(std::nullopt), versionChecker9_(), mutex_()
{}
inline bool operator()(TimedDataWithEnvironment<std::variant<A0,A1,A2,A3,A4,A5,A6,A7,A8,A9>, StateT, typename StateT::TimePointType> const &data) {
std::lock_guard<std::mutex> _(mutex_);
switch (data.timedData.value.index()) {
case 0:
if (!versionChecker0_.checkVersion(std::get<0>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp0_ && data.timedData.timePoint < *tp0_) {
return false;
}
}
tp0_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(0);
}
break;
case 1:
if (!versionChecker1_.checkVersion(std::get<1>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp1_ && data.timedData.timePoint < *tp1_) {
return false;
}
}
tp1_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(1);
}
break;
case 2:
if (!versionChecker2_.checkVersion(std::get<2>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp2_ && data.timedData.timePoint < *tp2_) {
return false;
}
}
tp2_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(2);
}
break;
case 3:
if (!versionChecker3_.checkVersion(std::get<3>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp3_ && data.timedData.timePoint < *tp3_) {
return false;
}
}
tp3_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(3);
}
break;
case 4:
if (!versionChecker4_.checkVersion(std::get<4>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp4_ && data.timedData.timePoint < *tp4_) {
return false;
}
}
tp4_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(4);
}
break;
case 5:
if (!versionChecker5_.checkVersion(std::get<5>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp5_ && data.timedData.timePoint < *tp5_) {
return false;
}
}
tp5_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(5);
}
break;
case 6:
if (!versionChecker6_.checkVersion(std::get<6>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp6_ && data.timedData.timePoint < *tp6_) {
return false;
}
}
tp6_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(6);
}
break;
case 7:
if (!versionChecker7_.checkVersion(std::get<7>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp7_ && data.timedData.timePoint < *tp7_) {
return false;
}
}
tp7_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(7);
}
break;
case 8:
if (!versionChecker8_.checkVersion(std::get<8>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp8_ && data.timedData.timePoint < *tp8_) {
return false;
}
}
tp8_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(8);
}
break;
case 9:
if (!versionChecker9_.checkVersion(std::get<9>(data.timedData.value))) {
return false;
}
if (StateT::CheckTime) {
if (tp9_ && data.timedData.timePoint < *tp9_) {
return false;
}
}
tp9_ = data.timedData.timePoint;
if (data.timedData.finalFlag) {
finalMask_.set(9);
}
break;
}
return true;
}
inline bool isFinalUpdate() const {
std::lock_guard<std::mutex> _(mutex_);
return finalMask_.all();
}
}; | 36.996118 | 430 | 0.520322 | cd606 |
b35bd95e3401934078a1539df76ca686a32eff47 | 271 | cpp | C++ | atcoder/abc195/A/main.cpp | xirc/cp-algorithm | 89c67cff2f00459c5bb020ab44bff5ae419a1728 | [
"Apache-2.0"
] | 8 | 2020-12-23T07:54:53.000Z | 2021-11-23T02:46:35.000Z | atcoder/abc195/A/main.cpp | xirc/cp-algorithm | 89c67cff2f00459c5bb020ab44bff5ae419a1728 | [
"Apache-2.0"
] | 1 | 2020-11-07T13:22:29.000Z | 2020-12-20T12:54:00.000Z | atcoder/abc195/A/main.cpp | xirc/cp-algorithm | 89c67cff2f00459c5bb020ab44bff5ae419a1728 | [
"Apache-2.0"
] | 1 | 2021-01-16T03:40:10.000Z | 2021-01-16T03:40:10.000Z | #include <bits/stdc++.h>
using namespace std;
using ll = int64_t;
using ff = long double;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int M, H;
cin >> M >> H;
cout << (H % M == 0 ? "Yes" : "No") << endl;
return 0;
} | 16.9375 | 48 | 0.542435 | xirc |
b35f99f968ed1708af0d2fa82b8de89ce4d61017 | 7,696 | cpp | C++ | flatland_server/src/yaml_preprocessor.cpp | eborghi10/flatland | 5bcd91630b2e8c682084519162828b5b7855e710 | [
"BSD-3-Clause"
] | 59 | 2017-09-22T22:19:39.000Z | 2022-03-03T03:48:22.000Z | flatland_server/src/yaml_preprocessor.cpp | eborghi10/flatland | 5bcd91630b2e8c682084519162828b5b7855e710 | [
"BSD-3-Clause"
] | 34 | 2017-08-19T03:06:07.000Z | 2021-09-29T16:15:41.000Z | flatland_server/src/yaml_preprocessor.cpp | eborghi10/flatland | 5bcd91630b2e8c682084519162828b5b7855e710 | [
"BSD-3-Clause"
] | 38 | 2017-09-25T11:46:42.000Z | 2022-03-01T17:20:20.000Z | /*
* ______ __ __ __
* /\ _ \ __ /\ \/\ \ /\ \__
* \ \ \L\ \ __ __ /\_\ \_\ \ \ \____ ___\ \ ,_\ ____
* \ \ __ \/\ \/\ \\/\ \ /'_` \ \ '__`\ / __`\ \ \/ /',__\
* \ \ \/\ \ \ \_/ |\ \ \/\ \L\ \ \ \L\ \/\ \L\ \ \ \_/\__, `\
* \ \_\ \_\ \___/ \ \_\ \___,_\ \_,__/\ \____/\ \__\/\____/
* \/_/\/_/\/__/ \/_/\/__,_ /\/___/ \/___/ \/__/\/___/
* @copyright Copyright 2018 Avidbots Corp.
* @name yaml_preprocessor
* @brief Yaml preprocessor using Lua
* @author Joseph Duchesne
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2017, Avidbots Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Avidbots Corp. 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 "flatland_server/yaml_preprocessor.h"
#include <ros/ros.h>
#include <boost/algorithm/string/trim.hpp>
#include <boost/lexical_cast.hpp>
#include <cstdlib>
#include <cstring>
namespace flatland_server {
void YamlPreprocessor::Parse(YAML::Node &node) {
YamlPreprocessor::ProcessNodes(node);
}
void YamlPreprocessor::ProcessNodes(YAML::Node &node) {
switch (node.Type()) {
case YAML::NodeType::Sequence:
for (YAML::Node child : node) {
YamlPreprocessor::ProcessNodes(child);
}
break;
case YAML::NodeType::Map:
for (YAML::iterator it = node.begin(); it != node.end(); ++it) {
YamlPreprocessor::ProcessNodes(it->second);
}
break;
case YAML::NodeType::Scalar:
if (node.as<std::string>().compare(0, 5, "$eval") == 0) {
ProcessScalarNode(node);
}
break;
default:
ROS_DEBUG_STREAM(
"Yaml Preprocessor found an unexpected type: " << node.Type());
break;
}
}
void YamlPreprocessor::ProcessScalarNode(YAML::Node &node) {
std::string value = node.as<std::string>().substr(5); // omit the $parse
boost::algorithm::trim(value); // trim whitespace
ROS_INFO_STREAM("Attempting to parse lua " << value);
if (value.find("return ") == std::string::npos) { // Has no return statement
value = "return " + value;
}
// Create the Lua context
lua_State *L = luaL_newstate();
luaL_openlibs(L);
lua_pushcfunction(L, YamlPreprocessor::LuaGetEnv);
lua_setglobal(L, "env");
lua_pushcfunction(L, YamlPreprocessor::LuaGetParam);
lua_setglobal(L, "param");
try { /* Attempt to run the Lua string and parse its results */
int error = luaL_dostring(L, value.c_str());
if (error) {
ROS_ERROR_STREAM(lua_tostring(L, -1));
lua_pop(L, 1); /* pop error message from the stack */
} else {
int t = lua_type(L, 1);
if (t == LUA_TNIL) {
node = "";
ROS_INFO_STREAM("Preprocessor parsed " << value << " as empty string");
} else if (t == LUA_TBOOLEAN) {
ROS_INFO_STREAM("Preprocessor parsed "
<< value << " as bool "
<< (lua_toboolean(L, 1) ? "true" : "false"));
node = lua_toboolean(L, 1) ? "true" : "false";
} else if (t == LUA_TSTRING || t == LUA_TNUMBER) {
ROS_INFO_STREAM("Preprocessor parsed " << value << " as "
<< lua_tostring(L, 1));
node = lua_tostring(L, 1);
} else {
ROS_ERROR_STREAM("No lua output for " << value);
}
}
} catch (
...) { /* Something went wrong parsing the lua, or gettings its results */
ROS_ERROR_STREAM("Lua error in: " << value);
}
}
YAML::Node YamlPreprocessor::LoadParse(const std::string &path) {
YAML::Node node;
try {
node = YAML::LoadFile(path);
} catch (const YAML::BadFile &e) {
throw YAMLException("File does not exist, path=" + path);
} catch (const YAML::ParserException &e) {
throw YAMLException("Malformatted file, path=" + path, e);
} catch (const YAML::Exception &e) {
throw YAMLException("Error loading file, path=" + path, e);
}
YamlPreprocessor::Parse(node);
return node;
}
int YamlPreprocessor::LuaGetEnv(lua_State *L) {
const char *name = lua_tostring(L, 1);
const char *env = std::getenv(name);
if (lua_gettop(L) == 2 && env == NULL) { // use default
if (lua_isnumber(L, 2)) {
lua_pushnumber(L, lua_tonumber(L, 2));
} else if (lua_isstring(L, 2)) {
lua_pushstring(L, lua_tostring(L, 2));
} else if (lua_isboolean(L, 2)) {
lua_pushboolean(L, lua_toboolean(L, 2));
}
} else { // no default
if (env == NULL) { // Push back a nil
ROS_WARN_STREAM("No environment variable for: " << name);
lua_pushnil(L);
} else {
ROS_WARN_STREAM("Found env for " << name);
try { // Try to push a number
double x = boost::lexical_cast<double>(env);
lua_pushnumber(L, x);
} catch (boost::bad_lexical_cast &) { // Otherwise it's a string
lua_pushstring(L, env);
}
}
}
return 1; // 1 return value
}
int YamlPreprocessor::LuaGetParam(lua_State *L) {
const char *name = lua_tostring(L, 1);
std::string param_s;
double param_d;
bool param_b;
if (lua_gettop(L) == 2 && !ros::param::has(name)) { // use default
if (lua_isnumber(L, 2)) {
lua_pushnumber(L, lua_tonumber(L, 2));
} else if (lua_isboolean(L, 2)) {
lua_pushboolean(L, lua_toboolean(L, 2));
} else if (lua_isstring(L, 2)) {
lua_pushstring(L, lua_tostring(L, 2));
} else {
ROS_WARN_STREAM("Couldn't load int/double/string value at param "
<< name);
lua_pushnil(L);
}
} else { // no default
if (!ros::param::has(name)) { // Push back a nil
ROS_WARN_STREAM("No rosparam found for: " << name);
lua_pushnil(L);
} else {
if (ros::param::get(name, param_d)) {
lua_pushnumber(L, param_d);
} else if (ros::param::get(name, param_s)) {
lua_pushstring(L, param_s.c_str());
} else if (ros::param::get(name, param_b)) {
lua_pushstring(L, param_b ? "true" : "false");
} else {
ROS_WARN_STREAM("Couldn't load int/double/string value at param "
<< name);
lua_pushnil(L);
}
}
}
return 1; // 1 return value
}
} | 35.465438 | 80 | 0.602521 | eborghi10 |
b3609fd8fd48b8b18034c9e7ab7fc55a02ec86dd | 27,197 | cpp | C++ | ConceptEngine/ConceptEngine/ConceptEngineRenderer/Editor/Editor.cpp | Ludaxord/ConceptEngine | 16775bc9b518d4fd4c8bd32bb5f297223dfacbae | [
"MIT"
] | 4 | 2021-01-10T00:46:21.000Z | 2022-02-25T18:43:26.000Z | ConceptEngine/ConceptEngine/ConceptEngineRenderer/Editor/Editor.cpp | Ludaxord/ConceptEngine | 16775bc9b518d4fd4c8bd32bb5f297223dfacbae | [
"MIT"
] | null | null | null | ConceptEngine/ConceptEngine/ConceptEngineRenderer/Editor/Editor.cpp | Ludaxord/ConceptEngine | 16775bc9b518d4fd4c8bd32bb5f297223dfacbae | [
"MIT"
] | null | null | null | #include "Editor.h"
#include "../Rendering/DebugUI.h"
#include "../Rendering/CERenderer.h"
#include "../Core/Engine/Engine.h"
#include "../Core/Engine/EngineLoop.h"
#include "../Core/Engine/EngineGlobals.h"
#include "../Scene/CEScene.h"
#include "../Scene/Lights/DirectionalLight.h"
#include "../Scene/Lights/PointLight.h"
#include "../Scene/Components/CEMeshComponent.h"
#include "../Core/Application/Application.h"
#include "../Debug/Console/Console.h"
#include <imgui_internal.h>
#include "Boot/CECore.h"
#include "Boot/Callbacks/CEEngineController.h"
#include "Debug/Console/CEConsoleVariable.h"
#include "Platform/Generic/Console/CETypedConsole.h"
static float MainMenuBarHeight = 0.0f;
static bool ShowRenderSettings = false;
TCEConsoleVariable<bool> GShowSceneGraph(true);
static void DrawMenu();
static void DrawSideWindow();
static void DrawRenderSettings();
static void DrawSceneInfo();
static void DrawFloat3Control(const std::string& Label, XMFLOAT3& Value, float ResetValue = 0.0f, float ColumnWidth = 100.0f, float Speed = 0.01f)
{
ImGui::PushID(Label.c_str());
ImGui::Columns(2, nullptr, false);
// Text
ImGui::SetColumnWidth(0, ColumnWidth);
ImGui::Text(Label.c_str());
ImGui::NextColumn();
// Drag Floats
ImGui::PushMultiItemsWidths(3, ImGui::CalcItemWidth());
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0));
ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 0.0f);
float LineHeight = GImGui->Font->FontSize + GImGui->Style.FramePadding.y * 2.0f;
ImVec2 ButtonSize = ImVec2(LineHeight + 3.0f, LineHeight);
// X
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.8f, 0.1f, 0.15f, 1.0f));
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.9f, 0.2f, 0.2f, 1.0f));
ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.8f, 0.1f, 0.15f, 1.0f));
if (ImGui::Button("X", ButtonSize))
{
Value.x = ResetValue;
}
ImGui::PopStyleColor(3);
ImGui::SameLine();
ImGui::DragFloat("##X", &Value.x, Speed);
ImGui::PopItemWidth();
ImGui::SameLine();
// Y
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.2f, 0.7f, 0.2f, 1.0f));
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.3f, 0.8f, 0.3f, 1.0f));
ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.2f, 0.7f, 0.2f, 1.0f));
if (ImGui::Button("Y", ButtonSize))
{
Value.y = ResetValue;
}
ImGui::PopStyleColor(3);
ImGui::SameLine();
ImGui::DragFloat("##Y", &Value.y, Speed);
ImGui::PopItemWidth();
ImGui::SameLine();
// Z
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.1f, 0.25f, 0.8f, 1.0f));
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.2f, 0.35f, 0.9f, 1.0f));
ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.1f, 0.25f, 0.8f, 1.0f));
if (ImGui::Button("Z", ButtonSize))
{
Value.z = ResetValue;
}
ImGui::PopStyleColor(3);
ImGui::SameLine();
ImGui::DragFloat("##Z", &Value.z, Speed);
ImGui::PopItemWidth();
// Reset
ImGui::PopStyleVar();
ImGui::PopStyleVar();
ImGui::Columns(1);
ImGui::PopID();
}
static void DrawMenu()
{
CEDebugUI::DrawUI([]
{
if (ImGui::BeginMainMenuBar())
{
// Set Size
MainMenuBarHeight = ImGui::GetWindowHeight();
// Menu
if (ImGui::BeginMenu("File"))
{
if (ImGui::MenuItem("Toggle Fullscreen"))
{
CECore::GetPlatform()->GetWindow()->ToggleFullscreen();
}
if (ImGui::MenuItem("Quit"))
{
GEngineController.Exit();
}
ImGui::EndMenu();
}
if (ImGui::BeginMenu("View"))
{
ImGui::MenuItem("Render Settings", NULL, &ShowRenderSettings);
//ImGui::MenuItem("SceneGraph", NULL, &ShowSceneGraph);
//ImGui::MenuItem("Profiler", NULL, &GlobalDrawProfiler);
//ImGui::MenuItem("Texture Debugger", NULL, &GlobalDrawTextureDebugger);
ImGui::EndMenu();
}
ImGui::EndMainMenuBar();
}
});
}
static void DrawSideWindow()
{
CEDebugUI::DrawUI([]
{
const uint32 WindowWidth = CECore::GetPlatform()->GetWindow()->GetWidth();
const uint32 WindowHeight = CECore::GetPlatform()->GetWindow()->GetHeight();
const float Width = Math::Max(WindowWidth * 0.3f, 400.0f);
const float Height = WindowHeight * 0.7f;
ImGui::PushStyleColor(ImGuiCol_ResizeGrip, 0);
ImGui::PushStyleColor(ImGuiCol_ResizeGripHovered, 0);
ImGui::PushStyleColor(ImGuiCol_ResizeGripActive, 0);
ImGui::SetNextWindowPos(
ImVec2(float(WindowWidth) * 0.5f, float(WindowHeight) * 0.175f),
ImGuiCond_Appearing,
ImVec2(0.5f, 0.0f));
ImGui::SetNextWindowSize(
ImVec2(Width, Height),
ImGuiCond_Appearing);
const ImGuiWindowFlags Flags =
ImGuiWindowFlags_NoResize |
ImGuiWindowFlags_NoCollapse |
ImGuiWindowFlags_NoFocusOnAppearing |
ImGuiWindowFlags_NoSavedSettings;
bool TempDrawProfiler = GShowSceneGraph.GetBool();
if (ImGui::Begin(
"SceneGraph",
&TempDrawProfiler,
Flags))
{
DrawSceneInfo();
}
ImGui::PopStyleColor();
ImGui::PopStyleColor();
ImGui::PopStyleColor();
ImGui::End();
GShowSceneGraph.SetBool(TempDrawProfiler);
});
}
static void DrawRenderSettings()
{
ImGui::BeginChild("RendererInfo");
CEWindowShape WindowShape;
CECore::GetPlatform()->GetWindow()->GetWindowShape(WindowShape);
ImGui::Spacing();
ImGui::Text("Renderer Info");
ImGui::Separator();
ImGui::Indent();
ImGui::Text("Resolution: %d x %d", WindowShape.Width, WindowShape.Height);
//ImGui::Checkbox("Enable Z-PrePass", &GlobalPrePassEnabled);
//ImGui::Checkbox("Enable VSync", &GlobalVSyncEnabled);
//ImGui::Checkbox("Enable Frustum Culling", &GlobalFrustumCullEnabled);
//ImGui::Checkbox("Draw AABBs", &GlobalDrawAABBs);
static const char* AAItems[] =
{
"OFF",
"FXAA",
};
static int32 CurrentItem = 0;
//if (GlobalFXAAEnabled)
//{
// CurrentItem = 1;
//}
//else
//{
// CurrentItem = 0;
//}
if (ImGui::Combo("Anti-Aliasing", &CurrentItem, AAItems, IM_ARRAYSIZE(AAItems)))
{
//if (CurrentItem == 0)
//{
// GlobalFXAAEnabled = false;
//}
//else if (CurrentItem == 1)
//{
// GlobalFXAAEnabled = true;
//}
}
ImGui::Spacing();
ImGui::Text("Shadow Settings:");
ImGui::Separator();
static const char* Items[] =
{
"8192x8192",
"4096x4096",
"3072x3072",
"2048x2048",
"1024x1024",
"512x512",
"256x256"
};
//LightSettings Settings = GlobalRenderer->GetLightSettings();
//if (Settings.ShadowMapWidth == 8192)
//{
// CurrentItem = 0;
//}
//else if (Settings.ShadowMapWidth == 4096)
//{
// CurrentItem = 1;
//}
//else if (Settings.ShadowMapWidth == 3072)
//{
// CurrentItem = 2;
//}
//else if (Settings.ShadowMapWidth == 2048)
//{
// CurrentItem = 3;
//}
//else if (Settings.ShadowMapWidth == 1024)
//{
// CurrentItem = 4;
//}
//else if (Settings.ShadowMapWidth == 512)
//{
// CurrentItem = 5;
//}
//else if (Settings.ShadowMapWidth == 256)
//{
// CurrentItem = 6;
//}
//if (ImGui::Combo("Directional Light ShadowMap", &CurrentItem, Items, IM_ARRAYSIZE(Items)))
//{
// if (CurrentItem == 0)
// {
// Settings.ShadowMapWidth = 8192;
// Settings.ShadowMapHeight = 8192;
// }
// else if (CurrentItem == 1)
// {
// Settings.ShadowMapWidth = 4096;
// Settings.ShadowMapHeight = 4096;
// }
// else if (CurrentItem == 2)
// {
// Settings.ShadowMapWidth = 3072;
// Settings.ShadowMapHeight = 3072;
// }
// else if (CurrentItem == 3)
// {
// Settings.ShadowMapWidth = 2048;
// Settings.ShadowMapHeight = 2048;
// }
// else if (CurrentItem == 4)
// {
// Settings.ShadowMapWidth = 1024;
// Settings.ShadowMapHeight = 1024;
// }
// else if (CurrentItem == 5)
// {
// Settings.ShadowMapWidth = 512;
// Settings.ShadowMapHeight = 512;
// }
// else if (CurrentItem == 6)
// {
// Settings.ShadowMapWidth = 256;
// Settings.ShadowMapHeight = 256;
// }
// GlobalRenderer->SetLightSettings(Settings);
//}
ImGui::Spacing();
ImGui::Text("SSAO:");
ImGui::Separator();
ImGui::Columns(2, nullptr, false);
// Text
ImGui::SetColumnWidth(0, 100.0f);
ImGui::Text("Enabled: ");
ImGui::NextColumn();
//ImGui::Checkbox("##Enabled", &GlobalSSAOEnabled);
ImGui::NextColumn();
ImGui::Text("Radius: ");
ImGui::NextColumn();
//float Radius = GlobalRenderer->GetSSAORadius();
//if (ImGui::SliderFloat("##Radius", &Radius, 0.05f, 5.0f, "%.3f"))
//{
// GlobalRenderer->SetSSAORadius(Radius);
//}
//ImGui::NextColumn();
//ImGui::Text("Bias: ");
//ImGui::NextColumn();
//float Bias = GlobalRenderer->GetSSAOBias();
//if (ImGui::SliderFloat("##Bias", &Bias, 0.0f, 0.5f, "%.3f"))
//{
// GlobalRenderer->SetSSAOBias(Bias);
//}
//ImGui::NextColumn();
//ImGui::Text("KernelSize: ");
//ImGui::NextColumn();
//int32 KernelSize = GlobalRenderer->GetSSAOKernelSize();
//if (ImGui::SliderInt("##KernelSize", &KernelSize, 4, 64))
//{
// GlobalRenderer->SetSSAOKernelSize(KernelSize);
//}
ImGui::Columns(1);
ImGui::EndChild();
}
static void DrawSceneInfo()
{
constexpr float Width = 450.0f;
ImGui::Spacing();
ImGui::Text("Current Scene");
ImGui::Separator();
CEWindowShape WindowShape;
CECore::GetPlatform()->GetWindow()->GetWindowShape(WindowShape);
// Actors
if (ImGui::TreeNode("Actors"))
{
for (Actor* Actor : GApplication->Scene->GetActors())
{
ImGui::PushID(Actor);
if (ImGui::TreeNode(Actor->GetName().c_str()))
{
// Transform
if (ImGui::TreeNode("Transform"))
{
// Transform
XMFLOAT3 Translation = Actor->GetTransform().GetTranslation();
DrawFloat3Control("Translation", Translation);
Actor->GetTransform().SetTranslation(Translation);
// Rotation
XMFLOAT3 Rotation = Actor->GetTransform().GetRotation();
Rotation = XMFLOAT3(
XMConvertToDegrees(Rotation.x),
XMConvertToDegrees(Rotation.y),
XMConvertToDegrees(Rotation.z));
DrawFloat3Control("Rotation", Rotation, 0.0f, 100.0f, 1.0f);
Rotation = XMFLOAT3(
XMConvertToRadians(Rotation.x),
XMConvertToRadians(Rotation.y),
XMConvertToRadians(Rotation.z));
Actor->GetTransform().SetRotation(Rotation);
// Scale
XMFLOAT3 Scale0 = Actor->GetTransform().GetScale();
XMFLOAT3 Scale1 = Scale0;
DrawFloat3Control("Scale", Scale0, 1.0f);
ImGui::SameLine();
static bool Uniform = false;
ImGui::Checkbox("##Uniform", &Uniform);
if (ImGui::IsItemHovered())
{
ImGui::SetTooltip("Enable Uniform Scaling");
}
if (Uniform)
{
if (Scale1.x != Scale0.x)
{
Scale0.y = Scale0.x;
Scale0.z = Scale0.x;
}
else if (Scale1.y != Scale0.y)
{
Scale0.x = Scale0.y;
Scale0.z = Scale0.y;
}
else if (Scale1.z != Scale0.z)
{
Scale0.x = Scale0.z;
Scale0.y = Scale0.z;
}
}
Actor->GetTransform().SetScale(Scale0);
ImGui::TreePop();
}
// MeshComponent
CEMeshComponent* MComponent = Actor->GetComponentOfType<CEMeshComponent>();
if (MComponent)
{
if (ImGui::TreeNode("MeshComponent"))
{
ImGui::Columns(2, nullptr, false);
ImGui::SetColumnWidth(0, 100.0f);
// Albedo
ImGui::Text("Albedo");
ImGui::NextColumn();
const XMFLOAT3& Color = MComponent->Material->GetMaterialProperties().Albedo;
float Arr[3] = { Color.x, Color.y, Color.z };
if (ImGui::ColorEdit3("##Albedo", Arr))
{
MComponent->Material->SetAlbedo(Arr[0], Arr[1], Arr[2]);
}
// Roughness
ImGui::NextColumn();
ImGui::Text("Roughness");
ImGui::NextColumn();
float Roughness = MComponent->Material->GetMaterialProperties().Roughness;
if (ImGui::SliderFloat("##Roughness", &Roughness, 0.01f, 1.0f, "%.2f"))
{
MComponent->Material->SetRoughness(Roughness);
}
// Metallic
ImGui::NextColumn();
ImGui::Text("Metallic");
ImGui::NextColumn();
float Metallic = MComponent->Material->GetMaterialProperties().Metallic;
if (ImGui::SliderFloat("##Metallic", &Metallic, 0.01f, 1.0f, "%.2f"))
{
MComponent->Material->SetMetallic(Metallic);
}
// AO
ImGui::NextColumn();
ImGui::Text("AO");
ImGui::NextColumn();
float AO = MComponent->Material->GetMaterialProperties().AO;
if (ImGui::SliderFloat("##AO", &AO, 0.01f, 1.0f, "%.2f"))
{
MComponent->Material->SetAmbientOcclusion(AO);
}
ImGui::Columns(1);
ImGui::TreePop();
}
}
ImGui::TreePop();
}
ImGui::PopID();
}
ImGui::TreePop();
}
// Lights
if (ImGui::TreeNode("Lights"))
{
for (Light* CurrentLight : GApplication->Scene->GetLights())
{
ImGui::PushID(CurrentLight);
if (IsSubClassOf<PointLight>(CurrentLight))
{
PointLight* CurrentPointLight = Cast<PointLight>(CurrentLight);
if (ImGui::TreeNode("PointLight"))
{
const float ColumnWidth = 150.0f;
// Transform
if (ImGui::TreeNode("Transform"))
{
XMFLOAT3 Translation = CurrentPointLight->GetPosition();
DrawFloat3Control("Translation", Translation, 0.0f, ColumnWidth);
CurrentPointLight->SetPosition(Translation);
ImGui::TreePop();
}
// Color
if (ImGui::TreeNode("Light Settings"))
{
ImGui::Columns(2, nullptr, false);
ImGui::SetColumnWidth(0, ColumnWidth);
ImGui::Text("Color");
ImGui::NextColumn();
const XMFLOAT3& Color = CurrentPointLight->GetColor();
float Arr[3] = { Color.x, Color.y, Color.z };
if (ImGui::ColorEdit3("##Color", Arr))
{
CurrentPointLight->SetColor(Arr[0], Arr[1], Arr[2]);
}
ImGui::NextColumn();
ImGui::Text("Intensity");
ImGui::NextColumn();
float Intensity = CurrentPointLight->GetIntensity();
if (ImGui::SliderFloat("##Intensity", &Intensity, 0.01f, 1000.0f, "%.2f"))
{
CurrentPointLight->SetIntensity(Intensity);
}
ImGui::Columns(1);
ImGui::TreePop();
}
// Shadow Settings
if (ImGui::TreeNode("Shadows"))
{
ImGui::Columns(2, nullptr, false);
ImGui::SetColumnWidth(0, ColumnWidth);
// Bias
ImGui::Text("Shadow Bias");
ImGui::NextColumn();
float ShadowBias = CurrentPointLight->GetShadowBias();
if (ImGui::SliderFloat("##ShadowBias", &ShadowBias, 0.0001f, 0.1f, "%.4f"))
{
CurrentPointLight->SetShadowBias(ShadowBias);
}
if (ImGui::IsItemHovered())
{
ImGui::SetTooltip("A Bias value used in lightning calculations\nwhen measuring the depth in a ShadowMap");
}
// Max Shadow Bias
ImGui::NextColumn();
ImGui::Text("Max Shadow Bias");
ImGui::NextColumn();
float MaxShadowBias = CurrentPointLight->GetMaxShadowBias();
if (ImGui::SliderFloat("##MaxShadowBias", &MaxShadowBias, 0.0001f, 0.1f, "%.4f"))
{
CurrentPointLight->SetMaxShadowBias(MaxShadowBias);
}
// Shadow Near Plane
ImGui::NextColumn();
ImGui::Text("Shadow Near Plane");
ImGui::NextColumn();
float ShadowNearPlane = CurrentPointLight->GetShadowNearPlane();
if (ImGui::SliderFloat("##ShadowNearPlane", &ShadowNearPlane, 0.01f, 1.0f, "%0.2f"))
{
CurrentPointLight->SetShadowNearPlane(ShadowNearPlane);
}
// Shadow Far Plane
ImGui::NextColumn();
ImGui::Text("Shadow Far Plane");
ImGui::NextColumn();
float ShadowFarPlane = CurrentPointLight->GetShadowFarPlane();
if (ImGui::SliderFloat("##ShadowFarPlane", &ShadowFarPlane, 1.0f, 100.0f, "%.1f"))
{
CurrentPointLight->SetShadowFarPlane(ShadowFarPlane);
}
ImGui::Columns(1);
ImGui::TreePop();
}
ImGui::TreePop();
}
}
else if (IsSubClassOf<DirectionalLight>(CurrentLight))
{
DirectionalLight* CurrentDirectionalLight = Cast<DirectionalLight>(CurrentLight);
if (ImGui::TreeNode("DirectionalLight"))
{
const float ColumnWidth = 150.0f;
// Color
if (ImGui::TreeNode("Light Settings"))
{
ImGui::Columns(2, nullptr, false);
ImGui::SetColumnWidth(0, ColumnWidth);
ImGui::Text("Color");
ImGui::NextColumn();
const XMFLOAT3& Color = CurrentDirectionalLight->GetColor();
float Arr[3] = { Color.x, Color.y, Color.z };
if (ImGui::ColorEdit3("##Color", Arr))
{
CurrentDirectionalLight->SetColor(Arr[0], Arr[1], Arr[2]);
}
ImGui::NextColumn();
ImGui::Text("Intensity");
ImGui::NextColumn();
float Intensity = CurrentDirectionalLight->GetIntensity();
if (ImGui::SliderFloat("##Intensity", &Intensity, 0.01f, 1000.0f, "%.2f"))
{
CurrentDirectionalLight->SetIntensity(Intensity);
}
ImGui::Columns(1);
ImGui::TreePop();
}
// Transform
if (ImGui::TreeNode("Transform"))
{
XMFLOAT3 Rotation = CurrentDirectionalLight->GetRotation();
Rotation = XMFLOAT3(
XMConvertToDegrees(Rotation.x),
XMConvertToDegrees(Rotation.y),
XMConvertToDegrees(Rotation.z)
);
DrawFloat3Control("Rotation", Rotation, 0.0f, ColumnWidth, 1.0f);
Rotation = XMFLOAT3(
XMConvertToRadians(Rotation.x),
XMConvertToRadians(Rotation.y),
XMConvertToRadians(Rotation.z)
);
CurrentDirectionalLight->SetRotation(Rotation);
ImGui::Columns(2, nullptr, false);
ImGui::SetColumnWidth(0, ColumnWidth);
ImGui::Text("Direction");
ImGui::NextColumn();
XMFLOAT3 Direction = CurrentDirectionalLight->GetDirection();
float* DirArr = reinterpret_cast<float*>(&Direction);
ImGui::InputFloat3("##Direction", DirArr, "%.3f", ImGuiInputTextFlags_::ImGuiInputTextFlags_ReadOnly);
ImGui::Columns(1);
ImGui::TreePop();
}
// Shadow Settings
if (ImGui::TreeNode("Shadow Settings"))
{
XMFLOAT3 LookAt = CurrentDirectionalLight->GetLookAt();
DrawFloat3Control("LookAt", LookAt, 0.0f, ColumnWidth);
CurrentDirectionalLight->SetLookAt(LookAt);
ImGui::Columns(2, nullptr, false);
ImGui::SetColumnWidth(0, ColumnWidth);
// Read only translation
ImGui::Text("Translation");
ImGui::NextColumn();
XMFLOAT3 Position = CurrentDirectionalLight->GetShadowMapPosition();
float* PosArr = reinterpret_cast<float*>(&Position);
ImGui::InputFloat3("##Translation", PosArr, "%.3f", ImGuiInputTextFlags_::ImGuiInputTextFlags_ReadOnly);
// Shadow Bias
ImGui::NextColumn();
ImGui::Text("Shadow Bias");
ImGui::NextColumn();
float ShadowBias = CurrentDirectionalLight->GetShadowBias();
if (ImGui::SliderFloat("##ShadowBias", &ShadowBias, 0.0001f, 0.1f, "%.4f"))
{
CurrentDirectionalLight->SetShadowBias(ShadowBias);
}
if (ImGui::IsItemHovered())
{
ImGui::SetTooltip("A Bias value used in lightning calculations\nwhen measuring the depth in a ShadowMap");
}
// Max Shadow Bias
ImGui::NextColumn();
ImGui::Text("Max Shadow Bias");
ImGui::NextColumn();
float MaxShadowBias = CurrentDirectionalLight->GetMaxShadowBias();
if (ImGui::SliderFloat("##MaxShadowBias", &MaxShadowBias, 0.0001f, 0.1f, "%.4f"))
{
CurrentDirectionalLight->SetMaxShadowBias(MaxShadowBias);
}
// Shadow Near Plane
ImGui::NextColumn();
ImGui::Text("Shadow Near Plane");
ImGui::NextColumn();
float ShadowNearPlane = CurrentDirectionalLight->GetShadowNearPlane();
if (ImGui::SliderFloat("##ShadowNearPlane", &ShadowNearPlane, 0.01f, 1.0f, "%.2f"))
{
CurrentDirectionalLight->SetShadowNearPlane(ShadowNearPlane);
}
// Shadow Far Plane
ImGui::NextColumn();
ImGui::Text("Shadow Far Plane");
ImGui::NextColumn();
float ShadowFarPlane = CurrentLight->GetShadowFarPlane();
if (ImGui::SliderFloat("##ShadowFarPlane", &ShadowFarPlane, 1.0f, 1000.0f, "%.1f"))
{
CurrentDirectionalLight->SetShadowFarPlane(ShadowFarPlane);
}
ImGui::Columns(1);
ImGui::TreePop();
}
ImGui::TreePop();
}
}
ImGui::PopID();
}
ImGui::TreePop();
}
}
void Editor::Init()
{
INIT_CONSOLE_VARIABLE("ShowSceneGraph", &GShowSceneGraph);
}
void Editor::Tick()
{
#if 0
DrawMenu();
#endif
if (GShowSceneGraph.GetBool())
{
DrawSideWindow();
}
} | 33.743176 | 146 | 0.475825 | Ludaxord |
b3612b67874f5d112db450aa7efd49bf06b6016d | 1,841 | cpp | C++ | computer-networks/udp-agenda/server1.cpp | hsnavarro/CompIME | b4f285826d001b6f818d94636a6294782f1cedf2 | [
"MIT"
] | null | null | null | computer-networks/udp-agenda/server1.cpp | hsnavarro/CompIME | b4f285826d001b6f818d94636a6294782f1cedf2 | [
"MIT"
] | null | null | null | computer-networks/udp-agenda/server1.cpp | hsnavarro/CompIME | b4f285826d001b6f818d94636a6294782f1cedf2 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
using namespace std;
#define PORT 8080
#define MAX_SIZE 100
int sockfd;
char msg[MAX_SIZE];
string ok = "Server 1 updated successfully";
struct sockaddr_in servaddr, cliaddr;
int len = sizeof(cliaddr);
map<string, string> tel_of;
string name, tel;
void take_input(string in){
name.clear(), tel.clear();
int cond = 0;
for(auto x : in){
if(x == ' ') { cond = 1; continue; }
cond ? tel += x : name += x;
}
}
void assemble(){
tel_of.clear();
ifstream readFile("agenda1");
string name, tel;
while(readFile >> name >> tel){
tel_of[name] = tel;
}
readFile.close();
}
void update(){
ofstream writeFile("agenda1");
for(auto x : tel_of){
writeFile << x.first << " " << x.second << endl;
}
writeFile.close();
}
int main() {
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
memset(&servaddr, 0, sizeof(servaddr));
memset(&cliaddr, 0, sizeof(cliaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = INADDR_ANY;
servaddr.sin_port = htons(PORT);
bind(sockfd, (const struct sockaddr *)&servaddr, sizeof(servaddr));
while(1){
recvfrom(sockfd, (char*) msg, MAX_SIZE, 0, (struct sockaddr*) &cliaddr, (socklen_t *) &len);
if(msg[0] == '#') break;
string aux(msg);
cout << "Received request: " << aux << endl;
cout << "Processing..." << endl;
take_input(aux);
assemble();
tel_of[name] = tel;
update();
cout << "Updated" << endl;
//memset(&cliaddr, 0, sizeof(cliaddr).
sendto(sockfd, ok.c_str(), ok.size(), 0, (struct sockaddr*) &cliaddr, len);
cout << "Sended" << endl;
}
close(sockfd);
return 0;
}
| 23.602564 | 99 | 0.593156 | hsnavarro |
b362223baab6702fb85b62fe0b80ec50b4d3fef0 | 4,681 | cpp | C++ | UVa 10007 count the trees/sample/sol.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | 1 | 2020-11-24T03:17:21.000Z | 2020-11-24T03:17:21.000Z | UVa 10007 count the trees/sample/sol.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | null | null | null | UVa 10007 count the trees/sample/sol.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | 1 | 2021-04-11T16:22:31.000Z | 2021-04-11T16:22:31.000Z | #include<stdio.h>
#include<iostream>
#define MAXDIGITS 793
using namespace std;
#define PLUS 1
#define MINUS -1
typedef struct
{
char digits[MAXDIGITS];
int signbit;
int lastdigit;
} bignum;
bignum catalans[301];
bignum factorials[301];
void print_bignum(bignum *);
void subtract_bignum(bignum *, bignum *, bignum *);
void int_to_bignum(int, bignum *);
void initialize_bignum(bignum *);
void digit_shift(bignum *, int);
void zero_justify(bignum *);
int compare_bignum(bignum *, bignum *);
void divide_bignum(bignum *, bignum *, bignum *);
void multiply_bignum(bignum *, bignum *, bignum *);
int compare_bignum(bignum *a, bignum *b)
{
int i;
if (b->lastdigit > a->lastdigit) return (PLUS);
if (a->lastdigit > b->lastdigit) return (MINUS);
for (i = a->lastdigit; i >= 0; i--)
{
if (a->digits[i] > b->digits[i]) return (MINUS);
if (b->digits[i] > a->digits[i]) return (PLUS);
}
return 0;
}
void print_bignum(bignum *n)
{
int i;
for (i = n->lastdigit; i >= 0; i--)
printf("%c", '0' + n->digits[i]);
printf("\n");
}
void initialize_bignum(bignum *n)
{
int_to_bignum(0, n);
}
void int_to_bignum(int s, bignum *n)
{
int i;
int t;
n->signbit = PLUS;
for (i = 0; i < MAXDIGITS; i++)
n->digits[i] = (char) 0;
n->lastdigit = -1;
t = s;
while (t > 0)
{
n->lastdigit ++;
n->digits[ n->lastdigit ] = (t % 10);
t = t / 10;
}
if (s == 0)
n->lastdigit = 0;
}
int max(int a, int b)
{
if (a > b) return (a); else return (b);
}
void zero_justify(bignum *n)
{
while ((n->lastdigit > 0) && (n->digits[ n->lastdigit ] == 0))
n->lastdigit --;
}
void digit_shift(bignum *n, int d)
{
int i;
if ((n->lastdigit == 0) && (n->digits[0] == 0)) return;
for (i = n->lastdigit; i >= 0; i--)
n->digits[i + d] = n->digits[i];
for (i = 0; i < d; i++)
n->digits[i] = 0;
n->lastdigit = n->lastdigit + d;
}
void add_bignum(bignum *a, bignum *b, bignum *c)
{
int carry;
int i;
initialize_bignum(c);
c->signbit = a->signbit;
c->lastdigit = max(a->lastdigit, b->lastdigit) + 1;
carry = 0;
for (i = 0; i <= (c->lastdigit); i++)
{
c->digits[i] = (char) (carry + a->digits[i] + b->digits[i]) % 10;
carry = (carry + a->digits[i] + b->digits[i]) / 10;
}
zero_justify(c);
}
void multiply_bignum(bignum *a, bignum *b, bignum *c)
{
bignum row;
bignum tmp;
int i, j;
initialize_bignum(c);
row = *a;
for (i = 0; i <= b->lastdigit; i++)
{
for (j = 1; j <= b->digits[i]; j++)
{
add_bignum(c, &row, &tmp);
*c = tmp;
}
digit_shift(&row, 1);
}
zero_justify(c);
}
void subtract_bignum(bignum *a, bignum *b, bignum *c)
{
int borrow;
int v;
int i;
initialize_bignum(c);
c->lastdigit = max(a->lastdigit, b->lastdigit);
borrow = 0;
for (i = 0; i <= (c->lastdigit); i++)
{
v = (a->digits[i] - borrow - b->digits[i]);
if (a->digits[i] > 0)
borrow = 0;
if (v < 0)
{
v = v + 10;
borrow = 1;
}
c->digits[i] = (char) v % 10;
}
zero_justify(c);
}
void divide_bignum(bignum *a, bignum *b, bignum *c)
{
bignum row;
bignum tmp;
int i, j;
initialize_bignum(c);
initialize_bignum(&row);
initialize_bignum(&tmp);
c->lastdigit = a->lastdigit;
for (i = a->lastdigit; i >= 0; i--)
{
digit_shift(&row, 1);
row.digits[0] = a->digits[i];
c->digits[i] = 0;
while (compare_bignum(&row, b) != PLUS)
{
c->digits[i] ++;
subtract_bignum(&row, b, &tmp);
row = tmp;
}
}
zero_justify(c);
}
void catalan(int n)
{
int counter;
bignum aux, aux2;
counter = 0;
int_to_bignum(1, &catalans[0]);
for (int i = 1; i <= n; i++)
{
counter++;
int_to_bignum((4 * i - 2), &catalans[i]);
multiply_bignum(&catalans[i - 1], &catalans[i], &aux);
int_to_bignum(i + 1, &aux2);
divide_bignum(&aux, &aux2, &catalans[i]);
}
}
void factorial(int n)
{
bignum aux;
int_to_bignum(1, &factorials[0]);
int_to_bignum(1, &factorials[1]);
for (int i = 2; i <= n; i++)
{
int_to_bignum(i, &aux);
multiply_bignum(&factorials[i - 1], &aux, &factorials[i]);
}
}
int main()
{
int n;
catalan(300);
factorial(300);
bignum aux2;
while (cin >> n && n != 0)
{
multiply_bignum(&factorials[n], &catalans[n], &aux2);
print_bignum(&aux2);
}
return 0;
} | 23.405 | 73 | 0.521043 | tadvi |
b367ee59d5f312c4f9bd67540c9725b2c2e5b863 | 796 | cc | C++ | src/Parser/AST/TFPDefStatementNode.cc | stenbror/PythonCoreNative | 9b5b1e55acf7d6adc7d8202e951872b2b9f71167 | [
"BSL-1.0"
] | null | null | null | src/Parser/AST/TFPDefStatementNode.cc | stenbror/PythonCoreNative | 9b5b1e55acf7d6adc7d8202e951872b2b9f71167 | [
"BSL-1.0"
] | null | null | null | src/Parser/AST/TFPDefStatementNode.cc | stenbror/PythonCoreNative | 9b5b1e55acf7d6adc7d8202e951872b2b9f71167 | [
"BSL-1.0"
] | 1 | 2021-05-24T11:18:32.000Z | 2021-05-24T11:18:32.000Z |
#include <ast/TFPDefStatementNode.h>
using namespace PythonCoreNative::RunTime::Parser::AST;
using namespace PythonCoreNative::RunTime::Parser;
TFPDefStatementNode::TFPDefStatementNode(
unsigned int start, unsigned int end,
std::shared_ptr<Token> op1,
std::shared_ptr<Token> op2,
std::shared_ptr<ExpressionNode> right
) : StatementNode(start, end)
{
mOp1 = op1;
mOp2 = op2;
mRight = right;
}
std::shared_ptr<Token> TFPDefStatementNode::GetOperator1()
{
return mOp1;
}
std::shared_ptr<Token> TFPDefStatementNode::GetOperator2()
{
return mOp2;
}
std::shared_ptr<ExpressionNode> TFPDefStatementNode::GetRight()
{
return mRight;
}
| 24.121212 | 66 | 0.616834 | stenbror |
b36b61be7f7d0726d37bfa4c1b71f12462e923f7 | 24,490 | cpp | C++ | MultiSource/Benchmarks/7zip/CPP/7zip/Archive/Zip/ZipIn.cpp | Nuullll/llvm-test-suite | afbdd0a9ee7770e074708b68b34a6a5312bb0b36 | [
"Apache-2.0"
] | 70 | 2019-01-15T03:03:55.000Z | 2022-03-28T02:16:13.000Z | MultiSource/Benchmarks/7zip/CPP/7zip/Archive/Zip/ZipIn.cpp | Nuullll/llvm-test-suite | afbdd0a9ee7770e074708b68b34a6a5312bb0b36 | [
"Apache-2.0"
] | 519 | 2020-09-15T07:40:51.000Z | 2022-03-31T20:51:15.000Z | MultiSource/Benchmarks/7zip/CPP/7zip/Archive/Zip/ZipIn.cpp | Nuullll/llvm-test-suite | afbdd0a9ee7770e074708b68b34a6a5312bb0b36 | [
"Apache-2.0"
] | 117 | 2020-06-24T13:11:04.000Z | 2022-03-23T15:44:23.000Z | // Archive/ZipIn.cpp
#include "StdAfx.h"
#include "../../../../C/CpuArch.h"
#include "Common/DynamicBuffer.h"
#include "../../Common/LimitedStreams.h"
#include "../../Common/StreamUtils.h"
#include "ZipIn.h"
#define Get16(p) GetUi16(p)
#define Get32(p) GetUi32(p)
#define Get64(p) GetUi64(p)
namespace NArchive {
namespace NZip {
HRESULT CInArchive::Open(IInStream *stream, const UInt64 *searchHeaderSizeLimit)
{
_inBufMode = false;
Close();
RINOK(stream->Seek(0, STREAM_SEEK_CUR, &m_StreamStartPosition));
m_Position = m_StreamStartPosition;
RINOK(FindAndReadMarker(stream, searchHeaderSizeLimit));
RINOK(stream->Seek(m_Position, STREAM_SEEK_SET, NULL));
m_Stream = stream;
return S_OK;
}
void CInArchive::Close()
{
_inBuffer.ReleaseStream();
m_Stream.Release();
}
HRESULT CInArchive::Seek(UInt64 offset)
{
return m_Stream->Seek(offset, STREAM_SEEK_SET, NULL);
}
//////////////////////////////////////
// Markers
static inline bool TestMarkerCandidate(const Byte *p, UInt32 &value)
{
value = Get32(p);
return
(value == NSignature::kLocalFileHeader) ||
(value == NSignature::kEndOfCentralDir);
}
static const UInt32 kNumMarkerAddtionalBytes = 2;
static inline bool TestMarkerCandidate2(const Byte *p, UInt32 &value)
{
value = Get32(p);
if (value == NSignature::kEndOfCentralDir)
return (Get16(p + 4) == 0);
return (value == NSignature::kLocalFileHeader && p[4] < 128);
}
HRESULT CInArchive::FindAndReadMarker(IInStream *stream, const UInt64 *searchHeaderSizeLimit)
{
ArcInfo.Clear();
m_Position = m_StreamStartPosition;
Byte marker[NSignature::kMarkerSize];
RINOK(ReadStream_FALSE(stream, marker, NSignature::kMarkerSize));
m_Position += NSignature::kMarkerSize;
if (TestMarkerCandidate(marker, m_Signature))
return S_OK;
CByteDynamicBuffer dynamicBuffer;
const UInt32 kSearchMarkerBufferSize = 0x10000;
dynamicBuffer.EnsureCapacity(kSearchMarkerBufferSize);
Byte *buffer = dynamicBuffer;
UInt32 numBytesPrev = NSignature::kMarkerSize - 1;
memcpy(buffer, marker + 1, numBytesPrev);
UInt64 curTestPos = m_StreamStartPosition + 1;
for (;;)
{
if (searchHeaderSizeLimit != NULL)
if (curTestPos - m_StreamStartPosition > *searchHeaderSizeLimit)
break;
size_t numReadBytes = kSearchMarkerBufferSize - numBytesPrev;
RINOK(ReadStream(stream, buffer + numBytesPrev, &numReadBytes));
m_Position += numReadBytes;
UInt32 numBytesInBuffer = numBytesPrev + (UInt32)numReadBytes;
const UInt32 kMarker2Size = NSignature::kMarkerSize + kNumMarkerAddtionalBytes;
if (numBytesInBuffer < kMarker2Size)
break;
UInt32 numTests = numBytesInBuffer - kMarker2Size + 1;
for (UInt32 pos = 0; pos < numTests; pos++)
{
if (buffer[pos] != 0x50)
continue;
if (TestMarkerCandidate2(buffer + pos, m_Signature))
{
curTestPos += pos;
ArcInfo.StartPosition = curTestPos;
m_Position = curTestPos + NSignature::kMarkerSize;
return S_OK;
}
}
curTestPos += numTests;
numBytesPrev = numBytesInBuffer - numTests;
memmove(buffer, buffer + numTests, numBytesPrev);
}
return S_FALSE;
}
HRESULT CInArchive::ReadBytes(void *data, UInt32 size, UInt32 *processedSize)
{
size_t realProcessedSize = size;
HRESULT result = S_OK;
if (_inBufMode)
{
try { realProcessedSize = _inBuffer.ReadBytes((Byte *)data, size); }
catch (const CInBufferException &e) { return e.ErrorCode; }
}
else
result = ReadStream(m_Stream, data, &realProcessedSize);
if (processedSize != NULL)
*processedSize = (UInt32)realProcessedSize;
m_Position += realProcessedSize;
return result;
}
void CInArchive::Skip(UInt64 num)
{
for (UInt64 i = 0; i < num; i++)
ReadByte();
}
void CInArchive::IncreaseRealPosition(UInt64 addValue)
{
if (m_Stream->Seek(addValue, STREAM_SEEK_CUR, &m_Position) != S_OK)
throw CInArchiveException(CInArchiveException::kSeekStreamError);
}
bool CInArchive::ReadBytesAndTestSize(void *data, UInt32 size)
{
UInt32 realProcessedSize;
if (ReadBytes(data, size, &realProcessedSize) != S_OK)
throw CInArchiveException(CInArchiveException::kReadStreamError);
return (realProcessedSize == size);
}
void CInArchive::SafeReadBytes(void *data, UInt32 size)
{
if (!ReadBytesAndTestSize(data, size))
throw CInArchiveException(CInArchiveException::kUnexpectedEndOfArchive);
}
void CInArchive::ReadBuffer(CByteBuffer &buffer, UInt32 size)
{
buffer.SetCapacity(size);
if (size > 0)
SafeReadBytes(buffer, size);
}
Byte CInArchive::ReadByte()
{
Byte b;
SafeReadBytes(&b, 1);
return b;
}
UInt16 CInArchive::ReadUInt16()
{
Byte buf[2];
SafeReadBytes(buf, 2);
return Get16(buf);
}
UInt32 CInArchive::ReadUInt32()
{
Byte buf[4];
SafeReadBytes(buf, 4);
return Get32(buf);
}
UInt64 CInArchive::ReadUInt64()
{
Byte buf[8];
SafeReadBytes(buf, 8);
return Get64(buf);
}
bool CInArchive::ReadUInt32(UInt32 &value)
{
Byte buf[4];
if (!ReadBytesAndTestSize(buf, 4))
return false;
value = Get32(buf);
return true;
}
void CInArchive::ReadFileName(UInt32 nameSize, AString &dest)
{
if (nameSize == 0)
dest.Empty();
char *p = dest.GetBuffer((int)nameSize);
SafeReadBytes(p, nameSize);
p[nameSize] = 0;
dest.ReleaseBuffer();
}
void CInArchive::ReadExtra(UInt32 extraSize, CExtraBlock &extraBlock,
UInt64 &unpackSize, UInt64 &packSize, UInt64 &localHeaderOffset, UInt32 &diskStartNumber)
{
extraBlock.Clear();
UInt32 remain = extraSize;
while(remain >= 4)
{
CExtraSubBlock subBlock;
subBlock.ID = ReadUInt16();
UInt32 dataSize = ReadUInt16();
remain -= 4;
if (dataSize > remain) // it's bug
dataSize = remain;
if (subBlock.ID == NFileHeader::NExtraID::kZip64)
{
if (unpackSize == 0xFFFFFFFF)
{
if (dataSize < 8)
break;
unpackSize = ReadUInt64();
remain -= 8;
dataSize -= 8;
}
if (packSize == 0xFFFFFFFF)
{
if (dataSize < 8)
break;
packSize = ReadUInt64();
remain -= 8;
dataSize -= 8;
}
if (localHeaderOffset == 0xFFFFFFFF)
{
if (dataSize < 8)
break;
localHeaderOffset = ReadUInt64();
remain -= 8;
dataSize -= 8;
}
if (diskStartNumber == 0xFFFF)
{
if (dataSize < 4)
break;
diskStartNumber = ReadUInt32();
remain -= 4;
dataSize -= 4;
}
for (UInt32 i = 0; i < dataSize; i++)
ReadByte();
}
else
{
ReadBuffer(subBlock.Data, dataSize);
extraBlock.SubBlocks.Add(subBlock);
}
remain -= dataSize;
}
Skip(remain);
}
HRESULT CInArchive::ReadLocalItem(CItemEx &item)
{
const int kBufSize = 26;
Byte p[kBufSize];
SafeReadBytes(p, kBufSize);
item.ExtractVersion.Version = p[0];
item.ExtractVersion.HostOS = p[1];
item.Flags = Get16(p + 2);
item.CompressionMethod = Get16(p + 4);
item.Time = Get32(p + 6);
item.FileCRC = Get32(p + 10);
item.PackSize = Get32(p + 14);
item.UnPackSize = Get32(p + 18);
UInt32 fileNameSize = Get16(p + 22);
item.LocalExtraSize = Get16(p + 24);
ReadFileName(fileNameSize, item.Name);
item.FileHeaderWithNameSize = 4 + NFileHeader::kLocalBlockSize + fileNameSize;
if (item.LocalExtraSize > 0)
{
UInt64 localHeaderOffset = 0;
UInt32 diskStartNumber = 0;
ReadExtra(item.LocalExtraSize, item.LocalExtra, item.UnPackSize, item.PackSize,
localHeaderOffset, diskStartNumber);
}
/*
if (item.IsDir())
item.UnPackSize = 0; // check It
*/
return S_OK;
}
static bool FlagsAreSame(CItem &i1, CItem &i2)
{
if (i1.CompressionMethod != i2.CompressionMethod)
return false;
// i1.Time
if (i1.Flags == i2.Flags)
return true;
UInt32 mask = 0xFFFF;
switch(i1.CompressionMethod)
{
case NFileHeader::NCompressionMethod::kDeflated:
mask = 0x7FF9;
break;
default:
if (i1.CompressionMethod <= NFileHeader::NCompressionMethod::kImploded)
mask = 0x7FFF;
}
return ((i1.Flags & mask) == (i2.Flags & mask));
}
HRESULT CInArchive::ReadLocalItemAfterCdItem(CItemEx &item)
{
if (item.FromLocal)
return S_OK;
try
{
RINOK(Seek(ArcInfo.Base + item.LocalHeaderPosition));
CItemEx localItem;
if (ReadUInt32() != NSignature::kLocalFileHeader)
return S_FALSE;
RINOK(ReadLocalItem(localItem));
if (!FlagsAreSame(item, localItem))
return S_FALSE;
if ((!localItem.HasDescriptor() &&
(
item.FileCRC != localItem.FileCRC ||
item.PackSize != localItem.PackSize ||
item.UnPackSize != localItem.UnPackSize
)
) ||
item.Name.Length() != localItem.Name.Length()
)
return S_FALSE;
item.FileHeaderWithNameSize = localItem.FileHeaderWithNameSize;
item.LocalExtraSize = localItem.LocalExtraSize;
item.LocalExtra = localItem.LocalExtra;
item.FromLocal = true;
}
catch(...) { return S_FALSE; }
return S_OK;
}
HRESULT CInArchive::ReadLocalItemDescriptor(CItemEx &item)
{
if (item.HasDescriptor())
{
const int kBufferSize = (1 << 12);
Byte buffer[kBufferSize];
UInt32 numBytesInBuffer = 0;
UInt32 packedSize = 0;
bool descriptorWasFound = false;
for (;;)
{
UInt32 processedSize;
RINOK(ReadBytes(buffer + numBytesInBuffer, kBufferSize - numBytesInBuffer, &processedSize));
numBytesInBuffer += processedSize;
if (numBytesInBuffer < NFileHeader::kDataDescriptorSize)
return S_FALSE;
UInt32 i;
for (i = 0; i <= numBytesInBuffer - NFileHeader::kDataDescriptorSize; i++)
{
// descriptorSignature field is Info-ZIP's extension
// to Zip specification.
UInt32 descriptorSignature = Get32(buffer + i);
// !!!! It must be fixed for Zip64 archives
UInt32 descriptorPackSize = Get32(buffer + i + 8);
if (descriptorSignature== NSignature::kDataDescriptor && descriptorPackSize == packedSize + i)
{
descriptorWasFound = true;
item.FileCRC = Get32(buffer + i + 4);
item.PackSize = descriptorPackSize;
item.UnPackSize = Get32(buffer + i + 12);
IncreaseRealPosition(Int64(Int32(0 - (numBytesInBuffer - i - NFileHeader::kDataDescriptorSize))));
break;
}
}
if (descriptorWasFound)
break;
packedSize += i;
int j;
for (j = 0; i < numBytesInBuffer; i++, j++)
buffer[j] = buffer[i];
numBytesInBuffer = j;
}
}
else
IncreaseRealPosition(item.PackSize);
return S_OK;
}
HRESULT CInArchive::ReadLocalItemAfterCdItemFull(CItemEx &item)
{
if (item.FromLocal)
return S_OK;
try
{
RINOK(ReadLocalItemAfterCdItem(item));
if (item.HasDescriptor())
{
RINOK(Seek(ArcInfo.Base + item.GetDataPosition() + item.PackSize));
if (ReadUInt32() != NSignature::kDataDescriptor)
return S_FALSE;
UInt32 crc = ReadUInt32();
UInt64 packSize, unpackSize;
/*
if (IsZip64)
{
packSize = ReadUInt64();
unpackSize = ReadUInt64();
}
else
*/
{
packSize = ReadUInt32();
unpackSize = ReadUInt32();
}
if (crc != item.FileCRC || item.PackSize != packSize || item.UnPackSize != unpackSize)
return S_FALSE;
}
}
catch(...) { return S_FALSE; }
return S_OK;
}
HRESULT CInArchive::ReadCdItem(CItemEx &item)
{
item.FromCentral = true;
const int kBufSize = 42;
Byte p[kBufSize];
SafeReadBytes(p, kBufSize);
item.MadeByVersion.Version = p[0];
item.MadeByVersion.HostOS = p[1];
item.ExtractVersion.Version = p[2];
item.ExtractVersion.HostOS = p[3];
item.Flags = Get16(p + 4);
item.CompressionMethod = Get16(p + 6);
item.Time = Get32(p + 8);
item.FileCRC = Get32(p + 12);
item.PackSize = Get32(p + 16);
item.UnPackSize = Get32(p + 20);
UInt16 headerNameSize = Get16(p + 24);
UInt16 headerExtraSize = Get16(p + 26);
UInt16 headerCommentSize = Get16(p + 28);
UInt32 headerDiskNumberStart = Get16(p + 30);
item.InternalAttributes = Get16(p + 32);
item.ExternalAttributes = Get32(p + 34);
item.LocalHeaderPosition = Get32(p + 38);
ReadFileName(headerNameSize, item.Name);
if (headerExtraSize > 0)
{
ReadExtra(headerExtraSize, item.CentralExtra, item.UnPackSize, item.PackSize,
item.LocalHeaderPosition, headerDiskNumberStart);
}
if (headerDiskNumberStart != 0)
throw CInArchiveException(CInArchiveException::kMultiVolumeArchiveAreNotSupported);
// May be these strings must be deleted
/*
if (item.IsDir())
item.UnPackSize = 0;
*/
ReadBuffer(item.Comment, headerCommentSize);
return S_OK;
}
HRESULT CInArchive::TryEcd64(UInt64 offset, CCdInfo &cdInfo)
{
RINOK(Seek(offset));
const UInt32 kEcd64Size = 56;
Byte buf[kEcd64Size];
if (!ReadBytesAndTestSize(buf, kEcd64Size))
return S_FALSE;
if (Get32(buf) != NSignature::kZip64EndOfCentralDir)
return S_FALSE;
// cdInfo.NumEntries = Get64(buf + 24);
cdInfo.Size = Get64(buf + 40);
cdInfo.Offset = Get64(buf + 48);
return S_OK;
}
HRESULT CInArchive::FindCd(CCdInfo &cdInfo)
{
UInt64 endPosition;
RINOK(m_Stream->Seek(0, STREAM_SEEK_END, &endPosition));
const UInt32 kBufSizeMax = (1 << 16) + kEcdSize + kZip64EcdLocatorSize;
CByteBuffer byteBuffer;
byteBuffer.SetCapacity(kBufSizeMax);
Byte *buf = byteBuffer;
UInt32 bufSize = (endPosition < kBufSizeMax) ? (UInt32)endPosition : kBufSizeMax;
if (bufSize < kEcdSize)
return S_FALSE;
UInt64 startPosition = endPosition - bufSize;
RINOK(m_Stream->Seek(startPosition, STREAM_SEEK_SET, &m_Position));
if (m_Position != startPosition)
return S_FALSE;
if (!ReadBytesAndTestSize(buf, bufSize))
return S_FALSE;
for (int i = (int)(bufSize - kEcdSize); i >= 0; i--)
{
if (Get32(buf + i) == NSignature::kEndOfCentralDir)
{
if (i >= kZip64EcdLocatorSize)
{
const Byte *locator = buf + i - kZip64EcdLocatorSize;
if (Get32(locator) == NSignature::kZip64EndOfCentralDirLocator)
{
UInt64 ecd64Offset = Get64(locator + 8);
if (TryEcd64(ecd64Offset, cdInfo) == S_OK)
return S_OK;
if (TryEcd64(ArcInfo.StartPosition + ecd64Offset, cdInfo) == S_OK)
{
ArcInfo.Base = ArcInfo.StartPosition;
return S_OK;
}
}
}
if (Get32(buf + i + 4) == 0)
{
// cdInfo.NumEntries = GetUInt16(buf + i + 10);
cdInfo.Size = Get32(buf + i + 12);
cdInfo.Offset = Get32(buf + i + 16);
UInt64 curPos = endPosition - bufSize + i;
UInt64 cdEnd = cdInfo.Size + cdInfo.Offset;
if (curPos != cdEnd)
{
/*
if (cdInfo.Offset <= 16 && cdInfo.Size != 0)
{
// here we support some rare ZIP files with Central directory at the start
ArcInfo.Base = 0;
}
else
*/
ArcInfo.Base = curPos - cdEnd;
}
return S_OK;
}
}
}
return S_FALSE;
}
HRESULT CInArchive::TryReadCd(CObjectVector<CItemEx> &items, UInt64 cdOffset, UInt64 cdSize, CProgressVirt *progress)
{
items.Clear();
RINOK(m_Stream->Seek(cdOffset, STREAM_SEEK_SET, &m_Position));
if (m_Position != cdOffset)
return S_FALSE;
if (!_inBuffer.Create(1 << 15))
return E_OUTOFMEMORY;
_inBuffer.SetStream(m_Stream);
_inBuffer.Init();
_inBufMode = true;
while(m_Position - cdOffset < cdSize)
{
if (ReadUInt32() != NSignature::kCentralFileHeader)
return S_FALSE;
CItemEx cdItem;
RINOK(ReadCdItem(cdItem));
items.Add(cdItem);
if (progress && items.Size() % 1000 == 0)
RINOK(progress->SetCompleted(items.Size()));
}
return (m_Position - cdOffset == cdSize) ? S_OK : S_FALSE;
}
HRESULT CInArchive::ReadCd(CObjectVector<CItemEx> &items, UInt64 &cdOffset, UInt64 &cdSize, CProgressVirt *progress)
{
ArcInfo.Base = 0;
CCdInfo cdInfo;
RINOK(FindCd(cdInfo));
HRESULT res = S_FALSE;
cdSize = cdInfo.Size;
cdOffset = cdInfo.Offset;
res = TryReadCd(items, ArcInfo.Base + cdOffset, cdSize, progress);
if (res == S_FALSE && ArcInfo.Base == 0)
{
res = TryReadCd(items, cdInfo.Offset + ArcInfo.StartPosition, cdSize, progress);
if (res == S_OK)
ArcInfo.Base = ArcInfo.StartPosition;
}
if (!ReadUInt32(m_Signature))
return S_FALSE;
return res;
}
HRESULT CInArchive::ReadLocalsAndCd(CObjectVector<CItemEx> &items, CProgressVirt *progress, UInt64 &cdOffset, int &numCdItems)
{
items.Clear();
numCdItems = 0;
while (m_Signature == NSignature::kLocalFileHeader)
{
// FSeek points to next byte after signature
// NFileHeader::CLocalBlock localHeader;
CItemEx item;
item.LocalHeaderPosition = m_Position - m_StreamStartPosition - 4; // points to signature;
RINOK(ReadLocalItem(item));
item.FromLocal = true;
ReadLocalItemDescriptor(item);
items.Add(item);
if (progress && items.Size() % 100 == 0)
RINOK(progress->SetCompleted(items.Size()));
if (!ReadUInt32(m_Signature))
break;
}
cdOffset = m_Position - 4;
int i;
for (i = 0; i < items.Size(); i++, numCdItems++)
{
if (progress && i % 1000 == 0)
RINOK(progress->SetCompleted(items.Size()));
if (m_Signature == NSignature::kEndOfCentralDir)
break;
if (m_Signature != NSignature::kCentralFileHeader)
return S_FALSE;
CItemEx cdItem;
RINOK(ReadCdItem(cdItem));
if (i == 0)
{
int j;
for (j = 0; j < items.Size(); j++)
{
CItemEx &item = items[j];
if (item.Name == cdItem.Name)
{
ArcInfo.Base = item.LocalHeaderPosition - cdItem.LocalHeaderPosition;
break;
}
}
if (j == items.Size())
return S_FALSE;
}
int index;
int left = 0, right = items.Size();
for (;;)
{
if (left >= right)
return S_FALSE;
index = (left + right) / 2;
UInt64 position = items[index].LocalHeaderPosition - ArcInfo.Base;
if (cdItem.LocalHeaderPosition == position)
break;
if (cdItem.LocalHeaderPosition < position)
right = index;
else
left = index + 1;
}
CItemEx &item = items[index];
// item.LocalHeaderPosition = cdItem.LocalHeaderPosition;
item.MadeByVersion = cdItem.MadeByVersion;
item.CentralExtra = cdItem.CentralExtra;
if (
// item.ExtractVersion != cdItem.ExtractVersion ||
!FlagsAreSame(item, cdItem) ||
item.FileCRC != cdItem.FileCRC)
return S_FALSE;
if (item.Name.Length() != cdItem.Name.Length() ||
item.PackSize != cdItem.PackSize ||
item.UnPackSize != cdItem.UnPackSize
)
return S_FALSE;
item.Name = cdItem.Name;
item.InternalAttributes = cdItem.InternalAttributes;
item.ExternalAttributes = cdItem.ExternalAttributes;
item.Comment = cdItem.Comment;
item.FromCentral = cdItem.FromCentral;
if (!ReadUInt32(m_Signature))
return S_FALSE;
}
for (i = 0; i < items.Size(); i++)
items[i].LocalHeaderPosition -= ArcInfo.Base;
return S_OK;
}
struct CEcd
{
UInt16 thisDiskNumber;
UInt16 startCDDiskNumber;
UInt16 numEntriesInCDOnThisDisk;
UInt16 numEntriesInCD;
UInt32 cdSize;
UInt32 cdStartOffset;
UInt16 commentSize;
void Parse(const Byte *p);
};
void CEcd::Parse(const Byte *p)
{
thisDiskNumber = Get16(p);
startCDDiskNumber = Get16(p + 2);
numEntriesInCDOnThisDisk = Get16(p + 4);
numEntriesInCD = Get16(p + 6);
cdSize = Get32(p + 8);
cdStartOffset = Get32(p + 12);
commentSize = Get16(p + 16);
}
struct CEcd64
{
UInt16 versionMade;
UInt16 versionNeedExtract;
UInt32 thisDiskNumber;
UInt32 startCDDiskNumber;
UInt64 numEntriesInCDOnThisDisk;
UInt64 numEntriesInCD;
UInt64 cdSize;
UInt64 cdStartOffset;
void Parse(const Byte *p);
CEcd64() { memset(this, 0, sizeof(*this)); }
};
void CEcd64::Parse(const Byte *p)
{
versionMade = Get16(p);
versionNeedExtract = Get16(p + 2);
thisDiskNumber = Get32(p + 4);
startCDDiskNumber = Get32(p + 8);
numEntriesInCDOnThisDisk = Get64(p + 12);
numEntriesInCD = Get64(p + 20);
cdSize = Get64(p + 28);
cdStartOffset = Get64(p + 36);
}
#define COPY_ECD_ITEM_16(n) if (!isZip64 || ecd. n != 0xFFFF) ecd64. n = ecd. n;
#define COPY_ECD_ITEM_32(n) if (!isZip64 || ecd. n != 0xFFFFFFFF) ecd64. n = ecd. n;
HRESULT CInArchive::ReadHeaders(CObjectVector<CItemEx> &items, CProgressVirt *progress)
{
// m_Signature must be kLocalFileHeaderSignature or
// kEndOfCentralDirSignature
// m_Position points to next byte after signature
IsZip64 = false;
items.Clear();
UInt64 cdSize, cdStartOffset;
HRESULT res;
try
{
res = ReadCd(items, cdStartOffset, cdSize, progress);
}
catch(CInArchiveException &)
{
res = S_FALSE;
}
if (res != S_FALSE && res != S_OK)
return res;
/*
if (res != S_OK)
return res;
res = S_FALSE;
*/
int numCdItems = items.Size();
if (res == S_FALSE)
{
_inBufMode = false;
ArcInfo.Base = 0;
RINOK(m_Stream->Seek(ArcInfo.StartPosition, STREAM_SEEK_SET, &m_Position));
if (m_Position != ArcInfo.StartPosition)
return S_FALSE;
if (!ReadUInt32(m_Signature))
return S_FALSE;
RINOK(ReadLocalsAndCd(items, progress, cdStartOffset, numCdItems));
cdSize = (m_Position - 4) - cdStartOffset;
cdStartOffset -= ArcInfo.Base;
}
CEcd64 ecd64;
bool isZip64 = false;
UInt64 zip64EcdStartOffset = m_Position - 4 - ArcInfo.Base;
if (m_Signature == NSignature::kZip64EndOfCentralDir)
{
IsZip64 = isZip64 = true;
UInt64 recordSize = ReadUInt64();
const int kBufSize = kZip64EcdSize;
Byte buf[kBufSize];
SafeReadBytes(buf, kBufSize);
ecd64.Parse(buf);
Skip(recordSize - kZip64EcdSize);
if (!ReadUInt32(m_Signature))
return S_FALSE;
if (ecd64.thisDiskNumber != 0 || ecd64.startCDDiskNumber != 0)
throw CInArchiveException(CInArchiveException::kMultiVolumeArchiveAreNotSupported);
if (ecd64.numEntriesInCDOnThisDisk != numCdItems ||
ecd64.numEntriesInCD != numCdItems ||
ecd64.cdSize != cdSize ||
(ecd64.cdStartOffset != cdStartOffset &&
(!items.IsEmpty())))
return S_FALSE;
}
if (m_Signature == NSignature::kZip64EndOfCentralDirLocator)
{
/* UInt32 startEndCDDiskNumber = */ ReadUInt32();
UInt64 endCDStartOffset = ReadUInt64();
/* UInt32 numberOfDisks = */ ReadUInt32();
if (zip64EcdStartOffset != endCDStartOffset)
return S_FALSE;
if (!ReadUInt32(m_Signature))
return S_FALSE;
}
if (m_Signature != NSignature::kEndOfCentralDir)
return S_FALSE;
const int kBufSize = kEcdSize - 4;
Byte buf[kBufSize];
SafeReadBytes(buf, kBufSize);
CEcd ecd;
ecd.Parse(buf);
COPY_ECD_ITEM_16(thisDiskNumber);
COPY_ECD_ITEM_16(startCDDiskNumber);
COPY_ECD_ITEM_16(numEntriesInCDOnThisDisk);
COPY_ECD_ITEM_16(numEntriesInCD);
COPY_ECD_ITEM_32(cdSize);
COPY_ECD_ITEM_32(cdStartOffset);
ReadBuffer(ArcInfo.Comment, ecd.commentSize);
if (ecd64.thisDiskNumber != 0 || ecd64.startCDDiskNumber != 0)
throw CInArchiveException(CInArchiveException::kMultiVolumeArchiveAreNotSupported);
if ((UInt16)ecd64.numEntriesInCDOnThisDisk != ((UInt16)numCdItems) ||
(UInt16)ecd64.numEntriesInCD != ((UInt16)numCdItems) ||
(UInt32)ecd64.cdSize != (UInt32)cdSize ||
((UInt32)(ecd64.cdStartOffset) != (UInt32)cdStartOffset &&
(!items.IsEmpty())))
return S_FALSE;
_inBufMode = false;
_inBuffer.Free();
IsOkHeaders = (numCdItems == items.Size());
ArcInfo.FinishPosition = m_Position;
return S_OK;
}
ISequentialInStream* CInArchive::CreateLimitedStream(UInt64 position, UInt64 size)
{
CLimitedSequentialInStream *streamSpec = new CLimitedSequentialInStream;
CMyComPtr<ISequentialInStream> stream(streamSpec);
SeekInArchive(ArcInfo.Base + position);
streamSpec->SetStream(m_Stream);
streamSpec->Init(size);
return stream.Detach();
}
IInStream* CInArchive::CreateStream()
{
CMyComPtr<IInStream> stream = m_Stream;
return stream.Detach();
}
bool CInArchive::SeekInArchive(UInt64 position)
{
UInt64 newPosition;
if (m_Stream->Seek(position, STREAM_SEEK_SET, &newPosition) != S_OK)
return false;
return (newPosition == position);
}
}}
| 27.393736 | 126 | 0.657289 | Nuullll |
b36d7f29d09c25d1d5b251965bd303b59242ab32 | 971 | cc | C++ | RAVL2/3D/Mesh/Tri.cc | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | RAVL2/3D/Mesh/Tri.cc | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | RAVL2/3D/Mesh/Tri.cc | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | // This file is part of RAVL, Recognition And Vision Library
// Copyright (C) 2002, University of Surrey
// This code may be redistributed under the terms of the GNU Lesser
// General Public License (LGPL). See the lgpl.licence file for details or
// see http://www.gnu.org/copyleft/lesser.html
// file-header-ends-here
////////////////////////////////////////////////////////////////////////////
//! rcsid="$Id: Tri.cc 1025 2002-04-24 15:53:44Z craftit $"
//! author="Charles Galambos"
//! lib=Ravl3D
//! file="Ravl/3D/Mesh/Tri.cc"
#include "Ravl/3D/Tri.hh"
namespace Ravl3DN {
//: Flips the triangle.
// Reverse the order of the vertices in the triangle.
void TriC::Flip(void) {
Swap(vertices[0],vertices[2]);
Swap(texture[0],texture[2]);
normal = normal * -1;
}
//: Update the face normal.
void TriC::UpdateFaceNormal() {
normal = (Vector3dC(Position(1) - Position(0)).Cross(Position(2) - Position(0))).Unit();
}
}
| 28.558824 | 93 | 0.610711 | isuhao |
b3710a42b03d33f32ae14ddb7236e8ec1853db92 | 893 | cpp | C++ | C++/sentence-similarity-iii.cpp | Priyansh2/LeetCode-Solutions | d613da1881ec2416ccbe15f20b8000e36ddf1291 | [
"MIT"
] | 3,269 | 2018-10-12T01:29:40.000Z | 2022-03-31T17:58:41.000Z | C++/sentence-similarity-iii.cpp | Priyansh2/LeetCode-Solutions | d613da1881ec2416ccbe15f20b8000e36ddf1291 | [
"MIT"
] | 53 | 2018-12-16T22:54:20.000Z | 2022-02-25T08:31:20.000Z | C++/sentence-similarity-iii.cpp | Priyansh2/LeetCode-Solutions | d613da1881ec2416ccbe15f20b8000e36ddf1291 | [
"MIT"
] | 1,236 | 2018-10-12T02:51:40.000Z | 2022-03-30T13:30:37.000Z | // Time: O(n)
// Space: O(1)
class Solution {
public:
bool areSentencesSimilar(string sentence1, string sentence2) {
if (size(sentence1) > size(sentence2)) {
swap(sentence1, sentence2);
}
int count = 0;
for (int step = 0; step < 2; ++step) {
for (int i = 0; i <= size(sentence1); ++i) {
char c1 = i != size(sentence1) ? sentence1[step == 0 ? i : size(sentence1) - 1 - i] : ' ';
char c2 = i != size(sentence2) ? sentence2[step == 0 ? i : size(sentence2) - 1 - i] : ' ';
if (c1 != c2) {
break;
}
if (c1 == ' ') {
++count;
}
}
}
return count >= count_if(cbegin(sentence1), cend(sentence1),
[](char x) { return x == ' '; }) + 1;
}
};
| 33.074074 | 106 | 0.410974 | Priyansh2 |
b3722316be7a68ed15c4e0fc6f2c0b18809bd1c6 | 9,135 | cpp | C++ | foedus_code/foedus-core/src/foedus/memory/shared_memory.cpp | sam1016yu/cicada-exp-sigmod2017 | 64e582370076b2923d37b279d1c32730babc15f8 | [
"Apache-2.0"
] | null | null | null | foedus_code/foedus-core/src/foedus/memory/shared_memory.cpp | sam1016yu/cicada-exp-sigmod2017 | 64e582370076b2923d37b279d1c32730babc15f8 | [
"Apache-2.0"
] | null | null | null | foedus_code/foedus-core/src/foedus/memory/shared_memory.cpp | sam1016yu/cicada-exp-sigmod2017 | 64e582370076b2923d37b279d1c32730babc15f8 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2014-2015, Hewlett-Packard Development Company, LP.
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 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
*
* HP designates this particular file as subject to the "Classpath" exception
* as provided by HP in the LICENSE.txt file that accompanied this code.
*/
#include "foedus/memory/shared_memory.hpp"
#include <fcntl.h>
#include <numa.h>
#include <numaif.h>
#include <unistd.h>
#include <valgrind.h> // just for RUNNING_ON_VALGRIND macro.
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include "foedus/assert_nd.hpp"
#include "foedus/assorted/assorted_func.hpp"
#include "foedus/debugging/rdtsc.hpp"
#include "foedus/fs/filesystem.hpp"
#include "foedus/memory/memory_id.hpp"
namespace foedus {
namespace memory {
// Note, we can't use glog in this file because shared memory is used before glog is initialized.
SharedMemory::SharedMemory(SharedMemory &&other) noexcept : block_(nullptr) {
*this = std::move(other);
}
SharedMemory& SharedMemory::operator=(SharedMemory &&other) noexcept {
release_block();
meta_path_ = other.meta_path_;
size_ = other.size_;
numa_node_ = other.numa_node_;
shmid_ = other.shmid_;
shmkey_ = other.shmkey_;
owner_pid_ = other.owner_pid_;
block_ = other.block_;
other.block_ = nullptr;
return *this;
}
bool SharedMemory::is_owned() const {
return owner_pid_ != 0 && owner_pid_ == ::getpid();
}
ErrorStack SharedMemory::alloc(
const std::string& meta_path,
uint64_t size,
int numa_node,
bool use_hugepages) {
release_block();
if (size % (1ULL << 21) != 0) {
size = ((size >> 21) + 1ULL) << 21;
}
// create a meta file. we must first create it then generate key.
// shmkey will change whenever we modify the file.
if (fs::exists(fs::Path(meta_path))) {
std::string msg = std::string("Shared memory meta file already exists:") + meta_path;
return ERROR_STACK_MSG(kErrorCodeSocShmAllocFailed, msg.c_str());
}
std::ofstream file(meta_path, std::ofstream::binary);
if (!file.is_open()) {
std::string msg = std::string("Failed to create shared memory meta file:") + meta_path;
return ERROR_STACK_MSG(kErrorCodeSocShmAllocFailed, msg.c_str());
}
// randomly generate shmkey. We initially used ftok(), but it occasionally gives lots of
// conflicts for some reason, esp on aarch64. we just need some random number, so here
// we use pid and CPU cycle.
pid_t the_pid = ::getpid();
uint64_t key64 = debugging::get_rdtsc() ^ the_pid;
key_t the_key = (key64 >> 32) ^ key64;
if (the_key == 0) {
// rdtsc and getpid not working??
std::string msg = std::string("Dubious shmkey");
return ERROR_STACK_MSG(kErrorCodeSocShmAllocFailed, msg.c_str());
}
// Write out the size/node/shmkey of the shared memory in the meta file
file.write(reinterpret_cast<char*>(&size), sizeof(size));
file.write(reinterpret_cast<char*>(&numa_node), sizeof(numa_node));
file.write(reinterpret_cast<char*>(&the_key), sizeof(key_t));
file.flush();
file.close();
size_ = size;
numa_node_ = numa_node;
owner_pid_ = the_pid;
meta_path_ = meta_path;
shmkey_ = the_key;
// if this is running under valgrind, we have to avoid using hugepages due to a bug in valgrind.
// When we are running on valgrind, we don't care performance anyway. So shouldn't matter.
if (RUNNING_ON_VALGRIND) {
use_hugepages = false;
}
// see https://bugs.kde.org/show_bug.cgi?id=338995
// Use libnuma's numa_set_preferred to initialize the NUMA node of the memory.
// This is the only way to control numa allocation for shared memory.
// mbind does nothing for shared memory.
ScopedNumaPreferred numa_scope(numa_node, true);
shmid_ = ::shmget(
shmkey_,
size_,
IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR | (use_hugepages ? SHM_HUGETLB : 0));
if (shmid_ == -1) {
std::string msg = std::string("shmget() failed! size=") + std::to_string(size_)
+ std::string(", os_error=") + assorted::os_error() + std::string(", meta_path=") + meta_path;
return ERROR_STACK_MSG(kErrorCodeSocShmAllocFailed, msg.c_str());
}
block_ = reinterpret_cast<char*>(::shmat(shmid_, nullptr, 0));
if (block_ == reinterpret_cast<void*>(-1)) {
::shmctl(shmid_, IPC_RMID, nullptr); // first thing. release it! before everything else.
block_ = nullptr;
std::stringstream msg;
msg << "shmat alloc failed!" << *this << ", error=" << assorted::os_error();
release_block();
std::string str = msg.str();
return ERROR_STACK_MSG(kErrorCodeSocShmAllocFailed, str.c_str());
}
std::memset(block_, 0, size_); // see class comment for why we do this immediately
// This memset takes a very long time due to the issue in linux kernel:
// https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=8382d914ebf72092aa15cdc2a5dcedb2daa0209d
// In linux 3.15 and later, this problem gets resolved and highly parallelizable.
return kRetOk;
}
void SharedMemory::attach(const std::string& meta_path, bool use_hugepages) {
release_block();
if (!fs::exists(fs::Path(meta_path))) {
std::cerr << "Shared memory meta file does not exist:" << meta_path << std::endl;
return;
}
// the meta file contains the size of the shared memory
std::ifstream file(meta_path, std::ifstream::binary);
if (!file.is_open()) {
std::cerr << "Failed to open shared memory meta file:" << meta_path << std::endl;
return;
}
uint64_t shared_size = 0;
int numa_node = 0;
key_t the_key = 0;
file.read(reinterpret_cast<char*>(&shared_size), sizeof(shared_size));
file.read(reinterpret_cast<char*>(&numa_node), sizeof(numa_node));
file.read(reinterpret_cast<char*>(&the_key), sizeof(key_t));
file.close();
// we always use hugepages, so it's at least 2MB
if (shared_size < (1ULL << 21)) {
std::cerr << "Failed to read size of shared memory from meta file:" << meta_path
<< ". It looks like:" << shared_size << std::endl;
return;
}
if (the_key == 0) {
std::cerr << "Failed to read shmkey from meta file:" << meta_path << std::endl;
return;
}
size_ = shared_size;
numa_node_ = numa_node;
meta_path_ = meta_path;
shmkey_ = the_key;
owner_pid_ = 0;
if (RUNNING_ON_VALGRIND) {
use_hugepages = false;
}
shmid_ = ::shmget(shmkey_, size_, use_hugepages ? SHM_HUGETLB : 0);
if (shmid_ == -1) {
std::cerr << "shmget() attach failed! size=" << size_ << ", error=" << assorted::os_error()
<< std::endl;
return;
}
block_ = reinterpret_cast<char*>(::shmat(shmid_, nullptr, 0));
if (block_ == reinterpret_cast<void*>(-1)) {
block_ = nullptr;
std::cerr << "shmat attach failed!" << *this << ", error=" << assorted::os_error() << std::endl;
release_block();
return;
}
}
void SharedMemory::mark_for_release() {
if (block_ != nullptr && shmid_ != 0) {
// Some material says that Linux allows shmget even after shmctl(IPC_RMID), but it doesn't.
// It allows shmat() after shmctl(IPC_RMID), but not shmget().
// So we have to invoke IPC_RMID after all child processes acked.
::shmctl(shmid_, IPC_RMID, nullptr);
}
}
void SharedMemory::release_block() {
if (block_ != nullptr) {
// mark the memory to be reclaimed
if (is_owned()) {
mark_for_release();
}
// Just detach it. as we already invoked shmctl(IPC_RMID) at beginning, linux will
// automatically release it once the reference count reaches zero.
int dt_ret = ::shmdt(block_);
if (dt_ret == -1) {
std::cerr << "shmdt() failed." << *this << ", error=" << assorted::os_error() << std::endl;
}
block_ = nullptr;
// clean up meta file.
if (is_owned()) {
std::remove(meta_path_.c_str());
}
}
}
std::ostream& operator<<(std::ostream& o, const SharedMemory& v) {
o << "<SharedMemory>";
o << "<meta_path>" << v.get_meta_path() << "</meta_path>";
o << "<size>" << v.get_size() << "</size>";
o << "<owned>" << v.is_owned() << "</owned>";
o << "<owner_pid>" << v.get_owner_pid() << "</owner_pid>";
o << "<numa_node>" << v.get_numa_node() << "</numa_node>";
o << "<shmid>" << v.get_shmid() << "</shmid>";
o << "<shmkey>" << v.get_shmkey() << "</shmkey>";
o << "<address>" << reinterpret_cast<uintptr_t>(v.get_block()) << "</address>";
o << "</SharedMemory>";
return o;
}
} // namespace memory
} // namespace foedus
| 34.866412 | 120 | 0.673454 | sam1016yu |
b37c72cbae3ff5e65c7d2ebd2b7416791da0980a | 3,606 | cpp | C++ | test/src/gpu.cpp | BeatWolf/etl | 32e8153b38e0029176ca4fe2395b7fa6babe3189 | [
"MIT"
] | 1 | 2020-02-19T13:13:10.000Z | 2020-02-19T13:13:10.000Z | test/src/gpu.cpp | BeatWolf/etl | 32e8153b38e0029176ca4fe2395b7fa6babe3189 | [
"MIT"
] | null | null | null | test/src/gpu.cpp | BeatWolf/etl | 32e8153b38e0029176ca4fe2395b7fa6babe3189 | [
"MIT"
] | null | null | null | //=======================================================================
// Copyright (c) 2014-2018 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
/*!
* Suite of tests to make sure that CPU and GPU are correctly
* updated when operations are mixed.
*
* It is necessary to use large matrices in orders to ensure that
* GPU is used.
*/
#include "test.hpp"
#include "etl/stop.hpp"
#include "mmul_test.hpp"
#ifdef ETL_CUDA
#ifdef ETL_EGBLAS_MODE
TEMPLATE_TEST_CASE_2("gpu/status/0", "[gpu]", T, float, double) {
etl::fast_matrix<T, 75, 75> a;
etl::fast_matrix<T, 75, 75> b;
etl::fast_matrix<T, 75, 75> c;
a.ensure_gpu_up_to_date();
b.ensure_gpu_up_to_date();
c = -(a + b);
REQUIRE(c.is_gpu_up_to_date());
}
TEMPLATE_TEST_CASE_2("gpu/status/1", "[gpu]", T, float, double) {
etl::fast_matrix<T, 75, 75> a;
etl::fast_matrix<T, 75, 75> b;
etl::fast_matrix<T, 75, 75> c;
a.ensure_gpu_up_to_date();
b.ensure_gpu_up_to_date();
c = exp(a + b) >> log(a - b);
REQUIRE(c.is_gpu_up_to_date());
}
#endif
TEMPLATE_TEST_CASE_2("gpu/1", "[gpu]", T, float, double) {
etl::fast_matrix<T, 200, 200> a;
etl::fast_matrix<T, 200, 200> b;
a = 1;
b = 2;
etl::fast_matrix<T, 200, 200> c1;
etl::fast_matrix<T, 200, 200> c2;
c1 = a * b;
c2 = c1;
REQUIRE_EQUALS(c1(0, 0), 400);
REQUIRE_EQUALS(c1(0, 1), 400);
REQUIRE_EQUALS(c1(0, 2), 400);
REQUIRE_EQUALS(c1(1, 0), 400);
REQUIRE_EQUALS(c1(1, 1), 400);
REQUIRE_EQUALS(c1(1, 2), 400);
REQUIRE_EQUALS(c1(2, 0), 400);
REQUIRE_EQUALS(c1(2, 1), 400);
REQUIRE_EQUALS(c1(2, 2), 400);
REQUIRE_EQUALS(c2(0, 0), 400);
REQUIRE_EQUALS(c2(0, 1), 400);
REQUIRE_EQUALS(c2(0, 2), 400);
REQUIRE_EQUALS(c2(1, 0), 400);
REQUIRE_EQUALS(c2(1, 1), 400);
REQUIRE_EQUALS(c2(1, 2), 400);
REQUIRE_EQUALS(c2(2, 0), 400);
REQUIRE_EQUALS(c2(2, 1), 400);
REQUIRE_EQUALS(c2(2, 2), 400);
}
TEMPLATE_TEST_CASE_2("gpu/2", "[gpu]", T, float, double) {
etl::fast_matrix<T, 200, 200> a;
etl::fast_matrix<T, 200, 200> b;
a = 1;
b = 2;
etl::fast_matrix<T, 200, 200> c1;
etl::fast_matrix<T, 200, 200> c2;
c2 = 1;
c1 = a * b;
c2 += c1;
REQUIRE_EQUALS(c1(0, 0), 400);
REQUIRE_EQUALS(c1(0, 1), 400);
REQUIRE_EQUALS(c1(0, 2), 400);
REQUIRE_EQUALS(c1(1, 0), 400);
REQUIRE_EQUALS(c1(1, 1), 400);
REQUIRE_EQUALS(c1(1, 2), 400);
REQUIRE_EQUALS(c1(2, 0), 400);
REQUIRE_EQUALS(c1(2, 1), 400);
REQUIRE_EQUALS(c1(2, 2), 400);
REQUIRE_EQUALS(c2(0, 0), 401);
REQUIRE_EQUALS(c2(0, 1), 401);
REQUIRE_EQUALS(c2(0, 2), 401);
REQUIRE_EQUALS(c2(1, 0), 401);
REQUIRE_EQUALS(c2(1, 1), 401);
REQUIRE_EQUALS(c2(1, 2), 401);
REQUIRE_EQUALS(c2(2, 0), 401);
REQUIRE_EQUALS(c2(2, 1), 401);
REQUIRE_EQUALS(c2(2, 2), 401);
}
TEMPLATE_TEST_CASE_2("gpu/3", "[gpu]", T, float, double) {
etl::fast_matrix<T, 200, 200> a;
etl::fast_matrix<T, 200, 200> b;
a = 1;
b = 2;
etl::fast_matrix<T, 200, 200> c1;
c1 = a * b;
c1 *= 2.0;
REQUIRE_EQUALS(c1(0, 0), 800);
REQUIRE_EQUALS(c1(0, 1), 800);
REQUIRE_EQUALS(c1(0, 2), 800);
REQUIRE_EQUALS(c1(1, 0), 800);
REQUIRE_EQUALS(c1(1, 1), 800);
REQUIRE_EQUALS(c1(1, 2), 800);
REQUIRE_EQUALS(c1(2, 0), 800);
REQUIRE_EQUALS(c1(2, 1), 800);
REQUIRE_EQUALS(c1(2, 2), 800);
}
#endif
| 24.530612 | 73 | 0.574321 | BeatWolf |
b37d2c02d5c873483dba449319dee844fcc4e7aa | 13,774 | cpp | C++ | src/ops/cdl/CDLOpCPU.cpp | omi-lab/lib_opencolorio | a2457657353b5081ca24b5b9b11dd708451c05ba | [
"BSD-3-Clause"
] | null | null | null | src/ops/cdl/CDLOpCPU.cpp | omi-lab/lib_opencolorio | a2457657353b5081ca24b5b9b11dd708451c05ba | [
"BSD-3-Clause"
] | null | null | null | src/ops/cdl/CDLOpCPU.cpp | omi-lab/lib_opencolorio | a2457657353b5081ca24b5b9b11dd708451c05ba | [
"BSD-3-Clause"
] | 1 | 2022-01-27T17:21:42.000Z | 2022-01-27T17:21:42.000Z | // SPDX-License-Identifier: BSD-3-Clause
// Copyright Contributors to the OpenColorIO Project.
#include <algorithm>
#include <cmath>
#include <string.h>
#include <OpenColorIO/OpenColorIO.h>
#include "BitDepthUtils.h"
#include "CDLOpCPU.h"
#include "SSE.h"
namespace OCIO_NAMESPACE
{
const float RcpMinValue = 1e-2f;
inline float Reciprocal(float x)
{
return 1.0f / std::max(x, RcpMinValue);
}
RenderParams::RenderParams()
{
setSlope (1.0f, 1.0f, 1.0f);
setOffset(0.0f, 0.0f, 0.0f);
setPower (1.0f, 1.0f, 1.0f);
setSaturation(1.0f);
}
void RenderParams::setSlope(float r, float g, float b)
{
m_slope[0] = r;
m_slope[1] = g;
m_slope[2] = b;
m_slope[3] = 1.f;
}
void RenderParams::setOffset(float r, float g, float b)
{
m_offset[0] = r;
m_offset[1] = g;
m_offset[2] = b;
m_offset[3] = 0.f;
}
void RenderParams::setPower(float r, float g, float b)
{
m_power[0] = r;
m_power[1] = g;
m_power[2] = b;
m_power[3] = 1.f;
}
void RenderParams::setSaturation(float sat)
{
m_saturation = sat;
}
void RenderParams::update(ConstCDLOpDataRcPtr & cdl)
{
double slope[3], offset[3], power[3];
cdl->getSlopeParams().getRGB(slope);
cdl->getOffsetParams().getRGB(offset);
cdl->getPowerParams().getRGB(power);
const float saturation = float(cdl->getSaturation());
const CDLOpData::Style style = cdl->getStyle();
m_isReverse = (style == CDLOpData::CDL_V1_2_REV) || (style == CDLOpData::CDL_NO_CLAMP_REV);
m_isNoClamp = (style == CDLOpData::CDL_NO_CLAMP_FWD) || (style == CDLOpData::CDL_NO_CLAMP_REV);
if (isReverse())
{
// Reverse render parameters
setSlope(Reciprocal(float(slope[0])),
Reciprocal(float(slope[1])),
Reciprocal(float(slope[2])));
setOffset(float(-offset[0]), float(-offset[1]), float(-offset[2]));
setPower(Reciprocal(float(power[0])),
Reciprocal(float(power[1])),
Reciprocal(float(power[2])));
setSaturation(Reciprocal(saturation));
}
else
{
// Forward render parameters
setSlope(float(slope[0]), float(slope[1]), float(slope[2]));
setOffset(float(offset[0]), float(offset[1]), float(offset[2]));
setPower(float(power[0]), float(power[1]), float(power[2]));
setSaturation(saturation);
}
}
#ifdef USE_SSE
static const __m128 LumaWeights = _mm_setr_ps(0.2126f, 0.7152f, 0.0722f, 0.0);
// Load a given pixel from the pixel list into a SSE register
inline __m128 LoadPixel(const float * rgbaBuffer, float & inAlpha)
{
inAlpha = rgbaBuffer[3];
return _mm_loadu_ps(rgbaBuffer);
}
// Store the pixel's values into a given pixel list's position
inline void StorePixel(float * rgbaBuffer, const __m128 pix, const float outAlpha)
{
_mm_storeu_ps(rgbaBuffer, pix);
rgbaBuffer[3] = outAlpha;
}
// Conditionally clamp the pixel's values to the range [0, 1]
// When the template argument is true, the clamp mode is used,
// and the values in pix are clamped to the range [0,1]. When
// the argument is false, nothing is done.
template<bool>
inline void ApplyClamp(__m128& pix)
{
pix = _mm_min_ps(_mm_max_ps(pix, EZERO), EONE);
}
template<>
inline void ApplyClamp<false>(__m128&)
{
}
// Apply the power component to the the pixel's values.
// When the template argument is true, the values in pix
// are clamped to the range [0,1] and the power operation is
// applied. When the argument is false, the values in pix are
// not clamped before the power operation is applied. When the
// base is negative in this mode, pixel values are just passed
// through.
template<bool CLAMP>
inline void ApplyPower(__m128& pix, const __m128& power)
{
ApplyClamp<CLAMP>(pix);
pix = ssePower(pix, power);
}
template<>
inline void ApplyPower<false>(__m128& pix, const __m128& power)
{
__m128 negMask = _mm_cmplt_ps(pix, EZERO);
__m128 pixPower = ssePower(pix, power);
pix = sseSelect(negMask, pix, pixPower);
}
// Apply the saturation component to the the pixel's values
inline void ApplySaturation(__m128& pix, const __m128 saturation)
{
// Compute luma: dot product of pixel values and the luma weights
__m128 luma = _mm_mul_ps(pix, LumaWeights);
// luma = [ x+y , y+x , z+w , w+z ]
luma = _mm_add_ps(luma, _mm_shuffle_ps(luma, luma, _MM_SHUFFLE(2,3,0,1)));
// luma = [ x+y+z+w , y+x+w+z , z+w+x+y , w+z+y+x ]
luma = _mm_add_ps(luma, _mm_shuffle_ps(luma, luma, _MM_SHUFFLE(1,0,3,2)));
// Apply saturation
pix = _mm_add_ps(luma, _mm_mul_ps(saturation, _mm_sub_ps(pix, luma)));
}
#endif // USE_SSE
inline void ApplyScale(float * pix, const float scale)
{
pix[0] = pix[0] * scale;
pix[1] = pix[1] * scale;
pix[2] = pix[2] * scale;
}
// Apply the slope component to the the pixel's values
inline void ApplySlope(float * pix, const float * slope)
{
pix[0] = pix[0] * slope[0];
pix[1] = pix[1] * slope[1];
pix[2] = pix[2] * slope[2];
}
// Apply the offset component to the the pixel's values
inline void ApplyOffset(float * pix, const float * offset)
{
pix[0] = pix[0] + offset[0];
pix[1] = pix[1] + offset[1];
pix[2] = pix[2] + offset[2];
}
// Apply the saturation component to the the pixel's values
inline void ApplySaturation(float * pix, const float saturation)
{
const float srcpix[3] = { pix[0], pix[1], pix[2] };
static const float LumaWeights[3] = { 0.2126f, 0.7152f, 0.0722f };
// Compute luma: dot product of pixel values and the luma weights
ApplySlope(pix, LumaWeights);
// luma = x+y+z+w
const float luma = pix[0] + pix[1] + pix[2];
// Apply saturation
pix[0] = luma + saturation * (srcpix[0] - luma);
pix[1] = luma + saturation * (srcpix[1] - luma);
pix[2] = luma + saturation * (srcpix[2] - luma);
}
// Conditionally clamp the pixel's values to the range [0, 1]
// When the template argument is true, the clamp mode is used,
// and the values in pix are clamped to the range [0,1]. When
// the argument is false, nothing is done.
template<bool>
inline void ApplyClamp(float * pix)
{
// NaNs become 0.
pix[0] = Clamp(pix[0], 0.f, 1.f);
pix[1] = Clamp(pix[1], 0.f, 1.f);
pix[2] = Clamp(pix[2], 0.f, 1.f);
}
template<>
inline void ApplyClamp<false>(float *)
{
}
// Apply the power component to the the pixel's values.
// When the template argument is true, the values in pix
// are clamped to the range [0,1] and the power operation is
// applied. When the argument is false, the values in pix are
// not clamped before the power operation is applied. When the
// base is negative in this mode, pixel values are just passed
// through.
template<bool>
inline void ApplyPower(float * pix, const float * power)
{
ApplyClamp<true>(pix);
pix[0] = powf(pix[0], power[0]);
pix[1] = powf(pix[1], power[1]);
pix[2] = powf(pix[2], power[2]);
}
template<>
inline void ApplyPower<false>(float * pix, const float * power)
{
// Note: Set NaNs to 0 to match the SSE path.
pix[0] = IsNan(pix[0]) ? 0.0f : (pix[0]<0.f ? pix[0] : powf(pix[0], power[0]));
pix[1] = IsNan(pix[1]) ? 0.0f : (pix[1]<0.f ? pix[1] : powf(pix[1], power[1]));
pix[2] = IsNan(pix[2]) ? 0.0f : (pix[2]<0.f ? pix[2] : powf(pix[2], power[2]));
}
class CDLOpCPU;
typedef OCIO_SHARED_PTR<CDLOpCPU> CDLOpCPURcPtr;
// Base class for the CDL operation renderers
class CDLOpCPU : public OpCPU
{
public:
CDLOpCPU() = delete;
CDLOpCPU(ConstCDLOpDataRcPtr & cdl);
protected:
RenderParams m_renderParams;
};
template<bool CLAMP>
class CDLRendererFwd : public CDLOpCPU
{
public:
CDLRendererFwd(ConstCDLOpDataRcPtr & cdl)
: CDLOpCPU(cdl)
{
}
virtual void apply(const void * inImg, void * outImg, long numPixels) const;
};
#ifdef USE_SSE
template<bool CLAMP>
class CDLRendererFwdSSE : public CDLRendererFwd<CLAMP>
{
public:
CDLRendererFwdSSE(ConstCDLOpDataRcPtr & cdl)
: CDLRendererFwd<CLAMP>(cdl)
{
}
virtual void apply(const void * inImg, void * outImg, long numPixels) const;
};
#endif
template<bool CLAMP>
class CDLRendererRev : public CDLOpCPU
{
public:
CDLRendererRev(ConstCDLOpDataRcPtr & cdl)
: CDLOpCPU(cdl)
{
}
virtual void apply(const void * inImg, void * outImg, long numPixels) const;
};
#ifdef USE_SSE
template<bool CLAMP>
class CDLRendererRevSSE : public CDLRendererRev<CLAMP>
{
public:
CDLRendererRevSSE(ConstCDLOpDataRcPtr & cdl)
: CDLRendererRev<CLAMP>(cdl)
{
}
virtual void apply(const void * inImg, void * outImg, long numPixels) const;
};
#endif
CDLOpCPU::CDLOpCPU(ConstCDLOpDataRcPtr & cdl)
: OpCPU()
{
m_renderParams.update(cdl);
}
#ifdef USE_SSE
void LoadRenderParams(const RenderParams & renderParams,
__m128 & slope,
__m128 & offset,
__m128 & power,
__m128 & saturation)
{
slope = _mm_loadu_ps(renderParams.getSlope());
offset = _mm_loadu_ps(renderParams.getOffset());
power = _mm_loadu_ps(renderParams.getPower());
saturation = _mm_set1_ps(renderParams.getSaturation());
}
#endif
#ifdef USE_SSE
template<bool CLAMP>
void CDLRendererFwdSSE<CLAMP>::apply(const void * inImg, void * outImg, long numPixels) const
{
__m128 slope, offset, power, saturation, pix;
LoadRenderParams(this->m_renderParams, slope, offset, power, saturation);
float inAlpha;
const float * in = (const float *)inImg;
float * out = (float *)outImg;
for(long idx=0; idx<numPixels; ++idx)
{
pix = LoadPixel(in, inAlpha);
pix = _mm_mul_ps(pix, slope);
pix = _mm_add_ps(pix, offset);
ApplyPower<CLAMP>(pix, power);
ApplySaturation(pix, saturation);
ApplyClamp<CLAMP>(pix);
StorePixel(out, pix, inAlpha);
in += 4;
out += 4;
}
}
#endif
template<bool CLAMP>
void CDLRendererFwd<CLAMP>::apply(const void * inImg, void * outImg, long numPixels) const
{
const float * in = static_cast<const float *>(inImg);
float * out = static_cast<float *>(outImg);
const float * slope = m_renderParams.getSlope();
float inSlope[3] = {slope[0], slope[1], slope[2]};
for (long idx = 0; idx<numPixels; ++idx)
{
const float inAlpha = in[3];
// NB: 'in' and 'out' could be pointers to the same memory buffer.
memcpy(out, in, 4 * sizeof(float));
ApplySlope(out, inSlope);
ApplyOffset(out, m_renderParams.getOffset());
ApplyPower<CLAMP>(out, m_renderParams.getPower());
ApplySaturation(out, m_renderParams.getSaturation());
ApplyClamp<CLAMP>(out);
out[3] = inAlpha;
in += 4;
out += 4;
}
}
#ifdef USE_SSE
template<bool CLAMP>
void CDLRendererRevSSE<CLAMP>::apply(const void * inImg, void * outImg, long numPixels) const
{
__m128 slopeRev, offsetRev, powerRev, saturationRev, pix;
LoadRenderParams(this->m_renderParams, slopeRev, offsetRev, powerRev, saturationRev);
float inAlpha = 1.0f;
const float * in = (const float *)inImg;
float * out = (float *)outImg;
for(long idx=0; idx<numPixels; ++idx)
{
pix = LoadPixel(in, inAlpha);
ApplyClamp<CLAMP>(pix);
ApplySaturation(pix, saturationRev);
ApplyPower<CLAMP>(pix, powerRev);
pix = _mm_add_ps(pix, offsetRev);
pix = _mm_mul_ps(pix, slopeRev);
ApplyClamp<CLAMP>(pix);
StorePixel(out, pix, inAlpha);
in += 4;
out += 4;
}
}
#endif
template<bool CLAMP>
void CDLRendererRev<CLAMP>::apply(const void * inImg, void * outImg, long numPixels) const
{
const float * in = static_cast<const float *>(inImg);
float * out = static_cast<float *>(outImg);
for (long idx = 0; idx<numPixels; ++idx)
{
const float inAlpha = in[3];
// NB: 'in' and 'out' could be pointers to the same memory buffer.
memcpy(out, in, 4 * sizeof(float));
ApplyClamp<CLAMP>(out);
ApplySaturation(out, m_renderParams.getSaturation());
ApplyPower<CLAMP>(out, m_renderParams.getPower());
ApplyOffset(out, m_renderParams.getOffset());
ApplySlope(out, m_renderParams.getSlope());
ApplyClamp<CLAMP>(out);
out[3] = inAlpha;
in += 4;
out += 4;
}
}
// Note that if power is 1, the optimizer is able to convert the CDL op into a pair of matrices and
// clamp (when needed). So by default, the following will only get called when power is not 1.
ConstOpCPURcPtr GetCDLCPURenderer(ConstCDLOpDataRcPtr & cdl, bool fastPower)
{
#ifndef USE_SSE
std::ignore = fastPower;
#endif
switch(cdl->getStyle())
{
case CDLOpData::CDL_V1_2_FWD:
#ifdef USE_SSE
if (fastPower) return std::make_shared<CDLRendererFwdSSE<true>>(cdl);
else
#endif
return std::make_shared<CDLRendererFwd<true>>(cdl);
case CDLOpData::CDL_NO_CLAMP_FWD:
#ifdef USE_SSE
if (fastPower) return std::make_shared<CDLRendererFwdSSE<false>>(cdl);
else
#endif
return std::make_shared<CDLRendererFwd<false>>(cdl);
case CDLOpData::CDL_V1_2_REV:
#ifdef USE_SSE
if (fastPower) return std::make_shared<CDLRendererRevSSE<true>>(cdl);
else
#endif
return std::make_shared<CDLRendererRev<true>>(cdl);
case CDLOpData::CDL_NO_CLAMP_REV:
#ifdef USE_SSE
if (fastPower) return std::make_shared<CDLRendererRevSSE<false>>(cdl);
else
#endif
return std::make_shared<CDLRendererRev<false>>(cdl);
}
throw Exception("Unknown CDL style");
return ConstOpCPURcPtr();
}
} // namespace OCIO_NAMESPACE
| 26.95499 | 99 | 0.644112 | omi-lab |
b37f0a67ab52fe8338755ea118678316d8f9b45d | 3,336 | hpp | C++ | templates/BalancedBinarySearchTree.SizeBalancedTree.hpp | BoleynSu/CP-CompetitiveProgramming | cc256bf402360fe0f689fdcdc4e898473a9594dd | [
"MIT"
] | 6 | 2019-03-23T21:06:25.000Z | 2021-06-27T05:22:41.000Z | templates/BalancedBinarySearchTree.SizeBalancedTree.hpp | BoleynSu/CP-CompetitiveProgramming | cc256bf402360fe0f689fdcdc4e898473a9594dd | [
"MIT"
] | 1 | 2020-10-11T08:14:00.000Z | 2020-10-11T08:14:00.000Z | templates/BalancedBinarySearchTree.SizeBalancedTree.hpp | BoleynSu/CP-CompetitiveProgramming | cc256bf402360fe0f689fdcdc4e898473a9594dd | [
"MIT"
] | 3 | 2019-03-23T21:06:31.000Z | 2021-10-24T01:44:01.000Z | /*
* Package: StandardCodeLibrary.BalancedBinarySearchTree.SizeBalancedTree
* Usage:
* MAXNODE:SizeBalancedTree最多有多少个节点,null会占用一个节点
* */
#include <Core>
namespace StandardCodeLibrary
{
namespace BinarySearchTree
{
namespace SizeBalancedTree
{
typedef int type;
const int MAXNODE=1;
typedef struct struct_node* node;
struct struct_node{type k;int s;node c[2];}pool[MAXNODE];
node top,null;
struct Initializer{Initializer(){top=pool,null=top++,null->s=0,null->c[0]=null->c[1]=null;}}initializer;
node make(const type& k)
{
rtn top->k=k,top->s=1,top->c[0]=top->c[1]=null,top++;
}
void rotate(node& x,bool d)
{
node y=x->c[!d];
x->c[!d]=y->c[d],y->c[d]=x;
y->s=x->s,x->s=x->c[0]->s+x->c[1]->s+1;
x=y;
}
void maintain(node& x,bool d)
{
if (x->c[d]->c[d]->s>x->c[!d]->s) rotate(x,!d);
else if (x->c[d]->c[!d]->s>x->c[!d]->s) rotate(x->c[d],d),rotate(x,!d);
else rtn;
rep(d,2) maintain(x->c[d],d);
rep(d,2) maintain(x,d);
}
//须确保树上没有和k相同的元素
void insert(node& x,const type& k)
{
if (x==null) x=make(k);
else
{
bool d=x->k<k;
x->s++,insert(x->c[d],k),maintain(x,d);
}
}
//须确保删除的元素k一定在树上
type erase(node& x,const type& k)
{
bool d=x->k<k;
x->s--;
if (k==x->k||x->c[d]==null)
{
type y=x->k;
if (x->c[0]==null||x->c[1]==null) x=x->c[x->c[0]==null];
else x->k=erase(x->c[0],k);
rtn y;
}
else rtn erase(x->c[d],k);
}
int size(node x)
{
rtn x->s;
}
//找不到返回null
node find(node x,const type& k)
{
whl(x!=null&&x->k!=k) x=x->c[x->k<k];
rtn x;
}
//返回第一个不小于k的元素的排名 排名从0开始
int order_of_key(node x,const type& k)
{
int y=0;
whl(x!=null)
{
bool d=x->k<k;
if (d) y+=x->c[0]->s+1;
x=x->c[d];
}
rtn y;
}
//返回排名为s的元素 排名从0开始 如果s超出范围 返回null
node find_by_order(node x,int s)
{
whl(x!=null&&x->c[0]->s!=s)
{
bool d=x->c[0]->s<s;
if (d) s-=x->c[0]->s+1;
x=x->c[d];
}
rtn x;
}
node min(node x)
{
whl(x->c[0]!=null) x=x->c[0];
rtn x;
}
node max(node x)
{
whl(x->c[1]!=null) x=x->c[1];
rtn x;
}
//返回第一个小于k的元素 如果没有比k小的元素则返回null
node pred(node x,const type& k)
{
if (x==null) rtn null;
else if (x->k==k) rtn max(x->c[0]);
else if (x->k<k)
{
node y=pred(x->c[1],k);
if (y==null) rtn x;
else rtn y;
}
else rtn pred(x->c[0],k);
}
//返回第一个大于k的元素 如果没有比k大的元素则返回null
node succ(node x,const type& k)
{
if (x==null) rtn null;
else if (x->k==k) rtn min(x->c[1]);
else if (x->k<k) rtn succ(x->c[1],k);
else
{
node y=succ(x->c[0],k);
if (y==null) rtn x;
else rtn y;
}
}
struct tree
{
node rt;
tree():rt(SizeBalancedTree::null){}
void insert(const type& k){if (!count(k)) SizeBalancedTree::insert(rt,k);}
void erase(const type& k){if (count(k)) SizeBalancedTree::erase(rt,k);}
int size(){rtn SizeBalancedTree::size(rt);}
node find(const type& k){rtn SizeBalancedTree::find(rt,k);}
int count(const type& k){rtn SizeBalancedTree::find(rt,k)!=SizeBalancedTree::null;}
int order_of_key(const type& k){rtn SizeBalancedTree::order_of_key(rt,k);}
node find_by_order(int s){rtn SizeBalancedTree::find_by_order(rt,s);}
node min(){rtn SizeBalancedTree::min(rt);}
node max(){rtn SizeBalancedTree::max(rt);}
node pred(const type& k){rtn SizeBalancedTree::pred(rt,k);}
node succ(const type& k){rtn SizeBalancedTree::succ(rt,k);}
};
}
}
}
| 21.384615 | 105 | 0.588429 | BoleynSu |
b37f4194f86a4b5ae4b7849eef545edec2373158 | 1,057 | hpp | C++ | src/HF_state.hpp | simondlevy/HackflightCPP | 1f6fdd0c0ac2797d9663eb2b57410bb45c43c77e | [
"MIT"
] | null | null | null | src/HF_state.hpp | simondlevy/HackflightCPP | 1f6fdd0c0ac2797d9663eb2b57410bb45c43c77e | [
"MIT"
] | null | null | null | src/HF_state.hpp | simondlevy/HackflightCPP | 1f6fdd0c0ac2797d9663eb2b57410bb45c43c77e | [
"MIT"
] | 1 | 2021-12-27T23:07:06.000Z | 2021-12-27T23:07:06.000Z | /*
Datatype declarations for vehicle state
Copyright (c) 2018 Simon D. Levy
MIT License
*/
#pragma once
#include "HF_filters.hpp"
namespace hf {
class State {
friend class HackflightPure;
friend class HackflightFull;
private:
static constexpr float MAX_ARMING_ANGLE_DEGREES = 25;
bool safeAngle(uint8_t axis)
{
return fabs(x[axis]) < Filter::deg2rad(MAX_ARMING_ANGLE_DEGREES);
}
public:
bool armed = false;
bool failsafe = false;
// See Bouabdallah et al. (2004)
enum {X, DX, Y, DY, Z, DZ, PHI, DPHI, THETA, DTHETA, PSI, DPSI, SIZE};
float x[SIZE];
State(bool start_armed=false)
{
armed = start_armed;
}
bool safeToArm(void)
{
return safeAngle(PHI) && safeAngle(THETA);
}
}; // class State
} // namespace hf
| 20.326923 | 83 | 0.492904 | simondlevy |