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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c5a77dc47bfd97026329f9e1dd8da605ddf730bf | 3,136 | cpp | C++ | code archive/TIOJ/1739.cpp | brianbbsu/program | c4505f2b8c0b91010e157db914a63c49638516bc | [
"MIT"
] | 4 | 2018-04-08T08:07:58.000Z | 2021-06-07T14:55:24.000Z | code archive/TIOJ/1739.cpp | brianbbsu/program | c4505f2b8c0b91010e157db914a63c49638516bc | [
"MIT"
] | null | null | null | code archive/TIOJ/1739.cpp | brianbbsu/program | c4505f2b8c0b91010e157db914a63c49638516bc | [
"MIT"
] | 1 | 2018-10-29T12:37:25.000Z | 2018-10-29T12:37:25.000Z | //{
#include<bits/stdc++.h>
using namespace std;
typedef int ll;
typedef double lf;
typedef pair<ll,ll> ii;
#define REP(i,n) for(ll i=0;i<n;i++)
#define REP1(i,n) for(ll i=1;i<=n;i++)
#define FILL(i,n) memset(i,n,sizeof i)
#define X first
#define Y second
#define SZ(_a) (int)_a.size()
#define ALL(_a) _a.begin(),_a.end()
#define pb push_back
#ifdef brian
#define debug(...) do{\
fprintf(stderr,"%s - %d (%s) = ",__PRETTY_FUNCTION__,__LINE__,#__VA_ARGS__);\
_do(__VA_ARGS__);\
}while(0)
template<typename T>void _do(T &&_x){cerr<<_x<<endl;}
template<typename T,typename ...S> void _do(T &&_x,S &&..._t){cerr<<_x<<" ,";_do(_t...);}
template<typename _a,typename _b> ostream& operator << (ostream &_s,const pair<_a,_b> &_p){return _s<<"("<<_p.X<<","<<_p.Y<<")";}
template<typename It> ostream& _OUTC(ostream &_s,It _ita,It _itb)
{
_s<<"{";
for(It _it=_ita;_it!=_itb;_it++)
{
_s<<(_it==_ita?"":",")<<*_it;
}
_s<<"}";
return _s;
}
template<typename _a> ostream &operator << (ostream &_s,vector<_a> &_c){return _OUTC(_s,ALL(_c));}
template<typename _a> ostream &operator << (ostream &_s,set<_a> &_c){return _OUTC(_s,ALL(_c));}
template<typename _a,typename _b> ostream &operator << (ostream &_s,map<_a,_b> &_c){return _OUTC(_s,ALL(_c));}
template<typename _t> void pary(_t _a,_t _b){_OUTC(cerr,_a,_b);cerr<<endl;}
#define IOS()
#else
#define debug(...)
#define pary(...)
#define endl '\n'
#define IOS() ios_base::sync_with_stdio(0);cin.tie(0);
#endif // brian
//}
#ifdef brian
int getNumQuestions(){
ll q;
cin>>q;
return q;
}
void getQuestion(int &A, int &B)
{
cin>>A>>B;
}
void answer(int ans)
{
printf("Answer: %d\n", ans);
}
#else
#include "lib1739.h"
#endif
const ll MAXn=3e5+5,MAXlg=__lg(MAXn)+2;
const ll MOD=1000000007;
const ll INF=ll(1e15);
vector<ii> _v[2 * MAXn];
int vid[MAXn][MAXlg], vit = 0;
inline vector<ii> &v(int i,int j)
{
if(vid[i][j] == 0)return _v[vid[i][j] = ++vit];
else return _v[vid[i][j]];
}
ll mp(int i, int j, int x)
{
ll t = lower_bound(ALL(v(i,j)), ii(x, -1)) - v(i,j).begin();
if(t == SZ(v(i,j)) || v(i,j)[t].X != x)return x;
else return v(i,j)[t].Y;
}
int d[MAXn], u[MAXn];
int main()
{
debug(MAXn * MAXlg);
int n, m;
scanf("%d%d", &n, &m);
REP1(i, m)scanf("%d", d + i);
REP(i, m)
{
v(i, 0).pb(ii(d[i+1], d[i+1] + 1));
v(i, 0).pb(ii(d[i+1] + 1, d[i+1]));
}
for(int j = 1;(1<<j) <= m;j++)
{
for(int i = 0;i + (1<<j) <= m;i += (1<<j))
{
ll t = i + (1<<(j-1));
for(auto &p:v(i, j-1))
{
v(i,j).pb(ii(p.X, mp(t, j-1, p.Y)));
u[p.X] = 1;
}
for(auto &p:v(t, j-1))if(!u[p.X])v(i,j).pb(p);
for(auto &p:v(i,j))u[p.X] = 0;
sort(ALL(v(i,j)));
}
}
/*ll q = getNumQuestions();
while(q--)
{
int a, b;
getQuestion(a, b);
int now = 0;
for(int j = MAXlg - 1;j >= 0;j --)if(b&(1<<j))
{
a = mp(now, j, a);
now += (1<<j);
}
answer(a);
}*/
} | 23.938931 | 129 | 0.520408 | brianbbsu |
c5ababaec40d08b3250baf901c5c3f8cbedb618d | 3,297 | hpp | C++ | Dialogs/MoveBaseDialog.hpp | joseffallman/Intrusion | a3937bcbfaaab7da0321dce3ab7d9a5fe1b350ff | [
"MIT"
] | null | null | null | Dialogs/MoveBaseDialog.hpp | joseffallman/Intrusion | a3937bcbfaaab7da0321dce3ab7d9a5fe1b350ff | [
"MIT"
] | 4 | 2019-04-21T23:30:19.000Z | 2019-05-08T21:03:25.000Z | Dialogs/MoveBaseDialog.hpp | joseffallman/Intrusion | a3937bcbfaaab7da0321dce3ab7d9a5fe1b350ff | [
"MIT"
] | 1 | 2019-03-22T08:28:07.000Z | 2019-03-22T08:28:07.000Z | /*
* Name: IntMoveBaseDialog
* Date: 2020-03-29
* Version: 1.0
* Author: Josef
*
* Description:
* The Move base dialog.
*/
class IntMoveBaseDialog : IntBaseDialog
{
onUnload = "call Intrusion_Client_MoveBaseDialog_onUnload;";
class Controls : Controls
{
class _CT_CONTROLS_GROUP
{
type = 15;
idc = -1;
style = 16;
//x = 0.5 * GUI_GRID_W + GUI_GRID_X;
//y = 2.5 * GUI_GRID_H + GUI_GRID_Y;
//w = 39.5 * GUI_GRID_W;
//h = 17.5 * GUI_GRID_H;
x = 0.5 * GUI_GRID_W + GUI_GRID_X;
y = 2.5 * GUI_GRID_H + GUI_GRID_Y;
w = 39 * GUI_GRID_W;
h = 17 * GUI_GRID_H;
shadow = 0;
onLBDrop = "call Intrusion_Client_MoveBaseDialog_OnMapDrop;";
class ScrollBar
{
color[] = {1,1,1,0.6};
colorActive[] = {1,1,1,1};
colorDisabled[] = {1,1,1,0.3};
thumb = "\A3\ui_f\data\gui\cfg\scrollbar\thumb_ca.paa";
arrowEmpty = "\A3\ui_f\data\gui\cfg\scrollbar\arrowEmpty_ca.paa";
arrowFull = "\A3\ui_f\data\gui\cfg\scrollbar\arrowFull_ca.paa";
border = "\A3\ui_f\data\gui\cfg\scrollbar\border_ca.paa";
};
class VScrollbar: ScrollBar
{
width = 0.021;
autoScrollSpeed = -1;
autoScrollDelay = 5;
autoScrollRewind = 0;
shadow = 0;
};
class HScrollbar: ScrollBar
{
height = 0.028;
shadow = 0;
};
class Controls
{
class Map : RscMapControl
{
idc = 2550;
x = 0.5 * GUI_GRID_W;
y = 2.5 * GUI_GRID_H + GUI_GRID_Y;
w = 26.5 * GUI_GRID_W;
h = 16.5 * GUI_GRID_H;
//scaleMin = 0.02;
//scaleMax = 0.02;
scaleDefault = 1; //0.02;
onMouseButtonClick = "call Intrusion_Client_MoveBaseDialog_onMapClick;";
};
class ListBox : RscListBox
{
idc = 2552;
x = 27.5 * GUI_GRID_W + GUI_GRID_X;
y = 0;
w = 11.5 * GUI_GRID_W;
h = 16 * GUI_GRID_H;
canDrag = 1;
onLBSelChanged = "call Intrusion_Client_MoveBaseDialog_OnListBoxSelectChanged;";
onLBDrag = "call Intrusion_Client_MoveBaseDialog_OnListBoxDrag;";
};
};
};
class CancelButton : Base_CancelButton
{
action = "call Intrusion_Client_MoveBaseDialog_OnCancelButtonPressed;";
};
class OKButton : Base_OkButton
{
text = "Move Base";
action = "call Intrusion_Client_MoveBaseDialog_OnOkButtonPressed;";
};
class Header : Base_Header
{
text = "Move base dialog.";
};
class Description : Base_Description
{
idc = 2553;
x = 0.5 * GUI_GRID_W + GUI_GRID_X;
y = 19.5 * GUI_GRID_H + GUI_GRID_Y;
w = 27.5 * GUI_GRID_W;
h = 5 * GUI_GRID_H;
//colorBackground[] = {1,1,1,1};
};
};
};
class ContextMenu : RscListBox
{
idc = 2560;
type = CT_LISTBOX;
style = ST_LEFT;
x = 0.5 * GUI_GRID_W;
y = 2.5 * GUI_GRID_H + GUI_GRID_Y;
w = 5 * GUI_GRID_W;
h = 5 * GUI_GRID_H;
colorSelectBackground[] = {0.6,0.6,0.6,1};
colorSelectBackground2[] = {0.2,0.2,0.2,1};
onLBSelChanged = "call Intrusion_Client_MoveBaseContextMenu_OnListBoxSelectChanged;";
};
| 24.604478 | 88 | 0.561116 | joseffallman |
c5adf2a31d53d674fd8368a9126bbc7a6b1e6df0 | 219 | cpp | C++ | test/global-ctor.cpp | russellw/olivine | df147a65ea197191caf43e452e24e51003df13b4 | [
"MIT"
] | 1 | 2022-03-18T02:41:34.000Z | 2022-03-18T02:41:34.000Z | test/global-ctor.cpp | russellw/olivine | df147a65ea197191caf43e452e24e51003df13b4 | [
"MIT"
] | null | null | null | test/global-ctor.cpp | russellw/olivine | df147a65ea197191caf43e452e24e51003df13b4 | [
"MIT"
] | null | null | null | struct Marble {
double r;
Marble(double r): r(r) {
}
double volume() {
return 4.0 / 3.0 * 3.14159265359 * r * r * r;
}
};
Marble m(10.0);
int main() {
return !(4188.0 < m.volume() && m.volume() < 4189.0);
}
| 12.882353 | 54 | 0.538813 | russellw |
c5af4925158a050a299d3431b0624c5477aec1d8 | 7,040 | cpp | C++ | NotThatGameEngine/NotThatGameEngine/GameObject.cpp | HoduRe/NotThatGameEngine | e1a6bd073fbd34f3598b2c03f8d0d82cd8540ccc | [
"MIT"
] | 1 | 2021-01-07T13:36:34.000Z | 2021-01-07T13:36:34.000Z | NotThatGameEngine/NotThatGameEngine/GameObject.cpp | HoduRe/NotThatGameEngine | e1a6bd073fbd34f3598b2c03f8d0d82cd8540ccc | [
"MIT"
] | null | null | null | NotThatGameEngine/NotThatGameEngine/GameObject.cpp | HoduRe/NotThatGameEngine | e1a6bd073fbd34f3598b2c03f8d0d82cd8540ccc | [
"MIT"
] | 1 | 2021-01-06T11:10:33.000Z | 2021-01-06T11:10:33.000Z | #include "GameObject.h"
#include "OpenGLFuncionality.h"
#include "Component.h"
#include "Transform.h"
#include "Mesh.h"
#include "Material.h"
#include "Camera.h"
#include "Animation.h"
#include "Application.h"
#include "Textures.h"
GameObject::GameObject(Application* _App, long long int _id, std::string _name, GameObject* _parent, bool _enabled, std::vector<GameObject*> children) :
name(_name), id(_id), worldTransform(), parent(_parent), childs(children), enabled(_enabled), deleteGameObject(false), idGenerator(),
mesh(nullptr), material(nullptr), transform(nullptr), camera(nullptr), App(_App) {
AddComponent(COMPONENT_TYPE::TRANSFORM, idGenerator.Int());
}
GameObject::~GameObject() {
delete mesh;
delete material;
delete transform;
delete camera;
mesh = nullptr;
material = nullptr;
transform = nullptr;
camera = nullptr;
parent = nullptr;
}
void GameObject::Update() {
if (mesh != nullptr) { mesh->SetIsAnimation(false); }
int size = childs.size();
for (int i = 0; i < size; i++) { if (childs[i]->enabled) { childs[i]->Update(); } }
}
void GameObject::PostUpdate(int focusId) {
// TODO: try implementing dirty flag ;)
if (enabled) {
transform->RecalculateTransformFromParent();
if (camera != nullptr) { camera->UpdateTransform(); }
if (animation != nullptr) { animation->PlayAnimation(); }
for (int i = childs.size() - 1; i > -1; i--) { childs[i]->PostUpdate(focusId); }
if (mesh != nullptr) {
if (material != nullptr) { OpenGLFunctionality::DrawMeshes(*mesh, worldTransform, App->texture->IsTextureRepeated(material->GetTextureName())); }
else { OpenGLFunctionality::DrawMeshes(*mesh, worldTransform, 0); }
DebugBones();
if (id == focusId) { ManageAABB(mesh->boundingBox, true); }
else { ManageAABB(mesh->boundingBox); }
if (mesh->paintNormals) { OpenGLFunctionality::DrawLines(worldTransform, mesh->DebugNormals(), mesh->debugNormals); }
}
}
CheckComponentDeletion();
}
Component* GameObject::AddComponent(COMPONENT_TYPE _type, long long int id) {
if (id == -1) { id = idGenerator.Int(); }
switch (_type) {
case COMPONENT_TYPE::TRANSFORM: if (transform == nullptr) { return transform = new Transform(id, this); } break;
case COMPONENT_TYPE::MESH: if (mesh == nullptr) { return mesh = new Mesh(id, this); } break;
case COMPONENT_TYPE::MATERIAL: if (material == nullptr) { return material = new Material(id, this); } break;
case COMPONENT_TYPE::CAMERA: if (camera == nullptr) { return camera = new Camera(id, this); } break;
case COMPONENT_TYPE::ANIMATION: if (animation == nullptr) { return animation = new Animation(id, this); } break;
default:
assert(true == false);
break;
}
return nullptr;
}
bool GameObject::AddGameObjectByParent(GameObject* newObject) {
bool ret = false;
if (newObject->parent->id == this->id) {
childs.push_back(newObject);
return true;
}
else {
int size = childs.size();
for (int i = 0; i < size; i++) {
ret = childs[i]->AddGameObjectByParent(newObject);
if (ret) { return ret; }
}
}
return false;
}
bool GameObject::CheckChildDeletionById(long long int _id) {
bool ret = false;
if (id == _id) {
SetDeleteGameObject();
return true;
}
else {
int size = childs.size();
for (int i = 0; i < size; i++) {
ret = childs[i]->CheckChildDeletionById(_id);
if (ret) { return ret; }
}
}
return false;
}
void GameObject::SetDeleteGameObject(bool deleteBool) {
deleteGameObject = deleteBool;
int size = childs.size();
for (int i = 0; i < size; i++) { childs[i]->SetDeleteGameObject(deleteBool); }
}
void GameObject::SetDeleteComponent(COMPONENT_TYPE _type) {
Component* component = GetComponent(_type);
component->deleteComponent = true;
}
void GameObject::CheckComponentDeletion() {
if (mesh != nullptr) { if (mesh->deleteComponent) { delete mesh; } }
if (material != nullptr) { if (material->deleteComponent) { delete material; } }
if (camera != nullptr) { if (camera->deleteComponent) { delete camera; } }
}
Component* GameObject::GetComponent(COMPONENT_TYPE _type) {
switch (_type) {
case COMPONENT_TYPE::TRANSFORM: return transform;
case COMPONENT_TYPE::MESH: return mesh;
case COMPONENT_TYPE::MATERIAL: return material;
case COMPONENT_TYPE::CAMERA: return camera;
case COMPONENT_TYPE::ANIMATION: return animation;
default:
assert(true == false);
break;
}
return nullptr;
}
Component* GameObject::FindGameObjectChildByComponent(long long int componentId) {
Component* ret = nullptr;
if (transform != nullptr) { if (transform->id == componentId) { return transform; } }
if (mesh != nullptr) { if (mesh->id == componentId) { return mesh; } }
if (material != nullptr) { if (material->id == componentId) { return material; } }
if (camera != nullptr) { if (camera->id == componentId) { return camera; } }
for (int i = 0; i < childs.size(); i++) {
ret = childs[i]->FindGameObjectChildByComponent(componentId);
if (ret) { return ret; }
}
return ret;
}
GameObject* GameObject::FindGameObjectChild(long long int id) {
GameObject* ret = nullptr;
for (int i = 0; i < childs.size(); i++) {
if (childs[i]->id == id) { return childs[i]; }
else {
ret = childs[i]->FindGameObjectChild(id);
if (ret) { return ret; }
}
}
return ret;
}
void GameObject::ManageAABB(AABB aabb, bool focus, bool guaranteedShow) {
if (mesh != nullptr) {
bool show = guaranteedShow || focus ? true : mesh->showBoxes;
if (show) {
OBB obb = aabb;
obb.Transform(worldTransform);
AABB newBoundingBox;
newBoundingBox.SetNegativeInfinity();
newBoundingBox.Enclose(obb);
std::vector<float> cornerVec;
for (int i = 0; i < 8; i++) {
float3 corner = newBoundingBox.CornerPoint(i);
cornerVec.push_back(corner.x);
cornerVec.push_back(corner.y);
cornerVec.push_back(corner.z);
}
if (focus) { OpenGLFunctionality::DrawBox(cornerVec, 80.0f, 0.0f, 0.0f); }
else { OpenGLFunctionality::DrawBox(cornerVec); }
}
}
}
void GameObject::DebugBones() {
AABB boneAABB;
if (mesh->showAllBones) {
for (uint i = 0; i < mesh->boneDisplayVecSize; i++) {
boneAABB.SetNegativeInfinity();
int size = mesh->vertexSize / 3;
for (int it = 0; it < size; it++) {
for (int itAux = 0; itAux < 4; itAux++) {
if (mesh->boneIDs[(it * 4) + itAux] == (int)i) {
boneAABB.Enclose(vec(mesh->vertices[it * 3], mesh->vertices[(it * 3) + 1], mesh->vertices[(it * 3) + 2]));
}
}
}
ManageAABB(boneAABB, false, true);
}
}
else {
for (uint i = 0; i < mesh->boneDisplayVecSize; i++) {
if (mesh->boneDisplayVec[i]) {
boneAABB.SetNegativeInfinity();
int size = mesh->vertexSize / 3;
for (int it = 0; it < size; it++) {
for (int itAux = 0; itAux < 4; itAux++) {
if (mesh->boneIDs[(it * 4) + itAux] == (int)i) {
boneAABB.Enclose(vec(mesh->vertices[it * 3], mesh->vertices[(it * 3) + 1], mesh->vertices[(it * 3) + 2]));
}
}
}
ManageAABB(boneAABB, false, true);
}
}
}
}
| 21.595092 | 152 | 0.65554 | HoduRe |
c5b2576542165e747bc3f04a7a127a44f73987bd | 37,332 | cpp | C++ | FireRender.Max.Plugin/parser/MaterialLoader.cpp | Vsevolod1983/RadeonProRenderMaxPlugin | d5393fd04e45dd2c77c8b17fac4e10b20df55285 | [
"Apache-2.0"
] | 6 | 2020-05-24T12:00:43.000Z | 2021-07-13T06:22:49.000Z | FireRender.Max.Plugin/parser/MaterialLoader.cpp | Vsevolod1983/RadeonProRenderMaxPlugin | d5393fd04e45dd2c77c8b17fac4e10b20df55285 | [
"Apache-2.0"
] | 4 | 2020-09-17T17:05:38.000Z | 2021-06-23T14:29:14.000Z | FireRender.Max.Plugin/parser/MaterialLoader.cpp | Vsevolod1983/RadeonProRenderMaxPlugin | d5393fd04e45dd2c77c8b17fac4e10b20df55285 | [
"Apache-2.0"
] | 8 | 2020-05-15T08:29:17.000Z | 2021-07-14T08:38:07.000Z | /**********************************************************************
Copyright 2020 Advanced Micro Devices, 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.
********************************************************************/
#if 0
#include "MaterialLoader.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <map>
#include <set>
#include <string>
#include <stack>
#include <regex>
#include "Common.h"
using namespace std;
//executed RPR func and check for an error
#define CHECK_NO_ERROR(func) { \
rpr_int status = func; \
if (status != RPR_SUCCESS) \
throw std::runtime_error("Radeon ProRender error (" + std::to_string(status) + ") in " + std::string(__FILE__) + ":" + std::to_string(__LINE__)); \
}
namespace
{
const std::string kTab = " "; // default 4spaces tab for xml writer
#ifdef RPR_VERSION_MAJOR_MINOR_REVISION
const int kVersion = RPR_VERSION_MAJOR_MINOR_REVISION;
#else
const int kVersion = RPR_API_VERSION;
#endif
const std::map<int, std::string> kMaterialTypeNames{ { RPR_MATERIAL_NODE_DIFFUSE, "DIFFUSE" },
{ RPR_MATERIAL_NODE_MICROFACET, "MICROFACET" },
{ RPR_MATERIAL_NODE_REFLECTION, "REFLECTION" },
{ RPR_MATERIAL_NODE_REFRACTION, "REFRACTION" },
{ RPR_MATERIAL_NODE_MICROFACET_REFRACTION, "MICROFACET_REFRACTION" },
{ RPR_MATERIAL_NODE_TRANSPARENT, "TRANSPARENT" },
{ RPR_MATERIAL_NODE_EMISSIVE, "EMISSIVE" },
{ RPR_MATERIAL_NODE_WARD, "WARD" },
{ RPR_MATERIAL_NODE_ADD, "ADD" },
{ RPR_MATERIAL_NODE_BLEND, "BLEND" },
{ RPR_MATERIAL_NODE_ARITHMETIC, "ARITHMETIC" },
{ RPR_MATERIAL_NODE_FRESNEL, "FRESNEL" },
{ RPR_MATERIAL_NODE_NORMAL_MAP, "NORMAL_MAP" },
{ RPR_MATERIAL_NODE_IMAGE_TEXTURE, "IMAGE_TEXTURE" },
{ RPR_MATERIAL_NODE_NOISE2D_TEXTURE, "NOISE2D_TEXTURE" },
{ RPR_MATERIAL_NODE_DOT_TEXTURE, "DOT_TEXTURE" },
{ RPR_MATERIAL_NODE_GRADIENT_TEXTURE, "GRADIENT_TEXTURE" },
{ RPR_MATERIAL_NODE_CHECKER_TEXTURE, "CHECKER_TEXTURE" },
{ RPR_MATERIAL_NODE_CONSTANT_TEXTURE, "CONSTANT_TEXTURE" },
{ RPR_MATERIAL_NODE_INPUT_LOOKUP, "INPUT_LOOKUP" },
{ RPR_MATERIAL_NODE_UBERV2, "STANDARD" },
{ RPR_MATERIAL_NODE_BLEND_VALUE, "BLEND_VALUE" },
{ RPR_MATERIAL_NODE_PASSTHROUGH, "PASSTHROUGH" },
{ RPR_MATERIAL_NODE_ORENNAYAR, "ORENNAYAR" },
{ RPR_MATERIAL_NODE_FRESNEL_SCHLICK, "FRESNEL_SCHLICK" },
{ RPR_MATERIAL_NODE_DIFFUSE_REFRACTION, "DIFFUSE_REFRACTION" },
{ RPR_MATERIAL_NODE_BUMP_MAP, "BUMP_MAP" }, };
const std::map<std::string, int> kNodeTypesMap = { { "INPUT_COLOR4F", RPR_MATERIAL_NODE_INPUT_TYPE_FLOAT4 },
{ "INPUT_FLOAT1", RPR_MATERIAL_NODE_INPUT_TYPE_FLOAT4 },
{ "INPUT_UINT", RPR_MATERIAL_NODE_INPUT_TYPE_UINT },
{ "INPUT_NODE", RPR_MATERIAL_NODE_INPUT_TYPE_NODE },
{ "INPUT_TEXTURE", RPR_MATERIAL_NODE_INPUT_TYPE_IMAGE },
{ "DIFFUSE", RPR_MATERIAL_NODE_DIFFUSE },
{ "MICROFACET", RPR_MATERIAL_NODE_MICROFACET },
{ "REFLECTION", RPR_MATERIAL_NODE_REFLECTION },
{ "REFRACTION", RPR_MATERIAL_NODE_REFRACTION },
{ "MICROFACET_REFRACTION", RPR_MATERIAL_NODE_MICROFACET_REFRACTION },
{ "TRANSPARENT", RPR_MATERIAL_NODE_TRANSPARENT },
{ "EMISSIVE", RPR_MATERIAL_NODE_EMISSIVE },
{ "WARD", RPR_MATERIAL_NODE_WARD },
{ "ADD", RPR_MATERIAL_NODE_ADD },
{ "BLEND", RPR_MATERIAL_NODE_BLEND },
{ "ARITHMETIC", RPR_MATERIAL_NODE_ARITHMETIC },
{ "FRESNEL", RPR_MATERIAL_NODE_FRESNEL },
{ "NORMAL_MAP", RPR_MATERIAL_NODE_NORMAL_MAP },
{ "IMAGE_TEXTURE", RPR_MATERIAL_NODE_IMAGE_TEXTURE },
{ "NOISE2D_TEXTURE", RPR_MATERIAL_NODE_NOISE2D_TEXTURE },
{ "DOT_TEXTURE", RPR_MATERIAL_NODE_DOT_TEXTURE },
{ "GRADIENT_TEXTURE", RPR_MATERIAL_NODE_GRADIENT_TEXTURE },
{ "CHECKER_TEXTURE", RPR_MATERIAL_NODE_CHECKER_TEXTURE },
{ "CONSTANT_TEXTURE", RPR_MATERIAL_NODE_CONSTANT_TEXTURE },
{ "INPUT_LOOKUP", RPR_MATERIAL_NODE_INPUT_LOOKUP },
{ "STANDARD", RPR_MATERIAL_NODE_UBERV2 },
{ "BLEND_VALUE", RPR_MATERIAL_NODE_BLEND_VALUE },
{ "PASSTHROUGH", RPR_MATERIAL_NODE_PASSTHROUGH },
{ "ORENNAYAR", RPR_MATERIAL_NODE_ORENNAYAR },
{ "FRESNEL_SCHLICK", RPR_MATERIAL_NODE_FRESNEL_SCHLICK },
{ "DIFFUSE_REFRACTION", RPR_MATERIAL_NODE_DIFFUSE_REFRACTION },
{ "BUMP_MAP", RPR_MATERIAL_NODE_BUMP_MAP }, };
void printMaterialNode(rpr_material_node node)
{
std::cout << "__________________________________________" << std::endl;
size_t mat_name_size = 0;
CHECK_NO_ERROR(rprMaterialNodeGetInfo(node, RPR_OBJECT_NAME, 0, nullptr, &mat_name_size));
std::string mat_name;
mat_name.resize(mat_name_size - 1); // std::string contains terminator already
CHECK_NO_ERROR(rprMaterialNodeGetInfo(node, RPR_OBJECT_NAME, mat_name_size, &mat_name[0], nullptr));
rpr_int type = 0;
CHECK_NO_ERROR(rprMaterialNodeGetInfo(node, RPR_MATERIAL_NODE_TYPE, sizeof(rpr_int), &type, nullptr));
std::cout << "name " << mat_name + ", type: " << kMaterialTypeNames.at(type) << std::endl;
size_t count = 0;
CHECK_NO_ERROR(rprMaterialNodeGetInfo(node, RPR_MATERIAL_NODE_INPUT_COUNT, sizeof(size_t), &count, nullptr));
for (int i = 0; i < count; ++i)
{
size_t str_size = 0;
CHECK_NO_ERROR(rprMaterialNodeGetInputInfo(node, i, RPR_MATERIAL_NODE_INPUT_NAME_STRING, NULL, nullptr, &str_size));
char* str = new char[str_size];
CHECK_NO_ERROR(rprMaterialNodeGetInputInfo(node, i, RPR_MATERIAL_NODE_INPUT_NAME_STRING, str_size, str, nullptr));
std::cout << "\tparam: " << str << ". ";
delete[]str; str = nullptr;
std::cout << std::endl;
}
std::cout << "__________________________________________" << std::endl;
}
struct Param
{
std::string type;
std::string value;
};
struct MaterialNode
{
std::string type;
std::map<std::string, Param> params;
void* data; // RPR object
};
class XmlWriter
{
public:
XmlWriter(const std::string& file)
: m_doc(file)
, top_written(true)
{
}
~XmlWriter()
{
endDocument();
}
//write header
void startDocument()
{
m_doc << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << endl;
}
void endDocument()
{
int size = int_cast(m_nodes.size());
for (int i = 0; i < size; ++i)
{
endElement();
}
}
void startElement(const std::string& node_name)
{
// write prev node with atts
if (m_nodes.size() != 0 && top_written)
{
std::string tab = "";
for (int i = 0; i < m_nodes.size() - 1; ++i) tab += kTab;
const Node& node = m_nodes.top();
m_doc << tab << "<" << node.name << "";
for (const auto& at : node.atts)
{
m_doc << " " << at.type << "=\"" << at.value << "\""; // name = "value"
}
m_doc << ">" << endl;
}
m_nodes.push({ node_name });
top_written = true;
}
void endElement()
{
std::string tab = "";
for (int i = 0; i < m_nodes.size() - 1; ++i) tab += kTab;
const Node& node = m_nodes.top();
if (top_written)
{
const Node& node = m_nodes.top();
m_doc << tab << "<" << node.name << "";
for (const auto& at : node.atts)
{
m_doc << " " << at.type << "=\"" << at.value << "\""; // name = "value"
}
m_doc << "/>" << endl;
}
else
m_doc << tab << "</" << node.name << ">" << endl;
m_nodes.pop();
top_written = false;
}
void writeAttribute(const std::string& name, const std::string& value)
{
Node& node = m_nodes.top();
node.atts.push_back({ name, value });
}
void writeTextElement(const std::string& name, const std::string& text)
{
std::string tab = "";
for (int i = 0; i < m_nodes.size() - 1; ++i) tab += kTab;
if (m_nodes.size() != 0 && top_written)
{
const Node& node = m_nodes.top();
m_doc << tab << "<" << node.name << "";
for (const auto& at : node.atts)
{
m_doc << " " << at.type << "=\"" << at.value << "\""; // name = "value"
}
m_doc << ">" << endl;
}
tab += kTab;
// <name>text</name>
m_doc << tab << "<" << name << ">" << text << "</" << name << ">" << endl;
top_written = false;
}
private:
std::ofstream m_doc;
struct Node
{
std::string name;
std::vector<Param> atts;
};
std::stack<Node> m_nodes;
bool top_written; // true when element in top of m_nodes stack already written into xml
};
class XmlReader
{
public:
struct Node
{
std::string name;
std::string text;
std::map<string, string> atts;
bool is_closing;
Node() : name(""), text(""), is_closing(false) {};
};
XmlReader(const std::string& file) noexcept
: m_xml_text("")
, m_is_open(false)
, m_is_end(false)
, m_self_closing(false)
{
std::ifstream doc(file);
m_is_open = doc.is_open();
m_is_end = !m_is_open;
if (m_is_open)
{
m_xml_text = std::move(std::string((std::istreambuf_iterator<char>(doc)), std::istreambuf_iterator<char>()));
next();
}
}
bool isOpen() const noexcept
{
return m_is_open;
}
bool isEnd() const noexcept
{
return m_is_end;
}
bool next() noexcept
{
// root element is closed
if (!m_is_open || m_is_end)
return false;
if (m_self_closing)
{
m_self_closing = false;
Node& node = m_nodes.top();
node.is_closing = true;
return true;
}
try
{
// remove last node if it's closed
if (!m_nodes.empty() && m_nodes.top().is_closing)
m_nodes.pop();
// regex for searching XML nodes
std::regex node_reg("<[^<^>]*>");
std::smatch node_match;
m_is_end = !std::regex_search(m_xml_text, node_match, node_reg);
if (m_is_end)
return !m_is_end;
if (node_match.size() == 0)
Throw("Invalid xml: bad node");
std::string value = node_match[0];
std::regex name_reg("[^<][^>\\s/]+"); //ignoring '<' symbol
std::smatch name_match;
std::regex_search(value, name_match, name_reg);
// create new node if this is not the closing one
if (name_match.str().find('/') == std::string::npos)
m_nodes.push(Node());
Node& node = m_nodes.top();
node.name = name_match.str();
const std::string ksc_ending = "/>"; //self-closing node ending
if (value.size() > ksc_ending.size())
m_self_closing = std::equal(ksc_ending.rbegin(), ksc_ending.rend(), value.rbegin());
if (node.name.find('/') != std::string::npos)
{
node.is_closing = true;
node.name.erase(std::remove(node.name.begin(), node.name.end(), '/')); //remove closing '/'
}
std::regex att_split_reg("[\\S]+=\".*?\""); //split attributes regex string="string"
std::string attributes = name_match.suffix().str();
auto att_split_begin = std::sregex_iterator(attributes.begin(), attributes.end(), att_split_reg);
auto att_split_end = std::sregex_iterator();
// parsing attributes
for (auto i = att_split_begin; i != att_split_end; ++i)
{
std::string att = i->str();
std::regex att_reg("[^=?>\"]+");
auto att_begin = std::sregex_iterator(att.begin(), att.end(), att_reg);
auto att_end = std::sregex_iterator();
std::vector<std::string> splited_att;
splited_att.reserve(2); //should be 2 values
for (auto j = att_begin; j != att_end; ++j)
{
splited_att.push_back(j->str());
}
if (splited_att.size() == 2)
node.atts[splited_att[0]] = splited_att[1];
else // case when value = ""
node.atts[splited_att[0]] = "";
}
// cut parsed data
m_xml_text = node_match.suffix().str();
// looking for node text data
size_t pos = m_xml_text.find('<');
if (pos != std::string::npos && !m_self_closing)
{
node.text = m_xml_text.substr(0, pos);
node.text = std::regex_replace(node.text, std::regex("^[\\s]+"), ""); //removing beginning whitespaces
node.text = std::regex_replace(node.text, std::regex("[\\s]+^"), ""); //removing ending whitespaces
node.text = std::regex_replace(node.text, std::regex("[\\s]+"), " "); //replace multiple whitespaces by single space
}
}
catch (std::exception e)
{
cout << "Regex exception: " << e.what() << endl;
m_is_end = true;
}
return !m_is_end;
}
const Node& get() const
{
return m_nodes.top();
}
private:
void Throw(const std::string& msg)
{
m_is_end = true;
throw std::runtime_error(msg);
}
std::string m_xml_text;
bool m_is_open;
bool m_is_end;
bool m_self_closing;
std::stack<Node> m_nodes; //stores previoulsy open yet not closed nodes
};
rpr_material_node CreateMaterial(rpr_material_system sys, const MaterialNode& node, const std::string& name)
{
rpr_material_node mat = nullptr;
int type = kNodeTypesMap.at(node.type);
CHECK_NO_ERROR(rprMaterialSystemCreateNode(sys, type, &mat));
CHECK_NO_ERROR(rprObjectSetName(mat, name.c_str()));
return mat;
}
}
void ExportMaterials(const std::string& filename,
const std::set<rpr_material_node>& nodeList,
const std::set<rprx_material>& nodeListX ,
const std::vector<RPRX_DEFINE_PARAM_MATERIAL>& rprxParamList,
rprx_context contextX ,
std::unordered_map<rpr_image , RPR_MATERIAL_XML_EXPORT_TEXTURE_PARAM>& textureParameter,
void* closureNode, // pointer to a rpr_material_node or a rprx_material
const std::string& material_name // example : "Emissive_Fluorescent_Magenta"
)
{
XmlWriter writer(filename);
if (nodeListX.size() == 0 && nodeList.size() == 0)
{
cout << "MaterialExport error: materials input array is nullptr" << endl;
return;
}
try
{
writer.startDocument();
writer.startElement("material");
writer.writeAttribute("name", material_name);
// in case we need versioning the material XMLs... - unused for the moment.
writer.writeAttribute("version_exporter", "10");
//version of the RPR_API_VERSION used to generate this XML
std::stringstream hex_version;
hex_version << "0x" << std::hex << kVersion;
writer.writeAttribute("version_rpr", hex_version.str());
// file path as key, id - for material nodes connections
std::map<std::string, std::pair< std::string , rpr_image > > textures;
std::map<void*, std::string> objects; // <object, node_name> map
std::set<std::string> used_names; // to avoid duplicating node names
std::string closureNodeName = "";
// fill materials first
for(const auto& iNode : nodeList )
{
rpr_material_node mat = iNode;
if (objects.count(mat))
continue;
size_t name_size = 0;
CHECK_NO_ERROR(rprMaterialNodeGetInfo(mat, RPR_OBJECT_NAME, NULL, nullptr, &name_size));
std::string mat_node_name;
mat_node_name.resize(name_size - 1); // exclude extra terminator
CHECK_NO_ERROR(rprMaterialNodeGetInfo(mat, RPR_OBJECT_NAME, name_size, &mat_node_name[0], nullptr));
int postfix_id = 0;
if (mat_node_name.empty())
mat_node_name = "node" + std::to_string(postfix_id);
while (used_names.count(mat_node_name))
{
mat_node_name = "node" + std::to_string(postfix_id);
++postfix_id;
}
if ( mat == closureNode )
closureNodeName = mat_node_name;
objects[mat] = mat_node_name;
used_names.insert(mat_node_name);
}
for(const auto& iNode : nodeListX )
{
rprx_material mat = iNode;
if (objects.count(mat))
continue;
int postfix_id = 0;
std::string mat_node_name = "Uber_" + std::to_string(postfix_id);
while (used_names.count(mat_node_name))
{
mat_node_name = "Uber_" + std::to_string(postfix_id);
++postfix_id;
}
if ( mat == closureNode )
closureNodeName = mat_node_name;
objects[mat] = mat_node_name;
used_names.insert(mat_node_name);
}
// closure_node is the name of the node containing the final output of the material
writer.writeAttribute("closure_node", closureNodeName);
// look for images
for(const auto& iNode : nodeList )
{
rpr_material_node mat = iNode;
size_t input_count = 0;
CHECK_NO_ERROR(rprMaterialNodeGetInfo(mat, RPR_MATERIAL_NODE_INPUT_COUNT, sizeof(size_t), &input_count, nullptr));
for (int input_id = 0; input_id < input_count; ++input_id)
{
rpr_material_node_type input_type;
CHECK_NO_ERROR(rprMaterialNodeGetInputInfo(mat, input_id, RPR_MATERIAL_NODE_INPUT_TYPE, sizeof(input_type), &input_type, nullptr));
if (input_type != RPR_MATERIAL_NODE_INPUT_TYPE_IMAGE)
continue;
rpr_image img = nullptr;
CHECK_NO_ERROR(rprMaterialNodeGetInputInfo(mat, input_id, RPR_MATERIAL_NODE_INPUT_VALUE, sizeof(img), &img, nullptr));
if (objects.count(img)) //already mentioned
continue;
std::string img_node_name = "node0";
int postfix_id = 0;
while (used_names.count(img_node_name))
{
img_node_name = "node" + std::to_string(postfix_id);
++postfix_id;
}
objects[img] = img_node_name;
used_names.insert(img_node_name);
}
}
// optionally write description (at the moment there is no description)
writer.writeTextElement("description", "");
for(const auto& iNode : nodeList )
{
rpr_material_node node = iNode;
rpr_material_node_type type;
size_t input_count = 0;
CHECK_NO_ERROR(rprMaterialNodeGetInfo(node, RPR_MATERIAL_NODE_TYPE, sizeof(rpr_material_node_type), &type, nullptr));
CHECK_NO_ERROR(rprMaterialNodeGetInfo(node, RPR_MATERIAL_NODE_INPUT_COUNT, sizeof(size_t), &input_count, nullptr));
writer.startElement("node");
writer.writeAttribute("name", objects[node]);
writer.writeAttribute("type", kMaterialTypeNames.at(type));
for (int input_id = 0; input_id < input_count; ++input_id)
{
size_t read_count = 0;
CHECK_NO_ERROR(rprMaterialNodeGetInputInfo(node, input_id, RPR_MATERIAL_NODE_INPUT_NAME_STRING, sizeof(size_t), nullptr, &read_count));
std::vector<char> param_name(read_count, ' ');
CHECK_NO_ERROR(rprMaterialNodeGetInputInfo(node, input_id, RPR_MATERIAL_NODE_INPUT_NAME_STRING, sizeof(param_name), param_name.data(), nullptr));
std::string type = "";
std::string value = "";
rpr_material_node_type input_type;
CHECK_NO_ERROR(rprMaterialNodeGetInputInfo(node, input_id, RPR_MATERIAL_NODE_INPUT_TYPE, sizeof(input_type), &input_type, &read_count));
switch (input_type)
{
case RPR_MATERIAL_NODE_INPUT_TYPE_FLOAT4:
{
rpr_float fvalue[4] = { 0.f, 0.f, 0.f, 0.f };
CHECK_NO_ERROR(rprMaterialNodeGetInputInfo(node, input_id, RPR_MATERIAL_NODE_INPUT_VALUE, sizeof(fvalue), fvalue, nullptr));
//fvalue converted to string
std::stringstream ss;
ss << fvalue[0] << ", " <<
fvalue[1] << ", " <<
fvalue[2] << ", " <<
fvalue[3];
type = "float4";
value = ss.str();
break;
}
case RPR_MATERIAL_NODE_INPUT_TYPE_UINT:
{
rpr_int uivalue = RPR_SUCCESS;
CHECK_NO_ERROR(rprMaterialNodeGetInputInfo(node, input_id, RPR_MATERIAL_NODE_INPUT_VALUE, sizeof(uivalue), &uivalue, nullptr));
//value converted to string
type = "uint";
value = std::to_string(uivalue);
break;
}
case RPR_MATERIAL_NODE_INPUT_TYPE_NODE:
{
rpr_material_node connection = nullptr;
rpr_int res = rprMaterialNodeGetInputInfo(node, input_id, RPR_MATERIAL_NODE_INPUT_VALUE, sizeof(connection), &connection, nullptr);
CHECK_NO_ERROR(rprMaterialNodeGetInputInfo(node, input_id, RPR_MATERIAL_NODE_INPUT_VALUE, sizeof(connection), &connection, nullptr));
type = "connection";
if (!objects.count(connection) && connection)
{
throw std::runtime_error("input material node is missing");
}
value = objects[connection];
break;
}
case RPR_MATERIAL_NODE_INPUT_TYPE_IMAGE:
{
type = "connection";
rpr_image tex = nullptr;
CHECK_NO_ERROR(rprMaterialNodeGetInputInfo(node, input_id, RPR_MATERIAL_NODE_INPUT_VALUE, sizeof(tex), &tex, nullptr));
size_t name_size = 0;
CHECK_NO_ERROR(rprImageGetInfo(tex, RPR_OBJECT_NAME, NULL, nullptr, &name_size));
std::string tex_name;
tex_name.resize(name_size - 1);
CHECK_NO_ERROR(rprImageGetInfo(tex, RPR_OBJECT_NAME, name_size, &tex_name[0], nullptr));
//replace \\ by /
//so we ensure all paths are using same convention ( better for Unix )
for(int i=0; i<tex_name.length(); i++)
{
if ( tex_name[i] == '\\' )
tex_name[i] = '/';
}
// we don't want path that looks like : "H:/RPR/MatLib/MaterialLibrary/1.0 - Copy/RadeonProRMaps/Glass_Used_normal.jpg"
// all paths must look like "RadeonProRMaps/Glass_Used_normal.jpg"
// the path RadeonProRMaps/ is hard coded here for the moment .. needs to be exposed in exporter GUI if we change it ?
const std::string radeonProRMapsFolder = "/RadeonProRMaps/";
size_t pos = tex_name.find(radeonProRMapsFolder);
if ( pos != std::string::npos )
{
tex_name = tex_name.substr(pos+1);
int a=0;
}
if (!textures.count(tex_name))
{
int tex_node_id = 0;
std::string tex_node_name = objects[tex];
textures[tex_name] = std::pair<std::string , rpr_image> ( tex_node_name , tex ) ;
}
value = textures[tex_name].first;
break;
}
default:
throw std::runtime_error("unexpected material node input type " + std::to_string(input_type));
}
if (!value.empty())
{
writer.startElement("param");
writer.writeAttribute("name", param_name.data());
writer.writeAttribute("type", type);
writer.writeAttribute("value", value);
writer.endElement();
}
}
writer.endElement();
}
for(const auto& iNode : nodeListX )
{
rprx_material materialX = iNode;
writer.startElement("node");
writer.writeAttribute("name", objects[materialX]);
writer.writeAttribute("type", "UBER");
for(int iParam=0; iParam<rprxParamList.size(); iParam++)
{
std::string type = "";
std::string value = "";
rprx_parameter_type input_type = 0;
CHECK_NO_ERROR( rprxMaterialGetParameterType(contextX,materialX,rprxParamList[iParam].param,&input_type));
if ( input_type == RPRX_PARAMETER_TYPE_FLOAT4 )
{
rpr_float fvalue[4] = { 0.f, 0.f, 0.f, 0.f };
CHECK_NO_ERROR( rprxMaterialGetParameterValue(contextX,materialX,rprxParamList[iParam].param,&fvalue) );
//fvalue converted to string
std::stringstream ss;
ss << fvalue[0] << ", " <<
fvalue[1] << ", " <<
fvalue[2] << ", " <<
fvalue[3];
type = "float4";
value = ss.str();
}
else if ( input_type == RPRX_PARAMETER_TYPE_UINT )
{
rpr_int uivalue = RPR_SUCCESS;
CHECK_NO_ERROR( rprxMaterialGetParameterValue(contextX,materialX,rprxParamList[iParam].param,&uivalue));
//value converted to string
type = "uint";
value = std::to_string(uivalue);
}
else if ( input_type == RPRX_PARAMETER_TYPE_NODE )
{
rpr_material_node connection = 0;
CHECK_NO_ERROR( rprxMaterialGetParameterValue(contextX,materialX,rprxParamList[iParam].param,&connection));
if ( connection )
{
type = "connection";
if (!objects.count(connection) && connection)
{
throw std::runtime_error("input material node is missing");
}
const auto& connectName = objects.find(connection);
if ( connectName != objects.end() )
{
value = connectName->second;
}
else
{
int a=0; // ERROR ?
}
}
}
else
{
throw std::runtime_error("unexpected material nodeX input type " + std::to_string(input_type));
}
if (!value.empty())
{
writer.startElement("param");
writer.writeAttribute("name", rprxParamList[iParam].nameInXML );
writer.writeAttribute("type", type);
writer.writeAttribute("value", value);
writer.endElement();
}
}
writer.endElement();
}
for (const auto& tex : textures)
{
writer.startElement("node");
writer.writeAttribute("name", tex.second.first);
writer.writeAttribute("type", "INPUT_TEXTURE");
writer.startElement("param");
writer.writeAttribute("name", "path");
writer.writeAttribute("type", "file_path");
writer.writeAttribute("value", tex.first);
writer.endElement();
writer.startElement("param");
writer.writeAttribute("name", "gamma");
writer.writeAttribute("type", "float");
bool gammaset = false;
if ( textureParameter.find(tex.second.second) != textureParameter.end() )
{
RPR_MATERIAL_XML_EXPORT_TEXTURE_PARAM& param = textureParameter[tex.second.second];
if ( param.useGamma )
{
writer.writeAttribute("value", std::to_string(2.2f) );
gammaset = true;
}
}
else
{
int a=0;
}
if ( !gammaset )
{
writer.writeAttribute("value", std::to_string(1.0f) );
}
writer.endElement();
writer.endElement();
}
writer.endDocument();
}
catch (const std::exception& ex)
{
cout << "MaterialExport error: " << ex.what() << endl;
}
return;
}
bool ImportMaterials(const std::string& filename, rpr_context context, rpr_material_system sys, rpr_material_node** out_materials, int* out_mat_count)
{
XmlReader read(filename);
if (!read.isOpen())
{
std::cout << "Failed to open file " << filename << std::endl;
return false;
}
std::map<std::string, MaterialNode> nodes;
MaterialNode* last_node = nullptr;
std::vector<rpr_material_node> material_nodes;
std::vector<rpr_image> textures;
std::vector<std::string> tex_files;
try
{
while (!read.isEnd())
{
const XmlReader::Node& node = read.get();
if (!node.is_closing)
{
if (node.name == "node")
{
last_node = &(nodes[read.get().atts.at("name")]);
last_node->type = read.get().atts.at("type");
}
else if (node.name == "param")
{
std::string param_name = read.get().atts.at("name");
std::string param_type = read.get().atts.at("type");
std::string param_value = read.get().atts.at("value");
last_node->params[param_name] = { param_type, param_value };
}
else if (node.name == "description")
{
// at the moment we don't support a description field. easy to add:
// description = read.get().text;
}
else if (node.name == "material")
{
std::stringstream version_stream;
version_stream << std::hex << node.atts.at("version");
int version;
version_stream >> version;
if (version != kVersion)
std::cout << "Warning: Invalid API version. Expected " << hex << kVersion << "." << std::endl;
}
}
read.next();
}
// count material nodes
int count = 0;
for (auto& i : nodes)
if (i.second.type.find("INPUT") == std::string::npos)
++count;
// create nodes
for (auto& i : nodes)
{
MaterialNode& node = i.second;
if (node.type.find("INPUT") == std::string::npos)
{
material_nodes.push_back(CreateMaterial(sys, i.second, i.first));
node.data = material_nodes.back();
}
else if (node.type == "INPUT_TEXTURE")
{
rpr_image texture = nullptr;
const std::string kFilename = node.params.at("path").value;
rpr_int res = rprContextCreateImageFromFile(context, kFilename.c_str(), &texture);
// TODO: Might produce unwanted dialog box?
//^ maybe don't want to give Error messages to the user about unsupported image formats, since we support them through the plugin.
//FCHECK_CONTEXT(res, context, "rprContextCreateImageFromFile");
CHECK_NO_ERROR(res);
textures.push_back(texture);
tex_files.push_back(kFilename);
node.data = texture;
}
}
// setup material parameters
for (auto& i : nodes)
{
MaterialNode& node = i.second;
if (!node.data || node.type == "INPUT_TEXTURE") // we only need material nodes
continue;
for (auto param : node.params)
{
std::string in_input = param.first;
std::string type = param.second.type;
MaterialNode* data_node = &node;
Param* data_param = ¶m.second;
if (type == "connection")
{
data_node = &nodes.at(param.second.value); // connection node
if (data_node->type.find("INPUT") != std::string::npos && data_node->params.size() == 1)
data_param = &(data_node->params.begin()->second);
else if (!data_node->data)
{
cout << "Error: invalid connection.\n";
return false;
}
}
if (data_node->type == "INPUT_TEXTURE")
{
CHECK_NO_ERROR(rprMaterialNodeSetInputImageData(node.data, in_input.c_str(), data_node->data));
}
else if (data_param->type.find("float") != std::string::npos)
{
rpr_float fvalue[4] = { 0.f, 0.f, 0.f, 0.f };
std::string data = data_param->value;
std::replace(data.begin(), data.end(), ',', ' '); // replace comas by spaces to simplify string splitting
std::istringstream iss(data);
std::vector<std::string> tokens{ istream_iterator<std::string>{iss}, std::istream_iterator<string>{} };
int i = 0;
for (const auto& val : tokens)
{
fvalue[i] = std::stof(val);
++i;
}
CHECK_NO_ERROR(rprMaterialNodeSetInputF(node.data, in_input.c_str(), fvalue[0], fvalue[1], fvalue[2], fvalue[3]));
}
else if (data_node->type == "INPUT_UINT")
{
// not handled
rpr_uint uivalue = 0;
CHECK_NO_ERROR(rprMaterialNodeSetInputU(node.data, in_input.c_str(), uivalue));
}
else if (type == "file_path")
{
rpr_image img = nullptr;
rpr_int res = rprContextCreateImageFromFile(context, param.second.value.c_str(), &img);
// TODO: Might produce unwanted dialog box?
//^ maybe don't want to give Error messages to the user about unsupported image formats, since we support them through the plugin.
//FCHECK_CONTEXT(res, context, "rprContextCreateImageFromFile");
CHECK_NO_ERROR(res);
CHECK_NO_ERROR(rprMaterialNodeSetInputImageData(node.data, in_input.c_str(), img));
}
else if (data_node->data)
{
CHECK_NO_ERROR(rprMaterialNodeSetInputN(node.data, in_input.c_str(), data_node->data));
}
else
{
// not handled
cout << "Warning: Unknwon node type: " << data_node->type << endl;
}
}
}
// fill out buffers
if (textures.size() != tex_files.size())
{
cout << "Error: internal error." << endl;
return false;
}
if (out_materials)
{
*out_materials = new rpr_material_node[material_nodes.size()];
memcpy(*out_materials, material_nodes.data(), material_nodes.size() * sizeof(rpr_material_node));
}
if (out_mat_count)
*out_mat_count = int_cast(material_nodes.size());
}
catch (const std::exception& e)
{
cout << "MaterialImport error: " << e.what() << endl;
// Make log to Max Log
string str = e.what();
std::wstring wstr(str.begin(), str.end());
FireRender::LogErrorStringToMaxLog(wstr);
return false;
}
return true;
}
#endif
| 38.055046 | 161 | 0.545484 | Vsevolod1983 |
c5b494796a7a3f93fd5cd88bc784b6ef1ee1b00d | 1,047 | hpp | C++ | include/caffe/util/OpenCL/prelu_layer.hpp | lunochod/caffe | 209fac06cb7893da4fcae0295f5cc882c6569ce9 | [
"BSD-2-Clause"
] | 20 | 2015-06-20T18:08:42.000Z | 2018-05-27T09:28:34.000Z | include/caffe/util/OpenCL/prelu_layer.hpp | rickyHong/CaffeForOpenCL | 209fac06cb7893da4fcae0295f5cc882c6569ce9 | [
"BSD-2-Clause"
] | 3 | 2015-03-30T16:40:42.000Z | 2015-06-03T10:31:51.000Z | include/caffe/util/OpenCL/prelu_layer.hpp | rickyHong/CaffeForOpenCL | 209fac06cb7893da4fcae0295f5cc882c6569ce9 | [
"BSD-2-Clause"
] | 6 | 2015-05-09T02:06:20.000Z | 2015-10-19T07:13:47.000Z | #ifndef __OPENCL_PRELU_LAYER_HPP__
#define __OPENCL_PRELU_LAYER_HPP__
#include <CL/cl.h>
#include <glog/logging.h>
#include <caffe/util/OpenCL/OpenCLDevice.hpp>
#include <caffe/util/OpenCL/OpenCLManager.hpp>
#include <caffe/util/OpenCL/OpenCLPlatform.hpp>
#include <caffe/util/OpenCL/OpenCLSupport.hpp>
#include <iostream> // NOLINT(*)
#include <sstream> // NOLINT(*)
#include <string>
namespace caffe {
namespace OpenCL {
template<typename T> bool clPReLUForward(
const int n,
const int channels,
const int dim,
const T* in,
T* out,
const T* slope_data,
const int div_factor);
template<typename T> bool clPReLUBackward(
const int n,
const int channels,
const int dim,
const T* in_diff,
const T* in_data,
T* out_diff,
const T* slope_data,
const int div_factor);
template<typename T> bool clPReLUParamBackward(
const int n,
const T* in_diff,
const T* in_data,
T* out_diff);
} // namespace OpenCL
} // namespace caffe
#endif // __OPENCL_PRELU_LAYER_HPP__
| 21.367347 | 47 | 0.700096 | lunochod |
c5b805bf68f116642d224142956f83e1f8717ebf | 1,959 | cpp | C++ | lib/src/platform/win/shell.cpp | Voxelum/DeskGap | 9201f1197170385c53f0a2dbb45b6283b518b1c3 | [
"MIT"
] | null | null | null | lib/src/platform/win/shell.cpp | Voxelum/DeskGap | 9201f1197170385c53f0a2dbb45b6283b518b1c3 | [
"MIT"
] | 2 | 2022-03-20T13:09:11.000Z | 2022-03-30T05:07:12.000Z | lib/src/platform/win/shell.cpp | Voxelum/DeskGap | 9201f1197170385c53f0a2dbb45b6283b518b1c3 | [
"MIT"
] | 1 | 2022-03-24T01:33:56.000Z | 2022-03-24T01:33:56.000Z | #include "shell.hpp"
#include "./util/wstring_utf8.h"
#include <Windows.h>
#include <shellapi.h>
#include <shlobj.h>
#include <atlbase.h>
#include <comdef.h>
#include <filesystem>
#include <wrl/client.h>
namespace fs = std::filesystem;
bool DeskGap::Shell::OpenExternal(const std::string &urlString)
{
std::wstring wUrlString = UTF8ToWString(urlString.c_str());
return ShellExecuteW(
nullptr, L"open",
wUrlString.c_str(),
nullptr, nullptr,
SW_SHOWNORMAL) > (HINSTANCE)32;
}
bool DeskGap::Shell::ShowItemInFolder(const std::string &path)
{
// copy from electron ShowItemInFolder
Microsoft::WRL::ComPtr<IShellFolder> desktop;
HRESULT hr = SHGetDesktopFolder(desktop.GetAddressOf());
if (FAILED(hr))
return false;
fs::path full_path(path);
fs::path dir(full_path.parent_path());
ITEMIDLIST *dir_item;
hr = desktop->ParseDisplayName(NULL, NULL,
const_cast<wchar_t *>(dir.c_str()),
NULL, &dir_item, NULL);
if (FAILED(hr))
return false;
ITEMIDLIST *file_item;
hr = desktop->ParseDisplayName(
NULL, NULL, const_cast<wchar_t *>(full_path.c_str()), NULL,
&file_item, NULL);
if (FAILED(hr))
return false;
const ITEMIDLIST *highlight[] = {file_item};
hr = SHOpenFolderAndSelectItems(dir_item, std::size(highlight), highlight, NULL);
if (FAILED(hr))
{
if (hr == ERROR_FILE_NOT_FOUND)
{
// On some systems, the above call mysteriously fails with "file not
// found" even though the file is there. In these cases, ShellExecute()
// seems to work as a fallback (although it won't select the file).
ShellExecute(NULL, L"open", dir.c_str(), NULL, NULL, SW_SHOW);
}
}
CoTaskMemFree(dir_item);
CoTaskMemFree(file_item);
return true;
}
| 28.391304 | 85 | 0.61511 | Voxelum |
c5baa1014ecd4f16fbee2cd167a2760716161dc0 | 2,067 | cpp | C++ | Othuum/VishalaNetworkLib/Protocoll/Server/GameLobby.cpp | Liech/Yathsou | 95b6dda3c053bc25789cce416088e22f54a743b4 | [
"MIT"
] | 5 | 2021-04-20T17:00:41.000Z | 2022-01-18T20:16:03.000Z | Othuum/VishalaNetworkLib/Protocoll/Server/GameLobby.cpp | Liech/Yathsou | 95b6dda3c053bc25789cce416088e22f54a743b4 | [
"MIT"
] | 7 | 2021-08-22T21:30:50.000Z | 2022-01-14T16:56:34.000Z | Othuum/VishalaNetworkLib/Protocoll/Server/GameLobby.cpp | Liech/Yathsou | 95b6dda3c053bc25789cce416088e22f54a743b4 | [
"MIT"
] | null | null | null | #include "GameLobby.h"
#include "LobbyPlayer.h"
#include <iostream>
namespace Vishala {
namespace Server {
GameLobby::GameLobby(std::string name,int gameServerPort, std::string ip, size_t number, std::shared_ptr<LobbyModel> model) {
_name = name ;
_model = model ;
_number = number;
_gameServerPort = gameServerPort;
_gameServerIP = ip;
}
std::string GameLobby::getName() {
return _name;
}
size_t GameLobby::getNumber() {
return _number;
}
void GameLobby::addPlayer(std::shared_ptr<LobbyPlayer> player) {
_participators[player->getID()] = player;
sendUpdate();
}
void GameLobby::removePlayer(size_t playerID) {
auto player = _participators[playerID];
_participators.erase(playerID);
player->leaveGame();
sendUpdate();
}
void GameLobby::closeGame() {
for (auto player : _participators) {
player.second->leaveGame();
}
}
size_t GameLobby::getNumberOfPlayers() {
return _participators.size();
}
void GameLobby::sendUpdate() {
GameLobbyStateUpdate update;
update.currentPlayers.clear();
std::cout << "Send GameLobby update: " << getName()<<std::endl;
for (auto p : _participators){
GameLobbyPlayer player;
player.lobbyIdentification.name = p.second->getName();
player.lobbyIdentification.color = p.second->getColor();
player.lobbyIdentification.id = p.first;
std::cout << " " << player.lobbyIdentification.name << std::endl;
update.currentPlayers.push_back(player);
}
update.gameName = getName();
update.gameStart = _gameStarted;
update.gameServerPort = _gameServerPort;
update.gameServerIP = _gameServerIP;
for (auto p : _participators)
p.second->sendGameLobbyUpdate(update);
}
void GameLobby::startGame() {
std::cout << "GAME START" << std::endl;
_gameStarted = true;
sendUpdate();
}
}
} | 28.315068 | 129 | 0.613933 | Liech |
c5bc64a0b17db35d8fd3a28c53c5500edcd1a503 | 3,712 | cpp | C++ | dev/g++/ifsttar/wifiMapping/wifimapping/src/checkRtc.cpp | YannGarcia/repo | 0f3de24c71d942c752ada03c10861e83853fdf71 | [
"MIT"
] | null | null | null | dev/g++/ifsttar/wifiMapping/wifimapping/src/checkRtc.cpp | YannGarcia/repo | 0f3de24c71d942c752ada03c10861e83853fdf71 | [
"MIT"
] | null | null | null | dev/g++/ifsttar/wifiMapping/wifimapping/src/checkRtc.cpp | YannGarcia/repo | 0f3de24c71d942c752ada03c10861e83853fdf71 | [
"MIT"
] | 1 | 2017-01-27T12:53:50.000Z | 2017-01-27T12:53:50.000Z | /* Beaglebone check RTC result implementation
* Copyright (c) 2013 ygarcia, MIT License
*
* 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 <iomanip>
#include <sstream> // std::ostringstream
#include <cstring> // Used std::strerror, memcpy
#include <unistd.h>
#include "beagleboneCommEx.h"
#include "checkRtc.h"
#include "ipcCommon.h"
namespace wifimapping {
checkRtc::checkRtc() : _status(0x00), _timestamp(0) {
std::clog << ">>> checkRtc::checkRtc" << std::endl;
} // End of Constructor
checkRtc::~checkRtc() {
std::clog << ">>> checkRtc::~checkRtc" << std::endl;
uninitialize();
}
int checkRtc::initialize() {
std::clog << ">>> checkRtc::initialize" << std::endl;
if (_smMgr.open(RTC_SEGMENT_ID) != 0) {
std::cerr << "checkRtc::initialize: Failed to open the shared memory: " << std::strerror(errno) << std::endl;
return -1;
}
_result.clear();
return 0;
}
int checkRtc::uninitialize() {
std::clog << ">>> checkRtc::uninitialize" << std::endl;
return _smMgr.close();
}
void checkRtc::update() {
// std::clog << ">>> checkRtc::update" << std::endl;
_status = 0x00;
_timestamp = time(NULL); // Current time
/**
// Read share memory
_result.clear();
if (_smMgr.read(_result, RTC_DATA_LENGTH) != 0) {
std::cerr << "checkRtc::update: Failed to access the shared memory: " << std::strerror(errno) << std::endl;
return;
}
// Update values
_values.clear();
unsigned int nvalues = _result[0];
if (nvalues != 0) {
unsigned int offset = sizeof(unsigned char);
for (unsigned int i = 0; i < nvalues; i++) {
float value = *((float *)(_result.data() + offset));
_values.push_back(value);
offset += sizeof(float);
} // End of 'for' statement
}
*/
// std::clog << "<<< checkRtc::update: size=" << (int)_values.size() << std::endl;
} // End of method update
void checkRtc::serialize(archive & p_archive) {
// std::clog << ">>> checkRtc::serialize: " << (int)_values.size() << std::endl;
// Serialize shared memory segment identifier
p_archive.serialize(static_cast<unsigned char>(RTC_SEGMENT_ID));
// Serialize the status
p_archive.serialize(_status);
// Serialize the time stamp
p_archive.serialize(_timestamp);
} // End of method serialize
std::string & checkRtc::toString() const {
static std::string str;
std::ostringstream os;
os << "status: " << static_cast<unsigned int>(_status) << " - timestamp: " << _timestamp << std::endl;
str = os.str();
return str;
} // End of method toString
} // End of namespace wifimapping
| 32.561404 | 115 | 0.65625 | YannGarcia |
c5bcd29a0721bf8b18d5dd4d87aa3e9125bd80c8 | 3,749 | cpp | C++ | 6LinkedList/linkedListFunctions/linkedList/linkedList/main.cpp | mingyuefly/geekTimeCode | d97c5f29a429ac9cc7289ac34e049ea43fa58822 | [
"MIT"
] | 1 | 2019-05-01T04:51:14.000Z | 2019-05-01T04:51:14.000Z | 6LinkedList/linkedListFunctions/linkedList/linkedList/main.cpp | mingyuefly/geekTimeCode | d97c5f29a429ac9cc7289ac34e049ea43fa58822 | [
"MIT"
] | null | null | null | 6LinkedList/linkedListFunctions/linkedList/linkedList/main.cpp | mingyuefly/geekTimeCode | d97c5f29a429ac9cc7289ac34e049ea43fa58822 | [
"MIT"
] | null | null | null | //
// main.cpp
// linkedList
//
// Created by Gguomingyue on 2019/3/12.
// Copyright © 2019 Gmingyue. All rights reserved.
//
#include <iostream>
#include "LinkedList.h"
using namespace std;
int main(int argc, const char * argv[]) {
ListNode *head = (ListNode *)malloc(sizeof(ListNode));
head->val = 0;
ListNode *node1 = (ListNode *)malloc(sizeof(ListNode));
node1->val = 2;
head->next = node1;
ListNode *node2 = (ListNode *)malloc(sizeof(ListNode));
node2->val = 5;
node1->next = node2;
ListNode *node3 = (ListNode *)malloc(sizeof(ListNode));
node3->val = 7;
node2->next = node3;
ListNode *node4 = (ListNode *)malloc(sizeof(ListNode));
node4->val = 8;
node3->next = node4;
ListNode *node5 = (ListNode *)malloc(sizeof(ListNode));
node5->val = 13;
//node5->next = node3;
node5->next = NULL;
node4->next = node5;
//ListNode *newHead = reverseList(head);
int hasCircle = hasCycle(head);
cout << hasCircle << endl;
if (!hasCircle) {
ListNode *lHead = head;
//ListNode *lHead = newHead;
while (lHead) {
cout << lHead->val << " ";
lHead = lHead->next;
}
cout << endl;
} else {
ListNode * prtNode = findLoopStart(head);
cout << prtNode->val << endl;
}
ListNode *headt = (ListNode *)malloc(sizeof(ListNode));
headt->val = 1;
ListNode *nodet1 = (ListNode *)malloc(sizeof(ListNode));
nodet1->val = 4;
headt->next = nodet1;
ListNode *nodet2 = (ListNode *)malloc(sizeof(ListNode));
nodet2->val = 5;
nodet1->next = nodet2;
ListNode *nodet3 = (ListNode *)malloc(sizeof(ListNode));
nodet3->val = 9;
nodet2->next = nodet3;
ListNode *nodet4 = (ListNode *)malloc(sizeof(ListNode));
nodet4->val = 17;
nodet3->next = nodet4;
ListNode *nodet5 = (ListNode *)malloc(sizeof(ListNode));
nodet5->val = 21;
//node5->next = node3;
nodet5->next = NULL;
nodet4->next = nodet5;
int hasCirclet = hasCycle(headt);
cout << hasCirclet << endl;
if (!hasCirclet) {
ListNode *lHead = headt;
//ListNode *lHead = newHead;
while (lHead) {
cout << lHead->val << " ";
lHead = lHead->next;
}
cout << endl;
} else {
ListNode * prtNode = findLoopStart(headt);
cout << prtNode->val << endl;
}
ListNode *headMerge = mergeTwoLists(head, headt);
int hasCircleMerge = hasCycle(headMerge);
cout << hasCircleMerge << endl;
if (!hasCircleMerge) {
ListNode *lHead = headMerge;
//ListNode *lHead = newHead;
while (lHead) {
cout << lHead->val << " ";
lHead = lHead->next;
}
cout << endl;
} else {
ListNode * prtNode = findLoopStart(headMerge);
cout << prtNode->val << endl;
}
ListNode * middleheadMerge = middleNode(headMerge);
cout << middleheadMerge->val << endl;
ListNode *headAfterRemove = removeNthFromEnd(headMerge, 5);
int hasCircleAfterRemove = hasCycle(headAfterRemove);
cout << hasCircleAfterRemove << endl;
if (!hasCircleAfterRemove) {
ListNode *lHead = headAfterRemove;
//ListNode *lHead = newHead;
while (lHead) {
cout << lHead->val << " ";
lHead = lHead->next;
}
cout << endl;
} else {
ListNode * prtNode = findLoopStart(headAfterRemove);
cout << prtNode->val << endl;
}
ListNode * middleheadAfterRemove = middleNode(headAfterRemove);
cout << middleheadAfterRemove->val << endl;
return 0;
}
| 26.778571 | 67 | 0.561216 | mingyuefly |
c5bea01be7c111b3e27b5dbba3ab7ca7841540d0 | 3,004 | hpp | C++ | sandbox/usda/lexy/dsl/bom.hpp | fire/tinyusdz | 2a98a12d0c6f34de8d7a219e5f82135e9beb4376 | [
"MIT"
] | 159 | 2020-04-14T15:59:35.000Z | 2022-03-31T14:19:05.000Z | sandbox/usda/lexy/dsl/bom.hpp | fire/tinyusdz | 2a98a12d0c6f34de8d7a219e5f82135e9beb4376 | [
"MIT"
] | 16 | 2020-05-21T06:00:40.000Z | 2022-02-26T08:50:33.000Z | sandbox/usda/lexy/dsl/bom.hpp | fire/tinyusdz | 2a98a12d0c6f34de8d7a219e5f82135e9beb4376 | [
"MIT"
] | 8 | 2020-07-01T04:13:42.000Z | 2022-01-30T17:50:52.000Z | // Copyright (C) 2020 Jonathan Müller <jonathanmueller.dev@gmail.com>
// This file is subject to the license terms in the LICENSE file
// found in the top-level directory of this distribution.
#ifndef LEXY_DSL_BOM_HPP_INCLUDED
#define LEXY_DSL_BOM_HPP_INCLUDED
#include <lexy/dsl/base.hpp>
namespace lexyd
{
template <typename Encoding, lexy::encoding_endianness Endianness>
struct _bom_impl
{
static_assert(Endianness != lexy::encoding_endianness::bom,
"bom with BOM-endianness doesn't make sense");
static constexpr auto name = "";
static constexpr const unsigned char* value = nullptr;
static constexpr std::size_t length = 0u;
};
template <lexy::encoding_endianness DontCare>
struct _bom_impl<lexy::utf8_encoding, DontCare>
{
static constexpr auto name = "BOM.UTF-8";
static constexpr unsigned char value[] = {0xEF, 0xBB, 0xBF};
static constexpr auto length = 3u;
};
template <>
struct _bom_impl<lexy::utf16_encoding, lexy::encoding_endianness::little>
{
static constexpr auto name = "BOM.UTF-16-LE";
static constexpr unsigned char value[] = {0xFF, 0xFE};
static constexpr auto length = 2u;
};
template <>
struct _bom_impl<lexy::utf16_encoding, lexy::encoding_endianness::big>
{
static constexpr auto name = "BOM.UTF-16-BE";
static constexpr unsigned char value[] = {0xFE, 0xFF};
static constexpr auto length = 2u;
};
template <>
struct _bom_impl<lexy::utf32_encoding, lexy::encoding_endianness::little>
{
static constexpr auto name = "BOM.UTF-32-LE";
static constexpr unsigned char value[] = {0xFF, 0xFE, 0x00, 0x00};
static constexpr auto length = 4u;
};
template <>
struct _bom_impl<lexy::utf32_encoding, lexy::encoding_endianness::big>
{
static constexpr auto name = "BOM.UTF-32-BE";
static constexpr unsigned char value[] = {0x00, 0x00, 0xFE, 0xFF};
static constexpr auto length = 4u;
};
template <typename Encoding, lexy::encoding_endianness Endianness>
struct _bom : atom_base<_bom<Encoding, Endianness>>
{
using _impl = _bom_impl<Encoding, Endianness>;
template <typename Reader>
LEXY_DSL_FUNC bool match(Reader& reader)
{
constexpr auto string
= lexy::_detail::basic_string_view<unsigned char>(_impl::value, _impl::length);
for (auto c : string)
{
if (reader.peek() != Reader::encoding::to_int_type(typename Reader::char_type(c)))
return false;
reader.bump();
}
return true;
}
template <typename Reader>
LEXY_DSL_FUNC auto error(const Reader&, typename Reader::iterator pos)
{
return lexy::make_error<Reader, lexy::expected_char_class>(pos, _impl::name);
}
};
/// The BOM for that particular encoding.
template <typename Encoding, lexy::encoding_endianness Endianness>
inline constexpr auto bom = _bom<Encoding, Endianness>{};
} // namespace lexyd
#endif // LEXY_DSL_BOM_HPP_INCLUDED
| 30.653061 | 94 | 0.687417 | fire |
c5c14cc59e7efddc4ae133c81c329968966b7f35 | 389 | hpp | C++ | cef_client/include/FunctionBinding.hpp | jarrettchisholm/glr | 79a57b12e26fe84595e833cace3528cb9c82bc20 | [
"WTFPL"
] | 11 | 2015-08-19T23:15:41.000Z | 2018-05-15T21:53:28.000Z | cef_client/include/FunctionBinding.hpp | jarrettchisholm/glr | 79a57b12e26fe84595e833cace3528cb9c82bc20 | [
"WTFPL"
] | 2 | 2015-05-21T06:37:24.000Z | 2015-05-23T05:37:16.000Z | cef_client/include/FunctionBinding.hpp | jarrettchisholm/glr | 79a57b12e26fe84595e833cace3528cb9c82bc20 | [
"WTFPL"
] | 5 | 2016-10-31T08:02:15.000Z | 2018-08-24T07:40:23.000Z | #ifndef FUNCTIONBINDING_H_
#define FUNCTIONBINDING_H_
#include <string>
#include "Macros.hpp"
namespace glr
{
namespace cef_client
{
class FunctionBinding
{
public:
FunctionBinding(std::wstring name);
virtual ~FunctionBinding();
// TODO: Get rid of macro setter and getter
GETSET(std::wstring, name_, Name)
private:
std::wstring name_;
};
}
}
#endif /* FUNCTIONBINDING_H_ */
| 12.966667 | 44 | 0.737789 | jarrettchisholm |
c5c2d6397466d1196be986eee82ec310d8178785 | 655 | cpp | C++ | Containers/set.cpp | JanaSabuj/CodingLibrary | 92bc141ae327ce01b480fde7a10ffb0be0ba401d | [
"MIT"
] | 14 | 2020-05-17T18:31:32.000Z | 2021-02-04T03:56:30.000Z | Containers/set.cpp | JanaSabuj/cppdump | 92bc141ae327ce01b480fde7a10ffb0be0ba401d | [
"MIT"
] | null | null | null | Containers/set.cpp | JanaSabuj/cppdump | 92bc141ae327ce01b480fde7a10ffb0be0ba401d | [
"MIT"
] | 2 | 2020-05-27T10:42:36.000Z | 2021-02-02T11:59:04.000Z | #include <bits/stdc++.h>
using namespace std;
int main() {
multiset<int> s;
s.insert(2);s.insert(78);s.insert(-3);s.insert(-3);s.insert(-3);
// -3 -3 -3 2 78
cout << *s.begin() << endl;// -3
cout << *s.rbegin() << endl;// 78
s.erase(s.find(-3));// -3 -3 2 78
cout << *s.begin() << endl;// -3
s.erase(s.find(-3));// -3 2 78
cout << *s.begin() << endl;// -3
s.erase(s.find(-3));// 2 78
cout << *s.begin() << endl;// 2
// s.erase(s.find(-3));// error
if(s.find(-3) != s.end()) // do check for no error
s.erase(s.find(-3));// no-error
cout << *s.begin() << endl;
return 0;
}
| 22.586207 | 68 | 0.473282 | JanaSabuj |
c5c6246b804cd4f3cf602bf3a99304183cd3ecab | 11,192 | cc | C++ | src/ui/a11y/lib/gesture_manager/recognizers/m_finger_n_tap_drag_recognizer.cc | billchen1977/fuchsia | d443f9c7b03ad317d1700c2c9457be8ed1147b86 | [
"BSD-2-Clause"
] | null | null | null | src/ui/a11y/lib/gesture_manager/recognizers/m_finger_n_tap_drag_recognizer.cc | billchen1977/fuchsia | d443f9c7b03ad317d1700c2c9457be8ed1147b86 | [
"BSD-2-Clause"
] | null | null | null | src/ui/a11y/lib/gesture_manager/recognizers/m_finger_n_tap_drag_recognizer.cc | billchen1977/fuchsia | d443f9c7b03ad317d1700c2c9457be8ed1147b86 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 2021 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 "src/ui/a11y/lib/gesture_manager/recognizers/m_finger_n_tap_drag_recognizer.h"
#include <lib/async/cpp/task.h>
#include <lib/async/default.h>
#include <lib/syslog/cpp/macros.h>
#include <set>
#include "src/lib/fxl/strings/string_printf.h"
#include "src/ui/a11y/lib/gesture_manager/gesture_util/util.h"
namespace a11y {
struct MFingerNTapDragRecognizer::Contest {
Contest(std::unique_ptr<ContestMember> contest_member)
: member(std::move(contest_member)), reject_task(member.get()), accept_task(member.get()) {}
std::unique_ptr<ContestMember> member;
// Indicates whether m fingers have been on the screen at the same time
// during the current tap.
bool tap_in_progress = false;
// Keeps the count of the number of taps detected so far, for the gesture.
uint32_t number_of_taps_detected = 0;
// Indicaes whether the recognizer has successfully accepted the gesture.
bool won = false;
// Async task used to schedule long-press timeout.
async::TaskClosureMethod<ContestMember, &ContestMember::Reject> reject_task;
// Async task to schedule delayed win for held tap.
async::TaskClosureMethod<ContestMember, &ContestMember::Accept> accept_task;
};
MFingerNTapDragRecognizer::MFingerNTapDragRecognizer(OnMFingerNTapDragCallback on_recognize,
OnMFingerNTapDragCallback on_update,
OnMFingerNTapDragCallback on_complete,
uint32_t number_of_fingers,
uint32_t number_of_taps)
: number_of_fingers_in_gesture_(number_of_fingers),
number_of_taps_in_gesture_(number_of_taps),
on_recognize_(std::move(on_recognize)),
on_update_(std::move(on_update)),
on_complete_(std::move(on_complete)) {}
MFingerNTapDragRecognizer::~MFingerNTapDragRecognizer() = default;
void MFingerNTapDragRecognizer::OnTapStarted() {
// If this tap is the last in the gesture, post a task to accept the gesture
// if the fingers are still on screen after kMinTapHoldDuration has elapsed.
// Otherwise, if this tap is NOT the last in the gesture, post a task to
// reject the gesture if the fingers have not lifted by the time kTapTimeout
// elapses.
if (contest_->number_of_taps_detected == number_of_taps_in_gesture_ - 1) {
contest_->accept_task.PostDelayed(async_get_default_dispatcher(), kMinTapHoldDuration);
} else {
contest_->reject_task.PostDelayed(async_get_default_dispatcher(), kTapTimeout);
}
}
void MFingerNTapDragRecognizer::OnExcessFingers() {
// If the gesture has already been accepted (i.e. the user has successfully
// performed n-1 taps, followed by a valid hold, but an (m+1)th finger comes
// down on screen, we should invoke the on_complete_ callback.
// In any event, the gesture is no longer valid, so we should reset the
// recognizer.
if (contest_->won) {
on_complete_(gesture_context_);
}
ResetRecognizer();
}
void MFingerNTapDragRecognizer::OnMoveEvent(
const fuchsia::ui::input::accessibility::PointerEvent& pointer_event) {
// If we've accepted the gesture, invoke on_update_. Otherwise, if the current
// tap is the last (which could become a drag), we should check if the
// fingers have already moved far enough to constitute a drag.
// If this tap is not the last, we should verify that the
// fingers are close enough to their starting locations to constitute a valid
// tap.
if (contest_->won) {
on_update_(gesture_context_);
} else if (contest_->number_of_taps_detected == number_of_taps_in_gesture_ - 1) {
if (DisplacementExceedsDragThreshold()) {
contest_->member->Accept();
return;
}
} else if (!PointerEventIsValidTap(gesture_context_, pointer_event)) {
ResetRecognizer();
}
}
void MFingerNTapDragRecognizer::OnUpEvent() {
// If we've already accepted the gesture, then we should invoke on_complete_
// and reset the recognizer once the first UP event is received (at which
// point, the drag is considered complete).
if (contest_->won) {
on_complete_(gesture_context_);
ResetRecognizer();
return;
}
// If we have counted number_of_taps_in_gesture_ - 1 complete taps, then this
// UP event must mark the end of the drag. If we have not already accepted the
// gesture at this point, we should reject.
if (contest_->number_of_taps_detected == number_of_taps_in_gesture_ - 1) {
ResetRecognizer();
return;
}
// If this UP event removed the last finger from the screen, then the most
// recent tap is complete.
if (!NumberOfFingersOnScreen(gesture_context_)) {
// If we've made it this far, we know that (1) m fingers were on screen
// simultaneously during the current single tap, and (2) The m fingers have
// now been removed, without any interceding finger DOWN events.
// Therefore, we can conclude that a complete m-finger tap has occurred.
contest_->number_of_taps_detected++;
// Mark that all m fingers were removed from the screen.
contest_->tap_in_progress = false;
// Cancel task which was scheduled for detecting single tap.
contest_->reject_task.Cancel();
// Schedule task with delay of timeout_between_taps_.
contest_->reject_task.PostDelayed(async_get_default_dispatcher(), kTimeoutBetweenTaps);
}
}
void MFingerNTapDragRecognizer::HandleEvent(
const fuchsia::ui::input::accessibility::PointerEvent& pointer_event) {
FX_DCHECK(contest_);
FX_DCHECK(pointer_event.has_pointer_id())
<< DebugName() << ": Pointer event is missing pointer id.";
const auto pointer_id = pointer_event.pointer_id();
FX_DCHECK(pointer_event.has_phase())
<< DebugName() << ": Pointer event is missing phase information.";
switch (pointer_event.phase()) {
case fuchsia::ui::input::PointerEventPhase::DOWN:
// If we receive a DOWN event when there are already m fingers on the
// screen, then either we've received a second DOWN event for one of the fingers that's
// already on the screen, or we've received a DOWN event for an (m+1)th
// finger. In either case, we should abandon the current gesture.
if (NumberOfFingersOnScreen(gesture_context_) >= number_of_fingers_in_gesture_) {
OnExcessFingers();
break;
}
// If we receive a DOWN event when there is a tap in progress, then we
// should abandon the gesture.
// NOTE: this is a distinct check from the one above, and is required to
// ensure that the number of fingers touching the screen decreases
// monotonically once the first finger is removed.
// For example,
// consider the case of finger 1 DOWN, finger 2 DOWN, finger 2 UP, finger
// 2 DOWN. Clearly, this is not a two-finger tap, but at the time of the
// second "finger 2 DOWN" event, contest->fingers_on_screen.size() would
// be 1, so the check above would pass.
if (contest_->tap_in_progress) {
ResetRecognizer();
break;
}
// If we receive successive DOWN events for the same pointer without an
// UP event, then we should abandon the current gesture.
if (FingerIsOnScreen(gesture_context_, pointer_id)) {
ResetRecognizer();
break;
}
// Initialize starting info for this new tap.
if (!InitializeStartingGestureContext(pointer_event, &gesture_context_)) {
ResetRecognizer();
break;
}
// If the total number of fingers involved in the gesture now exceeds
// number_of_fingers_in_gesture_, reject the gesture.
if (gesture_context_.starting_pointer_locations.size() > number_of_fingers_in_gesture_) {
ResetRecognizer();
break;
}
// Cancel task which would be scheduled for timeout between taps.
contest_->reject_task.Cancel();
contest_->tap_in_progress =
(NumberOfFingersOnScreen(gesture_context_) == number_of_fingers_in_gesture_);
// Only start the timeout once all m fingers are on the screen together.
if (contest_->tap_in_progress) {
OnTapStarted();
}
break;
case fuchsia::ui::input::PointerEventPhase::MOVE:
FX_DCHECK(FingerIsOnScreen(gesture_context_, pointer_id))
<< DebugName() << ": Pointer MOVE event received without preceding DOWN event.";
// Validate the pointer_event for the gesture being performed.
if (!ValidatePointerEvent(gesture_context_, pointer_event)) {
ResetRecognizer();
break;
}
UpdateGestureContext(pointer_event, true /* finger is on screen */, &gesture_context_);
OnMoveEvent(pointer_event);
break;
case fuchsia::ui::input::PointerEventPhase::UP:
FX_DCHECK(FingerIsOnScreen(gesture_context_, pointer_id))
<< DebugName() << ": Pointer UP event received without preceding DOWN event.";
// Validate pointer_event for the gesture being performed.
if (!ValidatePointerEvent(gesture_context_, pointer_event)) {
ResetRecognizer();
break;
}
UpdateGestureContext(pointer_event, false /* finger is not on screen */, &gesture_context_);
// The number of fingers on screen during a multi-finger tap should
// monotonically increase from 0 to m, and
// then monotonically decrease back to 0. If a finger is removed before
// number_of_fingers_in_gesture_ fingers are on the screen simultaneously,
// then we should reject this gesture.
if (!contest_->tap_in_progress) {
ResetRecognizer();
break;
}
OnUpEvent();
break;
default:
break;
}
}
bool MFingerNTapDragRecognizer::DisplacementExceedsDragThreshold() {
return SquareDistanceBetweenPoints(
gesture_context_.StartingCentroid(false /*use_local_coordinates*/),
gesture_context_.CurrentCentroid(false /*use_local_coordinates*/)) >=
kDragDisplacementThreshold * kDragDisplacementThreshold;
}
void MFingerNTapDragRecognizer::ResetRecognizer() {
contest_.reset();
ResetGestureContext(&gesture_context_);
}
void MFingerNTapDragRecognizer::OnWin() {
on_recognize_(gesture_context_);
if (contest_) {
contest_->won = true;
} else {
// It's possible that we don't get awarded the win until after the gesture has
// completed, in which case we also need to call the complete handler.
on_complete_(gesture_context_);
ResetRecognizer();
}
}
void MFingerNTapDragRecognizer::OnDefeat() { ResetRecognizer(); }
void MFingerNTapDragRecognizer::OnContestStarted(std::unique_ptr<ContestMember> contest_member) {
ResetRecognizer();
contest_ = std::make_unique<Contest>(std::move(contest_member));
}
std::string MFingerNTapDragRecognizer::DebugName() const {
return fxl::StringPrintf("MFingerNTapDragRecognizer(m=%d, n=%d)", number_of_fingers_in_gesture_,
number_of_taps_in_gesture_);
}
} // namespace a11y
| 39.687943 | 98 | 0.703181 | billchen1977 |
c5c718c78e8a9e32e4da00cff280a44ac6c6d6f5 | 6,409 | cpp | C++ | direct/src/plugin_activex/P3DActiveX.cpp | cmarshall108/panda3d-python3 | 8bea2c0c120b03ec1c9fd179701fdeb7510bb97b | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | direct/src/plugin_activex/P3DActiveX.cpp | cmarshall108/panda3d-python3 | 8bea2c0c120b03ec1c9fd179701fdeb7510bb97b | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | direct/src/plugin_activex/P3DActiveX.cpp | cmarshall108/panda3d-python3 | 8bea2c0c120b03ec1c9fd179701fdeb7510bb97b | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | /**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file P3DActiveX.cpp
* @author atrestman
* @date 2009-09-14
*/
// P3DActiveX.cpp : Implementation of CP3DActiveXApp and DLL registration.
#include "stdafx.h"
#include "P3DActiveX.h"
#include "comcat.h"
#include "strsafe.h"
#include "objsafe.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
CP3DActiveXApp NEAR theApp;
const GUID CDECL BASED_CODE _tlid =
{ 0x22A8FC5F, 0xBC33, 0x479A, { 0x83, 0x17, 0x2B, 0xC8, 0x16, 0xB8, 0xAB, 0x8A } };
const WORD _wVerMajor = 1;
const WORD _wVerMinor = 0;
// CLSID_SafeItem - Necessary for safe ActiveX control
// Id taken from IMPLEMENT_OLECREATE_EX function in xxxCtrl.cpp
const CATID CLSID_SafeItem =
{ 0x924b4927, 0xd3ba, 0x41ea, 0x9f, 0x7e, 0x8a, 0x89, 0x19, 0x4a, 0xb3, 0xac };
// HRESULT CreateComponentCategory - Used to register ActiveX control as safe
HRESULT CreateComponentCategory(CATID catid, WCHAR *catDescription)
{
ICatRegister *pcr = NULL ;
HRESULT hr = S_OK ;
hr = CoCreateInstance(CLSID_StdComponentCategoriesMgr,
NULL, CLSCTX_INPROC_SERVER, IID_ICatRegister, (void**)&pcr);
if (FAILED(hr))
return hr;
// Make sure the HKCR\Component Categories\{..catid...}
// key is registered.
CATEGORYINFO catinfo;
catinfo.catid = catid;
catinfo.lcid = 0x0409 ; // english
size_t len;
// Make sure the provided description is not too long.
// Only copy the first 127 characters if it is.
// The second parameter of StringCchLength is the maximum
// number of characters that may be read into catDescription.
// There must be room for a NULL-terminator. The third parameter
// contains the number of characters excluding the NULL-terminator.
hr = StringCchLengthW(catDescription, STRSAFE_MAX_CCH, &len);
if (SUCCEEDED(hr))
{
if (len>127)
{
len = 127;
}
}
else
{
// TODO: Write an error handler;
}
// The second parameter of StringCchCopy is 128 because you need
// room for a NULL-terminator.
hr = StringCchCopyW(catinfo.szDescription, len + 1, catDescription);
// Make sure the description is null terminated.
catinfo.szDescription[len + 1] = '\0';
hr = pcr->RegisterCategories(1, &catinfo);
pcr->Release();
return hr;
}
// HRESULT RegisterCLSIDInCategory -
// Register your component categories information
HRESULT RegisterCLSIDInCategory(REFCLSID clsid, CATID catid)
{
// Register your component categories information.
ICatRegister *pcr = NULL ;
HRESULT hr = S_OK ;
hr = CoCreateInstance(CLSID_StdComponentCategoriesMgr,
NULL, CLSCTX_INPROC_SERVER, IID_ICatRegister, (void**)&pcr);
if (SUCCEEDED(hr))
{
// Register this category as being "implemented" by the class.
CATID rgcatid[1] ;
rgcatid[0] = catid;
hr = pcr->RegisterClassImplCategories(clsid, 1, rgcatid);
}
if (pcr != NULL)
pcr->Release();
return hr;
}
// HRESULT UnRegisterCLSIDInCategory - Remove entries from the registry
HRESULT UnRegisterCLSIDInCategory(REFCLSID clsid, CATID catid)
{
ICatRegister *pcr = NULL ;
HRESULT hr = S_OK ;
hr = CoCreateInstance(CLSID_StdComponentCategoriesMgr,
NULL, CLSCTX_INPROC_SERVER, IID_ICatRegister, (void**)&pcr);
if (SUCCEEDED(hr))
{
// Unregister this category as being "implemented" by the class.
CATID rgcatid[1] ;
rgcatid[0] = catid;
hr = pcr->UnRegisterClassImplCategories(clsid, 1, rgcatid);
}
if (pcr != NULL)
pcr->Release();
return hr;
}
// CP3DActiveXApp::InitInstance - DLL initialization
BOOL CP3DActiveXApp::InitInstance()
{
BOOL bInit = COleControlModule::InitInstance();
if (bInit)
{
// TODO: Add your own module initialization code here.
// Seed the lame random number generator in rand(); we use it to select
// a mirror for downloading.
srand((unsigned int)time(NULL));
}
return bInit;
}
// CP3DActiveXApp::ExitInstance - DLL termination
int CP3DActiveXApp::ExitInstance()
{
// TODO: Add your own module termination code here.
return COleControlModule::ExitInstance();
}
// DllRegisterServer - Adds entries to the system registry
STDAPI DllRegisterServer(void)
{
HRESULT hr; // HResult used by Safety Functions
AFX_MANAGE_STATE(_afxModuleAddrThis);
if (!AfxOleRegisterTypeLib(AfxGetInstanceHandle(), _tlid))
return ResultFromScode(SELFREG_E_TYPELIB);
if (!COleObjectFactoryEx::UpdateRegistryAll(TRUE))
return ResultFromScode(SELFREG_E_CLASS);
// Mark the control as safe for initializing.
hr = CreateComponentCategory(CATID_SafeForInitializing,
L"Controls safely initializable from persistent data!");
if (FAILED(hr))
return hr;
hr = RegisterCLSIDInCategory(CLSID_SafeItem,
CATID_SafeForInitializing);
if (FAILED(hr))
return hr;
// Mark the control as safe for scripting.
hr = CreateComponentCategory(CATID_SafeForScripting,
L"Controls safely scriptable!");
if (FAILED(hr))
return hr;
hr = RegisterCLSIDInCategory(CLSID_SafeItem,
CATID_SafeForScripting);
if (FAILED(hr))
return hr;
return NOERROR;
}
// DllUnregisterServer - Removes entries from the system registry
STDAPI DllUnregisterServer(void)
{
HRESULT hr; // HResult used by Safety Functions
AFX_MANAGE_STATE(_afxModuleAddrThis);
// Remove entries from the registry.
hr = UnRegisterCLSIDInCategory(CLSID_SafeItem,
CATID_SafeForInitializing);
if (FAILED(hr))
return hr;
hr = UnRegisterCLSIDInCategory(CLSID_SafeItem,
CATID_SafeForScripting);
if (FAILED(hr))
return hr;
if (!AfxOleUnregisterTypeLib(_tlid, _wVerMajor, _wVerMinor))
return ResultFromScode(SELFREG_E_TYPELIB);
if (!COleObjectFactoryEx::UpdateRegistryAll(FALSE))
return ResultFromScode(SELFREG_E_CLASS);
return NOERROR;
}
| 24.093985 | 91 | 0.672804 | cmarshall108 |
c5c796a5b36eb9ce01c779f301c5b4d4c6192dc1 | 9,705 | cpp | C++ | Mocap/src/publisher.cpp | robinzhoucmu/MLab_EXP | 4d86db9438203f51c4368e5b886def5c402955f3 | [
"Apache-2.0"
] | 2 | 2016-06-16T00:46:02.000Z | 2018-12-02T16:17:59.000Z | Mocap/src/publisher.cpp | robinzhoucmu/MLab_EXP | 4d86db9438203f51c4368e5b886def5c402955f3 | [
"Apache-2.0"
] | null | null | null | Mocap/src/publisher.cpp | robinzhoucmu/MLab_EXP | 4d86db9438203f51c4368e5b886def5c402955f3 | [
"Apache-2.0"
] | null | null | null | #include "publisher.h"
MocapPublisher::MocapPublisher(ros::NodeHandle *n) {
nodeHandle = n;
// Set as default frequency.
SetPublishFrequency(Globals::kPublishFreq);
// Without given transformation: set transformation (from robot base to mocap frame)
// as identity. Therefore mocap just return in its (unknown/uncalibrated) native
// coordinate frame.
double pose[7] = {0,0,0,1,0,0,0};
setMocapTransformation(pose);
}
MocapPublisher::~MocapPublisher() {
handle_mocap_GetMocapFrame.shutdown();
handle_mocap_SetMocapTransformation.shutdown();
}
void MocapPublisher::SetPublishFrequency(int _pub_freq_hz) {
pub_freq_hz = _pub_freq_hz;
}
void MocapPublisher::EstablishCommunications(int argc, char* argv[]) {
// Sockets Initialization.
sdCommand = -1;
sdData = -1;
// Catch ctrl-c and terminate gracefully.
signal(SIGINT, Globals::Terminate);
// Set addresses
Globals::ReadOpts(argc, argv);
// Create sockets
sdCommand = NatNet::createCommandSocket( Globals::localAddress );
sdData = NatNet::createDataSocket( Globals::localAddress );
// Ensure that the socket creation was successful
assert(sdCommand != -1);
assert(sdData != -1);
// Create Listeners with the sockets.
CreateListener();
}
void MocapPublisher::CreateListener() {
// Version number of the NatNet protocol, as reported by the server.
unsigned char natNetMajor;
unsigned char natNetMinor;
// Use this socket address to send commands to the server.
// Default NatNet command port is 1510.
struct sockaddr_in serverCommands =
NatNet::createAddress(Globals::serverAddress, NatNet::commandPort);
printf("About to start command listener\n");
// Start the CommandListener in a new thread.
commandListener = new CommandListener(sdCommand);
commandListener->start();
printf("cmd listener started. about to ping\n");
// Send a ping packet to the server so that it sends us the NatNet version
// in its response to commandListener.
NatNetPacket ping = NatNetPacket::pingPacket();
ping.send(sdCommand, serverCommands);
printf("ping sent. waiting...\n");
// Wait here for ping response to give us the NatNet version.
commandListener->getNatNetVersion(&natNetMajor, &natNetMinor);
printf("ping recieved. Major = %u, Minor = %u \n",natNetMajor,natNetMinor);
// Start up a FrameListener in a new thread.
frameListener = new FrameListener(sdData, natNetMajor, natNetMinor);
frameListener->start();
}
void MocapPublisher::ExtractPoseMsg(const MocapFrame& mframe,
Mocap::mocap_frame* msg) {
// See NatNet.h file for relevant data structures of MocapFrame.
// Extract unidenfied markers (e.g., single calibration marker).
const int num_uid_markers = mframe.unIdMarkers().size();
msg->uid_markers.markers.clear();
for (int i = 0; i < num_uid_markers; ++i) {
const Point3f& pt = mframe.unIdMarkers()[i];
geometry_msgs::Point uid_marker_pt;
uid_marker_pt.x = k_unit * pt.x;
uid_marker_pt.y = k_unit * pt.y;
uid_marker_pt.z = k_unit * pt.z;
// Transform the point.
transformPoint(&uid_marker_pt);
msg->uid_markers.markers.push_back(uid_marker_pt);
}
// Extract tracked body/ies poses and corresponding identified marker sets.
const int num_bodies = mframe.rigidBodies().size();
msg->id_marker_sets.clear();
msg->body_poses.clear();
for (int i = 0; i < num_bodies; i++) {
const RigidBody& body = mframe.rigidBodies()[i];
geometry_msgs::Pose pose;
// Copy x,y,z.
pose.position.x = k_unit * body.location().x;
pose.position.y = k_unit * body.location().y;
pose.position.z = k_unit * body.location().z;
// Copy Quaternion.
pose.orientation.x = body.orientation().qx;
pose.orientation.y = body.orientation().qy;
pose.orientation.z = body.orientation().qz;
pose.orientation.w = body.orientation().qw;
// Transform the pose.
transformPose(&pose);
msg->body_poses.push_back(pose);
msg->header.stamp = ros::Time::now();
const int marker_set_size = body.markers().size();
Mocap::marker_set id_marker_set;
for (int j = 0; j < marker_set_size; ++j) {
const Point3f& pt = body.markers()[j];
geometry_msgs::Point id_marker_pt;
id_marker_pt.x = k_unit * pt.x;
id_marker_pt.y = k_unit * pt.y;
id_marker_pt.z = k_unit * pt.z;
// Transform the point.
transformPoint(&id_marker_pt);
id_marker_set.markers.push_back(id_marker_pt);
}
msg->id_marker_sets.push_back(id_marker_set);
}
}
void MocapPublisher::PublishToTopic() {
// Set the publiser queue size.
const int kQueueSize = 100;
// Set the publishing frequency.
ros::Rate loop_rate(pub_freq_hz);
ros::Publisher mocapPub = nodeHandle->advertise<Mocap::mocap_frame>("Mocap", kQueueSize);
unsigned int rosMsgCount = 0;
Globals::run = true;
while( ros::ok() && Globals::run) {
// Try to get a new frame from the listener.
bool valid;
MocapFrame frame(frameListener->pop(&valid).first);
// Quit if the listener has no more frames.
if(!valid) {
// fprintf(stderr,"No valid frame available \n");
}
else {
// std::cout << frame << std::endl;
// Extract rigid bodies and publish to ROS.
Mocap::mocap_frame msg;
ExtractPoseMsg(frame, &msg);
//std::cout << ros::Time::now() << std::endl;
mocapPub.publish(msg);
}
// All callbacks/services will be processed here.
ros::spinOnce();
loop_rate.sleep();
rosMsgCount++;
}
printf("after ROS loop: ros::ok = %i, Globals::run = %i \n",ros::ok(),Globals::run);
// Wait for threads to finish.
frameListener->stop();
commandListener->stop();
frameListener->join();
commandListener->join();
// Epilogue (Close sockets)
close(sdData);
close(sdCommand);
// Close topic.
mocapPub.shutdown();
}
void MocapPublisher::AdvertiseServices() {
handle_mocap_GetMocapFrame =
nodeHandle->advertiseService("mocap_GetMocapFrame",
&MocapPublisher::GetMocapFrame, this);
handle_mocap_GetMocapTransformation =
nodeHandle->advertiseService("mocap_GetMocapTransformation",
&MocapPublisher::GetMocapTransformation, this);
handle_mocap_SetMocapTransformation =
nodeHandle->advertiseService("mocap_SetMocapTransformation",
&MocapPublisher::SetMocapTransformation, this);
}
bool MocapPublisher::GetMocapFrame(Mocap::mocap_GetMocapFrame::Request& req,
Mocap::mocap_GetMocapFrame::Response& res) {
double start_secs = ros::Time::now().toSec();
bool flag_tle = false;
bool flag_captured_frame = false;
while (!flag_tle && !flag_captured_frame) {
double cur_secs = ros::Time::now().toSec();
if (cur_secs - start_secs > k_max_wait) {
flag_tle = true;
}
// Try to get a new frame from the listener.
bool valid;
MocapFrame frame(frameListener->pop(&valid).first);
// Quit if the listener has no more frames.
if(!valid) {
fprintf(stderr,"No valid frame available \n");
}
else {
// Extract rigid bodies and publish to ROS.
Mocap::mocap_frame msg;
ExtractPoseMsg(frame, &msg);
res.mf = msg;
flag_captured_frame = true;
}
}
if (flag_captured_frame) {
res.msg = "OK.";
res.ret = 1;
return true;
} else {
res.msg = "Time limit exceeded.";
res.ret = 1;
return false;
}
}
bool MocapPublisher::GetMocapTransformation(Mocap::mocap_GetMocapTransformation::Request& req,
Mocap::mocap_GetMocapTransformation::Response& res) {
Vec tf_trans = tf_mocap.getTranslation();
res.x = tf_trans[0];
res.y = tf_trans[1];
res.z = tf_trans[2];
Quaternion tf_quat = tf_mocap.getQuaternion();
res.q0 = tf_quat[0];
res.qx = tf_quat[1];
res.qy = tf_quat[2];
res.qz = tf_quat[3];
res.msg = "Ok.";
res.ret = 1;
return true;
}
// TODO: the return false logic.
bool MocapPublisher::SetMocapTransformation(Mocap::mocap_SetMocapTransformation::Request& req,
Mocap::mocap_SetMocapTransformation::Response& res) {
double pose[7];
pose[0] = req.x;
pose[1] = req.y;
pose[2] = req.z;
pose[3] = req.q0;
pose[4] = req.qx;
pose[5] = req.qy;
pose[6] = req.qz;
setMocapTransformation(pose);
res.msg = "OK.";
res.ret = 1;
return true;
}
void MocapPublisher::setMocapTransformation(double pose[7]) {
tf_mocap = HomogTransf(pose);
}
void MocapPublisher::transformPoint(geometry_msgs::Point* pt) {
double p[3];
p[0] = pt->x;
p[1] = pt->y;
p[2] = pt->z;
Vec vec_p(p, 3);
vec_p = tf_mocap * vec_p;
pt->x = vec_p[0];
pt->y = vec_p[1];
pt->z = vec_p[2];
}
void MocapPublisher::transformPose(geometry_msgs::Pose* pose) {
geometry_msgs::Point& trans = pose->position;
geometry_msgs::Quaternion& quat = pose->orientation;
// Todo(Jiaji): Note q.w comes first here, in matVec q.w is the 4th element.
double tmp_pose[7] = {trans.x, trans.y, trans.z,
quat.w, quat.x, quat.y, quat.z};
HomogTransf cur_tf = HomogTransf(tmp_pose);
HomogTransf tf = tf_mocap * cur_tf;
Vec tf_trans = tf.getTranslation();
trans.x = tf_trans[0];
trans.y = tf_trans[1];
trans.z = tf_trans[2];
Quaternion tf_quat = tf.getQuaternion();
quat.x = tf_quat.x();
quat.y = tf_quat.y();
quat.z = tf_quat.z();
quat.w = tf_quat.w();
}
// Main function for the Mocap Node.
// The Mocap node is publishing Mocap frames to the Mocap Topic.
int main(int argc, char* argv[]) {
// Initialize the ROS node.
ros::init(argc, argv, "Mocap");
ros::NodeHandle node;
MocapPublisher mocap_pub(&node);
mocap_pub.EstablishCommunications(argc, argv);
mocap_pub.AdvertiseServices();
mocap_pub.PublishToTopic();
}
| 30.615142 | 95 | 0.678001 | robinzhoucmu |
c5c990ae5523ab1cf6ccf7db48a26f74d3f5afb6 | 1,222 | hpp | C++ | include/hazeRemove.hpp | norishigefukushima/OpenCP | 63090131ec975e834f85b04e84ec29b2893845b2 | [
"BSD-3-Clause"
] | 137 | 2015-03-27T07:11:19.000Z | 2022-03-30T05:58:22.000Z | include/hazeRemove.hpp | Pandinosaurus/OpenCP | a5234ed531c610d7944fa14d42f7320442ea34a1 | [
"BSD-3-Clause"
] | 2 | 2016-05-18T06:33:16.000Z | 2016-07-11T17:39:17.000Z | include/hazeRemove.hpp | Pandinosaurus/OpenCP | a5234ed531c610d7944fa14d42f7320442ea34a1 | [
"BSD-3-Clause"
] | 43 | 2015-02-20T15:34:25.000Z | 2022-01-27T14:59:37.000Z | #pragma once
#include "common.hpp"
namespace cp
{
class CP_EXPORT HazeRemove
{
cv::Size size;
cv::Mat dark;
std::vector<cv::Mat> minvalue;
cv::Mat tmap;
cv::Scalar A;
void darkChannel(cv::Mat& src, int r);
void getAtmosphericLight(cv::Mat& srcImage, double topPercent = 0.1);
void getTransmissionMap(float omega = 0.95f);
void removeHaze(cv::Mat& src, cv::Mat& trans, cv::Scalar v, cv::Mat& dest, float clip = 0.3f);
public:
HazeRemove();
~HazeRemove();
void getAtmosphericLightImage(cv::Mat& dest);
void showTransmissionMap(cv::Mat& dest, bool isPseudoColor = false);
void showDarkChannel(cv::Mat& dest, bool isPseudoColor = false);
void removeFastGlobalSmootherFilter(cv::Mat& src, cv::Mat& dest, const int r_dark, const double top_rate, const double lambda, const double sigma_color, const double lambda_attenuation, const int iteration);
void removeGuidedFilter(cv::Mat& src, cv::Mat& dest, const int r_dark, const double toprate, const int r_joint, const double e_joint);
void operator() (cv::Mat& src, cv::Mat& dest, const int r_dark, const double toprate, const int r_joint, const double e_joint);
void gui(cv::Mat& src, std::string wname = "hazeRemove");
};
} | 34.914286 | 209 | 0.713584 | norishigefukushima |
c5cbb17a63e2cba61b08f9e02c106799e95a767d | 1,276 | cpp | C++ | tests/parse/iterator_test.cpp | BastianBlokland/novus | 3b984c36855aa84d6746c14ff7e294ab7d9c1575 | [
"MIT"
] | 14 | 2020-04-14T17:00:56.000Z | 2021-08-30T08:29:26.000Z | tests/parse/iterator_test.cpp | BastianBlokland/novus | 3b984c36855aa84d6746c14ff7e294ab7d9c1575 | [
"MIT"
] | 27 | 2020-12-27T16:00:44.000Z | 2021-08-01T13:12:14.000Z | tests/parse/iterator_test.cpp | BastianBlokland/novus | 3b984c36855aa84d6746c14ff7e294ab7d9c1575 | [
"MIT"
] | 1 | 2020-05-29T18:33:37.000Z | 2020-05-29T18:33:37.000Z | #include "catch2/catch.hpp"
#include "lex/lexer.hpp"
#include "parse/parser.hpp"
#include <string>
namespace parse {
TEST_CASE("[parse] Iterating the parser", "parse") {
const std::string input = "print(1) print(x * y)";
SECTION("Range for") {
auto lexer = lex::Lexer{input.begin(), input.end()};
auto parser = parse::Parser{lexer.begin(), lexer.end()};
std::vector<NodePtr> nodes;
for (auto&& node : parser) {
nodes.push_back(std::move(node));
}
REQUIRE(nodes.size() == 2);
}
SECTION("While loop") {
auto lexer = lex::Lexer{input.begin(), input.end()};
auto parser = parse::Parser{lexer.begin(), lexer.end()};
auto i = 0;
while (parser.next() != nullptr) {
++i;
}
REQUIRE(i == 2);
}
SECTION("Iterator") {
auto lexer = lex::Lexer{input.begin(), input.end()};
auto parser = parse::Parser{lexer.begin(), lexer.end()};
auto i = 0;
auto nodeItr = parser.begin();
auto endItr = parser.end();
for (; nodeItr != endItr; ++nodeItr) {
i++;
}
REQUIRE(i == 2);
}
SECTION("ParseAll") {
auto lexer = lex::Lexer{input.begin(), input.end()};
auto vec = parseAll(lexer.begin(), lexer.end());
REQUIRE(vec.size() == 2);
}
}
} // namespace parse
| 23.2 | 60 | 0.575235 | BastianBlokland |
c5cbc32e477982145511d6a3cf13caf960799809 | 8,066 | cpp | C++ | AROGSBP/ARGOS_BP_SW/VSCODE/CameraDSLR/photo.cpp | EIDOSDATA/Argos_Main_Series | 2d6e4839afa7bd05d3b87fb530481bdf5eeac31a | [
"Unlicense"
] | null | null | null | AROGSBP/ARGOS_BP_SW/VSCODE/CameraDSLR/photo.cpp | EIDOSDATA/Argos_Main_Series | 2d6e4839afa7bd05d3b87fb530481bdf5eeac31a | [
"Unlicense"
] | null | null | null | AROGSBP/ARGOS_BP_SW/VSCODE/CameraDSLR/photo.cpp | EIDOSDATA/Argos_Main_Series | 2d6e4839afa7bd05d3b87fb530481bdf5eeac31a | [
"Unlicense"
] | null | null | null | #include "photo.h"
#include <iostream>
#include <unistd.h>
static const char* config_texts[CONFIG_TYPE]=
{
"f-number",
"shutterspeed2",
"iso",
};
int photo::threeShootWait(CameraFilePath *path, int port_num, Camera *camera, GPContext *context)
{
CameraEventType eventtype;
struct timeval start, temp;
void *eventdata = NULL;
int startflag = 0;
//NEED: wait other camera starting..
gettimeofday(&start, nullptr);
do
{
int result = gp_camera_wait_for_event(camera, 200, &eventtype, &eventdata, context);
if (result < 0)
{
perror("wait_for_event error in two shoot");
return 1;
}
switch (eventtype)
{
case GP_EVENT_TIMEOUT:
case GP_EVENT_CAPTURE_COMPLETE:
case GP_EVENT_UNKNOWN:
case GP_EVENT_FOLDER_ADDED:
break;
case GP_EVENT_FILE_ADDED:
strcpy(path->folder, ((CameraFilePath *)eventdata)->folder);
strcpy(path->name, ((CameraFilePath *)eventdata)->name);
startflag = 1;
break;
}
if(eventdata != nullptr)
{
free(eventdata);
eventdata = nullptr;
}
gettimeofday(&temp, nullptr);
} while (temp.tv_sec - start.tv_sec < 9);
if(startflag == 0)
{
std::cout << "Can't receive file added event.(cam: " << port_num << ")" << std::endl;
return 1;
}
return 0;
}
int photo::cameraClose(Camera *camera, GPContext *context)
{
if (gp_camera_exit(camera, context))
{
perror("camera exit error.\n");
return 1;
}
if (gp_camera_unref(camera))
{
perror("camera free error.\n");
return 1;
}
gp_context_unref(context);
return 0;
}
int photo::downloadFileFromCamera(CameraFile *file, const CameraFilePath *path, CameraFileType type, Camera *camera, GPContext *context)
{
int result = gp_file_clean(file); // clean file
if(result)
{
std::cout << "download_file_from_camera(file clean): " << gp_result_as_string(result) << std::endl;
return 1;
}
result = gp_camera_file_get(camera, path->folder, path->name, type, file, context); // get file
if(result)
{
const char* data;
unsigned long int size;
result = gp_file_get_data_and_size(file, &data, &size); // 사진 받기에 에러가 떳지만, 사진 내용이 있으면 저장하고 계속(??)
std::cout << "result: ," << result << " data size: " << size << std::endl; // 왠지 모르게 에러가 나지만 사진이 괜찮은 경우가 많았음(??)
if(size > 0)
{
std::cout << "file_get error but file is valid. downloading continue.." << std::endl;
return 0;
}
std::cout << "download_file_from_camera(file get): " << gp_result_as_string(result) << std::endl;
return 1;
}
return 0;
}
int photo::presetConfig(const char *name, const void *value, Config_Kind kind, CameraWidget *window, Camera *camera, GPContext *context)
{
CameraWidget* widget;
int result = gp_widget_get_child_by_name(window, name, &widget);
if (result)
{
std::cout << "wiget_get_child_by_name error. " << gp_result_as_string(result) << std::endl;
return 1;
}
if( kind == CONFIG_BY_TEXT)
{
result = gp_widget_set_value(widget, (char*)value);
if (result)
{
std::cout << "gp_widget_set_value error. " << gp_result_as_string(result) << std::endl;
return 1;
}
result = gp_camera_set_config(camera,window,context); //set config
if(result)
{
std::cout << name << "-"<< (char*)value << " config presetting error. " << gp_result_as_string(result) << std::endl;
return 1;
}
}
else if(kind == CONFIG_BY_INTEGER)
{
const char* choice;
// printf("Integer: %d\n", *(int*)value);
result = gp_widget_get_choice(widget, *(int*)value, &choice);
if(result){
std::cout << "gp_widget_get_choice error. " << gp_result_as_string(result) << std::endl;
return 1;
}
result = gp_widget_set_value(widget, (char*)choice);
if (result)
{
std::cout << "gp_widget_set_value error. " << gp_result_as_string(result) << std::endl;
return 1;
}
result = gp_camera_set_config(camera,window,context); //set config.
if(result)
{
std::cout << name << "-"<< choice << " config presetting error. " << gp_result_as_string(result) << std::endl;
return 1;
}
}
// gp_widget_unref(widget);
return 0;
}
int photo::initTextConfig(TextConfig *text_config, int config_num, int preset, CameraWidget *window)
{
text_config->name = config_texts[config_num];
int result = gp_widget_get_child_by_name(window, text_config->name, &text_config->widget);
if (result)
{
std::cout << "wiget_get_child_by_name error. " << gp_result_as_string(result) << std::endl;
return 1;
}
result = gp_widget_count_choices(text_config->widget);
if (result < 0)
{
std::cout << "wiget_count choices error. " << gp_result_as_string(result) << std::endl;
return 1;
}
text_config->n = result;
text_config->choices= (const char**)malloc(sizeof(char*)*text_config->n);
// (*choices)[result] = NULL;
const char* tmp;
for(int i=0; i<text_config->n; i++)
{
result = gp_widget_get_choice(text_config->widget,i,&tmp);
if (result)
{
std::cout << "wiget_get_choices error. " << gp_result_as_string(result) << std::endl;
break;
}
text_config->choices[i] = tmp;
}
// if (preset >= text_config->n)
// {
// std::cout << "invalid preset number" << std::endl;
// return 1;
// }
// else
// {
// result = gp_widget_set_value(text_config->widget,text_config->choices[preset]);
// if (result)
// {
// std::cout << "widget set value error: " << gp_result_as_string(result) << std::endl;
// return 1;
// }
// }
return 0;
}
int photo::portInfoListNew(GPPortInfoList **portinfolist)
{
int ret = gp_port_info_list_new(portinfolist);
if (ret < GP_OK) return ret;
ret = gp_port_info_list_load(*portinfolist);
if (ret < 0) return ret;
ret = gp_port_info_list_count(*portinfolist);
if (ret < 0) return ret;
return 0;
}
int photo::abilitiesListNew(CameraAbilitiesList **abilities, GPContext *context)
{
int ret = gp_abilities_list_new(abilities);
if (ret < GP_OK) return ret;
ret = gp_abilities_list_load(*abilities, context);
if (ret < GP_OK) return ret;
return 0;
}
int photo::openCamera(Camera **camera, const char *model, const char *port, GPContext *context, GPPortInfoList *portinfolist, CameraAbilitiesList *abilities)
{
CameraAbilities CA;
GPPortInfo GPI;
int ret = gp_camera_new(camera);
if (ret < GP_OK) return ret;
int m = gp_abilities_list_lookup_model(abilities, model);
if (m < GP_OK) return ret;
ret = gp_abilities_list_get_abilities(abilities, m, &CA);
if (ret < GP_OK) return ret;
ret = gp_camera_set_abilities(*camera, CA);
if (ret < GP_OK) return ret;
int p = gp_port_info_list_lookup_path(portinfolist, port);
switch (p)
{
case GP_ERROR_UNKNOWN_PORT:
fprintf(stderr,
"The port you specified "
"('%s') can not be found. Please "
"specify one of the ports found by "
"'gphoto2 --list-ports' and make "
"sure the spelling is correct "
"(i.e. with prefix 'serial:' or 'usb:').",
port);
break;
default:
break;
}
if (p < GP_OK) return p;
ret = gp_port_info_list_get_info(portinfolist, p, &GPI);
if (ret < GP_OK) return ret;
ret = gp_camera_set_port_info(*camera, GPI);
if (ret < GP_OK) return ret;
return GP_OK;
}
| 27.435374 | 157 | 0.5879 | EIDOSDATA |
c5d10c43cd5ba09bebf30aacd2335f9a7e1caa99 | 303 | hpp | C++ | recursive/aliases.hpp | e-Sharp/cpp_general_recusive_functions | f94a1d0385915988f41d3245588bdc6df7af8dd5 | [
"MIT"
] | null | null | null | recursive/aliases.hpp | e-Sharp/cpp_general_recusive_functions | f94a1d0385915988f41d3245588bdc6df7af8dd5 | [
"MIT"
] | null | null | null | recursive/aliases.hpp | e-Sharp/cpp_general_recusive_functions | f94a1d0385915988f41d3245588bdc6df7af8dd5 | [
"MIT"
] | null | null | null | #pragma once
#include <array> // std::array
#include <cstdlib> // std::size_t
#include <span> // std::span
namespace rec {
using nat = std::size_t;
template<std::size_t Size>
using arr = std::array<nat, Size>;
template<std::size_t Size>
using span = std::span<const nat, Size>;
} // namespace rec
| 16.833333 | 40 | 0.676568 | e-Sharp |
c5d28e9f588915161d2fb455c60248ad65eb2287 | 4,453 | cc | C++ | build/X86_MESI_Two_Level/mem/protocol/L2Cache_State.cc | hoho20000000/gem5-fy | b59f6feed22896d6752331652c4d8a41a4ca4435 | [
"BSD-3-Clause"
] | null | null | null | build/X86_MESI_Two_Level/mem/protocol/L2Cache_State.cc | hoho20000000/gem5-fy | b59f6feed22896d6752331652c4d8a41a4ca4435 | [
"BSD-3-Clause"
] | 1 | 2020-08-20T05:53:30.000Z | 2020-08-20T05:53:30.000Z | build/X86_MESI_Two_Level/mem/protocol/L2Cache_State.cc | hoho20000000/gem5-fy | b59f6feed22896d6752331652c4d8a41a4ca4435 | [
"BSD-3-Clause"
] | null | null | null | /** \file L2Cache_State.hh
*
* Auto generated C++ code started by /home/hongyu/gem5-fy/src/mem/slicc/symbols/Type.py:555
*/
#include <cassert>
#include <iostream>
#include <string>
#include "base/misc.hh"
#include "mem/protocol/L2Cache_State.hh"
using namespace std;
// Code to convert the current state to an access permission
AccessPermission L2Cache_State_to_permission(const L2Cache_State& obj)
{
switch(obj) {
case L2Cache_State_NP:
return AccessPermission_Invalid;
case L2Cache_State_SS:
return AccessPermission_Read_Only;
case L2Cache_State_M:
return AccessPermission_Read_Write;
case L2Cache_State_MT:
return AccessPermission_Maybe_Stale;
case L2Cache_State_M_I:
return AccessPermission_Busy;
case L2Cache_State_MT_I:
return AccessPermission_Busy;
case L2Cache_State_MCT_I:
return AccessPermission_Busy;
case L2Cache_State_I_I:
return AccessPermission_Busy;
case L2Cache_State_S_I:
return AccessPermission_Busy;
case L2Cache_State_ISS:
return AccessPermission_Busy;
case L2Cache_State_IS:
return AccessPermission_Busy;
case L2Cache_State_IM:
return AccessPermission_Busy;
case L2Cache_State_SS_MB:
return AccessPermission_Busy;
case L2Cache_State_MT_MB:
return AccessPermission_Busy;
case L2Cache_State_MT_IIB:
return AccessPermission_Busy;
case L2Cache_State_MT_IB:
return AccessPermission_Busy;
case L2Cache_State_MT_SB:
return AccessPermission_Busy;
default:
panic("Unknown state access permission converstion for L2Cache_State");
}
}
// Code for output operator
ostream&
operator<<(ostream& out, const L2Cache_State& obj)
{
out << L2Cache_State_to_string(obj);
out << flush;
return out;
}
// Code to convert state to a string
string
L2Cache_State_to_string(const L2Cache_State& obj)
{
switch(obj) {
case L2Cache_State_NP:
return "NP";
case L2Cache_State_SS:
return "SS";
case L2Cache_State_M:
return "M";
case L2Cache_State_MT:
return "MT";
case L2Cache_State_M_I:
return "M_I";
case L2Cache_State_MT_I:
return "MT_I";
case L2Cache_State_MCT_I:
return "MCT_I";
case L2Cache_State_I_I:
return "I_I";
case L2Cache_State_S_I:
return "S_I";
case L2Cache_State_ISS:
return "ISS";
case L2Cache_State_IS:
return "IS";
case L2Cache_State_IM:
return "IM";
case L2Cache_State_SS_MB:
return "SS_MB";
case L2Cache_State_MT_MB:
return "MT_MB";
case L2Cache_State_MT_IIB:
return "MT_IIB";
case L2Cache_State_MT_IB:
return "MT_IB";
case L2Cache_State_MT_SB:
return "MT_SB";
default:
panic("Invalid range for type L2Cache_State");
}
}
// Code to convert from a string to the enumeration
L2Cache_State
string_to_L2Cache_State(const string& str)
{
if (str == "NP") {
return L2Cache_State_NP;
} else if (str == "SS") {
return L2Cache_State_SS;
} else if (str == "M") {
return L2Cache_State_M;
} else if (str == "MT") {
return L2Cache_State_MT;
} else if (str == "M_I") {
return L2Cache_State_M_I;
} else if (str == "MT_I") {
return L2Cache_State_MT_I;
} else if (str == "MCT_I") {
return L2Cache_State_MCT_I;
} else if (str == "I_I") {
return L2Cache_State_I_I;
} else if (str == "S_I") {
return L2Cache_State_S_I;
} else if (str == "ISS") {
return L2Cache_State_ISS;
} else if (str == "IS") {
return L2Cache_State_IS;
} else if (str == "IM") {
return L2Cache_State_IM;
} else if (str == "SS_MB") {
return L2Cache_State_SS_MB;
} else if (str == "MT_MB") {
return L2Cache_State_MT_MB;
} else if (str == "MT_IIB") {
return L2Cache_State_MT_IIB;
} else if (str == "MT_IB") {
return L2Cache_State_MT_IB;
} else if (str == "MT_SB") {
return L2Cache_State_MT_SB;
} else {
panic("Invalid string conversion for %s, type L2Cache_State", str);
}
}
// Code to increment an enumeration type
L2Cache_State&
operator++(L2Cache_State& e)
{
assert(e < L2Cache_State_NUM);
return e = L2Cache_State(e+1);
}
| 27.658385 | 92 | 0.642488 | hoho20000000 |
c5d4c2edc312dc7e6631847f5322ac62dd912bf5 | 2,917 | cpp | C++ | bscc/tools/bgbhex2_t0.cpp | cr88192/bgbtech_engine | 03869a92fbf3197dd176d311f3b917f4f4e88d1a | [
"MIT"
] | 1 | 2019-07-02T22:53:52.000Z | 2019-07-02T22:53:52.000Z | bscc/tools/bgbhex2_t0.cpp | cr88192/bgbtech_engine | 03869a92fbf3197dd176d311f3b917f4f4e88d1a | [
"MIT"
] | 5 | 2015-11-17T05:45:50.000Z | 2015-11-26T18:36:51.000Z | bscc/tools/bgbhex2_t0.cpp | cr88192/bgbtech_engine | 03869a92fbf3197dd176d311f3b917f4f4e88d1a | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
int main(int argc, char *argv[])
{
long lc, offs, ofs, len, i, j, c;
FILE *in;
unsigned char buf[16], *s;
in=NULL;
offs=0;
len=-1;
for(i=1;i<argc;i++)
{
// printf("Arg %d: %s\n", i, argv[i]);
if(argv[i][0]=='-')
{
switch(argv[i][1])
{
case 'o':
ofs=atoi(argv[i+1]);
i++;
break;
case 'l':
len=atoi(argv[i+1]);
i++;
break;
default:
break;
}
continue;
}
if(!in)in=fopen(argv[i],"r+b");
}
if(!in)
{
printf("no input.\n");
exit(-1);
}
#if 0
fcntl(0, F_SETFL, fcntl (0, F_GETFL, 0) & ~FNDELAY);
fcntl(0, F_SETFL, fcntl (0, F_GETFL, 0) | FNDELAY);
#endif
while(1)
{
fseek(in, offs, 0);
ofs=offs;
for(i=0; i<23; i++)
{
lc=fread(&buf, 1, ((16<len)||(len==-1))?16:len, in);
printf("%08X", ofs);
for(j=0;j<lc;j++)
{
if(!(j%4))printf(" ");
printf("%02X ", buf[j]);
}
for(;j<16;j++)
{
if(!(j%4))printf(" ");
printf(" ");
}
for(j=0;j<lc;j++)
{
if(buf[j]<' ')buf[j]='~';
if(buf[j]>='\x7f')buf[j]='~';
printf("%c", buf[j]);
}
ofs+=16;
printf("\n");
if(len>0)
{
len-=lc;
if(len<=0)break;
}
}
l0:
printf(": ");
fgets((char *)(&buf), 15, stdin);
switch(buf[0])
{
case '\n':
offs+=16*23;
break;
case 'h':
printf("\\n next page\n");
printf("-, w back 16 bytes\n");
printf("s forward 16 bytes\n");
printf("p, a prev page\n");
printf("n, d next page\n");
printf("q quit\n");
printf("g, e <adr> goto addr\n");
printf("t <adr> <val> set val at addr\n");
goto l0;
break;
case '-':
case 'w':
offs-=16;
break;
case 's':
offs+=16;
break;
case 'p':
case 'a':
offs-=16*23;
break;
case 'n':
case 'd':
offs+=16*23;
break;
case 'q':
fclose(in);
exit(0);
break;
case 'g':
case 'e':
s=buf;
s++;
j=0;
while(*s<=' ')s++;
while(*s>' ')
{
j<<=4;
if(*s>='0' && *s<='9')j+=*s-'0';
if(*s>='A' && *s<='F')j+=*s-'A'+10;
if(*s>='a' && *s<='f')j+=*s-'a'+10;
s++;
}
offs=j;
i=strlen((char *)(&buf))-1;
break;
case 't':
s=buf;
s++;
j=0;
while(*s<=' ')s++;
while(*s>' ')
{
j<<=4;
if(*s>='0' && *s<='9')j+=*s-'0';
if(*s>='A' && *s<='F')j+=*s-'A'+10;
if(*s>='a' && *s<='f')j+=*s-'a'+10;
s++;
}
fseek(in, j, 0);
while(*s<=' ')s++;
while(*s>' ')
{
c=*s;
s++;
if(c=='\\')
{
j=0;
for(c=0; c<2; c++)
{
j<<=4;
if(*s>='0' && *s<='9')j+=*s-'0';
if(*s>='A' && *s<='F')j+=*s-'A'+10;
if(*s>='a' && *s<='f')j+=*s-'a'+10;
s++;
}
c=j;
}
fputc(c, in);
}
i=strlen((char *)(&buf))-1;
break;
default:
break;
}
}
}
| 15.767568 | 55 | 0.397669 | cr88192 |
c5d51607911d7c76376d1901875c9105474aabae | 3,806 | cpp | C++ | Source/TopDownARPG/Characters/TopDownARPGCharacter.cpp | frostblooded/UE4BossProject | 3f80ce23822a870a00553c256ee39377ac1b07ba | [
"MIT"
] | 1 | 2020-02-26T15:16:21.000Z | 2020-02-26T15:16:21.000Z | Source/TopDownARPG/Characters/TopDownARPGCharacter.cpp | frostblooded/UE4BossProject | 3f80ce23822a870a00553c256ee39377ac1b07ba | [
"MIT"
] | null | null | null | Source/TopDownARPG/Characters/TopDownARPGCharacter.cpp | frostblooded/UE4BossProject | 3f80ce23822a870a00553c256ee39377ac1b07ba | [
"MIT"
] | null | null | null | // Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
#include "TopDownARPGCharacter.h"
#include "UObject/ConstructorHelpers.h"
#include "Camera/CameraComponent.h"
#include "Components/DecalComponent.h"
#include "Components/CapsuleComponent.h"
#include "GameFramework/CharacterMovementComponent.h"
#include "GameFramework/PlayerController.h"
#include "GameFramework/SpringArmComponent.h"
#include "HeadMountedDisplayFunctionLibrary.h"
#include "Materials/Material.h"
#include "Engine/World.h"
#include "TopDownARPG.h"
#include "GameModes/TopDownARPGGameMode.h"
ATopDownARPGCharacter::ATopDownARPGCharacter()
{
// Set size for player capsule
GetCapsuleComponent()->InitCapsuleSize(42.f, 96.0f);
// Don't rotate character to camera direction
bUseControllerRotationPitch = false;
bUseControllerRotationYaw = false;
bUseControllerRotationRoll = false;
// Configure character movement
GetCharacterMovement()->bOrientRotationToMovement = true; // Rotate character to moving direction
GetCharacterMovement()->RotationRate = FRotator(0.f, 640.f, 0.f);
GetCharacterMovement()->bConstrainToPlane = true;
GetCharacterMovement()->bSnapToPlaneAtStart = true;
// Create a camera boom...
CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom"));
CameraBoom->SetupAttachment(RootComponent);
CameraBoom->bAbsoluteRotation = true; // Don't want arm to rotate when character does
CameraBoom->TargetArmLength = 800.f;
CameraBoom->RelativeRotation = FRotator(-60.f, 0.f, 0.f);
CameraBoom->bDoCollisionTest = false; // Don't want to pull camera in when it collides with level
// Create a camera...
TopDownCameraComponent = CreateDefaultSubobject<UCameraComponent>(TEXT("TopDownCamera"));
TopDownCameraComponent->SetupAttachment(CameraBoom, USpringArmComponent::SocketName);
TopDownCameraComponent->bUsePawnControlRotation = false; // Camera does not rotate relative to arm
// Create a decal in the world to show the cursor's location
CursorToWorld = CreateDefaultSubobject<UDecalComponent>("CursorToWorld");
CursorToWorld->SetupAttachment(RootComponent);
static ConstructorHelpers::FObjectFinder<UMaterial> DecalMaterialAsset(TEXT("Material'/Game/TopDownCPP/Blueprints/M_Cursor_Decal.M_Cursor_Decal'"));
if (DecalMaterialAsset.Succeeded())
{
CursorToWorld->SetDecalMaterial(DecalMaterialAsset.Object);
}
CursorToWorld->DecalSize = FVector(16.0f, 32.0f, 32.0f);
CursorToWorld->SetRelativeRotation(FRotator(90.0f, 0.0f, 0.0f).Quaternion());
// Activate ticking in order to update the cursor every frame.
PrimaryActorTick.bCanEverTick = true;
PrimaryActorTick.bStartWithTickEnabled = true;
DamageableComponent = CreateDefaultSubobject<UDamageableComponent>("Damageable");
}
void ATopDownARPGCharacter::BeginPlay()
{
Super::BeginPlay();
FTopDownARPGCharacterStruct* CharacterStruct = CharacterStatsRow.GetRow<FTopDownARPGCharacterStruct>(TEXT(""));
if (CharacterStruct == nullptr)
{
UE_LOG(LogTopDownARPG, Error, TEXT("ATopDownARPGCharacter::BeginPlay CharacterStruct != nullptr"));
return;
}
for (const TSubclassOf<UAbility>Template : CharacterStruct->AbilityTemplates)
{
AbilityInstances.Add(NewObject<UAbility>(this, Template));
}
}
void ATopDownARPGCharacter::Tick(float DeltaSeconds)
{
Super::Tick(DeltaSeconds);
if (CursorToWorld != nullptr)
{
if (APlayerController* PC = Cast<APlayerController>(GetController()))
{
FHitResult TraceHitResult;
PC->GetHitResultUnderCursor(ECC_Visibility, true, TraceHitResult);
FVector CursorFV = TraceHitResult.ImpactNormal;
FRotator CursorR = CursorFV.Rotation();
CursorToWorld->SetWorldLocation(TraceHitResult.Location);
CursorToWorld->SetWorldRotation(CursorR);
}
}
}
| 38.444444 | 150 | 0.769049 | frostblooded |
c5d835cb3603806f929d8fc2e98ab38f16792861 | 1,138 | cc | C++ | statements/ReadStmt.cc | R2333333/SCAPES | 98f8aafc1bbd279165e82a70eaa3c22eef62c892 | [
"MIT"
] | null | null | null | statements/ReadStmt.cc | R2333333/SCAPES | 98f8aafc1bbd279165e82a70eaa3c22eef62c892 | [
"MIT"
] | null | null | null | statements/ReadStmt.cc | R2333333/SCAPES | 98f8aafc1bbd279165e82a70eaa3c22eef62c892 | [
"MIT"
] | null | null | null | #include "../headerFiles/ReadStmt.h"
#include "../headerFiles/Program.h"
using namespace std;
ReadStmt::ReadStmt()
:Statement(){}
void ReadStmt::compile(QString stat){
if (checkError(stat)){
return;
}
QStringList list = stat.split(" ");
instruction = list.at(0);
operand1 = new Operand(list.at(1));
statementObj["Instruction"] = instruction;
statementObj["Operand1"] = this->getFirstOperand();
}
void ReadStmt::run(){
if(!program->getVMap()->contains(operand1->getIdent()->getName())){
QMessageBox::warning(nullptr, "Error", QString("Variable not exists yet!!!"));
}else {
int input = QInputDialog::getInt(nullptr, ("Please enter an integer"), ("Value:"));
if(program->getVMap()->value(operand1->getIdent()->getName())->getType().compare("int") == 0){
program->getVMap()->value(operand1->getIdent()->getName())->setValue(input);
}
if(program->getVMap()->value(operand1->getIdent()->getName())->getType().compare("array") == 0){
program->getVMap()->value(operand1->getIdent()->getName())->addArrElement(input);
}
}
}
| 29.179487 | 104 | 0.623023 | R2333333 |
c5d99e4135541ff66bfbb967dc53ecc3d143ed9a | 2,393 | hpp | C++ | include/UnityEngine/TestRunner/NUnitExtensions/TestResultExtensions.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/UnityEngine/TestRunner/NUnitExtensions/TestResultExtensions.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/UnityEngine/TestRunner/NUnitExtensions/TestResultExtensions.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: NUnit::Framework::Internal
namespace NUnit::Framework::Internal {
// Forward declaring type: TestResult
class TestResult;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Exception
class Exception;
}
// Forward declaring namespace: NUnit::Framework::Interfaces
namespace NUnit::Framework::Interfaces {
// Forward declaring type: ResultState
class ResultState;
}
// Completed forward declares
// Type namespace: UnityEngine.TestRunner.NUnitExtensions
namespace UnityEngine::TestRunner::NUnitExtensions {
// Size: 0x10
#pragma pack(push, 1)
// Autogenerated type: UnityEngine.TestRunner.NUnitExtensions.TestResultExtensions
// [ExtensionAttribute] Offset: FFFFFFFF
class TestResultExtensions : public ::Il2CppObject {
public:
// Creating value type constructor for type: TestResultExtensions
TestResultExtensions() noexcept {}
// static public System.Void RecordPrefixedException(NUnit.Framework.Internal.TestResult testResult, System.String prefix, System.Exception ex, NUnit.Framework.Interfaces.ResultState resultState)
// Offset: 0x1496A14
static void RecordPrefixedException(NUnit::Framework::Internal::TestResult* testResult, ::Il2CppString* prefix, System::Exception* ex, NUnit::Framework::Interfaces::ResultState* resultState);
// static public System.Void RecordPrefixedError(NUnit.Framework.Internal.TestResult testResult, System.String prefix, System.String error, NUnit.Framework.Interfaces.ResultState resultState)
// Offset: 0x1496E84
static void RecordPrefixedError(NUnit::Framework::Internal::TestResult* testResult, ::Il2CppString* prefix, ::Il2CppString* error, NUnit::Framework::Interfaces::ResultState* resultState);
}; // UnityEngine.TestRunner.NUnitExtensions.TestResultExtensions
#pragma pack(pop)
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(UnityEngine::TestRunner::NUnitExtensions::TestResultExtensions*, "UnityEngine.TestRunner.NUnitExtensions", "TestResultExtensions");
| 52.021739 | 200 | 0.752194 | darknight1050 |
c5da7565372b3c8a4fb8d54869459fddce5b60b9 | 795 | cpp | C++ | src/algorithms/kamenevs/KuniHeroVector.cpp | av-elier/fast-exponentiation-algs | 1d6393021583686372564a7ca52b09dc7013fb38 | [
"MIT"
] | 2 | 2016-10-17T20:30:05.000Z | 2020-03-24T19:52:14.000Z | src/algorithms/kamenevs/KuniHeroVector.cpp | av-elier/fast-exponentiation-algs | 1d6393021583686372564a7ca52b09dc7013fb38 | [
"MIT"
] | null | null | null | src/algorithms/kamenevs/KuniHeroVector.cpp | av-elier/fast-exponentiation-algs | 1d6393021583686372564a7ca52b09dc7013fb38 | [
"MIT"
] | null | null | null | #include "algorithms/kamenevs/KuniHeroVector.h"
#include <algorithm>
vector<string>* KuniheroVector::create_str_dicitionary(string s)
{
double p = 0;
for (int i = 0; i < s.length(); ++i)
p+=s[i] - 48;
p /= s.length();
double q = 1 - p;
Node* n = fill(k,p);
vector<string>* res = (n->get_paths());
for (int i = 0; i < res->size(); ++i)
{
(*res)[i] = (*res)[i].substr(0,(*res)[i].find_last_of("1")+1).c_str();
}
return res;
}
vector<ZZ>* KuniheroVector::create_num_dicitionary(vector<string>& strs)
{
vector<ZZ>* res = new vector<ZZ>();
for (int i = 0; i < strs.size(); ++i)
{
ZZ z;
conv(z,0);
for (int j = 0; j < strs[i].size(); ++j)
{
if (strs[i][j]=='1')
{
SetBit(z,strs[i].size() - j - 1);
}
}
res->push_back(z);
}
return res;
}
| 19.875 | 72 | 0.54717 | av-elier |
c5dfc442120aec8deaa0d3d2fb657b3bdc7f7f67 | 3,385 | cpp | C++ | pl2_assembler/main.cpp | MassiveBattlebotsFan/team-lightning-cpu | 513b92aec5b3fe185f4e9220340a23bb09561059 | [
"Unlicense"
] | 1 | 2021-09-30T19:39:55.000Z | 2021-09-30T19:39:55.000Z | pl2_assembler/main.cpp | MassiveBattlebotsFan/team-lightning-cpu | 513b92aec5b3fe185f4e9220340a23bb09561059 | [
"Unlicense"
] | null | null | null | pl2_assembler/main.cpp | MassiveBattlebotsFan/team-lightning-cpu | 513b92aec5b3fe185f4e9220340a23bb09561059 | [
"Unlicense"
] | null | null | null | #include <cstdio>
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <cstdint>
#include <cstring>
#include <map>
using namespace std;
int main(int argc, char const *argv[]) {
try{
//init logging to file
ofstream logging("pl2asm.log");
auto old_rdbuf = clog.rdbuf(); // not implemented
clog.rdbuf(logging.rdbuf());
std::map<string, uint16_t> opcodes = {};
string opcodesDb = "opcodes.db";
if(argc == 1){
cerr << "Usage: " << argv[0] << " -i source.pl2 [-v] [-d opcodes.db] [-o output.pl2c]" << endl;
return -1;
}
for(int i = 1; i < argc; i++){
if(strcmp(argv[i], "-v")==0){
clog.rdbuf(old_rdbuf);
break;
}
}
string outfile, infile;
for(int i = 1; i < argc; i++){
if(strcmp(argv[i], "-i")==0){
infile = argv[i+1];
break;
}
}
outfile = infile + 'c';
for(int i = 1; i < argc; i++){
if(strcmp(argv[i], "-o")==0){
outfile = argv[i+1];
clog << "outfile set" << endl;
}
if(strcmp(argv[i], "-d")==0){
opcodesDb = argv[i+1];
clog << "db set" << endl;
}
}
ifstream opcodesIn;
opcodesIn.open(opcodesDb);
if(!opcodesIn.is_open()){
throw("opcodes db open failed");
}
char buffer1[4096] = "", buffer2[4096] = "", buffer3[4096] = "";
stringstream parser;
clog << "Opcodes read:" << endl;
while(opcodesIn.getline(buffer1, 4096, '\n')){
parser.str("");
if(opcodesIn.fail()){
if(opcodesIn.bad()){
throw("opcodes db read stream bad");
}
if(opcodesIn.eof()){
break;
}
throw("opcodes db read loop failed");
}
parser << buffer1 << '\0';
parser.getline(buffer2, 4096, '=');
parser.getline(buffer3, 4096, '\0');
clog << buffer2 << ", " << buffer3 << endl;
opcodes[buffer3] = (uint16_t)strtol(buffer2, NULL, 16);
}
opcodesIn.close();
ifstream asmIn(infile.c_str());
if(!asmIn.is_open()){
throw("Assembly input file open failed");
}
ofstream asmOut(outfile.c_str());
if(!asmOut.is_open()){
throw("Assembled output file open failed");
}
uint16_t instrArgOut = 0x0;
uint16_t opCodeOut = 0x0;
clog << "Assembler output:" << endl;
while(asmIn.getline(buffer1, 4096, '\n')){
parser.str("");
if(asmIn.fail()){
if(asmIn.bad()){
throw("asm read stream bad");
}
throw("asm read loop failed");
}
parser << buffer1 << '\0';
parser.getline(buffer2, 4096, ':');
parser.getline(buffer3, 4096, '\0');
instrArgOut = (uint16_t)strtol(buffer3, NULL, 16);
opCodeOut = opcodes[buffer2];
clog << std::hex << std::setfill('0') << std::setw(2) << opCodeOut;
asmOut << std::hex << std::setfill('0') << std::setw(2) << opCodeOut;
clog << std::hex << std::setfill('0') << ',' << std::setw(4) << instrArgOut << ';' << endl;
asmOut << std::hex << std::setfill('0') << ',' << std::setw(4) << instrArgOut << ';';
}
asmIn.close();
asmOut.close();
return 0;
}catch(const char* error){
cerr << "Error: " << error << ", errno = " << strerror(errno) << endl;
return -1;
}catch(...){
cerr << "Unknown error. Program aborting." << endl;
return -1;
}
}
| 29.181034 | 101 | 0.52969 | MassiveBattlebotsFan |
c5dff3aade8632a6e61e52c3056107c113bcd0f2 | 3,936 | cpp | C++ | Plugins/OVRPlatformBP/Source/OVRPlatformBP/Private/OBPRequests_LanguagePack.cpp | Brain-Vision/Unreal-SharedSpaces | 262153c5c52c4e15fed5ece901e0e1c8502bb030 | [
"MIT"
] | null | null | null | Plugins/OVRPlatformBP/Source/OVRPlatformBP/Private/OBPRequests_LanguagePack.cpp | Brain-Vision/Unreal-SharedSpaces | 262153c5c52c4e15fed5ece901e0e1c8502bb030 | [
"MIT"
] | null | null | null | Plugins/OVRPlatformBP/Source/OVRPlatformBP/Private/OBPRequests_LanguagePack.cpp | Brain-Vision/Unreal-SharedSpaces | 262153c5c52c4e15fed5ece901e0e1c8502bb030 | [
"MIT"
] | null | null | null | // OVRPlatformBP plugin by InnerLoop LLC 2021
#include "OBPRequests_LanguagePack.h"
// --------------------
// Initializers
// --------------------
UOBPLanguagePack_GetCurrent::UOBPLanguagePack_GetCurrent(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
}
UOBPLanguagePack_SetCurrent::UOBPLanguagePack_SetCurrent(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
}
// --------------------
// OVR_Requests_LanguagePack.h
// --------------------
//---GetCurrent---
void UOBPLanguagePack_GetCurrent::Activate()
{
#if PLATFORM_MINOR_VERSION >= 28
auto OculusIdentityInterface = Online::GetIdentityInterface(OCULUS_SUBSYSTEM);
if (OculusIdentityInterface.IsValid())
{
ovrRequest RequestId = ovr_LanguagePack_GetCurrent();
FOnlineSubsystemOculus* OSS = static_cast<FOnlineSubsystemOculus*>(IOnlineSubsystem::Get(OCULUS_SUBSYSTEM));
OSS->AddRequestDelegate(RequestId, FOculusMessageOnCompleteDelegate::CreateLambda(
[this](ovrMessageHandle Message, bool bIsError)
{
if (bIsError)
{
OBPMessageError("LanguagePack::GetCurrent", Message);
OnFailure.Broadcast(nullptr);
}
else
{
ovrMessageType messageType = ovr_Message_GetType(Message);
if (messageType == ovrMessage_LanguagePack_GetCurrent)
{
UE_LOG(LogOVRPlatformBP, Log, TEXT("Successfully got current language pack."));
auto AssetDetails = NewObject<UOBPAssetDetails>();
AssetDetails->ovrAssetDetailsHandle = ovr_Message_GetAssetDetails(Message);
OnSuccess.Broadcast(AssetDetails);
}
else
{
UE_LOG(LogOVRPlatformBP, Log, TEXT("Failed to get current language pack."));
OnFailure.Broadcast(nullptr);
}
}
}));
}
else
{
OBPSubsystemError("LanguagePack::GetCurrent");
OnFailure.Broadcast(nullptr);
}
#else
OBPPlatformVersionError("LanguagePack::GetCurrent", "1.28");
OnFailure.Broadcast(nullptr);
#endif
}
UOBPLanguagePack_GetCurrent* UOBPLanguagePack_GetCurrent::GetCurrent(UObject* WorldContextObject)
{
return NewObject<UOBPLanguagePack_GetCurrent>();
}
//---SetCurrent---
void UOBPLanguagePack_SetCurrent::Activate()
{
#if PLATFORM_MINOR_VERSION >= 31
auto OculusIdentityInterface = Online::GetIdentityInterface(OCULUS_SUBSYSTEM);
if (OculusIdentityInterface.IsValid())
{
ovrRequest RequestId = ovr_LanguagePack_SetCurrent(TCHAR_TO_ANSI(*Tag));
FOnlineSubsystemOculus* OSS = static_cast<FOnlineSubsystemOculus*>(IOnlineSubsystem::Get(OCULUS_SUBSYSTEM));
OSS->AddRequestDelegate(RequestId, FOculusMessageOnCompleteDelegate::CreateLambda(
[this](ovrMessageHandle Message, bool bIsError)
{
if (bIsError)
{
OBPMessageError("LanguagePack::SetCurrent", Message);
OnFailure.Broadcast(FString(), FString());
}
else
{
ovrMessageType messageType = ovr_Message_GetType(Message);
if (messageType == ovrMessage_LanguagePack_SetCurrent)
{
UE_LOG(LogOVRPlatformBP, Log, TEXT("Successfully set current language pack."));
auto AssetFileDownloadResultHandle = ovr_Message_GetAssetFileDownloadResult(Message);
auto AssetID = OBPInt64ToFString(ovr_AssetFileDownloadResult_GetAssetId(AssetFileDownloadResultHandle));
auto FilePath = ovr_AssetFileDownloadResult_GetFilepath(AssetFileDownloadResultHandle);
OnSuccess.Broadcast(AssetID, FilePath);
}
else
{
UE_LOG(LogOVRPlatformBP, Log, TEXT("Failed to set current language pack."));
OnFailure.Broadcast(FString(), FString());
}
}
}));
}
else
{
OBPSubsystemError("LanguagePack::SetCurrent");
OnFailure.Broadcast(FString(), FString());
}
#else
OBPPlatformVersionError("LanguagePack::SetCurrent", "1.31");
OnFailure.Broadcast(FString(), FString());
#endif
}
UOBPLanguagePack_SetCurrent* UOBPLanguagePack_SetCurrent::SetCurrent(UObject* WorldContextObject, FString Tag)
{
auto SetCurrent = NewObject<UOBPLanguagePack_SetCurrent>();
SetCurrent->Tag = Tag;
return SetCurrent;
} | 29.818182 | 110 | 0.746697 | Brain-Vision |
c5e0fd6a70bc8bcda03a611793e213567f02d46e | 12,175 | cpp | C++ | src/ny/wayland/util.cpp | nyorain/ny | 9349a6f668a9458d3a37b76bb3cd1e5c679d16ad | [
"BSL-1.0"
] | 18 | 2015-12-14T09:04:06.000Z | 2021-11-14T20:38:17.000Z | src/ny/wayland/util.cpp | nyorain/ny | 9349a6f668a9458d3a37b76bb3cd1e5c679d16ad | [
"BSL-1.0"
] | 2 | 2015-06-26T09:26:05.000Z | 2019-04-02T09:05:12.000Z | src/ny/wayland/util.cpp | nyorain/ny | 9349a6f668a9458d3a37b76bb3cd1e5c679d16ad | [
"BSL-1.0"
] | 2 | 2017-08-23T06:04:26.000Z | 2019-11-27T01:48:02.000Z | // Copyright (c) 2015-2018 nyorain
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt
#include <ny/wayland/util.hpp>
#include <ny/wayland/appContext.hpp>
#include <ny/wayland/windowContext.hpp>
#include <ny/cursor.hpp>
#include <dlg/dlg.hpp>
#include <nytl/scope.hpp>
#include <wayland-client-protocol.h>
#include <ny/wayland/protocols/xdg-shell-v5.h>
#include <ny/wayland/protocols/xdg-shell-v6.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <iostream>
#include <cstring>
namespace ny {
namespace wayland {
namespace {
int setCloexecOrClose(int fd)
{
long flags;
if(fd == -1) goto err2;
flags = fcntl(fd, F_GETFD);
if(flags == -1) goto err1;
if(fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) goto err1;
return fd;
err1:
close(fd);
err2:
dlg_warn("fctnl failed: {}", std::strerror(errno));
return -1;
}
int createTmpfileCloexec(char *tmpname)
{
int fd;
#ifdef HAVE_MKOSTEMP
fd = mkostemp(tmpname, O_CLOEXEC);
if(fd >= 0) unlink(tmpname);
#else
fd = mkstemp(tmpname);
if(fd >= 0)
{
fd = setCloexecOrClose(fd);
unlink(tmpname);
}
#endif
return fd;
}
int osCreateAnonymousFile(off_t size)
{
static const char template1[] = "/weston-shared-XXXXXX";
const char *path;
char *name;
int fd;
path = getenv("XDG_RUNTIME_DIR");
if (!path) {
errno = ENOENT;
return -1;
}
name = (char*) malloc(strlen(path) + sizeof(template1));
if(!name) return -1;
strcpy(name, path);
strcat(name, template1);
fd = createTmpfileCloexec(name);
free(name);
if(fd < 0) return -1;
if(ftruncate(fd, size) < 0) {
close(fd);
return -1;
}
return fd;
}
} // anonymous util namespace
//shmBuffer
ShmBuffer::ShmBuffer(WaylandAppContext& ac, nytl::Vec2ui size, unsigned int stride)
: appContext_(&ac), size_(size), stride_(stride)
{
format_ = WL_SHM_FORMAT_ARGB8888;
if(!stride_) stride_ = size[0] * 4;
create();
}
ShmBuffer::~ShmBuffer()
{
destroy();
}
ShmBuffer::ShmBuffer(ShmBuffer&& other)
{
appContext_ = other.appContext_;
shmSize_ = other.shmSize_;
size_ = other.size_;
stride_ = other.stride_;
buffer_ = other.buffer_;
pool_ = other.pool_;
data_ = other.data_;
format_ = other.format_;
used_ = other.used_;
other.appContext_ = {};
other.shmSize_ = {};
other.size_ = {};
other.buffer_ = {};
other.pool_ = {};
other.data_ = {};
other.format_ = {};
other.used_ = {};
if(buffer_) wl_buffer_set_user_data(buffer_, this);
}
ShmBuffer& ShmBuffer::operator=(ShmBuffer&& other)
{
destroy();
appContext_ = other.appContext_;
shmSize_ = other.shmSize_;
size_ = other.size_;
stride_ = other.stride_;
buffer_ = other.buffer_;
pool_ = other.pool_;
data_ = other.data_;
format_ = other.format_;
used_ = other.used_;
other.appContext_ = {};
other.shmSize_ = {};
other.size_ = {};
other.buffer_ = {};
other.pool_ = {};
other.data_ = {};
other.format_ = {};
other.used_ = {};
if(buffer_) wl_buffer_set_user_data(buffer_, this);
return *this;
}
void ShmBuffer::create()
{
destroy();
if(!size_[0] || !size_[1]) throw std::runtime_error("ny::wayland::ShmBuffer invalid size");
if(!stride_) throw std::runtime_error("ny::wayland::ShmBuffer invalid stride");
auto* shm = appContext_->wlShm();
if(!shm) throw std::runtime_error("ny::wayland::ShmBuffer: appContext has no wl_shm");
auto vecSize = stride_ * size_[1];
shmSize_ = std::max(vecSize, shmSize_);
auto fd = osCreateAnonymousFile(shmSize_);
if (fd < 0) throw std::runtime_error("ny::wayland::ShmBuffer: could not create shm file");
// the fd is not needed here anymore AFTER the pool was created
// our access to the file is represented by the pool
auto fdGuard = nytl::ScopeGuard([&]{ close(fd); });
auto ptr = mmap(nullptr, shmSize_, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if(ptr == MAP_FAILED) throw std::runtime_error("ny::wayland::ShmBuffer: could not mmap file");
data_ = reinterpret_cast<std::uint8_t*>(ptr);
pool_ = wl_shm_create_pool(shm, fd, shmSize_);
buffer_ = wl_shm_pool_create_buffer(pool_, 0, size_[0], size_[1], stride_, format_);
static constexpr wl_buffer_listener listener {
memberCallback<&ShmBuffer::released>
};
wl_buffer_add_listener(buffer_, &listener, this);
}
void ShmBuffer::destroy()
{
if(buffer_) wl_buffer_destroy(buffer_);
if(pool_) wl_shm_pool_destroy(pool_);
if(data_) munmap(data_, shmSize_);
}
bool ShmBuffer::size(nytl::Vec2ui size, unsigned int stride)
{
size_ = size;
stride_ = stride;
if(!stride_) stride_ = size[0] * 4;
unsigned int vecSize = stride_ * size_[1];
if(!size_[0] || !size_[1]) throw std::runtime_error("ny::wayland::ShmBuffer invalid size");
if(!stride_) throw std::runtime_error("ny::wayland::ShmBuffer invalid stride");
if(vecSize > shmSize_) {
create();
return true;
} else {
wl_buffer_destroy(buffer_);
buffer_ = wl_shm_pool_create_buffer(pool_, 0, size_[0], size_[1], stride_, format_);
return false;
}
}
// Output
Output::Output(WaylandAppContext& ac, wl_output& outp, unsigned int id)
: appContext_(&ac), wlOutput_(&outp), globalID_(id)
{
static constexpr wl_output_listener listener {
memberCallback<&Output::geometry>,
memberCallback<&Output::mode>,
memberCallback<&Output::done>,
memberCallback<&Output::scale>
};
wl_output_add_listener(&outp, &listener, this);
}
Output::~Output()
{
if(wlOutput_) {
if(wl_output_get_version(wlOutput_) > 3) wl_output_release(wlOutput_);
else wl_output_destroy(wlOutput_);
}
}
Output::Output(Output&& other) noexcept :
appContext_(other.appContext_), wlOutput_(other.wlOutput_), globalID_(other.globalID_),
information_(other.information_)
{
other.appContext_ = {};
other.wlOutput_ = {};
if(wlOutput_) wl_output_set_user_data(wlOutput_, this);
}
Output& Output::operator=(Output&& other) noexcept
{
if(wlOutput_) wl_output_release(wlOutput_);
appContext_ = other.appContext_;
wlOutput_ = other.wlOutput_;
globalID_ = other.globalID_;
information_ = std::move(other.information_);
other.appContext_ = {};
other.wlOutput_ = {};
if(wlOutput_) wl_output_set_user_data(wlOutput_, this);
return *this;
}
void Output::geometry(wl_output*, int32_t x, int32_t y, int32_t phwidth, int32_t phheight,
int32_t subpixel, const char* make, const char* model, int32_t transform)
{
information_.make = make;
information_.model = model;
information_.transform = transform;
information_.position = {x, y};
information_.physicalSize = {static_cast<uint32_t>(phwidth), static_cast<uint32_t>(phheight)};
information_.subpixel = subpixel;
}
void Output::mode(wl_output*, uint32_t flags, int32_t width, int32_t height, int32_t refresh)
{
unsigned int urefresh = refresh;
information_.modes.push_back({{}, flags, urefresh});
information_.modes.back().size = {static_cast<uint32_t>(width), static_cast<uint32_t>(height)};
}
void Output::done(wl_output*)
{
information_.done = true;
}
void Output::scale(wl_output*, int32_t scale)
{
information_.scale = scale;
}
// util
const char* errorName(const wl_interface& interface, int error)
{
struct Error {
int code;
const char* msg;
};
static struct {
const wl_interface& interface;
std::vector<Error> errors;
} interfaces[] = {
// core protocol
{ wl_display_interface, {
{ WL_DISPLAY_ERROR_INVALID_OBJECT, "WL_DISPLAY_ERROR_INVALID_OBJECT" },
{ WL_DISPLAY_ERROR_INVALID_METHOD, "WL_DISPLAY_ERROR_INVALID_METHOD" },
{ WL_DISPLAY_ERROR_NO_MEMORY, "WL_DISPLAY_ERROR_NO_MEMORY" } }
},
{ wl_shm_interface, {
{ WL_SHM_ERROR_INVALID_FORMAT, "WL_SHM_ERROR_INVALID_FORMAT" },
{ WL_SHM_ERROR_INVALID_STRIDE, "WL_SHM_ERROR_INVALID_STRIDE" },
{ WL_SHM_ERROR_INVALID_FD, "WL_SHM_ERROR_INVALID_FD" } }
},
{ wl_data_offer_interface, {
{ WL_DATA_OFFER_ERROR_INVALID_FINISH, "WL_DATA_OFFER_ERROR_INVALID_FINISH" },
{ WL_DATA_OFFER_ERROR_INVALID_ACTION_MASK, "WL_DATA_OFFER_ERROR_INVALID_ACTION_MASK" },
{ WL_DATA_OFFER_ERROR_INVALID_ACTION, "WL_DATA_OFFER_ERROR_INVALID_ACTION" },
{ WL_DATA_OFFER_ERROR_INVALID_OFFER , "WL_DATA_OFFER_ERROR_INVALID_OFFER" } }
},
{ wl_data_source_interface, {
{ WL_DATA_SOURCE_ERROR_INVALID_ACTION_MASK, "WL_DATA_SOURCE_ERROR_INVALID_ACTION_MASK" },
{ WL_DATA_SOURCE_ERROR_INVALID_SOURCE, "WL_DATA_SOURCE_ERROR_INVALID_SOURCE" } }
},
{ wl_data_device_interface, {
{ WL_DATA_DEVICE_ERROR_ROLE, "WL_DATA_DEVICE_ERROR_ROLE" } },
},
{ wl_shell_interface, {
{ WL_SHELL_ERROR_ROLE, "WL_SHELL_ERROR_ROLE" } },
},
{ wl_surface_interface, {
{ WL_SURFACE_ERROR_INVALID_SCALE, "WL_SURFACE_ERROR_INVALID_SCALE" },
{ WL_SURFACE_ERROR_INVALID_TRANSFORM, "WL_SURFACE_ERROR_INVALID_TRANSFORM" } },
},
{ wl_shell_interface, {
{ WL_POINTER_ERROR_ROLE, "WL_POINTER_ERROR_ROLE" } },
},
{ wl_subcompositor_interface, {
{ WL_SUBCOMPOSITOR_ERROR_BAD_SURFACE, "WL_SUBCOMPOSITOR_ERROR_BAD_SURFACE" } },
},
{ wl_subsurface_interface, {
{ WL_SUBSURFACE_ERROR_BAD_SURFACE, "WL_SUBSURFACE_ERROR_BAD_SURFACE" } },
},
// xdg
// shell v5
{ xdg_shell_interface, {
{ XDG_SHELL_ERROR_ROLE, "XDG_SHELL_ERROR_ROLE" },
{ XDG_SHELL_ERROR_DEFUNCT_SURFACES, "XDG_SHELL_ERROR_DEFUNCT_SURFACES" },
{ XDG_SHELL_ERROR_NOT_THE_TOPMOST_POPUP, "XDG_SHELL_ERROR_NOT_THE_TOPMOST_POPUP" },
{ XDG_SHELL_ERROR_INVALID_POPUP_PARENT, "XDG_SHELL_ERROR_INVALID_POPUP_PARENT" } },
},
// shell v6
{ zxdg_shell_v6_interface, {
{ ZXDG_SHELL_V6_ERROR_ROLE, "ZXDG_SHELL_V6_ERROR_ROLE" },
{ ZXDG_SHELL_V6_ERROR_DEFUNCT_SURFACES, "ZXDG_SHELL_V6_ERROR_DEFUNCT_SURFACES" },
{ ZXDG_SHELL_V6_ERROR_NOT_THE_TOPMOST_POPUP,
"ZXDG_SHELL_V6_ERROR_NOT_THE_TOPMOST_POPUP" },
{ ZXDG_SHELL_V6_ERROR_INVALID_POPUP_PARENT,
"ZXDG_SHELL_V6_ERROR_INVALID_POPUP_PARENT" },
{ ZXDG_SHELL_V6_ERROR_INVALID_SURFACE_STATE,
"ZXDG_SHELL_V6_ERROR_INVALID_SURFACE_STATE" },
{ ZXDG_SHELL_V6_ERROR_INVALID_POSITIONER, "ZXDG_SHELL_V6_ERROR_INVALID_POSITIONER" } },
},
{ zxdg_positioner_v6_interface, {
{ ZXDG_POSITIONER_V6_ERROR_INVALID_INPUT, "ZXDG_POSITIONER_V6_ERROR_INVALID_INPUT"} }
},
{ zxdg_surface_v6_interface, {
{ ZXDG_SURFACE_V6_ERROR_NOT_CONSTRUCTED, "ZXDG_SURFACE_V6_ERROR_NOT_CONSTRUCTED" },
{ ZXDG_SURFACE_V6_ERROR_ALREADY_CONSTRUCTED,
"ZXDG_SURFACE_V6_ERROR_ALREADY_CONSTRUCTED" },
{ ZXDG_SURFACE_V6_ERROR_UNCONFIGURED_BUFFER,
"ZXDG_SURFACE_V6_ERROR_UNCONFIGURED_BUFFER" } }
},
{ zxdg_popup_v6_interface, {
{ ZXDG_POPUP_V6_ERROR_INVALID_GRAB, "ZXDG_POPUP_V6_ERROR_INVALID_GRAB"} }
},
};
for(auto& i : interfaces) {
if(&i.interface != &interface) {
continue;
}
for(auto& e : i.errors) {
if(e.code == error) {
return e.msg;
}
}
break;
}
return "<unknown interface error>";
}
} // namespace wayland
WindowEdge waylandToEdge(unsigned int wlEdge)
{
return static_cast<WindowEdge>(wlEdge);
}
unsigned int edgeToWayland(WindowEdge edge)
{
return static_cast<unsigned int>(edge);
}
constexpr struct FormatConversion {
ImageFormat imageFormat;
unsigned int shmFormat;
} formatConversions[] {
{ImageFormat::argb8888, WL_SHM_FORMAT_ARGB8888},
{ImageFormat::argb8888, WL_SHM_FORMAT_XRGB8888},
{ImageFormat::rgba8888, WL_SHM_FORMAT_RGBA8888},
{ImageFormat::bgra8888, WL_SHM_FORMAT_BGRA8888},
{ImageFormat::abgr8888, WL_SHM_FORMAT_ABGR8888},
{ImageFormat::bgr888, WL_SHM_FORMAT_BGR888},
{ImageFormat::rgb888, WL_SHM_FORMAT_RGB888},
};
int imageFormatToWayland(const ImageFormat& format)
{
for(auto& fc : formatConversions) if(fc.imageFormat == format) return fc.shmFormat;
return -1;
}
ImageFormat waylandToImageFormat(unsigned int shmFormat)
{
for(auto& fc : formatConversions) if(fc.shmFormat == shmFormat) return fc.imageFormat;
return ImageFormat::none;
}
unsigned int stateToWayland(ToplevelState state)
{
switch(state) {
case ToplevelState::maximized: return 1;
case ToplevelState::fullscreen: return 2;
default: return 0;
}
}
ToplevelState waylandToState(unsigned int wlState)
{
switch(wlState) {
case 1: return ToplevelState::maximized;
case 2: return ToplevelState::fullscreen;
default: return ToplevelState::unknown;
}
}
} // namespace ny
| 26.070664 | 96 | 0.733306 | nyorain |
c5e41c26b1839f262fd7709cf3963962bcad1f3c | 953 | hh | C++ | difAlgebra/DifExternal.hh | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | difAlgebra/DifExternal.hh | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | difAlgebra/DifExternal.hh | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | //--------------------------------------------------------------------------
// File and Version Information:
// $Id: DifExternal.hh 501 2010-01-14 12:46:50Z stroili $
//
// Description:
// Class Header for |DifExternal|
// Define some useful constants
//
// Environment:
// Software developed for the BaBar Detector at the SLAC B-Factory.
//
// Author List:
// A. Snyder
//
// Copyright Information:
// Copyright (C) 1996 SLAC
//
//------------------------------------------------------------------------
#ifndef DifExternal_HH
#define DifExternal_HH
#include "difAlgebra/DifNumber.hh"
#include "difAlgebra/DifVector.hh"
#include "difAlgebra/DifPoint.hh"
#include "difAlgebra/DifComplex.hh"
extern const DifNumber one;
extern const DifNumber zero;
extern const DifVector xhat;
extern const DifVector yhat;
extern const DifVector zhat;
extern const DifVector nullVec;
extern const DifPoint origin;
extern const DifComplex I;
#endif
| 19.44898 | 76 | 0.624344 | brownd1978 |
c5e463b01a0e2c06917cd62f068e8d9829f89032 | 8,544 | cpp | C++ | third_party/WebKit/Source/core/loader/MixedContentCheckerTest.cpp | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/WebKit/Source/core/loader/MixedContentCheckerTest.cpp | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/WebKit/Source/core/loader/MixedContentCheckerTest.cpp | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2014 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 "core/loader/MixedContentChecker.h"
#include <base/macros.h>
#include <memory>
#include "core/frame/Settings.h"
#include "core/loader/EmptyClients.h"
#include "core/testing/DummyPageHolder.h"
#include "platform/loader/fetch/ResourceResponse.h"
#include "platform/weborigin/KURL.h"
#include "platform/weborigin/SecurityOrigin.h"
#include "platform/wtf/RefPtr.h"
#include "public/platform/WebMixedContent.h"
#include "public/platform/WebMixedContentContextType.h"
#include "testing/gmock/include/gmock/gmock-generated-function-mockers.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace blink {
// Tests that MixedContentChecker::isMixedContent correctly detects or ignores
// many cases where there is or there is not mixed content, respectively.
// Note: Renderer side version of
// MixedContentNavigationThrottleTest.IsMixedContent. Must be kept in sync
// manually!
TEST(MixedContentCheckerTest, IsMixedContent) {
struct TestCase {
const char* origin;
const char* target;
bool expectation;
} cases[] = {
{"http://example.com/foo", "http://example.com/foo", false},
{"http://example.com/foo", "https://example.com/foo", false},
{"http://example.com/foo", "data:text/html,<p>Hi!</p>", false},
{"http://example.com/foo", "about:blank", false},
{"https://example.com/foo", "https://example.com/foo", false},
{"https://example.com/foo", "wss://example.com/foo", false},
{"https://example.com/foo", "data:text/html,<p>Hi!</p>", false},
{"https://example.com/foo", "http://127.0.0.1/", false},
{"https://example.com/foo", "http://[::1]/", false},
{"https://example.com/foo", "blob:https://example.com/foo", false},
{"https://example.com/foo", "blob:http://example.com/foo", false},
{"https://example.com/foo", "blob:null/foo", false},
{"https://example.com/foo", "filesystem:https://example.com/foo", false},
{"https://example.com/foo", "filesystem:http://example.com/foo", false},
{"https://example.com/foo", "http://example.com/foo", true},
{"https://example.com/foo", "http://google.com/foo", true},
{"https://example.com/foo", "ws://example.com/foo", true},
{"https://example.com/foo", "ws://google.com/foo", true},
{"https://example.com/foo", "http://192.168.1.1/", true},
{"https://example.com/foo", "http://localhost/", true},
};
for (const auto& test : cases) {
SCOPED_TRACE(::testing::Message() << "Origin: " << test.origin
<< ", Target: " << test.target
<< ", Expectation: " << test.expectation);
KURL origin_url(NullURL(), test.origin);
RefPtr<SecurityOrigin> security_origin(SecurityOrigin::Create(origin_url));
KURL target_url(NullURL(), test.target);
EXPECT_EQ(test.expectation, MixedContentChecker::IsMixedContent(
security_origin.Get(), target_url));
}
}
TEST(MixedContentCheckerTest, ContextTypeForInspector) {
std::unique_ptr<DummyPageHolder> dummy_page_holder =
DummyPageHolder::Create(IntSize(1, 1));
dummy_page_holder->GetFrame().GetDocument()->SetSecurityOrigin(
SecurityOrigin::CreateFromString("http://example.test"));
ResourceRequest not_mixed_content("https://example.test/foo.jpg");
not_mixed_content.SetFrameType(WebURLRequest::kFrameTypeAuxiliary);
not_mixed_content.SetRequestContext(WebURLRequest::kRequestContextScript);
EXPECT_EQ(WebMixedContentContextType::kNotMixedContent,
MixedContentChecker::ContextTypeForInspector(
&dummy_page_holder->GetFrame(), not_mixed_content));
dummy_page_holder->GetFrame().GetDocument()->SetSecurityOrigin(
SecurityOrigin::CreateFromString("https://example.test"));
EXPECT_EQ(WebMixedContentContextType::kNotMixedContent,
MixedContentChecker::ContextTypeForInspector(
&dummy_page_holder->GetFrame(), not_mixed_content));
ResourceRequest blockable_mixed_content("http://example.test/foo.jpg");
blockable_mixed_content.SetFrameType(WebURLRequest::kFrameTypeAuxiliary);
blockable_mixed_content.SetRequestContext(
WebURLRequest::kRequestContextScript);
EXPECT_EQ(WebMixedContentContextType::kBlockable,
MixedContentChecker::ContextTypeForInspector(
&dummy_page_holder->GetFrame(), blockable_mixed_content));
ResourceRequest optionally_blockable_mixed_content(
"http://example.test/foo.jpg");
blockable_mixed_content.SetFrameType(WebURLRequest::kFrameTypeAuxiliary);
blockable_mixed_content.SetRequestContext(
WebURLRequest::kRequestContextImage);
EXPECT_EQ(WebMixedContentContextType::kOptionallyBlockable,
MixedContentChecker::ContextTypeForInspector(
&dummy_page_holder->GetFrame(), blockable_mixed_content));
}
namespace {
class MixedContentCheckerMockLocalFrameClient : public EmptyLocalFrameClient {
public:
MixedContentCheckerMockLocalFrameClient() : EmptyLocalFrameClient() {}
MOCK_METHOD0(DidContainInsecureFormAction, void());
MOCK_METHOD1(DidDisplayContentWithCertificateErrors, void(const KURL&));
MOCK_METHOD1(DidRunContentWithCertificateErrors, void(const KURL&));
};
} // namespace
TEST(MixedContentCheckerTest, HandleCertificateError) {
MixedContentCheckerMockLocalFrameClient* client =
new MixedContentCheckerMockLocalFrameClient;
std::unique_ptr<DummyPageHolder> dummy_page_holder =
DummyPageHolder::Create(IntSize(1, 1), nullptr, client);
KURL main_resource_url(NullURL(), "https://example.test");
KURL displayed_url(NullURL(), "https://example-displayed.test");
KURL ran_url(NullURL(), "https://example-ran.test");
dummy_page_holder->GetFrame().GetDocument()->SetURL(main_resource_url);
ResourceResponse response1;
response1.SetURL(ran_url);
EXPECT_CALL(*client, DidRunContentWithCertificateErrors(ran_url));
MixedContentChecker::HandleCertificateError(
&dummy_page_holder->GetFrame(), response1, WebURLRequest::kFrameTypeNone,
WebURLRequest::kRequestContextScript);
ResourceResponse response2;
WebURLRequest::RequestContext request_context =
WebURLRequest::kRequestContextImage;
ASSERT_EQ(
WebMixedContentContextType::kOptionallyBlockable,
WebMixedContent::ContextTypeFromRequestContext(
request_context, dummy_page_holder->GetFrame()
.GetSettings()
->GetStrictMixedContentCheckingForPlugin()));
response2.SetURL(displayed_url);
EXPECT_CALL(*client, DidDisplayContentWithCertificateErrors(displayed_url));
MixedContentChecker::HandleCertificateError(
&dummy_page_holder->GetFrame(), response2, WebURLRequest::kFrameTypeNone,
request_context);
}
TEST(MixedContentCheckerTest, DetectMixedForm) {
MixedContentCheckerMockLocalFrameClient* client =
new MixedContentCheckerMockLocalFrameClient;
std::unique_ptr<DummyPageHolder> dummy_page_holder =
DummyPageHolder::Create(IntSize(1, 1), nullptr, client);
KURL main_resource_url(NullURL(), "https://example.test/");
KURL http_form_action_url(NullURL(), "http://example-action.test/");
KURL https_form_action_url(NullURL(), "https://example-action.test/");
KURL javascript_form_action_url(NullURL(), "javascript:void(0);");
KURL mailto_form_action_url(NullURL(), "mailto:action@example-action.test");
dummy_page_holder->GetFrame().GetDocument()->SetSecurityOrigin(
SecurityOrigin::Create(main_resource_url));
// mailto and http are non-secure form targets.
EXPECT_CALL(*client, DidContainInsecureFormAction()).Times(2);
EXPECT_TRUE(MixedContentChecker::IsMixedFormAction(
&dummy_page_holder->GetFrame(), http_form_action_url,
SecurityViolationReportingPolicy::kSuppressReporting));
EXPECT_FALSE(MixedContentChecker::IsMixedFormAction(
&dummy_page_holder->GetFrame(), https_form_action_url,
SecurityViolationReportingPolicy::kSuppressReporting));
EXPECT_FALSE(MixedContentChecker::IsMixedFormAction(
&dummy_page_holder->GetFrame(), javascript_form_action_url,
SecurityViolationReportingPolicy::kSuppressReporting));
EXPECT_TRUE(MixedContentChecker::IsMixedFormAction(
&dummy_page_holder->GetFrame(), mailto_form_action_url,
SecurityViolationReportingPolicy::kSuppressReporting));
}
} // namespace blink
| 45.935484 | 80 | 0.72823 | metux |
c5e6927a84897e035464382bbce98ce647ae81a9 | 395 | cpp | C++ | round1/integration/main.cpp | ymadzhunkov/codeit | a013480ef39259bd282996d7d62296f089e708f4 | [
"MIT"
] | null | null | null | round1/integration/main.cpp | ymadzhunkov/codeit | a013480ef39259bd282996d7d62296f089e708f4 | [
"MIT"
] | null | null | null | round1/integration/main.cpp | ymadzhunkov/codeit | a013480ef39259bd282996d7d62296f089e708f4 | [
"MIT"
] | null | null | null | #include "keyboard.h"
#include "answer.h"
#include "simulated_annealing.h"
#include "progress.h"
int main(int argc, char *argv[]) {
Problem problem(fopen("keyboard.in", "r"));
Progress progress(2.8);
SimulatedAnnealing sa(problem, progress);
sa.optimize(1234);
sa.getBest().write(fopen("keyboard.out", "w"), problem);
progress.report(stdout);
return EXIT_SUCCESS;
}
| 26.333333 | 60 | 0.678481 | ymadzhunkov |
c5ea42f2091e276d7a67c5ef5bbe3bacbaf683f9 | 4,810 | cpp | C++ | SoftUni/C++Programming/4.Inheritance(extended)/4.Inheritance_ext_homework/Shop.cpp | NikolovV/CPP-Language | a0b31f3cff0a764fee21546073338b2ca7f99979 | [
"MIT"
] | null | null | null | SoftUni/C++Programming/4.Inheritance(extended)/4.Inheritance_ext_homework/Shop.cpp | NikolovV/CPP-Language | a0b31f3cff0a764fee21546073338b2ca7f99979 | [
"MIT"
] | null | null | null | SoftUni/C++Programming/4.Inheritance(extended)/4.Inheritance_ext_homework/Shop.cpp | NikolovV/CPP-Language | a0b31f3cff0a764fee21546073338b2ca7f99979 | [
"MIT"
] | null | null | null | #include <iosfwd>
#include "Shop.h"
Shop::Shop() : _shopName("CandyShop"), _BIC("123456789"),
_address("Somewhere in the middle of nowhere"),
ordinaryCustomer(NULL), shopItem(NULL)
{
}
Shop::Shop(string newName, string newBIC, string newAddress,
Customer *customer, vector<Item> *items)
: _shopName(newName), _BIC(newBIC), _address(newAddress),
ordinaryCustomer(customer), shopItem(items)
{
}
Shop::~Shop()
{
}
// setters
void Shop::set_name(string newName)
{
this->_shopName = newName;
}
void Shop::set_BIC(string newBIC)
{
this->_BIC = newBIC;
}
void Shop::set_address(string newAddress)
{
this->_address = newAddress;
}
void Shop::set_customer(Customer *customer)
{
this->ordinaryCustomer = customer;
}
void Shop::set_items(vector<Item> *item)
{
this->shopItem = item;
}
//getters
string Shop::get_name() const
{
return this->_shopName;
}
string Shop::get_BIC() const
{
return this->_BIC;
}
string Shop::get_address() const
{
return this->_address;
}
float Shop::get_customer_total() const
{
return ordinaryCustomer->get_total();
}
// methods
bool Shop::is_empty_items()
{
if (shopItem->empty())
{
return true;
}
return false;
}
void Shop::show_shop_info()
{
cout << get_name() << "\t" << get_BIC() << endl;
cout << get_address() << endl;
}
void Shop::add_item_to_base()
{
Item temp;
cout << "Enter product barcode: ";
string newBarcode;
cin >> newBarcode;
cin.get();
cin.clear();
fflush(stdin);
temp.set_barcode(newBarcode);
cout << "Enter product name: ";
string productName;
getline(cin, productName);
temp.set_product_name(productName);
cout << "Enter product price: ";
float price;
cin >> price;
temp.set_price(price);
shopItem->push_back(temp);
}
void Shop::print_shop_info()
{
cout << "\t\t\tINVOICE" << endl;
cout << "=========================================================" << endl;
cout << "Shop: " << get_name() << endl;
cout << "BIC: " << get_BIC() << endl;
cout << "Address: " << get_address() << endl;
cout << "=========================================================" << endl;
cout << *ordinaryCustomer;
cout << "=========================================================" << endl;
cout << "Total sum: " << ordinaryCustomer->get_total() << " leva" << endl;
if (ordinaryCustomer->get_total() == 0)
{
cout << "Would you bay something?" << endl;
}
if (ordinaryCustomer->get_change() == 0.0)
{
cout << "Customer doesn't finish shopping! ";
cout << "Please enter amount of money (option 'G')" << endl;
}
else
{
cout << "Change: " << ordinaryCustomer->get_change() << " leva" << endl;
}
}
// Variant 1.
void Shop::change_item_price()
{
if (is_empty_items())
{
cout << "No stock!" << endl;
return;
}
cout << "Enter product barcode: ";
string barcode;
cin >> barcode;
cin.get();
cin.clear();
fflush(stdin);
bool isFound = false;
for (int i = 0; i < shopItem->size(); i++)
{
// if (barcode.compare((*shopItem)[i].get_barcode()) == 0)
if (barcode.compare(shopItem->at(i).get_barcode()) == 0)
{
cout << "Old price: " << shopItem->at(i).get_price() << endl;
cout << "Enter new price: ";
float newPrice;
cin >> newPrice;
cin.get();
cin.clear();
fflush(stdin);
// (*shopItem)[i].set_price(newPrice);
shopItem->at(i).set_price(newPrice);
isFound = true;
break;
}
else if (!isFound && i == (shopItem->size() - 1))
{
cout << "Item cannot be found!" << endl;
}
}
}
void Shop::search_item()
{
if (is_empty_items())
{
cout << "No items, sorry. Come back when we get some stock." << endl;
return;
}
cout << "Enter 10-digit barcode: ";
string barcode;
getline(cin, barcode);
bool isFound = false;
for (int i = 0; i < shopItem->size(); i++)
{
// if (barcode.compare((*shopItem)[i].get_barcode()) == 0)
if (barcode.compare(shopItem->at(i).get_barcode()) == 0)
{
Item temp = shopItem->at(i);
ordinaryCustomer->add_to_invoice(temp);
float total = ordinaryCustomer->get_total();
// total += (*shopItem)[i].get_price();
total += shopItem->at(i).get_price();
ordinaryCustomer->set_total(total);
isFound = true;
// cout << customer << endl;
break;
}
else if (!isFound && i == (shopItem->size() - 1))
{
cout << "Item cannot be found!" << endl;
}
}
} | 23.349515 | 80 | 0.534719 | NikolovV |
c5eaeb476dc8c69d5770c7fa480e144243cd1ed7 | 1,902 | cpp | C++ | EngineGUI/FolderBrowser.cpp | openlastchaos/lastchaos-source-client | 3d88594dba7347b1bb45378136605e31f73a8555 | [
"Apache-2.0"
] | 1 | 2022-02-14T15:46:44.000Z | 2022-02-14T15:46:44.000Z | EngineGUI/FolderBrowser.cpp | openlastchaos/lastchaos-source-client | 3d88594dba7347b1bb45378136605e31f73a8555 | [
"Apache-2.0"
] | null | null | null | EngineGUI/FolderBrowser.cpp | openlastchaos/lastchaos-source-client | 3d88594dba7347b1bb45378136605e31f73a8555 | [
"Apache-2.0"
] | 2 | 2022-01-10T22:17:06.000Z | 2022-01-17T09:34:08.000Z | #include "stdh.h"
#include <shlobj.h>
static int CALLBACK BrowseCallbackProc(HWND hwnd,UINT uMsg,LPARAM lp, LPARAM pData)
{
TCHAR szDir[MAX_PATH];
switch(uMsg) {
case BFFM_INITIALIZED: {
SendMessage(hwnd,BFFM_SETSELECTION,TRUE,(LPARAM)pData);
break;
}
case BFFM_SELCHANGED: {
// enable or disable ok button if current dir is inside app path
if (SHGetPathFromIDList((LPITEMIDLIST) lp ,szDir)) {
CTFileName fnSelectedDir = (CTString)szDir + (CTString)"\\";
try {
fnSelectedDir.RemoveApplicationPath_t();
SendMessage(hwnd,BFFM_ENABLEOK ,0,TRUE);
} catch(char *) {
SendMessage(hwnd,BFFM_ENABLEOK ,0,FALSE);
}
return 0;
}
break;
}
}
return 0;
}
// Folder browse
ENGINEGUI_API BOOL CEngineGUI::BrowseForFolder(CTFileName &fnBrowsedFolder, CTString strDefaultDir, char *strWindowTitle/*="Choose folder"*/)
{
CTString fnFullRootDir = _fnmApplicationPath+strDefaultDir;
BROWSEINFO biBrowse;
memset(&biBrowse,0,sizeof(BROWSEINFO));
biBrowse.hwndOwner = AfxGetMainWnd()->m_hWnd;
biBrowse.pidlRoot = NULL;
biBrowse.pszDisplayName = NULL;
biBrowse.lpszTitle = strWindowTitle;
biBrowse.ulFlags = BIF_RETURNFSANCESTORS;
biBrowse.lpfn = BrowseCallbackProc;
biBrowse.lParam = (LPARAM)(const char*)fnFullRootDir;
// From msdn
ITEMIDLIST *pidl = SHBrowseForFolder(&biBrowse);
if(pidl!=NULL) {
char ach[MAX_PATH];
SHGetPathFromIDList(pidl, ach);
IMalloc *pm;
SHGetMalloc(&pm);
if(pm) {
pm->Free(pidl);
pm->Release();
}
CTFileName fnFullBrowsedDir = (CTString)ach + (CTString)"\\";
try {
fnFullBrowsedDir.RemoveApplicationPath_t();
fnBrowsedFolder = fnFullBrowsedDir;
return TRUE;
} catch(char *strErr) {
WarningMessage(strErr);
return FALSE;
}
} else {
return FALSE;
}
}
| 27.565217 | 141 | 0.666667 | openlastchaos |
c5eba0d073d8882945741c6aeb5c5be60c700c5e | 24,449 | cc | C++ | tests/unit/lb/test_lb_stats_comm.cc | rbuch/vt | 74c2e0cae3201dfbcbfda7644c354703ddaed6bb | [
"BSD-3-Clause"
] | 26 | 2019-11-26T08:36:15.000Z | 2022-02-15T17:13:21.000Z | tests/unit/lb/test_lb_stats_comm.cc | rbuch/vt | 74c2e0cae3201dfbcbfda7644c354703ddaed6bb | [
"BSD-3-Clause"
] | 1,215 | 2019-09-09T14:31:33.000Z | 2022-03-30T20:20:14.000Z | tests/unit/lb/test_lb_stats_comm.cc | rbuch/vt | 74c2e0cae3201dfbcbfda7644c354703ddaed6bb | [
"BSD-3-Clause"
] | 12 | 2019-09-08T00:03:05.000Z | 2022-02-23T21:28:35.000Z | /*
//@HEADER
// *****************************************************************************
//
// test_lb_stats_comm.cc
// DARMA/vt => Virtual Transport
//
// Copyright 2019-2021 National Technology & Engineering Solutions of Sandia, LLC
// (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, 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:
//
// * 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 copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
//
// Questions? Contact darma@sandia.gov
//
// *****************************************************************************
//@HEADER
*/
#include "test_parallel_harness.h"
#include <vt/transport.h>
#include <vt/utils/json/json_appender.h>
#include <vt/utils/json/json_reader.h>
#include <vt/utils/json/decompression_input_container.h>
#include <vt/utils/json/input_iterator.h>
#include <nlohmann/json.hpp>
#if vt_check_enabled(lblite)
namespace vt { namespace tests { namespace unit { namespace comm {
/**
* --------------------------------------
* Communication Record Summary
* --------------------------------------
* -------- || --------- Sender ---------
* Receiver || ColT | ObjGroup | Handler
* --------------------------------------
* ColT || R | R | R
* ObjGroup || S | S | S
* Handler || S | S | S
* --------------------------------------
*/
using TestLBStatsComm = TestParallelHarness;
using StatsData = vt::vrt::collection::balance::StatsData;
StatsData getStatsDataForPhase(vt::PhaseType phase) {
using JSONAppender = vt::util::json::Appender<std::stringstream>;
using vt::util::json::DecompressionInputContainer;
using vt::vrt::collection::balance::StatsData;
using json = nlohmann::json;
std::stringstream ss{std::ios_base::out | std::ios_base::in};
auto ap = std::make_unique<JSONAppender>("phases", std::move(ss), true);
auto j = vt::theNodeStats()->getStatsData()->toJson(phase);
ap->addElm(*j);
ss = ap->finish();
auto c = DecompressionInputContainer{
DecompressionInputContainer::AnyStreamTag{}, std::move(ss)
};
return StatsData{json::parse(c)};
}
namespace {
auto constexpr dim1 = 64;
auto constexpr num_sends = 4;
struct MyCol : vt::Collection<MyCol, vt::Index1D> { };
struct MyMsg : vt::CollectionMessage<MyCol> { double x, y, z; };
struct MyObjMsg : vt::Message { double x, y, z; };
struct ElementInfo {
using MapType = std::map<vt::Index1D, vt::elm::ElementIDStruct>;
ElementInfo() = default;
explicit ElementInfo(MapType in_map) : elms(in_map) { }
friend ElementInfo operator+(ElementInfo a1, ElementInfo const& a2) {
for (auto&& x : a2.elms) a1.elms.insert(x);
return a1;
}
template <typename SerializerT>
void serialize(SerializerT& s) {
s | elms;
}
MapType elms;
};
struct ReduceMsg : SerializeRequired<
vt::collective::ReduceTMsg<ElementInfo>, ReduceMsg
> {
using MessageParentType = SerializeRequired<
vt::collective::ReduceTMsg<ElementInfo>, ReduceMsg
>;
ReduceMsg() = default;
ReduceMsg(vt::Index1D idx, vt::elm::ElementIDStruct elm_id)
: MessageParentType(
ElementInfo{
std::map<vt::Index1D, vt::elm::ElementIDStruct>{{idx, elm_id}}
}
)
{ }
template <typename SerializerT>
void serialize(SerializerT& s) {
MessageParentType::serialize(s);
}
};
struct ColProxyMsg : vt::Message {
using ProxyType = vt::CollectionProxy<MyCol>;
ColProxyMsg(ProxyType in_proxy) : proxy(in_proxy) { }
ProxyType proxy;
};
struct ProxyMsg;
struct MyObj {
void dummyHandler(MyObjMsg* msg) {}
void simulateObjGroupColTSends(ColProxyMsg* msg);
void simulateObjGroupObjGroupSends(ProxyMsg* msg);
void simulateObjGroupHandlerSends(MyMsg* msg);
};
struct ProxyMsg : vt::CollectionMessage<MyCol> {
using ProxyType = vt::objgroup::proxy::Proxy<MyObj>;
ProxyMsg(ProxyType in_proxy) : obj_proxy(in_proxy) { }
ProxyType obj_proxy;
};
void handler2(MyMsg* msg, MyCol* col) {}
void MyObj::simulateObjGroupColTSends(ColProxyMsg* msg) {
auto proxy = msg->proxy;
auto this_node = theContext()->getNode();
auto num_nodes = theContext()->getNumNodes();
auto next = (this_node + 1) % num_nodes;
for (int i = 0; i < dim1; i++) {
vt::Index1D idx{i};
auto node = vt::theCollection()->getMappedNode(proxy, idx);
if (node == next) {
for (int j = 0; j < num_sends; j++) {
proxy(idx).template send<MyMsg, handler2>();
}
}
}
}
void MyObj::simulateObjGroupObjGroupSends(ProxyMsg* msg) {
auto obj_proxy = msg->obj_proxy;
auto this_node = theContext()->getNode();
auto num_nodes = theContext()->getNumNodes();
auto next = (this_node + 1) % num_nodes;
for (int i = 0; i < num_sends; i++) {
obj_proxy[next].template send<MyObjMsg, &MyObj::dummyHandler>();
}
}
void simulateColTColTSends(MyMsg* msg, MyCol* col) {
auto proxy = col->getCollectionProxy();
auto index = col->getIndex();
auto next = (index.x() + 1) % dim1;
for (int i = 0; i < num_sends; i++) {
proxy(next).template send<MyMsg, handler2>();
}
}
void simulateColTObjGroupSends(ProxyMsg* msg, MyCol* col) {
auto obj_proxy = msg->obj_proxy;
auto this_node = theContext()->getNode();
auto num_nodes = theContext()->getNumNodes();
auto next = (this_node + 1) % num_nodes;
for (int i = 0; i < num_sends; i++) {
obj_proxy[next].template send<MyObjMsg, &MyObj::dummyHandler>();
}
}
void bareDummyHandler(MyObjMsg* msg) {}
void simulateColTHandlerSends(MyMsg* msg, MyCol* col) {
auto this_node = theContext()->getNode();
auto num_nodes = theContext()->getNumNodes();
auto next = (this_node + 1) % num_nodes;
for (int i = 0; i < num_sends; i++) {
auto msg2 = makeMessage<MyObjMsg>();
vt::theMsg()->sendMsg<MyObjMsg, bareDummyHandler>(next, msg2);
}
}
void MyObj::simulateObjGroupHandlerSends(MyMsg* msg) {
auto this_node = theContext()->getNode();
auto num_nodes = theContext()->getNumNodes();
auto next = (this_node + 1) % num_nodes;
for (int i = 0; i < num_sends; i++) {
auto msg2 = makeMessage<MyObjMsg>();
vt::theMsg()->sendMsg<MyObjMsg, bareDummyHandler>(next, msg2);
}
}
void simulateHandlerColTSends(ColProxyMsg* msg) {
auto proxy = msg->proxy;
auto this_node = theContext()->getNode();
auto num_nodes = theContext()->getNumNodes();
auto next = (this_node + 1) % num_nodes;
for (int i = 0; i < dim1; i++) {
vt::Index1D idx{i};
auto node = vt::theCollection()->getMappedNode(proxy, idx);
if (node == next) {
for (int j = 0; j < num_sends; j++) {
proxy(idx).template send<MyMsg, handler2>();
}
}
}
}
void simulateHandlerObjGroupSends(ProxyMsg* msg) {
auto obj_proxy = msg->obj_proxy;
auto this_node = theContext()->getNode();
auto num_nodes = theContext()->getNumNodes();
auto next = (this_node + 1) % num_nodes;
for (int i = 0; i < num_sends; i++) {
obj_proxy[next].template send<MyObjMsg, &MyObj::dummyHandler>();
}
}
void simulateHandlerHandlerSends(MyMsg* msg) {
auto this_node = theContext()->getNode();
auto num_nodes = theContext()->getNumNodes();
auto next = (this_node + 1) % num_nodes;
for (int i = 0; i < num_sends; i++) {
auto msg2 = makeMessage<MyObjMsg>();
vt::theMsg()->sendMsg<MyObjMsg, bareDummyHandler>(next, msg2);
}
}
std::map<vt::Index1D, vt::elm::ElementIDStruct> all_elms;
auto idxToElmID = [](vt::Index1D i) -> vt::elm::ElementIDType {
return all_elms.find(i)->second.id;
};
void recvElementIDs(ReduceMsg* msg) { all_elms = msg->getVal().elms; }
void doReduce(MyMsg*, MyCol* col) {
auto proxy = col->getCollectionProxy();
auto index = col->getIndex();
auto cb = theCB()->makeBcast<ReduceMsg, recvElementIDs>();
auto msg = makeMessage<ReduceMsg>(index, col->getElmID());
proxy.reduce<vt::collective::PlusOp<ElementInfo>>(msg.get(), cb);
}
// ColT -> ColT, expected communication edge on receive side
TEST_F(TestLBStatsComm, test_lb_stats_comm_col_to_col_send) {
auto range = vt::Index1D{dim1};
auto proxy = vt::makeCollection<MyCol>()
.bounds(range)
.bulkInsert()
.wait();
vt::runInEpochCollective("simulateColTColTSends", [&]{
for (int i = 0; i < dim1; i++) {
if (proxy(i).tryGetLocalPtr()) {
proxy(i).invoke<MyMsg, simulateColTColTSends>();
}
}
});
vt::thePhase()->nextPhaseCollective();
vt::runInEpochCollective("doReduce", [&]{
for (int i = 0; i < dim1; i++) {
if (proxy(i).tryGetLocalPtr()) {
proxy(i).invoke<MyMsg, doReduce>();
}
}
});
vt::PhaseType phase = 0;
auto sd = getStatsDataForPhase(phase);
auto& comm = sd.node_comm_;
// Check that communication exists on the receive side as expected
for (int i = 0; i < dim1; i++) {
vt::Index1D idx{i};
auto prev_i = i-1 >= 0 ? i-1 : dim1-1;
vt::Index1D prev_idx{prev_i};
if (proxy(i).tryGetLocalPtr()) {
bool found = false;
for (auto&& x : comm) {
for (auto&& y : x.second) {
auto key = y.first;
auto vol = y.second;
if (key.to_.id == idxToElmID(idx)) {
EXPECT_TRUE(key.to_.isMigratable());
EXPECT_TRUE(key.from_.isMigratable());
EXPECT_EQ(key.from_.id, idxToElmID(prev_idx));
EXPECT_EQ(vol.bytes, sizeof(MyMsg) * num_sends);
EXPECT_EQ(vol.messages, num_sends);
found = true;
}
}
}
EXPECT_TRUE(found);
}
}
}
// ColT -> ObjGroup, expected communication edge on send side
TEST_F(TestLBStatsComm, test_lb_stats_comm_col_to_objgroup_send) {
auto range = vt::Index1D{dim1};
auto proxy = vt::makeCollection<MyCol>()
.bounds(range)
.bulkInsert()
.wait();
auto obj_proxy = vt::theObjGroup()->makeCollective<MyObj>();
vt::runInEpochCollective("simulateColTObjGroupSends", [&]{
for (int i = 0; i < dim1; i++) {
if (proxy(i).tryGetLocalPtr()) {
proxy(i).invoke<ProxyMsg, simulateColTObjGroupSends>(obj_proxy);
}
}
});
vt::thePhase()->nextPhaseCollective();
vt::runInEpochCollective("doReduce", [&]{
for (int i = 0; i < dim1; i++) {
if (proxy(i).tryGetLocalPtr()) {
proxy(i).invoke<MyMsg, doReduce>();
}
}
});
vt::PhaseType phase = 0;
auto sd = getStatsDataForPhase(phase);
auto& comm = sd.node_comm_;
auto this_node = theContext()->getNode();
auto num_nodes = theContext()->getNumNodes();
auto next = (this_node + 1) % num_nodes;
auto op = obj_proxy.getProxy();
// Check that communication exists on the send side as expected
for (int i = 0; i < dim1; i++) {
vt::Index1D idx{i};
if (proxy(i).tryGetLocalPtr()) {
bool found = false;
auto idb = vt::elm::ElmIDBits::createObjGroup(op, next).id;
for (auto&& x : comm) {
for (auto&& y : x.second) {
auto key = y.first;
auto vol = y.second;
if (key.from_.id == idxToElmID(idx) /*and key.to_.id == idb*/) {
EXPECT_TRUE(key.from_.isMigratable());
EXPECT_EQ(key.from_.id, idxToElmID(idx));
EXPECT_FALSE(key.to_.isMigratable());
EXPECT_EQ(key.to_.id, idb);
EXPECT_EQ(vol.bytes, sizeof(MyObjMsg) * num_sends);
EXPECT_EQ(vol.messages, num_sends);
found = true;
}
}
}
EXPECT_TRUE(found);
}
}
}
// ObjGroup -> ColT, expected communication edge on receive side
TEST_F(TestLBStatsComm, test_lb_stats_comm_objgroup_to_col_send) {
auto range = vt::Index1D{dim1};
auto proxy = vt::makeCollection<MyCol>()
.bounds(range)
.bulkInsert()
.wait();
auto obj_proxy = vt::theObjGroup()->makeCollective<MyObj>();
vt::runInEpochCollective("simulateObjGroupColTSends", [&]{
auto node = theContext()->getNode();
// @note: .invoke does not work here because it doesn't create the LBStats
// context!
obj_proxy(node).send<ColProxyMsg, &MyObj::simulateObjGroupColTSends>(proxy);
});
vt::thePhase()->nextPhaseCollective();
vt::runInEpochCollective("doReduce", [&]{
for (int i = 0; i < dim1; i++) {
if (proxy(i).tryGetLocalPtr()) {
proxy(i).invoke<MyMsg, doReduce>();
}
}
});
vt::PhaseType phase = 0;
auto sd = getStatsDataForPhase(phase);
auto& comm = sd.node_comm_;
auto this_node = theContext()->getNode();
auto num_nodes = theContext()->getNumNodes();
auto prev = this_node - 1 >= 0 ? this_node - 1 : num_nodes-1;
auto op = obj_proxy.getProxy();
// Check that communication exists on the receive side as expected
for (int i = 0; i < dim1; i++) {
vt::Index1D idx{i};
if (proxy(i).tryGetLocalPtr()) {
bool found = false;
for (auto&& x : comm) {
for (auto&& y : x.second) {
auto key = y.first;
auto vol = y.second;
if (key.to_.id == idxToElmID(idx)) {
EXPECT_TRUE(key.to_.isMigratable());
EXPECT_EQ(key.to_.id, idxToElmID(idx));
EXPECT_FALSE(key.from_.isMigratable());
EXPECT_EQ(key.from_.id, vt::elm::ElmIDBits::createObjGroup(op, prev).id);
EXPECT_EQ(vol.bytes, sizeof(MyMsg) * num_sends);
EXPECT_EQ(vol.messages, num_sends);
found = true;
}
}
}
EXPECT_TRUE(found);
}
}
}
// ObjGroup -> ObjGroup, expected communication edge on send side
TEST_F(TestLBStatsComm, test_lb_stats_comm_objgroup_to_objgroup_send) {
auto obj_proxy_a = vt::theObjGroup()->makeCollective<MyObj>();
auto obj_proxy_b = vt::theObjGroup()->makeCollective<MyObj>();
vt::runInEpochCollective("simulateObjGroupObjGroupSends", [&]{
auto node = theContext()->getNode();
// @note: .invoke does not work here because it doesn't create the LBStats
// context!
obj_proxy_a(node).send<ProxyMsg, &MyObj::simulateObjGroupObjGroupSends>(
obj_proxy_b
);
});
vt::thePhase()->nextPhaseCollective();
vt::PhaseType phase = 0;
auto sd = getStatsDataForPhase(phase);
auto& comm = sd.node_comm_;
auto this_node = theContext()->getNode();
auto num_nodes = theContext()->getNumNodes();
auto next = (this_node + 1) % num_nodes;
auto opa = obj_proxy_a.getProxy();
auto opb = obj_proxy_b.getProxy();
auto ida = vt::elm::ElmIDBits::createObjGroup(opa, this_node).id;
auto idb = vt::elm::ElmIDBits::createObjGroup(opb, next).id;
// Check that communication exists on the send side as expected
bool found = false;
for (auto&& x : comm) {
for (auto&& y : x.second) {
auto key = y.first;
auto vol = y.second;
if (key.from_.id == ida /*and key.to_.id == idb*/) {
EXPECT_FALSE(key.to_.isMigratable());
EXPECT_EQ(key.from_.id, ida);
EXPECT_FALSE(key.from_.isMigratable());
EXPECT_EQ(key.to_.id, idb);
EXPECT_EQ(vol.bytes, sizeof(MyObjMsg) * num_sends);
EXPECT_EQ(vol.messages, num_sends);
found = true;
}
}
}
EXPECT_TRUE(found);
}
// Handler -> ColT, expected communication edge on receive side
TEST_F(TestLBStatsComm, test_lb_stats_comm_handler_to_col_send) {
auto range = vt::Index1D{dim1};
auto proxy = vt::makeCollection<MyCol>()
.bounds(range)
.bulkInsert()
.wait();
vt::runInEpochCollective("simulateHandlerColTSends", [&]{
auto this_node = theContext()->getNode();
auto num_nodes = theContext()->getNumNodes();
auto next = (this_node + 1) % num_nodes;
auto msg = makeMessage<ColProxyMsg>(proxy);
theMsg()->sendMsg<ColProxyMsg, simulateHandlerColTSends>(next, msg);
});
vt::thePhase()->nextPhaseCollective();
vt::runInEpochCollective("doReduce", [&]{
for (int i = 0; i < dim1; i++) {
if (proxy(i).tryGetLocalPtr()) {
proxy(i).invoke<MyMsg, doReduce>();
}
}
});
vt::PhaseType phase = 0;
auto sd = getStatsDataForPhase(phase);
auto& comm = sd.node_comm_;
auto this_node = theContext()->getNode();
auto num_nodes = theContext()->getNumNodes();
auto prev = this_node - 1 >= 0 ? this_node - 1 : num_nodes-1;
// Check that communication exists on the receive side as expected
for (int i = 0; i < dim1; i++) {
vt::Index1D idx{i};
if (proxy(i).tryGetLocalPtr()) {
bool found = false;
for (auto&& x : comm) {
for (auto&& y : x.second) {
auto key = y.first;
auto vol = y.second;
if (key.to_.id == idxToElmID(idx)) {
EXPECT_TRUE(key.to_.isMigratable());
EXPECT_EQ(key.to_.id, idxToElmID(idx));
EXPECT_FALSE(key.from_.isMigratable());
EXPECT_EQ(key.from_.id, vt::elm::ElmIDBits::createBareHandler(prev).id);
EXPECT_EQ(vol.bytes, sizeof(MyMsg) * num_sends);
EXPECT_EQ(vol.messages, num_sends);
found = true;
}
}
}
EXPECT_TRUE(found);
}
}
}
// ColT -> Handler, expected communication edge on send side
TEST_F(TestLBStatsComm, test_lb_stats_comm_col_to_handler_send) {
auto range = vt::Index1D{dim1};
auto proxy = vt::makeCollection<MyCol>()
.bounds(range)
.bulkInsert()
.wait();
vt::runInEpochCollective("simulateColTHandlerSends", [&]{
for (int i = 0; i < dim1; i++) {
if (proxy(i).tryGetLocalPtr()) {
proxy(i).invoke<MyMsg, simulateColTHandlerSends>();
}
}
});
vt::thePhase()->nextPhaseCollective();
vt::runInEpochCollective("doReduce", [&]{
for (int i = 0; i < dim1; i++) {
if (proxy(i).tryGetLocalPtr()) {
proxy(i).invoke<MyMsg, doReduce>();
}
}
});
vt::PhaseType phase = 0;
auto sd = getStatsDataForPhase(phase);
auto& comm = sd.node_comm_;
auto this_node = theContext()->getNode();
auto num_nodes = theContext()->getNumNodes();
auto next = (this_node + 1) % num_nodes;
// Check that communication exists on the send side as expected
for (int i = 0; i < dim1; i++) {
vt::Index1D idx{i};
if (proxy(i).tryGetLocalPtr()) {
bool found = false;
for (auto&& x : comm) {
for (auto&& y : x.second) {
auto key = y.first;
auto vol = y.second;
fmt::print("from={}, to={}\n", key.from_, key.to_);
if (key.from_.id == idxToElmID(idx)) {
EXPECT_TRUE(key.from_.isMigratable());
EXPECT_EQ(key.from_.id, idxToElmID(idx));
EXPECT_FALSE(key.to_.isMigratable());
EXPECT_EQ(key.to_.id, vt::elm::ElmIDBits::createBareHandler(next).id);
EXPECT_EQ(vol.bytes, sizeof(MyObjMsg) * num_sends);
EXPECT_EQ(vol.messages, num_sends);
found = true;
}
}
}
EXPECT_TRUE(found);
}
}
}
// ObjGroup -> Handler, expected communication edge on send side
TEST_F(TestLBStatsComm, test_lb_stats_comm_objgroup_to_handler_send) {
auto obj_proxy_a = vt::theObjGroup()->makeCollective<MyObj>();
vt::runInEpochCollective("simulateObjGroupHandlerSends", [&]{
auto node = theContext()->getNode();
// @note: .invoke does not work here because it doesn't create the LBStats
// context!
obj_proxy_a(node).send<MyMsg, &MyObj::simulateObjGroupHandlerSends>();
});
vt::thePhase()->nextPhaseCollective();
vt::PhaseType phase = 0;
auto sd = getStatsDataForPhase(phase);
auto& comm = sd.node_comm_;
auto this_node = theContext()->getNode();
auto num_nodes = theContext()->getNumNodes();
auto next = (this_node + 1) % num_nodes;
auto opa = obj_proxy_a.getProxy();
auto ida = vt::elm::ElmIDBits::createObjGroup(opa, this_node).id;
// Check that communication exists on the send side as expected
bool found = false;
for (auto&& x : comm) {
for (auto&& y : x.second) {
auto key = y.first;
auto vol = y.second;
if (key.from_.id == ida) {
EXPECT_FALSE(key.to_.isMigratable());
EXPECT_EQ(key.to_.id, vt::elm::ElmIDBits::createBareHandler(next).id);
EXPECT_FALSE(key.from_.isMigratable());
EXPECT_EQ(vol.bytes, sizeof(MyObjMsg) * num_sends);
EXPECT_EQ(vol.messages, num_sends);
found = true;
}
}
}
EXPECT_TRUE(found);
}
// Handler -> ObjGroup, expected communication edge on send side
TEST_F(TestLBStatsComm, test_lb_stats_comm_handler_to_objgroup_send) {
auto obj_proxy_a = vt::theObjGroup()->makeCollective<MyObj>();
vt::runInEpochCollective("simulateHandlerObjGroupSends", [&]{
auto this_node = theContext()->getNode();
auto num_nodes = theContext()->getNumNodes();
auto next = (this_node + 1) % num_nodes;
auto msg = makeMessage<ProxyMsg>(obj_proxy_a);
theMsg()->sendMsg<ProxyMsg, simulateHandlerObjGroupSends>(next, msg);
});
vt::thePhase()->nextPhaseCollective();
vt::PhaseType phase = 0;
auto sd = getStatsDataForPhase(phase);
auto& comm = sd.node_comm_;
auto this_node = theContext()->getNode();
auto num_nodes = theContext()->getNumNodes();
auto next = (this_node + 1) % num_nodes;
auto opa = obj_proxy_a.getProxy();
auto ida = vt::elm::ElmIDBits::createObjGroup(opa, next).id;
// Check that communication exists on the send side as expected
bool found = false;
for (auto&& x : comm) {
for (auto&& y : x.second) {
auto key = y.first;
auto vol = y.second;
if (key.to_.id == ida) {
EXPECT_FALSE(key.to_.isMigratable());
EXPECT_EQ(key.from_.id, vt::elm::ElmIDBits::createBareHandler(this_node).id);
EXPECT_FALSE(key.from_.isMigratable());
EXPECT_EQ(vol.bytes, sizeof(MyObjMsg) * num_sends);
EXPECT_EQ(vol.messages, num_sends);
found = true;
}
}
}
EXPECT_TRUE(found);
}
// Handler -> Handler, expected communication edge on send side
TEST_F(TestLBStatsComm, test_lb_stats_comm_handler_to_handler_send) {
vt::runInEpochCollective("simulateHandlerHandlerSends", [&]{
auto this_node = theContext()->getNode();
auto num_nodes = theContext()->getNumNodes();
auto next = (this_node + 1) % num_nodes;
auto msg = makeMessage<MyMsg>();
theMsg()->sendMsg<MyMsg, simulateHandlerHandlerSends>(next, msg);
});
vt::thePhase()->nextPhaseCollective();
vt::PhaseType phase = 0;
auto sd = getStatsDataForPhase(phase);
auto& comm = sd.node_comm_;
auto this_node = theContext()->getNode();
auto num_nodes = theContext()->getNumNodes();
auto next = (this_node + 1) % num_nodes;
auto ida = vt::elm::ElmIDBits::createBareHandler(next).id;
auto idb = vt::elm::ElmIDBits::createBareHandler(this_node).id;
// Check that communication exists on the send side as expected
bool found = false;
for (auto&& x : comm) {
for (auto&& y : x.second) {
auto key = y.first;
auto vol = y.second;
if (key.to_.id == ida and key.from_.id == idb) {
EXPECT_FALSE(key.to_.isMigratable());
EXPECT_FALSE(key.from_.isMigratable());
EXPECT_GE(vol.bytes, sizeof(MyObjMsg) * num_sends);
EXPECT_GE(vol.messages, num_sends);
found = true;
}
}
}
EXPECT_TRUE(found);
}
} /* end anon namespace */
}}}} // end namespace vt::tests::unit::comm
#endif
| 32.55526 | 85 | 0.635282 | rbuch |
c5ef0b940689fea493d051625492c56319b38462 | 2,485 | hpp | C++ | oarphkit/ok/IArray-inl.hpp | pwais/oarphkit | e799e7904d5b374cb6b58cd06a42d05506e83d94 | [
"Apache-2.0"
] | 1 | 2016-07-11T08:38:52.000Z | 2016-07-11T08:38:52.000Z | oarphkit/ok/IArray-inl.hpp | pwais/oarphkit | e799e7904d5b374cb6b58cd06a42d05506e83d94 | [
"Apache-2.0"
] | null | null | null | oarphkit/ok/IArray-inl.hpp | pwais/oarphkit | e799e7904d5b374cb6b58cd06a42d05506e83d94 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2015 Maintainers of OarphKit
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OK_IARRAY_INL_HPP_
#define OK_IARRAY_INL_HPP_
#ifndef OK_IARRAY_HPP_
#error "Include IArray.hpp instead"
#endif
#include <sstream>
#include "ok/Demangle.hpp"
#include "ok/Stringify.hpp"
namespace ok {
template <typename T>
inline
IArray<T>::IArray(IArray<T> &&other)
: data_(other.data_),
size_(other.size_),
owner_(std::move(other.owner_)) {
other.data_ = nullptr;
other.size_ = 0;
}
template <typename T>
inline
IArray<T>& IArray<T>::operator=(IArray<T> &&other) {
if(owner_ && OK_LIKELY(owner_ != other.owner_)) {
owner_->Dispose();
owner_ = nullptr;
}
data_ = other.data_;
size_ = other.size_;
owner_ = std::move(other.owner_);
other.data_ = nullptr;
other.size_ = 0;
return *this;
}
template <typename T>
inline
IArray<T> IArray<T>::GetDeepCopy() const {
if (OK_UNLIKELY(IsEmpty())) { return IArray<T>(); }
IArray<T> cp = IArray<T>::Create(Size());
memcpy(cp.data_, data_, sizeof(T) * size_);
return cp;
}
template <typename T>
inline
std::string IArray<T>::ToString() const {
std::stringstream ss;
/*
* Build e.g. "IArray(sz:0;data=0xff;owner:1;vals: a, b, c )"
*/
ss << "IArray<" << DemangledName(typeid(T)) << ">(sz:" << Size();
// Aside: for nullptr, OSX prints "0x0" but Ubuntu
// prints "(nil)", so we normalize
if (IsEmpty()) {
ss << ";data:null";
} else {
ss << ";data:" << ((const void *) Data());
}
ss << ";owner:" << IsOwner() << ";vals: ";
// Print values
if (OK_LIKELY(!IsEmpty())) {
auto front_str = Stringify<ValueType>(Data()[0]);
if (front_str == strify::kOpaque) {
ss << "[opaque vals]";
} else {
ss << front_str;
for (size_t i = 1; i < Size(); ++i) {
ss << ", " << Stringify<ValueType>(Data()[i]);
}
}
}
ss << " )";
return ss.str();
}
} /* namespace ok */
#endif /* OK_IARRAY_INL_HPP_ */
| 22.387387 | 75 | 0.631388 | pwais |
c5f31b69144585a176889d448ff7d494a236d747 | 821 | cpp | C++ | judges/codeforces/exercises/new_year_and_north_pole.cpp | eduardonunes2525/competitive-programming | 0f6bdc573b4d03d1ed20a2b77ec5388dca1ee47b | [
"MIT"
] | null | null | null | judges/codeforces/exercises/new_year_and_north_pole.cpp | eduardonunes2525/competitive-programming | 0f6bdc573b4d03d1ed20a2b77ec5388dca1ee47b | [
"MIT"
] | 1 | 2018-10-17T11:53:02.000Z | 2018-10-17T11:54:42.000Z | judges/codeforces/exercises/new_year_and_north_pole.cpp | eduardonunes2525/competitive-programming | 0f6bdc573b4d03d1ed20a2b77ec5388dca1ee47b | [
"MIT"
] | 1 | 2018-10-17T12:14:04.000Z | 2018-10-17T12:14:04.000Z | #include<bits/stdc++.h>
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define what_is(x) cerr << #x << " is " << x << endl
#define REP(i,a,b) for (int i = a; i <= b; i++)
#define endl "\n"
using namespace std;
using ii = pair<int, int>;
using ll = long long;
#define xmax 40000LL
#define ymax 20000LL
int main(){
IOS;
ll n; cin >> n;
ll t; string s, last;
ll y = ymax;
bool b = true;
while(n--){
cin >> t >> s;
if((y == ymax and s!="South") or (y == 0 and s!="North")) { b = false; }
if(s == "South"){
y -= t;
if(y < 0) b = false;
}
else if(s == "North"){
y += t;
if(y > ymax) b = false;
}
}
((y==ymax) and b) ? cout << "YES" << endl : cout << "NO" << endl;
return 0;
}
| 21.051282 | 80 | 0.461632 | eduardonunes2525 |
c5f60941a7a64a234edec73f2130cb22451ed8c5 | 6,796 | cc | C++ | tests/native/cxx_object.cc | Natus/natus | 4074619edd45f1bb62a5561d08a64e9960b3d9e8 | [
"MIT"
] | 1 | 2015-11-05T03:19:22.000Z | 2015-11-05T03:19:22.000Z | tests/native/cxx_object.cc | Natus/natus | 4074619edd45f1bb62a5561d08a64e9960b3d9e8 | [
"MIT"
] | null | null | null | tests/native/cxx_object.cc | Natus/natus | 4074619edd45f1bb62a5561d08a64e9960b3d9e8 | [
"MIT"
] | null | null | null | #include "test.hh"
class TestClass : public Class {
virtual Value
del(Value& obj, Value& name)
{
assert(obj.borrowCValue());
assert(name.borrowCValue());
assert(obj.isObject());
assert(name.getType() == obj.getPrivateName<size_t>("type"));
return obj.getPrivateName<Value>("retval");
}
virtual Value
get(Value& obj, Value& name)
{
assert(obj.borrowCValue());
assert(name.borrowCValue());
assert(obj.isObject());
assert(name.getType() == obj.getPrivateName<size_t>("type"));
return obj.getPrivateName<Value>("retval");
}
virtual Value
set(Value& obj, Value& name, Value& value)
{
assert(obj.borrowCValue());
assert(name.borrowCValue());
assert(value.borrowCValue());
assert(obj.isObject());
assert(name.getType() == obj.getPrivateName<size_t>("type"));
return obj.getPrivateName<Value>("retval");
}
virtual Value
enumerate(Value& obj)
{
assert(obj.borrowCValue());
assert(obj.isObject());
return obj.getPrivateName<Value>("retval");
}
virtual Value
call(Value& obj, Value& ths, Value& args)
{
assert(obj.borrowCValue());
assert(ths.borrowCValue());
assert(args.borrowCValue());
assert(obj.isObject());
assert(args.isArray());
if (strcmp(obj.getEngineName(), "v8")) // Work around a bug in v8
assert(ths.isObject() || ths.isUndefined());
if (args.get("length").to<int>() == 0)
return obj.getPrivateName<Value>("retval");
return args[0];
}
virtual Class::Hooks
getHooks()
{
return Class::HookAll;
}
};
int
doTest(Value& global)
{
assert(!global.set("x", global.newObject(new TestClass())).isException());
Value x = global.get("x");
assert(x.isObject());
//// Check for bypass
x.setPrivateName<Value>("retval", NULL); // Ensure NULL
// Number, native
assert(x.setPrivateName("type", (void*) Value::TypeNumber));
assert(!x.set(0, 17).isException());
assert(!x.get(0).isException());
assert(x.get(0).to<int>() == 17);
assert(!x.del(0).isException());
assert(x.get(0).isUndefined());
// Number, eval
assert(!global.evaluate("x[0] = 17;").isException());
assert(!global.evaluate("x[0];").isException());
assert(global.evaluate("x[0];").to<int>() == 17);
assert(!global.evaluate("delete x[0];").isException());
assert(global.evaluate("x[0];").isUndefined());
// String, native
assert(x.setPrivateName("type", (void*) Value::TypeString));
assert(!x.set("foo", 17).isException());
assert(!x.get("foo").isException());
assert(x.get("foo").to<int>() == 17);
assert(!x.del("foo").isException());
assert(x.get("foo").isUndefined());
// String, eval
assert(!global.evaluate("x['foo'] = 17;").isException());
assert(!global.evaluate("x['foo'];").isException());
assert(global.evaluate("x['foo'];").to<int>() == 17);
assert(!global.evaluate("delete x['foo'];").isException());
assert(global.evaluate("x['foo'];").isUndefined());
//// Check for exception
assert(x.setPrivateName<Value>("retval", global.newString("error").toException()));
// Number, native
assert(x.setPrivateName("type", (void*) Value::TypeNumber));
assert(x.del(0).isException());
assert(x.get(0).isException());
assert(x.set(0, 0).isException());
// Number, eval
assert(global.evaluate("delete x[0];").isException());
assert(global.evaluate("x[0];").isException());
assert(global.evaluate("x[0] = 0;").isException());
// String, native
assert(x.setPrivateName("type", (void*) Value::TypeString));
assert(x.del("foo").isException());
assert(x.get("foo").isException());
assert(x.set("foo", 0).isException());
// String, eval
assert(global.evaluate("delete x['foo'];").isException());
assert(global.evaluate("x['foo'];").isException());
assert(global.evaluate("x['foo'] = 0;").isException());
//// Check for intercept
assert(x.setPrivateName<Value>("retval", global.newBoolean(true)));
// Number, native
assert(x.setPrivateName("type", (void*) Value::TypeNumber));
assert(!x.del(0).isException());
assert(x.get(0).isBoolean());
assert(x.get(0).to<bool>());
assert(!x.set(0, 0).isException());
// Number, eval
assert(!global.evaluate("delete x[0];").isException());
assert(global.evaluate("x[0];").isBoolean());
assert(global.evaluate("x[0];").to<bool>());
assert(!global.evaluate("x[0] = 0;").isException());
// String, native
assert(x.setPrivateName("type", (void*) Value::TypeString));
assert(!x.del("foo").isException());
assert(x.get("foo").isBoolean());
assert(x.get("foo").to<bool>());
assert(!x.set("foo", 0).isException());
// String, eval
assert(!global.evaluate("delete x['foo'];").isException());
assert(global.evaluate("x['foo'];").isBoolean());
assert(global.evaluate("x['foo'];").to<bool>());
assert(!global.evaluate("x['foo'] = 0;").isException());
//// Check for successful calls
// Call from C++
Value y = global.call("x", global.newArray().push(123));
assert(!y.isException());
assert(y.isNumber());
assert(y.to<int>() == 123);
// New from C++
y = global.callNew("x", global.newArray().push(global.newObject()));
assert(!y.isException());
assert(y.isObject());
// Call from JS
y = global.evaluate("x(123);");
assert(!y.isException());
assert(y.isNumber());
assert(y.to<int>() == 123);
// New from JS
y = global.evaluate("new x({});");
assert(!y.isException());
assert(y.isObject());
//// Check for exception calls
assert(x.setPrivateName<Value>("retval", global.newString("error").toException()));
// Call from C++
y = global.call("x");
assert(y.isString());
assert(y.isException());
// New from C++
y = global.callNew("x");
assert(y.isString());
assert(y.isException());
// Call from JS
y = global.evaluate("x();");
assert(y.isString());
assert(y.isException());
// New from JS
y = global.evaluate("new x();");
assert(y.isString());
assert(y.isException());
//// Check for NULL calls
assert(x.setPrivateName<Value>("retval", NULL));
// Ensure NULL
// Call from C++
y = global.call("x");
assert(y.isUndefined());
assert(y.isException());
// New from C++
y = global.callNew("x");
assert(y.isUndefined());
assert(y.isException());
// Call from JS
y = global.evaluate("x();");
assert(y.isUndefined());
assert(y.isException());
// New from JS
y = global.evaluate("new x();");
assert(y.isUndefined());
assert(y.isException());
// Enumerate
assert(x.setPrivateName<Value>("retval", x.newArray().push(5).push(10)));
y = x.enumerate();
assert(y.isArray());
assert(y.get("length").to<int>() == 2);
assert(y.get(0).to<int>() == 5);
assert(y.get(1).to<int>() == 10);
// Cleanup
assert(!global.del("x").isException());
assert(global.get("x").isUndefined());
return 0;
}
| 31.031963 | 85 | 0.626986 | Natus |
c5f87eedb016a33fa671c21be96f2bf102333aac | 128 | cc | C++ | source/code/programs/examples/jni/src/Main.cc | luxe/CodeLang-compiler | 78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a | [
"MIT"
] | 33 | 2019-05-30T07:43:32.000Z | 2021-12-30T13:12:32.000Z | source/code/programs/examples/jni/src/Main.cc | luxe/CodeLang-compiler | 78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a | [
"MIT"
] | 371 | 2019-05-16T15:23:50.000Z | 2021-09-04T15:45:27.000Z | source/code/programs/examples/jni/src/Main.cc | UniLang/compiler | c338ee92994600af801033a37dfb2f1a0c9ca897 | [
"MIT"
] | 6 | 2019-08-22T17:37:36.000Z | 2020-11-07T07:15:32.000Z | #include <jni.h>
#include <stdio.h>
#include "Main.h"
JNIEXPORT jint JNICALL Java_Main_foo(JNIEnv *, jobject) {
return 42;
} | 18.285714 | 57 | 0.703125 | luxe |
c5f8bff9b3bc4e32bb471e125ea7b44b7e064ef4 | 12,408 | cpp | C++ | OGLFrameworkLib/volumeScene/TransferFunctionGUI.cpp | dasmysh/OGLFrameworkLib_uulm | 36fd5e65d7fb028a07f9d4f95c543f27a23a7d24 | [
"MIT"
] | null | null | null | OGLFrameworkLib/volumeScene/TransferFunctionGUI.cpp | dasmysh/OGLFrameworkLib_uulm | 36fd5e65d7fb028a07f9d4f95c543f27a23a7d24 | [
"MIT"
] | null | null | null | OGLFrameworkLib/volumeScene/TransferFunctionGUI.cpp | dasmysh/OGLFrameworkLib_uulm | 36fd5e65d7fb028a07f9d4f95c543f27a23a7d24 | [
"MIT"
] | 1 | 2019-11-14T06:24:26.000Z | 2019-11-14T06:24:26.000Z | /**
* @file TransferFunctionGUI.cpp
* @author Sebastian Maisch <sebastian.maisch@uni-ulm.de>
* @date 2015.08.24
*
* @brief Definition of the transfer function GUI.
*/
#include "TransferFunctionGUI.h"
#include "app/ApplicationBase.h"
#include "gfx/glrenderer/GLTexture.h"
#include "gfx/glrenderer/GLUniformBuffer.h"
#include <glm/gtc/matrix_transform.hpp>
#include "app/GLWindow.h"
#include "gfx/glrenderer/ScreenQuadRenderable.h"
#include <imgui.h>
#include <boost/algorithm/string/predicate.hpp>
#include <GLFW/glfw3.h>
namespace cgu {
TransferFunctionGUI::TransferFunctionGUI(const glm::vec2& boxMin, const glm::vec2& boxMax, ApplicationBase* app) :
rectMin(boxMin), rectMax(boxMax),
quad(nullptr),
quadTex(nullptr),
tfTex(nullptr),
screenAlignedProg(std::move(app->GetGPUProgramManager()->GetResource("shader/gui/tfRenderGUI.vp|shader/gui/tfRenderGUI.fp"))),
screenAlignedTextureUniform(screenAlignedProg->GetUniformLocation("guiTex")),
selection(-1),
draggingSelection(false),
lastButtonAction(0),
tfProgram(std::move(app->GetGPUProgramManager()->GetResource("shader/gui/tfPicker.vp|shader/gui/tfPicker.fp"))),
orthoUBO(new GLUniformBuffer("tfOrthoProjection", sizeof(OrthoProjectionBuffer), app->GetUBOBindingPoints())),
tfVBO(0)
{
screenAlignedProg->BindUniformBlock("tfOrthoProjection", *app->GetUBOBindingPoints());
tfProgram->BindUniformBlock("tfOrthoProjection", *app->GetUBOBindingPoints());
std::array<glm::vec2, 4> quadVerts;
quadVerts[0] = glm::vec2(0.0f);
quadVerts[1] = glm::vec2(0.0f, 1.0f);
quadVerts[2] = glm::vec2(1.0f, 0.0f);
quadVerts[3] = glm::vec2(1.0f, 1.0f);
quad.reset(new ScreenQuadRenderable(quadVerts, screenAlignedProg));
// Create default control points for TF
tf::ControlPoint p0, p1;
p0.SetColor(glm::vec3(0));
p0.SetPos(glm::vec2(0));
p1.SetColor(glm::vec3(1));
p1.SetPos(glm::vec2(1));
tf_.InsertControlPoint(p0);
tf_.InsertControlPoint(p1);
// Create texture and update it
tfTex.reset(new GLTexture(TEX_RES, TextureDescriptor(32, GL_RGBA8, GL_RGBA, GL_FLOAT)));
UpdateTexture();
// Create BG texture
std::vector<glm::vec4> texContent(TEX_RES * (TEX_RES / 2), glm::vec4(0.2f));
quadTex.reset(new GLTexture(TEX_RES, TEX_RES / 2, TextureDescriptor(32, GL_RGBA8, GL_RGBA, GL_FLOAT), texContent.data()));
UpdateTF(true);
Resize(glm::uvec2(app->GetWindow()->GetWidth(), app->GetWindow()->GetHeight()));
}
TransferFunctionGUI::~TransferFunctionGUI() = default;
void TransferFunctionGUI::Resize(const glm::uvec2& screenSize)
{
auto left = -rectMin.x / (rectMax.x - rectMin.x);
auto right = (static_cast<float>(screenSize.x) - rectMin.x) / (rectMax.x - rectMin.x);
auto bottom = (static_cast<float>(screenSize.y) - rectMin.y) / (rectMax.y - rectMin.y);
auto top = -rectMin.y / (rectMax.y - rectMin.y);
orthoBuffer.orthoMatrix = glm::ortho(left, right, bottom, top, 1.0f, -1.0f);
orthoUBO->UploadData(0, sizeof(OrthoProjectionBuffer), &orthoBuffer);
}
void TransferFunctionGUI::Draw()
{
glDisable(GL_DEPTH_TEST);
glDepthMask(GL_FALSE);
orthoUBO->BindBuffer();
screenAlignedProg->UseProgram();
quadTex->ActivateTexture(GL_TEXTURE0);
screenAlignedProg->SetUniform(screenAlignedTextureUniform, 0);
quad->Draw();// RenderGeometry();
// draw
glPointSize(0.5f * pickRadius);
tfProgram->UseProgram();
attribBind->EnableVertexAttributeArray();
// draw function
glDrawArrays(GL_LINE_STRIP, 0, static_cast<GLsizei>((tf_.points().size() + 2)));
// draw points
glDrawArrays(GL_POINTS, 1, static_cast<GLsizei>(tf_.points().size()));
// draw selection
if (selection != -1) {
glPointSize(0.8f * pickRadius);
glDrawArrays(GL_POINTS, selection + 1, static_cast<GLsizei>(1));
}
attribBind->DisableVertexAttributeArray();
glDepthMask(GL_TRUE);
glEnable(GL_DEPTH_TEST);
ImGui::SetNextWindowSize(ImVec2(rectMax.x - rectMin.x, 115), ImGuiSetCond_FirstUseEver);
ImGui::SetNextWindowPos(ImVec2(rectMin.x, rectMax.y + 10.0f), ImGuiSetCond_FirstUseEver);
ImGui::Begin("PickColor");
if (selection != -1) {
auto selectionColor = tf_.points()[selection].GetColor();
if (ImGui::ColorEdit3("Point Color", reinterpret_cast<float*>(&selectionColor))) {
tf_.points()[selection].SetColor(selectionColor);
UpdateTF();
}
}
std::array<char, 1024> tmpFilename;
auto lastPos = saveTFFilename.copy(tmpFilename.data(), 1023, 0);
tmpFilename[lastPos] = '\0';
if (ImGui::InputText("TF Filename", tmpFilename.data(), tmpFilename.size())) {
saveTFFilename = tmpFilename.data();
}
if (ImGui::Button("Save TF")) {
SaveTransferFunction();
}
if (ImGui::Button("Load TF")) {
LoadTransferFunction(saveTFFilename);
}
if (ImGui::Button("Init TF High Freq")) {
InitTF(1.0f / 16.0f);
}
if (ImGui::Button("Init TF Low Freq")) {
InitTF(1.0f / 4.0f);
}
ImGui::End();
}
void TransferFunctionGUI::LoadTransferFunction(const std::string& filename)
{
saveTFFilename = filename;
tf_.LoadFromFile(saveTFFilename + ".tf");
UpdateTF();
}
const std::string& TransferFunctionGUI::SaveTransferFunction() const
{
tf_.SaveToFile(saveTFFilename + ".tf");
return saveTFFilename;
}
bool TransferFunctionGUI::HandleMouse(int button, int action, int mods, float mouseWheelDelta, GLWindow* sender)
{
auto handled = false;
if (selection == -1) draggingSelection = false;
// if (buttonAction == 0 && !draggingSelection) return handled;
glm::vec2 screenSize(static_cast<float>(sender->GetWidth()), static_cast<float>(sender->GetHeight()));
auto pickSize = glm::vec2(pickRadius) / screenSize;
auto mouseCoords = sender->GetMousePosition();
// calculate relative points
auto relCoords = (mouseCoords - rectMin) / (rectMax - rectMin);
relCoords.y = 1.0f - relCoords.y;
// relCoords.y = glm::log((relCoords.y * (scaleBase - 1.0f)) + 1.0f) / glm::log(scaleBase);
relCoords.y = (glm::pow(scaleBase, relCoords.y) - 1.0f) / (scaleBase - 1.0f);
if (draggingSelection) {
relCoords = glm::clamp(relCoords, glm::vec2(0.0f), glm::vec2(1.0f));
// update selected point position
selection = tf_.SetPosition(selection, relCoords);
UpdateTF();
// check for drop
if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_RELEASE) draggingSelection = false;
return true;
}
const auto SEL_RAD2 = (pickRadius / (rectMax.x - rectMin.x)) * (pickRadius / (rectMax.y - rectMin.y));
if (relCoords.x >= -SEL_RAD2 && relCoords.y >= -SEL_RAD2 && relCoords.x <= 1.0f + SEL_RAD2 && relCoords.y <= 1.0f + SEL_RAD2)
{
// left click: select point or start dragging
if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) {
auto oldSelection = selection;
if (SelectPoint(relCoords, pickSize) && selection != -1 && selection == oldSelection) draggingSelection = true;
}
// right click: delete old point
if (button == GLFW_MOUSE_BUTTON_RIGHT && action == GLFW_PRESS && RemovePoint(relCoords, pickSize)) {
UpdateTF();
}
// middle click: new point
if (button == GLFW_MOUSE_BUTTON_MIDDLE && action == GLFW_PRESS && AddPoint(relCoords, pickSize)) {
UpdateTF();
}
handled = true;
}
return handled;
}
bool TransferFunctionGUI::SelectPoint(const glm::vec2& position, const glm::vec2&)
{
selection = GetControlPoint(position);
return selection != -1;
}
bool TransferFunctionGUI::AddPoint(const glm::vec2& position, const glm::vec2&)
{
auto i = GetControlPoint(position);
selection = i;
if (i == -1 && Overlap(position)) {
tf::ControlPoint p;
p.SetPos(position);
p.SetColor(glm::vec3(tf_.RGBA(p.val)));
tf_.InsertControlPoint(p);
selection = GetControlPoint(position);
draggingSelection = false;
return true;
}
draggingSelection = true;
return false;
}
bool TransferFunctionGUI::RemovePoint(const glm::vec2& position, const glm::vec2&)
{
auto i = GetControlPoint(position);
if (i > -1) {
tf_.RemoveControlPoint(i);
selection = -1;
return true;
}
return false;
}
void TransferFunctionGUI::InitTF(float freq)
{
tf_.InitWithFreqRGBA(freq / 2.0f, 1.0f - freq / 2.0f, 1.0f / ((1.0f / freq) + 1.0f), 0.1f);
UpdateTF();
}
void TransferFunctionGUI::LoadTransferFunctionFromFile(const std::string& filename)
{
if (boost::algorithm::ends_with(filename, ".tf")) saveTFFilename = filename.substr(0, filename.find_last_of("."));
else saveTFFilename = filename;
tf_.LoadFromFile(saveTFFilename + ".tf");
UpdateTF();
}
void TransferFunctionGUI::UpdateTF(bool createVAO)
{
if (createVAO) tfVBO = std::move(BufferRAII());
OGL_CALL(glBindBuffer, GL_ARRAY_BUFFER, tfVBO);
OGL_CALL(glBufferData, GL_ARRAY_BUFFER, (tf_.points().size() + 2) * sizeof(tf::ControlPoint),
nullptr, GL_DYNAMIC_DRAW);
auto tmpPoints = tf_.points();
for (auto& pt : tmpPoints) {
auto pos = pt.GetPos();
pos.y = glm::log((pos.y * (scaleBase - 1.0f)) + 1.0f) / glm::log(scaleBase);
pt.SetPos(pos);
}
tf::ControlPoint first, last;
first = tmpPoints[0];
first.SetValue(0.0f);
last = tmpPoints.back();
last.SetValue(1.0f);
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(tf::ControlPoint), &first);
glBufferSubData(GL_ARRAY_BUFFER, sizeof(tf::ControlPoint), tmpPoints.size() * sizeof(tf::ControlPoint), tmpPoints.data());
glBufferSubData(GL_ARRAY_BUFFER, (tmpPoints.size() + 1) * sizeof(tf::ControlPoint), sizeof(tf::ControlPoint), &last);
if (createVAO) {
auto loc = tfProgram->GetAttributeLocations({ "value", "color" });
attribBind = tfProgram->CreateVertexAttributeArray(tfVBO, 0);
attribBind->StartAttributeSetup();
attribBind->AddVertexAttribute(loc[0], 1, GL_FLOAT, GL_FALSE, sizeof(tf::ControlPoint), 0);
attribBind->AddVertexAttribute(loc[1], 4, GL_FLOAT, GL_FALSE, sizeof(tf::ControlPoint), sizeof(float));
attribBind->EndAttributeSetup();
} else {
attribBind->UpdateVertexAttributes();
}
UpdateTexture();
}
void TransferFunctionGUI::UpdateTexture() const
{
std::array<glm::vec4, TEX_RES> texData;
tf_.CreateTextureData(texData.data(), TEX_RES);
tfTex->SetData(texData.data());
}
// Gets an index to a control point if found within radii of mouse_pos
int TransferFunctionGUI::GetControlPoint(const glm::vec2& mouse_pos)
{
const auto SEL_RAD2 = (pickRadius / (rectMax.x - rectMin.x)) * (pickRadius / (rectMax.y - rectMin.y));
auto curSelectDist2 = SEL_RAD2 * 2.0f;
auto curSel = -1;
for (auto i = 0; i < static_cast<int>(tf_.points().size()); ++i) {
auto p = tf_.points()[i].GetPos();
// p.y = 1.f - p.y;
// glm::vec2 pos = p * (rectMax - rectMin) + rectMin;
auto d = mouse_pos - p;
auto dist2 = d.x * d.x + d.y * d.y;
if (dist2 < SEL_RAD2 && dist2 < curSelectDist2) {
curSelectDist2 = dist2;
curSel = i;
}
}
return curSel;
}
}
| 38.178462 | 134 | 0.603482 | dasmysh |
c5fccebb686264bc1f68372fd87182218f3b5cc6 | 3,718 | cpp | C++ | src/devices/bus/nscsi/s1410.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 26 | 2015-03-31T06:25:51.000Z | 2021-12-14T09:29:04.000Z | src/devices/bus/nscsi/s1410.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | null | null | null | src/devices/bus/nscsi/s1410.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 10 | 2015-03-27T05:45:51.000Z | 2022-02-04T06:57:36.000Z | // license:BSD-3-Clause
// copyright-holders:Olivier Galibert
#include "emu.h"
#include "bus/nscsi/s1410.h"
#define LOG_GENERAL (1U << 0)
#define LOG_COMMAND (1U << 1)
#define LOG_DATA (1U << 2)
#define VERBOSE 0
#include "logmacro.h"
DEFINE_DEVICE_TYPE(NSCSI_S1410, nscsi_s1410_device, "scsi_s1410", "Xebec S1410 5.25 Inch Winchester Disk Controller")
nscsi_s1410_device::nscsi_s1410_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) :
nscsi_harddisk_device(mconfig, NSCSI_S1410, tag, owner, clock)
{
}
void nscsi_s1410_device::device_reset()
{
nscsi_harddisk_device::device_reset();
// initialize drive characteristics
params[0] = 0;
params[1] = 153;
params[2] = 4;
params[3] = 0;
params[4] = 128;
params[5] = 0;
params[6] = 64;
params[7] = 11;
}
void nscsi_s1410_device::scsi_command()
{
switch(scsi_cmdbuf[0]) {
case SC_TEST_UNIT_READY:
case SC_REZERO:
case SC_FORMAT_UNIT: // TODO does not support starting LBA
case SC_REQUEST_SENSE:
case SC_REASSIGN_BLOCKS:
case SC_READ:
case SC_WRITE:
case SC_SEEK:
if (scsi_cmdbuf[1] >> 5) {
scsi_status_complete(SS_NOT_READY);
} else {
nscsi_harddisk_device::scsi_command();
}
break;
case SC_FORMAT_TRACK: {
if (scsi_cmdbuf[1] >> 5) {
scsi_status_complete(SS_NOT_READY);
return;
}
lba = ((scsi_cmdbuf[1] & 0x1f)<<16) | (scsi_cmdbuf[2]<<8) | scsi_cmdbuf[3];
blocks = (bytes_per_sector == 256) ? 32 : 17;
int track_length = blocks*bytes_per_sector;
std::vector<uint8_t> data(track_length);
memset(&data[0], 0xc6, track_length);
if(!hard_disk_write(harddisk, lba, &data[0])) {
logerror("%s: HD WRITE ERROR !\n", tag());
scsi_status_complete(SS_FORMAT_ERROR);
} else {
scsi_status_complete(SS_GOOD);
}
}
break;
case SC_FORMAT_ALT_TRACK:
if (scsi_cmdbuf[1] >> 5) {
scsi_status_complete(SS_NOT_READY);
return;
}
scsi_data_out(2, 3);
scsi_status_complete(SS_GOOD);
break;
case SC_INIT_DRIVE_PARAMS:
scsi_data_out(2, 8);
scsi_status_complete(SS_GOOD);
break;
case SC_WRITE_SECTOR_BUFFER:
scsi_data_out(2, 512);
scsi_status_complete(SS_GOOD);
break;
case SC_READ_SECTOR_BUFFER:
scsi_data_in(2, 512);
scsi_status_complete(SS_GOOD);
break;
case SC_CHECK_TRACK_FORMAT:
if (scsi_cmdbuf[1] >> 5) {
scsi_status_complete(SS_NOT_READY);
return;
}
scsi_status_complete(SS_GOOD);
break;
case SC_READ_ECC_BURST:
case SC_RAM_DIAG:
case SC_DRIVE_DIAG:
case SC_CONTROLLER_DIAG:
case SC_READ_LONG:
case SC_WRITE_LONG:
scsi_status_complete(SS_GOOD);
break;
default:
logerror("%s: command %02x ***UNKNOWN***\n", tag(), scsi_cmdbuf[0]);
break;
}
}
uint8_t nscsi_s1410_device::scsi_get_data(int id, int pos)
{
switch(scsi_cmdbuf[0]) {
case SC_READ_SECTOR_BUFFER:
return block[pos];
default:
return nscsi_harddisk_device::scsi_get_data(id, pos);
}
}
void nscsi_s1410_device::scsi_put_data(int id, int pos, uint8_t data)
{
if(id != 2 && !pos) {
return nscsi_harddisk_device::scsi_put_data(id, pos, data);
}
switch(scsi_cmdbuf[0]) {
case SC_FORMAT_ALT_TRACK:
LOGMASKED(LOG_DATA, "s1410: scsi_put_data, id:%d pos:%d data:%02x %c\n", id, pos, data, data >= 0x20 && data < 0x7f ? (char)data : ' ');
break;
case SC_INIT_DRIVE_PARAMS:
LOGMASKED(LOG_DATA, "s1410: scsi_put_data, id:%d pos:%d data:%02x %c\n", id, pos, data, data >= 0x20 && data < 0x7f ? (char)data : ' ');
params[pos] = data;
break;
case SC_WRITE_SECTOR_BUFFER:
LOGMASKED(LOG_DATA, "s1410: scsi_put_data, id:%d pos:%d data:%02x %c\n", id, pos, data, data >= 0x20 && data < 0x7f ? (char)data : ' ');
block[pos] = data;
break;
default:
return nscsi_harddisk_device::scsi_put_data(id, pos, data);
}
}
| 23.2375 | 138 | 0.702528 | Robbbert |
c5fd6f7fe3fdd5aecac37c1733e3b4a978584371 | 7,161 | cpp | C++ | src/Surface/VolInt.cpp | squarefk/spheretree-fixed | 79ec91538030a271f7aba16e22dc20c9ebb63444 | [
"Unlicense"
] | 17 | 2016-08-12T13:15:41.000Z | 2021-11-11T10:03:48.000Z | src/Surface/VolInt.cpp | squarefk/spheretree-fixed | 79ec91538030a271f7aba16e22dc20c9ebb63444 | [
"Unlicense"
] | null | null | null | src/Surface/VolInt.cpp | squarefk/spheretree-fixed | 79ec91538030a271f7aba16e22dc20c9ebb63444 | [
"Unlicense"
] | 9 | 2016-04-26T16:15:45.000Z | 2020-10-29T00:12:12.000Z |
/*******************************************************
* *
* volInt.c *
* *
* This code computes volume integrals needed for *
* determining mass properties of polyhedral bodies. *
* *
* For more information, see the accompanying README *
* file, and the paper *
* *
* Brian Mirtich, "Fast and Accurate Computation of *
* Polyhedral Mass Properties," journal of graphics *
* tools, volume 1, number 2, 1996. *
* *
* This source code is public domain, and may be used *
* in any way, shape or form, free of charge. *
* *
* Copyright 1995 by Brian Mirtich *
* *
* mirtich@cs.berkeley.edu *
* http://www.cs.berkeley.edu/~mirtich *
* *
*******************************************************/
/*
Revision history
26 Jan 1996 Program creation.
3 Aug 1996 Corrected bug arising when polyhedron density
is not 1.0. Changes confined to function main().
Thanks to Zoran Popovic for catching this one.
27 May 1997 Corrected sign error in translation of inertia
product terms to center of mass frame. Changes
confined to function main(). Thanks to
Chris Hecker.
*/
#include "VolInt.h"
#define X 0
#define Y 1
#define Z 2
#define SQR(x) ((x)*(x))
#define CUBE(x) ((x)*(x)*(x))
// globals
namespace VolInt_Globals{
static int A; /* alpha */
static int B; /* beta */
static int C; /* gamma */
/* projection integrals */
static double P1, Pa, Pb, Paa, Pab, Pbb, Paaa, Paab, Pabb, Pbbb;
/* face integrals */
static double Fa, Fb, Fc, Faa, Fbb, Fcc, Faaa, Fbbb, Fccc, Faab, Fbbc, Fcca;
/* volume integrals */
static double T0, T1[3], T2[3], TP[3];
};
/* compute various integrations over projection of face */
void compProjectionIntegrals(const Surface &sur, int face){
using namespace VolInt_Globals;
double a0, a1, da;
double b0, b1, db;
double a0_2, a0_3, a0_4, b0_2, b0_3, b0_4;
double a1_2, a1_3, b1_2, b1_3;
double C1, Ca, Caa, Caaa, Cb, Cbb, Cbbb;
double Cab, Kab, Caab, Kaab, Cabb, Kabb;
int i;
P1 = Pa = Pb = Paa = Pab = Pbb = Paaa = Paab = Pabb = Pbbb = 0.0;
// make face into arrays
struct Face{
double verts[3][3];
}FACE;
const Surface::Triangle *tri = &sur.triangles.index(face);
for (i = 0; i < 3; i++){
const Point3D *p = &sur.vertices.index(tri->v[i]).p;
FACE.verts[i][0] = p->x;
FACE.verts[i][1] = p->y;
FACE.verts[i][2] = p->z;
}
// do his stuff
for (i = 0; i < 3; i++) {
a0 = FACE.verts[i][A];
b0 = FACE.verts[i][B];
a1 = FACE.verts[(i+1) % 3][A];
b1 = FACE.verts[(i+1) % 3][B];
da = a1 - a0;
db = b1 - b0;
a0_2 = a0 * a0; a0_3 = a0_2 * a0; a0_4 = a0_3 * a0;
b0_2 = b0 * b0; b0_3 = b0_2 * b0; b0_4 = b0_3 * b0;
a1_2 = a1 * a1; a1_3 = a1_2 * a1;
b1_2 = b1 * b1; b1_3 = b1_2 * b1;
C1 = a1 + a0;
Ca = a1*C1 + a0_2; Caa = a1*Ca + a0_3; Caaa = a1*Caa + a0_4;
Cb = b1*(b1 + b0) + b0_2; Cbb = b1*Cb + b0_3; Cbbb = b1*Cbb + b0_4;
Cab = 3*a1_2 + 2*a1*a0 + a0_2; Kab = a1_2 + 2*a1*a0 + 3*a0_2;
Caab = a0*Cab + 4*a1_3; Kaab = a1*Kab + 4*a0_3;
Cabb = 4*b1_3 + 3*b1_2*b0 + 2*b1*b0_2 + b0_3;
Kabb = b1_3 + 2*b1_2*b0 + 3*b1*b0_2 + 4*b0_3;
P1 += db*C1;
Pa += db*Ca;
Paa += db*Caa;
Paaa += db*Caaa;
Pb += da*Cb;
Pbb += da*Cbb;
Pbbb += da*Cbbb;
Pab += db*(b1*Cab + b0*Kab);
Paab += db*(b1*Caab + b0*Kaab);
Pabb += da*(a1*Cabb + a0*Kabb);
}
P1 /= 2.0;
Pa /= 6.0;
Paa /= 12.0;
Paaa /= 20.0;
Pb /= -6.0;
Pbb /= -12.0;
Pbbb /= -20.0;
Pab /= 24.0;
Paab /= 60.0;
Pabb /= -60.0;
}
void compFaceIntegrals(const Surface &sur, int FACE_NUM, double *n)
{
using namespace VolInt_Globals;
double k1, k2, k3, k4;
compProjectionIntegrals(sur, FACE_NUM);
Point3D vert = sur.vertices.index(sur.triangles.index(FACE_NUM).v[0]).p;
double w = - n[X] * vert.x - n[Y] * vert.y - n[Z] * vert.z;
k1 = 1 / n[C]; k2 = k1 * k1; k3 = k2 * k1; k4 = k3 * k1;
Fa = k1 * Pa;
Fb = k1 * Pb;
Fc = -k2 * (n[A]*Pa + n[B]*Pb + w*P1);
Faa = k1 * Paa;
Fbb = k1 * Pbb;
Fcc = k3 * (SQR(n[A])*Paa + 2*n[A]*n[B]*Pab + SQR(n[B])*Pbb
+ w*(2*(n[A]*Pa + n[B]*Pb) + w*P1));
Faaa = k1 * Paaa;
Fbbb = k1 * Pbbb;
Fccc = -k4 * (CUBE(n[A])*Paaa + 3*SQR(n[A])*n[B]*Paab
+ 3*n[A]*SQR(n[B])*Pabb + CUBE(n[B])*Pbbb
+ 3*w*(SQR(n[A])*Paa + 2*n[A]*n[B]*Pab + SQR(n[B])*Pbb)
+ w*w*(3*(n[A]*Pa + n[B]*Pb) + w*P1));
Faab = k1 * Paab;
Fbbc = -k2 * (n[A]*Pabb + n[B]*Pbbb + w*Pbb);
Fcca = k3 * (SQR(n[A])*Paaa + 2*n[A]*n[B]*Paab + SQR(n[B])*Pabb
+ w*(2*(n[A]*Paa + n[B]*Pab) + w*Pa));
}
void compVolumeIntegrals(const Surface &sur){
using namespace VolInt_Globals;
double nx, ny, nz;
int i;
T0 = T1[X] = T1[Y] = T1[Z]
= T2[X] = T2[Y] = T2[Z]
= TP[X] = TP[Y] = TP[Z] = 0;
int numTri = sur.triangles.getSize();
for (i = 0; i < numTri ; i++) {
Vector3D v;
sur.getTriangleNormal(&v, i);
double norm[3] = {v.x, v.y, v.z};
nx = fabs(v.x);
ny = fabs(v.y);
nz = fabs(v.z);
if (nx > ny && nx > nz) C = X;
else C = (ny > nz) ? Y : Z;
A = (C + 1) % 3;
B = (A + 1) % 3;
compFaceIntegrals(sur, i, norm);
T0 += norm[X] * ((A == X) ? Fa : ((B == X) ? Fb : Fc));
T1[A] += norm[A] * Faa;
T1[B] += norm[B] * Fbb;
T1[C] += norm[C] * Fcc;
T2[A] += norm[A] * Faaa;
T2[B] += norm[B] * Fbbb;
T2[C] += norm[C] * Fccc;
TP[A] += norm[A] * Faab;
TP[B] += norm[B] * Fbbc;
TP[C] += norm[C] * Fcca;
}
T1[X] /= 2; T1[Y] /= 2; T1[Z] /= 2;
T2[X] /= 3; T2[Y] /= 3; T2[Z] /= 3;
TP[X] /= 2; TP[Y] /= 2; TP[Z] /= 2;
}
void computeMassProperties(REAL *mass, REAL R[3], REAL J[3][3], const Surface &sur){
using namespace VolInt_Globals;
compVolumeIntegrals(sur);
/* compute mass - assume unit density */
REAL density = 1.0;
*mass = density * T0;
/* compute center of mass */
R[X] = T1[X] / T0;
R[Y] = T1[Y] / T0;
R[Z] = T1[Z] / T0;
/* compute inertia tensor */
J[X][X] = density * (T2[Y] + T2[Z]);
J[Y][Y] = density * (T2[Z] + T2[X]);
J[Z][Z] = density * (T2[X] + T2[Y]);
J[X][Y] = J[Y][X] = - density * TP[X];
J[Y][Z] = J[Z][Y] = - density * TP[Y];
J[Z][X] = J[X][Z] = - density * TP[Z];
/* translate inertia tensor to center of mass */
double m = *mass;
J[X][X] -= m * (R[Y]*R[Y] + R[Z]*R[Z]);
J[Y][Y] -= m * (R[Z]*R[Z] + R[X]*R[X]);
J[Z][Z] -= m * (R[X]*R[X] + R[Y]*R[Y]);
J[X][Y] = J[Y][X] += m * R[X] * R[Y];
J[Y][Z] = J[Z][Y] += m * R[Y] * R[Z];
J[Z][X] = J[X][Z] += m * R[Z] * R[X];
} | 29.228571 | 84 | 0.470325 | squarefk |
68080c70acdabd1d3e5137466c037c8d81a2acfb | 1,424 | cpp | C++ | engine/src/common/pixelboost/input/joystickManager.cpp | pixelballoon/pixelboost | 085873310050ce62493df61142b7d4393795bdc2 | [
"MIT"
] | 6 | 2015-04-21T11:30:52.000Z | 2020-04-29T00:10:04.000Z | engine/src/common/pixelboost/input/joystickManager.cpp | pixelballoon/pixelboost | 085873310050ce62493df61142b7d4393795bdc2 | [
"MIT"
] | null | null | null | engine/src/common/pixelboost/input/joystickManager.cpp | pixelballoon/pixelboost | 085873310050ce62493df61142b7d4393795bdc2 | [
"MIT"
] | null | null | null | #include "pixelboost/input/joystickManager.h"
using namespace pb;
JoystickHandler::JoystickHandler()
{
}
JoystickHandler::~JoystickHandler()
{
}
bool JoystickHandler::OnAxisChanged(int joystick, int stick, int axis, float value)
{
return false;
}
bool JoystickHandler::OnButtonDown(int joystick, int button)
{
return false;
}
bool JoystickHandler::OnButtonUp(int joystick, int button)
{
return false;
}
JoystickManager::JoystickManager()
{
}
JoystickManager::~JoystickManager()
{
}
void JoystickManager::OnAxisChanged(int joystick, int stick, int axis, float value)
{
UpdateHandlers();
for (HandlerList::iterator it = _Handlers.begin(); it != _Handlers.end(); ++it)
{
if (dynamic_cast<JoystickHandler*>(*it)->OnAxisChanged(joystick, stick, axis, value))
return;
}
}
void JoystickManager::OnButtonDown(int joystick, int button)
{
UpdateHandlers();
for (HandlerList::iterator it = _Handlers.begin(); it != _Handlers.end(); ++it)
{
if (dynamic_cast<JoystickHandler*>(*it)->OnButtonDown(joystick, button))
return;
}
}
void JoystickManager::OnButtonUp(int joystick, int button)
{
UpdateHandlers();
for (HandlerList::iterator it = _Handlers.begin(); it != _Handlers.end(); ++it)
{
if (dynamic_cast<JoystickHandler*>(*it)->OnButtonUp(joystick, button))
return;
}
}
| 19.777778 | 93 | 0.662219 | pixelballoon |
680d20a5390f605ac39b267c0f27585c472f45f7 | 1,805 | cpp | C++ | unittest/energy.cpp | thanhndv212/pinocchio | 3b4d272bf4e8a231954b71201ee7e0963c944aef | [
"BSD-2-Clause-FreeBSD"
] | 716 | 2015-03-30T16:26:45.000Z | 2022-03-30T12:26:58.000Z | unittest/energy.cpp | thanhndv212/pinocchio | 3b4d272bf4e8a231954b71201ee7e0963c944aef | [
"BSD-2-Clause-FreeBSD"
] | 1,130 | 2015-02-21T17:30:44.000Z | 2022-03-30T09:06:22.000Z | unittest/energy.cpp | thanhndv212/pinocchio | 3b4d272bf4e8a231954b71201ee7e0963c944aef | [
"BSD-2-Clause-FreeBSD"
] | 239 | 2015-02-05T14:15:14.000Z | 2022-03-14T23:51:47.000Z | //
// Copyright (c) 2016-2020 CNRS INRIA
//
#include "pinocchio/algorithm/energy.hpp"
#include "pinocchio/algorithm/crba.hpp"
#include "pinocchio/algorithm/joint-configuration.hpp"
#include "pinocchio/algorithm/center-of-mass.hpp"
#include "pinocchio/parsers/sample-models.hpp"
#include <boost/test/unit_test.hpp>
#include <boost/utility/binary.hpp>
#include <boost/test/floating_point_comparison.hpp>
BOOST_AUTO_TEST_SUITE ( BOOST_TEST_MODULE )
BOOST_AUTO_TEST_CASE(test_kinetic_energy)
{
using namespace Eigen;
using namespace pinocchio;
pinocchio::Model model;
pinocchio::buildModels::humanoidRandom(model);
pinocchio::Data data(model);
const VectorXd qmax = VectorXd::Ones(model.nq);
VectorXd q = randomConfiguration(model,-qmax,qmax);
VectorXd v = VectorXd::Ones(model.nv);
data.M.fill(0); crba(model,data,q);
data.M.triangularView<Eigen::StrictlyLower>()
= data.M.transpose().triangularView<Eigen::StrictlyLower>();
double kinetic_energy_ref = 0.5 * v.transpose() * data.M * v;
double kinetic_energy = computeKineticEnergy(model, data, q, v);
BOOST_CHECK_SMALL(kinetic_energy_ref - kinetic_energy, 1e-12);
}
BOOST_AUTO_TEST_CASE(test_potential_energy)
{
using namespace Eigen;
using namespace pinocchio;
pinocchio::Model model;
pinocchio::buildModels::humanoidRandom(model);
pinocchio::Data data(model), data_ref(model);
const VectorXd qmax = VectorXd::Ones(model.nq);
VectorXd q = randomConfiguration(model,-qmax,qmax);
double potential_energy = computePotentialEnergy(model, data, q);
centerOfMass(model,data_ref,q);
double potential_energy_ref = -data_ref.mass[0] * (data_ref.com[0].dot(model.gravity.linear()));
BOOST_CHECK_SMALL(potential_energy_ref - potential_energy, 1e-12);
}
BOOST_AUTO_TEST_SUITE_END()
| 29.112903 | 98 | 0.754017 | thanhndv212 |
680e090513b5ca735290d816d96ce46941a37677 | 1,317 | hpp | C++ | iOS/G3MiOSSDK/Commons/JSON/JSONBaseObject.hpp | AeroGlass/g3m | a21a9e70a6205f1f37046ae85dafc6e3bfaeb917 | [
"BSD-2-Clause"
] | null | null | null | iOS/G3MiOSSDK/Commons/JSON/JSONBaseObject.hpp | AeroGlass/g3m | a21a9e70a6205f1f37046ae85dafc6e3bfaeb917 | [
"BSD-2-Clause"
] | null | null | null | iOS/G3MiOSSDK/Commons/JSON/JSONBaseObject.hpp | AeroGlass/g3m | a21a9e70a6205f1f37046ae85dafc6e3bfaeb917 | [
"BSD-2-Clause"
] | null | null | null | //
// JSONBaseObject.hpp
// G3MiOSSDK
//
// Created by Oliver Koehler on 17/09/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#ifndef G3MiOSSDK_JSONBaseObject
#define G3MiOSSDK_JSONBaseObject
class JSONObject;
class JSONArray;
class JSONBoolean;
class JSONNumber;
class JSONString;
class JSONNull;
class JSONVisitor;
#include <string>
class JSONBaseObject {
public:
static JSONBaseObject* deepCopy(const JSONBaseObject* object) {
return (object == NULL) ? NULL : object->deepCopy();
}
static const std::string toString(const JSONBaseObject* object) {
return (object == NULL) ? "null" : object->toString();
}
virtual ~JSONBaseObject() {
}
virtual const JSONObject* asObject() const;
virtual const JSONArray* asArray() const;
virtual const JSONBoolean* asBoolean() const;
virtual const JSONNumber* asNumber() const;
virtual const JSONString* asString() const;
virtual const JSONNull* asNull() const;
virtual JSONBaseObject* deepCopy() const = 0;
virtual const std::string description() const = 0;
//#ifdef JAVA_CODE
// @Override
// public String toString() {
// return description();
// }
//#endif
virtual void acceptVisitor(JSONVisitor* visitor) const = 0;
virtual const std::string toString() const = 0;
};
#endif
| 20.578125 | 67 | 0.707669 | AeroGlass |
680e8a0dcdf05979bd7192591cfa4ecbf8dae8f3 | 1,626 | cpp | C++ | Client/chat.cpp | edoblette/QtChat | 154db25b97b2420a13b15993d1b4d0ee7b23c160 | [
"MIT"
] | null | null | null | Client/chat.cpp | edoblette/QtChat | 154db25b97b2420a13b15993d1b4d0ee7b23c160 | [
"MIT"
] | null | null | null | Client/chat.cpp | edoblette/QtChat | 154db25b97b2420a13b15993d1b4d0ee7b23c160 | [
"MIT"
] | null | null | null | /**
* CLIENT SIDE
* Projet Reseau
* @teacher Pablo Rauzy <pr@up8.edu> <https://pablo.rauzy.name/teaching.html#rmpp>
*
* @autor Edgar Oblette <edwardoblette@gmail.com>
* @collegues: Lina Tlemcem
* Nourdine ---
*
* 21/04/2019
*/
#include "ui_chat.h"
#include "eventshandler.hpp"
// ne pas remplir name, si chat public
chat::chat(QWidget *parent, EventHandler * addrEventHandler, std::string name ) :
QWidget(parent),
ui(new Ui::chat)
{
ui->setupUi(this);
pcEventHandler = addrEventHandler;
pcEventHandler->set_chat(this, name);
_destName = name;
}
chat::~chat()
{
delete ui;
}
void chat::displayMsg(std::string message){
QString qmessage = QString::fromStdString(message);
//ui->ui_messageStream->append("good !");
QPlainTextEdit *myTextEdit = ui->ui_messageStream;
myTextEdit->moveCursor (QTextCursor::End);
myTextEdit->insertPlainText(qmessage+"\n");
}
void chat::on_ui_messageSend_clicked()
{
std::string message = ui->ui_messageEdit->text().toStdString();
if(!message.empty()){
ui->ui_messageEdit->clear();
if (!_destName.empty()){ // Message prive
std::cout << "message prive" << std::endl;
pcEventHandler->SendingMessage("PRV " + _destName + " " + message);
displayMsg("Vous : " + message);
}
/* Pas implemente ici dans cette version
else { // Message public
std::cout << "message public" << std::endl;
pcEventHandler->SendingMessage("MSG " + message);
}
*/
}
}
| 27.1 | 85 | 0.599631 | edoblette |
681080aebf16c44e3f86bb1c1852e596638afe02 | 8,497 | cpp | C++ | src/ElgForward/loaders/scene_loader.cpp | BartSiwek/ElgForward | cd776d4f138f82ac881bd0508215274073a65aad | [
"MIT"
] | 1 | 2016-06-07T07:37:31.000Z | 2016-06-07T07:37:31.000Z | src/ElgForward/loaders/scene_loader.cpp | BartSiwek/ElgForward | cd776d4f138f82ac881bd0508215274073a65aad | [
"MIT"
] | null | null | null | src/ElgForward/loaders/scene_loader.cpp | BartSiwek/ElgForward | cd776d4f138f82ac881bd0508215274073a65aad | [
"MIT"
] | 1 | 2021-03-08T07:20:25.000Z | 2021-03-08T07:20:25.000Z | #include "scene_loader.h"
#pragma warning(push)
#pragma warning(disable: 4706)
#include <nlohmann/json.hpp>
#pragma warning(pop)
#include <dxfw/dxfw.h>
#include "core/json_helpers.h"
#include "loaders/light_loader.h"
#include "loaders/camera_loader.h"
#include "loaders/material_loader.h"
#include "loaders/mesh_loader.h"
#include "loaders/transform_loader.h"
#include "loaders/texture_loader.h"
#include "rendering/screen.h"
#include "rendering/material.h"
#include "rendering/mesh.h"
#include "rendering/transform.h"
#include "rendering/transform_and_inverse_transpose.h"
namespace Loaders {
void ReadMeshes(const nlohmann::json& json_scene, const filesystem::path& base_path, DirectXState* state, std::vector<MeshIdentifier>* mesh_identifiers) {
const auto& json_meshes = json_scene["meshes"];
for (const auto& json_mesh : json_meshes) {
bool is_valid_mesh_entry = json_mesh["prefix"].is_string()
&& json_mesh["path"].is_string()
&& json_mesh["options"].is_object();
if (!is_valid_mesh_entry) {
DXFW_TRACE(__FILE__, __LINE__, false, "Invalid mesh entry %S", json_mesh.dump().c_str());
continue;
}
bool mesh_ok = ReadMesh(json_mesh, base_path, state->device.Get(), mesh_identifiers);
if (!mesh_ok) {
DXFW_TRACE(__FILE__, __LINE__, false, "Error reading mesh from %S", json_mesh.dump().c_str());
continue;
}
}
}
void ReadDrawableTransform(const std::string& drawable_name, const nlohmann::json& json_drawable, DirectXState* state, Rendering::Transform::Transform* transform) {
const auto& json_transform = json_drawable["transform"];
if (!json_transform.is_object()) {
DXFW_TRACE(__FILE__, __LINE__, false, "Invalid drawable transform entry [%S]", json_transform.dump().c_str());
return;
}
bool transform_ok = ReadTransform(drawable_name, json_transform, state->device.Get(), transform);
if (!transform_ok) {
DXFW_TRACE(__FILE__, __LINE__, false, "Error reading drawable transform entry [%S]", json_transform.dump().c_str());
}
}
void BuildDrawables(const nlohmann::json& json_scene, const std::vector<MeshIdentifier>& mesh_indetifiers,
const std::vector<MaterialIdentifier>& materials, DirectXState* state,
std::vector<Rendering::Drawable>* drawables) {
const auto& json_drawables = json_scene["scene"];
for (const auto& json_drawable : json_drawables) {
bool is_valid_drawable_entry = json_drawable["name"].is_string()
&& json_drawable["mesh_name"].is_string()
&& json_drawable["material_name"].is_string();
if (!is_valid_drawable_entry) {
DXFW_TRACE(__FILE__, __LINE__, false, "Invalid drawable entry %S", json_drawable.dump().c_str());
continue;
}
const std::string& drawable_name = json_drawable["name"];
const std::string& mesh_name = json_drawable["mesh_name"];
const std::string& material_name = json_drawable["material_name"];
std::hash<std::string> hasher;
auto drawable_name_hash = hasher(drawable_name);
auto mesh_name_hash = hasher(mesh_name);
auto material_name_hash = hasher(material_name);
auto mesh_indetifier_it = std::find_if(std::begin(mesh_indetifiers), std::end(mesh_indetifiers), [mesh_name_hash](const auto& identifier){
return mesh_name_hash == identifier.Hash;
});
if (mesh_indetifier_it == std::end(mesh_indetifiers)) {
DXFW_TRACE(__FILE__, __LINE__, false, "Error creating drawable from mesh %S and material %S - mesh not found", mesh_name.c_str(), material_name.c_str());
continue;
}
auto mesh = Rendering::Mesh::Retreive(mesh_indetifier_it->handle);
auto material_identifier_it = std::find_if(std::begin(materials), std::end(materials), [material_name_hash](const auto& material) {
return material_name_hash == material.Hash;
});
if (material_identifier_it == std::end(materials)) {
DXFW_TRACE(__FILE__, __LINE__, false, "Error creating drawable from mesh %S and material %S - material not found", mesh_name.c_str(), material_name.c_str());
continue;
}
Rendering::Transform::Transform transform;
ReadDrawableTransform(drawable_name, json_drawable, state, &transform);
Rendering::Drawable drawable;
bool drawable_ok = CreateDrawable(drawable_name_hash, *mesh, material_identifier_it->Hash, material_identifier_it->Material, transform, state->device.Get(), &drawable);
if (!drawable_ok) {
DXFW_TRACE(__FILE__, __LINE__, false, "Error creating drawable from mesh %S and material %S - CreateDrawable failed", mesh_name.c_str(), material_name.c_str());
continue;
}
drawables->emplace_back(std::move(drawable));
}
}
void ReadMaterials(const nlohmann::json& json_scene, const filesystem::path& base_path,
const std::vector<TextureIdentifier>& textures, DirectXState* state,
std::vector<MaterialIdentifier>* materials) {
const auto& json_materials = json_scene["materials"];
for (const auto& json_material : json_materials) {
MaterialIdentifier new_material;
bool material_ok = ReadMaterial(json_material, base_path, textures, state->device.Get(), &new_material);
if (!material_ok) {
DXFW_TRACE(__FILE__, __LINE__, false, "Error loading material [%S]", json_material.dump().c_str());
}
materials->emplace_back(std::move(new_material));
}
}
void ReadLights(const nlohmann::json& json_scene, const filesystem::path& base_path, Scene* scene) {
auto lights_it = json_scene.find("lights");
if (lights_it == json_scene.end()) {
return;
}
if (!lights_it->is_string()) {
DXFW_TRACE(__FILE__, __LINE__, false, "Invalid lights entry [%S]", lights_it->dump().c_str());
return;
}
const std::string& lights_relative_path = *lights_it;
auto lights_path = base_path / lights_relative_path;
bool lights_ok = ReadLightsFromFile(lights_path, scene->DirectionalLightsStructuredBuffer,
scene->SpotLightsStructuredBuffer, scene->PointLightsStructuredBuffer);
if (!lights_ok) {
DXFW_TRACE(__FILE__, __LINE__, false, "Error reading lights from [%S]", lights_path.c_str());
}
}
void ReadTextures(const nlohmann::json& json_scene, const filesystem::path& base_path, DirectXState* state, std::vector<TextureIdentifier>* textures) {
auto textures_it = json_scene.find("textures");
if (textures_it == json_scene.end()) {
return;
}
if (!textures_it->is_string()) {
DXFW_TRACE(__FILE__, __LINE__, false, "Invalid textures entry [%S]", textures_it->dump().c_str());
return;
}
const std::string& textures_relative_path = *textures_it;
auto textures_path = base_path / textures_relative_path;
bool textures_ok = ReadTexturesFromFile(textures_path, base_path, state->device.Get(), textures);
if (!textures_ok) {
DXFW_TRACE(__FILE__, __LINE__, false, "Error reading textures from [%S]", textures_path.c_str());
}
}
void ReadCamera(const nlohmann::json& json_scene, const filesystem::path& base_path, DirectXState* state, Scene* scene) {
const auto& json_camera = json_scene["camera"];
if (!json_camera.is_object()) {
DXFW_TRACE(__FILE__, __LINE__, false, "Invalid camera entry [%S]", json_camera.dump().c_str());
return;
}
bool camera_ok = ReadCamera(json_camera, base_path, state, &scene->Camera, &scene->Lens, &scene->CameraScript);
if (!camera_ok) {
DXFW_TRACE(__FILE__, __LINE__, false, "Error reading camera from [%S]", json_camera.dump().c_str());
}
}
bool LoadScene(const filesystem::path& path, const filesystem::path& base_path, DirectXState* state, Scene* scene) {
nlohmann::json json_scene;
bool load_ok = Core::ReadJsonFile(path, &json_scene);
if (!load_ok) {
DXFW_TRACE(__FILE__, __LINE__, false, "Error reading scene file from %S", path.c_str());
return false;
}
std::vector<MeshIdentifier> mesh_identifiers;
ReadMeshes(json_scene, base_path, state, &mesh_identifiers);
std::vector<TextureIdentifier> textures;
ReadTextures(json_scene, base_path, state, &textures);
std::vector<MaterialIdentifier> materials;
ReadMaterials(json_scene, base_path, textures, state, &materials);
ReadLights(json_scene, base_path, scene);
BuildDrawables(json_scene, mesh_identifiers, materials, state, &scene->Drawables);
ReadCamera(json_scene, base_path, state, scene);
return true;
}
} // namespace Loaders
| 39.156682 | 172 | 0.707073 | BartSiwek |
6810b9e013996f7d618e92ad385c6ffc122fb955 | 601 | cpp | C++ | Analysis/src/AlThrust.cpp | gganis/AlphappLite | e52a184c2d39a3acdd6ff09d1d61bcfca7807460 | [
"Apache-2.0"
] | null | null | null | Analysis/src/AlThrust.cpp | gganis/AlphappLite | e52a184c2d39a3acdd6ff09d1d61bcfca7807460 | [
"Apache-2.0"
] | null | null | null | Analysis/src/AlThrust.cpp | gganis/AlphappLite | e52a184c2d39a3acdd6ff09d1d61bcfca7807460 | [
"Apache-2.0"
] | null | null | null | //////////////////////////////////////////////////////////
// implementation of the AlThrust class methods
//
// Author : M. Hoerndl
//
///////////////////////////////////////////////////////////
#include "AlThrust.h"
// default constructor : has to do something,
// since it is not created out of qvec
AlThrust::AlThrust() {}
// copy constructor :Everything is set by the QvecBase copy constructor
AlThrust::AlThrust(const AlThrust& oldT):QvecBase(oldT) {}
TVector3 AlThrust::getThrustDirection() const
{ return A4V().Vect(); }
float AlThrust::getThrustValue() const
{ return A4V().E(); }
| 24.04 | 71 | 0.572379 | gganis |
68122067b1d2352555bae044246215ae359135a8 | 3,992 | cpp | C++ | Code/Engine/GameEngine/Physics/Implementation/ClothSheetSimulator.cpp | Tekh-ops/ezEngine | d6a5887d8709f267bf8f2943ef15054e29f6d3d5 | [
"MIT"
] | 703 | 2015-03-07T15:30:40.000Z | 2022-03-30T00:12:40.000Z | Code/Engine/GameEngine/Physics/Implementation/ClothSheetSimulator.cpp | Tekh-ops/ezEngine | d6a5887d8709f267bf8f2943ef15054e29f6d3d5 | [
"MIT"
] | 233 | 2015-01-11T16:54:32.000Z | 2022-03-19T18:00:47.000Z | Code/Engine/GameEngine/Physics/Implementation/ClothSheetSimulator.cpp | Tekh-ops/ezEngine | d6a5887d8709f267bf8f2943ef15054e29f6d3d5 | [
"MIT"
] | 101 | 2016-10-28T14:05:10.000Z | 2022-03-30T19:00:59.000Z | #include <GameEngine/GameEnginePCH.h>
#include <Foundation/SimdMath/SimdConversion.h>
#include <GameEngine/Physics/ClothSheetSimulator.h>
void ezClothSimulator::SimulateCloth(const ezTime& tDiff)
{
m_leftOverTimeStep += tDiff;
constexpr ezTime tStep = ezTime::Seconds(1.0 / 60.0);
const ezSimdFloat tStepSqr = static_cast<float>(tStep.GetSeconds() * tStep.GetSeconds());
while (m_leftOverTimeStep >= tStep)
{
SimulateStep(tStepSqr, 32, m_vSegmentLength.x);
m_leftOverTimeStep -= tStep;
}
}
void ezClothSimulator::SimulateStep(const ezSimdFloat tDiffSqr, ezUInt32 uiMaxIterations, ezSimdFloat fAllowedError)
{
if (m_Nodes.GetCount() < 4)
return;
UpdateNodePositions(tDiffSqr);
// repeatedly apply the distance constraint, until the overall error is low enough
for (ezUInt32 i = 0; i < uiMaxIterations; ++i)
{
const ezSimdFloat fError = EnforceDistanceConstraint();
if (fError < fAllowedError)
return;
}
}
ezSimdFloat ezClothSimulator::EnforceDistanceConstraint()
{
ezSimdFloat fError = ezSimdFloat::Zero();
for (ezUInt32 y = 0; y < m_uiHeight; ++y)
{
for (ezUInt32 x = 0; x < m_uiWidth; ++x)
{
const ezUInt32 idx = (y * m_uiWidth) + x;
auto& n = m_Nodes[idx];
if (n.m_bFixed)
continue;
const ezSimdVec4f posThis = n.m_vPosition;
if (x > 0)
{
const ezSimdVec4f pos = m_Nodes[idx - 1].m_vPosition;
n.m_vPosition += MoveTowards(posThis, pos, 0.5f, ezSimdVec4f(-1, 0, 0), fError, m_vSegmentLength.x);
}
if (x + 1 < m_uiWidth)
{
const ezSimdVec4f pos = m_Nodes[idx + 1].m_vPosition;
n.m_vPosition += MoveTowards(posThis, pos, 0.5f, ezSimdVec4f(1, 0, 0), fError, m_vSegmentLength.x);
}
if (y > 0)
{
const ezSimdVec4f pos = m_Nodes[idx - m_uiWidth].m_vPosition;
n.m_vPosition += MoveTowards(posThis, pos, 0.5f, ezSimdVec4f(0, -1, 0), fError, m_vSegmentLength.y);
}
if (y + 1 < m_uiHeight)
{
const ezSimdVec4f pos = m_Nodes[idx + m_uiWidth].m_vPosition;
n.m_vPosition += MoveTowards(posThis, pos, 0.5f, ezSimdVec4f(0, 1, 0), fError, m_vSegmentLength.y);
}
}
}
return fError;
}
ezSimdVec4f ezClothSimulator::MoveTowards(const ezSimdVec4f posThis, const ezSimdVec4f posNext, ezSimdFloat factor, const ezSimdVec4f fallbackDir, ezSimdFloat& inout_fError, ezSimdFloat fSegLen)
{
ezSimdVec4f vDir = (posNext - posThis);
ezSimdFloat fLen = vDir.GetLength<3>();
if (fLen.IsEqual(ezSimdFloat::Zero(), 0.001f))
{
vDir = fallbackDir;
fLen = 1;
}
vDir /= fLen;
fLen -= fSegLen;
const ezSimdFloat fLocalError = fLen * factor;
vDir *= fLocalError;
// keep track of how much the rope had to be moved to fulfill the constraint
inout_fError += fLocalError.Abs();
return vDir;
}
void ezClothSimulator::UpdateNodePositions(const ezSimdFloat tDiffSqr)
{
const ezSimdFloat damping = m_fDampingFactor;
const ezSimdVec4f acceleration = ezSimdConversion::ToVec3(m_vAcceleration) * tDiffSqr;
for (auto& n : m_Nodes)
{
if (n.m_bFixed)
{
n.m_vPreviousPosition = n.m_vPosition;
}
else
{
// this (simple) logic is the so called 'Verlet integration' (+ damping)
const ezSimdVec4f previousPos = n.m_vPosition;
const ezSimdVec4f vel = (n.m_vPosition - n.m_vPreviousPosition) * damping;
// instead of using a single global acceleration, this could also use individual accelerations per node
// this would be needed to affect the rope more localized
n.m_vPosition += vel + acceleration;
n.m_vPreviousPosition = previousPos;
}
}
}
bool ezClothSimulator::HasEquilibrium(ezSimdFloat fAllowedMovement) const
{
const ezSimdFloat fErrorSqr = fAllowedMovement * fAllowedMovement;
for (const auto& n : m_Nodes)
{
if ((n.m_vPosition - n.m_vPreviousPosition).GetLengthSquared<3>() > fErrorSqr)
{
return false;
}
}
return true;
}
| 26.791946 | 194 | 0.676854 | Tekh-ops |
68135617db854f4ce233a3b6dc0df9a4087d88b5 | 2,344 | hpp | C++ | src/prx/simulation/playback/trajectory.hpp | aravindsiv/ML4KP | 064015a7545e1713cbcad3e79807b5cec0849f54 | [
"MIT"
] | 3 | 2021-05-31T11:28:03.000Z | 2021-05-31T13:49:30.000Z | src/prx/simulation/playback/trajectory.hpp | aravindsiv/ML4KP | 064015a7545e1713cbcad3e79807b5cec0849f54 | [
"MIT"
] | 1 | 2021-09-03T09:39:32.000Z | 2021-12-10T22:17:56.000Z | src/prx/simulation/playback/trajectory.hpp | aravindsiv/ML4KP | 064015a7545e1713cbcad3e79807b5cec0849f54 | [
"MIT"
] | 2 | 2021-09-03T09:17:45.000Z | 2021-10-04T15:52:58.000Z | #pragma once
#include "prx/utilities/spaces/space.hpp"
#include "prx/utilities/defs.hpp"
#include <deque>
namespace prx
{
/**
* @brief <b>A class that defines a trajectory.</b>
*
* A trajectory consists of a sequence of states.
*
* @authors Zakary Littlefield
*
*/
class trajectory_t
{
public:
typedef std::vector<space_point_t>::iterator iterator;
typedef std::vector<space_point_t>::const_iterator const_iterator;
trajectory_t(const space_t* space);
~trajectory_t();
trajectory_t(const trajectory_t& traj);
inline unsigned size() const
{
return num_states;
}
inline space_point_t operator[](unsigned index) const
{
return at(index);
}
inline space_point_t operator[](double index) const
{
return at(index);
}
inline space_point_t front() const
{
prx_assert(num_states != 0,"Trying to access the front of a trajectory with zero size.");
return states[0];
}
inline space_point_t back() const
{
prx_assert(num_states != 0,"Trying to access the back of a trajectory with zero size.");
return states[num_states - 1];
}
inline iterator begin()
{
return states.begin();
}
inline iterator end()
{
return end_iterator;
}
inline const_iterator begin() const
{
return states.begin();
}
inline const_iterator end() const
{
return const_end_iterator;
}
space_point_t at(unsigned index) const
{
prx_assert(index < num_states,"Trying to access state outside of trajectory size.");
return states[index];
}
space_point_t at(double index) const
{
return interpolate(index);
}
unsigned get_num_states() const
{
return num_states;
}
void resize(unsigned num_size);
trajectory_t& operator=(const trajectory_t& t);
trajectory_t& operator+=(const trajectory_t& t);
bool operator==(const trajectory_t& t);
bool operator!=(const trajectory_t& t);
void clear();
void copy_onto_back(space_point_t state);
void copy_onto_back(const space_t* space);
std::string print(unsigned precision=3) const;
protected:
space_point_t interpolate(double s) const;
void increase_buffer();
const space_t* state_space;
iterator end_iterator;
const_iterator const_end_iterator;
unsigned max_num_states;
unsigned num_states;
std::vector<space_point_t> states;
};
}
| 20.561404 | 92 | 0.699232 | aravindsiv |
6816ec48ab02ac844ecbad666ba6f61c60d884ce | 16,932 | cpp | C++ | src/Context.cpp | k0zmo/clw | f0be6d1b674118a4b99bc879894eb9481c868887 | [
"MIT"
] | 1 | 2016-08-21T00:01:38.000Z | 2016-08-21T00:01:38.000Z | src/Context.cpp | k0zmo/clw | f0be6d1b674118a4b99bc879894eb9481c868887 | [
"MIT"
] | null | null | null | src/Context.cpp | k0zmo/clw | f0be6d1b674118a4b99bc879894eb9481c868887 | [
"MIT"
] | null | null | null | /*
Copyright (c) 2012, 2013 Kajetan Swierk <k0zmo@outlook.com>
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 "clw/Context.h"
#include "clw/Platform.h"
#include "clw/CommandQueue.h"
#include "clw/Program.h"
#include "clw/Buffer.h"
#include "clw/Image.h"
#include "details.h"
#include <iostream>
#if !defined(CL_CONTEXT_OFFLINE_DEVICES_AMD)
# define CL_CONTEXT_OFFLINE_DEVICES_AMD 0x403F
#endif
namespace clw
{
namespace detail
{
extern "C" void CL_API_CALL contextNotify(const char* errInfo,
const void* privateInfo,
size_t cb,
void* userData)
{
(void) privateInfo;
(void) cb;
(void) userData;
std::cerr << "Context notification: " << errInfo << std::endl;
}
string errorName(cl_int _eid)
{
#define CASE(X) case X: return string(#X);
switch(_eid)
{
CASE(CL_SUCCESS);
CASE(CL_DEVICE_NOT_FOUND);
CASE(CL_DEVICE_NOT_AVAILABLE);
CASE(CL_COMPILER_NOT_AVAILABLE);
CASE(CL_MEM_OBJECT_ALLOCATION_FAILURE);
CASE(CL_OUT_OF_RESOURCES);
CASE(CL_OUT_OF_HOST_MEMORY);
CASE(CL_PROFILING_INFO_NOT_AVAILABLE);
CASE(CL_MEM_COPY_OVERLAP);
CASE(CL_IMAGE_FORMAT_MISMATCH);
CASE(CL_IMAGE_FORMAT_NOT_SUPPORTED);
CASE(CL_BUILD_PROGRAM_FAILURE);
CASE(CL_MAP_FAILURE);
CASE(CL_MISALIGNED_SUB_BUFFER_OFFSET);
CASE(CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST);
CASE(CL_INVALID_VALUE);
CASE(CL_INVALID_DEVICE_TYPE);
CASE(CL_INVALID_PLATFORM);
CASE(CL_INVALID_DEVICE);
CASE(CL_INVALID_CONTEXT);
CASE(CL_INVALID_QUEUE_PROPERTIES);
CASE(CL_INVALID_COMMAND_QUEUE);
CASE(CL_INVALID_HOST_PTR);
CASE(CL_INVALID_MEM_OBJECT);
CASE(CL_INVALID_IMAGE_FORMAT_DESCRIPTOR);
CASE(CL_INVALID_IMAGE_SIZE);
CASE(CL_INVALID_SAMPLER);
CASE(CL_INVALID_BINARY);
CASE(CL_INVALID_BUILD_OPTIONS);
CASE(CL_INVALID_PROGRAM);
CASE(CL_INVALID_PROGRAM_EXECUTABLE);
CASE(CL_INVALID_KERNEL_NAME);
CASE(CL_INVALID_KERNEL_DEFINITION);
CASE(CL_INVALID_KERNEL);
CASE(CL_INVALID_ARG_INDEX);
CASE(CL_INVALID_ARG_VALUE);
CASE(CL_INVALID_ARG_SIZE);
CASE(CL_INVALID_KERNEL_ARGS);
CASE(CL_INVALID_WORK_DIMENSION);
CASE(CL_INVALID_WORK_GROUP_SIZE);
CASE(CL_INVALID_WORK_ITEM_SIZE);
CASE(CL_INVALID_GLOBAL_OFFSET);
CASE(CL_INVALID_EVENT_WAIT_LIST);
CASE(CL_INVALID_EVENT);
CASE(CL_INVALID_OPERATION);
CASE(CL_INVALID_GL_OBJECT);
CASE(CL_INVALID_BUFFER_SIZE);
CASE(CL_INVALID_MIP_LEVEL);
CASE(CL_INVALID_GLOBAL_WORK_SIZE);
CASE(CL_INVALID_PROPERTY);
#if defined(HAVE_OPENCL_1_2)
CASE(CL_COMPILE_PROGRAM_FAILURE);
CASE(CL_LINKER_NOT_AVAILABLE);
CASE(CL_LINK_PROGRAM_FAILURE);
CASE(CL_DEVICE_PARTITION_FAILED);
CASE(CL_KERNEL_ARG_INFO_NOT_AVAILABLE);
CASE(CL_INVALID_IMAGE_DESCRIPTOR);
CASE(CL_INVALID_COMPILER_OPTIONS);
CASE(CL_INVALID_LINKER_OPTIONS);
CASE(CL_INVALID_DEVICE_PARTITION_COUNT);
#endif
// cl_khr_icd extension
CASE(CL_PLATFORM_NOT_FOUND_KHR);
default: return string("Error ") + std::to_string(
static_cast<unsigned long long>(_eid));
}
#undef CASE
}
static ErrorHandler reportErrorHandler;
void reportError(const char* name, cl_int _eid)
{
if(_eid != CL_SUCCESS)
{
if(reportErrorHandler)
reportErrorHandler(_eid, string(name) + errorName(_eid));
else
std::cerr << name << errorName(_eid) << std::endl;;
}
}
vector<ImageFormat> supportedImageFormats(
cl_context id,
cl_mem_object_type image_type)
{
cl_uint num;
cl_int error;
if((error = clGetSupportedImageFormats(id, CL_MEM_READ_WRITE,
image_type, 0, nullptr, &num)) != CL_SUCCESS || !num)
{
reportError("supportedImageFormats() ", error);
return vector<ImageFormat>();
}
vector<cl_image_format> buf(num);
if((error = clGetSupportedImageFormats(id, CL_MEM_READ_WRITE,
image_type, num, buf.data(), nullptr)) != CL_SUCCESS)
{
reportError("supportedImageFormats() ", error);
return vector<ImageFormat>();
}
vector<ImageFormat> imageFormats(num);
for(cl_uint i = 0; i < num; ++i)
imageFormats[i] = ImageFormat(
EChannelOrder(buf[i].image_channel_order),
EChannelType(buf[i].image_channel_data_type));
return imageFormats;
}
}
void installErrorHandler(const ErrorHandler& handler)
{
detail::reportErrorHandler = handler;
}
Context::Context()
: _id(0)
, _isCreated(false)
, _eid(CL_SUCCESS)
{
}
Context::~Context()
{
if(_isCreated && _id != 0)
clReleaseContext(_id);
}
Context::Context(const Context& other)
: _id(other._id), _isCreated(other._isCreated),
_eid(other._eid), _devs(other._devs)
{
if(_id)
clRetainContext(_id);
}
Context& Context::operator=(const Context& other)
{
if(other._id)
clRetainContext(other._id);
if(_id)
clReleaseContext(_id);
_id = other._id;
_isCreated = other._isCreated;
_eid = other._eid;
_devs = other._devs;
return *this;
}
Context::Context(Context&& other)
: _id(0)
, _isCreated(false)
, _eid(CL_SUCCESS)
{
*this = std::move(other);
}
Context& Context::operator=(Context&& other)
{
if (&other != this)
{
if(_isCreated && _id != 0)
clReleaseContext(_id);
_id = other._id;
_isCreated = other._isCreated;
_eid = other._eid;
_devs = std::move(other._devs);
other._id = 0;
}
return *this;
}
bool Context::create(EDeviceType type)
{
if(_isCreated)
return true;
vector<Platform> pls = clw::availablePlatforms();
for(size_t i = 0; i < pls.size(); ++i)
{
vector<Device> devices = clw::devices(type, pls[i]);
for(size_t j = 0; j < devices.size(); ++j)
{
cl_device_id did = devices[j].deviceId();
cl_context_properties props[] = {
CL_CONTEXT_PLATFORM,
cl_context_properties(pls[i].platformId()),
0
};
if((_id = clCreateContext(props, 1, &did,
&detail::contextNotify, nullptr, &_eid)) != 0)
{
_devs.clear();
_devs.push_back(Device(did));
_isCreated = true;
return true;
}
detail::reportError("Context::create(type): ", _eid);
}
}
_isCreated = false;
return false;
}
bool Context::create(const vector<Device>& devices)
{
if(_isCreated)
return true;
if(devices.empty())
return false;
vector<cl_device_id> dids(devices.size());
for(size_t i = 0; i < devices.size(); ++i)
dids[i] = devices[i].deviceId();
cl_platform_id pid = devices[0].platform().platformId();
cl_context_properties props[] = {
CL_CONTEXT_PLATFORM,
cl_context_properties(pid),
0
};
if((_id = clCreateContext(props, cl_uint(dids.size()), dids.data(),
&detail::contextNotify, nullptr, &_eid)) != 0)
{
size_t size;
if((_eid = clGetContextInfo(_id, CL_CONTEXT_DEVICES, 0,
nullptr, &size)) == CL_SUCCESS)
{
// !FIXME: assert(size == dids.size())
_devs = devices;
_isCreated = true;
return true;
}
}
detail::reportError("Context::create(devices): ", _eid);
return false;
}
bool Context::createOffline(const Platform& platform)
{
if(_isCreated)
return true;
cl_platform_id plid = platform.platformId();
if(plid == 0)
plid = clw::defaultPlatform().platformId();
cl_context_properties props[] = {
CL_CONTEXT_PLATFORM,
cl_context_properties(plid),
CL_CONTEXT_OFFLINE_DEVICES_AMD,
cl_context_properties(1),
0
};
_id = clCreateContextFromType
(props, CL_DEVICE_TYPE_ALL, nullptr, nullptr, &_eid);
detail::reportError("Context::createOffline(devices): ", _eid);
if(_eid == CL_SUCCESS)
{
size_t size;
if((_eid = clGetContextInfo(_id, CL_CONTEXT_DEVICES, 0,
nullptr, &size)) == CL_SUCCESS)
{
size_t numDevices = size / sizeof(cl_device_id);
vector<cl_device_id> devices_id(numDevices);
clGetContextInfo(_id, CL_CONTEXT_DEVICES, size,
devices_id.data(), nullptr);
_devs.clear();
for(size_t i = 0; i < numDevices; ++i)
_devs.push_back(Device(devices_id[i]));
_isCreated = true;
return true;
}
}
return false;
}
bool Context::createDefault(Device& device, CommandQueue& queue)
{
if(!create() || numDevices() == 0)
return false;
device = devices()[0];
if(device.isNull())
return false;
queue = createCommandQueue(device, CommandQueueFlags());
return !queue.isNull();
}
void Context::release()
{
if(_isCreated)
{
clReleaseContext(_id);
_id = 0;
_isCreated = false;
}
}
CommandQueue Context::createCommandQueue(const Device& device,
CommandQueueFlags properties)
{
cl_command_queue cid = clCreateCommandQueue
(_id, device.deviceId(),
properties.raw(), &_eid);
detail::reportError("Context::createCommandQueue(): ", _eid);
return cid ? CommandQueue(this, cid) : CommandQueue();
}
Buffer Context::createBuffer(EAccess access,
EMemoryLocation location,
size_t size,
const void* data)
{
cl_mem_flags mem_flags = cl_mem_flags(access);
if(data && location != EMemoryLocation::UseHostMemory)
mem_flags |= CL_MEM_COPY_HOST_PTR;
mem_flags |= cl_mem_flags(location);
cl_mem bid = clCreateBuffer
(_id, mem_flags, size, const_cast<void*>(data), &_eid);
detail::reportError("Context::createBuffer(): ", _eid);
return bid ? Buffer(this, bid) : Buffer();
}
Image2D Context::createImage2D(EAccess access,
EMemoryLocation location,
const ImageFormat& format,
size_t width,
size_t height,
const void* data)
{
cl_image_format image_format;
image_format.image_channel_order = cl_channel_order(format.order);
image_format.image_channel_data_type = cl_channel_type(format.type);
cl_mem_flags mem_flags = cl_mem_flags(access);
if(data && location != EMemoryLocation::UseHostMemory)
mem_flags |= CL_MEM_COPY_HOST_PTR;
mem_flags |= cl_mem_flags(location);
#if defined(HAVE_OPENCL_1_2)
cl_image_desc desc;
desc.image_type = CL_MEM_OBJECT_IMAGE2D;
desc.image_width = width;
desc.image_height = height;
desc.image_depth = 0;
desc.image_array_size = 1;
desc.image_row_pitch = 0;
desc.image_slice_pitch = 0;
desc.num_mip_levels = 0;
desc.num_samples = 0;
desc.buffer = nullptr;
cl_mem iid = clCreateImage
(_id, mem_flags, &image_format,
&desc, const_cast<void*>(data), &_eid);
#else
cl_mem iid = clCreateImage2D
(_id, mem_flags, &image_format,
width, height, 0, const_cast<void*>(data), &_eid);
#endif
detail::reportError("Context::createImage2D(): ", _eid);
return iid ? Image2D(this, iid) : Image2D();
}
Sampler Context::createSampler(bool normalizedCoords,
EAddressingMode addressingMode,
EFilterMode filterMode)
{
cl_sampler sampler = clCreateSampler
(_id, normalizedCoords ? CL_TRUE : CL_FALSE,
cl_addressing_mode(addressingMode),
cl_filter_mode(filterMode), &_eid);
detail::reportError("Context::createSampler() ", _eid);
return sampler ? Sampler(this, sampler) : Sampler();
}
UserEvent Context::createUserEvent()
{
#if defined(HAVE_OPENCL_1_1)
cl_event event = clCreateUserEvent(_id, &_eid);
detail::reportError("Context::createUserEvent() ", _eid);
return UserEvent(event);
#else
return UserEvent();
#endif
}
vector<ImageFormat> Context::supportedImage2DFormats() const
{
return detail::supportedImageFormats(_id, CL_MEM_OBJECT_IMAGE2D);
}
vector<ImageFormat> Context::supportedImage3DFormats() const
{
return detail::supportedImageFormats(_id, CL_MEM_OBJECT_IMAGE3D);
}
Program Context::createProgramFromSourceCode(const string& sourceCode)
{
size_t length = sourceCode.length();
const char* code = sourceCode.c_str();
cl_program pid = clCreateProgramWithSource(_id, 1, &code, &length, &_eid);
detail::reportError("Context::createProgramFromSourceCode(): ", _eid);
return pid ? Program(this, pid) : Program();
}
Program Context::createProgramFromSourceFile(const string& fileName)
{
string sourceCode;
if(!detail::readAsString(fileName, &sourceCode))
return Program();
return createProgramFromSourceCode(sourceCode);
}
Program Context::buildProgramFromSourceCode(const string& sourceCode,
const string& options)
{
Program program = createProgramFromSourceCode(sourceCode);
if(program.isNull() || program.build(options))
return program;
return Program();
}
Program Context::buildProgramFromSourceFile(const string& fileName,
const string& options)
{
Program program = createProgramFromSourceFile(fileName);
if(program.isNull() || program.build(options))
return program;
return Program();
}
}
| 35.055901 | 82 | 0.56408 | k0zmo |
6817374a7adaf810a5621a991bc6c6638fa695f5 | 457 | tpp | C++ | src/tp_plus_examples/src/tst_user_input.tpp | kobbled/rossum_example_ws | b705b8afab229a607c687bb9fb7dc7dac9bad87e | [
"Apache-2.0"
] | null | null | null | src/tp_plus_examples/src/tst_user_input.tpp | kobbled/rossum_example_ws | b705b8afab229a607c687bb9fb7dc7dac9bad87e | [
"Apache-2.0"
] | null | null | null | src/tp_plus_examples/src/tst_user_input.tpp | kobbled/rossum_example_ws | b705b8afab229a607c687bb9fb7dc7dac9bad87e | [
"Apache-2.0"
] | null | null | null | # Print a ascii tree with the base length
# specified by the user
# -----------------------
userclear()
usershow()
number := R[56]
number = userReadInt('enter length of ascii tree.')
i := R[46]
Dummy_1 := R[225]
Dummy_1 = number - 1
for i in (0 to Dummy_1)
Dummy_2 := R[226]
Dummy_2 = Dummy_1 - i
j := R[48]
for j in (0 to Dummy_2)
print(' ')
end
k := R[50]
for k in (0 to i)
print('* ')
end
print_line('')
end
| 15.758621 | 51 | 0.544858 | kobbled |
6817d1b46bef915ad538225b3ecabdd2f05de687 | 1,668 | cpp | C++ | src/database/overlay/SoXipMenuStyle.cpp | OpenXIP/xip-libraries | 9f0fef66038b20ff0c81c089d7dd0038e3126e40 | [
"Apache-2.0"
] | 2 | 2020-05-21T07:06:07.000Z | 2021-06-28T02:14:34.000Z | src/database/overlay/SoXipMenuStyle.cpp | OpenXIP/xip-libraries | 9f0fef66038b20ff0c81c089d7dd0038e3126e40 | [
"Apache-2.0"
] | null | null | null | src/database/overlay/SoXipMenuStyle.cpp | OpenXIP/xip-libraries | 9f0fef66038b20ff0c81c089d7dd0038e3126e40 | [
"Apache-2.0"
] | 6 | 2016-03-21T19:53:18.000Z | 2021-06-08T18:06:03.000Z | /*
Copyright (c) 2011, Siemens Corporate Research a Division of Siemens Corporation
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <Inventor/actions/SoGLRenderAction.h>
#include "SoXipMenuStyle.h"
#include "SoXipMenuStyleElement.h"
SO_NODE_SOURCE( SoXipMenuStyle );
SoXipMenuStyle::SoXipMenuStyle()
{
SO_NODE_CONSTRUCTOR( SoXipMenuStyle );
SO_NODE_ADD_FIELD( color, (0xccccccff) );
SO_NODE_ADD_FIELD( focusedColor, (0xffffaaff) );
SO_NODE_ADD_FIELD( disabledColor, (0xccccccff) );
SO_NODE_ADD_FIELD( textColor, (0, 0, 0) );
SO_NODE_ADD_FIELD( focusedTextColor, (0, 0, 0) );
SO_NODE_ADD_FIELD( disabledTextColor, (0.8, 0.8, 0.8) );
}
SoXipMenuStyle::~SoXipMenuStyle()
{
}
void
SoXipMenuStyle::initClass()
{
SO_NODE_INIT_CLASS( SoXipMenuStyle, SoNode, "Node" );
SO_ENABLE( SoGLRenderAction, SoXipMenuStyleElement );
}
void
SoXipMenuStyle::GLRender( SoGLRenderAction* action )
{
if( action->getState() )
{
SbXipMenuStyle style( color, focusedColor, disabledColor,
textColor.getValue(), focusedTextColor.getValue(), disabledTextColor.getValue() );
SoXipMenuStyleElement::set( action->getState(), this, style );
}
}
| 27.8 | 85 | 0.757794 | OpenXIP |
68194d10b70a101f39dcf8c5c984e13a327be87d | 929 | cpp | C++ | src/pdb_component/parsers/hb/source/src/vdw/ca_main.cpp | MelvinYin/Defined_Proteins | 75da20be82a47d85d27176db29580ab87d52b670 | [
"BSD-3-Clause"
] | 2 | 2021-01-05T02:55:57.000Z | 2021-04-16T15:49:08.000Z | src/pdb_component/parsers/hb/source/src/vdw/ca_main.cpp | MelvinYin/Defined_Proteins | 75da20be82a47d85d27176db29580ab87d52b670 | [
"BSD-3-Clause"
] | null | null | null | src/pdb_component/parsers/hb/source/src/vdw/ca_main.cpp | MelvinYin/Defined_Proteins | 75da20be82a47d85d27176db29580ab87d52b670 | [
"BSD-3-Clause"
] | 1 | 2021-01-05T08:12:38.000Z | 2021-01-05T08:12:38.000Z | #include "pdb_data.hpp"
#include "contact_data.hpp"
#include "contact_formatting.hpp"
int main(int argc, char *argv[])
{
if (argc<4)
{
printf("You must supply a filename to compute on, filename for contacts data, as well as the filename for residue bounds data.");
return -1;
};
// Read the structure in
string input_fname(argv[1]);
string atomcs_fname(argv[2]);
string bounds_fname(argv[3]);
FILE* fh = openFile(argv[1], "r");
if (! fh)
return -1;
AtomVector vec = parseAtomLines(fh);
fclose(fh);
// Compute contacts on it
ContactResult r = contactForAtoms(vec);
// Format distances for individual atom contacts and output it
AtomBasicsVector atomcs = formatAtomBasics(vec, r);
writeAtomBasics(atomcs_fname, atomcs);
// Write chain residues (bounds)
ChainBounds bounds = makeChainBounds(vec);
writeChainBounds(bounds_fname, bounds);
return 0;
};
| 29.967742 | 135 | 0.684607 | MelvinYin |
681a4a6294a488761f7e7f2d495b7c95e3556d21 | 2,195 | cpp | C++ | com/win32comext/taskscheduler/src/PyIProvideTaskPage.cpp | huanyin88/Mod-Pywin32-For-Python3.x-DDE | 992931aa534357d54aaac34077f0128d3a740e5e | [
"Apache-2.0"
] | 3 | 2020-06-18T16:57:44.000Z | 2020-07-21T17:52:06.000Z | com/win32comext/taskscheduler/src/PyIProvideTaskPage.cpp | huanyin88/Mod-Pywin32-For-Python3.x-DDE | 992931aa534357d54aaac34077f0128d3a740e5e | [
"Apache-2.0"
] | null | null | null | com/win32comext/taskscheduler/src/PyIProvideTaskPage.cpp | huanyin88/Mod-Pywin32-For-Python3.x-DDE | 992931aa534357d54aaac34077f0128d3a740e5e | [
"Apache-2.0"
] | null | null | null | // This file implements the IProvideTaskPage Interface for Python.
// Generated by makegw.py
#include "PyIProvideTaskPage.h"
#include "PyWinObjects.h"
// @doc - This file contains autoduck documentation
// ---------------------------------------------------
//
// Interface Implementation
PyIProvideTaskPage::PyIProvideTaskPage(IUnknown *pdisp) : PyIUnknown(pdisp) { ob_type = &type; }
PyIProvideTaskPage::~PyIProvideTaskPage() {}
/* static */ IProvideTaskPage *PyIProvideTaskPage::GetI(PyObject *self)
{
return (IProvideTaskPage *)PyIUnknown::GetI(self);
}
// @pymethod |PyIProvideTaskPage|GetPage|Return a property sheet page handle for the spedified type
// (TASKPAGE_TASK,TASKPAGE_SCHEDULE,TASKPAGE_SETTINGS)
// @comm There's not yet anything useful that can be done with this handle - return type subject to change
PyObject *PyIProvideTaskPage::GetPage(PyObject *self, PyObject *args)
{
IProvideTaskPage *pIPTP = GetI(self);
if (pIPTP == NULL)
return NULL;
TASKPAGE tpType;
// @pyparm int|tpType||Type of page to retreive (TASKPAGE_TASK,TASKPAGE_SCHEDULE,TASKPAGE_SETTINGS)
// @pyparm bool|PersistChanges||Indicates if changes should be saved automatically
HPROPSHEETPAGE phPage;
BOOL bPersistChanges;
if (!PyArg_ParseTuple(args, "ii:GetPage", &tpType, &bPersistChanges))
return NULL;
HRESULT hr;
PY_INTERFACE_PRECALL;
hr = pIPTP->GetPage(tpType, bPersistChanges, &phPage);
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return PyCom_BuildPyException(hr, pIPTP, IID_IProvideTaskPage);
return PyWinLong_FromHANDLE(phPage);
}
// @object PyIProvideTaskPage|Description of the interface
static struct PyMethodDef PyIProvideTaskPage_methods[] = {
{"GetPage", PyIProvideTaskPage::GetPage, 1}, // @pymeth GetPage|Return a property sheet page handle for the
// spedified type (TASKPAGE_TASK,TASKPAGE_SCHEDULE,TASKPAGE_SETTINGS)
{NULL}};
PyComTypeObject PyIProvideTaskPage::type("PyIProvideTaskPage", &PyIUnknown::type, sizeof(PyIProvideTaskPage),
PyIProvideTaskPage_methods, GET_PYCOM_CTOR(PyIProvideTaskPage));
| 39.909091 | 119 | 0.708884 | huanyin88 |
681bd6ac1bf927097f4279af4eafa91873035a77 | 7,147 | hpp | C++ | svntrunk/src/bgfe/obsolete_pk/reactor/include/reactor.hpp | Bhaskers-Blu-Org1/BlueMatter | 1ab2c41af870c19e2e1b1095edd1d5c85eeb9b5e | [
"BSD-2-Clause"
] | 7 | 2020-02-25T15:46:18.000Z | 2022-02-25T07:04:47.000Z | svntrunk/src/bgfe/obsolete_pk/reactor/include/reactor.hpp | IBM/BlueMatter | 5243c0ef119e599fc3e9b7c4213ecfe837de59f3 | [
"BSD-2-Clause"
] | null | null | null | svntrunk/src/bgfe/obsolete_pk/reactor/include/reactor.hpp | IBM/BlueMatter | 5243c0ef119e599fc3e9b7c4213ecfe837de59f3 | [
"BSD-2-Clause"
] | 5 | 2019-06-06T16:30:21.000Z | 2020-11-16T19:43:01.000Z | /* Copyright 2001, 2019 IBM Corporation
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
THIS FILE HAS BEEN RETIRED AND SHOULD NOT BE INCLUDED
/***************************************************************************
* Project: pK
*
* Module: pkreactor.hpp
*
* Purpose: Provide reactor messages using mpi.
*
* Classification: IBM Internal Use Only
*
* History: 010297 BGF Created.
*
***************************************************************************/
#ifndef __PKREACTOR_HPP__
#define __PKREACTOR_HPP__
#ifndef PKFXLOG_PKREACTOR
#define PKFXLOG_PKREACTOR (0)
#endif
#ifndef PKREACTOR_DATAGRAM_SIZE
#define PKREACTOR_DATAGRAM_SIZE (32 * 1024)
#endif
#define PKREACTOR_OK (0)
#define PKREACTOR_DETATCH_BUFFER (1)
#define PKREACTOR_ERROR (-1)
#include <stdio.h>
#include <assert.h>
#ifdef MPI
#include <pk/mpi.hpp>
#endif
#include <pk/pthread.hpp>
#include <pk/pktrace.hpp>
#include <pk/fxlogger.hpp>
#include <pk/yieldlock.hpp>
#if BLUEGENE
#ifndef BLUEGENE_PACKET_PAYLOAD_SIZE
#define BLUEGENE_PACKET_PAYLOAD_SIZE 250
#endif
// Redefine datagram size to bluegene payload size.
#undef PKREACTOR_DATAGRAM_SIZE
#define PKREACTOR_DATAGRAM_SIZE BLUEGENE_PACKET_PAYLOAD_SIZE
typedef int (*PkActorFxPtr)( // no src for BLUEGENE
// no len for BLUEGENE
void *MsgBuf );
// A reactor provides local state with the function invocation.
typedef int (*PkReactorFxPtr)(void *State,
void *MsgBuf );
#else
typedef int (*PkActorFxPtr)(unsigned SrcProc,
unsigned MsgLen,
void *MsgBuf );
// A reactor provides local state with the function invocation.
typedef int (*PkReactorFxPtr)(void *State,
unsigned SrcProc,
unsigned MsgLen,
void *MsgBuf );
#endif
typedef struct ReactorTableEntry
{
char *State;
PkReactorFxPtr RFxPtr;
};
typedef struct
{
int Task;
ReactorTableEntry *ReactorTableEntryPtr;
int IsValid() { return( ReactorTableEntryPtr != NULL ); }
} ReactorHandle;
#ifdef MPI
class PkActiveMsgSubSys : public PhysicalThreadContext, public YieldLockable
#else
#ifdef SMP
class PkActiveMsgSubSys : public PhysicalThreadContext, public YieldLockable
#else
class PkActiveMsgSubSys : public YieldLockable
#endif
#endif
{
public :
PkActiveMsgSubSys( );
ReactorTableEntry ReactorTable[1024];
ReactorTableEntry *ReactorTableNext;
public:
static int Init();
static int IsInit();
static int Trigger( int TaskNo,
PkActorFxPtr FxPtr,
void *Msg,
unsigned MsgLen);
static int Trigger( ReactorHandle Handle,
void *Msg,
unsigned MsgLen);
static
ReactorHandle RegisterReactor( char *State, PkReactorFxPtr RFxPtr );
void *PhysicalThreadMain( void *arg );
typedef char Buffer[PKREACTOR_DATAGRAM_SIZE];
typedef char *BufferPtr;
#ifdef MPI
MPI_Comm REACTIVE_MESSAGE_COMM_WORLD;
BufferPtr *AllBuf ; // A pointer to an array of pointers.
MPI_Request *AllRequests;
MPI_Status *AllStatus ;
#endif // end ifdef mpi
// Pk Trace point state
TraceClient TraceTrigger;
TraceClient TraceExecute;
int TracePPid;
char TraceName[128];
// The buffer pool is a stack of free buffers. It is worth maintaining
// as a stack rather than a circular queue becuase it is hoped that the
// bottom of the stack will point to buffers that have been paged out
// of memory because they haven't been used.
// NEED: The GetBuffer/FreeBuffer routines contain dyanamic memory calls.
// Although the delete call may never be made, An assert it placed after
// the 'new' call which will catch the worst offenders.
#define FREE_BUFFER_POOL_SIZE (16 * 1024)
BufferPtr FreeBufferPool[FREE_BUFFER_POOL_SIZE];
int FreeBufferPoolCount;
int FreeBufferPoolLockWord;
int BuffersInService;
BufferPtr
GetBuffer()
{
BufferPtr ReturnBufferPtr;
YieldLock( FreeBufferPoolLockWord );
if( FreeBufferPoolCount > 0 )
{
int Index = --FreeBufferPoolCount; // NEED: make this SMP safe!
ReturnBufferPtr = FreeBufferPool[ Index ];
}
else
{
BuffersInService++;
BegLogLine( PKFXLOG_PKREACTOR )
<< " GetBuffer() "
<< " allocating Buffer to cnt: "
<< BuffersInService
<< EndLogLine;
ReturnBufferPtr = new Buffer;
// The following assert means that something is consuming
// actor receive buffers. If this assert goes off, think hard!
assert( ReturnBufferPtr != NULL );
}
UnYieldLock( FreeBufferPoolLockWord );
return( ReturnBufferPtr );
}
void
FreeBuffer( void * BufferToFree )
{
YieldLock( FreeBufferPoolLockWord );
if( FreeBufferPoolCount < FREE_BUFFER_POOL_SIZE )
{
FreeBufferPool[ FreeBufferPoolCount ] = ( BufferPtr ) BufferToFree;
FreeBufferPoolCount++;
}
else
{
BuffersInService--;
BegLogLine( PKFXLOG_PKREACTOR )
<< " FreeBuffer() "
<< " Forced to do delete from cnt: "
<< BuffersInService
<< EndLogLine;
delete (BufferPtr) BufferToFree; //LINUX/GCC cast pointer to type to delete
}
UnYieldLock( FreeBufferPoolLockWord );
}
static PkActiveMsgSubSys* GetIFPtr();
};
#endif
| 29.171429 | 118 | 0.633972 | Bhaskers-Blu-Org1 |
681d1dfa678d19cb65a83b8532d3079b9fb2d741 | 3,764 | cpp | C++ | engine/time/source/CreatureStatisticsMarkerChecker.cpp | prolog/shadow-of-the-wyrm | a1312c3e9bb74473f73c4e7639e8bd537f10b488 | [
"MIT"
] | 60 | 2019-08-21T04:08:41.000Z | 2022-03-10T13:48:04.000Z | engine/time/source/CreatureStatisticsMarkerChecker.cpp | prolog/shadow-of-the-wyrm | a1312c3e9bb74473f73c4e7639e8bd537f10b488 | [
"MIT"
] | 3 | 2021-03-18T15:11:14.000Z | 2021-10-20T12:13:07.000Z | engine/time/source/CreatureStatisticsMarkerChecker.cpp | prolog/shadow-of-the-wyrm | a1312c3e9bb74473f73c4e7639e8bd537f10b488 | [
"MIT"
] | 8 | 2019-11-16T06:29:05.000Z | 2022-01-23T17:33:43.000Z | #include "CreatureStatisticsMarkerChecker.hpp"
#include "EngineConversion.hpp"
#include "HungerCalculator.hpp"
#include "RaceManager.hpp"
#include "RNG.hpp"
#include "StatisticsMarker.hpp"
using namespace std;
const int CreatureStatisticsMarkerChecker::PASSIVE_STATISTIC_THRESHOLD = 15;
CreatureStatisticsMarkerChecker::CreatureStatisticsMarkerChecker()
: minutes_interval(9999)
{
}
CreatureStatisticsMarkerChecker::CreatureStatisticsMarkerChecker(const uint new_interval)
: minutes_interval(new_interval)
{
}
void CreatureStatisticsMarkerChecker::tick(CreaturePtr creature, TilePtr tile, const ulonglong min_this_tick, const ulonglong total_minutes_elapsed)
{
if (creature != nullptr)
{
if (total_minutes_elapsed % minutes_interval == 0)
{
check_strength_conditions(creature);
check_health_conditions(creature);
check_charisma_conditions(creature);
}
}
}
// If a creature is consistently carrying around heavy loads, it will become
// stronger.
void CreatureStatisticsMarkerChecker::check_strength_conditions(CreaturePtr creature)
{
BurdenLevel bl = BurdenLevelConverter::to_burden_level(creature);
int num_marks = 0;
if (bl == BurdenLevel::BURDEN_LEVEL_BURDENED)
{
num_marks++;
}
else if (bl == BurdenLevel::BURDEN_LEVEL_STRAINED)
{
num_marks += 2;
}
StatisticsMarker sm;
if (can_increase_passive_statistic(creature->get_strength()))
{
for (int i = 0; i < num_marks; i++)
{
sm.mark_strength(creature);
}
}
}
// If a creature maintains a good level of satiation, being neither full
// nor hungry, this will increase their overall health. Up to a point -
// otherwise, Fae would be able to get 99 Hea by just waiting around.
void CreatureStatisticsMarkerChecker::check_health_conditions(CreaturePtr creature)
{
if (creature != nullptr && can_increase_passive_statistic(creature->get_health()))
{
HungerLevel hl = HungerLevelConverter::to_hunger_level(creature->get_hunger_clock().get_hunger());
RaceManager rm;
Race* race = rm.get_race(creature->get_race_id());
// Ensure that hungerless races like the fae don't easily max out Health
// simply by existing. Hungerless races can still increase health over
// time, but at a much reduced rate.
if (race != nullptr)
{
HungerCalculator hc;
if (RNG::percent_chance(hc.calculate_pct_chance_mark_health(hl, race->get_hungerless())))
{
StatisticsMarker sm;
sm.mark_health(creature);
}
}
}
}
void CreatureStatisticsMarkerChecker::check_charisma_conditions(CreaturePtr creature)
{
Equipment& eq = creature->get_equipment();
Statistic cha = creature->get_charisma();
ItemPtr lf = eq.get_item(EquipmentWornLocation::EQUIPMENT_WORN_LEFT_FINGER);
ItemPtr rf = eq.get_item(EquipmentWornLocation::EQUIPMENT_WORN_RIGHT_FINGER);
ItemPtr neck = eq.get_item(EquipmentWornLocation::EQUIPMENT_WORN_NECK);
vector<ItemPtr> items = {lf, rf, neck};
vector<ItemType> jewelry_types = {ItemType::ITEM_TYPE_AMULET, ItemType::ITEM_TYPE_RING};
bool adorned = false;
for (ItemPtr item : items)
{
if (item != nullptr)
{
ItemType itype = item->get_type();
if (std::find(jewelry_types.begin(), jewelry_types.end(), itype) != jewelry_types.end())
{
adorned = true;
break;
}
}
}
StatisticsMarker sm;
if (can_increase_passive_statistic(cha) && adorned)
{
sm.mark_charisma(creature);
}
}
bool CreatureStatisticsMarkerChecker::can_increase_passive_statistic(const Statistic& stat)
{
bool can_increase = false;
int modifier = (stat.get_base() - stat.get_original());
if (modifier < PASSIVE_STATISTIC_THRESHOLD)
{
can_increase = true;
}
return can_increase;
} | 27.881481 | 148 | 0.729012 | prolog |
681e3bb316222511721a5a0d06ac03fe59db21d5 | 660 | hpp | C++ | ComputerInfo.hpp | Ferinko/CPPAmpRaytracer | 459d9804cadd0489eea335cf4b6ba4a1256f76dd | [
"MIT"
] | null | null | null | ComputerInfo.hpp | Ferinko/CPPAmpRaytracer | 459d9804cadd0489eea335cf4b6ba4a1256f76dd | [
"MIT"
] | null | null | null | ComputerInfo.hpp | Ferinko/CPPAmpRaytracer | 459d9804cadd0489eea335cf4b6ba4a1256f76dd | [
"MIT"
] | null | null | null | #pragma once
#include <amp.h>
#include <ostream>
namespace Smurf {
void printPCInfo(std::wostream& os) {
auto accelerators = Concurrency::accelerator::get_all();
for (auto && elem : accelerators) {
os << elem.description << std::endl;
}
}
void printRayTraceInfo(std::wostream& os) {
os << L"Resolution: " << Settings::HRes << L" * " << Settings::VRes << "\n"
<< L"Antialiasing: " << Settings::NumSamples << "\n"
<< L"Shading: " << L"Simple lights" << "\n"
<< L"Materials: " << L"Matte" << "\n"
<< std::endl;
}
} // namespace Smurf | 30 | 84 | 0.506061 | Ferinko |
6821abf0af39f37c7d40ab5361c375fe549a2445 | 2,249 | cpp | C++ | Krispy/src/Krispy/Core/OrthographicCameraController.cpp | Dallin343/GameEngine | 029de5127edb29f3372b354cf8902a29ee80d768 | [
"MIT"
] | null | null | null | Krispy/src/Krispy/Core/OrthographicCameraController.cpp | Dallin343/GameEngine | 029de5127edb29f3372b354cf8902a29ee80d768 | [
"MIT"
] | null | null | null | Krispy/src/Krispy/Core/OrthographicCameraController.cpp | Dallin343/GameEngine | 029de5127edb29f3372b354cf8902a29ee80d768 | [
"MIT"
] | null | null | null | //
// Created by dallin on 9/11/20.
//
#include "OrthographicCameraController.h"
namespace Krispy {
OrthographicCameraController::OrthographicCameraController(float aspectRatio, bool rotation)
: m_Rotation(rotation), m_AspectRatio(aspectRatio),
m_Camera(-m_AspectRatio * m_ZoomLevel, m_AspectRatio * m_ZoomLevel, -m_ZoomLevel, m_ZoomLevel) {
}
void OrthographicCameraController::OnUpdate(Timestep ts) {
if (Input::IsKeyPressed(KRISPY_KEY_D)) {
m_CameraPosition.x += m_CameraTranslationSpeed * ts;
} if (Input::IsKeyPressed(KRISPY_KEY_A)) {
m_CameraPosition.x -= m_CameraTranslationSpeed * ts;
}
if (Input::IsKeyPressed(KRISPY_KEY_W)) {
m_CameraPosition.y += m_CameraTranslationSpeed * ts;
} if (Input::IsKeyPressed(KRISPY_KEY_S)) {
m_CameraPosition.y -= m_CameraTranslationSpeed * ts;
}
if (m_Rotation) {
if (Input::IsKeyPressed(KRISPY_KEY_Q)) {
m_CameraRotation += m_CameraRotationSpeed * ts;
} if (Input::IsKeyPressed(KRISPY_KEY_E)) {
m_CameraRotation -= m_CameraRotationSpeed * ts;
}
m_Camera.SetRotation(m_CameraRotation);
}
m_Camera.SetPosition(m_CameraPosition);
m_CameraTranslationSpeed = m_ZoomLevel;
}
void OrthographicCameraController::OnEvent(Event &e) {
EventDispatcher dispatcher(e);
dispatcher.Dispatch<MouseScrolledEvent>(BIND_EVENT_FN(OnMouseScrolled));
dispatcher.Dispatch<WindowResizeEvent>(BIND_EVENT_FN(OnWindowResized));
}
bool OrthographicCameraController::OnMouseScrolled(MouseScrolledEvent &e) {
m_ZoomLevel -= e.GetYOffset() * 0.25f;
m_ZoomLevel = std::max(m_ZoomLevel, 0.25f);
m_Camera.SetProjection(-m_AspectRatio * m_ZoomLevel, m_AspectRatio * m_ZoomLevel, -m_ZoomLevel, m_ZoomLevel);
return false;
}
bool OrthographicCameraController::OnWindowResized(WindowResizeEvent &e) {
m_AspectRatio = (float) e.GetWidth() / (float) e.GetHeight();
m_Camera.SetProjection(-m_AspectRatio * m_ZoomLevel, m_AspectRatio * m_ZoomLevel, -m_ZoomLevel, m_ZoomLevel);
return false;
}
}
| 36.274194 | 117 | 0.672743 | Dallin343 |
68240349f35988ea521f53be03241ffc2a993d52 | 5,149 | cpp | C++ | ProjectEuler+/euler-0015.cpp | sarvekash/HackerRank_Solutions | 8f48e5b1a6e792a85a10d8c328cd1f5341fb16a8 | [
"Apache-2.0"
] | null | null | null | ProjectEuler+/euler-0015.cpp | sarvekash/HackerRank_Solutions | 8f48e5b1a6e792a85a10d8c328cd1f5341fb16a8 | [
"Apache-2.0"
] | null | null | null | ProjectEuler+/euler-0015.cpp | sarvekash/HackerRank_Solutions | 8f48e5b1a6e792a85a10d8c328cd1f5341fb16a8 | [
"Apache-2.0"
] | 1 | 2021-05-28T11:14:34.000Z | 2021-05-28T11:14:34.000Z | // ////////////////////////////////////////////////////////
// # Title
// Lattice paths
//
// # URL
// https://projecteuler.net/problem=15
// http://euler.stephan-brumme.com/15/
//
// # Problem
// Starting in the top left corner of a 2x2 grid, and only being able to move to the right and down,
// there are exactly 6 routes to the bottom right corner.
//
// 
//
// How many such routes are there through a 20x20 grid?
//
// # Solved by
// Stephan Brumme
// February 2017
//
// # Algorithm
// Each grid consists of ''(width+1)*(height+1)'' points. The grid in the problem statement has ''(2+1)*(2+1)=9'' points.
// I chose my coordinates to be ''[0][0]'' in the top left corner and ''[width][height]'' in the bottom right corner.
//
// For each point in a grid, the number of routes from the current point to the lower right corner
// is the sum of all routes when going right plus all routes when going down:
// ''grid[x][y] = grid[x+1][y] + grid[x][y+1];''
//
// There is a single route from the lower right corner to itself ("stay where you are"):
// ''grid[width][height] = 1;''
//
// Now I perform a breadth-first search ( https://en.wikipedia.org/wiki/Breadth-first_search ) from the lower-right corner to the upper-left corner.
// A queue named ''next'' contains the coordinates of the next points to analyze - initially it holds the point above the lower-right corner
// and the point to the left of the lower-right corner.
//
// A loop processes each point in ''next'':
// 1. If this point was already processed, skip it
// 2. If it is possible to move right then get the number of routes stored in ''grid[x+1][y]''
// 3. If it is possible to move down then get the number of routes stored in ''grid[x][y+1]''
// 4. Write the sum of step 2 and 3 to ''grid[x][y]'', potentially avoid overflow (see Hackerrank modification)
// 5. If there is a left neighbor, enqueue it in ''next''
// 6. If there is a neighbor above, enqueue it in ''next''
//
// Finally we have the result in ''grid[0][0]''.
//
// # Alternative
// I later found a posting on the internet that the result is
//
// `dfrac{(width + height)!}{width! height!}`
//
// but I'm not a math guy, I'm a programmer ...
// however, the best explanation for that formula is as follows and unfortunately, it's about bits :-) :
//
// If we take any route through the grid then a decision has to be made at each point: walk to the right or walk down.
// That's similar to a binary number where each bit can be either 0 or 1. Let's say 0 means "right" and 1 means "down".
//
// Then we have to make `width + height` decisions: exactly `width` times we have to go right and exactly `height` times we have to go down.
// In our imaginary binary number, there are `width + height` bits with `height` times 0s and `width` times 1s.
//
// All permutations of these bits are valid routes in the grid.
//
// And as turns out, there are `dfrac{(width + height)!}{width! height!}` permutations, see https://en.wikipedia.org/wiki/Permutation
//
// # Hackerrank
// The result should be printed ` mod (10^9 + 7)`
#include <vector>
#include <deque>
#include <utility>
#include <iostream>
int main()
{
unsigned int tests;
std::cin >> tests;
while (tests--)
{
unsigned int width, height;
std::cin >> width >> height;
// create a 2D array which contains the number of paths
// from the current lattice point to the lower-right corner
// there are (width + 1) * (height + 1) such points
// for the original problem, i.e. 21x21 numbers must be found
const unsigned long long Unknown = 0;
std::vector<std::vector<unsigned long long>> grid(width + 1);
for (auto& column : grid)
column.resize(height + 1, Unknown);
// one route if we are already at the goal
grid[width][height] = 1;
// enqueue the next unprocessed lattice points: left and upper neighbor of the lower-right corner
std::deque<std::pair<unsigned int, unsigned int>> next;
next.push_back(std::make_pair(width - 1, height));
next.push_back(std::make_pair(width, height - 1));
// as long as there are unprocessed points
while (!next.empty())
{
// get next point
auto current = next.front();
next.pop_front();
// I prefer names which are easier to read ...
auto x = current.first;
auto y = current.second;
// already solved ?
if (grid[x][y] != Unknown)
continue;
// sum of all path when going right plus when going down
unsigned long long routes = 0;
if (x < width) // can go right ?
routes += grid[x + 1][y];
if (y < height) // can go down ?
routes += grid[x][y + 1];
#define ORIGINAL
#ifndef ORIGINAL
routes %= 1000000007; // Hackerrank wants the result MOD 10^9 + 7
#endif
// solved number for current lattice point
grid[x][y] = routes;
// add left and upper neighbors for further processing
if (x > 0)
next.push_back(std::make_pair(x - 1, y));
if (y > 0)
next.push_back(std::make_pair(x, y - 1));
}
// we are done !
std::cout << grid[0][0] << std::endl;
}
return 0;
}
| 37.043165 | 148 | 0.646533 | sarvekash |
6825cbe7fd45c02203f82d3966e4fa4776b31e87 | 19,718 | cpp | C++ | msf_localization_ros/src/source/ros_free_model_robot_interface.cpp | Ahrovan/msf_localization | a78ba2473115234910789617e9b45262ebf1d13d | [
"BSD-3-Clause"
] | 1 | 2021-02-27T15:23:13.000Z | 2021-02-27T15:23:13.000Z | msf_localization_ros/src/source/ros_free_model_robot_interface.cpp | Ahrovan/msf_localization | a78ba2473115234910789617e9b45262ebf1d13d | [
"BSD-3-Clause"
] | null | null | null | msf_localization_ros/src/source/ros_free_model_robot_interface.cpp | Ahrovan/msf_localization | a78ba2473115234910789617e9b45262ebf1d13d | [
"BSD-3-Clause"
] | null | null | null |
#include "msf_localization_ros/ros_free_model_robot_interface.h"
#include "msf_localization_core/msfLocalization.h"
RosFreeModelRobotInterface::RosFreeModelRobotInterface(ros::NodeHandle* nh, tf::TransformBroadcaster *tf_transform_broadcaster, MsfLocalizationCore* msf_localization_core_ptr) :
RosRobotInterface(nh, tf_transform_broadcaster),
FreeModelRobotCore(msf_localization_core_ptr)
{
return;
}
RosFreeModelRobotInterface::~RosFreeModelRobotInterface()
{
return;
}
bool RosFreeModelRobotInterface::getPoseWithCovarianceByStamp(msf_localization_ros_srvs::GetPoseWithCovarianceByStamp::Request &req,
msf_localization_ros_srvs::GetPoseWithCovarianceByStamp::Response &res)
{
// Variables
TimeStamp requested_time_stamp;
TimeStamp received_time_stamp;
std::shared_ptr<StateEstimationCore> received_state;
// Fill request
requested_time_stamp=TimeStamp(req.requested_stamp.sec, req.requested_stamp.nsec);
if(!this->getMsfLocalizationCorePtr())
{
std::cout<<"Error!"<<std::endl;
return false;
}
// Do the request
int error=this->getMsfLocalizationCorePtr()->getStateByStamp(requested_time_stamp,
received_time_stamp, received_state);
// Fill response
// Success
if(error)
{
res.success=false;
return true;
}
else
{
res.success=true;
}
// Received TimeStamp
res.received_stamp=ros::Time(received_time_stamp.getSec(), received_time_stamp.getNSec());
// Received State
this->setRobotPoseWithCovarianceMsg(std::dynamic_pointer_cast<RobotStateCore>(received_state->state_component_->TheRobotStateCore), *received_state->state_component_->covarianceMatrix,
res.received_pose);
// Free state ownership
if(received_state)
received_state.reset();
// End
return true;
}
int RosFreeModelRobotInterface::readParameters()
{
// Topic names
// Pose
//
ros::param::param<std::string>("~robot_pose_with_cov_topic_name", robotPoseWithCovarianceStampedTopicName, "msf_localization/robot_pose_cov");
std::cout<<"\t robot_pose_with_cov_topic_name="<<robotPoseWithCovarianceStampedTopicName<<std::endl;
//
ros::param::param<std::string>("~robot_pose_topic_name", robotPoseStampedTopicName, "msf_localization/robot_pose");
std::cout<<"\t robot_pose_topic_name="<<robotPoseStampedTopicName<<std::endl;
//
ros::param::param<std::string>("~robot_pose_with_covariance_stamped_srv_name", robot_pose_with_covariance_stamped_srv_name_, "msf_localization/robot_pose_cov");
std::cout<<"\t robot_pose_with_covariance_stamped_srv_name="<<robot_pose_with_covariance_stamped_srv_name_<<std::endl;
// Velocities
//
ros::param::param<std::string>("~robot_velocities_stamped_topic_name", robot_velocities_stamped_topic_name_, "msf_localization/robot_velocity");
std::cout<<"\t robot_velocities_stamped_topic_name="<<robot_velocities_stamped_topic_name_<<std::endl;
//
ros::param::param<std::string>("~robot_velocities_with_covariance_stamped_topic_name", robot_velocities_with_covariance_stamped_topic_name_, "msf_localization/robot_velocity_cov");
std::cout<<"\t robot_velocities_with_covariance_stamped_topic_name="<<robot_velocities_with_covariance_stamped_topic_name_<<std::endl;
//
ros::param::param<std::string>("~robot_linear_speed_topic_name", robotLinearSpeedStampedTopicName, "msf_localization/robot_linear_speed");
std::cout<<"\t robot_linear_speed_topic_name="<<robotLinearSpeedStampedTopicName<<std::endl;
//
ros::param::param<std::string>("~robot_angular_velocity_topic_name", robotAngularVelocityStampedTopicName, "msf_localization/robot_angular_velocity");
std::cout<<"\t robot_angular_velocity_topic_name="<<robotAngularVelocityStampedTopicName<<std::endl;
// Accelerations
//
ros::param::param<std::string>("~robot_accelerations_stamped_topic_name", robot_accelerations_stamped_topic_name_, "msf_localization/robot_acceleration");
std::cout<<"\t robot_accelerations_stamped_topic_name_="<<robot_accelerations_stamped_topic_name_<<std::endl;
//
ros::param::param<std::string>("~robot_accelerations_with_covariance_stamped_topic_name", robot_accelerations_with_covariance_stamped_topic_name_, "msf_localization/robot_acceleration_cov");
std::cout<<"\t robot_accelerations_with_covariance_stamped_topic_name="<<robot_accelerations_with_covariance_stamped_topic_name_<<std::endl;
//
ros::param::param<std::string>("~robot_linear_acceleration_topic_name", robotLinearAccelerationStampedTopicName, "msf_localization/robot_linear_acceleration");
std::cout<<"\t robot_linear_acceleration_topic_name="<<robotLinearAccelerationStampedTopicName<<std::endl;
//
ros::param::param<std::string>("~robot_angular_acceleration_topic_name", robotAngularAccelerationStampedTopicName, "msf_localization/robot_angular_acceleration");
std::cout<<"\t robot_angular_acceleration_topic_name="<<robotAngularAccelerationStampedTopicName<<std::endl;
// Odometry
//
ros::param::param<std::string>("~robot_odometry_out_topic_name", robot_odometry_out_topic_name_, "msf_localization/robot_odometry");
std::cout<<"\t robot_odometry_out_topic_name="<<robot_odometry_out_topic_name_<<std::endl;
return 0;
}
int RosFreeModelRobotInterface::open()
{
// Read ROS Parameters
this->readParameters();
// Publishers
// Pose
//
robotPoseStampedPub = nh->advertise<geometry_msgs::PoseStamped>(robotPoseStampedTopicName, 1, true);
//
robotPoseWithCovarianceStampedPub = nh->advertise<geometry_msgs::PoseWithCovarianceStamped>(robotPoseWithCovarianceStampedTopicName, 1, true);
//
robot_pose_with_covariance_stamped_srv_ = nh->advertiseService(robot_pose_with_covariance_stamped_srv_name_, &RosFreeModelRobotInterface::getPoseWithCovarianceByStamp, this);
// Velocities
//
robot_velocities_stamped_pub_=nh->advertise<geometry_msgs::TwistStamped>(robot_velocities_stamped_topic_name_, 1, true);
//
robot_velocities_with_covariance_stamped_pub_=nh->advertise<geometry_msgs::TwistWithCovarianceStamped>(robot_velocities_with_covariance_stamped_topic_name_, 1, true);
//
robotLinearSpeedStampedPub = nh->advertise<geometry_msgs::Vector3Stamped>(robotLinearSpeedStampedTopicName, 1, true);
//
robotAngularVelocityStampedPub = nh->advertise<geometry_msgs::Vector3Stamped>(robotAngularVelocityStampedTopicName, 1, true);
// Accelerations
//
robot_accelerations_stamped_pub_=nh->advertise<geometry_msgs::AccelStamped>(robot_accelerations_stamped_topic_name_, 1, true);
//
robot_accelerations_with_covariance_stamped_pub_=nh->advertise<geometry_msgs::AccelWithCovarianceStamped>(robot_accelerations_with_covariance_stamped_topic_name_, 1, true);
//
robotLinearAccelerationStampedPub = nh->advertise<geometry_msgs::Vector3Stamped>(robotLinearAccelerationStampedTopicName, 1, true);
//
robotAngularAccelerationStampedPub = nh->advertise<geometry_msgs::Vector3Stamped>(robotAngularAccelerationStampedTopicName, 1, true);
// Odometry
//
robot_odometry_out_pub_=nh->advertise<nav_msgs::Odometry>(robot_odometry_out_topic_name_, 1, true);
return 0;
}
int RosFreeModelRobotInterface::setRobotPoseMsg(const std::shared_ptr<RobotStateCore>& robot_state_core,
geometry_msgs::Pose& robot_pose_msg)
{
std::shared_ptr<FreeModelRobotStateCore> TheRobotStateCore=std::static_pointer_cast<FreeModelRobotStateCore>(robot_state_core);
Eigen::Vector3d robotPosition=TheRobotStateCore->getPositionRobotWrtWorld();
Eigen::Vector4d robotAttitude=TheRobotStateCore->getAttitudeRobotWrtWorld();
// Position
robot_pose_msg.position.x=robotPosition[0];
robot_pose_msg.position.y=robotPosition[1];
robot_pose_msg.position.z=robotPosition[2];
// Attitude
robot_pose_msg.orientation.w=robotAttitude[0];
robot_pose_msg.orientation.x=robotAttitude[1];
robot_pose_msg.orientation.y=robotAttitude[2];
robot_pose_msg.orientation.z=robotAttitude[3];
return 0;
}
int RosFreeModelRobotInterface::setRobotPoseWithCovarianceMsg(const std::shared_ptr<RobotStateCore>& robot_state_core, const Eigen::MatrixXd &covariance_robot_matrix,
geometry_msgs::PoseWithCovariance& robot_pose_msg)
{
// Pose
setRobotPoseMsg(robot_state_core, robot_pose_msg.pose);
// Covariance
// TODO fix! Covariance of the attitude is not ok!
Eigen::Matrix<double, 6, 6> robotPoseCovariance;//(6,6);
robotPoseCovariance.setZero();
robotPoseCovariance.block<3,3>(0,0)=covariance_robot_matrix.block<3,3>(0,0);
robotPoseCovariance.block<3,3>(3,3)=covariance_robot_matrix.block<3,3>(9,9);
robotPoseCovariance.block<3,3>(0,3)=covariance_robot_matrix.block<3,3>(0,9);
robotPoseCovariance.block<3,3>(3,0)=covariance_robot_matrix.block<3,3>(9,0);
double robotPoseCovarianceArray[36];
Eigen::Map< Eigen::Matrix<double, 6, 6> >(robotPoseCovarianceArray, 6, 6) = robotPoseCovariance;
for(unsigned int i=0; i<36; i++)
{
robot_pose_msg.covariance[i]=robotPoseCovarianceArray[i];
}
}
int RosFreeModelRobotInterface::publish(const TimeStamp& time_stamp, const std::shared_ptr<GlobalParametersCore> &world_core, const std::shared_ptr<RobotStateCore> &robot_state_core, const Eigen::MatrixXd& covariance_robot_matrix)
{
/// tf pose robot wrt world
this->publishTfPoseRobotWrtWorld(time_stamp, world_core, robot_state_core);
/// Other publishers
// Getters
std::shared_ptr<FreeModelRobotStateCore> TheRobotStateCore=std::static_pointer_cast<FreeModelRobotStateCore>(robot_state_core);
Eigen::Vector3d robotLinearSpeed=TheRobotStateCore->getLinearSpeedRobotWrtWorld();
Eigen::Vector3d robotLinearAcceleration=TheRobotStateCore->getLinearAccelerationRobotWrtWorld();
Eigen::Vector3d robotAngularVelocity=TheRobotStateCore->getAngularVelocityRobotWrtWorld();
Eigen::Vector3d robotAngularAcceleration=TheRobotStateCore->getAngularAccelerationRobotWrtWorld();
// Fill msg
// Header
// ROBOT POSE
// Stamp
robotPoseWithCovarianceStampedMsg.header.stamp=ros::Time(time_stamp.getSec(), time_stamp.getNSec());
// Frame id
robotPoseWithCovarianceStampedMsg.header.frame_id=world_core->getWorldName();
//
robotPoseStampedMsg.header.stamp=ros::Time(time_stamp.getSec(), time_stamp.getNSec());
// Frame id
robotPoseStampedMsg.header.frame_id=world_core->getWorldName();
// Velocities
//
robot_velocities_stamped_msg_.header.stamp=ros::Time(time_stamp.getSec(), time_stamp.getNSec());
//
robot_velocities_stamped_msg_.header.frame_id=world_core->getWorldName();
//
robot_velocities_with_covariance_stamped_msg_.header.stamp=ros::Time(time_stamp.getSec(), time_stamp.getNSec());
//
robot_velocities_with_covariance_stamped_msg_.header.frame_id=world_core->getWorldName();
//
robotLinearSpeedStampedMsg.header.stamp=ros::Time(time_stamp.getSec(), time_stamp.getNSec());
// Frame id
robotLinearSpeedStampedMsg.header.frame_id=world_core->getWorldName();
//
robotAngularVelocityStampedMsg.header.stamp=ros::Time(time_stamp.getSec(), time_stamp.getNSec());
// Frame id
robotAngularVelocityStampedMsg.header.frame_id=world_core->getWorldName();
// Accelerations
//
robot_accelerations_stamped_msg_.header.stamp=ros::Time(time_stamp.getSec(), time_stamp.getNSec());
//
robot_accelerations_stamped_msg_.header.frame_id=world_core->getWorldName();
//
robot_accelerations_with_covariance_stamped_msg_.header.stamp=ros::Time(time_stamp.getSec(), time_stamp.getNSec());
//
robot_accelerations_with_covariance_stamped_msg_.header.frame_id=world_core->getWorldName();
//
robotLinearAccelerationStampedMsg.header.stamp=ros::Time(time_stamp.getSec(), time_stamp.getNSec());
// Frame id
robotLinearAccelerationStampedMsg.header.frame_id=world_core->getWorldName();
//
robotAngularAccelerationStampedMsg.header.stamp=ros::Time(time_stamp.getSec(), time_stamp.getNSec());
// Frame id
robotAngularAccelerationStampedMsg.header.frame_id=world_core->getWorldName();
/// Pose
//
this->setRobotPoseWithCovarianceMsg(robot_state_core, covariance_robot_matrix,
robotPoseWithCovarianceStampedMsg.pose);
//
this->setRobotPoseMsg(robot_state_core,
robotPoseStampedMsg.pose);
/// Velocity
geometry_msgs::Vector3 lin_vel;
lin_vel.x=robotLinearSpeed[0];
lin_vel.y=robotLinearSpeed[1];
lin_vel.z=robotLinearSpeed[2];
geometry_msgs::Vector3 ang_vel;
ang_vel.x=robotAngularVelocity[0];
ang_vel.y=robotAngularVelocity[1];
ang_vel.z=robotAngularVelocity[2];
geometry_msgs::Twist velocity;
velocity.linear=lin_vel;
velocity.angular=ang_vel;
//
robot_velocities_stamped_msg_.twist=velocity;
//
robot_velocities_with_covariance_stamped_msg_.twist.twist=velocity;
//{
Eigen::Matrix<double, 6, 6> covariance_velocity;//(6,6);
covariance_velocity.setZero();
covariance_velocity.block<3,3>(0,0)=covariance_robot_matrix.block<3,3>(3,3);
covariance_velocity.block<3,3>(3,3)=covariance_robot_matrix.block<3,3>(12,12);
covariance_velocity.block<3,3>(3,0)=covariance_robot_matrix.block<3,3>(12,3);
covariance_velocity.block<3,3>(0,3)=covariance_robot_matrix.block<3,3>(3,12);
double covariance_velocity_array[36];
Eigen::Map< Eigen::Matrix<double, 6, 6> >(covariance_velocity_array, 6, 6) = covariance_velocity;
for(unsigned int i=0; i<36; i++)
{
robot_velocities_with_covariance_stamped_msg_.twist.covariance[i]=covariance_velocity_array[i];
}
//}
//
robotLinearSpeedStampedMsg.vector=lin_vel;
//
robotAngularVelocityStampedMsg.vector=ang_vel;
/// Acceleration
geometry_msgs::Vector3 lin_acc;
lin_acc.x=robotLinearAcceleration[0];
lin_acc.y=robotLinearAcceleration[1];
lin_acc.z=robotLinearAcceleration[2];
geometry_msgs::Vector3 ang_acc;
ang_acc.x=robotAngularAcceleration[0];
ang_acc.y=robotAngularAcceleration[1];
ang_acc.z=robotAngularAcceleration[2];
geometry_msgs::Accel acceleration;
acceleration.linear=lin_acc;
acceleration.angular=ang_acc;
//
robot_accelerations_stamped_msg_.accel=acceleration;
//
robot_accelerations_with_covariance_stamped_msg_.accel.accel=acceleration;
//{
Eigen::Matrix<double, 6, 6> covariance_acceleration;//(6,6);
covariance_acceleration.setZero();
covariance_acceleration.block<3,3>(0,0)=covariance_robot_matrix.block<3,3>(6,6);
covariance_acceleration.block<3,3>(3,3)=covariance_robot_matrix.block<3,3>(15,15);
covariance_acceleration.block<3,3>(3,0)=covariance_robot_matrix.block<3,3>(15,6);
covariance_acceleration.block<3,3>(0,3)=covariance_robot_matrix.block<3,3>(6,15);
double covariance_acceleration_array[36];
Eigen::Map< Eigen::Matrix<double, 6, 6> >(covariance_acceleration_array, 6, 6) = covariance_acceleration;
for(unsigned int i=0; i<36; i++)
{
robot_accelerations_with_covariance_stamped_msg_.accel.covariance[i]=covariance_acceleration_array[i];
}
//}
//
robotLinearAccelerationStampedMsg.vector=lin_acc;
//
robotAngularAccelerationStampedMsg.vector=ang_acc;
// Odometry
robot_odometry_out_msg_.header.stamp=ros::Time(time_stamp.getSec(), time_stamp.getNSec());
robot_odometry_out_msg_.header.frame_id=world_core->getWorldName();
robot_odometry_out_msg_.child_frame_id=getRobotName();
robot_odometry_out_msg_.pose.pose=robotPoseWithCovarianceStampedMsg.pose.pose;
robot_odometry_out_msg_.pose.covariance=robotPoseWithCovarianceStampedMsg.pose.covariance;
robot_odometry_out_msg_.twist.twist=velocity;
//robot_odometry_out_msg_.twist.covariance;
//{
for(unsigned int i=0; i<36; i++)
{
robot_odometry_out_msg_.twist.covariance[i]=covariance_velocity_array[i];
}
//}
/// Publish Robot State
// Pose
if(robotPoseStampedPub.getNumSubscribers()>0)
robotPoseStampedPub.publish(robotPoseStampedMsg);
if(robotPoseWithCovarianceStampedPub.getNumSubscribers()>0)
robotPoseWithCovarianceStampedPub.publish(robotPoseWithCovarianceStampedMsg);
// Velocities
if(robot_velocities_stamped_pub_.getNumSubscribers()>0)
robot_velocities_stamped_pub_.publish(robot_velocities_stamped_msg_);
if(robot_velocities_with_covariance_stamped_pub_.getNumSubscribers()>0)
robot_velocities_with_covariance_stamped_pub_.publish(robot_velocities_with_covariance_stamped_msg_);
if(robotLinearSpeedStampedPub.getNumSubscribers()>0)
robotLinearSpeedStampedPub.publish(robotLinearSpeedStampedMsg);
if(robotAngularVelocityStampedPub.getNumSubscribers()>0)
robotAngularVelocityStampedPub.publish(robotAngularVelocityStampedMsg);
// Accelerations
if(robot_accelerations_stamped_pub_.getNumSubscribers()>0)
robot_accelerations_stamped_pub_.publish(robot_accelerations_stamped_msg_);
if(robot_accelerations_with_covariance_stamped_pub_.getNumSubscribers()>0)
robot_accelerations_with_covariance_stamped_pub_.publish(robot_accelerations_with_covariance_stamped_msg_);
if(robotLinearAccelerationStampedPub.getNumSubscribers()>0)
robotLinearAccelerationStampedPub.publish(robotLinearAccelerationStampedMsg);
if(robotAngularAccelerationStampedPub.getNumSubscribers()>0)
robotAngularAccelerationStampedPub.publish(robotAngularAccelerationStampedMsg);
// Odometry
if(robot_odometry_out_pub_.getNumSubscribers()>0)
robot_odometry_out_pub_.publish(robot_odometry_out_msg_);
// end
return 0;
}
int RosFreeModelRobotInterface::publishTfPoseRobotWrtWorld(const TimeStamp& time_stamp, const std::shared_ptr<GlobalParametersCore>& world_core, const std::shared_ptr<RobotStateCore>& robot_state_core)
{
std::shared_ptr<FreeModelRobotStateCore> TheRobotStateCore=std::dynamic_pointer_cast<FreeModelRobotStateCore>(robot_state_core);
Eigen::Vector3d robotPosition=TheRobotStateCore->getPositionRobotWrtWorld();
Eigen::Vector4d robotAttitude=TheRobotStateCore->getAttitudeRobotWrtWorld();
tf::Quaternion tf_rot(robotAttitude[1], robotAttitude[2], robotAttitude[3], robotAttitude[0]);
tf::Vector3 tf_tran(robotPosition[0], robotPosition[1], robotPosition[2]);
tf::Transform transform(tf_rot, tf_tran);
tf_transform_broadcaster_->sendTransform(tf::StampedTransform(transform, ros::Time(time_stamp.getSec(), time_stamp.getNSec()),
world_core->getWorldName(), this->getRobotName()));
return 0;
}
int RosFreeModelRobotInterface::readConfig(const pugi::xml_node &robot, std::shared_ptr<FreeModelRobotStateCore>& robot_state_core)
{
/// Imu Sensor Configs
int errorReadConfig=this->FreeModelRobotCore::readConfig(robot, robot_state_core);
if(errorReadConfig)
return errorReadConfig;
/// Ros Configs
// Name
std::string robot_name=robot.child_value("name");
this->setRobotName(robot_name);
/// Finish
// Open
this->open();
// End
return 0;
}
| 36.650558 | 230 | 0.750127 | Ahrovan |
68278f6de4cfe566b0345654a6af702a3c9b553e | 5,054 | cpp | C++ | src/mame/drivers/sanremmg.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 26 | 2015-03-31T06:25:51.000Z | 2021-12-14T09:29:04.000Z | src/mame/drivers/sanremmg.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | null | null | null | src/mame/drivers/sanremmg.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 10 | 2015-03-27T05:45:51.000Z | 2022-02-04T06:57:36.000Z | // license:BSD-3-Clause
// copyright-holders:David Haywood
/* San Remo / Elsy games
presumably gambling games, maybe missing a sub-board?
Devices
1x unknown quad SMT chip etched "ELSY" main
1x M30624FGAFP 16-bit Single-Chip Microcomputer - main (internal ROM not dumped)
1x TDA2003 Audio Amplifier - sound
1x oscillator 40.000
1x oscillator R100YXA62
ROMs
2x HY29LV160BT or equivalent
RAMs
2x HY628100BLG_70-70W or equivalent
Others
1x 28x2 JAMMA edge connector
1x 50 pins flat cable connector
1x 4 pins black connector
1x RS232 connectors
1x 8 DIP switches bank
1x battery 3.6V
1x battery 5.5V
M30624FG (M16C/62A family) needs CPU core and dumping of internal ROM
*/
#include "emu.h"
#include "cpu/arm7/arm7.h"
#include "cpu/arm7/arm7core.h"
#include "emupal.h"
#include "screen.h"
class sanremmg_state : public driver_device
{
public:
sanremmg_state(const machine_config &mconfig, device_type type, const char *tag)
: driver_device(mconfig, type, tag)
, m_maincpu(*this, "maincpu")
{ }
void sanremmg(machine_config &config);
protected:
virtual void video_start() override;
private:
required_device<cpu_device> m_maincpu;
uint32_t screen_update_sanremmg(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect);
void sanremmg_map(address_map &map);
};
void sanremmg_state::video_start()
{
}
uint32_t sanremmg_state::screen_update_sanremmg(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect)
{
return 0;
}
void sanremmg_state::sanremmg_map(address_map &map)
{
map(0x00000000, 0x00003fff).rom();
}
static INPUT_PORTS_START( sanremmg )
INPUT_PORTS_END
void sanremmg_state::sanremmg(machine_config &config)
{
/* basic machine hardware */
ARM7(config, m_maincpu, 50000000); // wrong, this is an M30624FG (M16C/62A family) with 256K internal ROM, no CPU core available
m_maincpu->set_addrmap(AS_PROGRAM, &sanremmg_state::sanremmg_map);
screen_device &screen(SCREEN(config, "screen", SCREEN_TYPE_RASTER));
screen.set_refresh_hz(60);
screen.set_vblank_time(ATTOSECONDS_IN_USEC(0));
screen.set_size(64*8, 32*8);
screen.set_visarea(8*8, 48*8-1, 2*8, 30*8-1);
screen.set_screen_update(FUNC(sanremmg_state::screen_update_sanremmg));
screen.set_palette("palette");
PALETTE(config, "palette").set_format(palette_device::xRGB_555, 0x200);
}
/*
PCB is marked: "ELSY CE" and "2-028B" and "San Remo Games - Via Val D'OLIVI 295 - 18038 SANREMO (IM)" on component side
*/
ROM_START( sanremmg )
ROM_REGION( 0x4000, "maincpu", 0 )
ROM_LOAD( "sanremmg_m30624fg.mcu", 0x00000, 0x4000, NO_DUMP )
ROM_REGION(0x400000, "data", 0 ) // start of 1.bin has 'Tue Sep 03 11:37:03' Not sure if 03 is year or day, start of string is erased with boot vector?
ROM_LOAD( "1.bin", 0x000000, 0x200000, CRC(67fa5e76) SHA1(92beb90e1b370763966017d47cb748106014d371) ) // HY29LV160BT
ROM_LOAD( "2.bin", 0x200000, 0x200000, CRC(61f69735) SHA1(ff46362ce6fe239089c85e698add1b8090bb39bb) )
// there is space for what looks like a 3rd rom
ROM_END
/*
PCB is marked: "ELSY CE" and "OM1 2-030B" on component side
PCB is marked: "23:04E" and "N2557 TE" on solder side
PCB is labeled: "ELECTROSYSTEM ELSY" and "TEST OK 26" and "F03E04 Ver. 2.2" on component side
*/
ROM_START( elsypokr )
ROM_REGION( 0x4000, "maincpu", 0 )
ROM_LOAD( "elsypokr_m30624fg.mcu", 0x00000, 0x4000, NO_DUMP )
ROM_REGION(0x400000, "data", 0 ) // start of first ROM has 'Mon Apr 05 10:25:38'. Not sure if 05 is year or day, start of string is erased with boot vector?
ROM_LOAD( "mx29lv160bb.1.bin", 0x000000, 0x200000, CRC(da620fa6) SHA1(f2eea0146f6ddcaa4049f6fe7797d755faeace88) ) // MX29LV160BBTC-70
ROM_LOAD( "mx29lv160bb.2.bin", 0x200000, 0x200000, CRC(7a0c3e38) SHA1(dd98d6f56272bf3cc0ed1a14234a8c6e0bc4dd37) )
// there is space for what looks like a 3rd rom
ROM_END
/*
PCB is marked: "ELSY CE" and "2-0291" on component side
PCB is labelled: "Fruit Diamont", "3", "G09004 Ver.1.6" and "TEST OK 02/46" on component side
*/
ROM_START( elsygame )
ROM_REGION( 0x4000, "maincpu", 0 )
ROM_LOAD( "elsygame_m30624fg.mcu", 0x00000, 0x4000, NO_DUMP )
ROM_REGION(0x400000, "data", 0 ) // start of first ROM has 'Thu Nov 07 12:12:25'. Not sure if 07 is year or day, start of string is erased with boot vector?
ROM_LOAD( "mx29lv160bb.1.bin", 0x000000, 0x200000, CRC(cef067b2) SHA1(16fb83d6053532872db89259b64761f8be02de71) ) // MX29LV160BBTC-70
ROM_LOAD( "mx29lv160bb.2.bin", 0x200000, 0x200000, CRC(9b0cb755) SHA1(e66bac00c219d345cb6a9478e23bee2a2e79398b) )
// there is space for what looks like a 3rd rom
ROM_END
GAME( 2003, sanremmg, 0, sanremmg, sanremmg, sanremmg_state, empty_init, ROT0, "San Remo Games", "unknown San Remo / Elsy Multigame", MACHINE_IS_SKELETON )
GAME( 200?, elsypokr, 0, sanremmg, sanremmg, sanremmg_state, empty_init, ROT0, "Electro System (Elsy)", "unknown Elsy poker", MACHINE_IS_SKELETON )
GAME( 2002, elsygame, 0, sanremmg, sanremmg, sanremmg_state, empty_init, ROT0, "Electro System (Elsy)", "unknown Elsy game", MACHINE_IS_SKELETON ) // Fruit Diamont (sic)?
| 34.855172 | 179 | 0.750693 | Robbbert |
6827daa819555eef6698af9548abe30e355a3392 | 3,953 | cpp | C++ | src/160_intersection_of_two_linked_lists.cpp | llife09/leetcode | f5bd6bc7819628b9921441d8362f62123ab881b7 | [
"MIT"
] | 1 | 2019-09-01T22:54:39.000Z | 2019-09-01T22:54:39.000Z | src/160_intersection_of_two_linked_lists.cpp | llife09/leetcode | f5bd6bc7819628b9921441d8362f62123ab881b7 | [
"MIT"
] | 6 | 2019-07-19T07:16:42.000Z | 2019-07-26T08:21:31.000Z | src/160_intersection_of_two_linked_lists.cpp | llife09/leetcode | f5bd6bc7819628b9921441d8362f62123ab881b7 | [
"MIT"
] | null | null | null |
/*
Intersection of Two Linked Lists
URL: https://leetcode.com/problems/intersection-of-two-linked-lists
Tags: ['linked-list']
___
Write a program to find the node at which the intersection of two singly
linked lists begins.
For example, the following two linked lists:
[](https://assets.leetcode.com/uploads/2018/12/13/160_statement.png)
begin to intersect at node c1.
Example 1:
[](https://assets.leetcode.com/uploads/2018/12/13/160_example_1.png)
Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA =
2, skipB = 3 Output: Reference of the node with value = 8 Input Explanation: The
intersected node 's value is 8 (note that this must not be 0 if the two lists
intersect). From the head of A, it reads as [4,1,8,4,5]. From the head of B, it
reads as [5,0,1,8,4,5]. There are 2 nodes before the intersected node in A;
There are 3 nodes before the intersected node in B.
Example 2:
[](https://assets.leetcode.com/uploads/2018/12/13/160_example_2.png)
Input: intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3,
skipB = 1 Output: Reference of the node with value = 2 Input Explanation: The
intersected node's value is 2 (note that this must not be 0 if the two lists
intersect). From the head of A, it reads as [0,9,1,2,4]. From the head of B, it
reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are
1 node before the intersected node in B.
Example 3:
[](https://assets.leetcode.com/uploads/2018/12/13/160_example_3.png)
Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB =
2 Output: null Input Explanation: From the head of A, it reads as [2,6,4]. From
the head of B, it reads as [1,5]. Since the two lists do not intersect,
intersectVal must be 0, while skipA and skipB can be arbitrary values.
Explanation: The two lists do not intersect, so return null.
Notes:
* If the two linked lists have no intersection at all, return `null`.
* The linked lists must retain their original structure after the function
returns.
* You may assume there are no cycles anywhere in the entire linked structure.
* Your code should preferably run in O(n) time and use only O(1) memory.
*/
#include "test.h"
using namespace leetcode;
namespace intersection_of_two_linked_lists {
/*
当 A 和 B 相遇时, 刚好都走完了所有的节点.
*/
inline namespace v1 {
class Solution {
public:
ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) {
if (!headA || !headB) {
return nullptr;
}
auto i = headA, j = headB;
bool aJumped = false, bJumped = false;
while (i != j) {
if (i->next) {
i = i->next;
} else {
if (aJumped) {
return nullptr;
}
i = headB;
aJumped = true;
}
if (j->next) {
j = j->next;
} else {
if (bJumped) {
return nullptr;
}
j = headA;
bJumped = true;
}
}
return i;
}
};
} // namespace v1
TEST_CASE("Intersection of Two Linked Lists") {
TEST_SOLUTION(getIntersectionNode, v1) {
ListNode a1(0);
ListNode a2(0);
ListNode a3(0);
ListNode a4(0);
ListNode a5(0);
a1.next = &a2;
a2.next = &a3;
a3.next = &a4;
a4.next = &a5;
ListNode b1(0);
ListNode b2(0);
b1.next = &b2;
b2.next = &a4;
CHECK(getIntersectionNode(&a1, &b1) == &a4);
};
}
} // namespace intersection_of_two_linked_lists
| 28.235714 | 137 | 0.620288 | llife09 |
68344879905a2fd5f125c66422f3d191d8429164 | 2,966 | cc | C++ | tests/test_ipsec.cc | ANLAB-KAIST/NBA | a093a72af32ccdc041792a01ae65a699294470cd | [
"MIT"
] | 61 | 2015-03-25T04:49:09.000Z | 2020-11-24T08:36:19.000Z | tests/test_ipsec.cc | ANLAB-KAIST/NBA | a093a72af32ccdc041792a01ae65a699294470cd | [
"MIT"
] | 32 | 2015-04-29T08:20:39.000Z | 2017-02-09T22:49:37.000Z | tests/test_ipsec.cc | ANLAB-KAIST/NBA | a093a72af32ccdc041792a01ae65a699294470cd | [
"MIT"
] | 11 | 2015-07-24T22:48:05.000Z | 2020-09-10T11:48:47.000Z | #include <cstdint>
#include <cstdlib>
#include <cstdio>
#include <unordered_map>
#ifdef USE_CUDA
#include <cuda_runtime.h>
#endif
#include <nba/framework/datablock.hh>
#include <nba/framework/datablock_shared.hh>
#include <nba/element/annotation.hh>
#include <nba/element/packet.hh>
#include <nba/element/packetbatch.hh>
#include <nba/framework/test_utils.hh>
#include <gtest/gtest.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <openssl/evp.h>
#include <openssl/err.h>
#include <openssl/aes.h>
#include <openssl/sha.h>
#include <rte_mbuf.h>
#include "../elements/ipsec/util_esp.hh"
#include "../elements/ipsec/util_ipsec_key.hh"
#include "../elements/ipsec/util_sa_entry.hh"
#ifdef USE_CUDA
#include "../elements/ipsec/IPsecAES_kernel.hh"
#include "../elements/ipsec/IPsecAuthHMACSHA1_kernel.hh"
#endif
#include "../elements/ipsec/IPsecDatablocks.hh"
/*
#require <lib/datablock.o>
#require <lib/test_utils.o>
#require "../elements/ipsec/IPsecDatablocks.o"
*/
#ifdef USE_CUDA
/*
#require "../elements/ipsec/IPsecAES_kernel.o"
#require "../elements/ipsec/IPsecAuthHMACSHA1_kernel.o"
*/
#endif
using namespace std;
using namespace nba;
#ifdef USE_CUDA
static int getNumCUDADevices() {
int count;
cudaGetDeviceCount(&count);
return count;
}
class IPsecAESCUDAMatchTest : public ::testing::TestWithParam<int> {
protected:
virtual void SetUp() {
cudaSetDevice(GetParam());
struct ipaddr_pair pair;
struct aes_sa_entry *entry;
unsigned char fake_iv[AES_BLOCK_SIZE] = {0};
aes_sa_entry_array = (struct aes_sa_entry *) malloc(sizeof(struct aes_sa_entry) * num_tunnels);
for (int i = 0; i < num_tunnels; i++) {
pair.src_addr = 0x0a000001u;
pair.dest_addr = 0x0a000000u | (i + 1);
auto result = aes_sa_table.insert(make_pair<ipaddr_pair&, int&>(pair, i));
assert(result.second == true);
entry = &aes_sa_entry_array[i];
entry->entry_idx = i;
rte_memcpy(entry->aes_key, "1234123412341234", AES_BLOCK_SIZE);
#ifdef USE_OPENSSL_EVP
EVP_CIPHER_CTX_init(&entry->evpctx);
if (EVP_EncryptInit(&entry->evpctx, EVP_aes_128_ctr(), entry->aes_key, fake_iv) != 1)
fprintf(stderr, "IPsecAES: EVP_EncryptInit() - %s\n", ERR_error_string(ERR_get_error(), NULL));
#endif
AES_set_encrypt_key((uint8_t *) entry->aes_key, 128, &entry->aes_key_t);
}
}
virtual void TearDown() {
free(aes_sa_entry_array);
cudaDeviceReset();
}
const long num_tunnels = 1024;
struct aes_sa_entry *aes_sa_entry_array;
unordered_map<struct ipaddr_pair, int> aes_sa_table;
};
TEST_P(IPsecAESCUDAMatchTest, SingleBatchWithDatablock) {
}
INSTANTIATE_TEST_CASE_P(PerDeviceIPsecAESCUDAMatchTests, IPsecAESCUDAMatchTest,
::testing::Values(0, getNumCUDADevices() - 1));
#endif
// vim: ts=8 sts=4 sw=4 et
| 29.66 | 111 | 0.683749 | ANLAB-KAIST |
683471193b0181139b491d4c60980f08955bbe39 | 11,256 | cpp | C++ | Sankore-3.1/src/domain/UBGraphicsMediaItem.cpp | eaglezzb/rsdc | cce881f6542ff206bf286cf798c8ec8da3b51d50 | [
"MIT"
] | null | null | null | Sankore-3.1/src/domain/UBGraphicsMediaItem.cpp | eaglezzb/rsdc | cce881f6542ff206bf286cf798c8ec8da3b51d50 | [
"MIT"
] | null | null | null | Sankore-3.1/src/domain/UBGraphicsMediaItem.cpp | eaglezzb/rsdc | cce881f6542ff206bf286cf798c8ec8da3b51d50 | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2010-2013 Groupement d'Intérêt Public pour l'Education Numérique en Afrique (GIP ENA)
*
* This file is part of Open-Sankoré.
*
* Open-Sankoré 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, version 3 of the License,
* with a specific linking exception for the OpenSSL project's
* "OpenSSL" library (or with modified versions of it that use the
* same license as the "OpenSSL" library).
*
* Open-Sankoré 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 Open-Sankoré. If not, see <http://www.gnu.org/licenses/>.
*/
#include "UBGraphicsGroupContainerItem.h"
#include "UBGraphicsMediaItem.h"
#include "UBGraphicsMediaItemDelegate.h"
#include "UBGraphicsScene.h"
#include "UBGraphicsDelegateFrame.h"
#include "document/UBDocumentProxy.h"
#include "core/UBApplication.h"
#include "board/UBBoardController.h"
#include "core/memcheck.h"
UBAudioPresentationWidget::UBAudioPresentationWidget(QWidget *parent)
: QWidget(parent)
, mBorderSize(10)
{
}
void UBAudioPresentationWidget::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
painter.fillRect(rect(), QBrush(Qt::white));
QPen borderPen;
borderPen.setWidth(2);
borderPen.setColor(QColor(Qt::black));
painter.setPen(borderPen);
painter.drawRect(0,0, width(), height());
if (QString() != mTitle)
{
painter.setPen(QPen(Qt::black));
QRect titleRect = rect();
titleRect.setX(mBorderSize);
titleRect.setY(2);
titleRect.setHeight(15);
painter.drawText(titleRect, mTitle);
}
QWidget::paintEvent(event);
}
bool UBGraphicsMediaItem::sIsMutedByDefault = false;
UBGraphicsMediaItem::UBGraphicsMediaItem(const QUrl& pMediaFileUrl, QGraphicsItem *parent)
: UBAbstractGraphicsProxyWidget(parent)
, mVideoWidget(NULL)
, mAudioWidget(NULL)
, mMuted(sIsMutedByDefault)
, mMutedByUserAction(sIsMutedByDefault)
, mMediaFileUrl(pMediaFileUrl)
, mLinkedImage(NULL)
, mInitialPos(0)
{
update();
mMediaObject = new Phonon::MediaObject(this);
QString mediaPath = pMediaFileUrl.toString();
if ("" == mediaPath)
mediaPath = pMediaFileUrl.toLocalFile();
if (mediaPath.toLower().contains("videos"))
{
mMediaType = mediaType_Video;
mAudioOutput = new Phonon::AudioOutput(Phonon::VideoCategory, this);
mMediaObject->setTickInterval(50);
mVideoWidget = new Phonon::VideoWidget(); // owned and destructed by the scene ...
Phonon::createPath(mMediaObject, mVideoWidget);
if(mVideoWidget->sizeHint() == QSize(1,1)){
mVideoWidget->resize(320,240);
}
mVideoWidget->setMinimumSize(140,26);
haveLinkedImage = true;
}
else
if (mediaPath.toLower().contains("audios"))
{
mMediaType = mediaType_Audio;
mAudioOutput = new Phonon::AudioOutput(Phonon::MusicCategory, this);
mMediaObject->setTickInterval(1000);
mAudioWidget = new UBAudioPresentationWidget();
int borderSize = 0;
UBAudioPresentationWidget* pAudioWidget = dynamic_cast<UBAudioPresentationWidget*>(mAudioWidget);
if (pAudioWidget)
{
borderSize = pAudioWidget->borderSize();
}
mAudioWidget->resize(320,26+2*borderSize); //3*border size with enabled title
mAudioWidget->setMinimumSize(150,26+borderSize);
haveLinkedImage = false;
}
Phonon::createPath(mMediaObject, mAudioOutput);
mSource = Phonon::MediaSource(pMediaFileUrl);
mMediaObject->setCurrentSource(mSource);
// we should create delegate after media objects because delegate uses his properties at creation.
setDelegate(new UBGraphicsMediaItemDelegate(this, mMediaObject));
// delegate should be created earler because we setWidget calls resize event for graphics proxy widgt.
// resize uses delegate.
if (mediaType_Video == mMediaType)
setWidget(mVideoWidget);
else
setWidget(mAudioWidget);
// media widget should be created and placed on proxy widget here.
Delegate()->init();
if (mediaType_Audio == mMediaType)
Delegate()->frame()->setOperationMode(UBGraphicsDelegateFrame::ResizingHorizontally);
else
Delegate()->frame()->setOperationMode(UBGraphicsDelegateFrame::Resizing);
setData(UBGraphicsItemData::itemLayerType, QVariant(itemLayerType::ObjectItem)); //Necessary to set if we want z value to be assigned correctly
connect(Delegate(), SIGNAL(showOnDisplayChanged(bool)), this, SLOT(showOnDisplayChanged(bool)));
connect(mMediaObject, SIGNAL(hasVideoChanged(bool)), this, SLOT(hasMediaChanged(bool)));
}
UBGraphicsMediaItem::~UBGraphicsMediaItem()
{
if (mMediaObject)
mMediaObject->stop();
}
QVariant UBGraphicsMediaItem::itemChange(GraphicsItemChange change, const QVariant &value)
{
if ((change == QGraphicsItem::ItemEnabledChange)
|| (change == QGraphicsItem::ItemSceneChange)
|| (change == QGraphicsItem::ItemVisibleChange))
{
if (mMediaObject && (!isEnabled() || !isVisible() || !scene()))
{
mMediaObject->pause();
}
}
else if (change == QGraphicsItem::ItemSceneHasChanged)
{
if (!scene())
{
mMediaObject->stop();
}
else
{
QString absoluteMediaFilename;
if(mMediaFileUrl.toLocalFile().startsWith("audios/") || mMediaFileUrl.toLocalFile().startsWith("videos/")){
absoluteMediaFilename = scene()->document()->persistencePath() + "/" + mMediaFileUrl.toLocalFile();
}
else{
absoluteMediaFilename = mMediaFileUrl.toLocalFile();
}
if (absoluteMediaFilename.length() > 0)
mMediaObject->setCurrentSource(Phonon::MediaSource(absoluteMediaFilename));
}
}
return UBAbstractGraphicsProxyWidget::itemChange(change, value);
}
void UBGraphicsMediaItem::setSourceUrl(const QUrl &pSourceUrl)
{
UBAudioPresentationWidget* pAudioWidget = dynamic_cast<UBAudioPresentationWidget*>(mAudioWidget);
if (pAudioWidget)
{
// pAudioWidget->setTitle(UBFileSystemUtils::lastPathComponent(pSourceUrl.toString()));
}
UBItem::setSourceUrl(pSourceUrl);
}
void UBGraphicsMediaItem::clearSource()
{
QString path = mediaFileUrl().toLocalFile();
//if path is absolute clean duplicated path string
if (!path.contains(UBApplication::boardController->selectedDocument()->persistencePath()))
path = UBApplication::boardController->selectedDocument()->persistencePath() + "/" + path;
if (!UBFileSystemUtils::deleteFile(path))
qDebug() << "cannot delete file: " << path;
}
void UBGraphicsMediaItem::toggleMute()
{
mMuted = !mMuted;
setMute(mMuted);
}
void UBGraphicsMediaItem::setMute(bool bMute)
{
mMuted = bMute;
mAudioOutput->setMuted(mMuted);
mMutedByUserAction = mMuted;
sIsMutedByDefault = mMuted;
}
void UBGraphicsMediaItem::hasMediaChanged(bool hasMedia)
{
if(hasMedia && mMediaObject->isSeekable())
{
Q_UNUSED(hasMedia);
mMediaObject->seek(mInitialPos);
UBGraphicsMediaItemDelegate *med = dynamic_cast<UBGraphicsMediaItemDelegate *>(Delegate());
if (med)
med->updateTicker(initialPos());
}
}
UBGraphicsScene* UBGraphicsMediaItem::scene()
{
return qobject_cast<UBGraphicsScene*>(QGraphicsItem::scene());
}
void UBGraphicsMediaItem::activeSceneChanged()
{
if (UBApplication::boardController->activeScene() != scene())
{
mMediaObject->pause();
}
}
void UBGraphicsMediaItem::showOnDisplayChanged(bool shown)
{
if (!shown)
{
mMuted = true;
mAudioOutput->setMuted(mMuted);
}
else if (!mMutedByUserAction)
{
mMuted = false;
mAudioOutput->setMuted(mMuted);
}
}
UBItem* UBGraphicsMediaItem::deepCopy() const
{
QUrl url = this->mediaFileUrl();
UBGraphicsMediaItem *copy = new UBGraphicsMediaItem(url, parentItem());
copy->setUuid(QUuid::createUuid()); // this is OK for now as long as Widgets are imutable
copyItemParameters(copy);
return copy;
}
void UBGraphicsMediaItem::copyItemParameters(UBItem *copy) const
{
UBGraphicsMediaItem *cp = dynamic_cast<UBGraphicsMediaItem*>(copy);
if (cp)
{
cp->setPos(this->pos());
cp->setTransform(this->transform());
cp->setFlag(QGraphicsItem::ItemIsMovable, true);
cp->setFlag(QGraphicsItem::ItemIsSelectable, true);
cp->setData(UBGraphicsItemData::ItemLayerType, this->data(UBGraphicsItemData::ItemLayerType));
cp->setData(UBGraphicsItemData::ItemLocked, this->data(UBGraphicsItemData::ItemLocked));
cp->setSourceUrl(this->sourceUrl());
cp->resize(this->size());
connect(UBApplication::boardController, SIGNAL(activeSceneChanged()), cp, SLOT(activeSceneChanged()));
// TODO UB 4.7 complete all members
}
}
void UBGraphicsMediaItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
if (Delegate())
{
Delegate()->mousePressEvent(event);
if (parentItem() && UBGraphicsGroupContainerItem::Type == parentItem()->type())
{
UBGraphicsGroupContainerItem *group = qgraphicsitem_cast<UBGraphicsGroupContainerItem*>(parentItem());
if (group)
{
QGraphicsItem *curItem = group->getCurrentItem();
if (curItem && this != curItem)
{
group->deselectCurrentItem();
}
group->setCurrentItem(this);
this->setSelected(true);
Delegate()->positionHandles();
}
}
}
if (parentItem() && parentItem()->type() == UBGraphicsGroupContainerItem::Type)
{
mShouldMove = false;
if (!Delegate()->mousePressEvent(event))
{
event->accept();
}
}
else
{
mShouldMove = (event->buttons() & Qt::LeftButton);
mMousePressPos = event->scenePos();
mMouseMovePos = mMousePressPos;
event->accept();
setSelected(true);
}
}
void UBGraphicsMediaItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
if(mShouldMove && (event->buttons() & Qt::LeftButton))
{
QPointF offset = event->scenePos() - mMousePressPos;
if (offset.toPoint().manhattanLength() > QApplication::startDragDistance())
{
QPointF mouseMovePos = mapFromScene(mMouseMovePos);
QPointF eventPos = mapFromScene( event->scenePos());
QPointF translation = eventPos - mouseMovePos;
translate(translation.x(), translation.y());
}
mMouseMovePos = event->scenePos();
}
event->accept();
}
| 30.016 | 147 | 0.661514 | eaglezzb |
683758dcbc7168f1c6a4b23ddf2f7e66fd0438f9 | 2,653 | cpp | C++ | orbsvcs/Event/EC_Bitmask_Filter.cpp | binary42/OCI | 08191bfe4899f535ff99637d019734ed044f479d | [
"MIT"
] | null | null | null | orbsvcs/Event/EC_Bitmask_Filter.cpp | binary42/OCI | 08191bfe4899f535ff99637d019734ed044f479d | [
"MIT"
] | null | null | null | orbsvcs/Event/EC_Bitmask_Filter.cpp | binary42/OCI | 08191bfe4899f535ff99637d019734ed044f479d | [
"MIT"
] | null | null | null | // $Id: EC_Bitmask_Filter.cpp 1861 2011-08-31 16:18:08Z mesnierp $
#include "orbsvcs/Event/EC_Bitmask_Filter.h"
TAO_BEGIN_VERSIONED_NAMESPACE_DECL
TAO_EC_Bitmask_Filter::TAO_EC_Bitmask_Filter (CORBA::ULong source_mask,
CORBA::ULong type_mask,
TAO_EC_Filter* child)
: source_mask_ (source_mask),
type_mask_ (type_mask),
child_ (child)
{
this->adopt_child (this->child_);
}
TAO_EC_Bitmask_Filter::~TAO_EC_Bitmask_Filter (void)
{
delete this->child_;
}
TAO_EC_Filter::ChildrenIterator
TAO_EC_Bitmask_Filter::begin (void) const
{
return const_cast<TAO_EC_Filter**> (&this->child_);
}
TAO_EC_Filter::ChildrenIterator
TAO_EC_Bitmask_Filter::end (void) const
{
return const_cast<TAO_EC_Filter**> (&this->child_) + 1;
}
int
TAO_EC_Bitmask_Filter::size (void) const
{
return 1;
}
int
TAO_EC_Bitmask_Filter::filter (const RtecEventComm::EventSet& event,
TAO_EC_QOS_Info& qos_info)
{
if (event.length () != 1)
return 0;
if ((event[0].header.type & this->type_mask_) == 0
|| (event[0].header.source & this->source_mask_) == 0)
return 0;
return this->child_->filter (event, qos_info);
}
int
TAO_EC_Bitmask_Filter::filter_nocopy (RtecEventComm::EventSet& event,
TAO_EC_QOS_Info& qos_info)
{
if (event.length () != 1)
return 0;
if ((event[0].header.type & this->type_mask_) == 0
|| (event[0].header.source & this->source_mask_) == 0)
return 0;
return this->child_->filter_nocopy (event, qos_info);
}
void
TAO_EC_Bitmask_Filter::push (const RtecEventComm::EventSet &event,
TAO_EC_QOS_Info &qos_info)
{
if (this->parent () != 0)
this->parent ()->push (event, qos_info);
}
void
TAO_EC_Bitmask_Filter::push_nocopy (RtecEventComm::EventSet &event,
TAO_EC_QOS_Info &qos_info)
{
if (this->parent () != 0)
this->parent ()->push_nocopy (event, qos_info);
}
void
TAO_EC_Bitmask_Filter::clear (void)
{
this->child_->clear ();
}
CORBA::ULong
TAO_EC_Bitmask_Filter::max_event_size (void) const
{
return this->child_->max_event_size ();
}
int
TAO_EC_Bitmask_Filter::can_match (
const RtecEventComm::EventHeader& header) const
{
if ((header.type & this->type_mask_) == 0
|| (header.source & this->source_mask_) == 0)
return 0;
return this->child_->can_match (header);
}
int
TAO_EC_Bitmask_Filter::add_dependencies (
const RtecEventComm::EventHeader&,
const TAO_EC_QOS_Info &)
{
return 0;
}
TAO_END_VERSIONED_NAMESPACE_DECL
| 22.483051 | 71 | 0.652469 | binary42 |
683787adcf74d0720ef1397164780d2759656daa | 879 | cpp | C++ | Source/Flopnite/Private/FNAttributeSet.cpp | BEASTSM96/flopnite-ue4 | 76193544a6b7fe6b969864e74409b6b5a43f3d7a | [
"MIT"
] | null | null | null | Source/Flopnite/Private/FNAttributeSet.cpp | BEASTSM96/flopnite-ue4 | 76193544a6b7fe6b969864e74409b6b5a43f3d7a | [
"MIT"
] | null | null | null | Source/Flopnite/Private/FNAttributeSet.cpp | BEASTSM96/flopnite-ue4 | 76193544a6b7fe6b969864e74409b6b5a43f3d7a | [
"MIT"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "FNAttributeSet.h"
#include "Net/UnrealNetwork.h"
UFNAttributeSet::UFNAttributeSet() {
}
void UFNAttributeSet::PreAttributeChange(const FGameplayAttribute& Attribute, float& NewValue) {
Super::PreAttributeChange(Attribute, NewValue);
}
void UFNAttributeSet::PostGameplayEffectExecute(const FGameplayEffectModCallbackData& Data) {
Super::PostGameplayEffectExecute(Data);
}
void UFNAttributeSet::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const {
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
DOREPLIFETIME_CONDITION_NOTIFY(UFNAttributeSet, MoveSpeed, COND_None, REPNOTIFY_Always);
}
void UFNAttributeSet::OnRep_MoveSpeed(const FGameplayAttributeData& OldMoveSpeed)
{
GAMEPLAYATTRIBUTE_REPNOTIFY( UFNAttributeSet, MoveSpeed, OldMoveSpeed );
}
| 30.310345 | 101 | 0.829352 | BEASTSM96 |
683a085249930e046385b141a55e5d2152dd78b6 | 1,351 | cpp | C++ | PBitmapLibrary/Sample.cpp | bear1704/WindowsProgramming_Portfolio | 83f1d763c73d08b82291aa894ef246558fdf0198 | [
"Apache-2.0"
] | null | null | null | PBitmapLibrary/Sample.cpp | bear1704/WindowsProgramming_Portfolio | 83f1d763c73d08b82291aa894ef246558fdf0198 | [
"Apache-2.0"
] | null | null | null | PBitmapLibrary/Sample.cpp | bear1704/WindowsProgramming_Portfolio | 83f1d763c73d08b82291aa894ef246558fdf0198 | [
"Apache-2.0"
] | null | null | null | #include "Sample.h"
Sample::Sample()
{
}
Sample::~Sample()
{
}
bool Sample::Init()
{
object_background_bitmap_.Init();
object_background_bitmap_.Load(L"../../data/bitmap/Loading800x600.bmp");
PRectObjectStat stat;
stat.position = pPoint(0, 0);
RECT rect = { 0, 0, rectangle_client.right, rectangle_client.bottom };
stat.rect = rect;
object_background_bitmap_.Set(stat);
hero_.Init();
hero_.Load(L"../../data/bitmap/bitmap1.bmp");
PRectObjectStat stat1;
stat1.position = pPoint(100, 100);
RECT rect1 = { 90, 1 , 40, 60 };
stat1.rect = rect1;
stat1.moveSpeed = 100.0f;
hero_.Set(stat1);
character_npc_.Init();
character_npc_.Load(L"../../data/bitmap/bitmap1.bmp");
PRectObjectStat stat2;
stat2.position = pPoint(200, 200);
RECT rect2 = { 46, 62, 67, 79 };
stat2.rect = rect2;
character_npc_.Set(stat2);
//PSoundMgr::GetInstance().Play(PSoundMgr::GetInstance().Load(L"../../data/sound/onlyLove.mp3"));
return true;
}
bool Sample::Frame()
{
object_background_bitmap_.Frame();
hero_.Frame();
character_npc_.Frame();
return true;
}
bool Sample::Render()
{
object_background_bitmap_.Render();
hero_.Render();
character_npc_.Render();
return true;
}
bool Sample::Release()
{
object_background_bitmap_.Release();
hero_.Release();
character_npc_.Release();
return true;
}
PCORE_RUN(L"abcd", 0, 0, 800, 600);
| 18.506849 | 98 | 0.695781 | bear1704 |
683a4c91e23d361308f426615c06b1df1389926a | 13,848 | cpp | C++ | Engine/src/core/Quaternion.cpp | katoun/kg_engine | fdcc6ec01b191d07cedf7a8d6c274166e25401a8 | [
"Unlicense"
] | 2 | 2015-04-21T05:36:12.000Z | 2017-04-16T19:31:26.000Z | Engine/src/core/Quaternion.cpp | katoun/kg_engine | fdcc6ec01b191d07cedf7a8d6c274166e25401a8 | [
"Unlicense"
] | null | null | null | Engine/src/core/Quaternion.cpp | katoun/kg_engine | fdcc6ec01b191d07cedf7a8d6c274166e25401a8 | [
"Unlicense"
] | null | null | null | /*
-----------------------------------------------------------------------------
KG game engine (http://katoun.github.com/kg_engine) is made available under the MIT License.
Copyright (c) 2006-2013 Catalin Alexandru Nastase
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 <core/Quaternion.h>
#include <core/Math.h>
#include <core/Matrix4.h>
#include <core/Vector3d.h>
namespace core
{
quaternion::quaternion(): x(0), y(0), z(0), w(1) {}
quaternion::quaternion(const matrix4& mat)
{
(*this) = mat;
}
quaternion::quaternion(float nx, float ny, float nz)
{
set(nx, ny, nz);
}
quaternion::quaternion(float nx, float ny, float nz, float nw): x(nx), y(ny), z(nz), w(nw) {}
quaternion::quaternion(const quaternion& other): x(other.x), y(other.y), z(other.z), w(other.w) {}
quaternion::quaternion(const vector3d& axis, const float& angle)
{
fromAngleAxis(angle, axis);
}
quaternion quaternion::operator- () const
{
return quaternion(-x, -y, -z, -w);
}
quaternion& quaternion::operator=(const quaternion& other)
{
x = other.x;
y = other.y;
z = other.z;
w = other.w;
return *this;
}
quaternion& quaternion::operator=(const matrix4& m)
{
float diag = m(0, 0) + m(1, 1) + m(2, 2) + 1;
float scale = 0.0f;
if (diag > 0.0f)
{
scale = sqrt(diag) * 2.0f; // get scale from diagonal
// TODO: speed this up
x = (m(2, 1) - m(1, 2)) / scale;
y = (m(0, 2) - m(2, 0)) / scale;
z = (m(1, 0) - m(0, 1)) / scale;
w = 0.25f * scale;
}
else
{
if (m(0, 0) > m(1, 1) && m(0, 0) > m(2, 2))
{
// 1st element of diag is greatest value
// find scale according to 1st element, and double it
scale = sqrt(1.0f + m(0, 0) - m(1, 1) - m(2, 2)) * 2.0f;
// TODO: speed this up
x = 0.25f * scale;
y = (m(0, 1) + m(1, 0)) / scale;
z = (m(2, 0) + m(0, 2)) / scale;
w = (m(2, 1) - m(1, 2)) / scale;
}
else if (m(1, 1) > m(2, 2))
{
// 2nd element of diag is greatest value
// find scale according to 2nd element, and double it
scale = sqrt(1.0f + m(1, 1) - m(0, 0) - m(2, 2)) * 2.0f;
// TODO: speed this up
x = (m(0, 1) + m(1, 0)) / scale;
y = 0.25f * scale;
z = (m(1, 2) + m(2, 1)) / scale;
w = (m(0, 2) - m(2, 0)) / scale;
}
else
{
// 3rd element of diag is greatest value
// find scale according to 3rd element, and double it
scale = sqrt(1.0f + m(2, 2) - m(0, 0) - m(1, 1)) * 2.0f;
// TODO: speed this up
x = (m(0, 2) + m(2, 0)) / scale;
y = (m(1, 2) + m(2, 1)) / scale;
z = 0.25f * scale;
w = (m(1, 0) - m(0, 1)) / scale;
}
}
normalize();
return *this;
}
quaternion quaternion::operator+(const quaternion& b) const
{
return quaternion(x + b.x, y + b.y, z + b.z, w + b.w);
}
quaternion quaternion::operator-(const quaternion& b) const
{
return quaternion(x -b.x, y - b.y, z - b.z, w - b.w);
}
quaternion quaternion::operator*(const quaternion& other) const
{
quaternion tmp;
tmp.x = (w * other.x) + (x * other.w) + (y * other.z) - (z * other.y);
tmp.y = (w * other.y) + (y * other.w) + (z * other.x) - (x * other.z);
tmp.z = (w * other.z) + (z * other.w) + (x * other.y) - (y * other.x);
tmp.w = (w * other.w) - (x * other.x) - (y * other.y) - (z * other.z);
return tmp;
}
vector3d quaternion::operator*(const vector3d& v) const
{
// nVidia SDK implementation
vector3d uv, uuv;
vector3d qvec(x, y, z);
uv = qvec.crossProduct(v);
uuv = qvec.crossProduct(uv);
uv *= (2.0f * w);
uuv *= 2.0f;
return v + uv + uuv;
}
quaternion quaternion::operator*(float s) const
{
return quaternion(s*x, s*y, s*z, s*w);
}
quaternion& quaternion::operator*=(float s)
{
x *= s;
y *= s;
z *= s;
w *= s;
return *this;
}
quaternion& quaternion::operator*=(const quaternion& other)
{
*this = other * (*this);
return *this;
}
bool quaternion::operator==(const quaternion& other) const
{
return ((other.x + EPSILON > x) && (other.x - EPSILON < x) &&
(other.y + EPSILON > y) && (other.y - EPSILON < y) &&
(other.z + EPSILON > z) && (other.z - EPSILON < z) &&
(other.w + EPSILON > w) && (other.w - EPSILON < w));
}
bool quaternion::operator!=(const quaternion& other) const
{
return ((other.x + EPSILON < x) || (other.x - EPSILON > x) ||
(other.y + EPSILON < y) || (other.y - EPSILON > y) ||
(other.z + EPSILON < z) || (other.z - EPSILON > z) ||
(other.w + EPSILON < w) || (other.w - EPSILON > w));
}
void quaternion::set(float x, float y, float z, float w)
{
x = x;
y = y;
z = z;
w = w;
}
void quaternion::set(float nx, float ny, float nz)
{
float angle;
angle = nx * 0.5f;
float sr = (float)sin(angle);
float cr = (float)cos(angle);
angle = ny * 0.5f;
float sp = (float)sin(angle);
float cp = (float)cos(angle);
angle = nz * 0.5f;
float sy = (float)sin(angle);
float cy = (float)cos(angle);
float cpcy = cp * cy;
float spcy = sp * cy;
float cpsy = cp * sy;
float spsy = sp * sy; //quaternion fix by jox
x = sr * cpcy - cr * spsy;
y = cr * spcy + sr * cpsy;
z = cr * cpsy - sr * spcy;
w = cr * cpcy + sr * spsy;
normalize();
}
void quaternion::set(vector3d rot)
{
set(rot.x, rot.y, rot.z);
}
void quaternion::setDegrees(float x, float y, float z)
{
set((float)(x * DEGTORAD), (float)(y * DEGTORAD), (float)(z * DEGTORAD));
}
void quaternion::setDegrees(vector3d rot)
{
set((float)(rot.x * DEGTORAD), (float)(rot.y * DEGTORAD), (float)(rot.z * DEGTORAD));
}
void quaternion::setDegrees(const vector3d& axis, const float& angle)
{
fromAngleAxis((float)(angle * DEGTORAD), axis);
}
void quaternion::invert()
{
float fNorm = x * x + y * y + z * z + w * w;
if (fNorm > 0.0)
{
float fInvNorm = 1.0f / fNorm;
x = -x * fInvNorm;
y = -y * fInvNorm;
z = -z * fInvNorm;
w = w * fInvNorm;
}
else
{
// return an invalid result to flag the error
x = 0.0f;
y = 0.0f;
z = 0.0f;
w = 0.0f;
}
}
void quaternion::unitInvert()
{
x = -x;
y = -y;
z = -z;
}
quaternion quaternion::getInverse() const
{
float fNorm = x * x + y * y + z * z + w * w;
if (fNorm > 0.0)
{
float fInvNorm = 1.0f / fNorm;
return quaternion(-x*fInvNorm, -y*fInvNorm, -z*fInvNorm, w*fInvNorm);
}
else
{
// return an invalid result to flag the error
return quaternion(0.0, 0.0, 0.0, 0.0);
}
}
quaternion quaternion::getUnitInverse() const
{
return quaternion(-x, -y, -z);
}
quaternion& quaternion::normalize()
{
float n = x * x + y * y + z * z + w * w;
if (n == 1)
return *this;
n = 1.0f / sqrt(n);
x *= n;
y *= n;
z *= n;
w *= n;
return *this;
}
float quaternion::dotProduct(const quaternion& q2) const
{
return (x * q2.x) + (y * q2.y) + (z * q2.z) + (w * q2.w);
}
void quaternion::fromAngleAxis(const float& angle, const vector3d& axis)
{
// assert: axis is unit length
//
// The quaternion representing the rotation is
// q = cos(A/2)+sin(A/2)*(x*i+y*j+z*k)
// assert commented out since vector.normalize cant even create 100% normalized f32s
// assert(sqrt(axis.x * axis.x + axis.y * axis.y + axis.z * axis.z) == 1);
float fHalfAngle = 0.5f * angle;
float fSin = (float)sin(fHalfAngle);
w = (float)cos(fHalfAngle);
x = fSin * axis.x;
y = fSin * axis.y;
z = fSin * axis.z;
}
void quaternion::fromDegreeAxis(const float& degree, const vector3d& axis)
{
float fHalfAngle = 0.5f * (degree * DEGTORAD);
float fSin = (float)sin(fHalfAngle);
w = (float)cos(fHalfAngle);
x = fSin * axis.x;
y = fSin * axis.y;
z = fSin * axis.z;
}
void quaternion::fromAxisToAxis(const vector3d& src, const vector3d& dest, const vector3d& fallbackAxis)
{
// Based on Stan Melax's article in Game Programming Gems
// Copy, since cannot modify local
vector3d v0 = src;
vector3d v1 = dest;
v0.normalize();
v1.normalize();
float d = v0.dotProduct(v1);
// If dot == 1, vectors are the same
if (d >= 1.0f)
{
x = IDENTITY.x;
y = IDENTITY.y;
z = IDENTITY.z;
w = IDENTITY.w;
}
if (d < (1e-6f - 1.0f))
{
if (fallbackAxis != vector3d::ORIGIN_3D)
{
// rotate 180 degrees about the fallback axis
fromAngleAxis(PI, fallbackAxis);
}
else
{
// Generate an axis
vector3d axis = vector3d::UNIT_X.crossProduct(src);
if (axis.getLength() == 0) // pick another if colinear
axis = vector3d::UNIT_Y.crossProduct(src);
axis.normalize();
fromAngleAxis(PI, axis);
}
}
else
{
float s = sqrt((1+d)*2);
float invs = 1 / s;
vector3d c = v0.crossProduct(v1);
x = c.x * invs;
y = c.y * invs;
z = c.z * invs;
w = s * 0.5f;
normalize();
}
}
void quaternion::fromRotationMatrix(const matrix4& m)
{
float T = 1 + m(0, 0) + m(1, 1) + m(2, 2);
if (T > 0.00000001f)
{
float S = 0.5f / (float)sqrt(T);
x = (m(2, 1) - m(1, 2)) * S;
y = (m(0, 2) - m(2, 0)) * S;
z = (m(1, 0) - m(0, 1)) * S;
w = 0.25f / S;
}
else if (m(0, 0) > m(1, 1) && m(0, 0) > m(2, 2))
{
float S = 1.0f / (2.0f * (float)sqrt(1.0f + m(0, 0) - m(1, 1) - m(2, 2)));
x = 0.25f / S;
y = (m(1, 0) + m(0, 1)) * S;
z = (m(0, 2) + m(2, 0)) * S;
w = (m(2, 1) - m(1, 2)) * S;
}
else if (m(1, 1) > m(2, 2))
{
float S = 1.0f / (2.0f * (float)sqrt(1.0f - m(0, 0) + m(1, 1) - m(2, 2)));
x = (m(1, 0) + m(0, 1)) * S;
y = 0.25f / S;
z = (m(2, 1) + m(1, 2)) * S;
w = (m(0, 2) - m(2, 0)) * S;
}
else
{
float S = 1.0f / (2.0f * (float)sqrt(1.0f - m(0, 0) - m(1, 1) + m(2, 2)));
x = (m(0, 2) + m(2, 0)) * S;
y = (m(2, 1) + m(1, 2)) * S;
z = 0.25f / S;
w = (m(1, 0) - m(0, 1)) * S;
}
}
matrix4 quaternion::toRotationMatrix() const
{
core::matrix4 m;
m(0, 0) = 1.0f - (2.0f * y * y + 2.0f * z * z);
m(0, 1) = 2.0f * x * y - 2.0f * z * w;
m(0, 2) = 2.0f * x * z + 2.0f * y * w;
m(0, 3) = 0.0f;
m(1, 0) = 2.0f * x * y + 2.0f * z * w;
m(1, 1) = 1.0f - (2.0f * x * x + 2.0f * z * z);
m(1, 2) = 2.0f * z * y - 2.0f * x * w;
m(1, 3) = 0.0f;
m(2, 0) = 2.0f * x * z - 2.0f * y * w;
m(2, 1) = 2.0f * z * y + 2.0f * x * w;
m(2, 2) = 1.0f - (2.0f * x * x + 2.0f * y * y);
m(2, 3) = 0.0f;
m(3, 0) = 0.0f;
m(3, 1) = 0.0f;
m(3, 2) = 0.0f;
m(3, 3) = 1.0f;
return m;
}
vector3d quaternion::toEulerAngles() const
{
/* new version after euclideanspace.com by Matthias Meyer
old version had a problem where the initial quaternion
would return -0 for y value and NaN for rotation of 1.5708
around y-axis when using fromangleaxis() */
vector3d euler;
float testValue = x * y + z * w;
if (testValue > 0.499f) // north pole singularity
{
euler.y = (float)(2.0f * atan2(x, w));
euler.z = HALF_PI;
euler.x = 0.0f;
return euler;
}
if (testValue < -0.499f) // south pole singularity
{
euler.y = (float)(-2.0f * atan2(x, w));
euler.z = -HALF_PI;
euler.x = 0.0f;
return euler;
}
float sqx = x * x;
float sqy = y * y;
float sqz = z * z;
float sqw = w * w;
float unit = sqx + sqy + sqz + sqw;
euler.y = (float)atan2(2.0f * y * w - 2.0f * x * z, sqx - sqy - sqz + sqw);
euler.z = (float)asin(2.0f * testValue / unit);
euler.x = (float)atan2(2.0f * x * w - 2.0f * y * z, -sqx + sqy - sqz + sqw);
return euler;
}
vector3d quaternion::toEulerDegrees() const
{
vector3d eulerRad = toEulerAngles();
eulerRad.x *= RADTODEG;
eulerRad.y *= RADTODEG;
eulerRad.z *= RADTODEG;
return eulerRad;
}
float quaternion::getXDegrees() const
{
float eulerx;
float testValue = x * y + z * w;
if (testValue > 0.499f) // north pole singularity
{
eulerx = 0.0f;
return eulerx;
}
if (testValue < -0.499f) // south pole singularity
{
eulerx = 0.0f;
return eulerx;
}
float sqx = x * x;
float sqy = y * y;
float sqz = z * z;
float sqw = w * w;
//float unit = sqx + sqy + sqz + sqw;
eulerx = atan2(2.0f * x * w - 2.0f * y * z, -sqx + sqy - sqz + sqw);
eulerx *= RADTODEG;
return eulerx;
}
float quaternion::getYDegrees() const
{
float eulery;
float testValue = x * y + z * w;
if (testValue > 0.499f) // north pole singularity
{
eulery = (float)(2.0f * atan2(x, w));;
return eulery;
}
if (testValue < -0.499f) // south pole singularity
{
eulery = (float)(-2.0f * atan2(x, w));
return eulery;
}
float sqx = x * x;
float sqy = y * y;
float sqz = z * z;
float sqw = w * w;
//float unit = sqx + sqy + sqz + sqw;
eulery = (float)atan2(2.0f * y * w - 2.0f * x * z, sqx - sqy - sqz + sqw);
eulery *= RADTODEG;
return eulery;
}
float quaternion::getZDegrees() const
{
float eulerz;
float testValue = x * y + z * w;
if (testValue > 0.499f) // north pole singularity
{
eulerz = HALF_PI;
return eulerz;
}
if (testValue < -0.499f) // south pole singularity
{
eulerz = -HALF_PI;
return eulerz;
}
float sqx = x * x;
float sqy = y * y;
float sqz = z * z;
float sqw = w * w;
float unit = sqx + sqy + sqz + sqw;
eulerz = (float)asin(2.0f * testValue / unit);
eulerz *= RADTODEG;
return eulerz;
}
const quaternion quaternion::ZERO = quaternion(0.0f, 0.0f, 0.0f, 0.0f);
const quaternion quaternion::IDENTITY = quaternion(0.0f, 0.0f, 0.0f, 1.0f);
} // end namespace core
| 22.927152 | 104 | 0.578928 | katoun |
683f14df85f58185b1c55e9c870de4008820903c | 550 | cpp | C++ | Data Structures and Algorithms CPP/10 Linked List 2/04ReverseRec.cpp | shivamaggarwal513/Coding-Ninjas | b445f4caf09730cc0a6cc7d2ab10fda3e9188111 | [
"MIT"
] | null | null | null | Data Structures and Algorithms CPP/10 Linked List 2/04ReverseRec.cpp | shivamaggarwal513/Coding-Ninjas | b445f4caf09730cc0a6cc7d2ab10fda3e9188111 | [
"MIT"
] | null | null | null | Data Structures and Algorithms CPP/10 Linked List 2/04ReverseRec.cpp | shivamaggarwal513/Coding-Ninjas | b445f4caf09730cc0a6cc7d2ab10fda3e9188111 | [
"MIT"
] | null | null | null | #include <iostream>
#include "..\09 Linked List 1\01LinkedList.h"
using namespace std;
Node *reverseLLRec(Node *head)
{
if (!(head && head->next))
return head;
Node *newHead = reverseLLRec(head->next);
Node *temp = newHead;
while (temp->next)
temp = temp->next;
temp->next = head;
head->next = nullptr;
return newHead;
}
int main()
{
int t;
Node *head;
cin >> t;
while (t--)
{
head = takeInput();
head = reverseLLRec(head);
printLL(head);
}
return 0;
} | 18.333333 | 45 | 0.552727 | shivamaggarwal513 |
684382b1883cc26b1f2b8ac15edb63fe4f070be1 | 2,118 | cpp | C++ | data/train/cpp/684382b1883cc26b1f2b8ac15edb63fe4f070be1TestRepository.cpp | harshp8l/deep-learning-lang-detection | 2a54293181c1c2b1a2b840ddee4d4d80177efb33 | [
"MIT"
] | 84 | 2017-10-25T15:49:21.000Z | 2021-11-28T21:25:54.000Z | data/train/cpp/684382b1883cc26b1f2b8ac15edb63fe4f070be1TestRepository.cpp | vassalos/deep-learning-lang-detection | cbb00b3e81bed3a64553f9c6aa6138b2511e544e | [
"MIT"
] | 5 | 2018-03-29T11:50:46.000Z | 2021-04-26T13:33:18.000Z | data/train/cpp/684382b1883cc26b1f2b8ac15edb63fe4f070be1TestRepository.cpp | vassalos/deep-learning-lang-detection | cbb00b3e81bed3a64553f9c6aa6138b2511e544e | [
"MIT"
] | 24 | 2017-11-22T08:31:00.000Z | 2022-03-27T01:22:31.000Z | /*
* MacGitver
* Copyright (C) 2012-2013 The MacGitver-Developers <dev@macgitver.org>
*
* (C) Sascha Cunz <sascha@macgitver.org>
* (C) Cunz RaD Ltd.
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License (Version 2) as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program; if
* not, see <http://www.gnu.org/licenses/>.
*
*/
#include "gtest/gtest.h"
#include "libGitWrap/Result.hpp"
#include "libGitWrap/Repository.hpp"
#include "Infra/Fixture.hpp"
#include "Infra/TempRepo.hpp"
typedef Fixture RepositoryFixture;
TEST_F(RepositoryFixture, CanOpen)
{
Git::Result r;
TempRepoOpener tempRepo(this, "SimpleRepo1", r);
CHECK_GIT_RESULT(r);
Git::Repository repo(tempRepo);
ASSERT_TRUE(repo.isValid());
ASSERT_FALSE(repo.isBare());
ASSERT_FALSE(repo.isHeadDetached());
ASSERT_STREQ("SimpleRepo1", qPrintable(repo.name()));
}
TEST_F(RepositoryFixture, CanListBranches)
{
Git::Result r;
TempRepoOpener tempRepo(this, "SimpleRepo1", r);
CHECK_GIT_RESULT(r);
Git::Repository repo(tempRepo);
ASSERT_TRUE(repo.isValid());
QStringList sl = repo.branchNames(r, true, false);
CHECK_GIT_RESULT(r);
ASSERT_EQ(1, sl.count());
EXPECT_STREQ("master",
qPrintable(sl[0]));
sl = repo.branchNames(r, false, true);
CHECK_GIT_RESULT(r);
ASSERT_EQ(0, sl.count());
}
TEST_F(RepositoryFixture, CanDetachHEAD)
{
Git::Result r;
TempRepoOpener tempRepo(this, "SimpleRepo1", r);
CHECK_GIT_RESULT(r);
Git::Repository repo(tempRepo);
ASSERT_TRUE(repo.isValid());
ASSERT_FALSE(repo.isHeadDetached());
ASSERT_TRUE(repo.detachHead(r));
CHECK_GIT_RESULT(r);
ASSERT_TRUE(repo.isHeadDetached());
}
| 27.153846 | 100 | 0.704438 | harshp8l |
96961f8c99a776743b1a779a152b99b8ce30b131 | 1,734 | hpp | C++ | src/libhashkit/rijndael.hpp | remicollet/libmemcached | 5d97952f140aaed543d06150e5d05b56c4971b51 | [
"BSD-3-Clause"
] | null | null | null | src/libhashkit/rijndael.hpp | remicollet/libmemcached | 5d97952f140aaed543d06150e5d05b56c4971b51 | [
"BSD-3-Clause"
] | null | null | null | src/libhashkit/rijndael.hpp | remicollet/libmemcached | 5d97952f140aaed543d06150e5d05b56c4971b51 | [
"BSD-3-Clause"
] | null | null | null | /*
+--------------------------------------------------------------------+
| libmemcached-awesome - C/C++ Client Library for memcached |
+--------------------------------------------------------------------+
| Redistribution and use in source and binary forms, with or without |
| modification, are permitted under the terms of the BSD license. |
| You should have received a copy of the license in a bundled file |
| named LICENSE; in case you did not receive a copy you can review |
| the terms online at: https://opensource.org/licenses/BSD-3-Clause |
+--------------------------------------------------------------------+
| Copyright (c) 2006-2014 Brian Aker https://datadifferential.com/ |
| Copyright (c) 2020-2021 Michael Wallner https://awesome.co/ |
+--------------------------------------------------------------------+
*/
#pragma once
#define MAXKC (256 / 32)
#define MAXKB (256 / 8)
#define MAXNR 14
#define AES_MAXKC MAXKC
#define AES_MAXKB MAXKB
#define AES_MAXNR MAXNR
typedef unsigned char u8;
typedef unsigned short u16;
typedef unsigned int u32;
int rijndaelKeySetupEnc(u32 rk[/*4*(Nr + 1)*/], const u8 cipherKey[], int keyBits);
int rijndaelKeySetupDec(u32 rk[/*4*(Nr + 1)*/], const u8 cipherKey[], int keyBits);
void rijndaelEncrypt(const u32 rk[/*4*(Nr + 1)*/], int Nr, const u8 pt[16], u8 ct[16]);
void rijndaelDecrypt(const u32 rk[/*4*(Nr + 1)*/], int Nr, const u8 ct[16], u8 pt[16]);
#ifdef INTERMEDIATE_VALUE_KAT
void rijndaelEncryptRound(const u32 rk[/*4*(Nr + 1)*/], int Nr, u8 block[16], int rounds);
void rijndaelDecryptRound(const u32 rk[/*4*(Nr + 1)*/], int Nr, u8 block[16], int rounds);
#endif /* INTERMEDIATE_VALUE_KAT */ | 45.631579 | 90 | 0.567474 | remicollet |
96974e75f756a3ddc8aea42f9af6f45f958dad4a | 3,338 | hh | C++ | tests/quizzer/deserializers/AssessmentDeserializerTest.hh | davidmogar/quizzer-hack | 04fbd8faffc03f9924ebb75e2334114f1b931b88 | [
"MIT"
] | null | null | null | tests/quizzer/deserializers/AssessmentDeserializerTest.hh | davidmogar/quizzer-hack | 04fbd8faffc03f9924ebb75e2334114f1b931b88 | [
"MIT"
] | null | null | null | tests/quizzer/deserializers/AssessmentDeserializerTest.hh | davidmogar/quizzer-hack | 04fbd8faffc03f9924ebb75e2334114f1b931b88 | [
"MIT"
] | null | null | null | <?hh
require_once 'quizzer/deserializers/AssessmentDeserializer.hh';
class AssessmentDeserializerTest extends PHPUnit_Framework_TestCase
{
private static $questionsJson = '{ "questions": [ { "type": "multichoice", "id" : 1,
"questionText": "Scala fue creado por...", "alternatives": [ { "text": "Martin Odersky", "code": 1,
"value": 1 }, { "text": "James Gosling", "code": 2, "value": -0.25 }, { "text": "Guido van Rossum",
"code": 3, "value": -0.25 } ] }, { "type" : "truefalse", "id" : 2,
"questionText": "El creador de Ruby es Yukihiro Matsumoto", "correct": true, "valueOK": 1,
"valueFailed": -0.25, "feedback": "Yukihiro Matsumoto es el principal desarrollador de Ruby desde 1996" } ] }';
private static $answersJson = '{ "items": [ { "studentId": 234 , "answers": [ { "question" : 1, "value": 1 },
{ "question" : 2, "value": false } ] }, { "studentId": 245 , "answers": [ { "question" : 1, "value": 1 },
{ "question" : 2, "value": true } ] }, { "studentId": 221 , "answers": [ { "question" : 1,
"value": 2 } ] } ] }';
private static $gradesJson = '{ "scores": [ { "studentId": 234, "value": 0.75 } , { "studentId": 245,
"value": 2.0 } , { "studentId": 221, "value": 0.75 } ] }';
public function testDeserializeAnswers()
{
$answers = AssessmentDeserializer::deserializeAnswers(self::$answersJson);
$this->assertNotNull($answers, 'Answers is null');
$this->assertTrue(count($answers) == 3, 'Unexpected size for answers map');
$this->assertTrue(count($answers[234]) == 2, 'Unexpected size for answers of student id 234');
$this->assertTrue(count($answers[245]) == 2, 'Unexpected size for answers of student id 245');
$this->assertTrue(count($answers[221]) == 1, 'Unexpected size for answers of student id 221');
}
public function testDeserializeGrades()
{
$grades = AssessmentDeserializer::deserializeGrades(self::$gradesJson);
$this->assertNotNull($grades, 'Grades is null');
$this->assertTrue(count($grades) == 3, 'Unexpected size for grades map');
$this->assertEquals($grades[234]->getGrade(), 0.75, 'Grade value for id 234 doesn\'t match', 0.05);
$this->assertEquals($grades[245]->getGrade(), 2, 'Grade value for id 234 doesn\'t match', 0.05);
$this->assertEquals($grades[221]->getGrade(), 0.75, 'Grade value for id 221 doesn\'t match', 0.05);
}
public function testDeserializeQuestions()
{
$questions = AssessmentDeserializer::deserializeQuestions(self::$questionsJson);
$this->assertNotNull($questions, 'Questions is null');
$this->assertTrue(count($questions) == 2, 'Unexpected size for questions map');
$this->assertTrue($questions[1] instanceof MultichoiceQuestion, 'Unexpected type for question 1');
$this->assertTrue($questions[2] instanceof TrueFalseQuestion, 'Unexpected type for question 2');
$this->assertTrue($questions[2]->getCorrect(), 'Unexpected value for question 2');
$answers = AssessmentDeserializer::deserializeAnswers(self::$answersJson);
$this->assertEquals($questions[1]->getScore($answers[234][0]), 1,
'Unexpected score for answer 1 of student 234', 0.05);
}
}
| 55.633333 | 123 | 0.619233 | davidmogar |
969821dddfb585019e6128e8689b6e60984ca4a6 | 1,297 | cpp | C++ | C++/LeetCode/0450.cpp | Nimesh-Srivastava/DSA | db33aa138f0df8ab6015d2e8ec3ddde1c6838848 | [
"MIT"
] | 4 | 2021-08-28T19:16:50.000Z | 2022-03-04T19:46:31.000Z | C++/LeetCode/0450.cpp | Nimesh-Srivastava/DSA | db33aa138f0df8ab6015d2e8ec3ddde1c6838848 | [
"MIT"
] | 8 | 2021-10-29T19:10:51.000Z | 2021-11-03T12:38:00.000Z | C++/LeetCode/0450.cpp | Nimesh-Srivastava/DSA | db33aa138f0df8ab6015d2e8ec3ddde1c6838848 | [
"MIT"
] | 4 | 2021-09-06T05:53:07.000Z | 2021-12-24T10:31:40.000Z | class Solution {
public:
int getVal(TreeNode* root){
if(!root -> right)
return root -> val;
return getVal(root -> right);
}
TreeNode* delNode(TreeNode* root, int key){
if(!root)
return NULL;
if(root -> val == key){
TreeNode* temp;
if(!root -> left && !root -> right)
return NULL;
else if(!root -> left){
temp = root -> right;
delete(root);
return temp;
}
else if(!root -> right){
temp = root -> left;
delete(root);
return temp;
}
else{
root -> val = getVal(root -> left);
root -> left = delNode(root -> left, root -> val);
return root;
}
}
root -> left = delNode(root -> left, key);
root -> right = delNode(root -> right, key);
return root;
}
TreeNode* deleteNode(TreeNode* root, int key) {
TreeNode* result = delNode(root, key);
return result;
}
};
| 23.581818 | 66 | 0.374711 | Nimesh-Srivastava |
969e602e1eb24f0be93741aa364948d7b904f31e | 413 | cpp | C++ | Leetcode/2114.cpp | prameetu/CP_codes | 41f8cfc188d2e08a8091bc5134247d05ba8a78f5 | [
"MIT"
] | null | null | null | Leetcode/2114.cpp | prameetu/CP_codes | 41f8cfc188d2e08a8091bc5134247d05ba8a78f5 | [
"MIT"
] | null | null | null | Leetcode/2114.cpp | prameetu/CP_codes | 41f8cfc188d2e08a8091bc5134247d05ba8a78f5 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
class Solution {
public:
int mostWordsFound(vector<string>& sentences) {
int ans(0);
for(auto x:sentences)
{
int curr_ans(0);
for(auto words:x)
{
if(words == ' ')
curr_ans++;
}
ans = max(ans,curr_ans);
}
return ans+1;
}
}; | 19.666667 | 51 | 0.438257 | prameetu |
969eb2ddcb0a1e56dfcd28c69e81c0c3ef5a9384 | 88,143 | hpp | C++ | utils/alias.hpp | zouxiaoliang/nerv-kubernetes-client-c | 07528948c643270fd757d38edc68da8c9628ee7a | [
"Apache-2.0"
] | null | null | null | utils/alias.hpp | zouxiaoliang/nerv-kubernetes-client-c | 07528948c643270fd757d38edc68da8c9628ee7a | [
"Apache-2.0"
] | null | null | null | utils/alias.hpp | zouxiaoliang/nerv-kubernetes-client-c | 07528948c643270fd757d38edc68da8c9628ee7a | [
"Apache-2.0"
] | null | null | null | #ifndef ALIAS_H
#define ALIAS_H
#define NS_API(type) io_k8s_api_core_##type
#define function_alias(name)
namespace nerv {
namespace k8s {
// core
namespace core {
typedef struct io_k8s_api_core_v1_namespace_t v1_namespace_t;
// io_k8s_api_core_v1_namespace_t
typedef struct io_k8s_api_core_v1_binding_t v1_binding_t;
// io_k8s_api_core_v1_binding_t
typedef struct io_k8s_api_core_v1_config_map_t v1_config_map_t;
// io_k8s_api_core_v1_config_map_t
typedef struct io_k8s_api_core_v1_endpoints_t v1_endpoints_t;
// io_k8s_api_core_v1_endpoints_t
typedef struct io_k8s_api_core_v1_event_t v1_event_t;
// io_k8s_api_core_v1_event_t
typedef struct io_k8s_api_core_v1_limit_range_t v1_limit_range_t;
// io_k8s_api_core_v1_limit_range_t
typedef struct io_k8s_api_core_v1_persistent_volume_claim_t v1_persistent_volume_claim_t;
// io_k8s_api_core_v1_persistent_volume_claim_t
typedef struct io_k8s_api_core_v1_pod_t v1_pod_t;
// io_k8s_api_core_v1_pod_t
typedef struct io_k8s_api_core_v1_pod_template_t v1_pod_template_t;
// io_k8s_api_core_v1_pod_template_t
typedef struct io_k8s_api_core_v1_replication_controller_t v1_replication_controller_t;
// io_k8s_api_core_v1_replication_controller_t
typedef struct io_k8s_api_core_v1_resource_quota_t v1_resource_quota_t;
// io_k8s_api_core_v1_resource_quota_t
typedef struct io_k8s_api_core_v1_secret_t v1_secret_t;
// io_k8s_api_core_v1_secret_t
typedef struct io_k8s_api_core_v1_service_t v1_service_t;
// io_k8s_api_core_v1_service_t
typedef struct io_k8s_api_core_v1_service_account_t v1_service_account_t;
// io_k8s_api_core_v1_service_account_t
typedef struct io_k8s_api_core_v1_node_t v1_node_t;
// io_k8s_api_core_v1_node_t
typedef struct io_k8s_api_core_v1_persistent_volume_t v1_persistent_volume_t;
// io_k8s_api_core_v1_persistent_volume_t
typedef struct io_k8s_api_core_v1_component_status_list_t v1_component_status_list_t;
// io_k8s_api_core_v1_component_status_list_t
typedef struct io_k8s_api_core_v1_config_map_list_t v1_config_map_list_t;
// io_k8s_api_core_v1_config_map_list_t
typedef struct io_k8s_api_core_v1_endpoints_list_t v1_endpoints_list_t;
// io_k8s_api_core_v1_endpoints_list_t
typedef struct io_k8s_api_core_v1_event_list_t v1_event_list_t;
// io_k8s_api_core_v1_event_list_t
typedef struct io_k8s_api_core_v1_limit_range_list_t v1_limit_range_list_t;
// io_k8s_api_core_v1_limit_range_list_t
typedef struct io_k8s_api_core_v1_namespace_list_t v1_namespace_list_t;
// io_k8s_api_core_v1_namespace_list_t
typedef struct io_k8s_api_core_v1_persistent_volume_claim_list_t v1_persistent_volume_claim_list_t;
// io_k8s_api_core_v1_persistent_volume_claim_list_t
typedef struct io_k8s_api_core_v1_pod_list_t v1_pod_list_t;
// io_k8s_api_core_v1_pod_list_t
typedef struct io_k8s_api_core_v1_pod_template_list_t v1_pod_template_list_t;
// io_k8s_api_core_v1_pod_template_list_t
typedef struct io_k8s_api_core_v1_replication_controller_list_t v1_replication_controller_list_t;
// io_k8s_api_core_v1_replication_controller_list_t
typedef struct io_k8s_api_core_v1_resource_quota_list_t v1_resource_quota_list_t;
// io_k8s_api_core_v1_resource_quota_list_t
typedef struct io_k8s_api_core_v1_secret_list_t v1_secret_list_t;
// io_k8s_api_core_v1_secret_list_t
typedef struct io_k8s_api_core_v1_service_list_t v1_service_list_t;
// io_k8s_api_core_v1_service_list_t
typedef struct io_k8s_api_core_v1_service_account_list_t v1_service_account_list_t;
// io_k8s_api_core_v1_service_account_list_t
typedef struct io_k8s_api_core_v1_node_list_t v1_node_list_t;
// io_k8s_api_core_v1_node_list_t
typedef struct io_k8s_api_core_v1_persistent_volume_list_t v1_persistent_volume_list_t;
// io_k8s_api_core_v1_persistent_volume_list_t
typedef struct io_k8s_api_core_v1_ephemeral_containers_t v1_ephemeral_containers_t;
// io_k8s_api_core_v1_ephemeral_containers_t
typedef struct io_k8s_api_core_v1_component_status_t v1_component_status_t;
// io_k8s_api_core_v1_component_status_t
typedef struct io_k8s_api_core_v1_csi_volume_source_t v1_csi_volume_source_t;
// io_k8s_api_core_v1_csi_volume_source_t
typedef struct io_k8s_api_core_v1_local_object_reference_t v1_local_object_reference_t;
// io_k8s_api_core_v1_local_object_reference_t
typedef struct io_k8s_api_core_v1_flex_persistent_volume_source_t v1_flex_persistent_volume_source_t;
// io_k8s_api_core_v1_flex_persistent_volume_source_t
typedef struct io_k8s_api_core_v1_secret_reference_t v1_secret_reference_t;
// io_k8s_api_core_v1_secret_reference_t
typedef struct io_k8s_api_core_v1_volume_device_t v1_volume_device_t;
// io_k8s_api_core_v1_volume_device_t
typedef struct io_k8s_api_core_v1_namespace_spec_t v1_namespace_spec_t;
// io_k8s_api_core_v1_namespace_spec_t
typedef struct io_k8s_api_core_v1_secret_env_source_t v1_secret_env_source_t;
// io_k8s_api_core_v1_secret_env_source_t
typedef struct io_k8s_api_core_v1_pod_security_context_t v1_pod_security_context_t;
// io_k8s_api_core_v1_pod_security_context_t
typedef struct io_k8s_api_core_v1_se_linux_options_t v1_se_linux_options_t;
// io_k8s_api_core_v1_se_linux_options_t
typedef struct io_k8s_api_core_v1_seccomp_profile_t v1_seccomp_profile_t;
// io_k8s_api_core_v1_seccomp_profile_t
typedef struct io_k8s_api_core_v1_windows_security_context_options_t v1_windows_security_context_options_t;
// io_k8s_api_core_v1_windows_security_context_options_t
typedef struct io_k8s_api_core_v1_probe_t v1_probe_t;
// io_k8s_api_core_v1_probe_t
typedef struct io_k8s_api_core_v1_exec_action_t v1_exec_action_t;
// io_k8s_api_core_v1_exec_action_t
typedef struct io_k8s_api_core_v1_http_get_action_t v1_http_get_action_t;
// io_k8s_api_core_v1_http_get_action_t
typedef struct io_k8s_api_core_v1_tcp_socket_action_t v1_tcp_socket_action_t;
// io_k8s_api_core_v1_tcp_socket_action_t
typedef struct io_k8s_api_core_v1_gce_persistent_disk_volume_source_t v1_gce_persistent_disk_volume_source_t;
// io_k8s_api_core_v1_gce_persistent_disk_volume_source_t
typedef struct io_k8s_api_core_v1_object_reference_t v1_object_reference_t;
// io_k8s_api_core_v1_object_reference_t
typedef struct io_k8s_api_core_v1_env_var_t v1_env_var_t;
// io_k8s_api_core_v1_env_var_t
typedef struct io_k8s_api_core_v1_env_var_source_t v1_env_var_source_t;
// io_k8s_api_core_v1_env_var_source_t
typedef struct io_k8s_api_core_v1_downward_api_projection_t v1_downward_api_projection_t;
// io_k8s_api_core_v1_downward_api_projection_t
typedef struct io_k8s_api_core_v1_node_config_status_t v1_node_config_status_t;
// io_k8s_api_core_v1_node_config_status_t
typedef struct io_k8s_api_core_v1_node_config_source_t v1_node_config_source_t;
// io_k8s_api_core_v1_node_config_source_t
typedef struct io_k8s_api_core_v1_persistent_volume_claim_spec_t v1_persistent_volume_claim_spec_t;
// io_k8s_api_core_v1_persistent_volume_claim_spec_t
typedef struct io_k8s_api_core_v1_persistent_volume_claim_status_t v1_persistent_volume_claim_status_t;
// io_k8s_api_core_v1_persistent_volume_claim_status_t
typedef struct io_k8s_api_core_v1_pod_template_spec_t v1_pod_template_spec_t;
// io_k8s_api_core_v1_pod_template_spec_t
typedef struct io_k8s_api_core_v1_csi_persistent_volume_source_t v1_csi_persistent_volume_source_t;
// io_k8s_api_core_v1_csi_persistent_volume_source_t
typedef struct io_k8s_api_core_v1_resource_quota_spec_t v1_resource_quota_spec_t;
// io_k8s_api_core_v1_resource_quota_spec_t
typedef struct io_k8s_api_core_v1_scope_selector_t v1_scope_selector_t;
// io_k8s_api_core_v1_scope_selector_t
typedef struct io_k8s_api_core_v1_pod_dns_config_option_t v1_pod_dns_config_option_t;
// io_k8s_api_core_v1_pod_dns_config_option_t
typedef struct io_k8s_api_core_v1_quobyte_volume_source_t v1_quobyte_volume_source_t;
// io_k8s_api_core_v1_quobyte_volume_source_t
typedef struct io_k8s_api_core_v1_service_spec_t v1_service_spec_t;
// io_k8s_api_core_v1_service_spec_t
typedef struct io_k8s_api_core_v1_service_status_t v1_service_status_t;
// io_k8s_api_core_v1_service_status_t
typedef struct io_k8s_api_core_v1_pod_dns_config_t v1_pod_dns_config_t;
// io_k8s_api_core_v1_pod_dns_config_t
typedef struct io_k8s_api_core_v1_git_repo_volume_source_t v1_git_repo_volume_source_t;
// io_k8s_api_core_v1_git_repo_volume_source_t
typedef struct io_k8s_api_core_v1_volume_t v1_volume_t;
// io_k8s_api_core_v1_volume_t
typedef struct io_k8s_api_core_v1_aws_elastic_block_store_volume_source_t v1_aws_elastic_block_store_volume_source_t;
// io_k8s_api_core_v1_aws_elastic_block_store_volume_source_t
typedef struct io_k8s_api_core_v1_azure_disk_volume_source_t v1_azure_disk_volume_source_t;
// io_k8s_api_core_v1_azure_disk_volume_source_t
typedef struct io_k8s_api_core_v1_azure_file_volume_source_t v1_azure_file_volume_source_t;
// io_k8s_api_core_v1_azure_file_volume_source_t
typedef struct io_k8s_api_core_v1_ceph_fs_volume_source_t v1_ceph_fs_volume_source_t;
// io_k8s_api_core_v1_ceph_fs_volume_source_t
typedef struct io_k8s_api_core_v1_cinder_volume_source_t v1_cinder_volume_source_t;
// io_k8s_api_core_v1_cinder_volume_source_t
typedef struct io_k8s_api_core_v1_config_map_volume_source_t v1_config_map_volume_source_t;
// io_k8s_api_core_v1_config_map_volume_source_t
typedef struct io_k8s_api_core_v1_downward_api_volume_source_t v1_downward_api_volume_source_t;
// io_k8s_api_core_v1_downward_api_volume_source_t
typedef struct io_k8s_api_core_v1_empty_dir_volume_source_t v1_empty_dir_volume_source_t;
// io_k8s_api_core_v1_empty_dir_volume_source_t
typedef struct io_k8s_api_core_v1_ephemeral_volume_source_t v1_ephemeral_volume_source_t;
// io_k8s_api_core_v1_ephemeral_volume_source_t
typedef struct io_k8s_api_core_v1_fc_volume_source_t v1_fc_volume_source_t;
// io_k8s_api_core_v1_fc_volume_source_t
typedef struct io_k8s_api_core_v1_flex_volume_source_t v1_flex_volume_source_t;
// io_k8s_api_core_v1_flex_volume_source_t
typedef struct io_k8s_api_core_v1_flocker_volume_source_t v1_flocker_volume_source_t;
// io_k8s_api_core_v1_flocker_volume_source_t
typedef struct io_k8s_api_core_v1_glusterfs_volume_source_t v1_glusterfs_volume_source_t;
// io_k8s_api_core_v1_glusterfs_volume_source_t
typedef struct io_k8s_api_core_v1_host_path_volume_source_t v1_host_path_volume_source_t;
// io_k8s_api_core_v1_host_path_volume_source_t
typedef struct io_k8s_api_core_v1_iscsi_volume_source_t v1_iscsi_volume_source_t;
// io_k8s_api_core_v1_iscsi_volume_source_t
typedef struct io_k8s_api_core_v1_nfs_volume_source_t v1_nfs_volume_source_t;
// io_k8s_api_core_v1_nfs_volume_source_t
typedef struct io_k8s_api_core_v1_persistent_volume_claim_volume_source_t v1_persistent_volume_claim_volume_source_t;
// io_k8s_api_core_v1_persistent_volume_claim_volume_source_t
typedef struct io_k8s_api_core_v1_photon_persistent_disk_volume_source_t v1_photon_persistent_disk_volume_source_t;
// io_k8s_api_core_v1_photon_persistent_disk_volume_source_t
typedef struct io_k8s_api_core_v1_portworx_volume_source_t v1_portworx_volume_source_t;
// io_k8s_api_core_v1_portworx_volume_source_t
typedef struct io_k8s_api_core_v1_projected_volume_source_t v1_projected_volume_source_t;
// io_k8s_api_core_v1_projected_volume_source_t
typedef struct io_k8s_api_core_v1_rbd_volume_source_t v1_rbd_volume_source_t;
// io_k8s_api_core_v1_rbd_volume_source_t
typedef struct io_k8s_api_core_v1_scale_io_volume_source_t v1_scale_io_volume_source_t;
// io_k8s_api_core_v1_scale_io_volume_source_t
typedef struct io_k8s_api_core_v1_secret_volume_source_t v1_secret_volume_source_t;
// io_k8s_api_core_v1_secret_volume_source_t
typedef struct io_k8s_api_core_v1_storage_os_volume_source_t v1_storage_os_volume_source_t;
// io_k8s_api_core_v1_storage_os_volume_source_t
typedef struct io_k8s_api_core_v1_vsphere_virtual_disk_volume_source_t v1_vsphere_virtual_disk_volume_source_t;
// io_k8s_api_core_v1_vsphere_virtual_disk_volume_source_t
typedef struct io_k8s_api_core_v1_config_map_key_selector_t v1_config_map_key_selector_t;
// io_k8s_api_core_v1_config_map_key_selector_t
typedef struct io_k8s_api_core_v1_object_field_selector_t v1_object_field_selector_t;
// io_k8s_api_core_v1_object_field_selector_t
typedef struct io_k8s_api_core_v1_resource_field_selector_t v1_resource_field_selector_t;
// io_k8s_api_core_v1_resource_field_selector_t
typedef struct io_k8s_api_core_v1_secret_key_selector_t v1_secret_key_selector_t;
// io_k8s_api_core_v1_secret_key_selector_t
typedef struct io_k8s_api_core_v1_weighted_pod_affinity_term_t v1_weighted_pod_affinity_term_t;
// io_k8s_api_core_v1_weighted_pod_affinity_term_t
typedef struct io_k8s_api_core_v1_pod_affinity_term_t v1_pod_affinity_term_t;
// io_k8s_api_core_v1_pod_affinity_term_t
typedef struct io_k8s_api_core_v1_node_selector_requirement_t v1_node_selector_requirement_t;
// io_k8s_api_core_v1_node_selector_requirement_t
typedef struct io_k8s_api_core_v1_namespace_status_t v1_namespace_status_t;
// io_k8s_api_core_v1_namespace_status_t
typedef struct io_k8s_api_core_v1_node_address_t v1_node_address_t;
// io_k8s_api_core_v1_node_address_t
typedef struct io_k8s_api_core_v1_endpoint_port_t v1_endpoint_port_t;
// io_k8s_api_core_v1_endpoint_port_t
typedef struct io_k8s_api_core_v1_pod_ip_t v1_pod_ip_t;
// io_k8s_api_core_v1_pod_ip_t
typedef struct io_k8s_api_core_v1_event_series_t v1_event_series_t;
// io_k8s_api_core_v1_event_series_t
typedef struct io_k8s_api_core_v1_env_from_source_t v1_env_from_source_t;
// io_k8s_api_core_v1_env_from_source_t
typedef struct io_k8s_api_core_v1_config_map_env_source_t v1_config_map_env_source_t;
// io_k8s_api_core_v1_config_map_env_source_t
typedef struct io_k8s_api_core_v1_session_affinity_config_t v1_session_affinity_config_t;
// io_k8s_api_core_v1_session_affinity_config_t
typedef struct io_k8s_api_core_v1_client_ip_config_t v1_client_ip_config_t;
// io_k8s_api_core_v1_client_ip_config_t
typedef struct io_k8s_api_core_v1_typed_local_object_reference_t v1_typed_local_object_reference_t;
// io_k8s_api_core_v1_typed_local_object_reference_t
typedef struct io_k8s_api_core_v1_endpoint_subset_t v1_endpoint_subset_t;
// io_k8s_api_core_v1_endpoint_subset_t
typedef struct io_k8s_api_core_v1_pod_anti_affinity_t v1_pod_anti_affinity_t;
// io_k8s_api_core_v1_pod_anti_affinity_t
typedef struct io_k8s_api_core_v1_persistent_volume_spec_t v1_persistent_volume_spec_t;
// io_k8s_api_core_v1_persistent_volume_spec_t
typedef struct io_k8s_api_core_v1_persistent_volume_status_t v1_persistent_volume_status_t;
// io_k8s_api_core_v1_persistent_volume_status_t
typedef struct io_k8s_api_core_v1_topology_selector_term_t v1_topology_selector_term_t;
// io_k8s_api_core_v1_topology_selector_term_t
typedef struct io_k8s_api_core_v1_event_source_t v1_event_source_t;
// io_k8s_api_core_v1_event_source_t
typedef struct io_k8s_api_core_v1_config_map_projection_t v1_config_map_projection_t;
// io_k8s_api_core_v1_config_map_projection_t
typedef struct io_k8s_api_core_v1_host_alias_t v1_host_alias_t;
// io_k8s_api_core_v1_host_alias_t
typedef struct io_k8s_api_core_v1_service_account_token_projection_t v1_service_account_token_projection_t;
// io_k8s_api_core_v1_service_account_token_projection_t
typedef struct io_k8s_api_core_v1_container_status_t v1_container_status_t;
// io_k8s_api_core_v1_container_status_t
typedef struct io_k8s_api_core_v1_container_state_t v1_container_state_t;
// io_k8s_api_core_v1_container_state_t
typedef struct io_k8s_api_core_v1_load_balancer_status_t v1_load_balancer_status_t;
// io_k8s_api_core_v1_load_balancer_status_t
typedef struct io_k8s_api_core_v1_preferred_scheduling_term_t v1_preferred_scheduling_term_t;
// io_k8s_api_core_v1_preferred_scheduling_term_t
typedef struct io_k8s_api_core_v1_node_selector_term_t v1_node_selector_term_t;
// io_k8s_api_core_v1_node_selector_term_t
typedef struct io_k8s_api_core_v1_security_context_t v1_security_context_t;
// io_k8s_api_core_v1_security_context_t
typedef struct io_k8s_api_core_v1_capabilities_t v1_capabilities_t;
// io_k8s_api_core_v1_capabilities_t
typedef struct io_k8s_api_core_v1_limit_range_item_t v1_limit_range_item_t;
// io_k8s_api_core_v1_limit_range_item_t
typedef struct io_k8s_api_core_v1_lifecycle_t v1_lifecycle_t;
// io_k8s_api_core_v1_lifecycle_t
typedef struct io_k8s_api_core_v1_handler_t v1_handler_t;
// io_k8s_api_core_v1_handler_t
typedef struct io_k8s_api_core_v1_port_status_t v1_port_status_t;
// io_k8s_api_core_v1_port_status_t
typedef struct io_k8s_api_core_v1_volume_node_affinity_t v1_volume_node_affinity_t;
// io_k8s_api_core_v1_volume_node_affinity_t
typedef struct io_k8s_api_core_v1_node_selector_t v1_node_selector_t;
// io_k8s_api_core_v1_node_selector_t
typedef struct io_k8s_api_core_v1_pod_spec_t v1_pod_spec_t;
// io_k8s_api_core_v1_pod_spec_t
typedef struct io_k8s_api_core_v1_persistent_volume_claim_template_t v1_persistent_volume_claim_template_t;
// io_k8s_api_core_v1_persistent_volume_claim_template_t
typedef struct io_k8s_api_core_v1_limit_range_spec_t v1_limit_range_spec_t;
// io_k8s_api_core_v1_limit_range_spec_t
typedef struct io_k8s_api_core_v1_http_header_t v1_http_header_t;
// io_k8s_api_core_v1_http_header_t
typedef struct io_k8s_api_core_v1_container_t v1_container_t;
// io_k8s_api_core_v1_container_t
typedef struct io_k8s_api_core_v1_resource_requirements_t v1_resource_requirements_t;
// io_k8s_api_core_v1_resource_requirements_t
typedef struct io_k8s_api_core_v1_pod_status_t v1_pod_status_t;
// io_k8s_api_core_v1_pod_status_t
typedef struct io_k8s_api_core_v1_config_map_node_config_source_t v1_config_map_node_config_source_t;
// io_k8s_api_core_v1_config_map_node_config_source_t
typedef struct io_k8s_api_core_v1_replication_controller_spec_t v1_replication_controller_spec_t;
// io_k8s_api_core_v1_replication_controller_spec_t
typedef struct io_k8s_api_core_v1_replication_controller_status_t v1_replication_controller_status_t;
// io_k8s_api_core_v1_replication_controller_status_t
typedef struct io_k8s_api_core_v1_key_to_path_t v1_key_to_path_t;
// io_k8s_api_core_v1_key_to_path_t
typedef struct io_k8s_api_core_v1_ceph_fs_persistent_volume_source_t v1_ceph_fs_persistent_volume_source_t;
// io_k8s_api_core_v1_ceph_fs_persistent_volume_source_t
typedef struct io_k8s_api_core_v1_sysctl_t v1_sysctl_t;
// io_k8s_api_core_v1_sysctl_t
typedef struct io_k8s_api_core_v1_node_spec_t v1_node_spec_t;
// io_k8s_api_core_v1_node_spec_t
typedef struct io_k8s_api_core_v1_node_status_t v1_node_status_t;
// io_k8s_api_core_v1_node_status_t
typedef struct io_k8s_api_core_v1_container_state_running_t v1_container_state_running_t;
// io_k8s_api_core_v1_container_state_running_t
typedef struct io_k8s_api_core_v1_container_state_terminated_t v1_container_state_terminated_t;
// io_k8s_api_core_v1_container_state_terminated_t
typedef struct io_k8s_api_core_v1_container_state_waiting_t v1_container_state_waiting_t;
// io_k8s_api_core_v1_container_state_waiting_t
typedef struct io_k8s_api_core_v1_iscsi_persistent_volume_source_t v1_iscsi_persistent_volume_source_t;
// io_k8s_api_core_v1_iscsi_persistent_volume_source_t
typedef struct io_k8s_api_core_v1_affinity_t v1_affinity_t;
// io_k8s_api_core_v1_affinity_t
typedef struct io_k8s_api_core_v1_node_affinity_t v1_node_affinity_t;
// io_k8s_api_core_v1_node_affinity_t
typedef struct io_k8s_api_core_v1_pod_affinity_t v1_pod_affinity_t;
// io_k8s_api_core_v1_pod_affinity_t
typedef struct io_k8s_api_core_v1_azure_file_persistent_volume_source_t v1_azure_file_persistent_volume_source_t;
// io_k8s_api_core_v1_azure_file_persistent_volume_source_t
typedef struct io_k8s_api_core_v1_local_volume_source_t v1_local_volume_source_t;
// io_k8s_api_core_v1_local_volume_source_t
typedef struct io_k8s_api_core_v1_cinder_persistent_volume_source_t v1_cinder_persistent_volume_source_t;
// io_k8s_api_core_v1_cinder_persistent_volume_source_t
typedef struct io_k8s_api_core_v1_component_condition_t v1_component_condition_t;
// io_k8s_api_core_v1_component_condition_t
typedef struct io_k8s_api_core_v1_pod_readiness_gate_t v1_pod_readiness_gate_t;
// io_k8s_api_core_v1_pod_readiness_gate_t
typedef struct io_k8s_api_core_v1_secret_projection_t v1_secret_projection_t;
// io_k8s_api_core_v1_secret_projection_t
typedef struct io_k8s_api_core_v1_persistent_volume_claim_condition_t v1_persistent_volume_claim_condition_t;
// io_k8s_api_core_v1_persistent_volume_claim_condition_t
typedef struct io_k8s_api_core_v1_toleration_t v1_toleration_t;
// io_k8s_api_core_v1_toleration_t
typedef struct io_k8s_api_core_v1_resource_quota_status_t v1_resource_quota_status_t;
// io_k8s_api_core_v1_resource_quota_status_t
typedef struct io_k8s_api_core_v1_topology_spread_constraint_t v1_topology_spread_constraint_t;
// io_k8s_api_core_v1_topology_spread_constraint_t
typedef struct io_k8s_api_core_v1_node_system_info_t v1_node_system_info_t;
// io_k8s_api_core_v1_node_system_info_t
typedef struct io_k8s_api_core_v1_taint_t v1_taint_t;
// io_k8s_api_core_v1_taint_t
typedef struct io_k8s_api_core_v1_node_condition_t v1_node_condition_t;
// io_k8s_api_core_v1_node_condition_t
typedef struct io_k8s_api_core_v1_volume_mount_t v1_volume_mount_t;
// io_k8s_api_core_v1_volume_mount_t
typedef struct io_k8s_api_core_v1_container_port_t v1_container_port_t;
// io_k8s_api_core_v1_container_port_t
typedef struct io_k8s_api_core_v1_topology_selector_label_requirement_t v1_topology_selector_label_requirement_t;
// io_k8s_api_core_v1_topology_selector_label_requirement_t
typedef struct io_k8s_api_core_v1_container_image_t v1_container_image_t;
// io_k8s_api_core_v1_container_image_t
typedef struct io_k8s_api_core_v1_rbd_persistent_volume_source_t v1_rbd_persistent_volume_source_t;
// io_k8s_api_core_v1_rbd_persistent_volume_source_t
typedef struct io_k8s_api_core_v1_endpoint_address_t v1_endpoint_address_t;
// io_k8s_api_core_v1_endpoint_address_t
typedef struct io_k8s_api_core_v1_attached_volume_t v1_attached_volume_t;
// io_k8s_api_core_v1_attached_volume_t
typedef struct io_k8s_api_core_v1_pod_condition_t v1_pod_condition_t;
// io_k8s_api_core_v1_pod_condition_t
typedef struct io_k8s_api_core_v1_load_balancer_ingress_t v1_load_balancer_ingress_t;
// io_k8s_api_core_v1_load_balancer_ingress_t
typedef struct io_k8s_api_core_v1_glusterfs_persistent_volume_source_t v1_glusterfs_persistent_volume_source_t;
// io_k8s_api_core_v1_glusterfs_persistent_volume_source_t
typedef struct io_k8s_api_core_v1_scoped_resource_selector_requirement_t v1_scoped_resource_selector_requirement_t;
// io_k8s_api_core_v1_scoped_resource_selector_requirement_t
typedef struct io_k8s_api_core_v1_node_daemon_endpoints_t v1_node_daemon_endpoints_t;
// io_k8s_api_core_v1_node_daemon_endpoints_t
typedef struct io_k8s_api_core_v1_volume_projection_t v1_volume_projection_t;
// io_k8s_api_core_v1_volume_projection_t
typedef struct io_k8s_api_core_v1_namespace_condition_t v1_namespace_condition_t;
// io_k8s_api_core_v1_namespace_condition_t
typedef struct io_k8s_api_core_v1_replication_controller_condition_t v1_replication_controller_condition_t;
// io_k8s_api_core_v1_replication_controller_condition_t
typedef struct io_k8s_api_core_v1_daemon_endpoint_t v1_daemon_endpoint_t;
// io_k8s_api_core_v1_daemon_endpoint_t
typedef struct io_k8s_api_core_v1_storage_os_persistent_volume_source_t v1_storage_os_persistent_volume_source_t;
// io_k8s_api_core_v1_storage_os_persistent_volume_source_t
typedef struct io_k8s_api_core_v1_scale_io_persistent_volume_source_t v1_scale_io_persistent_volume_source_t;
// io_k8s_api_core_v1_scale_io_persistent_volume_source_t
typedef struct io_k8s_api_core_v1_downward_api_volume_file_t v1_downward_api_volume_file_t;
// io_k8s_api_core_v1_downward_api_volume_file_t
typedef struct io_k8s_api_core_v1_ephemeral_container_t v1_ephemeral_container_t;
// io_k8s_api_core_v1_ephemeral_container_t
typedef struct io_k8s_api_core_v1_service_port_t v1_service_port_t;
// io_k8s_api_core_v1_service_port_t
}
// apimachinery
namespace apimachinery {
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_api_resource_list_t v1_api_resource_list_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_api_resource_list_t
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_status_t v1_status_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_status_t
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_watch_event_t v1_watch_event_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_watch_event_t
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_api_group_t v1_api_group_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_api_group_t
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_api_group_list_t v1_api_group_list_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_api_group_list_t
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_api_versions_t v1_api_versions_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_api_versions_t
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_object_meta_t v1_object_meta_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_object_meta_t
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_api_resource_t v1_api_resource_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_api_resource_t
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_list_meta_t v1_list_meta_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_list_meta_t
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_label_selector_t v1_label_selector_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_label_selector_t
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_status_cause_t v1_status_cause_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_status_cause_t
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_group_version_for_discovery_t v1_group_version_for_discovery_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_group_version_for_discovery_t
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_condition_t v1_condition_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_condition_t
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_label_selector_requirement_t v1_label_selector_requirement_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_label_selector_requirement_t
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_status_details_t v1_status_details_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_status_details_t
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_managed_fields_entry_t v1_managed_fields_entry_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_managed_fields_entry_t
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_server_address_by_client_cidr_t v1_server_address_by_client_cidr_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_server_address_by_client_cidr_t
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_preconditions_t v1_preconditions_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_preconditions_t
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_delete_options_t v1_delete_options_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_delete_options_t
typedef struct io_k8s_apimachinery_pkg_apis_meta_v1_owner_reference_t v1_owner_reference_t;
// io_k8s_apimachinery_pkg_apis_meta_v1_owner_reference_t
}
// authorization
namespace authorization {
typedef struct io_k8s_api_authorization_v1_local_subject_access_review_t v1_local_subject_access_review_t;
// io_k8s_api_authorization_v1_local_subject_access_review_t
typedef struct io_k8s_api_authorization_v1_self_subject_access_review_t v1_self_subject_access_review_t;
// io_k8s_api_authorization_v1_self_subject_access_review_t
typedef struct io_k8s_api_authorization_v1_self_subject_rules_review_t v1_self_subject_rules_review_t;
// io_k8s_api_authorization_v1_self_subject_rules_review_t
typedef struct io_k8s_api_authorization_v1_subject_access_review_t v1_subject_access_review_t;
// io_k8s_api_authorization_v1_subject_access_review_t
typedef struct io_k8s_api_authorization_v1beta1_local_subject_access_review_t v1beta1_local_subject_access_review_t;
// io_k8s_api_authorization_v1beta1_local_subject_access_review_t
typedef struct io_k8s_api_authorization_v1beta1_self_subject_access_review_t v1beta1_self_subject_access_review_t;
// io_k8s_api_authorization_v1beta1_self_subject_access_review_t
typedef struct io_k8s_api_authorization_v1beta1_self_subject_rules_review_t v1beta1_self_subject_rules_review_t;
// io_k8s_api_authorization_v1beta1_self_subject_rules_review_t
typedef struct io_k8s_api_authorization_v1beta1_subject_access_review_t v1beta1_subject_access_review_t;
// io_k8s_api_authorization_v1beta1_subject_access_review_t
typedef struct io_k8s_api_authorization_v1beta1_self_subject_rules_review_spec_t v1beta1_self_subject_rules_review_spec_t;
// io_k8s_api_authorization_v1beta1_self_subject_rules_review_spec_t
typedef struct io_k8s_api_authorization_v1beta1_subject_rules_review_status_t v1beta1_subject_rules_review_status_t;
// io_k8s_api_authorization_v1beta1_subject_rules_review_status_t
typedef struct io_k8s_api_authorization_v1beta1_non_resource_attributes_t v1beta1_non_resource_attributes_t;
// io_k8s_api_authorization_v1beta1_non_resource_attributes_t
typedef struct io_k8s_api_authorization_v1_resource_attributes_t v1_resource_attributes_t;
// io_k8s_api_authorization_v1_resource_attributes_t
typedef struct io_k8s_api_authorization_v1beta1_self_subject_access_review_spec_t v1beta1_self_subject_access_review_spec_t;
// io_k8s_api_authorization_v1beta1_self_subject_access_review_spec_t
typedef struct io_k8s_api_authorization_v1beta1_subject_access_review_status_t v1beta1_subject_access_review_status_t;
// io_k8s_api_authorization_v1beta1_subject_access_review_status_t
typedef struct io_k8s_api_authorization_v1_non_resource_attributes_t v1_non_resource_attributes_t;
// io_k8s_api_authorization_v1_non_resource_attributes_t
typedef struct io_k8s_api_authorization_v1_self_subject_access_review_spec_t v1_self_subject_access_review_spec_t;
// io_k8s_api_authorization_v1_self_subject_access_review_spec_t
typedef struct io_k8s_api_authorization_v1beta1_subject_access_review_spec_t v1beta1_subject_access_review_spec_t;
// io_k8s_api_authorization_v1beta1_subject_access_review_spec_t
typedef struct io_k8s_api_authorization_v1beta1_non_resource_rule_t v1beta1_non_resource_rule_t;
// io_k8s_api_authorization_v1beta1_non_resource_rule_t
typedef struct io_k8s_api_authorization_v1_non_resource_rule_t v1_non_resource_rule_t;
// io_k8s_api_authorization_v1_non_resource_rule_t
typedef struct io_k8s_api_authorization_v1_subject_access_review_status_t v1_subject_access_review_status_t;
// io_k8s_api_authorization_v1_subject_access_review_status_t
typedef struct io_k8s_api_authorization_v1beta1_resource_attributes_t v1beta1_resource_attributes_t;
// io_k8s_api_authorization_v1beta1_resource_attributes_t
typedef struct io_k8s_api_authorization_v1_subject_access_review_spec_t v1_subject_access_review_spec_t;
// io_k8s_api_authorization_v1_subject_access_review_spec_t
typedef struct io_k8s_api_authorization_v1beta1_resource_rule_t v1beta1_resource_rule_t;
// io_k8s_api_authorization_v1beta1_resource_rule_t
typedef struct io_k8s_api_authorization_v1_self_subject_rules_review_spec_t v1_self_subject_rules_review_spec_t;
// io_k8s_api_authorization_v1_self_subject_rules_review_spec_t
typedef struct io_k8s_api_authorization_v1_subject_rules_review_status_t v1_subject_rules_review_status_t;
// io_k8s_api_authorization_v1_subject_rules_review_status_t
typedef struct io_k8s_api_authorization_v1_resource_rule_t v1_resource_rule_t;
// io_k8s_api_authorization_v1_resource_rule_t
}
// events
namespace events {
typedef struct io_k8s_api_events_v1beta1_event_t v1beta1_event_t;
// io_k8s_api_events_v1beta1_event_t
typedef struct io_k8s_api_events_v1beta1_event_list_t v1beta1_event_list_t;
// io_k8s_api_events_v1beta1_event_list_t
typedef struct io_k8s_api_events_v1beta1_event_series_t v1beta1_event_series_t;
// io_k8s_api_events_v1beta1_event_series_t
typedef struct io_k8s_api_events_v1_event_list_t v1_event_list_t;;
// io_k8s_api_events_v1_event_list_t
typedef struct io_k8s_api_events_v1_event_t v1_event_t;;
// io_k8s_api_events_v1_event_t
typedef struct io_k8s_api_events_v1_event_series_t v1_event_series_t;;
// io_k8s_api_events_v1_event_series_t
}
// node
namespace node {
typedef struct io_k8s_api_node_v1beta1_runtime_class_t v1beta1_runtime_class_t;
// io_k8s_api_node_v1beta1_runtime_class_t
typedef struct io_k8s_api_node_v1beta1_runtime_class_list_t v1beta1_runtime_class_list_t;
// io_k8s_api_node_v1beta1_runtime_class_list_t
typedef struct io_k8s_api_node_v1alpha1_runtime_class_t v1alpha1_runtime_class_t;
// io_k8s_api_node_v1alpha1_runtime_class_t
typedef struct io_k8s_api_node_v1alpha1_runtime_class_list_t v1alpha1_runtime_class_list_t;
// io_k8s_api_node_v1alpha1_runtime_class_list_t
typedef struct io_k8s_api_node_v1_runtime_class_t v1_runtime_class_t;
// io_k8s_api_node_v1_runtime_class_t
typedef struct io_k8s_api_node_v1_runtime_class_list_t v1_runtime_class_list_t;
// io_k8s_api_node_v1_runtime_class_list_t
typedef struct io_k8s_api_node_v1beta1_scheduling_t v1beta1_scheduling_t;
// io_k8s_api_node_v1beta1_scheduling_t
typedef struct io_k8s_api_node_v1alpha1_scheduling_t v1alpha1_scheduling_t;
// io_k8s_api_node_v1alpha1_scheduling_t
typedef struct io_k8s_api_node_v1_scheduling_t v1_scheduling_t;
// io_k8s_api_node_v1_scheduling_t
typedef struct io_k8s_api_node_v1_overhead_t v1_overhead_t;
// io_k8s_api_node_v1_overhead_t
typedef struct io_k8s_api_node_v1beta1_overhead_t v1beta1_overhead_t;
// io_k8s_api_node_v1beta1_overhead_t
typedef struct io_k8s_api_node_v1alpha1_runtime_class_spec_t v1alpha1_runtime_class_spec_t;
// io_k8s_api_node_v1alpha1_runtime_class_spec_t
typedef struct io_k8s_api_node_v1alpha1_overhead_t v1alpha1_overhead_t;
// io_k8s_api_node_v1alpha1_overhead_t
}
// scheduling
namespace scheduling {
typedef struct io_k8s_api_scheduling_v1_priority_class_t v1_priority_class_t;
// io_k8s_api_scheduling_v1_priority_class_t
typedef struct io_k8s_api_scheduling_v1_priority_class_list_t v1_priority_class_list_t;
// io_k8s_api_scheduling_v1_priority_class_list_t
typedef struct io_k8s_api_scheduling_v1alpha1_priority_class_t v1alpha1_priority_class_t;
// io_k8s_api_scheduling_v1alpha1_priority_class_t
typedef struct io_k8s_api_scheduling_v1alpha1_priority_class_list_t v1alpha1_priority_class_list_t;
// io_k8s_api_scheduling_v1alpha1_priority_class_list_t
typedef struct io_k8s_api_scheduling_v1beta1_priority_class_t v1beta1_priority_class_t;
// io_k8s_api_scheduling_v1beta1_priority_class_t
typedef struct io_k8s_api_scheduling_v1beta1_priority_class_list_t v1beta1_priority_class_list_t;
// io_k8s_api_scheduling_v1beta1_priority_class_list_t
}
// certificates
namespace certificates {
typedef struct io_k8s_api_certificates_v1beta1_certificate_signing_request_t v1beta1_certificate_signing_request_t;
// io_k8s_api_certificates_v1beta1_certificate_signing_request_t
typedef struct io_k8s_api_certificates_v1beta1_certificate_signing_request_list_t v1beta1_certificate_signing_request_list_t;
// io_k8s_api_certificates_v1beta1_certificate_signing_request_list_t
typedef struct io_k8s_api_certificates_v1_certificate_signing_request_t v1_certificate_signing_request_t;
// io_k8s_api_certificates_v1_certificate_signing_request_t
typedef struct io_k8s_api_certificates_v1_certificate_signing_request_list_t v1_certificate_signing_request_list_t;
// io_k8s_api_certificates_v1_certificate_signing_request_list_t
typedef struct io_k8s_api_certificates_v1_certificate_signing_request_spec_t v1_certificate_signing_request_spec_t;
// io_k8s_api_certificates_v1_certificate_signing_request_spec_t
typedef struct io_k8s_api_certificates_v1_certificate_signing_request_status_t v1_certificate_signing_request_status_t;
// io_k8s_api_certificates_v1_certificate_signing_request_status_t
typedef struct io_k8s_api_certificates_v1beta1_certificate_signing_request_spec_t v1beta1_certificate_signing_request_spec_t;
// io_k8s_api_certificates_v1beta1_certificate_signing_request_spec_t
typedef struct io_k8s_api_certificates_v1beta1_certificate_signing_request_status_t v1beta1_certificate_signing_request_status_t;
// io_k8s_api_certificates_v1beta1_certificate_signing_request_status_t
typedef struct io_k8s_api_certificates_v1_certificate_signing_request_condition_t v1_certificate_signing_request_condition_t;
// io_k8s_api_certificates_v1_certificate_signing_request_condition_t
typedef struct io_k8s_api_certificates_v1beta1_certificate_signing_request_condition_t v1beta1_certificate_signing_request_condition_t;
// io_k8s_api_certificates_v1beta1_certificate_signing_request_condition_t
}
// apiserverinternal
namespace apiserverinternal {
typedef struct io_k8s_api_apiserverinternal_v1alpha1_storage_version_t v1alpha1_storage_version_t;
// io_k8s_api_apiserverinternal_v1alpha1_storage_version_t
typedef struct io_k8s_api_apiserverinternal_v1alpha1_storage_version_list_t v1alpha1_storage_version_list_t;
// io_k8s_api_apiserverinternal_v1alpha1_storage_version_list_t
typedef struct io_k8s_api_apiserverinternal_v1alpha1_storage_version_status_t v1alpha1_storage_version_status_t;
// io_k8s_api_apiserverinternal_v1alpha1_storage_version_status_t
typedef struct io_k8s_api_apiserverinternal_v1alpha1_storage_version_condition_t v1alpha1_storage_version_condition_t;
// io_k8s_api_apiserverinternal_v1alpha1_storage_version_condition_t
typedef struct io_k8s_api_apiserverinternal_v1alpha1_server_storage_version_t v1alpha1_server_storage_version_t;
// io_k8s_api_apiserverinternal_v1alpha1_server_storage_version_t
}
// apps
namespace apps {
typedef struct io_k8s_api_apps_v1_controller_revision_t v1_controller_revision_t;
// io_k8s_api_apps_v1_controller_revision_t
typedef struct io_k8s_api_apps_v1_daemon_set_t v1_daemon_set_t;
// io_k8s_api_apps_v1_daemon_set_t
typedef struct io_k8s_api_apps_v1_deployment_t v1_deployment_t;
// io_k8s_api_apps_v1_deployment_t
typedef struct io_k8s_api_apps_v1_replica_set_t v1_replica_set_t;
// io_k8s_api_apps_v1_replica_set_t
typedef struct io_k8s_api_apps_v1_stateful_set_t v1_stateful_set_t;
// io_k8s_api_apps_v1_stateful_set_t
typedef struct io_k8s_api_apps_v1_controller_revision_list_t v1_controller_revision_list_t;
// io_k8s_api_apps_v1_controller_revision_list_t
typedef struct io_k8s_api_apps_v1_daemon_set_list_t v1_daemon_set_list_t;
// io_k8s_api_apps_v1_daemon_set_list_t
typedef struct io_k8s_api_apps_v1_deployment_list_t v1_deployment_list_t;
// io_k8s_api_apps_v1_deployment_list_t
typedef struct io_k8s_api_apps_v1_replica_set_list_t v1_replica_set_list_t;
// io_k8s_api_apps_v1_replica_set_list_t
typedef struct io_k8s_api_apps_v1_stateful_set_list_t v1_stateful_set_list_t;
// io_k8s_api_apps_v1_stateful_set_list_t
typedef struct io_k8s_api_apps_v1_stateful_set_update_strategy_t v1_stateful_set_update_strategy_t;
// io_k8s_api_apps_v1_stateful_set_update_strategy_t
typedef struct io_k8s_api_apps_v1_rolling_update_stateful_set_strategy_t v1_rolling_update_stateful_set_strategy_t;
// io_k8s_api_apps_v1_rolling_update_stateful_set_strategy_t
typedef struct io_k8s_api_apps_v1_rolling_update_daemon_set_t v1_rolling_update_daemon_set_t;
// io_k8s_api_apps_v1_rolling_update_daemon_set_t
typedef struct io_k8s_api_apps_v1_deployment_spec_t v1_deployment_spec_t;
// io_k8s_api_apps_v1_deployment_spec_t
typedef struct io_k8s_api_apps_v1_deployment_strategy_t v1_deployment_strategy_t;
// io_k8s_api_apps_v1_deployment_strategy_t
typedef struct io_k8s_api_apps_v1_deployment_status_t v1_deployment_status_t;
// io_k8s_api_apps_v1_deployment_status_t
typedef struct io_k8s_api_apps_v1_deployment_condition_t v1_deployment_condition_t;
// io_k8s_api_apps_v1_deployment_condition_t
typedef struct io_k8s_api_apps_v1_daemon_set_spec_t v1_daemon_set_spec_t;
// io_k8s_api_apps_v1_daemon_set_spec_t
typedef struct io_k8s_api_apps_v1_daemon_set_status_t v1_daemon_set_status_t;
// io_k8s_api_apps_v1_daemon_set_status_t
typedef struct io_k8s_api_apps_v1_replica_set_spec_t v1_replica_set_spec_t;
// io_k8s_api_apps_v1_replica_set_spec_t
typedef struct io_k8s_api_apps_v1_daemon_set_update_strategy_t v1_daemon_set_update_strategy_t;
// io_k8s_api_apps_v1_daemon_set_update_strategy_t
typedef struct io_k8s_api_apps_v1_replica_set_condition_t v1_replica_set_condition_t;
// io_k8s_api_apps_v1_replica_set_condition_t
typedef struct io_k8s_api_apps_v1_replica_set_status_t v1_replica_set_status_t;
// io_k8s_api_apps_v1_replica_set_status_t
typedef struct io_k8s_api_apps_v1_stateful_set_condition_t v1_stateful_set_condition_t;
// io_k8s_api_apps_v1_stateful_set_condition_t
typedef struct io_k8s_api_apps_v1_rolling_update_deployment_t v1_rolling_update_deployment_t;
// io_k8s_api_apps_v1_rolling_update_deployment_t
typedef struct io_k8s_api_apps_v1_stateful_set_spec_t v1_stateful_set_spec_t;
// io_k8s_api_apps_v1_stateful_set_spec_t
typedef struct io_k8s_api_apps_v1_stateful_set_status_t v1_stateful_set_status_t;
// io_k8s_api_apps_v1_stateful_set_status_t
typedef struct io_k8s_api_apps_v1_daemon_set_condition_t v1_daemon_set_condition_t;
// io_k8s_api_apps_v1_daemon_set_condition_t
}
// authentication
namespace authentication {
typedef struct io_k8s_api_authentication_v1_token_review_t v1_token_review_t;
// io_k8s_api_authentication_v1_token_review_t
typedef struct io_k8s_api_authentication_v1_token_request_t v1_token_request_t;
// io_k8s_api_authentication_v1_token_request_t
typedef struct io_k8s_api_authentication_v1beta1_token_review_t v1beta1_token_review_t;
// io_k8s_api_authentication_v1beta1_token_review_t
typedef struct io_k8s_api_authentication_v1_token_review_spec_t v1_token_review_spec_t;
// io_k8s_api_authentication_v1_token_review_spec_t
typedef struct io_k8s_api_authentication_v1_token_review_status_t v1_token_review_status_t;
// io_k8s_api_authentication_v1_token_review_status_t
typedef struct io_k8s_api_authentication_v1_token_request_spec_t v1_token_request_spec_t;
// io_k8s_api_authentication_v1_token_request_spec_t
typedef struct io_k8s_api_authentication_v1_bound_object_reference_t v1_bound_object_reference_t;
// io_k8s_api_authentication_v1_bound_object_reference_t
typedef struct io_k8s_api_authentication_v1_user_info_t v1_user_info_t;
// io_k8s_api_authentication_v1_user_info_t
typedef struct io_k8s_api_authentication_v1beta1_token_review_status_t v1beta1_token_review_status_t;
// io_k8s_api_authentication_v1beta1_token_review_status_t
typedef struct io_k8s_api_authentication_v1beta1_user_info_t v1beta1_user_info_t;
// io_k8s_api_authentication_v1beta1_user_info_t
typedef struct io_k8s_api_authentication_v1_token_request_status_t v1_token_request_status_t;
// io_k8s_api_authentication_v1_token_request_status_t
typedef struct io_k8s_api_authentication_v1beta1_token_review_spec_t v1beta1_token_review_spec_t;
// io_k8s_api_authentication_v1beta1_token_review_spec_t
}
// autoscaling
namespace autoscaling {
typedef struct io_k8s_api_autoscaling_v1_horizontal_pod_autoscaler_t v1_horizontal_pod_autoscaler_t;
// io_k8s_api_autoscaling_v1_horizontal_pod_autoscaler_t
typedef struct io_k8s_api_autoscaling_v1_horizontal_pod_autoscaler_list_t v1_horizontal_pod_autoscaler_list_t;
// io_k8s_api_autoscaling_v1_horizontal_pod_autoscaler_list_t
typedef struct io_k8s_api_autoscaling_v2beta2_horizontal_pod_autoscaler_t v2beta2_horizontal_pod_autoscaler_t;
// io_k8s_api_autoscaling_v2beta2_horizontal_pod_autoscaler_t
typedef struct io_k8s_api_autoscaling_v2beta2_horizontal_pod_autoscaler_list_t v2beta2_horizontal_pod_autoscaler_list_t;
// io_k8s_api_autoscaling_v2beta2_horizontal_pod_autoscaler_list_t
typedef struct io_k8s_api_autoscaling_v1_scale_t v1_scale_t;
// io_k8s_api_autoscaling_v1_scale_t
typedef struct io_k8s_api_autoscaling_v2beta1_horizontal_pod_autoscaler_t v2beta1_horizontal_pod_autoscaler_t;
// io_k8s_api_autoscaling_v2beta1_horizontal_pod_autoscaler_t
typedef struct io_k8s_api_autoscaling_v2beta1_horizontal_pod_autoscaler_list_t v2beta1_horizontal_pod_autoscaler_list_t;
// io_k8s_api_autoscaling_v2beta1_horizontal_pod_autoscaler_list_t
typedef struct io_k8s_api_autoscaling_v2beta1_metric_spec_t v2beta1_metric_spec_t;
// io_k8s_api_autoscaling_v2beta1_metric_spec_t
typedef struct io_k8s_api_autoscaling_v2beta1_container_resource_metric_source_t v2beta1_container_resource_metric_source_t;
// io_k8s_api_autoscaling_v2beta1_container_resource_metric_source_t
typedef struct io_k8s_api_autoscaling_v2beta1_external_metric_source_t v2beta1_external_metric_source_t;
// io_k8s_api_autoscaling_v2beta1_external_metric_source_t
typedef struct io_k8s_api_autoscaling_v2beta1_object_metric_source_t v2beta1_object_metric_source_t;
// io_k8s_api_autoscaling_v2beta1_object_metric_source_t
typedef struct io_k8s_api_autoscaling_v2beta1_pods_metric_source_t v2beta1_pods_metric_source_t;
// io_k8s_api_autoscaling_v2beta1_pods_metric_source_t
typedef struct io_k8s_api_autoscaling_v2beta1_resource_metric_source_t v2beta1_resource_metric_source_t;
// io_k8s_api_autoscaling_v2beta1_resource_metric_source_t
typedef struct io_k8s_api_autoscaling_v1_horizontal_pod_autoscaler_status_t v1_horizontal_pod_autoscaler_status_t;
// io_k8s_api_autoscaling_v1_horizontal_pod_autoscaler_status_t
typedef struct io_k8s_api_autoscaling_v2beta1_resource_metric_status_t v2beta1_resource_metric_status_t;
// io_k8s_api_autoscaling_v2beta1_resource_metric_status_t
typedef struct io_k8s_api_autoscaling_v2beta2_horizontal_pod_autoscaler_condition_t v2beta2_horizontal_pod_autoscaler_condition_t;
// io_k8s_api_autoscaling_v2beta2_horizontal_pod_autoscaler_condition_t
typedef struct io_k8s_api_autoscaling_v2beta1_horizontal_pod_autoscaler_condition_t v2beta1_horizontal_pod_autoscaler_condition_t;
// io_k8s_api_autoscaling_v2beta1_horizontal_pod_autoscaler_condition_t
typedef struct io_k8s_api_autoscaling_v2beta1_horizontal_pod_autoscaler_status_t v2beta1_horizontal_pod_autoscaler_status_t;
// io_k8s_api_autoscaling_v2beta1_horizontal_pod_autoscaler_status_t
typedef struct io_k8s_api_autoscaling_v2beta2_metric_identifier_t v2beta2_metric_identifier_t;
// io_k8s_api_autoscaling_v2beta2_metric_identifier_t
typedef struct io_k8s_api_autoscaling_v2beta2_object_metric_source_t v2beta2_object_metric_source_t;
// io_k8s_api_autoscaling_v2beta2_object_metric_source_t
typedef struct io_k8s_api_autoscaling_v2beta2_cross_version_object_reference_t v2beta2_cross_version_object_reference_t;
// io_k8s_api_autoscaling_v2beta2_cross_version_object_reference_t
typedef struct io_k8s_api_autoscaling_v2beta2_metric_target_t v2beta2_metric_target_t;
// io_k8s_api_autoscaling_v2beta2_metric_target_t
typedef struct io_k8s_api_autoscaling_v2beta2_horizontal_pod_autoscaler_spec_t v2beta2_horizontal_pod_autoscaler_spec_t;
// io_k8s_api_autoscaling_v2beta2_horizontal_pod_autoscaler_spec_t
typedef struct io_k8s_api_autoscaling_v2beta2_horizontal_pod_autoscaler_behavior_t v2beta2_horizontal_pod_autoscaler_behavior_t;
// io_k8s_api_autoscaling_v2beta2_horizontal_pod_autoscaler_behavior_t
typedef struct io_k8s_api_autoscaling_v2beta1_external_metric_status_t v2beta1_external_metric_status_t;
// io_k8s_api_autoscaling_v2beta1_external_metric_status_t
typedef struct io_k8s_api_autoscaling_v2beta1_cross_version_object_reference_t v2beta1_cross_version_object_reference_t;
// io_k8s_api_autoscaling_v2beta1_cross_version_object_reference_t
typedef struct io_k8s_api_autoscaling_v1_scale_spec_t v1_scale_spec_t;
// io_k8s_api_autoscaling_v1_scale_spec_t
typedef struct io_k8s_api_autoscaling_v1_scale_status_t v1_scale_status_t;
// io_k8s_api_autoscaling_v1_scale_status_t
typedef struct io_k8s_api_autoscaling_v2beta2_metric_spec_t v2beta2_metric_spec_t;
// io_k8s_api_autoscaling_v2beta2_metric_spec_t
typedef struct io_k8s_api_autoscaling_v2beta2_container_resource_metric_source_t v2beta2_container_resource_metric_source_t;
// io_k8s_api_autoscaling_v2beta2_container_resource_metric_source_t
typedef struct io_k8s_api_autoscaling_v2beta2_external_metric_source_t v2beta2_external_metric_source_t;
// io_k8s_api_autoscaling_v2beta2_external_metric_source_t
typedef struct io_k8s_api_autoscaling_v2beta2_pods_metric_source_t v2beta2_pods_metric_source_t;
// io_k8s_api_autoscaling_v2beta2_pods_metric_source_t
typedef struct io_k8s_api_autoscaling_v2beta2_resource_metric_source_t v2beta2_resource_metric_source_t;
// io_k8s_api_autoscaling_v2beta2_resource_metric_source_t
typedef struct io_k8s_api_autoscaling_v2beta2_pods_metric_status_t v2beta2_pods_metric_status_t;
// io_k8s_api_autoscaling_v2beta2_pods_metric_status_t
typedef struct io_k8s_api_autoscaling_v2beta2_metric_value_status_t v2beta2_metric_value_status_t;
// io_k8s_api_autoscaling_v2beta2_metric_value_status_t
typedef struct io_k8s_api_autoscaling_v2beta1_object_metric_status_t v2beta1_object_metric_status_t;
// io_k8s_api_autoscaling_v2beta1_object_metric_status_t
typedef struct io_k8s_api_autoscaling_v2beta1_container_resource_metric_status_t v2beta1_container_resource_metric_status_t;
// io_k8s_api_autoscaling_v2beta1_container_resource_metric_status_t
typedef struct io_k8s_api_autoscaling_v2beta1_metric_status_t v2beta1_metric_status_t;
// io_k8s_api_autoscaling_v2beta1_metric_status_t
typedef struct io_k8s_api_autoscaling_v2beta1_pods_metric_status_t v2beta1_pods_metric_status_t;
// io_k8s_api_autoscaling_v2beta1_pods_metric_status_t
typedef struct io_k8s_api_autoscaling_v2beta2_horizontal_pod_autoscaler_status_t v2beta2_horizontal_pod_autoscaler_status_t;
// io_k8s_api_autoscaling_v2beta2_horizontal_pod_autoscaler_status_t
typedef struct io_k8s_api_autoscaling_v2beta2_object_metric_status_t v2beta2_object_metric_status_t;
// io_k8s_api_autoscaling_v2beta2_object_metric_status_t
typedef struct io_k8s_api_autoscaling_v1_horizontal_pod_autoscaler_spec_t v1_horizontal_pod_autoscaler_spec_t;
// io_k8s_api_autoscaling_v1_horizontal_pod_autoscaler_spec_t
typedef struct io_k8s_api_autoscaling_v2beta1_horizontal_pod_autoscaler_spec_t v2beta1_horizontal_pod_autoscaler_spec_t;
// io_k8s_api_autoscaling_v2beta1_horizontal_pod_autoscaler_spec_t
typedef struct io_k8s_api_autoscaling_v2beta2_hpa_scaling_rules_t v2beta2_hpa_scaling_rules_t;
// io_k8s_api_autoscaling_v2beta2_hpa_scaling_rules_t
typedef struct io_k8s_api_autoscaling_v2beta2_external_metric_status_t v2beta2_external_metric_status_t;
// io_k8s_api_autoscaling_v2beta2_external_metric_status_t
typedef struct io_k8s_api_autoscaling_v1_cross_version_object_reference_t v1_cross_version_object_reference_t;
// io_k8s_api_autoscaling_v1_cross_version_object_reference_t
typedef struct io_k8s_api_autoscaling_v2beta2_container_resource_metric_status_t v2beta2_container_resource_metric_status_t;
// io_k8s_api_autoscaling_v2beta2_container_resource_metric_status_t
typedef struct io_k8s_api_autoscaling_v2beta2_resource_metric_status_t v2beta2_resource_metric_status_t;
// io_k8s_api_autoscaling_v2beta2_resource_metric_status_t
typedef struct io_k8s_api_autoscaling_v2beta2_metric_status_t v2beta2_metric_status_t;
// io_k8s_api_autoscaling_v2beta2_metric_status_t
typedef struct io_k8s_api_autoscaling_v2beta2_hpa_scaling_policy_t v2beta2_hpa_scaling_policy_t;
// io_k8s_api_autoscaling_v2beta2_hpa_scaling_policy_t
}
// batch
namespace batch {
typedef struct io_k8s_api_batch_v1_job_t v1_job_t;
// io_k8s_api_batch_v1_job_t
typedef struct io_k8s_api_batch_v1_job_list_t v1_job_list_t;
// io_k8s_api_batch_v1_job_list_t
typedef struct io_k8s_api_batch_v1beta1_cron_job_t v1beta1_cron_job_t;
// io_k8s_api_batch_v1beta1_cron_job_t
typedef struct io_k8s_api_batch_v1beta1_cron_job_list_t v1beta1_cron_job_list_t;
// io_k8s_api_batch_v1beta1_cron_job_list_t
typedef struct io_k8s_api_batch_v1_job_condition_t v1_job_condition_t;
// io_k8s_api_batch_v1_job_condition_t
typedef struct io_k8s_api_batch_v1beta1_cron_job_status_t v1beta1_cron_job_status_t;
// io_k8s_api_batch_v1beta1_cron_job_status_t
typedef struct io_k8s_api_batch_v1_job_spec_t v1_job_spec_t;
// io_k8s_api_batch_v1_job_spec_t
typedef struct io_k8s_api_batch_v1_job_status_t v1_job_status_t;
// io_k8s_api_batch_v1_job_status_t
typedef struct io_k8s_api_batch_v1beta1_cron_job_spec_t v1beta1_cron_job_spec_t;
// io_k8s_api_batch_v1beta1_cron_job_spec_t
typedef struct io_k8s_api_batch_v1beta1_job_template_spec_t v1beta1_job_template_spec_t;
// io_k8s_api_batch_v1beta1_job_template_spec_t
}
// coordination
namespace coordination {
typedef struct io_k8s_api_coordination_v1beta1_lease_t v1beta1_lease_t;
// io_k8s_api_coordination_v1beta1_lease_t
typedef struct io_k8s_api_coordination_v1beta1_lease_list_t v1beta1_lease_list_t;
// io_k8s_api_coordination_v1beta1_lease_list_t
typedef struct io_k8s_api_coordination_v1_lease_t v1_lease_t;
// io_k8s_api_coordination_v1_lease_t
typedef struct io_k8s_api_coordination_v1_lease_list_t v1_lease_list_t;
// io_k8s_api_coordination_v1_lease_list_t
typedef struct io_k8s_api_coordination_v1_lease_spec_t v1_lease_spec_t;
// io_k8s_api_coordination_v1_lease_spec_t
typedef struct io_k8s_api_coordination_v1beta1_lease_spec_t v1beta1_lease_spec_t;
// io_k8s_api_coordination_v1beta1_lease_spec_t
}
// rbac
namespace rbac {
typedef struct io_k8s_api_rbac_v1alpha1_cluster_role_t v1alpha1_cluster_role_t;
// io_k8s_api_rbac_v1alpha1_cluster_role_t
typedef struct io_k8s_api_rbac_v1alpha1_cluster_role_binding_t v1alpha1_cluster_role_binding_t;
// io_k8s_api_rbac_v1alpha1_cluster_role_binding_t
typedef struct io_k8s_api_rbac_v1alpha1_role_t v1alpha1_role_t;
// io_k8s_api_rbac_v1alpha1_role_t
typedef struct io_k8s_api_rbac_v1alpha1_role_binding_t v1alpha1_role_binding_t;
// io_k8s_api_rbac_v1alpha1_role_binding_t
typedef struct io_k8s_api_rbac_v1alpha1_cluster_role_list_t v1alpha1_cluster_role_list_t;
// io_k8s_api_rbac_v1alpha1_cluster_role_list_t
typedef struct io_k8s_api_rbac_v1alpha1_cluster_role_binding_list_t v1alpha1_cluster_role_binding_list_t;
// io_k8s_api_rbac_v1alpha1_cluster_role_binding_list_t
typedef struct io_k8s_api_rbac_v1alpha1_role_list_t v1alpha1_role_list_t;
// io_k8s_api_rbac_v1alpha1_role_list_t
typedef struct io_k8s_api_rbac_v1alpha1_role_binding_list_t v1alpha1_role_binding_list_t;
// io_k8s_api_rbac_v1alpha1_role_binding_list_t
typedef struct io_k8s_api_rbac_v1_cluster_role_t v1_cluster_role_t;
// io_k8s_api_rbac_v1_cluster_role_t
typedef struct io_k8s_api_rbac_v1_cluster_role_binding_t v1_cluster_role_binding_t;
// io_k8s_api_rbac_v1_cluster_role_binding_t
typedef struct io_k8s_api_rbac_v1_role_t v1_role_t;
// io_k8s_api_rbac_v1_role_t
typedef struct io_k8s_api_rbac_v1_role_binding_t v1_role_binding_t;
// io_k8s_api_rbac_v1_role_binding_t
typedef struct io_k8s_api_rbac_v1_cluster_role_list_t v1_cluster_role_list_t;
// io_k8s_api_rbac_v1_cluster_role_list_t
typedef struct io_k8s_api_rbac_v1_cluster_role_binding_list_t v1_cluster_role_binding_list_t;
// io_k8s_api_rbac_v1_cluster_role_binding_list_t
typedef struct io_k8s_api_rbac_v1_role_list_t v1_role_list_t;
// io_k8s_api_rbac_v1_role_list_t
typedef struct io_k8s_api_rbac_v1_role_binding_list_t v1_role_binding_list_t;
// io_k8s_api_rbac_v1_role_binding_list_t
typedef struct io_k8s_api_rbac_v1beta1_cluster_role_t v1beta1_cluster_role_t;
// io_k8s_api_rbac_v1beta1_cluster_role_t
typedef struct io_k8s_api_rbac_v1beta1_cluster_role_binding_t v1beta1_cluster_role_binding_t;
// io_k8s_api_rbac_v1beta1_cluster_role_binding_t
typedef struct io_k8s_api_rbac_v1beta1_role_t v1beta1_role_t;
// io_k8s_api_rbac_v1beta1_role_t
typedef struct io_k8s_api_rbac_v1beta1_role_binding_t v1beta1_role_binding_t;
// io_k8s_api_rbac_v1beta1_role_binding_t
typedef struct io_k8s_api_rbac_v1beta1_cluster_role_list_t v1beta1_cluster_role_list_t;
// io_k8s_api_rbac_v1beta1_cluster_role_list_t
typedef struct io_k8s_api_rbac_v1beta1_cluster_role_binding_list_t v1beta1_cluster_role_binding_list_t;
// io_k8s_api_rbac_v1beta1_cluster_role_binding_list_t
typedef struct io_k8s_api_rbac_v1beta1_role_list_t v1beta1_role_list_t;
// io_k8s_api_rbac_v1beta1_role_list_t
typedef struct io_k8s_api_rbac_v1beta1_role_binding_list_t v1beta1_role_binding_list_t;
// io_k8s_api_rbac_v1beta1_role_binding_list_t
typedef struct io_k8s_api_rbac_v1beta1_aggregation_rule_t v1beta1_aggregation_rule_t;
// io_k8s_api_rbac_v1beta1_aggregation_rule_t
typedef struct io_k8s_api_rbac_v1alpha1_role_ref_t v1alpha1_role_ref_t;
// io_k8s_api_rbac_v1alpha1_role_ref_t
typedef struct io_k8s_api_rbac_v1beta1_role_ref_t v1beta1_role_ref_t;
// io_k8s_api_rbac_v1beta1_role_ref_t
typedef struct io_k8s_api_rbac_v1_aggregation_rule_t v1_aggregation_rule_t;
// io_k8s_api_rbac_v1_aggregation_rule_t
typedef struct io_k8s_api_rbac_v1_role_ref_t v1_role_ref_t;
// io_k8s_api_rbac_v1_role_ref_t
typedef struct io_k8s_api_rbac_v1beta1_subject_t v1beta1_subject_t;
// io_k8s_api_rbac_v1beta1_subject_t
typedef struct io_k8s_api_rbac_v1alpha1_aggregation_rule_t v1alpha1_aggregation_rule_t;
// io_k8s_api_rbac_v1alpha1_aggregation_rule_t
typedef struct io_k8s_api_rbac_v1alpha1_subject_t v1alpha1_subject_t;
// io_k8s_api_rbac_v1alpha1_subject_t
typedef struct io_k8s_api_rbac_v1beta1_policy_rule_t v1beta1_policy_rule_t;
// io_k8s_api_rbac_v1beta1_policy_rule_t
typedef struct io_k8s_api_rbac_v1_subject_t v1_subject_t;
// io_k8s_api_rbac_v1_subject_t
typedef struct io_k8s_api_rbac_v1alpha1_policy_rule_t v1alpha1_policy_rule_t;
// io_k8s_api_rbac_v1alpha1_policy_rule_t
typedef struct io_k8s_api_rbac_v1_policy_rule_t v1_policy_rule_t;
// io_k8s_api_rbac_v1_policy_rule_t
}
// admissionregistration
namespace admissionregistration {
typedef struct io_k8s_api_admissionregistration_v1beta1_mutating_webhook_configuration_t v1beta1_mutating_webhook_configuration_t;
// io_k8s_api_admissionregistration_v1beta1_mutating_webhook_configuration_t
typedef struct io_k8s_api_admissionregistration_v1beta1_validating_webhook_configuration_t v1beta1_validating_webhook_configuration_t;
// io_k8s_api_admissionregistration_v1beta1_validating_webhook_configuration_t
typedef struct io_k8s_api_admissionregistration_v1beta1_mutating_webhook_configuration_list_t v1beta1_mutating_webhook_configuration_list_t;
// io_k8s_api_admissionregistration_v1beta1_mutating_webhook_configuration_list_t
typedef struct io_k8s_api_admissionregistration_v1beta1_validating_webhook_configuration_list_t v1beta1_validating_webhook_configuration_list_t;
// io_k8s_api_admissionregistration_v1beta1_validating_webhook_configuration_list_t
typedef struct io_k8s_api_admissionregistration_v1_mutating_webhook_configuration_t v1_mutating_webhook_configuration_t;
// io_k8s_api_admissionregistration_v1_mutating_webhook_configuration_t
typedef struct io_k8s_api_admissionregistration_v1_validating_webhook_configuration_t v1_validating_webhook_configuration_t;
// io_k8s_api_admissionregistration_v1_validating_webhook_configuration_t
typedef struct io_k8s_api_admissionregistration_v1_mutating_webhook_configuration_list_t v1_mutating_webhook_configuration_list_t;
// io_k8s_api_admissionregistration_v1_mutating_webhook_configuration_list_t
typedef struct io_k8s_api_admissionregistration_v1_validating_webhook_configuration_list_t v1_validating_webhook_configuration_list_t;
// io_k8s_api_admissionregistration_v1_validating_webhook_configuration_list_t
typedef struct io_k8s_api_admissionregistration_v1_webhook_client_config_t v1_webhook_client_config_t;
// io_k8s_api_admissionregistration_v1_webhook_client_config_t
typedef struct io_k8s_api_admissionregistration_v1_service_reference_t v1_service_reference_t;
// io_k8s_api_admissionregistration_v1_service_reference_t
typedef struct io_k8s_api_admissionregistration_v1beta1_validating_webhook_t v1beta1_validating_webhook_t;
// io_k8s_api_admissionregistration_v1beta1_validating_webhook_t
typedef struct io_k8s_api_admissionregistration_v1beta1_webhook_client_config_t v1beta1_webhook_client_config_t;
// io_k8s_api_admissionregistration_v1beta1_webhook_client_config_t
typedef struct io_k8s_api_admissionregistration_v1beta1_mutating_webhook_t v1beta1_mutating_webhook_t;
// io_k8s_api_admissionregistration_v1beta1_mutating_webhook_t
typedef struct io_k8s_api_admissionregistration_v1beta1_service_reference_t v1beta1_service_reference_t;
// io_k8s_api_admissionregistration_v1beta1_service_reference_t
typedef struct io_k8s_api_admissionregistration_v1_validating_webhook_t v1_validating_webhook_t;
// io_k8s_api_admissionregistration_v1_validating_webhook_t
typedef struct io_k8s_api_admissionregistration_v1_rule_with_operations_t v1_rule_with_operations_t;
// io_k8s_api_admissionregistration_v1_rule_with_operations_t
typedef struct io_k8s_api_admissionregistration_v1_mutating_webhook_t v1_mutating_webhook_t;
// io_k8s_api_admissionregistration_v1_mutating_webhook_t
typedef struct io_k8s_api_admissionregistration_v1beta1_rule_with_operations_t v1beta1_rule_with_operations_t;
// io_k8s_api_admissionregistration_v1beta1_rule_with_operations_t
}
// apiserver
namespace apiserver {
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_definition_t pkg_apis_apiextensions_v1_custom_resource_definition_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_definition_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_definition_list_t pkg_apis_apiextensions_v1_custom_resource_definition_list_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_definition_list_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_definition_t pkg_apis_apiextensions_v1beta1_custom_resource_definition_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_definition_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_definition_list_t pkg_apis_apiextensions_v1beta1_custom_resource_definition_list_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_definition_list_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_service_reference_t pkg_apis_apiextensions_v1_service_reference_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_service_reference_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_definition_spec_t pkg_apis_apiextensions_v1beta1_custom_resource_definition_spec_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_definition_spec_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_conversion_t pkg_apis_apiextensions_v1beta1_custom_resource_conversion_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_conversion_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_definition_names_t pkg_apis_apiextensions_v1beta1_custom_resource_definition_names_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_definition_names_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_subresources_t pkg_apis_apiextensions_v1beta1_custom_resource_subresources_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_subresources_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_validation_t pkg_apis_apiextensions_v1beta1_custom_resource_validation_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_validation_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_webhook_conversion_t pkg_apis_apiextensions_v1_webhook_conversion_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_webhook_conversion_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_webhook_client_config_t pkg_apis_apiextensions_v1_webhook_client_config_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_webhook_client_config_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_service_reference_t pkg_apis_apiextensions_v1beta1_service_reference_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_service_reference_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_json_schema_props_t pkg_apis_apiextensions_v1beta1_json_schema_props_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_json_schema_props_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_validation_t pkg_apis_apiextensions_v1_custom_resource_validation_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_validation_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_json_schema_props_t pkg_apis_apiextensions_v1_json_schema_props_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_json_schema_props_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_definition_version_t pkg_apis_apiextensions_v1_custom_resource_definition_version_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_definition_version_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_subresources_t pkg_apis_apiextensions_v1_custom_resource_subresources_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_subresources_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_webhook_client_config_t pkg_apis_apiextensions_v1beta1_webhook_client_config_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_webhook_client_config_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_subresource_scale_t pkg_apis_apiextensions_v1_custom_resource_subresource_scale_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_subresource_scale_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_definition_status_t pkg_apis_apiextensions_v1_custom_resource_definition_status_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_definition_status_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_definition_names_t pkg_apis_apiextensions_v1_custom_resource_definition_names_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_definition_names_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_column_definition_t pkg_apis_apiextensions_v1_custom_resource_column_definition_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_column_definition_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_external_documentation_t pkg_apis_apiextensions_v1beta1_external_documentation_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_external_documentation_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_subresource_scale_t pkg_apis_apiextensions_v1beta1_custom_resource_subresource_scale_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_subresource_scale_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_definition_version_t pkg_apis_apiextensions_v1beta1_custom_resource_definition_version_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_definition_version_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_conversion_t pkg_apis_apiextensions_v1_custom_resource_conversion_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_conversion_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_definition_condition_t pkg_apis_apiextensions_v1_custom_resource_definition_condition_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_definition_condition_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_definition_status_t pkg_apis_apiextensions_v1beta1_custom_resource_definition_status_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_definition_status_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_definition_spec_t pkg_apis_apiextensions_v1_custom_resource_definition_spec_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_custom_resource_definition_spec_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_external_documentation_t pkg_apis_apiextensions_v1_external_documentation_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1_external_documentation_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_definition_condition_t pkg_apis_apiextensions_v1beta1_custom_resource_definition_condition_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_definition_condition_t
typedef struct io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_column_definition_t pkg_apis_apiextensions_v1beta1_custom_resource_column_definition_t;
// io_k8s_apiextensions_apiserver_pkg_apis_apiextensions_v1beta1_custom_resource_column_definition_t
}
// flowcontrol
namespace flowcontrol {
typedef struct io_k8s_api_flowcontrol_v1beta1_flow_schema_t v1beta1_flow_schema_t;
// io_k8s_api_flowcontrol_v1beta1_flow_schema_t
typedef struct io_k8s_api_flowcontrol_v1beta1_priority_level_configuration_t v1beta1_priority_level_configuration_t;
// io_k8s_api_flowcontrol_v1beta1_priority_level_configuration_t
typedef struct io_k8s_api_flowcontrol_v1beta1_flow_schema_list_t v1beta1_flow_schema_list_t;
// io_k8s_api_flowcontrol_v1beta1_flow_schema_list_t
typedef struct io_k8s_api_flowcontrol_v1beta1_priority_level_configuration_list_t v1beta1_priority_level_configuration_list_t;
// io_k8s_api_flowcontrol_v1beta1_priority_level_configuration_list_t
typedef struct io_k8s_api_flowcontrol_v1beta1_limit_response_t v1beta1_limit_response_t;
// io_k8s_api_flowcontrol_v1beta1_limit_response_t
typedef struct io_k8s_api_flowcontrol_v1beta1_queuing_configuration_t v1beta1_queuing_configuration_t;
// io_k8s_api_flowcontrol_v1beta1_queuing_configuration_t
typedef struct io_k8s_api_flowcontrol_v1beta1_non_resource_policy_rule_t v1beta1_non_resource_policy_rule_t;
// io_k8s_api_flowcontrol_v1beta1_non_resource_policy_rule_t
typedef struct io_k8s_api_flowcontrol_v1beta1_flow_schema_spec_t v1beta1_flow_schema_spec_t;
// io_k8s_api_flowcontrol_v1beta1_flow_schema_spec_t
typedef struct io_k8s_api_flowcontrol_v1beta1_flow_schema_status_t v1beta1_flow_schema_status_t;
// io_k8s_api_flowcontrol_v1beta1_flow_schema_status_t
typedef struct io_k8s_api_flowcontrol_v1beta1_priority_level_configuration_condition_t v1beta1_priority_level_configuration_condition_t;
// io_k8s_api_flowcontrol_v1beta1_priority_level_configuration_condition_t
typedef struct io_k8s_api_flowcontrol_v1beta1_service_account_subject_t v1beta1_service_account_subject_t;
// io_k8s_api_flowcontrol_v1beta1_service_account_subject_t
typedef struct io_k8s_api_flowcontrol_v1beta1_resource_policy_rule_t v1beta1_resource_policy_rule_t;
// io_k8s_api_flowcontrol_v1beta1_resource_policy_rule_t
typedef struct io_k8s_api_flowcontrol_v1beta1_group_subject_t v1beta1_group_subject_t;
// io_k8s_api_flowcontrol_v1beta1_group_subject_t
typedef struct io_k8s_api_flowcontrol_v1beta1_user_subject_t v1beta1_user_subject_t;
// io_k8s_api_flowcontrol_v1beta1_user_subject_t
typedef struct io_k8s_api_flowcontrol_v1beta1_flow_schema_condition_t v1beta1_flow_schema_condition_t;
// io_k8s_api_flowcontrol_v1beta1_flow_schema_condition_t
typedef struct io_k8s_api_flowcontrol_v1beta1_flow_distinguisher_method_t v1beta1_flow_distinguisher_method_t;
// io_k8s_api_flowcontrol_v1beta1_flow_distinguisher_method_t
typedef struct io_k8s_api_flowcontrol_v1beta1_priority_level_configuration_spec_t v1beta1_priority_level_configuration_spec_t;
// io_k8s_api_flowcontrol_v1beta1_priority_level_configuration_spec_t
typedef struct io_k8s_api_flowcontrol_v1beta1_priority_level_configuration_status_t v1beta1_priority_level_configuration_status_t;
// io_k8s_api_flowcontrol_v1beta1_priority_level_configuration_status_t
typedef struct io_k8s_api_flowcontrol_v1beta1_priority_level_configuration_reference_t v1beta1_priority_level_configuration_reference_t;
// io_k8s_api_flowcontrol_v1beta1_priority_level_configuration_reference_t
typedef struct io_k8s_api_flowcontrol_v1beta1_policy_rules_with_subjects_t v1beta1_policy_rules_with_subjects_t;
// io_k8s_api_flowcontrol_v1beta1_policy_rules_with_subjects_t
typedef struct io_k8s_api_flowcontrol_v1beta1_limited_priority_level_configuration_t v1beta1_limited_priority_level_configuration_t;
// io_k8s_api_flowcontrol_v1beta1_limited_priority_level_configuration_t
typedef struct io_k8s_api_flowcontrol_v1beta1_subject_t v1beta1_subject_t;;
// io_k8s_api_flowcontrol_v1beta1_subject_t
}
// pkg
namespace pkg {
typedef struct io_k8s_apimachinery_pkg_version_info_t version_info_t;
// io_k8s_apimachinery_pkg_version_info_t
}
// extensions
namespace extensions {
typedef struct io_k8s_api_extensions_v1beta1_ingress_t v1beta1_ingress_t;
// io_k8s_api_extensions_v1beta1_ingress_t
typedef struct io_k8s_api_extensions_v1beta1_ingress_list_t v1beta1_ingress_list_t;
// io_k8s_api_extensions_v1beta1_ingress_list_t
typedef struct io_k8s_api_extensions_v1beta1_ingress_tls_t v1beta1_ingress_tls_t;
// io_k8s_api_extensions_v1beta1_ingress_tls_t
typedef struct io_k8s_api_extensions_v1beta1_http_ingress_rule_value_t v1beta1_http_ingress_rule_value_t;
// io_k8s_api_extensions_v1beta1_http_ingress_rule_value_t
typedef struct io_k8s_api_extensions_v1beta1_http_ingress_path_t v1beta1_http_ingress_path_t;
// io_k8s_api_extensions_v1beta1_http_ingress_path_t
typedef struct io_k8s_api_extensions_v1beta1_ingress_backend_t v1beta1_ingress_backend_t;
// io_k8s_api_extensions_v1beta1_ingress_backend_t
typedef struct io_k8s_api_extensions_v1beta1_ingress_spec_t v1beta1_ingress_spec_t;
// io_k8s_api_extensions_v1beta1_ingress_spec_t
typedef struct io_k8s_api_extensions_v1beta1_ingress_rule_t v1beta1_ingress_rule_t;
// io_k8s_api_extensions_v1beta1_ingress_rule_t
typedef struct io_k8s_api_extensions_v1beta1_ingress_status_t v1beta1_ingress_status_t;
// io_k8s_api_extensions_v1beta1_ingress_status_t
}
// policy
namespace policy {
typedef struct io_k8s_api_policy_v1beta1_pod_disruption_budget_t v1beta1_pod_disruption_budget_t;
// io_k8s_api_policy_v1beta1_pod_disruption_budget_t
typedef struct io_k8s_api_policy_v1beta1_pod_security_policy_t v1beta1_pod_security_policy_t;
// io_k8s_api_policy_v1beta1_pod_security_policy_t
typedef struct io_k8s_api_policy_v1beta1_pod_disruption_budget_list_t v1beta1_pod_disruption_budget_list_t;
// io_k8s_api_policy_v1beta1_pod_disruption_budget_list_t
typedef struct io_k8s_api_policy_v1beta1_pod_security_policy_list_t v1beta1_pod_security_policy_list_t;
// io_k8s_api_policy_v1beta1_pod_security_policy_list_t
typedef struct io_k8s_api_policy_v1beta1_eviction_t v1beta1_eviction_t;
// io_k8s_api_policy_v1beta1_eviction_t
typedef struct io_k8s_api_policy_v1beta1_host_port_range_t v1beta1_host_port_range_t;
// io_k8s_api_policy_v1beta1_host_port_range_t
typedef struct io_k8s_api_policy_v1beta1_se_linux_strategy_options_t v1beta1_se_linux_strategy_options_t;
// io_k8s_api_policy_v1beta1_se_linux_strategy_options_t
typedef struct io_k8s_api_policy_v1beta1_allowed_csi_driver_t v1beta1_allowed_csi_driver_t;
// io_k8s_api_policy_v1beta1_allowed_csi_driver_t
typedef struct io_k8s_api_policy_v1beta1_runtime_class_strategy_options_t v1beta1_runtime_class_strategy_options_t;
// io_k8s_api_policy_v1beta1_runtime_class_strategy_options_t
typedef struct io_k8s_api_policy_v1beta1_pod_disruption_budget_spec_t v1beta1_pod_disruption_budget_spec_t;
// io_k8s_api_policy_v1beta1_pod_disruption_budget_spec_t
typedef struct io_k8s_api_policy_v1beta1_pod_disruption_budget_status_t v1beta1_pod_disruption_budget_status_t;
// io_k8s_api_policy_v1beta1_pod_disruption_budget_status_t
typedef struct io_k8s_api_policy_v1beta1_pod_security_policy_spec_t v1beta1_pod_security_policy_spec_t;
// io_k8s_api_policy_v1beta1_pod_security_policy_spec_t
typedef struct io_k8s_api_policy_v1beta1_fs_group_strategy_options_t v1beta1_fs_group_strategy_options_t;
// io_k8s_api_policy_v1beta1_fs_group_strategy_options_t
typedef struct io_k8s_api_policy_v1beta1_run_as_group_strategy_options_t v1beta1_run_as_group_strategy_options_t;
// io_k8s_api_policy_v1beta1_run_as_group_strategy_options_t
typedef struct io_k8s_api_policy_v1beta1_run_as_user_strategy_options_t v1beta1_run_as_user_strategy_options_t;
// io_k8s_api_policy_v1beta1_run_as_user_strategy_options_t
typedef struct io_k8s_api_policy_v1beta1_supplemental_groups_strategy_options_t v1beta1_supplemental_groups_strategy_options_t;
// io_k8s_api_policy_v1beta1_supplemental_groups_strategy_options_t
typedef struct io_k8s_api_policy_v1beta1_id_range_t v1beta1_id_range_t;
// io_k8s_api_policy_v1beta1_id_range_t
typedef struct io_k8s_api_policy_v1beta1_allowed_flex_volume_t v1beta1_allowed_flex_volume_t;
// io_k8s_api_policy_v1beta1_allowed_flex_volume_t
typedef struct io_k8s_api_policy_v1beta1_allowed_host_path_t v1beta1_allowed_host_path_t;
// io_k8s_api_policy_v1beta1_allowed_host_path_t
}
// discovery
namespace discovery {
typedef struct io_k8s_api_discovery_v1beta1_endpoint_slice_t v1beta1_endpoint_slice_t;
// io_k8s_api_discovery_v1beta1_endpoint_slice_t
typedef struct io_k8s_api_discovery_v1beta1_endpoint_slice_list_t v1beta1_endpoint_slice_list_t;
// io_k8s_api_discovery_v1beta1_endpoint_slice_list_t
typedef struct io_k8s_api_discovery_v1beta1_endpoint_t v1beta1_endpoint_t;
// io_k8s_api_discovery_v1beta1_endpoint_t
typedef struct io_k8s_api_discovery_v1beta1_endpoint_conditions_t v1beta1_endpoint_conditions_t;
// io_k8s_api_discovery_v1beta1_endpoint_conditions_t
typedef struct io_k8s_api_discovery_v1beta1_endpoint_port_t v1beta1_endpoint_port_t;
// io_k8s_api_discovery_v1beta1_endpoint_port_t
}
// storage
namespace storage {
typedef struct io_k8s_api_storage_v1beta1_csi_driver_t v1beta1_csi_driver_t;
// io_k8s_api_storage_v1beta1_csi_driver_t
typedef struct io_k8s_api_storage_v1beta1_csi_node_t v1beta1_csi_node_t;
// io_k8s_api_storage_v1beta1_csi_node_t
typedef struct io_k8s_api_storage_v1beta1_storage_class_t v1beta1_storage_class_t;
// io_k8s_api_storage_v1beta1_storage_class_t
typedef struct io_k8s_api_storage_v1beta1_volume_attachment_t v1beta1_volume_attachment_t;
// io_k8s_api_storage_v1beta1_volume_attachment_t
typedef struct io_k8s_api_storage_v1beta1_csi_driver_list_t v1beta1_csi_driver_list_t;
// io_k8s_api_storage_v1beta1_csi_driver_list_t
typedef struct io_k8s_api_storage_v1beta1_csi_node_list_t v1beta1_csi_node_list_t;
// io_k8s_api_storage_v1beta1_csi_node_list_t
typedef struct io_k8s_api_storage_v1beta1_storage_class_list_t v1beta1_storage_class_list_t;
// io_k8s_api_storage_v1beta1_storage_class_list_t
typedef struct io_k8s_api_storage_v1beta1_volume_attachment_list_t v1beta1_volume_attachment_list_t;
// io_k8s_api_storage_v1beta1_volume_attachment_list_t
typedef struct io_k8s_api_storage_v1alpha1_csi_storage_capacity_t v1alpha1_csi_storage_capacity_t;
// io_k8s_api_storage_v1alpha1_csi_storage_capacity_t
typedef struct io_k8s_api_storage_v1alpha1_volume_attachment_t v1alpha1_volume_attachment_t;
// io_k8s_api_storage_v1alpha1_volume_attachment_t
typedef struct io_k8s_api_storage_v1alpha1_csi_storage_capacity_list_t v1alpha1_csi_storage_capacity_list_t;
// io_k8s_api_storage_v1alpha1_csi_storage_capacity_list_t
typedef struct io_k8s_api_storage_v1alpha1_volume_attachment_list_t v1alpha1_volume_attachment_list_t;
// io_k8s_api_storage_v1alpha1_volume_attachment_list_t
typedef struct io_k8s_api_storage_v1_csi_driver_t v1_csi_driver_t;
// io_k8s_api_storage_v1_csi_driver_t
typedef struct io_k8s_api_storage_v1_csi_node_t v1_csi_node_t;
// io_k8s_api_storage_v1_csi_node_t
typedef struct io_k8s_api_storage_v1_storage_class_t v1_storage_class_t;
// io_k8s_api_storage_v1_storage_class_t
typedef struct io_k8s_api_storage_v1_volume_attachment_t v1_volume_attachment_t;
// io_k8s_api_storage_v1_volume_attachment_t
typedef struct io_k8s_api_storage_v1_csi_driver_list_t v1_csi_driver_list_t;
// io_k8s_api_storage_v1_csi_driver_list_t
typedef struct io_k8s_api_storage_v1_csi_node_list_t v1_csi_node_list_t;
// io_k8s_api_storage_v1_csi_node_list_t
typedef struct io_k8s_api_storage_v1_storage_class_list_t v1_storage_class_list_t;
// io_k8s_api_storage_v1_storage_class_list_t
typedef struct io_k8s_api_storage_v1_volume_attachment_list_t v1_volume_attachment_list_t;
// io_k8s_api_storage_v1_volume_attachment_list_t
typedef struct io_k8s_api_storage_v1_volume_attachment_spec_t v1_volume_attachment_spec_t;
// io_k8s_api_storage_v1_volume_attachment_spec_t
typedef struct io_k8s_api_storage_v1_volume_attachment_source_t v1_volume_attachment_source_t;
// io_k8s_api_storage_v1_volume_attachment_source_t
typedef struct io_k8s_api_storage_v1beta1_csi_driver_spec_t v1beta1_csi_driver_spec_t;
// io_k8s_api_storage_v1beta1_csi_driver_spec_t
typedef struct io_k8s_api_storage_v1beta1_volume_node_resources_t v1beta1_volume_node_resources_t;
// io_k8s_api_storage_v1beta1_volume_node_resources_t
typedef struct io_k8s_api_storage_v1beta1_volume_error_t v1beta1_volume_error_t;
// io_k8s_api_storage_v1beta1_volume_error_t
typedef struct io_k8s_api_storage_v1_csi_node_driver_t v1_csi_node_driver_t;
// io_k8s_api_storage_v1_csi_node_driver_t
typedef struct io_k8s_api_storage_v1_volume_node_resources_t v1_volume_node_resources_t;
// io_k8s_api_storage_v1_volume_node_resources_t
typedef struct io_k8s_api_storage_v1_csi_node_spec_t v1_csi_node_spec_t;
// io_k8s_api_storage_v1_csi_node_spec_t
typedef struct io_k8s_api_storage_v1_csi_driver_spec_t v1_csi_driver_spec_t;
// io_k8s_api_storage_v1_csi_driver_spec_t
typedef struct io_k8s_api_storage_v1beta1_csi_node_spec_t v1beta1_csi_node_spec_t;
// io_k8s_api_storage_v1beta1_csi_node_spec_t
typedef struct io_k8s_api_storage_v1alpha1_volume_attachment_status_t v1alpha1_volume_attachment_status_t;
// io_k8s_api_storage_v1alpha1_volume_attachment_status_t
typedef struct io_k8s_api_storage_v1alpha1_volume_error_t v1alpha1_volume_error_t;
// io_k8s_api_storage_v1alpha1_volume_error_t
typedef struct io_k8s_api_storage_v1_volume_error_t v1_volume_error_t;
// io_k8s_api_storage_v1_volume_error_t
typedef struct io_k8s_api_storage_v1beta1_volume_attachment_source_t v1beta1_volume_attachment_source_t;
// io_k8s_api_storage_v1beta1_volume_attachment_source_t
typedef struct io_k8s_api_storage_v1beta1_token_request_t v1beta1_token_request_t;
// io_k8s_api_storage_v1beta1_token_request_t
typedef struct io_k8s_api_storage_v1alpha1_volume_attachment_spec_t v1alpha1_volume_attachment_spec_t;
// io_k8s_api_storage_v1alpha1_volume_attachment_spec_t
typedef struct io_k8s_api_storage_v1_volume_attachment_status_t v1_volume_attachment_status_t;
// io_k8s_api_storage_v1_volume_attachment_status_t
typedef struct io_k8s_api_storage_v1alpha1_volume_attachment_source_t v1alpha1_volume_attachment_source_t;
// io_k8s_api_storage_v1alpha1_volume_attachment_source_t
typedef struct io_k8s_api_storage_v1beta1_csi_node_driver_t v1beta1_csi_node_driver_t;
// io_k8s_api_storage_v1beta1_csi_node_driver_t
typedef struct io_k8s_api_storage_v1beta1_volume_attachment_status_t v1beta1_volume_attachment_status_t;
// io_k8s_api_storage_v1beta1_volume_attachment_status_t
typedef struct io_k8s_api_storage_v1beta1_volume_attachment_spec_t v1beta1_volume_attachment_spec_t;
// io_k8s_api_storage_v1beta1_volume_attachment_spec_t
typedef struct io_k8s_api_storage_v1_token_request_t v1_token_request_t;;
// io_k8s_api_storage_v1_token_request_t
}
// networking
namespace networking {
typedef struct io_k8s_api_networking_v1beta1_ingress_class_t v1beta1_ingress_class_t;
// io_k8s_api_networking_v1beta1_ingress_class_t
typedef struct io_k8s_api_networking_v1beta1_ingress_class_list_t v1beta1_ingress_class_list_t;
// io_k8s_api_networking_v1beta1_ingress_class_list_t
typedef struct io_k8s_api_networking_v1_ingress_class_t v1_ingress_class_t;
// io_k8s_api_networking_v1_ingress_class_t
typedef struct io_k8s_api_networking_v1_ingress_t v1_ingress_t;
// io_k8s_api_networking_v1_ingress_t
typedef struct io_k8s_api_networking_v1_network_policy_t v1_network_policy_t;
// io_k8s_api_networking_v1_network_policy_t
typedef struct io_k8s_api_networking_v1_ingress_class_list_t v1_ingress_class_list_t;
// io_k8s_api_networking_v1_ingress_class_list_t
typedef struct io_k8s_api_networking_v1_ingress_list_t v1_ingress_list_t;
// io_k8s_api_networking_v1_ingress_list_t
typedef struct io_k8s_api_networking_v1_network_policy_list_t v1_network_policy_list_t;
// io_k8s_api_networking_v1_network_policy_list_t
typedef struct io_k8s_api_networking_v1_ingress_class_spec_t v1_ingress_class_spec_t;
// io_k8s_api_networking_v1_ingress_class_spec_t
typedef struct io_k8s_api_networking_v1_ingress_spec_t v1_ingress_spec_t;
// io_k8s_api_networking_v1_ingress_spec_t
typedef struct io_k8s_api_networking_v1_ingress_status_t v1_ingress_status_t;
// io_k8s_api_networking_v1_ingress_status_t
typedef struct io_k8s_api_networking_v1_network_policy_port_t v1_network_policy_port_t;
// io_k8s_api_networking_v1_network_policy_port_t
typedef struct io_k8s_api_networking_v1_ingress_service_backend_t v1_ingress_service_backend_t;
// io_k8s_api_networking_v1_ingress_service_backend_t
typedef struct io_k8s_api_networking_v1_service_backend_port_t v1_service_backend_port_t;
// io_k8s_api_networking_v1_service_backend_port_t
typedef struct io_k8s_api_networking_v1beta1_ingress_class_spec_t v1beta1_ingress_class_spec_t;
// io_k8s_api_networking_v1beta1_ingress_class_spec_t
typedef struct io_k8s_api_networking_v1_ingress_backend_t v1_ingress_backend_t;
// io_k8s_api_networking_v1_ingress_backend_t
typedef struct io_k8s_api_networking_v1_network_policy_peer_t v1_network_policy_peer_t;
// io_k8s_api_networking_v1_network_policy_peer_t
typedef struct io_k8s_api_networking_v1_ip_block_t v1_ip_block_t;
// io_k8s_api_networking_v1_ip_block_t
typedef struct io_k8s_api_networking_v1_network_policy_spec_t v1_network_policy_spec_t;
// io_k8s_api_networking_v1_network_policy_spec_t
typedef struct io_k8s_api_networking_v1_ingress_rule_t v1_ingress_rule_t;
// io_k8s_api_networking_v1_ingress_rule_t
typedef struct io_k8s_api_networking_v1_http_ingress_rule_value_t v1_http_ingress_rule_value_t;
// io_k8s_api_networking_v1_http_ingress_rule_value_t
typedef struct io_k8s_api_networking_v1_ingress_tls_t v1_ingress_tls_t;
// io_k8s_api_networking_v1_ingress_tls_t
typedef struct io_k8s_api_networking_v1_network_policy_egress_rule_t v1_network_policy_egress_rule_t;
// io_k8s_api_networking_v1_network_policy_egress_rule_t
typedef struct io_k8s_api_networking_v1_http_ingress_path_t v1_http_ingress_path_t;
// io_k8s_api_networking_v1_http_ingress_path_t
typedef struct io_k8s_api_networking_v1_network_policy_ingress_rule_t v1_network_policy_ingress_rule_t;
// io_k8s_api_networking_v1_network_policy_ingress_rule_t
typedef struct io_k8s_api_networking_v1beta1_ingress_backend_t v1beta1_ingress_backend_t;;
// io_k8s_api_networking_v1beta1_ingress_backend_t
typedef struct io_k8s_api_networking_v1beta1_ingress_rule_t v1beta1_ingress_rule_t;;
// io_k8s_api_networking_v1beta1_ingress_rule_t
typedef struct io_k8s_api_networking_v1beta1_ingress_status_t v1beta1_ingress_status_t;;
// io_k8s_api_networking_v1beta1_ingress_status_t
typedef struct io_k8s_api_networking_v1beta1_http_ingress_path_t v1beta1_http_ingress_path_t;;
// io_k8s_api_networking_v1beta1_http_ingress_path_t
typedef struct io_k8s_api_networking_v1beta1_ingress_spec_t v1beta1_ingress_spec_t;;
// io_k8s_api_networking_v1beta1_ingress_spec_t
typedef struct io_k8s_api_networking_v1beta1_ingress_tls_t v1beta1_ingress_tls_t;;
// io_k8s_api_networking_v1beta1_ingress_tls_t
typedef struct io_k8s_api_networking_v1beta1_ingress_t v1beta1_ingress_t;;
// io_k8s_api_networking_v1beta1_ingress_t
typedef struct io_k8s_api_networking_v1beta1_http_ingress_rule_value_t v1beta1_http_ingress_rule_value_t;;
// io_k8s_api_networking_v1beta1_http_ingress_rule_value_t
typedef struct io_k8s_api_networking_v1beta1_ingress_list_t v1beta1_ingress_list_t;;
// io_k8s_api_networking_v1beta1_ingress_list_t
}
}
}
#endif // ALIAS_H | 66.422758 | 186 | 0.935003 | zouxiaoliang |
96a3b765eb5f7343224730fff1913d50479d4139 | 1,042 | cpp | C++ | 19999/11054.cpp | rmagur1203/acmicpc | 83c4018548e42fc758b3858e8290990701e69e73 | [
"MIT"
] | null | null | null | 19999/11054.cpp | rmagur1203/acmicpc | 83c4018548e42fc758b3858e8290990701e69e73 | [
"MIT"
] | null | null | null | 19999/11054.cpp | rmagur1203/acmicpc | 83c4018548e42fc758b3858e8290990701e69e73 | [
"MIT"
] | 1 | 2022-01-11T05:03:52.000Z | 2022-01-11T05:03:52.000Z | #include <iostream>
#include <algorithm>
#define MAX 1001
using namespace std;
int arr[MAX];
int f_dp[MAX];
int b_dp[MAX];
int f_lis(int k)
{
if (k <= 0)
return 1;
if (f_dp[k] > 0)
return f_dp[k];
int mx = -1;
for (int i = k - 1; i >= 0; i--)
{
if (arr[i] < arr[k])
mx = max(mx, f_lis(i));
}
if (mx == -1)
f_dp[k] = 1;
else
f_dp[k] = mx + 1;
return f_dp[k];
}
int b_lis(int k, int n)
{
if (b_dp[k] > 0)
return b_dp[k];
int mx = -1;
for (int i = k + 1; i < n; i++)
{
if (arr[i] < arr[k])
mx = max(mx, b_lis(i, n));
}
if (mx == -1)
b_dp[k] = 1;
else
b_dp[k] = mx + 1;
return b_dp[k];
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
int mx = -1;
for (int i = 0; i < n; i++)
{
mx = max(mx, f_lis(i) + b_lis(i, n) - 1);
}
cout << mx;
} | 16.806452 | 49 | 0.415547 | rmagur1203 |
96a55515e63b554e7889792b81ca15583ee212b3 | 1,305 | cc | C++ | 445.Add-Two-Numbers-II/AddNumII.cc | stdbilly/leetcode | 752704ff99c21863bde4c929b7cc4fa18128cf39 | [
"MIT"
] | null | null | null | 445.Add-Two-Numbers-II/AddNumII.cc | stdbilly/leetcode | 752704ff99c21863bde4c929b7cc4fa18128cf39 | [
"MIT"
] | null | null | null | 445.Add-Two-Numbers-II/AddNumII.cc | stdbilly/leetcode | 752704ff99c21863bde4c929b7cc4fa18128cf39 | [
"MIT"
] | null | null | null | #include <stack>
#include "list/list.h"
using std::stack;
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
stack<int> s1, s2;
while (l1) {
s1.push(l1->val);
l1 = l1->next;
}
while (l2) {
s2.push(l2->val);
l2 = l2->next;
}
int carry = 0;
ListNode* cur = nullptr;
ListNode* pre = nullptr;
while (!s1.empty() || !s2.empty() || carry) {
int sum = carry;
if (!s1.empty()) {
sum += s1.top();
s1.pop();
}
if (!s2.empty()) {
sum += s2.top();
s2.pop();
}
carry = sum / 10;
pre = new ListNode(sum % 10);
pre->next = cur;
cur = pre;
}
return cur;
}
};
int main() {
Solution solution;
vector<int> arr1{7, 2, 4, 3};
vector<int> arr2{5, 6, 4};
ListNode* l1 = createLinkedList(arr1);
ListNode* l2 = createLinkedList(arr2);
printLinkedList(l1);
printLinkedList(l2);
ListNode* res = solution.addTwoNumbers(l1, l2);
printLinkedList(res);
destroyLinkedList(res);
destroyLinkedList(l1);
destroyLinkedList(l2);
return 0;
} | 24.166667 | 57 | 0.468966 | stdbilly |
96a713e91c76935a4ab020d15957b298d7e02cec | 1,190 | hpp | C++ | src/test/cpp/cn/edu/SUSTech/YeCanming/Judge/GTestExtensions.hpp | 2catycm/P_Algorithm_Design_and_Analysis_cpp | d1678d4db6f59a11215a8c790c2852bf9ad852dd | [
"MulanPSL-1.0"
] | null | null | null | src/test/cpp/cn/edu/SUSTech/YeCanming/Judge/GTestExtensions.hpp | 2catycm/P_Algorithm_Design_and_Analysis_cpp | d1678d4db6f59a11215a8c790c2852bf9ad852dd | [
"MulanPSL-1.0"
] | null | null | null | src/test/cpp/cn/edu/SUSTech/YeCanming/Judge/GTestExtensions.hpp | 2catycm/P_Algorithm_Design_and_Analysis_cpp | d1678d4db6f59a11215a8c790c2852bf9ad852dd | [
"MulanPSL-1.0"
] | null | null | null | #include <gtest/gtest.h>
#include <span>
#define EXPECT_MEMEQ(val1, val2, limit) \
if (0 != memcmp(val1, val2, limit)) { \
std::cout << "Expected: " << std::hex << std::uppercase << std::setfill('0'); \
for (const auto b : std::as_bytes(std::span{val1})) { \
std::cout << std::setw(2) << std::to_integer<unsigned>(b) << ' '; \
} \
std::cout << '\n'; \
std::cout << "Actually: " << std::hex << std::uppercase << std::setfill('0'); \
for (const auto b : std::as_bytes(std::span{val2})) { \
std::cout << std::setw(2) << std::to_integer<unsigned>(b) << ' '; \
} \
std::cout << '\n'; \
EXPECT_TRUE(false); \
} | 74.375 | 87 | 0.290756 | 2catycm |
96ab59e9195b9969d9f4be59ebe7ab4157bc8a37 | 2,027 | hpp | C++ | src/match.hpp | weibaohui/pipy | 14494f650fecc28410952c4c70f659f7b69b2c6a | [
"BSL-1.0"
] | null | null | null | src/match.hpp | weibaohui/pipy | 14494f650fecc28410952c4c70f659f7b69b2c6a | [
"BSL-1.0"
] | null | null | null | src/match.hpp | weibaohui/pipy | 14494f650fecc28410952c4c70f659f7b69b2c6a | [
"BSL-1.0"
] | null | null | null | /*
* Copyright (c) 2019 by flomesh.io
*
* Unless prior written consent has been obtained from the copyright
* owner, the following shall not be allowed.
*
* 1. The distribution of any source codes, header files, make files,
* or libraries of the software.
*
* 2. Disclosure of any source codes pertaining to the software to any
* additional parties.
*
* 3. Alteration or removal of any notices in or on the software or
* within the documentation included within the software.
*
* ALL SOURCE CODE AS WELL AS ALL DOCUMENTATION INCLUDED WITH THIS
* SOFTWARE IS PROVIDED IN AN “AS IS” CONDITION, WITHOUT WARRANTY OF ANY
* KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef MATCH_HPP
#define MATCH_HPP
#include "object.hpp"
#include <list>
#include <string>
#include <vector>
NS_BEGIN
//
// Match
//
class Match {
public:
Match();
Match(const std::string &path);
Match(const Match &other);
auto operator=(const Match &other) -> Match&;
bool is_root() const { return m_path.size() == 0; }
bool is_list() const { return !is_root() && m_path.back().is_array; }
bool is_map() const { return !is_root() && !m_path.back().is_array; }
auto key() const -> const std::string& { return m_path.back().key; }
bool matching() const { return m_matched == m_path.size(); }
void reset();
void process(const Object *obj);
private:
struct PathLevel {
bool is_array;
int index;
std::string key;
};
struct StackLevel {
bool is_array;
int index;
};
std::vector<PathLevel> m_path;
std::list<StackLevel> m_stack;
int m_matched = 0;
};
NS_END
#endif // MATCH_HPP
| 25.658228 | 77 | 0.693636 | weibaohui |
96ab99724a04c28c0f499d19bdae15f9d917c31b | 630 | cpp | C++ | src/0592_FractionAdditionandSubtraction/solution.cpp | hustzxd/leetcode | 83828602183e4709a6f20f163951e10b66f26935 | [
"MIT"
] | null | null | null | src/0592_FractionAdditionandSubtraction/solution.cpp | hustzxd/leetcode | 83828602183e4709a6f20f163951e10b66f26935 | [
"MIT"
] | null | null | null | src/0592_FractionAdditionandSubtraction/solution.cpp | hustzxd/leetcode | 83828602183e4709a6f20f163951e10b66f26935 | [
"MIT"
] | null | null | null | #include "../../include/solution.h"
class Solution {
public:
string fractionAddition(string expression) {
istringstream in(expression);
int a=0, b=1, c, d;
char _;
while (in >> c >> _ >> d) {
a = a * d + b * c;
b = b * d;
int g = abs(gcd(a, b));
a /= g;
b /= g;
}
return to_string(a) + '/' + to_string(b);
}
private:
int gcd(int a, int b) {
return a !=0 ? gcd(b % a, a) : b;
}
};
int main() {
string s;
while (cin >> s)
cout << Solution().fractionAddition(s) << endl;
return 0;
} | 20.322581 | 55 | 0.44127 | hustzxd |
96ad47916296749853a87e1cd3a4e43bade6f889 | 9,546 | cpp | C++ | Utilities/ftgl/src/FTVectoriser.cpp | Lin1225/vtk_v5.10.0 | b54ac74f4716572862365fbff28cd0ecb8d08c3d | [
"BSD-3-Clause"
] | 3 | 2020-06-20T23:31:06.000Z | 2021-01-11T02:17:16.000Z | Utilities/ftgl/src/FTVectoriser.cpp | Lin1225/vtk_v5.10.0 | b54ac74f4716572862365fbff28cd0ecb8d08c3d | [
"BSD-3-Clause"
] | 2 | 2015-06-19T07:24:42.000Z | 2015-06-19T13:39:01.000Z | Utilities/ftgl/src/FTVectoriser.cpp | Lin1225/vtk_v5.10.0 | b54ac74f4716572862365fbff28cd0ecb8d08c3d | [
"BSD-3-Clause"
] | 5 | 2015-03-23T21:13:19.000Z | 2022-01-03T11:15:39.000Z | #include "FTVectoriser.h"
#include "FTGL.h"
#ifdef FTGL_DEBUG
#include "mmgr.h"
#endif
#ifndef CALLBACK
#define CALLBACK
#endif
extern "C" {
typedef void (CALLBACK*ftglCallback)();
void CALLBACK ftglError( GLenum errCode, FTMesh* mesh)
{
mesh->Error( errCode);
}
void CALLBACK ftglVertex( void* data, FTMesh* mesh)
{
FTGL_DOUBLE* vertex = (FTGL_DOUBLE*)data;
mesh->AddPoint( vertex[0], vertex[1], vertex[2]);
}
void CALLBACK ftglBegin( GLenum type, FTMesh* mesh)
{
mesh->Begin( type);
}
void CALLBACK ftglEnd( FTMesh* mesh)
{
mesh->End();
}
void CALLBACK ftglCombine( FTGL_DOUBLE coords[3], void* , GLfloat*, void** outData, FTMesh* mesh)
{
FTGL_DOUBLE* vertex = (FTGL_DOUBLE*)coords;
mesh->tempPool.push_back( ftPoint( vertex[0], vertex[1], vertex[2]));
*outData = &mesh->tempPool[ mesh->tempPool.size() - 1].x;
}
} // End of extern C
#ifdef FTGL_USE_NAMESPACE
namespace ftgl
{
#endif
//=============================================================================
bool operator == ( const ftPoint &a, const ftPoint &b)
{
return((a.x == b.x) && (a.y == b.y) && (a.z == b.z));
}
bool operator != ( const ftPoint &a, const ftPoint &b)
{
return((a.x != b.x) || (a.y != b.y) || (a.z != b.z));
}
FTMesh::FTMesh()
: err(0)
{
tess.reserve( 16);
tempPool.reserve( 128);
}
FTMesh::~FTMesh()
{
for( size_t t = 0; t < tess.size(); ++t)
{
delete tess[t];
}
tess.clear();
tempPool.clear();
}
void FTMesh::AddPoint( const FTGL_DOUBLE x, const FTGL_DOUBLE y, const FTGL_DOUBLE z)
{
tempTess->AddPoint( x, y, z);
}
void FTMesh::Begin( GLenum m)
{
tempTess = new FTTesselation;
tempTess->meshType = m;
}
void FTMesh::End()
{
tess.push_back( tempTess);
}
FTGL_DOUBLE* FTMesh::Point()
{
return &tempTess->pointList[ tempTess->size() - 1].x;
}
int FTMesh::size() const
{
int s = 0;
for( size_t t = 0; t < tess.size(); ++t)
{
s += tess[t]->size();
++s;
}
return s;
}
//=============================================================================
FTVectoriser::FTVectoriser( const FT_Glyph glyph)
: contour(0),
mesh(0),
contourFlag(0),
kBSTEPSIZE( 0.2f)
{
FT_OutlineGlyph outline = (FT_OutlineGlyph)glyph;
ftOutline = outline->outline;
contourList.reserve( ftOutline.n_contours);
}
FTVectoriser::~FTVectoriser()
{
for( size_t c = 0; c < contours(); ++c)
{
delete contourList[c];
}
contourList.clear();
if( mesh)
delete mesh;
}
int FTVectoriser::points()
{
int s = 0;
for( size_t c = 0; c < contours(); ++c)
{
s += contourList[c]->size();
}
return s;
}
bool FTVectoriser::Process()
{
short first = 0;
short last;
const short cont = ftOutline.n_contours;
for( short c = 0; c < cont; ++c)
{
contour = new FTContour;
contourFlag = ftOutline.flags;
last = ftOutline.contours[c];
for( int p = first; p <= last; ++p)
{
switch( ftOutline.tags[p])
{
case FT_Curve_Tag_Conic:
p += Conic( p, first, last);
break;
case FT_Curve_Tag_Cubic:
p += Cubic( p, first, last);
break;
case FT_Curve_Tag_On:
default:
contour->AddPoint( ftOutline.points[p].x, ftOutline.points[p].y);
}
}
contourList.push_back( contour);
first = (short)(last + 1);
}
return true;
}
int FTVectoriser::Conic( const int index, const int first, const int last)
{
int next = index + 1;
int prev = index - 1;
if( index == last)
next = first;
if( index == first)
prev = last;
if( ftOutline.tags[next] != FT_Curve_Tag_Conic)
{
ctrlPtArray[0][0] = (float)ftOutline.points[prev].x;
ctrlPtArray[0][1] = (float)ftOutline.points[prev].y;
ctrlPtArray[1][0] = (float)ftOutline.points[index].x;
ctrlPtArray[1][1] = (float)ftOutline.points[index].y;
ctrlPtArray[2][0] = (float)ftOutline.points[next].x;
ctrlPtArray[2][1] = (float)ftOutline.points[next].y;
evaluateCurve( 2);
return 1;
}
else
{
int next2 = next + 1;
if( next == last)
next2 = first;
//create a phantom point
float x = (float)(ftOutline.points[index].x + ftOutline.points[next].x)/ 2;
float y = (float)(ftOutline.points[index].y + ftOutline.points[next].y)/ 2;
// process first curve
ctrlPtArray[0][0] = (float)ftOutline.points[prev].x;
ctrlPtArray[0][1] = (float)ftOutline.points[prev].y;
ctrlPtArray[1][0] = (float)ftOutline.points[index].x;
ctrlPtArray[1][1] = (float)ftOutline.points[index].y;
ctrlPtArray[2][0] = (float)x;
ctrlPtArray[2][1] = (float)y;
evaluateCurve( 2);
// process second curve
ctrlPtArray[0][0] = (float)x;
ctrlPtArray[0][1] = (float)y;
ctrlPtArray[1][0] = (float)ftOutline.points[next].x;
ctrlPtArray[1][1] = (float)ftOutline.points[next].y;
ctrlPtArray[2][0] = (float)ftOutline.points[next2].x;
ctrlPtArray[2][1] = (float)ftOutline.points[next2].y;
evaluateCurve( 2);
return 2;
}
}
int FTVectoriser::Cubic( const int index, const int first, const int last)
{
int next = index + 1;
int prev = index - 1;
if( index == last)
next = first;
int next2 = next + 1;
if( next == last)
next2 = first;
if( index == first)
prev = last;
ctrlPtArray[0][0] = (float)ftOutline.points[prev].x;
ctrlPtArray[0][1] = (float)ftOutline.points[prev].y;
ctrlPtArray[1][0] = (float)ftOutline.points[index].x;
ctrlPtArray[1][1] = (float)ftOutline.points[index].y;
ctrlPtArray[2][0] = (float)ftOutline.points[next].x;
ctrlPtArray[2][1] = (float)ftOutline.points[next].y;
ctrlPtArray[3][0] = (float)ftOutline.points[next2].x;
ctrlPtArray[3][1] = (float)ftOutline.points[next2].y;
evaluateCurve( 3);
return 2;
}
// De Casteljau algorithm contributed by Jed Soane
void FTVectoriser::deCasteljau( const float t, const int n)
{
//Calculating successive b(i)'s using de Casteljau algorithm.
for( int i = 1; i <= n; i++)
for( int k = 0; k <= (n - i); k++)
{
bValues[i][k][0] = (1 - t) * bValues[i - 1][k][0] + t * bValues[i - 1][k + 1][0];
bValues[i][k][1] = (1 - t) * bValues[i - 1][k][1] + t * bValues[i - 1][k + 1][1];
}
//Specify next vertex to be included on curve
contour->AddPoint( bValues[n][0][0], bValues[n][0][1]);
}
// De Casteljau algorithm contributed by Jed Soane
void FTVectoriser::evaluateCurve( const int n)
{
// setting the b(0) equal to the control points
for( int i = 0; i <= n; i++)
{
bValues[0][i][0] = ctrlPtArray[i][0];
bValues[0][i][1] = ctrlPtArray[i][1];
}
float t; //parameter for curve point calc. [0.0, 1.0]
for( int m = 0; m <= ( 1 / kBSTEPSIZE); m++)
{
t = m * kBSTEPSIZE;
deCasteljau( t, n); //calls to evaluate point on curve att.
}
}
void FTVectoriser::GetOutline( FTGL_DOUBLE* data)
{
int i = 0;
for( size_t c= 0; c < contours(); ++c)
{
const FTContour* acontour = contourList[c];
for( size_t p = 0; p < acontour->size(); ++p)
{
data[i] = static_cast<FTGL_DOUBLE>(acontour->pointList[p].x / 64.0f); // is 64 correct?
data[i + 1] = static_cast<FTGL_DOUBLE>(acontour->pointList[p].y / 64.0f);
data[i + 2] = 0.0; // static_cast<FTGL_DOUBLE>(acontour->pointList[p].z / 64.0f);
i += 3;
}
}
}
void FTVectoriser::MakeMesh( FTGL_DOUBLE zNormal)
{
if( mesh)
{
delete mesh;
}
mesh = new FTMesh;
GLUtesselator* tobj = gluNewTess();
gluTessCallback( tobj, GLU_TESS_BEGIN_DATA, (ftglCallback)ftglBegin);
gluTessCallback( tobj, GLU_TESS_VERTEX_DATA, (ftglCallback)ftglVertex);
gluTessCallback( tobj, GLU_TESS_COMBINE_DATA, (ftglCallback)ftglCombine);
gluTessCallback( tobj, GLU_TESS_END_DATA, (ftglCallback)ftglEnd);
gluTessCallback( tobj, GLU_TESS_ERROR_DATA, (ftglCallback)ftglError);
if( contourFlag & ft_outline_even_odd_fill) // ft_outline_reverse_fill
{
gluTessProperty( tobj, GLU_TESS_WINDING_RULE, GLU_TESS_WINDING_ODD);
}
else
{
gluTessProperty( tobj, GLU_TESS_WINDING_RULE, GLU_TESS_WINDING_NONZERO);
}
gluTessProperty( tobj, GLU_TESS_TOLERANCE, 0);
gluTessNormal( tobj, 0.0, 0.0, zNormal);
gluTessBeginPolygon( tobj, mesh);
for( size_t c = 0; c < contours(); ++c)
{
const FTContour* acontour = contourList[c];
gluTessBeginContour( tobj);
for( size_t p = 0; p < acontour->size(); ++p)
{
FTGL_DOUBLE* d = const_cast<FTGL_DOUBLE*>(&acontour->pointList[p].x);
gluTessVertex( tobj, d, d);
}
gluTessEndContour( tobj);
}
gluTessEndPolygon( tobj);
gluDeleteTess( tobj);
}
void FTVectoriser::GetMesh( FTGL_DOUBLE* data)
{
// Now write it out
int i = 0;
// fill out the header
size_t msize = mesh->tess.size();
data[0] = msize;
for( int p = 0; p < data[0]; ++p)
{
FTTesselation* tess = mesh->tess[p];
size_t tSize = tess->pointList.size();
int tType = tess->meshType;
data[i+1] = tType;
data[i+2] = tSize;
i += 3;
for( size_t q = 0; q < ( tess->pointList.size()); ++q)
{
data[i] = tess->pointList[q].x / 64.0f; // is 64 correct?
data[i + 1] = tess->pointList[q].y / 64.0f;
data[i + 2] = 0.0; // static_cast<FTGL_DOUBLE>(mesh->pointList[p].z / 64.0f);
i += 3;
}
}
}
#ifdef FTGL_USE_NAMESPACE
} // namespace ftgl
#endif
| 22.148492 | 97 | 0.589357 | Lin1225 |
96bacdbe3160a6594e226f92f48e771148e930cc | 1,772 | cpp | C++ | galaxy/src/galaxy/core/Config.cpp | reworks/rework | 90508252c9a4c77e45a38e7ce63cfd99f533f42b | [
"Apache-2.0"
] | 6 | 2018-07-21T20:37:01.000Z | 2018-10-31T01:49:35.000Z | galaxy/src/galaxy/core/Config.cpp | reworks/rework | 90508252c9a4c77e45a38e7ce63cfd99f533f42b | [
"Apache-2.0"
] | null | null | null | galaxy/src/galaxy/core/Config.cpp | reworks/rework | 90508252c9a4c77e45a38e7ce63cfd99f533f42b | [
"Apache-2.0"
] | null | null | null | ///
/// Config.cpp
/// galaxy
///
/// Refer to LICENSE.txt for more details.
///
#include <fstream>
#include "Config.hpp"
namespace galaxy
{
namespace core
{
Config::Config() noexcept
: m_loaded {false}
{
m_config = "{\"config\":{}}"_json;
}
Config::Config(std::string_view file)
: m_loaded {false}
{
m_config = "{\"config\":{}}"_json;
load(file);
}
Config::~Config() noexcept
{
m_loaded = false;
m_config.clear();
}
void Config::load(std::string_view file)
{
auto path = std::filesystem::path(file);
m_path = path.string();
if (!std::filesystem::exists(path))
{
std::ofstream ofs {m_path, std::ofstream::out | std::ofstream::trunc};
if (ofs.good())
{
ofs << m_config.dump(4);
ofs.close();
}
else
{
ofs.close();
GALAXY_LOG(GALAXY_FATAL, "Failed to save config file to disk.");
}
}
else
{
std::ifstream input {m_path, std::ifstream::in};
if (!input.good())
{
input.close();
GALAXY_LOG(GALAXY_FATAL, "Failed to load config file.");
}
else
{
input >> m_config;
input.close();
m_loaded = true;
}
}
}
void Config::save()
{
if (m_loaded)
{
std::ofstream ofs {m_path, std::ofstream::out | std::ofstream::trunc};
if (ofs.good())
{
ofs << m_config.dump(4);
ofs.close();
}
else
{
ofs.close();
GALAXY_LOG(GALAXY_ERROR, "Failed to save config file to disk.");
}
}
else
{
GALAXY_LOG(GALAXY_WARNING, "Attempted to save config that was not loaded.");
}
}
bool Config::empty() noexcept
{
if (m_loaded)
{
return m_config.at("config").empty();
}
return true;
}
} // namespace core
} // namespace galaxy | 16.560748 | 80 | 0.560948 | reworks |
96bd074058fbaa114c758fc21664a2551ff6bccf | 1,210 | hpp | C++ | aslam_cv/aslam_cameras/include/aslam/implementation/utilities.hpp | PushyamiKaveti/kalibr | d8bdfc59ee666ef854012becc93571f96fe5d80c | [
"BSD-4-Clause"
] | 2,690 | 2015-01-07T03:50:23.000Z | 2022-03-31T20:27:01.000Z | aslam_cv/aslam_cameras/include/aslam/implementation/utilities.hpp | PushyamiKaveti/kalibr | d8bdfc59ee666ef854012becc93571f96fe5d80c | [
"BSD-4-Clause"
] | 481 | 2015-01-27T10:21:00.000Z | 2022-03-31T14:02:41.000Z | aslam_cv/aslam_cameras/include/aslam/implementation/utilities.hpp | PushyamiKaveti/kalibr | d8bdfc59ee666ef854012becc93571f96fe5d80c | [
"BSD-4-Clause"
] | 1,091 | 2015-01-26T21:21:13.000Z | 2022-03-30T01:55:33.000Z | namespace aslam {
template<typename FRAME_T>
void doBackProjection(FRAME_T & frame) {
typedef FRAME_T frame_t;
typedef typename frame_t::keypoint_t keypoint_t;
typedef typename frame_t::camera_geometry_t camera_geometry_t;
const camera_geometry_t & geometry = frame.geometry();
for (size_t k = 0; k < frame.numKeypoints(); ++k) {
keypoint_t & kp = frame[k];
Eigen::Vector3d bp(0.0, 0.0, 0.0);
geometry.keypointToEuclidean(kp.y(), bp);
bp.normalize();
kp.setBackProjection(bp);
}
}
template<typename FRAME_T>
void doBackProjectionWithUncertainty(FRAME_T & frame) {
typedef FRAME_T frame_t;
typedef typename frame_t::keypoint_t keypoint_t;
typedef typename frame_t::camera_geometry_t camera_geometry_t;
const camera_geometry_t & geometry = frame.geometry();
for (size_t k = 0; k < frame.numKeypoints(); ++k) {
keypoint_t & kp = frame[k];
Eigen::Vector3d bp;
typename camera_geometry_t::inverse_jacobian_t Jb;
geometry.keypointToEuclidean(kp.y(), bp, Jb);
Eigen::Matrix3d P = Jb * kp.invR().inverse() * Jb.transpose();
sm::kinematics::UncertainVector3 b(bp, P);
b.normalize();
kp.setBackProjection(b);
}
}
} // namespace aslam
| 28.139535 | 66 | 0.705785 | PushyamiKaveti |
96c032133b7b1c4038487c6ad81795b9b18f9eee | 1,570 | cpp | C++ | src/tests/world_assertions.cpp | fairlight1337/GDAPlanner | c39d4e8fdcb0bbf18ff9e646349161853943dd5e | [
"BSD-2-Clause"
] | null | null | null | src/tests/world_assertions.cpp | fairlight1337/GDAPlanner | c39d4e8fdcb0bbf18ff9e646349161853943dd5e | [
"BSD-2-Clause"
] | null | null | null | src/tests/world_assertions.cpp | fairlight1337/GDAPlanner | c39d4e8fdcb0bbf18ff9e646349161853943dd5e | [
"BSD-2-Clause"
] | null | null | null | #include <iostream>
#include <cstdlib>
#include <string>
#include <gdaplanner/GDAPlanner.h>
using namespace gdaplanner;
int main(__attribute__((unused)) int argc, __attribute__((unused)) char** argv) {
int nReturnvalue = EXIT_FAILURE;
World::Ptr wdWorld = World::create();
Expression exA = Expression::parseSingle("(table-set table-1");
if(wdWorld->holds(exA).size() == 0) {
if(wdWorld->assertFact(exA)) {
if(wdWorld->holds(exA).size() == 1) {
wdWorld->retractFact(exA);
if(wdWorld->holds(exA).size() == 0) {
Expression exB = Expression::parseSingle("(table-set table-2");
Expression exC = Expression::parseSingle("(table-set ?a)");
if(wdWorld->assertFact(exA) && wdWorld->assertFact(exB)) {
std::vector<std::map<std::string, Expression>> vecHolds = wdWorld->holds(exC);
if(vecHolds.size() > 0) {
bool bA = false, bB = false;
for(std::map<std::string, Expression> mapHolds : vecHolds) {
if(mapHolds["?a"] == "table-1") {
bA = true;
} else if(mapHolds["?a"] == "table-2") {
bB = true;
}
}
if(bA && bB) {
wdWorld->retractFact(exA);
if(wdWorld->holds(exC).size() == 1) {
wdWorld->retractFact(exC);
if(wdWorld->holds(exC).size() == 0) {
if(wdWorld->assertFact(exA) && wdWorld->assertFact(exB)) {
wdWorld->retractFact(exC, 0, true);
if(wdWorld->holds(exC).size() == 2) {
nReturnvalue = EXIT_SUCCESS;
}
}
}
}
}
}
}
}
}
}
}
return nReturnvalue;
}
| 23.432836 | 83 | 0.576433 | fairlight1337 |
96c19a8b815f0da1e1ea7a54f5aedaf68c587d95 | 2,059 | cpp | C++ | XJ Contests/2021/1.2/T2/me.cpp | jinzhengyu1212/Clovers | 0efbb0d87b5c035e548103409c67914a1f776752 | [
"MIT"
] | null | null | null | XJ Contests/2021/1.2/T2/me.cpp | jinzhengyu1212/Clovers | 0efbb0d87b5c035e548103409c67914a1f776752 | [
"MIT"
] | null | null | null | XJ Contests/2021/1.2/T2/me.cpp | jinzhengyu1212/Clovers | 0efbb0d87b5c035e548103409c67914a1f776752 | [
"MIT"
] | null | null | null | /*
the vast starry sky,
bright for those who chase the light.
*/
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
#define mk make_pair
const int inf=(int)1e9;
const ll INF=(ll)5e18;
const int MOD=998244353;
int _abs(int x){return x<0 ? -x : x;}
int add(int x,int y){x+=y; return x>=MOD ? x-MOD : x;}
int sub(int x,int y){x-=y; return x<0 ? x+MOD : x;}
#define mul(x,y) (ll)(x)*(y)%MOD
void Add(int &x,int y){x+=y; if(x>=MOD) x-=MOD;}
void Sub(int &x,int y){x-=y; if(x<0) x+=MOD;}
void Mul(int &x,int y){x=mul(x,y);}
int qpow(int x,int y){int ret=1; while(y){if(y&1) ret=mul(ret,x); x=mul(x,x); y>>=1;} return ret;}
void checkmin(int &x,int y){if(x>y) x=y;}
void checkmax(int &x,int y){if(x<y) x=y;}
void checkmin(ll &x,ll y){if(x>y) x=y;}
void checkmax(ll &x,ll y){if(x<y) x=y;}
#define out(x) cerr<<#x<<'='<<x<<' '
#define outln(x) cerr<<#x<<'='<<x<<endl
#define sz(x) (int)(x).size()
inline int read(){
int x=0,f=1; char c=getchar();
while(c>'9'||c<'0'){if(c=='-') f=-1; c=getchar();}
while(c>='0'&&c<='9') x=(x<<1)+(x<<3)+(c^48),c=getchar();
return x*f;
}
const int N=1005;
int n,dp[N][N],match[N],a[N],top=0,vis[N],tmp[N];
void init(){
n=read(); top=0;
memset(vis,0,sizeof(vis));
for(int i=1;i<=n;i++) tmp[i]=read();
for(int i=1;i<=n;i++){
int x=read();
match[tmp[i]]=x;
}
for(int i=1;i<=n;i++){
if(vis[i]) continue;
int x=match[i],len=1; top++;
while(x!=i){
len++;
vis[x]=1;
x=match[x];
}
a[top]=len; vis[i]=1;
}
}
void solve(){
int ans=0;
for(int i=1;i<=n;i++) if(match[i]==i) ans++;
for(int l=2;l<=n;l++){
dp[l][l]=l-1;
for(int i=l+1;i<=n;i++){
dp[l][i]=max(dp[l][i-l]+l-1,dp[l][i-l-1]+l);
}
int sum=0;
for(int i=1;i<=top;i++) sum+=dp[l][a[i]];
checkmax(ans,sum);
}
printf("%d\n",ans);
}
int main()
{
int T=read();
while(T--){
init();
solve();
}
return 0;
} | 26.063291 | 98 | 0.504614 | jinzhengyu1212 |
96c43e87f29f8126f14efbbf8ceec6a03312e5c2 | 6,625 | cpp | C++ | check/TestFreezeBasis.cpp | chrhansk/HiGHS | 311aa8571925ed23c952687569dbe7207e542e0a | [
"MIT"
] | 3 | 2019-04-17T11:34:07.000Z | 2021-05-21T05:56:42.000Z | check/TestFreezeBasis.cpp | chrhansk/HiGHS | 311aa8571925ed23c952687569dbe7207e542e0a | [
"MIT"
] | 17 | 2020-03-30T19:16:59.000Z | 2020-12-15T01:01:42.000Z | check/TestFreezeBasis.cpp | chrhansk/HiGHS | 311aa8571925ed23c952687569dbe7207e542e0a | [
"MIT"
] | 1 | 2022-02-08T19:30:43.000Z | 2022-02-08T19:30:43.000Z | #include "Highs.h"
#include "catch.hpp"
const double inf = kHighsInf;
const bool dev_run = false;
const double double_equal_tolerance = 1e-5;
TEST_CASE("FreezeBasis", "[highs_test_freeze_basis]") {
std::string filename;
filename = std::string(HIGHS_DIR) + "/check/instances/avgas.mps";
Highs highs;
if (!dev_run) highs.setOptionValue("output_flag", false);
highs.readModel(filename);
const HighsLp& lp = highs.getLp();
const HighsInt num_col = lp.num_col_;
const HighsInt num_row = lp.num_row_;
const HighsInt from_col = 0;
const HighsInt to_col = num_col - 1;
const HighsInfo& info = highs.getInfo();
vector<double> original_col_lower = lp.col_lower_;
vector<double> original_col_upper = lp.col_upper_;
// Get the continuous solution and iteration count from a logical basis
highs.run();
HighsInt continuous_iteration_count = info.simplex_iteration_count;
double continuous_objective = info.objective_function_value;
// Get the integer solution to provide bound tightenings
vector<HighsVarType> integrality;
integrality.assign(num_col, HighsVarType::kInteger);
highs.changeColsIntegrality(from_col, to_col, &integrality[0]);
highs.setOptionValue("output_flag", false);
highs.run();
if (dev_run) highs.setOptionValue("output_flag", true);
vector<double> integer_solution = highs.getSolution().col_value;
vector<double> local_col_lower;
vector<double> local_col_upper;
// Now restore the original integrality and set an explicit logical
// basis to force reinversion
integrality.assign(num_col, HighsVarType::kContinuous);
highs.changeColsIntegrality(from_col, to_col, &integrality[0]);
HighsBasis basis;
for (HighsInt iCol = 0; iCol < num_col; iCol++)
basis.col_status.push_back(HighsBasisStatus::kLower);
for (HighsInt iRow = 0; iRow < num_row; iRow++)
basis.row_status.push_back(HighsBasisStatus::kBasic);
highs.setBasis(basis);
HighsInt frozen_basis_id0;
// Cannot freeze a basis when there's no INVERT
REQUIRE(highs.freezeBasis(frozen_basis_id0) == HighsStatus::kError);
// Get the basic variables to force INVERT with a logical basis
vector<HighsInt> basic_variables;
basic_variables.resize(lp.num_row_);
highs.getBasicVariables(&basic_variables[0]);
// Can freeze a basis now!
REQUIRE(highs.freezeBasis(frozen_basis_id0) == HighsStatus::kOk);
if (dev_run) {
highs.setOptionValue("output_flag", true);
highs.setOptionValue("log_dev_level", 2);
highs.setOptionValue("highs_debug_level", 3);
}
highs.run();
// highs.setOptionValue("output_flag", false);
// Now freeze the current basis and add the integer solution as lower bounds
HighsInt frozen_basis_id1;
REQUIRE(highs.freezeBasis(frozen_basis_id1) == HighsStatus::kOk);
if (dev_run) printf("\nSolving with bounds (integer solution, upper)\n");
local_col_lower = integer_solution;
local_col_upper = original_col_upper;
highs.changeColsBounds(from_col, to_col, &local_col_lower[0],
&local_col_upper[0]);
if (dev_run) highs.setOptionValue("output_flag", true);
highs.run();
// highs.setOptionValue("output_flag", false);
double semi_continuous_objective = info.objective_function_value;
// Now freeze the current basis and add the integer solution as upper bounds
HighsInt frozen_basis_id2;
REQUIRE(highs.freezeBasis(frozen_basis_id2) == HighsStatus::kOk);
if (dev_run)
printf("\nSolving with bounds (integer solution, integer solution)\n");
local_col_lower = integer_solution;
local_col_upper = integer_solution;
highs.changeColsBounds(from_col, to_col, &local_col_lower[0],
&local_col_upper[0]);
if (dev_run) highs.setOptionValue("output_flag", true);
highs.run();
// highs.setOptionValue("output_flag", false);
// Now test unfreeze
//
// Restore the upper bounds and unfreeze frozen_basis_id2 (semi-continuous
// optimal basis)
if (dev_run)
printf(
"\nSolving with bounds (integer solution, upper) after unfreezing "
"basis %d\n",
(int)frozen_basis_id2);
if (dev_run) printf("Change column bounds to (integer solution, upper)\n");
local_col_lower = integer_solution;
local_col_upper = original_col_upper;
highs.changeColsBounds(from_col, to_col, &local_col_lower[0],
&local_col_upper[0]);
if (dev_run) printf("Unfreeze basis %d\n", (int)frozen_basis_id2);
REQUIRE(highs.unfreezeBasis(frozen_basis_id2) == HighsStatus::kOk);
// Solving the LP should require no iterations
if (dev_run) highs.setOptionValue("output_flag", true);
highs.run();
// highs.setOptionValue("output_flag", false);
REQUIRE(info.simplex_iteration_count == 0);
double dl_objective =
fabs(semi_continuous_objective - info.objective_function_value);
REQUIRE(dl_objective < double_equal_tolerance);
REQUIRE(info.simplex_iteration_count == 0);
//
// Restore the lower bounds and unfreeze frozen_basis_id1 (continuous optimal
// basis)
if (dev_run)
printf("\nSolving with bounds (lower, upper) after unfreezing basis %d\n",
(int)frozen_basis_id1);
if (dev_run) printf("Change column bounds to (lower, upper)\n");
local_col_lower = original_col_lower;
local_col_upper = original_col_upper;
highs.changeColsBounds(from_col, to_col, &local_col_lower[0],
&local_col_upper[0]);
if (dev_run) printf("Unfreeze basis %d\n", (int)frozen_basis_id1);
REQUIRE(highs.unfreezeBasis(frozen_basis_id1) == HighsStatus::kOk);
// Solving the LP should require no iterations
if (dev_run) highs.setOptionValue("output_flag", true);
highs.run();
// highs.setOptionValue("output_flag", false);
dl_objective = fabs(continuous_objective - info.objective_function_value);
REQUIRE(dl_objective < double_equal_tolerance);
REQUIRE(info.simplex_iteration_count == 0);
//
// Unfreeze frozen_basis_id0
if (dev_run)
printf("\nSolving with bounds (lower, upper) after unfreezing basis %d\n",
(int)frozen_basis_id0);
if (dev_run) printf("Unfreeze basis %d\n", (int)frozen_basis_id0);
REQUIRE(highs.unfreezeBasis(frozen_basis_id0) == HighsStatus::kOk);
// Solving the LP should require the same number of iterations as before
if (dev_run) highs.setOptionValue("output_flag", true);
highs.run();
// highs.setOptionValue("output_flag", false);
dl_objective = fabs(continuous_objective - info.objective_function_value);
REQUIRE(dl_objective < double_equal_tolerance);
REQUIRE(info.simplex_iteration_count == continuous_iteration_count);
REQUIRE(highs.frozenBasisAllDataClear() == HighsStatus::kOk);
}
| 40.895062 | 79 | 0.736151 | chrhansk |
96c53110064be6f4400cd9f3fd1c77f3f79af362 | 82,078 | cpp | C++ | src/test/dict_test/dict_test.cpp | shines77/jstd | a9fe267ac692162af53e16515a3552b45b6fd55a | [
"MIT"
] | null | null | null | src/test/dict_test/dict_test.cpp | shines77/jstd | a9fe267ac692162af53e16515a3552b45b6fd55a | [
"MIT"
] | null | null | null | src/test/dict_test/dict_test.cpp | shines77/jstd | a9fe267ac692162af53e16515a3552b45b6fd55a | [
"MIT"
] | 1 | 2021-06-21T12:33:06.000Z | 2021-06-21T12:33:06.000Z |
#ifdef _MSC_VER
// Your can edit 'JSTD_ENABLE_VLD' marco in <jstd/basic/vld_def.h> file
// to switch Visual Leak Detector(vld).
#include <jstd/basic/vld.h>
#endif
#ifndef __SSE4_2__
#define __SSE4_2__ 1
#endif
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <string>
#include <atomic>
#include <memory>
#include <utility>
#include <vector>
#include <map>
#include <unordered_map>
/* SIMD support features */
#define JSTD_HAVE_MMX 1
#define JSTD_HAVE_SSE 1
#define JSTD_HAVE_SSE2 1
#define JSTD_HAVE_SSE3 1
#define JSTD_HAVE_SSSE3 1
#define JSTD_HAVE_SSE4 1
#define JSTD_HAVE_SSE4A 1
#define JSTD_HAVE_SSE4_1 1
#define JSTD_HAVE_SSE4_2 1
#if __SSE4_2__
// Support SSE 4.2: _mm_crc32_u32(), _mm_crc32_u64().
#define JSTD_HAVE_SSE42_CRC32C 1
// Support Intel SMID SHA module: sha1 & sha256, it's higher than SSE 4.2 .
// _mm_sha1msg1_epu32(), _mm_sha1msg2_epu32() and so on.
#define JSTD_HAVE_SMID_SHA 0
#endif // __SSE4_2__
// String compare mode
#define STRING_UTILS_STL 0
#define STRING_UTILS_U64 1
#define STRING_UTILS_SSE42 2
#define STRING_UTILS_MODE STRING_UTILS_SSE42
// Use in <jstd/support/PowerOf2.h>
#define JSTD_SUPPORT_X86_BITSCAN_INSTRUCTION 1
#define USE_JSTD_HASH_TABLE 0
#define USE_JSTD_DICTIONARY 0
#include <jstd/basic/stddef.h>
#include <jstd/basic/stdint.h>
#include <jstd/basic/inttypes.h>
#include <jstd/hash/hash_table.h>
#include <jstd/hash/dictionary.h>
#include <jstd/hash/hashmap_analyzer.h>
#include <jstd/string/string_view.h>
#include <jstd/memory/shiftable_ptr.h>
#include <jstd/system/Console.h>
#include <jstd/system/RandomGen.h>
#include <jstd/test/StopWatch.h>
#include <jstd/test/CPUWarmUp.h>
#include <jstd/test/ProcessMemInfo.h>
#include <jstd/hasher/fnv1a.h>
#include <jstd/string/formatter.h>
#include <jstd/string/snprintf.hpp>
#include <jstd/memory/c_aligned_malloc.h>
//#include <jstd/all.h>
using namespace jstd;
static std::vector<std::string> dict_words;
static std::string dict_filename;
static bool dict_words_is_ready = false;
static const std::size_t kInitCapacity = 16;
#ifdef NDEBUG
static const std::size_t kIterations = 3000000;
#else
static const std::size_t kIterations = 1000;
#endif
//
// See: https://blog.csdn.net/janekeyzheng/article/details/42419407
//
static const char * header_fields[] = {
// Request
"Accept",
"Accept-Charset",
"Accept-Encoding",
"Accept-Language",
"Authorization",
"Cache-Control",
"Connection",
"Cookie",
"Content-Length",
"Content-MD5",
"Content-Type",
"Date", // <-- repeat
"DNT",
"From",
"Front-End-Https",
"Host",
"If-Match",
"If-Modified-Since",
"If-None-Match",
"If-Range",
"If-Unmodified-Since",
"Max-Forwards",
"Pragma",
"Proxy-Authorization",
"Range",
"Referer",
"User-Agent",
"Upgrade",
"Via", // <-- repeat
"Warning",
"X-ATT-DeviceId",
"X-Content-Type-Options",
"X-Forwarded-For",
"X-Forwarded-Proto",
"X-Powered-By",
"X-Requested-With",
"X-XSS-Protection",
// Response
"Access-Control-Allow-Origin",
"Accept-Ranges",
"Age",
"Allow",
//"Cache-Control",
//"Connection",
"Content-Encoding",
"Content-Language",
//"Content-Length",
"Content-Disposition",
//"Content-MD5",
"Content-Range",
//"Content-Type",
"Date", // <-- repeat
"ETag",
"Expires",
"Last-Modified",
"Link",
"Location",
"P3P",
"Proxy-Authenticate",
"Refresh",
"Retry-After",
"Server",
"Set-Cookie",
"Strict-Transport-Security",
"Trailer",
"Transfer-Encoding",
"Vary",
"Via", // <-- repeat
"WWW-Authenticate",
//"X-Content-Type-Options",
//"X-Powered-By",
//"X-XSS-Protection",
"Last"
};
static const size_t kHeaderFieldSize = sizeof(header_fields) / sizeof(char *);
namespace std {
template <>
struct hash<jstd::StringRef> {
typedef std::uint32_t result_type;
jstd::string_hash_helper<jstd::StringRef, std::uint32_t, HashFunc_CRC32C> hash_helper_;
result_type operator()(const jstd::StringRef & key) const {
return hash_helper_.getHashCode(key);
}
};
} // namespace std
namespace jstd {
template <>
struct hash<jstd::StringRef, std::uint32_t, HashFunc_CRC32C> {
typedef std::uint32_t result_type;
jstd::string_hash_helper<jstd::StringRef, std::uint32_t, HashFunc_CRC32C> hash_helper_;
result_type operator()(const jstd::StringRef & key) const {
return hash_helper_.getHashCode(key);
}
};
template <>
struct hash<jstd::StringRef, std::uint32_t, HashFunc_Time31> {
typedef std::uint32_t result_type;
jstd::string_hash_helper<jstd::StringRef, std::uint32_t, HashFunc_Time31> hash_helper_;
result_type operator()(const jstd::StringRef & key) const {
return hash_helper_.getHashCode(key);
}
};
template <>
struct hash<jstd::StringRef, std::uint32_t, HashFunc_Time31Std> {
typedef std::uint32_t result_type;
jstd::string_hash_helper<jstd::StringRef, std::uint32_t, HashFunc_Time31Std> hash_helper_;
result_type operator()(const jstd::StringRef & key) const {
return hash_helper_.getHashCode(key);
}
};
} // namespace jstd
namespace test {
template <typename Key, typename Value>
class std_map {
public:
typedef std::map<Key, Value> map_type;
typedef Key key_type;
typedef Value value_type;
typedef typename map_type::size_type size_type;
typedef typename map_type::iterator iterator;
typedef typename map_type::const_iterator const_iterator;
private:
map_type map_;
public:
std_map(size_type capacity = kInitCapacity) {
}
~std_map() {}
static const char * name() {
return "std::map<K, V>";
}
bool is_hashtable() {
return false;
}
iterator begin() {
return this->map_.begin();
}
iterator end() {
return this->map_.end();
}
const_iterator begin() const {
return this->map_.begin();
}
const_iterator end() const {
return this->map_.end();
}
size_type size() const {
return this->map_.size();
}
bool empty() const {
return this->map_.empty();
}
size_type count(const key_type & key) const {
return this->map_.count(key);
}
void clear() {
this->map_.clear();
}
void reserve(size_type new_capacity) {
// Not implemented
}
void rehash(size_type new_capacity) {
// Not implemented
}
void shrink_to_fit(size_type new_capacity) {
// Not implemented
}
iterator find(const key_type & key) {
return this->map_.find(key);
}
void insert(const key_type & key, const value_type & value) {
this->map_.insert(std::make_pair(key, value));
}
void insert(key_type && key, value_type && value) {
this->map_.insert(std::make_pair(std::forward<key_type>(key),
std::forward<value_type>(value)));
}
template <typename ...Args>
void emplace(Args && ... args) {
this->map_.emplace(std::forward<Args>(args)...);
}
size_type erase(const key_type & key) {
return this->map_.erase(key);
}
};
template <typename Key, typename Value>
class std_unordered_map {
public:
typedef std::unordered_map<Key, Value> map_type;
typedef Key key_type;
typedef Value value_type;
typedef typename map_type::size_type size_type;
typedef typename map_type::iterator iterator;
typedef typename map_type::const_iterator const_iterator;
private:
map_type map_;
public:
std_unordered_map(size_type capacity = kInitCapacity) : map_(capacity) {}
~std_unordered_map() {}
static const char * name() {
return "std::unordered_map<K, V>";
}
bool is_hashtable() {
return true;
}
iterator begin() {
return this->map_.begin();
}
iterator end() {
return this->map_.end();
}
const_iterator begin() const {
return this->map_.begin();
}
const_iterator end() const {
return this->map_.end();
}
size_type size() const {
return this->map_.size();
}
bool empty() const {
return this->map_.empty();
}
size_type bucket_count() const {
return this->map_.bucket_count();
}
size_type count(const key_type & key) const {
return this->map_.count(key);
}
void clear() {
this->map_.clear();
}
void reserve(size_type max_count) {
this->map_.reserve(max_count);
}
void rehash(size_type new_buckets) {
this->map_.rehash(new_buckets);
}
void shrink_to_fit(size_type new_buckets) {
this->map_.rehash(new_buckets);
}
iterator find(const key_type & key) {
return this->map_.find(key);
}
void insert(const key_type & key, const value_type & value) {
this->map_.insert(std::make_pair(key, value));
}
void insert(key_type && key, value_type && value) {
this->map_.insert(std::make_pair(std::forward<key_type>(key),
std::forward<value_type>(value)));
}
template <typename ...Args>
void emplace(Args && ... args) {
this->map_.emplace(std::forward<Args>(args)...);
}
size_type erase(const key_type & key) {
return this->map_.erase(key);
}
};
template <typename T>
class hash_table_impl {
public:
typedef T map_type;
typedef typename map_type::key_type key_type;
typedef typename map_type::mapped_type value_type;
typedef typename map_type::size_type size_type;
typedef typename map_type::iterator iterator;
typedef typename map_type::const_iterator const_iterator;
typedef std::pair<iterator, bool> insert_return_type;
private:
map_type map_;
public:
hash_table_impl(size_type capacity = kInitCapacity) : map_(capacity) {}
~hash_table_impl() {}
static const char * name() {
return map_type::name();
}
bool is_hashtable() {
return true;
}
iterator begin() {
return this->map_.begin();
}
iterator end() {
return this->map_.end();
}
const_iterator begin() const {
return this->map_.begin();
}
const_iterator end() const {
return this->map_.end();
}
size_type size() const {
return this->map_.size();
}
bool empty() const {
return this->map_.empty();
}
size_type bucket_mask() const {
return this->map_.bucket_mask();
}
size_type bucket_count() const {
return this->map_.bucket_count();
}
void clear() {
this->map_.clear();
}
void reserve(size_type new_buckets) {
this->map_.reserve(new_buckets);
}
void rehash(size_type new_buckets) {
this->map_.rehash(new_buckets);
}
void shrink_to_fit(size_type new_buckets) {
this->map_.shrink_to_fit(new_buckets);
}
iterator find(const key_type & key) {
return this->map_.find(key);
}
void insert(const key_type & key, const value_type & value) {
this->map_.insert(key, value);
}
void insert(const key_type & key, value_type && value) {
this->map_.insert(key, std::forward<value_type>(value));
}
void insert(key_type && key, value_type && value) {
this->map_.insert(std::forward<key_type>(key),
std::forward<value_type>(value));
}
template <typename ...Args>
void emplace(Args && ... args) {
this->map_.emplace(std::forward<Args>(args)...);
}
size_type erase(const key_type & key) {
return this->map_.erase(key);
}
};
} // namespace test
template <typename AlgorithmTy>
void hashtable_find_benchmark()
{
static const size_t kRepeatTimes = (kIterations / kHeaderFieldSize);
std::string field_str[kHeaderFieldSize];
std::string index_str[kHeaderFieldSize];
for (size_t i = 0; i < kHeaderFieldSize; ++i) {
field_str[i].assign(header_fields[i]);
index_str[i] = std::to_string(i);
}
{
typedef typename AlgorithmTy::iterator iterator;
size_t checksum = 0;
AlgorithmTy algorithm;
for (size_t i = 0; i < kHeaderFieldSize; ++i) {
algorithm.emplace(field_str[i], index_str[i]);
}
jtest::StopWatch sw;
sw.start();
for (size_t i = 0; i < kRepeatTimes; ++i) {
for (size_t j = 0; j < kHeaderFieldSize; ++j) {
iterator iter = algorithm.find(field_str[j]);
if (iter != algorithm.end()) {
checksum++;
}
}
}
sw.stop();
printf("---------------------------------------------------------------------------\n");
printf(" %-36s ", AlgorithmTy::name());
printf("sum = %-10" PRIuPTR " time: %8.3f ms\n", checksum, sw.getElapsedMillisec());
}
}
void hashtable_find_benchmark()
{
std::cout << " hashtable_find_benchmark()" << std::endl;
std::cout << std::endl;
//hashtable_find_benchmark<test::std_map<std::string, std::string>>();
hashtable_find_benchmark<test::std_unordered_map<std::string, std::string>>();
#if USE_JSTD_HASH_TABLE
hashtable_find_benchmark<test::hash_table_impl<jstd::hash_table<std::string, std::string>>>();
hashtable_find_benchmark<test::hash_table_impl<jstd::hash_table_time31<std::string, std::string>>>();
hashtable_find_benchmark<test::hash_table_impl<jstd::hash_table_time31_std<std::string, std::string>>>();
#endif
#if USE_JSTD_DICTIONARY
hashtable_find_benchmark<test::hash_table_impl<jstd::Dictionary<std::string, std::string>>>();
hashtable_find_benchmark<test::hash_table_impl<jstd::Dictionary_Time31<std::string, std::string>>>();
hashtable_find_benchmark<test::hash_table_impl<jstd::Dictionary_Time31Std<std::string, std::string>>>();
#else
hashtable_find_benchmark<test::hash_table_impl<jstd::Dictionary<std::string, std::string>>>();
#endif
printf("---------------------------------------------------------------------------\n");
printf("\n");
}
template <typename AlgorithmTy>
void hashtable_insert_benchmark_impl()
{
static const size_t kRepeatTimes = (kIterations / kHeaderFieldSize);
std::string field_str[kHeaderFieldSize];
std::string index_str[kHeaderFieldSize];
for (size_t i = 0; i < kHeaderFieldSize; ++i) {
field_str[i].assign(header_fields[i]);
index_str[i] = std::to_string(i);
}
{
size_t checksum = 0;
double totalTime = 0.0;
jtest::StopWatch sw;
for (size_t i = 0; i < kRepeatTimes; ++i) {
AlgorithmTy algorithm(kInitCapacity);
sw.start();
for (size_t j = 0; j < kHeaderFieldSize; ++j) {
algorithm.insert(field_str[j], index_str[j]);
}
checksum += algorithm.size();
sw.stop();
totalTime += sw.getElapsedMillisec();
}
printf("---------------------------------------------------------------------------\n");
printf(" %-36s ", AlgorithmTy::name());
printf("sum = %-10" PRIuPTR " time: %8.3f ms\n", checksum, totalTime);
}
}
void hashtable_insert_benchmark()
{
std::cout << " hashtable_insert_benchmark()" << std::endl;
std::cout << std::endl;
//hashtable_insert_benchmark_impl<test::std_map<std::string, std::string>>();
hashtable_insert_benchmark_impl<test::std_unordered_map<std::string, std::string>>();
#if USE_JSTD_HASH_TABLE
hashtable_insert_benchmark_impl<test::hash_table_impl<jstd::hash_table<std::string, std::string>>>();
hashtable_insert_benchmark_impl<test::hash_table_impl<jstd::hash_table_time31<std::string, std::string>>>();
hashtable_insert_benchmark_impl<test::hash_table_impl<jstd::hash_table_time31_std<std::string, std::string>>>();
#endif
#if USE_JSTD_DICTIONARY
hashtable_insert_benchmark_impl<test::hash_table_impl<jstd::Dictionary<std::string, std::string>>>();
hashtable_insert_benchmark_impl<test::hash_table_impl<jstd::Dictionary_Time31<std::string, std::string>>>();
hashtable_insert_benchmark_impl<test::hash_table_impl<jstd::Dictionary_Time31Std<std::string, std::string>>>();
#else
hashtable_insert_benchmark_impl<test::hash_table_impl<jstd::Dictionary<std::string, std::string>>>();
#endif
printf("---------------------------------------------------------------------------\n");
printf("\n");
}
template <typename AlgorithmTy>
void hashtable_emplace_benchmark_impl()
{
static const size_t kRepeatTimes = (kIterations / kHeaderFieldSize);
std::string field_str[kHeaderFieldSize];
std::string index_str[kHeaderFieldSize];
for (size_t i = 0; i < kHeaderFieldSize; ++i) {
field_str[i].assign(header_fields[i]);
index_str[i] = std::to_string(i);
}
{
size_t checksum = 0;
double totalTime = 0.0;
jtest::StopWatch sw;
for (size_t i = 0; i < kRepeatTimes; ++i) {
AlgorithmTy algorithm(kInitCapacity);
sw.start();
for (size_t j = 0; j < kHeaderFieldSize; ++j) {
algorithm.emplace(field_str[j], index_str[j]);
}
checksum += algorithm.size();
sw.stop();
totalTime += sw.getElapsedMillisec();
}
printf("---------------------------------------------------------------------------\n");
printf(" %-36s ", AlgorithmTy::name());
printf("sum = %-10" PRIuPTR " time: %8.3f ms\n", checksum, totalTime);
}
}
void hashtable_emplace_benchmark()
{
std::cout << " hashtable_emplace_benchmark()" << std::endl;
std::cout << std::endl;
//hashtable_emplace_benchmark_impl<test::std_map<std::string, std::string>>();
hashtable_emplace_benchmark_impl<test::std_unordered_map<std::string, std::string>>();
#if USE_JSTD_HASH_TABLE
hashtable_emplace_benchmark_impl<test::hash_table_impl<jstd::hash_table<std::string, std::string>>>();
hashtable_emplace_benchmark_impl<test::hash_table_impl<jstd::hash_table_time31<std::string, std::string>>>();
hashtable_emplace_benchmark_impl<test::hash_table_impl<jstd::hash_table_time31_std<std::string, std::string>>>();
#endif
#if USE_JSTD_DICTIONARY
hashtable_emplace_benchmark_impl<test::hash_table_impl<jstd::Dictionary<std::string, std::string>>>();
hashtable_emplace_benchmark_impl<test::hash_table_impl<jstd::Dictionary_Time31<std::string, std::string>>>();
hashtable_emplace_benchmark_impl<test::hash_table_impl<jstd::Dictionary_Time31Std<std::string, std::string>>>();
#else
hashtable_emplace_benchmark_impl<test::hash_table_impl<jstd::Dictionary<std::string, std::string>>>();
#endif
printf("---------------------------------------------------------------------------\n");
printf("\n");
}
template <typename AlgorithmTy>
void hashtable_erase_benchmark_impl()
{
static const size_t kRepeatTimes = (kIterations / kHeaderFieldSize);
std::string field_str[kHeaderFieldSize];
std::string index_str[kHeaderFieldSize];
for (size_t i = 0; i < kHeaderFieldSize; ++i) {
field_str[i].assign(header_fields[i]);
index_str[i] = std::to_string(i);
}
{
size_t checksum = 0;
double totalTime = 0.0;
jtest::StopWatch sw;
for (size_t i = 0; i < kRepeatTimes; ++i) {
AlgorithmTy algorithm;
for (size_t j = 0; j < kHeaderFieldSize; ++j) {
algorithm.emplace(field_str[j], index_str[j]);
}
checksum += algorithm.size();
sw.start();
for (size_t j = 0; j < kHeaderFieldSize; ++j) {
size_t counts = algorithm.erase(field_str[j]);
}
sw.stop();
assert(algorithm.size() == 0);
checksum += algorithm.size();
totalTime += sw.getElapsedMillisec();
}
printf("---------------------------------------------------------------------------\n");
printf(" %-36s ", AlgorithmTy::name());
printf("sum = %-10" PRIuPTR " time: %8.3f ms\n", checksum, totalTime);
}
}
void hashtable_erase_benchmark()
{
std::cout << " hashtable_erase_benchmark()" << std::endl;
std::cout << std::endl;
//hashtable_erase_benchmark_impl<test::std_map<std::string, std::string>>();
hashtable_erase_benchmark_impl<test::std_unordered_map<std::string, std::string>>();
#if USE_JSTD_HASH_TABLE
hashtable_erase_benchmark_impl<test::hash_table_impl<jstd::hash_table<std::string, std::string>>>();
hashtable_erase_benchmark_impl<test::hash_table_impl<jstd::hash_table_time31<std::string, std::string>>>();
hashtable_erase_benchmark_impl<test::hash_table_impl<jstd::hash_table_time31_std<std::string, std::string>>>();
#endif
#if USE_JSTD_DICTIONARY
hashtable_erase_benchmark_impl<test::hash_table_impl<jstd::Dictionary<std::string, std::string>>>();
hashtable_erase_benchmark_impl<test::hash_table_impl<jstd::Dictionary_Time31<std::string, std::string>>>();
hashtable_erase_benchmark_impl<test::hash_table_impl<jstd::Dictionary_Time31Std<std::string, std::string>>>();
#else
hashtable_erase_benchmark_impl<test::hash_table_impl<jstd::Dictionary<std::string, std::string>>>();
#endif
printf("---------------------------------------------------------------------------\n");
printf("\n");
}
template <typename AlgorithmTy>
void hashtable_insert_erase_benchmark_impl()
{
static const size_t kRepeatTimes = (kIterations / kHeaderFieldSize);
std::string field_str[kHeaderFieldSize];
std::string index_str[kHeaderFieldSize];
for (size_t i = 0; i < kHeaderFieldSize; ++i) {
field_str[i].assign(header_fields[i]);
index_str[i] = std::to_string(i);
}
{
size_t checksum = 0;
AlgorithmTy algorithm;
jtest::StopWatch sw;
sw.start();
for (size_t i = 0; i < kRepeatTimes; ++i) {
for (size_t j = 0; j < kHeaderFieldSize; ++j) {
algorithm.emplace(field_str[j], index_str[j]);
}
checksum += algorithm.size();
for (size_t j = 0; j < kHeaderFieldSize; ++j) {
algorithm.erase(field_str[j]);
}
assert(algorithm.size() == 0);
checksum += algorithm.size();
}
sw.stop();
printf("---------------------------------------------------------------------------\n");
printf(" %-36s ", AlgorithmTy::name());
printf("sum = %-10" PRIuPTR " time: %8.3f ms\n", checksum, sw.getElapsedMillisec());
}
}
void hashtable_insert_erase_benchmark()
{
std::cout << " hashtable_insert_erase_benchmark()" << std::endl;
std::cout << std::endl;
//hashtable_insert_erase_benchmark_impl<test::std_map<std::string, std::string>>();
hashtable_insert_erase_benchmark_impl<test::std_unordered_map<std::string, std::string>>();
#if USE_JSTD_HASH_TABLE
hashtable_insert_erase_benchmark_impl<test::hash_table_impl<jstd::hash_table<std::string, std::string>>>();
hashtable_insert_erase_benchmark_impl<test::hash_table_impl<jstd::hash_table_time31<std::string, std::string>>>();
hashtable_insert_erase_benchmark_impl<test::hash_table_impl<jstd::hash_table_time31_std<std::string, std::string>>>();
#endif
#if USE_JSTD_DICTIONARY
hashtable_insert_erase_benchmark_impl<test::hash_table_impl<jstd::Dictionary<std::string, std::string>>>();
hashtable_insert_erase_benchmark_impl<test::hash_table_impl<jstd::Dictionary_Time31<std::string, std::string>>>();
hashtable_insert_erase_benchmark_impl<test::hash_table_impl<jstd::Dictionary_Time31Std<std::string, std::string>>>();
#else
hashtable_insert_erase_benchmark_impl<test::hash_table_impl<jstd::Dictionary<std::string, std::string>>>();
#endif
printf("---------------------------------------------------------------------------\n");
printf("\n");
}
template <typename AlgorithmTy>
void hashtable_ref_find_benchmark()
{
static const size_t kRepeatTimes = (kIterations / kHeaderFieldSize);
std::string index_buf[kHeaderFieldSize];
StringRef field_str[kHeaderFieldSize];
StringRef index_str[kHeaderFieldSize];
for (size_t i = 0; i < kHeaderFieldSize; ++i) {
field_str[i].attach(header_fields[i]);
index_buf[i] = std::to_string(i);
index_str[i] = index_buf[i];
}
{
typedef typename AlgorithmTy::iterator iterator;
size_t checksum = 0;
AlgorithmTy algorithm;
for (size_t i = 0; i < kHeaderFieldSize; ++i) {
algorithm.emplace(field_str[i], index_str[i]);
}
jtest::StopWatch sw;
sw.start();
for (size_t i = 0; i < kRepeatTimes; ++i) {
for (size_t j = 0; j < kHeaderFieldSize; ++j) {
iterator iter = algorithm.find(field_str[j]);
if (iter != algorithm.end()) {
checksum++;
}
}
}
sw.stop();
printf("---------------------------------------------------------------------------\n");
printf(" %-36s ", AlgorithmTy::name());
printf("sum = %-10" PRIuPTR " time: %8.3f ms\n", checksum, sw.getElapsedMillisec());
}
}
void hashtable_ref_find_benchmark()
{
std::cout << " hashtable_ref_find_benchmark()" << std::endl;
std::cout << std::endl;
//hashtable_ref_find_benchmark<test::std_map<StringRef, StringRef>>();
hashtable_ref_find_benchmark<test::std_unordered_map<StringRef, StringRef>>();
#if USE_JSTD_HASH_TABLE
hashtable_ref_find_benchmark<test::hash_table_impl<jstd::hash_table<StringRef, StringRef>>>();
hashtable_ref_find_benchmark<test::hash_table_impl<jstd::hash_table_time31<StringRef, StringRef>>>();
hashtable_ref_find_benchmark<test::hash_table_impl<jstd::hash_table_time31_std<StringRef, StringRef>>>();
#endif
#if USE_JSTD_DICTIONARY
hashtable_ref_find_benchmark<test::hash_table_impl<jstd::Dictionary<StringRef, StringRef>>>();
hashtable_ref_find_benchmark<test::hash_table_impl<jstd::Dictionary_Time31<StringRef, StringRef>>>();
hashtable_ref_find_benchmark<test::hash_table_impl<jstd::Dictionary_Time31Std<StringRef, StringRef>>>();
#else
hashtable_ref_find_benchmark<test::hash_table_impl<jstd::Dictionary<StringRef, StringRef>>>();
#endif
printf("---------------------------------------------------------------------------\n");
printf("\n");
}
template <typename AlgorithmTy>
void hashtable_ref_insert_benchmark_impl()
{
static const size_t kRepeatTimes = (kIterations / kHeaderFieldSize);
std::string index_buf[kHeaderFieldSize];
StringRef field_str[kHeaderFieldSize];
StringRef index_str[kHeaderFieldSize];
for (size_t i = 0; i < kHeaderFieldSize; ++i) {
field_str[i].attach(header_fields[i]);
index_buf[i] = std::to_string(i);
index_str[i] = index_buf[i];
}
{
size_t checksum = 0;
double totalTime = 0.0;
jtest::StopWatch sw;
for (size_t i = 0; i < kRepeatTimes; ++i) {
AlgorithmTy algorithm(kInitCapacity);
sw.start();
for (size_t j = 0; j < kHeaderFieldSize; ++j) {
algorithm.insert(field_str[j], index_str[j]);
}
checksum += algorithm.size();
sw.stop();
totalTime += sw.getElapsedMillisec();
}
printf("---------------------------------------------------------------------------\n");
printf(" %-36s ", AlgorithmTy::name());
printf("sum = %-10" PRIuPTR " time: %8.3f ms\n", checksum, totalTime);
}
}
void hashtable_ref_insert_benchmark()
{
std::cout << " hashtable_ref_insert_benchmark()" << std::endl;
std::cout << std::endl;
//hashtable_ref_emplace_benchmark_impl<test::std_map<StringRef, StringRef>>();
hashtable_ref_insert_benchmark_impl<test::std_unordered_map<StringRef, StringRef>>();
#if USE_JSTD_HASH_TABLE
hashtable_ref_insert_benchmark_impl<test::hash_table_impl<jstd::hash_table<StringRef, StringRef>>>();
hashtable_ref_insert_benchmark_impl<test::hash_table_impl<jstd::hash_table_time31<StringRef, StringRef>>>();
hashtable_ref_insert_benchmark_impl<test::hash_table_impl<jstd::hash_table_time31_std<StringRef, StringRef>>>();
#endif
#if USE_JSTD_DICTIONARY
hashtable_ref_insert_benchmark_impl<test::hash_table_impl<jstd::Dictionary<StringRef, StringRef>>>();
hashtable_ref_insert_benchmark_impl<test::hash_table_impl<jstd::Dictionary_Time31<StringRef, StringRef>>>();
hashtable_ref_insert_benchmark_impl<test::hash_table_impl<jstd::Dictionary_Time31Std<StringRef, StringRef>>>();
#else
hashtable_ref_insert_benchmark_impl<test::hash_table_impl<jstd::Dictionary<StringRef, StringRef>>>();
#endif
printf("---------------------------------------------------------------------------\n");
printf("\n");
}
template <typename AlgorithmTy>
void hashtable_ref_emplace_benchmark_impl()
{
static const size_t kRepeatTimes = (kIterations / kHeaderFieldSize);
std::string index_buf[kHeaderFieldSize];
StringRef field_str[kHeaderFieldSize];
StringRef index_str[kHeaderFieldSize];
for (size_t i = 0; i < kHeaderFieldSize; ++i) {
field_str[i].attach(header_fields[i]);
index_buf[i] = std::to_string(i);
index_str[i] = index_buf[i];
}
{
size_t checksum = 0;
double totalTime = 0.0;
jtest::StopWatch sw;
for (size_t i = 0; i < kRepeatTimes; ++i) {
AlgorithmTy algorithm(kInitCapacity);
sw.start();
for (size_t j = 0; j < kHeaderFieldSize; ++j) {
algorithm.emplace(field_str[j], index_str[j]);
}
checksum += algorithm.size();
sw.stop();
totalTime += sw.getElapsedMillisec();
}
printf("---------------------------------------------------------------------------\n");
printf(" %-36s ", AlgorithmTy::name());
printf("sum = %-10" PRIuPTR " time: %8.3f ms\n", checksum, totalTime);
}
}
void hashtable_ref_emplace_benchmark()
{
std::cout << " hashtable_ref_emplace_benchmark()" << std::endl;
std::cout << std::endl;
//hashtable_ref_emplace_benchmark_impl<test::std_map<StringRef, StringRef>>();
hashtable_ref_emplace_benchmark_impl<test::std_unordered_map<StringRef, StringRef>>();
#if USE_JSTD_HASH_TABLE
hashtable_ref_emplace_benchmark_impl<test::hash_table_impl<jstd::hash_table<StringRef, StringRef>>>();
hashtable_ref_emplace_benchmark_impl<test::hash_table_impl<jstd::hash_table_time31<StringRef, StringRef>>>();
hashtable_ref_emplace_benchmark_impl<test::hash_table_impl<jstd::hash_table_time31_std<StringRef, StringRef>>>();
#endif
#if USE_JSTD_DICTIONARY
hashtable_ref_emplace_benchmark_impl<test::hash_table_impl<jstd::Dictionary<StringRef, StringRef>>>();
hashtable_ref_emplace_benchmark_impl<test::hash_table_impl<jstd::Dictionary_Time31<StringRef, StringRef>>>();
hashtable_ref_emplace_benchmark_impl<test::hash_table_impl<jstd::Dictionary_Time31Std<StringRef, StringRef>>>();
#else
hashtable_ref_emplace_benchmark_impl<test::hash_table_impl<jstd::Dictionary<StringRef, StringRef>>>();
#endif
printf("---------------------------------------------------------------------------\n");
printf("\n");
}
template <typename AlgorithmTy>
void hashtable_ref_erase_benchmark_impl()
{
static const size_t kRepeatTimes = (kIterations / kHeaderFieldSize);
std::string field_str[kHeaderFieldSize];
std::string index_str[kHeaderFieldSize];
for (size_t i = 0; i < kHeaderFieldSize; ++i) {
field_str[i].assign(header_fields[i]);
index_str[i] = std::to_string(i);
}
{
size_t checksum = 0;
double totalTime = 0.0;
jtest::StopWatch sw;
for (size_t i = 0; i < kRepeatTimes; ++i) {
AlgorithmTy algorithm;
for (size_t j = 0; j < kHeaderFieldSize; ++j) {
algorithm.emplace(field_str[j], index_str[j]);
}
checksum += algorithm.size();
sw.start();
for (size_t j = 0; j < kHeaderFieldSize; ++j) {
size_t counts = algorithm.erase(field_str[j]);
}
sw.stop();
assert(algorithm.size() == 0);
checksum += algorithm.size();
totalTime += sw.getElapsedMillisec();
}
printf("---------------------------------------------------------------------------\n");
printf(" %-36s ", AlgorithmTy::name());
printf("sum = %-10" PRIuPTR " time: %8.3f ms\n", checksum, totalTime);
}
}
void hashtable_ref_erase_benchmark()
{
std::cout << " hashtable_ref_erase_benchmark()" << std::endl;
std::cout << std::endl;
//hashtable_ref_erase_benchmark_impl<test::std_map<StringRef, StringRef>>();
hashtable_ref_erase_benchmark_impl<test::std_unordered_map<StringRef, StringRef>>();
#if USE_JSTD_HASH_TABLE
hashtable_ref_erase_benchmark_impl<test::hash_table_impl<jstd::hash_table<StringRef, StringRef>>>();
hashtable_ref_erase_benchmark_impl<test::hash_table_impl<jstd::hash_table_time31<StringRef, StringRef>>>();
hashtable_ref_erase_benchmark_impl<test::hash_table_impl<jstd::hash_table_time31_std<StringRef, StringRef>>>();
#endif
#if USE_JSTD_DICTIONARY
hashtable_ref_erase_benchmark_impl<test::hash_table_impl<jstd::Dictionary<StringRef, StringRef>>>();
hashtable_ref_erase_benchmark_impl<test::hash_table_impl<jstd::Dictionary_Time31<StringRef, StringRef>>>();
hashtable_ref_erase_benchmark_impl<test::hash_table_impl<jstd::Dictionary_Time31Std<StringRef, StringRef>>>();
#else
hashtable_ref_erase_benchmark_impl<test::hash_table_impl<jstd::Dictionary<StringRef, StringRef>>>();
#endif
printf("---------------------------------------------------------------------------\n");
printf("\n");
}
template <typename AlgorithmTy>
void hashtable_ref_insert_erase_benchmark_impl()
{
static const size_t kRepeatTimes = (kIterations / kHeaderFieldSize);
std::string index_buf[kHeaderFieldSize];
StringRef field_str[kHeaderFieldSize];
StringRef index_str[kHeaderFieldSize];
for (size_t i = 0; i < kHeaderFieldSize; ++i) {
field_str[i].attach(header_fields[i]);
index_buf[i] = std::to_string(i);
index_str[i] = index_buf[i];
}
{
size_t checksum = 0;
AlgorithmTy algorithm;
jtest::StopWatch sw;
sw.start();
for (size_t i = 0; i < kRepeatTimes; ++i) {
#if 0
assert(algorithm.size() == 0);
algorithm.clear();
assert(algorithm.size() == 0);
checksum += algorithm.size();
#endif
for (size_t j = 0; j < kHeaderFieldSize; ++j) {
algorithm.emplace(field_str[j], index_str[j]);
}
checksum += algorithm.size();
for (size_t j = 0; j < kHeaderFieldSize; ++j) {
algorithm.erase(field_str[j]);
}
assert(algorithm.size() == 0);
checksum += algorithm.size();
}
sw.stop();
printf("---------------------------------------------------------------------------\n");
printf(" %-36s ", AlgorithmTy::name());
printf("sum = %-10" PRIuPTR " time: %8.3f ms\n", checksum, sw.getElapsedMillisec());
}
}
void hashtable_ref_insert_erase_benchmark()
{
std::cout << " hashtable_ref_insert_erase_benchmark()" << std::endl;
std::cout << std::endl;
//hashtable_ref_insert_erase_benchmark_impl<test::std_map<StringRef, StringRef>>();
hashtable_ref_insert_erase_benchmark_impl<test::std_unordered_map<StringRef, StringRef>>();
#if USE_JSTD_HASH_TABLE
hashtable_ref_insert_erase_benchmark_impl<test::hash_table_impl<jstd::hash_table<StringRef, StringRef>>>();
hashtable_ref_insert_erase_benchmark_impl<test::hash_table_impl<jstd::hash_table_time31<StringRef, StringRef>>>();
hashtable_ref_insert_erase_benchmark_impl<test::hash_table_impl<jstd::hash_table_time31_std<StringRef, StringRef>>>();
#endif
#if USE_JSTD_DICTIONARY
hashtable_ref_insert_erase_benchmark_impl<test::hash_table_impl<jstd::Dictionary<StringRef, StringRef>>>();
hashtable_ref_insert_erase_benchmark_impl<test::hash_table_impl<jstd::Dictionary_Time31<StringRef, StringRef>>>();
hashtable_ref_insert_erase_benchmark_impl<test::hash_table_impl<jstd::Dictionary_Time31Std<StringRef, StringRef>>>();
#else
hashtable_ref_insert_erase_benchmark_impl<test::hash_table_impl<jstd::Dictionary<StringRef, StringRef>>>();
#endif
printf("---------------------------------------------------------------------------\n");
printf("\n");
}
template <typename AlgorithmTy>
void hashtable_rehash_benchmark_impl()
{
static const size_t kRepeatTimes = (kIterations / kHeaderFieldSize);
std::string field_str[kHeaderFieldSize];
std::string index_str[kHeaderFieldSize];
for (size_t i = 0; i < kHeaderFieldSize; ++i) {
field_str[i].assign(header_fields[i]);
index_str[i] = std::to_string(i);
}
{
size_t checksum = 0;
size_t buckets = 128;
AlgorithmTy algorithm(kInitCapacity);
for (size_t i = 0; i < kHeaderFieldSize; ++i) {
algorithm.emplace(field_str[i], index_str[i]);
}
jtest::StopWatch sw;
sw.start();
for (size_t i = 0; i < kRepeatTimes; ++i) {
checksum += algorithm.size();
buckets = 128;
algorithm.rehash(buckets);
checksum += algorithm.bucket_count();
#ifndef NDEBUG
static size_t rehash_cnt1 = 0;
if (rehash_cnt1 < 20) {
if (algorithm.bucket_count() != buckets) {
size_t bucket_count = algorithm.bucket_count();
printf("rehash1(): size = %" PRIuPTR ", buckets = %" PRIuPTR ", bucket_count = %" PRIuPTR "\n",
algorithm.size(), buckets, bucket_count);
}
rehash_cnt1++;
}
#endif
for (size_t j = 0; j < 7; ++j) {
buckets *= 2;
algorithm.rehash(buckets);
checksum += algorithm.bucket_count();
#ifndef NDEBUG
static size_t rehash_cnt2 = 0;
if (rehash_cnt2 < 20) {
if (algorithm.bucket_count() != buckets) {
size_t bucket_count = algorithm.bucket_count();
printf("rehash2(%u): size = %" PRIuPTR ", buckets = %" PRIuPTR ", bucket_count = %" PRIuPTR "\n",
(uint32_t)j, algorithm.size(), buckets, bucket_count);
}
rehash_cnt2++;
}
#endif
}
}
sw.stop();
printf("---------------------------------------------------------------------------\n");
printf(" %-36s ", AlgorithmTy::name());
printf("sum = %-10" PRIuPTR " time: %8.3f ms\n", checksum, sw.getElapsedMillisec());
}
}
void hashtable_rehash_benchmark()
{
std::cout << " hashtable_rehash_benchmark()" << std::endl;
std::cout << std::endl;
hashtable_rehash_benchmark_impl<test::std_unordered_map<std::string, std::string>>();
#if USE_JSTD_HASH_TABLE
hashtable_rehash_benchmark_impl<test::hash_table_impl<jstd::hash_table<std::string, std::string>>>();
hashtable_rehash_benchmark_impl<test::hash_table_impl<jstd::hash_table_time31<std::string, std::string>>>();
hashtable_rehash_benchmark_impl<test::hash_table_impl<jstd::hash_table_time31_std<std::string, std::string>>>();
#endif
#if USE_JSTD_DICTIONARY
hashtable_rehash_benchmark_impl<test::hash_table_impl<jstd::Dictionary<std::string, std::string>>>();
hashtable_rehash_benchmark_impl<test::hash_table_impl<jstd::Dictionary_Time31<std::string, std::string>>>();
hashtable_rehash_benchmark_impl<test::hash_table_impl<jstd::Dictionary_Time31Std<std::string, std::string>>>();
#else
hashtable_rehash_benchmark_impl<test::hash_table_impl<jstd::Dictionary<std::string, std::string>>>();
#endif
printf("---------------------------------------------------------------------------\n");
printf("\n");
}
template <typename AlgorithmTy>
void hashtable_rehash2_benchmark_impl()
{
static const size_t kRepeatTimes = (kIterations / kHeaderFieldSize / 2);
std::string field_str[kHeaderFieldSize];
std::string index_str[kHeaderFieldSize];
for (size_t i = 0; i < kHeaderFieldSize; ++i) {
field_str[i].assign(header_fields[i]);
index_str[i] = std::to_string(i);
}
{
size_t checksum = 0;
size_t buckets;
jtest::StopWatch sw;
sw.start();
for (size_t i = 0; i < kRepeatTimes; ++i) {
AlgorithmTy algorithm(kInitCapacity);
for (size_t j = 0; j < kHeaderFieldSize; ++j) {
algorithm.emplace(field_str[j], index_str[j]);
}
checksum += algorithm.size();
checksum += algorithm.bucket_count();
buckets = 128;
algorithm.rehash(buckets);
#ifndef NDEBUG
static size_t rehash_cnt1 = 0;
if (rehash_cnt1 < 20) {
if (algorithm.bucket_count() != buckets) {
size_t bucket_count = algorithm.bucket_count();
printf("rehash1(): size = %" PRIuPTR ", buckets = %" PRIuPTR ", bucket_count = %" PRIuPTR "\n",
algorithm.size(), buckets, bucket_count);
}
rehash_cnt1++;
}
#endif
checksum += algorithm.bucket_count();
for (size_t j = 0; j < 7; ++j) {
buckets *= 2;
algorithm.rehash(buckets);
#ifndef NDEBUG
static size_t rehash_cnt2 = 0;
if (rehash_cnt2 < 20) {
if (algorithm.bucket_count() != buckets) {
size_t bucket_count = algorithm.bucket_count();
printf("rehash2(%u): size = %" PRIuPTR ", buckets = %" PRIuPTR ", bucket_count = %" PRIuPTR "\n",
(uint32_t)j, algorithm.size(), buckets, bucket_count);
}
rehash_cnt2++;
}
#endif
checksum += algorithm.bucket_count();
}
}
sw.stop();
printf("---------------------------------------------------------------------------\n");
printf(" %-36s ", AlgorithmTy::name());
printf("sum = %-10" PRIuPTR " time: %8.3f ms\n", checksum, sw.getElapsedMillisec());
}
}
void hashtable_rehash2_benchmark()
{
std::cout << " hashtable_rehash2_benchmark()" << std::endl;
std::cout << std::endl;
hashtable_rehash2_benchmark_impl<test::std_unordered_map<std::string, std::string>>();
#if USE_JSTD_HASH_TABLE
hashtable_rehash2_benchmark_impl<test::hash_table_impl<jstd::hash_table<std::string, std::string>>>();
hashtable_rehash2_benchmark_impl<test::hash_table_impl<jstd::hash_table_time31<std::string, std::string>>>();
hashtable_rehash2_benchmark_impl<test::hash_table_impl<jstd::hash_table_time31_std<std::string, std::string>>>();
#endif
#if USE_JSTD_DICTIONARY
hashtable_rehash2_benchmark_impl<test::hash_table_impl<jstd::Dictionary<std::string, std::string>>>();
hashtable_rehash2_benchmark_impl<test::hash_table_impl<jstd::Dictionary_Time31<std::string, std::string>>>();
hashtable_rehash2_benchmark_impl<test::hash_table_impl<jstd::Dictionary_Time31Std<std::string, std::string>>>();
#else
hashtable_rehash2_benchmark_impl<test::hash_table_impl<jstd::Dictionary<std::string, std::string>>>();
#endif
printf("---------------------------------------------------------------------------\n");
printf("\n");
}
void hashtable_benchmark()
{
hashtable_find_benchmark();
hashtable_insert_benchmark();
hashtable_emplace_benchmark();
hashtable_erase_benchmark();
hashtable_insert_erase_benchmark();
hashtable_ref_find_benchmark();
hashtable_ref_insert_benchmark();
hashtable_ref_emplace_benchmark();
hashtable_ref_erase_benchmark();
hashtable_ref_insert_erase_benchmark();
hashtable_rehash_benchmark();
hashtable_rehash2_benchmark();
}
template <typename Container>
void hashtable_iterator_uinttest()
{
std::string field_str[kHeaderFieldSize];
std::string index_str[kHeaderFieldSize];
for (size_t i = 0; i < kHeaderFieldSize; ++i) {
field_str[i].assign(header_fields[i]);
index_str[i] = std::to_string(i);
}
Container container(kInitCapacity);
Container container2(kInitCapacity);
for (size_t j = 0; j < kHeaderFieldSize; ++j) {
container2.emplace(field_str[j], index_str[j]);
}
container.swap(container2);
container.display_status();
typedef typename Container::iterator iterator;
typedef typename Container::const_iterator const_iterator;
typedef typename Container::local_iterator local_iterator;
typedef typename Container::const_local_iterator const_local_iterator;
typedef typename Container::hasher hasher;
hasher hasher_;
{
// " [ 1]: 0x7289F843 3 From: 13"
printf("\n");
printf(" # hash index key value\n");
printf("----------------------------------------------------------------------\n");
uint32_t index = 0;
for (iterator iter = container.begin(); iter != container.end(); ++iter) {
std::uint32_t hash_code = container.get_hash(iter->first);
std::string key_name = iter->first.c_str() + std::string(":");
printf(" [%3d]: 0x%08X %-5u %-30s %s\n", index + 1,
hash_code,
uint32_t(hash_code & container.bucket_mask()),
key_name.c_str(),
iter->second.c_str());
index++;
}
printf("\n\n");
}
{
printf("\n");
printf(" # hash index key value\n");
printf("----------------------------------------------------------------------\n");
uint32_t index = 0;
for (local_iterator iter = container.l_begin(); iter != container.l_end(); ++iter) {
std::uint32_t hash_code = container.get_hash(iter->value.first);
std::uint32_t hash_code2 = iter->hash_code;
assert(hash_code == hash_code2);
std::string key_name = iter->value.first.c_str() + std::string(":");
printf(" [%3d]: 0x%08X %-5u %-30s %s\n", index + 1,
hash_code,
uint32_t(hash_code & container.bucket_mask()),
key_name.c_str(),
iter->value.second.c_str());
index++;
}
printf("\n\n");
}
{
printf("\n");
printf(" # hash index key value\n");
printf("----------------------------------------------------------------------\n");
uint32_t index = 0;
for (const_iterator iter = container.cbegin(); iter != container.cend(); ++iter) {
std::uint32_t hash_code = container.get_hash(iter->first);
std::string key_name = iter->first.c_str() + std::string(":");
printf(" [%3d]: 0x%08X %-5u %-30s %s\n", index + 1,
hash_code,
uint32_t(hash_code & container.bucket_mask()),
key_name.c_str(),
iter->second.c_str());
index++;
}
printf("\n\n");
}
{
printf("\n");
printf(" # hash index key value\n");
printf("----------------------------------------------------------------------\n");
uint32_t index = 0;
for (const_local_iterator iter = container.l_cbegin(); iter != container.l_cend(); ++iter) {
std::uint32_t hash_code = container.get_hash(iter->value.first);
std::uint32_t hash_code2 = iter->hash_code;
assert(hash_code == hash_code2);
std::string key_name = iter->value.first.c_str() + std::string(":");
printf(" [%3d]: 0x%08X %-5u %-30s %s\n", index + 1,
hash_code,
uint32_t(hash_code & container.bucket_mask()),
key_name.c_str(),
iter->value.second.c_str());
index++;
}
printf("\n\n");
}
}
template <typename Container>
void hashtable_show_status(const std::string & name)
{
std::string field_str[kHeaderFieldSize];
std::string index_str[kHeaderFieldSize];
for (size_t i = 0; i < kHeaderFieldSize; ++i) {
field_str[i].assign(header_fields[i]);
index_str[i] = std::to_string(i);
}
Container container(kInitCapacity);
for (size_t i = 0; i < kHeaderFieldSize; ++i) {
container.emplace(field_str[i], index_str[i]);
}
HashMapAnalyzer<Container> analyzer(container);
analyzer.set_name(name);
analyzer.start_analyse();
analyzer.display_status();
analyzer.dump_entries();
}
template <typename Container>
void hashtable_i_show_status(const std::string & name)
{
Container container(kInitCapacity);
for (size_t i = 0; i < kHeaderFieldSize; ++i) {
container.emplace(i, i + 1);
}
HashMapAnalyzer<Container> analyzer(container);
analyzer.set_name(name);
analyzer.start_analyse();
analyzer.display_status();
analyzer.dump_entries();
}
template <typename Container>
void hashtable_dict_words_show_status(const std::string & name)
{
Container container(kInitCapacity);
for (size_t i = 0; i < dict_words.size(); i++) {
container.emplace(dict_words[i], std::to_string(i));
}
HashMapAnalyzer<Container> analyzer(container);
analyzer.set_name(name);
analyzer.start_analyse();
analyzer.display_status();
analyzer.dump_entries(100);
}
template <typename Container>
void hashtable_dict_words_i_show_status(const std::string & name)
{
Container container(kInitCapacity);
for (size_t i = 0; i < dict_words.size(); i++) {
container.emplace(i, i + 1);
}
HashMapAnalyzer<Container> analyzer(container);
analyzer.set_name(name);
analyzer.start_analyse();
analyzer.display_status();
analyzer.dump_entries(100);
}
void hashtable_uinttest()
{
if (dict_words_is_ready && dict_words.size() > 0) {
hashtable_dict_words_show_status<jstd::Dictionary<std::string, std::string>>("Dictionary<std::string, std::string>");
hashtable_dict_words_show_status<jstd::Dictionary<jstd::string_view, jstd::string_view>>("Dictionary<jstd::string_view, jstd::string_view>");
hashtable_dict_words_show_status<jstd::Dictionary_Time31<std::string, std::string>>("Dictionary_Time31<std::string, std::string>");
hashtable_dict_words_show_status<jstd::Dictionary_Time31<jstd::string_view, jstd::string_view>>("Dictionary_Time31<jstd::string_view, jstd::string_view>");
//hashtable_dict_words_show_status<std::unordered_map<std::string, std::string>>("std::unordered_map<std::string, std::string>");
//hashtable_dict_words_show_status<std::unordered_map<jstd::string_view, jstd::string_view>>("std::unordered_map<jstd::string_view, jstd::string_view>");
hashtable_dict_words_i_show_status<jstd::Dictionary<std::size_t, std::size_t>>("Dictionary<std::size_t, std::size_t>");
}
else {
hashtable_show_status<jstd::Dictionary<std::string, std::string>>("Dictionary<std::string, std::string>");
hashtable_show_status<jstd::Dictionary<jstd::string_view, jstd::string_view>>("Dictionary<jstd::string_view, jstd::string_view>");
hashtable_show_status<jstd::Dictionary_Time31<std::string, std::string>>("Dictionary_Time31<std::string, std::string>");
hashtable_show_status<jstd::Dictionary_Time31<jstd::string_view, jstd::string_view>>("Dictionary_Time31<jstd::string_view, jstd::string_view>");
//hashtable_show_status<std::unordered_map<std::string, std::string>>("std::unordered_map<std::string, std::string>");
//hashtable_show_status<std::unordered_map<jstd::string_view, jstd::string_view>>("std::unordered_map<jstd::string_view, jstd::string_view>");
hashtable_i_show_status<jstd::Dictionary<std::size_t, std::size_t>>("Dictionary<std::size_t, std::size_t>");
}
//hashtable_iterator_uinttest<jstd::Dictionary<std::string, std::string>>();
}
void formatter_benchmark_sprintf_Integer_1()
{
#ifdef NDEBUG
static const std::size_t iters = 999999;
#else
static const std::size_t iters = 9999;
#endif
std::size_t i;
double time, time_base;
jtest::StopWatch sw;
char fmtbuf1[512] = { 0 };
char fmtbuf2[512] = { 0 };
std::string str1;
std::size_t fmt_len;
printf("==========================================================================\n\n");
printf(" formatter_benchmark_sprintf_Integer_1()\n\n");
printf("==========================================================================\n\n");
printf(" for (i = 0; i < %" PRIuPTR "; ++i) {\n", iters);
printf(" len = snprintf(buf, bufsize, count,\n"
" \"%%d, %%d, %%d, %%d, %%d,\\n\"\n"
" \"%%d, %%d, %%d, %%d, %%d.\",\n"
" 12, 1234, 123456, 12345678, 123456789,\n"
" -12, -1234, -123456, -12345678, -123456789);\n");
printf(" }\n\n");
//printf("==========================================================================\n\n");
{
sw.start();
for (i = 0; i < iters; ++i) {
int fmt_size;
#ifdef _MSC_VER
fmt_size = sprintf_s(fmtbuf1, sizeof(fmtbuf1),
#else
fmt_size = sprintf(fmtbuf1,
#endif
"%d, %d, %d, %d, %d,\n"
"%d, %d, %d, %d, %d.",
12, 1234, 123456, 12345678, 123456789,
-12, -1234, -123456, -12345678, -123456789);
JSTD_UNUSED_VARS(fmt_size);
}
sw.stop();
time = sw.getElapsedMillisec();
time_base = time;
printf("==========================================================================\n\n");
printf(">>> %-20s <<<\n\n", "sprintf()");
printf("result =\n%s\n\n", fmtbuf1);
printf("strlen = %" PRIuPTR " bytes\n", ::strlen(fmtbuf1));
printf("elapsed time = %0.3f ms\n", time);
printf("\n");
}
{
sw.start();
for (i = 0; i < iters; ++i) {
int fmt_size;
#ifdef _MSC_VER
fmt_size = _snprintf_s(fmtbuf2, sizeof(fmtbuf2),
#else
fmt_size = snprintf(fmtbuf2, sizeof(fmtbuf2),
#endif
"%d, %d, %d, %d, %d,\n"
"%d, %d, %d, %d, %d.",
12, 1234, 123456, 12345678, 123456789,
-12, -1234, -123456, -12345678, -123456789);
JSTD_UNUSED_VARS(fmt_size);
}
sw.stop();
time = sw.getElapsedMillisec();
time_base = time;
printf("==========================================================================\n\n");
printf(">>> %-20s <<<\n\n", "snprintf()");
printf("result =\n%s\n\n", fmtbuf2);
printf("strlen = %" PRIuPTR " bytes\n", ::strlen(fmtbuf2));
printf("elapsed time = %0.3f ms\n", time);
printf("\n");
}
jstd::formatter fmt;
{
sw.start();
for (i = 0; i < iters; ++i) {
const char * fmt_buf = nullptr;
fmt_len = fmt.output(fmt_buf,
"%d, %d, %d, %d, %d,\n"
"%d, %d, %d, %d, %d.",
12, 1234, 123456, 12345678, 123456789,
-12, -1234, -123456, -12345678, -123456789);
if (fmt_buf != nullptr) {
::free((void *)fmt_buf);
}
}
sw.stop();
time = sw.getElapsedMillisec();
const char * fmt_buf = nullptr;
fmt_len = fmt.output(fmt_buf,
"%d, %d, %d, %d, %d,\n"
"%d, %d, %d, %d, %d.",
12, 1234, 123456, 12345678, 123456789,
-12, -1234, -123456, -12345678, -123456789);
printf("==========================================================================\n\n");
printf(">>> %-20s <<<\n\n", "fmt.output()");
printf("result =\n%s\n\n", fmt_buf);
printf("strlen = %" PRIuPTR " bytes\n", ::strlen(fmt_buf));
printf("elapsed time = %0.3f ms\n", time);
printf("\n");
if (fmt_buf != nullptr) {
::free((void *)fmt_buf);
}
}
{
sw.restart();
for (i = 0; i < iters; ++i) {
std::string str;
fmt_len = fmt.sprintf(str,
"%d, %d, %d, %d, %d,\n"
"%d, %d, %d, %d, %d.",
12, 1234, 123456, 12345678, 123456789,
-12, -1234, -123456, -12345678, -123456789);
}
sw.stop();
time = sw.getElapsedMillisec();
str1.clear();
fmt_len = fmt.sprintf(str1,
"%d, %d, %d, %d, %d,\n"
"%d, %d, %d, %d, %d.",
12, 1234, 123456, 12345678, 123456789,
-12, -1234, -123456, -12345678, -123456789);
printf("==========================================================================\n\n");
printf(">>> %-20s <<<\n\n", "fmt.sprintf() *");
printf("result = \n%s\n\n", str1.c_str());
printf("strlen = %" PRIuPTR " bytes\n", str1.size());
printf("elapsed time = %0.3f ms\n\n", time);
printf("fmt.sprintf() * vs snprintf(): %0.3f x times.\n", time_base / time);
printf("\n");
}
{
std::string str;
sw.restart();
for (i = 0; i < iters; ++i) {
str.clear();
fmt_len = fmt.sprintf(str,
"%d, %d, %d, %d, %d,\n"
"%d, %d, %d, %d, %d.",
12, 1234, 123456, 12345678, 123456789,
-12, -1234, -123456, -12345678, -123456789);
}
sw.stop();
time = sw.getElapsedMillisec();
printf("==========================================================================\n\n");
printf(">>> %-20s <<<\n\n", "fmt.sprintf()");
printf("result = \n%s\n\n", str.c_str());
printf("strlen = %" PRIuPTR " bytes\n", str.size());
printf("elapsed time = %0.3f ms\n\n", time);
printf("fmt.sprintf() vs snprintf(): %0.3f x times.\n", time_base / time);
printf("\n");
}
{
sw.restart();
for (i = 0; i < iters; ++i) {
std::string str;
fmt_len = fmt.sprintf_direct(str,
"%d, %d, %d, %d, %d,\n"
"%d, %d, %d, %d, %d.",
12, 1234, 123456, 12345678, 123456789,
-12, -1234, -123456, -12345678, -123456789);
}
sw.stop();
time = sw.getElapsedMillisec();
str1.clear();
fmt_len = fmt.sprintf_direct(str1,
"%d, %d, %d, %d, %d,\n"
"%d, %d, %d, %d, %d.",
12, 1234, 123456, 12345678, 123456789,
-12, -1234, -123456, -12345678, -123456789);
printf("==========================================================================\n\n");
printf(">>> %-20s <<<\n\n", "fmt.sprintf_direct() *");
printf("result = \n%s\n\n", str1.c_str());
printf("strlen = %" PRIuPTR " bytes\n", str1.size());
printf("elapsed time = %0.3f ms\n\n", time);
printf("fmt.sprintf_direct() * vs snprintf(): %0.3f x times.\n", time_base / time);
printf("\n");
}
{
std::string str;
sw.restart();
for (i = 0; i < iters; ++i) {
str.clear();
fmt_len = fmt.sprintf_direct(str,
"%d, %d, %d, %d, %d,\n"
"%d, %d, %d, %d, %d.",
12, 1234, 123456, 12345678, 123456789,
-12, -1234, -123456, -12345678, -123456789);
}
sw.stop();
time = sw.getElapsedMillisec();
printf("==========================================================================\n\n");
printf(">>> %-20s <<<\n\n", "fmt.sprintf_direct()");
printf("result = \n%s\n\n", str.c_str());
printf("strlen = %" PRIuPTR " bytes\n", str.size());
printf("elapsed time = %0.3f ms\n\n", time);
printf("fmt.sprintf_direct() vs snprintf(): %0.3f x times.\n", time_base / time);
printf("\n");
}
{
sw.restart();
for (i = 0; i < iters; ++i) {
std::string str;
fmt_len = fmt.sprintf_no_prepare(str,
"%d, %d, %d, %d, %d,\n"
"%d, %d, %d, %d, %d.",
12, 1234, 123456, 12345678, 123456789,
-12, -1234, -123456, -12345678, -123456789);
}
sw.stop();
time = sw.getElapsedMillisec();
str1.clear();
fmt_len = fmt.sprintf_no_prepare(str1,
"%d, %d, %d, %d, %d,\n"
"%d, %d, %d, %d, %d.",
12, 1234, 123456, 12345678, 123456789,
-12, -1234, -123456, -12345678, -123456789);
printf("==========================================================================\n\n");
printf(">>> %-20s <<<\n\n", "fmt.sprintf_no_prepare() *");
printf("result = \n%s\n\n", str1.c_str());
printf("strlen = %" PRIuPTR " bytes\n", str1.size());
printf("elapsed time = %0.3f ms\n\n", time);
printf("fmt.sprintf_no_prepare() * vs snprintf(): %0.3f x times.\n", time_base / time);
printf("\n");
}
{
std::string str;
sw.restart();
for (i = 0; i < iters; ++i) {
str.clear();
fmt_len = fmt.sprintf_no_prepare(str,
"%d, %d, %d, %d, %d,\n"
"%d, %d, %d, %d, %d.",
12, 1234, 123456, 12345678, 123456789,
-12, -1234, -123456, -12345678, -123456789);
}
sw.stop();
time = sw.getElapsedMillisec();
printf("==========================================================================\n\n");
printf(">>> %-20s <<<\n\n", "fmt.sprintf_no_prepare()");
printf("result = \n%s\n\n", str.c_str());
printf("strlen = %" PRIuPTR " bytes\n", str.size());
printf("elapsed time = %0.3f ms\n\n", time);
printf("fmt.sprintf_no_prepare() vs snprintf(): %0.3f x times.\n", time_base / time);
printf("\n");
}
{
sw.restart();
for (i = 0; i < iters; ++i) {
std::string str;
fmt_len = format::snprintf(str,
"%d, %d, %d, %d, %d,\n"
"%d, %d, %d, %d, %d.",
12, 1234, 123456, 12345678, 123456789,
-12, -1234, -123456, -12345678, -123456789);
}
sw.stop();
time = sw.getElapsedMillisec();
fmt_len = format::snprintf(str1,
"%d, %d, %d, %d, %d,\n"
"%d, %d, %d, %d, %d.",
12, 1234, 123456, 12345678, 123456789,
-12, -1234, -123456, -12345678, -123456789);
printf("==========================================================================\n\n");
printf(">>> %-20s <<<\n\n", "format::snprintf() *");
printf("result = \n%s\n\n", str1.c_str());
printf("strlen = %" PRIuPTR " bytes\n", str1.size());
printf("elapsed time = %0.3f ms\n\n", time);
printf("format::snprintf() * vs snprintf(): %0.3f x times.\n", time_base / time);
printf("\n");
}
{
std::string str;
sw.restart();
for (i = 0; i < iters; ++i) {
str.clear();
fmt_len = format::snprintf(str,
"%d, %d, %d, %d, %d,\n"
"%d, %d, %d, %d, %d.",
12, 1234, 123456, 12345678, 123456789,
-12, -1234, -123456, -12345678, -123456789);
}
sw.stop();
time = sw.getElapsedMillisec();
printf("==========================================================================\n\n");
printf(">>> %-20s <<<\n\n", "format::snprintf()");
printf("result = \n%s\n\n", str.c_str());
printf("strlen = %" PRIuPTR " bytes\n", str.size());
printf("elapsed time = %0.3f ms\n\n", time);
printf("format::snprintf() vs snprintf(): %0.3f x times.\n", time_base / time);
printf("\n");
}
JSTD_UNUSED_VARS(fmt_len);
printf("==========================================================================\n");
printf("\n");
}
void formatter_benchmark()
{
formatter_benchmark_sprintf_Integer_1();
}
void string_view_test()
{
string_view sv1(header_fields[4]);
//sv1[2] = 'a'; // Error, readonly
std::string str1("12345676890");
printf("str1 = %s\n", str1.c_str());
string_view sv2("abcdefg");
std::size_t n2 = sv2.copy((char *)str1.data(), 4, 0);
printf("str1 = %s\n", str1.c_str());
string_view sv3(str1);
sv3[2] = 'q';
printf("str1 = %s\n", str1.c_str());
}
void shiftable_ptr_test()
{
{
{
jstd::shiftable_ptr<int> i = new int {100};
jstd::shiftable_ptr<int> j = i;
printf("i.value() = 0x%p, j.value() = 0x%p, j = %d\n\n",
i.get(), j.get(), *j);
}
{
jstd::shiftable_ptr<int> m = new int {99};
jstd::shiftable_ptr<int> n = m;
m = new int {0};
printf("m.value() = 0x%p, n.value() = 0x%p, m = %d, n = %d\n\n",
m.get(), n.get(), *m, *n);
}
{
jstd::custom_shiftable_ptr<int> i {100};
jstd::custom_shiftable_ptr<int> j = i;
printf("custom_shiftable_ptr<T>: i.value() = 0x%p, j.value() = 0x%p, j = %d\n\n",
i.get(), j.get(), *j);
}
{
jstd::custom_shiftable_ptr<int> m {99};
jstd::custom_shiftable_ptr<int> n = m;
m.reset(jstd::custom_shiftable_ptr<int>{88});
printf("custom_shiftable_ptr<T>: m.value() = 0x%p, n.value() = 0x%p, m = %d, n = %d\n\n",
m.get(), n.get(), *m, *n);
}
}
{
{
jstd::shiftable_ptr<jstd::string_view> i = new jstd::string_view("ijk");
jstd::shiftable_ptr<jstd::string_view> j = i;
printf("i.value() = 0x%p, j.value() = 0x%p, j = %s\n\n",
i.get(), j.get(), j->c_str());
}
{
jstd::shiftable_ptr<jstd::string_view> m = new jstd::string_view("mn");
jstd::shiftable_ptr<jstd::string_view> n = m;
m = new jstd::string_view("m123");
printf("m.value() = 0x%p, n.value() = 0x%p, m = %s, n = %s\n\n",
m.get(), n.get(), m->c_str(), n->c_str());
}
{
jstd::custom_shiftable_ptr<jstd::string_view> i("ijk");
jstd::custom_shiftable_ptr<jstd::string_view> j = i;
printf("custom_shiftable_ptr<T>: i.value() = 0x%p, j.value() = 0x%p, j = %s\n\n",
i.get(), j.get(), j->c_str());
}
{
jstd::custom_shiftable_ptr<jstd::string_view> m("mn");
jstd::custom_shiftable_ptr<jstd::string_view> n = m;
m.reset(jstd::custom_shiftable_ptr<jstd::string_view>("mmmmmm"));
printf("custom_shiftable_ptr<T>: m.value() = 0x%p, n.value() = 0x%p, m = %s, n = %s\n\n",
m.get(), n.get(), m->c_str(), n->c_str());
}
}
}
void formatter_test()
{
std::string str1, str2, str3;
int v1 = 100, v2 = 220;
int v3 = 500, v4 = 1024;
unsigned int v5 = 2048, v6 = 4096;
unsigned int v7 = 16384, v8 = 65536;
jstd::formatter fmt;
fmt.sprintf(str1, "num1 = %d, num2 = %d\n\n", v1, v2);
fmt.sprintf_no_prepare(str2, "num1 = %d, num2 = %d\n\n", v1, v2);
fmt.sprintf_direct(str3, "num1 = %d, num2 = %d\n\n", v1, v2);
printf("\n");
printf("fmt.sprintf(str1) = \"%s\"\n", str1.c_str());
printf("fmt.sprintf_no_prepare(str2) = \"%s\"\n", str2.c_str());
printf("fmt.sprintf_direct(str3) = \"%s\"\n", str3.c_str());
str1.clear();
fmt.sprintf(str1,
"num1 = %d, num2 = %d\n"
"num3 = %u, num4 = %d\n"
"num4 = %u, num5 = %d\n"
"num7 = %u, num8 = %d\n\n",
v1, v2, v3, v4, v5, v6, v7, v8);
str2.clear();
fmt.sprintf_no_prepare(str2,
"num1 = %d, num2 = %d\n"
"num3 = %u, num4 = %d\n"
"num4 = %u, num5 = %d\n"
"num7 = %u, num8 = %d\n\n",
v1, v2, v3, v4, v5, v6, v7, v8);
str3.clear();
fmt.sprintf_direct(str3,
"num1 = %d, num2 = %d\n"
"num3 = %u, num4 = %d\n"
"num4 = %u, num5 = %d\n"
"num7 = %u, num8 = %d\n\n",
v1, v2, v3, v4, v5, v6, v7, v8);
printf("\n");
printf("fmt.sprintf(str1) = \"%s\"\n", str1.c_str());
printf("fmt.sprintf_no_prepare(str2) = \"%s\"\n", str2.c_str());
printf("fmt.sprintf_direct(str3) = \"%s\"\n", str3.c_str());
printf("\n");
}
void fnv1a_hash_test()
{
const char * test_str = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"
"abcdefghijklmnopqrstuvwxyz";
uint32_t fnv1a_1 = hasher::FNV1A_Yoshimura(test_str, libc::StrLen(test_str));
uint32_t fnv1a_2 = hasher::FNV1A_Yoshimitsu_TRIADii_xmm(test_str, libc::StrLen(test_str));
uint32_t fnv1a_3 = hasher::FNV1A_penumbra(test_str, libc::StrLen(test_str));
}
#define PTR2HEX16(ptr) (uint32_t)((uint64_t)(ptr) >> 32), (uint32_t)((uint64_t)(ptr) & 0xFFFFFFFFULL)
void realloc_test()
{
void * mem_ptr, * new_ptr;
size_t old_size = 4, new_size;
mem_ptr = ::malloc(old_size);
if (mem_ptr == nullptr)
return;
printf("realloc_test()\n");
printf("\n");
for (size_t i = 0; i < 25; i++) {
new_size = old_size * 2;
new_ptr = ::realloc(mem_ptr, new_size);
if (new_ptr != nullptr) {
if (mem_ptr != new_ptr) {
printf(" old-ptr: 0x%08X%08X, new-ptr: 0x%08X%08X, size: [%8u -> %-8u] bytes\n",
PTR2HEX16(mem_ptr), PTR2HEX16(new_ptr), (uint32_t)old_size, (uint32_t)new_size);
}
else {
printf("(*) old-ptr: 0x%08X%08X, new-ptr: 0x%08X%08X, size: [%8u -> %-8u] bytes\n",
PTR2HEX16(mem_ptr), PTR2HEX16(new_ptr), (uint32_t)old_size, (uint32_t)new_size);
}
mem_ptr = new_ptr;
}
else {
printf("realloc() error.\n\n");
goto realloc_exit;
}
old_size *= 2;
}
printf("\n");
for (size_t i = 0; i < 25; i++) {
new_size = old_size / 2;
new_ptr = ::realloc(mem_ptr, new_size);
if (new_ptr != nullptr) {
if (mem_ptr != new_ptr) {
printf(" old-ptr: 0x%08X%08X, new-ptr: 0x%08X%08X, size: [%8u -> %-8u] bytes\n",
PTR2HEX16(mem_ptr), PTR2HEX16(new_ptr), (uint32_t)old_size, (uint32_t)new_size);
}
else {
printf("(*) old-ptr: 0x%08X%08X, new-ptr: 0x%08X%08X, size: [%8u -> %-8u] bytes\n",
PTR2HEX16(mem_ptr), PTR2HEX16(new_ptr), (uint32_t)old_size, (uint32_t)new_size);
}
mem_ptr = new_ptr;
}
else {
printf("realloc() error.\n\n");
goto realloc_exit;
}
old_size /= 2;
}
printf("\n");
for (size_t i = 0; i < 25; i++) {
new_size = old_size * 2;
new_ptr = ::realloc(mem_ptr, new_size);
if (new_ptr != nullptr) {
if (mem_ptr != new_ptr) {
printf(" old-ptr: 0x%08X%08X, new-ptr: 0x%08X%08X, size: [%8u -> %-8u] bytes\n",
PTR2HEX16(mem_ptr), PTR2HEX16(new_ptr), (uint32_t)old_size, (uint32_t)new_size);
}
else {
printf("(*) old-ptr: 0x%08X%08X, new-ptr: 0x%08X%08X, size: [%8u -> %-8u] bytes\n",
PTR2HEX16(mem_ptr), PTR2HEX16(new_ptr), (uint32_t)old_size, (uint32_t)new_size);
}
mem_ptr = new_ptr;
}
else {
printf("realloc() error.\n\n");
goto realloc_exit;
}
old_size *= 2;
}
realloc_exit:
printf("\n");
if (mem_ptr != nullptr)
::free(mem_ptr);
}
#ifdef _MSC_VER
//
// MSVC: _expand(void * ptr, size_t size);
// https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/expand?view=msvc-160
//
void expand_test()
{
void * mem_ptr, * new_ptr;
size_t old_size = 4, new_size;
mem_ptr = ::malloc(old_size);
if (mem_ptr == nullptr)
return;
printf("expand_test()\n");
printf("\n");
for (size_t i = 0; i < 25; i++) {
new_size = old_size * 2;
new_ptr = ::_expand(mem_ptr, new_size);
if (new_ptr != nullptr) {
if (mem_ptr != new_ptr) {
printf(" old-ptr: 0x%08X%08X, new-ptr: 0x%08X%08X, size: [%8u -> %-8u] bytes\n",
PTR2HEX16(mem_ptr), PTR2HEX16(new_ptr), (uint32_t)old_size, (uint32_t)new_size);
}
else {
printf("(*) old-ptr: 0x%08X%08X, new-ptr: 0x%08X%08X, size: [%8u -> %-8u] bytes\n",
PTR2HEX16(mem_ptr), PTR2HEX16(new_ptr), (uint32_t)old_size, (uint32_t)new_size);
}
mem_ptr = new_ptr;
}
else {
printf("_expand() error.\n\n");
return;
}
old_size *= 2;
}
printf("\n");
for (size_t i = 0; i < 25; i++) {
new_size = old_size / 2;
new_ptr = ::_expand(mem_ptr, new_size);
if (new_ptr != nullptr) {
if (mem_ptr != new_ptr) {
printf(" old-ptr: 0x%08X%08X, new-ptr: 0x%08X%08X, size: [%8u -> %-8u] bytes\n",
PTR2HEX16(mem_ptr), PTR2HEX16(new_ptr), (uint32_t)old_size, (uint32_t)new_size);
}
else {
printf("(*) old-ptr: 0x%08X%08X, new-ptr: 0x%08X%08X, size: [%8u -> %-8u] bytes\n",
PTR2HEX16(mem_ptr), PTR2HEX16(new_ptr), (uint32_t)old_size, (uint32_t)new_size);
}
mem_ptr = new_ptr;
}
else {
printf("_expand() error.\n\n");
goto expand_exit;
}
old_size /= 2;
}
printf("\n");
for (size_t i = 0; i < 25; i++) {
new_size = old_size * 2;
new_ptr = ::_expand(mem_ptr, new_size);
if (new_ptr != nullptr) {
if (mem_ptr != new_ptr) {
printf(" old-ptr: 0x%08X%08X, new-ptr: 0x%08X%08X, size: [%8u -> %-8u] bytes\n",
PTR2HEX16(mem_ptr), PTR2HEX16(new_ptr), (uint32_t)old_size, (uint32_t)new_size);
}
else {
printf("(*) old-ptr: 0x%08X%08X, new-ptr: 0x%08X%08X, size: [%8u -> %-8u] bytes\n",
PTR2HEX16(mem_ptr), PTR2HEX16(new_ptr), (uint32_t)old_size, (uint32_t)new_size);
}
mem_ptr = new_ptr;
}
else {
printf("_expand() error.\n\n");
goto expand_exit;
}
old_size *= 2;
}
expand_exit:
printf("\n");
if (mem_ptr != nullptr)
::free(mem_ptr);
}
#endif // _MSC_VER
void jm_aligned_realloc_test()
{
void * mem_ptr, * new_ptr;
size_t old_size = 4, new_size;
size_t alignment = allocator<int>::kMallocDefaultAlignment;
mem_ptr = jm_aligned_malloc(old_size, alignment);
if (mem_ptr == nullptr)
return;
printf("jm_aligned_realloc_test(): alignment = %u\n", (uint32_t)alignment);
printf("\n");
for (size_t i = 0; i < 25; i++) {
new_size = old_size * 2;
new_ptr = jm_aligned_realloc(mem_ptr, new_size, alignment);
if (new_ptr != nullptr) {
if (mem_ptr != new_ptr) {
printf(" old-ptr: 0x%08X%08X, new-ptr: 0x%08X%08X, size: [%8u -> %-8u] bytes\n",
PTR2HEX16(mem_ptr), PTR2HEX16(new_ptr), (uint32_t)old_size, (uint32_t)new_size);
}
else {
printf("(*) old-ptr: 0x%08X%08X, new-ptr: 0x%08X%08X, size: [%8u -> %-8u] bytes\n",
PTR2HEX16(mem_ptr), PTR2HEX16(new_ptr), (uint32_t)old_size, (uint32_t)new_size);
}
mem_ptr = new_ptr;
}
else {
printf("jm_aligned_realloc() error.\n\n");
goto realloc_exit;
}
old_size *= 2;
}
printf("\n");
for (size_t i = 0; i < 25; i++) {
new_size = old_size / 2;
new_ptr = jm_aligned_realloc(mem_ptr, new_size, alignment);
if (new_ptr != nullptr) {
if (mem_ptr != new_ptr) {
printf(" old-ptr: 0x%08X%08X, new-ptr: 0x%08X%08X, size: [%8u -> %-8u] bytes\n",
PTR2HEX16(mem_ptr), PTR2HEX16(new_ptr), (uint32_t)old_size, (uint32_t)new_size);
}
else {
printf("(*) old-ptr: 0x%08X%08X, new-ptr: 0x%08X%08X, size: [%8u -> %-8u] bytes\n",
PTR2HEX16(mem_ptr), PTR2HEX16(new_ptr), (uint32_t)old_size, (uint32_t)new_size);
}
mem_ptr = new_ptr;
}
else {
printf("jm_aligned_realloc() error.\n\n");
goto realloc_exit;
}
old_size /= 2;
}
printf("\n");
for (size_t i = 0; i < 25; i++) {
new_size = old_size * 2;
new_ptr = jm_aligned_realloc(mem_ptr, new_size, alignment);
if (new_ptr != nullptr) {
if (mem_ptr != new_ptr) {
printf(" old-ptr: 0x%08X%08X, new-ptr: 0x%08X%08X, size: [%8u -> %-8u] bytes\n",
PTR2HEX16(mem_ptr), PTR2HEX16(new_ptr), (uint32_t)old_size, (uint32_t)new_size);
}
else {
printf("(*) old-ptr: 0x%08X%08X, new-ptr: 0x%08X%08X, size: [%8u -> %-8u] bytes\n",
PTR2HEX16(mem_ptr), PTR2HEX16(new_ptr), (uint32_t)old_size, (uint32_t)new_size);
}
mem_ptr = new_ptr;
}
else {
printf("jm_aligned_realloc() error.\n\n");
goto realloc_exit;
}
old_size *= 2;
}
realloc_exit:
printf("\n");
if (mem_ptr != nullptr)
jm_aligned_free(mem_ptr, 8);
}
bool read_dict_file(const std::string & filename)
{
bool is_ok = false;
try {
std::ifstream dict(filename.c_str());
if (dict.is_open()) {
std::string word;
while (!dict.eof()) {
char buf[256];
dict.getline(buf, sizeof(buf));
word = buf;
dict_words.push_back(word);
}
is_ok = true;
dict.close();
}
}
catch (const std::exception & ex) {
std::cout << "read_dict_file() Exception: " << ex.what() << std::endl << std::endl;
is_ok = false;
}
return is_ok;
}
int main(int argc, char * argv[])
{
if (argc == 2) {
std::string filename = argv[1];
bool read_ok = read_dict_file(filename);
dict_words_is_ready = read_ok;
dict_filename = filename;
}
if (!dict_words_is_ready) {
jtest::CPU::warmup(1000);
}
//string_view_test();
//shiftable_ptr_test();
//formatter_test();
//fnv1a_hash_test();
realloc_test();
#ifdef _MSC_VER
expand_test();
#endif
jm_aligned_realloc_test();
//formatter_benchmark();
//hashtable_uinttest();
//hashtable_benchmark();
jstd::Console::ReadKey();
return 0;
}
| 34.25626 | 163 | 0.547833 | shines77 |
96c569ef7d41d75f7e9c2704a8fd5076345ae767 | 3,126 | cpp | C++ | Asdos/Tugas-Latihan/Tgs2_672021224.cpp | DimasAkmall/DDP | f6411aafc799378f99119dd35033047bd1bdb950 | [
"MIT"
] | null | null | null | Asdos/Tugas-Latihan/Tgs2_672021224.cpp | DimasAkmall/DDP | f6411aafc799378f99119dd35033047bd1bdb950 | [
"MIT"
] | null | null | null | Asdos/Tugas-Latihan/Tgs2_672021224.cpp | DimasAkmall/DDP | f6411aafc799378f99119dd35033047bd1bdb950 | [
"MIT"
] | null | null | null | // Dimas Akmal Widi Pradana - 672021224 - DDP F
#include <iostream>
using namespace std;
/*int main(){
int a;
cout << "masukkan a (maks 9): ";
cin >> a;
for (int k = 1; k <= 8*a+8; k++){
cout << " ";
}
for (int i = 1; i <= a-8; i++){
cout << " " << " " << " " << " " << " " << " " << " " << " " << " ";
for (int j = 1; j <= a-8; j++){
cout << "*";
}
}
cout << endl;
for (int k = 1; k <= 7*a+7; k++){
cout << " ";
}
for (int i = 1; i <= a-7; i++){
cout << " " << " " << " " << " " << " " << " " << " " << " ";
for (int j = 1; j <= a-7; j++){
cout << "*";
}
}
cout << endl;
for (int k = 1; k <= 6*a+6; k++){
cout << " ";
}
for (int i = 1; i <= a-6; i++){
cout << " " << " " << " " << " " << " " << " " << " ";
for (int j = 1; j <= a-6; j++){
cout << "*";
}
}
cout << endl;
for (int k = 1; k <= 5*a+5; k++){
cout << " ";
}
for (int i = 1; i <= a-5; i++){
cout << " " << " " << " " << " " << " " << " ";
for (int j = 1; j <= a-5; j++){
cout << "*";
}
}
cout << endl;
for (int k = 1; k <= 4*a+4; k++){
cout << " ";
}
for (int i = 1; i <= a-4; i++){
cout << " " << " " << " " << " " << " ";
for (int j = 1; j <= a-4; j++){
cout << "*";
}
}
cout << endl;
for (int k = 1; k <= 3*a+3; k++){
cout << " ";
}
for (int i = 1; i <= a-3; i++){
cout << " " << " " << " " << " ";
for (int j = 1; j <= a-3; j++){
cout << "*";
}
}
cout << endl;
for (int k = 1; k <= 2*a+2; k++){
cout << " ";
}
for (int i = 1; i <= a-2; i++){
cout << " " << " " << " ";
for (int j = 1; j <= a-2; j++){
cout << "*";
}
}
cout << endl;
for (int k = 1; k <= 1*a+1; k++){
cout << " ";
}
for (int i = 1; i <= a-1; i++){
cout << " " << " ";
for (int j = 1; j <= a-1; j++){
cout << "*";
}
}
cout << endl;
for (int i = 1; i <= a; i++){
cout << " ";
for (int h = 1; h <= a; h++){
cout << "*";
}
}
cout << endl;
//Maaf kak masih bingung hehe..
return 0;
}*/
// pembetulan from rio a.
int main(){
int tinggi;
int baris, jeda, invers, berundak;
cout << "Tingginya (Maks 8): ";
cin >> tinggi;
for(baris=1;baris<=tinggi;baris++){
for(jeda=1;jeda<=tinggi;jeda++){
for(invers=tinggi-baris;invers>0;invers--){
cout << " ";
}
for(berundak=baris;berundak>0;berundak--) {
if(tinggi<jeda+baris){
cout << "*";
}
else{
cout << " ";
}
}
cout << " ";
}
cout << endl;
}
return 0;
} | 22.328571 | 76 | 0.27991 | DimasAkmall |
96c946d267f9328e957d6c1dece07f6b38182e56 | 2,870 | cpp | C++ | QtCef/QtCef/main.cpp | fuyanzhi1234/DevelopQt | f4590cca8cde5e8b38ee19d97ea82c43257ec1b3 | [
"MIT"
] | null | null | null | QtCef/QtCef/main.cpp | fuyanzhi1234/DevelopQt | f4590cca8cde5e8b38ee19d97ea82c43257ec1b3 | [
"MIT"
] | null | null | null | QtCef/QtCef/main.cpp | fuyanzhi1234/DevelopQt | f4590cca8cde5e8b38ee19d97ea82c43257ec1b3 | [
"MIT"
] | null | null | null | #include "qtcef.h"
#include <QApplication>
#include <qt_windows.h>
#include "include/base/cef_scoped_ptr.h"
#include "include/cef_command_line.h"
#include "include/cef_sandbox_win.h"
#include "cefsimple/simple_app.h"
#include "include/cef_sandbox_win.h"
#include <QMessageBox>
#include "cefsimple/simple_handler.h"
bool IsSubprocess(int & argc, char ** argv)
{
std::vector<std::string> argVector(argv, argv + argc);
for (auto i = 0; i < argc; ++i) {
if (argVector[i].find("--type") != std::string::npos) {
return true;
}
}
return false;
}
int RunCefSubprocess(int & argc, char ** argv)
{
CefMainArgs cefMainArgs(GetModuleHandle(nullptr));
return CefExecuteProcess(cefMainArgs, nullptr, nullptr);
}
int main(int argc, char *argv[])
{
if (IsSubprocess(argc, argv)) {
// QMessageBox::about(NULL, "1", "2");
return RunCefSubprocess(argc, argv);
}
// argc = 2;
// argv[1] = "--ppapi-flash-path=plugins\\pepflashplayer.dll";
QApplication a(argc, argv);
// Enable High-DPI support on Windows 7 or newer.
CefEnableHighDPISupport();
void* sandbox_info = NULL;
#if defined(CEF_USE_SANDBOX)
// Manage the life span of the sandbox information object. This is necessary
// for sandbox support on Windows. See cef_sandbox_win.h for complete details.
CefScopedSandboxInfo scoped_sandbox;
sandbox_info = scoped_sandbox.sandbox_info();
#endif
HINSTANCE hInstance = (HINSTANCE)GetModuleHandle(NULL);
// Provide CEF with command-line arguments.
CefMainArgs main_args(hInstance);
// SimpleApp implements application-level callbacks. It will create the first
// browser instance in OnContextInitialized() after CEF has initialized.
// QMessageBox::about(NULL, "main", "1");
CefRefPtr<SimpleApp> app(new SimpleApp());
// CEF applications have multiple sub-processes (render, plugin, GPU, etc)
// that share the same executable. This function checks the command-line and,
// if this is a sub-process, executes the appropriate logic.
// QMessageBox::about(NULL, "main", "2");
// int exit_code = CefExecuteProcess(main_args, app.get(), sandbox_info);
// // The sub-process has completed so return here.
// QMessageBox::about(NULL, "main", QString("%1").arg(exit_code));
//
// if (exit_code >= 0) {
// QMessageBox::about(NULL, "main", "3");
// return 0;
// }
// QMessageBox::about(NULL, "main", "4");
// Specify CEF global settings here.
CefSettings settings;
#if !defined(CEF_USE_SANDBOX)
settings.no_sandbox = true;
#endif
settings.multi_threaded_message_loop = true;
settings.remote_debugging_port = 2012;
// settings.single_process = true;
// Initialize CEF.
CefInitialize(main_args, settings, app.get(), sandbox_info);
QtCef w;
w.show();
int result = a.exec();
// Shut down CEF.
#ifndef _DEBUG
CefShutdown();
#endif // _DEBUG
return result;
}
| 28.7 | 79 | 0.7 | fuyanzhi1234 |
96ca802a7ae3ba460994ccc7caadd74cce9997be | 1,640 | cpp | C++ | Siv3D/src/Siv3D-Platform/WindowsDesktop/Window/HighDPI.cpp | yumetodo/OpenSiv3D | ea191438ecbc64185f5df3d9f79dffc6757e4192 | [
"MIT"
] | 7 | 2020-04-26T11:06:02.000Z | 2021-09-05T16:42:31.000Z | Siv3D/src/Siv3D-Platform/WindowsDesktop/Window/HighDPI.cpp | yumetodo/OpenSiv3D | ea191438ecbc64185f5df3d9f79dffc6757e4192 | [
"MIT"
] | 10 | 2020-04-26T13:25:36.000Z | 2022-03-01T12:34:44.000Z | Siv3D/src/Siv3D-Platform/WindowsDesktop/Window/HighDPI.cpp | yumetodo/OpenSiv3D | ea191438ecbc64185f5df3d9f79dffc6757e4192 | [
"MIT"
] | 2 | 2020-05-11T08:23:23.000Z | 2020-08-08T12:33:30.000Z | //-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2019 Ryo Suzuki
// Copyright (c) 2016-2019 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# include <Siv3D/EngineLog.hpp>
# include <Siv3D/Windows.hpp>
# include <Siv3D/DLL.hpp>
# include <ShellScalingApi.h>
# include "HighDPI.hpp"
namespace s3d
{
// 高 DPI ディスプレイで、フルスクリーン使用時に High DPI Aware を有効にしないと、
// Windows の互換性マネージャーによって
// HKEY_CURRENT_USER/Software/Microsoft/Windows NT/CurrentVersion/AppCompatFlags/Layers
// に高 DPI が既定の設定として登録されてしまう。
void SetHighDPIAwareness(const bool aware)
{
LOG_TRACE(U"SetHighDPIAwareness(aware = {})"_fmt(aware));
if (HMODULE user32 = DLL::LoadSystemLibrary(L"user32.dll"))
{
decltype(SetThreadDpiAwarenessContext)* p_SetThreadDpiAwarenessContext = DLL::GetFunctionNoThrow(user32, "SetThreadDpiAwarenessContext");
if (p_SetThreadDpiAwarenessContext)
{
p_SetThreadDpiAwarenessContext(aware ? DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 : DPI_AWARENESS_CONTEXT_UNAWARE);
::FreeLibrary(user32);
return;
}
::FreeLibrary(user32);
}
if (HINSTANCE shcore = DLL::LoadSystemLibrary(L"shcore.dll"))
{
decltype(SetProcessDpiAwareness)* p_SetProcessDpiAwareness = DLL::GetFunctionNoThrow(shcore, "SetProcessDpiAwareness");
if (p_SetProcessDpiAwareness)
{
p_SetProcessDpiAwareness(aware ? PROCESS_PER_MONITOR_DPI_AWARE : PROCESS_DPI_UNAWARE);
::FreeLibrary(shcore);
return;
}
::FreeLibrary(shcore);
}
if (aware)
{
::SetProcessDPIAware();
}
}
}
| 26.451613 | 140 | 0.693293 | yumetodo |
96cbd824a9526d5c62a48c4144d4fefaa6bda4c5 | 2,786 | cpp | C++ | cpp/virtual/virtual3.cpp | stdbilly/CS_Note | a8a87e135a525d53c283a4c70fb942c9ca59a758 | [
"MIT"
] | 2 | 2020-12-09T09:55:51.000Z | 2021-01-08T11:38:22.000Z | cpp/virtual/virtual3.cpp | stdbilly/CS_Note | a8a87e135a525d53c283a4c70fb942c9ca59a758 | [
"MIT"
] | null | null | null | cpp/virtual/virtual3.cpp | stdbilly/CS_Note | a8a87e135a525d53c283a4c70fb942c9ca59a758 | [
"MIT"
] | null | null | null | #pragma vtordisp(off)
#include <iostream>
using std::cout;
using std::endl;
class Base1 {
public:
Base1() : _iBase1(10) {}
virtual void f() { cout << "Base1::f()" << endl; }
virtual void g() { cout << "Base1::g()" << endl; }
virtual void h() { cout << "Base1::h()" << endl; }
private:
int _iBase1;
};
class Base2 {
public:
Base2() : _iBase2(100) {}
virtual void f() { cout << "Base2::f()" << endl; }
virtual void g() { cout << "Base2::g()" << endl; }
virtual void h() { cout << "Base2::h()" << endl; }
private:
int _iBase2;
};
class Base3 {
public:
Base3() : _iBase3(1000) {}
virtual void f() { cout << "Base3::f()" << endl; }
virtual void g() { cout << "Base3::g()" << endl; }
virtual void h() { cout << "Base3::h()" << endl; }
private:
int _iBase3;
};
/*
32位系统下
测试三:多重继承(带虚函数)
1. 每个基类都有自己的虚函数表
2. 派生类如果有自己的虚函数,会被加入到第一个虚函数表之中
3. 内存布局中, 其基类的布局按照基类被声明时的顺序进行排列
4. 派生类会覆盖基类的虚函数,只有第一个虚函数表中存放的是
真实的被覆盖的函数的地址;其它的虚函数表中存放的并不是真实的
对应的虚函数的地址,而只是一条跳转指令
1>class Derived size(28):
1> +---
1> 0 | +--- (base class Base1)
1> 0 | | {vfptr}
1> 4 | | _iBase1
1> | +---
1> 8 | +--- (base class Base2)
1> 8 | | {vfptr}
1>12 | | _iBase2
1> | +---
1>16 | +--- (base class Base3)
1>16 | | {vfptr}
1>20 | | _iBase3
1> | +---
1>24 | _iDerived
1> +---
1>Derived::$vftable@Base1@:
1> | &Derived_meta
1> | 0
1> 0 | &Derived::f
1> 1 | &Base1::g
1> 2 | &Base1::h
1> 3 | &Derived::g1
1>Derived::$vftable@Base2@:
1> | -8
1> 0 | &thunk: this-=8; goto Derived::f 跳转指令
1> 1 | &Base2::g
1> 2 | &Base2::h
1>
1>Derived::$vftable@Base3@:
1> | -16
1> 0 | &thunk: this-=16; goto Derived::f 跳转指令
1> 1 | &Base3::g
1> 2 | &Base3::h
*/
/*
虚继承Base1
1>class Derived size(32):
1> +---
1> 0 | +--- (base class Base2)
1> 0 | | {vfptr}
1> 4 | | _iBase2
1> | +---
1> 8 | +--- (base class Base3)
1> 8 | | {vfptr}
1>12 | | _iBase3
1> | +---
1>16 | {vbptr} ==> 谁虚继承的基类,该虚基指针就跟着谁
1>20 | _iDerived
1> +---
1> +--- (virtual base Base1)
1>24 | {vfptr}
1>28 | _iBase1
1> +---
*/
class Derived : virtual public Base1, public Base2, public Base3 {
public:
Derived() : _iDerived(10000) {}
void f() { cout << "Derived::f()" << endl; }
virtual void g1() { cout << "Derived::g1()" << endl; }
private:
int _iDerived;
};
int main(void) {
Derived d;
Base2* pBase2 = &d;
Base3* pBase3 = &d;
Derived* pDerived = &d;
pBase2->f();
cout << "sizeof(d) = " << sizeof(d) << endl;
cout << "&Derived = " << &d << endl; // 这三个地址值是不一样的
cout << "pBase2 = " << pBase2 << endl; //
cout << "pBase3 = " << pBase3 << endl; //
return 0;
}
| 19.9 | 67 | 0.507897 | stdbilly |
96cd0fc938ada87d2f809727cb36a2627b0279a3 | 316 | cpp | C++ | src/converter/ExporterOne.cpp | rfrolov/otus_homework_05 | 15e20fb0261c037e4eaaa972734248eb50aba646 | [
"MIT"
] | null | null | null | src/converter/ExporterOne.cpp | rfrolov/otus_homework_05 | 15e20fb0261c037e4eaaa972734248eb50aba646 | [
"MIT"
] | null | null | null | src/converter/ExporterOne.cpp | rfrolov/otus_homework_05 | 15e20fb0261c037e4eaaa972734248eb50aba646 | [
"MIT"
] | null | null | null | #include "../primitives/IPrimitive.h"
#include "../utils/utils.h"
#include "ExporterOne.h"
bool ExporterOne::do_convert(data_t &data) {
if (!fs_.is_open()) { return false; }
fs_ << data.size() << std::endl;
for (auto &serialised_data : data) {
fs_ << serialised_data;
}
return true;
} | 21.066667 | 44 | 0.617089 | rfrolov |
96d089e3997839083c2276f6681cb9be43fa7399 | 1,157 | hpp | C++ | src/shared/network/NetworkServerGame.hpp | darkenk/soldat_cpp | 5d455bbb4f8a82dd6316642a96917f2de2cedec6 | [
"Zlib"
] | 3 | 2022-01-21T10:38:06.000Z | 2022-02-01T16:44:46.000Z | src/shared/network/NetworkServerGame.hpp | darkenk/soldat_cpp | 5d455bbb4f8a82dd6316642a96917f2de2cedec6 | [
"Zlib"
] | null | null | null | src/shared/network/NetworkServerGame.hpp | darkenk/soldat_cpp | 5d455bbb4f8a82dd6316642a96917f2de2cedec6 | [
"Zlib"
] | null | null | null | #pragma once
/*#include "delphi.h"*/
/*#include "and.h"*/
/*#include "system.h"*/
/*#include "units.h"*/
/*#include "SysUtils.h"*/
/*#include "Classes.h"*/
/*#include "Script.h"*/
/*#include "ScriptDispatcher.h"*/
/*#include "soldat.h"*/
/*#include "units.h"*/
/*#include "GameNetworkingSockets.h"*/
/*#include "Net.h"*/
/*#include "Sprites.h"*/
/*#include "Constants.h"*/
#include <steam/isteamnetworkingmessages.h>
#include <string>
void serverhandleplayerdisconnect(SteamNetworkingMessage_t *netmessage);
void servermapchange(std::uint8_t id);
void serverflaginfo(std::uint8_t style, std::uint8_t who);
void serveridleanimation(std::uint8_t num, std::int16_t style);
void serversendvoteon(std::uint8_t votestyle, std::int32_t voter, std::string targetname,
std::string reason);
void serversendvoteoff();
void serverhandlevotekick(SteamNetworkingMessage_t *netmessage);
void serverhandlevotemap(SteamNetworkingMessage_t *netmessage);
void serverhandlechangeteam(SteamNetworkingMessage_t *netmessage);
void serversyncmsg(std::int32_t tonum = 0);
#ifdef STEAM
void serverhandlevoicedata(SteamNetworkingMessage_t *netmessage);
#endif
| 34.029412 | 89 | 0.747623 | darkenk |
96d3eff9d1a8e3eb52b0ba299d150bd95f8692b9 | 15,716 | cpp | C++ | Math Test/src/mat4_test.cpp | gerrygoo/graficas | 443832dc6820c0a93c8291831109e3248f57f9b0 | [
"MIT"
] | null | null | null | Math Test/src/mat4_test.cpp | gerrygoo/graficas | 443832dc6820c0a93c8291831109e3248f57f9b0 | [
"MIT"
] | null | null | null | Math Test/src/mat4_test.cpp | gerrygoo/graficas | 443832dc6820c0a93c8291831109e3248f57f9b0 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "CppUnitTest.h"
#include <cmath>
#include <limits>
#include <locale>
#include <codecvt>
#include "vec4.h"
#include "mat4.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace Microsoft
{
namespace VisualStudio
{
namespace CppUnitTestFramework
{
template<>
static std::wstring ToString<cgmath::vec4>(const cgmath::vec4& v)
{
return L"(" + std::to_wstring(v.x) + L", " + std::to_wstring(v.y) + L", " + std::to_wstring(v.z) + L", " + std::to_wstring(v.w) + L")";
}
template<>
static std::wstring ToString<cgmath::mat4>(const cgmath::mat4& m)
{
std::stringstream ss;
ss << m;
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
std::wstring wide = converter.from_bytes(ss.rdbuf()->str());
return wide;
}
}
}
}
namespace MathTest
{
TEST_CLASS(mat4_test)
{
public:
TEST_METHOD(ConstructorTest)
{
cgmath::mat4 a;
Assert::AreEqual(0.0f, a[0][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, a[0][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, a[0][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, a[0][3], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, a[1][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, a[1][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, a[1][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, a[1][3], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, a[2][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, a[2][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, a[2][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, a[2][3], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, a[3][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, a[3][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, a[3][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, a[3][3], std::numeric_limits<float>::epsilon());
cgmath::mat4 b(1.0f);
Assert::AreEqual(1.0f, b[0][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, b[0][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, b[0][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, b[0][3], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, b[1][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(1.0f, b[1][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, b[1][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, b[1][3], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, b[2][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, b[2][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(1.0f, b[2][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, b[2][3], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, b[3][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, b[3][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, b[3][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(1.0f, b[3][3], std::numeric_limits<float>::epsilon());
cgmath::mat4 c(-7.0f);
Assert::AreEqual(-7.0f, c[0][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, c[0][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, c[0][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, c[0][3], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, c[1][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(-7.0f, c[1][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, c[1][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, c[1][3], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, c[2][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, c[2][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(-7.0f, c[2][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, c[2][3], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, c[3][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, c[3][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, c[3][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(-7.0f, c[3][3], std::numeric_limits<float>::epsilon());
cgmath::vec4 col1(0.0f, 1.0f, 2.0f, 3.0f);
cgmath::vec4 col2(4.0f, 5.0f, 6.0f, 7.0f);
cgmath::vec4 col3(8.0f, 9.0f, 10.0f, 11.0f);
cgmath::vec4 col4(12.0f, 13.0f, 14.0f, 15.0f);
cgmath::mat4 d(col1, col2, col3, col4);
for (auto& col : { 0, 1, 2, 3 })
for (auto& row : { 0, 1, 2, 3 })
Assert::AreEqual(col * 4.0f + row, d[col][row], std::numeric_limits<float>::epsilon());
}
TEST_METHOD(IndexTest)
{
cgmath::vec4 col1(0.0f, 1.0f, 2.0f, 3.0f);
cgmath::vec4 col2(4.0f, 5.0f, 6.0f, 7.0f);
cgmath::vec4 col3(8.0f, 9.0f, 10.0f, 11.0f);
cgmath::vec4 col4(12.0f, 13.0f, 14.0f, 15.0f);
cgmath::mat4 a(col1, col2, col3, col4);
for (auto& col : { 0, 1, 2, 3 })
for (auto& row : { 0, 1, 2, 3 })
Assert::AreEqual(col * 4.0f + row, a[col][row], std::numeric_limits<float>::epsilon());
a[0][0] = 1.0f + 22.0f; a[1][0] -= 2.0f; a[2][0] = 7.0f * 3.0f; a[3][0] = 1.0f + 22.0f;
a[0][1] = 22.0f - 3.0f; a[1][1] += 11.0f; a[2][1] *= 3.0f; a[3][1] = 22.0f - 3.0f;
a[0][2] = 18.0f; a[1][2] = 6.0f / 3.0f; a[2][2] /= 3.0f; a[3][2] = 18.0f;
a[0][3] = 17.0f; a[1][3] = 9.0f / 3.0f; a[2][3] /= 3.0f; a[3][3] = 38.0f;
Assert::AreEqual(1.0f + 22.0f, a[0][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(22.0f - 3.0f, a[0][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(18.0f, a[0][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(17.0f, a[0][3], std::numeric_limits<float>::epsilon());
Assert::AreEqual(4.0f - 2.0f, a[1][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(5.0f + 11.0f, a[1][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(6.0f / 3.0f, a[1][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(9.0f / 3.0f, a[1][3], std::numeric_limits<float>::epsilon());
Assert::AreEqual(7.0f * 3.0f, a[2][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(9.0f * 3.0f, a[2][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(10.0f / 3.0f, a[2][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(11.0f / 3.0f, a[2][3], std::numeric_limits<float>::epsilon());
Assert::AreEqual(1.0f + 22.0f, a[3][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(22.0f - 3.0f, a[3][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(18.0f, a[3][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(38.0f, a[3][3], std::numeric_limits<float>::epsilon());
}
TEST_METHOD(EqualityTest)
{
cgmath::mat4 a;
cgmath::mat4 b;
Assert::IsTrue(a == b);
cgmath::vec4 col1(1.0f, 2.0f, 3.0f, 1.0f);
cgmath::vec4 col2(4.0f, 5.0f, 6.0f, -2.0f);
cgmath::vec4 col3(7.0f, 8.0f, 9.0f, 3.0f);
cgmath::vec4 col4(7.0f, 8.0f, 9.0f, -4.0f);
cgmath::mat4 c(col1, col2, col3, col4);
Assert::IsTrue(a == b);
Assert::IsFalse(a == c);
Assert::IsFalse(b == c);
cgmath::mat4 d(-col1, col2, -col3, col4);
Assert::IsTrue(a == b);
Assert::IsFalse(a == c);
Assert::IsFalse(a == d);
Assert::IsFalse(b == c);
Assert::IsFalse(b == d);
Assert::IsFalse(c == d);
cgmath::mat4 e;
e[0] = col1;
e[1] = col2;
e[2] = col3;
e[3] = col4;
Assert::IsTrue(a == b);
Assert::IsFalse(a == c);
Assert::IsFalse(a == d);
Assert::IsFalse(a == e);
Assert::IsFalse(b == c);
Assert::IsFalse(b == d);
Assert::IsFalse(b == e);
Assert::IsFalse(c == d);
Assert::IsTrue(c == e);
Assert::IsFalse(d == e);
}
TEST_METHOD(InverseTest)
{
cgmath::mat4 a;
for (auto& i : { 0, 1, 2, 3 })
for (auto& j : { 0, 1, 2, 3 })
Assert::IsTrue(std::isnan(cgmath::mat4::inverse(a)[i][j]));
cgmath::mat4 b(1.0f);
Assert::AreEqual<cgmath::mat4>(b, cgmath::mat4::inverse(b));
cgmath::mat4 c(2.0f);
cgmath::mat4 d(0.5f);
Assert::AreEqual<cgmath::mat4>(d, cgmath::mat4::inverse(c));
cgmath::vec4 col1(1.0f, 4.0f, -7.0f, 1.0f);
cgmath::vec4 col2(2.0f, -5.0f, 8.0f, -2.0f);
cgmath::vec4 col3(3.0f, 6.0f, -9.0f, 3.0f);
cgmath::vec4 col4(4.0f, -7.0f, 10.0f, 1.0f);
cgmath::mat4 e(col1, col2, col3, col4);
cgmath::mat4 f = cgmath::mat4::inverse(e);
Assert::AreEqual(1.0f / 8.0f, f[0][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(1.0f / 4.0f, f[0][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(1.0f / 8.0f, f[0][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, f[0][3], std::numeric_limits<float>::epsilon());
Assert::AreEqual(-23.0f / 20.0f, f[1][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(3.0f / 10.0f, f[1][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(43.0f / 60.0f, f[1][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(-2.0f / 5.0f, f[1][3], std::numeric_limits<float>::epsilon());
Assert::AreEqual(-33.0f / 40.0f, f[2][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(3.0f / 20.0f, f[2][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(53.0f / 120.0f, f[2][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(-1.0f / 5.0f, f[2][3], std::numeric_limits<float>::epsilon());
Assert::AreEqual(-3.0f / 10.0f, f[3][0], std::numeric_limits<float>::epsilon());
Assert::AreEqual(-2.0f / 5.0f, f[3][1], std::numeric_limits<float>::epsilon());
Assert::AreEqual(1.0f / 10.0f, f[3][2], std::numeric_limits<float>::epsilon());
Assert::AreEqual(1.0f / 5.0f, f[3][3], std::numeric_limits<float>::epsilon());
}
TEST_METHOD(StreamExtraction)
{
std::stringstream ss1;
cgmath::mat4 a;
ss1 << a;
std::string matstring1 = ss1.rdbuf()->str();
Assert::AreEqual<std::string>("0 0 0 0\n0 0 0 0\n0 0 0 0\n0 0 0 0", matstring1);
std::stringstream ss2;
cgmath::vec4 col1(1.0f, 2.0f, 3.0f, 4.0f);
cgmath::vec4 col2(5.0f, 6.0f, 7.0f, 8.0f);
cgmath::vec4 col3(9.0f, 10.0f, 11.0f, 12.0f);
cgmath::vec4 col4(13.0f, 14.0f, 15.0f, 16.0f);
cgmath::mat4 b(col1, col2, col3, col4);
ss2 << b;
std::string vecstring2 = ss2.rdbuf()->str();
Assert::AreEqual<std::string>("1 5 9 13\n2 6 10 14\n3 7 11 15\n4 8 12 16", vecstring2);
}
TEST_METHOD(Mat4xVec4)
{
cgmath::vec4 v1(3.0f, 6.0f, 4.0f, -2.0f);
cgmath::mat4 m(1.0f);
Assert::AreEqual<cgmath::vec4>(v1, m * v1);
m[0][0] *= 3.0f;
m[1][1] *= 3.0f;
m[2][2] *= 3.0f;
m[3][3] *= 3.0f;
Assert::AreEqual<cgmath::vec4>(v1 * 3.0f, m * v1);
cgmath::vec4 v2(2.0f, -40.0f, 1.0f, 1.0f);
m[2][0] = v2.x;
m[2][1] = v2.y;
m[2][2] = v2.z;
m[3][3] = v2.w;
Assert::AreEqual<cgmath::vec4>(cgmath::vec4(17.0f, -142.0f, 4.0f, -2.0f), m * v1);
cgmath::vec4 v3(-3.0f, 0.0f, 8.0f, 1.0f);
m[1][0] = -2.0f;
m[0][1] = -3.0f;
m[0][2] = -7.0f;
Assert::AreEqual<cgmath::vec4>(cgmath::vec4(7.0f, -311.0f, 29.0f, 1.0f), m * v3);
cgmath::vec4 v4;
Assert::AreEqual<cgmath::vec4>(cgmath::vec4(), m * v4);
cgmath::mat4 m2;
Assert::AreEqual<cgmath::vec4>(v4, m2 * v2);
v4[0] = 1.0f;
v4[1] = 0.0f;
v4[2] = 1.0f;
m2[0][0] = cos(3.14159f); m2[1][0] = -sin(3.14159f); m2[2][0] = 0.0f; m2[3][0] = 0.0f;
m2[0][1] = sin(3.14159f); m2[1][1] = cos(3.14159f); m2[2][1] = 0.0f; m2[3][1] = 0.0f;
m2[0][2] = 0.0f; m2[1][2] = 0.0f; m2[2][2] = 1.0f; m2[3][2] = 0.0f;
m2[0][3] = 0.0f; m2[1][3] = 0.0f; m2[2][3] = 0.0f; m2[3][3] = 1.0f;
Assert::AreEqual(-1.0f, (m2 * v4).x, std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, (m2 * v4).y, 0.00001f);
Assert::AreEqual(1.0f, (m2 * v4).z, std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, (m2 * v4).w, std::numeric_limits<float>::epsilon());
}
TEST_METHOD(Mat4xMat4)
{
cgmath::mat4 m1;
cgmath::mat4 m2(1.0f);
Assert::AreEqual<cgmath::mat4>(m1, m1 * m2);
Assert::AreNotEqual<cgmath::mat4>(m2, m2 * m1);
m1[0][0] = 1.0f; m1[1][0] = 2.0f; m1[2][0] = 3.0f; m1[3][0] = 4.0f;
m1[0][1] = 5.0f; m1[1][1] = 6.0f; m1[2][1] = 7.0f; m1[3][1] = 8.0f;
m1[0][2] = 9.0f; m1[1][2] = 10.0f; m1[2][2] = 11.0f; m1[3][2] = 12.0f;
m1[0][3] = 13.0f; m1[1][3] = 14.0f; m1[2][3] = 15.0f; m1[3][3] = 16.0f;
m2[0][0] = -1.0f; m2[1][0] = -2.0f; m2[2][0] = -3.0f; m2[3][0] = -4.0f;
m2[0][1] = -5.0f; m2[1][1] = -6.0f; m2[2][1] = -7.0f; m2[3][1] = -8.0f;
m2[0][2] = -9.0f; m2[1][2] = -10.0f; m2[2][2] = -11.0f; m2[3][2] = -12.0f;
m2[0][3] = -13.0f; m2[1][3] = -14.0f; m2[2][3] = -15.0f; m2[3][3] = -16.0f;
cgmath::mat4 r;
r[0][0] = -90.0f; r[1][0] = -100.0f; r[2][0] = -110.0f; r[3][0] = -120.0f;
r[0][1] = -202.0f; r[1][1] = -228.0f; r[2][1] = -254.0f; r[3][1] = -280.0f;
r[0][2] = -314.0f; r[1][2] = -356.0f; r[2][2] = -398.0f; r[3][2] = -440.0f;
r[0][3] = -426.0f; r[1][3] = -484.0f; r[2][3] = -542.0f; r[3][3] = -600.0f;
Assert::AreEqual<cgmath::mat4>(r, m1 * m2);
m1[0][0] = 1.0f; m1[1][0] = 2.0f; m1[2][0] = 3.0f; m1[3][0] = 4.0f;
m1[0][1] = 5.0f; m1[1][1] = 6.0f; m1[2][1] = 7.0f; m1[3][1] = 8.0f;
m1[0][2] = 9.0f; m1[1][2] = 10.0f; m1[2][2] = 11.0f; m1[3][2] = 12.0f;
m1[0][3] = 13.0f; m1[1][3] = 14.0f; m1[2][3] = 15.0f; m1[3][3] = 16.0f;
m2[0][0] = 17.0f; m2[1][0] = 18.0f; m2[2][0] = 19.0f; m2[3][0] = 20.0f;
m2[0][1] = 21.0f; m2[1][1] = 22.0f; m2[2][1] = 23.0f; m2[3][1] = 24.0f;
m2[0][2] = 25.0f; m2[1][2] = 26.0f; m2[2][2] = 27.0f; m2[3][2] = 28.0f;
m2[0][3] = 29.0f; m2[1][3] = 30.0f; m2[2][3] = 31.0f; m2[3][3] = 32.0f;
r[0][0] = 250.0f; r[1][0] = 260.0f; r[2][0] = 270.0f; r[3][0] = 280.0f;
r[0][1] = 618.0f; r[1][1] = 644.0f; r[2][1] = 670.0f; r[3][1] = 696.0f;
r[0][2] = 986.0f; r[1][2] = 1028.0f; r[2][2] = 1070.0f; r[3][2] = 1112.0f;
r[0][3] = 1354.0f; r[1][3] = 1412.0f; r[2][3] = 1470.0f; r[3][3] = 1528.0f;
Assert::AreEqual<cgmath::mat4>(r, m1 * m2);
Assert::AreNotEqual<cgmath::mat4>(r, m2 * m1);
r[0][0] = 538.0f; r[1][0] = 612.0f; r[2][0] = 686.0f; r[3][0] = 760.0f;
r[0][1] = 650.0f; r[1][1] = 740.0f; r[2][1] = 830.0f; r[3][1] = 920.0f;
r[0][2] = 762.0f; r[1][2] = 868.0f; r[2][2] = 974.0f; r[3][2] = 1080.0f;
r[0][3] = 874.0f; r[1][3] = 996.0f; r[2][3] = 1118.0f; r[3][3] = 1240.0f;
Assert::AreEqual<cgmath::mat4>(r, m2 * m1);
cgmath::vec4 v(2.0f, 0.0f, -1.0f, 1.0f);
float pi = 3.1415926535897932384626433832795f;
m1[0][0] = cos(pi); m1[1][0] = -sin(pi); m1[2][0] = 0.0f; m1[3][0] = 0.0f;
m1[0][1] = sin(pi); m1[1][1] = cos(pi); m1[2][1] = 0.0f; m1[3][1] = 0.0f;
m1[0][2] = 0.0f; m1[1][2] = 0.0f; m1[2][2] = 1.0f; m1[3][2] = 0.0f;
m1[0][3] = 0.0f; m1[1][3] = 0.0f; m1[2][3] = 0.0f; m1[3][3] = 1.0f;
m2[0][0] = cos(pi); m2[1][0] = -sin(pi); m2[2][0] = 0.0f; m2[3][0] = 0.0f;
m2[0][1] = sin(pi); m2[1][1] = cos(pi); m2[2][1] = 0.0f; m2[3][1] = 0.0f;
m2[0][2] = 0.0f; m2[1][2] = 0.0f; m2[2][2] = 1.0f; m2[3][2] = 0.0f;
m2[0][3] = 0.0f; m2[1][3] = 0.0f; m2[2][3] = 0.0f; m2[3][3] = 1.0f;
cgmath::vec4 res = m1 * m2 * v;
Assert::AreEqual(2.0f, v.x, std::numeric_limits<float>::epsilon());
Assert::AreEqual(0.0f, v.y, 0.000001f);
Assert::AreEqual(-1.0f, v.z, std::numeric_limits<float>::epsilon());
Assert::AreEqual(1.0f, v.w, std::numeric_limits<float>::epsilon());
}
};
} | 44.39548 | 139 | 0.570247 | gerrygoo |
96d4119de16c2d0b7b07531b48824487fead2bb0 | 2,278 | hpp | C++ | blast/include/objtools/edit/publication_edit.hpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | blast/include/objtools/edit/publication_edit.hpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | blast/include/objtools/edit/publication_edit.hpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | #ifndef OBJTOOLS_EDIT__PUBLICATION_EDIT__HPP
#define OBJTOOLS_EDIT__PUBLICATION_EDIT__HPP
/* $Id: publication_edit.hpp 632623 2021-06-03 17:38:11Z ivanov $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Authors: Igor Filippov, Andrea Asztalos
*
* File Description:
* Functions that provides fixes for author names
*/
#include <corelib/ncbistd.hpp>
BEGIN_NCBI_SCOPE
BEGIN_SCOPE(objects)
class CName_std;
BEGIN_SCOPE(edit)
// returns one or more (skip_rest = true) initials from the input string
NCBI_XOBJEDIT_EXPORT string GetFirstInitial(string input, bool skip_rest);
// generates the contents of the 'initials' member based on the first name and
// existing value
NCBI_XOBJEDIT_EXPORT bool GenerateInitials(CName_std& name);
// fixes the 'initials' member only if it has been already set
NCBI_XOBJEDIT_EXPORT bool FixInitials(CName_std& name);
// moves the middle name (initials member) to the first name
NCBI_XOBJEDIT_EXPORT bool MoveMiddleToFirst(CName_std& name);
END_SCOPE(edit)
END_SCOPE(objects)
END_NCBI_SCOPE
#endif // OBJTOOLS_EDIT__PUBLICATION_EDIT__HPP
| 37.966667 | 78 | 0.717735 | mycolab |
96d4391bfa03cc3db1052b74bd3bd6a7aa9bce5b | 903 | cpp | C++ | selection_sort/main.cpp | sangkyunyoon/learn_algorithms_cpp | 1bfafd37f4f80f6fa7fd9f843e77ddce631f6acb | [
"MIT"
] | null | null | null | selection_sort/main.cpp | sangkyunyoon/learn_algorithms_cpp | 1bfafd37f4f80f6fa7fd9f843e77ddce631f6acb | [
"MIT"
] | null | null | null | selection_sort/main.cpp | sangkyunyoon/learn_algorithms_cpp | 1bfafd37f4f80f6fa7fd9f843e77ddce631f6acb | [
"MIT"
] | null | null | null | //
// Created by Sangkyun Yoon on 3/12/21.
//
#include <iostream>
int main() {
int min, index, temp;
int arr[10] = {1, 10, 5, 8, 7, 6, 4, 3, 2, 9};
//정렬을 해야하는 수 만큼 루프를 돈다.
for (int i = 0; i < 10; ++i) {
//항상 최소값은 가장 큰수보다 큰 값으로 매번 초기화 되어야 한다.
min = 9999;
//정렬 대상을 최소값과 하나씩 비교하면서 정렬되지 않은 대상에서 최소값을 찾는다. 값과 위치 정보 획득
for (int j = i; j < 10; ++j) {
if(min > arr[j]) {
min = arr[j];
index = j;
}
}
//i번째 위치의 값과 최소값을 스왑한다.
temp = arr[i];
arr[i] = arr[index];
arr[index] = temp;
std::cout << i << ": ";
for (int k = 0; k < 10; ++k) {
std::cout << arr[k] << " ";
}
std::cout << std::endl;
}
//배열의 수 만큼 루프를 돌면서 값을 출력한다.
for (int k = 0; k < 10; ++k) {
std::cout << arr[k] << " ";
}
return 0;
} | 23.153846 | 66 | 0.399779 | sangkyunyoon |
96d5e00f80e2249b7da56aef2b6fe0b20657d7c4 | 8,702 | cc | C++ | src/benchmark/sorting_bench.cc | calvincaulfield/lib_calvin | cecf2d8b9cc7b6a4e7f269d0e94e0b80774fc30b | [
"Apache-2.0"
] | null | null | null | src/benchmark/sorting_bench.cc | calvincaulfield/lib_calvin | cecf2d8b9cc7b6a4e7f269d0e94e0b80774fc30b | [
"Apache-2.0"
] | null | null | null | src/benchmark/sorting_bench.cc | calvincaulfield/lib_calvin | cecf2d8b9cc7b6a4e7f269d0e94e0b80774fc30b | [
"Apache-2.0"
] | null | null | null | #include <utility>
#include <vector>
#include <string>
#include "sorting_bench.h"
#include "sort.h"
#include "sort_test.h"
#include "pdqsort.h"
#include "bench.h"
#include "random.h"
#include "in_place_merge_sort.h"
#include "intro_sort_parallel.h"
#include "merge_sort_parallel.h"
#include "boost/sort/sort.hpp"
std::vector<lib_calvin_benchmark::sorting::Algorithm>
lib_calvin_benchmark::sorting::getBenchAlgorithms() {
using namespace lib_calvin_benchmark::sorting;
return {
STD_SORT,
LIB_CALVIN_QSORT,
//ORLP_PDQSORT,
BOOST_PDQSORT,
LIB_CALVIN_BLOCK_QSORT,
STD_STABLE_SORT,
BOOST_SPINSORT,
LIB_CALVIN_MERGESORT,
//LIB_CALVIN_STABLE_BLOCK_QSORT, // weak to all equal
BOOST_FLAT_STABLE_SORT,
LIB_CALVIN_IN_PLACE_MERGESORT,
//LIB_CALVIN_HEAPSORT,
BOOST_BLOCK_INDIRECT_SORT,
LIB_CALVIN_BLOCK_QSORT_PARALLEL,
LIB_CALVIN_BLOCK_QSORT_PARALLEL_ADVANCED,
BOOST_SAMPLE_SORT_PARALLEL,
LIB_CALVIN_MERGESORT_PARALLEL
};
}
std::vector<std::string>
lib_calvin_benchmark::sorting::getAlgorithmNamesAndTags(Algorithm algo) {
switch (algo) {
case STD_SORT:
return { "std::sort", "in-place" };
case STD_STABLE_SORT:
return { "std::stable_sort", "stable" };
case ORLP_PDQSORT:
return { "orlp::pdqsort", "in-place" };
case BOOST_SPINSORT:
return { "boost::spinsort", "stable" };
case BOOST_FLAT_STABLE_SORT:
return { "boost::flat_stable_sort", "stable", "in-place" };
case BOOST_PDQSORT:
return { "boost::pdqsort", "in-place" };
case LIB_CALVIN_QSORT:
return { "lib_calvin::qsort", "in-place" };
case LIB_CALVIN_BLOCK_QSORT:
return { "lib_calvin::block_qsort", "in-place" };
case LIB_CALVIN_MERGESORT:
return { "lib_calvin::mergesort", "stable" };
case LIB_CALVIN_STABLE_BLOCK_QSORT:
return { "lib_calvin::stable_block_qsort", "stable" };
case LIB_CALVIN_IN_PLACE_MERGESORT:
return { "lib_calvin::inplace_mergesort", "stable", "in-place" };
case LIB_CALVIN_HEAPSORT:
return { "lib_calvin::heapsort", "in-place" };
case BOOST_BLOCK_INDIRECT_SORT:
return { "boost::block_indirect_sort_parallel", "in-place", "parallel" };
case BOOST_SAMPLE_SORT_PARALLEL:
return { "boost::sample_sort_parallel", "stable", "parallel" };
case LIB_CALVIN_BLOCK_QSORT_PARALLEL:
return { "lib_calvin::block_qsort_parallel", "parallel", "in-place" };
case LIB_CALVIN_BLOCK_QSORT_PARALLEL_ADVANCED:
return { "lib_calvin::block_qsort_parallel+", "parallel", "in-place" };
case LIB_CALVIN_MERGESORT_PARALLEL:
return { "lib_calvin::mergesort_parallel", "stable", "parallel" };
default:
return { "getAlgorithmName error!" };
}
}
std::string
lib_calvin_benchmark::sorting::getTitle(size_t num) {
return category + " " + lib_calvin_benchmark::getSizeString(benchTestSize[num]) +
" " + benchTitleSuffix;
}
std::string
lib_calvin_benchmark::sorting::getPatternString(InputPattern pattern) {
switch (pattern) {
case RANDOM_ORDER:
return "Random array";
case SORTED_90_PERCENT:
return "Nearly sorted (10% randomized)";
case SORTED:
return "Sorted";
case ALL_EQUAL:
return "All equal";
default:
return "Error";
}
}
template <typename T>
std::string
lib_calvin_benchmark::sorting::getSubCategory(InputPattern pattern) {
return T::to_string() + " / " + getPatternString(pattern);
}
std::vector<std::vector<std::string>>
lib_calvin_benchmark::sorting::getAlgorithmNamesAndTagsVector(std::vector<Algorithm> algorithms) {
using namespace std;
vector<vector<string>> algorithmNamesAndTags = {};
std::for_each(algorithms.begin(), algorithms.end(),
[&algorithmNamesAndTags](Algorithm algo) {
algorithmNamesAndTags.push_back(getAlgorithmNamesAndTags(algo)); });
return algorithmNamesAndTags;
}
void lib_calvin_benchmark::sorting::sortBench() {
sortBench(RANDOM_ORDER);
//sortBench(SORTED);
sortBench(ALL_EQUAL);
}
void lib_calvin_benchmark::sorting::sortBench(InputPattern pattern) {
std::cout << "Size : " << benchTestSize.size() << "\n\n\n";
currentInputPattern = pattern;
for (size_t i = 0; i < benchTestSize.size(); i++) {
std::cout << "Doing : " << i << "\n\n\n";
sortBench<object_16>(i);
sortBench<object_32>(i);
sortBench<object_64>(i);
sortBench<object_vector>(i);
}
}
template <typename T>
void lib_calvin_benchmark::sorting::sortBench(size_t num) {
using namespace std;
using namespace lib_calvin_sort;
string category = "Sorting";
string comment = "";
string unit = "M/s (higher is better)";
vector<string> testCases = { "comparison sorting" };
auto algorithms = getBenchAlgorithms();
vector<vector<double>> results;
for (auto algorithm : algorithms) {
results.push_back(
{ sortBenchSub<T>(algorithm, benchTestSize[num], benchNumIter[num]) });
}
lib_calvin_benchmark::save_bench(category, getSubCategory<T>(currentInputPattern), getTitle(num), comment,
getAlgorithmNamesAndTagsVector(algorithms),
results, testCases, unit, benchOrder[num]);
}
template <typename T>
double lib_calvin_benchmark::sorting::sortBenchSub(
Algorithm algo, size_t testSize, size_t numIter) {
using namespace lib_calvin_sort;
using std::less;
std::cout << "Now benchmarking: " << testSize << " " << "object size: " << sizeof(T) <<
" " << getSubCategory<T>(currentInputPattern) <<
" " << getAlgorithmNamesAndTags(algo)[0] << "\n";
switch (algo) {
case STD_SORT:
return sortBenchSub2(std::sort<T *, less<T>>, testSize, numIter);
case STD_STABLE_SORT:
return sortBenchSub2(std::stable_sort<T *, less<T>>, testSize, numIter);
case ORLP_PDQSORT:
return sortBenchSub2(pdqsort_branchless<T *, less<T>>, testSize, numIter);
case BOOST_SPINSORT:
return sortBenchSub2(boost::sort::spinsort<T *, less<T>>, testSize, numIter);
case BOOST_FLAT_STABLE_SORT:
return sortBenchSub2(boost::sort::flat_stable_sort<T *, less<T>>, testSize, numIter);
case BOOST_PDQSORT:
return sortBenchSub2(boost::sort::pdqsort_branchless<T *, less<T>>, testSize, numIter);
case LIB_CALVIN_QSORT:
return sortBenchSub2(introSort<T *, less<T>>, testSize, numIter);
case LIB_CALVIN_BLOCK_QSORT:
return sortBenchSub2(blockIntroSort<T *, less<T>>, testSize, numIter);
case LIB_CALVIN_MERGESORT:
return sortBenchSub2(mergeSort2<T *, less<T>>, testSize, numIter);
case LIB_CALVIN_STABLE_BLOCK_QSORT:
return sortBenchSub2(stableBlockIntroSort<T *, less<T>>, testSize, numIter);
case LIB_CALVIN_IN_PLACE_MERGESORT:
return sortBenchSub2(inPlaceMergeSort2<T *, less<T>>, testSize, numIter);
case LIB_CALVIN_HEAPSORT:
return sortBenchSub2(heapSort<T *, less<T>>, testSize, numIter);
case BOOST_SAMPLE_SORT_PARALLEL:
return sortBenchSub2(boost::sort::sample_sort<T *, less<T>>, testSize, numIter);
case BOOST_BLOCK_INDIRECT_SORT:
return sortBenchSub2(boost::sort::block_indirect_sort<T *, less<T>>, testSize, numIter);
case LIB_CALVIN_BLOCK_QSORT_PARALLEL:
return sortBenchSub2(introSortParallel<T *, less<T>>, testSize, numIter);
case LIB_CALVIN_BLOCK_QSORT_PARALLEL_ADVANCED:
return sortBenchSub2(introSortParallelAdvanced2<T *, less<T>>, testSize, numIter);
case LIB_CALVIN_MERGESORT_PARALLEL:
return sortBenchSub2(mergeSortParallel<T *, less<T>>, testSize, numIter);
default:
cout << "sortBenchSub error!";
exit(0);
}
}
template <typename T>
double
lib_calvin_benchmark::sorting::sortBenchSub2(void(*sorter)(T *first, T *last, std::less<T>),
size_t testSize, size_t numIter) {
using namespace lib_calvin_sort;
lib_calvin::stopwatch watch;
lib_calvin::random_number_generator gen;
T *testSet = static_cast<T *>(operator new(sizeof(T) * testSize));
double min = 1000000;
for (int i = 0; i < numIter; i++) {
if (currentInputPattern == RANDOM_ORDER) {
for (int j = 0; j < testSize; j++) {
new (testSet + j) T(j);
}
std::shuffle(testSet, testSet + testSize, std::mt19937_64(std::random_device()()));
} else if (currentInputPattern == SORTED_90_PERCENT) {
for (int j = 0; j < testSize; j++) {
if (i % 10 == 0) {
new (testSet + j) T(gen() % testSize);
} else {
new (testSet + j) T(j);
}
}
} else if (currentInputPattern == SORTED) {
for (int j = 0; j < testSize; j++) {
new (testSet + j) T(j);
}
} else if (currentInputPattern == ALL_EQUAL) {
for (int j = 0; j < testSize; j++) {
new (testSet + j) T(0);
}
} else {
cout << "sortBenchSub2 error!";
exit(0);
}
double time = 0;
bool isCorrect = true;
bool isStable = true;
sortTest(sorter, testSet, testSet + testSize, "", time, isCorrect, isStable, std::less<T>());
for (int j = 0; j < testSize; j++) {
testSet[j].~T();
}
if (time < min) {
min = time;
}
}
operator delete(testSet);
return testSize * std::log(testSize) / min / 1000 / 1000;
}
| 30.006897 | 107 | 0.714319 | calvincaulfield |
96d86fcf63579188b7a89f507b9ad824af9fab33 | 22,730 | cpp | C++ | NPlan/NPlan/view/NProjectResourceView.cpp | Avens666/NPlan | 726411b053ded26ce6c1b8c280c994d4c1bac71a | [
"Apache-2.0"
] | 16 | 2018-08-30T11:27:14.000Z | 2021-12-17T02:05:45.000Z | NPlan/NPlan/view/NProjectResourceView.cpp | Avens666/NPlan | 726411b053ded26ce6c1b8c280c994d4c1bac71a | [
"Apache-2.0"
] | null | null | null | NPlan/NPlan/view/NProjectResourceView.cpp | Avens666/NPlan | 726411b053ded26ce6c1b8c280c994d4c1bac71a | [
"Apache-2.0"
] | 14 | 2018-08-30T12:13:56.000Z | 2021-02-06T11:07:44.000Z | // File: NProjectResourceView.cpp
// Copyright: Copyright(C) 2013-2017 Wuhan KOTEI Informatics Co., Ltd. All rights reserved.
// Website: http://www.nuiengine.com
// Description: This code is part of NPlan Project (Powered by NUI Engine)
// Comments:
// Rev: 1
// Created: 2018/8/27
// Last edit: 2015/8/28
// Author: Chen Zhi and his team
// E-mail: cz_666@qq.com
// License: APACHE V2.0 (see license file)
#include "NProjectResourceView.h"
#include "../manager/KStringManager.h"
#include "../manager/KProjectManager.h"
extern int g_iScreenWidth; // 屏幕宽度
extern int g_iScreenHeight; // 屏幕高度
NProjectResourceView::NProjectResourceView(CNProjectData* pProjectData)
{
m_down_x=m_down_y=0;
m_p_originalProjData = pProjectData;
if (pProjectData->getTaskBoardItems().size()==0)
{
CNProjectTaskBoardItem board1;
board1.setName(_T("Todo"));
board1.setId(0);
pProjectData->m_taskboard.addBoardItem( board1 );
CNProjectTaskBoardItem board2;
board2.setName(_T("In Process"));
board2.setId(1);
pProjectData->m_taskboard.addBoardItem( board2 );
CNProjectTaskBoardItem board3;
board3.setName(_T("Verify"));
board3.setId(2);
pProjectData->m_taskboard.addBoardItem( board3 );
CNProjectTaskBoardItem board4;
board4.setName(_T("Done"));
board4.setId(3);
pProjectData->m_taskboard.addBoardItem( board4 );
//CNProjectTask task;
//
//task.setStartTime( _T("not a valid time "));
//task.setEndTime( _T( "not a valid time "));
//m_p_originalProjData->addTask( task);
}
m_projectData= *pProjectData;
m_globalResource=*(getProjectManager()->getGlobalResource());
m_down_title = false;
}
NProjectResourceView::~NProjectResourceView( void )
{
}
void NProjectResourceView::initCtrl()
{
kn_int i_btn_w = 100;
kn_int i_btn_h = 40;
int iSlideWidth = 15;
int iGridRow = 3;
int i_grid_col = 6;
int i_width = 700; //窗口高度
int i_height = 480; //窗口宽度
int i_title_height = 38; //标题栏高度
int i_text_width = 65; //文本宽度;
int i_text_x = 20; //文本框left坐标
int i_edit_height = 32; //编辑框高度;
int i_name_edit_width = 598; //项目名称编辑框宽度
int i_pm_edit_width = 500; //项目经理编辑框宽度
int i_start_edit_width = 300; //起始时间编辑框宽度
int i_end_edit_width = 300; //结束时间编辑框宽度
int i_pool_height = 300; //资源池查看框的高度
int i_view_y = 0;
//初始化背景
K9PatchImageDrawable_PTR p_tsk_bg = K9PatchImageDrawable_PTR(new K9PatchImageDrawable(
getSurfaceManager()->GetSurface(_T("./resource/resource_bg.9.png")),true));
m_group_project = KViewGroup_PTR(new KViewGroup);
m_group_project->Create(RERect::MakeXYWH((g_iScreenWidth-i_width)/2,(g_iScreenHeight-i_height)/2,i_width,i_height));
m_group_project->addDrawable(p_tsk_bg);
AddView(m_group_project);
//初始化标题
m_text_title = KTextView_PTR(new KTextView);
m_text_title->SetText(getStringManager()->GetStringByID(_T("project_info")));
m_text_title->setTextAlign(REPaint::kLeft_Align);
m_text_title->SetTextColor(RE_ColorWHITE,RE_ColorWHITE,RE_ColorWHITE,RE_ColorWHITE);
m_text_title->SetFontSize(18);
m_text_title->Create(20,4,i_width - 46,i_title_height);
m_group_project->AddView(m_text_title);
m_text_title->enableMessage(false);
i_view_y = 4 + i_title_height + 15;
//project name and edit
m_text_name = KTextView_PTR(new KTextView);
m_text_name->SetText(getStringManager()->GetStringByID(_T("name")));
m_text_name->setTextAlign(REPaint::kLeft_Align);
m_text_name->SetTextColor(0xff666666,0xff666666,0xff666666,0xff666666);
m_text_name->SetFontSize(14);
m_text_name->Create(i_text_x,i_view_y,i_text_width,i_edit_height);
m_text_name->enableMessage(false);
m_group_project->AddView(m_text_name);
m_edit_name = KEditView_PTR( new KEditView);
K9PatchImageDrawable_PTR p_name = K9PatchImageDrawable_PTR(new K9PatchImageDrawable(
getSurfaceManager()->GetSurface(_T("./resource/public_resource_text.9.png")),true));
p_name->SetRect(RERect::MakeWH(i_name_edit_width,i_edit_height));
K9PatchImageDrawable_PTR p_name_a = K9PatchImageDrawable_PTR(new K9PatchImageDrawable(
getSurfaceManager()->GetSurface(_T("./resource/public_resource_text_a.9.png")),true));
p_name_a->SetRect(RERect::MakeWH(i_name_edit_width,i_edit_height));
m_edit_name->Create(m_text_name->GetRect().right(),i_view_y,i_name_edit_width,i_edit_height);
m_edit_name->Init(5,5,RE_ColorBLACK);
m_edit_name->SetTextColor(0xff444444,0xff444444,0xff444444,0xff444444);;
m_edit_name->setBKDrawable(p_name);
m_edit_name->setFocusDrawable(p_name_a);
m_edit_name->SetCrossIndex(0);
m_edit_name->setTextOff(2,2);
m_edit_name->setCrossOff(4);
m_edit_name->SetText(m_projectData.getName());
m_group_project->AddView(m_edit_name);
i_view_y += i_edit_height+15;
//start and end time
if (!m_projectData.getProBeginTime().is_not_a_date_time())
{
m_text_time_start = KTextView_PTR( new KTextView);
m_text_time_start->SetText(getStringManager()->GetStringByID(_T("task_resource_time_start"))+ _T(" ") + to_iso_extended_wstring(m_projectData.getProBeginTime().date()) );
m_text_time_start->setTextAlign(REPaint::kLeft_Align);
m_text_time_start->SetTextColor(0xff666666,0xff666666,0xff666666,0xff666666);
m_text_time_start->SetFontSize(14);
m_text_time_start->Create(i_text_x,i_view_y,(i_text_width+i_start_edit_width)/2,i_edit_height);
m_text_time_start->enableMessage(false);
m_group_project->AddView(m_text_time_start);
m_text_time_end = KTextView_PTR(new KTextView);
m_text_time_end->SetText(getStringManager()->GetStringByID(_T("task_resource_time_end")) + _T(" ") + to_iso_extended_wstring(m_projectData.getProEndTime().date()) );
m_text_time_end->setTextAlign(REPaint::kLeft_Align);
m_text_time_end->SetTextColor(0xff666666,0xff666666,0xff666666,0xff666666);
m_text_time_end->SetFontSize(14);
m_text_time_end->Create(m_text_time_start->GetRect().right(), i_view_y,(i_text_width+i_end_edit_width)/2,i_edit_height);
m_text_time_end->enableMessage(false);
m_group_project->AddView(m_text_time_end);
i_view_y += i_edit_height+15;
}
//project manager name and edit
m_text_pm =KTextView_PTR( new KTextView);
m_text_pm->SetText(getStringManager()->GetStringByID(_T("task_owner")));
m_text_pm->setTextAlign(REPaint::kLeft_Align);
m_text_pm->SetTextColor(0xff666666,0xff666666,0xff666666,0xff666666);
m_text_pm->SetFontSize(14);
m_text_pm->Create(i_text_x, i_view_y,i_text_width,i_edit_height);
m_text_pm->enableMessage(false);
m_group_project->AddView(m_text_pm);
m_edit_pm = KEditView_PTR(new KEditView);
K9PatchImageDrawable_PTR p_manager_name = K9PatchImageDrawable_PTR(new K9PatchImageDrawable(
getSurfaceManager()->GetSurface(_T("./resource/public_resource_text.9.png")),true));
K9PatchImageDrawable_PTR p_manager_name_a = K9PatchImageDrawable_PTR(new K9PatchImageDrawable(
getSurfaceManager()->GetSurface(_T("./resource/public_resource_text_a.9.png")),true));
p_manager_name->SetRect(RERect::MakeWH((i_pm_edit_width - i_text_width)/2,i_edit_height));
p_manager_name_a->SetRect(RERect::MakeWH((i_pm_edit_width - i_text_width)/2,i_edit_height));
m_edit_pm->Create(m_text_pm->GetRect().right(), i_view_y,(i_pm_edit_width - i_text_width)/2,i_edit_height);
m_edit_pm->Init(5,5,RE_ColorBLACK);
m_edit_pm->SetTextColor(0xff444444,0xff444444,0xff444444,0xff444444);;
m_edit_pm->setBKDrawable(p_manager_name);
m_edit_pm->setFocusDrawable(p_manager_name_a);
m_edit_pm->SetCrossIndex(0);
m_edit_pm->setTextOff(2,2);
m_edit_pm->setCrossOff(4);
m_edit_pm->SetText(m_projectData.getLeader());
m_edit_pm->setReadonly(true);
i_view_y += i_edit_height+15;
p_pmedit_active = K9PatchImageDrawable_PTR(
new K9PatchImageDrawable(getSurfaceManager()->GetSurface(_T("./resource/member_bg_a.9.png")),true));
p_pmedit_active->SetRect(RERect::MakeXYWH(0,0,m_edit_pm->GetRect().width(),m_edit_pm->GetRect().height()));
p_pmedit_active->SetShow(FALSE);
m_edit_pm->addDrawable(p_pmedit_active);
m_group_project->AddView(m_edit_pm);
//resource management
//resource text
m_text_resource = KTextView_PTR( new KTextView);
m_text_resource->SetText(getStringManager()->GetStringByID(_T("project_res")));
m_text_resource->setTextAlign(REPaint::kLeft_Align);
m_text_resource->SetTextColor(0xff666666,0xff666666,0xff666666,0xff666666);
m_text_resource->SetFontSize(14);
m_text_resource->Create(i_text_x, i_view_y,i_text_width*4,i_edit_height);
m_text_resource->enableMessage(false);
m_group_project->AddView(m_text_resource);
i_view_y += i_edit_height+2;
//add people button
KImgButtonView_PTR p_btn_add;
m_group_project->createImgViewHelper(&p_btn_add,
_T("./resource/btn_add_n.png")
, _T("./resource/btn_add_n.png"),
_T("./resource/btn_add_a.png"),
m_edit_name->GetRect().right()-30, m_text_resource->GetRect().top() + 5);
p_btn_add->m_clicked_signal.connect(this,&NProjectResourceView::onBtnAdd);
//project resource pool
/** 添加一个用于滑动的人员*/
m_p_drag_view = NDragStaffView_PTR( new NDragStaffView(_T(""),(res_type)0,0) );
m_p_drag_view->SetTextColor(0xFF555555,0xFF555555,0xFF555555,0xFF555555);
m_p_drag_view->setOpacity(0X88);
m_p_drag_view->SetShow(FALSE);
AddView(m_p_drag_view);
m_grou_resource = KViewGroup_PTR(new KViewGroup);
K9PatchImageDrawable_PTR draw_resource = K9PatchImageDrawable_PTR(new K9PatchImageDrawable(
getSurfaceManager()->GetSurface(_T("./resource/public_resource_people_bg.9.png")),true));
draw_resource->SetRect(RERect::MakeWH(i_width - 46,i_pool_height));
m_grou_resource->Create(23, i_view_y,i_width - 46,i_pool_height);
m_grou_resource->addDrawable(draw_resource);
m_group_project->AddView(m_grou_resource);
RERect rect;
rect.setXYWH(10,2,draw_resource->GetRect().width() - 20,draw_resource->GetRect().height() - 4);
//gridview
m_view_satff_grid = NGridView_PTR( new NGridView((rect.width()-20) / i_grid_col,rect.height() / iGridRow,rect) );
m_view_satff_grid->Create(rect);
m_view_satff_grid->m_sign_GridItemDClicked.connect(this,&NProjectResourceView::onResourceDClick);
m_grou_resource->AddView(m_view_satff_grid);
//init project resource pool
int count = m_projectData.getResourcePool().getCount();
int leaderID = m_projectData.getResourceIdByName(m_projectData.getLeader().c_str());
for (int i = 0 ; i < count; i++)
{
CNProjectResource * tempRes = m_projectData.getResourcePool().getResByIndex(i);
NStaffView_PTR pView = NStaffView_PTR( new NStaffView( tempRes->getName() ,tempRes->getType(),tempRes->getId()) );
pView->SetTextColor(0xff444444,0xff444444,0xff444444,0xff444444);
pView->m_sign_down.connect(this,&NProjectResourceView::onDownMem);
pView->setLeader(leaderID == tempRes->getId());
m_view_satff_grid->AddView(pView);
}
//初始化游标
KSlideView_PTR p_slide = KSlideView_PTR(new KSlideView() );
K9PatchImageDrawable_PTR normal = K9PatchImageDrawable_PTR(
new K9PatchImageDrawable(getSurfaceManager()->GetSurface(_T("./resource/list_silder_bk.9.png")),true));
p_slide->setBKDrawable(normal);
normal = K9PatchImageDrawable_PTR(
new K9PatchImageDrawable(getSurfaceManager()->GetSurface(_T("./resource/list_silder_cursor.9.png")),true));
p_slide->setIconDrawable(normal);
p_slide->Create( RERect::MakeXYWH( m_view_satff_grid->GetRect().width()-8,10,18,m_view_satff_grid->GetRect().height() - 20));
p_slide->init(PROCESS_Vertical);
p_slide->showBK(TRUE);
m_view_satff_grid->BindSlide(p_slide);
m_grou_resource->AddView(p_slide);
//取消
KImgButtonView_PTR p_btn_ok;
m_group_project->createImgView9PatchHelper(&p_btn_ok,
_T("./resource/btn_ok_n.9.png"),
_T("./resource/btn_ok_a.9.png"),
_T("./resource/btn_ok_n.9.png"),
i_width - 23 - i_btn_w, m_grou_resource->GetRect().bottom()+13, i_btn_w, i_btn_h);
p_btn_ok->SetText(getStringManager()->GetStringByID(_T("ok")));
p_btn_ok->SetFontSize(14);
p_btn_ok->setStateChangeEnable(true);
p_btn_ok->SetTextColor(RE_ColorWHITE,RE_ColorWHITE,0xfffff000,RE_ColorWHITE);
p_btn_ok->SetTextBound(RERect::MakeXYWH(8,10,80,24));
p_btn_ok->setTextAlign(REPaint::kCenter_Align);
p_btn_ok->m_clicked_signal.connect(this,&NProjectResourceView::onBtnOk);
//ȷ��
KImgButtonView_PTR p_btn_cancel;
m_group_project->createImgView9PatchHelper(&p_btn_cancel,
_T("./resource/btn_cancel_n.9.png"),
_T("./resource/btn_cancel_a.9.png"),
_T("./resource/btn_cancel_n.9.png"),
p_btn_ok->GetRect().left()- 15 - i_btn_w, m_grou_resource->GetRect().bottom()+13, i_btn_w, i_btn_h);
p_btn_cancel->SetText(getStringManager()->GetStringByID(_T("cancel")));
p_btn_cancel->SetFontSize(14);
p_btn_cancel->setStateChangeEnable(true);
p_btn_cancel->SetTextColor(RE_ColorWHITE,RE_ColorWHITE,0xfffff000,RE_ColorWHITE);
p_btn_cancel->SetTextBound(RERect::MakeXYWH(8,10,80,24));
p_btn_cancel->setTextAlign(REPaint::kCenter_Align);
p_btn_cancel->m_clicked_signal.connect(this,&NProjectResourceView::onBtnCancle);
p_tsk_bg->SetRect(RERect::MakeWH(i_width,p_btn_ok->GetRect().bottom() + 30));
m_group_project->changeViewLayerTop(m_grou_resource);
m_group_project->m_sign_down.connect(this,&NProjectResourceView::onDown);
m_group_project->m_sign_move.connect(this,&NProjectResourceView::onMove);
m_group_project->m_sign_up.connect(this,&NProjectResourceView::onUp);
//�˳�
m_group_project->createImgViewHelper(&m_p_btn_exit,
_T("./resource/btn_delete_n.png")
,_T("./resource/btn_delete_a.png"),
_T("./resource/btn_delete_f.png"),
i_width - 45,3);
m_p_btn_exit->m_clicked_signal.connect(this,&NProjectResourceView::onBtnCancle);
}
/**
* 确定
*/
void NProjectResourceView::onBtnOk(KView_PTR p)
{
if (m_edit_name->getText().size()==0)
{
MessageBox(GetScreen()->getWnd(), getStringManager()->GetStringByID(_T("prj_name_error")).c_str(),getStringManager()->GetStringByID(_T("error")).c_str(), MB_OK);
return;
}
m_projectData.setName(m_edit_name->getText().c_str());
m_projectData.setLeader(m_edit_pm->getText());
m_p_originalProjData->setResourcePool(m_projectData.getResourcePool());
m_p_originalProjData->setName(m_edit_name->getText().c_str());
m_p_originalProjData->setLeader(m_edit_pm->getText());
endModal(KN_REUSLT_OK,TRUE);
if (m_p_originalProjData->getFileName().empty())
{
kn_string filePath = _T("project/");
filePath+=m_edit_name->getText();
filePath+=_T(".nprj");
m_p_originalProjData->setFileName(filePath);
if (NO_ERROR!=m_p_originalProjData->savePrjFile())
{
MessageBox(GetScreen()->getWnd(), getStringManager()->GetStringByID(_T("create_file_fail")).c_str(),getStringManager()->GetStringByID(_T("error")).c_str(), MB_OK);
}
}
}
/**
* 取消
*/
void NProjectResourceView::onBtnCancle(KView_PTR p)
{
endModal(KN_REUSLT_CANCLE,TRUE);
}
void NProjectResourceView::onBtnAdd( KView_PTR p )
{
vector<CNProjectResource> vec_project_member = m_projectData.getResourcePool().getResources();
vector<NMemberMsg> vec_project_mem;
CNProjectTask_LST* taskList=m_projectData.getpManTasks();
for (vector<CNProjectResource>::iterator itr = vec_project_member.begin();
itr != vec_project_member.end() ; ++itr)
{
NMemberMsg member = NMemberMsg(*itr);
for (CNProjectTask_LST::iterator taskIter=taskList->begin();taskIter!=taskList->end();taskIter++)
{
if (taskIter->getLeaderName()==itr->getName())
{
member.b_update=false;
}
}
vec_project_mem.push_back(member);
}
vector<CNProjectResource> vec_global_member =m_globalResource.getResources();
vector<NMemberMsg> vec_global_mem;
for (vector<CNProjectResource>::iterator itr = vec_global_member.begin();
itr != vec_global_member.end() ; ++itr)
{
vec_global_mem.push_back(NMemberMsg(*itr));
}
NMemberSourceView_PTR m_p_mem = NMemberSourceView_PTR( new NMemberSourceView(vec_global_mem, vec_project_mem) );
m_p_mem->Create(0,0,g_iScreenWidth,g_iScreenHeight);
m_p_mem->initCtrl();
m_p_mem->m_sign_btn_ok.connect(this,&NProjectResourceView::UpdateResourceGrid);
AddView(m_p_mem);
m_p_mem->doModal();
}
void NProjectResourceView::UpdateResourceGrid(vector<NMemberMsg>& v )
{
m_view_satff_grid->resetCursorPos();
for (int i = m_view_satff_grid->getViewCount() - 1; i >= 0 ; i--)
{
m_view_satff_grid->AddViewToDel(m_view_satff_grid->getViewByIndex(i));
m_view_satff_grid->eraseView(m_view_satff_grid->getViewByIndex(i));
}
std::vector <CNProjectResource > NewResources;
int offset =0;
bool leaderStillExist=false;
//OutputDebugString(_T("UpdateResourceGrid : "));
for (vector<NMemberMsg>::iterator it = v.begin();
it != v.end() ; it++)
{
NStaffView_PTR pView = NStaffView_PTR( new NStaffView((*it)) );
pView->SetTextColor(0xFF555555,0xFF555555,0xFF555555,0xFF555555);
m_view_satff_grid->AddView(pView);
pView->setCanLeader(true);
pView->m_sign_down.connect(this,&NProjectResourceView::onDownMem);
if (m_edit_pm->getText()==pView->GetName())
{
pView->setLeader(true);
leaderStillExist=true;
}
//OutputDebugString(it->str_name.c_str());
}
if (leaderStillExist==false)
{
m_edit_pm->SetText(_T(""));
}
//OutputDebugString(_T("\n"));
TranslateMemberListToResouceList(v,m_projectData.getResourcePool(),m_globalResource);
}
void NProjectResourceView::TranslateMemberListToResouceList(vector<NMemberMsg>& vecMemeber,CNProjectResourcePool& originalResourcePool, CNProjectResourcePool& extraResourcePool )
{
std::vector <CNProjectResource > NewResources;
int offset =0;
//OutputDebugString(_T("TranslateMemberListToResouceList : "));
for (vector<NMemberMsg>::iterator it = vecMemeber.begin();
it != vecMemeber.end() ; it++)
{
//OutputDebugString(it->str_name.c_str());
// CNProjectResource* pFoundResource = originalResourcePool.getResourceByID(it->id);
// if (pFoundResource!=NULL && pFoundResource->getName()==it->str_name)
// {
// CNProjectResource tempResource(*pFoundResource);
// NewResources.push_back(tempResource);
// }
// else
// {
// pFoundResource= extraResourcePool.getResourceByID(it->id);
// if (pFoundResource!=NULL)
// {
// CNProjectResource tempResource(*pFoundResource);
// tempResource.setId(offset + m_projectData.getResourcePool().getLargestResId());
// offset++;
// NewResources.push_back(tempResource);
// }
// }
CNProjectResource* pFoundResource=NULL;
int resourceID=originalResourcePool.findResourceID(it->str_name.c_str());
//not in original pool
if (resourceID == -1)
{
resourceID = originalResourcePool.getLargestResId();
pFoundResource = extraResourcePool.getResourceByID(it->id);
if (pFoundResource!=NULL)
{
CNProjectResource tempResource(*pFoundResource);
tempResource.setId(offset + m_projectData.getResourcePool().getLargestResId());
offset++;
NewResources.push_back(tempResource);
}
}
//in original pool
else
{
pFoundResource = originalResourcePool.getResourceByID(resourceID);
if (pFoundResource!=NULL)
{
CNProjectResource tempResource(*pFoundResource);
NewResources.push_back(tempResource);
}
}
}
//OutputDebugString(_T("\n"));
originalResourcePool.setResources(NewResources);
}
void NProjectResourceView::MergeResourceByName(CNProjectResourcePool& dstPool, CNProjectResourcePool&srcPool)
{
vector<CNProjectResource> srcResourceVector = srcPool.getResources();
for (vector<CNProjectResource>::iterator iter =srcResourceVector.begin();iter!=srcResourceVector.end();iter++)
{
if(-1 == dstPool.findResourceID(iter->getName().c_str()))
{
if (dstPool.checkResourceByID(iter->getId()))
{
iter->setId(dstPool.getLargestResId());
}
dstPool.addResource(*iter);
}
}
}
/**
* 标题移动相关
*/
void NProjectResourceView::onDown( kn_int iScreenX, kn_int iScreenY, KMessageMouse* pMsg )
{
iScreenX -= m_group_project->GetRect().left();
iScreenY -= m_group_project->GetRect().top();
if (m_text_title->isPointInView(iScreenX,iScreenY))
{
m_down_title = true;
m_down_x = iScreenX;
m_down_y = iScreenY;
}
}
/**
* 标题移动相关
*/
void NProjectResourceView::onMove( kn_int iScreenX, kn_int iScreenY, KMessageMouse* pMsg )
{
if (m_down_title)
{
m_group_project->SetPosition(iScreenX - m_down_x ,iScreenY - m_down_y );
InvalidateView(true);
}
}
/**
* 标题移动相关
*/
void NProjectResourceView::onUp( kn_int iScreenX, kn_int iScreenY, KMessageMouse* pMsg )
{
m_down_title = false;
}
void NProjectResourceView::onResourceDClick( KView_PTR view )
{
NStaffView_PTR staff = VIEW_PTR(NStaffView) (view);
if (staff==NULL)
{
return;
}
m_edit_pm->SetText(staff->GetName());
}
/**
* 拖拽一个成员到负责人窗口
*/
void NProjectResourceView::onDownMem(kn_int x, kn_int y,KMessageMouse* msg)
{
NStaffView_PTR pView = VIEW_PTR(NStaffView)(msg->m_p_view);
kn_string str ;
//������û������ ��������ק cxc 2014-5-5
//if (pView->getCanUpdate())
{
pView->GetName(str);
m_p_drag_view->SetResourceType(pView->GetResourceType());
m_p_drag_view->SetName(str);
m_p_drag_view->OnDown(x,y,msg);
}
}
void NProjectResourceView::OnMemDrag(KMessageDrag* msg)
{
kn_int ix,iy,lx,ly;
ix = msg->m_pos_x;
iy = msg->m_pos_y;
KView_PTR p = msg->m_p_drag_view;
m_edit_pm->GetScreenXY(lx,ly);
if (ix > lx && ix < lx + m_edit_pm->GetRect().width()&&
iy > ly && iy < ly + m_edit_pm->GetRect().height())
{
ix -= lx;
iy -= ly;
p_pmedit_active->SetShow(true);
}
else
{
p_pmedit_active->SetShow(false);
}
}
void NProjectResourceView::OnMemDragEnd(KMessageDrag* msg)
{
kn_int ix,iy,lx,ly;
ix = msg->m_pos_x;
iy = msg->m_pos_y;
KView_PTR p = msg->m_p_drag_view;
m_edit_pm->GetScreenXY(lx,ly);
if (ix > lx && ix < lx + m_edit_pm->GetRect().width()&&
iy > ly && iy < ly + m_edit_pm->GetRect().height())
{
ix -= lx;
iy -= ly;
m_edit_pm->SetText((VIEW_PTR(NStaffView)(p))->GetName());
p_pmedit_active->SetShow(FALSE);
for (int i = 0; i < m_view_satff_grid->getViewCount() ; i++)
{
NStaffView_PTR pview = VIEW_PTR(NStaffView)(m_view_satff_grid->getViewByIndex(i));
pview->setLeader(pview->getMsg() == (VIEW_PTR(NStaffView)(p))->getMsg());
}
m_view_satff_grid->InvalidateView();
}
InvalidateView();
}
void NProjectResourceView::onDragDirect( KMessageDrag* msg )
{
if (msg)
{
if (msg->m_drag_type == TASK_GROUP_DRAG_UP)
{
OnMemDragEnd(msg);
}
if (msg->m_drag_type == TASK_GROUP_DRAG)
{
OnMemDrag(msg);
}
}
}
| 35.682889 | 180 | 0.729916 | Avens666 |
96d8ce4da6ebb11efd89c45f109d9875ff70a6dc | 2,346 | hpp | C++ | system/core/Sha1/Sha1.hpp | fabsgc/gestnotes | 61e8ff8a42e9f5954a57489f7103937f5ce36863 | [
"MIT"
] | 11 | 2015-04-27T21:43:25.000Z | 2020-04-09T18:42:42.000Z | system/core/Sha1/Sha1.hpp | fabsgc/gestnotes | 61e8ff8a42e9f5954a57489f7103937f5ce36863 | [
"MIT"
] | 3 | 2015-06-15T19:48:12.000Z | 2015-07-04T22:13:40.000Z | system/core/Sha1/Sha1.hpp | fabsgc/gestnotes | 61e8ff8a42e9f5954a57489f7103937f5ce36863 | [
"MIT"
] | 3 | 2016-06-20T01:31:19.000Z | 2021-06-06T09:42:01.000Z | /*
Copyright (c) 2011, Micael Hildenborg
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 Micael Hildenborg 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 Micael Hildenborg ''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 Micael Hildenborg BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef SHA1_DEFINED
#define SHA1_DEFINED
namespace sha1
{
/**
@param src points to any kind of data to be hashed.
@param bytelength the number of bytes to hash from the src pointer.
@param hash should point to a buffer of at least 20 bytes of size for storing the sha1 result in.
*/
void calc(const void* src, const int bytelength, unsigned char* hash);
/**
@param hash is 20 bytes of sha1 hash. This is the same data that is the result from the calc function.
@param hexstring should point to a buffer of at least 41 bytes of size for storing the hexadecimal representation of the hash. A zero will be written at position 40, so the buffer will be a valid zero ended string.
*/
void toHexString(const unsigned char* hash, char* hexstring);
} // namespace sha1
#endif // SHA1_DEFINED
| 46.92 | 219 | 0.758312 | fabsgc |